From abffce64240797791f32568096bee517e0e520bd Mon Sep 17 00:00:00 2001 From: Alex Newman Date: Wed, 28 Jan 2026 16:18:15 -0500 Subject: [PATCH] fix: use cwd instead of CLAUDE_CONFIG_DIR for observer session isolation (#845) The previous approach (PR #837) set CLAUDE_CONFIG_DIR to isolate observer sessions from `claude --resume`. However, this broke authentication because Claude Code stores credentials in the config directory. This fix uses the SDK's `cwd` option instead: - Observer sessions run with cwd=~/.claude-mem/observer-sessions/ - Project name = path.basename(cwd) = "observer-sessions" - Sessions won't appear when running `claude --resume` from actual projects - Authentication works because ~/.claude/ config is preserved Changes: - ProcessRegistry.ts: Remove CLAUDE_CONFIG_DIR override from spawn - SDKAgent.ts: Add cwd option to query() pointing to observer dir - paths.ts: Rename OBSERVER_CONFIG_DIR to OBSERVER_SESSIONS_DIR Fixes regression from #837 Co-authored-by: Claude Opus 4.5 --- plugin/scripts/context-generator.cjs | 12 +++---- plugin/scripts/worker-service.cjs | 48 +++++++++++++------------- src/services/worker/ProcessRegistry.ts | 17 ++------- src/services/worker/SDKAgent.ts | 7 +++- src/shared/paths.ts | 6 ++-- 5 files changed, 42 insertions(+), 48 deletions(-) diff --git a/plugin/scripts/context-generator.cjs b/plugin/scripts/context-generator.cjs index b1cf63e6..d712a0a6 100644 --- a/plugin/scripts/context-generator.cjs +++ b/plugin/scripts/context-generator.cjs @@ -6,7 +6,7 @@ ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?u=` `,"utf8")}catch(E){process.stderr.write(`[LOGGER] Failed to write to log file: ${E} `)}else process.stderr.write(g+` `)}debug(e,t,s,n){this.log(0,e,t,s,n)}info(e,t,s,n){this.log(1,e,t,s,n)}warn(e,t,s,n){this.log(2,e,t,s,n)}error(e,t,s,n){this.log(3,e,t,s,n)}dataIn(e,t,s,n){this.info(e,`\u2192 ${t}`,s,n)}dataOut(e,t,s,n){this.info(e,`\u2190 ${t}`,s,n)}success(e,t,s,n){this.info(e,`\u2713 ${t}`,s,n)}failure(e,t,s,n){this.error(e,`\u2717 ${t}`,s,n)}timing(e,t,s,n){this.info(e,`\u23F1 ${t}`,n,{duration:`${s}ms`})}happyPathError(e,t,s,n,o=""){let c=((new Error().stack||"").split(` -`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),u=c?`${c[1].split("/").pop()}:${c[2]}`:"unknown",l={...s,location:u};return this.warn(e,`[HAPPY-PATH] ${t}`,l,n),o}},m=new H;var Ct={};function bt(){return typeof __dirname<"u"?__dirname:(0,h.dirname)((0,ce.fileURLToPath)(Ct.url))}var Ot=bt(),R=y.get("CLAUDE_MEM_DATA_DIR"),W=process.env.CLAUDE_CONFIG_DIR||(0,h.join)((0,de.homedir)(),".claude"),Ht=(0,h.join)(R,"archives"),Wt=(0,h.join)(R,"logs"),Yt=(0,h.join)(R,"trash"),Vt=(0,h.join)(R,"backups"),qt=(0,h.join)(R,"modes"),Kt=(0,h.join)(R,"settings.json"),me=(0,h.join)(R,"claude-mem.db"),Jt=(0,h.join)(R,"vector-db"),zt=(0,h.join)(R,"observer-config"),Qt=(0,h.join)(W,"settings.json"),Zt=(0,h.join)(W,"commands"),es=(0,h.join)(W,"CLAUDE.md");function ue(r){(0,pe.mkdirSync)(r,{recursive:!0})}function le(){return(0,h.join)(Ot,"..")}var U=class{db;constructor(e=me){e!==":memory:"&&ue(R),this.db=new _e.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()}initializeSchema(){this.db.run(` +`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),u=c?`${c[1].split("/").pop()}:${c[2]}`:"unknown",l={...s,location:u};return this.warn(e,`[HAPPY-PATH] ${t}`,l,n),o}},m=new H;var Ct={};function bt(){return typeof __dirname<"u"?__dirname:(0,h.dirname)((0,ce.fileURLToPath)(Ct.url))}var Ot=bt(),R=y.get("CLAUDE_MEM_DATA_DIR"),W=process.env.CLAUDE_CONFIG_DIR||(0,h.join)((0,de.homedir)(),".claude"),Ht=(0,h.join)(R,"archives"),Wt=(0,h.join)(R,"logs"),Yt=(0,h.join)(R,"trash"),Vt=(0,h.join)(R,"backups"),qt=(0,h.join)(R,"modes"),Kt=(0,h.join)(R,"settings.json"),me=(0,h.join)(R,"claude-mem.db"),Jt=(0,h.join)(R,"vector-db"),zt=(0,h.join)(R,"observer-sessions"),Qt=(0,h.join)(W,"settings.json"),Zt=(0,h.join)(W,"commands"),es=(0,h.join)(W,"CLAUDE.md");function ue(r){(0,pe.mkdirSync)(r,{recursive:!0})}function le(){return(0,h.join)(Ot,"..")}var U=class{db;constructor(e=me){e!==":memory:"&&ue(R),this.db=new _e.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()}initializeSchema(){this.db.run(` CREATE TABLE IF NOT EXISTS schema_versions ( id INTEGER PRIMARY KEY, version INTEGER UNIQUE NOT NULL, @@ -491,7 +491,7 @@ ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?u=` content_session_id, prompt_number, prompt_text, created_at, created_at_epoch ) VALUES (?, ?, ?, ?, ?) - `).run(e.content_session_id,e.prompt_number,e.prompt_text,e.created_at,e.created_at_epoch).lastInsertRowid}}};var Ee=v(require("path"),1);function ge(r){if(!r||r.trim()==="")return m.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:r}),"unknown-project";let e=Ee.default.basename(r);if(e===""){if(process.platform==="win32"){let s=r.match(/^([A-Z]):\\/i);if(s){let o=`drive-${s[1].toUpperCase()}`;return m.info("PROJECT_NAME","Drive root detected",{cwd:r,projectName:o}),o}}return m.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:r}),"unknown-project"}return e}var Te=v(require("path"),1),fe=require("os");var L=require("fs"),w=require("path");var O=class r{static instance=null;activeMode=null;modesDir;constructor(){let e=le(),t=[(0,w.join)(e,"modes"),(0,w.join)(e,"..","plugin","modes")],s=t.find(n=>(0,L.existsSync)(n));this.modesDir=s||t[0]}static getInstance(){return r.instance||(r.instance=new r),r.instance}parseInheritance(e){let t=e.split("--");if(t.length===1)return{hasParent:!1,parentId:"",overrideId:""};if(t.length>2)throw new Error(`Invalid mode inheritance: ${e}. Only one level of inheritance supported (parent--override)`);return{hasParent:!0,parentId:t[0],overrideId:e}}isPlainObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}deepMerge(e,t){let s={...e};for(let n in t){let o=t[n],i=e[n];this.isPlainObject(o)&&this.isPlainObject(i)?s[n]=this.deepMerge(i,o):s[n]=o}return s}loadModeFile(e){let t=(0,w.join)(this.modesDir,`${e}.json`);if(!(0,L.existsSync)(t))throw new Error(`Mode file not found: ${t}`);let s=(0,L.readFileSync)(t,"utf-8");return JSON.parse(s)}loadMode(e){let t=this.parseInheritance(e);if(!t.hasParent)try{let d=this.loadModeFile(e);return this.activeMode=d,m.debug("SYSTEM",`Loaded mode: ${d.name} (${e})`,void 0,{types:d.observation_types.map(c=>c.id),concepts:d.observation_concepts.map(c=>c.id)}),d}catch{if(m.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:s,overrideId:n}=t,o;try{o=this.loadMode(s)}catch{m.warn("SYSTEM",`Parent mode '${s}' not found for ${e}, falling back to 'code'`),o=this.loadMode("code")}let i;try{i=this.loadModeFile(n),m.debug("SYSTEM",`Loaded override file: ${n} for parent ${s}`)}catch{return m.warn("SYSTEM",`Override file '${n}' not found, using parent mode '${s}' only`),this.activeMode=o,o}if(!i)return m.warn("SYSTEM",`Invalid override file: ${n}, using parent mode '${s}' only`),this.activeMode=o,o;let a=this.deepMerge(o,i);return this.activeMode=a,m.debug("SYSTEM",`Loaded mode with inheritance: ${a.name} (${e} = ${s} + ${n})`,void 0,{parent:s,override:n,types:a.observation_types.map(d=>d.id),concepts:a.observation_concepts.map(d=>d.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(s=>s.id===e)?.emoji||"\u{1F4DD}"}getWorkEmoji(e){return this.getObservationTypes().find(s=>s.id===e)?.work_emoji||"\u{1F4DD}"}validateType(e){return this.getObservationTypes().some(t=>t.id===e)}getTypeLabel(e){return this.getObservationTypes().find(s=>s.id===e)?.label||e}};function Y(){let r=Te.default.join((0,fe.homedir)(),".claude-mem","settings.json"),e=y.loadFromFile(r),t=e.CLAUDE_MEM_MODE,s=t==="code"||t.startsWith("code--"),n,o;if(s)n=new Set(e.CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES.split(",").map(i=>i.trim()).filter(Boolean)),o=new Set(e.CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS.split(",").map(i=>i.trim()).filter(Boolean));else{let i=O.getInstance().getActiveMode();n=new Set(i.observation_types.map(a=>a.id)),o=new Set(i.observation_concepts.map(a=>a.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:o,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 p={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"},Se=4,V=1;function q(r){let e=(r.title?.length||0)+(r.subtitle?.length||0)+(r.narrative?.length||0)+JSON.stringify(r.facts||[]).length;return Math.ceil(e/Se)}function K(r){let e=r.length,t=r.reduce((i,a)=>i+q(a),0),s=r.reduce((i,a)=>i+(a.discovery_tokens||0),0),n=s-t,o=s>0?Math.round(n/s*100):0;return{totalObservations:e,totalReadTokens:t,totalDiscoveryTokens:s,savings:n,savingsPercent:o}}function Rt(r){return O.getInstance().getWorkEmoji(r)}function A(r,e){let t=q(r),s=r.discovery_tokens||0,n=Rt(r.type),o=s>0?`${n} ${s.toLocaleString()}`:"-";return{readTokens:t,discoveryTokens:s,discoveryDisplay:o,workEmoji:n}}function F(r){return r.showReadTokens||r.showWorkTokens||r.showSavingsAmount||r.showSavingsPercent}var he=v(require("path"),1),be=require("os"),P=require("fs");function J(r,e,t){let s=Array.from(t.observationTypes),n=s.map(()=>"?").join(","),o=Array.from(t.observationConcepts),i=o.map(()=>"?").join(",");return r.db.prepare(` + `).run(e.content_session_id,e.prompt_number,e.prompt_text,e.created_at,e.created_at_epoch).lastInsertRowid}}};var Ee=v(require("path"),1);function ge(r){if(!r||r.trim()==="")return m.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:r}),"unknown-project";let e=Ee.default.basename(r);if(e===""){if(process.platform==="win32"){let s=r.match(/^([A-Z]):\\/i);if(s){let o=`drive-${s[1].toUpperCase()}`;return m.info("PROJECT_NAME","Drive root detected",{cwd:r,projectName:o}),o}}return m.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:r}),"unknown-project"}return e}var Te=v(require("path"),1),fe=require("os");var L=require("fs"),w=require("path");var O=class r{static instance=null;activeMode=null;modesDir;constructor(){let e=le(),t=[(0,w.join)(e,"modes"),(0,w.join)(e,"..","plugin","modes")],s=t.find(n=>(0,L.existsSync)(n));this.modesDir=s||t[0]}static getInstance(){return r.instance||(r.instance=new r),r.instance}parseInheritance(e){let t=e.split("--");if(t.length===1)return{hasParent:!1,parentId:"",overrideId:""};if(t.length>2)throw new Error(`Invalid mode inheritance: ${e}. Only one level of inheritance supported (parent--override)`);return{hasParent:!0,parentId:t[0],overrideId:e}}isPlainObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}deepMerge(e,t){let s={...e};for(let n in t){let o=t[n],i=e[n];this.isPlainObject(o)&&this.isPlainObject(i)?s[n]=this.deepMerge(i,o):s[n]=o}return s}loadModeFile(e){let t=(0,w.join)(this.modesDir,`${e}.json`);if(!(0,L.existsSync)(t))throw new Error(`Mode file not found: ${t}`);let s=(0,L.readFileSync)(t,"utf-8");return JSON.parse(s)}loadMode(e){let t=this.parseInheritance(e);if(!t.hasParent)try{let d=this.loadModeFile(e);return this.activeMode=d,m.debug("SYSTEM",`Loaded mode: ${d.name} (${e})`,void 0,{types:d.observation_types.map(c=>c.id),concepts:d.observation_concepts.map(c=>c.id)}),d}catch{if(m.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:s,overrideId:n}=t,o;try{o=this.loadMode(s)}catch{m.warn("SYSTEM",`Parent mode '${s}' not found for ${e}, falling back to 'code'`),o=this.loadMode("code")}let i;try{i=this.loadModeFile(n),m.debug("SYSTEM",`Loaded override file: ${n} for parent ${s}`)}catch{return m.warn("SYSTEM",`Override file '${n}' not found, using parent mode '${s}' only`),this.activeMode=o,o}if(!i)return m.warn("SYSTEM",`Invalid override file: ${n}, using parent mode '${s}' only`),this.activeMode=o,o;let a=this.deepMerge(o,i);return this.activeMode=a,m.debug("SYSTEM",`Loaded mode with inheritance: ${a.name} (${e} = ${s} + ${n})`,void 0,{parent:s,override:n,types:a.observation_types.map(d=>d.id),concepts:a.observation_concepts.map(d=>d.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(s=>s.id===e)?.emoji||"\u{1F4DD}"}getWorkEmoji(e){return this.getObservationTypes().find(s=>s.id===e)?.work_emoji||"\u{1F4DD}"}validateType(e){return this.getObservationTypes().some(t=>t.id===e)}getTypeLabel(e){return this.getObservationTypes().find(s=>s.id===e)?.label||e}};function Y(){let r=Te.default.join((0,fe.homedir)(),".claude-mem","settings.json"),e=y.loadFromFile(r),t=e.CLAUDE_MEM_MODE,s=t==="code"||t.startsWith("code--"),n,o;if(s)n=new Set(e.CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES.split(",").map(i=>i.trim()).filter(Boolean)),o=new Set(e.CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS.split(",").map(i=>i.trim()).filter(Boolean));else{let i=O.getInstance().getActiveMode();n=new Set(i.observation_types.map(a=>a.id)),o=new Set(i.observation_concepts.map(a=>a.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:o,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 p={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"},Se=4,V=1;function q(r){let e=(r.title?.length||0)+(r.subtitle?.length||0)+(r.narrative?.length||0)+JSON.stringify(r.facts||[]).length;return Math.ceil(e/Se)}function K(r){let e=r.length,t=r.reduce((i,a)=>i+q(a),0),s=r.reduce((i,a)=>i+(a.discovery_tokens||0),0),n=s-t,o=s>0?Math.round(n/s*100):0;return{totalObservations:e,totalReadTokens:t,totalDiscoveryTokens:s,savings:n,savingsPercent:o}}function Rt(r){return O.getInstance().getWorkEmoji(r)}function A(r,e){let t=q(r),s=r.discovery_tokens||0,n=Rt(r.type),o=s>0?`${n} ${s.toLocaleString()}`:"-";return{readTokens:t,discoveryTokens:s,discoveryDisplay:o,workEmoji:n}}function P(r){return r.showReadTokens||r.showWorkTokens||r.showSavingsAmount||r.showSavingsPercent}var he=v(require("path"),1),be=require("os"),F=require("fs");function J(r,e,t){let s=Array.from(t.observationTypes),n=s.map(()=>"?").join(","),o=Array.from(t.observationConcepts),i=o.map(()=>"?").join(",");return r.db.prepare(` SELECT id, memory_session_id, type, title, subtitle, narrative, facts, concepts, files_read, files_modified, discovery_tokens, @@ -531,14 +531,14 @@ ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?u=` WHERE project IN (${s}) ORDER BY created_at_epoch DESC LIMIT ? - `).all(...e,t.sessionCount+V)}function Nt(r){return r.replace(/\//g,"-")}function It(r){try{if(!(0,P.existsSync)(r))return{userMessage:"",assistantMessage:""};let e=(0,P.readFileSync)(r,"utf-8").trim();if(!e)return{userMessage:"",assistantMessage:""};let t=e.split(` -`).filter(n=>n.trim()),s="";for(let n=t.length-1;n>=0;n--)try{let o=t[n];if(!o.includes('"type":"assistant"'))continue;let i=JSON.parse(o);if(i.type==="assistant"&&i.message?.content&&Array.isArray(i.message.content)){let a="";for(let d of i.message.content)d.type==="text"&&(a+=d.text);if(a=a.replace(/[\s\S]*?<\/system-reminder>/g,"").trim(),a){s=a;break}}}catch(o){m.debug("PARSER","Skipping malformed transcript line",{lineIndex:n},o);continue}return{userMessage:"",assistantMessage:s}}catch(e){return m.failure("WORKER","Failed to extract prior messages from transcript",{transcriptPath:r},e),{userMessage:"",assistantMessage:""}}}function Q(r,e,t,s){if(!e.showLastMessage||r.length===0)return{userMessage:"",assistantMessage:""};let n=r.find(d=>d.memory_session_id!==t);if(!n)return{userMessage:"",assistantMessage:""};let o=n.memory_session_id,i=Nt(s),a=he.default.join((0,be.homedir)(),".claude","projects",i,`${o}.jsonl`);return It(a)}function Re(r,e){let t=e[0]?.id;return r.map((s,n)=>{let o=n===0?null:e[n+1];return{...s,displayEpoch:o?o.created_at_epoch:s.created_at_epoch,displayTime:o?o.created_at:s.created_at,shouldShowLink:s.id!==t}})}function Z(r,e){let t=[...r.map(s=>({type:"observation",data:s})),...e.map(s=>({type:"summary",data:s}))];return t.sort((s,n)=>{let o=s.type==="observation"?s.data.created_at_epoch:s.data.displayEpoch,i=n.type==="observation"?n.data.created_at_epoch:n.data.displayEpoch;return o-i}),t}function Ne(r,e){return new Set(r.slice(0,e).map(t=>t.id))}function Ie(){let r=new Date,e=r.toLocaleDateString("en-CA"),t=r.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}).toLowerCase().replace(" ",""),s=r.toLocaleTimeString("en-US",{timeZoneName:"short"}).split(" ").pop();return`${e} ${t} ${s}`}function ye(r){return[`# [${r}] recent context, ${Ie()}`,""]}function Ae(){return[`**Legend:** session-request | ${O.getInstance().getActiveMode().observation_types.map(t=>`${t.emoji} ${t.id}`).join(" | ")}`,""]}function ve(){return["**Column Key**:","- **Read**: Tokens to read this observation (cost to learn it now)","- **Work**: Tokens spent on work that produced this record ( research, building, deciding)",""]}function Me(){return["**Context Index:** This semantic index (titles, types, files, tokens) is usually sufficient to understand past work.","","When you need implementation details, rationale, or debugging context:","- Use MCP tools (search, get_observations) to fetch full observations on-demand","- Critical types ( bugfix, decision) often need detailed fetching","- Trust this index over re-reading code for past decisions and learnings",""]}function Le(r,e){let t=[];if(t.push("**Context Economics**:"),t.push(`- Loading: ${r.totalObservations} observations (${r.totalReadTokens.toLocaleString()} tokens to read)`),t.push(`- Work investment: ${r.totalDiscoveryTokens.toLocaleString()} tokens spent on research, building, and decisions`),r.totalDiscoveryTokens>0&&(e.showSavingsAmount||e.showSavingsPercent)){let s="- Your savings: ";e.showSavingsAmount&&e.showSavingsPercent?s+=`${r.savings.toLocaleString()} tokens (${r.savingsPercent}% reduction from reuse)`:e.showSavingsAmount?s+=`${r.savings.toLocaleString()} tokens`:s+=`${r.savingsPercent}% reduction from reuse`,t.push(s)}return t.push(""),t}function De(r){return[`### ${r}`,""]}function xe(r){return[`**${r}**`,"| ID | Time | T | Title | Read | Work |","|----|------|---|-------|------|------|"]}function ke(r,e,t){let s=r.title||"Untitled",n=O.getInstance().getTypeIcon(r.type),{readTokens:o,discoveryDisplay:i}=A(r,t),a=t.showReadTokens?`~${o}`:"",d=t.showWorkTokens?i:"";return`| #${r.id} | ${e||'"'} | ${n} | ${s} | ${a} | ${d} |`}function $e(r,e,t,s){let n=[],o=r.title||"Untitled",i=O.getInstance().getTypeIcon(r.type),{readTokens:a,discoveryDisplay:d}=A(r,s);n.push(`**#${r.id}** ${e||'"'} ${i} **${o}**`),t&&(n.push(""),n.push(t),n.push(""));let c=[];return s.showReadTokens&&c.push(`Read: ~${a}`),s.showWorkTokens&&c.push(`Work: ${d}`),c.length>0&&n.push(c.join(", ")),n.push(""),n}function Ue(r,e){let t=`${r.request||"Session started"} (${e})`;return[`**#S${r.id}** ${t}`,""]}function D(r,e){return e?[`**${r}**: ${e}`,""]:[]}function we(r){return r.assistantMessage?["","---","","**Previously**","",`A: ${r.assistantMessage}`,""]:[]}function Fe(r,e){return["",`Access ${Math.round(r/1e3)}k tokens of past research & decisions for just ${e.toLocaleString()}t. Use MCP search tools to access memories by ID.`]}function Pe(r){return`# [${r}] recent context, ${Ie()} + `).all(...e,t.sessionCount+V)}function Nt(r){return r.replace(/\//g,"-")}function It(r){try{if(!(0,F.existsSync)(r))return{userMessage:"",assistantMessage:""};let e=(0,F.readFileSync)(r,"utf-8").trim();if(!e)return{userMessage:"",assistantMessage:""};let t=e.split(` +`).filter(n=>n.trim()),s="";for(let n=t.length-1;n>=0;n--)try{let o=t[n];if(!o.includes('"type":"assistant"'))continue;let i=JSON.parse(o);if(i.type==="assistant"&&i.message?.content&&Array.isArray(i.message.content)){let a="";for(let d of i.message.content)d.type==="text"&&(a+=d.text);if(a=a.replace(/[\s\S]*?<\/system-reminder>/g,"").trim(),a){s=a;break}}}catch(o){m.debug("PARSER","Skipping malformed transcript line",{lineIndex:n},o);continue}return{userMessage:"",assistantMessage:s}}catch(e){return m.failure("WORKER","Failed to extract prior messages from transcript",{transcriptPath:r},e),{userMessage:"",assistantMessage:""}}}function Q(r,e,t,s){if(!e.showLastMessage||r.length===0)return{userMessage:"",assistantMessage:""};let n=r.find(d=>d.memory_session_id!==t);if(!n)return{userMessage:"",assistantMessage:""};let o=n.memory_session_id,i=Nt(s),a=he.default.join((0,be.homedir)(),".claude","projects",i,`${o}.jsonl`);return It(a)}function Re(r,e){let t=e[0]?.id;return r.map((s,n)=>{let o=n===0?null:e[n+1];return{...s,displayEpoch:o?o.created_at_epoch:s.created_at_epoch,displayTime:o?o.created_at:s.created_at,shouldShowLink:s.id!==t}})}function Z(r,e){let t=[...r.map(s=>({type:"observation",data:s})),...e.map(s=>({type:"summary",data:s}))];return t.sort((s,n)=>{let o=s.type==="observation"?s.data.created_at_epoch:s.data.displayEpoch,i=n.type==="observation"?n.data.created_at_epoch:n.data.displayEpoch;return o-i}),t}function Ne(r,e){return new Set(r.slice(0,e).map(t=>t.id))}function Ie(){let r=new Date,e=r.toLocaleDateString("en-CA"),t=r.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}).toLowerCase().replace(" ",""),s=r.toLocaleTimeString("en-US",{timeZoneName:"short"}).split(" ").pop();return`${e} ${t} ${s}`}function ye(r){return[`# [${r}] recent context, ${Ie()}`,""]}function Ae(){return[`**Legend:** session-request | ${O.getInstance().getActiveMode().observation_types.map(t=>`${t.emoji} ${t.id}`).join(" | ")}`,""]}function ve(){return["**Column Key**:","- **Read**: Tokens to read this observation (cost to learn it now)","- **Work**: Tokens spent on work that produced this record ( research, building, deciding)",""]}function Me(){return["**Context Index:** This semantic index (titles, types, files, tokens) is usually sufficient to understand past work.","","When you need implementation details, rationale, or debugging context:","- Use MCP tools (search, get_observations) to fetch full observations on-demand","- Critical types ( bugfix, decision) often need detailed fetching","- Trust this index over re-reading code for past decisions and learnings",""]}function Le(r,e){let t=[];if(t.push("**Context Economics**:"),t.push(`- Loading: ${r.totalObservations} observations (${r.totalReadTokens.toLocaleString()} tokens to read)`),t.push(`- Work investment: ${r.totalDiscoveryTokens.toLocaleString()} tokens spent on research, building, and decisions`),r.totalDiscoveryTokens>0&&(e.showSavingsAmount||e.showSavingsPercent)){let s="- Your savings: ";e.showSavingsAmount&&e.showSavingsPercent?s+=`${r.savings.toLocaleString()} tokens (${r.savingsPercent}% reduction from reuse)`:e.showSavingsAmount?s+=`${r.savings.toLocaleString()} tokens`:s+=`${r.savingsPercent}% reduction from reuse`,t.push(s)}return t.push(""),t}function De(r){return[`### ${r}`,""]}function xe(r){return[`**${r}**`,"| ID | Time | T | Title | Read | Work |","|----|------|---|-------|------|------|"]}function ke(r,e,t){let s=r.title||"Untitled",n=O.getInstance().getTypeIcon(r.type),{readTokens:o,discoveryDisplay:i}=A(r,t),a=t.showReadTokens?`~${o}`:"",d=t.showWorkTokens?i:"";return`| #${r.id} | ${e||'"'} | ${n} | ${s} | ${a} | ${d} |`}function $e(r,e,t,s){let n=[],o=r.title||"Untitled",i=O.getInstance().getTypeIcon(r.type),{readTokens:a,discoveryDisplay:d}=A(r,s);n.push(`**#${r.id}** ${e||'"'} ${i} **${o}**`),t&&(n.push(""),n.push(t),n.push(""));let c=[];return s.showReadTokens&&c.push(`Read: ~${a}`),s.showWorkTokens&&c.push(`Work: ${d}`),c.length>0&&n.push(c.join(", ")),n.push(""),n}function Ue(r,e){let t=`${r.request||"Session started"} (${e})`;return[`**#S${r.id}** ${t}`,""]}function D(r,e){return e?[`**${r}**: ${e}`,""]:[]}function we(r){return r.assistantMessage?["","---","","**Previously**","",`A: ${r.assistantMessage}`,""]:[]}function Pe(r,e){return["",`Access ${Math.round(r/1e3)}k tokens of past research & decisions for just ${e.toLocaleString()}t. Use MCP search tools to access memories by ID.`]}function Fe(r){return`# [${r}] recent context, ${Ie()} No previous sessions found for this project yet.`}function je(){let r=new Date,e=r.toLocaleDateString("en-CA"),t=r.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}).toLowerCase().replace(" ",""),s=r.toLocaleTimeString("en-US",{timeZoneName:"short"}).split(" ").pop();return`${e} ${t} ${s}`}function Xe(r){return["",`${p.bright}${p.cyan}[${r}] recent context, ${je()}${p.reset}`,`${p.gray}${"\u2500".repeat(60)}${p.reset}`,""]}function Be(){let e=O.getInstance().getActiveMode().observation_types.map(t=>`${t.emoji} ${t.id}`).join(" | ");return[`${p.dim}Legend: session-request | ${e}${p.reset}`,""]}function Ge(){return[`${p.bright}Column Key${p.reset}`,`${p.dim} Read: Tokens to read this observation (cost to learn it now)${p.reset}`,`${p.dim} Work: Tokens spent on work that produced this record ( research, building, deciding)${p.reset}`,""]}function He(){return[`${p.dim}Context Index: This semantic index (titles, types, files, tokens) is usually sufficient to understand past work.${p.reset}`,"",`${p.dim}When you need implementation details, rationale, or debugging context:${p.reset}`,`${p.dim} - Use MCP tools (search, get_observations) to fetch full observations on-demand${p.reset}`,`${p.dim} - Critical types ( bugfix, decision) often need detailed fetching${p.reset}`,`${p.dim} - Trust this index over re-reading code for past decisions and learnings${p.reset}`,""]}function We(r,e){let t=[];if(t.push(`${p.bright}${p.cyan}Context Economics${p.reset}`),t.push(`${p.dim} Loading: ${r.totalObservations} observations (${r.totalReadTokens.toLocaleString()} tokens to read)${p.reset}`),t.push(`${p.dim} Work investment: ${r.totalDiscoveryTokens.toLocaleString()} tokens spent on research, building, and decisions${p.reset}`),r.totalDiscoveryTokens>0&&(e.showSavingsAmount||e.showSavingsPercent)){let s=" Your savings: ";e.showSavingsAmount&&e.showSavingsPercent?s+=`${r.savings.toLocaleString()} tokens (${r.savingsPercent}% reduction from reuse)`:e.showSavingsAmount?s+=`${r.savings.toLocaleString()} tokens`:s+=`${r.savingsPercent}% reduction from reuse`,t.push(`${p.green}${s}${p.reset}`)}return t.push(""),t}function Ye(r){return[`${p.bright}${p.cyan}${r}${p.reset}`,""]}function Ve(r){return[`${p.dim}${r}${p.reset}`]}function qe(r,e,t,s){let n=r.title||"Untitled",o=O.getInstance().getTypeIcon(r.type),{readTokens:i,discoveryTokens:a,workEmoji:d}=A(r,s),c=t?`${p.dim}${e}${p.reset}`:" ".repeat(e.length),u=s.showReadTokens&&i>0?`${p.dim}(~${i}t)${p.reset}`:"",l=s.showWorkTokens&&a>0?`${p.dim}(${d} ${a.toLocaleString()}t)${p.reset}`:"";return` ${p.dim}#${r.id}${p.reset} ${c} ${o} ${n} ${u} ${l}`}function Ke(r,e,t,s,n){let o=[],i=r.title||"Untitled",a=O.getInstance().getTypeIcon(r.type),{readTokens:d,discoveryTokens:c,workEmoji:u}=A(r,n),l=t?`${p.dim}${e}${p.reset}`:" ".repeat(e.length),g=n.showReadTokens&&d>0?`${p.dim}(~${d}t)${p.reset}`:"",E=n.showWorkTokens&&c>0?`${p.dim}(${u} ${c.toLocaleString()}t)${p.reset}`:"";return o.push(` ${p.dim}#${r.id}${p.reset} ${l} ${a} ${p.bright}${i}${p.reset}`),s&&o.push(` ${p.dim}${s}${p.reset}`),(g||E)&&o.push(` ${g} ${E}`),o.push(""),o}function Je(r,e){let t=`${r.request||"Session started"} (${e})`;return[`${p.yellow}#S${r.id}${p.reset} ${t}`,""]}function x(r,e,t){return e?[`${t}${r}:${p.reset} ${e}`,""]:[]}function ze(r){return r.assistantMessage?["","---","",`${p.bright}${p.magenta}Previously${p.reset}`,"",`${p.dim}A: ${r.assistantMessage}${p.reset}`,""]:[]}function Qe(r,e){let t=Math.round(r/1e3);return["",`${p.dim}Access ${t}k tokens of past research & decisions for just ${e.toLocaleString()}t. Use MCP search tools to access memories by ID.${p.reset}`]}function Ze(r){return` ${p.bright}${p.cyan}[${r}] recent context, ${je()}${p.reset} ${p.gray}${"\u2500".repeat(60)}${p.reset} ${p.dim}No previous sessions found for this project yet.${p.reset} -`}function et(r,e,t,s){let n=[];return s?n.push(...Xe(r)):n.push(...ye(r)),s?n.push(...Be()):n.push(...Ae()),s?n.push(...Ge()):n.push(...ve()),s?n.push(...He()):n.push(...Me()),F(t)&&(s?n.push(...We(e,t)):n.push(...Le(e,t))),n}var ee=v(require("path"),1);function B(r){if(!r)return[];try{let e=JSON.parse(r);return Array.isArray(e)?e:[]}catch(e){return m.debug("PARSER","Failed to parse JSON array, using empty fallback",{preview:r?.substring(0,50)},e),[]}}function st(r){return new Date(r).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function rt(r){return new Date(r).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function nt(r){return new Date(r).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}function tt(r,e){return ee.default.isAbsolute(r)?ee.default.relative(e,r):r}function ot(r,e,t){let s=B(r);if(s.length>0)return tt(s[0],e);if(t){let n=B(t);if(n.length>0)return tt(n[0],e)}return"General"}function yt(r){let e=new Map;for(let s of r){let n=s.type==="observation"?s.data.created_at:s.data.displayTime,o=nt(n);e.has(o)||e.set(o,[]),e.get(o).push(s)}let t=Array.from(e.entries()).sort((s,n)=>{let o=new Date(s[0]).getTime(),i=new Date(n[0]).getTime();return o-i});return new Map(t)}function At(r,e){return e.fullObservationField==="narrative"?r.narrative:r.facts?B(r.facts).join(` -`):null}function vt(r,e,t,s,n,o){let i=[];o?i.push(...Ye(r)):i.push(...De(r));let a=null,d="",c=!1;for(let u of e)if(u.type==="summary"){c&&(i.push(""),c=!1,a=null,d="");let l=u.data,g=st(l.displayTime);o?i.push(...Je(l,g)):i.push(...Ue(l,g))}else{let l=u.data,g=ot(l.files_modified,n,l.files_read),E=rt(l.created_at),T=E!==d,b=T?E:"";d=E;let _=t.has(l.id);if(g!==a&&(c&&i.push(""),o?i.push(...Ve(g)):i.push(...xe(g)),a=g,c=!0),_){let S=At(l,s);o?i.push(...Ke(l,E,T,S,s)):(c&&!o&&(i.push(""),c=!1),i.push(...$e(l,b,S,s)),a=null)}else o?i.push(qe(l,E,T,s)):i.push(ke(l,b,s))}return c&&i.push(""),i}function it(r,e,t,s,n){let o=[],i=yt(r);for(let[a,d]of i)o.push(...vt(a,d,e,t,s,n));return o}function at(r,e,t){return!(!r.showLastSummary||!e||!!!(e.investigated||e.learned||e.completed||e.next_steps)||t&&e.created_at_epoch<=t.created_at_epoch)}function dt(r,e){let t=[];return e?(t.push(...x("Investigated",r.investigated,p.blue)),t.push(...x("Learned",r.learned,p.yellow)),t.push(...x("Completed",r.completed,p.green)),t.push(...x("Next Steps",r.next_steps,p.magenta))):(t.push(...D("Investigated",r.investigated)),t.push(...D("Learned",r.learned)),t.push(...D("Completed",r.completed)),t.push(...D("Next Steps",r.next_steps))),t}function pt(r,e){return e?ze(r):we(r)}function ct(r,e,t){return!F(e)||r.totalDiscoveryTokens<=0||r.savings<=0?[]:t?Qe(r.totalDiscoveryTokens,r.totalReadTokens):Fe(r.totalDiscoveryTokens,r.totalReadTokens)}var Mt=mt.default.join((0,ut.homedir)(),".claude","plugins","marketplaces","thedotmack","plugin",".install-version");function Lt(){try{return new U}catch(r){if(r.code==="ERR_DLOPEN_FAILED"){try{(0,lt.unlinkSync)(Mt)}catch(e){m.debug("SYSTEM","Marker file cleanup failed (may not exist)",{},e)}return m.error("SYSTEM","Native module rebuild needed - restart Claude Code to auto-fix"),null}throw r}}function Dt(r,e){return e?Ze(r):Pe(r)}function xt(r,e,t,s,n,o,i){let a=[],d=K(e);a.push(...et(r,d,s,i));let c=t.slice(0,s.sessionCount),u=Re(c,t),l=Z(e,u),g=Ne(e,s.fullObservationCount);a.push(...it(l,g,s,n,i));let E=t[0],T=e[0];at(s,E,T)&&a.push(...dt(E,i));let b=Q(e,s,o,n);return a.push(...pt(b,i)),a.push(...ct(d,s,i)),a.join(` +`}function et(r,e,t,s){let n=[];return s?n.push(...Xe(r)):n.push(...ye(r)),s?n.push(...Be()):n.push(...Ae()),s?n.push(...Ge()):n.push(...ve()),s?n.push(...He()):n.push(...Me()),P(t)&&(s?n.push(...We(e,t)):n.push(...Le(e,t))),n}var ee=v(require("path"),1);function B(r){if(!r)return[];try{let e=JSON.parse(r);return Array.isArray(e)?e:[]}catch(e){return m.debug("PARSER","Failed to parse JSON array, using empty fallback",{preview:r?.substring(0,50)},e),[]}}function st(r){return new Date(r).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function rt(r){return new Date(r).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function nt(r){return new Date(r).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}function tt(r,e){return ee.default.isAbsolute(r)?ee.default.relative(e,r):r}function ot(r,e,t){let s=B(r);if(s.length>0)return tt(s[0],e);if(t){let n=B(t);if(n.length>0)return tt(n[0],e)}return"General"}function yt(r){let e=new Map;for(let s of r){let n=s.type==="observation"?s.data.created_at:s.data.displayTime,o=nt(n);e.has(o)||e.set(o,[]),e.get(o).push(s)}let t=Array.from(e.entries()).sort((s,n)=>{let o=new Date(s[0]).getTime(),i=new Date(n[0]).getTime();return o-i});return new Map(t)}function At(r,e){return e.fullObservationField==="narrative"?r.narrative:r.facts?B(r.facts).join(` +`):null}function vt(r,e,t,s,n,o){let i=[];o?i.push(...Ye(r)):i.push(...De(r));let a=null,d="",c=!1;for(let u of e)if(u.type==="summary"){c&&(i.push(""),c=!1,a=null,d="");let l=u.data,g=st(l.displayTime);o?i.push(...Je(l,g)):i.push(...Ue(l,g))}else{let l=u.data,g=ot(l.files_modified,n,l.files_read),E=rt(l.created_at),T=E!==d,b=T?E:"";d=E;let _=t.has(l.id);if(g!==a&&(c&&i.push(""),o?i.push(...Ve(g)):i.push(...xe(g)),a=g,c=!0),_){let S=At(l,s);o?i.push(...Ke(l,E,T,S,s)):(c&&!o&&(i.push(""),c=!1),i.push(...$e(l,b,S,s)),a=null)}else o?i.push(qe(l,E,T,s)):i.push(ke(l,b,s))}return c&&i.push(""),i}function it(r,e,t,s,n){let o=[],i=yt(r);for(let[a,d]of i)o.push(...vt(a,d,e,t,s,n));return o}function at(r,e,t){return!(!r.showLastSummary||!e||!!!(e.investigated||e.learned||e.completed||e.next_steps)||t&&e.created_at_epoch<=t.created_at_epoch)}function dt(r,e){let t=[];return e?(t.push(...x("Investigated",r.investigated,p.blue)),t.push(...x("Learned",r.learned,p.yellow)),t.push(...x("Completed",r.completed,p.green)),t.push(...x("Next Steps",r.next_steps,p.magenta))):(t.push(...D("Investigated",r.investigated)),t.push(...D("Learned",r.learned)),t.push(...D("Completed",r.completed)),t.push(...D("Next Steps",r.next_steps))),t}function pt(r,e){return e?ze(r):we(r)}function ct(r,e,t){return!P(e)||r.totalDiscoveryTokens<=0||r.savings<=0?[]:t?Qe(r.totalDiscoveryTokens,r.totalReadTokens):Pe(r.totalDiscoveryTokens,r.totalReadTokens)}var Mt=mt.default.join((0,ut.homedir)(),".claude","plugins","marketplaces","thedotmack","plugin",".install-version");function Lt(){try{return new U}catch(r){if(r.code==="ERR_DLOPEN_FAILED"){try{(0,lt.unlinkSync)(Mt)}catch(e){m.debug("SYSTEM","Marker file cleanup failed (may not exist)",{},e)}return m.error("SYSTEM","Native module rebuild needed - restart Claude Code to auto-fix"),null}throw r}}function Dt(r,e){return e?Ze(r):Fe(r)}function xt(r,e,t,s,n,o,i){let a=[],d=K(e);a.push(...et(r,d,s,i));let c=t.slice(0,s.sessionCount),u=Re(c,t),l=Z(e,u),g=Ne(e,s.fullObservationCount);a.push(...it(l,g,s,n,i));let E=t[0],T=e[0];at(s,E,T)&&a.push(...dt(E,i));let b=Q(e,s,o,n);return a.push(...pt(b,i)),a.push(...ct(d,s,i)),a.join(` `).trimEnd()}async function te(r,e=!1){let t=Y(),s=r?.cwd??process.cwd(),n=ge(s),o=r?.projects||[n],i=Lt();if(!i)return"";try{let a=o.length>1?Oe(i,o,t):J(i,n,t),d=o.length>1?Ce(i,o,t):z(i,n,t);return a.length===0&&d.length===0?Dt(n,e):xt(n,a,d,t,s,r?.session_id,e)}finally{i.close()}}0&&(module.exports={generateContext}); diff --git a/plugin/scripts/worker-service.cjs b/plugin/scripts/worker-service.cjs index e23e6c00..08ce8247 100755 --- a/plugin/scripts/worker-service.cjs +++ b/plugin/scripts/worker-service.cjs @@ -14,7 +14,7 @@ ${a.stack}`:` ${a.message}`:this.getLevel()===0&&typeof a=="object"?l=` `,"utf8")}catch(f){process.stderr.write(`[LOGGER] Failed to write to log file: ${f} `)}else process.stderr.write(p+` `)}debug(e,r,n,i){this.log(0,e,r,n,i)}info(e,r,n,i){this.log(1,e,r,n,i)}warn(e,r,n,i){this.log(2,e,r,n,i)}error(e,r,n,i){this.log(3,e,r,n,i)}dataIn(e,r,n,i){this.info(e,`\u2192 ${r}`,n,i)}dataOut(e,r,n,i){this.info(e,`\u2190 ${r}`,n,i)}success(e,r,n,i){this.info(e,`\u2713 ${r}`,n,i)}failure(e,r,n,i){this.error(e,`\u2717 ${r}`,n,i)}timing(e,r,n,i){this.info(e,`\u23F1 ${r}`,i,{duration:`${n}ms`})}happyPathError(e,r,n,i,a=""){let u=((new Error().stack||"").split(` -`)[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),a}},E=new JS});function ZR(t){return process.platform==="win32"?Math.round(t*ma.WINDOWS_MULTIPLIER):t}var ma,bl,xl=Le(()=>{"use strict";ma={DEFAULT:3e5,HEALTH_CHECK:3e4,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:300,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5},bl={SUCCESS:0,FAILURE:1,BLOCKING_ERROR:2}});var HR,BR,VR=Le(()=>{"use strict";HR="bugfix,feature,refactor,discovery,decision,change",BR="how-it-works,why-it-exists,what-changed,problem-solution,gotcha,pattern,trade-off"});var WR={};pn(WR,{SettingsDefaultsManager:()=>Qe});var pi,sm,GR,Qe,un=Le(()=>{"use strict";pi=require("fs"),sm=require("path"),GR=require("os");VR();Qe=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_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,sm.join)((0,GR.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:"true",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"true",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"true",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:HR,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:BR,CLAUDE_MEM_CONTEXT_FULL_COUNT:"5",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"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static getBool(e){return this.get(e)==="true"}static loadFromFile(e){try{if(!(0,pi.existsSync)(e)){let o=this.getAllDefaults();try{let s=(0,sm.dirname)(e);(0,pi.existsSync)(s)||(0,pi.mkdirSync)(s,{recursive:!0}),(0,pi.writeFileSync)(e,JSON.stringify(o,null,2),"utf-8"),console.log("[SETTINGS] Created settings file with defaults:",e)}catch(s){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,s)}return o}let r=(0,pi.readFileSync)(e,"utf-8"),n=JSON.parse(r),i=n;if(n.env&&typeof n.env=="object"){i=n.env;try{(0,pi.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 a={...this.DEFAULTS};for(let o of Object.keys(this.DEFAULTS))i[o]!==void 0&&(a[o]=i[o]);return a}catch(r){return console.warn("[SETTINGS] Failed to load settings, using defaults:",e,r),this.getAllDefaults()}}}});function KR(t={}){let{port:e,includeSkillFallback:r=!1,customPrefix:n,actualError:i}=t,a=n||"Worker service connection failed.",o=e?` (port ${e})`:"",s=`${a}${o} +`)[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),a}},E=new JS});function ZR(t){return process.platform==="win32"?Math.round(t*ma.WINDOWS_MULTIPLIER):t}var ma,bl,xl=Le(()=>{"use strict";ma={DEFAULT:3e5,HEALTH_CHECK:3e4,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:300,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5},bl={SUCCESS:0,FAILURE:1,BLOCKING_ERROR:2}});var HR,BR,VR=Le(()=>{"use strict";HR="bugfix,feature,refactor,discovery,decision,change",BR="how-it-works,why-it-exists,what-changed,problem-solution,gotcha,pattern,trade-off"});var WR={};pn(WR,{SettingsDefaultsManager:()=>Qe});var pi,sm,GR,Qe,cn=Le(()=>{"use strict";pi=require("fs"),sm=require("path"),GR=require("os");VR();Qe=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_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,sm.join)((0,GR.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:"true",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"true",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"true",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:HR,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:BR,CLAUDE_MEM_CONTEXT_FULL_COUNT:"5",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"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static getBool(e){return this.get(e)==="true"}static loadFromFile(e){try{if(!(0,pi.existsSync)(e)){let o=this.getAllDefaults();try{let s=(0,sm.dirname)(e);(0,pi.existsSync)(s)||(0,pi.mkdirSync)(s,{recursive:!0}),(0,pi.writeFileSync)(e,JSON.stringify(o,null,2),"utf-8"),console.log("[SETTINGS] Created settings file with defaults:",e)}catch(s){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,s)}return o}let r=(0,pi.readFileSync)(e,"utf-8"),n=JSON.parse(r),i=n;if(n.env&&typeof n.env=="object"){i=n.env;try{(0,pi.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 a={...this.DEFAULTS};for(let o of Object.keys(this.DEFAULTS))i[o]!==void 0&&(a[o]=i[o]);return a}catch(r){return console.warn("[SETTINGS] Failed to load settings, using defaults:",e,r),this.getAllDefaults()}}}});function KR(t={}){let{port:e,includeSkillFallback:r=!1,customPrefix:n,actualError:i}=t,a=n||"Worker service connection failed.",o=e?` (port ${e})`:"",s=`${a}${o} `;return s+=`To restart the worker: `,s+=`1. Exit Claude Code completely @@ -23,7 +23,7 @@ ${a.stack}`:` ${a.message}`:this.getLevel()===0&&typeof a=="object"?l=` If that doesn't work, try: /troubleshoot`),i&&(s=`Worker Error: ${i} -${s}`),s}var JR=Le(()=>{"use strict"});function It(){if(Sl!==null)return Sl;let t=$l.default.join(Qe.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),e=Qe.loadFromFile(t);return Sl=parseInt(e.CLAUDE_MEM_WORKER_PORT,10),Sl}function cm(){if(wl!==null)return wl;let t=$l.default.join(Qe.get("CLAUDE_MEM_DATA_DIR"),"settings.json");return wl=Qe.loadFromFile(t).CLAUDE_MEM_WORKER_HOST,wl}function QR(){Sl=null,wl=null}async function TG(){let t=It();return(await fetch(`http://127.0.0.1:${t}/api/readiness`)).ok}function IG(){let t=$l.default.join(kG,"package.json");return JSON.parse((0,YR.readFileSync)(t,"utf-8")).version}async function PG(){let t=It(),e=await fetch(`http://127.0.0.1:${t}/api/version`);if(!e.ok)throw new Error(`Failed to get worker version: ${e.status}`);return(await e.json()).version}async function OG(){let t=IG(),e=await PG();t!==e&&E.debug("SYSTEM","Version check",{pluginVersion:t,workerVersion:e,note:"Mismatch will be auto-restarted by worker-service start command"})}async function Sn(){for(let r=0;r<75;r++){try{if(await TG()){await OG();return}}catch(n){E.debug("SYSTEM","Worker health check failed, will retry",{attempt:r+1,maxRetries:75,error:n instanceof Error?n.message:String(n)})}await new Promise(n=>setTimeout(n,200))}throw new Error(KR({port:It(),customPrefix:"Worker did not become ready within 15 seconds."}))}var $l,XR,YR,kG,wEe,Sl,wl,Hr=Le(()=>{"use strict";$l=ut(require("path"),1),XR=require("os"),YR=require("fs");we();xl();un();JR();kG=$l.default.join((0,XR.homedir)(),".claude","plugins","marketplaces","thedotmack"),wEe=ZR(ma.HEALTH_CHECK),Sl=null,wl=null});var fi=j((NEe,vC)=>{var jG=require("path").relative;vC.exports=UG;var AG=process.cwd();function hC(t,e){for(var r=t.split(/[ ,]+/),n=String(e).toLowerCase(),i=0;i{"use strict"});function It(){if(Sl!==null)return Sl;let t=$l.default.join(Qe.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),e=Qe.loadFromFile(t);return Sl=parseInt(e.CLAUDE_MEM_WORKER_PORT,10),Sl}function cm(){if(wl!==null)return wl;let t=$l.default.join(Qe.get("CLAUDE_MEM_DATA_DIR"),"settings.json");return wl=Qe.loadFromFile(t).CLAUDE_MEM_WORKER_HOST,wl}function QR(){Sl=null,wl=null}async function TG(){let t=It();return(await fetch(`http://127.0.0.1:${t}/api/readiness`)).ok}function IG(){let t=$l.default.join(kG,"package.json");return JSON.parse((0,YR.readFileSync)(t,"utf-8")).version}async function PG(){let t=It(),e=await fetch(`http://127.0.0.1:${t}/api/version`);if(!e.ok)throw new Error(`Failed to get worker version: ${e.status}`);return(await e.json()).version}async function OG(){let t=IG(),e=await PG();t!==e&&E.debug("SYSTEM","Version check",{pluginVersion:t,workerVersion:e,note:"Mismatch will be auto-restarted by worker-service start command"})}async function Sn(){for(let r=0;r<75;r++){try{if(await TG()){await OG();return}}catch(n){E.debug("SYSTEM","Worker health check failed, will retry",{attempt:r+1,maxRetries:75,error:n instanceof Error?n.message:String(n)})}await new Promise(n=>setTimeout(n,200))}throw new Error(KR({port:It(),customPrefix:"Worker did not become ready within 15 seconds."}))}var $l,XR,YR,kG,wEe,Sl,wl,Hr=Le(()=>{"use strict";$l=ut(require("path"),1),XR=require("os"),YR=require("fs");we();xl();cn();JR();kG=$l.default.join((0,XR.homedir)(),".claude","plugins","marketplaces","thedotmack"),wEe=ZR(ma.HEALTH_CHECK),Sl=null,wl=null});var fi=j((NEe,vC)=>{var jG=require("path").relative;vC.exports=UG;var AG=process.cwd();function hC(t,e){for(var r=t.split(/[ ,]+/),n=String(e).toLowerCase(),i=0;i0}function qG(t){if(process.noDeprecation)return!0;var e=process.env.NO_DEPRECATION||"";return hC(e,t)}function FG(t){if(process.traceDeprecation)return!0;var e=process.env.TRACE_DEPRECATION||"";return hC(e,t)}function fm(t,e){var r=LG(process,"deprecation");if(!(!r&&this._ignored)){var n,i,a,o,s=0,c=!1,u=mm(),l=this._file;for(e?(o=e,a=Ts(u[1]),a.name=o.name,l=a[0]):(s=2,o=Ts(u[s]),a=o);s",r=t.getLineNumber(),n=t.getColumnNumber();t.isEval()&&(e=t.getEvalOrigin()+", "+e);var i=[e,r,n];return i.callSite=t,i.name=t.getFunctionName(),i}function mC(t){var e=t.callSite,r=t.name;r||(r="");var n=e.getThis(),i=n&&e.getTypeName();return i==="Object"&&(i=void 0),i==="Function"&&(i=n.name||i),i&&e.getMethodName()?i+"."+r:r}function ZG(t,e,r){var n=new Date().toUTCString(),i=n+" "+this._namespace+" deprecated "+t;if(this._traced){for(var a=0;a `}function fte(t,e){return e?e instanceof Error?jw(t,e,{expose:!1}):jw(t,e):jw(t)}function mte(t){try{return decodeURIComponent(t)}catch{return-1}}function hte(t){return typeof t.getHeaderNames!="function"?Object.keys(t._headers||{}):t.getHeaderNames()}function ez(t,e){var r=typeof t.listenerCount!="function"?t.listeners(e).length:t.listenerCount(e);return r>0}function gte(t){return typeof t.headersSent!="boolean"?!!t._header:t.headersSent}function Dw(t,e){for(var r=[].concat(t||[]),n=0;n{"use strict";tz.exports=_te;function _te(t){if(!t)throw new TypeError("argument req is required");var e=xte(t.headers["x-forwarded-for"]||""),r=bte(t),n=[r].concat(e);return n}function bte(t){return t.socket?t.socket.remoteAddress:t.connection.remoteAddress}function xte(t){for(var e=t.length,r=[],n=t.length,i=t.length-1;i>=0;i--)switch(t.charCodeAt(i)){case 32:n===e&&(n=e=i);break;case 44:n!==e&&r.push(t.substring(n,e)),n=e=i;break;default:n=i;break}return n!==e&&r.push(t.substring(n,e)),r}});var iz=j((nz,id)=>{(function(){var t,e,r,n,i,a,o,s,c;e={},s=this,typeof id<"u"&&id!==null&&id.exports?id.exports=e:s.ipaddr=e,o=function(u,l,d,p){var f,g;if(u.length!==l.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");for(f=0;p>0;){if(g=d-p,g<0&&(g=0),u[f]>>g!==l[f]>>g)return!1;p-=d,f+=1}return!0},e.subnetMatch=function(u,l,d){var p,f,g,_,h;d==null&&(d="unicast");for(g in l)for(_=l[g],_[0]&&!(_[0]instanceof Array)&&(_=[_]),p=0,f=_.length;p=0;d=p+=-1)if(f=this.octets[d],f in h){if(_=h[f],g&&_!==0)return null;_!==8&&(g=!0),l+=_}else return null;return 32-l},u})(),r="(0?\\d+|0x[a-f0-9]+)",n={fourOctet:new RegExp("^"+r+"\\."+r+"\\."+r+"\\."+r+"$","i"),longValue:new RegExp("^"+r+"$","i")},e.IPv4.parser=function(u){var l,d,p,f,g;if(d=function(_){return _[0]==="0"&&_[1]!=="x"?parseInt(_,8):parseInt(_)},l=u.match(n.fourOctet))return(function(){var _,h,m,y;for(m=l.slice(1,6),y=[],_=0,h=m.length;_4294967295||g<0)throw new Error("ipaddr: address outside defined range");return(function(){var _,h;for(h=[],f=_=0;_<=24;f=_+=8)h.push(g>>f&255);return h})().reverse()}else return null},e.IPv6=(function(){function u(l,d){var p,f,g,_,h,m;if(l.length===16)for(this.parts=[],p=f=0;f<=14;p=f+=2)this.parts.push(l[p]<<8|l[p+1]);else if(l.length===8)this.parts=l;else throw new Error("ipaddr: ipv6 part count should be 8 or 16");for(m=this.parts,g=0,_=m.length;g<_;g++)if(h=m[g],!(0<=h&&h<=65535))throw new Error("ipaddr: ipv6 part should fit in 16 bits");d&&(this.zoneId=d)}return u.prototype.kind=function(){return"ipv6"},u.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},u.prototype.toRFC5952String=function(){var l,d,p,f,g;for(f=/((^|:)(0(:|$)){2,})/g,g=this.toNormalizedString(),l=0,d=-1;p=f.exec(g);)p[0].length>d&&(l=p.index,d=p[0].length);return d<0?g:g.substring(0,l)+"::"+g.substring(l+d)},u.prototype.toByteArray=function(){var l,d,p,f,g;for(l=[],g=this.parts,d=0,p=g.length;d>8),l.push(f&255);return l},u.prototype.toNormalizedString=function(){var l,d,p;return l=(function(){var f,g,_,h;for(_=this.parts,h=[],f=0,g=_.length;f>8,l&255,d>>8,d&255])},u.prototype.prefixLengthFromSubnetMask=function(){var l,d,p,f,g,_,h;for(h={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},l=0,g=!1,d=p=7;p>=0;d=p+=-1)if(f=this.parts[d],f in h){if(_=h[f],g&&_!==0)return null;_!==16&&(g=!0),l+=_}else return null;return 128-l},u})(),i="(?:[0-9a-f]+::?)+",c="%[0-9a-z]{1,}",a={zoneIndex:new RegExp(c,"i"),native:new RegExp("^(::)?("+i+")?([0-9a-f]+)?(::)?("+c+")?$","i"),transitional:new RegExp("^((?:"+i+")|(?:::)(?:"+i+")?)"+(r+"\\."+r+"\\."+r+"\\."+r)+("("+c+")?$"),"i")},t=function(u,l){var d,p,f,g,_,h;if(u.indexOf("::")!==u.lastIndexOf("::"))return null;for(h=(u.match(a.zoneIndex)||[])[0],h&&(h=h.substring(1),u=u.replace(/%.+$/,"")),d=0,p=-1;(p=u.indexOf(":",p+1))>=0;)d++;if(u.substr(0,2)==="::"&&d--,u.substr(-2,2)==="::"&&d--,d>l)return null;for(_=l-d,g=":";_--;)g+="0:";return u=u.replace("::",g),u[0]===":"&&(u=u.slice(1)),u[u.length-1]===":"&&(u=u.slice(0,-1)),l=(function(){var m,y,v,b;for(v=u.split(":"),b=[],m=0,y=v.length;m=0&&l<=32))return p=[this.parse(d[1]),l],Object.defineProperty(p,"toString",{value:function(){return this.join("/")}}),p;throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},e.IPv4.subnetMaskFromPrefixLength=function(u){var l,d,p;if(u=parseInt(u),u<0||u>32)throw new Error("ipaddr: invalid IPv4 prefix length");for(p=[0,0,0,0],d=0,l=Math.floor(u/8);d=0&&l<=128))return p=[this.parse(d[1]),l],Object.defineProperty(p,"toString",{value:function(){return this.join("/")}}),p;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},e.isValid=function(u){return e.IPv6.isValid(u)||e.IPv4.isValid(u)},e.parse=function(u){if(e.IPv6.isValid(u))return e.IPv6.parse(u);if(e.IPv4.isValid(u))return e.IPv4.parse(u);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},e.parseCIDR=function(u){var l;try{return e.IPv6.parseCIDR(u)}catch(d){l=d;try{return e.IPv4.parseCIDR(u)}catch(p){throw l=p,new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},e.fromByteArray=function(u){var l;if(l=u.length,l===4)return new e.IPv4(u);if(l===16)return new e.IPv6(u);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},e.process=function(u){var l;return l=this.parse(u),l.kind()==="ipv6"&&l.isIPv4MappedAddress()?l.toIPv4Address():l}}).call(nz)});var Lw=j((ZTe,mh)=>{"use strict";mh.exports=Ite;mh.exports.all=sz;mh.exports.compile=cz;var Ste=rz(),oz=iz(),wte=/^[0-9]+$/,ph=oz.isValid,fh=oz.parse,az={linklocal:["169.254.0.0/16","fe80::/10"],loopback:["127.0.0.1/8","::1/128"],uniquelocal:["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16","fc00::/7"]};function sz(t,e){var r=Ste(t);if(!e)return r;typeof e!="function"&&(e=cz(e));for(var n=0;ni)throw new TypeError("invalid range on address: "+t);return[n,a]}function Tte(t){var e=fh(t),r=e.kind();return r==="ipv4"?e.prefixLengthFromSubnetMask():null}function Ite(t,e){if(!t)throw new TypeError("req argument is required");if(!e)throw new TypeError("trust argument is required");var r=sz(t,e),n=r[r.length-1];return n}function Pte(){return!1}function Ote(t){return function(r){if(!ph(r))return!1;for(var n=fh(r),i,a=n.kind(),o=0;o{"use strict";var uz=oh().Buffer,Cte=Ow(),lz=kl(),dz=fi()("express"),Nte=ed(),jte=dh().mime,Ate=Rw(),Mte=Lw(),Dte=Xm(),zte=require("querystring");Ar.etag=pz({weak:!1});Ar.wetag=pz({weak:!0});Ar.isAbsolute=function(t){if(t[0]==="/"||t[1]===":"&&(t[2]==="\\"||t[2]==="/")||t.substring(0,2)==="\\\\")return!0};Ar.flatten=dz.function(Nte,"utils.flatten: use array-flatten npm module instead");Ar.normalizeType=function(t){return~t.indexOf("/")?Ute(t):{value:jte.lookup(t),params:{}}};Ar.normalizeTypes=function(t){for(var e=[],r=0;r{"use strict";var Fte=KM(),Zte=kw(),Fw=th(),Hte=xD(),Bte=Tw(),hh=wn()("express:application"),Vte=TD(),Gte=require("http"),Wte=wa().compileETag,Kte=wa().compileQueryParser,Jte=wa().compileTrust,Xte=fi()("express"),Yte=ed(),qw=td(),Qte=require("path").resolve,Ys=Tl(),ere=Object.prototype.hasOwnProperty,Hw=Array.prototype.slice,tr=fz=mz.exports={},Zw="@@symbol:trust_proxy_default";tr.init=function(){this.cache={},this.engines={},this.settings={},this.defaultConfiguration()};tr.defaultConfiguration=function(){var e=process.env.NODE_ENV||"development";this.enable("x-powered-by"),this.set("etag","weak"),this.set("env",e),this.set("query parser","extended"),this.set("subdomain offset",2),this.set("trust proxy",!1),Object.defineProperty(this.settings,Zw,{configurable:!0,value:!0}),hh("booting in %s mode",e),this.on("mount",function(n){this.settings[Zw]===!0&&typeof n.settings["trust proxy fn"]=="function"&&(delete this.settings["trust proxy"],delete this.settings["trust proxy fn"]),Ys(this.request,n.request),Ys(this.response,n.response),Ys(this.engines,n.engines),Ys(this.settings,n.settings)}),this.locals=Object.create(null),this.mountpath="/",this.locals.settings=this.settings,this.set("view",Vte),this.set("views",Qte("views")),this.set("jsonp callback name","callback"),e==="production"&&this.enable("view cache"),Object.defineProperty(this,"router",{get:function(){throw new Error(`'app.router' is deprecated! -Please see the 3.x to 4.x migration guide for details on how to update your app.`)}})};tr.lazyrouter=function(){this._router||(this._router=new Zte({caseSensitive:this.enabled("case sensitive routing"),strict:this.enabled("strict routing")}),this._router.use(Bte(this.get("query parser fn"))),this._router.use(Hte.init(this)))};tr.handle=function(e,r,n){var i=this._router,a=n||Fte(e,r,{env:this.get("env"),onerror:tre.bind(this)});if(!i){hh("no routes defined on app"),a();return}i.handle(e,r,a)};tr.use=function(e){var r=0,n="/";if(typeof e!="function"){for(var i=e;Array.isArray(i)&&i.length!==0;)i=i[0];typeof i!="function"&&(r=1,n=e)}var a=Yte(Hw.call(arguments,r));if(a.length===0)throw new TypeError("app.use() requires a middleware function");this.lazyrouter();var o=this._router;return a.forEach(function(s){if(!s||!s.handle||!s.set)return o.use(n,s);hh(".use app under %s",n),s.mountpath=n,s.parent=this,o.use(n,function(u,l,d){var p=u.app;s.handle(u,l,function(f){Ys(u,p.request),Ys(l,p.response),d(f)})}),s.emit("mount",this)},this),this};tr.route=function(e){return this.lazyrouter(),this._router.route(e)};tr.engine=function(e,r){if(typeof r!="function")throw new Error("callback function required");var n=e[0]!=="."?"."+e:e;return this.engines[n]=r,this};tr.param=function(e,r){if(this.lazyrouter(),Array.isArray(e)){for(var n=0;n1?'directories "'+u.root.slice(0,-1).join('", "')+'" or "'+u.root[u.root.length-1]+'"':'directory "'+u.root+'"',p=new Error('Failed to lookup view "'+e+'" in views '+d);return p.view=u,a(p)}c.cache&&(i[e]=u)}rre(u,c,a)};tr.listen=function(){var e=Gte.createServer(this);return e.listen.apply(e,arguments)};function tre(t){this.get("env")!=="test"&&console.error(t.stack||t.toString())}function rre(t,e,r){try{t.render(e,r)}catch(n){r(n)}}});var _z=j((BTe,Bw)=>{"use strict";Bw.exports=yz;Bw.exports.preferredCharsets=yz;var nre=/^\s*([^\s;]+)\s*(?:;(.*))?$/;function ire(t){for(var e=t.split(","),r=0,n=0;r0}});var $z=j((VTe,Vw)=>{"use strict";Vw.exports=wz;Vw.exports.preferredEncodings=wz;var ure=/^\s*([^\s;]+)\s*(?:;(.*))?$/;function lre(t){for(var e=t.split(","),r=!1,n=1,i=0,a=0;i0}});var Pz=j((GTe,Gw)=>{"use strict";Gw.exports=Iz;Gw.exports.preferredLanguages=Iz;var mre=/^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/;function hre(t){for(var e=t.split(","),r=0,n=0;r0}});var Az=j((WTe,Ww)=>{"use strict";Ww.exports=Nz;Ww.exports.preferredMediaTypes=Nz;var _re=/^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/;function bre(t){for(var e=Ere(t),r=0,n=0;r0)if(a.every(function(o){return e.params[o]=="*"||(e.params[o]||"").toLowerCase()==(n.params[o]||"").toLowerCase()}))i|=1;else return null;return{i:r,o:e.i,q:e.q,s:i}}function Nz(t,e){var r=bre(t===void 0?"*/*":t||"");if(!e)return r.filter(Rz).sort(Oz).map(wre);var n=e.map(function(a,o){return xre(a,r,o)});return n.filter(Rz).sort(Oz).map(function(a){return e[n.indexOf(a)]})}function Oz(t,e){return e.q-t.q||e.s-t.s||t.o-e.o||t.i-e.i||0}function wre(t){return t.type+"/"+t.subtype}function Rz(t){return t.q>0}function jz(t){for(var e=0,r=0;(r=t.indexOf('"',r))!==-1;)e++,r++;return e}function $re(t){var e=t.indexOf("="),r,n;return e===-1?r=t:(r=t.substr(0,e),n=t.substr(e+1)),[r,n]}function Ere(t){for(var e=t.split(","),r=1,n=0;r{"use strict";var Tre=_z(),Ire=$z(),Pre=Pz(),Ore=Az();Kw.exports=wt;Kw.exports.Negotiator=wt;function wt(t){if(!(this instanceof wt))return new wt(t);this.request=t}wt.prototype.charset=function(e){var r=this.charsets(e);return r&&r[0]};wt.prototype.charsets=function(e){return Tre(this.request.headers["accept-charset"],e)};wt.prototype.encoding=function(e){var r=this.encodings(e);return r&&r[0]};wt.prototype.encodings=function(e){return Ire(this.request.headers["accept-encoding"],e)};wt.prototype.language=function(e){var r=this.languages(e);return r&&r[0]};wt.prototype.languages=function(e){return Pre(this.request.headers["accept-language"],e)};wt.prototype.mediaType=function(e){var r=this.mediaTypes(e);return r&&r[0]};wt.prototype.mediaTypes=function(e){return Ore(this.request.headers.accept,e)};wt.prototype.preferredCharset=wt.prototype.charset;wt.prototype.preferredCharsets=wt.prototype.charsets;wt.prototype.preferredEncoding=wt.prototype.encoding;wt.prototype.preferredEncodings=wt.prototype.encodings;wt.prototype.preferredLanguage=wt.prototype.language;wt.prototype.preferredLanguages=wt.prototype.languages;wt.prototype.preferredMediaType=wt.prototype.mediaType;wt.prototype.preferredMediaTypes=wt.prototype.mediaTypes});var zz=j((JTe,Dz)=>{"use strict";var Rre=Mz(),Cre=Z0();Dz.exports=ln;function ln(t){if(!(this instanceof ln))return new ln(t);this.headers=t.headers,this.negotiator=new Rre(t)}ln.prototype.type=ln.prototype.types=function(t){var e=t;if(e&&!Array.isArray(e)){e=new Array(arguments.length);for(var r=0;r{"use strict";var gh=zz(),ad=fi()("express"),Are=require("net").isIP,Mre=Ds(),Dre=require("http"),zre=Cw(),Ure=Nw(),Lre=Hs(),Uz=Lw(),Pt=Object.create(Dre.IncomingMessage.prototype);Lz.exports=Pt;Pt.get=Pt.header=function(e){if(!e)throw new TypeError("name argument is required to req.get");if(typeof e!="string")throw new TypeError("name must be a string to req.get");var r=e.toLowerCase();switch(r){case"referer":case"referrer":return this.headers.referrer||this.headers.referer;default:return this.headers[r]}};Pt.accepts=function(){var t=gh(this);return t.types.apply(t,arguments)};Pt.acceptsEncodings=function(){var t=gh(this);return t.encodings.apply(t,arguments)};Pt.acceptsEncoding=ad.function(Pt.acceptsEncodings,"req.acceptsEncoding: Use acceptsEncodings instead");Pt.acceptsCharsets=function(){var t=gh(this);return t.charsets.apply(t,arguments)};Pt.acceptsCharset=ad.function(Pt.acceptsCharsets,"req.acceptsCharset: Use acceptsCharsets instead");Pt.acceptsLanguages=function(){var t=gh(this);return t.languages.apply(t,arguments)};Pt.acceptsLanguage=ad.function(Pt.acceptsLanguages,"req.acceptsLanguage: Use acceptsLanguages instead");Pt.range=function(e,r){var n=this.get("Range");if(n)return Ure(e,n,r)};Pt.param=function(e,r){var n=this.params||{},i=this.body||{},a=this.query||{},o=arguments.length===1?"name":"name, default";return ad("req.param("+o+"): Use req.params, req.body, or req.query instead"),n[e]!=null&&n.hasOwnProperty(e)?n[e]:i[e]!=null?i[e]:a[e]!=null?a[e]:r};Pt.is=function(e){var r=e;if(!Array.isArray(e)){r=new Array(arguments.length);for(var n=0;n=200&&r<300||r===304?zre(this.headers,{etag:e.get("ETag"),"last-modified":e.get("Last-Modified")}):!1});Wn(Pt,"stale",function(){return!this.fresh});Wn(Pt,"xhr",function(){var e=this.get("X-Requested-With")||"";return e.toLowerCase()==="xmlhttprequest"});function Wn(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get:r})}});var Hz=j(vh=>{var Zz=require("crypto");vh.sign=function(t,e){if(typeof t!="string")throw new TypeError("Cookie value must be provided as a string.");if(e==null)throw new TypeError("Secret key must be provided.");return t+"."+Zz.createHmac("sha256",e).update(t).digest("base64").replace(/\=+$/,"")};vh.unsign=function(t,e){if(typeof t!="string")throw new TypeError("Signed cookie string must be provided.");if(e==null)throw new TypeError("Secret key must be provided.");var r=t.slice(0,t.lastIndexOf(".")),n=vh.sign(r,e);return Fz(n)==Fz(t)?r:!1};function Fz(t){return Zz.createHash("sha1").update(t).digest("hex")}});var Gz=j(Jw=>{"use strict";Jw.parse=Gre;Jw.serialize=Wre;var qre=Object.prototype.toString,Fre=Object.prototype.hasOwnProperty,Zre=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Hre=/^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/,Bre=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Vre=/^[\u0020-\u003A\u003D-\u007E]*$/;function Gre(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");var r={},n=t.length;if(n<2)return r;var i=e&&e.decode||Kre,a=0,o=0,s=0;do{if(o=t.indexOf("=",a),o===-1)break;if(s=t.indexOf(";",a),s===-1)s=n;else if(o>s){a=t.lastIndexOf(";",o-1)+1;continue}var c=Bz(t,a,o),u=Vz(t,o,c),l=t.slice(c,u);if(!Fre.call(r,l)){var d=Bz(t,o+1,s),p=Vz(t,s,d);t.charCodeAt(d)===34&&t.charCodeAt(p-1)===34&&(d++,p--);var f=t.slice(d,p);r[l]=Xre(f,i)}a=s+1}while(ar;){var n=t.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return r}function Wre(t,e,r){var n=r&&r.encode||encodeURIComponent;if(typeof n!="function")throw new TypeError("option encode is invalid");if(!Zre.test(t))throw new TypeError("argument name is invalid");var i=n(e);if(!Hre.test(i))throw new TypeError("argument val is invalid");var a=t+"="+i;if(!r)return a;if(r.maxAge!=null){var o=Math.floor(r.maxAge);if(!isFinite(o))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+o}if(r.domain){if(!Bre.test(r.domain))throw new TypeError("option domain is invalid");a+="; Domain="+r.domain}if(r.path){if(!Vre.test(r.path))throw new TypeError("option path is invalid");a+="; Path="+r.path}if(r.expires){var s=r.expires;if(!Jre(s)||isNaN(s.valueOf()))throw new TypeError("option expires is invalid");a+="; Expires="+s.toUTCString()}if(r.httpOnly&&(a+="; HttpOnly"),r.secure&&(a+="; Secure"),r.partitioned&&(a+="; Partitioned"),r.priority){var c=typeof r.priority=="string"?r.priority.toLowerCase():r.priority;switch(c){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}}if(r.sameSite){var u=typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite;switch(u){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return a}function Kre(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}function Jre(t){return qre.call(t)==="[object Date]"}function Xre(t,e){try{return e(t)}catch{return t}}});var Yw=j((e1e,Xw)=>{"use strict";Xw.exports=Qre;Xw.exports.append=Kz;var Yre=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function Kz(t,e){if(typeof t!="string")throw new TypeError("header argument is required");if(!e)throw new TypeError("field argument is required");for(var r=Array.isArray(e)?e:Wz(String(e)),n=0;n{"use strict";var od=oh().Buffer,Jz=Ow(),ene=oo(),Gr=fi()("express"),tne=Yl(),rne=Ql(),nne=require("http"),ine=wa().isAbsolute,ane=Dl(),Xz=require("path"),yh=Il(),Yz=td(),one=Hz().sign,sne=wa().normalizeType,cne=wa().normalizeTypes,une=wa().setCharset,lne=Gz(),Qw=dh(),dne=Xz.extname,Qz=Qw.mime,pne=Xz.resolve,fne=Yw(),Ct=Object.create(nne.ServerResponse.prototype);r4.exports=Ct;var mne=/;\s*charset\s*=/;Ct.status=function(e){return(typeof e=="string"||Math.floor(e)!==e)&&e>99&&e<1e3&&Gr("res.status("+JSON.stringify(e)+"): use res.status("+Math.floor(e)+") instead"),this.statusCode=e,this};Ct.links=function(t){var e=this.get("Link")||"";return e&&(e+=", "),this.set("Link",e+Object.keys(t).map(function(r){return"<"+t[r]+'>; rel="'+r+'"'}).join(", "))};Ct.send=function(e){var r=e,n,i=this.req,a,o=this.app;switch(arguments.length===2&&(typeof arguments[0]!="number"&&typeof arguments[1]=="number"?(Gr("res.send(body, status): Use res.status(status).send(body) instead"),this.statusCode=arguments[1]):(Gr("res.send(status, body): Use res.status(status).send(body) instead"),this.statusCode=arguments[0],r=arguments[1])),typeof r=="number"&&arguments.length===1&&(this.get("Content-Type")||this.type("txt"),Gr("res.send(status): Use res.sendStatus(status) instead"),this.statusCode=r,r=yh.message[r]),typeof r){case"string":this.get("Content-Type")||this.type("html");break;case"boolean":case"number":case"object":if(r===null)r="";else if(od.isBuffer(r))this.get("Content-Type")||this.type("bin");else return this.json(r);break}typeof r=="string"&&(n="utf8",a=this.get("Content-Type"),typeof a=="string"&&this.set("Content-Type",une(a,"utf-8")));var s=o.get("etag fn"),c=!this.get("ETag")&&typeof s=="function",u;r!==void 0&&(od.isBuffer(r)?u=r.length:!c&&r.length<1e3?u=od.byteLength(r,n):(r=od.from(r,n),n=void 0,u=r.length),this.set("Content-Length",u));var l;return c&&u!==void 0&&(l=s(r,n))&&this.set("ETag",l),i.fresh&&(this.statusCode=304),(this.statusCode===204||this.statusCode===304)&&(this.removeHeader("Content-Type"),this.removeHeader("Content-Length"),this.removeHeader("Transfer-Encoding"),r=""),this.statusCode===205&&(this.set("Content-Length","0"),this.removeHeader("Transfer-Encoding"),r=""),i.method==="HEAD"?this.end():this.end(r,n),this};Ct.json=function(e){var r=e;arguments.length===2&&(typeof arguments[1]=="number"?(Gr("res.json(obj, status): Use res.status(status).json(obj) instead"),this.statusCode=arguments[1]):(Gr("res.json(status, obj): Use res.status(status).json(obj) instead"),this.statusCode=arguments[0],r=arguments[1]));var n=this.app,i=n.get("json escape"),a=n.get("json replacer"),o=n.get("json spaces"),s=t4(r,a,o,i);return this.get("Content-Type")||this.set("Content-Type","application/json"),this.send(s)};Ct.jsonp=function(e){var r=e;arguments.length===2&&(typeof arguments[1]=="number"?(Gr("res.jsonp(obj, status): Use res.status(status).jsonp(obj) instead"),this.statusCode=arguments[1]):(Gr("res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead"),this.statusCode=arguments[0],r=arguments[1]));var n=this.app,i=n.get("json escape"),a=n.get("json replacer"),o=n.get("json spaces"),s=t4(r,a,o,i),c=this.req.query[n.get("jsonp callback name")];return this.get("Content-Type")||(this.set("X-Content-Type-Options","nosniff"),this.set("Content-Type","application/json")),Array.isArray(c)&&(c=c[0]),typeof c=="string"&&c.length!==0&&(this.set("X-Content-Type-Options","nosniff"),this.set("Content-Type","text/javascript"),c=c.replace(/[^\[\]\w$.]/g,""),s===void 0?s="":typeof s=="string"&&(s=s.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")),s="/**/ typeof "+c+" === 'function' && "+c+"("+s+");"),this.send(s)};Ct.sendStatus=function(e){var r=yh.message[e]||String(e);return this.statusCode=e,this.type("txt"),this.send(r)};Ct.sendFile=function(e,r,n){var i=n,a=this.req,o=this,s=a.next,c=r||{};if(!e)throw new TypeError("path argument is required to res.sendFile");if(typeof e!="string")throw new TypeError("path must be a string to res.sendFile");if(typeof r=="function"&&(i=r,c={}),!c.root&&!ine(e))throw new TypeError("path must be absolute or specify root to res.sendFile");var u=encodeURI(e),l=Qw(a,u,c);e4(o,l,c,function(d){if(i)return i(d);if(d&&d.code==="EISDIR")return s();d&&d.code!=="ECONNABORTED"&&d.syscall!=="write"&&s(d)})};Ct.sendfile=function(t,e,r){var n=r,i=this.req,a=this,o=i.next,s=e||{};typeof e=="function"&&(n=e,s={});var c=Qw(i,t,s);e4(a,c,s,function(u){if(n)return n(u);if(u&&u.code==="EISDIR")return o();u&&u.code!=="ECONNABORTED"&&u.syscall!=="write"&&o(u)})};Ct.sendfile=Gr.function(Ct.sendfile,"res.sendfile: Use res.sendFile instead");Ct.download=function(e,r,n,i){var a=i,o=r,s=n||null;typeof r=="function"?(a=r,o=null,s=null):typeof n=="function"&&(a=n,s=null),typeof r=="object"&&(typeof n=="function"||n===void 0)&&(o=null,s=r);var c={"Content-Disposition":Jz(o||e)};if(s&&s.headers)for(var u=Object.keys(s.headers),l=0;l0?e.accepts(n):!1;return this.vary("Accept"),i?(this.set("Content-Type",sne(i).value),t[i](e,this,r)):t.default?t.default(e,this,r):r(ene(406,{types:cne(n).map(function(a){return a.value})})),this};Ct.attachment=function(e){return e&&this.type(dne(e)),this.set("Content-Disposition",Jz(e)),this};Ct.append=function(e,r){var n=this.get(e),i=r;return n&&(i=Array.isArray(n)?n.concat(r):Array.isArray(r)?[n].concat(r):[n,r]),this.set(e,i)};Ct.set=Ct.header=function(e,r){if(arguments.length===2){var n=Array.isArray(r)?r.map(String):String(r);if(e.toLowerCase()==="content-type"){if(Array.isArray(n))throw new TypeError("Content-Type cannot be set to an Array");if(!mne.test(n)){var i=Qz.charsets.lookup(n.split(";")[0]);i&&(n+="; charset="+i.toLowerCase())}}this.setHeader(e,n)}else for(var a in e)this.set(a,e[a]);return this};Ct.get=function(t){return this.getHeader(t)};Ct.clearCookie=function(e,r){r&&(r.maxAge&&Gr('res.clearCookie: Passing "options.maxAge" is deprecated. In v5.0.0 of Express, this option will be ignored, as res.clearCookie will automatically set cookies to expire immediately. Please update your code to omit this option.'),r.expires&&Gr('res.clearCookie: Passing "options.expires" is deprecated. In v5.0.0 of Express, this option will be ignored, as res.clearCookie will automatically set cookies to expire immediately. Please update your code to omit this option.'));var n=Yz({expires:new Date(1),path:"/"},r);return this.cookie(e,"",n)};Ct.cookie=function(t,e,r){var n=Yz({},r),i=this.req.secret,a=n.signed;if(a&&!i)throw new Error('cookieParser("secret") required for signed cookies');var o=typeof e=="object"?"j:"+JSON.stringify(e):String(e);if(a&&(o="s:"+one(o,i)),n.maxAge!=null){var s=n.maxAge-0;isNaN(s)||(n.expires=new Date(Date.now()+s),n.maxAge=Math.floor(s/1e3))}return n.path==null&&(n.path="/"),this.append("Set-Cookie",lne.serialize(t,String(o),n)),this};Ct.location=function(e){var r;return e==="back"?(Gr('res.location("back"): use res.location(req.get("Referrer") || "/") and refer to https://dub.sh/security-redirect for best practices'),r=this.req.get("Referrer")||"/"):r=String(e),this.set("Location",tne(r))};Ct.redirect=function(e){var r=e,n,i=302;arguments.length===2&&(typeof arguments[0]=="number"?(i=arguments[0],r=arguments[1]):(Gr("res.redirect(url, status): Use res.redirect(status, url) instead"),i=arguments[1])),r=this.location(r).get("Location"),this.format({text:function(){n=yh.message[i]+". Redirecting to "+r},html:function(){var a=rne(r);n="

"+yh.message[i]+". Redirecting to "+a+"

"},default:function(){n=""}}),this.statusCode=i,this.set("Content-Length",od.byteLength(n)),this.req.method==="HEAD"?this.end():this.end(n)};Ct.vary=function(t){return!t||Array.isArray(t)&&!t.length?(Gr("res.vary(): Provide a field name"),this):(fne(this,t),this)};Ct.render=function(e,r,n){var i=this.req.app,a=n,o=r||{},s=this.req,c=this;typeof r=="function"&&(a=r,o={}),o._locals=c.locals,a=a||function(u,l){if(u)return s.next(u);c.send(l)},i.render(e,o,a)};function e4(t,e,r,n){var i=!1,a;function o(){if(!i){i=!0;var f=new Error("Request aborted");f.code="ECONNABORTED",n(f)}}function s(){if(!i){i=!0;var f=new Error("EISDIR, read");f.code="EISDIR",n(f)}}function c(f){i||(i=!0,n(f))}function u(){i||(i=!0,n())}function l(){a=!1}function d(f){if(f&&f.code==="ECONNRESET")return o();if(f)return c(f);i||setImmediate(function(){if(a!==!1&&!i){o();return}i||(i=!0,n())})}function p(){a=!0}e.on("directory",s),e.on("end",u),e.on("error",c),e.on("file",l),e.on("stream",p),ane(t,d),r.headers&&e.on("headers",function(g){for(var _=r.headers,h=Object.keys(_),m=0;m&]/g,function(a){switch(a.charCodeAt(0)){case 60:return"\\u003c";case 62:return"\\u003e";case 38:return"\\u0026";default:return a}})),i}});var a4=j((r1e,t$)=>{"use strict";var hne=Yl(),gne=Ql(),e$=Hs(),vne=require("path").resolve,i4=dh(),yne=require("url");t$.exports=_ne;t$.exports.mime=i4.mime;function _ne(t,e){if(!t)throw new TypeError("root path required");if(typeof t!="string")throw new TypeError("root path must be a string");var r=Object.create(e||null),n=r.fallthrough!==!1,i=r.redirect!==!1,a=r.setHeaders;if(a&&typeof a!="function")throw new TypeError("option setHeaders must be function");r.maxage=r.maxage||r.maxAge||0,r.root=vne(t);var o=i?wne():Sne();return function(c,u,l){if(c.method!=="GET"&&c.method!=="HEAD"){if(n)return l();u.statusCode=405,u.setHeader("Allow","GET, HEAD"),u.setHeader("Content-Length","0"),u.end();return}var d=!n,p=e$.original(c),f=e$(c).pathname;f==="/"&&p.pathname.substr(-1)!=="/"&&(f="");var g=i4(c,f,r);g.on("directory",o),a&&g.on("headers",a),n&&g.on("file",function(){d=!0}),g.on("error",function(h){if(d||!(h.statusCode<500)){l(h);return}l()}),g.pipe(u)}}function bne(t){for(var e=0;e1?"/"+t.substr(e):t}function xne(t,e){return` +Please see the 3.x to 4.x migration guide for details on how to update your app.`)}})};tr.lazyrouter=function(){this._router||(this._router=new Zte({caseSensitive:this.enabled("case sensitive routing"),strict:this.enabled("strict routing")}),this._router.use(Bte(this.get("query parser fn"))),this._router.use(Hte.init(this)))};tr.handle=function(e,r,n){var i=this._router,a=n||Fte(e,r,{env:this.get("env"),onerror:tre.bind(this)});if(!i){hh("no routes defined on app"),a();return}i.handle(e,r,a)};tr.use=function(e){var r=0,n="/";if(typeof e!="function"){for(var i=e;Array.isArray(i)&&i.length!==0;)i=i[0];typeof i!="function"&&(r=1,n=e)}var a=Yte(Hw.call(arguments,r));if(a.length===0)throw new TypeError("app.use() requires a middleware function");this.lazyrouter();var o=this._router;return a.forEach(function(s){if(!s||!s.handle||!s.set)return o.use(n,s);hh(".use app under %s",n),s.mountpath=n,s.parent=this,o.use(n,function(u,l,d){var p=u.app;s.handle(u,l,function(f){Ys(u,p.request),Ys(l,p.response),d(f)})}),s.emit("mount",this)},this),this};tr.route=function(e){return this.lazyrouter(),this._router.route(e)};tr.engine=function(e,r){if(typeof r!="function")throw new Error("callback function required");var n=e[0]!=="."?"."+e:e;return this.engines[n]=r,this};tr.param=function(e,r){if(this.lazyrouter(),Array.isArray(e)){for(var n=0;n1?'directories "'+u.root.slice(0,-1).join('", "')+'" or "'+u.root[u.root.length-1]+'"':'directory "'+u.root+'"',p=new Error('Failed to lookup view "'+e+'" in views '+d);return p.view=u,a(p)}c.cache&&(i[e]=u)}rre(u,c,a)};tr.listen=function(){var e=Gte.createServer(this);return e.listen.apply(e,arguments)};function tre(t){this.get("env")!=="test"&&console.error(t.stack||t.toString())}function rre(t,e,r){try{t.render(e,r)}catch(n){r(n)}}});var _z=j((BTe,Bw)=>{"use strict";Bw.exports=yz;Bw.exports.preferredCharsets=yz;var nre=/^\s*([^\s;]+)\s*(?:;(.*))?$/;function ire(t){for(var e=t.split(","),r=0,n=0;r0}});var $z=j((VTe,Vw)=>{"use strict";Vw.exports=wz;Vw.exports.preferredEncodings=wz;var ure=/^\s*([^\s;]+)\s*(?:;(.*))?$/;function lre(t){for(var e=t.split(","),r=!1,n=1,i=0,a=0;i0}});var Pz=j((GTe,Gw)=>{"use strict";Gw.exports=Iz;Gw.exports.preferredLanguages=Iz;var mre=/^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/;function hre(t){for(var e=t.split(","),r=0,n=0;r0}});var Az=j((WTe,Ww)=>{"use strict";Ww.exports=Nz;Ww.exports.preferredMediaTypes=Nz;var _re=/^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/;function bre(t){for(var e=Ere(t),r=0,n=0;r0)if(a.every(function(o){return e.params[o]=="*"||(e.params[o]||"").toLowerCase()==(n.params[o]||"").toLowerCase()}))i|=1;else return null;return{i:r,o:e.i,q:e.q,s:i}}function Nz(t,e){var r=bre(t===void 0?"*/*":t||"");if(!e)return r.filter(Rz).sort(Oz).map(wre);var n=e.map(function(a,o){return xre(a,r,o)});return n.filter(Rz).sort(Oz).map(function(a){return e[n.indexOf(a)]})}function Oz(t,e){return e.q-t.q||e.s-t.s||t.o-e.o||t.i-e.i||0}function wre(t){return t.type+"/"+t.subtype}function Rz(t){return t.q>0}function jz(t){for(var e=0,r=0;(r=t.indexOf('"',r))!==-1;)e++,r++;return e}function $re(t){var e=t.indexOf("="),r,n;return e===-1?r=t:(r=t.substr(0,e),n=t.substr(e+1)),[r,n]}function Ere(t){for(var e=t.split(","),r=1,n=0;r{"use strict";var Tre=_z(),Ire=$z(),Pre=Pz(),Ore=Az();Kw.exports=wt;Kw.exports.Negotiator=wt;function wt(t){if(!(this instanceof wt))return new wt(t);this.request=t}wt.prototype.charset=function(e){var r=this.charsets(e);return r&&r[0]};wt.prototype.charsets=function(e){return Tre(this.request.headers["accept-charset"],e)};wt.prototype.encoding=function(e){var r=this.encodings(e);return r&&r[0]};wt.prototype.encodings=function(e){return Ire(this.request.headers["accept-encoding"],e)};wt.prototype.language=function(e){var r=this.languages(e);return r&&r[0]};wt.prototype.languages=function(e){return Pre(this.request.headers["accept-language"],e)};wt.prototype.mediaType=function(e){var r=this.mediaTypes(e);return r&&r[0]};wt.prototype.mediaTypes=function(e){return Ore(this.request.headers.accept,e)};wt.prototype.preferredCharset=wt.prototype.charset;wt.prototype.preferredCharsets=wt.prototype.charsets;wt.prototype.preferredEncoding=wt.prototype.encoding;wt.prototype.preferredEncodings=wt.prototype.encodings;wt.prototype.preferredLanguage=wt.prototype.language;wt.prototype.preferredLanguages=wt.prototype.languages;wt.prototype.preferredMediaType=wt.prototype.mediaType;wt.prototype.preferredMediaTypes=wt.prototype.mediaTypes});var zz=j((JTe,Dz)=>{"use strict";var Rre=Mz(),Cre=Z0();Dz.exports=un;function un(t){if(!(this instanceof un))return new un(t);this.headers=t.headers,this.negotiator=new Rre(t)}un.prototype.type=un.prototype.types=function(t){var e=t;if(e&&!Array.isArray(e)){e=new Array(arguments.length);for(var r=0;r{"use strict";var gh=zz(),ad=fi()("express"),Are=require("net").isIP,Mre=Ds(),Dre=require("http"),zre=Cw(),Ure=Nw(),Lre=Hs(),Uz=Lw(),Pt=Object.create(Dre.IncomingMessage.prototype);Lz.exports=Pt;Pt.get=Pt.header=function(e){if(!e)throw new TypeError("name argument is required to req.get");if(typeof e!="string")throw new TypeError("name must be a string to req.get");var r=e.toLowerCase();switch(r){case"referer":case"referrer":return this.headers.referrer||this.headers.referer;default:return this.headers[r]}};Pt.accepts=function(){var t=gh(this);return t.types.apply(t,arguments)};Pt.acceptsEncodings=function(){var t=gh(this);return t.encodings.apply(t,arguments)};Pt.acceptsEncoding=ad.function(Pt.acceptsEncodings,"req.acceptsEncoding: Use acceptsEncodings instead");Pt.acceptsCharsets=function(){var t=gh(this);return t.charsets.apply(t,arguments)};Pt.acceptsCharset=ad.function(Pt.acceptsCharsets,"req.acceptsCharset: Use acceptsCharsets instead");Pt.acceptsLanguages=function(){var t=gh(this);return t.languages.apply(t,arguments)};Pt.acceptsLanguage=ad.function(Pt.acceptsLanguages,"req.acceptsLanguage: Use acceptsLanguages instead");Pt.range=function(e,r){var n=this.get("Range");if(n)return Ure(e,n,r)};Pt.param=function(e,r){var n=this.params||{},i=this.body||{},a=this.query||{},o=arguments.length===1?"name":"name, default";return ad("req.param("+o+"): Use req.params, req.body, or req.query instead"),n[e]!=null&&n.hasOwnProperty(e)?n[e]:i[e]!=null?i[e]:a[e]!=null?a[e]:r};Pt.is=function(e){var r=e;if(!Array.isArray(e)){r=new Array(arguments.length);for(var n=0;n=200&&r<300||r===304?zre(this.headers,{etag:e.get("ETag"),"last-modified":e.get("Last-Modified")}):!1});Wn(Pt,"stale",function(){return!this.fresh});Wn(Pt,"xhr",function(){var e=this.get("X-Requested-With")||"";return e.toLowerCase()==="xmlhttprequest"});function Wn(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get:r})}});var Hz=j(vh=>{var Zz=require("crypto");vh.sign=function(t,e){if(typeof t!="string")throw new TypeError("Cookie value must be provided as a string.");if(e==null)throw new TypeError("Secret key must be provided.");return t+"."+Zz.createHmac("sha256",e).update(t).digest("base64").replace(/\=+$/,"")};vh.unsign=function(t,e){if(typeof t!="string")throw new TypeError("Signed cookie string must be provided.");if(e==null)throw new TypeError("Secret key must be provided.");var r=t.slice(0,t.lastIndexOf(".")),n=vh.sign(r,e);return Fz(n)==Fz(t)?r:!1};function Fz(t){return Zz.createHash("sha1").update(t).digest("hex")}});var Gz=j(Jw=>{"use strict";Jw.parse=Gre;Jw.serialize=Wre;var qre=Object.prototype.toString,Fre=Object.prototype.hasOwnProperty,Zre=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Hre=/^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/,Bre=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Vre=/^[\u0020-\u003A\u003D-\u007E]*$/;function Gre(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");var r={},n=t.length;if(n<2)return r;var i=e&&e.decode||Kre,a=0,o=0,s=0;do{if(o=t.indexOf("=",a),o===-1)break;if(s=t.indexOf(";",a),s===-1)s=n;else if(o>s){a=t.lastIndexOf(";",o-1)+1;continue}var c=Bz(t,a,o),u=Vz(t,o,c),l=t.slice(c,u);if(!Fre.call(r,l)){var d=Bz(t,o+1,s),p=Vz(t,s,d);t.charCodeAt(d)===34&&t.charCodeAt(p-1)===34&&(d++,p--);var f=t.slice(d,p);r[l]=Xre(f,i)}a=s+1}while(ar;){var n=t.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return r}function Wre(t,e,r){var n=r&&r.encode||encodeURIComponent;if(typeof n!="function")throw new TypeError("option encode is invalid");if(!Zre.test(t))throw new TypeError("argument name is invalid");var i=n(e);if(!Hre.test(i))throw new TypeError("argument val is invalid");var a=t+"="+i;if(!r)return a;if(r.maxAge!=null){var o=Math.floor(r.maxAge);if(!isFinite(o))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+o}if(r.domain){if(!Bre.test(r.domain))throw new TypeError("option domain is invalid");a+="; Domain="+r.domain}if(r.path){if(!Vre.test(r.path))throw new TypeError("option path is invalid");a+="; Path="+r.path}if(r.expires){var s=r.expires;if(!Jre(s)||isNaN(s.valueOf()))throw new TypeError("option expires is invalid");a+="; Expires="+s.toUTCString()}if(r.httpOnly&&(a+="; HttpOnly"),r.secure&&(a+="; Secure"),r.partitioned&&(a+="; Partitioned"),r.priority){var c=typeof r.priority=="string"?r.priority.toLowerCase():r.priority;switch(c){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}}if(r.sameSite){var u=typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite;switch(u){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return a}function Kre(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}function Jre(t){return qre.call(t)==="[object Date]"}function Xre(t,e){try{return e(t)}catch{return t}}});var Yw=j((e1e,Xw)=>{"use strict";Xw.exports=Qre;Xw.exports.append=Kz;var Yre=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function Kz(t,e){if(typeof t!="string")throw new TypeError("header argument is required");if(!e)throw new TypeError("field argument is required");for(var r=Array.isArray(e)?e:Wz(String(e)),n=0;n{"use strict";var od=oh().Buffer,Jz=Ow(),ene=oo(),Gr=fi()("express"),tne=Yl(),rne=Ql(),nne=require("http"),ine=wa().isAbsolute,ane=Dl(),Xz=require("path"),yh=Il(),Yz=td(),one=Hz().sign,sne=wa().normalizeType,cne=wa().normalizeTypes,une=wa().setCharset,lne=Gz(),Qw=dh(),dne=Xz.extname,Qz=Qw.mime,pne=Xz.resolve,fne=Yw(),Ct=Object.create(nne.ServerResponse.prototype);r4.exports=Ct;var mne=/;\s*charset\s*=/;Ct.status=function(e){return(typeof e=="string"||Math.floor(e)!==e)&&e>99&&e<1e3&&Gr("res.status("+JSON.stringify(e)+"): use res.status("+Math.floor(e)+") instead"),this.statusCode=e,this};Ct.links=function(t){var e=this.get("Link")||"";return e&&(e+=", "),this.set("Link",e+Object.keys(t).map(function(r){return"<"+t[r]+'>; rel="'+r+'"'}).join(", "))};Ct.send=function(e){var r=e,n,i=this.req,a,o=this.app;switch(arguments.length===2&&(typeof arguments[0]!="number"&&typeof arguments[1]=="number"?(Gr("res.send(body, status): Use res.status(status).send(body) instead"),this.statusCode=arguments[1]):(Gr("res.send(status, body): Use res.status(status).send(body) instead"),this.statusCode=arguments[0],r=arguments[1])),typeof r=="number"&&arguments.length===1&&(this.get("Content-Type")||this.type("txt"),Gr("res.send(status): Use res.sendStatus(status) instead"),this.statusCode=r,r=yh.message[r]),typeof r){case"string":this.get("Content-Type")||this.type("html");break;case"boolean":case"number":case"object":if(r===null)r="";else if(od.isBuffer(r))this.get("Content-Type")||this.type("bin");else return this.json(r);break}typeof r=="string"&&(n="utf8",a=this.get("Content-Type"),typeof a=="string"&&this.set("Content-Type",une(a,"utf-8")));var s=o.get("etag fn"),c=!this.get("ETag")&&typeof s=="function",u;r!==void 0&&(od.isBuffer(r)?u=r.length:!c&&r.length<1e3?u=od.byteLength(r,n):(r=od.from(r,n),n=void 0,u=r.length),this.set("Content-Length",u));var l;return c&&u!==void 0&&(l=s(r,n))&&this.set("ETag",l),i.fresh&&(this.statusCode=304),(this.statusCode===204||this.statusCode===304)&&(this.removeHeader("Content-Type"),this.removeHeader("Content-Length"),this.removeHeader("Transfer-Encoding"),r=""),this.statusCode===205&&(this.set("Content-Length","0"),this.removeHeader("Transfer-Encoding"),r=""),i.method==="HEAD"?this.end():this.end(r,n),this};Ct.json=function(e){var r=e;arguments.length===2&&(typeof arguments[1]=="number"?(Gr("res.json(obj, status): Use res.status(status).json(obj) instead"),this.statusCode=arguments[1]):(Gr("res.json(status, obj): Use res.status(status).json(obj) instead"),this.statusCode=arguments[0],r=arguments[1]));var n=this.app,i=n.get("json escape"),a=n.get("json replacer"),o=n.get("json spaces"),s=t4(r,a,o,i);return this.get("Content-Type")||this.set("Content-Type","application/json"),this.send(s)};Ct.jsonp=function(e){var r=e;arguments.length===2&&(typeof arguments[1]=="number"?(Gr("res.jsonp(obj, status): Use res.status(status).jsonp(obj) instead"),this.statusCode=arguments[1]):(Gr("res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead"),this.statusCode=arguments[0],r=arguments[1]));var n=this.app,i=n.get("json escape"),a=n.get("json replacer"),o=n.get("json spaces"),s=t4(r,a,o,i),c=this.req.query[n.get("jsonp callback name")];return this.get("Content-Type")||(this.set("X-Content-Type-Options","nosniff"),this.set("Content-Type","application/json")),Array.isArray(c)&&(c=c[0]),typeof c=="string"&&c.length!==0&&(this.set("X-Content-Type-Options","nosniff"),this.set("Content-Type","text/javascript"),c=c.replace(/[^\[\]\w$.]/g,""),s===void 0?s="":typeof s=="string"&&(s=s.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")),s="/**/ typeof "+c+" === 'function' && "+c+"("+s+");"),this.send(s)};Ct.sendStatus=function(e){var r=yh.message[e]||String(e);return this.statusCode=e,this.type("txt"),this.send(r)};Ct.sendFile=function(e,r,n){var i=n,a=this.req,o=this,s=a.next,c=r||{};if(!e)throw new TypeError("path argument is required to res.sendFile");if(typeof e!="string")throw new TypeError("path must be a string to res.sendFile");if(typeof r=="function"&&(i=r,c={}),!c.root&&!ine(e))throw new TypeError("path must be absolute or specify root to res.sendFile");var u=encodeURI(e),l=Qw(a,u,c);e4(o,l,c,function(d){if(i)return i(d);if(d&&d.code==="EISDIR")return s();d&&d.code!=="ECONNABORTED"&&d.syscall!=="write"&&s(d)})};Ct.sendfile=function(t,e,r){var n=r,i=this.req,a=this,o=i.next,s=e||{};typeof e=="function"&&(n=e,s={});var c=Qw(i,t,s);e4(a,c,s,function(u){if(n)return n(u);if(u&&u.code==="EISDIR")return o();u&&u.code!=="ECONNABORTED"&&u.syscall!=="write"&&o(u)})};Ct.sendfile=Gr.function(Ct.sendfile,"res.sendfile: Use res.sendFile instead");Ct.download=function(e,r,n,i){var a=i,o=r,s=n||null;typeof r=="function"?(a=r,o=null,s=null):typeof n=="function"&&(a=n,s=null),typeof r=="object"&&(typeof n=="function"||n===void 0)&&(o=null,s=r);var c={"Content-Disposition":Jz(o||e)};if(s&&s.headers)for(var u=Object.keys(s.headers),l=0;l0?e.accepts(n):!1;return this.vary("Accept"),i?(this.set("Content-Type",sne(i).value),t[i](e,this,r)):t.default?t.default(e,this,r):r(ene(406,{types:cne(n).map(function(a){return a.value})})),this};Ct.attachment=function(e){return e&&this.type(dne(e)),this.set("Content-Disposition",Jz(e)),this};Ct.append=function(e,r){var n=this.get(e),i=r;return n&&(i=Array.isArray(n)?n.concat(r):Array.isArray(r)?[n].concat(r):[n,r]),this.set(e,i)};Ct.set=Ct.header=function(e,r){if(arguments.length===2){var n=Array.isArray(r)?r.map(String):String(r);if(e.toLowerCase()==="content-type"){if(Array.isArray(n))throw new TypeError("Content-Type cannot be set to an Array");if(!mne.test(n)){var i=Qz.charsets.lookup(n.split(";")[0]);i&&(n+="; charset="+i.toLowerCase())}}this.setHeader(e,n)}else for(var a in e)this.set(a,e[a]);return this};Ct.get=function(t){return this.getHeader(t)};Ct.clearCookie=function(e,r){r&&(r.maxAge&&Gr('res.clearCookie: Passing "options.maxAge" is deprecated. In v5.0.0 of Express, this option will be ignored, as res.clearCookie will automatically set cookies to expire immediately. Please update your code to omit this option.'),r.expires&&Gr('res.clearCookie: Passing "options.expires" is deprecated. In v5.0.0 of Express, this option will be ignored, as res.clearCookie will automatically set cookies to expire immediately. Please update your code to omit this option.'));var n=Yz({expires:new Date(1),path:"/"},r);return this.cookie(e,"",n)};Ct.cookie=function(t,e,r){var n=Yz({},r),i=this.req.secret,a=n.signed;if(a&&!i)throw new Error('cookieParser("secret") required for signed cookies');var o=typeof e=="object"?"j:"+JSON.stringify(e):String(e);if(a&&(o="s:"+one(o,i)),n.maxAge!=null){var s=n.maxAge-0;isNaN(s)||(n.expires=new Date(Date.now()+s),n.maxAge=Math.floor(s/1e3))}return n.path==null&&(n.path="/"),this.append("Set-Cookie",lne.serialize(t,String(o),n)),this};Ct.location=function(e){var r;return e==="back"?(Gr('res.location("back"): use res.location(req.get("Referrer") || "/") and refer to https://dub.sh/security-redirect for best practices'),r=this.req.get("Referrer")||"/"):r=String(e),this.set("Location",tne(r))};Ct.redirect=function(e){var r=e,n,i=302;arguments.length===2&&(typeof arguments[0]=="number"?(i=arguments[0],r=arguments[1]):(Gr("res.redirect(url, status): Use res.redirect(status, url) instead"),i=arguments[1])),r=this.location(r).get("Location"),this.format({text:function(){n=yh.message[i]+". Redirecting to "+r},html:function(){var a=rne(r);n="

"+yh.message[i]+". Redirecting to "+a+"

"},default:function(){n=""}}),this.statusCode=i,this.set("Content-Length",od.byteLength(n)),this.req.method==="HEAD"?this.end():this.end(n)};Ct.vary=function(t){return!t||Array.isArray(t)&&!t.length?(Gr("res.vary(): Provide a field name"),this):(fne(this,t),this)};Ct.render=function(e,r,n){var i=this.req.app,a=n,o=r||{},s=this.req,c=this;typeof r=="function"&&(a=r,o={}),o._locals=c.locals,a=a||function(u,l){if(u)return s.next(u);c.send(l)},i.render(e,o,a)};function e4(t,e,r,n){var i=!1,a;function o(){if(!i){i=!0;var f=new Error("Request aborted");f.code="ECONNABORTED",n(f)}}function s(){if(!i){i=!0;var f=new Error("EISDIR, read");f.code="EISDIR",n(f)}}function c(f){i||(i=!0,n(f))}function u(){i||(i=!0,n())}function l(){a=!1}function d(f){if(f&&f.code==="ECONNRESET")return o();if(f)return c(f);i||setImmediate(function(){if(a!==!1&&!i){o();return}i||(i=!0,n())})}function p(){a=!0}e.on("directory",s),e.on("end",u),e.on("error",c),e.on("file",l),e.on("stream",p),ane(t,d),r.headers&&e.on("headers",function(g){for(var _=r.headers,h=Object.keys(_),m=0;m&]/g,function(a){switch(a.charCodeAt(0)){case 60:return"\\u003c";case 62:return"\\u003e";case 38:return"\\u0026";default:return a}})),i}});var a4=j((r1e,t$)=>{"use strict";var hne=Yl(),gne=Ql(),e$=Hs(),vne=require("path").resolve,i4=dh(),yne=require("url");t$.exports=_ne;t$.exports.mime=i4.mime;function _ne(t,e){if(!t)throw new TypeError("root path required");if(typeof t!="string")throw new TypeError("root path must be a string");var r=Object.create(e||null),n=r.fallthrough!==!1,i=r.redirect!==!1,a=r.setHeaders;if(a&&typeof a!="function")throw new TypeError("option setHeaders must be function");r.maxage=r.maxage||r.maxAge||0,r.root=vne(t);var o=i?wne():Sne();return function(c,u,l){if(c.method!=="GET"&&c.method!=="HEAD"){if(n)return l();u.statusCode=405,u.setHeader("Allow","GET, HEAD"),u.setHeader("Content-Length","0"),u.end();return}var d=!n,p=e$.original(c),f=e$(c).pathname;f==="/"&&p.pathname.substr(-1)!=="/"&&(f="");var g=i4(c,f,r);g.on("directory",o),a&&g.on("headers",a),n&&g.on("file",function(){d=!0}),g.on("error",function(h){if(d||!(h.statusCode<500)){l(h);return}l()}),g.pipe(u)}}function bne(t){for(var e=0;e1?"/"+t.substr(e):t}function xne(t,e){return` @@ -73,7 +73,7 @@ Please see the 3.x to 4.x migration guide for details on how to update your app.
`+e+`
-`}function Sne(){return function(){this.error(404)}}function wne(){return function(e){if(this.hasTrailingSlash()){this.error(404);return}var r=e$.original(this.req);r.path=null,r.pathname=bne(r.pathname+"/");var n=hne(yne.format(r)),i=xne("Redirecting","Redirecting to "+gne(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 d4=j((Wr,l4)=>{"use strict";var _h=AM(),$ne=require("events").EventEmitter,o4=DM(),s4=hz(),Ene=$w(),kne=kw(),c4=qz(),u4=n4();Wr=l4.exports=Tne;function Tne(){var t=function(e,r,n){t.handle(e,r,n)};return o4(t,$ne.prototype,!1),o4(t,s4,!1),t.request=Object.create(c4,{app:{configurable:!0,enumerable:!0,writable:!0,value:t}}),t.response=Object.create(u4,{app:{configurable:!0,enumerable:!0,writable:!0,value:t}}),t.init(),t}Wr.application=s4;Wr.request=c4;Wr.response=u4;Wr.Route=Ene;Wr.Router=kne;Wr.json=_h.json;Wr.query=Tw();Wr.raw=_h.raw;Wr.static=a4();Wr.text=_h.text;Wr.urlencoded=_h.urlencoded;var Ine=["bodyParser","compress","cookieSession","session","logger","cookieParser","favicon","responseTime","errorHandler","timeout","methodOverride","vhost","csrf","directory","limit","multipart","staticCache"];Ine.forEach(function(t){Object.defineProperty(Wr,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 bh=j((n1e,p4)=>{"use strict";p4.exports=d4()});var h4=j((i1e,m4)=>{"use strict";var f4=Object.getOwnPropertySymbols,Pne=Object.prototype.hasOwnProperty,One=Object.prototype.propertyIsEnumerable;function Rne(t){if(t==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}function Cne(){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(a){return e[a]});if(n.join("")!=="0123456789")return!1;var i={};return"abcdefghijklmnopqrst".split("").forEach(function(a){i[a]=a}),Object.keys(Object.assign({},i)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}m4.exports=Cne()?Object.assign:function(t,e){for(var r,n=Rne(t),i,a=1;a{(function(){"use strict";var t=h4(),e=Yw(),r={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function n(g){return typeof g=="string"||g instanceof String}function i(g,_){if(Array.isArray(_)){for(var h=0;h<_.length;++h)if(i(g,_[h]))return!0;return!1}else return n(_)?g===_:_ instanceof RegExp?_.test(g):!!_}function a(g,_){var h=_.headers.origin,m=[],y;return!g.origin||g.origin==="*"?m.push([{key:"Access-Control-Allow-Origin",value:"*"}]):n(g.origin)?(m.push([{key:"Access-Control-Allow-Origin",value:g.origin}]),m.push([{key:"Vary",value:"Origin"}])):(y=i(h,g.origin),m.push([{key:"Access-Control-Allow-Origin",value:y?h:!1}]),m.push([{key:"Vary",value:"Origin"}])),m}function o(g){var _=g.methods;return _.join&&(_=g.methods.join(",")),{key:"Access-Control-Allow-Methods",value:_}}function s(g){return g.credentials===!0?{key:"Access-Control-Allow-Credentials",value:"true"}:null}function c(g,_){var h=g.allowedHeaders||g.headers,m=[];return h?h.join&&(h=h.join(",")):(h=_.headers["access-control-request-headers"],m.push([{key:"Vary",value:"Access-Control-Request-Headers"}])),h&&h.length&&m.push([{key:"Access-Control-Allow-Headers",value:h}]),m}function u(g){var _=g.exposedHeaders;if(_)_.join&&(_=_.join(","));else return null;return _&&_.length?{key:"Access-Control-Expose-Headers",value:_}:null}function l(g){var _=(typeof g.maxAge=="number"||g.maxAge)&&g.maxAge.toString();return _&&_.length?{key:"Access-Control-Max-Age",value:_}:null}function d(g,_){for(var h=0,m=g.length;hr$,BACKUPS_DIR:()=>$4,CLAUDE_COMMANDS_DIR:()=>E4,CLAUDE_CONFIG_DIR:()=>sd,CLAUDE_MD_PATH:()=>Dne,CLAUDE_SETTINGS_PATH:()=>Mne,DATA_DIR:()=>wr,DB_PATH:()=>cd,LOGS_DIR:()=>S4,MODES_DIR:()=>n$,OBSERVER_CONFIG_DIR:()=>xh,TRASH_DIR:()=>w4,USER_SETTINGS_PATH:()=>Tn,VECTOR_DB_DIR:()=>Ane,createBackupFilename:()=>Bne,ensureAllClaudeDirs:()=>Fne,ensureAllDataDirs:()=>Lne,ensureDir:()=>Sr,ensureModesDir:()=>qne,getCurrentProjectName:()=>Zne,getPackageCommandsDir:()=>Hne,getPackageRoot:()=>Kr,getProjectArchiveDir:()=>zne,getWorkerSocketPath:()=>Une});function Nne(){return typeof __dirname<"u"?__dirname:(0,Vt.dirname)((0,x4.fileURLToPath)(Vne.url))}function zne(t){return(0,Vt.join)(r$,t)}function Une(t){return(0,Vt.join)(wr,`worker-${t}.sock`)}function Sr(t){(0,_4.mkdirSync)(t,{recursive:!0})}function Lne(){Sr(wr),Sr(r$),Sr(S4),Sr(w4),Sr($4),Sr(n$)}function qne(){Sr(n$)}function Fne(){Sr(sd),Sr(E4)}function Zne(){try{let t=(0,b4.execSync)("git rev-parse --show-toplevel",{cwd:process.cwd(),encoding:"utf8",stdio:["pipe","pipe","ignore"],windowsHide:!0}).trim();return(0,Vt.basename)(t)}catch(t){return E.debug("SYSTEM","Git root detection failed, using cwd basename",{cwd:process.cwd()},t),(0,Vt.basename)(process.cwd())}}function Kr(){return(0,Vt.join)(jne,"..")}function Hne(){let t=Kr();return(0,Vt.join)(t,"commands")}function Bne(t){let e=new Date().toISOString().replace(/[:.]/g,"-").replace("T","_").slice(0,19);return`${t}.backup.${e}`}var Vt,y4,_4,b4,x4,Vne,jne,wr,sd,r$,S4,w4,$4,n$,Tn,cd,Ane,xh,Mne,E4,Dne,Jr=Le(()=>{"use strict";Vt=require("path"),y4=require("os"),_4=require("fs"),b4=require("child_process"),x4=require("url");un();we();Vne={};jne=Nne(),wr=Qe.get("CLAUDE_MEM_DATA_DIR"),sd=process.env.CLAUDE_CONFIG_DIR||(0,Vt.join)((0,y4.homedir)(),".claude"),r$=(0,Vt.join)(wr,"archives"),S4=(0,Vt.join)(wr,"logs"),w4=(0,Vt.join)(wr,"trash"),$4=(0,Vt.join)(wr,"backups"),n$=(0,Vt.join)(wr,"modes"),Tn=(0,Vt.join)(wr,"settings.json"),cd=(0,Vt.join)(wr,"claude-mem.db"),Ane=(0,Vt.join)(wr,"vector-db"),xh=(0,Vt.join)(wr,"observer-config"),Mne=(0,Vt.join)(sd,"settings.json"),E4=(0,Vt.join)(sd,"commands"),Dne=(0,Vt.join)(sd,"CLAUDE.md")});var F4,$a,$h=Le(()=>{"use strict";F4=require("bun:sqlite");Jr();we();$a=class{db;constructor(e=cd){e!==":memory:"&&Sr(wr),this.db=new F4.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()}initializeSchema(){this.db.run(` +`}function Sne(){return function(){this.error(404)}}function wne(){return function(e){if(this.hasTrailingSlash()){this.error(404);return}var r=e$.original(this.req);r.path=null,r.pathname=bne(r.pathname+"/");var n=hne(yne.format(r)),i=xne("Redirecting","Redirecting to "+gne(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 d4=j((Wr,l4)=>{"use strict";var _h=AM(),$ne=require("events").EventEmitter,o4=DM(),s4=hz(),Ene=$w(),kne=kw(),c4=qz(),u4=n4();Wr=l4.exports=Tne;function Tne(){var t=function(e,r,n){t.handle(e,r,n)};return o4(t,$ne.prototype,!1),o4(t,s4,!1),t.request=Object.create(c4,{app:{configurable:!0,enumerable:!0,writable:!0,value:t}}),t.response=Object.create(u4,{app:{configurable:!0,enumerable:!0,writable:!0,value:t}}),t.init(),t}Wr.application=s4;Wr.request=c4;Wr.response=u4;Wr.Route=Ene;Wr.Router=kne;Wr.json=_h.json;Wr.query=Tw();Wr.raw=_h.raw;Wr.static=a4();Wr.text=_h.text;Wr.urlencoded=_h.urlencoded;var Ine=["bodyParser","compress","cookieSession","session","logger","cookieParser","favicon","responseTime","errorHandler","timeout","methodOverride","vhost","csrf","directory","limit","multipart","staticCache"];Ine.forEach(function(t){Object.defineProperty(Wr,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 bh=j((n1e,p4)=>{"use strict";p4.exports=d4()});var h4=j((i1e,m4)=>{"use strict";var f4=Object.getOwnPropertySymbols,Pne=Object.prototype.hasOwnProperty,One=Object.prototype.propertyIsEnumerable;function Rne(t){if(t==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}function Cne(){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(a){return e[a]});if(n.join("")!=="0123456789")return!1;var i={};return"abcdefghijklmnopqrst".split("").forEach(function(a){i[a]=a}),Object.keys(Object.assign({},i)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}m4.exports=Cne()?Object.assign:function(t,e){for(var r,n=Rne(t),i,a=1;a{(function(){"use strict";var t=h4(),e=Yw(),r={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function n(g){return typeof g=="string"||g instanceof String}function i(g,_){if(Array.isArray(_)){for(var h=0;h<_.length;++h)if(i(g,_[h]))return!0;return!1}else return n(_)?g===_:_ instanceof RegExp?_.test(g):!!_}function a(g,_){var h=_.headers.origin,m=[],y;return!g.origin||g.origin==="*"?m.push([{key:"Access-Control-Allow-Origin",value:"*"}]):n(g.origin)?(m.push([{key:"Access-Control-Allow-Origin",value:g.origin}]),m.push([{key:"Vary",value:"Origin"}])):(y=i(h,g.origin),m.push([{key:"Access-Control-Allow-Origin",value:y?h:!1}]),m.push([{key:"Vary",value:"Origin"}])),m}function o(g){var _=g.methods;return _.join&&(_=g.methods.join(",")),{key:"Access-Control-Allow-Methods",value:_}}function s(g){return g.credentials===!0?{key:"Access-Control-Allow-Credentials",value:"true"}:null}function c(g,_){var h=g.allowedHeaders||g.headers,m=[];return h?h.join&&(h=h.join(",")):(h=_.headers["access-control-request-headers"],m.push([{key:"Vary",value:"Access-Control-Request-Headers"}])),h&&h.length&&m.push([{key:"Access-Control-Allow-Headers",value:h}]),m}function u(g){var _=g.exposedHeaders;if(_)_.join&&(_=_.join(","));else return null;return _&&_.length?{key:"Access-Control-Expose-Headers",value:_}:null}function l(g){var _=(typeof g.maxAge=="number"||g.maxAge)&&g.maxAge.toString();return _&&_.length?{key:"Access-Control-Max-Age",value:_}:null}function d(g,_){for(var h=0,m=g.length;hr$,BACKUPS_DIR:()=>$4,CLAUDE_COMMANDS_DIR:()=>E4,CLAUDE_CONFIG_DIR:()=>sd,CLAUDE_MD_PATH:()=>Dne,CLAUDE_SETTINGS_PATH:()=>Mne,DATA_DIR:()=>wr,DB_PATH:()=>cd,LOGS_DIR:()=>S4,MODES_DIR:()=>n$,OBSERVER_SESSIONS_DIR:()=>xh,TRASH_DIR:()=>w4,USER_SETTINGS_PATH:()=>Tn,VECTOR_DB_DIR:()=>Ane,createBackupFilename:()=>Bne,ensureAllClaudeDirs:()=>Fne,ensureAllDataDirs:()=>Lne,ensureDir:()=>Sr,ensureModesDir:()=>qne,getCurrentProjectName:()=>Zne,getPackageCommandsDir:()=>Hne,getPackageRoot:()=>Kr,getProjectArchiveDir:()=>zne,getWorkerSocketPath:()=>Une});function Nne(){return typeof __dirname<"u"?__dirname:(0,Vt.dirname)((0,x4.fileURLToPath)(Vne.url))}function zne(t){return(0,Vt.join)(r$,t)}function Une(t){return(0,Vt.join)(wr,`worker-${t}.sock`)}function Sr(t){(0,_4.mkdirSync)(t,{recursive:!0})}function Lne(){Sr(wr),Sr(r$),Sr(S4),Sr(w4),Sr($4),Sr(n$)}function qne(){Sr(n$)}function Fne(){Sr(sd),Sr(E4)}function Zne(){try{let t=(0,b4.execSync)("git rev-parse --show-toplevel",{cwd:process.cwd(),encoding:"utf8",stdio:["pipe","pipe","ignore"],windowsHide:!0}).trim();return(0,Vt.basename)(t)}catch(t){return E.debug("SYSTEM","Git root detection failed, using cwd basename",{cwd:process.cwd()},t),(0,Vt.basename)(process.cwd())}}function Kr(){return(0,Vt.join)(jne,"..")}function Hne(){let t=Kr();return(0,Vt.join)(t,"commands")}function Bne(t){let e=new Date().toISOString().replace(/[:.]/g,"-").replace("T","_").slice(0,19);return`${t}.backup.${e}`}var Vt,y4,_4,b4,x4,Vne,jne,wr,sd,r$,S4,w4,$4,n$,Tn,cd,Ane,xh,Mne,E4,Dne,ln=Le(()=>{"use strict";Vt=require("path"),y4=require("os"),_4=require("fs"),b4=require("child_process"),x4=require("url");cn();we();Vne={};jne=Nne(),wr=Qe.get("CLAUDE_MEM_DATA_DIR"),sd=process.env.CLAUDE_CONFIG_DIR||(0,Vt.join)((0,y4.homedir)(),".claude"),r$=(0,Vt.join)(wr,"archives"),S4=(0,Vt.join)(wr,"logs"),w4=(0,Vt.join)(wr,"trash"),$4=(0,Vt.join)(wr,"backups"),n$=(0,Vt.join)(wr,"modes"),Tn=(0,Vt.join)(wr,"settings.json"),cd=(0,Vt.join)(wr,"claude-mem.db"),Ane=(0,Vt.join)(wr,"vector-db"),xh=(0,Vt.join)(wr,"observer-sessions"),Mne=(0,Vt.join)(sd,"settings.json"),E4=(0,Vt.join)(sd,"commands"),Dne=(0,Vt.join)(sd,"CLAUDE.md")});var F4,$a,$h=Le(()=>{"use strict";F4=require("bun:sqlite");ln();we();$a=class{db;constructor(e=cd){e!==":memory:"&&Sr(wr),this.db=new F4.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()}initializeSchema(){this.db.run(` CREATE TABLE IF NOT EXISTS schema_versions ( id INTEGER PRIMARY KEY, version INTEGER UNIQUE NOT NULL, @@ -641,7 +641,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 Q4={};pn(Q4,{ModeManager:()=>Be});var pd,Nh,Be,Mr=Le(()=>{"use strict";pd=require("fs"),Nh=require("path");we();Jr();Be=class t{static instance=null;activeMode=null;modesDir;constructor(){let e=Kr(),r=[(0,Nh.join)(e,"modes"),(0,Nh.join)(e,"..","plugin","modes")],n=r.find(i=>(0,pd.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 a=r[i],o=e[i];this.isPlainObject(a)&&this.isPlainObject(o)?n[i]=this.deepMerge(o,a):n[i]=a}return n}loadModeFile(e){let r=(0,Nh.join)(this.modesDir,`${e}.json`);if(!(0,pd.existsSync)(r))throw new Error(`Mode file not found: ${r}`);let n=(0,pd.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,E.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(E.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,a;try{a=this.loadMode(n)}catch{E.warn("SYSTEM",`Parent mode '${n}' not found for ${e}, falling back to 'code'`),a=this.loadMode("code")}let o;try{o=this.loadModeFile(i),E.debug("SYSTEM",`Loaded override file: ${i} for parent ${n}`)}catch{return E.warn("SYSTEM",`Override file '${i}' not found, using parent mode '${n}' only`),this.activeMode=a,a}if(!o)return E.warn("SYSTEM",`Invalid override file: ${i}, using parent mode '${n}' only`),this.activeMode=a,a;let s=this.deepMerge(a,o);return this.activeMode=s,E.debug("SYSTEM",`Loaded mode with inheritance: ${s.name} (${e} = ${n} + ${i})`,void 0,{parent:n,override:i,types:s.observation_types.map(c=>c.id),concepts:s.observation_concepts.map(c=>c.id)}),s}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 Ah(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e:[]}catch(e){return E.debug("PARSER","Failed to parse JSON array, using empty fallback",{preview:t?.substring(0,50)},e),[]}}function Pn(t){return new Date(t).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function Dr(t){return new Date(t).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function Fi(t){return new Date(t).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}function r2(t,e){return f$.default.isAbsolute(t)?f$.default.relative(e,t):t}function Kn(t,e,r){let n=Ah(t);if(n.length>0)return r2(n[0],e);if(r){let i=Ah(r);if(i.length>0)return r2(i[0],e)}return"General"}function oc(t){return t?Math.ceil(t.length/4):0}function So(t,e){let r=new Map;for(let i of t){let a=e(i),o=Fi(a);r.has(o)||r.set(o,[]),r.get(o).push(i)}let n=Array.from(r.entries()).sort((i,a)=>{let o=new Date(i[0]).getTime(),s=new Date(a[0]).getTime();return o-s});return new Map(n)}var f$,sc=Le(()=>{"use strict";f$=ut(require("path"),1);we()});function ZU(t){let e=Ng.default.join(t,".git"),r;try{r=(0,jg.statSync)(e)}catch{return Hd}if(!r.isFile())return Hd;let n;try{n=(0,jg.readFileSync)(e,"utf-8").trim()}catch{return Hd}let i=n.match(/^gitdir:\s*(.+)$/);if(!i)return Hd;let o=i[1].match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!o)return Hd;let s=o[1],c=Ng.default.basename(t),u=Ng.default.basename(s);return{isWorktree:!0,worktreeName:c,parentRepoPath:s,parentProjectName:u}}var jg,Ng,Hd,HU=Le(()=>{"use strict";jg=require("fs"),Ng=ut(require("path"),1),Hd={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null}});function Bd(t){if(!t||t.trim()==="")return E.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),"unknown-project";let e=BU.default.basename(t);if(e===""){if(process.platform==="win32"){let n=t.match(/^([A-Z]):\\/i);if(n){let a=`drive-${n[1].toUpperCase()}`;return E.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:a}),a}}return E.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),"unknown-project"}return e}function VU(t){let e=Bd(t);if(!t)return{primary:e,parent:null,isWorktree:!1,allProjects:[e]};let r=ZU(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 BU,Ag=Le(()=>{"use strict";BU=ut(require("path"),1);we();HU()});function hE(){let t=GU.default.join((0,WU.homedir)(),".claude-mem","settings.json"),e=Qe.loadFromFile(t),r=e.CLAUDE_MEM_MODE,n=r==="code"||r.startsWith("code--"),i,a;if(n)i=new Set(e.CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES.split(",").map(o=>o.trim()).filter(Boolean)),a=new Set(e.CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS.split(",").map(o=>o.trim()).filter(Boolean));else{let o=Be.getInstance().getActiveMode();i=new Set(o.observation_types.map(s=>s.id)),a=new Set(o.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:i,observationConcepts:a,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 GU,WU,gE=Le(()=>{"use strict";GU=ut(require("path"),1),WU=require("os");un();Mr()});var ne,KU,vE,Vd=Le(()=>{"use strict";ne={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"},KU=4,vE=1});function yE(t){let e=(t.title?.length||0)+(t.subtitle?.length||0)+(t.narrative?.length||0)+JSON.stringify(t.facts||[]).length;return Math.ceil(e/KU)}function _E(t){let e=t.length,r=t.reduce((o,s)=>o+yE(s),0),n=t.reduce((o,s)=>o+(s.discovery_tokens||0),0),i=n-r,a=n>0?Math.round(i/n*100):0;return{totalObservations:e,totalReadTokens:r,totalDiscoveryTokens:n,savings:i,savingsPercent:a}}function qme(t){return Be.getInstance().getWorkEmoji(t)}function Cc(t,e){let r=yE(t),n=t.discovery_tokens||0,i=qme(t.type),a=n>0?`${i} ${n.toLocaleString()}`:"-";return{readTokens:r,discoveryTokens:n,discoveryDisplay:a,workEmoji:i}}function Mg(t){return t.showReadTokens||t.showWorkTokens||t.showSavingsAmount||t.showSavingsPercent}var Oo=Le(()=>{"use strict";Vd();Mr()});function bE(t,e,r){let n=Array.from(r.observationTypes),i=n.map(()=>"?").join(","),a=Array.from(r.observationConcepts),o=a.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 Q4={};pn(Q4,{ModeManager:()=>Be});var pd,Nh,Be,Mr=Le(()=>{"use strict";pd=require("fs"),Nh=require("path");we();ln();Be=class t{static instance=null;activeMode=null;modesDir;constructor(){let e=Kr(),r=[(0,Nh.join)(e,"modes"),(0,Nh.join)(e,"..","plugin","modes")],n=r.find(i=>(0,pd.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 a=r[i],o=e[i];this.isPlainObject(a)&&this.isPlainObject(o)?n[i]=this.deepMerge(o,a):n[i]=a}return n}loadModeFile(e){let r=(0,Nh.join)(this.modesDir,`${e}.json`);if(!(0,pd.existsSync)(r))throw new Error(`Mode file not found: ${r}`);let n=(0,pd.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,E.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(E.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,a;try{a=this.loadMode(n)}catch{E.warn("SYSTEM",`Parent mode '${n}' not found for ${e}, falling back to 'code'`),a=this.loadMode("code")}let o;try{o=this.loadModeFile(i),E.debug("SYSTEM",`Loaded override file: ${i} for parent ${n}`)}catch{return E.warn("SYSTEM",`Override file '${i}' not found, using parent mode '${n}' only`),this.activeMode=a,a}if(!o)return E.warn("SYSTEM",`Invalid override file: ${i}, using parent mode '${n}' only`),this.activeMode=a,a;let s=this.deepMerge(a,o);return this.activeMode=s,E.debug("SYSTEM",`Loaded mode with inheritance: ${s.name} (${e} = ${n} + ${i})`,void 0,{parent:n,override:i,types:s.observation_types.map(c=>c.id),concepts:s.observation_concepts.map(c=>c.id)}),s}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 Ah(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e:[]}catch(e){return E.debug("PARSER","Failed to parse JSON array, using empty fallback",{preview:t?.substring(0,50)},e),[]}}function Pn(t){return new Date(t).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function Dr(t){return new Date(t).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function Fi(t){return new Date(t).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}function r2(t,e){return f$.default.isAbsolute(t)?f$.default.relative(e,t):t}function Kn(t,e,r){let n=Ah(t);if(n.length>0)return r2(n[0],e);if(r){let i=Ah(r);if(i.length>0)return r2(i[0],e)}return"General"}function oc(t){return t?Math.ceil(t.length/4):0}function So(t,e){let r=new Map;for(let i of t){let a=e(i),o=Fi(a);r.has(o)||r.set(o,[]),r.get(o).push(i)}let n=Array.from(r.entries()).sort((i,a)=>{let o=new Date(i[0]).getTime(),s=new Date(a[0]).getTime();return o-s});return new Map(n)}var f$,sc=Le(()=>{"use strict";f$=ut(require("path"),1);we()});function ZU(t){let e=Ng.default.join(t,".git"),r;try{r=(0,jg.statSync)(e)}catch{return Hd}if(!r.isFile())return Hd;let n;try{n=(0,jg.readFileSync)(e,"utf-8").trim()}catch{return Hd}let i=n.match(/^gitdir:\s*(.+)$/);if(!i)return Hd;let o=i[1].match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!o)return Hd;let s=o[1],c=Ng.default.basename(t),u=Ng.default.basename(s);return{isWorktree:!0,worktreeName:c,parentRepoPath:s,parentProjectName:u}}var jg,Ng,Hd,HU=Le(()=>{"use strict";jg=require("fs"),Ng=ut(require("path"),1),Hd={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null}});function Bd(t){if(!t||t.trim()==="")return E.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),"unknown-project";let e=BU.default.basename(t);if(e===""){if(process.platform==="win32"){let n=t.match(/^([A-Z]):\\/i);if(n){let a=`drive-${n[1].toUpperCase()}`;return E.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:a}),a}}return E.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),"unknown-project"}return e}function VU(t){let e=Bd(t);if(!t)return{primary:e,parent:null,isWorktree:!1,allProjects:[e]};let r=ZU(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 BU,Ag=Le(()=>{"use strict";BU=ut(require("path"),1);we();HU()});function hE(){let t=GU.default.join((0,WU.homedir)(),".claude-mem","settings.json"),e=Qe.loadFromFile(t),r=e.CLAUDE_MEM_MODE,n=r==="code"||r.startsWith("code--"),i,a;if(n)i=new Set(e.CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES.split(",").map(o=>o.trim()).filter(Boolean)),a=new Set(e.CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS.split(",").map(o=>o.trim()).filter(Boolean));else{let o=Be.getInstance().getActiveMode();i=new Set(o.observation_types.map(s=>s.id)),a=new Set(o.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:i,observationConcepts:a,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 GU,WU,gE=Le(()=>{"use strict";GU=ut(require("path"),1),WU=require("os");cn();Mr()});var ne,KU,vE,Vd=Le(()=>{"use strict";ne={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"},KU=4,vE=1});function yE(t){let e=(t.title?.length||0)+(t.subtitle?.length||0)+(t.narrative?.length||0)+JSON.stringify(t.facts||[]).length;return Math.ceil(e/KU)}function _E(t){let e=t.length,r=t.reduce((o,s)=>o+yE(s),0),n=t.reduce((o,s)=>o+(s.discovery_tokens||0),0),i=n-r,a=n>0?Math.round(i/n*100):0;return{totalObservations:e,totalReadTokens:r,totalDiscoveryTokens:n,savings:i,savingsPercent:a}}function qme(t){return Be.getInstance().getWorkEmoji(t)}function Cc(t,e){let r=yE(t),n=t.discovery_tokens||0,i=qme(t.type),a=n>0?`${i} ${n.toLocaleString()}`:"-";return{readTokens:r,discoveryTokens:n,discoveryDisplay:a,workEmoji:i}}function Mg(t){return t.showReadTokens||t.showWorkTokens||t.showSavingsAmount||t.showSavingsPercent}var Oo=Le(()=>{"use strict";Vd();Mr()});function bE(t,e,r){let n=Array.from(r.observationTypes),i=n.map(()=>"?").join(","),a=Array.from(r.observationConcepts),o=a.map(()=>"?").join(",");return t.db.prepare(` SELECT id, memory_session_id, type, title, subtitle, narrative, facts, concepts, files_read, files_modified, discovery_tokens, @@ -706,9 +706,9 @@ ${ne.dim}No previous sessions found for this project yet.${ne.reset} `+String.fromCodePoint(128172)+` Community https://discord.gg/J4wttp9vDu `+String.fromCodePoint(128250)+` Watch live in browser http://localhost:${e}/ -`),{exitCode:bl.USER_MESSAGE_ONLY}}}});var FE,ZE=Le(()=>{"use strict";Hr();we();FE={async execute(t){await Sn();let{sessionId:e,cwd:r,filePath:n,edits:i}=t;if(!n)throw new Error("fileEditHandler requires filePath");let a=It();if(E.dataIn("HOOK",`FileEdit: ${n}`,{workerPort:a,editCount:i?.length??0}),!r)throw new Error(`Missing cwd in FileEdit hook input for session ${e}, file ${n}`);let o=await fetch(`http://127.0.0.1:${a}/api/sessions/observations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentSessionId:e,tool_name:"write_file",tool_input:{filePath:n,edits:i},tool_response:{success:!0},cwd:r})});if(!o.ok)throw new Error(`File edit observation storage failed: ${o.status}`);return E.debug("HOOK","File edit observation sent successfully",{filePath:n}),{continue:!0,suppressOutput:!0}}}});function cq(t){let e=Yme[t];if(!e)throw new Error(`Unknown event type: ${t}`);return e}var Yme,uq=Le(()=>{"use strict";NE();AE();DE();UE();qE();ZE();NE();AE();DE();UE();qE();ZE();Yme={context:CE,"session-init":jE,observation:ME,summarize:zE,"user-message":LE,"file-edit":FE}});var lq={};pn(lq,{hookCommand:()=>Qme});async function Qme(t,e){try{let r=nq(t),n=cq(e),i=await KL(),a=r.normalizeInput(i);a.platform=t;let o=await n.execute(a),s=r.formatOutput(o);console.log(JSON.stringify(s)),process.exit(o.exitCode??bl.SUCCESS)}catch(r){console.error(`Hook error: ${r}`),process.exit(bl.BLOCKING_ERROR)}}var dq=Le(()=>{"use strict";JL();iq();uq();xl()});var nhe={};pn(nhe,{WorkerService:()=>Vg,buildStatusOutput:()=>fq});module.exports=Yd(nhe);var pq=ut(require("path"),1);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 a={};for(let o of i)a[o]=o;return a},t.getValidEnumValues=i=>{let a=t.objectKeys(i).filter(s=>typeof i[i[s]]!="number"),o={};for(let s of a)o[s]=i[s];return t.objectValues(o)},t.objectValues=i=>t.objectKeys(i).map(function(a){return i[a]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let a=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&a.push(o);return a},t.find=(i,a)=>{for(let o of i)if(a(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,a=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(a)}t.joinValues=n,t.jsonStringifyReplacer=(i,a)=>typeof a=="bigint"?a.toString():a})(Ye||(Ye={}));var BE;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(BE||(BE={}));var ue=Ye.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),wi=t=>{switch(typeof t){case"undefined":return ue.undefined;case"string":return ue.string;case"number":return Number.isNaN(t)?ue.nan:ue.number;case"boolean":return ue.boolean;case"function":return ue.function;case"bigint":return ue.bigint;case"symbol":return ue.symbol;case"object":return Array.isArray(t)?ue.array:t===null?ue.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?ue.promise:typeof Map<"u"&&t instanceof Map?ue.map:typeof Set<"u"&&t instanceof Set?ue.set:typeof Date<"u"&&t instanceof Date?ue.date:ue.object;default:return ue.unknown}};var Q=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 rn=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(a){return a.message},n={_errors:[]},i=a=>{for(let o of a.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 s=n,c=0;for(;cr.message){let r=Object.create(null),n=[];for(let i of this.issues)if(i.path.length>0){let a=i.path[0];r[a]=r[a]||[],r[a].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};rn.create=t=>new rn(t);var _q=(t,e)=>{let r;switch(t.code){case Q.invalid_type:t.received===ue.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case Q.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Ye.jsonStringifyReplacer)}`;break;case Q.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ye.joinValues(t.keys,", ")}`;break;case Q.invalid_union:r="Invalid input";break;case Q.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ye.joinValues(t.options)}`;break;case Q.invalid_enum_value:r=`Invalid enum value. Expected ${Ye.joinValues(t.options)}, received '${t.received}'`;break;case Q.invalid_arguments:r="Invalid function arguments";break;case Q.invalid_return_type:r="Invalid function return type";break;case Q.invalid_date:r="Invalid date";break;case Q.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 Q.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 Q.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 Q.custom:r="Invalid input";break;case Q.invalid_intersection_types:r="Intersection results could not be merged";break;case Q.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case Q.not_finite:r="Number must be finite";break;default:r=e.defaultError,Ye.assertNever(t)}return{message:r}},Ji=_q;var bq=Ji;function Dc(){return bq}var Qd=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,a=[...r,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)s=u(o,{data:e,defaultError:s}).message;return{...i,path:a,message:s}};function ae(t,e){let r=Dc(),n=Qd({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ji?void 0:Ji].filter(i=>!!i)});t.common.issues.push(n)}var gr=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 Ie;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 a=await i.key,o=await i.value;n.push({key:a,value:o})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:a,value:o}=i;if(a.status==="aborted"||o.status==="aborted")return Ie;a.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(n[a.value]=o.value)}return{status:e.value,value:n}}},Ie=Object.freeze({status:"aborted"}),jo=t=>({status:"dirty",value:t}),Tr=t=>({status:"valid",value:t}),Wg=t=>t.status==="aborted",Kg=t=>t.status==="dirty",Aa=t=>t.status==="valid",zc=t=>typeof Promise<"u"&&t instanceof Promise;var he;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(he||(he={}));var fn=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}},VE=(t,e)=>{if(Aa(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 rn(t.common.issues);return this._error=r,this._error}}};function Me(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,s)=>{let{message:c}=t;return o.code==="invalid_enum_value"?{message:c??s.defaultError}:typeof s.data>"u"?{message:c??n??s.defaultError}:o.code!=="invalid_type"?{message:s.defaultError}:{message:c??r??s.defaultError}},description:i}}var Ze=class{get description(){return this._def.description}_getType(e){return wi(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:wi(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new gr,ctx:{common:e.parent.common,data:e.data,parsedType:wi(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(zc(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:wi(e)},i=this._parseSync({data:e,path:n.path,parent:n});return VE(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:wi(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Aa(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=>Aa(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:wi(e)},i=this._parse({data:e,path:n.path,parent:n}),a=await(zc(i)?i:Promise.resolve(i));return VE(n,a)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,a)=>{let o=e(i),s=()=>a.addIssue({code:Q.custom,...n(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(s(),!1)):o?!0:(s(),!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 Dn({schema:this,typeName:$e.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 Mn.create(this,this._def)}nullable(){return ki.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yi.create(this)}promise(){return Ma.create(this,this._def)}or(e){return Uo.create([this,e],this._def)}and(e){return Lo.create(this,e,this._def)}transform(e){return new Dn({...Me(this._def),schema:this,typeName:$e.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Bo({...Me(this._def),innerType:this,defaultValue:r,typeName:$e.ZodDefault})}brand(){return new ep({typeName:$e.ZodBranded,type:this,...Me(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Vo({...Me(this._def),innerType:this,catchValue:r,typeName:$e.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return tp.create(this,e)}readonly(){return Go.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},xq=/^c[^\s-]{8,}$/i,Sq=/^[0-9a-z]+$/,wq=/^[0-9A-HJKMNP-TV-Z]{26}$/i,$q=/^[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,Eq=/^[a-z0-9_-]{21}$/i,kq=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Tq=/^[-+]?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)?)??$/,Iq=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Pq="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Jg,Oq=/^(?:(?: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])$/,Rq=/^(?:(?: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])$/,Cq=/^(([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]))$/,Nq=/^(([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])$/,jq=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Aq=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,GE="((\\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])))",Mq=new RegExp(`^${GE}$`);function WE(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 Dq(t){return new RegExp(`^${WE(t)}$`)}function zq(t){let e=`${GE}T${WE(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 Uq(t,e){return!!((e==="v4"||!e)&&Oq.test(t)||(e==="v6"||!e)&&Cq.test(t))}function Lq(t,e){if(!kq.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 qq(t,e){return!!((e==="v4"||!e)&&Rq.test(t)||(e==="v6"||!e)&&Nq.test(t))}var Mo=class t extends Ze{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ue.string){let a=this._getOrReturnCtx(e);return ae(a,{code:Q.invalid_type,expected:ue.string,received:a.parsedType}),Ie}let n=new gr,i;for(let a of this._def.checks)if(a.kind==="min")e.data.lengtha.value&&(i=this._getOrReturnCtx(e,i),ae(i,{code:Q.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){let o=e.data.length>a.value,s=e.data.lengthe.test(i),{validation:r,code:Q.invalid_string,...he.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...he.errToObj(e)})}url(e){return this._addCheck({kind:"url",...he.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...he.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...he.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...he.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...he.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...he.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...he.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...he.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...he.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...he.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...he.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...he.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,...he.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,...he.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...he.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...he.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...he.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...he.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...he.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...he.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...he.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...he.errToObj(r)})}nonempty(e){return this.min(1,he.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 Mo({checks:[],typeName:$e.ZodString,coerce:t?.coerce??!1,...Me(t)});function Fq(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,a=Number.parseInt(t.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return a%o/10**i}var Uc=class t extends Ze{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)!==ue.number){let a=this._getOrReturnCtx(e);return ae(a,{code:Q.invalid_type,expected:ue.number,received:a.parsedType}),Ie}let n,i=new gr;for(let a of this._def.checks)a.kind==="int"?Ye.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{code:Q.invalid_type,expected:"integer",received:"float",message:a.message}),i.dirty()):a.kind==="min"?(a.inclusive?e.dataa.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),ae(n,{code:Q.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="multipleOf"?Fq(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),ae(n,{code:Q.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{code:Q.not_finite,message:a.message}),i.dirty()):Ye.assertNever(a);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,he.toString(r))}gt(e,r){return this.setLimit("min",e,!1,he.toString(r))}lte(e,r){return this.setLimit("max",e,!0,he.toString(r))}lt(e,r){return this.setLimit("max",e,!1,he.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:he.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:he.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:he.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:he.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:he.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:he.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:he.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:he.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:he.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:he.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 Uc({checks:[],typeName:$e.ZodNumber,coerce:t?.coerce||!1,...Me(t)});var Lc=class t extends Ze{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)!==ue.bigint)return this._getInvalidInput(e);let n,i=new gr;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.dataa.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),ae(n,{code:Q.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),ae(n,{code:Q.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):Ye.assertNever(a);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return ae(r,{code:Q.invalid_type,expected:ue.bigint,received:r.parsedType}),Ie}gte(e,r){return this.setLimit("min",e,!0,he.toString(r))}gt(e,r){return this.setLimit("min",e,!1,he.toString(r))}lte(e,r){return this.setLimit("max",e,!0,he.toString(r))}lt(e,r){return this.setLimit("max",e,!1,he.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:he.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:he.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:he.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:he.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:he.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:he.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 Lc({checks:[],typeName:$e.ZodBigInt,coerce:t?.coerce??!1,...Me(t)});var qc=class extends Ze{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ue.boolean){let n=this._getOrReturnCtx(e);return ae(n,{code:Q.invalid_type,expected:ue.boolean,received:n.parsedType}),Ie}return Tr(e.data)}};qc.create=t=>new qc({typeName:$e.ZodBoolean,coerce:t?.coerce||!1,...Me(t)});var Fc=class t extends Ze{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ue.date){let a=this._getOrReturnCtx(e);return ae(a,{code:Q.invalid_type,expected:ue.date,received:a.parsedType}),Ie}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return ae(a,{code:Q.invalid_date}),Ie}let n=new gr,i;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()a.value&&(i=this._getOrReturnCtx(e,i),ae(i,{code:Q.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):Ye.assertNever(a);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:he.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:he.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 Fc({checks:[],coerce:t?.coerce||!1,typeName:$e.ZodDate,...Me(t)});var Zc=class extends Ze{_parse(e){if(this._getType(e)!==ue.symbol){let n=this._getOrReturnCtx(e);return ae(n,{code:Q.invalid_type,expected:ue.symbol,received:n.parsedType}),Ie}return Tr(e.data)}};Zc.create=t=>new Zc({typeName:$e.ZodSymbol,...Me(t)});var Do=class extends Ze{_parse(e){if(this._getType(e)!==ue.undefined){let n=this._getOrReturnCtx(e);return ae(n,{code:Q.invalid_type,expected:ue.undefined,received:n.parsedType}),Ie}return Tr(e.data)}};Do.create=t=>new Do({typeName:$e.ZodUndefined,...Me(t)});var zo=class extends Ze{_parse(e){if(this._getType(e)!==ue.null){let n=this._getOrReturnCtx(e);return ae(n,{code:Q.invalid_type,expected:ue.null,received:n.parsedType}),Ie}return Tr(e.data)}};zo.create=t=>new zo({typeName:$e.ZodNull,...Me(t)});var Hc=class extends Ze{constructor(){super(...arguments),this._any=!0}_parse(e){return Tr(e.data)}};Hc.create=t=>new Hc({typeName:$e.ZodAny,...Me(t)});var Xi=class extends Ze{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Tr(e.data)}};Xi.create=t=>new Xi({typeName:$e.ZodUnknown,...Me(t)});var ni=class extends Ze{_parse(e){let r=this._getOrReturnCtx(e);return ae(r,{code:Q.invalid_type,expected:ue.never,received:r.parsedType}),Ie}};ni.create=t=>new ni({typeName:$e.ZodNever,...Me(t)});var Bc=class extends Ze{_parse(e){if(this._getType(e)!==ue.undefined){let n=this._getOrReturnCtx(e);return ae(n,{code:Q.invalid_type,expected:ue.void,received:n.parsedType}),Ie}return Tr(e.data)}};Bc.create=t=>new Bc({typeName:$e.ZodVoid,...Me(t)});var Yi=class t extends Ze{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==ue.array)return ae(r,{code:Q.invalid_type,expected:ue.array,received:r.parsedType}),Ie;if(i.exactLength!==null){let o=r.data.length>i.exactLength.value,s=r.data.lengthi.maxLength.value&&(ae(r,{code:Q.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,s)=>i.type._parseAsync(new fn(r,o,r.path,s)))).then(o=>gr.mergeArray(n,o));let a=[...r.data].map((o,s)=>i.type._parseSync(new fn(r,o,r.path,s)));return gr.mergeArray(n,a)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:he.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:he.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:he.toString(r)}})}nonempty(e){return this.min(1,e)}};Yi.create=(t,e)=>new Yi({type:t,minLength:null,maxLength:null,exactLength:null,typeName:$e.ZodArray,...Me(e)});function Ao(t){if(t instanceof nn){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Mn.create(Ao(n))}return new nn({...t._def,shape:()=>e})}else return t instanceof Yi?new Yi({...t._def,type:Ao(t.element)}):t instanceof Mn?Mn.create(Ao(t.unwrap())):t instanceof ki?ki.create(Ao(t.unwrap())):t instanceof Ei?Ei.create(t.items.map(e=>Ao(e))):t}var nn=class t extends Ze{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)!==ue.object){let u=this._getOrReturnCtx(e);return ae(u,{code:Q.invalid_type,expected:ue.object,received:u.parsedType}),Ie}let{status:n,ctx:i}=this._processInputParams(e),{shape:a,keys:o}=this._getCached(),s=[];if(!(this._def.catchall instanceof ni&&this._def.unknownKeys==="strip"))for(let u in i.data)o.includes(u)||s.push(u);let c=[];for(let u of o){let l=a[u],d=i.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new fn(i,d,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof ni){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of s)c.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(u==="strict")s.length>0&&(ae(i,{code:Q.unrecognized_keys,keys:s}),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 s){let d=i.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new fn(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=>gr.mergeObjectSync(n,u)):gr.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return he.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:he.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:$e.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 Ao(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 a=this.shape[n];for(;a instanceof Mn;)a=a._def.innerType;r[n]=a}return new t({...this._def,shape:()=>r})}keyof(){return KE(Ye.objectKeys(this.shape))}};nn.create=(t,e)=>new nn({shape:()=>t,unknownKeys:"strip",catchall:ni.create(),typeName:$e.ZodObject,...Me(e)});nn.strictCreate=(t,e)=>new nn({shape:()=>t,unknownKeys:"strict",catchall:ni.create(),typeName:$e.ZodObject,...Me(e)});nn.lazycreate=(t,e)=>new nn({shape:t,unknownKeys:"strip",catchall:ni.create(),typeName:$e.ZodObject,...Me(e)});var Uo=class extends Ze{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(a){for(let s of a)if(s.result.status==="valid")return s.result;for(let s of a)if(s.result.status==="dirty")return r.common.issues.push(...s.ctx.common.issues),s.result;let o=a.map(s=>new rn(s.ctx.common.issues));return ae(r,{code:Q.invalid_union,unionErrors:o}),Ie}if(r.common.async)return Promise.all(n.map(async a=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(i);{let a,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"&&!a&&(a={result:l,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(c=>new rn(c));return ae(r,{code:Q.invalid_union,unionErrors:s}),Ie}}get options(){return this._def.options}};Uo.create=(t,e)=>new Uo({options:t,typeName:$e.ZodUnion,...Me(e)});var $i=t=>t instanceof qo?$i(t.schema):t instanceof Dn?$i(t.innerType()):t instanceof Fo?[t.value]:t instanceof Zo?t.options:t instanceof Ho?Ye.objectValues(t.enum):t instanceof Bo?$i(t._def.innerType):t instanceof Do?[void 0]:t instanceof zo?[null]:t instanceof Mn?[void 0,...$i(t.unwrap())]:t instanceof ki?[null,...$i(t.unwrap())]:t instanceof ep||t instanceof Go?$i(t.unwrap()):t instanceof Vo?$i(t._def.innerType):[],Xg=class t extends Ze{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==ue.object)return ae(r,{code:Q.invalid_type,expected:ue.object,received:r.parsedType}),Ie;let n=this.discriminator,i=r.data[n],a=this.optionsMap.get(i);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(ae(r,{code:Q.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Ie)}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 a of r){let o=$i(a.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of o){if(i.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);i.set(s,a)}}return new t({typeName:$e.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...Me(n)})}};function Yg(t,e){let r=wi(t),n=wi(e);if(t===e)return{valid:!0,data:t};if(r===ue.object&&n===ue.object){let i=Ye.objectKeys(e),a=Ye.objectKeys(t).filter(s=>i.indexOf(s)!==-1),o={...t,...e};for(let s of a){let c=Yg(t[s],e[s]);if(!c.valid)return{valid:!1};o[s]=c.data}return{valid:!0,data:o}}else if(r===ue.array&&n===ue.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let a=0;a{if(Wg(a)||Wg(o))return Ie;let s=Yg(a.value,o.value);return s.valid?((Kg(a)||Kg(o))&&r.dirty(),{status:r.value,value:s.data}):(ae(n,{code:Q.invalid_intersection_types}),Ie)};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(([a,o])=>i(a,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}))}};Lo.create=(t,e,r)=>new Lo({left:t,right:e,typeName:$e.ZodIntersection,...Me(r)});var Ei=class t extends Ze{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ue.array)return ae(n,{code:Q.invalid_type,expected:ue.array,received:n.parsedType}),Ie;if(n.data.lengththis._def.items.length&&(ae(n,{code:Q.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let a=[...n.data].map((o,s)=>{let c=this._def.items[s]||this._def.rest;return c?c._parse(new fn(n,o,n.path,s)):null}).filter(o=>!!o);return n.common.async?Promise.all(a).then(o=>gr.mergeArray(r,o)):gr.mergeArray(r,a)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Ei.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ei({items:t,typeName:$e.ZodTuple,rest:null,...Me(e)})};var Qg=class t extends Ze{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!==ue.object)return ae(n,{code:Q.invalid_type,expected:ue.object,received:n.parsedType}),Ie;let i=[],a=this._def.keyType,o=this._def.valueType;for(let s in n.data)i.push({key:a._parse(new fn(n,s,n.path,s)),value:o._parse(new fn(n,n.data[s],n.path,s)),alwaysSet:s in n.data});return n.common.async?gr.mergeObjectAsync(r,i):gr.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Ze?new t({keyType:e,valueType:r,typeName:$e.ZodRecord,...Me(n)}):new t({keyType:Mo.create(),valueType:e,typeName:$e.ZodRecord,...Me(r)})}},Vc=class extends Ze{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!==ue.map)return ae(n,{code:Q.invalid_type,expected:ue.map,received:n.parsedType}),Ie;let i=this._def.keyType,a=this._def.valueType,o=[...n.data.entries()].map(([s,c],u)=>({key:i._parse(new fn(n,s,n.path,[u,"key"])),value:a._parse(new fn(n,c,n.path,[u,"value"]))}));if(n.common.async){let s=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 Ie;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),s.set(u.value,l.value)}return{status:r.value,value:s}})}else{let s=new Map;for(let c of o){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return Ie;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),s.set(u.value,l.value)}return{status:r.value,value:s}}}};Vc.create=(t,e,r)=>new Vc({valueType:e,keyType:t,typeName:$e.ZodMap,...Me(r)});var Gc=class t extends Ze{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ue.set)return ae(n,{code:Q.invalid_type,expected:ue.set,received:n.parsedType}),Ie;let i=this._def;i.minSize!==null&&n.data.sizei.maxSize.value&&(ae(n,{code:Q.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let a=this._def.valueType;function o(c){let u=new Set;for(let l of c){if(l.status==="aborted")return Ie;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let s=[...n.data.values()].map((c,u)=>a._parse(new fn(n,c,n.path,u)));return n.common.async?Promise.all(s).then(c=>o(c)):o(s)}min(e,r){return new t({...this._def,minSize:{value:e,message:he.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:he.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Gc.create=(t,e)=>new Gc({valueType:t,minSize:null,maxSize:null,typeName:$e.ZodSet,...Me(e)});var ev=class t extends Ze{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==ue.function)return ae(r,{code:Q.invalid_type,expected:ue.function,received:r.parsedType}),Ie;function n(s,c){return Qd({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Dc(),Ji].filter(u=>!!u),issueData:{code:Q.invalid_arguments,argumentsError:c}})}function i(s,c){return Qd({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Dc(),Ji].filter(u=>!!u),issueData:{code:Q.invalid_return_type,returnTypeError:c}})}let a={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof Ma){let s=this;return Tr(async function(...c){let u=new rn([]),l=await s._def.args.parseAsync(c,a).catch(f=>{throw u.addIssue(n(c,f)),u}),d=await Reflect.apply(o,this,l);return await s._def.returns._def.type.parseAsync(d,a).catch(f=>{throw u.addIssue(i(d,f)),u})})}else{let s=this;return Tr(function(...c){let u=s._def.args.safeParse(c,a);if(!u.success)throw new rn([n(c,u.error)]);let l=Reflect.apply(o,this,u.data),d=s._def.returns.safeParse(l,a);if(!d.success)throw new rn([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:Ei.create(e).rest(Xi.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||Ei.create([]).rest(Xi.create()),returns:r||Xi.create(),typeName:$e.ZodFunction,...Me(n)})}},qo=class extends Ze{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})}};qo.create=(t,e)=>new qo({getter:t,typeName:$e.ZodLazy,...Me(e)});var Fo=class extends Ze{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return ae(r,{received:r.data,code:Q.invalid_literal,expected:this._def.value}),Ie}return{status:"valid",value:e.data}}get value(){return this._def.value}};Fo.create=(t,e)=>new Fo({value:t,typeName:$e.ZodLiteral,...Me(e)});function KE(t,e){return new Zo({values:t,typeName:$e.ZodEnum,...Me(e)})}var Zo=class t extends Ze{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return ae(r,{expected:Ye.joinValues(n),received:r.parsedType,code:Q.invalid_type}),Ie}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 ae(r,{received:r.data,code:Q.invalid_enum_value,options:n}),Ie}return Tr(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})}};Zo.create=KE;var Ho=class extends Ze{_parse(e){let r=Ye.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==ue.string&&n.parsedType!==ue.number){let i=Ye.objectValues(r);return ae(n,{expected:Ye.joinValues(i),received:n.parsedType,code:Q.invalid_type}),Ie}if(this._cache||(this._cache=new Set(Ye.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=Ye.objectValues(r);return ae(n,{received:n.data,code:Q.invalid_enum_value,options:i}),Ie}return Tr(e.data)}get enum(){return this._def.values}};Ho.create=(t,e)=>new Ho({values:t,typeName:$e.ZodNativeEnum,...Me(e)});var Ma=class extends Ze{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==ue.promise&&r.common.async===!1)return ae(r,{code:Q.invalid_type,expected:ue.promise,received:r.parsedType}),Ie;let n=r.parsedType===ue.promise?r.data:Promise.resolve(r.data);return Tr(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Ma.create=(t,e)=>new Ma({type:t,typeName:$e.ZodPromise,...Me(e)});var Dn=class extends Ze{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===$e.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,a={addIssue:o=>{ae(n,o),o.fatal?r.abort():r.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),i.type==="preprocess"){let o=i.transform(n.data,a);if(n.common.async)return Promise.resolve(o).then(async s=>{if(r.value==="aborted")return Ie;let c=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return c.status==="aborted"?Ie:c.status==="dirty"?jo(c.value):r.value==="dirty"?jo(c.value):c});{if(r.value==="aborted")return Ie;let s=this._def.schema._parseSync({data:o,path:n.path,parent:n});return s.status==="aborted"?Ie:s.status==="dirty"?jo(s.value):r.value==="dirty"?jo(s.value):s}}if(i.type==="refinement"){let o=s=>{let c=i.refinement(s,a);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 s};if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?Ie:(s.status==="dirty"&&r.dirty(),o(s.value),{status:r.value,value:s.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>s.status==="aborted"?Ie:(s.status==="dirty"&&r.dirty(),o(s.value).then(()=>({status:r.value,value:s.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(!Aa(o))return Ie;let s=i.transform(o.value,a);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>Aa(o)?Promise.resolve(i.transform(o.value,a)).then(s=>({status:r.value,value:s})):Ie);Ye.assertNever(i)}};Dn.create=(t,e,r)=>new Dn({schema:t,typeName:$e.ZodEffects,effect:e,...Me(r)});Dn.createWithPreprocess=(t,e,r)=>new Dn({schema:e,effect:{type:"preprocess",transform:t},typeName:$e.ZodEffects,...Me(r)});var Mn=class extends Ze{_parse(e){return this._getType(e)===ue.undefined?Tr(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Mn.create=(t,e)=>new Mn({innerType:t,typeName:$e.ZodOptional,...Me(e)});var ki=class extends Ze{_parse(e){return this._getType(e)===ue.null?Tr(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ki.create=(t,e)=>new ki({innerType:t,typeName:$e.ZodNullable,...Me(e)});var Bo=class extends Ze{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===ue.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Bo.create=(t,e)=>new Bo({innerType:t,typeName:$e.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Me(e)});var Vo=class extends Ze{_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 zc(i)?i.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new rn(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new rn(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Vo.create=(t,e)=>new Vo({innerType:t,typeName:$e.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Me(e)});var Wc=class extends Ze{_parse(e){if(this._getType(e)!==ue.nan){let n=this._getOrReturnCtx(e);return ae(n,{code:Q.invalid_type,expected:ue.nan,received:n.parsedType}),Ie}return{status:"valid",value:e.data}}};Wc.create=t=>new Wc({typeName:$e.ZodNaN,...Me(t)});var ep=class extends Ze{_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}},tp=class t extends Ze{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?Ie:a.status==="dirty"?(r.dirty(),jo(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?Ie: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:$e.ZodPipeline})}},Go=class extends Ze{_parse(e){let r=this._def.innerType._parse(e),n=i=>(Aa(i)&&(i.value=Object.freeze(i.value)),i);return zc(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};Go.create=(t,e)=>new Go({innerType:t,typeName:$e.ZodReadonly,...Me(e)});var whe={object:nn.lazycreate},$e;(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"})($e||($e={}));var $he=Mo.create,Ehe=Uc.create,khe=Wc.create,The=Lc.create,Ihe=qc.create,Phe=Fc.create,Ohe=Zc.create,Rhe=Do.create,Che=zo.create,Nhe=Hc.create,jhe=Xi.create,Ahe=ni.create,Mhe=Bc.create,Dhe=Yi.create,Zq=nn.create,zhe=nn.strictCreate,Uhe=Uo.create,Lhe=Xg.create,qhe=Lo.create,Fhe=Ei.create,Zhe=Qg.create,Hhe=Vc.create,Bhe=Gc.create,Vhe=ev.create,Ghe=qo.create,Whe=Fo.create,Khe=Zo.create,Jhe=Ho.create,Xhe=Ma.create,Yhe=Dn.create,Qhe=Mn.create,ege=ki.create,tge=Dn.createWithPreprocess,rge=tp.create;var JE=Object.freeze({status:"aborted"});function q(t,e,r){function n(s,c){if(s._zod||Object.defineProperty(s,"_zod",{value:{def:c,constr:o,traits:new Set},enumerable:!1}),s._zod.traits.has(t))return;s._zod.traits.add(t),e(s,c);let u=o.prototype,l=Object.keys(u);for(let d=0;dr?.Parent&&s instanceof r.Parent?!0:s?._zod?.traits?.has(t)}),Object.defineProperty(o,"name",{value:t}),o}var ii=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Da=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}},rp={};function rr(t){return t&&Object.assign(rp,t),rp}var ee={};pn(ee,{BIGINT_FORMAT_RANGES:()=>uv,Class:()=>rv,NUMBER_FORMAT_RANGES:()=>cv,aborted:()=>ra,allowsEval:()=>av,assert:()=>Jq,assertEqual:()=>Vq,assertIs:()=>Wq,assertNever:()=>Kq,assertNotEqual:()=>Gq,assignProp:()=>ea,base64ToUint8Array:()=>QE,base64urlToUint8Array:()=>f9,cached:()=>Ko,captureStackTrace:()=>ip,cleanEnum:()=>p9,cleanRegex:()=>Xc,clone:()=>Ir,cloneDef:()=>Yq,createTransparentProxy:()=>i9,defineLazy:()=>qe,esc:()=>np,escapeRegex:()=>mn,extend:()=>s9,finalizeIssue:()=>Ur,floatSafeRemainder:()=>nv,getElementAtPath:()=>Qq,getEnumValues:()=>Jc,getLengthableOrigin:()=>eu,getParsedType:()=>n9,getSizableOrigin:()=>Qc,hexToUint8Array:()=>h9,isObject:()=>za,isPlainObject:()=>ta,issue:()=>Jo,joinValues:()=>Ee,jsonStringifyReplacer:()=>Wo,merge:()=>u9,mergeDefs:()=>Ti,normalizeParams:()=>oe,nullish:()=>Qi,numKeys:()=>r9,objectClone:()=>Xq,omit:()=>o9,optionalKeys:()=>sv,parsedType:()=>Pe,partial:()=>l9,pick:()=>a9,prefixIssues:()=>an,primitiveTypes:()=>ov,promiseAllObject:()=>e9,propertyKeyTypes:()=>Yc,randomString:()=>t9,required:()=>d9,safeExtend:()=>c9,shallowClone:()=>YE,slugify:()=>iv,stringifyPrimitive:()=>ke,uint8ArrayToBase64:()=>ek,uint8ArrayToBase64url:()=>m9,uint8ArrayToHex:()=>g9,unwrapMessage:()=>Kc});function Vq(t){return t}function Gq(t){return t}function Wq(t){}function Kq(t){throw new Error("Unexpected value in exhaustive check")}function Jq(t){}function Jc(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 Ee(t,e="|"){return t.map(r=>ke(r)).join(e)}function Wo(t,e){return typeof e=="bigint"?e.toString():e}function Ko(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Qi(t){return t==null}function Xc(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function nv(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 a=r>i?r:i,o=Number.parseInt(t.toFixed(a).replace(".","")),s=Number.parseInt(e.toFixed(a).replace(".",""));return o%s/10**a}var XE=Symbol("evaluating");function qe(t,e,r){let n;Object.defineProperty(t,e,{get(){if(n!==XE)return n===void 0&&(n=XE,n=r()),n},set(i){Object.defineProperty(t,e,{value:i})},configurable:!0})}function Xq(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function ea(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Ti(...t){let e={};for(let r of t){let n=Object.getOwnPropertyDescriptors(r);Object.assign(e,n)}return Object.defineProperties({},e)}function Yq(t){return Ti(t._zod.def)}function Qq(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function e9(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let i={};for(let a=0;a{};function za(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var av=Ko(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function ta(t){if(za(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(za(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function YE(t){return ta(t)?{...t}:Array.isArray(t)?[...t]:t}function r9(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var n9=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}`)}},Yc=new Set(["string","number","symbol"]),ov=new Set(["string","number","bigint","boolean","symbol","undefined"]);function mn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ir(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function oe(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 i9(t){let e;return new Proxy({},{get(r,n,i){return e??(e=t()),Reflect.get(e,n,i)},set(r,n,i,a){return e??(e=t()),Reflect.set(e,n,i,a)},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 ke(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function sv(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var cv={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]},uv={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function a9(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 a=Ti(t._zod.def,{get shape(){let o={};for(let s in e){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(o[s]=r.shape[s])}return ea(this,"shape",o),o},checks:[]});return Ir(t,a)}function o9(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 a=Ti(t._zod.def,{get shape(){let o={...t._zod.def.shape};for(let s in e){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete o[s]}return ea(this,"shape",o),o},checks:[]});return Ir(t,a)}function s9(t,e){if(!ta(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0){let a=t._zod.def.shape;for(let o in e)if(Object.getOwnPropertyDescriptor(a,o)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let i=Ti(t._zod.def,{get shape(){let a={...t._zod.def.shape,...e};return ea(this,"shape",a),a}});return Ir(t,i)}function c9(t,e){if(!ta(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=Ti(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e};return ea(this,"shape",n),n}});return Ir(t,r)}function u9(t,e){let r=Ti(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return ea(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:[]});return Ir(t,r)}function l9(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=Ti(e._zod.def,{get shape(){let s=e._zod.def.shape,c={...s};if(r)for(let u in r){if(!(u in s))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(c[u]=t?new t({type:"optional",innerType:s[u]}):s[u])}else for(let u in s)c[u]=t?new t({type:"optional",innerType:s[u]}):s[u];return ea(this,"shape",c),c},checks:[]});return Ir(e,o)}function d9(t,e,r){let n=Ti(e._zod.def,{get shape(){let i=e._zod.def.shape,a={...i};if(r)for(let o in r){if(!(o in a))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(a[o]=new t({type:"nonoptional",innerType:i[o]}))}else for(let o in i)a[o]=new t({type:"nonoptional",innerType:i[o]});return ea(this,"shape",a),a}});return Ir(e,n)}function ra(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 Kc(t){return typeof t=="string"?t:t?.message}function Ur(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let i=Kc(t.inst?._zod.def?.error?.(t))??Kc(e?.error?.(t))??Kc(r.customError?.(t))??Kc(r.localeError?.(t))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Qc(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function eu(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Pe(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 Jo(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function p9(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function QE(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;ne.toString(16).padStart(2,"0")).join("")}var rv=class{constructor(...e){}};var tk=(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,Wo,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ap=q("$ZodError",tk),tu=q("$ZodError",tk,{Parent:Error});function op(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 sp(t,e=r=>r.message){let r={_errors:[]},n=i=>{for(let a of i.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(o=>n({issues:o}));else if(a.code==="invalid_key")n({issues:a.issues});else if(a.code==="invalid_element")n({issues:a.issues});else if(a.path.length===0)r._errors.push(e(a));else{let o=r,s=0;for(;s(e,r,n,i)=>{let a=n?Object.assign(n,{async:!1}):{async:!1},o=e._zod.run({value:r,issues:[]},a);if(o instanceof Promise)throw new ii;if(o.issues.length){let s=new(i?.Err??t)(o.issues.map(c=>Ur(c,a,rr())));throw ip(s,i?.callee),s}return o.value},nu=ru(tu),iu=t=>async(e,r,n,i)=>{let a=n?Object.assign(n,{async:!0}):{async:!0},o=e._zod.run({value:r,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let s=new(i?.Err??t)(o.issues.map(c=>Ur(c,a,rr())));throw ip(s,i?.callee),s}return o.value},au=iu(tu),ou=t=>(e,r,n)=>{let i=n?{...n,async:!1}:{async:!1},a=e._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new ii;return a.issues.length?{success:!1,error:new(t??ap)(a.issues.map(o=>Ur(o,i,rr())))}:{success:!0,data:a.value}},Xo=ou(tu),su=t=>async(e,r,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},a=e._zod.run({value:r,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new t(a.issues.map(o=>Ur(o,i,rr())))}:{success:!0,data:a.value}},cu=su(tu),rk=t=>(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return ru(t)(e,r,i)};var nk=t=>(e,r,n)=>ru(t)(e,r,n);var ik=t=>async(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return iu(t)(e,r,i)};var ak=t=>async(e,r,n)=>iu(t)(e,r,n);var ok=t=>(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return ou(t)(e,r,i)};var sk=t=>(e,r,n)=>ou(t)(e,r,n);var ck=t=>async(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return su(t)(e,r,i)};var uk=t=>async(e,r,n)=>su(t)(e,r,n);var hn={};pn(hn,{base64:()=>Ev,base64url:()=>cp,bigint:()=>Rv,boolean:()=>Nv,browserEmail:()=>E9,cidrv4:()=>wv,cidrv6:()=>$v,cuid:()=>lv,cuid2:()=>dv,date:()=>Tv,datetime:()=>Pv,domain:()=>I9,duration:()=>gv,e164:()=>kv,email:()=>yv,emoji:()=>_v,extendedDuration:()=>y9,guid:()=>vv,hex:()=>P9,hostname:()=>T9,html5Email:()=>S9,idnEmail:()=>$9,integer:()=>Cv,ipv4:()=>bv,ipv6:()=>xv,ksuid:()=>mv,lowercase:()=>Mv,mac:()=>Sv,md5_base64:()=>R9,md5_base64url:()=>C9,md5_hex:()=>O9,nanoid:()=>hv,null:()=>jv,number:()=>up,rfc5322Email:()=>w9,sha1_base64:()=>j9,sha1_base64url:()=>A9,sha1_hex:()=>N9,sha256_base64:()=>D9,sha256_base64url:()=>z9,sha256_hex:()=>M9,sha384_base64:()=>L9,sha384_base64url:()=>q9,sha384_hex:()=>U9,sha512_base64:()=>Z9,sha512_base64url:()=>H9,sha512_hex:()=>F9,string:()=>Ov,time:()=>Iv,ulid:()=>pv,undefined:()=>Av,unicodeEmail:()=>lk,uppercase:()=>Dv,uuid:()=>Ua,uuid4:()=>_9,uuid6:()=>b9,uuid7:()=>x9,xid:()=>fv});var lv=/^[cC][^\s-]{8,}$/,dv=/^[0-9a-z]+$/,pv=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,fv=/^[0-9a-vA-V]{20}$/,mv=/^[A-Za-z0-9]{27}$/,hv=/^[a-zA-Z0-9_-]{21}$/,gv=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,y9=/^[-+]?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)?)??$/,vv=/^([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})$/,Ua=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)$/,_9=Ua(4),b9=Ua(6),x9=Ua(7),yv=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,S9=/^[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])?)*$/,w9=/^(([^<>()\[\]\\.,;:\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,}))$/,lk=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,$9=lk,E9=/^[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])?)*$/,k9="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function _v(){return new RegExp(k9,"u")}var bv=/^(?:(?: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])$/,xv=/^(([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}|:))$/,Sv=t=>{let e=mn(t??":");return new RegExp(`^(?:[0-9A-F]{2}${e}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${e}){5}[0-9a-f]{2}$`)},wv=/^((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])$/,$v=/^(([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])$/,Ev=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,cp=/^[A-Za-z0-9_-]*$/,T9=/^(?=.{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])?)*\.?$/,I9=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,kv=/^\+[1-9]\d{6,14}$/,dk="(?:(?:\\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])))",Tv=new RegExp(`^${dk}$`);function pk(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 Iv(t){return new RegExp(`^${pk(t)}$`)}function Pv(t){let e=pk({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(`^${dk}T(?:${n})$`)}var Ov=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Rv=/^-?\d+n?$/,Cv=/^-?\d+$/,up=/^-?\d+(?:\.\d+)?$/,Nv=/^(?:true|false)$/i,jv=/^null$/i;var Av=/^undefined$/i;var Mv=/^[^A-Z]*$/,Dv=/^[^a-z]*$/,P9=/^[0-9a-fA-F]*$/;function uu(t,e){return new RegExp(`^[A-Za-z0-9+/]{${t}}${e}$`)}function lu(t){return new RegExp(`^[A-Za-z0-9_-]{${t}}$`)}var O9=/^[0-9a-fA-F]{32}$/,R9=uu(22,"=="),C9=lu(22),N9=/^[0-9a-fA-F]{40}$/,j9=uu(27,"="),A9=lu(27),M9=/^[0-9a-fA-F]{64}$/,D9=uu(43,"="),z9=lu(43),U9=/^[0-9a-fA-F]{96}$/,L9=uu(64,""),q9=lu(64),F9=/^[0-9a-fA-F]{128}$/,Z9=uu(86,"=="),H9=lu(86);var $t=q("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),mk={number:"number",bigint:"bigint",object:"date"},zv=q("$ZodCheckLessThan",(t,e)=>{$t.init(t,e);let r=mk[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,a=(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=mk[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,a=(e.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>a&&(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})}}),hk=q("$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):nv(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})}}),gk=q("$ZodCheckNumberFormat",(t,e)=>{$t.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[i,a]=cv[e.format];t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,s.minimum=i,s.maximum=a,r&&(s.pattern=Cv)}),t._zod.check=o=>{let s=o.value;if(r){if(!Number.isInteger(s)){o.issues.push({expected:n,format:e.format,code:"invalid_type",continue:!1,input:s,inst:t});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,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:s,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}}sa&&o.issues.push({origin:"number",input:s,code:"too_big",maximum:a,inclusive:!0,inst:t,continue:!e.abort})}}),vk=q("$ZodCheckBigIntFormat",(t,e)=>{$t.init(t,e);let[r,n]=uv[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=r,a.maximum=n}),t._zod.check=i=>{let a=i.value;an&&i.issues.push({origin:"bigint",input:a,code:"too_big",maximum:n,inclusive:!0,inst:t,continue:!e.abort})}}),yk=q("$ZodCheckMaxSize",(t,e)=>{var r;$t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Qi(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:Qc(i),code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),_k=q("$ZodCheckMinSize",(t,e)=>{var r;$t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Qi(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:Qc(i),code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),bk=q("$ZodCheckSizeEquals",(t,e)=>{var r;$t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Qi(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,a=i.size;if(a===e.size)return;let o=a>e.size;n.issues.push({origin:Qc(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})}}),xk=q("$ZodCheckMaxLength",(t,e)=>{var r;$t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Qi(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=eu(i);n.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),Sk=q("$ZodCheckMinLength",(t,e)=>{var r;$t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Qi(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=eu(i);n.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),wk=q("$ZodCheckLengthEquals",(t,e)=>{var r;$t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Qi(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,a=i.length;if(a===e.length)return;let o=eu(i),s=a>e.length;n.issues.push({origin:o,...s?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),du=q("$ZodCheckStringFormat",(t,e)=>{var r,n;$t.init(t,e),t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,e.pattern&&(a.patterns??(a.patterns=new Set),a.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=()=>{})}),$k=q("$ZodCheckRegex",(t,e)=>{du.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})}}),Ek=q("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Mv),du.init(t,e)}),kk=q("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Dv),du.init(t,e)}),Tk=q("$ZodCheckIncludes",(t,e)=>{$t.init(t,e);let r=mn(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(i=>{let a=i._zod.bag;a.patterns??(a.patterns=new Set),a.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})}}),Ik=q("$ZodCheckStartsWith",(t,e)=>{$t.init(t,e);let r=new RegExp(`^${mn(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})}}),Pk=q("$ZodCheckEndsWith",(t,e)=>{$t.init(t,e);let r=new RegExp(`.*${mn(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 fk(t,e,r){t.issues.length&&e.issues.push(...an(r,t.issues))}var Ok=q("$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=>fk(i,r,e.property));fk(n,r,e.property)}}),Rk=q("$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})}}),Ck=q("$ZodCheckOverwrite",(t,e)=>{$t.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var lp=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(` +`),{exitCode:bl.USER_MESSAGE_ONLY}}}});var FE,ZE=Le(()=>{"use strict";Hr();we();FE={async execute(t){await Sn();let{sessionId:e,cwd:r,filePath:n,edits:i}=t;if(!n)throw new Error("fileEditHandler requires filePath");let a=It();if(E.dataIn("HOOK",`FileEdit: ${n}`,{workerPort:a,editCount:i?.length??0}),!r)throw new Error(`Missing cwd in FileEdit hook input for session ${e}, file ${n}`);let o=await fetch(`http://127.0.0.1:${a}/api/sessions/observations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentSessionId:e,tool_name:"write_file",tool_input:{filePath:n,edits:i},tool_response:{success:!0},cwd:r})});if(!o.ok)throw new Error(`File edit observation storage failed: ${o.status}`);return E.debug("HOOK","File edit observation sent successfully",{filePath:n}),{continue:!0,suppressOutput:!0}}}});function cq(t){let e=Yme[t];if(!e)throw new Error(`Unknown event type: ${t}`);return e}var Yme,uq=Le(()=>{"use strict";NE();AE();DE();UE();qE();ZE();NE();AE();DE();UE();qE();ZE();Yme={context:CE,"session-init":jE,observation:ME,summarize:zE,"user-message":LE,"file-edit":FE}});var lq={};pn(lq,{hookCommand:()=>Qme});async function Qme(t,e){try{let r=nq(t),n=cq(e),i=await KL(),a=r.normalizeInput(i);a.platform=t;let o=await n.execute(a),s=r.formatOutput(o);console.log(JSON.stringify(s)),process.exit(o.exitCode??bl.SUCCESS)}catch(r){console.error(`Hook error: ${r}`),process.exit(bl.BLOCKING_ERROR)}}var dq=Le(()=>{"use strict";JL();iq();uq();xl()});var nhe={};pn(nhe,{WorkerService:()=>Vg,buildStatusOutput:()=>fq});module.exports=Yd(nhe);var pq=ut(require("path"),1);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 a={};for(let o of i)a[o]=o;return a},t.getValidEnumValues=i=>{let a=t.objectKeys(i).filter(s=>typeof i[i[s]]!="number"),o={};for(let s of a)o[s]=i[s];return t.objectValues(o)},t.objectValues=i=>t.objectKeys(i).map(function(a){return i[a]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let a=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&a.push(o);return a},t.find=(i,a)=>{for(let o of i)if(a(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,a=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(a)}t.joinValues=n,t.jsonStringifyReplacer=(i,a)=>typeof a=="bigint"?a.toString():a})(Ye||(Ye={}));var BE;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(BE||(BE={}));var ue=Ye.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),wi=t=>{switch(typeof t){case"undefined":return ue.undefined;case"string":return ue.string;case"number":return Number.isNaN(t)?ue.nan:ue.number;case"boolean":return ue.boolean;case"function":return ue.function;case"bigint":return ue.bigint;case"symbol":return ue.symbol;case"object":return Array.isArray(t)?ue.array:t===null?ue.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?ue.promise:typeof Map<"u"&&t instanceof Map?ue.map:typeof Set<"u"&&t instanceof Set?ue.set:typeof Date<"u"&&t instanceof Date?ue.date:ue.object;default:return ue.unknown}};var Q=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 tn=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(a){return a.message},n={_errors:[]},i=a=>{for(let o of a.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 s=n,c=0;for(;cr.message){let r=Object.create(null),n=[];for(let i of this.issues)if(i.path.length>0){let a=i.path[0];r[a]=r[a]||[],r[a].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};tn.create=t=>new tn(t);var _q=(t,e)=>{let r;switch(t.code){case Q.invalid_type:t.received===ue.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case Q.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Ye.jsonStringifyReplacer)}`;break;case Q.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ye.joinValues(t.keys,", ")}`;break;case Q.invalid_union:r="Invalid input";break;case Q.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ye.joinValues(t.options)}`;break;case Q.invalid_enum_value:r=`Invalid enum value. Expected ${Ye.joinValues(t.options)}, received '${t.received}'`;break;case Q.invalid_arguments:r="Invalid function arguments";break;case Q.invalid_return_type:r="Invalid function return type";break;case Q.invalid_date:r="Invalid date";break;case Q.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 Q.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 Q.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 Q.custom:r="Invalid input";break;case Q.invalid_intersection_types:r="Intersection results could not be merged";break;case Q.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case Q.not_finite:r="Number must be finite";break;default:r=e.defaultError,Ye.assertNever(t)}return{message:r}},Ji=_q;var bq=Ji;function Dc(){return bq}var Qd=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,a=[...r,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)s=u(o,{data:e,defaultError:s}).message;return{...i,path:a,message:s}};function ae(t,e){let r=Dc(),n=Qd({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ji?void 0:Ji].filter(i=>!!i)});t.common.issues.push(n)}var gr=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 Ie;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 a=await i.key,o=await i.value;n.push({key:a,value:o})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:a,value:o}=i;if(a.status==="aborted"||o.status==="aborted")return Ie;a.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(n[a.value]=o.value)}return{status:e.value,value:n}}},Ie=Object.freeze({status:"aborted"}),jo=t=>({status:"dirty",value:t}),Tr=t=>({status:"valid",value:t}),Wg=t=>t.status==="aborted",Kg=t=>t.status==="dirty",Aa=t=>t.status==="valid",zc=t=>typeof Promise<"u"&&t instanceof Promise;var he;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(he||(he={}));var fn=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}},VE=(t,e)=>{if(Aa(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 tn(t.common.issues);return this._error=r,this._error}}};function Me(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,s)=>{let{message:c}=t;return o.code==="invalid_enum_value"?{message:c??s.defaultError}:typeof s.data>"u"?{message:c??n??s.defaultError}:o.code!=="invalid_type"?{message:s.defaultError}:{message:c??r??s.defaultError}},description:i}}var Ze=class{get description(){return this._def.description}_getType(e){return wi(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:wi(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new gr,ctx:{common:e.parent.common,data:e.data,parsedType:wi(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(zc(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:wi(e)},i=this._parseSync({data:e,path:n.path,parent:n});return VE(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:wi(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Aa(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=>Aa(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:wi(e)},i=this._parse({data:e,path:n.path,parent:n}),a=await(zc(i)?i:Promise.resolve(i));return VE(n,a)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,a)=>{let o=e(i),s=()=>a.addIssue({code:Q.custom,...n(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(s(),!1)):o?!0:(s(),!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 Dn({schema:this,typeName:$e.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 Mn.create(this,this._def)}nullable(){return ki.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yi.create(this)}promise(){return Ma.create(this,this._def)}or(e){return Uo.create([this,e],this._def)}and(e){return Lo.create(this,e,this._def)}transform(e){return new Dn({...Me(this._def),schema:this,typeName:$e.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Bo({...Me(this._def),innerType:this,defaultValue:r,typeName:$e.ZodDefault})}brand(){return new ep({typeName:$e.ZodBranded,type:this,...Me(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Vo({...Me(this._def),innerType:this,catchValue:r,typeName:$e.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return tp.create(this,e)}readonly(){return Go.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},xq=/^c[^\s-]{8,}$/i,Sq=/^[0-9a-z]+$/,wq=/^[0-9A-HJKMNP-TV-Z]{26}$/i,$q=/^[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,Eq=/^[a-z0-9_-]{21}$/i,kq=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Tq=/^[-+]?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)?)??$/,Iq=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Pq="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Jg,Oq=/^(?:(?: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])$/,Rq=/^(?:(?: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])$/,Cq=/^(([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]))$/,Nq=/^(([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])$/,jq=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Aq=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,GE="((\\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])))",Mq=new RegExp(`^${GE}$`);function WE(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 Dq(t){return new RegExp(`^${WE(t)}$`)}function zq(t){let e=`${GE}T${WE(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 Uq(t,e){return!!((e==="v4"||!e)&&Oq.test(t)||(e==="v6"||!e)&&Cq.test(t))}function Lq(t,e){if(!kq.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 qq(t,e){return!!((e==="v4"||!e)&&Rq.test(t)||(e==="v6"||!e)&&Nq.test(t))}var Mo=class t extends Ze{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ue.string){let a=this._getOrReturnCtx(e);return ae(a,{code:Q.invalid_type,expected:ue.string,received:a.parsedType}),Ie}let n=new gr,i;for(let a of this._def.checks)if(a.kind==="min")e.data.lengtha.value&&(i=this._getOrReturnCtx(e,i),ae(i,{code:Q.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){let o=e.data.length>a.value,s=e.data.lengthe.test(i),{validation:r,code:Q.invalid_string,...he.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...he.errToObj(e)})}url(e){return this._addCheck({kind:"url",...he.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...he.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...he.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...he.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...he.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...he.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...he.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...he.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...he.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...he.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...he.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...he.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,...he.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,...he.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...he.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...he.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...he.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...he.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...he.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...he.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...he.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...he.errToObj(r)})}nonempty(e){return this.min(1,he.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 Mo({checks:[],typeName:$e.ZodString,coerce:t?.coerce??!1,...Me(t)});function Fq(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,a=Number.parseInt(t.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return a%o/10**i}var Uc=class t extends Ze{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)!==ue.number){let a=this._getOrReturnCtx(e);return ae(a,{code:Q.invalid_type,expected:ue.number,received:a.parsedType}),Ie}let n,i=new gr;for(let a of this._def.checks)a.kind==="int"?Ye.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{code:Q.invalid_type,expected:"integer",received:"float",message:a.message}),i.dirty()):a.kind==="min"?(a.inclusive?e.dataa.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),ae(n,{code:Q.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="multipleOf"?Fq(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),ae(n,{code:Q.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{code:Q.not_finite,message:a.message}),i.dirty()):Ye.assertNever(a);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,he.toString(r))}gt(e,r){return this.setLimit("min",e,!1,he.toString(r))}lte(e,r){return this.setLimit("max",e,!0,he.toString(r))}lt(e,r){return this.setLimit("max",e,!1,he.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:he.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:he.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:he.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:he.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:he.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:he.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:he.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:he.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:he.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:he.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 Uc({checks:[],typeName:$e.ZodNumber,coerce:t?.coerce||!1,...Me(t)});var Lc=class t extends Ze{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)!==ue.bigint)return this._getInvalidInput(e);let n,i=new gr;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.dataa.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),ae(n,{code:Q.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),ae(n,{code:Q.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):Ye.assertNever(a);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return ae(r,{code:Q.invalid_type,expected:ue.bigint,received:r.parsedType}),Ie}gte(e,r){return this.setLimit("min",e,!0,he.toString(r))}gt(e,r){return this.setLimit("min",e,!1,he.toString(r))}lte(e,r){return this.setLimit("max",e,!0,he.toString(r))}lt(e,r){return this.setLimit("max",e,!1,he.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:he.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:he.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:he.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:he.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:he.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:he.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 Lc({checks:[],typeName:$e.ZodBigInt,coerce:t?.coerce??!1,...Me(t)});var qc=class extends Ze{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ue.boolean){let n=this._getOrReturnCtx(e);return ae(n,{code:Q.invalid_type,expected:ue.boolean,received:n.parsedType}),Ie}return Tr(e.data)}};qc.create=t=>new qc({typeName:$e.ZodBoolean,coerce:t?.coerce||!1,...Me(t)});var Fc=class t extends Ze{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ue.date){let a=this._getOrReturnCtx(e);return ae(a,{code:Q.invalid_type,expected:ue.date,received:a.parsedType}),Ie}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return ae(a,{code:Q.invalid_date}),Ie}let n=new gr,i;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()a.value&&(i=this._getOrReturnCtx(e,i),ae(i,{code:Q.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):Ye.assertNever(a);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:he.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:he.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 Fc({checks:[],coerce:t?.coerce||!1,typeName:$e.ZodDate,...Me(t)});var Zc=class extends Ze{_parse(e){if(this._getType(e)!==ue.symbol){let n=this._getOrReturnCtx(e);return ae(n,{code:Q.invalid_type,expected:ue.symbol,received:n.parsedType}),Ie}return Tr(e.data)}};Zc.create=t=>new Zc({typeName:$e.ZodSymbol,...Me(t)});var Do=class extends Ze{_parse(e){if(this._getType(e)!==ue.undefined){let n=this._getOrReturnCtx(e);return ae(n,{code:Q.invalid_type,expected:ue.undefined,received:n.parsedType}),Ie}return Tr(e.data)}};Do.create=t=>new Do({typeName:$e.ZodUndefined,...Me(t)});var zo=class extends Ze{_parse(e){if(this._getType(e)!==ue.null){let n=this._getOrReturnCtx(e);return ae(n,{code:Q.invalid_type,expected:ue.null,received:n.parsedType}),Ie}return Tr(e.data)}};zo.create=t=>new zo({typeName:$e.ZodNull,...Me(t)});var Hc=class extends Ze{constructor(){super(...arguments),this._any=!0}_parse(e){return Tr(e.data)}};Hc.create=t=>new Hc({typeName:$e.ZodAny,...Me(t)});var Xi=class extends Ze{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Tr(e.data)}};Xi.create=t=>new Xi({typeName:$e.ZodUnknown,...Me(t)});var ni=class extends Ze{_parse(e){let r=this._getOrReturnCtx(e);return ae(r,{code:Q.invalid_type,expected:ue.never,received:r.parsedType}),Ie}};ni.create=t=>new ni({typeName:$e.ZodNever,...Me(t)});var Bc=class extends Ze{_parse(e){if(this._getType(e)!==ue.undefined){let n=this._getOrReturnCtx(e);return ae(n,{code:Q.invalid_type,expected:ue.void,received:n.parsedType}),Ie}return Tr(e.data)}};Bc.create=t=>new Bc({typeName:$e.ZodVoid,...Me(t)});var Yi=class t extends Ze{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==ue.array)return ae(r,{code:Q.invalid_type,expected:ue.array,received:r.parsedType}),Ie;if(i.exactLength!==null){let o=r.data.length>i.exactLength.value,s=r.data.lengthi.maxLength.value&&(ae(r,{code:Q.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,s)=>i.type._parseAsync(new fn(r,o,r.path,s)))).then(o=>gr.mergeArray(n,o));let a=[...r.data].map((o,s)=>i.type._parseSync(new fn(r,o,r.path,s)));return gr.mergeArray(n,a)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:he.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:he.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:he.toString(r)}})}nonempty(e){return this.min(1,e)}};Yi.create=(t,e)=>new Yi({type:t,minLength:null,maxLength:null,exactLength:null,typeName:$e.ZodArray,...Me(e)});function Ao(t){if(t instanceof rn){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Mn.create(Ao(n))}return new rn({...t._def,shape:()=>e})}else return t instanceof Yi?new Yi({...t._def,type:Ao(t.element)}):t instanceof Mn?Mn.create(Ao(t.unwrap())):t instanceof ki?ki.create(Ao(t.unwrap())):t instanceof Ei?Ei.create(t.items.map(e=>Ao(e))):t}var rn=class t extends Ze{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)!==ue.object){let u=this._getOrReturnCtx(e);return ae(u,{code:Q.invalid_type,expected:ue.object,received:u.parsedType}),Ie}let{status:n,ctx:i}=this._processInputParams(e),{shape:a,keys:o}=this._getCached(),s=[];if(!(this._def.catchall instanceof ni&&this._def.unknownKeys==="strip"))for(let u in i.data)o.includes(u)||s.push(u);let c=[];for(let u of o){let l=a[u],d=i.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new fn(i,d,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof ni){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of s)c.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(u==="strict")s.length>0&&(ae(i,{code:Q.unrecognized_keys,keys:s}),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 s){let d=i.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new fn(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=>gr.mergeObjectSync(n,u)):gr.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return he.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:he.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:$e.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 Ao(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 a=this.shape[n];for(;a instanceof Mn;)a=a._def.innerType;r[n]=a}return new t({...this._def,shape:()=>r})}keyof(){return KE(Ye.objectKeys(this.shape))}};rn.create=(t,e)=>new rn({shape:()=>t,unknownKeys:"strip",catchall:ni.create(),typeName:$e.ZodObject,...Me(e)});rn.strictCreate=(t,e)=>new rn({shape:()=>t,unknownKeys:"strict",catchall:ni.create(),typeName:$e.ZodObject,...Me(e)});rn.lazycreate=(t,e)=>new rn({shape:t,unknownKeys:"strip",catchall:ni.create(),typeName:$e.ZodObject,...Me(e)});var Uo=class extends Ze{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(a){for(let s of a)if(s.result.status==="valid")return s.result;for(let s of a)if(s.result.status==="dirty")return r.common.issues.push(...s.ctx.common.issues),s.result;let o=a.map(s=>new tn(s.ctx.common.issues));return ae(r,{code:Q.invalid_union,unionErrors:o}),Ie}if(r.common.async)return Promise.all(n.map(async a=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(i);{let a,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"&&!a&&(a={result:l,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(c=>new tn(c));return ae(r,{code:Q.invalid_union,unionErrors:s}),Ie}}get options(){return this._def.options}};Uo.create=(t,e)=>new Uo({options:t,typeName:$e.ZodUnion,...Me(e)});var $i=t=>t instanceof qo?$i(t.schema):t instanceof Dn?$i(t.innerType()):t instanceof Fo?[t.value]:t instanceof Zo?t.options:t instanceof Ho?Ye.objectValues(t.enum):t instanceof Bo?$i(t._def.innerType):t instanceof Do?[void 0]:t instanceof zo?[null]:t instanceof Mn?[void 0,...$i(t.unwrap())]:t instanceof ki?[null,...$i(t.unwrap())]:t instanceof ep||t instanceof Go?$i(t.unwrap()):t instanceof Vo?$i(t._def.innerType):[],Xg=class t extends Ze{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==ue.object)return ae(r,{code:Q.invalid_type,expected:ue.object,received:r.parsedType}),Ie;let n=this.discriminator,i=r.data[n],a=this.optionsMap.get(i);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(ae(r,{code:Q.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Ie)}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 a of r){let o=$i(a.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of o){if(i.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);i.set(s,a)}}return new t({typeName:$e.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...Me(n)})}};function Yg(t,e){let r=wi(t),n=wi(e);if(t===e)return{valid:!0,data:t};if(r===ue.object&&n===ue.object){let i=Ye.objectKeys(e),a=Ye.objectKeys(t).filter(s=>i.indexOf(s)!==-1),o={...t,...e};for(let s of a){let c=Yg(t[s],e[s]);if(!c.valid)return{valid:!1};o[s]=c.data}return{valid:!0,data:o}}else if(r===ue.array&&n===ue.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let a=0;a{if(Wg(a)||Wg(o))return Ie;let s=Yg(a.value,o.value);return s.valid?((Kg(a)||Kg(o))&&r.dirty(),{status:r.value,value:s.data}):(ae(n,{code:Q.invalid_intersection_types}),Ie)};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(([a,o])=>i(a,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}))}};Lo.create=(t,e,r)=>new Lo({left:t,right:e,typeName:$e.ZodIntersection,...Me(r)});var Ei=class t extends Ze{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ue.array)return ae(n,{code:Q.invalid_type,expected:ue.array,received:n.parsedType}),Ie;if(n.data.lengththis._def.items.length&&(ae(n,{code:Q.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let a=[...n.data].map((o,s)=>{let c=this._def.items[s]||this._def.rest;return c?c._parse(new fn(n,o,n.path,s)):null}).filter(o=>!!o);return n.common.async?Promise.all(a).then(o=>gr.mergeArray(r,o)):gr.mergeArray(r,a)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Ei.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ei({items:t,typeName:$e.ZodTuple,rest:null,...Me(e)})};var Qg=class t extends Ze{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!==ue.object)return ae(n,{code:Q.invalid_type,expected:ue.object,received:n.parsedType}),Ie;let i=[],a=this._def.keyType,o=this._def.valueType;for(let s in n.data)i.push({key:a._parse(new fn(n,s,n.path,s)),value:o._parse(new fn(n,n.data[s],n.path,s)),alwaysSet:s in n.data});return n.common.async?gr.mergeObjectAsync(r,i):gr.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Ze?new t({keyType:e,valueType:r,typeName:$e.ZodRecord,...Me(n)}):new t({keyType:Mo.create(),valueType:e,typeName:$e.ZodRecord,...Me(r)})}},Vc=class extends Ze{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!==ue.map)return ae(n,{code:Q.invalid_type,expected:ue.map,received:n.parsedType}),Ie;let i=this._def.keyType,a=this._def.valueType,o=[...n.data.entries()].map(([s,c],u)=>({key:i._parse(new fn(n,s,n.path,[u,"key"])),value:a._parse(new fn(n,c,n.path,[u,"value"]))}));if(n.common.async){let s=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 Ie;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),s.set(u.value,l.value)}return{status:r.value,value:s}})}else{let s=new Map;for(let c of o){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return Ie;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),s.set(u.value,l.value)}return{status:r.value,value:s}}}};Vc.create=(t,e,r)=>new Vc({valueType:e,keyType:t,typeName:$e.ZodMap,...Me(r)});var Gc=class t extends Ze{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ue.set)return ae(n,{code:Q.invalid_type,expected:ue.set,received:n.parsedType}),Ie;let i=this._def;i.minSize!==null&&n.data.sizei.maxSize.value&&(ae(n,{code:Q.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let a=this._def.valueType;function o(c){let u=new Set;for(let l of c){if(l.status==="aborted")return Ie;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let s=[...n.data.values()].map((c,u)=>a._parse(new fn(n,c,n.path,u)));return n.common.async?Promise.all(s).then(c=>o(c)):o(s)}min(e,r){return new t({...this._def,minSize:{value:e,message:he.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:he.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Gc.create=(t,e)=>new Gc({valueType:t,minSize:null,maxSize:null,typeName:$e.ZodSet,...Me(e)});var ev=class t extends Ze{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==ue.function)return ae(r,{code:Q.invalid_type,expected:ue.function,received:r.parsedType}),Ie;function n(s,c){return Qd({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Dc(),Ji].filter(u=>!!u),issueData:{code:Q.invalid_arguments,argumentsError:c}})}function i(s,c){return Qd({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Dc(),Ji].filter(u=>!!u),issueData:{code:Q.invalid_return_type,returnTypeError:c}})}let a={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof Ma){let s=this;return Tr(async function(...c){let u=new tn([]),l=await s._def.args.parseAsync(c,a).catch(f=>{throw u.addIssue(n(c,f)),u}),d=await Reflect.apply(o,this,l);return await s._def.returns._def.type.parseAsync(d,a).catch(f=>{throw u.addIssue(i(d,f)),u})})}else{let s=this;return Tr(function(...c){let u=s._def.args.safeParse(c,a);if(!u.success)throw new tn([n(c,u.error)]);let l=Reflect.apply(o,this,u.data),d=s._def.returns.safeParse(l,a);if(!d.success)throw new tn([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:Ei.create(e).rest(Xi.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||Ei.create([]).rest(Xi.create()),returns:r||Xi.create(),typeName:$e.ZodFunction,...Me(n)})}},qo=class extends Ze{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})}};qo.create=(t,e)=>new qo({getter:t,typeName:$e.ZodLazy,...Me(e)});var Fo=class extends Ze{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return ae(r,{received:r.data,code:Q.invalid_literal,expected:this._def.value}),Ie}return{status:"valid",value:e.data}}get value(){return this._def.value}};Fo.create=(t,e)=>new Fo({value:t,typeName:$e.ZodLiteral,...Me(e)});function KE(t,e){return new Zo({values:t,typeName:$e.ZodEnum,...Me(e)})}var Zo=class t extends Ze{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return ae(r,{expected:Ye.joinValues(n),received:r.parsedType,code:Q.invalid_type}),Ie}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 ae(r,{received:r.data,code:Q.invalid_enum_value,options:n}),Ie}return Tr(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})}};Zo.create=KE;var Ho=class extends Ze{_parse(e){let r=Ye.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==ue.string&&n.parsedType!==ue.number){let i=Ye.objectValues(r);return ae(n,{expected:Ye.joinValues(i),received:n.parsedType,code:Q.invalid_type}),Ie}if(this._cache||(this._cache=new Set(Ye.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=Ye.objectValues(r);return ae(n,{received:n.data,code:Q.invalid_enum_value,options:i}),Ie}return Tr(e.data)}get enum(){return this._def.values}};Ho.create=(t,e)=>new Ho({values:t,typeName:$e.ZodNativeEnum,...Me(e)});var Ma=class extends Ze{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==ue.promise&&r.common.async===!1)return ae(r,{code:Q.invalid_type,expected:ue.promise,received:r.parsedType}),Ie;let n=r.parsedType===ue.promise?r.data:Promise.resolve(r.data);return Tr(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Ma.create=(t,e)=>new Ma({type:t,typeName:$e.ZodPromise,...Me(e)});var Dn=class extends Ze{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===$e.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,a={addIssue:o=>{ae(n,o),o.fatal?r.abort():r.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),i.type==="preprocess"){let o=i.transform(n.data,a);if(n.common.async)return Promise.resolve(o).then(async s=>{if(r.value==="aborted")return Ie;let c=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return c.status==="aborted"?Ie:c.status==="dirty"?jo(c.value):r.value==="dirty"?jo(c.value):c});{if(r.value==="aborted")return Ie;let s=this._def.schema._parseSync({data:o,path:n.path,parent:n});return s.status==="aborted"?Ie:s.status==="dirty"?jo(s.value):r.value==="dirty"?jo(s.value):s}}if(i.type==="refinement"){let o=s=>{let c=i.refinement(s,a);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 s};if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?Ie:(s.status==="dirty"&&r.dirty(),o(s.value),{status:r.value,value:s.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>s.status==="aborted"?Ie:(s.status==="dirty"&&r.dirty(),o(s.value).then(()=>({status:r.value,value:s.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(!Aa(o))return Ie;let s=i.transform(o.value,a);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>Aa(o)?Promise.resolve(i.transform(o.value,a)).then(s=>({status:r.value,value:s})):Ie);Ye.assertNever(i)}};Dn.create=(t,e,r)=>new Dn({schema:t,typeName:$e.ZodEffects,effect:e,...Me(r)});Dn.createWithPreprocess=(t,e,r)=>new Dn({schema:e,effect:{type:"preprocess",transform:t},typeName:$e.ZodEffects,...Me(r)});var Mn=class extends Ze{_parse(e){return this._getType(e)===ue.undefined?Tr(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Mn.create=(t,e)=>new Mn({innerType:t,typeName:$e.ZodOptional,...Me(e)});var ki=class extends Ze{_parse(e){return this._getType(e)===ue.null?Tr(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ki.create=(t,e)=>new ki({innerType:t,typeName:$e.ZodNullable,...Me(e)});var Bo=class extends Ze{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===ue.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Bo.create=(t,e)=>new Bo({innerType:t,typeName:$e.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Me(e)});var Vo=class extends Ze{_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 zc(i)?i.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new tn(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new tn(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Vo.create=(t,e)=>new Vo({innerType:t,typeName:$e.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Me(e)});var Wc=class extends Ze{_parse(e){if(this._getType(e)!==ue.nan){let n=this._getOrReturnCtx(e);return ae(n,{code:Q.invalid_type,expected:ue.nan,received:n.parsedType}),Ie}return{status:"valid",value:e.data}}};Wc.create=t=>new Wc({typeName:$e.ZodNaN,...Me(t)});var ep=class extends Ze{_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}},tp=class t extends Ze{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?Ie:a.status==="dirty"?(r.dirty(),jo(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?Ie: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:$e.ZodPipeline})}},Go=class extends Ze{_parse(e){let r=this._def.innerType._parse(e),n=i=>(Aa(i)&&(i.value=Object.freeze(i.value)),i);return zc(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};Go.create=(t,e)=>new Go({innerType:t,typeName:$e.ZodReadonly,...Me(e)});var whe={object:rn.lazycreate},$e;(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"})($e||($e={}));var $he=Mo.create,Ehe=Uc.create,khe=Wc.create,The=Lc.create,Ihe=qc.create,Phe=Fc.create,Ohe=Zc.create,Rhe=Do.create,Che=zo.create,Nhe=Hc.create,jhe=Xi.create,Ahe=ni.create,Mhe=Bc.create,Dhe=Yi.create,Zq=rn.create,zhe=rn.strictCreate,Uhe=Uo.create,Lhe=Xg.create,qhe=Lo.create,Fhe=Ei.create,Zhe=Qg.create,Hhe=Vc.create,Bhe=Gc.create,Vhe=ev.create,Ghe=qo.create,Whe=Fo.create,Khe=Zo.create,Jhe=Ho.create,Xhe=Ma.create,Yhe=Dn.create,Qhe=Mn.create,ege=ki.create,tge=Dn.createWithPreprocess,rge=tp.create;var JE=Object.freeze({status:"aborted"});function q(t,e,r){function n(s,c){if(s._zod||Object.defineProperty(s,"_zod",{value:{def:c,constr:o,traits:new Set},enumerable:!1}),s._zod.traits.has(t))return;s._zod.traits.add(t),e(s,c);let u=o.prototype,l=Object.keys(u);for(let d=0;dr?.Parent&&s instanceof r.Parent?!0:s?._zod?.traits?.has(t)}),Object.defineProperty(o,"name",{value:t}),o}var ii=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Da=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}},rp={};function rr(t){return t&&Object.assign(rp,t),rp}var ee={};pn(ee,{BIGINT_FORMAT_RANGES:()=>uv,Class:()=>rv,NUMBER_FORMAT_RANGES:()=>cv,aborted:()=>ra,allowsEval:()=>av,assert:()=>Jq,assertEqual:()=>Vq,assertIs:()=>Wq,assertNever:()=>Kq,assertNotEqual:()=>Gq,assignProp:()=>ea,base64ToUint8Array:()=>QE,base64urlToUint8Array:()=>f9,cached:()=>Ko,captureStackTrace:()=>ip,cleanEnum:()=>p9,cleanRegex:()=>Xc,clone:()=>Ir,cloneDef:()=>Yq,createTransparentProxy:()=>i9,defineLazy:()=>qe,esc:()=>np,escapeRegex:()=>mn,extend:()=>s9,finalizeIssue:()=>Ur,floatSafeRemainder:()=>nv,getElementAtPath:()=>Qq,getEnumValues:()=>Jc,getLengthableOrigin:()=>eu,getParsedType:()=>n9,getSizableOrigin:()=>Qc,hexToUint8Array:()=>h9,isObject:()=>za,isPlainObject:()=>ta,issue:()=>Jo,joinValues:()=>Ee,jsonStringifyReplacer:()=>Wo,merge:()=>u9,mergeDefs:()=>Ti,normalizeParams:()=>oe,nullish:()=>Qi,numKeys:()=>r9,objectClone:()=>Xq,omit:()=>o9,optionalKeys:()=>sv,parsedType:()=>Pe,partial:()=>l9,pick:()=>a9,prefixIssues:()=>nn,primitiveTypes:()=>ov,promiseAllObject:()=>e9,propertyKeyTypes:()=>Yc,randomString:()=>t9,required:()=>d9,safeExtend:()=>c9,shallowClone:()=>YE,slugify:()=>iv,stringifyPrimitive:()=>ke,uint8ArrayToBase64:()=>ek,uint8ArrayToBase64url:()=>m9,uint8ArrayToHex:()=>g9,unwrapMessage:()=>Kc});function Vq(t){return t}function Gq(t){return t}function Wq(t){}function Kq(t){throw new Error("Unexpected value in exhaustive check")}function Jq(t){}function Jc(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 Ee(t,e="|"){return t.map(r=>ke(r)).join(e)}function Wo(t,e){return typeof e=="bigint"?e.toString():e}function Ko(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Qi(t){return t==null}function Xc(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function nv(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 a=r>i?r:i,o=Number.parseInt(t.toFixed(a).replace(".","")),s=Number.parseInt(e.toFixed(a).replace(".",""));return o%s/10**a}var XE=Symbol("evaluating");function qe(t,e,r){let n;Object.defineProperty(t,e,{get(){if(n!==XE)return n===void 0&&(n=XE,n=r()),n},set(i){Object.defineProperty(t,e,{value:i})},configurable:!0})}function Xq(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function ea(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Ti(...t){let e={};for(let r of t){let n=Object.getOwnPropertyDescriptors(r);Object.assign(e,n)}return Object.defineProperties({},e)}function Yq(t){return Ti(t._zod.def)}function Qq(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function e9(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let i={};for(let a=0;a{};function za(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var av=Ko(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function ta(t){if(za(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(za(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function YE(t){return ta(t)?{...t}:Array.isArray(t)?[...t]:t}function r9(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var n9=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}`)}},Yc=new Set(["string","number","symbol"]),ov=new Set(["string","number","bigint","boolean","symbol","undefined"]);function mn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ir(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function oe(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 i9(t){let e;return new Proxy({},{get(r,n,i){return e??(e=t()),Reflect.get(e,n,i)},set(r,n,i,a){return e??(e=t()),Reflect.set(e,n,i,a)},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 ke(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function sv(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var cv={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]},uv={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function a9(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 a=Ti(t._zod.def,{get shape(){let o={};for(let s in e){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(o[s]=r.shape[s])}return ea(this,"shape",o),o},checks:[]});return Ir(t,a)}function o9(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 a=Ti(t._zod.def,{get shape(){let o={...t._zod.def.shape};for(let s in e){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete o[s]}return ea(this,"shape",o),o},checks:[]});return Ir(t,a)}function s9(t,e){if(!ta(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0){let a=t._zod.def.shape;for(let o in e)if(Object.getOwnPropertyDescriptor(a,o)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let i=Ti(t._zod.def,{get shape(){let a={...t._zod.def.shape,...e};return ea(this,"shape",a),a}});return Ir(t,i)}function c9(t,e){if(!ta(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=Ti(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e};return ea(this,"shape",n),n}});return Ir(t,r)}function u9(t,e){let r=Ti(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return ea(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:[]});return Ir(t,r)}function l9(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=Ti(e._zod.def,{get shape(){let s=e._zod.def.shape,c={...s};if(r)for(let u in r){if(!(u in s))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(c[u]=t?new t({type:"optional",innerType:s[u]}):s[u])}else for(let u in s)c[u]=t?new t({type:"optional",innerType:s[u]}):s[u];return ea(this,"shape",c),c},checks:[]});return Ir(e,o)}function d9(t,e,r){let n=Ti(e._zod.def,{get shape(){let i=e._zod.def.shape,a={...i};if(r)for(let o in r){if(!(o in a))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(a[o]=new t({type:"nonoptional",innerType:i[o]}))}else for(let o in i)a[o]=new t({type:"nonoptional",innerType:i[o]});return ea(this,"shape",a),a}});return Ir(e,n)}function ra(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 Kc(t){return typeof t=="string"?t:t?.message}function Ur(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let i=Kc(t.inst?._zod.def?.error?.(t))??Kc(e?.error?.(t))??Kc(r.customError?.(t))??Kc(r.localeError?.(t))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Qc(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function eu(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Pe(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 Jo(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function p9(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function QE(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;ne.toString(16).padStart(2,"0")).join("")}var rv=class{constructor(...e){}};var tk=(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,Wo,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ap=q("$ZodError",tk),tu=q("$ZodError",tk,{Parent:Error});function op(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 sp(t,e=r=>r.message){let r={_errors:[]},n=i=>{for(let a of i.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(o=>n({issues:o}));else if(a.code==="invalid_key")n({issues:a.issues});else if(a.code==="invalid_element")n({issues:a.issues});else if(a.path.length===0)r._errors.push(e(a));else{let o=r,s=0;for(;s(e,r,n,i)=>{let a=n?Object.assign(n,{async:!1}):{async:!1},o=e._zod.run({value:r,issues:[]},a);if(o instanceof Promise)throw new ii;if(o.issues.length){let s=new(i?.Err??t)(o.issues.map(c=>Ur(c,a,rr())));throw ip(s,i?.callee),s}return o.value},nu=ru(tu),iu=t=>async(e,r,n,i)=>{let a=n?Object.assign(n,{async:!0}):{async:!0},o=e._zod.run({value:r,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let s=new(i?.Err??t)(o.issues.map(c=>Ur(c,a,rr())));throw ip(s,i?.callee),s}return o.value},au=iu(tu),ou=t=>(e,r,n)=>{let i=n?{...n,async:!1}:{async:!1},a=e._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new ii;return a.issues.length?{success:!1,error:new(t??ap)(a.issues.map(o=>Ur(o,i,rr())))}:{success:!0,data:a.value}},Xo=ou(tu),su=t=>async(e,r,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},a=e._zod.run({value:r,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new t(a.issues.map(o=>Ur(o,i,rr())))}:{success:!0,data:a.value}},cu=su(tu),rk=t=>(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return ru(t)(e,r,i)};var nk=t=>(e,r,n)=>ru(t)(e,r,n);var ik=t=>async(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return iu(t)(e,r,i)};var ak=t=>async(e,r,n)=>iu(t)(e,r,n);var ok=t=>(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return ou(t)(e,r,i)};var sk=t=>(e,r,n)=>ou(t)(e,r,n);var ck=t=>async(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return su(t)(e,r,i)};var uk=t=>async(e,r,n)=>su(t)(e,r,n);var hn={};pn(hn,{base64:()=>Ev,base64url:()=>cp,bigint:()=>Rv,boolean:()=>Nv,browserEmail:()=>E9,cidrv4:()=>wv,cidrv6:()=>$v,cuid:()=>lv,cuid2:()=>dv,date:()=>Tv,datetime:()=>Pv,domain:()=>I9,duration:()=>gv,e164:()=>kv,email:()=>yv,emoji:()=>_v,extendedDuration:()=>y9,guid:()=>vv,hex:()=>P9,hostname:()=>T9,html5Email:()=>S9,idnEmail:()=>$9,integer:()=>Cv,ipv4:()=>bv,ipv6:()=>xv,ksuid:()=>mv,lowercase:()=>Mv,mac:()=>Sv,md5_base64:()=>R9,md5_base64url:()=>C9,md5_hex:()=>O9,nanoid:()=>hv,null:()=>jv,number:()=>up,rfc5322Email:()=>w9,sha1_base64:()=>j9,sha1_base64url:()=>A9,sha1_hex:()=>N9,sha256_base64:()=>D9,sha256_base64url:()=>z9,sha256_hex:()=>M9,sha384_base64:()=>L9,sha384_base64url:()=>q9,sha384_hex:()=>U9,sha512_base64:()=>Z9,sha512_base64url:()=>H9,sha512_hex:()=>F9,string:()=>Ov,time:()=>Iv,ulid:()=>pv,undefined:()=>Av,unicodeEmail:()=>lk,uppercase:()=>Dv,uuid:()=>Ua,uuid4:()=>_9,uuid6:()=>b9,uuid7:()=>x9,xid:()=>fv});var lv=/^[cC][^\s-]{8,}$/,dv=/^[0-9a-z]+$/,pv=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,fv=/^[0-9a-vA-V]{20}$/,mv=/^[A-Za-z0-9]{27}$/,hv=/^[a-zA-Z0-9_-]{21}$/,gv=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,y9=/^[-+]?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)?)??$/,vv=/^([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})$/,Ua=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)$/,_9=Ua(4),b9=Ua(6),x9=Ua(7),yv=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,S9=/^[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])?)*$/,w9=/^(([^<>()\[\]\\.,;:\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,}))$/,lk=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,$9=lk,E9=/^[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])?)*$/,k9="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function _v(){return new RegExp(k9,"u")}var bv=/^(?:(?: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])$/,xv=/^(([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}|:))$/,Sv=t=>{let e=mn(t??":");return new RegExp(`^(?:[0-9A-F]{2}${e}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${e}){5}[0-9a-f]{2}$`)},wv=/^((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])$/,$v=/^(([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])$/,Ev=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,cp=/^[A-Za-z0-9_-]*$/,T9=/^(?=.{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])?)*\.?$/,I9=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,kv=/^\+[1-9]\d{6,14}$/,dk="(?:(?:\\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])))",Tv=new RegExp(`^${dk}$`);function pk(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 Iv(t){return new RegExp(`^${pk(t)}$`)}function Pv(t){let e=pk({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(`^${dk}T(?:${n})$`)}var Ov=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Rv=/^-?\d+n?$/,Cv=/^-?\d+$/,up=/^-?\d+(?:\.\d+)?$/,Nv=/^(?:true|false)$/i,jv=/^null$/i;var Av=/^undefined$/i;var Mv=/^[^A-Z]*$/,Dv=/^[^a-z]*$/,P9=/^[0-9a-fA-F]*$/;function uu(t,e){return new RegExp(`^[A-Za-z0-9+/]{${t}}${e}$`)}function lu(t){return new RegExp(`^[A-Za-z0-9_-]{${t}}$`)}var O9=/^[0-9a-fA-F]{32}$/,R9=uu(22,"=="),C9=lu(22),N9=/^[0-9a-fA-F]{40}$/,j9=uu(27,"="),A9=lu(27),M9=/^[0-9a-fA-F]{64}$/,D9=uu(43,"="),z9=lu(43),U9=/^[0-9a-fA-F]{96}$/,L9=uu(64,""),q9=lu(64),F9=/^[0-9a-fA-F]{128}$/,Z9=uu(86,"=="),H9=lu(86);var $t=q("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),mk={number:"number",bigint:"bigint",object:"date"},zv=q("$ZodCheckLessThan",(t,e)=>{$t.init(t,e);let r=mk[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,a=(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=mk[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,a=(e.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>a&&(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})}}),hk=q("$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):nv(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})}}),gk=q("$ZodCheckNumberFormat",(t,e)=>{$t.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[i,a]=cv[e.format];t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,s.minimum=i,s.maximum=a,r&&(s.pattern=Cv)}),t._zod.check=o=>{let s=o.value;if(r){if(!Number.isInteger(s)){o.issues.push({expected:n,format:e.format,code:"invalid_type",continue:!1,input:s,inst:t});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,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:s,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}}sa&&o.issues.push({origin:"number",input:s,code:"too_big",maximum:a,inclusive:!0,inst:t,continue:!e.abort})}}),vk=q("$ZodCheckBigIntFormat",(t,e)=>{$t.init(t,e);let[r,n]=uv[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=r,a.maximum=n}),t._zod.check=i=>{let a=i.value;an&&i.issues.push({origin:"bigint",input:a,code:"too_big",maximum:n,inclusive:!0,inst:t,continue:!e.abort})}}),yk=q("$ZodCheckMaxSize",(t,e)=>{var r;$t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Qi(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:Qc(i),code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),_k=q("$ZodCheckMinSize",(t,e)=>{var r;$t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Qi(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:Qc(i),code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),bk=q("$ZodCheckSizeEquals",(t,e)=>{var r;$t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Qi(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,a=i.size;if(a===e.size)return;let o=a>e.size;n.issues.push({origin:Qc(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})}}),xk=q("$ZodCheckMaxLength",(t,e)=>{var r;$t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Qi(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=eu(i);n.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),Sk=q("$ZodCheckMinLength",(t,e)=>{var r;$t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Qi(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=eu(i);n.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),wk=q("$ZodCheckLengthEquals",(t,e)=>{var r;$t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Qi(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,a=i.length;if(a===e.length)return;let o=eu(i),s=a>e.length;n.issues.push({origin:o,...s?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),du=q("$ZodCheckStringFormat",(t,e)=>{var r,n;$t.init(t,e),t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,e.pattern&&(a.patterns??(a.patterns=new Set),a.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=()=>{})}),$k=q("$ZodCheckRegex",(t,e)=>{du.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})}}),Ek=q("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Mv),du.init(t,e)}),kk=q("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Dv),du.init(t,e)}),Tk=q("$ZodCheckIncludes",(t,e)=>{$t.init(t,e);let r=mn(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(i=>{let a=i._zod.bag;a.patterns??(a.patterns=new Set),a.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})}}),Ik=q("$ZodCheckStartsWith",(t,e)=>{$t.init(t,e);let r=new RegExp(`^${mn(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})}}),Pk=q("$ZodCheckEndsWith",(t,e)=>{$t.init(t,e);let r=new RegExp(`.*${mn(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 fk(t,e,r){t.issues.length&&e.issues.push(...nn(r,t.issues))}var Ok=q("$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=>fk(i,r,e.property));fk(n,r,e.property)}}),Rk=q("$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})}}),Ck=q("$ZodCheckOverwrite",(t,e)=>{$t.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var lp=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)),a=n.map(o=>o.slice(i)).map(o=>" ".repeat(this.indent*2)+o);for(let o of a)this.content.push(o)}compile(){let e=Function,r=this?.args,i=[...(this?.content??[""]).map(a=>` ${a}`)];return new e(...r,i.join(` -`))}};var jk={major:4,minor:3,patch:4};var Ae=q("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=jk;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let i of n)for(let a of i._zod.onattach)a(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,s,c)=>{let u=ra(o),l;for(let d of s){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 ii;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,o.issues.length!==p&&(u||(u=ra(o,p)))});else{if(o.issues.length===p)continue;u||(u=ra(o,p))}}return l?l.then(()=>o):o},a=(o,s,c)=>{if(ra(o))return o.aborted=!0,o;let u=i(s,n,c);if(u instanceof Promise){if(c.async===!1)throw new ii;return u.then(l=>t._zod.parse(l,c))}return t._zod.parse(u,c)};t._zod.run=(o,s)=>{if(s.skipChecks)return t._zod.parse(o,s);if(s.direction==="backward"){let u=t._zod.parse({value:o.value,issues:[]},{...s,skipChecks:!0});return u instanceof Promise?u.then(l=>a(l,o,s)):a(u,o,s)}let c=t._zod.parse(o,s);if(c instanceof Promise){if(s.async===!1)throw new ii;return c.then(u=>i(u,n,s))}return i(c,n,s)}}qe(t,"~standard",()=>({validate:i=>{try{let a=Xo(t,i);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return cu(t,i).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}))}),La=q("$ZodString",(t,e)=>{Ae.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Ov(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}}),bt=q("$ZodStringFormat",(t,e)=>{du.init(t,e),La.init(t,e)}),qv=q("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=vv),bt.init(t,e)}),Fv=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=Ua(n))}else e.pattern??(e.pattern=Ua());bt.init(t,e)}),Zv=q("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=yv),bt.init(t,e)}),Hv=q("$ZodURL",(t,e)=>{bt.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})}}}),Bv=q("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=_v()),bt.init(t,e)}),Vv=q("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=hv),bt.init(t,e)}),Gv=q("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=lv),bt.init(t,e)}),Wv=q("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=dv),bt.init(t,e)}),Kv=q("$ZodULID",(t,e)=>{e.pattern??(e.pattern=pv),bt.init(t,e)}),Jv=q("$ZodXID",(t,e)=>{e.pattern??(e.pattern=fv),bt.init(t,e)}),Xv=q("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=mv),bt.init(t,e)}),Yv=q("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Pv(e)),bt.init(t,e)}),Qv=q("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Tv),bt.init(t,e)}),ey=q("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Iv(e)),bt.init(t,e)}),ty=q("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=gv),bt.init(t,e)}),ry=q("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=bv),bt.init(t,e),t._zod.bag.format="ipv4"}),ny=q("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=xv),bt.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})}}}),iy=q("$ZodMAC",(t,e)=>{e.pattern??(e.pattern=Sv(e.delimiter)),bt.init(t,e),t._zod.bag.format="mac"}),ay=q("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=wv),bt.init(t,e)}),oy=q("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=$v),bt.init(t,e),t._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[i,a]=n;if(!a)throw new Error;let o=Number(a);if(`${o}`!==a)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 Vk(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var sy=q("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Ev),bt.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{Vk(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function B9(t){if(!cp.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Vk(r)}var cy=q("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=cp),bt.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{B9(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),uy=q("$ZodE164",(t,e)=>{e.pattern??(e.pattern=kv),bt.init(t,e)});function V9(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 ly=q("$ZodJWT",(t,e)=>{bt.init(t,e),t._zod.check=r=>{V9(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),dy=q("$ZodCustomStringFormat",(t,e)=>{bt.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})}}),gp=q("$ZodNumber",(t,e)=>{Ae.init(t,e),t._zod.pattern=t._zod.bag.pattern??up,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 a=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,...a?{received:a}:{}}),r}}),py=q("$ZodNumberFormat",(t,e)=>{gk.init(t,e),gp.init(t,e)}),pu=q("$ZodBoolean",(t,e)=>{Ae.init(t,e),t._zod.pattern=Nv,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}}),vp=q("$ZodBigInt",(t,e)=>{Ae.init(t,e),t._zod.pattern=Rv,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}}),fy=q("$ZodBigIntFormat",(t,e)=>{vk.init(t,e),vp.init(t,e)}),my=q("$ZodSymbol",(t,e)=>{Ae.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}}),hy=q("$ZodUndefined",(t,e)=>{Ae.init(t,e),t._zod.pattern=Av,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}}),gy=q("$ZodNull",(t,e)=>{Ae.init(t,e),t._zod.pattern=jv,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}}),vy=q("$ZodAny",(t,e)=>{Ae.init(t,e),t._zod.parse=r=>r}),yy=q("$ZodUnknown",(t,e)=>{Ae.init(t,e),t._zod.parse=r=>r}),_y=q("$ZodNever",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)}),by=q("$ZodVoid",(t,e)=>{Ae.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}}),xy=q("$ZodDate",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=new Date(r.value)}catch{}let i=r.value,a=i instanceof Date;return a&&!Number.isNaN(i.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:i,...a?{received:"Invalid Date"}:{},inst:t}),r}});function Ak(t,e,r){t.issues.length&&e.issues.push(...an(r,t.issues)),e.value[r]=t.value}var Sy=q("$ZodArray",(t,e)=>{Ae.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 a=[];for(let o=0;oAk(u,r,o))):Ak(c,r,o)}return a.length?Promise.all(a).then(()=>r):r}});function hp(t,e,r,n,i){if(t.issues.length){if(i&&!(r in n))return;e.issues.push(...an(r,t.issues))}t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function Gk(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=sv(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function Wk(t,e,r,n,i,a){let o=[],s=i.keySet,c=i.catchall._zod,u=c.def.type,l=c.optout==="optional";for(let d in e){if(s.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=>hp(f,r,d,e,l))):hp(p,r,d,e,l)}return o.length&&r.issues.push({code:"unrecognized_keys",keys:o,input:e,inst:a}),t.length?Promise.all(t).then(()=>r):r}var Kk=q("$ZodObject",(t,e)=>{if(Ae.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let s=e.shape;Object.defineProperty(e,"shape",{get:()=>{let c={...s};return Object.defineProperty(e,"shape",{value:c}),c}})}let n=Ko(()=>Gk(e));qe(t._zod,"propValues",()=>{let s=e.shape,c={};for(let u in s){let l=s[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=za,a=e.catchall,o;t._zod.parse=(s,c)=>{o??(o=n.value);let u=s.value;if(!i(u))return s.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),s;s.value={};let l=[],d=o.shape;for(let p of o.keys){let f=d[p],g=f._zod.optout==="optional",_=f._zod.run({value:u[p],issues:[]},c);_ instanceof Promise?l.push(_.then(h=>hp(h,s,p,u,g))):hp(_,s,p,u,g)}return a?Wk(l,u,s,c,n.value,t):l.length?Promise.all(l).then(()=>s):s}}),Jk=q("$ZodObjectJIT",(t,e)=>{Kk.init(t,e);let r=t._zod.parse,n=Ko(()=>Gk(e)),i=p=>{let f=new lp(["shape","payload","ctx"]),g=n.value,_=v=>{let b=np(v);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`};f.write("const input = payload.value;");let h=Object.create(null),m=0;for(let v of g.keys)h[v]=`key_${m++}`;f.write("const newResult = {};");for(let v of g.keys){let b=h[v],S=np(v),w=p[v]?._zod?.optout==="optional";f.write(`const ${b} = ${_(v)};`),w?f.write(` +`))}};var jk={major:4,minor:3,patch:4};var Ae=q("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=jk;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let i of n)for(let a of i._zod.onattach)a(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,s,c)=>{let u=ra(o),l;for(let d of s){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 ii;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,o.issues.length!==p&&(u||(u=ra(o,p)))});else{if(o.issues.length===p)continue;u||(u=ra(o,p))}}return l?l.then(()=>o):o},a=(o,s,c)=>{if(ra(o))return o.aborted=!0,o;let u=i(s,n,c);if(u instanceof Promise){if(c.async===!1)throw new ii;return u.then(l=>t._zod.parse(l,c))}return t._zod.parse(u,c)};t._zod.run=(o,s)=>{if(s.skipChecks)return t._zod.parse(o,s);if(s.direction==="backward"){let u=t._zod.parse({value:o.value,issues:[]},{...s,skipChecks:!0});return u instanceof Promise?u.then(l=>a(l,o,s)):a(u,o,s)}let c=t._zod.parse(o,s);if(c instanceof Promise){if(s.async===!1)throw new ii;return c.then(u=>i(u,n,s))}return i(c,n,s)}}qe(t,"~standard",()=>({validate:i=>{try{let a=Xo(t,i);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return cu(t,i).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}))}),La=q("$ZodString",(t,e)=>{Ae.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Ov(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}}),bt=q("$ZodStringFormat",(t,e)=>{du.init(t,e),La.init(t,e)}),qv=q("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=vv),bt.init(t,e)}),Fv=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=Ua(n))}else e.pattern??(e.pattern=Ua());bt.init(t,e)}),Zv=q("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=yv),bt.init(t,e)}),Hv=q("$ZodURL",(t,e)=>{bt.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})}}}),Bv=q("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=_v()),bt.init(t,e)}),Vv=q("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=hv),bt.init(t,e)}),Gv=q("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=lv),bt.init(t,e)}),Wv=q("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=dv),bt.init(t,e)}),Kv=q("$ZodULID",(t,e)=>{e.pattern??(e.pattern=pv),bt.init(t,e)}),Jv=q("$ZodXID",(t,e)=>{e.pattern??(e.pattern=fv),bt.init(t,e)}),Xv=q("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=mv),bt.init(t,e)}),Yv=q("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Pv(e)),bt.init(t,e)}),Qv=q("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Tv),bt.init(t,e)}),ey=q("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Iv(e)),bt.init(t,e)}),ty=q("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=gv),bt.init(t,e)}),ry=q("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=bv),bt.init(t,e),t._zod.bag.format="ipv4"}),ny=q("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=xv),bt.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})}}}),iy=q("$ZodMAC",(t,e)=>{e.pattern??(e.pattern=Sv(e.delimiter)),bt.init(t,e),t._zod.bag.format="mac"}),ay=q("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=wv),bt.init(t,e)}),oy=q("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=$v),bt.init(t,e),t._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[i,a]=n;if(!a)throw new Error;let o=Number(a);if(`${o}`!==a)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 Vk(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var sy=q("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Ev),bt.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{Vk(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function B9(t){if(!cp.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Vk(r)}var cy=q("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=cp),bt.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{B9(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),uy=q("$ZodE164",(t,e)=>{e.pattern??(e.pattern=kv),bt.init(t,e)});function V9(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 ly=q("$ZodJWT",(t,e)=>{bt.init(t,e),t._zod.check=r=>{V9(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),dy=q("$ZodCustomStringFormat",(t,e)=>{bt.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})}}),gp=q("$ZodNumber",(t,e)=>{Ae.init(t,e),t._zod.pattern=t._zod.bag.pattern??up,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 a=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,...a?{received:a}:{}}),r}}),py=q("$ZodNumberFormat",(t,e)=>{gk.init(t,e),gp.init(t,e)}),pu=q("$ZodBoolean",(t,e)=>{Ae.init(t,e),t._zod.pattern=Nv,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}}),vp=q("$ZodBigInt",(t,e)=>{Ae.init(t,e),t._zod.pattern=Rv,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}}),fy=q("$ZodBigIntFormat",(t,e)=>{vk.init(t,e),vp.init(t,e)}),my=q("$ZodSymbol",(t,e)=>{Ae.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}}),hy=q("$ZodUndefined",(t,e)=>{Ae.init(t,e),t._zod.pattern=Av,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}}),gy=q("$ZodNull",(t,e)=>{Ae.init(t,e),t._zod.pattern=jv,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}}),vy=q("$ZodAny",(t,e)=>{Ae.init(t,e),t._zod.parse=r=>r}),yy=q("$ZodUnknown",(t,e)=>{Ae.init(t,e),t._zod.parse=r=>r}),_y=q("$ZodNever",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)}),by=q("$ZodVoid",(t,e)=>{Ae.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}}),xy=q("$ZodDate",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=new Date(r.value)}catch{}let i=r.value,a=i instanceof Date;return a&&!Number.isNaN(i.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:i,...a?{received:"Invalid Date"}:{},inst:t}),r}});function Ak(t,e,r){t.issues.length&&e.issues.push(...nn(r,t.issues)),e.value[r]=t.value}var Sy=q("$ZodArray",(t,e)=>{Ae.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 a=[];for(let o=0;oAk(u,r,o))):Ak(c,r,o)}return a.length?Promise.all(a).then(()=>r):r}});function hp(t,e,r,n,i){if(t.issues.length){if(i&&!(r in n))return;e.issues.push(...nn(r,t.issues))}t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function Gk(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=sv(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function Wk(t,e,r,n,i,a){let o=[],s=i.keySet,c=i.catchall._zod,u=c.def.type,l=c.optout==="optional";for(let d in e){if(s.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=>hp(f,r,d,e,l))):hp(p,r,d,e,l)}return o.length&&r.issues.push({code:"unrecognized_keys",keys:o,input:e,inst:a}),t.length?Promise.all(t).then(()=>r):r}var Kk=q("$ZodObject",(t,e)=>{if(Ae.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let s=e.shape;Object.defineProperty(e,"shape",{get:()=>{let c={...s};return Object.defineProperty(e,"shape",{value:c}),c}})}let n=Ko(()=>Gk(e));qe(t._zod,"propValues",()=>{let s=e.shape,c={};for(let u in s){let l=s[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=za,a=e.catchall,o;t._zod.parse=(s,c)=>{o??(o=n.value);let u=s.value;if(!i(u))return s.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),s;s.value={};let l=[],d=o.shape;for(let p of o.keys){let f=d[p],g=f._zod.optout==="optional",_=f._zod.run({value:u[p],issues:[]},c);_ instanceof Promise?l.push(_.then(h=>hp(h,s,p,u,g))):hp(_,s,p,u,g)}return a?Wk(l,u,s,c,n.value,t):l.length?Promise.all(l).then(()=>s):s}}),Jk=q("$ZodObjectJIT",(t,e)=>{Kk.init(t,e);let r=t._zod.parse,n=Ko(()=>Gk(e)),i=p=>{let f=new lp(["shape","payload","ctx"]),g=n.value,_=v=>{let b=np(v);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`};f.write("const input = payload.value;");let h=Object.create(null),m=0;for(let v of g.keys)h[v]=`key_${m++}`;f.write("const newResult = {};");for(let v of g.keys){let b=h[v],S=np(v),w=p[v]?._zod?.optout==="optional";f.write(`const ${b} = ${_(v)};`),w?f.write(` if (${b}.issues.length) { if (${S} in input) { payload.issues = payload.issues.concat(${b}.issues.map(iss => ({ @@ -742,14 +742,14 @@ ${ne.dim}No previous sessions found for this project yet.${ne.reset} newResult[${S}] = ${b}.value; } - `)}f.write("payload.value = newResult;"),f.write("return payload;");let y=f.compile();return(v,b)=>y(p,v,b)},a,o=za,s=!rp.jitless,u=s&&av.value,l=e.catchall,d;t._zod.parse=(p,f)=>{d??(d=n.value);let g=p.value;return o(g)?s&&u&&f?.async===!1&&f.jitless!==!0?(a||(a=i(e.shape)),p=a(p,f),l?Wk([],g,p,f,d,t):p):r(p,f):(p.issues.push({expected:"object",code:"invalid_type",input:g,inst:t}),p)}});function Mk(t,e,r,n){for(let a of t)if(a.issues.length===0)return e.value=a.value,e;let i=t.filter(a=>!ra(a));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(a=>a.issues.map(o=>Ur(o,n,rr())))}),e)}var fu=q("$ZodUnion",(t,e)=>{Ae.init(t,e),qe(t._zod,"optin",()=>e.options.some(i=>i._zod.optin==="optional")?"optional":void 0),qe(t._zod,"optout",()=>e.options.some(i=>i._zod.optout==="optional")?"optional":void 0),qe(t._zod,"values",()=>{if(e.options.every(i=>i._zod.values))return new Set(e.options.flatMap(i=>Array.from(i._zod.values)))}),qe(t._zod,"pattern",()=>{if(e.options.every(i=>i._zod.pattern)){let i=e.options.map(a=>a._zod.pattern);return new RegExp(`^(${i.map(a=>Xc(a.source)).join("|")})$`)}});let r=e.options.length===1,n=e.options[0]._zod.run;t._zod.parse=(i,a)=>{if(r)return n(i,a);let o=!1,s=[];for(let c of e.options){let u=c._zod.run({value:i.value,issues:[]},a);if(u instanceof Promise)s.push(u),o=!0;else{if(u.issues.length===0)return u;s.push(u)}}return o?Promise.all(s).then(c=>Mk(c,i,t,a)):Mk(s,i,t,a)}});function Dk(t,e,r,n){let i=t.filter(a=>a.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(a=>a.issues.map(o=>Ur(o,n,rr())))}):e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:[],inclusive:!1}),e)}var wy=q("$ZodXor",(t,e)=>{fu.init(t,e),e.inclusive=!1;let r=e.options.length===1,n=e.options[0]._zod.run;t._zod.parse=(i,a)=>{if(r)return n(i,a);let o=!1,s=[];for(let c of e.options){let u=c._zod.run({value:i.value,issues:[]},a);u instanceof Promise?(s.push(u),o=!0):s.push(u)}return o?Promise.all(s).then(c=>Dk(c,i,t,a)):Dk(s,i,t,a)}}),$y=q("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,fu.init(t,e);let r=t._zod.parse;qe(t._zod,"propValues",()=>{let i={};for(let a of e.options){let o=a._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(a)}"`);for(let[s,c]of Object.entries(o)){i[s]||(i[s]=new Set);for(let u of c)i[s].add(u)}}return i});let n=Ko(()=>{let i=e.options,a=new Map;for(let o of i){let s=o._zod.propValues?.[e.discriminator];if(!s||s.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(let c of s){if(a.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);a.set(c,o)}}return a});t._zod.parse=(i,a)=>{let o=i.value;if(!za(o))return i.issues.push({code:"invalid_type",expected:"object",input:o,inst:t}),i;let s=n.value.get(o?.[e.discriminator]);return s?s._zod.run(i,a):e.unionFallback?r(i,a):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,input:o,path:[e.discriminator],inst:t}),i)}}),Ey=q("$ZodIntersection",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{let i=r.value,a=e.left._zod.run({value:i,issues:[]},n),o=e.right._zod.run({value:i,issues:[]},n);return a instanceof Promise||o instanceof Promise?Promise.all([a,o]).then(([c,u])=>zk(r,c,u)):zk(r,a,o)}});function Lv(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(ta(t)&&ta(e)){let r=Object.keys(e),n=Object.keys(t).filter(a=>r.indexOf(a)!==-1),i={...t,...e};for(let a of n){let o=Lv(t[a],e[a]);if(!o.valid)return{valid:!1,mergeErrorPath:[a,...o.mergeErrorPath]};i[a]=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;ns.l&&s.r).map(([s])=>s);if(a.length&&i&&t.issues.push({...i,keys:a}),ra(t))return t;let o=Lv(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 yp=q("$ZodTuple",(t,e)=>{Ae.init(t,e);let r=e.items;t._zod.parse=(n,i)=>{let a=n.value;if(!Array.isArray(a))return n.issues.push({input:a,inst:t,expected:"tuple",code:"invalid_type"}),n;n.value=[];let o=[],s=[...r].reverse().findIndex(l=>l._zod.optin!=="optional"),c=s===-1?0:r.length-s;if(!e.rest){let l=a.length>r.length,d=a.length=a.length&&u>=c)continue;let d=l._zod.run({value:a[u],issues:[]},i);d instanceof Promise?o.push(d.then(p=>dp(p,n,u))):dp(d,n,u)}if(e.rest){let l=a.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=>dp(f,n,u))):dp(p,n,u)}}return o.length?Promise.all(o).then(()=>n):n}});function dp(t,e,r){t.issues.length&&e.issues.push(...an(r,t.issues)),e.value[r]=t.value}var ky=q("$ZodRecord",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;if(!ta(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:t}),r;let a=[],o=e.keyType._zod.values;if(o){r.value={};let s=new Set;for(let u of o)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){s.add(typeof u=="number"?u.toString():u);let l=e.valueType._zod.run({value:i[u],issues:[]},n);l instanceof Promise?a.push(l.then(d=>{d.issues.length&&r.issues.push(...an(u,d.issues)),r.value[u]=d.value})):(l.issues.length&&r.issues.push(...an(u,l.issues)),r.value[u]=l.value)}let c;for(let u in i)s.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 s of Reflect.ownKeys(i)){if(s==="__proto__")continue;let c=e.keyType._zod.run({value:s,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof s=="string"&&up.test(s)&&c.issues.length&&c.issues.some(d=>d.code==="invalid_type"&&d.expected==="number")){let d=e.keyType._zod.run({value:Number(s),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[s]=i[s]:r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(d=>Ur(d,n,rr())),input:s,path:[s],inst:t});continue}let l=e.valueType._zod.run({value:i[s],issues:[]},n);l instanceof Promise?a.push(l.then(d=>{d.issues.length&&r.issues.push(...an(s,d.issues)),r.value[c.value]=d.value})):(l.issues.length&&r.issues.push(...an(s,l.issues)),r.value[c.value]=l.value)}}return a.length?Promise.all(a).then(()=>r):r}}),Ty=q("$ZodMap",(t,e)=>{Ae.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 a=[];r.value=new Map;for(let[o,s]of i){let c=e.keyType._zod.run({value:o,issues:[]},n),u=e.valueType._zod.run({value:s,issues:[]},n);c instanceof Promise||u instanceof Promise?a.push(Promise.all([c,u]).then(([l,d])=>{Uk(l,d,r,o,i,t,n)})):Uk(c,u,r,o,i,t,n)}return a.length?Promise.all(a).then(()=>r):r}});function Uk(t,e,r,n,i,a,o){t.issues.length&&(Yc.has(typeof n)?r.issues.push(...an(n,t.issues)):r.issues.push({code:"invalid_key",origin:"map",input:i,inst:a,issues:t.issues.map(s=>Ur(s,o,rr()))})),e.issues.length&&(Yc.has(typeof n)?r.issues.push(...an(n,e.issues)):r.issues.push({origin:"map",code:"invalid_element",input:i,inst:a,key:n,issues:e.issues.map(s=>Ur(s,o,rr()))})),r.value.set(t.value,e.value)}var Iy=q("$ZodSet",(t,e)=>{Ae.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 a=[];r.value=new Set;for(let o of i){let s=e.valueType._zod.run({value:o,issues:[]},n);s instanceof Promise?a.push(s.then(c=>Lk(c,r))):Lk(s,r)}return a.length?Promise.all(a).then(()=>r):r}});function Lk(t,e){t.issues.length&&e.issues.push(...t.issues),e.value.add(t.value)}var Py=q("$ZodEnum",(t,e)=>{Ae.init(t,e);let r=Jc(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(i=>Yc.has(typeof i)).map(i=>typeof i=="string"?mn(i):i.toString()).join("|")})$`),t._zod.parse=(i,a)=>{let o=i.value;return n.has(o)||i.issues.push({code:"invalid_value",values:r,input:o,inst:t}),i}}),Oy=q("$ZodLiteral",(t,e)=>{if(Ae.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"?mn(n):n?mn(n.toString()):String(n)).join("|")})$`),t._zod.parse=(n,i)=>{let a=n.value;return r.has(a)||n.issues.push({code:"invalid_value",values:e.values,input:a,inst:t}),n}}),Ry=q("$ZodFile",(t,e)=>{Ae.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}}),Cy=q("$ZodTransform",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Da(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 ii;return r.value=i,r}});function qk(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}var _p=q("$ZodOptional",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",t._zod.optout="optional",qe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),qe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Xc(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(a=>qk(a,r.value)):qk(i,r.value)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),Ny=q("$ZodExactOptional",(t,e)=>{_p.init(t,e),qe(t._zod,"values",()=>e.innerType._zod.values),qe(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(r,n)=>e.innerType._zod.run(r,n)}),jy=q("$ZodNullable",(t,e)=>{Ae.init(t,e),qe(t._zod,"optin",()=>e.innerType._zod.optin),qe(t._zod,"optout",()=>e.innerType._zod.optout),qe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Xc(r.source)}|null)$`):void 0}),qe(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)}),Ay=q("$ZodDefault",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",qe(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(a=>Fk(a,e)):Fk(i,e)}});function Fk(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var My=q("$ZodPrefault",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",qe(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))}),Dy=q("$ZodNonOptional",(t,e)=>{Ae.init(t,e),qe(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(a=>Zk(a,t)):Zk(i,t)}});function Zk(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 zy=q("$ZodSuccess",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Da("ZodSuccess");let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(a=>(r.value=a.issues.length===0,r)):(r.value=i.issues.length===0,r)}}),Uy=q("$ZodCatch",(t,e)=>{Ae.init(t,e),qe(t._zod,"optin",()=>e.innerType._zod.optin),qe(t._zod,"optout",()=>e.innerType._zod.optout),qe(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(a=>(r.value=a.value,a.issues.length&&(r.value=e.catchValue({...r,error:{issues:a.issues.map(o=>Ur(o,n,rr()))},input:r.value}),r.issues=[]),r)):(r.value=i.value,i.issues.length&&(r.value=e.catchValue({...r,error:{issues:i.issues.map(a=>Ur(a,n,rr()))},input:r.value}),r.issues=[]),r)}}),Ly=q("$ZodNaN",(t,e)=>{Ae.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)}),qy=q("$ZodPipe",(t,e)=>{Ae.init(t,e),qe(t._zod,"values",()=>e.in._zod.values),qe(t._zod,"optin",()=>e.in._zod.optin),qe(t._zod,"optout",()=>e.out._zod.optout),qe(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(r,n)=>{if(n.direction==="backward"){let a=e.out._zod.run(r,n);return a instanceof Promise?a.then(o=>pp(o,e.in,n)):pp(a,e.in,n)}let i=e.in._zod.run(r,n);return i instanceof Promise?i.then(a=>pp(a,e.out,n)):pp(i,e.out,n)}});function pp(t,e,r){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},r)}var mu=q("$ZodCodec",(t,e)=>{Ae.init(t,e),qe(t._zod,"values",()=>e.in._zod.values),qe(t._zod,"optin",()=>e.in._zod.optin),qe(t._zod,"optout",()=>e.out._zod.optout),qe(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(r,n)=>{if((n.direction||"forward")==="forward"){let a=e.in._zod.run(r,n);return a instanceof Promise?a.then(o=>fp(o,e,n)):fp(a,e,n)}else{let a=e.out._zod.run(r,n);return a instanceof Promise?a.then(o=>fp(o,e,n)):fp(a,e,n)}}});function fp(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(a=>mp(t,a,e.out,r)):mp(t,i,e.out,r)}else{let i=e.reverseTransform(t.value,t);return i instanceof Promise?i.then(a=>mp(t,a,e.in,r)):mp(t,i,e.in,r)}}function mp(t,e,r,n){return t.issues.length?(t.aborted=!0,t):r._zod.run({value:e,issues:t.issues},n)}var Fy=q("$ZodReadonly",(t,e)=>{Ae.init(t,e),qe(t._zod,"propValues",()=>e.innerType._zod.propValues),qe(t._zod,"values",()=>e.innerType._zod.values),qe(t._zod,"optin",()=>e.innerType?._zod?.optin),qe(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(Hk):Hk(i)}});function Hk(t){return t.value=Object.freeze(t.value),t}var Zy=q("$ZodTemplateLiteral",(t,e)=>{Ae.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 a=i.startsWith("^")?1:0,o=i.endsWith("$")?i.length-1:i.length;r.push(i.slice(a,o))}else if(n===null||ov.has(typeof n))r.push(mn(`${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)}),Hy=q("$ZodFunction",(t,e)=>(Ae.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?nu(t._def.input,n):n,a=Reflect.apply(r,this,i);return t._def.output?nu(t._def.output,a):a}},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 au(t._def.input,n):n,a=await Reflect.apply(r,this,i);return t._def.output?await au(t._def.output,a):a}},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 yp({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)),By=q("$ZodPromise",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>Promise.resolve(r.value).then(i=>e.innerType._zod.run({value:i,issues:[]},n))}),Vy=q("$ZodLazy",(t,e)=>{Ae.init(t,e),qe(t._zod,"innerType",()=>e.getter()),qe(t._zod,"pattern",()=>t._zod.innerType?._zod?.pattern),qe(t._zod,"propValues",()=>t._zod.innerType?._zod?.propValues),qe(t._zod,"optin",()=>t._zod.innerType?._zod?.optin??void 0),qe(t._zod,"optout",()=>t._zod.innerType?._zod?.optout??void 0),t._zod.parse=(r,n)=>t._zod.innerType._zod.run(r,n)}),Gy=q("$ZodCustom",(t,e)=>{$t.init(t,e),Ae.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(a=>Bk(a,r,n,t));Bk(i,r,n,t)}});function Bk(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(Jo(i))}}var W9=()=>{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 a=n[i.expected]??i.expected,o=Pe(i.input),s=n[o]??o;return`Invalid input: expected ${a}, received ${s}`}case"invalid_value":return i.values.length===1?`Invalid input: expected ${ke(i.values[0])}`:`Invalid option: expected one of ${Ee(i.values,"|")}`;case"too_big":{let a=i.inclusive?"<=":"<",o=e(i.origin);return o?`Too big: expected ${i.origin??"value"} to have ${a}${i.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${i.origin??"value"} to be ${a}${i.maximum.toString()}`}case"too_small":{let a=i.inclusive?">=":">",o=e(i.origin);return o?`Too small: expected ${i.origin} to have ${a}${i.minimum.toString()} ${o.unit}`:`Too small: expected ${i.origin} to be ${a}${i.minimum.toString()}`}case"invalid_format":{let a=i;return a.format==="starts_with"?`Invalid string: must start with "${a.prefix}"`:a.format==="ends_with"?`Invalid string: must end with "${a.suffix}"`:a.format==="includes"?`Invalid string: must include "${a.includes}"`:a.format==="regex"?`Invalid string: must match pattern ${a.pattern}`:`Invalid ${r[a.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":""}: ${Ee(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 Wy(){return{localeError:W9()}}var Xk;var Jy=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 Xy(){return new Jy}(Xk=globalThis).__zod_globalRegistry??(Xk.__zod_globalRegistry=Xy());var Pr=globalThis.__zod_globalRegistry;function Yy(t,e){return new t({type:"string",...oe(e)})}function bp(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...oe(e)})}function hu(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...oe(e)})}function xp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...oe(e)})}function Sp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...oe(e)})}function wp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...oe(e)})}function $p(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...oe(e)})}function gu(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...oe(e)})}function Ep(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...oe(e)})}function kp(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...oe(e)})}function Tp(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...oe(e)})}function Ip(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...oe(e)})}function Pp(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...oe(e)})}function Op(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...oe(e)})}function Rp(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...oe(e)})}function Cp(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...oe(e)})}function Np(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...oe(e)})}function Qy(t,e){return new t({type:"string",format:"mac",check:"string_format",abort:!1,...oe(e)})}function jp(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...oe(e)})}function Ap(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...oe(e)})}function Mp(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...oe(e)})}function Dp(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...oe(e)})}function zp(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...oe(e)})}function Up(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...oe(e)})}function e_(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...oe(e)})}function t_(t,e){return new t({type:"string",format:"date",check:"string_format",...oe(e)})}function r_(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...oe(e)})}function n_(t,e){return new t({type:"string",format:"duration",check:"string_format",...oe(e)})}function i_(t,e){return new t({type:"number",checks:[],...oe(e)})}function a_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...oe(e)})}function o_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float32",...oe(e)})}function s_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float64",...oe(e)})}function c_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"int32",...oe(e)})}function u_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"uint32",...oe(e)})}function l_(t,e){return new t({type:"boolean",...oe(e)})}function d_(t,e){return new t({type:"bigint",...oe(e)})}function p_(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...oe(e)})}function f_(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...oe(e)})}function m_(t,e){return new t({type:"symbol",...oe(e)})}function h_(t,e){return new t({type:"undefined",...oe(e)})}function g_(t,e){return new t({type:"null",...oe(e)})}function v_(t){return new t({type:"any"})}function y_(t){return new t({type:"unknown"})}function __(t,e){return new t({type:"never",...oe(e)})}function b_(t,e){return new t({type:"void",...oe(e)})}function x_(t,e){return new t({type:"date",...oe(e)})}function S_(t,e){return new t({type:"nan",...oe(e)})}function Ii(t,e){return new zv({check:"less_than",...oe(e),value:t,inclusive:!1})}function on(t,e){return new zv({check:"less_than",...oe(e),value:t,inclusive:!0})}function Pi(t,e){return new Uv({check:"greater_than",...oe(e),value:t,inclusive:!1})}function Or(t,e){return new Uv({check:"greater_than",...oe(e),value:t,inclusive:!0})}function w_(t){return Pi(0,t)}function $_(t){return Ii(0,t)}function E_(t){return on(0,t)}function k_(t){return Or(0,t)}function qa(t,e){return new hk({check:"multiple_of",...oe(e),value:t})}function Fa(t,e){return new yk({check:"max_size",...oe(e),maximum:t})}function Oi(t,e){return new _k({check:"min_size",...oe(e),minimum:t})}function Yo(t,e){return new bk({check:"size_equals",...oe(e),size:t})}function Qo(t,e){return new xk({check:"max_length",...oe(e),maximum:t})}function na(t,e){return new Sk({check:"min_length",...oe(e),minimum:t})}function es(t,e){return new wk({check:"length_equals",...oe(e),length:t})}function vu(t,e){return new $k({check:"string_format",format:"regex",...oe(e),pattern:t})}function yu(t){return new Ek({check:"string_format",format:"lowercase",...oe(t)})}function _u(t){return new kk({check:"string_format",format:"uppercase",...oe(t)})}function bu(t,e){return new Tk({check:"string_format",format:"includes",...oe(e),includes:t})}function xu(t,e){return new Ik({check:"string_format",format:"starts_with",...oe(e),prefix:t})}function Su(t,e){return new Pk({check:"string_format",format:"ends_with",...oe(e),suffix:t})}function T_(t,e,r){return new Ok({check:"property",property:t,schema:e,...oe(r)})}function wu(t,e){return new Rk({check:"mime_type",mime:t,...oe(e)})}function ai(t){return new Ck({check:"overwrite",tx:t})}function $u(t){return ai(e=>e.normalize(t))}function Eu(){return ai(t=>t.trim())}function ku(){return ai(t=>t.toLowerCase())}function Tu(){return ai(t=>t.toUpperCase())}function Lp(){return ai(t=>iv(t))}function Yk(t,e,r){return new t({type:"array",element:e,...oe(r)})}function I_(t,e){return new t({type:"file",...oe(e)})}function P_(t,e,r){let n=oe(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function O_(t,e,r){return new t({type:"custom",check:"custom",fn:e,...oe(r)})}function R_(t){let e=Y9(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Jo(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(Jo(i))}},t(r.value,r)));return e}function Y9(t,e){let r=new $t({check:"custom",...oe(e)});return r._zod.check=t,r}function C_(t){let e=new $t({check:"describe"});return e._zod.onattach=[r=>{let n=Pr.get(r)??{};Pr.add(r,{...n,description:t})}],e._zod.check=()=>{},e}function N_(t){let e=new $t({check:"meta"});return e._zod.onattach=[r=>{let n=Pr.get(r)??{};Pr.add(r,{...n,...t})}],e._zod.check=()=>{},e}function j_(t,e){let r=oe(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 a=new Set(n),o=new Set(i),s=t.Codec??mu,c=t.Boolean??pu,u=t.String??La,l=new u({type:"string",error:r.error}),d=new c({type:"boolean",error:r.error}),p=new s({type:"pipe",in:l,out:d,transform:((f,g)=>{let _=f;return r.case!=="sensitive"&&(_=_.toLowerCase()),a.has(_)?!0:o.has(_)?!1:(g.issues.push({code:"invalid_value",expected:"stringbool",values:[...a,...o],input:g.value,inst:p,continue:!1}),{})}),reverseTransform:((f,g)=>f===!0?n[0]||"true":i[0]||"false"),error:r.error});return p}function ts(t,e,r,n={}){let i=oe(n),a={...oe(n),check:"string_format",type:"string",format:e,fn:typeof r=="function"?r:s=>r.test(s),...i};return r instanceof RegExp&&(a.pattern=r),new t(a)}function qp(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??Pr,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 Ot(t,e,r={path:[],schemaPath:[]}){var n;let i=t._zod.def,a=e.seen.get(t);if(a)return a.count++,r.schemaPath.includes(t)&&(a.cycle=r.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,o);let s=t._zod.toJSONSchema?.();if(s)o.schema=s;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),Ot(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"&&Rr(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 Fp(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 s=t.metadataRegistry.get(o[0])?.id;if(s){let c=n.get(s);if(c&&c!==o[0])throw new Error(`Duplicate schema id "${s}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(s,o[0])}}let i=o=>{let s=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let d=t.external.registry.get(o[0])?.id,p=t.external.uri??(g=>g);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")}#/${s}/${f}`}}if(o[1]===r)return{ref:"#"};let u=`#/${s}/`,l=o[1].schema.id??`__schema${t.counter++}`;return{defId:l,ref:u+l}},a=o=>{if(o[1].schema.$ref)return;let s=o[1],{ref:c,defId:u}=i(o);s.def={...s.schema},u&&(s.defId=u);let l=s.schema;for(let d in l)delete l[d];l.$ref=c};if(t.cycles==="throw")for(let o of t.seen.entries()){let s=o[1];if(s.cycle)throw new Error(`Cycle detected: #/${s.cycle?.join("/")}/ + `)}f.write("payload.value = newResult;"),f.write("return payload;");let y=f.compile();return(v,b)=>y(p,v,b)},a,o=za,s=!rp.jitless,u=s&&av.value,l=e.catchall,d;t._zod.parse=(p,f)=>{d??(d=n.value);let g=p.value;return o(g)?s&&u&&f?.async===!1&&f.jitless!==!0?(a||(a=i(e.shape)),p=a(p,f),l?Wk([],g,p,f,d,t):p):r(p,f):(p.issues.push({expected:"object",code:"invalid_type",input:g,inst:t}),p)}});function Mk(t,e,r,n){for(let a of t)if(a.issues.length===0)return e.value=a.value,e;let i=t.filter(a=>!ra(a));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(a=>a.issues.map(o=>Ur(o,n,rr())))}),e)}var fu=q("$ZodUnion",(t,e)=>{Ae.init(t,e),qe(t._zod,"optin",()=>e.options.some(i=>i._zod.optin==="optional")?"optional":void 0),qe(t._zod,"optout",()=>e.options.some(i=>i._zod.optout==="optional")?"optional":void 0),qe(t._zod,"values",()=>{if(e.options.every(i=>i._zod.values))return new Set(e.options.flatMap(i=>Array.from(i._zod.values)))}),qe(t._zod,"pattern",()=>{if(e.options.every(i=>i._zod.pattern)){let i=e.options.map(a=>a._zod.pattern);return new RegExp(`^(${i.map(a=>Xc(a.source)).join("|")})$`)}});let r=e.options.length===1,n=e.options[0]._zod.run;t._zod.parse=(i,a)=>{if(r)return n(i,a);let o=!1,s=[];for(let c of e.options){let u=c._zod.run({value:i.value,issues:[]},a);if(u instanceof Promise)s.push(u),o=!0;else{if(u.issues.length===0)return u;s.push(u)}}return o?Promise.all(s).then(c=>Mk(c,i,t,a)):Mk(s,i,t,a)}});function Dk(t,e,r,n){let i=t.filter(a=>a.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(a=>a.issues.map(o=>Ur(o,n,rr())))}):e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:[],inclusive:!1}),e)}var wy=q("$ZodXor",(t,e)=>{fu.init(t,e),e.inclusive=!1;let r=e.options.length===1,n=e.options[0]._zod.run;t._zod.parse=(i,a)=>{if(r)return n(i,a);let o=!1,s=[];for(let c of e.options){let u=c._zod.run({value:i.value,issues:[]},a);u instanceof Promise?(s.push(u),o=!0):s.push(u)}return o?Promise.all(s).then(c=>Dk(c,i,t,a)):Dk(s,i,t,a)}}),$y=q("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,fu.init(t,e);let r=t._zod.parse;qe(t._zod,"propValues",()=>{let i={};for(let a of e.options){let o=a._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(a)}"`);for(let[s,c]of Object.entries(o)){i[s]||(i[s]=new Set);for(let u of c)i[s].add(u)}}return i});let n=Ko(()=>{let i=e.options,a=new Map;for(let o of i){let s=o._zod.propValues?.[e.discriminator];if(!s||s.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(let c of s){if(a.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);a.set(c,o)}}return a});t._zod.parse=(i,a)=>{let o=i.value;if(!za(o))return i.issues.push({code:"invalid_type",expected:"object",input:o,inst:t}),i;let s=n.value.get(o?.[e.discriminator]);return s?s._zod.run(i,a):e.unionFallback?r(i,a):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,input:o,path:[e.discriminator],inst:t}),i)}}),Ey=q("$ZodIntersection",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{let i=r.value,a=e.left._zod.run({value:i,issues:[]},n),o=e.right._zod.run({value:i,issues:[]},n);return a instanceof Promise||o instanceof Promise?Promise.all([a,o]).then(([c,u])=>zk(r,c,u)):zk(r,a,o)}});function Lv(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(ta(t)&&ta(e)){let r=Object.keys(e),n=Object.keys(t).filter(a=>r.indexOf(a)!==-1),i={...t,...e};for(let a of n){let o=Lv(t[a],e[a]);if(!o.valid)return{valid:!1,mergeErrorPath:[a,...o.mergeErrorPath]};i[a]=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;ns.l&&s.r).map(([s])=>s);if(a.length&&i&&t.issues.push({...i,keys:a}),ra(t))return t;let o=Lv(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 yp=q("$ZodTuple",(t,e)=>{Ae.init(t,e);let r=e.items;t._zod.parse=(n,i)=>{let a=n.value;if(!Array.isArray(a))return n.issues.push({input:a,inst:t,expected:"tuple",code:"invalid_type"}),n;n.value=[];let o=[],s=[...r].reverse().findIndex(l=>l._zod.optin!=="optional"),c=s===-1?0:r.length-s;if(!e.rest){let l=a.length>r.length,d=a.length=a.length&&u>=c)continue;let d=l._zod.run({value:a[u],issues:[]},i);d instanceof Promise?o.push(d.then(p=>dp(p,n,u))):dp(d,n,u)}if(e.rest){let l=a.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=>dp(f,n,u))):dp(p,n,u)}}return o.length?Promise.all(o).then(()=>n):n}});function dp(t,e,r){t.issues.length&&e.issues.push(...nn(r,t.issues)),e.value[r]=t.value}var ky=q("$ZodRecord",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;if(!ta(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:t}),r;let a=[],o=e.keyType._zod.values;if(o){r.value={};let s=new Set;for(let u of o)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){s.add(typeof u=="number"?u.toString():u);let l=e.valueType._zod.run({value:i[u],issues:[]},n);l instanceof Promise?a.push(l.then(d=>{d.issues.length&&r.issues.push(...nn(u,d.issues)),r.value[u]=d.value})):(l.issues.length&&r.issues.push(...nn(u,l.issues)),r.value[u]=l.value)}let c;for(let u in i)s.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 s of Reflect.ownKeys(i)){if(s==="__proto__")continue;let c=e.keyType._zod.run({value:s,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof s=="string"&&up.test(s)&&c.issues.length&&c.issues.some(d=>d.code==="invalid_type"&&d.expected==="number")){let d=e.keyType._zod.run({value:Number(s),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[s]=i[s]:r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(d=>Ur(d,n,rr())),input:s,path:[s],inst:t});continue}let l=e.valueType._zod.run({value:i[s],issues:[]},n);l instanceof Promise?a.push(l.then(d=>{d.issues.length&&r.issues.push(...nn(s,d.issues)),r.value[c.value]=d.value})):(l.issues.length&&r.issues.push(...nn(s,l.issues)),r.value[c.value]=l.value)}}return a.length?Promise.all(a).then(()=>r):r}}),Ty=q("$ZodMap",(t,e)=>{Ae.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 a=[];r.value=new Map;for(let[o,s]of i){let c=e.keyType._zod.run({value:o,issues:[]},n),u=e.valueType._zod.run({value:s,issues:[]},n);c instanceof Promise||u instanceof Promise?a.push(Promise.all([c,u]).then(([l,d])=>{Uk(l,d,r,o,i,t,n)})):Uk(c,u,r,o,i,t,n)}return a.length?Promise.all(a).then(()=>r):r}});function Uk(t,e,r,n,i,a,o){t.issues.length&&(Yc.has(typeof n)?r.issues.push(...nn(n,t.issues)):r.issues.push({code:"invalid_key",origin:"map",input:i,inst:a,issues:t.issues.map(s=>Ur(s,o,rr()))})),e.issues.length&&(Yc.has(typeof n)?r.issues.push(...nn(n,e.issues)):r.issues.push({origin:"map",code:"invalid_element",input:i,inst:a,key:n,issues:e.issues.map(s=>Ur(s,o,rr()))})),r.value.set(t.value,e.value)}var Iy=q("$ZodSet",(t,e)=>{Ae.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 a=[];r.value=new Set;for(let o of i){let s=e.valueType._zod.run({value:o,issues:[]},n);s instanceof Promise?a.push(s.then(c=>Lk(c,r))):Lk(s,r)}return a.length?Promise.all(a).then(()=>r):r}});function Lk(t,e){t.issues.length&&e.issues.push(...t.issues),e.value.add(t.value)}var Py=q("$ZodEnum",(t,e)=>{Ae.init(t,e);let r=Jc(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(i=>Yc.has(typeof i)).map(i=>typeof i=="string"?mn(i):i.toString()).join("|")})$`),t._zod.parse=(i,a)=>{let o=i.value;return n.has(o)||i.issues.push({code:"invalid_value",values:r,input:o,inst:t}),i}}),Oy=q("$ZodLiteral",(t,e)=>{if(Ae.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"?mn(n):n?mn(n.toString()):String(n)).join("|")})$`),t._zod.parse=(n,i)=>{let a=n.value;return r.has(a)||n.issues.push({code:"invalid_value",values:e.values,input:a,inst:t}),n}}),Ry=q("$ZodFile",(t,e)=>{Ae.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}}),Cy=q("$ZodTransform",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Da(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 ii;return r.value=i,r}});function qk(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}var _p=q("$ZodOptional",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",t._zod.optout="optional",qe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),qe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Xc(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(a=>qk(a,r.value)):qk(i,r.value)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),Ny=q("$ZodExactOptional",(t,e)=>{_p.init(t,e),qe(t._zod,"values",()=>e.innerType._zod.values),qe(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(r,n)=>e.innerType._zod.run(r,n)}),jy=q("$ZodNullable",(t,e)=>{Ae.init(t,e),qe(t._zod,"optin",()=>e.innerType._zod.optin),qe(t._zod,"optout",()=>e.innerType._zod.optout),qe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Xc(r.source)}|null)$`):void 0}),qe(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)}),Ay=q("$ZodDefault",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",qe(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(a=>Fk(a,e)):Fk(i,e)}});function Fk(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var My=q("$ZodPrefault",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",qe(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))}),Dy=q("$ZodNonOptional",(t,e)=>{Ae.init(t,e),qe(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(a=>Zk(a,t)):Zk(i,t)}});function Zk(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 zy=q("$ZodSuccess",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Da("ZodSuccess");let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(a=>(r.value=a.issues.length===0,r)):(r.value=i.issues.length===0,r)}}),Uy=q("$ZodCatch",(t,e)=>{Ae.init(t,e),qe(t._zod,"optin",()=>e.innerType._zod.optin),qe(t._zod,"optout",()=>e.innerType._zod.optout),qe(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(a=>(r.value=a.value,a.issues.length&&(r.value=e.catchValue({...r,error:{issues:a.issues.map(o=>Ur(o,n,rr()))},input:r.value}),r.issues=[]),r)):(r.value=i.value,i.issues.length&&(r.value=e.catchValue({...r,error:{issues:i.issues.map(a=>Ur(a,n,rr()))},input:r.value}),r.issues=[]),r)}}),Ly=q("$ZodNaN",(t,e)=>{Ae.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)}),qy=q("$ZodPipe",(t,e)=>{Ae.init(t,e),qe(t._zod,"values",()=>e.in._zod.values),qe(t._zod,"optin",()=>e.in._zod.optin),qe(t._zod,"optout",()=>e.out._zod.optout),qe(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(r,n)=>{if(n.direction==="backward"){let a=e.out._zod.run(r,n);return a instanceof Promise?a.then(o=>pp(o,e.in,n)):pp(a,e.in,n)}let i=e.in._zod.run(r,n);return i instanceof Promise?i.then(a=>pp(a,e.out,n)):pp(i,e.out,n)}});function pp(t,e,r){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},r)}var mu=q("$ZodCodec",(t,e)=>{Ae.init(t,e),qe(t._zod,"values",()=>e.in._zod.values),qe(t._zod,"optin",()=>e.in._zod.optin),qe(t._zod,"optout",()=>e.out._zod.optout),qe(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(r,n)=>{if((n.direction||"forward")==="forward"){let a=e.in._zod.run(r,n);return a instanceof Promise?a.then(o=>fp(o,e,n)):fp(a,e,n)}else{let a=e.out._zod.run(r,n);return a instanceof Promise?a.then(o=>fp(o,e,n)):fp(a,e,n)}}});function fp(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(a=>mp(t,a,e.out,r)):mp(t,i,e.out,r)}else{let i=e.reverseTransform(t.value,t);return i instanceof Promise?i.then(a=>mp(t,a,e.in,r)):mp(t,i,e.in,r)}}function mp(t,e,r,n){return t.issues.length?(t.aborted=!0,t):r._zod.run({value:e,issues:t.issues},n)}var Fy=q("$ZodReadonly",(t,e)=>{Ae.init(t,e),qe(t._zod,"propValues",()=>e.innerType._zod.propValues),qe(t._zod,"values",()=>e.innerType._zod.values),qe(t._zod,"optin",()=>e.innerType?._zod?.optin),qe(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(Hk):Hk(i)}});function Hk(t){return t.value=Object.freeze(t.value),t}var Zy=q("$ZodTemplateLiteral",(t,e)=>{Ae.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 a=i.startsWith("^")?1:0,o=i.endsWith("$")?i.length-1:i.length;r.push(i.slice(a,o))}else if(n===null||ov.has(typeof n))r.push(mn(`${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)}),Hy=q("$ZodFunction",(t,e)=>(Ae.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?nu(t._def.input,n):n,a=Reflect.apply(r,this,i);return t._def.output?nu(t._def.output,a):a}},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 au(t._def.input,n):n,a=await Reflect.apply(r,this,i);return t._def.output?await au(t._def.output,a):a}},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 yp({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)),By=q("$ZodPromise",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>Promise.resolve(r.value).then(i=>e.innerType._zod.run({value:i,issues:[]},n))}),Vy=q("$ZodLazy",(t,e)=>{Ae.init(t,e),qe(t._zod,"innerType",()=>e.getter()),qe(t._zod,"pattern",()=>t._zod.innerType?._zod?.pattern),qe(t._zod,"propValues",()=>t._zod.innerType?._zod?.propValues),qe(t._zod,"optin",()=>t._zod.innerType?._zod?.optin??void 0),qe(t._zod,"optout",()=>t._zod.innerType?._zod?.optout??void 0),t._zod.parse=(r,n)=>t._zod.innerType._zod.run(r,n)}),Gy=q("$ZodCustom",(t,e)=>{$t.init(t,e),Ae.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(a=>Bk(a,r,n,t));Bk(i,r,n,t)}});function Bk(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(Jo(i))}}var W9=()=>{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 a=n[i.expected]??i.expected,o=Pe(i.input),s=n[o]??o;return`Invalid input: expected ${a}, received ${s}`}case"invalid_value":return i.values.length===1?`Invalid input: expected ${ke(i.values[0])}`:`Invalid option: expected one of ${Ee(i.values,"|")}`;case"too_big":{let a=i.inclusive?"<=":"<",o=e(i.origin);return o?`Too big: expected ${i.origin??"value"} to have ${a}${i.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${i.origin??"value"} to be ${a}${i.maximum.toString()}`}case"too_small":{let a=i.inclusive?">=":">",o=e(i.origin);return o?`Too small: expected ${i.origin} to have ${a}${i.minimum.toString()} ${o.unit}`:`Too small: expected ${i.origin} to be ${a}${i.minimum.toString()}`}case"invalid_format":{let a=i;return a.format==="starts_with"?`Invalid string: must start with "${a.prefix}"`:a.format==="ends_with"?`Invalid string: must end with "${a.suffix}"`:a.format==="includes"?`Invalid string: must include "${a.includes}"`:a.format==="regex"?`Invalid string: must match pattern ${a.pattern}`:`Invalid ${r[a.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":""}: ${Ee(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 Wy(){return{localeError:W9()}}var Xk;var Jy=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 Xy(){return new Jy}(Xk=globalThis).__zod_globalRegistry??(Xk.__zod_globalRegistry=Xy());var Pr=globalThis.__zod_globalRegistry;function Yy(t,e){return new t({type:"string",...oe(e)})}function bp(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...oe(e)})}function hu(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...oe(e)})}function xp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...oe(e)})}function Sp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...oe(e)})}function wp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...oe(e)})}function $p(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...oe(e)})}function gu(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...oe(e)})}function Ep(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...oe(e)})}function kp(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...oe(e)})}function Tp(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...oe(e)})}function Ip(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...oe(e)})}function Pp(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...oe(e)})}function Op(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...oe(e)})}function Rp(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...oe(e)})}function Cp(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...oe(e)})}function Np(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...oe(e)})}function Qy(t,e){return new t({type:"string",format:"mac",check:"string_format",abort:!1,...oe(e)})}function jp(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...oe(e)})}function Ap(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...oe(e)})}function Mp(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...oe(e)})}function Dp(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...oe(e)})}function zp(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...oe(e)})}function Up(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...oe(e)})}function e_(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...oe(e)})}function t_(t,e){return new t({type:"string",format:"date",check:"string_format",...oe(e)})}function r_(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...oe(e)})}function n_(t,e){return new t({type:"string",format:"duration",check:"string_format",...oe(e)})}function i_(t,e){return new t({type:"number",checks:[],...oe(e)})}function a_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...oe(e)})}function o_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float32",...oe(e)})}function s_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float64",...oe(e)})}function c_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"int32",...oe(e)})}function u_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"uint32",...oe(e)})}function l_(t,e){return new t({type:"boolean",...oe(e)})}function d_(t,e){return new t({type:"bigint",...oe(e)})}function p_(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...oe(e)})}function f_(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...oe(e)})}function m_(t,e){return new t({type:"symbol",...oe(e)})}function h_(t,e){return new t({type:"undefined",...oe(e)})}function g_(t,e){return new t({type:"null",...oe(e)})}function v_(t){return new t({type:"any"})}function y_(t){return new t({type:"unknown"})}function __(t,e){return new t({type:"never",...oe(e)})}function b_(t,e){return new t({type:"void",...oe(e)})}function x_(t,e){return new t({type:"date",...oe(e)})}function S_(t,e){return new t({type:"nan",...oe(e)})}function Ii(t,e){return new zv({check:"less_than",...oe(e),value:t,inclusive:!1})}function an(t,e){return new zv({check:"less_than",...oe(e),value:t,inclusive:!0})}function Pi(t,e){return new Uv({check:"greater_than",...oe(e),value:t,inclusive:!1})}function Or(t,e){return new Uv({check:"greater_than",...oe(e),value:t,inclusive:!0})}function w_(t){return Pi(0,t)}function $_(t){return Ii(0,t)}function E_(t){return an(0,t)}function k_(t){return Or(0,t)}function qa(t,e){return new hk({check:"multiple_of",...oe(e),value:t})}function Fa(t,e){return new yk({check:"max_size",...oe(e),maximum:t})}function Oi(t,e){return new _k({check:"min_size",...oe(e),minimum:t})}function Yo(t,e){return new bk({check:"size_equals",...oe(e),size:t})}function Qo(t,e){return new xk({check:"max_length",...oe(e),maximum:t})}function na(t,e){return new Sk({check:"min_length",...oe(e),minimum:t})}function es(t,e){return new wk({check:"length_equals",...oe(e),length:t})}function vu(t,e){return new $k({check:"string_format",format:"regex",...oe(e),pattern:t})}function yu(t){return new Ek({check:"string_format",format:"lowercase",...oe(t)})}function _u(t){return new kk({check:"string_format",format:"uppercase",...oe(t)})}function bu(t,e){return new Tk({check:"string_format",format:"includes",...oe(e),includes:t})}function xu(t,e){return new Ik({check:"string_format",format:"starts_with",...oe(e),prefix:t})}function Su(t,e){return new Pk({check:"string_format",format:"ends_with",...oe(e),suffix:t})}function T_(t,e,r){return new Ok({check:"property",property:t,schema:e,...oe(r)})}function wu(t,e){return new Rk({check:"mime_type",mime:t,...oe(e)})}function ai(t){return new Ck({check:"overwrite",tx:t})}function $u(t){return ai(e=>e.normalize(t))}function Eu(){return ai(t=>t.trim())}function ku(){return ai(t=>t.toLowerCase())}function Tu(){return ai(t=>t.toUpperCase())}function Lp(){return ai(t=>iv(t))}function Yk(t,e,r){return new t({type:"array",element:e,...oe(r)})}function I_(t,e){return new t({type:"file",...oe(e)})}function P_(t,e,r){let n=oe(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function O_(t,e,r){return new t({type:"custom",check:"custom",fn:e,...oe(r)})}function R_(t){let e=Y9(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Jo(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(Jo(i))}},t(r.value,r)));return e}function Y9(t,e){let r=new $t({check:"custom",...oe(e)});return r._zod.check=t,r}function C_(t){let e=new $t({check:"describe"});return e._zod.onattach=[r=>{let n=Pr.get(r)??{};Pr.add(r,{...n,description:t})}],e._zod.check=()=>{},e}function N_(t){let e=new $t({check:"meta"});return e._zod.onattach=[r=>{let n=Pr.get(r)??{};Pr.add(r,{...n,...t})}],e._zod.check=()=>{},e}function j_(t,e){let r=oe(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 a=new Set(n),o=new Set(i),s=t.Codec??mu,c=t.Boolean??pu,u=t.String??La,l=new u({type:"string",error:r.error}),d=new c({type:"boolean",error:r.error}),p=new s({type:"pipe",in:l,out:d,transform:((f,g)=>{let _=f;return r.case!=="sensitive"&&(_=_.toLowerCase()),a.has(_)?!0:o.has(_)?!1:(g.issues.push({code:"invalid_value",expected:"stringbool",values:[...a,...o],input:g.value,inst:p,continue:!1}),{})}),reverseTransform:((f,g)=>f===!0?n[0]||"true":i[0]||"false"),error:r.error});return p}function ts(t,e,r,n={}){let i=oe(n),a={...oe(n),check:"string_format",type:"string",format:e,fn:typeof r=="function"?r:s=>r.test(s),...i};return r instanceof RegExp&&(a.pattern=r),new t(a)}function qp(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??Pr,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 Ot(t,e,r={path:[],schemaPath:[]}){var n;let i=t._zod.def,a=e.seen.get(t);if(a)return a.count++,r.schemaPath.includes(t)&&(a.cycle=r.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,o);let s=t._zod.toJSONSchema?.();if(s)o.schema=s;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),Ot(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"&&Rr(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 Fp(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 s=t.metadataRegistry.get(o[0])?.id;if(s){let c=n.get(s);if(c&&c!==o[0])throw new Error(`Duplicate schema id "${s}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(s,o[0])}}let i=o=>{let s=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let d=t.external.registry.get(o[0])?.id,p=t.external.uri??(g=>g);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")}#/${s}/${f}`}}if(o[1]===r)return{ref:"#"};let u=`#/${s}/`,l=o[1].schema.id??`__schema${t.counter++}`;return{defId:l,ref:u+l}},a=o=>{if(o[1].schema.$ref)return;let s=o[1],{ref:c,defId:u}=i(o);s.def={...s.schema},u&&(s.defId=u);let l=s.schema;for(let d in l)delete l[d];l.$ref=c};if(t.cycles==="throw")for(let o of t.seen.entries()){let s=o[1];if(s.cycle)throw new Error(`Cycle detected: #/${s.cycle?.join("/")}/ -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let o of t.seen.entries()){let s=o[1];if(e===o[0]){a(o);continue}if(t.external){let u=t.external.registry.get(o[0])?.id;if(e!==o[0]&&u){a(o);continue}}if(t.metadataRegistry.get(o[0])?.id){a(o);continue}if(s.cycle){a(o);continue}if(s.count>1&&t.reused==="ref"){a(o);continue}}}function Zp(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 s=t.seen.get(o);if(s.ref===null)return;let c=s.def??s.schema,u={...c},l=s.ref;if(s.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 _ in c)_==="$ref"||_==="allOf"||_ in u||delete c[_];if(f.$ref)for(let _ in c)_==="$ref"||_==="allOf"||_ in p.def&&JSON.stringify(c[_])===JSON.stringify(p.def[_])&&delete c[_]}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:s.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 a=t.external?.defs??{};for(let o of t.seen.entries()){let s=o[1];s.def&&s.defId&&(a[s.defId]=s.def)}t.external||Object.keys(a).length>0&&(t.target==="draft-2020-12"?i.$defs=a:i.definitions=a);try{let o=JSON.parse(JSON.stringify(i));return Object.defineProperty(o,"~standard",{value:{...e["~standard"],jsonSchema:{input:Iu(e,"input",t.processors),output:Iu(e,"output",t.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function Rr(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 Rr(n.element,r);if(n.type==="set")return Rr(n.valueType,r);if(n.type==="lazy")return Rr(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 Rr(n.innerType,r);if(n.type==="intersection")return Rr(n.left,r)||Rr(n.right,r);if(n.type==="record"||n.type==="map")return Rr(n.keyType,r)||Rr(n.valueType,r);if(n.type==="pipe")return Rr(n.in,r)||Rr(n.out,r);if(n.type==="object"){for(let i in n.shape)if(Rr(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(let i of n.options)if(Rr(i,r))return!0;return!1}if(n.type==="tuple"){for(let i of n.items)if(Rr(i,r))return!0;return!!(n.rest&&Rr(n.rest,r))}return!1}var Qk=(t,e={})=>r=>{let n=qp({...r,processors:e});return Ot(t,n),Fp(n,t),Zp(n,t)},Iu=(t,e,r={})=>n=>{let{libraryOptions:i,target:a}=n??{},o=qp({...i??{},target:a,io:e,processors:r});return Ot(t,o),Fp(o,t),Zp(o,t)};var Q9={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},eT=(t,e,r,n)=>{let i=r;i.type="string";let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof a=="number"&&(i.minLength=a),typeof o=="number"&&(i.maxLength=o),s&&(i.format=Q9[s]??s,i.format===""&&delete i.format,s==="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}))])}},tT=(t,e,r,n)=>{let i=r,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=t._zod.bag;typeof s=="string"&&s.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 a=="number"&&(i.minimum=a,typeof l=="number"&&e.target!=="draft-04"&&(l>=a?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)},rT=(t,e,r,n)=>{r.type="boolean"},nT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},iT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},aT=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},oT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},sT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},cT=(t,e,r,n)=>{r.not={}},uT=(t,e,r,n)=>{},lT=(t,e,r,n)=>{},dT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},pT=(t,e,r,n)=>{let i=t._zod.def,a=Jc(i.entries);a.every(o=>typeof o=="number")&&(r.type="number"),a.every(o=>typeof o=="string")&&(r.type="string"),r.enum=a},fT=(t,e,r,n)=>{let i=t._zod.def,a=[];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");a.push(Number(o))}else a.push(o);if(a.length!==0)if(a.length===1){let o=a[0];r.type=o===null?"null":typeof o,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[o]:r.const=o}else a.every(o=>typeof o=="number")&&(r.type="number"),a.every(o=>typeof o=="string")&&(r.type="string"),a.every(o=>typeof o=="boolean")&&(r.type="boolean"),a.every(o=>o===null)&&(r.type="null"),r.enum=a},mT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},hT=(t,e,r,n)=>{let i=r,a=t._zod.pattern;if(!a)throw new Error("Pattern not found in template literal");i.type="string",i.pattern=a.source},gT=(t,e,r,n)=>{let i=r,a={type:"string",format:"binary",contentEncoding:"binary"},{minimum:o,maximum:s,mime:c}=t._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(u=>({contentMediaType:u}))):Object.assign(i,a)},vT=(t,e,r,n)=>{r.type="boolean"},yT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},_T=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},bT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},xT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},ST=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},wT=(t,e,r,n)=>{let i=r,a=t._zod.def,{minimum:o,maximum:s}=t._zod.bag;typeof o=="number"&&(i.minItems=o),typeof s=="number"&&(i.maxItems=s),i.type="array",i.items=Ot(a.element,e,{...n,path:[...n.path,"items"]})},$T=(t,e,r,n)=>{let i=r,a=t._zod.def;i.type="object",i.properties={};let o=a.shape;for(let u in o)i.properties[u]=Ot(o[u],e,{...n,path:[...n.path,"properties",u]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(u=>{let l=a.shape[u]._zod;return e.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type==="never"?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=Ot(a.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(i.additionalProperties=!1)},A_=(t,e,r,n)=>{let i=t._zod.def,a=i.inclusive===!1,o=i.options.map((s,c)=>Ot(s,e,{...n,path:[...n.path,a?"oneOf":"anyOf",c]}));a?r.oneOf=o:r.anyOf=o},ET=(t,e,r,n)=>{let i=t._zod.def,a=Ot(i.left,e,{...n,path:[...n.path,"allOf",0]}),o=Ot(i.right,e,{...n,path:[...n.path,"allOf",1]}),s=u=>"allOf"in u&&Object.keys(u).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];r.allOf=c},kT=(t,e,r,n)=>{let i=r,a=t._zod.def;i.type="array";let o=e.target==="draft-2020-12"?"prefixItems":"items",s=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=a.items.map((p,f)=>Ot(p,e,{...n,path:[...n.path,o,f]})),u=a.rest?Ot(a.rest,e,{...n,path:[...n.path,s,...e.target==="openapi-3.0"?[a.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)},TT=(t,e,r,n)=>{let i=r,a=t._zod.def;i.type="object";let o=a.keyType,c=o._zod.bag?.patterns;if(a.mode==="loose"&&c&&c.size>0){let l=Ot(a.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=Ot(a.keyType,e,{...n,path:[...n.path,"propertyNames"]})),i.additionalProperties=Ot(a.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)}},IT=(t,e,r,n)=>{let i=t._zod.def,a=Ot(i.innerType,e,n),o=e.seen.get(t);e.target==="openapi-3.0"?(o.ref=i.innerType,r.nullable=!0):r.anyOf=[a,{type:"null"}]},PT=(t,e,r,n)=>{let i=t._zod.def;Ot(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType},OT=(t,e,r,n)=>{let i=t._zod.def;Ot(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))},RT=(t,e,r,n)=>{let i=t._zod.def;Ot(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},CT=(t,e,r,n)=>{let i=t._zod.def;Ot(i.innerType,e,n);let a=e.seen.get(t);a.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},NT=(t,e,r,n)=>{let i=t._zod.def,a=e.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;Ot(a,e,n);let o=e.seen.get(t);o.ref=a},jT=(t,e,r,n)=>{let i=t._zod.def;Ot(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType,r.readOnly=!0},AT=(t,e,r,n)=>{let i=t._zod.def;Ot(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType},M_=(t,e,r,n)=>{let i=t._zod.def;Ot(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType},MT=(t,e,r,n)=>{let i=t._zod.innerType;Ot(i,e,n);let a=e.seen.get(t);a.ref=i};function rs(t){return!!t._zod}function Un(t,e){return rs(t)?Xo(t,e):t.safeParse(e)}function Hp(t){if(!t)return;let e;if(rs(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function LT(t){if(rs(t)){let a=t._zod?.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.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 Pu={};pn(Pu,{ZodAny:()=>i1,ZodArray:()=>c1,ZodBase64:()=>ob,ZodBase64URL:()=>sb,ZodBigInt:()=>Qp,ZodBigIntFormat:()=>lb,ZodBoolean:()=>Yp,ZodCIDRv4:()=>ib,ZodCIDRv6:()=>ab,ZodCUID:()=>X_,ZodCUID2:()=>Y_,ZodCatch:()=>I1,ZodCodec:()=>vb,ZodCustom:()=>af,ZodCustomStringFormat:()=>Ru,ZodDate:()=>pb,ZodDefault:()=>S1,ZodDiscriminatedUnion:()=>l1,ZodE164:()=>cb,ZodEmail:()=>W_,ZodEmoji:()=>K_,ZodEnum:()=>Ou,ZodExactOptional:()=>_1,ZodFile:()=>v1,ZodFunction:()=>D1,ZodGUID:()=>Vp,ZodIPv4:()=>rb,ZodIPv6:()=>nb,ZodIntersection:()=>d1,ZodJWT:()=>ub,ZodKSUID:()=>tb,ZodLazy:()=>j1,ZodLiteral:()=>g1,ZodMAC:()=>e1,ZodMap:()=>m1,ZodNaN:()=>O1,ZodNanoID:()=>J_,ZodNever:()=>o1,ZodNonOptional:()=>hb,ZodNull:()=>n1,ZodNullable:()=>x1,ZodNumber:()=>Xp,ZodNumberFormat:()=>ns,ZodObject:()=>ef,ZodOptional:()=>mb,ZodPipe:()=>gb,ZodPrefault:()=>$1,ZodPromise:()=>M1,ZodReadonly:()=>R1,ZodRecord:()=>nf,ZodSet:()=>h1,ZodString:()=>Kp,ZodStringFormat:()=>Et,ZodSuccess:()=>T1,ZodSymbol:()=>t1,ZodTemplateLiteral:()=>N1,ZodTransform:()=>y1,ZodTuple:()=>p1,ZodType:()=>ze,ZodULID:()=>Q_,ZodURL:()=>Jp,ZodUUID:()=>Ri,ZodUndefined:()=>r1,ZodUnion:()=>tf,ZodUnknown:()=>a1,ZodVoid:()=>s1,ZodXID:()=>eb,ZodXor:()=>u1,_ZodString:()=>G_,_default:()=>w1,_function:()=>vF,any:()=>Q8,array:()=>We,base64:()=>M8,base64url:()=>D8,bigint:()=>W8,boolean:()=>er,catch:()=>P1,check:()=>yF,cidrv4:()=>j8,cidrv6:()=>A8,codec:()=>mF,cuid:()=>k8,cuid2:()=>T8,custom:()=>yb,date:()=>tF,describe:()=>_F,discriminatedUnion:()=>rf,e164:()=>z8,email:()=>g8,emoji:()=>$8,enum:()=>yr,exactOptional:()=>b1,file:()=>lF,float32:()=>H8,float64:()=>B8,function:()=>vF,guid:()=>v8,hash:()=>Z8,hex:()=>F8,hostname:()=>q8,httpUrl:()=>w8,instanceof:()=>xF,int:()=>V_,int32:()=>V8,int64:()=>K8,intersection:()=>Nu,ipv4:()=>R8,ipv6:()=>N8,json:()=>wF,jwt:()=>U8,keyof:()=>rF,ksuid:()=>O8,lazy:()=>A1,literal:()=>ve,looseObject:()=>vr,looseRecord:()=>oF,mac:()=>C8,map:()=>sF,meta:()=>bF,nan:()=>fF,nanoid:()=>E8,nativeEnum:()=>uF,never:()=>db,nonoptional:()=>k1,null:()=>Cu,nullable:()=>Gp,nullish:()=>dF,number:()=>ft,object:()=>le,optional:()=>At,partialRecord:()=>aF,pipe:()=>Wp,prefault:()=>E1,preprocess:()=>of,promise:()=>gF,readonly:()=>C1,record:()=>Rt,refine:()=>z1,set:()=>cF,strictObject:()=>nF,string:()=>H,stringFormat:()=>L8,stringbool:()=>SF,success:()=>pF,superRefine:()=>U1,symbol:()=>X8,templateLiteral:()=>hF,transform:()=>fb,tuple:()=>f1,uint32:()=>G8,uint64:()=>J8,ulid:()=>I8,undefined:()=>Y8,union:()=>xt,unknown:()=>kt,url:()=>S8,uuid:()=>y8,uuidv4:()=>_8,uuidv6:()=>b8,uuidv7:()=>x8,void:()=>eF,xid:()=>P8,xor:()=>iF});var Bp={};pn(Bp,{endsWith:()=>Su,gt:()=>Pi,gte:()=>Or,includes:()=>bu,length:()=>es,lowercase:()=>yu,lt:()=>Ii,lte:()=>on,maxLength:()=>Qo,maxSize:()=>Fa,mime:()=>wu,minLength:()=>na,minSize:()=>Oi,multipleOf:()=>qa,negative:()=>$_,nonnegative:()=>k_,nonpositive:()=>E_,normalize:()=>$u,overwrite:()=>ai,positive:()=>w_,property:()=>T_,regex:()=>vu,size:()=>Yo,slugify:()=>Lp,startsWith:()=>xu,toLowerCase:()=>ku,toUpperCase:()=>Tu,trim:()=>Eu,uppercase:()=>_u});var Za={};pn(Za,{ZodISODate:()=>L_,ZodISODateTime:()=>z_,ZodISODuration:()=>H_,ZodISOTime:()=>F_,date:()=>q_,datetime:()=>U_,duration:()=>B_,time:()=>Z_});var z_=q("ZodISODateTime",(t,e)=>{Yv.init(t,e),Et.init(t,e)});function U_(t){return e_(z_,t)}var L_=q("ZodISODate",(t,e)=>{Qv.init(t,e),Et.init(t,e)});function q_(t){return t_(L_,t)}var F_=q("ZodISOTime",(t,e)=>{ey.init(t,e),Et.init(t,e)});function Z_(t){return r_(F_,t)}var H_=q("ZodISODuration",(t,e)=>{ty.init(t,e),Et.init(t,e)});function B_(t){return n_(H_,t)}var qT=(t,e)=>{ap.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>sp(t,r)},flatten:{value:r=>op(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,Wo,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,Wo,2)}},isEmpty:{get(){return t.issues.length===0}}})},sbe=q("ZodError",qT),sn=q("ZodError",qT,{Parent:Error});var FT=ru(sn),ZT=iu(sn),HT=ou(sn),BT=su(sn),VT=rk(sn),GT=nk(sn),WT=ik(sn),KT=ak(sn),JT=ok(sn),XT=sk(sn),YT=ck(sn),QT=uk(sn);var ze=q("ZodType",(t,e)=>(Ae.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:Iu(t,"input"),output:Iu(t,"output")}}),t.toJSONSchema=Qk(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone(ee.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)=>Ir(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>FT(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>HT(t,r,n),t.parseAsync=async(r,n)=>ZT(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>BT(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>VT(t,r,n),t.decode=(r,n)=>GT(t,r,n),t.encodeAsync=async(r,n)=>WT(t,r,n),t.decodeAsync=async(r,n)=>KT(t,r,n),t.safeEncode=(r,n)=>JT(t,r,n),t.safeDecode=(r,n)=>XT(t,r,n),t.safeEncodeAsync=async(r,n)=>YT(t,r,n),t.safeDecodeAsync=async(r,n)=>QT(t,r,n),t.refine=(r,n)=>t.check(z1(r,n)),t.superRefine=r=>t.check(U1(r)),t.overwrite=r=>t.check(ai(r)),t.optional=()=>At(t),t.exactOptional=()=>b1(t),t.nullable=()=>Gp(t),t.nullish=()=>At(Gp(t)),t.nonoptional=r=>k1(t,r),t.array=()=>We(t),t.or=r=>xt([t,r]),t.and=r=>Nu(t,r),t.transform=r=>Wp(t,fb(r)),t.default=r=>w1(t,r),t.prefault=r=>E1(t,r),t.catch=r=>P1(t,r),t.pipe=r=>Wp(t,r),t.readonly=()=>C1(t),t.describe=r=>{let n=t.clone();return Pr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Pr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Pr.get(t);let n=t.clone();return Pr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t.apply=r=>r(t),t)),G_=q("_ZodString",(t,e)=>{La.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(n,i,a)=>eT(t,n,i,a);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(vu(...n)),t.includes=(...n)=>t.check(bu(...n)),t.startsWith=(...n)=>t.check(xu(...n)),t.endsWith=(...n)=>t.check(Su(...n)),t.min=(...n)=>t.check(na(...n)),t.max=(...n)=>t.check(Qo(...n)),t.length=(...n)=>t.check(es(...n)),t.nonempty=(...n)=>t.check(na(1,...n)),t.lowercase=n=>t.check(yu(n)),t.uppercase=n=>t.check(_u(n)),t.trim=()=>t.check(Eu()),t.normalize=(...n)=>t.check($u(...n)),t.toLowerCase=()=>t.check(ku()),t.toUpperCase=()=>t.check(Tu()),t.slugify=()=>t.check(Lp())}),Kp=q("ZodString",(t,e)=>{La.init(t,e),G_.init(t,e),t.email=r=>t.check(bp(W_,r)),t.url=r=>t.check(gu(Jp,r)),t.jwt=r=>t.check(Up(ub,r)),t.emoji=r=>t.check(Ep(K_,r)),t.guid=r=>t.check(hu(Vp,r)),t.uuid=r=>t.check(xp(Ri,r)),t.uuidv4=r=>t.check(Sp(Ri,r)),t.uuidv6=r=>t.check(wp(Ri,r)),t.uuidv7=r=>t.check($p(Ri,r)),t.nanoid=r=>t.check(kp(J_,r)),t.guid=r=>t.check(hu(Vp,r)),t.cuid=r=>t.check(Tp(X_,r)),t.cuid2=r=>t.check(Ip(Y_,r)),t.ulid=r=>t.check(Pp(Q_,r)),t.base64=r=>t.check(Mp(ob,r)),t.base64url=r=>t.check(Dp(sb,r)),t.xid=r=>t.check(Op(eb,r)),t.ksuid=r=>t.check(Rp(tb,r)),t.ipv4=r=>t.check(Cp(rb,r)),t.ipv6=r=>t.check(Np(nb,r)),t.cidrv4=r=>t.check(jp(ib,r)),t.cidrv6=r=>t.check(Ap(ab,r)),t.e164=r=>t.check(zp(cb,r)),t.datetime=r=>t.check(U_(r)),t.date=r=>t.check(q_(r)),t.time=r=>t.check(Z_(r)),t.duration=r=>t.check(B_(r))});function H(t){return Yy(Kp,t)}var Et=q("ZodStringFormat",(t,e)=>{bt.init(t,e),G_.init(t,e)}),W_=q("ZodEmail",(t,e)=>{Zv.init(t,e),Et.init(t,e)});function g8(t){return bp(W_,t)}var Vp=q("ZodGUID",(t,e)=>{qv.init(t,e),Et.init(t,e)});function v8(t){return hu(Vp,t)}var Ri=q("ZodUUID",(t,e)=>{Fv.init(t,e),Et.init(t,e)});function y8(t){return xp(Ri,t)}function _8(t){return Sp(Ri,t)}function b8(t){return wp(Ri,t)}function x8(t){return $p(Ri,t)}var Jp=q("ZodURL",(t,e)=>{Hv.init(t,e),Et.init(t,e)});function S8(t){return gu(Jp,t)}function w8(t){return gu(Jp,{protocol:/^https?$/,hostname:hn.domain,...ee.normalizeParams(t)})}var K_=q("ZodEmoji",(t,e)=>{Bv.init(t,e),Et.init(t,e)});function $8(t){return Ep(K_,t)}var J_=q("ZodNanoID",(t,e)=>{Vv.init(t,e),Et.init(t,e)});function E8(t){return kp(J_,t)}var X_=q("ZodCUID",(t,e)=>{Gv.init(t,e),Et.init(t,e)});function k8(t){return Tp(X_,t)}var Y_=q("ZodCUID2",(t,e)=>{Wv.init(t,e),Et.init(t,e)});function T8(t){return Ip(Y_,t)}var Q_=q("ZodULID",(t,e)=>{Kv.init(t,e),Et.init(t,e)});function I8(t){return Pp(Q_,t)}var eb=q("ZodXID",(t,e)=>{Jv.init(t,e),Et.init(t,e)});function P8(t){return Op(eb,t)}var tb=q("ZodKSUID",(t,e)=>{Xv.init(t,e),Et.init(t,e)});function O8(t){return Rp(tb,t)}var rb=q("ZodIPv4",(t,e)=>{ry.init(t,e),Et.init(t,e)});function R8(t){return Cp(rb,t)}var e1=q("ZodMAC",(t,e)=>{iy.init(t,e),Et.init(t,e)});function C8(t){return Qy(e1,t)}var nb=q("ZodIPv6",(t,e)=>{ny.init(t,e),Et.init(t,e)});function N8(t){return Np(nb,t)}var ib=q("ZodCIDRv4",(t,e)=>{ay.init(t,e),Et.init(t,e)});function j8(t){return jp(ib,t)}var ab=q("ZodCIDRv6",(t,e)=>{oy.init(t,e),Et.init(t,e)});function A8(t){return Ap(ab,t)}var ob=q("ZodBase64",(t,e)=>{sy.init(t,e),Et.init(t,e)});function M8(t){return Mp(ob,t)}var sb=q("ZodBase64URL",(t,e)=>{cy.init(t,e),Et.init(t,e)});function D8(t){return Dp(sb,t)}var cb=q("ZodE164",(t,e)=>{uy.init(t,e),Et.init(t,e)});function z8(t){return zp(cb,t)}var ub=q("ZodJWT",(t,e)=>{ly.init(t,e),Et.init(t,e)});function U8(t){return Up(ub,t)}var Ru=q("ZodCustomStringFormat",(t,e)=>{dy.init(t,e),Et.init(t,e)});function L8(t,e,r={}){return ts(Ru,t,e,r)}function q8(t){return ts(Ru,"hostname",hn.hostname,t)}function F8(t){return ts(Ru,"hex",hn.hex,t)}function Z8(t,e){let r=e?.enc??"hex",n=`${t}_${r}`,i=hn[n];if(!i)throw new Error(`Unrecognized hash format: ${n}`);return ts(Ru,n,i,e)}var Xp=q("ZodNumber",(t,e)=>{gp.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(n,i,a)=>tT(t,n,i,a),t.gt=(n,i)=>t.check(Pi(n,i)),t.gte=(n,i)=>t.check(Or(n,i)),t.min=(n,i)=>t.check(Or(n,i)),t.lt=(n,i)=>t.check(Ii(n,i)),t.lte=(n,i)=>t.check(on(n,i)),t.max=(n,i)=>t.check(on(n,i)),t.int=n=>t.check(V_(n)),t.safe=n=>t.check(V_(n)),t.positive=n=>t.check(Pi(0,n)),t.nonnegative=n=>t.check(Or(0,n)),t.negative=n=>t.check(Ii(0,n)),t.nonpositive=n=>t.check(on(0,n)),t.multipleOf=(n,i)=>t.check(qa(n,i)),t.step=(n,i)=>t.check(qa(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 ft(t){return i_(Xp,t)}var ns=q("ZodNumberFormat",(t,e)=>{py.init(t,e),Xp.init(t,e)});function V_(t){return a_(ns,t)}function H8(t){return o_(ns,t)}function B8(t){return s_(ns,t)}function V8(t){return c_(ns,t)}function G8(t){return u_(ns,t)}var Yp=q("ZodBoolean",(t,e)=>{pu.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>rT(t,r,n,i)});function er(t){return l_(Yp,t)}var Qp=q("ZodBigInt",(t,e)=>{vp.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(n,i,a)=>nT(t,n,i,a),t.gte=(n,i)=>t.check(Or(n,i)),t.min=(n,i)=>t.check(Or(n,i)),t.gt=(n,i)=>t.check(Pi(n,i)),t.gte=(n,i)=>t.check(Or(n,i)),t.min=(n,i)=>t.check(Or(n,i)),t.lt=(n,i)=>t.check(Ii(n,i)),t.lte=(n,i)=>t.check(on(n,i)),t.max=(n,i)=>t.check(on(n,i)),t.positive=n=>t.check(Pi(BigInt(0),n)),t.negative=n=>t.check(Ii(BigInt(0),n)),t.nonpositive=n=>t.check(on(BigInt(0),n)),t.nonnegative=n=>t.check(Or(BigInt(0),n)),t.multipleOf=(n,i)=>t.check(qa(n,i));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});function W8(t){return d_(Qp,t)}var lb=q("ZodBigIntFormat",(t,e)=>{fy.init(t,e),Qp.init(t,e)});function K8(t){return p_(lb,t)}function J8(t){return f_(lb,t)}var t1=q("ZodSymbol",(t,e)=>{my.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>iT(t,r,n,i)});function X8(t){return m_(t1,t)}var r1=q("ZodUndefined",(t,e)=>{hy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>oT(t,r,n,i)});function Y8(t){return h_(r1,t)}var n1=q("ZodNull",(t,e)=>{gy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>aT(t,r,n,i)});function Cu(t){return g_(n1,t)}var i1=q("ZodAny",(t,e)=>{vy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>uT(t,r,n,i)});function Q8(){return v_(i1)}var a1=q("ZodUnknown",(t,e)=>{yy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lT(t,r,n,i)});function kt(){return y_(a1)}var o1=q("ZodNever",(t,e)=>{_y.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>cT(t,r,n,i)});function db(t){return __(o1,t)}var s1=q("ZodVoid",(t,e)=>{by.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>sT(t,r,n,i)});function eF(t){return b_(s1,t)}var pb=q("ZodDate",(t,e)=>{xy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(n,i,a)=>dT(t,n,i,a),t.min=(n,i)=>t.check(Or(n,i)),t.max=(n,i)=>t.check(on(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 tF(t){return x_(pb,t)}var c1=q("ZodArray",(t,e)=>{Sy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>wT(t,r,n,i),t.element=e.element,t.min=(r,n)=>t.check(na(r,n)),t.nonempty=r=>t.check(na(1,r)),t.max=(r,n)=>t.check(Qo(r,n)),t.length=(r,n)=>t.check(es(r,n)),t.unwrap=()=>t.element});function We(t,e){return Yk(c1,t,e)}function rF(t){let e=t._zod.def.shape;return yr(Object.keys(e))}var ef=q("ZodObject",(t,e)=>{Jk.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>$T(t,r,n,i),ee.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>yr(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:kt()}),t.loose=()=>t.clone({...t._zod.def,catchall:kt()}),t.strict=()=>t.clone({...t._zod.def,catchall:db()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ee.extend(t,r),t.safeExtend=r=>ee.safeExtend(t,r),t.merge=r=>ee.merge(t,r),t.pick=r=>ee.pick(t,r),t.omit=r=>ee.omit(t,r),t.partial=(...r)=>ee.partial(mb,t,r[0]),t.required=(...r)=>ee.required(hb,t,r[0])});function le(t,e){let r={type:"object",shape:t??{},...ee.normalizeParams(e)};return new ef(r)}function nF(t,e){return new ef({type:"object",shape:t,catchall:db(),...ee.normalizeParams(e)})}function vr(t,e){return new ef({type:"object",shape:t,catchall:kt(),...ee.normalizeParams(e)})}var tf=q("ZodUnion",(t,e)=>{fu.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>A_(t,r,n,i),t.options=e.options});function xt(t,e){return new tf({type:"union",options:t,...ee.normalizeParams(e)})}var u1=q("ZodXor",(t,e)=>{tf.init(t,e),wy.init(t,e),t._zod.processJSONSchema=(r,n,i)=>A_(t,r,n,i),t.options=e.options});function iF(t,e){return new u1({type:"union",options:t,inclusive:!1,...ee.normalizeParams(e)})}var l1=q("ZodDiscriminatedUnion",(t,e)=>{tf.init(t,e),$y.init(t,e)});function rf(t,e,r){return new l1({type:"union",options:e,discriminator:t,...ee.normalizeParams(r)})}var d1=q("ZodIntersection",(t,e)=>{Ey.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>ET(t,r,n,i)});function Nu(t,e){return new d1({type:"intersection",left:t,right:e})}var p1=q("ZodTuple",(t,e)=>{yp.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>kT(t,r,n,i),t.rest=r=>t.clone({...t._zod.def,rest:r})});function f1(t,e,r){let n=e instanceof Ae,i=n?r:e,a=n?e:null;return new p1({type:"tuple",items:t,rest:a,...ee.normalizeParams(i)})}var nf=q("ZodRecord",(t,e)=>{ky.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>TT(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType});function Rt(t,e,r){return new nf({type:"record",keyType:t,valueType:e,...ee.normalizeParams(r)})}function aF(t,e,r){let n=Ir(t);return n._zod.values=void 0,new nf({type:"record",keyType:n,valueType:e,...ee.normalizeParams(r)})}function oF(t,e,r){return new nf({type:"record",keyType:t,valueType:e,mode:"loose",...ee.normalizeParams(r)})}var m1=q("ZodMap",(t,e)=>{Ty.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>xT(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(Oi(...r)),t.nonempty=r=>t.check(Oi(1,r)),t.max=(...r)=>t.check(Fa(...r)),t.size=(...r)=>t.check(Yo(...r))});function sF(t,e,r){return new m1({type:"map",keyType:t,valueType:e,...ee.normalizeParams(r)})}var h1=q("ZodSet",(t,e)=>{Iy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>ST(t,r,n,i),t.min=(...r)=>t.check(Oi(...r)),t.nonempty=r=>t.check(Oi(1,r)),t.max=(...r)=>t.check(Fa(...r)),t.size=(...r)=>t.check(Yo(...r))});function cF(t,e){return new h1({type:"set",valueType:t,...ee.normalizeParams(e)})}var Ou=q("ZodEnum",(t,e)=>{Py.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(n,i,a)=>pT(t,n,i,a),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,i)=>{let a={};for(let o of n)if(r.has(o))a[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Ou({...e,checks:[],...ee.normalizeParams(i),entries:a})},t.exclude=(n,i)=>{let a={...e.entries};for(let o of n)if(r.has(o))delete a[o];else throw new Error(`Key ${o} not found in enum`);return new Ou({...e,checks:[],...ee.normalizeParams(i),entries:a})}});function yr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Ou({type:"enum",entries:r,...ee.normalizeParams(e)})}function uF(t,e){return new Ou({type:"enum",entries:t,...ee.normalizeParams(e)})}var g1=q("ZodLiteral",(t,e)=>{Oy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>fT(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 ve(t,e){return new g1({type:"literal",values:Array.isArray(t)?t:[t],...ee.normalizeParams(e)})}var v1=q("ZodFile",(t,e)=>{Ry.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>gT(t,r,n,i),t.min=(r,n)=>t.check(Oi(r,n)),t.max=(r,n)=>t.check(Fa(r,n)),t.mime=(r,n)=>t.check(wu(Array.isArray(r)?r:[r],n))});function lF(t){return I_(v1,t)}var y1=q("ZodTransform",(t,e)=>{Cy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>bT(t,r,n,i),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Da(t.constructor.name);r.addIssue=a=>{if(typeof a=="string")r.issues.push(ee.issue(a,r.value,e));else{let o=a;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),r.issues.push(ee.issue(o))}};let i=e.transform(r.value,r);return i instanceof Promise?i.then(a=>(r.value=a,r)):(r.value=i,r)}});function fb(t){return new y1({type:"transform",transform:t})}var mb=q("ZodOptional",(t,e)=>{_p.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>M_(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function At(t){return new mb({type:"optional",innerType:t})}var _1=q("ZodExactOptional",(t,e)=>{Ny.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>M_(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function b1(t){return new _1({type:"optional",innerType:t})}var x1=q("ZodNullable",(t,e)=>{jy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>IT(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Gp(t){return new x1({type:"nullable",innerType:t})}function dF(t){return At(Gp(t))}var S1=q("ZodDefault",(t,e)=>{Ay.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>OT(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function w1(t,e){return new S1({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():ee.shallowClone(e)}})}var $1=q("ZodPrefault",(t,e)=>{My.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>RT(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function E1(t,e){return new $1({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():ee.shallowClone(e)}})}var hb=q("ZodNonOptional",(t,e)=>{Dy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>PT(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function k1(t,e){return new hb({type:"nonoptional",innerType:t,...ee.normalizeParams(e)})}var T1=q("ZodSuccess",(t,e)=>{zy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>vT(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function pF(t){return new T1({type:"success",innerType:t})}var I1=q("ZodCatch",(t,e)=>{Uy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>CT(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function P1(t,e){return new I1({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var O1=q("ZodNaN",(t,e)=>{Ly.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>mT(t,r,n,i)});function fF(t){return S_(O1,t)}var gb=q("ZodPipe",(t,e)=>{qy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>NT(t,r,n,i),t.in=e.in,t.out=e.out});function Wp(t,e){return new gb({type:"pipe",in:t,out:e})}var vb=q("ZodCodec",(t,e)=>{gb.init(t,e),mu.init(t,e)});function mF(t,e,r){return new vb({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}var R1=q("ZodReadonly",(t,e)=>{Fy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>jT(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function C1(t){return new R1({type:"readonly",innerType:t})}var N1=q("ZodTemplateLiteral",(t,e)=>{Zy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>hT(t,r,n,i)});function hF(t,e){return new N1({type:"template_literal",parts:t,...ee.normalizeParams(e)})}var j1=q("ZodLazy",(t,e)=>{Vy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>MT(t,r,n,i),t.unwrap=()=>t._zod.def.getter()});function A1(t){return new j1({type:"lazy",getter:t})}var M1=q("ZodPromise",(t,e)=>{By.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>AT(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function gF(t){return new M1({type:"promise",innerType:t})}var D1=q("ZodFunction",(t,e)=>{Hy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>_T(t,r,n,i)});function vF(t){return new D1({type:"function",input:Array.isArray(t?.input)?f1(t?.input):t?.input??We(kt()),output:t?.output??kt()})}var af=q("ZodCustom",(t,e)=>{Gy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>yT(t,r,n,i)});function yF(t){let e=new $t({check:"custom"});return e._zod.check=t,e}function yb(t,e){return P_(af,t??(()=>!0),e)}function z1(t,e={}){return O_(af,t,e)}function U1(t){return R_(t)}var _F=C_,bF=N_;function xF(t,e={}){let r=new af({type:"custom",check:"custom",fn:n=>n instanceof t,abort:!0,...ee.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 SF=(...t)=>j_({Codec:vb,Boolean:Yp,String:Kp},...t);function wF(t){let e=A1(()=>xt([H(t),ft(),er(),Cu(),We(e),Rt(H(),e)]));return e}function of(t,e){return Wp(fb(t),e)}var L1;L1||(L1={});var hbe={...Pu,...Bp,iso:Za};rr(Wy());var bb="2025-11-25";var q1=[bb,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],ia="io.modelcontextprotocol/related-task",cf="2.0",cr=yb(t=>t!==null&&(typeof t=="object"||typeof t=="function")),F1=xt([H(),ft().int()]),Z1=H(),jbe=vr({ttl:xt([ft(),Cu()]).optional(),pollInterval:ft().optional()}),TF=le({ttl:ft().optional()}),IF=le({taskId:H()}),xb=vr({progressToken:F1.optional(),[ia]:IF.optional()}),cn=le({_meta:xb.optional()}),ju=cn.extend({task:TF.optional()}),H1=t=>ju.safeParse(t).success,ur=le({method:H(),params:cn.loose().optional()}),gn=le({_meta:xb.optional()}),vn=le({method:H(),params:gn.loose().optional()}),lr=vr({_meta:xb.optional()}),uf=xt([H(),ft().int()]),B1=le({jsonrpc:ve(cf),id:uf,...ur.shape}).strict(),Sb=t=>B1.safeParse(t).success,V1=le({jsonrpc:ve(cf),...vn.shape}).strict(),G1=t=>V1.safeParse(t).success,wb=le({jsonrpc:ve(cf),id:uf,result:lr}).strict(),Au=t=>wb.safeParse(t).success;var Ce;(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"})(Ce||(Ce={}));var $b=le({jsonrpc:ve(cf),id:uf.optional(),error:le({code:ft().int(),message:H(),data:kt().optional()})}).strict();var W1=t=>$b.safeParse(t).success;var K1=xt([B1,V1,wb,$b]),Abe=xt([wb,$b]),Ha=lr.strict(),PF=gn.extend({requestId:uf.optional(),reason:H().optional()}),lf=vn.extend({method:ve("notifications/cancelled"),params:PF}),OF=le({src:H(),mimeType:H().optional(),sizes:We(H()).optional(),theme:yr(["light","dark"]).optional()}),Mu=le({icons:We(OF).optional()}),is=le({name:H(),title:H().optional()}),J1=is.extend({...is.shape,...Mu.shape,version:H(),websiteUrl:H().optional(),description:H().optional()}),RF=Nu(le({applyDefaults:er().optional()}),Rt(H(),kt())),CF=of(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Nu(le({form:RF.optional(),url:cr.optional()}),Rt(H(),kt()).optional())),NF=vr({list:cr.optional(),cancel:cr.optional(),requests:vr({sampling:vr({createMessage:cr.optional()}).optional(),elicitation:vr({create:cr.optional()}).optional()}).optional()}),jF=vr({list:cr.optional(),cancel:cr.optional(),requests:vr({tools:vr({call:cr.optional()}).optional()}).optional()}),AF=le({experimental:Rt(H(),cr).optional(),sampling:le({context:cr.optional(),tools:cr.optional()}).optional(),elicitation:CF.optional(),roots:le({listChanged:er().optional()}).optional(),tasks:NF.optional()}),MF=cn.extend({protocolVersion:H(),capabilities:AF,clientInfo:J1}),DF=ur.extend({method:ve("initialize"),params:MF});var zF=le({experimental:Rt(H(),cr).optional(),logging:cr.optional(),completions:cr.optional(),prompts:le({listChanged:er().optional()}).optional(),resources:le({subscribe:er().optional(),listChanged:er().optional()}).optional(),tools:le({listChanged:er().optional()}).optional(),tasks:jF.optional()}),Eb=lr.extend({protocolVersion:H(),capabilities:zF,serverInfo:J1,instructions:H().optional()}),UF=vn.extend({method:ve("notifications/initialized"),params:gn.optional()});var df=ur.extend({method:ve("ping"),params:cn.optional()}),LF=le({progress:ft(),total:At(ft()),message:At(H())}),qF=le({...gn.shape,...LF.shape,progressToken:F1}),pf=vn.extend({method:ve("notifications/progress"),params:qF}),FF=cn.extend({cursor:Z1.optional()}),Du=ur.extend({params:FF.optional()}),zu=lr.extend({nextCursor:Z1.optional()}),ZF=yr(["working","input_required","completed","failed","cancelled"]),Uu=le({taskId:H(),status:ZF,ttl:xt([ft(),Cu()]),createdAt:H(),lastUpdatedAt:H(),pollInterval:At(ft()),statusMessage:At(H())}),Ba=lr.extend({task:Uu}),HF=gn.merge(Uu),Lu=vn.extend({method:ve("notifications/tasks/status"),params:HF}),ff=ur.extend({method:ve("tasks/get"),params:cn.extend({taskId:H()})}),mf=lr.merge(Uu),hf=ur.extend({method:ve("tasks/result"),params:cn.extend({taskId:H()})}),Mbe=lr.loose(),gf=Du.extend({method:ve("tasks/list")}),vf=zu.extend({tasks:We(Uu)}),yf=ur.extend({method:ve("tasks/cancel"),params:cn.extend({taskId:H()})}),X1=lr.merge(Uu),Y1=le({uri:H(),mimeType:At(H()),_meta:Rt(H(),kt()).optional()}),Q1=Y1.extend({text:H()}),kb=H().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),eI=Y1.extend({blob:kb}),qu=yr(["user","assistant"]),as=le({audience:We(qu).optional(),priority:ft().min(0).max(1).optional(),lastModified:Za.datetime({offset:!0}).optional()}),tI=le({...is.shape,...Mu.shape,uri:H(),description:At(H()),mimeType:At(H()),annotations:as.optional(),_meta:At(vr({}))}),BF=le({...is.shape,...Mu.shape,uriTemplate:H(),description:At(H()),mimeType:At(H()),annotations:as.optional(),_meta:At(vr({}))}),VF=Du.extend({method:ve("resources/list")}),Tb=zu.extend({resources:We(tI)}),GF=Du.extend({method:ve("resources/templates/list")}),Ib=zu.extend({resourceTemplates:We(BF)}),Pb=cn.extend({uri:H()}),WF=Pb,KF=ur.extend({method:ve("resources/read"),params:WF}),Ob=lr.extend({contents:We(xt([Q1,eI]))}),Rb=vn.extend({method:ve("notifications/resources/list_changed"),params:gn.optional()}),JF=Pb,XF=ur.extend({method:ve("resources/subscribe"),params:JF}),YF=Pb,QF=ur.extend({method:ve("resources/unsubscribe"),params:YF}),e5=gn.extend({uri:H()}),t5=vn.extend({method:ve("notifications/resources/updated"),params:e5}),r5=le({name:H(),description:At(H()),required:At(er())}),n5=le({...is.shape,...Mu.shape,description:At(H()),arguments:At(We(r5)),_meta:At(vr({}))}),i5=Du.extend({method:ve("prompts/list")}),Cb=zu.extend({prompts:We(n5)}),a5=cn.extend({name:H(),arguments:Rt(H(),H()).optional()}),o5=ur.extend({method:ve("prompts/get"),params:a5}),Nb=le({type:ve("text"),text:H(),annotations:as.optional(),_meta:Rt(H(),kt()).optional()}),jb=le({type:ve("image"),data:kb,mimeType:H(),annotations:as.optional(),_meta:Rt(H(),kt()).optional()}),Ab=le({type:ve("audio"),data:kb,mimeType:H(),annotations:as.optional(),_meta:Rt(H(),kt()).optional()}),s5=le({type:ve("tool_use"),name:H(),id:H(),input:Rt(H(),kt()),_meta:Rt(H(),kt()).optional()}),c5=le({type:ve("resource"),resource:xt([Q1,eI]),annotations:as.optional(),_meta:Rt(H(),kt()).optional()}),u5=tI.extend({type:ve("resource_link")}),Mb=xt([Nb,jb,Ab,u5,c5]),l5=le({role:qu,content:Mb}),Db=lr.extend({description:H().optional(),messages:We(l5)}),zb=vn.extend({method:ve("notifications/prompts/list_changed"),params:gn.optional()}),d5=le({title:H().optional(),readOnlyHint:er().optional(),destructiveHint:er().optional(),idempotentHint:er().optional(),openWorldHint:er().optional()}),p5=le({taskSupport:yr(["required","optional","forbidden"]).optional()}),rI=le({...is.shape,...Mu.shape,description:H().optional(),inputSchema:le({type:ve("object"),properties:Rt(H(),cr).optional(),required:We(H()).optional()}).catchall(kt()),outputSchema:le({type:ve("object"),properties:Rt(H(),cr).optional(),required:We(H()).optional()}).catchall(kt()).optional(),annotations:d5.optional(),execution:p5.optional(),_meta:Rt(H(),kt()).optional()}),f5=Du.extend({method:ve("tools/list")}),Ub=zu.extend({tools:We(rI)}),os=lr.extend({content:We(Mb).default([]),structuredContent:Rt(H(),kt()).optional(),isError:er().optional()}),Dbe=os.or(lr.extend({toolResult:kt()})),m5=ju.extend({name:H(),arguments:Rt(H(),kt()).optional()}),h5=ur.extend({method:ve("tools/call"),params:m5}),Lb=vn.extend({method:ve("notifications/tools/list_changed"),params:gn.optional()}),nI=le({autoRefresh:er().default(!0),debounceMs:ft().int().nonnegative().default(300)}),iI=yr(["debug","info","notice","warning","error","critical","alert","emergency"]),g5=cn.extend({level:iI}),v5=ur.extend({method:ve("logging/setLevel"),params:g5}),y5=gn.extend({level:iI,logger:H().optional(),data:kt()}),_5=vn.extend({method:ve("notifications/message"),params:y5}),b5=le({name:H().optional()}),x5=le({hints:We(b5).optional(),costPriority:ft().min(0).max(1).optional(),speedPriority:ft().min(0).max(1).optional(),intelligencePriority:ft().min(0).max(1).optional()}),S5=le({mode:yr(["auto","required","none"]).optional()}),w5=le({type:ve("tool_result"),toolUseId:H().describe("The unique identifier for the corresponding tool call."),content:We(Mb).default([]),structuredContent:le({}).loose().optional(),isError:er().optional(),_meta:Rt(H(),kt()).optional()}),$5=rf("type",[Nb,jb,Ab]),sf=rf("type",[Nb,jb,Ab,s5,w5]),E5=le({role:qu,content:xt([sf,We(sf)]),_meta:Rt(H(),kt()).optional()}),k5=ju.extend({messages:We(E5),modelPreferences:x5.optional(),systemPrompt:H().optional(),includeContext:yr(["none","thisServer","allServers"]).optional(),temperature:ft().optional(),maxTokens:ft().int(),stopSequences:We(H()).optional(),metadata:cr.optional(),tools:We(rI).optional(),toolChoice:S5.optional()}),qb=ur.extend({method:ve("sampling/createMessage"),params:k5}),Fb=lr.extend({model:H(),stopReason:At(yr(["endTurn","stopSequence","maxTokens"]).or(H())),role:qu,content:$5}),T5=lr.extend({model:H(),stopReason:At(yr(["endTurn","stopSequence","maxTokens","toolUse"]).or(H())),role:qu,content:xt([sf,We(sf)])}),I5=le({type:ve("boolean"),title:H().optional(),description:H().optional(),default:er().optional()}),P5=le({type:ve("string"),title:H().optional(),description:H().optional(),minLength:ft().optional(),maxLength:ft().optional(),format:yr(["email","uri","date","date-time"]).optional(),default:H().optional()}),O5=le({type:yr(["number","integer"]),title:H().optional(),description:H().optional(),minimum:ft().optional(),maximum:ft().optional(),default:ft().optional()}),R5=le({type:ve("string"),title:H().optional(),description:H().optional(),enum:We(H()),default:H().optional()}),C5=le({type:ve("string"),title:H().optional(),description:H().optional(),oneOf:We(le({const:H(),title:H()})),default:H().optional()}),N5=le({type:ve("string"),title:H().optional(),description:H().optional(),enum:We(H()),enumNames:We(H()).optional(),default:H().optional()}),j5=xt([R5,C5]),A5=le({type:ve("array"),title:H().optional(),description:H().optional(),minItems:ft().optional(),maxItems:ft().optional(),items:le({type:ve("string"),enum:We(H())}),default:We(H()).optional()}),M5=le({type:ve("array"),title:H().optional(),description:H().optional(),minItems:ft().optional(),maxItems:ft().optional(),items:le({anyOf:We(le({const:H(),title:H()}))}),default:We(H()).optional()}),D5=xt([A5,M5]),z5=xt([N5,j5,D5]),U5=xt([z5,I5,P5,O5]),L5=ju.extend({mode:ve("form").optional(),message:H(),requestedSchema:le({type:ve("object"),properties:Rt(H(),U5),required:We(H()).optional()})}),q5=ju.extend({mode:ve("url"),message:H(),elicitationId:H(),url:H().url()}),F5=xt([L5,q5]),Zb=ur.extend({method:ve("elicitation/create"),params:F5}),Z5=gn.extend({elicitationId:H()}),H5=vn.extend({method:ve("notifications/elicitation/complete"),params:Z5}),Hb=lr.extend({action:yr(["accept","decline","cancel"]),content:of(t=>t===null?void 0:t,Rt(H(),xt([H(),ft(),er(),We(H())])).optional())}),B5=le({type:ve("ref/resource"),uri:H()});var V5=le({type:ve("ref/prompt"),name:H()}),G5=cn.extend({ref:xt([V5,B5]),argument:le({name:H(),value:H()}),context:le({arguments:Rt(H(),H()).optional()}).optional()}),W5=ur.extend({method:ve("completion/complete"),params:G5});var Bb=lr.extend({completion:vr({values:We(H()).max(100),total:At(ft().int()),hasMore:At(er())})}),K5=le({uri:H().startsWith("file://"),name:H().optional(),_meta:Rt(H(),kt()).optional()}),J5=ur.extend({method:ve("roots/list"),params:cn.optional()}),X5=lr.extend({roots:We(K5)}),Y5=vn.extend({method:ve("notifications/roots/list_changed"),params:gn.optional()}),zbe=xt([df,DF,W5,v5,o5,i5,VF,GF,KF,XF,QF,h5,f5,ff,hf,gf,yf]),Ube=xt([lf,pf,UF,Y5,Lu]),Lbe=xt([Ha,Fb,T5,Hb,X5,mf,vf,Ba]),qbe=xt([df,qb,Zb,J5,ff,hf,gf,yf]),Fbe=xt([lf,pf,_5,t5,Rb,Lb,zb,Lu,H5]),Zbe=xt([Ha,Eb,Bb,Db,Cb,Tb,Ib,Ob,os,Ub,mf,vf,Ba]),Se=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===Ce.UrlElicitationRequired&&n){let i=n;if(i.elicitations)return new _b(i.elicitations,r)}return new t(e,r,n)}},_b=class extends Se{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(Ce.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function aa(t){return t==="completed"||t==="failed"||t==="cancelled"}var wxe=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Vb(t){let r=Hp(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=LT(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Gb(t,e){let r=Un(t,e);if(!r.success)throw r.error;return r.data}var i3=6e4,_f=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(lf,r=>{this._oncancel(r)}),this.setNotificationHandler(pf,r=>{this._onprogress(r)}),this.setRequestHandler(df,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ff,async(r,n)=>{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new Se(Ce.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(hf,async(r,n)=>{let i=async()=>{let a=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(a,n.sessionId);){if(s.type==="response"||s.type==="error"){let c=s.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),s.type==="response")l(c);else{let d=c,p=new Se(d.error.code,d.error.message,d.error.data);l(p)}else{let d=s.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:n.requestId})}}let o=await this._taskStore.getTask(a,n.sessionId);if(!o)throw new Se(Ce.InvalidParams,`Task not found: ${a}`);if(!aa(o.status))return await this._waitForTaskUpdate(a,n.signal),await i();if(aa(o.status)){let s=await this._taskStore.getTaskResult(a,n.sessionId);return this._clearTaskQueue(a),{...s,_meta:{...s._meta,[ia]:{taskId:a}}}}return await i()};return await i()}),this.setRequestHandler(gf,async(r,n)=>{try{let{tasks:i,nextCursor:a}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:i,nextCursor:a,_meta:{}}}catch(i){throw new Se(Ce.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(yf,async(r,n)=>{try{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new Se(Ce.InvalidParams,`Task not found: ${r.params.taskId}`);if(aa(i.status))throw new Se(Ce.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 a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new Se(Ce.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...a}}catch(i){throw i instanceof Se?i:new Se(Ce.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,a=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:a,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),Se.fromError(Ce.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=a=>{n?.(a),this._onerror(a)};let i=this._transport?.onmessage;this._transport.onmessage=(a,o)=>{i?.(a,o),Au(a)||W1(a)?this._onresponse(a):Sb(a)?this._onrequest(a,o):G1(a)?this._onnotification(a):this._onerror(new Error(`Unknown message type: ${JSON.stringify(a)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let r=Se.fromError(Ce.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,a=e.params?._meta?.[ia]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:Ce.MethodNotFound,message:"Method not found"}};a&&this._taskMessageQueue?this._enqueueTaskMessage(a,{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 s=H1(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};a&&(d.relatedTask={taskId:a}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{let f={...p,relatedRequestId:e.id};a&&!f.relatedTask&&(f.relatedTask={taskId:a});let g=f.relatedTask?.taskId??a;return g&&c&&await c.updateTaskStatus(g,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:a,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&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};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{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:Ce.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{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),a=this._progressHandlers.get(i);if(!a){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let o=this._responseHandlers.get(i),s=this._timeoutInfo.get(i);if(s&&o&&s.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(c){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),o(c);return}a(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Au(e))n(e);else{let o=new Se(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 a=!1;if(Au(e)&&e.result&&typeof e.result=="object"){let o=e.result;if(o.task&&typeof o.task=="object"){let s=o.task;typeof s.taskId=="string"&&(a=!0,this._taskProgressTokens.set(s.taskId,r))}}if(a||this._progressHandlers.delete(r),Au(e))i(e);else{let o=Se.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 Se?o:new Se(Ce.InternalError,String(o))}}return}let a;try{let o=await this.request(e,Ba,n);if(o.task)a=o.task.taskId,yield{type:"taskCreated",task:o.task};else throw new Se(Ce.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:a},n);if(yield{type:"taskStatus",task:s},aa(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:a},r,n)}:s.status==="failed"?yield{type:"error",error:new Se(Ce.InternalError,`Task ${a} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new Se(Ce.InternalError,`Task ${a} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:a},r,n)};return}let c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(o){yield{type:"error",error:o instanceof Se?o:new Se(Ce.InternalError,String(o))}}}request(e,r,n){let{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,task:s,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=y=>{l(y)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(y){d(y);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}}),s&&(f.params={...f.params,task:s}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[ia]:c}});let g=y=>{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(y)}},{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(b=>this._onerror(new Error(`Failed to send cancellation: ${b}`)));let v=y instanceof Se?y:new Se(Ce.RequestTimeout,String(y));l(v)};this._responseHandlers.set(p,y=>{if(!n?.signal?.aborted){if(y instanceof Error)return l(y);try{let v=Un(r,y.result);v.success?u(v.data):l(v.error)}catch(v){l(v)}}}),n?.signal?.addEventListener("abort",()=>{g(n?.signal?.reason)});let _=n?.timeout??i3,h=()=>g(Se.fromError(Ce.RequestTimeout,"Request timed out",{timeout:_}));this._setupTimeout(p,_,n?.maxTotalTimeout,h,n?.resetTimeoutOnProgress??!1);let m=c?.taskId;if(m){let y=v=>{let b=this._responseHandlers.get(p);b?b(v):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,y),this._enqueueTaskMessage(m,{type:"request",message:f,timestamp:Date.now()}).catch(v=>{this._cleanupTimeout(p),l(v)})}else this._transport.send(f,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(y=>{this._cleanupTimeout(p),l(y)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},mf,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},vf,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},X1,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 s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[ia]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:s,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 s={...e,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[ia]:r.relatedTask}}}),this._transport?.send(s,r).catch(c=>this._onerror(c))});return}let o={...e,jsonrpc:"2.0"};r?.relatedTask&&(o={...o,params:{...o.params,_meta:{...o.params?._meta||{},[ia]:r.relatedTask}}}),await this._transport.send(o,r)}setRequestHandler(e,r){let n=Vb(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,a)=>{let o=Gb(e,i);return Promise.resolve(r(o,a))})}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=Vb(e);this._notificationHandlers.set(n,i=>{let a=Gb(e,i);return Promise.resolve(r(a))})}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"&&Sb(i.message)){let a=i.message.id,o=this._requestResolvers.get(a);o?(o(new Se(Ce.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(a)):this._onerror(new Error(`Resolver missing for request ${a} 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,a)=>{if(r.aborted){a(new Se(Ce.InvalidRequest,"Request cancelled"));return}let o=setTimeout(i,n);r.addEventListener("abort",()=>{clearTimeout(o),a(new Se(Ce.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 a=await n.getTask(i,r);if(!a)throw new Se(Ce.InvalidParams,"Failed to retrieve task: Task not found");return a},storeTaskResult:async(i,a,o)=>{await n.storeTaskResult(i,a,o,r);let s=await n.getTask(i,r);if(s){let c=Lu.parse({method:"notifications/tasks/status",params:s});await this.notification(c),aa(s.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>n.getTaskResult(i,r),updateTaskStatus:async(i,a,o)=>{let s=await n.getTask(i,r);if(!s)throw new Se(Ce.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(aa(s.status))throw new Se(Ce.InvalidParams,`Cannot update task "${i}" from terminal status "${s.status}" to "${a}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(i,a,o,r);let c=await n.getTask(i,r);if(c){let u=Lu.parse({method:"notifications/tasks/status",params:c});await this.notification(u),aa(c.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>n.listTasks(i,r)}}};function aI(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function oI(t,e){let r={...t};for(let n in e){let i=n,a=e[i];if(a===void 0)continue;let o=r[i];aI(o)&&aI(a)?r[i]={...o,...a}:r[i]=a}return r}var VO=ut(CS(),1),GO=ut(BO(),1);function W7(){let t=new VO.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,GO.default)(t),t}var rm=class{constructor(e){this._ajv=e??W7()}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 nm=class{constructor(e){this._client=e}async*callToolStream(e,r=os,n){let i=this._client,a={...n,task:n?.task??(i.isToolTask(e.name)?{}:void 0)},o=i.requestStream({method:"tools/call",params:e},r,a),s=i.getToolOutputValidator(e.name);for await(let c of o){if(c.type==="result"&&s){let u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new Se(Ce.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{let l=s(u.structuredContent);if(!l.valid){yield{type:"error",error:new Se(Ce.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof Se){yield{type:"error",error:l};return}yield{type:"error",error:new Se(Ce.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 WO(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 KO(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 im(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 a=n[i];r[i]===void 0&&Object.prototype.hasOwnProperty.call(a,"default")&&(r[i]=a.default),r[i]!==void 0&&im(a,r[i])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&im(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&im(r,e)}}function K7(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 ws=class extends _f{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 rm,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Lb,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",zb,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Rb,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new nm(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=oI(this._capabilities,e)}setRequestHandler(e,r){let i=Hp(e)?.method;if(!i)throw new Error("Schema is missing a method literal");let a;if(rs(i)){let s=i;a=s._zod?.def?.value??s.value}else{let s=i;a=s._def?.value??s.value}if(typeof a!="string")throw new Error("Schema method literal must be a string");let o=a;if(o==="elicitation/create"){let s=async(c,u)=>{let l=Un(Zb,c);if(!l.success){let y=l.error instanceof Error?l.error.message:String(l.error);throw new Se(Ce.InvalidParams,`Invalid elicitation request: ${y}`)}let{params:d}=l.data;d.mode=d.mode??"form";let{supportsFormMode:p,supportsUrlMode:f}=K7(this._capabilities.elicitation);if(d.mode==="form"&&!p)throw new Se(Ce.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!f)throw new Se(Ce.InvalidParams,"Client does not support URL-mode elicitation requests");let g=await Promise.resolve(r(c,u));if(d.task){let y=Un(Ba,g);if(!y.success){let v=y.error instanceof Error?y.error.message:String(y.error);throw new Se(Ce.InvalidParams,`Invalid task creation result: ${v}`)}return y.data}let _=Un(Hb,g);if(!_.success){let y=_.error instanceof Error?_.error.message:String(_.error);throw new Se(Ce.InvalidParams,`Invalid elicitation result: ${y}`)}let h=_.data,m=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&h.action==="accept"&&h.content&&m&&this._capabilities.elicitation?.form?.applyDefaults)try{im(m,h.content)}catch{}return h};return super.setRequestHandler(e,s)}if(o==="sampling/createMessage"){let s=async(c,u)=>{let l=Un(qb,c);if(!l.success){let g=l.error instanceof Error?l.error.message:String(l.error);throw new Se(Ce.InvalidParams,`Invalid sampling request: ${g}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let g=Un(Ba,p);if(!g.success){let _=g.error instanceof Error?g.error.message:String(g.error);throw new Se(Ce.InvalidParams,`Invalid task creation result: ${_}`)}return g.data}let f=Un(Fb,p);if(!f.success){let g=f.error instanceof Error?f.error.message:String(f.error);throw new Se(Ce.InvalidParams,`Invalid sampling result: ${g}`)}return f.data};return super.setRequestHandler(e,s)}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:bb,capabilities:this._capabilities,clientInfo:this._clientInfo}},Eb,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!q1.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){WO(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&KO(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Ha,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Bb,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},Ha,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},Db,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},Cb,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},Tb,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},Ib,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Ob,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},Ha,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},Ha,r)}async callTool(e,r=os,n){if(this.isToolTaskRequired(e.name))throw new Se(Ce.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),a=this.getToolOutputValidator(e.name);if(a){if(!i.structuredContent&&!i.isError)throw new Se(Ce.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(i.structuredContent)try{let o=a(i.structuredContent);if(!o.valid)throw new Se(Ce.InvalidParams,`Structured content does not match the tool's output schema: ${o.errorMessage}`)}catch(o){throw o instanceof Se?o:new Se(Ce.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},Ub,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,i){let a=nI.safeParse(n);if(!a.success)throw new Error(`Invalid ${e} listChanged options: ${a.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:o,debounceMs:s}=a.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(s){let d=this._listChangedDebounceTimers.get(e);d&&clearTimeout(d);let p=setTimeout(u,s);this._listChangedDebounceTimers.set(e,p)}else u()};this.setNotificationHandler(r,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var UR=ut(DR(),1),yl=ut(require("node:process"),1),LR=require("node:stream");var om=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 s=o[1];if(e===o[0]){a(o);continue}if(t.external){let u=t.external.registry.get(o[0])?.id;if(e!==o[0]&&u){a(o);continue}}if(t.metadataRegistry.get(o[0])?.id){a(o);continue}if(s.cycle){a(o);continue}if(s.count>1&&t.reused==="ref"){a(o);continue}}}function Zp(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 s=t.seen.get(o);if(s.ref===null)return;let c=s.def??s.schema,u={...c},l=s.ref;if(s.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 _ in c)_==="$ref"||_==="allOf"||_ in u||delete c[_];if(f.$ref)for(let _ in c)_==="$ref"||_==="allOf"||_ in p.def&&JSON.stringify(c[_])===JSON.stringify(p.def[_])&&delete c[_]}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:s.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 a=t.external?.defs??{};for(let o of t.seen.entries()){let s=o[1];s.def&&s.defId&&(a[s.defId]=s.def)}t.external||Object.keys(a).length>0&&(t.target==="draft-2020-12"?i.$defs=a:i.definitions=a);try{let o=JSON.parse(JSON.stringify(i));return Object.defineProperty(o,"~standard",{value:{...e["~standard"],jsonSchema:{input:Iu(e,"input",t.processors),output:Iu(e,"output",t.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function Rr(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 Rr(n.element,r);if(n.type==="set")return Rr(n.valueType,r);if(n.type==="lazy")return Rr(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 Rr(n.innerType,r);if(n.type==="intersection")return Rr(n.left,r)||Rr(n.right,r);if(n.type==="record"||n.type==="map")return Rr(n.keyType,r)||Rr(n.valueType,r);if(n.type==="pipe")return Rr(n.in,r)||Rr(n.out,r);if(n.type==="object"){for(let i in n.shape)if(Rr(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(let i of n.options)if(Rr(i,r))return!0;return!1}if(n.type==="tuple"){for(let i of n.items)if(Rr(i,r))return!0;return!!(n.rest&&Rr(n.rest,r))}return!1}var Qk=(t,e={})=>r=>{let n=qp({...r,processors:e});return Ot(t,n),Fp(n,t),Zp(n,t)},Iu=(t,e,r={})=>n=>{let{libraryOptions:i,target:a}=n??{},o=qp({...i??{},target:a,io:e,processors:r});return Ot(t,o),Fp(o,t),Zp(o,t)};var Q9={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},eT=(t,e,r,n)=>{let i=r;i.type="string";let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof a=="number"&&(i.minLength=a),typeof o=="number"&&(i.maxLength=o),s&&(i.format=Q9[s]??s,i.format===""&&delete i.format,s==="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}))])}},tT=(t,e,r,n)=>{let i=r,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=t._zod.bag;typeof s=="string"&&s.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 a=="number"&&(i.minimum=a,typeof l=="number"&&e.target!=="draft-04"&&(l>=a?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)},rT=(t,e,r,n)=>{r.type="boolean"},nT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},iT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},aT=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},oT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},sT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},cT=(t,e,r,n)=>{r.not={}},uT=(t,e,r,n)=>{},lT=(t,e,r,n)=>{},dT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},pT=(t,e,r,n)=>{let i=t._zod.def,a=Jc(i.entries);a.every(o=>typeof o=="number")&&(r.type="number"),a.every(o=>typeof o=="string")&&(r.type="string"),r.enum=a},fT=(t,e,r,n)=>{let i=t._zod.def,a=[];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");a.push(Number(o))}else a.push(o);if(a.length!==0)if(a.length===1){let o=a[0];r.type=o===null?"null":typeof o,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[o]:r.const=o}else a.every(o=>typeof o=="number")&&(r.type="number"),a.every(o=>typeof o=="string")&&(r.type="string"),a.every(o=>typeof o=="boolean")&&(r.type="boolean"),a.every(o=>o===null)&&(r.type="null"),r.enum=a},mT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},hT=(t,e,r,n)=>{let i=r,a=t._zod.pattern;if(!a)throw new Error("Pattern not found in template literal");i.type="string",i.pattern=a.source},gT=(t,e,r,n)=>{let i=r,a={type:"string",format:"binary",contentEncoding:"binary"},{minimum:o,maximum:s,mime:c}=t._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(u=>({contentMediaType:u}))):Object.assign(i,a)},vT=(t,e,r,n)=>{r.type="boolean"},yT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},_T=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},bT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},xT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},ST=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},wT=(t,e,r,n)=>{let i=r,a=t._zod.def,{minimum:o,maximum:s}=t._zod.bag;typeof o=="number"&&(i.minItems=o),typeof s=="number"&&(i.maxItems=s),i.type="array",i.items=Ot(a.element,e,{...n,path:[...n.path,"items"]})},$T=(t,e,r,n)=>{let i=r,a=t._zod.def;i.type="object",i.properties={};let o=a.shape;for(let u in o)i.properties[u]=Ot(o[u],e,{...n,path:[...n.path,"properties",u]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(u=>{let l=a.shape[u]._zod;return e.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type==="never"?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=Ot(a.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(i.additionalProperties=!1)},A_=(t,e,r,n)=>{let i=t._zod.def,a=i.inclusive===!1,o=i.options.map((s,c)=>Ot(s,e,{...n,path:[...n.path,a?"oneOf":"anyOf",c]}));a?r.oneOf=o:r.anyOf=o},ET=(t,e,r,n)=>{let i=t._zod.def,a=Ot(i.left,e,{...n,path:[...n.path,"allOf",0]}),o=Ot(i.right,e,{...n,path:[...n.path,"allOf",1]}),s=u=>"allOf"in u&&Object.keys(u).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];r.allOf=c},kT=(t,e,r,n)=>{let i=r,a=t._zod.def;i.type="array";let o=e.target==="draft-2020-12"?"prefixItems":"items",s=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=a.items.map((p,f)=>Ot(p,e,{...n,path:[...n.path,o,f]})),u=a.rest?Ot(a.rest,e,{...n,path:[...n.path,s,...e.target==="openapi-3.0"?[a.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)},TT=(t,e,r,n)=>{let i=r,a=t._zod.def;i.type="object";let o=a.keyType,c=o._zod.bag?.patterns;if(a.mode==="loose"&&c&&c.size>0){let l=Ot(a.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=Ot(a.keyType,e,{...n,path:[...n.path,"propertyNames"]})),i.additionalProperties=Ot(a.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)}},IT=(t,e,r,n)=>{let i=t._zod.def,a=Ot(i.innerType,e,n),o=e.seen.get(t);e.target==="openapi-3.0"?(o.ref=i.innerType,r.nullable=!0):r.anyOf=[a,{type:"null"}]},PT=(t,e,r,n)=>{let i=t._zod.def;Ot(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType},OT=(t,e,r,n)=>{let i=t._zod.def;Ot(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))},RT=(t,e,r,n)=>{let i=t._zod.def;Ot(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},CT=(t,e,r,n)=>{let i=t._zod.def;Ot(i.innerType,e,n);let a=e.seen.get(t);a.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},NT=(t,e,r,n)=>{let i=t._zod.def,a=e.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;Ot(a,e,n);let o=e.seen.get(t);o.ref=a},jT=(t,e,r,n)=>{let i=t._zod.def;Ot(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType,r.readOnly=!0},AT=(t,e,r,n)=>{let i=t._zod.def;Ot(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType},M_=(t,e,r,n)=>{let i=t._zod.def;Ot(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType},MT=(t,e,r,n)=>{let i=t._zod.innerType;Ot(i,e,n);let a=e.seen.get(t);a.ref=i};function rs(t){return!!t._zod}function Un(t,e){return rs(t)?Xo(t,e):t.safeParse(e)}function Hp(t){if(!t)return;let e;if(rs(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function LT(t){if(rs(t)){let a=t._zod?.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.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 Pu={};pn(Pu,{ZodAny:()=>i1,ZodArray:()=>c1,ZodBase64:()=>ob,ZodBase64URL:()=>sb,ZodBigInt:()=>Qp,ZodBigIntFormat:()=>lb,ZodBoolean:()=>Yp,ZodCIDRv4:()=>ib,ZodCIDRv6:()=>ab,ZodCUID:()=>X_,ZodCUID2:()=>Y_,ZodCatch:()=>I1,ZodCodec:()=>vb,ZodCustom:()=>af,ZodCustomStringFormat:()=>Ru,ZodDate:()=>pb,ZodDefault:()=>S1,ZodDiscriminatedUnion:()=>l1,ZodE164:()=>cb,ZodEmail:()=>W_,ZodEmoji:()=>K_,ZodEnum:()=>Ou,ZodExactOptional:()=>_1,ZodFile:()=>v1,ZodFunction:()=>D1,ZodGUID:()=>Vp,ZodIPv4:()=>rb,ZodIPv6:()=>nb,ZodIntersection:()=>d1,ZodJWT:()=>ub,ZodKSUID:()=>tb,ZodLazy:()=>j1,ZodLiteral:()=>g1,ZodMAC:()=>e1,ZodMap:()=>m1,ZodNaN:()=>O1,ZodNanoID:()=>J_,ZodNever:()=>o1,ZodNonOptional:()=>hb,ZodNull:()=>n1,ZodNullable:()=>x1,ZodNumber:()=>Xp,ZodNumberFormat:()=>ns,ZodObject:()=>ef,ZodOptional:()=>mb,ZodPipe:()=>gb,ZodPrefault:()=>$1,ZodPromise:()=>M1,ZodReadonly:()=>R1,ZodRecord:()=>nf,ZodSet:()=>h1,ZodString:()=>Kp,ZodStringFormat:()=>Et,ZodSuccess:()=>T1,ZodSymbol:()=>t1,ZodTemplateLiteral:()=>N1,ZodTransform:()=>y1,ZodTuple:()=>p1,ZodType:()=>ze,ZodULID:()=>Q_,ZodURL:()=>Jp,ZodUUID:()=>Ri,ZodUndefined:()=>r1,ZodUnion:()=>tf,ZodUnknown:()=>a1,ZodVoid:()=>s1,ZodXID:()=>eb,ZodXor:()=>u1,_ZodString:()=>G_,_default:()=>w1,_function:()=>vF,any:()=>Q8,array:()=>We,base64:()=>M8,base64url:()=>D8,bigint:()=>W8,boolean:()=>er,catch:()=>P1,check:()=>yF,cidrv4:()=>j8,cidrv6:()=>A8,codec:()=>mF,cuid:()=>k8,cuid2:()=>T8,custom:()=>yb,date:()=>tF,describe:()=>_F,discriminatedUnion:()=>rf,e164:()=>z8,email:()=>g8,emoji:()=>$8,enum:()=>yr,exactOptional:()=>b1,file:()=>lF,float32:()=>H8,float64:()=>B8,function:()=>vF,guid:()=>v8,hash:()=>Z8,hex:()=>F8,hostname:()=>q8,httpUrl:()=>w8,instanceof:()=>xF,int:()=>V_,int32:()=>V8,int64:()=>K8,intersection:()=>Nu,ipv4:()=>R8,ipv6:()=>N8,json:()=>wF,jwt:()=>U8,keyof:()=>rF,ksuid:()=>O8,lazy:()=>A1,literal:()=>ve,looseObject:()=>vr,looseRecord:()=>oF,mac:()=>C8,map:()=>sF,meta:()=>bF,nan:()=>fF,nanoid:()=>E8,nativeEnum:()=>uF,never:()=>db,nonoptional:()=>k1,null:()=>Cu,nullable:()=>Gp,nullish:()=>dF,number:()=>ft,object:()=>le,optional:()=>At,partialRecord:()=>aF,pipe:()=>Wp,prefault:()=>E1,preprocess:()=>of,promise:()=>gF,readonly:()=>C1,record:()=>Rt,refine:()=>z1,set:()=>cF,strictObject:()=>nF,string:()=>H,stringFormat:()=>L8,stringbool:()=>SF,success:()=>pF,superRefine:()=>U1,symbol:()=>X8,templateLiteral:()=>hF,transform:()=>fb,tuple:()=>f1,uint32:()=>G8,uint64:()=>J8,ulid:()=>I8,undefined:()=>Y8,union:()=>xt,unknown:()=>kt,url:()=>S8,uuid:()=>y8,uuidv4:()=>_8,uuidv6:()=>b8,uuidv7:()=>x8,void:()=>eF,xid:()=>P8,xor:()=>iF});var Bp={};pn(Bp,{endsWith:()=>Su,gt:()=>Pi,gte:()=>Or,includes:()=>bu,length:()=>es,lowercase:()=>yu,lt:()=>Ii,lte:()=>an,maxLength:()=>Qo,maxSize:()=>Fa,mime:()=>wu,minLength:()=>na,minSize:()=>Oi,multipleOf:()=>qa,negative:()=>$_,nonnegative:()=>k_,nonpositive:()=>E_,normalize:()=>$u,overwrite:()=>ai,positive:()=>w_,property:()=>T_,regex:()=>vu,size:()=>Yo,slugify:()=>Lp,startsWith:()=>xu,toLowerCase:()=>ku,toUpperCase:()=>Tu,trim:()=>Eu,uppercase:()=>_u});var Za={};pn(Za,{ZodISODate:()=>L_,ZodISODateTime:()=>z_,ZodISODuration:()=>H_,ZodISOTime:()=>F_,date:()=>q_,datetime:()=>U_,duration:()=>B_,time:()=>Z_});var z_=q("ZodISODateTime",(t,e)=>{Yv.init(t,e),Et.init(t,e)});function U_(t){return e_(z_,t)}var L_=q("ZodISODate",(t,e)=>{Qv.init(t,e),Et.init(t,e)});function q_(t){return t_(L_,t)}var F_=q("ZodISOTime",(t,e)=>{ey.init(t,e),Et.init(t,e)});function Z_(t){return r_(F_,t)}var H_=q("ZodISODuration",(t,e)=>{ty.init(t,e),Et.init(t,e)});function B_(t){return n_(H_,t)}var qT=(t,e)=>{ap.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>sp(t,r)},flatten:{value:r=>op(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,Wo,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,Wo,2)}},isEmpty:{get(){return t.issues.length===0}}})},sbe=q("ZodError",qT),on=q("ZodError",qT,{Parent:Error});var FT=ru(on),ZT=iu(on),HT=ou(on),BT=su(on),VT=rk(on),GT=nk(on),WT=ik(on),KT=ak(on),JT=ok(on),XT=sk(on),YT=ck(on),QT=uk(on);var ze=q("ZodType",(t,e)=>(Ae.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:Iu(t,"input"),output:Iu(t,"output")}}),t.toJSONSchema=Qk(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone(ee.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)=>Ir(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>FT(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>HT(t,r,n),t.parseAsync=async(r,n)=>ZT(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>BT(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>VT(t,r,n),t.decode=(r,n)=>GT(t,r,n),t.encodeAsync=async(r,n)=>WT(t,r,n),t.decodeAsync=async(r,n)=>KT(t,r,n),t.safeEncode=(r,n)=>JT(t,r,n),t.safeDecode=(r,n)=>XT(t,r,n),t.safeEncodeAsync=async(r,n)=>YT(t,r,n),t.safeDecodeAsync=async(r,n)=>QT(t,r,n),t.refine=(r,n)=>t.check(z1(r,n)),t.superRefine=r=>t.check(U1(r)),t.overwrite=r=>t.check(ai(r)),t.optional=()=>At(t),t.exactOptional=()=>b1(t),t.nullable=()=>Gp(t),t.nullish=()=>At(Gp(t)),t.nonoptional=r=>k1(t,r),t.array=()=>We(t),t.or=r=>xt([t,r]),t.and=r=>Nu(t,r),t.transform=r=>Wp(t,fb(r)),t.default=r=>w1(t,r),t.prefault=r=>E1(t,r),t.catch=r=>P1(t,r),t.pipe=r=>Wp(t,r),t.readonly=()=>C1(t),t.describe=r=>{let n=t.clone();return Pr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Pr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Pr.get(t);let n=t.clone();return Pr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t.apply=r=>r(t),t)),G_=q("_ZodString",(t,e)=>{La.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(n,i,a)=>eT(t,n,i,a);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(vu(...n)),t.includes=(...n)=>t.check(bu(...n)),t.startsWith=(...n)=>t.check(xu(...n)),t.endsWith=(...n)=>t.check(Su(...n)),t.min=(...n)=>t.check(na(...n)),t.max=(...n)=>t.check(Qo(...n)),t.length=(...n)=>t.check(es(...n)),t.nonempty=(...n)=>t.check(na(1,...n)),t.lowercase=n=>t.check(yu(n)),t.uppercase=n=>t.check(_u(n)),t.trim=()=>t.check(Eu()),t.normalize=(...n)=>t.check($u(...n)),t.toLowerCase=()=>t.check(ku()),t.toUpperCase=()=>t.check(Tu()),t.slugify=()=>t.check(Lp())}),Kp=q("ZodString",(t,e)=>{La.init(t,e),G_.init(t,e),t.email=r=>t.check(bp(W_,r)),t.url=r=>t.check(gu(Jp,r)),t.jwt=r=>t.check(Up(ub,r)),t.emoji=r=>t.check(Ep(K_,r)),t.guid=r=>t.check(hu(Vp,r)),t.uuid=r=>t.check(xp(Ri,r)),t.uuidv4=r=>t.check(Sp(Ri,r)),t.uuidv6=r=>t.check(wp(Ri,r)),t.uuidv7=r=>t.check($p(Ri,r)),t.nanoid=r=>t.check(kp(J_,r)),t.guid=r=>t.check(hu(Vp,r)),t.cuid=r=>t.check(Tp(X_,r)),t.cuid2=r=>t.check(Ip(Y_,r)),t.ulid=r=>t.check(Pp(Q_,r)),t.base64=r=>t.check(Mp(ob,r)),t.base64url=r=>t.check(Dp(sb,r)),t.xid=r=>t.check(Op(eb,r)),t.ksuid=r=>t.check(Rp(tb,r)),t.ipv4=r=>t.check(Cp(rb,r)),t.ipv6=r=>t.check(Np(nb,r)),t.cidrv4=r=>t.check(jp(ib,r)),t.cidrv6=r=>t.check(Ap(ab,r)),t.e164=r=>t.check(zp(cb,r)),t.datetime=r=>t.check(U_(r)),t.date=r=>t.check(q_(r)),t.time=r=>t.check(Z_(r)),t.duration=r=>t.check(B_(r))});function H(t){return Yy(Kp,t)}var Et=q("ZodStringFormat",(t,e)=>{bt.init(t,e),G_.init(t,e)}),W_=q("ZodEmail",(t,e)=>{Zv.init(t,e),Et.init(t,e)});function g8(t){return bp(W_,t)}var Vp=q("ZodGUID",(t,e)=>{qv.init(t,e),Et.init(t,e)});function v8(t){return hu(Vp,t)}var Ri=q("ZodUUID",(t,e)=>{Fv.init(t,e),Et.init(t,e)});function y8(t){return xp(Ri,t)}function _8(t){return Sp(Ri,t)}function b8(t){return wp(Ri,t)}function x8(t){return $p(Ri,t)}var Jp=q("ZodURL",(t,e)=>{Hv.init(t,e),Et.init(t,e)});function S8(t){return gu(Jp,t)}function w8(t){return gu(Jp,{protocol:/^https?$/,hostname:hn.domain,...ee.normalizeParams(t)})}var K_=q("ZodEmoji",(t,e)=>{Bv.init(t,e),Et.init(t,e)});function $8(t){return Ep(K_,t)}var J_=q("ZodNanoID",(t,e)=>{Vv.init(t,e),Et.init(t,e)});function E8(t){return kp(J_,t)}var X_=q("ZodCUID",(t,e)=>{Gv.init(t,e),Et.init(t,e)});function k8(t){return Tp(X_,t)}var Y_=q("ZodCUID2",(t,e)=>{Wv.init(t,e),Et.init(t,e)});function T8(t){return Ip(Y_,t)}var Q_=q("ZodULID",(t,e)=>{Kv.init(t,e),Et.init(t,e)});function I8(t){return Pp(Q_,t)}var eb=q("ZodXID",(t,e)=>{Jv.init(t,e),Et.init(t,e)});function P8(t){return Op(eb,t)}var tb=q("ZodKSUID",(t,e)=>{Xv.init(t,e),Et.init(t,e)});function O8(t){return Rp(tb,t)}var rb=q("ZodIPv4",(t,e)=>{ry.init(t,e),Et.init(t,e)});function R8(t){return Cp(rb,t)}var e1=q("ZodMAC",(t,e)=>{iy.init(t,e),Et.init(t,e)});function C8(t){return Qy(e1,t)}var nb=q("ZodIPv6",(t,e)=>{ny.init(t,e),Et.init(t,e)});function N8(t){return Np(nb,t)}var ib=q("ZodCIDRv4",(t,e)=>{ay.init(t,e),Et.init(t,e)});function j8(t){return jp(ib,t)}var ab=q("ZodCIDRv6",(t,e)=>{oy.init(t,e),Et.init(t,e)});function A8(t){return Ap(ab,t)}var ob=q("ZodBase64",(t,e)=>{sy.init(t,e),Et.init(t,e)});function M8(t){return Mp(ob,t)}var sb=q("ZodBase64URL",(t,e)=>{cy.init(t,e),Et.init(t,e)});function D8(t){return Dp(sb,t)}var cb=q("ZodE164",(t,e)=>{uy.init(t,e),Et.init(t,e)});function z8(t){return zp(cb,t)}var ub=q("ZodJWT",(t,e)=>{ly.init(t,e),Et.init(t,e)});function U8(t){return Up(ub,t)}var Ru=q("ZodCustomStringFormat",(t,e)=>{dy.init(t,e),Et.init(t,e)});function L8(t,e,r={}){return ts(Ru,t,e,r)}function q8(t){return ts(Ru,"hostname",hn.hostname,t)}function F8(t){return ts(Ru,"hex",hn.hex,t)}function Z8(t,e){let r=e?.enc??"hex",n=`${t}_${r}`,i=hn[n];if(!i)throw new Error(`Unrecognized hash format: ${n}`);return ts(Ru,n,i,e)}var Xp=q("ZodNumber",(t,e)=>{gp.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(n,i,a)=>tT(t,n,i,a),t.gt=(n,i)=>t.check(Pi(n,i)),t.gte=(n,i)=>t.check(Or(n,i)),t.min=(n,i)=>t.check(Or(n,i)),t.lt=(n,i)=>t.check(Ii(n,i)),t.lte=(n,i)=>t.check(an(n,i)),t.max=(n,i)=>t.check(an(n,i)),t.int=n=>t.check(V_(n)),t.safe=n=>t.check(V_(n)),t.positive=n=>t.check(Pi(0,n)),t.nonnegative=n=>t.check(Or(0,n)),t.negative=n=>t.check(Ii(0,n)),t.nonpositive=n=>t.check(an(0,n)),t.multipleOf=(n,i)=>t.check(qa(n,i)),t.step=(n,i)=>t.check(qa(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 ft(t){return i_(Xp,t)}var ns=q("ZodNumberFormat",(t,e)=>{py.init(t,e),Xp.init(t,e)});function V_(t){return a_(ns,t)}function H8(t){return o_(ns,t)}function B8(t){return s_(ns,t)}function V8(t){return c_(ns,t)}function G8(t){return u_(ns,t)}var Yp=q("ZodBoolean",(t,e)=>{pu.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>rT(t,r,n,i)});function er(t){return l_(Yp,t)}var Qp=q("ZodBigInt",(t,e)=>{vp.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(n,i,a)=>nT(t,n,i,a),t.gte=(n,i)=>t.check(Or(n,i)),t.min=(n,i)=>t.check(Or(n,i)),t.gt=(n,i)=>t.check(Pi(n,i)),t.gte=(n,i)=>t.check(Or(n,i)),t.min=(n,i)=>t.check(Or(n,i)),t.lt=(n,i)=>t.check(Ii(n,i)),t.lte=(n,i)=>t.check(an(n,i)),t.max=(n,i)=>t.check(an(n,i)),t.positive=n=>t.check(Pi(BigInt(0),n)),t.negative=n=>t.check(Ii(BigInt(0),n)),t.nonpositive=n=>t.check(an(BigInt(0),n)),t.nonnegative=n=>t.check(Or(BigInt(0),n)),t.multipleOf=(n,i)=>t.check(qa(n,i));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});function W8(t){return d_(Qp,t)}var lb=q("ZodBigIntFormat",(t,e)=>{fy.init(t,e),Qp.init(t,e)});function K8(t){return p_(lb,t)}function J8(t){return f_(lb,t)}var t1=q("ZodSymbol",(t,e)=>{my.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>iT(t,r,n,i)});function X8(t){return m_(t1,t)}var r1=q("ZodUndefined",(t,e)=>{hy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>oT(t,r,n,i)});function Y8(t){return h_(r1,t)}var n1=q("ZodNull",(t,e)=>{gy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>aT(t,r,n,i)});function Cu(t){return g_(n1,t)}var i1=q("ZodAny",(t,e)=>{vy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>uT(t,r,n,i)});function Q8(){return v_(i1)}var a1=q("ZodUnknown",(t,e)=>{yy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lT(t,r,n,i)});function kt(){return y_(a1)}var o1=q("ZodNever",(t,e)=>{_y.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>cT(t,r,n,i)});function db(t){return __(o1,t)}var s1=q("ZodVoid",(t,e)=>{by.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>sT(t,r,n,i)});function eF(t){return b_(s1,t)}var pb=q("ZodDate",(t,e)=>{xy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(n,i,a)=>dT(t,n,i,a),t.min=(n,i)=>t.check(Or(n,i)),t.max=(n,i)=>t.check(an(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 tF(t){return x_(pb,t)}var c1=q("ZodArray",(t,e)=>{Sy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>wT(t,r,n,i),t.element=e.element,t.min=(r,n)=>t.check(na(r,n)),t.nonempty=r=>t.check(na(1,r)),t.max=(r,n)=>t.check(Qo(r,n)),t.length=(r,n)=>t.check(es(r,n)),t.unwrap=()=>t.element});function We(t,e){return Yk(c1,t,e)}function rF(t){let e=t._zod.def.shape;return yr(Object.keys(e))}var ef=q("ZodObject",(t,e)=>{Jk.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>$T(t,r,n,i),ee.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>yr(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:kt()}),t.loose=()=>t.clone({...t._zod.def,catchall:kt()}),t.strict=()=>t.clone({...t._zod.def,catchall:db()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ee.extend(t,r),t.safeExtend=r=>ee.safeExtend(t,r),t.merge=r=>ee.merge(t,r),t.pick=r=>ee.pick(t,r),t.omit=r=>ee.omit(t,r),t.partial=(...r)=>ee.partial(mb,t,r[0]),t.required=(...r)=>ee.required(hb,t,r[0])});function le(t,e){let r={type:"object",shape:t??{},...ee.normalizeParams(e)};return new ef(r)}function nF(t,e){return new ef({type:"object",shape:t,catchall:db(),...ee.normalizeParams(e)})}function vr(t,e){return new ef({type:"object",shape:t,catchall:kt(),...ee.normalizeParams(e)})}var tf=q("ZodUnion",(t,e)=>{fu.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>A_(t,r,n,i),t.options=e.options});function xt(t,e){return new tf({type:"union",options:t,...ee.normalizeParams(e)})}var u1=q("ZodXor",(t,e)=>{tf.init(t,e),wy.init(t,e),t._zod.processJSONSchema=(r,n,i)=>A_(t,r,n,i),t.options=e.options});function iF(t,e){return new u1({type:"union",options:t,inclusive:!1,...ee.normalizeParams(e)})}var l1=q("ZodDiscriminatedUnion",(t,e)=>{tf.init(t,e),$y.init(t,e)});function rf(t,e,r){return new l1({type:"union",options:e,discriminator:t,...ee.normalizeParams(r)})}var d1=q("ZodIntersection",(t,e)=>{Ey.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>ET(t,r,n,i)});function Nu(t,e){return new d1({type:"intersection",left:t,right:e})}var p1=q("ZodTuple",(t,e)=>{yp.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>kT(t,r,n,i),t.rest=r=>t.clone({...t._zod.def,rest:r})});function f1(t,e,r){let n=e instanceof Ae,i=n?r:e,a=n?e:null;return new p1({type:"tuple",items:t,rest:a,...ee.normalizeParams(i)})}var nf=q("ZodRecord",(t,e)=>{ky.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>TT(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType});function Rt(t,e,r){return new nf({type:"record",keyType:t,valueType:e,...ee.normalizeParams(r)})}function aF(t,e,r){let n=Ir(t);return n._zod.values=void 0,new nf({type:"record",keyType:n,valueType:e,...ee.normalizeParams(r)})}function oF(t,e,r){return new nf({type:"record",keyType:t,valueType:e,mode:"loose",...ee.normalizeParams(r)})}var m1=q("ZodMap",(t,e)=>{Ty.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>xT(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(Oi(...r)),t.nonempty=r=>t.check(Oi(1,r)),t.max=(...r)=>t.check(Fa(...r)),t.size=(...r)=>t.check(Yo(...r))});function sF(t,e,r){return new m1({type:"map",keyType:t,valueType:e,...ee.normalizeParams(r)})}var h1=q("ZodSet",(t,e)=>{Iy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>ST(t,r,n,i),t.min=(...r)=>t.check(Oi(...r)),t.nonempty=r=>t.check(Oi(1,r)),t.max=(...r)=>t.check(Fa(...r)),t.size=(...r)=>t.check(Yo(...r))});function cF(t,e){return new h1({type:"set",valueType:t,...ee.normalizeParams(e)})}var Ou=q("ZodEnum",(t,e)=>{Py.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(n,i,a)=>pT(t,n,i,a),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,i)=>{let a={};for(let o of n)if(r.has(o))a[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Ou({...e,checks:[],...ee.normalizeParams(i),entries:a})},t.exclude=(n,i)=>{let a={...e.entries};for(let o of n)if(r.has(o))delete a[o];else throw new Error(`Key ${o} not found in enum`);return new Ou({...e,checks:[],...ee.normalizeParams(i),entries:a})}});function yr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Ou({type:"enum",entries:r,...ee.normalizeParams(e)})}function uF(t,e){return new Ou({type:"enum",entries:t,...ee.normalizeParams(e)})}var g1=q("ZodLiteral",(t,e)=>{Oy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>fT(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 ve(t,e){return new g1({type:"literal",values:Array.isArray(t)?t:[t],...ee.normalizeParams(e)})}var v1=q("ZodFile",(t,e)=>{Ry.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>gT(t,r,n,i),t.min=(r,n)=>t.check(Oi(r,n)),t.max=(r,n)=>t.check(Fa(r,n)),t.mime=(r,n)=>t.check(wu(Array.isArray(r)?r:[r],n))});function lF(t){return I_(v1,t)}var y1=q("ZodTransform",(t,e)=>{Cy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>bT(t,r,n,i),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Da(t.constructor.name);r.addIssue=a=>{if(typeof a=="string")r.issues.push(ee.issue(a,r.value,e));else{let o=a;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),r.issues.push(ee.issue(o))}};let i=e.transform(r.value,r);return i instanceof Promise?i.then(a=>(r.value=a,r)):(r.value=i,r)}});function fb(t){return new y1({type:"transform",transform:t})}var mb=q("ZodOptional",(t,e)=>{_p.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>M_(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function At(t){return new mb({type:"optional",innerType:t})}var _1=q("ZodExactOptional",(t,e)=>{Ny.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>M_(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function b1(t){return new _1({type:"optional",innerType:t})}var x1=q("ZodNullable",(t,e)=>{jy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>IT(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Gp(t){return new x1({type:"nullable",innerType:t})}function dF(t){return At(Gp(t))}var S1=q("ZodDefault",(t,e)=>{Ay.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>OT(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function w1(t,e){return new S1({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():ee.shallowClone(e)}})}var $1=q("ZodPrefault",(t,e)=>{My.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>RT(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function E1(t,e){return new $1({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():ee.shallowClone(e)}})}var hb=q("ZodNonOptional",(t,e)=>{Dy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>PT(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function k1(t,e){return new hb({type:"nonoptional",innerType:t,...ee.normalizeParams(e)})}var T1=q("ZodSuccess",(t,e)=>{zy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>vT(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function pF(t){return new T1({type:"success",innerType:t})}var I1=q("ZodCatch",(t,e)=>{Uy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>CT(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function P1(t,e){return new I1({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var O1=q("ZodNaN",(t,e)=>{Ly.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>mT(t,r,n,i)});function fF(t){return S_(O1,t)}var gb=q("ZodPipe",(t,e)=>{qy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>NT(t,r,n,i),t.in=e.in,t.out=e.out});function Wp(t,e){return new gb({type:"pipe",in:t,out:e})}var vb=q("ZodCodec",(t,e)=>{gb.init(t,e),mu.init(t,e)});function mF(t,e,r){return new vb({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}var R1=q("ZodReadonly",(t,e)=>{Fy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>jT(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function C1(t){return new R1({type:"readonly",innerType:t})}var N1=q("ZodTemplateLiteral",(t,e)=>{Zy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>hT(t,r,n,i)});function hF(t,e){return new N1({type:"template_literal",parts:t,...ee.normalizeParams(e)})}var j1=q("ZodLazy",(t,e)=>{Vy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>MT(t,r,n,i),t.unwrap=()=>t._zod.def.getter()});function A1(t){return new j1({type:"lazy",getter:t})}var M1=q("ZodPromise",(t,e)=>{By.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>AT(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function gF(t){return new M1({type:"promise",innerType:t})}var D1=q("ZodFunction",(t,e)=>{Hy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>_T(t,r,n,i)});function vF(t){return new D1({type:"function",input:Array.isArray(t?.input)?f1(t?.input):t?.input??We(kt()),output:t?.output??kt()})}var af=q("ZodCustom",(t,e)=>{Gy.init(t,e),ze.init(t,e),t._zod.processJSONSchema=(r,n,i)=>yT(t,r,n,i)});function yF(t){let e=new $t({check:"custom"});return e._zod.check=t,e}function yb(t,e){return P_(af,t??(()=>!0),e)}function z1(t,e={}){return O_(af,t,e)}function U1(t){return R_(t)}var _F=C_,bF=N_;function xF(t,e={}){let r=new af({type:"custom",check:"custom",fn:n=>n instanceof t,abort:!0,...ee.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 SF=(...t)=>j_({Codec:vb,Boolean:Yp,String:Kp},...t);function wF(t){let e=A1(()=>xt([H(t),ft(),er(),Cu(),We(e),Rt(H(),e)]));return e}function of(t,e){return Wp(fb(t),e)}var L1;L1||(L1={});var hbe={...Pu,...Bp,iso:Za};rr(Wy());var bb="2025-11-25";var q1=[bb,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],ia="io.modelcontextprotocol/related-task",cf="2.0",cr=yb(t=>t!==null&&(typeof t=="object"||typeof t=="function")),F1=xt([H(),ft().int()]),Z1=H(),jbe=vr({ttl:xt([ft(),Cu()]).optional(),pollInterval:ft().optional()}),TF=le({ttl:ft().optional()}),IF=le({taskId:H()}),xb=vr({progressToken:F1.optional(),[ia]:IF.optional()}),sn=le({_meta:xb.optional()}),ju=sn.extend({task:TF.optional()}),H1=t=>ju.safeParse(t).success,ur=le({method:H(),params:sn.loose().optional()}),gn=le({_meta:xb.optional()}),vn=le({method:H(),params:gn.loose().optional()}),lr=vr({_meta:xb.optional()}),uf=xt([H(),ft().int()]),B1=le({jsonrpc:ve(cf),id:uf,...ur.shape}).strict(),Sb=t=>B1.safeParse(t).success,V1=le({jsonrpc:ve(cf),...vn.shape}).strict(),G1=t=>V1.safeParse(t).success,wb=le({jsonrpc:ve(cf),id:uf,result:lr}).strict(),Au=t=>wb.safeParse(t).success;var Ce;(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"})(Ce||(Ce={}));var $b=le({jsonrpc:ve(cf),id:uf.optional(),error:le({code:ft().int(),message:H(),data:kt().optional()})}).strict();var W1=t=>$b.safeParse(t).success;var K1=xt([B1,V1,wb,$b]),Abe=xt([wb,$b]),Ha=lr.strict(),PF=gn.extend({requestId:uf.optional(),reason:H().optional()}),lf=vn.extend({method:ve("notifications/cancelled"),params:PF}),OF=le({src:H(),mimeType:H().optional(),sizes:We(H()).optional(),theme:yr(["light","dark"]).optional()}),Mu=le({icons:We(OF).optional()}),is=le({name:H(),title:H().optional()}),J1=is.extend({...is.shape,...Mu.shape,version:H(),websiteUrl:H().optional(),description:H().optional()}),RF=Nu(le({applyDefaults:er().optional()}),Rt(H(),kt())),CF=of(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Nu(le({form:RF.optional(),url:cr.optional()}),Rt(H(),kt()).optional())),NF=vr({list:cr.optional(),cancel:cr.optional(),requests:vr({sampling:vr({createMessage:cr.optional()}).optional(),elicitation:vr({create:cr.optional()}).optional()}).optional()}),jF=vr({list:cr.optional(),cancel:cr.optional(),requests:vr({tools:vr({call:cr.optional()}).optional()}).optional()}),AF=le({experimental:Rt(H(),cr).optional(),sampling:le({context:cr.optional(),tools:cr.optional()}).optional(),elicitation:CF.optional(),roots:le({listChanged:er().optional()}).optional(),tasks:NF.optional()}),MF=sn.extend({protocolVersion:H(),capabilities:AF,clientInfo:J1}),DF=ur.extend({method:ve("initialize"),params:MF});var zF=le({experimental:Rt(H(),cr).optional(),logging:cr.optional(),completions:cr.optional(),prompts:le({listChanged:er().optional()}).optional(),resources:le({subscribe:er().optional(),listChanged:er().optional()}).optional(),tools:le({listChanged:er().optional()}).optional(),tasks:jF.optional()}),Eb=lr.extend({protocolVersion:H(),capabilities:zF,serverInfo:J1,instructions:H().optional()}),UF=vn.extend({method:ve("notifications/initialized"),params:gn.optional()});var df=ur.extend({method:ve("ping"),params:sn.optional()}),LF=le({progress:ft(),total:At(ft()),message:At(H())}),qF=le({...gn.shape,...LF.shape,progressToken:F1}),pf=vn.extend({method:ve("notifications/progress"),params:qF}),FF=sn.extend({cursor:Z1.optional()}),Du=ur.extend({params:FF.optional()}),zu=lr.extend({nextCursor:Z1.optional()}),ZF=yr(["working","input_required","completed","failed","cancelled"]),Uu=le({taskId:H(),status:ZF,ttl:xt([ft(),Cu()]),createdAt:H(),lastUpdatedAt:H(),pollInterval:At(ft()),statusMessage:At(H())}),Ba=lr.extend({task:Uu}),HF=gn.merge(Uu),Lu=vn.extend({method:ve("notifications/tasks/status"),params:HF}),ff=ur.extend({method:ve("tasks/get"),params:sn.extend({taskId:H()})}),mf=lr.merge(Uu),hf=ur.extend({method:ve("tasks/result"),params:sn.extend({taskId:H()})}),Mbe=lr.loose(),gf=Du.extend({method:ve("tasks/list")}),vf=zu.extend({tasks:We(Uu)}),yf=ur.extend({method:ve("tasks/cancel"),params:sn.extend({taskId:H()})}),X1=lr.merge(Uu),Y1=le({uri:H(),mimeType:At(H()),_meta:Rt(H(),kt()).optional()}),Q1=Y1.extend({text:H()}),kb=H().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),eI=Y1.extend({blob:kb}),qu=yr(["user","assistant"]),as=le({audience:We(qu).optional(),priority:ft().min(0).max(1).optional(),lastModified:Za.datetime({offset:!0}).optional()}),tI=le({...is.shape,...Mu.shape,uri:H(),description:At(H()),mimeType:At(H()),annotations:as.optional(),_meta:At(vr({}))}),BF=le({...is.shape,...Mu.shape,uriTemplate:H(),description:At(H()),mimeType:At(H()),annotations:as.optional(),_meta:At(vr({}))}),VF=Du.extend({method:ve("resources/list")}),Tb=zu.extend({resources:We(tI)}),GF=Du.extend({method:ve("resources/templates/list")}),Ib=zu.extend({resourceTemplates:We(BF)}),Pb=sn.extend({uri:H()}),WF=Pb,KF=ur.extend({method:ve("resources/read"),params:WF}),Ob=lr.extend({contents:We(xt([Q1,eI]))}),Rb=vn.extend({method:ve("notifications/resources/list_changed"),params:gn.optional()}),JF=Pb,XF=ur.extend({method:ve("resources/subscribe"),params:JF}),YF=Pb,QF=ur.extend({method:ve("resources/unsubscribe"),params:YF}),e5=gn.extend({uri:H()}),t5=vn.extend({method:ve("notifications/resources/updated"),params:e5}),r5=le({name:H(),description:At(H()),required:At(er())}),n5=le({...is.shape,...Mu.shape,description:At(H()),arguments:At(We(r5)),_meta:At(vr({}))}),i5=Du.extend({method:ve("prompts/list")}),Cb=zu.extend({prompts:We(n5)}),a5=sn.extend({name:H(),arguments:Rt(H(),H()).optional()}),o5=ur.extend({method:ve("prompts/get"),params:a5}),Nb=le({type:ve("text"),text:H(),annotations:as.optional(),_meta:Rt(H(),kt()).optional()}),jb=le({type:ve("image"),data:kb,mimeType:H(),annotations:as.optional(),_meta:Rt(H(),kt()).optional()}),Ab=le({type:ve("audio"),data:kb,mimeType:H(),annotations:as.optional(),_meta:Rt(H(),kt()).optional()}),s5=le({type:ve("tool_use"),name:H(),id:H(),input:Rt(H(),kt()),_meta:Rt(H(),kt()).optional()}),c5=le({type:ve("resource"),resource:xt([Q1,eI]),annotations:as.optional(),_meta:Rt(H(),kt()).optional()}),u5=tI.extend({type:ve("resource_link")}),Mb=xt([Nb,jb,Ab,u5,c5]),l5=le({role:qu,content:Mb}),Db=lr.extend({description:H().optional(),messages:We(l5)}),zb=vn.extend({method:ve("notifications/prompts/list_changed"),params:gn.optional()}),d5=le({title:H().optional(),readOnlyHint:er().optional(),destructiveHint:er().optional(),idempotentHint:er().optional(),openWorldHint:er().optional()}),p5=le({taskSupport:yr(["required","optional","forbidden"]).optional()}),rI=le({...is.shape,...Mu.shape,description:H().optional(),inputSchema:le({type:ve("object"),properties:Rt(H(),cr).optional(),required:We(H()).optional()}).catchall(kt()),outputSchema:le({type:ve("object"),properties:Rt(H(),cr).optional(),required:We(H()).optional()}).catchall(kt()).optional(),annotations:d5.optional(),execution:p5.optional(),_meta:Rt(H(),kt()).optional()}),f5=Du.extend({method:ve("tools/list")}),Ub=zu.extend({tools:We(rI)}),os=lr.extend({content:We(Mb).default([]),structuredContent:Rt(H(),kt()).optional(),isError:er().optional()}),Dbe=os.or(lr.extend({toolResult:kt()})),m5=ju.extend({name:H(),arguments:Rt(H(),kt()).optional()}),h5=ur.extend({method:ve("tools/call"),params:m5}),Lb=vn.extend({method:ve("notifications/tools/list_changed"),params:gn.optional()}),nI=le({autoRefresh:er().default(!0),debounceMs:ft().int().nonnegative().default(300)}),iI=yr(["debug","info","notice","warning","error","critical","alert","emergency"]),g5=sn.extend({level:iI}),v5=ur.extend({method:ve("logging/setLevel"),params:g5}),y5=gn.extend({level:iI,logger:H().optional(),data:kt()}),_5=vn.extend({method:ve("notifications/message"),params:y5}),b5=le({name:H().optional()}),x5=le({hints:We(b5).optional(),costPriority:ft().min(0).max(1).optional(),speedPriority:ft().min(0).max(1).optional(),intelligencePriority:ft().min(0).max(1).optional()}),S5=le({mode:yr(["auto","required","none"]).optional()}),w5=le({type:ve("tool_result"),toolUseId:H().describe("The unique identifier for the corresponding tool call."),content:We(Mb).default([]),structuredContent:le({}).loose().optional(),isError:er().optional(),_meta:Rt(H(),kt()).optional()}),$5=rf("type",[Nb,jb,Ab]),sf=rf("type",[Nb,jb,Ab,s5,w5]),E5=le({role:qu,content:xt([sf,We(sf)]),_meta:Rt(H(),kt()).optional()}),k5=ju.extend({messages:We(E5),modelPreferences:x5.optional(),systemPrompt:H().optional(),includeContext:yr(["none","thisServer","allServers"]).optional(),temperature:ft().optional(),maxTokens:ft().int(),stopSequences:We(H()).optional(),metadata:cr.optional(),tools:We(rI).optional(),toolChoice:S5.optional()}),qb=ur.extend({method:ve("sampling/createMessage"),params:k5}),Fb=lr.extend({model:H(),stopReason:At(yr(["endTurn","stopSequence","maxTokens"]).or(H())),role:qu,content:$5}),T5=lr.extend({model:H(),stopReason:At(yr(["endTurn","stopSequence","maxTokens","toolUse"]).or(H())),role:qu,content:xt([sf,We(sf)])}),I5=le({type:ve("boolean"),title:H().optional(),description:H().optional(),default:er().optional()}),P5=le({type:ve("string"),title:H().optional(),description:H().optional(),minLength:ft().optional(),maxLength:ft().optional(),format:yr(["email","uri","date","date-time"]).optional(),default:H().optional()}),O5=le({type:yr(["number","integer"]),title:H().optional(),description:H().optional(),minimum:ft().optional(),maximum:ft().optional(),default:ft().optional()}),R5=le({type:ve("string"),title:H().optional(),description:H().optional(),enum:We(H()),default:H().optional()}),C5=le({type:ve("string"),title:H().optional(),description:H().optional(),oneOf:We(le({const:H(),title:H()})),default:H().optional()}),N5=le({type:ve("string"),title:H().optional(),description:H().optional(),enum:We(H()),enumNames:We(H()).optional(),default:H().optional()}),j5=xt([R5,C5]),A5=le({type:ve("array"),title:H().optional(),description:H().optional(),minItems:ft().optional(),maxItems:ft().optional(),items:le({type:ve("string"),enum:We(H())}),default:We(H()).optional()}),M5=le({type:ve("array"),title:H().optional(),description:H().optional(),minItems:ft().optional(),maxItems:ft().optional(),items:le({anyOf:We(le({const:H(),title:H()}))}),default:We(H()).optional()}),D5=xt([A5,M5]),z5=xt([N5,j5,D5]),U5=xt([z5,I5,P5,O5]),L5=ju.extend({mode:ve("form").optional(),message:H(),requestedSchema:le({type:ve("object"),properties:Rt(H(),U5),required:We(H()).optional()})}),q5=ju.extend({mode:ve("url"),message:H(),elicitationId:H(),url:H().url()}),F5=xt([L5,q5]),Zb=ur.extend({method:ve("elicitation/create"),params:F5}),Z5=gn.extend({elicitationId:H()}),H5=vn.extend({method:ve("notifications/elicitation/complete"),params:Z5}),Hb=lr.extend({action:yr(["accept","decline","cancel"]),content:of(t=>t===null?void 0:t,Rt(H(),xt([H(),ft(),er(),We(H())])).optional())}),B5=le({type:ve("ref/resource"),uri:H()});var V5=le({type:ve("ref/prompt"),name:H()}),G5=sn.extend({ref:xt([V5,B5]),argument:le({name:H(),value:H()}),context:le({arguments:Rt(H(),H()).optional()}).optional()}),W5=ur.extend({method:ve("completion/complete"),params:G5});var Bb=lr.extend({completion:vr({values:We(H()).max(100),total:At(ft().int()),hasMore:At(er())})}),K5=le({uri:H().startsWith("file://"),name:H().optional(),_meta:Rt(H(),kt()).optional()}),J5=ur.extend({method:ve("roots/list"),params:sn.optional()}),X5=lr.extend({roots:We(K5)}),Y5=vn.extend({method:ve("notifications/roots/list_changed"),params:gn.optional()}),zbe=xt([df,DF,W5,v5,o5,i5,VF,GF,KF,XF,QF,h5,f5,ff,hf,gf,yf]),Ube=xt([lf,pf,UF,Y5,Lu]),Lbe=xt([Ha,Fb,T5,Hb,X5,mf,vf,Ba]),qbe=xt([df,qb,Zb,J5,ff,hf,gf,yf]),Fbe=xt([lf,pf,_5,t5,Rb,Lb,zb,Lu,H5]),Zbe=xt([Ha,Eb,Bb,Db,Cb,Tb,Ib,Ob,os,Ub,mf,vf,Ba]),Se=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===Ce.UrlElicitationRequired&&n){let i=n;if(i.elicitations)return new _b(i.elicitations,r)}return new t(e,r,n)}},_b=class extends Se{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(Ce.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function aa(t){return t==="completed"||t==="failed"||t==="cancelled"}var wxe=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Vb(t){let r=Hp(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=LT(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Gb(t,e){let r=Un(t,e);if(!r.success)throw r.error;return r.data}var i3=6e4,_f=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(lf,r=>{this._oncancel(r)}),this.setNotificationHandler(pf,r=>{this._onprogress(r)}),this.setRequestHandler(df,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ff,async(r,n)=>{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new Se(Ce.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(hf,async(r,n)=>{let i=async()=>{let a=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(a,n.sessionId);){if(s.type==="response"||s.type==="error"){let c=s.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),s.type==="response")l(c);else{let d=c,p=new Se(d.error.code,d.error.message,d.error.data);l(p)}else{let d=s.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:n.requestId})}}let o=await this._taskStore.getTask(a,n.sessionId);if(!o)throw new Se(Ce.InvalidParams,`Task not found: ${a}`);if(!aa(o.status))return await this._waitForTaskUpdate(a,n.signal),await i();if(aa(o.status)){let s=await this._taskStore.getTaskResult(a,n.sessionId);return this._clearTaskQueue(a),{...s,_meta:{...s._meta,[ia]:{taskId:a}}}}return await i()};return await i()}),this.setRequestHandler(gf,async(r,n)=>{try{let{tasks:i,nextCursor:a}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:i,nextCursor:a,_meta:{}}}catch(i){throw new Se(Ce.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(yf,async(r,n)=>{try{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new Se(Ce.InvalidParams,`Task not found: ${r.params.taskId}`);if(aa(i.status))throw new Se(Ce.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 a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new Se(Ce.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...a}}catch(i){throw i instanceof Se?i:new Se(Ce.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,a=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:a,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),Se.fromError(Ce.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=a=>{n?.(a),this._onerror(a)};let i=this._transport?.onmessage;this._transport.onmessage=(a,o)=>{i?.(a,o),Au(a)||W1(a)?this._onresponse(a):Sb(a)?this._onrequest(a,o):G1(a)?this._onnotification(a):this._onerror(new Error(`Unknown message type: ${JSON.stringify(a)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let r=Se.fromError(Ce.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,a=e.params?._meta?.[ia]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:Ce.MethodNotFound,message:"Method not found"}};a&&this._taskMessageQueue?this._enqueueTaskMessage(a,{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 s=H1(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};a&&(d.relatedTask={taskId:a}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{let f={...p,relatedRequestId:e.id};a&&!f.relatedTask&&(f.relatedTask={taskId:a});let g=f.relatedTask?.taskId??a;return g&&c&&await c.updateTaskStatus(g,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:a,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&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};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{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:Ce.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{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),a=this._progressHandlers.get(i);if(!a){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let o=this._responseHandlers.get(i),s=this._timeoutInfo.get(i);if(s&&o&&s.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(c){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),o(c);return}a(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Au(e))n(e);else{let o=new Se(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 a=!1;if(Au(e)&&e.result&&typeof e.result=="object"){let o=e.result;if(o.task&&typeof o.task=="object"){let s=o.task;typeof s.taskId=="string"&&(a=!0,this._taskProgressTokens.set(s.taskId,r))}}if(a||this._progressHandlers.delete(r),Au(e))i(e);else{let o=Se.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 Se?o:new Se(Ce.InternalError,String(o))}}return}let a;try{let o=await this.request(e,Ba,n);if(o.task)a=o.task.taskId,yield{type:"taskCreated",task:o.task};else throw new Se(Ce.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:a},n);if(yield{type:"taskStatus",task:s},aa(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:a},r,n)}:s.status==="failed"?yield{type:"error",error:new Se(Ce.InternalError,`Task ${a} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new Se(Ce.InternalError,`Task ${a} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:a},r,n)};return}let c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(o){yield{type:"error",error:o instanceof Se?o:new Se(Ce.InternalError,String(o))}}}request(e,r,n){let{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,task:s,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=y=>{l(y)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(y){d(y);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}}),s&&(f.params={...f.params,task:s}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[ia]:c}});let g=y=>{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(y)}},{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(b=>this._onerror(new Error(`Failed to send cancellation: ${b}`)));let v=y instanceof Se?y:new Se(Ce.RequestTimeout,String(y));l(v)};this._responseHandlers.set(p,y=>{if(!n?.signal?.aborted){if(y instanceof Error)return l(y);try{let v=Un(r,y.result);v.success?u(v.data):l(v.error)}catch(v){l(v)}}}),n?.signal?.addEventListener("abort",()=>{g(n?.signal?.reason)});let _=n?.timeout??i3,h=()=>g(Se.fromError(Ce.RequestTimeout,"Request timed out",{timeout:_}));this._setupTimeout(p,_,n?.maxTotalTimeout,h,n?.resetTimeoutOnProgress??!1);let m=c?.taskId;if(m){let y=v=>{let b=this._responseHandlers.get(p);b?b(v):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,y),this._enqueueTaskMessage(m,{type:"request",message:f,timestamp:Date.now()}).catch(v=>{this._cleanupTimeout(p),l(v)})}else this._transport.send(f,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(y=>{this._cleanupTimeout(p),l(y)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},mf,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},vf,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},X1,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 s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[ia]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:s,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 s={...e,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[ia]:r.relatedTask}}}),this._transport?.send(s,r).catch(c=>this._onerror(c))});return}let o={...e,jsonrpc:"2.0"};r?.relatedTask&&(o={...o,params:{...o.params,_meta:{...o.params?._meta||{},[ia]:r.relatedTask}}}),await this._transport.send(o,r)}setRequestHandler(e,r){let n=Vb(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,a)=>{let o=Gb(e,i);return Promise.resolve(r(o,a))})}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=Vb(e);this._notificationHandlers.set(n,i=>{let a=Gb(e,i);return Promise.resolve(r(a))})}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"&&Sb(i.message)){let a=i.message.id,o=this._requestResolvers.get(a);o?(o(new Se(Ce.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(a)):this._onerror(new Error(`Resolver missing for request ${a} 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,a)=>{if(r.aborted){a(new Se(Ce.InvalidRequest,"Request cancelled"));return}let o=setTimeout(i,n);r.addEventListener("abort",()=>{clearTimeout(o),a(new Se(Ce.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 a=await n.getTask(i,r);if(!a)throw new Se(Ce.InvalidParams,"Failed to retrieve task: Task not found");return a},storeTaskResult:async(i,a,o)=>{await n.storeTaskResult(i,a,o,r);let s=await n.getTask(i,r);if(s){let c=Lu.parse({method:"notifications/tasks/status",params:s});await this.notification(c),aa(s.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>n.getTaskResult(i,r),updateTaskStatus:async(i,a,o)=>{let s=await n.getTask(i,r);if(!s)throw new Se(Ce.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(aa(s.status))throw new Se(Ce.InvalidParams,`Cannot update task "${i}" from terminal status "${s.status}" to "${a}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(i,a,o,r);let c=await n.getTask(i,r);if(c){let u=Lu.parse({method:"notifications/tasks/status",params:c});await this.notification(u),aa(c.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>n.listTasks(i,r)}}};function aI(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function oI(t,e){let r={...t};for(let n in e){let i=n,a=e[i];if(a===void 0)continue;let o=r[i];aI(o)&&aI(a)?r[i]={...o,...a}:r[i]=a}return r}var VO=ut(CS(),1),GO=ut(BO(),1);function W7(){let t=new VO.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,GO.default)(t),t}var rm=class{constructor(e){this._ajv=e??W7()}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 nm=class{constructor(e){this._client=e}async*callToolStream(e,r=os,n){let i=this._client,a={...n,task:n?.task??(i.isToolTask(e.name)?{}:void 0)},o=i.requestStream({method:"tools/call",params:e},r,a),s=i.getToolOutputValidator(e.name);for await(let c of o){if(c.type==="result"&&s){let u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new Se(Ce.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{let l=s(u.structuredContent);if(!l.valid){yield{type:"error",error:new Se(Ce.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof Se){yield{type:"error",error:l};return}yield{type:"error",error:new Se(Ce.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 WO(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 KO(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 im(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 a=n[i];r[i]===void 0&&Object.prototype.hasOwnProperty.call(a,"default")&&(r[i]=a.default),r[i]!==void 0&&im(a,r[i])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&im(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&im(r,e)}}function K7(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 ws=class extends _f{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 rm,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Lb,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",zb,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Rb,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new nm(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=oI(this._capabilities,e)}setRequestHandler(e,r){let i=Hp(e)?.method;if(!i)throw new Error("Schema is missing a method literal");let a;if(rs(i)){let s=i;a=s._zod?.def?.value??s.value}else{let s=i;a=s._def?.value??s.value}if(typeof a!="string")throw new Error("Schema method literal must be a string");let o=a;if(o==="elicitation/create"){let s=async(c,u)=>{let l=Un(Zb,c);if(!l.success){let y=l.error instanceof Error?l.error.message:String(l.error);throw new Se(Ce.InvalidParams,`Invalid elicitation request: ${y}`)}let{params:d}=l.data;d.mode=d.mode??"form";let{supportsFormMode:p,supportsUrlMode:f}=K7(this._capabilities.elicitation);if(d.mode==="form"&&!p)throw new Se(Ce.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!f)throw new Se(Ce.InvalidParams,"Client does not support URL-mode elicitation requests");let g=await Promise.resolve(r(c,u));if(d.task){let y=Un(Ba,g);if(!y.success){let v=y.error instanceof Error?y.error.message:String(y.error);throw new Se(Ce.InvalidParams,`Invalid task creation result: ${v}`)}return y.data}let _=Un(Hb,g);if(!_.success){let y=_.error instanceof Error?_.error.message:String(_.error);throw new Se(Ce.InvalidParams,`Invalid elicitation result: ${y}`)}let h=_.data,m=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&h.action==="accept"&&h.content&&m&&this._capabilities.elicitation?.form?.applyDefaults)try{im(m,h.content)}catch{}return h};return super.setRequestHandler(e,s)}if(o==="sampling/createMessage"){let s=async(c,u)=>{let l=Un(qb,c);if(!l.success){let g=l.error instanceof Error?l.error.message:String(l.error);throw new Se(Ce.InvalidParams,`Invalid sampling request: ${g}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let g=Un(Ba,p);if(!g.success){let _=g.error instanceof Error?g.error.message:String(g.error);throw new Se(Ce.InvalidParams,`Invalid task creation result: ${_}`)}return g.data}let f=Un(Fb,p);if(!f.success){let g=f.error instanceof Error?f.error.message:String(f.error);throw new Se(Ce.InvalidParams,`Invalid sampling result: ${g}`)}return f.data};return super.setRequestHandler(e,s)}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:bb,capabilities:this._capabilities,clientInfo:this._clientInfo}},Eb,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!q1.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){WO(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&KO(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Ha,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Bb,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},Ha,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},Db,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},Cb,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},Tb,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},Ib,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Ob,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},Ha,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},Ha,r)}async callTool(e,r=os,n){if(this.isToolTaskRequired(e.name))throw new Se(Ce.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),a=this.getToolOutputValidator(e.name);if(a){if(!i.structuredContent&&!i.isError)throw new Se(Ce.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(i.structuredContent)try{let o=a(i.structuredContent);if(!o.valid)throw new Se(Ce.InvalidParams,`Structured content does not match the tool's output schema: ${o.errorMessage}`)}catch(o){throw o instanceof Se?o:new Se(Ce.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},Ub,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,i){let a=nI.safeParse(n);if(!a.success)throw new Error(`Invalid ${e} listChanged options: ${a.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:o,debounceMs:s}=a.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(s){let d=this._listChangedDebounceTimers.get(e);d&&clearTimeout(d);let p=setTimeout(u,s);this._listChangedDebounceTimers.set(e,p)}else u()};this.setNotificationHandler(r,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var UR=ut(DR(),1),yl=ut(require("node:process"),1),LR=require("node:stream");var om=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),SG(r)}clear(){this._buffer=void 0}};function SG(t){return K1.parse(JSON.parse(t))}function zR(t){return JSON.stringify(t)+` `}var wG=yl.default.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function $G(){let t={};for(let e of wG){let r=yl.default.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var ks=class{constructor(e){this._readBuffer=new om,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new LR.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,UR.default)(this._serverParams.command,this._serverParams.args??[],{env:{...$G(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:yl.default.platform==="win32"&&EG(),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=zR(e);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};function EG(){return"type"in yl.default}Hr();we();var XS=ut(require("path"),1),eC=require("os"),Bn=require("fs"),no=require("child_process"),tC=require("util");we();xl();var um=(0,tC.promisify)(no.exec),rC=XS.default.join((0,eC.homedir)(),".claude-mem"),ro=XS.default.join(rC,"worker.pid");function nC(t){(0,Bn.mkdirSync)(rC,{recursive:!0}),(0,Bn.writeFileSync)(ro,JSON.stringify(t,null,2))}function iC(){if(!(0,Bn.existsSync)(ro))return null;try{return JSON.parse((0,Bn.readFileSync)(ro,"utf-8"))}catch(t){return E.warn("SYSTEM","Failed to parse PID file",{path:ro},t),null}}function Ui(){if((0,Bn.existsSync)(ro))try{(0,Bn.unlinkSync)(ro)}catch(t){E.warn("SYSTEM","Failed to remove PID file",{path:ro},t)}}function io(t){return process.platform==="win32"?Math.round(t*2):t}async function aC(t){if(process.platform!=="win32")return[];if(!Number.isInteger(t)||t<=0)return E.warn("SYSTEM","Invalid parent PID for child process enumeration",{parentPid:t}),[];try{let e=`powershell -NoProfile -NonInteractive -Command "Get-Process | Where-Object { \\$_.ParentProcessId -eq ${t} } | Select-Object -ExpandProperty Id"`,{stdout:r}=await um(e,{timeout:ma.POWERSHELL_COMMAND});return r.split(` `).map(n=>n.trim()).filter(n=>n.length>0&&/^\d+$/.test(n)).map(n=>parseInt(n,10)).filter(n=>n>0)}catch(e){return E.error("SYSTEM","Failed to enumerate child processes",{parentPid:t},e),[]}}async function oC(t){if(!Number.isInteger(t)||t<=0){E.warn("SYSTEM","Invalid PID for force kill",{pid:t});return}try{process.platform==="win32"?await um(`taskkill /PID ${t} /T /F`,{timeout:ma.POWERSHELL_COMMAND}):process.kill(t,"SIGKILL"),E.info("SYSTEM","Killed process",{pid:t})}catch(e){E.debug("SYSTEM","Process already exited during force kill",{pid:t},e)}}async function sC(t,e){let r=Date.now();for(;Date.now()-r{try{return process.kill(i,0),!0}catch{return!1}});if(n.length===0){E.info("SYSTEM","All child processes exited");return}E.debug("SYSTEM","Waiting for processes to exit",{stillAlive:n}),await new Promise(i=>setTimeout(i,100))}E.warn("SYSTEM","Timeout waiting for child processes to exit")}async function cC(){let t=process.platform==="win32",e=[];try{if(t){let r=`powershell -NoProfile -NonInteractive -Command "Get-CimInstance Win32_Process | Where-Object { \\$_.Name -like '*python*' -and \\$_.CommandLine -like '*chroma-mcp*' } | Select-Object -ExpandProperty ProcessId"`,{stdout:n}=await um(r,{timeout:ma.POWERSHELL_COMMAND});if(!n.trim()){E.debug("SYSTEM","No orphaned chroma-mcp processes found (Windows)");return}let i=n.split(` `).map(a=>a.trim()).filter(a=>a.length>0&&/^\d+$/.test(a));for(let a of i){let o=parseInt(a,10);!isNaN(o)&&Number.isInteger(o)&&o>0&&e.push(o)}}else{let{stdout:r}=await um('ps aux | grep "chroma-mcp" | grep -v grep || true');if(!r.trim()){E.debug("SYSTEM","No orphaned chroma-mcp processes found (Unix)");return}let n=r.trim().split(` -`);for(let i of n){let a=i.trim().split(/\s+/);if(a.length>1){let o=parseInt(a[1],10);!isNaN(o)&&Number.isInteger(o)&&o>0&&e.push(o)}}}}catch(r){E.error("SYSTEM","Failed to enumerate orphaned processes",{},r);return}if(e.length!==0){if(E.info("SYSTEM","Cleaning up orphaned chroma-mcp processes",{platform:t?"Windows":"Unix",count:e.length,pids:e}),t)for(let r of e){if(!Number.isInteger(r)||r<=0){E.warn("SYSTEM","Skipping invalid PID",{pid:r});continue}try{(0,no.execSync)(`taskkill /PID ${r} /T /F`,{timeout:ma.POWERSHELL_COMMAND,stdio:"ignore"})}catch(n){E.debug("SYSTEM","Failed to kill process, may have already exited",{pid:r},n)}}else for(let r of e)try{process.kill(r,"SIGKILL")}catch(n){E.debug("SYSTEM","Process already exited",{pid:r},n)}E.info("SYSTEM","Orphaned processes cleaned up",{count:e.length})}}function YS(t,e,r={}){let n=process.platform==="win32",i={...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r};if(n){let c=`wmic process call create "\\"${process.execPath}\\" \\"${t}\\" --daemon"`;try{return(0,no.execSync)(c,{stdio:"ignore",windowsHide:!0}),0}catch{return}}let a=(0,no.spawn)(process.execPath,[t,"--daemon"],{detached:!0,stdio:"ignore",env:i});if(a.pid!==void 0)return a.unref(),a.pid}function uC(t,e){return async r=>{if(e.value){E.warn("SYSTEM",`Received ${r} but shutdown already in progress`);return}e.value=!0,E.info("SYSTEM",`Received ${r}, shutting down...`);try{await t(),process.exit(0)}catch(n){E.error("SYSTEM","Error during shutdown",{},n),process.exit(0)}}}var QS=ut(require("path"),1),lC=require("os"),dC=require("fs");we();async function lm(t){try{return(await fetch(`http://127.0.0.1:${t}/api/health`)).ok}catch{return!1}}async function El(t,e=3e4){let r=Date.now();for(;Date.now()-rsetTimeout(n,500))}return!1}async function dm(t,e=1e4){let r=Date.now();for(;Date.now()-rsetTimeout(n,500))}return!1}async function pm(t){try{let e=await fetch(`http://127.0.0.1:${t}/api/admin/shutdown`,{method:"POST"});return e.ok?!0:(E.warn("SYSTEM","Shutdown request returned error",{port:t,status:e.status}),!1)}catch(e){return e instanceof Error&&e.message?.includes("ECONNREFUSED")?(E.debug("SYSTEM","Worker already stopped",{port:t},e),!1):(E.error("SYSTEM","Shutdown request failed unexpectedly",{port:t},e),!1)}}function RG(){let t=QS.default.join((0,lC.homedir)(),".claude","plugins","marketplaces","thedotmack"),e=QS.default.join(t,"package.json");return JSON.parse((0,dC.readFileSync)(e,"utf-8")).version}async function CG(t){try{let e=await fetch(`http://127.0.0.1:${t}/api/version`);return e.ok?(await e.json()).version:null}catch{return E.debug("SYSTEM","Could not fetch worker version",{port:t}),null}}async function pC(t){let e=RG(),r=await CG(t);return r?{matches:e===r,pluginVersion:e,workerVersion:r}:{matches:!0,pluginVersion:e,workerVersion:r}}we();async function fC(t){E.info("SYSTEM","Shutdown initiated"),Ui();let e=await aC(process.pid);if(E.info("SYSTEM","Found child processes",{count:e.length,pids:e}),t.server&&(await NG(t.server),E.info("SYSTEM","HTTP server closed")),await t.sessionManager.shutdownAll(),t.mcpClient&&(await t.mcpClient.close(),E.info("SYSTEM","MCP client closed")),t.dbManager&&await t.dbManager.close(),e.length>0){E.info("SYSTEM","Force killing remaining children");for(let r of e)await oC(r);await sC(e,5e3)}E.info("SYSTEM","Worker shutdown complete")}async function NG(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)),E.info("SYSTEM","Waited for Windows port cleanup"))}var C4=ut(bh(),1),s$=ut(require("fs"),1),c$=ut(require("path"),1);we();var i$=ut(bh(),1),T4=ut(v4(),1),I4=ut(require("path"),1);Jr();we();function a$(t){let e=[];e.push(i$.default.json({limit:"50mb"})),e.push((0,T4.default)()),e.push((i,a,o)=>{let c=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(g=>i.path.endsWith(g)),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);E.info("HTTP",`\u2192 ${i.method} ${i.path}`,{requestId:d},p);let f=a.send.bind(a);a.send=function(g){let _=Date.now()-l;return E.info("HTTP",`\u2190 ${a.statusCode} ${i.path}`,{requestId:d,duration:`${_}ms`}),f(g)},o()});let r=Kr(),n=I4.default.join(r,"plugin","ui");return e.push(i$.default.static(n)),e}function Sh(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")){E.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 o$(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=${E.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}we();var Qs=class extends Error{constructor(r,n=500,i,a){super(r);this.statusCode=n;this.code=i;this.details=a;this.name="AppError"}};function P4(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}var O4=(t,e,r,n)=>{let i=t instanceof Qs?t.statusCode:500;E.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof Qs?t.code:void 0},t);let a=P4(t.name||"Error",t.message,t instanceof Qs?t.code:void 0,t instanceof Qs?t.details:void 0);r.status(i).json(a)};function R4(t,e){e.status(404).json(P4("NotFound",`Cannot ${t.method} ${t.path}`))}var Gne="9.0.11",wh=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,C4.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,()=>{E.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,E.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(R4),this.app.use(O4)}setupMiddleware(){a$(o$).forEach(r=>this.app.use(r))}setupCoreRoutes(){let e="TEST-008-wrapper-ipc";this.app.get("/api/health",(r,n)=>{n.status(200).json({status:"ok",build:e,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()})}),this.app.get("/api/readiness",(r,n)=>{this.options.getInitializationComplete()?n.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):n.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(r,n)=>{n.status(200).json({version:Gne})}),this.app.get("/api/instructions",async(r,n)=>{let i=r.query.topic||"all",a=r.query.operation;try{let o;if(a){let s=c$.default.join(__dirname,"../skills/mem-search/operations",`${a}.md`);o=await s$.promises.readFile(s,"utf-8")}else{let s=c$.default.join(__dirname,"../skills/mem-search/SKILL.md"),c=await s$.promises.readFile(s,"utf-8");o=this.extractInstructionSection(c,i)}n.json({content:[{type:"text",text:o}]})}catch{n.status(404).json({error:"Instruction not found"})}}),this.app.post("/api/admin/restart",Sh,async(r,n)=>{n.json({status:"restarting"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(E.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):setTimeout(async()=>{await this.options.onRestart()},100)}),this.app.post("/api/admin/shutdown",Sh,async(r,n)=>{n.json({status:"shutting_down"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(E.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):setTimeout(async()=>{await this.options.onShutdown()},100)})}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),a=e.indexOf(n);return i===-1?e:a===-1?e.substring(i):e.substring(i,a).trim()}};var lt=ut(require("path"),1),ec=require("os"),Gt=require("fs"),A4=require("child_process"),M4=require("util");we();Hr();var In=require("fs"),ud=require("path");we();function N4(t){try{return(0,In.existsSync)(t)?JSON.parse((0,In.readFileSync)(t,"utf-8")):{}}catch(e){return E.error("CONFIG","Failed to read Cursor registry, using empty registry",{file:t,error:e instanceof Error?e.message:String(e)}),{}}}function j4(t,e){let r=(0,ud.join)(t,"..");(0,In.mkdirSync)(r,{recursive:!0}),(0,In.writeFileSync)(t,JSON.stringify(e,null,2))}function u$(t,e){let r=(0,ud.join)(t,".cursor","rules"),n=(0,ud.join)(r,"claude-mem-context.mdc"),i=`${n}.tmp`;(0,In.mkdirSync)(r,{recursive:!0});let a=`--- +`);for(let i of n){let a=i.trim().split(/\s+/);if(a.length>1){let o=parseInt(a[1],10);!isNaN(o)&&Number.isInteger(o)&&o>0&&e.push(o)}}}}catch(r){E.error("SYSTEM","Failed to enumerate orphaned processes",{},r);return}if(e.length!==0){if(E.info("SYSTEM","Cleaning up orphaned chroma-mcp processes",{platform:t?"Windows":"Unix",count:e.length,pids:e}),t)for(let r of e){if(!Number.isInteger(r)||r<=0){E.warn("SYSTEM","Skipping invalid PID",{pid:r});continue}try{(0,no.execSync)(`taskkill /PID ${r} /T /F`,{timeout:ma.POWERSHELL_COMMAND,stdio:"ignore"})}catch(n){E.debug("SYSTEM","Failed to kill process, may have already exited",{pid:r},n)}}else for(let r of e)try{process.kill(r,"SIGKILL")}catch(n){E.debug("SYSTEM","Process already exited",{pid:r},n)}E.info("SYSTEM","Orphaned processes cleaned up",{count:e.length})}}function YS(t,e,r={}){let n=process.platform==="win32",i={...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r};if(n){let c=`wmic process call create "\\"${process.execPath}\\" \\"${t}\\" --daemon"`;try{return(0,no.execSync)(c,{stdio:"ignore",windowsHide:!0}),0}catch{return}}let a=(0,no.spawn)(process.execPath,[t,"--daemon"],{detached:!0,stdio:"ignore",env:i});if(a.pid!==void 0)return a.unref(),a.pid}function uC(t,e){return async r=>{if(e.value){E.warn("SYSTEM",`Received ${r} but shutdown already in progress`);return}e.value=!0,E.info("SYSTEM",`Received ${r}, shutting down...`);try{await t(),process.exit(0)}catch(n){E.error("SYSTEM","Error during shutdown",{},n),process.exit(0)}}}var QS=ut(require("path"),1),lC=require("os"),dC=require("fs");we();async function lm(t){try{return(await fetch(`http://127.0.0.1:${t}/api/health`)).ok}catch{return!1}}async function El(t,e=3e4){let r=Date.now();for(;Date.now()-rsetTimeout(n,500))}return!1}async function dm(t,e=1e4){let r=Date.now();for(;Date.now()-rsetTimeout(n,500))}return!1}async function pm(t){try{let e=await fetch(`http://127.0.0.1:${t}/api/admin/shutdown`,{method:"POST"});return e.ok?!0:(E.warn("SYSTEM","Shutdown request returned error",{port:t,status:e.status}),!1)}catch(e){return e instanceof Error&&e.message?.includes("ECONNREFUSED")?(E.debug("SYSTEM","Worker already stopped",{port:t},e),!1):(E.error("SYSTEM","Shutdown request failed unexpectedly",{port:t},e),!1)}}function RG(){let t=QS.default.join((0,lC.homedir)(),".claude","plugins","marketplaces","thedotmack"),e=QS.default.join(t,"package.json");return JSON.parse((0,dC.readFileSync)(e,"utf-8")).version}async function CG(t){try{let e=await fetch(`http://127.0.0.1:${t}/api/version`);return e.ok?(await e.json()).version:null}catch{return E.debug("SYSTEM","Could not fetch worker version",{port:t}),null}}async function pC(t){let e=RG(),r=await CG(t);return r?{matches:e===r,pluginVersion:e,workerVersion:r}:{matches:!0,pluginVersion:e,workerVersion:r}}we();async function fC(t){E.info("SYSTEM","Shutdown initiated"),Ui();let e=await aC(process.pid);if(E.info("SYSTEM","Found child processes",{count:e.length,pids:e}),t.server&&(await NG(t.server),E.info("SYSTEM","HTTP server closed")),await t.sessionManager.shutdownAll(),t.mcpClient&&(await t.mcpClient.close(),E.info("SYSTEM","MCP client closed")),t.dbManager&&await t.dbManager.close(),e.length>0){E.info("SYSTEM","Force killing remaining children");for(let r of e)await oC(r);await sC(e,5e3)}E.info("SYSTEM","Worker shutdown complete")}async function NG(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)),E.info("SYSTEM","Waited for Windows port cleanup"))}var C4=ut(bh(),1),s$=ut(require("fs"),1),c$=ut(require("path"),1);we();var i$=ut(bh(),1),T4=ut(v4(),1),I4=ut(require("path"),1);ln();we();function a$(t){let e=[];e.push(i$.default.json({limit:"50mb"})),e.push((0,T4.default)()),e.push((i,a,o)=>{let c=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(g=>i.path.endsWith(g)),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);E.info("HTTP",`\u2192 ${i.method} ${i.path}`,{requestId:d},p);let f=a.send.bind(a);a.send=function(g){let _=Date.now()-l;return E.info("HTTP",`\u2190 ${a.statusCode} ${i.path}`,{requestId:d,duration:`${_}ms`}),f(g)},o()});let r=Kr(),n=I4.default.join(r,"plugin","ui");return e.push(i$.default.static(n)),e}function Sh(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")){E.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 o$(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=${E.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}we();var Qs=class extends Error{constructor(r,n=500,i,a){super(r);this.statusCode=n;this.code=i;this.details=a;this.name="AppError"}};function P4(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}var O4=(t,e,r,n)=>{let i=t instanceof Qs?t.statusCode:500;E.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof Qs?t.code:void 0},t);let a=P4(t.name||"Error",t.message,t instanceof Qs?t.code:void 0,t instanceof Qs?t.details:void 0);r.status(i).json(a)};function R4(t,e){e.status(404).json(P4("NotFound",`Cannot ${t.method} ${t.path}`))}var Gne="9.0.11",wh=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,C4.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,()=>{E.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,E.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(R4),this.app.use(O4)}setupMiddleware(){a$(o$).forEach(r=>this.app.use(r))}setupCoreRoutes(){let e="TEST-008-wrapper-ipc";this.app.get("/api/health",(r,n)=>{n.status(200).json({status:"ok",build:e,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()})}),this.app.get("/api/readiness",(r,n)=>{this.options.getInitializationComplete()?n.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):n.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(r,n)=>{n.status(200).json({version:Gne})}),this.app.get("/api/instructions",async(r,n)=>{let i=r.query.topic||"all",a=r.query.operation;try{let o;if(a){let s=c$.default.join(__dirname,"../skills/mem-search/operations",`${a}.md`);o=await s$.promises.readFile(s,"utf-8")}else{let s=c$.default.join(__dirname,"../skills/mem-search/SKILL.md"),c=await s$.promises.readFile(s,"utf-8");o=this.extractInstructionSection(c,i)}n.json({content:[{type:"text",text:o}]})}catch{n.status(404).json({error:"Instruction not found"})}}),this.app.post("/api/admin/restart",Sh,async(r,n)=>{n.json({status:"restarting"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(E.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):setTimeout(async()=>{await this.options.onRestart()},100)}),this.app.post("/api/admin/shutdown",Sh,async(r,n)=>{n.json({status:"shutting_down"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(E.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):setTimeout(async()=>{await this.options.onShutdown()},100)})}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),a=e.indexOf(n);return i===-1?e:a===-1?e.substring(i):e.substring(i,a).trim()}};var lt=ut(require("path"),1),ec=require("os"),Gt=require("fs"),A4=require("child_process"),M4=require("util");we();Hr();var In=require("fs"),ud=require("path");we();function N4(t){try{return(0,In.existsSync)(t)?JSON.parse((0,In.readFileSync)(t,"utf-8")):{}}catch(e){return E.error("CONFIG","Failed to read Cursor registry, using empty registry",{file:t,error:e instanceof Error?e.message:String(e)}),{}}}function j4(t,e){let r=(0,ud.join)(t,"..");(0,In.mkdirSync)(r,{recursive:!0}),(0,In.writeFileSync)(t,JSON.stringify(e,null,2))}function u$(t,e){let r=(0,ud.join)(t,".cursor","rules"),n=(0,ud.join)(r,"claude-mem-context.mdc"),i=`${n}.tmp`;(0,In.mkdirSync)(r,{recursive:!0});let a=`--- alwaysApply: true description: "Claude-mem context from past sessions (auto-updated)" --- @@ -821,7 +821,7 @@ Examples: claude-mem cursor status # Check if hooks are installed For more info: https://docs.claude-mem.ai/cursor - `),0}}$h();var H4=require("bun:sqlite");Jr();we();function Z4(t){return t.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/+$/,"")}function d$(t,e){let r=Z4(t),n=Z4(e);if(r.startsWith(n+"/"))return!r.slice(n.length+1).includes("/");let i=n.split("/"),a=r.split("/");if(a.length<2)return!1;let o=a.slice(0,-1).join("/"),s=a[a.length-1];if(n.endsWith("/"+o)||n===o)return!s.includes("/");for(let c=0;cn.name==="observations_fts"||n.name==="session_summaries_fts")||(E.info("DB","Creating FTS5 tables"),this.db.run(` + `),0}}$h();var H4=require("bun:sqlite");ln();we();function Z4(t){return t.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/+$/,"")}function d$(t,e){let r=Z4(t),n=Z4(e);if(r.startsWith(n+"/"))return!r.slice(n.length+1).includes("/");let i=n.split("/"),a=r.split("/");if(a.length<2)return!1;let o=a.slice(0,-1).join("/"),s=a[a.length-1];if(n.endsWith("/"+o)||n===o)return!s.includes("/");for(let c=0;cn.name==="observations_fts"||n.name==="session_summaries_fts")||(E.info("DB","Creating FTS5 tables"),this.db.run(` CREATE VIRTUAL TABLE IF NOT EXISTS observations_fts USING fts5( title, subtitle, @@ -945,7 +945,7 @@ For more info: https://docs.claude-mem.ai/cursor FROM user_prompts WHERE content_session_id = ? ORDER BY prompt_number ASC - `).all(e)}close(){this.db.close()}};$h();we();un();Jr();var B4=ut(require("path"),1),V4=ut(require("os"),1),nie="9.0.11",kh=class{client=null;transport=null;connected=!1;project;collectionName;VECTOR_DB_DIR;BATCH_SIZE=100;disabled;constructor(e){this.project=e,this.collectionName=`cm__${e}`,this.VECTOR_DB_DIR=B4.default.join(V4.default.homedir(),".claude-mem","vector-db"),this.disabled=process.platform==="win32",this.disabled&&E.warn("CHROMA_SYNC","Vector search disabled on Windows (prevents console popups)",{project:this.project,reason:"MCP SDK subprocess spawning causes visible console windows"})}isDisabled(){return this.disabled}async ensureConnection(){if(!(this.connected&&this.client)){E.info("CHROMA_SYNC","Connecting to Chroma MCP server...",{project:this.project});try{let r=Qe.loadFromFile(Tn).CLAUDE_MEM_PYTHON_VERSION,n=process.platform==="win32",i={command:"uvx",args:["--python",r,"chroma-mcp","--client-type","persistent","--data-dir",this.VECTOR_DB_DIR],stderr:"ignore"};n&&(i.windowsHide=!0,E.debug("CHROMA_SYNC","Windows detected, attempting to hide console window",{project:this.project})),this.transport=new ks(i),this.client=new ws({name:"claude-mem-chroma-sync",version:nie},{capabilities:{}}),await this.client.connect(this.transport),this.connected=!0,E.info("CHROMA_SYNC","Connected to Chroma MCP server",{project:this.project})}catch(e){throw E.error("CHROMA_SYNC","Failed to connect to Chroma MCP server",{project:this.project},e),new Error(`Chroma connection failed: ${e instanceof Error?e.message:String(e)}`)}}}async ensureCollection(){if(await this.ensureConnection(),!this.client)throw new Error(`Chroma client not initialized. Call ensureConnection() before using client methods. Project: ${this.project}`);try{await this.client.callTool({name:"chroma_get_collection_info",arguments:{collection_name:this.collectionName}}),E.debug("CHROMA_SYNC","Collection exists",{collection:this.collectionName})}catch(e){let r=e instanceof Error?e.message:String(e);if(r.includes("Not connected")||r.includes("Connection closed")||r.includes("MCP error -32000"))throw this.connected=!1,this.client=null,E.error("CHROMA_SYNC","Connection lost during collection check",{collection:this.collectionName},e),new Error(`Chroma connection lost: ${r}`);E.error("CHROMA_SYNC","Collection check failed, attempting to create",{collection:this.collectionName},e),E.info("CHROMA_SYNC","Creating collection",{collection:this.collectionName});try{await this.client.callTool({name:"chroma_create_collection",arguments:{collection_name:this.collectionName,embedding_function_name:"default"}}),E.info("CHROMA_SYNC","Collection created",{collection:this.collectionName})}catch(i){throw E.error("CHROMA_SYNC","Failed to create collection",{collection:this.collectionName},i),new Error(`Collection creation failed: ${i instanceof Error?i.message:String(i)}`)}}}formatObservationDocs(e){let r=[],n=e.facts?JSON.parse(e.facts):[],i=e.concepts?JSON.parse(e.concepts):[],a=e.files_read?JSON.parse(e.files_read):[],o=e.files_modified?JSON.parse(e.files_modified):[],s={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&&(s.subtitle=e.subtitle),i.length>0&&(s.concepts=i.join(",")),a.length>0&&(s.files_read=a.join(",")),o.length>0&&(s.files_modified=o.join(",")),e.narrative&&r.push({id:`obs_${e.id}_narrative`,document:e.narrative,metadata:{...s,field_type:"narrative"}}),e.text&&r.push({id:`obs_${e.id}_text`,document:e.text,metadata:{...s,field_type:"text"}}),n.forEach((c,u)=>{r.push({id:`obs_${e.id}_fact_${u}`,document:c,metadata:{...s,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){if(await this.ensureCollection(),!this.client)throw new Error(`Chroma client not initialized. Call ensureConnection() before using client methods. Project: ${this.project}`);try{await this.client.callTool({name:"chroma_add_documents",arguments:{collection_name:this.collectionName,documents:e.map(r=>r.document),ids:e.map(r=>r.id),metadatas:e.map(r=>r.metadata)}}),E.debug("CHROMA_SYNC","Documents added",{collection:this.collectionName,count:e.length})}catch(r){throw E.error("CHROMA_SYNC","Failed to add documents",{collection:this.collectionName,count:e.length},r),new Error(`Document add failed: ${r instanceof Error?r.message:String(r)}`)}}}async syncObservation(e,r,n,i,a,o,s=0){if(this.disabled)return;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:a,discovery_tokens:s,created_at:new Date(o*1e3).toISOString(),created_at_epoch:o},u=this.formatObservationDocs(c);E.info("CHROMA_SYNC","Syncing observation",{observationId:e,documentCount:u.length,project:n}),await this.addDocuments(u)}async syncSummary(e,r,n,i,a,o,s=0){if(this.disabled)return;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:a,discovery_tokens:s,created_at:new Date(o*1e3).toISOString(),created_at_epoch:o},u=this.formatSummaryDocs(c);E.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,a,o){if(this.disabled)return;let s={id:e,content_session_id:"",prompt_number:a,prompt_text:i,created_at:new Date(o*1e3).toISOString(),created_at_epoch:o,memory_session_id:r,project:n},c=this.formatUserPromptDoc(s);E.info("CHROMA_SYNC","Syncing user prompt",{promptId:e,project:n}),await this.addDocuments([c])}async getExistingChromaIds(){if(await this.ensureConnection(),!this.client)throw new Error(`Chroma client not initialized. Call ensureConnection() before using client methods. Project: ${this.project}`);let e=new Set,r=new Set,n=new Set,i=0,a=1e3;for(E.info("CHROMA_SYNC","Fetching existing Chroma document IDs...",{project:this.project});;)try{let s=(await this.client.callTool({name:"chroma_get_documents",arguments:{collection_name:this.collectionName,limit:a,offset:i,where:{project:this.project},include:["metadatas"]}})).content[0];if(s.type!=="text")throw new Error("Unexpected response type from chroma_get_documents");let u=JSON.parse(s.text).metadatas||[];if(u.length===0)break;for(let l of u)l.sqlite_id&&(l.doc_type==="observation"?e.add(l.sqlite_id):l.doc_type==="session_summary"?r.add(l.sqlite_id):l.doc_type==="user_prompt"&&n.add(l.sqlite_id));i+=a,E.debug("CHROMA_SYNC","Fetched batch of existing IDs",{project:this.project,offset:i,batchSize:u.length})}catch(o){throw E.error("CHROMA_SYNC","Failed to fetch existing IDs",{project:this.project},o),o}return E.info("CHROMA_SYNC","Existing IDs fetched",{project:this.project,observations:e.size,summaries:r.size,prompts:n.size}),{observations:e,summaries:r,prompts:n}}async ensureBackfilled(){if(this.disabled)return;E.info("CHROMA_SYNC","Starting smart backfill",{project:this.project}),await this.ensureCollection();let e=await this.getExistingChromaIds(),r=new $a;try{let n=Array.from(e.observations),i=n.length>0?`AND id NOT IN (${n.join(",")})`:"",a=r.db.prepare(` + `).all(e)}close(){this.db.close()}};$h();we();cn();ln();var B4=ut(require("path"),1),V4=ut(require("os"),1),nie="9.0.11",kh=class{client=null;transport=null;connected=!1;project;collectionName;VECTOR_DB_DIR;BATCH_SIZE=100;disabled;constructor(e){this.project=e,this.collectionName=`cm__${e}`,this.VECTOR_DB_DIR=B4.default.join(V4.default.homedir(),".claude-mem","vector-db"),this.disabled=process.platform==="win32",this.disabled&&E.warn("CHROMA_SYNC","Vector search disabled on Windows (prevents console popups)",{project:this.project,reason:"MCP SDK subprocess spawning causes visible console windows"})}isDisabled(){return this.disabled}async ensureConnection(){if(!(this.connected&&this.client)){E.info("CHROMA_SYNC","Connecting to Chroma MCP server...",{project:this.project});try{let r=Qe.loadFromFile(Tn).CLAUDE_MEM_PYTHON_VERSION,n=process.platform==="win32",i={command:"uvx",args:["--python",r,"chroma-mcp","--client-type","persistent","--data-dir",this.VECTOR_DB_DIR],stderr:"ignore"};n&&(i.windowsHide=!0,E.debug("CHROMA_SYNC","Windows detected, attempting to hide console window",{project:this.project})),this.transport=new ks(i),this.client=new ws({name:"claude-mem-chroma-sync",version:nie},{capabilities:{}}),await this.client.connect(this.transport),this.connected=!0,E.info("CHROMA_SYNC","Connected to Chroma MCP server",{project:this.project})}catch(e){throw E.error("CHROMA_SYNC","Failed to connect to Chroma MCP server",{project:this.project},e),new Error(`Chroma connection failed: ${e instanceof Error?e.message:String(e)}`)}}}async ensureCollection(){if(await this.ensureConnection(),!this.client)throw new Error(`Chroma client not initialized. Call ensureConnection() before using client methods. Project: ${this.project}`);try{await this.client.callTool({name:"chroma_get_collection_info",arguments:{collection_name:this.collectionName}}),E.debug("CHROMA_SYNC","Collection exists",{collection:this.collectionName})}catch(e){let r=e instanceof Error?e.message:String(e);if(r.includes("Not connected")||r.includes("Connection closed")||r.includes("MCP error -32000"))throw this.connected=!1,this.client=null,E.error("CHROMA_SYNC","Connection lost during collection check",{collection:this.collectionName},e),new Error(`Chroma connection lost: ${r}`);E.error("CHROMA_SYNC","Collection check failed, attempting to create",{collection:this.collectionName},e),E.info("CHROMA_SYNC","Creating collection",{collection:this.collectionName});try{await this.client.callTool({name:"chroma_create_collection",arguments:{collection_name:this.collectionName,embedding_function_name:"default"}}),E.info("CHROMA_SYNC","Collection created",{collection:this.collectionName})}catch(i){throw E.error("CHROMA_SYNC","Failed to create collection",{collection:this.collectionName},i),new Error(`Collection creation failed: ${i instanceof Error?i.message:String(i)}`)}}}formatObservationDocs(e){let r=[],n=e.facts?JSON.parse(e.facts):[],i=e.concepts?JSON.parse(e.concepts):[],a=e.files_read?JSON.parse(e.files_read):[],o=e.files_modified?JSON.parse(e.files_modified):[],s={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&&(s.subtitle=e.subtitle),i.length>0&&(s.concepts=i.join(",")),a.length>0&&(s.files_read=a.join(",")),o.length>0&&(s.files_modified=o.join(",")),e.narrative&&r.push({id:`obs_${e.id}_narrative`,document:e.narrative,metadata:{...s,field_type:"narrative"}}),e.text&&r.push({id:`obs_${e.id}_text`,document:e.text,metadata:{...s,field_type:"text"}}),n.forEach((c,u)=>{r.push({id:`obs_${e.id}_fact_${u}`,document:c,metadata:{...s,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){if(await this.ensureCollection(),!this.client)throw new Error(`Chroma client not initialized. Call ensureConnection() before using client methods. Project: ${this.project}`);try{await this.client.callTool({name:"chroma_add_documents",arguments:{collection_name:this.collectionName,documents:e.map(r=>r.document),ids:e.map(r=>r.id),metadatas:e.map(r=>r.metadata)}}),E.debug("CHROMA_SYNC","Documents added",{collection:this.collectionName,count:e.length})}catch(r){throw E.error("CHROMA_SYNC","Failed to add documents",{collection:this.collectionName,count:e.length},r),new Error(`Document add failed: ${r instanceof Error?r.message:String(r)}`)}}}async syncObservation(e,r,n,i,a,o,s=0){if(this.disabled)return;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:a,discovery_tokens:s,created_at:new Date(o*1e3).toISOString(),created_at_epoch:o},u=this.formatObservationDocs(c);E.info("CHROMA_SYNC","Syncing observation",{observationId:e,documentCount:u.length,project:n}),await this.addDocuments(u)}async syncSummary(e,r,n,i,a,o,s=0){if(this.disabled)return;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:a,discovery_tokens:s,created_at:new Date(o*1e3).toISOString(),created_at_epoch:o},u=this.formatSummaryDocs(c);E.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,a,o){if(this.disabled)return;let s={id:e,content_session_id:"",prompt_number:a,prompt_text:i,created_at:new Date(o*1e3).toISOString(),created_at_epoch:o,memory_session_id:r,project:n},c=this.formatUserPromptDoc(s);E.info("CHROMA_SYNC","Syncing user prompt",{promptId:e,project:n}),await this.addDocuments([c])}async getExistingChromaIds(){if(await this.ensureConnection(),!this.client)throw new Error(`Chroma client not initialized. Call ensureConnection() before using client methods. Project: ${this.project}`);let e=new Set,r=new Set,n=new Set,i=0,a=1e3;for(E.info("CHROMA_SYNC","Fetching existing Chroma document IDs...",{project:this.project});;)try{let s=(await this.client.callTool({name:"chroma_get_documents",arguments:{collection_name:this.collectionName,limit:a,offset:i,where:{project:this.project},include:["metadatas"]}})).content[0];if(s.type!=="text")throw new Error("Unexpected response type from chroma_get_documents");let u=JSON.parse(s.text).metadatas||[];if(u.length===0)break;for(let l of u)l.sqlite_id&&(l.doc_type==="observation"?e.add(l.sqlite_id):l.doc_type==="session_summary"?r.add(l.sqlite_id):l.doc_type==="user_prompt"&&n.add(l.sqlite_id));i+=a,E.debug("CHROMA_SYNC","Fetched batch of existing IDs",{project:this.project,offset:i,batchSize:u.length})}catch(o){throw E.error("CHROMA_SYNC","Failed to fetch existing IDs",{project:this.project},o),o}return E.info("CHROMA_SYNC","Existing IDs fetched",{project:this.project,observations:e.size,summaries:r.size,prompts:n.size}),{observations:e,summaries:r,prompts:n}}async ensureBackfilled(){if(this.disabled)return;E.info("CHROMA_SYNC","Starting smart backfill",{project:this.project}),await this.ensureCollection();let e=await this.getExistingChromaIds(),r=new $a;try{let n=Array.from(e.observations),i=n.length>0?`AND id NOT IN (${n.join(",")})`:"",a=r.db.prepare(` SELECT * FROM observations WHERE project = ? ${i} ORDER BY id ASC @@ -971,8 +971,8 @@ For more info: https://docs.claude-mem.ai/cursor FROM user_prompts up JOIN sdk_sessions s ON up.content_session_id = s.content_session_id WHERE s.project = ? - `).get(this.project);E.info("CHROMA_SYNC","Backfilling user prompts",{project:this.project,missing:_.length,existing:e.prompts.size,total:h.count});let m=[];for(let y of _)m.push(this.formatUserPromptDoc(y));for(let y=0;ysetTimeout(i,1e3))}}toPendingMessageWithId(e){return{...this.store.toPendingMessage(e),_persistentId:e.id,_originalTimestamp:e.created_at_epoch}}waitForMessage(e){return new Promise(r=>{let n=()=>{a(),r()},i=()=>{a(),r()},a=()=>{this.events.off("message",n),e.removeEventListener("abort",i)};this.events.once("message",n),e.addEventListener("abort",i,{once:!0})})}};var Ph=require("child_process"),G4=require("util");we();Jr();var iie=(0,G4.promisify)(Ph.exec),Oh=new Map;function aie(t,e,r){Oh.set(t,{pid:t,sessionDbId:e,spawnedAt:Date.now(),process:r}),E.info("PROCESS",`Registered PID ${t} for session ${e}`,{pid:t,sessionDbId:e})}function dd(t){Oh.delete(t),E.debug("PROCESS",`Unregistered PID ${t}`,{pid:t})}function W4(t){let e=[];for(let[,r]of Oh)r.sessionDbId===t&&e.push(r);return e.length>1&&E.warn("PROCESS",`Multiple processes found for session ${t}`,{count:e.length,pids:e.map(r=>r.pid)}),e[0]}async function K4(t,e=5e3){let{pid:r,process:n}=t;if(n.killed||n.exitCode!==null){dd(r);return}let i=new Promise(o=>{n.once("exit",()=>o())}),a=new Promise(o=>{setTimeout(o,e)});if(await Promise.race([i,a]),n.killed||n.exitCode!==null){dd(r);return}E.warn("PROCESS",`PID ${r} did not exit after ${e}ms, sending SIGKILL`,{pid:r,timeoutMs:e});try{n.kill("SIGKILL")}catch{}await new Promise(o=>setTimeout(o,200)),dd(r)}async function oie(){if(process.platform==="win32")return 0;try{let{stdout:t}=await iie('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]);E.warn("PROCESS",`Killing system orphan PID ${i}`,{pid:i});try{process.kill(i,"SIGKILL"),e++}catch{}}}return e}catch{return 0}}async function sie(t){let e=0;for(let[r,n]of Oh)if(!t.has(n.sessionDbId)){E.warn("PROCESS",`Killing orphan PID ${r} (session ${n.sessionDbId} gone)`,{pid:r,sessionDbId:n.sessionDbId});try{n.process.kill("SIGKILL"),e++}catch{}dd(r)}return e+=await oie(),e}function J4(t){return Sr(xh),e=>{let r={...e.env,CLAUDE_CONFIG_DIR:xh},n=(0,Ph.spawn)(e.command,e.args,{cwd:e.cwd,env:r,stdio:["pipe","pipe","pipe"],signal:e.signal,windowsHide:!0});return n.pid&&(aie(n.pid,t,n),n.on("exit",()=>{n.pid&&dd(n.pid)})),{stdin:n.stdin,stdout:n.stdout,get killed(){return n.killed},get exitCode(){return n.exitCode},kill:n.kill.bind(n),on:n.on.bind(n),once:n.once.bind(n),off:n.off.bind(n)}}}function X4(t,e=300*1e3){let r=setInterval(async()=>{try{let n=t(),i=await sie(n);i>0&&E.info("PROCESS",`Reaper cleaned up ${i} orphaned processes`,{killed:i})}catch(n){E.error("PROCESS","Reaper error",{},n)}},e);return()=>clearInterval(r)}var Rh=class{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 ld(e.db,3)}return this.pendingStore}setOnSessionDeleted(e){this.onSessionDeletedCallback=e}initializeSession(e,r,n){E.debug("SESSION","initializeSession called",{sessionDbId:e,promptNumber:n,has_currentUserPrompt:!!r});let i=this.sessions.get(e);if(i){E.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&&(E.debug("SESSION","Updating project from database",{sessionDbId:e,oldProject:i.project,newProject:c.project}),i.project=c.project),r?(E.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):E.debug("SESSION","No currentUserPrompt provided for existing session",{sessionDbId:e,promptNumber:n,usingCachedPrompt:i.userPrompt.substring(0,80)}),i}let a=this.dbManager.getSessionById(e);E.debug("SESSION","Fetched session from database",{sessionDbId:e,content_session_id:a.content_session_id,memory_session_id:a.memory_session_id}),a.memory_session_id&&E.warn("SESSION","Discarding stale memory_session_id from previous worker instance (Issue #817)",{sessionDbId:e,staleMemorySessionId:a.memory_session_id,reason:"SDK context lost on worker restart - will capture new ID"});let o=r||a.user_prompt;r?E.debug("SESSION","Initializing session with fresh userPrompt",{sessionDbId:e,promptNumber:n,userPrompt:r.substring(0,80)}):E.debug("SESSION","No currentUserPrompt provided for new session, using database",{sessionDbId:e,promptNumber:n,dbPrompt:a.user_prompt.substring(0,80)}),i={sessionDbId:e,contentSessionId:a.content_session_id,memorySessionId:null,project:a.project,userPrompt:o,pendingMessages:[],abortController:new AbortController,generatorPromise:null,lastPromptNumber:n||this.dbManager.getSessionStore().getPromptNumberFromUserPrompts(a.content_session_id),startTime:Date.now(),cumulativeInputTokens:0,cumulativeOutputTokens:0,earliestPendingTimestamp:null,conversationHistory:[],currentProvider:null},E.debug("SESSION","Creating new session object (memorySessionId cleared to prevent stale resume)",{sessionDbId:e,contentSessionId:a.content_session_id,dbMemorySessionId:a.memory_session_id||"(none in DB)",memorySessionId:"(cleared - will capture fresh from SDK)",lastPromptNumber:n||this.dbManager.getSessionStore().getPromptNumberFromUserPrompts(a.content_session_id)}),this.sessions.set(e,i);let s=new Y4.EventEmitter;return this.sessionQueues.set(e,s),E.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),s=this.getPendingStore().getPendingCount(e),c=E.formatTool(r.tool_name,r.tool_input);E.info("QUEUE",`ENQUEUED | sessionDbId=${e} | messageId=${o} | type=observation | tool=${c} | depth=${s}`,{sessionId:e})}catch(o){throw E.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),s=this.getPendingStore().getPendingCount(e);E.info("QUEUE",`ENQUEUED | sessionDbId=${e} | messageId=${o} | type=summarize | depth=${s}`,{sessionId:e})}catch(o){throw E.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;r.abortController.abort(),r.generatorPromise&&await r.generatorPromise.catch(()=>{E.debug("SYSTEM","Generator already failed, cleaning up",{sessionId:r.sessionDbId})});let i=W4(e);i&&!i.process.killed&&i.process.exitCode===null&&(E.debug("SESSION",`Waiting for subprocess PID ${i.pid} to exit`,{sessionId:e,pid:i.pid}),await K4(i,5e3)),this.sessions.delete(e),this.sessionQueues.delete(e),E.info("SESSION","Session deleted",{sessionId:e,duration:`${(n/1e3).toFixed(1)}s`,project:r.project}),this.onSessionDeletedCallback&&this.onSessionDeletedCallback()}async shutdownAll(){let e=Array.from(this.sessions.keys());await Promise.all(e.map(r=>this.deleteSession(r)))}hasPendingMessages(){return this.getPendingStore().hasAnyPendingWork()}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.getPendingStore().hasAnyPendingWork()}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 Ih(this.getPendingStore(),n);for await(let a of i.createIterator(e,r.abortController.signal))r.earliestPendingTimestamp===null?r.earliestPendingTimestamp=a._originalTimestamp:r.earliestPendingTimestamp=Math.min(r.earliestPendingTimestamp,a._originalTimestamp),yield a}getPendingMessageStore(){return this.getPendingStore()}};we();var Ch=class{sseClients=new Set;addClient(e){this.sseClients.add(e),E.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),E.debug("WORKER","Client disconnected",{total:this.sseClients.size})}broadcast(e){if(this.sseClients.size===0){E.debug("WORKER","SSE broadcast skipped (no clients)",{eventType:e.type});return}let r={...e,timestamp:Date.now()},n=`data: ${JSON.stringify(r)} + `).get(this.project);E.info("CHROMA_SYNC","Backfilling user prompts",{project:this.project,missing:_.length,existing:e.prompts.size,total:h.count});let m=[];for(let y of _)m.push(this.formatUserPromptDoc(y));for(let y=0;ysetTimeout(i,1e3))}}toPendingMessageWithId(e){return{...this.store.toPendingMessage(e),_persistentId:e.id,_originalTimestamp:e.created_at_epoch}}waitForMessage(e){return new Promise(r=>{let n=()=>{a(),r()},i=()=>{a(),r()},a=()=>{this.events.off("message",n),e.removeEventListener("abort",i)};this.events.once("message",n),e.addEventListener("abort",i,{once:!0})})}};var Ph=require("child_process"),G4=require("util");we();var iie=(0,G4.promisify)(Ph.exec),Oh=new Map;function aie(t,e,r){Oh.set(t,{pid:t,sessionDbId:e,spawnedAt:Date.now(),process:r}),E.info("PROCESS",`Registered PID ${t} for session ${e}`,{pid:t,sessionDbId:e})}function dd(t){Oh.delete(t),E.debug("PROCESS",`Unregistered PID ${t}`,{pid:t})}function W4(t){let e=[];for(let[,r]of Oh)r.sessionDbId===t&&e.push(r);return e.length>1&&E.warn("PROCESS",`Multiple processes found for session ${t}`,{count:e.length,pids:e.map(r=>r.pid)}),e[0]}async function K4(t,e=5e3){let{pid:r,process:n}=t;if(n.killed||n.exitCode!==null){dd(r);return}let i=new Promise(o=>{n.once("exit",()=>o())}),a=new Promise(o=>{setTimeout(o,e)});if(await Promise.race([i,a]),n.killed||n.exitCode!==null){dd(r);return}E.warn("PROCESS",`PID ${r} did not exit after ${e}ms, sending SIGKILL`,{pid:r,timeoutMs:e});try{n.kill("SIGKILL")}catch{}await new Promise(o=>setTimeout(o,200)),dd(r)}async function oie(){if(process.platform==="win32")return 0;try{let{stdout:t}=await iie('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]);E.warn("PROCESS",`Killing system orphan PID ${i}`,{pid:i});try{process.kill(i,"SIGKILL"),e++}catch{}}}return e}catch{return 0}}async function sie(t){let e=0;for(let[r,n]of Oh)if(!t.has(n.sessionDbId)){E.warn("PROCESS",`Killing orphan PID ${r} (session ${n.sessionDbId} gone)`,{pid:r,sessionDbId:n.sessionDbId});try{n.process.kill("SIGKILL"),e++}catch{}dd(r)}return e+=await oie(),e}function J4(t){return e=>{let r=(0,Ph.spawn)(e.command,e.args,{cwd:e.cwd,env:e.env,stdio:["pipe","pipe","pipe"],signal:e.signal,windowsHide:!0});return r.pid&&(aie(r.pid,t,r),r.on("exit",()=>{r.pid&&dd(r.pid)})),{stdin:r.stdin,stdout:r.stdout,get killed(){return r.killed},get exitCode(){return r.exitCode},kill:r.kill.bind(r),on:r.on.bind(r),once:r.once.bind(r),off:r.off.bind(r)}}}function X4(t,e=300*1e3){let r=setInterval(async()=>{try{let n=t(),i=await sie(n);i>0&&E.info("PROCESS",`Reaper cleaned up ${i} orphaned processes`,{killed:i})}catch(n){E.error("PROCESS","Reaper error",{},n)}},e);return()=>clearInterval(r)}var Rh=class{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 ld(e.db,3)}return this.pendingStore}setOnSessionDeleted(e){this.onSessionDeletedCallback=e}initializeSession(e,r,n){E.debug("SESSION","initializeSession called",{sessionDbId:e,promptNumber:n,has_currentUserPrompt:!!r});let i=this.sessions.get(e);if(i){E.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&&(E.debug("SESSION","Updating project from database",{sessionDbId:e,oldProject:i.project,newProject:c.project}),i.project=c.project),r?(E.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):E.debug("SESSION","No currentUserPrompt provided for existing session",{sessionDbId:e,promptNumber:n,usingCachedPrompt:i.userPrompt.substring(0,80)}),i}let a=this.dbManager.getSessionById(e);E.debug("SESSION","Fetched session from database",{sessionDbId:e,content_session_id:a.content_session_id,memory_session_id:a.memory_session_id}),a.memory_session_id&&E.warn("SESSION","Discarding stale memory_session_id from previous worker instance (Issue #817)",{sessionDbId:e,staleMemorySessionId:a.memory_session_id,reason:"SDK context lost on worker restart - will capture new ID"});let o=r||a.user_prompt;r?E.debug("SESSION","Initializing session with fresh userPrompt",{sessionDbId:e,promptNumber:n,userPrompt:r.substring(0,80)}):E.debug("SESSION","No currentUserPrompt provided for new session, using database",{sessionDbId:e,promptNumber:n,dbPrompt:a.user_prompt.substring(0,80)}),i={sessionDbId:e,contentSessionId:a.content_session_id,memorySessionId:null,project:a.project,userPrompt:o,pendingMessages:[],abortController:new AbortController,generatorPromise:null,lastPromptNumber:n||this.dbManager.getSessionStore().getPromptNumberFromUserPrompts(a.content_session_id),startTime:Date.now(),cumulativeInputTokens:0,cumulativeOutputTokens:0,earliestPendingTimestamp:null,conversationHistory:[],currentProvider:null},E.debug("SESSION","Creating new session object (memorySessionId cleared to prevent stale resume)",{sessionDbId:e,contentSessionId:a.content_session_id,dbMemorySessionId:a.memory_session_id||"(none in DB)",memorySessionId:"(cleared - will capture fresh from SDK)",lastPromptNumber:n||this.dbManager.getSessionStore().getPromptNumberFromUserPrompts(a.content_session_id)}),this.sessions.set(e,i);let s=new Y4.EventEmitter;return this.sessionQueues.set(e,s),E.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),s=this.getPendingStore().getPendingCount(e),c=E.formatTool(r.tool_name,r.tool_input);E.info("QUEUE",`ENQUEUED | sessionDbId=${e} | messageId=${o} | type=observation | tool=${c} | depth=${s}`,{sessionId:e})}catch(o){throw E.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),s=this.getPendingStore().getPendingCount(e);E.info("QUEUE",`ENQUEUED | sessionDbId=${e} | messageId=${o} | type=summarize | depth=${s}`,{sessionId:e})}catch(o){throw E.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;r.abortController.abort(),r.generatorPromise&&await r.generatorPromise.catch(()=>{E.debug("SYSTEM","Generator already failed, cleaning up",{sessionId:r.sessionDbId})});let i=W4(e);i&&!i.process.killed&&i.process.exitCode===null&&(E.debug("SESSION",`Waiting for subprocess PID ${i.pid} to exit`,{sessionId:e,pid:i.pid}),await K4(i,5e3)),this.sessions.delete(e),this.sessionQueues.delete(e),E.info("SESSION","Session deleted",{sessionId:e,duration:`${(n/1e3).toFixed(1)}s`,project:r.project}),this.onSessionDeletedCallback&&this.onSessionDeletedCallback()}async shutdownAll(){let e=Array.from(this.sessions.keys());await Promise.all(e.map(r=>this.deleteSession(r)))}hasPendingMessages(){return this.getPendingStore().hasAnyPendingWork()}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.getPendingStore().hasAnyPendingWork()}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 Ih(this.getPendingStore(),n);for await(let a of i.createIterator(e,r.abortController.signal))r.earliestPendingTimestamp===null?r.earliestPendingTimestamp=a._originalTimestamp:r.earliestPendingTimestamp=Math.min(r.earliestPendingTimestamp,a._originalTimestamp),yield a}getPendingMessageStore(){return this.getPendingStore()}};we();var Ch=class{sseClients=new Set;addClient(e){this.sseClients.add(e),E.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),E.debug("WORKER","Client disconnected",{total:this.sseClients.size})}broadcast(e){if(this.sseClients.size===0){E.debug("WORKER","SSE broadcast skipped (no clients)",{eventType:e.type});return}let r={...e,timestamp:Date.now()},n=`data: ${JSON.stringify(r)} `;E.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)} @@ -1112,7 +1112,7 @@ ${n.prompts.format_examples} ${n.prompts.footer} -${n.prompts.header_memory_continued}`}un();Jr();Mr();var p$=["429","500","502","503","ECONNREFUSED","ETIMEDOUT","fetch failed"];we();we();Mr();function e2(t,e){let r=[],n=/([\s\S]*?)<\/observation>/g,i;for(;(i=n.exec(t))!==null;){let a=i[1],o=bi(a,"type"),s=bi(a,"title"),c=bi(a,"subtitle"),u=bi(a,"narrative"),l=jh(a,"facts","fact"),d=jh(a,"concepts","concept"),p=jh(a,"files_read","file"),f=jh(a,"files_modified","file"),_=Be.getInstance().getActiveMode().observation_types.map(v=>v.id),h=_[0],m=h;o?_.includes(o.trim())?m=o.trim():E.error("PARSER",`Invalid observation type: ${o}, using "${h}"`,{correlationId:e}):E.error("PARSER",`Observation missing type field, using "${h}"`,{correlationId:e});let y=d.filter(v=>v!==m);y.length!==d.length&&E.error("PARSER","Removed observation type from concepts array",{correlationId:e,type:m,originalConcepts:d,cleanedConcepts:y}),r.push({type:m,title:s,subtitle:c,facts:l,narrative:u,concepts:y,files_read:p,files_modified:f})}return r}function t2(t,e){let n=//.exec(t);if(n)return E.info("PARSER","Summary skipped",{sessionId:e,reason:n[1]}),null;let a=/([\s\S]*?)<\/summary>/.exec(t);if(!a)return null;let o=a[1],s=bi(o,"request"),c=bi(o,"investigated"),u=bi(o,"learned"),l=bi(o,"completed"),d=bi(o,"next_steps"),p=bi(o,"notes");return{request:s,investigated:c,learned:u,completed:l,next_steps:d,notes:p}}function bi(t,e){let n=new RegExp(`<${e}>([^<]*)`).exec(t);if(!n)return null;let i=n[1].trim();return i===""?null:i}function jh(t,e,r){let n=[],a=new RegExp(`<${e}>(.*?)`,"s").exec(t);if(!a)return n;let o=a[1],s=new RegExp(`<${r}>([^<]+)`,"g"),c;for(;(c=s.exec(o))!==null;)n.push(c[1].trim());return n}var Jn=require("fs"),On=ut(require("path"),1),n2=ut(require("os"),1);we();sc();un();Hr();var cie=On.default.join(n2.default.homedir(),".claude-mem","settings.json");function uie(t,e){if(!t||!t.trim()||t.startsWith("~")||t.startsWith("http://")||t.startsWith("https://")||t.includes(" ")||t.includes("#"))return!1;if(e){let r=On.default.isAbsolute(t)?t:On.default.resolve(e,t),n=On.default.resolve(e);if(!r.startsWith(n+On.default.sep)&&r!==n)return!1}return!0}function lie(t,e){let r="",n="";if(!t)return`${r} +${n.prompts.header_memory_continued}`}cn();ln();Mr();var p$=["429","500","502","503","ECONNREFUSED","ETIMEDOUT","fetch failed"];we();we();Mr();function e2(t,e){let r=[],n=/([\s\S]*?)<\/observation>/g,i;for(;(i=n.exec(t))!==null;){let a=i[1],o=bi(a,"type"),s=bi(a,"title"),c=bi(a,"subtitle"),u=bi(a,"narrative"),l=jh(a,"facts","fact"),d=jh(a,"concepts","concept"),p=jh(a,"files_read","file"),f=jh(a,"files_modified","file"),_=Be.getInstance().getActiveMode().observation_types.map(v=>v.id),h=_[0],m=h;o?_.includes(o.trim())?m=o.trim():E.error("PARSER",`Invalid observation type: ${o}, using "${h}"`,{correlationId:e}):E.error("PARSER",`Observation missing type field, using "${h}"`,{correlationId:e});let y=d.filter(v=>v!==m);y.length!==d.length&&E.error("PARSER","Removed observation type from concepts array",{correlationId:e,type:m,originalConcepts:d,cleanedConcepts:y}),r.push({type:m,title:s,subtitle:c,facts:l,narrative:u,concepts:y,files_read:p,files_modified:f})}return r}function t2(t,e){let n=//.exec(t);if(n)return E.info("PARSER","Summary skipped",{sessionId:e,reason:n[1]}),null;let a=/([\s\S]*?)<\/summary>/.exec(t);if(!a)return null;let o=a[1],s=bi(o,"request"),c=bi(o,"investigated"),u=bi(o,"learned"),l=bi(o,"completed"),d=bi(o,"next_steps"),p=bi(o,"notes");return{request:s,investigated:c,learned:u,completed:l,next_steps:d,notes:p}}function bi(t,e){let n=new RegExp(`<${e}>([^<]*)`).exec(t);if(!n)return null;let i=n[1].trim();return i===""?null:i}function jh(t,e,r){let n=[],a=new RegExp(`<${e}>(.*?)`,"s").exec(t);if(!a)return n;let o=a[1],s=new RegExp(`<${r}>([^<]+)`,"g"),c;for(;(c=s.exec(o))!==null;)n.push(c[1].trim());return n}var Jn=require("fs"),On=ut(require("path"),1),n2=ut(require("os"),1);we();sc();cn();Hr();var cie=On.default.join(n2.default.homedir(),".claude-mem","settings.json");function uie(t,e){if(!t||!t.trim()||t.startsWith("~")||t.startsWith("http://")||t.startsWith("https://")||t.includes(" ")||t.includes("#"))return!1;if(e){let r=On.default.isAbsolute(t)?t:On.default.resolve(e,t),n=On.default.resolve(e);if(!r.startsWith(n+On.default.sep)&&r!==n)return!1}return!0}function lie(t,e){let r="",n="";if(!t)return`${r} ${e} ${n}`;let i=t.indexOf(r),a=t.indexOf(n);return i!==-1&&a!==-1?t.substring(0,i)+`${r} ${e} @@ -1127,14 +1127,14 @@ ${n}`}function die(t,e){let r=On.default.join(t,"CLAUDE.md"),n=`${r}.tmp`;if(!(0 `:""},this._extScope=$,this._scope=new r.Scope({parent:$}),this._nodes=[new _]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,T){let N=this._extScope.value($,T);return(this._values[N.prefix]||(this._values[N.prefix]=new Set)).add(N),N}getScopeValue($,T){return this._extScope.getValue($,T)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,T,N,W){let K=this._scope.toName(T);return N!==void 0&&W&&(this._constants[K.str]=N),this._leafNode(new o($,K,N)),K}const($,T,N){return this._def(r.varKinds.const,$,T,N)}let($,T,N){return this._def(r.varKinds.let,$,T,N)}var($,T,N){return this._def(r.varKinds.var,$,T,N)}assign($,T,N){return this._leafNode(new s($,T,N))}add($,T){return this._leafNode(new c($,t.operators.ADD,T))}code($){return typeof $=="function"?$():$!==e.nil&&this._leafNode(new p($)),this}object(...$){let T=["{"];for(let[N,W]of $)T.length>1&&T.push(","),T.push(N),(N!==W||this.opts.es5)&&(T.push(":"),(0,e.addCodeArg)(T,W));return T.push("}"),new e._Code(T)}if($,T,N){if(this._blockNode(new m($)),T&&N)this.code(T).else().code(N).endIf();else if(T)this.code(T).endIf();else if(N)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new m($))}else(){return this._elseNode(new h)}endIf(){return this._endBlockNode(m,h)}_for($,T){return this._blockNode($),T&&this.code(T).endFor(),this}for($,T){return this._for(new v($),T)}forRange($,T,N,W,K=this.opts.es5?r.varKinds.var:r.varKinds.let){let pe=this._scope.toName($);return this._for(new b(K,pe,T,N),()=>W(pe))}forOf($,T,N,W=r.varKinds.const){let K=this._scope.toName($);if(this.opts.es5){let pe=T instanceof e.Name?T:this.var("_arr",T);return this.forRange("_i",0,(0,e._)`${pe}.length`,ce=>{this.var(K,(0,e._)`${pe}[${ce}]`),N(K)})}return this._for(new S("of",W,K,T),()=>N(K))}forIn($,T,N,W=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf($,(0,e._)`Object.keys(${T})`,N);let K=this._scope.toName($);return this._for(new S("in",W,K,T),()=>N(K))}endFor(){return this._endBlockNode(y)}label($){return this._leafNode(new u($))}break($){return this._leafNode(new l($))}return($){let T=new w;if(this._blockNode(T),this.code($),T.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(w)}try($,T,N){if(!T&&!N)throw new Error('CodeGen: "try" without "catch" and "finally"');let W=new k;if(this._blockNode(W),this.code($),T){let K=this.name("e");this._currNode=W.catch=new O(K),T(K)}return N&&(this._currNode=W.finally=new A,this.code(N)),this._endBlockNode(O,A)}throw($){return this._leafNode(new d($))}block($,T){return this._blockStarts.push(this._nodes.length),$&&this.code($).endBlock(T),this}endBlock($){let T=this._blockStarts.pop();if(T===void 0)throw new Error("CodeGen: not in self-balancing block");let N=this._nodes.length-T;if(N<0||$!==void 0&&N!==$)throw new Error(`CodeGen: wrong number of nodes: ${N} vs ${$} expected`);return this._nodes.length=T,this}func($,T=e.nil,N,W){return this._blockNode(new x($,T,N)),W&&this.code(W).endFunc(),this}endFunc(){return this._endBlockNode(x)}optimize($=1){for(;$-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode($){return this._currNode.nodes.push($),this}_blockNode($){this._currNode.nodes.push($),this._nodes.push($)}_endBlockNode($,T){let N=this._currNode;if(N instanceof $||T&&N instanceof T)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${T?`${$.kind}/${T.kind}`:$.kind}"`)}_elseNode($){let T=this._currNode;if(!(T instanceof m))throw new Error('CodeGen: "else" without "if"');return this._currNode=T.else=$,this}get _root(){return this._nodes[0]}get _currNode(){let $=this._nodes;return $[$.length-1]}set _currNode($){let T=this._nodes;T[T.length-1]=$}}t.CodeGen=M;function L(C,$){for(let T in $)C[T]=(C[T]||0)+($[T]||0);return C}function B(C,$){return $ instanceof e._CodeOrName?L(C,$.names):C}function U(C,$,T){if(C instanceof e.Name)return N(C);if(!W(C))return C;return new e._Code(C._items.reduce((K,pe)=>(pe instanceof e.Name&&(pe=N(pe)),pe instanceof e._Code?K.push(...pe._items):K.push(pe),K),[]));function N(K){let pe=T[K.str];return pe===void 0||$[K.str]!==1?K:(delete $[K.str],pe)}function W(K){return K instanceof e._Code&&K._items.some(pe=>pe instanceof e.Name&&$[pe.str]===1&&T[pe.str]!==void 0)}}function Y(C,$){for(let T in $)C[T]=(C[T]||0)-($[T]||0)}function me(C){return typeof C=="boolean"||typeof C=="number"||C===null?!C:(0,e._)`!${D(C)}`}t.not=me;var et=I(t.operators.AND);function ht(...C){return C.reduce(et)}t.and=ht;var fe=I(t.operators.OR);function F(...C){return C.reduce(fe)}t.or=F;function I(C){return($,T)=>$===e.nil?T:T===e.nil?$:(0,e._)`${D($)} ${C} ${D(T)}`}function D(C){return C instanceof e.Name?C:(0,e._)`(${C})`}}),dt=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkStrictMode=t.getErrorPath=t.Type=t.useFunc=t.setEvaluated=t.evaluatedPropsToName=t.mergeEvaluated=t.eachItem=t.unescapeJsonPointer=t.escapeJsonPointer=t.escapeFragment=t.unescapeFragment=t.schemaRefOrVal=t.schemaHasRulesButRef=t.schemaHasRules=t.checkUnknownRules=t.alwaysValidSchema=t.toHash=void 0;var e=Xe(),r=qh();function n(x){let w={};for(let k of x)w[k]=!0;return w}t.toHash=n;function i(x,w){return typeof w=="boolean"?w:Object.keys(w).length===0?!0:(a(x,w),!o(w,x.self.RULES.all))}t.alwaysValidSchema=i;function a(x,w=x.schema){let{opts:k,self:O}=x;if(!k.strictSchema||typeof w=="boolean")return;let A=O.RULES.keywords;for(let M in w)A[M]||S(x,`unknown keyword: "${M}"`)}t.checkUnknownRules=a;function o(x,w){if(typeof x=="boolean")return!x;for(let k in x)if(w[k])return!0;return!1}t.schemaHasRules=o;function s(x,w){if(typeof x=="boolean")return!x;for(let k in x)if(k!=="$ref"&&w.all[k])return!0;return!1}t.schemaHasRulesButRef=s;function c({topSchemaRef:x,schemaPath:w},k,O,A){if(!A){if(typeof k=="number"||typeof k=="boolean")return k;if(typeof k=="string")return(0,e._)`${k}`}return(0,e._)`${x}${w}${(0,e.getProperty)(O)}`}t.schemaRefOrVal=c;function u(x){return p(decodeURIComponent(x))}t.unescapeFragment=u;function l(x){return encodeURIComponent(d(x))}t.escapeFragment=l;function d(x){return typeof x=="number"?`${x}`:x.replace(/~/g,"~0").replace(/\//g,"~1")}t.escapeJsonPointer=d;function p(x){return x.replace(/~1/g,"/").replace(/~0/g,"~")}t.unescapeJsonPointer=p;function f(x,w){if(Array.isArray(x))for(let k of x)w(k);else w(x)}t.eachItem=f;function g({mergeNames:x,mergeToName:w,mergeValues:k,resultToName:O}){return(A,M,L,B)=>{let U=L===void 0?M:L instanceof e.Name?(M instanceof e.Name?x(A,M,L):w(A,M,L),L):M instanceof e.Name?(w(A,L,M),M):k(M,L);return B===e.Name&&!(U instanceof e.Name)?O(A,U):U}}t.mergeEvaluated={props:g({mergeNames:(x,w,k)=>x.if((0,e._)`${k} !== true && ${w} !== undefined`,()=>{x.if((0,e._)`${w} === true`,()=>x.assign(k,!0),()=>x.assign(k,(0,e._)`${k} || {}`).code((0,e._)`Object.assign(${k}, ${w})`))}),mergeToName:(x,w,k)=>x.if((0,e._)`${k} !== true`,()=>{w===!0?x.assign(k,!0):(x.assign(k,(0,e._)`${k} || {}`),h(x,k,w))}),mergeValues:(x,w)=>x===!0?!0:{...x,...w},resultToName:_}),items:g({mergeNames:(x,w,k)=>x.if((0,e._)`${k} !== true && ${w} !== undefined`,()=>x.assign(k,(0,e._)`${w} === true ? true : ${k} > ${w} ? ${k} : ${w}`)),mergeToName:(x,w,k)=>x.if((0,e._)`${k} !== true`,()=>x.assign(k,w===!0?!0:(0,e._)`${k} > ${w} ? ${k} : ${w}`)),mergeValues:(x,w)=>x===!0?!0:Math.max(x,w),resultToName:(x,w)=>x.var("items",w)})};function _(x,w){if(w===!0)return x.var("props",!0);let k=x.var("props",(0,e._)`{}`);return w!==void 0&&h(x,k,w),k}t.evaluatedPropsToName=_;function h(x,w,k){Object.keys(k).forEach(O=>x.assign((0,e._)`${w}${(0,e.getProperty)(O)}`,!0))}t.setEvaluated=h;var m={};function y(x,w){return x.scopeValue("func",{ref:w,code:m[w.code]||(m[w.code]=new r._Code(w.code))})}t.useFunc=y;var v;(function(x){x[x.Num=0]="Num",x[x.Str=1]="Str"})(v||(t.Type=v={}));function b(x,w,k){if(x instanceof e.Name){let O=w===v.Num;return k?O?(0,e._)`"[" + ${x} + "]"`:(0,e._)`"['" + ${x} + "']"`:O?(0,e._)`"/" + ${x}`:(0,e._)`"/" + ${x}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return k?(0,e.getProperty)(x).toString():"/"+d(x)}t.getErrorPath=b;function S(x,w,k=x.opts.strictSchema){if(k){if(w=`strict mode: ${w}`,k===!0)throw new Error(w);x.self.logger.warn(w)}}t.checkStrictMode=S}),Oa=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),r={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};t.default=r}),Xh=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;var e=Xe(),r=dt(),n=Oa();t.keywordError={message:({keyword:h})=>(0,e.str)`must pass "${h}" keyword validation`},t.keyword$DataError={message:({keyword:h,schemaType:m})=>m?(0,e.str)`"${h}" keyword must be ${m} ($data)`:(0,e.str)`"${h}" keyword is invalid ($data)`};function i(h,m=t.keywordError,y,v){let{it:b}=h,{gen:S,compositeRule:x,allErrors:w}=b,k=d(h,m,y);v??(x||w)?c(S,k):u(b,(0,e._)`[${k}]`)}t.reportError=i;function a(h,m=t.keywordError,y){let{it:v}=h,{gen:b,compositeRule:S,allErrors:x}=v,w=d(h,m,y);c(b,w),S||x||u(v,n.default.vErrors)}t.reportExtraError=a;function o(h,m){h.assign(n.default.errors,m),h.if((0,e._)`${n.default.vErrors} !== null`,()=>h.if(m,()=>h.assign((0,e._)`${n.default.vErrors}.length`,m),()=>h.assign(n.default.vErrors,null)))}t.resetErrorsCount=o;function s({gen:h,keyword:m,schemaValue:y,data:v,errsCount:b,it:S}){if(b===void 0)throw new Error("ajv implementation error");let x=h.name("err");h.forRange("i",b,n.default.errors,w=>{h.const(x,(0,e._)`${n.default.vErrors}[${w}]`),h.if((0,e._)`${x}.instancePath === undefined`,()=>h.assign((0,e._)`${x}.instancePath`,(0,e.strConcat)(n.default.instancePath,S.errorPath))),h.assign((0,e._)`${x}.schemaPath`,(0,e.str)`${S.errSchemaPath}/${m}`),S.opts.verbose&&(h.assign((0,e._)`${x}.schema`,y),h.assign((0,e._)`${x}.data`,v))})}t.extendErrors=s;function c(h,m){let y=h.const("err",m);h.if((0,e._)`${n.default.vErrors} === null`,()=>h.assign(n.default.vErrors,(0,e._)`[${y}]`),(0,e._)`${n.default.vErrors}.push(${y})`),h.code((0,e._)`${n.default.errors}++`)}function u(h,m){let{gen:y,validateName:v,schemaEnv:b}=h;b.$async?y.throw((0,e._)`new ${h.ValidationError}(${m})`):(y.assign((0,e._)`${v}.errors`,m),y.return(!1))}var l={keyword:new e.Name("keyword"),schemaPath:new e.Name("schemaPath"),params:new e.Name("params"),propertyName:new e.Name("propertyName"),message:new e.Name("message"),schema:new e.Name("schema"),parentSchema:new e.Name("parentSchema")};function d(h,m,y){let{createErrors:v}=h.it;return v===!1?(0,e._)`{}`:p(h,m,y)}function p(h,m,y={}){let{gen:v,it:b}=h,S=[f(b,y),g(h,y)];return _(h,m,S),v.object(...S)}function f({errorPath:h},{instancePath:m}){let y=m?(0,e.str)`${h}${(0,r.getErrorPath)(m,r.Type.Str)}`:h;return[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,y)]}function g({keyword:h,it:{errSchemaPath:m}},{schemaPath:y,parentSchema:v}){let b=v?m:(0,e.str)`${m}/${h}`;return y&&(b=(0,e.str)`${b}${(0,r.getErrorPath)(y,r.Type.Str)}`),[l.schemaPath,b]}function _(h,{params:m,message:y},v){let{keyword:b,data:S,schemaValue:x,it:w}=h,{opts:k,propertyName:O,topSchemaRef:A,schemaPath:M}=w;v.push([l.keyword,b],[l.params,typeof m=="function"?m(h):m||(0,e._)`{}`]),k.messages&&v.push([l.message,typeof y=="function"?y(h):y]),k.verbose&&v.push([l.schema,x],[l.parentSchema,(0,e._)`${A}${M}`],[n.default.data,S]),O&&v.push([l.propertyName,O])}}),Sie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.boolOrEmptySchema=t.topBoolOrEmptySchema=void 0;var e=Xh(),r=Xe(),n=Oa(),i={message:"boolean schema is false"};function a(c){let{gen:u,schema:l,validateName:d}=c;l===!1?s(c,!1):typeof l=="object"&&l.$async===!0?u.return(n.default.data):(u.assign((0,r._)`${d}.errors`,null),u.return(!0))}t.topBoolOrEmptySchema=a;function o(c,u){let{gen:l,schema:d}=c;d===!1?(l.var(u,!1),s(c)):l.var(u,!0)}t.boolOrEmptySchema=o;function s(c,u){let{gen:l,data:d}=c,p={gen:l,keyword:"false schema",data:d,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:c};(0,e.reportError)(p,i,void 0,u)}}),U2=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getRules=t.isJSONType=void 0;var e=["string","number","integer","boolean","null","object","array"],r=new Set(e);function n(a){return typeof a=="string"&&r.has(a)}t.isJSONType=n;function i(){let a={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...a,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},a.number,a.string,a.array,a.object],post:{rules:[]},all:{},keywords:{}}}t.getRules=i}),L2=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shouldUseRule=t.shouldUseGroup=t.schemaHasRulesForType=void 0;function e({schema:i,self:a},o){let s=a.RULES.types[o];return s&&s!==!0&&r(i,s)}t.schemaHasRulesForType=e;function r(i,a){return a.rules.some(o=>n(i,o))}t.shouldUseGroup=r;function n(i,a){var o;return i[a.keyword]!==void 0||((o=a.definition.implements)===null||o===void 0?void 0:o.some(s=>i[s]!==void 0))}t.shouldUseRule=n}),Fh=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reportTypeError=t.checkDataTypes=t.checkDataType=t.coerceAndCheckDataType=t.getJSONTypes=t.getSchemaTypes=t.DataType=void 0;var e=U2(),r=L2(),n=Xh(),i=Xe(),a=dt(),o;(function(v){v[v.Correct=0]="Correct",v[v.Wrong=1]="Wrong"})(o||(t.DataType=o={}));function s(v){let b=c(v.type);if(b.includes("null")){if(v.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!b.length&&v.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');v.nullable===!0&&b.push("null")}return b}t.getSchemaTypes=s;function c(v){let b=Array.isArray(v)?v:v?[v]:[];if(b.every(e.isJSONType))return b;throw new Error("type must be JSONType or JSONType[]: "+b.join(","))}t.getJSONTypes=c;function u(v,b){let{gen:S,data:x,opts:w}=v,k=d(b,w.coerceTypes),O=b.length>0&&!(k.length===0&&b.length===1&&(0,r.schemaHasRulesForType)(v,b[0]));if(O){let A=_(b,x,w.strictNumbers,o.Wrong);S.if(A,()=>{k.length?p(v,b,k):m(v)})}return O}t.coerceAndCheckDataType=u;var l=new Set(["string","number","integer","boolean","null"]);function d(v,b){return b?v.filter(S=>l.has(S)||b==="array"&&S==="array"):[]}function p(v,b,S){let{gen:x,data:w,opts:k}=v,O=x.let("dataType",(0,i._)`typeof ${w}`),A=x.let("coerced",(0,i._)`undefined`);k.coerceTypes==="array"&&x.if((0,i._)`${O} == 'object' && Array.isArray(${w}) && ${w}.length == 1`,()=>x.assign(w,(0,i._)`${w}[0]`).assign(O,(0,i._)`typeof ${w}`).if(_(b,w,k.strictNumbers),()=>x.assign(A,w))),x.if((0,i._)`${A} !== undefined`);for(let L of S)(l.has(L)||L==="array"&&k.coerceTypes==="array")&&M(L);x.else(),m(v),x.endIf(),x.if((0,i._)`${A} !== undefined`,()=>{x.assign(w,A),f(v,A)});function M(L){switch(L){case"string":x.elseIf((0,i._)`${O} == "number" || ${O} == "boolean"`).assign(A,(0,i._)`"" + ${w}`).elseIf((0,i._)`${w} === null`).assign(A,(0,i._)`""`);return;case"number":x.elseIf((0,i._)`${O} == "boolean" || ${w} === null || (${O} == "string" && ${w} && ${w} == +${w})`).assign(A,(0,i._)`+${w}`);return;case"integer":x.elseIf((0,i._)`${O} === "boolean" || ${w} === null || (${O} === "string" && ${w} && ${w} == +${w} && !(${w} % 1))`).assign(A,(0,i._)`+${w}`);return;case"boolean":x.elseIf((0,i._)`${w} === "false" || ${w} === 0 || ${w} === null`).assign(A,!1).elseIf((0,i._)`${w} === "true" || ${w} === 1`).assign(A,!0);return;case"null":x.elseIf((0,i._)`${w} === "" || ${w} === 0 || ${w} === false`),x.assign(A,null);return;case"array":x.elseIf((0,i._)`${O} === "string" || ${O} === "number" - || ${O} === "boolean" || ${w} === null`).assign(A,(0,i._)`[${w}]`)}}}function f({gen:v,parentData:b,parentDataProperty:S},x){v.if((0,i._)`${b} !== undefined`,()=>v.assign((0,i._)`${b}[${S}]`,x))}function g(v,b,S,x=o.Correct){let w=x===o.Correct?i.operators.EQ:i.operators.NEQ,k;switch(v){case"null":return(0,i._)`${b} ${w} null`;case"array":k=(0,i._)`Array.isArray(${b})`;break;case"object":k=(0,i._)`${b} && typeof ${b} == "object" && !Array.isArray(${b})`;break;case"integer":k=O((0,i._)`!(${b} % 1) && !isNaN(${b})`);break;case"number":k=O();break;default:return(0,i._)`typeof ${b} ${w} ${v}`}return x===o.Correct?k:(0,i.not)(k);function O(A=i.nil){return(0,i.and)((0,i._)`typeof ${b} == "number"`,A,S?(0,i._)`isFinite(${b})`:i.nil)}}t.checkDataType=g;function _(v,b,S,x){if(v.length===1)return g(v[0],b,S,x);let w,k=(0,a.toHash)(v);if(k.array&&k.object){let O=(0,i._)`typeof ${b} != "object"`;w=k.null?O:(0,i._)`!${b} || ${O}`,delete k.null,delete k.array,delete k.object}else w=i.nil;k.number&&delete k.integer;for(let O in k)w=(0,i.and)(w,g(O,b,S,x));return w}t.checkDataTypes=_;var h={message:({schema:v})=>`must be ${v}`,params:({schema:v,schemaValue:b})=>typeof v=="string"?(0,i._)`{type: ${v}}`:(0,i._)`{type: ${b}}`};function m(v){let b=y(v);(0,n.reportError)(b,h)}t.reportTypeError=m;function y(v){let{gen:b,data:S,schema:x}=v,w=(0,a.schemaRefOrVal)(v,x,"type");return{gen:b,keyword:"type",data:S,schema:x.type,schemaCode:w,schemaValue:w,parentSchema:x,params:{},it:v}}}),wie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.assignDefaults=void 0;var e=Xe(),r=dt();function n(a,o){let{properties:s,items:c}=a.schema;if(o==="object"&&s)for(let u in s)i(a,u,s[u].default);else o==="array"&&Array.isArray(c)&&c.forEach((u,l)=>i(a,l,u.default))}t.assignDefaults=n;function i(a,o,s){let{gen:c,compositeRule:u,data:l,opts:d}=a;if(s===void 0)return;let p=(0,e._)`${l}${(0,e.getProperty)(o)}`;if(u){(0,r.checkStrictMode)(a,`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)(s)}`)}}),ti=V(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=Xe(),r=dt(),n=Oa(),i=dt();function a(v,b){let{gen:S,data:x,it:w}=v;S.if(d(S,x,b,w.opts.ownProperties),()=>{v.setParams({missingProperty:(0,e._)`${b}`},!0),v.error()})}t.checkReportMissingProp=a;function o({gen:v,data:b,it:{opts:S}},x,w){return(0,e.or)(...x.map(k=>(0,e.and)(d(v,b,k,S.ownProperties),(0,e._)`${w} = ${k}`)))}t.checkMissingProp=o;function s(v,b){v.setParams({missingProperty:b},!0),v.error()}t.reportMissingProp=s;function c(v){return v.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}t.hasPropFunc=c;function u(v,b,S){return(0,e._)`${c(v)}.call(${b}, ${S})`}t.isOwnProperty=u;function l(v,b,S,x){let w=(0,e._)`${b}${(0,e.getProperty)(S)} !== undefined`;return x?(0,e._)`${w} && ${u(v,b,S)}`:w}t.propertyInData=l;function d(v,b,S,x){let w=(0,e._)`${b}${(0,e.getProperty)(S)} === undefined`;return x?(0,e.or)(w,(0,e.not)(u(v,b,S))):w}t.noPropertyInData=d;function p(v){return v?Object.keys(v).filter(b=>b!=="__proto__"):[]}t.allSchemaProperties=p;function f(v,b){return p(b).filter(S=>!(0,r.alwaysValidSchema)(v,b[S]))}t.schemaProperties=f;function g({schemaCode:v,data:b,it:{gen:S,topSchemaRef:x,schemaPath:w,errorPath:k},it:O},A,M,L){let B=L?(0,e._)`${v}, ${b}, ${x}${w}`:b,U=[[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,k)],[n.default.parentData,O.parentData],[n.default.parentDataProperty,O.parentDataProperty],[n.default.rootData,n.default.rootData]];O.opts.dynamicRef&&U.push([n.default.dynamicAnchors,n.default.dynamicAnchors]);let Y=(0,e._)`${B}, ${S.object(...U)}`;return M!==e.nil?(0,e._)`${A}.call(${M}, ${Y})`:(0,e._)`${A}(${Y})`}t.callValidateCode=g;var _=(0,e._)`new RegExp`;function h({gen:v,it:{opts:b}},S){let x=b.unicodeRegExp?"u":"",{regExp:w}=b.code,k=w(S,x);return v.scopeValue("pattern",{key:k.toString(),ref:k,code:(0,e._)`${w.code==="new RegExp"?_:(0,i.useFunc)(v,w)}(${S}, ${x})`})}t.usePattern=h;function m(v){let{gen:b,data:S,keyword:x,it:w}=v,k=b.name("valid");if(w.allErrors){let A=b.let("valid",!0);return O(()=>b.assign(A,!1)),A}return b.var(k,!0),O(()=>b.break()),k;function O(A){let M=b.const("len",(0,e._)`${S}.length`);b.forRange("i",0,M,L=>{v.subschema({keyword:x,dataProp:L,dataPropType:r.Type.Num},k),b.if((0,e.not)(k),A)})}}t.validateArray=m;function y(v){let{gen:b,schema:S,keyword:x,it:w}=v;if(!Array.isArray(S))throw new Error("ajv implementation error");if(S.some(M=>(0,r.alwaysValidSchema)(w,M))&&!w.opts.unevaluated)return;let O=b.let("valid",!1),A=b.name("_valid");b.block(()=>S.forEach((M,L)=>{let B=v.subschema({keyword:x,schemaProp:L,compositeRule:!0},A);b.assign(O,(0,e._)`${O} || ${A}`),v.mergeValidEvaluated(B,A)||b.if((0,e.not)(O))})),v.result(O,()=>v.reset(),()=>v.error(!0))}t.validateUnion=y}),$ie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateKeywordUsage=t.validSchemaType=t.funcKeywordCode=t.macroKeywordCode=void 0;var e=Xe(),r=Oa(),n=ti(),i=Xh();function a(f,g){let{gen:_,keyword:h,schema:m,parentSchema:y,it:v}=f,b=g.macro.call(v.self,m,y,v),S=l(_,h,b);v.opts.validateSchema!==!1&&v.self.validateSchema(b,!0);let x=_.name("valid");f.subschema({schema:b,schemaPath:e.nil,errSchemaPath:`${v.errSchemaPath}/${h}`,topSchemaRef:S,compositeRule:!0},x),f.pass(x,()=>f.error(!0))}t.macroKeywordCode=a;function o(f,g){var _;let{gen:h,keyword:m,schema:y,parentSchema:v,$data:b,it:S}=f;u(S,g);let x=!b&&g.compile?g.compile.call(S.self,y,v,S):g.validate,w=l(h,m,x),k=h.let("valid");f.block$data(k,O),f.ok((_=g.valid)!==null&&_!==void 0?_:k);function O(){if(g.errors===!1)L(),g.modifying&&s(f),B(()=>f.error());else{let U=g.async?A():M();g.modifying&&s(f),B(()=>c(f,U))}}function A(){let U=h.let("ruleErrs",null);return h.try(()=>L((0,e._)`await `),Y=>h.assign(k,!1).if((0,e._)`${Y} instanceof ${S.ValidationError}`,()=>h.assign(U,(0,e._)`${Y}.errors`),()=>h.throw(Y))),U}function M(){let U=(0,e._)`${w}.errors`;return h.assign(U,null),L(e.nil),U}function L(U=g.async?(0,e._)`await `:e.nil){let Y=S.opts.passContext?r.default.this:r.default.self,me=!("compile"in g&&!b||g.schema===!1);h.assign(k,(0,e._)`${U}${(0,n.callValidateCode)(f,w,Y,me)}`,g.modifying)}function B(U){var Y;h.if((0,e.not)((Y=g.valid)!==null&&Y!==void 0?Y:k),U)}}t.funcKeywordCode=o;function s(f){let{gen:g,data:_,it:h}=f;g.if(h.parentData,()=>g.assign(_,(0,e._)`${h.parentData}[${h.parentDataProperty}]`))}function c(f,g){let{gen:_}=f;_.if((0,e._)`Array.isArray(${g})`,()=>{_.assign(r.default.vErrors,(0,e._)`${r.default.vErrors} === null ? ${g} : ${r.default.vErrors}.concat(${g})`).assign(r.default.errors,(0,e._)`${r.default.vErrors}.length`),(0,i.extendErrors)(f)},()=>f.error())}function u({schemaEnv:f},g){if(g.async&&!f.$async)throw new Error("async keyword in sync schema")}function l(f,g,_){if(_===void 0)throw new Error(`keyword "${g}" failed to compile`);return f.scopeValue("keyword",typeof _=="function"?{ref:_}:{ref:_,code:(0,e.stringify)(_)})}function d(f,g,_=!1){return!g.length||g.some(h=>h==="array"?Array.isArray(f):h==="object"?f&&typeof f=="object"&&!Array.isArray(f):typeof f==h||_&&typeof f>"u")}t.validSchemaType=d;function p({schema:f,opts:g,self:_,errSchemaPath:h},m,y){if(Array.isArray(m.keyword)?!m.keyword.includes(y):m.keyword!==y)throw new Error("ajv implementation error");let v=m.dependencies;if(v?.some(b=>!Object.prototype.hasOwnProperty.call(f,b)))throw new Error(`parent schema must have dependencies of ${y}: ${v.join(",")}`);if(m.validateSchema&&!m.validateSchema(f[y])){let S=`keyword "${y}" value is invalid at path "${h}": `+_.errorsText(m.validateSchema.errors);if(g.validateSchema==="log")_.logger.error(S);else throw new Error(S)}}t.validateKeywordUsage=p}),Eie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extendSubschemaMode=t.extendSubschemaData=t.getSubschema=void 0;var e=Xe(),r=dt();function n(o,{keyword:s,schemaProp:c,schema:u,schemaPath:l,errSchemaPath:d,topSchemaRef:p}){if(s!==void 0&&u!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(s!==void 0){let f=o.schema[s];return c===void 0?{schema:f,schemaPath:(0,e._)`${o.schemaPath}${(0,e.getProperty)(s)}`,errSchemaPath:`${o.errSchemaPath}/${s}`}:{schema:f[c],schemaPath:(0,e._)`${o.schemaPath}${(0,e.getProperty)(s)}${(0,e.getProperty)(c)}`,errSchemaPath:`${o.errSchemaPath}/${s}/${(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,s,{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}=s;if(c!==void 0){let{errorPath:_,dataPathArr:h,opts:m}=s,y=f.let("data",(0,e._)`${s.data}${(0,e.getProperty)(c)}`,!0);g(y),o.errorPath=(0,e.str)`${_}${(0,r.getErrorPath)(c,u,m.jsPropertySyntax)}`,o.parentDataProperty=(0,e._)`${c}`,o.dataPathArr=[...h,o.parentDataProperty]}if(l!==void 0){let _=l instanceof e.Name?l:f.let("data",l,!0);g(_),p!==void 0&&(o.propertyName=p)}d&&(o.dataTypes=d);function g(_){o.data=_,o.dataLevel=s.dataLevel+1,o.dataTypes=[],s.definedProperties=new Set,o.parentData=s.data,o.dataNames=[...s.dataNames,_]}}t.extendSubschemaData=i;function a(o,{jtdDiscriminator:s,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=s,o.jtdMetadata=c}t.extendSubschemaMode=a}),Yh=V((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 a,o,s;if(Array.isArray(n)){if(a=n.length,a!=i.length)return!1;for(o=a;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(s=Object.keys(n),a=s.length,a!==Object.keys(i).length)return!1;for(o=a;o--!==0;)if(!Object.prototype.hasOwnProperty.call(i,s[o]))return!1;for(o=a;o--!==0;){var c=s[o];if(!r(n[c],i[c]))return!1}return!0}return n!==n&&i!==i}}),kie=V((t,e)=>{var r=e.exports=function(a,o,s){typeof o=="function"&&(s=o,o={}),s=o.cb||s;var c=typeof s=="function"?s:s.pre||function(){},u=s.post||function(){};n(o,c,u,a,"",a)};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(a,o,s,c,u,l,d,p,f,g){if(c&&typeof c=="object"&&!Array.isArray(c)){o(c,u,l,d,p,f,g);for(var _ in c){var h=c[_];if(Array.isArray(h)){if(_ in r.arrayKeywords)for(var m=0;m{Object.defineProperty(t,"__esModule",{value:!0}),t.getSchemaRefs=t.resolveUrl=t.normalizeId=t._getFullPath=t.getFullPath=t.inlineRef=void 0;var e=dt(),r=Yh(),n=kie(),i=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function a(h,m=!0){return typeof h=="boolean"?!0:m===!0?!s(h):m?c(h)<=m:!1}t.inlineRef=a;var o=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function s(h){for(let m in h){if(o.has(m))return!0;let y=h[m];if(Array.isArray(y)&&y.some(s)||typeof y=="object"&&s(y))return!0}return!1}function c(h){let m=0;for(let y in h){if(y==="$ref")return 1/0;if(m++,!i.has(y)&&(typeof h[y]=="object"&&(0,e.eachItem)(h[y],v=>m+=c(v)),m===1/0))return 1/0}return m}function u(h,m="",y){y!==!1&&(m=p(m));let v=h.parse(m);return l(h,v)}t.getFullPath=u;function l(h,m){return h.serialize(m).split("#")[0]+"#"}t._getFullPath=l;var d=/#\/?$/;function p(h){return h?h.replace(d,""):""}t.normalizeId=p;function f(h,m,y){return y=p(y),h.resolve(m,y)}t.resolveUrl=f;var g=/^[a-z_][-a-z0-9._]*$/i;function _(h,m){if(typeof h=="boolean")return{};let{schemaId:y,uriResolver:v}=this.opts,b=p(h[y]||m),S={"":b},x=u(v,b,!1),w={},k=new Set;return n(h,{allKeys:!0},(M,L,B,U)=>{if(U===void 0)return;let Y=x+L,me=S[U];typeof M[y]=="string"&&(me=et.call(this,M[y])),ht.call(this,M.$anchor),ht.call(this,M.$dynamicAnchor),S[L]=me;function et(fe){let F=this.opts.uriResolver.resolve;if(fe=p(me?F(me,fe):fe),k.has(fe))throw A(fe);k.add(fe);let I=this.refs[fe];return typeof I=="string"&&(I=this.refs[I]),typeof I=="object"?O(M,I.schema,fe):fe!==p(Y)&&(fe[0]==="#"?(O(M,w[fe],fe),w[fe]=M):this.refs[fe]=Y),fe}function ht(fe){if(typeof fe=="string"){if(!g.test(fe))throw new Error(`invalid anchor "${fe}"`);et.call(this,`#${fe}`)}}}),w;function O(M,L,B){if(L!==void 0&&!r(M,L))throw A(B)}function A(M){return new Error(`reference "${M}" resolves to more than one schema`)}}t.getSchemaRefs=_}),eg=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getData=t.KeywordCxt=t.validateFunctionCode=void 0;var e=Sie(),r=Fh(),n=L2(),i=Fh(),a=wie(),o=$ie(),s=Eie(),c=Xe(),u=Oa(),l=Qh(),d=dt(),p=Xh();function f(P){if(x(P)&&(k(P),S(P))){m(P);return}g(P,()=>(0,e.topBoolOrEmptySchema)(P))}t.validateFunctionCode=f;function g({gen:P,validateName:R,schema:z,schemaEnv:Z,opts:J},ie){J.code.es5?P.func(R,(0,c._)`${u.default.data}, ${u.default.valCxt}`,Z.$async,()=>{P.code((0,c._)`"use strict"; ${v(z,J)}`),h(P,J),P.code(ie)}):P.func(R,(0,c._)`${u.default.data}, ${_(J)}`,Z.$async,()=>P.code(v(z,J)).code(ie))}function _(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 h(P,R){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}`),R.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),R.dynamicRef&&P.var(u.default.dynamicAnchors,(0,c._)`{}`)})}function m(P){let{schema:R,opts:z,gen:Z}=P;g(P,()=>{z.$comment&&R.$comment&&U(P),M(P),Z.let(u.default.vErrors,null),Z.let(u.default.errors,0),z.unevaluated&&y(P),O(P),Y(P)})}function y(P){let{gen:R,validateName:z}=P;P.evaluated=R.const("evaluated",(0,c._)`${z}.evaluated`),R.if((0,c._)`${P.evaluated}.dynamicProps`,()=>R.assign((0,c._)`${P.evaluated}.props`,(0,c._)`undefined`)),R.if((0,c._)`${P.evaluated}.dynamicItems`,()=>R.assign((0,c._)`${P.evaluated}.items`,(0,c._)`undefined`))}function v(P,R){let z=typeof P=="object"&&P[R.schemaId];return z&&(R.code.source||R.code.process)?(0,c._)`/*# sourceURL=${z} */`:c.nil}function b(P,R){if(x(P)&&(k(P),S(P))){w(P,R);return}(0,e.boolOrEmptySchema)(P,R)}function S({schema:P,self:R}){if(typeof P=="boolean")return!P;for(let z in P)if(R.RULES.all[z])return!0;return!1}function x(P){return typeof P.schema!="boolean"}function w(P,R){let{schema:z,gen:Z,opts:J}=P;J.$comment&&z.$comment&&U(P),L(P),B(P);let ie=Z.const("_errs",u.default.errors);O(P,ie),Z.var(R,(0,c._)`${ie} === ${u.default.errors}`)}function k(P){(0,d.checkUnknownRules)(P),A(P)}function O(P,R){if(P.opts.jtd)return et(P,[],!1,R);let z=(0,r.getSchemaTypes)(P.schema),Z=(0,r.coerceAndCheckDataType)(P,z);et(P,z,!Z,R)}function A(P){let{schema:R,errSchemaPath:z,opts:Z,self:J}=P;R.$ref&&Z.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(R,J.RULES)&&J.logger.warn(`$ref: keywords ignored in schema at path "${z}"`)}function M(P){let{schema:R,opts:z}=P;R.default!==void 0&&z.useDefaults&&z.strictSchema&&(0,d.checkStrictMode)(P,"default is ignored in the schema root")}function L(P){let R=P.schema[P.opts.schemaId];R&&(P.baseId=(0,l.resolveUrl)(P.opts.uriResolver,P.baseId,R))}function B(P){if(P.schema.$async&&!P.schemaEnv.$async)throw new Error("async schema in sync schema")}function U({gen:P,schemaEnv:R,schema:z,errSchemaPath:Z,opts:J}){let ie=z.$comment;if(J.$comment===!0)P.code((0,c._)`${u.default.self}.logger.log(${ie})`);else if(typeof J.$comment=="function"){let tt=(0,c.str)`${Z}/$comment`,Ht=P.scopeValue("root",{ref:R.root});P.code((0,c._)`${u.default.self}.opts.$comment(${ie}, ${tt}, ${Ht}.schema)`)}}function Y(P){let{gen:R,schemaEnv:z,validateName:Z,ValidationError:J,opts:ie}=P;z.$async?R.if((0,c._)`${u.default.errors} === 0`,()=>R.return(u.default.data),()=>R.throw((0,c._)`new ${J}(${u.default.vErrors})`)):(R.assign((0,c._)`${Z}.errors`,u.default.vErrors),ie.unevaluated&&me(P),R.return((0,c._)`${u.default.errors} === 0`))}function me({gen:P,evaluated:R,props:z,items:Z}){z instanceof c.Name&&P.assign((0,c._)`${R}.props`,z),Z instanceof c.Name&&P.assign((0,c._)`${R}.items`,Z)}function et(P,R,z,Z){let{gen:J,schema:ie,data:tt,allErrors:Ht,opts:yt,self:_t}=P,{RULES:rt}=_t;if(ie.$ref&&(yt.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(ie,rt))){J.block(()=>K(P,"$ref",rt.all.$ref.definition));return}yt.jtd||fe(P,R),J.block(()=>{for(let jt of rt.rules)tn(jt);tn(rt.post)});function tn(jt){(0,n.shouldUseGroup)(ie,jt)&&(jt.type?(J.if((0,i.checkDataType)(jt.type,tt,yt.strictNumbers)),ht(P,jt),R.length===1&&R[0]===jt.type&&z&&(J.else(),(0,i.reportTypeError)(P)),J.endIf()):ht(P,jt),Ht||J.if((0,c._)`${u.default.errors} === ${Z||0}`))}}function ht(P,R){let{gen:z,schema:Z,opts:{useDefaults:J}}=P;J&&(0,a.assignDefaults)(P,R.type),z.block(()=>{for(let ie of R.rules)(0,n.shouldUseRule)(Z,ie)&&K(P,ie.keyword,ie.definition,R.type)})}function fe(P,R){P.schemaEnv.meta||!P.opts.strictTypes||(F(P,R),P.opts.allowUnionTypes||I(P,R),D(P,P.dataTypes))}function F(P,R){if(R.length){if(!P.dataTypes.length){P.dataTypes=R;return}R.forEach(z=>{$(P.dataTypes,z)||N(P,`type "${z}" not allowed by context "${P.dataTypes.join(",")}"`)}),T(P,R)}}function I(P,R){R.length>1&&!(R.length===2&&R.includes("null"))&&N(P,"use allowUnionTypes to allow union type keyword")}function D(P,R){let z=P.self.RULES.all;for(let Z in z){let J=z[Z];if(typeof J=="object"&&(0,n.shouldUseRule)(P.schema,J)){let{type:ie}=J.definition;ie.length&&!ie.some(tt=>C(R,tt))&&N(P,`missing type "${ie.join(",")}" for keyword "${Z}"`)}}}function C(P,R){return P.includes(R)||R==="number"&&P.includes("integer")}function $(P,R){return P.includes(R)||R==="integer"&&P.includes("number")}function T(P,R){let z=[];for(let Z of P.dataTypes)$(R,Z)?z.push(Z):R.includes("integer")&&Z==="number"&&z.push("integer");P.dataTypes=z}function N(P,R){let z=P.schemaEnv.baseId+P.errSchemaPath;R+=` at "${z}" (strictTypes)`,(0,d.checkStrictMode)(P,R,P.opts.strictTypes)}class W{constructor(R,z,Z){if((0,o.validateKeywordUsage)(R,z,Z),this.gen=R.gen,this.allErrors=R.allErrors,this.keyword=Z,this.data=R.data,this.schema=R.schema[Z],this.$data=z.$data&&R.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(R,this.schema,Z,this.$data),this.schemaType=z.schemaType,this.parentSchema=R.schema,this.params={},this.it=R,this.def=z,this.$data)this.schemaCode=R.gen.const("vSchema",je(this.$data,R));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,z.schemaType,z.allowUndefined))throw new Error(`${Z} value must be ${JSON.stringify(z.schemaType)}`);("code"in z?z.trackErrors:z.errors!==!1)&&(this.errsCount=R.gen.const("_errs",u.default.errors))}result(R,z,Z){this.failResult((0,c.not)(R),z,Z)}failResult(R,z,Z){this.gen.if(R),Z?Z():this.error(),z?(this.gen.else(),z(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(R,z){this.failResult((0,c.not)(R),void 0,z)}fail(R){if(R===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(R),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(R){if(!this.$data)return this.fail(R);let{schemaCode:z}=this;this.fail((0,c._)`${z} !== undefined && (${(0,c.or)(this.invalid$data(),R)})`)}error(R,z,Z){if(z){this.setParams(z),this._error(R,Z),this.setParams({});return}this._error(R,Z)}_error(R,z){(R?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(R){this.allErrors||this.gen.if(R)}setParams(R,z){z?Object.assign(this.params,R):this.params=R}block$data(R,z,Z=c.nil){this.gen.block(()=>{this.check$data(R,Z),z()})}check$data(R=c.nil,z=c.nil){if(!this.$data)return;let{gen:Z,schemaCode:J,schemaType:ie,def:tt}=this;Z.if((0,c.or)((0,c._)`${J} === undefined`,z)),R!==c.nil&&Z.assign(R,!0),(ie.length||tt.validateSchema)&&(Z.elseIf(this.invalid$data()),this.$dataError(),R!==c.nil&&Z.assign(R,!1)),Z.else()}invalid$data(){let{gen:R,schemaCode:z,schemaType:Z,def:J,it:ie}=this;return(0,c.or)(tt(),Ht());function tt(){if(Z.length){if(!(z instanceof c.Name))throw new Error("ajv implementation error");let yt=Array.isArray(Z)?Z:[Z];return(0,c._)`${(0,i.checkDataTypes)(yt,z,ie.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function Ht(){if(J.validateSchema){let yt=R.scopeValue("validate$data",{ref:J.validateSchema});return(0,c._)`!${yt}(${z})`}return c.nil}}subschema(R,z){let Z=(0,s.getSubschema)(this.it,R);(0,s.extendSubschemaData)(Z,this.it,R),(0,s.extendSubschemaMode)(Z,R);let J={...this.it,...Z,items:void 0,props:void 0};return b(J,z),J}mergeEvaluated(R,z){let{it:Z,gen:J}=this;Z.opts.unevaluated&&(Z.props!==!0&&R.props!==void 0&&(Z.props=d.mergeEvaluated.props(J,R.props,Z.props,z)),Z.items!==!0&&R.items!==void 0&&(Z.items=d.mergeEvaluated.items(J,R.items,Z.items,z)))}mergeValidEvaluated(R,z){let{it:Z,gen:J}=this;if(Z.opts.unevaluated&&(Z.props!==!0||Z.items!==!0))return J.if(z,()=>this.mergeEvaluated(R,c.Name)),!0}}t.KeywordCxt=W;function K(P,R,z,Z){let J=new W(P,z,R);"code"in z?z.code(J,Z):J.$data&&z.validate?(0,o.funcKeywordCode)(J,z):"macro"in z?(0,o.macroKeywordCode)(J,z):(z.compile||z.validate)&&(0,o.funcKeywordCode)(J,z)}var pe=/^\/(?:[^~]|~0|~1)*$/,ce=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function je(P,{dataLevel:R,dataNames:z,dataPathArr:Z}){let J,ie;if(P==="")return u.default.rootData;if(P[0]==="/"){if(!pe.test(P))throw new Error(`Invalid JSON-pointer: ${P}`);J=P,ie=u.default.rootData}else{let _t=ce.exec(P);if(!_t)throw new Error(`Invalid JSON-pointer: ${P}`);let rt=+_t[1];if(J=_t[2],J==="#"){if(rt>=R)throw new Error(yt("property/index",rt));return Z[R-rt]}if(rt>R)throw new Error(yt("data",rt));if(ie=z[R-rt],!J)return ie}let tt=ie,Ht=J.split("/");for(let _t of Ht)_t&&(ie=(0,c._)`${ie}${(0,c.getProperty)((0,d.unescapeJsonPointer)(_t))}`,tt=(0,c._)`${tt} && ${ie}`);return tt;function yt(_t,rt){return`Cannot access ${_t} ${rt} levels up, current level is ${R}`}}t.getData=je}),F$=V(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}),tg=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Qh();class r extends Error{constructor(i,a,o,s){super(s||`can't resolve reference ${o} from id ${a}`),this.missingRef=(0,e.resolveUrl)(i,a,o),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(i,this.missingRef))}}t.default=r}),Z$=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resolveSchema=t.getCompilingSchema=t.resolveRef=t.compileSchema=t.SchemaEnv=void 0;var e=Xe(),r=F$(),n=Oa(),i=Qh(),a=dt(),o=eg();class s{constructor(y){var v;this.refs={},this.dynamicAnchors={};let b;typeof y.schema=="object"&&(b=y.schema),this.schema=y.schema,this.schemaId=y.schemaId,this.root=y.root||this,this.baseId=(v=y.baseId)!==null&&v!==void 0?v:(0,i.normalizeId)(b?.[y.schemaId||"$id"]),this.schemaPath=y.schemaPath,this.localRefs=y.localRefs,this.meta=y.meta,this.$async=b?.$async,this.refs={}}}t.SchemaEnv=s;function c(m){let y=d.call(this,m);if(y)return y;let v=(0,i.getFullPath)(this.opts.uriResolver,m.root.baseId),{es5:b,lines:S}=this.opts.code,{ownProperties:x}=this.opts,w=new e.CodeGen(this.scope,{es5:b,lines:S,ownProperties:x}),k;m.$async&&(k=w.scopeValue("Error",{ref:r.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));let O=w.scopeName("validate");m.validateName=O;let A={gen:w,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:w.scopeValue("schema",this.opts.code.source===!0?{ref:m.schema,code:(0,e.stringify)(m.schema)}:{ref:m.schema}),validateName:O,ValidationError:k,schema:m.schema,schemaEnv:m,rootId:v,baseId:m.baseId||v,schemaPath:e.nil,errSchemaPath:m.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this},M;try{this._compilations.add(m),(0,o.validateFunctionCode)(A),w.optimize(this.opts.code.optimize);let L=w.toString();M=`${w.scopeRefs(n.default.scope)}return ${L}`,this.opts.code.process&&(M=this.opts.code.process(M,m));let U=new Function(`${n.default.self}`,`${n.default.scope}`,M)(this,this.scope.get());if(this.scope.value(O,{ref:U}),U.errors=null,U.schema=m.schema,U.schemaEnv=m,m.$async&&(U.$async=!0),this.opts.code.source===!0&&(U.source={validateName:O,validateCode:L,scopeValues:w._values}),this.opts.unevaluated){let{props:Y,items:me}=A;U.evaluated={props:Y instanceof e.Name?void 0:Y,items:me instanceof e.Name?void 0:me,dynamicProps:Y instanceof e.Name,dynamicItems:me instanceof e.Name},U.source&&(U.source.evaluated=(0,e.stringify)(U.evaluated))}return m.validate=U,m}catch(L){throw delete m.validate,delete m.validateName,M&&this.logger.error("Error compiling schema, function code:",M),L}finally{this._compilations.delete(m)}}t.compileSchema=c;function u(m,y,v){var b;v=(0,i.resolveUrl)(this.opts.uriResolver,y,v);let S=m.refs[v];if(S)return S;let x=f.call(this,m,v);if(x===void 0){let w=(b=m.localRefs)===null||b===void 0?void 0:b[v],{schemaId:k}=this.opts;w&&(x=new s({schema:w,schemaId:k,root:m,baseId:y}))}if(x!==void 0)return m.refs[v]=l.call(this,x)}t.resolveRef=u;function l(m){return(0,i.inlineRef)(m.schema,this.opts.inlineRefs)?m.schema:m.validate?m:c.call(this,m)}function d(m){for(let y of this._compilations)if(p(y,m))return y}t.getCompilingSchema=d;function p(m,y){return m.schema===y.schema&&m.root===y.root&&m.baseId===y.baseId}function f(m,y){let v;for(;typeof(v=this.refs[y])=="string";)y=v;return v||this.schemas[y]||g.call(this,m,y)}function g(m,y){let v=this.opts.uriResolver.parse(y),b=(0,i._getFullPath)(this.opts.uriResolver,v),S=(0,i.getFullPath)(this.opts.uriResolver,m.baseId,void 0);if(Object.keys(m.schema).length>0&&b===S)return h.call(this,v,m);let x=(0,i.normalizeId)(b),w=this.refs[x]||this.schemas[x];if(typeof w=="string"){let k=g.call(this,m,w);return typeof k?.schema!="object"?void 0:h.call(this,v,k)}if(typeof w?.schema=="object"){if(w.validate||c.call(this,w),x===(0,i.normalizeId)(y)){let{schema:k}=w,{schemaId:O}=this.opts,A=k[O];return A&&(S=(0,i.resolveUrl)(this.opts.uriResolver,S,A)),new s({schema:k,schemaId:O,root:m,baseId:S})}return h.call(this,v,w)}}t.resolveSchema=g;var _=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function h(m,{baseId:y,schema:v,root:b}){var S;if(((S=m.fragment)===null||S===void 0?void 0:S[0])!=="/")return;for(let k of m.fragment.slice(1).split("/")){if(typeof v=="boolean")return;let O=v[(0,a.unescapeFragment)(k)];if(O===void 0)return;v=O;let A=typeof v=="object"&&v[this.opts.schemaId];!_.has(k)&&A&&(y=(0,i.resolveUrl)(this.opts.uriResolver,y,A))}let x;if(typeof v!="boolean"&&v.$ref&&!(0,a.schemaHasRulesButRef)(v,this.RULES)){let k=(0,i.resolveUrl)(this.opts.uriResolver,y,v.$ref);x=g.call(this,b,k)}let{schemaId:w}=this.opts;if(x=x||new s({schema:v,schemaId:w,root:b,baseId:y}),x.schema!==x.root.schema)return x}}),Tie=V((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}}),Iie=V((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}}),Pie=V((t,e)=>{var{HEX:r}=Iie(),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(m){if(u(m,".")<3)return{host:m,isIPV4:!1};let y=m.match(n)||[],[v]=y;return v?{host:c(v,"."),isIPV4:!0}:{host:m,isIPV4:!1}}function a(m,y=!1){let v="",b=!0;for(let S of m){if(r[S]===void 0)return;S!=="0"&&b===!0&&(b=!1),b||(v+=S)}return y&&v.length===0&&(v="0"),v}function o(m){let y=0,v={error:!1,address:"",zone:""},b=[],S=[],x=!1,w=!1,k=!1;function O(){if(S.length){if(x===!1){let A=a(S);if(A!==void 0)b.push(A);else return v.error=!0,!1}S.length=0}return!0}for(let A=0;A7){v.error=!0;break}A-1>=0&&m[A-1]===":"&&(w=!0);continue}else if(M==="%"){if(!O())break;x=!0}else{S.push(M);continue}}return S.length&&(x?v.zone=S.join(""):k?b.push(S.join("")):b.push(a(S))),v.address=b.join(""),v}function s(m){if(u(m,":")<2)return{host:m,isIPV6:!1};let y=o(m);if(y.error)return{host:m,isIPV6:!1};{let v=y.address,b=y.address;return y.zone&&(v+="%"+y.zone,b+="%25"+y.zone),{host:v,escapedHost:b,isIPV6:!0}}}function c(m,y){let v="",b=!0,S=m.length;for(let x=0;x{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(b){return typeof b.secure=="boolean"?b.secure:String(b.scheme).toLowerCase()==="wss"}function a(b){return b.host||(b.error=b.error||"HTTP URIs must have a host."),b}function o(b){let S=String(b.scheme).toLowerCase()==="https";return(b.port===(S?443:80)||b.port==="")&&(b.port=void 0),b.path||(b.path="/"),b}function s(b){return b.secure=i(b),b.resourceName=(b.path||"/")+(b.query?"?"+b.query:""),b.path=void 0,b.query=void 0,b}function c(b){if((b.port===(i(b)?443:80)||b.port==="")&&(b.port=void 0),typeof b.secure=="boolean"&&(b.scheme=b.secure?"wss":"ws",b.secure=void 0),b.resourceName){let[S,x]=b.resourceName.split("?");b.path=S&&S!=="/"?S:void 0,b.query=x,b.resourceName=void 0}return b.fragment=void 0,b}function u(b,S){if(!b.path)return b.error="URN can not be parsed",b;let x=b.path.match(n);if(x){let w=S.scheme||b.scheme||"urn";b.nid=x[1].toLowerCase(),b.nss=x[2];let k=`${w}:${S.nid||b.nid}`,O=v[k];b.path=void 0,O&&(b=O.parse(b,S))}else b.error=b.error||"URN can not be parsed.";return b}function l(b,S){let x=S.scheme||b.scheme||"urn",w=b.nid.toLowerCase(),k=`${x}:${S.nid||w}`,O=v[k];O&&(b=O.serialize(b,S));let A=b,M=b.nss;return A.path=`${w||S.nid}:${M}`,S.skipEscape=!0,A}function d(b,S){let x=b;return x.uuid=x.nss,x.nss=void 0,!S.tolerant&&(!x.uuid||!r.test(x.uuid))&&(x.error=x.error||"UUID is not valid."),x}function p(b){let S=b;return S.nss=(b.uuid||"").toLowerCase(),S}var f={scheme:"http",domainHost:!0,parse:a,serialize:o},g={scheme:"https",domainHost:f.domainHost,parse:a,serialize:o},_={scheme:"ws",domainHost:!0,parse:s,serialize:c},h={scheme:"wss",domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},m={scheme:"urn",parse:u,serialize:l,skipNormalize:!0},y={scheme:"urn:uuid",parse:d,serialize:p,skipNormalize:!0},v={http:f,https:g,ws:_,wss:h,urn:m,"urn:uuid":y};e.exports=v}),q2=V((t,e)=>{var{normalizeIPv6:r,normalizeIPv4:n,removeDotSegments:i,recomposeAuthority:a,normalizeComponentEncoding:o}=Pie(),s=Oie();function c(y,v){return typeof y=="string"?y=p(h(y,v),v):typeof y=="object"&&(y=h(p(y,v),v)),y}function u(y,v,b){let S=Object.assign({scheme:"null"},b),x=l(h(y,S),h(v,S),S,!0);return p(x,{...S,skipEscape:!0})}function l(y,v,b,S){let x={};return S||(y=h(p(y,b),b),v=h(p(v,b),b)),b=b||{},!b.tolerant&&v.scheme?(x.scheme=v.scheme,x.userinfo=v.userinfo,x.host=v.host,x.port=v.port,x.path=i(v.path||""),x.query=v.query):(v.userinfo!==void 0||v.host!==void 0||v.port!==void 0?(x.userinfo=v.userinfo,x.host=v.host,x.port=v.port,x.path=i(v.path||""),x.query=v.query):(v.path?(v.path.charAt(0)==="/"?x.path=i(v.path):((y.userinfo!==void 0||y.host!==void 0||y.port!==void 0)&&!y.path?x.path="/"+v.path:y.path?x.path=y.path.slice(0,y.path.lastIndexOf("/")+1)+v.path:x.path=v.path,x.path=i(x.path)),x.query=v.query):(x.path=y.path,v.query!==void 0?x.query=v.query:x.query=y.query),x.userinfo=y.userinfo,x.host=y.host,x.port=y.port),x.scheme=y.scheme),x.fragment=v.fragment,x}function d(y,v,b){return typeof y=="string"?(y=unescape(y),y=p(o(h(y,b),!0),{...b,skipEscape:!0})):typeof y=="object"&&(y=p(o(y,!0),{...b,skipEscape:!0})),typeof v=="string"?(v=unescape(v),v=p(o(h(v,b),!0),{...b,skipEscape:!0})):typeof v=="object"&&(v=p(o(v,!0),{...b,skipEscape:!0})),y.toLowerCase()===v.toLowerCase()}function p(y,v){let b={host:y.host,scheme:y.scheme,userinfo:y.userinfo,port:y.port,path:y.path,query:y.query,nid:y.nid,nss:y.nss,uuid:y.uuid,fragment:y.fragment,reference:y.reference,resourceName:y.resourceName,secure:y.secure,error:""},S=Object.assign({},v),x=[],w=s[(S.scheme||b.scheme||"").toLowerCase()];w&&w.serialize&&w.serialize(b,S),b.path!==void 0&&(S.skipEscape?b.path=unescape(b.path):(b.path=escape(b.path),b.scheme!==void 0&&(b.path=b.path.split("%3A").join(":")))),S.reference!=="suffix"&&b.scheme&&x.push(b.scheme,":");let k=a(b);if(k!==void 0&&(S.reference!=="suffix"&&x.push("//"),x.push(k),b.path&&b.path.charAt(0)!=="/"&&x.push("/")),b.path!==void 0){let O=b.path;!S.absolutePath&&(!w||!w.absolutePath)&&(O=i(O)),k===void 0&&(O=O.replace(/^\/\//u,"/%2F")),x.push(O)}return b.query!==void 0&&x.push("?",b.query),b.fragment!==void 0&&x.push("#",b.fragment),x.join("")}var f=Array.from({length:127},(y,v)=>/[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(v)));function g(y){let v=0;for(let b=0,S=y.length;b126||f[v])return!0;return!1}var _=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function h(y,v){let b=Object.assign({},v),S={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},x=y.indexOf("%")!==-1,w=!1;b.reference==="suffix"&&(y=(b.scheme?b.scheme+":":"")+"//"+y);let k=y.match(_);if(k){if(S.scheme=k[1],S.userinfo=k[3],S.host=k[4],S.port=parseInt(k[5],10),S.path=k[6]||"",S.query=k[7],S.fragment=k[8],isNaN(S.port)&&(S.port=k[5]),S.host){let A=n(S.host);if(A.isIPV4===!1){let M=r(A.host);S.host=M.host.toLowerCase(),w=M.isIPV6}else S.host=A.host,w=!0}S.scheme===void 0&&S.userinfo===void 0&&S.host===void 0&&S.port===void 0&&S.query===void 0&&!S.path?S.reference="same-document":S.scheme===void 0?S.reference="relative":S.fragment===void 0?S.reference="absolute":S.reference="uri",b.reference&&b.reference!=="suffix"&&b.reference!==S.reference&&(S.error=S.error||"URI is not a "+b.reference+" reference.");let O=s[(b.scheme||S.scheme||"").toLowerCase()];if(!b.unicodeSupport&&(!O||!O.unicodeSupport)&&S.host&&(b.domainHost||O&&O.domainHost)&&w===!1&&g(S.host))try{S.host=URL.domainToASCII(S.host.toLowerCase())}catch(A){S.error=S.error||"Host's domain name can not be converted to ASCII: "+A}(!O||O&&!O.skipNormalize)&&(x&&S.scheme!==void 0&&(S.scheme=unescape(S.scheme)),x&&S.host!==void 0&&(S.host=unescape(S.host)),S.path&&(S.path=escape(unescape(S.path))),S.fragment&&(S.fragment=encodeURI(decodeURIComponent(S.fragment)))),O&&O.parse&&O.parse(S,b)}else S.error=S.error||"URI can not be parsed.";return S}var m={SCHEMES:s,normalize:c,resolve:u,resolveComponents:l,equal:d,serialize:p,parse:h};e.exports=m,e.exports.default=m,e.exports.fastUri=m}),Rie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=q2();e.code='require("ajv/dist/runtime/uri").default',t.default=e}),Cie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var e=eg();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var r=Xe();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=F$(),i=tg(),a=U2(),o=Z$(),s=Xe(),c=Qh(),u=Fh(),l=dt(),d=Tie(),p=Rie(),f=(F,I)=>new RegExp(F,I);f.code="new RegExp";var g=["removeAdditional","useDefaults","coerceTypes"],_=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),h={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."},m={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},y=200;function v(F){var I,D,C,$,T,N,W,K,pe,ce,je,P,R,z,Z,J,ie,tt,Ht,yt,_t,rt,tn,jt,Na;let An=F.strict,ja=(I=F.code)===null||I===void 0?void 0:I.optimize,Ac=ja===!0||ja===void 0?1:ja||0,Mc=(C=(D=F.code)===null||D===void 0?void 0:D.regExp)!==null&&C!==void 0?C:f,Gg=($=F.uriResolver)!==null&&$!==void 0?$:p.default;return{strictSchema:(N=(T=F.strictSchema)!==null&&T!==void 0?T:An)!==null&&N!==void 0?N:!0,strictNumbers:(K=(W=F.strictNumbers)!==null&&W!==void 0?W:An)!==null&&K!==void 0?K:!0,strictTypes:(ce=(pe=F.strictTypes)!==null&&pe!==void 0?pe:An)!==null&&ce!==void 0?ce:"log",strictTuples:(P=(je=F.strictTuples)!==null&&je!==void 0?je:An)!==null&&P!==void 0?P:"log",strictRequired:(z=(R=F.strictRequired)!==null&&R!==void 0?R:An)!==null&&z!==void 0?z:!1,code:F.code?{...F.code,optimize:Ac,regExp:Mc}:{optimize:Ac,regExp:Mc},loopRequired:(Z=F.loopRequired)!==null&&Z!==void 0?Z:y,loopEnum:(J=F.loopEnum)!==null&&J!==void 0?J:y,meta:(ie=F.meta)!==null&&ie!==void 0?ie:!0,messages:(tt=F.messages)!==null&&tt!==void 0?tt:!0,inlineRefs:(Ht=F.inlineRefs)!==null&&Ht!==void 0?Ht:!0,schemaId:(yt=F.schemaId)!==null&&yt!==void 0?yt:"$id",addUsedSchema:(_t=F.addUsedSchema)!==null&&_t!==void 0?_t:!0,validateSchema:(rt=F.validateSchema)!==null&&rt!==void 0?rt:!0,validateFormats:(tn=F.validateFormats)!==null&&tn!==void 0?tn:!0,unicodeRegExp:(jt=F.unicodeRegExp)!==null&&jt!==void 0?jt:!0,int32range:(Na=F.int32range)!==null&&Na!==void 0?Na:!0,uriResolver:Gg}}class b{constructor(I={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,I=this.opts={...I,...v(I)};let{es5:D,lines:C}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:_,es5:D,lines:C}),this.logger=L(I.logger);let $=I.validateFormats;I.validateFormats=!1,this.RULES=(0,a.getRules)(),S.call(this,h,I,"NOT SUPPORTED"),S.call(this,m,I,"DEPRECATED","warn"),this._metaOpts=A.call(this),I.formats&&k.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),I.keywords&&O.call(this,I.keywords),typeof I.meta=="object"&&this.addMetaSchema(I.meta),w.call(this),I.validateFormats=$}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:I,meta:D,schemaId:C}=this.opts,$=d;C==="id"&&($={...d},$.id=$.$id,delete $.$id),D&&I&&this.addMetaSchema($,$[C],!1)}defaultMeta(){let{meta:I,schemaId:D}=this.opts;return this.opts.defaultMeta=typeof I=="object"?I[D]||I:void 0}validate(I,D){let C;if(typeof I=="string"){if(C=this.getSchema(I),!C)throw new Error(`no schema with key or ref "${I}"`)}else C=this.compile(I);let $=C(D);return"$async"in C||(this.errors=C.errors),$}compile(I,D){let C=this._addSchema(I,D);return C.validate||this._compileSchemaEnv(C)}compileAsync(I,D){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:C}=this.opts;return $.call(this,I,D);async function $(ce,je){await T.call(this,ce.$schema);let P=this._addSchema(ce,je);return P.validate||N.call(this,P)}async function T(ce){ce&&!this.getSchema(ce)&&await $.call(this,{$ref:ce},!0)}async function N(ce){try{return this._compileSchemaEnv(ce)}catch(je){if(!(je instanceof i.default))throw je;return W.call(this,je),await K.call(this,je.missingSchema),N.call(this,ce)}}function W({missingSchema:ce,missingRef:je}){if(this.refs[ce])throw new Error(`AnySchema ${ce} is loaded but ${je} cannot be resolved`)}async function K(ce){let je=await pe.call(this,ce);this.refs[ce]||await T.call(this,je.$schema),this.refs[ce]||this.addSchema(je,ce,D)}async function pe(ce){let je=this._loading[ce];if(je)return je;try{return await(this._loading[ce]=C(ce))}finally{delete this._loading[ce]}}}addSchema(I,D,C,$=this.opts.validateSchema){if(Array.isArray(I)){for(let N of I)this.addSchema(N,void 0,C,$);return this}let T;if(typeof I=="object"){let{schemaId:N}=this.opts;if(T=I[N],T!==void 0&&typeof T!="string")throw new Error(`schema ${N} must be string`)}return D=(0,c.normalizeId)(D||T),this._checkUnique(D),this.schemas[D]=this._addSchema(I,C,D,$,!0),this}addMetaSchema(I,D,C=this.opts.validateSchema){return this.addSchema(I,D,!0,C),this}validateSchema(I,D){if(typeof I=="boolean")return!0;let C;if(C=I.$schema,C!==void 0&&typeof C!="string")throw new Error("$schema must be a string");if(C=C||this.opts.defaultMeta||this.defaultMeta(),!C)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let $=this.validate(C,I);if(!$&&D){let T="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(T);else throw new Error(T)}return $}getSchema(I){let D;for(;typeof(D=x.call(this,I))=="string";)I=D;if(D===void 0){let{schemaId:C}=this.opts,$=new o.SchemaEnv({schema:{},schemaId:C});if(D=o.resolveSchema.call(this,$,I),!D)return;this.refs[I]=D}return D.validate||this._compileSchemaEnv(D)}removeSchema(I){if(I instanceof RegExp)return this._removeAllSchemas(this.schemas,I),this._removeAllSchemas(this.refs,I),this;switch(typeof I){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let D=x.call(this,I);return typeof D=="object"&&this._cache.delete(D.schema),delete this.schemas[I],delete this.refs[I],this}case"object":{let D=I;this._cache.delete(D);let C=I[this.opts.schemaId];return C&&(C=(0,c.normalizeId)(C),delete this.schemas[C],delete this.refs[C]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(I){for(let D of I)this.addKeyword(D);return this}addKeyword(I,D){let C;if(typeof I=="string")C=I,typeof D=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),D.keyword=C);else if(typeof I=="object"&&D===void 0){if(D=I,C=D.keyword,Array.isArray(C)&&!C.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(U.call(this,C,D),!D)return(0,l.eachItem)(C,T=>Y.call(this,T)),this;et.call(this,D);let $={...D,type:(0,u.getJSONTypes)(D.type),schemaType:(0,u.getJSONTypes)(D.schemaType)};return(0,l.eachItem)(C,$.type.length===0?T=>Y.call(this,T,$):T=>$.type.forEach(N=>Y.call(this,T,$,N))),this}getKeyword(I){let D=this.RULES.all[I];return typeof D=="object"?D.definition:!!D}removeKeyword(I){let{RULES:D}=this;delete D.keywords[I],delete D.all[I];for(let C of D.rules){let $=C.rules.findIndex(T=>T.keyword===I);$>=0&&C.rules.splice($,1)}return this}addFormat(I,D){return typeof D=="string"&&(D=new RegExp(D)),this.formats[I]=D,this}errorsText(I=this.errors,{separator:D=", ",dataVar:C="data"}={}){return!I||I.length===0?"No errors":I.map($=>`${C}${$.instancePath} ${$.message}`).reduce(($,T)=>$+D+T)}$dataMetaSchema(I,D){let C=this.RULES.all;I=JSON.parse(JSON.stringify(I));for(let $ of D){let T=$.split("/").slice(1),N=I;for(let W of T)N=N[W];for(let W in C){let K=C[W];if(typeof K!="object")continue;let{$data:pe}=K.definition,ce=N[W];pe&&ce&&(N[W]=fe(ce))}}return I}_removeAllSchemas(I,D){for(let C in I){let $=I[C];(!D||D.test(C))&&(typeof $=="string"?delete I[C]:$&&!$.meta&&(this._cache.delete($.schema),delete I[C]))}}_addSchema(I,D,C,$=this.opts.validateSchema,T=this.opts.addUsedSchema){let N,{schemaId:W}=this.opts;if(typeof I=="object")N=I[W];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof I!="boolean")throw new Error("schema must be object or boolean")}let K=this._cache.get(I);if(K!==void 0)return K;C=(0,c.normalizeId)(N||C);let pe=c.getSchemaRefs.call(this,I,C);return K=new o.SchemaEnv({schema:I,schemaId:W,meta:D,baseId:C,localRefs:pe}),this._cache.set(K.schema,K),T&&!C.startsWith("#")&&(C&&this._checkUnique(C),this.refs[C]=K),$&&this.validateSchema(I,!0),K}_checkUnique(I){if(this.schemas[I]||this.refs[I])throw new Error(`schema with key or id "${I}" already exists`)}_compileSchemaEnv(I){if(I.meta?this._compileMetaSchema(I):o.compileSchema.call(this,I),!I.validate)throw new Error("ajv implementation error");return I.validate}_compileMetaSchema(I){let D=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,I)}finally{this.opts=D}}}b.ValidationError=n.default,b.MissingRefError=i.default,t.default=b;function S(F,I,D,C="error"){for(let $ in F){let T=$;T in I&&this.logger[C](`${D}: option ${$}. ${F[T]}`)}}function x(F){return F=(0,c.normalizeId)(F),this.schemas[F]||this.refs[F]}function w(){let F=this.opts.schemas;if(F)if(Array.isArray(F))this.addSchema(F);else for(let I in F)this.addSchema(F[I],I)}function k(){for(let F in this.opts.formats){let I=this.opts.formats[F];I&&this.addFormat(F,I)}}function O(F){if(Array.isArray(F)){this.addVocabulary(F);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let I in F){let D=F[I];D.keyword||(D.keyword=I),this.addKeyword(D)}}function A(){let F={...this.opts};for(let I of g)delete F[I];return F}var M={log(){},warn(){},error(){}};function L(F){if(F===!1)return M;if(F===void 0)return console;if(F.log&&F.warn&&F.error)return F;throw new Error("logger must implement log, warn and error methods")}var B=/^[a-z_$][a-z0-9_$:-]*$/i;function U(F,I){let{RULES:D}=this;if((0,l.eachItem)(F,C=>{if(D.keywords[C])throw new Error(`Keyword ${C} is already defined`);if(!B.test(C))throw new Error(`Keyword ${C} has invalid name`)}),!!I&&I.$data&&!("code"in I||"validate"in I))throw new Error('$data keyword must have "code" or "validate" function')}function Y(F,I,D){var C;let $=I?.post;if(D&&$)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:T}=this,N=$?T.post:T.rules.find(({type:K})=>K===D);if(N||(N={type:D,rules:[]},T.rules.push(N)),T.keywords[F]=!0,!I)return;let W={keyword:F,definition:{...I,type:(0,u.getJSONTypes)(I.type),schemaType:(0,u.getJSONTypes)(I.schemaType)}};I.before?me.call(this,N,W,I.before):N.rules.push(W),T.all[F]=W,(C=I.implements)===null||C===void 0||C.forEach(K=>this.addKeyword(K))}function me(F,I,D){let C=F.rules.findIndex($=>$.keyword===D);C>=0?F.rules.splice(C,0,I):(F.rules.push(I),this.logger.warn(`rule ${D} is not defined`))}function et(F){let{metaSchema:I}=F;I!==void 0&&(F.$data&&this.opts.$data&&(I=fe(I)),F.validateSchema=this.compile(I,!0))}var ht={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function fe(F){return{anyOf:[F,ht]}}}),Nie=V(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}),jie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.callRef=t.getValidate=void 0;var e=tg(),r=ti(),n=Xe(),i=Oa(),a=Z$(),o=dt(),s={keyword:"$ref",schemaType:"string",code(l){let{gen:d,schema:p,it:f}=l,{baseId:g,schemaEnv:_,validateName:h,opts:m,self:y}=f,{root:v}=_;if((p==="#"||p==="#/")&&g===v.baseId)return S();let b=a.resolveRef.call(y,v,g,p);if(b===void 0)throw new e.default(f.opts.uriResolver,g,p);if(b instanceof a.SchemaEnv)return x(b);return w(b);function S(){if(_===v)return u(l,h,_,_.$async);let k=d.scopeValue("root",{ref:v});return u(l,(0,n._)`${k}.validate`,v,v.$async)}function x(k){let O=c(l,k);u(l,O,k,k.$async)}function w(k){let O=d.scopeValue("schema",m.code.source===!0?{ref:k,code:(0,n.stringify)(k)}:{ref:k}),A=d.name("valid"),M=l.subschema({schema:k,dataTypes:[],schemaPath:n.nil,topSchemaRef:O,errSchemaPath:p},A);l.mergeEvaluated(M),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:g,it:_}=l,{allErrors:h,schemaEnv:m,opts:y}=_,v=y.passContext?i.default.this:n.nil;f?b():S();function b(){if(!m.$async)throw new Error("async schema referenced by sync schema");let k=g.let("valid");g.try(()=>{g.code((0,n._)`await ${(0,r.callValidateCode)(l,d,v)}`),w(d),h||g.assign(k,!0)},O=>{g.if((0,n._)`!(${O} instanceof ${_.ValidationError})`,()=>g.throw(O)),x(O),h||g.assign(k,!1)}),l.ok(k)}function S(){l.result((0,r.callValidateCode)(l,d,v),()=>w(d),()=>x(d))}function x(k){let O=(0,n._)`${k}.errors`;g.assign(i.default.vErrors,(0,n._)`${i.default.vErrors} === null ? ${O} : ${i.default.vErrors}.concat(${O})`),g.assign(i.default.errors,(0,n._)`${i.default.vErrors}.length`)}function w(k){var O;if(!_.opts.unevaluated)return;let A=(O=p?.validate)===null||O===void 0?void 0:O.evaluated;if(_.props!==!0)if(A&&!A.dynamicProps)A.props!==void 0&&(_.props=o.mergeEvaluated.props(g,A.props,_.props));else{let M=g.var("props",(0,n._)`${k}.evaluated.props`);_.props=o.mergeEvaluated.props(g,M,_.props,n.Name)}if(_.items!==!0)if(A&&!A.dynamicItems)A.items!==void 0&&(_.items=o.mergeEvaluated.items(g,A.items,_.items));else{let M=g.var("items",(0,n._)`${k}.evaluated.items`);_.items=o.mergeEvaluated.items(g,M,_.items,n.Name)}}}t.callRef=u,t.default=s}),Aie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Nie(),r=jie(),n=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,r.default];t.default=n}),Mie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),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:s})=>(0,e.str)`must be ${n[o].okStr} ${s}`,params:({keyword:o,schemaCode:s})=>(0,e._)`{comparison: ${n[o].okStr}, limit: ${s}}`},a={keyword:Object.keys(n),type:"number",schemaType:"number",$data:!0,error:i,code(o){let{keyword:s,data:c,schemaCode:u}=o;o.fail$data((0,e._)`${c} ${n[s].fail} ${u} || isNaN(${c})`)}};t.default=a}),Die=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),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:a,data:o,schemaCode:s,it:c}=i,u=c.opts.multipleOfPrecision,l=a.let("res"),d=u?(0,e._)`Math.abs(Math.round(${l}) - ${l}) > 1e-${u}`:(0,e._)`${l} !== parseInt(${l})`;i.fail$data((0,e._)`(${s} === 0 || (${l} = ${o}/${s}, ${d}))`)}};t.default=n}),zie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});function e(r){let n=r.length,i=0,a=0,o;for(;a=55296&&o<=56319&&a{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),r=dt(),n=zie(),i={message({keyword:o,schemaCode:s}){let c=o==="maxLength"?"more":"fewer";return(0,e.str)`must NOT have ${c} than ${s} characters`},params:({schemaCode:o})=>(0,e._)`{limit: ${o}}`},a={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:i,code(o){let{keyword:s,data:c,schemaCode:u,it:l}=o,d=s==="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=a}),Lie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ti(),r=Xe(),n={message:({schemaCode:a})=>(0,r.str)`must match pattern "${a}"`,params:({schemaCode:a})=>(0,r._)`{pattern: ${a}}`},i={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:n,code(a){let{data:o,$data:s,schema:c,schemaCode:u,it:l}=a,d=l.opts.unicodeRegExp?"u":"",p=s?(0,r._)`(new RegExp(${u}, ${d}))`:(0,e.usePattern)(a,c);a.fail$data((0,r._)`!${p}.test(${o})`)}};t.default=i}),qie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),r={message({keyword:i,schemaCode:a}){let o=i==="maxProperties"?"more":"fewer";return(0,e.str)`must NOT have ${o} than ${a} properties`},params:({schemaCode:i})=>(0,e._)`{limit: ${i}}`},n={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:r,code(i){let{keyword:a,data:o,schemaCode:s}=i,c=a==="maxProperties"?e.operators.GT:e.operators.LT;i.fail$data((0,e._)`Object.keys(${o}).length ${c} ${s}`)}};t.default=n}),Fie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ti(),r=Xe(),n=dt(),i={message:({params:{missingProperty:o}})=>(0,r.str)`must have required property '${o}'`,params:({params:{missingProperty:o}})=>(0,r._)`{missingProperty: ${o}}`},a={keyword:"required",type:"object",schemaType:"array",$data:!0,error:i,code(o){let{gen:s,schema:c,schemaCode:u,data:l,$data:d,it:p}=o,{opts:f}=p;if(!d&&c.length===0)return;let g=c.length>=f.loopRequired;if(p.allErrors?_():h(),f.strictRequired){let v=o.parentSchema.properties,{definedProperties:b}=o.it;for(let S of c)if(v?.[S]===void 0&&!b.has(S)){let x=p.schemaEnv.baseId+p.errSchemaPath,w=`required property "${S}" is not defined at "${x}" (strictRequired)`;(0,n.checkStrictMode)(p,w,p.opts.strictRequired)}}function _(){if(g||d)o.block$data(r.nil,m);else for(let v of c)(0,e.checkReportMissingProp)(o,v)}function h(){let v=s.let("missing");if(g||d){let b=s.let("valid",!0);o.block$data(b,()=>y(v,b)),o.ok(b)}else s.if((0,e.checkMissingProp)(o,c,v)),(0,e.reportMissingProp)(o,v),s.else()}function m(){s.forOf("prop",u,v=>{o.setParams({missingProperty:v}),s.if((0,e.noPropertyInData)(s,l,v,f.ownProperties),()=>o.error())})}function y(v,b){o.setParams({missingProperty:v}),s.forOf(v,u,()=>{s.assign(b,(0,e.propertyInData)(s,l,v,f.ownProperties)),s.if((0,r.not)(b),()=>{o.error(),s.break()})},r.nil)}}};t.default=a}),Zie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),r={message({keyword:i,schemaCode:a}){let o=i==="maxItems"?"more":"fewer";return(0,e.str)`must NOT have ${o} than ${a} items`},params:({schemaCode:i})=>(0,e._)`{limit: ${i}}`},n={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:r,code(i){let{keyword:a,data:o,schemaCode:s}=i,c=a==="maxItems"?e.operators.GT:e.operators.LT;i.fail$data((0,e._)`${o}.length ${c} ${s}`)}};t.default=n}),H$=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Yh();e.code='require("ajv/dist/runtime/equal").default',t.default=e}),Hie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Fh(),r=Xe(),n=dt(),i=H$(),a={message:({params:{i:s,j:c}})=>(0,r.str)`must NOT have duplicate items (items ## ${c} and ${s} are identical)`,params:({params:{i:s,j:c}})=>(0,r._)`{i: ${s}, j: ${c}}`},o={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:a,code(s){let{gen:c,data:u,$data:l,schema:d,parentSchema:p,schemaCode:f,it:g}=s;if(!l&&!d)return;let _=c.let("valid"),h=p.items?(0,e.getSchemaTypes)(p.items):[];s.block$data(_,m,(0,r._)`${f} === false`),s.ok(_);function m(){let S=c.let("i",(0,r._)`${u}.length`),x=c.let("j");s.setParams({i:S,j:x}),c.assign(_,!0),c.if((0,r._)`${S} > 1`,()=>(y()?v:b)(S,x))}function y(){return h.length>0&&!h.some(S=>S==="object"||S==="array")}function v(S,x){let w=c.name("item"),k=(0,e.checkDataTypes)(h,w,g.opts.strictNumbers,e.DataType.Wrong),O=c.const("indices",(0,r._)`{}`);c.for((0,r._)`;${S}--;`,()=>{c.let(w,(0,r._)`${u}[${S}]`),c.if(k,(0,r._)`continue`),h.length>1&&c.if((0,r._)`typeof ${w} == "string"`,(0,r._)`${w} += "_"`),c.if((0,r._)`typeof ${O}[${w}] == "number"`,()=>{c.assign(x,(0,r._)`${O}[${w}]`),s.error(),c.assign(_,!1).break()}).code((0,r._)`${O}[${w}] = ${S}`)})}function b(S,x){let w=(0,n.useFunc)(c,i.default),k=c.name("outer");c.label(k).for((0,r._)`;${S}--;`,()=>c.for((0,r._)`${x} = ${S}; ${x}--;`,()=>c.if((0,r._)`${w}(${u}[${S}], ${u}[${x}])`,()=>{s.error(),c.assign(_,!1).break(k)})))}}};t.default=o}),Bie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),r=dt(),n=H$(),i={message:"must be equal to constant",params:({schemaCode:o})=>(0,e._)`{allowedValue: ${o}}`},a={keyword:"const",$data:!0,error:i,code(o){let{gen:s,data:c,$data:u,schemaCode:l,schema:d}=o;u||d&&typeof d=="object"?o.fail$data((0,e._)`!${(0,r.useFunc)(s,n.default)}(${c}, ${l})`):o.fail((0,e._)`${d} !== ${c}`)}};t.default=a}),Vie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),r=dt(),n=H$(),i={message:"must be equal to one of the allowed values",params:({schemaCode:o})=>(0,e._)`{allowedValues: ${o}}`},a={keyword:"enum",schemaType:"array",$data:!0,error:i,code(o){let{gen:s,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,g,_=()=>g??(g=(0,r.useFunc)(s,n.default)),h;if(f||u)h=s.let("valid"),o.block$data(h,m);else{if(!Array.isArray(l))throw new Error("ajv implementation error");let v=s.const("vSchema",d);h=(0,e.or)(...l.map((b,S)=>y(v,S)))}o.pass(h);function m(){s.assign(h,!1),s.forOf("v",d,v=>s.if((0,e._)`${_()}(${c}, ${v})`,()=>s.assign(h,!0).break()))}function y(v,b){let S=l[b];return typeof S=="object"&&S!==null?(0,e._)`${_()}(${c}, ${v}[${b}])`:(0,e._)`${c} === ${S}`}}};t.default=a}),Gie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Mie(),r=Die(),n=Uie(),i=Lie(),a=qie(),o=Fie(),s=Zie(),c=Hie(),u=Bie(),l=Vie(),d=[e.default,r.default,n.default,i.default,a.default,o.default,s.default,c.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},u.default,l.default];t.default=d}),F2=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateAdditionalItems=void 0;var e=Xe(),r=dt(),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:s,it:c}=o,{items:u}=s;if(!Array.isArray(u)){(0,r.checkStrictMode)(c,'"additionalItems" is ignored when "items" is not an array of schemas');return}a(o,u)}};function a(o,s){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:s.length}),o.pass((0,e._)`${f} <= ${s.length}`);else if(typeof u=="object"&&!(0,r.alwaysValidSchema)(p,u)){let _=c.var("valid",(0,e._)`${f} <= ${s.length}`);c.if((0,e.not)(_),()=>g(_)),o.ok(_)}function g(_){c.forRange("i",s.length,f,h=>{o.subschema({keyword:d,dataProp:h,dataPropType:r.Type.Num},_),p.allErrors||c.if((0,e.not)(_),()=>c.break())})}}t.validateAdditionalItems=a,t.default=i}),Z2=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateTuple=void 0;var e=Xe(),r=dt(),n=ti(),i={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(o){let{schema:s,it:c}=o;if(Array.isArray(s))return a(o,"additionalItems",s);c.items=!0,!(0,r.alwaysValidSchema)(c,s)&&o.ok((0,n.validateArray)(o))}};function a(o,s,c=o.schema){let{gen:u,parentSchema:l,data:d,keyword:p,it:f}=o;h(l),f.opts.unevaluated&&c.length&&f.items!==!0&&(f.items=r.mergeEvaluated.items(u,c.length,f.items));let g=u.name("valid"),_=u.const("len",(0,e._)`${d}.length`);c.forEach((m,y)=>{(0,r.alwaysValidSchema)(f,m)||(u.if((0,e._)`${_} > ${y}`,()=>o.subschema({keyword:p,schemaProp:y,dataProp:y},g)),o.ok(g))});function h(m){let{opts:y,errSchemaPath:v}=f,b=c.length,S=b===m.minItems&&(b===m.maxItems||m[s]===!1);if(y.strictTuples&&!S){let x=`"${p}" is ${b}-tuple, but minItems or maxItems/${s} are not specified or different at path "${v}"`;(0,r.checkStrictMode)(f,x,y.strictTuples)}}}t.validateTuple=a,t.default=i}),Wie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Z2(),r={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:n=>(0,e.validateTuple)(n,"items")};t.default=r}),Kie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),r=dt(),n=ti(),i=F2(),a={message:({params:{len:s}})=>(0,e.str)`must NOT have more than ${s} items`,params:({params:{len:s}})=>(0,e._)`{limit: ${s}}`},o={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:a,code(s){let{schema:c,parentSchema:u,it:l}=s,{prefixItems:d}=u;l.items=!0,!(0,r.alwaysValidSchema)(l,c)&&(d?(0,i.validateAdditionalItems)(s,d):s.ok((0,n.validateArray)(s)))}};t.default=o}),Jie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),r=dt(),n={message:({params:{min:a,max:o}})=>o===void 0?(0,e.str)`must contain at least ${a} valid item(s)`:(0,e.str)`must contain at least ${a} and no more than ${o} valid item(s)`,params:({params:{min:a,max:o}})=>o===void 0?(0,e._)`{minContains: ${a}}`:(0,e._)`{minContains: ${a}, maxContains: ${o}}`},i={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:n,code(a){let{gen:o,schema:s,parentSchema:c,data:u,it:l}=a,d,p,{minContains:f,maxContains:g}=c;l.opts.next?(d=f===void 0?1:f,p=g):d=1;let _=o.const("len",(0,e._)`${u}.length`);if(a.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'),a.fail();return}if((0,r.alwaysValidSchema)(l,s)){let b=(0,e._)`${_} >= ${d}`;p!==void 0&&(b=(0,e._)`${b} && ${_} <= ${p}`),a.pass(b);return}l.items=!0;let h=o.name("valid");p===void 0&&d===1?y(h,()=>o.if(h,()=>o.break())):d===0?(o.let(h,!0),p!==void 0&&o.if((0,e._)`${u}.length > 0`,m)):(o.let(h,!1),m()),a.result(h,()=>a.reset());function m(){let b=o.name("_valid"),S=o.let("count",0);y(b,()=>o.if(b,()=>v(S)))}function y(b,S){o.forRange("i",0,_,x=>{a.subschema({keyword:"contains",dataProp:x,dataPropType:r.Type.Num,compositeRule:!0},b),S()})}function v(b){o.code((0,e._)`${b}++`),p===void 0?o.if((0,e._)`${b} >= ${d}`,()=>o.assign(h,!0).break()):(o.if((0,e._)`${b} > ${p}`,()=>o.assign(h,!1).break()),d===1?o.assign(h,!0):o.if((0,e._)`${b} >= ${d}`,()=>o.assign(h,!0)))}}};t.default=i}),Xie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;var e=Xe(),r=dt(),n=ti();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}, + || ${O} === "boolean" || ${w} === null`).assign(A,(0,i._)`[${w}]`)}}}function f({gen:v,parentData:b,parentDataProperty:S},x){v.if((0,i._)`${b} !== undefined`,()=>v.assign((0,i._)`${b}[${S}]`,x))}function g(v,b,S,x=o.Correct){let w=x===o.Correct?i.operators.EQ:i.operators.NEQ,k;switch(v){case"null":return(0,i._)`${b} ${w} null`;case"array":k=(0,i._)`Array.isArray(${b})`;break;case"object":k=(0,i._)`${b} && typeof ${b} == "object" && !Array.isArray(${b})`;break;case"integer":k=O((0,i._)`!(${b} % 1) && !isNaN(${b})`);break;case"number":k=O();break;default:return(0,i._)`typeof ${b} ${w} ${v}`}return x===o.Correct?k:(0,i.not)(k);function O(A=i.nil){return(0,i.and)((0,i._)`typeof ${b} == "number"`,A,S?(0,i._)`isFinite(${b})`:i.nil)}}t.checkDataType=g;function _(v,b,S,x){if(v.length===1)return g(v[0],b,S,x);let w,k=(0,a.toHash)(v);if(k.array&&k.object){let O=(0,i._)`typeof ${b} != "object"`;w=k.null?O:(0,i._)`!${b} || ${O}`,delete k.null,delete k.array,delete k.object}else w=i.nil;k.number&&delete k.integer;for(let O in k)w=(0,i.and)(w,g(O,b,S,x));return w}t.checkDataTypes=_;var h={message:({schema:v})=>`must be ${v}`,params:({schema:v,schemaValue:b})=>typeof v=="string"?(0,i._)`{type: ${v}}`:(0,i._)`{type: ${b}}`};function m(v){let b=y(v);(0,n.reportError)(b,h)}t.reportTypeError=m;function y(v){let{gen:b,data:S,schema:x}=v,w=(0,a.schemaRefOrVal)(v,x,"type");return{gen:b,keyword:"type",data:S,schema:x.type,schemaCode:w,schemaValue:w,parentSchema:x,params:{},it:v}}}),wie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.assignDefaults=void 0;var e=Xe(),r=dt();function n(a,o){let{properties:s,items:c}=a.schema;if(o==="object"&&s)for(let u in s)i(a,u,s[u].default);else o==="array"&&Array.isArray(c)&&c.forEach((u,l)=>i(a,l,u.default))}t.assignDefaults=n;function i(a,o,s){let{gen:c,compositeRule:u,data:l,opts:d}=a;if(s===void 0)return;let p=(0,e._)`${l}${(0,e.getProperty)(o)}`;if(u){(0,r.checkStrictMode)(a,`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)(s)}`)}}),ti=V(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=Xe(),r=dt(),n=Oa(),i=dt();function a(v,b){let{gen:S,data:x,it:w}=v;S.if(d(S,x,b,w.opts.ownProperties),()=>{v.setParams({missingProperty:(0,e._)`${b}`},!0),v.error()})}t.checkReportMissingProp=a;function o({gen:v,data:b,it:{opts:S}},x,w){return(0,e.or)(...x.map(k=>(0,e.and)(d(v,b,k,S.ownProperties),(0,e._)`${w} = ${k}`)))}t.checkMissingProp=o;function s(v,b){v.setParams({missingProperty:b},!0),v.error()}t.reportMissingProp=s;function c(v){return v.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}t.hasPropFunc=c;function u(v,b,S){return(0,e._)`${c(v)}.call(${b}, ${S})`}t.isOwnProperty=u;function l(v,b,S,x){let w=(0,e._)`${b}${(0,e.getProperty)(S)} !== undefined`;return x?(0,e._)`${w} && ${u(v,b,S)}`:w}t.propertyInData=l;function d(v,b,S,x){let w=(0,e._)`${b}${(0,e.getProperty)(S)} === undefined`;return x?(0,e.or)(w,(0,e.not)(u(v,b,S))):w}t.noPropertyInData=d;function p(v){return v?Object.keys(v).filter(b=>b!=="__proto__"):[]}t.allSchemaProperties=p;function f(v,b){return p(b).filter(S=>!(0,r.alwaysValidSchema)(v,b[S]))}t.schemaProperties=f;function g({schemaCode:v,data:b,it:{gen:S,topSchemaRef:x,schemaPath:w,errorPath:k},it:O},A,M,L){let B=L?(0,e._)`${v}, ${b}, ${x}${w}`:b,U=[[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,k)],[n.default.parentData,O.parentData],[n.default.parentDataProperty,O.parentDataProperty],[n.default.rootData,n.default.rootData]];O.opts.dynamicRef&&U.push([n.default.dynamicAnchors,n.default.dynamicAnchors]);let Y=(0,e._)`${B}, ${S.object(...U)}`;return M!==e.nil?(0,e._)`${A}.call(${M}, ${Y})`:(0,e._)`${A}(${Y})`}t.callValidateCode=g;var _=(0,e._)`new RegExp`;function h({gen:v,it:{opts:b}},S){let x=b.unicodeRegExp?"u":"",{regExp:w}=b.code,k=w(S,x);return v.scopeValue("pattern",{key:k.toString(),ref:k,code:(0,e._)`${w.code==="new RegExp"?_:(0,i.useFunc)(v,w)}(${S}, ${x})`})}t.usePattern=h;function m(v){let{gen:b,data:S,keyword:x,it:w}=v,k=b.name("valid");if(w.allErrors){let A=b.let("valid",!0);return O(()=>b.assign(A,!1)),A}return b.var(k,!0),O(()=>b.break()),k;function O(A){let M=b.const("len",(0,e._)`${S}.length`);b.forRange("i",0,M,L=>{v.subschema({keyword:x,dataProp:L,dataPropType:r.Type.Num},k),b.if((0,e.not)(k),A)})}}t.validateArray=m;function y(v){let{gen:b,schema:S,keyword:x,it:w}=v;if(!Array.isArray(S))throw new Error("ajv implementation error");if(S.some(M=>(0,r.alwaysValidSchema)(w,M))&&!w.opts.unevaluated)return;let O=b.let("valid",!1),A=b.name("_valid");b.block(()=>S.forEach((M,L)=>{let B=v.subschema({keyword:x,schemaProp:L,compositeRule:!0},A);b.assign(O,(0,e._)`${O} || ${A}`),v.mergeValidEvaluated(B,A)||b.if((0,e.not)(O))})),v.result(O,()=>v.reset(),()=>v.error(!0))}t.validateUnion=y}),$ie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateKeywordUsage=t.validSchemaType=t.funcKeywordCode=t.macroKeywordCode=void 0;var e=Xe(),r=Oa(),n=ti(),i=Xh();function a(f,g){let{gen:_,keyword:h,schema:m,parentSchema:y,it:v}=f,b=g.macro.call(v.self,m,y,v),S=l(_,h,b);v.opts.validateSchema!==!1&&v.self.validateSchema(b,!0);let x=_.name("valid");f.subschema({schema:b,schemaPath:e.nil,errSchemaPath:`${v.errSchemaPath}/${h}`,topSchemaRef:S,compositeRule:!0},x),f.pass(x,()=>f.error(!0))}t.macroKeywordCode=a;function o(f,g){var _;let{gen:h,keyword:m,schema:y,parentSchema:v,$data:b,it:S}=f;u(S,g);let x=!b&&g.compile?g.compile.call(S.self,y,v,S):g.validate,w=l(h,m,x),k=h.let("valid");f.block$data(k,O),f.ok((_=g.valid)!==null&&_!==void 0?_:k);function O(){if(g.errors===!1)L(),g.modifying&&s(f),B(()=>f.error());else{let U=g.async?A():M();g.modifying&&s(f),B(()=>c(f,U))}}function A(){let U=h.let("ruleErrs",null);return h.try(()=>L((0,e._)`await `),Y=>h.assign(k,!1).if((0,e._)`${Y} instanceof ${S.ValidationError}`,()=>h.assign(U,(0,e._)`${Y}.errors`),()=>h.throw(Y))),U}function M(){let U=(0,e._)`${w}.errors`;return h.assign(U,null),L(e.nil),U}function L(U=g.async?(0,e._)`await `:e.nil){let Y=S.opts.passContext?r.default.this:r.default.self,me=!("compile"in g&&!b||g.schema===!1);h.assign(k,(0,e._)`${U}${(0,n.callValidateCode)(f,w,Y,me)}`,g.modifying)}function B(U){var Y;h.if((0,e.not)((Y=g.valid)!==null&&Y!==void 0?Y:k),U)}}t.funcKeywordCode=o;function s(f){let{gen:g,data:_,it:h}=f;g.if(h.parentData,()=>g.assign(_,(0,e._)`${h.parentData}[${h.parentDataProperty}]`))}function c(f,g){let{gen:_}=f;_.if((0,e._)`Array.isArray(${g})`,()=>{_.assign(r.default.vErrors,(0,e._)`${r.default.vErrors} === null ? ${g} : ${r.default.vErrors}.concat(${g})`).assign(r.default.errors,(0,e._)`${r.default.vErrors}.length`),(0,i.extendErrors)(f)},()=>f.error())}function u({schemaEnv:f},g){if(g.async&&!f.$async)throw new Error("async keyword in sync schema")}function l(f,g,_){if(_===void 0)throw new Error(`keyword "${g}" failed to compile`);return f.scopeValue("keyword",typeof _=="function"?{ref:_}:{ref:_,code:(0,e.stringify)(_)})}function d(f,g,_=!1){return!g.length||g.some(h=>h==="array"?Array.isArray(f):h==="object"?f&&typeof f=="object"&&!Array.isArray(f):typeof f==h||_&&typeof f>"u")}t.validSchemaType=d;function p({schema:f,opts:g,self:_,errSchemaPath:h},m,y){if(Array.isArray(m.keyword)?!m.keyword.includes(y):m.keyword!==y)throw new Error("ajv implementation error");let v=m.dependencies;if(v?.some(b=>!Object.prototype.hasOwnProperty.call(f,b)))throw new Error(`parent schema must have dependencies of ${y}: ${v.join(",")}`);if(m.validateSchema&&!m.validateSchema(f[y])){let S=`keyword "${y}" value is invalid at path "${h}": `+_.errorsText(m.validateSchema.errors);if(g.validateSchema==="log")_.logger.error(S);else throw new Error(S)}}t.validateKeywordUsage=p}),Eie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extendSubschemaMode=t.extendSubschemaData=t.getSubschema=void 0;var e=Xe(),r=dt();function n(o,{keyword:s,schemaProp:c,schema:u,schemaPath:l,errSchemaPath:d,topSchemaRef:p}){if(s!==void 0&&u!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(s!==void 0){let f=o.schema[s];return c===void 0?{schema:f,schemaPath:(0,e._)`${o.schemaPath}${(0,e.getProperty)(s)}`,errSchemaPath:`${o.errSchemaPath}/${s}`}:{schema:f[c],schemaPath:(0,e._)`${o.schemaPath}${(0,e.getProperty)(s)}${(0,e.getProperty)(c)}`,errSchemaPath:`${o.errSchemaPath}/${s}/${(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,s,{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}=s;if(c!==void 0){let{errorPath:_,dataPathArr:h,opts:m}=s,y=f.let("data",(0,e._)`${s.data}${(0,e.getProperty)(c)}`,!0);g(y),o.errorPath=(0,e.str)`${_}${(0,r.getErrorPath)(c,u,m.jsPropertySyntax)}`,o.parentDataProperty=(0,e._)`${c}`,o.dataPathArr=[...h,o.parentDataProperty]}if(l!==void 0){let _=l instanceof e.Name?l:f.let("data",l,!0);g(_),p!==void 0&&(o.propertyName=p)}d&&(o.dataTypes=d);function g(_){o.data=_,o.dataLevel=s.dataLevel+1,o.dataTypes=[],s.definedProperties=new Set,o.parentData=s.data,o.dataNames=[...s.dataNames,_]}}t.extendSubschemaData=i;function a(o,{jtdDiscriminator:s,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=s,o.jtdMetadata=c}t.extendSubschemaMode=a}),Yh=V((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 a,o,s;if(Array.isArray(n)){if(a=n.length,a!=i.length)return!1;for(o=a;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(s=Object.keys(n),a=s.length,a!==Object.keys(i).length)return!1;for(o=a;o--!==0;)if(!Object.prototype.hasOwnProperty.call(i,s[o]))return!1;for(o=a;o--!==0;){var c=s[o];if(!r(n[c],i[c]))return!1}return!0}return n!==n&&i!==i}}),kie=V((t,e)=>{var r=e.exports=function(a,o,s){typeof o=="function"&&(s=o,o={}),s=o.cb||s;var c=typeof s=="function"?s:s.pre||function(){},u=s.post||function(){};n(o,c,u,a,"",a)};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(a,o,s,c,u,l,d,p,f,g){if(c&&typeof c=="object"&&!Array.isArray(c)){o(c,u,l,d,p,f,g);for(var _ in c){var h=c[_];if(Array.isArray(h)){if(_ in r.arrayKeywords)for(var m=0;m{Object.defineProperty(t,"__esModule",{value:!0}),t.getSchemaRefs=t.resolveUrl=t.normalizeId=t._getFullPath=t.getFullPath=t.inlineRef=void 0;var e=dt(),r=Yh(),n=kie(),i=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function a(h,m=!0){return typeof h=="boolean"?!0:m===!0?!s(h):m?c(h)<=m:!1}t.inlineRef=a;var o=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function s(h){for(let m in h){if(o.has(m))return!0;let y=h[m];if(Array.isArray(y)&&y.some(s)||typeof y=="object"&&s(y))return!0}return!1}function c(h){let m=0;for(let y in h){if(y==="$ref")return 1/0;if(m++,!i.has(y)&&(typeof h[y]=="object"&&(0,e.eachItem)(h[y],v=>m+=c(v)),m===1/0))return 1/0}return m}function u(h,m="",y){y!==!1&&(m=p(m));let v=h.parse(m);return l(h,v)}t.getFullPath=u;function l(h,m){return h.serialize(m).split("#")[0]+"#"}t._getFullPath=l;var d=/#\/?$/;function p(h){return h?h.replace(d,""):""}t.normalizeId=p;function f(h,m,y){return y=p(y),h.resolve(m,y)}t.resolveUrl=f;var g=/^[a-z_][-a-z0-9._]*$/i;function _(h,m){if(typeof h=="boolean")return{};let{schemaId:y,uriResolver:v}=this.opts,b=p(h[y]||m),S={"":b},x=u(v,b,!1),w={},k=new Set;return n(h,{allKeys:!0},(M,L,B,U)=>{if(U===void 0)return;let Y=x+L,me=S[U];typeof M[y]=="string"&&(me=et.call(this,M[y])),ht.call(this,M.$anchor),ht.call(this,M.$dynamicAnchor),S[L]=me;function et(fe){let F=this.opts.uriResolver.resolve;if(fe=p(me?F(me,fe):fe),k.has(fe))throw A(fe);k.add(fe);let I=this.refs[fe];return typeof I=="string"&&(I=this.refs[I]),typeof I=="object"?O(M,I.schema,fe):fe!==p(Y)&&(fe[0]==="#"?(O(M,w[fe],fe),w[fe]=M):this.refs[fe]=Y),fe}function ht(fe){if(typeof fe=="string"){if(!g.test(fe))throw new Error(`invalid anchor "${fe}"`);et.call(this,`#${fe}`)}}}),w;function O(M,L,B){if(L!==void 0&&!r(M,L))throw A(B)}function A(M){return new Error(`reference "${M}" resolves to more than one schema`)}}t.getSchemaRefs=_}),eg=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getData=t.KeywordCxt=t.validateFunctionCode=void 0;var e=Sie(),r=Fh(),n=L2(),i=Fh(),a=wie(),o=$ie(),s=Eie(),c=Xe(),u=Oa(),l=Qh(),d=dt(),p=Xh();function f(P){if(x(P)&&(k(P),S(P))){m(P);return}g(P,()=>(0,e.topBoolOrEmptySchema)(P))}t.validateFunctionCode=f;function g({gen:P,validateName:R,schema:z,schemaEnv:Z,opts:J},ie){J.code.es5?P.func(R,(0,c._)`${u.default.data}, ${u.default.valCxt}`,Z.$async,()=>{P.code((0,c._)`"use strict"; ${v(z,J)}`),h(P,J),P.code(ie)}):P.func(R,(0,c._)`${u.default.data}, ${_(J)}`,Z.$async,()=>P.code(v(z,J)).code(ie))}function _(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 h(P,R){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}`),R.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),R.dynamicRef&&P.var(u.default.dynamicAnchors,(0,c._)`{}`)})}function m(P){let{schema:R,opts:z,gen:Z}=P;g(P,()=>{z.$comment&&R.$comment&&U(P),M(P),Z.let(u.default.vErrors,null),Z.let(u.default.errors,0),z.unevaluated&&y(P),O(P),Y(P)})}function y(P){let{gen:R,validateName:z}=P;P.evaluated=R.const("evaluated",(0,c._)`${z}.evaluated`),R.if((0,c._)`${P.evaluated}.dynamicProps`,()=>R.assign((0,c._)`${P.evaluated}.props`,(0,c._)`undefined`)),R.if((0,c._)`${P.evaluated}.dynamicItems`,()=>R.assign((0,c._)`${P.evaluated}.items`,(0,c._)`undefined`))}function v(P,R){let z=typeof P=="object"&&P[R.schemaId];return z&&(R.code.source||R.code.process)?(0,c._)`/*# sourceURL=${z} */`:c.nil}function b(P,R){if(x(P)&&(k(P),S(P))){w(P,R);return}(0,e.boolOrEmptySchema)(P,R)}function S({schema:P,self:R}){if(typeof P=="boolean")return!P;for(let z in P)if(R.RULES.all[z])return!0;return!1}function x(P){return typeof P.schema!="boolean"}function w(P,R){let{schema:z,gen:Z,opts:J}=P;J.$comment&&z.$comment&&U(P),L(P),B(P);let ie=Z.const("_errs",u.default.errors);O(P,ie),Z.var(R,(0,c._)`${ie} === ${u.default.errors}`)}function k(P){(0,d.checkUnknownRules)(P),A(P)}function O(P,R){if(P.opts.jtd)return et(P,[],!1,R);let z=(0,r.getSchemaTypes)(P.schema),Z=(0,r.coerceAndCheckDataType)(P,z);et(P,z,!Z,R)}function A(P){let{schema:R,errSchemaPath:z,opts:Z,self:J}=P;R.$ref&&Z.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(R,J.RULES)&&J.logger.warn(`$ref: keywords ignored in schema at path "${z}"`)}function M(P){let{schema:R,opts:z}=P;R.default!==void 0&&z.useDefaults&&z.strictSchema&&(0,d.checkStrictMode)(P,"default is ignored in the schema root")}function L(P){let R=P.schema[P.opts.schemaId];R&&(P.baseId=(0,l.resolveUrl)(P.opts.uriResolver,P.baseId,R))}function B(P){if(P.schema.$async&&!P.schemaEnv.$async)throw new Error("async schema in sync schema")}function U({gen:P,schemaEnv:R,schema:z,errSchemaPath:Z,opts:J}){let ie=z.$comment;if(J.$comment===!0)P.code((0,c._)`${u.default.self}.logger.log(${ie})`);else if(typeof J.$comment=="function"){let tt=(0,c.str)`${Z}/$comment`,Ht=P.scopeValue("root",{ref:R.root});P.code((0,c._)`${u.default.self}.opts.$comment(${ie}, ${tt}, ${Ht}.schema)`)}}function Y(P){let{gen:R,schemaEnv:z,validateName:Z,ValidationError:J,opts:ie}=P;z.$async?R.if((0,c._)`${u.default.errors} === 0`,()=>R.return(u.default.data),()=>R.throw((0,c._)`new ${J}(${u.default.vErrors})`)):(R.assign((0,c._)`${Z}.errors`,u.default.vErrors),ie.unevaluated&&me(P),R.return((0,c._)`${u.default.errors} === 0`))}function me({gen:P,evaluated:R,props:z,items:Z}){z instanceof c.Name&&P.assign((0,c._)`${R}.props`,z),Z instanceof c.Name&&P.assign((0,c._)`${R}.items`,Z)}function et(P,R,z,Z){let{gen:J,schema:ie,data:tt,allErrors:Ht,opts:yt,self:_t}=P,{RULES:rt}=_t;if(ie.$ref&&(yt.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(ie,rt))){J.block(()=>K(P,"$ref",rt.all.$ref.definition));return}yt.jtd||fe(P,R),J.block(()=>{for(let jt of rt.rules)en(jt);en(rt.post)});function en(jt){(0,n.shouldUseGroup)(ie,jt)&&(jt.type?(J.if((0,i.checkDataType)(jt.type,tt,yt.strictNumbers)),ht(P,jt),R.length===1&&R[0]===jt.type&&z&&(J.else(),(0,i.reportTypeError)(P)),J.endIf()):ht(P,jt),Ht||J.if((0,c._)`${u.default.errors} === ${Z||0}`))}}function ht(P,R){let{gen:z,schema:Z,opts:{useDefaults:J}}=P;J&&(0,a.assignDefaults)(P,R.type),z.block(()=>{for(let ie of R.rules)(0,n.shouldUseRule)(Z,ie)&&K(P,ie.keyword,ie.definition,R.type)})}function fe(P,R){P.schemaEnv.meta||!P.opts.strictTypes||(F(P,R),P.opts.allowUnionTypes||I(P,R),D(P,P.dataTypes))}function F(P,R){if(R.length){if(!P.dataTypes.length){P.dataTypes=R;return}R.forEach(z=>{$(P.dataTypes,z)||N(P,`type "${z}" not allowed by context "${P.dataTypes.join(",")}"`)}),T(P,R)}}function I(P,R){R.length>1&&!(R.length===2&&R.includes("null"))&&N(P,"use allowUnionTypes to allow union type keyword")}function D(P,R){let z=P.self.RULES.all;for(let Z in z){let J=z[Z];if(typeof J=="object"&&(0,n.shouldUseRule)(P.schema,J)){let{type:ie}=J.definition;ie.length&&!ie.some(tt=>C(R,tt))&&N(P,`missing type "${ie.join(",")}" for keyword "${Z}"`)}}}function C(P,R){return P.includes(R)||R==="number"&&P.includes("integer")}function $(P,R){return P.includes(R)||R==="integer"&&P.includes("number")}function T(P,R){let z=[];for(let Z of P.dataTypes)$(R,Z)?z.push(Z):R.includes("integer")&&Z==="number"&&z.push("integer");P.dataTypes=z}function N(P,R){let z=P.schemaEnv.baseId+P.errSchemaPath;R+=` at "${z}" (strictTypes)`,(0,d.checkStrictMode)(P,R,P.opts.strictTypes)}class W{constructor(R,z,Z){if((0,o.validateKeywordUsage)(R,z,Z),this.gen=R.gen,this.allErrors=R.allErrors,this.keyword=Z,this.data=R.data,this.schema=R.schema[Z],this.$data=z.$data&&R.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(R,this.schema,Z,this.$data),this.schemaType=z.schemaType,this.parentSchema=R.schema,this.params={},this.it=R,this.def=z,this.$data)this.schemaCode=R.gen.const("vSchema",je(this.$data,R));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,z.schemaType,z.allowUndefined))throw new Error(`${Z} value must be ${JSON.stringify(z.schemaType)}`);("code"in z?z.trackErrors:z.errors!==!1)&&(this.errsCount=R.gen.const("_errs",u.default.errors))}result(R,z,Z){this.failResult((0,c.not)(R),z,Z)}failResult(R,z,Z){this.gen.if(R),Z?Z():this.error(),z?(this.gen.else(),z(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(R,z){this.failResult((0,c.not)(R),void 0,z)}fail(R){if(R===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(R),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(R){if(!this.$data)return this.fail(R);let{schemaCode:z}=this;this.fail((0,c._)`${z} !== undefined && (${(0,c.or)(this.invalid$data(),R)})`)}error(R,z,Z){if(z){this.setParams(z),this._error(R,Z),this.setParams({});return}this._error(R,Z)}_error(R,z){(R?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(R){this.allErrors||this.gen.if(R)}setParams(R,z){z?Object.assign(this.params,R):this.params=R}block$data(R,z,Z=c.nil){this.gen.block(()=>{this.check$data(R,Z),z()})}check$data(R=c.nil,z=c.nil){if(!this.$data)return;let{gen:Z,schemaCode:J,schemaType:ie,def:tt}=this;Z.if((0,c.or)((0,c._)`${J} === undefined`,z)),R!==c.nil&&Z.assign(R,!0),(ie.length||tt.validateSchema)&&(Z.elseIf(this.invalid$data()),this.$dataError(),R!==c.nil&&Z.assign(R,!1)),Z.else()}invalid$data(){let{gen:R,schemaCode:z,schemaType:Z,def:J,it:ie}=this;return(0,c.or)(tt(),Ht());function tt(){if(Z.length){if(!(z instanceof c.Name))throw new Error("ajv implementation error");let yt=Array.isArray(Z)?Z:[Z];return(0,c._)`${(0,i.checkDataTypes)(yt,z,ie.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function Ht(){if(J.validateSchema){let yt=R.scopeValue("validate$data",{ref:J.validateSchema});return(0,c._)`!${yt}(${z})`}return c.nil}}subschema(R,z){let Z=(0,s.getSubschema)(this.it,R);(0,s.extendSubschemaData)(Z,this.it,R),(0,s.extendSubschemaMode)(Z,R);let J={...this.it,...Z,items:void 0,props:void 0};return b(J,z),J}mergeEvaluated(R,z){let{it:Z,gen:J}=this;Z.opts.unevaluated&&(Z.props!==!0&&R.props!==void 0&&(Z.props=d.mergeEvaluated.props(J,R.props,Z.props,z)),Z.items!==!0&&R.items!==void 0&&(Z.items=d.mergeEvaluated.items(J,R.items,Z.items,z)))}mergeValidEvaluated(R,z){let{it:Z,gen:J}=this;if(Z.opts.unevaluated&&(Z.props!==!0||Z.items!==!0))return J.if(z,()=>this.mergeEvaluated(R,c.Name)),!0}}t.KeywordCxt=W;function K(P,R,z,Z){let J=new W(P,z,R);"code"in z?z.code(J,Z):J.$data&&z.validate?(0,o.funcKeywordCode)(J,z):"macro"in z?(0,o.macroKeywordCode)(J,z):(z.compile||z.validate)&&(0,o.funcKeywordCode)(J,z)}var pe=/^\/(?:[^~]|~0|~1)*$/,ce=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function je(P,{dataLevel:R,dataNames:z,dataPathArr:Z}){let J,ie;if(P==="")return u.default.rootData;if(P[0]==="/"){if(!pe.test(P))throw new Error(`Invalid JSON-pointer: ${P}`);J=P,ie=u.default.rootData}else{let _t=ce.exec(P);if(!_t)throw new Error(`Invalid JSON-pointer: ${P}`);let rt=+_t[1];if(J=_t[2],J==="#"){if(rt>=R)throw new Error(yt("property/index",rt));return Z[R-rt]}if(rt>R)throw new Error(yt("data",rt));if(ie=z[R-rt],!J)return ie}let tt=ie,Ht=J.split("/");for(let _t of Ht)_t&&(ie=(0,c._)`${ie}${(0,c.getProperty)((0,d.unescapeJsonPointer)(_t))}`,tt=(0,c._)`${tt} && ${ie}`);return tt;function yt(_t,rt){return`Cannot access ${_t} ${rt} levels up, current level is ${R}`}}t.getData=je}),F$=V(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}),tg=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Qh();class r extends Error{constructor(i,a,o,s){super(s||`can't resolve reference ${o} from id ${a}`),this.missingRef=(0,e.resolveUrl)(i,a,o),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(i,this.missingRef))}}t.default=r}),Z$=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resolveSchema=t.getCompilingSchema=t.resolveRef=t.compileSchema=t.SchemaEnv=void 0;var e=Xe(),r=F$(),n=Oa(),i=Qh(),a=dt(),o=eg();class s{constructor(y){var v;this.refs={},this.dynamicAnchors={};let b;typeof y.schema=="object"&&(b=y.schema),this.schema=y.schema,this.schemaId=y.schemaId,this.root=y.root||this,this.baseId=(v=y.baseId)!==null&&v!==void 0?v:(0,i.normalizeId)(b?.[y.schemaId||"$id"]),this.schemaPath=y.schemaPath,this.localRefs=y.localRefs,this.meta=y.meta,this.$async=b?.$async,this.refs={}}}t.SchemaEnv=s;function c(m){let y=d.call(this,m);if(y)return y;let v=(0,i.getFullPath)(this.opts.uriResolver,m.root.baseId),{es5:b,lines:S}=this.opts.code,{ownProperties:x}=this.opts,w=new e.CodeGen(this.scope,{es5:b,lines:S,ownProperties:x}),k;m.$async&&(k=w.scopeValue("Error",{ref:r.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));let O=w.scopeName("validate");m.validateName=O;let A={gen:w,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:w.scopeValue("schema",this.opts.code.source===!0?{ref:m.schema,code:(0,e.stringify)(m.schema)}:{ref:m.schema}),validateName:O,ValidationError:k,schema:m.schema,schemaEnv:m,rootId:v,baseId:m.baseId||v,schemaPath:e.nil,errSchemaPath:m.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this},M;try{this._compilations.add(m),(0,o.validateFunctionCode)(A),w.optimize(this.opts.code.optimize);let L=w.toString();M=`${w.scopeRefs(n.default.scope)}return ${L}`,this.opts.code.process&&(M=this.opts.code.process(M,m));let U=new Function(`${n.default.self}`,`${n.default.scope}`,M)(this,this.scope.get());if(this.scope.value(O,{ref:U}),U.errors=null,U.schema=m.schema,U.schemaEnv=m,m.$async&&(U.$async=!0),this.opts.code.source===!0&&(U.source={validateName:O,validateCode:L,scopeValues:w._values}),this.opts.unevaluated){let{props:Y,items:me}=A;U.evaluated={props:Y instanceof e.Name?void 0:Y,items:me instanceof e.Name?void 0:me,dynamicProps:Y instanceof e.Name,dynamicItems:me instanceof e.Name},U.source&&(U.source.evaluated=(0,e.stringify)(U.evaluated))}return m.validate=U,m}catch(L){throw delete m.validate,delete m.validateName,M&&this.logger.error("Error compiling schema, function code:",M),L}finally{this._compilations.delete(m)}}t.compileSchema=c;function u(m,y,v){var b;v=(0,i.resolveUrl)(this.opts.uriResolver,y,v);let S=m.refs[v];if(S)return S;let x=f.call(this,m,v);if(x===void 0){let w=(b=m.localRefs)===null||b===void 0?void 0:b[v],{schemaId:k}=this.opts;w&&(x=new s({schema:w,schemaId:k,root:m,baseId:y}))}if(x!==void 0)return m.refs[v]=l.call(this,x)}t.resolveRef=u;function l(m){return(0,i.inlineRef)(m.schema,this.opts.inlineRefs)?m.schema:m.validate?m:c.call(this,m)}function d(m){for(let y of this._compilations)if(p(y,m))return y}t.getCompilingSchema=d;function p(m,y){return m.schema===y.schema&&m.root===y.root&&m.baseId===y.baseId}function f(m,y){let v;for(;typeof(v=this.refs[y])=="string";)y=v;return v||this.schemas[y]||g.call(this,m,y)}function g(m,y){let v=this.opts.uriResolver.parse(y),b=(0,i._getFullPath)(this.opts.uriResolver,v),S=(0,i.getFullPath)(this.opts.uriResolver,m.baseId,void 0);if(Object.keys(m.schema).length>0&&b===S)return h.call(this,v,m);let x=(0,i.normalizeId)(b),w=this.refs[x]||this.schemas[x];if(typeof w=="string"){let k=g.call(this,m,w);return typeof k?.schema!="object"?void 0:h.call(this,v,k)}if(typeof w?.schema=="object"){if(w.validate||c.call(this,w),x===(0,i.normalizeId)(y)){let{schema:k}=w,{schemaId:O}=this.opts,A=k[O];return A&&(S=(0,i.resolveUrl)(this.opts.uriResolver,S,A)),new s({schema:k,schemaId:O,root:m,baseId:S})}return h.call(this,v,w)}}t.resolveSchema=g;var _=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function h(m,{baseId:y,schema:v,root:b}){var S;if(((S=m.fragment)===null||S===void 0?void 0:S[0])!=="/")return;for(let k of m.fragment.slice(1).split("/")){if(typeof v=="boolean")return;let O=v[(0,a.unescapeFragment)(k)];if(O===void 0)return;v=O;let A=typeof v=="object"&&v[this.opts.schemaId];!_.has(k)&&A&&(y=(0,i.resolveUrl)(this.opts.uriResolver,y,A))}let x;if(typeof v!="boolean"&&v.$ref&&!(0,a.schemaHasRulesButRef)(v,this.RULES)){let k=(0,i.resolveUrl)(this.opts.uriResolver,y,v.$ref);x=g.call(this,b,k)}let{schemaId:w}=this.opts;if(x=x||new s({schema:v,schemaId:w,root:b,baseId:y}),x.schema!==x.root.schema)return x}}),Tie=V((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}}),Iie=V((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}}),Pie=V((t,e)=>{var{HEX:r}=Iie(),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(m){if(u(m,".")<3)return{host:m,isIPV4:!1};let y=m.match(n)||[],[v]=y;return v?{host:c(v,"."),isIPV4:!0}:{host:m,isIPV4:!1}}function a(m,y=!1){let v="",b=!0;for(let S of m){if(r[S]===void 0)return;S!=="0"&&b===!0&&(b=!1),b||(v+=S)}return y&&v.length===0&&(v="0"),v}function o(m){let y=0,v={error:!1,address:"",zone:""},b=[],S=[],x=!1,w=!1,k=!1;function O(){if(S.length){if(x===!1){let A=a(S);if(A!==void 0)b.push(A);else return v.error=!0,!1}S.length=0}return!0}for(let A=0;A7){v.error=!0;break}A-1>=0&&m[A-1]===":"&&(w=!0);continue}else if(M==="%"){if(!O())break;x=!0}else{S.push(M);continue}}return S.length&&(x?v.zone=S.join(""):k?b.push(S.join("")):b.push(a(S))),v.address=b.join(""),v}function s(m){if(u(m,":")<2)return{host:m,isIPV6:!1};let y=o(m);if(y.error)return{host:m,isIPV6:!1};{let v=y.address,b=y.address;return y.zone&&(v+="%"+y.zone,b+="%25"+y.zone),{host:v,escapedHost:b,isIPV6:!0}}}function c(m,y){let v="",b=!0,S=m.length;for(let x=0;x{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(b){return typeof b.secure=="boolean"?b.secure:String(b.scheme).toLowerCase()==="wss"}function a(b){return b.host||(b.error=b.error||"HTTP URIs must have a host."),b}function o(b){let S=String(b.scheme).toLowerCase()==="https";return(b.port===(S?443:80)||b.port==="")&&(b.port=void 0),b.path||(b.path="/"),b}function s(b){return b.secure=i(b),b.resourceName=(b.path||"/")+(b.query?"?"+b.query:""),b.path=void 0,b.query=void 0,b}function c(b){if((b.port===(i(b)?443:80)||b.port==="")&&(b.port=void 0),typeof b.secure=="boolean"&&(b.scheme=b.secure?"wss":"ws",b.secure=void 0),b.resourceName){let[S,x]=b.resourceName.split("?");b.path=S&&S!=="/"?S:void 0,b.query=x,b.resourceName=void 0}return b.fragment=void 0,b}function u(b,S){if(!b.path)return b.error="URN can not be parsed",b;let x=b.path.match(n);if(x){let w=S.scheme||b.scheme||"urn";b.nid=x[1].toLowerCase(),b.nss=x[2];let k=`${w}:${S.nid||b.nid}`,O=v[k];b.path=void 0,O&&(b=O.parse(b,S))}else b.error=b.error||"URN can not be parsed.";return b}function l(b,S){let x=S.scheme||b.scheme||"urn",w=b.nid.toLowerCase(),k=`${x}:${S.nid||w}`,O=v[k];O&&(b=O.serialize(b,S));let A=b,M=b.nss;return A.path=`${w||S.nid}:${M}`,S.skipEscape=!0,A}function d(b,S){let x=b;return x.uuid=x.nss,x.nss=void 0,!S.tolerant&&(!x.uuid||!r.test(x.uuid))&&(x.error=x.error||"UUID is not valid."),x}function p(b){let S=b;return S.nss=(b.uuid||"").toLowerCase(),S}var f={scheme:"http",domainHost:!0,parse:a,serialize:o},g={scheme:"https",domainHost:f.domainHost,parse:a,serialize:o},_={scheme:"ws",domainHost:!0,parse:s,serialize:c},h={scheme:"wss",domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},m={scheme:"urn",parse:u,serialize:l,skipNormalize:!0},y={scheme:"urn:uuid",parse:d,serialize:p,skipNormalize:!0},v={http:f,https:g,ws:_,wss:h,urn:m,"urn:uuid":y};e.exports=v}),q2=V((t,e)=>{var{normalizeIPv6:r,normalizeIPv4:n,removeDotSegments:i,recomposeAuthority:a,normalizeComponentEncoding:o}=Pie(),s=Oie();function c(y,v){return typeof y=="string"?y=p(h(y,v),v):typeof y=="object"&&(y=h(p(y,v),v)),y}function u(y,v,b){let S=Object.assign({scheme:"null"},b),x=l(h(y,S),h(v,S),S,!0);return p(x,{...S,skipEscape:!0})}function l(y,v,b,S){let x={};return S||(y=h(p(y,b),b),v=h(p(v,b),b)),b=b||{},!b.tolerant&&v.scheme?(x.scheme=v.scheme,x.userinfo=v.userinfo,x.host=v.host,x.port=v.port,x.path=i(v.path||""),x.query=v.query):(v.userinfo!==void 0||v.host!==void 0||v.port!==void 0?(x.userinfo=v.userinfo,x.host=v.host,x.port=v.port,x.path=i(v.path||""),x.query=v.query):(v.path?(v.path.charAt(0)==="/"?x.path=i(v.path):((y.userinfo!==void 0||y.host!==void 0||y.port!==void 0)&&!y.path?x.path="/"+v.path:y.path?x.path=y.path.slice(0,y.path.lastIndexOf("/")+1)+v.path:x.path=v.path,x.path=i(x.path)),x.query=v.query):(x.path=y.path,v.query!==void 0?x.query=v.query:x.query=y.query),x.userinfo=y.userinfo,x.host=y.host,x.port=y.port),x.scheme=y.scheme),x.fragment=v.fragment,x}function d(y,v,b){return typeof y=="string"?(y=unescape(y),y=p(o(h(y,b),!0),{...b,skipEscape:!0})):typeof y=="object"&&(y=p(o(y,!0),{...b,skipEscape:!0})),typeof v=="string"?(v=unescape(v),v=p(o(h(v,b),!0),{...b,skipEscape:!0})):typeof v=="object"&&(v=p(o(v,!0),{...b,skipEscape:!0})),y.toLowerCase()===v.toLowerCase()}function p(y,v){let b={host:y.host,scheme:y.scheme,userinfo:y.userinfo,port:y.port,path:y.path,query:y.query,nid:y.nid,nss:y.nss,uuid:y.uuid,fragment:y.fragment,reference:y.reference,resourceName:y.resourceName,secure:y.secure,error:""},S=Object.assign({},v),x=[],w=s[(S.scheme||b.scheme||"").toLowerCase()];w&&w.serialize&&w.serialize(b,S),b.path!==void 0&&(S.skipEscape?b.path=unescape(b.path):(b.path=escape(b.path),b.scheme!==void 0&&(b.path=b.path.split("%3A").join(":")))),S.reference!=="suffix"&&b.scheme&&x.push(b.scheme,":");let k=a(b);if(k!==void 0&&(S.reference!=="suffix"&&x.push("//"),x.push(k),b.path&&b.path.charAt(0)!=="/"&&x.push("/")),b.path!==void 0){let O=b.path;!S.absolutePath&&(!w||!w.absolutePath)&&(O=i(O)),k===void 0&&(O=O.replace(/^\/\//u,"/%2F")),x.push(O)}return b.query!==void 0&&x.push("?",b.query),b.fragment!==void 0&&x.push("#",b.fragment),x.join("")}var f=Array.from({length:127},(y,v)=>/[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(v)));function g(y){let v=0;for(let b=0,S=y.length;b126||f[v])return!0;return!1}var _=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function h(y,v){let b=Object.assign({},v),S={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},x=y.indexOf("%")!==-1,w=!1;b.reference==="suffix"&&(y=(b.scheme?b.scheme+":":"")+"//"+y);let k=y.match(_);if(k){if(S.scheme=k[1],S.userinfo=k[3],S.host=k[4],S.port=parseInt(k[5],10),S.path=k[6]||"",S.query=k[7],S.fragment=k[8],isNaN(S.port)&&(S.port=k[5]),S.host){let A=n(S.host);if(A.isIPV4===!1){let M=r(A.host);S.host=M.host.toLowerCase(),w=M.isIPV6}else S.host=A.host,w=!0}S.scheme===void 0&&S.userinfo===void 0&&S.host===void 0&&S.port===void 0&&S.query===void 0&&!S.path?S.reference="same-document":S.scheme===void 0?S.reference="relative":S.fragment===void 0?S.reference="absolute":S.reference="uri",b.reference&&b.reference!=="suffix"&&b.reference!==S.reference&&(S.error=S.error||"URI is not a "+b.reference+" reference.");let O=s[(b.scheme||S.scheme||"").toLowerCase()];if(!b.unicodeSupport&&(!O||!O.unicodeSupport)&&S.host&&(b.domainHost||O&&O.domainHost)&&w===!1&&g(S.host))try{S.host=URL.domainToASCII(S.host.toLowerCase())}catch(A){S.error=S.error||"Host's domain name can not be converted to ASCII: "+A}(!O||O&&!O.skipNormalize)&&(x&&S.scheme!==void 0&&(S.scheme=unescape(S.scheme)),x&&S.host!==void 0&&(S.host=unescape(S.host)),S.path&&(S.path=escape(unescape(S.path))),S.fragment&&(S.fragment=encodeURI(decodeURIComponent(S.fragment)))),O&&O.parse&&O.parse(S,b)}else S.error=S.error||"URI can not be parsed.";return S}var m={SCHEMES:s,normalize:c,resolve:u,resolveComponents:l,equal:d,serialize:p,parse:h};e.exports=m,e.exports.default=m,e.exports.fastUri=m}),Rie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=q2();e.code='require("ajv/dist/runtime/uri").default',t.default=e}),Cie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var e=eg();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var r=Xe();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=F$(),i=tg(),a=U2(),o=Z$(),s=Xe(),c=Qh(),u=Fh(),l=dt(),d=Tie(),p=Rie(),f=(F,I)=>new RegExp(F,I);f.code="new RegExp";var g=["removeAdditional","useDefaults","coerceTypes"],_=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),h={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."},m={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},y=200;function v(F){var I,D,C,$,T,N,W,K,pe,ce,je,P,R,z,Z,J,ie,tt,Ht,yt,_t,rt,en,jt,Na;let An=F.strict,ja=(I=F.code)===null||I===void 0?void 0:I.optimize,Ac=ja===!0||ja===void 0?1:ja||0,Mc=(C=(D=F.code)===null||D===void 0?void 0:D.regExp)!==null&&C!==void 0?C:f,Gg=($=F.uriResolver)!==null&&$!==void 0?$:p.default;return{strictSchema:(N=(T=F.strictSchema)!==null&&T!==void 0?T:An)!==null&&N!==void 0?N:!0,strictNumbers:(K=(W=F.strictNumbers)!==null&&W!==void 0?W:An)!==null&&K!==void 0?K:!0,strictTypes:(ce=(pe=F.strictTypes)!==null&&pe!==void 0?pe:An)!==null&&ce!==void 0?ce:"log",strictTuples:(P=(je=F.strictTuples)!==null&&je!==void 0?je:An)!==null&&P!==void 0?P:"log",strictRequired:(z=(R=F.strictRequired)!==null&&R!==void 0?R:An)!==null&&z!==void 0?z:!1,code:F.code?{...F.code,optimize:Ac,regExp:Mc}:{optimize:Ac,regExp:Mc},loopRequired:(Z=F.loopRequired)!==null&&Z!==void 0?Z:y,loopEnum:(J=F.loopEnum)!==null&&J!==void 0?J:y,meta:(ie=F.meta)!==null&&ie!==void 0?ie:!0,messages:(tt=F.messages)!==null&&tt!==void 0?tt:!0,inlineRefs:(Ht=F.inlineRefs)!==null&&Ht!==void 0?Ht:!0,schemaId:(yt=F.schemaId)!==null&&yt!==void 0?yt:"$id",addUsedSchema:(_t=F.addUsedSchema)!==null&&_t!==void 0?_t:!0,validateSchema:(rt=F.validateSchema)!==null&&rt!==void 0?rt:!0,validateFormats:(en=F.validateFormats)!==null&&en!==void 0?en:!0,unicodeRegExp:(jt=F.unicodeRegExp)!==null&&jt!==void 0?jt:!0,int32range:(Na=F.int32range)!==null&&Na!==void 0?Na:!0,uriResolver:Gg}}class b{constructor(I={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,I=this.opts={...I,...v(I)};let{es5:D,lines:C}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:_,es5:D,lines:C}),this.logger=L(I.logger);let $=I.validateFormats;I.validateFormats=!1,this.RULES=(0,a.getRules)(),S.call(this,h,I,"NOT SUPPORTED"),S.call(this,m,I,"DEPRECATED","warn"),this._metaOpts=A.call(this),I.formats&&k.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),I.keywords&&O.call(this,I.keywords),typeof I.meta=="object"&&this.addMetaSchema(I.meta),w.call(this),I.validateFormats=$}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:I,meta:D,schemaId:C}=this.opts,$=d;C==="id"&&($={...d},$.id=$.$id,delete $.$id),D&&I&&this.addMetaSchema($,$[C],!1)}defaultMeta(){let{meta:I,schemaId:D}=this.opts;return this.opts.defaultMeta=typeof I=="object"?I[D]||I:void 0}validate(I,D){let C;if(typeof I=="string"){if(C=this.getSchema(I),!C)throw new Error(`no schema with key or ref "${I}"`)}else C=this.compile(I);let $=C(D);return"$async"in C||(this.errors=C.errors),$}compile(I,D){let C=this._addSchema(I,D);return C.validate||this._compileSchemaEnv(C)}compileAsync(I,D){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:C}=this.opts;return $.call(this,I,D);async function $(ce,je){await T.call(this,ce.$schema);let P=this._addSchema(ce,je);return P.validate||N.call(this,P)}async function T(ce){ce&&!this.getSchema(ce)&&await $.call(this,{$ref:ce},!0)}async function N(ce){try{return this._compileSchemaEnv(ce)}catch(je){if(!(je instanceof i.default))throw je;return W.call(this,je),await K.call(this,je.missingSchema),N.call(this,ce)}}function W({missingSchema:ce,missingRef:je}){if(this.refs[ce])throw new Error(`AnySchema ${ce} is loaded but ${je} cannot be resolved`)}async function K(ce){let je=await pe.call(this,ce);this.refs[ce]||await T.call(this,je.$schema),this.refs[ce]||this.addSchema(je,ce,D)}async function pe(ce){let je=this._loading[ce];if(je)return je;try{return await(this._loading[ce]=C(ce))}finally{delete this._loading[ce]}}}addSchema(I,D,C,$=this.opts.validateSchema){if(Array.isArray(I)){for(let N of I)this.addSchema(N,void 0,C,$);return this}let T;if(typeof I=="object"){let{schemaId:N}=this.opts;if(T=I[N],T!==void 0&&typeof T!="string")throw new Error(`schema ${N} must be string`)}return D=(0,c.normalizeId)(D||T),this._checkUnique(D),this.schemas[D]=this._addSchema(I,C,D,$,!0),this}addMetaSchema(I,D,C=this.opts.validateSchema){return this.addSchema(I,D,!0,C),this}validateSchema(I,D){if(typeof I=="boolean")return!0;let C;if(C=I.$schema,C!==void 0&&typeof C!="string")throw new Error("$schema must be a string");if(C=C||this.opts.defaultMeta||this.defaultMeta(),!C)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let $=this.validate(C,I);if(!$&&D){let T="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(T);else throw new Error(T)}return $}getSchema(I){let D;for(;typeof(D=x.call(this,I))=="string";)I=D;if(D===void 0){let{schemaId:C}=this.opts,$=new o.SchemaEnv({schema:{},schemaId:C});if(D=o.resolveSchema.call(this,$,I),!D)return;this.refs[I]=D}return D.validate||this._compileSchemaEnv(D)}removeSchema(I){if(I instanceof RegExp)return this._removeAllSchemas(this.schemas,I),this._removeAllSchemas(this.refs,I),this;switch(typeof I){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let D=x.call(this,I);return typeof D=="object"&&this._cache.delete(D.schema),delete this.schemas[I],delete this.refs[I],this}case"object":{let D=I;this._cache.delete(D);let C=I[this.opts.schemaId];return C&&(C=(0,c.normalizeId)(C),delete this.schemas[C],delete this.refs[C]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(I){for(let D of I)this.addKeyword(D);return this}addKeyword(I,D){let C;if(typeof I=="string")C=I,typeof D=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),D.keyword=C);else if(typeof I=="object"&&D===void 0){if(D=I,C=D.keyword,Array.isArray(C)&&!C.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(U.call(this,C,D),!D)return(0,l.eachItem)(C,T=>Y.call(this,T)),this;et.call(this,D);let $={...D,type:(0,u.getJSONTypes)(D.type),schemaType:(0,u.getJSONTypes)(D.schemaType)};return(0,l.eachItem)(C,$.type.length===0?T=>Y.call(this,T,$):T=>$.type.forEach(N=>Y.call(this,T,$,N))),this}getKeyword(I){let D=this.RULES.all[I];return typeof D=="object"?D.definition:!!D}removeKeyword(I){let{RULES:D}=this;delete D.keywords[I],delete D.all[I];for(let C of D.rules){let $=C.rules.findIndex(T=>T.keyword===I);$>=0&&C.rules.splice($,1)}return this}addFormat(I,D){return typeof D=="string"&&(D=new RegExp(D)),this.formats[I]=D,this}errorsText(I=this.errors,{separator:D=", ",dataVar:C="data"}={}){return!I||I.length===0?"No errors":I.map($=>`${C}${$.instancePath} ${$.message}`).reduce(($,T)=>$+D+T)}$dataMetaSchema(I,D){let C=this.RULES.all;I=JSON.parse(JSON.stringify(I));for(let $ of D){let T=$.split("/").slice(1),N=I;for(let W of T)N=N[W];for(let W in C){let K=C[W];if(typeof K!="object")continue;let{$data:pe}=K.definition,ce=N[W];pe&&ce&&(N[W]=fe(ce))}}return I}_removeAllSchemas(I,D){for(let C in I){let $=I[C];(!D||D.test(C))&&(typeof $=="string"?delete I[C]:$&&!$.meta&&(this._cache.delete($.schema),delete I[C]))}}_addSchema(I,D,C,$=this.opts.validateSchema,T=this.opts.addUsedSchema){let N,{schemaId:W}=this.opts;if(typeof I=="object")N=I[W];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof I!="boolean")throw new Error("schema must be object or boolean")}let K=this._cache.get(I);if(K!==void 0)return K;C=(0,c.normalizeId)(N||C);let pe=c.getSchemaRefs.call(this,I,C);return K=new o.SchemaEnv({schema:I,schemaId:W,meta:D,baseId:C,localRefs:pe}),this._cache.set(K.schema,K),T&&!C.startsWith("#")&&(C&&this._checkUnique(C),this.refs[C]=K),$&&this.validateSchema(I,!0),K}_checkUnique(I){if(this.schemas[I]||this.refs[I])throw new Error(`schema with key or id "${I}" already exists`)}_compileSchemaEnv(I){if(I.meta?this._compileMetaSchema(I):o.compileSchema.call(this,I),!I.validate)throw new Error("ajv implementation error");return I.validate}_compileMetaSchema(I){let D=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,I)}finally{this.opts=D}}}b.ValidationError=n.default,b.MissingRefError=i.default,t.default=b;function S(F,I,D,C="error"){for(let $ in F){let T=$;T in I&&this.logger[C](`${D}: option ${$}. ${F[T]}`)}}function x(F){return F=(0,c.normalizeId)(F),this.schemas[F]||this.refs[F]}function w(){let F=this.opts.schemas;if(F)if(Array.isArray(F))this.addSchema(F);else for(let I in F)this.addSchema(F[I],I)}function k(){for(let F in this.opts.formats){let I=this.opts.formats[F];I&&this.addFormat(F,I)}}function O(F){if(Array.isArray(F)){this.addVocabulary(F);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let I in F){let D=F[I];D.keyword||(D.keyword=I),this.addKeyword(D)}}function A(){let F={...this.opts};for(let I of g)delete F[I];return F}var M={log(){},warn(){},error(){}};function L(F){if(F===!1)return M;if(F===void 0)return console;if(F.log&&F.warn&&F.error)return F;throw new Error("logger must implement log, warn and error methods")}var B=/^[a-z_$][a-z0-9_$:-]*$/i;function U(F,I){let{RULES:D}=this;if((0,l.eachItem)(F,C=>{if(D.keywords[C])throw new Error(`Keyword ${C} is already defined`);if(!B.test(C))throw new Error(`Keyword ${C} has invalid name`)}),!!I&&I.$data&&!("code"in I||"validate"in I))throw new Error('$data keyword must have "code" or "validate" function')}function Y(F,I,D){var C;let $=I?.post;if(D&&$)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:T}=this,N=$?T.post:T.rules.find(({type:K})=>K===D);if(N||(N={type:D,rules:[]},T.rules.push(N)),T.keywords[F]=!0,!I)return;let W={keyword:F,definition:{...I,type:(0,u.getJSONTypes)(I.type),schemaType:(0,u.getJSONTypes)(I.schemaType)}};I.before?me.call(this,N,W,I.before):N.rules.push(W),T.all[F]=W,(C=I.implements)===null||C===void 0||C.forEach(K=>this.addKeyword(K))}function me(F,I,D){let C=F.rules.findIndex($=>$.keyword===D);C>=0?F.rules.splice(C,0,I):(F.rules.push(I),this.logger.warn(`rule ${D} is not defined`))}function et(F){let{metaSchema:I}=F;I!==void 0&&(F.$data&&this.opts.$data&&(I=fe(I)),F.validateSchema=this.compile(I,!0))}var ht={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function fe(F){return{anyOf:[F,ht]}}}),Nie=V(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}),jie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.callRef=t.getValidate=void 0;var e=tg(),r=ti(),n=Xe(),i=Oa(),a=Z$(),o=dt(),s={keyword:"$ref",schemaType:"string",code(l){let{gen:d,schema:p,it:f}=l,{baseId:g,schemaEnv:_,validateName:h,opts:m,self:y}=f,{root:v}=_;if((p==="#"||p==="#/")&&g===v.baseId)return S();let b=a.resolveRef.call(y,v,g,p);if(b===void 0)throw new e.default(f.opts.uriResolver,g,p);if(b instanceof a.SchemaEnv)return x(b);return w(b);function S(){if(_===v)return u(l,h,_,_.$async);let k=d.scopeValue("root",{ref:v});return u(l,(0,n._)`${k}.validate`,v,v.$async)}function x(k){let O=c(l,k);u(l,O,k,k.$async)}function w(k){let O=d.scopeValue("schema",m.code.source===!0?{ref:k,code:(0,n.stringify)(k)}:{ref:k}),A=d.name("valid"),M=l.subschema({schema:k,dataTypes:[],schemaPath:n.nil,topSchemaRef:O,errSchemaPath:p},A);l.mergeEvaluated(M),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:g,it:_}=l,{allErrors:h,schemaEnv:m,opts:y}=_,v=y.passContext?i.default.this:n.nil;f?b():S();function b(){if(!m.$async)throw new Error("async schema referenced by sync schema");let k=g.let("valid");g.try(()=>{g.code((0,n._)`await ${(0,r.callValidateCode)(l,d,v)}`),w(d),h||g.assign(k,!0)},O=>{g.if((0,n._)`!(${O} instanceof ${_.ValidationError})`,()=>g.throw(O)),x(O),h||g.assign(k,!1)}),l.ok(k)}function S(){l.result((0,r.callValidateCode)(l,d,v),()=>w(d),()=>x(d))}function x(k){let O=(0,n._)`${k}.errors`;g.assign(i.default.vErrors,(0,n._)`${i.default.vErrors} === null ? ${O} : ${i.default.vErrors}.concat(${O})`),g.assign(i.default.errors,(0,n._)`${i.default.vErrors}.length`)}function w(k){var O;if(!_.opts.unevaluated)return;let A=(O=p?.validate)===null||O===void 0?void 0:O.evaluated;if(_.props!==!0)if(A&&!A.dynamicProps)A.props!==void 0&&(_.props=o.mergeEvaluated.props(g,A.props,_.props));else{let M=g.var("props",(0,n._)`${k}.evaluated.props`);_.props=o.mergeEvaluated.props(g,M,_.props,n.Name)}if(_.items!==!0)if(A&&!A.dynamicItems)A.items!==void 0&&(_.items=o.mergeEvaluated.items(g,A.items,_.items));else{let M=g.var("items",(0,n._)`${k}.evaluated.items`);_.items=o.mergeEvaluated.items(g,M,_.items,n.Name)}}}t.callRef=u,t.default=s}),Aie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Nie(),r=jie(),n=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,r.default];t.default=n}),Mie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),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:s})=>(0,e.str)`must be ${n[o].okStr} ${s}`,params:({keyword:o,schemaCode:s})=>(0,e._)`{comparison: ${n[o].okStr}, limit: ${s}}`},a={keyword:Object.keys(n),type:"number",schemaType:"number",$data:!0,error:i,code(o){let{keyword:s,data:c,schemaCode:u}=o;o.fail$data((0,e._)`${c} ${n[s].fail} ${u} || isNaN(${c})`)}};t.default=a}),Die=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),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:a,data:o,schemaCode:s,it:c}=i,u=c.opts.multipleOfPrecision,l=a.let("res"),d=u?(0,e._)`Math.abs(Math.round(${l}) - ${l}) > 1e-${u}`:(0,e._)`${l} !== parseInt(${l})`;i.fail$data((0,e._)`(${s} === 0 || (${l} = ${o}/${s}, ${d}))`)}};t.default=n}),zie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});function e(r){let n=r.length,i=0,a=0,o;for(;a=55296&&o<=56319&&a{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),r=dt(),n=zie(),i={message({keyword:o,schemaCode:s}){let c=o==="maxLength"?"more":"fewer";return(0,e.str)`must NOT have ${c} than ${s} characters`},params:({schemaCode:o})=>(0,e._)`{limit: ${o}}`},a={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:i,code(o){let{keyword:s,data:c,schemaCode:u,it:l}=o,d=s==="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=a}),Lie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ti(),r=Xe(),n={message:({schemaCode:a})=>(0,r.str)`must match pattern "${a}"`,params:({schemaCode:a})=>(0,r._)`{pattern: ${a}}`},i={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:n,code(a){let{data:o,$data:s,schema:c,schemaCode:u,it:l}=a,d=l.opts.unicodeRegExp?"u":"",p=s?(0,r._)`(new RegExp(${u}, ${d}))`:(0,e.usePattern)(a,c);a.fail$data((0,r._)`!${p}.test(${o})`)}};t.default=i}),qie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),r={message({keyword:i,schemaCode:a}){let o=i==="maxProperties"?"more":"fewer";return(0,e.str)`must NOT have ${o} than ${a} properties`},params:({schemaCode:i})=>(0,e._)`{limit: ${i}}`},n={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:r,code(i){let{keyword:a,data:o,schemaCode:s}=i,c=a==="maxProperties"?e.operators.GT:e.operators.LT;i.fail$data((0,e._)`Object.keys(${o}).length ${c} ${s}`)}};t.default=n}),Fie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ti(),r=Xe(),n=dt(),i={message:({params:{missingProperty:o}})=>(0,r.str)`must have required property '${o}'`,params:({params:{missingProperty:o}})=>(0,r._)`{missingProperty: ${o}}`},a={keyword:"required",type:"object",schemaType:"array",$data:!0,error:i,code(o){let{gen:s,schema:c,schemaCode:u,data:l,$data:d,it:p}=o,{opts:f}=p;if(!d&&c.length===0)return;let g=c.length>=f.loopRequired;if(p.allErrors?_():h(),f.strictRequired){let v=o.parentSchema.properties,{definedProperties:b}=o.it;for(let S of c)if(v?.[S]===void 0&&!b.has(S)){let x=p.schemaEnv.baseId+p.errSchemaPath,w=`required property "${S}" is not defined at "${x}" (strictRequired)`;(0,n.checkStrictMode)(p,w,p.opts.strictRequired)}}function _(){if(g||d)o.block$data(r.nil,m);else for(let v of c)(0,e.checkReportMissingProp)(o,v)}function h(){let v=s.let("missing");if(g||d){let b=s.let("valid",!0);o.block$data(b,()=>y(v,b)),o.ok(b)}else s.if((0,e.checkMissingProp)(o,c,v)),(0,e.reportMissingProp)(o,v),s.else()}function m(){s.forOf("prop",u,v=>{o.setParams({missingProperty:v}),s.if((0,e.noPropertyInData)(s,l,v,f.ownProperties),()=>o.error())})}function y(v,b){o.setParams({missingProperty:v}),s.forOf(v,u,()=>{s.assign(b,(0,e.propertyInData)(s,l,v,f.ownProperties)),s.if((0,r.not)(b),()=>{o.error(),s.break()})},r.nil)}}};t.default=a}),Zie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),r={message({keyword:i,schemaCode:a}){let o=i==="maxItems"?"more":"fewer";return(0,e.str)`must NOT have ${o} than ${a} items`},params:({schemaCode:i})=>(0,e._)`{limit: ${i}}`},n={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:r,code(i){let{keyword:a,data:o,schemaCode:s}=i,c=a==="maxItems"?e.operators.GT:e.operators.LT;i.fail$data((0,e._)`${o}.length ${c} ${s}`)}};t.default=n}),H$=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Yh();e.code='require("ajv/dist/runtime/equal").default',t.default=e}),Hie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Fh(),r=Xe(),n=dt(),i=H$(),a={message:({params:{i:s,j:c}})=>(0,r.str)`must NOT have duplicate items (items ## ${c} and ${s} are identical)`,params:({params:{i:s,j:c}})=>(0,r._)`{i: ${s}, j: ${c}}`},o={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:a,code(s){let{gen:c,data:u,$data:l,schema:d,parentSchema:p,schemaCode:f,it:g}=s;if(!l&&!d)return;let _=c.let("valid"),h=p.items?(0,e.getSchemaTypes)(p.items):[];s.block$data(_,m,(0,r._)`${f} === false`),s.ok(_);function m(){let S=c.let("i",(0,r._)`${u}.length`),x=c.let("j");s.setParams({i:S,j:x}),c.assign(_,!0),c.if((0,r._)`${S} > 1`,()=>(y()?v:b)(S,x))}function y(){return h.length>0&&!h.some(S=>S==="object"||S==="array")}function v(S,x){let w=c.name("item"),k=(0,e.checkDataTypes)(h,w,g.opts.strictNumbers,e.DataType.Wrong),O=c.const("indices",(0,r._)`{}`);c.for((0,r._)`;${S}--;`,()=>{c.let(w,(0,r._)`${u}[${S}]`),c.if(k,(0,r._)`continue`),h.length>1&&c.if((0,r._)`typeof ${w} == "string"`,(0,r._)`${w} += "_"`),c.if((0,r._)`typeof ${O}[${w}] == "number"`,()=>{c.assign(x,(0,r._)`${O}[${w}]`),s.error(),c.assign(_,!1).break()}).code((0,r._)`${O}[${w}] = ${S}`)})}function b(S,x){let w=(0,n.useFunc)(c,i.default),k=c.name("outer");c.label(k).for((0,r._)`;${S}--;`,()=>c.for((0,r._)`${x} = ${S}; ${x}--;`,()=>c.if((0,r._)`${w}(${u}[${S}], ${u}[${x}])`,()=>{s.error(),c.assign(_,!1).break(k)})))}}};t.default=o}),Bie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),r=dt(),n=H$(),i={message:"must be equal to constant",params:({schemaCode:o})=>(0,e._)`{allowedValue: ${o}}`},a={keyword:"const",$data:!0,error:i,code(o){let{gen:s,data:c,$data:u,schemaCode:l,schema:d}=o;u||d&&typeof d=="object"?o.fail$data((0,e._)`!${(0,r.useFunc)(s,n.default)}(${c}, ${l})`):o.fail((0,e._)`${d} !== ${c}`)}};t.default=a}),Vie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),r=dt(),n=H$(),i={message:"must be equal to one of the allowed values",params:({schemaCode:o})=>(0,e._)`{allowedValues: ${o}}`},a={keyword:"enum",schemaType:"array",$data:!0,error:i,code(o){let{gen:s,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,g,_=()=>g??(g=(0,r.useFunc)(s,n.default)),h;if(f||u)h=s.let("valid"),o.block$data(h,m);else{if(!Array.isArray(l))throw new Error("ajv implementation error");let v=s.const("vSchema",d);h=(0,e.or)(...l.map((b,S)=>y(v,S)))}o.pass(h);function m(){s.assign(h,!1),s.forOf("v",d,v=>s.if((0,e._)`${_()}(${c}, ${v})`,()=>s.assign(h,!0).break()))}function y(v,b){let S=l[b];return typeof S=="object"&&S!==null?(0,e._)`${_()}(${c}, ${v}[${b}])`:(0,e._)`${c} === ${S}`}}};t.default=a}),Gie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Mie(),r=Die(),n=Uie(),i=Lie(),a=qie(),o=Fie(),s=Zie(),c=Hie(),u=Bie(),l=Vie(),d=[e.default,r.default,n.default,i.default,a.default,o.default,s.default,c.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},u.default,l.default];t.default=d}),F2=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateAdditionalItems=void 0;var e=Xe(),r=dt(),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:s,it:c}=o,{items:u}=s;if(!Array.isArray(u)){(0,r.checkStrictMode)(c,'"additionalItems" is ignored when "items" is not an array of schemas');return}a(o,u)}};function a(o,s){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:s.length}),o.pass((0,e._)`${f} <= ${s.length}`);else if(typeof u=="object"&&!(0,r.alwaysValidSchema)(p,u)){let _=c.var("valid",(0,e._)`${f} <= ${s.length}`);c.if((0,e.not)(_),()=>g(_)),o.ok(_)}function g(_){c.forRange("i",s.length,f,h=>{o.subschema({keyword:d,dataProp:h,dataPropType:r.Type.Num},_),p.allErrors||c.if((0,e.not)(_),()=>c.break())})}}t.validateAdditionalItems=a,t.default=i}),Z2=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateTuple=void 0;var e=Xe(),r=dt(),n=ti(),i={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(o){let{schema:s,it:c}=o;if(Array.isArray(s))return a(o,"additionalItems",s);c.items=!0,!(0,r.alwaysValidSchema)(c,s)&&o.ok((0,n.validateArray)(o))}};function a(o,s,c=o.schema){let{gen:u,parentSchema:l,data:d,keyword:p,it:f}=o;h(l),f.opts.unevaluated&&c.length&&f.items!==!0&&(f.items=r.mergeEvaluated.items(u,c.length,f.items));let g=u.name("valid"),_=u.const("len",(0,e._)`${d}.length`);c.forEach((m,y)=>{(0,r.alwaysValidSchema)(f,m)||(u.if((0,e._)`${_} > ${y}`,()=>o.subschema({keyword:p,schemaProp:y,dataProp:y},g)),o.ok(g))});function h(m){let{opts:y,errSchemaPath:v}=f,b=c.length,S=b===m.minItems&&(b===m.maxItems||m[s]===!1);if(y.strictTuples&&!S){let x=`"${p}" is ${b}-tuple, but minItems or maxItems/${s} are not specified or different at path "${v}"`;(0,r.checkStrictMode)(f,x,y.strictTuples)}}}t.validateTuple=a,t.default=i}),Wie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Z2(),r={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:n=>(0,e.validateTuple)(n,"items")};t.default=r}),Kie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),r=dt(),n=ti(),i=F2(),a={message:({params:{len:s}})=>(0,e.str)`must NOT have more than ${s} items`,params:({params:{len:s}})=>(0,e._)`{limit: ${s}}`},o={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:a,code(s){let{schema:c,parentSchema:u,it:l}=s,{prefixItems:d}=u;l.items=!0,!(0,r.alwaysValidSchema)(l,c)&&(d?(0,i.validateAdditionalItems)(s,d):s.ok((0,n.validateArray)(s)))}};t.default=o}),Jie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),r=dt(),n={message:({params:{min:a,max:o}})=>o===void 0?(0,e.str)`must contain at least ${a} valid item(s)`:(0,e.str)`must contain at least ${a} and no more than ${o} valid item(s)`,params:({params:{min:a,max:o}})=>o===void 0?(0,e._)`{minContains: ${a}}`:(0,e._)`{minContains: ${a}, maxContains: ${o}}`},i={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:n,code(a){let{gen:o,schema:s,parentSchema:c,data:u,it:l}=a,d,p,{minContains:f,maxContains:g}=c;l.opts.next?(d=f===void 0?1:f,p=g):d=1;let _=o.const("len",(0,e._)`${u}.length`);if(a.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'),a.fail();return}if((0,r.alwaysValidSchema)(l,s)){let b=(0,e._)`${_} >= ${d}`;p!==void 0&&(b=(0,e._)`${b} && ${_} <= ${p}`),a.pass(b);return}l.items=!0;let h=o.name("valid");p===void 0&&d===1?y(h,()=>o.if(h,()=>o.break())):d===0?(o.let(h,!0),p!==void 0&&o.if((0,e._)`${u}.length > 0`,m)):(o.let(h,!1),m()),a.result(h,()=>a.reset());function m(){let b=o.name("_valid"),S=o.let("count",0);y(b,()=>o.if(b,()=>v(S)))}function y(b,S){o.forRange("i",0,_,x=>{a.subschema({keyword:"contains",dataProp:x,dataPropType:r.Type.Num,compositeRule:!0},b),S()})}function v(b){o.code((0,e._)`${b}++`),p===void 0?o.if((0,e._)`${b} >= ${d}`,()=>o.assign(h,!0).break()):(o.if((0,e._)`${b} > ${p}`,()=>o.assign(h,!1).break()),d===1?o.assign(h,!0):o.if((0,e._)`${b} >= ${d}`,()=>o.assign(h,!0)))}}};t.default=i}),Xie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;var e=Xe(),r=dt(),n=ti();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]=a(c);o(c,u),s(c,l)}};function a({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 g in u){let _=u[g];if(_.length===0)continue;let h=(0,n.propertyInData)(l,d,g,p.opts.ownProperties);c.setParams({property:g,depsCount:_.length,deps:_.join(", ")}),p.allErrors?l.if(h,()=>{for(let m of _)(0,n.checkReportMissingProp)(c,m)}):(l.if((0,e._)`${h} && (${(0,n.checkMissingProp)(c,_,f)})`),(0,n.reportMissingProp)(c,f),l.else())}}t.validatePropertyDeps=o;function s(c,u=c.schema){let{gen:l,data:d,keyword:p,it:f}=c,g=l.name("valid");for(let _ in u)(0,r.alwaysValidSchema)(f,u[_])||(l.if((0,n.propertyInData)(l,d,_,f.opts.ownProperties),()=>{let h=c.subschema({keyword:p,schemaProp:_},g);c.mergeValidEvaluated(h,g)},()=>l.var(g,!0)),c.ok(g))}t.validateSchemaDeps=s,t.default=i}),Yie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),r=dt(),n={message:"property name must be valid",params:({params:a})=>(0,e._)`{propertyName: ${a.propertyName}}`},i={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:n,code(a){let{gen:o,schema:s,data:c,it:u}=a;if((0,r.alwaysValidSchema)(u,s))return;let l=o.name("valid");o.forIn("key",c,d=>{a.setParams({propertyName:d}),a.subschema({keyword:"propertyNames",data:d,dataTypes:["string"],propertyName:d,compositeRule:!0},l),o.if((0,e.not)(l),()=>{a.error(!0),u.allErrors||o.break()})}),a.ok(l)}};t.default=i}),H2=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ti(),r=Xe(),n=Oa(),i=dt(),a={message:"must NOT have additional properties",params:({params:s})=>(0,r._)`{additionalProperty: ${s.additionalProperty}}`},o={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:a,code(s){let{gen:c,schema:u,parentSchema:l,data:d,errsCount:p,it:f}=s;if(!p)throw new Error("ajv implementation error");let{allErrors:g,opts:_}=f;if(f.props=!0,_.removeAdditional!=="all"&&(0,i.alwaysValidSchema)(f,u))return;let h=(0,e.allSchemaProperties)(l.properties),m=(0,e.allSchemaProperties)(l.patternProperties);y(),s.ok((0,r._)`${p} === ${n.default.errors}`);function y(){c.forIn("key",d,w=>{!h.length&&!m.length?S(w):c.if(v(w),()=>S(w))})}function v(w){let k;if(h.length>8){let O=(0,i.schemaRefOrVal)(f,l.properties,"properties");k=(0,e.isOwnProperty)(c,O,w)}else h.length?k=(0,r.or)(...h.map(O=>(0,r._)`${w} === ${O}`)):k=r.nil;return m.length&&(k=(0,r.or)(k,...m.map(O=>(0,r._)`${(0,e.usePattern)(s,O)}.test(${w})`))),(0,r.not)(k)}function b(w){c.code((0,r._)`delete ${d}[${w}]`)}function S(w){if(_.removeAdditional==="all"||_.removeAdditional&&u===!1){b(w);return}if(u===!1){s.setParams({additionalProperty:w}),s.error(),g||c.break();return}if(typeof u=="object"&&!(0,i.alwaysValidSchema)(f,u)){let k=c.name("valid");_.removeAdditional==="failing"?(x(w,k,!1),c.if((0,r.not)(k),()=>{s.reset(),b(w)})):(x(w,k),g||c.if((0,r.not)(k),()=>c.break()))}}function x(w,k,O){let A={keyword:"additionalProperties",dataProp:w,dataPropType:i.Type.Str};O===!1&&Object.assign(A,{compositeRule:!0,createErrors:!1,allErrors:!1}),s.subschema(A,k)}}};t.default=o}),Qie=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=eg(),r=ti(),n=dt(),i=H2(),a={keyword:"properties",type:"object",schemaType:"object",code(o){let{gen:s,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 m of p)d.definedProperties.add(m);d.opts.unevaluated&&p.length&&d.props!==!0&&(d.props=n.mergeEvaluated.props(s,(0,n.toHash)(p),d.props));let f=p.filter(m=>!(0,n.alwaysValidSchema)(d,c[m]));if(f.length===0)return;let g=s.name("valid");for(let m of f)_(m)?h(m):(s.if((0,r.propertyInData)(s,l,m,d.opts.ownProperties)),h(m),d.allErrors||s.else().var(g,!0),s.endIf()),o.it.definedProperties.add(m),o.ok(g);function _(m){return d.opts.useDefaults&&!d.compositeRule&&c[m].default!==void 0}function h(m){o.subschema({keyword:"properties",schemaProp:m,dataProp:m},g)}}};t.default=a}),eae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ti(),r=Xe(),n=dt(),i=dt(),a={keyword:"patternProperties",type:"object",schemaType:"object",code(o){let{gen:s,schema:c,data:u,parentSchema:l,it:d}=o,{opts:p}=d,f=(0,e.allSchemaProperties)(c),g=f.filter(S=>(0,n.alwaysValidSchema)(d,c[S]));if(f.length===0||g.length===f.length&&(!d.opts.unevaluated||d.props===!0))return;let _=p.strictSchema&&!p.allowMatchingProperties&&l.properties,h=s.name("valid");d.props!==!0&&!(d.props instanceof r.Name)&&(d.props=(0,i.evaluatedPropsToName)(s,d.props));let{props:m}=d;y();function y(){for(let S of f)_&&v(S),d.allErrors?b(S):(s.var(h,!0),b(S),s.if(h))}function v(S){for(let x in _)new RegExp(S).test(x)&&(0,n.checkStrictMode)(d,`property ${x} matches pattern ${S} (use allowMatchingProperties)`)}function b(S){s.forIn("key",u,x=>{s.if((0,r._)`${(0,e.usePattern)(o,S)}.test(${x})`,()=>{let w=g.includes(S);w||o.subschema({keyword:"patternProperties",schemaProp:S,dataProp:x,dataPropType:i.Type.Str},h),d.opts.unevaluated&&m!==!0?s.assign((0,r._)`${m}[${x}]`,!0):!w&&!d.allErrors&&s.if((0,r.not)(h),()=>s.break())})})}}};t.default=a}),tae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=dt(),r={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(n){let{gen:i,schema:a,it:o}=n;if((0,e.alwaysValidSchema)(o,a)){n.fail();return}let s=i.name("valid");n.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),n.failResult(s,()=>n.reset(),()=>n.error())},error:{message:"must NOT be valid"}};t.default=r}),rae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ti(),r={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:e.validateUnion,error:{message:"must match a schema in anyOf"}};t.default=r}),nae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),r=dt(),n={message:"must match exactly one schema in oneOf",params:({params:a})=>(0,e._)`{passingSchemas: ${a.passing}}`},i={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:n,code(a){let{gen:o,schema:s,parentSchema:c,it:u}=a;if(!Array.isArray(s))throw new Error("ajv implementation error");if(u.opts.discriminator&&c.discriminator)return;let l=s,d=o.let("valid",!1),p=o.let("passing",null),f=o.name("_valid");a.setParams({passing:p}),o.block(g),a.result(d,()=>a.reset(),()=>a.error(!0));function g(){l.forEach((_,h)=>{let m;(0,r.alwaysValidSchema)(u,_)?o.var(f,!0):m=a.subschema({keyword:"oneOf",schemaProp:h,compositeRule:!0},f),h>0&&o.if((0,e._)`${f} && ${d}`).assign(d,!1).assign(p,(0,e._)`[${p}, ${h}]`).else(),o.if(f,()=>{o.assign(d,!0),o.assign(p,h),m&&a.mergeEvaluated(m,e.Name)})})}}};t.default=i}),iae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=dt(),r={keyword:"allOf",schemaType:"array",code(n){let{gen:i,schema:a,it:o}=n;if(!Array.isArray(a))throw new Error("ajv implementation error");let s=i.name("valid");a.forEach((c,u)=>{if((0,e.alwaysValidSchema)(o,c))return;let l=n.subschema({keyword:"allOf",schemaProp:u},s);n.ok(s),n.mergeEvaluated(l)})}};t.default=r}),aae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),r=dt(),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:s,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=a(u,"then"),d=a(u,"else");if(!l&&!d)return;let p=s.let("valid",!0),f=s.name("_valid");if(g(),o.reset(),l&&d){let h=s.let("ifClause");o.setParams({ifClause:h}),s.if(f,_("then",h),_("else",h))}else l?s.if(f,_("then")):s.if((0,e.not)(f),_("else"));o.pass(p,()=>o.error(!0));function g(){let h=o.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},f);o.mergeEvaluated(h)}function _(h,m){return()=>{let y=o.subschema({keyword:h},f);s.assign(p,f),o.mergeValidEvaluated(y,p),m?s.assign(m,(0,e._)`${h}`):o.setParams({ifClause:h})}}}};function a(o,s){let c=o.schema[s];return c!==void 0&&!(0,r.alwaysValidSchema)(o,c)}t.default=i}),oae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=dt(),r={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:n,parentSchema:i,it:a}){i.if===void 0&&(0,e.checkStrictMode)(a,`"${n}" without "if" is ignored`)}};t.default=r}),sae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=F2(),r=Wie(),n=Z2(),i=Kie(),a=Jie(),o=Xie(),s=Yie(),c=H2(),u=Qie(),l=eae(),d=tae(),p=rae(),f=nae(),g=iae(),_=aae(),h=oae();function m(y=!1){let v=[d.default,p.default,f.default,g.default,_.default,h.default,s.default,c.default,o.default,u.default,l.default];return y?v.push(r.default,i.default):v.push(e.default,n.default),v.push(a.default),v}t.default=m}),cae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),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,a){let{gen:o,data:s,$data:c,schema:u,schemaCode:l,it:d}=i,{opts:p,errSchemaPath:f,schemaEnv:g,self:_}=d;if(!p.validateFormats)return;c?h():m();function h(){let y=o.scopeValue("formats",{ref:_.formats,code:p.code.formats}),v=o.const("fDef",(0,e._)`${y}[${l}]`),b=o.let("fType"),S=o.let("format");o.if((0,e._)`typeof ${v} == "object" && !(${v} instanceof RegExp)`,()=>o.assign(b,(0,e._)`${v}.type || "string"`).assign(S,(0,e._)`${v}.validate`),()=>o.assign(b,(0,e._)`"string"`).assign(S,v)),i.fail$data((0,e.or)(x(),w()));function x(){return p.strictSchema===!1?e.nil:(0,e._)`${l} && !${S}`}function w(){let k=g.$async?(0,e._)`(${v}.async ? await ${S}(${s}) : ${S}(${s}))`:(0,e._)`${S}(${s})`,O=(0,e._)`(typeof ${S} == "function" ? ${k} : ${S}.test(${s}))`;return(0,e._)`${S} && ${S} !== true && ${b} === ${a} && !${O}`}}function m(){let y=_.formats[u];if(!y){x();return}if(y===!0)return;let[v,b,S]=w(y);v===a&&i.pass(k());function x(){if(p.strictSchema===!1){_.logger.warn(O());return}throw new Error(O());function O(){return`unknown format "${u}" ignored in schema at path "${f}"`}}function w(O){let A=O instanceof RegExp?(0,e.regexpCode)(O):p.code.formats?(0,e._)`${p.code.formats}${(0,e.getProperty)(u)}`:void 0,M=o.scopeValue("formats",{key:u,ref:O,code:A});return typeof O=="object"&&!(O instanceof RegExp)?[O.type||"string",O.validate,(0,e._)`${M}.validate`]:["string",O,M]}function k(){if(typeof y=="object"&&!(y instanceof RegExp)&&y.async){if(!g.$async)throw new Error("async format in sync schema");return(0,e._)`await ${S}(${s})`}return typeof b=="function"?(0,e._)`${S}(${s})`:(0,e._)`${S}.test(${s})`}}}};t.default=n}),uae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=cae(),r=[e.default];t.default=r}),lae=V(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"]}),dae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Aie(),r=Gie(),n=sae(),i=uae(),a=lae(),o=[e.default,r.default,(0,n.default)(),i.default,a.metadataVocabulary,a.contentVocabulary];t.default=o}),pae=V(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={}))}),fae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Xe(),r=pae(),n=Z$(),i=tg(),a=dt(),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}}`},s={keyword:"discriminator",type:"object",schemaType:"object",error:o,code(c){let{gen:u,data:l,schema:d,parentSchema:p,it:f}=c,{oneOf:g}=p;if(!f.opts.discriminator)throw new Error("discriminator: requires discriminator option");let _=d.propertyName;if(typeof _!="string")throw new Error("discriminator: requires propertyName");if(d.mapping)throw new Error("discriminator: mapping is not supported");if(!g)throw new Error("discriminator: requires oneOf keyword");let h=u.let("valid",!1),m=u.const("tag",(0,e._)`${l}${(0,e.getProperty)(_)}`);u.if((0,e._)`typeof ${m} == "string"`,()=>y(),()=>c.error(!1,{discrError:r.DiscrError.Tag,tag:m,tagName:_})),c.ok(h);function y(){let S=b();u.if(!1);for(let x in S)u.elseIf((0,e._)`${m} === ${x}`),u.assign(h,v(S[x]));u.else(),c.error(!1,{discrError:r.DiscrError.Mapping,tag:m,tagName:_}),u.endIf()}function v(S){let x=u.name("valid"),w=c.subschema({keyword:"oneOf",schemaProp:S},x);return c.mergeEvaluated(w,e.Name),x}function b(){var S;let x={},w=O(p),k=!0;for(let L=0;L{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}}),hae=V((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=Cie(),n=dae(),i=fae(),a=mae(),o=["/properties"],s="http://json-schema.org/draft-07/schema";class c extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(g=>this.addVocabulary(g)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let g=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(g,s,!1),this.refs["http://json-schema.org/schema"]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var u=eg();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=Xe();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=F$();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var p=tg();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})}),gae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.formatNames=t.fastFormats=t.fullFormats=void 0;function e(M,L){return{validate:M,compare:L}}t.fullFormats={date:e(a,o),time:e(c(!0),u),"date-time":e(p(!0),f),"iso-time":e(c(),l),"iso-date-time":e(p(),g),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:m,"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:v,int32:{type:"number",validate:x},int64:{type:"number",validate:w},float:{type:"number",validate:k},double:{type:"number",validate:k},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,g),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(M){return M%4===0&&(M%100!==0||M%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 a(M){let L=n.exec(M);if(!L)return!1;let B=+L[1],U=+L[2],Y=+L[3];return U>=1&&U<=12&&Y>=1&&Y<=(U===2&&r(B)?29:i[U])}function o(M,L){if(M&&L)return M>L?1:M23||I>59||M&&!ht)return!1;if(Y<=23&&me<=59&&et<60)return!0;let D=me-I*fe,C=Y-F*fe-(D<0?1:0);return(C===23||C===-1)&&(D===59||D===-1)&&et<61}}function u(M,L){if(!(M&&L))return;let B=new Date("2020-01-01T"+M).valueOf(),U=new Date("2020-01-01T"+L).valueOf();if(B&&U)return B-U}function l(M,L){if(!(M&&L))return;let B=s.exec(M),U=s.exec(L);if(B&&U)return M=B[1]+B[2]+B[3],L=U[1]+U[2]+U[3],M>L?1:M=b}function w(M){return Number.isInteger(M)}function k(){return!0}var O=/[^\\]\\Z/;function A(M){if(O.test(M))return!1;try{return new RegExp(M),!0}catch{return!1}}}),Zh=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class e{}t._CodeOrName=e,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends e{constructor(y){if(super(),!t.IDENTIFIER.test(y))throw new Error("CodeGen: name must be a valid identifier");this.str=y}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=r;class n extends e{constructor(y){super(),this._items=typeof y=="string"?[y]:y}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let y=this._items[0];return y===""||y==='""'}get str(){var y;return(y=this._str)!==null&&y!==void 0?y:this._str=this._items.reduce((v,b)=>`${v}${b}`,"")}get names(){var y;return(y=this._names)!==null&&y!==void 0?y:this._names=this._items.reduce((v,b)=>(b instanceof r&&(v[b.str]=(v[b.str]||0)+1),v),{})}}t._Code=n,t.nil=new n("");function i(m,...y){let v=[m[0]],b=0;for(;b{Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;var e=Zh();class r extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var n;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(n||(t.UsedValueState=n={})),t.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};class i{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof e.Name?u:this.name(u)}name(u){return new e.Name(this._newName(u))}_newName(u){let l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,d;if(!((d=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||d===void 0)&&d.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}t.Scope=i;class a extends e.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:d}){this.value=u,this.scopePath=(0,e._)`.${new e.Name(l)}[${d}]`}}t.ValueScopeName=a;var o=(0,e._)`\n`;class s extends i{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?o:e.nil}}get(){return this._scope}name(u){return new a(u,this._newName(u))}value(u,l){var d;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let p=this.toName(u),{prefix:f}=p,g=(d=l.key)!==null&&d!==void 0?d:l.ref,_=this._values[f];if(_){let y=_.get(g);if(y)return y}else _=this._values[f]=new Map;_.set(g,p);let h=this._scope[f]||(this._scope[f]=[]),m=h.length;return h[m]=l.ref,p.setValue(l,{property:f,itemIndex:m}),p}getValue(u,l){let d=this._values[u];if(d)return d.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,d=>{if(d.scopePath===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return(0,e._)`${u}${d.scopePath}`})}scopeCode(u=this._values,l,d){return this._reduceValues(u,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},l,d)}_reduceValues(u,l,d={},p){let f=e.nil;for(let g in u){let _=u[g];if(!_)continue;let h=d[g]=d[g]||new Map;_.forEach(m=>{if(h.has(m))return;h.set(m,n.Started);let y=l(m);if(y){let v=this.opts.es5?t.varKinds.var:t.varKinds.const;f=(0,e._)`${f}${v} ${m} = ${y};${this.opts._n}`}else if(y=p?.(m))f=(0,e._)`${f}${y}${this.opts._n}`;else throw new r(m);h.set(m,n.Completed)})}return f}}t.ValueScope=s}),Ve=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;var e=Zh(),r=o2(),n=Zh();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return n.Name}});var i=o2();Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),t.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class a{optimizeNodes(){return this}optimizeNames($,T){return this}}class o extends a{constructor($,T,N){super(),this.varKind=$,this.name=T,this.rhs=N}render({es5:$,_n:T}){let N=$?r.varKinds.var:this.varKind,W=this.rhs===void 0?"":` = ${this.rhs}`;return`${N} ${this.name}${W};`+T}optimizeNames($,T){if($[this.name.str])return this.rhs&&(this.rhs=U(this.rhs,$,T)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class s extends a{constructor($,T,N){super(),this.lhs=$,this.rhs=T,this.sideEffects=N}render({_n:$}){return`${this.lhs} = ${this.rhs};`+$}optimizeNames($,T){if(!(this.lhs instanceof e.Name&&!$[this.lhs.str]&&!this.sideEffects))return this.rhs=U(this.rhs,$,T),this}get names(){let $=this.lhs instanceof e.Name?{}:{...this.lhs.names};return B($,this.rhs)}}class c extends s{constructor($,T,N,W){super($,N,W),this.op=T}render({_n:$}){return`${this.lhs} ${this.op}= ${this.rhs};`+$}}class u extends a{constructor($){super(),this.label=$,this.names={}}render({_n:$}){return`${this.label}:`+$}}class l extends a{constructor($){super(),this.label=$,this.names={}}render({_n:$}){return`break${this.label?` ${this.label}`:""};`+$}}class d extends a{constructor($){super(),this.error=$}render({_n:$}){return`throw ${this.error};`+$}get names(){return this.error.names}}class p extends a{constructor($){super(),this.code=$}render({_n:$}){return`${this.code};`+$}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames($,T){return this.code=U(this.code,$,T),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class f extends a{constructor($=[]){super(),this.nodes=$}render($){return this.nodes.reduce((T,N)=>T+N.render($),"")}optimizeNodes(){let{nodes:$}=this,T=$.length;for(;T--;){let N=$[T].optimizeNodes();Array.isArray(N)?$.splice(T,1,...N):N?$[T]=N:$.splice(T,1)}return $.length>0?this:void 0}optimizeNames($,T){let{nodes:N}=this,W=N.length;for(;W--;){let K=N[W];K.optimizeNames($,T)||(Y($,K.names),N.splice(W,1))}return N.length>0?this:void 0}get names(){return this.nodes.reduce(($,T)=>L($,T.names),{})}}class g extends f{render($){return"{"+$._n+super.render($)+"}"+$._n}}class _ extends f{}class h extends g{}h.kind="else";class m extends g{constructor($,T){super(T),this.condition=$}render($){let T=`if(${this.condition})`+super.render($);return this.else&&(T+="else "+this.else.render($)),T}optimizeNodes(){super.optimizeNodes();let $=this.condition;if($===!0)return this.nodes;let T=this.else;if(T){let N=T.optimizeNodes();T=this.else=Array.isArray(N)?new h(N):N}if(T)return $===!1?T instanceof m?T:T.nodes:this.nodes.length?this:new m(me($),T instanceof m?[T]:T.nodes);if(!($===!1||!this.nodes.length))return this}optimizeNames($,T){var N;if(this.else=(N=this.else)===null||N===void 0?void 0:N.optimizeNames($,T),!!(super.optimizeNames($,T)||this.else))return this.condition=U(this.condition,$,T),this}get names(){let $=super.names;return B($,this.condition),this.else&&L($,this.else.names),$}}m.kind="if";class y extends g{}y.kind="for";class v extends y{constructor($){super(),this.iteration=$}render($){return`for(${this.iteration})`+super.render($)}optimizeNames($,T){if(super.optimizeNames($,T))return this.iteration=U(this.iteration,$,T),this}get names(){return L(super.names,this.iteration.names)}}class b extends y{constructor($,T,N,W){super(),this.varKind=$,this.name=T,this.from=N,this.to=W}render($){let T=$.es5?r.varKinds.var:this.varKind,{name:N,from:W,to:K}=this;return`for(${T} ${N}=${W}; ${N}<${K}; ${N}++)`+super.render($)}get names(){let $=B(super.names,this.from);return B($,this.to)}}class S extends y{constructor($,T,N,W){super(),this.loop=$,this.varKind=T,this.name=N,this.iterable=W}render($){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render($)}optimizeNames($,T){if(super.optimizeNames($,T))return this.iterable=U(this.iterable,$,T),this}get names(){return L(super.names,this.iterable.names)}}class x extends g{constructor($,T,N){super(),this.name=$,this.args=T,this.async=N}render($){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render($)}}x.kind="func";class w extends f{render($){return"return "+super.render($)}}w.kind="return";class k extends g{render($){let T="try"+super.render($);return this.catch&&(T+=this.catch.render($)),this.finally&&(T+=this.finally.render($)),T}optimizeNodes(){var $,T;return super.optimizeNodes(),($=this.catch)===null||$===void 0||$.optimizeNodes(),(T=this.finally)===null||T===void 0||T.optimizeNodes(),this}optimizeNames($,T){var N,W;return super.optimizeNames($,T),(N=this.catch)===null||N===void 0||N.optimizeNames($,T),(W=this.finally)===null||W===void 0||W.optimizeNames($,T),this}get names(){let $=super.names;return this.catch&&L($,this.catch.names),this.finally&&L($,this.finally.names),$}}class O extends g{constructor($){super(),this.error=$}render($){return`catch(${this.error})`+super.render($)}}O.kind="catch";class A extends g{render($){return"finally"+super.render($)}}A.kind="finally";class M{constructor($,T={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...T,_n:T.lines?` `:""},this._extScope=$,this._scope=new r.Scope({parent:$}),this._nodes=[new _]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,T){let N=this._extScope.value($,T);return(this._values[N.prefix]||(this._values[N.prefix]=new Set)).add(N),N}getScopeValue($,T){return this._extScope.getValue($,T)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,T,N,W){let K=this._scope.toName(T);return N!==void 0&&W&&(this._constants[K.str]=N),this._leafNode(new o($,K,N)),K}const($,T,N){return this._def(r.varKinds.const,$,T,N)}let($,T,N){return this._def(r.varKinds.let,$,T,N)}var($,T,N){return this._def(r.varKinds.var,$,T,N)}assign($,T,N){return this._leafNode(new s($,T,N))}add($,T){return this._leafNode(new c($,t.operators.ADD,T))}code($){return typeof $=="function"?$():$!==e.nil&&this._leafNode(new p($)),this}object(...$){let T=["{"];for(let[N,W]of $)T.length>1&&T.push(","),T.push(N),(N!==W||this.opts.es5)&&(T.push(":"),(0,e.addCodeArg)(T,W));return T.push("}"),new e._Code(T)}if($,T,N){if(this._blockNode(new m($)),T&&N)this.code(T).else().code(N).endIf();else if(T)this.code(T).endIf();else if(N)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new m($))}else(){return this._elseNode(new h)}endIf(){return this._endBlockNode(m,h)}_for($,T){return this._blockNode($),T&&this.code(T).endFor(),this}for($,T){return this._for(new v($),T)}forRange($,T,N,W,K=this.opts.es5?r.varKinds.var:r.varKinds.let){let pe=this._scope.toName($);return this._for(new b(K,pe,T,N),()=>W(pe))}forOf($,T,N,W=r.varKinds.const){let K=this._scope.toName($);if(this.opts.es5){let pe=T instanceof e.Name?T:this.var("_arr",T);return this.forRange("_i",0,(0,e._)`${pe}.length`,ce=>{this.var(K,(0,e._)`${pe}[${ce}]`),N(K)})}return this._for(new S("of",W,K,T),()=>N(K))}forIn($,T,N,W=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf($,(0,e._)`Object.keys(${T})`,N);let K=this._scope.toName($);return this._for(new S("in",W,K,T),()=>N(K))}endFor(){return this._endBlockNode(y)}label($){return this._leafNode(new u($))}break($){return this._leafNode(new l($))}return($){let T=new w;if(this._blockNode(T),this.code($),T.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(w)}try($,T,N){if(!T&&!N)throw new Error('CodeGen: "try" without "catch" and "finally"');let W=new k;if(this._blockNode(W),this.code($),T){let K=this.name("e");this._currNode=W.catch=new O(K),T(K)}return N&&(this._currNode=W.finally=new A,this.code(N)),this._endBlockNode(O,A)}throw($){return this._leafNode(new d($))}block($,T){return this._blockStarts.push(this._nodes.length),$&&this.code($).endBlock(T),this}endBlock($){let T=this._blockStarts.pop();if(T===void 0)throw new Error("CodeGen: not in self-balancing block");let N=this._nodes.length-T;if(N<0||$!==void 0&&N!==$)throw new Error(`CodeGen: wrong number of nodes: ${N} vs ${$} expected`);return this._nodes.length=T,this}func($,T=e.nil,N,W){return this._blockNode(new x($,T,N)),W&&this.code(W).endFunc(),this}endFunc(){return this._endBlockNode(x)}optimize($=1){for(;$-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode($){return this._currNode.nodes.push($),this}_blockNode($){this._currNode.nodes.push($),this._nodes.push($)}_endBlockNode($,T){let N=this._currNode;if(N instanceof $||T&&N instanceof T)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${T?`${$.kind}/${T.kind}`:$.kind}"`)}_elseNode($){let T=this._currNode;if(!(T instanceof m))throw new Error('CodeGen: "else" without "if"');return this._currNode=T.else=$,this}get _root(){return this._nodes[0]}get _currNode(){let $=this._nodes;return $[$.length-1]}set _currNode($){let T=this._nodes;T[T.length-1]=$}}t.CodeGen=M;function L(C,$){for(let T in $)C[T]=(C[T]||0)+($[T]||0);return C}function B(C,$){return $ instanceof e._CodeOrName?L(C,$.names):C}function U(C,$,T){if(C instanceof e.Name)return N(C);if(!W(C))return C;return new e._Code(C._items.reduce((K,pe)=>(pe instanceof e.Name&&(pe=N(pe)),pe instanceof e._Code?K.push(...pe._items):K.push(pe),K),[]));function N(K){let pe=T[K.str];return pe===void 0||$[K.str]!==1?K:(delete $[K.str],pe)}function W(K){return K instanceof e._Code&&K._items.some(pe=>pe instanceof e.Name&&$[pe.str]===1&&T[pe.str]!==void 0)}}function Y(C,$){for(let T in $)C[T]=(C[T]||0)-($[T]||0)}function me(C){return typeof C=="boolean"||typeof C=="number"||C===null?!C:(0,e._)`!${D(C)}`}t.not=me;var et=I(t.operators.AND);function ht(...C){return C.reduce(et)}t.and=ht;var fe=I(t.operators.OR);function F(...C){return C.reduce(fe)}t.or=F;function I(C){return($,T)=>$===e.nil?T:T===e.nil?$:(0,e._)`${D($)} ${C} ${D(T)}`}function D(C){return C instanceof e.Name?C:(0,e._)`(${C})`}}),pt=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkStrictMode=t.getErrorPath=t.Type=t.useFunc=t.setEvaluated=t.evaluatedPropsToName=t.mergeEvaluated=t.eachItem=t.unescapeJsonPointer=t.escapeJsonPointer=t.escapeFragment=t.unescapeFragment=t.schemaRefOrVal=t.schemaHasRulesButRef=t.schemaHasRules=t.checkUnknownRules=t.alwaysValidSchema=t.toHash=void 0;var e=Ve(),r=Zh();function n(x){let w={};for(let k of x)w[k]=!0;return w}t.toHash=n;function i(x,w){return typeof w=="boolean"?w:Object.keys(w).length===0?!0:(a(x,w),!o(w,x.self.RULES.all))}t.alwaysValidSchema=i;function a(x,w=x.schema){let{opts:k,self:O}=x;if(!k.strictSchema||typeof w=="boolean")return;let A=O.RULES.keywords;for(let M in w)A[M]||S(x,`unknown keyword: "${M}"`)}t.checkUnknownRules=a;function o(x,w){if(typeof x=="boolean")return!x;for(let k in x)if(w[k])return!0;return!1}t.schemaHasRules=o;function s(x,w){if(typeof x=="boolean")return!x;for(let k in x)if(k!=="$ref"&&w.all[k])return!0;return!1}t.schemaHasRulesButRef=s;function c({topSchemaRef:x,schemaPath:w},k,O,A){if(!A){if(typeof k=="number"||typeof k=="boolean")return k;if(typeof k=="string")return(0,e._)`${k}`}return(0,e._)`${x}${w}${(0,e.getProperty)(O)}`}t.schemaRefOrVal=c;function u(x){return p(decodeURIComponent(x))}t.unescapeFragment=u;function l(x){return encodeURIComponent(d(x))}t.escapeFragment=l;function d(x){return typeof x=="number"?`${x}`:x.replace(/~/g,"~0").replace(/\//g,"~1")}t.escapeJsonPointer=d;function p(x){return x.replace(/~1/g,"/").replace(/~0/g,"~")}t.unescapeJsonPointer=p;function f(x,w){if(Array.isArray(x))for(let k of x)w(k);else w(x)}t.eachItem=f;function g({mergeNames:x,mergeToName:w,mergeValues:k,resultToName:O}){return(A,M,L,B)=>{let U=L===void 0?M:L instanceof e.Name?(M instanceof e.Name?x(A,M,L):w(A,M,L),L):M instanceof e.Name?(w(A,L,M),M):k(M,L);return B===e.Name&&!(U instanceof e.Name)?O(A,U):U}}t.mergeEvaluated={props:g({mergeNames:(x,w,k)=>x.if((0,e._)`${k} !== true && ${w} !== undefined`,()=>{x.if((0,e._)`${w} === true`,()=>x.assign(k,!0),()=>x.assign(k,(0,e._)`${k} || {}`).code((0,e._)`Object.assign(${k}, ${w})`))}),mergeToName:(x,w,k)=>x.if((0,e._)`${k} !== true`,()=>{w===!0?x.assign(k,!0):(x.assign(k,(0,e._)`${k} || {}`),h(x,k,w))}),mergeValues:(x,w)=>x===!0?!0:{...x,...w},resultToName:_}),items:g({mergeNames:(x,w,k)=>x.if((0,e._)`${k} !== true && ${w} !== undefined`,()=>x.assign(k,(0,e._)`${w} === true ? true : ${k} > ${w} ? ${k} : ${w}`)),mergeToName:(x,w,k)=>x.if((0,e._)`${k} !== true`,()=>x.assign(k,w===!0?!0:(0,e._)`${k} > ${w} ? ${k} : ${w}`)),mergeValues:(x,w)=>x===!0?!0:Math.max(x,w),resultToName:(x,w)=>x.var("items",w)})};function _(x,w){if(w===!0)return x.var("props",!0);let k=x.var("props",(0,e._)`{}`);return w!==void 0&&h(x,k,w),k}t.evaluatedPropsToName=_;function h(x,w,k){Object.keys(k).forEach(O=>x.assign((0,e._)`${w}${(0,e.getProperty)(O)}`,!0))}t.setEvaluated=h;var m={};function y(x,w){return x.scopeValue("func",{ref:w,code:m[w.code]||(m[w.code]=new r._Code(w.code))})}t.useFunc=y;var v;(function(x){x[x.Num=0]="Num",x[x.Str=1]="Str"})(v||(t.Type=v={}));function b(x,w,k){if(x instanceof e.Name){let O=w===v.Num;return k?O?(0,e._)`"[" + ${x} + "]"`:(0,e._)`"['" + ${x} + "']"`:O?(0,e._)`"/" + ${x}`:(0,e._)`"/" + ${x}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return k?(0,e.getProperty)(x).toString():"/"+d(x)}t.getErrorPath=b;function S(x,w,k=x.opts.strictSchema){if(k){if(w=`strict mode: ${w}`,k===!0)throw new Error(w);x.self.logger.warn(w)}}t.checkStrictMode=S}),Ra=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),r={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};t.default=r}),rg=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;var e=Ve(),r=pt(),n=Ra();t.keywordError={message:({keyword:h})=>(0,e.str)`must pass "${h}" keyword validation`},t.keyword$DataError={message:({keyword:h,schemaType:m})=>m?(0,e.str)`"${h}" keyword must be ${m} ($data)`:(0,e.str)`"${h}" keyword is invalid ($data)`};function i(h,m=t.keywordError,y,v){let{it:b}=h,{gen:S,compositeRule:x,allErrors:w}=b,k=d(h,m,y);v??(x||w)?c(S,k):u(b,(0,e._)`[${k}]`)}t.reportError=i;function a(h,m=t.keywordError,y){let{it:v}=h,{gen:b,compositeRule:S,allErrors:x}=v,w=d(h,m,y);c(b,w),S||x||u(v,n.default.vErrors)}t.reportExtraError=a;function o(h,m){h.assign(n.default.errors,m),h.if((0,e._)`${n.default.vErrors} !== null`,()=>h.if(m,()=>h.assign((0,e._)`${n.default.vErrors}.length`,m),()=>h.assign(n.default.vErrors,null)))}t.resetErrorsCount=o;function s({gen:h,keyword:m,schemaValue:y,data:v,errsCount:b,it:S}){if(b===void 0)throw new Error("ajv implementation error");let x=h.name("err");h.forRange("i",b,n.default.errors,w=>{h.const(x,(0,e._)`${n.default.vErrors}[${w}]`),h.if((0,e._)`${x}.instancePath === undefined`,()=>h.assign((0,e._)`${x}.instancePath`,(0,e.strConcat)(n.default.instancePath,S.errorPath))),h.assign((0,e._)`${x}.schemaPath`,(0,e.str)`${S.errSchemaPath}/${m}`),S.opts.verbose&&(h.assign((0,e._)`${x}.schema`,y),h.assign((0,e._)`${x}.data`,v))})}t.extendErrors=s;function c(h,m){let y=h.const("err",m);h.if((0,e._)`${n.default.vErrors} === null`,()=>h.assign(n.default.vErrors,(0,e._)`[${y}]`),(0,e._)`${n.default.vErrors}.push(${y})`),h.code((0,e._)`${n.default.errors}++`)}function u(h,m){let{gen:y,validateName:v,schemaEnv:b}=h;b.$async?y.throw((0,e._)`new ${h.ValidationError}(${m})`):(y.assign((0,e._)`${v}.errors`,m),y.return(!1))}var l={keyword:new e.Name("keyword"),schemaPath:new e.Name("schemaPath"),params:new e.Name("params"),propertyName:new e.Name("propertyName"),message:new e.Name("message"),schema:new e.Name("schema"),parentSchema:new e.Name("parentSchema")};function d(h,m,y){let{createErrors:v}=h.it;return v===!1?(0,e._)`{}`:p(h,m,y)}function p(h,m,y={}){let{gen:v,it:b}=h,S=[f(b,y),g(h,y)];return _(h,m,S),v.object(...S)}function f({errorPath:h},{instancePath:m}){let y=m?(0,e.str)`${h}${(0,r.getErrorPath)(m,r.Type.Str)}`:h;return[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,y)]}function g({keyword:h,it:{errSchemaPath:m}},{schemaPath:y,parentSchema:v}){let b=v?m:(0,e.str)`${m}/${h}`;return y&&(b=(0,e.str)`${b}${(0,r.getErrorPath)(y,r.Type.Str)}`),[l.schemaPath,b]}function _(h,{params:m,message:y},v){let{keyword:b,data:S,schemaValue:x,it:w}=h,{opts:k,propertyName:O,topSchemaRef:A,schemaPath:M}=w;v.push([l.keyword,b],[l.params,typeof m=="function"?m(h):m||(0,e._)`{}`]),k.messages&&v.push([l.message,typeof y=="function"?y(h):y]),k.verbose&&v.push([l.schema,x],[l.parentSchema,(0,e._)`${A}${M}`],[n.default.data,S]),O&&v.push([l.propertyName,O])}}),vae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.boolOrEmptySchema=t.topBoolOrEmptySchema=void 0;var e=rg(),r=Ve(),n=Ra(),i={message:"boolean schema is false"};function a(c){let{gen:u,schema:l,validateName:d}=c;l===!1?s(c,!1):typeof l=="object"&&l.$async===!0?u.return(n.default.data):(u.assign((0,r._)`${d}.errors`,null),u.return(!0))}t.topBoolOrEmptySchema=a;function o(c,u){let{gen:l,schema:d}=c;d===!1?(l.var(u,!1),s(c)):l.var(u,!0)}t.boolOrEmptySchema=o;function s(c,u){let{gen:l,data:d}=c,p={gen:l,keyword:"false schema",data:d,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:c};(0,e.reportError)(p,i,void 0,u)}}),B2=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getRules=t.isJSONType=void 0;var e=["string","number","integer","boolean","null","object","array"],r=new Set(e);function n(a){return typeof a=="string"&&r.has(a)}t.isJSONType=n;function i(){let a={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...a,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},a.number,a.string,a.array,a.object],post:{rules:[]},all:{},keywords:{}}}t.getRules=i}),V2=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shouldUseRule=t.shouldUseGroup=t.schemaHasRulesForType=void 0;function e({schema:i,self:a},o){let s=a.RULES.types[o];return s&&s!==!0&&r(i,s)}t.schemaHasRulesForType=e;function r(i,a){return a.rules.some(o=>n(i,o))}t.shouldUseGroup=r;function n(i,a){var o;return i[a.keyword]!==void 0||((o=a.definition.implements)===null||o===void 0?void 0:o.some(s=>i[s]!==void 0))}t.shouldUseRule=n}),Hh=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reportTypeError=t.checkDataTypes=t.checkDataType=t.coerceAndCheckDataType=t.getJSONTypes=t.getSchemaTypes=t.DataType=void 0;var e=B2(),r=V2(),n=rg(),i=Ve(),a=pt(),o;(function(v){v[v.Correct=0]="Correct",v[v.Wrong=1]="Wrong"})(o||(t.DataType=o={}));function s(v){let b=c(v.type);if(b.includes("null")){if(v.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!b.length&&v.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');v.nullable===!0&&b.push("null")}return b}t.getSchemaTypes=s;function c(v){let b=Array.isArray(v)?v:v?[v]:[];if(b.every(e.isJSONType))return b;throw new Error("type must be JSONType or JSONType[]: "+b.join(","))}t.getJSONTypes=c;function u(v,b){let{gen:S,data:x,opts:w}=v,k=d(b,w.coerceTypes),O=b.length>0&&!(k.length===0&&b.length===1&&(0,r.schemaHasRulesForType)(v,b[0]));if(O){let A=_(b,x,w.strictNumbers,o.Wrong);S.if(A,()=>{k.length?p(v,b,k):m(v)})}return O}t.coerceAndCheckDataType=u;var l=new Set(["string","number","integer","boolean","null"]);function d(v,b){return b?v.filter(S=>l.has(S)||b==="array"&&S==="array"):[]}function p(v,b,S){let{gen:x,data:w,opts:k}=v,O=x.let("dataType",(0,i._)`typeof ${w}`),A=x.let("coerced",(0,i._)`undefined`);k.coerceTypes==="array"&&x.if((0,i._)`${O} == 'object' && Array.isArray(${w}) && ${w}.length == 1`,()=>x.assign(w,(0,i._)`${w}[0]`).assign(O,(0,i._)`typeof ${w}`).if(_(b,w,k.strictNumbers),()=>x.assign(A,w))),x.if((0,i._)`${A} !== undefined`);for(let L of S)(l.has(L)||L==="array"&&k.coerceTypes==="array")&&M(L);x.else(),m(v),x.endIf(),x.if((0,i._)`${A} !== undefined`,()=>{x.assign(w,A),f(v,A)});function M(L){switch(L){case"string":x.elseIf((0,i._)`${O} == "number" || ${O} == "boolean"`).assign(A,(0,i._)`"" + ${w}`).elseIf((0,i._)`${w} === null`).assign(A,(0,i._)`""`);return;case"number":x.elseIf((0,i._)`${O} == "boolean" || ${w} === null || (${O} == "string" && ${w} && ${w} == +${w})`).assign(A,(0,i._)`+${w}`);return;case"integer":x.elseIf((0,i._)`${O} === "boolean" || ${w} === null || (${O} === "string" && ${w} && ${w} == +${w} && !(${w} % 1))`).assign(A,(0,i._)`+${w}`);return;case"boolean":x.elseIf((0,i._)`${w} === "false" || ${w} === 0 || ${w} === null`).assign(A,!1).elseIf((0,i._)`${w} === "true" || ${w} === 1`).assign(A,!0);return;case"null":x.elseIf((0,i._)`${w} === "" || ${w} === 0 || ${w} === false`),x.assign(A,null);return;case"array":x.elseIf((0,i._)`${O} === "string" || ${O} === "number" - || ${O} === "boolean" || ${w} === null`).assign(A,(0,i._)`[${w}]`)}}}function f({gen:v,parentData:b,parentDataProperty:S},x){v.if((0,i._)`${b} !== undefined`,()=>v.assign((0,i._)`${b}[${S}]`,x))}function g(v,b,S,x=o.Correct){let w=x===o.Correct?i.operators.EQ:i.operators.NEQ,k;switch(v){case"null":return(0,i._)`${b} ${w} null`;case"array":k=(0,i._)`Array.isArray(${b})`;break;case"object":k=(0,i._)`${b} && typeof ${b} == "object" && !Array.isArray(${b})`;break;case"integer":k=O((0,i._)`!(${b} % 1) && !isNaN(${b})`);break;case"number":k=O();break;default:return(0,i._)`typeof ${b} ${w} ${v}`}return x===o.Correct?k:(0,i.not)(k);function O(A=i.nil){return(0,i.and)((0,i._)`typeof ${b} == "number"`,A,S?(0,i._)`isFinite(${b})`:i.nil)}}t.checkDataType=g;function _(v,b,S,x){if(v.length===1)return g(v[0],b,S,x);let w,k=(0,a.toHash)(v);if(k.array&&k.object){let O=(0,i._)`typeof ${b} != "object"`;w=k.null?O:(0,i._)`!${b} || ${O}`,delete k.null,delete k.array,delete k.object}else w=i.nil;k.number&&delete k.integer;for(let O in k)w=(0,i.and)(w,g(O,b,S,x));return w}t.checkDataTypes=_;var h={message:({schema:v})=>`must be ${v}`,params:({schema:v,schemaValue:b})=>typeof v=="string"?(0,i._)`{type: ${v}}`:(0,i._)`{type: ${b}}`};function m(v){let b=y(v);(0,n.reportError)(b,h)}t.reportTypeError=m;function y(v){let{gen:b,data:S,schema:x}=v,w=(0,a.schemaRefOrVal)(v,x,"type");return{gen:b,keyword:"type",data:S,schema:x.type,schemaCode:w,schemaValue:w,parentSchema:x,params:{},it:v}}}),yae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.assignDefaults=void 0;var e=Ve(),r=pt();function n(a,o){let{properties:s,items:c}=a.schema;if(o==="object"&&s)for(let u in s)i(a,u,s[u].default);else o==="array"&&Array.isArray(c)&&c.forEach((u,l)=>i(a,l,u.default))}t.assignDefaults=n;function i(a,o,s){let{gen:c,compositeRule:u,data:l,opts:d}=a;if(s===void 0)return;let p=(0,e._)`${l}${(0,e.getProperty)(o)}`;if(u){(0,r.checkStrictMode)(a,`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)(s)}`)}}),ri=V(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=Ve(),r=pt(),n=Ra(),i=pt();function a(v,b){let{gen:S,data:x,it:w}=v;S.if(d(S,x,b,w.opts.ownProperties),()=>{v.setParams({missingProperty:(0,e._)`${b}`},!0),v.error()})}t.checkReportMissingProp=a;function o({gen:v,data:b,it:{opts:S}},x,w){return(0,e.or)(...x.map(k=>(0,e.and)(d(v,b,k,S.ownProperties),(0,e._)`${w} = ${k}`)))}t.checkMissingProp=o;function s(v,b){v.setParams({missingProperty:b},!0),v.error()}t.reportMissingProp=s;function c(v){return v.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}t.hasPropFunc=c;function u(v,b,S){return(0,e._)`${c(v)}.call(${b}, ${S})`}t.isOwnProperty=u;function l(v,b,S,x){let w=(0,e._)`${b}${(0,e.getProperty)(S)} !== undefined`;return x?(0,e._)`${w} && ${u(v,b,S)}`:w}t.propertyInData=l;function d(v,b,S,x){let w=(0,e._)`${b}${(0,e.getProperty)(S)} === undefined`;return x?(0,e.or)(w,(0,e.not)(u(v,b,S))):w}t.noPropertyInData=d;function p(v){return v?Object.keys(v).filter(b=>b!=="__proto__"):[]}t.allSchemaProperties=p;function f(v,b){return p(b).filter(S=>!(0,r.alwaysValidSchema)(v,b[S]))}t.schemaProperties=f;function g({schemaCode:v,data:b,it:{gen:S,topSchemaRef:x,schemaPath:w,errorPath:k},it:O},A,M,L){let B=L?(0,e._)`${v}, ${b}, ${x}${w}`:b,U=[[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,k)],[n.default.parentData,O.parentData],[n.default.parentDataProperty,O.parentDataProperty],[n.default.rootData,n.default.rootData]];O.opts.dynamicRef&&U.push([n.default.dynamicAnchors,n.default.dynamicAnchors]);let Y=(0,e._)`${B}, ${S.object(...U)}`;return M!==e.nil?(0,e._)`${A}.call(${M}, ${Y})`:(0,e._)`${A}(${Y})`}t.callValidateCode=g;var _=(0,e._)`new RegExp`;function h({gen:v,it:{opts:b}},S){let x=b.unicodeRegExp?"u":"",{regExp:w}=b.code,k=w(S,x);return v.scopeValue("pattern",{key:k.toString(),ref:k,code:(0,e._)`${w.code==="new RegExp"?_:(0,i.useFunc)(v,w)}(${S}, ${x})`})}t.usePattern=h;function m(v){let{gen:b,data:S,keyword:x,it:w}=v,k=b.name("valid");if(w.allErrors){let A=b.let("valid",!0);return O(()=>b.assign(A,!1)),A}return b.var(k,!0),O(()=>b.break()),k;function O(A){let M=b.const("len",(0,e._)`${S}.length`);b.forRange("i",0,M,L=>{v.subschema({keyword:x,dataProp:L,dataPropType:r.Type.Num},k),b.if((0,e.not)(k),A)})}}t.validateArray=m;function y(v){let{gen:b,schema:S,keyword:x,it:w}=v;if(!Array.isArray(S))throw new Error("ajv implementation error");if(S.some(M=>(0,r.alwaysValidSchema)(w,M))&&!w.opts.unevaluated)return;let O=b.let("valid",!1),A=b.name("_valid");b.block(()=>S.forEach((M,L)=>{let B=v.subschema({keyword:x,schemaProp:L,compositeRule:!0},A);b.assign(O,(0,e._)`${O} || ${A}`),v.mergeValidEvaluated(B,A)||b.if((0,e.not)(O))})),v.result(O,()=>v.reset(),()=>v.error(!0))}t.validateUnion=y}),_ae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateKeywordUsage=t.validSchemaType=t.funcKeywordCode=t.macroKeywordCode=void 0;var e=Ve(),r=Ra(),n=ri(),i=rg();function a(f,g){let{gen:_,keyword:h,schema:m,parentSchema:y,it:v}=f,b=g.macro.call(v.self,m,y,v),S=l(_,h,b);v.opts.validateSchema!==!1&&v.self.validateSchema(b,!0);let x=_.name("valid");f.subschema({schema:b,schemaPath:e.nil,errSchemaPath:`${v.errSchemaPath}/${h}`,topSchemaRef:S,compositeRule:!0},x),f.pass(x,()=>f.error(!0))}t.macroKeywordCode=a;function o(f,g){var _;let{gen:h,keyword:m,schema:y,parentSchema:v,$data:b,it:S}=f;u(S,g);let x=!b&&g.compile?g.compile.call(S.self,y,v,S):g.validate,w=l(h,m,x),k=h.let("valid");f.block$data(k,O),f.ok((_=g.valid)!==null&&_!==void 0?_:k);function O(){if(g.errors===!1)L(),g.modifying&&s(f),B(()=>f.error());else{let U=g.async?A():M();g.modifying&&s(f),B(()=>c(f,U))}}function A(){let U=h.let("ruleErrs",null);return h.try(()=>L((0,e._)`await `),Y=>h.assign(k,!1).if((0,e._)`${Y} instanceof ${S.ValidationError}`,()=>h.assign(U,(0,e._)`${Y}.errors`),()=>h.throw(Y))),U}function M(){let U=(0,e._)`${w}.errors`;return h.assign(U,null),L(e.nil),U}function L(U=g.async?(0,e._)`await `:e.nil){let Y=S.opts.passContext?r.default.this:r.default.self,me=!("compile"in g&&!b||g.schema===!1);h.assign(k,(0,e._)`${U}${(0,n.callValidateCode)(f,w,Y,me)}`,g.modifying)}function B(U){var Y;h.if((0,e.not)((Y=g.valid)!==null&&Y!==void 0?Y:k),U)}}t.funcKeywordCode=o;function s(f){let{gen:g,data:_,it:h}=f;g.if(h.parentData,()=>g.assign(_,(0,e._)`${h.parentData}[${h.parentDataProperty}]`))}function c(f,g){let{gen:_}=f;_.if((0,e._)`Array.isArray(${g})`,()=>{_.assign(r.default.vErrors,(0,e._)`${r.default.vErrors} === null ? ${g} : ${r.default.vErrors}.concat(${g})`).assign(r.default.errors,(0,e._)`${r.default.vErrors}.length`),(0,i.extendErrors)(f)},()=>f.error())}function u({schemaEnv:f},g){if(g.async&&!f.$async)throw new Error("async keyword in sync schema")}function l(f,g,_){if(_===void 0)throw new Error(`keyword "${g}" failed to compile`);return f.scopeValue("keyword",typeof _=="function"?{ref:_}:{ref:_,code:(0,e.stringify)(_)})}function d(f,g,_=!1){return!g.length||g.some(h=>h==="array"?Array.isArray(f):h==="object"?f&&typeof f=="object"&&!Array.isArray(f):typeof f==h||_&&typeof f>"u")}t.validSchemaType=d;function p({schema:f,opts:g,self:_,errSchemaPath:h},m,y){if(Array.isArray(m.keyword)?!m.keyword.includes(y):m.keyword!==y)throw new Error("ajv implementation error");let v=m.dependencies;if(v?.some(b=>!Object.prototype.hasOwnProperty.call(f,b)))throw new Error(`parent schema must have dependencies of ${y}: ${v.join(",")}`);if(m.validateSchema&&!m.validateSchema(f[y])){let S=`keyword "${y}" value is invalid at path "${h}": `+_.errorsText(m.validateSchema.errors);if(g.validateSchema==="log")_.logger.error(S);else throw new Error(S)}}t.validateKeywordUsage=p}),bae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extendSubschemaMode=t.extendSubschemaData=t.getSubschema=void 0;var e=Ve(),r=pt();function n(o,{keyword:s,schemaProp:c,schema:u,schemaPath:l,errSchemaPath:d,topSchemaRef:p}){if(s!==void 0&&u!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(s!==void 0){let f=o.schema[s];return c===void 0?{schema:f,schemaPath:(0,e._)`${o.schemaPath}${(0,e.getProperty)(s)}`,errSchemaPath:`${o.errSchemaPath}/${s}`}:{schema:f[c],schemaPath:(0,e._)`${o.schemaPath}${(0,e.getProperty)(s)}${(0,e.getProperty)(c)}`,errSchemaPath:`${o.errSchemaPath}/${s}/${(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,s,{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}=s;if(c!==void 0){let{errorPath:_,dataPathArr:h,opts:m}=s,y=f.let("data",(0,e._)`${s.data}${(0,e.getProperty)(c)}`,!0);g(y),o.errorPath=(0,e.str)`${_}${(0,r.getErrorPath)(c,u,m.jsPropertySyntax)}`,o.parentDataProperty=(0,e._)`${c}`,o.dataPathArr=[...h,o.parentDataProperty]}if(l!==void 0){let _=l instanceof e.Name?l:f.let("data",l,!0);g(_),p!==void 0&&(o.propertyName=p)}d&&(o.dataTypes=d);function g(_){o.data=_,o.dataLevel=s.dataLevel+1,o.dataTypes=[],s.definedProperties=new Set,o.parentData=s.data,o.dataNames=[...s.dataNames,_]}}t.extendSubschemaData=i;function a(o,{jtdDiscriminator:s,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=s,o.jtdMetadata=c}t.extendSubschemaMode=a}),xae=V((t,e)=>{var r=e.exports=function(a,o,s){typeof o=="function"&&(s=o,o={}),s=o.cb||s;var c=typeof s=="function"?s:s.pre||function(){},u=s.post||function(){};n(o,c,u,a,"",a)};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(a,o,s,c,u,l,d,p,f,g){if(c&&typeof c=="object"&&!Array.isArray(c)){o(c,u,l,d,p,f,g);for(var _ in c){var h=c[_];if(Array.isArray(h)){if(_ in r.arrayKeywords)for(var m=0;m{Object.defineProperty(t,"__esModule",{value:!0}),t.getSchemaRefs=t.resolveUrl=t.normalizeId=t._getFullPath=t.getFullPath=t.inlineRef=void 0;var e=pt(),r=Yh(),n=xae(),i=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function a(h,m=!0){return typeof h=="boolean"?!0:m===!0?!s(h):m?c(h)<=m:!1}t.inlineRef=a;var o=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function s(h){for(let m in h){if(o.has(m))return!0;let y=h[m];if(Array.isArray(y)&&y.some(s)||typeof y=="object"&&s(y))return!0}return!1}function c(h){let m=0;for(let y in h){if(y==="$ref")return 1/0;if(m++,!i.has(y)&&(typeof h[y]=="object"&&(0,e.eachItem)(h[y],v=>m+=c(v)),m===1/0))return 1/0}return m}function u(h,m="",y){y!==!1&&(m=p(m));let v=h.parse(m);return l(h,v)}t.getFullPath=u;function l(h,m){return h.serialize(m).split("#")[0]+"#"}t._getFullPath=l;var d=/#\/?$/;function p(h){return h?h.replace(d,""):""}t.normalizeId=p;function f(h,m,y){return y=p(y),h.resolve(m,y)}t.resolveUrl=f;var g=/^[a-z_][-a-z0-9._]*$/i;function _(h,m){if(typeof h=="boolean")return{};let{schemaId:y,uriResolver:v}=this.opts,b=p(h[y]||m),S={"":b},x=u(v,b,!1),w={},k=new Set;return n(h,{allKeys:!0},(M,L,B,U)=>{if(U===void 0)return;let Y=x+L,me=S[U];typeof M[y]=="string"&&(me=et.call(this,M[y])),ht.call(this,M.$anchor),ht.call(this,M.$dynamicAnchor),S[L]=me;function et(fe){let F=this.opts.uriResolver.resolve;if(fe=p(me?F(me,fe):fe),k.has(fe))throw A(fe);k.add(fe);let I=this.refs[fe];return typeof I=="string"&&(I=this.refs[I]),typeof I=="object"?O(M,I.schema,fe):fe!==p(Y)&&(fe[0]==="#"?(O(M,w[fe],fe),w[fe]=M):this.refs[fe]=Y),fe}function ht(fe){if(typeof fe=="string"){if(!g.test(fe))throw new Error(`invalid anchor "${fe}"`);et.call(this,`#${fe}`)}}}),w;function O(M,L,B){if(L!==void 0&&!r(M,L))throw A(B)}function A(M){return new Error(`reference "${M}" resolves to more than one schema`)}}t.getSchemaRefs=_}),ig=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getData=t.KeywordCxt=t.validateFunctionCode=void 0;var e=vae(),r=Hh(),n=V2(),i=Hh(),a=yae(),o=_ae(),s=bae(),c=Ve(),u=Ra(),l=ng(),d=pt(),p=rg();function f(P){if(x(P)&&(k(P),S(P))){m(P);return}g(P,()=>(0,e.topBoolOrEmptySchema)(P))}t.validateFunctionCode=f;function g({gen:P,validateName:R,schema:z,schemaEnv:Z,opts:J},ie){J.code.es5?P.func(R,(0,c._)`${u.default.data}, ${u.default.valCxt}`,Z.$async,()=>{P.code((0,c._)`"use strict"; ${v(z,J)}`),h(P,J),P.code(ie)}):P.func(R,(0,c._)`${u.default.data}, ${_(J)}`,Z.$async,()=>P.code(v(z,J)).code(ie))}function _(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 h(P,R){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}`),R.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),R.dynamicRef&&P.var(u.default.dynamicAnchors,(0,c._)`{}`)})}function m(P){let{schema:R,opts:z,gen:Z}=P;g(P,()=>{z.$comment&&R.$comment&&U(P),M(P),Z.let(u.default.vErrors,null),Z.let(u.default.errors,0),z.unevaluated&&y(P),O(P),Y(P)})}function y(P){let{gen:R,validateName:z}=P;P.evaluated=R.const("evaluated",(0,c._)`${z}.evaluated`),R.if((0,c._)`${P.evaluated}.dynamicProps`,()=>R.assign((0,c._)`${P.evaluated}.props`,(0,c._)`undefined`)),R.if((0,c._)`${P.evaluated}.dynamicItems`,()=>R.assign((0,c._)`${P.evaluated}.items`,(0,c._)`undefined`))}function v(P,R){let z=typeof P=="object"&&P[R.schemaId];return z&&(R.code.source||R.code.process)?(0,c._)`/*# sourceURL=${z} */`:c.nil}function b(P,R){if(x(P)&&(k(P),S(P))){w(P,R);return}(0,e.boolOrEmptySchema)(P,R)}function S({schema:P,self:R}){if(typeof P=="boolean")return!P;for(let z in P)if(R.RULES.all[z])return!0;return!1}function x(P){return typeof P.schema!="boolean"}function w(P,R){let{schema:z,gen:Z,opts:J}=P;J.$comment&&z.$comment&&U(P),L(P),B(P);let ie=Z.const("_errs",u.default.errors);O(P,ie),Z.var(R,(0,c._)`${ie} === ${u.default.errors}`)}function k(P){(0,d.checkUnknownRules)(P),A(P)}function O(P,R){if(P.opts.jtd)return et(P,[],!1,R);let z=(0,r.getSchemaTypes)(P.schema),Z=(0,r.coerceAndCheckDataType)(P,z);et(P,z,!Z,R)}function A(P){let{schema:R,errSchemaPath:z,opts:Z,self:J}=P;R.$ref&&Z.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(R,J.RULES)&&J.logger.warn(`$ref: keywords ignored in schema at path "${z}"`)}function M(P){let{schema:R,opts:z}=P;R.default!==void 0&&z.useDefaults&&z.strictSchema&&(0,d.checkStrictMode)(P,"default is ignored in the schema root")}function L(P){let R=P.schema[P.opts.schemaId];R&&(P.baseId=(0,l.resolveUrl)(P.opts.uriResolver,P.baseId,R))}function B(P){if(P.schema.$async&&!P.schemaEnv.$async)throw new Error("async schema in sync schema")}function U({gen:P,schemaEnv:R,schema:z,errSchemaPath:Z,opts:J}){let ie=z.$comment;if(J.$comment===!0)P.code((0,c._)`${u.default.self}.logger.log(${ie})`);else if(typeof J.$comment=="function"){let tt=(0,c.str)`${Z}/$comment`,Ht=P.scopeValue("root",{ref:R.root});P.code((0,c._)`${u.default.self}.opts.$comment(${ie}, ${tt}, ${Ht}.schema)`)}}function Y(P){let{gen:R,schemaEnv:z,validateName:Z,ValidationError:J,opts:ie}=P;z.$async?R.if((0,c._)`${u.default.errors} === 0`,()=>R.return(u.default.data),()=>R.throw((0,c._)`new ${J}(${u.default.vErrors})`)):(R.assign((0,c._)`${Z}.errors`,u.default.vErrors),ie.unevaluated&&me(P),R.return((0,c._)`${u.default.errors} === 0`))}function me({gen:P,evaluated:R,props:z,items:Z}){z instanceof c.Name&&P.assign((0,c._)`${R}.props`,z),Z instanceof c.Name&&P.assign((0,c._)`${R}.items`,Z)}function et(P,R,z,Z){let{gen:J,schema:ie,data:tt,allErrors:Ht,opts:yt,self:_t}=P,{RULES:rt}=_t;if(ie.$ref&&(yt.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(ie,rt))){J.block(()=>K(P,"$ref",rt.all.$ref.definition));return}yt.jtd||fe(P,R),J.block(()=>{for(let jt of rt.rules)tn(jt);tn(rt.post)});function tn(jt){(0,n.shouldUseGroup)(ie,jt)&&(jt.type?(J.if((0,i.checkDataType)(jt.type,tt,yt.strictNumbers)),ht(P,jt),R.length===1&&R[0]===jt.type&&z&&(J.else(),(0,i.reportTypeError)(P)),J.endIf()):ht(P,jt),Ht||J.if((0,c._)`${u.default.errors} === ${Z||0}`))}}function ht(P,R){let{gen:z,schema:Z,opts:{useDefaults:J}}=P;J&&(0,a.assignDefaults)(P,R.type),z.block(()=>{for(let ie of R.rules)(0,n.shouldUseRule)(Z,ie)&&K(P,ie.keyword,ie.definition,R.type)})}function fe(P,R){P.schemaEnv.meta||!P.opts.strictTypes||(F(P,R),P.opts.allowUnionTypes||I(P,R),D(P,P.dataTypes))}function F(P,R){if(R.length){if(!P.dataTypes.length){P.dataTypes=R;return}R.forEach(z=>{$(P.dataTypes,z)||N(P,`type "${z}" not allowed by context "${P.dataTypes.join(",")}"`)}),T(P,R)}}function I(P,R){R.length>1&&!(R.length===2&&R.includes("null"))&&N(P,"use allowUnionTypes to allow union type keyword")}function D(P,R){let z=P.self.RULES.all;for(let Z in z){let J=z[Z];if(typeof J=="object"&&(0,n.shouldUseRule)(P.schema,J)){let{type:ie}=J.definition;ie.length&&!ie.some(tt=>C(R,tt))&&N(P,`missing type "${ie.join(",")}" for keyword "${Z}"`)}}}function C(P,R){return P.includes(R)||R==="number"&&P.includes("integer")}function $(P,R){return P.includes(R)||R==="integer"&&P.includes("number")}function T(P,R){let z=[];for(let Z of P.dataTypes)$(R,Z)?z.push(Z):R.includes("integer")&&Z==="number"&&z.push("integer");P.dataTypes=z}function N(P,R){let z=P.schemaEnv.baseId+P.errSchemaPath;R+=` at "${z}" (strictTypes)`,(0,d.checkStrictMode)(P,R,P.opts.strictTypes)}class W{constructor(R,z,Z){if((0,o.validateKeywordUsage)(R,z,Z),this.gen=R.gen,this.allErrors=R.allErrors,this.keyword=Z,this.data=R.data,this.schema=R.schema[Z],this.$data=z.$data&&R.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(R,this.schema,Z,this.$data),this.schemaType=z.schemaType,this.parentSchema=R.schema,this.params={},this.it=R,this.def=z,this.$data)this.schemaCode=R.gen.const("vSchema",je(this.$data,R));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,z.schemaType,z.allowUndefined))throw new Error(`${Z} value must be ${JSON.stringify(z.schemaType)}`);("code"in z?z.trackErrors:z.errors!==!1)&&(this.errsCount=R.gen.const("_errs",u.default.errors))}result(R,z,Z){this.failResult((0,c.not)(R),z,Z)}failResult(R,z,Z){this.gen.if(R),Z?Z():this.error(),z?(this.gen.else(),z(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(R,z){this.failResult((0,c.not)(R),void 0,z)}fail(R){if(R===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(R),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(R){if(!this.$data)return this.fail(R);let{schemaCode:z}=this;this.fail((0,c._)`${z} !== undefined && (${(0,c.or)(this.invalid$data(),R)})`)}error(R,z,Z){if(z){this.setParams(z),this._error(R,Z),this.setParams({});return}this._error(R,Z)}_error(R,z){(R?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(R){this.allErrors||this.gen.if(R)}setParams(R,z){z?Object.assign(this.params,R):this.params=R}block$data(R,z,Z=c.nil){this.gen.block(()=>{this.check$data(R,Z),z()})}check$data(R=c.nil,z=c.nil){if(!this.$data)return;let{gen:Z,schemaCode:J,schemaType:ie,def:tt}=this;Z.if((0,c.or)((0,c._)`${J} === undefined`,z)),R!==c.nil&&Z.assign(R,!0),(ie.length||tt.validateSchema)&&(Z.elseIf(this.invalid$data()),this.$dataError(),R!==c.nil&&Z.assign(R,!1)),Z.else()}invalid$data(){let{gen:R,schemaCode:z,schemaType:Z,def:J,it:ie}=this;return(0,c.or)(tt(),Ht());function tt(){if(Z.length){if(!(z instanceof c.Name))throw new Error("ajv implementation error");let yt=Array.isArray(Z)?Z:[Z];return(0,c._)`${(0,i.checkDataTypes)(yt,z,ie.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function Ht(){if(J.validateSchema){let yt=R.scopeValue("validate$data",{ref:J.validateSchema});return(0,c._)`!${yt}(${z})`}return c.nil}}subschema(R,z){let Z=(0,s.getSubschema)(this.it,R);(0,s.extendSubschemaData)(Z,this.it,R),(0,s.extendSubschemaMode)(Z,R);let J={...this.it,...Z,items:void 0,props:void 0};return b(J,z),J}mergeEvaluated(R,z){let{it:Z,gen:J}=this;Z.opts.unevaluated&&(Z.props!==!0&&R.props!==void 0&&(Z.props=d.mergeEvaluated.props(J,R.props,Z.props,z)),Z.items!==!0&&R.items!==void 0&&(Z.items=d.mergeEvaluated.items(J,R.items,Z.items,z)))}mergeValidEvaluated(R,z){let{it:Z,gen:J}=this;if(Z.opts.unevaluated&&(Z.props!==!0||Z.items!==!0))return J.if(z,()=>this.mergeEvaluated(R,c.Name)),!0}}t.KeywordCxt=W;function K(P,R,z,Z){let J=new W(P,z,R);"code"in z?z.code(J,Z):J.$data&&z.validate?(0,o.funcKeywordCode)(J,z):"macro"in z?(0,o.macroKeywordCode)(J,z):(z.compile||z.validate)&&(0,o.funcKeywordCode)(J,z)}var pe=/^\/(?:[^~]|~0|~1)*$/,ce=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function je(P,{dataLevel:R,dataNames:z,dataPathArr:Z}){let J,ie;if(P==="")return u.default.rootData;if(P[0]==="/"){if(!pe.test(P))throw new Error(`Invalid JSON-pointer: ${P}`);J=P,ie=u.default.rootData}else{let _t=ce.exec(P);if(!_t)throw new Error(`Invalid JSON-pointer: ${P}`);let rt=+_t[1];if(J=_t[2],J==="#"){if(rt>=R)throw new Error(yt("property/index",rt));return Z[R-rt]}if(rt>R)throw new Error(yt("data",rt));if(ie=z[R-rt],!J)return ie}let tt=ie,Ht=J.split("/");for(let _t of Ht)_t&&(ie=(0,c._)`${ie}${(0,c.getProperty)((0,d.unescapeJsonPointer)(_t))}`,tt=(0,c._)`${tt} && ${ie}`);return tt;function yt(_t,rt){return`Cannot access ${_t} ${rt} levels up, current level is ${R}`}}t.getData=je}),B$=V(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}),ag=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ng();class r extends Error{constructor(i,a,o,s){super(s||`can't resolve reference ${o} from id ${a}`),this.missingRef=(0,e.resolveUrl)(i,a,o),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(i,this.missingRef))}}t.default=r}),V$=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resolveSchema=t.getCompilingSchema=t.resolveRef=t.compileSchema=t.SchemaEnv=void 0;var e=Ve(),r=B$(),n=Ra(),i=ng(),a=pt(),o=ig();class s{constructor(y){var v;this.refs={},this.dynamicAnchors={};let b;typeof y.schema=="object"&&(b=y.schema),this.schema=y.schema,this.schemaId=y.schemaId,this.root=y.root||this,this.baseId=(v=y.baseId)!==null&&v!==void 0?v:(0,i.normalizeId)(b?.[y.schemaId||"$id"]),this.schemaPath=y.schemaPath,this.localRefs=y.localRefs,this.meta=y.meta,this.$async=b?.$async,this.refs={}}}t.SchemaEnv=s;function c(m){let y=d.call(this,m);if(y)return y;let v=(0,i.getFullPath)(this.opts.uriResolver,m.root.baseId),{es5:b,lines:S}=this.opts.code,{ownProperties:x}=this.opts,w=new e.CodeGen(this.scope,{es5:b,lines:S,ownProperties:x}),k;m.$async&&(k=w.scopeValue("Error",{ref:r.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));let O=w.scopeName("validate");m.validateName=O;let A={gen:w,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:w.scopeValue("schema",this.opts.code.source===!0?{ref:m.schema,code:(0,e.stringify)(m.schema)}:{ref:m.schema}),validateName:O,ValidationError:k,schema:m.schema,schemaEnv:m,rootId:v,baseId:m.baseId||v,schemaPath:e.nil,errSchemaPath:m.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this},M;try{this._compilations.add(m),(0,o.validateFunctionCode)(A),w.optimize(this.opts.code.optimize);let L=w.toString();M=`${w.scopeRefs(n.default.scope)}return ${L}`,this.opts.code.process&&(M=this.opts.code.process(M,m));let U=new Function(`${n.default.self}`,`${n.default.scope}`,M)(this,this.scope.get());if(this.scope.value(O,{ref:U}),U.errors=null,U.schema=m.schema,U.schemaEnv=m,m.$async&&(U.$async=!0),this.opts.code.source===!0&&(U.source={validateName:O,validateCode:L,scopeValues:w._values}),this.opts.unevaluated){let{props:Y,items:me}=A;U.evaluated={props:Y instanceof e.Name?void 0:Y,items:me instanceof e.Name?void 0:me,dynamicProps:Y instanceof e.Name,dynamicItems:me instanceof e.Name},U.source&&(U.source.evaluated=(0,e.stringify)(U.evaluated))}return m.validate=U,m}catch(L){throw delete m.validate,delete m.validateName,M&&this.logger.error("Error compiling schema, function code:",M),L}finally{this._compilations.delete(m)}}t.compileSchema=c;function u(m,y,v){var b;v=(0,i.resolveUrl)(this.opts.uriResolver,y,v);let S=m.refs[v];if(S)return S;let x=f.call(this,m,v);if(x===void 0){let w=(b=m.localRefs)===null||b===void 0?void 0:b[v],{schemaId:k}=this.opts;w&&(x=new s({schema:w,schemaId:k,root:m,baseId:y}))}if(x!==void 0)return m.refs[v]=l.call(this,x)}t.resolveRef=u;function l(m){return(0,i.inlineRef)(m.schema,this.opts.inlineRefs)?m.schema:m.validate?m:c.call(this,m)}function d(m){for(let y of this._compilations)if(p(y,m))return y}t.getCompilingSchema=d;function p(m,y){return m.schema===y.schema&&m.root===y.root&&m.baseId===y.baseId}function f(m,y){let v;for(;typeof(v=this.refs[y])=="string";)y=v;return v||this.schemas[y]||g.call(this,m,y)}function g(m,y){let v=this.opts.uriResolver.parse(y),b=(0,i._getFullPath)(this.opts.uriResolver,v),S=(0,i.getFullPath)(this.opts.uriResolver,m.baseId,void 0);if(Object.keys(m.schema).length>0&&b===S)return h.call(this,v,m);let x=(0,i.normalizeId)(b),w=this.refs[x]||this.schemas[x];if(typeof w=="string"){let k=g.call(this,m,w);return typeof k?.schema!="object"?void 0:h.call(this,v,k)}if(typeof w?.schema=="object"){if(w.validate||c.call(this,w),x===(0,i.normalizeId)(y)){let{schema:k}=w,{schemaId:O}=this.opts,A=k[O];return A&&(S=(0,i.resolveUrl)(this.opts.uriResolver,S,A)),new s({schema:k,schemaId:O,root:m,baseId:S})}return h.call(this,v,w)}}t.resolveSchema=g;var _=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function h(m,{baseId:y,schema:v,root:b}){var S;if(((S=m.fragment)===null||S===void 0?void 0:S[0])!=="/")return;for(let k of m.fragment.slice(1).split("/")){if(typeof v=="boolean")return;let O=v[(0,a.unescapeFragment)(k)];if(O===void 0)return;v=O;let A=typeof v=="object"&&v[this.opts.schemaId];!_.has(k)&&A&&(y=(0,i.resolveUrl)(this.opts.uriResolver,y,A))}let x;if(typeof v!="boolean"&&v.$ref&&!(0,a.schemaHasRulesButRef)(v,this.RULES)){let k=(0,i.resolveUrl)(this.opts.uriResolver,y,v.$ref);x=g.call(this,b,k)}let{schemaId:w}=this.opts;if(x=x||new s({schema:v,schemaId:w,root:b,baseId:y}),x.schema!==x.root.schema)return x}}),Sae=V((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}}),wae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=q2();e.code='require("ajv/dist/runtime/uri").default',t.default=e}),$ae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var e=ig();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var r=Ve();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=B$(),i=ag(),a=B2(),o=V$(),s=Ve(),c=ng(),u=Hh(),l=pt(),d=Sae(),p=wae(),f=(F,I)=>new RegExp(F,I);f.code="new RegExp";var g=["removeAdditional","useDefaults","coerceTypes"],_=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),h={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."},m={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},y=200;function v(F){var I,D,C,$,T,N,W,K,pe,ce,je,P,R,z,Z,J,ie,tt,Ht,yt,_t,rt,tn,jt,Na;let An=F.strict,ja=(I=F.code)===null||I===void 0?void 0:I.optimize,Ac=ja===!0||ja===void 0?1:ja||0,Mc=(C=(D=F.code)===null||D===void 0?void 0:D.regExp)!==null&&C!==void 0?C:f,Gg=($=F.uriResolver)!==null&&$!==void 0?$:p.default;return{strictSchema:(N=(T=F.strictSchema)!==null&&T!==void 0?T:An)!==null&&N!==void 0?N:!0,strictNumbers:(K=(W=F.strictNumbers)!==null&&W!==void 0?W:An)!==null&&K!==void 0?K:!0,strictTypes:(ce=(pe=F.strictTypes)!==null&&pe!==void 0?pe:An)!==null&&ce!==void 0?ce:"log",strictTuples:(P=(je=F.strictTuples)!==null&&je!==void 0?je:An)!==null&&P!==void 0?P:"log",strictRequired:(z=(R=F.strictRequired)!==null&&R!==void 0?R:An)!==null&&z!==void 0?z:!1,code:F.code?{...F.code,optimize:Ac,regExp:Mc}:{optimize:Ac,regExp:Mc},loopRequired:(Z=F.loopRequired)!==null&&Z!==void 0?Z:y,loopEnum:(J=F.loopEnum)!==null&&J!==void 0?J:y,meta:(ie=F.meta)!==null&&ie!==void 0?ie:!0,messages:(tt=F.messages)!==null&&tt!==void 0?tt:!0,inlineRefs:(Ht=F.inlineRefs)!==null&&Ht!==void 0?Ht:!0,schemaId:(yt=F.schemaId)!==null&&yt!==void 0?yt:"$id",addUsedSchema:(_t=F.addUsedSchema)!==null&&_t!==void 0?_t:!0,validateSchema:(rt=F.validateSchema)!==null&&rt!==void 0?rt:!0,validateFormats:(tn=F.validateFormats)!==null&&tn!==void 0?tn:!0,unicodeRegExp:(jt=F.unicodeRegExp)!==null&&jt!==void 0?jt:!0,int32range:(Na=F.int32range)!==null&&Na!==void 0?Na:!0,uriResolver:Gg}}class b{constructor(I={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,I=this.opts={...I,...v(I)};let{es5:D,lines:C}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:_,es5:D,lines:C}),this.logger=L(I.logger);let $=I.validateFormats;I.validateFormats=!1,this.RULES=(0,a.getRules)(),S.call(this,h,I,"NOT SUPPORTED"),S.call(this,m,I,"DEPRECATED","warn"),this._metaOpts=A.call(this),I.formats&&k.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),I.keywords&&O.call(this,I.keywords),typeof I.meta=="object"&&this.addMetaSchema(I.meta),w.call(this),I.validateFormats=$}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:I,meta:D,schemaId:C}=this.opts,$=d;C==="id"&&($={...d},$.id=$.$id,delete $.$id),D&&I&&this.addMetaSchema($,$[C],!1)}defaultMeta(){let{meta:I,schemaId:D}=this.opts;return this.opts.defaultMeta=typeof I=="object"?I[D]||I:void 0}validate(I,D){let C;if(typeof I=="string"){if(C=this.getSchema(I),!C)throw new Error(`no schema with key or ref "${I}"`)}else C=this.compile(I);let $=C(D);return"$async"in C||(this.errors=C.errors),$}compile(I,D){let C=this._addSchema(I,D);return C.validate||this._compileSchemaEnv(C)}compileAsync(I,D){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:C}=this.opts;return $.call(this,I,D);async function $(ce,je){await T.call(this,ce.$schema);let P=this._addSchema(ce,je);return P.validate||N.call(this,P)}async function T(ce){ce&&!this.getSchema(ce)&&await $.call(this,{$ref:ce},!0)}async function N(ce){try{return this._compileSchemaEnv(ce)}catch(je){if(!(je instanceof i.default))throw je;return W.call(this,je),await K.call(this,je.missingSchema),N.call(this,ce)}}function W({missingSchema:ce,missingRef:je}){if(this.refs[ce])throw new Error(`AnySchema ${ce} is loaded but ${je} cannot be resolved`)}async function K(ce){let je=await pe.call(this,ce);this.refs[ce]||await T.call(this,je.$schema),this.refs[ce]||this.addSchema(je,ce,D)}async function pe(ce){let je=this._loading[ce];if(je)return je;try{return await(this._loading[ce]=C(ce))}finally{delete this._loading[ce]}}}addSchema(I,D,C,$=this.opts.validateSchema){if(Array.isArray(I)){for(let N of I)this.addSchema(N,void 0,C,$);return this}let T;if(typeof I=="object"){let{schemaId:N}=this.opts;if(T=I[N],T!==void 0&&typeof T!="string")throw new Error(`schema ${N} must be string`)}return D=(0,c.normalizeId)(D||T),this._checkUnique(D),this.schemas[D]=this._addSchema(I,C,D,$,!0),this}addMetaSchema(I,D,C=this.opts.validateSchema){return this.addSchema(I,D,!0,C),this}validateSchema(I,D){if(typeof I=="boolean")return!0;let C;if(C=I.$schema,C!==void 0&&typeof C!="string")throw new Error("$schema must be a string");if(C=C||this.opts.defaultMeta||this.defaultMeta(),!C)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let $=this.validate(C,I);if(!$&&D){let T="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(T);else throw new Error(T)}return $}getSchema(I){let D;for(;typeof(D=x.call(this,I))=="string";)I=D;if(D===void 0){let{schemaId:C}=this.opts,$=new o.SchemaEnv({schema:{},schemaId:C});if(D=o.resolveSchema.call(this,$,I),!D)return;this.refs[I]=D}return D.validate||this._compileSchemaEnv(D)}removeSchema(I){if(I instanceof RegExp)return this._removeAllSchemas(this.schemas,I),this._removeAllSchemas(this.refs,I),this;switch(typeof I){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let D=x.call(this,I);return typeof D=="object"&&this._cache.delete(D.schema),delete this.schemas[I],delete this.refs[I],this}case"object":{let D=I;this._cache.delete(D);let C=I[this.opts.schemaId];return C&&(C=(0,c.normalizeId)(C),delete this.schemas[C],delete this.refs[C]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(I){for(let D of I)this.addKeyword(D);return this}addKeyword(I,D){let C;if(typeof I=="string")C=I,typeof D=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),D.keyword=C);else if(typeof I=="object"&&D===void 0){if(D=I,C=D.keyword,Array.isArray(C)&&!C.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(U.call(this,C,D),!D)return(0,l.eachItem)(C,T=>Y.call(this,T)),this;et.call(this,D);let $={...D,type:(0,u.getJSONTypes)(D.type),schemaType:(0,u.getJSONTypes)(D.schemaType)};return(0,l.eachItem)(C,$.type.length===0?T=>Y.call(this,T,$):T=>$.type.forEach(N=>Y.call(this,T,$,N))),this}getKeyword(I){let D=this.RULES.all[I];return typeof D=="object"?D.definition:!!D}removeKeyword(I){let{RULES:D}=this;delete D.keywords[I],delete D.all[I];for(let C of D.rules){let $=C.rules.findIndex(T=>T.keyword===I);$>=0&&C.rules.splice($,1)}return this}addFormat(I,D){return typeof D=="string"&&(D=new RegExp(D)),this.formats[I]=D,this}errorsText(I=this.errors,{separator:D=", ",dataVar:C="data"}={}){return!I||I.length===0?"No errors":I.map($=>`${C}${$.instancePath} ${$.message}`).reduce(($,T)=>$+D+T)}$dataMetaSchema(I,D){let C=this.RULES.all;I=JSON.parse(JSON.stringify(I));for(let $ of D){let T=$.split("/").slice(1),N=I;for(let W of T)N=N[W];for(let W in C){let K=C[W];if(typeof K!="object")continue;let{$data:pe}=K.definition,ce=N[W];pe&&ce&&(N[W]=fe(ce))}}return I}_removeAllSchemas(I,D){for(let C in I){let $=I[C];(!D||D.test(C))&&(typeof $=="string"?delete I[C]:$&&!$.meta&&(this._cache.delete($.schema),delete I[C]))}}_addSchema(I,D,C,$=this.opts.validateSchema,T=this.opts.addUsedSchema){let N,{schemaId:W}=this.opts;if(typeof I=="object")N=I[W];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof I!="boolean")throw new Error("schema must be object or boolean")}let K=this._cache.get(I);if(K!==void 0)return K;C=(0,c.normalizeId)(N||C);let pe=c.getSchemaRefs.call(this,I,C);return K=new o.SchemaEnv({schema:I,schemaId:W,meta:D,baseId:C,localRefs:pe}),this._cache.set(K.schema,K),T&&!C.startsWith("#")&&(C&&this._checkUnique(C),this.refs[C]=K),$&&this.validateSchema(I,!0),K}_checkUnique(I){if(this.schemas[I]||this.refs[I])throw new Error(`schema with key or id "${I}" already exists`)}_compileSchemaEnv(I){if(I.meta?this._compileMetaSchema(I):o.compileSchema.call(this,I),!I.validate)throw new Error("ajv implementation error");return I.validate}_compileMetaSchema(I){let D=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,I)}finally{this.opts=D}}}b.ValidationError=n.default,b.MissingRefError=i.default,t.default=b;function S(F,I,D,C="error"){for(let $ in F){let T=$;T in I&&this.logger[C](`${D}: option ${$}. ${F[T]}`)}}function x(F){return F=(0,c.normalizeId)(F),this.schemas[F]||this.refs[F]}function w(){let F=this.opts.schemas;if(F)if(Array.isArray(F))this.addSchema(F);else for(let I in F)this.addSchema(F[I],I)}function k(){for(let F in this.opts.formats){let I=this.opts.formats[F];I&&this.addFormat(F,I)}}function O(F){if(Array.isArray(F)){this.addVocabulary(F);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let I in F){let D=F[I];D.keyword||(D.keyword=I),this.addKeyword(D)}}function A(){let F={...this.opts};for(let I of g)delete F[I];return F}var M={log(){},warn(){},error(){}};function L(F){if(F===!1)return M;if(F===void 0)return console;if(F.log&&F.warn&&F.error)return F;throw new Error("logger must implement log, warn and error methods")}var B=/^[a-z_$][a-z0-9_$:-]*$/i;function U(F,I){let{RULES:D}=this;if((0,l.eachItem)(F,C=>{if(D.keywords[C])throw new Error(`Keyword ${C} is already defined`);if(!B.test(C))throw new Error(`Keyword ${C} has invalid name`)}),!!I&&I.$data&&!("code"in I||"validate"in I))throw new Error('$data keyword must have "code" or "validate" function')}function Y(F,I,D){var C;let $=I?.post;if(D&&$)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:T}=this,N=$?T.post:T.rules.find(({type:K})=>K===D);if(N||(N={type:D,rules:[]},T.rules.push(N)),T.keywords[F]=!0,!I)return;let W={keyword:F,definition:{...I,type:(0,u.getJSONTypes)(I.type),schemaType:(0,u.getJSONTypes)(I.schemaType)}};I.before?me.call(this,N,W,I.before):N.rules.push(W),T.all[F]=W,(C=I.implements)===null||C===void 0||C.forEach(K=>this.addKeyword(K))}function me(F,I,D){let C=F.rules.findIndex($=>$.keyword===D);C>=0?F.rules.splice(C,0,I):(F.rules.push(I),this.logger.warn(`rule ${D} is not defined`))}function et(F){let{metaSchema:I}=F;I!==void 0&&(F.$data&&this.opts.$data&&(I=fe(I)),F.validateSchema=this.compile(I,!0))}var ht={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function fe(F){return{anyOf:[F,ht]}}}),Eae=V(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}),kae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.callRef=t.getValidate=void 0;var e=ag(),r=ri(),n=Ve(),i=Ra(),a=V$(),o=pt(),s={keyword:"$ref",schemaType:"string",code(l){let{gen:d,schema:p,it:f}=l,{baseId:g,schemaEnv:_,validateName:h,opts:m,self:y}=f,{root:v}=_;if((p==="#"||p==="#/")&&g===v.baseId)return S();let b=a.resolveRef.call(y,v,g,p);if(b===void 0)throw new e.default(f.opts.uriResolver,g,p);if(b instanceof a.SchemaEnv)return x(b);return w(b);function S(){if(_===v)return u(l,h,_,_.$async);let k=d.scopeValue("root",{ref:v});return u(l,(0,n._)`${k}.validate`,v,v.$async)}function x(k){let O=c(l,k);u(l,O,k,k.$async)}function w(k){let O=d.scopeValue("schema",m.code.source===!0?{ref:k,code:(0,n.stringify)(k)}:{ref:k}),A=d.name("valid"),M=l.subschema({schema:k,dataTypes:[],schemaPath:n.nil,topSchemaRef:O,errSchemaPath:p},A);l.mergeEvaluated(M),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:g,it:_}=l,{allErrors:h,schemaEnv:m,opts:y}=_,v=y.passContext?i.default.this:n.nil;f?b():S();function b(){if(!m.$async)throw new Error("async schema referenced by sync schema");let k=g.let("valid");g.try(()=>{g.code((0,n._)`await ${(0,r.callValidateCode)(l,d,v)}`),w(d),h||g.assign(k,!0)},O=>{g.if((0,n._)`!(${O} instanceof ${_.ValidationError})`,()=>g.throw(O)),x(O),h||g.assign(k,!1)}),l.ok(k)}function S(){l.result((0,r.callValidateCode)(l,d,v),()=>w(d),()=>x(d))}function x(k){let O=(0,n._)`${k}.errors`;g.assign(i.default.vErrors,(0,n._)`${i.default.vErrors} === null ? ${O} : ${i.default.vErrors}.concat(${O})`),g.assign(i.default.errors,(0,n._)`${i.default.vErrors}.length`)}function w(k){var O;if(!_.opts.unevaluated)return;let A=(O=p?.validate)===null||O===void 0?void 0:O.evaluated;if(_.props!==!0)if(A&&!A.dynamicProps)A.props!==void 0&&(_.props=o.mergeEvaluated.props(g,A.props,_.props));else{let M=g.var("props",(0,n._)`${k}.evaluated.props`);_.props=o.mergeEvaluated.props(g,M,_.props,n.Name)}if(_.items!==!0)if(A&&!A.dynamicItems)A.items!==void 0&&(_.items=o.mergeEvaluated.items(g,A.items,_.items));else{let M=g.var("items",(0,n._)`${k}.evaluated.items`);_.items=o.mergeEvaluated.items(g,M,_.items,n.Name)}}}t.callRef=u,t.default=s}),Tae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Eae(),r=kae(),n=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,r.default];t.default=n}),Iae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),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:s})=>(0,e.str)`must be ${n[o].okStr} ${s}`,params:({keyword:o,schemaCode:s})=>(0,e._)`{comparison: ${n[o].okStr}, limit: ${s}}`},a={keyword:Object.keys(n),type:"number",schemaType:"number",$data:!0,error:i,code(o){let{keyword:s,data:c,schemaCode:u}=o;o.fail$data((0,e._)`${c} ${n[s].fail} ${u} || isNaN(${c})`)}};t.default=a}),Pae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),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:a,data:o,schemaCode:s,it:c}=i,u=c.opts.multipleOfPrecision,l=a.let("res"),d=u?(0,e._)`Math.abs(Math.round(${l}) - ${l}) > 1e-${u}`:(0,e._)`${l} !== parseInt(${l})`;i.fail$data((0,e._)`(${s} === 0 || (${l} = ${o}/${s}, ${d}))`)}};t.default=n}),Oae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});function e(r){let n=r.length,i=0,a=0,o;for(;a=55296&&o<=56319&&a{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),r=pt(),n=Oae(),i={message({keyword:o,schemaCode:s}){let c=o==="maxLength"?"more":"fewer";return(0,e.str)`must NOT have ${c} than ${s} characters`},params:({schemaCode:o})=>(0,e._)`{limit: ${o}}`},a={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:i,code(o){let{keyword:s,data:c,schemaCode:u,it:l}=o,d=s==="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=a}),Cae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ri(),r=Ve(),n={message:({schemaCode:a})=>(0,r.str)`must match pattern "${a}"`,params:({schemaCode:a})=>(0,r._)`{pattern: ${a}}`},i={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:n,code(a){let{data:o,$data:s,schema:c,schemaCode:u,it:l}=a,d=l.opts.unicodeRegExp?"u":"",p=s?(0,r._)`(new RegExp(${u}, ${d}))`:(0,e.usePattern)(a,c);a.fail$data((0,r._)`!${p}.test(${o})`)}};t.default=i}),Nae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),r={message({keyword:i,schemaCode:a}){let o=i==="maxProperties"?"more":"fewer";return(0,e.str)`must NOT have ${o} than ${a} properties`},params:({schemaCode:i})=>(0,e._)`{limit: ${i}}`},n={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:r,code(i){let{keyword:a,data:o,schemaCode:s}=i,c=a==="maxProperties"?e.operators.GT:e.operators.LT;i.fail$data((0,e._)`Object.keys(${o}).length ${c} ${s}`)}};t.default=n}),jae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ri(),r=Ve(),n=pt(),i={message:({params:{missingProperty:o}})=>(0,r.str)`must have required property '${o}'`,params:({params:{missingProperty:o}})=>(0,r._)`{missingProperty: ${o}}`},a={keyword:"required",type:"object",schemaType:"array",$data:!0,error:i,code(o){let{gen:s,schema:c,schemaCode:u,data:l,$data:d,it:p}=o,{opts:f}=p;if(!d&&c.length===0)return;let g=c.length>=f.loopRequired;if(p.allErrors?_():h(),f.strictRequired){let v=o.parentSchema.properties,{definedProperties:b}=o.it;for(let S of c)if(v?.[S]===void 0&&!b.has(S)){let x=p.schemaEnv.baseId+p.errSchemaPath,w=`required property "${S}" is not defined at "${x}" (strictRequired)`;(0,n.checkStrictMode)(p,w,p.opts.strictRequired)}}function _(){if(g||d)o.block$data(r.nil,m);else for(let v of c)(0,e.checkReportMissingProp)(o,v)}function h(){let v=s.let("missing");if(g||d){let b=s.let("valid",!0);o.block$data(b,()=>y(v,b)),o.ok(b)}else s.if((0,e.checkMissingProp)(o,c,v)),(0,e.reportMissingProp)(o,v),s.else()}function m(){s.forOf("prop",u,v=>{o.setParams({missingProperty:v}),s.if((0,e.noPropertyInData)(s,l,v,f.ownProperties),()=>o.error())})}function y(v,b){o.setParams({missingProperty:v}),s.forOf(v,u,()=>{s.assign(b,(0,e.propertyInData)(s,l,v,f.ownProperties)),s.if((0,r.not)(b),()=>{o.error(),s.break()})},r.nil)}}};t.default=a}),Aae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),r={message({keyword:i,schemaCode:a}){let o=i==="maxItems"?"more":"fewer";return(0,e.str)`must NOT have ${o} than ${a} items`},params:({schemaCode:i})=>(0,e._)`{limit: ${i}}`},n={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:r,code(i){let{keyword:a,data:o,schemaCode:s}=i,c=a==="maxItems"?e.operators.GT:e.operators.LT;i.fail$data((0,e._)`${o}.length ${c} ${s}`)}};t.default=n}),G$=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Yh();e.code='require("ajv/dist/runtime/equal").default',t.default=e}),Mae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Hh(),r=Ve(),n=pt(),i=G$(),a={message:({params:{i:s,j:c}})=>(0,r.str)`must NOT have duplicate items (items ## ${c} and ${s} are identical)`,params:({params:{i:s,j:c}})=>(0,r._)`{i: ${s}, j: ${c}}`},o={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:a,code(s){let{gen:c,data:u,$data:l,schema:d,parentSchema:p,schemaCode:f,it:g}=s;if(!l&&!d)return;let _=c.let("valid"),h=p.items?(0,e.getSchemaTypes)(p.items):[];s.block$data(_,m,(0,r._)`${f} === false`),s.ok(_);function m(){let S=c.let("i",(0,r._)`${u}.length`),x=c.let("j");s.setParams({i:S,j:x}),c.assign(_,!0),c.if((0,r._)`${S} > 1`,()=>(y()?v:b)(S,x))}function y(){return h.length>0&&!h.some(S=>S==="object"||S==="array")}function v(S,x){let w=c.name("item"),k=(0,e.checkDataTypes)(h,w,g.opts.strictNumbers,e.DataType.Wrong),O=c.const("indices",(0,r._)`{}`);c.for((0,r._)`;${S}--;`,()=>{c.let(w,(0,r._)`${u}[${S}]`),c.if(k,(0,r._)`continue`),h.length>1&&c.if((0,r._)`typeof ${w} == "string"`,(0,r._)`${w} += "_"`),c.if((0,r._)`typeof ${O}[${w}] == "number"`,()=>{c.assign(x,(0,r._)`${O}[${w}]`),s.error(),c.assign(_,!1).break()}).code((0,r._)`${O}[${w}] = ${S}`)})}function b(S,x){let w=(0,n.useFunc)(c,i.default),k=c.name("outer");c.label(k).for((0,r._)`;${S}--;`,()=>c.for((0,r._)`${x} = ${S}; ${x}--;`,()=>c.if((0,r._)`${w}(${u}[${S}], ${u}[${x}])`,()=>{s.error(),c.assign(_,!1).break(k)})))}}};t.default=o}),Dae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),r=pt(),n=G$(),i={message:"must be equal to constant",params:({schemaCode:o})=>(0,e._)`{allowedValue: ${o}}`},a={keyword:"const",$data:!0,error:i,code(o){let{gen:s,data:c,$data:u,schemaCode:l,schema:d}=o;u||d&&typeof d=="object"?o.fail$data((0,e._)`!${(0,r.useFunc)(s,n.default)}(${c}, ${l})`):o.fail((0,e._)`${d} !== ${c}`)}};t.default=a}),zae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),r=pt(),n=G$(),i={message:"must be equal to one of the allowed values",params:({schemaCode:o})=>(0,e._)`{allowedValues: ${o}}`},a={keyword:"enum",schemaType:"array",$data:!0,error:i,code(o){let{gen:s,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,g,_=()=>g??(g=(0,r.useFunc)(s,n.default)),h;if(f||u)h=s.let("valid"),o.block$data(h,m);else{if(!Array.isArray(l))throw new Error("ajv implementation error");let v=s.const("vSchema",d);h=(0,e.or)(...l.map((b,S)=>y(v,S)))}o.pass(h);function m(){s.assign(h,!1),s.forOf("v",d,v=>s.if((0,e._)`${_()}(${c}, ${v})`,()=>s.assign(h,!0).break()))}function y(v,b){let S=l[b];return typeof S=="object"&&S!==null?(0,e._)`${_()}(${c}, ${v}[${b}])`:(0,e._)`${c} === ${S}`}}};t.default=a}),Uae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Iae(),r=Pae(),n=Rae(),i=Cae(),a=Nae(),o=jae(),s=Aae(),c=Mae(),u=Dae(),l=zae(),d=[e.default,r.default,n.default,i.default,a.default,o.default,s.default,c.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},u.default,l.default];t.default=d}),G2=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateAdditionalItems=void 0;var e=Ve(),r=pt(),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:s,it:c}=o,{items:u}=s;if(!Array.isArray(u)){(0,r.checkStrictMode)(c,'"additionalItems" is ignored when "items" is not an array of schemas');return}a(o,u)}};function a(o,s){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:s.length}),o.pass((0,e._)`${f} <= ${s.length}`);else if(typeof u=="object"&&!(0,r.alwaysValidSchema)(p,u)){let _=c.var("valid",(0,e._)`${f} <= ${s.length}`);c.if((0,e.not)(_),()=>g(_)),o.ok(_)}function g(_){c.forRange("i",s.length,f,h=>{o.subschema({keyword:d,dataProp:h,dataPropType:r.Type.Num},_),p.allErrors||c.if((0,e.not)(_),()=>c.break())})}}t.validateAdditionalItems=a,t.default=i}),W2=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateTuple=void 0;var e=Ve(),r=pt(),n=ri(),i={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(o){let{schema:s,it:c}=o;if(Array.isArray(s))return a(o,"additionalItems",s);c.items=!0,!(0,r.alwaysValidSchema)(c,s)&&o.ok((0,n.validateArray)(o))}};function a(o,s,c=o.schema){let{gen:u,parentSchema:l,data:d,keyword:p,it:f}=o;h(l),f.opts.unevaluated&&c.length&&f.items!==!0&&(f.items=r.mergeEvaluated.items(u,c.length,f.items));let g=u.name("valid"),_=u.const("len",(0,e._)`${d}.length`);c.forEach((m,y)=>{(0,r.alwaysValidSchema)(f,m)||(u.if((0,e._)`${_} > ${y}`,()=>o.subschema({keyword:p,schemaProp:y,dataProp:y},g)),o.ok(g))});function h(m){let{opts:y,errSchemaPath:v}=f,b=c.length,S=b===m.minItems&&(b===m.maxItems||m[s]===!1);if(y.strictTuples&&!S){let x=`"${p}" is ${b}-tuple, but minItems or maxItems/${s} are not specified or different at path "${v}"`;(0,r.checkStrictMode)(f,x,y.strictTuples)}}}t.validateTuple=a,t.default=i}),Lae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=W2(),r={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:n=>(0,e.validateTuple)(n,"items")};t.default=r}),qae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),r=pt(),n=ri(),i=G2(),a={message:({params:{len:s}})=>(0,e.str)`must NOT have more than ${s} items`,params:({params:{len:s}})=>(0,e._)`{limit: ${s}}`},o={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:a,code(s){let{schema:c,parentSchema:u,it:l}=s,{prefixItems:d}=u;l.items=!0,!(0,r.alwaysValidSchema)(l,c)&&(d?(0,i.validateAdditionalItems)(s,d):s.ok((0,n.validateArray)(s)))}};t.default=o}),Fae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),r=pt(),n={message:({params:{min:a,max:o}})=>o===void 0?(0,e.str)`must contain at least ${a} valid item(s)`:(0,e.str)`must contain at least ${a} and no more than ${o} valid item(s)`,params:({params:{min:a,max:o}})=>o===void 0?(0,e._)`{minContains: ${a}}`:(0,e._)`{minContains: ${a}, maxContains: ${o}}`},i={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:n,code(a){let{gen:o,schema:s,parentSchema:c,data:u,it:l}=a,d,p,{minContains:f,maxContains:g}=c;l.opts.next?(d=f===void 0?1:f,p=g):d=1;let _=o.const("len",(0,e._)`${u}.length`);if(a.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'),a.fail();return}if((0,r.alwaysValidSchema)(l,s)){let b=(0,e._)`${_} >= ${d}`;p!==void 0&&(b=(0,e._)`${b} && ${_} <= ${p}`),a.pass(b);return}l.items=!0;let h=o.name("valid");p===void 0&&d===1?y(h,()=>o.if(h,()=>o.break())):d===0?(o.let(h,!0),p!==void 0&&o.if((0,e._)`${u}.length > 0`,m)):(o.let(h,!1),m()),a.result(h,()=>a.reset());function m(){let b=o.name("_valid"),S=o.let("count",0);y(b,()=>o.if(b,()=>v(S)))}function y(b,S){o.forRange("i",0,_,x=>{a.subschema({keyword:"contains",dataProp:x,dataPropType:r.Type.Num,compositeRule:!0},b),S()})}function v(b){o.code((0,e._)`${b}++`),p===void 0?o.if((0,e._)`${b} >= ${d}`,()=>o.assign(h,!0).break()):(o.if((0,e._)`${b} > ${p}`,()=>o.assign(h,!1).break()),d===1?o.assign(h,!0):o.if((0,e._)`${b} >= ${d}`,()=>o.assign(h,!0)))}}};t.default=i}),Zae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;var e=Ve(),r=pt(),n=ri();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}, + || ${O} === "boolean" || ${w} === null`).assign(A,(0,i._)`[${w}]`)}}}function f({gen:v,parentData:b,parentDataProperty:S},x){v.if((0,i._)`${b} !== undefined`,()=>v.assign((0,i._)`${b}[${S}]`,x))}function g(v,b,S,x=o.Correct){let w=x===o.Correct?i.operators.EQ:i.operators.NEQ,k;switch(v){case"null":return(0,i._)`${b} ${w} null`;case"array":k=(0,i._)`Array.isArray(${b})`;break;case"object":k=(0,i._)`${b} && typeof ${b} == "object" && !Array.isArray(${b})`;break;case"integer":k=O((0,i._)`!(${b} % 1) && !isNaN(${b})`);break;case"number":k=O();break;default:return(0,i._)`typeof ${b} ${w} ${v}`}return x===o.Correct?k:(0,i.not)(k);function O(A=i.nil){return(0,i.and)((0,i._)`typeof ${b} == "number"`,A,S?(0,i._)`isFinite(${b})`:i.nil)}}t.checkDataType=g;function _(v,b,S,x){if(v.length===1)return g(v[0],b,S,x);let w,k=(0,a.toHash)(v);if(k.array&&k.object){let O=(0,i._)`typeof ${b} != "object"`;w=k.null?O:(0,i._)`!${b} || ${O}`,delete k.null,delete k.array,delete k.object}else w=i.nil;k.number&&delete k.integer;for(let O in k)w=(0,i.and)(w,g(O,b,S,x));return w}t.checkDataTypes=_;var h={message:({schema:v})=>`must be ${v}`,params:({schema:v,schemaValue:b})=>typeof v=="string"?(0,i._)`{type: ${v}}`:(0,i._)`{type: ${b}}`};function m(v){let b=y(v);(0,n.reportError)(b,h)}t.reportTypeError=m;function y(v){let{gen:b,data:S,schema:x}=v,w=(0,a.schemaRefOrVal)(v,x,"type");return{gen:b,keyword:"type",data:S,schema:x.type,schemaCode:w,schemaValue:w,parentSchema:x,params:{},it:v}}}),yae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.assignDefaults=void 0;var e=Ve(),r=pt();function n(a,o){let{properties:s,items:c}=a.schema;if(o==="object"&&s)for(let u in s)i(a,u,s[u].default);else o==="array"&&Array.isArray(c)&&c.forEach((u,l)=>i(a,l,u.default))}t.assignDefaults=n;function i(a,o,s){let{gen:c,compositeRule:u,data:l,opts:d}=a;if(s===void 0)return;let p=(0,e._)`${l}${(0,e.getProperty)(o)}`;if(u){(0,r.checkStrictMode)(a,`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)(s)}`)}}),ri=V(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=Ve(),r=pt(),n=Ra(),i=pt();function a(v,b){let{gen:S,data:x,it:w}=v;S.if(d(S,x,b,w.opts.ownProperties),()=>{v.setParams({missingProperty:(0,e._)`${b}`},!0),v.error()})}t.checkReportMissingProp=a;function o({gen:v,data:b,it:{opts:S}},x,w){return(0,e.or)(...x.map(k=>(0,e.and)(d(v,b,k,S.ownProperties),(0,e._)`${w} = ${k}`)))}t.checkMissingProp=o;function s(v,b){v.setParams({missingProperty:b},!0),v.error()}t.reportMissingProp=s;function c(v){return v.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}t.hasPropFunc=c;function u(v,b,S){return(0,e._)`${c(v)}.call(${b}, ${S})`}t.isOwnProperty=u;function l(v,b,S,x){let w=(0,e._)`${b}${(0,e.getProperty)(S)} !== undefined`;return x?(0,e._)`${w} && ${u(v,b,S)}`:w}t.propertyInData=l;function d(v,b,S,x){let w=(0,e._)`${b}${(0,e.getProperty)(S)} === undefined`;return x?(0,e.or)(w,(0,e.not)(u(v,b,S))):w}t.noPropertyInData=d;function p(v){return v?Object.keys(v).filter(b=>b!=="__proto__"):[]}t.allSchemaProperties=p;function f(v,b){return p(b).filter(S=>!(0,r.alwaysValidSchema)(v,b[S]))}t.schemaProperties=f;function g({schemaCode:v,data:b,it:{gen:S,topSchemaRef:x,schemaPath:w,errorPath:k},it:O},A,M,L){let B=L?(0,e._)`${v}, ${b}, ${x}${w}`:b,U=[[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,k)],[n.default.parentData,O.parentData],[n.default.parentDataProperty,O.parentDataProperty],[n.default.rootData,n.default.rootData]];O.opts.dynamicRef&&U.push([n.default.dynamicAnchors,n.default.dynamicAnchors]);let Y=(0,e._)`${B}, ${S.object(...U)}`;return M!==e.nil?(0,e._)`${A}.call(${M}, ${Y})`:(0,e._)`${A}(${Y})`}t.callValidateCode=g;var _=(0,e._)`new RegExp`;function h({gen:v,it:{opts:b}},S){let x=b.unicodeRegExp?"u":"",{regExp:w}=b.code,k=w(S,x);return v.scopeValue("pattern",{key:k.toString(),ref:k,code:(0,e._)`${w.code==="new RegExp"?_:(0,i.useFunc)(v,w)}(${S}, ${x})`})}t.usePattern=h;function m(v){let{gen:b,data:S,keyword:x,it:w}=v,k=b.name("valid");if(w.allErrors){let A=b.let("valid",!0);return O(()=>b.assign(A,!1)),A}return b.var(k,!0),O(()=>b.break()),k;function O(A){let M=b.const("len",(0,e._)`${S}.length`);b.forRange("i",0,M,L=>{v.subschema({keyword:x,dataProp:L,dataPropType:r.Type.Num},k),b.if((0,e.not)(k),A)})}}t.validateArray=m;function y(v){let{gen:b,schema:S,keyword:x,it:w}=v;if(!Array.isArray(S))throw new Error("ajv implementation error");if(S.some(M=>(0,r.alwaysValidSchema)(w,M))&&!w.opts.unevaluated)return;let O=b.let("valid",!1),A=b.name("_valid");b.block(()=>S.forEach((M,L)=>{let B=v.subschema({keyword:x,schemaProp:L,compositeRule:!0},A);b.assign(O,(0,e._)`${O} || ${A}`),v.mergeValidEvaluated(B,A)||b.if((0,e.not)(O))})),v.result(O,()=>v.reset(),()=>v.error(!0))}t.validateUnion=y}),_ae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateKeywordUsage=t.validSchemaType=t.funcKeywordCode=t.macroKeywordCode=void 0;var e=Ve(),r=Ra(),n=ri(),i=rg();function a(f,g){let{gen:_,keyword:h,schema:m,parentSchema:y,it:v}=f,b=g.macro.call(v.self,m,y,v),S=l(_,h,b);v.opts.validateSchema!==!1&&v.self.validateSchema(b,!0);let x=_.name("valid");f.subschema({schema:b,schemaPath:e.nil,errSchemaPath:`${v.errSchemaPath}/${h}`,topSchemaRef:S,compositeRule:!0},x),f.pass(x,()=>f.error(!0))}t.macroKeywordCode=a;function o(f,g){var _;let{gen:h,keyword:m,schema:y,parentSchema:v,$data:b,it:S}=f;u(S,g);let x=!b&&g.compile?g.compile.call(S.self,y,v,S):g.validate,w=l(h,m,x),k=h.let("valid");f.block$data(k,O),f.ok((_=g.valid)!==null&&_!==void 0?_:k);function O(){if(g.errors===!1)L(),g.modifying&&s(f),B(()=>f.error());else{let U=g.async?A():M();g.modifying&&s(f),B(()=>c(f,U))}}function A(){let U=h.let("ruleErrs",null);return h.try(()=>L((0,e._)`await `),Y=>h.assign(k,!1).if((0,e._)`${Y} instanceof ${S.ValidationError}`,()=>h.assign(U,(0,e._)`${Y}.errors`),()=>h.throw(Y))),U}function M(){let U=(0,e._)`${w}.errors`;return h.assign(U,null),L(e.nil),U}function L(U=g.async?(0,e._)`await `:e.nil){let Y=S.opts.passContext?r.default.this:r.default.self,me=!("compile"in g&&!b||g.schema===!1);h.assign(k,(0,e._)`${U}${(0,n.callValidateCode)(f,w,Y,me)}`,g.modifying)}function B(U){var Y;h.if((0,e.not)((Y=g.valid)!==null&&Y!==void 0?Y:k),U)}}t.funcKeywordCode=o;function s(f){let{gen:g,data:_,it:h}=f;g.if(h.parentData,()=>g.assign(_,(0,e._)`${h.parentData}[${h.parentDataProperty}]`))}function c(f,g){let{gen:_}=f;_.if((0,e._)`Array.isArray(${g})`,()=>{_.assign(r.default.vErrors,(0,e._)`${r.default.vErrors} === null ? ${g} : ${r.default.vErrors}.concat(${g})`).assign(r.default.errors,(0,e._)`${r.default.vErrors}.length`),(0,i.extendErrors)(f)},()=>f.error())}function u({schemaEnv:f},g){if(g.async&&!f.$async)throw new Error("async keyword in sync schema")}function l(f,g,_){if(_===void 0)throw new Error(`keyword "${g}" failed to compile`);return f.scopeValue("keyword",typeof _=="function"?{ref:_}:{ref:_,code:(0,e.stringify)(_)})}function d(f,g,_=!1){return!g.length||g.some(h=>h==="array"?Array.isArray(f):h==="object"?f&&typeof f=="object"&&!Array.isArray(f):typeof f==h||_&&typeof f>"u")}t.validSchemaType=d;function p({schema:f,opts:g,self:_,errSchemaPath:h},m,y){if(Array.isArray(m.keyword)?!m.keyword.includes(y):m.keyword!==y)throw new Error("ajv implementation error");let v=m.dependencies;if(v?.some(b=>!Object.prototype.hasOwnProperty.call(f,b)))throw new Error(`parent schema must have dependencies of ${y}: ${v.join(",")}`);if(m.validateSchema&&!m.validateSchema(f[y])){let S=`keyword "${y}" value is invalid at path "${h}": `+_.errorsText(m.validateSchema.errors);if(g.validateSchema==="log")_.logger.error(S);else throw new Error(S)}}t.validateKeywordUsage=p}),bae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extendSubschemaMode=t.extendSubschemaData=t.getSubschema=void 0;var e=Ve(),r=pt();function n(o,{keyword:s,schemaProp:c,schema:u,schemaPath:l,errSchemaPath:d,topSchemaRef:p}){if(s!==void 0&&u!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(s!==void 0){let f=o.schema[s];return c===void 0?{schema:f,schemaPath:(0,e._)`${o.schemaPath}${(0,e.getProperty)(s)}`,errSchemaPath:`${o.errSchemaPath}/${s}`}:{schema:f[c],schemaPath:(0,e._)`${o.schemaPath}${(0,e.getProperty)(s)}${(0,e.getProperty)(c)}`,errSchemaPath:`${o.errSchemaPath}/${s}/${(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,s,{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}=s;if(c!==void 0){let{errorPath:_,dataPathArr:h,opts:m}=s,y=f.let("data",(0,e._)`${s.data}${(0,e.getProperty)(c)}`,!0);g(y),o.errorPath=(0,e.str)`${_}${(0,r.getErrorPath)(c,u,m.jsPropertySyntax)}`,o.parentDataProperty=(0,e._)`${c}`,o.dataPathArr=[...h,o.parentDataProperty]}if(l!==void 0){let _=l instanceof e.Name?l:f.let("data",l,!0);g(_),p!==void 0&&(o.propertyName=p)}d&&(o.dataTypes=d);function g(_){o.data=_,o.dataLevel=s.dataLevel+1,o.dataTypes=[],s.definedProperties=new Set,o.parentData=s.data,o.dataNames=[...s.dataNames,_]}}t.extendSubschemaData=i;function a(o,{jtdDiscriminator:s,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=s,o.jtdMetadata=c}t.extendSubschemaMode=a}),xae=V((t,e)=>{var r=e.exports=function(a,o,s){typeof o=="function"&&(s=o,o={}),s=o.cb||s;var c=typeof s=="function"?s:s.pre||function(){},u=s.post||function(){};n(o,c,u,a,"",a)};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(a,o,s,c,u,l,d,p,f,g){if(c&&typeof c=="object"&&!Array.isArray(c)){o(c,u,l,d,p,f,g);for(var _ in c){var h=c[_];if(Array.isArray(h)){if(_ in r.arrayKeywords)for(var m=0;m{Object.defineProperty(t,"__esModule",{value:!0}),t.getSchemaRefs=t.resolveUrl=t.normalizeId=t._getFullPath=t.getFullPath=t.inlineRef=void 0;var e=pt(),r=Yh(),n=xae(),i=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function a(h,m=!0){return typeof h=="boolean"?!0:m===!0?!s(h):m?c(h)<=m:!1}t.inlineRef=a;var o=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function s(h){for(let m in h){if(o.has(m))return!0;let y=h[m];if(Array.isArray(y)&&y.some(s)||typeof y=="object"&&s(y))return!0}return!1}function c(h){let m=0;for(let y in h){if(y==="$ref")return 1/0;if(m++,!i.has(y)&&(typeof h[y]=="object"&&(0,e.eachItem)(h[y],v=>m+=c(v)),m===1/0))return 1/0}return m}function u(h,m="",y){y!==!1&&(m=p(m));let v=h.parse(m);return l(h,v)}t.getFullPath=u;function l(h,m){return h.serialize(m).split("#")[0]+"#"}t._getFullPath=l;var d=/#\/?$/;function p(h){return h?h.replace(d,""):""}t.normalizeId=p;function f(h,m,y){return y=p(y),h.resolve(m,y)}t.resolveUrl=f;var g=/^[a-z_][-a-z0-9._]*$/i;function _(h,m){if(typeof h=="boolean")return{};let{schemaId:y,uriResolver:v}=this.opts,b=p(h[y]||m),S={"":b},x=u(v,b,!1),w={},k=new Set;return n(h,{allKeys:!0},(M,L,B,U)=>{if(U===void 0)return;let Y=x+L,me=S[U];typeof M[y]=="string"&&(me=et.call(this,M[y])),ht.call(this,M.$anchor),ht.call(this,M.$dynamicAnchor),S[L]=me;function et(fe){let F=this.opts.uriResolver.resolve;if(fe=p(me?F(me,fe):fe),k.has(fe))throw A(fe);k.add(fe);let I=this.refs[fe];return typeof I=="string"&&(I=this.refs[I]),typeof I=="object"?O(M,I.schema,fe):fe!==p(Y)&&(fe[0]==="#"?(O(M,w[fe],fe),w[fe]=M):this.refs[fe]=Y),fe}function ht(fe){if(typeof fe=="string"){if(!g.test(fe))throw new Error(`invalid anchor "${fe}"`);et.call(this,`#${fe}`)}}}),w;function O(M,L,B){if(L!==void 0&&!r(M,L))throw A(B)}function A(M){return new Error(`reference "${M}" resolves to more than one schema`)}}t.getSchemaRefs=_}),ig=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getData=t.KeywordCxt=t.validateFunctionCode=void 0;var e=vae(),r=Hh(),n=V2(),i=Hh(),a=yae(),o=_ae(),s=bae(),c=Ve(),u=Ra(),l=ng(),d=pt(),p=rg();function f(P){if(x(P)&&(k(P),S(P))){m(P);return}g(P,()=>(0,e.topBoolOrEmptySchema)(P))}t.validateFunctionCode=f;function g({gen:P,validateName:R,schema:z,schemaEnv:Z,opts:J},ie){J.code.es5?P.func(R,(0,c._)`${u.default.data}, ${u.default.valCxt}`,Z.$async,()=>{P.code((0,c._)`"use strict"; ${v(z,J)}`),h(P,J),P.code(ie)}):P.func(R,(0,c._)`${u.default.data}, ${_(J)}`,Z.$async,()=>P.code(v(z,J)).code(ie))}function _(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 h(P,R){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}`),R.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),R.dynamicRef&&P.var(u.default.dynamicAnchors,(0,c._)`{}`)})}function m(P){let{schema:R,opts:z,gen:Z}=P;g(P,()=>{z.$comment&&R.$comment&&U(P),M(P),Z.let(u.default.vErrors,null),Z.let(u.default.errors,0),z.unevaluated&&y(P),O(P),Y(P)})}function y(P){let{gen:R,validateName:z}=P;P.evaluated=R.const("evaluated",(0,c._)`${z}.evaluated`),R.if((0,c._)`${P.evaluated}.dynamicProps`,()=>R.assign((0,c._)`${P.evaluated}.props`,(0,c._)`undefined`)),R.if((0,c._)`${P.evaluated}.dynamicItems`,()=>R.assign((0,c._)`${P.evaluated}.items`,(0,c._)`undefined`))}function v(P,R){let z=typeof P=="object"&&P[R.schemaId];return z&&(R.code.source||R.code.process)?(0,c._)`/*# sourceURL=${z} */`:c.nil}function b(P,R){if(x(P)&&(k(P),S(P))){w(P,R);return}(0,e.boolOrEmptySchema)(P,R)}function S({schema:P,self:R}){if(typeof P=="boolean")return!P;for(let z in P)if(R.RULES.all[z])return!0;return!1}function x(P){return typeof P.schema!="boolean"}function w(P,R){let{schema:z,gen:Z,opts:J}=P;J.$comment&&z.$comment&&U(P),L(P),B(P);let ie=Z.const("_errs",u.default.errors);O(P,ie),Z.var(R,(0,c._)`${ie} === ${u.default.errors}`)}function k(P){(0,d.checkUnknownRules)(P),A(P)}function O(P,R){if(P.opts.jtd)return et(P,[],!1,R);let z=(0,r.getSchemaTypes)(P.schema),Z=(0,r.coerceAndCheckDataType)(P,z);et(P,z,!Z,R)}function A(P){let{schema:R,errSchemaPath:z,opts:Z,self:J}=P;R.$ref&&Z.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(R,J.RULES)&&J.logger.warn(`$ref: keywords ignored in schema at path "${z}"`)}function M(P){let{schema:R,opts:z}=P;R.default!==void 0&&z.useDefaults&&z.strictSchema&&(0,d.checkStrictMode)(P,"default is ignored in the schema root")}function L(P){let R=P.schema[P.opts.schemaId];R&&(P.baseId=(0,l.resolveUrl)(P.opts.uriResolver,P.baseId,R))}function B(P){if(P.schema.$async&&!P.schemaEnv.$async)throw new Error("async schema in sync schema")}function U({gen:P,schemaEnv:R,schema:z,errSchemaPath:Z,opts:J}){let ie=z.$comment;if(J.$comment===!0)P.code((0,c._)`${u.default.self}.logger.log(${ie})`);else if(typeof J.$comment=="function"){let tt=(0,c.str)`${Z}/$comment`,Ht=P.scopeValue("root",{ref:R.root});P.code((0,c._)`${u.default.self}.opts.$comment(${ie}, ${tt}, ${Ht}.schema)`)}}function Y(P){let{gen:R,schemaEnv:z,validateName:Z,ValidationError:J,opts:ie}=P;z.$async?R.if((0,c._)`${u.default.errors} === 0`,()=>R.return(u.default.data),()=>R.throw((0,c._)`new ${J}(${u.default.vErrors})`)):(R.assign((0,c._)`${Z}.errors`,u.default.vErrors),ie.unevaluated&&me(P),R.return((0,c._)`${u.default.errors} === 0`))}function me({gen:P,evaluated:R,props:z,items:Z}){z instanceof c.Name&&P.assign((0,c._)`${R}.props`,z),Z instanceof c.Name&&P.assign((0,c._)`${R}.items`,Z)}function et(P,R,z,Z){let{gen:J,schema:ie,data:tt,allErrors:Ht,opts:yt,self:_t}=P,{RULES:rt}=_t;if(ie.$ref&&(yt.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(ie,rt))){J.block(()=>K(P,"$ref",rt.all.$ref.definition));return}yt.jtd||fe(P,R),J.block(()=>{for(let jt of rt.rules)en(jt);en(rt.post)});function en(jt){(0,n.shouldUseGroup)(ie,jt)&&(jt.type?(J.if((0,i.checkDataType)(jt.type,tt,yt.strictNumbers)),ht(P,jt),R.length===1&&R[0]===jt.type&&z&&(J.else(),(0,i.reportTypeError)(P)),J.endIf()):ht(P,jt),Ht||J.if((0,c._)`${u.default.errors} === ${Z||0}`))}}function ht(P,R){let{gen:z,schema:Z,opts:{useDefaults:J}}=P;J&&(0,a.assignDefaults)(P,R.type),z.block(()=>{for(let ie of R.rules)(0,n.shouldUseRule)(Z,ie)&&K(P,ie.keyword,ie.definition,R.type)})}function fe(P,R){P.schemaEnv.meta||!P.opts.strictTypes||(F(P,R),P.opts.allowUnionTypes||I(P,R),D(P,P.dataTypes))}function F(P,R){if(R.length){if(!P.dataTypes.length){P.dataTypes=R;return}R.forEach(z=>{$(P.dataTypes,z)||N(P,`type "${z}" not allowed by context "${P.dataTypes.join(",")}"`)}),T(P,R)}}function I(P,R){R.length>1&&!(R.length===2&&R.includes("null"))&&N(P,"use allowUnionTypes to allow union type keyword")}function D(P,R){let z=P.self.RULES.all;for(let Z in z){let J=z[Z];if(typeof J=="object"&&(0,n.shouldUseRule)(P.schema,J)){let{type:ie}=J.definition;ie.length&&!ie.some(tt=>C(R,tt))&&N(P,`missing type "${ie.join(",")}" for keyword "${Z}"`)}}}function C(P,R){return P.includes(R)||R==="number"&&P.includes("integer")}function $(P,R){return P.includes(R)||R==="integer"&&P.includes("number")}function T(P,R){let z=[];for(let Z of P.dataTypes)$(R,Z)?z.push(Z):R.includes("integer")&&Z==="number"&&z.push("integer");P.dataTypes=z}function N(P,R){let z=P.schemaEnv.baseId+P.errSchemaPath;R+=` at "${z}" (strictTypes)`,(0,d.checkStrictMode)(P,R,P.opts.strictTypes)}class W{constructor(R,z,Z){if((0,o.validateKeywordUsage)(R,z,Z),this.gen=R.gen,this.allErrors=R.allErrors,this.keyword=Z,this.data=R.data,this.schema=R.schema[Z],this.$data=z.$data&&R.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(R,this.schema,Z,this.$data),this.schemaType=z.schemaType,this.parentSchema=R.schema,this.params={},this.it=R,this.def=z,this.$data)this.schemaCode=R.gen.const("vSchema",je(this.$data,R));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,z.schemaType,z.allowUndefined))throw new Error(`${Z} value must be ${JSON.stringify(z.schemaType)}`);("code"in z?z.trackErrors:z.errors!==!1)&&(this.errsCount=R.gen.const("_errs",u.default.errors))}result(R,z,Z){this.failResult((0,c.not)(R),z,Z)}failResult(R,z,Z){this.gen.if(R),Z?Z():this.error(),z?(this.gen.else(),z(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(R,z){this.failResult((0,c.not)(R),void 0,z)}fail(R){if(R===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(R),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(R){if(!this.$data)return this.fail(R);let{schemaCode:z}=this;this.fail((0,c._)`${z} !== undefined && (${(0,c.or)(this.invalid$data(),R)})`)}error(R,z,Z){if(z){this.setParams(z),this._error(R,Z),this.setParams({});return}this._error(R,Z)}_error(R,z){(R?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(R){this.allErrors||this.gen.if(R)}setParams(R,z){z?Object.assign(this.params,R):this.params=R}block$data(R,z,Z=c.nil){this.gen.block(()=>{this.check$data(R,Z),z()})}check$data(R=c.nil,z=c.nil){if(!this.$data)return;let{gen:Z,schemaCode:J,schemaType:ie,def:tt}=this;Z.if((0,c.or)((0,c._)`${J} === undefined`,z)),R!==c.nil&&Z.assign(R,!0),(ie.length||tt.validateSchema)&&(Z.elseIf(this.invalid$data()),this.$dataError(),R!==c.nil&&Z.assign(R,!1)),Z.else()}invalid$data(){let{gen:R,schemaCode:z,schemaType:Z,def:J,it:ie}=this;return(0,c.or)(tt(),Ht());function tt(){if(Z.length){if(!(z instanceof c.Name))throw new Error("ajv implementation error");let yt=Array.isArray(Z)?Z:[Z];return(0,c._)`${(0,i.checkDataTypes)(yt,z,ie.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function Ht(){if(J.validateSchema){let yt=R.scopeValue("validate$data",{ref:J.validateSchema});return(0,c._)`!${yt}(${z})`}return c.nil}}subschema(R,z){let Z=(0,s.getSubschema)(this.it,R);(0,s.extendSubschemaData)(Z,this.it,R),(0,s.extendSubschemaMode)(Z,R);let J={...this.it,...Z,items:void 0,props:void 0};return b(J,z),J}mergeEvaluated(R,z){let{it:Z,gen:J}=this;Z.opts.unevaluated&&(Z.props!==!0&&R.props!==void 0&&(Z.props=d.mergeEvaluated.props(J,R.props,Z.props,z)),Z.items!==!0&&R.items!==void 0&&(Z.items=d.mergeEvaluated.items(J,R.items,Z.items,z)))}mergeValidEvaluated(R,z){let{it:Z,gen:J}=this;if(Z.opts.unevaluated&&(Z.props!==!0||Z.items!==!0))return J.if(z,()=>this.mergeEvaluated(R,c.Name)),!0}}t.KeywordCxt=W;function K(P,R,z,Z){let J=new W(P,z,R);"code"in z?z.code(J,Z):J.$data&&z.validate?(0,o.funcKeywordCode)(J,z):"macro"in z?(0,o.macroKeywordCode)(J,z):(z.compile||z.validate)&&(0,o.funcKeywordCode)(J,z)}var pe=/^\/(?:[^~]|~0|~1)*$/,ce=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function je(P,{dataLevel:R,dataNames:z,dataPathArr:Z}){let J,ie;if(P==="")return u.default.rootData;if(P[0]==="/"){if(!pe.test(P))throw new Error(`Invalid JSON-pointer: ${P}`);J=P,ie=u.default.rootData}else{let _t=ce.exec(P);if(!_t)throw new Error(`Invalid JSON-pointer: ${P}`);let rt=+_t[1];if(J=_t[2],J==="#"){if(rt>=R)throw new Error(yt("property/index",rt));return Z[R-rt]}if(rt>R)throw new Error(yt("data",rt));if(ie=z[R-rt],!J)return ie}let tt=ie,Ht=J.split("/");for(let _t of Ht)_t&&(ie=(0,c._)`${ie}${(0,c.getProperty)((0,d.unescapeJsonPointer)(_t))}`,tt=(0,c._)`${tt} && ${ie}`);return tt;function yt(_t,rt){return`Cannot access ${_t} ${rt} levels up, current level is ${R}`}}t.getData=je}),B$=V(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}),ag=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ng();class r extends Error{constructor(i,a,o,s){super(s||`can't resolve reference ${o} from id ${a}`),this.missingRef=(0,e.resolveUrl)(i,a,o),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(i,this.missingRef))}}t.default=r}),V$=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resolveSchema=t.getCompilingSchema=t.resolveRef=t.compileSchema=t.SchemaEnv=void 0;var e=Ve(),r=B$(),n=Ra(),i=ng(),a=pt(),o=ig();class s{constructor(y){var v;this.refs={},this.dynamicAnchors={};let b;typeof y.schema=="object"&&(b=y.schema),this.schema=y.schema,this.schemaId=y.schemaId,this.root=y.root||this,this.baseId=(v=y.baseId)!==null&&v!==void 0?v:(0,i.normalizeId)(b?.[y.schemaId||"$id"]),this.schemaPath=y.schemaPath,this.localRefs=y.localRefs,this.meta=y.meta,this.$async=b?.$async,this.refs={}}}t.SchemaEnv=s;function c(m){let y=d.call(this,m);if(y)return y;let v=(0,i.getFullPath)(this.opts.uriResolver,m.root.baseId),{es5:b,lines:S}=this.opts.code,{ownProperties:x}=this.opts,w=new e.CodeGen(this.scope,{es5:b,lines:S,ownProperties:x}),k;m.$async&&(k=w.scopeValue("Error",{ref:r.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));let O=w.scopeName("validate");m.validateName=O;let A={gen:w,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:w.scopeValue("schema",this.opts.code.source===!0?{ref:m.schema,code:(0,e.stringify)(m.schema)}:{ref:m.schema}),validateName:O,ValidationError:k,schema:m.schema,schemaEnv:m,rootId:v,baseId:m.baseId||v,schemaPath:e.nil,errSchemaPath:m.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this},M;try{this._compilations.add(m),(0,o.validateFunctionCode)(A),w.optimize(this.opts.code.optimize);let L=w.toString();M=`${w.scopeRefs(n.default.scope)}return ${L}`,this.opts.code.process&&(M=this.opts.code.process(M,m));let U=new Function(`${n.default.self}`,`${n.default.scope}`,M)(this,this.scope.get());if(this.scope.value(O,{ref:U}),U.errors=null,U.schema=m.schema,U.schemaEnv=m,m.$async&&(U.$async=!0),this.opts.code.source===!0&&(U.source={validateName:O,validateCode:L,scopeValues:w._values}),this.opts.unevaluated){let{props:Y,items:me}=A;U.evaluated={props:Y instanceof e.Name?void 0:Y,items:me instanceof e.Name?void 0:me,dynamicProps:Y instanceof e.Name,dynamicItems:me instanceof e.Name},U.source&&(U.source.evaluated=(0,e.stringify)(U.evaluated))}return m.validate=U,m}catch(L){throw delete m.validate,delete m.validateName,M&&this.logger.error("Error compiling schema, function code:",M),L}finally{this._compilations.delete(m)}}t.compileSchema=c;function u(m,y,v){var b;v=(0,i.resolveUrl)(this.opts.uriResolver,y,v);let S=m.refs[v];if(S)return S;let x=f.call(this,m,v);if(x===void 0){let w=(b=m.localRefs)===null||b===void 0?void 0:b[v],{schemaId:k}=this.opts;w&&(x=new s({schema:w,schemaId:k,root:m,baseId:y}))}if(x!==void 0)return m.refs[v]=l.call(this,x)}t.resolveRef=u;function l(m){return(0,i.inlineRef)(m.schema,this.opts.inlineRefs)?m.schema:m.validate?m:c.call(this,m)}function d(m){for(let y of this._compilations)if(p(y,m))return y}t.getCompilingSchema=d;function p(m,y){return m.schema===y.schema&&m.root===y.root&&m.baseId===y.baseId}function f(m,y){let v;for(;typeof(v=this.refs[y])=="string";)y=v;return v||this.schemas[y]||g.call(this,m,y)}function g(m,y){let v=this.opts.uriResolver.parse(y),b=(0,i._getFullPath)(this.opts.uriResolver,v),S=(0,i.getFullPath)(this.opts.uriResolver,m.baseId,void 0);if(Object.keys(m.schema).length>0&&b===S)return h.call(this,v,m);let x=(0,i.normalizeId)(b),w=this.refs[x]||this.schemas[x];if(typeof w=="string"){let k=g.call(this,m,w);return typeof k?.schema!="object"?void 0:h.call(this,v,k)}if(typeof w?.schema=="object"){if(w.validate||c.call(this,w),x===(0,i.normalizeId)(y)){let{schema:k}=w,{schemaId:O}=this.opts,A=k[O];return A&&(S=(0,i.resolveUrl)(this.opts.uriResolver,S,A)),new s({schema:k,schemaId:O,root:m,baseId:S})}return h.call(this,v,w)}}t.resolveSchema=g;var _=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function h(m,{baseId:y,schema:v,root:b}){var S;if(((S=m.fragment)===null||S===void 0?void 0:S[0])!=="/")return;for(let k of m.fragment.slice(1).split("/")){if(typeof v=="boolean")return;let O=v[(0,a.unescapeFragment)(k)];if(O===void 0)return;v=O;let A=typeof v=="object"&&v[this.opts.schemaId];!_.has(k)&&A&&(y=(0,i.resolveUrl)(this.opts.uriResolver,y,A))}let x;if(typeof v!="boolean"&&v.$ref&&!(0,a.schemaHasRulesButRef)(v,this.RULES)){let k=(0,i.resolveUrl)(this.opts.uriResolver,y,v.$ref);x=g.call(this,b,k)}let{schemaId:w}=this.opts;if(x=x||new s({schema:v,schemaId:w,root:b,baseId:y}),x.schema!==x.root.schema)return x}}),Sae=V((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}}),wae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=q2();e.code='require("ajv/dist/runtime/uri").default',t.default=e}),$ae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var e=ig();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var r=Ve();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=B$(),i=ag(),a=B2(),o=V$(),s=Ve(),c=ng(),u=Hh(),l=pt(),d=Sae(),p=wae(),f=(F,I)=>new RegExp(F,I);f.code="new RegExp";var g=["removeAdditional","useDefaults","coerceTypes"],_=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),h={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."},m={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},y=200;function v(F){var I,D,C,$,T,N,W,K,pe,ce,je,P,R,z,Z,J,ie,tt,Ht,yt,_t,rt,en,jt,Na;let An=F.strict,ja=(I=F.code)===null||I===void 0?void 0:I.optimize,Ac=ja===!0||ja===void 0?1:ja||0,Mc=(C=(D=F.code)===null||D===void 0?void 0:D.regExp)!==null&&C!==void 0?C:f,Gg=($=F.uriResolver)!==null&&$!==void 0?$:p.default;return{strictSchema:(N=(T=F.strictSchema)!==null&&T!==void 0?T:An)!==null&&N!==void 0?N:!0,strictNumbers:(K=(W=F.strictNumbers)!==null&&W!==void 0?W:An)!==null&&K!==void 0?K:!0,strictTypes:(ce=(pe=F.strictTypes)!==null&&pe!==void 0?pe:An)!==null&&ce!==void 0?ce:"log",strictTuples:(P=(je=F.strictTuples)!==null&&je!==void 0?je:An)!==null&&P!==void 0?P:"log",strictRequired:(z=(R=F.strictRequired)!==null&&R!==void 0?R:An)!==null&&z!==void 0?z:!1,code:F.code?{...F.code,optimize:Ac,regExp:Mc}:{optimize:Ac,regExp:Mc},loopRequired:(Z=F.loopRequired)!==null&&Z!==void 0?Z:y,loopEnum:(J=F.loopEnum)!==null&&J!==void 0?J:y,meta:(ie=F.meta)!==null&&ie!==void 0?ie:!0,messages:(tt=F.messages)!==null&&tt!==void 0?tt:!0,inlineRefs:(Ht=F.inlineRefs)!==null&&Ht!==void 0?Ht:!0,schemaId:(yt=F.schemaId)!==null&&yt!==void 0?yt:"$id",addUsedSchema:(_t=F.addUsedSchema)!==null&&_t!==void 0?_t:!0,validateSchema:(rt=F.validateSchema)!==null&&rt!==void 0?rt:!0,validateFormats:(en=F.validateFormats)!==null&&en!==void 0?en:!0,unicodeRegExp:(jt=F.unicodeRegExp)!==null&&jt!==void 0?jt:!0,int32range:(Na=F.int32range)!==null&&Na!==void 0?Na:!0,uriResolver:Gg}}class b{constructor(I={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,I=this.opts={...I,...v(I)};let{es5:D,lines:C}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:_,es5:D,lines:C}),this.logger=L(I.logger);let $=I.validateFormats;I.validateFormats=!1,this.RULES=(0,a.getRules)(),S.call(this,h,I,"NOT SUPPORTED"),S.call(this,m,I,"DEPRECATED","warn"),this._metaOpts=A.call(this),I.formats&&k.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),I.keywords&&O.call(this,I.keywords),typeof I.meta=="object"&&this.addMetaSchema(I.meta),w.call(this),I.validateFormats=$}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:I,meta:D,schemaId:C}=this.opts,$=d;C==="id"&&($={...d},$.id=$.$id,delete $.$id),D&&I&&this.addMetaSchema($,$[C],!1)}defaultMeta(){let{meta:I,schemaId:D}=this.opts;return this.opts.defaultMeta=typeof I=="object"?I[D]||I:void 0}validate(I,D){let C;if(typeof I=="string"){if(C=this.getSchema(I),!C)throw new Error(`no schema with key or ref "${I}"`)}else C=this.compile(I);let $=C(D);return"$async"in C||(this.errors=C.errors),$}compile(I,D){let C=this._addSchema(I,D);return C.validate||this._compileSchemaEnv(C)}compileAsync(I,D){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:C}=this.opts;return $.call(this,I,D);async function $(ce,je){await T.call(this,ce.$schema);let P=this._addSchema(ce,je);return P.validate||N.call(this,P)}async function T(ce){ce&&!this.getSchema(ce)&&await $.call(this,{$ref:ce},!0)}async function N(ce){try{return this._compileSchemaEnv(ce)}catch(je){if(!(je instanceof i.default))throw je;return W.call(this,je),await K.call(this,je.missingSchema),N.call(this,ce)}}function W({missingSchema:ce,missingRef:je}){if(this.refs[ce])throw new Error(`AnySchema ${ce} is loaded but ${je} cannot be resolved`)}async function K(ce){let je=await pe.call(this,ce);this.refs[ce]||await T.call(this,je.$schema),this.refs[ce]||this.addSchema(je,ce,D)}async function pe(ce){let je=this._loading[ce];if(je)return je;try{return await(this._loading[ce]=C(ce))}finally{delete this._loading[ce]}}}addSchema(I,D,C,$=this.opts.validateSchema){if(Array.isArray(I)){for(let N of I)this.addSchema(N,void 0,C,$);return this}let T;if(typeof I=="object"){let{schemaId:N}=this.opts;if(T=I[N],T!==void 0&&typeof T!="string")throw new Error(`schema ${N} must be string`)}return D=(0,c.normalizeId)(D||T),this._checkUnique(D),this.schemas[D]=this._addSchema(I,C,D,$,!0),this}addMetaSchema(I,D,C=this.opts.validateSchema){return this.addSchema(I,D,!0,C),this}validateSchema(I,D){if(typeof I=="boolean")return!0;let C;if(C=I.$schema,C!==void 0&&typeof C!="string")throw new Error("$schema must be a string");if(C=C||this.opts.defaultMeta||this.defaultMeta(),!C)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let $=this.validate(C,I);if(!$&&D){let T="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(T);else throw new Error(T)}return $}getSchema(I){let D;for(;typeof(D=x.call(this,I))=="string";)I=D;if(D===void 0){let{schemaId:C}=this.opts,$=new o.SchemaEnv({schema:{},schemaId:C});if(D=o.resolveSchema.call(this,$,I),!D)return;this.refs[I]=D}return D.validate||this._compileSchemaEnv(D)}removeSchema(I){if(I instanceof RegExp)return this._removeAllSchemas(this.schemas,I),this._removeAllSchemas(this.refs,I),this;switch(typeof I){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let D=x.call(this,I);return typeof D=="object"&&this._cache.delete(D.schema),delete this.schemas[I],delete this.refs[I],this}case"object":{let D=I;this._cache.delete(D);let C=I[this.opts.schemaId];return C&&(C=(0,c.normalizeId)(C),delete this.schemas[C],delete this.refs[C]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(I){for(let D of I)this.addKeyword(D);return this}addKeyword(I,D){let C;if(typeof I=="string")C=I,typeof D=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),D.keyword=C);else if(typeof I=="object"&&D===void 0){if(D=I,C=D.keyword,Array.isArray(C)&&!C.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(U.call(this,C,D),!D)return(0,l.eachItem)(C,T=>Y.call(this,T)),this;et.call(this,D);let $={...D,type:(0,u.getJSONTypes)(D.type),schemaType:(0,u.getJSONTypes)(D.schemaType)};return(0,l.eachItem)(C,$.type.length===0?T=>Y.call(this,T,$):T=>$.type.forEach(N=>Y.call(this,T,$,N))),this}getKeyword(I){let D=this.RULES.all[I];return typeof D=="object"?D.definition:!!D}removeKeyword(I){let{RULES:D}=this;delete D.keywords[I],delete D.all[I];for(let C of D.rules){let $=C.rules.findIndex(T=>T.keyword===I);$>=0&&C.rules.splice($,1)}return this}addFormat(I,D){return typeof D=="string"&&(D=new RegExp(D)),this.formats[I]=D,this}errorsText(I=this.errors,{separator:D=", ",dataVar:C="data"}={}){return!I||I.length===0?"No errors":I.map($=>`${C}${$.instancePath} ${$.message}`).reduce(($,T)=>$+D+T)}$dataMetaSchema(I,D){let C=this.RULES.all;I=JSON.parse(JSON.stringify(I));for(let $ of D){let T=$.split("/").slice(1),N=I;for(let W of T)N=N[W];for(let W in C){let K=C[W];if(typeof K!="object")continue;let{$data:pe}=K.definition,ce=N[W];pe&&ce&&(N[W]=fe(ce))}}return I}_removeAllSchemas(I,D){for(let C in I){let $=I[C];(!D||D.test(C))&&(typeof $=="string"?delete I[C]:$&&!$.meta&&(this._cache.delete($.schema),delete I[C]))}}_addSchema(I,D,C,$=this.opts.validateSchema,T=this.opts.addUsedSchema){let N,{schemaId:W}=this.opts;if(typeof I=="object")N=I[W];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof I!="boolean")throw new Error("schema must be object or boolean")}let K=this._cache.get(I);if(K!==void 0)return K;C=(0,c.normalizeId)(N||C);let pe=c.getSchemaRefs.call(this,I,C);return K=new o.SchemaEnv({schema:I,schemaId:W,meta:D,baseId:C,localRefs:pe}),this._cache.set(K.schema,K),T&&!C.startsWith("#")&&(C&&this._checkUnique(C),this.refs[C]=K),$&&this.validateSchema(I,!0),K}_checkUnique(I){if(this.schemas[I]||this.refs[I])throw new Error(`schema with key or id "${I}" already exists`)}_compileSchemaEnv(I){if(I.meta?this._compileMetaSchema(I):o.compileSchema.call(this,I),!I.validate)throw new Error("ajv implementation error");return I.validate}_compileMetaSchema(I){let D=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,I)}finally{this.opts=D}}}b.ValidationError=n.default,b.MissingRefError=i.default,t.default=b;function S(F,I,D,C="error"){for(let $ in F){let T=$;T in I&&this.logger[C](`${D}: option ${$}. ${F[T]}`)}}function x(F){return F=(0,c.normalizeId)(F),this.schemas[F]||this.refs[F]}function w(){let F=this.opts.schemas;if(F)if(Array.isArray(F))this.addSchema(F);else for(let I in F)this.addSchema(F[I],I)}function k(){for(let F in this.opts.formats){let I=this.opts.formats[F];I&&this.addFormat(F,I)}}function O(F){if(Array.isArray(F)){this.addVocabulary(F);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let I in F){let D=F[I];D.keyword||(D.keyword=I),this.addKeyword(D)}}function A(){let F={...this.opts};for(let I of g)delete F[I];return F}var M={log(){},warn(){},error(){}};function L(F){if(F===!1)return M;if(F===void 0)return console;if(F.log&&F.warn&&F.error)return F;throw new Error("logger must implement log, warn and error methods")}var B=/^[a-z_$][a-z0-9_$:-]*$/i;function U(F,I){let{RULES:D}=this;if((0,l.eachItem)(F,C=>{if(D.keywords[C])throw new Error(`Keyword ${C} is already defined`);if(!B.test(C))throw new Error(`Keyword ${C} has invalid name`)}),!!I&&I.$data&&!("code"in I||"validate"in I))throw new Error('$data keyword must have "code" or "validate" function')}function Y(F,I,D){var C;let $=I?.post;if(D&&$)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:T}=this,N=$?T.post:T.rules.find(({type:K})=>K===D);if(N||(N={type:D,rules:[]},T.rules.push(N)),T.keywords[F]=!0,!I)return;let W={keyword:F,definition:{...I,type:(0,u.getJSONTypes)(I.type),schemaType:(0,u.getJSONTypes)(I.schemaType)}};I.before?me.call(this,N,W,I.before):N.rules.push(W),T.all[F]=W,(C=I.implements)===null||C===void 0||C.forEach(K=>this.addKeyword(K))}function me(F,I,D){let C=F.rules.findIndex($=>$.keyword===D);C>=0?F.rules.splice(C,0,I):(F.rules.push(I),this.logger.warn(`rule ${D} is not defined`))}function et(F){let{metaSchema:I}=F;I!==void 0&&(F.$data&&this.opts.$data&&(I=fe(I)),F.validateSchema=this.compile(I,!0))}var ht={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function fe(F){return{anyOf:[F,ht]}}}),Eae=V(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}),kae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.callRef=t.getValidate=void 0;var e=ag(),r=ri(),n=Ve(),i=Ra(),a=V$(),o=pt(),s={keyword:"$ref",schemaType:"string",code(l){let{gen:d,schema:p,it:f}=l,{baseId:g,schemaEnv:_,validateName:h,opts:m,self:y}=f,{root:v}=_;if((p==="#"||p==="#/")&&g===v.baseId)return S();let b=a.resolveRef.call(y,v,g,p);if(b===void 0)throw new e.default(f.opts.uriResolver,g,p);if(b instanceof a.SchemaEnv)return x(b);return w(b);function S(){if(_===v)return u(l,h,_,_.$async);let k=d.scopeValue("root",{ref:v});return u(l,(0,n._)`${k}.validate`,v,v.$async)}function x(k){let O=c(l,k);u(l,O,k,k.$async)}function w(k){let O=d.scopeValue("schema",m.code.source===!0?{ref:k,code:(0,n.stringify)(k)}:{ref:k}),A=d.name("valid"),M=l.subschema({schema:k,dataTypes:[],schemaPath:n.nil,topSchemaRef:O,errSchemaPath:p},A);l.mergeEvaluated(M),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:g,it:_}=l,{allErrors:h,schemaEnv:m,opts:y}=_,v=y.passContext?i.default.this:n.nil;f?b():S();function b(){if(!m.$async)throw new Error("async schema referenced by sync schema");let k=g.let("valid");g.try(()=>{g.code((0,n._)`await ${(0,r.callValidateCode)(l,d,v)}`),w(d),h||g.assign(k,!0)},O=>{g.if((0,n._)`!(${O} instanceof ${_.ValidationError})`,()=>g.throw(O)),x(O),h||g.assign(k,!1)}),l.ok(k)}function S(){l.result((0,r.callValidateCode)(l,d,v),()=>w(d),()=>x(d))}function x(k){let O=(0,n._)`${k}.errors`;g.assign(i.default.vErrors,(0,n._)`${i.default.vErrors} === null ? ${O} : ${i.default.vErrors}.concat(${O})`),g.assign(i.default.errors,(0,n._)`${i.default.vErrors}.length`)}function w(k){var O;if(!_.opts.unevaluated)return;let A=(O=p?.validate)===null||O===void 0?void 0:O.evaluated;if(_.props!==!0)if(A&&!A.dynamicProps)A.props!==void 0&&(_.props=o.mergeEvaluated.props(g,A.props,_.props));else{let M=g.var("props",(0,n._)`${k}.evaluated.props`);_.props=o.mergeEvaluated.props(g,M,_.props,n.Name)}if(_.items!==!0)if(A&&!A.dynamicItems)A.items!==void 0&&(_.items=o.mergeEvaluated.items(g,A.items,_.items));else{let M=g.var("items",(0,n._)`${k}.evaluated.items`);_.items=o.mergeEvaluated.items(g,M,_.items,n.Name)}}}t.callRef=u,t.default=s}),Tae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Eae(),r=kae(),n=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,r.default];t.default=n}),Iae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),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:s})=>(0,e.str)`must be ${n[o].okStr} ${s}`,params:({keyword:o,schemaCode:s})=>(0,e._)`{comparison: ${n[o].okStr}, limit: ${s}}`},a={keyword:Object.keys(n),type:"number",schemaType:"number",$data:!0,error:i,code(o){let{keyword:s,data:c,schemaCode:u}=o;o.fail$data((0,e._)`${c} ${n[s].fail} ${u} || isNaN(${c})`)}};t.default=a}),Pae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),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:a,data:o,schemaCode:s,it:c}=i,u=c.opts.multipleOfPrecision,l=a.let("res"),d=u?(0,e._)`Math.abs(Math.round(${l}) - ${l}) > 1e-${u}`:(0,e._)`${l} !== parseInt(${l})`;i.fail$data((0,e._)`(${s} === 0 || (${l} = ${o}/${s}, ${d}))`)}};t.default=n}),Oae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});function e(r){let n=r.length,i=0,a=0,o;for(;a=55296&&o<=56319&&a{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),r=pt(),n=Oae(),i={message({keyword:o,schemaCode:s}){let c=o==="maxLength"?"more":"fewer";return(0,e.str)`must NOT have ${c} than ${s} characters`},params:({schemaCode:o})=>(0,e._)`{limit: ${o}}`},a={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:i,code(o){let{keyword:s,data:c,schemaCode:u,it:l}=o,d=s==="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=a}),Cae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ri(),r=Ve(),n={message:({schemaCode:a})=>(0,r.str)`must match pattern "${a}"`,params:({schemaCode:a})=>(0,r._)`{pattern: ${a}}`},i={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:n,code(a){let{data:o,$data:s,schema:c,schemaCode:u,it:l}=a,d=l.opts.unicodeRegExp?"u":"",p=s?(0,r._)`(new RegExp(${u}, ${d}))`:(0,e.usePattern)(a,c);a.fail$data((0,r._)`!${p}.test(${o})`)}};t.default=i}),Nae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),r={message({keyword:i,schemaCode:a}){let o=i==="maxProperties"?"more":"fewer";return(0,e.str)`must NOT have ${o} than ${a} properties`},params:({schemaCode:i})=>(0,e._)`{limit: ${i}}`},n={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:r,code(i){let{keyword:a,data:o,schemaCode:s}=i,c=a==="maxProperties"?e.operators.GT:e.operators.LT;i.fail$data((0,e._)`Object.keys(${o}).length ${c} ${s}`)}};t.default=n}),jae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ri(),r=Ve(),n=pt(),i={message:({params:{missingProperty:o}})=>(0,r.str)`must have required property '${o}'`,params:({params:{missingProperty:o}})=>(0,r._)`{missingProperty: ${o}}`},a={keyword:"required",type:"object",schemaType:"array",$data:!0,error:i,code(o){let{gen:s,schema:c,schemaCode:u,data:l,$data:d,it:p}=o,{opts:f}=p;if(!d&&c.length===0)return;let g=c.length>=f.loopRequired;if(p.allErrors?_():h(),f.strictRequired){let v=o.parentSchema.properties,{definedProperties:b}=o.it;for(let S of c)if(v?.[S]===void 0&&!b.has(S)){let x=p.schemaEnv.baseId+p.errSchemaPath,w=`required property "${S}" is not defined at "${x}" (strictRequired)`;(0,n.checkStrictMode)(p,w,p.opts.strictRequired)}}function _(){if(g||d)o.block$data(r.nil,m);else for(let v of c)(0,e.checkReportMissingProp)(o,v)}function h(){let v=s.let("missing");if(g||d){let b=s.let("valid",!0);o.block$data(b,()=>y(v,b)),o.ok(b)}else s.if((0,e.checkMissingProp)(o,c,v)),(0,e.reportMissingProp)(o,v),s.else()}function m(){s.forOf("prop",u,v=>{o.setParams({missingProperty:v}),s.if((0,e.noPropertyInData)(s,l,v,f.ownProperties),()=>o.error())})}function y(v,b){o.setParams({missingProperty:v}),s.forOf(v,u,()=>{s.assign(b,(0,e.propertyInData)(s,l,v,f.ownProperties)),s.if((0,r.not)(b),()=>{o.error(),s.break()})},r.nil)}}};t.default=a}),Aae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),r={message({keyword:i,schemaCode:a}){let o=i==="maxItems"?"more":"fewer";return(0,e.str)`must NOT have ${o} than ${a} items`},params:({schemaCode:i})=>(0,e._)`{limit: ${i}}`},n={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:r,code(i){let{keyword:a,data:o,schemaCode:s}=i,c=a==="maxItems"?e.operators.GT:e.operators.LT;i.fail$data((0,e._)`${o}.length ${c} ${s}`)}};t.default=n}),G$=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Yh();e.code='require("ajv/dist/runtime/equal").default',t.default=e}),Mae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Hh(),r=Ve(),n=pt(),i=G$(),a={message:({params:{i:s,j:c}})=>(0,r.str)`must NOT have duplicate items (items ## ${c} and ${s} are identical)`,params:({params:{i:s,j:c}})=>(0,r._)`{i: ${s}, j: ${c}}`},o={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:a,code(s){let{gen:c,data:u,$data:l,schema:d,parentSchema:p,schemaCode:f,it:g}=s;if(!l&&!d)return;let _=c.let("valid"),h=p.items?(0,e.getSchemaTypes)(p.items):[];s.block$data(_,m,(0,r._)`${f} === false`),s.ok(_);function m(){let S=c.let("i",(0,r._)`${u}.length`),x=c.let("j");s.setParams({i:S,j:x}),c.assign(_,!0),c.if((0,r._)`${S} > 1`,()=>(y()?v:b)(S,x))}function y(){return h.length>0&&!h.some(S=>S==="object"||S==="array")}function v(S,x){let w=c.name("item"),k=(0,e.checkDataTypes)(h,w,g.opts.strictNumbers,e.DataType.Wrong),O=c.const("indices",(0,r._)`{}`);c.for((0,r._)`;${S}--;`,()=>{c.let(w,(0,r._)`${u}[${S}]`),c.if(k,(0,r._)`continue`),h.length>1&&c.if((0,r._)`typeof ${w} == "string"`,(0,r._)`${w} += "_"`),c.if((0,r._)`typeof ${O}[${w}] == "number"`,()=>{c.assign(x,(0,r._)`${O}[${w}]`),s.error(),c.assign(_,!1).break()}).code((0,r._)`${O}[${w}] = ${S}`)})}function b(S,x){let w=(0,n.useFunc)(c,i.default),k=c.name("outer");c.label(k).for((0,r._)`;${S}--;`,()=>c.for((0,r._)`${x} = ${S}; ${x}--;`,()=>c.if((0,r._)`${w}(${u}[${S}], ${u}[${x}])`,()=>{s.error(),c.assign(_,!1).break(k)})))}}};t.default=o}),Dae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),r=pt(),n=G$(),i={message:"must be equal to constant",params:({schemaCode:o})=>(0,e._)`{allowedValue: ${o}}`},a={keyword:"const",$data:!0,error:i,code(o){let{gen:s,data:c,$data:u,schemaCode:l,schema:d}=o;u||d&&typeof d=="object"?o.fail$data((0,e._)`!${(0,r.useFunc)(s,n.default)}(${c}, ${l})`):o.fail((0,e._)`${d} !== ${c}`)}};t.default=a}),zae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),r=pt(),n=G$(),i={message:"must be equal to one of the allowed values",params:({schemaCode:o})=>(0,e._)`{allowedValues: ${o}}`},a={keyword:"enum",schemaType:"array",$data:!0,error:i,code(o){let{gen:s,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,g,_=()=>g??(g=(0,r.useFunc)(s,n.default)),h;if(f||u)h=s.let("valid"),o.block$data(h,m);else{if(!Array.isArray(l))throw new Error("ajv implementation error");let v=s.const("vSchema",d);h=(0,e.or)(...l.map((b,S)=>y(v,S)))}o.pass(h);function m(){s.assign(h,!1),s.forOf("v",d,v=>s.if((0,e._)`${_()}(${c}, ${v})`,()=>s.assign(h,!0).break()))}function y(v,b){let S=l[b];return typeof S=="object"&&S!==null?(0,e._)`${_()}(${c}, ${v}[${b}])`:(0,e._)`${c} === ${S}`}}};t.default=a}),Uae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Iae(),r=Pae(),n=Rae(),i=Cae(),a=Nae(),o=jae(),s=Aae(),c=Mae(),u=Dae(),l=zae(),d=[e.default,r.default,n.default,i.default,a.default,o.default,s.default,c.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},u.default,l.default];t.default=d}),G2=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateAdditionalItems=void 0;var e=Ve(),r=pt(),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:s,it:c}=o,{items:u}=s;if(!Array.isArray(u)){(0,r.checkStrictMode)(c,'"additionalItems" is ignored when "items" is not an array of schemas');return}a(o,u)}};function a(o,s){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:s.length}),o.pass((0,e._)`${f} <= ${s.length}`);else if(typeof u=="object"&&!(0,r.alwaysValidSchema)(p,u)){let _=c.var("valid",(0,e._)`${f} <= ${s.length}`);c.if((0,e.not)(_),()=>g(_)),o.ok(_)}function g(_){c.forRange("i",s.length,f,h=>{o.subschema({keyword:d,dataProp:h,dataPropType:r.Type.Num},_),p.allErrors||c.if((0,e.not)(_),()=>c.break())})}}t.validateAdditionalItems=a,t.default=i}),W2=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateTuple=void 0;var e=Ve(),r=pt(),n=ri(),i={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(o){let{schema:s,it:c}=o;if(Array.isArray(s))return a(o,"additionalItems",s);c.items=!0,!(0,r.alwaysValidSchema)(c,s)&&o.ok((0,n.validateArray)(o))}};function a(o,s,c=o.schema){let{gen:u,parentSchema:l,data:d,keyword:p,it:f}=o;h(l),f.opts.unevaluated&&c.length&&f.items!==!0&&(f.items=r.mergeEvaluated.items(u,c.length,f.items));let g=u.name("valid"),_=u.const("len",(0,e._)`${d}.length`);c.forEach((m,y)=>{(0,r.alwaysValidSchema)(f,m)||(u.if((0,e._)`${_} > ${y}`,()=>o.subschema({keyword:p,schemaProp:y,dataProp:y},g)),o.ok(g))});function h(m){let{opts:y,errSchemaPath:v}=f,b=c.length,S=b===m.minItems&&(b===m.maxItems||m[s]===!1);if(y.strictTuples&&!S){let x=`"${p}" is ${b}-tuple, but minItems or maxItems/${s} are not specified or different at path "${v}"`;(0,r.checkStrictMode)(f,x,y.strictTuples)}}}t.validateTuple=a,t.default=i}),Lae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=W2(),r={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:n=>(0,e.validateTuple)(n,"items")};t.default=r}),qae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),r=pt(),n=ri(),i=G2(),a={message:({params:{len:s}})=>(0,e.str)`must NOT have more than ${s} items`,params:({params:{len:s}})=>(0,e._)`{limit: ${s}}`},o={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:a,code(s){let{schema:c,parentSchema:u,it:l}=s,{prefixItems:d}=u;l.items=!0,!(0,r.alwaysValidSchema)(l,c)&&(d?(0,i.validateAdditionalItems)(s,d):s.ok((0,n.validateArray)(s)))}};t.default=o}),Fae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),r=pt(),n={message:({params:{min:a,max:o}})=>o===void 0?(0,e.str)`must contain at least ${a} valid item(s)`:(0,e.str)`must contain at least ${a} and no more than ${o} valid item(s)`,params:({params:{min:a,max:o}})=>o===void 0?(0,e._)`{minContains: ${a}}`:(0,e._)`{minContains: ${a}, maxContains: ${o}}`},i={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:n,code(a){let{gen:o,schema:s,parentSchema:c,data:u,it:l}=a,d,p,{minContains:f,maxContains:g}=c;l.opts.next?(d=f===void 0?1:f,p=g):d=1;let _=o.const("len",(0,e._)`${u}.length`);if(a.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'),a.fail();return}if((0,r.alwaysValidSchema)(l,s)){let b=(0,e._)`${_} >= ${d}`;p!==void 0&&(b=(0,e._)`${b} && ${_} <= ${p}`),a.pass(b);return}l.items=!0;let h=o.name("valid");p===void 0&&d===1?y(h,()=>o.if(h,()=>o.break())):d===0?(o.let(h,!0),p!==void 0&&o.if((0,e._)`${u}.length > 0`,m)):(o.let(h,!1),m()),a.result(h,()=>a.reset());function m(){let b=o.name("_valid"),S=o.let("count",0);y(b,()=>o.if(b,()=>v(S)))}function y(b,S){o.forRange("i",0,_,x=>{a.subschema({keyword:"contains",dataProp:x,dataPropType:r.Type.Num,compositeRule:!0},b),S()})}function v(b){o.code((0,e._)`${b}++`),p===void 0?o.if((0,e._)`${b} >= ${d}`,()=>o.assign(h,!0).break()):(o.if((0,e._)`${b} > ${p}`,()=>o.assign(h,!1).break()),d===1?o.assign(h,!0):o.if((0,e._)`${b} >= ${d}`,()=>o.assign(h,!0)))}}};t.default=i}),Zae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;var e=Ve(),r=pt(),n=ri();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]=a(c);o(c,u),s(c,l)}};function a({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 g in u){let _=u[g];if(_.length===0)continue;let h=(0,n.propertyInData)(l,d,g,p.opts.ownProperties);c.setParams({property:g,depsCount:_.length,deps:_.join(", ")}),p.allErrors?l.if(h,()=>{for(let m of _)(0,n.checkReportMissingProp)(c,m)}):(l.if((0,e._)`${h} && (${(0,n.checkMissingProp)(c,_,f)})`),(0,n.reportMissingProp)(c,f),l.else())}}t.validatePropertyDeps=o;function s(c,u=c.schema){let{gen:l,data:d,keyword:p,it:f}=c,g=l.name("valid");for(let _ in u)(0,r.alwaysValidSchema)(f,u[_])||(l.if((0,n.propertyInData)(l,d,_,f.opts.ownProperties),()=>{let h=c.subschema({keyword:p,schemaProp:_},g);c.mergeValidEvaluated(h,g)},()=>l.var(g,!0)),c.ok(g))}t.validateSchemaDeps=s,t.default=i}),Hae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),r=pt(),n={message:"property name must be valid",params:({params:a})=>(0,e._)`{propertyName: ${a.propertyName}}`},i={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:n,code(a){let{gen:o,schema:s,data:c,it:u}=a;if((0,r.alwaysValidSchema)(u,s))return;let l=o.name("valid");o.forIn("key",c,d=>{a.setParams({propertyName:d}),a.subschema({keyword:"propertyNames",data:d,dataTypes:["string"],propertyName:d,compositeRule:!0},l),o.if((0,e.not)(l),()=>{a.error(!0),u.allErrors||o.break()})}),a.ok(l)}};t.default=i}),K2=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ri(),r=Ve(),n=Ra(),i=pt(),a={message:"must NOT have additional properties",params:({params:s})=>(0,r._)`{additionalProperty: ${s.additionalProperty}}`},o={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:a,code(s){let{gen:c,schema:u,parentSchema:l,data:d,errsCount:p,it:f}=s;if(!p)throw new Error("ajv implementation error");let{allErrors:g,opts:_}=f;if(f.props=!0,_.removeAdditional!=="all"&&(0,i.alwaysValidSchema)(f,u))return;let h=(0,e.allSchemaProperties)(l.properties),m=(0,e.allSchemaProperties)(l.patternProperties);y(),s.ok((0,r._)`${p} === ${n.default.errors}`);function y(){c.forIn("key",d,w=>{!h.length&&!m.length?S(w):c.if(v(w),()=>S(w))})}function v(w){let k;if(h.length>8){let O=(0,i.schemaRefOrVal)(f,l.properties,"properties");k=(0,e.isOwnProperty)(c,O,w)}else h.length?k=(0,r.or)(...h.map(O=>(0,r._)`${w} === ${O}`)):k=r.nil;return m.length&&(k=(0,r.or)(k,...m.map(O=>(0,r._)`${(0,e.usePattern)(s,O)}.test(${w})`))),(0,r.not)(k)}function b(w){c.code((0,r._)`delete ${d}[${w}]`)}function S(w){if(_.removeAdditional==="all"||_.removeAdditional&&u===!1){b(w);return}if(u===!1){s.setParams({additionalProperty:w}),s.error(),g||c.break();return}if(typeof u=="object"&&!(0,i.alwaysValidSchema)(f,u)){let k=c.name("valid");_.removeAdditional==="failing"?(x(w,k,!1),c.if((0,r.not)(k),()=>{s.reset(),b(w)})):(x(w,k),g||c.if((0,r.not)(k),()=>c.break()))}}function x(w,k,O){let A={keyword:"additionalProperties",dataProp:w,dataPropType:i.Type.Str};O===!1&&Object.assign(A,{compositeRule:!0,createErrors:!1,allErrors:!1}),s.subschema(A,k)}}};t.default=o}),Bae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ig(),r=ri(),n=pt(),i=K2(),a={keyword:"properties",type:"object",schemaType:"object",code(o){let{gen:s,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 m of p)d.definedProperties.add(m);d.opts.unevaluated&&p.length&&d.props!==!0&&(d.props=n.mergeEvaluated.props(s,(0,n.toHash)(p),d.props));let f=p.filter(m=>!(0,n.alwaysValidSchema)(d,c[m]));if(f.length===0)return;let g=s.name("valid");for(let m of f)_(m)?h(m):(s.if((0,r.propertyInData)(s,l,m,d.opts.ownProperties)),h(m),d.allErrors||s.else().var(g,!0),s.endIf()),o.it.definedProperties.add(m),o.ok(g);function _(m){return d.opts.useDefaults&&!d.compositeRule&&c[m].default!==void 0}function h(m){o.subschema({keyword:"properties",schemaProp:m,dataProp:m},g)}}};t.default=a}),Vae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ri(),r=Ve(),n=pt(),i=pt(),a={keyword:"patternProperties",type:"object",schemaType:"object",code(o){let{gen:s,schema:c,data:u,parentSchema:l,it:d}=o,{opts:p}=d,f=(0,e.allSchemaProperties)(c),g=f.filter(S=>(0,n.alwaysValidSchema)(d,c[S]));if(f.length===0||g.length===f.length&&(!d.opts.unevaluated||d.props===!0))return;let _=p.strictSchema&&!p.allowMatchingProperties&&l.properties,h=s.name("valid");d.props!==!0&&!(d.props instanceof r.Name)&&(d.props=(0,i.evaluatedPropsToName)(s,d.props));let{props:m}=d;y();function y(){for(let S of f)_&&v(S),d.allErrors?b(S):(s.var(h,!0),b(S),s.if(h))}function v(S){for(let x in _)new RegExp(S).test(x)&&(0,n.checkStrictMode)(d,`property ${x} matches pattern ${S} (use allowMatchingProperties)`)}function b(S){s.forIn("key",u,x=>{s.if((0,r._)`${(0,e.usePattern)(o,S)}.test(${x})`,()=>{let w=g.includes(S);w||o.subschema({keyword:"patternProperties",schemaProp:S,dataProp:x,dataPropType:i.Type.Str},h),d.opts.unevaluated&&m!==!0?s.assign((0,r._)`${m}[${x}]`,!0):!w&&!d.allErrors&&s.if((0,r.not)(h),()=>s.break())})})}}};t.default=a}),Gae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=pt(),r={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(n){let{gen:i,schema:a,it:o}=n;if((0,e.alwaysValidSchema)(o,a)){n.fail();return}let s=i.name("valid");n.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),n.failResult(s,()=>n.reset(),()=>n.error())},error:{message:"must NOT be valid"}};t.default=r}),Wae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ri(),r={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:e.validateUnion,error:{message:"must match a schema in anyOf"}};t.default=r}),Kae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),r=pt(),n={message:"must match exactly one schema in oneOf",params:({params:a})=>(0,e._)`{passingSchemas: ${a.passing}}`},i={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:n,code(a){let{gen:o,schema:s,parentSchema:c,it:u}=a;if(!Array.isArray(s))throw new Error("ajv implementation error");if(u.opts.discriminator&&c.discriminator)return;let l=s,d=o.let("valid",!1),p=o.let("passing",null),f=o.name("_valid");a.setParams({passing:p}),o.block(g),a.result(d,()=>a.reset(),()=>a.error(!0));function g(){l.forEach((_,h)=>{let m;(0,r.alwaysValidSchema)(u,_)?o.var(f,!0):m=a.subschema({keyword:"oneOf",schemaProp:h,compositeRule:!0},f),h>0&&o.if((0,e._)`${f} && ${d}`).assign(d,!1).assign(p,(0,e._)`[${p}, ${h}]`).else(),o.if(f,()=>{o.assign(d,!0),o.assign(p,h),m&&a.mergeEvaluated(m,e.Name)})})}}};t.default=i}),Jae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=pt(),r={keyword:"allOf",schemaType:"array",code(n){let{gen:i,schema:a,it:o}=n;if(!Array.isArray(a))throw new Error("ajv implementation error");let s=i.name("valid");a.forEach((c,u)=>{if((0,e.alwaysValidSchema)(o,c))return;let l=n.subschema({keyword:"allOf",schemaProp:u},s);n.ok(s),n.mergeEvaluated(l)})}};t.default=r}),Xae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),r=pt(),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:s,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=a(u,"then"),d=a(u,"else");if(!l&&!d)return;let p=s.let("valid",!0),f=s.name("_valid");if(g(),o.reset(),l&&d){let h=s.let("ifClause");o.setParams({ifClause:h}),s.if(f,_("then",h),_("else",h))}else l?s.if(f,_("then")):s.if((0,e.not)(f),_("else"));o.pass(p,()=>o.error(!0));function g(){let h=o.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},f);o.mergeEvaluated(h)}function _(h,m){return()=>{let y=o.subschema({keyword:h},f);s.assign(p,f),o.mergeValidEvaluated(y,p),m?s.assign(m,(0,e._)`${h}`):o.setParams({ifClause:h})}}}};function a(o,s){let c=o.schema[s];return c!==void 0&&!(0,r.alwaysValidSchema)(o,c)}t.default=i}),Yae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=pt(),r={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:n,parentSchema:i,it:a}){i.if===void 0&&(0,e.checkStrictMode)(a,`"${n}" without "if" is ignored`)}};t.default=r}),Qae=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=G2(),r=Lae(),n=W2(),i=qae(),a=Fae(),o=Zae(),s=Hae(),c=K2(),u=Bae(),l=Vae(),d=Gae(),p=Wae(),f=Kae(),g=Jae(),_=Xae(),h=Yae();function m(y=!1){let v=[d.default,p.default,f.default,g.default,_.default,h.default,s.default,c.default,o.default,u.default,l.default];return y?v.push(r.default,i.default):v.push(e.default,n.default),v.push(a.default),v}t.default=m}),eoe=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),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,a){let{gen:o,data:s,$data:c,schema:u,schemaCode:l,it:d}=i,{opts:p,errSchemaPath:f,schemaEnv:g,self:_}=d;if(!p.validateFormats)return;c?h():m();function h(){let y=o.scopeValue("formats",{ref:_.formats,code:p.code.formats}),v=o.const("fDef",(0,e._)`${y}[${l}]`),b=o.let("fType"),S=o.let("format");o.if((0,e._)`typeof ${v} == "object" && !(${v} instanceof RegExp)`,()=>o.assign(b,(0,e._)`${v}.type || "string"`).assign(S,(0,e._)`${v}.validate`),()=>o.assign(b,(0,e._)`"string"`).assign(S,v)),i.fail$data((0,e.or)(x(),w()));function x(){return p.strictSchema===!1?e.nil:(0,e._)`${l} && !${S}`}function w(){let k=g.$async?(0,e._)`(${v}.async ? await ${S}(${s}) : ${S}(${s}))`:(0,e._)`${S}(${s})`,O=(0,e._)`(typeof ${S} == "function" ? ${k} : ${S}.test(${s}))`;return(0,e._)`${S} && ${S} !== true && ${b} === ${a} && !${O}`}}function m(){let y=_.formats[u];if(!y){x();return}if(y===!0)return;let[v,b,S]=w(y);v===a&&i.pass(k());function x(){if(p.strictSchema===!1){_.logger.warn(O());return}throw new Error(O());function O(){return`unknown format "${u}" ignored in schema at path "${f}"`}}function w(O){let A=O instanceof RegExp?(0,e.regexpCode)(O):p.code.formats?(0,e._)`${p.code.formats}${(0,e.getProperty)(u)}`:void 0,M=o.scopeValue("formats",{key:u,ref:O,code:A});return typeof O=="object"&&!(O instanceof RegExp)?[O.type||"string",O.validate,(0,e._)`${M}.validate`]:["string",O,M]}function k(){if(typeof y=="object"&&!(y instanceof RegExp)&&y.async){if(!g.$async)throw new Error("async format in sync schema");return(0,e._)`await ${S}(${s})`}return typeof b=="function"?(0,e._)`${S}(${s})`:(0,e._)`${S}.test(${s})`}}}};t.default=n}),toe=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=eoe(),r=[e.default];t.default=r}),roe=V(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"]}),noe=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Tae(),r=Uae(),n=Qae(),i=toe(),a=roe(),o=[e.default,r.default,(0,n.default)(),i.default,a.metadataVocabulary,a.contentVocabulary];t.default=o}),ioe=V(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={}))}),aoe=V(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ve(),r=ioe(),n=V$(),i=ag(),a=pt(),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}}`},s={keyword:"discriminator",type:"object",schemaType:"object",error:o,code(c){let{gen:u,data:l,schema:d,parentSchema:p,it:f}=c,{oneOf:g}=p;if(!f.opts.discriminator)throw new Error("discriminator: requires discriminator option");let _=d.propertyName;if(typeof _!="string")throw new Error("discriminator: requires propertyName");if(d.mapping)throw new Error("discriminator: mapping is not supported");if(!g)throw new Error("discriminator: requires oneOf keyword");let h=u.let("valid",!1),m=u.const("tag",(0,e._)`${l}${(0,e.getProperty)(_)}`);u.if((0,e._)`typeof ${m} == "string"`,()=>y(),()=>c.error(!1,{discrError:r.DiscrError.Tag,tag:m,tagName:_})),c.ok(h);function y(){let S=b();u.if(!1);for(let x in S)u.elseIf((0,e._)`${m} === ${x}`),u.assign(h,v(S[x]));u.else(),c.error(!1,{discrError:r.DiscrError.Mapping,tag:m,tagName:_}),u.endIf()}function v(S){let x=u.name("valid"),w=c.subschema({keyword:"oneOf",schemaProp:S},x);return c.mergeEvaluated(w,e.Name),x}function b(){var S;let x={},w=O(p),k=!0;for(let L=0;L{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}}),soe=V((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=$ae(),n=noe(),i=aoe(),a=ooe(),o=["/properties"],s="http://json-schema.org/draft-07/schema";class c extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(g=>this.addVocabulary(g)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let g=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(g,s,!1),this.refs["http://json-schema.org/schema"]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var u=ig();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=Ve();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=B$();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var p=ag();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})}),coe=V(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.formatLimitDefinition=void 0;var e=soe(),r=Ve(),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}},a={message:({keyword:s,schemaCode:c})=>(0,r.str)`should be ${i[s].okStr} ${c}`,params:({keyword:s,schemaCode:c})=>(0,r._)`{comparison: ${i[s].okStr}, limit: ${c}}`};t.formatLimitDefinition={keyword:Object.keys(i),type:"string",schemaType:"string",$data:!0,error:a,code(s){let{gen:c,data:u,schemaCode:l,keyword:d,it:p}=s,{opts:f,self:g}=p;if(!f.validateFormats)return;let _=new e.KeywordCxt(p,g.RULES.all.format.definition,"format");_.$data?h():m();function h(){let v=c.scopeValue("formats",{ref:g.formats,code:f.code.formats}),b=c.const("fmt",(0,r._)`${v}[${_.schemaCode}]`);s.fail$data((0,r.or)((0,r._)`typeof ${b} != "object"`,(0,r._)`${b} instanceof RegExp`,(0,r._)`typeof ${b}.compare != "function"`,y(b)))}function m(){let v=_.schema,b=g.formats[v];if(!b||b===!0)return;if(typeof b!="object"||b instanceof RegExp||typeof b.compare!="function")throw new Error(`"${d}": format "${v}" does not define "compare" function`);let S=c.scopeValue("formats",{key:v,ref:b,code:f.code.formats?(0,r._)`${f.code.formats}${(0,r.getProperty)(v)}`:void 0});s.fail$data(y(S))}function y(v){return(0,r._)`${v}.compare(${u}, ${l}) ${i[d].fail} 0`}},dependencies:["format"]};var o=s=>(s.addKeyword(t.formatLimitDefinition),s);t.default=o}),uoe=V((t,e)=>{Object.defineProperty(t,"__esModule",{value:!0});var r=gae(),n=coe(),i=Ve(),a=new i.Name("fullFormats"),o=new i.Name("fastFormats"),s=(u,l={keywords:!0})=>{if(Array.isArray(l))return c(u,l,r.fullFormats,a),u;let[d,p]=l.mode==="fast"?[r.fastFormats,o]:[r.fullFormats,a],f=l.formats||r.formatNames;return c(u,f,d,p),l.keywords&&(0,n.default)(u),u};s.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,g;(f=(g=u.opts.code).formats)!==null&&f!==void 0||(g.formats=(0,i._)`require("ajv-formats/dist/formats").${p}`);for(let _ of l)u.addFormat(_,d[_])}e.exports=t=s,Object.defineProperty(t,"__esModule",{value:!0}),t.default=s}),loe=50;function Y2(t=loe){let e=new AbortController;return(0,X2.setMaxListeners)(t,e.signal),e}var doe=typeof global=="object"&&global&&global.Object===Object&&global,poe=doe,foe=typeof self=="object"&&self&&self.Object===Object&&self,moe=poe||foe||Function("return this")(),W$=moe,hoe=W$.Symbol,Bh=hoe,r6=Object.prototype,goe=r6.hasOwnProperty,voe=r6.toString,hd=Bh?Bh.toStringTag:void 0;function yoe(t){var e=goe.call(t,hd),r=t[hd];try{t[hd]=void 0;var n=!0}catch{}var i=voe.call(t);return n&&(e?t[hd]=r:delete t[hd]),i}var _oe=yoe,boe=Object.prototype,xoe=boe.toString;function Soe(t){return xoe.call(t)}var woe=Soe,$oe="[object Null]",Eoe="[object Undefined]",s2=Bh?Bh.toStringTag:void 0;function koe(t){return t==null?t===void 0?Eoe:$oe:s2&&s2 in Object(t)?_oe(t):woe(t)}var Toe=koe;function Ioe(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var n6=Ioe,Poe="[object AsyncFunction]",Ooe="[object Function]",Roe="[object GeneratorFunction]",Coe="[object Proxy]";function Noe(t){if(!n6(t))return!1;var e=Toe(t);return e==Ooe||e==Roe||e==Poe||e==Coe}var joe=Noe,Aoe=W$["__core-js_shared__"],v$=Aoe,c2=(function(){var t=/[^.]+$/.exec(v$&&v$.keys&&v$.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""})();function Moe(t){return!!c2&&c2 in t}var Doe=Moe,zoe=Function.prototype,Uoe=zoe.toString;function Loe(t){if(t!=null){try{return Uoe.call(t)}catch{}try{return t+""}catch{}}return""}var qoe=Loe,Foe=/[\\^$.*+?()[\]{}|]/g,Zoe=/^\[object .+?Constructor\]$/,Hoe=Function.prototype,Boe=Object.prototype,Voe=Hoe.toString,Goe=Boe.hasOwnProperty,Woe=RegExp("^"+Voe.call(Goe).replace(Foe,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Koe(t){if(!n6(t)||Doe(t))return!1;var e=joe(t)?Woe:Zoe;return e.test(qoe(t))}var Joe=Koe;function Xoe(t,e){return t?.[e]}var Yoe=Xoe;function Qoe(t,e){var r=Yoe(t,e);return Joe(r)?r:void 0}var i6=Qoe,ese=i6(Object,"create"),yd=ese;function tse(){this.__data__=yd?yd(null):{},this.size=0}var rse=tse;function nse(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var ise=nse,ase="__lodash_hash_undefined__",ose=Object.prototype,sse=ose.hasOwnProperty;function cse(t){var e=this.__data__;if(yd){var r=e[t];return r===ase?void 0:r}return sse.call(e,t)?e[t]:void 0}var use=cse,lse=Object.prototype,dse=lse.hasOwnProperty;function pse(t){var e=this.__data__;return yd?e[t]!==void 0:dse.call(e,t)}var fse=pse,mse="__lodash_hash_undefined__";function hse(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=yd&&e===void 0?mse:e,this}var gse=hse;function Ec(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e-1}var Pse=Ise;function Ose(t,e){var r=this.__data__,n=og(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}var Rse=Ose;function kc(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(a=>a.trim()).filter(Boolean);if(e.length===0)return null;let r=e.some(a=>a.startsWith("!")),n=e.some(a=>!a.startsWith("!"));if(r&&n)return null;let i=e.map(a=>a.replace(/^!/,"").toLowerCase());return{include:r?[]:i,exclude:r?i:[],isExclusive:r}});function Xse(t){let e=[],r=t.match(/^MCP server ["']([^"']+)["']/);if(r&&r[1])e.push("mcp"),e.push(r[1].toLowerCase());else{let a=t.match(/^([^:[]+):/);a&&a[1]&&e.push(a[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 a=i[1].trim().toLowerCase();a.length<30&&!a.includes(" ")&&e.push(a)}return Array.from(new Set(e))}function Yse(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 Qse(t,e){if(!e)return!0;let r=Xse(t);return Yse(r,e)}function c6(){return process.env.CLAUDE_CONFIG_DIR??(0,o6.join)((0,s6.homedir)(),".claude")}function d2(t){if(!t)return!1;if(typeof t=="boolean")return t;let e=t.toLowerCase().trim();return["1","true","yes","on"].includes(e)}var ece={name:"BASH_MAX_OUTPUT_LENGTH",default:3e4,validate:t=>{if(!t)return{effective:3e4,status:"valid"};let n=parseInt(t,10);return isNaN(n)||n<=0?{effective:3e4,status:"invalid",message:`Invalid value "${t}" (using default: 30000)`}:n>15e4?{effective:15e4,status:"capped",message:`Capped from ${n} to 150000`}:{effective:n,status:"valid"}}},tce={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 rce(){let t="";return typeof process<"u"&&typeof process.cwd=="function"&&(t=(0,l6.realpathSync)((0,u6.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,d6.randomUUID)(),loggerProvider:null,eventLogger:null,meterProvider:null,tracerProvider:null,agentColorMap:new Map,agentColorIndex:0,envVarValidators:[ece,tce],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}}var nce=rce();function ice(){return nce.sessionId}function ace({writeFn:t,flushIntervalMs:e=1e3,maxBufferSize:r=100,immediateMode:n=!1}){let i=[],a=null;function o(){a&&(clearTimeout(a),a=null)}function s(){i.length!==0&&(t(i.join("")),i=[],o())}function c(){a||(a=setTimeout(s,e))}return{write(u){if(n){t(u);return}i.push(u),c(),i.length>=r&&s()},flush:s,dispose(){s()}}}var p2=new Set;function oce(t){return p2.add(t),()=>p2.delete(t)}var sce=Cd(()=>d2(process.env.DEBUG)||d2(process.env.DEBUG_SDK)||process.argv.includes("--debug")||process.argv.includes("-d")||p6()||process.argv.some(t=>t.startsWith("--debug="))),cce=Cd(()=>{let t=process.argv.find(r=>r.startsWith("--debug="));if(!t)return null;let e=t.substring(8);return Jse(e)}),p6=Cd(()=>process.argv.includes("--debug-to-stderr")||process.argv.includes("-d2e"));function uce(t){if(typeof process>"u"||typeof process.versions>"u"||typeof process.versions.node>"u")return!1;let e=cce();return Qse(t,e)}var lce=!1,Mh=null;function dce(){return Mh||(Mh=ace({writeFn:t=>{let e=f6();Hi().existsSync((0,Eo.dirname)(e))||Hi().mkdirSync((0,Eo.dirname)(e)),Hi().appendFileSync(e,t),pce()},flushIntervalMs:1e3,maxBufferSize:100,immediateMode:sce()}),oce(async()=>Mh?.dispose())),Mh}function Ea(t,{level:e}={level:"debug"}){if(!uce(t))return;lce&&t.includes(` @@ -1146,7 +1146,7 @@ ${n}`}function die(t,e){let r=On.default.join(t,"CLAUDE.md"),n=`${r}.tmp`;if(!(0 `))}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[a,o]of Object.entries(this.hooks))o.length>0&&(e[a]=o.map(s=>{let c=[];for(let u of s.hooks){let l=`hook_${this.nextCallbackId++}`;this.hookCallbacks.set(l,u),c.push(l)}return{matcher:s.matcher,hookCallbackIds:c,timeout:s.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){await this.request({subtype:"rewind_files",user_message_id:e})}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,a)=>{this.pendingControlResponses.set(r,o=>{o.subtype==="success"?i(o):(a(new Error(o.error)),o.pending_permission_requests&&this.processPendingPermissionRequests(o.pending_permission_requests))}),Promise.resolve(this.transport.write(JSON.stringify(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()),a=new Set(Object.keys(r));for(let c of i)a.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){Ea("[Query.streamInput] Starting to process input stream");try{let r=0;for await(let n of e){if(r++,Ea(`[Query.streamInput] Processing message ${r}: ${n.type}`),this.abortController?.signal.aborted)break;await Promise.resolve(this.transport.write(JSON.stringify(n)+` `))}Ea(`[Query.streamInput] Finished processing ${r} messages from input stream`),this.hasBidirectionalNeeds()&&(Ea("[Query.streamInput] Has bidirectional needs, waiting for first result"),await this.waitForFirstResult()),Ea("[Query] Calling transport.endInput() to close stdin to CLI process"),this.transport.endInput()}catch(r){if(!(r instanceof $o))throw r}}waitForFirstResult(){return this.firstResultReceived?(Ea("[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 a=this.hookCallbacks.get(e);if(!a)throw new Error(`No hook callback found for ID: ${e}`);return a(r,n,{signal:i})}connectSdkMcpServer(e,r){let n=new k$(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}`,a=this.pendingMcpResponses.get(i);if(a){a.resolve(r),this.pendingMcpResponses.delete(i);return}}let n={type:"control_request",request_id:(0,g6.randomUUID)(),request:{subtype:"mcp_message",server_name:e,message:r}};this.transport.write(JSON.stringify(n)+` -`)}handleMcpControlRequest(e,r,n){let i="id"in r.message?r.message.id:null,a=`${e}:${i}`;return new Promise((o,s)=>{let c=()=>{this.pendingMcpResponses.delete(a)},u=d=>{c(),o(d)},l=d=>{c(),s(d)};if(this.pendingMcpResponses.set(a,{resolve:u,reject:l}),n.onmessage)n.onmessage(r.message);else{c(),s(new Error("No message handler registered"));return}})}};var ct;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let a={};for(let o of i)a[o]=o;return a},t.getValidEnumValues=i=>{let a=t.objectKeys(i).filter(s=>typeof i[i[s]]!="number"),o={};for(let s of a)o[s]=i[s];return t.objectValues(o)},t.objectValues=i=>t.objectKeys(i).map(function(a){return i[a]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let a=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&a.push(o);return a},t.find=(i,a)=>{for(let o of i)if(a(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,a=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(a)}t.joinValues=n,t.jsonStringifyReplacer=(i,a)=>typeof a=="bigint"?a.toString():a})(ct||(ct={}));var m2;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(m2||(m2={}));var de=ct.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ka=t=>{switch(typeof t){case"undefined":return de.undefined;case"string":return de.string;case"number":return Number.isNaN(t)?de.nan:de.number;case"boolean":return de.boolean;case"function":return de.function;case"bigint":return de.bigint;case"symbol":return de.symbol;case"object":return Array.isArray(t)?de.array:t===null?de.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?de.promise:typeof Map<"u"&&t instanceof Map?de.map:typeof Set<"u"&&t instanceof Set?de.set:typeof Date<"u"&&t instanceof Date?de.date:de.object;default:return de.unknown}},te=ct.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"]),Rn=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(a){return a.message},n={_errors:[]},i=a=>{for(let o of a.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 s=n,c=0;for(;cr.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let a=i.path[0];r[a]=r[a]||[],r[a].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Rn.create=t=>new Rn(t);var _ce=(t,e)=>{let r;switch(t.code){case te.invalid_type:t.received===de.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case te.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ct.jsonStringifyReplacer)}`;break;case te.unrecognized_keys:r=`Unrecognized key(s) in object: ${ct.joinValues(t.keys,", ")}`;break;case te.invalid_union:r="Invalid input";break;case te.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ct.joinValues(t.options)}`;break;case te.invalid_enum_value:r=`Invalid enum value. Expected ${ct.joinValues(t.options)}, received '${t.received}'`;break;case te.invalid_arguments:r="Invalid function arguments";break;case te.invalid_return_type:r="Invalid function return type";break;case te.invalid_date:r="Invalid date";break;case te.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}"`:ct.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case te.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 te.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 te.custom:r="Invalid input";break;case te.invalid_intersection_types:r="Intersection results could not be merged";break;case te.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case te.not_finite:r="Number must be finite";break;default:r=e.defaultError,ct.assertNever(t)}return{message:r}},_d=_ce,bce=_d;function I$(){return bce}var P$=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,a=[...r,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)s=u(o,{data:e,defaultError:s}).message;return{...i,path:a,message:s}};function se(t,e){let r=I$(),n=P$({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===_d?void 0:_d].filter(i=>!!i)});t.common.issues.push(n)}var zr=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 Oe;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 a=await i.key,o=await i.value;n.push({key:a,value:o})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:a,value:o}=i;if(a.status==="aborted"||o.status==="aborted")return Oe;a.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(n[a.value]=o.value)}return{status:e.value,value:n}}},Oe=Object.freeze({status:"aborted"}),gd=t=>({status:"dirty",value:t}),Xr=t=>({status:"valid",value:t}),h2=t=>t.status==="aborted",g2=t=>t.status==="dirty",dc=t=>t.status==="valid",Vh=t=>typeof Promise<"u"&&t instanceof Promise,ge;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(ge||(ge={}));var Cn=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}},v2=(t,e)=>{if(dc(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 Rn(t.common.issues);return this._error=r,this._error}}};function De(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,s)=>{let{message:c}=t;return o.code==="invalid_enum_value"?{message:c??s.defaultError}:typeof s.data>"u"?{message:c??n??s.defaultError}:o.code!=="invalid_type"?{message:s.defaultError}:{message:c??r??s.defaultError}},description:i}}var Ge=class{get description(){return this._def.description}_getType(e){return ka(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:ka(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new zr,ctx:{common:e.parent.common,data:e.data,parsedType:ka(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Vh(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:ka(e)},i=this._parseSync({data:e,path:n.path,parent:n});return v2(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ka(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return dc(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=>dc(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:ka(e)},i=this._parse({data:e,path:n.path,parent:n}),a=await(Vh(i)?i:Promise.resolve(i));return v2(n,a)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,a)=>{let o=e(i),s=()=>a.addIssue({code:te.custom,...n(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(s(),!1)):o?!0:(s(),!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 Qn({schema:this,typeName:Re.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 Yn.create(this,this._def)}nullable(){return Vi.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Pa.create(this)}promise(){return ko.create(this,this._def)}or(e){return hc.create([this,e],this._def)}and(e){return gc.create(this,e,this._def)}transform(e){return new Qn({...De(this._def),schema:this,typeName:Re.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new xc({...De(this._def),innerType:this,defaultValue:r,typeName:Re.ZodDefault})}brand(){return new Gh({typeName:Re.ZodBranded,type:this,...De(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Sc({...De(this._def),innerType:this,catchValue:r,typeName:Re.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Wh.create(this,e)}readonly(){return wc.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},xce=/^c[^\s-]{8,}$/i,Sce=/^[0-9a-z]+$/,wce=/^[0-9A-HJKMNP-TV-Z]{26}$/i,$ce=/^[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,Ece=/^[a-z0-9_-]{21}$/i,kce=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Tce=/^[-+]?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)?)??$/,Ice=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Pce="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",y$,Oce=/^(?:(?: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])$/,Rce=/^(?:(?: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])$/,Cce=/^(([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]))$/,Nce=/^(([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])$/,jce=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ace=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,v6="((\\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])))",Mce=new RegExp(`^${v6}$`);function y6(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 Dce(t){return new RegExp(`^${y6(t)}$`)}function zce(t){let e=`${v6}T${y6(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 Uce(t,e){return!!((e==="v4"||!e)&&Oce.test(t)||(e==="v6"||!e)&&Cce.test(t))}function Lce(t,e){if(!kce.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 qce(t,e){return!!((e==="v4"||!e)&&Rce.test(t)||(e==="v6"||!e)&&Nce.test(t))}var pc=class t extends Ge{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==de.string){let a=this._getOrReturnCtx(e);return se(a,{code:te.invalid_type,expected:de.string,received:a.parsedType}),Oe}let n=new zr,i;for(let a of this._def.checks)if(a.kind==="min")e.data.lengtha.value&&(i=this._getOrReturnCtx(e,i),se(i,{code:te.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){let o=e.data.length>a.value,s=e.data.lengthe.test(i),{validation:r,code:te.invalid_string,...ge.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ge.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ge.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ge.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ge.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ge.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ge.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ge.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ge.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ge.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ge.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ge.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ge.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ge.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,...ge.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,...ge.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...ge.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...ge.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...ge.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...ge.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...ge.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...ge.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...ge.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...ge.errToObj(r)})}nonempty(e){return this.min(1,ge.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 pc({checks:[],typeName:Re.ZodString,coerce:t?.coerce??!1,...De(t)});function Fce(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,a=Number.parseInt(t.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return a%o/10**i}var bd=class t extends Ge{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)!==de.number){let a=this._getOrReturnCtx(e);return se(a,{code:te.invalid_type,expected:de.number,received:a.parsedType}),Oe}let n,i=new zr;for(let a of this._def.checks)a.kind==="int"?ct.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),se(n,{code:te.invalid_type,expected:"integer",received:"float",message:a.message}),i.dirty()):a.kind==="min"?(a.inclusive?e.dataa.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),se(n,{code:te.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="multipleOf"?Fce(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),se(n,{code:te.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),se(n,{code:te.not_finite,message:a.message}),i.dirty()):ct.assertNever(a);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,ge.toString(r))}gt(e,r){return this.setLimit("min",e,!1,ge.toString(r))}lte(e,r){return this.setLimit("max",e,!0,ge.toString(r))}lt(e,r){return this.setLimit("max",e,!1,ge.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:ge.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ge.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ge.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ge.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ge.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ge.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:ge.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:ge.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ge.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ge.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"&&ct.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 bd({checks:[],typeName:Re.ZodNumber,coerce:t?.coerce||!1,...De(t)});var xd=class t extends Ge{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)!==de.bigint)return this._getInvalidInput(e);let n,i=new zr;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.dataa.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),se(n,{code:te.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),se(n,{code:te.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):ct.assertNever(a);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return se(r,{code:te.invalid_type,expected:de.bigint,received:r.parsedType}),Oe}gte(e,r){return this.setLimit("min",e,!0,ge.toString(r))}gt(e,r){return this.setLimit("min",e,!1,ge.toString(r))}lte(e,r){return this.setLimit("max",e,!0,ge.toString(r))}lt(e,r){return this.setLimit("max",e,!1,ge.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:ge.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:ge.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ge.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ge.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ge.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:ge.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 xd({checks:[],typeName:Re.ZodBigInt,coerce:t?.coerce??!1,...De(t)});var Sd=class extends Ge{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==de.boolean){let n=this._getOrReturnCtx(e);return se(n,{code:te.invalid_type,expected:de.boolean,received:n.parsedType}),Oe}return Xr(e.data)}};Sd.create=t=>new Sd({typeName:Re.ZodBoolean,coerce:t?.coerce||!1,...De(t)});var wd=class t extends Ge{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==de.date){let a=this._getOrReturnCtx(e);return se(a,{code:te.invalid_type,expected:de.date,received:a.parsedType}),Oe}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return se(a,{code:te.invalid_date}),Oe}let n=new zr,i;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()a.value&&(i=this._getOrReturnCtx(e,i),se(i,{code:te.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):ct.assertNever(a);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:ge.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:ge.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 wd({checks:[],coerce:t?.coerce||!1,typeName:Re.ZodDate,...De(t)});var $d=class extends Ge{_parse(e){if(this._getType(e)!==de.symbol){let n=this._getOrReturnCtx(e);return se(n,{code:te.invalid_type,expected:de.symbol,received:n.parsedType}),Oe}return Xr(e.data)}};$d.create=t=>new $d({typeName:Re.ZodSymbol,...De(t)});var fc=class extends Ge{_parse(e){if(this._getType(e)!==de.undefined){let n=this._getOrReturnCtx(e);return se(n,{code:te.invalid_type,expected:de.undefined,received:n.parsedType}),Oe}return Xr(e.data)}};fc.create=t=>new fc({typeName:Re.ZodUndefined,...De(t)});var mc=class extends Ge{_parse(e){if(this._getType(e)!==de.null){let n=this._getOrReturnCtx(e);return se(n,{code:te.invalid_type,expected:de.null,received:n.parsedType}),Oe}return Xr(e.data)}};mc.create=t=>new mc({typeName:Re.ZodNull,...De(t)});var Ed=class extends Ge{constructor(){super(...arguments),this._any=!0}_parse(e){return Xr(e.data)}};Ed.create=t=>new Ed({typeName:Re.ZodAny,...De(t)});var Ia=class extends Ge{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Xr(e.data)}};Ia.create=t=>new Ia({typeName:Re.ZodUnknown,...De(t)});var Si=class extends Ge{_parse(e){let r=this._getOrReturnCtx(e);return se(r,{code:te.invalid_type,expected:de.never,received:r.parsedType}),Oe}};Si.create=t=>new Si({typeName:Re.ZodNever,...De(t)});var kd=class extends Ge{_parse(e){if(this._getType(e)!==de.undefined){let n=this._getOrReturnCtx(e);return se(n,{code:te.invalid_type,expected:de.void,received:n.parsedType}),Oe}return Xr(e.data)}};kd.create=t=>new kd({typeName:Re.ZodVoid,...De(t)});var Pa=class t extends Ge{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==de.array)return se(r,{code:te.invalid_type,expected:de.array,received:r.parsedType}),Oe;if(i.exactLength!==null){let o=r.data.length>i.exactLength.value,s=r.data.lengthi.maxLength.value&&(se(r,{code:te.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,s)=>i.type._parseAsync(new Cn(r,o,r.path,s)))).then(o=>zr.mergeArray(n,o));let a=[...r.data].map((o,s)=>i.type._parseSync(new Cn(r,o,r.path,s)));return zr.mergeArray(n,a)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:ge.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:ge.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:ge.toString(r)}})}nonempty(e){return this.min(1,e)}};Pa.create=(t,e)=>new Pa({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Re.ZodArray,...De(e)});function cc(t){if(t instanceof dn){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Yn.create(cc(n))}return new dn({...t._def,shape:()=>e})}else return t instanceof Pa?new Pa({...t._def,type:cc(t.element)}):t instanceof Yn?Yn.create(cc(t.unwrap())):t instanceof Vi?Vi.create(cc(t.unwrap())):t instanceof Bi?Bi.create(t.items.map(e=>cc(e))):t}var dn=class t extends Ge{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=ct.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==de.object){let u=this._getOrReturnCtx(e);return se(u,{code:te.invalid_type,expected:de.object,received:u.parsedType}),Oe}let{status:n,ctx:i}=this._processInputParams(e),{shape:a,keys:o}=this._getCached(),s=[];if(!(this._def.catchall instanceof Si&&this._def.unknownKeys==="strip"))for(let u in i.data)o.includes(u)||s.push(u);let c=[];for(let u of o){let l=a[u],d=i.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Cn(i,d,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Si){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of s)c.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(u==="strict")s.length>0&&(se(i,{code:te.unrecognized_keys,keys:s}),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 s){let d=i.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Cn(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=>zr.mergeObjectSync(n,u)):zr.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return ge.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:ge.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:Re.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 ct.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 ct.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return cc(this)}partial(e){let r={};for(let n of ct.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 ct.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof Yn;)a=a._def.innerType;r[n]=a}return new t({...this._def,shape:()=>r})}keyof(){return _6(ct.objectKeys(this.shape))}};dn.create=(t,e)=>new dn({shape:()=>t,unknownKeys:"strip",catchall:Si.create(),typeName:Re.ZodObject,...De(e)});dn.strictCreate=(t,e)=>new dn({shape:()=>t,unknownKeys:"strict",catchall:Si.create(),typeName:Re.ZodObject,...De(e)});dn.lazycreate=(t,e)=>new dn({shape:t,unknownKeys:"strip",catchall:Si.create(),typeName:Re.ZodObject,...De(e)});var hc=class extends Ge{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(a){for(let s of a)if(s.result.status==="valid")return s.result;for(let s of a)if(s.result.status==="dirty")return r.common.issues.push(...s.ctx.common.issues),s.result;let o=a.map(s=>new Rn(s.ctx.common.issues));return se(r,{code:te.invalid_union,unionErrors:o}),Oe}if(r.common.async)return Promise.all(n.map(async a=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(i);{let a,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"&&!a&&(a={result:l,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(c=>new Rn(c));return se(r,{code:te.invalid_union,unionErrors:s}),Oe}}get options(){return this._def.options}};hc.create=(t,e)=>new hc({options:t,typeName:Re.ZodUnion,...De(e)});var Zi=t=>t instanceof vc?Zi(t.schema):t instanceof Qn?Zi(t.innerType()):t instanceof yc?[t.value]:t instanceof _c?t.options:t instanceof bc?ct.objectValues(t.enum):t instanceof xc?Zi(t._def.innerType):t instanceof fc?[void 0]:t instanceof mc?[null]:t instanceof Yn?[void 0,...Zi(t.unwrap())]:t instanceof Vi?[null,...Zi(t.unwrap())]:t instanceof Gh||t instanceof wc?Zi(t.unwrap()):t instanceof Sc?Zi(t._def.innerType):[],O$=class t extends Ge{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==de.object)return se(r,{code:te.invalid_type,expected:de.object,received:r.parsedType}),Oe;let n=this.discriminator,i=r.data[n],a=this.optionsMap.get(i);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(se(r,{code:te.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Oe)}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 a of r){let o=Zi(a.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of o){if(i.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);i.set(s,a)}}return new t({typeName:Re.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...De(n)})}};function R$(t,e){let r=ka(t),n=ka(e);if(t===e)return{valid:!0,data:t};if(r===de.object&&n===de.object){let i=ct.objectKeys(e),a=ct.objectKeys(t).filter(s=>i.indexOf(s)!==-1),o={...t,...e};for(let s of a){let c=R$(t[s],e[s]);if(!c.valid)return{valid:!1};o[s]=c.data}return{valid:!0,data:o}}else if(r===de.array&&n===de.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let a=0;a{if(h2(a)||h2(o))return Oe;let s=R$(a.value,o.value);return s.valid?((g2(a)||g2(o))&&r.dirty(),{status:r.value,value:s.data}):(se(n,{code:te.invalid_intersection_types}),Oe)};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(([a,o])=>i(a,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}))}};gc.create=(t,e,r)=>new gc({left:t,right:e,typeName:Re.ZodIntersection,...De(r)});var Bi=class t extends Ge{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==de.array)return se(n,{code:te.invalid_type,expected:de.array,received:n.parsedType}),Oe;if(n.data.lengththis._def.items.length&&(se(n,{code:te.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let a=[...n.data].map((o,s)=>{let c=this._def.items[s]||this._def.rest;return c?c._parse(new Cn(n,o,n.path,s)):null}).filter(o=>!!o);return n.common.async?Promise.all(a).then(o=>zr.mergeArray(r,o)):zr.mergeArray(r,a)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Bi.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Bi({items:t,typeName:Re.ZodTuple,rest:null,...De(e)})};var C$=class t extends Ge{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!==de.object)return se(n,{code:te.invalid_type,expected:de.object,received:n.parsedType}),Oe;let i=[],a=this._def.keyType,o=this._def.valueType;for(let s in n.data)i.push({key:a._parse(new Cn(n,s,n.path,s)),value:o._parse(new Cn(n,n.data[s],n.path,s)),alwaysSet:s in n.data});return n.common.async?zr.mergeObjectAsync(r,i):zr.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Ge?new t({keyType:e,valueType:r,typeName:Re.ZodRecord,...De(n)}):new t({keyType:pc.create(),valueType:e,typeName:Re.ZodRecord,...De(r)})}},Td=class extends Ge{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!==de.map)return se(n,{code:te.invalid_type,expected:de.map,received:n.parsedType}),Oe;let i=this._def.keyType,a=this._def.valueType,o=[...n.data.entries()].map(([s,c],u)=>({key:i._parse(new Cn(n,s,n.path,[u,"key"])),value:a._parse(new Cn(n,c,n.path,[u,"value"]))}));if(n.common.async){let s=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 Oe;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),s.set(u.value,l.value)}return{status:r.value,value:s}})}else{let s=new Map;for(let c of o){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return Oe;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),s.set(u.value,l.value)}return{status:r.value,value:s}}}};Td.create=(t,e,r)=>new Td({valueType:e,keyType:t,typeName:Re.ZodMap,...De(r)});var Id=class t extends Ge{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==de.set)return se(n,{code:te.invalid_type,expected:de.set,received:n.parsedType}),Oe;let i=this._def;i.minSize!==null&&n.data.sizei.maxSize.value&&(se(n,{code:te.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let a=this._def.valueType;function o(c){let u=new Set;for(let l of c){if(l.status==="aborted")return Oe;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let s=[...n.data.values()].map((c,u)=>a._parse(new Cn(n,c,n.path,u)));return n.common.async?Promise.all(s).then(c=>o(c)):o(s)}min(e,r){return new t({...this._def,minSize:{value:e,message:ge.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:ge.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Id.create=(t,e)=>new Id({valueType:t,minSize:null,maxSize:null,typeName:Re.ZodSet,...De(e)});var N$=class t extends Ge{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==de.function)return se(r,{code:te.invalid_type,expected:de.function,received:r.parsedType}),Oe;function n(s,c){return P$({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,I$(),_d].filter(u=>!!u),issueData:{code:te.invalid_arguments,argumentsError:c}})}function i(s,c){return P$({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,I$(),_d].filter(u=>!!u),issueData:{code:te.invalid_return_type,returnTypeError:c}})}let a={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof ko){let s=this;return Xr(async function(...c){let u=new Rn([]),l=await s._def.args.parseAsync(c,a).catch(f=>{throw u.addIssue(n(c,f)),u}),d=await Reflect.apply(o,this,l);return await s._def.returns._def.type.parseAsync(d,a).catch(f=>{throw u.addIssue(i(d,f)),u})})}else{let s=this;return Xr(function(...c){let u=s._def.args.safeParse(c,a);if(!u.success)throw new Rn([n(c,u.error)]);let l=Reflect.apply(o,this,u.data),d=s._def.returns.safeParse(l,a);if(!d.success)throw new Rn([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:Bi.create(e).rest(Ia.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||Bi.create([]).rest(Ia.create()),returns:r||Ia.create(),typeName:Re.ZodFunction,...De(n)})}},vc=class extends Ge{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})}};vc.create=(t,e)=>new vc({getter:t,typeName:Re.ZodLazy,...De(e)});var yc=class extends Ge{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return se(r,{received:r.data,code:te.invalid_literal,expected:this._def.value}),Oe}return{status:"valid",value:e.data}}get value(){return this._def.value}};yc.create=(t,e)=>new yc({value:t,typeName:Re.ZodLiteral,...De(e)});function _6(t,e){return new _c({values:t,typeName:Re.ZodEnum,...De(e)})}var _c=class t extends Ge{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return se(r,{expected:ct.joinValues(n),received:r.parsedType,code:te.invalid_type}),Oe}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 se(r,{received:r.data,code:te.invalid_enum_value,options:n}),Oe}return Xr(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})}};_c.create=_6;var bc=class extends Ge{_parse(e){let r=ct.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==de.string&&n.parsedType!==de.number){let i=ct.objectValues(r);return se(n,{expected:ct.joinValues(i),received:n.parsedType,code:te.invalid_type}),Oe}if(this._cache||(this._cache=new Set(ct.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=ct.objectValues(r);return se(n,{received:n.data,code:te.invalid_enum_value,options:i}),Oe}return Xr(e.data)}get enum(){return this._def.values}};bc.create=(t,e)=>new bc({values:t,typeName:Re.ZodNativeEnum,...De(e)});var ko=class extends Ge{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==de.promise&&r.common.async===!1)return se(r,{code:te.invalid_type,expected:de.promise,received:r.parsedType}),Oe;let n=r.parsedType===de.promise?r.data:Promise.resolve(r.data);return Xr(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};ko.create=(t,e)=>new ko({type:t,typeName:Re.ZodPromise,...De(e)});var Qn=class extends Ge{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Re.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,a={addIssue:o=>{se(n,o),o.fatal?r.abort():r.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),i.type==="preprocess"){let o=i.transform(n.data,a);if(n.common.async)return Promise.resolve(o).then(async s=>{if(r.value==="aborted")return Oe;let c=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return c.status==="aborted"?Oe:c.status==="dirty"||r.value==="dirty"?gd(c.value):c});{if(r.value==="aborted")return Oe;let s=this._def.schema._parseSync({data:o,path:n.path,parent:n});return s.status==="aborted"?Oe:s.status==="dirty"||r.value==="dirty"?gd(s.value):s}}if(i.type==="refinement"){let o=s=>{let c=i.refinement(s,a);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 s};if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?Oe:(s.status==="dirty"&&r.dirty(),o(s.value),{status:r.value,value:s.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>s.status==="aborted"?Oe:(s.status==="dirty"&&r.dirty(),o(s.value).then(()=>({status:r.value,value:s.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(!dc(o))return Oe;let s=i.transform(o.value,a);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>dc(o)?Promise.resolve(i.transform(o.value,a)).then(s=>({status:r.value,value:s})):Oe);ct.assertNever(i)}};Qn.create=(t,e,r)=>new Qn({schema:t,typeName:Re.ZodEffects,effect:e,...De(r)});Qn.createWithPreprocess=(t,e,r)=>new Qn({schema:e,effect:{type:"preprocess",transform:t},typeName:Re.ZodEffects,...De(r)});var Yn=class extends Ge{_parse(e){return this._getType(e)===de.undefined?Xr(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Yn.create=(t,e)=>new Yn({innerType:t,typeName:Re.ZodOptional,...De(e)});var Vi=class extends Ge{_parse(e){return this._getType(e)===de.null?Xr(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Vi.create=(t,e)=>new Vi({innerType:t,typeName:Re.ZodNullable,...De(e)});var xc=class extends Ge{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===de.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};xc.create=(t,e)=>new xc({innerType:t,typeName:Re.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...De(e)});var Sc=class extends Ge{_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 Vh(i)?i.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new Rn(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Rn(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Sc.create=(t,e)=>new Sc({innerType:t,typeName:Re.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...De(e)});var Pd=class extends Ge{_parse(e){if(this._getType(e)!==de.nan){let n=this._getOrReturnCtx(e);return se(n,{code:te.invalid_type,expected:de.nan,received:n.parsedType}),Oe}return{status:"valid",value:e.data}}};Pd.create=t=>new Pd({typeName:Re.ZodNaN,...De(t)});var Gh=class extends Ge{_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}},Wh=class t extends Ge{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?Oe:a.status==="dirty"?(r.dirty(),gd(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?Oe: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:Re.ZodPipeline})}},wc=class extends Ge{_parse(e){let r=this._def.innerType._parse(e),n=i=>(dc(i)&&(i.value=Object.freeze(i.value)),i);return Vh(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};wc.create=(t,e)=>new wc({innerType:t,typeName:Re.ZodReadonly,...De(e)});var JIe={object:dn.lazycreate},Re;(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"})(Re||(Re={}));var XIe=pc.create,YIe=bd.create,QIe=Pd.create,ePe=xd.create,tPe=Sd.create,rPe=wd.create,nPe=$d.create,iPe=fc.create,aPe=mc.create,oPe=Ed.create,sPe=Ia.create,cPe=Si.create,uPe=kd.create,lPe=Pa.create,dPe=dn.create,pPe=dn.strictCreate,fPe=hc.create,mPe=O$.create,hPe=gc.create,gPe=Bi.create,vPe=C$.create,yPe=Td.create,_Pe=Id.create,bPe=N$.create,xPe=vc.create,SPe=yc.create,wPe=_c.create,$Pe=bc.create,EPe=ko.create,kPe=Qn.create,TPe=Yn.create,IPe=Vi.create,PPe=Qn.createWithPreprocess,OPe=Wh.create,RPe=Object.freeze({status:"aborted"});function X(t,e,r){function n(s,c){var u;Object.defineProperty(s,"_zod",{value:s._zod??{},enumerable:!1}),(u=s._zod).traits??(u.traits=new Set),s._zod.traits.add(t),e(s,c);for(let l in o.prototype)l in s||Object.defineProperty(s,l,{value:o.prototype[l].bind(s)});s._zod.constr=o,s._zod.def=c}let i=r?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:t});function o(s){var c;let u=r?.Parent?new a:this;n(u,s),(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:s=>r?.Parent&&s instanceof r.Parent?!0:s?._zod?.traits?.has(t)}),Object.defineProperty(o,"name",{value:t}),o}var To=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},j$={};function Gi(t){return t&&Object.assign(j$,t),j$}var zt={};z2(zt,{unwrapMessage:()=>vd,stringifyPrimitive:()=>Y$,required:()=>sue,randomString:()=>Jce,propertyKeyTypes:()=>$6,promiseAllObject:()=>Kce,primitiveTypes:()=>Qce,prefixIssues:()=>Ta,pick:()=>rue,partial:()=>oue,optionalKeys:()=>E6,omit:()=>nue,numKeys:()=>Xce,nullish:()=>ug,normalizeParams:()=>Te,merge:()=>aue,jsonStringifyReplacer:()=>x6,joinValues:()=>A$,issue:()=>T6,isPlainObject:()=>Rd,isObject:()=>Od,getSizableOrigin:()=>cue,getParsedType:()=>Yce,getLengthableOrigin:()=>dg,getEnumValues:()=>b6,getElementAtPath:()=>Wce,floatSafeRemainder:()=>S6,finalizeIssue:()=>Wi,extend:()=>iue,escapeRegex:()=>Pc,esc:()=>uc,defineLazy:()=>Ut,createTransparentProxy:()=>eue,clone:()=>Ca,cleanRegex:()=>lg,cleanEnum:()=>uue,captureStackTrace:()=>X$,cached:()=>cg,assignProp:()=>J$,assertNotEqual:()=>Hce,assertNever:()=>Vce,assertIs:()=>Bce,assertEqual:()=>Zce,assert:()=>Gce,allowsEval:()=>w6,aborted:()=>lc,NUMBER_FORMAT_RANGES:()=>k6,Class:()=>M$,BIGINT_FORMAT_RANGES:()=>tue});function Zce(t){return t}function Hce(t){return t}function Bce(t){}function Vce(t){throw new Error}function Gce(t){}function b6(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 A$(t,e="|"){return t.map(r=>Y$(r)).join(e)}function x6(t,e){return typeof e=="bigint"?e.toString():e}function cg(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function ug(t){return t==null}function lg(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function S6(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,a=Number.parseInt(t.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return a%o/10**i}function Ut(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 J$(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Wce(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function Kce(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let i={};for(let a=0;a{};function Od(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var w6=cg(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Rd(t){if(Od(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Od(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Xce(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var Yce=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}`)}},$6=new Set(["string","number","symbol"]),Qce=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Pc(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ca(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function Te(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 eue(t){let e;return new Proxy({},{get(r,n,i){return e??(e=t()),Reflect.get(e,n,i)},set(r,n,i,a){return e??(e=t()),Reflect.set(e,n,i,a)},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 Y$(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function E6(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var k6={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]},tue={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function rue(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 Ca(t,{...t._zod.def,shape:r,checks:[]})}function nue(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 Ca(t,{...t._zod.def,shape:r,checks:[]})}function iue(t,e){if(!Rd(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 J$(this,"shape",n),n},checks:[]};return Ca(t,r)}function aue(t,e){return Ca(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return J$(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function oue(t,e,r){let n=e._zod.def.shape,i={...n};if(r)for(let a in r){if(!(a in n))throw new Error(`Unrecognized key: "${a}"`);r[a]&&(i[a]=t?new t({type:"optional",innerType:n[a]}):n[a])}else for(let a in n)i[a]=t?new t({type:"optional",innerType:n[a]}):n[a];return Ca(e,{...e._zod.def,shape:i,checks:[]})}function sue(t,e,r){let n=e._zod.def.shape,i={...n};if(r)for(let a in r){if(!(a in i))throw new Error(`Unrecognized key: "${a}"`);r[a]&&(i[a]=new t({type:"nonoptional",innerType:n[a]}))}else for(let a in n)i[a]=new t({type:"nonoptional",innerType:n[a]});return Ca(e,{...e._zod.def,shape:i,checks:[]})}function lc(t,e=0){for(let r=e;r{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function vd(t){return typeof t=="string"?t:t?.message}function Wi(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let i=vd(t.inst?._zod.def?.error?.(t))??vd(e?.error?.(t))??vd(r.customError?.(t))??vd(r.localeError?.(t))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function cue(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function dg(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function T6(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function uue(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var M$=class{constructor(...e){}},I6=(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,x6,2)},enumerable:!0})},P6=X("$ZodError",I6),O6=X("$ZodError",I6,{Parent:Error});function lue(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 due(t,e){let r=e||function(a){return a.message},n={_errors:[]},i=a=>{for(let o of a.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(s=>i({issues:s}));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 s=n,c=0;for(;c(e,r,n,i)=>{let a=n?Object.assign(n,{async:!1}):{async:!1},o=e._zod.run({value:r,issues:[]},a);if(o instanceof Promise)throw new To;if(o.issues.length){let s=new(i?.Err??t)(o.issues.map(c=>Wi(c,a,Gi())));throw X$(s,i?.callee),s}return o.value};var fue=t=>async(e,r,n,i)=>{let a=n?Object.assign(n,{async:!0}):{async:!0},o=e._zod.run({value:r,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let s=new(i?.Err??t)(o.issues.map(c=>Wi(c,a,Gi())));throw X$(s,i?.callee),s}return o.value};var R6=t=>(e,r,n)=>{let i=n?{...n,async:!1}:{async:!1},a=e._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new To;return a.issues.length?{success:!1,error:new(t??P6)(a.issues.map(o=>Wi(o,i,Gi())))}:{success:!0,data:a.value}},mue=R6(O6),C6=t=>async(e,r,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},a=e._zod.run({value:r,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new t(a.issues.map(o=>Wi(o,i,Gi())))}:{success:!0,data:a.value}},hue=C6(O6),gue=/^[cC][^\s-]{8,}$/,vue=/^[0-9a-z]+$/,yue=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,_ue=/^[0-9a-vA-V]{20}$/,bue=/^[A-Za-z0-9]{27}$/,xue=/^[a-zA-Z0-9_-]{21}$/,Sue=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,wue=/^([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})$/,y2=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)$/,$ue=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Eue="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function kue(){return new RegExp(Eue,"u")}var Tue=/^(?:(?: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])$/,Iue=/^(([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})$/,Pue=/^((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])$/,Oue=/^(([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])$/,Rue=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,N6=/^[A-Za-z0-9_-]*$/,Cue=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Nue=/^\+(?:[0-9]){6,14}[0-9]$/,j6="(?:(?:\\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])))",jue=new RegExp(`^${j6}$`);function A6(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 Aue(t){return new RegExp(`^${A6(t)}$`)}function Mue(t){let e=A6({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(`^${j6}T(?:${n})$`)}var Due=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},zue=/^\d+$/,Uue=/^-?\d+(?:\.\d+)?/i,Lue=/true|false/i,que=/null/i,Fue=/^[^A-Z]*$/,Zue=/^[^a-z]*$/,Yr=X("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),M6={number:"number",bigint:"bigint",object:"date"},D6=X("$ZodCheckLessThan",(t,e)=>{Yr.init(t,e);let r=M6[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,a=(e.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value{(e.inclusive?n.value<=e.value:n.value{Yr.init(t,e);let r=M6[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,a=(e.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>a&&(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})}}),Hue=X("$ZodCheckMultipleOf",(t,e)=>{Yr.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):S6(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})}}),Bue=X("$ZodCheckNumberFormat",(t,e)=>{Yr.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[i,a]=k6[e.format];t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,s.minimum=i,s.maximum=a,r&&(s.pattern=zue)}),t._zod.check=o=>{let s=o.value;if(r){if(!Number.isInteger(s)){o.issues.push({expected:n,format:e.format,code:"invalid_type",input:s,inst:t});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,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:s,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}}sa&&o.issues.push({origin:"number",input:s,code:"too_big",maximum:a,inst:t})}}),Vue=X("$ZodCheckMaxLength",(t,e)=>{Yr.init(t,e),t._zod.when=r=>{let n=r.value;return!ug(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 a=dg(n);r.issues.push({origin:a,code:"too_big",maximum:e.maximum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),Gue=X("$ZodCheckMinLength",(t,e)=>{Yr.init(t,e),t._zod.when=r=>{let n=r.value;return!ug(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 a=dg(n);r.issues.push({origin:a,code:"too_small",minimum:e.minimum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),Wue=X("$ZodCheckLengthEquals",(t,e)=>{Yr.init(t,e),t._zod.when=r=>{let n=r.value;return!ug(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 a=dg(n),o=i>e.length;r.issues.push({origin:a,...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})}}),pg=X("$ZodCheckStringFormat",(t,e)=>{var r,n;Yr.init(t,e),t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,e.pattern&&(a.patterns??(a.patterns=new Set),a.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=()=>{})}),Kue=X("$ZodCheckRegex",(t,e)=>{pg.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})}}),Jue=X("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Fue),pg.init(t,e)}),Xue=X("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Zue),pg.init(t,e)}),Yue=X("$ZodCheckIncludes",(t,e)=>{Yr.init(t,e);let r=Pc(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(i=>{let a=i._zod.bag;a.patterns??(a.patterns=new Set),a.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})}}),Que=X("$ZodCheckStartsWith",(t,e)=>{Yr.init(t,e);let r=new RegExp(`^${Pc(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})}}),ele=X("$ZodCheckEndsWith",(t,e)=>{Yr.init(t,e);let r=new RegExp(`.*${Pc(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})}}),tle=X("$ZodCheckOverwrite",(t,e)=>{Yr.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}}),D$=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,a=`${e}:${i}`;return new Promise((o,s)=>{let c=()=>{this.pendingMcpResponses.delete(a)},u=d=>{c(),o(d)},l=d=>{c(),s(d)};if(this.pendingMcpResponses.set(a,{resolve:u,reject:l}),n.onmessage)n.onmessage(r.message);else{c(),s(new Error("No message handler registered"));return}})}};var ct;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let a={};for(let o of i)a[o]=o;return a},t.getValidEnumValues=i=>{let a=t.objectKeys(i).filter(s=>typeof i[i[s]]!="number"),o={};for(let s of a)o[s]=i[s];return t.objectValues(o)},t.objectValues=i=>t.objectKeys(i).map(function(a){return i[a]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let a=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&a.push(o);return a},t.find=(i,a)=>{for(let o of i)if(a(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,a=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(a)}t.joinValues=n,t.jsonStringifyReplacer=(i,a)=>typeof a=="bigint"?a.toString():a})(ct||(ct={}));var m2;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(m2||(m2={}));var de=ct.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ka=t=>{switch(typeof t){case"undefined":return de.undefined;case"string":return de.string;case"number":return Number.isNaN(t)?de.nan:de.number;case"boolean":return de.boolean;case"function":return de.function;case"bigint":return de.bigint;case"symbol":return de.symbol;case"object":return Array.isArray(t)?de.array:t===null?de.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?de.promise:typeof Map<"u"&&t instanceof Map?de.map:typeof Set<"u"&&t instanceof Set?de.set:typeof Date<"u"&&t instanceof Date?de.date:de.object;default:return de.unknown}},te=ct.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"]),Rn=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(a){return a.message},n={_errors:[]},i=a=>{for(let o of a.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 s=n,c=0;for(;cr.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let a=i.path[0];r[a]=r[a]||[],r[a].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Rn.create=t=>new Rn(t);var _ce=(t,e)=>{let r;switch(t.code){case te.invalid_type:t.received===de.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case te.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ct.jsonStringifyReplacer)}`;break;case te.unrecognized_keys:r=`Unrecognized key(s) in object: ${ct.joinValues(t.keys,", ")}`;break;case te.invalid_union:r="Invalid input";break;case te.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ct.joinValues(t.options)}`;break;case te.invalid_enum_value:r=`Invalid enum value. Expected ${ct.joinValues(t.options)}, received '${t.received}'`;break;case te.invalid_arguments:r="Invalid function arguments";break;case te.invalid_return_type:r="Invalid function return type";break;case te.invalid_date:r="Invalid date";break;case te.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}"`:ct.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case te.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 te.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 te.custom:r="Invalid input";break;case te.invalid_intersection_types:r="Intersection results could not be merged";break;case te.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case te.not_finite:r="Number must be finite";break;default:r=e.defaultError,ct.assertNever(t)}return{message:r}},_d=_ce,bce=_d;function I$(){return bce}var P$=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,a=[...r,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)s=u(o,{data:e,defaultError:s}).message;return{...i,path:a,message:s}};function se(t,e){let r=I$(),n=P$({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===_d?void 0:_d].filter(i=>!!i)});t.common.issues.push(n)}var zr=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 Oe;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 a=await i.key,o=await i.value;n.push({key:a,value:o})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:a,value:o}=i;if(a.status==="aborted"||o.status==="aborted")return Oe;a.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(n[a.value]=o.value)}return{status:e.value,value:n}}},Oe=Object.freeze({status:"aborted"}),gd=t=>({status:"dirty",value:t}),Jr=t=>({status:"valid",value:t}),h2=t=>t.status==="aborted",g2=t=>t.status==="dirty",dc=t=>t.status==="valid",Vh=t=>typeof Promise<"u"&&t instanceof Promise,ge;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(ge||(ge={}));var Cn=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}},v2=(t,e)=>{if(dc(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 Rn(t.common.issues);return this._error=r,this._error}}};function De(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,s)=>{let{message:c}=t;return o.code==="invalid_enum_value"?{message:c??s.defaultError}:typeof s.data>"u"?{message:c??n??s.defaultError}:o.code!=="invalid_type"?{message:s.defaultError}:{message:c??r??s.defaultError}},description:i}}var Ge=class{get description(){return this._def.description}_getType(e){return ka(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:ka(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new zr,ctx:{common:e.parent.common,data:e.data,parsedType:ka(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Vh(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:ka(e)},i=this._parseSync({data:e,path:n.path,parent:n});return v2(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ka(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return dc(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=>dc(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:ka(e)},i=this._parse({data:e,path:n.path,parent:n}),a=await(Vh(i)?i:Promise.resolve(i));return v2(n,a)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,a)=>{let o=e(i),s=()=>a.addIssue({code:te.custom,...n(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(s(),!1)):o?!0:(s(),!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 Qn({schema:this,typeName:Re.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 Yn.create(this,this._def)}nullable(){return Vi.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Pa.create(this)}promise(){return ko.create(this,this._def)}or(e){return hc.create([this,e],this._def)}and(e){return gc.create(this,e,this._def)}transform(e){return new Qn({...De(this._def),schema:this,typeName:Re.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new xc({...De(this._def),innerType:this,defaultValue:r,typeName:Re.ZodDefault})}brand(){return new Gh({typeName:Re.ZodBranded,type:this,...De(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Sc({...De(this._def),innerType:this,catchValue:r,typeName:Re.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Wh.create(this,e)}readonly(){return wc.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},xce=/^c[^\s-]{8,}$/i,Sce=/^[0-9a-z]+$/,wce=/^[0-9A-HJKMNP-TV-Z]{26}$/i,$ce=/^[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,Ece=/^[a-z0-9_-]{21}$/i,kce=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Tce=/^[-+]?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)?)??$/,Ice=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Pce="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",y$,Oce=/^(?:(?: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])$/,Rce=/^(?:(?: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])$/,Cce=/^(([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]))$/,Nce=/^(([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])$/,jce=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ace=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,v6="((\\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])))",Mce=new RegExp(`^${v6}$`);function y6(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 Dce(t){return new RegExp(`^${y6(t)}$`)}function zce(t){let e=`${v6}T${y6(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 Uce(t,e){return!!((e==="v4"||!e)&&Oce.test(t)||(e==="v6"||!e)&&Cce.test(t))}function Lce(t,e){if(!kce.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 qce(t,e){return!!((e==="v4"||!e)&&Rce.test(t)||(e==="v6"||!e)&&Nce.test(t))}var pc=class t extends Ge{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==de.string){let a=this._getOrReturnCtx(e);return se(a,{code:te.invalid_type,expected:de.string,received:a.parsedType}),Oe}let n=new zr,i;for(let a of this._def.checks)if(a.kind==="min")e.data.lengtha.value&&(i=this._getOrReturnCtx(e,i),se(i,{code:te.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){let o=e.data.length>a.value,s=e.data.lengthe.test(i),{validation:r,code:te.invalid_string,...ge.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ge.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ge.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ge.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ge.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ge.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ge.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ge.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ge.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ge.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ge.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ge.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ge.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ge.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,...ge.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,...ge.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...ge.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...ge.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...ge.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...ge.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...ge.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...ge.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...ge.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...ge.errToObj(r)})}nonempty(e){return this.min(1,ge.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 pc({checks:[],typeName:Re.ZodString,coerce:t?.coerce??!1,...De(t)});function Fce(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,a=Number.parseInt(t.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return a%o/10**i}var bd=class t extends Ge{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)!==de.number){let a=this._getOrReturnCtx(e);return se(a,{code:te.invalid_type,expected:de.number,received:a.parsedType}),Oe}let n,i=new zr;for(let a of this._def.checks)a.kind==="int"?ct.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),se(n,{code:te.invalid_type,expected:"integer",received:"float",message:a.message}),i.dirty()):a.kind==="min"?(a.inclusive?e.dataa.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),se(n,{code:te.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="multipleOf"?Fce(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),se(n,{code:te.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),se(n,{code:te.not_finite,message:a.message}),i.dirty()):ct.assertNever(a);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,ge.toString(r))}gt(e,r){return this.setLimit("min",e,!1,ge.toString(r))}lte(e,r){return this.setLimit("max",e,!0,ge.toString(r))}lt(e,r){return this.setLimit("max",e,!1,ge.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:ge.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ge.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ge.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ge.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ge.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ge.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:ge.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:ge.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ge.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ge.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"&&ct.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 bd({checks:[],typeName:Re.ZodNumber,coerce:t?.coerce||!1,...De(t)});var xd=class t extends Ge{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)!==de.bigint)return this._getInvalidInput(e);let n,i=new zr;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.dataa.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),se(n,{code:te.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),se(n,{code:te.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):ct.assertNever(a);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return se(r,{code:te.invalid_type,expected:de.bigint,received:r.parsedType}),Oe}gte(e,r){return this.setLimit("min",e,!0,ge.toString(r))}gt(e,r){return this.setLimit("min",e,!1,ge.toString(r))}lte(e,r){return this.setLimit("max",e,!0,ge.toString(r))}lt(e,r){return this.setLimit("max",e,!1,ge.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:ge.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:ge.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ge.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ge.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ge.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:ge.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 xd({checks:[],typeName:Re.ZodBigInt,coerce:t?.coerce??!1,...De(t)});var Sd=class extends Ge{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==de.boolean){let n=this._getOrReturnCtx(e);return se(n,{code:te.invalid_type,expected:de.boolean,received:n.parsedType}),Oe}return Jr(e.data)}};Sd.create=t=>new Sd({typeName:Re.ZodBoolean,coerce:t?.coerce||!1,...De(t)});var wd=class t extends Ge{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==de.date){let a=this._getOrReturnCtx(e);return se(a,{code:te.invalid_type,expected:de.date,received:a.parsedType}),Oe}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return se(a,{code:te.invalid_date}),Oe}let n=new zr,i;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()a.value&&(i=this._getOrReturnCtx(e,i),se(i,{code:te.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):ct.assertNever(a);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:ge.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:ge.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 wd({checks:[],coerce:t?.coerce||!1,typeName:Re.ZodDate,...De(t)});var $d=class extends Ge{_parse(e){if(this._getType(e)!==de.symbol){let n=this._getOrReturnCtx(e);return se(n,{code:te.invalid_type,expected:de.symbol,received:n.parsedType}),Oe}return Jr(e.data)}};$d.create=t=>new $d({typeName:Re.ZodSymbol,...De(t)});var fc=class extends Ge{_parse(e){if(this._getType(e)!==de.undefined){let n=this._getOrReturnCtx(e);return se(n,{code:te.invalid_type,expected:de.undefined,received:n.parsedType}),Oe}return Jr(e.data)}};fc.create=t=>new fc({typeName:Re.ZodUndefined,...De(t)});var mc=class extends Ge{_parse(e){if(this._getType(e)!==de.null){let n=this._getOrReturnCtx(e);return se(n,{code:te.invalid_type,expected:de.null,received:n.parsedType}),Oe}return Jr(e.data)}};mc.create=t=>new mc({typeName:Re.ZodNull,...De(t)});var Ed=class extends Ge{constructor(){super(...arguments),this._any=!0}_parse(e){return Jr(e.data)}};Ed.create=t=>new Ed({typeName:Re.ZodAny,...De(t)});var Ia=class extends Ge{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Jr(e.data)}};Ia.create=t=>new Ia({typeName:Re.ZodUnknown,...De(t)});var Si=class extends Ge{_parse(e){let r=this._getOrReturnCtx(e);return se(r,{code:te.invalid_type,expected:de.never,received:r.parsedType}),Oe}};Si.create=t=>new Si({typeName:Re.ZodNever,...De(t)});var kd=class extends Ge{_parse(e){if(this._getType(e)!==de.undefined){let n=this._getOrReturnCtx(e);return se(n,{code:te.invalid_type,expected:de.void,received:n.parsedType}),Oe}return Jr(e.data)}};kd.create=t=>new kd({typeName:Re.ZodVoid,...De(t)});var Pa=class t extends Ge{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==de.array)return se(r,{code:te.invalid_type,expected:de.array,received:r.parsedType}),Oe;if(i.exactLength!==null){let o=r.data.length>i.exactLength.value,s=r.data.lengthi.maxLength.value&&(se(r,{code:te.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,s)=>i.type._parseAsync(new Cn(r,o,r.path,s)))).then(o=>zr.mergeArray(n,o));let a=[...r.data].map((o,s)=>i.type._parseSync(new Cn(r,o,r.path,s)));return zr.mergeArray(n,a)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:ge.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:ge.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:ge.toString(r)}})}nonempty(e){return this.min(1,e)}};Pa.create=(t,e)=>new Pa({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Re.ZodArray,...De(e)});function cc(t){if(t instanceof dn){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Yn.create(cc(n))}return new dn({...t._def,shape:()=>e})}else return t instanceof Pa?new Pa({...t._def,type:cc(t.element)}):t instanceof Yn?Yn.create(cc(t.unwrap())):t instanceof Vi?Vi.create(cc(t.unwrap())):t instanceof Bi?Bi.create(t.items.map(e=>cc(e))):t}var dn=class t extends Ge{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=ct.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==de.object){let u=this._getOrReturnCtx(e);return se(u,{code:te.invalid_type,expected:de.object,received:u.parsedType}),Oe}let{status:n,ctx:i}=this._processInputParams(e),{shape:a,keys:o}=this._getCached(),s=[];if(!(this._def.catchall instanceof Si&&this._def.unknownKeys==="strip"))for(let u in i.data)o.includes(u)||s.push(u);let c=[];for(let u of o){let l=a[u],d=i.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Cn(i,d,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Si){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of s)c.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(u==="strict")s.length>0&&(se(i,{code:te.unrecognized_keys,keys:s}),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 s){let d=i.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Cn(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=>zr.mergeObjectSync(n,u)):zr.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return ge.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:ge.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:Re.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 ct.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 ct.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return cc(this)}partial(e){let r={};for(let n of ct.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 ct.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof Yn;)a=a._def.innerType;r[n]=a}return new t({...this._def,shape:()=>r})}keyof(){return _6(ct.objectKeys(this.shape))}};dn.create=(t,e)=>new dn({shape:()=>t,unknownKeys:"strip",catchall:Si.create(),typeName:Re.ZodObject,...De(e)});dn.strictCreate=(t,e)=>new dn({shape:()=>t,unknownKeys:"strict",catchall:Si.create(),typeName:Re.ZodObject,...De(e)});dn.lazycreate=(t,e)=>new dn({shape:t,unknownKeys:"strip",catchall:Si.create(),typeName:Re.ZodObject,...De(e)});var hc=class extends Ge{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(a){for(let s of a)if(s.result.status==="valid")return s.result;for(let s of a)if(s.result.status==="dirty")return r.common.issues.push(...s.ctx.common.issues),s.result;let o=a.map(s=>new Rn(s.ctx.common.issues));return se(r,{code:te.invalid_union,unionErrors:o}),Oe}if(r.common.async)return Promise.all(n.map(async a=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(i);{let a,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"&&!a&&(a={result:l,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(c=>new Rn(c));return se(r,{code:te.invalid_union,unionErrors:s}),Oe}}get options(){return this._def.options}};hc.create=(t,e)=>new hc({options:t,typeName:Re.ZodUnion,...De(e)});var Zi=t=>t instanceof vc?Zi(t.schema):t instanceof Qn?Zi(t.innerType()):t instanceof yc?[t.value]:t instanceof _c?t.options:t instanceof bc?ct.objectValues(t.enum):t instanceof xc?Zi(t._def.innerType):t instanceof fc?[void 0]:t instanceof mc?[null]:t instanceof Yn?[void 0,...Zi(t.unwrap())]:t instanceof Vi?[null,...Zi(t.unwrap())]:t instanceof Gh||t instanceof wc?Zi(t.unwrap()):t instanceof Sc?Zi(t._def.innerType):[],O$=class t extends Ge{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==de.object)return se(r,{code:te.invalid_type,expected:de.object,received:r.parsedType}),Oe;let n=this.discriminator,i=r.data[n],a=this.optionsMap.get(i);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(se(r,{code:te.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Oe)}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 a of r){let o=Zi(a.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of o){if(i.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);i.set(s,a)}}return new t({typeName:Re.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...De(n)})}};function R$(t,e){let r=ka(t),n=ka(e);if(t===e)return{valid:!0,data:t};if(r===de.object&&n===de.object){let i=ct.objectKeys(e),a=ct.objectKeys(t).filter(s=>i.indexOf(s)!==-1),o={...t,...e};for(let s of a){let c=R$(t[s],e[s]);if(!c.valid)return{valid:!1};o[s]=c.data}return{valid:!0,data:o}}else if(r===de.array&&n===de.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let a=0;a{if(h2(a)||h2(o))return Oe;let s=R$(a.value,o.value);return s.valid?((g2(a)||g2(o))&&r.dirty(),{status:r.value,value:s.data}):(se(n,{code:te.invalid_intersection_types}),Oe)};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(([a,o])=>i(a,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}))}};gc.create=(t,e,r)=>new gc({left:t,right:e,typeName:Re.ZodIntersection,...De(r)});var Bi=class t extends Ge{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==de.array)return se(n,{code:te.invalid_type,expected:de.array,received:n.parsedType}),Oe;if(n.data.lengththis._def.items.length&&(se(n,{code:te.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let a=[...n.data].map((o,s)=>{let c=this._def.items[s]||this._def.rest;return c?c._parse(new Cn(n,o,n.path,s)):null}).filter(o=>!!o);return n.common.async?Promise.all(a).then(o=>zr.mergeArray(r,o)):zr.mergeArray(r,a)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Bi.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Bi({items:t,typeName:Re.ZodTuple,rest:null,...De(e)})};var C$=class t extends Ge{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!==de.object)return se(n,{code:te.invalid_type,expected:de.object,received:n.parsedType}),Oe;let i=[],a=this._def.keyType,o=this._def.valueType;for(let s in n.data)i.push({key:a._parse(new Cn(n,s,n.path,s)),value:o._parse(new Cn(n,n.data[s],n.path,s)),alwaysSet:s in n.data});return n.common.async?zr.mergeObjectAsync(r,i):zr.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Ge?new t({keyType:e,valueType:r,typeName:Re.ZodRecord,...De(n)}):new t({keyType:pc.create(),valueType:e,typeName:Re.ZodRecord,...De(r)})}},Td=class extends Ge{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!==de.map)return se(n,{code:te.invalid_type,expected:de.map,received:n.parsedType}),Oe;let i=this._def.keyType,a=this._def.valueType,o=[...n.data.entries()].map(([s,c],u)=>({key:i._parse(new Cn(n,s,n.path,[u,"key"])),value:a._parse(new Cn(n,c,n.path,[u,"value"]))}));if(n.common.async){let s=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 Oe;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),s.set(u.value,l.value)}return{status:r.value,value:s}})}else{let s=new Map;for(let c of o){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return Oe;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),s.set(u.value,l.value)}return{status:r.value,value:s}}}};Td.create=(t,e,r)=>new Td({valueType:e,keyType:t,typeName:Re.ZodMap,...De(r)});var Id=class t extends Ge{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==de.set)return se(n,{code:te.invalid_type,expected:de.set,received:n.parsedType}),Oe;let i=this._def;i.minSize!==null&&n.data.sizei.maxSize.value&&(se(n,{code:te.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let a=this._def.valueType;function o(c){let u=new Set;for(let l of c){if(l.status==="aborted")return Oe;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let s=[...n.data.values()].map((c,u)=>a._parse(new Cn(n,c,n.path,u)));return n.common.async?Promise.all(s).then(c=>o(c)):o(s)}min(e,r){return new t({...this._def,minSize:{value:e,message:ge.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:ge.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Id.create=(t,e)=>new Id({valueType:t,minSize:null,maxSize:null,typeName:Re.ZodSet,...De(e)});var N$=class t extends Ge{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==de.function)return se(r,{code:te.invalid_type,expected:de.function,received:r.parsedType}),Oe;function n(s,c){return P$({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,I$(),_d].filter(u=>!!u),issueData:{code:te.invalid_arguments,argumentsError:c}})}function i(s,c){return P$({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,I$(),_d].filter(u=>!!u),issueData:{code:te.invalid_return_type,returnTypeError:c}})}let a={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof ko){let s=this;return Jr(async function(...c){let u=new Rn([]),l=await s._def.args.parseAsync(c,a).catch(f=>{throw u.addIssue(n(c,f)),u}),d=await Reflect.apply(o,this,l);return await s._def.returns._def.type.parseAsync(d,a).catch(f=>{throw u.addIssue(i(d,f)),u})})}else{let s=this;return Jr(function(...c){let u=s._def.args.safeParse(c,a);if(!u.success)throw new Rn([n(c,u.error)]);let l=Reflect.apply(o,this,u.data),d=s._def.returns.safeParse(l,a);if(!d.success)throw new Rn([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:Bi.create(e).rest(Ia.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||Bi.create([]).rest(Ia.create()),returns:r||Ia.create(),typeName:Re.ZodFunction,...De(n)})}},vc=class extends Ge{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})}};vc.create=(t,e)=>new vc({getter:t,typeName:Re.ZodLazy,...De(e)});var yc=class extends Ge{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return se(r,{received:r.data,code:te.invalid_literal,expected:this._def.value}),Oe}return{status:"valid",value:e.data}}get value(){return this._def.value}};yc.create=(t,e)=>new yc({value:t,typeName:Re.ZodLiteral,...De(e)});function _6(t,e){return new _c({values:t,typeName:Re.ZodEnum,...De(e)})}var _c=class t extends Ge{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return se(r,{expected:ct.joinValues(n),received:r.parsedType,code:te.invalid_type}),Oe}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 se(r,{received:r.data,code:te.invalid_enum_value,options:n}),Oe}return Jr(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})}};_c.create=_6;var bc=class extends Ge{_parse(e){let r=ct.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==de.string&&n.parsedType!==de.number){let i=ct.objectValues(r);return se(n,{expected:ct.joinValues(i),received:n.parsedType,code:te.invalid_type}),Oe}if(this._cache||(this._cache=new Set(ct.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=ct.objectValues(r);return se(n,{received:n.data,code:te.invalid_enum_value,options:i}),Oe}return Jr(e.data)}get enum(){return this._def.values}};bc.create=(t,e)=>new bc({values:t,typeName:Re.ZodNativeEnum,...De(e)});var ko=class extends Ge{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==de.promise&&r.common.async===!1)return se(r,{code:te.invalid_type,expected:de.promise,received:r.parsedType}),Oe;let n=r.parsedType===de.promise?r.data:Promise.resolve(r.data);return Jr(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};ko.create=(t,e)=>new ko({type:t,typeName:Re.ZodPromise,...De(e)});var Qn=class extends Ge{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Re.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,a={addIssue:o=>{se(n,o),o.fatal?r.abort():r.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),i.type==="preprocess"){let o=i.transform(n.data,a);if(n.common.async)return Promise.resolve(o).then(async s=>{if(r.value==="aborted")return Oe;let c=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return c.status==="aborted"?Oe:c.status==="dirty"||r.value==="dirty"?gd(c.value):c});{if(r.value==="aborted")return Oe;let s=this._def.schema._parseSync({data:o,path:n.path,parent:n});return s.status==="aborted"?Oe:s.status==="dirty"||r.value==="dirty"?gd(s.value):s}}if(i.type==="refinement"){let o=s=>{let c=i.refinement(s,a);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 s};if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?Oe:(s.status==="dirty"&&r.dirty(),o(s.value),{status:r.value,value:s.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>s.status==="aborted"?Oe:(s.status==="dirty"&&r.dirty(),o(s.value).then(()=>({status:r.value,value:s.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(!dc(o))return Oe;let s=i.transform(o.value,a);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>dc(o)?Promise.resolve(i.transform(o.value,a)).then(s=>({status:r.value,value:s})):Oe);ct.assertNever(i)}};Qn.create=(t,e,r)=>new Qn({schema:t,typeName:Re.ZodEffects,effect:e,...De(r)});Qn.createWithPreprocess=(t,e,r)=>new Qn({schema:e,effect:{type:"preprocess",transform:t},typeName:Re.ZodEffects,...De(r)});var Yn=class extends Ge{_parse(e){return this._getType(e)===de.undefined?Jr(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Yn.create=(t,e)=>new Yn({innerType:t,typeName:Re.ZodOptional,...De(e)});var Vi=class extends Ge{_parse(e){return this._getType(e)===de.null?Jr(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Vi.create=(t,e)=>new Vi({innerType:t,typeName:Re.ZodNullable,...De(e)});var xc=class extends Ge{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===de.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};xc.create=(t,e)=>new xc({innerType:t,typeName:Re.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...De(e)});var Sc=class extends Ge{_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 Vh(i)?i.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new Rn(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Rn(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Sc.create=(t,e)=>new Sc({innerType:t,typeName:Re.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...De(e)});var Pd=class extends Ge{_parse(e){if(this._getType(e)!==de.nan){let n=this._getOrReturnCtx(e);return se(n,{code:te.invalid_type,expected:de.nan,received:n.parsedType}),Oe}return{status:"valid",value:e.data}}};Pd.create=t=>new Pd({typeName:Re.ZodNaN,...De(t)});var Gh=class extends Ge{_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}},Wh=class t extends Ge{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?Oe:a.status==="dirty"?(r.dirty(),gd(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?Oe: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:Re.ZodPipeline})}},wc=class extends Ge{_parse(e){let r=this._def.innerType._parse(e),n=i=>(dc(i)&&(i.value=Object.freeze(i.value)),i);return Vh(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};wc.create=(t,e)=>new wc({innerType:t,typeName:Re.ZodReadonly,...De(e)});var KIe={object:dn.lazycreate},Re;(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"})(Re||(Re={}));var JIe=pc.create,XIe=bd.create,YIe=Pd.create,QIe=xd.create,ePe=Sd.create,tPe=wd.create,rPe=$d.create,nPe=fc.create,iPe=mc.create,aPe=Ed.create,oPe=Ia.create,sPe=Si.create,cPe=kd.create,uPe=Pa.create,lPe=dn.create,dPe=dn.strictCreate,pPe=hc.create,fPe=O$.create,mPe=gc.create,hPe=Bi.create,gPe=C$.create,vPe=Td.create,yPe=Id.create,_Pe=N$.create,bPe=vc.create,xPe=yc.create,SPe=_c.create,wPe=bc.create,$Pe=ko.create,EPe=Qn.create,kPe=Yn.create,TPe=Vi.create,IPe=Qn.createWithPreprocess,PPe=Wh.create,OPe=Object.freeze({status:"aborted"});function X(t,e,r){function n(s,c){var u;Object.defineProperty(s,"_zod",{value:s._zod??{},enumerable:!1}),(u=s._zod).traits??(u.traits=new Set),s._zod.traits.add(t),e(s,c);for(let l in o.prototype)l in s||Object.defineProperty(s,l,{value:o.prototype[l].bind(s)});s._zod.constr=o,s._zod.def=c}let i=r?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:t});function o(s){var c;let u=r?.Parent?new a:this;n(u,s),(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:s=>r?.Parent&&s instanceof r.Parent?!0:s?._zod?.traits?.has(t)}),Object.defineProperty(o,"name",{value:t}),o}var To=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},j$={};function Gi(t){return t&&Object.assign(j$,t),j$}var zt={};z2(zt,{unwrapMessage:()=>vd,stringifyPrimitive:()=>Y$,required:()=>sue,randomString:()=>Jce,propertyKeyTypes:()=>$6,promiseAllObject:()=>Kce,primitiveTypes:()=>Qce,prefixIssues:()=>Ta,pick:()=>rue,partial:()=>oue,optionalKeys:()=>E6,omit:()=>nue,numKeys:()=>Xce,nullish:()=>ug,normalizeParams:()=>Te,merge:()=>aue,jsonStringifyReplacer:()=>x6,joinValues:()=>A$,issue:()=>T6,isPlainObject:()=>Rd,isObject:()=>Od,getSizableOrigin:()=>cue,getParsedType:()=>Yce,getLengthableOrigin:()=>dg,getEnumValues:()=>b6,getElementAtPath:()=>Wce,floatSafeRemainder:()=>S6,finalizeIssue:()=>Wi,extend:()=>iue,escapeRegex:()=>Pc,esc:()=>uc,defineLazy:()=>Ut,createTransparentProxy:()=>eue,clone:()=>Ca,cleanRegex:()=>lg,cleanEnum:()=>uue,captureStackTrace:()=>X$,cached:()=>cg,assignProp:()=>J$,assertNotEqual:()=>Hce,assertNever:()=>Vce,assertIs:()=>Bce,assertEqual:()=>Zce,assert:()=>Gce,allowsEval:()=>w6,aborted:()=>lc,NUMBER_FORMAT_RANGES:()=>k6,Class:()=>M$,BIGINT_FORMAT_RANGES:()=>tue});function Zce(t){return t}function Hce(t){return t}function Bce(t){}function Vce(t){throw new Error}function Gce(t){}function b6(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 A$(t,e="|"){return t.map(r=>Y$(r)).join(e)}function x6(t,e){return typeof e=="bigint"?e.toString():e}function cg(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function ug(t){return t==null}function lg(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function S6(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,a=Number.parseInt(t.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return a%o/10**i}function Ut(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 J$(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Wce(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function Kce(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let i={};for(let a=0;a{};function Od(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var w6=cg(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Rd(t){if(Od(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Od(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Xce(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var Yce=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}`)}},$6=new Set(["string","number","symbol"]),Qce=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Pc(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ca(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function Te(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 eue(t){let e;return new Proxy({},{get(r,n,i){return e??(e=t()),Reflect.get(e,n,i)},set(r,n,i,a){return e??(e=t()),Reflect.set(e,n,i,a)},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 Y$(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function E6(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var k6={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]},tue={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function rue(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 Ca(t,{...t._zod.def,shape:r,checks:[]})}function nue(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 Ca(t,{...t._zod.def,shape:r,checks:[]})}function iue(t,e){if(!Rd(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 J$(this,"shape",n),n},checks:[]};return Ca(t,r)}function aue(t,e){return Ca(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return J$(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function oue(t,e,r){let n=e._zod.def.shape,i={...n};if(r)for(let a in r){if(!(a in n))throw new Error(`Unrecognized key: "${a}"`);r[a]&&(i[a]=t?new t({type:"optional",innerType:n[a]}):n[a])}else for(let a in n)i[a]=t?new t({type:"optional",innerType:n[a]}):n[a];return Ca(e,{...e._zod.def,shape:i,checks:[]})}function sue(t,e,r){let n=e._zod.def.shape,i={...n};if(r)for(let a in r){if(!(a in i))throw new Error(`Unrecognized key: "${a}"`);r[a]&&(i[a]=new t({type:"nonoptional",innerType:n[a]}))}else for(let a in n)i[a]=new t({type:"nonoptional",innerType:n[a]});return Ca(e,{...e._zod.def,shape:i,checks:[]})}function lc(t,e=0){for(let r=e;r{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function vd(t){return typeof t=="string"?t:t?.message}function Wi(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let i=vd(t.inst?._zod.def?.error?.(t))??vd(e?.error?.(t))??vd(r.customError?.(t))??vd(r.localeError?.(t))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function cue(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function dg(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function T6(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function uue(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var M$=class{constructor(...e){}},I6=(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,x6,2)},enumerable:!0})},P6=X("$ZodError",I6),O6=X("$ZodError",I6,{Parent:Error});function lue(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 due(t,e){let r=e||function(a){return a.message},n={_errors:[]},i=a=>{for(let o of a.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(s=>i({issues:s}));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 s=n,c=0;for(;c(e,r,n,i)=>{let a=n?Object.assign(n,{async:!1}):{async:!1},o=e._zod.run({value:r,issues:[]},a);if(o instanceof Promise)throw new To;if(o.issues.length){let s=new(i?.Err??t)(o.issues.map(c=>Wi(c,a,Gi())));throw X$(s,i?.callee),s}return o.value};var fue=t=>async(e,r,n,i)=>{let a=n?Object.assign(n,{async:!0}):{async:!0},o=e._zod.run({value:r,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let s=new(i?.Err??t)(o.issues.map(c=>Wi(c,a,Gi())));throw X$(s,i?.callee),s}return o.value};var R6=t=>(e,r,n)=>{let i=n?{...n,async:!1}:{async:!1},a=e._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new To;return a.issues.length?{success:!1,error:new(t??P6)(a.issues.map(o=>Wi(o,i,Gi())))}:{success:!0,data:a.value}},mue=R6(O6),C6=t=>async(e,r,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},a=e._zod.run({value:r,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new t(a.issues.map(o=>Wi(o,i,Gi())))}:{success:!0,data:a.value}},hue=C6(O6),gue=/^[cC][^\s-]{8,}$/,vue=/^[0-9a-z]+$/,yue=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,_ue=/^[0-9a-vA-V]{20}$/,bue=/^[A-Za-z0-9]{27}$/,xue=/^[a-zA-Z0-9_-]{21}$/,Sue=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,wue=/^([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})$/,y2=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)$/,$ue=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Eue="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function kue(){return new RegExp(Eue,"u")}var Tue=/^(?:(?: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])$/,Iue=/^(([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})$/,Pue=/^((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])$/,Oue=/^(([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])$/,Rue=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,N6=/^[A-Za-z0-9_-]*$/,Cue=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Nue=/^\+(?:[0-9]){6,14}[0-9]$/,j6="(?:(?:\\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])))",jue=new RegExp(`^${j6}$`);function A6(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 Aue(t){return new RegExp(`^${A6(t)}$`)}function Mue(t){let e=A6({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(`^${j6}T(?:${n})$`)}var Due=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},zue=/^\d+$/,Uue=/^-?\d+(?:\.\d+)?/i,Lue=/true|false/i,que=/null/i,Fue=/^[^A-Z]*$/,Zue=/^[^a-z]*$/,Xr=X("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),M6={number:"number",bigint:"bigint",object:"date"},D6=X("$ZodCheckLessThan",(t,e)=>{Xr.init(t,e);let r=M6[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,a=(e.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value{(e.inclusive?n.value<=e.value:n.value{Xr.init(t,e);let r=M6[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,a=(e.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>a&&(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})}}),Hue=X("$ZodCheckMultipleOf",(t,e)=>{Xr.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):S6(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})}}),Bue=X("$ZodCheckNumberFormat",(t,e)=>{Xr.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[i,a]=k6[e.format];t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,s.minimum=i,s.maximum=a,r&&(s.pattern=zue)}),t._zod.check=o=>{let s=o.value;if(r){if(!Number.isInteger(s)){o.issues.push({expected:n,format:e.format,code:"invalid_type",input:s,inst:t});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,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:s,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}}sa&&o.issues.push({origin:"number",input:s,code:"too_big",maximum:a,inst:t})}}),Vue=X("$ZodCheckMaxLength",(t,e)=>{Xr.init(t,e),t._zod.when=r=>{let n=r.value;return!ug(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 a=dg(n);r.issues.push({origin:a,code:"too_big",maximum:e.maximum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),Gue=X("$ZodCheckMinLength",(t,e)=>{Xr.init(t,e),t._zod.when=r=>{let n=r.value;return!ug(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 a=dg(n);r.issues.push({origin:a,code:"too_small",minimum:e.minimum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),Wue=X("$ZodCheckLengthEquals",(t,e)=>{Xr.init(t,e),t._zod.when=r=>{let n=r.value;return!ug(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 a=dg(n),o=i>e.length;r.issues.push({origin:a,...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})}}),pg=X("$ZodCheckStringFormat",(t,e)=>{var r,n;Xr.init(t,e),t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,e.pattern&&(a.patterns??(a.patterns=new Set),a.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=()=>{})}),Kue=X("$ZodCheckRegex",(t,e)=>{pg.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})}}),Jue=X("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Fue),pg.init(t,e)}),Xue=X("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Zue),pg.init(t,e)}),Yue=X("$ZodCheckIncludes",(t,e)=>{Xr.init(t,e);let r=Pc(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(i=>{let a=i._zod.bag;a.patterns??(a.patterns=new Set),a.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})}}),Que=X("$ZodCheckStartsWith",(t,e)=>{Xr.init(t,e);let r=new RegExp(`^${Pc(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})}}),ele=X("$ZodCheckEndsWith",(t,e)=>{Xr.init(t,e);let r=new RegExp(`.*${Pc(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})}}),tle=X("$ZodCheckOverwrite",(t,e)=>{Xr.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}}),D$=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)),a=n.map(o=>o.slice(i)).map(o=>" ".repeat(this.indent*2)+o);for(let o of a)this.content.push(o)}compile(){let e=Function,r=this?.args,i=[...(this?.content??[""]).map(a=>` ${a}`)];return new e(...r,i.join(` `))}},rle={major:4,minor:0,patch:0},Lt=X("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=rle;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let i of n)for(let a of i._zod.onattach)a(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let i=(a,o,s)=>{let c=lc(a),u;for(let l of o){if(l._zod.when){if(!l._zod.when(a))continue}else if(c)continue;let d=a.issues.length,p=l._zod.check(a);if(p instanceof Promise&&s?.async===!1)throw new To;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,a.issues.length!==d&&(c||(c=lc(a,d)))});else{if(a.issues.length===d)continue;c||(c=lc(a,d))}}return u?u.then(()=>a):a};t._zod.run=(a,o)=>{let s=t._zod.parse(a,o);if(s instanceof Promise){if(o.async===!1)throw new To;return s.then(c=>i(c,n,o))}return i(s,n,o)}}t["~standard"]={validate:i=>{try{let a=mue(t,i);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return hue(t,i).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}}),Q$=X("$ZodString",(t,e)=>{Lt.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Due(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}}),Ft=X("$ZodStringFormat",(t,e)=>{pg.init(t,e),Q$.init(t,e)}),nle=X("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=wue),Ft.init(t,e)}),ile=X("$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=y2(n))}else e.pattern??(e.pattern=y2());Ft.init(t,e)}),ale=X("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=$ue),Ft.init(t,e)}),ole=X("$ZodURL",(t,e)=>{Ft.init(t,e),t._zod.check=r=>{try{let n=r.value,i=new URL(n),a=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:Cue.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("/")&&a.endsWith("/")?r.value=a.slice(0,-1):r.value=a;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),sle=X("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=kue()),Ft.init(t,e)}),cle=X("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=xue),Ft.init(t,e)}),ule=X("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=gue),Ft.init(t,e)}),lle=X("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=vue),Ft.init(t,e)}),dle=X("$ZodULID",(t,e)=>{e.pattern??(e.pattern=yue),Ft.init(t,e)}),ple=X("$ZodXID",(t,e)=>{e.pattern??(e.pattern=_ue),Ft.init(t,e)}),fle=X("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=bue),Ft.init(t,e)}),mle=X("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Mue(e)),Ft.init(t,e)}),hle=X("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=jue),Ft.init(t,e)}),gle=X("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Aue(e)),Ft.init(t,e)}),vle=X("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Sue),Ft.init(t,e)}),yle=X("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Tue),Ft.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),_le=X("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Iue),Ft.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})}}}),ble=X("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Pue),Ft.init(t,e)}),xle=X("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Oue),Ft.init(t,e),t._zod.check=r=>{let[n,i]=r.value.split("/");try{if(!i)throw new Error;let a=Number(i);if(`${a}`!==i)throw new Error;if(a<0||a>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 U6(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var Sle=X("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Rue),Ft.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{U6(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function wle(t){if(!N6.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return U6(r)}var $le=X("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=N6),Ft.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{wle(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Ele=X("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Nue),Ft.init(t,e)});function kle(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 Tle=X("$ZodJWT",(t,e)=>{Ft.init(t,e),t._zod.check=r=>{kle(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),L6=X("$ZodNumber",(t,e)=>{Lt.init(t,e),t._zod.pattern=t._zod.bag.pattern??Uue,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 a=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,...a?{received:a}:{}}),r}}),Ile=X("$ZodNumber",(t,e)=>{Bue.init(t,e),L6.init(t,e)}),Ple=X("$ZodBoolean",(t,e)=>{Lt.init(t,e),t._zod.pattern=Lue,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}}),Ole=X("$ZodNull",(t,e)=>{Lt.init(t,e),t._zod.pattern=que,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}}),Rle=X("$ZodUnknown",(t,e)=>{Lt.init(t,e),t._zod.parse=r=>r}),Cle=X("$ZodNever",(t,e)=>{Lt.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function _2(t,e,r){t.issues.length&&e.issues.push(...Ta(r,t.issues)),e.value[r]=t.value}var Nle=X("$ZodArray",(t,e)=>{Lt.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 a=[];for(let o=0;o_2(u,r,o))):_2(c,r,o)}return a.length?Promise.all(a).then(()=>r):r}});function zh(t,e,r){t.issues.length&&e.issues.push(...Ta(r,t.issues)),e.value[r]=t.value}function b2(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(...Ta(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}var jle=X("$ZodObject",(t,e)=>{Lt.init(t,e);let r=cg(()=>{let d=Object.keys(e.shape);for(let f of d)if(!(e.shape[f]instanceof Lt))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let p=E6(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});Ut(t._zod,"propValues",()=>{let d=e.shape,p={};for(let f in d){let g=d[f]._zod;if(g.values){p[f]??(p[f]=new Set);for(let _ of g.values)p[f].add(_)}}return p});let n=d=>{let p=new D$(["shape","payload","ctx"]),f=r.value,g=y=>{let v=uc(y);return`shape[${v}]._zod.run({ value: input[${v}], issues: [] }, ctx)`};p.write("const input = payload.value;");let _=Object.create(null),h=0;for(let y of f.keys)_[y]=`key_${h++}`;p.write("const newResult = {}");for(let y of f.keys)if(f.optionalKeys.has(y)){let v=_[y];p.write(`const ${v} = ${g(y)};`);let b=uc(y);p.write(` if (${v}.issues.length) { @@ -1171,12 +1171,12 @@ ${n}`}function die(t,e){let r=On.default.join(t,"CLAUDE.md"),n=`${r}.tmp`;if(!(0 if (${v}.issues.length) payload.issues = payload.issues.concat(${v}.issues.map(iss => ({ ...iss, path: iss.path ? [${uc(y)}, ...iss.path] : [${uc(y)}] - })));`),p.write(`newResult[${uc(y)}] = ${v}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let m=p.compile();return(y,v)=>m(d,y,v)},i,a=Od,o=!j$.jitless,c=o&&w6.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=r.value);let f=d.value;if(!a(f))return d.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),d;let g=[];if(o&&c&&p?.async===!1&&p.jitless!==!0)i||(i=n(e.shape)),d=i(d,p);else{d.value={};let v=l.shape;for(let b of l.keys){let S=v[b],x=S._zod.run({value:f[b],issues:[]},p),w=S._zod.optin==="optional"&&S._zod.optout==="optional";x instanceof Promise?g.push(x.then(k=>w?b2(k,d,b,f):zh(k,d,b))):w?b2(x,d,b,f):zh(x,d,b)}}if(!u)return g.length?Promise.all(g).then(()=>d):d;let _=[],h=l.keySet,m=u._zod,y=m.def.type;for(let v of Object.keys(f)){if(h.has(v))continue;if(y==="never"){_.push(v);continue}let b=m.run({value:f[v],issues:[]},p);b instanceof Promise?g.push(b.then(S=>zh(S,d,v))):zh(b,d,v)}return _.length&&d.issues.push({code:"unrecognized_keys",keys:_,input:f,inst:t}),g.length?Promise.all(g).then(()=>d):d}});function x2(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(a=>Wi(a,n,Gi())))}),e}var q6=X("$ZodUnion",(t,e)=>{Lt.init(t,e),Ut(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Ut(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Ut(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Ut(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=>lg(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let i=!1,a=[];for(let o of e.options){let s=o._zod.run({value:r.value,issues:[]},n);if(s instanceof Promise)a.push(s),i=!0;else{if(s.issues.length===0)return s;a.push(s)}}return i?Promise.all(a).then(o=>x2(o,r,t,n)):x2(a,r,t,n)}}),Ale=X("$ZodDiscriminatedUnion",(t,e)=>{q6.init(t,e);let r=t._zod.parse;Ut(t._zod,"propValues",()=>{let i={};for(let a of e.options){let o=a._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(a)}"`);for(let[s,c]of Object.entries(o)){i[s]||(i[s]=new Set);for(let u of c)i[s].add(u)}}return i});let n=cg(()=>{let i=e.options,a=new Map;for(let o of i){let s=o._zod.propValues[e.discriminator];if(!s||s.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(let c of s){if(a.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);a.set(c,o)}}return a});t._zod.parse=(i,a)=>{let o=i.value;if(!Od(o))return i.issues.push({code:"invalid_type",expected:"object",input:o,inst:t}),i;let s=n.value.get(o?.[e.discriminator]);return s?s._zod.run(i,a):e.unionFallback?r(i,a):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:o,path:[e.discriminator],inst:t}),i)}}),Mle=X("$ZodIntersection",(t,e)=>{Lt.init(t,e),t._zod.parse=(r,n)=>{let i=r.value,a=e.left._zod.run({value:i,issues:[]},n),o=e.right._zod.run({value:i,issues:[]},n);return a instanceof Promise||o instanceof Promise?Promise.all([a,o]).then(([c,u])=>S2(r,c,u)):S2(r,a,o)}});function z$(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(Rd(t)&&Rd(e)){let r=Object.keys(e),n=Object.keys(t).filter(a=>r.indexOf(a)!==-1),i={...t,...e};for(let a of n){let o=z$(t[a],e[a]);if(!o.valid)return{valid:!1,mergeErrorPath:[a,...o.mergeErrorPath]};i[a]=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{Lt.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;if(!Rd(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:t}),r;let a=[];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?a.push(u.then(l=>{l.issues.length&&r.issues.push(...Ta(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...Ta(c,u.issues)),r.value[c]=u.value)}let s;for(let c in i)o.has(c)||(s=s??[],s.push(c));s&&s.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:t,keys:s})}else{r.value={};for(let o of Reflect.ownKeys(i)){if(o==="__proto__")continue;let s=e.keyType._zod.run({value:o,issues:[]},n);if(s instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(s.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:s.issues.map(u=>Wi(u,n,Gi())),input:o,path:[o],inst:t}),r.value[s.value]=s.value;continue}let c=e.valueType._zod.run({value:i[o],issues:[]},n);c instanceof Promise?a.push(c.then(u=>{u.issues.length&&r.issues.push(...Ta(o,u.issues)),r.value[s.value]=u.value})):(c.issues.length&&r.issues.push(...Ta(o,c.issues)),r.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>r):r}}),zle=X("$ZodEnum",(t,e)=>{Lt.init(t,e);let r=b6(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>$6.has(typeof n)).map(n=>typeof n=="string"?Pc(n):n.toString()).join("|")})$`),t._zod.parse=(n,i)=>{let a=n.value;return t._zod.values.has(a)||n.issues.push({code:"invalid_value",values:r,input:a,inst:t}),n}}),Ule=X("$ZodLiteral",(t,e)=>{Lt.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Pc(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}}),Lle=X("$ZodTransform",(t,e)=>{Lt.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 To;return r.value=i,r}}),qle=X("$ZodOptional",(t,e)=>{Lt.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Ut(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Ut(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${lg(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)}),Fle=X("$ZodNullable",(t,e)=>{Lt.init(t,e),Ut(t._zod,"optin",()=>e.innerType._zod.optin),Ut(t._zod,"optout",()=>e.innerType._zod.optout),Ut(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${lg(r.source)}|null)$`):void 0}),Ut(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)}),Zle=X("$ZodDefault",(t,e)=>{Lt.init(t,e),t._zod.optin="optional",Ut(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(a=>w2(a,e)):w2(i,e)}});function w2(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Hle=X("$ZodPrefault",(t,e)=>{Lt.init(t,e),t._zod.optin="optional",Ut(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))}),Ble=X("$ZodNonOptional",(t,e)=>{Lt.init(t,e),Ut(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(a=>$2(a,t)):$2(i,t)}});function $2(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 Vle=X("$ZodCatch",(t,e)=>{Lt.init(t,e),t._zod.optin="optional",Ut(t._zod,"optout",()=>e.innerType._zod.optout),Ut(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(a=>(r.value=a.value,a.issues.length&&(r.value=e.catchValue({...r,error:{issues:a.issues.map(o=>Wi(o,n,Gi()))},input:r.value}),r.issues=[]),r)):(r.value=i.value,i.issues.length&&(r.value=e.catchValue({...r,error:{issues:i.issues.map(a=>Wi(a,n,Gi()))},input:r.value}),r.issues=[]),r)}}),Gle=X("$ZodPipe",(t,e)=>{Lt.init(t,e),Ut(t._zod,"values",()=>e.in._zod.values),Ut(t._zod,"optin",()=>e.in._zod.optin),Ut(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(a=>E2(a,e,n)):E2(i,e,n)}});function E2(t,e,r){return lc(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var Wle=X("$ZodReadonly",(t,e)=>{Lt.init(t,e),Ut(t._zod,"propValues",()=>e.innerType._zod.propValues),Ut(t._zod,"values",()=>e.innerType._zod.values),Ut(t._zod,"optin",()=>e.innerType._zod.optin),Ut(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(k2):k2(i)}});function k2(t){return t.value=Object.freeze(t.value),t}var Kle=X("$ZodCustom",(t,e)=>{Yr.init(t,e),Lt.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(a=>T2(a,r,n,t));T2(i,r,n,t)}});function T2(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(T6(i))}}var Jle=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},Xle=()=>{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 ${Jle(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Y$(n.values[0])}`:`Invalid option: expected one of ${A$(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",a=e(n.origin);return a?`Too big: expected ${n.origin??"value"} to have ${i}${n.maximum.toString()} ${a.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",a=e(n.origin);return a?`Too small: expected ${n.origin} to have ${i}${n.minimum.toString()} ${a.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":""}: ${A$(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 Yle(){return{localeError:Xle()}}var U$=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 Qle(){return new U$}var Uh=Qle();function ede(t,e){return new t({type:"string",...Te(e)})}function tde(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...Te(e)})}function I2(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...Te(e)})}function rde(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...Te(e)})}function nde(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Te(e)})}function ide(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Te(e)})}function ade(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Te(e)})}function ode(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...Te(e)})}function sde(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...Te(e)})}function cde(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...Te(e)})}function ude(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...Te(e)})}function lde(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...Te(e)})}function dde(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...Te(e)})}function pde(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...Te(e)})}function fde(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...Te(e)})}function mde(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...Te(e)})}function hde(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...Te(e)})}function gde(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Te(e)})}function vde(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Te(e)})}function yde(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...Te(e)})}function _de(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...Te(e)})}function bde(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...Te(e)})}function xde(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...Te(e)})}function Sde(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Te(e)})}function wde(t,e){return new t({type:"string",format:"date",check:"string_format",...Te(e)})}function $de(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...Te(e)})}function Ede(t,e){return new t({type:"string",format:"duration",check:"string_format",...Te(e)})}function kde(t,e){return new t({type:"number",checks:[],...Te(e)})}function Tde(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...Te(e)})}function Ide(t,e){return new t({type:"boolean",...Te(e)})}function Pde(t,e){return new t({type:"null",...Te(e)})}function Ode(t){return new t({type:"unknown"})}function Rde(t,e){return new t({type:"never",...Te(e)})}function P2(t,e){return new D6({check:"less_than",...Te(e),value:t,inclusive:!1})}function _$(t,e){return new D6({check:"less_than",...Te(e),value:t,inclusive:!0})}function O2(t,e){return new z6({check:"greater_than",...Te(e),value:t,inclusive:!1})}function b$(t,e){return new z6({check:"greater_than",...Te(e),value:t,inclusive:!0})}function R2(t,e){return new Hue({check:"multiple_of",...Te(e),value:t})}function F6(t,e){return new Vue({check:"max_length",...Te(e),maximum:t})}function Kh(t,e){return new Gue({check:"min_length",...Te(e),minimum:t})}function Z6(t,e){return new Wue({check:"length_equals",...Te(e),length:t})}function Cde(t,e){return new Kue({check:"string_format",format:"regex",...Te(e),pattern:t})}function Nde(t){return new Jue({check:"string_format",format:"lowercase",...Te(t)})}function jde(t){return new Xue({check:"string_format",format:"uppercase",...Te(t)})}function Ade(t,e){return new Yue({check:"string_format",format:"includes",...Te(e),includes:t})}function Mde(t,e){return new Que({check:"string_format",format:"starts_with",...Te(e),prefix:t})}function Dde(t,e){return new ele({check:"string_format",format:"ends_with",...Te(e),suffix:t})}function Nd(t){return new tle({check:"overwrite",tx:t})}function zde(t){return Nd(e=>e.normalize(t))}function Ude(){return Nd(t=>t.trim())}function Lde(){return Nd(t=>t.toLowerCase())}function qde(){return Nd(t=>t.toUpperCase())}function Fde(t,e,r){return new t({type:"array",element:e,...Te(r)})}function Zde(t,e,r){let n=Te(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Hde(t,e,r){return new t({type:"custom",check:"custom",fn:e,...Te(r)})}var H6={};z2(H6,{time:()=>J6,duration:()=>Y6,datetime:()=>V6,date:()=>W6,ZodISOTime:()=>K6,ZodISODuration:()=>X6,ZodISODateTime:()=>B6,ZodISODate:()=>G6});var B6=X("ZodISODateTime",(t,e)=>{mle.init(t,e),Kt.init(t,e)});function V6(t){return Sde(B6,t)}var G6=X("ZodISODate",(t,e)=>{hle.init(t,e),Kt.init(t,e)});function W6(t){return wde(G6,t)}var K6=X("ZodISOTime",(t,e)=>{gle.init(t,e),Kt.init(t,e)});function J6(t){return $de(K6,t)}var X6=X("ZodISODuration",(t,e)=>{vle.init(t,e),Kt.init(t,e)});function Y6(t){return Ede(X6,t)}var Q6=(t,e)=>{P6.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>due(t,r)},flatten:{value:r=>lue(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},CPe=X("ZodError",Q6),fg=X("ZodError",Q6,{Parent:Error}),Bde=pue(fg),Vde=fue(fg),Gde=R6(fg),Wde=C6(fg),Wt=X("ZodType",(t,e)=>(Lt.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)=>Ca(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t),t.parse=(r,n)=>Bde(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Gde(t,r,n),t.parseAsync=async(r,n)=>Vde(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Wde(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(zpe(r,n)),t.superRefine=r=>t.check(Upe(r)),t.overwrite=r=>t.check(Nd(r)),t.optional=()=>_e(t),t.nullable=()=>j2(t),t.nullish=()=>_e(j2(t)),t.nonoptional=r=>Ope(t,r),t.array=()=>at(t),t.or=r=>Zt([t,r]),t.and=r=>eE(t,r),t.transform=r=>q$(t,oU(r)),t.default=r=>Tpe(t,r),t.prefault=r=>Ppe(t,r),t.catch=r=>Cpe(t,r),t.pipe=r=>q$(t,r),t.readonly=()=>Ape(t),t.describe=r=>{let n=t.clone();return Uh.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Uh.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Uh.get(t);let n=t.clone();return Uh.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),eU=X("_ZodString",(t,e)=>{Q$.init(t,e),Wt.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(Cde(...n)),t.includes=(...n)=>t.check(Ade(...n)),t.startsWith=(...n)=>t.check(Mde(...n)),t.endsWith=(...n)=>t.check(Dde(...n)),t.min=(...n)=>t.check(Kh(...n)),t.max=(...n)=>t.check(F6(...n)),t.length=(...n)=>t.check(Z6(...n)),t.nonempty=(...n)=>t.check(Kh(1,...n)),t.lowercase=n=>t.check(Nde(n)),t.uppercase=n=>t.check(jde(n)),t.trim=()=>t.check(Ude()),t.normalize=(...n)=>t.check(zde(...n)),t.toLowerCase=()=>t.check(Lde()),t.toUpperCase=()=>t.check(qde())}),Kde=X("ZodString",(t,e)=>{Q$.init(t,e),eU.init(t,e),t.email=r=>t.check(tde(Jde,r)),t.url=r=>t.check(ode(Xde,r)),t.jwt=r=>t.check(xde(ppe,r)),t.emoji=r=>t.check(sde(Yde,r)),t.guid=r=>t.check(I2(C2,r)),t.uuid=r=>t.check(rde(Lh,r)),t.uuidv4=r=>t.check(nde(Lh,r)),t.uuidv6=r=>t.check(ide(Lh,r)),t.uuidv7=r=>t.check(ade(Lh,r)),t.nanoid=r=>t.check(cde(Qde,r)),t.guid=r=>t.check(I2(C2,r)),t.cuid=r=>t.check(ude(epe,r)),t.cuid2=r=>t.check(lde(tpe,r)),t.ulid=r=>t.check(dde(rpe,r)),t.base64=r=>t.check(yde(upe,r)),t.base64url=r=>t.check(_de(lpe,r)),t.xid=r=>t.check(pde(npe,r)),t.ksuid=r=>t.check(fde(ipe,r)),t.ipv4=r=>t.check(mde(ape,r)),t.ipv6=r=>t.check(hde(ope,r)),t.cidrv4=r=>t.check(gde(spe,r)),t.cidrv6=r=>t.check(vde(cpe,r)),t.e164=r=>t.check(bde(dpe,r)),t.datetime=r=>t.check(V6(r)),t.date=r=>t.check(W6(r)),t.time=r=>t.check(J6(r)),t.duration=r=>t.check(Y6(r))});function G(t){return ede(Kde,t)}var Kt=X("ZodStringFormat",(t,e)=>{Ft.init(t,e),eU.init(t,e)}),Jde=X("ZodEmail",(t,e)=>{ale.init(t,e),Kt.init(t,e)}),C2=X("ZodGUID",(t,e)=>{nle.init(t,e),Kt.init(t,e)}),Lh=X("ZodUUID",(t,e)=>{ile.init(t,e),Kt.init(t,e)}),Xde=X("ZodURL",(t,e)=>{ole.init(t,e),Kt.init(t,e)}),Yde=X("ZodEmoji",(t,e)=>{sle.init(t,e),Kt.init(t,e)}),Qde=X("ZodNanoID",(t,e)=>{cle.init(t,e),Kt.init(t,e)}),epe=X("ZodCUID",(t,e)=>{ule.init(t,e),Kt.init(t,e)}),tpe=X("ZodCUID2",(t,e)=>{lle.init(t,e),Kt.init(t,e)}),rpe=X("ZodULID",(t,e)=>{dle.init(t,e),Kt.init(t,e)}),npe=X("ZodXID",(t,e)=>{ple.init(t,e),Kt.init(t,e)}),ipe=X("ZodKSUID",(t,e)=>{fle.init(t,e),Kt.init(t,e)}),ape=X("ZodIPv4",(t,e)=>{yle.init(t,e),Kt.init(t,e)}),ope=X("ZodIPv6",(t,e)=>{_le.init(t,e),Kt.init(t,e)}),spe=X("ZodCIDRv4",(t,e)=>{ble.init(t,e),Kt.init(t,e)}),cpe=X("ZodCIDRv6",(t,e)=>{xle.init(t,e),Kt.init(t,e)}),upe=X("ZodBase64",(t,e)=>{Sle.init(t,e),Kt.init(t,e)}),lpe=X("ZodBase64URL",(t,e)=>{$le.init(t,e),Kt.init(t,e)}),dpe=X("ZodE164",(t,e)=>{Ele.init(t,e),Kt.init(t,e)}),ppe=X("ZodJWT",(t,e)=>{Tle.init(t,e),Kt.init(t,e)}),tU=X("ZodNumber",(t,e)=>{L6.init(t,e),Wt.init(t,e),t.gt=(n,i)=>t.check(O2(n,i)),t.gte=(n,i)=>t.check(b$(n,i)),t.min=(n,i)=>t.check(b$(n,i)),t.lt=(n,i)=>t.check(P2(n,i)),t.lte=(n,i)=>t.check(_$(n,i)),t.max=(n,i)=>t.check(_$(n,i)),t.int=n=>t.check(N2(n)),t.safe=n=>t.check(N2(n)),t.positive=n=>t.check(O2(0,n)),t.nonnegative=n=>t.check(b$(0,n)),t.negative=n=>t.check(P2(0,n)),t.nonpositive=n=>t.check(_$(0,n)),t.multipleOf=(n,i)=>t.check(R2(n,i)),t.step=(n,i)=>t.check(R2(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 Nt(t){return kde(tU,t)}var fpe=X("ZodNumberFormat",(t,e)=>{Ile.init(t,e),tU.init(t,e)});function N2(t){return Tde(fpe,t)}var mpe=X("ZodBoolean",(t,e)=>{Ple.init(t,e),Wt.init(t,e)});function $r(t){return Ide(mpe,t)}var hpe=X("ZodNull",(t,e)=>{Ole.init(t,e),Wt.init(t,e)});function rU(t){return Pde(hpe,t)}var gpe=X("ZodUnknown",(t,e)=>{Rle.init(t,e),Wt.init(t,e)});function ir(){return Ode(gpe)}var vpe=X("ZodNever",(t,e)=>{Cle.init(t,e),Wt.init(t,e)});function ype(t){return Rde(vpe,t)}var _pe=X("ZodArray",(t,e)=>{Nle.init(t,e),Wt.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Kh(r,n)),t.nonempty=r=>t.check(Kh(1,r)),t.max=(r,n)=>t.check(F6(r,n)),t.length=(r,n)=>t.check(Z6(r,n)),t.unwrap=()=>t.element});function at(t,e){return Fde(_pe,t,e)}var nU=X("ZodObject",(t,e)=>{jle.init(t,e),Wt.init(t,e),zt.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Er(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:ir()}),t.loose=()=>t.clone({...t._zod.def,catchall:ir()}),t.strict=()=>t.clone({...t._zod.def,catchall:ype()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>zt.extend(t,r),t.merge=r=>zt.merge(t,r),t.pick=r=>zt.pick(t,r),t.omit=r=>zt.omit(t,r),t.partial=(...r)=>zt.partial(sU,t,r[0]),t.required=(...r)=>zt.required(cU,t,r[0])});function re(t,e){let r={type:"object",get shape(){return zt.assignProp(this,"shape",{...t}),this.shape},...zt.normalizeParams(e)};return new nU(r)}function ei(t,e){return new nU({type:"object",get shape(){return zt.assignProp(this,"shape",{...t}),this.shape},catchall:ir(),...zt.normalizeParams(e)})}var iU=X("ZodUnion",(t,e)=>{q6.init(t,e),Wt.init(t,e),t.options=e.options});function Zt(t,e){return new iU({type:"union",options:t,...zt.normalizeParams(e)})}var bpe=X("ZodDiscriminatedUnion",(t,e)=>{iU.init(t,e),Ale.init(t,e)});function aU(t,e,r){return new bpe({type:"union",options:e,discriminator:t,...zt.normalizeParams(r)})}var xpe=X("ZodIntersection",(t,e)=>{Mle.init(t,e),Wt.init(t,e)});function eE(t,e){return new xpe({type:"intersection",left:t,right:e})}var Spe=X("ZodRecord",(t,e)=>{Dle.init(t,e),Wt.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function ar(t,e,r){return new Spe({type:"record",keyType:t,valueType:e,...zt.normalizeParams(r)})}var L$=X("ZodEnum",(t,e)=>{zle.init(t,e),Wt.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 a={};for(let o of n)if(r.has(o))a[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new L$({...e,checks:[],...zt.normalizeParams(i),entries:a})},t.exclude=(n,i)=>{let a={...e.entries};for(let o of n)if(r.has(o))delete a[o];else throw new Error(`Key ${o} not found in enum`);return new L$({...e,checks:[],...zt.normalizeParams(i),entries:a})}});function Er(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new L$({type:"enum",entries:r,...zt.normalizeParams(e)})}var wpe=X("ZodLiteral",(t,e)=>{Ule.init(t,e),Wt.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 be(t,e){return new wpe({type:"literal",values:Array.isArray(t)?t:[t],...zt.normalizeParams(e)})}var $pe=X("ZodTransform",(t,e)=>{Lle.init(t,e),Wt.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=a=>{if(typeof a=="string")r.issues.push(zt.issue(a,r.value,e));else{let o=a;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(zt.issue(o))}};let i=e.transform(r.value,r);return i instanceof Promise?i.then(a=>(r.value=a,r)):(r.value=i,r)}});function oU(t){return new $pe({type:"transform",transform:t})}var sU=X("ZodOptional",(t,e)=>{qle.init(t,e),Wt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function _e(t){return new sU({type:"optional",innerType:t})}var Epe=X("ZodNullable",(t,e)=>{Fle.init(t,e),Wt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function j2(t){return new Epe({type:"nullable",innerType:t})}var kpe=X("ZodDefault",(t,e)=>{Zle.init(t,e),Wt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Tpe(t,e){return new kpe({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var Ipe=X("ZodPrefault",(t,e)=>{Hle.init(t,e),Wt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ppe(t,e){return new Ipe({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var cU=X("ZodNonOptional",(t,e)=>{Ble.init(t,e),Wt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ope(t,e){return new cU({type:"nonoptional",innerType:t,...zt.normalizeParams(e)})}var Rpe=X("ZodCatch",(t,e)=>{Vle.init(t,e),Wt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Cpe(t,e){return new Rpe({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Npe=X("ZodPipe",(t,e)=>{Gle.init(t,e),Wt.init(t,e),t.in=e.in,t.out=e.out});function q$(t,e){return new Npe({type:"pipe",in:t,out:e})}var jpe=X("ZodReadonly",(t,e)=>{Wle.init(t,e),Wt.init(t,e)});function Ape(t){return new jpe({type:"readonly",innerType:t})}var uU=X("ZodCustom",(t,e)=>{Kle.init(t,e),Wt.init(t,e)});function Mpe(t,e){let r=new Yr({check:"custom",...zt.normalizeParams(e)});return r._zod.check=t,r}function Dpe(t,e){return Zde(uU,t??(()=>!0),e)}function zpe(t,e={}){return Hde(uU,t,e)}function Upe(t,e){let r=Mpe(n=>(n.addIssue=i=>{if(typeof i=="string")n.issues.push(zt.issue(i,n.value,r._zod.def));else{let a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=r),a.continue??(a.continue=!r._zod.def.abort),n.issues.push(zt.issue(a))}},t(n.value,n)),e);return r}function lU(t,e){return q$(oU(t),e)}Gi(Yle());var tE="io.modelcontextprotocol/related-task",mg="2.0",xi=Dpe(t=>t!==null&&(typeof t=="object"||typeof t=="function")),dU=Zt([G(),Nt().int()]),pU=G(),Lpe=ei({ttl:Zt([Nt(),rU()]).optional(),pollInterval:Nt().optional()}),rE=ei({taskId:G()}),qpe=ei({progressToken:dU.optional(),[tE]:rE.optional()}),Qr=ei({task:Lpe.optional(),_meta:qpe.optional()}),mr=re({method:G(),params:Qr.optional()}),Io=ei({_meta:re({[tE]:_e(rE)}).passthrough().optional()}),Nn=re({method:G(),params:Io.optional()}),kr=ei({_meta:ei({[tE]:rE.optional()}).optional()}),hg=Zt([G(),Nt().int()]),Fpe=re({jsonrpc:be(mg),id:hg,...mr.shape}).strict();var Zpe=re({jsonrpc:be(mg),...Nn.shape}).strict();var Hpe=re({jsonrpc:be(mg),id:hg,result:kr}).strict();var A2;(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"})(A2||(A2={}));var Bpe=re({jsonrpc:be(mg),id:hg,error:re({code:Nt().int(),message:G(),data:_e(ir())})}).strict();var NPe=Zt([Fpe,Zpe,Hpe,Bpe]),fU=kr.strict(),Vpe=Io.extend({requestId:hg,reason:G().optional()}),mU=Nn.extend({method:be("notifications/cancelled"),params:Vpe}),Gpe=re({src:G(),mimeType:G().optional(),sizes:at(G()).optional()}),jd=re({icons:at(Gpe).optional()}),$c=re({name:G(),title:G().optional()}),hU=$c.extend({...$c.shape,...jd.shape,version:G(),websiteUrl:G().optional()}),Wpe=eE(re({applyDefaults:$r().optional()}),ar(G(),ir())),Kpe=lU(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,eE(re({form:Wpe.optional(),url:xi.optional()}),ar(G(),ir()).optional())),Jpe=re({list:_e(re({}).passthrough()),cancel:_e(re({}).passthrough()),requests:_e(re({sampling:_e(re({createMessage:_e(re({}).passthrough())}).passthrough()),elicitation:_e(re({create:_e(re({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),Xpe=re({list:_e(re({}).passthrough()),cancel:_e(re({}).passthrough()),requests:_e(re({tools:_e(re({call:_e(re({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),Ype=re({experimental:ar(G(),xi).optional(),sampling:re({context:xi.optional(),tools:xi.optional()}).optional(),elicitation:Kpe.optional(),roots:re({listChanged:$r().optional()}).optional(),tasks:_e(Jpe)}),Qpe=Qr.extend({protocolVersion:G(),capabilities:Ype,clientInfo:hU}),efe=mr.extend({method:be("initialize"),params:Qpe}),tfe=re({experimental:ar(G(),xi).optional(),logging:xi.optional(),completions:xi.optional(),prompts:_e(re({listChanged:_e($r())})),resources:re({subscribe:$r().optional(),listChanged:$r().optional()}).optional(),tools:re({listChanged:$r().optional()}).optional(),tasks:_e(Xpe)}).passthrough(),rfe=kr.extend({protocolVersion:G(),capabilities:tfe,serverInfo:hU,instructions:G().optional()}),nfe=Nn.extend({method:be("notifications/initialized")}),gU=mr.extend({method:be("ping")}),ife=re({progress:Nt(),total:_e(Nt()),message:_e(G())}),afe=re({...Io.shape,...ife.shape,progressToken:dU}),vU=Nn.extend({method:be("notifications/progress"),params:afe}),ofe=Qr.extend({cursor:pU.optional()}),Ad=mr.extend({params:ofe.optional()}),Md=kr.extend({nextCursor:_e(pU)}),Dd=re({taskId:G(),status:Er(["working","input_required","completed","failed","cancelled"]),ttl:Zt([Nt(),rU()]),createdAt:G(),lastUpdatedAt:G(),pollInterval:_e(Nt()),statusMessage:_e(G())}),yU=kr.extend({task:Dd}),sfe=Io.merge(Dd),_U=Nn.extend({method:be("notifications/tasks/status"),params:sfe}),bU=mr.extend({method:be("tasks/get"),params:Qr.extend({taskId:G()})}),xU=kr.merge(Dd),SU=mr.extend({method:be("tasks/result"),params:Qr.extend({taskId:G()})}),wU=Ad.extend({method:be("tasks/list")}),$U=Md.extend({tasks:at(Dd)}),jPe=mr.extend({method:be("tasks/cancel"),params:Qr.extend({taskId:G()})}),APe=kr.merge(Dd),EU=re({uri:G(),mimeType:_e(G()),_meta:ar(G(),ir()).optional()}),kU=EU.extend({text:G()}),nE=G().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),TU=EU.extend({blob:nE}),Oc=re({audience:at(Er(["user","assistant"])).optional(),priority:Nt().min(0).max(1).optional(),lastModified:H6.datetime({offset:!0}).optional()}),IU=re({...$c.shape,...jd.shape,uri:G(),description:_e(G()),mimeType:_e(G()),annotations:Oc.optional(),_meta:_e(ei({}))}),cfe=re({...$c.shape,...jd.shape,uriTemplate:G(),description:_e(G()),mimeType:_e(G()),annotations:Oc.optional(),_meta:_e(ei({}))}),ufe=Ad.extend({method:be("resources/list")}),lfe=Md.extend({resources:at(IU)}),dfe=Ad.extend({method:be("resources/templates/list")}),pfe=Md.extend({resourceTemplates:at(cfe)}),iE=Qr.extend({uri:G()}),ffe=iE,mfe=mr.extend({method:be("resources/read"),params:ffe}),hfe=kr.extend({contents:at(Zt([kU,TU]))}),gfe=Nn.extend({method:be("notifications/resources/list_changed")}),vfe=iE,yfe=mr.extend({method:be("resources/subscribe"),params:vfe}),_fe=iE,bfe=mr.extend({method:be("resources/unsubscribe"),params:_fe}),xfe=Io.extend({uri:G()}),Sfe=Nn.extend({method:be("notifications/resources/updated"),params:xfe}),wfe=re({name:G(),description:_e(G()),required:_e($r())}),$fe=re({...$c.shape,...jd.shape,description:_e(G()),arguments:_e(at(wfe)),_meta:_e(ei({}))}),Efe=Ad.extend({method:be("prompts/list")}),kfe=Md.extend({prompts:at($fe)}),Tfe=Qr.extend({name:G(),arguments:ar(G(),G()).optional()}),Ife=mr.extend({method:be("prompts/get"),params:Tfe}),aE=re({type:be("text"),text:G(),annotations:Oc.optional(),_meta:ar(G(),ir()).optional()}),oE=re({type:be("image"),data:nE,mimeType:G(),annotations:Oc.optional(),_meta:ar(G(),ir()).optional()}),sE=re({type:be("audio"),data:nE,mimeType:G(),annotations:Oc.optional(),_meta:ar(G(),ir()).optional()}),Pfe=re({type:be("tool_use"),name:G(),id:G(),input:re({}).passthrough(),_meta:_e(re({}).passthrough())}).passthrough(),Ofe=re({type:be("resource"),resource:Zt([kU,TU]),annotations:Oc.optional(),_meta:ar(G(),ir()).optional()}),Rfe=IU.extend({type:be("resource_link")}),cE=Zt([aE,oE,sE,Rfe,Ofe]),Cfe=re({role:Er(["user","assistant"]),content:cE}),Nfe=kr.extend({description:_e(G()),messages:at(Cfe)}),jfe=Nn.extend({method:be("notifications/prompts/list_changed")}),Afe=re({title:G().optional(),readOnlyHint:$r().optional(),destructiveHint:$r().optional(),idempotentHint:$r().optional(),openWorldHint:$r().optional()}),Mfe=re({taskSupport:Er(["required","optional","forbidden"]).optional()}),PU=re({...$c.shape,...jd.shape,description:G().optional(),inputSchema:re({type:be("object"),properties:ar(G(),xi).optional(),required:at(G()).optional()}).catchall(ir()),outputSchema:re({type:be("object"),properties:ar(G(),xi).optional(),required:at(G()).optional()}).catchall(ir()).optional(),annotations:_e(Afe),execution:_e(Mfe),_meta:ar(G(),ir()).optional()}),Dfe=Ad.extend({method:be("tools/list")}),zfe=Md.extend({tools:at(PU)}),OU=kr.extend({content:at(cE).default([]),structuredContent:ar(G(),ir()).optional(),isError:_e($r())}),MPe=OU.or(kr.extend({toolResult:ir()})),Ufe=Qr.extend({name:G(),arguments:_e(ar(G(),ir()))}),Lfe=mr.extend({method:be("tools/call"),params:Ufe}),qfe=Nn.extend({method:be("notifications/tools/list_changed")}),RU=Er(["debug","info","notice","warning","error","critical","alert","emergency"]),Ffe=Qr.extend({level:RU}),Zfe=mr.extend({method:be("logging/setLevel"),params:Ffe}),Hfe=Io.extend({level:RU,logger:G().optional(),data:ir()}),Bfe=Nn.extend({method:be("notifications/message"),params:Hfe}),Vfe=re({name:G().optional()}),Gfe=re({hints:_e(at(Vfe)),costPriority:_e(Nt().min(0).max(1)),speedPriority:_e(Nt().min(0).max(1)),intelligencePriority:_e(Nt().min(0).max(1))}),Wfe=re({mode:_e(Er(["auto","required","none"]))}),Kfe=re({type:be("tool_result"),toolUseId:G().describe("The unique identifier for the corresponding tool call."),content:at(cE).default([]),structuredContent:re({}).passthrough().optional(),isError:_e($r()),_meta:_e(re({}).passthrough())}).passthrough(),Jfe=aU("type",[aE,oE,sE]),Jh=aU("type",[aE,oE,sE,Pfe,Kfe]),Xfe=re({role:Er(["user","assistant"]),content:Zt([Jh,at(Jh)]),_meta:_e(re({}).passthrough())}).passthrough(),Yfe=Qr.extend({messages:at(Xfe),modelPreferences:Gfe.optional(),systemPrompt:G().optional(),includeContext:Er(["none","thisServer","allServers"]).optional(),temperature:Nt().optional(),maxTokens:Nt().int(),stopSequences:at(G()).optional(),metadata:xi.optional(),tools:_e(at(PU)),toolChoice:_e(Wfe)}),Qfe=mr.extend({method:be("sampling/createMessage"),params:Yfe}),eme=kr.extend({model:G(),stopReason:_e(Er(["endTurn","stopSequence","maxTokens"]).or(G())),role:Er(["user","assistant"]),content:Jfe}),tme=kr.extend({model:G(),stopReason:_e(Er(["endTurn","stopSequence","maxTokens","toolUse"]).or(G())),role:Er(["user","assistant"]),content:Zt([Jh,at(Jh)])}),rme=re({type:be("boolean"),title:G().optional(),description:G().optional(),default:$r().optional()}),nme=re({type:be("string"),title:G().optional(),description:G().optional(),minLength:Nt().optional(),maxLength:Nt().optional(),format:Er(["email","uri","date","date-time"]).optional(),default:G().optional()}),ime=re({type:Er(["number","integer"]),title:G().optional(),description:G().optional(),minimum:Nt().optional(),maximum:Nt().optional(),default:Nt().optional()}),ame=re({type:be("string"),title:G().optional(),description:G().optional(),enum:at(G()),default:G().optional()}),ome=re({type:be("string"),title:G().optional(),description:G().optional(),oneOf:at(re({const:G(),title:G()})),default:G().optional()}),sme=re({type:be("string"),title:G().optional(),description:G().optional(),enum:at(G()),enumNames:at(G()).optional(),default:G().optional()}),cme=Zt([ame,ome]),ume=re({type:be("array"),title:G().optional(),description:G().optional(),minItems:Nt().optional(),maxItems:Nt().optional(),items:re({type:be("string"),enum:at(G())}),default:at(G()).optional()}),lme=re({type:be("array"),title:G().optional(),description:G().optional(),minItems:Nt().optional(),maxItems:Nt().optional(),items:re({anyOf:at(re({const:G(),title:G()}))}),default:at(G()).optional()}),dme=Zt([ume,lme]),pme=Zt([sme,cme,dme]),fme=Zt([pme,rme,nme,ime]),mme=Qr.extend({mode:be("form").optional(),message:G(),requestedSchema:re({type:be("object"),properties:ar(G(),fme),required:at(G()).optional()})}),hme=Qr.extend({mode:be("url"),message:G(),elicitationId:G(),url:G().url()}),gme=Zt([mme,hme]),vme=mr.extend({method:be("elicitation/create"),params:gme}),yme=Io.extend({elicitationId:G()}),_me=Nn.extend({method:be("notifications/elicitation/complete"),params:yme}),bme=kr.extend({action:Er(["accept","decline","cancel"]),content:lU(t=>t===null?void 0:t,ar(G(),Zt([G(),Nt(),$r(),at(G())])).optional())}),xme=re({type:be("ref/resource"),uri:G()}),Sme=re({type:be("ref/prompt"),name:G()}),wme=Qr.extend({ref:Zt([Sme,xme]),argument:re({name:G(),value:G()}),context:re({arguments:ar(G(),G()).optional()}).optional()}),$me=mr.extend({method:be("completion/complete"),params:wme});var Eme=kr.extend({completion:ei({values:at(G()).max(100),total:_e(Nt().int()),hasMore:_e($r())})}),kme=re({uri:G().startsWith("file://"),name:G().optional(),_meta:ar(G(),ir()).optional()}),Tme=mr.extend({method:be("roots/list")}),Ime=kr.extend({roots:at(kme)}),Pme=Nn.extend({method:be("notifications/roots/list_changed")}),DPe=Zt([gU,efe,$me,Zfe,Ife,Efe,ufe,dfe,mfe,yfe,bfe,Lfe,Dfe,bU,SU,wU]),zPe=Zt([mU,vU,nfe,Pme,_U]),UPe=Zt([fU,eme,tme,bme,Ime,xU,$U,yU]),LPe=Zt([gU,Qfe,vme,Tme,bU,SU,wU]),qPe=Zt([mU,vU,Bfe,Sfe,gfe,qfe,jfe,_U,_me]),FPe=Zt([fU,rfe,Eme,Nfe,kfe,lfe,pfe,hfe,OU,zfe,xU,$U,yU]);var ZPe=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var HPe=D2(hae(),1),BPe=D2(uoe(),1);var M2;(function(t){t.Completable="McpCompletable"})(M2||(M2={}));function CU({prompt:t,options:e}){let{systemPrompt:r,settingSources:n,sandbox:i,...a}=e??{},o,s;r===void 0?o="":typeof r=="string"?o=r:r.type==="preset"&&(s=r.append);let c=a.pathToClaudeCodeExecutable;if(!c){let Z=(0,J2.fileURLToPath)(Ome.url),J=(0,S$.join)(Z,"..");c=(0,S$.join)(J,"cli.js")}process.env.CLAUDE_AGENT_SDK_VERSION="0.1.76";let{abortController:u=Y2(),additionalDirectories:l=[],agents:d,allowedTools:p=[],betas:f,canUseTool:g,continue:_,cwd:h,disallowedTools:m=[],tools:y,env:v,executable:b=m6()?"bun":"node",executableArgs:S=[],extraArgs:x={},fallbackModel:w,enableFileCheckpointing:k,forkSession:O,hooks:A,includePartialMessages:M,persistSession:L,maxThinkingTokens:B,maxTurns:U,maxBudgetUsd:Y,mcpServers:me,model:et,outputFormat:ht,permissionMode:fe="default",allowDangerouslySkipPermissions:F=!1,permissionPromptToolName:I,plugins:D,resume:C,resumeSessionAt:$,stderr:T,strictMcpConfig:N}=a,W=ht?.type==="json_schema"?ht.schema:void 0,K=v;if(K||(K={...process.env}),K.CLAUDE_CODE_ENTRYPOINT||(K.CLAUDE_CODE_ENTRYPOINT="sdk-ts"),k&&(K.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true"),!c)throw new Error("pathToClaudeCodeExecutable is required");let pe={},ce=new Map;if(me)for(let[Z,J]of Object.entries(me))J.type==="sdk"&&"instance"in J?(ce.set(Z,J.instance),pe[Z]={type:"sdk",name:Z}):pe[Z]=J;let je=typeof t=="string",P=new $$({abortController:u,additionalDirectories:l,betas:f,cwd:h,executable:b,executableArgs:S,extraArgs:x,pathToClaudeCodeExecutable:c,env:K,forkSession:O,stderr:T,maxThinkingTokens:B,maxTurns:U,maxBudgetUsd:Y,model:et,fallbackModel:w,jsonSchema:W,permissionMode:fe,allowDangerouslySkipPermissions:F,permissionPromptToolName:I,continueConversation:_,resume:C,resumeSessionAt:$,settingSources:n??[],allowedTools:p,disallowedTools:m,tools:y,mcpServers:pe,strictMcpConfig:N,canUseTool:!!g,hooks:!!A,includePartialMessages:M,persistSession:L,plugins:D,sandbox:i,spawnClaudeCodeProcess:a.spawnClaudeCodeProcess}),R={systemPrompt:o,appendSystemPrompt:s,agents:d},z=new T$(P,je,g,A,u,ce,W,R);return typeof t=="string"?P.write(JSON.stringify({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:t}]},parent_tool_use_id:null})+` -`):z.streamInput(t),z}var gg=class{dbManager;sessionManager;constructor(e,r){this.dbManager=e,this.sessionManager=r}async startSession(e,r){let n={lastCwd:void 0},i=this.findClaudeExecutable(),a=this.getModelId(),o=["Bash","Read","Write","Edit","Grep","Glob","WebFetch","WebSearch","Task","NotebookEdit","AskUserQuestion","TodoWrite"],s=this.createMessageGenerator(e,n),c=!!e.memorySessionId;if(E.info("SDK","Starting SDK query",{sessionDbId:e.sessionDbId,contentSessionId:e.contentSessionId,memorySessionId:e.memorySessionId,hasRealMemorySessionId:c,resume_parameter:c?e.memorySessionId:"(none - fresh start)",lastPromptNumber:e.lastPromptNumber}),e.lastPromptNumber>1){let d=c;E.debug("SDK",`[ALIGNMENT] Resume Decision | contentSessionId=${e.contentSessionId} | memorySessionId=${e.memorySessionId} | prompt#=${e.lastPromptNumber} | hasRealMemorySessionId=${c} | willResume=${d} | resumeWith=${d?e.memorySessionId:"NONE"}`)}else{let d=c;E.debug("SDK",`[ALIGNMENT] First Prompt (INIT) | contentSessionId=${e.contentSessionId} | prompt#=${e.lastPromptNumber} | hasStaleMemoryId=${d} | action=START_FRESH | Will capture new memorySessionId from SDK response`),d&&E.warn("SDK",`Skipping resume for INIT prompt despite existing memorySessionId=${e.memorySessionId} - SDK context was lost (worker restart or crash recovery)`)}let u=CU({prompt:s,options:{model:a,...c&&e.lastPromptNumber>1&&{resume:e.memorySessionId},disallowedTools:o,abortController:e.abortController,pathToClaudeCodeExecutable:i,spawnClaudeCodeProcess:J4(e.sessionDbId)}});for await(let d of u){if(!e.memorySessionId&&d.session_id){e.memorySessionId=d.session_id,this.dbManager.getSessionStore().updateMemorySessionId(e.sessionDbId,d.session_id);let p=this.dbManager.getSessionStore().getSessionById(e.sessionDbId),f=p?.memory_session_id===d.session_id;E.info("SESSION",`MEMORY_ID_CAPTURED | sessionDbId=${e.sessionDbId} | memorySessionId=${d.session_id} | dbVerified=${f}`,{sessionId:e.sessionDbId,memorySessionId:d.session_id}),f||E.error("SESSION",`MEMORY_ID_MISMATCH | sessionDbId=${e.sessionDbId} | expected=${d.session_id} | got=${p?.memory_session_id}`,{sessionId:e.sessionDbId}),E.debug("SDK",`[ALIGNMENT] Captured | contentSessionId=${e.contentSessionId} \u2192 memorySessionId=${d.session_id} | Future prompts will resume with this ID`)}if(d.type==="assistant"){let p=d.message.content,f=Array.isArray(p)?p.filter(v=>v.type==="text").map(v=>v.text).join(` + })));`),p.write(`newResult[${uc(y)}] = ${v}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let m=p.compile();return(y,v)=>m(d,y,v)},i,a=Od,o=!j$.jitless,c=o&&w6.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=r.value);let f=d.value;if(!a(f))return d.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),d;let g=[];if(o&&c&&p?.async===!1&&p.jitless!==!0)i||(i=n(e.shape)),d=i(d,p);else{d.value={};let v=l.shape;for(let b of l.keys){let S=v[b],x=S._zod.run({value:f[b],issues:[]},p),w=S._zod.optin==="optional"&&S._zod.optout==="optional";x instanceof Promise?g.push(x.then(k=>w?b2(k,d,b,f):zh(k,d,b))):w?b2(x,d,b,f):zh(x,d,b)}}if(!u)return g.length?Promise.all(g).then(()=>d):d;let _=[],h=l.keySet,m=u._zod,y=m.def.type;for(let v of Object.keys(f)){if(h.has(v))continue;if(y==="never"){_.push(v);continue}let b=m.run({value:f[v],issues:[]},p);b instanceof Promise?g.push(b.then(S=>zh(S,d,v))):zh(b,d,v)}return _.length&&d.issues.push({code:"unrecognized_keys",keys:_,input:f,inst:t}),g.length?Promise.all(g).then(()=>d):d}});function x2(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(a=>Wi(a,n,Gi())))}),e}var q6=X("$ZodUnion",(t,e)=>{Lt.init(t,e),Ut(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Ut(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Ut(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Ut(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=>lg(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let i=!1,a=[];for(let o of e.options){let s=o._zod.run({value:r.value,issues:[]},n);if(s instanceof Promise)a.push(s),i=!0;else{if(s.issues.length===0)return s;a.push(s)}}return i?Promise.all(a).then(o=>x2(o,r,t,n)):x2(a,r,t,n)}}),Ale=X("$ZodDiscriminatedUnion",(t,e)=>{q6.init(t,e);let r=t._zod.parse;Ut(t._zod,"propValues",()=>{let i={};for(let a of e.options){let o=a._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(a)}"`);for(let[s,c]of Object.entries(o)){i[s]||(i[s]=new Set);for(let u of c)i[s].add(u)}}return i});let n=cg(()=>{let i=e.options,a=new Map;for(let o of i){let s=o._zod.propValues[e.discriminator];if(!s||s.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(let c of s){if(a.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);a.set(c,o)}}return a});t._zod.parse=(i,a)=>{let o=i.value;if(!Od(o))return i.issues.push({code:"invalid_type",expected:"object",input:o,inst:t}),i;let s=n.value.get(o?.[e.discriminator]);return s?s._zod.run(i,a):e.unionFallback?r(i,a):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:o,path:[e.discriminator],inst:t}),i)}}),Mle=X("$ZodIntersection",(t,e)=>{Lt.init(t,e),t._zod.parse=(r,n)=>{let i=r.value,a=e.left._zod.run({value:i,issues:[]},n),o=e.right._zod.run({value:i,issues:[]},n);return a instanceof Promise||o instanceof Promise?Promise.all([a,o]).then(([c,u])=>S2(r,c,u)):S2(r,a,o)}});function z$(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(Rd(t)&&Rd(e)){let r=Object.keys(e),n=Object.keys(t).filter(a=>r.indexOf(a)!==-1),i={...t,...e};for(let a of n){let o=z$(t[a],e[a]);if(!o.valid)return{valid:!1,mergeErrorPath:[a,...o.mergeErrorPath]};i[a]=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{Lt.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;if(!Rd(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:t}),r;let a=[];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?a.push(u.then(l=>{l.issues.length&&r.issues.push(...Ta(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...Ta(c,u.issues)),r.value[c]=u.value)}let s;for(let c in i)o.has(c)||(s=s??[],s.push(c));s&&s.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:t,keys:s})}else{r.value={};for(let o of Reflect.ownKeys(i)){if(o==="__proto__")continue;let s=e.keyType._zod.run({value:o,issues:[]},n);if(s instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(s.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:s.issues.map(u=>Wi(u,n,Gi())),input:o,path:[o],inst:t}),r.value[s.value]=s.value;continue}let c=e.valueType._zod.run({value:i[o],issues:[]},n);c instanceof Promise?a.push(c.then(u=>{u.issues.length&&r.issues.push(...Ta(o,u.issues)),r.value[s.value]=u.value})):(c.issues.length&&r.issues.push(...Ta(o,c.issues)),r.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>r):r}}),zle=X("$ZodEnum",(t,e)=>{Lt.init(t,e);let r=b6(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>$6.has(typeof n)).map(n=>typeof n=="string"?Pc(n):n.toString()).join("|")})$`),t._zod.parse=(n,i)=>{let a=n.value;return t._zod.values.has(a)||n.issues.push({code:"invalid_value",values:r,input:a,inst:t}),n}}),Ule=X("$ZodLiteral",(t,e)=>{Lt.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Pc(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}}),Lle=X("$ZodTransform",(t,e)=>{Lt.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 To;return r.value=i,r}}),qle=X("$ZodOptional",(t,e)=>{Lt.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Ut(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Ut(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${lg(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)}),Fle=X("$ZodNullable",(t,e)=>{Lt.init(t,e),Ut(t._zod,"optin",()=>e.innerType._zod.optin),Ut(t._zod,"optout",()=>e.innerType._zod.optout),Ut(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${lg(r.source)}|null)$`):void 0}),Ut(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)}),Zle=X("$ZodDefault",(t,e)=>{Lt.init(t,e),t._zod.optin="optional",Ut(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(a=>w2(a,e)):w2(i,e)}});function w2(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Hle=X("$ZodPrefault",(t,e)=>{Lt.init(t,e),t._zod.optin="optional",Ut(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))}),Ble=X("$ZodNonOptional",(t,e)=>{Lt.init(t,e),Ut(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(a=>$2(a,t)):$2(i,t)}});function $2(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 Vle=X("$ZodCatch",(t,e)=>{Lt.init(t,e),t._zod.optin="optional",Ut(t._zod,"optout",()=>e.innerType._zod.optout),Ut(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(a=>(r.value=a.value,a.issues.length&&(r.value=e.catchValue({...r,error:{issues:a.issues.map(o=>Wi(o,n,Gi()))},input:r.value}),r.issues=[]),r)):(r.value=i.value,i.issues.length&&(r.value=e.catchValue({...r,error:{issues:i.issues.map(a=>Wi(a,n,Gi()))},input:r.value}),r.issues=[]),r)}}),Gle=X("$ZodPipe",(t,e)=>{Lt.init(t,e),Ut(t._zod,"values",()=>e.in._zod.values),Ut(t._zod,"optin",()=>e.in._zod.optin),Ut(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(a=>E2(a,e,n)):E2(i,e,n)}});function E2(t,e,r){return lc(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var Wle=X("$ZodReadonly",(t,e)=>{Lt.init(t,e),Ut(t._zod,"propValues",()=>e.innerType._zod.propValues),Ut(t._zod,"values",()=>e.innerType._zod.values),Ut(t._zod,"optin",()=>e.innerType._zod.optin),Ut(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(k2):k2(i)}});function k2(t){return t.value=Object.freeze(t.value),t}var Kle=X("$ZodCustom",(t,e)=>{Xr.init(t,e),Lt.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(a=>T2(a,r,n,t));T2(i,r,n,t)}});function T2(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(T6(i))}}var Jle=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},Xle=()=>{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 ${Jle(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Y$(n.values[0])}`:`Invalid option: expected one of ${A$(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",a=e(n.origin);return a?`Too big: expected ${n.origin??"value"} to have ${i}${n.maximum.toString()} ${a.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",a=e(n.origin);return a?`Too small: expected ${n.origin} to have ${i}${n.minimum.toString()} ${a.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":""}: ${A$(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 Yle(){return{localeError:Xle()}}var U$=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 Qle(){return new U$}var Uh=Qle();function ede(t,e){return new t({type:"string",...Te(e)})}function tde(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...Te(e)})}function I2(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...Te(e)})}function rde(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...Te(e)})}function nde(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Te(e)})}function ide(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Te(e)})}function ade(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Te(e)})}function ode(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...Te(e)})}function sde(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...Te(e)})}function cde(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...Te(e)})}function ude(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...Te(e)})}function lde(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...Te(e)})}function dde(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...Te(e)})}function pde(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...Te(e)})}function fde(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...Te(e)})}function mde(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...Te(e)})}function hde(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...Te(e)})}function gde(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Te(e)})}function vde(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Te(e)})}function yde(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...Te(e)})}function _de(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...Te(e)})}function bde(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...Te(e)})}function xde(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...Te(e)})}function Sde(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Te(e)})}function wde(t,e){return new t({type:"string",format:"date",check:"string_format",...Te(e)})}function $de(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...Te(e)})}function Ede(t,e){return new t({type:"string",format:"duration",check:"string_format",...Te(e)})}function kde(t,e){return new t({type:"number",checks:[],...Te(e)})}function Tde(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...Te(e)})}function Ide(t,e){return new t({type:"boolean",...Te(e)})}function Pde(t,e){return new t({type:"null",...Te(e)})}function Ode(t){return new t({type:"unknown"})}function Rde(t,e){return new t({type:"never",...Te(e)})}function P2(t,e){return new D6({check:"less_than",...Te(e),value:t,inclusive:!1})}function _$(t,e){return new D6({check:"less_than",...Te(e),value:t,inclusive:!0})}function O2(t,e){return new z6({check:"greater_than",...Te(e),value:t,inclusive:!1})}function b$(t,e){return new z6({check:"greater_than",...Te(e),value:t,inclusive:!0})}function R2(t,e){return new Hue({check:"multiple_of",...Te(e),value:t})}function F6(t,e){return new Vue({check:"max_length",...Te(e),maximum:t})}function Kh(t,e){return new Gue({check:"min_length",...Te(e),minimum:t})}function Z6(t,e){return new Wue({check:"length_equals",...Te(e),length:t})}function Cde(t,e){return new Kue({check:"string_format",format:"regex",...Te(e),pattern:t})}function Nde(t){return new Jue({check:"string_format",format:"lowercase",...Te(t)})}function jde(t){return new Xue({check:"string_format",format:"uppercase",...Te(t)})}function Ade(t,e){return new Yue({check:"string_format",format:"includes",...Te(e),includes:t})}function Mde(t,e){return new Que({check:"string_format",format:"starts_with",...Te(e),prefix:t})}function Dde(t,e){return new ele({check:"string_format",format:"ends_with",...Te(e),suffix:t})}function Nd(t){return new tle({check:"overwrite",tx:t})}function zde(t){return Nd(e=>e.normalize(t))}function Ude(){return Nd(t=>t.trim())}function Lde(){return Nd(t=>t.toLowerCase())}function qde(){return Nd(t=>t.toUpperCase())}function Fde(t,e,r){return new t({type:"array",element:e,...Te(r)})}function Zde(t,e,r){let n=Te(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Hde(t,e,r){return new t({type:"custom",check:"custom",fn:e,...Te(r)})}var H6={};z2(H6,{time:()=>J6,duration:()=>Y6,datetime:()=>V6,date:()=>W6,ZodISOTime:()=>K6,ZodISODuration:()=>X6,ZodISODateTime:()=>B6,ZodISODate:()=>G6});var B6=X("ZodISODateTime",(t,e)=>{mle.init(t,e),Kt.init(t,e)});function V6(t){return Sde(B6,t)}var G6=X("ZodISODate",(t,e)=>{hle.init(t,e),Kt.init(t,e)});function W6(t){return wde(G6,t)}var K6=X("ZodISOTime",(t,e)=>{gle.init(t,e),Kt.init(t,e)});function J6(t){return $de(K6,t)}var X6=X("ZodISODuration",(t,e)=>{vle.init(t,e),Kt.init(t,e)});function Y6(t){return Ede(X6,t)}var Q6=(t,e)=>{P6.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>due(t,r)},flatten:{value:r=>lue(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},RPe=X("ZodError",Q6),fg=X("ZodError",Q6,{Parent:Error}),Bde=pue(fg),Vde=fue(fg),Gde=R6(fg),Wde=C6(fg),Wt=X("ZodType",(t,e)=>(Lt.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)=>Ca(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t),t.parse=(r,n)=>Bde(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Gde(t,r,n),t.parseAsync=async(r,n)=>Vde(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Wde(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(zpe(r,n)),t.superRefine=r=>t.check(Upe(r)),t.overwrite=r=>t.check(Nd(r)),t.optional=()=>_e(t),t.nullable=()=>j2(t),t.nullish=()=>_e(j2(t)),t.nonoptional=r=>Ope(t,r),t.array=()=>at(t),t.or=r=>Zt([t,r]),t.and=r=>eE(t,r),t.transform=r=>q$(t,oU(r)),t.default=r=>Tpe(t,r),t.prefault=r=>Ppe(t,r),t.catch=r=>Cpe(t,r),t.pipe=r=>q$(t,r),t.readonly=()=>Ape(t),t.describe=r=>{let n=t.clone();return Uh.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Uh.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Uh.get(t);let n=t.clone();return Uh.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),eU=X("_ZodString",(t,e)=>{Q$.init(t,e),Wt.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(Cde(...n)),t.includes=(...n)=>t.check(Ade(...n)),t.startsWith=(...n)=>t.check(Mde(...n)),t.endsWith=(...n)=>t.check(Dde(...n)),t.min=(...n)=>t.check(Kh(...n)),t.max=(...n)=>t.check(F6(...n)),t.length=(...n)=>t.check(Z6(...n)),t.nonempty=(...n)=>t.check(Kh(1,...n)),t.lowercase=n=>t.check(Nde(n)),t.uppercase=n=>t.check(jde(n)),t.trim=()=>t.check(Ude()),t.normalize=(...n)=>t.check(zde(...n)),t.toLowerCase=()=>t.check(Lde()),t.toUpperCase=()=>t.check(qde())}),Kde=X("ZodString",(t,e)=>{Q$.init(t,e),eU.init(t,e),t.email=r=>t.check(tde(Jde,r)),t.url=r=>t.check(ode(Xde,r)),t.jwt=r=>t.check(xde(ppe,r)),t.emoji=r=>t.check(sde(Yde,r)),t.guid=r=>t.check(I2(C2,r)),t.uuid=r=>t.check(rde(Lh,r)),t.uuidv4=r=>t.check(nde(Lh,r)),t.uuidv6=r=>t.check(ide(Lh,r)),t.uuidv7=r=>t.check(ade(Lh,r)),t.nanoid=r=>t.check(cde(Qde,r)),t.guid=r=>t.check(I2(C2,r)),t.cuid=r=>t.check(ude(epe,r)),t.cuid2=r=>t.check(lde(tpe,r)),t.ulid=r=>t.check(dde(rpe,r)),t.base64=r=>t.check(yde(upe,r)),t.base64url=r=>t.check(_de(lpe,r)),t.xid=r=>t.check(pde(npe,r)),t.ksuid=r=>t.check(fde(ipe,r)),t.ipv4=r=>t.check(mde(ape,r)),t.ipv6=r=>t.check(hde(ope,r)),t.cidrv4=r=>t.check(gde(spe,r)),t.cidrv6=r=>t.check(vde(cpe,r)),t.e164=r=>t.check(bde(dpe,r)),t.datetime=r=>t.check(V6(r)),t.date=r=>t.check(W6(r)),t.time=r=>t.check(J6(r)),t.duration=r=>t.check(Y6(r))});function G(t){return ede(Kde,t)}var Kt=X("ZodStringFormat",(t,e)=>{Ft.init(t,e),eU.init(t,e)}),Jde=X("ZodEmail",(t,e)=>{ale.init(t,e),Kt.init(t,e)}),C2=X("ZodGUID",(t,e)=>{nle.init(t,e),Kt.init(t,e)}),Lh=X("ZodUUID",(t,e)=>{ile.init(t,e),Kt.init(t,e)}),Xde=X("ZodURL",(t,e)=>{ole.init(t,e),Kt.init(t,e)}),Yde=X("ZodEmoji",(t,e)=>{sle.init(t,e),Kt.init(t,e)}),Qde=X("ZodNanoID",(t,e)=>{cle.init(t,e),Kt.init(t,e)}),epe=X("ZodCUID",(t,e)=>{ule.init(t,e),Kt.init(t,e)}),tpe=X("ZodCUID2",(t,e)=>{lle.init(t,e),Kt.init(t,e)}),rpe=X("ZodULID",(t,e)=>{dle.init(t,e),Kt.init(t,e)}),npe=X("ZodXID",(t,e)=>{ple.init(t,e),Kt.init(t,e)}),ipe=X("ZodKSUID",(t,e)=>{fle.init(t,e),Kt.init(t,e)}),ape=X("ZodIPv4",(t,e)=>{yle.init(t,e),Kt.init(t,e)}),ope=X("ZodIPv6",(t,e)=>{_le.init(t,e),Kt.init(t,e)}),spe=X("ZodCIDRv4",(t,e)=>{ble.init(t,e),Kt.init(t,e)}),cpe=X("ZodCIDRv6",(t,e)=>{xle.init(t,e),Kt.init(t,e)}),upe=X("ZodBase64",(t,e)=>{Sle.init(t,e),Kt.init(t,e)}),lpe=X("ZodBase64URL",(t,e)=>{$le.init(t,e),Kt.init(t,e)}),dpe=X("ZodE164",(t,e)=>{Ele.init(t,e),Kt.init(t,e)}),ppe=X("ZodJWT",(t,e)=>{Tle.init(t,e),Kt.init(t,e)}),tU=X("ZodNumber",(t,e)=>{L6.init(t,e),Wt.init(t,e),t.gt=(n,i)=>t.check(O2(n,i)),t.gte=(n,i)=>t.check(b$(n,i)),t.min=(n,i)=>t.check(b$(n,i)),t.lt=(n,i)=>t.check(P2(n,i)),t.lte=(n,i)=>t.check(_$(n,i)),t.max=(n,i)=>t.check(_$(n,i)),t.int=n=>t.check(N2(n)),t.safe=n=>t.check(N2(n)),t.positive=n=>t.check(O2(0,n)),t.nonnegative=n=>t.check(b$(0,n)),t.negative=n=>t.check(P2(0,n)),t.nonpositive=n=>t.check(_$(0,n)),t.multipleOf=(n,i)=>t.check(R2(n,i)),t.step=(n,i)=>t.check(R2(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 Nt(t){return kde(tU,t)}var fpe=X("ZodNumberFormat",(t,e)=>{Ile.init(t,e),tU.init(t,e)});function N2(t){return Tde(fpe,t)}var mpe=X("ZodBoolean",(t,e)=>{Ple.init(t,e),Wt.init(t,e)});function $r(t){return Ide(mpe,t)}var hpe=X("ZodNull",(t,e)=>{Ole.init(t,e),Wt.init(t,e)});function rU(t){return Pde(hpe,t)}var gpe=X("ZodUnknown",(t,e)=>{Rle.init(t,e),Wt.init(t,e)});function ir(){return Ode(gpe)}var vpe=X("ZodNever",(t,e)=>{Cle.init(t,e),Wt.init(t,e)});function ype(t){return Rde(vpe,t)}var _pe=X("ZodArray",(t,e)=>{Nle.init(t,e),Wt.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Kh(r,n)),t.nonempty=r=>t.check(Kh(1,r)),t.max=(r,n)=>t.check(F6(r,n)),t.length=(r,n)=>t.check(Z6(r,n)),t.unwrap=()=>t.element});function at(t,e){return Fde(_pe,t,e)}var nU=X("ZodObject",(t,e)=>{jle.init(t,e),Wt.init(t,e),zt.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Er(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:ir()}),t.loose=()=>t.clone({...t._zod.def,catchall:ir()}),t.strict=()=>t.clone({...t._zod.def,catchall:ype()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>zt.extend(t,r),t.merge=r=>zt.merge(t,r),t.pick=r=>zt.pick(t,r),t.omit=r=>zt.omit(t,r),t.partial=(...r)=>zt.partial(sU,t,r[0]),t.required=(...r)=>zt.required(cU,t,r[0])});function re(t,e){let r={type:"object",get shape(){return zt.assignProp(this,"shape",{...t}),this.shape},...zt.normalizeParams(e)};return new nU(r)}function ei(t,e){return new nU({type:"object",get shape(){return zt.assignProp(this,"shape",{...t}),this.shape},catchall:ir(),...zt.normalizeParams(e)})}var iU=X("ZodUnion",(t,e)=>{q6.init(t,e),Wt.init(t,e),t.options=e.options});function Zt(t,e){return new iU({type:"union",options:t,...zt.normalizeParams(e)})}var bpe=X("ZodDiscriminatedUnion",(t,e)=>{iU.init(t,e),Ale.init(t,e)});function aU(t,e,r){return new bpe({type:"union",options:e,discriminator:t,...zt.normalizeParams(r)})}var xpe=X("ZodIntersection",(t,e)=>{Mle.init(t,e),Wt.init(t,e)});function eE(t,e){return new xpe({type:"intersection",left:t,right:e})}var Spe=X("ZodRecord",(t,e)=>{Dle.init(t,e),Wt.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function ar(t,e,r){return new Spe({type:"record",keyType:t,valueType:e,...zt.normalizeParams(r)})}var L$=X("ZodEnum",(t,e)=>{zle.init(t,e),Wt.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 a={};for(let o of n)if(r.has(o))a[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new L$({...e,checks:[],...zt.normalizeParams(i),entries:a})},t.exclude=(n,i)=>{let a={...e.entries};for(let o of n)if(r.has(o))delete a[o];else throw new Error(`Key ${o} not found in enum`);return new L$({...e,checks:[],...zt.normalizeParams(i),entries:a})}});function Er(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new L$({type:"enum",entries:r,...zt.normalizeParams(e)})}var wpe=X("ZodLiteral",(t,e)=>{Ule.init(t,e),Wt.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 be(t,e){return new wpe({type:"literal",values:Array.isArray(t)?t:[t],...zt.normalizeParams(e)})}var $pe=X("ZodTransform",(t,e)=>{Lle.init(t,e),Wt.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=a=>{if(typeof a=="string")r.issues.push(zt.issue(a,r.value,e));else{let o=a;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(zt.issue(o))}};let i=e.transform(r.value,r);return i instanceof Promise?i.then(a=>(r.value=a,r)):(r.value=i,r)}});function oU(t){return new $pe({type:"transform",transform:t})}var sU=X("ZodOptional",(t,e)=>{qle.init(t,e),Wt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function _e(t){return new sU({type:"optional",innerType:t})}var Epe=X("ZodNullable",(t,e)=>{Fle.init(t,e),Wt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function j2(t){return new Epe({type:"nullable",innerType:t})}var kpe=X("ZodDefault",(t,e)=>{Zle.init(t,e),Wt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Tpe(t,e){return new kpe({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var Ipe=X("ZodPrefault",(t,e)=>{Hle.init(t,e),Wt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ppe(t,e){return new Ipe({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var cU=X("ZodNonOptional",(t,e)=>{Ble.init(t,e),Wt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ope(t,e){return new cU({type:"nonoptional",innerType:t,...zt.normalizeParams(e)})}var Rpe=X("ZodCatch",(t,e)=>{Vle.init(t,e),Wt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Cpe(t,e){return new Rpe({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Npe=X("ZodPipe",(t,e)=>{Gle.init(t,e),Wt.init(t,e),t.in=e.in,t.out=e.out});function q$(t,e){return new Npe({type:"pipe",in:t,out:e})}var jpe=X("ZodReadonly",(t,e)=>{Wle.init(t,e),Wt.init(t,e)});function Ape(t){return new jpe({type:"readonly",innerType:t})}var uU=X("ZodCustom",(t,e)=>{Kle.init(t,e),Wt.init(t,e)});function Mpe(t,e){let r=new Xr({check:"custom",...zt.normalizeParams(e)});return r._zod.check=t,r}function Dpe(t,e){return Zde(uU,t??(()=>!0),e)}function zpe(t,e={}){return Hde(uU,t,e)}function Upe(t,e){let r=Mpe(n=>(n.addIssue=i=>{if(typeof i=="string")n.issues.push(zt.issue(i,n.value,r._zod.def));else{let a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=r),a.continue??(a.continue=!r._zod.def.abort),n.issues.push(zt.issue(a))}},t(n.value,n)),e);return r}function lU(t,e){return q$(oU(t),e)}Gi(Yle());var tE="io.modelcontextprotocol/related-task",mg="2.0",xi=Dpe(t=>t!==null&&(typeof t=="object"||typeof t=="function")),dU=Zt([G(),Nt().int()]),pU=G(),Lpe=ei({ttl:Zt([Nt(),rU()]).optional(),pollInterval:Nt().optional()}),rE=ei({taskId:G()}),qpe=ei({progressToken:dU.optional(),[tE]:rE.optional()}),Yr=ei({task:Lpe.optional(),_meta:qpe.optional()}),mr=re({method:G(),params:Yr.optional()}),Io=ei({_meta:re({[tE]:_e(rE)}).passthrough().optional()}),Nn=re({method:G(),params:Io.optional()}),kr=ei({_meta:ei({[tE]:rE.optional()}).optional()}),hg=Zt([G(),Nt().int()]),Fpe=re({jsonrpc:be(mg),id:hg,...mr.shape}).strict();var Zpe=re({jsonrpc:be(mg),...Nn.shape}).strict();var Hpe=re({jsonrpc:be(mg),id:hg,result:kr}).strict();var A2;(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"})(A2||(A2={}));var Bpe=re({jsonrpc:be(mg),id:hg,error:re({code:Nt().int(),message:G(),data:_e(ir())})}).strict();var CPe=Zt([Fpe,Zpe,Hpe,Bpe]),fU=kr.strict(),Vpe=Io.extend({requestId:hg,reason:G().optional()}),mU=Nn.extend({method:be("notifications/cancelled"),params:Vpe}),Gpe=re({src:G(),mimeType:G().optional(),sizes:at(G()).optional()}),jd=re({icons:at(Gpe).optional()}),$c=re({name:G(),title:G().optional()}),hU=$c.extend({...$c.shape,...jd.shape,version:G(),websiteUrl:G().optional()}),Wpe=eE(re({applyDefaults:$r().optional()}),ar(G(),ir())),Kpe=lU(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,eE(re({form:Wpe.optional(),url:xi.optional()}),ar(G(),ir()).optional())),Jpe=re({list:_e(re({}).passthrough()),cancel:_e(re({}).passthrough()),requests:_e(re({sampling:_e(re({createMessage:_e(re({}).passthrough())}).passthrough()),elicitation:_e(re({create:_e(re({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),Xpe=re({list:_e(re({}).passthrough()),cancel:_e(re({}).passthrough()),requests:_e(re({tools:_e(re({call:_e(re({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),Ype=re({experimental:ar(G(),xi).optional(),sampling:re({context:xi.optional(),tools:xi.optional()}).optional(),elicitation:Kpe.optional(),roots:re({listChanged:$r().optional()}).optional(),tasks:_e(Jpe)}),Qpe=Yr.extend({protocolVersion:G(),capabilities:Ype,clientInfo:hU}),efe=mr.extend({method:be("initialize"),params:Qpe}),tfe=re({experimental:ar(G(),xi).optional(),logging:xi.optional(),completions:xi.optional(),prompts:_e(re({listChanged:_e($r())})),resources:re({subscribe:$r().optional(),listChanged:$r().optional()}).optional(),tools:re({listChanged:$r().optional()}).optional(),tasks:_e(Xpe)}).passthrough(),rfe=kr.extend({protocolVersion:G(),capabilities:tfe,serverInfo:hU,instructions:G().optional()}),nfe=Nn.extend({method:be("notifications/initialized")}),gU=mr.extend({method:be("ping")}),ife=re({progress:Nt(),total:_e(Nt()),message:_e(G())}),afe=re({...Io.shape,...ife.shape,progressToken:dU}),vU=Nn.extend({method:be("notifications/progress"),params:afe}),ofe=Yr.extend({cursor:pU.optional()}),Ad=mr.extend({params:ofe.optional()}),Md=kr.extend({nextCursor:_e(pU)}),Dd=re({taskId:G(),status:Er(["working","input_required","completed","failed","cancelled"]),ttl:Zt([Nt(),rU()]),createdAt:G(),lastUpdatedAt:G(),pollInterval:_e(Nt()),statusMessage:_e(G())}),yU=kr.extend({task:Dd}),sfe=Io.merge(Dd),_U=Nn.extend({method:be("notifications/tasks/status"),params:sfe}),bU=mr.extend({method:be("tasks/get"),params:Yr.extend({taskId:G()})}),xU=kr.merge(Dd),SU=mr.extend({method:be("tasks/result"),params:Yr.extend({taskId:G()})}),wU=Ad.extend({method:be("tasks/list")}),$U=Md.extend({tasks:at(Dd)}),NPe=mr.extend({method:be("tasks/cancel"),params:Yr.extend({taskId:G()})}),jPe=kr.merge(Dd),EU=re({uri:G(),mimeType:_e(G()),_meta:ar(G(),ir()).optional()}),kU=EU.extend({text:G()}),nE=G().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),TU=EU.extend({blob:nE}),Oc=re({audience:at(Er(["user","assistant"])).optional(),priority:Nt().min(0).max(1).optional(),lastModified:H6.datetime({offset:!0}).optional()}),IU=re({...$c.shape,...jd.shape,uri:G(),description:_e(G()),mimeType:_e(G()),annotations:Oc.optional(),_meta:_e(ei({}))}),cfe=re({...$c.shape,...jd.shape,uriTemplate:G(),description:_e(G()),mimeType:_e(G()),annotations:Oc.optional(),_meta:_e(ei({}))}),ufe=Ad.extend({method:be("resources/list")}),lfe=Md.extend({resources:at(IU)}),dfe=Ad.extend({method:be("resources/templates/list")}),pfe=Md.extend({resourceTemplates:at(cfe)}),iE=Yr.extend({uri:G()}),ffe=iE,mfe=mr.extend({method:be("resources/read"),params:ffe}),hfe=kr.extend({contents:at(Zt([kU,TU]))}),gfe=Nn.extend({method:be("notifications/resources/list_changed")}),vfe=iE,yfe=mr.extend({method:be("resources/subscribe"),params:vfe}),_fe=iE,bfe=mr.extend({method:be("resources/unsubscribe"),params:_fe}),xfe=Io.extend({uri:G()}),Sfe=Nn.extend({method:be("notifications/resources/updated"),params:xfe}),wfe=re({name:G(),description:_e(G()),required:_e($r())}),$fe=re({...$c.shape,...jd.shape,description:_e(G()),arguments:_e(at(wfe)),_meta:_e(ei({}))}),Efe=Ad.extend({method:be("prompts/list")}),kfe=Md.extend({prompts:at($fe)}),Tfe=Yr.extend({name:G(),arguments:ar(G(),G()).optional()}),Ife=mr.extend({method:be("prompts/get"),params:Tfe}),aE=re({type:be("text"),text:G(),annotations:Oc.optional(),_meta:ar(G(),ir()).optional()}),oE=re({type:be("image"),data:nE,mimeType:G(),annotations:Oc.optional(),_meta:ar(G(),ir()).optional()}),sE=re({type:be("audio"),data:nE,mimeType:G(),annotations:Oc.optional(),_meta:ar(G(),ir()).optional()}),Pfe=re({type:be("tool_use"),name:G(),id:G(),input:re({}).passthrough(),_meta:_e(re({}).passthrough())}).passthrough(),Ofe=re({type:be("resource"),resource:Zt([kU,TU]),annotations:Oc.optional(),_meta:ar(G(),ir()).optional()}),Rfe=IU.extend({type:be("resource_link")}),cE=Zt([aE,oE,sE,Rfe,Ofe]),Cfe=re({role:Er(["user","assistant"]),content:cE}),Nfe=kr.extend({description:_e(G()),messages:at(Cfe)}),jfe=Nn.extend({method:be("notifications/prompts/list_changed")}),Afe=re({title:G().optional(),readOnlyHint:$r().optional(),destructiveHint:$r().optional(),idempotentHint:$r().optional(),openWorldHint:$r().optional()}),Mfe=re({taskSupport:Er(["required","optional","forbidden"]).optional()}),PU=re({...$c.shape,...jd.shape,description:G().optional(),inputSchema:re({type:be("object"),properties:ar(G(),xi).optional(),required:at(G()).optional()}).catchall(ir()),outputSchema:re({type:be("object"),properties:ar(G(),xi).optional(),required:at(G()).optional()}).catchall(ir()).optional(),annotations:_e(Afe),execution:_e(Mfe),_meta:ar(G(),ir()).optional()}),Dfe=Ad.extend({method:be("tools/list")}),zfe=Md.extend({tools:at(PU)}),OU=kr.extend({content:at(cE).default([]),structuredContent:ar(G(),ir()).optional(),isError:_e($r())}),APe=OU.or(kr.extend({toolResult:ir()})),Ufe=Yr.extend({name:G(),arguments:_e(ar(G(),ir()))}),Lfe=mr.extend({method:be("tools/call"),params:Ufe}),qfe=Nn.extend({method:be("notifications/tools/list_changed")}),RU=Er(["debug","info","notice","warning","error","critical","alert","emergency"]),Ffe=Yr.extend({level:RU}),Zfe=mr.extend({method:be("logging/setLevel"),params:Ffe}),Hfe=Io.extend({level:RU,logger:G().optional(),data:ir()}),Bfe=Nn.extend({method:be("notifications/message"),params:Hfe}),Vfe=re({name:G().optional()}),Gfe=re({hints:_e(at(Vfe)),costPriority:_e(Nt().min(0).max(1)),speedPriority:_e(Nt().min(0).max(1)),intelligencePriority:_e(Nt().min(0).max(1))}),Wfe=re({mode:_e(Er(["auto","required","none"]))}),Kfe=re({type:be("tool_result"),toolUseId:G().describe("The unique identifier for the corresponding tool call."),content:at(cE).default([]),structuredContent:re({}).passthrough().optional(),isError:_e($r()),_meta:_e(re({}).passthrough())}).passthrough(),Jfe=aU("type",[aE,oE,sE]),Jh=aU("type",[aE,oE,sE,Pfe,Kfe]),Xfe=re({role:Er(["user","assistant"]),content:Zt([Jh,at(Jh)]),_meta:_e(re({}).passthrough())}).passthrough(),Yfe=Yr.extend({messages:at(Xfe),modelPreferences:Gfe.optional(),systemPrompt:G().optional(),includeContext:Er(["none","thisServer","allServers"]).optional(),temperature:Nt().optional(),maxTokens:Nt().int(),stopSequences:at(G()).optional(),metadata:xi.optional(),tools:_e(at(PU)),toolChoice:_e(Wfe)}),Qfe=mr.extend({method:be("sampling/createMessage"),params:Yfe}),eme=kr.extend({model:G(),stopReason:_e(Er(["endTurn","stopSequence","maxTokens"]).or(G())),role:Er(["user","assistant"]),content:Jfe}),tme=kr.extend({model:G(),stopReason:_e(Er(["endTurn","stopSequence","maxTokens","toolUse"]).or(G())),role:Er(["user","assistant"]),content:Zt([Jh,at(Jh)])}),rme=re({type:be("boolean"),title:G().optional(),description:G().optional(),default:$r().optional()}),nme=re({type:be("string"),title:G().optional(),description:G().optional(),minLength:Nt().optional(),maxLength:Nt().optional(),format:Er(["email","uri","date","date-time"]).optional(),default:G().optional()}),ime=re({type:Er(["number","integer"]),title:G().optional(),description:G().optional(),minimum:Nt().optional(),maximum:Nt().optional(),default:Nt().optional()}),ame=re({type:be("string"),title:G().optional(),description:G().optional(),enum:at(G()),default:G().optional()}),ome=re({type:be("string"),title:G().optional(),description:G().optional(),oneOf:at(re({const:G(),title:G()})),default:G().optional()}),sme=re({type:be("string"),title:G().optional(),description:G().optional(),enum:at(G()),enumNames:at(G()).optional(),default:G().optional()}),cme=Zt([ame,ome]),ume=re({type:be("array"),title:G().optional(),description:G().optional(),minItems:Nt().optional(),maxItems:Nt().optional(),items:re({type:be("string"),enum:at(G())}),default:at(G()).optional()}),lme=re({type:be("array"),title:G().optional(),description:G().optional(),minItems:Nt().optional(),maxItems:Nt().optional(),items:re({anyOf:at(re({const:G(),title:G()}))}),default:at(G()).optional()}),dme=Zt([ume,lme]),pme=Zt([sme,cme,dme]),fme=Zt([pme,rme,nme,ime]),mme=Yr.extend({mode:be("form").optional(),message:G(),requestedSchema:re({type:be("object"),properties:ar(G(),fme),required:at(G()).optional()})}),hme=Yr.extend({mode:be("url"),message:G(),elicitationId:G(),url:G().url()}),gme=Zt([mme,hme]),vme=mr.extend({method:be("elicitation/create"),params:gme}),yme=Io.extend({elicitationId:G()}),_me=Nn.extend({method:be("notifications/elicitation/complete"),params:yme}),bme=kr.extend({action:Er(["accept","decline","cancel"]),content:lU(t=>t===null?void 0:t,ar(G(),Zt([G(),Nt(),$r(),at(G())])).optional())}),xme=re({type:be("ref/resource"),uri:G()}),Sme=re({type:be("ref/prompt"),name:G()}),wme=Yr.extend({ref:Zt([Sme,xme]),argument:re({name:G(),value:G()}),context:re({arguments:ar(G(),G()).optional()}).optional()}),$me=mr.extend({method:be("completion/complete"),params:wme});var Eme=kr.extend({completion:ei({values:at(G()).max(100),total:_e(Nt().int()),hasMore:_e($r())})}),kme=re({uri:G().startsWith("file://"),name:G().optional(),_meta:ar(G(),ir()).optional()}),Tme=mr.extend({method:be("roots/list")}),Ime=kr.extend({roots:at(kme)}),Pme=Nn.extend({method:be("notifications/roots/list_changed")}),MPe=Zt([gU,efe,$me,Zfe,Ife,Efe,ufe,dfe,mfe,yfe,bfe,Lfe,Dfe,bU,SU,wU]),DPe=Zt([mU,vU,nfe,Pme,_U]),zPe=Zt([fU,eme,tme,bme,Ime,xU,$U,yU]),UPe=Zt([gU,Qfe,vme,Tme,bU,SU,wU]),LPe=Zt([mU,vU,Bfe,Sfe,gfe,qfe,jfe,_U,_me]),qPe=Zt([fU,rfe,Eme,Nfe,kfe,lfe,pfe,hfe,OU,zfe,xU,$U,yU]);var FPe=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var ZPe=D2(hae(),1),HPe=D2(uoe(),1);var M2;(function(t){t.Completable="McpCompletable"})(M2||(M2={}));function CU({prompt:t,options:e}){let{systemPrompt:r,settingSources:n,sandbox:i,...a}=e??{},o,s;r===void 0?o="":typeof r=="string"?o=r:r.type==="preset"&&(s=r.append);let c=a.pathToClaudeCodeExecutable;if(!c){let Z=(0,J2.fileURLToPath)(Ome.url),J=(0,S$.join)(Z,"..");c=(0,S$.join)(J,"cli.js")}process.env.CLAUDE_AGENT_SDK_VERSION="0.1.76";let{abortController:u=Y2(),additionalDirectories:l=[],agents:d,allowedTools:p=[],betas:f,canUseTool:g,continue:_,cwd:h,disallowedTools:m=[],tools:y,env:v,executable:b=m6()?"bun":"node",executableArgs:S=[],extraArgs:x={},fallbackModel:w,enableFileCheckpointing:k,forkSession:O,hooks:A,includePartialMessages:M,persistSession:L,maxThinkingTokens:B,maxTurns:U,maxBudgetUsd:Y,mcpServers:me,model:et,outputFormat:ht,permissionMode:fe="default",allowDangerouslySkipPermissions:F=!1,permissionPromptToolName:I,plugins:D,resume:C,resumeSessionAt:$,stderr:T,strictMcpConfig:N}=a,W=ht?.type==="json_schema"?ht.schema:void 0,K=v;if(K||(K={...process.env}),K.CLAUDE_CODE_ENTRYPOINT||(K.CLAUDE_CODE_ENTRYPOINT="sdk-ts"),k&&(K.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true"),!c)throw new Error("pathToClaudeCodeExecutable is required");let pe={},ce=new Map;if(me)for(let[Z,J]of Object.entries(me))J.type==="sdk"&&"instance"in J?(ce.set(Z,J.instance),pe[Z]={type:"sdk",name:Z}):pe[Z]=J;let je=typeof t=="string",P=new $$({abortController:u,additionalDirectories:l,betas:f,cwd:h,executable:b,executableArgs:S,extraArgs:x,pathToClaudeCodeExecutable:c,env:K,forkSession:O,stderr:T,maxThinkingTokens:B,maxTurns:U,maxBudgetUsd:Y,model:et,fallbackModel:w,jsonSchema:W,permissionMode:fe,allowDangerouslySkipPermissions:F,permissionPromptToolName:I,continueConversation:_,resume:C,resumeSessionAt:$,settingSources:n??[],allowedTools:p,disallowedTools:m,tools:y,mcpServers:pe,strictMcpConfig:N,canUseTool:!!g,hooks:!!A,includePartialMessages:M,persistSession:L,plugins:D,sandbox:i,spawnClaudeCodeProcess:a.spawnClaudeCodeProcess}),R={systemPrompt:o,appendSystemPrompt:s,agents:d},z=new T$(P,je,g,A,u,ce,W,R);return typeof t=="string"?P.write(JSON.stringify({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:t}]},parent_tool_use_id:null})+` +`):z.streamInput(t),z}var gg=class{dbManager;sessionManager;constructor(e,r){this.dbManager=e,this.sessionManager=r}async startSession(e,r){let n={lastCwd:void 0},i=this.findClaudeExecutable(),a=this.getModelId(),o=["Bash","Read","Write","Edit","Grep","Glob","WebFetch","WebSearch","Task","NotebookEdit","AskUserQuestion","TodoWrite"],s=this.createMessageGenerator(e,n),c=!!e.memorySessionId;if(E.info("SDK","Starting SDK query",{sessionDbId:e.sessionDbId,contentSessionId:e.contentSessionId,memorySessionId:e.memorySessionId,hasRealMemorySessionId:c,resume_parameter:c?e.memorySessionId:"(none - fresh start)",lastPromptNumber:e.lastPromptNumber}),e.lastPromptNumber>1){let d=c;E.debug("SDK",`[ALIGNMENT] Resume Decision | contentSessionId=${e.contentSessionId} | memorySessionId=${e.memorySessionId} | prompt#=${e.lastPromptNumber} | hasRealMemorySessionId=${c} | willResume=${d} | resumeWith=${d?e.memorySessionId:"NONE"}`)}else{let d=c;E.debug("SDK",`[ALIGNMENT] First Prompt (INIT) | contentSessionId=${e.contentSessionId} | prompt#=${e.lastPromptNumber} | hasStaleMemoryId=${d} | action=START_FRESH | Will capture new memorySessionId from SDK response`),d&&E.warn("SDK",`Skipping resume for INIT prompt despite existing memorySessionId=${e.memorySessionId} - SDK context was lost (worker restart or crash recovery)`)}Sr(xh);let u=CU({prompt:s,options:{model:a,cwd:xh,...c&&e.lastPromptNumber>1&&{resume:e.memorySessionId},disallowedTools:o,abortController:e.abortController,pathToClaudeCodeExecutable:i,spawnClaudeCodeProcess:J4(e.sessionDbId)}});for await(let d of u){if(!e.memorySessionId&&d.session_id){e.memorySessionId=d.session_id,this.dbManager.getSessionStore().updateMemorySessionId(e.sessionDbId,d.session_id);let p=this.dbManager.getSessionStore().getSessionById(e.sessionDbId),f=p?.memory_session_id===d.session_id;E.info("SESSION",`MEMORY_ID_CAPTURED | sessionDbId=${e.sessionDbId} | memorySessionId=${d.session_id} | dbVerified=${f}`,{sessionId:e.sessionDbId,memorySessionId:d.session_id}),f||E.error("SESSION",`MEMORY_ID_MISMATCH | sessionDbId=${e.sessionDbId} | expected=${d.session_id} | got=${p?.memory_session_id}`,{sessionId:e.sessionDbId}),E.debug("SDK",`[ALIGNMENT] Captured | contentSessionId=${e.contentSessionId} \u2192 memorySessionId=${d.session_id} | Future prompts will resume with this ID`)}if(d.type==="assistant"){let p=d.message.content,f=Array.isArray(p)?p.filter(v=>v.type==="text").map(v=>v.text).join(` `):typeof p=="string"?p:"",g=f.length,_=e.cumulativeInputTokens+e.cumulativeOutputTokens,h=d.message.usage;h&&(e.cumulativeInputTokens+=h.input_tokens||0,e.cumulativeOutputTokens+=h.output_tokens||0,h.cache_creation_input_tokens&&(e.cumulativeInputTokens+=h.cache_creation_input_tokens),E.debug("SDK","Token usage captured",{sessionId:e.sessionDbId,inputTokens:h.input_tokens,outputTokens:h.output_tokens,cacheCreation:h.cache_creation_input_tokens||0,cacheRead:h.cache_read_input_tokens||0,cumulativeInput:e.cumulativeInputTokens,cumulativeOutput:e.cumulativeOutputTokens}));let m=e.cumulativeInputTokens+e.cumulativeOutputTokens-_,y=e.earliestPendingTimestamp;if(g>0){let v=g>100?f.substring(0,100)+"...":f;E.dataOut("SDK",`Response received (${g} chars)`,{sessionId:e.sessionDbId,promptNumber:e.lastPromptNumber},v)}await Xn(f,e,this.dbManager,this.sessionManager,r,m,y,"SDK",n.lastCwd)}d.type==="result"&&d.subtype}let l=Date.now()-e.startTime;E.success("SDK","Agent completed",{sessionId:e.sessionDbId,duration:`${(l/1e3).toFixed(1)}s`})}async*createMessageGenerator(e,r){let n=Be.getInstance().getActiveMode(),i=e.lastPromptNumber===1;E.info("SDK","Creating message generator",{sessionDbId:e.sessionDbId,contentSessionId:e.contentSessionId,lastPromptNumber:e.lastPromptNumber,isInitPrompt:i,promptType:i?"INIT":"CONTINUATION"});let a=i?rc(e.project,e.contentSessionId,e.userPrompt,n):ac(e.userPrompt,e.lastPromptNumber,e.contentSessionId,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};for await(let o of this.sessionManager.getMessageIterator(e.sessionDbId))if(o.cwd&&(r.lastCwd=o.cwd),o.type==="observation"){o.prompt_number!==void 0&&(e.lastPromptNumber=o.prompt_number);let s=nc({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:s}),yield{type:"user",message:{role:"user",content:s},session_id:e.contentSessionId,parent_tool_use_id:null,isSynthetic:!0}}else if(o.type==="summarize"){let s=ic({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:s}),yield{type:"user",message:{role:"user",content:s},session_id:e.contentSessionId,parent_tool_use_id:null,isSynthetic:!0}}}findClaudeExecutable(){let e=Qe.loadFromFile(Tn);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}try{let r=(0,NU.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){E.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=AU.default.join((0,jU.homedir)(),".claude-mem","settings.json");return Qe.loadFromFile(e).CLAUDE_MEM_MODEL}};var yg=ut(require("path"),1),_g=require("os");we();un();Mr();var Rme="https://generativelanguage.googleapis.com/v1beta/models",Cme={"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":5},MU=0;async function Nme(t,e){if(!e)return;let r=Cme[t]||5,n=Math.ceil(6e4/r)+100,a=Date.now()-MU;if(asetTimeout(s,o))}MU=Date.now()}var vg=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:a}=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.");let o=Be.getInstance().getActiveMode(),s=e.lastPromptNumber===1?rc(e.project,e.contentSessionId,e.userPrompt,o):ac(e.userPrompt,e.lastPromptNumber,e.contentSessionId,o);e.conversationHistory.push({role:"user",content:s});let c=await this.queryGeminiMultiTurn(e.conversationHistory,n,i,a);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 Xn(c.content,e,this.dbManager,this.sessionManager,r,d,null,"Gemini")}else E.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)){d.cwd&&(u=d.cwd);let p=e.earliestPendingTimestamp;if(d.type==="observation"){d.prompt_number!==void 0&&(e.lastPromptNumber=d.prompt_number);let f=nc({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 g=await this.queryGeminiMultiTurn(e.conversationHistory,n,i,a),_=0;g.content&&(e.conversationHistory.push({role:"assistant",content:g.content}),_=g.tokensUsed||0,e.cumulativeInputTokens+=Math.floor(_*.7),e.cumulativeOutputTokens+=Math.floor(_*.3)),await Xn(g.content||"",e,this.dbManager,this.sessionManager,r,_,p,"Gemini",u)}else if(d.type==="summarize"){let f=ic({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 g=await this.queryGeminiMultiTurn(e.conversationHistory,n,i,a),_=0;g.content&&(e.conversationHistory.push({role:"assistant",content:g.content}),_=g.tokensUsed||0,e.cumulativeInputTokens+=Math.floor(_*.7),e.cumulativeOutputTokens+=Math.floor(_*.3)),await Xn(g.content||"",e,this.dbManager,this.sessionManager,r,_,p,"Gemini",u)}}let l=Date.now()-e.startTime;E.success("SDK","Gemini agent completed",{sessionId:e.sessionDbId,duration:`${(l/1e3).toFixed(1)}s`,historyLength:e.conversationHistory.length})}catch(n){if(md(n))throw E.warn("SDK","Gemini agent aborted",{sessionId:e.sessionDbId}),n;if(fd(n)&&this.fallbackAgent)return E.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 E.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 a=this.conversationToGeminiContents(e),o=e.reduce((p,f)=>p+f.content.length,0);E.debug("SDK",`Querying Gemini multi-turn (${n})`,{turns:e.length,totalChars:o});let s=`${Rme}/${n}:generateContent?key=${r}`;await Nme(n,i);let c=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contents:a,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 E.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=yg.default.join((0,_g.homedir)(),".claude-mem","settings.json"),r=Qe.loadFromFile(e),n=r.CLAUDE_MEM_GEMINI_API_KEY||process.env.GEMINI_API_KEY||"",i="gemini-2.5-flash",a=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"],s;o.includes(a)?s=a:(E.warn("SDK",`Invalid Gemini model "${a}", falling back to ${i}`,{configured:a,validModels:o}),s=i);let c=r.CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED!=="false";return{apiKey:n,model:s,rateLimitingEnabled:c}}};function uE(){let t=yg.default.join((0,_g.homedir)(),".claude-mem","settings.json");return!!(Qe.loadFromFile(t).CLAUDE_MEM_GEMINI_API_KEY||process.env.GEMINI_API_KEY)}function lE(){let t=yg.default.join((0,_g.homedir)(),".claude-mem","settings.json");return Qe.loadFromFile(t).CLAUDE_MEM_PROVIDER==="gemini"}we();un();Jr();Mr();var jme="https://openrouter.ai/api/v1/chat/completions",Ame=20,Mme=1e5,Dme=4,bg=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:a,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.");let s=Be.getInstance().getActiveMode(),c=e.lastPromptNumber===1?rc(e.project,e.contentSessionId,e.userPrompt,s):ac(e.userPrompt,e.lastPromptNumber,e.contentSessionId,s);e.conversationHistory.push({role:"user",content:c});let u=await this.queryOpenRouterMultiTurn(e.conversationHistory,n,i,a,o);if(u.content){e.conversationHistory.push({role:"assistant",content:u.content});let p=u.tokensUsed||0;e.cumulativeInputTokens+=Math.floor(p*.7),e.cumulativeOutputTokens+=Math.floor(p*.3),await Xn(u.content,e,this.dbManager,this.sessionManager,r,p,null,"OpenRouter",void 0)}else E.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)){p.cwd&&(l=p.cwd);let f=e.earliestPendingTimestamp;if(p.type==="observation"){p.prompt_number!==void 0&&(e.lastPromptNumber=p.prompt_number);let g=nc({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:g});let _=await this.queryOpenRouterMultiTurn(e.conversationHistory,n,i,a,o),h=0;_.content&&(e.conversationHistory.push({role:"assistant",content:_.content}),h=_.tokensUsed||0,e.cumulativeInputTokens+=Math.floor(h*.7),e.cumulativeOutputTokens+=Math.floor(h*.3)),await Xn(_.content||"",e,this.dbManager,this.sessionManager,r,h,f,"OpenRouter",l)}else if(p.type==="summarize"){let g=ic({id:e.sessionDbId,memory_session_id:e.memorySessionId,project:e.project,user_prompt:e.userPrompt,last_assistant_message:p.last_assistant_message||""},s);e.conversationHistory.push({role:"user",content:g});let _=await this.queryOpenRouterMultiTurn(e.conversationHistory,n,i,a,o),h=0;_.content&&(e.conversationHistory.push({role:"assistant",content:_.content}),h=_.tokensUsed||0,e.cumulativeInputTokens+=Math.floor(h*.7),e.cumulativeOutputTokens+=Math.floor(h*.3)),await Xn(_.content||"",e,this.dbManager,this.sessionManager,r,h,f,"OpenRouter",l)}}let d=Date.now()-e.startTime;E.success("SDK","OpenRouter agent completed",{sessionId:e.sessionDbId,duration:`${(d/1e3).toFixed(1)}s`,historyLength:e.conversationHistory.length,model:i})}catch(n){if(md(n))throw E.warn("SDK","OpenRouter agent aborted",{sessionId:e.sessionDbId}),n;if(fd(n)&&this.fallbackAgent)return E.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 E.failure("SDK","OpenRouter agent error",{sessionDbId:e.sessionDbId},n),n}}estimateTokens(e){return Math.ceil(e.length/Dme)}truncateHistory(e){let r=Qe.loadFromFile(Tn),n=parseInt(r.CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES)||Ame,i=parseInt(r.CLAUDE_MEM_OPENROUTER_MAX_TOKENS)||Mme;if(e.length<=n&&e.reduce((c,u)=>c+this.estimateTokens(u.content),0)<=i)return e;let a=[],o=0;for(let s=e.length-1;s>=0;s--){let c=e[s],u=this.estimateTokens(c.content);if(a.length>=n||o+u>i){E.warn("SDK","Context window truncated to prevent runaway costs",{originalMessages:e.length,keptMessages:a.length,droppedMessages:s+1,estimatedTokens:o,tokenLimit:i});break}a.unshift(c),o+=u}return a}conversationToOpenAIMessages(e){return e.map(r=>({role:r.role==="assistant"?"assistant":"user",content:r.content}))}async queryOpenRouterMultiTurn(e,r,n,i,a){let o=this.truncateHistory(e),s=this.conversationToOpenAIMessages(o),c=o.reduce((g,_)=>g+_.content.length,0),u=this.estimateTokens(o.map(g=>g.content).join(""));E.debug("SDK",`Querying OpenRouter multi-turn (${n})`,{turns:o.length,totalChars:c,estimatedTokens:u});let l=await fetch(jme,{method:"POST",headers:{Authorization:`Bearer ${r}`,"HTTP-Referer":i||"https://github.com/thedotmack/claude-mem","X-Title":a||"claude-mem","Content-Type":"application/json"},body:JSON.stringify({model:n,messages:s,temperature:.3,max_tokens:4096})});if(!l.ok){let g=await l.text();throw new Error(`OpenRouter API error: ${l.status} - ${g}`)}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 E.error("SDK","Empty response from OpenRouter"),{content:""};let p=d.choices[0].message.content,f=d.usage?.total_tokens;if(f){let g=d.usage?.prompt_tokens||0,_=d.usage?.completion_tokens||0,h=g/1e6*3+_/1e6*15;E.info("SDK","OpenRouter API usage",{model:n,inputTokens:g,outputTokens:_,totalTokens:f,estimatedCostUSD:h.toFixed(4),messagesInContext:o.length}),f>5e4&&E.warn("SDK","High token usage detected - consider reducing context",{totalTokens:f,estimatedCost:h.toFixed(4)})}return{content:p,tokensUsed:f}}getOpenRouterConfig(){let e=Tn,r=Qe.loadFromFile(e),n=r.CLAUDE_MEM_OPENROUTER_API_KEY||process.env.OPENROUTER_API_KEY||"",i=r.CLAUDE_MEM_OPENROUTER_MODEL||"xiaomi/mimo-v2-flash:free",a=r.CLAUDE_MEM_OPENROUTER_SITE_URL||"",o=r.CLAUDE_MEM_OPENROUTER_APP_NAME||"claude-mem";return{apiKey:n,model:i,siteUrl:a,appName:o}}};function dE(){let t=Tn;return!!(Qe.loadFromFile(t).CLAUDE_MEM_OPENROUTER_API_KEY||process.env.OPENROUTER_API_KEY)}function pE(){let t=Tn;return Qe.loadFromFile(t).CLAUDE_MEM_PROVIDER==="openrouter"}we();var xg=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(a=>this.stripProjectPath(a,r));return JSON.stringify(i)}catch(n){return E.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(a=>this.sanitizeObservation(a))}}getSummaries(e,r,n){let i=this.dbManager.getSessionStore().db,a=` +2. Set CLAUDE_CODE_PATH in ~/.claude-mem/settings.json`)}getModelId(){let e=AU.default.join((0,jU.homedir)(),".claude-mem","settings.json");return Qe.loadFromFile(e).CLAUDE_MEM_MODEL}};var yg=ut(require("path"),1),_g=require("os");we();cn();Mr();var Rme="https://generativelanguage.googleapis.com/v1beta/models",Cme={"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":5},MU=0;async function Nme(t,e){if(!e)return;let r=Cme[t]||5,n=Math.ceil(6e4/r)+100,a=Date.now()-MU;if(asetTimeout(s,o))}MU=Date.now()}var vg=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:a}=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.");let o=Be.getInstance().getActiveMode(),s=e.lastPromptNumber===1?rc(e.project,e.contentSessionId,e.userPrompt,o):ac(e.userPrompt,e.lastPromptNumber,e.contentSessionId,o);e.conversationHistory.push({role:"user",content:s});let c=await this.queryGeminiMultiTurn(e.conversationHistory,n,i,a);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 Xn(c.content,e,this.dbManager,this.sessionManager,r,d,null,"Gemini")}else E.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)){d.cwd&&(u=d.cwd);let p=e.earliestPendingTimestamp;if(d.type==="observation"){d.prompt_number!==void 0&&(e.lastPromptNumber=d.prompt_number);let f=nc({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 g=await this.queryGeminiMultiTurn(e.conversationHistory,n,i,a),_=0;g.content&&(e.conversationHistory.push({role:"assistant",content:g.content}),_=g.tokensUsed||0,e.cumulativeInputTokens+=Math.floor(_*.7),e.cumulativeOutputTokens+=Math.floor(_*.3)),await Xn(g.content||"",e,this.dbManager,this.sessionManager,r,_,p,"Gemini",u)}else if(d.type==="summarize"){let f=ic({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 g=await this.queryGeminiMultiTurn(e.conversationHistory,n,i,a),_=0;g.content&&(e.conversationHistory.push({role:"assistant",content:g.content}),_=g.tokensUsed||0,e.cumulativeInputTokens+=Math.floor(_*.7),e.cumulativeOutputTokens+=Math.floor(_*.3)),await Xn(g.content||"",e,this.dbManager,this.sessionManager,r,_,p,"Gemini",u)}}let l=Date.now()-e.startTime;E.success("SDK","Gemini agent completed",{sessionId:e.sessionDbId,duration:`${(l/1e3).toFixed(1)}s`,historyLength:e.conversationHistory.length})}catch(n){if(md(n))throw E.warn("SDK","Gemini agent aborted",{sessionId:e.sessionDbId}),n;if(fd(n)&&this.fallbackAgent)return E.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 E.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 a=this.conversationToGeminiContents(e),o=e.reduce((p,f)=>p+f.content.length,0);E.debug("SDK",`Querying Gemini multi-turn (${n})`,{turns:e.length,totalChars:o});let s=`${Rme}/${n}:generateContent?key=${r}`;await Nme(n,i);let c=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contents:a,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 E.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=yg.default.join((0,_g.homedir)(),".claude-mem","settings.json"),r=Qe.loadFromFile(e),n=r.CLAUDE_MEM_GEMINI_API_KEY||process.env.GEMINI_API_KEY||"",i="gemini-2.5-flash",a=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"],s;o.includes(a)?s=a:(E.warn("SDK",`Invalid Gemini model "${a}", falling back to ${i}`,{configured:a,validModels:o}),s=i);let c=r.CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED!=="false";return{apiKey:n,model:s,rateLimitingEnabled:c}}};function uE(){let t=yg.default.join((0,_g.homedir)(),".claude-mem","settings.json");return!!(Qe.loadFromFile(t).CLAUDE_MEM_GEMINI_API_KEY||process.env.GEMINI_API_KEY)}function lE(){let t=yg.default.join((0,_g.homedir)(),".claude-mem","settings.json");return Qe.loadFromFile(t).CLAUDE_MEM_PROVIDER==="gemini"}we();cn();ln();Mr();var jme="https://openrouter.ai/api/v1/chat/completions",Ame=20,Mme=1e5,Dme=4,bg=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:a,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.");let s=Be.getInstance().getActiveMode(),c=e.lastPromptNumber===1?rc(e.project,e.contentSessionId,e.userPrompt,s):ac(e.userPrompt,e.lastPromptNumber,e.contentSessionId,s);e.conversationHistory.push({role:"user",content:c});let u=await this.queryOpenRouterMultiTurn(e.conversationHistory,n,i,a,o);if(u.content){e.conversationHistory.push({role:"assistant",content:u.content});let p=u.tokensUsed||0;e.cumulativeInputTokens+=Math.floor(p*.7),e.cumulativeOutputTokens+=Math.floor(p*.3),await Xn(u.content,e,this.dbManager,this.sessionManager,r,p,null,"OpenRouter",void 0)}else E.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)){p.cwd&&(l=p.cwd);let f=e.earliestPendingTimestamp;if(p.type==="observation"){p.prompt_number!==void 0&&(e.lastPromptNumber=p.prompt_number);let g=nc({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:g});let _=await this.queryOpenRouterMultiTurn(e.conversationHistory,n,i,a,o),h=0;_.content&&(e.conversationHistory.push({role:"assistant",content:_.content}),h=_.tokensUsed||0,e.cumulativeInputTokens+=Math.floor(h*.7),e.cumulativeOutputTokens+=Math.floor(h*.3)),await Xn(_.content||"",e,this.dbManager,this.sessionManager,r,h,f,"OpenRouter",l)}else if(p.type==="summarize"){let g=ic({id:e.sessionDbId,memory_session_id:e.memorySessionId,project:e.project,user_prompt:e.userPrompt,last_assistant_message:p.last_assistant_message||""},s);e.conversationHistory.push({role:"user",content:g});let _=await this.queryOpenRouterMultiTurn(e.conversationHistory,n,i,a,o),h=0;_.content&&(e.conversationHistory.push({role:"assistant",content:_.content}),h=_.tokensUsed||0,e.cumulativeInputTokens+=Math.floor(h*.7),e.cumulativeOutputTokens+=Math.floor(h*.3)),await Xn(_.content||"",e,this.dbManager,this.sessionManager,r,h,f,"OpenRouter",l)}}let d=Date.now()-e.startTime;E.success("SDK","OpenRouter agent completed",{sessionId:e.sessionDbId,duration:`${(d/1e3).toFixed(1)}s`,historyLength:e.conversationHistory.length,model:i})}catch(n){if(md(n))throw E.warn("SDK","OpenRouter agent aborted",{sessionId:e.sessionDbId}),n;if(fd(n)&&this.fallbackAgent)return E.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 E.failure("SDK","OpenRouter agent error",{sessionDbId:e.sessionDbId},n),n}}estimateTokens(e){return Math.ceil(e.length/Dme)}truncateHistory(e){let r=Qe.loadFromFile(Tn),n=parseInt(r.CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES)||Ame,i=parseInt(r.CLAUDE_MEM_OPENROUTER_MAX_TOKENS)||Mme;if(e.length<=n&&e.reduce((c,u)=>c+this.estimateTokens(u.content),0)<=i)return e;let a=[],o=0;for(let s=e.length-1;s>=0;s--){let c=e[s],u=this.estimateTokens(c.content);if(a.length>=n||o+u>i){E.warn("SDK","Context window truncated to prevent runaway costs",{originalMessages:e.length,keptMessages:a.length,droppedMessages:s+1,estimatedTokens:o,tokenLimit:i});break}a.unshift(c),o+=u}return a}conversationToOpenAIMessages(e){return e.map(r=>({role:r.role==="assistant"?"assistant":"user",content:r.content}))}async queryOpenRouterMultiTurn(e,r,n,i,a){let o=this.truncateHistory(e),s=this.conversationToOpenAIMessages(o),c=o.reduce((g,_)=>g+_.content.length,0),u=this.estimateTokens(o.map(g=>g.content).join(""));E.debug("SDK",`Querying OpenRouter multi-turn (${n})`,{turns:o.length,totalChars:c,estimatedTokens:u});let l=await fetch(jme,{method:"POST",headers:{Authorization:`Bearer ${r}`,"HTTP-Referer":i||"https://github.com/thedotmack/claude-mem","X-Title":a||"claude-mem","Content-Type":"application/json"},body:JSON.stringify({model:n,messages:s,temperature:.3,max_tokens:4096})});if(!l.ok){let g=await l.text();throw new Error(`OpenRouter API error: ${l.status} - ${g}`)}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 E.error("SDK","Empty response from OpenRouter"),{content:""};let p=d.choices[0].message.content,f=d.usage?.total_tokens;if(f){let g=d.usage?.prompt_tokens||0,_=d.usage?.completion_tokens||0,h=g/1e6*3+_/1e6*15;E.info("SDK","OpenRouter API usage",{model:n,inputTokens:g,outputTokens:_,totalTokens:f,estimatedCostUSD:h.toFixed(4),messagesInContext:o.length}),f>5e4&&E.warn("SDK","High token usage detected - consider reducing context",{totalTokens:f,estimatedCost:h.toFixed(4)})}return{content:p,tokensUsed:f}}getOpenRouterConfig(){let e=Tn,r=Qe.loadFromFile(e),n=r.CLAUDE_MEM_OPENROUTER_API_KEY||process.env.OPENROUTER_API_KEY||"",i=r.CLAUDE_MEM_OPENROUTER_MODEL||"xiaomi/mimo-v2-flash:free",a=r.CLAUDE_MEM_OPENROUTER_SITE_URL||"",o=r.CLAUDE_MEM_OPENROUTER_APP_NAME||"claude-mem";return{apiKey:n,model:i,siteUrl:a,appName:o}}};function dE(){let t=Tn;return!!(Qe.loadFromFile(t).CLAUDE_MEM_OPENROUTER_API_KEY||process.env.OPENROUTER_API_KEY)}function pE(){let t=Tn;return Qe.loadFromFile(t).CLAUDE_MEM_PROVIDER==="openrouter"}we();var xg=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(a=>this.stripProjectPath(a,r));return JSON.stringify(i)}catch(n){return E.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(a=>this.sanitizeObservation(a))}}getSummaries(e,r,n){let i=this.dbManager.getSessionStore().db,a=` SELECT ss.id, s.content_session_id as session_id, @@ -1277,15 +1277,15 @@ 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/Ume)}formatObservationIndex(e,r){let n=`#${e.id}`,i=this.formatTime(e.created_at_epoch),a=Be.getInstance().getTypeIcon(e.type),o=e.title||"Untitled",s=this.estimateReadTokens(e),c=Be.getInstance().getWorkEmoji(e.type),u=e.discovery_tokens||0,l=u>0?`${c} ${u}`:"-";return`| ${n} | ${i} | ${a} | ${o} | ~${s} | ${l} |`}formatSessionIndex(e,r){let n=`#S${e.id}`,i=this.formatTime(e.created_at_epoch),a="\u{1F3AF}",o=e.request||`Session ${e.memory_session_id?.substring(0,8)||"unknown"}`;return`| ${n} | ${i} | ${a} | ${o} | - | - |`}formatUserPromptIndex(e,r){let n=`#P${e.id}`,i=this.formatTime(e.created_at_epoch),a="\u{1F4AC}",o=e.prompt_text.length>60?e.prompt_text.substring(0,57)+"...":e.prompt_text;return`| ${n} | ${i} | ${a} | ${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),a=Be.getInstance().getTypeIcon(e.type),o=e.title||"Untitled",s=this.estimateReadTokens(e);return{row:`| ${n} | ${i===r?"\u2033":i} | ${a} | ${o} | ~${s} |`,time:i}}formatSessionSearchRow(e,r){let n=`#S${e.id}`,i=this.formatTime(e.created_at_epoch),a="\u{1F3AF}",o=e.request||`Session ${e.memory_session_id?.substring(0,8)||"unknown"}`;return{row:`| ${n} | ${i===r?"\u2033":i} | ${a} | ${o} | - |`,time:i}}formatUserPromptSearchRow(e,r){let n=`#P${e.id}`,i=this.formatTime(e.created_at_epoch),a="\u{1F4AC}",o=e.prompt_text.length>60?e.prompt_text.substring(0,57)+"...":e.prompt_text;return{row:`| ${n} | ${i===r?"\u2033":i} | ${a} | ${o} | - |`,time:i}}};Mr();var Eg=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,a){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 s=Math.max(0,o-i),c=Math.min(e.length,o+a+1);return e.slice(s,c)}formatTimeline(e,r,n,i,a){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&&a!==void 0?o.push(`**Window:** ${i} records before \u2192 ${a} 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 s=new Map;for(let u of e){let l=this.formatDate(u.epoch);s.has(l)||s.set(l,[]),s.get(l).push(u)}let c=Array.from(s.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 g of l){let _=typeof r=="number"&&g.type==="observation"&&g.data.id===r||typeof r=="string"&&r.startsWith("S")&&g.type==="session"&&`S${g.data.id}`===r;if(g.type==="session"){f&&(o.push(""),f=!1,d=null,p="");let h=g.data,m=h.request||"Session summary",y=_?" \u2190 **ANCHOR**":"";o.push(`**\u{1F3AF} #S${h.id}** ${m} (${this.formatDateTime(g.epoch)})${y}`),o.push("")}else if(g.type==="prompt"){f&&(o.push(""),f=!1,d=null,p="");let h=g.data,m=h.prompt_text.length>100?h.prompt_text.substring(0,100)+"...":h.prompt_text;o.push(`**\u{1F4AC} User Prompt #${h.prompt_number}** (${this.formatDateTime(g.epoch)})`),o.push(`> ${m}`),o.push("")}else if(g.type==="observation"){let h=g.data,m="General";m!==d&&(f&&o.push(""),o.push(`**${m}**`),o.push("| ID | Time | T | Title | Tokens |"),o.push("|----|------|---|-------|--------|"),d=m,f=!0,p="");let y=this.getTypeIcon(h.type),v=this.formatTime(g.epoch),b=h.title||"Untitled",S=this.estimateTokens(h.narrative),w=v!==p?v:"\u2033";p=v;let k=_?" \u2190 **ANCHOR**":"";o.push(`| #${h.id} | ${w} | ${y} | ${b}${k} | ~${S} |`)}}f&&o.push("")}return o.join(` -`)}getTypeIcon(e){return Be.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 kg=class{constructor(e,r){this.sseBroadcaster=e;this.workerService=r}broadcastNewPrompt(e){this.sseBroadcaster.broadcast({type:"new_prompt",prompt:e}),this.sseBroadcaster.broadcast({type:"processing_status",isProcessing:!0}),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 zU=ut(bh(),1),Tg=ut(require("path"),1),Pg=require("fs");Jr();we();var en=class{wrapHandler(e){return(r,n)=>{try{let i=e(r,n);i instanceof Promise&&i.catch(a=>this.handleError(n,a))}catch(i){E.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){E.failure("WORKER",n||"Request failed",{},r),e.headersSent||e.status(500).json({error:r.message})}};var Ig=class extends en{constructor(r,n,i){super();this.sseBroadcaster=r;this.dbManager=n;this.sessionManager=i}setupRoutes(r){let n=Kr();r.use(zU.default.static(Tg.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=Kr(),o=[Tg.default.join(i,"ui","viewer.html"),Tg.default.join(i,"plugin","ui","viewer.html")].find(c=>(0,Pg.existsSync)(c));if(!o)throw new Error("Viewer UI not found at any expected location");let s=(0,Pg.readFileSync)(o,"utf-8");n.setHeader("Content-Type","text/html"),n.send(s)});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 a=this.sessionManager.isAnySessionProcessing(),o=this.sessionManager.getTotalActiveWork();this.sseBroadcaster.broadcast({type:"processing_status",isProcessing:a,queueDepth:o})})};Hr();we();we();var UU=100;function Lme(t){let e=(t.match(//g)||[]).length,r=(t.match(//g)||[]).length;return e+r}function LU(t){let e=Lme(t);return e>UU&&E.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:e,maxAllowed:UU,contentLength:t.length}),t.replace(/[\s\S]*?<\/claude-mem-context>/g,"").replace(/[\s\S]*?<\/private>/g,"").trim()}function fE(t){return LU(t)}function qU(t){return LU(t)}var Og=class{constructor(e,r){this.sessionManager=e;this.eventBroadcaster=r}async completeByDbId(e){await this.sessionManager.deleteSession(e),this.eventBroadcaster.broadcastSessionCompleted(e)}};we();var Zd=class{static checkUserPromptPrivacy(e,r,n,i,a,o){let s=e.getUserPrompt(r,n);return!s||s.trim()===""?(E.debug("HOOK",`Skipping ${i} - user prompt was entirely private`,{sessionId:a,promptNumber:n,...o}),null):s}};un();Jr();var Rg=class extends en{constructor(r,n,i,a,o,s,c){super();this.sessionManager=r;this.dbManager=n;this.sdkAgent=i;this.geminiAgent=a;this.openRouterAgent=o;this.eventBroadcaster=s;this.workerService=c;this.completionHandler=new Og(r,s)}completionHandler;getActiveAgent(){if(pE()){if(dE())return E.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(lE()){if(uE())return E.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 pE()&&dE()?"openrouter":lE()&&uE()?"gemini":"claude"}ensureGeneratorRunning(r,n){let i=this.sessionManager.getSession(r);if(!i)return;let a=this.getSelectedProvider();if(!i.generatorPromise){this.startGeneratorWithProvider(i,a,n);return}i.currentProvider&&i.currentProvider!==a&&E.info("SESSION","Provider changed, will switch after current generator finishes",{sessionId:r,currentProvider:i.currentProvider,selectedProvider:a,historyLength:i.conversationHistory.length})}startGeneratorWithProvider(r,n,i){if(!r)return;let a=n==="openrouter"?this.openRouterAgent:n==="gemini"?this.geminiAgent:this.sdkAgent,o=n==="openrouter"?"OpenRouter":n==="gemini"?"Gemini":"Claude SDK";E.info("SESSION",`Generator auto-starting (${i}) using ${o}`,{sessionId:r.sessionDbId,queueDepth:r.pendingMessages.length,historyLength:r.conversationHistory.length}),r.currentProvider=n,r.generatorPromise=a.startSession(r,this.workerService).catch(s=>{if(r.abortController.signal.aborted)return;E.error("SESSION","Generator failed",{sessionId:r.sessionDbId,provider:n,error:s.message},s);let c=this.sessionManager.getPendingMessageStore();try{let u=c.markSessionMessagesFailed(r.sessionDbId);u>0&&E.error("SESSION","Marked messages as failed after generator error",{sessionId:r.sessionDbId,failedCount:u})}catch(u){E.error("SESSION","Failed to mark messages as failed",{sessionId:r.sessionDbId},u)}}).finally(()=>{let s=r.sessionDbId,c=r.abortController.signal.aborted;if(c?E.info("SESSION","Generator aborted",{sessionId:s}):E.error("SESSION","Generator exited unexpectedly",{sessionId:s}),r.generatorPromise=null,r.currentProvider=null,this.workerService.broadcastProcessingStatus(),!c)try{let l=this.sessionManager.getPendingMessageStore().getPendingCount(s);if(l>0){E.info("SESSION","Restarting generator after crash/exit with pending work",{sessionId:s,pendingCount:l});let d=r.abortController;r.abortController=new AbortController,d.abort(),setTimeout(()=>{let p=this.sessionManager.getSession(s);p&&!p.generatorPromise&&this.startGeneratorWithProvider(p,this.getSelectedProvider(),"crash-recovery")},1e3)}else r.abortController.abort(),E.debug("SESSION","Aborted controller after natural completion",{sessionId:s})}catch(u){E.debug("SESSION","Error during recovery check, aborting to prevent leaks",{sessionId:s,error:u instanceof Error?u.message:String(u)}),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))}handleSessionInit=this.wrapHandler((r,n)=>{let i=this.parseIntParam(r,n,"sessionDbId");if(i===null)return;let{userPrompt:a,promptNumber:o}=r.body;E.info("HTTP","SessionRoutes: handleSessionInit called",{sessionDbId:i,promptNumber:o,has_userPrompt:!!a});let s=this.sessionManager.initializeSession(i,a,o),c=this.dbManager.getSessionStore().getLatestUserPrompt(s.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;E.debug("CHROMA","User prompt synced",{promptId:c.id,duration:`${d}ms`,prompt:p})}).catch(d=>{E.error("CHROMA","User prompt sync failed, continuing without vector search",{promptId:c.id,prompt:l.length>60?l.substring(0,60)+"...":l},d)})}this.startGeneratorWithProvider(s,this.getSelectedProvider(),"init"),this.eventBroadcaster.broadcastSessionStarted(i,s.project),n.json({status:"initialized",sessionDbId:i,port:It()})});handleObservations=this.wrapHandler((r,n)=>{let i=this.parseIntParam(r,n,"sessionDbId");if(i===null)return;let{tool_name:a,tool_input:o,tool_response:s,prompt_number:c,cwd:u}=r.body;this.sessionManager.queueObservation(i,{tool_name:a,tool_input:o,tool_response:s,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:a}=r.body;this.sessionManager.queueSummarize(i,a),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 a=this.sessionManager.getSession(i);if(!a){n.json({status:"not_found"});return}n.json({status:"active",sessionDbId:i,project:a.project,queueLength:a.pendingMessages.length,uptime:Date.now()-a.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:a,tool_input:o,tool_response:s,cwd:c}=r.body;if(!i)return this.badRequest(n,"Missing contentSessionId");let u=Qe.loadFromFile(Tn);if(new Set(u.CLAUDE_MEM_SKIP_TOOLS.split(",").map(y=>y.trim()).filter(Boolean)).has(a)){E.debug("SESSION","Skipping observation for tool",{tool_name:a}),n.json({status:"skipped",reason:"tool_excluded"});return}if(new Set(["Edit","Write","Read","NotebookEdit"]).has(a)&&o){let y=o.file_path||o.notebook_path;if(y&&y.includes("session-memory")){E.debug("SESSION","Skipping meta-observation for session-memory file",{tool_name:a,file_path:y}),n.json({status:"skipped",reason:"session_memory_meta"});return}}let p=this.dbManager.getSessionStore(),f=p.createSDKSession(i,"",""),g=p.getPromptNumberFromUserPrompts(i);if(!Zd.checkUserPromptPrivacy(p,i,g,"observation",f,{tool_name:a})){n.json({status:"skipped",reason:"private"});return}let h=o!==void 0?fE(JSON.stringify(o)):"{}",m=s!==void 0?fE(JSON.stringify(s)):"{}";this.sessionManager.queueObservation(f,{tool_name:a,tool_input:h,tool_response:m,prompt_number:g,cwd:c||(E.error("SESSION","Missing cwd when queueing observation in SessionRoutes",{sessionId:f,tool_name:a}),"")}),this.ensureGeneratorRunning(f,"observation"),this.eventBroadcaster.broadcastObservationQueued(f),n.json({status:"queued"})});handleSummarizeByClaudeId=this.wrapHandler((r,n)=>{let{contentSessionId:i,last_assistant_message:a}=r.body;if(!i)return this.badRequest(n,"Missing contentSessionId");let o=this.dbManager.getSessionStore(),s=o.createSDKSession(i,"",""),c=o.getPromptNumberFromUserPrompts(i);if(!Zd.checkUserPromptPrivacy(o,i,c,"summarize",s)){n.json({status:"skipped",reason:"private"});return}this.sessionManager.queueSummarize(s,a),this.ensureGeneratorRunning(s,"summarize"),this.eventBroadcaster.broadcastSummarizeQueued(),n.json({status:"queued"})});handleSessionInitByClaudeId=this.wrapHandler((r,n)=>{let{contentSessionId:i,project:a,prompt:o}=r.body;if(E.info("HTTP","SessionRoutes: handleSessionInitByClaudeId called",{contentSessionId:i,project:a,prompt_length:o?.length}),!this.validateRequired(r,n,["contentSessionId","project","prompt"]))return;let s=this.dbManager.getSessionStore(),c=s.createSDKSession(i,a,o),u=s.getSessionById(c),l=!u?.memory_session_id;E.info("SESSION",`CREATED | contentSessionId=${i} \u2192 sessionDbId=${c} | isNew=${l} | project=${a}`,{sessionId:c});let p=s.getPromptNumberFromUserPrompts(i)+1,f=u?.memory_session_id||null;p>1?E.debug("HTTP",`[ALIGNMENT] DB Lookup Proof | contentSessionId=${i} \u2192 memorySessionId=${f||"(not yet captured)"} | prompt#=${p}`):E.debug("HTTP",`[ALIGNMENT] New Session | contentSessionId=${i} | prompt#=${p} | memorySessionId will be captured on first SDK response`);let g=qU(o);if(!g||g.trim()===""){E.debug("HOOK","Session init - prompt entirely private",{sessionId:c,promptNumber:p,originalLength:o.length}),n.json({sessionDbId:c,promptNumber:p,skipped:!0,reason:"private"});return}s.saveUserPrompt(i,p,g),E.debug("SESSION","User prompt saved",{sessionId:c,promptNumber:p}),n.json({sessionDbId:c,promptNumber:p,skipped:!1})})};var mE=ut(require("path"),1),Rc=require("fs");we();var FU=require("os");Jr();Hr();var Cg=class extends en{constructor(r,n,i,a,o,s){super();this.paginationHelper=r;this.dbManager=n;this.sessionManager=i;this.sseBroadcaster=a;this.workerService=o;this.startTime=s}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:a,project:o}=this.parsePaginationParams(r),s=this.paginationHelper.getObservations(i,a,o);n.json(s)});handleGetSummaries=this.wrapHandler((r,n)=>{let{offset:i,limit:a,project:o}=this.parsePaginationParams(r),s=this.paginationHelper.getSummaries(i,a,o);n.json(s)});handleGetPrompts=this.wrapHandler((r,n)=>{let{offset:i,limit:a,project:o}=this.parsePaginationParams(r),s=this.paginationHelper.getPrompts(i,a,o);n.json(s)});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:a,limit:o,project:s}=r.body;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:a,limit:o,project:s});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(!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,a=Kr(),o=mE.default.join(a,"package.json"),c=JSON.parse((0,Rc.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=mE.default.join((0,FU.homedir)(),".claude-mem","claude-mem.db"),f=0;(0,Rc.existsSync)(p)&&(f=(0,Rc.statSync)(p).size);let g=Math.floor((Date.now()-this.startTime)/1e3),_=this.sessionManager.getActiveSessionCount(),h=this.sseBroadcaster.getClientCount();n.json({worker:{version:c,uptime:g,activeSessions:_,sseClients:h,port:It()},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 Be.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 kg=class{constructor(e,r){this.sseBroadcaster=e;this.workerService=r}broadcastNewPrompt(e){this.sseBroadcaster.broadcast({type:"new_prompt",prompt:e}),this.sseBroadcaster.broadcast({type:"processing_status",isProcessing:!0}),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 zU=ut(bh(),1),Tg=ut(require("path"),1),Pg=require("fs");ln();we();var Qr=class{wrapHandler(e){return(r,n)=>{try{let i=e(r,n);i instanceof Promise&&i.catch(a=>this.handleError(n,a))}catch(i){E.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){E.failure("WORKER",n||"Request failed",{},r),e.headersSent||e.status(500).json({error:r.message})}};var Ig=class extends Qr{constructor(r,n,i){super();this.sseBroadcaster=r;this.dbManager=n;this.sessionManager=i}setupRoutes(r){let n=Kr();r.use(zU.default.static(Tg.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=Kr(),o=[Tg.default.join(i,"ui","viewer.html"),Tg.default.join(i,"plugin","ui","viewer.html")].find(c=>(0,Pg.existsSync)(c));if(!o)throw new Error("Viewer UI not found at any expected location");let s=(0,Pg.readFileSync)(o,"utf-8");n.setHeader("Content-Type","text/html"),n.send(s)});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 a=this.sessionManager.isAnySessionProcessing(),o=this.sessionManager.getTotalActiveWork();this.sseBroadcaster.broadcast({type:"processing_status",isProcessing:a,queueDepth:o})})};Hr();we();we();var UU=100;function Lme(t){let e=(t.match(//g)||[]).length,r=(t.match(//g)||[]).length;return e+r}function LU(t){let e=Lme(t);return e>UU&&E.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:e,maxAllowed:UU,contentLength:t.length}),t.replace(/[\s\S]*?<\/claude-mem-context>/g,"").replace(/[\s\S]*?<\/private>/g,"").trim()}function fE(t){return LU(t)}function qU(t){return LU(t)}var Og=class{constructor(e,r){this.sessionManager=e;this.eventBroadcaster=r}async completeByDbId(e){await this.sessionManager.deleteSession(e),this.eventBroadcaster.broadcastSessionCompleted(e)}};we();var Zd=class{static checkUserPromptPrivacy(e,r,n,i,a,o){let s=e.getUserPrompt(r,n);return!s||s.trim()===""?(E.debug("HOOK",`Skipping ${i} - user prompt was entirely private`,{sessionId:a,promptNumber:n,...o}),null):s}};cn();ln();var Rg=class extends Qr{constructor(r,n,i,a,o,s,c){super();this.sessionManager=r;this.dbManager=n;this.sdkAgent=i;this.geminiAgent=a;this.openRouterAgent=o;this.eventBroadcaster=s;this.workerService=c;this.completionHandler=new Og(r,s)}completionHandler;getActiveAgent(){if(pE()){if(dE())return E.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(lE()){if(uE())return E.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 pE()&&dE()?"openrouter":lE()&&uE()?"gemini":"claude"}ensureGeneratorRunning(r,n){let i=this.sessionManager.getSession(r);if(!i)return;let a=this.getSelectedProvider();if(!i.generatorPromise){this.startGeneratorWithProvider(i,a,n);return}i.currentProvider&&i.currentProvider!==a&&E.info("SESSION","Provider changed, will switch after current generator finishes",{sessionId:r,currentProvider:i.currentProvider,selectedProvider:a,historyLength:i.conversationHistory.length})}startGeneratorWithProvider(r,n,i){if(!r)return;let a=n==="openrouter"?this.openRouterAgent:n==="gemini"?this.geminiAgent:this.sdkAgent,o=n==="openrouter"?"OpenRouter":n==="gemini"?"Gemini":"Claude SDK";E.info("SESSION",`Generator auto-starting (${i}) using ${o}`,{sessionId:r.sessionDbId,queueDepth:r.pendingMessages.length,historyLength:r.conversationHistory.length}),r.currentProvider=n,r.generatorPromise=a.startSession(r,this.workerService).catch(s=>{if(r.abortController.signal.aborted)return;E.error("SESSION","Generator failed",{sessionId:r.sessionDbId,provider:n,error:s.message},s);let c=this.sessionManager.getPendingMessageStore();try{let u=c.markSessionMessagesFailed(r.sessionDbId);u>0&&E.error("SESSION","Marked messages as failed after generator error",{sessionId:r.sessionDbId,failedCount:u})}catch(u){E.error("SESSION","Failed to mark messages as failed",{sessionId:r.sessionDbId},u)}}).finally(()=>{let s=r.sessionDbId,c=r.abortController.signal.aborted;if(c?E.info("SESSION","Generator aborted",{sessionId:s}):E.error("SESSION","Generator exited unexpectedly",{sessionId:s}),r.generatorPromise=null,r.currentProvider=null,this.workerService.broadcastProcessingStatus(),!c)try{let l=this.sessionManager.getPendingMessageStore().getPendingCount(s);if(l>0){E.info("SESSION","Restarting generator after crash/exit with pending work",{sessionId:s,pendingCount:l});let d=r.abortController;r.abortController=new AbortController,d.abort(),setTimeout(()=>{let p=this.sessionManager.getSession(s);p&&!p.generatorPromise&&this.startGeneratorWithProvider(p,this.getSelectedProvider(),"crash-recovery")},1e3)}else r.abortController.abort(),E.debug("SESSION","Aborted controller after natural completion",{sessionId:s})}catch(u){E.debug("SESSION","Error during recovery check, aborting to prevent leaks",{sessionId:s,error:u instanceof Error?u.message:String(u)}),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))}handleSessionInit=this.wrapHandler((r,n)=>{let i=this.parseIntParam(r,n,"sessionDbId");if(i===null)return;let{userPrompt:a,promptNumber:o}=r.body;E.info("HTTP","SessionRoutes: handleSessionInit called",{sessionDbId:i,promptNumber:o,has_userPrompt:!!a});let s=this.sessionManager.initializeSession(i,a,o),c=this.dbManager.getSessionStore().getLatestUserPrompt(s.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;E.debug("CHROMA","User prompt synced",{promptId:c.id,duration:`${d}ms`,prompt:p})}).catch(d=>{E.error("CHROMA","User prompt sync failed, continuing without vector search",{promptId:c.id,prompt:l.length>60?l.substring(0,60)+"...":l},d)})}this.startGeneratorWithProvider(s,this.getSelectedProvider(),"init"),this.eventBroadcaster.broadcastSessionStarted(i,s.project),n.json({status:"initialized",sessionDbId:i,port:It()})});handleObservations=this.wrapHandler((r,n)=>{let i=this.parseIntParam(r,n,"sessionDbId");if(i===null)return;let{tool_name:a,tool_input:o,tool_response:s,prompt_number:c,cwd:u}=r.body;this.sessionManager.queueObservation(i,{tool_name:a,tool_input:o,tool_response:s,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:a}=r.body;this.sessionManager.queueSummarize(i,a),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 a=this.sessionManager.getSession(i);if(!a){n.json({status:"not_found"});return}n.json({status:"active",sessionDbId:i,project:a.project,queueLength:a.pendingMessages.length,uptime:Date.now()-a.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:a,tool_input:o,tool_response:s,cwd:c}=r.body;if(!i)return this.badRequest(n,"Missing contentSessionId");let u=Qe.loadFromFile(Tn);if(new Set(u.CLAUDE_MEM_SKIP_TOOLS.split(",").map(y=>y.trim()).filter(Boolean)).has(a)){E.debug("SESSION","Skipping observation for tool",{tool_name:a}),n.json({status:"skipped",reason:"tool_excluded"});return}if(new Set(["Edit","Write","Read","NotebookEdit"]).has(a)&&o){let y=o.file_path||o.notebook_path;if(y&&y.includes("session-memory")){E.debug("SESSION","Skipping meta-observation for session-memory file",{tool_name:a,file_path:y}),n.json({status:"skipped",reason:"session_memory_meta"});return}}let p=this.dbManager.getSessionStore(),f=p.createSDKSession(i,"",""),g=p.getPromptNumberFromUserPrompts(i);if(!Zd.checkUserPromptPrivacy(p,i,g,"observation",f,{tool_name:a})){n.json({status:"skipped",reason:"private"});return}let h=o!==void 0?fE(JSON.stringify(o)):"{}",m=s!==void 0?fE(JSON.stringify(s)):"{}";this.sessionManager.queueObservation(f,{tool_name:a,tool_input:h,tool_response:m,prompt_number:g,cwd:c||(E.error("SESSION","Missing cwd when queueing observation in SessionRoutes",{sessionId:f,tool_name:a}),"")}),this.ensureGeneratorRunning(f,"observation"),this.eventBroadcaster.broadcastObservationQueued(f),n.json({status:"queued"})});handleSummarizeByClaudeId=this.wrapHandler((r,n)=>{let{contentSessionId:i,last_assistant_message:a}=r.body;if(!i)return this.badRequest(n,"Missing contentSessionId");let o=this.dbManager.getSessionStore(),s=o.createSDKSession(i,"",""),c=o.getPromptNumberFromUserPrompts(i);if(!Zd.checkUserPromptPrivacy(o,i,c,"summarize",s)){n.json({status:"skipped",reason:"private"});return}this.sessionManager.queueSummarize(s,a),this.ensureGeneratorRunning(s,"summarize"),this.eventBroadcaster.broadcastSummarizeQueued(),n.json({status:"queued"})});handleSessionInitByClaudeId=this.wrapHandler((r,n)=>{let{contentSessionId:i,project:a,prompt:o}=r.body;if(E.info("HTTP","SessionRoutes: handleSessionInitByClaudeId called",{contentSessionId:i,project:a,prompt_length:o?.length}),!this.validateRequired(r,n,["contentSessionId","project","prompt"]))return;let s=this.dbManager.getSessionStore(),c=s.createSDKSession(i,a,o),u=s.getSessionById(c),l=!u?.memory_session_id;E.info("SESSION",`CREATED | contentSessionId=${i} \u2192 sessionDbId=${c} | isNew=${l} | project=${a}`,{sessionId:c});let p=s.getPromptNumberFromUserPrompts(i)+1,f=u?.memory_session_id||null;p>1?E.debug("HTTP",`[ALIGNMENT] DB Lookup Proof | contentSessionId=${i} \u2192 memorySessionId=${f||"(not yet captured)"} | prompt#=${p}`):E.debug("HTTP",`[ALIGNMENT] New Session | contentSessionId=${i} | prompt#=${p} | memorySessionId will be captured on first SDK response`);let g=qU(o);if(!g||g.trim()===""){E.debug("HOOK","Session init - prompt entirely private",{sessionId:c,promptNumber:p,originalLength:o.length}),n.json({sessionDbId:c,promptNumber:p,skipped:!0,reason:"private"});return}s.saveUserPrompt(i,p,g),E.debug("SESSION","User prompt saved",{sessionId:c,promptNumber:p}),n.json({sessionDbId:c,promptNumber:p,skipped:!1})})};var mE=ut(require("path"),1),Rc=require("fs");we();var FU=require("os");ln();Hr();var Cg=class extends Qr{constructor(r,n,i,a,o,s){super();this.paginationHelper=r;this.dbManager=n;this.sessionManager=i;this.sseBroadcaster=a;this.workerService=o;this.startTime=s}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:a,project:o}=this.parsePaginationParams(r),s=this.paginationHelper.getObservations(i,a,o);n.json(s)});handleGetSummaries=this.wrapHandler((r,n)=>{let{offset:i,limit:a,project:o}=this.parsePaginationParams(r),s=this.paginationHelper.getSummaries(i,a,o);n.json(s)});handleGetPrompts=this.wrapHandler((r,n)=>{let{offset:i,limit:a,project:o}=this.parsePaginationParams(r),s=this.paginationHelper.getPrompts(i,a,o);n.json(s)});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:a,limit:o,project:s}=r.body;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:a,limit:o,project:s});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(!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,a=Kr(),o=mE.default.join(a,"package.json"),c=JSON.parse((0,Rc.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=mE.default.join((0,FU.homedir)(),".claude-mem","claude-mem.db"),f=0;(0,Rc.existsSync)(p)&&(f=(0,Rc.statSync)(p).size);let g=Math.floor((Date.now()-this.startTime)/1e3),_=this.sessionManager.getActiveSessionCount(),h=this.sseBroadcaster.getClientCount();n.json({worker:{version:c,uptime:g,activeSessions:_,sseClients:h,port:It()},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(s=>s.project);n.json({projects:o})});handleGetProcessingStatus=this.wrapHandler((r,n)=>{let i=this.sessionManager.isAnySessionProcessing(),a=this.sessionManager.getTotalActiveWork();n.json({isProcessing:i,queueDepth:a})});handleSetProcessing=this.wrapHandler((r,n)=>{this.workerService.broadcastProcessingStatus();let i=this.sessionManager.isAnySessionProcessing(),a=this.sessionManager.getTotalQueueDepth(),o=this.sessionManager.getActiveSessionCount();n.json({status:"ok",isProcessing:i,queueDepth:a,activeSessions:o})});parsePaginationParams(r){let n=parseInt(r.query.offset,10)||0,i=Math.min(parseInt(r.query.limit,10)||20,100),a=r.query.project;return{offset:n,limit:i,project:a}}handleImport=this.wrapHandler((r,n)=>{let{sessions:i,summaries:a,observations:o,prompts:s}=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(a))for(let l of a)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(s))for(let l of s)u.importUserPrompt(l).imported?c.promptsImported++:c.promptsSkipped++;n.json({success:!0,stats:c})});handleGetPendingQueue=this.wrapHandler((r,n)=>{let{PendingMessageStore:i}=(xo(),Yd(tc)),a=new i(this.dbManager.getSessionStore().db,3),o=a.getQueueMessages(),s=a.getRecentlyProcessed(20,30),c=a.getStuckCount(300*1e3),u=a.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:s,sessionsWithPendingWork:u})});handleProcessPendingQueue=this.wrapHandler(async(r,n)=>{let i=Math.min(Math.max(parseInt(r.body.sessionLimit,10)||10,1),100),a=await this.workerService.processPendingQueues(i);n.json({success:!0,...a})});handleClearFailedQueue=this.wrapHandler((r,n)=>{let{PendingMessageStore:i}=(xo(),Yd(tc)),o=new i(this.dbManager.getSessionStore().db,3).clearFailed();E.info("QUEUE","Cleared failed queue messages",{clearedCount:o}),n.json({success:!0,clearedCount:o})});handleClearAllQueue=this.wrapHandler((r,n)=>{let{PendingMessageStore:i}=(xo(),Yd(tc)),o=new i(this.dbManager.getSessionStore().db,3).clearAll();E.warn("QUEUE","Cleared ALL queue messages (pending, processing, failed)",{clearedCount:o}),n.json({success:!0,clearedCount:o})})};var Lg=class extends en{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:a}=await Promise.resolve().then(()=>(TE(),kE)),o=`/preview/${i}`,s=await a({session_id:"preview-"+Date.now(),cwd:o},!0);n.setHeader("Content-Type","text/plain; charset=utf-8"),n.send(s)});handleContextInject=this.wrapHandler(async(r,n)=>{let i=r.query.projects||r.query.project,a=r.query.colors==="true";if(!i){this.badRequest(n,"Project(s) parameter is required");return}let o=i.split(",").map(d=>d.trim()).filter(Boolean);if(o.length===0){this.badRequest(n,"At least one project is required");return}let{generateContext:s}=await Promise.resolve().then(()=>(TE(),kE)),u=`/context/${o[o.length-1]}`,l=await s({session_id:"context-inject-"+Date.now(),cwd:u,projects:o},a);n.setHeader("Content-Type","text/plain; charset=utf-8"),n.send(l)});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 Co=ut(require("path"),1),hr=require("fs"),RE=require("os");Jr();we();var PE=require("child_process"),Ro=require("fs"),BL=require("os"),Kd=require("path");we();var Jd=(0,Kd.join)((0,BL.homedir)(),".claude","plugins","marketplaces","thedotmack");function IE(t){return!t||typeof t!="string"?!1:/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(t)&&!t.includes("..")}var Xme=3e5,OE=6e5;function jn(t){let e=(0,PE.spawnSync)("git",t,{cwd:Jd,encoding:"utf-8",timeout:Xme,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 VL(t,e=OE){let n=process.platform==="win32"?"npm.cmd":"npm",i=(0,PE.spawnSync)(n,t,{cwd:Jd,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 qg(){let t=(0,Kd.join)(Jd,".git");if(!(0,Ro.existsSync)(t))return{branch:null,isBeta:!1,isGitRepo:!1,isDirty:!1,canSwitch:!1,error:"Installed plugin is not a git repository"};try{let e=jn(["rev-parse","--abbrev-ref","HEAD"]),n=jn(["status","--porcelain"]).length>0,i=e.startsWith("beta");return{branch:e,isBeta:i,isGitRepo:!0,isDirty:n,canSwitch:!0}}catch(e){return E.error("BRANCH","Failed to get branch info",{},e),{branch:null,isBeta:!1,isGitRepo:!0,isDirty:!1,canSwitch:!1,error:e.message}}}async function GL(t){if(!IE(t))return{success:!1,error:`Invalid branch name: ${t}. Branch names must be alphanumeric with hyphens, underscores, slashes, or dots.`};let e=qg();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{E.info("BRANCH","Starting branch switch",{from:e.branch,to:t}),E.debug("BRANCH","Discarding local changes"),jn(["checkout","--","."]),jn(["clean","-fd"]),E.debug("BRANCH","Fetching from origin"),jn(["fetch","origin"]),E.debug("BRANCH","Checking out branch",{branch:t});try{jn(["checkout",t])}catch(n){E.debug("BRANCH","Branch not local, tracking remote",{branch:t,error:n instanceof Error?n.message:String(n)}),jn(["checkout","-b",t,`origin/${t}`])}E.debug("BRANCH","Pulling latest"),jn(["pull","origin",t]);let r=(0,Kd.join)(Jd,".install-version");return(0,Ro.existsSync)(r)&&(0,Ro.unlinkSync)(r),E.debug("BRANCH","Running npm install"),VL(["install"],OE),E.success("BRANCH","Branch switch complete",{branch:t}),{success:!0,branch:t,message:`Switched to ${t}. Worker will restart automatically.`}}catch(r){E.error("BRANCH","Branch switch failed",{targetBranch:t},r);try{e.branch&&IE(e.branch)&&jn(["checkout",e.branch])}catch(n){E.error("BRANCH","Recovery checkout also failed",{originalBranch:e.branch},n)}return{success:!1,error:`Branch switch failed: ${r.message}`}}}async function WL(){let t=qg();if(!t.isGitRepo||!t.branch)return{success:!1,error:"Cannot pull updates: not a git repository"};try{if(!IE(t.branch))return{success:!1,error:`Invalid current branch name: ${t.branch}`};E.info("BRANCH","Pulling updates",{branch:t.branch}),jn(["checkout","--","."]),jn(["fetch","origin"]),jn(["pull","origin",t.branch]);let e=(0,Kd.join)(Jd,".install-version");return(0,Ro.existsSync)(e)&&(0,Ro.unlinkSync)(e),VL(["install"],OE),E.success("BRANCH","Updates pulled",{branch:t.branch}),{success:!0,branch:t.branch,message:`Updated ${t.branch}. Worker will restart automatically.`}}catch(e){return E.error("BRANCH","Pull failed",{},e),{success:!1,error:`Pull failed: ${e.message}`}}}un();Hr();var Fg=class extends en{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=Co.default.join((0,RE.homedir)(),".claude-mem","settings.json");this.ensureSettingsFile(i);let a=Qe.loadFromFile(i);n.json(a)});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 a=Co.default.join((0,RE.homedir)(),".claude-mem","settings.json");this.ensureSettingsFile(a);let o={};if((0,hr.existsSync)(a)){let c=(0,hr.readFileSync)(a,"utf-8");try{o=JSON.parse(c)}catch(u){E.error("SETTINGS","Failed to parse settings file",{settingsPath:a},u),n.status(500).json({success:!1,error:"Settings file is corrupted. Delete ~/.claude-mem/settings.json to reset."});return}}let s=["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"];for(let c of s)r.body[c]!==void 0&&(o[c]=r.body[c]);(0,hr.writeFileSync)(a,JSON.stringify(o,null,2),"utf-8"),QR(),E.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=qg();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 a=["main","beta/7.0","feature/bun-executable"];if(!a.includes(i)){n.status(400).json({success:!1,error:`Invalid branch. Allowed: ${a.join(", ")}`});return}E.info("WORKER","Branch switch requested",{branch:i});let o=await GL(i);o.success&&setTimeout(()=>{E.info("WORKER","Restarting worker after branch switch"),process.exit(0)},1e3),n.json(o)});handleUpdateBranch=this.wrapHandler(async(r,n)=>{E.info("WORKER","Branch update requested");let i=await WL();i.success&&setTimeout(()=>{E.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"].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"};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 E.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=Kr(),n=Co.default.join(r,"plugin",".mcp.json");return(0,hr.existsSync)(n)}toggleMcp(r){let n=Kr(),i=Co.default.join(n,"plugin",".mcp.json"),a=Co.default.join(n,"plugin",".mcp.json.disabled");r&&(0,hr.existsSync)(a)?((0,hr.renameSync)(a,i),E.info("WORKER","MCP search server enabled")):!r&&(0,hr.existsSync)(i)?((0,hr.renameSync)(i,a),E.info("WORKER","MCP search server disabled")):E.debug("WORKER","MCP toggle no-op (already in desired state)",{enabled:r})}ensureSettingsFile(r){if(!(0,hr.existsSync)(r)){let n=Qe.getAllDefaults(),i=Co.default.dirname(r);(0,hr.existsSync)(i)||(0,hr.mkdirSync)(i,{recursive:!0}),(0,hr.writeFileSync)(r,JSON.stringify(n,null,2),"utf-8"),E.info("SETTINGS","Created settings file with defaults",{settingsPath:r})}}};var No=require("fs"),Zg=require("path");we();un();var Hg=class extends en{getLogFilePath(){let e=Qe.get("CLAUDE_MEM_DATA_DIR"),r=(0,Zg.join)(e,"logs"),n=new Date().toISOString().split("T")[0];return(0,Zg.join)(r,`claude-mem-${n}.log`)}getLogsDir(){let e=Qe.get("CLAUDE_MEM_DATA_DIR");return(0,Zg.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,No.existsSync)(n)){r.json({logs:"",path:n,exists:!1});return}let i=parseInt(e.query.lines||"1000",10),a=Math.min(i,1e4),s=(0,No.readFileSync)(n,"utf-8").split(` + `).all().map(s=>s.project);n.json({projects:o})});handleGetProcessingStatus=this.wrapHandler((r,n)=>{let i=this.sessionManager.isAnySessionProcessing(),a=this.sessionManager.getTotalActiveWork();n.json({isProcessing:i,queueDepth:a})});handleSetProcessing=this.wrapHandler((r,n)=>{this.workerService.broadcastProcessingStatus();let i=this.sessionManager.isAnySessionProcessing(),a=this.sessionManager.getTotalQueueDepth(),o=this.sessionManager.getActiveSessionCount();n.json({status:"ok",isProcessing:i,queueDepth:a,activeSessions:o})});parsePaginationParams(r){let n=parseInt(r.query.offset,10)||0,i=Math.min(parseInt(r.query.limit,10)||20,100),a=r.query.project;return{offset:n,limit:i,project:a}}handleImport=this.wrapHandler((r,n)=>{let{sessions:i,summaries:a,observations:o,prompts:s}=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(a))for(let l of a)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(s))for(let l of s)u.importUserPrompt(l).imported?c.promptsImported++:c.promptsSkipped++;n.json({success:!0,stats:c})});handleGetPendingQueue=this.wrapHandler((r,n)=>{let{PendingMessageStore:i}=(xo(),Yd(tc)),a=new i(this.dbManager.getSessionStore().db,3),o=a.getQueueMessages(),s=a.getRecentlyProcessed(20,30),c=a.getStuckCount(300*1e3),u=a.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:s,sessionsWithPendingWork:u})});handleProcessPendingQueue=this.wrapHandler(async(r,n)=>{let i=Math.min(Math.max(parseInt(r.body.sessionLimit,10)||10,1),100),a=await this.workerService.processPendingQueues(i);n.json({success:!0,...a})});handleClearFailedQueue=this.wrapHandler((r,n)=>{let{PendingMessageStore:i}=(xo(),Yd(tc)),o=new i(this.dbManager.getSessionStore().db,3).clearFailed();E.info("QUEUE","Cleared failed queue messages",{clearedCount:o}),n.json({success:!0,clearedCount:o})});handleClearAllQueue=this.wrapHandler((r,n)=>{let{PendingMessageStore:i}=(xo(),Yd(tc)),o=new i(this.dbManager.getSessionStore().db,3).clearAll();E.warn("QUEUE","Cleared ALL queue messages (pending, processing, failed)",{clearedCount:o}),n.json({success:!0,clearedCount:o})})};var Lg=class extends Qr{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:a}=await Promise.resolve().then(()=>(TE(),kE)),o=`/preview/${i}`,s=await a({session_id:"preview-"+Date.now(),cwd:o},!0);n.setHeader("Content-Type","text/plain; charset=utf-8"),n.send(s)});handleContextInject=this.wrapHandler(async(r,n)=>{let i=r.query.projects||r.query.project,a=r.query.colors==="true";if(!i){this.badRequest(n,"Project(s) parameter is required");return}let o=i.split(",").map(d=>d.trim()).filter(Boolean);if(o.length===0){this.badRequest(n,"At least one project is required");return}let{generateContext:s}=await Promise.resolve().then(()=>(TE(),kE)),u=`/context/${o[o.length-1]}`,l=await s({session_id:"context-inject-"+Date.now(),cwd:u,projects:o},a);n.setHeader("Content-Type","text/plain; charset=utf-8"),n.send(l)});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 Co=ut(require("path"),1),hr=require("fs"),RE=require("os");ln();we();var PE=require("child_process"),Ro=require("fs"),BL=require("os"),Kd=require("path");we();var Jd=(0,Kd.join)((0,BL.homedir)(),".claude","plugins","marketplaces","thedotmack");function IE(t){return!t||typeof t!="string"?!1:/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(t)&&!t.includes("..")}var Xme=3e5,OE=6e5;function jn(t){let e=(0,PE.spawnSync)("git",t,{cwd:Jd,encoding:"utf-8",timeout:Xme,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 VL(t,e=OE){let n=process.platform==="win32"?"npm.cmd":"npm",i=(0,PE.spawnSync)(n,t,{cwd:Jd,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 qg(){let t=(0,Kd.join)(Jd,".git");if(!(0,Ro.existsSync)(t))return{branch:null,isBeta:!1,isGitRepo:!1,isDirty:!1,canSwitch:!1,error:"Installed plugin is not a git repository"};try{let e=jn(["rev-parse","--abbrev-ref","HEAD"]),n=jn(["status","--porcelain"]).length>0,i=e.startsWith("beta");return{branch:e,isBeta:i,isGitRepo:!0,isDirty:n,canSwitch:!0}}catch(e){return E.error("BRANCH","Failed to get branch info",{},e),{branch:null,isBeta:!1,isGitRepo:!0,isDirty:!1,canSwitch:!1,error:e.message}}}async function GL(t){if(!IE(t))return{success:!1,error:`Invalid branch name: ${t}. Branch names must be alphanumeric with hyphens, underscores, slashes, or dots.`};let e=qg();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{E.info("BRANCH","Starting branch switch",{from:e.branch,to:t}),E.debug("BRANCH","Discarding local changes"),jn(["checkout","--","."]),jn(["clean","-fd"]),E.debug("BRANCH","Fetching from origin"),jn(["fetch","origin"]),E.debug("BRANCH","Checking out branch",{branch:t});try{jn(["checkout",t])}catch(n){E.debug("BRANCH","Branch not local, tracking remote",{branch:t,error:n instanceof Error?n.message:String(n)}),jn(["checkout","-b",t,`origin/${t}`])}E.debug("BRANCH","Pulling latest"),jn(["pull","origin",t]);let r=(0,Kd.join)(Jd,".install-version");return(0,Ro.existsSync)(r)&&(0,Ro.unlinkSync)(r),E.debug("BRANCH","Running npm install"),VL(["install"],OE),E.success("BRANCH","Branch switch complete",{branch:t}),{success:!0,branch:t,message:`Switched to ${t}. Worker will restart automatically.`}}catch(r){E.error("BRANCH","Branch switch failed",{targetBranch:t},r);try{e.branch&&IE(e.branch)&&jn(["checkout",e.branch])}catch(n){E.error("BRANCH","Recovery checkout also failed",{originalBranch:e.branch},n)}return{success:!1,error:`Branch switch failed: ${r.message}`}}}async function WL(){let t=qg();if(!t.isGitRepo||!t.branch)return{success:!1,error:"Cannot pull updates: not a git repository"};try{if(!IE(t.branch))return{success:!1,error:`Invalid current branch name: ${t.branch}`};E.info("BRANCH","Pulling updates",{branch:t.branch}),jn(["checkout","--","."]),jn(["fetch","origin"]),jn(["pull","origin",t.branch]);let e=(0,Kd.join)(Jd,".install-version");return(0,Ro.existsSync)(e)&&(0,Ro.unlinkSync)(e),VL(["install"],OE),E.success("BRANCH","Updates pulled",{branch:t.branch}),{success:!0,branch:t.branch,message:`Updated ${t.branch}. Worker will restart automatically.`}}catch(e){return E.error("BRANCH","Pull failed",{},e),{success:!1,error:`Pull failed: ${e.message}`}}}cn();Hr();var Fg=class extends Qr{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=Co.default.join((0,RE.homedir)(),".claude-mem","settings.json");this.ensureSettingsFile(i);let a=Qe.loadFromFile(i);n.json(a)});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 a=Co.default.join((0,RE.homedir)(),".claude-mem","settings.json");this.ensureSettingsFile(a);let o={};if((0,hr.existsSync)(a)){let c=(0,hr.readFileSync)(a,"utf-8");try{o=JSON.parse(c)}catch(u){E.error("SETTINGS","Failed to parse settings file",{settingsPath:a},u),n.status(500).json({success:!1,error:"Settings file is corrupted. Delete ~/.claude-mem/settings.json to reset."});return}}let s=["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"];for(let c of s)r.body[c]!==void 0&&(o[c]=r.body[c]);(0,hr.writeFileSync)(a,JSON.stringify(o,null,2),"utf-8"),QR(),E.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=qg();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 a=["main","beta/7.0","feature/bun-executable"];if(!a.includes(i)){n.status(400).json({success:!1,error:`Invalid branch. Allowed: ${a.join(", ")}`});return}E.info("WORKER","Branch switch requested",{branch:i});let o=await GL(i);o.success&&setTimeout(()=>{E.info("WORKER","Restarting worker after branch switch"),process.exit(0)},1e3),n.json(o)});handleUpdateBranch=this.wrapHandler(async(r,n)=>{E.info("WORKER","Branch update requested");let i=await WL();i.success&&setTimeout(()=>{E.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"].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"};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 E.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=Kr(),n=Co.default.join(r,"plugin",".mcp.json");return(0,hr.existsSync)(n)}toggleMcp(r){let n=Kr(),i=Co.default.join(n,"plugin",".mcp.json"),a=Co.default.join(n,"plugin",".mcp.json.disabled");r&&(0,hr.existsSync)(a)?((0,hr.renameSync)(a,i),E.info("WORKER","MCP search server enabled")):!r&&(0,hr.existsSync)(i)?((0,hr.renameSync)(i,a),E.info("WORKER","MCP search server disabled")):E.debug("WORKER","MCP toggle no-op (already in desired state)",{enabled:r})}ensureSettingsFile(r){if(!(0,hr.existsSync)(r)){let n=Qe.getAllDefaults(),i=Co.default.dirname(r);(0,hr.existsSync)(i)||(0,hr.mkdirSync)(i,{recursive:!0}),(0,hr.writeFileSync)(r,JSON.stringify(n,null,2),"utf-8"),E.info("SETTINGS","Created settings file with defaults",{settingsPath:r})}}};var No=require("fs"),Zg=require("path");we();cn();var Hg=class extends Qr{getLogFilePath(){let e=Qe.get("CLAUDE_MEM_DATA_DIR"),r=(0,Zg.join)(e,"logs"),n=new Date().toISOString().split("T")[0];return(0,Zg.join)(r,`claude-mem-${n}.log`)}getLogsDir(){let e=Qe.get("CLAUDE_MEM_DATA_DIR");return(0,Zg.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,No.existsSync)(n)){r.json({logs:"",path:n,exists:!1});return}let i=parseInt(e.query.lines||"1000",10),a=Math.min(i,1e4),s=(0,No.readFileSync)(n,"utf-8").split(` `),c=Math.max(0,s.length-a),u=s.slice(c).join(` -`);r.json({logs:u,path:n,exists:!0,totalLines:s.length,returnedLines:s.length-c})});handleClearLogs=this.wrapHandler((e,r)=>{let n=this.getLogFilePath();if(!(0,No.existsSync)(n)){r.json({success:!0,message:"Log file does not exist",path:n});return}(0,No.writeFileSync)(n,"","utf-8"),E.info("SYSTEM","Log file cleared via UI",{path:n}),r.json({success:!0,message:"Log file cleared",path:n})})};var ihe={},ehe="9.0.11";function fq(t,e){return{continue:!0,suppressOutput:!0,status:t,...e&&{message:e}}}var Vg=class{server;startTime=Date.now();mcpClient;mcpReady=!1;initializationCompleteFlag=!1;isShuttingDown=!1;dbManager;sessionManager;sseBroadcaster;sdkAgent;geminiAgent;openRouterAgent;paginationHelper;settingsManager;sessionEventBroadcaster;searchRoutes=null;initializationComplete;resolveInitialization;stopOrphanReaper=null;constructor(){this.initializationComplete=new Promise(e=>{this.resolveInitialization=e}),this.dbManager=new Th,this.sessionManager=new Rh(this.dbManager),this.sseBroadcaster=new Ch,this.sdkAgent=new gg(this.dbManager,this.sessionManager),this.geminiAgent=new vg(this.dbManager,this.sessionManager),this.openRouterAgent=new bg(this.dbManager,this.sessionManager),this.paginationHelper=new xg(this.dbManager),this.settingsManager=new Sg(this.dbManager),this.sessionEventBroadcaster=new kg(this.sseBroadcaster,this),this.sessionManager.setOnSessionDeleted(()=>{this.broadcastProcessingStatus()}),this.mcpClient=new ws({name:"worker-search-proxy",version:ehe},{capabilities:{}}),this.server=new wh({getInitializationComplete:()=>this.initializationCompleteFlag,getMcpReady:()=>this.mcpReady,onShutdown:()=>this.shutdown(),onRestart:()=>this.shutdown()}),this.registerRoutes(),this.registerSignalHandlers()}registerSignalHandlers(){let e={value:this.isShuttingDown},r=uC(()=>this.shutdown(),e);process.on("SIGTERM",()=>{this.isShuttingDown=e.value,r("SIGTERM")}),process.on("SIGINT",()=>{this.isShuttingDown=e.value,r("SIGINT")})}registerRoutes(){this.server.registerRoutes(new Ig(this.sseBroadcaster,this.dbManager,this.sessionManager)),this.server.registerRoutes(new Rg(this.sessionManager,this.dbManager,this.sdkAgent,this.geminiAgent,this.openRouterAgent,this.sessionEventBroadcaster,this)),this.server.registerRoutes(new Cg(this.paginationHelper,this.dbManager,this.sessionManager,this.sseBroadcaster,this,this.startTime)),this.server.registerRoutes(new Fg(this.settingsManager)),this.server.registerRoutes(new Hg),this.server.app.get("/api/context/inject",async(e,r,n)=>{let a=new Promise((o,s)=>setTimeout(()=>s(new Error("Initialization timeout")),3e5));if(await Promise.race([this.initializationComplete,a]),!this.searchRoutes){r.status(503).json({error:"Search routes not initialized"});return}n()})}async start(){let e=It(),r=cm();await this.server.listen(e,r),nC({pid:process.pid,port:e,startedAt:new Date().toISOString()}),E.info("SYSTEM","Worker started",{host:r,port:e,pid:process.pid}),this.initializeBackground().catch(n=>{E.error("SYSTEM","Background initialization failed",{},n)})}async initializeBackground(){try{await cC();let{ModeManager:e}=await Promise.resolve().then(()=>(Mr(),Q4)),{SettingsDefaultsManager:r}=await Promise.resolve().then(()=>(un(),WR)),{USER_SETTINGS_PATH:n}=await Promise.resolve().then(()=>(Jr(),k4)),a=r.loadFromFile(n).CLAUDE_MEM_MODE;e.getInstance().loadMode(a),E.info("SYSTEM",`Mode loaded: ${a}`),await this.dbManager.initialize();let{PendingMessageStore:o}=await Promise.resolve().then(()=>(xo(),tc)),s=new o(this.dbManager.getSessionStore().db,3),c=300*1e3,u=s.resetStuckMessages(c);u>0&&E.info("SYSTEM",`Recovered ${u} stuck messages from previous session`,{thresholdMinutes:5});let l=new $g,d=new Eg,p=new wg(this.dbManager.getSessionSearch(),this.dbManager.getSessionStore(),this.dbManager.getChromaSync(),l,d);this.searchRoutes=new Lg(p),this.server.registerRoutes(this.searchRoutes),E.info("WORKER","SearchManager initialized and search routes registered");let f=pq.default.join(__dirname,"mcp-server.cjs"),g=new ks({command:"node",args:[f],env:process.env}),_=3e5,h=this.mcpClient.connect(g),m=new Promise((y,v)=>setTimeout(()=>v(new Error("MCP connection timeout after 5 minutes")),_));await Promise.race([h,m]),this.mcpReady=!0,E.success("WORKER","Connected to MCP server"),this.initializationCompleteFlag=!0,this.resolveInitialization(),E.info("SYSTEM","Background initialization complete"),this.stopOrphanReaper=X4(()=>{let y=new Set;for(let[v]of this.sessionManager.sessions)y.add(v);return y}),E.info("SYSTEM","Started orphan reaper (runs every 5 minutes)"),this.processPendingQueues(50).then(y=>{y.sessionsStarted>0&&E.info("SYSTEM",`Auto-recovered ${y.sessionsStarted} sessions with pending work`,{totalPending:y.totalPendingSessions,started:y.sessionsStarted,sessionIds:y.startedSessionIds})}).catch(y=>{E.error("SYSTEM","Auto-recovery of pending queues failed",{},y)})}catch(e){throw E.error("SYSTEM","Background initialization failed",{},e),e}}startSessionProcessor(e,r){if(!e)return;let n=e.sessionDbId;E.info("SYSTEM",`Starting generator (${r})`,{sessionId:n}),e.generatorPromise=this.sdkAgent.startSession(e,this).catch(i=>{E.error("SDK","Session generator failed",{sessionId:e.sessionDbId,project:e.project},i)}).finally(()=>{e.generatorPromise=null,this.broadcastProcessingStatus()})}async processPendingQueues(e=10){let{PendingMessageStore:r}=await Promise.resolve().then(()=>(xo(),tc)),n=new r(this.dbManager.getSessionStore().db,3),i=n.getSessionsWithPendingMessages(),a={totalPendingSessions:i.length,sessionsStarted:0,sessionsSkipped:0,startedSessionIds:[]};if(i.length===0)return a;E.info("SYSTEM",`Processing up to ${e} of ${i.length} pending session queues`);for(let o of i){if(a.sessionsStarted>=e)break;try{if(this.sessionManager.getSession(o)?.generatorPromise){a.sessionsSkipped++;continue}let c=this.sessionManager.initializeSession(o);E.info("SYSTEM",`Starting processor for session ${o}`,{project:c.project,pendingCount:n.getPendingCount(o)}),this.startSessionProcessor(c,"startup-recovery"),a.sessionsStarted++,a.startedSessionIds.push(o),await new Promise(u=>setTimeout(u,100))}catch(s){E.error("SYSTEM",`Failed to process session ${o}`,{},s),a.sessionsSkipped++}}return a}async shutdown(){this.stopOrphanReaper&&(this.stopOrphanReaper(),this.stopOrphanReaper=null),await fC({server:this.server.getHttpServer(),sessionManager:this.sessionManager,mcpClient:this.mcpClient,dbManager:this.dbManager})}broadcastProcessingStatus(){let e=this.sessionManager.isAnySessionProcessing(),r=this.sessionManager.getTotalActiveWork(),n=this.sessionManager.getActiveSessionCount();E.info("WORKER","Broadcasting processing status",{isProcessing:e,queueDepth:r,activeSessions:n}),this.sseBroadcaster.broadcast({type:"processing_status",isProcessing:e,queueDepth:r})}};async function the(){let t=process.argv[2],e=It();function r(n,i){let a=fq(n,i);console.log(JSON.stringify(a)),process.exit(0)}switch(t){case"start":{if(await El(e,1e3)){let o=await pC(e);o.matches?(E.info("SYSTEM","Worker already running and healthy"),r("ready")):(E.info("SYSTEM","Worker version mismatch detected - auto-restarting",{pluginVersion:o.pluginVersion,workerVersion:o.workerVersion}),await pm(e),await dm(e,io(15e3))||(E.error("SYSTEM","Port did not free up after shutdown for version mismatch restart",{port:e}),r("error","Port did not free after version mismatch restart")),Ui())}await lm(e)&&(E.info("SYSTEM","Port in use, waiting for worker to become healthy"),await El(e,io(15e3))&&(E.info("SYSTEM","Worker is now healthy"),r("ready")),E.error("SYSTEM","Port in use but worker not responding to health checks"),r("error","Port in use but worker not responding")),E.info("SYSTEM","Starting worker daemon"),YS(__filename,e)===void 0&&(E.error("SYSTEM","Failed to spawn worker daemon"),r("error","Failed to spawn worker daemon")),await El(e,io(3e4))||(Ui(),E.error("SYSTEM","Worker failed to start (health check timeout)"),r("error","Worker failed to start (health check timeout)")),E.info("SYSTEM","Worker started successfully"),r("ready")}case"stop":await pm(e),await dm(e,io(15e3))||E.warn("SYSTEM","Port did not free up after shutdown",{port:e}),Ui(),E.info("SYSTEM","Worker stopped successfully"),process.exit(0);case"restart":E.info("SYSTEM","Restarting worker"),await pm(e),await dm(e,io(15e3))||(E.error("SYSTEM","Port did not free up after shutdown, aborting restart",{port:e}),process.exit(0)),Ui(),YS(__filename,e)===void 0&&(E.error("SYSTEM","Failed to spawn worker daemon during restart"),process.exit(0)),await El(e,io(3e4))||(Ui(),E.error("SYSTEM","Worker failed to restart"),process.exit(0)),E.info("SYSTEM","Worker restarted successfully"),process.exit(0);case"status":{let n=await lm(e),i=iC();n&&i?(console.log("Worker is running"),console.log(` PID: ${i.pid}`),console.log(` Port: ${i.port}`),console.log(` Started: ${i.startedAt}`)):console.log("Worker is not running"),process.exit(0)}case"cursor":{let n=process.argv[3],i=await q4(n,process.argv.slice(4));process.exit(i)}case"hook":{let n=process.argv[3],i=process.argv[4];(!n||!i)&&(console.error("Usage: claude-mem hook "),console.error("Platforms: claude-code, cursor, raw"),console.error("Events: context, session-init, observation, summarize, user-message"),process.exit(1));let{hookCommand:a}=await Promise.resolve().then(()=>(dq(),lq));await a(n,i);break}default:new Vg().start().catch(i=>{E.failure("SYSTEM","Worker failed to start",{},i),Ui(),process.exit(0)})}}var rhe=typeof require<"u"&&typeof module<"u"?require.main===module||!module.parent:ihe.url===`file://${process.argv[1]}`||process.argv[1]?.endsWith("worker-service");rhe&&the();0&&(module.exports={WorkerService,buildStatusOutput}); +`);r.json({logs:u,path:n,exists:!0,totalLines:s.length,returnedLines:s.length-c})});handleClearLogs=this.wrapHandler((e,r)=>{let n=this.getLogFilePath();if(!(0,No.existsSync)(n)){r.json({success:!0,message:"Log file does not exist",path:n});return}(0,No.writeFileSync)(n,"","utf-8"),E.info("SYSTEM","Log file cleared via UI",{path:n}),r.json({success:!0,message:"Log file cleared",path:n})})};var ihe={},ehe="9.0.11";function fq(t,e){return{continue:!0,suppressOutput:!0,status:t,...e&&{message:e}}}var Vg=class{server;startTime=Date.now();mcpClient;mcpReady=!1;initializationCompleteFlag=!1;isShuttingDown=!1;dbManager;sessionManager;sseBroadcaster;sdkAgent;geminiAgent;openRouterAgent;paginationHelper;settingsManager;sessionEventBroadcaster;searchRoutes=null;initializationComplete;resolveInitialization;stopOrphanReaper=null;constructor(){this.initializationComplete=new Promise(e=>{this.resolveInitialization=e}),this.dbManager=new Th,this.sessionManager=new Rh(this.dbManager),this.sseBroadcaster=new Ch,this.sdkAgent=new gg(this.dbManager,this.sessionManager),this.geminiAgent=new vg(this.dbManager,this.sessionManager),this.openRouterAgent=new bg(this.dbManager,this.sessionManager),this.paginationHelper=new xg(this.dbManager),this.settingsManager=new Sg(this.dbManager),this.sessionEventBroadcaster=new kg(this.sseBroadcaster,this),this.sessionManager.setOnSessionDeleted(()=>{this.broadcastProcessingStatus()}),this.mcpClient=new ws({name:"worker-search-proxy",version:ehe},{capabilities:{}}),this.server=new wh({getInitializationComplete:()=>this.initializationCompleteFlag,getMcpReady:()=>this.mcpReady,onShutdown:()=>this.shutdown(),onRestart:()=>this.shutdown()}),this.registerRoutes(),this.registerSignalHandlers()}registerSignalHandlers(){let e={value:this.isShuttingDown},r=uC(()=>this.shutdown(),e);process.on("SIGTERM",()=>{this.isShuttingDown=e.value,r("SIGTERM")}),process.on("SIGINT",()=>{this.isShuttingDown=e.value,r("SIGINT")})}registerRoutes(){this.server.registerRoutes(new Ig(this.sseBroadcaster,this.dbManager,this.sessionManager)),this.server.registerRoutes(new Rg(this.sessionManager,this.dbManager,this.sdkAgent,this.geminiAgent,this.openRouterAgent,this.sessionEventBroadcaster,this)),this.server.registerRoutes(new Cg(this.paginationHelper,this.dbManager,this.sessionManager,this.sseBroadcaster,this,this.startTime)),this.server.registerRoutes(new Fg(this.settingsManager)),this.server.registerRoutes(new Hg),this.server.app.get("/api/context/inject",async(e,r,n)=>{let a=new Promise((o,s)=>setTimeout(()=>s(new Error("Initialization timeout")),3e5));if(await Promise.race([this.initializationComplete,a]),!this.searchRoutes){r.status(503).json({error:"Search routes not initialized"});return}n()})}async start(){let e=It(),r=cm();await this.server.listen(e,r),nC({pid:process.pid,port:e,startedAt:new Date().toISOString()}),E.info("SYSTEM","Worker started",{host:r,port:e,pid:process.pid}),this.initializeBackground().catch(n=>{E.error("SYSTEM","Background initialization failed",{},n)})}async initializeBackground(){try{await cC();let{ModeManager:e}=await Promise.resolve().then(()=>(Mr(),Q4)),{SettingsDefaultsManager:r}=await Promise.resolve().then(()=>(cn(),WR)),{USER_SETTINGS_PATH:n}=await Promise.resolve().then(()=>(ln(),k4)),a=r.loadFromFile(n).CLAUDE_MEM_MODE;e.getInstance().loadMode(a),E.info("SYSTEM",`Mode loaded: ${a}`),await this.dbManager.initialize();let{PendingMessageStore:o}=await Promise.resolve().then(()=>(xo(),tc)),s=new o(this.dbManager.getSessionStore().db,3),c=300*1e3,u=s.resetStuckMessages(c);u>0&&E.info("SYSTEM",`Recovered ${u} stuck messages from previous session`,{thresholdMinutes:5});let l=new $g,d=new Eg,p=new wg(this.dbManager.getSessionSearch(),this.dbManager.getSessionStore(),this.dbManager.getChromaSync(),l,d);this.searchRoutes=new Lg(p),this.server.registerRoutes(this.searchRoutes),E.info("WORKER","SearchManager initialized and search routes registered");let f=pq.default.join(__dirname,"mcp-server.cjs"),g=new ks({command:"node",args:[f],env:process.env}),_=3e5,h=this.mcpClient.connect(g),m=new Promise((y,v)=>setTimeout(()=>v(new Error("MCP connection timeout after 5 minutes")),_));await Promise.race([h,m]),this.mcpReady=!0,E.success("WORKER","Connected to MCP server"),this.initializationCompleteFlag=!0,this.resolveInitialization(),E.info("SYSTEM","Background initialization complete"),this.stopOrphanReaper=X4(()=>{let y=new Set;for(let[v]of this.sessionManager.sessions)y.add(v);return y}),E.info("SYSTEM","Started orphan reaper (runs every 5 minutes)"),this.processPendingQueues(50).then(y=>{y.sessionsStarted>0&&E.info("SYSTEM",`Auto-recovered ${y.sessionsStarted} sessions with pending work`,{totalPending:y.totalPendingSessions,started:y.sessionsStarted,sessionIds:y.startedSessionIds})}).catch(y=>{E.error("SYSTEM","Auto-recovery of pending queues failed",{},y)})}catch(e){throw E.error("SYSTEM","Background initialization failed",{},e),e}}startSessionProcessor(e,r){if(!e)return;let n=e.sessionDbId;E.info("SYSTEM",`Starting generator (${r})`,{sessionId:n}),e.generatorPromise=this.sdkAgent.startSession(e,this).catch(i=>{E.error("SDK","Session generator failed",{sessionId:e.sessionDbId,project:e.project},i)}).finally(()=>{e.generatorPromise=null,this.broadcastProcessingStatus()})}async processPendingQueues(e=10){let{PendingMessageStore:r}=await Promise.resolve().then(()=>(xo(),tc)),n=new r(this.dbManager.getSessionStore().db,3),i=n.getSessionsWithPendingMessages(),a={totalPendingSessions:i.length,sessionsStarted:0,sessionsSkipped:0,startedSessionIds:[]};if(i.length===0)return a;E.info("SYSTEM",`Processing up to ${e} of ${i.length} pending session queues`);for(let o of i){if(a.sessionsStarted>=e)break;try{if(this.sessionManager.getSession(o)?.generatorPromise){a.sessionsSkipped++;continue}let c=this.sessionManager.initializeSession(o);E.info("SYSTEM",`Starting processor for session ${o}`,{project:c.project,pendingCount:n.getPendingCount(o)}),this.startSessionProcessor(c,"startup-recovery"),a.sessionsStarted++,a.startedSessionIds.push(o),await new Promise(u=>setTimeout(u,100))}catch(s){E.error("SYSTEM",`Failed to process session ${o}`,{},s),a.sessionsSkipped++}}return a}async shutdown(){this.stopOrphanReaper&&(this.stopOrphanReaper(),this.stopOrphanReaper=null),await fC({server:this.server.getHttpServer(),sessionManager:this.sessionManager,mcpClient:this.mcpClient,dbManager:this.dbManager})}broadcastProcessingStatus(){let e=this.sessionManager.isAnySessionProcessing(),r=this.sessionManager.getTotalActiveWork(),n=this.sessionManager.getActiveSessionCount();E.info("WORKER","Broadcasting processing status",{isProcessing:e,queueDepth:r,activeSessions:n}),this.sseBroadcaster.broadcast({type:"processing_status",isProcessing:e,queueDepth:r})}};async function the(){let t=process.argv[2],e=It();function r(n,i){let a=fq(n,i);console.log(JSON.stringify(a)),process.exit(0)}switch(t){case"start":{if(await El(e,1e3)){let o=await pC(e);o.matches?(E.info("SYSTEM","Worker already running and healthy"),r("ready")):(E.info("SYSTEM","Worker version mismatch detected - auto-restarting",{pluginVersion:o.pluginVersion,workerVersion:o.workerVersion}),await pm(e),await dm(e,io(15e3))||(E.error("SYSTEM","Port did not free up after shutdown for version mismatch restart",{port:e}),r("error","Port did not free after version mismatch restart")),Ui())}await lm(e)&&(E.info("SYSTEM","Port in use, waiting for worker to become healthy"),await El(e,io(15e3))&&(E.info("SYSTEM","Worker is now healthy"),r("ready")),E.error("SYSTEM","Port in use but worker not responding to health checks"),r("error","Port in use but worker not responding")),E.info("SYSTEM","Starting worker daemon"),YS(__filename,e)===void 0&&(E.error("SYSTEM","Failed to spawn worker daemon"),r("error","Failed to spawn worker daemon")),await El(e,io(3e4))||(Ui(),E.error("SYSTEM","Worker failed to start (health check timeout)"),r("error","Worker failed to start (health check timeout)")),E.info("SYSTEM","Worker started successfully"),r("ready")}case"stop":await pm(e),await dm(e,io(15e3))||E.warn("SYSTEM","Port did not free up after shutdown",{port:e}),Ui(),E.info("SYSTEM","Worker stopped successfully"),process.exit(0);case"restart":E.info("SYSTEM","Restarting worker"),await pm(e),await dm(e,io(15e3))||(E.error("SYSTEM","Port did not free up after shutdown, aborting restart",{port:e}),process.exit(0)),Ui(),YS(__filename,e)===void 0&&(E.error("SYSTEM","Failed to spawn worker daemon during restart"),process.exit(0)),await El(e,io(3e4))||(Ui(),E.error("SYSTEM","Worker failed to restart"),process.exit(0)),E.info("SYSTEM","Worker restarted successfully"),process.exit(0);case"status":{let n=await lm(e),i=iC();n&&i?(console.log("Worker is running"),console.log(` PID: ${i.pid}`),console.log(` Port: ${i.port}`),console.log(` Started: ${i.startedAt}`)):console.log("Worker is not running"),process.exit(0)}case"cursor":{let n=process.argv[3],i=await q4(n,process.argv.slice(4));process.exit(i)}case"hook":{let n=process.argv[3],i=process.argv[4];(!n||!i)&&(console.error("Usage: claude-mem hook "),console.error("Platforms: claude-code, cursor, raw"),console.error("Events: context, session-init, observation, summarize, user-message"),process.exit(1));let{hookCommand:a}=await Promise.resolve().then(()=>(dq(),lq));await a(n,i);break}default:new Vg().start().catch(i=>{E.failure("SYSTEM","Worker failed to start",{},i),Ui(),process.exit(0)})}}var rhe=typeof require<"u"&&typeof module<"u"?require.main===module||!module.parent:ihe.url===`file://${process.argv[1]}`||process.argv[1]?.endsWith("worker-service");rhe&&the();0&&(module.exports={WorkerService,buildStatusOutput}); /*! Bundled license information: depd/index.js: diff --git a/src/services/worker/ProcessRegistry.ts b/src/services/worker/ProcessRegistry.ts index 47c41a0a..56a70220 100644 --- a/src/services/worker/ProcessRegistry.ts +++ b/src/services/worker/ProcessRegistry.ts @@ -19,7 +19,6 @@ import { spawn, exec, ChildProcess } from 'child_process'; import { promisify } from 'util'; import { logger } from '../../utils/logger.js'; -import { OBSERVER_CONFIG_DIR, ensureDir } from '../../shared/paths.js'; const execAsync = promisify(exec); @@ -189,14 +188,10 @@ export async function reapOrphanedProcesses(activeSessionIds: Set): Prom * The SDK's spawnClaudeCodeProcess option allows us to intercept subprocess * creation and capture the PID before the SDK hides it. * - * IMPORTANT (Issue #832): We set CLAUDE_CONFIG_DIR to isolate observer sessions. - * This prevents observer sessions from appearing in `claude --resume` list, - * which was causing 34%+ of resume entries to be internal plugin sessions. + * NOTE: Session isolation is handled via the `cwd` option in SDKAgent.ts, + * NOT via CLAUDE_CONFIG_DIR (which breaks authentication). */ export function createPidCapturingSpawn(sessionDbId: number) { - // Ensure observer config directory exists - ensureDir(OBSERVER_CONFIG_DIR); - return (spawnOptions: { command: string; args: string[]; @@ -204,15 +199,9 @@ export function createPidCapturingSpawn(sessionDbId: number) { env?: NodeJS.ProcessEnv; signal?: AbortSignal; }) => { - // Inject CLAUDE_CONFIG_DIR to isolate observer sessions (Issue #832) - const isolatedEnv = { - ...spawnOptions.env, - CLAUDE_CONFIG_DIR: OBSERVER_CONFIG_DIR - }; - const child = spawn(spawnOptions.command, spawnOptions.args, { cwd: spawnOptions.cwd, - env: isolatedEnv, + env: spawnOptions.env, stdio: ['pipe', 'pipe', 'pipe'], signal: spawnOptions.signal, // CRITICAL: Pass signal for AbortController integration windowsHide: true diff --git a/src/services/worker/SDKAgent.ts b/src/services/worker/SDKAgent.ts index 78b7f18b..0ae35e63 100644 --- a/src/services/worker/SDKAgent.ts +++ b/src/services/worker/SDKAgent.ts @@ -16,7 +16,7 @@ import { SessionManager } from './SessionManager.js'; import { logger } from '../../utils/logger.js'; import { buildInitPrompt, buildObservationPrompt, buildSummaryPrompt, buildContinuationPrompt } from '../../sdk/prompts.js'; import { SettingsDefaultsManager } from '../../shared/SettingsDefaultsManager.js'; -import { USER_SETTINGS_PATH } from '../../shared/paths.js'; +import { USER_SETTINGS_PATH, OBSERVER_SESSIONS_DIR, ensureDir } from '../../shared/paths.js'; import type { ActiveSession, SDKUserMessage } from '../worker-types.js'; import { ModeManager } from '../domain/ModeManager.js'; import { processAgentResponse, type WorkerRef } from './agents/index.js'; @@ -101,10 +101,15 @@ export class SDKAgent { // Run Agent SDK query loop // Only resume if we have a captured memory session ID // Use custom spawn to capture PIDs for zombie process cleanup (Issue #737) + // Use dedicated cwd to isolate observer sessions from user's `claude --resume` list + ensureDir(OBSERVER_SESSIONS_DIR); const queryResult = query({ prompt: messageGenerator, options: { model: modelId, + // Isolate observer sessions - they'll appear under project "observer-sessions" + // instead of polluting user's actual project resume lists + cwd: OBSERVER_SESSIONS_DIR, // Only resume if BOTH: (1) we have a memorySessionId AND (2) this isn't the first prompt // On worker restart, memorySessionId may exist from a previous SDK session but we // need to start fresh since the SDK context was lost diff --git a/src/shared/paths.ts b/src/shared/paths.ts index 75a417cd..ca7e7aba 100644 --- a/src/shared/paths.ts +++ b/src/shared/paths.ts @@ -38,9 +38,9 @@ export const USER_SETTINGS_PATH = join(DATA_DIR, 'settings.json'); export const DB_PATH = join(DATA_DIR, 'claude-mem.db'); export const VECTOR_DB_DIR = join(DATA_DIR, 'vector-db'); -// Isolated config directory for observer sessions (Issue #832) -// This prevents observer sessions from appearing in `claude --resume` list -export const OBSERVER_CONFIG_DIR = join(DATA_DIR, 'observer-config'); +// Observer sessions directory - used as cwd for SDK queries +// Sessions here won't appear in user's `claude --resume` for their actual projects +export const OBSERVER_SESSIONS_DIR = join(DATA_DIR, 'observer-sessions'); // Claude integration paths export const CLAUDE_SETTINGS_PATH = join(CLAUDE_CONFIG_DIR, 'settings.json');