46d204ee9b
* fix: strip privacy tags from last_assistant_message in summarize path (cherry picked from commit bd68bfcc3cfe9d82977d5bdb87cf7e91a7258489) * fix: preserve Chroma relevance ordering in SQLite hydration When ChromaSearchStrategy queries by vector similarity with orderBy='relevance', SessionStore.getObservationsByIds and related methods silently coerced undefined to 'date_desc', destroying the semantic ranking. Add 'relevance' as a valid orderBy value that skips SQL ORDER BY and preserves caller-provided ID order. Fixes #2153 (cherry picked from commit 9fedf8fc165c01cc3a8a8cdb8c057ea980bf511e) * test(privacy): mock executeWithWorkerFallback and loadFromFileOnce Update the cherry-picked privacy-tag stripping test from swithek's fork to match current main: - Mock executeWithWorkerFallback / isWorkerFallback (the handler now uses these instead of workerHttpRequest directly). - Mock loadFromFileOnce in hook-settings.js (called by shouldTrackProject) so the handler resolves CLAUDE_MEM_EXCLUDED_PROJECTS to a string. - Switch the workerCallLog shape to record { path, method, body } and accept either object or JSON-string bodies. 10/10 tests pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: pass relevance through to SessionStore in ChromaSearchStrategy The Chroma strategy was coercing orderBy='relevance' to undefined before calling SessionStore. Combined with SessionStore's date_desc default for undefined, this destroyed the semantic ranking that Chroma had just computed. Pair this with the SessionStore-side fix from rogerdigital (commit 37c8988f) which now accepts 'relevance' as a valid orderBy and preserves caller-provided ID order. Adds a regression test asserting that getObservationsByIds returns rows in caller-provided order when orderBy='relevance', and continues to return date_desc order when orderBy is omitted. Closes #2153 Co-Authored-By: Roger Deng <13251150+rogerdigital@users.noreply.github.com> Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: isolate SDK boundary — settingSources, strictMcpConfig, cloud-provider env, observation cap Single architectural fix at the three @anthropic-ai/claude-agent-sdk query() call sites (SDKAgent.startSession, KnowledgeAgent.prime, KnowledgeAgent .executeQuery) plus the env sanitizer and ingest gate. Closes 6 issues: - #2155 settings.json bleed-through into observer SDK subprocess: pass settingSources: [] so user/project/local settings aren't inherited. - #2159 / #2171 / #2194 user MCP servers leak into observer SDK: pass strictMcpConfig: true alongside the existing mcpServers: {}. - #2199 Bedrock/Vertex env vars dropped: extend ENV_PRESERVE in src/supervisor/env-sanitizer.ts to keep CLAUDE_CODE_USE_BEDROCK, CLAUDE_CODE_USE_VERTEX, AWS_*, ANTHROPIC_VERTEX_PROJECT_ID, etc. - #2201 runaway tokens (345M/day reported): extend default CLAUDE_MEM_SKIP_TOOLS with exec_command, write_stdin, apply_patch and add a configurable CLAUDE_MEM_MAX_OBSERVATION_BYTES (default 64 KB) cap at the ingest gate. SDK option names verified against node_modules/@anthropic-ai/claude-agent-sdk/sdk.d.ts: settingSources?: SettingSource[] (SettingSource = 'user'|'project'|'local') strictMcpConfig?: boolean Anti-pattern guards observed: - Did not modify the proxy strip (#2099/#2115). - Did not skip Read/Write/Edit/Bash — those remain the primary observation surface; only added high-volume agentic-tool names (exec_command, write_stdin, apply_patch). - Did not invent SDK options. Closes #2155, #2159, #2171, #2194, #2199, #2201 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: restore Windows spawn fix from PR #751 + add Windows CI Re-applies the PowerShell Start-Process -WindowStyle Hidden daemon spawn that PR #751 (e6ae0176) introduced and commitd13662d5reverted. Also fixes the bun-runner cmd /c popup, sets detached:false on Windows for SDK subprocesses (so windowsHide actually works and claude.exe doesn't outlive the worker), and adds windows-latest CI to prevent regression. - ProcessManager.spawnDaemon: PowerShell -EncodedCommand branch back. Returns 0 sentinel on success — callers MUST use pid === undefined for failure detection, never falsy checks. - bun-runner.js: drop "cmd /c" wrapper. shell:true lets Node resolve bun.cmd via PATHEXT and respects windowsHide (the explicit cmd.exe wrapper was popping a visible window per hook — #2150, #2186). - process-registry.ts spawnSdkProcess: detached:false on Windows. Mixing detached:true with windowsHide:true is documented-undefined on Windows; with detached:false, windowsHide actually hides claude.exe and the SDK subprocess dies with the parent (#2190, #2198). - .github/workflows/windows.yml: smoke test counts visible cmd windows before/after spawn + grep guard that the Start-Process branch survives. WSL bash stdin (#2188) is acknowledged but deferred — the bash → node pipe boundary needs a real Windows VM to test, beyond this PR's scope. PTY for Claude CLI SDK mode (#2173, #2177) is also deferred per plan. Closes #2150, #2169, #2186, #2187, #2190, #2198 Refs #2183 (Windows perf — same root cause) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: Codex transcript ingestion + queue self-deadlock on Windows Three Windows-specific bugs surfaced by @MakaveliGER in #2192: A. Glob path normalization path.join(homedir(), ...) emits backslashes on Windows. globSync treats backslashes as escape characters, not separators, so it silently fails to match transcript files. Normalize backslashes to forward slashes before passing to globSync (only affects Windows; Unix paths unchanged). B. Live appends not picked up Per-file fs.watch on Windows ReFS/SMB misses appends to live JSONL files; the recursive root watcher is the only signal we can trust there. Expose FileTailer.poke() and call it from the root-watcher event when the file is already tailed, instead of returning early. Also normalize the resolved path so the tailer-map key matches what globSync stored. C. Queue self-deadlock on abort When the SDK generator aborts (idle timeout, user cancel, shutdown) with rows already claimed and yielded but not yet confirmed by ResponseProcessor, those rows sit in 'processing' under THIS worker's PID. The self-healing claim predicate skips them because the worker is still alive — the queue deadlocks until the worker restarts. In the .finally() block, walk the in-flight ids through markFailed so the retry ladder requeues them as 'pending' (or terminates them if retries are exhausted). Includes regression test tests/codex-transcript-watcher-windows.test.ts that asserts each fix at the source level so future refactors can't silently revert them. Co-Authored-By: MakaveliGER <noreply@github.com> Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> Closes #2192 * fix: standalone batch — npm peer-deps overrides, marketplace self-heal warning, cache prune - Add `overrides: { tree-sitter: ^0.25.0 }` to the generated plugin/package.json so `npm install --production` resolves cleanly without --legacy-peer-deps. Fixes the ERESOLVE between grammar packages declaring three different majors of tree-sitter as peer deps. Closes #2147. - mcp-server.ts: emit a single loud, actionable warning when MCP boots but the marketplace directory at ~/.claude/plugins/marketplaces/<source>/ is missing. IDE plugin loaders silently skip claude-mem hooks in this state while MCP keeps working — the user has no way to know memory capture is dead. We don't run an installer from MCP startup (different permission model), but we tell the user exactly which command to run. Closes #2174. - smart-install.js (both root and plugin variants): prune older claude-mem version directories from ~/.claude/plugins/cache/thedotmack/claude-mem/. Claude Code resolves and caches hook commands per session, so a stale 12.x directory keeps the old hook path alive across restarts even after upgrade. Pruning makes the stale path physically unreachable. Closes #2172 (stale version reference). Note: the issue's secondary claim that @anthropic-ai/claude-agent-sdk is missing from package.json is no longer true — it was added at line 115 in v12.4.x. - #2170 ("ToolUseContext is required for prompt hooks") triaged as upstream: the string does not appear anywhere in this repo. The error originates in Claude Code's hook framework, which we don't own. No code change here. Co-Authored-By: Amadan04 <amadan04@users.noreply.github.com> Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: remove stale macOS binary, regen plugin artifacts (build/bundle drift) The committed plugin/scripts/claude-mem (63 MB Mach-O) was last built at v10.3.2 (Feb 2026). It baked in BUILT_IN_VERSION="10.3.1", dev paths (/Users/alexnewman/Scripts/claude-mem/...), and a now-removed POST /api/sessions/complete client + handler (deleted by PR #2136). That meant macOS users running the cached binary hit 404s every time the SessionEnd hook fired (issue #2200), the /api/health endpoint reported a two-major-versions-ago version (issue #2158), and the binary embedded a Zod copy that drifted from the worker bundle (issue #2154). - Delete plugin/scripts/claude-mem and gitignore it. The npm package already excludes it from the "files" allowlist, so no consumer change. The JS fallback (bun-runner.js → worker-service.cjs) covers all functionality on every platform per the existing checkBinaryPlatformCompatibility comment in smart-install.js. - Add npm run build:cli-binary for users who want the macOS speedup back. Produces it on demand from current source — no drift. - Regenerate plugin/scripts/{worker-service,mcp-server}.cjs and plugin/ui/viewer-bundle.js so the shipped artifacts match HEAD. Closes #2158, #2200, #2154. * fix(ci): Windows workflow — install without lockfile (project uses Bun) actions/setup-node@v4 cache: npm requires a package-lock.json and this project uses Bun (only bunfig.toml exists at root). Drop the cache directive, switch npm ci to npm install --no-audit --no-fund, and narrow the build step to npm run build — build-and-sync also runs a marketplace sync + worker restart that hardcodes ~/.claude/plugins, which doesn't exist on CI. * fix: harden observation cap parsing + safe stringify in debug logger CodeRabbit majors on #2206: - shared.ts: validate parsed cap is finite and > 0 before use; wrap JSON.stringify(payload.toolResponse) in try/catch and skip with reason 'payload_unserializable' on circular/throwing payloads, so ingestion never crashes on a bad tool response shape. - logger.ts: the debug-mode JSON dump for objects was unguarded; wrap stringify in try/catch and fall back to formatData on cycles. This is the source the bundled plugin/scripts/context-generator.cjs is built from. * fix(ci+windows): quote bun-runner shell:true args; replace dynamic smoke with static guards CodeRabbit majors on #2208: 1. plugin/scripts/bun-runner.js — shell:true with separate spawnArgs triggers DEP0190 on Node 22+ and breaks paths/args containing spaces. Build a single fully-quoted command string (mirroring findBun()'s 'where bun' approach) and pass spawnArgs=[]. 2. .github/workflows/windows.yml — the dynamic smoke step that counted visible cmd windows around 'claude-mem start' exits 1 on 'claude-mem is not installed' before exercising the spawn path, AND PowerShell try/catch doesn't suppress native exit codes regardless. Replace with three static regression guards covering the exact patterns PR #2208 protects: - PowerShell Start-Process + WindowStyle Hidden in spawnDaemon - bun-runner shell:true with empty spawnArgs (DEP0190 guard) - windowsHide set on SDK spawn factory (issue #2190) * fix(2210): cross-platform paths — Windows USERPROFILE + XDG cache symmetry Greptile P2s on #2210: - mcp-server.ts checkMarketplaceMarker: switch from process.env.HOME ?? '' to os.homedir(). HOME is unset on Windows; the empty fallback resolves relative to cwd, silently no-opping the canary on every Windows install. Also probe both ~/.claude/ and ~/.config/claude/ for the cache check so XDG users get the same warning behavior. - smart-install.js pruneStaleVersionCache (both root + plugin copies): scan both ~/.claude/plugins/cache/thedotmack/ and ~/.config/claude/... paths so users on XDG don't keep stale dirs re-triggering #2172. Greptile's third P2 (mtime vs semver sort for current version) deferred: mtime works correctly for the common case and the directory names start with versions that lexicographically sort the same way mtime does for sequentially-installed versions; semver sort would be a separate change. Refs PR #2210 * fix(2211): drop hardcoded --target from build:cli-binary Greptile P2: the npm script was pinned to bun-darwin-arm64, so an Intel Mac user (or anyone on Linux/Windows running this script manually) got a cross-compiled arm64 binary that runs only via Rosetta on x64 macOS and not at all elsewhere. Bun's --compile defaults to the host platform when --target is omitted. Drop the flag so the script produces a binary that matches whoever runs it. CI builds that need a specific target can still pass --target explicitly. Refs PR #2211 * ci(windows): drop static-grep tripwires, keep real Windows build The "Anti-regression" steps grep ProcessManager.ts/bun-runner.js/process-registry.ts for specific strings (Start-Process, WindowStyle Hidden, shell:true, windowsHide). Tripwires aren't fixes — they make refactoring harder forever and verify nothing the actual Windows build doesn't already verify. The npm install + npm run build on windows-latest is the real guard. * revert: drop byte cap and skip-list extension band-aids Strips two band-aid mechanisms from the SDK boundary fix, keeping only the genuine isolation flags (settingSources: [], strictMcpConfig: true) and the cloud-provider env preservation. Removed: - CLAUDE_MEM_MAX_OBSERVATION_BYTES (default 65536) — dropped oversize observations entirely. The structural fix is to chunk/summarize oversize tool results, not punish the data flow with an invented byte threshold. Tracked separately. - exec_command, write_stdin, apply_patch added to default skip list — static taste decision baked into defaults for everyone. Users can still set CLAUDE_MEM_SKIP_TOOLS themselves. The data flows again. Real fix is a follow-up. * revert: drop pruneStaleVersionCache walker Removes the cache walker that scans plugin cache dirs and deletes "old" version directories by inferred staleness. The structural fix for #2172 is for the installer to delete the prior version when it writes the new one — not for a separate walker to wake up later and guess which directories are stale. Keeps: - npm peer-dep override for tree-sitter (#2147) - Marketplace marker startup probe (#2174) - Cross-platform path handling Tracked separately as a follow-up. * build: regenerate bundled artifacts after merge Rebuilt plugin/scripts/*.cjs from src after merging #2211, #2204, #2205, #2208, #2209, #2206 (post-strip), #2210 (post-strip). Conflicts during merge were resolved by accepting incoming bundled artifacts; this commit replaces them with a clean rebuild from the merged source. Verified: 0 references to MAX_OBSERVATION_BYTES, payload_too_large, or pruneStaleVersionCache in the rebuilt artifacts. --------- Co-authored-by: swithek <52840391+swithek@users.noreply.github.com> Co-authored-by: Roger Deng <13251150+rogerdigital@users.noreply.github.com> Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> Co-authored-by: Amadan04 <amadan04@users.noreply.github.com>
177 lines
231 KiB
JavaScript
Executable File
177 lines
231 KiB
JavaScript
Executable File
#!/usr/bin/env node
|
|
"use strict";var cd=Object.create;var Bi=Object.defineProperty;var ld=Object.getOwnPropertyDescriptor;var ud=Object.getOwnPropertyNames;var dd=Object.getPrototypeOf,fd=Object.prototype.hasOwnProperty;var b=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var pd=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ud(e))!fd.call(t,s)&&s!==r&&Bi(t,s,{get:()=>e[s],enumerable:!(n=ld(e,s))||n.enumerable});return t};var se=(t,e,r)=>(r=t!=null?cd(dd(t)):{},pd(e||!t||!t.__esModule?Bi(r,"default",{value:t,enumerable:!0}):r,t));var lr=b(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.regexpCode=N.getEsmExportName=N.getProperty=N.safeStringify=N.stringify=N.strConcat=N.addCodeArg=N.str=N._=N.nil=N._Code=N.Name=N.IDENTIFIER=N._CodeOrName=void 0;var ar=class{};N._CodeOrName=ar;N.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var ot=class extends ar{constructor(e){if(super(),!N.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};N.Name=ot;var me=class extends ar{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof ot&&(r[n.str]=(r[n.str]||0)+1),r),{})}};N._Code=me;N.nil=new me("");function _a(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Ms(r,e[n]),r.push(t[++n]);return new me(r)}N._=_a;var Rs=new me("+");function Sa(t,...e){let r=[cr(t[0])],n=0;for(;n<e.length;)r.push(Rs),Ms(r,e[n]),r.push(Rs,cr(t[++n]));return sp(r),new me(r)}N.str=Sa;function Ms(t,e){e instanceof me?t.push(...e._items):e instanceof ot?t.push(e):t.push(ap(e))}N.addCodeArg=Ms;function sp(t){let e=1;for(;e<t.length-1;){if(t[e]===Rs){let r=op(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function op(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof ot||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof ot))return`"${t}${e.slice(1)}`}function ip(t,e){return e.emptyStr()?t:t.emptyStr()?e:Sa`${t}${e}`}N.strConcat=ip;function ap(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:cr(Array.isArray(t)?t.join(","):t)}function cp(t){return new me(cr(t))}N.stringify=cp;function cr(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}N.safeStringify=cr;function lp(t){return typeof t=="string"&&N.IDENTIFIER.test(t)?new me(`.${t}`):_a`[${t}]`}N.getProperty=lp;function up(t){if(typeof t=="string"&&N.IDENTIFIER.test(t))return new me(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}N.getEsmExportName=up;function dp(t){return new me(t.toString())}N.regexpCode=dp});var Os=b(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.ValueScope=ie.ValueScopeName=ie.Scope=ie.varKinds=ie.UsedValueState=void 0;var oe=lr(),As=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},ln;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(ln||(ie.UsedValueState=ln={}));ie.varKinds={const:new oe.Name("const"),let:new oe.Name("let"),var:new oe.Name("var")};var un=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof oe.Name?e:this.name(e)}name(e){return new oe.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||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}}};ie.Scope=un;var dn=class extends oe.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,oe._)`.${new oe.Name(r)}[${n}]`}};ie.ValueScopeName=dn;var fp=(0,oe._)`\n`,Cs=class extends un{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?fp:oe.nil}}get(){return this._scope}name(e){return new dn(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let s=this.toName(e),{prefix:o}=s,i=(n=r.key)!==null&&n!==void 0?n:r.ref,c=this._values[o];if(c){let d=c.get(i);if(d)return d}else c=this._values[o]=new Map;c.set(i,s);let l=this._scope[o]||(this._scope[o]=[]),u=l.length;return l[u]=r.ref,s.setValue(r,{property:o,itemIndex:u}),s}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,oe._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},r,n)}_reduceValues(e,r,n={},s){let o=oe.nil;for(let i in e){let c=e[i];if(!c)continue;let l=n[i]=n[i]||new Map;c.forEach(u=>{if(l.has(u))return;l.set(u,ln.Started);let d=r(u);if(d){let f=this.opts.es5?ie.varKinds.var:ie.varKinds.const;o=(0,oe._)`${o}${f} ${u} = ${d};${this.opts._n}`}else if(d=s?.(u))o=(0,oe._)`${o}${d}${this.opts._n}`;else throw new As(u);l.set(u,ln.Completed)})}return o}};ie.ValueScope=Cs});var R=b(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.or=M.and=M.not=M.CodeGen=M.operators=M.varKinds=M.ValueScopeName=M.ValueScope=M.Scope=M.Name=M.regexpCode=M.stringify=M.getProperty=M.nil=M.strConcat=M.str=M._=void 0;var I=lr(),we=Os(),Be=lr();Object.defineProperty(M,"_",{enumerable:!0,get:function(){return Be._}});Object.defineProperty(M,"str",{enumerable:!0,get:function(){return Be.str}});Object.defineProperty(M,"strConcat",{enumerable:!0,get:function(){return Be.strConcat}});Object.defineProperty(M,"nil",{enumerable:!0,get:function(){return Be.nil}});Object.defineProperty(M,"getProperty",{enumerable:!0,get:function(){return Be.getProperty}});Object.defineProperty(M,"stringify",{enumerable:!0,get:function(){return Be.stringify}});Object.defineProperty(M,"regexpCode",{enumerable:!0,get:function(){return Be.regexpCode}});Object.defineProperty(M,"Name",{enumerable:!0,get:function(){return Be.Name}});var hn=Os();Object.defineProperty(M,"Scope",{enumerable:!0,get:function(){return hn.Scope}});Object.defineProperty(M,"ValueScope",{enumerable:!0,get:function(){return hn.ValueScope}});Object.defineProperty(M,"ValueScopeName",{enumerable:!0,get:function(){return hn.ValueScopeName}});Object.defineProperty(M,"varKinds",{enumerable:!0,get:function(){return hn.varKinds}});M.operators={GT:new I._Code(">"),GTE:new I._Code(">="),LT:new I._Code("<"),LTE:new I._Code("<="),EQ:new I._Code("==="),NEQ:new I._Code("!=="),NOT:new I._Code("!"),OR:new I._Code("||"),AND:new I._Code("&&"),ADD:new I._Code("+")};var qe=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Is=class extends qe{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?we.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${s};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=vt(this.rhs,e,r)),this}get names(){return this.rhs instanceof I._CodeOrName?this.rhs.names:{}}},fn=class extends qe{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof I.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=vt(this.rhs,e,r),this}get names(){let e=this.lhs instanceof I.Name?{}:{...this.lhs.names};return mn(e,this.rhs)}},xs=class extends fn{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ds=class extends qe{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ns=class extends qe{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},zs=class extends qe{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ls=class extends qe{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=vt(this.code,e,r),this}get names(){return this.code instanceof I._CodeOrName?this.code.names:{}}},ur=class extends qe{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,s=n.length;for(;s--;){let o=n[s];o.optimizeNames(e,r)||(pp(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>ct(e,r.names),{})}},Ue=class extends ur{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},js=class extends ur{},bt=class extends Ue{};bt.kind="else";var it=class t extends Ue{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new bt(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Ea(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=vt(this.condition,e,r),this}get names(){let e=super.names;return mn(e,this.condition),this.else&&ct(e,this.else.names),e}};it.kind="if";var at=class extends Ue{};at.kind="for";var qs=class extends at{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=vt(this.iteration,e,r),this}get names(){return ct(super.names,this.iteration.names)}},Us=class extends at{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?we.varKinds.var:this.varKind,{name:n,from:s,to:o}=this;return`for(${r} ${n}=${s}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=mn(super.names,this.from);return mn(e,this.to)}},pn=class extends at{constructor(e,r,n,s){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=s}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=vt(this.iterable,e,r),this}get names(){return ct(super.names,this.iterable.names)}},dr=class extends Ue{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};dr.kind="func";var fr=class extends ur{render(e){return"return "+super.render(e)}};fr.kind="return";var Fs=class extends Ue{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,s;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(s=this.finally)===null||s===void 0||s.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&ct(e,this.catch.names),this.finally&&ct(e,this.finally.names),e}},pr=class extends Ue{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};pr.kind="catch";var mr=class extends Ue{render(e){return"finally"+super.render(e)}};mr.kind="finally";var Hs=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
`:""},this._extScope=e,this._scope=new we.Scope({parent:e}),this._nodes=[new js]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,s){let o=this._scope.toName(r);return n!==void 0&&s&&(this._constants[o.str]=n),this._leafNode(new Is(e,o,n)),o}const(e,r,n){return this._def(we.varKinds.const,e,r,n)}let(e,r,n){return this._def(we.varKinds.let,e,r,n)}var(e,r,n){return this._def(we.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new fn(e,r,n))}add(e,r){return this._leafNode(new xs(e,M.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==I.nil&&this._leafNode(new Ls(e)),this}object(...e){let r=["{"];for(let[n,s]of e)r.length>1&&r.push(","),r.push(n),(n!==s||this.opts.es5)&&(r.push(":"),(0,I.addCodeArg)(r,s));return r.push("}"),new I._Code(r)}if(e,r,n){if(this._blockNode(new it(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new it(e))}else(){return this._elseNode(new bt)}endIf(){return this._endBlockNode(it,bt)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new qs(e),r)}forRange(e,r,n,s,o=this.opts.es5?we.varKinds.var:we.varKinds.let){let i=this._scope.toName(e);return this._for(new Us(o,i,r,n),()=>s(i))}forOf(e,r,n,s=we.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=r instanceof I.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,I._)`${i}.length`,c=>{this.var(o,(0,I._)`${i}[${c}]`),n(o)})}return this._for(new pn("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?we.varKinds.var:we.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,I._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new pn("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(at)}label(e){return this._leafNode(new Ds(e))}break(e){return this._leafNode(new Ns(e))}return(e){let r=new fr;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(fr)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new Fs;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new pr(o),r(o)}return n&&(this._currNode=s.finally=new mr,this.code(n)),this._endBlockNode(pr,mr)}throw(e){return this._leafNode(new zs(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=I.nil,n,s){return this._blockNode(new dr(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(dr)}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,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof it))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};M.CodeGen=Hs;function ct(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function mn(t,e){return e instanceof I._CodeOrName?ct(t,e.names):t}function vt(t,e,r){if(t instanceof I.Name)return n(t);if(!s(t))return t;return new I._Code(t._items.reduce((o,i)=>(i instanceof I.Name&&(i=n(i)),i instanceof I._Code?o.push(...i._items):o.push(i),o),[]));function n(o){let i=r[o.str];return i===void 0||e[o.str]!==1?o:(delete e[o.str],i)}function s(o){return o instanceof I._Code&&o._items.some(i=>i instanceof I.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function pp(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Ea(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,I._)`!${Ws(t)}`}M.not=Ea;var mp=wa(M.operators.AND);function hp(...t){return t.reduce(mp)}M.and=hp;var gp=wa(M.operators.OR);function yp(...t){return t.reduce(gp)}M.or=yp;function wa(t){return(e,r)=>e===I.nil?r:r===I.nil?e:(0,I._)`${Ws(e)} ${t} ${Ws(r)}`}function Ws(t){return t instanceof I.Name?t:(0,I._)`(${t})`}});var x=b(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.checkStrictMode=C.getErrorPath=C.Type=C.useFunc=C.setEvaluated=C.evaluatedPropsToName=C.mergeEvaluated=C.eachItem=C.unescapeJsonPointer=C.escapeJsonPointer=C.escapeFragment=C.unescapeFragment=C.schemaRefOrVal=C.schemaHasRulesButRef=C.schemaHasRules=C.checkUnknownRules=C.alwaysValidSchema=C.toHash=void 0;var L=R(),_p=lr();function Sp(t){let e={};for(let r of t)e[r]=!0;return e}C.toHash=Sp;function Ep(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(ka(t,e),!Ta(e,t.self.RULES.all))}C.alwaysValidSchema=Ep;function ka(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let s=n.RULES.keywords;for(let o in e)s[o]||Ra(t,`unknown keyword: "${o}"`)}C.checkUnknownRules=ka;function Ta(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}C.schemaHasRules=Ta;function wp(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}C.schemaHasRulesButRef=wp;function bp({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,L._)`${r}`}return(0,L._)`${t}${e}${(0,L.getProperty)(n)}`}C.schemaRefOrVal=bp;function vp(t){return Pa(decodeURIComponent(t))}C.unescapeFragment=vp;function kp(t){return encodeURIComponent(Gs(t))}C.escapeFragment=kp;function Gs(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}C.escapeJsonPointer=Gs;function Pa(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}C.unescapeJsonPointer=Pa;function Tp(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}C.eachItem=Tp;function ba({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,o,i,c)=>{let l=i===void 0?o:i instanceof L.Name?(o instanceof L.Name?t(s,o,i):e(s,o,i),i):o instanceof L.Name?(e(s,i,o),o):r(o,i);return c===L.Name&&!(l instanceof L.Name)?n(s,l):l}}C.mergeEvaluated={props:ba({mergeNames:(t,e,r)=>t.if((0,L._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,L._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,L._)`${r} || {}`).code((0,L._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,L._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,L._)`${r} || {}`),Ks(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:$a}),items:ba({mergeNames:(t,e,r)=>t.if((0,L._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,L._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,L._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,L._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function $a(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,L._)`{}`);return e!==void 0&&Ks(t,r,e),r}C.evaluatedPropsToName=$a;function Ks(t,e,r){Object.keys(r).forEach(n=>t.assign((0,L._)`${e}${(0,L.getProperty)(n)}`,!0))}C.setEvaluated=Ks;var va={};function Pp(t,e){return t.scopeValue("func",{ref:e,code:va[e.code]||(va[e.code]=new _p._Code(e.code))})}C.useFunc=Pp;var Vs;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Vs||(C.Type=Vs={}));function $p(t,e,r){if(t instanceof L.Name){let n=e===Vs.Num;return r?n?(0,L._)`"[" + ${t} + "]"`:(0,L._)`"['" + ${t} + "']"`:n?(0,L._)`"/" + ${t}`:(0,L._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,L.getProperty)(t).toString():"/"+Gs(t)}C.getErrorPath=$p;function Ra(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}C.checkStrictMode=Ra});var Fe=b(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});var Z=R(),Rp={data:new Z.Name("data"),valCxt:new Z.Name("valCxt"),instancePath:new Z.Name("instancePath"),parentData:new Z.Name("parentData"),parentDataProperty:new Z.Name("parentDataProperty"),rootData:new Z.Name("rootData"),dynamicAnchors:new Z.Name("dynamicAnchors"),vErrors:new Z.Name("vErrors"),errors:new Z.Name("errors"),this:new Z.Name("this"),self:new Z.Name("self"),scope:new Z.Name("scope"),json:new Z.Name("json"),jsonPos:new Z.Name("jsonPos"),jsonLen:new Z.Name("jsonLen"),jsonPart:new Z.Name("jsonPart")};Ys.default=Rp});var hr=b(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.extendErrors=X.resetErrorsCount=X.reportExtraError=X.reportError=X.keyword$DataError=X.keywordError=void 0;var D=R(),gn=x(),te=Fe();X.keywordError={message:({keyword:t})=>(0,D.str)`must pass "${t}" keyword validation`};X.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,D.str)`"${t}" keyword must be ${e} ($data)`:(0,D.str)`"${t}" keyword is invalid ($data)`};function Mp(t,e=X.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:c}=s,l=Ca(t,e,r);n??(i||c)?Ma(o,l):Aa(s,(0,D._)`[${l}]`)}X.reportError=Mp;function Ap(t,e=X.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,c=Ca(t,e,r);Ma(s,c),o||i||Aa(n,te.default.vErrors)}X.reportExtraError=Ap;function Cp(t,e){t.assign(te.default.errors,e),t.if((0,D._)`${te.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,D._)`${te.default.vErrors}.length`,e),()=>t.assign(te.default.vErrors,null)))}X.resetErrorsCount=Cp;function Op({gen:t,keyword:e,schemaValue:r,data:n,errsCount:s,it:o}){if(s===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",s,te.default.errors,c=>{t.const(i,(0,D._)`${te.default.vErrors}[${c}]`),t.if((0,D._)`${i}.instancePath === undefined`,()=>t.assign((0,D._)`${i}.instancePath`,(0,D.strConcat)(te.default.instancePath,o.errorPath))),t.assign((0,D._)`${i}.schemaPath`,(0,D.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,D._)`${i}.schema`,r),t.assign((0,D._)`${i}.data`,n))})}X.extendErrors=Op;function Ma(t,e){let r=t.const("err",e);t.if((0,D._)`${te.default.vErrors} === null`,()=>t.assign(te.default.vErrors,(0,D._)`[${r}]`),(0,D._)`${te.default.vErrors}.push(${r})`),t.code((0,D._)`${te.default.errors}++`)}function Aa(t,e){let{gen:r,validateName:n,schemaEnv:s}=t;s.$async?r.throw((0,D._)`new ${t.ValidationError}(${e})`):(r.assign((0,D._)`${n}.errors`,e),r.return(!1))}var lt={keyword:new D.Name("keyword"),schemaPath:new D.Name("schemaPath"),params:new D.Name("params"),propertyName:new D.Name("propertyName"),message:new D.Name("message"),schema:new D.Name("schema"),parentSchema:new D.Name("parentSchema")};function Ca(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,D._)`{}`:Ip(t,e,r)}function Ip(t,e,r={}){let{gen:n,it:s}=t,o=[xp(s,r),Dp(t,r)];return Np(t,e,o),n.object(...o)}function xp({errorPath:t},{instancePath:e}){let r=e?(0,D.str)`${t}${(0,gn.getErrorPath)(e,gn.Type.Str)}`:t;return[te.default.instancePath,(0,D.strConcat)(te.default.instancePath,r)]}function Dp({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let s=n?e:(0,D.str)`${e}/${t}`;return r&&(s=(0,D.str)`${s}${(0,gn.getErrorPath)(r,gn.Type.Str)}`),[lt.schemaPath,s]}function Np(t,{params:e,message:r},n){let{keyword:s,data:o,schemaValue:i,it:c}=t,{opts:l,propertyName:u,topSchemaRef:d,schemaPath:f}=c;n.push([lt.keyword,s],[lt.params,typeof e=="function"?e(t):e||(0,D._)`{}`]),l.messages&&n.push([lt.message,typeof r=="function"?r(t):r]),l.verbose&&n.push([lt.schema,i],[lt.parentSchema,(0,D._)`${d}${f}`],[te.default.data,o]),u&&n.push([lt.propertyName,u])}});var Ia=b(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.boolOrEmptySchema=kt.topBoolOrEmptySchema=void 0;var zp=hr(),Lp=R(),jp=Fe(),qp={message:"boolean schema is false"};function Up(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Oa(t,!1):typeof r=="object"&&r.$async===!0?e.return(jp.default.data):(e.assign((0,Lp._)`${n}.errors`,null),e.return(!0))}kt.topBoolOrEmptySchema=Up;function Fp(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Oa(t)):r.var(e,!0)}kt.boolOrEmptySchema=Fp;function Oa(t,e){let{gen:r,data:n}=t,s={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,zp.reportError)(s,qp,void 0,e)}});var Js=b(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.getRules=Tt.isJSONType=void 0;var Hp=["string","number","integer","boolean","null","object","array"],Wp=new Set(Hp);function Vp(t){return typeof t=="string"&&Wp.has(t)}Tt.isJSONType=Vp;function Gp(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Tt.getRules=Gp});var Bs=b(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.shouldUseRule=Ze.shouldUseGroup=Ze.schemaHasRulesForType=void 0;function Kp({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&xa(t,n)}Ze.schemaHasRulesForType=Kp;function xa(t,e){return e.rules.some(r=>Da(t,r))}Ze.shouldUseGroup=xa;function Da(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Ze.shouldUseRule=Da});var gr=b(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.reportTypeError=Q.checkDataTypes=Q.checkDataType=Q.coerceAndCheckDataType=Q.getJSONTypes=Q.getSchemaTypes=Q.DataType=void 0;var Yp=Js(),Jp=Bs(),Bp=hr(),$=R(),Na=x(),Pt;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Pt||(Q.DataType=Pt={}));function Zp(t){let e=za(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Q.getSchemaTypes=Zp;function za(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Yp.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Q.getJSONTypes=za;function Xp(t,e){let{gen:r,data:n,opts:s}=t,o=Qp(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,Jp.schemaHasRulesForType)(t,e[0]));if(i){let c=Xs(e,n,s.strictNumbers,Pt.Wrong);r.if(c,()=>{o.length?em(t,e,o):Qs(t)})}return i}Q.coerceAndCheckDataType=Xp;var La=new Set(["string","number","integer","boolean","null"]);function Qp(t,e){return e?t.filter(r=>La.has(r)||e==="array"&&r==="array"):[]}function em(t,e,r){let{gen:n,data:s,opts:o}=t,i=n.let("dataType",(0,$._)`typeof ${s}`),c=n.let("coerced",(0,$._)`undefined`);o.coerceTypes==="array"&&n.if((0,$._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,$._)`${s}[0]`).assign(i,(0,$._)`typeof ${s}`).if(Xs(e,s,o.strictNumbers),()=>n.assign(c,s))),n.if((0,$._)`${c} !== undefined`);for(let u of r)(La.has(u)||u==="array"&&o.coerceTypes==="array")&&l(u);n.else(),Qs(t),n.endIf(),n.if((0,$._)`${c} !== undefined`,()=>{n.assign(s,c),tm(t,c)});function l(u){switch(u){case"string":n.elseIf((0,$._)`${i} == "number" || ${i} == "boolean"`).assign(c,(0,$._)`"" + ${s}`).elseIf((0,$._)`${s} === null`).assign(c,(0,$._)`""`);return;case"number":n.elseIf((0,$._)`${i} == "boolean" || ${s} === null
|
|
|| (${i} == "string" && ${s} && ${s} == +${s})`).assign(c,(0,$._)`+${s}`);return;case"integer":n.elseIf((0,$._)`${i} === "boolean" || ${s} === null
|
|
|| (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(c,(0,$._)`+${s}`);return;case"boolean":n.elseIf((0,$._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(c,!1).elseIf((0,$._)`${s} === "true" || ${s} === 1`).assign(c,!0);return;case"null":n.elseIf((0,$._)`${s} === "" || ${s} === 0 || ${s} === false`),n.assign(c,null);return;case"array":n.elseIf((0,$._)`${i} === "string" || ${i} === "number"
|
|
|| ${i} === "boolean" || ${s} === null`).assign(c,(0,$._)`[${s}]`)}}}function tm({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,$._)`${e} !== undefined`,()=>t.assign((0,$._)`${e}[${r}]`,n))}function Zs(t,e,r,n=Pt.Correct){let s=n===Pt.Correct?$.operators.EQ:$.operators.NEQ,o;switch(t){case"null":return(0,$._)`${e} ${s} null`;case"array":o=(0,$._)`Array.isArray(${e})`;break;case"object":o=(0,$._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,$._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,$._)`typeof ${e} ${s} ${t}`}return n===Pt.Correct?o:(0,$.not)(o);function i(c=$.nil){return(0,$.and)((0,$._)`typeof ${e} == "number"`,c,r?(0,$._)`isFinite(${e})`:$.nil)}}Q.checkDataType=Zs;function Xs(t,e,r,n){if(t.length===1)return Zs(t[0],e,r,n);let s,o=(0,Na.toHash)(t);if(o.array&&o.object){let i=(0,$._)`typeof ${e} != "object"`;s=o.null?i:(0,$._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=$.nil;o.number&&delete o.integer;for(let i in o)s=(0,$.and)(s,Zs(i,e,r,n));return s}Q.checkDataTypes=Xs;var rm={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,$._)`{type: ${t}}`:(0,$._)`{type: ${e}}`};function Qs(t){let e=nm(t);(0,Bp.reportError)(e,rm)}Q.reportTypeError=Qs;function nm(t){let{gen:e,data:r,schema:n}=t,s=(0,Na.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var qa=b(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.assignDefaults=void 0;var $t=R(),sm=x();function om(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)ja(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>ja(t,o,s.default))}yn.assignDefaults=om;function ja(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let c=(0,$t._)`${o}${(0,$t.getProperty)(e)}`;if(s){(0,sm.checkStrictMode)(t,`default is ignored for: ${c}`);return}let l=(0,$t._)`${c} === undefined`;i.useDefaults==="empty"&&(l=(0,$t._)`${l} || ${c} === null || ${c} === ""`),n.if(l,(0,$t._)`${c} = ${(0,$t.stringify)(r)}`)}});var he=b(z=>{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.validateUnion=z.validateArray=z.usePattern=z.callValidateCode=z.schemaProperties=z.allSchemaProperties=z.noPropertyInData=z.propertyInData=z.isOwnProperty=z.hasPropFunc=z.reportMissingProp=z.checkMissingProp=z.checkReportMissingProp=void 0;var j=R(),eo=x(),Xe=Fe(),im=x();function am(t,e){let{gen:r,data:n,it:s}=t;r.if(ro(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,j._)`${e}`},!0),t.error()})}z.checkReportMissingProp=am;function cm({gen:t,data:e,it:{opts:r}},n,s){return(0,j.or)(...n.map(o=>(0,j.and)(ro(t,e,o,r.ownProperties),(0,j._)`${s} = ${o}`)))}z.checkMissingProp=cm;function lm(t,e){t.setParams({missingProperty:e},!0),t.error()}z.reportMissingProp=lm;function Ua(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,j._)`Object.prototype.hasOwnProperty`})}z.hasPropFunc=Ua;function to(t,e,r){return(0,j._)`${Ua(t)}.call(${e}, ${r})`}z.isOwnProperty=to;function um(t,e,r,n){let s=(0,j._)`${e}${(0,j.getProperty)(r)} !== undefined`;return n?(0,j._)`${s} && ${to(t,e,r)}`:s}z.propertyInData=um;function ro(t,e,r,n){let s=(0,j._)`${e}${(0,j.getProperty)(r)} === undefined`;return n?(0,j.or)(s,(0,j.not)(to(t,e,r))):s}z.noPropertyInData=ro;function Fa(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}z.allSchemaProperties=Fa;function dm(t,e){return Fa(e).filter(r=>!(0,eo.alwaysValidSchema)(t,e[r]))}z.schemaProperties=dm;function fm({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:o},it:i},c,l,u){let d=u?(0,j._)`${t}, ${e}, ${n}${s}`:e,f=[[Xe.default.instancePath,(0,j.strConcat)(Xe.default.instancePath,o)],[Xe.default.parentData,i.parentData],[Xe.default.parentDataProperty,i.parentDataProperty],[Xe.default.rootData,Xe.default.rootData]];i.opts.dynamicRef&&f.push([Xe.default.dynamicAnchors,Xe.default.dynamicAnchors]);let p=(0,j._)`${d}, ${r.object(...f)}`;return l!==j.nil?(0,j._)`${c}.call(${l}, ${p})`:(0,j._)`${c}(${p})`}z.callValidateCode=fm;var pm=(0,j._)`new RegExp`;function mm({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:s}=e.code,o=s(r,n);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,j._)`${s.code==="new RegExp"?pm:(0,im.useFunc)(t,s)}(${r}, ${n})`})}z.usePattern=mm;function hm(t){let{gen:e,data:r,keyword:n,it:s}=t,o=e.name("valid");if(s.allErrors){let c=e.let("valid",!0);return i(()=>e.assign(c,!1)),c}return e.var(o,!0),i(()=>e.break()),o;function i(c){let l=e.const("len",(0,j._)`${r}.length`);e.forRange("i",0,l,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:eo.Type.Num},o),e.if((0,j.not)(o),c)})}}z.validateArray=hm;function gm(t){let{gen:e,schema:r,keyword:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,eo.alwaysValidSchema)(s,l))&&!s.opts.unevaluated)return;let i=e.let("valid",!1),c=e.name("_valid");e.block(()=>r.forEach((l,u)=>{let d=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},c);e.assign(i,(0,j._)`${i} || ${c}`),t.mergeValidEvaluated(d,c)||e.if((0,j.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}z.validateUnion=gm});var Va=b($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.validateKeywordUsage=$e.validSchemaType=$e.funcKeywordCode=$e.macroKeywordCode=void 0;var re=R(),ut=Fe(),ym=he(),_m=hr();function Sm(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,c=e.macro.call(i.self,s,o,i),l=Wa(r,n,c);i.opts.validateSchema!==!1&&i.self.validateSchema(c,!0);let u=r.name("valid");t.subschema({schema:c,schemaPath:re.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}$e.macroKeywordCode=Sm;function Em(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:c,it:l}=t;bm(l,e);let u=!c&&e.compile?e.compile.call(l.self,o,i,l):e.validate,d=Wa(n,s,u),f=n.let("valid");t.block$data(f,p),t.ok((r=e.valid)!==null&&r!==void 0?r:f);function p(){if(e.errors===!1)g(),e.modifying&&Ha(t),_(()=>t.error());else{let E=e.async?m():h();e.modifying&&Ha(t),_(()=>wm(t,E))}}function m(){let E=n.let("ruleErrs",null);return n.try(()=>g((0,re._)`await `),S=>n.assign(f,!1).if((0,re._)`${S} instanceof ${l.ValidationError}`,()=>n.assign(E,(0,re._)`${S}.errors`),()=>n.throw(S))),E}function h(){let E=(0,re._)`${d}.errors`;return n.assign(E,null),g(re.nil),E}function g(E=e.async?(0,re._)`await `:re.nil){let S=l.opts.passContext?ut.default.this:ut.default.self,w=!("compile"in e&&!c||e.schema===!1);n.assign(f,(0,re._)`${E}${(0,ym.callValidateCode)(t,d,S,w)}`,e.modifying)}function _(E){var S;n.if((0,re.not)((S=e.valid)!==null&&S!==void 0?S:f),E)}}$e.funcKeywordCode=Em;function Ha(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,re._)`${n.parentData}[${n.parentDataProperty}]`))}function wm(t,e){let{gen:r}=t;r.if((0,re._)`Array.isArray(${e})`,()=>{r.assign(ut.default.vErrors,(0,re._)`${ut.default.vErrors} === null ? ${e} : ${ut.default.vErrors}.concat(${e})`).assign(ut.default.errors,(0,re._)`${ut.default.vErrors}.length`),(0,_m.extendErrors)(t)},()=>t.error())}function bm({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Wa(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,re.stringify)(r)})}function vm(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}$e.validSchemaType=vm;function km({schema:t,opts:e,self:r,errSchemaPath:n},s,o){if(Array.isArray(s.keyword)?!s.keyword.includes(o):s.keyword!==o)throw new Error("ajv implementation error");let i=s.dependencies;if(i?.some(c=>!Object.prototype.hasOwnProperty.call(t,c)))throw new Error(`parent schema must have dependencies of ${o}: ${i.join(",")}`);if(s.validateSchema&&!s.validateSchema(t[o])){let l=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}$e.validateKeywordUsage=km});var Ka=b(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.extendSubschemaMode=Qe.extendSubschemaData=Qe.getSubschema=void 0;var Re=R(),Ga=x();function Tm(t,{keyword:e,schemaProp:r,schema:n,schemaPath:s,errSchemaPath:o,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let c=t.schema[e];return r===void 0?{schema:c,schemaPath:(0,Re._)`${t.schemaPath}${(0,Re.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:c[r],schemaPath:(0,Re._)`${t.schemaPath}${(0,Re.getProperty)(e)}${(0,Re.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Ga.escapeFragment)(r)}`}}if(n!==void 0){if(s===void 0||o===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:s,topSchemaRef:i,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}Qe.getSubschema=Tm;function Pm(t,e,{dataProp:r,dataPropType:n,data:s,dataTypes:o,propertyName:i}){if(s!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:c}=e;if(r!==void 0){let{errorPath:u,dataPathArr:d,opts:f}=e,p=c.let("data",(0,Re._)`${e.data}${(0,Re.getProperty)(r)}`,!0);l(p),t.errorPath=(0,Re.str)`${u}${(0,Ga.getErrorPath)(r,n,f.jsPropertySyntax)}`,t.parentDataProperty=(0,Re._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(s!==void 0){let u=s instanceof Re.Name?s:c.let("data",s,!0);l(u),i!==void 0&&(t.propertyName=i)}o&&(t.dataTypes=o);function l(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Qe.extendSubschemaData=Pm;function $m(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:s,allErrors:o}){n!==void 0&&(t.compositeRule=n),s!==void 0&&(t.createErrors=s),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=r}Qe.extendSubschemaMode=$m});var no=b((uv,Ya)=>{"use strict";Ya.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,s,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[s]))return!1;for(s=n;s--!==0;){var i=o[s];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var Ba=b((dv,Ja)=>{"use strict";var et=Ja.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},s=r.post||function(){};_n(e,n,s,t,"",t)};et.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};et.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};et.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};et.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function _n(t,e,r,n,s,o,i,c,l,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,o,i,c,l,u);for(var d in n){var f=n[d];if(Array.isArray(f)){if(d in et.arrayKeywords)for(var p=0;p<f.length;p++)_n(t,e,r,f[p],s+"/"+d+"/"+p,o,s,d,n,p)}else if(d in et.propsKeywords){if(f&&typeof f=="object")for(var m in f)_n(t,e,r,f[m],s+"/"+d+"/"+Rm(m),o,s,d,n,m)}else(d in et.keywords||t.allKeys&&!(d in et.skipKeywords))&&_n(t,e,r,f,s+"/"+d,o,s,d,n)}r(n,s,o,i,c,l,u)}}function Rm(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var yr=b(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.getSchemaRefs=ae.resolveUrl=ae.normalizeId=ae._getFullPath=ae.getFullPath=ae.inlineRef=void 0;var Mm=x(),Am=no(),Cm=Ba(),Om=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Im(t,e=!0){return typeof t=="boolean"?!0:e===!0?!so(t):e?Za(t)<=e:!1}ae.inlineRef=Im;var xm=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function so(t){for(let e in t){if(xm.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(so)||typeof r=="object"&&so(r))return!0}return!1}function Za(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!Om.has(r)&&(typeof t[r]=="object"&&(0,Mm.eachItem)(t[r],n=>e+=Za(n)),e===1/0))return 1/0}return e}function Xa(t,e="",r){r!==!1&&(e=Rt(e));let n=t.parse(e);return Qa(t,n)}ae.getFullPath=Xa;function Qa(t,e){return t.serialize(e).split("#")[0]+"#"}ae._getFullPath=Qa;var Dm=/#\/?$/;function Rt(t){return t?t.replace(Dm,""):""}ae.normalizeId=Rt;function Nm(t,e,r){return r=Rt(r),t.resolve(e,r)}ae.resolveUrl=Nm;var zm=/^[a-z_][-a-z0-9._]*$/i;function Lm(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=Rt(t[r]||e),o={"":s},i=Xa(n,s,!1),c={},l=new Set;return Cm(t,{allKeys:!0},(f,p,m,h)=>{if(h===void 0)return;let g=i+p,_=o[h];typeof f[r]=="string"&&(_=E.call(this,f[r])),S.call(this,f.$anchor),S.call(this,f.$dynamicAnchor),o[p]=_;function E(w){let A=this.opts.uriResolver.resolve;if(w=Rt(_?A(_,w):w),l.has(w))throw d(w);l.add(w);let k=this.refs[w];return typeof k=="string"&&(k=this.refs[k]),typeof k=="object"?u(f,k.schema,w):w!==Rt(g)&&(w[0]==="#"?(u(f,c[w],w),c[w]=f):this.refs[w]=g),w}function S(w){if(typeof w=="string"){if(!zm.test(w))throw new Error(`invalid anchor "${w}"`);E.call(this,`#${w}`)}}}),c;function u(f,p,m){if(p!==void 0&&!Am(f,p))throw d(m)}function d(f){return new Error(`reference "${f}" resolves to more than one schema`)}}ae.getSchemaRefs=Lm});var Er=b(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.getData=tt.KeywordCxt=tt.validateFunctionCode=void 0;var sc=Ia(),ec=gr(),io=Bs(),Sn=gr(),jm=qa(),Sr=Va(),oo=Ka(),v=R(),T=Fe(),qm=yr(),He=x(),_r=hr();function Um(t){if(ac(t)&&(cc(t),ic(t))){Wm(t);return}oc(t,()=>(0,sc.topBoolOrEmptySchema)(t))}tt.validateFunctionCode=Um;function oc({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},o){s.code.es5?t.func(e,(0,v._)`${T.default.data}, ${T.default.valCxt}`,n.$async,()=>{t.code((0,v._)`"use strict"; ${tc(r,s)}`),Hm(t,s),t.code(o)}):t.func(e,(0,v._)`${T.default.data}, ${Fm(s)}`,n.$async,()=>t.code(tc(r,s)).code(o))}function Fm(t){return(0,v._)`{${T.default.instancePath}="", ${T.default.parentData}, ${T.default.parentDataProperty}, ${T.default.rootData}=${T.default.data}${t.dynamicRef?(0,v._)`, ${T.default.dynamicAnchors}={}`:v.nil}}={}`}function Hm(t,e){t.if(T.default.valCxt,()=>{t.var(T.default.instancePath,(0,v._)`${T.default.valCxt}.${T.default.instancePath}`),t.var(T.default.parentData,(0,v._)`${T.default.valCxt}.${T.default.parentData}`),t.var(T.default.parentDataProperty,(0,v._)`${T.default.valCxt}.${T.default.parentDataProperty}`),t.var(T.default.rootData,(0,v._)`${T.default.valCxt}.${T.default.rootData}`),e.dynamicRef&&t.var(T.default.dynamicAnchors,(0,v._)`${T.default.valCxt}.${T.default.dynamicAnchors}`)},()=>{t.var(T.default.instancePath,(0,v._)`""`),t.var(T.default.parentData,(0,v._)`undefined`),t.var(T.default.parentDataProperty,(0,v._)`undefined`),t.var(T.default.rootData,T.default.data),e.dynamicRef&&t.var(T.default.dynamicAnchors,(0,v._)`{}`)})}function Wm(t){let{schema:e,opts:r,gen:n}=t;oc(t,()=>{r.$comment&&e.$comment&&uc(t),Jm(t),n.let(T.default.vErrors,null),n.let(T.default.errors,0),r.unevaluated&&Vm(t),lc(t),Xm(t)})}function Vm(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,v._)`${r}.evaluated`),e.if((0,v._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,v._)`${t.evaluated}.props`,(0,v._)`undefined`)),e.if((0,v._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,v._)`${t.evaluated}.items`,(0,v._)`undefined`))}function tc(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,v._)`/*# sourceURL=${r} */`:v.nil}function Gm(t,e){if(ac(t)&&(cc(t),ic(t))){Km(t,e);return}(0,sc.boolOrEmptySchema)(t,e)}function ic({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function ac(t){return typeof t.schema!="boolean"}function Km(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&uc(t),Bm(t),Zm(t);let o=n.const("_errs",T.default.errors);lc(t,o),n.var(e,(0,v._)`${o} === ${T.default.errors}`)}function cc(t){(0,He.checkUnknownRules)(t),Ym(t)}function lc(t,e){if(t.opts.jtd)return rc(t,[],!1,e);let r=(0,ec.getSchemaTypes)(t.schema),n=(0,ec.coerceAndCheckDataType)(t,r);rc(t,r,!n,e)}function Ym(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,He.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function Jm(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,He.checkStrictMode)(t,"default is ignored in the schema root")}function Bm(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,qm.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Zm(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function uc({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let o=r.$comment;if(s.$comment===!0)t.code((0,v._)`${T.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,v.str)`${n}/$comment`,c=t.scopeValue("root",{ref:e.root});t.code((0,v._)`${T.default.self}.opts.$comment(${o}, ${i}, ${c}.schema)`)}}function Xm(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=t;r.$async?e.if((0,v._)`${T.default.errors} === 0`,()=>e.return(T.default.data),()=>e.throw((0,v._)`new ${s}(${T.default.vErrors})`)):(e.assign((0,v._)`${n}.errors`,T.default.vErrors),o.unevaluated&&Qm(t),e.return((0,v._)`${T.default.errors} === 0`))}function Qm({gen:t,evaluated:e,props:r,items:n}){r instanceof v.Name&&t.assign((0,v._)`${e}.props`,r),n instanceof v.Name&&t.assign((0,v._)`${e}.items`,n)}function rc(t,e,r,n){let{gen:s,schema:o,data:i,allErrors:c,opts:l,self:u}=t,{RULES:d}=u;if(o.$ref&&(l.ignoreKeywordsWithRef||!(0,He.schemaHasRulesButRef)(o,d))){s.block(()=>fc(t,"$ref",d.all.$ref.definition));return}l.jtd||eh(t,e),s.block(()=>{for(let p of d.rules)f(p);f(d.post)});function f(p){(0,io.shouldUseGroup)(o,p)&&(p.type?(s.if((0,Sn.checkDataType)(p.type,i,l.strictNumbers)),nc(t,p),e.length===1&&e[0]===p.type&&r&&(s.else(),(0,Sn.reportTypeError)(t)),s.endIf()):nc(t,p),c||s.if((0,v._)`${T.default.errors} === ${n||0}`))}}function nc(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,jm.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,io.shouldUseRule)(n,o)&&fc(t,o.keyword,o.definition,e.type)})}function eh(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(th(t,e),t.opts.allowUnionTypes||rh(t,e),nh(t,t.dataTypes))}function th(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{dc(t.dataTypes,r)||ao(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),oh(t,e)}}function rh(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&ao(t,"use allowUnionTypes to allow union type keyword")}function nh(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,io.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>sh(e,i))&&ao(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function sh(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function dc(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function oh(t,e){let r=[];for(let n of t.dataTypes)dc(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function ao(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,He.checkStrictMode)(t,e,t.opts.strictTypes)}var En=class{constructor(e,r,n){if((0,Sr.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,He.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",pc(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Sr.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",T.default.errors))}result(e,r,n){this.failResult((0,v.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,v.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,v._)`${r} !== undefined && (${(0,v.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?_r.reportExtraError:_r.reportError)(this,this.def.error,r)}$dataError(){(0,_r.reportError)(this,this.def.$dataError||_r.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,_r.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=v.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=v.nil,r=v.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:o,def:i}=this;n.if((0,v.or)((0,v._)`${s} === undefined`,r)),e!==v.nil&&n.assign(e,!0),(o.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==v.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:o}=this;return(0,v.or)(i(),c());function i(){if(n.length){if(!(r instanceof v.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return(0,v._)`${(0,Sn.checkDataTypes)(l,r,o.opts.strictNumbers,Sn.DataType.Wrong)}`}return v.nil}function c(){if(s.validateSchema){let l=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,v._)`!${l}(${r})`}return v.nil}}subschema(e,r){let n=(0,oo.getSubschema)(this.it,e);(0,oo.extendSubschemaData)(n,this.it,e),(0,oo.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return Gm(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=He.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=He.mergeEvaluated.items(s,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:s}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return s.if(r,()=>this.mergeEvaluated(e,v.Name)),!0}};tt.KeywordCxt=En;function fc(t,e,r,n){let s=new En(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,Sr.funcKeywordCode)(s,r):"macro"in r?(0,Sr.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,Sr.funcKeywordCode)(s,r)}var ih=/^\/(?:[^~]|~0|~1)*$/,ah=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function pc(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return T.default.rootData;if(t[0]==="/"){if(!ih.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=T.default.rootData}else{let u=ah.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let d=+u[1];if(s=u[2],s==="#"){if(d>=e)throw new Error(l("property/index",d));return n[e-d]}if(d>e)throw new Error(l("data",d));if(o=r[e-d],!s)return o}let i=o,c=s.split("/");for(let u of c)u&&(o=(0,v._)`${o}${(0,v.getProperty)((0,He.unescapeJsonPointer)(u))}`,i=(0,v._)`${i} && ${o}`);return i;function l(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}tt.getData=pc});var wn=b(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});var co=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};lo.default=co});var wr=b(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});var uo=yr(),fo=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,uo.resolveUrl)(e,r,n),this.missingSchema=(0,uo.normalizeId)((0,uo.getFullPath)(e,this.missingRef))}};po.default=fo});var vn=b(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.resolveSchema=ge.getCompilingSchema=ge.resolveRef=ge.compileSchema=ge.SchemaEnv=void 0;var be=R(),ch=wn(),dt=Fe(),ve=yr(),mc=x(),lh=Er(),Mt=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,ve.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};ge.SchemaEnv=Mt;function ho(t){let e=hc.call(this,t);if(e)return e;let r=(0,ve.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new be.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),c;t.$async&&(c=i.scopeValue("Error",{ref:ch.default,code:(0,be._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");t.validateName=l;let u={gen:i,allErrors:this.opts.allErrors,data:dt.default.data,parentData:dt.default.parentData,parentDataProperty:dt.default.parentDataProperty,dataNames:[dt.default.data],dataPathArr:[be.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,be.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:c,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:be.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,be._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,lh.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let f=i.toString();d=`${i.scopeRefs(dt.default.scope)}return ${f}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let m=new Function(`${dt.default.self}`,`${dt.default.scope}`,d)(this,this.scope.get());if(this.scope.value(l,{ref:m}),m.errors=null,m.schema=t.schema,m.schemaEnv=t,t.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:l,validateCode:f,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:g}=u;m.evaluated={props:h instanceof be.Name?void 0:h,items:g instanceof be.Name?void 0:g,dynamicProps:h instanceof be.Name,dynamicItems:g instanceof be.Name},m.source&&(m.source.evaluated=(0,be.stringify)(m.evaluated))}return t.validate=m,t}catch(f){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),f}finally{this._compilations.delete(t)}}ge.compileSchema=ho;function uh(t,e,r){var n;r=(0,ve.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let o=ph.call(this,t,r);if(o===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:c}=this.opts;i&&(o=new Mt({schema:i,schemaId:c,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=dh.call(this,o)}ge.resolveRef=uh;function dh(t){return(0,ve.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:ho.call(this,t)}function hc(t){for(let e of this._compilations)if(fh(e,t))return e}ge.getCompilingSchema=hc;function fh(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function ph(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||bn.call(this,t,e)}function bn(t,e){let r=this.opts.uriResolver.parse(e),n=(0,ve._getFullPath)(this.opts.uriResolver,r),s=(0,ve.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return mo.call(this,r,t);let o=(0,ve.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let c=bn.call(this,t,i);return typeof c?.schema!="object"?void 0:mo.call(this,r,c)}if(typeof i?.schema=="object"){if(i.validate||ho.call(this,i),o===(0,ve.normalizeId)(e)){let{schema:c}=i,{schemaId:l}=this.opts,u=c[l];return u&&(s=(0,ve.resolveUrl)(this.opts.uriResolver,s,u)),new Mt({schema:c,schemaId:l,root:t,baseId:s})}return mo.call(this,r,i)}}ge.resolveSchema=bn;var mh=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function mo(t,{baseId:e,schema:r,root:n}){var s;if(((s=t.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(let c of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let l=r[(0,mc.unescapeFragment)(c)];if(l===void 0)return;r=l;let u=typeof r=="object"&&r[this.opts.schemaId];!mh.has(c)&&u&&(e=(0,ve.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,mc.schemaHasRulesButRef)(r,this.RULES)){let c=(0,ve.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=bn.call(this,n,c)}let{schemaId:i}=this.opts;if(o=o||new Mt({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var gc=b((yv,hh)=>{hh.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var yo=b((_v,Ec)=>{"use strict";var gh=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),_c=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 go(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var yh=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function yc(t){return t.length=0,!0}function _h(t,e,r){if(t.length){let n=go(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function Sh(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],o=!1,i=!1,c=_h;for(let l=0;l<t.length;l++){let u=t[l];if(!(u==="["||u==="]"))if(u===":"){if(o===!0&&(i=!0),!c(s,n,r))break;if(++e>7){r.error=!0;break}l>0&&t[l-1]===":"&&(o=!0),n.push(":");continue}else if(u==="%"){if(!c(s,n,r))break;c=yc}else{s.push(u);continue}}return s.length&&(c===yc?r.zone=s.join(""):i?n.push(s.join("")):n.push(go(s))),r.address=n.join(""),r}function Sc(t){if(Eh(t,":")<2)return{host:t,isIPV6:!1};let e=Sh(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function Eh(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function wh(t){let e=t,r=[],n=-1,s=0;for(;s=e.length;){if(s===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(s===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(s===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function bh(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function vh(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!_c(r)){let n=Sc(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}Ec.exports={nonSimpleDomain:yh,recomposeAuthority:vh,normalizeComponentEncoding:bh,removeDotSegments:wh,isIPv4:_c,isUUID:gh,normalizeIPv6:Sc,stringArrayToHexStripped:go}});var Tc=b((Sv,kc)=>{"use strict";var{isUUID:kh}=yo(),Th=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Ph=["http","https","ws","wss","urn","urn:uuid"];function $h(t){return Ph.indexOf(t)!==-1}function _o(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function wc(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function bc(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function Rh(t){return t.secure=_o(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function Mh(t){if((t.port===(_o(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function Ah(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(Th);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let s=`${n}:${e.nid||t.nid}`,o=So(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function Ch(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),s=`${r}:${e.nid||n}`,o=So(s);o&&(t=o.serialize(t,e));let i=t,c=t.nss;return i.path=`${n||e.nid}:${c}`,e.skipEscape=!0,i}function Oh(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!kh(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Ih(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var vc={scheme:"http",domainHost:!0,parse:wc,serialize:bc},xh={scheme:"https",domainHost:vc.domainHost,parse:wc,serialize:bc},kn={scheme:"ws",domainHost:!0,parse:Rh,serialize:Mh},Dh={scheme:"wss",domainHost:kn.domainHost,parse:kn.parse,serialize:kn.serialize},Nh={scheme:"urn",parse:Ah,serialize:Ch,skipNormalize:!0},zh={scheme:"urn:uuid",parse:Oh,serialize:Ih,skipNormalize:!0},Tn={http:vc,https:xh,ws:kn,wss:Dh,urn:Nh,"urn:uuid":zh};Object.setPrototypeOf(Tn,null);function So(t){return t&&(Tn[t]||Tn[t.toLowerCase()])||void 0}kc.exports={wsIsSecure:_o,SCHEMES:Tn,isValidSchemeName:$h,getSchemeHandler:So}});var Rc=b((Ev,$n)=>{"use strict";var{normalizeIPv6:Lh,removeDotSegments:br,recomposeAuthority:jh,normalizeComponentEncoding:Pn,isIPv4:qh,nonSimpleDomain:Uh}=yo(),{SCHEMES:Fh,getSchemeHandler:Pc}=Tc();function Hh(t,e){return typeof t=="string"?t=Me(We(t,e),e):typeof t=="object"&&(t=We(Me(t,e),e)),t}function Wh(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},s=$c(We(t,n),We(e,n),n,!0);return n.skipEscape=!0,Me(s,n)}function $c(t,e,r,n){let s={};return n||(t=We(Me(t,r),r),e=We(Me(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(s.scheme=e.scheme,s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=br(e.path||""),s.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=br(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=br(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?s.path="/"+e.path:t.path?s.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:s.path=e.path,s.path=br(s.path)),s.query=e.query):(s.path=t.path,e.query!==void 0?s.query=e.query:s.query=t.query),s.userinfo=t.userinfo,s.host=t.host,s.port=t.port),s.scheme=t.scheme),s.fragment=e.fragment,s}function Vh(t,e,r){return typeof t=="string"?(t=unescape(t),t=Me(Pn(We(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Me(Pn(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Me(Pn(We(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Me(Pn(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Me(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),s=[],o=Pc(n.scheme||r.scheme);o&&o.serialize&&o.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&s.push(r.scheme,":");let i=jh(r);if(i!==void 0&&(n.reference!=="suffix"&&s.push("//"),s.push(i),r.path&&r.path[0]!=="/"&&s.push("/")),r.path!==void 0){let c=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(c=br(c)),i===void 0&&c[0]==="/"&&c[1]==="/"&&(c="/%2F"+c.slice(2)),s.push(c)}return r.query!==void 0&&s.push("?",r.query),r.fragment!==void 0&&s.push("#",r.fragment),s.join("")}var Gh=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function We(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let o=t.match(Gh);if(o){if(n.scheme=o[1],n.userinfo=o[3],n.host=o[4],n.port=parseInt(o[5],10),n.path=o[6]||"",n.query=o[7],n.fragment=o[8],isNaN(n.port)&&(n.port=o[5]),n.host)if(qh(n.host)===!1){let l=Lh(n.host);n.host=l.host.toLowerCase(),s=l.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=Pc(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&s===!1&&Uh(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(c){n.error=n.error||"Host's domain name can not be converted to ASCII: "+c}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var Eo={SCHEMES:Fh,normalize:Hh,resolve:Wh,resolveComponent:$c,equal:Vh,serialize:Me,parse:We};$n.exports=Eo;$n.exports.default=Eo;$n.exports.fastUri=Eo});var Ac=b(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});var Mc=Rc();Mc.code='require("ajv/dist/runtime/uri").default';wo.default=Mc});var Lc=b(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.CodeGen=Y.Name=Y.nil=Y.stringify=Y.str=Y._=Y.KeywordCxt=void 0;var Kh=Er();Object.defineProperty(Y,"KeywordCxt",{enumerable:!0,get:function(){return Kh.KeywordCxt}});var At=R();Object.defineProperty(Y,"_",{enumerable:!0,get:function(){return At._}});Object.defineProperty(Y,"str",{enumerable:!0,get:function(){return At.str}});Object.defineProperty(Y,"stringify",{enumerable:!0,get:function(){return At.stringify}});Object.defineProperty(Y,"nil",{enumerable:!0,get:function(){return At.nil}});Object.defineProperty(Y,"Name",{enumerable:!0,get:function(){return At.Name}});Object.defineProperty(Y,"CodeGen",{enumerable:!0,get:function(){return At.CodeGen}});var Yh=wn(),Dc=wr(),Jh=Js(),vr=vn(),Bh=R(),kr=yr(),Rn=gr(),vo=x(),Cc=gc(),Zh=Ac(),Nc=(t,e)=>new RegExp(t,e);Nc.code="new RegExp";var Xh=["removeAdditional","useDefaults","coerceTypes"],Qh=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),eg={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."},tg={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Oc=200;function rg(t){var e,r,n,s,o,i,c,l,u,d,f,p,m,h,g,_,E,S,w,A,k,le,de,Gt,gt;let H=t.strict,Ge=(e=t.code)===null||e===void 0?void 0:e.optimize,Ee=Ge===!0||Ge===void 0?1:Ge||0,Kt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Nc,ad=(s=t.uriResolver)!==null&&s!==void 0?s:Zh.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:H)!==null&&i!==void 0?i:!0,strictNumbers:(l=(c=t.strictNumbers)!==null&&c!==void 0?c:H)!==null&&l!==void 0?l:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:H)!==null&&d!==void 0?d:"log",strictTuples:(p=(f=t.strictTuples)!==null&&f!==void 0?f:H)!==null&&p!==void 0?p:"log",strictRequired:(h=(m=t.strictRequired)!==null&&m!==void 0?m:H)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:Ee,regExp:Kt}:{optimize:Ee,regExp:Kt},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:Oc,loopEnum:(_=t.loopEnum)!==null&&_!==void 0?_:Oc,meta:(E=t.meta)!==null&&E!==void 0?E:!0,messages:(S=t.messages)!==null&&S!==void 0?S:!0,inlineRefs:(w=t.inlineRefs)!==null&&w!==void 0?w:!0,schemaId:(A=t.schemaId)!==null&&A!==void 0?A:"$id",addUsedSchema:(k=t.addUsedSchema)!==null&&k!==void 0?k:!0,validateSchema:(le=t.validateSchema)!==null&&le!==void 0?le:!0,validateFormats:(de=t.validateFormats)!==null&&de!==void 0?de:!0,unicodeRegExp:(Gt=t.unicodeRegExp)!==null&&Gt!==void 0?Gt:!0,int32range:(gt=t.int32range)!==null&>!==void 0?gt:!0,uriResolver:ad}}var Tr=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...rg(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new Bh.ValueScope({scope:{},prefixes:Qh,es5:r,lines:n}),this.logger=cg(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Jh.getRules)(),Ic.call(this,eg,e,"NOT SUPPORTED"),Ic.call(this,tg,e,"DEPRECATED","warn"),this._metaOpts=ig.call(this),e.formats&&sg.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&og.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),ng.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=Cc;n==="id"&&(s={...Cc},s.id=s.$id,delete s.$id),r&&e&&this.addMetaSchema(s,s[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let s=n(r);return"$async"in n||(this.errors=n.errors),s}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return s.call(this,e,r);async function s(d,f){await o.call(this,d.$schema);let p=this._addSchema(d,f);return p.validate||i.call(this,p)}async function o(d){d&&!this.getSchema(d)&&await s.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(f){if(!(f instanceof Dc.default))throw f;return c.call(this,f),await l.call(this,f.missingSchema),i.call(this,d)}}function c({missingSchema:d,missingRef:f}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${f} cannot be resolved`)}async function l(d){let f=await u.call(this,d);this.refs[d]||await o.call(this,f.$schema),this.refs[d]||this.addSchema(f,d,r)}async function u(d){let f=this._loading[d];if(f)return f;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(e,r,n,s=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,s);return this}let o;if(typeof e=="object"){let{schemaId:i}=this.opts;if(o=e[i],o!==void 0&&typeof o!="string")throw new Error(`schema ${i} must be string`)}return r=(0,kr.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,s,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let s=this.validate(n,e);if(!s&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return s}getSchema(e){let r;for(;typeof(r=xc.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new vr.SchemaEnv({schema:{},schemaId:n});if(r=vr.resolveSchema.call(this,s,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=xc.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,kr.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(ug.call(this,n,r),!r)return(0,vo.eachItem)(n,o=>bo.call(this,o)),this;fg.call(this,r);let s={...r,type:(0,Rn.getJSONTypes)(r.type),schemaType:(0,Rn.getJSONTypes)(r.schemaType)};return(0,vo.eachItem)(n,s.type.length===0?o=>bo.call(this,o,s):o=>s.type.forEach(i=>bo.call(this,o,s,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let s=n.rules.findIndex(o=>o.keyword===e);s>=0&&n.rules.splice(s,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(s=>`${n}${s.instancePath} ${s.message}`).reduce((s,o)=>s+r+o)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of r){let o=s.split("/").slice(1),i=e;for(let c of o)i=i[c];for(let c in n){let l=n[c];if(typeof l!="object")continue;let{$data:u}=l.definition,d=i[c];u&&d&&(i[c]=zc(d))}}return e}_removeAllSchemas(e,r){for(let n in e){let s=e[n];(!r||r.test(n))&&(typeof s=="string"?delete e[n]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[n]))}}_addSchema(e,r,n,s=this.opts.validateSchema,o=this.opts.addUsedSchema){let i,{schemaId:c}=this.opts;if(typeof e=="object")i=e[c];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let l=this._cache.get(e);if(l!==void 0)return l;n=(0,kr.normalizeId)(i||n);let u=kr.getSchemaRefs.call(this,e,n);return l=new vr.SchemaEnv({schema:e,schemaId:c,meta:r,baseId:n,localRefs:u}),this._cache.set(l.schema,l),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=l),s&&this.validateSchema(e,!0),l}_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):vr.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{vr.compileSchema.call(this,e)}finally{this.opts=r}}};Tr.ValidationError=Yh.default;Tr.MissingRefError=Dc.default;Y.default=Tr;function Ic(t,e,r,n="error"){for(let s in t){let o=s;o in e&&this.logger[n](`${r}: option ${s}. ${t[o]}`)}}function xc(t){return t=(0,kr.normalizeId)(t),this.schemas[t]||this.refs[t]}function ng(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function sg(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function og(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function ig(){let t={...this.opts};for(let e of Xh)delete t[e];return t}var ag={log(){},warn(){},error(){}};function cg(t){if(t===!1)return ag;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var lg=/^[a-z_$][a-z0-9_$:-]*$/i;function ug(t,e){let{RULES:r}=this;if((0,vo.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!lg.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function bo(t,e,r){var n;let s=e?.post;if(r&&s)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,i=s?o.post:o.rules.find(({type:l})=>l===r);if(i||(i={type:r,rules:[]},o.rules.push(i)),o.keywords[t]=!0,!e)return;let c={keyword:t,definition:{...e,type:(0,Rn.getJSONTypes)(e.type),schemaType:(0,Rn.getJSONTypes)(e.schemaType)}};e.before?dg.call(this,i,c,e.before):i.rules.push(c),o.all[t]=c,(n=e.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l))}function dg(t,e,r){let n=t.rules.findIndex(s=>s.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function fg(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=zc(e)),t.validateSchema=this.compile(e,!0))}var pg={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function zc(t){return{anyOf:[t,pg]}}});var jc=b(ko=>{"use strict";Object.defineProperty(ko,"__esModule",{value:!0});var mg={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ko.default=mg});var Hc=b(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.callRef=ft.getValidate=void 0;var hg=wr(),qc=he(),ce=R(),Ct=Fe(),Uc=vn(),Mn=x(),gg={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:s,schemaEnv:o,validateName:i,opts:c,self:l}=n,{root:u}=o;if((r==="#"||r==="#/")&&s===u.baseId)return f();let d=Uc.resolveRef.call(l,u,s,r);if(d===void 0)throw new hg.default(n.opts.uriResolver,s,r);if(d instanceof Uc.SchemaEnv)return p(d);return m(d);function f(){if(o===u)return An(t,i,o,o.$async);let h=e.scopeValue("root",{ref:u});return An(t,(0,ce._)`${h}.validate`,u,u.$async)}function p(h){let g=Fc(t,h);An(t,g,h,h.$async)}function m(h){let g=e.scopeValue("schema",c.code.source===!0?{ref:h,code:(0,ce.stringify)(h)}:{ref:h}),_=e.name("valid"),E=t.subschema({schema:h,dataTypes:[],schemaPath:ce.nil,topSchemaRef:g,errSchemaPath:r},_);t.mergeEvaluated(E),t.ok(_)}}};function Fc(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,ce._)`${r.scopeValue("wrapper",{ref:e})}.validate`}ft.getValidate=Fc;function An(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:c,opts:l}=o,u=l.passContext?Ct.default.this:ce.nil;n?d():f();function d(){if(!c.$async)throw new Error("async schema referenced by sync schema");let h=s.let("valid");s.try(()=>{s.code((0,ce._)`await ${(0,qc.callValidateCode)(t,e,u)}`),m(e),i||s.assign(h,!0)},g=>{s.if((0,ce._)`!(${g} instanceof ${o.ValidationError})`,()=>s.throw(g)),p(g),i||s.assign(h,!1)}),t.ok(h)}function f(){t.result((0,qc.callValidateCode)(t,e,u),()=>m(e),()=>p(e))}function p(h){let g=(0,ce._)`${h}.errors`;s.assign(Ct.default.vErrors,(0,ce._)`${Ct.default.vErrors} === null ? ${g} : ${Ct.default.vErrors}.concat(${g})`),s.assign(Ct.default.errors,(0,ce._)`${Ct.default.vErrors}.length`)}function m(h){var g;if(!o.opts.unevaluated)return;let _=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(o.props!==!0)if(_&&!_.dynamicProps)_.props!==void 0&&(o.props=Mn.mergeEvaluated.props(s,_.props,o.props));else{let E=s.var("props",(0,ce._)`${h}.evaluated.props`);o.props=Mn.mergeEvaluated.props(s,E,o.props,ce.Name)}if(o.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(o.items=Mn.mergeEvaluated.items(s,_.items,o.items));else{let E=s.var("items",(0,ce._)`${h}.evaluated.items`);o.items=Mn.mergeEvaluated.items(s,E,o.items,ce.Name)}}}ft.callRef=An;ft.default=gg});var Wc=b(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});var yg=jc(),_g=Hc(),Sg=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",yg.default,_g.default];To.default=Sg});var Vc=b(Po=>{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});var Cn=R(),rt=Cn.operators,On={maximum:{okStr:"<=",ok:rt.LTE,fail:rt.GT},minimum:{okStr:">=",ok:rt.GTE,fail:rt.LT},exclusiveMaximum:{okStr:"<",ok:rt.LT,fail:rt.GTE},exclusiveMinimum:{okStr:">",ok:rt.GT,fail:rt.LTE}},Eg={message:({keyword:t,schemaCode:e})=>(0,Cn.str)`must be ${On[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Cn._)`{comparison: ${On[t].okStr}, limit: ${e}}`},wg={keyword:Object.keys(On),type:"number",schemaType:"number",$data:!0,error:Eg,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Cn._)`${r} ${On[e].fail} ${n} || isNaN(${r})`)}};Po.default=wg});var Gc=b($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});var Pr=R(),bg={message:({schemaCode:t})=>(0,Pr.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Pr._)`{multipleOf: ${t}}`},vg={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:bg,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),c=o?(0,Pr._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,Pr._)`${i} !== parseInt(${i})`;t.fail$data((0,Pr._)`(${n} === 0 || (${i} = ${r}/${n}, ${c}))`)}};$o.default=vg});var Yc=b(Ro=>{"use strict";Object.defineProperty(Ro,"__esModule",{value:!0});function Kc(t){let e=t.length,r=0,n=0,s;for(;n<e;)r++,s=t.charCodeAt(n++),s>=55296&&s<=56319&&n<e&&(s=t.charCodeAt(n),(s&64512)===56320&&n++);return r}Ro.default=Kc;Kc.code='require("ajv/dist/runtime/ucs2length").default'});var Jc=b(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});var pt=R(),kg=x(),Tg=Yc(),Pg={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,pt.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,pt._)`{limit: ${t}}`},$g={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Pg,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?pt.operators.GT:pt.operators.LT,i=s.opts.unicode===!1?(0,pt._)`${r}.length`:(0,pt._)`${(0,kg.useFunc)(t.gen,Tg.default)}(${r})`;t.fail$data((0,pt._)`${i} ${o} ${n}`)}};Mo.default=$g});var Bc=b(Ao=>{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});var Rg=he(),Mg=x(),Ot=R(),Ag={message:({schemaCode:t})=>(0,Ot.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Ot._)`{pattern: ${t}}`},Cg={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Ag,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t,c=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:l}=i.opts.code,u=l.code==="new RegExp"?(0,Ot._)`new RegExp`:(0,Mg.useFunc)(e,l),d=e.let("valid");e.try(()=>e.assign(d,(0,Ot._)`${u}(${o}, ${c}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,Ot._)`!${d}`)}else{let l=(0,Rg.usePattern)(t,s);t.fail$data((0,Ot._)`!${l}.test(${r})`)}}};Ao.default=Cg});var Zc=b(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});var $r=R(),Og={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,$r.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,$r._)`{limit: ${t}}`},Ig={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Og,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?$r.operators.GT:$r.operators.LT;t.fail$data((0,$r._)`Object.keys(${r}).length ${s} ${n}`)}};Co.default=Ig});var Xc=b(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});var Rr=he(),Mr=R(),xg=x(),Dg={message:({params:{missingProperty:t}})=>(0,Mr.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Mr._)`{missingProperty: ${t}}`},Ng={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Dg,code(t){let{gen:e,schema:r,schemaCode:n,data:s,$data:o,it:i}=t,{opts:c}=i;if(!o&&r.length===0)return;let l=r.length>=c.loopRequired;if(i.allErrors?u():d(),c.strictRequired){let m=t.parentSchema.properties,{definedProperties:h}=t.it;for(let g of r)if(m?.[g]===void 0&&!h.has(g)){let _=i.schemaEnv.baseId+i.errSchemaPath,E=`required property "${g}" is not defined at "${_}" (strictRequired)`;(0,xg.checkStrictMode)(i,E,i.opts.strictRequired)}}function u(){if(l||o)t.block$data(Mr.nil,f);else for(let m of r)(0,Rr.checkReportMissingProp)(t,m)}function d(){let m=e.let("missing");if(l||o){let h=e.let("valid",!0);t.block$data(h,()=>p(m,h)),t.ok(h)}else e.if((0,Rr.checkMissingProp)(t,r,m)),(0,Rr.reportMissingProp)(t,m),e.else()}function f(){e.forOf("prop",n,m=>{t.setParams({missingProperty:m}),e.if((0,Rr.noPropertyInData)(e,s,m,c.ownProperties),()=>t.error())})}function p(m,h){t.setParams({missingProperty:m}),e.forOf(m,n,()=>{e.assign(h,(0,Rr.propertyInData)(e,s,m,c.ownProperties)),e.if((0,Mr.not)(h),()=>{t.error(),e.break()})},Mr.nil)}}};Oo.default=Ng});var Qc=b(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0});var Ar=R(),zg={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ar.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ar._)`{limit: ${t}}`},Lg={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:zg,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?Ar.operators.GT:Ar.operators.LT;t.fail$data((0,Ar._)`${r}.length ${s} ${n}`)}};Io.default=Lg});var In=b(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});var el=no();el.code='require("ajv/dist/runtime/equal").default';xo.default=el});var tl=b(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});var Do=gr(),J=R(),jg=x(),qg=In(),Ug={message:({params:{i:t,j:e}})=>(0,J.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,J._)`{i: ${t}, j: ${e}}`},Fg={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Ug,code(t){let{gen:e,data:r,$data:n,schema:s,parentSchema:o,schemaCode:i,it:c}=t;if(!n&&!s)return;let l=e.let("valid"),u=o.items?(0,Do.getSchemaTypes)(o.items):[];t.block$data(l,d,(0,J._)`${i} === false`),t.ok(l);function d(){let h=e.let("i",(0,J._)`${r}.length`),g=e.let("j");t.setParams({i:h,j:g}),e.assign(l,!0),e.if((0,J._)`${h} > 1`,()=>(f()?p:m)(h,g))}function f(){return u.length>0&&!u.some(h=>h==="object"||h==="array")}function p(h,g){let _=e.name("item"),E=(0,Do.checkDataTypes)(u,_,c.opts.strictNumbers,Do.DataType.Wrong),S=e.const("indices",(0,J._)`{}`);e.for((0,J._)`;${h}--;`,()=>{e.let(_,(0,J._)`${r}[${h}]`),e.if(E,(0,J._)`continue`),u.length>1&&e.if((0,J._)`typeof ${_} == "string"`,(0,J._)`${_} += "_"`),e.if((0,J._)`typeof ${S}[${_}] == "number"`,()=>{e.assign(g,(0,J._)`${S}[${_}]`),t.error(),e.assign(l,!1).break()}).code((0,J._)`${S}[${_}] = ${h}`)})}function m(h,g){let _=(0,jg.useFunc)(e,qg.default),E=e.name("outer");e.label(E).for((0,J._)`;${h}--;`,()=>e.for((0,J._)`${g} = ${h}; ${g}--;`,()=>e.if((0,J._)`${_}(${r}[${h}], ${r}[${g}])`,()=>{t.error(),e.assign(l,!1).break(E)})))}}};No.default=Fg});var rl=b(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});var zo=R(),Hg=x(),Wg=In(),Vg={message:"must be equal to constant",params:({schemaCode:t})=>(0,zo._)`{allowedValue: ${t}}`},Gg={keyword:"const",$data:!0,error:Vg,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,zo._)`!${(0,Hg.useFunc)(e,Wg.default)}(${r}, ${s})`):t.fail((0,zo._)`${o} !== ${r}`)}};Lo.default=Gg});var nl=b(jo=>{"use strict";Object.defineProperty(jo,"__esModule",{value:!0});var Cr=R(),Kg=x(),Yg=In(),Jg={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Cr._)`{allowedValues: ${t}}`},Bg={keyword:"enum",schemaType:"array",$data:!0,error:Jg,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t;if(!n&&s.length===0)throw new Error("enum must have non-empty array");let c=s.length>=i.opts.loopEnum,l,u=()=>l??(l=(0,Kg.useFunc)(e,Yg.default)),d;if(c||n)d=e.let("valid"),t.block$data(d,f);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let m=e.const("vSchema",o);d=(0,Cr.or)(...s.map((h,g)=>p(m,g)))}t.pass(d);function f(){e.assign(d,!1),e.forOf("v",o,m=>e.if((0,Cr._)`${u()}(${r}, ${m})`,()=>e.assign(d,!0).break()))}function p(m,h){let g=s[h];return typeof g=="object"&&g!==null?(0,Cr._)`${u()}(${r}, ${m}[${h}])`:(0,Cr._)`${r} === ${g}`}}};jo.default=Bg});var sl=b(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});var Zg=Vc(),Xg=Gc(),Qg=Jc(),ey=Bc(),ty=Zc(),ry=Xc(),ny=Qc(),sy=tl(),oy=rl(),iy=nl(),ay=[Zg.default,Xg.default,Qg.default,ey.default,ty.default,ry.default,ny.default,sy.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},oy.default,iy.default];qo.default=ay});var Fo=b(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.validateAdditionalItems=void 0;var mt=R(),Uo=x(),cy={message:({params:{len:t}})=>(0,mt.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,mt._)`{limit: ${t}}`},ly={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:cy,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Uo.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}ol(t,n)}};function ol(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let c=r.const("len",(0,mt._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,mt._)`${c} <= ${e.length}`);else if(typeof n=="object"&&!(0,Uo.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,mt._)`${c} <= ${e.length}`);r.if((0,mt.not)(u),()=>l(u)),t.ok(u)}function l(u){r.forRange("i",e.length,c,d=>{t.subschema({keyword:o,dataProp:d,dataPropType:Uo.Type.Num},u),i.allErrors||r.if((0,mt.not)(u),()=>r.break())})}}Or.validateAdditionalItems=ol;Or.default=ly});var Ho=b(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.validateTuple=void 0;var il=R(),xn=x(),uy=he(),dy={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return al(t,"additionalItems",e);r.items=!0,!(0,xn.alwaysValidSchema)(r,e)&&t.ok((0,uy.validateArray)(t))}};function al(t,e,r=t.schema){let{gen:n,parentSchema:s,data:o,keyword:i,it:c}=t;d(s),c.opts.unevaluated&&r.length&&c.items!==!0&&(c.items=xn.mergeEvaluated.items(n,r.length,c.items));let l=n.name("valid"),u=n.const("len",(0,il._)`${o}.length`);r.forEach((f,p)=>{(0,xn.alwaysValidSchema)(c,f)||(n.if((0,il._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},l)),t.ok(l))});function d(f){let{opts:p,errSchemaPath:m}=c,h=r.length,g=h===f.minItems&&(h===f.maxItems||f[e]===!1);if(p.strictTuples&&!g){let _=`"${i}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${m}"`;(0,xn.checkStrictMode)(c,_,p.strictTuples)}}}Ir.validateTuple=al;Ir.default=dy});var cl=b(Wo=>{"use strict";Object.defineProperty(Wo,"__esModule",{value:!0});var fy=Ho(),py={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,fy.validateTuple)(t,"items")};Wo.default=py});var ul=b(Vo=>{"use strict";Object.defineProperty(Vo,"__esModule",{value:!0});var ll=R(),my=x(),hy=he(),gy=Fo(),yy={message:({params:{len:t}})=>(0,ll.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,ll._)`{limit: ${t}}`},_y={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:yy,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,my.alwaysValidSchema)(n,e)&&(s?(0,gy.validateAdditionalItems)(t,s):t.ok((0,hy.validateArray)(t)))}};Vo.default=_y});var dl=b(Go=>{"use strict";Object.defineProperty(Go,"__esModule",{value:!0});var ye=R(),Dn=x(),Sy={message:({params:{min:t,max:e}})=>e===void 0?(0,ye.str)`must contain at least ${t} valid item(s)`:(0,ye.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,ye._)`{minContains: ${t}}`:(0,ye._)`{minContains: ${t}, maxContains: ${e}}`},Ey={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Sy,code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t,i,c,{minContains:l,maxContains:u}=n;o.opts.next?(i=l===void 0?1:l,c=u):i=1;let d=e.const("len",(0,ye._)`${s}.length`);if(t.setParams({min:i,max:c}),c===void 0&&i===0){(0,Dn.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(c!==void 0&&i>c){(0,Dn.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Dn.alwaysValidSchema)(o,r)){let g=(0,ye._)`${d} >= ${i}`;c!==void 0&&(g=(0,ye._)`${g} && ${d} <= ${c}`),t.pass(g);return}o.items=!0;let f=e.name("valid");c===void 0&&i===1?m(f,()=>e.if(f,()=>e.break())):i===0?(e.let(f,!0),c!==void 0&&e.if((0,ye._)`${s}.length > 0`,p)):(e.let(f,!1),p()),t.result(f,()=>t.reset());function p(){let g=e.name("_valid"),_=e.let("count",0);m(g,()=>e.if(g,()=>h(_)))}function m(g,_){e.forRange("i",0,d,E=>{t.subschema({keyword:"contains",dataProp:E,dataPropType:Dn.Type.Num,compositeRule:!0},g),_()})}function h(g){e.code((0,ye._)`${g}++`),c===void 0?e.if((0,ye._)`${g} >= ${i}`,()=>e.assign(f,!0).break()):(e.if((0,ye._)`${g} > ${c}`,()=>e.assign(f,!1).break()),i===1?e.assign(f,!0):e.if((0,ye._)`${g} >= ${i}`,()=>e.assign(f,!0)))}}};Go.default=Ey});var ml=b(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.validateSchemaDeps=Ae.validatePropertyDeps=Ae.error=void 0;var Ko=R(),wy=x(),xr=he();Ae.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Ko.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Ko._)`{property: ${t},
|
|
missingProperty: ${n},
|
|
depsCount: ${e},
|
|
deps: ${r}}`};var by={keyword:"dependencies",type:"object",schemaType:"object",error:Ae.error,code(t){let[e,r]=vy(t);fl(t,e),pl(t,r)}};function vy({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let s=Array.isArray(t[n])?e:r;s[n]=t[n]}return[e,r]}function fl(t,e=t.schema){let{gen:r,data:n,it:s}=t;if(Object.keys(e).length===0)return;let o=r.let("missing");for(let i in e){let c=e[i];if(c.length===0)continue;let l=(0,xr.propertyInData)(r,n,i,s.opts.ownProperties);t.setParams({property:i,depsCount:c.length,deps:c.join(", ")}),s.allErrors?r.if(l,()=>{for(let u of c)(0,xr.checkReportMissingProp)(t,u)}):(r.if((0,Ko._)`${l} && (${(0,xr.checkMissingProp)(t,c,o)})`),(0,xr.reportMissingProp)(t,o),r.else())}}Ae.validatePropertyDeps=fl;function pl(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let c in e)(0,wy.alwaysValidSchema)(o,e[c])||(r.if((0,xr.propertyInData)(r,n,c,o.opts.ownProperties),()=>{let l=t.subschema({keyword:s,schemaProp:c},i);t.mergeValidEvaluated(l,i)},()=>r.var(i,!0)),t.ok(i))}Ae.validateSchemaDeps=pl;Ae.default=by});var gl=b(Yo=>{"use strict";Object.defineProperty(Yo,"__esModule",{value:!0});var hl=R(),ky=x(),Ty={message:"property name must be valid",params:({params:t})=>(0,hl._)`{propertyName: ${t.propertyName}}`},Py={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Ty,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,ky.alwaysValidSchema)(s,r))return;let o=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},o),e.if((0,hl.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};Yo.default=Py});var Bo=b(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});var Nn=he(),ke=R(),$y=Fe(),zn=x(),Ry={message:"must NOT have additional properties",params:({params:t})=>(0,ke._)`{additionalProperty: ${t.additionalProperty}}`},My={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Ry,code(t){let{gen:e,schema:r,parentSchema:n,data:s,errsCount:o,it:i}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:c,opts:l}=i;if(i.props=!0,l.removeAdditional!=="all"&&(0,zn.alwaysValidSchema)(i,r))return;let u=(0,Nn.allSchemaProperties)(n.properties),d=(0,Nn.allSchemaProperties)(n.patternProperties);f(),t.ok((0,ke._)`${o} === ${$y.default.errors}`);function f(){e.forIn("key",s,_=>{!u.length&&!d.length?h(_):e.if(p(_),()=>h(_))})}function p(_){let E;if(u.length>8){let S=(0,zn.schemaRefOrVal)(i,n.properties,"properties");E=(0,Nn.isOwnProperty)(e,S,_)}else u.length?E=(0,ke.or)(...u.map(S=>(0,ke._)`${_} === ${S}`)):E=ke.nil;return d.length&&(E=(0,ke.or)(E,...d.map(S=>(0,ke._)`${(0,Nn.usePattern)(t,S)}.test(${_})`))),(0,ke.not)(E)}function m(_){e.code((0,ke._)`delete ${s}[${_}]`)}function h(_){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){m(_);return}if(r===!1){t.setParams({additionalProperty:_}),t.error(),c||e.break();return}if(typeof r=="object"&&!(0,zn.alwaysValidSchema)(i,r)){let E=e.name("valid");l.removeAdditional==="failing"?(g(_,E,!1),e.if((0,ke.not)(E),()=>{t.reset(),m(_)})):(g(_,E),c||e.if((0,ke.not)(E),()=>e.break()))}}function g(_,E,S){let w={keyword:"additionalProperties",dataProp:_,dataPropType:zn.Type.Str};S===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(w,E)}}};Jo.default=My});var Sl=b(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});var Ay=Er(),yl=he(),Zo=x(),_l=Bo(),Cy={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&_l.default.code(new Ay.KeywordCxt(o,_l.default,"additionalProperties"));let i=(0,yl.allSchemaProperties)(r);for(let f of i)o.definedProperties.add(f);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=Zo.mergeEvaluated.props(e,(0,Zo.toHash)(i),o.props));let c=i.filter(f=>!(0,Zo.alwaysValidSchema)(o,r[f]));if(c.length===0)return;let l=e.name("valid");for(let f of c)u(f)?d(f):(e.if((0,yl.propertyInData)(e,s,f,o.opts.ownProperties)),d(f),o.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(f),t.ok(l);function u(f){return o.opts.useDefaults&&!o.compositeRule&&r[f].default!==void 0}function d(f){t.subschema({keyword:"properties",schemaProp:f,dataProp:f},l)}}};Xo.default=Cy});var vl=b(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});var El=he(),Ln=R(),wl=x(),bl=x(),Oy={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:s,it:o}=t,{opts:i}=o,c=(0,El.allSchemaProperties)(r),l=c.filter(g=>(0,wl.alwaysValidSchema)(o,r[g]));if(c.length===0||l.length===c.length&&(!o.opts.unevaluated||o.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&s.properties,d=e.name("valid");o.props!==!0&&!(o.props instanceof Ln.Name)&&(o.props=(0,bl.evaluatedPropsToName)(e,o.props));let{props:f}=o;p();function p(){for(let g of c)u&&m(g),o.allErrors?h(g):(e.var(d,!0),h(g),e.if(d))}function m(g){for(let _ in u)new RegExp(g).test(_)&&(0,wl.checkStrictMode)(o,`property ${_} matches pattern ${g} (use allowMatchingProperties)`)}function h(g){e.forIn("key",n,_=>{e.if((0,Ln._)`${(0,El.usePattern)(t,g)}.test(${_})`,()=>{let E=l.includes(g);E||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:_,dataPropType:bl.Type.Str},d),o.opts.unevaluated&&f!==!0?e.assign((0,Ln._)`${f}[${_}]`,!0):!E&&!o.allErrors&&e.if((0,Ln.not)(d),()=>e.break())})})}}};Qo.default=Oy});var kl=b(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});var Iy=x(),xy={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,Iy.alwaysValidSchema)(n,r)){t.fail();return}let s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};ei.default=xy});var Tl=b(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});var Dy=he(),Ny={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Dy.validateUnion,error:{message:"must match a schema in anyOf"}};ti.default=Ny});var Pl=b(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});var jn=R(),zy=x(),Ly={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,jn._)`{passingSchemas: ${t.passing}}`},jy={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Ly,code(t){let{gen:e,schema:r,parentSchema:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;let o=r,i=e.let("valid",!1),c=e.let("passing",null),l=e.name("_valid");t.setParams({passing:c}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){o.forEach((d,f)=>{let p;(0,zy.alwaysValidSchema)(s,d)?e.var(l,!0):p=t.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},l),f>0&&e.if((0,jn._)`${l} && ${i}`).assign(i,!1).assign(c,(0,jn._)`[${c}, ${f}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(c,f),p&&t.mergeEvaluated(p,jn.Name)})})}}};ri.default=jy});var $l=b(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});var qy=x(),Uy={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let s=e.name("valid");r.forEach((o,i)=>{if((0,qy.alwaysValidSchema)(n,o))return;let c=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(c)})}};ni.default=Uy});var Al=b(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});var qn=R(),Ml=x(),Fy={message:({params:t})=>(0,qn.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,qn._)`{failingKeyword: ${t.ifClause}}`},Hy={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Fy,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Ml.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=Rl(n,"then"),o=Rl(n,"else");if(!s&&!o)return;let i=e.let("valid",!0),c=e.name("_valid");if(l(),t.reset(),s&&o){let d=e.let("ifClause");t.setParams({ifClause:d}),e.if(c,u("then",d),u("else",d))}else s?e.if(c,u("then")):e.if((0,qn.not)(c),u("else"));t.pass(i,()=>t.error(!0));function l(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},c);t.mergeEvaluated(d)}function u(d,f){return()=>{let p=t.subschema({keyword:d},c);e.assign(i,c),t.mergeValidEvaluated(p,i),f?e.assign(f,(0,qn._)`${d}`):t.setParams({ifClause:d})}}}};function Rl(t,e){let r=t.schema[e];return r!==void 0&&!(0,Ml.alwaysValidSchema)(t,r)}si.default=Hy});var Cl=b(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});var Wy=x(),Vy={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,Wy.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};oi.default=Vy});var Ol=b(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});var Gy=Fo(),Ky=cl(),Yy=Ho(),Jy=ul(),By=dl(),Zy=ml(),Xy=gl(),Qy=Bo(),e_=Sl(),t_=vl(),r_=kl(),n_=Tl(),s_=Pl(),o_=$l(),i_=Al(),a_=Cl();function c_(t=!1){let e=[r_.default,n_.default,s_.default,o_.default,i_.default,a_.default,Xy.default,Qy.default,Zy.default,e_.default,t_.default];return t?e.push(Ky.default,Jy.default):e.push(Gy.default,Yy.default),e.push(By.default),e}ii.default=c_});var Il=b(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});var U=R(),l_={message:({schemaCode:t})=>(0,U.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,U._)`{format: ${t}}`},u_={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:l_,code(t,e){let{gen:r,data:n,$data:s,schema:o,schemaCode:i,it:c}=t,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;s?p():m();function p(){let h=r.scopeValue("formats",{ref:f.formats,code:l.code.formats}),g=r.const("fDef",(0,U._)`${h}[${i}]`),_=r.let("fType"),E=r.let("format");r.if((0,U._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(_,(0,U._)`${g}.type || "string"`).assign(E,(0,U._)`${g}.validate`),()=>r.assign(_,(0,U._)`"string"`).assign(E,g)),t.fail$data((0,U.or)(S(),w()));function S(){return l.strictSchema===!1?U.nil:(0,U._)`${i} && !${E}`}function w(){let A=d.$async?(0,U._)`(${g}.async ? await ${E}(${n}) : ${E}(${n}))`:(0,U._)`${E}(${n})`,k=(0,U._)`(typeof ${E} == "function" ? ${A} : ${E}.test(${n}))`;return(0,U._)`${E} && ${E} !== true && ${_} === ${e} && !${k}`}}function m(){let h=f.formats[o];if(!h){S();return}if(h===!0)return;let[g,_,E]=w(h);g===e&&t.pass(A());function S(){if(l.strictSchema===!1){f.logger.warn(k());return}throw new Error(k());function k(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function w(k){let le=k instanceof RegExp?(0,U.regexpCode)(k):l.code.formats?(0,U._)`${l.code.formats}${(0,U.getProperty)(o)}`:void 0,de=r.scopeValue("formats",{key:o,ref:k,code:le});return typeof k=="object"&&!(k instanceof RegExp)?[k.type||"string",k.validate,(0,U._)`${de}.validate`]:["string",k,de]}function A(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!d.$async)throw new Error("async format in sync schema");return(0,U._)`await ${E}(${n})`}return typeof _=="function"?(0,U._)`${E}(${n})`:(0,U._)`${E}.test(${n})`}}}};ai.default=u_});var xl=b(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});var d_=Il(),f_=[d_.default];ci.default=f_});var Dl=b(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.contentVocabulary=It.metadataVocabulary=void 0;It.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];It.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var zl=b(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});var p_=Wc(),m_=sl(),h_=Ol(),g_=xl(),Nl=Dl(),y_=[p_.default,m_.default,(0,h_.default)(),g_.default,Nl.metadataVocabulary,Nl.contentVocabulary];li.default=y_});var jl=b(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.DiscrError=void 0;var Ll;(function(t){t.Tag="tag",t.Mapping="mapping"})(Ll||(Un.DiscrError=Ll={}))});var Ul=b(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});var xt=R(),ui=jl(),ql=vn(),__=wr(),S_=x(),E_={message:({params:{discrError:t,tagName:e}})=>t===ui.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,xt._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},w_={keyword:"discriminator",type:"object",schemaType:"object",error:E_,code(t){let{gen:e,data:r,schema:n,parentSchema:s,it:o}=t,{oneOf:i}=s;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let c=n.propertyName;if(typeof c!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let l=e.let("valid",!1),u=e.const("tag",(0,xt._)`${r}${(0,xt.getProperty)(c)}`);e.if((0,xt._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:ui.DiscrError.Tag,tag:u,tagName:c})),t.ok(l);function d(){let m=p();e.if(!1);for(let h in m)e.elseIf((0,xt._)`${u} === ${h}`),e.assign(l,f(m[h]));e.else(),t.error(!1,{discrError:ui.DiscrError.Mapping,tag:u,tagName:c}),e.endIf()}function f(m){let h=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:m},h);return t.mergeEvaluated(g,xt.Name),h}function p(){var m;let h={},g=E(s),_=!0;for(let A=0;A<i.length;A++){let k=i[A];if(k?.$ref&&!(0,S_.schemaHasRulesButRef)(k,o.self.RULES)){let de=k.$ref;if(k=ql.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,de),k instanceof ql.SchemaEnv&&(k=k.schema),k===void 0)throw new __.default(o.opts.uriResolver,o.baseId,de)}let le=(m=k?.properties)===null||m===void 0?void 0:m[c];if(typeof le!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${c}"`);_=_&&(g||E(k)),S(le,A)}if(!_)throw new Error(`discriminator: "${c}" must be required`);return h;function E({required:A}){return Array.isArray(A)&&A.includes(c)}function S(A,k){if(A.const)w(A.const,k);else if(A.enum)for(let le of A.enum)w(le,k);else throw new Error(`discriminator: "properties/${c}" must have "const" or "enum"`)}function w(A,k){if(typeof A!="string"||A in h)throw new Error(`discriminator: "${c}" values must be unique strings`);h[A]=k}}}};di.default=w_});var Fl=b((ck,b_)=>{b_.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var pi=b((q,fi)=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.MissingRefError=q.ValidationError=q.CodeGen=q.Name=q.nil=q.stringify=q.str=q._=q.KeywordCxt=q.Ajv=void 0;var v_=Lc(),k_=zl(),T_=Ul(),Hl=Fl(),P_=["/properties"],Fn="http://json-schema.org/draft-07/schema",Dt=class extends v_.default{_addVocabularies(){super._addVocabularies(),k_.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(T_.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Hl,P_):Hl;this.addMetaSchema(e,Fn,!1),this.refs["http://json-schema.org/schema"]=Fn}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Fn)?Fn:void 0)}};q.Ajv=Dt;fi.exports=q=Dt;fi.exports.Ajv=Dt;Object.defineProperty(q,"__esModule",{value:!0});q.default=Dt;var $_=Er();Object.defineProperty(q,"KeywordCxt",{enumerable:!0,get:function(){return $_.KeywordCxt}});var Nt=R();Object.defineProperty(q,"_",{enumerable:!0,get:function(){return Nt._}});Object.defineProperty(q,"str",{enumerable:!0,get:function(){return Nt.str}});Object.defineProperty(q,"stringify",{enumerable:!0,get:function(){return Nt.stringify}});Object.defineProperty(q,"nil",{enumerable:!0,get:function(){return Nt.nil}});Object.defineProperty(q,"Name",{enumerable:!0,get:function(){return Nt.Name}});Object.defineProperty(q,"CodeGen",{enumerable:!0,get:function(){return Nt.CodeGen}});var R_=wn();Object.defineProperty(q,"ValidationError",{enumerable:!0,get:function(){return R_.default}});var M_=wr();Object.defineProperty(q,"MissingRefError",{enumerable:!0,get:function(){return M_.default}})});var Zl=b(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.formatNames=Oe.fastFormats=Oe.fullFormats=void 0;function Ce(t,e){return{validate:t,compare:e}}Oe.fullFormats={date:Ce(Kl,yi),time:Ce(hi(!0),_i),"date-time":Ce(Wl(!0),Jl),"iso-time":Ce(hi(),Yl),"iso-date-time":Ce(Wl(),Bl),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:D_,"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:F_,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:N_,int32:{type:"number",validate:j_},int64:{type:"number",validate:q_},float:{type:"number",validate:Gl},double:{type:"number",validate:Gl},password:!0,binary:!0};Oe.fastFormats={...Oe.fullFormats,date:Ce(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,yi),time:Ce(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,_i),"date-time":Ce(/^\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,Jl),"iso-time":Ce(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Yl),"iso-date-time":Ce(/^\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,Bl),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};Oe.formatNames=Object.keys(Oe.fullFormats);function A_(t){return t%4===0&&(t%100!==0||t%400===0)}var C_=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,O_=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Kl(t){let e=C_.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],s=+e[3];return n>=1&&n<=12&&s>=1&&s<=(n===2&&A_(r)?29:O_[n])}function yi(t,e){if(t&&e)return t>e?1:t<e?-1:0}var mi=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function hi(t){return function(r){let n=mi.exec(r);if(!n)return!1;let s=+n[1],o=+n[2],i=+n[3],c=n[4],l=n[5]==="-"?-1:1,u=+(n[6]||0),d=+(n[7]||0);if(u>23||d>59||t&&!c)return!1;if(s<=23&&o<=59&&i<60)return!0;let f=o-d*l,p=s-u*l-(f<0?1:0);return(p===23||p===-1)&&(f===59||f===-1)&&i<61}}function _i(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function Yl(t,e){if(!(t&&e))return;let r=mi.exec(t),n=mi.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var gi=/t|\s/i;function Wl(t){let e=hi(t);return function(n){let s=n.split(gi);return s.length===2&&Kl(s[0])&&e(s[1])}}function Jl(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Bl(t,e){if(!(t&&e))return;let[r,n]=t.split(gi),[s,o]=e.split(gi),i=yi(r,s);if(i!==void 0)return i||_i(n,o)}var I_=/\/|:/,x_=/^(?:[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;function D_(t){return I_.test(t)&&x_.test(t)}var Vl=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function N_(t){return Vl.lastIndex=0,Vl.test(t)}var z_=-(2**31),L_=2**31-1;function j_(t){return Number.isInteger(t)&&t<=L_&&t>=z_}function q_(t){return Number.isInteger(t)}function Gl(){return!0}var U_=/[^\\]\\Z/;function F_(t){if(U_.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Xl=b(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.formatLimitDefinition=void 0;var H_=pi(),Te=R(),nt=Te.operators,Hn={formatMaximum:{okStr:"<=",ok:nt.LTE,fail:nt.GT},formatMinimum:{okStr:">=",ok:nt.GTE,fail:nt.LT},formatExclusiveMaximum:{okStr:"<",ok:nt.LT,fail:nt.GTE},formatExclusiveMinimum:{okStr:">",ok:nt.GT,fail:nt.LTE}},W_={message:({keyword:t,schemaCode:e})=>(0,Te.str)`should be ${Hn[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Te._)`{comparison: ${Hn[t].okStr}, limit: ${e}}`};zt.formatLimitDefinition={keyword:Object.keys(Hn),type:"string",schemaType:"string",$data:!0,error:W_,code(t){let{gen:e,data:r,schemaCode:n,keyword:s,it:o}=t,{opts:i,self:c}=o;if(!i.validateFormats)return;let l=new H_.KeywordCxt(o,c.RULES.all.format.definition,"format");l.$data?u():d();function u(){let p=e.scopeValue("formats",{ref:c.formats,code:i.code.formats}),m=e.const("fmt",(0,Te._)`${p}[${l.schemaCode}]`);t.fail$data((0,Te.or)((0,Te._)`typeof ${m} != "object"`,(0,Te._)`${m} instanceof RegExp`,(0,Te._)`typeof ${m}.compare != "function"`,f(m)))}function d(){let p=l.schema,m=c.formats[p];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${s}": format "${p}" does not define "compare" function`);let h=e.scopeValue("formats",{key:p,ref:m,code:i.code.formats?(0,Te._)`${i.code.formats}${(0,Te.getProperty)(p)}`:void 0});t.fail$data(f(h))}function f(p){return(0,Te._)`${p}.compare(${r}, ${n}) ${Hn[s].fail} 0`}},dependencies:["format"]};var V_=t=>(t.addKeyword(zt.formatLimitDefinition),t);zt.default=V_});var ru=b((Dr,tu)=>{"use strict";Object.defineProperty(Dr,"__esModule",{value:!0});var Lt=Zl(),G_=Xl(),Si=R(),Ql=new Si.Name("fullFormats"),K_=new Si.Name("fastFormats"),Ei=(t,e={keywords:!0})=>{if(Array.isArray(e))return eu(t,e,Lt.fullFormats,Ql),t;let[r,n]=e.mode==="fast"?[Lt.fastFormats,K_]:[Lt.fullFormats,Ql],s=e.formats||Lt.formatNames;return eu(t,s,r,n),e.keywords&&(0,G_.default)(t),t};Ei.get=(t,e="full")=>{let n=(e==="fast"?Lt.fastFormats:Lt.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function eu(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,Si._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}tu.exports=Dr=Ei;Object.defineProperty(Dr,"__esModule",{value:!0});Dr.default=Ei});var Le=require("fs"),Yt=require("path"),Xi=require("os"),is=(o=>(o[o.DEBUG=0]="DEBUG",o[o.INFO=1]="INFO",o[o.WARN=2]="WARN",o[o.ERROR=3]="ERROR",o[o.SILENT=4]="SILENT",o))(is||{}),Zi=(0,Yt.join)((0,Xi.homedir)(),".claude-mem"),as=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let e=(0,Yt.join)(Zi,"logs");(0,Le.existsSync)(e)||(0,Le.mkdirSync)(e,{recursive:!0});let r=new Date().toISOString().split("T")[0];this.logFilePath=(0,Yt.join)(e,`claude-mem-${r}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e instanceof Error?e.message:String(e)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=(0,Yt.join)(Zi,"settings.json");if((0,Le.existsSync)(e)){let r=(0,Le.readFileSync)(e,"utf-8"),s=(JSON.parse(r).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=is[s]??1}else this.level=1}catch(e){console.error("[LOGGER] Failed to load log level from settings:",e instanceof Error?e.message:String(e)),this.level=1}return this.level}correlationId(e,r){return`obs-${e}-${r}`}sessionId(e){return`session-${e}`}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message}
|
|
${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let r=Object.keys(e);return r.length===0?"{}":r.length<=3?JSON.stringify(e):`{${r.length} keys: ${r.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,r){if(!r)return e;let n=r;if(typeof r=="string")try{n=JSON.parse(r)}catch{n=r}if(e==="Bash"&&n.command)return`${e}(${n.command})`;if(n.file_path)return`${e}(${n.file_path})`;if(n.notebook_path)return`${e}(${n.notebook_path})`;if(e==="Glob"&&n.pattern)return`${e}(${n.pattern})`;if(e==="Grep"&&n.pattern)return`${e}(${n.pattern})`;if(n.url)return`${e}(${n.url})`;if(n.query)return`${e}(${n.query})`;if(e==="Task"){if(n.subagent_type)return`${e}(${n.subagent_type})`;if(n.description)return`${e}(${n.description})`}return e==="Skill"&&n.skill?`${e}(${n.skill})`:e==="LSP"&&n.operation?`${e}(${n.operation})`:e}formatTimestamp(e){let r=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0"),o=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),c=String(e.getSeconds()).padStart(2,"0"),l=String(e.getMilliseconds()).padStart(3,"0");return`${r}-${n}-${s} ${o}:${i}:${c}.${l}`}log(e,r,n,s,o){if(e<this.getLevel())return;this.ensureLogFileInitialized();let i=this.formatTimestamp(new Date),c=is[e].padEnd(5),l=r.padEnd(6),u="";s?.correlationId?u=`[${s.correlationId}] `:s?.sessionId&&(u=`[session-${s.sessionId}] `);let d="";if(o!=null)if(o instanceof Error)d=this.getLevel()===0?`
|
|
${o.message}
|
|
${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{d=`
|
|
`+JSON.stringify(o,null,2)}catch{d=" "+this.formatData(o)}else d=" "+this.formatData(o);let f="";if(s){let{sessionId:m,memorySessionId:h,correlationId:g,..._}=s;Object.keys(_).length>0&&(f=` {${Object.entries(_).map(([S,w])=>`${S}=${w}`).join(", ")}}`)}let p=`[${i}] [${c}] [${l}] ${u}${n}${f}${d}`;if(this.logFilePath)try{(0,Le.appendFileSync)(this.logFilePath,p+`
|
|
`,"utf8")}catch(m){process.stderr.write(`[LOGGER] Failed to write to log file: ${m instanceof Error?m.message:String(m)}
|
|
`)}else process.stderr.write(p+`
|
|
`)}debug(e,r,n,s){this.log(0,e,r,n,s)}info(e,r,n,s){this.log(1,e,r,n,s)}warn(e,r,n,s){this.log(2,e,r,n,s)}error(e,r,n,s){this.log(3,e,r,n,s)}dataIn(e,r,n,s){this.info(e,`\u2192 ${r}`,n,s)}dataOut(e,r,n,s){this.info(e,`\u2190 ${r}`,n,s)}success(e,r,n,s){this.info(e,`\u2713 ${r}`,n,s)}failure(e,r,n,s){this.error(e,`\u2717 ${r}`,n,s)}timing(e,r,n,s){this.info(e,`\u23F1 ${r}`,s,{duration:`${n}ms`})}happyPathError(e,r,n,s,o=""){let u=((new Error().stack||"").split(`
|
|
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),d=u?`${u[1].split("/").pop()}:${u[2]}`:"unknown",f={...n,location:d};return this.warn(e,`[HAPPY-PATH] ${r}`,f,s),o}},y=new as;var md=se(require("zod/v3"),1),Vr=se(require("zod/v4-mini"),1);function yt(t){return!!t._zod}function Ke(t,e){return yt(t)?Vr.safeParse(t,e):t.safeParse(e)}function Gr(t){if(!t)return;let e;if(yt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Qi(t){if(yt(t)){let o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var a=se(require("zod/v4"),1),ls="2025-11-25";var ea=[ls,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ye="io.modelcontextprotocol/related-task",Yr="2.0",W=a.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),ta=a.union([a.string(),a.number().int()]),ra=a.string(),cE=a.looseObject({ttl:a.number().optional(),pollInterval:a.number().optional()}),hd=a.object({ttl:a.number().optional()}),gd=a.object({taskId:a.string()}),us=a.looseObject({progressToken:ta.optional(),[Ye]:gd.optional()}),ue=a.object({_meta:us.optional()}),Jt=ue.extend({task:hd.optional()}),na=t=>Jt.safeParse(t).success,V=a.object({method:a.string(),params:ue.loose().optional()}),fe=a.object({_meta:us.optional()}),pe=a.object({method:a.string(),params:fe.loose().optional()}),G=a.looseObject({_meta:us.optional()}),Jr=a.union([a.string(),a.number().int()]),sa=a.object({jsonrpc:a.literal(Yr),id:Jr,...V.shape}).strict(),ds=t=>sa.safeParse(t).success,oa=a.object({jsonrpc:a.literal(Yr),...pe.shape}).strict(),ia=t=>oa.safeParse(t).success,fs=a.object({jsonrpc:a.literal(Yr),id:Jr,result:G}).strict(),Bt=t=>fs.safeParse(t).success;var O;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(O||(O={}));var ps=a.object({jsonrpc:a.literal(Yr),id:Jr.optional(),error:a.object({code:a.number().int(),message:a.string(),data:a.unknown().optional()})}).strict();var aa=t=>ps.safeParse(t).success;var ca=a.union([sa,oa,fs,ps]),lE=a.union([fs,ps]),Br=G.strict(),yd=fe.extend({requestId:Jr.optional(),reason:a.string().optional()}),Zr=pe.extend({method:a.literal("notifications/cancelled"),params:yd}),_d=a.object({src:a.string(),mimeType:a.string().optional(),sizes:a.array(a.string()).optional(),theme:a.enum(["light","dark"]).optional()}),Zt=a.object({icons:a.array(_d).optional()}),_t=a.object({name:a.string(),title:a.string().optional()}),la=_t.extend({..._t.shape,...Zt.shape,version:a.string(),websiteUrl:a.string().optional(),description:a.string().optional()}),Sd=a.intersection(a.object({applyDefaults:a.boolean().optional()}),a.record(a.string(),a.unknown())),Ed=a.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,a.intersection(a.object({form:Sd.optional(),url:W.optional()}),a.record(a.string(),a.unknown()).optional())),wd=a.looseObject({list:W.optional(),cancel:W.optional(),requests:a.looseObject({sampling:a.looseObject({createMessage:W.optional()}).optional(),elicitation:a.looseObject({create:W.optional()}).optional()}).optional()}),bd=a.looseObject({list:W.optional(),cancel:W.optional(),requests:a.looseObject({tools:a.looseObject({call:W.optional()}).optional()}).optional()}),vd=a.object({experimental:a.record(a.string(),W).optional(),sampling:a.object({context:W.optional(),tools:W.optional()}).optional(),elicitation:Ed.optional(),roots:a.object({listChanged:a.boolean().optional()}).optional(),tasks:wd.optional(),extensions:a.record(a.string(),W).optional()}),kd=ue.extend({protocolVersion:a.string(),capabilities:vd,clientInfo:la}),ms=V.extend({method:a.literal("initialize"),params:kd});var Td=a.object({experimental:a.record(a.string(),W).optional(),logging:W.optional(),completions:W.optional(),prompts:a.object({listChanged:a.boolean().optional()}).optional(),resources:a.object({subscribe:a.boolean().optional(),listChanged:a.boolean().optional()}).optional(),tools:a.object({listChanged:a.boolean().optional()}).optional(),tasks:bd.optional(),extensions:a.record(a.string(),W).optional()}),Pd=G.extend({protocolVersion:a.string(),capabilities:Td,serverInfo:la,instructions:a.string().optional()}),hs=pe.extend({method:a.literal("notifications/initialized"),params:fe.optional()});var Xr=V.extend({method:a.literal("ping"),params:ue.optional()}),$d=a.object({progress:a.number(),total:a.optional(a.number()),message:a.optional(a.string())}),Rd=a.object({...fe.shape,...$d.shape,progressToken:ta}),Qr=pe.extend({method:a.literal("notifications/progress"),params:Rd}),Md=ue.extend({cursor:ra.optional()}),Xt=V.extend({params:Md.optional()}),Qt=G.extend({nextCursor:ra.optional()}),Ad=a.enum(["working","input_required","completed","failed","cancelled"]),er=a.object({taskId:a.string(),status:Ad,ttl:a.union([a.number(),a.null()]),createdAt:a.string(),lastUpdatedAt:a.string(),pollInterval:a.optional(a.number()),statusMessage:a.optional(a.string())}),St=G.extend({task:er}),Cd=fe.merge(er),tr=pe.extend({method:a.literal("notifications/tasks/status"),params:Cd}),en=V.extend({method:a.literal("tasks/get"),params:ue.extend({taskId:a.string()})}),tn=G.merge(er),rn=V.extend({method:a.literal("tasks/result"),params:ue.extend({taskId:a.string()})}),uE=G.loose(),nn=Xt.extend({method:a.literal("tasks/list")}),sn=Qt.extend({tasks:a.array(er)}),on=V.extend({method:a.literal("tasks/cancel"),params:ue.extend({taskId:a.string()})}),ua=G.merge(er),da=a.object({uri:a.string(),mimeType:a.optional(a.string()),_meta:a.record(a.string(),a.unknown()).optional()}),fa=da.extend({text:a.string()}),gs=a.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),pa=da.extend({blob:gs}),rr=a.enum(["user","assistant"]),Et=a.object({audience:a.array(rr).optional(),priority:a.number().min(0).max(1).optional(),lastModified:a.iso.datetime({offset:!0}).optional()}),ma=a.object({..._t.shape,...Zt.shape,uri:a.string(),description:a.optional(a.string()),mimeType:a.optional(a.string()),size:a.optional(a.number()),annotations:Et.optional(),_meta:a.optional(a.looseObject({}))}),Od=a.object({..._t.shape,...Zt.shape,uriTemplate:a.string(),description:a.optional(a.string()),mimeType:a.optional(a.string()),annotations:Et.optional(),_meta:a.optional(a.looseObject({}))}),Id=Xt.extend({method:a.literal("resources/list")}),xd=Qt.extend({resources:a.array(ma)}),Dd=Xt.extend({method:a.literal("resources/templates/list")}),Nd=Qt.extend({resourceTemplates:a.array(Od)}),ys=ue.extend({uri:a.string()}),zd=ys,Ld=V.extend({method:a.literal("resources/read"),params:zd}),jd=G.extend({contents:a.array(a.union([fa,pa]))}),qd=pe.extend({method:a.literal("notifications/resources/list_changed"),params:fe.optional()}),Ud=ys,Fd=V.extend({method:a.literal("resources/subscribe"),params:Ud}),Hd=ys,Wd=V.extend({method:a.literal("resources/unsubscribe"),params:Hd}),Vd=fe.extend({uri:a.string()}),Gd=pe.extend({method:a.literal("notifications/resources/updated"),params:Vd}),Kd=a.object({name:a.string(),description:a.optional(a.string()),required:a.optional(a.boolean())}),Yd=a.object({..._t.shape,...Zt.shape,description:a.optional(a.string()),arguments:a.optional(a.array(Kd)),_meta:a.optional(a.looseObject({}))}),Jd=Xt.extend({method:a.literal("prompts/list")}),Bd=Qt.extend({prompts:a.array(Yd)}),Zd=ue.extend({name:a.string(),arguments:a.record(a.string(),a.string()).optional()}),Xd=V.extend({method:a.literal("prompts/get"),params:Zd}),_s=a.object({type:a.literal("text"),text:a.string(),annotations:Et.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),Ss=a.object({type:a.literal("image"),data:gs,mimeType:a.string(),annotations:Et.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),Es=a.object({type:a.literal("audio"),data:gs,mimeType:a.string(),annotations:Et.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),Qd=a.object({type:a.literal("tool_use"),name:a.string(),id:a.string(),input:a.record(a.string(),a.unknown()),_meta:a.record(a.string(),a.unknown()).optional()}),ef=a.object({type:a.literal("resource"),resource:a.union([fa,pa]),annotations:Et.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),tf=ma.extend({type:a.literal("resource_link")}),ws=a.union([_s,Ss,Es,tf,ef]),rf=a.object({role:rr,content:ws}),nf=G.extend({description:a.string().optional(),messages:a.array(rf)}),sf=pe.extend({method:a.literal("notifications/prompts/list_changed"),params:fe.optional()}),of=a.object({title:a.string().optional(),readOnlyHint:a.boolean().optional(),destructiveHint:a.boolean().optional(),idempotentHint:a.boolean().optional(),openWorldHint:a.boolean().optional()}),af=a.object({taskSupport:a.enum(["required","optional","forbidden"]).optional()}),ha=a.object({..._t.shape,...Zt.shape,description:a.string().optional(),inputSchema:a.object({type:a.literal("object"),properties:a.record(a.string(),W).optional(),required:a.array(a.string()).optional()}).catchall(a.unknown()),outputSchema:a.object({type:a.literal("object"),properties:a.record(a.string(),W).optional(),required:a.array(a.string()).optional()}).catchall(a.unknown()).optional(),annotations:of.optional(),execution:af.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),bs=Xt.extend({method:a.literal("tools/list")}),cf=Qt.extend({tools:a.array(ha)}),an=G.extend({content:a.array(ws).default([]),structuredContent:a.record(a.string(),a.unknown()).optional(),isError:a.boolean().optional()}),dE=an.or(G.extend({toolResult:a.unknown()})),lf=Jt.extend({name:a.string(),arguments:a.record(a.string(),a.unknown()).optional()}),nr=V.extend({method:a.literal("tools/call"),params:lf}),uf=pe.extend({method:a.literal("notifications/tools/list_changed"),params:fe.optional()}),fE=a.object({autoRefresh:a.boolean().default(!0),debounceMs:a.number().int().nonnegative().default(300)}),sr=a.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),df=ue.extend({level:sr}),vs=V.extend({method:a.literal("logging/setLevel"),params:df}),ff=fe.extend({level:sr,logger:a.string().optional(),data:a.unknown()}),pf=pe.extend({method:a.literal("notifications/message"),params:ff}),mf=a.object({name:a.string().optional()}),hf=a.object({hints:a.array(mf).optional(),costPriority:a.number().min(0).max(1).optional(),speedPriority:a.number().min(0).max(1).optional(),intelligencePriority:a.number().min(0).max(1).optional()}),gf=a.object({mode:a.enum(["auto","required","none"]).optional()}),yf=a.object({type:a.literal("tool_result"),toolUseId:a.string().describe("The unique identifier for the corresponding tool call."),content:a.array(ws).default([]),structuredContent:a.object({}).loose().optional(),isError:a.boolean().optional(),_meta:a.record(a.string(),a.unknown()).optional()}),_f=a.discriminatedUnion("type",[_s,Ss,Es]),Kr=a.discriminatedUnion("type",[_s,Ss,Es,Qd,yf]),Sf=a.object({role:rr,content:a.union([Kr,a.array(Kr)]),_meta:a.record(a.string(),a.unknown()).optional()}),Ef=Jt.extend({messages:a.array(Sf),modelPreferences:hf.optional(),systemPrompt:a.string().optional(),includeContext:a.enum(["none","thisServer","allServers"]).optional(),temperature:a.number().optional(),maxTokens:a.number().int(),stopSequences:a.array(a.string()).optional(),metadata:W.optional(),tools:a.array(ha).optional(),toolChoice:gf.optional()}),wf=V.extend({method:a.literal("sampling/createMessage"),params:Ef}),or=G.extend({model:a.string(),stopReason:a.optional(a.enum(["endTurn","stopSequence","maxTokens"]).or(a.string())),role:rr,content:_f}),ks=G.extend({model:a.string(),stopReason:a.optional(a.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(a.string())),role:rr,content:a.union([Kr,a.array(Kr)])}),bf=a.object({type:a.literal("boolean"),title:a.string().optional(),description:a.string().optional(),default:a.boolean().optional()}),vf=a.object({type:a.literal("string"),title:a.string().optional(),description:a.string().optional(),minLength:a.number().optional(),maxLength:a.number().optional(),format:a.enum(["email","uri","date","date-time"]).optional(),default:a.string().optional()}),kf=a.object({type:a.enum(["number","integer"]),title:a.string().optional(),description:a.string().optional(),minimum:a.number().optional(),maximum:a.number().optional(),default:a.number().optional()}),Tf=a.object({type:a.literal("string"),title:a.string().optional(),description:a.string().optional(),enum:a.array(a.string()),default:a.string().optional()}),Pf=a.object({type:a.literal("string"),title:a.string().optional(),description:a.string().optional(),oneOf:a.array(a.object({const:a.string(),title:a.string()})),default:a.string().optional()}),$f=a.object({type:a.literal("string"),title:a.string().optional(),description:a.string().optional(),enum:a.array(a.string()),enumNames:a.array(a.string()).optional(),default:a.string().optional()}),Rf=a.union([Tf,Pf]),Mf=a.object({type:a.literal("array"),title:a.string().optional(),description:a.string().optional(),minItems:a.number().optional(),maxItems:a.number().optional(),items:a.object({type:a.literal("string"),enum:a.array(a.string())}),default:a.array(a.string()).optional()}),Af=a.object({type:a.literal("array"),title:a.string().optional(),description:a.string().optional(),minItems:a.number().optional(),maxItems:a.number().optional(),items:a.object({anyOf:a.array(a.object({const:a.string(),title:a.string()}))}),default:a.array(a.string()).optional()}),Cf=a.union([Mf,Af]),Of=a.union([$f,Rf,Cf]),If=a.union([Of,bf,vf,kf]),xf=Jt.extend({mode:a.literal("form").optional(),message:a.string(),requestedSchema:a.object({type:a.literal("object"),properties:a.record(a.string(),If),required:a.array(a.string()).optional()})}),Df=Jt.extend({mode:a.literal("url"),message:a.string(),elicitationId:a.string(),url:a.string().url()}),Nf=a.union([xf,Df]),zf=V.extend({method:a.literal("elicitation/create"),params:Nf}),Lf=fe.extend({elicitationId:a.string()}),jf=pe.extend({method:a.literal("notifications/elicitation/complete"),params:Lf}),wt=G.extend({action:a.enum(["accept","decline","cancel"]),content:a.preprocess(t=>t===null?void 0:t,a.record(a.string(),a.union([a.string(),a.number(),a.boolean(),a.array(a.string())])).optional())}),qf=a.object({type:a.literal("ref/resource"),uri:a.string()});var Uf=a.object({type:a.literal("ref/prompt"),name:a.string()}),Ff=ue.extend({ref:a.union([Uf,qf]),argument:a.object({name:a.string(),value:a.string()}),context:a.object({arguments:a.record(a.string(),a.string()).optional()}).optional()}),Hf=V.extend({method:a.literal("completion/complete"),params:Ff});var Wf=G.extend({completion:a.looseObject({values:a.array(a.string()).max(100),total:a.optional(a.number().int()),hasMore:a.optional(a.boolean())})}),Vf=a.object({uri:a.string().startsWith("file://"),name:a.string().optional(),_meta:a.record(a.string(),a.unknown()).optional()}),Gf=V.extend({method:a.literal("roots/list"),params:ue.optional()}),Ts=G.extend({roots:a.array(Vf)}),Kf=pe.extend({method:a.literal("notifications/roots/list_changed"),params:fe.optional()}),pE=a.union([Xr,ms,Hf,vs,Xd,Jd,Id,Dd,Ld,Fd,Wd,nr,bs,en,rn,nn,on]),mE=a.union([Zr,Qr,hs,Kf,tr]),hE=a.union([Br,or,ks,wt,Ts,tn,sn,St]),gE=a.union([Xr,wf,zf,Gf,en,rn,nn,on]),yE=a.union([Zr,Qr,pf,Gd,qd,uf,sf,tr,jf]),_E=a.union([Br,Pd,Wf,nf,Bd,xd,Nd,jd,an,cf,tn,sn,St]),P=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===O.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new cs(s.elicitations,r)}return new t(e,r,n)}},cs=class extends P{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(O.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Je(t){return t==="completed"||t==="failed"||t==="cancelled"}var rp=se(require("zod/v4-mini"),1);var ep=require("zod/v3");var Jf=require("zod/v3");var Xf=require("zod/v3");var ZE=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Ps(t){let r=Gr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Qi(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function $s(t,e){let r=Ke(t,e);if(!r.success)throw r.error;return r.data}var np=6e4,cn=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Zr,r=>{this._oncancel(r)}),this.setNotificationHandler(Qr,r=>{this._onprogress(r)}),this.setRequestHandler(Xr,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(en,async(r,n)=>{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new P(O.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(rn,async(r,n)=>{let s=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let c;for(;c=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(c.type==="response"||c.type==="error"){let l=c.message,u=l.id,d=this._requestResolvers.get(u);if(d)if(this._requestResolvers.delete(u),c.type==="response")d(l);else{let f=l,p=new P(f.error.code,f.error.message,f.error.data);d(p)}else{let f=c.type==="response"?"Response":"Error";this._onerror(new Error(`${f} handler missing for request ${u}`))}continue}await this._transport?.send(c.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(o,n.sessionId);if(!i)throw new P(O.InvalidParams,`Task not found: ${o}`);if(!Je(i.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(Je(i.status)){let c=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...c,_meta:{...c._meta,[Ye]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(nn,async(r,n)=>{try{let{tasks:s,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:s,nextCursor:o,_meta:{}}}catch(s){throw new P(O.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(on,async(r,n)=>{try{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new P(O.InvalidParams,`Task not found: ${r.params.taskId}`);if(Je(s.status))throw new P(O.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new P(O.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof P?s:new P(O.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:s})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),P.fromError(O.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=o=>{n?.(o),this._onerror(o)};let s=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{s?.(o,i),Bt(o)||aa(o)?this._onresponse(o):ds(o)?this._onrequest(o,i):ia(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=P.fromError(O.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,o=e.params?._meta?.[Ye]?.taskId;if(n===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:O.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},s?.sessionId).catch(f=>this._onerror(new Error(`Failed to enqueue error response: ${f}`))):s?.send(d).catch(f=>this._onerror(new Error(`Failed to send an error response: ${f}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let c=na(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,u={signal:i.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async d=>{if(i.signal.aborted)return;let f={relatedRequestId:e.id};o&&(f.relatedTask={taskId:o}),await this.notification(d,f)},sendRequest:async(d,f,p)=>{if(i.signal.aborted)throw new P(O.ConnectionClosed,"Request was cancelled");let m={...p,relatedRequestId:e.id};o&&!m.relatedTask&&(m.relatedTask={taskId:o});let h=m.relatedTask?.taskId??o;return h&&l&&await l.updateTaskStatus(h,"input_required"),await this.request(d,f,m)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:o,taskStore:l,taskRequestedTtl:c?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{c&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async d=>{if(i.signal.aborted)return;let f={result:d,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:f,timestamp:Date.now()},s?.sessionId):await s?.send(f)},async d=>{if(i.signal.aborted)return;let f={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:O.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:f,timestamp:Date.now()},s?.sessionId):await s?.send(f)}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,s=Number(r),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(s),c=this._timeoutInfo.get(s);if(c&&i&&c.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(l){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),i(l);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Bt(e))n(e);else{let i=new P(e.error.code,e.error.message,e.error.data);n(i)}return}let s=this._responseHandlers.get(r);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(Bt(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let c=i.task;typeof c.taskId=="string"&&(o=!0,this._taskProgressTokens.set(c.taskId,r))}}if(o||this._progressHandlers.delete(r),Bt(e))s(e);else{let i=P.fromError(e.error.code,e.error.message,e.error.data);s(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:s}=n??{};if(!s){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof P?i:new P(O.InternalError,String(i))}}return}let o;try{let i=await this.request(e,St,n);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new P(O.InternalError,"Task creation did not return a task");for(;;){let c=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:c},Je(c.status)){c.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:c.status==="failed"?yield{type:"error",error:new P(O.InternalError,`Task ${o} failed`)}:c.status==="cancelled"&&(yield{type:"error",error:new P(O.InternalError,`Task ${o} was cancelled`)});return}if(c.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)};return}let l=c.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,l)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof P?i:new P(O.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i,task:c,relatedTask:l}=n??{};return new Promise((u,d)=>{let f=S=>{d(S)};if(!this._transport){f(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),c&&this.assertTaskCapability(e.method)}catch(S){f(S);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),c&&(m.params={...m.params,task:c}),l&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Ye]:l}});let h=S=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(S)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(A=>this._onerror(new Error(`Failed to send cancellation: ${A}`)));let w=S instanceof P?S:new P(O.RequestTimeout,String(S));d(w)};this._responseHandlers.set(p,S=>{if(!n?.signal?.aborted){if(S instanceof Error)return d(S);try{let w=Ke(r,S.result);w.success?u(w.data):d(w.error)}catch(w){d(w)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let g=n?.timeout??np,_=()=>h(P.fromError(O.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);let E=l?.taskId;if(E){let S=w=>{let A=this._responseHandlers.get(p);A?A(w):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,S),this._enqueueTaskMessage(E,{type:"request",message:m,timestamp:Date.now()}).catch(w=>{this._cleanupTimeout(p),d(w)})}else this._transport.send(m,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(S=>{this._cleanupTimeout(p),d(S)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},tn,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},sn,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},ua,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let c={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Ye]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:c,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let c={...e,jsonrpc:"2.0"};r?.relatedTask&&(c={...c,params:{...c.params,_meta:{...c.params?._meta||{},[Ye]:r.relatedTask}}}),this._transport?.send(c,r).catch(l=>this._onerror(l))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Ye]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Ps(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=$s(e,s);return Promise.resolve(r(i,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=Ps(e);this._notificationHandlers.set(n,s=>{let o=$s(e,s);return Promise.resolve(r(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,s)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let s of n)if(s.type==="request"&&ds(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new P(O.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e);s?.pollInterval&&(n=s.pollInterval)}catch{}return new Promise((s,o)=>{if(r.aborted){o(new P(O.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(i),o(new P(O.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},r)},getTask:async s=>{let o=await n.getTask(s,r);if(!o)throw new P(O.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,i)=>{await n.storeTaskResult(s,o,i,r);let c=await n.getTask(s,r);if(c){let l=tr.parse({method:"notifications/tasks/status",params:c});await this.notification(l),Je(c.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,r),updateTaskStatus:async(s,o,i)=>{let c=await n.getTask(s,r);if(!c)throw new P(O.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(Je(c.status))throw new P(O.InvalidParams,`Cannot update task "${s}" from terminal status "${c.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,o,i,r);let l=await n.getTask(s,r);if(l){let u=tr.parse({method:"notifications/tasks/status",params:l});await this.notification(u),Je(l.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}};function ga(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ya(t,e){let r={...t};for(let n in e){let s=n,o=e[s];if(o===void 0)continue;let i=r[s];ga(i)&&ga(o)?r[s]={...i,...o}:r[s]=o}return r}var nu=se(pi(),1),su=se(ru(),1);function Y_(){let t=new nu.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,su.default)(t),t}var Wn=class{constructor(e){this._ajv=e??Y_()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Vn=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let s=e.messages[e.messages.length-1],o=Array.isArray(s.content)?s.content:[s.content],i=o.some(d=>d.type==="tool_result"),c=e.messages.length>1?e.messages[e.messages.length-2]:void 0,l=c?Array.isArray(c.content)?c.content:[c.content]:[],u=l.some(d=>d.type==="tool_use");if(i){if(o.some(d=>d.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let d=new Set(l.filter(p=>p.type==="tool_use").map(p=>p.id)),f=new Set(o.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(d.size!==f.size||![...d].every(p=>f.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},or,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),s=e.mode??"form";switch(s){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let o=s==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},wt,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function ou(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function iu(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Gn=class extends cn{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(sr.options.map((n,s)=>[n,s])),this.isMessageIgnored=(n,s)=>{let o=this._loggingLevels.get(s);return o?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Wn,this.setRequestHandler(ms,n=>this._oninitialize(n)),this.setNotificationHandler(hs,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(vs,async(n,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,c=sr.safeParse(i);return c.success&&this._loggingLevels.set(o,c.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Vn(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ya(this._capabilities,e)}setRequestHandler(e,r){let s=Gr(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o;if(yt(s)){let c=s;o=c._zod?.def?.value??c.value}else{let c=s;o=c._def?.value??c.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let c=async(l,u)=>{let d=Ke(nr,l);if(!d.success){let h=d.error instanceof Error?d.error.message:String(d.error);throw new P(O.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:f}=d.data,p=await Promise.resolve(r(l,u));if(f.task){let h=Ke(St,p);if(!h.success){let g=h.error instanceof Error?h.error.message:String(h.error);throw new P(O.InvalidParams,`Invalid task creation result: ${g}`)}return h.data}let m=Ke(an,p);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new P(O.InvalidParams,`Invalid tools/call result: ${h}`)}return m.data};return super.setRequestHandler(e,c)}return super.setRequestHandler(e,r)}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})`);break;case"ping":break}}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})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}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})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){iu(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&ou(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:ea.includes(r)?r:ls,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"},Br)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],s=Array.isArray(n.content)?n.content:[n.content],o=s.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=i?Array.isArray(i.content)?i.content:[i.content]:[],l=c.some(u=>u.type==="tool_use");if(o){if(s.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let u=new Set(c.filter(f=>f.type==="tool_use").map(f=>f.id)),d=new Set(s.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(u.size!==d.size||![...u].every(f=>d.has(f)))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},ks,r):this.request({method:"sampling/createMessage",params:e},or,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let s=e;return this.request({method:"elicitation/create",params:s},wt,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let s=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:s},wt,r);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let c=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!c.valid)throw new P(O.InvalidParams,`Elicitation response content does not match requested schema: ${c.errorMessage}`)}catch(i){throw i instanceof P?i:new P(O.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}createElicitationCompletionNotifier(e,r){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}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Ts,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))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"})}};var wi=se(require("node:process"),1);var Kn=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),J_(r)}clear(){this._buffer=void 0}};function J_(t){return ca.parse(JSON.parse(t))}function au(t){return JSON.stringify(t)+`
|
|
`}var Yn=class{constructor(e=wi.default.stdin,r=wi.default.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Kn,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}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{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=au(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var Ii=se(require("path"),1);var _e={DEFAULT:3e5,HEALTH_CHECK:3e3,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5};function cu(t){return process.platform==="win32"?Math.round(t*_e.WINDOWS_MULTIPLIER):t}var Ie=require("fs"),Nr=require("path"),bi=require("os"),xe=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-sonnet-4-6",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"cli",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_GEMINI_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_GEMINI_MAX_TOKENS:"100000",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:(0,Nr.join)((0,bi.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,Nr.join)((0,bi.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static getBool(e){let r=this.get(e);return r==="true"||r===!0}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e){try{if(!(0,Ie.existsSync)(e)){let i=this.getAllDefaults();try{let c=(0,Nr.dirname)(e);(0,Ie.existsSync)(c)||(0,Ie.mkdirSync)(c,{recursive:!0}),(0,Ie.writeFileSync)(e,JSON.stringify(i,null,2),"utf-8"),console.log("[SETTINGS] Created settings file with defaults:",e)}catch(c){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,c instanceof Error?c.message:String(c))}return this.applyEnvOverrides(i)}let r=(0,Ie.readFileSync)(e,"utf-8"),n=JSON.parse(r),s=n;if(n.env&&typeof n.env=="object"){s=n.env;try{(0,Ie.writeFileSync)(e,JSON.stringify(s,null,2),"utf-8"),console.log("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(i){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,i instanceof Error?i.message:String(i))}}let o={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))s[i]!==void 0&&(o[i]=s[i]);return this.applyEnvOverrides(o)}catch(r){return console.warn("[SETTINGS] Failed to load settings, using defaults:",e,r instanceof Error?r.message:String(r)),this.applyEnvOverrides(this.getAllDefaults())}}};var F=require("path"),vi=require("os"),ki=require("fs");var lu=require("url");var eS={};function B_(){return typeof __dirname<"u"?__dirname:(0,F.dirname)((0,lu.fileURLToPath)(eS.url))}var Ak=B_();function Z_(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let t=(0,F.join)((0,vi.homedir)(),".claude-mem"),e=(0,F.join)(t,"settings.json");try{if((0,ki.existsSync)(e)){let{readFileSync:r}=require("fs"),n=JSON.parse(r(e,"utf-8")),s=n.env??n;if(s.CLAUDE_MEM_DATA_DIR)return s.CLAUDE_MEM_DATA_DIR}}catch{}return t}var De=Z_(),Jn=process.env.CLAUDE_CONFIG_DIR||(0,F.join)((0,vi.homedir)(),".claude"),uu=(0,F.join)(Jn,"plugins","marketplaces","thedotmack"),Ck=(0,F.join)(De,"archives"),Ok=(0,F.join)(De,"logs"),Ik=(0,F.join)(De,"trash"),xk=(0,F.join)(De,"backups"),Dk=(0,F.join)(De,"modes"),X_=(0,F.join)(De,"settings.json"),Nk=(0,F.join)(De,"claude-mem.db"),zk=(0,F.join)(De,"vector-db"),Q_=(0,F.join)(De,"observer-sessions"),Lk=(0,F.basename)(Q_),jk=(0,F.join)(Jn,"settings.json"),qk=(0,F.join)(Jn,"commands"),Uk=(0,F.join)(Jn,"CLAUDE.md");var ht=require("fs"),vu=require("os"),Oi=se(require("path"),1);var Ri=require("child_process"),ze=require("fs"),du=require("os"),zr=se(require("path"),1);var tS=["CLAUDECODE_","CLAUDE_CODE_"],rS=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),nS=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),sS=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"]);function Ti(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(sS.has(r)){e[r]=n;continue}rS.has(r)||nS.has(r)||tS.some(s=>r.startsWith(s))||(e[r]=n)}return e}var oS=5e3,iS=1e3,aS=zr.default.join((0,du.homedir)(),".claude-mem"),cS=zr.default.join(aS,"supervisor.json");function Ne(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(y.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return y.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}function fu(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,ze.readFileSync)(`/proc/${t}/stat`,"utf-8"),r=e.lastIndexOf(") ");if(r<0)return null;let s=e.slice(r+2).split(" ")[19];return s&&/^\d+$/.test(s)?s:null}catch(e){return y.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return null;try{let e=(0,Ri.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...process.env,LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let r=e.stdout.trim();return r.length>0?r:null}catch(e){return y.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}}function Mi(t){if(!t||!Ne(t.pid))return!1;if(!t.startToken)return!0;let e=fu(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||y.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}var $i=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=cS){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,ze.mkdirSync)(zr.default.dirname(this.registryPath),{recursive:!0}),!(0,ze.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,ze.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[s,o]of Object.entries(n))this.entries.set(s,o)}catch(r){r instanceof Error?y.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):y.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&y.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,n){this.initialize(),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize(),this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),s=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(s)?0:s)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(r=>r.pid===e)}pruneDeadEntries(){this.initialize();let e=0;for(let[r,n]of this.entries)Ne(n.pid)||(this.entries.delete(r),this.runtimeProcesses.delete(r),e+=1);return e>0&&this.persist(),e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;y.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(c=>c.pid)});let s=r.filter(c=>Ne(c.pid));for(let c of s)try{typeof c.pgid=="number"&&process.platform!=="win32"?process.kill(-c.pgid,"SIGTERM"):process.kill(c.pid,"SIGTERM")}catch(l){l instanceof Error?l.code!=="ESRCH"&&y.debug("SYSTEM",`Failed to SIGTERM session process PID ${c.pid}`,{pid:c.pid,pgid:c.pgid},l):y.warn("SYSTEM",`Failed to SIGTERM session process PID ${c.pid} (non-Error)`,{pid:c.pid,pgid:c.pgid,error:String(l)})}let o=Date.now()+oS;for(;Date.now()<o&&s.filter(l=>Ne(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100));let i=s.filter(c=>Ne(c.pid));for(let c of i){y.warn("SYSTEM",`Session process PID ${c.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:c.pid,pgid:c.pgid,sessionId:n});try{typeof c.pgid=="number"&&process.platform!=="win32"?process.kill(-c.pgid,"SIGKILL"):process.kill(c.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&y.debug("SYSTEM",`Failed to SIGKILL session process PID ${c.pid}`,{pid:c.pid,pgid:c.pgid},l):y.warn("SYSTEM",`Failed to SIGKILL session process PID ${c.pid} (non-Error)`,{pid:c.pid,pgid:c.pgid,error:String(l)})}}if(i.length>0){let c=Date.now()+iS;for(;Date.now()<c&&i.filter(u=>Ne(u.pid)).length!==0;)await new Promise(u=>setTimeout(u,100))}for(let c of r)this.entries.delete(c.id),this.runtimeProcesses.delete(c.id);return this.persist(),y.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,ze.mkdirSync)(zr.default.dirname(this.registryPath),{recursive:!0}),(0,ze.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},Pi=null;function Bn(){return Pi||(Pi=new $i),Pi}var hu=require("child_process"),gu=require("fs"),yu=require("os"),Ai=se(require("path"),1),_u=require("util");var lS=(0,_u.promisify)(hu.execFile),uS=Ai.default.join((0,yu.homedir)(),".claude-mem"),dS=Ai.default.join(uS,"worker.pid");async function Su(t){let e=t.currentPid??process.pid,r=t.pidFilePath??dS,n=t.registry.getAll(),s=[...n].filter(i=>i.pid!==e).sort((i,c)=>Date.parse(c.startedAt)-Date.parse(i.startedAt));for(let i of s){if(!Ne(i.pid)){t.registry.unregister(i.id);continue}try{await mu(i,"SIGTERM")}catch(c){c instanceof Error?y.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:i.pid,pgid:i.pgid,type:i.type},c):y.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:i.pid,pgid:i.pgid,type:i.type,error:String(c)})}}await pu(s,5e3);let o=s.filter(i=>Ne(i.pid));for(let i of o)try{await mu(i,"SIGKILL")}catch(c){c instanceof Error?y.debug("SYSTEM","Failed to force kill child process",{pid:i.pid,pgid:i.pgid,type:i.type},c):y.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:i.pid,pgid:i.pgid,type:i.type,error:String(c)})}await pu(o,1e3);for(let i of s)t.registry.unregister(i.id);for(let i of n.filter(c=>c.pid===e))t.registry.unregister(i.id);try{(0,gu.rmSync)(r,{force:!0})}catch(i){i instanceof Error?y.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:r},i):y.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:r,error:String(i)})}t.registry.pruneDeadEntries()}async function pu(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.filter(s=>Ne(s.pid)).length===0)return;await new Promise(s=>setTimeout(s,100))}}async function mu(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){try{typeof n=="number"?process.kill(-n,e):process.kill(r,e)}catch(i){if(i instanceof Error&&i.code==="ESRCH")return;throw i}return}if(e==="SIGTERM"){try{process.kill(r,e)}catch(i){if(i instanceof Error&&i.code==="ESRCH")return;throw i}return}let s=await fS();if(s){await new Promise((i,c)=>{s(r,e,l=>{if(!l){i();return}if(l.code==="ESRCH"){i();return}c(l)})});return}let o=["/PID",String(r),"/T"];e==="SIGKILL"&&o.push("/F"),await lS("taskkill",o,{timeout:_e.POWERSHELL_COMMAND,windowsHide:!0})}async function fS(){let t="tree-kill";try{let e=await import(t);return e.default??e}catch(e){return y.debug("SYSTEM","tree-kill module not available, using fallback",{},e instanceof Error?e:void 0),null}}var Eu=3e4,jt=null;function pS(){let e=Bn().pruneDeadEntries();e>0&&y.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function wu(){jt===null&&(jt=setInterval(pS,Eu),jt.unref(),y.debug("SYSTEM","Health checker started",{intervalMs:Eu}))}function bu(){jt!==null&&(clearInterval(jt),jt=null,y.debug("SYSTEM","Health checker stopped"))}var mS=Oi.default.join((0,vu.homedir)(),".claude-mem"),hS=Oi.default.join(mS,"worker.pid"),Ci=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),Zn({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,wu()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){y.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,y.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(s){s instanceof Error?y.error("SYSTEM","Error during shutdown",{},s):y.error("SYSTEM","Error during shutdown (non-Error)",{error:String(s)});try{await this.stop()}catch(o){o instanceof Error?y.debug("SYSTEM","Supervisor shutdown fallback failed",{},o):y.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(o)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{y.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}bu(),this.stopPromise=Su({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},gS=new Ci(Bn());function ku(){return gS}function Zn(t={}){let e=t.pidFilePath??hS;if(!(0,ht.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,ht.readFileSync)(e,"utf-8"))}catch(s){return s instanceof Error?y.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},s):y.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(s)}),(0,ht.rmSync)(e,{force:!0}),"invalid"}return Mi(r)&&r?((t.logAlive??!0)&&y.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(y.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,ht.rmSync)(e,{force:!0}),"stale")}var yS=(()=>{let t=process.env.CLAUDE_MEM_HEALTH_TIMEOUT_MS;if(t){let e=parseInt(t,10);if(Number.isFinite(e)&&e>=500&&e<=3e5)return e;y.warn("SYSTEM","Invalid CLAUDE_MEM_HEALTH_TIMEOUT_MS, using default",{value:t,min:500,max:3e5})}return cu(_e.HEALTH_CHECK)})();function _S(t,e={},r){return new Promise((n,s)=>{let o=setTimeout(()=>s(new Error(`Request timed out after ${r}ms`)),r);fetch(t,e).then(i=>{clearTimeout(o),n(i)},i=>{clearTimeout(o),s(i)})})}var Xn=null,Qn=null;function xi(){if(Xn!==null)return Xn;let t=Ii.default.join(xe.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),e=xe.loadFromFile(t);return Xn=parseInt(e.CLAUDE_MEM_WORKER_PORT,10),Xn}function SS(){if(Qn!==null)return Qn;let t=Ii.default.join(xe.get("CLAUDE_MEM_DATA_DIR"),"settings.json");return Qn=xe.loadFromFile(t).CLAUDE_MEM_WORKER_HOST,Qn}function ES(t){return`http://${SS()}:${xi()}${t}`}function es(t,e={}){let r=e.method??"GET",n=e.timeoutMs??yS,s=ES(t),o={method:r};return e.headers&&(o.headers=e.headers),e.body&&(o.body=e.body),n>0?_S(s,o,n):fetch(s,o)}var Li=se(require("path"),1),Se=require("fs");var Ve=se(require("path"),1),Ni=require("os"),ne=require("fs"),st=require("child_process"),Pu=require("util");var bT=(0,Pu.promisify)(st.exec),wS=Ve.default.join((0,Ni.homedir)(),".claude-mem"),qt=Ve.default.join(wS,"worker.pid");function Tu(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function bS(t,e){let r=e==="win32"?`where ${t}`:`which ${t}`,n;try{n=(0,st.execSync)(r,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(o){return o instanceof Error?y.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},o):y.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},new Error(String(o))),null}return n.split(/\r?\n/).map(o=>o.trim()).find(o=>o.length>0)||null}var Di;function vS(t={}){let e=Object.keys(t).length===0;if(e&&Di!==void 0)return Di;let r=kS(t);return e&&r!==null&&(Di=r),r}function kS(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(Tu(r))return r;let n=t.env??process.env,s=t.homeDirectory??(0,Ni.homedir)(),o=t.pathExists??ne.existsSync,i=t.lookupInPath??bS,c=e==="win32"?[n.BUN,n.BUN_PATH,Ve.default.join(s,".bun","bin","bun.exe"),Ve.default.join(s,".bun","bin","bun"),n.USERPROFILE?Ve.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?Ve.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?Ve.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[n.BUN,n.BUN_PATH,Ve.default.join(s,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let l of c){let u=l?.trim();if(u&&(Tu(u)&&o(u)||u.toLowerCase()==="bun"))return u}return i("bun",e)}function $u(){if((0,ne.existsSync)(qt))try{(0,ne.unlinkSync)(qt)}catch(t){t instanceof Error?y.warn("SYSTEM","Failed to remove PID file",{path:qt},t):y.warn("SYSTEM","Failed to remove PID file",{path:qt},new Error(String(t)))}}function Ut(t){return process.platform==="win32"?Math.round(t*2):t}function Ru(t,e,r={}){ku().assertCanSpawn("worker daemon");let n=Ti({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),s=vS();if(!s){y.error("SYSTEM","Bun runtime not found \u2014 install from https://bun.sh and ensure it is on PATH or set BUN env var. The worker daemon requires Bun because it uses bun:sqlite.");return}if(process.platform==="win32"){let d=`Start-Process -FilePath '${s.replace(/'/g,"''")}' -ArgumentList @('${t.replace(/'/g,"''")}','--daemon') -WindowStyle Hidden`,f=Buffer.from(d,"utf16le").toString("base64");try{return(0,st.execSync)(`powershell -NoProfile -EncodedCommand ${f}`,{stdio:"ignore",windowsHide:!0,env:n}),0}catch(p){y.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:s},p instanceof Error?p:new Error(String(p)));return}}let o="/usr/bin/setsid",i=(0,ne.existsSync)(o),u=(0,st.spawn)(i?o:s,i?[s,t,"--daemon"]:[t,"--daemon"],{detached:!0,stdio:"ignore",env:n});if(u.pid!==void 0)return u.unref(),u.pid}function Mu(){try{if(!(0,ne.existsSync)(qt))return;let t=new Date;(0,ne.utimesSync)(qt,t,t)}catch{}}function Au(){return Zn({logAlive:!1})}var Cu=se(require("net"),1);async function TS(t,e,r="GET"){let n=await fetch(`http://127.0.0.1:${t}${e}`,{method:r}),s="";try{s=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:s}}async function Ou(t){if(process.platform==="win32")try{return(await fetch(`http://127.0.0.1:${t}/api/health`)).ok}catch(e){return e instanceof Error?y.debug("SYSTEM","Windows health check failed (port not in use)",{},e):y.debug("SYSTEM","Windows health check failed (port not in use)",{error:String(e)}),!1}return new Promise(e=>{let r=Cu.default.createServer();r.once("error",n=>{n.code==="EADDRINUSE"?e(!0):e(!1)}),r.once("listening",()=>{r.close(()=>e(!1))}),r.listen(t,"127.0.0.1")})}async function Iu(t,e,r,n){let s=Date.now();for(;Date.now()-s<r;){try{if((await TS(t,e)).ok)return!0}catch(o){o instanceof Error?y.debug("SYSTEM",n,{},o):y.debug("SYSTEM",n,{error:String(o)})}await new Promise(o=>setTimeout(o,500))}return!1}function Lr(t,e=3e4){return Iu(t,"/api/health",e,"Service not ready yet, will retry")}function zi(t,e=3e4){return Iu(t,"/api/readiness",e,"Worker not ready yet, will retry")}var PS=120*1e3;function ji(){return Li.default.join(xe.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function $S(){if(process.platform!=="win32")return!1;let t=ji();if(!(0,Se.existsSync)(t))return!1;try{let e=(0,Se.statSync)(t).mtimeMs;return Date.now()-e<PS}catch(e){return e instanceof Error?y.debug("SYSTEM","Could not stat worker spawn lock file",{},e):y.debug("SYSTEM","Could not stat worker spawn lock file",{error:String(e)}),!1}}function RS(){if(process.platform==="win32")try{let t=ji();(0,Se.mkdirSync)(Li.default.dirname(t),{recursive:!0}),(0,Se.writeFileSync)(t,"","utf-8")}catch{}}function ts(){if(process.platform==="win32")try{let t=ji();(0,Se.existsSync)(t)&&(0,Se.unlinkSync)(t)}catch{}}async function xu(t,e){return e?(0,Se.existsSync)(e)?Au()==="alive"?(y.info("SYSTEM","Worker PID file points to a live process, skipping duplicate spawn"),await Lr(t,Ut(_e.PORT_IN_USE_WAIT))?(ts(),y.info("SYSTEM","Worker became healthy while waiting on live PID"),!0):(y.warn("SYSTEM","Live PID detected but worker did not become healthy before timeout"),!1)):await Lr(t,1e3)?(ts(),await zi(t,Ut(_e.READINESS_WAIT))||y.warn("SYSTEM","Worker is alive but readiness timed out \u2014 proceeding anyway"),y.info("SYSTEM","Worker already running and healthy"),!0):await Ou(t)?(y.info("SYSTEM","Port in use, waiting for worker to become healthy"),await Lr(t,Ut(_e.PORT_IN_USE_WAIT))?(ts(),y.info("SYSTEM","Worker is now healthy"),!0):(y.error("SYSTEM","Port in use but worker not responding to health checks"),!1)):$S()?(y.warn("SYSTEM","Worker unavailable on Windows \u2014 skipping spawn (recent attempt failed within cooldown)"),!1):(y.info("SYSTEM","Starting worker daemon",{workerScriptPath:e}),RS(),Ru(e,t)===void 0?(y.error("SYSTEM","Failed to spawn worker daemon"),!1):await Lr(t,Ut(_e.POST_SPAWN_WAIT))?(await zi(t,Ut(_e.READINESS_WAIT))||y.warn("SYSTEM","Worker is alive but readiness timed out \u2014 proceeding anyway"),ts(),Mu(),y.info("SYSTEM","Worker started successfully"),!0):($u(),y.error("SYSTEM","Worker failed to start (health check timeout)"),!1)):(y.error("SYSTEM","ensureWorkerStarted: worker script not found at expected path \u2014 likely a partial install or build artifact missing",{workerScriptPath:e}),!1):(y.error("SYSTEM","ensureWorkerStarted called with empty workerScriptPath \u2014 caller bug"),!1)}var Wt=require("node:fs/promises"),Fr=require("node:path");var zu=require("node:child_process"),ee=require("node:fs"),B=require("node:path"),Vi=require("node:os"),Fi=require("node:module");var FS={},Hi=typeof __filename<"u"?(0,Fi.createRequire)(__filename):(0,Fi.createRequire)(FS.url),Wi={".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"tsx",".ts":"typescript",".tsx":"tsx",".py":"python",".pyw":"python",".go":"go",".rs":"rust",".rb":"ruby",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".kt":"kotlin",".kts":"kotlin",".swift":"swift",".php":"php",".ex":"elixir",".exs":"elixir",".lua":"lua",".scala":"scala",".sc":"scala",".sh":"bash",".bash":"bash",".zsh":"bash",".hs":"haskell",".zig":"zig",".css":"css",".scss":"scss",".toml":"toml",".yml":"yaml",".yaml":"yaml",".sql":"sql",".md":"markdown",".mdx":"markdown"};function Lu(t,e){let r=t.slice(t.lastIndexOf("."));return Wi[r]?Wi[r]:e.extensionToLanguage[r]?e.extensionToLanguage[r]:"unknown"}function ju(t,e){return e.languageToQueryKey[t]?e.languageToQueryKey[t]:CS(t)}var jr=new Map,Ft={grammars:{},extensionToLanguage:{},languageToQueryKey:{}};function Ur(t){if(jr.has(t))return jr.get(t);let e=(0,B.join)(t,".claude-mem.json"),r;try{let o=(0,ee.readFileSync)(e,"utf-8");r=JSON.parse(o)}catch{return jr.set(t,Ft),Ft}let n=r.grammars;if(!n||typeof n!="object"||Array.isArray(n))return jr.set(t,Ft),Ft;let s={grammars:{},extensionToLanguage:{},languageToQueryKey:{}};for(let[o,i]of Object.entries(n)){if(qu[o]||!i||typeof i!="object"||Array.isArray(i))continue;let c=i,l=c.package,u=c.extensions,d=c.query;if(!(typeof l!="string"||!Array.isArray(u))&&u.every(f=>typeof f=="string")){s.grammars[o]={package:l,extensions:u,query:typeof d=="string"?d:void 0};for(let f of u)Wi[f]||(s.extensionToLanguage[f]=o);if(typeof d=="string"){let f=(0,B.join)(t,d);try{let p=(0,ee.readFileSync)(f,"utf-8"),m=`user_${o}`;Fu[m]=p,s.languageToQueryKey[o]=m}catch{console.error(`[smart-file-read] Custom query file not found: ${f}, falling back to generic`),s.languageToQueryKey[o]="generic"}}else s.languageToQueryKey[o]="generic"}}return jr.set(t,s),s}var qu={javascript:"tree-sitter-javascript",typescript:"tree-sitter-typescript/typescript",tsx:"tree-sitter-typescript/tsx",python:"tree-sitter-python",go:"tree-sitter-go",rust:"tree-sitter-rust",ruby:"tree-sitter-ruby",java:"tree-sitter-java",c:"tree-sitter-c",cpp:"tree-sitter-cpp",kotlin:"tree-sitter-kotlin",swift:"tree-sitter-swift",php:"tree-sitter-php/php",elixir:"tree-sitter-elixir",lua:"@tree-sitter-grammars/tree-sitter-lua",scala:"tree-sitter-scala",bash:"tree-sitter-bash",haskell:"tree-sitter-haskell",zig:"@tree-sitter-grammars/tree-sitter-zig",css:"tree-sitter-css",scss:"tree-sitter-scss",toml:"@tree-sitter-grammars/tree-sitter-toml",yaml:"@tree-sitter-grammars/tree-sitter-yaml",sql:"@derekstride/tree-sitter-sql",markdown:"@tree-sitter-grammars/tree-sitter-markdown"},MS={markdown:"tree-sitter-markdown"};function AS(t){let e=qu[t];if(!e)return null;let r=MS[t];if(r){try{let n=Hi.resolve(e+"/package.json"),s=(0,B.join)((0,B.dirname)(n),r);if((0,ee.existsSync)((0,B.join)(s,"src")))return s}catch{}return null}try{let n=Hi.resolve(e+"/package.json");return(0,B.dirname)(n)}catch{return null}}function Uu(t,e){let r=AS(t);if(r)return r;if(!e)return null;let s=Ur(e).grammars[t];if(!s)return null;try{let o=(0,B.join)(e,"node_modules",s.package,"package.json");if((0,ee.existsSync)(o)){let i=(0,B.dirname)(o);if((0,ee.existsSync)((0,B.join)(i,"src")))return i}}catch{}return console.error(`[smart-file-read] Grammar package not found for "${t}": ${s.package} (install it in your project's node_modules)`),null}var Fu={jsts:`
|
|
(function_declaration name: (identifier) @name) @func
|
|
(lexical_declaration (variable_declarator name: (identifier) @name value: [(arrow_function) (function_expression)])) @const_func
|
|
(class_declaration name: (type_identifier) @name) @cls
|
|
(method_definition name: (property_identifier) @name) @method
|
|
(interface_declaration name: (type_identifier) @name) @iface
|
|
(type_alias_declaration name: (type_identifier) @name) @tdef
|
|
(enum_declaration name: (identifier) @name) @enm
|
|
(import_statement) @imp
|
|
(export_statement) @exp
|
|
`,python:`
|
|
(function_definition name: (identifier) @name) @func
|
|
(class_definition name: (identifier) @name) @cls
|
|
(import_statement) @imp
|
|
(import_from_statement) @imp
|
|
`,go:`
|
|
(function_declaration name: (identifier) @name) @func
|
|
(method_declaration name: (field_identifier) @name) @method
|
|
(type_declaration (type_spec name: (type_identifier) @name)) @tdef
|
|
(import_declaration) @imp
|
|
`,rust:`
|
|
(function_item name: (identifier) @name) @func
|
|
(struct_item name: (type_identifier) @name) @struct_def
|
|
(enum_item name: (type_identifier) @name) @enm
|
|
(trait_item name: (type_identifier) @name) @trait_def
|
|
(impl_item type: (type_identifier) @name) @impl_def
|
|
(use_declaration) @imp
|
|
`,ruby:`
|
|
(method name: (identifier) @name) @func
|
|
(class name: (constant) @name) @cls
|
|
(module name: (constant) @name) @cls
|
|
(call method: (identifier) @name) @imp
|
|
`,java:`
|
|
(method_declaration name: (identifier) @name) @method
|
|
(class_declaration name: (identifier) @name) @cls
|
|
(interface_declaration name: (identifier) @name) @iface
|
|
(enum_declaration name: (identifier) @name) @enm
|
|
(import_declaration) @imp
|
|
`,kotlin:`
|
|
(function_declaration (simple_identifier) @name) @func
|
|
(class_declaration (type_identifier) @name) @cls
|
|
(object_declaration (type_identifier) @name) @cls
|
|
(import_header) @imp
|
|
`,swift:`
|
|
(function_declaration name: (simple_identifier) @name) @func
|
|
(class_declaration name: (type_identifier) @name) @cls
|
|
(protocol_declaration name: (type_identifier) @name) @iface
|
|
(import_declaration) @imp
|
|
`,php:`
|
|
(function_definition name: (name) @name) @func
|
|
(class_declaration name: (name) @name) @cls
|
|
(interface_declaration name: (name) @name) @iface
|
|
(trait_declaration name: (name) @name) @trait_def
|
|
(method_declaration name: (name) @name) @method
|
|
(namespace_use_declaration) @imp
|
|
`,lua:`
|
|
(function_declaration name: (identifier) @name) @func
|
|
(function_declaration name: (dot_index_expression) @name) @func
|
|
(function_declaration name: (method_index_expression) @name) @func
|
|
`,scala:`
|
|
(function_definition name: (identifier) @name) @func
|
|
(class_definition name: (identifier) @name) @cls
|
|
(object_definition name: (identifier) @name) @cls
|
|
(trait_definition name: (identifier) @name) @trait_def
|
|
(import_declaration) @imp
|
|
`,bash:`
|
|
(function_definition name: (word) @name) @func
|
|
`,haskell:`
|
|
(function name: (variable) @name) @func
|
|
(type_synomym name: (name) @name) @tdef
|
|
(newtype name: (name) @name) @tdef
|
|
(data_type name: (name) @name) @tdef
|
|
(class name: (name) @name) @cls
|
|
(import) @imp
|
|
`,zig:`
|
|
(function_declaration name: (identifier) @name) @func
|
|
(test_declaration) @func
|
|
`,css:`
|
|
(rule_set (selectors) @name) @func
|
|
(media_statement) @cls
|
|
(keyframes_statement (keyframes_name) @name) @cls
|
|
(import_statement) @imp
|
|
`,scss:`
|
|
(rule_set (selectors) @name) @func
|
|
(media_statement) @cls
|
|
(keyframes_statement (keyframes_name) @name) @cls
|
|
(import_statement) @imp
|
|
(mixin_statement name: (identifier) @name) @mixin_def
|
|
(function_statement name: (identifier) @name) @func
|
|
(include_statement) @imp
|
|
`,toml:`
|
|
(table (bare_key) @name) @cls
|
|
(table (dotted_key) @name) @cls
|
|
(table_array_element (bare_key) @name) @cls
|
|
(table_array_element (dotted_key) @name) @cls
|
|
`,yaml:`
|
|
(block_mapping_pair key: (flow_node) @name) @func
|
|
`,sql:`
|
|
(create_table (object_reference) @name) @cls
|
|
(create_function (object_reference) @name) @func
|
|
(create_view (object_reference) @name) @cls
|
|
`,markdown:`
|
|
(atx_heading heading_content: (inline) @name) @heading
|
|
(setext_heading heading_content: (paragraph) @name) @heading
|
|
(fenced_code_block (info_string (language) @name)) @code_block
|
|
(fenced_code_block) @code_block
|
|
(minus_metadata) @frontmatter
|
|
(link_reference_definition (link_label) @name) @ref
|
|
`,generic:`
|
|
(function_declaration name: (identifier) @name) @func
|
|
(function_definition name: (identifier) @name) @func
|
|
(class_declaration name: (identifier) @name) @cls
|
|
(class_definition name: (identifier) @name) @cls
|
|
(import_statement) @imp
|
|
(import_declaration) @imp
|
|
`};function CS(t){switch(t){case"javascript":case"typescript":case"tsx":return"jsts";case"python":return"python";case"go":return"go";case"rust":return"rust";case"ruby":return"ruby";case"java":return"java";case"kotlin":return"kotlin";case"swift":return"swift";case"php":return"php";case"elixir":return"generic";case"lua":return"lua";case"scala":return"scala";case"bash":return"bash";case"haskell":return"haskell";case"zig":return"zig";case"css":return"css";case"scss":return"scss";case"toml":return"toml";case"yaml":return"yaml";case"sql":return"sql";case"markdown":return"markdown";default:return"generic"}}var qi=null,Ui=new Map;function Hu(t){if(Ui.has(t))return Ui.get(t);qi||(qi=(0,ee.mkdtempSync)((0,B.join)((0,Vi.tmpdir)(),"smart-read-queries-")));let e=(0,B.join)(qi,`${t}.scm`);return(0,ee.writeFileSync)(e,Fu[t]),Ui.set(t,e),e}var qr=null;function OS(){if(qr)return qr;try{let t=Hi.resolve("tree-sitter-cli/package.json"),e=(0,B.join)((0,B.dirname)(t),"tree-sitter");if((0,ee.existsSync)(e))return qr=e,e}catch{}return qr="tree-sitter",qr}function IS(t,e,r){return Wu(t,[e],r).get(e)||[]}function Wu(t,e,r){if(e.length===0)return new Map;let n=OS(),s=["query","-p",r,t,...e],o;try{o=(0,zu.execFileSync)(n,s,{encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]})}catch(i){return y.debug("WORKER",`tree-sitter query failed for ${e.length} file(s)`,void 0,i instanceof Error?i:void 0),new Map}return xS(o)}function xS(t){let e=new Map,r=null,n=null;for(let s of t.split(`
|
|
`)){if(s.length>0&&!s.startsWith(" ")&&!s.startsWith(" ")){r=s.trim(),e.has(r)||e.set(r,[]),n=null;continue}if(!r)continue;let o=s.match(/^\s+pattern:\s+(\d+)/);if(o){n={pattern:parseInt(o[1]),captures:[]},e.get(r).push(n);continue}let i=s.match(/^\s+capture:\s+(?:\d+\s*-\s*)?(\w+),\s*start:\s*\((\d+),\s*(\d+)\),\s*end:\s*\((\d+),\s*(\d+)\)(?:,\s*text:\s*`([^`]*)`)?/);i&&n&&n.captures.push({tag:i[1],startRow:parseInt(i[2]),startCol:parseInt(i[3]),endRow:parseInt(i[4]),endCol:parseInt(i[5]),text:i[6]})}return e}var Du={func:"function",const_func:"function",cls:"class",method:"method",iface:"interface",tdef:"type",enm:"enum",struct_def:"struct",trait_def:"trait",impl_def:"impl",mixin_def:"mixin",heading:"section",code_block:"code",frontmatter:"metadata",ref:"reference"},DS=new Set(["class","struct","impl","trait"]);function NS(t,e,r,n=200){let o=t[e]||"";if(!o.trimEnd().endsWith("{")&&!o.trimEnd().endsWith(":")){let i=t.slice(e,Math.min(e+10,r+1)).join(`
|
|
`),c=i.indexOf("{");c!==-1&&c<500&&(o=i.slice(0,c).replace(/\n/g," ").replace(/\s+/g," ").trim())}return o=o.replace(/\s*[{:]\s*$/,"").trim(),o.length>n&&(o=o.slice(0,n-3)+"..."),o}function zS(t,e){let r=[],n=!1;for(let s=e-1;s>=0;s--){let o=t[s].trim();if(o===""){if(n)break;continue}if(o.startsWith("/**")||o.startsWith("*")||o.startsWith("*/")||o.startsWith("//")||o.startsWith("///")||o.startsWith("//!")||o.startsWith("#")||o.startsWith("@"))r.unshift(t[s]),n=!0;else break}return r.length>0?r.join(`
|
|
`).trim():void 0}function LS(t,e,r){for(let n=e+1;n<=Math.min(e+3,r);n++){let s=t[n]?.trim();if(s){if(s.startsWith('"""')||s.startsWith("'''"))return s;break}}}function jS(t,e,r,n,s,o){switch(o){case"javascript":case"typescript":case"tsx":return n.some(i=>e>=i.startRow&&r<=i.endRow);case"python":return!t.startsWith("_");case"go":return t.length>0&&t[0]===t[0].toUpperCase()&&t[0]!==t[0].toLowerCase();case"rust":return s[e]?.trimStart().startsWith("pub")??!1;default:return!0}}function Vu(t,e,r){let n=[],s=[],o=[],i=[];for(let l of t)for(let u of l.captures)u.tag==="exp"&&o.push({startRow:u.startRow,endRow:u.endRow}),u.tag==="imp"&&s.push(u.text||e[u.startRow]?.trim()||"");for(let l of t){let u=l.captures.find(w=>Du[w.tag]),d=l.captures.find(w=>w.tag==="name");if(!u)continue;let f=u.startRow,p=u.endRow,m=Du[u.tag],h=d?.text||"anonymous",g;if(r==="markdown"&&m==="section"){let A=(e[f]||"").match(/^(#{1,6})\s/),k=A?A[1].length:1;g=`${"#".repeat(k)} ${h}`}else if(r==="markdown"&&m==="code"){let w=h!=="anonymous"?h:"";g=w?"```"+w:"```"}else r==="markdown"&&m==="metadata"?g="---frontmatter---":r==="markdown"&&m==="reference"?g=e[f]?.trim()||h:g=NS(e,f,p);let _=r==="markdown"?void 0:zS(e,f),E=r==="python"?LS(e,f,p):void 0,S={name:h,kind:m,signature:g,jsdoc:_||E,lineStart:f,lineEnd:p,exported:jS(h,f,p,o,e,r)};DS.has(m)&&(S.children=[],i.push({sym:S,startRow:f,endRow:p})),n.push(S)}if(r==="markdown"){let l=new Map,u=new Set;for(let d of n){if(d.kind!=="code")continue;let f=`${d.lineStart}:${d.lineEnd}`,p=l.get(f);p?d.name!=="anonymous"?(u.add(p),l.set(f,d)):u.add(d):l.set(f,d)}if(u.size>0){let d=n.filter(f=>!u.has(f));n.length=0,n.push(...d)}}let c=new Set;for(let l of i)for(let u of n)u!==l.sym&&u.lineStart>l.startRow&&u.lineEnd<=l.endRow&&(u.kind==="function"&&(u.kind="method"),l.sym.children.push(u),c.add(u));return{symbols:n.filter(l=>!c.has(l)),imports:s}}function rs(t,e,r){let n=r?Ur(r):Ft,s=Lu(e,n),o=t.split(`
|
|
`),i=Uu(s,r);if(!i)return{filePath:e,language:s,symbols:[],imports:[],totalLines:o.length,foldedTokenEstimate:50};let c=ju(s,n),l=Hu(c),u=e.slice(e.lastIndexOf("."))||".txt",d=(0,ee.mkdtempSync)((0,B.join)((0,Vi.tmpdir)(),"smart-src-")),f=(0,B.join)(d,`source${u}`);(0,ee.writeFileSync)(f,t);try{let p=IS(l,f,i),m=Vu(p,o,s),h=Ht({filePath:e,language:s,symbols:m.symbols,imports:m.imports,totalLines:o.length,foldedTokenEstimate:0});return{filePath:e,language:s,symbols:m.symbols,imports:m.imports,totalLines:o.length,foldedTokenEstimate:Math.ceil(h.length/4)}}finally{(0,ee.rmSync)(d,{recursive:!0,force:!0})}}function Gu(t,e){let r=new Map,n=e?Ur(e):Ft,s=new Map;for(let o of t){let i=Lu(o.relativePath,n);s.has(i)||s.set(i,[]),s.get(i).push(o)}for(let[o,i]of s){let c=Uu(o,e);if(!c){for(let p of i){let m=p.content.split(`
|
|
`);r.set(p.relativePath,{filePath:p.relativePath,language:o,symbols:[],imports:[],totalLines:m.length,foldedTokenEstimate:50})}continue}let l=ju(o,n),u=Hu(l),d=i.map(p=>p.absolutePath),f=Wu(u,d,c);for(let p of i){let m=p.content.split(`
|
|
`),h=f.get(p.absolutePath)||[],g=Vu(h,m,o),_=Ht({filePath:p.relativePath,language:o,symbols:g.symbols,imports:g.imports,totalLines:m.length,foldedTokenEstimate:0});r.set(p.relativePath,{filePath:p.relativePath,language:o,symbols:g.symbols,imports:g.imports,totalLines:m.length,foldedTokenEstimate:Math.ceil(_.length/4)})}}return r}function Ht(t){if(t.language==="markdown")return qS(t);let e=[];if(e.push(`\u{1F4C1} ${t.filePath} (${t.language}, ${t.totalLines} lines)`),e.push(""),t.imports.length>0){e.push(` \u{1F4E6} Imports: ${t.imports.length} statements`);for(let r of t.imports.slice(0,10))e.push(` ${r}`);t.imports.length>10&&e.push(` ... +${t.imports.length-10} more`),e.push("")}for(let r of t.symbols)e.push(Ku(r," "));return e.join(`
|
|
`)}function qS(t){let e=[];e.push(`\u{1F4C4} ${t.filePath} (${t.language}, ${t.totalLines} lines)`);for(let n of t.symbols)if(n.kind==="section"){let s=n.signature.match(/^(#{1,6})\s/),o=s?s[1].length:1,i=" ".repeat(o),c=`L${n.lineStart+1}`,l=`${i}${n.signature}`;e.push(`${l.padEnd(56)}${c}`)}else if(n.kind==="code"){let s=Nu(t.symbols,n.lineStart),o=" ".repeat(s+1),i=n.lineStart===n.lineEnd?`L${n.lineStart+1}`:`L${n.lineStart+1}-${n.lineEnd+1}`,c=`${o}${n.signature}`;e.push(`${c.padEnd(56)}${i}`)}else if(n.kind==="metadata"){let s=n.lineStart===n.lineEnd?`L${n.lineStart+1}`:`L${n.lineStart+1}-${n.lineEnd+1}`,o=` ${n.signature}`;e.push(`${o.padEnd(56)}${s}`)}else if(n.kind==="reference"){let s=Nu(t.symbols,n.lineStart),o=" ".repeat(s+1),i=`L${n.lineStart+1}`,c=`${o}\u2197 ${n.name}`;e.push(`${c.padEnd(56)}${i}`)}return e.join(`
|
|
`)}function Nu(t,e){let r=0;for(let n of t)if(n.kind==="section"&&n.lineStart<e){let s=n.signature.match(/^(#{1,6})\s/);r=s?s[1].length:1}return r}function Ku(t,e){let r=[],n=US(t.kind),s=t.exported?" [exported]":"",o=t.lineStart===t.lineEnd?`L${t.lineStart+1}`:`L${t.lineStart+1}-${t.lineEnd+1}`;if(r.push(`${e}${n} ${t.name}${s} (${o})`),r.push(`${e} ${t.signature}`),t.jsdoc){let c=t.jsdoc.split(`
|
|
`).find(l=>{let u=l.replace(/^[\s*/]+/,"").replace(/^['"`]{3}/,"").trim();return u.length>0&&!u.startsWith("/**")});if(c){let l=c.replace(/^[\s*/]+/,"").replace(/^['"`]{3}/,"").replace(/['"`]{3}$/,"").trim();l&&r.push(`${e} \u{1F4AC} ${l}`)}}if(t.children&&t.children.length>0)for(let i of t.children)r.push(Ku(i,e+" "));return r.join(`
|
|
`)}function US(t){return{function:"\u0192",method:"\u0192",class:"\u25C6",interface:"\u25C7",type:"\u25C7",const:"\u25CF",variable:"\u25CB",export:"\u2192",struct:"\u25C6",enum:"\u25A3",trait:"\u25C7",impl:"\u25C8",property:"\u25CB",getter:"\u21E2",setter:"\u21E0",mixin:"\u25C8",section:"\xA7",code:"\u2318",metadata:"\u25CA",reference:"\u2197"}[t]||"\xB7"}function Yu(t,e,r){let n=rs(t,e),s=u=>{for(let d of u){if(d.name===r)return d;if(d.children){let f=s(d.children);if(f)return f}}return null},o=s(n.symbols);if(!o)return null;let i=t.split(`
|
|
`);if(n.language==="markdown"&&o.kind==="section"){let u=o.signature.match(/^(#{1,6})\s/),d=u?u[1].length:1,f=o.lineStart,p=i.length-1;for(let h of n.symbols)if(h.kind==="section"&&h.lineStart>f){let g=h.signature.match(/^(#{1,6})\s/);if((g?g[1].length:1)<=d){for(p=h.lineStart-1;p>f&&i[p].trim()==="";)p--;break}}let m=i.slice(f,p+1).join(`
|
|
`);return`<!-- \u{1F4CD} ${e} L${f+1}-${p+1} -->
|
|
${m}`}let c=o.lineStart;for(let u=o.lineStart-1;u>=0;u--){let d=i[u].trim();if(d===""||d.startsWith("*")||d.startsWith("/**")||d.startsWith("///")||d.startsWith("//")||d.startsWith("#")||d.startsWith("@")||d==="*/")c=u;else break}let l=i.slice(c,o.lineEnd+1).join(`
|
|
`);return`// \u{1F4CD} ${e} L${c+1}-${o.lineEnd+1}
|
|
${l}`}var Ju=new Set([".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".pyw",".go",".rs",".rb",".java",".cs",".cpp",".cc",".cxx",".c",".h",".hpp",".hh",".swift",".kt",".kts",".php",".vue",".svelte",".ex",".exs",".lua",".scala",".sc",".sh",".bash",".zsh",".hs",".zig",".css",".scss",".toml",".yml",".yaml",".sql",".md",".mdx"]),HS=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),WS=512*1024;async function*Bu(t,e,r=20,n){if(r<=0)return;let s;try{s=await(0,Wt.readdir)(t,{withFileTypes:!0})}catch(o){y.debug("WORKER",`walkDir: failed to read directory ${t}`,void 0,o instanceof Error?o:void 0);return}for(let o of s){if(o.name.startsWith(".")&&o.name!=="."||HS.has(o.name))continue;let i=(0,Fr.join)(t,o.name);if(o.isDirectory())yield*Bu(i,e,r-1,n);else if(o.isFile()){let c=o.name.slice(o.name.lastIndexOf("."));(Ju.has(c)||n&&n.has(c))&&(yield i)}}}async function VS(t){try{let e=await(0,Wt.stat)(t);if(e.size>WS||e.size===0)return null;let r=await(0,Wt.readFile)(t,"utf-8");return r.slice(0,1e3).includes("\0")?null:r}catch(e){return y.debug("WORKER",`safeReadFile: failed to read ${t}`,void 0,e instanceof Error?e:void 0),null}}async function Zu(t,e,r={}){let n=r.maxResults||20,s=e.toLowerCase(),o=s.split(/[\s_\-./]+/).filter(S=>S.length>0),i=r.projectRoot||t,c=Ur(i),l=new Set;for(let S of Object.values(c.grammars))for(let w of S.extensions)Ju.has(w)||l.add(w);let u=[];for await(let S of Bu(t,t,20,l.size>0?l:void 0)){if(r.filePattern&&!(0,Fr.relative)(t,S).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let w=await VS(S);w&&u.push({absolutePath:S,relativePath:(0,Fr.relative)(t,S),content:w})}let d=Gu(u,i),f=[],p=[],m=0;for(let[S,w]of d){m+=GS(w);let k=ns(S.toLowerCase(),o)>0,le=[],de=(Gt,gt)=>{for(let H of Gt){let Ge=0,Ee="",Kt=ns(H.name.toLowerCase(),o);Kt>0&&(Ge+=Kt*3,Ee="name match"),H.signature.toLowerCase().includes(s)&&(Ge+=2,Ee=Ee?`${Ee} + signature`:"signature match"),H.jsdoc&&H.jsdoc.toLowerCase().includes(s)&&(Ge+=1,Ee=Ee?`${Ee} + jsdoc`:"jsdoc match"),Ge>0&&(k=!0,le.push({filePath:S,symbolName:gt?`${gt}.${H.name}`:H.name,kind:H.kind,signature:H.signature,jsdoc:H.jsdoc,lineStart:H.lineStart,lineEnd:H.lineEnd,matchReason:Ee})),H.children&&de(H.children,H.name)}};de(w.symbols),k&&(f.push(w),p.push(...le))}p.sort((S,w)=>{let A=ns(S.symbolName.toLowerCase(),o);return ns(w.symbolName.toLowerCase(),o)-A});let h=p.slice(0,n),g=new Set(h.map(S=>S.filePath)),_=f.filter(S=>g.has(S.filePath)).slice(0,n),E=_.reduce((S,w)=>S+w.foldedTokenEstimate,0);return{foldedFiles:_,matchingSymbols:h,totalFilesScanned:u.length,totalSymbolsFound:m,tokenEstimate:E}}function ns(t,e){let r=0;for(let n of e)if(t===n)r+=10;else if(t.includes(n))r+=5;else{let s=0,o=0;for(let i of n){let c=t.indexOf(i,s);c!==-1&&(o++,s=c+1)}o===n.length&&(r+=1)}return r}function GS(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function Xu(t,e){let r=[];if(r.push(`\u{1F50D} Smart Search: "${e}"`),r.push(` Scanned ${t.totalFilesScanned} files, found ${t.totalSymbolsFound} symbols`),r.push(` ${t.matchingSymbols.length} matches across ${t.foldedFiles.length} files (~${t.tokenEstimate} tokens for folded view)`),r.push(""),t.matchingSymbols.length===0)return r.push(" No matching symbols found."),r.join(`
|
|
`);r.push("\u2500\u2500 Matching Symbols \u2500\u2500"),r.push("");for(let n of t.matchingSymbols){if(r.push(` ${n.kind} ${n.symbolName} (${n.filePath}:${n.lineStart+1})`),r.push(` ${n.signature}`),n.jsdoc){let s=n.jsdoc.split(`
|
|
`).find(o=>o.replace(/^[\s*/]+/,"").trim().length>0);s&&r.push(` \u{1F4AC} ${s.replace(/^[\s*/]+/,"").trim()}`)}r.push("")}r.push("\u2500\u2500 Folded File Views \u2500\u2500"),r.push("");for(let n of t.foldedFiles)r.push(Ht(n)),r.push("");return r.push("\u2500\u2500 Actions \u2500\u2500"),r.push(" To see full implementation: use smart_unfold with file path and symbol name"),r.join(`
|
|
`)}var Ki=require("node:fs/promises"),ss=require("node:fs"),Pe=require("node:path"),td=require("node:os"),rd=require("node:url"),sE={},KS="12.4.8";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var nd=!1,sd=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,Pe.dirname)((0,rd.fileURLToPath)(sE.url))}catch{return nd=!0,process.cwd()}})(),Yi=(0,Pe.resolve)(sd,"worker-service.cjs");function YS(){nd&&((0,ss.existsSync)(Yi)||y.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:Yi,mcpServerDir:sd}))}var Qu={search:"/api/search",timeline:"/api/timeline"};async function Gi(t,e){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});let r=new URLSearchParams;for(let[s,o]of Object.entries(e))o!=null&&r.append(s,String(o));let n=`${t}?${r}`;try{let s=await es(n);if(!s.ok){let i=await s.text();throw new Error(`Worker API error (${s.status}): ${i}`)}let o=await s.json();return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),o}catch(s){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},s instanceof Error?s:new Error(String(s))),{content:[{type:"text",text:`Error calling Worker API: ${s instanceof Error?s.message:String(s)}`}],isError:!0}}}async function JS(t,e){let r=await es(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let s=await r.text();throw new Error(`Worker API error (${r.status}): ${s}`)}let n=await r.json();return y.debug("HTTP","Worker API success (POST)",void 0,{endpoint:t}),{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}async function Vt(t,e){y.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{return await JS(t,e)}catch(r){return y.error("HTTP","Worker API error (POST)",{endpoint:t},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function BS(){try{return(await es("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}async function ZS(){if(await BS())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),YS();try{let t=xi(),e=await xu(t,Yi);return e||y.error("SYSTEM","Worker auto-start returned false \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),e}catch(t){return y.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,t instanceof Error?t:new Error(String(t))),!1}}var od=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
|
|
1. search(query) \u2192 Get index with IDs (~50-100 tokens/result)
|
|
2. timeline(anchor=ID) \u2192 Get context around interesting results
|
|
3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs
|
|
NEVER fetch full details without filtering first. 10x token savings.`,inputSchema:{type:"object",properties:{}},handler:async()=>({content:[{type:"text",text:`# Memory Search Workflow
|
|
|
|
**3-Layer Pattern (ALWAYS follow this):**
|
|
|
|
1. **Search** - Get index of results with IDs
|
|
\`search(query="...", limit=20, project="...")\`
|
|
Returns: Table with IDs, titles, dates (~50-100 tokens/result)
|
|
|
|
2. **Timeline** - Get context around interesting results
|
|
\`timeline(anchor=<ID>, depth_before=3, depth_after=3)\`
|
|
Returns: Chronological context showing what was happening
|
|
|
|
3. **Fetch** - Get full details ONLY for relevant IDs
|
|
\`get_observations(ids=[...])\` # ALWAYS batch for 2+ items
|
|
Returns: Complete details (~500-1000 tokens/result)
|
|
|
|
**Why:** 10x token savings. Never fetch full details without filtering first.`}]})},{name:"search",description:"Step 1: Search memory. Returns index with IDs. Params: query, limit, project, type, obs_type, dateStart, dateEnd, offset, orderBy",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query"},limit:{type:"number",description:"Max results (default 20)"},project:{type:"string",description:"Filter by project name"},type:{type:"string",description:"Filter by observation type"},obs_type:{type:"string",description:"Filter by obs_type field"},dateStart:{type:"string",description:"Start date filter (ISO)"},dateEnd:{type:"string",description:"End date filter (ISO)"},offset:{type:"number",description:"Pagination offset"},orderBy:{type:"string",description:"Sort order: date_desc or date_asc"}},additionalProperties:!0},handler:async t=>{let e=Qu.search;return await Gi(e,t)}},{name:"timeline",description:"Step 2: Get context around results. Params: anchor (observation ID) OR query (finds anchor automatically), depth_before, depth_after, project",inputSchema:{type:"object",properties:{anchor:{type:"number",description:"Observation ID to center the timeline around"},query:{type:"string",description:"Query to find anchor automatically"},depth_before:{type:"number",description:"Items before anchor (default 3)"},depth_after:{type:"number",description:"Items after anchor (default 3)"},project:{type:"string",description:"Filter by project name"}},additionalProperties:!0},handler:async t=>{let e=Qu.timeline;return await Gi(e,t)}},{name:"get_observations",description:"Step 3: Fetch full details for filtered IDs. Params: ids (array of observation IDs, required), orderBy, limit, project",inputSchema:{type:"object",properties:{ids:{type:"array",items:{type:"number"},description:"Array of observation IDs to fetch (required)"}},required:["ids"],additionalProperties:!0},handler:async t=>await Vt("/api/observations/batch",t)},{name:"smart_search",description:"Search codebase for symbols, functions, classes using tree-sitter AST parsing. Returns folded structural views with token counts. Use path parameter to scope the search.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search term \u2014 matches against symbol names, file names, and file content"},path:{type:"string",description:"Root directory to search (default: current working directory)"},max_results:{type:"number",description:"Maximum results to return (default: 20)"},file_pattern:{type:"string",description:'Substring filter for file paths (e.g. ".ts", "src/services")'}},required:["query"]},handler:async t=>{let e=(0,Pe.resolve)(t.path||process.cwd()),r=await Zu(e,t.query,{maxResults:t.max_results||20,filePattern:t.file_pattern});return{content:[{type:"text",text:Xu(r,t.query)}]}}},{name:"smart_unfold",description:"Expand a specific symbol (function, class, method) from a file. Returns the full source code of just that symbol. Use after smart_search or smart_outline to read specific code.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Path to the source file"},symbol_name:{type:"string",description:"Name of the symbol to unfold (function, class, method, etc.)"}},required:["file_path","symbol_name"]},handler:async t=>{let e=(0,Pe.resolve)(t.file_path),r=await(0,Ki.readFile)(e,"utf-8"),n=Yu(r,e,t.symbol_name);if(n)return{content:[{type:"text",text:n}]};let s=rs(r,e);if(s.symbols.length>0){let o=s.symbols.map(i=>` - ${i.name} (${i.kind})`).join(`
|
|
`);return{content:[{type:"text",text:`Symbol "${t.symbol_name}" not found in ${t.file_path}.
|
|
|
|
Available symbols:
|
|
${o}`}]}}return{content:[{type:"text",text:`Could not parse ${t.file_path}. File may be unsupported or empty.`}]}}},{name:"smart_outline",description:"Get structural outline of a file \u2014 shows all symbols (functions, classes, methods, types) with signatures but bodies folded. Much cheaper than reading the full file.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Path to the source file"}},required:["file_path"]},handler:async t=>{let e=(0,Pe.resolve)(t.file_path),r=await(0,Ki.readFile)(e,"utf-8"),n=rs(r,e);return n.symbols.length>0?{content:[{type:"text",text:Ht(n)}]}:{content:[{type:"text",text:`Could not parse ${t.file_path}. File may use an unsupported language or be empty.`}]}}},{name:"build_corpus",description:"Build a knowledge corpus from filtered observations. Creates a queryable knowledge agent. Params: name (required), description, project, types (comma-separated), concepts (comma-separated), files (comma-separated), query, dateStart, dateEnd, limit",inputSchema:{type:"object",properties:{name:{type:"string",description:"Corpus name (used as filename)"},description:{type:"string",description:"What this corpus is about"},project:{type:"string",description:"Filter by project"},types:{type:"string",description:"Comma-separated observation types: decision,bugfix,feature,refactor,discovery,change"},concepts:{type:"string",description:"Comma-separated concepts to filter by"},files:{type:"string",description:"Comma-separated file paths to filter by"},query:{type:"string",description:"Semantic search query"},dateStart:{type:"string",description:"Start date (ISO format)"},dateEnd:{type:"string",description:"End date (ISO format)"},limit:{type:"number",description:"Maximum observations (default 500)"}},required:["name"],additionalProperties:!0},handler:async t=>await Vt("/api/corpus",t)},{name:"list_corpora",description:"List all knowledge corpora with their stats and priming status",inputSchema:{type:"object",properties:{},additionalProperties:!0},handler:async t=>await Gi("/api/corpus",t)},{name:"prime_corpus",description:"Prime a knowledge corpus \u2014 creates an AI session loaded with the corpus knowledge. Must be called before query_corpus.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to prime"}},required:["name"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await Vt(`/api/corpus/${encodeURIComponent(e)}/prime`,r)}},{name:"query_corpus",description:"Ask a question to a primed knowledge corpus. The corpus must be primed first with prime_corpus.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to query"},question:{type:"string",description:"The question to ask"}},required:["name","question"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await Vt(`/api/corpus/${encodeURIComponent(e)}/query`,r)}},{name:"rebuild_corpus",description:"Rebuild a knowledge corpus from its stored filter \u2014 re-runs the search to refresh with new observations. Does not re-prime the session.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to rebuild"}},required:["name"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await Vt(`/api/corpus/${encodeURIComponent(e)}/rebuild`,r)}},{name:"reprime_corpus",description:"Create a fresh knowledge agent session for a corpus, clearing prior Q&A context. Use when conversation has drifted or after rebuilding.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to reprime"}},required:["name"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await Vt(`/api/corpus/${encodeURIComponent(e)}/reprime`,r)}}],Ji=new Gn({name:"claude-mem",version:KS},{capabilities:{tools:{}}});Ji.setRequestHandler(bs,async()=>({tools:od.map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))}));Ji.setRequestHandler(nr,async t=>{let e=od.find(r=>r.name===t.params.name);if(!e)throw new Error(`Unknown tool: ${t.params.name}`);try{return await e.handler(t.params.arguments||{})}catch(r){return y.error("SYSTEM","Tool execution failed",{tool:t.params.name},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Tool execution failed: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}});var XS=3e4,Hr=null,ed=!1;function os(){Wr("stdio-closed")}function id(t){y.warn("SYSTEM","MCP stdio stream errored, shutting down",{message:t.message}),Wr("stdio-error")}function QS(){process.stdin.on("end",os),process.stdin.on("close",os),process.stdin.on("error",id)}function eE(){process.stdin.off("end",os),process.stdin.off("close",os),process.stdin.off("error",id)}function tE(){if(process.platform==="win32")return;let t=process.ppid;Hr=setInterval(()=>{(process.ppid===1||process.ppid!==t)&&(y.info("SYSTEM","Parent process died, self-exiting to prevent orphan",{initialPpid:t,currentPpid:process.ppid}),Wr())},XS),Hr.unref&&Hr.unref()}function Wr(t="shutdown"){ed||(ed=!0,Hr&&clearInterval(Hr),eE(),y.info("SYSTEM","MCP server shutting down",{reason:t}),process.exit(0))}process.on("SIGTERM",Wr);process.on("SIGINT",Wr);function rE(){try{let t=(0,td.homedir)(),e=[(0,Pe.resolve)(t,".claude","plugins","marketplaces","thedotmack"),(0,Pe.resolve)(t,".config","claude","plugins","marketplaces","thedotmack")],r=e.some(i=>i&&(0,ss.existsSync)(i)),n=[(0,Pe.resolve)(t,".claude","plugins","cache","thedotmack","claude-mem"),(0,Pe.resolve)(t,".config","claude","plugins","cache","thedotmack","claude-mem")],s=n.some(i=>i&&(0,ss.existsSync)(i)),o=n[0];!r&&s&&y.error("SYSTEM","claude-mem MCP started but no marketplace directory was found at ~/.claude/plugins/marketplaces/thedotmack or the XDG equivalent. The IDE plugin loader needs that directory to fire claude-mem hooks (SessionStart, PostToolUse, Stop, etc.). Without it, MCP search will work but no new memories will be captured. To self-heal, run: node ~/.claude/plugins/cache/thedotmack/claude-mem/*/scripts/smart-install.js (or reinstall the plugin from the marketplace).",{marketplaceCandidates:e,cacheRoot:o})}catch{}}async function nE(){let t=new Yn;QS(),await Ji.connect(t),y.info("SYSTEM","Claude-mem search server started"),rE(),tE(),setTimeout(async()=>{await ZS()?y.info("SYSTEM","Worker available",void 0,{}):(y.error("SYSTEM","Worker not available",void 0,{}),y.error("SYSTEM","Tools will fail until Worker is started"),y.error("SYSTEM","Start Worker with: npm run worker:restart"))},0)}nE().catch(t=>{y.error("SYSTEM","Fatal error",void 0,t),process.exit(0)});
|