@gabrywu/knowledge-bank 0.1.2-alpha.175 → 0.1.2-alpha.181

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import{Command as e}from"commander";import t,{dirname as n,join as r}from"path";import s from"os";import o,{readFileSync as a,existsSync as i,mkdirSync as c,appendFileSync as d,writeFileSync as u}from"fs";import{fileURLToPath as l}from"url";import{exec as p}from"child_process";import h from"better-sqlite3";import m from"simple-git";import{cwd as f}from"process";import{ZodOptional as g,z as y}from"zod";import _ from"node:process";import v from"express";import w from"express-ejs-layouts";import b from"markdown-it";const k=["personal","project","organization"],E=["developer","architect","reviewer","ai"],$=["code_pattern","tool_usage","architecture","config","pitfall","api_usage","exploration"],S=["draft","suggested","verified"],T=["session_start","session_end","tool_use","user_prompt","pre_compact","notification","permission_request","stop","subagent_stop"],O={knowledge_item:`\n CREATE TABLE IF NOT EXISTS knowledge_item (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n\n -- Basic information\n title TEXT NOT NULL,\n summary TEXT NOT NULL,\n content TEXT NOT NULL,\n\n -- Classification dimensions\n scope TEXT NOT NULL CHECK(scope IN (${k.map(e=>`'${e}'`).join(", ")})),\n source_type TEXT NOT NULL CHECK(source_type IN (${E.map(e=>`'${e}'`).join(", ")})),\n knowledge_type TEXT NOT NULL CHECK(knowledge_type IN (${$.map(e=>`'${e}'`).join(", ")})),\n status TEXT NOT NULL DEFAULT 'draft' CHECK(status IN (${S.map(e=>`'${e}'`).join(", ")})),\n\n -- Association information\n repository_id INTEGER,\n session_id TEXT NOT NULL,\n\n -- Source tracking\n source_file TEXT,\n commit_hash TEXT,\n contributor TEXT,\n\n -- Timestamps\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n\n FOREIGN KEY (repository_id) REFERENCES repository(id)\n )\n `,repository:"\n CREATE TABLE IF NOT EXISTS repository (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n\n name TEXT NOT NULL,\n remote_url TEXT UNIQUE NOT NULL,\n local_path TEXT,\n\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL\n )\n ",session:"\n CREATE TABLE IF NOT EXISTS session (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n\n session_id TEXT UNIQUE NOT NULL,\n repository_id INTEGER,\n\n -- Session basic information\n working_directory TEXT NOT NULL,\n branch TEXT,\n username TEXT,\n\n -- Environment information (stored as JSON)\n env TEXT,\n\n -- Configuration information (stored as JSON)\n config TEXT,\n\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n\n FOREIGN KEY (repository_id) REFERENCES repository(id)\n )\n ",hook_event:"\n CREATE TABLE IF NOT EXISTS hook_event (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n\n session_id TEXT NOT NULL,\n\n -- Hook information\n name TEXT NOT NULL,\n input TEXT NOT NULL,\n output TEXT,\n\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n\n FOREIGN KEY (session_id) REFERENCES session(session_id)\n )\n ",sync_status:`\n CREATE TABLE IF NOT EXISTS sync_status (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n\n repository_id INTEGER,\n\n last_sync_at INTEGER,\n last_pull_at INTEGER,\n last_push_at INTEGER,\n\n remote_url TEXT,\n sync_protocol TEXT CHECK(sync_protocol IN (${["http","ftp","sftp"].map(e=>`'${e}'`).join(", ")})),\n\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n\n FOREIGN KEY (repository_id) REFERENCES repository(id)\n )\n `,knowledge_item_fts:"\n CREATE VIRTUAL TABLE IF NOT EXISTS knowledge_item_fts USING fts5(\n title, summary, content,\n content='knowledge_item',\n content_rowid='id',\n tokenize='trigram'\n )\n "},x={knowledge_item_fts_insert:"\n CREATE TRIGGER IF NOT EXISTS knowledge_item_fts_insert AFTER INSERT ON knowledge_item BEGIN\n INSERT INTO knowledge_item_fts(rowid, title, summary, content)\n VALUES (new.id, new.title, new.summary, new.content);\n END\n ",knowledge_item_fts_delete:"\n CREATE TRIGGER IF NOT EXISTS knowledge_item_fts_delete AFTER DELETE ON knowledge_item BEGIN\n INSERT INTO knowledge_item_fts(knowledge_item_fts, rowid, title, summary, content)\n VALUES('delete', old.id, old.title, old.summary, old.content);\n END\n ",knowledge_item_fts_update:"\n CREATE TRIGGER IF NOT EXISTS knowledge_item_fts_update AFTER UPDATE ON knowledge_item BEGIN\n INSERT INTO knowledge_item_fts(knowledge_item_fts, rowid, title, summary, content)\n VALUES('delete', old.id, old.title, old.summary, old.content);\n INSERT INTO knowledge_item_fts(rowid, title, summary, content)\n VALUES (new.id, new.title, new.summary, new.content);\n END\n "},N={idx_knowledge_scope:"CREATE INDEX IF NOT EXISTS idx_knowledge_scope ON knowledge_item(scope)",idx_knowledge_type:"CREATE INDEX IF NOT EXISTS idx_knowledge_type ON knowledge_item(knowledge_type)",idx_knowledge_status:"CREATE INDEX IF NOT EXISTS idx_knowledge_status ON knowledge_item(status)",idx_knowledge_repo:"CREATE INDEX IF NOT EXISTS idx_knowledge_repo ON knowledge_item(repository_id)",idx_knowledge_session:"CREATE INDEX IF NOT EXISTS idx_knowledge_session ON knowledge_item(session_id)",idx_session_repo:"CREATE INDEX IF NOT EXISTS idx_session_repo ON session(repository_id)",idx_session_id:"CREATE INDEX IF NOT EXISTS idx_session_id ON session(session_id)",idx_hook_event_session:"CREATE INDEX IF NOT EXISTS idx_hook_event_session ON hook_event(session_id)",idx_hook_event_type:"CREATE INDEX IF NOT EXISTS idx_hook_event_type ON hook_event(name)",idx_sync_repo:"CREATE INDEX IF NOT EXISTS idx_sync_repo ON sync_status(repository_id)"};function I(e){Object.values(O).forEach(t=>{e.prepare(t).run()}),Object.values(N).forEach(t=>{e.prepare(t).run()}),Object.values(x).forEach(t=>{e.prepare(t).run()});const t=e.prepare("SELECT COUNT(*) as count FROM knowledge_item_fts").get(),n=e.prepare("SELECT COUNT(*) as count FROM knowledge_item").get();n.count>0&&0===t.count&&(console.log("Populating FTS index from existing data..."),e.prepare("\n INSERT INTO knowledge_item_fts(rowid, title, summary, content)\n SELECT id, title, summary, content FROM knowledge_item\n ").run(),console.log(`FTS index populated with ${n.count} items`))}const R={logging:{level:"DEBUG"},db:{path:t.join(s.homedir(),".knowledge-bank","knowledge.db"),configs:["journal_mode = WAL","foreign_keys = ON"]},tmp:t.join(s.homedir(),".knowledge-bank","tmp")};let P=null;function C(){if(null===P){const e=process.env.KNOWLEDGE_CONF_DIR||t.join(s.homedir(),".knowledge-bank"),n=t.join(e,"config.json");P={...R,...o.existsSync(n)?JSON.parse(o.readFileSync(n,"utf-8")):{}}}return P}const j=C(),z={DEBUG:"DEBUG",INFO:"INFO",WARN:"WARN",ERROR:"ERROR"},A=Object.values(z);class M{constructor(e,n){this.loggerName=n;const r=j.logging.path||t.join(s.homedir(),".knowledge-bank","logs");o.mkdirSync(r,{recursive:!0}),this.loggerFile=t.join(r,`${e}.log`),this.logLevel=j.logging.level.toUpperCase()||z.INFO}formatMessage(e,t,n=null){const r=`${(new Date).toISOString().replace("T","-").split(".")[0]} ${this.loggerName} ${e}: ${t}`;return null===n?r:`${r} - ${JSON.stringify(n)}`}isLogLevelEnabled(e){const t=A.indexOf(this.logLevel);return A.indexOf(e)>=t}writeMessage(e,t,n){if(this.isLogLevelEnabled(e)){const r=this.formatMessage(e,t,n);o.appendFileSync(this.loggerFile,`${r}\n`,"utf8")}}logInfo(e,t=null){this.writeMessage(z.INFO,e,t)}logError(e,t=null){if(t instanceof Error){const n={message:t.message,stack:t.stack,name:t.name,...t.cause&&{cause:t.cause},...Object.getOwnPropertyNames(t).reduce((e,n)=>(["message","stack","name"].includes(n)||(e[n]=t[n]),e),{})};this.writeMessage(z.ERROR,e,n)}else this.writeMessage(z.ERROR,e,t)}logWarn(e,t=null){this.writeMessage(z.WARN,e,t)}logDebug(e,t=null){this.writeMessage(z.DEBUG,e,t)}}function D(e,t){return new M(e,t)}const L=D("common","common"),Z=l(import.meta.url),F=t.dirname(Z),U=t.join(F,"..","claude-marketplace"),q=function(){const e=t.join(F,"package.json"),n=t.join(".","package.json");return o.existsSync(e)?JSON.parse(a(e,"utf8")):JSON.parse(a(n,"utf8"))}();function H(e){return o.existsSync(e)?JSON.parse(o.readFileSync(e,"utf-8")):{}}const V=t.join(s.homedir(),".claude","settings.local.json");function J(){const e=function(){const e=process.env.CLAUDE_PROJECT_DIR||process.cwd(),n=t.join(e,".claude/settings.local.json"),r=t.join(e,".claude/settings.json"),s=H(n),o=H(r);return{...H(V),...o,...s}}(),n=!1!==(e?.knowledge||{}).enabled;return n||L.logWarn("Knowledge collection is disabled in settings."),{enabled:n}}function K(){return new Promise((e,t)=>{p("claude plugin marketplace list --json",(n,r,s)=>{if(n)t(n);else{s&&console.error(s);try{const t=r.trim()?JSON.parse(r):[];e(t)}catch(e){t(e)}}})})}const B=C();class W{constructor(){this.dbPath=B.db.path,this.db=null,this.transactionDepth=0}initialize(){const e=n(this.dbPath);return i(e)||c(e,{recursive:!0}),this.db=new h(this.dbPath),B.db.configs.forEach(e=>{this.db.pragma(e)}),this}getConnection(){return this.db||this.initialize(),this.db}beginTransaction(){return 0===this.transactionDepth&&this.getConnection().prepare("BEGIN").run(),this.transactionDepth++,this}commit(){return this.transactionDepth--,0===this.transactionDepth&&this.getConnection().prepare("COMMIT").run(),this}rollback(){return this.transactionDepth--,0===this.transactionDepth&&this.getConnection().prepare("ROLLBACK").run(),this}transaction(e){this.beginTransaction();try{const t=e(this.getConnection());return this.commit(),t}catch(e){throw this.rollback(),e}}close(){return this.db&&(this.db.close(),this.db=null),this}exists(){return i(this.dbPath)}getPath(){return this.dbPath}}let G=null;function X(){return G||(G=new W),G}const Y=D("knowledge-repository","knowledge-repository");class Q{constructor(e){this.database=e,this.db=e.getConnection()}create(e){const t=Date.now(),n=this.db.prepare("\n INSERT INTO knowledge_item (\n title, summary, content,\n scope, source_type, knowledge_type, status,\n repository_id, session_id,\n source_file, commit_hash, contributor,\n created_at, updated_at\n ) VALUES (\n @title, @summary, @content,\n @scope, @source_type, @knowledge_type, @status,\n @repository_id, @session_id,\n @source_file, @commit_hash, @contributor,\n @created_at, @updated_at\n )\n ").run({...e,status:e.status||S.DRAFT,created_at:t,updated_at:t});return this.findById(n.lastInsertRowid)}findById(e){return this.db.prepare("SELECT * FROM knowledge_item WHERE id = ?").get(e)}findByRepository(e,t=null){return t?this.db.prepare("SELECT * FROM knowledge_item WHERE repository_id = ? AND scope = ? ORDER BY updated_at DESC").all(e,t):this.db.prepare("SELECT * FROM knowledge_item WHERE repository_id = ? ORDER BY updated_at DESC").all(e)}findByScope(e){return this.db.prepare("SELECT * FROM knowledge_item WHERE scope = ? ORDER BY updated_at DESC").all(e)}findByStatus(e){return this.db.prepare("SELECT * FROM knowledge_item WHERE status = ? ORDER BY updated_at DESC").all(e)}findByKnowledgeType(e){return this.db.prepare("SELECT * FROM knowledge_item WHERE knowledge_type = ? ORDER BY updated_at DESC").all(e)}findBySession(e){return this.db.prepare("SELECT * FROM knowledge_item WHERE session_id = ?").all(e)}findRelevant(e,t=5){return this.db.prepare("\n SELECT * FROM knowledge_item\n WHERE repository_id = ? OR scope = 'organization'\n ORDER BY\n CASE status\n WHEN 'verified' THEN 3\n WHEN 'suggested' THEN 2\n WHEN 'draft' THEN 1\n END DESC,\n updated_at DESC\n LIMIT ?\n ").all(e,t)}update(e,t){const n=Date.now(),r=Object.keys(t).map(e=>`${e} = @${e}`).join(", ");return this.db.prepare(`\n UPDATE knowledge_item\n SET ${r}, updated_at = @updated_at\n WHERE id = @id\n `).run({...t,id:e,updated_at:n}),this.findById(e)}updateStatus(e,t){return this.update(e,{status:t})}delete(e){return this.db.prepare("DELETE FROM knowledge_item WHERE id = ?").run(e)}count(e={}){let t="SELECT COUNT(*) as count FROM knowledge_item";const n=[],r=[];return e.scope&&(n.push("scope = ?"),r.push(e.scope)),e.status&&(n.push("status = ?"),r.push(e.status)),e.knowledge_type&&(n.push("knowledge_type = ?"),r.push(e.knowledge_type)),e.repository_id&&(n.push("repository_id = ?"),r.push(e.repository_id)),n.length>0&&(t+=` WHERE ${n.join(" AND ")}`),this.db.prepare(t).get(...r).count}findAll(e=100,t=0){return this.db.prepare("SELECT * FROM knowledge_item ORDER BY updated_at DESC LIMIT ? OFFSET ?").all(e,t)}search(e,t=10){const n=Array.isArray(e)?e.map(e=>`"${e}"`).join(" OR "):`"${e}"`;return Y.logDebug("Searching knowledge items with query: ",n),this.db.prepare("\n SELECT ki.*\n FROM knowledge_item ki\n JOIN knowledge_item_fts fts ON fts.rowid = ki.id\n WHERE knowledge_item_fts MATCH ?\n ORDER BY rank\n LIMIT ?\n ").all(n,t)}}class ee{constructor(e){this.database=e,this.db=e.getConnection()}create(e){const t=Date.now(),n=this.db.prepare("\n INSERT INTO repository (\n name, remote_url, local_path,\n created_at, updated_at\n ) VALUES (\n @name, @remote_url, @local_path,\n @created_at, @updated_at\n )\n ").run({...e,created_at:t,updated_at:t});return this.findById(n.lastInsertRowid)}findById(e){return this.db.prepare("SELECT * FROM repository WHERE id = ?").get(e)}findByRemoteUrl(e){return this.db.prepare("SELECT * FROM repository WHERE remote_url = ?").get(e)}findByPath(e){return this.db.prepare("SELECT * FROM repository WHERE local_path = ?").get(e)}findByName(e){return this.db.prepare("SELECT * FROM repository WHERE name = ?").get(e)}getOrCreate(e,t,n=null){let r=this.findByRemoteUrl(e);return r?n&&r.local_path!==n&&(r=this.update(r.id,{local_path:n})):r=this.create({name:t,remote_url:e,local_path:n}),r}update(e,t){const n=Date.now(),r=Object.keys(t).map(e=>`${e} = @${e}`).join(", ");return this.db.prepare(`\n UPDATE repository\n SET ${r}, updated_at = @updated_at\n WHERE id = @id\n `).run({...t,id:e,updated_at:n}),this.findById(e)}delete(e){return this.db.prepare("DELETE FROM repository WHERE id = ?").run(e)}findAll(){return this.db.prepare("SELECT * FROM repository ORDER BY updated_at DESC").all()}count(){return this.db.prepare("SELECT COUNT(*) as count FROM repository").get().count}}class te{constructor(e){this.database=e,this.db=e.getConnection()}create(e){const t=Date.now(),n=this.db.prepare("\n INSERT INTO sync_status (\n repository_id,\n last_sync_at, last_pull_at, last_push_at,\n remote_url, sync_protocol,\n created_at, updated_at\n ) VALUES (\n @repository_id,\n @last_sync_at, @last_pull_at, @last_push_at,\n @remote_url, @sync_protocol,\n @created_at, @updated_at\n )\n ").run({repository_id:e.repository_id||null,last_sync_at:e.last_sync_at||null,last_pull_at:e.last_pull_at||null,last_push_at:e.last_push_at||null,remote_url:e.remote_url||null,sync_protocol:e.sync_protocol||null,created_at:t,updated_at:t});return this.findById(n.lastInsertRowid)}findById(e){return this.db.prepare("SELECT * FROM sync_status WHERE id = ?").get(e)}findByRepository(e){return this.db.prepare("SELECT * FROM sync_status WHERE repository_id = ?").get(e)}findGlobal(){return this.db.prepare("SELECT * FROM sync_status WHERE repository_id IS NULL").get()}getOrCreate(e,t={}){let n=e?this.findByRepository(e):this.findGlobal();return n||(n=this.create({repository_id:e,...t})),n}update(e,t){const n=Date.now(),r=Object.keys(t).map(e=>`${e} = @${e}`).join(", ");return this.db.prepare(`\n UPDATE sync_status\n SET ${r}, updated_at = @updated_at\n WHERE id = @id\n `).run({...t,id:e,updated_at:n}),this.findById(e)}recordPull(e){const t=this.getOrCreate(e),n=Date.now();return this.update(t.id,{last_pull_at:n,last_sync_at:n})}recordPush(e){const t=this.getOrCreate(e),n=Date.now();return this.update(t.id,{last_push_at:n,last_sync_at:n})}recordSync(e){const t=this.getOrCreate(e),n=Date.now();return this.update(t.id,{last_pull_at:n,last_push_at:n,last_sync_at:n})}updateConfig(e,t){const n=this.getOrCreate(e);return this.update(n.id,{remote_url:t.remote_url,sync_protocol:t.sync_protocol})}delete(e){return this.db.prepare("DELETE FROM sync_status WHERE id = ?").run(e)}findAll(){return this.db.prepare("SELECT * FROM sync_status ORDER BY updated_at DESC").all()}needsSync(e,t=36e5){const n=e?this.findByRepository(e):this.findGlobal();return!n||!n.last_sync_at||Date.now()-n.last_sync_at>t}getStats(){return{total:this.db.prepare("SELECT COUNT(*) as count FROM sync_status").get().count,with_remote:this.db.prepare("SELECT COUNT(*) as count FROM sync_status WHERE remote_url IS NOT NULL").get().count,recent_syncs_24h:this.db.prepare("\n SELECT COUNT(*) as count FROM sync_status\n WHERE last_sync_at > ?\n ").get(Date.now()-864e5).count}}}class ne{constructor(e){this.database=e,this.db=e.getConnection()}createSession(e){const t=this.findSessionBySessionId(e.session_id);if(t)return t;const n=Date.now(),r=e.config||C();return this.db.prepare("\n INSERT INTO session (\n session_id, repository_id, working_directory, branch, username, env, config,\n created_at, updated_at\n ) VALUES (\n @session_id, @repository_id, @working_directory, @branch, @username, @env, @config,\n @created_at, @updated_at\n )\n ").run({session_id:e.session_id,repository_id:e.repository_id||null,working_directory:e.working_directory,branch:e.branch||null,username:e.username||null,env:e.env?JSON.stringify(e.env):null,config:JSON.stringify(r),created_at:n,updated_at:n}),this.findSessionBySessionId(e.session_id)}findSessionBySessionId(e){const t=this.db.prepare("SELECT * FROM session WHERE session_id = ?").get(e);return this._parseSessionData(t)}_parseSessionData(e){return e?{...e,env:e.env?JSON.parse(e.env):null,config:e.config?JSON.parse(e.config):null}:null}updateSessionConfig(e,t){const n=Date.now();return this.db.prepare("\n UPDATE session\n SET config = ?, updated_at = ?\n WHERE session_id = ?\n ").run(JSON.stringify(t),n,e),this.findSessionBySessionId(e)}create(e){const t=Date.now(),n=this.db.prepare("\n INSERT INTO hook_event (\n session_id,\n name, input, output,\n created_at, updated_at\n ) VALUES (\n @session_id,\n @name, @input, @output,\n @created_at, @updated_at\n )\n ").run({session_id:e.session_id,name:e.name,input:"string"==typeof e.input?e.input:JSON.stringify(e.input),output:void 0===e.output||null===e.output?null:"string"==typeof e.output?e.output:JSON.stringify(e.output),created_at:t,updated_at:t});return this.findById(n.lastInsertRowid)}updateOutput(e,t){const n=Date.now(),r=this.db.prepare("\n UPDATE hook_event\n SET output = ?, updated_at = ?\n WHERE id = ?\n "),s="string"==typeof t?t:JSON.stringify(t);return r.run(s,n,e),this.findById(e)}findById(e){const t=this.db.prepare("SELECT * FROM hook_event WHERE id = ?").get(e);return t&&(t.input&&(t.input=JSON.parse(t.input)),t.output&&(t.output=JSON.parse(t.output))),t}findBySession(e){return this.db.prepare("SELECT * FROM hook_event WHERE session_id = ? ORDER BY created_at ASC").all(e).map(e=>({...e,input:e.input?JSON.parse(e.input):null,output:e.output?JSON.parse(e.output):null}))}findBySessionAndType(e,t){return this.db.prepare("SELECT * FROM hook_event WHERE session_id = ? AND name = ? ORDER BY created_at ASC").all(e,t).map(e=>({...e,input:e.input?JSON.parse(e.input):null,output:e.output?JSON.parse(e.output):null}))}findByRepository(e,t=100){return this.db.prepare("\n SELECT he.* FROM hook_event he\n JOIN session s ON he.session_id = s.session_id\n WHERE s.repository_id = ?\n ORDER BY he.created_at DESC\n LIMIT ?\n ").all(e,t).map(e=>({...e,input:e.input?JSON.parse(e.input):null,output:e.output?JSON.parse(e.output):null}))}findByHookType(e,t=100){return this.db.prepare("SELECT * FROM hook_event WHERE name = ? ORDER BY created_at DESC LIMIT ?").all(e,t).map(e=>({...e,input:e.input?JSON.parse(e.input):null,output:e.output?JSON.parse(e.output):null}))}findLatestSessionStart(e){const t=this.db.prepare("\n SELECT * FROM hook_event\n WHERE session_id = ? AND name = ?\n ORDER BY created_at DESC\n LIMIT 1\n ").get(e,T.SESSION_START);return t&&(t.input&&(t.input=JSON.parse(t.input)),t.output&&(t.output=JSON.parse(t.output))),t}hasSessionEnded(e){return this.db.prepare("\n SELECT COUNT(*) as count FROM hook_event\n WHERE session_id = ? AND name = ?\n ").get(e,T.SESSION_END).count>0}getSessionSummary(e){const t=this.findBySession(e),n=this._parseSessionData(this.db.prepare("SELECT * FROM session WHERE session_id = ?").get(e)),r={session_id:e,total_events:t.length,hook_types:{},start_time:null,end_time:null,duration:null,repository_id:n?.repository_id||null,branch:n?.branch||null,config:n?.config||null,created_at:n?.created_at||null,updated_at:n?.updated_at||null};return t.forEach(e=>{r.hook_types[e.name]=(r.hook_types[e.name]||0)+1,e.name!==T.SESSION_START||r.start_time||(r.start_time=e.created_at),e.name!==T.SESSION_END||r.end_time||(r.end_time=e.created_at)}),r.start_time&&r.end_time&&(r.duration=r.end_time-r.start_time),r}delete(e){return this.db.prepare("DELETE FROM hook_event WHERE id = ?").run(e)}deleteBySession(e){return this.db.prepare("DELETE FROM hook_event WHERE session_id = ?").run(e)}getRecentSessions(e=10){return this.db.prepare("\n SELECT DISTINCT session_id, MAX(created_at) as last_activity\n FROM hook_event\n GROUP BY session_id\n ORDER BY last_activity DESC\n LIMIT ?\n ").all(e)}count(e={}){let t="SELECT COUNT(*) as count FROM hook_event";const n=[],r=[];return e.session_id&&(n.push("session_id = ?"),r.push(e.session_id)),e.name&&(n.push("name = ?"),r.push(e.name)),n.length>0&&(t+=` WHERE ${n.join(" AND ")}`),this.db.prepare(t).get(...r).count}}class re{constructor(e=null){this.repoPath=e||f(),this.git=m(this.repoPath)}getCurrentBranch(){return this.git.branchLocal().then(e=>e.current).catch(e=>{throw new Error(`Failed to get current branch: ${e.message}`)})}getRemoteUrl(e="origin"){return this.git.getRemotes(!0).then(t=>{const n=t.find(t=>t.name===e);if(!n)throw new Error(`Remote '${e}' not found`);return n.refs.fetch||n.refs.push}).catch(e=>{throw new Error(`Failed to get remote URL: ${e.message}`)})}getMainBranch(){return this.git.branchLocal().then(e=>{const t=e.all;return t.includes("main")?"main":t.includes("master")?"master":t[0]||"main"}).catch(()=>"main")}isOnMainBranch(){return this.getCurrentBranch().then(e=>this.getMainBranch().then(t=>e===t))}getCurrentCommitHash(){return this.git.revparse(["HEAD"]).then(e=>e.trim()).catch(e=>{throw new Error(`Failed to get commit hash: ${e.message}`)})}getCommitAuthor(e="HEAD"){return this.git.show(["-s","--format=%an <%ae>",e]).then(e=>e.trim()).catch(e=>{throw new Error(`Failed to get commit author: ${e.message}`)})}isBranchMergedToMain(e){return this.getMainBranch().then(t=>this.git.branch(["--merged",t]).then(t=>t.all.map(e=>e.replace("*","").trim()).includes(e))).catch(e=>(console.error(`Failed to check merge status: ${e.message}`),!1))}getRepoRoot(){return this.git.revparse(["--show-toplevel"]).then(e=>e.trim()).catch(e=>{throw new Error(`Failed to get repo root: ${e.message}`)})}isGitRepository(){return this.git.checkIsRepo().catch(()=>!1)}getStatus(){return this.git.status().catch(e=>{throw new Error(`Failed to get git status: ${e.message}`)})}getAllBranches(){return this.git.branchLocal().then(e=>e.all).catch(e=>{throw new Error(`Failed to get branches: ${e.message}`)})}getRepositoryName(){return this.getRemoteUrl().then(e=>{const t=e.match(/([^/:]+?)(?:\.git)?$/);return t?t[1]:"unknown"}).catch(()=>"unknown")}getUserName(){return this.git.getConfig("user.name").then(e=>e.value||process.env.USER||process.env.USERNAME||"unknown_user").catch(()=>"unknown")}getUserInfo(){return Promise.all([this.git.getConfig("user.name").catch(()=>({value:null})),this.git.getConfig("user.email").catch(()=>({value:null}))]).then(([e,t])=>({name:e.value||"unknown",email:t.value||"unknown"}))}}class se{constructor(e,t){this.gitUtils=e,this.repositoryRepo=t}getCurrentRepository(){return Promise.all([this.gitUtils.getRemoteUrl(),this.gitUtils.getRepositoryName(),this.gitUtils.getRepoRoot()]).then(([e,t,n])=>this.getOrCreateRepository(e,t,n)).catch(e=>{throw new Error(`Failed to get current repository: ${e.message}`)})}getOrCreateRepository(e,t,n=null){return Promise.resolve(this.repositoryRepo.getOrCreate(e,t,n))}getRepository(e){return Promise.resolve(this.repositoryRepo.findById(e))}getRepositoryByUrl(e){return Promise.resolve(this.repositoryRepo.findByRemoteUrl(e))}getAllRepositories(){return Promise.resolve(this.repositoryRepo.findAll())}updateRepository(e,t){return Promise.resolve(this.repositoryRepo.update(e,t))}deleteRepository(e){return Promise.resolve(this.repositoryRepo.delete(e))}getRepositoryStats(e){return Promise.resolve({total_repositories:this.repositoryRepo.count()})}}class oe{constructor(e){this.gitUtils=e}validateBranchForSession(){return this.gitUtils.getCurrentBranch().then(e=>this.gitUtils.getMainBranch().then(t=>e===t?{valid:!1,branch:e,message:`Cannot start session on main branch '${e}'. Please create a feature branch first.\n\nExample:\n git checkout -b feature/my-feature\n claude "your prompt here"`}:{valid:!0,branch:e,message:`Session validated on branch '${e}'`})).catch(e=>(console.warn(`Branch validation warning: ${e.message}`),{valid:!0,branch:"unknown",message:`Branch validation skipped: ${e.message}`}))}isMainBranch(){return this.gitUtils.isOnMainBranch().catch(()=>!1)}}const ae=new class{constructor(){this.database=X(),this.initialized=!1}initialize(){this.initialized||(this.database.initialize(),this.initialized=!0)}async prepare(){this.initialize(),I(this.database.getConnection())}getConnection(){return this.initialize(),this.database.getConnection()}close(){this.database&&(this.database.close(),this.initialized=!1)}},ie=new class{constructor(e){this.dbService=e,this._repositoryRepo=null,this._syncRepo=null}get repositoryRepo(){return this._repositoryRepo||(this._repositoryRepo=new ee(this.dbService.database)),this._repositoryRepo}get syncRepo(){return this._syncRepo||(this._syncRepo=new te(this.dbService.database)),this._syncRepo}}(ae),ce=new class{constructor(e){this.dbService=e,this._knowledgeRepo=null}get knowledgeRepo(){return this._knowledgeRepo||(this._knowledgeRepo=new Q(this.dbService.database)),this._knowledgeRepo}}(ae),de=new class{constructor(e){this.dbService=e,this._sessionRepo=null}get sessionRepo(){return this._sessionRepo||(this._sessionRepo=new ne(this.dbService.database)),this._sessionRepo}}(ae),ue=new class{constructor(e){this.gitUtils=new re,this.repositoryManager=new se(this.gitUtils,e),this.branchValidator=new oe(this.gitUtils)}}(ie.repositoryRepo);ie.gitService=ue;class le{constructor(){this.logger=D("knowledge-management","knowledge-management"),this.knowledgeService=ce}getRepositoryId(){return process.env.CLAUDE_SESSION_REPOSITORYID}getSessionId(){return process.env.CLAUDE_SESSION_ID}buildUpdateData(e){const t={};return["title","summary","content","scope","source_type","knowledge_type","status","source_file","commit_hash","contributor"].forEach(n=>{void 0!==e[n]&&(t[n]=e[n])}),t}aggregateByStatus(e,t){e.forEach(e=>{t.by_status[e]=this.knowledgeService.knowledgeRepo.count({status:e})})}aggregateByScope(e,t){e.forEach(e=>{t.by_scope[e]=this.knowledgeService.knowledgeRepo.count({scope:e})})}aggregateByType(e,t){e.forEach(e=>{t.by_type[e]=this.knowledgeService.knowledgeRepo.count({knowledge_type:e})})}async create(e){this.logger.logDebug("Creating new knowledge item",e);const t=this.knowledgeService.knowledgeRepo.create({title:e.title,summary:e.summary,content:e.content,scope:e.scope,source_type:e.source_type,knowledge_type:e.knowledge_type,status:e.status,source_file:e.source_file,commit_hash:e.commit_hash,contributor:e.contributor,repository_id:e.repository_id||this.getRepositoryId(),session_id:e.session_id||this.getSessionId()});return this.logger.logDebug(`✓ Knowledge item created with ID: ${t.id}`),t}async update(e,t){this.logger.logInfo(`Updating knowledge item ${e}...`);const n=this.buildUpdateData(t),r=this.knowledgeService.knowledgeRepo.update(e,n);return this.logger.logInfo(`✓ Knowledge item ${e} updated`),r}async delete(e){this.logger.logInfo(`Deleting knowledge item ${e}...`),this.knowledgeService.knowledgeRepo.delete(e),this.logger.logInfo(`✓ Knowledge item ${e} deleted`)}async get(e){return this.knowledgeService.knowledgeRepo.findById(e)||(this.logger.logWarn(`Knowledge item ${e} not found`),null)}async list(e={}){if(e.scope)return this.knowledgeService.knowledgeRepo.findByScope(e.scope);if(e.status)return this.knowledgeService.knowledgeRepo.findByStatus(e.status);if(e.knowledge_type)return this.knowledgeService.knowledgeRepo.findByKnowledgeType(e.knowledge_type);const t=e.limit||100,n=e.offset||0;return this.knowledgeService.knowledgeRepo.findAll(t,n)}async search(e,t=10){return this.knowledgeService.knowledgeRepo.search(e,t)}async updateStatus(e,t){this.logger.logInfo(`Updating status of knowledge item ${e} to ${t}...`);const n=this.knowledgeService.knowledgeRepo.updateStatus(e,t);return this.logger.logInfo(`✓ Status updated to ${t}`),n}async getStats(){const e={total:0,by_status:{draft:0,suggested:0,verified:0},by_scope:{personal:0,project:0,organization:0},by_type:{code_pattern:0,architecture:0,config:0,pitfall:0,api_usage:0}};return e.total=this.knowledgeService.knowledgeRepo.count({}),this.aggregateByStatus(["draft","suggested","verified"],e),this.aggregateByScope(["personal","project","organization"],e),this.aggregateByType(["code_pattern","architecture","config","pitfall","api_usage"],e),e}}class pe extends M{constructor(e){super(e.session_id,e.hook_event_name),this.input=e,this.sessionId=e.session_id,this.transcriptPath=e.transcript_path,this.cwd=e.cwd,this.permissionMode=e.permission_mode,this.hookEventName=e.hook_event_name,this.sessionRecordId=null}async initSessionRecord(){try{const e=new re,t=await e.getCurrentBranch(),n=await e.getUserName(),r=await e.getRepoRoot();let s=null;if(r){const e=await ie.repositoryRepo.findByPath(r);e&&(s=e.id)}de.sessionRepo.createSession({session_id:this.sessionId,repository_id:s,working_directory:this.cwd,branch:t||"unknown",username:n||"unknown",env:{...process.env}});const o=de.sessionRepo.create({session_id:this.sessionId,name:this.hookEventName,input:this.input});this.sessionRecordId=o.id}catch(e){this.logError("Failed to initialize session record",e)}}static async parseInput(){const e=await pe.readStdin();return JSON.parse(e)}static async readStdin(){return new Promise((e,t)=>{let n="";const r=process.stdin;r.setEncoding("utf8"),r.on("data",e=>{n+=e}),r.on("end",()=>{e(n)}),r.on("error",e=>{t(e)}),r.resume()})}updateSessionOutput(e){if(this.sessionRecordId)try{de.sessionRepo.updateOutput(this.sessionRecordId,e)}catch(e){this.logError("Failed to update session record with output",e)}}async execute(){return await this.initSessionRecord(),this.internalExecute()}async internalExecute(){throw new Error("internalExecute() must be implemented by subclass")}createSuccessOutput(e={}){const t=new he({exitCode:0,message:e});return this.updateSessionOutput(e),t}createBlockingError(e){const t=new he({exitCode:2,message:e});return this.updateSessionOutput({error:e}),t}createNonBlockingError(e){const t=new he({exitCode:1,message:e});return this.updateSessionOutput({error:e}),t}}class he{constructor({exitCode:e,message:t}){this.exitCode=e,this.message=t,this.logger=D("ClaudeHookOutput","ClaudeHookOutput")}send(){0===this.exitCode?process.stdout.write("object"==typeof this.message?JSON.stringify(this.message,null,2):this.message):process.stderr.write(this.message),process.exit(this.exitCode)}}class me{constructor(){this.continue=!0,this.stopReason=null,this.suppressOutput=!1,this.systemMessage=null,this.hookSpecificOutput=null}setContinue(e,t=null){return this.continue=e,!e&&t&&(this.stopReason=t),this}setSuppressOutput(e){return this.suppressOutput=e,this}setSystemMessage(e){return this.systemMessage=e,this}toJSON(){const e={};return void 0!==this.continue&&(e.continue=this.continue),this.stopReason&&(e.stopReason=this.stopReason),this.suppressOutput&&(e.suppressOutput=this.suppressOutput),this.systemMessage&&(e.systemMessage=this.systemMessage),this.hookSpecificOutput&&(e.hookSpecificOutput=this.hookSpecificOutput),e}}class fe extends me{constructor(){super(),this.permissionDecision=null,this.permissionDecisionReason=null,this.updatedInput=null,this.additionalContext=null}allow(e=null){return this.permissionDecision="allow",this.permissionDecisionReason=e,this}deny(e){return this.permissionDecision="deny",this.permissionDecisionReason=e,this}ask(e=null){return this.permissionDecision="ask",this.permissionDecisionReason=e,this}updateInput(e){return this.updatedInput=e,this}addContext(e){return this.additionalContext=e,this}toJSON(){const e=super.toJSON(),t=!!this.permissionDecision,n=!!this.updatedInput,r=!!this.additionalContext;if(t||n||r){const t={hookEventName:"PreToolUse"};this.permissionDecision&&(t.permissionDecision=this.permissionDecision),this.permissionDecisionReason&&(t.permissionDecisionReason=this.permissionDecisionReason),this.updatedInput&&(t.updatedInput=this.updatedInput),this.additionalContext&&(t.additionalContext=this.additionalContext),e.hookSpecificOutput=t}return e}}class ge extends me{constructor(){super(),this.hookSpecificOutput={hookEventName:"PermissionRequest",decision:null}}allow(e=null){return this.hookSpecificOutput.decision={behavior:"allow"},e&&(this.hookSpecificOutput.decision.updatedInput=e),this}deny(e=null,t=!1){return this.hookSpecificOutput.decision={behavior:"deny"},e&&(this.hookSpecificOutput.decision.message=e),t&&(this.hookSpecificOutput.decision.interrupt=t),this}toJSON(){const e=super.toJSON();return this.hookSpecificOutput.decision&&(e.hookSpecificOutput={hookEventName:"PermissionRequest",decision:this.hookSpecificOutput.decision}),e}}class ye extends me{constructor(){super(),this.decision=null,this.reason=null,this.additionalContext=null}block(e){return this.decision="block",this.reason=e,this}addContext(e){return this.additionalContext=e,this}toJSON(){const e=super.toJSON();return this.decision&&(e.decision=this.decision,e.reason=this.reason),this.additionalContext&&(e.hookSpecificOutput={hookEventName:"PostToolUse",additionalContext:this.additionalContext}),e}}class _e extends me{constructor(){super(),this.decision=null,this.reason=null,this.additionalContext=null}block(e){return this.decision="block",this.reason=e,this}addContext(e){return this.additionalContext=e,this}toJSON(){const e=super.toJSON();return this.decision&&(e.decision=this.decision,e.reason=this.reason),this.additionalContext&&(e.hookSpecificOutput={hookEventName:"UserPromptSubmit",additionalContext:this.additionalContext}),e}}class ve extends me{constructor(){super(),this.decision=null,this.reason=null}block(e){return this.decision="block",this.reason=e,this}toJSON(){const e=super.toJSON();return this.decision&&(e.decision=this.decision,e.reason=this.reason),e}}class we extends me{constructor(){super(),this.additionalContext=null}setAdditionalContext(e){return this.additionalContext=e,this}toJSON(){const e=super.toJSON();return this.additionalContext&&(e.hookSpecificOutput={hookEventName:"SessionStart",additionalContext:this.additionalContext}),e}}class be extends ve{}class ke extends me{}class Ee extends me{}class $e extends me{}class Se extends pe{async persistInputVariables(e={}){const t=process.env.CLAUDE_ENV_FILE;if(!t)return void this.logDebug("CLAUDE_ENV_FILE not set, skipping variable persistence");const n={CLAUDE_SESSION_ID:this.sessionId,CLAUDE_SESSION_TRANSCRIPT_PATH:this.transcriptPath,CLAUDE_SESSION_CWD:this.cwd,CLAUDE_SESSION_SOURCE:this.input.source,CLAUDE_SESSION_MODE:this.input.model};[...Object.entries(n).map(([e,t])=>[e,t]),...Object.entries(e).map(([e,t])=>[`CLAUDE_SESSION_${e.toUpperCase()}`,t])].forEach(([e,n])=>{if(!process.env[e]){const r=String(n).replace(/'/g,"'\\''");d(t,`export ${e}='${r}'\n`)}}),this.logDebug("Persisted input variables to CLAUDE_ENV_FILE",{envFile:t})}async configureTmpPermissions(){try{const e=C().tmp;this.logDebug("Getting tmp directory from config",{tmpDir:e});const n=process.env.CLAUDE_PROJECT_DIR||this.cwd,r=t.join(n,".claude","settings.local.json");let s;if(this.logDebug("Settings path determined",{settingsPath:r,projectDir:n}),i(r)){const e=a(r,"utf-8");s=JSON.parse(e)}else{this.logDebug("settings.local.json does not exist, creating empty settings file"),s={permissions:{allow:[]}};const e=t.dirname(r);i(e)||(c(e,{recursive:!0}),this.logDebug("Created .claude directory",{settingsDir:e})),u(r,`${JSON.stringify(s,null,2)}\n`),this.logDebug("Created empty settings.local.json file",{settingsPath:r})}s.permissions||(s.permissions={}),s.permissions.allow||(s.permissions.allow=[]);const o=[`Read(/${e}/*)`,`Write(/${e}/*)`,"Skill(core:knowledge.add)","Skill(core:knowledge.collect)","Skill(core:knowledge.delete)","Skill(core:knowledge.enhance)","Skill(core:knowledge.import)","Skill(core:knowledge.init)","Skill(core:knowledge.save)","Skill(core:knowledge.status)","Skill(core:knowledge.update)","mcp__plugin_core_knowledge-bank-management__knowledge_create","mcp__plugin_core_knowledge-bank-management__knowledge_get","mcp__plugin_core_knowledge-bank-management__knowledge_update","mcp__plugin_core_knowledge-bank-management__knowledge_delete","mcp__plugin_core_knowledge-bank-management__knowledge_list","mcp__plugin_core_knowledge-bank-management__knowledge_search","mcp__plugin_core_knowledge-bank-management__knowledge_update_status","mcp__plugin_core_knowledge-bank-management__knowledge_stats"].filter(e=>!s.permissions.allow.includes(e));o.length>0&&(s.permissions.allow.push(...o),this.logDebug("Added permissions",{permissions:o})),o.length>0?(u(r,`${JSON.stringify(s,null,2)}\n`),this.logDebug("Updated settings.local.json with tmp directory permissions")):this.logDebug("Tmp directory permissions already configured")}catch(e){this.logDebug("Failed to configure tmp permissions",{error:e.message})}}injectKnowledgePrompt(){return["KNOWLEDGE INTEGRATION WORKFLOW:","","**At the START of each new task** (when user submits their first prompt for a task):","1. FIRST: Proactively invoke the `knowledge.enhance` skill to search and inject relevant knowledge based on user input"," - This provides context from past sessions and related knowledge"," - Only call this ONCE at the beginning of the task","","**At the END of successful task completion** (when the task is fully resolved):","2. LAST: Proactively invoke the `knowledge.collect` skill in the background to collect and organize knowledge from this session"," - This captures learnings from the completed work"," - Only call this ONCE after all work is done","","**IMPORTANT - Conflict Prevention & Manual Override**:","- If you have already invoked ANY `knowledge.*` skill (e.g., `knowledge.add`, `knowledge.save`, `knowledge.init`, `knowledge.update`, `knowledge.import`) during this session, **do NOT invoke `knowledge.collect`** at the end. Manual knowledge operations take precedence over automatic collection.","- Do NOT invoke these skills during task interruptions (network issues, asking user for clarification, etc.)","- Do NOT invoke these skills when user is providing additional information for an ongoing task","- Do NOT invoke these skills repeatedly - only ONCE at start and ONCE at end","","**How to detect interruptions vs new tasks**:","- If the user prompt is answering your question or providing requested information, it is an interruption","- If the user prompt is a brand new request or task, invoke `knowledge.enhance` first"]}async internalExecute(){const e=J(),t=new we;if(e.enabled){const n=await ue.branchValidator.validateBranchForSession(),r=await ue.repositoryManager.getCurrentRepository();await this.persistInputVariables({repositoryId:r.id}),await ue.gitUtils.getRemoteUrl(),this.logDebug("Knowledge context loaded",e);const s=[`Knowledge-Bank session started (${this.sessionId})`,`- Repository: ${n.branch}@${r.name}`,`- Knowledge auto-collection: enabled, version ${q.version}`];t.setSystemMessage(s.join("\n"));const o=this.injectKnowledgePrompt();t.setAdditionalContext(o.join("\n")),this.logDebug("SessionStart hook completed",{repository:r.name,branch:n.branch})}return super.createSuccessOutput(t.toJSON())}}class Te extends pe{async internalExecute(){const e=new ke;this.logDebug("Notification hook triggered",{input:this.input});const t=e.toJSON();return this.logDebug("Notification hook output generated",{output:t}),super.createSuccessOutput(t)}}C();class Oe extends pe{async internalExecute(){const e=(new ge).toJSON();return this.logDebug("PermissionRequest hook output generated",{output:e}),super.createSuccessOutput(e)}}class xe extends pe{async internalExecute(){const e=new ye;return this.logDebug("PostToolUse hook completed",e),super.createSuccessOutput(e.toJSON())}}class Ne extends pe{async internalExecute(){de.sessionRepo.findLatestSessionStart(this.sessionId);const e=new Ee;return this.logDebug("PreCompact hook completed",{sessionId:this.sessionId}),super.createSuccessOutput(e.toJSON())}generateSessionSummary(e){const t={};e.forEach(e=>{t[e.name]=(t[e.name]||0)+1});const n=[];return(t.tool_use||t.post_tool_use)&&n.push(`${(t.tool_use||0)+(t.post_tool_use||0)} tool operation(s)`),(t.user_prompt||t.user_prompt_submit)&&n.push(`${(t.user_prompt||0)+(t.user_prompt_submit||0)} user prompt(s)`),`Session with ${n.join(", ")}`}}const Ie=C();class Re extends pe{async internalExecute(){const e=new fe;this.shouldAutoApprove()&&e.allow(),this.logDebug("PreToolUse hook triggered",{input:this.input});const t=e.toJSON();return super.createSuccessOutput(t)}shouldAutoApprove(){let e=!1;this.logDebug("Evaluating permission request for auto-approval",this.input);const{tool_name:t,tool_input:n}=this.input;switch(t){case"mcp__plugin_core_knowledge-bank-management__knowledge_create":case"mcp__plugin_core_knowledge-bank-management__knowledge_get":case"mcp__plugin_core_knowledge-bank-management__knowledge_update":case"mcp__plugin_core_knowledge-bank-management__knowledge_delete":case"mcp__plugin_core_knowledge-bank-management__knowledge_list":case"mcp__plugin_core_knowledge-bank-management__knowledge_search":case"mcp__plugin_core_knowledge-bank-management__knowledge_update_status":case"mcp__plugin_core_knowledge-bank-management__knowledge_stats":e=!0;break;case"Read":case"Write":case"Edit":e=n.file_path.startsWith(Ie.tmp);break;case"Skill":e=n.skill.startsWith("core:knowledge.")||n.skill.startsWith("knowledge.")}return e}}class Pe extends pe{async internalExecute(){if(!de.sessionRepo.findLatestSessionStart(this.sessionId)){const e=new $e;return super.createSuccessOutput(e.toJSON())}const e=await ue.gitUtils.getCurrentBranch(),t=await ue.gitUtils.isBranchMergedToMain(e);let n=`Session ended (${this.sessionId})`;t&&(n+=`\n- Branch "${e}" has been merged to main`,n+="\n- Consider running: npx knowledge-bank knowledge-collect");const r=(new $e).setSystemMessage(n);return this.logDebug("SessionEnd hook completed",{sessionId:this.sessionId,branch:e,isMerged:t}),super.createSuccessOutput(r.toJSON())}}class Ce extends pe{async internalExecute(){const e=new ve;this.logDebug("Stop hook triggered",{input:this.input});const t=e.toJSON();return this.logDebug("Stop hook output generated",{output:t}),super.createSuccessOutput(t)}}class je extends pe{async internalExecute(){const e=new be;this.logDebug("SubagentStop hook triggered",{input:this.input});const t=e.toJSON();return this.logDebug("SubagentStop hook output generated",{output:t}),super.createSuccessOutput(t)}}class ze extends pe{isLikelyContinuation(){const e=this.input.transcript_path;return!!i(e)&&a(e,"utf-8").split("\n").filter(e=>e.trim()).filter(e=>"assistant"===JSON.parse(e).role).length>0}isKnowledgeSkillInvocation(){const e=this.input.prompt||"";return e.startsWith("/knowledge.")||e.startsWith("/knowledge.")}async internalExecute(){const e=new _e,t=J();if(t.enabled&&!this.isKnowledgeSkillInvocation()){const t=["REMINDER: Knowledge Integration Workflow","- FIRST: Invoke `knowledge.enhance` skill to get relevant context","- LAST: After task completion, invoke `knowledge.collect` skill to capture learnings","","Note: This is a new task - remember to invoke knowledge.enhance first before proceeding."];e.addContext(t.join("\n")),this.logDebug("UserPromptSubmitHook: Added knowledge context for new task")}else this.logDebug("UserPromptSubmitHook: Skipped knowledge context",{enabled:t.enabled,isKnowledgeSkill:this.isKnowledgeSkillInvocation()});return super.createSuccessOutput(e.toJSON())}}var Ae,Me;!function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const n of e)t[n]=n;return t},e.getValidEnumValues=t=>{const n=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),r={};for(const e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(const n of e)if(t(n))return n},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(Ae||(Ae={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(Me||(Me={}));const De=Ae.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Le=e=>{switch(typeof e){case"undefined":return De.undefined;case"string":return De.string;case"number":return Number.isNaN(e)?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(e)?De.array:null===e?De.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?De.promise:"undefined"!=typeof Map&&e instanceof Map?De.map:"undefined"!=typeof Set&&e instanceof Set?De.set:"undefined"!=typeof Date&&e instanceof Date?De.date:De.object;default:return De.unknown}},Ze=Ae.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"]);class Fe extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(r);else if("invalid_return_type"===s.code)r(s.returnTypeError);else if("invalid_arguments"===s.code)r(s.argumentsError);else if(0===s.path.length)n._errors.push(t(s));else{let e=n,r=0;for(;r<s.path.length;){const n=s.path[r];r===s.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(s))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(e){if(!(e instanceof Fe))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ae.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t=Object.create(null),n=[];for(const r of this.issues)if(r.path.length>0){const n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}Fe.create=e=>new Fe(e);const Ue=(e,t)=>{let n;switch(e.code){case Ze.invalid_type:n=e.received===De.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case Ze.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,Ae.jsonStringifyReplacer)}`;break;case Ze.unrecognized_keys:n=`Unrecognized key(s) in object: ${Ae.joinValues(e.keys,", ")}`;break;case Ze.invalid_union:n="Invalid input";break;case Ze.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Ae.joinValues(e.options)}`;break;case Ze.invalid_enum_value:n=`Invalid enum value. Expected ${Ae.joinValues(e.options)}, received '${e.received}'`;break;case Ze.invalid_arguments:n="Invalid function arguments";break;case Ze.invalid_return_type:n="Invalid function return type";break;case Ze.invalid_date:n="Invalid date";break;case Ze.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:Ae.assertNever(e.validation):n="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case Ze.too_small:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case Ze.too_big:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case Ze.custom:n="Invalid input";break;case Ze.invalid_intersection_types:n="Intersection results could not be merged";break;case Ze.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Ze.not_finite:n="Number must be finite";break;default:n=t.defaultError,Ae.assertNever(e)}return{message:n}};let qe=Ue;function He(e,t){const n=qe,r=(e=>{const{data:t,path:n,errorMaps:r,issueData:s}=e,o=[...n,...s.path||[]],a={...s,path:o};if(void 0!==s.message)return{...s,path:o,message:s.message};let i="";const c=r.filter(e=>!!e).slice().reverse();for(const e of c)i=e(a,{data:t,defaultError:i}).message;return{...s,path:o,message:i}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Ue?void 0:Ue].filter(e=>!!e)});e.common.issues.push(r)}class Ve{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const r of t){if("aborted"===r.status)return Je;"dirty"===r.status&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const e of t){const t=await e.key,r=await e.value;n.push({key:t,value:r})}return Ve.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const r of t){const{key:t,value:s}=r;if("aborted"===t.status)return Je;if("aborted"===s.status)return Je;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!r.alwaysSet||(n[t.value]=s.value)}return{status:e.value,value:n}}}const Je=Object.freeze({status:"aborted"}),Ke=e=>({status:"dirty",value:e}),Be=e=>({status:"valid",value:e}),We=e=>"aborted"===e.status,Ge=e=>"dirty"===e.status,Xe=e=>"valid"===e.status,Ye=e=>"undefined"!=typeof Promise&&e instanceof Promise;var Qe;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(Qe||(Qe={}));class et{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}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}}const tt=(e,t)=>{if(Xe(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Fe(e.common.issues);return this._error=t,this._error}}};function nt(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:s}:{errorMap:(t,s)=>{const{message:o}=e;return"invalid_enum_value"===t.code?{message:o??s.defaultError}:void 0===s.data?{message:o??r??s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:o??n??s.defaultError}},description:s}}let rt=class{get description(){return this._def.description}_getType(e){return Le(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Le(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ve,ctx:{common:e.parent.common,data:e.data,parsedType:Le(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Ye(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){const n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Le(e)},r=this._parseSync({data:e,path:n.path,parent:n});return tt(n,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Le(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:t});return Xe(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>Xe(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Le(e)},r=this._parse({data:e,path:n.path,parent:n}),s=await(Ye(r)?r:Promise.resolve(r));return tt(n,s)}refine(e,t){const n=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,r)=>{const s=e(t),o=()=>r.addIssue({code:Ze.custom,...n(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then(e=>!!e||(o(),!1)):!!s||(o(),!1)})}refinement(e,t){return this._refinement((n,r)=>!!e(n)||(r.addIssue("function"==typeof t?t(n,r):t),!1))}_refinement(e){return new tn({schema:this,typeName:ln.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:e=>this["~validate"](e)}}optional(){return nn.create(this,this._def)}nullable(){return rn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Zt.create(this)}promise(){return en.create(this,this._def)}or(e){return qt.create([this,e],this._def)}and(e){return Vt.create(this,e,this._def)}transform(e){return new tn({...nt(this._def),schema:this,typeName:ln.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new sn({...nt(this._def),innerType:this,defaultValue:t,typeName:ln.ZodDefault})}brand(){return new cn({typeName:ln.ZodBranded,type:this,...nt(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new on({...nt(this._def),innerType:this,catchValue:t,typeName:ln.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return dn.create(this,e)}readonly(){return un.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const st=/^c[^\s-]{8,}$/i,ot=/^[0-9a-z]+$/,at=/^[0-9A-HJKMNP-TV-Z]{26}$/i,it=/^[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,ct=/^[a-z0-9_-]{21}$/i,dt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ut=/^[-+]?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)?)??$/,lt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let pt;const ht=/^(?:(?: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])$/,mt=/^(?:(?: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])$/,ft=/^(([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]))$/,gt=/^(([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])$/,yt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_t=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,vt="((\\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])))",wt=new RegExp(`^${vt}$`);function bt(e){let t="[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function kt(e){return new RegExp(`^${bt(e)}$`)}function Et(e){let t=`${vt}T${bt(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function $t(e,t){return!("v4"!==t&&t||!ht.test(e))||!("v6"!==t&&t||!ft.test(e))}function St(e,t){if(!dt.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!("object"!=typeof s||null===s||"typ"in s&&"JWT"!==s?.typ||!s.alg||t&&s.alg!==t)}catch{return!1}}function Tt(e,t){return!("v4"!==t&&t||!mt.test(e))||!("v6"!==t&&t||!gt.test(e))}let Ot=class e extends rt{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==De.string){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.string,received:t.parsedType}),Je}const t=new Ve;let n;for(const r of this._def.checks)if("min"===r.kind)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),He(n,{code:Ze.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("max"===r.kind)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),He(n,{code:Ze.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("length"===r.kind){const s=e.data.length>r.value,o=e.data.length<r.value;(s||o)&&(n=this._getOrReturnCtx(e,n),s?He(n,{code:Ze.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):o&&He(n,{code:Ze.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if("email"===r.kind)lt.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"email",code:Ze.invalid_string,message:r.message}),t.dirty());else if("emoji"===r.kind)pt||(pt=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),pt.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"emoji",code:Ze.invalid_string,message:r.message}),t.dirty());else if("uuid"===r.kind)it.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"uuid",code:Ze.invalid_string,message:r.message}),t.dirty());else if("nanoid"===r.kind)ct.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"nanoid",code:Ze.invalid_string,message:r.message}),t.dirty());else if("cuid"===r.kind)st.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"cuid",code:Ze.invalid_string,message:r.message}),t.dirty());else if("cuid2"===r.kind)ot.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"cuid2",code:Ze.invalid_string,message:r.message}),t.dirty());else if("ulid"===r.kind)at.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"ulid",code:Ze.invalid_string,message:r.message}),t.dirty());else if("url"===r.kind)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),He(n,{validation:"url",code:Ze.invalid_string,message:r.message}),t.dirty()}else"regex"===r.kind?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"regex",code:Ze.invalid_string,message:r.message}),t.dirty())):"trim"===r.kind?e.data=e.data.trim():"includes"===r.kind?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),He(n,{code:Ze.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):"toLowerCase"===r.kind?e.data=e.data.toLowerCase():"toUpperCase"===r.kind?e.data=e.data.toUpperCase():"startsWith"===r.kind?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),He(n,{code:Ze.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):"endsWith"===r.kind?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),He(n,{code:Ze.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):"datetime"===r.kind?Et(r).test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{code:Ze.invalid_string,validation:"datetime",message:r.message}),t.dirty()):"date"===r.kind?wt.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{code:Ze.invalid_string,validation:"date",message:r.message}),t.dirty()):"time"===r.kind?kt(r).test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{code:Ze.invalid_string,validation:"time",message:r.message}),t.dirty()):"duration"===r.kind?ut.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"duration",code:Ze.invalid_string,message:r.message}),t.dirty()):"ip"===r.kind?$t(e.data,r.version)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"ip",code:Ze.invalid_string,message:r.message}),t.dirty()):"jwt"===r.kind?St(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"jwt",code:Ze.invalid_string,message:r.message}),t.dirty()):"cidr"===r.kind?Tt(e.data,r.version)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"cidr",code:Ze.invalid_string,message:r.message}),t.dirty()):"base64"===r.kind?yt.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"base64",code:Ze.invalid_string,message:r.message}),t.dirty()):"base64url"===r.kind?_t.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"base64url",code:Ze.invalid_string,message:r.message}),t.dirty()):Ae.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:Ze.invalid_string,...Qe.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:"email",...Qe.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Qe.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Qe.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Qe.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Qe.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Qe.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Qe.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Qe.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Qe.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Qe.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Qe.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Qe.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Qe.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Qe.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...Qe.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Qe.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Qe.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...Qe.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Qe.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Qe.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Qe.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Qe.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Qe.errToObj(t)})}nonempty(e){return this.min(1,Qe.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}};function xt(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}Ot.create=e=>new Ot({checks:[],typeName:ln.ZodString,coerce:e?.coerce??!1,...nt(e)});let Nt=class e extends rt{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){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.number,received:t.parsedType}),Je}let t;const n=new Ve;for(const r of this._def.checks)"int"===r.kind?Ae.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),He(t,{code:Ze.invalid_type,expected:"integer",received:"float",message:r.message}),n.dirty()):"min"===r.kind?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),He(t,{code:Ze.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):"max"===r.kind?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),He(t,{code:Ze.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):"multipleOf"===r.kind?0!==xt(e.data,r.value)&&(t=this._getOrReturnCtx(e,t),He(t,{code:Ze.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):"finite"===r.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),He(t,{code:Ze.not_finite,message:r.message}),n.dirty()):Ae.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Qe.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Qe.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Qe.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Qe.toString(t))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Qe.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:"int",message:Qe.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Qe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Qe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Qe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Qe.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Qe.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Qe.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Qe.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Qe.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&Ae.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if("finite"===n.kind||"int"===n.kind||"multipleOf"===n.kind)return!0;"min"===n.kind?(null===t||n.value>t)&&(t=n.value):"max"===n.kind&&(null===e||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Nt.create=e=>new Nt({checks:[],typeName:ln.ZodNumber,coerce:e?.coerce||!1,...nt(e)});class It extends rt{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 t;const n=new Ve;for(const r of this._def.checks)"min"===r.kind?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),He(t,{code:Ze.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):"max"===r.kind?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),He(t,{code:Ze.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):"multipleOf"===r.kind?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),He(t,{code:Ze.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):Ae.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.bigint,received:t.parsedType}),Je}gte(e,t){return this.setLimit("min",e,!0,Qe.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Qe.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Qe.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Qe.toString(t))}setLimit(e,t,n,r){return new It({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:Qe.toString(r)}]})}_addCheck(e){return new It({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Qe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Qe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Qe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Qe.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Qe.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}It.create=e=>new It({checks:[],typeName:ln.ZodBigInt,coerce:e?.coerce??!1,...nt(e)});let Rt=class extends rt{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==De.boolean){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.boolean,received:t.parsedType}),Je}return Be(e.data)}};Rt.create=e=>new Rt({typeName:ln.ZodBoolean,coerce:e?.coerce||!1,...nt(e)});class Pt extends rt{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==De.date){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.date,received:t.parsedType}),Je}if(Number.isNaN(e.data.getTime()))return He(this._getOrReturnCtx(e),{code:Ze.invalid_date}),Je;const t=new Ve;let n;for(const r of this._def.checks)"min"===r.kind?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),He(n,{code:Ze.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),t.dirty()):"max"===r.kind?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),He(n,{code:Ze.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),t.dirty()):Ae.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Pt({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Qe.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Qe.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}Pt.create=e=>new Pt({checks:[],coerce:e?.coerce||!1,typeName:ln.ZodDate,...nt(e)});class Ct extends rt{_parse(e){if(this._getType(e)!==De.symbol){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.symbol,received:t.parsedType}),Je}return Be(e.data)}}Ct.create=e=>new Ct({typeName:ln.ZodSymbol,...nt(e)});class jt extends rt{_parse(e){if(this._getType(e)!==De.undefined){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.undefined,received:t.parsedType}),Je}return Be(e.data)}}jt.create=e=>new jt({typeName:ln.ZodUndefined,...nt(e)});let zt=class extends rt{_parse(e){if(this._getType(e)!==De.null){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.null,received:t.parsedType}),Je}return Be(e.data)}};zt.create=e=>new zt({typeName:ln.ZodNull,...nt(e)});class At extends rt{constructor(){super(...arguments),this._any=!0}_parse(e){return Be(e.data)}}At.create=e=>new At({typeName:ln.ZodAny,...nt(e)});let Mt=class extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Be(e.data)}};Mt.create=e=>new Mt({typeName:ln.ZodUnknown,...nt(e)});let Dt=class extends rt{_parse(e){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.never,received:t.parsedType}),Je}};Dt.create=e=>new Dt({typeName:ln.ZodNever,...nt(e)});class Lt extends rt{_parse(e){if(this._getType(e)!==De.undefined){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.void,received:t.parsedType}),Je}return Be(e.data)}}Lt.create=e=>new Lt({typeName:ln.ZodVoid,...nt(e)});let Zt=class e extends rt{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==De.array)return He(t,{code:Ze.invalid_type,expected:De.array,received:t.parsedType}),Je;if(null!==r.exactLength){const e=t.data.length>r.exactLength.value,s=t.data.length<r.exactLength.value;(e||s)&&(He(t,{code:e?Ze.too_big:Ze.too_small,minimum:s?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(null!==r.minLength&&t.data.length<r.minLength.value&&(He(t,{code:Ze.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),null!==r.maxLength&&t.data.length>r.maxLength.value&&(He(t,{code:Ze.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new et(t,e,t.path,n)))).then(e=>Ve.mergeArray(n,e));const s=[...t.data].map((e,n)=>r.type._parseSync(new et(t,e,t.path,n)));return Ve.mergeArray(n,s)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:Qe.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:Qe.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:Qe.toString(n)}})}nonempty(e){return this.min(1,e)}};function Ft(e){if(e instanceof Ut){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=nn.create(Ft(r))}return new Ut({...e._def,shape:()=>t})}return e instanceof Zt?new Zt({...e._def,type:Ft(e.element)}):e instanceof nn?nn.create(Ft(e.unwrap())):e instanceof rn?rn.create(Ft(e.unwrap())):e instanceof Jt?Jt.create(e.items.map(e=>Ft(e))):e}Zt.create=(e,t)=>new Zt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ln.ZodArray,...nt(t)});let Ut=class e extends rt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=Ae.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==De.object){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.object,received:t.parsedType}),Je}const{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:s}=this._getCached(),o=[];if(!(this._def.catchall instanceof Dt&&"strip"===this._def.unknownKeys))for(const e in n.data)s.includes(e)||o.push(e);const a=[];for(const e of s){const t=r[e],s=n.data[e];a.push({key:{status:"valid",value:e},value:t._parse(new et(n,s,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Dt){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of o)a.push({key:{status:"valid",value:e},value:{status:"valid",value:n.data[e]}});else if("strict"===e)o.length>0&&(He(n,{code:Ze.unrecognized_keys,keys:o}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of o){const r=n.data[t];a.push({key:{status:"valid",value:t},value:e._parse(new et(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of a){const n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>Ve.mergeObjectSync(t,e)):Ve.mergeObjectSync(t,a)}get shape(){return this._def.shape()}strict(t){return Qe.errToObj,new e({...this._def,unknownKeys:"strict",...void 0!==t?{errorMap:(e,n)=>{const r=this._def.errorMap?.(e,n).message??n.defaultError;return"unrecognized_keys"===e.code?{message:Qe.errToObj(t).message??r}:{message:r}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ln.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){const n={};for(const e of Ae.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){const n={};for(const e of Ae.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Ft(this)}partial(t){const n={};for(const e of Ae.objectKeys(this.shape)){const r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){const n={};for(const e of Ae.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof nn;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return Xt(Ae.objectKeys(this.shape))}};Ut.create=(e,t)=>new Ut({shape:()=>e,unknownKeys:"strip",catchall:Dt.create(),typeName:ln.ZodObject,...nt(t)}),Ut.strictCreate=(e,t)=>new Ut({shape:()=>e,unknownKeys:"strict",catchall:Dt.create(),typeName:ln.ZodObject,...nt(t)}),Ut.lazycreate=(e,t)=>new Ut({shape:e,unknownKeys:"strip",catchall:Dt.create(),typeName:ln.ZodObject,...nt(t)});let qt=class extends rt{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;if(t.common.async)return Promise.all(n.map(async e=>{const n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const n of e)if("dirty"===n.result.status)return t.common.issues.push(...n.ctx.common.issues),n.result;const n=e.map(e=>new Fe(e.ctx.common.issues));return He(t,{code:Ze.invalid_union,unionErrors:n}),Je});{let e;const r=[];for(const s of n){const n={...t,common:{...t.common,issues:[]},parent:null},o=s._parseSync({data:t.data,path:t.path,parent:n});if("valid"===o.status)return o;"dirty"!==o.status||e||(e={result:o,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=r.map(e=>new Fe(e));return He(t,{code:Ze.invalid_union,unionErrors:s}),Je}}get options(){return this._def.options}};function Ht(e,t){const n=Le(e),r=Le(t);if(e===t)return{valid:!0,data:e};if(n===De.object&&r===De.object){const n=Ae.objectKeys(t),r=Ae.objectKeys(e).filter(e=>-1!==n.indexOf(e)),s={...e,...t};for(const n of r){const r=Ht(e[n],t[n]);if(!r.valid)return{valid:!1};s[n]=r.data}return{valid:!0,data:s}}if(n===De.array&&r===De.array){if(e.length!==t.length)return{valid:!1};const n=[];for(let r=0;r<e.length;r++){const s=Ht(e[r],t[r]);if(!s.valid)return{valid:!1};n.push(s.data)}return{valid:!0,data:n}}return n===De.date&&r===De.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}qt.create=(e,t)=>new qt({options:e,typeName:ln.ZodUnion,...nt(t)});let Vt=class extends rt{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(We(e)||We(r))return Je;const s=Ht(e.value,r.value);return s.valid?((Ge(e)||Ge(r))&&t.dirty(),{status:t.value,value:s.data}):(He(n,{code:Ze.invalid_intersection_types}),Je)};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(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Vt.create=(e,t,n)=>new Vt({left:e,right:t,typeName:ln.ZodIntersection,...nt(n)});class Jt extends rt{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==De.array)return He(n,{code:Ze.invalid_type,expected:De.array,received:n.parsedType}),Je;if(n.data.length<this._def.items.length)return He(n,{code:Ze.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Je;!this._def.rest&&n.data.length>this._def.items.length&&(He(n,{code:Ze.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const r=[...n.data].map((e,t)=>{const r=this._def.items[t]||this._def.rest;return r?r._parse(new et(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>Ve.mergeArray(t,e)):Ve.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new Jt({...this._def,rest:e})}}Jt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Jt({items:e,typeName:ln.ZodTuple,rest:null,...nt(t)})};class Kt extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==De.map)return He(n,{code:Ze.invalid_type,expected:De.map,received:n.parsedType}),Je;const r=this._def.keyType,s=this._def.valueType,o=[...n.data.entries()].map(([e,t],o)=>({key:r._parse(new et(n,e,n.path,[o,"key"])),value:s._parse(new et(n,t,n.path,[o,"value"]))}));if(n.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const n of o){const r=await n.key,s=await n.value;if("aborted"===r.status||"aborted"===s.status)return Je;"dirty"!==r.status&&"dirty"!==s.status||t.dirty(),e.set(r.value,s.value)}return{status:t.value,value:e}})}{const e=new Map;for(const n of o){const r=n.key,s=n.value;if("aborted"===r.status||"aborted"===s.status)return Je;"dirty"!==r.status&&"dirty"!==s.status||t.dirty(),e.set(r.value,s.value)}return{status:t.value,value:e}}}}Kt.create=(e,t,n)=>new Kt({valueType:t,keyType:e,typeName:ln.ZodMap,...nt(n)});class Bt extends rt{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==De.set)return He(n,{code:Ze.invalid_type,expected:De.set,received:n.parsedType}),Je;const r=this._def;null!==r.minSize&&n.data.size<r.minSize.value&&(He(n,{code:Ze.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),null!==r.maxSize&&n.data.size>r.maxSize.value&&(He(n,{code:Ze.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const s=this._def.valueType;function o(e){const n=new Set;for(const r of e){if("aborted"===r.status)return Je;"dirty"===r.status&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}const a=[...n.data.values()].map((e,t)=>s._parse(new et(n,e,n.path,t)));return n.common.async?Promise.all(a).then(e=>o(e)):o(a)}min(e,t){return new Bt({...this._def,minSize:{value:e,message:Qe.toString(t)}})}max(e,t){return new Bt({...this._def,maxSize:{value:e,message:Qe.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Bt.create=(e,t)=>new Bt({valueType:e,minSize:null,maxSize:null,typeName:ln.ZodSet,...nt(t)});class Wt extends rt{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Wt.create=(e,t)=>new Wt({getter:e,typeName:ln.ZodLazy,...nt(t)});let Gt=class extends rt{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return He(t,{received:t.data,code:Ze.invalid_literal,expected:this._def.value}),Je}return{status:"valid",value:e.data}}get value(){return this._def.value}};function Xt(e,t){return new Yt({values:e,typeName:ln.ZodEnum,...nt(t)})}Gt.create=(e,t)=>new Gt({value:e,typeName:ln.ZodLiteral,...nt(t)});let Yt=class e extends rt{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),n=this._def.values;return He(t,{expected:Ae.joinValues(n),received:t.parsedType,code:Ze.invalid_type}),Je}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return He(t,{received:t.data,code:Ze.invalid_enum_value,options:n}),Je}return Be(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};Yt.create=Xt;class Qt extends rt{_parse(e){const t=Ae.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==De.string&&n.parsedType!==De.number){const e=Ae.objectValues(t);return He(n,{expected:Ae.joinValues(e),received:n.parsedType,code:Ze.invalid_type}),Je}if(this._cache||(this._cache=new Set(Ae.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=Ae.objectValues(t);return He(n,{received:n.data,code:Ze.invalid_enum_value,options:e}),Je}return Be(e.data)}get enum(){return this._def.values}}Qt.create=(e,t)=>new Qt({values:e,typeName:ln.ZodNativeEnum,...nt(t)});class en extends rt{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==De.promise&&!1===t.common.async)return He(t,{code:Ze.invalid_type,expected:De.promise,received:t.parsedType}),Je;const n=t.parsedType===De.promise?t.data:Promise.resolve(t.data);return Be(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}en.create=(e,t)=>new en({type:e,typeName:ln.ZodPromise,...nt(t)});class tn extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ln.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,s={addIssue:e=>{He(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),"preprocess"===r.type){const e=r.transform(n.data,s);if(n.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return Je;const r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===r.status?Je:"dirty"===r.status||"dirty"===t.value?Ke(r.value):r});{if("aborted"===t.value)return Je;const r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===r.status?Je:"dirty"===r.status||"dirty"===t.value?Ke(r.value):r}}if("refinement"===r.type){const e=e=>{const t=r.refinement(e,s);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===n.common.async){const r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===r.status?Je:("dirty"===r.status&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>"aborted"===n.status?Je:("dirty"===n.status&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if("transform"===r.type){if(!1===n.common.async){const e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Xe(e))return Je;const o=r.transform(e.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>Xe(e)?Promise.resolve(r.transform(e.value,s)).then(e=>({status:t.value,value:e})):Je)}Ae.assertNever(r)}}tn.create=(e,t,n)=>new tn({schema:e,typeName:ln.ZodEffects,effect:t,...nt(n)}),tn.createWithPreprocess=(e,t,n)=>new tn({schema:t,effect:{type:"preprocess",transform:e},typeName:ln.ZodEffects,...nt(n)});let nn=class extends rt{_parse(e){return this._getType(e)===De.undefined?Be(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};nn.create=(e,t)=>new nn({innerType:e,typeName:ln.ZodOptional,...nt(t)});let rn=class extends rt{_parse(e){return this._getType(e)===De.null?Be(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};rn.create=(e,t)=>new rn({innerType:e,typeName:ln.ZodNullable,...nt(t)});let sn=class extends rt{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===De.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};sn.create=(e,t)=>new sn({innerType:e,typeName:ln.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...nt(t)});let on=class extends rt{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ye(r)?r.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new Fe(n.common.issues)},input:n.data})})):{status:"valid",value:"valid"===r.status?r.value:this._def.catchValue({get error(){return new Fe(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};on.create=(e,t)=>new on({innerType:e,typeName:ln.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...nt(t)});class an extends rt{_parse(e){if(this._getType(e)!==De.nan){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.nan,received:t.parsedType}),Je}return{status:"valid",value:e.data}}}an.create=e=>new an({typeName:ln.ZodNaN,...nt(e)});class cn extends rt{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class dn extends rt{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?Je:"dirty"===e.status?(t.dirty(),Ke(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{const e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?Je:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(e,t){return new dn({in:e,out:t,typeName:ln.ZodPipeline})}}let un=class extends rt{_parse(e){const t=this._def.innerType._parse(e),n=e=>(Xe(e)&&(e.value=Object.freeze(e.value)),e);return Ye(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};var ln;un.create=(e,t)=>new un({innerType:e,typeName:ln.ZodReadonly,...nt(t)}),function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(ln||(ln={})),Dt.create,Zt.create;const pn=Ut.create;function hn(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:a,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);const s=a.prototype,o=Object.keys(s);for(let e=0;e<o.length;e++){const t=o[e];t in n||(n[t]=s[t].bind(n))}}const s=n?.Parent??Object;class o extends s{}function a(e){var t;const s=n?.Parent?new o:this;r(s,e),(t=s._zod).deferred??(t.deferred=[]);for(const e of s._zod.deferred)e();return s}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}qt.create,Vt.create,Jt.create,Yt.create,en.create,nn.create,rn.create;class mn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class fn extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const gn={};function yn(e){return gn}function _n(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function vn(e,t){return"bigint"==typeof t?t.toString():t}function wn(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function bn(e){return null==e}function kn(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const En=Symbol("evaluating");function $n(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==En)return void 0===r&&(r=En,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Sn(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Tn(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function On(e){return JSON.stringify(e)}const xn="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Nn(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const In=wn(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Rn(e){if(!1===Nn(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const n=t.prototype;return!1!==Nn(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function Pn(e){return Rn(e)?{...e}:Array.isArray(e)?[...e]:e}const Cn=new Set(["string","number","symbol"]);function jn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function zn(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function An(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}const Mn={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]};function Dn(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function Ln(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Zn(e){return"string"==typeof e?e:e?.message}function Fn(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const s=Zn(e.inst?._zod.def?.error?.(e))??Zn(t?.error?.(e))??Zn(n.customError?.(e))??Zn(n.localeError?.(e))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function Un(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function qn(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}const Hn=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,vn,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Vn=hn("$ZodError",Hn),Jn=hn("$ZodError",Hn,{Parent:Error}),Kn=e=>(t,n,r,s)=>{const o=r?Object.assign(r,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},o);if(a instanceof Promise)throw new mn;if(a.issues.length){const t=new(s?.Err??e)(a.issues.map(e=>Fn(e,o,yn())));throw xn(t,s?.callee),t}return a.value},Bn=Kn(Jn),Wn=e=>async(t,n,r,s)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},o);if(a instanceof Promise&&(a=await a),a.issues.length){const t=new(s?.Err??e)(a.issues.map(e=>Fn(e,o,yn())));throw xn(t,s?.callee),t}return a.value},Gn=Wn(Jn),Xn=e=>(t,n,r)=>{const s=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},s);if(o instanceof Promise)throw new mn;return o.issues.length?{success:!1,error:new(e??Vn)(o.issues.map(e=>Fn(e,s,yn())))}:{success:!0,data:o.value}},Yn=Xn(Jn),Qn=e=>async(t,n,r)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let o=t._zod.run({value:n,issues:[]},s);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(e=>Fn(e,s,yn())))}:{success:!0,data:o.value}},er=Qn(Jn),tr=e=>(t,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Kn(e)(t,n,s)},nr=e=>(t,n,r)=>Kn(e)(t,n,r),rr=e=>async(t,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Wn(e)(t,n,s)},sr=e=>async(t,n,r)=>Wn(e)(t,n,r),or=e=>(t,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Xn(e)(t,n,s)},ar=e=>(t,n,r)=>Xn(e)(t,n,r),ir=e=>async(t,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Qn(e)(t,n,s)},cr=e=>async(t,n,r)=>Qn(e)(t,n,r),dr=/^[cC][^\s-]{8,}$/,ur=/^[0-9a-z]+$/,lr=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,pr=/^[0-9a-vA-V]{20}$/,hr=/^[A-Za-z0-9]{27}$/,mr=/^[a-zA-Z0-9_-]{21}$/,fr=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,gr=/^([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})$/,yr=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[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)$/,_r=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,vr=/^(?:(?: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])$/,wr=/^(([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}|:))$/,br=/^((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])$/,kr=/^(([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])$/,Er=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,$r=/^[A-Za-z0-9_-]*$/,Sr=/^\+[1-9]\d{6,14}$/,Tr="(?:(?:\\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])))",Or=new RegExp(`^${Tr}$`);function xr(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}const Nr=/^-?\d+$/,Ir=/^-?\d+(?:\.\d+)?$/,Rr=/^(?:true|false)$/i,Pr=/^null$/i,Cr=/^[^A-Z]*$/,jr=/^[^a-z]*$/,zr=hn("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ar={number:"number",bigint:"bigint",object:"date"},Mr=hn("$ZodCheckLessThan",(e,t)=>{zr.init(e,t);const n=Ar[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Dr=hn("$ZodCheckGreaterThan",(e,t)=>{zr.init(e,t);const n=Ar[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Lr=hn("$ZodCheckMultipleOf",(e,t)=>{zr.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?n.value%t.value===BigInt(0):0===function(e,t){const n=(e.toString().split(".")[1]||"").length,r=t.toString();let s=(r.split(".")[1]||"").length;if(0===s&&/\d?e-\d?/.test(r)){const e=r.match(/\d?e-(\d?)/);e?.[1]&&(s=Number.parseInt(e[1]))}const o=n>s?n:s;return Number.parseInt(e.toFixed(o).replace(".",""))%Number.parseInt(t.toFixed(o).replace(".",""))/10**o}(n.value,t.value))||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Zr=hn("$ZodCheckNumberFormat",(e,t)=>{zr.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[s,o]=Mn[t.format];e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,r.minimum=s,r.maximum=o,n&&(r.pattern=Nr)}),e._zod.check=a=>{const i=a.value;if(n){if(!Number.isInteger(i))return void a.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:i,inst:e});if(!Number.isSafeInteger(i))return void(i>0?a.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):a.issues.push({input:i,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}))}i<s&&a.issues.push({origin:"number",input:i,code:"too_small",minimum:s,inclusive:!0,inst:e,continue:!t.abort}),i>o&&a.issues.push({origin:"number",input:i,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),Fr=hn("$ZodCheckMaxLength",(e,t)=>{var n;zr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!bn(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const s=Un(r);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ur=hn("$ZodCheckMinLength",(e,t)=>{var n;zr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!bn(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const s=Un(r);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),qr=hn("$ZodCheckLengthEquals",(e,t)=>{var n;zr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!bn(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{const r=n.value,s=r.length;if(s===t.length)return;const o=Un(r),a=s>t.length;n.issues.push({origin:o,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Hr=hn("$ZodCheckStringFormat",(e,t)=>{var n,r;zr.init(e,t),e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=new Set),n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Vr=hn("$ZodCheckRegex",(e,t)=>{Hr.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Jr=hn("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Cr),Hr.init(e,t)}),Kr=hn("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=jr),Hr.init(e,t)}),Br=hn("$ZodCheckIncludes",(e,t)=>{zr.init(e,t);const n=jn(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Wr=hn("$ZodCheckStartsWith",(e,t)=>{zr.init(e,t);const n=new RegExp(`^${jn(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Gr=hn("$ZodCheckEndsWith",(e,t)=>{zr.init(e,t);const n=new RegExp(`.*${jn(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Xr=hn("$ZodCheckOverwrite",(e,t)=>{zr.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class Yr{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const e of r)this.content.push(e)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}const Qr={major:4,minor:3,patch:6},es=hn("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Qr;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const t of r)for(const n of t._zod.onattach)n(e);if(0===r.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let r,s=Dn(e);for(const o of t){if(o._zod.def.when){if(!o._zod.def.when(e))continue}else if(s)continue;const t=e.issues.length,a=o._zod.check(e);if(a instanceof Promise&&!1===n?.async)throw new mn;if(r||a instanceof Promise)r=(r??Promise.resolve()).then(async()=>{await a,e.issues.length!==t&&(s||(s=Dn(e,t)))});else{if(e.issues.length===t)continue;s||(s=Dn(e,t))}}return r?r.then(()=>e):e},n=(n,s,o)=>{if(Dn(n))return n.aborted=!0,n;const a=t(s,r,o);if(a instanceof Promise){if(!1===o.async)throw new mn;return a.then(t=>e._zod.parse(t,o))}return e._zod.parse(a,o)};e._zod.run=(s,o)=>{if(o.skipChecks)return e._zod.parse(s,o);if("backward"===o.direction){const t=e._zod.parse({value:s.value,issues:[]},{...o,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,s,o)):n(t,s,o)}const a=e._zod.parse(s,o);if(a instanceof Promise){if(!1===o.async)throw new mn;return a.then(e=>t(e,r,o))}return t(a,r,o)}}$n(e,"~standard",()=>({validate:t=>{try{const n=Yn(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return er(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),ts=hn("$ZodString",(e,t)=>{var n;es.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(n=e._zod.bag,new RegExp(`^${n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),ns=hn("$ZodStringFormat",(e,t)=>{Hr.init(e,t),ts.init(e,t)}),rs=hn("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=gr),ns.init(e,t)}),ss=hn("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=yr(e))}else t.pattern??(t.pattern=yr());ns.init(e,t)}),os=hn("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=_r),ns.init(e,t)}),as=hn("$ZodURL",(e,t)=>{ns.init(e,t),e._zod.check=n=>{try{const r=n.value.trim(),s=new URL(r);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(s.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(t.normalize?n.value=s.href:n.value=r)}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),is=hn("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ns.init(e,t)}),cs=hn("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=mr),ns.init(e,t)}),ds=hn("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=dr),ns.init(e,t)}),us=hn("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=ur),ns.init(e,t)}),ls=hn("$ZodULID",(e,t)=>{t.pattern??(t.pattern=lr),ns.init(e,t)}),ps=hn("$ZodXID",(e,t)=>{t.pattern??(t.pattern=pr),ns.init(e,t)}),hs=hn("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=hr),ns.init(e,t)}),ms=hn("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=xr({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${Tr}T(?:${r})$`)}(t)),ns.init(e,t)}),fs=hn("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Or),ns.init(e,t)}),gs=hn("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${xr(t)}$`)),ns.init(e,t)}),ys=hn("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=fr),ns.init(e,t)}),_s=hn("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=vr),ns.init(e,t),e._zod.bag.format="ipv4"}),vs=hn("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=wr),ns.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),ws=hn("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=br),ns.init(e,t)}),bs=hn("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=kr),ns.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(2!==r.length)throw new Error;const[e,t]=r;if(!t)throw new Error;const n=Number(t);if(`${n}`!==t)throw new Error;if(n<0||n>128)throw new Error;new URL(`http://[${e}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function ks(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const Es=hn("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Er),ns.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{ks(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),$s=hn("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=$r),ns.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!$r.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return ks(t.padEnd(4*Math.ceil(t.length/4),"="))})(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Ss=hn("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Sr),ns.init(e,t)}),Ts=hn("$ZodJWT",(e,t)=>{ns.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const s=JSON.parse(atob(r));return!("typ"in s&&"JWT"!==s?.typ||!s.alg||t&&(!("alg"in s)||s.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Os=hn("$ZodNumber",(e,t)=>{es.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ir,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(e){}const s=n.value;if("number"==typeof s&&!Number.isNaN(s)&&Number.isFinite(s))return n;const o="number"==typeof s?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:s,inst:e,...o?{received:o}:{}}),n}}),xs=hn("$ZodNumberFormat",(e,t)=>{Zr.init(e,t),Os.init(e,t)}),Ns=hn("$ZodBoolean",(e,t)=>{es.init(e,t),e._zod.pattern=Rr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(e){}const s=n.value;return"boolean"==typeof s||n.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:e}),n}}),Is=hn("$ZodNull",(e,t)=>{es.init(e,t),e._zod.pattern=Pr,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{const r=t.value;return null===r||t.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),t}}),Rs=hn("$ZodUnknown",(e,t)=>{es.init(e,t),e._zod.parse=e=>e}),Ps=hn("$ZodNever",(e,t)=>{es.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function Cs(e,t,n){e.issues.length&&t.issues.push(...Ln(n,e.issues)),t.value[n]=e.value}const js=hn("$ZodArray",(e,t)=>{es.init(e,t),e._zod.parse=(n,r)=>{const s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:e}),n;n.value=Array(s.length);const o=[];for(let e=0;e<s.length;e++){const a=s[e],i=t.element._zod.run({value:a,issues:[]},r);i instanceof Promise?o.push(i.then(t=>Cs(t,n,e))):Cs(i,n,e)}return o.length?Promise.all(o).then(()=>n):n}});function zs(e,t,n,r,s){if(e.issues.length){if(s&&!(n in r))return;t.issues.push(...Ln(n,e.issues))}void 0===e.value?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function As(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const n=(r=e.shape,Object.keys(r).filter(e=>"optional"===r[e]._zod.optin&&"optional"===r[e]._zod.optout));var r;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Ms(e,t,n,r,s,o){const a=[],i=s.keySet,c=s.catchall._zod,d=c.def.type,u="optional"===c.optout;for(const s in t){if(i.has(s))continue;if("never"===d){a.push(s);continue}const o=c.run({value:t[s],issues:[]},r);o instanceof Promise?e.push(o.then(e=>zs(e,n,s,t,u))):zs(o,n,s,t,u)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:o}),e.length?Promise.all(e).then(()=>n):n}const Ds=hn("$ZodObject",(e,t)=>{es.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!n?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}const r=wn(()=>As(t));$n(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(const e of r.values)n[t].add(e)}}return n});const s=Nn,o=t.catchall;let a;e._zod.parse=(t,n)=>{a??(a=r.value);const i=t.value;if(!s(i))return t.issues.push({expected:"object",code:"invalid_type",input:i,inst:e}),t;t.value={};const c=[],d=a.shape;for(const e of a.keys){const r=d[e],s="optional"===r._zod.optout,o=r._zod.run({value:i[e],issues:[]},n);o instanceof Promise?c.push(o.then(n=>zs(n,t,e,i,s))):zs(o,t,e,i,s)}return o?Ms(c,i,t,n,r.value,e):c.length?Promise.all(c).then(()=>t):t}}),Ls=hn("$ZodObjectJIT",(e,t)=>{Ds.init(e,t);const n=e._zod.parse,r=wn(()=>As(t));let s;const o=Nn,a=!gn.jitless,i=a&&In.value,c=t.catchall;let d;e._zod.parse=(u,l)=>{d??(d=r.value);const p=u.value;return o(p)?a&&i&&!1===l?.async&&!0!==l.jitless?(s||(s=(e=>{const t=new Yr(["shape","payload","ctx"]),n=r.value,s=e=>{const t=On(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const o=Object.create(null);let a=0;for(const e of n.keys)o[e]="key_"+a++;t.write("const newResult = {};");for(const r of n.keys){const n=o[r],a=On(r),i=e[r],c="optional"===i?._zod?.optout;t.write(`const ${n} = ${s(r)};`),c?t.write(`\n if (${n}.issues.length) {\n if (${a} in input) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n }\n \n if (${n}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${n}.value;\n }\n \n `):t.write(`\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n \n if (${n}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${n}.value;\n }\n \n `)}t.write("payload.value = newResult;"),t.write("return payload;");const i=t.compile();return(t,n)=>i(e,t,n)})(t.shape)),u=s(u,l),c?Ms([],p,u,l,d,e):u):n(u,l):(u.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),u)}});function Zs(e,t,n,r){for(const n of e)if(0===n.issues.length)return t.value=n.value,t;const s=e.filter(e=>!Dn(e));return 1===s.length?(t.value=s[0].value,s[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Fn(e,r,yn())))}),t)}const Fs=hn("$ZodUnion",(e,t)=>{es.init(e,t),$n(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),$n(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),$n(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),$n(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>kn(e.source)).join("|")})$`)}});const n=1===t.options.length,r=t.options[0]._zod.run;e._zod.parse=(s,o)=>{if(n)return r(s,o);let a=!1;const i=[];for(const e of t.options){const t=e._zod.run({value:s.value,issues:[]},o);if(t instanceof Promise)i.push(t),a=!0;else{if(0===t.issues.length)return t;i.push(t)}}return a?Promise.all(i).then(t=>Zs(t,s,e,o)):Zs(i,s,e,o)}}),Us=hn("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Fs.init(e,t);const n=e._zod.parse;$n(e._zod,"propValues",()=>{const e={};for(const n of t.options){const r=n._zod.propValues;if(!r||0===Object.keys(r).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(const r of n)e[t].add(r)}}return e});const r=wn(()=>{const e=t.options,n=new Map;for(const r of e){const e=r._zod.propValues?.[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const t of e){if(n.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(s,o)=>{const a=s.value;if(!Nn(a))return s.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),s;const i=r.value.get(a?.[t.discriminator]);return i?i._zod.run(s,o):t.unionFallback?n(s,o):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:a,path:[t.discriminator],inst:e}),s)}}),qs=hn("$ZodIntersection",(e,t)=>{es.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,s=t.left._zod.run({value:r,issues:[]},n),o=t.right._zod.run({value:r,issues:[]},n);return s instanceof Promise||o instanceof Promise?Promise.all([s,o]).then(([t,n])=>Vs(e,t,n)):Vs(e,s,o)}});function Hs(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(Rn(e)&&Rn(t)){const n=Object.keys(t),r=Object.keys(e).filter(e=>-1!==n.indexOf(e)),s={...e,...t};for(const n of r){const r=Hs(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};s[n]=r.data}return{valid:!0,data:s}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const s=Hs(e[r],t[r]);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Vs(e,t,n){const r=new Map;let s;for(const n of t.issues)if("unrecognized_keys"===n.code){s??(s=n);for(const e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(const t of n.issues)if("unrecognized_keys"===t.code)for(const e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);const o=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(o.length&&s&&e.issues.push({...s,keys:o}),Dn(e))return e;const a=Hs(t.value,n.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}const Js=hn("$ZodRecord",(e,t)=>{es.init(e,t),e._zod.parse=(n,r)=>{const s=n.value;if(!Rn(s))return n.issues.push({expected:"record",code:"invalid_type",input:s,inst:e}),n;const o=[],a=t.keyType._zod.values;if(a){n.value={};const i=new Set;for(const e of a)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){i.add("number"==typeof e?e.toString():e);const a=t.valueType._zod.run({value:s[e],issues:[]},r);a instanceof Promise?o.push(a.then(t=>{t.issues.length&&n.issues.push(...Ln(e,t.issues)),n.value[e]=t.value})):(a.issues.length&&n.issues.push(...Ln(e,a.issues)),n.value[e]=a.value)}let c;for(const e in s)i.has(e)||(c=c??[],c.push(e));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:c})}else{n.value={};for(const a of Reflect.ownKeys(s)){if("__proto__"===a)continue;let i=t.keyType._zod.run({value:a,issues:[]},r);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if("string"==typeof a&&Ir.test(a)&&i.issues.length){const e=t.keyType._zod.run({value:Number(a),issues:[]},r);if(e instanceof Promise)throw new Error("Async schemas not supported in object keys currently");0===e.issues.length&&(i=e)}if(i.issues.length){"loose"===t.mode?n.value[a]=s[a]:n.issues.push({code:"invalid_key",origin:"record",issues:i.issues.map(e=>Fn(e,r,yn())),input:a,path:[a],inst:e});continue}const c=t.valueType._zod.run({value:s[a],issues:[]},r);c instanceof Promise?o.push(c.then(e=>{e.issues.length&&n.issues.push(...Ln(a,e.issues)),n.value[i.value]=e.value})):(c.issues.length&&n.issues.push(...Ln(a,c.issues)),n.value[i.value]=c.value)}}return o.length?Promise.all(o).then(()=>n):n}}),Ks=hn("$ZodEnum",(e,t)=>{es.init(e,t);const n=_n(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(e=>Cn.has(typeof e)).map(e=>"string"==typeof e?jn(e):e.toString()).join("|")})$`),e._zod.parse=(t,s)=>{const o=t.value;return r.has(o)||t.issues.push({code:"invalid_value",values:n,input:o,inst:e}),t}}),Bs=hn("$ZodLiteral",(e,t)=>{if(es.init(e,t),0===t.values.length)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?jn(e):e?jn(e.toString()):String(e)).join("|")})$`),e._zod.parse=(r,s)=>{const o=r.value;return n.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),Ws=hn("$ZodTransform",(e,t)=>{es.init(e,t),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new fn(e.constructor.name);const s=t.transform(n.value,n);if(r.async)return(s instanceof Promise?s:Promise.resolve(s)).then(e=>(n.value=e,n));if(s instanceof Promise)throw new mn;return n.value=s,n}});function Gs(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const Xs=hn("$ZodOptional",(e,t)=>{es.init(e,t),e._zod.optin="optional",e._zod.optout="optional",$n(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),$n(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${kn(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>Gs(t,e.value)):Gs(r,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),Ys=hn("$ZodExactOptional",(e,t)=>{Xs.init(e,t),$n(e._zod,"values",()=>t.innerType._zod.values),$n(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Qs=hn("$ZodNullable",(e,t)=>{es.init(e,t),$n(e._zod,"optin",()=>t.innerType._zod.optin),$n(e._zod,"optout",()=>t.innerType._zod.optout),$n(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${kn(e.source)}|null)$`):void 0}),$n(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),eo=hn("$ZodDefault",(e,t)=>{es.init(e,t),e._zod.optin="optional",$n(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>to(e,t)):to(r,t)}});function to(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const no=hn("$ZodPrefault",(e,t)=>{es.init(e,t),e._zod.optin="optional",$n(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>("backward"===n.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),ro=hn("$ZodNonOptional",(e,t)=>{es.init(e,t),$n(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,r)=>{const s=t.innerType._zod.run(n,r);return s instanceof Promise?s.then(t=>so(t,e)):so(s,e)}});function so(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const oo=hn("$ZodCatch",(e,t)=>{es.init(e,t),$n(e._zod,"optin",()=>t.innerType._zod.optin),$n(e._zod,"optout",()=>t.innerType._zod.optout),$n(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Fn(e,n,yn()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Fn(e,n,yn()))},input:e.value}),e.issues=[]),e)}}),ao=hn("$ZodPipe",(e,t)=>{es.init(e,t),$n(e._zod,"values",()=>t.in._zod.values),$n(e._zod,"optin",()=>t.in._zod.optin),$n(e._zod,"optout",()=>t.out._zod.optout),$n(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>io(e,t.in,n)):io(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>io(e,t.out,n)):io(r,t.out,n)}});function io(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const co=hn("$ZodReadonly",(e,t)=>{es.init(e,t),$n(e._zod,"propValues",()=>t.innerType._zod.propValues),$n(e._zod,"values",()=>t.innerType._zod.values),$n(e._zod,"optin",()=>t.innerType?._zod?.optin),$n(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(uo):uo(r)}});function uo(e){return e.value=Object.freeze(e.value),e}const lo=hn("$ZodCustom",(e,t)=>{zr.init(e,t),es.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,s=t.fn(r);if(s instanceof Promise)return s.then(t=>po(t,n,r,e));po(s,n,r,e)}});function po(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(qn(e))}}var ho;(ho=globalThis).__zod_globalRegistry??(ho.__zod_globalRegistry=new class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}});const mo=globalThis.__zod_globalRegistry;function fo(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...An(t)})}function go(e,t){return new Mr({check:"less_than",...An(t),value:e,inclusive:!1})}function yo(e,t){return new Mr({check:"less_than",...An(t),value:e,inclusive:!0})}function _o(e,t){return new Dr({check:"greater_than",...An(t),value:e,inclusive:!1})}function vo(e,t){return new Dr({check:"greater_than",...An(t),value:e,inclusive:!0})}function wo(e,t){return new Lr({check:"multiple_of",...An(t),value:e})}function bo(e,t){return new Fr({check:"max_length",...An(t),maximum:e})}function ko(e,t){return new Ur({check:"min_length",...An(t),minimum:e})}function Eo(e,t){return new qr({check:"length_equals",...An(t),length:e})}function $o(e){return new Xr({check:"overwrite",tx:e})}function So(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??mo,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function To(e,t,n={path:[],schemaPath:[]}){var r;const s=e._zod.def,o=t.seen.get(e);if(o)return o.count++,n.schemaPath.includes(e)&&(o.cycle=n.path),o.schema;const a={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,a);const i=e._zod.toJSONSchema?.();if(i)a.schema=i;else{const r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,r);else{const n=a.schema,o=t.processors[s.type];if(!o)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${s.type}`);o(e,t,n,r)}const o=e._zod.parent;o&&(a.ref||(a.ref=o),To(o,t,r),t.seen.get(o).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(a.schema,c),"input"===t.io&&No(e)&&(delete a.schema.examples,delete a.schema.default),"input"===t.io&&a.schema._prefault&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function Oo(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const t of e.seen.entries()){const n=e.metadataRegistry.get(t[0])?.id;if(n){const e=r.get(n);if(e&&e!==t[0])throw new Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}const s=t=>{if(t[1].schema.$ref)return;const r=t[1],{ref:s,defId:o}=(t=>{const r="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const n=e.external.registry.get(t[0])?.id,s=e.external.uri??(e=>e);if(n)return{ref:s(n)};const o=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=o,{defId:o,ref:`${s("__shared")}#/${r}/${o}`}}if(t[1]===n)return{ref:"#"};const s=`#/${r}/`,o=t[1].schema.id??"__schema"+e.counter++;return{defId:o,ref:s+o}})(t);r.def={...r.schema},o&&(r.defId=o);const a=r.schema;for(const e in a)delete a[e];a.$ref=s};if("throw"===e.cycles)for(const t of e.seen.entries()){const e=t[1];if(e.cycle)throw new Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const n of e.seen.entries()){const r=n[1];if(t===n[0]){s(n);continue}if(e.external){const r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){s(n);continue}}const o=e.metadataRegistry.get(n[0])?.id;(o||r.cycle||r.count>1&&"ref"===e.reused)&&s(n)}}function xo(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=t=>{const n=e.seen.get(t);if(null===n.ref)return;const s=n.def??n.schema,o={...s},a=n.ref;if(n.ref=null,a){r(a);const n=e.seen.get(a),i=n.schema;if(!i.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Object.assign(s,i):(s.allOf=s.allOf??[],s.allOf.push(i)),Object.assign(s,o),t._zod.parent===a)for(const e in s)"$ref"!==e&&"allOf"!==e&&(e in o||delete s[e]);if(i.$ref&&n.def)for(const e in s)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(s[e])===JSON.stringify(n.def[e])&&delete s[e]}const i=t._zod.parent;if(i&&i!==a){r(i);const t=e.seen.get(i);if(t?.schema.$ref&&(s.$ref=t.schema.$ref,t.def))for(const e in s)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(s[e])===JSON.stringify(t.def[e])&&delete s[e]}e.override({zodSchema:t,jsonSchema:s,path:n.path??[]})};for(const t of[...e.seen.entries()].reverse())r(t[0]);const s={};if("draft-2020-12"===e.target?s.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?s.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?s.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const n=e.external.registry.get(t)?.id;if(!n)throw new Error("Schema is missing an `id` property");s.$id=e.external.uri(n)}Object.assign(s,n.def??n.schema);const o=e.external?.defs??{};for(const t of e.seen.entries()){const e=t[1];e.def&&e.defId&&(o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&("draft-2020-12"===e.target?s.$defs=o:s.definitions=o);try{const n=JSON.parse(JSON.stringify(s));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:Io(t,"input",e.processors),output:Io(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(e){throw new Error("Error converting schema to JSON.")}}function No(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if("transform"===r.type)return!0;if("array"===r.type)return No(r.element,n);if("set"===r.type)return No(r.valueType,n);if("lazy"===r.type)return No(r.getter(),n);if("promise"===r.type||"optional"===r.type||"nonoptional"===r.type||"nullable"===r.type||"readonly"===r.type||"default"===r.type||"prefault"===r.type)return No(r.innerType,n);if("intersection"===r.type)return No(r.left,n)||No(r.right,n);if("record"===r.type||"map"===r.type)return No(r.keyType,n)||No(r.valueType,n);if("pipe"===r.type)return No(r.in,n)||No(r.out,n);if("object"===r.type){for(const e in r.shape)if(No(r.shape[e],n))return!0;return!1}if("union"===r.type){for(const e of r.options)if(No(e,n))return!0;return!1}if("tuple"===r.type){for(const e of r.items)if(No(e,n))return!0;return!(!r.rest||!No(r.rest,n))}return!1}const Io=(e,t,n={})=>r=>{const{libraryOptions:s,target:o}=r??{},a=So({...s??{},target:o,io:t,processors:n});return To(e,a),Oo(a,e),xo(a,e)},Ro={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Po=(e,t,n,r)=>{const s=n;s.type="string";const{minimum:o,maximum:a,format:i,patterns:c,contentEncoding:d}=e._zod.bag;if("number"==typeof o&&(s.minLength=o),"number"==typeof a&&(s.maxLength=a),i&&(s.format=Ro[i]??i,""===s.format&&delete s.format,"time"===i&&delete s.format),d&&(s.contentEncoding=d),c&&c.size>0){const e=[...c];1===e.length?s.pattern=e[0].source:e.length>1&&(s.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}},Co=(e,t,n,r)=>{const s=n,{minimum:o,maximum:a,format:i,multipleOf:c,exclusiveMaximum:d,exclusiveMinimum:u}=e._zod.bag;"string"==typeof i&&i.includes("int")?s.type="integer":s.type="number","number"==typeof u&&("draft-04"===t.target||"openapi-3.0"===t.target?(s.minimum=u,s.exclusiveMinimum=!0):s.exclusiveMinimum=u),"number"==typeof o&&(s.minimum=o,"number"==typeof u&&"draft-04"!==t.target&&(u>=o?delete s.minimum:delete s.exclusiveMinimum)),"number"==typeof d&&("draft-04"===t.target||"openapi-3.0"===t.target?(s.maximum=d,s.exclusiveMaximum=!0):s.exclusiveMaximum=d),"number"==typeof a&&(s.maximum=a,"number"==typeof d&&"draft-04"!==t.target&&(d<=a?delete s.maximum:delete s.exclusiveMaximum)),"number"==typeof c&&(s.multipleOf=c)},jo=(e,t,n,r)=>{n.type="boolean"},zo=(e,t,n,r)=>{"openapi-3.0"===t.target?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},Ao=(e,t,n,r)=>{n.not={}},Mo=(e,t,n,r)=>{const s=_n(e._zod.def.entries);s.every(e=>"number"==typeof e)&&(n.type="number"),s.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=s},Do=(e,t,n,r)=>{const s=e._zod.def,o=[];for(const e of s.values)if(void 0===e){if("throw"===t.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof e){if("throw"===t.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");o.push(Number(e))}else o.push(e);if(0===o.length);else if(1===o.length){const e=o[0];n.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?n.enum=[e]:n.const=e}else o.every(e=>"number"==typeof e)&&(n.type="number"),o.every(e=>"string"==typeof e)&&(n.type="string"),o.every(e=>"boolean"==typeof e)&&(n.type="boolean"),o.every(e=>null===e)&&(n.type="null"),n.enum=o},Lo=(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")},Zo=(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")},Fo=(e,t,n,r)=>{const s=n,o=e._zod.def,{minimum:a,maximum:i}=e._zod.bag;"number"==typeof a&&(s.minItems=a),"number"==typeof i&&(s.maxItems=i),s.type="array",s.items=To(o.element,t,{...r,path:[...r.path,"items"]})},Uo=(e,t,n,r)=>{const s=n,o=e._zod.def;s.type="object",s.properties={};const a=o.shape;for(const e in a)s.properties[e]=To(a[e],t,{...r,path:[...r.path,"properties",e]});const i=new Set(Object.keys(a)),c=new Set([...i].filter(e=>{const n=o.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));c.size>0&&(s.required=Array.from(c)),"never"===o.catchall?._zod.def.type?s.additionalProperties=!1:o.catchall?o.catchall&&(s.additionalProperties=To(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(s.additionalProperties=!1)},qo=(e,t,n,r)=>{const s=e._zod.def,o=!1===s.inclusive,a=s.options.map((e,n)=>To(e,t,{...r,path:[...r.path,o?"oneOf":"anyOf",n]}));o?n.oneOf=a:n.anyOf=a},Ho=(e,t,n,r)=>{const s=e._zod.def,o=To(s.left,t,{...r,path:[...r.path,"allOf",0]}),a=To(s.right,t,{...r,path:[...r.path,"allOf",1]}),i=e=>"allOf"in e&&1===Object.keys(e).length,c=[...i(o)?o.allOf:[o],...i(a)?a.allOf:[a]];n.allOf=c},Vo=(e,t,n,r)=>{const s=n,o=e._zod.def;s.type="object";const a=o.keyType,i=a._zod.bag,c=i?.patterns;if("loose"===o.mode&&c&&c.size>0){const e=To(o.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});s.patternProperties={};for(const t of c)s.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(s.propertyNames=To(o.keyType,t,{...r,path:[...r.path,"propertyNames"]})),s.additionalProperties=To(o.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const d=a._zod.values;if(d){const e=[...d].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(s.required=e)}},Jo=(e,t,n,r)=>{const s=e._zod.def,o=To(s.innerType,t,r),a=t.seen.get(e);"openapi-3.0"===t.target?(a.ref=s.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]},Ko=(e,t,n,r)=>{const s=e._zod.def;To(s.innerType,t,r),t.seen.get(e).ref=s.innerType},Bo=(e,t,n,r)=>{const s=e._zod.def;To(s.innerType,t,r),t.seen.get(e).ref=s.innerType,n.default=JSON.parse(JSON.stringify(s.defaultValue))},Wo=(e,t,n,r)=>{const s=e._zod.def;To(s.innerType,t,r),t.seen.get(e).ref=s.innerType,"input"===t.io&&(n._prefault=JSON.parse(JSON.stringify(s.defaultValue)))},Go=(e,t,n,r)=>{const s=e._zod.def;let o;To(s.innerType,t,r),t.seen.get(e).ref=s.innerType;try{o=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=o},Xo=(e,t,n,r)=>{const s=e._zod.def,o="input"===t.io?"transform"===s.in._zod.def.type?s.out:s.in:s.out;To(o,t,r),t.seen.get(e).ref=o},Yo=(e,t,n,r)=>{const s=e._zod.def;To(s.innerType,t,r),t.seen.get(e).ref=s.innerType,n.readOnly=!0},Qo=(e,t,n,r)=>{const s=e._zod.def;To(s.innerType,t,r),t.seen.get(e).ref=s.innerType},ea={string:Po,number:Co,boolean:jo,bigint:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("BigInt cannot be represented in JSON Schema")},symbol:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Symbols cannot be represented in JSON Schema")},null:zo,undefined:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Undefined cannot be represented in JSON Schema")},void:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Void cannot be represented in JSON Schema")},never:Ao,any:(e,t,n,r)=>{},unknown:(e,t,n,r)=>{},date:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Date cannot be represented in JSON Schema")},enum:Mo,literal:Do,nan:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("NaN cannot be represented in JSON Schema")},template_literal:(e,t,n,r)=>{const s=n,o=e._zod.pattern;if(!o)throw new Error("Pattern not found in template literal");s.type="string",s.pattern=o.source},file:(e,t,n,r)=>{const s=n,o={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:i,mime:c}=e._zod.bag;void 0!==a&&(o.minLength=a),void 0!==i&&(o.maxLength=i),c?1===c.length?(o.contentMediaType=c[0],Object.assign(s,o)):(Object.assign(s,o),s.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(s,o)},success:(e,t,n,r)=>{n.type="boolean"},custom:Lo,function:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Function types cannot be represented in JSON Schema")},transform:Zo,map:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Map cannot be represented in JSON Schema")},set:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Set cannot be represented in JSON Schema")},array:Fo,object:Uo,union:qo,intersection:Ho,tuple:(e,t,n,r)=>{const s=n,o=e._zod.def;s.type="array";const a="draft-2020-12"===t.target?"prefixItems":"items",i="draft-2020-12"===t.target||"openapi-3.0"===t.target?"items":"additionalItems",c=o.items.map((e,n)=>To(e,t,{...r,path:[...r.path,a,n]})),d=o.rest?To(o.rest,t,{...r,path:[...r.path,i,..."openapi-3.0"===t.target?[o.items.length]:[]]}):null;"draft-2020-12"===t.target?(s.prefixItems=c,d&&(s.items=d)):"openapi-3.0"===t.target?(s.items={anyOf:c},d&&s.items.anyOf.push(d),s.minItems=c.length,d||(s.maxItems=c.length)):(s.items=c,d&&(s.additionalItems=d));const{minimum:u,maximum:l}=e._zod.bag;"number"==typeof u&&(s.minItems=u),"number"==typeof l&&(s.maxItems=l)},record:Vo,nullable:Jo,nonoptional:Ko,default:Bo,prefault:Wo,catch:Go,pipe:Xo,readonly:Yo,promise:(e,t,n,r)=>{const s=e._zod.def;To(s.innerType,t,r),t.seen.get(e).ref=s.innerType},optional:Qo,lazy:(e,t,n,r)=>{const s=e._zod.innerType;To(s,t,r),t.seen.get(e).ref=s}},ta=hn("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");es.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>Bn(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Yn(e,t,n),e.parseAsync=async(t,n)=>Gn(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>er(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>zn(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.apply=t=>t(e)}),na=hn("ZodMiniObject",(e,t)=>{Ds.init(e,t),ta.init(e,t),$n(e,"shape",()=>t.shape)});function ra(e,t){const n={type:"object",shape:e??{},...An(t)};return new na(n)}function sa(e){return!!e._zod}function oa(e){const t=Object.values(e);if(0===t.length)return ra({});const n=t.every(sa),r=t.every(e=>!sa(e));if(n)return ra(e);if(r)return pn(e);throw new Error("Mixed Zod versions detected in object shape.")}function aa(e,t){return sa(e)?Yn(e,t):e.safeParse(t)}async function ia(e,t){if(sa(e))return await er(e,t);const n=e;return await n.safeParseAsync(t)}function ca(e){if(!e)return;let t;if(sa(e)){const n=e;t=n._zod?.def?.shape}else t=e.shape;if(t){if("function"==typeof t)try{return t()}catch{return}return t}}function da(e){if(e){if("object"==typeof e){const t=e;if(!e._def&&!t._zod){const t=Object.values(e);if(t.length>0&&t.every(e=>"object"==typeof e&&null!==e&&(void 0!==e._def||void 0!==e._zod||"function"==typeof e.parse)))return oa(e)}}if(sa(e)){const t=e,n=t._zod?.def;if(n&&("object"===n.type||void 0!==n.shape))return e}else if(void 0!==e.shape)return e}}function ua(e){if(e&&"object"==typeof e){if("message"in e&&"string"==typeof e.message)return e.message;if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0){const t=e.issues[0];if(t&&"object"==typeof t&&"message"in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function la(e){if(sa(e)){const t=e,n=t._zod?.def;if(n){if(void 0!==n.value)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}}const t=e._def;if(t){if(void 0!==t.value)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}const n=e.value;if(void 0!==n)return n}const pa=hn("ZodISODateTime",(e,t)=>{ms.init(e,t),ja.init(e,t)});function ha(e){return function(e,t){return new pa({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...An(t)})}(0,e)}const ma=hn("ZodISODate",(e,t)=>{fs.init(e,t),ja.init(e,t)});const fa=hn("ZodISOTime",(e,t)=>{gs.init(e,t),ja.init(e,t)});const ga=hn("ZodISODuration",(e,t)=>{ys.init(e,t),ja.init(e,t)});const ya=hn("ZodError",(e,t)=>{Vn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t=e=>e.message){const n={_errors:[]},r=e=>{for(const s of e.issues)if("invalid_union"===s.code&&s.errors.length)s.errors.map(e=>r({issues:e}));else if("invalid_key"===s.code)r({issues:s.issues});else if("invalid_element"===s.code)r({issues:s.issues});else if(0===s.path.length)n._errors.push(t(s));else{let e=n,r=0;for(;r<s.path.length;){const n=s.path[r];r===s.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(s))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(e),n}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const n={},r=[];for(const s of e.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(t(s))):r.push(t(s));return{formErrors:r,fieldErrors:n}}(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,vn,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,vn,2)}},isEmpty:{get:()=>0===e.issues.length}})},{Parent:Error}),_a=Kn(ya),va=Wn(ya),wa=Xn(ya),ba=Qn(ya),ka=tr(ya),Ea=nr(ya),$a=rr(ya),Sa=sr(ya),Ta=or(ya),Oa=ar(ya),xa=ir(ya),Na=cr(ya),Ia=hn("ZodType",(e,t)=>(es.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Io(e,"input"),output:Io(e,"output")}}),e.toJSONSchema=((e,t={})=>n=>{const r=So({...n,processors:t});return To(e,r),Oo(r,e),xo(r,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(Tn(t,{checks:[...t.checks??[],...n.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0}),e.with=e.check,e.clone=(t,n)=>zn(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.parse=(t,n)=>_a(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>wa(e,t,n),e.parseAsync=async(t,n)=>va(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>ba(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>ka(e,t,n),e.decode=(t,n)=>Ea(e,t,n),e.encodeAsync=async(t,n)=>$a(e,t,n),e.decodeAsync=async(t,n)=>Sa(e,t,n),e.safeEncode=(t,n)=>Ta(e,t,n),e.safeDecode=(t,n)=>Oa(e,t,n),e.safeEncodeAsync=async(t,n)=>xa(e,t,n),e.safeDecodeAsync=async(t,n)=>Na(e,t,n),e.refine=(t,n)=>e.check(function(e,t={}){return function(e,t,n){return new Ui({type:"custom",check:"custom",fn:t,...An(n)})}(0,e,t)}(t,n)),e.superRefine=t=>e.check(function(e){const t=function(e){const t=new zr({check:"custom",...An(void 0)});return t._zod.check=e,t}(n=>(n.addIssue=e=>{if("string"==typeof e)n.issues.push(qn(e,n.value,t._zod.def));else{const r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push(qn(r))}},e(n.value,n)));return t}(t)),e.overwrite=t=>e.check($o(t)),e.optional=()=>Ri(e),e.exactOptional=()=>new Pi({type:"optional",innerType:e}),e.nullable=()=>ji(e),e.nullish=()=>Ri(ji(e)),e.nonoptional=t=>function(e,t){return new Mi({type:"nonoptional",innerType:e,...An(t)})}(e,t),e.array=()=>pi(e),e.or=t=>yi([e,t]),e.and=t=>bi(e,t),e.transform=t=>Zi(e,Ni(t)),e.default=t=>{return n=t,new zi({type:"default",innerType:e,get defaultValue(){return"function"==typeof n?n():Pn(n)}});var n},e.prefault=t=>{return n=t,new Ai({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof n?n():Pn(n)}});var n},e.catch=t=>{return new Di({type:"catch",innerType:e,catchValue:"function"==typeof(n=t)?n:()=>n});var n},e.pipe=t=>Zi(e,t),e.readonly=()=>new Fi({type:"readonly",innerType:e}),e.describe=t=>{const n=e.clone();return mo.add(n,{description:t}),n},Object.defineProperty(e,"description",{get:()=>mo.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return mo.get(e);const n=e.clone();return mo.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),Ra=hn("_ZodString",(e,t)=>{ts.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Po(e,t,n);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(function(e,t){return new Vr({check:"string_format",format:"regex",...An(t),pattern:e})}(...t)),e.includes=(...t)=>e.check(function(e,t){return new Br({check:"string_format",format:"includes",...An(t),includes:e})}(...t)),e.startsWith=(...t)=>e.check(function(e,t){return new Wr({check:"string_format",format:"starts_with",...An(t),prefix:e})}(...t)),e.endsWith=(...t)=>e.check(function(e,t){return new Gr({check:"string_format",format:"ends_with",...An(t),suffix:e})}(...t)),e.min=(...t)=>e.check(ko(...t)),e.max=(...t)=>e.check(bo(...t)),e.length=(...t)=>e.check(Eo(...t)),e.nonempty=(...t)=>e.check(ko(1,...t)),e.lowercase=t=>e.check(function(e){return new Jr({check:"string_format",format:"lowercase",...An(e)})}(t)),e.uppercase=t=>e.check(function(e){return new Kr({check:"string_format",format:"uppercase",...An(e)})}(t)),e.trim=()=>e.check($o(e=>e.trim())),e.normalize=(...t)=>e.check(function(e){return $o(t=>t.normalize(e))}(...t)),e.toLowerCase=()=>e.check($o(e=>e.toLowerCase())),e.toUpperCase=()=>e.check($o(e=>e.toUpperCase())),e.slugify=()=>e.check($o(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}),Pa=hn("ZodString",(e,t)=>{ts.init(e,t),Ra.init(e,t),e.email=t=>e.check(function(e,t){return new za({type:"string",format:"email",check:"string_format",abort:!1,...An(t)})}(0,t)),e.url=t=>e.check(function(e,t){return new Da({type:"string",format:"url",check:"string_format",abort:!1,...An(t)})}(0,t)),e.jwt=t=>e.check(function(e,t){return new Qa({type:"string",format:"jwt",check:"string_format",abort:!1,...An(t)})}(0,t)),e.emoji=t=>e.check(function(e,t){return new La({type:"string",format:"emoji",check:"string_format",abort:!1,...An(t)})}(0,t)),e.guid=t=>e.check(fo(Aa,t)),e.uuid=t=>e.check(function(e,t){return new Ma({type:"string",format:"uuid",check:"string_format",abort:!1,...An(t)})}(0,t)),e.uuidv4=t=>e.check(function(e,t){return new Ma({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...An(t)})}(0,t)),e.uuidv6=t=>e.check(function(e,t){return new Ma({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...An(t)})}(0,t)),e.uuidv7=t=>e.check(function(e,t){return new Ma({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...An(t)})}(0,t)),e.nanoid=t=>e.check(function(e,t){return new Za({type:"string",format:"nanoid",check:"string_format",abort:!1,...An(t)})}(0,t)),e.guid=t=>e.check(fo(Aa,t)),e.cuid=t=>e.check(function(e,t){return new Fa({type:"string",format:"cuid",check:"string_format",abort:!1,...An(t)})}(0,t)),e.cuid2=t=>e.check(function(e,t){return new Ua({type:"string",format:"cuid2",check:"string_format",abort:!1,...An(t)})}(0,t)),e.ulid=t=>e.check(function(e,t){return new qa({type:"string",format:"ulid",check:"string_format",abort:!1,...An(t)})}(0,t)),e.base64=t=>e.check(function(e,t){return new Ga({type:"string",format:"base64",check:"string_format",abort:!1,...An(t)})}(0,t)),e.base64url=t=>e.check(function(e,t){return new Xa({type:"string",format:"base64url",check:"string_format",abort:!1,...An(t)})}(0,t)),e.xid=t=>e.check(function(e,t){return new Ha({type:"string",format:"xid",check:"string_format",abort:!1,...An(t)})}(0,t)),e.ksuid=t=>e.check(function(e,t){return new Va({type:"string",format:"ksuid",check:"string_format",abort:!1,...An(t)})}(0,t)),e.ipv4=t=>e.check(function(e,t){return new Ja({type:"string",format:"ipv4",check:"string_format",abort:!1,...An(t)})}(0,t)),e.ipv6=t=>e.check(function(e,t){return new Ka({type:"string",format:"ipv6",check:"string_format",abort:!1,...An(t)})}(0,t)),e.cidrv4=t=>e.check(function(e,t){return new Ba({type:"string",format:"cidrv4",check:"string_format",abort:!1,...An(t)})}(0,t)),e.cidrv6=t=>e.check(function(e,t){return new Wa({type:"string",format:"cidrv6",check:"string_format",abort:!1,...An(t)})}(0,t)),e.e164=t=>e.check(function(e,t){return new Ya({type:"string",format:"e164",check:"string_format",abort:!1,...An(t)})}(0,t)),e.datetime=t=>e.check(ha(t)),e.date=t=>e.check(function(e){return function(e,t){return new ma({type:"string",format:"date",check:"string_format",...An(t)})}(0,e)}(t)),e.time=t=>e.check(function(e){return function(e,t){return new fa({type:"string",format:"time",check:"string_format",precision:null,...An(t)})}(0,e)}(t)),e.duration=t=>e.check(function(e){return function(e,t){return new ga({type:"string",format:"duration",check:"string_format",...An(t)})}(0,e)}(t))});function Ca(e){return function(e,t){return new Pa({type:"string",...An(t)})}(0,e)}const ja=hn("ZodStringFormat",(e,t)=>{ns.init(e,t),Ra.init(e,t)}),za=hn("ZodEmail",(e,t)=>{os.init(e,t),ja.init(e,t)}),Aa=hn("ZodGUID",(e,t)=>{rs.init(e,t),ja.init(e,t)}),Ma=hn("ZodUUID",(e,t)=>{ss.init(e,t),ja.init(e,t)}),Da=hn("ZodURL",(e,t)=>{as.init(e,t),ja.init(e,t)}),La=hn("ZodEmoji",(e,t)=>{is.init(e,t),ja.init(e,t)}),Za=hn("ZodNanoID",(e,t)=>{cs.init(e,t),ja.init(e,t)}),Fa=hn("ZodCUID",(e,t)=>{ds.init(e,t),ja.init(e,t)}),Ua=hn("ZodCUID2",(e,t)=>{us.init(e,t),ja.init(e,t)}),qa=hn("ZodULID",(e,t)=>{ls.init(e,t),ja.init(e,t)}),Ha=hn("ZodXID",(e,t)=>{ps.init(e,t),ja.init(e,t)}),Va=hn("ZodKSUID",(e,t)=>{hs.init(e,t),ja.init(e,t)}),Ja=hn("ZodIPv4",(e,t)=>{_s.init(e,t),ja.init(e,t)}),Ka=hn("ZodIPv6",(e,t)=>{vs.init(e,t),ja.init(e,t)}),Ba=hn("ZodCIDRv4",(e,t)=>{ws.init(e,t),ja.init(e,t)}),Wa=hn("ZodCIDRv6",(e,t)=>{bs.init(e,t),ja.init(e,t)}),Ga=hn("ZodBase64",(e,t)=>{Es.init(e,t),ja.init(e,t)}),Xa=hn("ZodBase64URL",(e,t)=>{$s.init(e,t),ja.init(e,t)}),Ya=hn("ZodE164",(e,t)=>{Ss.init(e,t),ja.init(e,t)}),Qa=hn("ZodJWT",(e,t)=>{Ts.init(e,t),ja.init(e,t)}),ei=hn("ZodNumber",(e,t)=>{Os.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Co(e,t,n),e.gt=(t,n)=>e.check(_o(t,n)),e.gte=(t,n)=>e.check(vo(t,n)),e.min=(t,n)=>e.check(vo(t,n)),e.lt=(t,n)=>e.check(go(t,n)),e.lte=(t,n)=>e.check(yo(t,n)),e.max=(t,n)=>e.check(yo(t,n)),e.int=t=>e.check(ri(t)),e.safe=t=>e.check(ri(t)),e.positive=t=>e.check(_o(0,t)),e.nonnegative=t=>e.check(vo(0,t)),e.negative=t=>e.check(go(0,t)),e.nonpositive=t=>e.check(yo(0,t)),e.multipleOf=(t,n)=>e.check(wo(t,n)),e.step=(t,n)=>e.check(wo(t,n)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function ti(e){return function(e,t){return new ei({type:"number",checks:[],...An(t)})}(0,e)}const ni=hn("ZodNumberFormat",(e,t)=>{xs.init(e,t),ei.init(e,t)});function ri(e){return function(e,t){return new ni({type:"number",check:"number_format",abort:!1,format:"safeint",...An(t)})}(0,e)}const si=hn("ZodBoolean",(e,t)=>{Ns.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(e,t,n)=>jo(0,0,t)});function oi(e){return function(e,t){return new si({type:"boolean",...An(t)})}(0,e)}const ai=hn("ZodNull",(e,t)=>{Is.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(e,t,n)=>zo(0,e,t)});function ii(e){return function(e,t){return new ai({type:"null",...An(t)})}(0,e)}const ci=hn("ZodUnknown",(e,t)=>{Rs.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function di(){return new ci({type:"unknown"})}const ui=hn("ZodNever",(e,t)=>{Ps.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(e,t,n)=>Ao(0,0,t)});const li=hn("ZodArray",(e,t)=>{js.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fo(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(ko(t,n)),e.nonempty=t=>e.check(ko(1,t)),e.max=(t,n)=>e.check(bo(t,n)),e.length=(t,n)=>e.check(Eo(t,n)),e.unwrap=()=>e.element});function pi(e,t){return function(e,t,n){return new li({type:"array",element:t,...An(n)})}(0,e,t)}const hi=hn("ZodObject",(e,t)=>{Ls.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Uo(e,t,n,r),$n(e,"shape",()=>t.shape),e.keyof=()=>Si(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:di()}),e.loose=()=>e.clone({...e._zod.def,catchall:di()}),e.strict=()=>{return e.clone({...e._zod.def,catchall:function(e,t){return new ui({type:"never",...An(t)})}(0,t)});var t},e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!Rn(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const n=e._zod.def.shape;for(const e in t)if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const r=Tn(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Sn(this,"shape",n),n}});return zn(e,r)}(e,t),e.safeExtend=t=>function(e,t){if(!Rn(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Tn(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Sn(this,"shape",n),n}});return zn(e,n)}(e,t),e.merge=t=>function(e,t){const n=Tn(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Sn(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return zn(e,n)}(e,t),e.pick=t=>function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return zn(e,Tn(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Sn(this,"shape",e),e},checks:[]}))}(e,t),e.omit=t=>function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const s=Tn(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Sn(this,"shape",r),r},checks:[]});return zn(e,s)}(e,t),e.partial=(...t)=>function(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const s=Tn(t._zod.def,{get shape(){const r=t._zod.def.shape,s={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(s[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)s[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return Sn(this,"shape",s),s},checks:[]});return zn(t,s)}(Ii,e,t[0]),e.required=(...t)=>function(e,t,n){const r=Tn(t._zod.def,{get shape(){const r=t._zod.def.shape,s={...r};if(n)for(const t in n){if(!(t in s))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(s[t]=new e({type:"nonoptional",innerType:r[t]}))}else for(const t in r)s[t]=new e({type:"nonoptional",innerType:r[t]});return Sn(this,"shape",s),s}});return zn(t,r)}(Mi,e,t[0])});function mi(e,t){const n={type:"object",shape:e??{},...An(t)};return new hi(n)}function fi(e,t){return new hi({type:"object",shape:e,catchall:di(),...An(t)})}const gi=hn("ZodUnion",(e,t)=>{Fs.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qo(e,t,n,r),e.options=t.options});function yi(e,t){return new gi({type:"union",options:e,...An(t)})}const _i=hn("ZodDiscriminatedUnion",(e,t)=>{gi.init(e,t),Us.init(e,t)});function vi(e,t,n){return new _i({type:"union",options:t,discriminator:e,...An(n)})}const wi=hn("ZodIntersection",(e,t)=>{qs.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ho(e,t,n,r)});function bi(e,t){return new wi({type:"intersection",left:e,right:t})}const ki=hn("ZodRecord",(e,t)=>{Js.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vo(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Ei(e,t,n){return new ki({type:"record",keyType:e,valueType:t,...An(n)})}const $i=hn("ZodEnum",(e,t)=>{Ks.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mo(e,0,n),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const s={};for(const r of e){if(!n.has(r))throw new Error(`Key ${r} not found in enum`);s[r]=t.entries[r]}return new $i({...t,checks:[],...An(r),entries:s})},e.exclude=(e,r)=>{const s={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete s[t]}return new $i({...t,checks:[],...An(r),entries:s})}});function Si(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new $i({type:"enum",entries:n,...An(t)})}const Ti=hn("ZodLiteral",(e,t)=>{Bs.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Do(e,t,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Oi(e,t){return new Ti({type:"literal",values:Array.isArray(e)?e:[e],...An(t)})}const xi=hn("ZodTransform",(e,t)=>{Ws.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(e,t,n)=>Zo(0,e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new fn(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(qn(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(qn(t))}};const s=t.transform(n.value,n);return s instanceof Promise?s.then(e=>(n.value=e,n)):(n.value=s,n)}});function Ni(e){return new xi({type:"transform",transform:e})}const Ii=hn("ZodOptional",(e,t)=>{Xs.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qo(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function Ri(e){return new Ii({type:"optional",innerType:e})}const Pi=hn("ZodExactOptional",(e,t)=>{Ys.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qo(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),Ci=hn("ZodNullable",(e,t)=>{Qs.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Jo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ji(e){return new Ci({type:"nullable",innerType:e})}const zi=hn("ZodDefault",(e,t)=>{eo.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),Ai=hn("ZodPrefault",(e,t)=>{no.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),Mi=hn("ZodNonOptional",(e,t)=>{ro.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ko(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),Di=hn("ZodCatch",(e,t)=>{oo.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Go(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),Li=hn("ZodPipe",(e,t)=>{ao.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xo(e,t,0,r),e.in=t.in,e.out=t.out});function Zi(e,t){return new Li({type:"pipe",in:e,out:t})}const Fi=hn("ZodReadonly",(e,t)=>{co.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),Ui=hn("ZodCustom",(e,t)=>{lo.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(e,t,n)=>Lo(0,e)});function qi(e,t){return Zi(Ni(e),t)}const Hi="2025-11-25",Vi=[Hi,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ji="io.modelcontextprotocol/related-task",Ki="2.0",Bi=function(e,t,n){const r=An(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:(e=>null!==e&&("object"==typeof e||"function"==typeof e))??(()=>!0),...r})}(Ui,0,void 0);const Wi=yi([Ca(),ti().int()]),Gi=Ca();fi({ttl:yi([ti(),ii()]).optional(),pollInterval:ti().optional()});const Xi=mi({ttl:ti().optional()}),Yi=mi({taskId:Ca()}),Qi=fi({progressToken:Wi.optional(),[Ji]:Yi.optional()}),ec=mi({_meta:Qi.optional()}),tc=ec.extend({task:Xi.optional()}),nc=mi({method:Ca(),params:ec.loose().optional()}),rc=mi({_meta:Qi.optional()}),sc=mi({method:Ca(),params:rc.loose().optional()}),oc=fi({_meta:Qi.optional()}),ac=yi([Ca(),ti().int()]),ic=mi({jsonrpc:Oi(Ki),id:ac,...nc.shape}).strict(),cc=e=>ic.safeParse(e).success,dc=mi({jsonrpc:Oi(Ki),...sc.shape}).strict(),uc=mi({jsonrpc:Oi(Ki),id:ac,result:oc}).strict(),lc=e=>uc.safeParse(e).success;var pc;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"}(pc||(pc={}));const hc=mi({jsonrpc:Oi(Ki),id:ac.optional(),error:mi({code:ti().int(),message:Ca(),data:di().optional()})}).strict(),mc=yi([ic,dc,uc,hc]);yi([uc,hc]);const fc=oc.strict(),gc=rc.extend({requestId:ac.optional(),reason:Ca().optional()}),yc=sc.extend({method:Oi("notifications/cancelled"),params:gc}),_c=mi({src:Ca(),mimeType:Ca().optional(),sizes:pi(Ca()).optional(),theme:Si(["light","dark"]).optional()}),vc=mi({icons:pi(_c).optional()}),wc=mi({name:Ca(),title:Ca().optional()}),bc=wc.extend({...wc.shape,...vc.shape,version:Ca(),websiteUrl:Ca().optional(),description:Ca().optional()}),kc=bi(mi({applyDefaults:oi().optional()}),Ei(Ca(),di())),Ec=qi(e=>e&&"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length?{form:{}}:e,bi(mi({form:kc.optional(),url:Bi.optional()}),Ei(Ca(),di()).optional())),$c=fi({list:Bi.optional(),cancel:Bi.optional(),requests:fi({sampling:fi({createMessage:Bi.optional()}).optional(),elicitation:fi({create:Bi.optional()}).optional()}).optional()}),Sc=fi({list:Bi.optional(),cancel:Bi.optional(),requests:fi({tools:fi({call:Bi.optional()}).optional()}).optional()}),Tc=mi({experimental:Ei(Ca(),Bi).optional(),sampling:mi({context:Bi.optional(),tools:Bi.optional()}).optional(),elicitation:Ec.optional(),roots:mi({listChanged:oi().optional()}).optional(),tasks:$c.optional()}),Oc=ec.extend({protocolVersion:Ca(),capabilities:Tc,clientInfo:bc}),xc=nc.extend({method:Oi("initialize"),params:Oc}),Nc=mi({experimental:Ei(Ca(),Bi).optional(),logging:Bi.optional(),completions:Bi.optional(),prompts:mi({listChanged:oi().optional()}).optional(),resources:mi({subscribe:oi().optional(),listChanged:oi().optional()}).optional(),tools:mi({listChanged:oi().optional()}).optional(),tasks:Sc.optional()}),Ic=oc.extend({protocolVersion:Ca(),capabilities:Nc,serverInfo:bc,instructions:Ca().optional()}),Rc=sc.extend({method:Oi("notifications/initialized"),params:rc.optional()}),Pc=nc.extend({method:Oi("ping"),params:ec.optional()}),Cc=mi({progress:ti(),total:Ri(ti()),message:Ri(Ca())}),jc=mi({...rc.shape,...Cc.shape,progressToken:Wi}),zc=sc.extend({method:Oi("notifications/progress"),params:jc}),Ac=ec.extend({cursor:Gi.optional()}),Mc=nc.extend({params:Ac.optional()}),Dc=oc.extend({nextCursor:Gi.optional()}),Lc=Si(["working","input_required","completed","failed","cancelled"]),Zc=mi({taskId:Ca(),status:Lc,ttl:yi([ti(),ii()]),createdAt:Ca(),lastUpdatedAt:Ca(),pollInterval:Ri(ti()),statusMessage:Ri(Ca())}),Fc=oc.extend({task:Zc}),Uc=rc.merge(Zc),qc=sc.extend({method:Oi("notifications/tasks/status"),params:Uc}),Hc=nc.extend({method:Oi("tasks/get"),params:ec.extend({taskId:Ca()})}),Vc=oc.merge(Zc),Jc=nc.extend({method:Oi("tasks/result"),params:ec.extend({taskId:Ca()})});oc.loose();const Kc=Mc.extend({method:Oi("tasks/list")}),Bc=Dc.extend({tasks:pi(Zc)}),Wc=nc.extend({method:Oi("tasks/cancel"),params:ec.extend({taskId:Ca()})}),Gc=oc.merge(Zc),Xc=mi({uri:Ca(),mimeType:Ri(Ca()),_meta:Ei(Ca(),di()).optional()}),Yc=Xc.extend({text:Ca()}),Qc=Ca().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),ed=Xc.extend({blob:Qc}),td=Si(["user","assistant"]),nd=mi({audience:pi(td).optional(),priority:ti().min(0).max(1).optional(),lastModified:ha({offset:!0}).optional()}),rd=mi({...wc.shape,...vc.shape,uri:Ca(),description:Ri(Ca()),mimeType:Ri(Ca()),annotations:nd.optional(),_meta:Ri(fi({}))}),sd=mi({...wc.shape,...vc.shape,uriTemplate:Ca(),description:Ri(Ca()),mimeType:Ri(Ca()),annotations:nd.optional(),_meta:Ri(fi({}))}),od=Mc.extend({method:Oi("resources/list")}),ad=Dc.extend({resources:pi(rd)}),id=Mc.extend({method:Oi("resources/templates/list")}),cd=Dc.extend({resourceTemplates:pi(sd)}),dd=ec.extend({uri:Ca()}),ud=dd,ld=nc.extend({method:Oi("resources/read"),params:ud}),pd=oc.extend({contents:pi(yi([Yc,ed]))}),hd=sc.extend({method:Oi("notifications/resources/list_changed"),params:rc.optional()}),md=dd,fd=nc.extend({method:Oi("resources/subscribe"),params:md}),gd=dd,yd=nc.extend({method:Oi("resources/unsubscribe"),params:gd}),_d=rc.extend({uri:Ca()}),vd=sc.extend({method:Oi("notifications/resources/updated"),params:_d}),wd=mi({name:Ca(),description:Ri(Ca()),required:Ri(oi())}),bd=mi({...wc.shape,...vc.shape,description:Ri(Ca()),arguments:Ri(pi(wd)),_meta:Ri(fi({}))}),kd=Mc.extend({method:Oi("prompts/list")}),Ed=Dc.extend({prompts:pi(bd)}),$d=ec.extend({name:Ca(),arguments:Ei(Ca(),Ca()).optional()}),Sd=nc.extend({method:Oi("prompts/get"),params:$d}),Td=mi({type:Oi("text"),text:Ca(),annotations:nd.optional(),_meta:Ei(Ca(),di()).optional()}),Od=mi({type:Oi("image"),data:Qc,mimeType:Ca(),annotations:nd.optional(),_meta:Ei(Ca(),di()).optional()}),xd=mi({type:Oi("audio"),data:Qc,mimeType:Ca(),annotations:nd.optional(),_meta:Ei(Ca(),di()).optional()}),Nd=mi({type:Oi("tool_use"),name:Ca(),id:Ca(),input:Ei(Ca(),di()),_meta:Ei(Ca(),di()).optional()}),Id=mi({type:Oi("resource"),resource:yi([Yc,ed]),annotations:nd.optional(),_meta:Ei(Ca(),di()).optional()}),Rd=yi([Td,Od,xd,rd.extend({type:Oi("resource_link")}),Id]),Pd=mi({role:td,content:Rd}),Cd=oc.extend({description:Ca().optional(),messages:pi(Pd)}),jd=sc.extend({method:Oi("notifications/prompts/list_changed"),params:rc.optional()}),zd=mi({title:Ca().optional(),readOnlyHint:oi().optional(),destructiveHint:oi().optional(),idempotentHint:oi().optional(),openWorldHint:oi().optional()}),Ad=mi({taskSupport:Si(["required","optional","forbidden"]).optional()}),Md=mi({...wc.shape,...vc.shape,description:Ca().optional(),inputSchema:mi({type:Oi("object"),properties:Ei(Ca(),Bi).optional(),required:pi(Ca()).optional()}).catchall(di()),outputSchema:mi({type:Oi("object"),properties:Ei(Ca(),Bi).optional(),required:pi(Ca()).optional()}).catchall(di()).optional(),annotations:zd.optional(),execution:Ad.optional(),_meta:Ei(Ca(),di()).optional()}),Dd=Mc.extend({method:Oi("tools/list")}),Ld=Dc.extend({tools:pi(Md)}),Zd=oc.extend({content:pi(Rd).default([]),structuredContent:Ei(Ca(),di()).optional(),isError:oi().optional()});Zd.or(oc.extend({toolResult:di()}));const Fd=tc.extend({name:Ca(),arguments:Ei(Ca(),di()).optional()}),Ud=nc.extend({method:Oi("tools/call"),params:Fd}),qd=sc.extend({method:Oi("notifications/tools/list_changed"),params:rc.optional()});mi({autoRefresh:oi().default(!0),debounceMs:ti().int().nonnegative().default(300)});const Hd=Si(["debug","info","notice","warning","error","critical","alert","emergency"]),Vd=ec.extend({level:Hd}),Jd=nc.extend({method:Oi("logging/setLevel"),params:Vd}),Kd=rc.extend({level:Hd,logger:Ca().optional(),data:di()}),Bd=sc.extend({method:Oi("notifications/message"),params:Kd}),Wd=mi({name:Ca().optional()}),Gd=mi({hints:pi(Wd).optional(),costPriority:ti().min(0).max(1).optional(),speedPriority:ti().min(0).max(1).optional(),intelligencePriority:ti().min(0).max(1).optional()}),Xd=mi({mode:Si(["auto","required","none"]).optional()}),Yd=mi({type:Oi("tool_result"),toolUseId:Ca().describe("The unique identifier for the corresponding tool call."),content:pi(Rd).default([]),structuredContent:mi({}).loose().optional(),isError:oi().optional(),_meta:Ei(Ca(),di()).optional()}),Qd=vi("type",[Td,Od,xd]),eu=vi("type",[Td,Od,xd,Nd,Yd]),tu=mi({role:td,content:yi([eu,pi(eu)]),_meta:Ei(Ca(),di()).optional()}),nu=tc.extend({messages:pi(tu),modelPreferences:Gd.optional(),systemPrompt:Ca().optional(),includeContext:Si(["none","thisServer","allServers"]).optional(),temperature:ti().optional(),maxTokens:ti().int(),stopSequences:pi(Ca()).optional(),metadata:Bi.optional(),tools:pi(Md).optional(),toolChoice:Xd.optional()}),ru=nc.extend({method:Oi("sampling/createMessage"),params:nu}),su=oc.extend({model:Ca(),stopReason:Ri(Si(["endTurn","stopSequence","maxTokens"]).or(Ca())),role:td,content:Qd}),ou=oc.extend({model:Ca(),stopReason:Ri(Si(["endTurn","stopSequence","maxTokens","toolUse"]).or(Ca())),role:td,content:yi([eu,pi(eu)])}),au=mi({type:Oi("boolean"),title:Ca().optional(),description:Ca().optional(),default:oi().optional()}),iu=mi({type:Oi("string"),title:Ca().optional(),description:Ca().optional(),minLength:ti().optional(),maxLength:ti().optional(),format:Si(["email","uri","date","date-time"]).optional(),default:Ca().optional()}),cu=mi({type:Si(["number","integer"]),title:Ca().optional(),description:Ca().optional(),minimum:ti().optional(),maximum:ti().optional(),default:ti().optional()}),du=mi({type:Oi("string"),title:Ca().optional(),description:Ca().optional(),enum:pi(Ca()),default:Ca().optional()}),uu=mi({type:Oi("string"),title:Ca().optional(),description:Ca().optional(),oneOf:pi(mi({const:Ca(),title:Ca()})),default:Ca().optional()}),lu=mi({type:Oi("string"),title:Ca().optional(),description:Ca().optional(),enum:pi(Ca()),enumNames:pi(Ca()).optional(),default:Ca().optional()}),pu=yi([du,uu]),hu=yi([mi({type:Oi("array"),title:Ca().optional(),description:Ca().optional(),minItems:ti().optional(),maxItems:ti().optional(),items:mi({type:Oi("string"),enum:pi(Ca())}),default:pi(Ca()).optional()}),mi({type:Oi("array"),title:Ca().optional(),description:Ca().optional(),minItems:ti().optional(),maxItems:ti().optional(),items:mi({anyOf:pi(mi({const:Ca(),title:Ca()}))}),default:pi(Ca()).optional()})]),mu=yi([lu,pu,hu]),fu=yi([mu,au,iu,cu]),gu=yi([tc.extend({mode:Oi("form").optional(),message:Ca(),requestedSchema:mi({type:Oi("object"),properties:Ei(Ca(),fu),required:pi(Ca()).optional()})}),tc.extend({mode:Oi("url"),message:Ca(),elicitationId:Ca(),url:Ca().url()})]),yu=nc.extend({method:Oi("elicitation/create"),params:gu}),_u=rc.extend({elicitationId:Ca()}),vu=sc.extend({method:Oi("notifications/elicitation/complete"),params:_u}),wu=oc.extend({action:Si(["accept","decline","cancel"]),content:qi(e=>null===e?void 0:e,Ei(Ca(),yi([Ca(),ti(),oi(),pi(Ca())])).optional())}),bu=mi({type:Oi("ref/resource"),uri:Ca()}),ku=mi({type:Oi("ref/prompt"),name:Ca()}),Eu=ec.extend({ref:yi([ku,bu]),argument:mi({name:Ca(),value:Ca()}),context:mi({arguments:Ei(Ca(),Ca()).optional()}).optional()}),$u=nc.extend({method:Oi("completion/complete"),params:Eu}),Su=oc.extend({completion:fi({values:pi(Ca()).max(100),total:Ri(ti().int()),hasMore:Ri(oi())})}),Tu=mi({uri:Ca().startsWith("file://"),name:Ca().optional(),_meta:Ei(Ca(),di()).optional()}),Ou=nc.extend({method:Oi("roots/list"),params:ec.optional()}),xu=oc.extend({roots:pi(Tu)}),Nu=sc.extend({method:Oi("notifications/roots/list_changed"),params:rc.optional()});yi([Pc,xc,$u,Jd,Sd,kd,od,id,ld,fd,yd,Ud,Dd,Hc,Jc,Kc,Wc]),yi([yc,zc,Rc,Nu,qc]),yi([fc,su,ou,wu,xu,Vc,Bc,Fc]),yi([Pc,ru,yu,Ou,Hc,Jc,Kc,Wc]),yi([yc,zc,Bd,vd,hd,qd,jd,qc,vu]),yi([fc,Ic,Su,Cd,Ed,ad,cd,pd,Zd,Ld,Vc,Bc,Fc]);class Iu extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,t,n){if(e===pc.UrlElicitationRequired&&n){const e=n;if(e.elicitations)return new Ru(e.elicitations,t)}return new Iu(e,t,n)}}class Ru extends Iu{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(pc.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}function Pu(e){return"completed"===e||"failed"===e||"cancelled"===e}const Cu=Symbol("Let zodToJsonSchema decide on which parser to use"),ju={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"};function zu(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function Au(e,t,n,r,s){e[t]=n,zu(e,t,r,s)}const Mu=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};function Du(e){if("openAi"!==e.target)return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?Mu(t,e.currentPath):t.join("/")}}function Lu(e,t){return ll(e.type._def,t)}function Zu(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>Zu(e,t,n))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Fu(e,t)}}const Fu=(e,t)=>{const n={type:"integer",format:"unix-time"};if("openApi3"===t.target)return n;for(const r of e.checks)switch(r.kind){case"min":Au(n,"minimum",r.value,r.message,t);break;case"max":Au(n,"maximum",r.value,r.message,t)}return n};let Uu;const qu=/^[cC][^\s-]{8,}$/,Hu=/^[0-9a-z]+$/,Vu=/^[0-9A-HJKMNP-TV-Z]{26}$/,Ju=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,Ku=()=>(void 0===Uu&&(Uu=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Uu),Bu=/^(?:(?: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])$/,Wu=/^(([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])$/,Gu=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Xu=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Yu=/^[a-zA-Z0-9_-]{21}$/,Qu=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function el(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":Au(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,r.value):r.value,r.message,t);break;case"max":Au(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"email":switch(t.emailStrategy){case"format:email":rl(n,"email",r.message,t);break;case"format:idn-email":rl(n,"idn-email",r.message,t);break;case"pattern:zod":sl(n,Ju,r.message,t)}break;case"url":rl(n,"uri",r.message,t);break;case"uuid":rl(n,"uuid",r.message,t);break;case"regex":sl(n,r.regex,r.message,t);break;case"cuid":sl(n,qu,r.message,t);break;case"cuid2":sl(n,Hu,r.message,t);break;case"startsWith":sl(n,RegExp(`^${tl(r.value,t)}`),r.message,t);break;case"endsWith":sl(n,RegExp(`${tl(r.value,t)}$`),r.message,t);break;case"datetime":rl(n,"date-time",r.message,t);break;case"date":rl(n,"date",r.message,t);break;case"time":rl(n,"time",r.message,t);break;case"duration":rl(n,"duration",r.message,t);break;case"length":Au(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,r.value):r.value,r.message,t),Au(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"includes":sl(n,RegExp(tl(r.value,t)),r.message,t);break;case"ip":"v6"!==r.version&&rl(n,"ipv4",r.message,t),"v4"!==r.version&&rl(n,"ipv6",r.message,t);break;case"base64url":sl(n,Xu,r.message,t);break;case"jwt":sl(n,Qu,r.message,t);break;case"cidr":"v6"!==r.version&&sl(n,Bu,r.message,t),"v4"!==r.version&&sl(n,Wu,r.message,t);break;case"emoji":sl(n,Ku(),r.message,t);break;case"ulid":sl(n,Vu,r.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":rl(n,"binary",r.message,t);break;case"contentEncoding:base64":Au(n,"contentEncoding","base64",r.message,t);break;case"pattern:zod":sl(n,Gu,r.message,t)}break;case"nanoid":sl(n,Yu,r.message,t)}return n}function tl(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let n=0;n<e.length;n++)nl.has(e[n])||(t+="\\"),t+=e[n];return t}(e):e}const nl=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function rl(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):Au(e,"format",t,n,r)}function sl(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:ol(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):Au(e,"pattern",ol(t,r),n,r)}function ol(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const n=e.flags.includes("i"),r=e.flags.includes("m"),s=e.flags.includes("s"),o=n?e.source.toLowerCase():e.source;let a="",i=!1,c=!1,d=!1;for(let e=0;e<o.length;e++)if(i)a+=o[e],i=!1;else{if(n)if(c){if(o[e].match(/[a-z]/)){d?(a+=o[e],a+=`${o[e-2]}-${o[e]}`.toUpperCase(),d=!1):"-"===o[e+1]&&o[e+2]?.match(/[a-z]/)?(a+=o[e],d=!0):a+=`${o[e]}${o[e].toUpperCase()}`;continue}}else if(o[e].match(/[a-z]/)){a+=`[${o[e]}${o[e].toUpperCase()}]`;continue}if(r){if("^"===o[e]){a+="(^|(?<=[\r\n]))";continue}if("$"===o[e]){a+="($|(?=[\r\n]))";continue}}s&&"."===o[e]?a+=c?`${o[e]}\r\n`:`[${o[e]}\r\n]`:(a+=o[e],"\\"===o[e]?i=!0:c&&"]"===o[e]?c=!1:c||"["!==o[e]||(c=!0))}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return a}function al(e,t){if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&e.keyType?._def.typeName===ln.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:ll(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",r]})??Du(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const n={type:"object",additionalProperties:ll(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return n;if(e.keyType?._def.typeName===ln.ZodString&&e.keyType._def.checks?.length){const{type:r,...s}=el(e.keyType._def,t);return{...n,propertyNames:s}}if(e.keyType?._def.typeName===ln.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===ln.ZodBranded&&e.keyType._def.type._def.typeName===ln.ZodString&&e.keyType._def.type._def.checks?.length){const{type:r,...s}=Lu(e.keyType._def,t);return{...n,propertyNames:s}}return n}const il={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},cl=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>ll(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function dl(e){try{return e.isOptional()}catch{return!0}}const ul=(e,t,n)=>{switch(t){case ln.ZodString:return el(e,n);case ln.ZodNumber:return function(e,t){const n={type:"number"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"int":n.type="integer",zu(n,"type",r.message,t);break;case"min":"jsonSchema7"===t.target?r.inclusive?Au(n,"minimum",r.value,r.message,t):Au(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Au(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?Au(n,"maximum",r.value,r.message,t):Au(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Au(n,"maximum",r.value,r.message,t));break;case"multipleOf":Au(n,"multipleOf",r.value,r.message,t)}return n}(e,n);case ln.ZodObject:return function(e,t){const n="openAi"===t.target,r={type:"object",properties:{}},s=[],o=e.shape();for(const e in o){let a=o[e];if(void 0===a||void 0===a._def)continue;let i=dl(a);i&&n&&("ZodOptional"===a._def.typeName&&(a=a._def.innerType),a.isNullable()||(a=a.nullable()),i=!1);const c=ll(a._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==c&&(r.properties[e]=c,i||s.push(e))}s.length&&(r.required=s);const a=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return ll(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==a&&(r.additionalProperties=a),r}(e,n);case ln.ZodBigInt:return function(e,t){const n={type:"integer",format:"int64"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"min":"jsonSchema7"===t.target?r.inclusive?Au(n,"minimum",r.value,r.message,t):Au(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Au(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?Au(n,"maximum",r.value,r.message,t):Au(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Au(n,"maximum",r.value,r.message,t));break;case"multipleOf":Au(n,"multipleOf",r.value,r.message,t)}return n}(e,n);case ln.ZodBoolean:return{type:"boolean"};case ln.ZodDate:return Zu(e,n);case ln.ZodUndefined:return function(e){return{not:Du(e)}}(n);case ln.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(n);case ln.ZodArray:return function(e,t){const n={type:"array"};return e.type?._def&&e.type?._def?.typeName!==ln.ZodAny&&(n.items=ll(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Au(n,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Au(n,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Au(n,"minItems",e.exactLength.value,e.exactLength.message,t),Au(n,"maxItems",e.exactLength.value,e.exactLength.message,t)),n}(e,n);case ln.ZodUnion:case ln.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return cl(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in il&&(!e._def.checks||!e._def.checks.length))){const e=n.reduce((e,t)=>{const n=il[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}if(n.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){const e=n.reduce((e,t)=>{const n=typeof t._def.value;switch(n){case"string":case"number":case"boolean":return[...e,n];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===n.length){const t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return cl(e,t)}(e,n);case ln.ZodIntersection:return function(e,t){const n=[ll(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),ll(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(e=>!!e);let r="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const s=[];return n.forEach(e=>{if("type"in(t=e)&&"string"===t.type||!("allOf"in t)){let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:n,...r}=e;t=r}else r=void 0;s.push(t)}else s.push(...e.allOf),void 0===e.unevaluatedProperties&&(r=void 0);var t}),s.length?{allOf:s,...r}:void 0}(e,n);case ln.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,n)=>ll(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:ll(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>ll(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])}}(e,n);case ln.ZodRecord:return al(e,n);case ln.ZodLiteral:return function(e,t){const n=typeof e.value;return"bigint"!==n&&"number"!==n&&"boolean"!==n&&"string"!==n?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===n?"integer":n,enum:[e.value]}:{type:"bigint"===n?"integer":n,const:e.value}}(e,n);case ln.ZodEnum:return function(e){return{type:"string",enum:Array.from(e.values)}}(e);case ln.ZodNativeEnum:return function(e){const t=e.values,n=Object.keys(e.values).filter(e=>"number"!=typeof t[t[e]]).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:1===r.length?"string"===r[0]?"string":"number":["string","number"],enum:n}}(e);case ln.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:il[e.innerType._def.typeName],nullable:!0}:{type:[il[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const n=ll(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const n=ll(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}(e,n);case ln.ZodOptional:return((e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return ll(e.innerType._def,t);const n=ll(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Du(t)},n]}:Du(t)})(e,n);case ln.ZodMap:return function(e,t){return"record"===t.mapStrategy?al(e,t):{type:"array",maxItems:125,items:{type:"array",items:[ll(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Du(t),ll(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Du(t)],minItems:2,maxItems:2}}}(e,n);case ln.ZodSet:return function(e,t){const n={type:"array",uniqueItems:!0,items:ll(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Au(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Au(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}(e,n);case ln.ZodLazy:return()=>e.getter()._def;case ln.ZodPromise:return function(e,t){return ll(e.type._def,t)}(e,n);case ln.ZodNaN:case ln.ZodNever:return function(e){return"openAi"===e.target?void 0:{not:Du({...e,currentPath:[...e.currentPath,"not"]})}}(n);case ln.ZodEffects:return function(e,t){return"input"===t.effectStrategy?ll(e.schema._def,t):Du(t)}(e,n);case ln.ZodAny:return Du(n);case ln.ZodUnknown:return function(e){return Du(e)}(n);case ln.ZodDefault:return function(e,t){return{...ll(e.innerType._def,t),default:e.defaultValue()}}(e,n);case ln.ZodBranded:return Lu(e,n);case ln.ZodReadonly:case ln.ZodCatch:return((e,t)=>ll(e.innerType._def,t))(e,n);case ln.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return ll(e.in._def,t);if("output"===t.pipeStrategy)return ll(e.out._def,t);const n=ll(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[n,ll(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]})].filter(e=>void 0!==e)}})(e,n);case ln.ZodFunction:case ln.ZodVoid:case ln.ZodSymbol:default:return}};function ll(e,t,n=!1){const r=t.seen.get(e);if(t.override){const s=t.override?.(e,t,r,n);if(s!==Cu)return s}if(r&&!n){const e=pl(r,t);if(void 0!==e)return e}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const o=ul(e,e.typeName,t),a="function"==typeof o?ll(o(),t):o;if(a&&hl(e,t,a),t.postProcess){const n=t.postProcess(a,e,t);return s.jsonSchema=a,n}return s.jsonSchema=a,a}const pl=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Mu(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Du(t)):"seen"===t.$refStrategy?Du(t):void 0}},hl=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n);function ml(e,t){return sa(e)?function(e,t){if("_idmap"in e){const n=e,r=So({...t,processors:ea}),s={};for(const e of n._idmap.entries()){const[t,n]=e;To(n,r)}const o={},a={registry:n,uri:t?.uri,defs:s};r.external=a;for(const e of n._idmap.entries()){const[t,n]=e;Oo(r,n),o[t]=xo(r,n)}if(Object.keys(s).length>0){const e="draft-2020-12"===r.target?"$defs":"definitions";o.__shared={[e]:s}}return{schemas:o}}const n=So({...t,processors:ea});return To(e,n),Oo(n,e),xo(n,e)}(e,{target:(n=t?.target,n?"jsonSchema7"===n||"draft-7"===n?"draft-7":"jsonSchema2019-09"===n||"draft-2020-12"===n?"draft-2020-12":"draft-7":"draft-7"),io:t?.pipeStrategy??"input"}):((e,t)=>{const n=(e=>{const t=(e=>"string"==typeof e?{...ju,name:e}:{...ju,...e})(e),n=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}})(t);let r=t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:ll(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??Du(n)}),{}):void 0;const s="title"===t?.nameStrategy?void 0:t?.name,o=ll(e._def,void 0===s?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1)??Du(n),a=void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==a&&(o.title=a),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===n.$refStrategy?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const i=void 0===s?r?{...o,[n.definitionPath]:r}:o:{$ref:[..."relative"===n.$refStrategy?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...r,[s]:o}};return"jsonSchema7"===n.target?i.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==n.target&&"openAi"!==n.target||(i.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===n.target&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i})(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"});var n}function fl(e){const t=ca(e),n=t?.method;if(!n)throw new Error("Schema is missing a method literal");const r=la(n);if("string"!=typeof r)throw new Error("Schema method literal must be a string");return r}function gl(e,t){const n=aa(e,t);if(!n.success)throw n.error;return n.data}class yl{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(yc,e=>{this._oncancel(e)}),this.setNotificationHandler(zc,e=>{this._onprogress(e)}),this.setRequestHandler(Pc,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Hc,async(e,t)=>{const n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Iu(pc.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Jc,async(e,t)=>{const n=async()=>{const r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if("response"===e.type||"error"===e.type){const t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r)if(this._requestResolvers.delete(n),"response"===e.type)r(t);else{const e=t;r(new Iu(e.error.code,e.error.message,e.error.data))}else{const t="response"===e.type?"Response":"Error";this._onerror(new Error(`${t} handler missing for request ${n}`))}continue}await(this._transport?.send(e.message,{relatedRequestId:t.requestId}))}}const s=await this._taskStore.getTask(r,t.sessionId);if(!s)throw new Iu(pc.InvalidParams,`Task not found: ${r}`);if(!Pu(s.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(Pu(s.status)){const e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[Ji]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(Kc,async(e,t)=>{try{const{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new Iu(pc.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(Wc,async(e,t)=>{try{const n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Iu(pc.InvalidParams,`Task not found: ${e.params.taskId}`);if(Pu(n.status))throw new Iu(pc.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,"cancelled","Client cancelled task execution.",t.sessionId),this._clearTaskQueue(e.params.taskId);const r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new Iu(pc.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){if(e instanceof Iu)throw e;throw new Iu(pc.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;const t=this._requestHandlerAbortControllers.get(e.params.requestId);t?.abort(e.params.reason)}_setupTimeout(e,t,n,r,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:r})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Iu.fromError(pc.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;const t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};const n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};const r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{var n;r?.(e,t),lc(e)||(n=e,hc.safeParse(n).success)?this._onresponse(e):cc(e)?this._onrequest(e,t):(e=>dc.safeParse(e).success)(e)?this._onnotification(e):this._onerror(new Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();const t=Iu.fromError(pc.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){const t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;void 0!==t&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){const n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,s=e.params?._meta?.[Ji]?.taskId;if(void 0===n){const t={jsonrpc:"2.0",id:e.id,error:{code:pc.MethodNotFound,message:"Method not found"}};return void(s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(new Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(new Error(`Failed to send an error response: ${e}`))))}const o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);const a=(i=e.params,tc.safeParse(i).success?e.params.task:void 0);var i;const c=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,d={signal:o.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{const n={relatedRequestId:e.id};s&&(n.relatedTask={taskId:s}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{const o={...r,relatedRequestId:e.id};s&&!o.relatedTask&&(o.relatedTask={taskId:s});const a=o.relatedTask?.taskId??s;return a&&c&&await c.updateTaskStatus(a,"input_required"),await this.request(t,n,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,d)).then(async t=>{if(o.signal.aborted)return;const n={result:t,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:n,timestamp:Date.now()},r?.sessionId):await(r?.send(n))},async t=>{if(o.signal.aborted)return;const n={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:pc.InternalError,message:t.message??"Internal error",...void 0!==t.data&&{data:t.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:n,timestamp:Date.now()},r?.sessionId):await(r?.send(n))}).catch(e=>this._onerror(new Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...n}=e.params,r=Number(t),s=this._progressHandlers.get(r);if(!s)return void this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));const o=this._responseHandlers.get(r),a=this._timeoutInfo.get(r);if(a&&o&&a.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){return this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),void o(e)}s(n)}_onresponse(e){const t=Number(e.id),n=this._requestResolvers.get(t);if(n)return this._requestResolvers.delete(t),void(lc(e)?n(e):n(new Iu(e.error.code,e.error.message,e.error.data)));const r=this._responseHandlers.get(t);if(void 0===r)return void this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));this._responseHandlers.delete(t),this._cleanupTimeout(t);let s=!1;if(lc(e)&&e.result&&"object"==typeof e.result){const n=e.result;if(n.task&&"object"==typeof n.task){const e=n.task;"string"==typeof e.taskId&&(s=!0,this._taskProgressTokens.set(e.taskId,t))}}s||this._progressHandlers.delete(t),lc(e)?r(e):r(Iu.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await(this._transport?.close())}async*requestStream(e,t,n){const{task:r}=n??{};if(!r){try{const r=await this.request(e,t,n);yield{type:"result",result:r}}catch(e){yield{type:"error",error:e instanceof Iu?e:new Iu(pc.InternalError,String(e))}}return}let s;try{const r=await this.request(e,Fc,n);if(!r.task)throw new Iu(pc.InternalError,"Task creation did not return a task");for(s=r.task.taskId,yield{type:"taskCreated",task:r.task};;){const e=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:e},Pu(e.status)){if("completed"===e.status){const e=await this.getTaskResult({taskId:s},t,n);yield{type:"result",result:e}}else"failed"===e.status?yield{type:"error",error:new Iu(pc.InternalError,`Task ${s} failed`)}:"cancelled"===e.status&&(yield{type:"error",error:new Iu(pc.InternalError,`Task ${s} was cancelled`)});return}if("input_required"===e.status){const e=await this.getTaskResult({taskId:s},t,n);return void(yield{type:"result",result:e})}const r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:"error",error:e instanceof Iu?e:new Iu(pc.InternalError,String(e))}}}request(e,t,n){const{relatedRequestId:r,resumptionToken:s,onresumptiontoken:o,task:a,relatedTask:i}=n??{};return new Promise((c,d)=>{const u=e=>{d(e)};if(!this._transport)return void u(new Error("Not connected"));if(!0===this._options?.enforceStrictCapabilities)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(e){return void u(e)}n?.signal?.throwIfAborted();const l=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:l};n?.onprogress&&(this._progressHandlers.set(l,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:l}}),a&&(p.params={...p.params,task:a}),i&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Ji]:i}});const h=e=>{this._responseHandlers.delete(l),this._progressHandlers.delete(l),this._cleanupTimeout(l),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:l,reason:String(e)}},{relatedRequestId:r,resumptionToken:s,onresumptiontoken:o}).catch(e=>this._onerror(new Error(`Failed to send cancellation: ${e}`)));const t=e instanceof Iu?e:new Iu(pc.RequestTimeout,String(e));d(t)};this._responseHandlers.set(l,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return d(e);try{const n=aa(t,e.result);n.success?c(n.data):d(n.error)}catch(e){d(e)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});const m=n?.timeout??6e4;this._setupTimeout(l,m,n?.maxTotalTimeout,()=>h(Iu.fromError(pc.RequestTimeout,"Request timed out",{timeout:m})),n?.resetTimeoutOnProgress??!1);const f=i?.taskId;if(f){const e=e=>{const t=this._responseHandlers.get(l);t?t(e):this._onerror(new Error(`Response handler missing for side-channeled request ${l}`))};this._requestResolvers.set(l,e),this._enqueueTaskMessage(f,{type:"request",message:p,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(l),d(e)})}else this._transport.send(p,{relatedRequestId:r,resumptionToken:s,onresumptiontoken:o}).catch(e=>{this._cleanupTimeout(l),d(e)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},Vc,t)}async getTaskResult(e,t,n){return this.request({method:"tasks/result",params:e},t,n)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},Bc,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},Gc,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const n=t?.relatedTask?.taskId;if(n){const r={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Ji]:t.relatedTask}}};return void await this._enqueueTaskMessage(n,{type:"notification",message:r,timestamp:Date.now()})}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;return this._pendingDebouncedNotifications.add(e.method),void Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:"2.0"};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[Ji]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))})}let r={...e,jsonrpc:"2.0"};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[Ji]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){const n=fl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{const s=gl(e,n);return Promise.resolve(t(s,r))})}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,t){const n=fl(e);this._notificationHandlers.set(n,n=>{const r=gl(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const t=this._taskProgressTokens.get(e);void 0!==t&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){const n=await this._taskMessageQueue.dequeueAll(e,t);for(const t of n)if("request"===t.type&&cc(t.message)){const n=t.message.id,r=this._requestResolvers.get(n);r?(r(new Iu(pc.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(n)):this._onerror(new Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{const t=await(this._taskStore?.getTask(e));t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted)return void r(new Iu(pc.InvalidRequest,"Request cancelled"));const s=setTimeout(e,n);t.addEventListener("abort",()=>{clearTimeout(s),r(new Iu(pc.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async r=>{if(!e)throw new Error("No request provided");return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{const r=await n.getTask(e,t);if(!r)throw new Iu(pc.InvalidParams,"Failed to retrieve task: Task not found");return r},storeTaskResult:async(e,r,s)=>{await n.storeTaskResult(e,r,s,t);const o=await n.getTask(e,t);if(o){const t=qc.parse({method:"notifications/tasks/status",params:o});await this.notification(t),Pu(o.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,s)=>{const o=await n.getTask(e,t);if(!o)throw new Iu(pc.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(Pu(o.status))throw new Iu(pc.InvalidParams,`Cannot update task "${e}" from terminal status "${o.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,s,t);const a=await n.getTask(e,t);if(a){const t=qc.parse({method:"notifications/tasks/status",params:a});await this.notification(t),Pu(a.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}}function _l(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function vl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var wl,bl={exports:{}},kl={},El={},$l={},Sl={},Tl={},Ol={};function xl(){return wl||(wl=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class n extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=n;class r extends t{constructor(e){super(),this._items="string"==typeof e?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const e=this._items[0];return""===e||'""'===e}get str(){var e;return null!==(e=this._str)&&void 0!==e?e:this._str=this._items.reduce((e,t)=>`${e}${t}`,"")}get names(){var e;return null!==(e=this._names)&&void 0!==e?e:this._names=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}}function s(e,...t){const n=[e[0]];let s=0;for(;s<t.length;)i(n,t[s]),n.push(e[++s]);return new r(n)}e._Code=r,e.nil=new r(""),e._=s;const o=new r("+");function a(e,...t){const n=[d(e[0])];let s=0;for(;s<t.length;)n.push(o),i(n,t[s]),n.push(o,d(e[++s]));return function(e){let t=1;for(;t<e.length-1;){if(e[t]===o){const n=c(e[t-1],e[t+1]);if(void 0!==n){e.splice(t-1,3,n);continue}e[t++]="+"}t++}}(n),new r(n)}function i(e,t){var s;t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push("number"==typeof(s=t)||"boolean"==typeof s||null===s?s:d(Array.isArray(s)?s.join(","):s))}function c(e,t){if('""'===t)return e;if('""'===e)return t;if("string"==typeof e){if(t instanceof n||'"'!==e[e.length-1])return;return"string"!=typeof t?`${e.slice(0,-1)}${t}"`:'"'===t[0]?e.slice(0,-1)+t.slice(1):void 0}return"string"!=typeof t||'"'!==t[0]||e instanceof n?void 0:`"${e}${t.slice(1)}`}function d(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.str=a,e.addCodeArg=i,e.strConcat=function(e,t){return t.emptyStr()?e:e.emptyStr()?t:a`${e}${t}`},e.stringify=function(e){return new r(d(e))},e.safeStringify=d,e.getProperty=function(t){return"string"==typeof t&&e.IDENTIFIER.test(t)?new r(`.${t}`):s`[${t}]`},e.getEsmExportName=function(t){if("string"==typeof t&&e.IDENTIFIER.test(t))return new r(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)},e.regexpCode=function(e){return new r(e.toString())}}(Ol)),Ol}var Nl,Il,Rl={};function Pl(){return Nl||(Nl=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=xl();class n extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}}var r;!function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"}(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class s{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){return`${e}${(this._names[e]||this._nameGroup(e)).index++}`}_nameGroup(e){var t,n;if((null===(n=null===(t=this._parent)||void 0===t?void 0:t._prefixes)||void 0===n?void 0:n.has(e))||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}}e.Scope=s;class o extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=t._`.${new t.Name(n)}[${r}]`}}e.ValueScopeName=o;const a=t._`\n`;e.ValueScope=class extends s{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?a:t.nil}}get(){return this._scope}name(e){return new o(e,this._newName(e))}value(e,t){var n;if(void 0===t.ref)throw new Error("CodeGen: ref must be passed in value");const r=this.toName(e),{prefix:s}=r,o=null!==(n=t.key)&&void 0!==n?n:t.ref;let a=this._values[s];if(a){const e=a.get(o);if(e)return e}else a=this._values[s]=new Map;a.set(o,r);const i=this._scope[s]||(this._scope[s]=[]),c=i.length;return i[c]=t.ref,r.setValue(t,{property:s,itemIndex:c}),r}getValue(e,t){const n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(void 0===n.scopePath)throw new Error(`CodeGen: name "${n}" has no value`);return t._`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(void 0===e.value)throw new Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(s,o,a={},i){let c=t.nil;for(const d in s){const u=s[d];if(!u)continue;const l=a[d]=a[d]||new Map;u.forEach(s=>{if(l.has(s))return;l.set(s,r.Started);let a=o(s);if(a){const n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=t._`${c}${n} ${s} = ${a};${this.opts._n}`}else{if(!(a=null==i?void 0:i(s)))throw new n(s);c=t._`${c}${a}${this.opts._n}`}l.set(s,r.Completed)})}return c}}}(Rl)),Rl}function Cl(){return Il||(Il=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=xl(),n=Pl();var r=xl();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var s=Pl();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return s.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return s.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return s.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return s.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class o{optimizeNodes(){return this}optimizeNames(e,t){return this}}class a extends o{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){const r=e?n.varKinds.var:this.varKind,s=void 0===this.rhs?"":` = ${this.rhs}`;return`${r} ${this.name}${s};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=N(this.rhs,e,t)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class i extends o{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name)||e[this.lhs.str]||this.sideEffects)return this.rhs=N(this.rhs,e,n),this}get names(){return x(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}}class c extends i{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class d extends o{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class u extends o{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class l extends o{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class p extends o{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=N(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class h extends o{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),"")}optimizeNodes(){const{nodes:e}=this;let t=e.length;for(;t--;){const n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){const{nodes:n}=this;let r=n.length;for(;r--;){const s=n[r];s.optimizeNames(e,t)||(I(e,s.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>O(e,t.names),{})}}class m extends h{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class f extends h{}class g extends m{}g.kind="else";class y extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();const e=this.condition;if(!0===e)return this.nodes;let t=this.else;if(t){const e=t.optimizeNodes();t=this.else=Array.isArray(e)?new g(e):e}return t?!1===e?t instanceof y?t:t.nodes:this.nodes.length?this:new y(R(e),t instanceof y?[t]:t.nodes):!1!==e&&this.nodes.length?this:void 0}optimizeNames(e,t){var n;if(this.else=null===(n=this.else)||void 0===n?void 0:n.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=N(this.condition,e,t),this}get names(){const e=super.names;return x(e,this.condition),this.else&&O(e,this.else.names),e}}y.kind="if";class _ extends m{}_.kind="for";class v extends _{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=N(this.iteration,e,t),this}get names(){return O(super.names,this.iteration.names)}}class w extends _{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){const t=e.es5?n.varKinds.var:this.varKind,{name:r,from:s,to:o}=this;return`for(${t} ${r}=${s}; ${r}<${o}; ${r}++)`+super.render(e)}get names(){const e=x(super.names,this.from);return x(e,this.to)}}class b extends _{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=N(this.iterable,e,t),this}get names(){return O(super.names,this.iterable.names)}}class k extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}k.kind="func";class E extends h{render(e){return"return "+super.render(e)}}E.kind="return";class $ extends m{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),null===(e=this.catch)||void 0===e||e.optimizeNodes(),null===(t=this.finally)||void 0===t||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),null===(n=this.catch)||void 0===n||n.optimizeNames(e,t),null===(r=this.finally)||void 0===r||r.optimizeNames(e,t),this}get names(){const e=super.names;return this.catch&&O(e,this.catch.names),this.finally&&O(e,this.finally.names),e}}class S extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}S.kind="catch";class T extends m{render(e){return"finally"+super.render(e)}}function O(e,t){for(const n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function x(e,n){return n instanceof t._CodeOrName?O(e,n.names):e}function N(e,n,r){return e instanceof t.Name?o(e):(s=e)instanceof t._Code&&s._items.some(e=>e instanceof t.Name&&1===n[e.str]&&void 0!==r[e.str])?new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=o(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[])):e;var s;function o(e){const t=r[e.str];return void 0===t||1!==n[e.str]?e:(delete n[e.str],t)}}function I(e,t){for(const n in t)e[n]=(e[n]||0)-(t[n]||0)}function R(e){return"boolean"==typeof e||"number"==typeof e||null===e?!e:t._`!${z(e)}`}T.kind="finally",e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?"\n":""},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new f]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){const n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){const s=this._scope.toName(t);return void 0!==n&&r&&(this._constants[s.str]=n),this._leafNode(new a(e,s,n)),s}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new i(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return"function"==typeof e?e():e!==t.nil&&this._leafNode(new p(e)),this}object(...e){const n=["{"];for(const[r,s]of e)n.length>1&&n.push(","),n.push(r),(r!==s||this.opts.es5)&&(n.push(":"),(0,t.addCodeArg)(n,s));return n.push("}"),new t._Code(n)}if(e,t,n){if(this._blockNode(new y(e)),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(e){return this._elseNode(new y(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(y,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new v(e),t)}forRange(e,t,r,s,o=(this.opts.es5?n.varKinds.var:n.varKinds.let)){const a=this._scope.toName(e);return this._for(new w(o,a,t,r),()=>s(a))}forOf(e,r,s,o=n.varKinds.const){const a=this._scope.toName(e);if(this.opts.es5){const e=r instanceof t.Name?r:this.var("_arr",r);return this.forRange("_i",0,t._`${e}.length`,n=>{this.var(a,t._`${e}[${n}]`),s(a)})}return this._for(new b("of",o,a,r),()=>s(a))}forIn(e,r,s,o=(this.opts.es5?n.varKinds.var:n.varKinds.const)){if(this.opts.ownProperties)return this.forOf(e,t._`Object.keys(${r})`,s);const a=this._scope.toName(e);return this._for(new b("in",o,a,r),()=>s(a))}endFor(){return this._endBlockNode(_)}label(e){return this._leafNode(new d(e))}break(e){return this._leafNode(new u(e))}return(e){const t=new E;if(this._blockNode(t),this.code(e),1!==t.nodes.length)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(E)}try(e,t,n){if(!t&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');const r=new $;if(this._blockNode(r),this.code(e),t){const e=this.name("e");this._currNode=r.catch=new S(e),t(e)}return n&&(this._currNode=r.finally=new T,this.code(n)),this._endBlockNode(S,T)}throw(e){return this._leafNode(new l(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){const t=this._blockStarts.pop();if(void 0===t)throw new Error("CodeGen: not in self-balancing block");const n=this._nodes.length-t;if(n<0||void 0!==e&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,s){return this._blockNode(new k(e,n,r)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(k)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){const n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){const t=this._currNode;if(!(t instanceof y))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){const e=this._nodes;return e[e.length-1]}set _currNode(e){const t=this._nodes;t[t.length-1]=e}},e.not=R;const P=j(e.operators.AND);e.and=function(...e){return e.reduce(P)};const C=j(e.operators.OR);function j(e){return(n,r)=>n===t.nil?r:r===t.nil?n:t._`${z(n)} ${e} ${z(r)}`}function z(e){return e instanceof t.Name?e:t._`(${e})`}e.or=function(...e){return e.reduce(C)}}(Tl)),Tl}var jl,zl={};function Al(){if(jl)return zl;jl=1,Object.defineProperty(zl,"__esModule",{value:!0}),zl.checkStrictMode=zl.getErrorPath=zl.Type=zl.useFunc=zl.setEvaluated=zl.evaluatedPropsToName=zl.mergeEvaluated=zl.eachItem=zl.unescapeJsonPointer=zl.escapeJsonPointer=zl.escapeFragment=zl.unescapeFragment=zl.schemaRefOrVal=zl.schemaHasRulesButRef=zl.schemaHasRules=zl.checkUnknownRules=zl.alwaysValidSchema=zl.toHash=void 0;const e=Cl(),t=xl();function n(e,t=e.schema){const{opts:n,self:r}=e;if(!n.strictSchema)return;if("boolean"==typeof t)return;const s=r.RULES.keywords;for(const n in t)s[n]||l(e,`unknown keyword: "${n}"`)}function r(e,t){if("boolean"==typeof e)return!e;for(const n in e)if(t[n])return!0;return!1}function s(e){return"number"==typeof e?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}function o(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function a({mergeNames:t,mergeToName:n,mergeValues:r,resultToName:s}){return(o,a,i,c)=>{const d=void 0===i?a:i instanceof e.Name?(a instanceof e.Name?t(o,a,i):n(o,a,i),i):a instanceof e.Name?(n(o,i,a),a):r(a,i);return c!==e.Name||d instanceof e.Name?d:s(o,d)}}function i(t,n){if(!0===n)return t.var("props",!0);const r=t.var("props",e._`{}`);return void 0!==n&&c(t,r,n),r}function c(t,n,r){Object.keys(r).forEach(r=>t.assign(e._`${n}${(0,e.getProperty)(r)}`,!0))}zl.toHash=function(e){const t={};for(const n of e)t[n]=!0;return t},zl.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(n(e,t),!r(t,e.self.RULES.all))},zl.checkUnknownRules=n,zl.schemaHasRules=r,zl.schemaHasRulesButRef=function(e,t){if("boolean"==typeof e)return!e;for(const n in e)if("$ref"!==n&&t.all[n])return!0;return!1},zl.schemaRefOrVal=function({topSchemaRef:t,schemaPath:n},r,s,o){if(!o){if("number"==typeof r||"boolean"==typeof r)return r;if("string"==typeof r)return e._`${r}`}return e._`${t}${n}${(0,e.getProperty)(s)}`},zl.unescapeFragment=function(e){return o(decodeURIComponent(e))},zl.escapeFragment=function(e){return encodeURIComponent(s(e))},zl.escapeJsonPointer=s,zl.unescapeJsonPointer=o,zl.eachItem=function(e,t){if(Array.isArray(e))for(const n of e)t(n);else t(e)},zl.mergeEvaluated={props:a({mergeNames:(t,n,r)=>t.if(e._`${r} !== true && ${n} !== undefined`,()=>{t.if(e._`${n} === true`,()=>t.assign(r,!0),()=>t.assign(r,e._`${r} || {}`).code(e._`Object.assign(${r}, ${n})`))}),mergeToName:(t,n,r)=>t.if(e._`${r} !== true`,()=>{!0===n?t.assign(r,!0):(t.assign(r,e._`${r} || {}`),c(t,r,n))}),mergeValues:(e,t)=>!0===e||{...e,...t},resultToName:i}),items:a({mergeNames:(t,n,r)=>t.if(e._`${r} !== true && ${n} !== undefined`,()=>t.assign(r,e._`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(t,n,r)=>t.if(e._`${r} !== true`,()=>t.assign(r,!0===n||e._`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>!0===e||Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})},zl.evaluatedPropsToName=i,zl.setEvaluated=c;const d={};var u;function l(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,!0===n)throw new Error(t);e.self.logger.warn(t)}}return zl.useFunc=function(e,n){return e.scopeValue("func",{ref:n,code:d[n.code]||(d[n.code]=new t._Code(n.code))})},function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"}(u||(zl.Type=u={})),zl.getErrorPath=function(t,n,r){if(t instanceof e.Name){const s=n===u.Num;return r?s?e._`"[" + ${t} + "]"`:e._`"['" + ${t} + "']"`:s?e._`"/" + ${t}`:e._`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,e.getProperty)(t).toString():"/"+s(t)},zl.checkStrictMode=l,zl}var Ml,Dl,Ll,Zl={};function Fl(){if(Ml)return Zl;Ml=1,Object.defineProperty(Zl,"__esModule",{value:!0});const e=Cl(),t={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")};return Zl.default=t,Zl}function Ul(){return Dl||(Dl=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=Cl(),n=Al(),r=Fl();function s(e,n){const s=e.const("err",n);e.if(t._`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,t._`[${s}]`),t._`${r.default.vErrors}.push(${s})`),e.code(t._`${r.default.errors}++`)}function o(e,n){const{gen:r,validateName:s,schemaEnv:o}=e;o.$async?r.throw(t._`new ${e.ValidationError}(${n})`):(r.assign(t._`${s}.errors`,n),r.return(!1))}e.keywordError={message:({keyword:e})=>t.str`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?t.str`"${e}" keyword must be ${n} ($data)`:t.str`"${e}" keyword is invalid ($data)`},e.reportError=function(n,r=e.keywordError,a,c){const{it:d}=n,{gen:u,compositeRule:l,allErrors:p}=d,h=i(n,r,a);(null!=c?c:l||p)?s(u,h):o(d,t._`[${h}]`)},e.reportExtraError=function(t,n=e.keywordError,a){const{it:c}=t,{gen:d,compositeRule:u,allErrors:l}=c;s(d,i(t,n,a)),u||l||o(c,r.default.vErrors)},e.resetErrorsCount=function(e,n){e.assign(r.default.errors,n),e.if(t._`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign(t._`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))},e.extendErrors=function({gen:e,keyword:n,schemaValue:s,data:o,errsCount:a,it:i}){if(void 0===a)throw new Error("ajv implementation error");const c=e.name("err");e.forRange("i",a,r.default.errors,a=>{e.const(c,t._`${r.default.vErrors}[${a}]`),e.if(t._`${c}.instancePath === undefined`,()=>e.assign(t._`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,i.errorPath))),e.assign(t._`${c}.schemaPath`,t.str`${i.errSchemaPath}/${n}`),i.opts.verbose&&(e.assign(t._`${c}.schema`,s),e.assign(t._`${c}.data`,o))})};const a={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function i(e,n,s){const{createErrors:o}=e.it;return!1===o?t._`{}`:function(e,n,s={}){const{gen:o,it:i}=e,u=[c(i,s),d(e,s)];return function(e,{params:n,message:s},o){const{keyword:i,data:c,schemaValue:d,it:u}=e,{opts:l,propertyName:p,topSchemaRef:h,schemaPath:m}=u;o.push([a.keyword,i],[a.params,"function"==typeof n?n(e):n||t._`{}`]),l.messages&&o.push([a.message,"function"==typeof s?s(e):s]),l.verbose&&o.push([a.schema,d],[a.parentSchema,t._`${h}${m}`],[r.default.data,c]),p&&o.push([a.propertyName,p])}(e,n,u),o.object(...u)}(e,n,s)}function c({errorPath:e},{instancePath:s}){const o=s?t.str`${e}${(0,n.getErrorPath)(s,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,o)]}function d({keyword:e,it:{errSchemaPath:r}},{schemaPath:s,parentSchema:o}){let i=o?r:t.str`${r}/${e}`;return s&&(i=t.str`${i}${(0,n.getErrorPath)(s,n.Type.Str)}`),[a.schemaPath,i]}}(Sl)),Sl}var ql,Hl={},Vl={};function Jl(){if(ql)return Vl;ql=1,Object.defineProperty(Vl,"__esModule",{value:!0}),Vl.getRules=Vl.isJSONType=void 0;const e=new Set(["string","number","integer","boolean","null","object","array"]);return Vl.isJSONType=function(t){return"string"==typeof t&&e.has(t)},Vl.getRules=function(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}},Vl}var Kl,Bl,Wl={};function Gl(){if(Kl)return Wl;function e(e,n){return n.rules.some(n=>t(e,n))}function t(e,t){var n;return void 0!==e[t.keyword]||(null===(n=t.definition.implements)||void 0===n?void 0:n.some(t=>void 0!==e[t]))}return Kl=1,Object.defineProperty(Wl,"__esModule",{value:!0}),Wl.shouldUseRule=Wl.shouldUseGroup=Wl.schemaHasRulesForType=void 0,Wl.schemaHasRulesForType=function({schema:t,self:n},r){const s=n.RULES.types[r];return s&&!0!==s&&e(t,s)},Wl.shouldUseGroup=e,Wl.shouldUseRule=t,Wl}function Xl(){if(Bl)return Hl;Bl=1,Object.defineProperty(Hl,"__esModule",{value:!0}),Hl.reportTypeError=Hl.checkDataTypes=Hl.checkDataType=Hl.coerceAndCheckDataType=Hl.getJSONTypes=Hl.getSchemaTypes=Hl.DataType=void 0;const e=Jl(),t=Gl(),n=Ul(),r=Cl(),s=Al();var o;function a(t){const n=Array.isArray(t)?t:t?[t]:[];if(n.every(e.isJSONType))return n;throw new Error("type must be JSONType or JSONType[]: "+n.join(","))}!function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"}(o||(Hl.DataType=o={})),Hl.getSchemaTypes=function(e){const t=a(e.type);if(t.includes("null")){if(!1===e.nullable)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&void 0!==e.nullable)throw new Error('"nullable" cannot be used without "type"');!0===e.nullable&&t.push("null")}return t},Hl.getJSONTypes=a,Hl.coerceAndCheckDataType=function(e,n){const{gen:s,data:a,opts:c}=e,u=function(e,t){return t?e.filter(e=>i.has(e)||"array"===t&&"array"===e):[]}(n,c.coerceTypes),p=n.length>0&&!(0===u.length&&1===n.length&&(0,t.schemaHasRulesForType)(e,n[0]));if(p){const t=d(n,a,c.strictNumbers,o.Wrong);s.if(t,()=>{u.length?function(e,t,n){const{gen:s,data:o,opts:a}=e,c=s.let("dataType",r._`typeof ${o}`),u=s.let("coerced",r._`undefined`);"array"===a.coerceTypes&&s.if(r._`${c} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>s.assign(o,r._`${o}[0]`).assign(c,r._`typeof ${o}`).if(d(t,o,a.strictNumbers),()=>s.assign(u,o))),s.if(r._`${u} !== undefined`);for(const e of n)(i.has(e)||"array"===e&&"array"===a.coerceTypes)&&p(e);function p(e){switch(e){case"string":return void s.elseIf(r._`${c} == "number" || ${c} == "boolean"`).assign(u,r._`"" + ${o}`).elseIf(r._`${o} === null`).assign(u,r._`""`);case"number":return void s.elseIf(r._`${c} == "boolean" || ${o} === null
2
+ import{Command as e}from"commander";import t,{dirname as n,join as r}from"path";import s from"os";import o,{readFileSync as a,existsSync as i,mkdirSync as c,writeFileSync as d}from"fs";import{fileURLToPath as u}from"url";import{exec as l}from"child_process";import p from"better-sqlite3";import h from"simple-git";import{cwd as m}from"process";import{ZodOptional as f,z as g}from"zod";import y from"node:process";import _ from"express";import v from"express-ejs-layouts";import w from"markdown-it";const b=["personal","project","organization"],k=["developer","architect","reviewer","ai"],$=["code_pattern","tool_usage","architecture","config","pitfall","api_usage","exploration"],S=["draft","suggested","verified"],E=["session_start","session_end","tool_use","user_prompt","pre_compact","notification","permission_request","stop","subagent_stop"],T={knowledge_item:`\n CREATE TABLE IF NOT EXISTS knowledge_item (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n\n -- Basic information\n title TEXT NOT NULL,\n summary TEXT NOT NULL,\n content TEXT NOT NULL,\n\n -- Classification dimensions\n scope TEXT NOT NULL CHECK(scope IN (${b.map(e=>`'${e}'`).join(", ")})),\n source_type TEXT NOT NULL CHECK(source_type IN (${k.map(e=>`'${e}'`).join(", ")})),\n knowledge_type TEXT NOT NULL CHECK(knowledge_type IN (${$.map(e=>`'${e}'`).join(", ")})),\n status TEXT NOT NULL DEFAULT 'draft' CHECK(status IN (${S.map(e=>`'${e}'`).join(", ")})),\n\n -- Association information\n repository_id INTEGER,\n session_id TEXT NOT NULL,\n\n -- Source tracking\n source_file TEXT,\n commit_hash TEXT,\n contributor TEXT,\n\n -- Timestamps\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n\n FOREIGN KEY (repository_id) REFERENCES repository(id)\n )\n `,repository:"\n CREATE TABLE IF NOT EXISTS repository (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n\n name TEXT NOT NULL,\n remote_url TEXT UNIQUE NOT NULL,\n local_path TEXT,\n\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL\n )\n ",session:"\n CREATE TABLE IF NOT EXISTS session (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n\n session_id TEXT UNIQUE NOT NULL,\n repository_id INTEGER,\n\n -- Session basic information\n working_directory TEXT NOT NULL,\n branch TEXT,\n username TEXT,\n\n -- Environment information (stored as JSON)\n env TEXT,\n\n -- Configuration information (stored as JSON)\n config TEXT,\n\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n\n FOREIGN KEY (repository_id) REFERENCES repository(id)\n )\n ",hook_event:"\n CREATE TABLE IF NOT EXISTS hook_event (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n\n session_id TEXT NOT NULL,\n\n -- Hook information\n name TEXT NOT NULL,\n input TEXT NOT NULL,\n output TEXT,\n\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n\n FOREIGN KEY (session_id) REFERENCES session(session_id)\n )\n ",knowledge_item_fts:"\n CREATE VIRTUAL TABLE IF NOT EXISTS knowledge_item_fts USING fts5(\n title, summary, content,\n content='knowledge_item',\n content_rowid='id',\n tokenize='trigram'\n )\n "},O={knowledge_item_fts_insert:"\n CREATE TRIGGER IF NOT EXISTS knowledge_item_fts_insert AFTER INSERT ON knowledge_item BEGIN\n INSERT INTO knowledge_item_fts(rowid, title, summary, content)\n VALUES (new.id, new.title, new.summary, new.content);\n END\n ",knowledge_item_fts_delete:"\n CREATE TRIGGER IF NOT EXISTS knowledge_item_fts_delete AFTER DELETE ON knowledge_item BEGIN\n INSERT INTO knowledge_item_fts(knowledge_item_fts, rowid, title, summary, content)\n VALUES('delete', old.id, old.title, old.summary, old.content);\n END\n ",knowledge_item_fts_update:"\n CREATE TRIGGER IF NOT EXISTS knowledge_item_fts_update AFTER UPDATE ON knowledge_item BEGIN\n INSERT INTO knowledge_item_fts(knowledge_item_fts, rowid, title, summary, content)\n VALUES('delete', old.id, old.title, old.summary, old.content);\n INSERT INTO knowledge_item_fts(rowid, title, summary, content)\n VALUES (new.id, new.title, new.summary, new.content);\n END\n "},x={idx_knowledge_scope:"CREATE INDEX IF NOT EXISTS idx_knowledge_scope ON knowledge_item(scope)",idx_knowledge_type:"CREATE INDEX IF NOT EXISTS idx_knowledge_type ON knowledge_item(knowledge_type)",idx_knowledge_status:"CREATE INDEX IF NOT EXISTS idx_knowledge_status ON knowledge_item(status)",idx_knowledge_repo:"CREATE INDEX IF NOT EXISTS idx_knowledge_repo ON knowledge_item(repository_id)",idx_knowledge_session:"CREATE INDEX IF NOT EXISTS idx_knowledge_session ON knowledge_item(session_id)",idx_session_repo:"CREATE INDEX IF NOT EXISTS idx_session_repo ON session(repository_id)",idx_session_id:"CREATE INDEX IF NOT EXISTS idx_session_id ON session(session_id)",idx_hook_event_session:"CREATE INDEX IF NOT EXISTS idx_hook_event_session ON hook_event(session_id)",idx_hook_event_type:"CREATE INDEX IF NOT EXISTS idx_hook_event_type ON hook_event(name)"};function N(e){Object.values(T).forEach(t=>{e.prepare(t).run()}),Object.values(x).forEach(t=>{e.prepare(t).run()}),Object.values(O).forEach(t=>{e.prepare(t).run()});const t=e.prepare("SELECT COUNT(*) as count FROM knowledge_item_fts").get(),n=e.prepare("SELECT COUNT(*) as count FROM knowledge_item").get();n.count>0&&0===t.count&&(console.log("Populating FTS index from existing data..."),e.prepare("\n INSERT INTO knowledge_item_fts(rowid, title, summary, content)\n SELECT id, title, summary, content FROM knowledge_item\n ").run(),console.log(`FTS index populated with ${n.count} items`))}const I={logging:{level:"DEBUG"},db:{path:t.join(s.homedir(),".knowledge-bank","knowledge.db"),configs:["journal_mode = WAL","foreign_keys = ON"]},tmp:t.join(s.homedir(),".knowledge-bank","tmp")};let R=null;function P(){if(null===R){const e=process.env.KNOWLEDGE_CONF_DIR||t.join(s.homedir(),".knowledge-bank"),n=t.join(e,"config.json");R={...I,...o.existsSync(n)?JSON.parse(o.readFileSync(n,"utf-8")):{}}}return R}const C=P(),j={DEBUG:"DEBUG",INFO:"INFO",WARN:"WARN",ERROR:"ERROR"},z=Object.values(j);class A{constructor(e,n){this.loggerName=n;const r=C.logging.path||t.join(s.homedir(),".knowledge-bank","logs");o.mkdirSync(r,{recursive:!0}),this.loggerFile=t.join(r,`${e}.log`),this.logLevel=C.logging.level.toUpperCase()||j.INFO}formatMessage(e,t,n=null){const r=`${(new Date).toISOString().replace("T","-").split(".")[0]} ${this.loggerName} ${e}: ${t}`;return null===n?r:`${r} - ${JSON.stringify(n)}`}isLogLevelEnabled(e){const t=z.indexOf(this.logLevel);return z.indexOf(e)>=t}writeMessage(e,t,n){if(this.isLogLevelEnabled(e)){const r=this.formatMessage(e,t,n);o.appendFileSync(this.loggerFile,`${r}\n`,"utf8")}}logInfo(e,t=null){this.writeMessage(j.INFO,e,t)}logError(e,t=null){if(t instanceof Error){const n={message:t.message,stack:t.stack,name:t.name,...t.cause&&{cause:t.cause},...Object.getOwnPropertyNames(t).reduce((e,n)=>(["message","stack","name"].includes(n)||(e[n]=t[n]),e),{})};this.writeMessage(j.ERROR,e,n)}else this.writeMessage(j.ERROR,e,t)}logWarn(e,t=null){this.writeMessage(j.WARN,e,t)}logDebug(e,t=null){this.writeMessage(j.DEBUG,e,t)}}function M(e,t){return new A(e,t)}const D=M("common","common"),L=u(import.meta.url),Z=t.dirname(L),F=t.join(Z,"..","claude-marketplace"),q=function(){const e=t.join(Z,"package.json"),n=t.join(".","package.json");return o.existsSync(e)?JSON.parse(a(e,"utf8")):JSON.parse(a(n,"utf8"))}();function U(e){return o.existsSync(e)?JSON.parse(o.readFileSync(e,"utf-8")):{}}const H=t.join(s.homedir(),".claude","settings.local.json");function V(){const e=function(){const e=process.env.CLAUDE_PROJECT_DIR||process.cwd(),n=t.join(e,".claude/settings.local.json"),r=t.join(e,".claude/settings.json"),s=U(n),o=U(r);return{...U(H),...o,...s}}(),n=!1!==(e?.knowledge||{}).enabled;return n||D.logWarn("Knowledge collection is disabled in settings."),{enabled:n}}function K(){return new Promise((e,t)=>{l("claude plugin marketplace list --json",(n,r,s)=>{if(n)t(n);else{s&&console.error(s);try{const t=r.trim()?JSON.parse(r):[];e(t)}catch(e){t(e)}}})})}function J(e=0){const t=new Date;return t.setDate(t.getDate()-e),`${t.getFullYear()}${String(t.getMonth()+1).padStart(2,"0")}${String(t.getDate()).padStart(2,"0")}`}const B=P();class W{constructor(){this.dbPath=B.db.path,this.db=null,this.transactionDepth=0}initialize(){const e=n(this.dbPath);return i(e)||c(e,{recursive:!0}),this.db=new p(this.dbPath),B.db.configs.forEach(e=>{this.db.pragma(e)}),this}getConnection(){return this.db||this.initialize(),this.db}beginTransaction(){return 0===this.transactionDepth&&this.getConnection().prepare("BEGIN").run(),this.transactionDepth++,this}commit(){return this.transactionDepth--,0===this.transactionDepth&&this.getConnection().prepare("COMMIT").run(),this}rollback(){return this.transactionDepth--,0===this.transactionDepth&&this.getConnection().prepare("ROLLBACK").run(),this}transaction(e){this.beginTransaction();try{const t=e(this.getConnection());return this.commit(),t}catch(e){throw this.rollback(),e}}close(){return this.db&&(this.db.close(),this.db=null),this}exists(){return i(this.dbPath)}getPath(){return this.dbPath}}let G=null;function X(){return G||(G=new W),G}const Y=M("knowledge-repository","knowledge-repository");class Q{constructor(e){this.database=e,this.db=e.getConnection()}create(e){const t=Date.now(),n=this.db.prepare("\n INSERT INTO knowledge_item (\n title, summary, content,\n scope, source_type, knowledge_type, status,\n repository_id, session_id,\n source_file, commit_hash, contributor,\n created_at, updated_at\n ) VALUES (\n @title, @summary, @content,\n @scope, @source_type, @knowledge_type, @status,\n @repository_id, @session_id,\n @source_file, @commit_hash, @contributor,\n @created_at, @updated_at\n )\n ").run({...e,status:e.status||S.DRAFT,created_at:t,updated_at:t});return this.findById(n.lastInsertRowid)}findById(e){return this.db.prepare("SELECT * FROM knowledge_item WHERE id = ?").get(e)}findByRepository(e,t=null){return t?this.db.prepare("SELECT * FROM knowledge_item WHERE repository_id = ? AND scope = ? ORDER BY updated_at DESC").all(e,t):this.db.prepare("SELECT * FROM knowledge_item WHERE repository_id = ? ORDER BY updated_at DESC").all(e)}findByScope(e){return this.db.prepare("SELECT * FROM knowledge_item WHERE scope = ? ORDER BY updated_at DESC").all(e)}findByStatus(e){return this.db.prepare("SELECT * FROM knowledge_item WHERE status = ? ORDER BY updated_at DESC").all(e)}findByKnowledgeType(e){return this.db.prepare("SELECT * FROM knowledge_item WHERE knowledge_type = ? ORDER BY updated_at DESC").all(e)}findBySession(e){return this.db.prepare("SELECT * FROM knowledge_item WHERE session_id = ?").all(e)}findRelevant(e,t=5){return this.db.prepare("\n SELECT * FROM knowledge_item\n WHERE repository_id = ? OR scope = 'organization'\n ORDER BY\n CASE status\n WHEN 'verified' THEN 3\n WHEN 'suggested' THEN 2\n WHEN 'draft' THEN 1\n END DESC,\n updated_at DESC\n LIMIT ?\n ").all(e,t)}update(e,t){const n=Date.now(),r=Object.keys(t).map(e=>`${e} = @${e}`).join(", ");return this.db.prepare(`\n UPDATE knowledge_item\n SET ${r}, updated_at = @updated_at\n WHERE id = @id\n `).run({...t,id:e,updated_at:n}),this.findById(e)}updateStatus(e,t){return this.update(e,{status:t})}delete(e){return this.db.prepare("DELETE FROM knowledge_item WHERE id = ?").run(e)}count(e={}){let t="SELECT COUNT(*) as count FROM knowledge_item";const n=[],r=[];return e.scope&&(n.push("scope = ?"),r.push(e.scope)),e.status&&(n.push("status = ?"),r.push(e.status)),e.knowledge_type&&(n.push("knowledge_type = ?"),r.push(e.knowledge_type)),e.repository_id&&(n.push("repository_id = ?"),r.push(e.repository_id)),n.length>0&&(t+=` WHERE ${n.join(" AND ")}`),this.db.prepare(t).get(...r).count}findAll(e=100,t=0){return this.db.prepare("SELECT * FROM knowledge_item ORDER BY updated_at DESC LIMIT ? OFFSET ?").all(e,t)}search(e,t=10){const n=Array.isArray(e)?e.map(e=>`"${e}"`).join(" OR "):`"${e}"`;return Y.logDebug("Searching knowledge items with query: ",n),this.db.prepare("\n SELECT ki.*\n FROM knowledge_item ki\n JOIN knowledge_item_fts fts ON fts.rowid = ki.id\n WHERE knowledge_item_fts MATCH ?\n ORDER BY rank\n LIMIT ?\n ").all(n,t)}}class ee{constructor(e){this.database=e,this.db=e.getConnection()}create(e){const t=Date.now(),n=this.db.prepare("\n INSERT INTO repository (\n name, remote_url, local_path,\n created_at, updated_at\n ) VALUES (\n @name, @remote_url, @local_path,\n @created_at, @updated_at\n )\n ").run({...e,created_at:t,updated_at:t});return this.findById(n.lastInsertRowid)}findById(e){return this.db.prepare("SELECT * FROM repository WHERE id = ?").get(e)}findByRemoteUrl(e){return this.db.prepare("SELECT * FROM repository WHERE remote_url = ?").get(e)}findByPath(e){return this.db.prepare("SELECT * FROM repository WHERE local_path = ?").get(e)}findByName(e){return this.db.prepare("SELECT * FROM repository WHERE name = ?").get(e)}getOrCreate(e,t,n=null){let r=this.findByRemoteUrl(e);return r?n&&r.local_path!==n&&(r=this.update(r.id,{local_path:n})):r=this.create({name:t,remote_url:e,local_path:n}),r}update(e,t){const n=Date.now(),r=Object.keys(t).map(e=>`${e} = @${e}`).join(", ");return this.db.prepare(`\n UPDATE repository\n SET ${r}, updated_at = @updated_at\n WHERE id = @id\n `).run({...t,id:e,updated_at:n}),this.findById(e)}delete(e){return this.db.prepare("DELETE FROM repository WHERE id = ?").run(e)}findAll(){return this.db.prepare("SELECT * FROM repository ORDER BY updated_at DESC").all()}count(){return this.db.prepare("SELECT COUNT(*) as count FROM repository").get().count}}class te{constructor(e){this.database=e,this.db=e.getConnection()}createSession(e){const t=this.findSessionBySessionId(e.session_id);if(t)return t;const n=Date.now(),r=e.config||P();return this.db.prepare("\n INSERT INTO session (\n session_id, repository_id, working_directory, branch, username, env, config,\n created_at, updated_at\n ) VALUES (\n @session_id, @repository_id, @working_directory, @branch, @username, @env, @config,\n @created_at, @updated_at\n )\n ").run({session_id:e.session_id,repository_id:e.repository_id||null,working_directory:e.working_directory,branch:e.branch||null,username:e.username||null,env:e.env?JSON.stringify(e.env):null,config:JSON.stringify(r),created_at:n,updated_at:n}),this.findSessionBySessionId(e.session_id)}findSessionBySessionId(e){const t=this.db.prepare("SELECT * FROM session WHERE session_id = ?").get(e);return this._parseSessionData(t)}_parseSessionData(e){return e?{...e,env:e.env?JSON.parse(e.env):null,config:e.config?JSON.parse(e.config):null}:null}updateSessionConfig(e,t){const n=Date.now();return this.db.prepare("\n UPDATE session\n SET config = ?, updated_at = ?\n WHERE session_id = ?\n ").run(JSON.stringify(t),n,e),this.findSessionBySessionId(e)}create(e){const t=Date.now(),n=this.db.prepare("\n INSERT INTO hook_event (\n session_id,\n name, input, output,\n created_at, updated_at\n ) VALUES (\n @session_id,\n @name, @input, @output,\n @created_at, @updated_at\n )\n ").run({session_id:e.session_id,name:e.name,input:"string"==typeof e.input?e.input:JSON.stringify(e.input),output:void 0===e.output||null===e.output?null:"string"==typeof e.output?e.output:JSON.stringify(e.output),created_at:t,updated_at:t});return this.findById(n.lastInsertRowid)}updateOutput(e,t){const n=Date.now(),r=this.db.prepare("\n UPDATE hook_event\n SET output = ?, updated_at = ?\n WHERE id = ?\n "),s="string"==typeof t?t:JSON.stringify(t);return r.run(s,n,e),this.findById(e)}findById(e){const t=this.db.prepare("SELECT * FROM hook_event WHERE id = ?").get(e);return t&&(t.input&&(t.input=JSON.parse(t.input)),t.output&&(t.output=JSON.parse(t.output))),t}findBySession(e){return this.db.prepare("SELECT * FROM hook_event WHERE session_id = ? ORDER BY created_at ASC").all(e).map(e=>({...e,input:e.input?JSON.parse(e.input):null,output:e.output?JSON.parse(e.output):null}))}findBySessionAndType(e,t){return this.db.prepare("SELECT * FROM hook_event WHERE session_id = ? AND name = ? ORDER BY created_at ASC").all(e,t).map(e=>({...e,input:e.input?JSON.parse(e.input):null,output:e.output?JSON.parse(e.output):null}))}findByRepository(e,t=100){return this.db.prepare("\n SELECT he.* FROM hook_event he\n JOIN session s ON he.session_id = s.session_id\n WHERE s.repository_id = ?\n ORDER BY he.created_at DESC\n LIMIT ?\n ").all(e,t).map(e=>({...e,input:e.input?JSON.parse(e.input):null,output:e.output?JSON.parse(e.output):null}))}findByHookType(e,t=100){return this.db.prepare("SELECT * FROM hook_event WHERE name = ? ORDER BY created_at DESC LIMIT ?").all(e,t).map(e=>({...e,input:e.input?JSON.parse(e.input):null,output:e.output?JSON.parse(e.output):null}))}findLatestSessionStart(e){const t=this.db.prepare("\n SELECT * FROM hook_event\n WHERE session_id = ? AND name = ?\n ORDER BY created_at DESC\n LIMIT 1\n ").get(e,E.SESSION_START);return t&&(t.input&&(t.input=JSON.parse(t.input)),t.output&&(t.output=JSON.parse(t.output))),t}hasSessionEnded(e){return this.db.prepare("\n SELECT COUNT(*) as count FROM hook_event\n WHERE session_id = ? AND name = ?\n ").get(e,E.SESSION_END).count>0}getSessionSummary(e){const t=this.findBySession(e),n=this._parseSessionData(this.db.prepare("SELECT * FROM session WHERE session_id = ?").get(e)),r={session_id:e,total_events:t.length,hook_types:{},start_time:null,end_time:null,duration:null,repository_id:n?.repository_id||null,branch:n?.branch||null,config:n?.config||null,created_at:n?.created_at||null,updated_at:n?.updated_at||null};return t.forEach(e=>{r.hook_types[e.name]=(r.hook_types[e.name]||0)+1,e.name!==E.SESSION_START||r.start_time||(r.start_time=e.created_at),e.name!==E.SESSION_END||r.end_time||(r.end_time=e.created_at)}),r.start_time&&r.end_time&&(r.duration=r.end_time-r.start_time),r}delete(e){return this.db.prepare("DELETE FROM hook_event WHERE id = ?").run(e)}deleteBySession(e){return this.db.prepare("DELETE FROM hook_event WHERE session_id = ?").run(e)}getRecentSessions(e=10){return this.db.prepare("\n SELECT DISTINCT session_id, MAX(created_at) as last_activity\n FROM hook_event\n GROUP BY session_id\n ORDER BY last_activity DESC\n LIMIT ?\n ").all(e)}count(e={}){let t="SELECT COUNT(*) as count FROM hook_event";const n=[],r=[];return e.session_id&&(n.push("session_id = ?"),r.push(e.session_id)),e.name&&(n.push("name = ?"),r.push(e.name)),n.length>0&&(t+=` WHERE ${n.join(" AND ")}`),this.db.prepare(t).get(...r).count}}class ne{constructor(e=null){this.repoPath=e||m(),this.git=h(this.repoPath)}getCurrentBranch(){return this.git.branchLocal().then(e=>e.current).catch(e=>{throw new Error(`Failed to get current branch: ${e.message}`)})}getRemoteUrl(e="origin"){return this.git.getRemotes(!0).then(t=>{const n=t.find(t=>t.name===e);if(!n)throw new Error(`Remote '${e}' not found`);return n.refs.fetch||n.refs.push}).catch(e=>{throw new Error(`Failed to get remote URL: ${e.message}`)})}getMainBranch(){return this.git.branchLocal().then(e=>{const t=e.all;return t.includes("main")?"main":t.includes("master")?"master":t[0]||"main"}).catch(()=>"main")}isOnMainBranch(){return this.getCurrentBranch().then(e=>this.getMainBranch().then(t=>e===t))}getCurrentCommitHash(){return this.git.revparse(["HEAD"]).then(e=>e.trim()).catch(e=>{throw new Error(`Failed to get commit hash: ${e.message}`)})}getCommitAuthor(e="HEAD"){return this.git.show(["-s","--format=%an <%ae>",e]).then(e=>e.trim()).catch(e=>{throw new Error(`Failed to get commit author: ${e.message}`)})}isBranchMergedToMain(e){return this.getMainBranch().then(t=>this.git.branch(["--merged",t]).then(t=>t.all.map(e=>e.replace("*","").trim()).includes(e))).catch(e=>(console.error(`Failed to check merge status: ${e.message}`),!1))}getRepoRoot(){return this.git.revparse(["--show-toplevel"]).then(e=>e.trim()).catch(e=>{throw new Error(`Failed to get repo root: ${e.message}`)})}isGitRepository(){return this.git.checkIsRepo().catch(()=>!1)}getStatus(){return this.git.status().catch(e=>{throw new Error(`Failed to get git status: ${e.message}`)})}getAllBranches(){return this.git.branchLocal().then(e=>e.all).catch(e=>{throw new Error(`Failed to get branches: ${e.message}`)})}getRepositoryName(){return this.getRemoteUrl().then(e=>{const t=e.match(/([^/:]+?)(?:\.git)?$/);return t?t[1]:"unknown"}).catch(()=>"unknown")}getUserName(){return this.git.getConfig("user.name").then(e=>e.value||process.env.USER||process.env.USERNAME||"unknown_user").catch(()=>"unknown")}getUserInfo(){return Promise.all([this.git.getConfig("user.name").catch(()=>({value:null})),this.git.getConfig("user.email").catch(()=>({value:null}))]).then(([e,t])=>({name:e.value||"unknown",email:t.value||"unknown"}))}}class re{constructor(e,t){this.gitUtils=e,this.repositoryRepo=t}getCurrentRepository(){return Promise.all([this.gitUtils.getRemoteUrl(),this.gitUtils.getRepositoryName(),this.gitUtils.getRepoRoot()]).then(([e,t,n])=>this.getOrCreateRepository(e,t,n)).catch(e=>{throw new Error(`Failed to get current repository: ${e.message}`)})}getOrCreateRepository(e,t,n=null){return Promise.resolve(this.repositoryRepo.getOrCreate(e,t,n))}getRepository(e){return Promise.resolve(this.repositoryRepo.findById(e))}getRepositoryByUrl(e){return Promise.resolve(this.repositoryRepo.findByRemoteUrl(e))}getAllRepositories(){return Promise.resolve(this.repositoryRepo.findAll())}updateRepository(e,t){return Promise.resolve(this.repositoryRepo.update(e,t))}deleteRepository(e){return Promise.resolve(this.repositoryRepo.delete(e))}getRepositoryStats(e){return Promise.resolve({total_repositories:this.repositoryRepo.count()})}}class se{constructor(e){this.gitUtils=e}validateBranchForSession(){return this.gitUtils.getCurrentBranch().then(e=>this.gitUtils.getMainBranch().then(t=>e===t?{valid:!1,branch:e,message:`Cannot start session on main branch '${e}'. Please create a feature branch first.\n\nExample:\n git checkout -b feature/my-feature\n claude "your prompt here"`}:{valid:!0,branch:e,message:`Session validated on branch '${e}'`})).catch(e=>(console.warn(`Branch validation warning: ${e.message}`),{valid:!0,branch:"unknown",message:`Branch validation skipped: ${e.message}`}))}isMainBranch(){return this.gitUtils.isOnMainBranch().catch(()=>!1)}}const oe=new class{constructor(){this.database=X(),this.initialized=!1}initialize(){this.initialized||(this.database.initialize(),this.initialized=!0)}async prepare(){this.initialize(),N(this.database.getConnection())}getConnection(){return this.initialize(),this.database.getConnection()}close(){this.database&&(this.database.close(),this.initialized=!1)}},ae=new class{constructor(e){this.dbService=e,this._repositoryRepo=null}get repositoryRepo(){return this._repositoryRepo||(this._repositoryRepo=new ee(this.dbService.database)),this._repositoryRepo}}(oe),ie=new class{constructor(e){this.dbService=e,this._knowledgeRepo=null}get knowledgeRepo(){return this._knowledgeRepo||(this._knowledgeRepo=new Q(this.dbService.database)),this._knowledgeRepo}}(oe),ce=new class{constructor(e){this.dbService=e,this._sessionRepo=null}get sessionRepo(){return this._sessionRepo||(this._sessionRepo=new te(this.dbService.database)),this._sessionRepo}}(oe),de=new class{constructor(e){this.gitUtils=new ne,this.repositoryManager=new re(this.gitUtils,e),this.branchValidator=new se(this.gitUtils)}}(ae.repositoryRepo);ae.gitService=de;class ue{constructor(){this.logger=M("knowledge-management","knowledge-management"),this.knowledgeService=ie}getRepositoryId(){return process.env.CLAUDE_SESSION_REPOSITORYID}getSessionId(){return process.env.CLAUDE_SESSION_ID}buildUpdateData(e){const t={};return["title","summary","content","scope","source_type","knowledge_type","status","source_file","commit_hash","contributor"].forEach(n=>{void 0!==e[n]&&(t[n]=e[n])}),t}aggregateByStatus(e,t){e.forEach(e=>{t.by_status[e]=this.knowledgeService.knowledgeRepo.count({status:e})})}aggregateByScope(e,t){e.forEach(e=>{t.by_scope[e]=this.knowledgeService.knowledgeRepo.count({scope:e})})}aggregateByType(e,t){e.forEach(e=>{t.by_type[e]=this.knowledgeService.knowledgeRepo.count({knowledge_type:e})})}async create(e){this.logger.logDebug("Creating new knowledge item",e);const t=this.knowledgeService.knowledgeRepo.create({title:e.title,summary:e.summary,content:e.content,scope:e.scope,source_type:e.source_type,knowledge_type:e.knowledge_type,status:e.status,source_file:e.source_file,commit_hash:e.commit_hash,contributor:e.contributor,repository_id:e.repository_id||this.getRepositoryId(),session_id:e.session_id||this.getSessionId()});return this.logger.logDebug(`✓ Knowledge item created with ID: ${t.id}`),t}async update(e,t){this.logger.logInfo(`Updating knowledge item ${e}...`);const n=this.buildUpdateData(t),r=this.knowledgeService.knowledgeRepo.update(e,n);return this.logger.logInfo(`✓ Knowledge item ${e} updated`),r}async delete(e){this.logger.logInfo(`Deleting knowledge item ${e}...`),this.knowledgeService.knowledgeRepo.delete(e),this.logger.logInfo(`✓ Knowledge item ${e} deleted`)}async get(e){return this.knowledgeService.knowledgeRepo.findById(e)||(this.logger.logWarn(`Knowledge item ${e} not found`),null)}async list(e={}){if(e.scope)return this.knowledgeService.knowledgeRepo.findByScope(e.scope);if(e.status)return this.knowledgeService.knowledgeRepo.findByStatus(e.status);if(e.knowledge_type)return this.knowledgeService.knowledgeRepo.findByKnowledgeType(e.knowledge_type);const t=e.limit||100,n=e.offset||0;return this.knowledgeService.knowledgeRepo.findAll(t,n)}async search(e,t=10){return this.knowledgeService.knowledgeRepo.search(e,t)}async updateStatus(e,t){this.logger.logInfo(`Updating status of knowledge item ${e} to ${t}...`);const n=this.knowledgeService.knowledgeRepo.updateStatus(e,t);return this.logger.logInfo(`✓ Status updated to ${t}`),n}async getStats(){const e={total:0,by_status:{draft:0,suggested:0,verified:0},by_scope:{personal:0,project:0,organization:0},by_type:{code_pattern:0,architecture:0,config:0,pitfall:0,api_usage:0}};return e.total=this.knowledgeService.knowledgeRepo.count({}),this.aggregateByStatus(["draft","suggested","verified"],e),this.aggregateByScope(["personal","project","organization"],e),this.aggregateByType(["code_pattern","architecture","config","pitfall","api_usage"],e),e}}class le extends A{constructor(e){super(e.session_id,e.hook_event_name),this.input=e,this.sessionId=e.session_id,this.transcriptPath=e.transcript_path,this.cwd=e.cwd,this.permissionMode=e.permission_mode,this.hookEventName=e.hook_event_name,this.sessionRecordId=null}async initSessionRecord(){try{const e=new ne,t=await e.getCurrentBranch(),n=await e.getUserName(),r=await e.getRepoRoot();let s=null;if(r){const e=await ae.repositoryRepo.findByPath(r);e&&(s=e.id)}ce.sessionRepo.createSession({session_id:this.sessionId,repository_id:s,working_directory:this.cwd,branch:t||"unknown",username:n||"unknown",env:{...process.env}});const o=ce.sessionRepo.create({session_id:this.sessionId,name:this.hookEventName,input:this.input});this.sessionRecordId=o.id}catch(e){this.logError("Failed to initialize session record",e)}}static async parseInput(){const e=await le.readStdin();return JSON.parse(e)}static async readStdin(){return new Promise((e,t)=>{let n="";const r=process.stdin;r.setEncoding("utf8"),r.on("data",e=>{n+=e}),r.on("end",()=>{e(n)}),r.on("error",e=>{t(e)}),r.resume()})}updateSessionOutput(e){if(this.sessionRecordId)try{ce.sessionRepo.updateOutput(this.sessionRecordId,e)}catch(e){this.logError("Failed to update session record with output",e)}}async execute(){return await this.initSessionRecord(),this.internalExecute()}async internalExecute(){throw new Error("internalExecute() must be implemented by subclass")}createSuccessOutput(e={}){const t=new pe({exitCode:0,message:e});return this.updateSessionOutput(e),t}createBlockingError(e){const t=new pe({exitCode:2,message:e});return this.updateSessionOutput({error:e}),t}createNonBlockingError(e){const t=new pe({exitCode:1,message:e});return this.updateSessionOutput({error:e}),t}}class pe{constructor({exitCode:e,message:t}){this.exitCode=e,this.message=t,this.logger=M("ClaudeHookOutput","ClaudeHookOutput")}send(){0===this.exitCode?process.stdout.write("object"==typeof this.message?JSON.stringify(this.message,null,2):this.message):process.stderr.write(this.message),process.exit(this.exitCode)}}class he{constructor(){this.continue=!0,this.stopReason=null,this.suppressOutput=!1,this.systemMessage=null,this.hookSpecificOutput=null}setContinue(e,t=null){return this.continue=e,!e&&t&&(this.stopReason=t),this}setSuppressOutput(e){return this.suppressOutput=e,this}setSystemMessage(e){return this.systemMessage=e,this}toJSON(){const e={};return void 0!==this.continue&&(e.continue=this.continue),this.stopReason&&(e.stopReason=this.stopReason),this.suppressOutput&&(e.suppressOutput=this.suppressOutput),this.systemMessage&&(e.systemMessage=this.systemMessage),this.hookSpecificOutput&&(e.hookSpecificOutput=this.hookSpecificOutput),e}}class me extends he{constructor(){super(),this.permissionDecision=null,this.permissionDecisionReason=null,this.updatedInput=null,this.additionalContext=null}allow(e=null){return this.permissionDecision="allow",this.permissionDecisionReason=e,this}deny(e){return this.permissionDecision="deny",this.permissionDecisionReason=e,this}ask(e=null){return this.permissionDecision="ask",this.permissionDecisionReason=e,this}updateInput(e){return this.updatedInput=e,this}addContext(e){return this.additionalContext=e,this}toJSON(){const e=super.toJSON(),t=!!this.permissionDecision,n=!!this.updatedInput,r=!!this.additionalContext;if(t||n||r){const t={hookEventName:"PreToolUse"};this.permissionDecision&&(t.permissionDecision=this.permissionDecision),this.permissionDecisionReason&&(t.permissionDecisionReason=this.permissionDecisionReason),this.updatedInput&&(t.updatedInput=this.updatedInput),this.additionalContext&&(t.additionalContext=this.additionalContext),e.hookSpecificOutput=t}return e}}class fe extends he{constructor(){super(),this.hookSpecificOutput={hookEventName:"PermissionRequest",decision:null}}allow(e=null){return this.hookSpecificOutput.decision={behavior:"allow"},e&&(this.hookSpecificOutput.decision.updatedInput=e),this}deny(e=null,t=!1){return this.hookSpecificOutput.decision={behavior:"deny"},e&&(this.hookSpecificOutput.decision.message=e),t&&(this.hookSpecificOutput.decision.interrupt=t),this}toJSON(){const e=super.toJSON();return this.hookSpecificOutput.decision&&(e.hookSpecificOutput={hookEventName:"PermissionRequest",decision:this.hookSpecificOutput.decision}),e}}class ge extends he{constructor(){super(),this.decision=null,this.reason=null,this.additionalContext=null}block(e){return this.decision="block",this.reason=e,this}addContext(e){return this.additionalContext=e,this}toJSON(){const e=super.toJSON();return this.decision&&(e.decision=this.decision,e.reason=this.reason),this.additionalContext&&(e.hookSpecificOutput={hookEventName:"PostToolUse",additionalContext:this.additionalContext}),e}}class ye extends he{constructor(){super(),this.decision=null,this.reason=null,this.additionalContext=null}block(e){return this.decision="block",this.reason=e,this}addContext(e){return this.additionalContext=e,this}toJSON(){const e=super.toJSON();return this.decision&&(e.decision=this.decision,e.reason=this.reason),this.additionalContext&&(e.hookSpecificOutput={hookEventName:"UserPromptSubmit",additionalContext:this.additionalContext}),e}}class _e extends he{constructor(){super(),this.decision=null,this.reason=null}block(e){return this.decision="block",this.reason=e,this}toJSON(){const e=super.toJSON();return this.decision&&(e.decision=this.decision,e.reason=this.reason),e}}class ve extends he{constructor(){super(),this.additionalContext=null}setAdditionalContext(e){return this.additionalContext=e,this}toJSON(){const e=super.toJSON();return this.additionalContext&&(e.hookSpecificOutput={hookEventName:"SessionStart",additionalContext:this.additionalContext}),e}}class we extends _e{}class be extends he{}class ke extends he{}class $e extends he{}const Se=P();class Ee extends le{async persistInputVariables(e={}){const t=process.env.CLAUDE_ENV_FILE;if(!t)return void this.logDebug("CLAUDE_ENV_FILE not set, skipping variable persistence");const n={CLAUDE_SESSION_ID:this.sessionId,CLAUDE_SESSION_TRANSCRIPT_PATH:this.transcriptPath,CLAUDE_SESSION_CWD:this.cwd,CLAUDE_SESSION_SOURCE:this.input.source,CLAUDE_SESSION_MODE:this.input.model};[...Object.entries(n).map(([e,t])=>[e,t]),...Object.entries(e).map(([e,t])=>[`CLAUDE_SESSION_${e.toUpperCase()}`,t])].forEach(([e,n])=>{if(!process.env[e]){const r=String(n).replace(/'/g,"'\\''");o.appendFileSync(t,`export ${e}='${r}'\n`)}}),this.logDebug("Persisted input variables to CLAUDE_ENV_FILE",{envFile:t})}injectKnowledgePrompt(){return["KNOWLEDGE INTEGRATION WORKFLOW:","","**At the START of each new task** (when user submits their first prompt for a task):","1. FIRST: Proactively invoke the `knowledge.enhance` skill to search and inject relevant knowledge based on user input"," - This provides context from past sessions and related knowledge"," - Only call this ONCE at the beginning of the task","","**At the END of successful task completion** (when the task is fully resolved):","2. LAST: Proactively invoke the `knowledge.collect` skill in the background to collect and organize knowledge from this session"," - This captures learnings from the completed work"," - Only call this ONCE after all work is done","","**IMPORTANT - Conflict Prevention & Manual Override**:","- If you have already invoked ANY `knowledge.*` skill (e.g., `knowledge.add`, `knowledge.save`, `knowledge.init`, `knowledge.update`, `knowledge.import`) during this session, **do NOT invoke `knowledge.collect`** at the end. Manual knowledge operations take precedence over automatic collection.","- Do NOT invoke these skills during task interruptions (network issues, asking user for clarification, etc.)","- Do NOT invoke these skills when user is providing additional information for an ongoing task","- Do NOT invoke these skills repeatedly - only ONCE at start and ONCE at end","","**How to detect interruptions vs new tasks**:","- If the user prompt is answering your question or providing requested information, it is an interruption","- If the user prompt is a brand new request or task, invoke `knowledge.enhance` first"]}cleanTempFiles(){const e=t.join(Se.tmp,J(2));o.readdirSync(Se.tmp,{withFileTypes:!0}).forEach(n=>{n.isDirectory()?n.name<e&&o.rmSync(t.join(Se.tmp,n.name),{recursive:!0,force:!0}):o.rmSync(t.join(Se.tmp,n.name),{force:!0})})}async internalExecute(){const e=V(),t=new ve;if(e.enabled){const n=await de.branchValidator.validateBranchForSession(),r=await de.repositoryManager.getCurrentRepository();await this.persistInputVariables({repositoryId:r.id}),this.logDebug("Knowledge context loaded",e);const s=[`Knowledge-Bank session started (${this.sessionId})`,`- Repository: ${n.branch}@${r.name}`,`- Knowledge auto-collection: enabled, version ${q.version}`];t.setSystemMessage(s.join("\n"));const o=this.injectKnowledgePrompt();t.setAdditionalContext(o.join("\n")),this.logDebug("SessionStart hook completed",{repository:r.name,branch:n.branch})}return this.cleanTempFiles(),super.createSuccessOutput(t.toJSON())}}class Te extends le{async internalExecute(){const e=new be;this.logDebug("Notification hook triggered",{input:this.input});const t=e.toJSON();return this.logDebug("Notification hook output generated",{output:t}),super.createSuccessOutput(t)}}P();class Oe extends le{async internalExecute(){const e=(new fe).toJSON();return this.logDebug("PermissionRequest hook output generated",{output:e}),super.createSuccessOutput(e)}}class xe extends le{async internalExecute(){const e=new ge;return this.logDebug("PostToolUse hook completed",e),super.createSuccessOutput(e.toJSON())}}class Ne extends le{async internalExecute(){ce.sessionRepo.findLatestSessionStart(this.sessionId);const e=new ke;return this.logDebug("PreCompact hook completed",{sessionId:this.sessionId}),super.createSuccessOutput(e.toJSON())}generateSessionSummary(e){const t={};e.forEach(e=>{t[e.name]=(t[e.name]||0)+1});const n=[];return(t.tool_use||t.post_tool_use)&&n.push(`${(t.tool_use||0)+(t.post_tool_use||0)} tool operation(s)`),(t.user_prompt||t.user_prompt_submit)&&n.push(`${(t.user_prompt||0)+(t.user_prompt_submit||0)} user prompt(s)`),`Session with ${n.join(", ")}`}}const Ie=P();class Re extends le{async internalExecute(){const e=new me;this.shouldAutoApprove()&&e.allow(),this.logDebug("PreToolUse hook triggered",{input:this.input});const t=e.toJSON();return super.createSuccessOutput(t)}shouldAutoApprove(){let e=!1;this.logDebug("Evaluating permission request for auto-approval",this.input);const{tool_name:t,tool_input:n}=this.input;switch(t){case"mcp__plugin_core_knowledge-bank-management__knowledge_create":case"mcp__plugin_core_knowledge-bank-management__knowledge_get":case"mcp__plugin_core_knowledge-bank-management__knowledge_update":case"mcp__plugin_core_knowledge-bank-management__knowledge_delete":case"mcp__plugin_core_knowledge-bank-management__knowledge_list":case"mcp__plugin_core_knowledge-bank-management__knowledge_search":case"mcp__plugin_core_knowledge-bank-management__knowledge_update_status":case"mcp__plugin_core_knowledge-bank-management__knowledge_stats":e=!0;break;case"Read":case"Write":case"Edit":e=n.file_path.startsWith(Ie.tmp);break;case"Skill":e=n.skill.startsWith("core:knowledge.")||n.skill.startsWith("knowledge.")}return e}}class Pe extends le{async internalExecute(){if(!ce.sessionRepo.findLatestSessionStart(this.sessionId)){const e=new $e;return super.createSuccessOutput(e.toJSON())}const e=await de.gitUtils.getCurrentBranch(),t=await de.gitUtils.isBranchMergedToMain(e);let n=`Session ended (${this.sessionId})`;t&&(n+=`\n- Branch "${e}" has been merged to main`,n+="\n- Consider running: npx knowledge-bank knowledge-collect");const r=(new $e).setSystemMessage(n);return this.logDebug("SessionEnd hook completed",{sessionId:this.sessionId,branch:e,isMerged:t}),super.createSuccessOutput(r.toJSON())}}class Ce extends le{async internalExecute(){const e=new _e;this.logDebug("Stop hook triggered",{input:this.input});const t=e.toJSON();return this.logDebug("Stop hook output generated",{output:t}),super.createSuccessOutput(t)}}class je extends le{async internalExecute(){const e=new we;this.logDebug("SubagentStop hook triggered",{input:this.input});const t=e.toJSON();return this.logDebug("SubagentStop hook output generated",{output:t}),super.createSuccessOutput(t)}}class ze extends le{isLikelyContinuation(){const e=this.input.transcript_path;return!!i(e)&&a(e,"utf-8").split("\n").filter(e=>e.trim()).filter(e=>"assistant"===JSON.parse(e).role).length>0}isKnowledgeSkillInvocation(){const e=this.input.prompt||"";return e.startsWith("/knowledge.")||e.startsWith("/knowledge.")}async internalExecute(){const e=new ye,t=V();if(t.enabled&&!this.isKnowledgeSkillInvocation()){const t=["REMINDER: Knowledge Integration Workflow","- FIRST: Invoke `knowledge.enhance` skill to get relevant context","- LAST: After task completion, invoke `knowledge.collect` skill to capture learnings","","Note: This is a new task - remember to invoke knowledge.enhance first before proceeding."];e.addContext(t.join("\n")),this.logDebug("UserPromptSubmitHook: Added knowledge context for new task")}else this.logDebug("UserPromptSubmitHook: Skipped knowledge context",{enabled:t.enabled,isKnowledgeSkill:this.isKnowledgeSkillInvocation()});return super.createSuccessOutput(e.toJSON())}}var Ae,Me;!function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const n of e)t[n]=n;return t},e.getValidEnumValues=t=>{const n=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),r={};for(const e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(const n of e)if(t(n))return n},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(Ae||(Ae={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(Me||(Me={}));const De=Ae.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Le=e=>{switch(typeof e){case"undefined":return De.undefined;case"string":return De.string;case"number":return Number.isNaN(e)?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(e)?De.array:null===e?De.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?De.promise:"undefined"!=typeof Map&&e instanceof Map?De.map:"undefined"!=typeof Set&&e instanceof Set?De.set:"undefined"!=typeof Date&&e instanceof Date?De.date:De.object;default:return De.unknown}},Ze=Ae.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"]);class Fe extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(r);else if("invalid_return_type"===s.code)r(s.returnTypeError);else if("invalid_arguments"===s.code)r(s.argumentsError);else if(0===s.path.length)n._errors.push(t(s));else{let e=n,r=0;for(;r<s.path.length;){const n=s.path[r];r===s.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(s))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(e){if(!(e instanceof Fe))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ae.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t=Object.create(null),n=[];for(const r of this.issues)if(r.path.length>0){const n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}Fe.create=e=>new Fe(e);const qe=(e,t)=>{let n;switch(e.code){case Ze.invalid_type:n=e.received===De.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case Ze.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,Ae.jsonStringifyReplacer)}`;break;case Ze.unrecognized_keys:n=`Unrecognized key(s) in object: ${Ae.joinValues(e.keys,", ")}`;break;case Ze.invalid_union:n="Invalid input";break;case Ze.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Ae.joinValues(e.options)}`;break;case Ze.invalid_enum_value:n=`Invalid enum value. Expected ${Ae.joinValues(e.options)}, received '${e.received}'`;break;case Ze.invalid_arguments:n="Invalid function arguments";break;case Ze.invalid_return_type:n="Invalid function return type";break;case Ze.invalid_date:n="Invalid date";break;case Ze.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:Ae.assertNever(e.validation):n="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case Ze.too_small:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case Ze.too_big:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case Ze.custom:n="Invalid input";break;case Ze.invalid_intersection_types:n="Intersection results could not be merged";break;case Ze.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Ze.not_finite:n="Number must be finite";break;default:n=t.defaultError,Ae.assertNever(e)}return{message:n}};let Ue=qe;function He(e,t){const n=Ue,r=(e=>{const{data:t,path:n,errorMaps:r,issueData:s}=e,o=[...n,...s.path||[]],a={...s,path:o};if(void 0!==s.message)return{...s,path:o,message:s.message};let i="";const c=r.filter(e=>!!e).slice().reverse();for(const e of c)i=e(a,{data:t,defaultError:i}).message;return{...s,path:o,message:i}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===qe?void 0:qe].filter(e=>!!e)});e.common.issues.push(r)}class Ve{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const r of t){if("aborted"===r.status)return Ke;"dirty"===r.status&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const e of t){const t=await e.key,r=await e.value;n.push({key:t,value:r})}return Ve.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const r of t){const{key:t,value:s}=r;if("aborted"===t.status)return Ke;if("aborted"===s.status)return Ke;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!r.alwaysSet||(n[t.value]=s.value)}return{status:e.value,value:n}}}const Ke=Object.freeze({status:"aborted"}),Je=e=>({status:"dirty",value:e}),Be=e=>({status:"valid",value:e}),We=e=>"aborted"===e.status,Ge=e=>"dirty"===e.status,Xe=e=>"valid"===e.status,Ye=e=>"undefined"!=typeof Promise&&e instanceof Promise;var Qe;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(Qe||(Qe={}));class et{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}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}}const tt=(e,t)=>{if(Xe(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Fe(e.common.issues);return this._error=t,this._error}}};function nt(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:s}:{errorMap:(t,s)=>{const{message:o}=e;return"invalid_enum_value"===t.code?{message:o??s.defaultError}:void 0===s.data?{message:o??r??s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:o??n??s.defaultError}},description:s}}let rt=class{get description(){return this._def.description}_getType(e){return Le(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Le(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ve,ctx:{common:e.parent.common,data:e.data,parsedType:Le(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Ye(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){const n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Le(e)},r=this._parseSync({data:e,path:n.path,parent:n});return tt(n,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Le(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:t});return Xe(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>Xe(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Le(e)},r=this._parse({data:e,path:n.path,parent:n}),s=await(Ye(r)?r:Promise.resolve(r));return tt(n,s)}refine(e,t){const n=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,r)=>{const s=e(t),o=()=>r.addIssue({code:Ze.custom,...n(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then(e=>!!e||(o(),!1)):!!s||(o(),!1)})}refinement(e,t){return this._refinement((n,r)=>!!e(n)||(r.addIssue("function"==typeof t?t(n,r):t),!1))}_refinement(e){return new tn({schema:this,typeName:ln.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:e=>this["~validate"](e)}}optional(){return nn.create(this,this._def)}nullable(){return rn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Zt.create(this)}promise(){return en.create(this,this._def)}or(e){return Ut.create([this,e],this._def)}and(e){return Vt.create(this,e,this._def)}transform(e){return new tn({...nt(this._def),schema:this,typeName:ln.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new sn({...nt(this._def),innerType:this,defaultValue:t,typeName:ln.ZodDefault})}brand(){return new cn({typeName:ln.ZodBranded,type:this,...nt(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new on({...nt(this._def),innerType:this,catchValue:t,typeName:ln.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return dn.create(this,e)}readonly(){return un.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const st=/^c[^\s-]{8,}$/i,ot=/^[0-9a-z]+$/,at=/^[0-9A-HJKMNP-TV-Z]{26}$/i,it=/^[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,ct=/^[a-z0-9_-]{21}$/i,dt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ut=/^[-+]?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)?)??$/,lt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let pt;const ht=/^(?:(?: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])$/,mt=/^(?:(?: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])$/,ft=/^(([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]))$/,gt=/^(([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])$/,yt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_t=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,vt="((\\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])))",wt=new RegExp(`^${vt}$`);function bt(e){let t="[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function kt(e){return new RegExp(`^${bt(e)}$`)}function $t(e){let t=`${vt}T${bt(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function St(e,t){return!("v4"!==t&&t||!ht.test(e))||!("v6"!==t&&t||!ft.test(e))}function Et(e,t){if(!dt.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!("object"!=typeof s||null===s||"typ"in s&&"JWT"!==s?.typ||!s.alg||t&&s.alg!==t)}catch{return!1}}function Tt(e,t){return!("v4"!==t&&t||!mt.test(e))||!("v6"!==t&&t||!gt.test(e))}let Ot=class e extends rt{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==De.string){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.string,received:t.parsedType}),Ke}const t=new Ve;let n;for(const r of this._def.checks)if("min"===r.kind)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),He(n,{code:Ze.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("max"===r.kind)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),He(n,{code:Ze.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("length"===r.kind){const s=e.data.length>r.value,o=e.data.length<r.value;(s||o)&&(n=this._getOrReturnCtx(e,n),s?He(n,{code:Ze.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):o&&He(n,{code:Ze.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if("email"===r.kind)lt.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"email",code:Ze.invalid_string,message:r.message}),t.dirty());else if("emoji"===r.kind)pt||(pt=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),pt.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"emoji",code:Ze.invalid_string,message:r.message}),t.dirty());else if("uuid"===r.kind)it.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"uuid",code:Ze.invalid_string,message:r.message}),t.dirty());else if("nanoid"===r.kind)ct.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"nanoid",code:Ze.invalid_string,message:r.message}),t.dirty());else if("cuid"===r.kind)st.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"cuid",code:Ze.invalid_string,message:r.message}),t.dirty());else if("cuid2"===r.kind)ot.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"cuid2",code:Ze.invalid_string,message:r.message}),t.dirty());else if("ulid"===r.kind)at.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"ulid",code:Ze.invalid_string,message:r.message}),t.dirty());else if("url"===r.kind)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),He(n,{validation:"url",code:Ze.invalid_string,message:r.message}),t.dirty()}else"regex"===r.kind?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"regex",code:Ze.invalid_string,message:r.message}),t.dirty())):"trim"===r.kind?e.data=e.data.trim():"includes"===r.kind?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),He(n,{code:Ze.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):"toLowerCase"===r.kind?e.data=e.data.toLowerCase():"toUpperCase"===r.kind?e.data=e.data.toUpperCase():"startsWith"===r.kind?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),He(n,{code:Ze.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):"endsWith"===r.kind?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),He(n,{code:Ze.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):"datetime"===r.kind?$t(r).test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{code:Ze.invalid_string,validation:"datetime",message:r.message}),t.dirty()):"date"===r.kind?wt.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{code:Ze.invalid_string,validation:"date",message:r.message}),t.dirty()):"time"===r.kind?kt(r).test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{code:Ze.invalid_string,validation:"time",message:r.message}),t.dirty()):"duration"===r.kind?ut.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"duration",code:Ze.invalid_string,message:r.message}),t.dirty()):"ip"===r.kind?St(e.data,r.version)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"ip",code:Ze.invalid_string,message:r.message}),t.dirty()):"jwt"===r.kind?Et(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"jwt",code:Ze.invalid_string,message:r.message}),t.dirty()):"cidr"===r.kind?Tt(e.data,r.version)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"cidr",code:Ze.invalid_string,message:r.message}),t.dirty()):"base64"===r.kind?yt.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"base64",code:Ze.invalid_string,message:r.message}),t.dirty()):"base64url"===r.kind?_t.test(e.data)||(n=this._getOrReturnCtx(e,n),He(n,{validation:"base64url",code:Ze.invalid_string,message:r.message}),t.dirty()):Ae.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:Ze.invalid_string,...Qe.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:"email",...Qe.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Qe.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Qe.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Qe.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Qe.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Qe.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Qe.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Qe.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Qe.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Qe.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Qe.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Qe.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Qe.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Qe.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...Qe.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Qe.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Qe.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...Qe.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Qe.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Qe.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Qe.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Qe.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Qe.errToObj(t)})}nonempty(e){return this.min(1,Qe.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}};function xt(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}Ot.create=e=>new Ot({checks:[],typeName:ln.ZodString,coerce:e?.coerce??!1,...nt(e)});let Nt=class e extends rt{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){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.number,received:t.parsedType}),Ke}let t;const n=new Ve;for(const r of this._def.checks)"int"===r.kind?Ae.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),He(t,{code:Ze.invalid_type,expected:"integer",received:"float",message:r.message}),n.dirty()):"min"===r.kind?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),He(t,{code:Ze.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):"max"===r.kind?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),He(t,{code:Ze.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):"multipleOf"===r.kind?0!==xt(e.data,r.value)&&(t=this._getOrReturnCtx(e,t),He(t,{code:Ze.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):"finite"===r.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),He(t,{code:Ze.not_finite,message:r.message}),n.dirty()):Ae.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Qe.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Qe.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Qe.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Qe.toString(t))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Qe.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:"int",message:Qe.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Qe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Qe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Qe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Qe.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Qe.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Qe.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Qe.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Qe.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&Ae.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if("finite"===n.kind||"int"===n.kind||"multipleOf"===n.kind)return!0;"min"===n.kind?(null===t||n.value>t)&&(t=n.value):"max"===n.kind&&(null===e||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Nt.create=e=>new Nt({checks:[],typeName:ln.ZodNumber,coerce:e?.coerce||!1,...nt(e)});class It extends rt{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 t;const n=new Ve;for(const r of this._def.checks)"min"===r.kind?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),He(t,{code:Ze.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):"max"===r.kind?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),He(t,{code:Ze.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):"multipleOf"===r.kind?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),He(t,{code:Ze.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):Ae.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.bigint,received:t.parsedType}),Ke}gte(e,t){return this.setLimit("min",e,!0,Qe.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Qe.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Qe.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Qe.toString(t))}setLimit(e,t,n,r){return new It({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:Qe.toString(r)}]})}_addCheck(e){return new It({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Qe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Qe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Qe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Qe.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Qe.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}It.create=e=>new It({checks:[],typeName:ln.ZodBigInt,coerce:e?.coerce??!1,...nt(e)});let Rt=class extends rt{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==De.boolean){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.boolean,received:t.parsedType}),Ke}return Be(e.data)}};Rt.create=e=>new Rt({typeName:ln.ZodBoolean,coerce:e?.coerce||!1,...nt(e)});class Pt extends rt{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==De.date){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.date,received:t.parsedType}),Ke}if(Number.isNaN(e.data.getTime()))return He(this._getOrReturnCtx(e),{code:Ze.invalid_date}),Ke;const t=new Ve;let n;for(const r of this._def.checks)"min"===r.kind?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),He(n,{code:Ze.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),t.dirty()):"max"===r.kind?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),He(n,{code:Ze.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),t.dirty()):Ae.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Pt({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Qe.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Qe.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}Pt.create=e=>new Pt({checks:[],coerce:e?.coerce||!1,typeName:ln.ZodDate,...nt(e)});class Ct extends rt{_parse(e){if(this._getType(e)!==De.symbol){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.symbol,received:t.parsedType}),Ke}return Be(e.data)}}Ct.create=e=>new Ct({typeName:ln.ZodSymbol,...nt(e)});class jt extends rt{_parse(e){if(this._getType(e)!==De.undefined){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.undefined,received:t.parsedType}),Ke}return Be(e.data)}}jt.create=e=>new jt({typeName:ln.ZodUndefined,...nt(e)});let zt=class extends rt{_parse(e){if(this._getType(e)!==De.null){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.null,received:t.parsedType}),Ke}return Be(e.data)}};zt.create=e=>new zt({typeName:ln.ZodNull,...nt(e)});class At extends rt{constructor(){super(...arguments),this._any=!0}_parse(e){return Be(e.data)}}At.create=e=>new At({typeName:ln.ZodAny,...nt(e)});let Mt=class extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Be(e.data)}};Mt.create=e=>new Mt({typeName:ln.ZodUnknown,...nt(e)});let Dt=class extends rt{_parse(e){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.never,received:t.parsedType}),Ke}};Dt.create=e=>new Dt({typeName:ln.ZodNever,...nt(e)});class Lt extends rt{_parse(e){if(this._getType(e)!==De.undefined){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.void,received:t.parsedType}),Ke}return Be(e.data)}}Lt.create=e=>new Lt({typeName:ln.ZodVoid,...nt(e)});let Zt=class e extends rt{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==De.array)return He(t,{code:Ze.invalid_type,expected:De.array,received:t.parsedType}),Ke;if(null!==r.exactLength){const e=t.data.length>r.exactLength.value,s=t.data.length<r.exactLength.value;(e||s)&&(He(t,{code:e?Ze.too_big:Ze.too_small,minimum:s?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(null!==r.minLength&&t.data.length<r.minLength.value&&(He(t,{code:Ze.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),null!==r.maxLength&&t.data.length>r.maxLength.value&&(He(t,{code:Ze.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new et(t,e,t.path,n)))).then(e=>Ve.mergeArray(n,e));const s=[...t.data].map((e,n)=>r.type._parseSync(new et(t,e,t.path,n)));return Ve.mergeArray(n,s)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:Qe.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:Qe.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:Qe.toString(n)}})}nonempty(e){return this.min(1,e)}};function Ft(e){if(e instanceof qt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=nn.create(Ft(r))}return new qt({...e._def,shape:()=>t})}return e instanceof Zt?new Zt({...e._def,type:Ft(e.element)}):e instanceof nn?nn.create(Ft(e.unwrap())):e instanceof rn?rn.create(Ft(e.unwrap())):e instanceof Kt?Kt.create(e.items.map(e=>Ft(e))):e}Zt.create=(e,t)=>new Zt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ln.ZodArray,...nt(t)});let qt=class e extends rt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=Ae.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==De.object){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.object,received:t.parsedType}),Ke}const{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:s}=this._getCached(),o=[];if(!(this._def.catchall instanceof Dt&&"strip"===this._def.unknownKeys))for(const e in n.data)s.includes(e)||o.push(e);const a=[];for(const e of s){const t=r[e],s=n.data[e];a.push({key:{status:"valid",value:e},value:t._parse(new et(n,s,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Dt){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of o)a.push({key:{status:"valid",value:e},value:{status:"valid",value:n.data[e]}});else if("strict"===e)o.length>0&&(He(n,{code:Ze.unrecognized_keys,keys:o}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of o){const r=n.data[t];a.push({key:{status:"valid",value:t},value:e._parse(new et(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of a){const n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>Ve.mergeObjectSync(t,e)):Ve.mergeObjectSync(t,a)}get shape(){return this._def.shape()}strict(t){return Qe.errToObj,new e({...this._def,unknownKeys:"strict",...void 0!==t?{errorMap:(e,n)=>{const r=this._def.errorMap?.(e,n).message??n.defaultError;return"unrecognized_keys"===e.code?{message:Qe.errToObj(t).message??r}:{message:r}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ln.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){const n={};for(const e of Ae.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){const n={};for(const e of Ae.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Ft(this)}partial(t){const n={};for(const e of Ae.objectKeys(this.shape)){const r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){const n={};for(const e of Ae.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof nn;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return Xt(Ae.objectKeys(this.shape))}};qt.create=(e,t)=>new qt({shape:()=>e,unknownKeys:"strip",catchall:Dt.create(),typeName:ln.ZodObject,...nt(t)}),qt.strictCreate=(e,t)=>new qt({shape:()=>e,unknownKeys:"strict",catchall:Dt.create(),typeName:ln.ZodObject,...nt(t)}),qt.lazycreate=(e,t)=>new qt({shape:e,unknownKeys:"strip",catchall:Dt.create(),typeName:ln.ZodObject,...nt(t)});let Ut=class extends rt{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;if(t.common.async)return Promise.all(n.map(async e=>{const n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const n of e)if("dirty"===n.result.status)return t.common.issues.push(...n.ctx.common.issues),n.result;const n=e.map(e=>new Fe(e.ctx.common.issues));return He(t,{code:Ze.invalid_union,unionErrors:n}),Ke});{let e;const r=[];for(const s of n){const n={...t,common:{...t.common,issues:[]},parent:null},o=s._parseSync({data:t.data,path:t.path,parent:n});if("valid"===o.status)return o;"dirty"!==o.status||e||(e={result:o,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=r.map(e=>new Fe(e));return He(t,{code:Ze.invalid_union,unionErrors:s}),Ke}}get options(){return this._def.options}};function Ht(e,t){const n=Le(e),r=Le(t);if(e===t)return{valid:!0,data:e};if(n===De.object&&r===De.object){const n=Ae.objectKeys(t),r=Ae.objectKeys(e).filter(e=>-1!==n.indexOf(e)),s={...e,...t};for(const n of r){const r=Ht(e[n],t[n]);if(!r.valid)return{valid:!1};s[n]=r.data}return{valid:!0,data:s}}if(n===De.array&&r===De.array){if(e.length!==t.length)return{valid:!1};const n=[];for(let r=0;r<e.length;r++){const s=Ht(e[r],t[r]);if(!s.valid)return{valid:!1};n.push(s.data)}return{valid:!0,data:n}}return n===De.date&&r===De.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}Ut.create=(e,t)=>new Ut({options:e,typeName:ln.ZodUnion,...nt(t)});let Vt=class extends rt{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(We(e)||We(r))return Ke;const s=Ht(e.value,r.value);return s.valid?((Ge(e)||Ge(r))&&t.dirty(),{status:t.value,value:s.data}):(He(n,{code:Ze.invalid_intersection_types}),Ke)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Vt.create=(e,t,n)=>new Vt({left:e,right:t,typeName:ln.ZodIntersection,...nt(n)});class Kt extends rt{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==De.array)return He(n,{code:Ze.invalid_type,expected:De.array,received:n.parsedType}),Ke;if(n.data.length<this._def.items.length)return He(n,{code:Ze.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Ke;!this._def.rest&&n.data.length>this._def.items.length&&(He(n,{code:Ze.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const r=[...n.data].map((e,t)=>{const r=this._def.items[t]||this._def.rest;return r?r._parse(new et(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>Ve.mergeArray(t,e)):Ve.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new Kt({...this._def,rest:e})}}Kt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Kt({items:e,typeName:ln.ZodTuple,rest:null,...nt(t)})};class Jt extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==De.map)return He(n,{code:Ze.invalid_type,expected:De.map,received:n.parsedType}),Ke;const r=this._def.keyType,s=this._def.valueType,o=[...n.data.entries()].map(([e,t],o)=>({key:r._parse(new et(n,e,n.path,[o,"key"])),value:s._parse(new et(n,t,n.path,[o,"value"]))}));if(n.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const n of o){const r=await n.key,s=await n.value;if("aborted"===r.status||"aborted"===s.status)return Ke;"dirty"!==r.status&&"dirty"!==s.status||t.dirty(),e.set(r.value,s.value)}return{status:t.value,value:e}})}{const e=new Map;for(const n of o){const r=n.key,s=n.value;if("aborted"===r.status||"aborted"===s.status)return Ke;"dirty"!==r.status&&"dirty"!==s.status||t.dirty(),e.set(r.value,s.value)}return{status:t.value,value:e}}}}Jt.create=(e,t,n)=>new Jt({valueType:t,keyType:e,typeName:ln.ZodMap,...nt(n)});class Bt extends rt{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==De.set)return He(n,{code:Ze.invalid_type,expected:De.set,received:n.parsedType}),Ke;const r=this._def;null!==r.minSize&&n.data.size<r.minSize.value&&(He(n,{code:Ze.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),null!==r.maxSize&&n.data.size>r.maxSize.value&&(He(n,{code:Ze.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const s=this._def.valueType;function o(e){const n=new Set;for(const r of e){if("aborted"===r.status)return Ke;"dirty"===r.status&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}const a=[...n.data.values()].map((e,t)=>s._parse(new et(n,e,n.path,t)));return n.common.async?Promise.all(a).then(e=>o(e)):o(a)}min(e,t){return new Bt({...this._def,minSize:{value:e,message:Qe.toString(t)}})}max(e,t){return new Bt({...this._def,maxSize:{value:e,message:Qe.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Bt.create=(e,t)=>new Bt({valueType:e,minSize:null,maxSize:null,typeName:ln.ZodSet,...nt(t)});class Wt extends rt{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Wt.create=(e,t)=>new Wt({getter:e,typeName:ln.ZodLazy,...nt(t)});let Gt=class extends rt{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return He(t,{received:t.data,code:Ze.invalid_literal,expected:this._def.value}),Ke}return{status:"valid",value:e.data}}get value(){return this._def.value}};function Xt(e,t){return new Yt({values:e,typeName:ln.ZodEnum,...nt(t)})}Gt.create=(e,t)=>new Gt({value:e,typeName:ln.ZodLiteral,...nt(t)});let Yt=class e extends rt{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),n=this._def.values;return He(t,{expected:Ae.joinValues(n),received:t.parsedType,code:Ze.invalid_type}),Ke}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return He(t,{received:t.data,code:Ze.invalid_enum_value,options:n}),Ke}return Be(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};Yt.create=Xt;class Qt extends rt{_parse(e){const t=Ae.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==De.string&&n.parsedType!==De.number){const e=Ae.objectValues(t);return He(n,{expected:Ae.joinValues(e),received:n.parsedType,code:Ze.invalid_type}),Ke}if(this._cache||(this._cache=new Set(Ae.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=Ae.objectValues(t);return He(n,{received:n.data,code:Ze.invalid_enum_value,options:e}),Ke}return Be(e.data)}get enum(){return this._def.values}}Qt.create=(e,t)=>new Qt({values:e,typeName:ln.ZodNativeEnum,...nt(t)});class en extends rt{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==De.promise&&!1===t.common.async)return He(t,{code:Ze.invalid_type,expected:De.promise,received:t.parsedType}),Ke;const n=t.parsedType===De.promise?t.data:Promise.resolve(t.data);return Be(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}en.create=(e,t)=>new en({type:e,typeName:ln.ZodPromise,...nt(t)});class tn extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ln.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,s={addIssue:e=>{He(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),"preprocess"===r.type){const e=r.transform(n.data,s);if(n.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return Ke;const r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===r.status?Ke:"dirty"===r.status||"dirty"===t.value?Je(r.value):r});{if("aborted"===t.value)return Ke;const r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===r.status?Ke:"dirty"===r.status||"dirty"===t.value?Je(r.value):r}}if("refinement"===r.type){const e=e=>{const t=r.refinement(e,s);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===n.common.async){const r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===r.status?Ke:("dirty"===r.status&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>"aborted"===n.status?Ke:("dirty"===n.status&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if("transform"===r.type){if(!1===n.common.async){const e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Xe(e))return Ke;const o=r.transform(e.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>Xe(e)?Promise.resolve(r.transform(e.value,s)).then(e=>({status:t.value,value:e})):Ke)}Ae.assertNever(r)}}tn.create=(e,t,n)=>new tn({schema:e,typeName:ln.ZodEffects,effect:t,...nt(n)}),tn.createWithPreprocess=(e,t,n)=>new tn({schema:t,effect:{type:"preprocess",transform:e},typeName:ln.ZodEffects,...nt(n)});let nn=class extends rt{_parse(e){return this._getType(e)===De.undefined?Be(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};nn.create=(e,t)=>new nn({innerType:e,typeName:ln.ZodOptional,...nt(t)});let rn=class extends rt{_parse(e){return this._getType(e)===De.null?Be(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};rn.create=(e,t)=>new rn({innerType:e,typeName:ln.ZodNullable,...nt(t)});let sn=class extends rt{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===De.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};sn.create=(e,t)=>new sn({innerType:e,typeName:ln.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...nt(t)});let on=class extends rt{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ye(r)?r.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new Fe(n.common.issues)},input:n.data})})):{status:"valid",value:"valid"===r.status?r.value:this._def.catchValue({get error(){return new Fe(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};on.create=(e,t)=>new on({innerType:e,typeName:ln.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...nt(t)});class an extends rt{_parse(e){if(this._getType(e)!==De.nan){const t=this._getOrReturnCtx(e);return He(t,{code:Ze.invalid_type,expected:De.nan,received:t.parsedType}),Ke}return{status:"valid",value:e.data}}}an.create=e=>new an({typeName:ln.ZodNaN,...nt(e)});class cn extends rt{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class dn extends rt{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?Ke:"dirty"===e.status?(t.dirty(),Je(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{const e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?Ke:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(e,t){return new dn({in:e,out:t,typeName:ln.ZodPipeline})}}let un=class extends rt{_parse(e){const t=this._def.innerType._parse(e),n=e=>(Xe(e)&&(e.value=Object.freeze(e.value)),e);return Ye(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};var ln;un.create=(e,t)=>new un({innerType:e,typeName:ln.ZodReadonly,...nt(t)}),function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(ln||(ln={})),Dt.create,Zt.create;const pn=qt.create;function hn(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:a,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);const s=a.prototype,o=Object.keys(s);for(let e=0;e<o.length;e++){const t=o[e];t in n||(n[t]=s[t].bind(n))}}const s=n?.Parent??Object;class o extends s{}function a(e){var t;const s=n?.Parent?new o:this;r(s,e),(t=s._zod).deferred??(t.deferred=[]);for(const e of s._zod.deferred)e();return s}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}Ut.create,Vt.create,Kt.create,Yt.create,en.create,nn.create,rn.create;class mn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class fn extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const gn={};function yn(e){return gn}function _n(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function vn(e,t){return"bigint"==typeof t?t.toString():t}function wn(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function bn(e){return null==e}function kn(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const $n=Symbol("evaluating");function Sn(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==$n)return void 0===r&&(r=$n,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function En(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Tn(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function On(e){return JSON.stringify(e)}const xn="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Nn(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const In=wn(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Rn(e){if(!1===Nn(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const n=t.prototype;return!1!==Nn(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function Pn(e){return Rn(e)?{...e}:Array.isArray(e)?[...e]:e}const Cn=new Set(["string","number","symbol"]);function jn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function zn(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function An(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}const Mn={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]};function Dn(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function Ln(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Zn(e){return"string"==typeof e?e:e?.message}function Fn(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const s=Zn(e.inst?._zod.def?.error?.(e))??Zn(t?.error?.(e))??Zn(n.customError?.(e))??Zn(n.localeError?.(e))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function qn(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function Un(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}const Hn=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,vn,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Vn=hn("$ZodError",Hn),Kn=hn("$ZodError",Hn,{Parent:Error}),Jn=e=>(t,n,r,s)=>{const o=r?Object.assign(r,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},o);if(a instanceof Promise)throw new mn;if(a.issues.length){const t=new(s?.Err??e)(a.issues.map(e=>Fn(e,o,yn())));throw xn(t,s?.callee),t}return a.value},Bn=Jn(Kn),Wn=e=>async(t,n,r,s)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},o);if(a instanceof Promise&&(a=await a),a.issues.length){const t=new(s?.Err??e)(a.issues.map(e=>Fn(e,o,yn())));throw xn(t,s?.callee),t}return a.value},Gn=Wn(Kn),Xn=e=>(t,n,r)=>{const s=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},s);if(o instanceof Promise)throw new mn;return o.issues.length?{success:!1,error:new(e??Vn)(o.issues.map(e=>Fn(e,s,yn())))}:{success:!0,data:o.value}},Yn=Xn(Kn),Qn=e=>async(t,n,r)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let o=t._zod.run({value:n,issues:[]},s);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(e=>Fn(e,s,yn())))}:{success:!0,data:o.value}},er=Qn(Kn),tr=e=>(t,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Jn(e)(t,n,s)},nr=e=>(t,n,r)=>Jn(e)(t,n,r),rr=e=>async(t,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Wn(e)(t,n,s)},sr=e=>async(t,n,r)=>Wn(e)(t,n,r),or=e=>(t,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Xn(e)(t,n,s)},ar=e=>(t,n,r)=>Xn(e)(t,n,r),ir=e=>async(t,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Qn(e)(t,n,s)},cr=e=>async(t,n,r)=>Qn(e)(t,n,r),dr=/^[cC][^\s-]{8,}$/,ur=/^[0-9a-z]+$/,lr=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,pr=/^[0-9a-vA-V]{20}$/,hr=/^[A-Za-z0-9]{27}$/,mr=/^[a-zA-Z0-9_-]{21}$/,fr=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,gr=/^([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})$/,yr=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[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)$/,_r=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,vr=/^(?:(?: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])$/,wr=/^(([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}|:))$/,br=/^((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])$/,kr=/^(([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])$/,$r=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Sr=/^[A-Za-z0-9_-]*$/,Er=/^\+[1-9]\d{6,14}$/,Tr="(?:(?:\\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])))",Or=new RegExp(`^${Tr}$`);function xr(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}const Nr=/^-?\d+$/,Ir=/^-?\d+(?:\.\d+)?$/,Rr=/^(?:true|false)$/i,Pr=/^null$/i,Cr=/^[^A-Z]*$/,jr=/^[^a-z]*$/,zr=hn("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ar={number:"number",bigint:"bigint",object:"date"},Mr=hn("$ZodCheckLessThan",(e,t)=>{zr.init(e,t);const n=Ar[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Dr=hn("$ZodCheckGreaterThan",(e,t)=>{zr.init(e,t);const n=Ar[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Lr=hn("$ZodCheckMultipleOf",(e,t)=>{zr.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?n.value%t.value===BigInt(0):0===function(e,t){const n=(e.toString().split(".")[1]||"").length,r=t.toString();let s=(r.split(".")[1]||"").length;if(0===s&&/\d?e-\d?/.test(r)){const e=r.match(/\d?e-(\d?)/);e?.[1]&&(s=Number.parseInt(e[1]))}const o=n>s?n:s;return Number.parseInt(e.toFixed(o).replace(".",""))%Number.parseInt(t.toFixed(o).replace(".",""))/10**o}(n.value,t.value))||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Zr=hn("$ZodCheckNumberFormat",(e,t)=>{zr.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[s,o]=Mn[t.format];e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,r.minimum=s,r.maximum=o,n&&(r.pattern=Nr)}),e._zod.check=a=>{const i=a.value;if(n){if(!Number.isInteger(i))return void a.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:i,inst:e});if(!Number.isSafeInteger(i))return void(i>0?a.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):a.issues.push({input:i,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}))}i<s&&a.issues.push({origin:"number",input:i,code:"too_small",minimum:s,inclusive:!0,inst:e,continue:!t.abort}),i>o&&a.issues.push({origin:"number",input:i,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),Fr=hn("$ZodCheckMaxLength",(e,t)=>{var n;zr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!bn(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const s=qn(r);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),qr=hn("$ZodCheckMinLength",(e,t)=>{var n;zr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!bn(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const s=qn(r);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ur=hn("$ZodCheckLengthEquals",(e,t)=>{var n;zr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!bn(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{const r=n.value,s=r.length;if(s===t.length)return;const o=qn(r),a=s>t.length;n.issues.push({origin:o,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Hr=hn("$ZodCheckStringFormat",(e,t)=>{var n,r;zr.init(e,t),e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=new Set),n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Vr=hn("$ZodCheckRegex",(e,t)=>{Hr.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Kr=hn("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Cr),Hr.init(e,t)}),Jr=hn("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=jr),Hr.init(e,t)}),Br=hn("$ZodCheckIncludes",(e,t)=>{zr.init(e,t);const n=jn(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Wr=hn("$ZodCheckStartsWith",(e,t)=>{zr.init(e,t);const n=new RegExp(`^${jn(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Gr=hn("$ZodCheckEndsWith",(e,t)=>{zr.init(e,t);const n=new RegExp(`.*${jn(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Xr=hn("$ZodCheckOverwrite",(e,t)=>{zr.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class Yr{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const e of r)this.content.push(e)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}const Qr={major:4,minor:3,patch:6},es=hn("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Qr;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const t of r)for(const n of t._zod.onattach)n(e);if(0===r.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let r,s=Dn(e);for(const o of t){if(o._zod.def.when){if(!o._zod.def.when(e))continue}else if(s)continue;const t=e.issues.length,a=o._zod.check(e);if(a instanceof Promise&&!1===n?.async)throw new mn;if(r||a instanceof Promise)r=(r??Promise.resolve()).then(async()=>{await a,e.issues.length!==t&&(s||(s=Dn(e,t)))});else{if(e.issues.length===t)continue;s||(s=Dn(e,t))}}return r?r.then(()=>e):e},n=(n,s,o)=>{if(Dn(n))return n.aborted=!0,n;const a=t(s,r,o);if(a instanceof Promise){if(!1===o.async)throw new mn;return a.then(t=>e._zod.parse(t,o))}return e._zod.parse(a,o)};e._zod.run=(s,o)=>{if(o.skipChecks)return e._zod.parse(s,o);if("backward"===o.direction){const t=e._zod.parse({value:s.value,issues:[]},{...o,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,s,o)):n(t,s,o)}const a=e._zod.parse(s,o);if(a instanceof Promise){if(!1===o.async)throw new mn;return a.then(e=>t(e,r,o))}return t(a,r,o)}}Sn(e,"~standard",()=>({validate:t=>{try{const n=Yn(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return er(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),ts=hn("$ZodString",(e,t)=>{var n;es.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(n=e._zod.bag,new RegExp(`^${n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),ns=hn("$ZodStringFormat",(e,t)=>{Hr.init(e,t),ts.init(e,t)}),rs=hn("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=gr),ns.init(e,t)}),ss=hn("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=yr(e))}else t.pattern??(t.pattern=yr());ns.init(e,t)}),os=hn("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=_r),ns.init(e,t)}),as=hn("$ZodURL",(e,t)=>{ns.init(e,t),e._zod.check=n=>{try{const r=n.value.trim(),s=new URL(r);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(s.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(t.normalize?n.value=s.href:n.value=r)}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),is=hn("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ns.init(e,t)}),cs=hn("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=mr),ns.init(e,t)}),ds=hn("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=dr),ns.init(e,t)}),us=hn("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=ur),ns.init(e,t)}),ls=hn("$ZodULID",(e,t)=>{t.pattern??(t.pattern=lr),ns.init(e,t)}),ps=hn("$ZodXID",(e,t)=>{t.pattern??(t.pattern=pr),ns.init(e,t)}),hs=hn("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=hr),ns.init(e,t)}),ms=hn("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=xr({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${Tr}T(?:${r})$`)}(t)),ns.init(e,t)}),fs=hn("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Or),ns.init(e,t)}),gs=hn("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${xr(t)}$`)),ns.init(e,t)}),ys=hn("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=fr),ns.init(e,t)}),_s=hn("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=vr),ns.init(e,t),e._zod.bag.format="ipv4"}),vs=hn("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=wr),ns.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),ws=hn("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=br),ns.init(e,t)}),bs=hn("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=kr),ns.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(2!==r.length)throw new Error;const[e,t]=r;if(!t)throw new Error;const n=Number(t);if(`${n}`!==t)throw new Error;if(n<0||n>128)throw new Error;new URL(`http://[${e}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function ks(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const $s=hn("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=$r),ns.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{ks(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),Ss=hn("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Sr),ns.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!Sr.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return ks(t.padEnd(4*Math.ceil(t.length/4),"="))})(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Es=hn("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Er),ns.init(e,t)}),Ts=hn("$ZodJWT",(e,t)=>{ns.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const s=JSON.parse(atob(r));return!("typ"in s&&"JWT"!==s?.typ||!s.alg||t&&(!("alg"in s)||s.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Os=hn("$ZodNumber",(e,t)=>{es.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ir,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(e){}const s=n.value;if("number"==typeof s&&!Number.isNaN(s)&&Number.isFinite(s))return n;const o="number"==typeof s?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:s,inst:e,...o?{received:o}:{}}),n}}),xs=hn("$ZodNumberFormat",(e,t)=>{Zr.init(e,t),Os.init(e,t)}),Ns=hn("$ZodBoolean",(e,t)=>{es.init(e,t),e._zod.pattern=Rr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(e){}const s=n.value;return"boolean"==typeof s||n.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:e}),n}}),Is=hn("$ZodNull",(e,t)=>{es.init(e,t),e._zod.pattern=Pr,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{const r=t.value;return null===r||t.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),t}}),Rs=hn("$ZodUnknown",(e,t)=>{es.init(e,t),e._zod.parse=e=>e}),Ps=hn("$ZodNever",(e,t)=>{es.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function Cs(e,t,n){e.issues.length&&t.issues.push(...Ln(n,e.issues)),t.value[n]=e.value}const js=hn("$ZodArray",(e,t)=>{es.init(e,t),e._zod.parse=(n,r)=>{const s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:e}),n;n.value=Array(s.length);const o=[];for(let e=0;e<s.length;e++){const a=s[e],i=t.element._zod.run({value:a,issues:[]},r);i instanceof Promise?o.push(i.then(t=>Cs(t,n,e))):Cs(i,n,e)}return o.length?Promise.all(o).then(()=>n):n}});function zs(e,t,n,r,s){if(e.issues.length){if(s&&!(n in r))return;t.issues.push(...Ln(n,e.issues))}void 0===e.value?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function As(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const n=(r=e.shape,Object.keys(r).filter(e=>"optional"===r[e]._zod.optin&&"optional"===r[e]._zod.optout));var r;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Ms(e,t,n,r,s,o){const a=[],i=s.keySet,c=s.catchall._zod,d=c.def.type,u="optional"===c.optout;for(const s in t){if(i.has(s))continue;if("never"===d){a.push(s);continue}const o=c.run({value:t[s],issues:[]},r);o instanceof Promise?e.push(o.then(e=>zs(e,n,s,t,u))):zs(o,n,s,t,u)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:o}),e.length?Promise.all(e).then(()=>n):n}const Ds=hn("$ZodObject",(e,t)=>{es.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!n?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}const r=wn(()=>As(t));Sn(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(const e of r.values)n[t].add(e)}}return n});const s=Nn,o=t.catchall;let a;e._zod.parse=(t,n)=>{a??(a=r.value);const i=t.value;if(!s(i))return t.issues.push({expected:"object",code:"invalid_type",input:i,inst:e}),t;t.value={};const c=[],d=a.shape;for(const e of a.keys){const r=d[e],s="optional"===r._zod.optout,o=r._zod.run({value:i[e],issues:[]},n);o instanceof Promise?c.push(o.then(n=>zs(n,t,e,i,s))):zs(o,t,e,i,s)}return o?Ms(c,i,t,n,r.value,e):c.length?Promise.all(c).then(()=>t):t}}),Ls=hn("$ZodObjectJIT",(e,t)=>{Ds.init(e,t);const n=e._zod.parse,r=wn(()=>As(t));let s;const o=Nn,a=!gn.jitless,i=a&&In.value,c=t.catchall;let d;e._zod.parse=(u,l)=>{d??(d=r.value);const p=u.value;return o(p)?a&&i&&!1===l?.async&&!0!==l.jitless?(s||(s=(e=>{const t=new Yr(["shape","payload","ctx"]),n=r.value,s=e=>{const t=On(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const o=Object.create(null);let a=0;for(const e of n.keys)o[e]="key_"+a++;t.write("const newResult = {};");for(const r of n.keys){const n=o[r],a=On(r),i=e[r],c="optional"===i?._zod?.optout;t.write(`const ${n} = ${s(r)};`),c?t.write(`\n if (${n}.issues.length) {\n if (${a} in input) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n }\n \n if (${n}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${n}.value;\n }\n \n `):t.write(`\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n \n if (${n}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${n}.value;\n }\n \n `)}t.write("payload.value = newResult;"),t.write("return payload;");const i=t.compile();return(t,n)=>i(e,t,n)})(t.shape)),u=s(u,l),c?Ms([],p,u,l,d,e):u):n(u,l):(u.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),u)}});function Zs(e,t,n,r){for(const n of e)if(0===n.issues.length)return t.value=n.value,t;const s=e.filter(e=>!Dn(e));return 1===s.length?(t.value=s[0].value,s[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Fn(e,r,yn())))}),t)}const Fs=hn("$ZodUnion",(e,t)=>{es.init(e,t),Sn(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),Sn(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),Sn(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),Sn(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>kn(e.source)).join("|")})$`)}});const n=1===t.options.length,r=t.options[0]._zod.run;e._zod.parse=(s,o)=>{if(n)return r(s,o);let a=!1;const i=[];for(const e of t.options){const t=e._zod.run({value:s.value,issues:[]},o);if(t instanceof Promise)i.push(t),a=!0;else{if(0===t.issues.length)return t;i.push(t)}}return a?Promise.all(i).then(t=>Zs(t,s,e,o)):Zs(i,s,e,o)}}),qs=hn("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Fs.init(e,t);const n=e._zod.parse;Sn(e._zod,"propValues",()=>{const e={};for(const n of t.options){const r=n._zod.propValues;if(!r||0===Object.keys(r).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(const r of n)e[t].add(r)}}return e});const r=wn(()=>{const e=t.options,n=new Map;for(const r of e){const e=r._zod.propValues?.[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const t of e){if(n.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(s,o)=>{const a=s.value;if(!Nn(a))return s.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),s;const i=r.value.get(a?.[t.discriminator]);return i?i._zod.run(s,o):t.unionFallback?n(s,o):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:a,path:[t.discriminator],inst:e}),s)}}),Us=hn("$ZodIntersection",(e,t)=>{es.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,s=t.left._zod.run({value:r,issues:[]},n),o=t.right._zod.run({value:r,issues:[]},n);return s instanceof Promise||o instanceof Promise?Promise.all([s,o]).then(([t,n])=>Vs(e,t,n)):Vs(e,s,o)}});function Hs(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(Rn(e)&&Rn(t)){const n=Object.keys(t),r=Object.keys(e).filter(e=>-1!==n.indexOf(e)),s={...e,...t};for(const n of r){const r=Hs(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};s[n]=r.data}return{valid:!0,data:s}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const s=Hs(e[r],t[r]);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Vs(e,t,n){const r=new Map;let s;for(const n of t.issues)if("unrecognized_keys"===n.code){s??(s=n);for(const e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(const t of n.issues)if("unrecognized_keys"===t.code)for(const e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);const o=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(o.length&&s&&e.issues.push({...s,keys:o}),Dn(e))return e;const a=Hs(t.value,n.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}const Ks=hn("$ZodRecord",(e,t)=>{es.init(e,t),e._zod.parse=(n,r)=>{const s=n.value;if(!Rn(s))return n.issues.push({expected:"record",code:"invalid_type",input:s,inst:e}),n;const o=[],a=t.keyType._zod.values;if(a){n.value={};const i=new Set;for(const e of a)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){i.add("number"==typeof e?e.toString():e);const a=t.valueType._zod.run({value:s[e],issues:[]},r);a instanceof Promise?o.push(a.then(t=>{t.issues.length&&n.issues.push(...Ln(e,t.issues)),n.value[e]=t.value})):(a.issues.length&&n.issues.push(...Ln(e,a.issues)),n.value[e]=a.value)}let c;for(const e in s)i.has(e)||(c=c??[],c.push(e));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:c})}else{n.value={};for(const a of Reflect.ownKeys(s)){if("__proto__"===a)continue;let i=t.keyType._zod.run({value:a,issues:[]},r);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if("string"==typeof a&&Ir.test(a)&&i.issues.length){const e=t.keyType._zod.run({value:Number(a),issues:[]},r);if(e instanceof Promise)throw new Error("Async schemas not supported in object keys currently");0===e.issues.length&&(i=e)}if(i.issues.length){"loose"===t.mode?n.value[a]=s[a]:n.issues.push({code:"invalid_key",origin:"record",issues:i.issues.map(e=>Fn(e,r,yn())),input:a,path:[a],inst:e});continue}const c=t.valueType._zod.run({value:s[a],issues:[]},r);c instanceof Promise?o.push(c.then(e=>{e.issues.length&&n.issues.push(...Ln(a,e.issues)),n.value[i.value]=e.value})):(c.issues.length&&n.issues.push(...Ln(a,c.issues)),n.value[i.value]=c.value)}}return o.length?Promise.all(o).then(()=>n):n}}),Js=hn("$ZodEnum",(e,t)=>{es.init(e,t);const n=_n(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(e=>Cn.has(typeof e)).map(e=>"string"==typeof e?jn(e):e.toString()).join("|")})$`),e._zod.parse=(t,s)=>{const o=t.value;return r.has(o)||t.issues.push({code:"invalid_value",values:n,input:o,inst:e}),t}}),Bs=hn("$ZodLiteral",(e,t)=>{if(es.init(e,t),0===t.values.length)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?jn(e):e?jn(e.toString()):String(e)).join("|")})$`),e._zod.parse=(r,s)=>{const o=r.value;return n.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),Ws=hn("$ZodTransform",(e,t)=>{es.init(e,t),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new fn(e.constructor.name);const s=t.transform(n.value,n);if(r.async)return(s instanceof Promise?s:Promise.resolve(s)).then(e=>(n.value=e,n));if(s instanceof Promise)throw new mn;return n.value=s,n}});function Gs(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const Xs=hn("$ZodOptional",(e,t)=>{es.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Sn(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Sn(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${kn(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>Gs(t,e.value)):Gs(r,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),Ys=hn("$ZodExactOptional",(e,t)=>{Xs.init(e,t),Sn(e._zod,"values",()=>t.innerType._zod.values),Sn(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Qs=hn("$ZodNullable",(e,t)=>{es.init(e,t),Sn(e._zod,"optin",()=>t.innerType._zod.optin),Sn(e._zod,"optout",()=>t.innerType._zod.optout),Sn(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${kn(e.source)}|null)$`):void 0}),Sn(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),eo=hn("$ZodDefault",(e,t)=>{es.init(e,t),e._zod.optin="optional",Sn(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>to(e,t)):to(r,t)}});function to(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const no=hn("$ZodPrefault",(e,t)=>{es.init(e,t),e._zod.optin="optional",Sn(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>("backward"===n.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),ro=hn("$ZodNonOptional",(e,t)=>{es.init(e,t),Sn(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,r)=>{const s=t.innerType._zod.run(n,r);return s instanceof Promise?s.then(t=>so(t,e)):so(s,e)}});function so(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const oo=hn("$ZodCatch",(e,t)=>{es.init(e,t),Sn(e._zod,"optin",()=>t.innerType._zod.optin),Sn(e._zod,"optout",()=>t.innerType._zod.optout),Sn(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Fn(e,n,yn()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Fn(e,n,yn()))},input:e.value}),e.issues=[]),e)}}),ao=hn("$ZodPipe",(e,t)=>{es.init(e,t),Sn(e._zod,"values",()=>t.in._zod.values),Sn(e._zod,"optin",()=>t.in._zod.optin),Sn(e._zod,"optout",()=>t.out._zod.optout),Sn(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>io(e,t.in,n)):io(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>io(e,t.out,n)):io(r,t.out,n)}});function io(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const co=hn("$ZodReadonly",(e,t)=>{es.init(e,t),Sn(e._zod,"propValues",()=>t.innerType._zod.propValues),Sn(e._zod,"values",()=>t.innerType._zod.values),Sn(e._zod,"optin",()=>t.innerType?._zod?.optin),Sn(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(uo):uo(r)}});function uo(e){return e.value=Object.freeze(e.value),e}const lo=hn("$ZodCustom",(e,t)=>{zr.init(e,t),es.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,s=t.fn(r);if(s instanceof Promise)return s.then(t=>po(t,n,r,e));po(s,n,r,e)}});function po(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Un(e))}}var ho;(ho=globalThis).__zod_globalRegistry??(ho.__zod_globalRegistry=new class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}});const mo=globalThis.__zod_globalRegistry;function fo(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...An(t)})}function go(e,t){return new Mr({check:"less_than",...An(t),value:e,inclusive:!1})}function yo(e,t){return new Mr({check:"less_than",...An(t),value:e,inclusive:!0})}function _o(e,t){return new Dr({check:"greater_than",...An(t),value:e,inclusive:!1})}function vo(e,t){return new Dr({check:"greater_than",...An(t),value:e,inclusive:!0})}function wo(e,t){return new Lr({check:"multiple_of",...An(t),value:e})}function bo(e,t){return new Fr({check:"max_length",...An(t),maximum:e})}function ko(e,t){return new qr({check:"min_length",...An(t),minimum:e})}function $o(e,t){return new Ur({check:"length_equals",...An(t),length:e})}function So(e){return new Xr({check:"overwrite",tx:e})}function Eo(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??mo,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function To(e,t,n={path:[],schemaPath:[]}){var r;const s=e._zod.def,o=t.seen.get(e);if(o)return o.count++,n.schemaPath.includes(e)&&(o.cycle=n.path),o.schema;const a={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,a);const i=e._zod.toJSONSchema?.();if(i)a.schema=i;else{const r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,r);else{const n=a.schema,o=t.processors[s.type];if(!o)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${s.type}`);o(e,t,n,r)}const o=e._zod.parent;o&&(a.ref||(a.ref=o),To(o,t,r),t.seen.get(o).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(a.schema,c),"input"===t.io&&No(e)&&(delete a.schema.examples,delete a.schema.default),"input"===t.io&&a.schema._prefault&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function Oo(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const t of e.seen.entries()){const n=e.metadataRegistry.get(t[0])?.id;if(n){const e=r.get(n);if(e&&e!==t[0])throw new Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}const s=t=>{if(t[1].schema.$ref)return;const r=t[1],{ref:s,defId:o}=(t=>{const r="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const n=e.external.registry.get(t[0])?.id,s=e.external.uri??(e=>e);if(n)return{ref:s(n)};const o=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=o,{defId:o,ref:`${s("__shared")}#/${r}/${o}`}}if(t[1]===n)return{ref:"#"};const s=`#/${r}/`,o=t[1].schema.id??"__schema"+e.counter++;return{defId:o,ref:s+o}})(t);r.def={...r.schema},o&&(r.defId=o);const a=r.schema;for(const e in a)delete a[e];a.$ref=s};if("throw"===e.cycles)for(const t of e.seen.entries()){const e=t[1];if(e.cycle)throw new Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const n of e.seen.entries()){const r=n[1];if(t===n[0]){s(n);continue}if(e.external){const r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){s(n);continue}}const o=e.metadataRegistry.get(n[0])?.id;(o||r.cycle||r.count>1&&"ref"===e.reused)&&s(n)}}function xo(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=t=>{const n=e.seen.get(t);if(null===n.ref)return;const s=n.def??n.schema,o={...s},a=n.ref;if(n.ref=null,a){r(a);const n=e.seen.get(a),i=n.schema;if(!i.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Object.assign(s,i):(s.allOf=s.allOf??[],s.allOf.push(i)),Object.assign(s,o),t._zod.parent===a)for(const e in s)"$ref"!==e&&"allOf"!==e&&(e in o||delete s[e]);if(i.$ref&&n.def)for(const e in s)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(s[e])===JSON.stringify(n.def[e])&&delete s[e]}const i=t._zod.parent;if(i&&i!==a){r(i);const t=e.seen.get(i);if(t?.schema.$ref&&(s.$ref=t.schema.$ref,t.def))for(const e in s)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(s[e])===JSON.stringify(t.def[e])&&delete s[e]}e.override({zodSchema:t,jsonSchema:s,path:n.path??[]})};for(const t of[...e.seen.entries()].reverse())r(t[0]);const s={};if("draft-2020-12"===e.target?s.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?s.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?s.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const n=e.external.registry.get(t)?.id;if(!n)throw new Error("Schema is missing an `id` property");s.$id=e.external.uri(n)}Object.assign(s,n.def??n.schema);const o=e.external?.defs??{};for(const t of e.seen.entries()){const e=t[1];e.def&&e.defId&&(o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&("draft-2020-12"===e.target?s.$defs=o:s.definitions=o);try{const n=JSON.parse(JSON.stringify(s));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:Io(t,"input",e.processors),output:Io(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(e){throw new Error("Error converting schema to JSON.")}}function No(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if("transform"===r.type)return!0;if("array"===r.type)return No(r.element,n);if("set"===r.type)return No(r.valueType,n);if("lazy"===r.type)return No(r.getter(),n);if("promise"===r.type||"optional"===r.type||"nonoptional"===r.type||"nullable"===r.type||"readonly"===r.type||"default"===r.type||"prefault"===r.type)return No(r.innerType,n);if("intersection"===r.type)return No(r.left,n)||No(r.right,n);if("record"===r.type||"map"===r.type)return No(r.keyType,n)||No(r.valueType,n);if("pipe"===r.type)return No(r.in,n)||No(r.out,n);if("object"===r.type){for(const e in r.shape)if(No(r.shape[e],n))return!0;return!1}if("union"===r.type){for(const e of r.options)if(No(e,n))return!0;return!1}if("tuple"===r.type){for(const e of r.items)if(No(e,n))return!0;return!(!r.rest||!No(r.rest,n))}return!1}const Io=(e,t,n={})=>r=>{const{libraryOptions:s,target:o}=r??{},a=Eo({...s??{},target:o,io:t,processors:n});return To(e,a),Oo(a,e),xo(a,e)},Ro={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Po=(e,t,n,r)=>{const s=n;s.type="string";const{minimum:o,maximum:a,format:i,patterns:c,contentEncoding:d}=e._zod.bag;if("number"==typeof o&&(s.minLength=o),"number"==typeof a&&(s.maxLength=a),i&&(s.format=Ro[i]??i,""===s.format&&delete s.format,"time"===i&&delete s.format),d&&(s.contentEncoding=d),c&&c.size>0){const e=[...c];1===e.length?s.pattern=e[0].source:e.length>1&&(s.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}},Co=(e,t,n,r)=>{const s=n,{minimum:o,maximum:a,format:i,multipleOf:c,exclusiveMaximum:d,exclusiveMinimum:u}=e._zod.bag;"string"==typeof i&&i.includes("int")?s.type="integer":s.type="number","number"==typeof u&&("draft-04"===t.target||"openapi-3.0"===t.target?(s.minimum=u,s.exclusiveMinimum=!0):s.exclusiveMinimum=u),"number"==typeof o&&(s.minimum=o,"number"==typeof u&&"draft-04"!==t.target&&(u>=o?delete s.minimum:delete s.exclusiveMinimum)),"number"==typeof d&&("draft-04"===t.target||"openapi-3.0"===t.target?(s.maximum=d,s.exclusiveMaximum=!0):s.exclusiveMaximum=d),"number"==typeof a&&(s.maximum=a,"number"==typeof d&&"draft-04"!==t.target&&(d<=a?delete s.maximum:delete s.exclusiveMaximum)),"number"==typeof c&&(s.multipleOf=c)},jo=(e,t,n,r)=>{n.type="boolean"},zo=(e,t,n,r)=>{"openapi-3.0"===t.target?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},Ao=(e,t,n,r)=>{n.not={}},Mo=(e,t,n,r)=>{const s=_n(e._zod.def.entries);s.every(e=>"number"==typeof e)&&(n.type="number"),s.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=s},Do=(e,t,n,r)=>{const s=e._zod.def,o=[];for(const e of s.values)if(void 0===e){if("throw"===t.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof e){if("throw"===t.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");o.push(Number(e))}else o.push(e);if(0===o.length);else if(1===o.length){const e=o[0];n.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?n.enum=[e]:n.const=e}else o.every(e=>"number"==typeof e)&&(n.type="number"),o.every(e=>"string"==typeof e)&&(n.type="string"),o.every(e=>"boolean"==typeof e)&&(n.type="boolean"),o.every(e=>null===e)&&(n.type="null"),n.enum=o},Lo=(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")},Zo=(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")},Fo=(e,t,n,r)=>{const s=n,o=e._zod.def,{minimum:a,maximum:i}=e._zod.bag;"number"==typeof a&&(s.minItems=a),"number"==typeof i&&(s.maxItems=i),s.type="array",s.items=To(o.element,t,{...r,path:[...r.path,"items"]})},qo=(e,t,n,r)=>{const s=n,o=e._zod.def;s.type="object",s.properties={};const a=o.shape;for(const e in a)s.properties[e]=To(a[e],t,{...r,path:[...r.path,"properties",e]});const i=new Set(Object.keys(a)),c=new Set([...i].filter(e=>{const n=o.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));c.size>0&&(s.required=Array.from(c)),"never"===o.catchall?._zod.def.type?s.additionalProperties=!1:o.catchall?o.catchall&&(s.additionalProperties=To(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(s.additionalProperties=!1)},Uo=(e,t,n,r)=>{const s=e._zod.def,o=!1===s.inclusive,a=s.options.map((e,n)=>To(e,t,{...r,path:[...r.path,o?"oneOf":"anyOf",n]}));o?n.oneOf=a:n.anyOf=a},Ho=(e,t,n,r)=>{const s=e._zod.def,o=To(s.left,t,{...r,path:[...r.path,"allOf",0]}),a=To(s.right,t,{...r,path:[...r.path,"allOf",1]}),i=e=>"allOf"in e&&1===Object.keys(e).length,c=[...i(o)?o.allOf:[o],...i(a)?a.allOf:[a]];n.allOf=c},Vo=(e,t,n,r)=>{const s=n,o=e._zod.def;s.type="object";const a=o.keyType,i=a._zod.bag,c=i?.patterns;if("loose"===o.mode&&c&&c.size>0){const e=To(o.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});s.patternProperties={};for(const t of c)s.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(s.propertyNames=To(o.keyType,t,{...r,path:[...r.path,"propertyNames"]})),s.additionalProperties=To(o.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const d=a._zod.values;if(d){const e=[...d].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(s.required=e)}},Ko=(e,t,n,r)=>{const s=e._zod.def,o=To(s.innerType,t,r),a=t.seen.get(e);"openapi-3.0"===t.target?(a.ref=s.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]},Jo=(e,t,n,r)=>{const s=e._zod.def;To(s.innerType,t,r),t.seen.get(e).ref=s.innerType},Bo=(e,t,n,r)=>{const s=e._zod.def;To(s.innerType,t,r),t.seen.get(e).ref=s.innerType,n.default=JSON.parse(JSON.stringify(s.defaultValue))},Wo=(e,t,n,r)=>{const s=e._zod.def;To(s.innerType,t,r),t.seen.get(e).ref=s.innerType,"input"===t.io&&(n._prefault=JSON.parse(JSON.stringify(s.defaultValue)))},Go=(e,t,n,r)=>{const s=e._zod.def;let o;To(s.innerType,t,r),t.seen.get(e).ref=s.innerType;try{o=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=o},Xo=(e,t,n,r)=>{const s=e._zod.def,o="input"===t.io?"transform"===s.in._zod.def.type?s.out:s.in:s.out;To(o,t,r),t.seen.get(e).ref=o},Yo=(e,t,n,r)=>{const s=e._zod.def;To(s.innerType,t,r),t.seen.get(e).ref=s.innerType,n.readOnly=!0},Qo=(e,t,n,r)=>{const s=e._zod.def;To(s.innerType,t,r),t.seen.get(e).ref=s.innerType},ea={string:Po,number:Co,boolean:jo,bigint:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("BigInt cannot be represented in JSON Schema")},symbol:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Symbols cannot be represented in JSON Schema")},null:zo,undefined:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Undefined cannot be represented in JSON Schema")},void:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Void cannot be represented in JSON Schema")},never:Ao,any:(e,t,n,r)=>{},unknown:(e,t,n,r)=>{},date:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Date cannot be represented in JSON Schema")},enum:Mo,literal:Do,nan:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("NaN cannot be represented in JSON Schema")},template_literal:(e,t,n,r)=>{const s=n,o=e._zod.pattern;if(!o)throw new Error("Pattern not found in template literal");s.type="string",s.pattern=o.source},file:(e,t,n,r)=>{const s=n,o={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:i,mime:c}=e._zod.bag;void 0!==a&&(o.minLength=a),void 0!==i&&(o.maxLength=i),c?1===c.length?(o.contentMediaType=c[0],Object.assign(s,o)):(Object.assign(s,o),s.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(s,o)},success:(e,t,n,r)=>{n.type="boolean"},custom:Lo,function:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Function types cannot be represented in JSON Schema")},transform:Zo,map:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Map cannot be represented in JSON Schema")},set:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Set cannot be represented in JSON Schema")},array:Fo,object:qo,union:Uo,intersection:Ho,tuple:(e,t,n,r)=>{const s=n,o=e._zod.def;s.type="array";const a="draft-2020-12"===t.target?"prefixItems":"items",i="draft-2020-12"===t.target||"openapi-3.0"===t.target?"items":"additionalItems",c=o.items.map((e,n)=>To(e,t,{...r,path:[...r.path,a,n]})),d=o.rest?To(o.rest,t,{...r,path:[...r.path,i,..."openapi-3.0"===t.target?[o.items.length]:[]]}):null;"draft-2020-12"===t.target?(s.prefixItems=c,d&&(s.items=d)):"openapi-3.0"===t.target?(s.items={anyOf:c},d&&s.items.anyOf.push(d),s.minItems=c.length,d||(s.maxItems=c.length)):(s.items=c,d&&(s.additionalItems=d));const{minimum:u,maximum:l}=e._zod.bag;"number"==typeof u&&(s.minItems=u),"number"==typeof l&&(s.maxItems=l)},record:Vo,nullable:Ko,nonoptional:Jo,default:Bo,prefault:Wo,catch:Go,pipe:Xo,readonly:Yo,promise:(e,t,n,r)=>{const s=e._zod.def;To(s.innerType,t,r),t.seen.get(e).ref=s.innerType},optional:Qo,lazy:(e,t,n,r)=>{const s=e._zod.innerType;To(s,t,r),t.seen.get(e).ref=s}},ta=hn("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");es.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>Bn(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Yn(e,t,n),e.parseAsync=async(t,n)=>Gn(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>er(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>zn(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.apply=t=>t(e)}),na=hn("ZodMiniObject",(e,t)=>{Ds.init(e,t),ta.init(e,t),Sn(e,"shape",()=>t.shape)});function ra(e,t){const n={type:"object",shape:e??{},...An(t)};return new na(n)}function sa(e){return!!e._zod}function oa(e){const t=Object.values(e);if(0===t.length)return ra({});const n=t.every(sa),r=t.every(e=>!sa(e));if(n)return ra(e);if(r)return pn(e);throw new Error("Mixed Zod versions detected in object shape.")}function aa(e,t){return sa(e)?Yn(e,t):e.safeParse(t)}async function ia(e,t){if(sa(e))return await er(e,t);const n=e;return await n.safeParseAsync(t)}function ca(e){if(!e)return;let t;if(sa(e)){const n=e;t=n._zod?.def?.shape}else t=e.shape;if(t){if("function"==typeof t)try{return t()}catch{return}return t}}function da(e){if(e){if("object"==typeof e){const t=e;if(!e._def&&!t._zod){const t=Object.values(e);if(t.length>0&&t.every(e=>"object"==typeof e&&null!==e&&(void 0!==e._def||void 0!==e._zod||"function"==typeof e.parse)))return oa(e)}}if(sa(e)){const t=e,n=t._zod?.def;if(n&&("object"===n.type||void 0!==n.shape))return e}else if(void 0!==e.shape)return e}}function ua(e){if(e&&"object"==typeof e){if("message"in e&&"string"==typeof e.message)return e.message;if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0){const t=e.issues[0];if(t&&"object"==typeof t&&"message"in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function la(e){if(sa(e)){const t=e,n=t._zod?.def;if(n){if(void 0!==n.value)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}}const t=e._def;if(t){if(void 0!==t.value)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}const n=e.value;if(void 0!==n)return n}const pa=hn("ZodISODateTime",(e,t)=>{ms.init(e,t),ja.init(e,t)});function ha(e){return function(e,t){return new pa({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...An(t)})}(0,e)}const ma=hn("ZodISODate",(e,t)=>{fs.init(e,t),ja.init(e,t)});const fa=hn("ZodISOTime",(e,t)=>{gs.init(e,t),ja.init(e,t)});const ga=hn("ZodISODuration",(e,t)=>{ys.init(e,t),ja.init(e,t)});const ya=hn("ZodError",(e,t)=>{Vn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t=e=>e.message){const n={_errors:[]},r=e=>{for(const s of e.issues)if("invalid_union"===s.code&&s.errors.length)s.errors.map(e=>r({issues:e}));else if("invalid_key"===s.code)r({issues:s.issues});else if("invalid_element"===s.code)r({issues:s.issues});else if(0===s.path.length)n._errors.push(t(s));else{let e=n,r=0;for(;r<s.path.length;){const n=s.path[r];r===s.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(s))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(e),n}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const n={},r=[];for(const s of e.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(t(s))):r.push(t(s));return{formErrors:r,fieldErrors:n}}(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,vn,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,vn,2)}},isEmpty:{get:()=>0===e.issues.length}})},{Parent:Error}),_a=Jn(ya),va=Wn(ya),wa=Xn(ya),ba=Qn(ya),ka=tr(ya),$a=nr(ya),Sa=rr(ya),Ea=sr(ya),Ta=or(ya),Oa=ar(ya),xa=ir(ya),Na=cr(ya),Ia=hn("ZodType",(e,t)=>(es.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Io(e,"input"),output:Io(e,"output")}}),e.toJSONSchema=((e,t={})=>n=>{const r=Eo({...n,processors:t});return To(e,r),Oo(r,e),xo(r,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(Tn(t,{checks:[...t.checks??[],...n.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0}),e.with=e.check,e.clone=(t,n)=>zn(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.parse=(t,n)=>_a(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>wa(e,t,n),e.parseAsync=async(t,n)=>va(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>ba(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>ka(e,t,n),e.decode=(t,n)=>$a(e,t,n),e.encodeAsync=async(t,n)=>Sa(e,t,n),e.decodeAsync=async(t,n)=>Ea(e,t,n),e.safeEncode=(t,n)=>Ta(e,t,n),e.safeDecode=(t,n)=>Oa(e,t,n),e.safeEncodeAsync=async(t,n)=>xa(e,t,n),e.safeDecodeAsync=async(t,n)=>Na(e,t,n),e.refine=(t,n)=>e.check(function(e,t={}){return function(e,t,n){return new qi({type:"custom",check:"custom",fn:t,...An(n)})}(0,e,t)}(t,n)),e.superRefine=t=>e.check(function(e){const t=function(e){const t=new zr({check:"custom",...An(void 0)});return t._zod.check=e,t}(n=>(n.addIssue=e=>{if("string"==typeof e)n.issues.push(Un(e,n.value,t._zod.def));else{const r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push(Un(r))}},e(n.value,n)));return t}(t)),e.overwrite=t=>e.check(So(t)),e.optional=()=>Ri(e),e.exactOptional=()=>new Pi({type:"optional",innerType:e}),e.nullable=()=>ji(e),e.nullish=()=>Ri(ji(e)),e.nonoptional=t=>function(e,t){return new Mi({type:"nonoptional",innerType:e,...An(t)})}(e,t),e.array=()=>pi(e),e.or=t=>yi([e,t]),e.and=t=>bi(e,t),e.transform=t=>Zi(e,Ni(t)),e.default=t=>{return n=t,new zi({type:"default",innerType:e,get defaultValue(){return"function"==typeof n?n():Pn(n)}});var n},e.prefault=t=>{return n=t,new Ai({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof n?n():Pn(n)}});var n},e.catch=t=>{return new Di({type:"catch",innerType:e,catchValue:"function"==typeof(n=t)?n:()=>n});var n},e.pipe=t=>Zi(e,t),e.readonly=()=>new Fi({type:"readonly",innerType:e}),e.describe=t=>{const n=e.clone();return mo.add(n,{description:t}),n},Object.defineProperty(e,"description",{get:()=>mo.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return mo.get(e);const n=e.clone();return mo.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),Ra=hn("_ZodString",(e,t)=>{ts.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Po(e,t,n);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(function(e,t){return new Vr({check:"string_format",format:"regex",...An(t),pattern:e})}(...t)),e.includes=(...t)=>e.check(function(e,t){return new Br({check:"string_format",format:"includes",...An(t),includes:e})}(...t)),e.startsWith=(...t)=>e.check(function(e,t){return new Wr({check:"string_format",format:"starts_with",...An(t),prefix:e})}(...t)),e.endsWith=(...t)=>e.check(function(e,t){return new Gr({check:"string_format",format:"ends_with",...An(t),suffix:e})}(...t)),e.min=(...t)=>e.check(ko(...t)),e.max=(...t)=>e.check(bo(...t)),e.length=(...t)=>e.check($o(...t)),e.nonempty=(...t)=>e.check(ko(1,...t)),e.lowercase=t=>e.check(function(e){return new Kr({check:"string_format",format:"lowercase",...An(e)})}(t)),e.uppercase=t=>e.check(function(e){return new Jr({check:"string_format",format:"uppercase",...An(e)})}(t)),e.trim=()=>e.check(So(e=>e.trim())),e.normalize=(...t)=>e.check(function(e){return So(t=>t.normalize(e))}(...t)),e.toLowerCase=()=>e.check(So(e=>e.toLowerCase())),e.toUpperCase=()=>e.check(So(e=>e.toUpperCase())),e.slugify=()=>e.check(So(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}),Pa=hn("ZodString",(e,t)=>{ts.init(e,t),Ra.init(e,t),e.email=t=>e.check(function(e,t){return new za({type:"string",format:"email",check:"string_format",abort:!1,...An(t)})}(0,t)),e.url=t=>e.check(function(e,t){return new Da({type:"string",format:"url",check:"string_format",abort:!1,...An(t)})}(0,t)),e.jwt=t=>e.check(function(e,t){return new Qa({type:"string",format:"jwt",check:"string_format",abort:!1,...An(t)})}(0,t)),e.emoji=t=>e.check(function(e,t){return new La({type:"string",format:"emoji",check:"string_format",abort:!1,...An(t)})}(0,t)),e.guid=t=>e.check(fo(Aa,t)),e.uuid=t=>e.check(function(e,t){return new Ma({type:"string",format:"uuid",check:"string_format",abort:!1,...An(t)})}(0,t)),e.uuidv4=t=>e.check(function(e,t){return new Ma({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...An(t)})}(0,t)),e.uuidv6=t=>e.check(function(e,t){return new Ma({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...An(t)})}(0,t)),e.uuidv7=t=>e.check(function(e,t){return new Ma({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...An(t)})}(0,t)),e.nanoid=t=>e.check(function(e,t){return new Za({type:"string",format:"nanoid",check:"string_format",abort:!1,...An(t)})}(0,t)),e.guid=t=>e.check(fo(Aa,t)),e.cuid=t=>e.check(function(e,t){return new Fa({type:"string",format:"cuid",check:"string_format",abort:!1,...An(t)})}(0,t)),e.cuid2=t=>e.check(function(e,t){return new qa({type:"string",format:"cuid2",check:"string_format",abort:!1,...An(t)})}(0,t)),e.ulid=t=>e.check(function(e,t){return new Ua({type:"string",format:"ulid",check:"string_format",abort:!1,...An(t)})}(0,t)),e.base64=t=>e.check(function(e,t){return new Ga({type:"string",format:"base64",check:"string_format",abort:!1,...An(t)})}(0,t)),e.base64url=t=>e.check(function(e,t){return new Xa({type:"string",format:"base64url",check:"string_format",abort:!1,...An(t)})}(0,t)),e.xid=t=>e.check(function(e,t){return new Ha({type:"string",format:"xid",check:"string_format",abort:!1,...An(t)})}(0,t)),e.ksuid=t=>e.check(function(e,t){return new Va({type:"string",format:"ksuid",check:"string_format",abort:!1,...An(t)})}(0,t)),e.ipv4=t=>e.check(function(e,t){return new Ka({type:"string",format:"ipv4",check:"string_format",abort:!1,...An(t)})}(0,t)),e.ipv6=t=>e.check(function(e,t){return new Ja({type:"string",format:"ipv6",check:"string_format",abort:!1,...An(t)})}(0,t)),e.cidrv4=t=>e.check(function(e,t){return new Ba({type:"string",format:"cidrv4",check:"string_format",abort:!1,...An(t)})}(0,t)),e.cidrv6=t=>e.check(function(e,t){return new Wa({type:"string",format:"cidrv6",check:"string_format",abort:!1,...An(t)})}(0,t)),e.e164=t=>e.check(function(e,t){return new Ya({type:"string",format:"e164",check:"string_format",abort:!1,...An(t)})}(0,t)),e.datetime=t=>e.check(ha(t)),e.date=t=>e.check(function(e){return function(e,t){return new ma({type:"string",format:"date",check:"string_format",...An(t)})}(0,e)}(t)),e.time=t=>e.check(function(e){return function(e,t){return new fa({type:"string",format:"time",check:"string_format",precision:null,...An(t)})}(0,e)}(t)),e.duration=t=>e.check(function(e){return function(e,t){return new ga({type:"string",format:"duration",check:"string_format",...An(t)})}(0,e)}(t))});function Ca(e){return function(e,t){return new Pa({type:"string",...An(t)})}(0,e)}const ja=hn("ZodStringFormat",(e,t)=>{ns.init(e,t),Ra.init(e,t)}),za=hn("ZodEmail",(e,t)=>{os.init(e,t),ja.init(e,t)}),Aa=hn("ZodGUID",(e,t)=>{rs.init(e,t),ja.init(e,t)}),Ma=hn("ZodUUID",(e,t)=>{ss.init(e,t),ja.init(e,t)}),Da=hn("ZodURL",(e,t)=>{as.init(e,t),ja.init(e,t)}),La=hn("ZodEmoji",(e,t)=>{is.init(e,t),ja.init(e,t)}),Za=hn("ZodNanoID",(e,t)=>{cs.init(e,t),ja.init(e,t)}),Fa=hn("ZodCUID",(e,t)=>{ds.init(e,t),ja.init(e,t)}),qa=hn("ZodCUID2",(e,t)=>{us.init(e,t),ja.init(e,t)}),Ua=hn("ZodULID",(e,t)=>{ls.init(e,t),ja.init(e,t)}),Ha=hn("ZodXID",(e,t)=>{ps.init(e,t),ja.init(e,t)}),Va=hn("ZodKSUID",(e,t)=>{hs.init(e,t),ja.init(e,t)}),Ka=hn("ZodIPv4",(e,t)=>{_s.init(e,t),ja.init(e,t)}),Ja=hn("ZodIPv6",(e,t)=>{vs.init(e,t),ja.init(e,t)}),Ba=hn("ZodCIDRv4",(e,t)=>{ws.init(e,t),ja.init(e,t)}),Wa=hn("ZodCIDRv6",(e,t)=>{bs.init(e,t),ja.init(e,t)}),Ga=hn("ZodBase64",(e,t)=>{$s.init(e,t),ja.init(e,t)}),Xa=hn("ZodBase64URL",(e,t)=>{Ss.init(e,t),ja.init(e,t)}),Ya=hn("ZodE164",(e,t)=>{Es.init(e,t),ja.init(e,t)}),Qa=hn("ZodJWT",(e,t)=>{Ts.init(e,t),ja.init(e,t)}),ei=hn("ZodNumber",(e,t)=>{Os.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Co(e,t,n),e.gt=(t,n)=>e.check(_o(t,n)),e.gte=(t,n)=>e.check(vo(t,n)),e.min=(t,n)=>e.check(vo(t,n)),e.lt=(t,n)=>e.check(go(t,n)),e.lte=(t,n)=>e.check(yo(t,n)),e.max=(t,n)=>e.check(yo(t,n)),e.int=t=>e.check(ri(t)),e.safe=t=>e.check(ri(t)),e.positive=t=>e.check(_o(0,t)),e.nonnegative=t=>e.check(vo(0,t)),e.negative=t=>e.check(go(0,t)),e.nonpositive=t=>e.check(yo(0,t)),e.multipleOf=(t,n)=>e.check(wo(t,n)),e.step=(t,n)=>e.check(wo(t,n)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function ti(e){return function(e,t){return new ei({type:"number",checks:[],...An(t)})}(0,e)}const ni=hn("ZodNumberFormat",(e,t)=>{xs.init(e,t),ei.init(e,t)});function ri(e){return function(e,t){return new ni({type:"number",check:"number_format",abort:!1,format:"safeint",...An(t)})}(0,e)}const si=hn("ZodBoolean",(e,t)=>{Ns.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(e,t,n)=>jo(0,0,t)});function oi(e){return function(e,t){return new si({type:"boolean",...An(t)})}(0,e)}const ai=hn("ZodNull",(e,t)=>{Is.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(e,t,n)=>zo(0,e,t)});function ii(e){return function(e,t){return new ai({type:"null",...An(t)})}(0,e)}const ci=hn("ZodUnknown",(e,t)=>{Rs.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function di(){return new ci({type:"unknown"})}const ui=hn("ZodNever",(e,t)=>{Ps.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(e,t,n)=>Ao(0,0,t)});const li=hn("ZodArray",(e,t)=>{js.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fo(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(ko(t,n)),e.nonempty=t=>e.check(ko(1,t)),e.max=(t,n)=>e.check(bo(t,n)),e.length=(t,n)=>e.check($o(t,n)),e.unwrap=()=>e.element});function pi(e,t){return function(e,t,n){return new li({type:"array",element:t,...An(n)})}(0,e,t)}const hi=hn("ZodObject",(e,t)=>{Ls.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qo(e,t,n,r),Sn(e,"shape",()=>t.shape),e.keyof=()=>Ei(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:di()}),e.loose=()=>e.clone({...e._zod.def,catchall:di()}),e.strict=()=>{return e.clone({...e._zod.def,catchall:function(e,t){return new ui({type:"never",...An(t)})}(0,t)});var t},e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!Rn(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const n=e._zod.def.shape;for(const e in t)if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const r=Tn(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return En(this,"shape",n),n}});return zn(e,r)}(e,t),e.safeExtend=t=>function(e,t){if(!Rn(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Tn(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return En(this,"shape",n),n}});return zn(e,n)}(e,t),e.merge=t=>function(e,t){const n=Tn(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return En(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return zn(e,n)}(e,t),e.pick=t=>function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return zn(e,Tn(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return En(this,"shape",e),e},checks:[]}))}(e,t),e.omit=t=>function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const s=Tn(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return En(this,"shape",r),r},checks:[]});return zn(e,s)}(e,t),e.partial=(...t)=>function(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const s=Tn(t._zod.def,{get shape(){const r=t._zod.def.shape,s={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(s[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)s[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return En(this,"shape",s),s},checks:[]});return zn(t,s)}(Ii,e,t[0]),e.required=(...t)=>function(e,t,n){const r=Tn(t._zod.def,{get shape(){const r=t._zod.def.shape,s={...r};if(n)for(const t in n){if(!(t in s))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(s[t]=new e({type:"nonoptional",innerType:r[t]}))}else for(const t in r)s[t]=new e({type:"nonoptional",innerType:r[t]});return En(this,"shape",s),s}});return zn(t,r)}(Mi,e,t[0])});function mi(e,t){const n={type:"object",shape:e??{},...An(t)};return new hi(n)}function fi(e,t){return new hi({type:"object",shape:e,catchall:di(),...An(t)})}const gi=hn("ZodUnion",(e,t)=>{Fs.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Uo(e,t,n,r),e.options=t.options});function yi(e,t){return new gi({type:"union",options:e,...An(t)})}const _i=hn("ZodDiscriminatedUnion",(e,t)=>{gi.init(e,t),qs.init(e,t)});function vi(e,t,n){return new _i({type:"union",options:t,discriminator:e,...An(n)})}const wi=hn("ZodIntersection",(e,t)=>{Us.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ho(e,t,n,r)});function bi(e,t){return new wi({type:"intersection",left:e,right:t})}const ki=hn("ZodRecord",(e,t)=>{Ks.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vo(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function $i(e,t,n){return new ki({type:"record",keyType:e,valueType:t,...An(n)})}const Si=hn("ZodEnum",(e,t)=>{Js.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mo(e,0,n),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const s={};for(const r of e){if(!n.has(r))throw new Error(`Key ${r} not found in enum`);s[r]=t.entries[r]}return new Si({...t,checks:[],...An(r),entries:s})},e.exclude=(e,r)=>{const s={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete s[t]}return new Si({...t,checks:[],...An(r),entries:s})}});function Ei(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Si({type:"enum",entries:n,...An(t)})}const Ti=hn("ZodLiteral",(e,t)=>{Bs.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Do(e,t,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Oi(e,t){return new Ti({type:"literal",values:Array.isArray(e)?e:[e],...An(t)})}const xi=hn("ZodTransform",(e,t)=>{Ws.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(e,t,n)=>Zo(0,e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new fn(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(Un(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(Un(t))}};const s=t.transform(n.value,n);return s instanceof Promise?s.then(e=>(n.value=e,n)):(n.value=s,n)}});function Ni(e){return new xi({type:"transform",transform:e})}const Ii=hn("ZodOptional",(e,t)=>{Xs.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qo(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function Ri(e){return new Ii({type:"optional",innerType:e})}const Pi=hn("ZodExactOptional",(e,t)=>{Ys.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qo(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),Ci=hn("ZodNullable",(e,t)=>{Qs.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ko(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ji(e){return new Ci({type:"nullable",innerType:e})}const zi=hn("ZodDefault",(e,t)=>{eo.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),Ai=hn("ZodPrefault",(e,t)=>{no.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),Mi=hn("ZodNonOptional",(e,t)=>{ro.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Jo(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),Di=hn("ZodCatch",(e,t)=>{oo.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Go(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),Li=hn("ZodPipe",(e,t)=>{ao.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xo(e,t,0,r),e.in=t.in,e.out=t.out});function Zi(e,t){return new Li({type:"pipe",in:e,out:t})}const Fi=hn("ZodReadonly",(e,t)=>{co.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),qi=hn("ZodCustom",(e,t)=>{lo.init(e,t),Ia.init(e,t),e._zod.processJSONSchema=(e,t,n)=>Lo(0,e)});function Ui(e,t){return Zi(Ni(e),t)}const Hi="2025-11-25",Vi=[Hi,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ki="io.modelcontextprotocol/related-task",Ji="2.0",Bi=function(e,t,n){const r=An(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:(e=>null!==e&&("object"==typeof e||"function"==typeof e))??(()=>!0),...r})}(qi,0,void 0);const Wi=yi([Ca(),ti().int()]),Gi=Ca();fi({ttl:yi([ti(),ii()]).optional(),pollInterval:ti().optional()});const Xi=mi({ttl:ti().optional()}),Yi=mi({taskId:Ca()}),Qi=fi({progressToken:Wi.optional(),[Ki]:Yi.optional()}),ec=mi({_meta:Qi.optional()}),tc=ec.extend({task:Xi.optional()}),nc=mi({method:Ca(),params:ec.loose().optional()}),rc=mi({_meta:Qi.optional()}),sc=mi({method:Ca(),params:rc.loose().optional()}),oc=fi({_meta:Qi.optional()}),ac=yi([Ca(),ti().int()]),ic=mi({jsonrpc:Oi(Ji),id:ac,...nc.shape}).strict(),cc=e=>ic.safeParse(e).success,dc=mi({jsonrpc:Oi(Ji),...sc.shape}).strict(),uc=mi({jsonrpc:Oi(Ji),id:ac,result:oc}).strict(),lc=e=>uc.safeParse(e).success;var pc;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"}(pc||(pc={}));const hc=mi({jsonrpc:Oi(Ji),id:ac.optional(),error:mi({code:ti().int(),message:Ca(),data:di().optional()})}).strict(),mc=yi([ic,dc,uc,hc]);yi([uc,hc]);const fc=oc.strict(),gc=rc.extend({requestId:ac.optional(),reason:Ca().optional()}),yc=sc.extend({method:Oi("notifications/cancelled"),params:gc}),_c=mi({src:Ca(),mimeType:Ca().optional(),sizes:pi(Ca()).optional(),theme:Ei(["light","dark"]).optional()}),vc=mi({icons:pi(_c).optional()}),wc=mi({name:Ca(),title:Ca().optional()}),bc=wc.extend({...wc.shape,...vc.shape,version:Ca(),websiteUrl:Ca().optional(),description:Ca().optional()}),kc=bi(mi({applyDefaults:oi().optional()}),$i(Ca(),di())),$c=Ui(e=>e&&"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length?{form:{}}:e,bi(mi({form:kc.optional(),url:Bi.optional()}),$i(Ca(),di()).optional())),Sc=fi({list:Bi.optional(),cancel:Bi.optional(),requests:fi({sampling:fi({createMessage:Bi.optional()}).optional(),elicitation:fi({create:Bi.optional()}).optional()}).optional()}),Ec=fi({list:Bi.optional(),cancel:Bi.optional(),requests:fi({tools:fi({call:Bi.optional()}).optional()}).optional()}),Tc=mi({experimental:$i(Ca(),Bi).optional(),sampling:mi({context:Bi.optional(),tools:Bi.optional()}).optional(),elicitation:$c.optional(),roots:mi({listChanged:oi().optional()}).optional(),tasks:Sc.optional()}),Oc=ec.extend({protocolVersion:Ca(),capabilities:Tc,clientInfo:bc}),xc=nc.extend({method:Oi("initialize"),params:Oc}),Nc=mi({experimental:$i(Ca(),Bi).optional(),logging:Bi.optional(),completions:Bi.optional(),prompts:mi({listChanged:oi().optional()}).optional(),resources:mi({subscribe:oi().optional(),listChanged:oi().optional()}).optional(),tools:mi({listChanged:oi().optional()}).optional(),tasks:Ec.optional()}),Ic=oc.extend({protocolVersion:Ca(),capabilities:Nc,serverInfo:bc,instructions:Ca().optional()}),Rc=sc.extend({method:Oi("notifications/initialized"),params:rc.optional()}),Pc=nc.extend({method:Oi("ping"),params:ec.optional()}),Cc=mi({progress:ti(),total:Ri(ti()),message:Ri(Ca())}),jc=mi({...rc.shape,...Cc.shape,progressToken:Wi}),zc=sc.extend({method:Oi("notifications/progress"),params:jc}),Ac=ec.extend({cursor:Gi.optional()}),Mc=nc.extend({params:Ac.optional()}),Dc=oc.extend({nextCursor:Gi.optional()}),Lc=Ei(["working","input_required","completed","failed","cancelled"]),Zc=mi({taskId:Ca(),status:Lc,ttl:yi([ti(),ii()]),createdAt:Ca(),lastUpdatedAt:Ca(),pollInterval:Ri(ti()),statusMessage:Ri(Ca())}),Fc=oc.extend({task:Zc}),qc=rc.merge(Zc),Uc=sc.extend({method:Oi("notifications/tasks/status"),params:qc}),Hc=nc.extend({method:Oi("tasks/get"),params:ec.extend({taskId:Ca()})}),Vc=oc.merge(Zc),Kc=nc.extend({method:Oi("tasks/result"),params:ec.extend({taskId:Ca()})});oc.loose();const Jc=Mc.extend({method:Oi("tasks/list")}),Bc=Dc.extend({tasks:pi(Zc)}),Wc=nc.extend({method:Oi("tasks/cancel"),params:ec.extend({taskId:Ca()})}),Gc=oc.merge(Zc),Xc=mi({uri:Ca(),mimeType:Ri(Ca()),_meta:$i(Ca(),di()).optional()}),Yc=Xc.extend({text:Ca()}),Qc=Ca().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),ed=Xc.extend({blob:Qc}),td=Ei(["user","assistant"]),nd=mi({audience:pi(td).optional(),priority:ti().min(0).max(1).optional(),lastModified:ha({offset:!0}).optional()}),rd=mi({...wc.shape,...vc.shape,uri:Ca(),description:Ri(Ca()),mimeType:Ri(Ca()),annotations:nd.optional(),_meta:Ri(fi({}))}),sd=mi({...wc.shape,...vc.shape,uriTemplate:Ca(),description:Ri(Ca()),mimeType:Ri(Ca()),annotations:nd.optional(),_meta:Ri(fi({}))}),od=Mc.extend({method:Oi("resources/list")}),ad=Dc.extend({resources:pi(rd)}),id=Mc.extend({method:Oi("resources/templates/list")}),cd=Dc.extend({resourceTemplates:pi(sd)}),dd=ec.extend({uri:Ca()}),ud=dd,ld=nc.extend({method:Oi("resources/read"),params:ud}),pd=oc.extend({contents:pi(yi([Yc,ed]))}),hd=sc.extend({method:Oi("notifications/resources/list_changed"),params:rc.optional()}),md=dd,fd=nc.extend({method:Oi("resources/subscribe"),params:md}),gd=dd,yd=nc.extend({method:Oi("resources/unsubscribe"),params:gd}),_d=rc.extend({uri:Ca()}),vd=sc.extend({method:Oi("notifications/resources/updated"),params:_d}),wd=mi({name:Ca(),description:Ri(Ca()),required:Ri(oi())}),bd=mi({...wc.shape,...vc.shape,description:Ri(Ca()),arguments:Ri(pi(wd)),_meta:Ri(fi({}))}),kd=Mc.extend({method:Oi("prompts/list")}),$d=Dc.extend({prompts:pi(bd)}),Sd=ec.extend({name:Ca(),arguments:$i(Ca(),Ca()).optional()}),Ed=nc.extend({method:Oi("prompts/get"),params:Sd}),Td=mi({type:Oi("text"),text:Ca(),annotations:nd.optional(),_meta:$i(Ca(),di()).optional()}),Od=mi({type:Oi("image"),data:Qc,mimeType:Ca(),annotations:nd.optional(),_meta:$i(Ca(),di()).optional()}),xd=mi({type:Oi("audio"),data:Qc,mimeType:Ca(),annotations:nd.optional(),_meta:$i(Ca(),di()).optional()}),Nd=mi({type:Oi("tool_use"),name:Ca(),id:Ca(),input:$i(Ca(),di()),_meta:$i(Ca(),di()).optional()}),Id=mi({type:Oi("resource"),resource:yi([Yc,ed]),annotations:nd.optional(),_meta:$i(Ca(),di()).optional()}),Rd=yi([Td,Od,xd,rd.extend({type:Oi("resource_link")}),Id]),Pd=mi({role:td,content:Rd}),Cd=oc.extend({description:Ca().optional(),messages:pi(Pd)}),jd=sc.extend({method:Oi("notifications/prompts/list_changed"),params:rc.optional()}),zd=mi({title:Ca().optional(),readOnlyHint:oi().optional(),destructiveHint:oi().optional(),idempotentHint:oi().optional(),openWorldHint:oi().optional()}),Ad=mi({taskSupport:Ei(["required","optional","forbidden"]).optional()}),Md=mi({...wc.shape,...vc.shape,description:Ca().optional(),inputSchema:mi({type:Oi("object"),properties:$i(Ca(),Bi).optional(),required:pi(Ca()).optional()}).catchall(di()),outputSchema:mi({type:Oi("object"),properties:$i(Ca(),Bi).optional(),required:pi(Ca()).optional()}).catchall(di()).optional(),annotations:zd.optional(),execution:Ad.optional(),_meta:$i(Ca(),di()).optional()}),Dd=Mc.extend({method:Oi("tools/list")}),Ld=Dc.extend({tools:pi(Md)}),Zd=oc.extend({content:pi(Rd).default([]),structuredContent:$i(Ca(),di()).optional(),isError:oi().optional()});Zd.or(oc.extend({toolResult:di()}));const Fd=tc.extend({name:Ca(),arguments:$i(Ca(),di()).optional()}),qd=nc.extend({method:Oi("tools/call"),params:Fd}),Ud=sc.extend({method:Oi("notifications/tools/list_changed"),params:rc.optional()});mi({autoRefresh:oi().default(!0),debounceMs:ti().int().nonnegative().default(300)});const Hd=Ei(["debug","info","notice","warning","error","critical","alert","emergency"]),Vd=ec.extend({level:Hd}),Kd=nc.extend({method:Oi("logging/setLevel"),params:Vd}),Jd=rc.extend({level:Hd,logger:Ca().optional(),data:di()}),Bd=sc.extend({method:Oi("notifications/message"),params:Jd}),Wd=mi({name:Ca().optional()}),Gd=mi({hints:pi(Wd).optional(),costPriority:ti().min(0).max(1).optional(),speedPriority:ti().min(0).max(1).optional(),intelligencePriority:ti().min(0).max(1).optional()}),Xd=mi({mode:Ei(["auto","required","none"]).optional()}),Yd=mi({type:Oi("tool_result"),toolUseId:Ca().describe("The unique identifier for the corresponding tool call."),content:pi(Rd).default([]),structuredContent:mi({}).loose().optional(),isError:oi().optional(),_meta:$i(Ca(),di()).optional()}),Qd=vi("type",[Td,Od,xd]),eu=vi("type",[Td,Od,xd,Nd,Yd]),tu=mi({role:td,content:yi([eu,pi(eu)]),_meta:$i(Ca(),di()).optional()}),nu=tc.extend({messages:pi(tu),modelPreferences:Gd.optional(),systemPrompt:Ca().optional(),includeContext:Ei(["none","thisServer","allServers"]).optional(),temperature:ti().optional(),maxTokens:ti().int(),stopSequences:pi(Ca()).optional(),metadata:Bi.optional(),tools:pi(Md).optional(),toolChoice:Xd.optional()}),ru=nc.extend({method:Oi("sampling/createMessage"),params:nu}),su=oc.extend({model:Ca(),stopReason:Ri(Ei(["endTurn","stopSequence","maxTokens"]).or(Ca())),role:td,content:Qd}),ou=oc.extend({model:Ca(),stopReason:Ri(Ei(["endTurn","stopSequence","maxTokens","toolUse"]).or(Ca())),role:td,content:yi([eu,pi(eu)])}),au=mi({type:Oi("boolean"),title:Ca().optional(),description:Ca().optional(),default:oi().optional()}),iu=mi({type:Oi("string"),title:Ca().optional(),description:Ca().optional(),minLength:ti().optional(),maxLength:ti().optional(),format:Ei(["email","uri","date","date-time"]).optional(),default:Ca().optional()}),cu=mi({type:Ei(["number","integer"]),title:Ca().optional(),description:Ca().optional(),minimum:ti().optional(),maximum:ti().optional(),default:ti().optional()}),du=mi({type:Oi("string"),title:Ca().optional(),description:Ca().optional(),enum:pi(Ca()),default:Ca().optional()}),uu=mi({type:Oi("string"),title:Ca().optional(),description:Ca().optional(),oneOf:pi(mi({const:Ca(),title:Ca()})),default:Ca().optional()}),lu=mi({type:Oi("string"),title:Ca().optional(),description:Ca().optional(),enum:pi(Ca()),enumNames:pi(Ca()).optional(),default:Ca().optional()}),pu=yi([du,uu]),hu=yi([mi({type:Oi("array"),title:Ca().optional(),description:Ca().optional(),minItems:ti().optional(),maxItems:ti().optional(),items:mi({type:Oi("string"),enum:pi(Ca())}),default:pi(Ca()).optional()}),mi({type:Oi("array"),title:Ca().optional(),description:Ca().optional(),minItems:ti().optional(),maxItems:ti().optional(),items:mi({anyOf:pi(mi({const:Ca(),title:Ca()}))}),default:pi(Ca()).optional()})]),mu=yi([lu,pu,hu]),fu=yi([mu,au,iu,cu]),gu=yi([tc.extend({mode:Oi("form").optional(),message:Ca(),requestedSchema:mi({type:Oi("object"),properties:$i(Ca(),fu),required:pi(Ca()).optional()})}),tc.extend({mode:Oi("url"),message:Ca(),elicitationId:Ca(),url:Ca().url()})]),yu=nc.extend({method:Oi("elicitation/create"),params:gu}),_u=rc.extend({elicitationId:Ca()}),vu=sc.extend({method:Oi("notifications/elicitation/complete"),params:_u}),wu=oc.extend({action:Ei(["accept","decline","cancel"]),content:Ui(e=>null===e?void 0:e,$i(Ca(),yi([Ca(),ti(),oi(),pi(Ca())])).optional())}),bu=mi({type:Oi("ref/resource"),uri:Ca()}),ku=mi({type:Oi("ref/prompt"),name:Ca()}),$u=ec.extend({ref:yi([ku,bu]),argument:mi({name:Ca(),value:Ca()}),context:mi({arguments:$i(Ca(),Ca()).optional()}).optional()}),Su=nc.extend({method:Oi("completion/complete"),params:$u}),Eu=oc.extend({completion:fi({values:pi(Ca()).max(100),total:Ri(ti().int()),hasMore:Ri(oi())})}),Tu=mi({uri:Ca().startsWith("file://"),name:Ca().optional(),_meta:$i(Ca(),di()).optional()}),Ou=nc.extend({method:Oi("roots/list"),params:ec.optional()}),xu=oc.extend({roots:pi(Tu)}),Nu=sc.extend({method:Oi("notifications/roots/list_changed"),params:rc.optional()});yi([Pc,xc,Su,Kd,Ed,kd,od,id,ld,fd,yd,qd,Dd,Hc,Kc,Jc,Wc]),yi([yc,zc,Rc,Nu,Uc]),yi([fc,su,ou,wu,xu,Vc,Bc,Fc]),yi([Pc,ru,yu,Ou,Hc,Kc,Jc,Wc]),yi([yc,zc,Bd,vd,hd,Ud,jd,Uc,vu]),yi([fc,Ic,Eu,Cd,$d,ad,cd,pd,Zd,Ld,Vc,Bc,Fc]);class Iu extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,t,n){if(e===pc.UrlElicitationRequired&&n){const e=n;if(e.elicitations)return new Ru(e.elicitations,t)}return new Iu(e,t,n)}}class Ru extends Iu{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(pc.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}function Pu(e){return"completed"===e||"failed"===e||"cancelled"===e}const Cu=Symbol("Let zodToJsonSchema decide on which parser to use"),ju={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"};function zu(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function Au(e,t,n,r,s){e[t]=n,zu(e,t,r,s)}const Mu=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};function Du(e){if("openAi"!==e.target)return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?Mu(t,e.currentPath):t.join("/")}}function Lu(e,t){return ll(e.type._def,t)}function Zu(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>Zu(e,t,n))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Fu(e,t)}}const Fu=(e,t)=>{const n={type:"integer",format:"unix-time"};if("openApi3"===t.target)return n;for(const r of e.checks)switch(r.kind){case"min":Au(n,"minimum",r.value,r.message,t);break;case"max":Au(n,"maximum",r.value,r.message,t)}return n};let qu;const Uu=/^[cC][^\s-]{8,}$/,Hu=/^[0-9a-z]+$/,Vu=/^[0-9A-HJKMNP-TV-Z]{26}$/,Ku=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,Ju=()=>(void 0===qu&&(qu=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),qu),Bu=/^(?:(?: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])$/,Wu=/^(([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])$/,Gu=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Xu=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Yu=/^[a-zA-Z0-9_-]{21}$/,Qu=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function el(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":Au(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,r.value):r.value,r.message,t);break;case"max":Au(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"email":switch(t.emailStrategy){case"format:email":rl(n,"email",r.message,t);break;case"format:idn-email":rl(n,"idn-email",r.message,t);break;case"pattern:zod":sl(n,Ku,r.message,t)}break;case"url":rl(n,"uri",r.message,t);break;case"uuid":rl(n,"uuid",r.message,t);break;case"regex":sl(n,r.regex,r.message,t);break;case"cuid":sl(n,Uu,r.message,t);break;case"cuid2":sl(n,Hu,r.message,t);break;case"startsWith":sl(n,RegExp(`^${tl(r.value,t)}`),r.message,t);break;case"endsWith":sl(n,RegExp(`${tl(r.value,t)}$`),r.message,t);break;case"datetime":rl(n,"date-time",r.message,t);break;case"date":rl(n,"date",r.message,t);break;case"time":rl(n,"time",r.message,t);break;case"duration":rl(n,"duration",r.message,t);break;case"length":Au(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,r.value):r.value,r.message,t),Au(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"includes":sl(n,RegExp(tl(r.value,t)),r.message,t);break;case"ip":"v6"!==r.version&&rl(n,"ipv4",r.message,t),"v4"!==r.version&&rl(n,"ipv6",r.message,t);break;case"base64url":sl(n,Xu,r.message,t);break;case"jwt":sl(n,Qu,r.message,t);break;case"cidr":"v6"!==r.version&&sl(n,Bu,r.message,t),"v4"!==r.version&&sl(n,Wu,r.message,t);break;case"emoji":sl(n,Ju(),r.message,t);break;case"ulid":sl(n,Vu,r.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":rl(n,"binary",r.message,t);break;case"contentEncoding:base64":Au(n,"contentEncoding","base64",r.message,t);break;case"pattern:zod":sl(n,Gu,r.message,t)}break;case"nanoid":sl(n,Yu,r.message,t)}return n}function tl(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let n=0;n<e.length;n++)nl.has(e[n])||(t+="\\"),t+=e[n];return t}(e):e}const nl=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function rl(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):Au(e,"format",t,n,r)}function sl(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:ol(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):Au(e,"pattern",ol(t,r),n,r)}function ol(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const n=e.flags.includes("i"),r=e.flags.includes("m"),s=e.flags.includes("s"),o=n?e.source.toLowerCase():e.source;let a="",i=!1,c=!1,d=!1;for(let e=0;e<o.length;e++)if(i)a+=o[e],i=!1;else{if(n)if(c){if(o[e].match(/[a-z]/)){d?(a+=o[e],a+=`${o[e-2]}-${o[e]}`.toUpperCase(),d=!1):"-"===o[e+1]&&o[e+2]?.match(/[a-z]/)?(a+=o[e],d=!0):a+=`${o[e]}${o[e].toUpperCase()}`;continue}}else if(o[e].match(/[a-z]/)){a+=`[${o[e]}${o[e].toUpperCase()}]`;continue}if(r){if("^"===o[e]){a+="(^|(?<=[\r\n]))";continue}if("$"===o[e]){a+="($|(?=[\r\n]))";continue}}s&&"."===o[e]?a+=c?`${o[e]}\r\n`:`[${o[e]}\r\n]`:(a+=o[e],"\\"===o[e]?i=!0:c&&"]"===o[e]?c=!1:c||"["!==o[e]||(c=!0))}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return a}function al(e,t){if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&e.keyType?._def.typeName===ln.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:ll(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",r]})??Du(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const n={type:"object",additionalProperties:ll(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return n;if(e.keyType?._def.typeName===ln.ZodString&&e.keyType._def.checks?.length){const{type:r,...s}=el(e.keyType._def,t);return{...n,propertyNames:s}}if(e.keyType?._def.typeName===ln.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===ln.ZodBranded&&e.keyType._def.type._def.typeName===ln.ZodString&&e.keyType._def.type._def.checks?.length){const{type:r,...s}=Lu(e.keyType._def,t);return{...n,propertyNames:s}}return n}const il={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},cl=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>ll(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function dl(e){try{return e.isOptional()}catch{return!0}}const ul=(e,t,n)=>{switch(t){case ln.ZodString:return el(e,n);case ln.ZodNumber:return function(e,t){const n={type:"number"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"int":n.type="integer",zu(n,"type",r.message,t);break;case"min":"jsonSchema7"===t.target?r.inclusive?Au(n,"minimum",r.value,r.message,t):Au(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Au(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?Au(n,"maximum",r.value,r.message,t):Au(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Au(n,"maximum",r.value,r.message,t));break;case"multipleOf":Au(n,"multipleOf",r.value,r.message,t)}return n}(e,n);case ln.ZodObject:return function(e,t){const n="openAi"===t.target,r={type:"object",properties:{}},s=[],o=e.shape();for(const e in o){let a=o[e];if(void 0===a||void 0===a._def)continue;let i=dl(a);i&&n&&("ZodOptional"===a._def.typeName&&(a=a._def.innerType),a.isNullable()||(a=a.nullable()),i=!1);const c=ll(a._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==c&&(r.properties[e]=c,i||s.push(e))}s.length&&(r.required=s);const a=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return ll(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==a&&(r.additionalProperties=a),r}(e,n);case ln.ZodBigInt:return function(e,t){const n={type:"integer",format:"int64"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"min":"jsonSchema7"===t.target?r.inclusive?Au(n,"minimum",r.value,r.message,t):Au(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Au(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?Au(n,"maximum",r.value,r.message,t):Au(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Au(n,"maximum",r.value,r.message,t));break;case"multipleOf":Au(n,"multipleOf",r.value,r.message,t)}return n}(e,n);case ln.ZodBoolean:return{type:"boolean"};case ln.ZodDate:return Zu(e,n);case ln.ZodUndefined:return function(e){return{not:Du(e)}}(n);case ln.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(n);case ln.ZodArray:return function(e,t){const n={type:"array"};return e.type?._def&&e.type?._def?.typeName!==ln.ZodAny&&(n.items=ll(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Au(n,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Au(n,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Au(n,"minItems",e.exactLength.value,e.exactLength.message,t),Au(n,"maxItems",e.exactLength.value,e.exactLength.message,t)),n}(e,n);case ln.ZodUnion:case ln.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return cl(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in il&&(!e._def.checks||!e._def.checks.length))){const e=n.reduce((e,t)=>{const n=il[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}if(n.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){const e=n.reduce((e,t)=>{const n=typeof t._def.value;switch(n){case"string":case"number":case"boolean":return[...e,n];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===n.length){const t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return cl(e,t)}(e,n);case ln.ZodIntersection:return function(e,t){const n=[ll(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),ll(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(e=>!!e);let r="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const s=[];return n.forEach(e=>{if("type"in(t=e)&&"string"===t.type||!("allOf"in t)){let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:n,...r}=e;t=r}else r=void 0;s.push(t)}else s.push(...e.allOf),void 0===e.unevaluatedProperties&&(r=void 0);var t}),s.length?{allOf:s,...r}:void 0}(e,n);case ln.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,n)=>ll(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:ll(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>ll(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])}}(e,n);case ln.ZodRecord:return al(e,n);case ln.ZodLiteral:return function(e,t){const n=typeof e.value;return"bigint"!==n&&"number"!==n&&"boolean"!==n&&"string"!==n?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===n?"integer":n,enum:[e.value]}:{type:"bigint"===n?"integer":n,const:e.value}}(e,n);case ln.ZodEnum:return function(e){return{type:"string",enum:Array.from(e.values)}}(e);case ln.ZodNativeEnum:return function(e){const t=e.values,n=Object.keys(e.values).filter(e=>"number"!=typeof t[t[e]]).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:1===r.length?"string"===r[0]?"string":"number":["string","number"],enum:n}}(e);case ln.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:il[e.innerType._def.typeName],nullable:!0}:{type:[il[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const n=ll(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const n=ll(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}(e,n);case ln.ZodOptional:return((e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return ll(e.innerType._def,t);const n=ll(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Du(t)},n]}:Du(t)})(e,n);case ln.ZodMap:return function(e,t){return"record"===t.mapStrategy?al(e,t):{type:"array",maxItems:125,items:{type:"array",items:[ll(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Du(t),ll(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Du(t)],minItems:2,maxItems:2}}}(e,n);case ln.ZodSet:return function(e,t){const n={type:"array",uniqueItems:!0,items:ll(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Au(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Au(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}(e,n);case ln.ZodLazy:return()=>e.getter()._def;case ln.ZodPromise:return function(e,t){return ll(e.type._def,t)}(e,n);case ln.ZodNaN:case ln.ZodNever:return function(e){return"openAi"===e.target?void 0:{not:Du({...e,currentPath:[...e.currentPath,"not"]})}}(n);case ln.ZodEffects:return function(e,t){return"input"===t.effectStrategy?ll(e.schema._def,t):Du(t)}(e,n);case ln.ZodAny:return Du(n);case ln.ZodUnknown:return function(e){return Du(e)}(n);case ln.ZodDefault:return function(e,t){return{...ll(e.innerType._def,t),default:e.defaultValue()}}(e,n);case ln.ZodBranded:return Lu(e,n);case ln.ZodReadonly:case ln.ZodCatch:return((e,t)=>ll(e.innerType._def,t))(e,n);case ln.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return ll(e.in._def,t);if("output"===t.pipeStrategy)return ll(e.out._def,t);const n=ll(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[n,ll(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]})].filter(e=>void 0!==e)}})(e,n);case ln.ZodFunction:case ln.ZodVoid:case ln.ZodSymbol:default:return}};function ll(e,t,n=!1){const r=t.seen.get(e);if(t.override){const s=t.override?.(e,t,r,n);if(s!==Cu)return s}if(r&&!n){const e=pl(r,t);if(void 0!==e)return e}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const o=ul(e,e.typeName,t),a="function"==typeof o?ll(o(),t):o;if(a&&hl(e,t,a),t.postProcess){const n=t.postProcess(a,e,t);return s.jsonSchema=a,n}return s.jsonSchema=a,a}const pl=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Mu(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Du(t)):"seen"===t.$refStrategy?Du(t):void 0}},hl=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n);function ml(e,t){return sa(e)?function(e,t){if("_idmap"in e){const n=e,r=Eo({...t,processors:ea}),s={};for(const e of n._idmap.entries()){const[t,n]=e;To(n,r)}const o={},a={registry:n,uri:t?.uri,defs:s};r.external=a;for(const e of n._idmap.entries()){const[t,n]=e;Oo(r,n),o[t]=xo(r,n)}if(Object.keys(s).length>0){const e="draft-2020-12"===r.target?"$defs":"definitions";o.__shared={[e]:s}}return{schemas:o}}const n=Eo({...t,processors:ea});return To(e,n),Oo(n,e),xo(n,e)}(e,{target:(n=t?.target,n?"jsonSchema7"===n||"draft-7"===n?"draft-7":"jsonSchema2019-09"===n||"draft-2020-12"===n?"draft-2020-12":"draft-7":"draft-7"),io:t?.pipeStrategy??"input"}):((e,t)=>{const n=(e=>{const t=(e=>"string"==typeof e?{...ju,name:e}:{...ju,...e})(e),n=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}})(t);let r=t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:ll(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??Du(n)}),{}):void 0;const s="title"===t?.nameStrategy?void 0:t?.name,o=ll(e._def,void 0===s?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1)??Du(n),a=void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==a&&(o.title=a),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===n.$refStrategy?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const i=void 0===s?r?{...o,[n.definitionPath]:r}:o:{$ref:[..."relative"===n.$refStrategy?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...r,[s]:o}};return"jsonSchema7"===n.target?i.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==n.target&&"openAi"!==n.target||(i.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===n.target&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i})(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"});var n}function fl(e){const t=ca(e),n=t?.method;if(!n)throw new Error("Schema is missing a method literal");const r=la(n);if("string"!=typeof r)throw new Error("Schema method literal must be a string");return r}function gl(e,t){const n=aa(e,t);if(!n.success)throw n.error;return n.data}class yl{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(yc,e=>{this._oncancel(e)}),this.setNotificationHandler(zc,e=>{this._onprogress(e)}),this.setRequestHandler(Pc,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Hc,async(e,t)=>{const n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Iu(pc.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Kc,async(e,t)=>{const n=async()=>{const r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if("response"===e.type||"error"===e.type){const t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r)if(this._requestResolvers.delete(n),"response"===e.type)r(t);else{const e=t;r(new Iu(e.error.code,e.error.message,e.error.data))}else{const t="response"===e.type?"Response":"Error";this._onerror(new Error(`${t} handler missing for request ${n}`))}continue}await(this._transport?.send(e.message,{relatedRequestId:t.requestId}))}}const s=await this._taskStore.getTask(r,t.sessionId);if(!s)throw new Iu(pc.InvalidParams,`Task not found: ${r}`);if(!Pu(s.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(Pu(s.status)){const e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[Ki]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(Jc,async(e,t)=>{try{const{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new Iu(pc.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(Wc,async(e,t)=>{try{const n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Iu(pc.InvalidParams,`Task not found: ${e.params.taskId}`);if(Pu(n.status))throw new Iu(pc.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,"cancelled","Client cancelled task execution.",t.sessionId),this._clearTaskQueue(e.params.taskId);const r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new Iu(pc.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){if(e instanceof Iu)throw e;throw new Iu(pc.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;const t=this._requestHandlerAbortControllers.get(e.params.requestId);t?.abort(e.params.reason)}_setupTimeout(e,t,n,r,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:r})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Iu.fromError(pc.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;const t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};const n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};const r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{var n;r?.(e,t),lc(e)||(n=e,hc.safeParse(n).success)?this._onresponse(e):cc(e)?this._onrequest(e,t):(e=>dc.safeParse(e).success)(e)?this._onnotification(e):this._onerror(new Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();const t=Iu.fromError(pc.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){const t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;void 0!==t&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){const n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,s=e.params?._meta?.[Ki]?.taskId;if(void 0===n){const t={jsonrpc:"2.0",id:e.id,error:{code:pc.MethodNotFound,message:"Method not found"}};return void(s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(new Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(new Error(`Failed to send an error response: ${e}`))))}const o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);const a=(i=e.params,tc.safeParse(i).success?e.params.task:void 0);var i;const c=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,d={signal:o.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{const n={relatedRequestId:e.id};s&&(n.relatedTask={taskId:s}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{const o={...r,relatedRequestId:e.id};s&&!o.relatedTask&&(o.relatedTask={taskId:s});const a=o.relatedTask?.taskId??s;return a&&c&&await c.updateTaskStatus(a,"input_required"),await this.request(t,n,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,d)).then(async t=>{if(o.signal.aborted)return;const n={result:t,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:n,timestamp:Date.now()},r?.sessionId):await(r?.send(n))},async t=>{if(o.signal.aborted)return;const n={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:pc.InternalError,message:t.message??"Internal error",...void 0!==t.data&&{data:t.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:n,timestamp:Date.now()},r?.sessionId):await(r?.send(n))}).catch(e=>this._onerror(new Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...n}=e.params,r=Number(t),s=this._progressHandlers.get(r);if(!s)return void this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));const o=this._responseHandlers.get(r),a=this._timeoutInfo.get(r);if(a&&o&&a.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){return this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),void o(e)}s(n)}_onresponse(e){const t=Number(e.id),n=this._requestResolvers.get(t);if(n)return this._requestResolvers.delete(t),void(lc(e)?n(e):n(new Iu(e.error.code,e.error.message,e.error.data)));const r=this._responseHandlers.get(t);if(void 0===r)return void this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));this._responseHandlers.delete(t),this._cleanupTimeout(t);let s=!1;if(lc(e)&&e.result&&"object"==typeof e.result){const n=e.result;if(n.task&&"object"==typeof n.task){const e=n.task;"string"==typeof e.taskId&&(s=!0,this._taskProgressTokens.set(e.taskId,t))}}s||this._progressHandlers.delete(t),lc(e)?r(e):r(Iu.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await(this._transport?.close())}async*requestStream(e,t,n){const{task:r}=n??{};if(!r){try{const r=await this.request(e,t,n);yield{type:"result",result:r}}catch(e){yield{type:"error",error:e instanceof Iu?e:new Iu(pc.InternalError,String(e))}}return}let s;try{const r=await this.request(e,Fc,n);if(!r.task)throw new Iu(pc.InternalError,"Task creation did not return a task");for(s=r.task.taskId,yield{type:"taskCreated",task:r.task};;){const e=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:e},Pu(e.status)){if("completed"===e.status){const e=await this.getTaskResult({taskId:s},t,n);yield{type:"result",result:e}}else"failed"===e.status?yield{type:"error",error:new Iu(pc.InternalError,`Task ${s} failed`)}:"cancelled"===e.status&&(yield{type:"error",error:new Iu(pc.InternalError,`Task ${s} was cancelled`)});return}if("input_required"===e.status){const e=await this.getTaskResult({taskId:s},t,n);return void(yield{type:"result",result:e})}const r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:"error",error:e instanceof Iu?e:new Iu(pc.InternalError,String(e))}}}request(e,t,n){const{relatedRequestId:r,resumptionToken:s,onresumptiontoken:o,task:a,relatedTask:i}=n??{};return new Promise((c,d)=>{const u=e=>{d(e)};if(!this._transport)return void u(new Error("Not connected"));if(!0===this._options?.enforceStrictCapabilities)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(e){return void u(e)}n?.signal?.throwIfAborted();const l=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:l};n?.onprogress&&(this._progressHandlers.set(l,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:l}}),a&&(p.params={...p.params,task:a}),i&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Ki]:i}});const h=e=>{this._responseHandlers.delete(l),this._progressHandlers.delete(l),this._cleanupTimeout(l),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:l,reason:String(e)}},{relatedRequestId:r,resumptionToken:s,onresumptiontoken:o}).catch(e=>this._onerror(new Error(`Failed to send cancellation: ${e}`)));const t=e instanceof Iu?e:new Iu(pc.RequestTimeout,String(e));d(t)};this._responseHandlers.set(l,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return d(e);try{const n=aa(t,e.result);n.success?c(n.data):d(n.error)}catch(e){d(e)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});const m=n?.timeout??6e4;this._setupTimeout(l,m,n?.maxTotalTimeout,()=>h(Iu.fromError(pc.RequestTimeout,"Request timed out",{timeout:m})),n?.resetTimeoutOnProgress??!1);const f=i?.taskId;if(f){const e=e=>{const t=this._responseHandlers.get(l);t?t(e):this._onerror(new Error(`Response handler missing for side-channeled request ${l}`))};this._requestResolvers.set(l,e),this._enqueueTaskMessage(f,{type:"request",message:p,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(l),d(e)})}else this._transport.send(p,{relatedRequestId:r,resumptionToken:s,onresumptiontoken:o}).catch(e=>{this._cleanupTimeout(l),d(e)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},Vc,t)}async getTaskResult(e,t,n){return this.request({method:"tasks/result",params:e},t,n)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},Bc,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},Gc,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const n=t?.relatedTask?.taskId;if(n){const r={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Ki]:t.relatedTask}}};return void await this._enqueueTaskMessage(n,{type:"notification",message:r,timestamp:Date.now()})}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;return this._pendingDebouncedNotifications.add(e.method),void Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:"2.0"};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[Ki]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))})}let r={...e,jsonrpc:"2.0"};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[Ki]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){const n=fl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{const s=gl(e,n);return Promise.resolve(t(s,r))})}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,t){const n=fl(e);this._notificationHandlers.set(n,n=>{const r=gl(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const t=this._taskProgressTokens.get(e);void 0!==t&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){const n=await this._taskMessageQueue.dequeueAll(e,t);for(const t of n)if("request"===t.type&&cc(t.message)){const n=t.message.id,r=this._requestResolvers.get(n);r?(r(new Iu(pc.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(n)):this._onerror(new Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{const t=await(this._taskStore?.getTask(e));t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted)return void r(new Iu(pc.InvalidRequest,"Request cancelled"));const s=setTimeout(e,n);t.addEventListener("abort",()=>{clearTimeout(s),r(new Iu(pc.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async r=>{if(!e)throw new Error("No request provided");return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{const r=await n.getTask(e,t);if(!r)throw new Iu(pc.InvalidParams,"Failed to retrieve task: Task not found");return r},storeTaskResult:async(e,r,s)=>{await n.storeTaskResult(e,r,s,t);const o=await n.getTask(e,t);if(o){const t=Uc.parse({method:"notifications/tasks/status",params:o});await this.notification(t),Pu(o.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,s)=>{const o=await n.getTask(e,t);if(!o)throw new Iu(pc.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(Pu(o.status))throw new Iu(pc.InvalidParams,`Cannot update task "${e}" from terminal status "${o.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,s,t);const a=await n.getTask(e,t);if(a){const t=Uc.parse({method:"notifications/tasks/status",params:a});await this.notification(t),Pu(a.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}}function _l(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function vl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var wl,bl={exports:{}},kl={},$l={},Sl={},El={},Tl={},Ol={};function xl(){return wl||(wl=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class n extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=n;class r extends t{constructor(e){super(),this._items="string"==typeof e?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const e=this._items[0];return""===e||'""'===e}get str(){var e;return null!==(e=this._str)&&void 0!==e?e:this._str=this._items.reduce((e,t)=>`${e}${t}`,"")}get names(){var e;return null!==(e=this._names)&&void 0!==e?e:this._names=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}}function s(e,...t){const n=[e[0]];let s=0;for(;s<t.length;)i(n,t[s]),n.push(e[++s]);return new r(n)}e._Code=r,e.nil=new r(""),e._=s;const o=new r("+");function a(e,...t){const n=[d(e[0])];let s=0;for(;s<t.length;)n.push(o),i(n,t[s]),n.push(o,d(e[++s]));return function(e){let t=1;for(;t<e.length-1;){if(e[t]===o){const n=c(e[t-1],e[t+1]);if(void 0!==n){e.splice(t-1,3,n);continue}e[t++]="+"}t++}}(n),new r(n)}function i(e,t){var s;t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push("number"==typeof(s=t)||"boolean"==typeof s||null===s?s:d(Array.isArray(s)?s.join(","):s))}function c(e,t){if('""'===t)return e;if('""'===e)return t;if("string"==typeof e){if(t instanceof n||'"'!==e[e.length-1])return;return"string"!=typeof t?`${e.slice(0,-1)}${t}"`:'"'===t[0]?e.slice(0,-1)+t.slice(1):void 0}return"string"!=typeof t||'"'!==t[0]||e instanceof n?void 0:`"${e}${t.slice(1)}`}function d(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.str=a,e.addCodeArg=i,e.strConcat=function(e,t){return t.emptyStr()?e:e.emptyStr()?t:a`${e}${t}`},e.stringify=function(e){return new r(d(e))},e.safeStringify=d,e.getProperty=function(t){return"string"==typeof t&&e.IDENTIFIER.test(t)?new r(`.${t}`):s`[${t}]`},e.getEsmExportName=function(t){if("string"==typeof t&&e.IDENTIFIER.test(t))return new r(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)},e.regexpCode=function(e){return new r(e.toString())}}(Ol)),Ol}var Nl,Il,Rl={};function Pl(){return Nl||(Nl=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=xl();class n extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}}var r;!function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"}(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class s{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){return`${e}${(this._names[e]||this._nameGroup(e)).index++}`}_nameGroup(e){var t,n;if((null===(n=null===(t=this._parent)||void 0===t?void 0:t._prefixes)||void 0===n?void 0:n.has(e))||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}}e.Scope=s;class o extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=t._`.${new t.Name(n)}[${r}]`}}e.ValueScopeName=o;const a=t._`\n`;e.ValueScope=class extends s{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?a:t.nil}}get(){return this._scope}name(e){return new o(e,this._newName(e))}value(e,t){var n;if(void 0===t.ref)throw new Error("CodeGen: ref must be passed in value");const r=this.toName(e),{prefix:s}=r,o=null!==(n=t.key)&&void 0!==n?n:t.ref;let a=this._values[s];if(a){const e=a.get(o);if(e)return e}else a=this._values[s]=new Map;a.set(o,r);const i=this._scope[s]||(this._scope[s]=[]),c=i.length;return i[c]=t.ref,r.setValue(t,{property:s,itemIndex:c}),r}getValue(e,t){const n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(void 0===n.scopePath)throw new Error(`CodeGen: name "${n}" has no value`);return t._`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(void 0===e.value)throw new Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(s,o,a={},i){let c=t.nil;for(const d in s){const u=s[d];if(!u)continue;const l=a[d]=a[d]||new Map;u.forEach(s=>{if(l.has(s))return;l.set(s,r.Started);let a=o(s);if(a){const n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=t._`${c}${n} ${s} = ${a};${this.opts._n}`}else{if(!(a=null==i?void 0:i(s)))throw new n(s);c=t._`${c}${a}${this.opts._n}`}l.set(s,r.Completed)})}return c}}}(Rl)),Rl}function Cl(){return Il||(Il=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=xl(),n=Pl();var r=xl();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var s=Pl();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return s.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return s.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return s.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return s.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class o{optimizeNodes(){return this}optimizeNames(e,t){return this}}class a extends o{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){const r=e?n.varKinds.var:this.varKind,s=void 0===this.rhs?"":` = ${this.rhs}`;return`${r} ${this.name}${s};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=N(this.rhs,e,t)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class i extends o{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name)||e[this.lhs.str]||this.sideEffects)return this.rhs=N(this.rhs,e,n),this}get names(){return x(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}}class c extends i{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class d extends o{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class u extends o{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class l extends o{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class p extends o{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=N(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class h extends o{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),"")}optimizeNodes(){const{nodes:e}=this;let t=e.length;for(;t--;){const n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){const{nodes:n}=this;let r=n.length;for(;r--;){const s=n[r];s.optimizeNames(e,t)||(I(e,s.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>O(e,t.names),{})}}class m extends h{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class f extends h{}class g extends m{}g.kind="else";class y extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();const e=this.condition;if(!0===e)return this.nodes;let t=this.else;if(t){const e=t.optimizeNodes();t=this.else=Array.isArray(e)?new g(e):e}return t?!1===e?t instanceof y?t:t.nodes:this.nodes.length?this:new y(R(e),t instanceof y?[t]:t.nodes):!1!==e&&this.nodes.length?this:void 0}optimizeNames(e,t){var n;if(this.else=null===(n=this.else)||void 0===n?void 0:n.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=N(this.condition,e,t),this}get names(){const e=super.names;return x(e,this.condition),this.else&&O(e,this.else.names),e}}y.kind="if";class _ extends m{}_.kind="for";class v extends _{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=N(this.iteration,e,t),this}get names(){return O(super.names,this.iteration.names)}}class w extends _{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){const t=e.es5?n.varKinds.var:this.varKind,{name:r,from:s,to:o}=this;return`for(${t} ${r}=${s}; ${r}<${o}; ${r}++)`+super.render(e)}get names(){const e=x(super.names,this.from);return x(e,this.to)}}class b extends _{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=N(this.iterable,e,t),this}get names(){return O(super.names,this.iterable.names)}}class k extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}k.kind="func";class $ extends h{render(e){return"return "+super.render(e)}}$.kind="return";class S extends m{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),null===(e=this.catch)||void 0===e||e.optimizeNodes(),null===(t=this.finally)||void 0===t||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),null===(n=this.catch)||void 0===n||n.optimizeNames(e,t),null===(r=this.finally)||void 0===r||r.optimizeNames(e,t),this}get names(){const e=super.names;return this.catch&&O(e,this.catch.names),this.finally&&O(e,this.finally.names),e}}class E extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}E.kind="catch";class T extends m{render(e){return"finally"+super.render(e)}}function O(e,t){for(const n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function x(e,n){return n instanceof t._CodeOrName?O(e,n.names):e}function N(e,n,r){return e instanceof t.Name?o(e):(s=e)instanceof t._Code&&s._items.some(e=>e instanceof t.Name&&1===n[e.str]&&void 0!==r[e.str])?new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=o(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[])):e;var s;function o(e){const t=r[e.str];return void 0===t||1!==n[e.str]?e:(delete n[e.str],t)}}function I(e,t){for(const n in t)e[n]=(e[n]||0)-(t[n]||0)}function R(e){return"boolean"==typeof e||"number"==typeof e||null===e?!e:t._`!${z(e)}`}T.kind="finally",e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?"\n":""},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new f]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){const n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){const s=this._scope.toName(t);return void 0!==n&&r&&(this._constants[s.str]=n),this._leafNode(new a(e,s,n)),s}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new i(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return"function"==typeof e?e():e!==t.nil&&this._leafNode(new p(e)),this}object(...e){const n=["{"];for(const[r,s]of e)n.length>1&&n.push(","),n.push(r),(r!==s||this.opts.es5)&&(n.push(":"),(0,t.addCodeArg)(n,s));return n.push("}"),new t._Code(n)}if(e,t,n){if(this._blockNode(new y(e)),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(e){return this._elseNode(new y(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(y,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new v(e),t)}forRange(e,t,r,s,o=(this.opts.es5?n.varKinds.var:n.varKinds.let)){const a=this._scope.toName(e);return this._for(new w(o,a,t,r),()=>s(a))}forOf(e,r,s,o=n.varKinds.const){const a=this._scope.toName(e);if(this.opts.es5){const e=r instanceof t.Name?r:this.var("_arr",r);return this.forRange("_i",0,t._`${e}.length`,n=>{this.var(a,t._`${e}[${n}]`),s(a)})}return this._for(new b("of",o,a,r),()=>s(a))}forIn(e,r,s,o=(this.opts.es5?n.varKinds.var:n.varKinds.const)){if(this.opts.ownProperties)return this.forOf(e,t._`Object.keys(${r})`,s);const a=this._scope.toName(e);return this._for(new b("in",o,a,r),()=>s(a))}endFor(){return this._endBlockNode(_)}label(e){return this._leafNode(new d(e))}break(e){return this._leafNode(new u(e))}return(e){const t=new $;if(this._blockNode(t),this.code(e),1!==t.nodes.length)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode($)}try(e,t,n){if(!t&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');const r=new S;if(this._blockNode(r),this.code(e),t){const e=this.name("e");this._currNode=r.catch=new E(e),t(e)}return n&&(this._currNode=r.finally=new T,this.code(n)),this._endBlockNode(E,T)}throw(e){return this._leafNode(new l(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){const t=this._blockStarts.pop();if(void 0===t)throw new Error("CodeGen: not in self-balancing block");const n=this._nodes.length-t;if(n<0||void 0!==e&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,s){return this._blockNode(new k(e,n,r)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(k)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){const n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){const t=this._currNode;if(!(t instanceof y))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){const e=this._nodes;return e[e.length-1]}set _currNode(e){const t=this._nodes;t[t.length-1]=e}},e.not=R;const P=j(e.operators.AND);e.and=function(...e){return e.reduce(P)};const C=j(e.operators.OR);function j(e){return(n,r)=>n===t.nil?r:r===t.nil?n:t._`${z(n)} ${e} ${z(r)}`}function z(e){return e instanceof t.Name?e:t._`(${e})`}e.or=function(...e){return e.reduce(C)}}(Tl)),Tl}var jl,zl={};function Al(){if(jl)return zl;jl=1,Object.defineProperty(zl,"__esModule",{value:!0}),zl.checkStrictMode=zl.getErrorPath=zl.Type=zl.useFunc=zl.setEvaluated=zl.evaluatedPropsToName=zl.mergeEvaluated=zl.eachItem=zl.unescapeJsonPointer=zl.escapeJsonPointer=zl.escapeFragment=zl.unescapeFragment=zl.schemaRefOrVal=zl.schemaHasRulesButRef=zl.schemaHasRules=zl.checkUnknownRules=zl.alwaysValidSchema=zl.toHash=void 0;const e=Cl(),t=xl();function n(e,t=e.schema){const{opts:n,self:r}=e;if(!n.strictSchema)return;if("boolean"==typeof t)return;const s=r.RULES.keywords;for(const n in t)s[n]||l(e,`unknown keyword: "${n}"`)}function r(e,t){if("boolean"==typeof e)return!e;for(const n in e)if(t[n])return!0;return!1}function s(e){return"number"==typeof e?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}function o(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function a({mergeNames:t,mergeToName:n,mergeValues:r,resultToName:s}){return(o,a,i,c)=>{const d=void 0===i?a:i instanceof e.Name?(a instanceof e.Name?t(o,a,i):n(o,a,i),i):a instanceof e.Name?(n(o,i,a),a):r(a,i);return c!==e.Name||d instanceof e.Name?d:s(o,d)}}function i(t,n){if(!0===n)return t.var("props",!0);const r=t.var("props",e._`{}`);return void 0!==n&&c(t,r,n),r}function c(t,n,r){Object.keys(r).forEach(r=>t.assign(e._`${n}${(0,e.getProperty)(r)}`,!0))}zl.toHash=function(e){const t={};for(const n of e)t[n]=!0;return t},zl.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(n(e,t),!r(t,e.self.RULES.all))},zl.checkUnknownRules=n,zl.schemaHasRules=r,zl.schemaHasRulesButRef=function(e,t){if("boolean"==typeof e)return!e;for(const n in e)if("$ref"!==n&&t.all[n])return!0;return!1},zl.schemaRefOrVal=function({topSchemaRef:t,schemaPath:n},r,s,o){if(!o){if("number"==typeof r||"boolean"==typeof r)return r;if("string"==typeof r)return e._`${r}`}return e._`${t}${n}${(0,e.getProperty)(s)}`},zl.unescapeFragment=function(e){return o(decodeURIComponent(e))},zl.escapeFragment=function(e){return encodeURIComponent(s(e))},zl.escapeJsonPointer=s,zl.unescapeJsonPointer=o,zl.eachItem=function(e,t){if(Array.isArray(e))for(const n of e)t(n);else t(e)},zl.mergeEvaluated={props:a({mergeNames:(t,n,r)=>t.if(e._`${r} !== true && ${n} !== undefined`,()=>{t.if(e._`${n} === true`,()=>t.assign(r,!0),()=>t.assign(r,e._`${r} || {}`).code(e._`Object.assign(${r}, ${n})`))}),mergeToName:(t,n,r)=>t.if(e._`${r} !== true`,()=>{!0===n?t.assign(r,!0):(t.assign(r,e._`${r} || {}`),c(t,r,n))}),mergeValues:(e,t)=>!0===e||{...e,...t},resultToName:i}),items:a({mergeNames:(t,n,r)=>t.if(e._`${r} !== true && ${n} !== undefined`,()=>t.assign(r,e._`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(t,n,r)=>t.if(e._`${r} !== true`,()=>t.assign(r,!0===n||e._`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>!0===e||Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})},zl.evaluatedPropsToName=i,zl.setEvaluated=c;const d={};var u;function l(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,!0===n)throw new Error(t);e.self.logger.warn(t)}}return zl.useFunc=function(e,n){return e.scopeValue("func",{ref:n,code:d[n.code]||(d[n.code]=new t._Code(n.code))})},function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"}(u||(zl.Type=u={})),zl.getErrorPath=function(t,n,r){if(t instanceof e.Name){const s=n===u.Num;return r?s?e._`"[" + ${t} + "]"`:e._`"['" + ${t} + "']"`:s?e._`"/" + ${t}`:e._`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,e.getProperty)(t).toString():"/"+s(t)},zl.checkStrictMode=l,zl}var Ml,Dl,Ll,Zl={};function Fl(){if(Ml)return Zl;Ml=1,Object.defineProperty(Zl,"__esModule",{value:!0});const e=Cl(),t={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")};return Zl.default=t,Zl}function ql(){return Dl||(Dl=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=Cl(),n=Al(),r=Fl();function s(e,n){const s=e.const("err",n);e.if(t._`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,t._`[${s}]`),t._`${r.default.vErrors}.push(${s})`),e.code(t._`${r.default.errors}++`)}function o(e,n){const{gen:r,validateName:s,schemaEnv:o}=e;o.$async?r.throw(t._`new ${e.ValidationError}(${n})`):(r.assign(t._`${s}.errors`,n),r.return(!1))}e.keywordError={message:({keyword:e})=>t.str`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?t.str`"${e}" keyword must be ${n} ($data)`:t.str`"${e}" keyword is invalid ($data)`},e.reportError=function(n,r=e.keywordError,a,c){const{it:d}=n,{gen:u,compositeRule:l,allErrors:p}=d,h=i(n,r,a);(null!=c?c:l||p)?s(u,h):o(d,t._`[${h}]`)},e.reportExtraError=function(t,n=e.keywordError,a){const{it:c}=t,{gen:d,compositeRule:u,allErrors:l}=c;s(d,i(t,n,a)),u||l||o(c,r.default.vErrors)},e.resetErrorsCount=function(e,n){e.assign(r.default.errors,n),e.if(t._`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign(t._`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))},e.extendErrors=function({gen:e,keyword:n,schemaValue:s,data:o,errsCount:a,it:i}){if(void 0===a)throw new Error("ajv implementation error");const c=e.name("err");e.forRange("i",a,r.default.errors,a=>{e.const(c,t._`${r.default.vErrors}[${a}]`),e.if(t._`${c}.instancePath === undefined`,()=>e.assign(t._`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,i.errorPath))),e.assign(t._`${c}.schemaPath`,t.str`${i.errSchemaPath}/${n}`),i.opts.verbose&&(e.assign(t._`${c}.schema`,s),e.assign(t._`${c}.data`,o))})};const a={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function i(e,n,s){const{createErrors:o}=e.it;return!1===o?t._`{}`:function(e,n,s={}){const{gen:o,it:i}=e,u=[c(i,s),d(e,s)];return function(e,{params:n,message:s},o){const{keyword:i,data:c,schemaValue:d,it:u}=e,{opts:l,propertyName:p,topSchemaRef:h,schemaPath:m}=u;o.push([a.keyword,i],[a.params,"function"==typeof n?n(e):n||t._`{}`]),l.messages&&o.push([a.message,"function"==typeof s?s(e):s]),l.verbose&&o.push([a.schema,d],[a.parentSchema,t._`${h}${m}`],[r.default.data,c]),p&&o.push([a.propertyName,p])}(e,n,u),o.object(...u)}(e,n,s)}function c({errorPath:e},{instancePath:s}){const o=s?t.str`${e}${(0,n.getErrorPath)(s,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,o)]}function d({keyword:e,it:{errSchemaPath:r}},{schemaPath:s,parentSchema:o}){let i=o?r:t.str`${r}/${e}`;return s&&(i=t.str`${i}${(0,n.getErrorPath)(s,n.Type.Str)}`),[a.schemaPath,i]}}(El)),El}var Ul,Hl={},Vl={};function Kl(){if(Ul)return Vl;Ul=1,Object.defineProperty(Vl,"__esModule",{value:!0}),Vl.getRules=Vl.isJSONType=void 0;const e=new Set(["string","number","integer","boolean","null","object","array"]);return Vl.isJSONType=function(t){return"string"==typeof t&&e.has(t)},Vl.getRules=function(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}},Vl}var Jl,Bl,Wl={};function Gl(){if(Jl)return Wl;function e(e,n){return n.rules.some(n=>t(e,n))}function t(e,t){var n;return void 0!==e[t.keyword]||(null===(n=t.definition.implements)||void 0===n?void 0:n.some(t=>void 0!==e[t]))}return Jl=1,Object.defineProperty(Wl,"__esModule",{value:!0}),Wl.shouldUseRule=Wl.shouldUseGroup=Wl.schemaHasRulesForType=void 0,Wl.schemaHasRulesForType=function({schema:t,self:n},r){const s=n.RULES.types[r];return s&&!0!==s&&e(t,s)},Wl.shouldUseGroup=e,Wl.shouldUseRule=t,Wl}function Xl(){if(Bl)return Hl;Bl=1,Object.defineProperty(Hl,"__esModule",{value:!0}),Hl.reportTypeError=Hl.checkDataTypes=Hl.checkDataType=Hl.coerceAndCheckDataType=Hl.getJSONTypes=Hl.getSchemaTypes=Hl.DataType=void 0;const e=Kl(),t=Gl(),n=ql(),r=Cl(),s=Al();var o;function a(t){const n=Array.isArray(t)?t:t?[t]:[];if(n.every(e.isJSONType))return n;throw new Error("type must be JSONType or JSONType[]: "+n.join(","))}!function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"}(o||(Hl.DataType=o={})),Hl.getSchemaTypes=function(e){const t=a(e.type);if(t.includes("null")){if(!1===e.nullable)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&void 0!==e.nullable)throw new Error('"nullable" cannot be used without "type"');!0===e.nullable&&t.push("null")}return t},Hl.getJSONTypes=a,Hl.coerceAndCheckDataType=function(e,n){const{gen:s,data:a,opts:c}=e,u=function(e,t){return t?e.filter(e=>i.has(e)||"array"===t&&"array"===e):[]}(n,c.coerceTypes),p=n.length>0&&!(0===u.length&&1===n.length&&(0,t.schemaHasRulesForType)(e,n[0]));if(p){const t=d(n,a,c.strictNumbers,o.Wrong);s.if(t,()=>{u.length?function(e,t,n){const{gen:s,data:o,opts:a}=e,c=s.let("dataType",r._`typeof ${o}`),u=s.let("coerced",r._`undefined`);"array"===a.coerceTypes&&s.if(r._`${c} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>s.assign(o,r._`${o}[0]`).assign(c,r._`typeof ${o}`).if(d(t,o,a.strictNumbers),()=>s.assign(u,o))),s.if(r._`${u} !== undefined`);for(const e of n)(i.has(e)||"array"===e&&"array"===a.coerceTypes)&&p(e);function p(e){switch(e){case"string":return void s.elseIf(r._`${c} == "number" || ${c} == "boolean"`).assign(u,r._`"" + ${o}`).elseIf(r._`${o} === null`).assign(u,r._`""`);case"number":return void s.elseIf(r._`${c} == "boolean" || ${o} === null
3
3
  || (${c} == "string" && ${o} && ${o} == +${o})`).assign(u,r._`+${o}`);case"integer":return void s.elseIf(r._`${c} === "boolean" || ${o} === null
4
4
  || (${c} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(u,r._`+${o}`);case"boolean":return void s.elseIf(r._`${o} === "false" || ${o} === 0 || ${o} === null`).assign(u,!1).elseIf(r._`${o} === "true" || ${o} === 1`).assign(u,!0);case"null":return s.elseIf(r._`${o} === "" || ${o} === 0 || ${o} === false`),void s.assign(u,null);case"array":s.elseIf(r._`${c} === "string" || ${c} === "number"
5
- || ${c} === "boolean" || ${o} === null`).assign(u,r._`[${o}]`)}}s.else(),l(e),s.endIf(),s.if(r._`${u} !== undefined`,()=>{s.assign(o,u),function({gen:e,parentData:t,parentDataProperty:n},s){e.if(r._`${t} !== undefined`,()=>e.assign(r._`${t}[${n}]`,s))}(e,u)})}(e,n,u):l(e)})}return p};const i=new Set(["string","number","integer","boolean","null"]);function c(e,t,n,s=o.Correct){const a=s===o.Correct?r.operators.EQ:r.operators.NEQ;let i;switch(e){case"null":return r._`${t} ${a} null`;case"array":i=r._`Array.isArray(${t})`;break;case"object":i=r._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=c(r._`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=c();break;default:return r._`typeof ${t} ${a} ${e}`}return s===o.Correct?i:(0,r.not)(i);function c(e=r.nil){return(0,r.and)(r._`typeof ${t} == "number"`,e,n?r._`isFinite(${t})`:r.nil)}}function d(e,t,n,o){if(1===e.length)return c(e[0],t,n,o);let a;const i=(0,s.toHash)(e);if(i.array&&i.object){const e=r._`typeof ${t} != "object"`;a=i.null?e:r._`!${t} || ${e}`,delete i.null,delete i.array,delete i.object}else a=r.nil;i.number&&delete i.integer;for(const e in i)a=(0,r.and)(a,c(e,t,n,o));return a}Hl.checkDataType=c,Hl.checkDataTypes=d;const u={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?r._`{type: ${e}}`:r._`{type: ${t}}`};function l(e){const t=function(e){const{gen:t,data:n,schema:r}=e,o=(0,s.schemaRefOrVal)(e,r,"type");return{gen:t,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:e}}(e);(0,n.reportError)(t,u)}return Hl.reportTypeError=l,Hl}var Yl,Ql,ep,tp={},np={},rp={};function sp(){if(Ql)return rp;Ql=1,Object.defineProperty(rp,"__esModule",{value:!0}),rp.validateUnion=rp.validateArray=rp.usePattern=rp.callValidateCode=rp.schemaProperties=rp.allSchemaProperties=rp.noPropertyInData=rp.propertyInData=rp.isOwnProperty=rp.hasPropFunc=rp.reportMissingProp=rp.checkMissingProp=rp.checkReportMissingProp=void 0;const e=Cl(),t=Al(),n=Fl(),r=Al();function s(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:e._`Object.prototype.hasOwnProperty`})}function o(t,n,r){return e._`${s(t)}.call(${n}, ${r})`}function a(t,n,r,s){const a=e._`${n}${(0,e.getProperty)(r)} === undefined`;return s?(0,e.or)(a,(0,e.not)(o(t,n,r))):a}function i(e){return e?Object.keys(e).filter(e=>"__proto__"!==e):[]}rp.checkReportMissingProp=function(t,n){const{gen:r,data:s,it:o}=t;r.if(a(r,s,n,o.opts.ownProperties),()=>{t.setParams({missingProperty:e._`${n}`},!0),t.error()})},rp.checkMissingProp=function({gen:t,data:n,it:{opts:r}},s,o){return(0,e.or)(...s.map(s=>(0,e.and)(a(t,n,s,r.ownProperties),e._`${o} = ${s}`)))},rp.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},rp.hasPropFunc=s,rp.isOwnProperty=o,rp.propertyInData=function(t,n,r,s){const a=e._`${n}${(0,e.getProperty)(r)} !== undefined`;return s?e._`${a} && ${o(t,n,r)}`:a},rp.noPropertyInData=a,rp.allSchemaProperties=i,rp.schemaProperties=function(e,n){return i(n).filter(r=>!(0,t.alwaysValidSchema)(e,n[r]))},rp.callValidateCode=function({schemaCode:t,data:r,it:{gen:s,topSchemaRef:o,schemaPath:a,errorPath:i},it:c},d,u,l){const p=l?e._`${t}, ${r}, ${o}${a}`:r,h=[[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,i)],[n.default.parentData,c.parentData],[n.default.parentDataProperty,c.parentDataProperty],[n.default.rootData,n.default.rootData]];c.opts.dynamicRef&&h.push([n.default.dynamicAnchors,n.default.dynamicAnchors]);const m=e._`${p}, ${s.object(...h)}`;return u!==e.nil?e._`${d}.call(${u}, ${m})`:e._`${d}(${m})`};const c=e._`new RegExp`;return rp.usePattern=function({gen:t,it:{opts:n}},s){const o=n.unicodeRegExp?"u":"",{regExp:a}=n.code,i=a(s,o);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:e._`${"new RegExp"===a.code?c:(0,r.useFunc)(t,a)}(${s}, ${o})`})},rp.validateArray=function(n){const{gen:r,data:s,keyword:o,it:a}=n,i=r.name("valid");if(a.allErrors){const e=r.let("valid",!0);return c(()=>r.assign(e,!1)),e}return r.var(i,!0),c(()=>r.break()),i;function c(a){const c=r.const("len",e._`${s}.length`);r.forRange("i",0,c,s=>{n.subschema({keyword:o,dataProp:s,dataPropType:t.Type.Num},i),r.if((0,e.not)(i),a)})}},rp.validateUnion=function(n){const{gen:r,schema:s,keyword:o,it:a}=n;if(!Array.isArray(s))throw new Error("ajv implementation error");if(s.some(e=>(0,t.alwaysValidSchema)(a,e))&&!a.opts.unevaluated)return;const i=r.let("valid",!1),c=r.name("_valid");r.block(()=>s.forEach((t,s)=>{const a=n.subschema({keyword:o,schemaProp:s,compositeRule:!0},c);r.assign(i,e._`${i} || ${c}`),n.mergeValidEvaluated(a,c)||r.if((0,e.not)(i))})),n.result(i,()=>n.reset(),()=>n.error(!0))},rp}var op,ap,ip,cp={},dp={};function up(){return ip||(ip=1,ap=function e(t,n){if(t===n)return!0;if(t&&n&&"object"==typeof t&&"object"==typeof n){if(t.constructor!==n.constructor)return!1;var r,s,o;if(Array.isArray(t)){if((r=t.length)!=n.length)return!1;for(s=r;0!==s--;)if(!e(t[s],n[s]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if((r=(o=Object.keys(t)).length)!==Object.keys(n).length)return!1;for(s=r;0!==s--;)if(!Object.prototype.hasOwnProperty.call(n,o[s]))return!1;for(s=r;0!==s--;){var a=o[s];if(!e(t[a],n[a]))return!1}return!0}return t!=t&&n!=n}),ap}var lp,pp,hp,mp={exports:{}};function fp(){if(lp)return mp.exports;lp=1;var e=mp.exports=function(e,n,r){"function"==typeof n&&(r=n,n={}),t(n,"function"==typeof(r=n.cb||r)?r:r.pre||function(){},r.post||function(){},e,"",e)};function t(r,s,o,a,i,c,d,u,l,p){if(a&&"object"==typeof a&&!Array.isArray(a)){for(var h in s(a,i,c,d,u,l,p),a){var m=a[h];if(Array.isArray(m)){if(h in e.arrayKeywords)for(var f=0;f<m.length;f++)t(r,s,o,m[f],i+"/"+h+"/"+f,c,i,h,a,f)}else if(h in e.propsKeywords){if(m&&"object"==typeof m)for(var g in m)t(r,s,o,m[g],i+"/"+h+"/"+n(g),c,i,h,a,g)}else(h in e.keywords||r.allKeys&&!(h in e.skipKeywords))&&t(r,s,o,m,i+"/"+h,c,i,h,a)}o(a,i,c,d,u,l,p)}}function n(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}return e.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},e.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},e.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},e.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},mp.exports}function gp(){if(pp)return dp;pp=1,Object.defineProperty(dp,"__esModule",{value:!0}),dp.getSchemaRefs=dp.resolveUrl=dp.normalizeId=dp._getFullPath=dp.getFullPath=dp.inlineRef=void 0;const e=Al(),t=up(),n=fp(),r=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);dp.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!o(e):!!t&&a(e)<=t)};const s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function o(e){for(const t in e){if(s.has(t))return!0;const n=e[t];if(Array.isArray(n)&&n.some(o))return!0;if("object"==typeof n&&o(n))return!0}return!1}function a(t){let n=0;for(const s in t){if("$ref"===s)return 1/0;if(n++,!r.has(s)&&("object"==typeof t[s]&&(0,e.eachItem)(t[s],e=>n+=a(e)),n===1/0))return 1/0}return n}function i(e,t="",n){!1!==n&&(t=u(t));const r=e.parse(t);return c(e,r)}function c(e,t){return e.serialize(t).split("#")[0]+"#"}dp.getFullPath=i,dp._getFullPath=c;const d=/#\/?$/;function u(e){return e?e.replace(d,""):""}dp.normalizeId=u,dp.resolveUrl=function(e,t,n){return n=u(n),e.resolve(t,n)};const l=/^[a-z_][-a-z0-9._]*$/i;return dp.getSchemaRefs=function(e,r){if("boolean"==typeof e)return{};const{schemaId:s,uriResolver:o}=this.opts,a=u(e[s]||r),c={"":a},d=i(o,a,!1),p={},h=new Set;return n(e,{allKeys:!0},(e,t,n,r)=>{if(void 0===r)return;const o=d+t;let a=c[r];function i(t){const n=this.opts.uriResolver.resolve;if(t=u(a?n(a,t):t),h.has(t))throw f(t);h.add(t);let r=this.refs[t];return"string"==typeof r&&(r=this.refs[r]),"object"==typeof r?m(e,r.schema,t):t!==u(o)&&("#"===t[0]?(m(e,p[t],t),p[t]=e):this.refs[t]=o),t}function g(e){if("string"==typeof e){if(!l.test(e))throw new Error(`invalid anchor "${e}"`);i.call(this,`#${e}`)}}"string"==typeof e[s]&&(a=i.call(this,e[s])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),c[t]=a}),p;function m(e,n,r){if(void 0!==n&&!t(e,n))throw f(r)}function f(e){return new Error(`reference "${e}" resolves to more than one schema`)}},dp}function yp(){if(hp)return El;hp=1,Object.defineProperty(El,"__esModule",{value:!0}),El.getData=El.KeywordCxt=El.validateFunctionCode=void 0;const e=function(){if(Ll)return $l;Ll=1,Object.defineProperty($l,"__esModule",{value:!0}),$l.boolOrEmptySchema=$l.topBoolOrEmptySchema=void 0;const e=Ul(),t=Cl(),n=Fl(),r={message:"boolean schema is false"};function s(t,n){const{gen:s,data:o}=t,a={gen:s,keyword:"false schema",data:o,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,e.reportError)(a,r,void 0,n)}return $l.topBoolOrEmptySchema=function(e){const{gen:r,schema:o,validateName:a}=e;!1===o?s(e,!1):"object"==typeof o&&!0===o.$async?r.return(n.default.data):(r.assign(t._`${a}.errors`,null),r.return(!0))},$l.boolOrEmptySchema=function(e,t){const{gen:n,schema:r}=e;!1===r?(n.var(t,!1),s(e)):n.var(t,!0)},$l}(),t=Xl(),n=Gl(),r=Xl(),s=function(){if(Yl)return tp;Yl=1,Object.defineProperty(tp,"__esModule",{value:!0}),tp.assignDefaults=void 0;const e=Cl(),t=Al();function n(n,r,s){const{gen:o,compositeRule:a,data:i,opts:c}=n;if(void 0===s)return;const d=e._`${i}${(0,e.getProperty)(r)}`;if(a)return void(0,t.checkStrictMode)(n,`default is ignored for: ${d}`);let u=e._`${d} === undefined`;"empty"===c.useDefaults&&(u=e._`${u} || ${d} === null || ${d} === ""`),o.if(u,e._`${d} = ${(0,e.stringify)(s)}`)}return tp.assignDefaults=function(e,t){const{properties:r,items:s}=e.schema;if("object"===t&&r)for(const t in r)n(e,t,r[t].default);else"array"===t&&Array.isArray(s)&&s.forEach((t,r)=>n(e,r,t.default))},tp}(),o=function(){if(ep)return np;ep=1,Object.defineProperty(np,"__esModule",{value:!0}),np.validateKeywordUsage=np.validSchemaType=np.funcKeywordCode=np.macroKeywordCode=void 0;const e=Cl(),t=Fl(),n=sp(),r=Ul();function s(t){const{gen:n,data:r,it:s}=t;n.if(s.parentData,()=>n.assign(r,e._`${s.parentData}[${s.parentDataProperty}]`))}function o(t,n,r){if(void 0===r)throw new Error(`keyword "${n}" failed to compile`);return t.scopeValue("keyword","function"==typeof r?{ref:r}:{ref:r,code:(0,e.stringify)(r)})}return np.macroKeywordCode=function(t,n){const{gen:r,keyword:s,schema:a,parentSchema:i,it:c}=t,d=n.macro.call(c.self,a,i,c),u=o(r,s,d);!1!==c.opts.validateSchema&&c.self.validateSchema(d,!0);const l=r.name("valid");t.subschema({schema:d,schemaPath:e.nil,errSchemaPath:`${c.errSchemaPath}/${s}`,topSchemaRef:u,compositeRule:!0},l),t.pass(l,()=>t.error(!0))},np.funcKeywordCode=function(a,i){var c;const{gen:d,keyword:u,schema:l,parentSchema:p,$data:h,it:m}=a;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(m,i);const f=!h&&i.compile?i.compile.call(m.self,l,p,m):i.validate,g=o(d,u,f),y=d.let("valid");function _(r=(i.async?e._`await `:e.nil)){const s=m.opts.passContext?t.default.this:t.default.self,o=!("compile"in i&&!h||!1===i.schema);d.assign(y,e._`${r}${(0,n.callValidateCode)(a,g,s,o)}`,i.modifying)}function v(t){var n;d.if((0,e.not)(null!==(n=i.valid)&&void 0!==n?n:y),t)}a.block$data(y,function(){if(!1===i.errors)_(),i.modifying&&s(a),v(()=>a.error());else{const n=i.async?function(){const t=d.let("ruleErrs",null);return d.try(()=>_(e._`await `),n=>d.assign(y,!1).if(e._`${n} instanceof ${m.ValidationError}`,()=>d.assign(t,e._`${n}.errors`),()=>d.throw(n))),t}():function(){const t=e._`${g}.errors`;return d.assign(t,null),_(e.nil),t}();i.modifying&&s(a),v(()=>function(n,s){const{gen:o}=n;o.if(e._`Array.isArray(${s})`,()=>{o.assign(t.default.vErrors,e._`${t.default.vErrors} === null ? ${s} : ${t.default.vErrors}.concat(${s})`).assign(t.default.errors,e._`${t.default.vErrors}.length`),(0,r.extendErrors)(n)},()=>n.error())}(a,n))}}),a.ok(null!==(c=i.valid)&&void 0!==c?c:y)},np.validSchemaType=function(e,t,n=!1){return!t.length||t.some(t=>"array"===t?Array.isArray(e):"object"===t?e&&"object"==typeof e&&!Array.isArray(e):typeof e==t||n&&void 0===e)},np.validateKeywordUsage=function({schema:e,opts:t,self:n,errSchemaPath:r},s,o){if(Array.isArray(s.keyword)?!s.keyword.includes(o):s.keyword!==o)throw new Error("ajv implementation error");const a=s.dependencies;if(null==a?void 0:a.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw new Error(`parent schema must have dependencies of ${o}: ${a.join(",")}`);if(s.validateSchema&&!s.validateSchema(e[o])){const e=`keyword "${o}" value is invalid at path "${r}": `+n.errorsText(s.validateSchema.errors);if("log"!==t.validateSchema)throw new Error(e);n.logger.error(e)}},np}(),a=function(){if(op)return cp;op=1,Object.defineProperty(cp,"__esModule",{value:!0}),cp.extendSubschemaMode=cp.extendSubschemaData=cp.getSubschema=void 0;const e=Cl(),t=Al();return cp.getSubschema=function(n,{keyword:r,schemaProp:s,schema:o,schemaPath:a,errSchemaPath:i,topSchemaRef:c}){if(void 0!==r&&void 0!==o)throw new Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==r){const o=n.schema[r];return void 0===s?{schema:o,schemaPath:e._`${n.schemaPath}${(0,e.getProperty)(r)}`,errSchemaPath:`${n.errSchemaPath}/${r}`}:{schema:o[s],schemaPath:e._`${n.schemaPath}${(0,e.getProperty)(r)}${(0,e.getProperty)(s)}`,errSchemaPath:`${n.errSchemaPath}/${r}/${(0,t.escapeFragment)(s)}`}}if(void 0!==o){if(void 0===a||void 0===i||void 0===c)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:o,schemaPath:a,topSchemaRef:c,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')},cp.extendSubschemaData=function(n,r,{dataProp:s,dataPropType:o,data:a,dataTypes:i,propertyName:c}){if(void 0!==a&&void 0!==s)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:d}=r;if(void 0!==s){const{errorPath:a,dataPathArr:i,opts:c}=r;u(d.let("data",e._`${r.data}${(0,e.getProperty)(s)}`,!0)),n.errorPath=e.str`${a}${(0,t.getErrorPath)(s,o,c.jsPropertySyntax)}`,n.parentDataProperty=e._`${s}`,n.dataPathArr=[...i,n.parentDataProperty]}function u(e){n.data=e,n.dataLevel=r.dataLevel+1,n.dataTypes=[],r.definedProperties=new Set,n.parentData=r.data,n.dataNames=[...r.dataNames,e]}void 0!==a&&(u(a instanceof e.Name?a:d.let("data",a,!0)),void 0!==c&&(n.propertyName=c)),i&&(n.dataTypes=i)},cp.extendSubschemaMode=function(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:s,allErrors:o}){void 0!==r&&(e.compositeRule=r),void 0!==s&&(e.createErrors=s),void 0!==o&&(e.allErrors=o),e.jtdDiscriminator=t,e.jtdMetadata=n},cp}(),i=Cl(),c=Fl(),d=gp(),u=Al(),l=Ul();function p({gen:e,validateName:t,schema:n,schemaEnv:r,opts:s},o){s.code.es5?e.func(t,i._`${c.default.data}, ${c.default.valCxt}`,r.$async,()=>{e.code(i._`"use strict"; ${h(n,s)}`),function(e,t){e.if(c.default.valCxt,()=>{e.var(c.default.instancePath,i._`${c.default.valCxt}.${c.default.instancePath}`),e.var(c.default.parentData,i._`${c.default.valCxt}.${c.default.parentData}`),e.var(c.default.parentDataProperty,i._`${c.default.valCxt}.${c.default.parentDataProperty}`),e.var(c.default.rootData,i._`${c.default.valCxt}.${c.default.rootData}`),t.dynamicRef&&e.var(c.default.dynamicAnchors,i._`${c.default.valCxt}.${c.default.dynamicAnchors}`)},()=>{e.var(c.default.instancePath,i._`""`),e.var(c.default.parentData,i._`undefined`),e.var(c.default.parentDataProperty,i._`undefined`),e.var(c.default.rootData,c.default.data),t.dynamicRef&&e.var(c.default.dynamicAnchors,i._`{}`)})}(e,s),e.code(o)}):e.func(t,i._`${c.default.data}, ${function(e){return i._`{${c.default.instancePath}="", ${c.default.parentData}, ${c.default.parentDataProperty}, ${c.default.rootData}=${c.default.data}${e.dynamicRef?i._`, ${c.default.dynamicAnchors}={}`:i.nil}}={}`}(s)}`,r.$async,()=>e.code(h(n,s)).code(o))}function h(e,t){const n="object"==typeof e&&e[t.schemaId];return n&&(t.code.source||t.code.process)?i._`/*# sourceURL=${n} */`:i.nil}function m({schema:e,self:t}){if("boolean"==typeof e)return!e;for(const n in e)if(t.RULES.all[n])return!0;return!1}function f(e){return"boolean"!=typeof e.schema}function g(e){(0,u.checkUnknownRules)(e),function(e){const{schema:t,errSchemaPath:n,opts:r,self:s}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(t,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}(e)}function y(e,n){if(e.opts.jtd)return v(e,[],!1,n);const r=(0,t.getSchemaTypes)(e.schema);v(e,r,!(0,t.coerceAndCheckDataType)(e,r),n)}function _({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:s}){const o=n.$comment;if(!0===s.$comment)e.code(i._`${c.default.self}.logger.log(${o})`);else if("function"==typeof s.$comment){const n=i.str`${r}/$comment`,s=e.scopeValue("root",{ref:t.root});e.code(i._`${c.default.self}.opts.$comment(${o}, ${n}, ${s}.schema)`)}}function v(e,t,s,o){const{gen:a,schema:d,data:l,allErrors:p,opts:h,self:m}=e,{RULES:f}=m;function g(u){(0,n.shouldUseGroup)(d,u)&&(u.type?(a.if((0,r.checkDataType)(u.type,l,h.strictNumbers)),w(e,u),1===t.length&&t[0]===u.type&&s&&(a.else(),(0,r.reportTypeError)(e)),a.endIf()):w(e,u),p||a.if(i._`${c.default.errors} === ${o||0}`))}!d.$ref||!h.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(d,f)?(h.jtd||function(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(function(e,t){t.length&&(e.dataTypes.length?(t.forEach(t=>{b(e.dataTypes,t)||k(e,`type "${t}" not allowed by context "${e.dataTypes.join(",")}"`)}),function(e,t){const n=[];for(const r of e.dataTypes)b(t,r)?n.push(r):t.includes("integer")&&"number"===r&&n.push("integer");e.dataTypes=n}(e,t)):e.dataTypes=t)}(e,t),e.opts.allowUnionTypes||function(e,t){t.length>1&&(2!==t.length||!t.includes("null"))&&k(e,"use allowUnionTypes to allow union type keyword")}(e,t),function(e,t){const r=e.self.RULES.all;for(const s in r){const o=r[s];if("object"==typeof o&&(0,n.shouldUseRule)(e.schema,o)){const{type:n}=o.definition;n.length&&!n.some(e=>{return r=e,(n=t).includes(r)||"number"===r&&n.includes("integer");var n,r})&&k(e,`missing type "${n.join(",")}" for keyword "${s}"`)}}}(e,e.dataTypes))}(e,t),a.block(()=>{for(const e of f.rules)g(e);g(f.post)})):a.block(()=>$(e,"$ref",f.all.$ref.definition))}function w(e,t){const{gen:r,schema:o,opts:{useDefaults:a}}=e;a&&(0,s.assignDefaults)(e,t.type),r.block(()=>{for(const r of t.rules)(0,n.shouldUseRule)(o,r)&&$(e,r.keyword,r.definition,t.type)})}function b(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function k(e,t){t+=` at "${e.schemaEnv.baseId+e.errSchemaPath}" (strictTypes)`,(0,u.checkStrictMode)(e,t,e.opts.strictTypes)}El.validateFunctionCode=function(t){f(t)&&(g(t),m(t))?function(e){const{schema:t,opts:n,gen:r}=e;p(e,()=>{n.$comment&&t.$comment&&_(e),function(e){const{schema:t,opts:n}=e;void 0!==t.default&&n.useDefaults&&n.strictSchema&&(0,u.checkStrictMode)(e,"default is ignored in the schema root")}(e),r.let(c.default.vErrors,null),r.let(c.default.errors,0),n.unevaluated&&function(e){const{gen:t,validateName:n}=e;e.evaluated=t.const("evaluated",i._`${n}.evaluated`),t.if(i._`${e.evaluated}.dynamicProps`,()=>t.assign(i._`${e.evaluated}.props`,i._`undefined`)),t.if(i._`${e.evaluated}.dynamicItems`,()=>t.assign(i._`${e.evaluated}.items`,i._`undefined`))}(e),y(e),function(e){const{gen:t,schemaEnv:n,validateName:r,ValidationError:s,opts:o}=e;n.$async?t.if(i._`${c.default.errors} === 0`,()=>t.return(c.default.data),()=>t.throw(i._`new ${s}(${c.default.vErrors})`)):(t.assign(i._`${r}.errors`,c.default.vErrors),o.unevaluated&&function({gen:e,evaluated:t,props:n,items:r}){n instanceof i.Name&&e.assign(i._`${t}.props`,n),r instanceof i.Name&&e.assign(i._`${t}.items`,r)}(e),t.return(i._`${c.default.errors} === 0`))}(e)})}(t):p(t,()=>(0,e.topBoolOrEmptySchema)(t))};class E{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",O(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:!1!==t.errors)&&(this.errsCount=e.gen.const("_errs",c.default.errors))}result(e,t,n){this.failResult((0,i.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,i.not)(e),void 0,t)}fail(e){if(void 0===e)return this.error(),void(this.allErrors||this.gen.if(!1));this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:t}=this;this.fail(i._`${t} !== undefined && (${(0,i.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t)return this.setParams(t),this._error(e,n),void this.setParams({});this._error(e,n)}_error(e,t){(e?l.reportExtraError:l.reportError)(this,this.def.error,t)}$dataError(){(0,l.reportError)(this,this.def.$dataError||l.keyword$DataError)}reset(){if(void 0===this.errsCount)throw new Error('add "trackErrors" to keyword definition');(0,l.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=i.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=i.nil,t=i.nil){if(!this.$data)return;const{gen:n,schemaCode:r,schemaType:s,def:o}=this;n.if((0,i.or)(i._`${r} === undefined`,t)),e!==i.nil&&n.assign(e,!0),(s.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==i.nil&&n.assign(e,!1)),n.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:n,def:s,it:o}=this;return(0,i.or)(function(){if(n.length){if(!(t instanceof i.Name))throw new Error("ajv implementation error");const e=Array.isArray(n)?n:[n];return i._`${(0,r.checkDataTypes)(e,t,o.opts.strictNumbers,r.DataType.Wrong)}`}return i.nil}(),function(){if(s.validateSchema){const n=e.scopeValue("validate$data",{ref:s.validateSchema});return i._`!${n}(${t})`}return i.nil}())}subschema(t,n){const r=(0,a.getSubschema)(this.it,t);(0,a.extendSubschemaData)(r,this.it,t),(0,a.extendSubschemaMode)(r,t);const s={...this.it,...r,items:void 0,props:void 0};return function(t,n){f(t)&&(g(t),m(t))?function(e,t){const{schema:n,gen:r,opts:s}=e;s.$comment&&n.$comment&&_(e),function(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,d.resolveUrl)(e.opts.uriResolver,e.baseId,t))}(e),function(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}(e);const o=r.const("_errs",c.default.errors);y(e,o),r.var(t,i._`${o} === ${c.default.errors}`)}(t,n):(0,e.boolOrEmptySchema)(t,n)}(s,n),s}mergeEvaluated(e,t){const{it:n,gen:r}=this;n.opts.unevaluated&&(!0!==n.props&&void 0!==e.props&&(n.props=u.mergeEvaluated.props(r,e.props,n.props,t)),!0!==n.items&&void 0!==e.items&&(n.items=u.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){const{it:n,gen:r}=this;if(n.opts.unevaluated&&(!0!==n.props||!0!==n.items))return r.if(t,()=>this.mergeEvaluated(e,i.Name)),!0}}function $(e,t,n,r){const s=new E(e,n,t);"code"in n?n.code(s,r):s.$data&&n.validate?(0,o.funcKeywordCode)(s,n):"macro"in n?(0,o.macroKeywordCode)(s,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(s,n)}El.KeywordCxt=E;const S=/^\/(?:[^~]|~0|~1)*$/,T=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function O(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let s,o;if(""===e)return c.default.rootData;if("/"===e[0]){if(!S.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);s=e,o=c.default.rootData}else{const a=T.exec(e);if(!a)throw new Error(`Invalid JSON-pointer: ${e}`);const i=+a[1];if(s=a[2],"#"===s){if(i>=t)throw new Error(l("property/index",i));return r[t-i]}if(i>t)throw new Error(l("data",i));if(o=n[t-i],!s)return o}let a=o;const d=s.split("/");for(const e of d)e&&(o=i._`${o}${(0,i.getProperty)((0,u.unescapeJsonPointer)(e))}`,a=i._`${a} && ${o}`);return a;function l(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}return El.getData=O,El}var _p,vp={};function wp(){if(_p)return vp;_p=1,Object.defineProperty(vp,"__esModule",{value:!0});class e extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}return vp.default=e,vp}var bp,kp={};function Ep(){if(bp)return kp;bp=1,Object.defineProperty(kp,"__esModule",{value:!0});const e=gp();class t extends Error{constructor(t,n,r,s){super(s||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,e.resolveUrl)(t,n,r),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(t,this.missingRef))}}return kp.default=t,kp}var $p,Sp={};function Tp(){if($p)return Sp;$p=1,Object.defineProperty(Sp,"__esModule",{value:!0}),Sp.resolveSchema=Sp.getCompilingSchema=Sp.resolveRef=Sp.compileSchema=Sp.SchemaEnv=void 0;const e=Cl(),t=wp(),n=Fl(),r=gp(),s=Al(),o=yp();class a{constructor(e){var t;let n;this.refs={},this.dynamicAnchors={},"object"==typeof e.schema&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=null!==(t=e.baseId)&&void 0!==t?t:(0,r.normalizeId)(null==n?void 0:n[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=null==n?void 0:n.$async,this.refs={}}}function i(s){const a=d.call(this,s);if(a)return a;const i=(0,r.getFullPath)(this.opts.uriResolver,s.root.baseId),{es5:c,lines:u}=this.opts.code,{ownProperties:l}=this.opts,p=new e.CodeGen(this.scope,{es5:c,lines:u,ownProperties:l});let h;s.$async&&(h=p.scopeValue("Error",{ref:t.default,code:e._`require("ajv/dist/runtime/validation_error").default`}));const m=p.scopeName("validate");s.validateName=m;const f={gen:p,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:p.scopeValue("schema",!0===this.opts.code.source?{ref:s.schema,code:(0,e.stringify)(s.schema)}:{ref:s.schema}),validateName:m,ValidationError:h,schema:s.schema,schemaEnv:s,rootId:i,baseId:s.baseId||i,schemaPath:e.nil,errSchemaPath:s.schemaPath||(this.opts.jtd?"":"#"),errorPath:e._`""`,opts:this.opts,self:this};let g;try{this._compilations.add(s),(0,o.validateFunctionCode)(f),p.optimize(this.opts.code.optimize);const t=p.toString();g=`${p.scopeRefs(n.default.scope)}return ${t}`,this.opts.code.process&&(g=this.opts.code.process(g,s));const r=new Function(`${n.default.self}`,`${n.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:r}),r.errors=null,r.schema=s.schema,r.schemaEnv=s,s.$async&&(r.$async=!0),!0===this.opts.code.source&&(r.source={validateName:m,validateCode:t,scopeValues:p._values}),this.opts.unevaluated){const{props:t,items:n}=f;r.evaluated={props:t instanceof e.Name?void 0:t,items:n instanceof e.Name?void 0:n,dynamicProps:t instanceof e.Name,dynamicItems:n instanceof e.Name},r.source&&(r.source.evaluated=(0,e.stringify)(r.evaluated))}return s.validate=r,s}catch(e){throw delete s.validate,delete s.validateName,g&&this.logger.error("Error compiling schema, function code:",g),e}finally{this._compilations.delete(s)}}function c(e){return(0,r.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:i.call(this,e)}function d(e){for(const t of this._compilations)if(u(t,e))return t}function u(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function l(e,t){let n;for(;"string"==typeof(n=this.refs[t]);)t=n;return n||this.schemas[t]||p.call(this,e,t)}function p(e,t){const n=this.opts.uriResolver.parse(t),s=(0,r._getFullPath)(this.opts.uriResolver,n);let o=(0,r.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&s===o)return m.call(this,n,e);const c=(0,r.normalizeId)(s),d=this.refs[c]||this.schemas[c];if("string"==typeof d){const t=p.call(this,e,d);if("object"!=typeof(null==t?void 0:t.schema))return;return m.call(this,n,t)}if("object"==typeof(null==d?void 0:d.schema)){if(d.validate||i.call(this,d),c===(0,r.normalizeId)(t)){const{schema:t}=d,{schemaId:n}=this.opts,s=t[n];return s&&(o=(0,r.resolveUrl)(this.opts.uriResolver,o,s)),new a({schema:t,schemaId:n,root:e,baseId:o})}return m.call(this,n,d)}}Sp.SchemaEnv=a,Sp.compileSchema=i,Sp.resolveRef=function(e,t,n){var s;n=(0,r.resolveUrl)(this.opts.uriResolver,t,n);const o=e.refs[n];if(o)return o;let i=l.call(this,e,n);if(void 0===i){const r=null===(s=e.localRefs)||void 0===s?void 0:s[n],{schemaId:o}=this.opts;r&&(i=new a({schema:r,schemaId:o,root:e,baseId:t}))}return void 0!==i?e.refs[n]=c.call(this,i):void 0},Sp.getCompilingSchema=d,Sp.resolveSchema=p;const h=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function m(e,{baseId:t,schema:n,root:o}){var i;if("/"!==(null===(i=e.fragment)||void 0===i?void 0:i[0]))return;for(const o of e.fragment.slice(1).split("/")){if("boolean"==typeof n)return;const e=n[(0,s.unescapeFragment)(o)];if(void 0===e)return;const a="object"==typeof(n=e)&&n[this.opts.schemaId];!h.has(o)&&a&&(t=(0,r.resolveUrl)(this.opts.uriResolver,t,a))}let c;if("boolean"!=typeof n&&n.$ref&&!(0,s.schemaHasRulesButRef)(n,this.RULES)){const e=(0,r.resolveUrl)(this.opts.uriResolver,t,n.$ref);c=p.call(this,o,e)}const{schemaId:d}=this.opts;return c=c||new a({schema:n,schemaId:d,root:o,baseId:t}),c.schema!==c.root.schema?c:void 0}return Sp}var Op,xp,Np,Ip,Rp,Pp,Cp,jp={$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},zp={},Ap={exports:{}};function Mp(){if(xp)return Op;xp=1;const e=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),t=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function n(e){let t="",n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),48!==n){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[r]}return t}const r=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function s(e){return e.length=0,!0}function o(e,t,r){if(e.length){const s=n(e);if(""===s)return r.error=!0,!1;t.push(s),e.length=0}return!0}function a(e){if(function(e){let t=0;for(let n=0;n<e.length;n++)":"===e[n]&&t++;return t}(e)<2)return{host:e,isIPV6:!1};const t=function(e){let t=0;const r={error:!1,address:"",zone:""},a=[],i=[];let c=!1,d=!1,u=o;for(let n=0;n<e.length;n++){const o=e[n];if("["!==o&&"]"!==o)if(":"!==o)if("%"===o){if(!u(i,a,r))break;u=s}else i.push(o);else{if(!0===c&&(d=!0),!u(i,a,r))break;if(++t>7){r.error=!0;break}n>0&&":"===e[n-1]&&(c=!0),a.push(":")}}return i.length&&(u===s?r.zone=i.join(""):d?a.push(i.join("")):a.push(n(i))),r.address=a.join(""),r}(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,n=t.address;return t.zone&&(e+="%"+t.zone,n+="%25"+t.zone),{host:e,isIPV6:!0,escapedHost:n}}}return Op={nonSimpleDomain:r,recomposeAuthority:function(e){const n=[];if(void 0!==e.userinfo&&(n.push(e.userinfo),n.push("@")),void 0!==e.host){let r=unescape(e.host);if(!t(r)){const t=a(r);r=!0===t.isIPV6?`[${t.escapedHost}]`:e.host}n.push(r)}return"number"!=typeof e.port&&"string"!=typeof e.port||(n.push(":"),n.push(String(e.port))),n.length?n.join(""):void 0},normalizeComponentEncoding:function(e,t){const n=!0!==t?escape:unescape;return void 0!==e.scheme&&(e.scheme=n(e.scheme)),void 0!==e.userinfo&&(e.userinfo=n(e.userinfo)),void 0!==e.host&&(e.host=n(e.host)),void 0!==e.path&&(e.path=n(e.path)),void 0!==e.query&&(e.query=n(e.query)),void 0!==e.fragment&&(e.fragment=n(e.fragment)),e},removeDotSegments:function(e){let t=e;const n=[];let r=-1,s=0;for(;s=t.length;){if(1===s){if("."===t)break;if("/"===t){n.push("/");break}n.push(t);break}if(2===s){if("."===t[0]){if("."===t[1])break;if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&("."===t[1]||"/"===t[1])){n.push("/");break}}else if(3===s&&"/.."===t){0!==n.length&&n.pop(),n.push("/");break}if("."===t[0]){if("."===t[1]){if("/"===t[2]){t=t.slice(3);continue}}else if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&"."===t[1]){if("/"===t[2]){t=t.slice(2);continue}if("."===t[2]&&"/"===t[3]){t=t.slice(3),0!==n.length&&n.pop();continue}}if(-1===(r=t.indexOf("/",1))){n.push(t);break}n.push(t.slice(0,r)),t=t.slice(r)}return n.join("")},isIPv4:t,isUUID:e,normalizeIPv6:a,stringArrayToHexStripped:n},Op}function Dp(){return Cp||(Cp=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=yp();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=Cl();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});const r=wp(),s=Ep(),o=Jl(),a=Tp(),i=Cl(),c=gp(),d=Xl(),u=Al(),l=jp,p=function(){if(Pp)return zp;Pp=1,Object.defineProperty(zp,"__esModule",{value:!0});const e=function(){if(Rp)return Ap.exports;Rp=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:n,normalizeComponentEncoding:r,isIPv4:s,nonSimpleDomain:o}=Mp(),{SCHEMES:a,getSchemeHandler:i}=function(){if(Ip)return Np;Ip=1;const{isUUID:e}=Mp(),t=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,n=["http","https","ws","wss","urn","urn:uuid"];function r(e){return!0===e.secure||!1!==e.secure&&!!e.scheme&&!(3!==e.scheme.length||"w"!==e.scheme[0]&&"W"!==e.scheme[0]||"s"!==e.scheme[1]&&"S"!==e.scheme[1]||"s"!==e.scheme[2]&&"S"!==e.scheme[2])}function s(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function o(e){const t="https"===String(e.scheme).toLowerCase();return e.port!==(t?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}const a={scheme:"http",domainHost:!0,parse:s,serialize:o},i={scheme:"ws",domainHost:!0,parse:function(e){return e.secure=r(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e},serialize:function(e){if(e.port!==(r(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){const[t,n]=e.resourceName.split("?");e.path=t&&"/"!==t?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}},c={http:a,https:{scheme:"https",domainHost:a.domainHost,parse:s,serialize:o},ws:i,wss:{scheme:"wss",domainHost:i.domainHost,parse:i.parse,serialize:i.serialize},urn:{scheme:"urn",parse:function(e,n){if(!e.path)return e.error="URN can not be parsed",e;const r=e.path.match(t);if(r){const t=n.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];const s=d(`${t}:${n.nid||e.nid}`);e.path=void 0,s&&(e=s.parse(e,n))}else e.error=e.error||"URN can not be parsed.";return e},serialize:function(e,t){if(void 0===e.nid)throw new Error("URN without nid cannot be serialized");const n=t.scheme||e.scheme||"urn",r=e.nid.toLowerCase(),s=d(`${n}:${t.nid||r}`);s&&(e=s.serialize(e,t));const o=e,a=e.nss;return o.path=`${r||t.nid}:${a}`,t.skipEscape=!0,o},skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:function(t,n){const r=t;return r.uuid=r.nss,r.nss=void 0,n.tolerant||r.uuid&&e(r.uuid)||(r.error=r.error||"UUID is not valid."),r},serialize:function(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t},skipNormalize:!0}};function d(e){return e&&(c[e]||c[e.toLowerCase()])||void 0}return Object.setPrototypeOf(c,null),Np={wsIsSecure:r,SCHEMES:c,isValidSchemeName:function(e){return-1!==n.indexOf(e)},getSchemeHandler:d}}();function c(e,n,r,s){const o={};return s||(e=l(d(e,r),r),n=l(d(n,r),r)),!(r=r||{}).tolerant&&n.scheme?(o.scheme=n.scheme,o.userinfo=n.userinfo,o.host=n.host,o.port=n.port,o.path=t(n.path||""),o.query=n.query):(void 0!==n.userinfo||void 0!==n.host||void 0!==n.port?(o.userinfo=n.userinfo,o.host=n.host,o.port=n.port,o.path=t(n.path||""),o.query=n.query):(n.path?("/"===n.path[0]?o.path=t(n.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+n.path:o.path=n.path:o.path="/"+n.path,o.path=t(o.path)),o.query=n.query):(o.path=e.path,void 0!==n.query?o.query=n.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=n.fragment,o}function d(e,r){const s={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},o=Object.assign({},r),a=[],c=i(o.scheme||s.scheme);c&&c.serialize&&c.serialize(s,o),void 0!==s.path&&(o.skipEscape?s.path=unescape(s.path):(s.path=escape(s.path),void 0!==s.scheme&&(s.path=s.path.split("%3A").join(":")))),"suffix"!==o.reference&&s.scheme&&a.push(s.scheme,":");const d=n(s);if(void 0!==d&&("suffix"!==o.reference&&a.push("//"),a.push(d),s.path&&"/"!==s.path[0]&&a.push("/")),void 0!==s.path){let e=s.path;o.absolutePath||c&&c.absolutePath||(e=t(e)),void 0===d&&"/"===e[0]&&"/"===e[1]&&(e="/%2F"+e.slice(2)),a.push(e)}return void 0!==s.query&&a.push("?",s.query),void 0!==s.fragment&&a.push("#",s.fragment),a.join("")}const u=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function l(t,n){const r=Object.assign({},n),a={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let c=!1;"suffix"===r.reference&&(t=r.scheme?r.scheme+":"+t:"//"+t);const d=t.match(u);if(d){if(a.scheme=d[1],a.userinfo=d[3],a.host=d[4],a.port=parseInt(d[5],10),a.path=d[6]||"",a.query=d[7],a.fragment=d[8],isNaN(a.port)&&(a.port=d[5]),a.host)if(!1===s(a.host)){const t=e(a.host);a.host=t.host.toLowerCase(),c=t.isIPV6}else c=!0;void 0!==a.scheme||void 0!==a.userinfo||void 0!==a.host||void 0!==a.port||void 0!==a.query||a.path?void 0===a.scheme?a.reference="relative":void 0===a.fragment?a.reference="absolute":a.reference="uri":a.reference="same-document",r.reference&&"suffix"!==r.reference&&r.reference!==a.reference&&(a.error=a.error||"URI is not a "+r.reference+" reference.");const n=i(r.scheme||a.scheme);if(!(r.unicodeSupport||n&&n.unicodeSupport)&&a.host&&(r.domainHost||n&&n.domainHost)&&!1===c&&o(a.host))try{a.host=URL.domainToASCII(a.host.toLowerCase())}catch(e){a.error=a.error||"Host's domain name can not be converted to ASCII: "+e}(!n||n&&!n.skipNormalize)&&(-1!==t.indexOf("%")&&(void 0!==a.scheme&&(a.scheme=unescape(a.scheme)),void 0!==a.host&&(a.host=unescape(a.host))),a.path&&(a.path=escape(unescape(a.path))),a.fragment&&(a.fragment=encodeURI(decodeURIComponent(a.fragment)))),n&&n.parse&&n.parse(a,r)}else a.error=a.error||"URI can not be parsed.";return a}const p={SCHEMES:a,normalize:function(e,t){return"string"==typeof e?e=d(l(e,t),t):"object"==typeof e&&(e=l(d(e,t),t)),e},resolve:function(e,t,n){const r=n?Object.assign({scheme:"null"},n):{scheme:"null"},s=c(l(e,r),l(t,r),r,!0);return r.skipEscape=!0,d(s,r)},resolveComponent:c,equal:function(e,t,n){return"string"==typeof e?(e=unescape(e),e=d(r(l(e,n),!0),{...n,skipEscape:!0})):"object"==typeof e&&(e=d(r(e,!0),{...n,skipEscape:!0})),"string"==typeof t?(t=unescape(t),t=d(r(l(t,n),!0),{...n,skipEscape:!0})):"object"==typeof t&&(t=d(r(t,!0),{...n,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()},serialize:d,parse:l};return Ap.exports=p,Ap.exports.default=p,Ap.exports.fastUri=p,Ap.exports}();return e.code='require("ajv/dist/runtime/uri").default',zp.default=e,zp}(),h=(e,t)=>new RegExp(e,t);h.code="new RegExp";const m=["removeAdditional","useDefaults","coerceTypes"],f=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),g={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},y={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};function _(e){var t,n,r,s,o,a,i,c,d,u,l,m,f,g,y,_,v,w,b,k,E,$,S,T,O;const x=e.strict,N=null===(t=e.code)||void 0===t?void 0:t.optimize,I=!0===N||void 0===N?1:N||0,R=null!==(r=null===(n=e.code)||void 0===n?void 0:n.regExp)&&void 0!==r?r:h,P=null!==(s=e.uriResolver)&&void 0!==s?s:p.default;return{strictSchema:null===(a=null!==(o=e.strictSchema)&&void 0!==o?o:x)||void 0===a||a,strictNumbers:null===(c=null!==(i=e.strictNumbers)&&void 0!==i?i:x)||void 0===c||c,strictTypes:null!==(u=null!==(d=e.strictTypes)&&void 0!==d?d:x)&&void 0!==u?u:"log",strictTuples:null!==(m=null!==(l=e.strictTuples)&&void 0!==l?l:x)&&void 0!==m?m:"log",strictRequired:null!==(g=null!==(f=e.strictRequired)&&void 0!==f?f:x)&&void 0!==g&&g,code:e.code?{...e.code,optimize:I,regExp:R}:{optimize:I,regExp:R},loopRequired:null!==(y=e.loopRequired)&&void 0!==y?y:200,loopEnum:null!==(_=e.loopEnum)&&void 0!==_?_:200,meta:null===(v=e.meta)||void 0===v||v,messages:null===(w=e.messages)||void 0===w||w,inlineRefs:null===(b=e.inlineRefs)||void 0===b||b,schemaId:null!==(k=e.schemaId)&&void 0!==k?k:"$id",addUsedSchema:null===(E=e.addUsedSchema)||void 0===E||E,validateSchema:null===($=e.validateSchema)||void 0===$||$,validateFormats:null===(S=e.validateFormats)||void 0===S||S,unicodeRegExp:null===(T=e.unicodeRegExp)||void 0===T||T,int32range:null===(O=e.int32range)||void 0===O||O,uriResolver:P}}class v{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,..._(e)};const{es5:t,lines:n}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:f,es5:t,lines:n}),this.logger=function(e){if(!1===e)return T;if(void 0===e)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}(e.logger);const r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,o.getRules)(),w.call(this,g,e,"NOT SUPPORTED"),w.call(this,y,e,"DEPRECATED","warn"),this._metaOpts=S.call(this),e.formats&&E.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&$.call(this,e.keywords),"object"==typeof e.meta&&this.addMetaSchema(e.meta),k.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:e,meta:t,schemaId:n}=this.opts;let r=l;"id"===n&&(r={...l},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){const{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta="object"==typeof e?e[t]||e:void 0}validate(e,t){let n;if("string"==typeof e){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);const r=n(t);return"$async"in n||(this.errors=n.errors),r}compile(e,t){const n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if("function"!=typeof this.opts.loadSchema)throw new Error("options.loadSchema should be a function");const{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await o.call(this,e.$schema);const n=this._addSchema(e,t);return n.validate||a.call(this,n)}async function o(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function a(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof s.default))throw t;return i.call(this,t),await c.call(this,t.missingSchema),a.call(this,e)}}function i({missingSchema:e,missingRef:t}){if(this.refs[e])throw new Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){const n=await d.call(this,e);this.refs[e]||await o.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function d(e){const t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(const t of e)this.addSchema(t,void 0,n,r);return this}let s;if("object"==typeof e){const{schemaId:t}=this.opts;if(s=e[t],void 0!==s&&"string"!=typeof s)throw new Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||s),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if("boolean"==typeof e)return!0;let n;if(n=e.$schema,void 0!==n&&"string"!=typeof n)throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const r=this.validate(n,e);if(!r&&t){const e="schema is invalid: "+this.errorsText();if("log"!==this.opts.validateSchema)throw new Error(e);this.logger.error(e)}return r}getSchema(e){let t;for(;"string"==typeof(t=b.call(this,e));)e=t;if(void 0===t){const{schemaId:n}=this.opts,r=new a.SchemaEnv({schema:{},schemaId:n});if(t=a.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const t=b.call(this,e);return"object"==typeof t&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{const t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(const t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if("string"==typeof e)n=e,"object"==typeof t&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=n);else{if("object"!=typeof e||void 0!==t)throw new Error("invalid addKeywords parameters");if(n=(t=e).keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}if(x.call(this,n,t),!t)return(0,u.eachItem)(n,e=>N.call(this,e)),this;R.call(this,t);const r={...t,type:(0,d.getJSONTypes)(t.type),schemaType:(0,d.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,0===r.type.length?e=>N.call(this,e,r):e=>r.type.forEach(t=>N.call(this,e,r,t))),this}getKeyword(e){const t=this.RULES.all[e];return"object"==typeof t?t.definition:!!t}removeKeyword(e){const{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(const n of t.rules){const t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return"string"==typeof t&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:n="data"}={}){return e&&0!==e.length?e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n):"No errors"}$dataMetaSchema(e,t){const n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(const r of t){const t=r.split("/").slice(1);let s=e;for(const e of t)s=s[e];for(const e in n){const t=n[e];if("object"!=typeof t)continue;const{$data:r}=t.definition,o=s[e];r&&o&&(s[e]=C(o))}}return e}_removeAllSchemas(e,t){for(const n in e){const r=e[n];t&&!t.test(n)||("string"==typeof r?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,s=this.opts.addUsedSchema){let o;const{schemaId:i}=this.opts;if("object"==typeof e)o=e[i];else{if(this.opts.jtd)throw new Error("schema must be object");if("boolean"!=typeof e)throw new Error("schema must be object or boolean")}let d=this._cache.get(e);if(void 0!==d)return d;n=(0,c.normalizeId)(o||n);const u=c.getSchemaRefs.call(this,e,n);return d=new a.SchemaEnv({schema:e,schemaId:i,meta:t,baseId:n,localRefs:u}),this._cache.set(d.schema,d),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=d),r&&this.validateSchema(e,!0),d}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):a.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){const t=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,e)}finally{this.opts=t}}}function w(e,t,n,r="error"){for(const s in e){const o=s;o in t&&this.logger[r](`${n}: option ${s}. ${e[o]}`)}}function b(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function k(){const e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(const t in e)this.addSchema(e[t],t)}function E(){for(const e in this.opts.formats){const t=this.opts.formats[e];t&&this.addFormat(e,t)}}function $(e){if(Array.isArray(e))this.addVocabulary(e);else{this.logger.warn("keywords option as map is deprecated, pass array");for(const t in e){const n=e[t];n.keyword||(n.keyword=t),this.addKeyword(n)}}}function S(){const e={...this.opts};for(const t of m)delete e[t];return e}v.ValidationError=r.default,v.MissingRefError=s.default,e.default=v;const T={log(){},warn(){},error(){}},O=/^[a-z_$][a-z0-9_$:-]*$/i;function x(e,t){const{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw new Error(`Keyword ${e} is already defined`);if(!O.test(e))throw new Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!("code"in t)&&!("validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function N(e,t,n){var r;const s=null==t?void 0:t.post;if(n&&s)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:o}=this;let a=s?o.post:o.rules.find(({type:e})=>e===n);if(a||(a={type:n,rules:[]},o.rules.push(a)),o.keywords[e]=!0,!t)return;const i={keyword:e,definition:{...t,type:(0,d.getJSONTypes)(t.type),schemaType:(0,d.getJSONTypes)(t.schemaType)}};t.before?I.call(this,a,i,t.before):a.rules.push(i),o.all[e]=i,null===(r=t.implements)||void 0===r||r.forEach(e=>this.addKeyword(e))}function I(e,t,n){const r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function R(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=C(t)),e.validateSchema=this.compile(t,!0))}const P={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function C(e){return{anyOf:[e,P]}}}(kl)),kl}var Lp,Zp,Fp,Up={},qp={},Hp={},Vp={};var Jp,Kp,Bp,Wp,Gp={},Xp={},Yp={},Qp={},eh={};var th,nh,rh,sh={},oh={},ah={};var ih,ch,dh,uh={},lh={},ph={};function hh(){if(ch)return ph;ch=1,Object.defineProperty(ph,"__esModule",{value:!0});const e=up();return e.code='require("ajv/dist/runtime/equal").default',ph.default=e,ph}function mh(){if(dh)return lh;dh=1,Object.defineProperty(lh,"__esModule",{value:!0});const e=Xl(),t=Cl(),n=Al(),r=hh(),s={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:n}})=>t.str`must NOT have duplicate items (items ## ${n} and ${e} are identical)`,params:({params:{i:e,j:n}})=>t._`{i: ${e}, j: ${n}}`},code(s){const{gen:o,data:a,$data:i,schema:c,parentSchema:d,schemaCode:u,it:l}=s;if(!i&&!c)return;const p=o.let("valid"),h=d.items?(0,e.getSchemaTypes)(d.items):[];function m(n,r){const i=o.name("item"),c=(0,e.checkDataTypes)(h,i,l.opts.strictNumbers,e.DataType.Wrong),d=o.const("indices",t._`{}`);o.for(t._`;${n}--;`,()=>{o.let(i,t._`${a}[${n}]`),o.if(c,t._`continue`),h.length>1&&o.if(t._`typeof ${i} == "string"`,t._`${i} += "_"`),o.if(t._`typeof ${d}[${i}] == "number"`,()=>{o.assign(r,t._`${d}[${i}]`),s.error(),o.assign(p,!1).break()}).code(t._`${d}[${i}] = ${n}`)})}function f(e,i){const c=(0,n.useFunc)(o,r.default),d=o.name("outer");o.label(d).for(t._`;${e}--;`,()=>o.for(t._`${i} = ${e}; ${i}--;`,()=>o.if(t._`${c}(${a}[${e}], ${a}[${i}])`,()=>{s.error(),o.assign(p,!1).break(d)})))}s.block$data(p,function(){const e=o.let("i",t._`${a}.length`),n=o.let("j");s.setParams({i:e,j:n}),o.assign(p,!0),o.if(t._`${e} > 1`,()=>(h.length>0&&!h.some(e=>"object"===e||"array"===e)?m:f)(e,n))},t._`${u} === false`),s.ok(p)}};return lh.default=s,lh}var fh,gh,yh,_h={},vh={};function wh(){if(yh)return Gp;yh=1,Object.defineProperty(Gp,"__esModule",{value:!0});const e=function(){if(Jp)return Xp;Jp=1,Object.defineProperty(Xp,"__esModule",{value:!0});const e=Cl(),t=e.operators,n={maximum:{okStr:"<=",ok:t.LTE,fail:t.GT},minimum:{okStr:">=",ok:t.GTE,fail:t.LT},exclusiveMaximum:{okStr:"<",ok:t.LT,fail:t.GTE},exclusiveMinimum:{okStr:">",ok:t.GT,fail:t.LTE}},r={message:({keyword:t,schemaCode:r})=>e.str`must be ${n[t].okStr} ${r}`,params:({keyword:t,schemaCode:r})=>e._`{comparison: ${n[t].okStr}, limit: ${r}}`},s={keyword:Object.keys(n),type:"number",schemaType:"number",$data:!0,error:r,code(t){const{keyword:r,data:s,schemaCode:o}=t;t.fail$data(e._`${s} ${n[r].fail} ${o} || isNaN(${s})`)}};return Xp.default=s,Xp}(),t=function(){if(Kp)return Yp;Kp=1,Object.defineProperty(Yp,"__esModule",{value:!0});const e=Cl(),t={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:t})=>e.str`must be multiple of ${t}`,params:({schemaCode:t})=>e._`{multipleOf: ${t}}`},code(t){const{gen:n,data:r,schemaCode:s,it:o}=t,a=o.opts.multipleOfPrecision,i=n.let("res"),c=a?e._`Math.abs(Math.round(${i}) - ${i}) > 1e-${a}`:e._`${i} !== parseInt(${i})`;t.fail$data(e._`(${s} === 0 || (${i} = ${r}/${s}, ${c}))`)}};return Yp.default=t,Yp}(),n=function(){if(Wp)return Qp;Wp=1,Object.defineProperty(Qp,"__esModule",{value:!0});const e=Cl(),t=Al(),n=function(){if(Bp)return eh;function e(e){const t=e.length;let n,r=0,s=0;for(;s<t;)r++,n=e.charCodeAt(s++),n>=55296&&n<=56319&&s<t&&(n=e.charCodeAt(s),56320==(64512&n)&&s++);return r}return Bp=1,Object.defineProperty(eh,"__esModule",{value:!0}),eh.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',eh}(),r={message({keyword:t,schemaCode:n}){const r="maxLength"===t?"more":"fewer";return e.str`must NOT have ${r} than ${n} characters`},params:({schemaCode:t})=>e._`{limit: ${t}}`},s={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:r,code(r){const{keyword:s,data:o,schemaCode:a,it:i}=r,c="maxLength"===s?e.operators.GT:e.operators.LT,d=!1===i.opts.unicode?e._`${o}.length`:e._`${(0,t.useFunc)(r.gen,n.default)}(${o})`;r.fail$data(e._`${d} ${c} ${a}`)}};return Qp.default=s,Qp}(),r=function(){if(th)return sh;th=1,Object.defineProperty(sh,"__esModule",{value:!0});const e=sp(),t=Cl(),n={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>t.str`must match pattern "${e}"`,params:({schemaCode:e})=>t._`{pattern: ${e}}`},code(n){const{data:r,$data:s,schema:o,schemaCode:a,it:i}=n,c=i.opts.unicodeRegExp?"u":"",d=s?t._`(new RegExp(${a}, ${c}))`:(0,e.usePattern)(n,o);n.fail$data(t._`!${d}.test(${r})`)}};return sh.default=n,sh}(),s=function(){if(nh)return oh;nh=1,Object.defineProperty(oh,"__esModule",{value:!0});const e=Cl(),t={message({keyword:t,schemaCode:n}){const r="maxProperties"===t?"more":"fewer";return e.str`must NOT have ${r} than ${n} properties`},params:({schemaCode:t})=>e._`{limit: ${t}}`},n={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:t,code(t){const{keyword:n,data:r,schemaCode:s}=t,o="maxProperties"===n?e.operators.GT:e.operators.LT;t.fail$data(e._`Object.keys(${r}).length ${o} ${s}`)}};return oh.default=n,oh}(),o=function(){if(rh)return ah;rh=1,Object.defineProperty(ah,"__esModule",{value:!0});const e=sp(),t=Cl(),n=Al(),r={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>t.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>t._`{missingProperty: ${e}}`},code(r){const{gen:s,schema:o,schemaCode:a,data:i,$data:c,it:d}=r,{opts:u}=d;if(!c&&0===o.length)return;const l=o.length>=u.loopRequired;if(d.allErrors?function(){if(l||c)r.block$data(t.nil,p);else for(const t of o)(0,e.checkReportMissingProp)(r,t)}():function(){const n=s.let("missing");if(l||c){const o=s.let("valid",!0);r.block$data(o,()=>function(n,o){r.setParams({missingProperty:n}),s.forOf(n,a,()=>{s.assign(o,(0,e.propertyInData)(s,i,n,u.ownProperties)),s.if((0,t.not)(o),()=>{r.error(),s.break()})},t.nil)}(n,o)),r.ok(o)}else s.if((0,e.checkMissingProp)(r,o,n)),(0,e.reportMissingProp)(r,n),s.else()}(),u.strictRequired){const e=r.parentSchema.properties,{definedProperties:t}=r.it;for(const r of o)if(void 0===(null==e?void 0:e[r])&&!t.has(r)){const e=`required property "${r}" is not defined at "${d.schemaEnv.baseId+d.errSchemaPath}" (strictRequired)`;(0,n.checkStrictMode)(d,e,d.opts.strictRequired)}}function p(){s.forOf("prop",a,t=>{r.setParams({missingProperty:t}),s.if((0,e.noPropertyInData)(s,i,t,u.ownProperties),()=>r.error())})}}};return ah.default=r,ah}(),a=function(){if(ih)return uh;ih=1,Object.defineProperty(uh,"__esModule",{value:!0});const e=Cl(),t={message({keyword:t,schemaCode:n}){const r="maxItems"===t?"more":"fewer";return e.str`must NOT have ${r} than ${n} items`},params:({schemaCode:t})=>e._`{limit: ${t}}`},n={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:t,code(t){const{keyword:n,data:r,schemaCode:s}=t,o="maxItems"===n?e.operators.GT:e.operators.LT;t.fail$data(e._`${r}.length ${o} ${s}`)}};return uh.default=n,uh}(),i=mh(),c=function(){if(fh)return _h;fh=1,Object.defineProperty(_h,"__esModule",{value:!0});const e=Cl(),t=Al(),n=hh(),r={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:t})=>e._`{allowedValue: ${t}}`},code(r){const{gen:s,data:o,$data:a,schemaCode:i,schema:c}=r;a||c&&"object"==typeof c?r.fail$data(e._`!${(0,t.useFunc)(s,n.default)}(${o}, ${i})`):r.fail(e._`${c} !== ${o}`)}};return _h.default=r,_h}(),d=function(){if(gh)return vh;gh=1,Object.defineProperty(vh,"__esModule",{value:!0});const e=Cl(),t=Al(),n=hh(),r={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:t})=>e._`{allowedValues: ${t}}`},code(r){const{gen:s,data:o,$data:a,schema:i,schemaCode:c,it:d}=r;if(!a&&0===i.length)throw new Error("enum must have non-empty array");const u=i.length>=d.opts.loopEnum;let l;const p=()=>null!=l?l:l=(0,t.useFunc)(s,n.default);let h;if(u||a)h=s.let("valid"),r.block$data(h,function(){s.assign(h,!1),s.forOf("v",c,t=>s.if(e._`${p()}(${o}, ${t})`,()=>s.assign(h,!0).break()))});else{if(!Array.isArray(i))throw new Error("ajv implementation error");const t=s.const("vSchema",c);h=(0,e.or)(...i.map((n,r)=>function(t,n){const r=i[n];return"object"==typeof r&&null!==r?e._`${p()}(${o}, ${t}[${n}])`:e._`${o} === ${r}`}(t,r)))}r.pass(h)}};return vh.default=r,vh}(),u=[e.default,t.default,n.default,r.default,s.default,o.default,a.default,i.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},c.default,d.default];return Gp.default=u,Gp}var bh,kh={},Eh={};function $h(){if(bh)return Eh;bh=1,Object.defineProperty(Eh,"__esModule",{value:!0}),Eh.validateAdditionalItems=void 0;const e=Cl(),t=Al(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:t}})=>e.str`must NOT have more than ${t} items`,params:({params:{len:t}})=>e._`{limit: ${t}}`},code(e){const{parentSchema:n,it:s}=e,{items:o}=n;Array.isArray(o)?r(e,o):(0,t.checkStrictMode)(s,'"additionalItems" is ignored when "items" is not an array of schemas')}};function r(n,r){const{gen:s,schema:o,data:a,keyword:i,it:c}=n;c.items=!0;const d=s.const("len",e._`${a}.length`);if(!1===o)n.setParams({len:r.length}),n.pass(e._`${d} <= ${r.length}`);else if("object"==typeof o&&!(0,t.alwaysValidSchema)(c,o)){const o=s.var("valid",e._`${d} <= ${r.length}`);s.if((0,e.not)(o),()=>function(o){s.forRange("i",r.length,d,r=>{n.subschema({keyword:i,dataProp:r,dataPropType:t.Type.Num},o),c.allErrors||s.if((0,e.not)(o),()=>s.break())})}(o)),n.ok(o)}}return Eh.validateAdditionalItems=r,Eh.default=n,Eh}var Sh,Th,Oh={},xh={};function Nh(){if(Sh)return xh;Sh=1,Object.defineProperty(xh,"__esModule",{value:!0}),xh.validateTuple=void 0;const e=Cl(),t=Al(),n=sp(),r={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:r,it:o}=e;if(Array.isArray(r))return s(e,"additionalItems",r);o.items=!0,(0,t.alwaysValidSchema)(o,r)||e.ok((0,n.validateArray)(e))}};function s(n,r,s=n.schema){const{gen:o,parentSchema:a,data:i,keyword:c,it:d}=n;!function(e){const{opts:n,errSchemaPath:o}=d,a=s.length,i=a===e.minItems&&(a===e.maxItems||!1===e[r]);if(n.strictTuples&&!i){const e=`"${c}" is ${a}-tuple, but minItems or maxItems/${r} are not specified or different at path "${o}"`;(0,t.checkStrictMode)(d,e,n.strictTuples)}}(a),d.opts.unevaluated&&s.length&&!0!==d.items&&(d.items=t.mergeEvaluated.items(o,s.length,d.items));const u=o.name("valid"),l=o.const("len",e._`${i}.length`);s.forEach((r,s)=>{(0,t.alwaysValidSchema)(d,r)||(o.if(e._`${l} > ${s}`,()=>n.subschema({keyword:c,schemaProp:s,dataProp:s},u)),n.ok(u))})}return xh.validateTuple=s,xh.default=r,xh}var Ih,Rh,Ph={},Ch={};var jh,zh={};var Ah,Mh,Dh={},Lh={};function Zh(){if(Mh)return Lh;Mh=1,Object.defineProperty(Lh,"__esModule",{value:!0});const e=sp(),t=Cl(),n=Fl(),r=Al(),s={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:e})=>t._`{additionalProperty: ${e.additionalProperty}}`},code(s){const{gen:o,schema:a,parentSchema:i,data:c,errsCount:d,it:u}=s;if(!d)throw new Error("ajv implementation error");const{allErrors:l,opts:p}=u;if(u.props=!0,"all"!==p.removeAdditional&&(0,r.alwaysValidSchema)(u,a))return;const h=(0,e.allSchemaProperties)(i.properties),m=(0,e.allSchemaProperties)(i.patternProperties);function f(e){o.code(t._`delete ${c}[${e}]`)}function g(e){if("all"===p.removeAdditional||p.removeAdditional&&!1===a)f(e);else{if(!1===a)return s.setParams({additionalProperty:e}),s.error(),void(l||o.break());if("object"==typeof a&&!(0,r.alwaysValidSchema)(u,a)){const n=o.name("valid");"failing"===p.removeAdditional?(y(e,n,!1),o.if((0,t.not)(n),()=>{s.reset(),f(e)})):(y(e,n),l||o.if((0,t.not)(n),()=>o.break()))}}}function y(e,t,n){const o={keyword:"additionalProperties",dataProp:e,dataPropType:r.Type.Str};!1===n&&Object.assign(o,{compositeRule:!0,createErrors:!1,allErrors:!1}),s.subschema(o,t)}o.forIn("key",c,n=>{h.length||m.length?o.if(function(n){let a;if(h.length>8){const t=(0,r.schemaRefOrVal)(u,i.properties,"properties");a=(0,e.isOwnProperty)(o,t,n)}else a=h.length?(0,t.or)(...h.map(e=>t._`${n} === ${e}`)):t.nil;return m.length&&(a=(0,t.or)(a,...m.map(r=>t._`${(0,e.usePattern)(s,r)}.test(${n})`))),(0,t.not)(a)}(n),()=>g(n)):g(n)}),s.ok(t._`${d} === ${n.default.errors}`)}};return Lh.default=s,Lh}var Fh,Uh,qh,Hh,Vh,Jh,Kh,Bh,Wh,Gh={},Xh={},Yh={},Qh={},em={},tm={},nm={},rm={};function sm(){if(Wh)return kh;Wh=1,Object.defineProperty(kh,"__esModule",{value:!0});const e=$h(),t=function(){if(Th)return Oh;Th=1,Object.defineProperty(Oh,"__esModule",{value:!0});const e=Nh(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,e.validateTuple)(t,"items")};return Oh.default=t,Oh}(),n=Nh(),r=function(){if(Ih)return Ph;Ih=1,Object.defineProperty(Ph,"__esModule",{value:!0});const e=Cl(),t=Al(),n=sp(),r=$h(),s={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:t}})=>e.str`must NOT have more than ${t} items`,params:({params:{len:t}})=>e._`{limit: ${t}}`},code(e){const{schema:s,parentSchema:o,it:a}=e,{prefixItems:i}=o;a.items=!0,(0,t.alwaysValidSchema)(a,s)||(i?(0,r.validateAdditionalItems)(e,i):e.ok((0,n.validateArray)(e)))}};return Ph.default=s,Ph}(),s=function(){if(Rh)return Ch;Rh=1,Object.defineProperty(Ch,"__esModule",{value:!0});const e=Cl(),t=Al(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:t,max:n}})=>void 0===n?e.str`must contain at least ${t} valid item(s)`:e.str`must contain at least ${t} and no more than ${n} valid item(s)`,params:({params:{min:t,max:n}})=>void 0===n?e._`{minContains: ${t}}`:e._`{minContains: ${t}, maxContains: ${n}}`},code(n){const{gen:r,schema:s,parentSchema:o,data:a,it:i}=n;let c,d;const{minContains:u,maxContains:l}=o;i.opts.next?(c=void 0===u?1:u,d=l):c=1;const p=r.const("len",e._`${a}.length`);if(n.setParams({min:c,max:d}),void 0===d&&0===c)return void(0,t.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==d&&c>d)return(0,t.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),void n.fail();if((0,t.alwaysValidSchema)(i,s)){let t=e._`${p} >= ${c}`;return void 0!==d&&(t=e._`${t} && ${p} <= ${d}`),void n.pass(t)}i.items=!0;const h=r.name("valid");function m(){const t=r.name("_valid"),n=r.let("count",0);f(t,()=>r.if(t,()=>function(t){r.code(e._`${t}++`),void 0===d?r.if(e._`${t} >= ${c}`,()=>r.assign(h,!0).break()):(r.if(e._`${t} > ${d}`,()=>r.assign(h,!1).break()),1===c?r.assign(h,!0):r.if(e._`${t} >= ${c}`,()=>r.assign(h,!0)))}(n)))}function f(e,s){r.forRange("i",0,p,r=>{n.subschema({keyword:"contains",dataProp:r,dataPropType:t.Type.Num,compositeRule:!0},e),s()})}void 0===d&&1===c?f(h,()=>r.if(h,()=>r.break())):0===c?(r.let(h,!0),void 0!==d&&r.if(e._`${a}.length > 0`,m)):(r.let(h,!1),m()),n.result(h,()=>n.reset())}};return Ch.default=n,Ch}(),o=(jh||(jh=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Cl(),n=Al(),r=sp();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{const s=1===n?"property":"properties";return t.str`must have ${s} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:s}})=>t._`{property: ${e},
5
+ || ${c} === "boolean" || ${o} === null`).assign(u,r._`[${o}]`)}}s.else(),l(e),s.endIf(),s.if(r._`${u} !== undefined`,()=>{s.assign(o,u),function({gen:e,parentData:t,parentDataProperty:n},s){e.if(r._`${t} !== undefined`,()=>e.assign(r._`${t}[${n}]`,s))}(e,u)})}(e,n,u):l(e)})}return p};const i=new Set(["string","number","integer","boolean","null"]);function c(e,t,n,s=o.Correct){const a=s===o.Correct?r.operators.EQ:r.operators.NEQ;let i;switch(e){case"null":return r._`${t} ${a} null`;case"array":i=r._`Array.isArray(${t})`;break;case"object":i=r._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=c(r._`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=c();break;default:return r._`typeof ${t} ${a} ${e}`}return s===o.Correct?i:(0,r.not)(i);function c(e=r.nil){return(0,r.and)(r._`typeof ${t} == "number"`,e,n?r._`isFinite(${t})`:r.nil)}}function d(e,t,n,o){if(1===e.length)return c(e[0],t,n,o);let a;const i=(0,s.toHash)(e);if(i.array&&i.object){const e=r._`typeof ${t} != "object"`;a=i.null?e:r._`!${t} || ${e}`,delete i.null,delete i.array,delete i.object}else a=r.nil;i.number&&delete i.integer;for(const e in i)a=(0,r.and)(a,c(e,t,n,o));return a}Hl.checkDataType=c,Hl.checkDataTypes=d;const u={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?r._`{type: ${e}}`:r._`{type: ${t}}`};function l(e){const t=function(e){const{gen:t,data:n,schema:r}=e,o=(0,s.schemaRefOrVal)(e,r,"type");return{gen:t,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:e}}(e);(0,n.reportError)(t,u)}return Hl.reportTypeError=l,Hl}var Yl,Ql,ep,tp={},np={},rp={};function sp(){if(Ql)return rp;Ql=1,Object.defineProperty(rp,"__esModule",{value:!0}),rp.validateUnion=rp.validateArray=rp.usePattern=rp.callValidateCode=rp.schemaProperties=rp.allSchemaProperties=rp.noPropertyInData=rp.propertyInData=rp.isOwnProperty=rp.hasPropFunc=rp.reportMissingProp=rp.checkMissingProp=rp.checkReportMissingProp=void 0;const e=Cl(),t=Al(),n=Fl(),r=Al();function s(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:e._`Object.prototype.hasOwnProperty`})}function o(t,n,r){return e._`${s(t)}.call(${n}, ${r})`}function a(t,n,r,s){const a=e._`${n}${(0,e.getProperty)(r)} === undefined`;return s?(0,e.or)(a,(0,e.not)(o(t,n,r))):a}function i(e){return e?Object.keys(e).filter(e=>"__proto__"!==e):[]}rp.checkReportMissingProp=function(t,n){const{gen:r,data:s,it:o}=t;r.if(a(r,s,n,o.opts.ownProperties),()=>{t.setParams({missingProperty:e._`${n}`},!0),t.error()})},rp.checkMissingProp=function({gen:t,data:n,it:{opts:r}},s,o){return(0,e.or)(...s.map(s=>(0,e.and)(a(t,n,s,r.ownProperties),e._`${o} = ${s}`)))},rp.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},rp.hasPropFunc=s,rp.isOwnProperty=o,rp.propertyInData=function(t,n,r,s){const a=e._`${n}${(0,e.getProperty)(r)} !== undefined`;return s?e._`${a} && ${o(t,n,r)}`:a},rp.noPropertyInData=a,rp.allSchemaProperties=i,rp.schemaProperties=function(e,n){return i(n).filter(r=>!(0,t.alwaysValidSchema)(e,n[r]))},rp.callValidateCode=function({schemaCode:t,data:r,it:{gen:s,topSchemaRef:o,schemaPath:a,errorPath:i},it:c},d,u,l){const p=l?e._`${t}, ${r}, ${o}${a}`:r,h=[[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,i)],[n.default.parentData,c.parentData],[n.default.parentDataProperty,c.parentDataProperty],[n.default.rootData,n.default.rootData]];c.opts.dynamicRef&&h.push([n.default.dynamicAnchors,n.default.dynamicAnchors]);const m=e._`${p}, ${s.object(...h)}`;return u!==e.nil?e._`${d}.call(${u}, ${m})`:e._`${d}(${m})`};const c=e._`new RegExp`;return rp.usePattern=function({gen:t,it:{opts:n}},s){const o=n.unicodeRegExp?"u":"",{regExp:a}=n.code,i=a(s,o);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:e._`${"new RegExp"===a.code?c:(0,r.useFunc)(t,a)}(${s}, ${o})`})},rp.validateArray=function(n){const{gen:r,data:s,keyword:o,it:a}=n,i=r.name("valid");if(a.allErrors){const e=r.let("valid",!0);return c(()=>r.assign(e,!1)),e}return r.var(i,!0),c(()=>r.break()),i;function c(a){const c=r.const("len",e._`${s}.length`);r.forRange("i",0,c,s=>{n.subschema({keyword:o,dataProp:s,dataPropType:t.Type.Num},i),r.if((0,e.not)(i),a)})}},rp.validateUnion=function(n){const{gen:r,schema:s,keyword:o,it:a}=n;if(!Array.isArray(s))throw new Error("ajv implementation error");if(s.some(e=>(0,t.alwaysValidSchema)(a,e))&&!a.opts.unevaluated)return;const i=r.let("valid",!1),c=r.name("_valid");r.block(()=>s.forEach((t,s)=>{const a=n.subschema({keyword:o,schemaProp:s,compositeRule:!0},c);r.assign(i,e._`${i} || ${c}`),n.mergeValidEvaluated(a,c)||r.if((0,e.not)(i))})),n.result(i,()=>n.reset(),()=>n.error(!0))},rp}var op,ap,ip,cp={},dp={};function up(){return ip||(ip=1,ap=function e(t,n){if(t===n)return!0;if(t&&n&&"object"==typeof t&&"object"==typeof n){if(t.constructor!==n.constructor)return!1;var r,s,o;if(Array.isArray(t)){if((r=t.length)!=n.length)return!1;for(s=r;0!==s--;)if(!e(t[s],n[s]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if((r=(o=Object.keys(t)).length)!==Object.keys(n).length)return!1;for(s=r;0!==s--;)if(!Object.prototype.hasOwnProperty.call(n,o[s]))return!1;for(s=r;0!==s--;){var a=o[s];if(!e(t[a],n[a]))return!1}return!0}return t!=t&&n!=n}),ap}var lp,pp,hp,mp={exports:{}};function fp(){if(lp)return mp.exports;lp=1;var e=mp.exports=function(e,n,r){"function"==typeof n&&(r=n,n={}),t(n,"function"==typeof(r=n.cb||r)?r:r.pre||function(){},r.post||function(){},e,"",e)};function t(r,s,o,a,i,c,d,u,l,p){if(a&&"object"==typeof a&&!Array.isArray(a)){for(var h in s(a,i,c,d,u,l,p),a){var m=a[h];if(Array.isArray(m)){if(h in e.arrayKeywords)for(var f=0;f<m.length;f++)t(r,s,o,m[f],i+"/"+h+"/"+f,c,i,h,a,f)}else if(h in e.propsKeywords){if(m&&"object"==typeof m)for(var g in m)t(r,s,o,m[g],i+"/"+h+"/"+n(g),c,i,h,a,g)}else(h in e.keywords||r.allKeys&&!(h in e.skipKeywords))&&t(r,s,o,m,i+"/"+h,c,i,h,a)}o(a,i,c,d,u,l,p)}}function n(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}return e.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},e.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},e.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},e.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},mp.exports}function gp(){if(pp)return dp;pp=1,Object.defineProperty(dp,"__esModule",{value:!0}),dp.getSchemaRefs=dp.resolveUrl=dp.normalizeId=dp._getFullPath=dp.getFullPath=dp.inlineRef=void 0;const e=Al(),t=up(),n=fp(),r=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);dp.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!o(e):!!t&&a(e)<=t)};const s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function o(e){for(const t in e){if(s.has(t))return!0;const n=e[t];if(Array.isArray(n)&&n.some(o))return!0;if("object"==typeof n&&o(n))return!0}return!1}function a(t){let n=0;for(const s in t){if("$ref"===s)return 1/0;if(n++,!r.has(s)&&("object"==typeof t[s]&&(0,e.eachItem)(t[s],e=>n+=a(e)),n===1/0))return 1/0}return n}function i(e,t="",n){!1!==n&&(t=u(t));const r=e.parse(t);return c(e,r)}function c(e,t){return e.serialize(t).split("#")[0]+"#"}dp.getFullPath=i,dp._getFullPath=c;const d=/#\/?$/;function u(e){return e?e.replace(d,""):""}dp.normalizeId=u,dp.resolveUrl=function(e,t,n){return n=u(n),e.resolve(t,n)};const l=/^[a-z_][-a-z0-9._]*$/i;return dp.getSchemaRefs=function(e,r){if("boolean"==typeof e)return{};const{schemaId:s,uriResolver:o}=this.opts,a=u(e[s]||r),c={"":a},d=i(o,a,!1),p={},h=new Set;return n(e,{allKeys:!0},(e,t,n,r)=>{if(void 0===r)return;const o=d+t;let a=c[r];function i(t){const n=this.opts.uriResolver.resolve;if(t=u(a?n(a,t):t),h.has(t))throw f(t);h.add(t);let r=this.refs[t];return"string"==typeof r&&(r=this.refs[r]),"object"==typeof r?m(e,r.schema,t):t!==u(o)&&("#"===t[0]?(m(e,p[t],t),p[t]=e):this.refs[t]=o),t}function g(e){if("string"==typeof e){if(!l.test(e))throw new Error(`invalid anchor "${e}"`);i.call(this,`#${e}`)}}"string"==typeof e[s]&&(a=i.call(this,e[s])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),c[t]=a}),p;function m(e,n,r){if(void 0!==n&&!t(e,n))throw f(r)}function f(e){return new Error(`reference "${e}" resolves to more than one schema`)}},dp}function yp(){if(hp)return $l;hp=1,Object.defineProperty($l,"__esModule",{value:!0}),$l.getData=$l.KeywordCxt=$l.validateFunctionCode=void 0;const e=function(){if(Ll)return Sl;Ll=1,Object.defineProperty(Sl,"__esModule",{value:!0}),Sl.boolOrEmptySchema=Sl.topBoolOrEmptySchema=void 0;const e=ql(),t=Cl(),n=Fl(),r={message:"boolean schema is false"};function s(t,n){const{gen:s,data:o}=t,a={gen:s,keyword:"false schema",data:o,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,e.reportError)(a,r,void 0,n)}return Sl.topBoolOrEmptySchema=function(e){const{gen:r,schema:o,validateName:a}=e;!1===o?s(e,!1):"object"==typeof o&&!0===o.$async?r.return(n.default.data):(r.assign(t._`${a}.errors`,null),r.return(!0))},Sl.boolOrEmptySchema=function(e,t){const{gen:n,schema:r}=e;!1===r?(n.var(t,!1),s(e)):n.var(t,!0)},Sl}(),t=Xl(),n=Gl(),r=Xl(),s=function(){if(Yl)return tp;Yl=1,Object.defineProperty(tp,"__esModule",{value:!0}),tp.assignDefaults=void 0;const e=Cl(),t=Al();function n(n,r,s){const{gen:o,compositeRule:a,data:i,opts:c}=n;if(void 0===s)return;const d=e._`${i}${(0,e.getProperty)(r)}`;if(a)return void(0,t.checkStrictMode)(n,`default is ignored for: ${d}`);let u=e._`${d} === undefined`;"empty"===c.useDefaults&&(u=e._`${u} || ${d} === null || ${d} === ""`),o.if(u,e._`${d} = ${(0,e.stringify)(s)}`)}return tp.assignDefaults=function(e,t){const{properties:r,items:s}=e.schema;if("object"===t&&r)for(const t in r)n(e,t,r[t].default);else"array"===t&&Array.isArray(s)&&s.forEach((t,r)=>n(e,r,t.default))},tp}(),o=function(){if(ep)return np;ep=1,Object.defineProperty(np,"__esModule",{value:!0}),np.validateKeywordUsage=np.validSchemaType=np.funcKeywordCode=np.macroKeywordCode=void 0;const e=Cl(),t=Fl(),n=sp(),r=ql();function s(t){const{gen:n,data:r,it:s}=t;n.if(s.parentData,()=>n.assign(r,e._`${s.parentData}[${s.parentDataProperty}]`))}function o(t,n,r){if(void 0===r)throw new Error(`keyword "${n}" failed to compile`);return t.scopeValue("keyword","function"==typeof r?{ref:r}:{ref:r,code:(0,e.stringify)(r)})}return np.macroKeywordCode=function(t,n){const{gen:r,keyword:s,schema:a,parentSchema:i,it:c}=t,d=n.macro.call(c.self,a,i,c),u=o(r,s,d);!1!==c.opts.validateSchema&&c.self.validateSchema(d,!0);const l=r.name("valid");t.subschema({schema:d,schemaPath:e.nil,errSchemaPath:`${c.errSchemaPath}/${s}`,topSchemaRef:u,compositeRule:!0},l),t.pass(l,()=>t.error(!0))},np.funcKeywordCode=function(a,i){var c;const{gen:d,keyword:u,schema:l,parentSchema:p,$data:h,it:m}=a;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(m,i);const f=!h&&i.compile?i.compile.call(m.self,l,p,m):i.validate,g=o(d,u,f),y=d.let("valid");function _(r=(i.async?e._`await `:e.nil)){const s=m.opts.passContext?t.default.this:t.default.self,o=!("compile"in i&&!h||!1===i.schema);d.assign(y,e._`${r}${(0,n.callValidateCode)(a,g,s,o)}`,i.modifying)}function v(t){var n;d.if((0,e.not)(null!==(n=i.valid)&&void 0!==n?n:y),t)}a.block$data(y,function(){if(!1===i.errors)_(),i.modifying&&s(a),v(()=>a.error());else{const n=i.async?function(){const t=d.let("ruleErrs",null);return d.try(()=>_(e._`await `),n=>d.assign(y,!1).if(e._`${n} instanceof ${m.ValidationError}`,()=>d.assign(t,e._`${n}.errors`),()=>d.throw(n))),t}():function(){const t=e._`${g}.errors`;return d.assign(t,null),_(e.nil),t}();i.modifying&&s(a),v(()=>function(n,s){const{gen:o}=n;o.if(e._`Array.isArray(${s})`,()=>{o.assign(t.default.vErrors,e._`${t.default.vErrors} === null ? ${s} : ${t.default.vErrors}.concat(${s})`).assign(t.default.errors,e._`${t.default.vErrors}.length`),(0,r.extendErrors)(n)},()=>n.error())}(a,n))}}),a.ok(null!==(c=i.valid)&&void 0!==c?c:y)},np.validSchemaType=function(e,t,n=!1){return!t.length||t.some(t=>"array"===t?Array.isArray(e):"object"===t?e&&"object"==typeof e&&!Array.isArray(e):typeof e==t||n&&void 0===e)},np.validateKeywordUsage=function({schema:e,opts:t,self:n,errSchemaPath:r},s,o){if(Array.isArray(s.keyword)?!s.keyword.includes(o):s.keyword!==o)throw new Error("ajv implementation error");const a=s.dependencies;if(null==a?void 0:a.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw new Error(`parent schema must have dependencies of ${o}: ${a.join(",")}`);if(s.validateSchema&&!s.validateSchema(e[o])){const e=`keyword "${o}" value is invalid at path "${r}": `+n.errorsText(s.validateSchema.errors);if("log"!==t.validateSchema)throw new Error(e);n.logger.error(e)}},np}(),a=function(){if(op)return cp;op=1,Object.defineProperty(cp,"__esModule",{value:!0}),cp.extendSubschemaMode=cp.extendSubschemaData=cp.getSubschema=void 0;const e=Cl(),t=Al();return cp.getSubschema=function(n,{keyword:r,schemaProp:s,schema:o,schemaPath:a,errSchemaPath:i,topSchemaRef:c}){if(void 0!==r&&void 0!==o)throw new Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==r){const o=n.schema[r];return void 0===s?{schema:o,schemaPath:e._`${n.schemaPath}${(0,e.getProperty)(r)}`,errSchemaPath:`${n.errSchemaPath}/${r}`}:{schema:o[s],schemaPath:e._`${n.schemaPath}${(0,e.getProperty)(r)}${(0,e.getProperty)(s)}`,errSchemaPath:`${n.errSchemaPath}/${r}/${(0,t.escapeFragment)(s)}`}}if(void 0!==o){if(void 0===a||void 0===i||void 0===c)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:o,schemaPath:a,topSchemaRef:c,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')},cp.extendSubschemaData=function(n,r,{dataProp:s,dataPropType:o,data:a,dataTypes:i,propertyName:c}){if(void 0!==a&&void 0!==s)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:d}=r;if(void 0!==s){const{errorPath:a,dataPathArr:i,opts:c}=r;u(d.let("data",e._`${r.data}${(0,e.getProperty)(s)}`,!0)),n.errorPath=e.str`${a}${(0,t.getErrorPath)(s,o,c.jsPropertySyntax)}`,n.parentDataProperty=e._`${s}`,n.dataPathArr=[...i,n.parentDataProperty]}function u(e){n.data=e,n.dataLevel=r.dataLevel+1,n.dataTypes=[],r.definedProperties=new Set,n.parentData=r.data,n.dataNames=[...r.dataNames,e]}void 0!==a&&(u(a instanceof e.Name?a:d.let("data",a,!0)),void 0!==c&&(n.propertyName=c)),i&&(n.dataTypes=i)},cp.extendSubschemaMode=function(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:s,allErrors:o}){void 0!==r&&(e.compositeRule=r),void 0!==s&&(e.createErrors=s),void 0!==o&&(e.allErrors=o),e.jtdDiscriminator=t,e.jtdMetadata=n},cp}(),i=Cl(),c=Fl(),d=gp(),u=Al(),l=ql();function p({gen:e,validateName:t,schema:n,schemaEnv:r,opts:s},o){s.code.es5?e.func(t,i._`${c.default.data}, ${c.default.valCxt}`,r.$async,()=>{e.code(i._`"use strict"; ${h(n,s)}`),function(e,t){e.if(c.default.valCxt,()=>{e.var(c.default.instancePath,i._`${c.default.valCxt}.${c.default.instancePath}`),e.var(c.default.parentData,i._`${c.default.valCxt}.${c.default.parentData}`),e.var(c.default.parentDataProperty,i._`${c.default.valCxt}.${c.default.parentDataProperty}`),e.var(c.default.rootData,i._`${c.default.valCxt}.${c.default.rootData}`),t.dynamicRef&&e.var(c.default.dynamicAnchors,i._`${c.default.valCxt}.${c.default.dynamicAnchors}`)},()=>{e.var(c.default.instancePath,i._`""`),e.var(c.default.parentData,i._`undefined`),e.var(c.default.parentDataProperty,i._`undefined`),e.var(c.default.rootData,c.default.data),t.dynamicRef&&e.var(c.default.dynamicAnchors,i._`{}`)})}(e,s),e.code(o)}):e.func(t,i._`${c.default.data}, ${function(e){return i._`{${c.default.instancePath}="", ${c.default.parentData}, ${c.default.parentDataProperty}, ${c.default.rootData}=${c.default.data}${e.dynamicRef?i._`, ${c.default.dynamicAnchors}={}`:i.nil}}={}`}(s)}`,r.$async,()=>e.code(h(n,s)).code(o))}function h(e,t){const n="object"==typeof e&&e[t.schemaId];return n&&(t.code.source||t.code.process)?i._`/*# sourceURL=${n} */`:i.nil}function m({schema:e,self:t}){if("boolean"==typeof e)return!e;for(const n in e)if(t.RULES.all[n])return!0;return!1}function f(e){return"boolean"!=typeof e.schema}function g(e){(0,u.checkUnknownRules)(e),function(e){const{schema:t,errSchemaPath:n,opts:r,self:s}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(t,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}(e)}function y(e,n){if(e.opts.jtd)return v(e,[],!1,n);const r=(0,t.getSchemaTypes)(e.schema);v(e,r,!(0,t.coerceAndCheckDataType)(e,r),n)}function _({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:s}){const o=n.$comment;if(!0===s.$comment)e.code(i._`${c.default.self}.logger.log(${o})`);else if("function"==typeof s.$comment){const n=i.str`${r}/$comment`,s=e.scopeValue("root",{ref:t.root});e.code(i._`${c.default.self}.opts.$comment(${o}, ${n}, ${s}.schema)`)}}function v(e,t,s,o){const{gen:a,schema:d,data:l,allErrors:p,opts:h,self:m}=e,{RULES:f}=m;function g(u){(0,n.shouldUseGroup)(d,u)&&(u.type?(a.if((0,r.checkDataType)(u.type,l,h.strictNumbers)),w(e,u),1===t.length&&t[0]===u.type&&s&&(a.else(),(0,r.reportTypeError)(e)),a.endIf()):w(e,u),p||a.if(i._`${c.default.errors} === ${o||0}`))}!d.$ref||!h.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(d,f)?(h.jtd||function(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(function(e,t){t.length&&(e.dataTypes.length?(t.forEach(t=>{b(e.dataTypes,t)||k(e,`type "${t}" not allowed by context "${e.dataTypes.join(",")}"`)}),function(e,t){const n=[];for(const r of e.dataTypes)b(t,r)?n.push(r):t.includes("integer")&&"number"===r&&n.push("integer");e.dataTypes=n}(e,t)):e.dataTypes=t)}(e,t),e.opts.allowUnionTypes||function(e,t){t.length>1&&(2!==t.length||!t.includes("null"))&&k(e,"use allowUnionTypes to allow union type keyword")}(e,t),function(e,t){const r=e.self.RULES.all;for(const s in r){const o=r[s];if("object"==typeof o&&(0,n.shouldUseRule)(e.schema,o)){const{type:n}=o.definition;n.length&&!n.some(e=>{return r=e,(n=t).includes(r)||"number"===r&&n.includes("integer");var n,r})&&k(e,`missing type "${n.join(",")}" for keyword "${s}"`)}}}(e,e.dataTypes))}(e,t),a.block(()=>{for(const e of f.rules)g(e);g(f.post)})):a.block(()=>S(e,"$ref",f.all.$ref.definition))}function w(e,t){const{gen:r,schema:o,opts:{useDefaults:a}}=e;a&&(0,s.assignDefaults)(e,t.type),r.block(()=>{for(const r of t.rules)(0,n.shouldUseRule)(o,r)&&S(e,r.keyword,r.definition,t.type)})}function b(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function k(e,t){t+=` at "${e.schemaEnv.baseId+e.errSchemaPath}" (strictTypes)`,(0,u.checkStrictMode)(e,t,e.opts.strictTypes)}$l.validateFunctionCode=function(t){f(t)&&(g(t),m(t))?function(e){const{schema:t,opts:n,gen:r}=e;p(e,()=>{n.$comment&&t.$comment&&_(e),function(e){const{schema:t,opts:n}=e;void 0!==t.default&&n.useDefaults&&n.strictSchema&&(0,u.checkStrictMode)(e,"default is ignored in the schema root")}(e),r.let(c.default.vErrors,null),r.let(c.default.errors,0),n.unevaluated&&function(e){const{gen:t,validateName:n}=e;e.evaluated=t.const("evaluated",i._`${n}.evaluated`),t.if(i._`${e.evaluated}.dynamicProps`,()=>t.assign(i._`${e.evaluated}.props`,i._`undefined`)),t.if(i._`${e.evaluated}.dynamicItems`,()=>t.assign(i._`${e.evaluated}.items`,i._`undefined`))}(e),y(e),function(e){const{gen:t,schemaEnv:n,validateName:r,ValidationError:s,opts:o}=e;n.$async?t.if(i._`${c.default.errors} === 0`,()=>t.return(c.default.data),()=>t.throw(i._`new ${s}(${c.default.vErrors})`)):(t.assign(i._`${r}.errors`,c.default.vErrors),o.unevaluated&&function({gen:e,evaluated:t,props:n,items:r}){n instanceof i.Name&&e.assign(i._`${t}.props`,n),r instanceof i.Name&&e.assign(i._`${t}.items`,r)}(e),t.return(i._`${c.default.errors} === 0`))}(e)})}(t):p(t,()=>(0,e.topBoolOrEmptySchema)(t))};class ${constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",O(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:!1!==t.errors)&&(this.errsCount=e.gen.const("_errs",c.default.errors))}result(e,t,n){this.failResult((0,i.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,i.not)(e),void 0,t)}fail(e){if(void 0===e)return this.error(),void(this.allErrors||this.gen.if(!1));this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:t}=this;this.fail(i._`${t} !== undefined && (${(0,i.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t)return this.setParams(t),this._error(e,n),void this.setParams({});this._error(e,n)}_error(e,t){(e?l.reportExtraError:l.reportError)(this,this.def.error,t)}$dataError(){(0,l.reportError)(this,this.def.$dataError||l.keyword$DataError)}reset(){if(void 0===this.errsCount)throw new Error('add "trackErrors" to keyword definition');(0,l.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=i.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=i.nil,t=i.nil){if(!this.$data)return;const{gen:n,schemaCode:r,schemaType:s,def:o}=this;n.if((0,i.or)(i._`${r} === undefined`,t)),e!==i.nil&&n.assign(e,!0),(s.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==i.nil&&n.assign(e,!1)),n.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:n,def:s,it:o}=this;return(0,i.or)(function(){if(n.length){if(!(t instanceof i.Name))throw new Error("ajv implementation error");const e=Array.isArray(n)?n:[n];return i._`${(0,r.checkDataTypes)(e,t,o.opts.strictNumbers,r.DataType.Wrong)}`}return i.nil}(),function(){if(s.validateSchema){const n=e.scopeValue("validate$data",{ref:s.validateSchema});return i._`!${n}(${t})`}return i.nil}())}subschema(t,n){const r=(0,a.getSubschema)(this.it,t);(0,a.extendSubschemaData)(r,this.it,t),(0,a.extendSubschemaMode)(r,t);const s={...this.it,...r,items:void 0,props:void 0};return function(t,n){f(t)&&(g(t),m(t))?function(e,t){const{schema:n,gen:r,opts:s}=e;s.$comment&&n.$comment&&_(e),function(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,d.resolveUrl)(e.opts.uriResolver,e.baseId,t))}(e),function(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}(e);const o=r.const("_errs",c.default.errors);y(e,o),r.var(t,i._`${o} === ${c.default.errors}`)}(t,n):(0,e.boolOrEmptySchema)(t,n)}(s,n),s}mergeEvaluated(e,t){const{it:n,gen:r}=this;n.opts.unevaluated&&(!0!==n.props&&void 0!==e.props&&(n.props=u.mergeEvaluated.props(r,e.props,n.props,t)),!0!==n.items&&void 0!==e.items&&(n.items=u.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){const{it:n,gen:r}=this;if(n.opts.unevaluated&&(!0!==n.props||!0!==n.items))return r.if(t,()=>this.mergeEvaluated(e,i.Name)),!0}}function S(e,t,n,r){const s=new $(e,n,t);"code"in n?n.code(s,r):s.$data&&n.validate?(0,o.funcKeywordCode)(s,n):"macro"in n?(0,o.macroKeywordCode)(s,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(s,n)}$l.KeywordCxt=$;const E=/^\/(?:[^~]|~0|~1)*$/,T=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function O(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let s,o;if(""===e)return c.default.rootData;if("/"===e[0]){if(!E.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);s=e,o=c.default.rootData}else{const a=T.exec(e);if(!a)throw new Error(`Invalid JSON-pointer: ${e}`);const i=+a[1];if(s=a[2],"#"===s){if(i>=t)throw new Error(l("property/index",i));return r[t-i]}if(i>t)throw new Error(l("data",i));if(o=n[t-i],!s)return o}let a=o;const d=s.split("/");for(const e of d)e&&(o=i._`${o}${(0,i.getProperty)((0,u.unescapeJsonPointer)(e))}`,a=i._`${a} && ${o}`);return a;function l(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}return $l.getData=O,$l}var _p,vp={};function wp(){if(_p)return vp;_p=1,Object.defineProperty(vp,"__esModule",{value:!0});class e extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}return vp.default=e,vp}var bp,kp={};function $p(){if(bp)return kp;bp=1,Object.defineProperty(kp,"__esModule",{value:!0});const e=gp();class t extends Error{constructor(t,n,r,s){super(s||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,e.resolveUrl)(t,n,r),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(t,this.missingRef))}}return kp.default=t,kp}var Sp,Ep={};function Tp(){if(Sp)return Ep;Sp=1,Object.defineProperty(Ep,"__esModule",{value:!0}),Ep.resolveSchema=Ep.getCompilingSchema=Ep.resolveRef=Ep.compileSchema=Ep.SchemaEnv=void 0;const e=Cl(),t=wp(),n=Fl(),r=gp(),s=Al(),o=yp();class a{constructor(e){var t;let n;this.refs={},this.dynamicAnchors={},"object"==typeof e.schema&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=null!==(t=e.baseId)&&void 0!==t?t:(0,r.normalizeId)(null==n?void 0:n[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=null==n?void 0:n.$async,this.refs={}}}function i(s){const a=d.call(this,s);if(a)return a;const i=(0,r.getFullPath)(this.opts.uriResolver,s.root.baseId),{es5:c,lines:u}=this.opts.code,{ownProperties:l}=this.opts,p=new e.CodeGen(this.scope,{es5:c,lines:u,ownProperties:l});let h;s.$async&&(h=p.scopeValue("Error",{ref:t.default,code:e._`require("ajv/dist/runtime/validation_error").default`}));const m=p.scopeName("validate");s.validateName=m;const f={gen:p,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:p.scopeValue("schema",!0===this.opts.code.source?{ref:s.schema,code:(0,e.stringify)(s.schema)}:{ref:s.schema}),validateName:m,ValidationError:h,schema:s.schema,schemaEnv:s,rootId:i,baseId:s.baseId||i,schemaPath:e.nil,errSchemaPath:s.schemaPath||(this.opts.jtd?"":"#"),errorPath:e._`""`,opts:this.opts,self:this};let g;try{this._compilations.add(s),(0,o.validateFunctionCode)(f),p.optimize(this.opts.code.optimize);const t=p.toString();g=`${p.scopeRefs(n.default.scope)}return ${t}`,this.opts.code.process&&(g=this.opts.code.process(g,s));const r=new Function(`${n.default.self}`,`${n.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:r}),r.errors=null,r.schema=s.schema,r.schemaEnv=s,s.$async&&(r.$async=!0),!0===this.opts.code.source&&(r.source={validateName:m,validateCode:t,scopeValues:p._values}),this.opts.unevaluated){const{props:t,items:n}=f;r.evaluated={props:t instanceof e.Name?void 0:t,items:n instanceof e.Name?void 0:n,dynamicProps:t instanceof e.Name,dynamicItems:n instanceof e.Name},r.source&&(r.source.evaluated=(0,e.stringify)(r.evaluated))}return s.validate=r,s}catch(e){throw delete s.validate,delete s.validateName,g&&this.logger.error("Error compiling schema, function code:",g),e}finally{this._compilations.delete(s)}}function c(e){return(0,r.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:i.call(this,e)}function d(e){for(const t of this._compilations)if(u(t,e))return t}function u(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function l(e,t){let n;for(;"string"==typeof(n=this.refs[t]);)t=n;return n||this.schemas[t]||p.call(this,e,t)}function p(e,t){const n=this.opts.uriResolver.parse(t),s=(0,r._getFullPath)(this.opts.uriResolver,n);let o=(0,r.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&s===o)return m.call(this,n,e);const c=(0,r.normalizeId)(s),d=this.refs[c]||this.schemas[c];if("string"==typeof d){const t=p.call(this,e,d);if("object"!=typeof(null==t?void 0:t.schema))return;return m.call(this,n,t)}if("object"==typeof(null==d?void 0:d.schema)){if(d.validate||i.call(this,d),c===(0,r.normalizeId)(t)){const{schema:t}=d,{schemaId:n}=this.opts,s=t[n];return s&&(o=(0,r.resolveUrl)(this.opts.uriResolver,o,s)),new a({schema:t,schemaId:n,root:e,baseId:o})}return m.call(this,n,d)}}Ep.SchemaEnv=a,Ep.compileSchema=i,Ep.resolveRef=function(e,t,n){var s;n=(0,r.resolveUrl)(this.opts.uriResolver,t,n);const o=e.refs[n];if(o)return o;let i=l.call(this,e,n);if(void 0===i){const r=null===(s=e.localRefs)||void 0===s?void 0:s[n],{schemaId:o}=this.opts;r&&(i=new a({schema:r,schemaId:o,root:e,baseId:t}))}return void 0!==i?e.refs[n]=c.call(this,i):void 0},Ep.getCompilingSchema=d,Ep.resolveSchema=p;const h=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function m(e,{baseId:t,schema:n,root:o}){var i;if("/"!==(null===(i=e.fragment)||void 0===i?void 0:i[0]))return;for(const o of e.fragment.slice(1).split("/")){if("boolean"==typeof n)return;const e=n[(0,s.unescapeFragment)(o)];if(void 0===e)return;const a="object"==typeof(n=e)&&n[this.opts.schemaId];!h.has(o)&&a&&(t=(0,r.resolveUrl)(this.opts.uriResolver,t,a))}let c;if("boolean"!=typeof n&&n.$ref&&!(0,s.schemaHasRulesButRef)(n,this.RULES)){const e=(0,r.resolveUrl)(this.opts.uriResolver,t,n.$ref);c=p.call(this,o,e)}const{schemaId:d}=this.opts;return c=c||new a({schema:n,schemaId:d,root:o,baseId:t}),c.schema!==c.root.schema?c:void 0}return Ep}var Op,xp,Np,Ip,Rp,Pp,Cp,jp={$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},zp={},Ap={exports:{}};function Mp(){if(xp)return Op;xp=1;const e=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),t=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function n(e){let t="",n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),48!==n){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[r]}return t}const r=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function s(e){return e.length=0,!0}function o(e,t,r){if(e.length){const s=n(e);if(""===s)return r.error=!0,!1;t.push(s),e.length=0}return!0}function a(e){if(function(e){let t=0;for(let n=0;n<e.length;n++)":"===e[n]&&t++;return t}(e)<2)return{host:e,isIPV6:!1};const t=function(e){let t=0;const r={error:!1,address:"",zone:""},a=[],i=[];let c=!1,d=!1,u=o;for(let n=0;n<e.length;n++){const o=e[n];if("["!==o&&"]"!==o)if(":"!==o)if("%"===o){if(!u(i,a,r))break;u=s}else i.push(o);else{if(!0===c&&(d=!0),!u(i,a,r))break;if(++t>7){r.error=!0;break}n>0&&":"===e[n-1]&&(c=!0),a.push(":")}}return i.length&&(u===s?r.zone=i.join(""):d?a.push(i.join("")):a.push(n(i))),r.address=a.join(""),r}(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,n=t.address;return t.zone&&(e+="%"+t.zone,n+="%25"+t.zone),{host:e,isIPV6:!0,escapedHost:n}}}return Op={nonSimpleDomain:r,recomposeAuthority:function(e){const n=[];if(void 0!==e.userinfo&&(n.push(e.userinfo),n.push("@")),void 0!==e.host){let r=unescape(e.host);if(!t(r)){const t=a(r);r=!0===t.isIPV6?`[${t.escapedHost}]`:e.host}n.push(r)}return"number"!=typeof e.port&&"string"!=typeof e.port||(n.push(":"),n.push(String(e.port))),n.length?n.join(""):void 0},normalizeComponentEncoding:function(e,t){const n=!0!==t?escape:unescape;return void 0!==e.scheme&&(e.scheme=n(e.scheme)),void 0!==e.userinfo&&(e.userinfo=n(e.userinfo)),void 0!==e.host&&(e.host=n(e.host)),void 0!==e.path&&(e.path=n(e.path)),void 0!==e.query&&(e.query=n(e.query)),void 0!==e.fragment&&(e.fragment=n(e.fragment)),e},removeDotSegments:function(e){let t=e;const n=[];let r=-1,s=0;for(;s=t.length;){if(1===s){if("."===t)break;if("/"===t){n.push("/");break}n.push(t);break}if(2===s){if("."===t[0]){if("."===t[1])break;if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&("."===t[1]||"/"===t[1])){n.push("/");break}}else if(3===s&&"/.."===t){0!==n.length&&n.pop(),n.push("/");break}if("."===t[0]){if("."===t[1]){if("/"===t[2]){t=t.slice(3);continue}}else if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&"."===t[1]){if("/"===t[2]){t=t.slice(2);continue}if("."===t[2]&&"/"===t[3]){t=t.slice(3),0!==n.length&&n.pop();continue}}if(-1===(r=t.indexOf("/",1))){n.push(t);break}n.push(t.slice(0,r)),t=t.slice(r)}return n.join("")},isIPv4:t,isUUID:e,normalizeIPv6:a,stringArrayToHexStripped:n},Op}function Dp(){return Cp||(Cp=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=yp();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=Cl();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});const r=wp(),s=$p(),o=Kl(),a=Tp(),i=Cl(),c=gp(),d=Xl(),u=Al(),l=jp,p=function(){if(Pp)return zp;Pp=1,Object.defineProperty(zp,"__esModule",{value:!0});const e=function(){if(Rp)return Ap.exports;Rp=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:n,normalizeComponentEncoding:r,isIPv4:s,nonSimpleDomain:o}=Mp(),{SCHEMES:a,getSchemeHandler:i}=function(){if(Ip)return Np;Ip=1;const{isUUID:e}=Mp(),t=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,n=["http","https","ws","wss","urn","urn:uuid"];function r(e){return!0===e.secure||!1!==e.secure&&!!e.scheme&&!(3!==e.scheme.length||"w"!==e.scheme[0]&&"W"!==e.scheme[0]||"s"!==e.scheme[1]&&"S"!==e.scheme[1]||"s"!==e.scheme[2]&&"S"!==e.scheme[2])}function s(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function o(e){const t="https"===String(e.scheme).toLowerCase();return e.port!==(t?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}const a={scheme:"http",domainHost:!0,parse:s,serialize:o},i={scheme:"ws",domainHost:!0,parse:function(e){return e.secure=r(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e},serialize:function(e){if(e.port!==(r(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){const[t,n]=e.resourceName.split("?");e.path=t&&"/"!==t?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}},c={http:a,https:{scheme:"https",domainHost:a.domainHost,parse:s,serialize:o},ws:i,wss:{scheme:"wss",domainHost:i.domainHost,parse:i.parse,serialize:i.serialize},urn:{scheme:"urn",parse:function(e,n){if(!e.path)return e.error="URN can not be parsed",e;const r=e.path.match(t);if(r){const t=n.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];const s=d(`${t}:${n.nid||e.nid}`);e.path=void 0,s&&(e=s.parse(e,n))}else e.error=e.error||"URN can not be parsed.";return e},serialize:function(e,t){if(void 0===e.nid)throw new Error("URN without nid cannot be serialized");const n=t.scheme||e.scheme||"urn",r=e.nid.toLowerCase(),s=d(`${n}:${t.nid||r}`);s&&(e=s.serialize(e,t));const o=e,a=e.nss;return o.path=`${r||t.nid}:${a}`,t.skipEscape=!0,o},skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:function(t,n){const r=t;return r.uuid=r.nss,r.nss=void 0,n.tolerant||r.uuid&&e(r.uuid)||(r.error=r.error||"UUID is not valid."),r},serialize:function(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t},skipNormalize:!0}};function d(e){return e&&(c[e]||c[e.toLowerCase()])||void 0}return Object.setPrototypeOf(c,null),Np={wsIsSecure:r,SCHEMES:c,isValidSchemeName:function(e){return-1!==n.indexOf(e)},getSchemeHandler:d}}();function c(e,n,r,s){const o={};return s||(e=l(d(e,r),r),n=l(d(n,r),r)),!(r=r||{}).tolerant&&n.scheme?(o.scheme=n.scheme,o.userinfo=n.userinfo,o.host=n.host,o.port=n.port,o.path=t(n.path||""),o.query=n.query):(void 0!==n.userinfo||void 0!==n.host||void 0!==n.port?(o.userinfo=n.userinfo,o.host=n.host,o.port=n.port,o.path=t(n.path||""),o.query=n.query):(n.path?("/"===n.path[0]?o.path=t(n.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+n.path:o.path=n.path:o.path="/"+n.path,o.path=t(o.path)),o.query=n.query):(o.path=e.path,void 0!==n.query?o.query=n.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=n.fragment,o}function d(e,r){const s={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},o=Object.assign({},r),a=[],c=i(o.scheme||s.scheme);c&&c.serialize&&c.serialize(s,o),void 0!==s.path&&(o.skipEscape?s.path=unescape(s.path):(s.path=escape(s.path),void 0!==s.scheme&&(s.path=s.path.split("%3A").join(":")))),"suffix"!==o.reference&&s.scheme&&a.push(s.scheme,":");const d=n(s);if(void 0!==d&&("suffix"!==o.reference&&a.push("//"),a.push(d),s.path&&"/"!==s.path[0]&&a.push("/")),void 0!==s.path){let e=s.path;o.absolutePath||c&&c.absolutePath||(e=t(e)),void 0===d&&"/"===e[0]&&"/"===e[1]&&(e="/%2F"+e.slice(2)),a.push(e)}return void 0!==s.query&&a.push("?",s.query),void 0!==s.fragment&&a.push("#",s.fragment),a.join("")}const u=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function l(t,n){const r=Object.assign({},n),a={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let c=!1;"suffix"===r.reference&&(t=r.scheme?r.scheme+":"+t:"//"+t);const d=t.match(u);if(d){if(a.scheme=d[1],a.userinfo=d[3],a.host=d[4],a.port=parseInt(d[5],10),a.path=d[6]||"",a.query=d[7],a.fragment=d[8],isNaN(a.port)&&(a.port=d[5]),a.host)if(!1===s(a.host)){const t=e(a.host);a.host=t.host.toLowerCase(),c=t.isIPV6}else c=!0;void 0!==a.scheme||void 0!==a.userinfo||void 0!==a.host||void 0!==a.port||void 0!==a.query||a.path?void 0===a.scheme?a.reference="relative":void 0===a.fragment?a.reference="absolute":a.reference="uri":a.reference="same-document",r.reference&&"suffix"!==r.reference&&r.reference!==a.reference&&(a.error=a.error||"URI is not a "+r.reference+" reference.");const n=i(r.scheme||a.scheme);if(!(r.unicodeSupport||n&&n.unicodeSupport)&&a.host&&(r.domainHost||n&&n.domainHost)&&!1===c&&o(a.host))try{a.host=URL.domainToASCII(a.host.toLowerCase())}catch(e){a.error=a.error||"Host's domain name can not be converted to ASCII: "+e}(!n||n&&!n.skipNormalize)&&(-1!==t.indexOf("%")&&(void 0!==a.scheme&&(a.scheme=unescape(a.scheme)),void 0!==a.host&&(a.host=unescape(a.host))),a.path&&(a.path=escape(unescape(a.path))),a.fragment&&(a.fragment=encodeURI(decodeURIComponent(a.fragment)))),n&&n.parse&&n.parse(a,r)}else a.error=a.error||"URI can not be parsed.";return a}const p={SCHEMES:a,normalize:function(e,t){return"string"==typeof e?e=d(l(e,t),t):"object"==typeof e&&(e=l(d(e,t),t)),e},resolve:function(e,t,n){const r=n?Object.assign({scheme:"null"},n):{scheme:"null"},s=c(l(e,r),l(t,r),r,!0);return r.skipEscape=!0,d(s,r)},resolveComponent:c,equal:function(e,t,n){return"string"==typeof e?(e=unescape(e),e=d(r(l(e,n),!0),{...n,skipEscape:!0})):"object"==typeof e&&(e=d(r(e,!0),{...n,skipEscape:!0})),"string"==typeof t?(t=unescape(t),t=d(r(l(t,n),!0),{...n,skipEscape:!0})):"object"==typeof t&&(t=d(r(t,!0),{...n,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()},serialize:d,parse:l};return Ap.exports=p,Ap.exports.default=p,Ap.exports.fastUri=p,Ap.exports}();return e.code='require("ajv/dist/runtime/uri").default',zp.default=e,zp}(),h=(e,t)=>new RegExp(e,t);h.code="new RegExp";const m=["removeAdditional","useDefaults","coerceTypes"],f=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),g={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},y={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};function _(e){var t,n,r,s,o,a,i,c,d,u,l,m,f,g,y,_,v,w,b,k,$,S,E,T,O;const x=e.strict,N=null===(t=e.code)||void 0===t?void 0:t.optimize,I=!0===N||void 0===N?1:N||0,R=null!==(r=null===(n=e.code)||void 0===n?void 0:n.regExp)&&void 0!==r?r:h,P=null!==(s=e.uriResolver)&&void 0!==s?s:p.default;return{strictSchema:null===(a=null!==(o=e.strictSchema)&&void 0!==o?o:x)||void 0===a||a,strictNumbers:null===(c=null!==(i=e.strictNumbers)&&void 0!==i?i:x)||void 0===c||c,strictTypes:null!==(u=null!==(d=e.strictTypes)&&void 0!==d?d:x)&&void 0!==u?u:"log",strictTuples:null!==(m=null!==(l=e.strictTuples)&&void 0!==l?l:x)&&void 0!==m?m:"log",strictRequired:null!==(g=null!==(f=e.strictRequired)&&void 0!==f?f:x)&&void 0!==g&&g,code:e.code?{...e.code,optimize:I,regExp:R}:{optimize:I,regExp:R},loopRequired:null!==(y=e.loopRequired)&&void 0!==y?y:200,loopEnum:null!==(_=e.loopEnum)&&void 0!==_?_:200,meta:null===(v=e.meta)||void 0===v||v,messages:null===(w=e.messages)||void 0===w||w,inlineRefs:null===(b=e.inlineRefs)||void 0===b||b,schemaId:null!==(k=e.schemaId)&&void 0!==k?k:"$id",addUsedSchema:null===($=e.addUsedSchema)||void 0===$||$,validateSchema:null===(S=e.validateSchema)||void 0===S||S,validateFormats:null===(E=e.validateFormats)||void 0===E||E,unicodeRegExp:null===(T=e.unicodeRegExp)||void 0===T||T,int32range:null===(O=e.int32range)||void 0===O||O,uriResolver:P}}class v{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,..._(e)};const{es5:t,lines:n}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:f,es5:t,lines:n}),this.logger=function(e){if(!1===e)return T;if(void 0===e)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}(e.logger);const r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,o.getRules)(),w.call(this,g,e,"NOT SUPPORTED"),w.call(this,y,e,"DEPRECATED","warn"),this._metaOpts=E.call(this),e.formats&&$.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&S.call(this,e.keywords),"object"==typeof e.meta&&this.addMetaSchema(e.meta),k.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:e,meta:t,schemaId:n}=this.opts;let r=l;"id"===n&&(r={...l},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){const{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta="object"==typeof e?e[t]||e:void 0}validate(e,t){let n;if("string"==typeof e){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);const r=n(t);return"$async"in n||(this.errors=n.errors),r}compile(e,t){const n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if("function"!=typeof this.opts.loadSchema)throw new Error("options.loadSchema should be a function");const{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await o.call(this,e.$schema);const n=this._addSchema(e,t);return n.validate||a.call(this,n)}async function o(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function a(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof s.default))throw t;return i.call(this,t),await c.call(this,t.missingSchema),a.call(this,e)}}function i({missingSchema:e,missingRef:t}){if(this.refs[e])throw new Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){const n=await d.call(this,e);this.refs[e]||await o.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function d(e){const t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(const t of e)this.addSchema(t,void 0,n,r);return this}let s;if("object"==typeof e){const{schemaId:t}=this.opts;if(s=e[t],void 0!==s&&"string"!=typeof s)throw new Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||s),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if("boolean"==typeof e)return!0;let n;if(n=e.$schema,void 0!==n&&"string"!=typeof n)throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const r=this.validate(n,e);if(!r&&t){const e="schema is invalid: "+this.errorsText();if("log"!==this.opts.validateSchema)throw new Error(e);this.logger.error(e)}return r}getSchema(e){let t;for(;"string"==typeof(t=b.call(this,e));)e=t;if(void 0===t){const{schemaId:n}=this.opts,r=new a.SchemaEnv({schema:{},schemaId:n});if(t=a.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const t=b.call(this,e);return"object"==typeof t&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{const t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(const t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if("string"==typeof e)n=e,"object"==typeof t&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=n);else{if("object"!=typeof e||void 0!==t)throw new Error("invalid addKeywords parameters");if(n=(t=e).keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}if(x.call(this,n,t),!t)return(0,u.eachItem)(n,e=>N.call(this,e)),this;R.call(this,t);const r={...t,type:(0,d.getJSONTypes)(t.type),schemaType:(0,d.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,0===r.type.length?e=>N.call(this,e,r):e=>r.type.forEach(t=>N.call(this,e,r,t))),this}getKeyword(e){const t=this.RULES.all[e];return"object"==typeof t?t.definition:!!t}removeKeyword(e){const{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(const n of t.rules){const t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return"string"==typeof t&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:n="data"}={}){return e&&0!==e.length?e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n):"No errors"}$dataMetaSchema(e,t){const n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(const r of t){const t=r.split("/").slice(1);let s=e;for(const e of t)s=s[e];for(const e in n){const t=n[e];if("object"!=typeof t)continue;const{$data:r}=t.definition,o=s[e];r&&o&&(s[e]=C(o))}}return e}_removeAllSchemas(e,t){for(const n in e){const r=e[n];t&&!t.test(n)||("string"==typeof r?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,s=this.opts.addUsedSchema){let o;const{schemaId:i}=this.opts;if("object"==typeof e)o=e[i];else{if(this.opts.jtd)throw new Error("schema must be object");if("boolean"!=typeof e)throw new Error("schema must be object or boolean")}let d=this._cache.get(e);if(void 0!==d)return d;n=(0,c.normalizeId)(o||n);const u=c.getSchemaRefs.call(this,e,n);return d=new a.SchemaEnv({schema:e,schemaId:i,meta:t,baseId:n,localRefs:u}),this._cache.set(d.schema,d),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=d),r&&this.validateSchema(e,!0),d}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):a.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){const t=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,e)}finally{this.opts=t}}}function w(e,t,n,r="error"){for(const s in e){const o=s;o in t&&this.logger[r](`${n}: option ${s}. ${e[o]}`)}}function b(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function k(){const e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(const t in e)this.addSchema(e[t],t)}function $(){for(const e in this.opts.formats){const t=this.opts.formats[e];t&&this.addFormat(e,t)}}function S(e){if(Array.isArray(e))this.addVocabulary(e);else{this.logger.warn("keywords option as map is deprecated, pass array");for(const t in e){const n=e[t];n.keyword||(n.keyword=t),this.addKeyword(n)}}}function E(){const e={...this.opts};for(const t of m)delete e[t];return e}v.ValidationError=r.default,v.MissingRefError=s.default,e.default=v;const T={log(){},warn(){},error(){}},O=/^[a-z_$][a-z0-9_$:-]*$/i;function x(e,t){const{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw new Error(`Keyword ${e} is already defined`);if(!O.test(e))throw new Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!("code"in t)&&!("validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function N(e,t,n){var r;const s=null==t?void 0:t.post;if(n&&s)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:o}=this;let a=s?o.post:o.rules.find(({type:e})=>e===n);if(a||(a={type:n,rules:[]},o.rules.push(a)),o.keywords[e]=!0,!t)return;const i={keyword:e,definition:{...t,type:(0,d.getJSONTypes)(t.type),schemaType:(0,d.getJSONTypes)(t.schemaType)}};t.before?I.call(this,a,i,t.before):a.rules.push(i),o.all[e]=i,null===(r=t.implements)||void 0===r||r.forEach(e=>this.addKeyword(e))}function I(e,t,n){const r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function R(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=C(t)),e.validateSchema=this.compile(t,!0))}const P={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function C(e){return{anyOf:[e,P]}}}(kl)),kl}var Lp,Zp,Fp,qp={},Up={},Hp={},Vp={};var Kp,Jp,Bp,Wp,Gp={},Xp={},Yp={},Qp={},eh={};var th,nh,rh,sh={},oh={},ah={};var ih,ch,dh,uh={},lh={},ph={};function hh(){if(ch)return ph;ch=1,Object.defineProperty(ph,"__esModule",{value:!0});const e=up();return e.code='require("ajv/dist/runtime/equal").default',ph.default=e,ph}function mh(){if(dh)return lh;dh=1,Object.defineProperty(lh,"__esModule",{value:!0});const e=Xl(),t=Cl(),n=Al(),r=hh(),s={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:n}})=>t.str`must NOT have duplicate items (items ## ${n} and ${e} are identical)`,params:({params:{i:e,j:n}})=>t._`{i: ${e}, j: ${n}}`},code(s){const{gen:o,data:a,$data:i,schema:c,parentSchema:d,schemaCode:u,it:l}=s;if(!i&&!c)return;const p=o.let("valid"),h=d.items?(0,e.getSchemaTypes)(d.items):[];function m(n,r){const i=o.name("item"),c=(0,e.checkDataTypes)(h,i,l.opts.strictNumbers,e.DataType.Wrong),d=o.const("indices",t._`{}`);o.for(t._`;${n}--;`,()=>{o.let(i,t._`${a}[${n}]`),o.if(c,t._`continue`),h.length>1&&o.if(t._`typeof ${i} == "string"`,t._`${i} += "_"`),o.if(t._`typeof ${d}[${i}] == "number"`,()=>{o.assign(r,t._`${d}[${i}]`),s.error(),o.assign(p,!1).break()}).code(t._`${d}[${i}] = ${n}`)})}function f(e,i){const c=(0,n.useFunc)(o,r.default),d=o.name("outer");o.label(d).for(t._`;${e}--;`,()=>o.for(t._`${i} = ${e}; ${i}--;`,()=>o.if(t._`${c}(${a}[${e}], ${a}[${i}])`,()=>{s.error(),o.assign(p,!1).break(d)})))}s.block$data(p,function(){const e=o.let("i",t._`${a}.length`),n=o.let("j");s.setParams({i:e,j:n}),o.assign(p,!0),o.if(t._`${e} > 1`,()=>(h.length>0&&!h.some(e=>"object"===e||"array"===e)?m:f)(e,n))},t._`${u} === false`),s.ok(p)}};return lh.default=s,lh}var fh,gh,yh,_h={},vh={};function wh(){if(yh)return Gp;yh=1,Object.defineProperty(Gp,"__esModule",{value:!0});const e=function(){if(Kp)return Xp;Kp=1,Object.defineProperty(Xp,"__esModule",{value:!0});const e=Cl(),t=e.operators,n={maximum:{okStr:"<=",ok:t.LTE,fail:t.GT},minimum:{okStr:">=",ok:t.GTE,fail:t.LT},exclusiveMaximum:{okStr:"<",ok:t.LT,fail:t.GTE},exclusiveMinimum:{okStr:">",ok:t.GT,fail:t.LTE}},r={message:({keyword:t,schemaCode:r})=>e.str`must be ${n[t].okStr} ${r}`,params:({keyword:t,schemaCode:r})=>e._`{comparison: ${n[t].okStr}, limit: ${r}}`},s={keyword:Object.keys(n),type:"number",schemaType:"number",$data:!0,error:r,code(t){const{keyword:r,data:s,schemaCode:o}=t;t.fail$data(e._`${s} ${n[r].fail} ${o} || isNaN(${s})`)}};return Xp.default=s,Xp}(),t=function(){if(Jp)return Yp;Jp=1,Object.defineProperty(Yp,"__esModule",{value:!0});const e=Cl(),t={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:t})=>e.str`must be multiple of ${t}`,params:({schemaCode:t})=>e._`{multipleOf: ${t}}`},code(t){const{gen:n,data:r,schemaCode:s,it:o}=t,a=o.opts.multipleOfPrecision,i=n.let("res"),c=a?e._`Math.abs(Math.round(${i}) - ${i}) > 1e-${a}`:e._`${i} !== parseInt(${i})`;t.fail$data(e._`(${s} === 0 || (${i} = ${r}/${s}, ${c}))`)}};return Yp.default=t,Yp}(),n=function(){if(Wp)return Qp;Wp=1,Object.defineProperty(Qp,"__esModule",{value:!0});const e=Cl(),t=Al(),n=function(){if(Bp)return eh;function e(e){const t=e.length;let n,r=0,s=0;for(;s<t;)r++,n=e.charCodeAt(s++),n>=55296&&n<=56319&&s<t&&(n=e.charCodeAt(s),56320==(64512&n)&&s++);return r}return Bp=1,Object.defineProperty(eh,"__esModule",{value:!0}),eh.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',eh}(),r={message({keyword:t,schemaCode:n}){const r="maxLength"===t?"more":"fewer";return e.str`must NOT have ${r} than ${n} characters`},params:({schemaCode:t})=>e._`{limit: ${t}}`},s={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:r,code(r){const{keyword:s,data:o,schemaCode:a,it:i}=r,c="maxLength"===s?e.operators.GT:e.operators.LT,d=!1===i.opts.unicode?e._`${o}.length`:e._`${(0,t.useFunc)(r.gen,n.default)}(${o})`;r.fail$data(e._`${d} ${c} ${a}`)}};return Qp.default=s,Qp}(),r=function(){if(th)return sh;th=1,Object.defineProperty(sh,"__esModule",{value:!0});const e=sp(),t=Cl(),n={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>t.str`must match pattern "${e}"`,params:({schemaCode:e})=>t._`{pattern: ${e}}`},code(n){const{data:r,$data:s,schema:o,schemaCode:a,it:i}=n,c=i.opts.unicodeRegExp?"u":"",d=s?t._`(new RegExp(${a}, ${c}))`:(0,e.usePattern)(n,o);n.fail$data(t._`!${d}.test(${r})`)}};return sh.default=n,sh}(),s=function(){if(nh)return oh;nh=1,Object.defineProperty(oh,"__esModule",{value:!0});const e=Cl(),t={message({keyword:t,schemaCode:n}){const r="maxProperties"===t?"more":"fewer";return e.str`must NOT have ${r} than ${n} properties`},params:({schemaCode:t})=>e._`{limit: ${t}}`},n={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:t,code(t){const{keyword:n,data:r,schemaCode:s}=t,o="maxProperties"===n?e.operators.GT:e.operators.LT;t.fail$data(e._`Object.keys(${r}).length ${o} ${s}`)}};return oh.default=n,oh}(),o=function(){if(rh)return ah;rh=1,Object.defineProperty(ah,"__esModule",{value:!0});const e=sp(),t=Cl(),n=Al(),r={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>t.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>t._`{missingProperty: ${e}}`},code(r){const{gen:s,schema:o,schemaCode:a,data:i,$data:c,it:d}=r,{opts:u}=d;if(!c&&0===o.length)return;const l=o.length>=u.loopRequired;if(d.allErrors?function(){if(l||c)r.block$data(t.nil,p);else for(const t of o)(0,e.checkReportMissingProp)(r,t)}():function(){const n=s.let("missing");if(l||c){const o=s.let("valid",!0);r.block$data(o,()=>function(n,o){r.setParams({missingProperty:n}),s.forOf(n,a,()=>{s.assign(o,(0,e.propertyInData)(s,i,n,u.ownProperties)),s.if((0,t.not)(o),()=>{r.error(),s.break()})},t.nil)}(n,o)),r.ok(o)}else s.if((0,e.checkMissingProp)(r,o,n)),(0,e.reportMissingProp)(r,n),s.else()}(),u.strictRequired){const e=r.parentSchema.properties,{definedProperties:t}=r.it;for(const r of o)if(void 0===(null==e?void 0:e[r])&&!t.has(r)){const e=`required property "${r}" is not defined at "${d.schemaEnv.baseId+d.errSchemaPath}" (strictRequired)`;(0,n.checkStrictMode)(d,e,d.opts.strictRequired)}}function p(){s.forOf("prop",a,t=>{r.setParams({missingProperty:t}),s.if((0,e.noPropertyInData)(s,i,t,u.ownProperties),()=>r.error())})}}};return ah.default=r,ah}(),a=function(){if(ih)return uh;ih=1,Object.defineProperty(uh,"__esModule",{value:!0});const e=Cl(),t={message({keyword:t,schemaCode:n}){const r="maxItems"===t?"more":"fewer";return e.str`must NOT have ${r} than ${n} items`},params:({schemaCode:t})=>e._`{limit: ${t}}`},n={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:t,code(t){const{keyword:n,data:r,schemaCode:s}=t,o="maxItems"===n?e.operators.GT:e.operators.LT;t.fail$data(e._`${r}.length ${o} ${s}`)}};return uh.default=n,uh}(),i=mh(),c=function(){if(fh)return _h;fh=1,Object.defineProperty(_h,"__esModule",{value:!0});const e=Cl(),t=Al(),n=hh(),r={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:t})=>e._`{allowedValue: ${t}}`},code(r){const{gen:s,data:o,$data:a,schemaCode:i,schema:c}=r;a||c&&"object"==typeof c?r.fail$data(e._`!${(0,t.useFunc)(s,n.default)}(${o}, ${i})`):r.fail(e._`${c} !== ${o}`)}};return _h.default=r,_h}(),d=function(){if(gh)return vh;gh=1,Object.defineProperty(vh,"__esModule",{value:!0});const e=Cl(),t=Al(),n=hh(),r={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:t})=>e._`{allowedValues: ${t}}`},code(r){const{gen:s,data:o,$data:a,schema:i,schemaCode:c,it:d}=r;if(!a&&0===i.length)throw new Error("enum must have non-empty array");const u=i.length>=d.opts.loopEnum;let l;const p=()=>null!=l?l:l=(0,t.useFunc)(s,n.default);let h;if(u||a)h=s.let("valid"),r.block$data(h,function(){s.assign(h,!1),s.forOf("v",c,t=>s.if(e._`${p()}(${o}, ${t})`,()=>s.assign(h,!0).break()))});else{if(!Array.isArray(i))throw new Error("ajv implementation error");const t=s.const("vSchema",c);h=(0,e.or)(...i.map((n,r)=>function(t,n){const r=i[n];return"object"==typeof r&&null!==r?e._`${p()}(${o}, ${t}[${n}])`:e._`${o} === ${r}`}(t,r)))}r.pass(h)}};return vh.default=r,vh}(),u=[e.default,t.default,n.default,r.default,s.default,o.default,a.default,i.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},c.default,d.default];return Gp.default=u,Gp}var bh,kh={},$h={};function Sh(){if(bh)return $h;bh=1,Object.defineProperty($h,"__esModule",{value:!0}),$h.validateAdditionalItems=void 0;const e=Cl(),t=Al(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:t}})=>e.str`must NOT have more than ${t} items`,params:({params:{len:t}})=>e._`{limit: ${t}}`},code(e){const{parentSchema:n,it:s}=e,{items:o}=n;Array.isArray(o)?r(e,o):(0,t.checkStrictMode)(s,'"additionalItems" is ignored when "items" is not an array of schemas')}};function r(n,r){const{gen:s,schema:o,data:a,keyword:i,it:c}=n;c.items=!0;const d=s.const("len",e._`${a}.length`);if(!1===o)n.setParams({len:r.length}),n.pass(e._`${d} <= ${r.length}`);else if("object"==typeof o&&!(0,t.alwaysValidSchema)(c,o)){const o=s.var("valid",e._`${d} <= ${r.length}`);s.if((0,e.not)(o),()=>function(o){s.forRange("i",r.length,d,r=>{n.subschema({keyword:i,dataProp:r,dataPropType:t.Type.Num},o),c.allErrors||s.if((0,e.not)(o),()=>s.break())})}(o)),n.ok(o)}}return $h.validateAdditionalItems=r,$h.default=n,$h}var Eh,Th,Oh={},xh={};function Nh(){if(Eh)return xh;Eh=1,Object.defineProperty(xh,"__esModule",{value:!0}),xh.validateTuple=void 0;const e=Cl(),t=Al(),n=sp(),r={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:r,it:o}=e;if(Array.isArray(r))return s(e,"additionalItems",r);o.items=!0,(0,t.alwaysValidSchema)(o,r)||e.ok((0,n.validateArray)(e))}};function s(n,r,s=n.schema){const{gen:o,parentSchema:a,data:i,keyword:c,it:d}=n;!function(e){const{opts:n,errSchemaPath:o}=d,a=s.length,i=a===e.minItems&&(a===e.maxItems||!1===e[r]);if(n.strictTuples&&!i){const e=`"${c}" is ${a}-tuple, but minItems or maxItems/${r} are not specified or different at path "${o}"`;(0,t.checkStrictMode)(d,e,n.strictTuples)}}(a),d.opts.unevaluated&&s.length&&!0!==d.items&&(d.items=t.mergeEvaluated.items(o,s.length,d.items));const u=o.name("valid"),l=o.const("len",e._`${i}.length`);s.forEach((r,s)=>{(0,t.alwaysValidSchema)(d,r)||(o.if(e._`${l} > ${s}`,()=>n.subschema({keyword:c,schemaProp:s,dataProp:s},u)),n.ok(u))})}return xh.validateTuple=s,xh.default=r,xh}var Ih,Rh,Ph={},Ch={};var jh,zh={};var Ah,Mh,Dh={},Lh={};function Zh(){if(Mh)return Lh;Mh=1,Object.defineProperty(Lh,"__esModule",{value:!0});const e=sp(),t=Cl(),n=Fl(),r=Al(),s={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:e})=>t._`{additionalProperty: ${e.additionalProperty}}`},code(s){const{gen:o,schema:a,parentSchema:i,data:c,errsCount:d,it:u}=s;if(!d)throw new Error("ajv implementation error");const{allErrors:l,opts:p}=u;if(u.props=!0,"all"!==p.removeAdditional&&(0,r.alwaysValidSchema)(u,a))return;const h=(0,e.allSchemaProperties)(i.properties),m=(0,e.allSchemaProperties)(i.patternProperties);function f(e){o.code(t._`delete ${c}[${e}]`)}function g(e){if("all"===p.removeAdditional||p.removeAdditional&&!1===a)f(e);else{if(!1===a)return s.setParams({additionalProperty:e}),s.error(),void(l||o.break());if("object"==typeof a&&!(0,r.alwaysValidSchema)(u,a)){const n=o.name("valid");"failing"===p.removeAdditional?(y(e,n,!1),o.if((0,t.not)(n),()=>{s.reset(),f(e)})):(y(e,n),l||o.if((0,t.not)(n),()=>o.break()))}}}function y(e,t,n){const o={keyword:"additionalProperties",dataProp:e,dataPropType:r.Type.Str};!1===n&&Object.assign(o,{compositeRule:!0,createErrors:!1,allErrors:!1}),s.subschema(o,t)}o.forIn("key",c,n=>{h.length||m.length?o.if(function(n){let a;if(h.length>8){const t=(0,r.schemaRefOrVal)(u,i.properties,"properties");a=(0,e.isOwnProperty)(o,t,n)}else a=h.length?(0,t.or)(...h.map(e=>t._`${n} === ${e}`)):t.nil;return m.length&&(a=(0,t.or)(a,...m.map(r=>t._`${(0,e.usePattern)(s,r)}.test(${n})`))),(0,t.not)(a)}(n),()=>g(n)):g(n)}),s.ok(t._`${d} === ${n.default.errors}`)}};return Lh.default=s,Lh}var Fh,qh,Uh,Hh,Vh,Kh,Jh,Bh,Wh,Gh={},Xh={},Yh={},Qh={},em={},tm={},nm={},rm={};function sm(){if(Wh)return kh;Wh=1,Object.defineProperty(kh,"__esModule",{value:!0});const e=Sh(),t=function(){if(Th)return Oh;Th=1,Object.defineProperty(Oh,"__esModule",{value:!0});const e=Nh(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,e.validateTuple)(t,"items")};return Oh.default=t,Oh}(),n=Nh(),r=function(){if(Ih)return Ph;Ih=1,Object.defineProperty(Ph,"__esModule",{value:!0});const e=Cl(),t=Al(),n=sp(),r=Sh(),s={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:t}})=>e.str`must NOT have more than ${t} items`,params:({params:{len:t}})=>e._`{limit: ${t}}`},code(e){const{schema:s,parentSchema:o,it:a}=e,{prefixItems:i}=o;a.items=!0,(0,t.alwaysValidSchema)(a,s)||(i?(0,r.validateAdditionalItems)(e,i):e.ok((0,n.validateArray)(e)))}};return Ph.default=s,Ph}(),s=function(){if(Rh)return Ch;Rh=1,Object.defineProperty(Ch,"__esModule",{value:!0});const e=Cl(),t=Al(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:t,max:n}})=>void 0===n?e.str`must contain at least ${t} valid item(s)`:e.str`must contain at least ${t} and no more than ${n} valid item(s)`,params:({params:{min:t,max:n}})=>void 0===n?e._`{minContains: ${t}}`:e._`{minContains: ${t}, maxContains: ${n}}`},code(n){const{gen:r,schema:s,parentSchema:o,data:a,it:i}=n;let c,d;const{minContains:u,maxContains:l}=o;i.opts.next?(c=void 0===u?1:u,d=l):c=1;const p=r.const("len",e._`${a}.length`);if(n.setParams({min:c,max:d}),void 0===d&&0===c)return void(0,t.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==d&&c>d)return(0,t.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),void n.fail();if((0,t.alwaysValidSchema)(i,s)){let t=e._`${p} >= ${c}`;return void 0!==d&&(t=e._`${t} && ${p} <= ${d}`),void n.pass(t)}i.items=!0;const h=r.name("valid");function m(){const t=r.name("_valid"),n=r.let("count",0);f(t,()=>r.if(t,()=>function(t){r.code(e._`${t}++`),void 0===d?r.if(e._`${t} >= ${c}`,()=>r.assign(h,!0).break()):(r.if(e._`${t} > ${d}`,()=>r.assign(h,!1).break()),1===c?r.assign(h,!0):r.if(e._`${t} >= ${c}`,()=>r.assign(h,!0)))}(n)))}function f(e,s){r.forRange("i",0,p,r=>{n.subschema({keyword:"contains",dataProp:r,dataPropType:t.Type.Num,compositeRule:!0},e),s()})}void 0===d&&1===c?f(h,()=>r.if(h,()=>r.break())):0===c?(r.let(h,!0),void 0!==d&&r.if(e._`${a}.length > 0`,m)):(r.let(h,!1),m()),n.result(h,()=>n.reset())}};return Ch.default=n,Ch}(),o=(jh||(jh=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Cl(),n=Al(),r=sp();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{const s=1===n?"property":"properties";return t.str`must have ${s} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:s}})=>t._`{property: ${e},
6
6
  missingProperty: ${s},
7
7
  depsCount: ${n},
8
- deps: ${r}}`};const s={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(e){const[t,n]=function({schema:e}){const t={},n={};for(const r in e)"__proto__"!==r&&((Array.isArray(e[r])?t:n)[r]=e[r]);return[t,n]}(e);o(e,t),a(e,n)}};function o(e,n=e.schema){const{gen:s,data:o,it:a}=e;if(0===Object.keys(n).length)return;const i=s.let("missing");for(const c in n){const d=n[c];if(0===d.length)continue;const u=(0,r.propertyInData)(s,o,c,a.opts.ownProperties);e.setParams({property:c,depsCount:d.length,deps:d.join(", ")}),a.allErrors?s.if(u,()=>{for(const t of d)(0,r.checkReportMissingProp)(e,t)}):(s.if(t._`${u} && (${(0,r.checkMissingProp)(e,d,i)})`),(0,r.reportMissingProp)(e,i),s.else())}}function a(e,t=e.schema){const{gen:s,data:o,keyword:a,it:i}=e,c=s.name("valid");for(const d in t)(0,n.alwaysValidSchema)(i,t[d])||(s.if((0,r.propertyInData)(s,o,d,i.opts.ownProperties),()=>{const t=e.subschema({keyword:a,schemaProp:d},c);e.mergeValidEvaluated(t,c)},()=>s.var(c,!0)),e.ok(c))}e.validatePropertyDeps=o,e.validateSchemaDeps=a,e.default=s}(zh)),zh),a=function(){if(Ah)return Dh;Ah=1,Object.defineProperty(Dh,"__esModule",{value:!0});const e=Cl(),t=Al(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:t})=>e._`{propertyName: ${t.propertyName}}`},code(n){const{gen:r,schema:s,data:o,it:a}=n;if((0,t.alwaysValidSchema)(a,s))return;const i=r.name("valid");r.forIn("key",o,t=>{n.setParams({propertyName:t}),n.subschema({keyword:"propertyNames",data:t,dataTypes:["string"],propertyName:t,compositeRule:!0},i),r.if((0,e.not)(i),()=>{n.error(!0),a.allErrors||r.break()})}),n.ok(i)}};return Dh.default=n,Dh}(),i=Zh(),c=function(){if(Fh)return Gh;Fh=1,Object.defineProperty(Gh,"__esModule",{value:!0});const e=yp(),t=sp(),n=Al(),r=Zh(),s={keyword:"properties",type:"object",schemaType:"object",code(s){const{gen:o,schema:a,parentSchema:i,data:c,it:d}=s;"all"===d.opts.removeAdditional&&void 0===i.additionalProperties&&r.default.code(new e.KeywordCxt(d,r.default,"additionalProperties"));const u=(0,t.allSchemaProperties)(a);for(const e of u)d.definedProperties.add(e);d.opts.unevaluated&&u.length&&!0!==d.props&&(d.props=n.mergeEvaluated.props(o,(0,n.toHash)(u),d.props));const l=u.filter(e=>!(0,n.alwaysValidSchema)(d,a[e]));if(0===l.length)return;const p=o.name("valid");for(const e of l)h(e)?m(e):(o.if((0,t.propertyInData)(o,c,e,d.opts.ownProperties)),m(e),d.allErrors||o.else().var(p,!0),o.endIf()),s.it.definedProperties.add(e),s.ok(p);function h(e){return d.opts.useDefaults&&!d.compositeRule&&void 0!==a[e].default}function m(e){s.subschema({keyword:"properties",schemaProp:e,dataProp:e},p)}}};return Gh.default=s,Gh}(),d=function(){if(Uh)return Xh;Uh=1,Object.defineProperty(Xh,"__esModule",{value:!0});const e=sp(),t=Cl(),n=Al(),r=Al(),s={keyword:"patternProperties",type:"object",schemaType:"object",code(s){const{gen:o,schema:a,data:i,parentSchema:c,it:d}=s,{opts:u}=d,l=(0,e.allSchemaProperties)(a),p=l.filter(e=>(0,n.alwaysValidSchema)(d,a[e]));if(0===l.length||p.length===l.length&&(!d.opts.unevaluated||!0===d.props))return;const h=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=o.name("valid");!0===d.props||d.props instanceof t.Name||(d.props=(0,r.evaluatedPropsToName)(o,d.props));const{props:f}=d;function g(e){for(const t in h)new RegExp(e).test(t)&&(0,n.checkStrictMode)(d,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function y(n){o.forIn("key",i,a=>{o.if(t._`${(0,e.usePattern)(s,n)}.test(${a})`,()=>{const e=p.includes(n);e||s.subschema({keyword:"patternProperties",schemaProp:n,dataProp:a,dataPropType:r.Type.Str},m),d.opts.unevaluated&&!0!==f?o.assign(t._`${f}[${a}]`,!0):e||d.allErrors||o.if((0,t.not)(m),()=>o.break())})})}!function(){for(const e of l)h&&g(e),d.allErrors?y(e):(o.var(m,!0),y(e),o.if(m))}()}};return Xh.default=s,Xh}(),u=function(){if(qh)return Yh;qh=1,Object.defineProperty(Yh,"__esModule",{value:!0});const e=Al(),t={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){const{gen:n,schema:r,it:s}=t;if((0,e.alwaysValidSchema)(s,r))return void t.fail();const o=n.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};return Yh.default=t,Yh}(),l=function(){if(Hh)return Qh;Hh=1,Object.defineProperty(Qh,"__esModule",{value:!0});const e={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:sp().validateUnion,error:{message:"must match a schema in anyOf"}};return Qh.default=e,Qh}(),p=function(){if(Vh)return em;Vh=1,Object.defineProperty(em,"__esModule",{value:!0});const e=Cl(),t=Al(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:t})=>e._`{passingSchemas: ${t.passing}}`},code(n){const{gen:r,schema:s,parentSchema:o,it:a}=n;if(!Array.isArray(s))throw new Error("ajv implementation error");if(a.opts.discriminator&&o.discriminator)return;const i=s,c=r.let("valid",!1),d=r.let("passing",null),u=r.name("_valid");n.setParams({passing:d}),r.block(function(){i.forEach((s,o)=>{let i;(0,t.alwaysValidSchema)(a,s)?r.var(u,!0):i=n.subschema({keyword:"oneOf",schemaProp:o,compositeRule:!0},u),o>0&&r.if(e._`${u} && ${c}`).assign(c,!1).assign(d,e._`[${d}, ${o}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(d,o),i&&n.mergeEvaluated(i,e.Name)})})}),n.result(c,()=>n.reset(),()=>n.error(!0))}};return em.default=n,em}(),h=function(){if(Jh)return tm;Jh=1,Object.defineProperty(tm,"__esModule",{value:!0});const e=Al(),t={keyword:"allOf",schemaType:"array",code(t){const{gen:n,schema:r,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");const o=n.name("valid");r.forEach((n,r)=>{if((0,e.alwaysValidSchema)(s,n))return;const a=t.subschema({keyword:"allOf",schemaProp:r},o);t.ok(o),t.mergeEvaluated(a)})}};return tm.default=t,tm}(),m=function(){if(Kh)return nm;Kh=1,Object.defineProperty(nm,"__esModule",{value:!0});const e=Cl(),t=Al(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:t})=>e.str`must match "${t.ifClause}" schema`,params:({params:t})=>e._`{failingKeyword: ${t.ifClause}}`},code(n){const{gen:s,parentSchema:o,it:a}=n;void 0===o.then&&void 0===o.else&&(0,t.checkStrictMode)(a,'"if" without "then" and "else" is ignored');const i=r(a,"then"),c=r(a,"else");if(!i&&!c)return;const d=s.let("valid",!0),u=s.name("_valid");if(function(){const e=n.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},u);n.mergeEvaluated(e)}(),n.reset(),i&&c){const e=s.let("ifClause");n.setParams({ifClause:e}),s.if(u,l("then",e),l("else",e))}else i?s.if(u,l("then")):s.if((0,e.not)(u),l("else"));function l(t,r){return()=>{const o=n.subschema({keyword:t},u);s.assign(d,u),n.mergeValidEvaluated(o,d),r?s.assign(r,e._`${t}`):n.setParams({ifClause:t})}}n.pass(d,()=>n.error(!0))}};function r(e,n){const r=e.schema[n];return void 0!==r&&!(0,t.alwaysValidSchema)(e,r)}return nm.default=n,nm}(),f=function(){if(Bh)return rm;Bh=1,Object.defineProperty(rm,"__esModule",{value:!0});const e=Al(),t={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:n,it:r}){void 0===n.if&&(0,e.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};return rm.default=t,rm}();return kh.default=function(g=!1){const y=[u.default,l.default,p.default,h.default,m.default,f.default,a.default,i.default,o.default,c.default,d.default];return g?y.push(t.default,r.default):y.push(e.default,n.default),y.push(s.default),y},kh}var om,am,im={},cm={};function dm(){if(om)return cm;om=1,Object.defineProperty(cm,"__esModule",{value:!0});const e=Cl(),t={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:t})=>e.str`must match format "${t}"`,params:({schemaCode:t})=>e._`{format: ${t}}`},code(t,n){const{gen:r,data:s,$data:o,schema:a,schemaCode:i,it:c}=t,{opts:d,errSchemaPath:u,schemaEnv:l,self:p}=c;d.validateFormats&&(o?function(){const o=r.scopeValue("formats",{ref:p.formats,code:d.code.formats}),a=r.const("fDef",e._`${o}[${i}]`),c=r.let("fType"),u=r.let("format");r.if(e._`typeof ${a} == "object" && !(${a} instanceof RegExp)`,()=>r.assign(c,e._`${a}.type || "string"`).assign(u,e._`${a}.validate`),()=>r.assign(c,e._`"string"`).assign(u,a)),t.fail$data((0,e.or)(!1===d.strictSchema?e.nil:e._`${i} && !${u}`,function(){const t=l.$async?e._`(${a}.async ? await ${u}(${s}) : ${u}(${s}))`:e._`${u}(${s})`,r=e._`(typeof ${u} == "function" ? ${t} : ${u}.test(${s}))`;return e._`${u} && ${u} !== true && ${c} === ${n} && !${r}`}()))}():function(){const o=p.formats[a];if(!o)return void function(){if(!1!==d.strictSchema)throw new Error(e());function e(){return`unknown format "${a}" ignored in schema at path "${u}"`}p.logger.warn(e())}();if(!0===o)return;const[i,c,h]=function(t){const n=t instanceof RegExp?(0,e.regexpCode)(t):d.code.formats?e._`${d.code.formats}${(0,e.getProperty)(a)}`:void 0,s=r.scopeValue("formats",{key:a,ref:t,code:n});return"object"!=typeof t||t instanceof RegExp?["string",t,s]:[t.type||"string",t.validate,e._`${s}.validate`]}(o);i===n&&t.pass(function(){if("object"==typeof o&&!(o instanceof RegExp)&&o.async){if(!l.$async)throw new Error("async format in sync schema");return e._`await ${h}(${s})`}return"function"==typeof c?e._`${h}(${s})`:e._`${h}.test(${s})`}())}())}};return cm.default=t,cm}var um,lm,pm={};function hm(){if(lm)return Up;lm=1,Object.defineProperty(Up,"__esModule",{value:!0});const e=function(){if(Fp)return qp;Fp=1,Object.defineProperty(qp,"__esModule",{value:!0});const e=function(){if(Lp)return Hp;Lp=1,Object.defineProperty(Hp,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return Hp.default=e,Hp}(),t=function(){if(Zp)return Vp;Zp=1,Object.defineProperty(Vp,"__esModule",{value:!0}),Vp.callRef=Vp.getValidate=void 0;const e=Ep(),t=sp(),n=Cl(),r=Fl(),s=Tp(),o=Al(),a={keyword:"$ref",schemaType:"string",code(t){const{gen:r,schema:o,it:a}=t,{baseId:d,schemaEnv:u,validateName:l,opts:p,self:h}=a,{root:m}=u;if(("#"===o||"#/"===o)&&d===m.baseId)return function(){if(u===m)return c(t,l,u,u.$async);const e=r.scopeValue("root",{ref:m});return c(t,n._`${e}.validate`,m,m.$async)}();const f=s.resolveRef.call(h,m,d,o);if(void 0===f)throw new e.default(a.opts.uriResolver,d,o);return f instanceof s.SchemaEnv?function(e){const n=i(t,e);c(t,n,e,e.$async)}(f):function(e){const s=r.scopeValue("schema",!0===p.code.source?{ref:e,code:(0,n.stringify)(e)}:{ref:e}),a=r.name("valid"),i=t.subschema({schema:e,dataTypes:[],schemaPath:n.nil,topSchemaRef:s,errSchemaPath:o},a);t.mergeEvaluated(i),t.ok(a)}(f)}};function i(e,t){const{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):n._`${r.scopeValue("wrapper",{ref:t})}.validate`}function c(e,s,a,i){const{gen:c,it:d}=e,{allErrors:u,schemaEnv:l,opts:p}=d,h=p.passContext?r.default.this:n.nil;function m(e){const t=n._`${e}.errors`;c.assign(r.default.vErrors,n._`${r.default.vErrors} === null ? ${t} : ${r.default.vErrors}.concat(${t})`),c.assign(r.default.errors,n._`${r.default.vErrors}.length`)}function f(e){var t;if(!d.opts.unevaluated)return;const r=null===(t=null==a?void 0:a.validate)||void 0===t?void 0:t.evaluated;if(!0!==d.props)if(r&&!r.dynamicProps)void 0!==r.props&&(d.props=o.mergeEvaluated.props(c,r.props,d.props));else{const t=c.var("props",n._`${e}.evaluated.props`);d.props=o.mergeEvaluated.props(c,t,d.props,n.Name)}if(!0!==d.items)if(r&&!r.dynamicItems)void 0!==r.items&&(d.items=o.mergeEvaluated.items(c,r.items,d.items));else{const t=c.var("items",n._`${e}.evaluated.items`);d.items=o.mergeEvaluated.items(c,t,d.items,n.Name)}}i?function(){if(!l.$async)throw new Error("async schema referenced by sync schema");const r=c.let("valid");c.try(()=>{c.code(n._`await ${(0,t.callValidateCode)(e,s,h)}`),f(s),u||c.assign(r,!0)},e=>{c.if(n._`!(${e} instanceof ${d.ValidationError})`,()=>c.throw(e)),m(e),u||c.assign(r,!1)}),e.ok(r)}():e.result((0,t.callValidateCode)(e,s,h),()=>f(s),()=>m(s))}return Vp.getValidate=i,Vp.callRef=c,Vp.default=a,Vp}(),n=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return qp.default=n,qp}(),t=wh(),n=sm(),r=function(){if(am)return im;am=1,Object.defineProperty(im,"__esModule",{value:!0});const e=[dm().default];return im.default=e,im}(),s=(um||(um=1,Object.defineProperty(pm,"__esModule",{value:!0}),pm.contentVocabulary=pm.metadataVocabulary=void 0,pm.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],pm.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),pm),o=[e.default,t.default,(0,n.default)(),r.default,s.metadataVocabulary,s.contentVocabulary];return Up.default=o,Up}var mm,fm,gm={},ym={};var _m,vm={$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};function wm(){return _m||(_m=1,function(e,t){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;const n=Dp(),r=hm(),s=function(){if(fm)return gm;fm=1,Object.defineProperty(gm,"__esModule",{value:!0});const e=Cl(),t=(mm||(mm=1,Object.defineProperty(ym,"__esModule",{value:!0}),ym.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(n||(ym.DiscrError=n={}))),ym);var n;const r=Tp(),s=Ep(),o=Al(),a={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:n}})=>e===t.DiscrError.Tag?`tag "${n}" must be string`:`value of tag "${n}" must be in oneOf`,params:({params:{discrError:t,tag:n,tagName:r}})=>e._`{error: ${t}, tag: ${r}, tagValue: ${n}}`},code(n){const{gen:a,data:i,schema:c,parentSchema:d,it:u}=n,{oneOf:l}=d;if(!u.opts.discriminator)throw new Error("discriminator: requires discriminator option");const p=c.propertyName;if("string"!=typeof p)throw new Error("discriminator: requires propertyName");if(c.mapping)throw new Error("discriminator: mapping is not supported");if(!l)throw new Error("discriminator: requires oneOf keyword");const h=a.let("valid",!1),m=a.const("tag",e._`${i}${(0,e.getProperty)(p)}`);function f(t){const r=a.name("valid"),s=n.subschema({keyword:"oneOf",schemaProp:t},r);return n.mergeEvaluated(s,e.Name),r}a.if(e._`typeof ${m} == "string"`,()=>function(){const i=function(){var e;const t={},n=i(d);let a=!0;for(let t=0;t<l.length;t++){let d=l[t];if((null==d?void 0:d.$ref)&&!(0,o.schemaHasRulesButRef)(d,u.self.RULES)){const e=d.$ref;if(d=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),d instanceof r.SchemaEnv&&(d=d.schema),void 0===d)throw new s.default(u.opts.uriResolver,u.baseId,e)}const h=null===(e=null==d?void 0:d.properties)||void 0===e?void 0:e[p];if("object"!=typeof h)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${p}"`);a=a&&(n||i(d)),c(h,t)}if(!a)throw new Error(`discriminator: "${p}" must be required`);return t;function i({required:e}){return Array.isArray(e)&&e.includes(p)}function c(e,t){if(e.const)h(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${p}" must have "const" or "enum"`);for(const n of e.enum)h(n,t)}}function h(e,n){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${p}" values must be unique strings`);t[e]=n}}();a.if(!1);for(const t in i)a.elseIf(e._`${m} === ${t}`),a.assign(h,f(i[t]));a.else(),n.error(!1,{discrError:t.DiscrError.Mapping,tag:m,tagName:p}),a.endIf()}(),()=>n.error(!1,{discrError:t.DiscrError.Tag,tag:m,tagName:p})),n.ok(h)}};return gm.default=a,gm}(),o=vm,a=["/properties"],i="http://json-schema.org/draft-07/schema";class c extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(s.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const e=this.opts.$data?this.$dataMetaSchema(o,a):o;this.addMetaSchema(e,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var d=yp();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return d.KeywordCxt}});var u=Cl();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var l=wp();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return l.default}});var p=Ep();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})}(bl,bl.exports)),bl.exports}var bm,km,Em,$m=vl(wm()),Sm={exports:{}},Tm={},Om={},xm=(Em||(Em=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const n=(bm||(bm=1,function(e){function t(e,t){return{validate:e,compare:t}}Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0,e.fullFormats={date:t(s,o),time:t(i(!0),c),"date-time":t(l(!0),p),"iso-time":t(i(),d),"iso-date-time":t(l(),h),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:function(e){return m.test(e)&&f.test(e)},"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:function(e){if(w.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}},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:function(e){return g.lastIndex=0,g.test(e)},int32:{type:"number",validate:function(e){return Number.isInteger(e)&&e<=_&&e>=y}},int64:{type:"number",validate:function(e){return Number.isInteger(e)}},float:{type:"number",validate:v},double:{type:"number",validate:v},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"date-time":t(/^\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,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,d),"iso-date-time":t(/^\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,h),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},e.formatNames=Object.keys(e.fullFormats);const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,r=[0,31,28,31,30,31,30,31,31,30,31,30,31];function s(e){const t=n.exec(e);if(!t)return!1;const s=+t[1],o=+t[2],a=+t[3];return o>=1&&o<=12&&a>=1&&a<=(2===o&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(s)?29:r[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}const a=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function i(e){return function(t){const n=a.exec(t);if(!n)return!1;const r=+n[1],s=+n[2],o=+n[3],i=n[4],c="-"===n[5]?-1:1,d=+(n[6]||0),u=+(n[7]||0);if(d>23||u>59||e&&!i)return!1;if(r<=23&&s<=59&&o<60)return!0;const l=s-u*c,p=r-d*c-(l<0?1:0);return(23===p||-1===p)&&(59===l||-1===l)&&o<61}}function c(e,t){if(!e||!t)return;const n=new Date("2020-01-01T"+e).valueOf(),r=new Date("2020-01-01T"+t).valueOf();return n&&r?n-r:void 0}function d(e,t){if(!e||!t)return;const n=a.exec(e),r=a.exec(t);return n&&r?(e=n[1]+n[2]+n[3])>(t=r[1]+r[2]+r[3])?1:e<t?-1:0:void 0}const u=/t|\s/i;function l(e){const t=i(e);return function(e){const n=e.split(u);return 2===n.length&&s(n[0])&&t(n[1])}}function p(e,t){if(!e||!t)return;const n=new Date(e).valueOf(),r=new Date(t).valueOf();return n&&r?n-r:void 0}function h(e,t){if(!e||!t)return;const[n,r]=e.split(u),[s,a]=t.split(u),i=o(n,s);return void 0!==i?i||c(r,a):void 0}const m=/\/|:/,f=/^(?:[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,g=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm,y=-2147483648,_=2**31-1;function v(){return!0}const w=/[^\\]\\Z/}(Tm)),Tm),r=(km||(km=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=wm(),n=Cl(),r=n.operators,s={formatMaximum:{okStr:"<=",ok:r.LTE,fail:r.GT},formatMinimum:{okStr:">=",ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:"<",ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:">",ok:r.GT,fail:r.LTE}},o={message:({keyword:e,schemaCode:t})=>n.str`should be ${s[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>n._`{comparison: ${s[e].okStr}, limit: ${t}}`};e.formatLimitDefinition={keyword:Object.keys(s),type:"string",schemaType:"string",$data:!0,error:o,code(e){const{gen:r,data:o,schemaCode:a,keyword:i,it:c}=e,{opts:d,self:u}=c;if(!d.validateFormats)return;const l=new t.KeywordCxt(c,u.RULES.all.format.definition,"format");function p(e){return n._`${e}.compare(${o}, ${a}) ${s[i].fail} 0`}l.$data?function(){const t=r.scopeValue("formats",{ref:u.formats,code:d.code.formats}),s=r.const("fmt",n._`${t}[${l.schemaCode}]`);e.fail$data((0,n.or)(n._`typeof ${s} != "object"`,n._`${s} instanceof RegExp`,n._`typeof ${s}.compare != "function"`,p(s)))}():function(){const t=l.schema,s=u.formats[t];if(!s||!0===s)return;if("object"!=typeof s||s instanceof RegExp||"function"!=typeof s.compare)throw new Error(`"${i}": format "${t}" does not define "compare" function`);const o=r.scopeValue("formats",{key:t,ref:s,code:d.code.formats?n._`${d.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(p(o))}()},dependencies:["format"]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)}(Om)),Om),s=Cl(),o=new s.Name("fullFormats"),a=new s.Name("fastFormats"),i=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,o),e;const[s,i]="fast"===t.mode?[n.fastFormats,a]:[n.fullFormats,o];return c(e,t.formats||n.formatNames,s,i),t.keywords&&(0,r.default)(e),e};function c(e,t,n,r){var o,a;null!==(o=(a=e.opts.code).formats)&&void 0!==o||(a.formats=s._`require("ajv-formats/dist/formats").${r}`);for(const r of t)e.addFormat(r,n[r])}i.get=(e,t="full")=>{const r=("fast"===t?n.fastFormats:n.fullFormats)[e];if(!r)throw new Error(`Unknown format "${e}"`);return r},e.exports=t=i,Object.defineProperty(t,"__esModule",{value:!0}),t.default=i}(Sm,Sm.exports)),Sm.exports),Nm=vl(xm);class Im{constructor(e){this._ajv=e??function(){const e=new $m({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return Nm(e),e}()}getValidator(e){const t="$id"in e&&"string"==typeof e.$id?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}class Rm{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}class Pm extends yl{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Hd.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{const n=this._loggingLevels.get(t);return!!n&&this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n)},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new Im,this.setRequestHandler(xc,e=>this._oninitialize(e)),this.setNotificationHandler(Rc,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Jd,async(e,t)=>{const n=t.sessionId||t.requestInfo?.headers["mcp-session-id"]||void 0,{level:r}=e.params,s=Hd.safeParse(r);return s.success&&this._loggingLevels.set(n,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Rm(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=function(e,t){const n={...e};for(const e in t){const r=e,s=t[r];if(void 0===s)continue;const o=n[r];_l(o)&&_l(s)?n[r]={...o,...s}:n[r]=s}return n}(this._capabilities,e)}setRequestHandler(e,t){const n=ca(e),r=n?.method;if(!r)throw new Error("Schema is missing a method literal");let s;if(sa(r)){const e=r,t=e._zod?.def;s=t?.value??e.value}else{const e=r,t=e._def;s=t?.value??e.value}if("string"!=typeof s)throw new Error("Schema method literal must be a string");if("tools/call"===s){const n=async(e,n)=>{const r=aa(Ud,e);if(!r.success){const e=r.error instanceof Error?r.error.message:String(r.error);throw new Iu(pc.InvalidParams,`Invalid tools/call request: ${e}`)}const{params:s}=r.data,o=await Promise.resolve(t(e,n));if(s.task){const e=aa(Fc,o);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new Iu(pc.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const a=aa(Zd,o);if(!a.success){const e=a.error instanceof Error?a.error.message:String(a.error);throw new Iu(pc.InvalidParams,`Invalid tools/call result: ${e}`)}return a.data};return super.setRequestHandler(e,n)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){!function(e,t,n){if(!e)throw new Error(`${n} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${t})`)}}(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&function(e,t,n){if(!e)throw new Error(`${n} does not support task creation (required for ${t})`);if("tools/call"===t&&!e.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${t})`)}(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){const t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Vi.includes(t)?t:Hi,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},fc)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){const t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>"tool_result"===e.type),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,o=s?Array.isArray(s.content)?s.content:[s.content]:[],a=o.some(e=>"tool_use"===e.type);if(r){if(n.some(e=>"tool_result"!==e.type))throw new Error("The last message must contain only tool_result content if any is present");if(!a)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(a){const e=new Set(o.filter(e=>"tool_use"===e.type).map(e=>e.id)),t=new Set(n.filter(e=>"tool_result"===e.type).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},ou,t):this.request({method:"sampling/createMessage",params:e},su,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");const n=e;return this.request({method:"elicitation/create",params:n},wu,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");const n="form"===e.mode?e:{...e,mode:"form"},r=await this.request({method:"elicitation/create",params:n},wu,t);if("accept"===r.action&&r.content&&n.requestedSchema)try{const e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new Iu(pc.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){if(e instanceof Iu)throw e;throw new Iu(pc.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},xu,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}const Cm=Symbol.for("mcp.completable");function jm(e){return!!e&&"object"==typeof e&&Cm in e}var zm;!function(e){e.Completable="McpCompletable"}(zm||(zm={}));const Am=/^[A-Za-z0-9._-]{1,128}$/;function Mm(e){const t=function(e){const t=[];if(0===e.length)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!Am.test(e)){const n=e.split("").filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}(e);return function(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(const e of t)console.warn(` - ${e}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}(e,t.warnings),t.isValid}class Dm{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){const r={taskSupport:"required",...t.execution};if("forbidden"===r.taskSupport)throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}}class Lm{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Pm(e,t)}get experimental(){return this._experimental||(this._experimental={tasks:new Dm(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Vm(Dd)),this.server.assertCanSetRequestHandler(Vm(Ud)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Dd,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{const n={name:e,title:t.title,description:t.description,inputSchema:(()=>{const e=da(t.inputSchema);return e?ml(e,{strictUnions:!0,pipeStrategy:"input"}):Zm})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){const e=da(t.outputSchema);e&&(n.outputSchema=ml(e,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Ud,async(e,t)=>{try{const n=this._registeredTools[e.params.name];if(!n)throw new Iu(pc.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Iu(pc.InvalidParams,`Tool ${e.params.name} disabled`);const r=!!e.params.task,s=n.execution?.taskSupport,o="createTask"in n.handler;if(("required"===s||"optional"===s)&&!o)throw new Iu(pc.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if("required"===s&&!r)throw new Iu(pc.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if("optional"===s&&!r&&o)return await this.handleAutomaticTaskPolling(n,e,t);const a=await this.validateToolInput(n,e.params.arguments,e.params.name),i=await this.executeToolHandler(n,a,t);return r||await this.validateToolOutput(n,i,e.params.name),i}catch(e){if(e instanceof Iu&&e.code===pc.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;const r=da(e.inputSchema)??e.inputSchema,s=await ia(r,t);if(!s.success){const e=ua("error"in s?s.error:"Unknown error");throw new Iu(pc.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return s.data}async validateToolOutput(e,t,n){if(!e.outputSchema)return;if(!("content"in t))return;if(t.isError)return;if(!t.structuredContent)throw new Iu(pc.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);const r=da(e.outputSchema),s=await ia(r,t.structuredContent);if(!s.success){const e=ua("error"in s?s.error:"Unknown error");throw new Iu(pc.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){const r=e.handler;if("createTask"in r){if(!n.taskStore)throw new Error("No task store provided.");const s={...n,taskStore:n.taskStore};if(e.inputSchema){const e=r;return await Promise.resolve(e.createTask(t,s))}{const e=r;return await Promise.resolve(e.createTask(s))}}if(e.inputSchema){const e=r;return await Promise.resolve(e(t,n))}{const e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");const r=await this.validateToolInput(e,t.params.arguments,t.params.name),s=e.handler,o={...n,taskStore:n.taskStore},a=r?await Promise.resolve(s.createTask(r,o)):await Promise.resolve(s.createTask(o)),i=a.task.taskId;let c=a.task;const d=c.pollInterval??5e3;for(;"completed"!==c.status&&"failed"!==c.status&&"cancelled"!==c.status;){await new Promise(e=>setTimeout(e,d));const e=await n.taskStore.getTask(i);if(!e)throw new Iu(pc.InternalError,`Task ${i} not found during polling`);c=e}return await n.taskStore.getTaskResult(i)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Vm($u)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler($u,async e=>{switch(e.params.ref.type){case"ref/prompt":return function(e){if("ref/prompt"!==e.params.ref.type)throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return function(e){if("ref/resource"!==e.params.ref.type)throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Iu(pc.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){const n=this._registeredPrompts[t.name];if(!n)throw new Iu(pc.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new Iu(pc.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return Km;const r=ca(n.argsSchema),s=r?.[e.params.argument.name];if(!jm(s))return Km;const o=function(e){const t=e[Cm];return t?.complete}(s);return o?Jm(await o(e.params.argument.value,e.params.context)):Km}async handleResourceCompletion(e,t){const n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return Km;throw new Iu(pc.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?Jm(await r(e.params.argument.value,e.params.context)):Km}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Vm(od)),this.server.assertCanSetRequestHandler(Vm(id)),this.server.assertCanSetRequestHandler(Vm(ld)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(od,async(e,t)=>{const n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(const e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;const n=await e.resourceTemplate.listCallback(t);for(const t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(id,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(ld,async(e,t)=>{const n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new Iu(pc.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(const e of Object.values(this._registeredResourceTemplates)){const r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new Iu(pc.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Vm(kd)),this.server.assertCanSetRequestHandler(Vm(Sd)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(kd,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Hm(t.argsSchema):void 0}))})),this.server.setRequestHandler(Sd,async(e,t)=>{const n=this._registeredPrompts[e.params.name];if(!n)throw new Iu(pc.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Iu(pc.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){const r=da(n.argsSchema),s=await ia(r,e.params.arguments);if(!s.success){const t=ua("error"in s?s.error:"Unknown error");throw new Iu(pc.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}const o=s.data,a=n.callback;return await Promise.resolve(a(o,t))}{const e=n.callback;return await Promise.resolve(e(t))}}),this._promptHandlersInitialized=!0)}resource(e,t,...n){let r;"object"==typeof n[0]&&(r=n.shift());const s=n[0];if("string"==typeof t){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);const n=this._createRegisteredResource(e,void 0,t,r,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const n=this._createRegisteredResourceTemplate(e,void 0,t,r,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if("string"==typeof t){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);const s=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const s=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,t,n,r,s){const o={name:e,title:t,metadata:r,readCallback:s,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({uri:null}),update:e=>{void 0!==e.uri&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=o)),void 0!==e.name&&(o.name=e.name),void 0!==e.title&&(o.title=e.title),void 0!==e.metadata&&(o.metadata=e.metadata),void 0!==e.callback&&(o.readCallback=e.callback),void 0!==e.enabled&&(o.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=o,o}_createRegisteredResourceTemplate(e,t,n,r,s){const o={resourceTemplate:n,title:t,metadata:r,readCallback:s,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=o)),void 0!==t.title&&(o.title=t.title),void 0!==t.template&&(o.resourceTemplate=t.template),void 0!==t.metadata&&(o.metadata=t.metadata),void 0!==t.callback&&(o.readCallback=t.callback),void 0!==t.enabled&&(o.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=o;const a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),o}_createRegisteredPrompt(e,t,n,r,s){const o={title:t,description:n,argsSchema:void 0===r?void 0:oa(r),callback:s,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=o)),void 0!==t.title&&(o.title=t.title),void 0!==t.description&&(o.description=t.description),void 0!==t.argsSchema&&(o.argsSchema=oa(t.argsSchema)),void 0!==t.callback&&(o.callback=t.callback),void 0!==t.enabled&&(o.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=o,r&&Object.values(r).some(e=>jm(e instanceof g?e._def?.innerType:e))&&this.setCompletionRequestHandler(),o}_createRegisteredTool(e,t,n,r,s,o,a,i,c){Mm(e);const d={title:t,description:n,inputSchema:qm(r),outputSchema:qm(s),annotations:o,execution:a,_meta:i,handler:c,enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&("string"==typeof t.name&&Mm(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=d)),void 0!==t.title&&(d.title=t.title),void 0!==t.description&&(d.description=t.description),void 0!==t.paramsSchema&&(d.inputSchema=oa(t.paramsSchema)),void 0!==t.outputSchema&&(d.outputSchema=oa(t.outputSchema)),void 0!==t.callback&&(d.handler=t.callback),void 0!==t.annotations&&(d.annotations=t.annotations),void 0!==t._meta&&(d._meta=t._meta),void 0!==t.enabled&&(d.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,r,s;if("string"==typeof t[0]&&(n=t.shift()),t.length>1){const e=t[0];Um(e)?(r=t.shift(),t.length>1&&"object"==typeof t[0]&&null!==t[0]&&!Um(t[0])&&(s=t.shift())):"object"==typeof e&&null!==e&&(s=t.shift())}const o=t[0];return this._createRegisteredTool(e,void 0,n,r,void 0,s,{taskSupport:"forbidden"},void 0,o)}registerTool(e,t,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);const{title:r,description:s,inputSchema:o,outputSchema:a,annotations:i,_meta:c}=t;return this._createRegisteredTool(e,r,s,o,a,i,{taskSupport:"forbidden"},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n,r;"string"==typeof t[0]&&(n=t.shift()),t.length>1&&(r=t.shift());const s=t[0],o=this._createRegisteredPrompt(e,void 0,n,r,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);const{title:r,description:s,argsSchema:o}=t,a=this._createRegisteredPrompt(e,r,s,o,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return void 0!==this.server.transport}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}const Zm={type:"object",properties:{}};function Fm(e){return null!==e&&"object"==typeof e&&"parse"in e&&"function"==typeof e.parse&&"safeParse"in e&&"function"==typeof e.safeParse}function Um(e){return"object"==typeof e&&null!==e&&!function(e){return"_def"in e||"_zod"in e||Fm(e)}(e)&&(0===Object.keys(e).length||Object.values(e).some(Fm))}function qm(e){if(e)return Um(e)?oa(e):e}function Hm(e){const t=ca(e);return t?Object.entries(t).map(([e,t])=>{const n=function(e){return e.description}(t),r=function(e){if(sa(e)){const t=e;return"optional"===t._zod?.def?.type}const t=e;return"function"==typeof e.isOptional?e.isOptional():"ZodOptional"===t._def?.typeName}(t);return{name:e,description:n,required:!r}}):[]}function Vm(e){const t=ca(e),n=t?.method;if(!n)throw new Error("Schema is missing a method literal");const r=la(n);if("string"==typeof r)return r;throw new Error("Schema method literal must be a string")}function Jm(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const Km={completion:{values:[],hasMore:!1}};class Bm{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf("\n");if(-1===e)return null;const t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),function(e){return mc.parse(JSON.parse(e))}(t)}clear(){this._buffer=void 0}}class Wm{constructor(e=_.stdin,t=_.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new Bm,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{this.onerror?.(e)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{const e=this._readBuffer.readMessage();if(null===e)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),0===this._stdin.listenerCount("data")&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{const n=function(e){return JSON.stringify(e)+"\n"}(e);this._stdout.write(n)?t():this._stdout.once("drain",t)})}}class Gm{static exists(e){return i(e)}static writeJson(e,t){const r=n(e);c(r,{recursive:!0}),u(e,JSON.stringify(t,null,2),"utf8")}static readJson(e){if(!this.exists(e))throw new Error(`File not found: ${e}`);const t=a(e,"utf8");return JSON.parse(t)}static writeMarkdown(e,t){const r=n(e);c(r,{recursive:!0}),u(e,t,"utf8")}static formatKnowledgeAsMarkdown(e){return`# ${e.title}\n\n**ID:** ${e.id}\n**Summary:** ${e.summary}\n**Knowledge Type:** ${e.knowledge_type}\n**Status:** ${e.status}\n**Scope:** ${e.scope}\n**Source Type:** ${e.source_type}\n${e.source_file?`**Source File:** ${e.source_file}`:""}\n${e.commit_hash?`**Commit Hash:** ${e.commit_hash}`:""}\n${e.contributor?`**Contributor:** ${e.contributor}`:""}\n${e.created_at?`**Created At:** ${e.created_at}`:""}\n${e.updated_at?`**Updated At:** ${e.updated_at}`:""}\n\n## Content\n\n${e.content}\n`}static extractKnowledgeForJson(e){return{title:e.title,summary:e.summary,content:e.content,knowledge_type:e.knowledge_type,status:e.status,scope:e.scope,source_type:e.source_type,source_file:e.source_file||null,commit_hash:e.commit_hash||null,contributor:e.contributor||null}}}const Xm=C(),Ym=D("mcp-server","mcp-server");class Qm{constructor(){this.knowledgeManagement=new le,this.tempDir=Xm.tmp,this.server=new Lm({name:"knowledge-bank",version:q.version},{capabilities:{tools:{}}}),this.setupHandlers()}setupHandlers(){this.server.registerTool("knowledge_create",{description:"Create a new knowledge item",inputSchema:y.object({session_id:y.string().describe("Session ID for tracking, can be omitted to use env vars CLAUDE_SESSION_ID"),repository_id:y.number().describe("Repository ID"),title:y.string().optional().describe("Knowledge title"),summary:y.string().optional().describe("Knowledge summary"),content:y.string().optional().describe("Knowledge content"),scope:y.enum(k).optional().describe("Scope of knowledge"),source_type:y.enum(E).optional().describe("Source type"),knowledge_type:y.enum($).optional().describe("Knowledge type"),status:y.enum(S).optional().describe("Status of knowledge"),source_file:y.string().optional().describe("Source file path (optional)"),commit_hash:y.string().optional().describe("Commit hash (optional)"),contributor:y.string().optional().describe("Contributor name (optional)"),from:y.string().optional().describe("Load knowledge data from JSON file")})},async e=>await this.handleCreate(e)),this.server.registerTool("knowledge_get",{description:"Get a knowledge item by ID",inputSchema:y.object({id:y.number().describe("Knowledge item ID"),to:y.string().optional().describe("Save knowledge to markdown file")})},async e=>await this.handleGet(e)),this.server.registerTool("knowledge_update",{description:"Update a knowledge item",inputSchema:y.object({id:y.number().describe("Knowledge item ID"),title:y.string().optional().describe("Knowledge title"),summary:y.string().optional().describe("Knowledge summary"),content:y.string().optional().describe("Knowledge content"),scope:y.enum(k).optional().describe("Scope of knowledge"),source_type:y.enum(E).optional().describe("Source type"),knowledge_type:y.enum($).optional().describe("Knowledge type"),status:y.enum(S).optional().describe("Status of knowledge"),source_file:y.string().optional().describe("Source file path"),commit_hash:y.string().optional().describe("Commit hash"),contributor:y.string().optional().describe("Contributor name"),from:y.string().optional().describe("Load update data from JSON file")})},async e=>await this.handleUpdate(e)),this.server.registerTool("knowledge_delete",{description:"Delete a knowledge item",inputSchema:y.object({id:y.number().describe("Knowledge item ID")})},async e=>await this.handleDelete(e)),this.server.registerTool("knowledge_list",{description:"List knowledge items with optional filters",inputSchema:y.object({scope:y.enum(k).optional().describe("Filter by scope"),status:y.enum(S).optional().describe("Filter by status"),knowledge_type:y.enum($).optional().describe("Filter by knowledge type"),limit:y.number().default(100).describe("Limit number of results"),offset:y.number().default(0).describe("Offset for pagination"),to:y.string().optional().describe("Save results to JSON file")})},async e=>await this.handleList(e)),this.server.registerTool("knowledge_search",{description:"Search knowledge items by text query",inputSchema:y.object({query:y.array(y.string()).describe("Search query terms"),limit:y.number().default(10).describe("Limit number of results"),to:y.string().optional().describe("Save results to JSON file")})},async e=>await this.handleSearch(e)),this.server.registerTool("knowledge_update_status",{description:"Update knowledge item status",inputSchema:y.object({id:y.number().describe("Knowledge item ID"),status:y.enum(S).describe("New status")})},async e=>await this.handleUpdateStatus(e)),this.server.registerTool("knowledge_stats",{description:"Get knowledge statistics",inputSchema:y.object({})},async()=>await this.handleStats())}async handleCreate(e){let n=e;if(e.from){const r=t.join(this.tempDir,e.from);if(!Gm.exists(r))return{content:[{type:"text",text:JSON.stringify({error:`File not found: ${r}`},null,2)}],isError:!0};try{n=Gm.readJson(r)}catch(e){return{content:[{type:"text",text:JSON.stringify({error:`Error reading JSON file: ${e.message}`},null,2)}],isError:!0}}}if(!(n.title&&n.summary&&n.content&&n.scope&&n.source_type&&n.knowledge_type&&n.status))return{content:[{type:"text",text:JSON.stringify({error:"Missing required fields: title, summary, content, scope, source_type, knowledge_type, status"},null,2)}],isError:!0};const r=await ue.repositoryManager.getCurrentRepository(),s=await this.knowledgeManagement.create({title:n.title,summary:n.summary,content:n.content,scope:n.scope,source_type:n.source_type,knowledge_type:n.knowledge_type,status:n.status,source_file:n.source_file,commit_hash:n.commit_hash,contributor:n.contributor,repository_id:r.id,session_id:process.env.CLAUDE_SESSION_ID||n.session_id||"unknown-session"});if(e.from){const n=t.join(this.tempDir,e.from);return{content:[{type:"text",text:JSON.stringify({id:s.id,title:s.title,message:`Knowledge item created from ${e.from}`,file_path:n},null,2)}]}}return{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}async handleGet(e){const n=await this.knowledgeManagement.get(e.id);if(!n)return{content:[{type:"text",text:JSON.stringify({error:"Knowledge item not found"},null,2)}],isError:!0};if(e.to)try{const r=t.join(this.tempDir,e.to),s=Gm.formatKnowledgeAsMarkdown(n);return Gm.writeMarkdown(r,s),{content:[{type:"text",text:JSON.stringify({success:!0,message:`Knowledge item ${e.id} saved to ${e.to}`,file_path:r},null,2)}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({error:`Error saving file: ${e.message}`},null,2)}],isError:!0}}return{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}async handleUpdate(e){const{id:n,from:r,...s}=e;let o=s;if(r){const e=t.join(this.tempDir,r);if(!Gm.exists(e))return{content:[{type:"text",text:JSON.stringify({error:`File not found: ${e}`},null,2)}],isError:!0};try{o={...Gm.readJson(e),...s}}catch(e){return{content:[{type:"text",text:JSON.stringify({error:`Error reading JSON file: ${e.message}`},null,2)}],isError:!0}}}const a=await this.knowledgeManagement.update(n,o);return{content:[{type:"text",text:JSON.stringify(a,null,2)}]}}async handleDelete(e){return await this.knowledgeManagement.delete(e.id),{content:[{type:"text",text:JSON.stringify({success:!0,message:"Knowledge item deleted successfully"})}]}}async handleList(e={}){const{to:n,...r}=e,s=await this.knowledgeManagement.list(r);if(n)try{const e=t.join(this.tempDir,n),o=s.map(e=>Gm.extractKnowledgeForJson(e));return Gm.writeJson(e,{count:s.length,filters:r,timestamp:(new Date).toISOString(),data:o}),{content:[{type:"text",text:JSON.stringify({success:!0,message:`${s.length} knowledge items saved to ${n}`,file_path:e},null,2)}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({error:`Error saving file: ${e.message}`},null,2)}],isError:!0}}return{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}async handleSearch(e){const{to:n,query:r,limit:s}=e,o=await this.knowledgeManagement.search(r,s);if(n)try{const e=t.join(this.tempDir,n),a=o.map(e=>Gm.extractKnowledgeForJson(e));return Gm.writeJson(e,{query:r,limit:s,count:o.length,timestamp:(new Date).toISOString(),data:a}),{content:[{type:"text",text:JSON.stringify({success:!0,message:`Search results (${o.length} items) saved to ${n}`,file_path:e},null,2)}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({error:`Error saving file: ${e.message}`},null,2)}],isError:!0}}return{content:[{type:"text",text:JSON.stringify(o,null,2)}]}}async handleUpdateStatus(e){const t=await this.knowledgeManagement.updateStatus(e.id,e.status);return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async handleStats(){const e=await this.knowledgeManagement.getStats();return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}async run(){const e=new Wm;await this.server.connect(e),Ym.logWarn(`Knowledge Bank MCP server running under ${process.cwd()}`)}}const ef=D("web-server","web-server"),tf=l(import.meta.url),nf=n(tf);class rf{constructor(e={}){this.port=e.port||3e3,this.isDev=e.dev||!1,this.app=v(),this.database=X(),this.db=this.database.getConnection(),this.server=null,this.connections=new Set,this.md=new b,this.setupApp()}setupApp(){this.app.set("view engine","ejs");const e=this.isDev?r(nf,"views"):r(nf,"web");this.app.set("views",e),this.app.use(w),this.app.set("layout","layout");const t=this.isDev?r(nf,"public"):r(nf,"web/public");this.app.use(v.static(t)),this.app.use(v.json()),this.app.use(v.urlencoded({extended:!0})),this.app.locals.formatTimestamp=this.formatTimestamp,this.app.locals.renderMarkdown=this.renderMarkdown.bind(this),this.app.locals.formatJsonAsMarkdown=this.formatJsonAsMarkdown.bind(this),this.setupRoutes()}async reconnect(){try{return ef.logInfo("Reconnecting to database..."),this.database.close(),this.db=this.database.getConnection(),ef.logInfo("Database reconnection successful"),!0}catch(e){throw ef.logError("Database reconnection failed:",e),e}}formatTimestamp(e){const t=new Date(parseInt(e));return isNaN(t)?e:`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")} ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}`}renderMarkdown(e){return e?this.md.render(e):""}formatJsonAsMarkdown(e){if(!e)return"";try{const t=JSON.parse(e),n=`\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``;return this.md.render(n)}catch(t){const n=`\`\`\`\n${e}\n\`\`\``;return this.md.render(n)}}setupRoutes(){this.app.get("/api/render/cell",(e,t)=>{const{tableName:n,col:r,value:s}=e.query;t.render("partials/cell",{tableName:n,col:r,val:s,layout:!1})}),this.app.get("/api/render/details",async(e,t)=>{const{tableName:n,id:r}=e.query,s=this.getRowById(n,r);if(!s)return t.status(404).send("Not found");t.render("partials/row-details",{tableName:n,data:s,layout:!1,renderMarkdown:this.renderMarkdown.bind(this),formatJsonAsMarkdown:this.formatJsonAsMarkdown.bind(this),formatTimestamp:this.formatTimestamp})}),this.app.get("/",(e,t)=>{const n=this.getTableNames().map(e=>({name:e,count:this.getTableCount(e)})),r=this.getRepositoriesWithCounts();t.render("index",{title:"Knowledge Bank Repository Browser",tableInfo:n,repositoryData:r,formatTimestamp:function(e){const t=new Date(parseInt(e));return isNaN(t)?e:`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")} ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}`},layout:"layout"})}),this.app.get("/repository/:id",(e,t)=>{try{const{id:n}=e.params,r=this.getRowById("repository",n);if(!r)return t.status(404).render("error",{title:"Error",error:"Repository not found",layout:"layout"});const s=this.getSessionsByRepository(n),o=this.getKnowledgeItemsByRepository(n),a=this.getHookEventsByRepository(n);function i(e){const t=new Date(parseInt(e));return isNaN(t)?e:`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")} ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}`}t.render("repository",{title:`Repository: ${r.name}`,repository:r,sessions:s,knowledgeItems:o,hookEvents:a,formatTimestamp:i,layout:"layout"})}catch(c){ef.logError(`Error viewing repository ${e.params.id}:`,c),t.status(500).render("error",{title:"Error",error:c.message,layout:"layout"})}}),this.app.get("/api/tables",(e,t)=>{try{const e=this.getTableNames();t.json({tables:e})}catch(e){ef.logError("Error getting tables:",e),t.status(500).json({error:e.message})}}),this.app.get("/api/tables/:table/schema",(e,t)=>{try{const{table:n}=e.params,r=this.getTableSchema(n);t.json({schema:r})}catch(e){ef.logError("Error getting table schema:",e),t.status(500).json({error:e.message})}}),this.app.get("/api/tables/:table/data",(e,t)=>{try{const{table:n}=e.params,r=parseInt(e.query.page)||1,s=parseInt(e.query.limit)||100,o=(r-1)*s,a={};if(e.query.repository_id){const t=parseInt(e.query.repository_id);isNaN(t)||(a.repository_id=t)}e.query.session_id&&(a.session_id=e.query.session_id),e.query.knowledge_type&&(a.knowledge_type=e.query.knowledge_type),e.query.status&&(a.status=e.query.status),e.query.branch&&(a.branch=e.query.branch),e.query.name&&(a.name=e.query.name),e.query.title&&(a.title=e.query.title),e.query.search&&(a.search=e.query.search);const i=e.query.sort||"",c=this.getTableData(n,s,o,a,i),d=this.getTableCount(n,a);t.json({data:c,pagination:{page:r,limit:s,total:d,pages:Math.ceil(d/s)}})}catch(e){ef.logError("Error getting table data:",e),t.status(500).json({error:e.message})}}),this.app.get("/api/tables/:table/row/:id",(e,t)=>{try{const{table:n,id:r}=e.params,s=this.getRowById(n,r);if(!s)return t.status(404).json({error:"Row not found"});t.json({data:s})}catch(n){ef.logError(`Error getting row from ${e.params.table}:`,n),t.status(500).json({error:n.message})}}),this.app.get("/api/tables/:table/relations",(e,t)=>{try{const{table:n}=e.params,r=this.getTableRelations(n);t.json({relations:r})}catch(e){ef.logError("Error getting table relations:",e),t.status(500).json({error:e.message})}}),this.app.get("/api/relations",(e,t)=>{try{const e=this.getDatabaseRelations();t.json({relations:e})}catch(e){ef.logError("Error getting database relations:",e),t.status(500).json({error:e.message})}}),this.app.post("/api/reconnect",async(e,t)=>{try{await this.reconnect(),t.json({success:!0,message:"Database reconnected successfully"})}catch(e){t.status(500).json({success:!1,error:e.message})}}),this.app.get("/tables/:table",(e,t)=>{try{const{table:n}=e.params,r=this.getTableSchema(n),s=this.getTableRelations(n),o=e.query.sort||"",a=this.parseSortParameter(o),i=this.getTableData(n,10,0,{},o),c=this.getEssentialColumns(n,r);t.render("table",{title:`Table: ${n}`,tableName:n,schema:r,relations:s,sampleData:i,essentialColumns:c,sortInfo:a,layout:"layout"})}catch(n){ef.logError(`Error viewing table ${e.params.table}:`,n),t.status(500).render("error",{title:"Error",error:n.message,layout:"layout"})}})}getTableNames(){const e=["hook_event","knowledge_item","repository","session","knowledge_item_fts"];return this.db.prepare("\n SELECT name FROM sqlite_master\n WHERE type = 'table' AND name NOT LIKE 'sqlite_%'\n ORDER BY name\n ").all().map(e=>e.name).filter(t=>e.includes(t))}getTableSchema(e){return this.db.prepare(`PRAGMA table_info(${e})`).all()}parseSortParameter(e){return e?e.endsWith("_asc")?{column:e.slice(0,-4),direction:"ASC",oppositeDirection:"DESC"}:e.endsWith("_desc")?{column:e.slice(0,-5),direction:"DESC",oppositeDirection:"ASC"}:{column:e,direction:"ASC",oppositeDirection:"DESC"}:{column:null,direction:null,oppositeDirection:null}}getTableData(e,t=100,n=0,r={},s=""){if("hook_event"===e&&r.repository_id)return this.getHookEventsByRepositoryPaginated(r.repository_id,t,n,s,r);let o="*";"knowledge_item"===e?o="repository_id, session_id, id, title, summary, scope, source_type, knowledge_type, status, created_at, updated_at":"repository"===e?o="id, name, remote_url, created_at, updated_at":"session"===e?o="id, session_id, repository_id, working_directory, branch, created_at":"hook_event"===e&&(o="session_id, id, name, created_at");let a="";const i=[];if(Object.keys(r).length>0){const t=(t=>{const n=[],r=[];return Object.entries(t).forEach(([t,s])=>{if(null!=s&&""!==s&&("hook_event"!==e||"repository_id"!==t))if("search"!==t){if("session_id"===t||"branch"===t||"name"===t||"title"===t)return n.push(`${t} LIKE ?`),void r.push(`%${s}%`);n.push(`${t} = ?`),r.push(s)}else if("knowledge_item"===e){n.push("(title LIKE ? OR summary LIKE ? OR content LIKE ? OR session_id LIKE ?)");const e=`%${s}%`;r.push(e,e,e,e)}else if("session"===e){n.push("(session_id LIKE ? OR branch LIKE ? OR working_directory LIKE ?)");const e=`%${s}%`;r.push(e,e,e)}else if("hook_event"===e){n.push("(name LIKE ? OR session_id LIKE ?)");const e=`%${s}%`;r.push(e,e)}}),{clause:n.length>0?` WHERE ${n.join(" AND ")}`:"",params:r}})(r);a=t.clause,i.push(...t.params)}let c="";if(s){const e=this.parseSortParameter(s);e.column&&e.direction&&(c=` ORDER BY ${e.column} ${e.direction}`)}else c=" ORDER BY id ASC";console.log(`[DEBUG] Table: ${e}, Query: SELECT ${o} FROM ${e}${a}${c}, Params:`,i),i.push(t,n);const d=this.db.prepare(`SELECT ${o} FROM ${e}${a}${c} LIMIT ? OFFSET ?`).all(...i);return"repository"===e&&d.forEach(e=>{const t=this.db.prepare("SELECT COUNT(*) as count FROM session WHERE repository_id = ?").get(e.id);e.sessionCount=t?t.count:0;const n=this.db.prepare("SELECT COUNT(*) as count FROM knowledge_item WHERE repository_id = ?").get(e.id);e.knowledgeCount=n?n.count:0}),d}getTableCount(e,t={}){if("hook_event"===e&&t.repository_id){let e=" WHERE s.repository_id = ?";const n=[t.repository_id];if(t.session_id&&(e+=" AND h.session_id LIKE ?",n.push(`%${t.session_id}%`)),t.name&&(e+=" AND h.name LIKE ?",n.push(`%${t.name}%`)),t.search){e+=" AND (h.name LIKE ? OR h.session_id LIKE ?)";const r=`%${t.search}%`;n.push(r,r)}return this.db.prepare(`SELECT COUNT(*) as count FROM hook_event h JOIN session s ON h.session_id = s.session_id${e}`).get(...n).count}let n="";const r=[];if(Object.keys(t).length>0){const s=[];Object.entries(t).forEach(([t,n])=>{if(null!=n&&""!==n&&("hook_event"!==e||"repository_id"!==t))if("search"!==t){if("session_id"===t||"branch"===t||"name"===t||"title"===t)return s.push(`${t} LIKE ?`),void r.push(`%${n}%`);s.push(`${t} = ?`),r.push(n)}else if("knowledge_item"===e){s.push("(title LIKE ? OR summary LIKE ? OR content LIKE ? OR session_id LIKE ?)");const e=`%${n}%`;r.push(e,e,e,e)}else if("session"===e){s.push("(session_id LIKE ? OR branch LIKE ? OR working_directory LIKE ?)");const e=`%${n}%`;r.push(e,e,e)}else if("hook_event"===e){s.push("(name LIKE ? OR session_id LIKE ?)");const e=`%${n}%`;r.push(e,e)}}),s.length>0&&(n=` WHERE ${s.join(" AND ")}`)}return this.db.prepare(`SELECT COUNT(*) as count FROM ${e}${n}`).get(...r).count}getRowById(e,t){return this.db.prepare(`SELECT * FROM ${e} WHERE id = ?`).get(t)}getEssentialColumns(e,t){const n=t.map(e=>e.name);return({knowledge_item:["id","title","summary","knowledge_type","status","repository_id","created_at"],repository:["id","name","created_at"],session:["id","session_id","branch","working_directory","repository_id","created_at"],hook_event:["id","session_id","name","created_at"],sync_status:["id","repository_id","last_sync_at"],knowledge_item_fts:["rowid","title","summary"]}[e]||["id","name","title","created_at"]).filter(e=>n.includes(e))}getTableRelations(e){return this.db.prepare(`PRAGMA foreign_key_list(${e})`).all()}getDatabaseRelations(){const e=this.getTableNames(),t={};return e.forEach(e=>{t[e]={foreignKeys:this.getTableRelations(e),referencedBy:[]}}),e.forEach(e=>{t[e].foreignKeys.forEach(n=>{const r=n.table;t[r]&&t[r].referencedBy.push({table:e,from:n.from,to:n.to})})}),t}getRepositoriesWithCounts(){try{const e=this.getTableData("repository",100,0);return e.forEach(e=>{const t=this.db.prepare("SELECT COUNT(*) as count FROM session WHERE repository_id = ?").get(e.id);e.sessionCount=t?t.count:0;const n=this.db.prepare("SELECT COUNT(*) as count FROM knowledge_item WHERE repository_id = ?").get(e.id);e.knowledgeCount=n?n.count:0}),e}catch(e){return ef.logError("Error getting repositories with counts:",e),[]}}getSessionsByRepository(e){try{return this.db.prepare("SELECT id, session_id, working_directory, branch, created_at FROM session WHERE repository_id = ? ORDER BY created_at DESC LIMIT 100").all(e)}catch(t){return ef.logError(`Error getting sessions for repository ${e}:`,t),[]}}getKnowledgeItemsByRepository(e){try{return this.db.prepare("SELECT id, title, summary, scope, source_type, knowledge_type, status, created_at FROM knowledge_item WHERE repository_id = ? ORDER BY created_at DESC LIMIT 100").all(e)}catch(t){return ef.logError(`Error getting knowledge items for repository ${e}:`,t),[]}}getHookEventsByRepository(e){try{return this.db.prepare("SELECT h.id, h.session_id, h.name, h.created_at FROM hook_event h JOIN session s ON h.session_id = s.session_id WHERE s.repository_id = ? ORDER BY h.created_at DESC LIMIT 100").all(e)}catch(t){return ef.logError(`Error getting hook events for repository ${e}:`,t),[]}}getHookEventsByRepositoryPaginated(e,t=10,n=0,r="",s={}){try{let o=" WHERE s.repository_id = ?";const a=[e];if(s.session_id&&(o+=" AND h.session_id LIKE ?",a.push(`%${s.session_id}%`)),s.name&&(o+=" AND h.name LIKE ?",a.push(`%${s.name}%`)),s.search){o+=" AND (h.name LIKE ? OR h.session_id LIKE ?)";const e=`%${s.search}%`;a.push(e,e)}let i="";if(r){const e=this.parseSortParameter(r);e.column&&e.direction&&(i=` ORDER BY h.${e.column} ${e.direction}`)}else i=" ORDER BY h.id ASC";return a.push(t,n),this.db.prepare(`SELECT h.id, h.session_id, h.name, h.created_at\n FROM hook_event h\n JOIN session s ON h.session_id = s.session_id\n ${o}${i}\n LIMIT ? OFFSET ?`).all(...a)}catch(t){return ef.logError(`Error getting paginated hook events for repository ${e}:`,t),[]}}start(){return new Promise((e,t)=>{try{I(this.db),this.server=this.app.listen(this.port,()=>{this.isDev?(ef.logInfo(`Web server started in development mode on port ${this.port}`),ef.logInfo("🚀 Running from source code (no build required)")):ef.logInfo(`Web server started on port ${this.port}`),ef.logInfo(`Open http://localhost:${this.port} in your browser`),e(this)}),this.server.on("connection",e=>{this.connections.add(e),e.on("close",()=>{this.connections.delete(e)})})}catch(e){ef.logError("Error starting web server:",e),t(e)}})}stop(){return new Promise((e,t)=>{if(!this.server)return void e();const n=setTimeout(()=>{ef.logWarn("Forcing server shutdown due to timeout");for(const e of this.connections)e.destroy();this.connections.clear(),this.server=null,e()},5e3);this.server.close(r=>{if(clearTimeout(n),r){ef.logError("Error closing web server:",r);for(const e of this.connections)e.destroy();this.connections.clear(),t(r)}else ef.logInfo("Web server stopped gracefully"),this.server=null,this.connections.clear(),e()}),this.server.unref()})}}const sf=D("web-command","web-command"),of=q.version,af=C(),cf=new e;cf.name("knowledge-bank").description("Claude Code plugin for lightweight knowledge management").version(of);const df=new le;cf.command("install").description("Install knowledge bank plugin").action(async()=>{await async function(){K().then(e=>e.find(e=>"knowledge-bank"===e.name)).then(async e=>{e||await new Promise((e,t)=>{p(`claude plugin marketplace add ${U}`,(n,r,s)=>{n?t(n):(s&&console.error(s),console.log(r),e())})}),await new Promise((e,t)=>{p("claude plugin install core@knowledge-bank",(n,r,s)=>{n?t(n):(s&&console.error(s),console.log(r),e())})})}).then(async()=>{await async function(){await ae.prepare(),ae.initialize()}()}).catch(e=>{console.error("Error during installation:",e)})}()}),cf.command("uninstall").description("Remove knowledge bank plugin").action(async()=>{await async function(){K().then(e=>e.find(e=>"knowledge-bank"===e.name)).then(async e=>{e?(await new Promise((e,t)=>{p("claude plugin uninstall core@knowledge-bank",(n,r,s)=>{n?t(n):(s&&console.error(s),console.log(r),e())})}),await new Promise((e,t)=>{p("claude plugin marketplace remove knowledge-bank",(n,r,s)=>{n?t(n):(s&&console.error(s),console.log(r),e())})})):console.log("knowledge-bank plugin is not installed.")}).catch(e=>{console.error("Error during uninstallation:",e)})}()}),cf.command("knowledge-status").description("Display knowledge bank status and statistics").addHelpText("after","\nOutput Example:\nKnowledge Bank Status:\nDatabase: ✓ Connected\nTotal Items: 156\nRecent Activity: 12 created, 8 updated (last 7 days)\n\nBy Scope:\n- Personal: 45\n- Project: 89\n- Organization: 22\n\nBy Status:\n- Draft: 67\n- Suggested: 34\n- Verified: 55\n\nBy Type:\n- Code Pattern: 42\n- Architecture: 38\n- Configuration: 25\n- Pitfall: 31\n- API Usage: 20").action(async()=>{await async function(){console.log("📚 Knowledge Bank Status\n");const e=ae.database.getPath(),t=ae.database.exists();if(console.log(`Database: ${e}`),console.log(`Status: ${t?"✓ Connected":"✗ Not found"}\n`),await ue.gitUtils.isGitRepository()){const e=await ue.repositoryManager.getCurrentRepository(),t=await ue.gitUtils.getCurrentBranch();console.log("Current Repository:"),console.log(` Name: ${e.name}`),console.log(` Branch: ${t}`),console.log(` Remote: ${e.remote_url}\n`);const n={total:ce.knowledgeRepo.count({repository_id:e.id}),by_status:{draft:ce.knowledgeRepo.count({repository_id:e.id,status:"draft"}),suggested:ce.knowledgeRepo.count({repository_id:e.id,status:"suggested"}),verified:ce.knowledgeRepo.count({repository_id:e.id,status:"verified"})},by_scope:{personal:ce.knowledgeRepo.count({repository_id:e.id,scope:"personal"}),project:ce.knowledgeRepo.count({repository_id:e.id,scope:"project"}),organization:ce.knowledgeRepo.count({repository_id:e.id,scope:"organization"})}};console.log("Knowledge Statistics:"),console.log(` Total: ${n.total}`),console.log(" By Status:"),console.log(` - Draft: ${n.by_status.draft}`),console.log(` - Suggested: ${n.by_status.suggested}`),console.log(` - Verified: ${n.by_status.verified}`),console.log(" By Scope:"),console.log(` - Personal: ${n.by_scope.personal}`),console.log(` - Project: ${n.by_scope.project}`),console.log(` - Organization: ${n.by_scope.organization}\n`);const r=de.sessionRepo.getRecentSessions(5);console.log(`Recent Sessions: ${r.length}`),r.length>0&&r.forEach((e,t)=>{const n=new Date(e.updated_at).toLocaleString();console.log(` ${t+1}. ${e.session_id.substring(0,8)}... (${n})`)})}else{console.log("Not in a Git repository\n");const e=ce.knowledgeRepo.count({});console.log("Global Knowledge Statistics:"),console.log(` Total: ${e}`)}}()});const uf=cf.command("knowledge").description("Manage knowledge items");uf.command("create").description("Create a new knowledge item").requiredOption("-t, --title <title>","[REQUIRED] Knowledge title").requiredOption("-s, --summary <summary>","[REQUIRED] Knowledge summary").requiredOption("-c, --content <content>","[REQUIRED] Knowledge content").requiredOption("--scope <scope>",`[REQUIRED] Scope: ${k.join(", ")}`).requiredOption("--source-type <type>",`[REQUIRED] Source type: ${E.join(", ")}`).requiredOption("--knowledge-type <type>",`[REQUIRED] Knowledge type: ${$.join(", ")}`).requiredOption("--status <status>",`[REQUIRED] Status: ${S.join(", ")}`).option("--source-file <file>","[OPTION] Source file path").option("--commit-hash <hash>","[OPTION] Commit hash").option("--contributor <contributor>","[OPTION] Contributor name").addHelpText("after",'\nOutput Example:\n{\n "id": 123,\n "title": "React Custom Hook Pattern",\n "summary": "Best practices for custom hooks",\n "content": "Always prefix with \'use\' and follow hooks rules",\n "scope": "project",\n "source_type": "ai",\n "knowledge_type": "code_pattern",\n "status": "draft",\n "source_file": null,\n "commit_hash": null,\n "contributor": null,\n "created_at": "2026-01-22T10:30:00Z",\n "updated_at": "2026-01-22T10:30:00Z"\n}').action(async e=>{console.log("creating knowledge");const t=await df.create({title:e.title,summary:e.summary,content:e.content,scope:e.scope,source_type:e.sourceType,knowledge_type:e.knowledgeType,status:e.status,source_file:e.sourceFile,commit_hash:e.commitHash,contributor:e.contributor});console.log(JSON.stringify(t,null,2))}),uf.command("get").description("Get a knowledge item by ID").argument("<id>","Knowledge item ID",parseInt).addHelpText("after",'\nOutput Example:\n{\n "id": 123,\n "title": "React Custom Hook Pattern",\n "summary": "Best practices for custom hooks",\n "content": "Always prefix with \'use\' and follow hooks rules",\n "scope": "project",\n "source_type": "ai",\n "knowledge_type": "code_pattern",\n "status": "verified",\n "source_file": "src/hooks/useCustomHook.ts",\n "commit_hash": "abc123def",\n "contributor": "Claude",\n "created_at": "2026-01-22T10:30:00Z",\n "updated_at": "2026-01-22T11:45:00Z"\n}').action(async e=>{const t=await df.get(e);t?console.log(JSON.stringify(t,null,2)):(console.log("Knowledge item not found"),process.exit(1))}),uf.command("update").description("Update a knowledge item").argument("<id>","Knowledge item ID",parseInt).option("-t, --title <title>","[OPTION] Knowledge title").option("-s, --summary <summary>","[OPTION] Knowledge summary").option("-c, --content <content>","[OPTION] Knowledge content").option("--scope <scope>",`[OPTION] Scope: ${k.join(", ")}`).option("--source-type <type>",`[OPTION] Source type: ${E.join(", ")}`).option("--knowledge-type <type>",`[OPTION] Knowledge type: ${$.join(", ")}`).option("--status <status>",`[OPTION] Status: ${S.join(", ")}`).option("--source-file <file>","[OPTION] Source file path").option("--commit-hash <hash>","[OPTION] Commit hash").option("--contributor <contributor>","[OPTION] Contributor name").addHelpText("after",'\nOutput Example:\n{\n "id": 123,\n "title": "Updated React Hook Pattern",\n "summary": "Enhanced best practices for custom hooks",\n "content": "Always prefix with \'use\', follow hooks rules, and add proper TypeScript types",\n "scope": "project",\n "source_type": "ai",\n "knowledge_type": "code_pattern",\n "status": "verified",\n "source_file": "src/hooks/useCustomHook.ts",\n "commit_hash": "def456ghi",\n "contributor": "Claude",\n "created_at": "2026-01-22T10:30:00Z",\n "updated_at": "2026-01-22T12:15:00Z"\n}').action(async(e,t)=>{const n=await df.update(e,{title:t.title,summary:t.summary,content:t.content,scope:t.scope,source_type:t.sourceType,knowledge_type:t.knowledgeType,status:t.status,source_file:t.sourceFile,commit_hash:t.commitHash,contributor:t.contributor});console.log(JSON.stringify(n,null,2))}),uf.command("delete").description("Delete a knowledge item").argument("<id>","Knowledge item ID",parseInt).addHelpText("after","\nOutput Example:\nKnowledge item deleted successfully").action(async e=>{await df.delete(e),console.log("Knowledge item deleted successfully")}),uf.command("list").description("List knowledge items").option("--scope <scope>","[OPTION] Filter by scope").option("--status <status>","[OPTION] Filter by status").option("--knowledge-type <type>","[OPTION] Filter by knowledge type").option("--limit <limit>","[OPTION] Limit number of results",parseInt,100).option("--offset <offset>","[OPTION] Offset for pagination",parseInt,0).addHelpText("after",'\nOutput Example:\n{\n "items": [\n {\n "id": 123,\n "title": "React Custom Hook Pattern",\n "summary": "Best practices for custom hooks",\n "scope": "project",\n "source_type": "ai",\n "knowledge_type": "code_pattern",\n "status": "verified",\n "created_at": "2026-01-22T10:30:00Z",\n "updated_at": "2026-01-22T12:15:00Z"\n },\n {\n "id": 124,\n "title": "API Error Handling",\n "summary": "Standard error handling patterns",\n "scope": "project",\n "source_type": "developer",\n "knowledge_type": "architecture",\n "status": "draft",\n "created_at": "2026-01-22T11:00:00Z",\n "updated_at": "2026-01-22T11:00:00Z"\n }\n ],\n "total": 2,\n "limit": 10,\n "offset": 0\n}').action(async e=>{const t=await df.list({scope:e.scope,status:e.status,knowledge_type:e.knowledgeType,limit:e.limit,offset:e.offset});console.log(JSON.stringify(t,null,2))}),uf.command("search").description("Search knowledge items by text").argument("<query...>","Search query terms").option("-l, --limit <limit>","[OPTION] Limit number of results",parseInt,10).addHelpText("after",'\nUsage Examples:\n $ knowledge search react hooks\n $ knowledge search "react hooks" --limit 5\n $ knowledge search title:api content:auth\n\nOutput Example:\n{\n "results": [\n {\n "id": 123,\n "title": "React Custom Hook Pattern",\n "summary": "Best practices for custom hooks",\n "content": "Always prefix with \'use\' and follow hooks rules",\n "scope": "project",\n "source_type": "ai",\n "knowledge_type": "code_pattern",\n "status": "verified",\n "relevance_score": 0.95,\n "created_at": "2026-01-22T10:30:00Z"\n }\n ],\n "total_results": 1,\n "query": "react hooks",\n "limit": 10\n}').action(async(e,t)=>{const n=await df.search(e,t.limit);console.log(JSON.stringify(n,null,2))}),uf.command("update-status").description("Update knowledge item status").argument("<id>","Knowledge item ID",parseInt).argument("<status>",`New status: ${S.join(", ")}`).addHelpText("after",'\nOutput Example:\n{\n "success": true,\n "message": "Status updated successfully",\n "id": 123,\n "old_status": "draft",\n "new_status": "verified",\n "updated_at": "2026-01-22T12:30:00Z"\n}').action(async(e,t)=>{const n=await df.updateStatus(e,t);console.log(JSON.stringify(n,null,2))}),uf.command("stats").description("Get knowledge statistics").addHelpText("after",'\nOutput Example:\n{\n "total_items": 156,\n "by_scope": {\n "personal": 45,\n "project": 89,\n "organization": 22\n },\n "by_status": {\n "draft": 67,\n "suggested": 34,\n "verified": 55\n },\n "by_knowledge_type": {\n "code_pattern": 42,\n "architecture": 38,\n "config": 25,\n "pitfall": 31,\n "api_usage": 20\n },\n "by_source_type": {\n "developer": 78,\n "architect": 23,\n "reviewer": 19,\n "ai": 36\n },\n "recent_activity": {\n "created_last_7_days": 12,\n "updated_last_7_days": 8\n }\n}').action(async()=>{const e=await df.getStats();console.log(JSON.stringify(e,null,2))}),cf.command("session-start").description("Hook: Called when a Claude Code session starts").action(async()=>{await pe.parseInput().then(async e=>{new Se(e).execute().then(e=>{e.send()})})}),cf.command("session-end").description("Hook: Called when a Claude Code session ends").action(async()=>{await pe.parseInput().then(async e=>{new Pe(e).execute().then(e=>{e.send()})})}),cf.command("notification").description("Hook: Called when a notification is triggered").action(async()=>{await pe.parseInput().then(async e=>{new Te(e).execute().then(e=>{e.send()})})}),cf.command("permission-request").description("Hook: Called when a permission request is made").action(async()=>{await pe.parseInput().then(async e=>{new Oe(e).execute().then(e=>{e.send()})})}),cf.command("pre-tool-use").description("Hook: Called before a tool is used").action(async()=>{await pe.parseInput().then(async e=>{new Re(e).execute().then(e=>{e.send()})})}),cf.command("post-tool-use").description("Hook: Called after a tool is used").action(async()=>{await pe.parseInput().then(async e=>{new xe(e).execute().then(e=>{e.send()})})}),cf.command("pre-compact").description("Hook: Called before compacting the session").action(async()=>{await pe.parseInput().then(async e=>{new Ne(e).execute().then(e=>{e.send()})})}),cf.command("stop").description("Hook: Called when a stop signal is received").action(async()=>{await pe.parseInput().then(async e=>{new Ce(e).execute().then(e=>{e.send()})})}),cf.command("subagent-stop").description("Hook: Called when a subagent stops").action(async()=>{await pe.parseInput().then(async e=>{new je(e).execute().then(e=>{e.send()})})}),cf.command("user-prompt-submit").description("Hook: Called when a user submits a prompt").action(async()=>{await pe.parseInput().then(async e=>{new ze(e).execute().then(e=>{e.send()})})}),cf.command("mcp-server").description("Start the Knowledge Bank MCP server").action(async()=>{const e=new Qm;await e.run()}),cf.command("web").description("Start a web server for browsing the database").option("-p, --port <port>","Port to listen on",e=>parseInt(e,10),3e3).option("-d, --dev","Start from source code (development mode)").addHelpText("after","\nUsage Example:\n $ knowledge-bank web\n $ knowledge-bank web --port 8080\n $ knowledge-bank web --dev\n $ knowledge-bank web --dev --port 8080\n\nOptions:\n --dev Start in development mode from source code\n --port Specify the port number (default: 3000)\n\nThis command starts a web server that allows you to browse the SQLite database tables\nand their relationships. Open the URL displayed in your browser after starting the server.\n\nDevelopment mode (--dev) runs the server directly from source code without building,\nuseful for development and debugging purposes.").action(async e=>{await async function(e={}){const t=e.port||3e3,n=e.dev||!1;n?sf.logInfo(`Starting web server in development mode (from source) on port ${t}...`):sf.logInfo(`Starting web server on port ${t}...`),console.log("================================================="),console.log(" Knowledge Bank Database Browser"),n&&console.log(" 🚀 Development Mode (Source Code)"),console.log("================================================="),console.log(` Starting server on port ${t}...`),console.log(` Open http://localhost:${t} in your browser`),console.log(" Press Ctrl+C to stop the server"),console.log("=================================================");const r=new rf({port:t,dev:n}),s=async e=>{sf.logInfo(`\nReceived ${e}, shutting down web server gracefully...`),console.log("\nShutting down server...");try{await r.stop(),sf.logInfo("Web server stopped successfully"),console.log("Server stopped successfully"),process.exit(0)}catch(e){sf.logError("Error during shutdown:",e),console.error("Error during shutdown:",e.message),process.exit(1)}};process.on("SIGINT",()=>s("SIGINT")),process.on("SIGTERM",()=>s("SIGTERM")),process.on("unhandledRejection",(e,t)=>{sf.logError("Unhandled Rejection at:",t,"reason:",e)}),await r.start();const o=setInterval(()=>{},1e3),a=s,i=async e=>{clearInterval(o),await a(e)};return process.removeAllListeners("SIGINT"),process.removeAllListeners("SIGTERM"),process.on("SIGINT",()=>i("SIGINT")),process.on("SIGTERM",()=>i("SIGTERM")),r}(e)}),cf.command("config").description("Get Knowledge Bank configuration settings").option("-t --temp","Get temporary directory path").action(async e=>{e.temp?console.log(af.tmp):console.error("unsupported option. Use --temp to get the temporary directory path.")}),cf.parse(process.argv);
8
+ deps: ${r}}`};const s={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(e){const[t,n]=function({schema:e}){const t={},n={};for(const r in e)"__proto__"!==r&&((Array.isArray(e[r])?t:n)[r]=e[r]);return[t,n]}(e);o(e,t),a(e,n)}};function o(e,n=e.schema){const{gen:s,data:o,it:a}=e;if(0===Object.keys(n).length)return;const i=s.let("missing");for(const c in n){const d=n[c];if(0===d.length)continue;const u=(0,r.propertyInData)(s,o,c,a.opts.ownProperties);e.setParams({property:c,depsCount:d.length,deps:d.join(", ")}),a.allErrors?s.if(u,()=>{for(const t of d)(0,r.checkReportMissingProp)(e,t)}):(s.if(t._`${u} && (${(0,r.checkMissingProp)(e,d,i)})`),(0,r.reportMissingProp)(e,i),s.else())}}function a(e,t=e.schema){const{gen:s,data:o,keyword:a,it:i}=e,c=s.name("valid");for(const d in t)(0,n.alwaysValidSchema)(i,t[d])||(s.if((0,r.propertyInData)(s,o,d,i.opts.ownProperties),()=>{const t=e.subschema({keyword:a,schemaProp:d},c);e.mergeValidEvaluated(t,c)},()=>s.var(c,!0)),e.ok(c))}e.validatePropertyDeps=o,e.validateSchemaDeps=a,e.default=s}(zh)),zh),a=function(){if(Ah)return Dh;Ah=1,Object.defineProperty(Dh,"__esModule",{value:!0});const e=Cl(),t=Al(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:t})=>e._`{propertyName: ${t.propertyName}}`},code(n){const{gen:r,schema:s,data:o,it:a}=n;if((0,t.alwaysValidSchema)(a,s))return;const i=r.name("valid");r.forIn("key",o,t=>{n.setParams({propertyName:t}),n.subschema({keyword:"propertyNames",data:t,dataTypes:["string"],propertyName:t,compositeRule:!0},i),r.if((0,e.not)(i),()=>{n.error(!0),a.allErrors||r.break()})}),n.ok(i)}};return Dh.default=n,Dh}(),i=Zh(),c=function(){if(Fh)return Gh;Fh=1,Object.defineProperty(Gh,"__esModule",{value:!0});const e=yp(),t=sp(),n=Al(),r=Zh(),s={keyword:"properties",type:"object",schemaType:"object",code(s){const{gen:o,schema:a,parentSchema:i,data:c,it:d}=s;"all"===d.opts.removeAdditional&&void 0===i.additionalProperties&&r.default.code(new e.KeywordCxt(d,r.default,"additionalProperties"));const u=(0,t.allSchemaProperties)(a);for(const e of u)d.definedProperties.add(e);d.opts.unevaluated&&u.length&&!0!==d.props&&(d.props=n.mergeEvaluated.props(o,(0,n.toHash)(u),d.props));const l=u.filter(e=>!(0,n.alwaysValidSchema)(d,a[e]));if(0===l.length)return;const p=o.name("valid");for(const e of l)h(e)?m(e):(o.if((0,t.propertyInData)(o,c,e,d.opts.ownProperties)),m(e),d.allErrors||o.else().var(p,!0),o.endIf()),s.it.definedProperties.add(e),s.ok(p);function h(e){return d.opts.useDefaults&&!d.compositeRule&&void 0!==a[e].default}function m(e){s.subschema({keyword:"properties",schemaProp:e,dataProp:e},p)}}};return Gh.default=s,Gh}(),d=function(){if(qh)return Xh;qh=1,Object.defineProperty(Xh,"__esModule",{value:!0});const e=sp(),t=Cl(),n=Al(),r=Al(),s={keyword:"patternProperties",type:"object",schemaType:"object",code(s){const{gen:o,schema:a,data:i,parentSchema:c,it:d}=s,{opts:u}=d,l=(0,e.allSchemaProperties)(a),p=l.filter(e=>(0,n.alwaysValidSchema)(d,a[e]));if(0===l.length||p.length===l.length&&(!d.opts.unevaluated||!0===d.props))return;const h=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=o.name("valid");!0===d.props||d.props instanceof t.Name||(d.props=(0,r.evaluatedPropsToName)(o,d.props));const{props:f}=d;function g(e){for(const t in h)new RegExp(e).test(t)&&(0,n.checkStrictMode)(d,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function y(n){o.forIn("key",i,a=>{o.if(t._`${(0,e.usePattern)(s,n)}.test(${a})`,()=>{const e=p.includes(n);e||s.subschema({keyword:"patternProperties",schemaProp:n,dataProp:a,dataPropType:r.Type.Str},m),d.opts.unevaluated&&!0!==f?o.assign(t._`${f}[${a}]`,!0):e||d.allErrors||o.if((0,t.not)(m),()=>o.break())})})}!function(){for(const e of l)h&&g(e),d.allErrors?y(e):(o.var(m,!0),y(e),o.if(m))}()}};return Xh.default=s,Xh}(),u=function(){if(Uh)return Yh;Uh=1,Object.defineProperty(Yh,"__esModule",{value:!0});const e=Al(),t={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){const{gen:n,schema:r,it:s}=t;if((0,e.alwaysValidSchema)(s,r))return void t.fail();const o=n.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};return Yh.default=t,Yh}(),l=function(){if(Hh)return Qh;Hh=1,Object.defineProperty(Qh,"__esModule",{value:!0});const e={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:sp().validateUnion,error:{message:"must match a schema in anyOf"}};return Qh.default=e,Qh}(),p=function(){if(Vh)return em;Vh=1,Object.defineProperty(em,"__esModule",{value:!0});const e=Cl(),t=Al(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:t})=>e._`{passingSchemas: ${t.passing}}`},code(n){const{gen:r,schema:s,parentSchema:o,it:a}=n;if(!Array.isArray(s))throw new Error("ajv implementation error");if(a.opts.discriminator&&o.discriminator)return;const i=s,c=r.let("valid",!1),d=r.let("passing",null),u=r.name("_valid");n.setParams({passing:d}),r.block(function(){i.forEach((s,o)=>{let i;(0,t.alwaysValidSchema)(a,s)?r.var(u,!0):i=n.subschema({keyword:"oneOf",schemaProp:o,compositeRule:!0},u),o>0&&r.if(e._`${u} && ${c}`).assign(c,!1).assign(d,e._`[${d}, ${o}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(d,o),i&&n.mergeEvaluated(i,e.Name)})})}),n.result(c,()=>n.reset(),()=>n.error(!0))}};return em.default=n,em}(),h=function(){if(Kh)return tm;Kh=1,Object.defineProperty(tm,"__esModule",{value:!0});const e=Al(),t={keyword:"allOf",schemaType:"array",code(t){const{gen:n,schema:r,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");const o=n.name("valid");r.forEach((n,r)=>{if((0,e.alwaysValidSchema)(s,n))return;const a=t.subschema({keyword:"allOf",schemaProp:r},o);t.ok(o),t.mergeEvaluated(a)})}};return tm.default=t,tm}(),m=function(){if(Jh)return nm;Jh=1,Object.defineProperty(nm,"__esModule",{value:!0});const e=Cl(),t=Al(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:t})=>e.str`must match "${t.ifClause}" schema`,params:({params:t})=>e._`{failingKeyword: ${t.ifClause}}`},code(n){const{gen:s,parentSchema:o,it:a}=n;void 0===o.then&&void 0===o.else&&(0,t.checkStrictMode)(a,'"if" without "then" and "else" is ignored');const i=r(a,"then"),c=r(a,"else");if(!i&&!c)return;const d=s.let("valid",!0),u=s.name("_valid");if(function(){const e=n.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},u);n.mergeEvaluated(e)}(),n.reset(),i&&c){const e=s.let("ifClause");n.setParams({ifClause:e}),s.if(u,l("then",e),l("else",e))}else i?s.if(u,l("then")):s.if((0,e.not)(u),l("else"));function l(t,r){return()=>{const o=n.subschema({keyword:t},u);s.assign(d,u),n.mergeValidEvaluated(o,d),r?s.assign(r,e._`${t}`):n.setParams({ifClause:t})}}n.pass(d,()=>n.error(!0))}};function r(e,n){const r=e.schema[n];return void 0!==r&&!(0,t.alwaysValidSchema)(e,r)}return nm.default=n,nm}(),f=function(){if(Bh)return rm;Bh=1,Object.defineProperty(rm,"__esModule",{value:!0});const e=Al(),t={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:n,it:r}){void 0===n.if&&(0,e.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};return rm.default=t,rm}();return kh.default=function(g=!1){const y=[u.default,l.default,p.default,h.default,m.default,f.default,a.default,i.default,o.default,c.default,d.default];return g?y.push(t.default,r.default):y.push(e.default,n.default),y.push(s.default),y},kh}var om,am,im={},cm={};function dm(){if(om)return cm;om=1,Object.defineProperty(cm,"__esModule",{value:!0});const e=Cl(),t={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:t})=>e.str`must match format "${t}"`,params:({schemaCode:t})=>e._`{format: ${t}}`},code(t,n){const{gen:r,data:s,$data:o,schema:a,schemaCode:i,it:c}=t,{opts:d,errSchemaPath:u,schemaEnv:l,self:p}=c;d.validateFormats&&(o?function(){const o=r.scopeValue("formats",{ref:p.formats,code:d.code.formats}),a=r.const("fDef",e._`${o}[${i}]`),c=r.let("fType"),u=r.let("format");r.if(e._`typeof ${a} == "object" && !(${a} instanceof RegExp)`,()=>r.assign(c,e._`${a}.type || "string"`).assign(u,e._`${a}.validate`),()=>r.assign(c,e._`"string"`).assign(u,a)),t.fail$data((0,e.or)(!1===d.strictSchema?e.nil:e._`${i} && !${u}`,function(){const t=l.$async?e._`(${a}.async ? await ${u}(${s}) : ${u}(${s}))`:e._`${u}(${s})`,r=e._`(typeof ${u} == "function" ? ${t} : ${u}.test(${s}))`;return e._`${u} && ${u} !== true && ${c} === ${n} && !${r}`}()))}():function(){const o=p.formats[a];if(!o)return void function(){if(!1!==d.strictSchema)throw new Error(e());function e(){return`unknown format "${a}" ignored in schema at path "${u}"`}p.logger.warn(e())}();if(!0===o)return;const[i,c,h]=function(t){const n=t instanceof RegExp?(0,e.regexpCode)(t):d.code.formats?e._`${d.code.formats}${(0,e.getProperty)(a)}`:void 0,s=r.scopeValue("formats",{key:a,ref:t,code:n});return"object"!=typeof t||t instanceof RegExp?["string",t,s]:[t.type||"string",t.validate,e._`${s}.validate`]}(o);i===n&&t.pass(function(){if("object"==typeof o&&!(o instanceof RegExp)&&o.async){if(!l.$async)throw new Error("async format in sync schema");return e._`await ${h}(${s})`}return"function"==typeof c?e._`${h}(${s})`:e._`${h}.test(${s})`}())}())}};return cm.default=t,cm}var um,lm,pm={};function hm(){if(lm)return qp;lm=1,Object.defineProperty(qp,"__esModule",{value:!0});const e=function(){if(Fp)return Up;Fp=1,Object.defineProperty(Up,"__esModule",{value:!0});const e=function(){if(Lp)return Hp;Lp=1,Object.defineProperty(Hp,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return Hp.default=e,Hp}(),t=function(){if(Zp)return Vp;Zp=1,Object.defineProperty(Vp,"__esModule",{value:!0}),Vp.callRef=Vp.getValidate=void 0;const e=$p(),t=sp(),n=Cl(),r=Fl(),s=Tp(),o=Al(),a={keyword:"$ref",schemaType:"string",code(t){const{gen:r,schema:o,it:a}=t,{baseId:d,schemaEnv:u,validateName:l,opts:p,self:h}=a,{root:m}=u;if(("#"===o||"#/"===o)&&d===m.baseId)return function(){if(u===m)return c(t,l,u,u.$async);const e=r.scopeValue("root",{ref:m});return c(t,n._`${e}.validate`,m,m.$async)}();const f=s.resolveRef.call(h,m,d,o);if(void 0===f)throw new e.default(a.opts.uriResolver,d,o);return f instanceof s.SchemaEnv?function(e){const n=i(t,e);c(t,n,e,e.$async)}(f):function(e){const s=r.scopeValue("schema",!0===p.code.source?{ref:e,code:(0,n.stringify)(e)}:{ref:e}),a=r.name("valid"),i=t.subschema({schema:e,dataTypes:[],schemaPath:n.nil,topSchemaRef:s,errSchemaPath:o},a);t.mergeEvaluated(i),t.ok(a)}(f)}};function i(e,t){const{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):n._`${r.scopeValue("wrapper",{ref:t})}.validate`}function c(e,s,a,i){const{gen:c,it:d}=e,{allErrors:u,schemaEnv:l,opts:p}=d,h=p.passContext?r.default.this:n.nil;function m(e){const t=n._`${e}.errors`;c.assign(r.default.vErrors,n._`${r.default.vErrors} === null ? ${t} : ${r.default.vErrors}.concat(${t})`),c.assign(r.default.errors,n._`${r.default.vErrors}.length`)}function f(e){var t;if(!d.opts.unevaluated)return;const r=null===(t=null==a?void 0:a.validate)||void 0===t?void 0:t.evaluated;if(!0!==d.props)if(r&&!r.dynamicProps)void 0!==r.props&&(d.props=o.mergeEvaluated.props(c,r.props,d.props));else{const t=c.var("props",n._`${e}.evaluated.props`);d.props=o.mergeEvaluated.props(c,t,d.props,n.Name)}if(!0!==d.items)if(r&&!r.dynamicItems)void 0!==r.items&&(d.items=o.mergeEvaluated.items(c,r.items,d.items));else{const t=c.var("items",n._`${e}.evaluated.items`);d.items=o.mergeEvaluated.items(c,t,d.items,n.Name)}}i?function(){if(!l.$async)throw new Error("async schema referenced by sync schema");const r=c.let("valid");c.try(()=>{c.code(n._`await ${(0,t.callValidateCode)(e,s,h)}`),f(s),u||c.assign(r,!0)},e=>{c.if(n._`!(${e} instanceof ${d.ValidationError})`,()=>c.throw(e)),m(e),u||c.assign(r,!1)}),e.ok(r)}():e.result((0,t.callValidateCode)(e,s,h),()=>f(s),()=>m(s))}return Vp.getValidate=i,Vp.callRef=c,Vp.default=a,Vp}(),n=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return Up.default=n,Up}(),t=wh(),n=sm(),r=function(){if(am)return im;am=1,Object.defineProperty(im,"__esModule",{value:!0});const e=[dm().default];return im.default=e,im}(),s=(um||(um=1,Object.defineProperty(pm,"__esModule",{value:!0}),pm.contentVocabulary=pm.metadataVocabulary=void 0,pm.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],pm.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),pm),o=[e.default,t.default,(0,n.default)(),r.default,s.metadataVocabulary,s.contentVocabulary];return qp.default=o,qp}var mm,fm,gm={},ym={};var _m,vm={$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};function wm(){return _m||(_m=1,function(e,t){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;const n=Dp(),r=hm(),s=function(){if(fm)return gm;fm=1,Object.defineProperty(gm,"__esModule",{value:!0});const e=Cl(),t=(mm||(mm=1,Object.defineProperty(ym,"__esModule",{value:!0}),ym.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(n||(ym.DiscrError=n={}))),ym);var n;const r=Tp(),s=$p(),o=Al(),a={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:n}})=>e===t.DiscrError.Tag?`tag "${n}" must be string`:`value of tag "${n}" must be in oneOf`,params:({params:{discrError:t,tag:n,tagName:r}})=>e._`{error: ${t}, tag: ${r}, tagValue: ${n}}`},code(n){const{gen:a,data:i,schema:c,parentSchema:d,it:u}=n,{oneOf:l}=d;if(!u.opts.discriminator)throw new Error("discriminator: requires discriminator option");const p=c.propertyName;if("string"!=typeof p)throw new Error("discriminator: requires propertyName");if(c.mapping)throw new Error("discriminator: mapping is not supported");if(!l)throw new Error("discriminator: requires oneOf keyword");const h=a.let("valid",!1),m=a.const("tag",e._`${i}${(0,e.getProperty)(p)}`);function f(t){const r=a.name("valid"),s=n.subschema({keyword:"oneOf",schemaProp:t},r);return n.mergeEvaluated(s,e.Name),r}a.if(e._`typeof ${m} == "string"`,()=>function(){const i=function(){var e;const t={},n=i(d);let a=!0;for(let t=0;t<l.length;t++){let d=l[t];if((null==d?void 0:d.$ref)&&!(0,o.schemaHasRulesButRef)(d,u.self.RULES)){const e=d.$ref;if(d=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),d instanceof r.SchemaEnv&&(d=d.schema),void 0===d)throw new s.default(u.opts.uriResolver,u.baseId,e)}const h=null===(e=null==d?void 0:d.properties)||void 0===e?void 0:e[p];if("object"!=typeof h)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${p}"`);a=a&&(n||i(d)),c(h,t)}if(!a)throw new Error(`discriminator: "${p}" must be required`);return t;function i({required:e}){return Array.isArray(e)&&e.includes(p)}function c(e,t){if(e.const)h(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${p}" must have "const" or "enum"`);for(const n of e.enum)h(n,t)}}function h(e,n){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${p}" values must be unique strings`);t[e]=n}}();a.if(!1);for(const t in i)a.elseIf(e._`${m} === ${t}`),a.assign(h,f(i[t]));a.else(),n.error(!1,{discrError:t.DiscrError.Mapping,tag:m,tagName:p}),a.endIf()}(),()=>n.error(!1,{discrError:t.DiscrError.Tag,tag:m,tagName:p})),n.ok(h)}};return gm.default=a,gm}(),o=vm,a=["/properties"],i="http://json-schema.org/draft-07/schema";class c extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(s.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const e=this.opts.$data?this.$dataMetaSchema(o,a):o;this.addMetaSchema(e,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var d=yp();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return d.KeywordCxt}});var u=Cl();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var l=wp();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return l.default}});var p=$p();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})}(bl,bl.exports)),bl.exports}var bm,km,$m,Sm=vl(wm()),Em={exports:{}},Tm={},Om={},xm=($m||($m=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const n=(bm||(bm=1,function(e){function t(e,t){return{validate:e,compare:t}}Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0,e.fullFormats={date:t(s,o),time:t(i(!0),c),"date-time":t(l(!0),p),"iso-time":t(i(),d),"iso-date-time":t(l(),h),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:function(e){return m.test(e)&&f.test(e)},"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:function(e){if(w.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}},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:function(e){return g.lastIndex=0,g.test(e)},int32:{type:"number",validate:function(e){return Number.isInteger(e)&&e<=_&&e>=y}},int64:{type:"number",validate:function(e){return Number.isInteger(e)}},float:{type:"number",validate:v},double:{type:"number",validate:v},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"date-time":t(/^\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,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,d),"iso-date-time":t(/^\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,h),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},e.formatNames=Object.keys(e.fullFormats);const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,r=[0,31,28,31,30,31,30,31,31,30,31,30,31];function s(e){const t=n.exec(e);if(!t)return!1;const s=+t[1],o=+t[2],a=+t[3];return o>=1&&o<=12&&a>=1&&a<=(2===o&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(s)?29:r[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}const a=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function i(e){return function(t){const n=a.exec(t);if(!n)return!1;const r=+n[1],s=+n[2],o=+n[3],i=n[4],c="-"===n[5]?-1:1,d=+(n[6]||0),u=+(n[7]||0);if(d>23||u>59||e&&!i)return!1;if(r<=23&&s<=59&&o<60)return!0;const l=s-u*c,p=r-d*c-(l<0?1:0);return(23===p||-1===p)&&(59===l||-1===l)&&o<61}}function c(e,t){if(!e||!t)return;const n=new Date("2020-01-01T"+e).valueOf(),r=new Date("2020-01-01T"+t).valueOf();return n&&r?n-r:void 0}function d(e,t){if(!e||!t)return;const n=a.exec(e),r=a.exec(t);return n&&r?(e=n[1]+n[2]+n[3])>(t=r[1]+r[2]+r[3])?1:e<t?-1:0:void 0}const u=/t|\s/i;function l(e){const t=i(e);return function(e){const n=e.split(u);return 2===n.length&&s(n[0])&&t(n[1])}}function p(e,t){if(!e||!t)return;const n=new Date(e).valueOf(),r=new Date(t).valueOf();return n&&r?n-r:void 0}function h(e,t){if(!e||!t)return;const[n,r]=e.split(u),[s,a]=t.split(u),i=o(n,s);return void 0!==i?i||c(r,a):void 0}const m=/\/|:/,f=/^(?:[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,g=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm,y=-2147483648,_=2**31-1;function v(){return!0}const w=/[^\\]\\Z/}(Tm)),Tm),r=(km||(km=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=wm(),n=Cl(),r=n.operators,s={formatMaximum:{okStr:"<=",ok:r.LTE,fail:r.GT},formatMinimum:{okStr:">=",ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:"<",ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:">",ok:r.GT,fail:r.LTE}},o={message:({keyword:e,schemaCode:t})=>n.str`should be ${s[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>n._`{comparison: ${s[e].okStr}, limit: ${t}}`};e.formatLimitDefinition={keyword:Object.keys(s),type:"string",schemaType:"string",$data:!0,error:o,code(e){const{gen:r,data:o,schemaCode:a,keyword:i,it:c}=e,{opts:d,self:u}=c;if(!d.validateFormats)return;const l=new t.KeywordCxt(c,u.RULES.all.format.definition,"format");function p(e){return n._`${e}.compare(${o}, ${a}) ${s[i].fail} 0`}l.$data?function(){const t=r.scopeValue("formats",{ref:u.formats,code:d.code.formats}),s=r.const("fmt",n._`${t}[${l.schemaCode}]`);e.fail$data((0,n.or)(n._`typeof ${s} != "object"`,n._`${s} instanceof RegExp`,n._`typeof ${s}.compare != "function"`,p(s)))}():function(){const t=l.schema,s=u.formats[t];if(!s||!0===s)return;if("object"!=typeof s||s instanceof RegExp||"function"!=typeof s.compare)throw new Error(`"${i}": format "${t}" does not define "compare" function`);const o=r.scopeValue("formats",{key:t,ref:s,code:d.code.formats?n._`${d.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(p(o))}()},dependencies:["format"]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)}(Om)),Om),s=Cl(),o=new s.Name("fullFormats"),a=new s.Name("fastFormats"),i=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,o),e;const[s,i]="fast"===t.mode?[n.fastFormats,a]:[n.fullFormats,o];return c(e,t.formats||n.formatNames,s,i),t.keywords&&(0,r.default)(e),e};function c(e,t,n,r){var o,a;null!==(o=(a=e.opts.code).formats)&&void 0!==o||(a.formats=s._`require("ajv-formats/dist/formats").${r}`);for(const r of t)e.addFormat(r,n[r])}i.get=(e,t="full")=>{const r=("fast"===t?n.fastFormats:n.fullFormats)[e];if(!r)throw new Error(`Unknown format "${e}"`);return r},e.exports=t=i,Object.defineProperty(t,"__esModule",{value:!0}),t.default=i}(Em,Em.exports)),Em.exports),Nm=vl(xm);class Im{constructor(e){this._ajv=e??function(){const e=new Sm({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return Nm(e),e}()}getValidator(e){const t="$id"in e&&"string"==typeof e.$id?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}class Rm{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}class Pm extends yl{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Hd.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{const n=this._loggingLevels.get(t);return!!n&&this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n)},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new Im,this.setRequestHandler(xc,e=>this._oninitialize(e)),this.setNotificationHandler(Rc,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Kd,async(e,t)=>{const n=t.sessionId||t.requestInfo?.headers["mcp-session-id"]||void 0,{level:r}=e.params,s=Hd.safeParse(r);return s.success&&this._loggingLevels.set(n,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Rm(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=function(e,t){const n={...e};for(const e in t){const r=e,s=t[r];if(void 0===s)continue;const o=n[r];_l(o)&&_l(s)?n[r]={...o,...s}:n[r]=s}return n}(this._capabilities,e)}setRequestHandler(e,t){const n=ca(e),r=n?.method;if(!r)throw new Error("Schema is missing a method literal");let s;if(sa(r)){const e=r,t=e._zod?.def;s=t?.value??e.value}else{const e=r,t=e._def;s=t?.value??e.value}if("string"!=typeof s)throw new Error("Schema method literal must be a string");if("tools/call"===s){const n=async(e,n)=>{const r=aa(qd,e);if(!r.success){const e=r.error instanceof Error?r.error.message:String(r.error);throw new Iu(pc.InvalidParams,`Invalid tools/call request: ${e}`)}const{params:s}=r.data,o=await Promise.resolve(t(e,n));if(s.task){const e=aa(Fc,o);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new Iu(pc.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const a=aa(Zd,o);if(!a.success){const e=a.error instanceof Error?a.error.message:String(a.error);throw new Iu(pc.InvalidParams,`Invalid tools/call result: ${e}`)}return a.data};return super.setRequestHandler(e,n)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){!function(e,t,n){if(!e)throw new Error(`${n} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${t})`)}}(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&function(e,t,n){if(!e)throw new Error(`${n} does not support task creation (required for ${t})`);if("tools/call"===t&&!e.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${t})`)}(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){const t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Vi.includes(t)?t:Hi,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},fc)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){const t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>"tool_result"===e.type),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,o=s?Array.isArray(s.content)?s.content:[s.content]:[],a=o.some(e=>"tool_use"===e.type);if(r){if(n.some(e=>"tool_result"!==e.type))throw new Error("The last message must contain only tool_result content if any is present");if(!a)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(a){const e=new Set(o.filter(e=>"tool_use"===e.type).map(e=>e.id)),t=new Set(n.filter(e=>"tool_result"===e.type).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},ou,t):this.request({method:"sampling/createMessage",params:e},su,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");const n=e;return this.request({method:"elicitation/create",params:n},wu,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");const n="form"===e.mode?e:{...e,mode:"form"},r=await this.request({method:"elicitation/create",params:n},wu,t);if("accept"===r.action&&r.content&&n.requestedSchema)try{const e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new Iu(pc.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){if(e instanceof Iu)throw e;throw new Iu(pc.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},xu,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}const Cm=Symbol.for("mcp.completable");function jm(e){return!!e&&"object"==typeof e&&Cm in e}var zm;!function(e){e.Completable="McpCompletable"}(zm||(zm={}));const Am=/^[A-Za-z0-9._-]{1,128}$/;function Mm(e){const t=function(e){const t=[];if(0===e.length)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!Am.test(e)){const n=e.split("").filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}(e);return function(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(const e of t)console.warn(` - ${e}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}(e,t.warnings),t.isValid}class Dm{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){const r={taskSupport:"required",...t.execution};if("forbidden"===r.taskSupport)throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}}class Lm{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Pm(e,t)}get experimental(){return this._experimental||(this._experimental={tasks:new Dm(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Vm(Dd)),this.server.assertCanSetRequestHandler(Vm(qd)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Dd,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{const n={name:e,title:t.title,description:t.description,inputSchema:(()=>{const e=da(t.inputSchema);return e?ml(e,{strictUnions:!0,pipeStrategy:"input"}):Zm})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){const e=da(t.outputSchema);e&&(n.outputSchema=ml(e,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(qd,async(e,t)=>{try{const n=this._registeredTools[e.params.name];if(!n)throw new Iu(pc.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Iu(pc.InvalidParams,`Tool ${e.params.name} disabled`);const r=!!e.params.task,s=n.execution?.taskSupport,o="createTask"in n.handler;if(("required"===s||"optional"===s)&&!o)throw new Iu(pc.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if("required"===s&&!r)throw new Iu(pc.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if("optional"===s&&!r&&o)return await this.handleAutomaticTaskPolling(n,e,t);const a=await this.validateToolInput(n,e.params.arguments,e.params.name),i=await this.executeToolHandler(n,a,t);return r||await this.validateToolOutput(n,i,e.params.name),i}catch(e){if(e instanceof Iu&&e.code===pc.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;const r=da(e.inputSchema)??e.inputSchema,s=await ia(r,t);if(!s.success){const e=ua("error"in s?s.error:"Unknown error");throw new Iu(pc.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return s.data}async validateToolOutput(e,t,n){if(!e.outputSchema)return;if(!("content"in t))return;if(t.isError)return;if(!t.structuredContent)throw new Iu(pc.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);const r=da(e.outputSchema),s=await ia(r,t.structuredContent);if(!s.success){const e=ua("error"in s?s.error:"Unknown error");throw new Iu(pc.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){const r=e.handler;if("createTask"in r){if(!n.taskStore)throw new Error("No task store provided.");const s={...n,taskStore:n.taskStore};if(e.inputSchema){const e=r;return await Promise.resolve(e.createTask(t,s))}{const e=r;return await Promise.resolve(e.createTask(s))}}if(e.inputSchema){const e=r;return await Promise.resolve(e(t,n))}{const e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");const r=await this.validateToolInput(e,t.params.arguments,t.params.name),s=e.handler,o={...n,taskStore:n.taskStore},a=r?await Promise.resolve(s.createTask(r,o)):await Promise.resolve(s.createTask(o)),i=a.task.taskId;let c=a.task;const d=c.pollInterval??5e3;for(;"completed"!==c.status&&"failed"!==c.status&&"cancelled"!==c.status;){await new Promise(e=>setTimeout(e,d));const e=await n.taskStore.getTask(i);if(!e)throw new Iu(pc.InternalError,`Task ${i} not found during polling`);c=e}return await n.taskStore.getTaskResult(i)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Vm(Su)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Su,async e=>{switch(e.params.ref.type){case"ref/prompt":return function(e){if("ref/prompt"!==e.params.ref.type)throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return function(e){if("ref/resource"!==e.params.ref.type)throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Iu(pc.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){const n=this._registeredPrompts[t.name];if(!n)throw new Iu(pc.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new Iu(pc.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return Jm;const r=ca(n.argsSchema),s=r?.[e.params.argument.name];if(!jm(s))return Jm;const o=function(e){const t=e[Cm];return t?.complete}(s);return o?Km(await o(e.params.argument.value,e.params.context)):Jm}async handleResourceCompletion(e,t){const n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return Jm;throw new Iu(pc.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?Km(await r(e.params.argument.value,e.params.context)):Jm}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Vm(od)),this.server.assertCanSetRequestHandler(Vm(id)),this.server.assertCanSetRequestHandler(Vm(ld)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(od,async(e,t)=>{const n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(const e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;const n=await e.resourceTemplate.listCallback(t);for(const t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(id,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(ld,async(e,t)=>{const n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new Iu(pc.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(const e of Object.values(this._registeredResourceTemplates)){const r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new Iu(pc.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Vm(kd)),this.server.assertCanSetRequestHandler(Vm(Ed)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(kd,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Hm(t.argsSchema):void 0}))})),this.server.setRequestHandler(Ed,async(e,t)=>{const n=this._registeredPrompts[e.params.name];if(!n)throw new Iu(pc.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Iu(pc.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){const r=da(n.argsSchema),s=await ia(r,e.params.arguments);if(!s.success){const t=ua("error"in s?s.error:"Unknown error");throw new Iu(pc.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}const o=s.data,a=n.callback;return await Promise.resolve(a(o,t))}{const e=n.callback;return await Promise.resolve(e(t))}}),this._promptHandlersInitialized=!0)}resource(e,t,...n){let r;"object"==typeof n[0]&&(r=n.shift());const s=n[0];if("string"==typeof t){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);const n=this._createRegisteredResource(e,void 0,t,r,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const n=this._createRegisteredResourceTemplate(e,void 0,t,r,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if("string"==typeof t){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);const s=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const s=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,t,n,r,s){const o={name:e,title:t,metadata:r,readCallback:s,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({uri:null}),update:e=>{void 0!==e.uri&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=o)),void 0!==e.name&&(o.name=e.name),void 0!==e.title&&(o.title=e.title),void 0!==e.metadata&&(o.metadata=e.metadata),void 0!==e.callback&&(o.readCallback=e.callback),void 0!==e.enabled&&(o.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=o,o}_createRegisteredResourceTemplate(e,t,n,r,s){const o={resourceTemplate:n,title:t,metadata:r,readCallback:s,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=o)),void 0!==t.title&&(o.title=t.title),void 0!==t.template&&(o.resourceTemplate=t.template),void 0!==t.metadata&&(o.metadata=t.metadata),void 0!==t.callback&&(o.readCallback=t.callback),void 0!==t.enabled&&(o.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=o;const a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),o}_createRegisteredPrompt(e,t,n,r,s){const o={title:t,description:n,argsSchema:void 0===r?void 0:oa(r),callback:s,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=o)),void 0!==t.title&&(o.title=t.title),void 0!==t.description&&(o.description=t.description),void 0!==t.argsSchema&&(o.argsSchema=oa(t.argsSchema)),void 0!==t.callback&&(o.callback=t.callback),void 0!==t.enabled&&(o.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=o,r&&Object.values(r).some(e=>jm(e instanceof f?e._def?.innerType:e))&&this.setCompletionRequestHandler(),o}_createRegisteredTool(e,t,n,r,s,o,a,i,c){Mm(e);const d={title:t,description:n,inputSchema:Um(r),outputSchema:Um(s),annotations:o,execution:a,_meta:i,handler:c,enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&("string"==typeof t.name&&Mm(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=d)),void 0!==t.title&&(d.title=t.title),void 0!==t.description&&(d.description=t.description),void 0!==t.paramsSchema&&(d.inputSchema=oa(t.paramsSchema)),void 0!==t.outputSchema&&(d.outputSchema=oa(t.outputSchema)),void 0!==t.callback&&(d.handler=t.callback),void 0!==t.annotations&&(d.annotations=t.annotations),void 0!==t._meta&&(d._meta=t._meta),void 0!==t.enabled&&(d.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,r,s;if("string"==typeof t[0]&&(n=t.shift()),t.length>1){const e=t[0];qm(e)?(r=t.shift(),t.length>1&&"object"==typeof t[0]&&null!==t[0]&&!qm(t[0])&&(s=t.shift())):"object"==typeof e&&null!==e&&(s=t.shift())}const o=t[0];return this._createRegisteredTool(e,void 0,n,r,void 0,s,{taskSupport:"forbidden"},void 0,o)}registerTool(e,t,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);const{title:r,description:s,inputSchema:o,outputSchema:a,annotations:i,_meta:c}=t;return this._createRegisteredTool(e,r,s,o,a,i,{taskSupport:"forbidden"},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n,r;"string"==typeof t[0]&&(n=t.shift()),t.length>1&&(r=t.shift());const s=t[0],o=this._createRegisteredPrompt(e,void 0,n,r,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);const{title:r,description:s,argsSchema:o}=t,a=this._createRegisteredPrompt(e,r,s,o,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return void 0!==this.server.transport}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}const Zm={type:"object",properties:{}};function Fm(e){return null!==e&&"object"==typeof e&&"parse"in e&&"function"==typeof e.parse&&"safeParse"in e&&"function"==typeof e.safeParse}function qm(e){return"object"==typeof e&&null!==e&&!function(e){return"_def"in e||"_zod"in e||Fm(e)}(e)&&(0===Object.keys(e).length||Object.values(e).some(Fm))}function Um(e){if(e)return qm(e)?oa(e):e}function Hm(e){const t=ca(e);return t?Object.entries(t).map(([e,t])=>{const n=function(e){return e.description}(t),r=function(e){if(sa(e)){const t=e;return"optional"===t._zod?.def?.type}const t=e;return"function"==typeof e.isOptional?e.isOptional():"ZodOptional"===t._def?.typeName}(t);return{name:e,description:n,required:!r}}):[]}function Vm(e){const t=ca(e),n=t?.method;if(!n)throw new Error("Schema is missing a method literal");const r=la(n);if("string"==typeof r)return r;throw new Error("Schema method literal must be a string")}function Km(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const Jm={completion:{values:[],hasMore:!1}};class Bm{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf("\n");if(-1===e)return null;const t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),function(e){return mc.parse(JSON.parse(e))}(t)}clear(){this._buffer=void 0}}class Wm{constructor(e=y.stdin,t=y.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new Bm,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{this.onerror?.(e)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{const e=this._readBuffer.readMessage();if(null===e)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),0===this._stdin.listenerCount("data")&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{const n=function(e){return JSON.stringify(e)+"\n"}(e);this._stdout.write(n)?t():this._stdout.once("drain",t)})}}class Gm{static exists(e){return i(e)}static writeJson(e,t){const r=n(e);c(r,{recursive:!0}),d(e,JSON.stringify(t,null,2),"utf8")}static readJson(e){if(!this.exists(e))throw new Error(`File not found: ${e}`);const t=a(e,"utf8");return JSON.parse(t)}static writeMarkdown(e,t){const r=n(e);c(r,{recursive:!0}),d(e,t,"utf8")}static formatKnowledgeAsMarkdown(e){return`# ${e.title}\n\n**ID:** ${e.id}\n**Summary:** ${e.summary}\n**Knowledge Type:** ${e.knowledge_type}\n**Status:** ${e.status}\n**Scope:** ${e.scope}\n**Source Type:** ${e.source_type}\n${e.source_file?`**Source File:** ${e.source_file}`:""}\n${e.commit_hash?`**Commit Hash:** ${e.commit_hash}`:""}\n${e.contributor?`**Contributor:** ${e.contributor}`:""}\n${e.created_at?`**Created At:** ${e.created_at}`:""}\n${e.updated_at?`**Updated At:** ${e.updated_at}`:""}\n\n## Content\n\n${e.content}\n`}static extractKnowledgeForJson(e){return{title:e.title,summary:e.summary,content:e.content,knowledge_type:e.knowledge_type,status:e.status,scope:e.scope,source_type:e.source_type,source_file:e.source_file||null,commit_hash:e.commit_hash||null,contributor:e.contributor||null}}}const Xm=P(),Ym=M("mcp-server","mcp-server");class Qm{constructor(){this.knowledgeManagement=new ue,this.tempDir=t.join(Xm.tmp,J()),this.server=new Lm({name:"knowledge-bank",version:q.version},{capabilities:{tools:{}}}),this.setupHandlers()}setupHandlers(){this.server.registerTool("knowledge_create",{description:"Create a new knowledge item",inputSchema:g.object({session_id:g.string().describe("Session ID for tracking, can be omitted to use env vars CLAUDE_SESSION_ID"),repository_id:g.number().describe("Repository ID"),title:g.string().optional().describe("Knowledge title"),summary:g.string().optional().describe("Knowledge summary"),content:g.string().optional().describe("Knowledge content"),scope:g.enum(b).optional().describe("Scope of knowledge"),source_type:g.enum(k).optional().describe("Source type"),knowledge_type:g.enum($).optional().describe("Knowledge type"),status:g.enum(S).optional().describe("Status of knowledge"),source_file:g.string().optional().describe("Source file path (optional)"),commit_hash:g.string().optional().describe("Commit hash (optional)"),contributor:g.string().optional().describe("Contributor name (optional)"),from:g.string().optional().describe("Load knowledge data from JSON file")})},async e=>await this.handleCreate(e)),this.server.registerTool("knowledge_get",{description:"Get a knowledge item by ID",inputSchema:g.object({id:g.number().describe("Knowledge item ID"),to:g.string().optional().describe("Save knowledge to markdown file")})},async e=>await this.handleGet(e)),this.server.registerTool("knowledge_update",{description:"Update a knowledge item",inputSchema:g.object({id:g.number().describe("Knowledge item ID"),title:g.string().optional().describe("Knowledge title"),summary:g.string().optional().describe("Knowledge summary"),content:g.string().optional().describe("Knowledge content"),scope:g.enum(b).optional().describe("Scope of knowledge"),source_type:g.enum(k).optional().describe("Source type"),knowledge_type:g.enum($).optional().describe("Knowledge type"),status:g.enum(S).optional().describe("Status of knowledge"),source_file:g.string().optional().describe("Source file path"),commit_hash:g.string().optional().describe("Commit hash"),contributor:g.string().optional().describe("Contributor name"),from:g.string().optional().describe("Load update data from JSON file")})},async e=>await this.handleUpdate(e)),this.server.registerTool("knowledge_delete",{description:"Delete a knowledge item",inputSchema:g.object({id:g.number().describe("Knowledge item ID")})},async e=>await this.handleDelete(e)),this.server.registerTool("knowledge_list",{description:"List knowledge items with optional filters",inputSchema:g.object({scope:g.enum(b).optional().describe("Filter by scope"),status:g.enum(S).optional().describe("Filter by status"),knowledge_type:g.enum($).optional().describe("Filter by knowledge type"),limit:g.number().default(100).describe("Limit number of results"),offset:g.number().default(0).describe("Offset for pagination"),to:g.string().optional().describe("Save results to JSON file")})},async e=>await this.handleList(e)),this.server.registerTool("knowledge_search",{description:"Search knowledge items by text query",inputSchema:g.object({query:g.array(g.string()).describe("Search query terms"),limit:g.number().default(10).describe("Limit number of results"),to:g.string().optional().describe("Save results to JSON file")})},async e=>await this.handleSearch(e)),this.server.registerTool("knowledge_update_status",{description:"Update knowledge item status",inputSchema:g.object({id:g.number().describe("Knowledge item ID"),status:g.enum(S).describe("New status")})},async e=>await this.handleUpdateStatus(e)),this.server.registerTool("knowledge_stats",{description:"Get knowledge statistics",inputSchema:g.object({})},async()=>await this.handleStats())}async handleCreate(e){let n=e;if(e.from){const r=t.join(this.tempDir,e.from);if(!Gm.exists(r))return{content:[{type:"text",text:JSON.stringify({error:`File not found: ${r}`},null,2)}],isError:!0};try{n=Gm.readJson(r)}catch(e){return{content:[{type:"text",text:JSON.stringify({error:`Error reading JSON file: ${e.message}`},null,2)}],isError:!0}}}if(!(n.title&&n.summary&&n.content&&n.scope&&n.source_type&&n.knowledge_type&&n.status))return{content:[{type:"text",text:JSON.stringify({error:"Missing required fields: title, summary, content, scope, source_type, knowledge_type, status"},null,2)}],isError:!0};const r=await de.repositoryManager.getCurrentRepository(),s=await this.knowledgeManagement.create({title:n.title,summary:n.summary,content:n.content,scope:n.scope,source_type:n.source_type,knowledge_type:n.knowledge_type,status:n.status,source_file:n.source_file,commit_hash:n.commit_hash,contributor:n.contributor,repository_id:r.id,session_id:process.env.CLAUDE_SESSION_ID||n.session_id||"unknown-session"});if(e.from){const n=t.join(this.tempDir,e.from);return{content:[{type:"text",text:JSON.stringify({id:s.id,title:s.title,message:`Knowledge item created from ${e.from}`,file_path:n},null,2)}]}}return{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}async handleGet(e){const n=await this.knowledgeManagement.get(e.id);if(!n)return{content:[{type:"text",text:JSON.stringify({error:"Knowledge item not found"},null,2)}],isError:!0};if(e.to)try{const r=t.join(this.tempDir,e.to),s=Gm.formatKnowledgeAsMarkdown(n);return Gm.writeMarkdown(r,s),{content:[{type:"text",text:JSON.stringify({success:!0,message:`Knowledge item ${e.id} saved to ${e.to}`,file_path:r},null,2)}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({error:`Error saving file: ${e.message}`},null,2)}],isError:!0}}return{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}async handleUpdate(e){const{id:n,from:r,...s}=e;let o=s;if(r){const e=t.join(this.tempDir,r);if(!Gm.exists(e))return{content:[{type:"text",text:JSON.stringify({error:`File not found: ${e}`},null,2)}],isError:!0};try{o={...Gm.readJson(e),...s}}catch(e){return{content:[{type:"text",text:JSON.stringify({error:`Error reading JSON file: ${e.message}`},null,2)}],isError:!0}}}const a=await this.knowledgeManagement.update(n,o);return{content:[{type:"text",text:JSON.stringify(a,null,2)}]}}async handleDelete(e){return await this.knowledgeManagement.delete(e.id),{content:[{type:"text",text:JSON.stringify({success:!0,message:"Knowledge item deleted successfully"})}]}}async handleList(e={}){const{to:n,...r}=e,s=await this.knowledgeManagement.list(r);if(n)try{const e=t.join(this.tempDir,n),o=s.map(e=>Gm.extractKnowledgeForJson(e));return Gm.writeJson(e,{count:s.length,filters:r,timestamp:(new Date).toISOString(),data:o}),{content:[{type:"text",text:JSON.stringify({success:!0,message:`${s.length} knowledge items saved to ${n}`,file_path:e},null,2)}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({error:`Error saving file: ${e.message}`},null,2)}],isError:!0}}return{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}async handleSearch(e){const{to:n,query:r,limit:s}=e,o=await this.knowledgeManagement.search(r,s);if(n)try{const e=t.join(this.tempDir,n),a=o.map(e=>Gm.extractKnowledgeForJson(e));return Gm.writeJson(e,{query:r,limit:s,count:o.length,timestamp:(new Date).toISOString(),data:a}),{content:[{type:"text",text:JSON.stringify({success:!0,message:`Search results (${o.length} items) saved to ${n}`,file_path:e},null,2)}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({error:`Error saving file: ${e.message}`},null,2)}],isError:!0}}return{content:[{type:"text",text:JSON.stringify(o,null,2)}]}}async handleUpdateStatus(e){const t=await this.knowledgeManagement.updateStatus(e.id,e.status);return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async handleStats(){const e=await this.knowledgeManagement.getStats();return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}async run(){const e=new Wm;await this.server.connect(e),Ym.logWarn(`Knowledge Bank MCP server running under ${process.cwd()}`)}}const ef=M("web-server","web-server"),tf=u(import.meta.url),nf=n(tf);class rf{constructor(e={}){this.port=e.port||3e3,this.isDev=e.dev||!1,this.app=_(),this.database=X(),this.db=this.database.getConnection(),this.server=null,this.connections=new Set,this.md=new w,this.setupApp()}setupApp(){this.app.set("view engine","ejs");const e=this.isDev?r(nf,"views"):r(nf,"web/views");this.app.set("views",e),this.app.use(v),this.app.set("layout","layout");const t=this.isDev?r(nf,"public"):r(nf,"web/public");this.app.use(_.static(t)),this.app.use(_.json()),this.app.use(_.urlencoded({extended:!0})),this.app.locals.formatTimestamp=this.formatTimestamp,this.app.locals.renderMarkdown=this.renderMarkdown.bind(this),this.app.locals.formatJsonAsMarkdown=this.formatJsonAsMarkdown.bind(this),this.setupRoutes()}async reconnect(){try{return ef.logInfo("Reconnecting to database..."),this.database.close(),this.db=this.database.getConnection(),ef.logInfo("Database reconnection successful"),!0}catch(e){throw ef.logError("Database reconnection failed:",e),e}}formatTimestamp(e){const t=new Date(parseInt(e));return isNaN(t)?e:`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")} ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}`}renderMarkdown(e){return e?this.md.render(e):""}formatJsonAsMarkdown(e){if(!e)return"";try{const t=JSON.parse(e),n=`\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``;return this.md.render(n)}catch(t){const n=`\`\`\`\n${e}\n\`\`\``;return this.md.render(n)}}setupRoutes(){this.app.get("/api/render/cell",(e,t)=>{const{tableName:n,col:r,value:s}=e.query;t.render("partials/cell",{tableName:n,col:r,val:s,layout:!1})}),this.app.get("/api/render/details",async(e,t)=>{const{tableName:n,id:r}=e.query,s=this.getRowById(n,r);if(!s)return t.status(404).send("Not found");t.render("partials/row-details",{tableName:n,data:s,layout:!1,renderMarkdown:this.renderMarkdown.bind(this),formatJsonAsMarkdown:this.formatJsonAsMarkdown.bind(this),formatTimestamp:this.formatTimestamp})}),this.app.get("/",(e,t)=>{const n=this.getTableNames().map(e=>({name:e,count:this.getTableCount(e)})),r=this.getRepositoriesWithCounts();t.render("index",{title:"Knowledge Bank Repository Browser",tableInfo:n,repositoryData:r,formatTimestamp:function(e){const t=new Date(parseInt(e));return isNaN(t)?e:`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")} ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}`},layout:"layout"})}),this.app.get("/repository/:id",(e,t)=>{try{const{id:n}=e.params,r=this.getRowById("repository",n);if(!r)return t.status(404).render("error",{title:"Error",error:"Repository not found",layout:"layout"});const s=this.getSessionsByRepository(n),o=this.getKnowledgeItemsByRepository(n),a=this.getHookEventsByRepository(n);function i(e){const t=new Date(parseInt(e));return isNaN(t)?e:`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")} ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}`}t.render("repository",{title:`Repository: ${r.name}`,repository:r,sessions:s,knowledgeItems:o,hookEvents:a,formatTimestamp:i,layout:"layout"})}catch(c){ef.logError(`Error viewing repository ${e.params.id}:`,c),t.status(500).render("error",{title:"Error",error:c.message,layout:"layout"})}}),this.app.get("/api/tables",(e,t)=>{try{const e=this.getTableNames();t.json({tables:e})}catch(e){ef.logError("Error getting tables:",e),t.status(500).json({error:e.message})}}),this.app.get("/api/tables/:table/schema",(e,t)=>{try{const{table:n}=e.params,r=this.getTableSchema(n);t.json({schema:r})}catch(e){ef.logError("Error getting table schema:",e),t.status(500).json({error:e.message})}}),this.app.get("/api/tables/:table/data",(e,t)=>{try{const{table:n}=e.params,r=parseInt(e.query.page)||1,s=parseInt(e.query.limit)||100,o=(r-1)*s,a={};if(e.query.repository_id){const t=parseInt(e.query.repository_id);isNaN(t)||(a.repository_id=t)}e.query.session_id&&(a.session_id=e.query.session_id),e.query.knowledge_type&&(a.knowledge_type=e.query.knowledge_type),e.query.status&&(a.status=e.query.status),e.query.branch&&(a.branch=e.query.branch),e.query.name&&(a.name=e.query.name),e.query.title&&(a.title=e.query.title),e.query.search&&(a.search=e.query.search);const i=e.query.sort||"",c=this.getTableData(n,s,o,a,i),d=this.getTableCount(n,a);t.json({data:c,pagination:{page:r,limit:s,total:d,pages:Math.ceil(d/s)}})}catch(e){ef.logError("Error getting table data:",e),t.status(500).json({error:e.message})}}),this.app.get("/api/tables/:table/row/:id",(e,t)=>{try{const{table:n,id:r}=e.params,s=this.getRowById(n,r);if(!s)return t.status(404).json({error:"Row not found"});t.json({data:s})}catch(n){ef.logError(`Error getting row from ${e.params.table}:`,n),t.status(500).json({error:n.message})}}),this.app.get("/api/tables/:table/relations",(e,t)=>{try{const{table:n}=e.params,r=this.getTableRelations(n);t.json({relations:r})}catch(e){ef.logError("Error getting table relations:",e),t.status(500).json({error:e.message})}}),this.app.get("/api/relations",(e,t)=>{try{const e=this.getDatabaseRelations();t.json({relations:e})}catch(e){ef.logError("Error getting database relations:",e),t.status(500).json({error:e.message})}}),this.app.post("/api/reconnect",async(e,t)=>{try{await this.reconnect(),t.json({success:!0,message:"Database reconnected successfully"})}catch(e){t.status(500).json({success:!1,error:e.message})}}),this.app.get("/tables/:table",(e,t)=>{try{const{table:n}=e.params,r=this.getTableSchema(n),s=this.getTableRelations(n),o=e.query.sort||"",a=this.parseSortParameter(o),i=this.getTableData(n,10,0,{},o),c=this.getEssentialColumns(n,r);t.render("table",{title:`Table: ${n}`,tableName:n,schema:r,relations:s,sampleData:i,essentialColumns:c,sortInfo:a,layout:"layout"})}catch(n){ef.logError(`Error viewing table ${e.params.table}:`,n),t.status(500).render("error",{title:"Error",error:n.message,layout:"layout"})}})}getTableNames(){const e=["hook_event","knowledge_item","repository","session","knowledge_item_fts"];return this.db.prepare("\n SELECT name FROM sqlite_master\n WHERE type = 'table' AND name NOT LIKE 'sqlite_%'\n ORDER BY name\n ").all().map(e=>e.name).filter(t=>e.includes(t))}getTableSchema(e){return this.db.prepare(`PRAGMA table_info(${e})`).all()}parseSortParameter(e){return e?e.endsWith("_asc")?{column:e.slice(0,-4),direction:"ASC",oppositeDirection:"DESC"}:e.endsWith("_desc")?{column:e.slice(0,-5),direction:"DESC",oppositeDirection:"ASC"}:{column:e,direction:"ASC",oppositeDirection:"DESC"}:{column:null,direction:null,oppositeDirection:null}}getTableData(e,t=100,n=0,r={},s=""){if("hook_event"===e&&r.repository_id)return this.getHookEventsByRepositoryPaginated(r.repository_id,t,n,s,r);let o="*";"knowledge_item"===e?o="repository_id, session_id, id, title, summary, scope, source_type, knowledge_type, status, created_at, updated_at":"repository"===e?o="id, name, remote_url, created_at, updated_at":"session"===e?o="id, session_id, repository_id, working_directory, branch, created_at":"hook_event"===e&&(o="session_id, id, name, created_at");let a="";const i=[];if(Object.keys(r).length>0){const t=(t=>{const n=[],r=[];return Object.entries(t).forEach(([t,s])=>{if(null!=s&&""!==s&&("hook_event"!==e||"repository_id"!==t))if("search"!==t){if("session_id"===t||"branch"===t||"name"===t||"title"===t)return n.push(`${t} LIKE ?`),void r.push(`%${s}%`);n.push(`${t} = ?`),r.push(s)}else if("knowledge_item"===e){n.push("(title LIKE ? OR summary LIKE ? OR content LIKE ? OR session_id LIKE ?)");const e=`%${s}%`;r.push(e,e,e,e)}else if("session"===e){n.push("(session_id LIKE ? OR branch LIKE ? OR working_directory LIKE ?)");const e=`%${s}%`;r.push(e,e,e)}else if("hook_event"===e){n.push("(name LIKE ? OR session_id LIKE ?)");const e=`%${s}%`;r.push(e,e)}}),{clause:n.length>0?` WHERE ${n.join(" AND ")}`:"",params:r}})(r);a=t.clause,i.push(...t.params)}let c="";if(s){const e=this.parseSortParameter(s);e.column&&e.direction&&(c=` ORDER BY ${e.column} ${e.direction}`)}else c=" ORDER BY id ASC";console.log(`[DEBUG] Table: ${e}, Query: SELECT ${o} FROM ${e}${a}${c}, Params:`,i),i.push(t,n);const d=this.db.prepare(`SELECT ${o} FROM ${e}${a}${c} LIMIT ? OFFSET ?`).all(...i);return"repository"===e&&d.forEach(e=>{const t=this.db.prepare("SELECT COUNT(*) as count FROM session WHERE repository_id = ?").get(e.id);e.sessionCount=t?t.count:0;const n=this.db.prepare("SELECT COUNT(*) as count FROM knowledge_item WHERE repository_id = ?").get(e.id);e.knowledgeCount=n?n.count:0}),d}getTableCount(e,t={}){if("hook_event"===e&&t.repository_id){let e=" WHERE s.repository_id = ?";const n=[t.repository_id];if(t.session_id&&(e+=" AND h.session_id LIKE ?",n.push(`%${t.session_id}%`)),t.name&&(e+=" AND h.name LIKE ?",n.push(`%${t.name}%`)),t.search){e+=" AND (h.name LIKE ? OR h.session_id LIKE ?)";const r=`%${t.search}%`;n.push(r,r)}return this.db.prepare(`SELECT COUNT(*) as count FROM hook_event h JOIN session s ON h.session_id = s.session_id${e}`).get(...n).count}let n="";const r=[];if(Object.keys(t).length>0){const s=[];Object.entries(t).forEach(([t,n])=>{if(null!=n&&""!==n&&("hook_event"!==e||"repository_id"!==t))if("search"!==t){if("session_id"===t||"branch"===t||"name"===t||"title"===t)return s.push(`${t} LIKE ?`),void r.push(`%${n}%`);s.push(`${t} = ?`),r.push(n)}else if("knowledge_item"===e){s.push("(title LIKE ? OR summary LIKE ? OR content LIKE ? OR session_id LIKE ?)");const e=`%${n}%`;r.push(e,e,e,e)}else if("session"===e){s.push("(session_id LIKE ? OR branch LIKE ? OR working_directory LIKE ?)");const e=`%${n}%`;r.push(e,e,e)}else if("hook_event"===e){s.push("(name LIKE ? OR session_id LIKE ?)");const e=`%${n}%`;r.push(e,e)}}),s.length>0&&(n=` WHERE ${s.join(" AND ")}`)}return this.db.prepare(`SELECT COUNT(*) as count FROM ${e}${n}`).get(...r).count}getRowById(e,t){return this.db.prepare(`SELECT * FROM ${e} WHERE id = ?`).get(t)}getEssentialColumns(e,t){const n=t.map(e=>e.name);return({knowledge_item:["id","title","summary","knowledge_type","status","repository_id","created_at"],repository:["id","name","created_at"],session:["id","session_id","branch","working_directory","repository_id","created_at"],hook_event:["id","session_id","name","created_at"],knowledge_item_fts:["rowid","title","summary"]}[e]||["id","name","title","created_at"]).filter(e=>n.includes(e))}getTableRelations(e){return this.db.prepare(`PRAGMA foreign_key_list(${e})`).all()}getDatabaseRelations(){const e=this.getTableNames(),t={};return e.forEach(e=>{t[e]={foreignKeys:this.getTableRelations(e),referencedBy:[]}}),e.forEach(e=>{t[e].foreignKeys.forEach(n=>{const r=n.table;t[r]&&t[r].referencedBy.push({table:e,from:n.from,to:n.to})})}),t}getRepositoriesWithCounts(){try{const e=this.getTableData("repository",100,0);return e.forEach(e=>{const t=this.db.prepare("SELECT COUNT(*) as count FROM session WHERE repository_id = ?").get(e.id);e.sessionCount=t?t.count:0;const n=this.db.prepare("SELECT COUNT(*) as count FROM knowledge_item WHERE repository_id = ?").get(e.id);e.knowledgeCount=n?n.count:0}),e}catch(e){return ef.logError("Error getting repositories with counts:",e),[]}}getSessionsByRepository(e){try{return this.db.prepare("SELECT id, session_id, working_directory, branch, created_at FROM session WHERE repository_id = ? ORDER BY created_at DESC LIMIT 100").all(e)}catch(t){return ef.logError(`Error getting sessions for repository ${e}:`,t),[]}}getKnowledgeItemsByRepository(e){try{return this.db.prepare("SELECT id, title, summary, scope, source_type, knowledge_type, status, created_at FROM knowledge_item WHERE repository_id = ? ORDER BY created_at DESC LIMIT 100").all(e)}catch(t){return ef.logError(`Error getting knowledge items for repository ${e}:`,t),[]}}getHookEventsByRepository(e){try{return this.db.prepare("SELECT h.id, h.session_id, h.name, h.created_at FROM hook_event h JOIN session s ON h.session_id = s.session_id WHERE s.repository_id = ? ORDER BY h.created_at DESC LIMIT 100").all(e)}catch(t){return ef.logError(`Error getting hook events for repository ${e}:`,t),[]}}getHookEventsByRepositoryPaginated(e,t=10,n=0,r="",s={}){try{let o=" WHERE s.repository_id = ?";const a=[e];if(s.session_id&&(o+=" AND h.session_id LIKE ?",a.push(`%${s.session_id}%`)),s.name&&(o+=" AND h.name LIKE ?",a.push(`%${s.name}%`)),s.search){o+=" AND (h.name LIKE ? OR h.session_id LIKE ?)";const e=`%${s.search}%`;a.push(e,e)}let i="";if(r){const e=this.parseSortParameter(r);e.column&&e.direction&&(i=` ORDER BY h.${e.column} ${e.direction}`)}else i=" ORDER BY h.id ASC";return a.push(t,n),this.db.prepare(`SELECT h.id, h.session_id, h.name, h.created_at\n FROM hook_event h\n JOIN session s ON h.session_id = s.session_id\n ${o}${i}\n LIMIT ? OFFSET ?`).all(...a)}catch(t){return ef.logError(`Error getting paginated hook events for repository ${e}:`,t),[]}}start(){return new Promise((e,t)=>{try{N(this.db),this.server=this.app.listen(this.port,()=>{this.isDev?(ef.logInfo(`Web server started in development mode on port ${this.port}`),ef.logInfo("🚀 Running from source code (no build required)")):ef.logInfo(`Web server started on port ${this.port}`),ef.logInfo(`Open http://localhost:${this.port} in your browser`),e(this)}),this.server.on("connection",e=>{this.connections.add(e),e.on("close",()=>{this.connections.delete(e)})})}catch(e){ef.logError("Error starting web server:",e),t(e)}})}stop(){return new Promise((e,t)=>{if(!this.server)return void e();const n=setTimeout(()=>{ef.logWarn("Forcing server shutdown due to timeout");for(const e of this.connections)e.destroy();this.connections.clear(),this.server=null,e()},5e3);this.server.close(r=>{if(clearTimeout(n),r){ef.logError("Error closing web server:",r);for(const e of this.connections)e.destroy();this.connections.clear(),t(r)}else ef.logInfo("Web server stopped gracefully"),this.server=null,this.connections.clear(),e()}),this.server.unref()})}}const sf=M("web-command","web-command"),of=q.version,af=P(),cf=new e;cf.name("knowledge-bank").description("Claude Code plugin for lightweight knowledge management").version(of);const df=new ue;cf.command("install").description("Install knowledge bank plugin").action(async()=>{await async function(){K().then(e=>e.find(e=>"knowledge-bank"===e.name)).then(async e=>{e||await new Promise((e,t)=>{l(`claude plugin marketplace add ${F}`,(n,r,s)=>{n?t(n):(s&&console.error(s),console.log(r),e())})}),await new Promise((e,t)=>{l("claude plugin install core@knowledge-bank",(n,r,s)=>{n?t(n):(s&&console.error(s),console.log(r),e())})})}).then(async()=>{await async function(){await oe.prepare(),oe.initialize()}()}).catch(e=>{console.error("Error during installation:",e)})}()}),cf.command("uninstall").description("Remove knowledge bank plugin").action(async()=>{await async function(){K().then(e=>e.find(e=>"knowledge-bank"===e.name)).then(async e=>{e?(await new Promise((e,t)=>{l("claude plugin uninstall core@knowledge-bank",(n,r,s)=>{n?t(n):(s&&console.error(s),console.log(r),e())})}),await new Promise((e,t)=>{l("claude plugin marketplace remove knowledge-bank",(n,r,s)=>{n?t(n):(s&&console.error(s),console.log(r),e())})})):console.log("knowledge-bank plugin is not installed.")}).catch(e=>{console.error("Error during uninstallation:",e)})}()}),cf.command("knowledge-status").description("Display knowledge bank status and statistics").addHelpText("after","\nOutput Example:\nKnowledge Bank Status:\nDatabase: ✓ Connected\nTotal Items: 156\nRecent Activity: 12 created, 8 updated (last 7 days)\n\nBy Scope:\n- Personal: 45\n- Project: 89\n- Organization: 22\n\nBy Status:\n- Draft: 67\n- Suggested: 34\n- Verified: 55\n\nBy Type:\n- Code Pattern: 42\n- Architecture: 38\n- Configuration: 25\n- Pitfall: 31\n- API Usage: 20").action(async()=>{await async function(){console.log("📚 Knowledge Bank Status\n");const e=oe.database.getPath(),t=oe.database.exists();if(console.log(`Database: ${e}`),console.log(`Status: ${t?"✓ Connected":"✗ Not found"}\n`),await de.gitUtils.isGitRepository()){const e=await de.repositoryManager.getCurrentRepository(),t=await de.gitUtils.getCurrentBranch();console.log("Current Repository:"),console.log(` Name: ${e.name}`),console.log(` Branch: ${t}`),console.log(` Remote: ${e.remote_url}\n`);const n={total:ie.knowledgeRepo.count({repository_id:e.id}),by_status:{draft:ie.knowledgeRepo.count({repository_id:e.id,status:"draft"}),suggested:ie.knowledgeRepo.count({repository_id:e.id,status:"suggested"}),verified:ie.knowledgeRepo.count({repository_id:e.id,status:"verified"})},by_scope:{personal:ie.knowledgeRepo.count({repository_id:e.id,scope:"personal"}),project:ie.knowledgeRepo.count({repository_id:e.id,scope:"project"}),organization:ie.knowledgeRepo.count({repository_id:e.id,scope:"organization"})}};console.log("Knowledge Statistics:"),console.log(` Total: ${n.total}`),console.log(" By Status:"),console.log(` - Draft: ${n.by_status.draft}`),console.log(` - Suggested: ${n.by_status.suggested}`),console.log(` - Verified: ${n.by_status.verified}`),console.log(" By Scope:"),console.log(` - Personal: ${n.by_scope.personal}`),console.log(` - Project: ${n.by_scope.project}`),console.log(` - Organization: ${n.by_scope.organization}\n`);const r=ce.sessionRepo.getRecentSessions(5);console.log(`Recent Sessions: ${r.length}`),r.length>0&&r.forEach((e,t)=>{const n=new Date(e.updated_at).toLocaleString();console.log(` ${t+1}. ${e.session_id.substring(0,8)}... (${n})`)})}else{console.log("Not in a Git repository\n");const e=ie.knowledgeRepo.count({});console.log("Global Knowledge Statistics:"),console.log(` Total: ${e}`)}}()});const uf=cf.command("knowledge").description("Manage knowledge items");uf.command("create").description("Create a new knowledge item").requiredOption("-t, --title <title>","[REQUIRED] Knowledge title").requiredOption("-s, --summary <summary>","[REQUIRED] Knowledge summary").requiredOption("-c, --content <content>","[REQUIRED] Knowledge content").requiredOption("--scope <scope>",`[REQUIRED] Scope: ${b.join(", ")}`).requiredOption("--source-type <type>",`[REQUIRED] Source type: ${k.join(", ")}`).requiredOption("--knowledge-type <type>",`[REQUIRED] Knowledge type: ${$.join(", ")}`).requiredOption("--status <status>",`[REQUIRED] Status: ${S.join(", ")}`).option("--source-file <file>","[OPTION] Source file path").option("--commit-hash <hash>","[OPTION] Commit hash").option("--contributor <contributor>","[OPTION] Contributor name").addHelpText("after",'\nOutput Example:\n{\n "id": 123,\n "title": "React Custom Hook Pattern",\n "summary": "Best practices for custom hooks",\n "content": "Always prefix with \'use\' and follow hooks rules",\n "scope": "project",\n "source_type": "ai",\n "knowledge_type": "code_pattern",\n "status": "draft",\n "source_file": null,\n "commit_hash": null,\n "contributor": null,\n "created_at": "2026-01-22T10:30:00Z",\n "updated_at": "2026-01-22T10:30:00Z"\n}').action(async e=>{console.log("creating knowledge");const t=await df.create({title:e.title,summary:e.summary,content:e.content,scope:e.scope,source_type:e.sourceType,knowledge_type:e.knowledgeType,status:e.status,source_file:e.sourceFile,commit_hash:e.commitHash,contributor:e.contributor});console.log(JSON.stringify(t,null,2))}),uf.command("get").description("Get a knowledge item by ID").argument("<id>","Knowledge item ID",parseInt).addHelpText("after",'\nOutput Example:\n{\n "id": 123,\n "title": "React Custom Hook Pattern",\n "summary": "Best practices for custom hooks",\n "content": "Always prefix with \'use\' and follow hooks rules",\n "scope": "project",\n "source_type": "ai",\n "knowledge_type": "code_pattern",\n "status": "verified",\n "source_file": "src/hooks/useCustomHook.ts",\n "commit_hash": "abc123def",\n "contributor": "Claude",\n "created_at": "2026-01-22T10:30:00Z",\n "updated_at": "2026-01-22T11:45:00Z"\n}').action(async e=>{const t=await df.get(e);t?console.log(JSON.stringify(t,null,2)):(console.log("Knowledge item not found"),process.exit(1))}),uf.command("update").description("Update a knowledge item").argument("<id>","Knowledge item ID",parseInt).option("-t, --title <title>","[OPTION] Knowledge title").option("-s, --summary <summary>","[OPTION] Knowledge summary").option("-c, --content <content>","[OPTION] Knowledge content").option("--scope <scope>",`[OPTION] Scope: ${b.join(", ")}`).option("--source-type <type>",`[OPTION] Source type: ${k.join(", ")}`).option("--knowledge-type <type>",`[OPTION] Knowledge type: ${$.join(", ")}`).option("--status <status>",`[OPTION] Status: ${S.join(", ")}`).option("--source-file <file>","[OPTION] Source file path").option("--commit-hash <hash>","[OPTION] Commit hash").option("--contributor <contributor>","[OPTION] Contributor name").addHelpText("after",'\nOutput Example:\n{\n "id": 123,\n "title": "Updated React Hook Pattern",\n "summary": "Enhanced best practices for custom hooks",\n "content": "Always prefix with \'use\', follow hooks rules, and add proper TypeScript types",\n "scope": "project",\n "source_type": "ai",\n "knowledge_type": "code_pattern",\n "status": "verified",\n "source_file": "src/hooks/useCustomHook.ts",\n "commit_hash": "def456ghi",\n "contributor": "Claude",\n "created_at": "2026-01-22T10:30:00Z",\n "updated_at": "2026-01-22T12:15:00Z"\n}').action(async(e,t)=>{const n=await df.update(e,{title:t.title,summary:t.summary,content:t.content,scope:t.scope,source_type:t.sourceType,knowledge_type:t.knowledgeType,status:t.status,source_file:t.sourceFile,commit_hash:t.commitHash,contributor:t.contributor});console.log(JSON.stringify(n,null,2))}),uf.command("delete").description("Delete a knowledge item").argument("<id>","Knowledge item ID",parseInt).addHelpText("after","\nOutput Example:\nKnowledge item deleted successfully").action(async e=>{await df.delete(e),console.log("Knowledge item deleted successfully")}),uf.command("list").description("List knowledge items").option("--scope <scope>","[OPTION] Filter by scope").option("--status <status>","[OPTION] Filter by status").option("--knowledge-type <type>","[OPTION] Filter by knowledge type").option("--limit <limit>","[OPTION] Limit number of results",parseInt,100).option("--offset <offset>","[OPTION] Offset for pagination",parseInt,0).addHelpText("after",'\nOutput Example:\n{\n "items": [\n {\n "id": 123,\n "title": "React Custom Hook Pattern",\n "summary": "Best practices for custom hooks",\n "scope": "project",\n "source_type": "ai",\n "knowledge_type": "code_pattern",\n "status": "verified",\n "created_at": "2026-01-22T10:30:00Z",\n "updated_at": "2026-01-22T12:15:00Z"\n },\n {\n "id": 124,\n "title": "API Error Handling",\n "summary": "Standard error handling patterns",\n "scope": "project",\n "source_type": "developer",\n "knowledge_type": "architecture",\n "status": "draft",\n "created_at": "2026-01-22T11:00:00Z",\n "updated_at": "2026-01-22T11:00:00Z"\n }\n ],\n "total": 2,\n "limit": 10,\n "offset": 0\n}').action(async e=>{const t=await df.list({scope:e.scope,status:e.status,knowledge_type:e.knowledgeType,limit:e.limit,offset:e.offset});console.log(JSON.stringify(t,null,2))}),uf.command("search").description("Search knowledge items by text").argument("<query...>","Search query terms").option("-l, --limit <limit>","[OPTION] Limit number of results",parseInt,10).addHelpText("after",'\nUsage Examples:\n $ knowledge search react hooks\n $ knowledge search "react hooks" --limit 5\n $ knowledge search title:api content:auth\n\nOutput Example:\n{\n "results": [\n {\n "id": 123,\n "title": "React Custom Hook Pattern",\n "summary": "Best practices for custom hooks",\n "content": "Always prefix with \'use\' and follow hooks rules",\n "scope": "project",\n "source_type": "ai",\n "knowledge_type": "code_pattern",\n "status": "verified",\n "relevance_score": 0.95,\n "created_at": "2026-01-22T10:30:00Z"\n }\n ],\n "total_results": 1,\n "query": "react hooks",\n "limit": 10\n}').action(async(e,t)=>{const n=await df.search(e,t.limit);console.log(JSON.stringify(n,null,2))}),uf.command("update-status").description("Update knowledge item status").argument("<id>","Knowledge item ID",parseInt).argument("<status>",`New status: ${S.join(", ")}`).addHelpText("after",'\nOutput Example:\n{\n "success": true,\n "message": "Status updated successfully",\n "id": 123,\n "old_status": "draft",\n "new_status": "verified",\n "updated_at": "2026-01-22T12:30:00Z"\n}').action(async(e,t)=>{const n=await df.updateStatus(e,t);console.log(JSON.stringify(n,null,2))}),uf.command("stats").description("Get knowledge statistics").addHelpText("after",'\nOutput Example:\n{\n "total_items": 156,\n "by_scope": {\n "personal": 45,\n "project": 89,\n "organization": 22\n },\n "by_status": {\n "draft": 67,\n "suggested": 34,\n "verified": 55\n },\n "by_knowledge_type": {\n "code_pattern": 42,\n "architecture": 38,\n "config": 25,\n "pitfall": 31,\n "api_usage": 20\n },\n "by_source_type": {\n "developer": 78,\n "architect": 23,\n "reviewer": 19,\n "ai": 36\n },\n "recent_activity": {\n "created_last_7_days": 12,\n "updated_last_7_days": 8\n }\n}').action(async()=>{const e=await df.getStats();console.log(JSON.stringify(e,null,2))}),cf.command("session-start").description("Hook: Called when a Claude Code session starts").action(async()=>{await le.parseInput().then(async e=>{new Ee(e).execute().then(e=>{e.send()})})}),cf.command("session-end").description("Hook: Called when a Claude Code session ends").action(async()=>{await le.parseInput().then(async e=>{new Pe(e).execute().then(e=>{e.send()})})}),cf.command("notification").description("Hook: Called when a notification is triggered").action(async()=>{await le.parseInput().then(async e=>{new Te(e).execute().then(e=>{e.send()})})}),cf.command("permission-request").description("Hook: Called when a permission request is made").action(async()=>{await le.parseInput().then(async e=>{new Oe(e).execute().then(e=>{e.send()})})}),cf.command("pre-tool-use").description("Hook: Called before a tool is used").action(async()=>{await le.parseInput().then(async e=>{new Re(e).execute().then(e=>{e.send()})})}),cf.command("post-tool-use").description("Hook: Called after a tool is used").action(async()=>{await le.parseInput().then(async e=>{new xe(e).execute().then(e=>{e.send()})})}),cf.command("pre-compact").description("Hook: Called before compacting the session").action(async()=>{await le.parseInput().then(async e=>{new Ne(e).execute().then(e=>{e.send()})})}),cf.command("stop").description("Hook: Called when a stop signal is received").action(async()=>{await le.parseInput().then(async e=>{new Ce(e).execute().then(e=>{e.send()})})}),cf.command("subagent-stop").description("Hook: Called when a subagent stops").action(async()=>{await le.parseInput().then(async e=>{new je(e).execute().then(e=>{e.send()})})}),cf.command("user-prompt-submit").description("Hook: Called when a user submits a prompt").action(async()=>{await le.parseInput().then(async e=>{new ze(e).execute().then(e=>{e.send()})})}),cf.command("mcp-server").description("Start the Knowledge Bank MCP server").action(async()=>{const e=new Qm;await e.run()}),cf.command("web").description("Start a web server for browsing the database").option("-p, --port <port>","Port to listen on",e=>parseInt(e,10),3e3).option("-d, --dev","Start from source code (development mode)").addHelpText("after","\nUsage Example:\n $ knowledge-bank web\n $ knowledge-bank web --port 8080\n $ knowledge-bank web --dev\n $ knowledge-bank web --dev --port 8080\n\nOptions:\n --dev Start in development mode from source code\n --port Specify the port number (default: 3000)\n\nThis command starts a web server that allows you to browse the SQLite database tables\nand their relationships. Open the URL displayed in your browser after starting the server.\n\nDevelopment mode (--dev) runs the server directly from source code without building,\nuseful for development and debugging purposes.").action(async e=>{await async function(e={}){const t=e.port||3e3,n=e.dev||!1;n?sf.logInfo(`Starting web server in development mode (from source) on port ${t}...`):sf.logInfo(`Starting web server on port ${t}...`),console.log("================================================="),console.log(" Knowledge Bank Database Browser"),n&&console.log(" 🚀 Development Mode (Source Code)"),console.log("================================================="),console.log(` Starting server on port ${t}...`),console.log(` Open http://localhost:${t} in your browser`),console.log(" Press Ctrl+C to stop the server"),console.log("=================================================");const r=new rf({port:t,dev:n}),s=async e=>{sf.logInfo(`\nReceived ${e}, shutting down web server gracefully...`),console.log("\nShutting down server...");try{await r.stop(),sf.logInfo("Web server stopped successfully"),console.log("Server stopped successfully"),process.exit(0)}catch(e){sf.logError("Error during shutdown:",e),console.error("Error during shutdown:",e.message),process.exit(1)}};process.on("SIGINT",()=>s("SIGINT")),process.on("SIGTERM",()=>s("SIGTERM")),process.on("unhandledRejection",(e,t)=>{sf.logError("Unhandled Rejection at:",t,"reason:",e)}),await r.start();const o=setInterval(()=>{},1e3),a=s,i=async e=>{clearInterval(o),await a(e)};return process.removeAllListeners("SIGINT"),process.removeAllListeners("SIGTERM"),process.on("SIGINT",()=>i("SIGINT")),process.on("SIGTERM",()=>i("SIGTERM")),r}(e)}),cf.command("config").description("Get Knowledge Bank configuration settings").option("-t --temp","Get temporary directory path").action(async e=>{e.temp?console.log(af.tmp):console.error("unsupported option. Use --temp to get the temporary directory path.")}),cf.parse(process.argv);