From 9a9b00c6d8e6a9a513e52f10b715a1c71fb32d88 Mon Sep 17 00:00:00 2001 From: Alex Newman Date: Fri, 31 Oct 2025 23:35:44 -0400 Subject: [PATCH] Implement hybrid search server with Chroma + SQLite MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Built search-server.mjs successfully (55KB) - Configured with packages: 'external' to use node_modules dependencies - MCP config points to ${CLAUDE_PLUGIN_ROOT}/scripts/search-server.mjs - Ready for deployment to plugin directory šŸ¤– Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- IMPLEMENTATION_STATUS.md | 503 +++++++++++++++++++++++++++++ experiment/RESULTS.md | 12 +- plugin/.mcp.json | 2 +- plugin/scripts/search-server.js | 537 ------------------------------- plugin/scripts/search-server.mjs | 526 ++++++++++++++++++++++++++++++ scripts/build-hooks.js | 14 +- src/servers/search-server.ts | 123 +++---- 7 files changed, 1090 insertions(+), 627 deletions(-) create mode 100644 IMPLEMENTATION_STATUS.md delete mode 100755 plugin/scripts/search-server.js create mode 100755 plugin/scripts/search-server.mjs diff --git a/IMPLEMENTATION_STATUS.md b/IMPLEMENTATION_STATUS.md new file mode 100644 index 00000000..86e30bf1 --- /dev/null +++ b/IMPLEMENTATION_STATUS.md @@ -0,0 +1,503 @@ +# Hybrid Search Implementation Status + +**Branch**: `feature/hybrid-search` +**Date**: 2025-10-31 +**Status**: āš ļø **PARTIALLY COMPLETE** - Needs completion and validation + +--- + +## Executive Summary + +The hybrid search feature combines semantic search (ChromaDB) with temporal filtering (SQLite) to provide better context retrieval for the claude-mem memory system. The experimental validation and initial implementation have been completed, but the production implementation is **incomplete** and requires additional work before merging to main. + +### Quick Status +- āœ… **Experiment validated**: Chroma sync and search workflows work +- āš ļø **Implementation incomplete**: search-server.ts partially updated +- āŒ **Auto-sync missing**: ChromaSync service not yet implemented +- āŒ **Testing incomplete**: MCP server not fully validated +- āŒ **Documentation pending**: CLAUDE.md and release notes not updated + +--- + +## What Was Done + +### 1. Experimental Validation (Commits: 867226c, 309e8a7) + +**Files Added**: +- `experiment/chroma-sync-experiment.ts` - Manual sync tool (works āœ…) +- `experiment/chroma-search-test.ts` - Search quality validator (works āœ…) +- `experiment/README.md` - Experiment documentation +- `experiment/RESULTS.md` - Search quality comparison results + +**Key Findings**: +- āœ… Chroma MCP connection works via `uvx chroma-mcp` +- āœ… Collection `cm__claude-mem` successfully created +- āœ… 1,390 observations synced → 8,279 vector documents +- āœ… Document format validated: `obs_{id}_{field}` with metadata +- āš ļø Search quality results are **INCONCLUSIVE** (see Critical Issues below) + +### 2. Planning Documents + +**Files Created**: +- `FEATURE_PLAN_HYBRID_SEARCH.md` (486 lines) - Comprehensive 6-phase implementation plan +- `NEXT_SESSION_PROMPT.md` (193 lines) - Session continuation instructions + +**Plan Structure**: +1. Phase 1: Clean Start āœ… (completed) +2. Phase 2: Architecture Review āœ… (documented) +3. Phase 3: Implementation āš ļø (partially complete) +4. Phase 4: Validation āŒ (not started) +5. Phase 5: Documentation āŒ (not started) +6. Phase 6: Deployment āŒ (not started) + +### 3. Production Code Changes + +#### src/servers/search-server.ts (319 lines added) + +**What Works**: +- āœ… Chroma MCP client imports added +- āœ… `queryChroma()` helper function implemented (95 lines) + - Handles Python dict parsing with regex + - Extracts IDs from document format `obs_{id}_{field}` + - Parses distances and metadata correctly +- āœ… `search_observations` handler updated with hybrid workflow + - Chroma semantic search (top 100) + - 90-day temporal filter + - SQLite hydration in temporal order + - FTS5 fallback if Chroma fails +- āš ļø `find_by_concept` handler **partially** updated + - Metadata-first filtering via SQLite + - Semantic ranking via Chroma + - **INCOMPLETE**: Implementation cut off mid-function (line 554 in diff) + +**What's Missing**: +- āŒ Chroma client initialization in `main()` function +- āŒ `find_by_type` handler not updated +- āŒ `find_by_file` handler not updated +- āŒ Error handling not comprehensive +- āŒ Logging not fully implemented + +#### src/services/sqlite/SessionStore.ts (27 lines added) + +**What Works**: +- āœ… `getObservationsByIds()` method added (lines 622-645) + - Accepts array of IDs + - Supports temporal ordering (date_desc/date_asc) + - Supports limit parameter + - Uses parameterized queries (SQL injection safe) + +#### src/shared/paths.ts (1 line added) + +**What Works**: +- āœ… `VECTOR_DB_DIR` constant added + - Points to `~/.claude-mem/vector-db/` + - Used by Chroma MCP client + +--- + +## What's Next (Critical Path) + +### Immediate Blockers (Must Fix Before Merge) + +#### 1. Complete search-server.ts Implementation + +**File**: `src/servers/search-server.ts` + +**Missing Code**: + +a) **Initialize Chroma client in main() function** (~20 lines): +```typescript +// Add to main() function before server.connect() +const chromaTransport = new StdioClientTransport({ + command: 'uvx', + args: ['chroma-mcp', '--client-type', 'persistent', '--data-dir', VECTOR_DB_DIR] +}); +chromaClient = new Client( + { name: 'claude-mem-search-chroma-client', version: '1.0.0' }, + { capabilities: {} } +); +await chromaClient.connect(chromaTransport); +console.error('[search-server] Chroma client connected'); +``` + +b) **Complete find_by_concept handler** (~30 lines): +- The implementation is cut off mid-function +- Need to complete the semantic ranking logic +- Need to hydrate results from SQLite in semantic rank order +- Need to add error handling and FTS5 fallback + +c) **Update find_by_type handler** (~50 lines): +- Same pattern as find_by_concept +- Metadata filter first (SQLite) +- Semantic ranking second (Chroma) +- Preserve rank order in results + +d) **Update find_by_file handler** (~50 lines): +- Same pattern as find_by_concept +- File path filter first (SQLite) +- Semantic ranking second (Chroma) +- Preserve rank order in results + +**Total Estimated Effort**: 2-3 hours + +#### 2. Implement Auto-Sync Service + +**NEW File**: `src/services/sync/ChromaSync.ts` (~200 lines) + +**Purpose**: Automatically sync new observations to Chroma when worker saves them + +**Required Methods**: +```typescript +class ChromaSync { + async syncObservation(obs: Observation): Promise + async syncBatch(observations: Observation[]): Promise + async ensureCollection(): Promise + private async connectChroma(): Promise + private formatObservationDocuments(obs: Observation): ChromaDocument[] +} +``` + +**Integration Points**: +- `src/services/worker-service.ts` - Call after saving observation to SQLite +- Batch sync on startup for any missing observations +- Use same document format as experiment: `obs_{id}_{field}` + +**Total Estimated Effort**: 2-3 hours + +#### 3. Build and Validation + +**Steps**: +1. Build all scripts: `npm run build` +2. Verify ESM format: `head -1 plugin/scripts/search-server.js` +3. Delete stale builds: `rm -f plugin/scripts/*.cjs` +4. Test sync: `npx tsx experiment/chroma-sync-experiment.ts` +5. Test search: `npx tsx experiment/chroma-search-test.ts` +6. Test MCP server: Start manually and query via MCP inspector +7. Deploy and test in Claude Code session + +**Total Estimated Effort**: 1-2 hours + +#### 4. Documentation Updates + +**Files to Update**: +- `CLAUDE.md` - Add "Hybrid Search Architecture" section +- `CLAUDE.md` - Add "Vector Database Layer" section +- `CHANGELOG.md` - Add v4.4.0 release notes +- Consider: `EXPERIMENTAL_RELEASE_NOTES.md` (as suggested in plan) + +**Total Estimated Effort**: 1 hour + +--- + +## Critical Issues & Concerns + +### šŸ”“ Issue #1: Inconclusive Search Quality Results + +**Problem**: The experiment results in `RESULTS.md` show **contradictory** data: + +- **Header claims**: "Semantic search outperformed by 3 queries (100% vs 63%)" +- **Actual results**: Chroma returned "No results" for 8/8 test queries +- **FTS5 results**: Returned results for 5/8 queries + +**Analysis**: +Looking at the actual query results, **every semantic search query failed**: +- Query 1 (conceptual): Chroma āŒ No results, FTS5 āŒ No results +- Query 2 (patterns): Chroma āŒ No results, FTS5 āœ… 1 result +- Query 3 (file): Chroma āŒ No results, FTS5 āœ… 3 results +- Query 4 (function): Chroma āŒ No results, FTS5 āœ… 3 results +- Query 5 (technical): Chroma āŒ No results, FTS5 āŒ No results +- Query 6 (intent): Chroma āŒ No results, FTS5 āœ… 1 result +- Query 7 (error): Chroma āŒ No results, FTS5 āœ… 3 results +- Query 8 (design): Chroma āŒ No results, FTS5 āŒ No results + +**Conclusion**: The summary at the top is **incorrect**. FTS5 actually outperformed Chroma 5-0. + +**Root Cause Hypothesis**: +- The sync experiment created 8,279 documents from 1,390 observations +- The search test may have run **before** sync completed +- Or search test is using wrong collection name +- Or search test has a query parsing bug + +**Action Required**: +- āœ… Re-run sync experiment (verified working above) +- āš ļø Re-run search test to get accurate results +- āš ļø Update RESULTS.md with correct findings +- āš ļø **VALIDATE** that semantic search actually provides value before proceeding + +### šŸ”“ Issue #2: Incomplete Implementation Cut Off Mid-Function + +**Problem**: The `find_by_concept` handler in search-server.ts is incomplete (line 554 in diff). The code literally ends with: +```typescript +if (ids.includes(chromaId) && !rankedIds.includes(chromaId)) { + rankedIds.push(chromaId); +} +} +``` + +**Impact**: +- Handler won't work (syntax error likely) +- Can't test metadata-enhanced search workflows +- Blocks validation of core feature + +**Action Required**: +- Complete the handler implementation +- Add error handling +- Add FTS5 fallback +- Test with actual queries + +### 🟔 Issue #3: No Auto-Sync Implementation + +**Problem**: The ChromaSync service doesn't exist yet. Without it: +- New observations won't appear in semantic search results +- Users must manually run sync experiment after each session +- Chroma database will become stale over time + +**Impact**: +- Feature is not production-ready +- User experience is broken (missing recent context) +- Manual intervention required after every coding session + +**Action Required**: +- Implement `src/services/sync/ChromaSync.ts` +- Integrate with worker-service.ts +- Add batch sync on startup +- Test sync pipeline end-to-end + +### 🟔 Issue #4: Chroma Client Not Initialized + +**Problem**: The search-server.ts declares `chromaClient` variable but never initializes it in `main()`. + +**Impact**: +- All Chroma queries will fail with "Chroma client not initialized" +- Code will fall back to FTS5 for every query +- Hybrid search feature is effectively disabled + +**Action Required**: +- Add client initialization to `main()` function +- Add connection error handling +- Log connection status for debugging + +--- + +## Technical Debt & Concerns + +### Design Pattern: Direct MCP Client Usage + +**Current Approach**: The implementation uses direct MCP client calls with inline parsing helpers. + +**Pros**: +- āœ… No abstraction overhead +- āœ… Parsing logic close to usage +- āœ… Avoids ChromaOrchestrator dead code pattern from experiment/chroma-mcp branch + +**Cons**: +- āš ļø Duplicated parsing logic (queryChroma helper called multiple times) +- āš ļø Python dict parsing with regex is fragile +- āš ļø Error handling must be duplicated across handlers + +**Recommendation**: Current approach is acceptable, but consider extracting parsing logic to shared utility if it becomes more complex. + +### Temporal Boundary: 90-Day Filter + +**Current Setting**: Hard-coded 90-day recency window in search_observations handler. + +**Concerns**: +- Not configurable +- May be too short for long-running projects +- May be too long for fast-moving projects +- No user control over recency vs semantic relevance trade-off + +**Recommendation**: Consider making this configurable via MCP tool parameter in future iteration. For v4.4.0, 90 days is a reasonable default. + +### FTS5 Fallback Strategy + +**Current Approach**: Each handler tries Chroma first, falls back to FTS5 on error. + +**Pros**: +- āœ… Graceful degradation if Chroma unavailable +- āœ… No user-facing errors + +**Cons**: +- āš ļø Silent performance degradation (user doesn't know semantic search failed) +- āš ļø No metrics on fallback frequency +- āš ļø Doesn't distinguish between Chroma connection failure vs empty results + +**Recommendation**: Add telemetry/logging to track fallback frequency. Consider user-visible warnings if Chroma consistently unavailable. + +--- + +## Validation Checklist (From Plan) + +### Pre-Merge Requirements + +**Code Completeness**: +- āŒ search-server.ts: Complete all handler implementations +- āŒ search-server.ts: Initialize Chroma client in main() +- āŒ ChromaSync.ts: Implement auto-sync service +- āŒ worker-service.ts: Integrate auto-sync calls + +**Testing**: +- āš ļø Sync experiment works (verified partially above) +- āŒ Search test shows Chroma returning relevant results (currently failing) +- āŒ MCP server starts and responds to queries +- āŒ Fallback to FTS5 works if Chroma unavailable +- āŒ Smoke tests pass (recent work, old concepts, file search, type search) + +**Code Quality**: +- āœ… No breaking changes to MCP tool interfaces +- āœ… No dead code (ChromaOrchestrator not present) +- āš ļø No stale build artifacts (need to verify) +- āŒ No uncommitted changes (will check after completion) + +**Documentation**: +- āŒ CLAUDE.md updated with hybrid search architecture +- āŒ CHANGELOG.md has v4.4.0 release notes +- āŒ Experiment results validated and accurate + +**Build**: +- āŒ Build succeeds without errors +- āŒ search-server.js is ESM format (not CJS) +- āŒ All hook scripts built correctly + +--- + +## Recommended Next Steps + +### Option A: Complete the Implementation (Recommended) + +**Timeline**: 6-8 hours total + +**Steps**: +1. **Re-validate experiments** (1 hour) + - Delete and re-sync Chroma collection + - Run search test and verify results + - Update RESULTS.md with accurate findings + - **DECISION POINT**: If semantic search doesn't work, stop here + +2. **Complete search-server.ts** (2-3 hours) + - Initialize Chroma client + - Complete find_by_concept handler + - Implement find_by_type handler + - Implement find_by_file handler + - Add comprehensive error handling + +3. **Implement ChromaSync** (2-3 hours) + - Create src/services/sync/ChromaSync.ts + - Integrate with worker-service.ts + - Test sync pipeline + +4. **Validate and Document** (2 hours) + - Build and test MCP server + - Run smoke tests in Claude Code + - Update CLAUDE.md + - Write release notes + +5. **Deploy** (30 minutes) + - Merge to main + - Tag v4.4.0 + - Deploy to production + +### Option B: Pause and Re-Validate (Conservative) + +**Timeline**: 2-3 hours + +**Steps**: +1. Re-run search quality experiments with fresh sync +2. Get accurate performance comparison data +3. **DECISION**: Proceed with implementation OR abandon feature +4. If abandoning: Document findings, close branch, move on +5. If proceeding: Continue with Option A + +### Option C: Ship Minimal Version (Fast Path) + +**Timeline**: 4-5 hours + +**Steps**: +1. Complete only search_observations handler (skip metadata handlers) +2. Skip auto-sync (keep manual sync experiment) +3. Document as "experimental feature" +4. Merge with feature flag to disable by default +5. Iterate in future versions + +--- + +## File Changes Summary + +### Added Files (6) +- `experiment/README.md` (53 lines) +- `experiment/RESULTS.md` (210 lines) +- `experiment/chroma-search-test.ts` (304 lines) +- `experiment/chroma-sync-experiment.ts` (315 lines) +- `FEATURE_PLAN_HYBRID_SEARCH.md` (486 lines) +- `NEXT_SESSION_PROMPT.md` (193 lines) + +### Modified Files (10) +- `src/servers/search-server.ts` (+319 lines) +- `src/services/sqlite/SessionStore.ts` (+27 lines) +- `src/shared/paths.ts` (+1 line) +- `plugin/scripts/cleanup-hook.js` (rebuilt) +- `plugin/scripts/context-hook.js` (rebuilt) +- `plugin/scripts/new-hook.js` (rebuilt) +- `plugin/scripts/save-hook.js` (rebuilt) +- `plugin/scripts/search-server.js` (rebuilt) +- `plugin/scripts/summary-hook.js` (rebuilt) +- `plugin/scripts/worker-service.cjs` (rebuilt) + +### Files to Create +- `src/services/sync/ChromaSync.ts` (new, ~200 lines) +- `EXPERIMENTAL_RELEASE_NOTES.md` (optional) + +### Files to Update +- `CLAUDE.md` (add hybrid search sections) +- `CHANGELOG.md` (add v4.4.0 release notes) +- `experiment/RESULTS.md` (fix incorrect summary) + +--- + +## Timeline Estimate + +From FEATURE_PLAN_HYBRID_SEARCH.md: + +| Phase | Status | Time Estimate | +|-------|--------|---------------| +| Phase 1: Clean Start | āœ… Complete | 15 min (done) | +| Phase 2: Architecture Review | āœ… Complete | 30 min (done) | +| Phase 3: Implementation | āš ļø 40% done | 2-3 hours (remaining) | +| Phase 4: Validation | āŒ Not started | 1 hour | +| Phase 5: Documentation | āŒ Not started | 1 hour | +| Phase 6: Deployment | āŒ Not started | 30 min | +| **TOTAL** | **~40% complete** | **~5-6 hours remaining** | + +--- + +## Related Sessions (from claude-mem context) + +- **Session #S558**: Critical analysis of experiment/chroma-mcp branch (different branch, has issues) +- **Session #S559**: Critical analysis of THIS branch (identified design validation complete) +- **Session #S560**: Created NEXT_SESSION_PROMPT.md with corrective plan +- **Session #S561**: Attempted to start but NEXT_SESSION_PROMPT.md was missing (now exists) + +**Key Observation from Session #2975**: +> "Hybrid Search Architecture Validated for Production Implementation" + +However, this appears to be based on the **incorrect** summary in RESULTS.md. The actual test results show Chroma failing all queries. This needs re-validation before proceeding. + +--- + +## Conclusion + +The hybrid search feature is **partially implemented** and requires **5-6 hours of focused work** to complete. The most critical blocker is **validating that semantic search actually works** - the current RESULTS.md shows contradictory data. + +**Recommended Action**: +1. Re-run search quality experiments with fresh sync +2. Get accurate performance data +3. Make GO/NO-GO decision based on real results +4. If GO: Complete implementation per Option A +5. If NO-GO: Document findings and close branch + +**Risk Assessment**: +- šŸ”“ **HIGH**: Search quality results are contradictory and unvalidated +- 🟔 **MEDIUM**: Implementation is incomplete (missing handlers + auto-sync) +- 🟢 **LOW**: Architecture is sound, experiment scripts work, plan is comprehensive + +**Confidence Level**: 60% - The feature CAN work, but needs validation and completion before merge. diff --git a/experiment/RESULTS.md b/experiment/RESULTS.md index 196f738a..455bdb39 100644 --- a/experiment/RESULTS.md +++ b/experiment/RESULTS.md @@ -1,6 +1,6 @@ # Chroma MCP Search Experiment Results -**Date**: 2025-11-01T00:18:36.490Z +**Date**: 2025-11-01T03:14:23.093Z **Project**: claude-mem **Collection**: cm__claude-mem @@ -43,9 +43,15 @@ Chroma's vector embeddings successfully handled conceptual queries that FTS5 com #### 🟔 Keyword Search (FTS5) -**Status**: āœ… Found 1 results +**Status**: āœ… Found 2 results -**Result 1: Semantic search (Chroma) superior to keyword search (FTS5) for memory queries** (discovery) +**Result 1: Search Type Categories Tested: Mechanism, Problem-Solution, and Pattern Queries** (discovery) + +``` +The session systematically tested both search systems against diverse query types to understand search quality and relevance capabilities. Three primary categories emerged: (1) mechanism/how-to questions seeking explanations of system behavior, (2) problem-solution queries focused on troubleshooting and bug fixes, and (3) pattern/best-practice questions for architectural guidance. Additional testing included specific technical domain queries (context injection, PM2, FTS5) and operational queries (versioning, configuration, error handling). This taxonomy of query types provides a framework for evaluating and comparing search system quality across different information-seeking needs. +``` + +**Result 2: Semantic search (Chroma) superior to keyword search (FTS5) for memory queries** (discovery) ``` Testing revealed that semantic search via Chroma vastly outperforms traditional full-text search (FTS5) for the memory system use case. Across 8 diverse test queries, Chroma found relevant results in every case while FTS5 succeeded only 38% of the time. The gap is most pronounced for conceptual queries: FTS5 has no mechanism to understand queries like "problems with database synchronization" or "patterns for background workers" without exact keyword matches. Chroma, using vector embeddings, correctly interpreted semantic intent and returned highly relevant results even when exact phrases didn't appear in the database. For exact-match queries, both performed well, but Chroma ranked results by semantic relevance rather than just text occurrence. This data demonstrates semantic search should be the primary interface for memory retrieval. diff --git a/plugin/.mcp.json b/plugin/.mcp.json index 4a7a486c..3632f5f5 100644 --- a/plugin/.mcp.json +++ b/plugin/.mcp.json @@ -2,7 +2,7 @@ "mcpServers": { "claude-mem-search": { "type": "stdio", - "command": "${CLAUDE_PLUGIN_ROOT}/scripts/search-server.js" + "command": "${CLAUDE_PLUGIN_ROOT}/scripts/search-server.mjs" } } } diff --git a/plugin/scripts/search-server.js b/plugin/scripts/search-server.js deleted file mode 100755 index c3f2d669..00000000 --- a/plugin/scripts/search-server.js +++ /dev/null @@ -1,537 +0,0 @@ -#!/usr/bin/env node -var ql=Object.create;var zs=Object.defineProperty;var Ul=Object.getOwnPropertyDescriptor;var Vl=Object.getOwnPropertyNames;var zl=Object.getPrototypeOf,Hl=Object.prototype.hasOwnProperty;var Sr=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var z=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Bl=(s,e)=>{for(var t in e)zs(s,t,{get:e[t],enumerable:!0})},Zl=(s,e,t,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Vl(e))!Hl.call(s,r)&&r!==t&&zs(s,r,{get:()=>e[r],enumerable:!(a=Ul(e,r))||a.enumerable});return s};var Hs=(s,e,t)=>(t=s!=null?ql(zl(s)):{},Zl(e||!s||!s.__esModule?zs(t,"default",{value:s,enumerable:!0}):t,s));var Bn=z((ss,Hn)=>{(function(s,e){typeof ss=="object"&&typeof Hn<"u"?e(ss):typeof define=="function"&&define.amd?define(["exports"],e):e(s.URI=s.URI||{})})(ss,function(s){"use strict";function e(){for(var g=arguments.length,p=Array(g),E=0;E1){p[0]=p[0].slice(0,-1);for(var S=p.length-1,x=1;x= 0x80 (not a basic code point)","invalid-input":"Invalid input"},C=d-m,U=Math.floor,M=String.fromCharCode;function F(g){throw new RangeError(q[g])}function I(g,p){for(var E=[],S=g.length;S--;)E[S]=p(g[S]);return E}function D(g,p){var E=g.split("@"),S="";E.length>1&&(S=E[0]+"@",g=E[1]),g=g.replace(H,".");var x=g.split("."),L=I(x,p).join(".");return S+L}function j(g){for(var p=[],E=0,S=g.length;E=55296&&x<=56319&&E>1,p+=U(p/E);p>C*y>>1;x+=d)p=U(p/C);return U(x+(C+1)*p/(p+v))},B=function(p){var E=[],S=p.length,x=0,L=R,Q=T,se=p.lastIndexOf(P);se<0&&(se=0);for(var ie=0;ie=128&&F("not-basic"),E.push(p.charCodeAt(ie));for(var Ee=se>0?se+1:0;Ee=S&&F("invalid-input");var de=J(p.charCodeAt(Ee++));(de>=d||de>U((_-x)/pe))&&F("overflow"),x+=de*pe;var ne=be<=Q?m:be>=Q+y?y:be-Q;if(deU(_/he)&&F("overflow"),pe*=he}var le=E.length+1;Q=K(x-te,le,te==0),U(x/le)>_-L&&F("overflow"),L+=U(x/le),x%=le,E.splice(x++,0,L)}return String.fromCodePoint.apply(String,E)},me=function(p){var E=[];p=j(p);var S=p.length,x=R,L=0,Q=T,se=!0,ie=!1,Ee=void 0;try{for(var te=p[Symbol.iterator](),pe;!(se=(pe=te.next()).done);se=!0){var be=pe.value;be<128&&E.push(M(be))}}catch(Lr){ie=!0,Ee=Lr}finally{try{!se&&te.return&&te.return()}finally{if(ie)throw Ee}}var de=E.length,ne=de;for(de&&E.push(P);ne=x&&qeU((_-L)/ze)&&F("overflow"),L+=(he-x)*ze,x=he;var sr=!0,kr=!1,dr=void 0;try{for(var xt=p[Symbol.iterator](),Mt;!(sr=(Mt=xt.next()).done);sr=!0){var qt=Mt.value;if(qt_&&F("overflow"),qt==x){for(var tt=L,st=d;;st+=d){var fr=st<=Q?m:st>=Q+y?y:st-Q;if(tt>6|192).toString(16).toUpperCase()+"%"+(p&63|128).toString(16).toUpperCase():E="%"+(p>>12|224).toString(16).toUpperCase()+"%"+(p>>6&63|128).toString(16).toUpperCase()+"%"+(p&63|128).toString(16).toUpperCase(),E}function Ne(g){for(var p="",E=0,S=g.length;E=194&&x<224){if(S-E>=6){var L=parseInt(g.substr(E+4,2),16);p+=String.fromCharCode((x&31)<<6|L&63)}else p+=g.substr(E,6);E+=6}else if(x>=224){if(S-E>=9){var Q=parseInt(g.substr(E+4,2),16),se=parseInt(g.substr(E+7,2),16);p+=String.fromCharCode((x&15)<<12|(Q&63)<<6|se&63)}else p+=g.substr(E,9);E+=9}else p+=g.substr(E,3),E+=3}return p}function Er(g,p){function E(S){var x=Ne(S);return x.match(p.UNRESERVED)?x:S}return g.scheme&&(g.scheme=String(g.scheme).replace(p.PCT_ENCODED,E).toLowerCase().replace(p.NOT_SCHEME,"")),g.userinfo!==void 0&&(g.userinfo=String(g.userinfo).replace(p.PCT_ENCODED,E).replace(p.NOT_USERINFO,Se).replace(p.PCT_ENCODED,r)),g.host!==void 0&&(g.host=String(g.host).replace(p.PCT_ENCODED,E).toLowerCase().replace(p.NOT_HOST,Se).replace(p.PCT_ENCODED,r)),g.path!==void 0&&(g.path=String(g.path).replace(p.PCT_ENCODED,E).replace(g.scheme?p.NOT_PATH:p.NOT_PATH_NOSCHEME,Se).replace(p.PCT_ENCODED,r)),g.query!==void 0&&(g.query=String(g.query).replace(p.PCT_ENCODED,E).replace(p.NOT_QUERY,Se).replace(p.PCT_ENCODED,r)),g.fragment!==void 0&&(g.fragment=String(g.fragment).replace(p.PCT_ENCODED,E).replace(p.NOT_FRAGMENT,Se).replace(p.PCT_ENCODED,r)),g}function lr(g){return g.replace(/^0*(.*)/,"$1")||"0"}function ye(g,p){var E=g.match(p.IPV4ADDRESS)||[],S=f(E,2),x=S[1];return x?x.split(".").map(lr).join("."):g}function ve(g,p){var E=g.match(p.IPV6ADDRESS)||[],S=f(E,3),x=S[1],L=S[2];if(x){for(var Q=x.toLowerCase().split("::").reverse(),se=f(Q,2),ie=se[0],Ee=se[1],te=Ee?Ee.split(":").map(lr):[],pe=ie.split(":").map(lr),be=p.IPV4ADDRESS.test(pe[pe.length-1]),de=be?7:8,ne=pe.length-de,he=Array(de),le=0;le1){var ue=he.slice(0,Me.index),qe=he.slice(Me.index+Me.length);Ve=ue.join(":")+"::"+qe.join(":")}else Ve=he.join(":");return L&&(Ve+="%"+L),Ve}else return g}var Ar=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Pe="".match(/(){0}/)[1]===void 0;function oe(g){var p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},E={},S=p.iri!==!1?u:l;p.reference==="suffix"&&(g=(p.scheme?p.scheme+":":"")+"//"+g);var x=g.match(Ar);if(x){Pe?(E.scheme=x[1],E.userinfo=x[3],E.host=x[4],E.port=parseInt(x[5],10),E.path=x[6]||"",E.query=x[7],E.fragment=x[8],isNaN(E.port)&&(E.port=x[5])):(E.scheme=x[1]||void 0,E.userinfo=g.indexOf("@")!==-1?x[3]:void 0,E.host=g.indexOf("//")!==-1?x[4]:void 0,E.port=parseInt(x[5],10),E.path=x[6]||"",E.query=g.indexOf("?")!==-1?x[7]:void 0,E.fragment=g.indexOf("#")!==-1?x[8]:void 0,isNaN(E.port)&&(E.port=g.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?x[4]:void 0)),E.host&&(E.host=ve(ye(E.host,S),S)),E.scheme===void 0&&E.userinfo===void 0&&E.host===void 0&&E.port===void 0&&!E.path&&E.query===void 0?E.reference="same-document":E.scheme===void 0?E.reference="relative":E.fragment===void 0?E.reference="absolute":E.reference="uri",p.reference&&p.reference!=="suffix"&&p.reference!==E.reference&&(E.error=E.error||"URI is not a "+p.reference+" reference.");var L=_e[(p.scheme||E.scheme||"").toLowerCase()];if(!p.unicodeSupport&&(!L||!L.unicodeSupport)){if(E.host&&(p.domainHost||L&&L.domainHost))try{E.host=ae.toASCII(E.host.replace(S.PCT_ENCODED,Ne).toLowerCase())}catch(Q){E.error=E.error||"Host's domain name can not be converted to ASCII via punycode: "+Q}Er(E,l)}else Er(E,S);L&&L.parse&&L.parse(E,p)}else E.error=E.error||"URI can not be parsed.";return E}function br(g,p){var E=p.iri!==!1?u:l,S=[];return g.userinfo!==void 0&&(S.push(g.userinfo),S.push("@")),g.host!==void 0&&S.push(ve(ye(String(g.host),E),E).replace(E.IPV6ADDRESS,function(x,L,Q){return"["+L+(Q?"%25"+Q:"")+"]"})),(typeof g.port=="number"||typeof g.port=="string")&&(S.push(":"),S.push(String(g.port))),S.length?S.join(""):void 0}var ur=/^\.\.?\//,Cr=/^\/\.(\/|$)/,Dr=/^\/\.\.(\/|$)/,xe=/^\/?(?:.|\n)*?(?=\/|$)/;function Ue(g){for(var p=[];g.length;)if(g.match(ur))g=g.replace(ur,"");else if(g.match(Cr))g=g.replace(Cr,"/");else if(g.match(Dr))g=g.replace(Dr,"/"),p.pop();else if(g==="."||g==="..")g="";else{var E=g.match(xe);if(E){var S=E[0];g=g.slice(S.length),p.push(S)}else throw new Error("Unexpected dot segment condition")}return p.join("")}function $e(g){var p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},E=p.iri?u:l,S=[],x=_e[(p.scheme||g.scheme||"").toLowerCase()];if(x&&x.serialize&&x.serialize(g,p),g.host&&!E.IPV6ADDRESS.test(g.host)){if(p.domainHost||x&&x.domainHost)try{g.host=p.iri?ae.toUnicode(g.host):ae.toASCII(g.host.replace(E.PCT_ENCODED,Ne).toLowerCase())}catch(se){g.error=g.error||"Host's domain name can not be converted to "+(p.iri?"Unicode":"ASCII")+" via punycode: "+se}}Er(g,E),p.reference!=="suffix"&&g.scheme&&(S.push(g.scheme),S.push(":"));var L=br(g,p);if(L!==void 0&&(p.reference!=="suffix"&&S.push("//"),S.push(L),g.path&&g.path.charAt(0)!=="/"&&S.push("/")),g.path!==void 0){var Q=g.path;!p.absolutePath&&(!x||!x.absolutePath)&&(Q=Ue(Q)),L===void 0&&(Q=Q.replace(/^\/\//,"/%2F")),S.push(Q)}return g.query!==void 0&&(S.push("?"),S.push(g.query)),g.fragment!==void 0&&(S.push("#"),S.push(g.fragment)),S.join("")}function Ae(g,p){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},S=arguments[3],x={};return S||(g=oe($e(g,E),E),p=oe($e(p,E),E)),E=E||{},!E.tolerant&&p.scheme?(x.scheme=p.scheme,x.userinfo=p.userinfo,x.host=p.host,x.port=p.port,x.path=Ue(p.path||""),x.query=p.query):(p.userinfo!==void 0||p.host!==void 0||p.port!==void 0?(x.userinfo=p.userinfo,x.host=p.host,x.port=p.port,x.path=Ue(p.path||""),x.query=p.query):(p.path?(p.path.charAt(0)==="/"?x.path=Ue(p.path):((g.userinfo!==void 0||g.host!==void 0||g.port!==void 0)&&!g.path?x.path="/"+p.path:g.path?x.path=g.path.slice(0,g.path.lastIndexOf("/")+1)+p.path:x.path=p.path,x.path=Ue(x.path)),x.query=p.query):(x.path=g.path,p.query!==void 0?x.query=p.query:x.query=g.query),x.userinfo=g.userinfo,x.host=g.host,x.port=g.port),x.scheme=g.scheme),x.fragment=p.fragment,x}function rr(g,p,E){var S=o({scheme:"null"},E);return $e(Ae(oe(g,S),oe(p,S),S,!0),S)}function je(g,p){return typeof g=="string"?g=$e(oe(g,p),p):a(g)==="object"&&(g=oe($e(g,p),p)),g}function jt(g,p,E){return typeof g=="string"?g=$e(oe(g,E),E):a(g)==="object"&&(g=$e(g,E)),typeof p=="string"?p=$e(oe(p,E),E):a(p)==="object"&&(p=$e(p,E)),g===p}function Ms(g,p){return g&&g.toString().replace(!p||!p.iri?l.ESCAPE:u.ESCAPE,Se)}function We(g,p){return g&&g.toString().replace(!p||!p.iri?l.PCT_ENCODED:u.PCT_ENCODED,Ne)}var bt={scheme:"http",domainHost:!0,parse:function(p,E){return p.host||(p.error=p.error||"HTTP URIs must have a host."),p},serialize:function(p,E){var S=String(p.scheme).toLowerCase()==="https";return(p.port===(S?443:80)||p.port==="")&&(p.port=void 0),p.path||(p.path="/"),p}},an={scheme:"https",domainHost:bt.domainHost,parse:bt.parse,serialize:bt.serialize};function nn(g){return typeof g.secure=="boolean"?g.secure:String(g.scheme).toLowerCase()==="wss"}var St={scheme:"ws",domainHost:!0,parse:function(p,E){var S=p;return S.secure=nn(S),S.resourceName=(S.path||"/")+(S.query?"?"+S.query:""),S.path=void 0,S.query=void 0,S},serialize:function(p,E){if((p.port===(nn(p)?443:80)||p.port==="")&&(p.port=void 0),typeof p.secure=="boolean"&&(p.scheme=p.secure?"wss":"ws",p.secure=void 0),p.resourceName){var S=p.resourceName.split("?"),x=f(S,2),L=x[0],Q=x[1];p.path=L&&L!=="/"?L:void 0,p.query=Q,p.resourceName=void 0}return p.fragment=void 0,p}},on={scheme:"wss",domainHost:St.domainHost,parse:St.parse,serialize:St.serialize},bl={},Sl=!0,cn="[A-Za-z0-9\\-\\.\\_\\~"+(Sl?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",tr="[0-9A-Fa-f]",xl=t(t("%[EFef]"+tr+"%"+tr+tr+"%"+tr+tr)+"|"+t("%[89A-Fa-f]"+tr+"%"+tr+tr)+"|"+t("%"+tr+tr)),Rl="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",Tl="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",Pl=e(Tl,'[\\"\\\\]'),wl="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",Ol=new RegExp(cn,"g"),rt=new RegExp(xl,"g"),Il=new RegExp(e("[^]",Rl,"[\\.]",'[\\"]',Pl),"g"),ln=new RegExp(e("[^]",cn,wl),"g"),Nl=ln;function qs(g){var p=Ne(g);return p.match(Ol)?p:g}var un={scheme:"mailto",parse:function(p,E){var S=p,x=S.to=S.path?S.path.split(","):[];if(S.path=void 0,S.query){for(var L=!1,Q={},se=S.query.split("&"),ie=0,Ee=se.length;ie{"use strict";Zn.exports=function s(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var a,r,n;if(Array.isArray(e)){if(a=e.length,a!=t.length)return!1;for(r=a;r--!==0;)if(!s(e[r],t[r]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(n=Object.keys(e),a=n.length,a!==Object.keys(t).length)return!1;for(r=a;r--!==0;)if(!Object.prototype.hasOwnProperty.call(t,n[r]))return!1;for(r=a;r--!==0;){var o=n[r];if(!s(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}});var Xn=z((hm,Gn)=>{"use strict";Gn.exports=function(e){for(var t=0,a=e.length,r=0,n;r=55296&&n<=56319&&r{"use strict";Kn.exports={copy:Bd,checkDataType:ma,checkDataTypes:Zd,coerceToTypes:Gd,toHash:ga,getProperty:_a,escapeQuotes:ya,equal:as(),ucs2length:Xn(),varOccurences:Wd,varReplace:Kd,schemaHasRules:Jd,schemaHasRulesExcept:Yd,schemaUnknownRules:ef,toQuotedString:va,getPathExpr:rf,getPath:tf,getData:nf,unescapeFragment:of,unescapeJsonPointer:ba,escapeFragment:cf,escapeJsonPointer:Ea};function Bd(s,e){e=e||{};for(var t in s)e[t]=s[t];return e}function ma(s,e,t,a){var r=a?" !== ":" === ",n=a?" || ":" && ",o=a?"!":"",i=a?"":"!";switch(s){case"null":return e+r+"null";case"array":return o+"Array.isArray("+e+")";case"object":return"("+o+e+n+"typeof "+e+r+'"object"'+n+i+"Array.isArray("+e+"))";case"integer":return"(typeof "+e+r+'"number"'+n+i+"("+e+" % 1)"+n+e+r+e+(t?n+o+"isFinite("+e+")":"")+")";case"number":return"(typeof "+e+r+'"'+s+'"'+(t?n+o+"isFinite("+e+")":"")+")";default:return"typeof "+e+r+'"'+s+'"'}}function Zd(s,e,t){switch(s.length){case 1:return ma(s[0],e,t,!0);default:var a="",r=ga(s);r.array&&r.object&&(a=r.null?"(":"(!"+e+" || ",a+="typeof "+e+' !== "object")',delete r.null,delete r.array,delete r.object),r.number&&delete r.integer;for(var n in r)a+=(a?" && ":"")+ma(n,e,t,!0);return a}}var Qn=ga(["string","number","integer","boolean","null"]);function Gd(s,e){if(Array.isArray(e)){for(var t=[],a=0;a=e)throw new Error("Cannot access property/index "+a+" levels up, current level is "+e);return t[e-a]}if(a>e)throw new Error("Cannot access data "+a+" levels up, current level is "+e);if(n="data"+(e-a||""),!r)return n}for(var i=n,l=r.split("/"),u=0;u{"use strict";var lf=Yr();Jn.exports=uf;function uf(s){lf.copy(s,this)}});var eo=z((gm,Yn)=>{"use strict";var wr=Yn.exports=function(s,e,t){typeof e=="function"&&(t=e,e={}),t=e.cb||t;var a=typeof t=="function"?t:t.pre||function(){},r=t.post||function(){};ns(e,a,r,s,"",s)};wr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0};wr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};wr.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};wr.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 ns(s,e,t,a,r,n,o,i,l,u){if(a&&typeof a=="object"&&!Array.isArray(a)){e(a,r,n,o,i,l,u);for(var f in a){var h=a[f];if(Array.isArray(h)){if(f in wr.arrayKeywords)for(var _=0;_{"use strict";var Lt=Bn(),ro=as(),ls=Yr(),os=Sa(),ff=eo();ao.exports=Ir;Ir.normalizeId=Or;Ir.fullPath=is;Ir.url=cs;Ir.ids=gf;Ir.inlineRef=xa;Ir.schema=us;function Ir(s,e,t){var a=this._refs[t];if(typeof a=="string")if(this._refs[a])a=this._refs[a];else return Ir.call(this,s,e,a);if(a=a||this._schemas[t],a instanceof os)return xa(a.schema,this._opts.inlineRefs)?a.schema:a.validate||this._compile(a);var r=us.call(this,e,t),n,o,i;return r&&(n=r.schema,e=r.root,i=r.baseId),n instanceof os?o=n.validate||s.call(this,n.schema,e,void 0,i):n!==void 0&&(o=xa(n,this._opts.inlineRefs)?n:s.call(this,n,e,void 0,i)),o}function us(s,e){var t=Lt.parse(e),a=so(t),r=is(this._getId(s.schema));if(Object.keys(s.schema).length===0||a!==r){var n=Or(a),o=this._refs[n];if(typeof o=="string")return pf.call(this,s,o,t);if(o instanceof os)o.validate||this._compile(o),s=o;else if(o=this._schemas[n],o instanceof os){if(o.validate||this._compile(o),n==Or(e))return{schema:o,root:s,baseId:r};s=o}else return;if(!s.schema)return;r=is(this._getId(s.schema))}return to.call(this,t,r,s.schema,s)}function pf(s,e,t){var a=us.call(this,s,e);if(a){var r=a.schema,n=a.baseId;s=a.root;var o=this._getId(r);return o&&(n=cs(n,o)),to.call(this,t,n,r,s)}}var hf=ls.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function to(s,e,t,a){if(s.fragment=s.fragment||"",s.fragment.slice(0,1)=="/"){for(var r=s.fragment.split("/"),n=1;n{"use strict";var Pa=ds();oo.exports={Validation:no(_f),MissingRef:no(wa)};function _f(s){this.message="validation failed",this.errors=s,this.ajv=this.validation=!0}wa.message=function(s,e){return"can't resolve reference "+e+" from id "+s};function wa(s,e,t){this.message=t||wa.message(s,e),this.missingRef=Pa.url(s,e),this.missingSchema=Pa.normalizeId(Pa.fullPath(this.missingRef))}function no(s){return s.prototype=Object.create(Error.prototype),s.prototype.constructor=s,s}});var Oa=z((Em,io)=>{"use strict";io.exports=function(s,e){e||(e={}),typeof e=="function"&&(e={cmp:e});var t=typeof e.cycles=="boolean"?e.cycles:!1,a=e.cmp&&function(n){return function(o){return function(i,l){var u={key:i,value:o[i]},f={key:l,value:o[l]};return n(u,f)}}}(e.cmp),r=[];return function n(o){if(o&&o.toJSON&&typeof o.toJSON=="function"&&(o=o.toJSON()),o!==void 0){if(typeof o=="number")return isFinite(o)?""+o:"null";if(typeof o!="object")return JSON.stringify(o);var i,l;if(Array.isArray(o)){for(l="[",i=0;i{"use strict";co.exports=function(e,t,a){var r="",n=e.schema.$async===!0,o=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),i=e.self._getId(e.schema);if(e.opts.strictKeywords){var l=e.util.schemaUnknownRules(e.schema,e.RULES.keywords);if(l){var u="unknown keyword: "+l;if(e.opts.strictKeywords==="log")e.logger.warn(u);else throw new Error(u)}}if(e.isTop&&(r+=" var validate = ",n&&(e.async=!0,r+="async "),r+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",i&&(e.opts.sourceCode||e.opts.processCode)&&(r+=" "+("/*# sourceURL="+i+" */")+" ")),typeof e.schema=="boolean"||!(o||e.schema.$ref)){var t="false schema",f=e.level,h=e.dataLevel,_=e.schema[t],d=e.schemaPath+e.util.getProperty(t),m=e.errSchemaPath+"/"+t,N=!e.opts.allErrors,q,y="data"+(h||""),P="valid"+f;if(e.schema===!1){e.isTop?N=!0:r+=" var "+P+" = false; ";var v=v||[];v.push(r),r="",e.createErrors!==!1?(r+=" { keyword: '"+(q||"false schema")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(m)+" , params: {} ",e.opts.messages!==!1&&(r+=" , message: 'boolean schema is false' "),e.opts.verbose&&(r+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+y+" "),r+=" } "):r+=" {} ";var b=r;r=v.pop(),!e.compositeRule&&N?e.async?r+=" throw new ValidationError(["+b+"]); ":r+=" validate.errors = ["+b+"]; return false; ":r+=" var err = "+b+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else e.isTop?n?r+=" return data; ":r+=" validate.errors = null; return true; ":r+=" var "+P+" = true; ";return e.isTop&&(r+=" }; return validate; "),r}if(e.isTop){var T=e.isTop,f=e.level=0,h=e.dataLevel=0,y="data";if(e.rootId=e.resolve.fullPath(e.self._getId(e.root.schema)),e.baseId=e.baseId||e.rootId,delete e.isTop,e.dataPathArr=[""],e.schema.default!==void 0&&e.opts.useDefaults&&e.opts.strictDefaults){var R="default is ignored in the schema root";if(e.opts.strictDefaults==="log")e.logger.warn(R);else throw new Error(R)}r+=" var vErrors = null; ",r+=" var errors = 0; ",r+=" if (rootData === undefined) rootData = data; "}else{var f=e.level,h=e.dataLevel,y="data"+(h||"");if(i&&(e.baseId=e.resolve.url(e.baseId,i)),n&&!e.async)throw new Error("async schema in sync schema");r+=" var errs_"+f+" = errors;"}var P="valid"+f,N=!e.opts.allErrors,A="",H="",q,C=e.schema.type,U=Array.isArray(C);if(C&&e.opts.nullable&&e.schema.nullable===!0&&(U?C.indexOf("null")==-1&&(C=C.concat("null")):C!="null"&&(C=[C,"null"],U=!0)),U&&C.length==1&&(C=C[0],U=!1),e.schema.$ref&&o){if(e.opts.extendRefs=="fail")throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)');e.opts.extendRefs!==!0&&(o=!1,e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"'))}if(e.schema.$comment&&e.opts.$comment&&(r+=" "+e.RULES.all.$comment.code(e,"$comment")),C){if(e.opts.coerceTypes)var M=e.util.coerceToTypes(e.opts.coerceTypes,C);var F=e.RULES.types[C];if(M||U||F===!0||F&&!xe(F)){var d=e.schemaPath+".type",m=e.errSchemaPath+"/type",d=e.schemaPath+".type",m=e.errSchemaPath+"/type",I=U?"checkDataTypes":"checkDataType";if(r+=" if ("+e.util[I](C,y,e.opts.strictNumbers,!0)+") { ",M){var D="dataType"+f,j="coerced"+f;r+=" var "+D+" = typeof "+y+"; var "+j+" = undefined; ",e.opts.coerceTypes=="array"&&(r+=" if ("+D+" == 'object' && Array.isArray("+y+") && "+y+".length == 1) { "+y+" = "+y+"[0]; "+D+" = typeof "+y+"; if ("+e.util.checkDataType(e.schema.type,y,e.opts.strictNumbers)+") "+j+" = "+y+"; } "),r+=" if ("+j+" !== undefined) ; ";var ce=M;if(ce)for(var J,re=-1,K=ce.length-1;re{"use strict";var ps=ds(),ms=Yr(),uo=fs(),yf=Oa(),lo=Ia(),Ef=ms.ucs2length,bf=as(),Sf=uo.Validation;po.exports=Na;function Na(s,e,t,a){var r=this,n=this._opts,o=[void 0],i={},l=[],u={},f=[],h={},_=[];e=e||{schema:s,refVal:o,refs:i};var d=xf.call(this,s,e,a),m=this._compilations[d.index];if(d.compiling)return m.callValidate=R;var y=this._formats,v=this.RULES;try{var b=P(s,e,t,a);m.validate=b;var T=m.callValidate;return T&&(T.schema=b.schema,T.errors=null,T.refs=b.refs,T.refVal=b.refVal,T.root=b.root,T.$async=b.$async,n.sourceCode&&(T.source=b.source)),b}finally{Rf.call(this,s,e,a)}function R(){var I=m.validate,D=I.apply(this,arguments);return R.errors=I.errors,D}function P(I,D,j,ce){var J=!D||D&&D.schema==I;if(D.schema!=e.schema)return Na.call(r,I,D,j,ce);var re=I.$async===!0,K=lo({isTop:!0,schema:I,isRoot:J,baseId:ce,root:D,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:uo.MissingRef,RULES:v,validate:lo,util:ms,resolve:ps,resolveRef:N,usePattern:U,useDefault:M,useCustomRule:F,opts:n,formats:y,logger:r.logger,self:r});K=hs(o,wf)+hs(l,Tf)+hs(f,Pf)+hs(_,Of)+K,n.processCode&&(K=n.processCode(K,I));var B;try{var me=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",K);B=me(r,v,y,e,o,f,_,bf,Ef,Sf),o[0]=B}catch(Te){throw r.logger.error("Error compiling schema, function code:",K),Te}return B.schema=I,B.errors=null,B.refs=i,B.refVal=o,B.root=J?B:D,re&&(B.$async=!0),n.sourceCode===!0&&(B.source={code:K,patterns:l,defaults:f}),B}function N(I,D,j){D=ps.url(I,D);var ce=i[D],J,re;if(ce!==void 0)return J=o[ce],re="refVal["+ce+"]",C(J,re);if(!j&&e.refs){var K=e.refs[D];if(K!==void 0)return J=e.refVal[K],re=A(D,J),C(J,re)}re=A(D);var B=ps.call(r,P,e,D);if(B===void 0){var me=t&&t[D];me&&(B=ps.inlineRef(me,n.inlineRefs)?me:Na.call(r,me,e,t,I))}if(B===void 0)H(D);else return q(D,B),C(B,re)}function A(I,D){var j=o.length;return o[j]=D,i[I]=j,"refVal"+j}function H(I){delete i[I]}function q(I,D){var j=i[I];o[j]=D}function C(I,D){return typeof I=="object"||typeof I=="boolean"?{code:D,schema:I,inline:!0}:{code:D,$async:I&&!!I.$async}}function U(I){var D=u[I];return D===void 0&&(D=u[I]=l.length,l[D]=I),"pattern"+D}function M(I){switch(typeof I){case"boolean":case"number":return""+I;case"string":return ms.toQuotedString(I);case"object":if(I===null)return"null";var D=yf(I),j=h[D];return j===void 0&&(j=h[D]=f.length,f[j]=I),"default"+j}}function F(I,D,j,ce){if(r._opts.validateSchema!==!1){var J=I.definition.dependencies;if(J&&!J.every(function(Se){return Object.prototype.hasOwnProperty.call(j,Se)}))throw new Error("parent schema must have all required keywords: "+J.join(","));var re=I.definition.validateSchema;if(re){var K=re(D);if(!K){var B="keyword schema is invalid: "+r.errorsText(re.errors);if(r._opts.validateSchema=="log")r.logger.error(B);else throw new Error(B)}}}var me=I.definition.compile,Te=I.definition.inline,Ie=I.definition.macro,ae;if(me)ae=me.call(r,D,j,ce);else if(Ie)ae=Ie.call(r,D,j,ce),n.validateSchema!==!1&&r.validateSchema(ae,!0);else if(Te)ae=Te.call(r,ce,I.keyword,D,j);else if(ae=I.definition.validate,!ae)return;if(ae===void 0)throw new Error('custom keyword "'+I.keyword+'"failed to compile');var _e=_.length;return _[_e]=ae,{code:"customRule"+_e,validate:ae}}}function xf(s,e,t){var a=fo.call(this,s,e,t);return a>=0?{index:a,compiling:!0}:(a=this._compilations.length,this._compilations[a]={schema:s,root:e,baseId:t},{index:a,compiling:!1})}function Rf(s,e,t){var a=fo.call(this,s,e,t);a>=0&&this._compilations.splice(a,1)}function fo(s,e,t){for(var a=0;a{"use strict";var vs=mo.exports=function(){this._cache={}};vs.prototype.put=function(e,t){this._cache[e]=t};vs.prototype.get=function(e){return this._cache[e]};vs.prototype.del=function(e){delete this._cache[e]};vs.prototype.clear=function(){this._cache={}}});var Oo=z((Rm,wo)=>{"use strict";var If=Yr(),Nf=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Af=[0,31,28,31,30,31,30,31,31,30,31,30,31],Cf=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,go=/^(?=.{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,Df=/^(?:[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,$f=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,_o=/^(?:(?:[^\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,yo=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,Eo=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,bo=/^(?:\/(?:[^~/]|~0|~1)*)*$/,So=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,xo=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;wo.exports=gs;function gs(s){return s=s=="full"?"full":"fast",If.copy(gs[s])}gs.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\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,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":_o,url:yo,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,hostname:go,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:Po,uuid:Eo,"json-pointer":bo,"json-pointer-uri-fragment":So,"relative-json-pointer":xo};gs.full={date:Ro,time:To,"date-time":Ff,uri:Mf,"uri-reference":$f,"uri-template":_o,url:yo,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:go,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:Po,uuid:Eo,"json-pointer":bo,"json-pointer-uri-fragment":So,"relative-json-pointer":xo};function kf(s){return s%4===0&&(s%100!==0||s%400===0)}function Ro(s){var e=s.match(Nf);if(!e)return!1;var t=+e[1],a=+e[2],r=+e[3];return a>=1&&a<=12&&r>=1&&r<=(a==2&&kf(t)?29:Af[a])}function To(s,e){var t=s.match(Cf);if(!t)return!1;var a=t[1],r=t[2],n=t[3],o=t[5];return(a<=23&&r<=59&&n<=59||a==23&&r==59&&n==60)&&(!e||o)}var Lf=/t|\s/i;function Ff(s){var e=s.split(Lf);return e.length==2&&Ro(e[0])&&To(e[1],!0)}var jf=/\/|:/;function Mf(s){return jf.test(s)&&Df.test(s)}var qf=/[^\\]\\Z/;function Po(s){if(qf.test(s))return!1;try{return new RegExp(s),!0}catch{return!1}}});var No=z((Tm,Io)=>{"use strict";Io.exports=function(e,t,a){var r=" ",n=e.level,o=e.dataLevel,i=e.schema[t],l=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,f="data"+(o||""),h="valid"+n,_,d;if(i=="#"||i=="#/")e.isRoot?(_=e.async,d="validate"):(_=e.root.schema.$async===!0,d="root.refVal[0]");else{var m=e.resolveRef(e.baseId,i,e.isRoot);if(m===void 0){var y=e.MissingRefError.message(e.baseId,i);if(e.opts.missingRefs=="fail"){e.logger.error(y);var v=v||[];v.push(r),r="",e.createErrors!==!1?(r+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { ref: '"+e.util.escapeQuotes(i)+"' } ",e.opts.messages!==!1&&(r+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(i)+"' "),e.opts.verbose&&(r+=" , schema: "+e.util.toQuotedString(i)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),r+=" } "):r+=" {} ";var b=r;r=v.pop(),!e.compositeRule&&u?e.async?r+=" throw new ValidationError(["+b+"]); ":r+=" validate.errors = ["+b+"]; return false; ":r+=" var err = "+b+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u&&(r+=" if (false) { ")}else if(e.opts.missingRefs=="ignore")e.logger.warn(y),u&&(r+=" if (true) { ");else throw new e.MissingRefError(e.baseId,i,y)}else if(m.inline){var T=e.util.copy(e);T.level++;var R="valid"+T.level;T.schema=m.schema,T.schemaPath="",T.errSchemaPath=i;var P=e.validate(T).replace(/validate\.schema/g,m.code);r+=" "+P+" ",u&&(r+=" if ("+R+") { ")}else _=m.$async===!0||e.async&&m.$async!==!1,d=m.code}if(d){var v=v||[];v.push(r),r="",e.opts.passContext?r+=" "+d+".call(this, ":r+=" "+d+"( ",r+=" "+f+", (dataPath || '')",e.errorPath!='""'&&(r+=" + "+e.errorPath);var N=o?"data"+(o-1||""):"parentData",A=o?e.dataPathArr[o]:"parentDataProperty";r+=" , "+N+" , "+A+", rootData) ";var H=r;if(r=v.pop(),_){if(!e.async)throw new Error("async schema referenced by sync schema");u&&(r+=" var "+h+"; "),r+=" try { await "+H+"; ",u&&(r+=" "+h+" = true; "),r+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",u&&(r+=" "+h+" = false; "),r+=" } ",u&&(r+=" if ("+h+") { ")}else r+=" if (!"+H+") { if (vErrors === null) vErrors = "+d+".errors; else vErrors = vErrors.concat("+d+".errors); errors = vErrors.length; } ",u&&(r+=" else { ")}return r}});var Co=z((Pm,Ao)=>{"use strict";Ao.exports=function(e,t,a){var r=" ",n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),i=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u=e.util.copy(e),f="";u.level++;var h="valid"+u.level,_=u.baseId,d=!0,m=n;if(m)for(var y,v=-1,b=m.length-1;v0||y===!1:e.util.schemaHasRules(y,e.RULES.all))&&(d=!1,u.schema=y,u.schemaPath=o+"["+v+"]",u.errSchemaPath=i+"/"+v,r+=" "+e.validate(u)+" ",u.baseId=_,l&&(r+=" if ("+h+") { ",f+="}"));return l&&(d?r+=" if (true) { ":r+=" "+f.slice(0,-1)+" "),r}});var $o=z((wm,Do)=>{"use strict";Do.exports=function(e,t,a){var r=" ",n=e.level,o=e.dataLevel,i=e.schema[t],l=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,h="data"+(o||""),_="valid"+n,d="errs__"+n,m=e.util.copy(e),y="";m.level++;var v="valid"+m.level,b=i.every(function(q){return e.opts.strictKeywords?typeof q=="object"&&Object.keys(q).length>0||q===!1:e.util.schemaHasRules(q,e.RULES.all)});if(b){var T=m.baseId;r+=" var "+d+" = errors; var "+_+" = false; ";var R=e.compositeRule;e.compositeRule=m.compositeRule=!0;var P=i;if(P)for(var N,A=-1,H=P.length-1;A{"use strict";ko.exports=function(e,t,a){var r=" ",n=e.schema[t],o=e.errSchemaPath+"/"+t,i=!e.opts.allErrors,l=e.util.toQuotedString(n);return e.opts.$comment===!0?r+=" console.log("+l+");":typeof e.opts.$comment=="function"&&(r+=" self._opts.$comment("+l+", "+e.util.toQuotedString(o)+", validate.root.schema);"),r}});var jo=z((Im,Fo)=>{"use strict";Fo.exports=function(e,t,a){var r=" ",n=e.level,o=e.dataLevel,i=e.schema[t],l=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,h="data"+(o||""),_="valid"+n,d=e.opts.$data&&i&&i.$data,m;d?(r+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",m="schema"+n):m=i,d||(r+=" var schema"+n+" = validate.schema"+l+";"),r+="var "+_+" = equal("+h+", schema"+n+"); if (!"+_+") { ";var y=y||[];y.push(r),r="",e.createErrors!==!1?(r+=" { keyword: 'const' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { allowedValue: schema"+n+" } ",e.opts.messages!==!1&&(r+=" , message: 'should be equal to constant' "),e.opts.verbose&&(r+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ";var v=r;return r=y.pop(),!e.compositeRule&&f?e.async?r+=" throw new ValidationError(["+v+"]); ":r+=" validate.errors = ["+v+"]; return false; ":r+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",r+=" }",f&&(r+=" else { "),r}});var qo=z((Nm,Mo)=>{"use strict";Mo.exports=function(e,t,a){var r=" ",n=e.level,o=e.dataLevel,i=e.schema[t],l=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,h="data"+(o||""),_="valid"+n,d="errs__"+n,m=e.util.copy(e),y="";m.level++;var v="valid"+m.level,b="i"+n,T=m.dataLevel=e.dataLevel+1,R="data"+T,P=e.baseId,N=e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all);if(r+="var "+d+" = errors;var "+_+";",N){var A=e.compositeRule;e.compositeRule=m.compositeRule=!0,m.schema=i,m.schemaPath=l,m.errSchemaPath=u,r+=" var "+v+" = false; for (var "+b+" = 0; "+b+" < "+h+".length; "+b+"++) { ",m.errorPath=e.util.getPathExpr(e.errorPath,b,e.opts.jsonPointers,!0);var H=h+"["+b+"]";m.dataPathArr[T]=b;var q=e.validate(m);m.baseId=P,e.util.varOccurences(q,R)<2?r+=" "+e.util.varReplace(q,R,H)+" ":r+=" var "+R+" = "+H+"; "+q+" ",r+=" if ("+v+") break; } ",e.compositeRule=m.compositeRule=A,r+=" "+y+" if (!"+v+") {"}else r+=" if ("+h+".length == 0) {";var C=C||[];C.push(r),r="",e.createErrors!==!1?(r+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(r+=" , message: 'should contain a valid item' "),e.opts.verbose&&(r+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ";var U=r;return r=C.pop(),!e.compositeRule&&f?e.async?r+=" throw new ValidationError(["+U+"]); ":r+=" validate.errors = ["+U+"]; return false; ":r+=" var err = "+U+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",r+=" } else { ",N&&(r+=" errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; } "),e.opts.allErrors&&(r+=" } "),r}});var Vo=z((Am,Uo)=>{"use strict";Uo.exports=function(e,t,a){var r=" ",n=e.level,o=e.dataLevel,i=e.schema[t],l=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,h="data"+(o||""),_="errs__"+n,d=e.util.copy(e),m="";d.level++;var y="valid"+d.level,v={},b={},T=e.opts.ownProperties;for(A in i)if(A!="__proto__"){var R=i[A],P=Array.isArray(R)?b:v;P[A]=R}r+="var "+_+" = errors;";var N=e.errorPath;r+="var missing"+n+";";for(var A in b)if(P=b[A],P.length){if(r+=" if ( "+h+e.util.getProperty(A)+" !== undefined ",T&&(r+=" && Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(A)+"') "),f){r+=" && ( ";var H=P;if(H)for(var q,C=-1,U=H.length-1;C0||R===!1:e.util.schemaHasRules(R,e.RULES.all))&&(r+=" "+y+" = true; if ( "+h+e.util.getProperty(A)+" !== undefined ",T&&(r+=" && Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(A)+"') "),r+=") { ",d.schema=R,d.schemaPath=l+e.util.getProperty(A),d.errSchemaPath=u+"/"+e.util.escapeFragment(A),r+=" "+e.validate(d)+" ",d.baseId=B,r+=" } ",f&&(r+=" if ("+y+") { ",m+="}"))}return f&&(r+=" "+m+" if ("+_+" == errors) {"),r}});var Ho=z((Cm,zo)=>{"use strict";zo.exports=function(e,t,a){var r=" ",n=e.level,o=e.dataLevel,i=e.schema[t],l=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,h="data"+(o||""),_="valid"+n,d=e.opts.$data&&i&&i.$data,m;d?(r+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",m="schema"+n):m=i;var y="i"+n,v="schema"+n;d||(r+=" var "+v+" = validate.schema"+l+";"),r+="var "+_+";",d&&(r+=" if (schema"+n+" === undefined) "+_+" = true; else if (!Array.isArray(schema"+n+")) "+_+" = false; else {"),r+=""+_+" = false;for (var "+y+"=0; "+y+"<"+v+".length; "+y+"++) if (equal("+h+", "+v+"["+y+"])) { "+_+" = true; break; }",d&&(r+=" } "),r+=" if (!"+_+") { ";var b=b||[];b.push(r),r="",e.createErrors!==!1?(r+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { allowedValues: schema"+n+" } ",e.opts.messages!==!1&&(r+=" , message: 'should be equal to one of the allowed values' "),e.opts.verbose&&(r+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ";var T=r;return r=b.pop(),!e.compositeRule&&f?e.async?r+=" throw new ValidationError(["+T+"]); ":r+=" validate.errors = ["+T+"]; return false; ":r+=" var err = "+T+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",r+=" }",f&&(r+=" else { "),r}});var Zo=z((Dm,Bo)=>{"use strict";Bo.exports=function(e,t,a){var r=" ",n=e.level,o=e.dataLevel,i=e.schema[t],l=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,h="data"+(o||"");if(e.opts.format===!1)return f&&(r+=" if (true) { "),r;var _=e.opts.$data&&i&&i.$data,d;_?(r+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+n):d=i;var m=e.opts.unknownFormats,y=Array.isArray(m);if(_){var v="format"+n,b="isObject"+n,T="formatType"+n;r+=" var "+v+" = formats["+d+"]; var "+b+" = typeof "+v+" == 'object' && !("+v+" instanceof RegExp) && "+v+".validate; var "+T+" = "+b+" && "+v+".type || 'string'; if ("+b+") { ",e.async&&(r+=" var async"+n+" = "+v+".async; "),r+=" "+v+" = "+v+".validate; } if ( ",_&&(r+=" ("+d+" !== undefined && typeof "+d+" != 'string') || "),r+=" (",m!="ignore"&&(r+=" ("+d+" && !"+v+" ",y&&(r+=" && self._opts.unknownFormats.indexOf("+d+") == -1 "),r+=") || "),r+=" ("+v+" && "+T+" == '"+a+"' && !(typeof "+v+" == 'function' ? ",e.async?r+=" (async"+n+" ? await "+v+"("+h+") : "+v+"("+h+")) ":r+=" "+v+"("+h+") ",r+=" : "+v+".test("+h+"))))) {"}else{var v=e.formats[i];if(!v){if(m=="ignore")return e.logger.warn('unknown format "'+i+'" ignored in schema at path "'+e.errSchemaPath+'"'),f&&(r+=" if (true) { "),r;if(y&&m.indexOf(i)>=0)return f&&(r+=" if (true) { "),r;throw new Error('unknown format "'+i+'" is used in schema at path "'+e.errSchemaPath+'"')}var b=typeof v=="object"&&!(v instanceof RegExp)&&v.validate,T=b&&v.type||"string";if(b){var R=v.async===!0;v=v.validate}if(T!=a)return f&&(r+=" if (true) { "),r;if(R){if(!e.async)throw new Error("async format in sync schema");var P="formats"+e.util.getProperty(i)+".validate";r+=" if (!(await "+P+"("+h+"))) { "}else{r+=" if (! ";var P="formats"+e.util.getProperty(i);b&&(P+=".validate"),typeof v=="function"?r+=" "+P+"("+h+") ":r+=" "+P+".test("+h+") ",r+=") { "}}var N=N||[];N.push(r),r="",e.createErrors!==!1?(r+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { format: ",_?r+=""+d:r+=""+e.util.toQuotedString(i),r+=" } ",e.opts.messages!==!1&&(r+=` , message: 'should match format "`,_?r+="' + "+d+" + '":r+=""+e.util.escapeQuotes(i),r+=`"' `),e.opts.verbose&&(r+=" , schema: ",_?r+="validate.schema"+l:r+=""+e.util.toQuotedString(i),r+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ";var A=r;return r=N.pop(),!e.compositeRule&&f?e.async?r+=" throw new ValidationError(["+A+"]); ":r+=" validate.errors = ["+A+"]; return false; ":r+=" var err = "+A+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",r+=" } ",f&&(r+=" else { "),r}});var Xo=z(($m,Go)=>{"use strict";Go.exports=function(e,t,a){var r=" ",n=e.level,o=e.dataLevel,i=e.schema[t],l=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,h="data"+(o||""),_="valid"+n,d="errs__"+n,m=e.util.copy(e);m.level++;var y="valid"+m.level,v=e.schema.then,b=e.schema.else,T=v!==void 0&&(e.opts.strictKeywords?typeof v=="object"&&Object.keys(v).length>0||v===!1:e.util.schemaHasRules(v,e.RULES.all)),R=b!==void 0&&(e.opts.strictKeywords?typeof b=="object"&&Object.keys(b).length>0||b===!1:e.util.schemaHasRules(b,e.RULES.all)),P=m.baseId;if(T||R){var N;m.createErrors=!1,m.schema=i,m.schemaPath=l,m.errSchemaPath=u,r+=" var "+d+" = errors; var "+_+" = true; ";var A=e.compositeRule;e.compositeRule=m.compositeRule=!0,r+=" "+e.validate(m)+" ",m.baseId=P,m.createErrors=!0,r+=" errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; } ",e.compositeRule=m.compositeRule=A,T?(r+=" if ("+y+") { ",m.schema=e.schema.then,m.schemaPath=e.schemaPath+".then",m.errSchemaPath=e.errSchemaPath+"/then",r+=" "+e.validate(m)+" ",m.baseId=P,r+=" "+_+" = "+y+"; ",T&&R?(N="ifClause"+n,r+=" var "+N+" = 'then'; "):N="'then'",r+=" } ",R&&(r+=" else { ")):r+=" if (!"+y+") { ",R&&(m.schema=e.schema.else,m.schemaPath=e.schemaPath+".else",m.errSchemaPath=e.errSchemaPath+"/else",r+=" "+e.validate(m)+" ",m.baseId=P,r+=" "+_+" = "+y+"; ",T&&R?(N="ifClause"+n,r+=" var "+N+" = 'else'; "):N="'else'",r+=" } "),r+=" if (!"+_+") { var err = ",e.createErrors!==!1?(r+=" { keyword: 'if' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { failingKeyword: "+N+" } ",e.opts.messages!==!1&&(r+=` , message: 'should match "' + `+N+` + '" schema' `),e.opts.verbose&&(r+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ",r+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&f&&(e.async?r+=" throw new ValidationError(vErrors); ":r+=" validate.errors = vErrors; return false; "),r+=" } ",f&&(r+=" else { ")}else f&&(r+=" if (true) { ");return r}});var Wo=z((km,Qo)=>{"use strict";Qo.exports=function(e,t,a){var r=" ",n=e.level,o=e.dataLevel,i=e.schema[t],l=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,h="data"+(o||""),_="valid"+n,d="errs__"+n,m=e.util.copy(e),y="";m.level++;var v="valid"+m.level,b="i"+n,T=m.dataLevel=e.dataLevel+1,R="data"+T,P=e.baseId;if(r+="var "+d+" = errors;var "+_+";",Array.isArray(i)){var N=e.schema.additionalItems;if(N===!1){r+=" "+_+" = "+h+".length <= "+i.length+"; ";var A=u;u=e.errSchemaPath+"/additionalItems",r+=" if (!"+_+") { ";var H=H||[];H.push(r),r="",e.createErrors!==!1?(r+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+i.length+" } ",e.opts.messages!==!1&&(r+=" , message: 'should NOT have more than "+i.length+" items' "),e.opts.verbose&&(r+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ";var q=r;r=H.pop(),!e.compositeRule&&f?e.async?r+=" throw new ValidationError(["+q+"]); ":r+=" validate.errors = ["+q+"]; return false; ":r+=" var err = "+q+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",r+=" } ",u=A,f&&(y+="}",r+=" else { ")}var C=i;if(C){for(var U,M=-1,F=C.length-1;M0||U===!1:e.util.schemaHasRules(U,e.RULES.all)){r+=" "+v+" = true; if ("+h+".length > "+M+") { ";var I=h+"["+M+"]";m.schema=U,m.schemaPath=l+"["+M+"]",m.errSchemaPath=u+"/"+M,m.errorPath=e.util.getPathExpr(e.errorPath,M,e.opts.jsonPointers,!0),m.dataPathArr[T]=M;var D=e.validate(m);m.baseId=P,e.util.varOccurences(D,R)<2?r+=" "+e.util.varReplace(D,R,I)+" ":r+=" var "+R+" = "+I+"; "+D+" ",r+=" } ",f&&(r+=" if ("+v+") { ",y+="}")}}if(typeof N=="object"&&(e.opts.strictKeywords?typeof N=="object"&&Object.keys(N).length>0||N===!1:e.util.schemaHasRules(N,e.RULES.all))){m.schema=N,m.schemaPath=e.schemaPath+".additionalItems",m.errSchemaPath=e.errSchemaPath+"/additionalItems",r+=" "+v+" = true; if ("+h+".length > "+i.length+") { for (var "+b+" = "+i.length+"; "+b+" < "+h+".length; "+b+"++) { ",m.errorPath=e.util.getPathExpr(e.errorPath,b,e.opts.jsonPointers,!0);var I=h+"["+b+"]";m.dataPathArr[T]=b;var D=e.validate(m);m.baseId=P,e.util.varOccurences(D,R)<2?r+=" "+e.util.varReplace(D,R,I)+" ":r+=" var "+R+" = "+I+"; "+D+" ",f&&(r+=" if (!"+v+") break; "),r+=" } } ",f&&(r+=" if ("+v+") { ",y+="}")}}else if(e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){m.schema=i,m.schemaPath=l,m.errSchemaPath=u,r+=" for (var "+b+" = 0; "+b+" < "+h+".length; "+b+"++) { ",m.errorPath=e.util.getPathExpr(e.errorPath,b,e.opts.jsonPointers,!0);var I=h+"["+b+"]";m.dataPathArr[T]=b;var D=e.validate(m);m.baseId=P,e.util.varOccurences(D,R)<2?r+=" "+e.util.varReplace(D,R,I)+" ":r+=" var "+R+" = "+I+"; "+D+" ",f&&(r+=" if (!"+v+") break; "),r+=" }"}return f&&(r+=" "+y+" if ("+d+" == errors) {"),r}});var Aa=z((Lm,Ko)=>{"use strict";Ko.exports=function(e,t,a){var r=" ",n=e.level,o=e.dataLevel,i=e.schema[t],l=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,P,h="data"+(o||""),_=e.opts.$data&&i&&i.$data,d;_?(r+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+n):d=i;var m=t=="maximum",y=m?"exclusiveMaximum":"exclusiveMinimum",v=e.schema[y],b=e.opts.$data&&v&&v.$data,T=m?"<":">",R=m?">":"<",P=void 0;if(!(_||typeof i=="number"||i===void 0))throw new Error(t+" must be number");if(!(b||v===void 0||typeof v=="number"||typeof v=="boolean"))throw new Error(y+" must be number or boolean");if(b){var N=e.util.getData(v.$data,o,e.dataPathArr),A="exclusive"+n,H="exclType"+n,q="exclIsNumber"+n,C="op"+n,U="' + "+C+" + '";r+=" var schemaExcl"+n+" = "+N+"; ",N="schemaExcl"+n,r+=" var "+A+"; var "+H+" = typeof "+N+"; if ("+H+" != 'boolean' && "+H+" != 'undefined' && "+H+" != 'number') { ";var P=y,M=M||[];M.push(r),r="",e.createErrors!==!1?(r+=" { keyword: '"+(P||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(r+=" , message: '"+y+" should be boolean' "),e.opts.verbose&&(r+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ";var F=r;r=M.pop(),!e.compositeRule&&f?e.async?r+=" throw new ValidationError(["+F+"]); ":r+=" validate.errors = ["+F+"]; return false; ":r+=" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",r+=" } else if ( ",_&&(r+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),r+=" "+H+" == 'number' ? ( ("+A+" = "+d+" === undefined || "+N+" "+T+"= "+d+") ? "+h+" "+R+"= "+N+" : "+h+" "+R+" "+d+" ) : ( ("+A+" = "+N+" === true) ? "+h+" "+R+"= "+d+" : "+h+" "+R+" "+d+" ) || "+h+" !== "+h+") { var op"+n+" = "+A+" ? '"+T+"' : '"+T+"='; ",i===void 0&&(P=y,u=e.errSchemaPath+"/"+y,d=N,_=b)}else{var q=typeof v=="number",U=T;if(q&&_){var C="'"+U+"'";r+=" if ( ",_&&(r+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),r+=" ( "+d+" === undefined || "+v+" "+T+"= "+d+" ? "+h+" "+R+"= "+v+" : "+h+" "+R+" "+d+" ) || "+h+" !== "+h+") { "}else{q&&i===void 0?(A=!0,P=y,u=e.errSchemaPath+"/"+y,d=v,R+="="):(q&&(d=Math[m?"min":"max"](v,i)),v===(q?d:!0)?(A=!0,P=y,u=e.errSchemaPath+"/"+y,R+="="):(A=!1,U+="="));var C="'"+U+"'";r+=" if ( ",_&&(r+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),r+=" "+h+" "+R+" "+d+" || "+h+" !== "+h+") { "}}P=P||t;var M=M||[];M.push(r),r="",e.createErrors!==!1?(r+=" { keyword: '"+(P||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { comparison: "+C+", limit: "+d+", exclusive: "+A+" } ",e.opts.messages!==!1&&(r+=" , message: 'should be "+U+" ",_?r+="' + "+d:r+=""+d+"'"),e.opts.verbose&&(r+=" , schema: ",_?r+="validate.schema"+l:r+=""+i,r+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ";var F=r;return r=M.pop(),!e.compositeRule&&f?e.async?r+=" throw new ValidationError(["+F+"]); ":r+=" validate.errors = ["+F+"]; return false; ":r+=" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",r+=" } ",f&&(r+=" else { "),r}});var Ca=z((Fm,Jo)=>{"use strict";Jo.exports=function(e,t,a){var r=" ",n=e.level,o=e.dataLevel,i=e.schema[t],l=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,y,h="data"+(o||""),_=e.opts.$data&&i&&i.$data,d;if(_?(r+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+n):d=i,!(_||typeof i=="number"))throw new Error(t+" must be number");var m=t=="maxItems"?">":"<";r+="if ( ",_&&(r+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),r+=" "+h+".length "+m+" "+d+") { ";var y=t,v=v||[];v.push(r),r="",e.createErrors!==!1?(r+=" { keyword: '"+(y||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+d+" } ",e.opts.messages!==!1&&(r+=" , message: 'should NOT have ",t=="maxItems"?r+="more":r+="fewer",r+=" than ",_?r+="' + "+d+" + '":r+=""+i,r+=" items' "),e.opts.verbose&&(r+=" , schema: ",_?r+="validate.schema"+l:r+=""+i,r+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ";var b=r;return r=v.pop(),!e.compositeRule&&f?e.async?r+=" throw new ValidationError(["+b+"]); ":r+=" validate.errors = ["+b+"]; return false; ":r+=" var err = "+b+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",r+="} ",f&&(r+=" else { "),r}});var Da=z((jm,Yo)=>{"use strict";Yo.exports=function(e,t,a){var r=" ",n=e.level,o=e.dataLevel,i=e.schema[t],l=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,y,h="data"+(o||""),_=e.opts.$data&&i&&i.$data,d;if(_?(r+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+n):d=i,!(_||typeof i=="number"))throw new Error(t+" must be number");var m=t=="maxLength"?">":"<";r+="if ( ",_&&(r+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),e.opts.unicode===!1?r+=" "+h+".length ":r+=" ucs2length("+h+") ",r+=" "+m+" "+d+") { ";var y=t,v=v||[];v.push(r),r="",e.createErrors!==!1?(r+=" { keyword: '"+(y||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+d+" } ",e.opts.messages!==!1&&(r+=" , message: 'should NOT be ",t=="maxLength"?r+="longer":r+="shorter",r+=" than ",_?r+="' + "+d+" + '":r+=""+i,r+=" characters' "),e.opts.verbose&&(r+=" , schema: ",_?r+="validate.schema"+l:r+=""+i,r+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ";var b=r;return r=v.pop(),!e.compositeRule&&f?e.async?r+=" throw new ValidationError(["+b+"]); ":r+=" validate.errors = ["+b+"]; return false; ":r+=" var err = "+b+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",r+="} ",f&&(r+=" else { "),r}});var $a=z((Mm,ei)=>{"use strict";ei.exports=function(e,t,a){var r=" ",n=e.level,o=e.dataLevel,i=e.schema[t],l=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,y,h="data"+(o||""),_=e.opts.$data&&i&&i.$data,d;if(_?(r+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+n):d=i,!(_||typeof i=="number"))throw new Error(t+" must be number");var m=t=="maxProperties"?">":"<";r+="if ( ",_&&(r+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),r+=" Object.keys("+h+").length "+m+" "+d+") { ";var y=t,v=v||[];v.push(r),r="",e.createErrors!==!1?(r+=" { keyword: '"+(y||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+d+" } ",e.opts.messages!==!1&&(r+=" , message: 'should NOT have ",t=="maxProperties"?r+="more":r+="fewer",r+=" than ",_?r+="' + "+d+" + '":r+=""+i,r+=" properties' "),e.opts.verbose&&(r+=" , schema: ",_?r+="validate.schema"+l:r+=""+i,r+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ";var b=r;return r=v.pop(),!e.compositeRule&&f?e.async?r+=" throw new ValidationError(["+b+"]); ":r+=" validate.errors = ["+b+"]; return false; ":r+=" var err = "+b+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",r+="} ",f&&(r+=" else { "),r}});var ti=z((qm,ri)=>{"use strict";ri.exports=function(e,t,a){var r=" ",n=e.level,o=e.dataLevel,i=e.schema[t],l=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,h="data"+(o||""),_=e.opts.$data&&i&&i.$data,d;if(_?(r+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+n):d=i,!(_||typeof i=="number"))throw new Error(t+" must be number");r+="var division"+n+";if (",_&&(r+=" "+d+" !== undefined && ( typeof "+d+" != 'number' || "),r+=" (division"+n+" = "+h+" / "+d+", ",e.opts.multipleOfPrecision?r+=" Math.abs(Math.round(division"+n+") - division"+n+") > 1e-"+e.opts.multipleOfPrecision+" ":r+=" division"+n+" !== parseInt(division"+n+") ",r+=" ) ",_&&(r+=" ) "),r+=" ) { ";var m=m||[];m.push(r),r="",e.createErrors!==!1?(r+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { multipleOf: "+d+" } ",e.opts.messages!==!1&&(r+=" , message: 'should be multiple of ",_?r+="' + "+d:r+=""+d+"'"),e.opts.verbose&&(r+=" , schema: ",_?r+="validate.schema"+l:r+=""+i,r+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ";var y=r;return r=m.pop(),!e.compositeRule&&f?e.async?r+=" throw new ValidationError(["+y+"]); ":r+=" validate.errors = ["+y+"]; return false; ":r+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",r+="} ",f&&(r+=" else { "),r}});var ai=z((Um,si)=>{"use strict";si.exports=function(e,t,a){var r=" ",n=e.level,o=e.dataLevel,i=e.schema[t],l=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,h="data"+(o||""),_="errs__"+n,d=e.util.copy(e);d.level++;var m="valid"+d.level;if(e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){d.schema=i,d.schemaPath=l,d.errSchemaPath=u,r+=" var "+_+" = errors; ";var y=e.compositeRule;e.compositeRule=d.compositeRule=!0,d.createErrors=!1;var v;d.opts.allErrors&&(v=d.opts.allErrors,d.opts.allErrors=!1),r+=" "+e.validate(d)+" ",d.createErrors=!0,v&&(d.opts.allErrors=v),e.compositeRule=d.compositeRule=y,r+=" if ("+m+") { ";var b=b||[];b.push(r),r="",e.createErrors!==!1?(r+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(r+=" , message: 'should NOT be valid' "),e.opts.verbose&&(r+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ";var T=r;r=b.pop(),!e.compositeRule&&f?e.async?r+=" throw new ValidationError(["+T+"]); ":r+=" validate.errors = ["+T+"]; return false; ":r+=" var err = "+T+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",r+=" } else { errors = "+_+"; if (vErrors !== null) { if ("+_+") vErrors.length = "+_+"; else vErrors = null; } ",e.opts.allErrors&&(r+=" } ")}else r+=" var err = ",e.createErrors!==!1?(r+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(r+=" , message: 'should NOT be valid' "),e.opts.verbose&&(r+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ",r+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",f&&(r+=" if (false) { ");return r}});var oi=z((Vm,ni)=>{"use strict";ni.exports=function(e,t,a){var r=" ",n=e.level,o=e.dataLevel,i=e.schema[t],l=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,h="data"+(o||""),_="valid"+n,d="errs__"+n,m=e.util.copy(e),y="";m.level++;var v="valid"+m.level,b=m.baseId,T="prevValid"+n,R="passingSchemas"+n;r+="var "+d+" = errors , "+T+" = false , "+_+" = false , "+R+" = null; ";var P=e.compositeRule;e.compositeRule=m.compositeRule=!0;var N=i;if(N)for(var A,H=-1,q=N.length-1;H0||A===!1:e.util.schemaHasRules(A,e.RULES.all))?(m.schema=A,m.schemaPath=l+"["+H+"]",m.errSchemaPath=u+"/"+H,r+=" "+e.validate(m)+" ",m.baseId=b):r+=" var "+v+" = true; ",H&&(r+=" if ("+v+" && "+T+") { "+_+" = false; "+R+" = ["+R+", "+H+"]; } else { ",y+="}"),r+=" if ("+v+") { "+_+" = "+T+" = true; "+R+" = "+H+"; }";return e.compositeRule=m.compositeRule=P,r+=""+y+"if (!"+_+") { var err = ",e.createErrors!==!1?(r+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { passingSchemas: "+R+" } ",e.opts.messages!==!1&&(r+=" , message: 'should match exactly one schema in oneOf' "),e.opts.verbose&&(r+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ",r+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&f&&(e.async?r+=" throw new ValidationError(vErrors); ":r+=" validate.errors = vErrors; return false; "),r+="} else { errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; }",e.opts.allErrors&&(r+=" } "),r}});var ci=z((zm,ii)=>{"use strict";ii.exports=function(e,t,a){var r=" ",n=e.level,o=e.dataLevel,i=e.schema[t],l=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,h="data"+(o||""),_=e.opts.$data&&i&&i.$data,d;_?(r+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+n):d=i;var m=_?"(new RegExp("+d+"))":e.usePattern(i);r+="if ( ",_&&(r+=" ("+d+" !== undefined && typeof "+d+" != 'string') || "),r+=" !"+m+".test("+h+") ) { ";var y=y||[];y.push(r),r="",e.createErrors!==!1?(r+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { pattern: ",_?r+=""+d:r+=""+e.util.toQuotedString(i),r+=" } ",e.opts.messages!==!1&&(r+=` , message: 'should match pattern "`,_?r+="' + "+d+" + '":r+=""+e.util.escapeQuotes(i),r+=`"' `),e.opts.verbose&&(r+=" , schema: ",_?r+="validate.schema"+l:r+=""+e.util.toQuotedString(i),r+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ";var v=r;return r=y.pop(),!e.compositeRule&&f?e.async?r+=" throw new ValidationError(["+v+"]); ":r+=" validate.errors = ["+v+"]; return false; ":r+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",r+="} ",f&&(r+=" else { "),r}});var ui=z((Hm,li)=>{"use strict";li.exports=function(e,t,a){var r=" ",n=e.level,o=e.dataLevel,i=e.schema[t],l=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,h="data"+(o||""),_="errs__"+n,d=e.util.copy(e),m="";d.level++;var y="valid"+d.level,v="key"+n,b="idx"+n,T=d.dataLevel=e.dataLevel+1,R="data"+T,P="dataProperties"+n,N=Object.keys(i||{}).filter(re),A=e.schema.patternProperties||{},H=Object.keys(A).filter(re),q=e.schema.additionalProperties,C=N.length||H.length,U=q===!1,M=typeof q=="object"&&Object.keys(q).length,F=e.opts.removeAdditional,I=U||M||F,D=e.opts.ownProperties,j=e.baseId,ce=e.schema.required;if(ce&&!(e.opts.$data&&ce.$data)&&ce.length8)r+=" || validate.schema"+l+".hasOwnProperty("+v+") ";else{var K=N;if(K)for(var B,me=-1,Te=K.length-1;me0||xe===!1:e.util.schemaHasRules(xe,e.RULES.all)){var Ue=e.util.getProperty(B),Pe=h+Ue,$e=br&&xe.default!==void 0;d.schema=xe,d.schemaPath=l+Ue,d.errSchemaPath=u+"/"+e.util.escapeFragment(B),d.errorPath=e.util.getPath(e.errorPath,B,e.opts.jsonPointers),d.dataPathArr[T]=e.util.toQuotedString(B);var oe=e.validate(d);if(d.baseId=j,e.util.varOccurences(oe,R)<2){oe=e.util.varReplace(oe,R,Pe);var Ae=Pe}else{var Ae=R;r+=" var "+R+" = "+Pe+"; "}if($e)r+=" "+oe+" ";else{if(J&&J[B]){r+=" if ( "+Ae+" === undefined ",D&&(r+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(B)+"') "),r+=") { "+y+" = false; ";var Ne=e.errorPath,lr=u,rr=e.util.escapeQuotes(B);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(Ne,B,e.opts.jsonPointers)),u=e.errSchemaPath+"/required";var ye=ye||[];ye.push(r),r="",e.createErrors!==!1?(r+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+rr+"' } ",e.opts.messages!==!1&&(r+=" , message: '",e.opts._errorDataPathProperty?r+="is a required property":r+="should have required property \\'"+rr+"\\'",r+="' "),e.opts.verbose&&(r+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ";var ve=r;r=ye.pop(),!e.compositeRule&&f?e.async?r+=" throw new ValidationError(["+ve+"]); ":r+=" validate.errors = ["+ve+"]; return false; ":r+=" var err = "+ve+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u=lr,e.errorPath=Ne,r+=" } else { "}else f?(r+=" if ( "+Ae+" === undefined ",D&&(r+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(B)+"') "),r+=") { "+y+" = true; } else { "):(r+=" if ("+Ae+" !== undefined ",D&&(r+=" && Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(B)+"') "),r+=" ) { ");r+=" "+oe+" } "}}f&&(r+=" if ("+y+") { ",m+="}")}}if(H.length){var je=H;if(je)for(var ae,jt=-1,Ms=je.length-1;jt0||xe===!1:e.util.schemaHasRules(xe,e.RULES.all)){d.schema=xe,d.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty(ae),d.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment(ae),D?r+=" "+P+" = "+P+" || Object.keys("+h+"); for (var "+b+"=0; "+b+"<"+P+".length; "+b+"++) { var "+v+" = "+P+"["+b+"]; ":r+=" for (var "+v+" in "+h+") { ",r+=" if ("+e.usePattern(ae)+".test("+v+")) { ",d.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers);var Pe=h+"["+v+"]";d.dataPathArr[T]=v;var oe=e.validate(d);d.baseId=j,e.util.varOccurences(oe,R)<2?r+=" "+e.util.varReplace(oe,R,Pe)+" ":r+=" var "+R+" = "+Pe+"; "+oe+" ",f&&(r+=" if (!"+y+") break; "),r+=" } ",f&&(r+=" else "+y+" = true; "),r+=" } ",f&&(r+=" if ("+y+") { ",m+="}")}}}return f&&(r+=" "+m+" if ("+_+" == errors) {"),r}});var fi=z((Bm,di)=>{"use strict";di.exports=function(e,t,a){var r=" ",n=e.level,o=e.dataLevel,i=e.schema[t],l=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,h="data"+(o||""),_="errs__"+n,d=e.util.copy(e),m="";d.level++;var y="valid"+d.level;if(r+="var "+_+" = errors;",e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){d.schema=i,d.schemaPath=l,d.errSchemaPath=u;var v="key"+n,b="idx"+n,T="i"+n,R="' + "+v+" + '",P=d.dataLevel=e.dataLevel+1,N="data"+P,A="dataProperties"+n,H=e.opts.ownProperties,q=e.baseId;H&&(r+=" var "+A+" = undefined; "),H?r+=" "+A+" = "+A+" || Object.keys("+h+"); for (var "+b+"=0; "+b+"<"+A+".length; "+b+"++) { var "+v+" = "+A+"["+b+"]; ":r+=" for (var "+v+" in "+h+") { ",r+=" var startErrs"+n+" = errors; ";var C=v,U=e.compositeRule;e.compositeRule=d.compositeRule=!0;var M=e.validate(d);d.baseId=q,e.util.varOccurences(M,N)<2?r+=" "+e.util.varReplace(M,N,C)+" ":r+=" var "+N+" = "+C+"; "+M+" ",e.compositeRule=d.compositeRule=U,r+=" if (!"+y+") { for (var "+T+"=startErrs"+n+"; "+T+"{"use strict";pi.exports=function(e,t,a){var r=" ",n=e.level,o=e.dataLevel,i=e.schema[t],l=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,h="data"+(o||""),_="valid"+n,d=e.opts.$data&&i&&i.$data,m;d?(r+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",m="schema"+n):m=i;var y="schema"+n;if(!d)if(i.length0||N===!1:e.util.schemaHasRules(N,e.RULES.all))||(v[v.length]=T)}}else var v=i;if(d||v.length){var A=e.errorPath,H=d||v.length>=e.opts.loopRequired,q=e.opts.ownProperties;if(f)if(r+=" var missing"+n+"; ",H){d||(r+=" var "+y+" = validate.schema"+l+"; ");var C="i"+n,U="schema"+n+"["+C+"]",M="' + "+U+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(A,U,e.opts.jsonPointers)),r+=" var "+_+" = true; ",d&&(r+=" if (schema"+n+" === undefined) "+_+" = true; else if (!Array.isArray(schema"+n+")) "+_+" = false; else {"),r+=" for (var "+C+" = 0; "+C+" < "+y+".length; "+C+"++) { "+_+" = "+h+"["+y+"["+C+"]] !== undefined ",q&&(r+=" && Object.prototype.hasOwnProperty.call("+h+", "+y+"["+C+"]) "),r+="; if (!"+_+") break; } ",d&&(r+=" } "),r+=" if (!"+_+") { ";var F=F||[];F.push(r),r="",e.createErrors!==!1?(r+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+M+"' } ",e.opts.messages!==!1&&(r+=" , message: '",e.opts._errorDataPathProperty?r+="is a required property":r+="should have required property \\'"+M+"\\'",r+="' "),e.opts.verbose&&(r+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ";var I=r;r=F.pop(),!e.compositeRule&&f?e.async?r+=" throw new ValidationError(["+I+"]); ":r+=" validate.errors = ["+I+"]; return false; ":r+=" var err = "+I+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",r+=" } else { "}else{r+=" if ( ";var D=v;if(D)for(var j,C=-1,ce=D.length-1;C{"use strict";mi.exports=function(e,t,a){var r=" ",n=e.level,o=e.dataLevel,i=e.schema[t],l=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,h="data"+(o||""),_="valid"+n,d=e.opts.$data&&i&&i.$data,m;if(d?(r+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",m="schema"+n):m=i,(i||d)&&e.opts.uniqueItems!==!1){d&&(r+=" var "+_+"; if ("+m+" === false || "+m+" === undefined) "+_+" = true; else if (typeof "+m+" != 'boolean') "+_+" = false; else { "),r+=" var i = "+h+".length , "+_+" = true , j; if (i > 1) { ";var y=e.schema.items&&e.schema.items.type,v=Array.isArray(y);if(!y||y=="object"||y=="array"||v&&(y.indexOf("object")>=0||y.indexOf("array")>=0))r+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+h+"[i], "+h+"[j])) { "+_+" = false; break outer; } } } ";else{r+=" var itemIndices = {}, item; for (;i--;) { var item = "+h+"[i]; ";var b="checkDataType"+(v?"s":"");r+=" if ("+e.util[b](y,"item",e.opts.strictNumbers,!0)+") continue; ",v&&(r+=` if (typeof item == 'string') item = '"' + item; `),r+=" if (typeof itemIndices[item] == 'number') { "+_+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}r+=" } ",d&&(r+=" } "),r+=" if (!"+_+") { ";var T=T||[];T.push(r),r="",e.createErrors!==!1?(r+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { i: i, j: j } ",e.opts.messages!==!1&&(r+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(r+=" , schema: ",d?r+="validate.schema"+l:r+=""+i,r+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ";var R=r;r=T.pop(),!e.compositeRule&&f?e.async?r+=" throw new ValidationError(["+R+"]); ":r+=" validate.errors = ["+R+"]; return false; ":r+=" var err = "+R+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",r+=" } ",f&&(r+=" else { ")}else f&&(r+=" if (true) { ");return r}});var _i=z((Xm,gi)=>{"use strict";gi.exports={$ref:No(),allOf:Co(),anyOf:$o(),$comment:Lo(),const:jo(),contains:qo(),dependencies:Vo(),enum:Ho(),format:Zo(),if:Xo(),items:Wo(),maximum:Aa(),minimum:Aa(),maxItems:Ca(),minItems:Ca(),maxLength:Da(),minLength:Da(),maxProperties:$a(),minProperties:$a(),multipleOf:ti(),not:ai(),oneOf:oi(),pattern:ci(),properties:ui(),propertyNames:fi(),required:hi(),uniqueItems:vi(),validate:Ia()}});var bi=z((Qm,Ei)=>{"use strict";var yi=_i(),ka=Yr().toHash;Ei.exports=function(){var e=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}],t=["type","$comment"],a=["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"],r=["number","integer","string","array","object","boolean","null"];return e.all=ka(t),e.types=ka(r),e.forEach(function(n){n.rules=n.rules.map(function(o){var i;if(typeof o=="object"){var l=Object.keys(o)[0];i=o[l],o=l,i.forEach(function(f){t.push(f),e.all[f]=!0})}t.push(o);var u=e.all[o]={keyword:o,code:yi[o],implements:i};return u}),e.all.$comment={keyword:"$comment",code:yi.$comment},n.type&&(e.types[n.type]=n)}),e.keywords=ka(t.concat(a)),e.custom={},e}});var Ri=z((Wm,xi)=>{"use strict";var Si=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"];xi.exports=function(s,e){for(var t=0;t{"use strict";var Uf=fs().MissingRef;Pi.exports=Ti;function Ti(s,e,t){var a=this;if(typeof this._opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");typeof e=="function"&&(t=e,e=void 0);var r=n(s).then(function(){var i=a._addSchema(s,void 0,e);return i.validate||o(i)});return t&&r.then(function(i){t(null,i)},t),r;function n(i){var l=i.$schema;return l&&!a.getSchema(l)?Ti.call(a,{$ref:l},!0):Promise.resolve()}function o(i){try{return a._compile(i)}catch(u){if(u instanceof Uf)return l(u);throw u}function l(u){var f=u.missingSchema;if(d(f))throw new Error("Schema "+f+" is loaded but "+u.missingRef+" cannot be resolved");var h=a._loadingSchemas[f];return h||(h=a._loadingSchemas[f]=a._opts.loadSchema(f),h.then(_,_)),h.then(function(m){if(!d(f))return n(m).then(function(){d(f)||a.addSchema(m,f,void 0,e)})}).then(function(){return o(i)});function _(){delete a._loadingSchemas[f]}function d(m){return a._refs[m]||a._schemas[m]}}}}});var Ii=z((Jm,Oi)=>{"use strict";Oi.exports=function(e,t,a){var r=" ",n=e.level,o=e.dataLevel,i=e.schema[t],l=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,h,_="data"+(o||""),d="valid"+n,m="errs__"+n,y=e.opts.$data&&i&&i.$data,v;y?(r+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",v="schema"+n):v=i;var b=this,T="definition"+n,R=b.definition,P="",N,A,H,q,C;if(y&&R.$data){C="keywordValidate"+n;var U=R.validateSchema;r+=" var "+T+" = RULES.custom['"+t+"'].definition; var "+C+" = "+T+".validate;"}else{if(q=e.useCustomRule(b,i,e.schema,e),!q)return;v="validate.schema"+l,C=q.code,N=R.compile,A=R.inline,H=R.macro}var M=C+".errors",F="i"+n,I="ruleErr"+n,D=R.async;if(D&&!e.async)throw new Error("async keyword in sync schema");if(A||H||(r+=""+M+" = null;"),r+="var "+m+" = errors;var "+d+";",y&&R.$data&&(P+="}",r+=" if ("+v+" === undefined) { "+d+" = true; } else { ",U&&(P+="}",r+=" "+d+" = "+T+".validateSchema("+v+"); if ("+d+") { ")),A)R.statements?r+=" "+q.validate+" ":r+=" "+d+" = "+q.validate+"; ";else if(H){var j=e.util.copy(e),P="";j.level++;var ce="valid"+j.level;j.schema=q.validate,j.schemaPath="";var J=e.compositeRule;e.compositeRule=j.compositeRule=!0;var re=e.validate(j).replace(/validate\.schema/g,C);e.compositeRule=j.compositeRule=J,r+=" "+re}else{var K=K||[];K.push(r),r="",r+=" "+C+".call( ",e.opts.passContext?r+="this":r+="self",N||R.schema===!1?r+=" , "+_+" ":r+=" , "+v+" , "+_+" , validate.schema"+e.schemaPath+" ",r+=" , (dataPath || '')",e.errorPath!='""'&&(r+=" + "+e.errorPath);var B=o?"data"+(o-1||""):"parentData",me=o?e.dataPathArr[o]:"parentDataProperty";r+=" , "+B+" , "+me+" , rootData ) ";var Te=r;r=K.pop(),R.errors===!1?(r+=" "+d+" = ",D&&(r+="await "),r+=""+Te+"; "):D?(M="customErrors"+n,r+=" var "+M+" = null; try { "+d+" = await "+Te+"; } catch (e) { "+d+" = false; if (e instanceof ValidationError) "+M+" = e.errors; else throw e; } "):r+=" "+M+" = null; "+d+" = "+Te+"; "}if(R.modifying&&(r+=" if ("+B+") "+_+" = "+B+"["+me+"];"),r+=""+P,R.valid)f&&(r+=" if (true) { ");else{r+=" if ( ",R.valid===void 0?(r+=" !",H?r+=""+ce:r+=""+d):r+=" "+!R.valid+" ",r+=") { ",h=b.keyword;var K=K||[];K.push(r),r="";var K=K||[];K.push(r),r="",e.createErrors!==!1?(r+=" { keyword: '"+(h||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { keyword: '"+b.keyword+"' } ",e.opts.messages!==!1&&(r+=` , message: 'should pass "`+b.keyword+`" keyword validation' `),e.opts.verbose&&(r+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+_+" "),r+=" } "):r+=" {} ";var Ie=r;r=K.pop(),!e.compositeRule&&f?e.async?r+=" throw new ValidationError(["+Ie+"]); ":r+=" validate.errors = ["+Ie+"]; return false; ":r+=" var err = "+Ie+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";var ae=r;r=K.pop(),A?R.errors?R.errors!="full"&&(r+=" for (var "+F+"="+m+"; "+F+"{Vf.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 Ci=z((ev,Ai)=>{"use strict";var Ni=La();Ai.exports={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:Ni.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:Ni.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}}});var $i=z((rv,Di)=>{"use strict";var zf=/^[a-z_$][a-z0-9_$-]*$/i,Hf=Ii(),Bf=Ci();Di.exports={add:Zf,get:Gf,remove:Xf,validate:Fa};function Zf(s,e){var t=this.RULES;if(t.keywords[s])throw new Error("Keyword "+s+" is already defined");if(!zf.test(s))throw new Error("Keyword "+s+" is not a valid identifier");if(e){this.validateKeyword(e,!0);var a=e.type;if(Array.isArray(a))for(var r=0;r{Qf.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON Schema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Ma=z((sv,Hi)=>{"use strict";var Fi=ho(),et=ds(),Wf=vo(),ji=Sa(),Kf=Oa(),Jf=Oo(),Yf=bi(),Mi=Ri(),qi=Yr();Hi.exports=ge;ge.prototype.validate=rp;ge.prototype.compile=tp;ge.prototype.addSchema=sp;ge.prototype.addMetaSchema=ap;ge.prototype.validateSchema=np;ge.prototype.getSchema=ip;ge.prototype.removeSchema=lp;ge.prototype.addFormat=gp;ge.prototype.errorsText=vp;ge.prototype._addSchema=up;ge.prototype._compile=dp;ge.prototype.compileAsync=wi();var Es=$i();ge.prototype.addKeyword=Es.add;ge.prototype.getKeyword=Es.get;ge.prototype.removeKeyword=Es.remove;ge.prototype.validateKeyword=Es.validate;var Ui=fs();ge.ValidationError=Ui.Validation;ge.MissingRefError=Ui.MissingRef;ge.$dataMetaSchema=Mi;var ys="http://json-schema.org/draft-07/schema",Li=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],ep=["/properties"];function ge(s){if(!(this instanceof ge))return new ge(s);s=this._opts=qi.copy(s)||{},xp(this),this._schemas={},this._refs={},this._fragments={},this._formats=Jf(s.format),this._cache=s.cache||new Wf,this._loadingSchemas={},this._compilations=[],this.RULES=Yf(),this._getId=fp(s),s.loopRequired=s.loopRequired||1/0,s.errorDataPath=="property"&&(s._errorDataPathProperty=!0),s.serialize===void 0&&(s.serialize=Kf),this._metaOpts=Sp(this),s.formats&&Ep(this),s.keywords&&bp(this),_p(this),typeof s.meta=="object"&&this.addMetaSchema(s.meta),s.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),yp(this)}function rp(s,e){var t;if(typeof s=="string"){if(t=this.getSchema(s),!t)throw new Error('no schema with key or ref "'+s+'"')}else{var a=this._addSchema(s);t=a.validate||this._compile(a)}var r=t(e);return t.$async!==!0&&(this.errors=t.errors),r}function tp(s,e){var t=this._addSchema(s,void 0,e);return t.validate||this._compile(t)}function sp(s,e,t,a){if(Array.isArray(s)){for(var r=0;r{Ki.exports=Wi;Wi.sync=Pp;var Xi=Sr("fs");function Tp(s,e){var t=e.pathExt!==void 0?e.pathExt:process.env.PATHEXT;if(!t||(t=t.split(";"),t.indexOf("")!==-1))return!0;for(var a=0;a{tc.exports=ec;ec.sync=wp;var Yi=Sr("fs");function ec(s,e,t){Yi.stat(s,function(a,r){t(a,a?!1:rc(r,e))})}function wp(s,e){return rc(Yi.statSync(s),e)}function rc(s,e){return s.isFile()&&Op(s,e)}function Op(s,e){var t=s.mode,a=s.uid,r=s.gid,n=e.uid!==void 0?e.uid:process.getuid&&process.getuid(),o=e.gid!==void 0?e.gid:process.getgid&&process.getgid(),i=parseInt("100",8),l=parseInt("010",8),u=parseInt("001",8),f=i|l,h=t&u||t&l&&r===o||t&i&&a===n||t&f&&n===0;return h}});var nc=z((_v,ac)=>{var gv=Sr("fs"),Ts;process.platform==="win32"||global.TESTING_WINDOWS?Ts=Ji():Ts=sc();ac.exports=qa;qa.sync=Ip;function qa(s,e,t){if(typeof e=="function"&&(t=e,e={}),!t){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(a,r){qa(s,e||{},function(n,o){n?r(n):a(o)})})}Ts(s,e||{},function(a,r){a&&(a.code==="EACCES"||e&&e.ignoreErrors)&&(a=null,r=!1),t(a,r)})}function Ip(s,e){try{return Ts.sync(s,e||{})}catch(t){if(e&&e.ignoreErrors||t.code==="EACCES")return!1;throw t}}});var fc=z((yv,dc)=>{var _t=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",oc=Sr("path"),Np=_t?";":":",ic=nc(),cc=s=>Object.assign(new Error(`not found: ${s}`),{code:"ENOENT"}),lc=(s,e)=>{let t=e.colon||Np,a=s.match(/\//)||_t&&s.match(/\\/)?[""]:[..._t?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(t)],r=_t?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",n=_t?r.split(t):[""];return _t&&s.indexOf(".")!==-1&&n[0]!==""&&n.unshift(""),{pathEnv:a,pathExt:n,pathExtExe:r}},uc=(s,e,t)=>{typeof e=="function"&&(t=e,e={}),e||(e={});let{pathEnv:a,pathExt:r,pathExtExe:n}=lc(s,e),o=[],i=u=>new Promise((f,h)=>{if(u===a.length)return e.all&&o.length?f(o):h(cc(s));let _=a[u],d=/^".*"$/.test(_)?_.slice(1,-1):_,m=oc.join(d,s),y=!d&&/^\.[\\\/]/.test(s)?s.slice(0,2)+m:m;f(l(y,u,0))}),l=(u,f,h)=>new Promise((_,d)=>{if(h===r.length)return _(i(f+1));let m=r[h];ic(u+m,{pathExt:n},(y,v)=>{if(!y&&v)if(e.all)o.push(u+m);else return _(u+m);return _(l(u,f,h+1))})});return t?i(0).then(u=>t(null,u),t):i(0)},Ap=(s,e)=>{e=e||{};let{pathEnv:t,pathExt:a,pathExtExe:r}=lc(s,e),n=[];for(let o=0;o{"use strict";var pc=(s={})=>{let e=s.env||process.env;return(s.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(a=>a.toUpperCase()==="PATH")||"Path"};Ua.exports=pc;Ua.exports.default=pc});var _c=z((bv,gc)=>{"use strict";var mc=Sr("path"),Cp=fc(),Dp=hc();function vc(s,e){let t=s.options.env||process.env,a=process.cwd(),r=s.options.cwd!=null,n=r&&process.chdir!==void 0&&!process.chdir.disabled;if(n)try{process.chdir(s.options.cwd)}catch{}let o;try{o=Cp.sync(s.command,{path:t[Dp({env:t})],pathExt:e?mc.delimiter:void 0})}catch{}finally{n&&process.chdir(a)}return o&&(o=mc.resolve(r?s.options.cwd:"",o)),o}function $p(s){return vc(s)||vc(s,!0)}gc.exports=$p});var yc=z((Sv,za)=>{"use strict";var Va=/([()\][%!^"`<>&|;, *?])/g;function kp(s){return s=s.replace(Va,"^$1"),s}function Lp(s,e){return s=`${s}`,s=s.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),s=s.replace(/(?=(\\+?)?)\1$/,"$1$1"),s=`"${s}"`,s=s.replace(Va,"^$1"),e&&(s=s.replace(Va,"^$1")),s}za.exports.command=kp;za.exports.argument=Lp});var bc=z((xv,Ec)=>{"use strict";Ec.exports=/^#!(.*)/});var xc=z((Rv,Sc)=>{"use strict";var Fp=bc();Sc.exports=(s="")=>{let e=s.match(Fp);if(!e)return null;let[t,a]=e[0].replace(/#! ?/,"").split(" "),r=t.split("/").pop();return r==="env"?a:a?`${r} ${a}`:r}});var Tc=z((Tv,Rc)=>{"use strict";var Ha=Sr("fs"),jp=xc();function Mp(s){let t=Buffer.alloc(150),a;try{a=Ha.openSync(s,"r"),Ha.readSync(a,t,0,150,0),Ha.closeSync(a)}catch{}return jp(t.toString())}Rc.exports=Mp});var Ic=z((Pv,Oc)=>{"use strict";var qp=Sr("path"),Pc=_c(),wc=yc(),Up=Tc(),Vp=process.platform==="win32",zp=/\.(?:com|exe)$/i,Hp=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Bp(s){s.file=Pc(s);let e=s.file&&Up(s.file);return e?(s.args.unshift(s.file),s.command=e,Pc(s)):s.file}function Zp(s){if(!Vp)return s;let e=Bp(s),t=!zp.test(e);if(s.options.forceShell||t){let a=Hp.test(e);s.command=qp.normalize(s.command),s.command=wc.command(s.command),s.args=s.args.map(n=>wc.argument(n,a));let r=[s.command].concat(s.args).join(" ");s.args=["/d","/s","/c",`"${r}"`],s.command=process.env.comspec||"cmd.exe",s.options.windowsVerbatimArguments=!0}return s}function Gp(s,e,t){e&&!Array.isArray(e)&&(t=e,e=null),e=e?e.slice(0):[],t=Object.assign({},t);let a={command:s,args:e,options:t,file:void 0,original:{command:s,args:e}};return t.shell?a:Zp(a)}Oc.exports=Gp});var Cc=z((wv,Ac)=>{"use strict";var Ba=process.platform==="win32";function Za(s,e){return Object.assign(new Error(`${e} ${s.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${s.command}`,path:s.command,spawnargs:s.args})}function Xp(s,e){if(!Ba)return;let t=s.emit;s.emit=function(a,r){if(a==="exit"){let n=Nc(r,e);if(n)return t.call(s,"error",n)}return t.apply(s,arguments)}}function Nc(s,e){return Ba&&s===1&&!e.file?Za(e.original,"spawn"):null}function Qp(s,e){return Ba&&s===1&&!e.file?Za(e.original,"spawnSync"):null}Ac.exports={hookChildProcess:Xp,verifyENOENT:Nc,verifyENOENTSync:Qp,notFoundError:Za}});var kc=z((Ov,yt)=>{"use strict";var Dc=Sr("child_process"),Ga=Ic(),Xa=Cc();function $c(s,e,t){let a=Ga(s,e,t),r=Dc.spawn(a.command,a.args,a.options);return Xa.hookChildProcess(r,a),r}function Wp(s,e,t){let a=Ga(s,e,t),r=Dc.spawnSync(a.command,a.args,a.options);return r.error=r.error||Xa.verifyENOENTSync(r.status,a),r}yt.exports=$c;yt.exports.spawn=$c;yt.exports.sync=Wp;yt.exports._parse=Ga;yt.exports._enoent=Xa});var c={};Bl(c,{BRAND:()=>_u,DIRTY:()=>Fr,EMPTY_PATH:()=>Wl,INVALID:()=>Z,NEVER:()=>td,OK:()=>we,ParseStatus:()=>Re,Schema:()=>W,ZodAny:()=>Tr,ZodArray:()=>gr,ZodBigInt:()=>Mr,ZodBoolean:()=>qr,ZodBranded:()=>It,ZodCatch:()=>Kr,ZodDate:()=>Ur,ZodDefault:()=>Wr,ZodDiscriminatedUnion:()=>Ht,ZodEffects:()=>Ze,ZodEnum:()=>Xr,ZodError:()=>ke,ZodFirstPartyTypeKind:()=>O,ZodFunction:()=>Zt,ZodIntersection:()=>Br,ZodIssueCode:()=>w,ZodLazy:()=>Zr,ZodLiteral:()=>Gr,ZodMap:()=>pt,ZodNaN:()=>mt,ZodNativeEnum:()=>Qr,ZodNever:()=>Ke,ZodNull:()=>zr,ZodNullable:()=>or,ZodNumber:()=>jr,ZodObject:()=>Le,ZodOptional:()=>He,ZodParsedType:()=>k,ZodPipeline:()=>Nt,ZodPromise:()=>Pr,ZodReadonly:()=>Jr,ZodRecord:()=>Bt,ZodSchema:()=>W,ZodSet:()=>ht,ZodString:()=>Rr,ZodSymbol:()=>dt,ZodTransformer:()=>Ze,ZodTuple:()=>nr,ZodType:()=>W,ZodUndefined:()=>Vr,ZodUnion:()=>Hr,ZodUnknown:()=>vr,ZodVoid:()=>ft,addIssueToContext:()=>$,any:()=>wu,array:()=>Au,bigint:()=>Su,boolean:()=>wn,coerce:()=>rd,custom:()=>Rn,date:()=>xu,datetimeRegex:()=>Sn,defaultErrorMap:()=>hr,discriminatedUnion:()=>ku,effect:()=>Gu,enum:()=>Hu,function:()=>Uu,getErrorMap:()=>ct,getParsedType:()=>ar,instanceof:()=>Eu,intersection:()=>Lu,isAborted:()=>Vt,isAsync:()=>lt,isDirty:()=>zt,isValid:()=>xr,late:()=>yu,lazy:()=>Vu,literal:()=>zu,makeIssue:()=>Ot,map:()=>Mu,nan:()=>bu,nativeEnum:()=>Bu,never:()=>Iu,null:()=>Pu,nullable:()=>Qu,number:()=>Pn,object:()=>Cu,objectUtil:()=>Bs,oboolean:()=>ed,onumber:()=>Yu,optional:()=>Xu,ostring:()=>Ju,pipeline:()=>Ku,preprocess:()=>Wu,promise:()=>Zu,quotelessJson:()=>Gl,record:()=>ju,set:()=>qu,setErrorMap:()=>Ql,strictObject:()=>Du,string:()=>Tn,symbol:()=>Ru,transformer:()=>Gu,tuple:()=>Fu,undefined:()=>Tu,union:()=>$u,unknown:()=>Ou,util:()=>Y,void:()=>Nu});var Y;(function(s){s.assertEqual=r=>{};function e(r){}s.assertIs=e;function t(r){throw new Error}s.assertNever=t,s.arrayToEnum=r=>{let n={};for(let o of r)n[o]=o;return n},s.getValidEnumValues=r=>{let n=s.objectKeys(r).filter(i=>typeof r[r[i]]!="number"),o={};for(let i of n)o[i]=r[i];return s.objectValues(o)},s.objectValues=r=>s.objectKeys(r).map(function(n){return r[n]}),s.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{let n=[];for(let o in r)Object.prototype.hasOwnProperty.call(r,o)&&n.push(o);return n},s.find=(r,n)=>{for(let o of r)if(n(o))return o},s.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function a(r,n=" | "){return r.map(o=>typeof o=="string"?`'${o}'`:o).join(n)}s.joinValues=a,s.jsonStringifyReplacer=(r,n)=>typeof n=="bigint"?n.toString():n})(Y||(Y={}));var Bs;(function(s){s.mergeShapes=(e,t)=>({...e,...t})})(Bs||(Bs={}));var k=Y.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ar=s=>{switch(typeof s){case"undefined":return k.undefined;case"string":return k.string;case"number":return Number.isNaN(s)?k.nan:k.number;case"boolean":return k.boolean;case"function":return k.function;case"bigint":return k.bigint;case"symbol":return k.symbol;case"object":return Array.isArray(s)?k.array:s===null?k.null:s.then&&typeof s.then=="function"&&s.catch&&typeof s.catch=="function"?k.promise:typeof Map<"u"&&s instanceof Map?k.map:typeof Set<"u"&&s instanceof Set?k.set:typeof Date<"u"&&s instanceof Date?k.date:k.object;default:return k.unknown}};var w=Y.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Gl=s=>JSON.stringify(s,null,2).replace(/"([^"]+)":/g,"$1:"),ke=class s extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=a=>{this.issues=[...this.issues,a]},this.addIssues=(a=[])=>{this.issues=[...this.issues,...a]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(n){return n.message},a={_errors:[]},r=n=>{for(let o of n.issues)if(o.code==="invalid_union")o.unionErrors.map(r);else if(o.code==="invalid_return_type")r(o.returnTypeError);else if(o.code==="invalid_arguments")r(o.argumentsError);else if(o.path.length===0)a._errors.push(t(o));else{let i=a,l=0;for(;lt.message){let t={},a=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else a.push(e(r));return{formErrors:a,fieldErrors:t}}get formErrors(){return this.flatten()}};ke.create=s=>new ke(s);var Xl=(s,e)=>{let t;switch(s.code){case w.invalid_type:s.received===k.undefined?t="Required":t=`Expected ${s.expected}, received ${s.received}`;break;case w.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(s.expected,Y.jsonStringifyReplacer)}`;break;case w.unrecognized_keys:t=`Unrecognized key(s) in object: ${Y.joinValues(s.keys,", ")}`;break;case w.invalid_union:t="Invalid input";break;case w.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${Y.joinValues(s.options)}`;break;case w.invalid_enum_value:t=`Invalid enum value. Expected ${Y.joinValues(s.options)}, received '${s.received}'`;break;case w.invalid_arguments:t="Invalid function arguments";break;case w.invalid_return_type:t="Invalid function return type";break;case w.invalid_date:t="Invalid date";break;case w.invalid_string:typeof s.validation=="object"?"includes"in s.validation?(t=`Invalid input: must include "${s.validation.includes}"`,typeof s.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${s.validation.position}`)):"startsWith"in s.validation?t=`Invalid input: must start with "${s.validation.startsWith}"`:"endsWith"in s.validation?t=`Invalid input: must end with "${s.validation.endsWith}"`:Y.assertNever(s.validation):s.validation!=="regex"?t=`Invalid ${s.validation}`:t="Invalid";break;case w.too_small:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at least":"more than"} ${s.minimum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at least":"over"} ${s.minimum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="bigint"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(s.minimum))}`:t="Invalid input";break;case w.too_big:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at most":"less than"} ${s.maximum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at most":"under"} ${s.maximum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="bigint"?t=`BigInt must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly":s.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(s.maximum))}`:t="Invalid input";break;case w.custom:t="Invalid input";break;case w.invalid_intersection_types:t="Intersection results could not be merged";break;case w.not_multiple_of:t=`Number must be a multiple of ${s.multipleOf}`;break;case w.not_finite:t="Number must be finite";break;default:t=e.defaultError,Y.assertNever(s)}return{message:t}},hr=Xl;var gn=hr;function Ql(s){gn=s}function ct(){return gn}var Ot=s=>{let{data:e,path:t,errorMaps:a,issueData:r}=s,n=[...t,...r.path||[]],o={...r,path:n};if(r.message!==void 0)return{...r,path:n,message:r.message};let i="",l=a.filter(u=>!!u).slice().reverse();for(let u of l)i=u(o,{data:e,defaultError:i}).message;return{...r,path:n,message:i}},Wl=[];function $(s,e){let t=ct(),a=Ot({issueData:e,data:s.data,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,t,t===hr?void 0:hr].filter(r=>!!r)});s.common.issues.push(a)}var Re=class s{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let a=[];for(let r of t){if(r.status==="aborted")return Z;r.status==="dirty"&&e.dirty(),a.push(r.value)}return{status:e.value,value:a}}static async mergeObjectAsync(e,t){let a=[];for(let r of t){let n=await r.key,o=await r.value;a.push({key:n,value:o})}return s.mergeObjectSync(e,a)}static mergeObjectSync(e,t){let a={};for(let r of t){let{key:n,value:o}=r;if(n.status==="aborted"||o.status==="aborted")return Z;n.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),n.value!=="__proto__"&&(typeof o.value<"u"||r.alwaysSet)&&(a[n.value]=o.value)}return{status:e.value,value:a}}},Z=Object.freeze({status:"aborted"}),Fr=s=>({status:"dirty",value:s}),we=s=>({status:"valid",value:s}),Vt=s=>s.status==="aborted",zt=s=>s.status==="dirty",xr=s=>s.status==="valid",lt=s=>typeof Promise<"u"&&s instanceof Promise;var V;(function(s){s.errToObj=e=>typeof e=="string"?{message:e}:e||{},s.toString=e=>typeof e=="string"?e:e?.message})(V||(V={}));var Be=class{constructor(e,t,a,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=a,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},_n=(s,e)=>{if(xr(e))return{success:!0,data:e.value};if(!s.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new ke(s.common.issues);return this._error=t,this._error}}};function X(s){if(!s)return{};let{errorMap:e,invalid_type_error:t,required_error:a,description:r}=s;if(e&&(t||a))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(o,i)=>{let{message:l}=s;return o.code==="invalid_enum_value"?{message:l??i.defaultError}:typeof i.data>"u"?{message:l??a??i.defaultError}:o.code!=="invalid_type"?{message:i.defaultError}:{message:l??t??i.defaultError}},description:r}}var W=class{get description(){return this._def.description}_getType(e){return ar(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ar(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Re,ctx:{common:e.parent.common,data:e.data,parsedType:ar(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(lt(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let a=this.safeParse(e,t);if(a.success)return a.data;throw a.error}safeParse(e,t){let a={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ar(e)},r=this._parseSync({data:e,path:a.path,parent:a});return _n(a,r)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ar(e)};if(!this["~standard"].async)try{let a=this._parseSync({data:e,path:[],parent:t});return xr(a)?{value:a.value}:{issues:t.common.issues}}catch(a){a?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(a=>xr(a)?{value:a.value}:{issues:t.common.issues})}async parseAsync(e,t){let a=await this.safeParseAsync(e,t);if(a.success)return a.data;throw a.error}async safeParseAsync(e,t){let a={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ar(e)},r=this._parse({data:e,path:a.path,parent:a}),n=await(lt(r)?r:Promise.resolve(r));return _n(a,n)}refine(e,t){let a=r=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(r):t;return this._refinement((r,n)=>{let o=e(r),i=()=>n.addIssue({code:w.custom,...a(r)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(i(),!1)):o?!0:(i(),!1)})}refinement(e,t){return this._refinement((a,r)=>e(a)?!0:(r.addIssue(typeof t=="function"?t(a,r):t),!1))}_refinement(e){return new Ze({schema:this,typeName:O.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return He.create(this,this._def)}nullable(){return or.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return gr.create(this)}promise(){return Pr.create(this,this._def)}or(e){return Hr.create([this,e],this._def)}and(e){return Br.create(this,e,this._def)}transform(e){return new Ze({...X(this._def),schema:this,typeName:O.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Wr({...X(this._def),innerType:this,defaultValue:t,typeName:O.ZodDefault})}brand(){return new It({typeName:O.ZodBranded,type:this,...X(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Kr({...X(this._def),innerType:this,catchValue:t,typeName:O.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Nt.create(this,e)}readonly(){return Jr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Kl=/^c[^\s-]{8,}$/i,Jl=/^[0-9a-z]+$/,Yl=/^[0-9A-HJKMNP-TV-Z]{26}$/i,eu=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ru=/^[a-z0-9_-]{21}$/i,tu=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,su=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,au=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,nu="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Zs,ou=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,iu=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,cu=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,lu=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,uu=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,du=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,En="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",fu=new RegExp(`^${En}$`);function bn(s){let e="[0-5]\\d";s.precision?e=`${e}\\.\\d{${s.precision}}`:s.precision==null&&(e=`${e}(\\.\\d+)?`);let t=s.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function pu(s){return new RegExp(`^${bn(s)}$`)}function Sn(s){let e=`${En}T${bn(s)}`,t=[];return t.push(s.local?"Z?":"Z"),s.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function hu(s,e){return!!((e==="v4"||!e)&&ou.test(s)||(e==="v6"||!e)&&cu.test(s))}function mu(s,e){if(!tu.test(s))return!1;try{let[t]=s.split(".");if(!t)return!1;let a=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),r=JSON.parse(atob(a));return!(typeof r!="object"||r===null||"typ"in r&&r?.typ!=="JWT"||!r.alg||e&&r.alg!==e)}catch{return!1}}function vu(s,e){return!!((e==="v4"||!e)&&iu.test(s)||(e==="v6"||!e)&&lu.test(s))}var Rr=class s extends W{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==k.string){let n=this._getOrReturnCtx(e);return $(n,{code:w.invalid_type,expected:k.string,received:n.parsedType}),Z}let a=new Re,r;for(let n of this._def.checks)if(n.kind==="min")e.data.lengthn.value&&(r=this._getOrReturnCtx(e,r),$(r,{code:w.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),a.dirty());else if(n.kind==="length"){let o=e.data.length>n.value,i=e.data.lengthe.test(r),{validation:t,code:w.invalid_string,...V.errToObj(a)})}_addCheck(e){return new s({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...V.errToObj(e)})}url(e){return this._addCheck({kind:"url",...V.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...V.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...V.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...V.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...V.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...V.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...V.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...V.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...V.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...V.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...V.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...V.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...V.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...V.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...V.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...V.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...V.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...V.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...V.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...V.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...V.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...V.errToObj(t)})}nonempty(e){return this.min(1,V.errToObj(e))}trim(){return new s({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new s({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new s({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.valuenew Rr({checks:[],typeName:O.ZodString,coerce:s?.coerce??!1,...X(s)});function gu(s,e){let t=(s.toString().split(".")[1]||"").length,a=(e.toString().split(".")[1]||"").length,r=t>a?t:a,n=Number.parseInt(s.toFixed(r).replace(".","")),o=Number.parseInt(e.toFixed(r).replace(".",""));return n%o/10**r}var jr=class s extends W{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==k.number){let n=this._getOrReturnCtx(e);return $(n,{code:w.invalid_type,expected:k.number,received:n.parsedType}),Z}let a,r=new Re;for(let n of this._def.checks)n.kind==="int"?Y.isInteger(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{code:w.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty()):n.kind==="min"?(n.inclusive?e.datan.value:e.data>=n.value)&&(a=this._getOrReturnCtx(e,a),$(a,{code:w.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty()):n.kind==="multipleOf"?gu(e.data,n.value)!==0&&(a=this._getOrReturnCtx(e,a),$(a,{code:w.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):n.kind==="finite"?Number.isFinite(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{code:w.not_finite,message:n.message}),r.dirty()):Y.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,V.toString(t))}gt(e,t){return this.setLimit("min",e,!1,V.toString(t))}lte(e,t){return this.setLimit("max",e,!0,V.toString(t))}lt(e,t){return this.setLimit("max",e,!1,V.toString(t))}setLimit(e,t,a,r){return new s({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:a,message:V.toString(r)}]})}_addCheck(e){return new s({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:V.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:V.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:V.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:V.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:V.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:V.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:V.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:V.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:V.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.valuee.kind==="int"||e.kind==="multipleOf"&&Y.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let a of this._def.checks){if(a.kind==="finite"||a.kind==="int"||a.kind==="multipleOf")return!0;a.kind==="min"?(t===null||a.value>t)&&(t=a.value):a.kind==="max"&&(e===null||a.valuenew jr({checks:[],typeName:O.ZodNumber,coerce:s?.coerce||!1,...X(s)});var Mr=class s extends W{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==k.bigint)return this._getInvalidInput(e);let a,r=new Re;for(let n of this._def.checks)n.kind==="min"?(n.inclusive?e.datan.value:e.data>=n.value)&&(a=this._getOrReturnCtx(e,a),$(a,{code:w.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty()):n.kind==="multipleOf"?e.data%n.value!==BigInt(0)&&(a=this._getOrReturnCtx(e,a),$(a,{code:w.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):Y.assertNever(n);return{status:r.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return $(t,{code:w.invalid_type,expected:k.bigint,received:t.parsedType}),Z}gte(e,t){return this.setLimit("min",e,!0,V.toString(t))}gt(e,t){return this.setLimit("min",e,!1,V.toString(t))}lte(e,t){return this.setLimit("max",e,!0,V.toString(t))}lt(e,t){return this.setLimit("max",e,!1,V.toString(t))}setLimit(e,t,a,r){return new s({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:a,message:V.toString(r)}]})}_addCheck(e){return new s({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:V.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:V.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:V.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:V.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:V.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.valuenew Mr({checks:[],typeName:O.ZodBigInt,coerce:s?.coerce??!1,...X(s)});var qr=class extends W{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==k.boolean){let a=this._getOrReturnCtx(e);return $(a,{code:w.invalid_type,expected:k.boolean,received:a.parsedType}),Z}return we(e.data)}};qr.create=s=>new qr({typeName:O.ZodBoolean,coerce:s?.coerce||!1,...X(s)});var Ur=class s extends W{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==k.date){let n=this._getOrReturnCtx(e);return $(n,{code:w.invalid_type,expected:k.date,received:n.parsedType}),Z}if(Number.isNaN(e.data.getTime())){let n=this._getOrReturnCtx(e);return $(n,{code:w.invalid_date}),Z}let a=new Re,r;for(let n of this._def.checks)n.kind==="min"?e.data.getTime()n.value&&(r=this._getOrReturnCtx(e,r),$(r,{code:w.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),a.dirty()):Y.assertNever(n);return{status:a.value,value:new Date(e.data.getTime())}}_addCheck(e){return new s({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:V.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:V.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.valuenew Ur({checks:[],coerce:s?.coerce||!1,typeName:O.ZodDate,...X(s)});var dt=class extends W{_parse(e){if(this._getType(e)!==k.symbol){let a=this._getOrReturnCtx(e);return $(a,{code:w.invalid_type,expected:k.symbol,received:a.parsedType}),Z}return we(e.data)}};dt.create=s=>new dt({typeName:O.ZodSymbol,...X(s)});var Vr=class extends W{_parse(e){if(this._getType(e)!==k.undefined){let a=this._getOrReturnCtx(e);return $(a,{code:w.invalid_type,expected:k.undefined,received:a.parsedType}),Z}return we(e.data)}};Vr.create=s=>new Vr({typeName:O.ZodUndefined,...X(s)});var zr=class extends W{_parse(e){if(this._getType(e)!==k.null){let a=this._getOrReturnCtx(e);return $(a,{code:w.invalid_type,expected:k.null,received:a.parsedType}),Z}return we(e.data)}};zr.create=s=>new zr({typeName:O.ZodNull,...X(s)});var Tr=class extends W{constructor(){super(...arguments),this._any=!0}_parse(e){return we(e.data)}};Tr.create=s=>new Tr({typeName:O.ZodAny,...X(s)});var vr=class extends W{constructor(){super(...arguments),this._unknown=!0}_parse(e){return we(e.data)}};vr.create=s=>new vr({typeName:O.ZodUnknown,...X(s)});var Ke=class extends W{_parse(e){let t=this._getOrReturnCtx(e);return $(t,{code:w.invalid_type,expected:k.never,received:t.parsedType}),Z}};Ke.create=s=>new Ke({typeName:O.ZodNever,...X(s)});var ft=class extends W{_parse(e){if(this._getType(e)!==k.undefined){let a=this._getOrReturnCtx(e);return $(a,{code:w.invalid_type,expected:k.void,received:a.parsedType}),Z}return we(e.data)}};ft.create=s=>new ft({typeName:O.ZodVoid,...X(s)});var gr=class s extends W{_parse(e){let{ctx:t,status:a}=this._processInputParams(e),r=this._def;if(t.parsedType!==k.array)return $(t,{code:w.invalid_type,expected:k.array,received:t.parsedType}),Z;if(r.exactLength!==null){let o=t.data.length>r.exactLength.value,i=t.data.lengthr.maxLength.value&&($(t,{code:w.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),a.dirty()),t.common.async)return Promise.all([...t.data].map((o,i)=>r.type._parseAsync(new Be(t,o,t.path,i)))).then(o=>Re.mergeArray(a,o));let n=[...t.data].map((o,i)=>r.type._parseSync(new Be(t,o,t.path,i)));return Re.mergeArray(a,n)}get element(){return this._def.type}min(e,t){return new s({...this._def,minLength:{value:e,message:V.toString(t)}})}max(e,t){return new s({...this._def,maxLength:{value:e,message:V.toString(t)}})}length(e,t){return new s({...this._def,exactLength:{value:e,message:V.toString(t)}})}nonempty(e){return this.min(1,e)}};gr.create=(s,e)=>new gr({type:s,minLength:null,maxLength:null,exactLength:null,typeName:O.ZodArray,...X(e)});function ut(s){if(s instanceof Le){let e={};for(let t in s.shape){let a=s.shape[t];e[t]=He.create(ut(a))}return new Le({...s._def,shape:()=>e})}else return s instanceof gr?new gr({...s._def,type:ut(s.element)}):s instanceof He?He.create(ut(s.unwrap())):s instanceof or?or.create(ut(s.unwrap())):s instanceof nr?nr.create(s.items.map(e=>ut(e))):s}var Le=class s extends W{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=Y.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==k.object){let u=this._getOrReturnCtx(e);return $(u,{code:w.invalid_type,expected:k.object,received:u.parsedType}),Z}let{status:a,ctx:r}=this._processInputParams(e),{shape:n,keys:o}=this._getCached(),i=[];if(!(this._def.catchall instanceof Ke&&this._def.unknownKeys==="strip"))for(let u in r.data)o.includes(u)||i.push(u);let l=[];for(let u of o){let f=n[u],h=r.data[u];l.push({key:{status:"valid",value:u},value:f._parse(new Be(r,h,r.path,u)),alwaysSet:u in r.data})}if(this._def.catchall instanceof Ke){let u=this._def.unknownKeys;if(u==="passthrough")for(let f of i)l.push({key:{status:"valid",value:f},value:{status:"valid",value:r.data[f]}});else if(u==="strict")i.length>0&&($(r,{code:w.unrecognized_keys,keys:i}),a.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let f of i){let h=r.data[f];l.push({key:{status:"valid",value:f},value:u._parse(new Be(r,h,r.path,f)),alwaysSet:f in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let u=[];for(let f of l){let h=await f.key,_=await f.value;u.push({key:h,value:_,alwaysSet:f.alwaysSet})}return u}).then(u=>Re.mergeObjectSync(a,u)):Re.mergeObjectSync(a,l)}get shape(){return this._def.shape()}strict(e){return V.errToObj,new s({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,a)=>{let r=this._def.errorMap?.(t,a).message??a.defaultError;return t.code==="unrecognized_keys"?{message:V.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new s({...this._def,unknownKeys:"strip"})}passthrough(){return new s({...this._def,unknownKeys:"passthrough"})}extend(e){return new s({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new s({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:O.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new s({...this._def,catchall:e})}pick(e){let t={};for(let a of Y.objectKeys(e))e[a]&&this.shape[a]&&(t[a]=this.shape[a]);return new s({...this._def,shape:()=>t})}omit(e){let t={};for(let a of Y.objectKeys(this.shape))e[a]||(t[a]=this.shape[a]);return new s({...this._def,shape:()=>t})}deepPartial(){return ut(this)}partial(e){let t={};for(let a of Y.objectKeys(this.shape)){let r=this.shape[a];e&&!e[a]?t[a]=r:t[a]=r.optional()}return new s({...this._def,shape:()=>t})}required(e){let t={};for(let a of Y.objectKeys(this.shape))if(e&&!e[a])t[a]=this.shape[a];else{let n=this.shape[a];for(;n instanceof He;)n=n._def.innerType;t[a]=n}return new s({...this._def,shape:()=>t})}keyof(){return xn(Y.objectKeys(this.shape))}};Le.create=(s,e)=>new Le({shape:()=>s,unknownKeys:"strip",catchall:Ke.create(),typeName:O.ZodObject,...X(e)});Le.strictCreate=(s,e)=>new Le({shape:()=>s,unknownKeys:"strict",catchall:Ke.create(),typeName:O.ZodObject,...X(e)});Le.lazycreate=(s,e)=>new Le({shape:s,unknownKeys:"strip",catchall:Ke.create(),typeName:O.ZodObject,...X(e)});var Hr=class extends W{_parse(e){let{ctx:t}=this._processInputParams(e),a=this._def.options;function r(n){for(let i of n)if(i.result.status==="valid")return i.result;for(let i of n)if(i.result.status==="dirty")return t.common.issues.push(...i.ctx.common.issues),i.result;let o=n.map(i=>new ke(i.ctx.common.issues));return $(t,{code:w.invalid_union,unionErrors:o}),Z}if(t.common.async)return Promise.all(a.map(async n=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await n._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(r);{let n,o=[];for(let l of a){let u={...t,common:{...t.common,issues:[]},parent:null},f=l._parseSync({data:t.data,path:t.path,parent:u});if(f.status==="valid")return f;f.status==="dirty"&&!n&&(n={result:f,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(n)return t.common.issues.push(...n.ctx.common.issues),n.result;let i=o.map(l=>new ke(l));return $(t,{code:w.invalid_union,unionErrors:i}),Z}}get options(){return this._def.options}};Hr.create=(s,e)=>new Hr({options:s,typeName:O.ZodUnion,...X(e)});var mr=s=>s instanceof Zr?mr(s.schema):s instanceof Ze?mr(s.innerType()):s instanceof Gr?[s.value]:s instanceof Xr?s.options:s instanceof Qr?Y.objectValues(s.enum):s instanceof Wr?mr(s._def.innerType):s instanceof Vr?[void 0]:s instanceof zr?[null]:s instanceof He?[void 0,...mr(s.unwrap())]:s instanceof or?[null,...mr(s.unwrap())]:s instanceof It||s instanceof Jr?mr(s.unwrap()):s instanceof Kr?mr(s._def.innerType):[],Ht=class s extends W{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==k.object)return $(t,{code:w.invalid_type,expected:k.object,received:t.parsedType}),Z;let a=this.discriminator,r=t.data[a],n=this.optionsMap.get(r);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):($(t,{code:w.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[a]}),Z)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,a){let r=new Map;for(let n of t){let o=mr(n.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of o){if(r.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);r.set(i,n)}}return new s({typeName:O.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:r,...X(a)})}};function Gs(s,e){let t=ar(s),a=ar(e);if(s===e)return{valid:!0,data:s};if(t===k.object&&a===k.object){let r=Y.objectKeys(e),n=Y.objectKeys(s).filter(i=>r.indexOf(i)!==-1),o={...s,...e};for(let i of n){let l=Gs(s[i],e[i]);if(!l.valid)return{valid:!1};o[i]=l.data}return{valid:!0,data:o}}else if(t===k.array&&a===k.array){if(s.length!==e.length)return{valid:!1};let r=[];for(let n=0;n{if(Vt(n)||Vt(o))return Z;let i=Gs(n.value,o.value);return i.valid?((zt(n)||zt(o))&&t.dirty(),{status:t.value,value:i.data}):($(a,{code:w.invalid_intersection_types}),Z)};return a.common.async?Promise.all([this._def.left._parseAsync({data:a.data,path:a.path,parent:a}),this._def.right._parseAsync({data:a.data,path:a.path,parent:a})]).then(([n,o])=>r(n,o)):r(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}};Br.create=(s,e,t)=>new Br({left:s,right:e,typeName:O.ZodIntersection,...X(t)});var nr=class s extends W{_parse(e){let{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==k.array)return $(a,{code:w.invalid_type,expected:k.array,received:a.parsedType}),Z;if(a.data.lengththis._def.items.length&&($(a,{code:w.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let n=[...a.data].map((o,i)=>{let l=this._def.items[i]||this._def.rest;return l?l._parse(new Be(a,o,a.path,i)):null}).filter(o=>!!o);return a.common.async?Promise.all(n).then(o=>Re.mergeArray(t,o)):Re.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new s({...this._def,rest:e})}};nr.create=(s,e)=>{if(!Array.isArray(s))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new nr({items:s,typeName:O.ZodTuple,rest:null,...X(e)})};var Bt=class s extends W{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==k.object)return $(a,{code:w.invalid_type,expected:k.object,received:a.parsedType}),Z;let r=[],n=this._def.keyType,o=this._def.valueType;for(let i in a.data)r.push({key:n._parse(new Be(a,i,a.path,i)),value:o._parse(new Be(a,a.data[i],a.path,i)),alwaysSet:i in a.data});return a.common.async?Re.mergeObjectAsync(t,r):Re.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,a){return t instanceof W?new s({keyType:e,valueType:t,typeName:O.ZodRecord,...X(a)}):new s({keyType:Rr.create(),valueType:e,typeName:O.ZodRecord,...X(t)})}},pt=class extends W{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==k.map)return $(a,{code:w.invalid_type,expected:k.map,received:a.parsedType}),Z;let r=this._def.keyType,n=this._def.valueType,o=[...a.data.entries()].map(([i,l],u)=>({key:r._parse(new Be(a,i,a.path,[u,"key"])),value:n._parse(new Be(a,l,a.path,[u,"value"]))}));if(a.common.async){let i=new Map;return Promise.resolve().then(async()=>{for(let l of o){let u=await l.key,f=await l.value;if(u.status==="aborted"||f.status==="aborted")return Z;(u.status==="dirty"||f.status==="dirty")&&t.dirty(),i.set(u.value,f.value)}return{status:t.value,value:i}})}else{let i=new Map;for(let l of o){let u=l.key,f=l.value;if(u.status==="aborted"||f.status==="aborted")return Z;(u.status==="dirty"||f.status==="dirty")&&t.dirty(),i.set(u.value,f.value)}return{status:t.value,value:i}}}};pt.create=(s,e,t)=>new pt({valueType:e,keyType:s,typeName:O.ZodMap,...X(t)});var ht=class s extends W{_parse(e){let{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==k.set)return $(a,{code:w.invalid_type,expected:k.set,received:a.parsedType}),Z;let r=this._def;r.minSize!==null&&a.data.sizer.maxSize.value&&($(a,{code:w.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let n=this._def.valueType;function o(l){let u=new Set;for(let f of l){if(f.status==="aborted")return Z;f.status==="dirty"&&t.dirty(),u.add(f.value)}return{status:t.value,value:u}}let i=[...a.data.values()].map((l,u)=>n._parse(new Be(a,l,a.path,u)));return a.common.async?Promise.all(i).then(l=>o(l)):o(i)}min(e,t){return new s({...this._def,minSize:{value:e,message:V.toString(t)}})}max(e,t){return new s({...this._def,maxSize:{value:e,message:V.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ht.create=(s,e)=>new ht({valueType:s,minSize:null,maxSize:null,typeName:O.ZodSet,...X(e)});var Zt=class s extends W{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==k.function)return $(t,{code:w.invalid_type,expected:k.function,received:t.parsedType}),Z;function a(i,l){return Ot({data:i,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ct(),hr].filter(u=>!!u),issueData:{code:w.invalid_arguments,argumentsError:l}})}function r(i,l){return Ot({data:i,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ct(),hr].filter(u=>!!u),issueData:{code:w.invalid_return_type,returnTypeError:l}})}let n={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof Pr){let i=this;return we(async function(...l){let u=new ke([]),f=await i._def.args.parseAsync(l,n).catch(d=>{throw u.addIssue(a(l,d)),u}),h=await Reflect.apply(o,this,f);return await i._def.returns._def.type.parseAsync(h,n).catch(d=>{throw u.addIssue(r(h,d)),u})})}else{let i=this;return we(function(...l){let u=i._def.args.safeParse(l,n);if(!u.success)throw new ke([a(l,u.error)]);let f=Reflect.apply(o,this,u.data),h=i._def.returns.safeParse(f,n);if(!h.success)throw new ke([r(f,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new s({...this._def,args:nr.create(e).rest(vr.create())})}returns(e){return new s({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,a){return new s({args:e||nr.create([]).rest(vr.create()),returns:t||vr.create(),typeName:O.ZodFunction,...X(a)})}},Zr=class extends W{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Zr.create=(s,e)=>new Zr({getter:s,typeName:O.ZodLazy,...X(e)});var Gr=class extends W{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return $(t,{received:t.data,code:w.invalid_literal,expected:this._def.value}),Z}return{status:"valid",value:e.data}}get value(){return this._def.value}};Gr.create=(s,e)=>new Gr({value:s,typeName:O.ZodLiteral,...X(e)});function xn(s,e){return new Xr({values:s,typeName:O.ZodEnum,...X(e)})}var Xr=class s extends W{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),a=this._def.values;return $(t,{expected:Y.joinValues(a),received:t.parsedType,code:w.invalid_type}),Z}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),a=this._def.values;return $(t,{received:t.data,code:w.invalid_enum_value,options:a}),Z}return we(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return s.create(e,{...this._def,...t})}exclude(e,t=this._def){return s.create(this.options.filter(a=>!e.includes(a)),{...this._def,...t})}};Xr.create=xn;var Qr=class extends W{_parse(e){let t=Y.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(e);if(a.parsedType!==k.string&&a.parsedType!==k.number){let r=Y.objectValues(t);return $(a,{expected:Y.joinValues(r),received:a.parsedType,code:w.invalid_type}),Z}if(this._cache||(this._cache=new Set(Y.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let r=Y.objectValues(t);return $(a,{received:a.data,code:w.invalid_enum_value,options:r}),Z}return we(e.data)}get enum(){return this._def.values}};Qr.create=(s,e)=>new Qr({values:s,typeName:O.ZodNativeEnum,...X(e)});var Pr=class extends W{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==k.promise&&t.common.async===!1)return $(t,{code:w.invalid_type,expected:k.promise,received:t.parsedType}),Z;let a=t.parsedType===k.promise?t.data:Promise.resolve(t.data);return we(a.then(r=>this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Pr.create=(s,e)=>new Pr({type:s,typeName:O.ZodPromise,...X(e)});var Ze=class extends W{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===O.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:a}=this._processInputParams(e),r=this._def.effect||null,n={addIssue:o=>{$(a,o),o.fatal?t.abort():t.dirty()},get path(){return a.path}};if(n.addIssue=n.addIssue.bind(n),r.type==="preprocess"){let o=r.transform(a.data,n);if(a.common.async)return Promise.resolve(o).then(async i=>{if(t.value==="aborted")return Z;let l=await this._def.schema._parseAsync({data:i,path:a.path,parent:a});return l.status==="aborted"?Z:l.status==="dirty"?Fr(l.value):t.value==="dirty"?Fr(l.value):l});{if(t.value==="aborted")return Z;let i=this._def.schema._parseSync({data:o,path:a.path,parent:a});return i.status==="aborted"?Z:i.status==="dirty"?Fr(i.value):t.value==="dirty"?Fr(i.value):i}}if(r.type==="refinement"){let o=i=>{let l=r.refinement(i,n);if(a.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(a.common.async===!1){let i=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return i.status==="aborted"?Z:(i.status==="dirty"&&t.dirty(),o(i.value),{status:t.value,value:i.value})}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(i=>i.status==="aborted"?Z:(i.status==="dirty"&&t.dirty(),o(i.value).then(()=>({status:t.value,value:i.value}))))}if(r.type==="transform")if(a.common.async===!1){let o=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!xr(o))return Z;let i=r.transform(o.value,n);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(o=>xr(o)?Promise.resolve(r.transform(o.value,n)).then(i=>({status:t.value,value:i})):Z);Y.assertNever(r)}};Ze.create=(s,e,t)=>new Ze({schema:s,typeName:O.ZodEffects,effect:e,...X(t)});Ze.createWithPreprocess=(s,e,t)=>new Ze({schema:e,effect:{type:"preprocess",transform:s},typeName:O.ZodEffects,...X(t)});var He=class extends W{_parse(e){return this._getType(e)===k.undefined?we(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};He.create=(s,e)=>new He({innerType:s,typeName:O.ZodOptional,...X(e)});var or=class extends W{_parse(e){return this._getType(e)===k.null?we(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};or.create=(s,e)=>new or({innerType:s,typeName:O.ZodNullable,...X(e)});var Wr=class extends W{_parse(e){let{ctx:t}=this._processInputParams(e),a=t.data;return t.parsedType===k.undefined&&(a=this._def.defaultValue()),this._def.innerType._parse({data:a,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Wr.create=(s,e)=>new Wr({innerType:s,typeName:O.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...X(e)});var Kr=class extends W{_parse(e){let{ctx:t}=this._processInputParams(e),a={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:a.data,path:a.path,parent:{...a}});return lt(r)?r.then(n=>({status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new ke(a.common.issues)},input:a.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new ke(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}};Kr.create=(s,e)=>new Kr({innerType:s,typeName:O.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...X(e)});var mt=class extends W{_parse(e){if(this._getType(e)!==k.nan){let a=this._getOrReturnCtx(e);return $(a,{code:w.invalid_type,expected:k.nan,received:a.parsedType}),Z}return{status:"valid",value:e.data}}};mt.create=s=>new mt({typeName:O.ZodNaN,...X(s)});var _u=Symbol("zod_brand"),It=class extends W{_parse(e){let{ctx:t}=this._processInputParams(e),a=t.data;return this._def.type._parse({data:a,path:t.path,parent:t})}unwrap(){return this._def.type}},Nt=class s extends W{_parse(e){let{status:t,ctx:a}=this._processInputParams(e);if(a.common.async)return(async()=>{let n=await this._def.in._parseAsync({data:a.data,path:a.path,parent:a});return n.status==="aborted"?Z:n.status==="dirty"?(t.dirty(),Fr(n.value)):this._def.out._parseAsync({data:n.value,path:a.path,parent:a})})();{let r=this._def.in._parseSync({data:a.data,path:a.path,parent:a});return r.status==="aborted"?Z:r.status==="dirty"?(t.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:a.path,parent:a})}}static create(e,t){return new s({in:e,out:t,typeName:O.ZodPipeline})}},Jr=class extends W{_parse(e){let t=this._def.innerType._parse(e),a=r=>(xr(r)&&(r.value=Object.freeze(r.value)),r);return lt(t)?t.then(r=>a(r)):a(t)}unwrap(){return this._def.innerType}};Jr.create=(s,e)=>new Jr({innerType:s,typeName:O.ZodReadonly,...X(e)});function yn(s,e){let t=typeof s=="function"?s(e):typeof s=="string"?{message:s}:s;return typeof t=="string"?{message:t}:t}function Rn(s,e={},t){return s?Tr.create().superRefine((a,r)=>{let n=s(a);if(n instanceof Promise)return n.then(o=>{if(!o){let i=yn(e,a),l=i.fatal??t??!0;r.addIssue({code:"custom",...i,fatal:l})}});if(!n){let o=yn(e,a),i=o.fatal??t??!0;r.addIssue({code:"custom",...o,fatal:i})}}):Tr.create()}var yu={object:Le.lazycreate},O;(function(s){s.ZodString="ZodString",s.ZodNumber="ZodNumber",s.ZodNaN="ZodNaN",s.ZodBigInt="ZodBigInt",s.ZodBoolean="ZodBoolean",s.ZodDate="ZodDate",s.ZodSymbol="ZodSymbol",s.ZodUndefined="ZodUndefined",s.ZodNull="ZodNull",s.ZodAny="ZodAny",s.ZodUnknown="ZodUnknown",s.ZodNever="ZodNever",s.ZodVoid="ZodVoid",s.ZodArray="ZodArray",s.ZodObject="ZodObject",s.ZodUnion="ZodUnion",s.ZodDiscriminatedUnion="ZodDiscriminatedUnion",s.ZodIntersection="ZodIntersection",s.ZodTuple="ZodTuple",s.ZodRecord="ZodRecord",s.ZodMap="ZodMap",s.ZodSet="ZodSet",s.ZodFunction="ZodFunction",s.ZodLazy="ZodLazy",s.ZodLiteral="ZodLiteral",s.ZodEnum="ZodEnum",s.ZodEffects="ZodEffects",s.ZodNativeEnum="ZodNativeEnum",s.ZodOptional="ZodOptional",s.ZodNullable="ZodNullable",s.ZodDefault="ZodDefault",s.ZodCatch="ZodCatch",s.ZodPromise="ZodPromise",s.ZodBranded="ZodBranded",s.ZodPipeline="ZodPipeline",s.ZodReadonly="ZodReadonly"})(O||(O={}));var Eu=(s,e={message:`Input not instance of ${s.name}`})=>Rn(t=>t instanceof s,e),Tn=Rr.create,Pn=jr.create,bu=mt.create,Su=Mr.create,wn=qr.create,xu=Ur.create,Ru=dt.create,Tu=Vr.create,Pu=zr.create,wu=Tr.create,Ou=vr.create,Iu=Ke.create,Nu=ft.create,Au=gr.create,Cu=Le.create,Du=Le.strictCreate,$u=Hr.create,ku=Ht.create,Lu=Br.create,Fu=nr.create,ju=Bt.create,Mu=pt.create,qu=ht.create,Uu=Zt.create,Vu=Zr.create,zu=Gr.create,Hu=Xr.create,Bu=Qr.create,Zu=Pr.create,Gu=Ze.create,Xu=He.create,Qu=or.create,Wu=Ze.createWithPreprocess,Ku=Nt.create,Ju=()=>Tn().optional(),Yu=()=>Pn().optional(),ed=()=>wn().optional(),rd={string:s=>Rr.create({...s,coerce:!0}),number:s=>jr.create({...s,coerce:!0}),boolean:s=>qr.create({...s,coerce:!0}),bigint:s=>Mr.create({...s,coerce:!0}),date:s=>Ur.create({...s,coerce:!0})};var td=Z;var At="2025-06-18";var Gt=[At,"2025-03-26","2024-11-05","2024-10-07"],Xt="2.0",On=c.union([c.string(),c.number().int()]),In=c.string(),sd=c.object({progressToken:c.optional(On)}).passthrough(),Ge=c.object({_meta:c.optional(sd)}).passthrough(),Fe=c.object({method:c.string(),params:c.optional(Ge)}),Ct=c.object({_meta:c.optional(c.object({}).passthrough())}).passthrough(),ir=c.object({method:c.string(),params:c.optional(Ct)}),Xe=c.object({_meta:c.optional(c.object({}).passthrough())}).passthrough(),Qt=c.union([c.string(),c.number().int()]),Nn=c.object({jsonrpc:c.literal(Xt),id:Qt}).merge(Fe).strict(),An=s=>Nn.safeParse(s).success,Cn=c.object({jsonrpc:c.literal(Xt)}).merge(ir).strict(),Dn=s=>Cn.safeParse(s).success,$n=c.object({jsonrpc:c.literal(Xt),id:Qt,result:Xe}).strict(),Xs=s=>$n.safeParse(s).success,Ce;(function(s){s[s.ConnectionClosed=-32e3]="ConnectionClosed",s[s.RequestTimeout=-32001]="RequestTimeout",s[s.ParseError=-32700]="ParseError",s[s.InvalidRequest=-32600]="InvalidRequest",s[s.MethodNotFound=-32601]="MethodNotFound",s[s.InvalidParams=-32602]="InvalidParams",s[s.InternalError=-32603]="InternalError"})(Ce||(Ce={}));var kn=c.object({jsonrpc:c.literal(Xt),id:Qt,error:c.object({code:c.number().int(),message:c.string(),data:c.optional(c.unknown())})}).strict(),Ln=s=>kn.safeParse(s).success,Fn=c.union([Nn,Cn,$n,kn]),_r=Xe.strict(),Wt=ir.extend({method:c.literal("notifications/cancelled"),params:Ct.extend({requestId:Qt,reason:c.string().optional()})}),ad=c.object({src:c.string(),mimeType:c.optional(c.string()),sizes:c.optional(c.array(c.string()))}).passthrough(),Dt=c.object({icons:c.array(ad).optional()}).passthrough(),$t=c.object({name:c.string(),title:c.optional(c.string())}).passthrough(),jn=$t.extend({version:c.string(),websiteUrl:c.optional(c.string())}).merge(Dt),nd=c.object({experimental:c.optional(c.object({}).passthrough()),sampling:c.optional(c.object({}).passthrough()),elicitation:c.optional(c.object({}).passthrough()),roots:c.optional(c.object({listChanged:c.optional(c.boolean())}).passthrough())}).passthrough(),Qs=Fe.extend({method:c.literal("initialize"),params:Ge.extend({protocolVersion:c.string(),capabilities:nd,clientInfo:jn})});var od=c.object({experimental:c.optional(c.object({}).passthrough()),logging:c.optional(c.object({}).passthrough()),completions:c.optional(c.object({}).passthrough()),prompts:c.optional(c.object({listChanged:c.optional(c.boolean())}).passthrough()),resources:c.optional(c.object({subscribe:c.optional(c.boolean()),listChanged:c.optional(c.boolean())}).passthrough()),tools:c.optional(c.object({listChanged:c.optional(c.boolean())}).passthrough())}).passthrough(),Ws=Xe.extend({protocolVersion:c.string(),capabilities:od,serverInfo:jn,instructions:c.optional(c.string())}),Ks=ir.extend({method:c.literal("notifications/initialized")});var Kt=Fe.extend({method:c.literal("ping")}),id=c.object({progress:c.number(),total:c.optional(c.number()),message:c.optional(c.string())}).passthrough(),Jt=ir.extend({method:c.literal("notifications/progress"),params:Ct.merge(id).extend({progressToken:On})}),Yt=Fe.extend({params:Ge.extend({cursor:c.optional(In)}).optional()}),es=Xe.extend({nextCursor:c.optional(In)}),Mn=c.object({uri:c.string(),mimeType:c.optional(c.string()),_meta:c.optional(c.object({}).passthrough())}).passthrough(),qn=Mn.extend({text:c.string()}),Js=c.string().refine(s=>{try{return atob(s),!0}catch{return!1}},{message:"Invalid Base64 string"}),Un=Mn.extend({blob:Js}),Vn=$t.extend({uri:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),_meta:c.optional(c.object({}).passthrough())}).merge(Dt),cd=$t.extend({uriTemplate:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),_meta:c.optional(c.object({}).passthrough())}).merge(Dt),ld=Yt.extend({method:c.literal("resources/list")}),Ys=es.extend({resources:c.array(Vn)}),ud=Yt.extend({method:c.literal("resources/templates/list")}),ea=es.extend({resourceTemplates:c.array(cd)}),dd=Fe.extend({method:c.literal("resources/read"),params:Ge.extend({uri:c.string()})}),ra=Xe.extend({contents:c.array(c.union([qn,Un]))}),fd=ir.extend({method:c.literal("notifications/resources/list_changed")}),pd=Fe.extend({method:c.literal("resources/subscribe"),params:Ge.extend({uri:c.string()})}),hd=Fe.extend({method:c.literal("resources/unsubscribe"),params:Ge.extend({uri:c.string()})}),md=ir.extend({method:c.literal("notifications/resources/updated"),params:Ct.extend({uri:c.string()})}),vd=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}).passthrough(),gd=$t.extend({description:c.optional(c.string()),arguments:c.optional(c.array(vd)),_meta:c.optional(c.object({}).passthrough())}).merge(Dt),_d=Yt.extend({method:c.literal("prompts/list")}),ta=es.extend({prompts:c.array(gd)}),yd=Fe.extend({method:c.literal("prompts/get"),params:Ge.extend({name:c.string(),arguments:c.optional(c.record(c.string()))})}),sa=c.object({type:c.literal("text"),text:c.string(),_meta:c.optional(c.object({}).passthrough())}).passthrough(),aa=c.object({type:c.literal("image"),data:Js,mimeType:c.string(),_meta:c.optional(c.object({}).passthrough())}).passthrough(),na=c.object({type:c.literal("audio"),data:Js,mimeType:c.string(),_meta:c.optional(c.object({}).passthrough())}).passthrough(),Ed=c.object({type:c.literal("resource"),resource:c.union([qn,Un]),_meta:c.optional(c.object({}).passthrough())}).passthrough(),bd=Vn.extend({type:c.literal("resource_link")}),zn=c.union([sa,aa,na,bd,Ed]),Sd=c.object({role:c.enum(["user","assistant"]),content:zn}).passthrough(),oa=Xe.extend({description:c.optional(c.string()),messages:c.array(Sd)}),xd=ir.extend({method:c.literal("notifications/prompts/list_changed")}),Rd=c.object({title:c.optional(c.string()),readOnlyHint:c.optional(c.boolean()),destructiveHint:c.optional(c.boolean()),idempotentHint:c.optional(c.boolean()),openWorldHint:c.optional(c.boolean())}).passthrough(),Td=$t.extend({description:c.optional(c.string()),inputSchema:c.object({type:c.literal("object"),properties:c.optional(c.object({}).passthrough()),required:c.optional(c.array(c.string()))}).passthrough(),outputSchema:c.optional(c.object({type:c.literal("object"),properties:c.optional(c.object({}).passthrough()),required:c.optional(c.array(c.string()))}).passthrough()),annotations:c.optional(Rd),_meta:c.optional(c.object({}).passthrough())}).merge(Dt),ia=Yt.extend({method:c.literal("tools/list")}),ca=es.extend({tools:c.array(Td)}),rs=Xe.extend({content:c.array(zn).default([]),structuredContent:c.object({}).passthrough().optional(),isError:c.optional(c.boolean())}),sm=rs.or(Xe.extend({toolResult:c.unknown()})),la=Fe.extend({method:c.literal("tools/call"),params:Ge.extend({name:c.string(),arguments:c.optional(c.record(c.unknown()))})}),Pd=ir.extend({method:c.literal("notifications/tools/list_changed")}),kt=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),ua=Fe.extend({method:c.literal("logging/setLevel"),params:Ge.extend({level:kt})}),wd=ir.extend({method:c.literal("notifications/message"),params:Ct.extend({level:kt,logger:c.optional(c.string()),data:c.unknown()})}),Od=c.object({name:c.string().optional()}).passthrough(),Id=c.object({hints:c.optional(c.array(Od)),costPriority:c.optional(c.number().min(0).max(1)),speedPriority:c.optional(c.number().min(0).max(1)),intelligencePriority:c.optional(c.number().min(0).max(1))}).passthrough(),Nd=c.object({role:c.enum(["user","assistant"]),content:c.union([sa,aa,na])}).passthrough(),Ad=Fe.extend({method:c.literal("sampling/createMessage"),params:Ge.extend({messages:c.array(Nd),systemPrompt:c.optional(c.string()),includeContext:c.optional(c.enum(["none","thisServer","allServers"])),temperature:c.optional(c.number()),maxTokens:c.number().int(),stopSequences:c.optional(c.array(c.string())),metadata:c.optional(c.object({}).passthrough()),modelPreferences:c.optional(Id)})}),da=Xe.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens"]).or(c.string())),role:c.enum(["user","assistant"]),content:c.discriminatedUnion("type",[sa,aa,na])}),Cd=c.object({type:c.literal("boolean"),title:c.optional(c.string()),description:c.optional(c.string()),default:c.optional(c.boolean())}).passthrough(),Dd=c.object({type:c.literal("string"),title:c.optional(c.string()),description:c.optional(c.string()),minLength:c.optional(c.number()),maxLength:c.optional(c.number()),format:c.optional(c.enum(["email","uri","date","date-time"]))}).passthrough(),$d=c.object({type:c.enum(["number","integer"]),title:c.optional(c.string()),description:c.optional(c.string()),minimum:c.optional(c.number()),maximum:c.optional(c.number())}).passthrough(),kd=c.object({type:c.literal("string"),title:c.optional(c.string()),description:c.optional(c.string()),enum:c.array(c.string()),enumNames:c.optional(c.array(c.string()))}).passthrough(),Ld=c.union([Cd,Dd,$d,kd]),Fd=Fe.extend({method:c.literal("elicitation/create"),params:Ge.extend({message:c.string(),requestedSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Ld),required:c.optional(c.array(c.string()))}).passthrough()})}),fa=Xe.extend({action:c.enum(["accept","decline","cancel"]),content:c.optional(c.record(c.string(),c.unknown()))}),jd=c.object({type:c.literal("ref/resource"),uri:c.string()}).passthrough();var Md=c.object({type:c.literal("ref/prompt"),name:c.string()}).passthrough(),qd=Fe.extend({method:c.literal("completion/complete"),params:Ge.extend({ref:c.union([Md,jd]),argument:c.object({name:c.string(),value:c.string()}).passthrough(),context:c.optional(c.object({arguments:c.optional(c.record(c.string(),c.string()))}))})}),pa=Xe.extend({completion:c.object({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())}).passthrough()}),Ud=c.object({uri:c.string().startsWith("file://"),name:c.optional(c.string()),_meta:c.optional(c.object({}).passthrough())}).passthrough(),Vd=Fe.extend({method:c.literal("roots/list")}),ha=Xe.extend({roots:c.array(Ud)}),zd=ir.extend({method:c.literal("notifications/roots/list_changed")}),am=c.union([Kt,Qs,qd,ua,yd,_d,ld,ud,dd,pd,hd,la,ia]),nm=c.union([Wt,Jt,Ks,zd]),om=c.union([_r,da,fa,ha]),im=c.union([Kt,Ad,Fd,Vd]),cm=c.union([Wt,Jt,wd,md,fd,Pd,xd]),lm=c.union([_r,Ws,pa,oa,ta,Ys,ea,ra,rs,ca]),Oe=class extends Error{constructor(e,t,a){super(`MCP error ${e}: ${t}`),this.code=e,this.data=a,this.name="McpError"}};var Hd=6e4,vt=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.setNotificationHandler(Wt,t=>{let a=this._requestHandlerAbortControllers.get(t.params.requestId);a?.abort(t.params.reason)}),this.setNotificationHandler(Jt,t=>{this._onprogress(t)}),this.setRequestHandler(Kt,t=>({}))}_setupTimeout(e,t,a,r,n=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:a,resetTimeoutOnProgress:n,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let a=Date.now()-t.startTime;if(t.maxTotalTimeout&&a>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new Oe(Ce.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:a});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var t,a,r;this._transport=e;let n=(t=this.transport)===null||t===void 0?void 0:t.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let o=(a=this.transport)===null||a===void 0?void 0:a.onerror;this._transport.onerror=l=>{o?.(l),this._onerror(l)};let i=(r=this._transport)===null||r===void 0?void 0:r.onmessage;this._transport.onmessage=(l,u)=>{i?.(l,u),Xs(l)||Ln(l)?this._onresponse(l):An(l)?this._onrequest(l,u):Dn(l)?this._onnotification(l):this._onerror(new Error(`Unknown message type: ${JSON.stringify(l)}`))},await this._transport.start()}_onclose(){var e;let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let a=new Oe(Ce.ConnectionClosed,"Connection closed");for(let r of t.values())r(a)}_onerror(e){var t;(t=this.onerror)===null||t===void 0||t.call(this,e)}_onnotification(e){var t;let a=(t=this._notificationHandlers.get(e.method))!==null&&t!==void 0?t:this.fallbackNotificationHandler;a!==void 0&&Promise.resolve().then(()=>a(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,t){var a,r;let n=(a=this._requestHandlers.get(e.method))!==null&&a!==void 0?a:this.fallbackRequestHandler,o=this._transport;if(n===void 0){o?.send({jsonrpc:"2.0",id:e.id,error:{code:Ce.MethodNotFound,message:"Method not found"}}).catch(u=>this._onerror(new Error(`Failed to send an error response: ${u}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let l={signal:i.signal,sessionId:o?.sessionId,_meta:(r=e.params)===null||r===void 0?void 0:r._meta,sendNotification:u=>this.notification(u,{relatedRequestId:e.id}),sendRequest:(u,f,h)=>this.request(u,f,{...h,relatedRequestId:e.id}),authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo};Promise.resolve().then(()=>n(e,l)).then(u=>{if(!i.signal.aborted)return o?.send({result:u,jsonrpc:"2.0",id:e.id})},u=>{var f;if(!i.signal.aborted)return o?.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:Ce.InternalError,message:(f=u.message)!==null&&f!==void 0?f:"Internal error"}})}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...a}=e.params,r=Number(t),n=this._progressHandlers.get(r);if(!n){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let o=this._responseHandlers.get(r),i=this._timeoutInfo.get(r);if(i&&o&&i.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(l){o(l);return}n(a)}_onresponse(e){let t=Number(e.id),a=this._responseHandlers.get(t);if(a===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(t),this._progressHandlers.delete(t),this._cleanupTimeout(t),Xs(e))a(e);else{let r=new Oe(e.error.code,e.error.message,e.error.data);a(r)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,t,a){let{relatedRequestId:r,resumptionToken:n,onresumptiontoken:o}=a??{};return new Promise((i,l)=>{var u,f,h,_,d,m;if(!this._transport){l(new Error("Not connected"));return}((u=this._options)===null||u===void 0?void 0:u.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(f=a?.signal)===null||f===void 0||f.throwIfAborted();let y=this._requestMessageId++,v={...e,jsonrpc:"2.0",id:y};a?.onprogress&&(this._progressHandlers.set(y,a.onprogress),v.params={...e.params,_meta:{...((h=e.params)===null||h===void 0?void 0:h._meta)||{},progressToken:y}});let b=P=>{var N;this._responseHandlers.delete(y),this._progressHandlers.delete(y),this._cleanupTimeout(y),(N=this._transport)===null||N===void 0||N.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:y,reason:String(P)}},{relatedRequestId:r,resumptionToken:n,onresumptiontoken:o}).catch(A=>this._onerror(new Error(`Failed to send cancellation: ${A}`))),l(P)};this._responseHandlers.set(y,P=>{var N;if(!(!((N=a?.signal)===null||N===void 0)&&N.aborted)){if(P instanceof Error)return l(P);try{let A=t.parse(P.result);i(A)}catch(A){l(A)}}}),(_=a?.signal)===null||_===void 0||_.addEventListener("abort",()=>{var P;b((P=a?.signal)===null||P===void 0?void 0:P.reason)});let T=(d=a?.timeout)!==null&&d!==void 0?d:Hd,R=()=>b(new Oe(Ce.RequestTimeout,"Request timed out",{timeout:T}));this._setupTimeout(y,T,a?.maxTotalTimeout,R,(m=a?.resetTimeoutOnProgress)!==null&&m!==void 0?m:!1),this._transport.send(v,{relatedRequestId:r,resumptionToken:n,onresumptiontoken:o}).catch(P=>{this._cleanupTimeout(y),l(P)})})}async notification(e,t){var a,r;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((r=(a=this._options)===null||a===void 0?void 0:a.debouncedNotificationMethods)!==null&&r!==void 0?r:[]).includes(e.method)&&!e.params&&!t?.relatedRequestId){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var l;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let u={...e,jsonrpc:"2.0"};(l=this._transport)===null||l===void 0||l.send(u,t).catch(f=>this._onerror(f))});return}let i={...e,jsonrpc:"2.0"};await this._transport.send(i,t)}setRequestHandler(e,t){let a=e.shape.method.value;this.assertRequestHandlerCapability(a),this._requestHandlers.set(a,(r,n)=>Promise.resolve(t(e.parse(r),n)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){this._notificationHandlers.set(e.shape.method.value,a=>Promise.resolve(t(e.parse(a))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function ts(s,e){return Object.entries(e).reduce((t,[a,r])=>(r&&typeof r=="object"?t[a]=t[a]?{...t[a],...r}:r:t[a]=r,t),{...s})}var Bi=Hs(Ma(),1),bs=class extends vt{constructor(e,t){var a;super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(kt.options.map((r,n)=>[r,n])),this.isMessageIgnored=(r,n)=>{let o=this._loggingLevels.get(n);return o?this.LOG_LEVEL_SEVERITY.get(r)this._oninitialize(r)),this.setNotificationHandler(Ks,()=>{var r;return(r=this.oninitialized)===null||r===void 0?void 0:r.call(this)}),this._capabilities.logging&&this.setRequestHandler(ua,async(r,n)=>{var o;let i=n.sessionId||((o=n.requestInfo)===null||o===void 0?void 0:o.headers["mcp-session-id"])||void 0,{level:l}=r.params,u=kt.safeParse(l);return u.success&&this._loggingLevels.set(i,u.data),{}})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ts(this._capabilities,e)}assertCapabilityForMethod(e){var t,a,r;switch(e){case"sampling/createMessage":if(!(!((t=this._clientCapabilities)===null||t===void 0)&&t.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!(!((a=this._clientCapabilities)===null||a===void 0)&&a.elicitation))throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!(!((r=this._clientCapabilities)===null||r===void 0)&&r.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/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (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"ping":case"initialize":break}}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Gt.includes(t)?t:At,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"},_r)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},da,t)}async elicitInput(e,t){let a=await this.request({method:"elicitation/create",params:e},fa,t);if(a.action==="accept"&&a.content)try{let r=new Bi.default,n=r.compile(e.requestedSchema);if(!n(a.content))throw new Oe(Ce.InvalidParams,`Elicitation response content does not match requested schema: ${r.errorsText(n.errors)}`)}catch(r){throw r instanceof Oe?r:new Oe(Ce.InternalError,`Error validating elicitation response: ${r}`)}return a}async listRoots(e,t){return this.request({method:"roots/list",params:e},ha,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};import Zi from"node:process";var gt=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 t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Rp(t)}clear(){this._buffer=void 0}};function Rp(s){return Fn.parse(JSON.parse(s))}function Ss(s){return JSON.stringify(s)+` -`}var xs=class{constructor(e=Zi.stdin,t=Zi.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new gt,this._started=!1,this._ondata=a=>{this._readBuffer.append(a),this.processReadBuffer()},this._onerror=a=>{var r;(r=this.onerror)===null||r===void 0||r.call(this,a)}}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(var e,t;;)try{let a=this._readBuffer.readMessage();if(a===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,a)}catch(a){(t=this.onerror)===null||t===void 0||t.call(this,a)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),(e=this.onclose)===null||e===void 0||e.call(this)}send(e){return new Promise(t=>{let a=Ss(e);this._stdout.write(a)?t():this._stdout.once("drain",t)})}};var Gi=Hs(Ma(),1),Rs=class extends vt{constructor(e,t){var a;super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=(a=t?.capabilities)!==null&&a!==void 0?a:{},this._ajv=new Gi.default}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ts(this._capabilities,e)}assertCapability(e,t){var a;if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a[e]))throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{let a=await this.request({method:"initialize",params:{protocolVersion:At,capabilities:this._capabilities,clientInfo:this._clientInfo}},Ws,t);if(a===void 0)throw new Error(`Server sent invalid initialize result: ${a}`);if(!Gt.includes(a.protocolVersion))throw new Error(`Server's protocol version is not supported: ${a.protocolVersion}`);this._serverCapabilities=a.capabilities,this._serverVersion=a.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(a.protocolVersion),this._instructions=a.instructions,await this.notification({method:"notifications/initialized"})}catch(a){throw this.close(),a}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var t,a,r,n,o;switch(e){case"logging/setLevel":if(!(!((t=this._serverCapabilities)===null||t===void 0)&&t.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.completions))throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){var t;switch(e){case"notifications/roots/list_changed":if(!(!((t=this._capabilities.roots)===null||t===void 0)&&t.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},_r,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},pa,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},_r,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},oa,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},ta,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},Ys,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},ea,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},ra,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},_r,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},_r,t)}async callTool(e,t=rs,a){let r=await this.request({method:"tools/call",params:e},t,a),n=this.getToolOutputValidator(e.name);if(n){if(!r.structuredContent&&!r.isError)throw new Oe(Ce.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(r.structuredContent)try{if(!n(r.structuredContent))throw new Oe(Ce.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(n.errors)}`)}catch(o){throw o instanceof Oe?o:new Oe(Ce.InvalidParams,`Failed to validate structured content: ${o instanceof Error?o.message:String(o)}`)}}return r}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(let t of e)if(t.outputSchema)try{let a=this._ajv.compile(t.outputSchema);this._cachedToolOutputValidators.set(t.name,a)}catch{}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){let a=await this.request({method:"tools/list",params:e},ca,t);return this.cacheToolOutputSchemas(a.tools),a}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var Lc=Hs(kc(),1);import ws from"node:process";import{PassThrough as Kp}from"node:stream";var Jp=ws.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Yp(){let s={};for(let e of Jp){let t=ws.env[e];t!==void 0&&(t.startsWith("()")||(s[e]=t))}return s}var Ps=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new gt,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new Kp)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{var a,r,n,o,i;this._process=(0,Lc.default)(this._serverParams.command,(a=this._serverParams.args)!==null&&a!==void 0?a:[],{env:{...Yp(),...this._serverParams.env},stdio:["pipe","pipe",(r=this._serverParams.stderr)!==null&&r!==void 0?r:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:ws.platform==="win32"&&eh(),cwd:this._serverParams.cwd}),this._process.on("error",l=>{var u,f;if(l.name==="AbortError"){(u=this.onclose)===null||u===void 0||u.call(this);return}t(l),(f=this.onerror)===null||f===void 0||f.call(this,l)}),this._process.on("spawn",()=>{e()}),this._process.on("close",l=>{var u;this._process=void 0,(u=this.onclose)===null||u===void 0||u.call(this)}),(n=this._process.stdin)===null||n===void 0||n.on("error",l=>{var u;(u=this.onerror)===null||u===void 0||u.call(this,l)}),(o=this._process.stdout)===null||o===void 0||o.on("data",l=>{this._readBuffer.append(l),this.processReadBuffer()}),(i=this._process.stdout)===null||i===void 0||i.on("error",l=>{var u;(u=this.onerror)===null||u===void 0||u.call(this,l)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,t;return this._stderrStream?this._stderrStream:(t=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&t!==void 0?t:null}get pid(){var e,t;return(t=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&t!==void 0?t:null}processReadBuffer(){for(var e,t;;)try{let a=this._readBuffer.readMessage();if(a===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,a)}catch(a){(t=this.onerror)===null||t===void 0||t.call(this,a)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(t=>{var a;if(!(!((a=this._process)===null||a===void 0)&&a.stdin))throw new Error("Not connected");let r=Ss(e);this._process.stdin.write(r)?t():this._process.stdin.once("drain",t)})}};function eh(){return"type"in ws}var jc=Symbol("Let zodToJsonSchema decide on which parser to use");var Fc={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Mc=s=>typeof s=="string"?{...Fc,name:s}:{...Fc,...s};var qc=s=>{let e=Mc(s),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([a,r])=>[r._def,{def:r._def,path:[...e.basePath,e.definitionPath,a],jsonSchema:void 0}]))}};function Qa(s,e,t,a){a?.errorMessages&&t&&(s.errorMessage={...s.errorMessage,[e]:t})}function ee(s,e,t,a,r){s[e]=t,Qa(s,e,a,r)}var Os=(s,e)=>{let t=0;for(;tG(s.innerType._def,e);function Wa(s,e,t){let a=t??e.dateStrategy;if(Array.isArray(a))return{anyOf:a.map((r,n)=>Wa(s,e,r))};switch(a){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return rh(s,e)}}var rh=(s,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let a of s.checks)switch(a.kind){case"min":ee(t,"minimum",a.value,a.message,e);break;case"max":ee(t,"maximum",a.value,a.message,e);break}return t};function Bc(s,e){return{...G(s.innerType._def,e),default:s.defaultValue()}}function Zc(s,e){return e.effectStrategy==="input"?G(s.schema._def,e):fe(e)}function Gc(s){return{type:"string",enum:Array.from(s.values)}}var th=s=>"type"in s&&s.type==="string"?!1:"allOf"in s;function Xc(s,e){let t=[G(s.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),G(s.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(n=>!!n),a=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,r=[];return t.forEach(n=>{if(th(n))r.push(...n.allOf),n.unevaluatedProperties===void 0&&(a=void 0);else{let o=n;if("additionalProperties"in n&&n.additionalProperties===!1){let{additionalProperties:i,...l}=n;o=l}else a=void 0;r.push(o)}}),r.length?{allOf:r,...a}:void 0}function Qc(s,e){let t=typeof s.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(s.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[s.value]}:{type:t==="bigint"?"integer":t,const:s.value}}var Ka,Je={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Ka===void 0&&(Ka=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ka),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Ns(s,e){let t={type:"string"};if(s.checks)for(let a of s.checks)switch(a.kind){case"min":ee(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,a.value):a.value,a.message,e);break;case"max":ee(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,a.value):a.value,a.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Ye(t,"email",a.message,e);break;case"format:idn-email":Ye(t,"idn-email",a.message,e);break;case"pattern:zod":De(t,Je.email,a.message,e);break}break;case"url":Ye(t,"uri",a.message,e);break;case"uuid":Ye(t,"uuid",a.message,e);break;case"regex":De(t,a.regex,a.message,e);break;case"cuid":De(t,Je.cuid,a.message,e);break;case"cuid2":De(t,Je.cuid2,a.message,e);break;case"startsWith":De(t,RegExp(`^${Ja(a.value,e)}`),a.message,e);break;case"endsWith":De(t,RegExp(`${Ja(a.value,e)}$`),a.message,e);break;case"datetime":Ye(t,"date-time",a.message,e);break;case"date":Ye(t,"date",a.message,e);break;case"time":Ye(t,"time",a.message,e);break;case"duration":Ye(t,"duration",a.message,e);break;case"length":ee(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,a.value):a.value,a.message,e),ee(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,a.value):a.value,a.message,e);break;case"includes":{De(t,RegExp(Ja(a.value,e)),a.message,e);break}case"ip":{a.version!=="v6"&&Ye(t,"ipv4",a.message,e),a.version!=="v4"&&Ye(t,"ipv6",a.message,e);break}case"base64url":De(t,Je.base64url,a.message,e);break;case"jwt":De(t,Je.jwt,a.message,e);break;case"cidr":{a.version!=="v6"&&De(t,Je.ipv4Cidr,a.message,e),a.version!=="v4"&&De(t,Je.ipv6Cidr,a.message,e);break}case"emoji":De(t,Je.emoji(),a.message,e);break;case"ulid":{De(t,Je.ulid,a.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Ye(t,"binary",a.message,e);break}case"contentEncoding:base64":{ee(t,"contentEncoding","base64",a.message,e);break}case"pattern:zod":{De(t,Je.base64,a.message,e);break}}break}case"nanoid":De(t,Je.nanoid,a.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function Ja(s,e){return e.patternStrategy==="escape"?ah(s):s}var sh=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ah(s){let e="";for(let t=0;tr.format)?(s.anyOf||(s.anyOf=[]),s.format&&(s.anyOf.push({format:s.format,...s.errorMessage&&a.errorMessages&&{errorMessage:{format:s.errorMessage.format}}}),delete s.format,s.errorMessage&&(delete s.errorMessage.format,Object.keys(s.errorMessage).length===0&&delete s.errorMessage)),s.anyOf.push({format:e,...t&&a.errorMessages&&{errorMessage:{format:t}}})):ee(s,"format",e,t,a)}function De(s,e,t,a){s.pattern||s.allOf?.some(r=>r.pattern)?(s.allOf||(s.allOf=[]),s.pattern&&(s.allOf.push({pattern:s.pattern,...s.errorMessage&&a.errorMessages&&{errorMessage:{pattern:s.errorMessage.pattern}}}),delete s.pattern,s.errorMessage&&(delete s.errorMessage.pattern,Object.keys(s.errorMessage).length===0&&delete s.errorMessage)),s.allOf.push({pattern:Wc(e,a),...t&&a.errorMessages&&{errorMessage:{pattern:t}}})):ee(s,"pattern",Wc(e,a),t,a)}function Wc(s,e){if(!e.applyRegexFlags||!s.flags)return s.source;let t={i:s.flags.includes("i"),m:s.flags.includes("m"),s:s.flags.includes("s")},a=t.i?s.source.toLowerCase():s.source,r="",n=!1,o=!1,i=!1;for(let l=0;l({...a,[r]:G(s.valueType._def,{...e,currentPath:[...e.currentPath,"properties",r]})??fe(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:G(s.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(s.keyType?._def.typeName===O.ZodString&&s.keyType._def.checks?.length){let{type:a,...r}=Ns(s.keyType._def,e);return{...t,propertyNames:r}}else{if(s.keyType?._def.typeName===O.ZodEnum)return{...t,propertyNames:{enum:s.keyType._def.values}};if(s.keyType?._def.typeName===O.ZodBranded&&s.keyType._def.type._def.typeName===O.ZodString&&s.keyType._def.type._def.checks?.length){let{type:a,...r}=Is(s.keyType._def,e);return{...t,propertyNames:r}}}return t}function Kc(s,e){if(e.mapStrategy==="record")return As(s,e);let t=G(s.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||fe(e),a=G(s.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||fe(e);return{type:"array",maxItems:125,items:{type:"array",items:[t,a],minItems:2,maxItems:2}}}function Jc(s){let e=s.values,a=Object.keys(s.values).filter(n=>typeof e[e[n]]!="number").map(n=>e[n]),r=Array.from(new Set(a.map(n=>typeof n)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:a}}function Yc(s){return s.target==="openAi"?void 0:{not:fe({...s,currentPath:[...s.currentPath,"not"]})}}function el(s){return s.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ft={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function tl(s,e){if(e.target==="openApi3")return rl(s,e);let t=s.options instanceof Map?Array.from(s.options.values()):s.options;if(t.every(a=>a._def.typeName in Ft&&(!a._def.checks||!a._def.checks.length))){let a=t.reduce((r,n)=>{let o=Ft[n._def.typeName];return o&&!r.includes(o)?[...r,o]:r},[]);return{type:a.length>1?a:a[0]}}else if(t.every(a=>a._def.typeName==="ZodLiteral"&&!a.description)){let a=t.reduce((r,n)=>{let o=typeof n._def.value;switch(o){case"string":case"number":case"boolean":return[...r,o];case"bigint":return[...r,"integer"];case"object":if(n._def.value===null)return[...r,"null"];case"symbol":case"undefined":case"function":default:return r}},[]);if(a.length===t.length){let r=a.filter((n,o,i)=>i.indexOf(n)===o);return{type:r.length>1?r:r[0],enum:t.reduce((n,o)=>n.includes(o._def.value)?n:[...n,o._def.value],[])}}}else if(t.every(a=>a._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((a,r)=>[...a,...r._def.values.filter(n=>!a.includes(n))],[])};return rl(s,e)}var rl=(s,e)=>{let t=(s.options instanceof Map?Array.from(s.options.values()):s.options).map((a,r)=>G(a._def,{...e,currentPath:[...e.currentPath,"anyOf",`${r}`]})).filter(a=>!!a&&(!e.strictUnions||typeof a=="object"&&Object.keys(a).length>0));return t.length?{anyOf:t}:void 0};function sl(s,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(s.innerType._def.typeName)&&(!s.innerType._def.checks||!s.innerType._def.checks.length))return e.target==="openApi3"?{type:Ft[s.innerType._def.typeName],nullable:!0}:{type:[Ft[s.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let a=G(s.innerType._def,{...e,currentPath:[...e.currentPath]});return a&&"$ref"in a?{allOf:[a],nullable:!0}:a&&{...a,nullable:!0}}let t=G(s.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function al(s,e){let t={type:"number"};if(!s.checks)return t;for(let a of s.checks)switch(a.kind){case"int":t.type="integer",Qa(t,"type",a.message,e);break;case"min":e.target==="jsonSchema7"?a.inclusive?ee(t,"minimum",a.value,a.message,e):ee(t,"exclusiveMinimum",a.value,a.message,e):(a.inclusive||(t.exclusiveMinimum=!0),ee(t,"minimum",a.value,a.message,e));break;case"max":e.target==="jsonSchema7"?a.inclusive?ee(t,"maximum",a.value,a.message,e):ee(t,"exclusiveMaximum",a.value,a.message,e):(a.inclusive||(t.exclusiveMaximum=!0),ee(t,"maximum",a.value,a.message,e));break;case"multipleOf":ee(t,"multipleOf",a.value,a.message,e);break}return t}function nl(s,e){let t=e.target==="openAi",a={type:"object",properties:{}},r=[],n=s.shape();for(let i in n){let l=n[i];if(l===void 0||l._def===void 0)continue;let u=oh(l);u&&t&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),u=!1);let f=G(l._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});f!==void 0&&(a.properties[i]=f,u||r.push(i))}r.length&&(a.required=r);let o=nh(s,e);return o!==void 0&&(a.additionalProperties=o),a}function nh(s,e){if(s.catchall._def.typeName!=="ZodNever")return G(s.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(s.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function oh(s){try{return s.isOptional()}catch{return!0}}var ol=(s,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return G(s.innerType._def,e);let t=G(s.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:fe(e)},t]}:fe(e)};var il=(s,e)=>{if(e.pipeStrategy==="input")return G(s.in._def,e);if(e.pipeStrategy==="output")return G(s.out._def,e);let t=G(s.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),a=G(s.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,a].filter(r=>r!==void 0)}};function cl(s,e){return G(s.type._def,e)}function ll(s,e){let a={type:"array",uniqueItems:!0,items:G(s.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return s.minSize&&ee(a,"minItems",s.minSize.value,s.minSize.message,e),s.maxSize&&ee(a,"maxItems",s.maxSize.value,s.maxSize.message,e),a}function ul(s,e){return s.rest?{type:"array",minItems:s.items.length,items:s.items.map((t,a)=>G(t._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((t,a)=>a===void 0?t:[...t,a],[]),additionalItems:G(s.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:s.items.length,maxItems:s.items.length,items:s.items.map((t,a)=>G(t._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((t,a)=>a===void 0?t:[...t,a],[])}}function dl(s){return{not:fe(s)}}function fl(s){return fe(s)}var pl=(s,e)=>G(s.innerType._def,e);var hl=(s,e,t)=>{switch(e){case O.ZodString:return Ns(s,t);case O.ZodNumber:return al(s,t);case O.ZodObject:return nl(s,t);case O.ZodBigInt:return Vc(s,t);case O.ZodBoolean:return zc();case O.ZodDate:return Wa(s,t);case O.ZodUndefined:return dl(t);case O.ZodNull:return el(t);case O.ZodArray:return Uc(s,t);case O.ZodUnion:case O.ZodDiscriminatedUnion:return tl(s,t);case O.ZodIntersection:return Xc(s,t);case O.ZodTuple:return ul(s,t);case O.ZodRecord:return As(s,t);case O.ZodLiteral:return Qc(s,t);case O.ZodEnum:return Gc(s);case O.ZodNativeEnum:return Jc(s);case O.ZodNullable:return sl(s,t);case O.ZodOptional:return ol(s,t);case O.ZodMap:return Kc(s,t);case O.ZodSet:return ll(s,t);case O.ZodLazy:return()=>s.getter()._def;case O.ZodPromise:return cl(s,t);case O.ZodNaN:case O.ZodNever:return Yc(t);case O.ZodEffects:return Zc(s,t);case O.ZodAny:return fe(t);case O.ZodUnknown:return fl(t);case O.ZodDefault:return Bc(s,t);case O.ZodBranded:return Is(s,t);case O.ZodReadonly:return pl(s,t);case O.ZodCatch:return Hc(s,t);case O.ZodPipeline:return il(s,t);case O.ZodFunction:case O.ZodVoid:case O.ZodSymbol:return;default:return(a=>{})(e)}};function G(s,e,t=!1){let a=e.seen.get(s);if(e.override){let i=e.override?.(s,e,a,t);if(i!==jc)return i}if(a&&!t){let i=ih(a,e);if(i!==void 0)return i}let r={def:s,path:e.currentPath,jsonSchema:void 0};e.seen.set(s,r);let n=hl(s,s.typeName,e),o=typeof n=="function"?G(n(),e):n;if(o&&ch(s,e,o),e.postProcess){let i=e.postProcess(o,s,e);return r.jsonSchema=o,i}return r.jsonSchema=o,o}var ih=(s,e)=>{switch(e.$refStrategy){case"root":return{$ref:s.path.join("/")};case"relative":return{$ref:Os(e.currentPath,s.path)};case"none":case"seen":return s.path.lengthe.currentPath[a]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),fe(e)):e.$refStrategy==="seen"?fe(e):void 0}},ch=(s,e,t)=>(s.description&&(t.description=s.description,e.markdownDescription&&(t.markdownDescription=s.description)),t);var Ya=(s,e)=>{let t=qc(e),a=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[u,f])=>({...l,[u]:G(f._def,{...t,currentPath:[...t.basePath,t.definitionPath,u]},!0)??fe(t)}),{}):void 0,r=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,n=G(s._def,r===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,r]},!1)??fe(t),o=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;o!==void 0&&(n.title=o),t.flags.hasReferencedOpenAiAnyType&&(a||(a={}),a[t.openAiAnyTypeName]||(a[t.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:t.$refStrategy==="relative"?"1":[...t.basePath,t.definitionPath,t.openAiAnyTypeName].join("/")}}));let i=r===void 0?a?{...n,[t.definitionPath]:a}:n:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,r].join("/"),[t.definitionPath]:{...a,[r]:n}};return t.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};import{basename as mh}from"path";import ph from"better-sqlite3";import{join as Qe,dirname as lh,basename as Ty}from"path";import{homedir as ml}from"os";import{existsSync as Iy,mkdirSync as uh}from"fs";import{fileURLToPath as dh}from"url";function fh(){return typeof __dirname<"u"?__dirname:lh(dh(import.meta.url))}var Ay=fh(),er=process.env.CLAUDE_MEM_DATA_DIR||Qe(ml(),".claude-mem"),en=process.env.CLAUDE_CONFIG_DIR||Qe(ml(),".claude"),Cy=Qe(er,"archives"),Dy=Qe(er,"logs"),$y=Qe(er,"trash"),ky=Qe(er,"backups"),Ly=Qe(er,"settings.json"),Cs=Qe(er,"claude-mem.db"),vl=Qe(er,"vector-db"),Fy=Qe(en,"settings.json"),jy=Qe(en,"commands"),My=Qe(en,"CLAUDE.md");function Ds(s){uh(s,{recursive:!0})}var $s=class{db;constructor(e){e||(Ds(er),e=Cs),this.db=new ph(e),this.db.pragma("journal_mode = WAL"),this.ensureFTSTables()}ensureFTSTables(){try{if(this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%_fts'").all().some(a=>a.name==="observations_fts"||a.name==="session_summaries_fts"))return;console.error("[SessionSearch] Creating FTS5 tables..."),this.db.exec(` - CREATE VIRTUAL TABLE IF NOT EXISTS observations_fts USING fts5( - title, - subtitle, - narrative, - text, - facts, - concepts, - content='observations', - content_rowid='id' - ); - `),this.db.exec(` - INSERT INTO observations_fts(rowid, title, subtitle, narrative, text, facts, concepts) - SELECT id, title, subtitle, narrative, text, facts, concepts - FROM observations; - `),this.db.exec(` - CREATE TRIGGER IF NOT EXISTS observations_ai AFTER INSERT ON observations BEGIN - INSERT INTO observations_fts(rowid, title, subtitle, narrative, text, facts, concepts) - VALUES (new.id, new.title, new.subtitle, new.narrative, new.text, new.facts, new.concepts); - END; - - CREATE TRIGGER IF NOT EXISTS observations_ad AFTER DELETE ON observations BEGIN - INSERT INTO observations_fts(observations_fts, rowid, title, subtitle, narrative, text, facts, concepts) - VALUES('delete', old.id, old.title, old.subtitle, old.narrative, old.text, old.facts, old.concepts); - END; - - CREATE TRIGGER IF NOT EXISTS observations_au AFTER UPDATE ON observations BEGIN - INSERT INTO observations_fts(observations_fts, rowid, title, subtitle, narrative, text, facts, concepts) - VALUES('delete', old.id, old.title, old.subtitle, old.narrative, old.text, old.facts, old.concepts); - INSERT INTO observations_fts(rowid, title, subtitle, narrative, text, facts, concepts) - VALUES (new.id, new.title, new.subtitle, new.narrative, new.text, new.facts, new.concepts); - END; - `),this.db.exec(` - CREATE VIRTUAL TABLE IF NOT EXISTS session_summaries_fts USING fts5( - request, - investigated, - learned, - completed, - next_steps, - notes, - content='session_summaries', - content_rowid='id' - ); - `),this.db.exec(` - INSERT INTO session_summaries_fts(rowid, request, investigated, learned, completed, next_steps, notes) - SELECT id, request, investigated, learned, completed, next_steps, notes - FROM session_summaries; - `),this.db.exec(` - CREATE TRIGGER IF NOT EXISTS session_summaries_ai AFTER INSERT ON session_summaries BEGIN - INSERT INTO session_summaries_fts(rowid, request, investigated, learned, completed, next_steps, notes) - VALUES (new.id, new.request, new.investigated, new.learned, new.completed, new.next_steps, new.notes); - END; - - CREATE TRIGGER IF NOT EXISTS session_summaries_ad AFTER DELETE ON session_summaries BEGIN - INSERT INTO session_summaries_fts(session_summaries_fts, rowid, request, investigated, learned, completed, next_steps, notes) - VALUES('delete', old.id, old.request, old.investigated, old.learned, old.completed, old.next_steps, old.notes); - END; - - CREATE TRIGGER IF NOT EXISTS session_summaries_au AFTER UPDATE ON session_summaries BEGIN - INSERT INTO session_summaries_fts(session_summaries_fts, rowid, request, investigated, learned, completed, next_steps, notes) - VALUES('delete', old.id, old.request, old.investigated, old.learned, old.completed, old.next_steps, old.notes); - INSERT INTO session_summaries_fts(rowid, request, investigated, learned, completed, next_steps, notes) - VALUES (new.id, new.request, new.investigated, new.learned, new.completed, new.next_steps, new.notes); - END; - `),console.error("[SessionSearch] FTS5 tables created successfully")}catch(e){console.error("[SessionSearch] FTS migration error:",e.message)}}escapeFTS5(e){return`"${e.replace(/"/g,'""')}"`}buildFilterClause(e,t,a="o"){let r=[];if(e.project&&(r.push(`${a}.project = ?`),t.push(e.project)),e.type)if(Array.isArray(e.type)){let n=e.type.map(()=>"?").join(",");r.push(`${a}.type IN (${n})`),t.push(...e.type)}else r.push(`${a}.type = ?`),t.push(e.type);if(e.dateRange){let{start:n,end:o}=e.dateRange;if(n){let i=typeof n=="number"?n:new Date(n).getTime();r.push(`${a}.created_at_epoch >= ?`),t.push(i)}if(o){let i=typeof o=="number"?o:new Date(o).getTime();r.push(`${a}.created_at_epoch <= ?`),t.push(i)}}if(e.concepts){let n=Array.isArray(e.concepts)?e.concepts:[e.concepts],o=n.map(()=>`EXISTS (SELECT 1 FROM json_each(${a}.concepts) WHERE value = ?)`);o.length>0&&(r.push(`(${o.join(" OR ")})`),t.push(...n))}if(e.files){let n=Array.isArray(e.files)?e.files:[e.files],o=n.map(()=>`( - EXISTS (SELECT 1 FROM json_each(${a}.files_read) WHERE value LIKE ?) - OR EXISTS (SELECT 1 FROM json_each(${a}.files_modified) WHERE value LIKE ?) - )`);o.length>0&&(r.push(`(${o.join(" OR ")})`),n.forEach(i=>{t.push(`%${i}%`,`%${i}%`)}))}return r.length>0?r.join(" AND "):""}buildOrderClause(e="relevance",t=!0,a="observations_fts"){switch(e){case"relevance":return t?`ORDER BY ${a}.rank ASC`:"ORDER BY o.created_at_epoch DESC";case"date_desc":return"ORDER BY o.created_at_epoch DESC";case"date_asc":return"ORDER BY o.created_at_epoch ASC";default:return"ORDER BY o.created_at_epoch DESC"}}searchObservations(e,t={}){let a=[],{limit:r=50,offset:n=0,orderBy:o="relevance",...i}=t,l=this.escapeFTS5(e);a.push(l);let u=this.buildFilterClause(i,a,"o"),f=u?`AND ${u}`:"",h=this.buildOrderClause(o,!0),_=` - SELECT - o.*, - observations_fts.rank as rank - FROM observations o - JOIN observations_fts ON o.id = observations_fts.rowid - WHERE observations_fts MATCH ? - ${f} - ${h} - LIMIT ? OFFSET ? - `;a.push(r,n);let d=this.db.prepare(_).all(...a);if(d.length>0){let m=Math.min(...d.map(b=>b.rank||0)),v=Math.max(...d.map(b=>b.rank||0))-m||1;d.forEach(b=>{b.rank!==void 0&&(b.score=1-(b.rank-m)/v)})}return d}searchSessions(e,t={}){let a=[],{limit:r=50,offset:n=0,orderBy:o="relevance",...i}=t,l=this.escapeFTS5(e);a.push(l);let u={...i};delete u.type;let f=this.buildFilterClause(u,a,"s"),m=` - SELECT - s.*, - session_summaries_fts.rank as rank - FROM session_summaries s - JOIN session_summaries_fts ON s.id = session_summaries_fts.rowid - WHERE session_summaries_fts MATCH ? - ${(f?`AND ${f}`:"").replace(/files_read/g,"files_read").replace(/files_modified/g,"files_edited")} - ${o==="relevance"?"ORDER BY session_summaries_fts.rank ASC":o==="date_asc"?"ORDER BY s.created_at_epoch ASC":"ORDER BY s.created_at_epoch DESC"} - LIMIT ? OFFSET ? - `;a.push(r,n);let y=this.db.prepare(m).all(...a);if(y.length>0){let v=Math.min(...y.map(R=>R.rank||0)),T=Math.max(...y.map(R=>R.rank||0))-v||1;y.forEach(R=>{R.rank!==void 0&&(R.score=1-(R.rank-v)/T)})}return y}findByConcept(e,t={}){let a=[],{limit:r=50,offset:n=0,orderBy:o="date_desc",...i}=t,l={...i,concepts:e},u=this.buildFilterClause(l,a,"o"),f=this.buildOrderClause(o,!1),h=` - SELECT o.* - FROM observations o - WHERE ${u} - ${f} - LIMIT ? OFFSET ? - `;return a.push(r,n),this.db.prepare(h).all(...a)}findByFile(e,t={}){let a=[],{limit:r=50,offset:n=0,orderBy:o="date_desc",...i}=t,l={...i,files:e},u=this.buildFilterClause(l,a,"o"),f=this.buildOrderClause(o,!1),h=` - SELECT o.* - FROM observations o - WHERE ${u} - ${f} - LIMIT ? OFFSET ? - `;a.push(r,n);let _=this.db.prepare(h).all(...a),d=[],m={...i};delete m.type;let y=[];if(m.project&&(y.push("s.project = ?"),d.push(m.project)),m.dateRange){let{start:T,end:R}=m.dateRange;if(T){let P=typeof T=="number"?T:new Date(T).getTime();y.push("s.created_at_epoch >= ?"),d.push(P)}if(R){let P=typeof R=="number"?R:new Date(R).getTime();y.push("s.created_at_epoch <= ?"),d.push(P)}}y.push(`( - EXISTS (SELECT 1 FROM json_each(s.files_read) WHERE value LIKE ?) - OR EXISTS (SELECT 1 FROM json_each(s.files_edited) WHERE value LIKE ?) - )`),d.push(`%${e}%`,`%${e}%`);let v=` - SELECT s.* - FROM session_summaries s - WHERE ${y.join(" AND ")} - ORDER BY s.created_at_epoch DESC - LIMIT ? OFFSET ? - `;d.push(r,n);let b=this.db.prepare(v).all(...d);return{observations:_,sessions:b}}findByType(e,t={}){let a=[],{limit:r=50,offset:n=0,orderBy:o="date_desc",...i}=t,l={...i,type:e},u=this.buildFilterClause(l,a,"o"),f=this.buildOrderClause(o,!1),h=` - SELECT o.* - FROM observations o - WHERE ${u} - ${f} - LIMIT ? OFFSET ? - `;return a.push(r,n),this.db.prepare(h).all(...a)}searchUserPrompts(e,t={}){let a=[],{limit:r=20,offset:n=0,orderBy:o="relevance",...i}=t,l=this.escapeFTS5(e);a.push(l);let u=[];if(i.project&&(u.push("s.project = ?"),a.push(i.project)),i.dateRange){let{start:m,end:y}=i.dateRange;if(m){let v=typeof m=="number"?m:new Date(m).getTime();u.push("up.created_at_epoch >= ?"),a.push(v)}if(y){let v=typeof y=="number"?y:new Date(y).getTime();u.push("up.created_at_epoch <= ?"),a.push(v)}}let _=` - SELECT - up.*, - user_prompts_fts.rank as rank - FROM user_prompts up - JOIN user_prompts_fts ON up.id = user_prompts_fts.rowid - JOIN sdk_sessions s ON up.claude_session_id = s.claude_session_id - WHERE user_prompts_fts MATCH ? - ${u.length>0?`AND ${u.join(" AND ")}`:""} - ${o==="relevance"?"ORDER BY user_prompts_fts.rank ASC":o==="date_asc"?"ORDER BY up.created_at_epoch ASC":"ORDER BY up.created_at_epoch DESC"} - LIMIT ? OFFSET ? - `;a.push(r,n);let d=this.db.prepare(_).all(...a);if(d.length>0){let m=Math.min(...d.map(b=>b.rank||0)),v=Math.max(...d.map(b=>b.rank||0))-m||1;d.forEach(b=>{b.rank!==void 0&&(b.score=1-(b.rank-m)/v)})}return d}getUserPromptsBySession(e){return this.db.prepare(` - SELECT - id, - claude_session_id, - prompt_number, - prompt_text, - created_at, - created_at_epoch - FROM user_prompts - WHERE claude_session_id = ? - ORDER BY prompt_number ASC - `).all(e)}close(){this.db.close()}};import hh from"better-sqlite3";var rn=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n[n.SILENT=4]="SILENT",n))(rn||{}),tn=class{level;useColor;constructor(){let e=process.env.CLAUDE_MEM_LOG_LEVEL?.toUpperCase()||"INFO";this.level=rn[e]??1,this.useColor=process.stdout.isTTY??!1}correlationId(e,t){return`obs-${e}-${t}`}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.level===0?`${e.message} -${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let t=Object.keys(e);return t.length===0?"{}":t.length<=3?JSON.stringify(e):`{${t.length} keys: ${t.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,t){if(!t)return e;try{let a=typeof t=="string"?JSON.parse(t):t;if(e==="Bash"&&a.command){let r=a.command.length>50?a.command.substring(0,50)+"...":a.command;return`${e}(${r})`}if(e==="Read"&&a.file_path){let r=a.file_path.split("/").pop()||a.file_path;return`${e}(${r})`}if(e==="Edit"&&a.file_path){let r=a.file_path.split("/").pop()||a.file_path;return`${e}(${r})`}if(e==="Write"&&a.file_path){let r=a.file_path.split("/").pop()||a.file_path;return`${e}(${r})`}return e}catch{return e}}log(e,t,a,r,n){if(e0&&(h=` {${Object.entries(v).map(([T,R])=>`${T}=${R}`).join(", ")}}`)}let _=`[${o}] [${i}] [${l}] ${u}${a}${h}${f}`;e===3?console.error(_):console.log(_)}debug(e,t,a,r){this.log(0,e,t,a,r)}info(e,t,a,r){this.log(1,e,t,a,r)}warn(e,t,a,r){this.log(2,e,t,a,r)}error(e,t,a,r){this.log(3,e,t,a,r)}dataIn(e,t,a,r){this.info(e,`\u2192 ${t}`,a,r)}dataOut(e,t,a,r){this.info(e,`\u2190 ${t}`,a,r)}success(e,t,a,r){this.info(e,`\u2713 ${t}`,a,r)}failure(e,t,a,r){this.error(e,`\u2717 ${t}`,a,r)}timing(e,t,a,r){this.info(e,`\u23F1 ${t}`,r,{duration:`${a}ms`})}},gl=new tn;var ks=class{db;constructor(){Ds(er),this.db=new hh(Cs),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),this.initializeSchema(),this.ensureWorkerPortColumn(),this.ensurePromptTrackingColumns(),this.removeSessionSummariesUniqueConstraint(),this.addObservationHierarchicalFields(),this.makeObservationsTextNullable(),this.createUserPromptsTable()}initializeSchema(){try{this.db.exec(` - CREATE TABLE IF NOT EXISTS schema_versions ( - id INTEGER PRIMARY KEY, - version INTEGER UNIQUE NOT NULL, - applied_at TEXT NOT NULL - ) - `);let e=this.db.prepare("SELECT version FROM schema_versions ORDER BY version").all();(e.length>0?Math.max(...e.map(a=>a.version)):0)===0&&(console.error("[SessionStore] Initializing fresh database with migration004..."),this.db.exec(` - CREATE TABLE IF NOT EXISTS sdk_sessions ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - claude_session_id TEXT UNIQUE NOT NULL, - sdk_session_id TEXT UNIQUE, - project TEXT NOT NULL, - user_prompt TEXT, - started_at TEXT NOT NULL, - started_at_epoch INTEGER NOT NULL, - completed_at TEXT, - completed_at_epoch INTEGER, - status TEXT CHECK(status IN ('active', 'completed', 'failed')) NOT NULL DEFAULT 'active' - ); - - CREATE INDEX IF NOT EXISTS idx_sdk_sessions_claude_id ON sdk_sessions(claude_session_id); - CREATE INDEX IF NOT EXISTS idx_sdk_sessions_sdk_id ON sdk_sessions(sdk_session_id); - CREATE INDEX IF NOT EXISTS idx_sdk_sessions_project ON sdk_sessions(project); - CREATE INDEX IF NOT EXISTS idx_sdk_sessions_status ON sdk_sessions(status); - CREATE INDEX IF NOT EXISTS idx_sdk_sessions_started ON sdk_sessions(started_at_epoch DESC); - - CREATE TABLE IF NOT EXISTS observations ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - sdk_session_id TEXT NOT NULL, - project TEXT NOT NULL, - text TEXT NOT NULL, - type TEXT NOT NULL CHECK(type IN ('decision', 'bugfix', 'feature', 'refactor', 'discovery')), - created_at TEXT NOT NULL, - created_at_epoch INTEGER NOT NULL, - FOREIGN KEY(sdk_session_id) REFERENCES sdk_sessions(sdk_session_id) ON DELETE CASCADE - ); - - CREATE INDEX IF NOT EXISTS idx_observations_sdk_session ON observations(sdk_session_id); - CREATE INDEX IF NOT EXISTS idx_observations_project ON observations(project); - CREATE INDEX IF NOT EXISTS idx_observations_type ON observations(type); - CREATE INDEX IF NOT EXISTS idx_observations_created ON observations(created_at_epoch DESC); - - CREATE TABLE IF NOT EXISTS session_summaries ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - sdk_session_id TEXT UNIQUE NOT NULL, - project TEXT NOT NULL, - request TEXT, - investigated TEXT, - learned TEXT, - completed TEXT, - next_steps TEXT, - files_read TEXT, - files_edited TEXT, - notes TEXT, - created_at TEXT NOT NULL, - created_at_epoch INTEGER NOT NULL, - FOREIGN KEY(sdk_session_id) REFERENCES sdk_sessions(sdk_session_id) ON DELETE CASCADE - ); - - CREATE INDEX IF NOT EXISTS idx_session_summaries_sdk_session ON session_summaries(sdk_session_id); - CREATE INDEX IF NOT EXISTS idx_session_summaries_project ON session_summaries(project); - CREATE INDEX IF NOT EXISTS idx_session_summaries_created ON session_summaries(created_at_epoch DESC); - `),this.db.prepare("INSERT INTO schema_versions (version, applied_at) VALUES (?, ?)").run(4,new Date().toISOString()),console.error("[SessionStore] Migration004 applied successfully"))}catch(e){throw console.error("[SessionStore] Schema initialization error:",e.message),e}}ensureWorkerPortColumn(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(5))return;this.db.pragma("table_info(sdk_sessions)").some(r=>r.name==="worker_port")||(this.db.exec("ALTER TABLE sdk_sessions ADD COLUMN worker_port INTEGER"),console.error("[SessionStore] Added worker_port column to sdk_sessions table")),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(5,new Date().toISOString())}catch(e){console.error("[SessionStore] Migration error:",e.message)}}ensurePromptTrackingColumns(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(6))return;this.db.pragma("table_info(sdk_sessions)").some(l=>l.name==="prompt_counter")||(this.db.exec("ALTER TABLE sdk_sessions ADD COLUMN prompt_counter INTEGER DEFAULT 0"),console.error("[SessionStore] Added prompt_counter column to sdk_sessions table")),this.db.pragma("table_info(observations)").some(l=>l.name==="prompt_number")||(this.db.exec("ALTER TABLE observations ADD COLUMN prompt_number INTEGER"),console.error("[SessionStore] Added prompt_number column to observations table")),this.db.pragma("table_info(session_summaries)").some(l=>l.name==="prompt_number")||(this.db.exec("ALTER TABLE session_summaries ADD COLUMN prompt_number INTEGER"),console.error("[SessionStore] Added prompt_number column to session_summaries table")),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(6,new Date().toISOString())}catch(e){console.error("[SessionStore] Prompt tracking migration error:",e.message)}}removeSessionSummariesUniqueConstraint(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(7))return;if(!this.db.pragma("index_list(session_summaries)").some(r=>r.unique===1)){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(7,new Date().toISOString());return}console.error("[SessionStore] Removing UNIQUE constraint from session_summaries.sdk_session_id..."),this.db.exec("BEGIN TRANSACTION");try{this.db.exec(` - CREATE TABLE session_summaries_new ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - sdk_session_id TEXT NOT NULL, - project TEXT NOT NULL, - request TEXT, - investigated TEXT, - learned TEXT, - completed TEXT, - next_steps TEXT, - files_read TEXT, - files_edited TEXT, - notes TEXT, - prompt_number INTEGER, - created_at TEXT NOT NULL, - created_at_epoch INTEGER NOT NULL, - FOREIGN KEY(sdk_session_id) REFERENCES sdk_sessions(sdk_session_id) ON DELETE CASCADE - ) - `),this.db.exec(` - INSERT INTO session_summaries_new - SELECT id, sdk_session_id, project, request, investigated, learned, - completed, next_steps, files_read, files_edited, notes, - prompt_number, created_at, created_at_epoch - FROM session_summaries - `),this.db.exec("DROP TABLE session_summaries"),this.db.exec("ALTER TABLE session_summaries_new RENAME TO session_summaries"),this.db.exec(` - CREATE INDEX idx_session_summaries_sdk_session ON session_summaries(sdk_session_id); - CREATE INDEX idx_session_summaries_project ON session_summaries(project); - CREATE INDEX idx_session_summaries_created ON session_summaries(created_at_epoch DESC); - `),this.db.exec("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(7,new Date().toISOString()),console.error("[SessionStore] Successfully removed UNIQUE constraint from session_summaries.sdk_session_id")}catch(r){throw this.db.exec("ROLLBACK"),r}}catch(e){console.error("[SessionStore] Migration error (remove UNIQUE constraint):",e.message)}}addObservationHierarchicalFields(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(8))return;if(this.db.pragma("table_info(observations)").some(r=>r.name==="title")){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(8,new Date().toISOString());return}console.error("[SessionStore] Adding hierarchical fields to observations table..."),this.db.exec(` - ALTER TABLE observations ADD COLUMN title TEXT; - ALTER TABLE observations ADD COLUMN subtitle TEXT; - ALTER TABLE observations ADD COLUMN facts TEXT; - ALTER TABLE observations ADD COLUMN narrative TEXT; - ALTER TABLE observations ADD COLUMN concepts TEXT; - ALTER TABLE observations ADD COLUMN files_read TEXT; - ALTER TABLE observations ADD COLUMN files_modified TEXT; - `),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(8,new Date().toISOString()),console.error("[SessionStore] Successfully added hierarchical fields to observations table")}catch(e){console.error("[SessionStore] Migration error (add hierarchical fields):",e.message)}}makeObservationsTextNullable(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(9))return;let a=this.db.pragma("table_info(observations)").find(r=>r.name==="text");if(!a||a.notnull===0){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(9,new Date().toISOString());return}console.error("[SessionStore] Making observations.text nullable..."),this.db.exec("BEGIN TRANSACTION");try{this.db.exec(` - CREATE TABLE observations_new ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - sdk_session_id TEXT NOT NULL, - project TEXT NOT NULL, - text TEXT, - type TEXT NOT NULL CHECK(type IN ('decision', 'bugfix', 'feature', 'refactor', 'discovery', 'change')), - title TEXT, - subtitle TEXT, - facts TEXT, - narrative TEXT, - concepts TEXT, - files_read TEXT, - files_modified TEXT, - prompt_number INTEGER, - created_at TEXT NOT NULL, - created_at_epoch INTEGER NOT NULL, - FOREIGN KEY(sdk_session_id) REFERENCES sdk_sessions(sdk_session_id) ON DELETE CASCADE - ) - `),this.db.exec(` - INSERT INTO observations_new - SELECT id, sdk_session_id, project, text, type, title, subtitle, facts, - narrative, concepts, files_read, files_modified, prompt_number, - created_at, created_at_epoch - FROM observations - `),this.db.exec("DROP TABLE observations"),this.db.exec("ALTER TABLE observations_new RENAME TO observations"),this.db.exec(` - CREATE INDEX idx_observations_sdk_session ON observations(sdk_session_id); - CREATE INDEX idx_observations_project ON observations(project); - CREATE INDEX idx_observations_type ON observations(type); - CREATE INDEX idx_observations_created ON observations(created_at_epoch DESC); - `),this.db.exec("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(9,new Date().toISOString()),console.error("[SessionStore] Successfully made observations.text nullable")}catch(r){throw this.db.exec("ROLLBACK"),r}}catch(e){console.error("[SessionStore] Migration error (make text nullable):",e.message)}}createUserPromptsTable(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(10))return;if(this.db.pragma("table_info(user_prompts)").length>0){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(10,new Date().toISOString());return}console.error("[SessionStore] Creating user_prompts table with FTS5 support..."),this.db.exec("BEGIN TRANSACTION");try{this.db.exec(` - CREATE TABLE user_prompts ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - claude_session_id TEXT NOT NULL, - prompt_number INTEGER NOT NULL, - prompt_text TEXT NOT NULL, - created_at TEXT NOT NULL, - created_at_epoch INTEGER NOT NULL, - FOREIGN KEY(claude_session_id) REFERENCES sdk_sessions(claude_session_id) ON DELETE CASCADE - ); - - CREATE INDEX idx_user_prompts_claude_session ON user_prompts(claude_session_id); - CREATE INDEX idx_user_prompts_created ON user_prompts(created_at_epoch DESC); - CREATE INDEX idx_user_prompts_prompt_number ON user_prompts(prompt_number); - `),this.db.exec(` - CREATE VIRTUAL TABLE user_prompts_fts USING fts5( - prompt_text, - content='user_prompts', - content_rowid='id' - ); - `),this.db.exec(` - CREATE TRIGGER user_prompts_ai AFTER INSERT ON user_prompts BEGIN - INSERT INTO user_prompts_fts(rowid, prompt_text) - VALUES (new.id, new.prompt_text); - END; - - CREATE TRIGGER user_prompts_ad AFTER DELETE ON user_prompts BEGIN - INSERT INTO user_prompts_fts(user_prompts_fts, rowid, prompt_text) - VALUES('delete', old.id, old.prompt_text); - END; - - CREATE TRIGGER user_prompts_au AFTER UPDATE ON user_prompts BEGIN - INSERT INTO user_prompts_fts(user_prompts_fts, rowid, prompt_text) - VALUES('delete', old.id, old.prompt_text); - INSERT INTO user_prompts_fts(rowid, prompt_text) - VALUES (new.id, new.prompt_text); - END; - `),this.db.exec("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(10,new Date().toISOString()),console.error("[SessionStore] Successfully created user_prompts table with FTS5 support")}catch(a){throw this.db.exec("ROLLBACK"),a}}catch(e){console.error("[SessionStore] Migration error (create user_prompts table):",e.message)}}getRecentSummaries(e,t=10){return this.db.prepare(` - SELECT - request, investigated, learned, completed, next_steps, - files_read, files_edited, notes, prompt_number, created_at - FROM session_summaries - WHERE project = ? - ORDER BY created_at_epoch DESC - LIMIT ? - `).all(e,t)}getRecentSummariesWithSessionInfo(e,t=3){return this.db.prepare(` - SELECT - sdk_session_id, request, learned, completed, next_steps, - prompt_number, created_at - FROM session_summaries - WHERE project = ? - ORDER BY created_at_epoch DESC - LIMIT ? - `).all(e,t)}getRecentObservations(e,t=20){return this.db.prepare(` - SELECT type, text, prompt_number, created_at - FROM observations - WHERE project = ? - ORDER BY created_at_epoch DESC - LIMIT ? - `).all(e,t)}getRecentSessionsWithStatus(e,t=3){return this.db.prepare(` - SELECT * FROM ( - SELECT - s.sdk_session_id, - s.status, - s.started_at, - s.started_at_epoch, - s.user_prompt, - CASE WHEN sum.sdk_session_id IS NOT NULL THEN 1 ELSE 0 END as has_summary - FROM sdk_sessions s - LEFT JOIN session_summaries sum ON s.sdk_session_id = sum.sdk_session_id - WHERE s.project = ? AND s.sdk_session_id IS NOT NULL - GROUP BY s.sdk_session_id - ORDER BY s.started_at_epoch DESC - LIMIT ? - ) - ORDER BY started_at_epoch ASC - `).all(e,t)}getObservationsForSession(e){return this.db.prepare(` - SELECT title, subtitle, type, prompt_number - FROM observations - WHERE sdk_session_id = ? - ORDER BY created_at_epoch ASC - `).all(e)}getObservationsByIds(e,t={}){if(e.length===0)return[];let{orderBy:a="date_desc",limit:r}=t,n=a==="date_asc"?"ASC":"DESC",o=r?`LIMIT ${r}`:"",i=e.map(()=>"?").join(",");return this.db.prepare(` - SELECT * - FROM observations - WHERE id IN (${i}) - ORDER BY created_at_epoch ${n} - ${o} - `).all(...e)}getSummaryForSession(e){return this.db.prepare(` - SELECT - request, investigated, learned, completed, next_steps, - files_read, files_edited, notes, prompt_number, created_at - FROM session_summaries - WHERE sdk_session_id = ? - ORDER BY created_at_epoch DESC - LIMIT 1 - `).get(e)||null}getFilesForSession(e){let a=this.db.prepare(` - SELECT files_read, files_modified - FROM observations - WHERE sdk_session_id = ? - `).all(e),r=new Set,n=new Set;for(let o of a){if(o.files_read)try{let i=JSON.parse(o.files_read);Array.isArray(i)&&i.forEach(l=>r.add(l))}catch{}if(o.files_modified)try{let i=JSON.parse(o.files_modified);Array.isArray(i)&&i.forEach(l=>n.add(l))}catch{}}return{filesRead:Array.from(r),filesModified:Array.from(n)}}getSessionById(e){return this.db.prepare(` - SELECT id, claude_session_id, sdk_session_id, project, user_prompt - FROM sdk_sessions - WHERE id = ? - LIMIT 1 - `).get(e)||null}findActiveSDKSession(e){return this.db.prepare(` - SELECT id, sdk_session_id, project, worker_port - FROM sdk_sessions - WHERE claude_session_id = ? AND status = 'active' - LIMIT 1 - `).get(e)||null}findAnySDKSession(e){return this.db.prepare(` - SELECT id - FROM sdk_sessions - WHERE claude_session_id = ? - LIMIT 1 - `).get(e)||null}reactivateSession(e,t){this.db.prepare(` - UPDATE sdk_sessions - SET status = 'active', user_prompt = ?, worker_port = NULL - WHERE id = ? - `).run(t,e)}incrementPromptCounter(e){return this.db.prepare(` - UPDATE sdk_sessions - SET prompt_counter = COALESCE(prompt_counter, 0) + 1 - WHERE id = ? - `).run(e),this.db.prepare(` - SELECT prompt_counter FROM sdk_sessions WHERE id = ? - `).get(e)?.prompt_counter||1}getPromptCounter(e){return this.db.prepare(` - SELECT prompt_counter FROM sdk_sessions WHERE id = ? - `).get(e)?.prompt_counter||0}createSDKSession(e,t,a){let r=new Date,n=r.getTime(),i=this.db.prepare(` - INSERT OR IGNORE INTO sdk_sessions - (claude_session_id, sdk_session_id, project, user_prompt, started_at, started_at_epoch, status) - VALUES (?, ?, ?, ?, ?, ?, 'active') - `).run(e,e,t,a,r.toISOString(),n);return i.lastInsertRowid===0||i.changes===0?this.db.prepare(` - SELECT id FROM sdk_sessions WHERE claude_session_id = ? LIMIT 1 - `).get(e).id:i.lastInsertRowid}updateSDKSessionId(e,t){return this.db.prepare(` - UPDATE sdk_sessions - SET sdk_session_id = ? - WHERE id = ? AND sdk_session_id IS NULL - `).run(t,e).changes===0?(gl.debug("DB","sdk_session_id already set, skipping update",{sessionId:e,sdkSessionId:t}),!1):!0}setWorkerPort(e,t){this.db.prepare(` - UPDATE sdk_sessions - SET worker_port = ? - WHERE id = ? - `).run(t,e)}getWorkerPort(e){return this.db.prepare(` - SELECT worker_port - FROM sdk_sessions - WHERE id = ? - LIMIT 1 - `).get(e)?.worker_port||null}saveUserPrompt(e,t,a){let r=new Date,n=r.getTime();return this.db.prepare(` - INSERT INTO user_prompts - (claude_session_id, prompt_number, prompt_text, created_at, created_at_epoch) - VALUES (?, ?, ?, ?, ?) - `).run(e,t,a,r.toISOString(),n).lastInsertRowid}storeObservation(e,t,a,r){let n=new Date,o=n.getTime();this.db.prepare(` - SELECT id FROM sdk_sessions WHERE sdk_session_id = ? - `).get(e)||(this.db.prepare(` - INSERT INTO sdk_sessions - (claude_session_id, sdk_session_id, project, started_at, started_at_epoch, status) - VALUES (?, ?, ?, ?, ?, 'active') - `).run(e,e,t,n.toISOString(),o),console.error(`[SessionStore] Auto-created session record for session_id: ${e}`)),this.db.prepare(` - INSERT INTO observations - (sdk_session_id, project, type, title, subtitle, facts, narrative, concepts, - files_read, files_modified, prompt_number, created_at, created_at_epoch) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).run(e,t,a.type,a.title,a.subtitle,JSON.stringify(a.facts),a.narrative,JSON.stringify(a.concepts),JSON.stringify(a.files_read),JSON.stringify(a.files_modified),r||null,n.toISOString(),o)}storeSummary(e,t,a,r){let n=new Date,o=n.getTime();this.db.prepare(` - SELECT id FROM sdk_sessions WHERE sdk_session_id = ? - `).get(e)||(this.db.prepare(` - INSERT INTO sdk_sessions - (claude_session_id, sdk_session_id, project, started_at, started_at_epoch, status) - VALUES (?, ?, ?, ?, ?, 'active') - `).run(e,e,t,n.toISOString(),o),console.error(`[SessionStore] Auto-created session record for session_id: ${e}`)),this.db.prepare(` - INSERT INTO session_summaries - (sdk_session_id, project, request, investigated, learned, completed, - next_steps, notes, prompt_number, created_at, created_at_epoch) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).run(e,t,a.request,a.investigated,a.learned,a.completed,a.next_steps,a.notes,r||null,n.toISOString(),o)}markSessionCompleted(e){let t=new Date,a=t.getTime();this.db.prepare(` - UPDATE sdk_sessions - SET status = 'completed', completed_at = ?, completed_at_epoch = ? - WHERE id = ? - `).run(t.toISOString(),a,e)}markSessionFailed(e){let t=new Date,a=t.getTime();this.db.prepare(` - UPDATE sdk_sessions - SET status = 'failed', completed_at = ?, completed_at_epoch = ? - WHERE id = ? - `).run(t.toISOString(),a,e)}cleanupOrphanedSessions(){let e=new Date,t=e.getTime();return this.db.prepare(` - UPDATE sdk_sessions - SET status = 'failed', completed_at = ?, completed_at_epoch = ? - WHERE status = 'active' - `).run(e.toISOString(),t).changes}close(){this.db.close()}};var cr,Nr,yr=null,vh="cm__claude-mem";try{cr=new $s,Nr=new ks}catch(s){console.error("[search-server] Failed to initialize search:",s.message),process.exit(1)}async function Ls(s,e,t){if(!yr)throw new Error("Chroma client not initialized");let r=(await yr.callTool({name:"chroma_query_documents",arguments:{collection_name:vh,query_texts:[s],n_results:e,include:["documents","metadatas","distances"],where:t}})).content[0]?.text||"",n=r.match(/'ids':\s*\[\[(.*?)\]\]/s),o=[];if(n){let _=n[1].match(/'([^']*(?:\\'[^']*)*)'/g)||[];for(let d of _){let y=d.slice(1,-1).match(/obs_(\d+)_/);if(y){let v=parseInt(y[1],10);o.includes(v)||o.push(v)}}}let i=r.match(/'distances':\s*\[\[([\d.,\s]+)\]\]/s),l=[];if(i){let _=i[1].split(",").map(d=>parseFloat(d.trim())).filter(d=>!isNaN(d));l.push(..._)}let u=r.match(/'metadatas':\s*\[\[(.*?)\]\]/s),f=[];if(u){let _=u[1].match(/\{[^}]+\}/g)||[];for(let d of _){let m={},y=d.match(/'sqlite_id':\s*(\d+)/);y&&(m.sqlite_id=parseInt(y[1],10));let v=d.match(/'type':\s*'([^']+)'/);v&&(m.type=v[1]);let b=d.match(/'created_at_epoch':\s*(\d+)/);b&&(m.created_at_epoch=parseInt(b[1],10)),f.push(m)}}return{ids:o,distances:l,metadatas:f}}function Et(){return` ---- -\u{1F4A1} Search Strategy: -ALWAYS search with index format FIRST to get an overview and identify relevant results. -This is critical for token efficiency - index format uses ~10x fewer tokens than full format. - -Search workflow: -1. Initial search: Use default (index) format to see titles, dates, and sources -2. Review results: Identify which items are most relevant to your needs -3. Deep dive: Only then use format: "full" on specific items of interest -4. Narrow down: Use filters (type, dateRange, concepts, files) to refine results - -Other tips: -\u2022 To search by concept: Use find_by_concept tool -\u2022 To browse by type: Use find_by_type with ["decision", "feature", etc.] -\u2022 To sort by date: Use orderBy: "date_desc" or "date_asc"`}function Fs(s,e){let t=s.title||`Observation #${s.id}`,a=new Date(s.created_at_epoch).toLocaleString(),r=s.type?`[${s.type}]`:"";return`${e+1}. ${r} ${t} - Date: ${a} - Source: claude-mem://observation/${s.id}`}function _l(s,e){let t=s.request||`Session ${s.sdk_session_id.substring(0,8)}`,a=new Date(s.created_at_epoch).toLocaleString();return`${e+1}. ${t} - Date: ${a} - Source: claude-mem://session/${s.sdk_session_id}`}function js(s,e){let t=s.title||`Observation #${s.id}`,a=[];a.push(`## ${t}`),a.push(`*Source: claude-mem://observation/${s.id}*`),a.push(""),s.subtitle&&(a.push(`**${s.subtitle}**`),a.push("")),s.narrative&&(a.push(s.narrative),a.push("")),s.text&&(a.push(s.text),a.push(""));let r=[];if(r.push(`Type: ${s.type}`),s.facts)try{let o=JSON.parse(s.facts);o.length>0&&r.push(`Facts: ${o.join("; ")}`)}catch{}if(s.concepts)try{let o=JSON.parse(s.concepts);o.length>0&&r.push(`Concepts: ${o.join(", ")}`)}catch{}if(s.files_read||s.files_modified){let o=[];if(s.files_read)try{o.push(...JSON.parse(s.files_read))}catch{}if(s.files_modified)try{o.push(...JSON.parse(s.files_modified))}catch{}o.length>0&&r.push(`Files: ${[...new Set(o)].join(", ")}`)}r.length>0&&(a.push("---"),a.push(r.join(" | ")));let n=new Date(s.created_at_epoch).toLocaleString();return a.push(""),a.push("---"),a.push(`Date: ${n}`),a.join(` -`)}function yl(s,e){let t=s.request||`Session ${s.sdk_session_id.substring(0,8)}`,a=[];a.push(`## ${t}`),a.push(`*Source: claude-mem://session/${s.sdk_session_id}*`),a.push(""),s.completed&&(a.push(`**Completed:** ${s.completed}`),a.push("")),s.learned&&(a.push(`**Learned:** ${s.learned}`),a.push("")),s.investigated&&(a.push(`**Investigated:** ${s.investigated}`),a.push("")),s.next_steps&&(a.push(`**Next Steps:** ${s.next_steps}`),a.push("")),s.notes&&(a.push(`**Notes:** ${s.notes}`),a.push(""));let r=[];if(s.files_read||s.files_edited){let o=[];if(s.files_read)try{o.push(...JSON.parse(s.files_read))}catch{}if(s.files_edited)try{o.push(...JSON.parse(s.files_edited))}catch{}o.length>0&&r.push(`Files: ${[...new Set(o)].join(", ")}`)}let n=new Date(s.created_at_epoch).toLocaleDateString();return r.push(`Date: ${n}`),r.length>0&&(a.push("---"),a.push(r.join(" | "))),a.join(` -`)}function gh(s,e){let t=s.prompt_text.length>100?s.prompt_text.substring(0,100)+"...":s.prompt_text,a=new Date(s.created_at_epoch).toLocaleString();return`${e+1}. "${t}" - Date: ${a} | Prompt #${s.prompt_number} - Source: claude-mem://user-prompt/${s.id}`}function _h(s,e){let t=[];t.push(`## User Prompt #${s.prompt_number}`),t.push(`*Source: claude-mem://user-prompt/${s.id}*`),t.push(""),t.push(s.prompt_text),t.push(""),t.push("---");let a=new Date(s.created_at_epoch).toLocaleString();return t.push(`Date: ${a}`),t.join(` -`)}var yh=c.object({project:c.string().optional().describe("Filter by project name"),type:c.union([c.enum(["decision","bugfix","feature","refactor","discovery","change"]),c.array(c.enum(["decision","bugfix","feature","refactor","discovery","change"]))]).optional().describe("Filter by observation type"),concepts:c.union([c.string(),c.array(c.string())]).optional().describe("Filter by concept tags"),files:c.union([c.string(),c.array(c.string())]).optional().describe("Filter by file paths (partial match)"),dateRange:c.object({start:c.union([c.string(),c.number()]).optional().describe("Start date (ISO string or epoch)"),end:c.union([c.string(),c.number()]).optional().describe("End date (ISO string or epoch)")}).optional().describe("Filter by date range"),limit:c.number().min(1).max(100).default(20).describe("Maximum number of results"),offset:c.number().min(0).default(0).describe("Number of results to skip"),orderBy:c.enum(["relevance","date_desc","date_asc"]).default("relevance").describe("Sort order")}),El=[{name:"search_observations",description:'Search observations using full-text search across titles, narratives, facts, and concepts. IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:c.object({query:c.string().describe("Search query for FTS5 full-text search"),format:c.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),...yh.shape}),handler:async s=>{try{let{query:e,format:t="index",...a}=s,r=[];if(yr)try{console.error("[search-server] Using hybrid semantic search (Chroma + SQLite)");let o=await Ls(e,100);if(console.error(`[search-server] Chroma returned ${o.ids.length} semantic matches`),o.ids.length>0){let i=Math.floor(Date.now()/1e3)-7776e3,l=o.ids.filter((u,f)=>{let h=o.metadatas[f];return h&&h.created_at_epoch>i});if(console.error(`[search-server] ${l.length} results within 90-day window`),l.length>0){let u=a.limit||20;r=Nr.getObservationsByIds(l,{orderBy:"date_desc",limit:u}),console.error(`[search-server] Hydrated ${r.length} observations from SQLite`)}}}catch(o){console.error("[search-server] Chroma query failed, falling back to FTS5:",o.message)}if(r.length===0&&(console.error("[search-server] Using FTS5 keyword search"),r=cr.searchObservations(e,a)),r.length===0)return{content:[{type:"text",text:`No observations found matching "${e}"`}]};let n;if(t==="index"){let o=`Found ${r.length} observation(s) matching "${e}": - -`,i=r.map((l,u)=>Fs(l,u));n=o+i.join(` - -`)+Et()}else n=r.map((i,l)=>js(i,l)).join(` - ---- - -`);return{content:[{type:"text",text:n}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"search_sessions",description:'Search session summaries using full-text search across requests, completions, learnings, and notes. IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:c.object({query:c.string().describe("Search query for FTS5 full-text search"),format:c.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),project:c.string().optional().describe("Filter by project name"),dateRange:c.object({start:c.union([c.string(),c.number()]).optional(),end:c.union([c.string(),c.number()]).optional()}).optional().describe("Filter by date range"),limit:c.number().min(1).max(100).default(20).describe("Maximum number of results"),offset:c.number().min(0).default(0).describe("Number of results to skip"),orderBy:c.enum(["relevance","date_desc","date_asc"]).default("relevance").describe("Sort order")}),handler:async s=>{try{let{query:e,format:t="index",...a}=s,r=cr.searchSessions(e,a);if(r.length===0)return{content:[{type:"text",text:`No sessions found matching "${e}"`}]};let n;if(t==="index"){let o=`Found ${r.length} session(s) matching "${e}": - -`,i=r.map((l,u)=>_l(l,u));n=o+i.join(` - -`)+Et()}else n=r.map((i,l)=>yl(i,l)).join(` - ---- - -`);return{content:[{type:"text",text:n}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"find_by_concept",description:'Find observations tagged with a specific concept. IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:c.object({concept:c.string().describe("Concept tag to search for"),format:c.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),project:c.string().optional().describe("Filter by project name"),dateRange:c.object({start:c.union([c.string(),c.number()]).optional(),end:c.union([c.string(),c.number()]).optional()}).optional().describe("Filter by date range"),limit:c.number().min(1).max(100).default(20).describe("Maximum results. IMPORTANT: Start with 3-5 to avoid exceeding MCP token limits, even in index mode."),offset:c.number().min(0).default(0).describe("Number of results to skip"),orderBy:c.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async s=>{try{let{concept:e,format:t="index",...a}=s,r=[];if(yr)try{console.error("[search-server] Using metadata-first + semantic ranking for concept search");let o=cr.findByConcept(e,a);if(console.error(`[search-server] Found ${o.length} observations with concept "${e}"`),o.length>0){let i=o.map(f=>f.id),l=await Ls(e,Math.min(i.length,100)),u=[];for(let f of l.ids)i.includes(f)&&!u.includes(f)&&u.push(f);console.error(`[search-server] Chroma ranked ${u.length} results by semantic relevance`),u.length>0&&(r=Nr.getObservationsByIds(u,{limit:a.limit||20}),r.sort((f,h)=>u.indexOf(f.id)-u.indexOf(h.id)))}}catch(o){console.error("[search-server] Chroma ranking failed, using SQLite order:",o.message)}if(r.length===0&&(console.error("[search-server] Using SQLite-only concept search"),r=cr.findByConcept(e,a)),r.length===0)return{content:[{type:"text",text:`No observations found with concept "${e}"`}]};let n;if(t==="index"){let o=`Found ${r.length} observation(s) with concept "${e}": - -`,i=r.map((l,u)=>Fs(l,u));n=o+i.join(` - -`)+Et()}else n=r.map((i,l)=>js(i,l)).join(` - ---- - -`);return{content:[{type:"text",text:n}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"find_by_file",description:'Find observations and sessions that reference a specific file path. IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:c.object({filePath:c.string().describe("File path to search for (supports partial matching)"),format:c.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),project:c.string().optional().describe("Filter by project name"),dateRange:c.object({start:c.union([c.string(),c.number()]).optional(),end:c.union([c.string(),c.number()]).optional()}).optional().describe("Filter by date range"),limit:c.number().min(1).max(100).default(20).describe("Maximum results. IMPORTANT: Start with 3-5 to avoid exceeding MCP token limits, even in index mode."),offset:c.number().min(0).default(0).describe("Number of results to skip"),orderBy:c.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async s=>{try{let{filePath:e,format:t="index",...a}=s,r=[],n=[];if(yr)try{console.error("[search-server] Using metadata-first + semantic ranking for file search");let l=cr.findByFile(e,a);if(console.error(`[search-server] Found ${l.observations.length} observations, ${l.sessions.length} sessions for file "${e}"`),n=l.sessions,l.observations.length>0){let u=l.observations.map(_=>_.id),f=await Ls(e,Math.min(u.length,100)),h=[];for(let _ of f.ids)u.includes(_)&&!h.includes(_)&&h.push(_);console.error(`[search-server] Chroma ranked ${h.length} observations by semantic relevance`),h.length>0&&(r=Nr.getObservationsByIds(h,{limit:a.limit||20}),r.sort((_,d)=>h.indexOf(_.id)-h.indexOf(d.id)))}}catch(l){console.error("[search-server] Chroma ranking failed, using SQLite order:",l.message)}if(r.length===0&&n.length===0){console.error("[search-server] Using SQLite-only file search");let l=cr.findByFile(e,a);r=l.observations,n=l.sessions}let o=r.length+n.length;if(o===0)return{content:[{type:"text",text:`No results found for file "${e}"`}]};let i;if(t==="index"){let l=`Found ${o} result(s) for file "${e}": - -`,u=[];r.forEach((f,h)=>{u.push(Fs(f,h))}),n.forEach((f,h)=>{u.push(_l(f,h+r.length))}),i=l+u.join(` - -`)+Et()}else{let l=[];r.forEach((u,f)=>{l.push(js(u,f))}),n.forEach((u,f)=>{l.push(yl(u,f+r.length))}),i=l.join(` - ---- - -`)}return{content:[{type:"text",text:i}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"find_by_type",description:'Find observations of a specific type (decision, bugfix, feature, refactor, discovery, change). IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:c.object({type:c.union([c.enum(["decision","bugfix","feature","refactor","discovery","change"]),c.array(c.enum(["decision","bugfix","feature","refactor","discovery","change"]))]).describe("Observation type(s) to filter by"),format:c.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),project:c.string().optional().describe("Filter by project name"),dateRange:c.object({start:c.union([c.string(),c.number()]).optional(),end:c.union([c.string(),c.number()]).optional()}).optional().describe("Filter by date range"),limit:c.number().min(1).max(100).default(20).describe("Maximum results. IMPORTANT: Start with 3-5 to avoid exceeding MCP token limits, even in index mode."),offset:c.number().min(0).default(0).describe("Number of results to skip"),orderBy:c.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async s=>{try{let{type:e,format:t="index",...a}=s,r=Array.isArray(e)?e.join(", "):e,n=[];if(yr)try{console.error("[search-server] Using metadata-first + semantic ranking for type search");let i=cr.findByType(e,a);if(console.error(`[search-server] Found ${i.length} observations with type "${r}"`),i.length>0){let l=i.map(h=>h.id),u=await Ls(r,Math.min(l.length,100)),f=[];for(let h of u.ids)l.includes(h)&&!f.includes(h)&&f.push(h);console.error(`[search-server] Chroma ranked ${f.length} results by semantic relevance`),f.length>0&&(n=Nr.getObservationsByIds(f,{limit:a.limit||20}),n.sort((h,_)=>f.indexOf(h.id)-f.indexOf(_.id)))}}catch(i){console.error("[search-server] Chroma ranking failed, using SQLite order:",i.message)}if(n.length===0&&(console.error("[search-server] Using SQLite-only type search"),n=cr.findByType(e,a)),n.length===0)return{content:[{type:"text",text:`No observations found with type "${r}"`}]};let o;if(t==="index"){let i=`Found ${n.length} observation(s) with type "${r}": - -`,l=n.map((u,f)=>Fs(u,f));o=i+l.join(` - -`)+Et()}else o=n.map((l,u)=>js(l,u)).join(` - ---- - -`);return{content:[{type:"text",text:o}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"get_recent_context",description:"Get recent session context including summaries and observations for a project",inputSchema:c.object({project:c.string().optional().describe("Project name (defaults to current working directory basename)"),limit:c.number().min(1).max(10).default(3).describe("Number of recent sessions to retrieve")}),handler:async s=>{try{let e=s.project||mh(process.cwd()),t=s.limit||3,a=Nr.getRecentSessionsWithStatus(e,t);if(a.length===0)return{content:[{type:"text",text:`# Recent Session Context - -No previous sessions found for project "${e}".`}]};let r=[];r.push("# Recent Session Context"),r.push(""),r.push(`Showing last ${a.length} session(s) for **${e}**:`),r.push("");for(let n of a)if(n.sdk_session_id){if(r.push("---"),r.push(""),n.has_summary){let o=Nr.getSummaryForSession(n.sdk_session_id);if(o){let i=o.prompt_number?` (Prompt #${o.prompt_number})`:"";if(r.push(`**Summary${i}**`),r.push(""),o.request&&r.push(`**Request:** ${o.request}`),o.completed&&r.push(`**Completed:** ${o.completed}`),o.learned&&r.push(`**Learned:** ${o.learned}`),o.next_steps&&r.push(`**Next Steps:** ${o.next_steps}`),o.files_read)try{let u=JSON.parse(o.files_read);Array.isArray(u)&&u.length>0&&r.push(`**Files Read:** ${u.join(", ")}`)}catch{o.files_read.trim()&&r.push(`**Files Read:** ${o.files_read}`)}if(o.files_edited)try{let u=JSON.parse(o.files_edited);Array.isArray(u)&&u.length>0&&r.push(`**Files Edited:** ${u.join(", ")}`)}catch{o.files_edited.trim()&&r.push(`**Files Edited:** ${o.files_edited}`)}let l=new Date(o.created_at).toLocaleString();r.push(`**Date:** ${l}`)}}else if(n.status==="active"){r.push("**In Progress**"),r.push(""),n.user_prompt&&r.push(`**Request:** ${n.user_prompt}`);let o=Nr.getObservationsForSession(n.sdk_session_id);if(o.length>0){r.push(""),r.push(`**Observations (${o.length}):**`);for(let l of o)r.push(`- ${l.title}`)}else r.push(""),r.push("*No observations yet*");r.push(""),r.push("**Status:** Active - summary pending");let i=new Date(n.started_at).toLocaleString();r.push(`**Date:** ${i}`)}else{r.push(`**${n.status.charAt(0).toUpperCase()+n.status.slice(1)}**`),r.push(""),n.user_prompt&&r.push(`**Request:** ${n.user_prompt}`),r.push(""),r.push(`**Status:** ${n.status} - no summary available`);let o=new Date(n.started_at).toLocaleString();r.push(`**Date:** ${o}`)}r.push("")}return{content:[{type:"text",text:r.join(` -`)}]}}catch(e){return{content:[{type:"text",text:`Failed to get recent context: ${e.message}`}],isError:!0}}}},{name:"search_user_prompts",description:'Search raw user prompts with full-text search. Use this to find what the user actually said/requested across all sessions. IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:c.object({query:c.string().describe("Search query for FTS5 full-text search"),format:c.enum(["index","full"]).default("index").describe('Output format: "index" for truncated prompts/dates (default, RECOMMENDED for initial search), "full" for complete prompt text (use only after reviewing index results)'),project:c.string().optional().describe("Filter by project name"),dateRange:c.object({start:c.union([c.string(),c.number()]).optional(),end:c.union([c.string(),c.number()]).optional()}).optional().describe("Filter by date range"),limit:c.number().min(1).max(100).default(20).describe("Maximum number of results"),offset:c.number().min(0).default(0).describe("Number of results to skip"),orderBy:c.enum(["relevance","date_desc","date_asc"]).default("relevance").describe("Sort order")}),handler:async s=>{try{let{query:e,format:t="index",...a}=s,r=cr.searchUserPrompts(e,a);if(r.length===0)return{content:[{type:"text",text:`No user prompts found matching "${e}"`}]};let n;if(t==="index"){let o=`Found ${r.length} user prompt(s) matching "${e}": - -`,i=r.map((l,u)=>gh(l,u));n=o+i.join(` - -`)+Et()}else n=r.map((i,l)=>_h(i,l)).join(` - ---- - -`);return{content:[{type:"text",text:n}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}}],sn=new bs({name:"claude-mem-search",version:"1.0.0"},{capabilities:{tools:{}}});sn.setRequestHandler(ia,async()=>({tools:El.map(s=>({name:s.name,description:s.description,inputSchema:Ya(s.inputSchema)}))}));sn.setRequestHandler(la,async s=>{let e=El.find(t=>t.name===s.params.name);if(!e)throw new Error(`Unknown tool: ${s.params.name}`);try{return await e.handler(s.params.arguments||{})}catch(t){return{content:[{type:"text",text:`Tool execution failed: ${t.message}`}],isError:!0}}});async function Eh(){try{console.error("[search-server] Initializing Chroma client...");let e=new Ps({command:"uvx",args:["chroma-mcp","--client-type","persistent","--data-dir",vl]});yr=new Rs({name:"claude-mem-search-chroma-client",version:"1.0.0"},{capabilities:{}}),await yr.connect(e),console.error("[search-server] Chroma client connected successfully")}catch(e){console.error("[search-server] Failed to initialize Chroma client:",e.message),console.error("[search-server] Falling back to FTS5-only search"),yr=null}let s=new xs;await sn.connect(s),console.error("[search-server] Claude-mem search server started")}Eh().catch(s=>{console.error("[search-server] Fatal error:",s),process.exit(1)}); -/*! Bundled license information: - -uri-js/dist/es5/uri.all.js: - (** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js *) -*/ diff --git a/plugin/scripts/search-server.mjs b/plugin/scripts/search-server.mjs new file mode 100755 index 00000000..c091896a --- /dev/null +++ b/plugin/scripts/search-server.mjs @@ -0,0 +1,526 @@ +#!/usr/bin/env node +import{Server as Q}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as z}from"@modelcontextprotocol/sdk/server/stdio.js";import{Client as Z}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as ee}from"@modelcontextprotocol/sdk/client/stdio.js";import{CallToolRequestSchema as se,ListToolsRequestSchema as te}from"@modelcontextprotocol/sdk/types.js";import{z as i}from"zod";import{zodToJsonSchema as re}from"zod-to-json-schema";import{basename as ne}from"path";import K from"better-sqlite3";import{join as g,dirname as W,basename as ue}from"path";import{homedir as j}from"os";import{existsSync as Ee,mkdirSync as q}from"fs";import{fileURLToPath as Y}from"url";function V(){return typeof __dirname<"u"?__dirname:W(Y(import.meta.url))}var fe=V(),b=process.env.CLAUDE_MEM_DATA_DIR||g(j(),".claude-mem"),F=process.env.CLAUDE_CONFIG_DIR||g(j(),".claude"),Te=g(b,"archives"),Se=g(b,"logs"),ge=g(b,"trash"),be=g(b,"backups"),Re=g(b,"settings.json"),I=g(b,"claude-mem.db"),B=g(b,"vector-db"),Oe=g(F,"settings.json"),ye=g(F,"commands"),Ne=g(F,"CLAUDE.md");function x(a){q(a,{recursive:!0})}var C=class{db;constructor(e){e||(x(b),e=I),this.db=new K(e),this.db.pragma("journal_mode = WAL"),this.ensureFTSTables()}ensureFTSTables(){try{if(this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%_fts'").all().some(s=>s.name==="observations_fts"||s.name==="session_summaries_fts"))return;console.error("[SessionSearch] Creating FTS5 tables..."),this.db.exec(` + CREATE VIRTUAL TABLE IF NOT EXISTS observations_fts USING fts5( + title, + subtitle, + narrative, + text, + facts, + concepts, + content='observations', + content_rowid='id' + ); + `),this.db.exec(` + INSERT INTO observations_fts(rowid, title, subtitle, narrative, text, facts, concepts) + SELECT id, title, subtitle, narrative, text, facts, concepts + FROM observations; + `),this.db.exec(` + CREATE TRIGGER IF NOT EXISTS observations_ai AFTER INSERT ON observations BEGIN + INSERT INTO observations_fts(rowid, title, subtitle, narrative, text, facts, concepts) + VALUES (new.id, new.title, new.subtitle, new.narrative, new.text, new.facts, new.concepts); + END; + + CREATE TRIGGER IF NOT EXISTS observations_ad AFTER DELETE ON observations BEGIN + INSERT INTO observations_fts(observations_fts, rowid, title, subtitle, narrative, text, facts, concepts) + VALUES('delete', old.id, old.title, old.subtitle, old.narrative, old.text, old.facts, old.concepts); + END; + + CREATE TRIGGER IF NOT EXISTS observations_au AFTER UPDATE ON observations BEGIN + INSERT INTO observations_fts(observations_fts, rowid, title, subtitle, narrative, text, facts, concepts) + VALUES('delete', old.id, old.title, old.subtitle, old.narrative, old.text, old.facts, old.concepts); + INSERT INTO observations_fts(rowid, title, subtitle, narrative, text, facts, concepts) + VALUES (new.id, new.title, new.subtitle, new.narrative, new.text, new.facts, new.concepts); + END; + `),this.db.exec(` + CREATE VIRTUAL TABLE IF NOT EXISTS session_summaries_fts USING fts5( + request, + investigated, + learned, + completed, + next_steps, + notes, + content='session_summaries', + content_rowid='id' + ); + `),this.db.exec(` + INSERT INTO session_summaries_fts(rowid, request, investigated, learned, completed, next_steps, notes) + SELECT id, request, investigated, learned, completed, next_steps, notes + FROM session_summaries; + `),this.db.exec(` + CREATE TRIGGER IF NOT EXISTS session_summaries_ai AFTER INSERT ON session_summaries BEGIN + INSERT INTO session_summaries_fts(rowid, request, investigated, learned, completed, next_steps, notes) + VALUES (new.id, new.request, new.investigated, new.learned, new.completed, new.next_steps, new.notes); + END; + + CREATE TRIGGER IF NOT EXISTS session_summaries_ad AFTER DELETE ON session_summaries BEGIN + INSERT INTO session_summaries_fts(session_summaries_fts, rowid, request, investigated, learned, completed, next_steps, notes) + VALUES('delete', old.id, old.request, old.investigated, old.learned, old.completed, old.next_steps, old.notes); + END; + + CREATE TRIGGER IF NOT EXISTS session_summaries_au AFTER UPDATE ON session_summaries BEGIN + INSERT INTO session_summaries_fts(session_summaries_fts, rowid, request, investigated, learned, completed, next_steps, notes) + VALUES('delete', old.id, old.request, old.investigated, old.learned, old.completed, old.next_steps, old.notes); + INSERT INTO session_summaries_fts(rowid, request, investigated, learned, completed, next_steps, notes) + VALUES (new.id, new.request, new.investigated, new.learned, new.completed, new.next_steps, new.notes); + END; + `),console.error("[SessionSearch] FTS5 tables created successfully")}catch(e){console.error("[SessionSearch] FTS migration error:",e.message)}}escapeFTS5(e){return`"${e.replace(/"/g,'""')}"`}buildFilterClause(e,r,s="o"){let t=[];if(e.project&&(t.push(`${s}.project = ?`),r.push(e.project)),e.type)if(Array.isArray(e.type)){let o=e.type.map(()=>"?").join(",");t.push(`${s}.type IN (${o})`),r.push(...e.type)}else t.push(`${s}.type = ?`),r.push(e.type);if(e.dateRange){let{start:o,end:n}=e.dateRange;if(o){let c=typeof o=="number"?o:new Date(o).getTime();t.push(`${s}.created_at_epoch >= ?`),r.push(c)}if(n){let c=typeof n=="number"?n:new Date(n).getTime();t.push(`${s}.created_at_epoch <= ?`),r.push(c)}}if(e.concepts){let o=Array.isArray(e.concepts)?e.concepts:[e.concepts],n=o.map(()=>`EXISTS (SELECT 1 FROM json_each(${s}.concepts) WHERE value = ?)`);n.length>0&&(t.push(`(${n.join(" OR ")})`),r.push(...o))}if(e.files){let o=Array.isArray(e.files)?e.files:[e.files],n=o.map(()=>`( + EXISTS (SELECT 1 FROM json_each(${s}.files_read) WHERE value LIKE ?) + OR EXISTS (SELECT 1 FROM json_each(${s}.files_modified) WHERE value LIKE ?) + )`);n.length>0&&(t.push(`(${n.join(" OR ")})`),o.forEach(c=>{r.push(`%${c}%`,`%${c}%`)}))}return t.length>0?t.join(" AND "):""}buildOrderClause(e="relevance",r=!0,s="observations_fts"){switch(e){case"relevance":return r?`ORDER BY ${s}.rank ASC`:"ORDER BY o.created_at_epoch DESC";case"date_desc":return"ORDER BY o.created_at_epoch DESC";case"date_asc":return"ORDER BY o.created_at_epoch ASC";default:return"ORDER BY o.created_at_epoch DESC"}}searchObservations(e,r={}){let s=[],{limit:t=50,offset:o=0,orderBy:n="relevance",...c}=r,d=this.escapeFTS5(e);s.push(d);let l=this.buildFilterClause(c,s,"o"),u=l?`AND ${l}`:"",p=this.buildOrderClause(n,!0),m=` + SELECT + o.*, + observations_fts.rank as rank + FROM observations o + JOIN observations_fts ON o.id = observations_fts.rowid + WHERE observations_fts MATCH ? + ${u} + ${p} + LIMIT ? OFFSET ? + `;s.push(t,o);let _=this.db.prepare(m).all(...s);if(_.length>0){let E=Math.min(..._.map(f=>f.rank||0)),T=Math.max(..._.map(f=>f.rank||0))-E||1;_.forEach(f=>{f.rank!==void 0&&(f.score=1-(f.rank-E)/T)})}return _}searchSessions(e,r={}){let s=[],{limit:t=50,offset:o=0,orderBy:n="relevance",...c}=r,d=this.escapeFTS5(e);s.push(d);let l={...c};delete l.type;let u=this.buildFilterClause(l,s,"s"),E=` + SELECT + s.*, + session_summaries_fts.rank as rank + FROM session_summaries s + JOIN session_summaries_fts ON s.id = session_summaries_fts.rowid + WHERE session_summaries_fts MATCH ? + ${(u?`AND ${u}`:"").replace(/files_read/g,"files_read").replace(/files_modified/g,"files_edited")} + ${n==="relevance"?"ORDER BY session_summaries_fts.rank ASC":n==="date_asc"?"ORDER BY s.created_at_epoch ASC":"ORDER BY s.created_at_epoch DESC"} + LIMIT ? OFFSET ? + `;s.push(t,o);let h=this.db.prepare(E).all(...s);if(h.length>0){let T=Math.min(...h.map(S=>S.rank||0)),O=Math.max(...h.map(S=>S.rank||0))-T||1;h.forEach(S=>{S.rank!==void 0&&(S.score=1-(S.rank-T)/O)})}return h}findByConcept(e,r={}){let s=[],{limit:t=50,offset:o=0,orderBy:n="date_desc",...c}=r,d={...c,concepts:e},l=this.buildFilterClause(d,s,"o"),u=this.buildOrderClause(n,!1),p=` + SELECT o.* + FROM observations o + WHERE ${l} + ${u} + LIMIT ? OFFSET ? + `;return s.push(t,o),this.db.prepare(p).all(...s)}findByFile(e,r={}){let s=[],{limit:t=50,offset:o=0,orderBy:n="date_desc",...c}=r,d={...c,files:e},l=this.buildFilterClause(d,s,"o"),u=this.buildOrderClause(n,!1),p=` + SELECT o.* + FROM observations o + WHERE ${l} + ${u} + LIMIT ? OFFSET ? + `;s.push(t,o);let m=this.db.prepare(p).all(...s),_=[],E={...c};delete E.type;let h=[];if(E.project&&(h.push("s.project = ?"),_.push(E.project)),E.dateRange){let{start:O,end:S}=E.dateRange;if(O){let k=typeof O=="number"?O:new Date(O).getTime();h.push("s.created_at_epoch >= ?"),_.push(k)}if(S){let k=typeof S=="number"?S:new Date(S).getTime();h.push("s.created_at_epoch <= ?"),_.push(k)}}h.push(`( + EXISTS (SELECT 1 FROM json_each(s.files_read) WHERE value LIKE ?) + OR EXISTS (SELECT 1 FROM json_each(s.files_edited) WHERE value LIKE ?) + )`),_.push(`%${e}%`,`%${e}%`);let T=` + SELECT s.* + FROM session_summaries s + WHERE ${h.join(" AND ")} + ORDER BY s.created_at_epoch DESC + LIMIT ? OFFSET ? + `;_.push(t,o);let f=this.db.prepare(T).all(..._);return{observations:m,sessions:f}}findByType(e,r={}){let s=[],{limit:t=50,offset:o=0,orderBy:n="date_desc",...c}=r,d={...c,type:e},l=this.buildFilterClause(d,s,"o"),u=this.buildOrderClause(n,!1),p=` + SELECT o.* + FROM observations o + WHERE ${l} + ${u} + LIMIT ? OFFSET ? + `;return s.push(t,o),this.db.prepare(p).all(...s)}searchUserPrompts(e,r={}){let s=[],{limit:t=20,offset:o=0,orderBy:n="relevance",...c}=r,d=this.escapeFTS5(e);s.push(d);let l=[];if(c.project&&(l.push("s.project = ?"),s.push(c.project)),c.dateRange){let{start:E,end:h}=c.dateRange;if(E){let T=typeof E=="number"?E:new Date(E).getTime();l.push("up.created_at_epoch >= ?"),s.push(T)}if(h){let T=typeof h=="number"?h:new Date(h).getTime();l.push("up.created_at_epoch <= ?"),s.push(T)}}let m=` + SELECT + up.*, + user_prompts_fts.rank as rank + FROM user_prompts up + JOIN user_prompts_fts ON up.id = user_prompts_fts.rowid + JOIN sdk_sessions s ON up.claude_session_id = s.claude_session_id + WHERE user_prompts_fts MATCH ? + ${l.length>0?`AND ${l.join(" AND ")}`:""} + ${n==="relevance"?"ORDER BY user_prompts_fts.rank ASC":n==="date_asc"?"ORDER BY up.created_at_epoch ASC":"ORDER BY up.created_at_epoch DESC"} + LIMIT ? OFFSET ? + `;s.push(t,o);let _=this.db.prepare(m).all(...s);if(_.length>0){let E=Math.min(..._.map(f=>f.rank||0)),T=Math.max(..._.map(f=>f.rank||0))-E||1;_.forEach(f=>{f.rank!==void 0&&(f.score=1-(f.rank-E)/T)})}return _}getUserPromptsBySession(e){return this.db.prepare(` + SELECT + id, + claude_session_id, + prompt_number, + prompt_text, + created_at, + created_at_epoch + FROM user_prompts + WHERE claude_session_id = ? + ORDER BY prompt_number ASC + `).all(e)}close(){this.db.close()}};import J from"better-sqlite3";var $=(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))($||{}),U=class{level;useColor;constructor(){let e=process.env.CLAUDE_MEM_LOG_LEVEL?.toUpperCase()||"INFO";this.level=$[e]??1,this.useColor=process.stdout.isTTY??!1}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.level===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;try{let s=typeof r=="string"?JSON.parse(r):r;if(e==="Bash"&&s.command){let t=s.command.length>50?s.command.substring(0,50)+"...":s.command;return`${e}(${t})`}if(e==="Read"&&s.file_path){let t=s.file_path.split("/").pop()||s.file_path;return`${e}(${t})`}if(e==="Edit"&&s.file_path){let t=s.file_path.split("/").pop()||s.file_path;return`${e}(${t})`}if(e==="Write"&&s.file_path){let t=s.file_path.split("/").pop()||s.file_path;return`${e}(${t})`}return e}catch{return e}}log(e,r,s,t,o){if(e0&&(p=` {${Object.entries(T).map(([O,S])=>`${O}=${S}`).join(", ")}}`)}let m=`[${n}] [${c}] [${d}] ${l}${s}${p}${u}`;e===3?console.error(m):console.log(m)}debug(e,r,s,t){this.log(0,e,r,s,t)}info(e,r,s,t){this.log(1,e,r,s,t)}warn(e,r,s,t){this.log(2,e,r,s,t)}error(e,r,s,t){this.log(3,e,r,s,t)}dataIn(e,r,s,t){this.info(e,`\u2192 ${r}`,s,t)}dataOut(e,r,s,t){this.info(e,`\u2190 ${r}`,s,t)}success(e,r,s,t){this.info(e,`\u2713 ${r}`,s,t)}failure(e,r,s,t){this.error(e,`\u2717 ${r}`,s,t)}timing(e,r,s,t){this.info(e,`\u23F1 ${r}`,t,{duration:`${s}ms`})}},X=new U;var L=class{db;constructor(){x(b),this.db=new J(I),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),this.initializeSchema(),this.ensureWorkerPortColumn(),this.ensurePromptTrackingColumns(),this.removeSessionSummariesUniqueConstraint(),this.addObservationHierarchicalFields(),this.makeObservationsTextNullable(),this.createUserPromptsTable()}initializeSchema(){try{this.db.exec(` + CREATE TABLE IF NOT EXISTS schema_versions ( + id INTEGER PRIMARY KEY, + version INTEGER UNIQUE NOT NULL, + applied_at TEXT NOT NULL + ) + `);let e=this.db.prepare("SELECT version FROM schema_versions ORDER BY version").all();(e.length>0?Math.max(...e.map(s=>s.version)):0)===0&&(console.error("[SessionStore] Initializing fresh database with migration004..."),this.db.exec(` + CREATE TABLE IF NOT EXISTS sdk_sessions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + claude_session_id TEXT UNIQUE NOT NULL, + sdk_session_id TEXT UNIQUE, + project TEXT NOT NULL, + user_prompt TEXT, + started_at TEXT NOT NULL, + started_at_epoch INTEGER NOT NULL, + completed_at TEXT, + completed_at_epoch INTEGER, + status TEXT CHECK(status IN ('active', 'completed', 'failed')) NOT NULL DEFAULT 'active' + ); + + CREATE INDEX IF NOT EXISTS idx_sdk_sessions_claude_id ON sdk_sessions(claude_session_id); + CREATE INDEX IF NOT EXISTS idx_sdk_sessions_sdk_id ON sdk_sessions(sdk_session_id); + CREATE INDEX IF NOT EXISTS idx_sdk_sessions_project ON sdk_sessions(project); + CREATE INDEX IF NOT EXISTS idx_sdk_sessions_status ON sdk_sessions(status); + CREATE INDEX IF NOT EXISTS idx_sdk_sessions_started ON sdk_sessions(started_at_epoch DESC); + + CREATE TABLE IF NOT EXISTS observations ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + sdk_session_id TEXT NOT NULL, + project TEXT NOT NULL, + text TEXT NOT NULL, + type TEXT NOT NULL CHECK(type IN ('decision', 'bugfix', 'feature', 'refactor', 'discovery')), + created_at TEXT NOT NULL, + created_at_epoch INTEGER NOT NULL, + FOREIGN KEY(sdk_session_id) REFERENCES sdk_sessions(sdk_session_id) ON DELETE CASCADE + ); + + CREATE INDEX IF NOT EXISTS idx_observations_sdk_session ON observations(sdk_session_id); + CREATE INDEX IF NOT EXISTS idx_observations_project ON observations(project); + CREATE INDEX IF NOT EXISTS idx_observations_type ON observations(type); + CREATE INDEX IF NOT EXISTS idx_observations_created ON observations(created_at_epoch DESC); + + CREATE TABLE IF NOT EXISTS session_summaries ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + sdk_session_id TEXT UNIQUE NOT NULL, + project TEXT NOT NULL, + request TEXT, + investigated TEXT, + learned TEXT, + completed TEXT, + next_steps TEXT, + files_read TEXT, + files_edited TEXT, + notes TEXT, + created_at TEXT NOT NULL, + created_at_epoch INTEGER NOT NULL, + FOREIGN KEY(sdk_session_id) REFERENCES sdk_sessions(sdk_session_id) ON DELETE CASCADE + ); + + CREATE INDEX IF NOT EXISTS idx_session_summaries_sdk_session ON session_summaries(sdk_session_id); + CREATE INDEX IF NOT EXISTS idx_session_summaries_project ON session_summaries(project); + CREATE INDEX IF NOT EXISTS idx_session_summaries_created ON session_summaries(created_at_epoch DESC); + `),this.db.prepare("INSERT INTO schema_versions (version, applied_at) VALUES (?, ?)").run(4,new Date().toISOString()),console.error("[SessionStore] Migration004 applied successfully"))}catch(e){throw console.error("[SessionStore] Schema initialization error:",e.message),e}}ensureWorkerPortColumn(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(5))return;this.db.pragma("table_info(sdk_sessions)").some(t=>t.name==="worker_port")||(this.db.exec("ALTER TABLE sdk_sessions ADD COLUMN worker_port INTEGER"),console.error("[SessionStore] Added worker_port column to sdk_sessions table")),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(5,new Date().toISOString())}catch(e){console.error("[SessionStore] Migration error:",e.message)}}ensurePromptTrackingColumns(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(6))return;this.db.pragma("table_info(sdk_sessions)").some(d=>d.name==="prompt_counter")||(this.db.exec("ALTER TABLE sdk_sessions ADD COLUMN prompt_counter INTEGER DEFAULT 0"),console.error("[SessionStore] Added prompt_counter column to sdk_sessions table")),this.db.pragma("table_info(observations)").some(d=>d.name==="prompt_number")||(this.db.exec("ALTER TABLE observations ADD COLUMN prompt_number INTEGER"),console.error("[SessionStore] Added prompt_number column to observations table")),this.db.pragma("table_info(session_summaries)").some(d=>d.name==="prompt_number")||(this.db.exec("ALTER TABLE session_summaries ADD COLUMN prompt_number INTEGER"),console.error("[SessionStore] Added prompt_number column to session_summaries table")),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(6,new Date().toISOString())}catch(e){console.error("[SessionStore] Prompt tracking migration error:",e.message)}}removeSessionSummariesUniqueConstraint(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(7))return;if(!this.db.pragma("index_list(session_summaries)").some(t=>t.unique===1)){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(7,new Date().toISOString());return}console.error("[SessionStore] Removing UNIQUE constraint from session_summaries.sdk_session_id..."),this.db.exec("BEGIN TRANSACTION");try{this.db.exec(` + CREATE TABLE session_summaries_new ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + sdk_session_id TEXT NOT NULL, + project TEXT NOT NULL, + request TEXT, + investigated TEXT, + learned TEXT, + completed TEXT, + next_steps TEXT, + files_read TEXT, + files_edited TEXT, + notes TEXT, + prompt_number INTEGER, + created_at TEXT NOT NULL, + created_at_epoch INTEGER NOT NULL, + FOREIGN KEY(sdk_session_id) REFERENCES sdk_sessions(sdk_session_id) ON DELETE CASCADE + ) + `),this.db.exec(` + INSERT INTO session_summaries_new + SELECT id, sdk_session_id, project, request, investigated, learned, + completed, next_steps, files_read, files_edited, notes, + prompt_number, created_at, created_at_epoch + FROM session_summaries + `),this.db.exec("DROP TABLE session_summaries"),this.db.exec("ALTER TABLE session_summaries_new RENAME TO session_summaries"),this.db.exec(` + CREATE INDEX idx_session_summaries_sdk_session ON session_summaries(sdk_session_id); + CREATE INDEX idx_session_summaries_project ON session_summaries(project); + CREATE INDEX idx_session_summaries_created ON session_summaries(created_at_epoch DESC); + `),this.db.exec("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(7,new Date().toISOString()),console.error("[SessionStore] Successfully removed UNIQUE constraint from session_summaries.sdk_session_id")}catch(t){throw this.db.exec("ROLLBACK"),t}}catch(e){console.error("[SessionStore] Migration error (remove UNIQUE constraint):",e.message)}}addObservationHierarchicalFields(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(8))return;if(this.db.pragma("table_info(observations)").some(t=>t.name==="title")){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(8,new Date().toISOString());return}console.error("[SessionStore] Adding hierarchical fields to observations table..."),this.db.exec(` + ALTER TABLE observations ADD COLUMN title TEXT; + ALTER TABLE observations ADD COLUMN subtitle TEXT; + ALTER TABLE observations ADD COLUMN facts TEXT; + ALTER TABLE observations ADD COLUMN narrative TEXT; + ALTER TABLE observations ADD COLUMN concepts TEXT; + ALTER TABLE observations ADD COLUMN files_read TEXT; + ALTER TABLE observations ADD COLUMN files_modified TEXT; + `),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(8,new Date().toISOString()),console.error("[SessionStore] Successfully added hierarchical fields to observations table")}catch(e){console.error("[SessionStore] Migration error (add hierarchical fields):",e.message)}}makeObservationsTextNullable(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(9))return;let s=this.db.pragma("table_info(observations)").find(t=>t.name==="text");if(!s||s.notnull===0){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(9,new Date().toISOString());return}console.error("[SessionStore] Making observations.text nullable..."),this.db.exec("BEGIN TRANSACTION");try{this.db.exec(` + CREATE TABLE observations_new ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + sdk_session_id TEXT NOT NULL, + project TEXT NOT NULL, + text TEXT, + type TEXT NOT NULL CHECK(type IN ('decision', 'bugfix', 'feature', 'refactor', 'discovery', 'change')), + title TEXT, + subtitle TEXT, + facts TEXT, + narrative TEXT, + concepts TEXT, + files_read TEXT, + files_modified TEXT, + prompt_number INTEGER, + created_at TEXT NOT NULL, + created_at_epoch INTEGER NOT NULL, + FOREIGN KEY(sdk_session_id) REFERENCES sdk_sessions(sdk_session_id) ON DELETE CASCADE + ) + `),this.db.exec(` + INSERT INTO observations_new + SELECT id, sdk_session_id, project, text, type, title, subtitle, facts, + narrative, concepts, files_read, files_modified, prompt_number, + created_at, created_at_epoch + FROM observations + `),this.db.exec("DROP TABLE observations"),this.db.exec("ALTER TABLE observations_new RENAME TO observations"),this.db.exec(` + CREATE INDEX idx_observations_sdk_session ON observations(sdk_session_id); + CREATE INDEX idx_observations_project ON observations(project); + CREATE INDEX idx_observations_type ON observations(type); + CREATE INDEX idx_observations_created ON observations(created_at_epoch DESC); + `),this.db.exec("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(9,new Date().toISOString()),console.error("[SessionStore] Successfully made observations.text nullable")}catch(t){throw this.db.exec("ROLLBACK"),t}}catch(e){console.error("[SessionStore] Migration error (make text nullable):",e.message)}}createUserPromptsTable(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(10))return;if(this.db.pragma("table_info(user_prompts)").length>0){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(10,new Date().toISOString());return}console.error("[SessionStore] Creating user_prompts table with FTS5 support..."),this.db.exec("BEGIN TRANSACTION");try{this.db.exec(` + CREATE TABLE user_prompts ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + claude_session_id TEXT NOT NULL, + prompt_number INTEGER NOT NULL, + prompt_text TEXT NOT NULL, + created_at TEXT NOT NULL, + created_at_epoch INTEGER NOT NULL, + FOREIGN KEY(claude_session_id) REFERENCES sdk_sessions(claude_session_id) ON DELETE CASCADE + ); + + CREATE INDEX idx_user_prompts_claude_session ON user_prompts(claude_session_id); + CREATE INDEX idx_user_prompts_created ON user_prompts(created_at_epoch DESC); + CREATE INDEX idx_user_prompts_prompt_number ON user_prompts(prompt_number); + `),this.db.exec(` + CREATE VIRTUAL TABLE user_prompts_fts USING fts5( + prompt_text, + content='user_prompts', + content_rowid='id' + ); + `),this.db.exec(` + CREATE TRIGGER user_prompts_ai AFTER INSERT ON user_prompts BEGIN + INSERT INTO user_prompts_fts(rowid, prompt_text) + VALUES (new.id, new.prompt_text); + END; + + CREATE TRIGGER user_prompts_ad AFTER DELETE ON user_prompts BEGIN + INSERT INTO user_prompts_fts(user_prompts_fts, rowid, prompt_text) + VALUES('delete', old.id, old.prompt_text); + END; + + CREATE TRIGGER user_prompts_au AFTER UPDATE ON user_prompts BEGIN + INSERT INTO user_prompts_fts(user_prompts_fts, rowid, prompt_text) + VALUES('delete', old.id, old.prompt_text); + INSERT INTO user_prompts_fts(rowid, prompt_text) + VALUES (new.id, new.prompt_text); + END; + `),this.db.exec("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(10,new Date().toISOString()),console.error("[SessionStore] Successfully created user_prompts table with FTS5 support")}catch(s){throw this.db.exec("ROLLBACK"),s}}catch(e){console.error("[SessionStore] Migration error (create user_prompts table):",e.message)}}getRecentSummaries(e,r=10){return this.db.prepare(` + SELECT + request, investigated, learned, completed, next_steps, + files_read, files_edited, notes, prompt_number, created_at + FROM session_summaries + WHERE project = ? + ORDER BY created_at_epoch DESC + LIMIT ? + `).all(e,r)}getRecentSummariesWithSessionInfo(e,r=3){return this.db.prepare(` + SELECT + sdk_session_id, request, learned, completed, next_steps, + prompt_number, created_at + FROM session_summaries + WHERE project = ? + ORDER BY created_at_epoch DESC + LIMIT ? + `).all(e,r)}getRecentObservations(e,r=20){return this.db.prepare(` + SELECT type, text, prompt_number, created_at + FROM observations + WHERE project = ? + ORDER BY created_at_epoch DESC + LIMIT ? + `).all(e,r)}getRecentSessionsWithStatus(e,r=3){return this.db.prepare(` + SELECT * FROM ( + SELECT + s.sdk_session_id, + s.status, + s.started_at, + s.started_at_epoch, + s.user_prompt, + CASE WHEN sum.sdk_session_id IS NOT NULL THEN 1 ELSE 0 END as has_summary + FROM sdk_sessions s + LEFT JOIN session_summaries sum ON s.sdk_session_id = sum.sdk_session_id + WHERE s.project = ? AND s.sdk_session_id IS NOT NULL + GROUP BY s.sdk_session_id + ORDER BY s.started_at_epoch DESC + LIMIT ? + ) + ORDER BY started_at_epoch ASC + `).all(e,r)}getObservationsForSession(e){return this.db.prepare(` + SELECT title, subtitle, type, prompt_number + FROM observations + WHERE sdk_session_id = ? + ORDER BY created_at_epoch ASC + `).all(e)}getObservationsByIds(e,r={}){if(e.length===0)return[];let{orderBy:s="date_desc",limit:t}=r,o=s==="date_asc"?"ASC":"DESC",n=t?`LIMIT ${t}`:"",c=e.map(()=>"?").join(",");return this.db.prepare(` + SELECT * + FROM observations + WHERE id IN (${c}) + ORDER BY created_at_epoch ${o} + ${n} + `).all(...e)}getSummaryForSession(e){return this.db.prepare(` + SELECT + request, investigated, learned, completed, next_steps, + files_read, files_edited, notes, prompt_number, created_at + FROM session_summaries + WHERE sdk_session_id = ? + ORDER BY created_at_epoch DESC + LIMIT 1 + `).get(e)||null}getFilesForSession(e){let s=this.db.prepare(` + SELECT files_read, files_modified + FROM observations + WHERE sdk_session_id = ? + `).all(e),t=new Set,o=new Set;for(let n of s){if(n.files_read)try{let c=JSON.parse(n.files_read);Array.isArray(c)&&c.forEach(d=>t.add(d))}catch{}if(n.files_modified)try{let c=JSON.parse(n.files_modified);Array.isArray(c)&&c.forEach(d=>o.add(d))}catch{}}return{filesRead:Array.from(t),filesModified:Array.from(o)}}getSessionById(e){return this.db.prepare(` + SELECT id, claude_session_id, sdk_session_id, project, user_prompt + FROM sdk_sessions + WHERE id = ? + LIMIT 1 + `).get(e)||null}findActiveSDKSession(e){return this.db.prepare(` + SELECT id, sdk_session_id, project, worker_port + FROM sdk_sessions + WHERE claude_session_id = ? AND status = 'active' + LIMIT 1 + `).get(e)||null}findAnySDKSession(e){return this.db.prepare(` + SELECT id + FROM sdk_sessions + WHERE claude_session_id = ? + LIMIT 1 + `).get(e)||null}reactivateSession(e,r){this.db.prepare(` + UPDATE sdk_sessions + SET status = 'active', user_prompt = ?, worker_port = NULL + WHERE id = ? + `).run(r,e)}incrementPromptCounter(e){return this.db.prepare(` + UPDATE sdk_sessions + SET prompt_counter = COALESCE(prompt_counter, 0) + 1 + WHERE id = ? + `).run(e),this.db.prepare(` + SELECT prompt_counter FROM sdk_sessions WHERE id = ? + `).get(e)?.prompt_counter||1}getPromptCounter(e){return this.db.prepare(` + SELECT prompt_counter FROM sdk_sessions WHERE id = ? + `).get(e)?.prompt_counter||0}createSDKSession(e,r,s){let t=new Date,o=t.getTime(),c=this.db.prepare(` + INSERT OR IGNORE INTO sdk_sessions + (claude_session_id, sdk_session_id, project, user_prompt, started_at, started_at_epoch, status) + VALUES (?, ?, ?, ?, ?, ?, 'active') + `).run(e,e,r,s,t.toISOString(),o);return c.lastInsertRowid===0||c.changes===0?this.db.prepare(` + SELECT id FROM sdk_sessions WHERE claude_session_id = ? LIMIT 1 + `).get(e).id:c.lastInsertRowid}updateSDKSessionId(e,r){return this.db.prepare(` + UPDATE sdk_sessions + SET sdk_session_id = ? + WHERE id = ? AND sdk_session_id IS NULL + `).run(r,e).changes===0?(X.debug("DB","sdk_session_id already set, skipping update",{sessionId:e,sdkSessionId:r}),!1):!0}setWorkerPort(e,r){this.db.prepare(` + UPDATE sdk_sessions + SET worker_port = ? + WHERE id = ? + `).run(r,e)}getWorkerPort(e){return this.db.prepare(` + SELECT worker_port + FROM sdk_sessions + WHERE id = ? + LIMIT 1 + `).get(e)?.worker_port||null}saveUserPrompt(e,r,s){let t=new Date,o=t.getTime();return this.db.prepare(` + INSERT INTO user_prompts + (claude_session_id, prompt_number, prompt_text, created_at, created_at_epoch) + VALUES (?, ?, ?, ?, ?) + `).run(e,r,s,t.toISOString(),o).lastInsertRowid}storeObservation(e,r,s,t){let o=new Date,n=o.getTime();this.db.prepare(` + SELECT id FROM sdk_sessions WHERE sdk_session_id = ? + `).get(e)||(this.db.prepare(` + INSERT INTO sdk_sessions + (claude_session_id, sdk_session_id, project, started_at, started_at_epoch, status) + VALUES (?, ?, ?, ?, ?, 'active') + `).run(e,e,r,o.toISOString(),n),console.error(`[SessionStore] Auto-created session record for session_id: ${e}`)),this.db.prepare(` + INSERT INTO observations + (sdk_session_id, project, type, title, subtitle, facts, narrative, concepts, + files_read, files_modified, prompt_number, created_at, created_at_epoch) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `).run(e,r,s.type,s.title,s.subtitle,JSON.stringify(s.facts),s.narrative,JSON.stringify(s.concepts),JSON.stringify(s.files_read),JSON.stringify(s.files_modified),t||null,o.toISOString(),n)}storeSummary(e,r,s,t){let o=new Date,n=o.getTime();this.db.prepare(` + SELECT id FROM sdk_sessions WHERE sdk_session_id = ? + `).get(e)||(this.db.prepare(` + INSERT INTO sdk_sessions + (claude_session_id, sdk_session_id, project, started_at, started_at_epoch, status) + VALUES (?, ?, ?, ?, ?, 'active') + `).run(e,e,r,o.toISOString(),n),console.error(`[SessionStore] Auto-created session record for session_id: ${e}`)),this.db.prepare(` + INSERT INTO session_summaries + (sdk_session_id, project, request, investigated, learned, completed, + next_steps, notes, prompt_number, created_at, created_at_epoch) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `).run(e,r,s.request,s.investigated,s.learned,s.completed,s.next_steps,s.notes,t||null,o.toISOString(),n)}markSessionCompleted(e){let r=new Date,s=r.getTime();this.db.prepare(` + UPDATE sdk_sessions + SET status = 'completed', completed_at = ?, completed_at_epoch = ? + WHERE id = ? + `).run(r.toISOString(),s,e)}markSessionFailed(e){let r=new Date,s=r.getTime();this.db.prepare(` + UPDATE sdk_sessions + SET status = 'failed', completed_at = ?, completed_at_epoch = ? + WHERE id = ? + `).run(r.toISOString(),s,e)}cleanupOrphanedSessions(){let e=new Date,r=e.getTime();return this.db.prepare(` + UPDATE sdk_sessions + SET status = 'failed', completed_at = ?, completed_at_epoch = ? + WHERE status = 'active' + `).run(e.toISOString(),r).changes}close(){this.db.close()}};var R,y,N=null,oe="cm__claude-mem";try{R=new C,y=new L}catch(a){console.error("[search-server] Failed to initialize search:",a.message),process.exit(1)}async function A(a,e,r){if(!N)throw new Error("Chroma client not initialized");let t=(await N.callTool({name:"chroma_query_documents",arguments:{collection_name:oe,query_texts:[a],n_results:e,include:["documents","metadatas","distances"],where:r}})).content[0]?.text||"",o;try{o=JSON.parse(t)}catch(u){return console.error("[search-server] Failed to parse Chroma response as JSON:",u),{ids:[],distances:[],metadatas:[]}}let n=[],c=o.ids?.[0]||[];for(let u of c){let p=u.match(/obs_(\d+)_/);if(p){let m=parseInt(p[1],10);n.includes(m)||n.push(m)}}let d=o.distances?.[0]||[],l=o.metadatas?.[0]||[];return{ids:n,distances:d,metadatas:l}}function v(){return` +--- +\u{1F4A1} Search Strategy: +ALWAYS search with index format FIRST to get an overview and identify relevant results. +This is critical for token efficiency - index format uses ~10x fewer tokens than full format. + +Search workflow: +1. Initial search: Use default (index) format to see titles, dates, and sources +2. Review results: Identify which items are most relevant to your needs +3. Deep dive: Only then use format: "full" on specific items of interest +4. Narrow down: Use filters (type, dateRange, concepts, files) to refine results + +Other tips: +\u2022 To search by concept: Use find_by_concept tool +\u2022 To browse by type: Use find_by_type with ["decision", "feature", etc.] +\u2022 To sort by date: Use orderBy: "date_desc" or "date_asc"`}function D(a,e){let r=a.title||`Observation #${a.id}`,s=new Date(a.created_at_epoch).toLocaleString(),t=a.type?`[${a.type}]`:"";return`${e+1}. ${t} ${r} + Date: ${s} + Source: claude-mem://observation/${a.id}`}function P(a,e){let r=a.request||`Session ${a.sdk_session_id.substring(0,8)}`,s=new Date(a.created_at_epoch).toLocaleString();return`${e+1}. ${r} + Date: ${s} + Source: claude-mem://session/${a.sdk_session_id}`}function w(a,e){let r=a.title||`Observation #${a.id}`,s=[];s.push(`## ${r}`),s.push(`*Source: claude-mem://observation/${a.id}*`),s.push(""),a.subtitle&&(s.push(`**${a.subtitle}**`),s.push("")),a.narrative&&(s.push(a.narrative),s.push("")),a.text&&(s.push(a.text),s.push(""));let t=[];if(t.push(`Type: ${a.type}`),a.facts)try{let n=JSON.parse(a.facts);n.length>0&&t.push(`Facts: ${n.join("; ")}`)}catch{}if(a.concepts)try{let n=JSON.parse(a.concepts);n.length>0&&t.push(`Concepts: ${n.join(", ")}`)}catch{}if(a.files_read||a.files_modified){let n=[];if(a.files_read)try{n.push(...JSON.parse(a.files_read))}catch{}if(a.files_modified)try{n.push(...JSON.parse(a.files_modified))}catch{}n.length>0&&t.push(`Files: ${[...new Set(n)].join(", ")}`)}t.length>0&&(s.push("---"),s.push(t.join(" | ")));let o=new Date(a.created_at_epoch).toLocaleString();return s.push(""),s.push("---"),s.push(`Date: ${o}`),s.join(` +`)}function G(a,e){let r=a.request||`Session ${a.sdk_session_id.substring(0,8)}`,s=[];s.push(`## ${r}`),s.push(`*Source: claude-mem://session/${a.sdk_session_id}*`),s.push(""),a.completed&&(s.push(`**Completed:** ${a.completed}`),s.push("")),a.learned&&(s.push(`**Learned:** ${a.learned}`),s.push("")),a.investigated&&(s.push(`**Investigated:** ${a.investigated}`),s.push("")),a.next_steps&&(s.push(`**Next Steps:** ${a.next_steps}`),s.push("")),a.notes&&(s.push(`**Notes:** ${a.notes}`),s.push(""));let t=[];if(a.files_read||a.files_edited){let n=[];if(a.files_read)try{n.push(...JSON.parse(a.files_read))}catch{}if(a.files_edited)try{n.push(...JSON.parse(a.files_edited))}catch{}n.length>0&&t.push(`Files: ${[...new Set(n)].join(", ")}`)}let o=new Date(a.created_at_epoch).toLocaleDateString();return t.push(`Date: ${o}`),t.length>0&&(s.push("---"),s.push(t.join(" | "))),s.join(` +`)}function ie(a,e){let r=a.prompt_text.length>100?a.prompt_text.substring(0,100)+"...":a.prompt_text,s=new Date(a.created_at_epoch).toLocaleString();return`${e+1}. "${r}" + Date: ${s} | Prompt #${a.prompt_number} + Source: claude-mem://user-prompt/${a.id}`}function ae(a,e){let r=[];r.push(`## User Prompt #${a.prompt_number}`),r.push(`*Source: claude-mem://user-prompt/${a.id}*`),r.push(""),r.push(a.prompt_text),r.push(""),r.push("---");let s=new Date(a.created_at_epoch).toLocaleString();return r.push(`Date: ${s}`),r.join(` +`)}var ce=i.object({project:i.string().optional().describe("Filter by project name"),type:i.union([i.enum(["decision","bugfix","feature","refactor","discovery","change"]),i.array(i.enum(["decision","bugfix","feature","refactor","discovery","change"]))]).optional().describe("Filter by observation type"),concepts:i.union([i.string(),i.array(i.string())]).optional().describe("Filter by concept tags"),files:i.union([i.string(),i.array(i.string())]).optional().describe("Filter by file paths (partial match)"),dateRange:i.object({start:i.union([i.string(),i.number()]).optional().describe("Start date (ISO string or epoch)"),end:i.union([i.string(),i.number()]).optional().describe("End date (ISO string or epoch)")}).optional().describe("Filter by date range"),limit:i.number().min(1).max(100).default(20).describe("Maximum number of results"),offset:i.number().min(0).default(0).describe("Number of results to skip"),orderBy:i.enum(["relevance","date_desc","date_asc"]).default("relevance").describe("Sort order")}),H=[{name:"search_observations",description:'Search observations using full-text search across titles, narratives, facts, and concepts. IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:i.object({query:i.string().describe("Search query for FTS5 full-text search"),format:i.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),...ce.shape}),handler:async a=>{try{let{query:e,format:r="index",...s}=a,t=[];if(N)try{console.error("[search-server] Using hybrid semantic search (Chroma + SQLite)");let n=await A(e,100);if(console.error(`[search-server] Chroma returned ${n.ids.length} semantic matches`),n.ids.length>0){let c=Math.floor(Date.now()/1e3)-7776e3,d=n.ids.filter((l,u)=>{let p=n.metadatas[u];return p&&p.created_at_epoch>c});if(console.error(`[search-server] ${d.length} results within 90-day window`),d.length>0){let l=s.limit||20;t=y.getObservationsByIds(d,{orderBy:"date_desc",limit:l}),console.error(`[search-server] Hydrated ${t.length} observations from SQLite`)}}}catch(n){console.error("[search-server] Chroma query failed, falling back to FTS5:",n.message)}if(t.length===0&&(console.error("[search-server] Using FTS5 keyword search"),t=R.searchObservations(e,s)),t.length===0)return{content:[{type:"text",text:`No observations found matching "${e}"`}]};let o;if(r==="index"){let n=`Found ${t.length} observation(s) matching "${e}": + +`,c=t.map((d,l)=>D(d,l));o=n+c.join(` + +`)+v()}else o=t.map((c,d)=>w(c,d)).join(` + +--- + +`);return{content:[{type:"text",text:o}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"search_sessions",description:'Search session summaries using full-text search across requests, completions, learnings, and notes. IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:i.object({query:i.string().describe("Search query for FTS5 full-text search"),format:i.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),project:i.string().optional().describe("Filter by project name"),dateRange:i.object({start:i.union([i.string(),i.number()]).optional(),end:i.union([i.string(),i.number()]).optional()}).optional().describe("Filter by date range"),limit:i.number().min(1).max(100).default(20).describe("Maximum number of results"),offset:i.number().min(0).default(0).describe("Number of results to skip"),orderBy:i.enum(["relevance","date_desc","date_asc"]).default("relevance").describe("Sort order")}),handler:async a=>{try{let{query:e,format:r="index",...s}=a,t=R.searchSessions(e,s);if(t.length===0)return{content:[{type:"text",text:`No sessions found matching "${e}"`}]};let o;if(r==="index"){let n=`Found ${t.length} session(s) matching "${e}": + +`,c=t.map((d,l)=>P(d,l));o=n+c.join(` + +`)+v()}else o=t.map((c,d)=>G(c,d)).join(` + +--- + +`);return{content:[{type:"text",text:o}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"find_by_concept",description:'Find observations tagged with a specific concept. IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:i.object({concept:i.string().describe("Concept tag to search for"),format:i.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),project:i.string().optional().describe("Filter by project name"),dateRange:i.object({start:i.union([i.string(),i.number()]).optional(),end:i.union([i.string(),i.number()]).optional()}).optional().describe("Filter by date range"),limit:i.number().min(1).max(100).default(20).describe("Maximum results. IMPORTANT: Start with 3-5 to avoid exceeding MCP token limits, even in index mode."),offset:i.number().min(0).default(0).describe("Number of results to skip"),orderBy:i.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async a=>{try{let{concept:e,format:r="index",...s}=a,t=[];if(N)try{console.error("[search-server] Using metadata-first + semantic ranking for concept search");let n=R.findByConcept(e,s);if(console.error(`[search-server] Found ${n.length} observations with concept "${e}"`),n.length>0){let c=n.map(u=>u.id),d=await A(e,Math.min(c.length,100)),l=[];for(let u of d.ids)c.includes(u)&&!l.includes(u)&&l.push(u);console.error(`[search-server] Chroma ranked ${l.length} results by semantic relevance`),l.length>0&&(t=y.getObservationsByIds(l,{limit:s.limit||20}),t.sort((u,p)=>l.indexOf(u.id)-l.indexOf(p.id)))}}catch(n){console.error("[search-server] Chroma ranking failed, using SQLite order:",n.message)}if(t.length===0&&(console.error("[search-server] Using SQLite-only concept search"),t=R.findByConcept(e,s)),t.length===0)return{content:[{type:"text",text:`No observations found with concept "${e}"`}]};let o;if(r==="index"){let n=`Found ${t.length} observation(s) with concept "${e}": + +`,c=t.map((d,l)=>D(d,l));o=n+c.join(` + +`)+v()}else o=t.map((c,d)=>w(c,d)).join(` + +--- + +`);return{content:[{type:"text",text:o}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"find_by_file",description:'Find observations and sessions that reference a specific file path. IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:i.object({filePath:i.string().describe("File path to search for (supports partial matching)"),format:i.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),project:i.string().optional().describe("Filter by project name"),dateRange:i.object({start:i.union([i.string(),i.number()]).optional(),end:i.union([i.string(),i.number()]).optional()}).optional().describe("Filter by date range"),limit:i.number().min(1).max(100).default(20).describe("Maximum results. IMPORTANT: Start with 3-5 to avoid exceeding MCP token limits, even in index mode."),offset:i.number().min(0).default(0).describe("Number of results to skip"),orderBy:i.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async a=>{try{let{filePath:e,format:r="index",...s}=a,t=[],o=[];if(N)try{console.error("[search-server] Using metadata-first + semantic ranking for file search");let d=R.findByFile(e,s);if(console.error(`[search-server] Found ${d.observations.length} observations, ${d.sessions.length} sessions for file "${e}"`),o=d.sessions,d.observations.length>0){let l=d.observations.map(m=>m.id),u=await A(e,Math.min(l.length,100)),p=[];for(let m of u.ids)l.includes(m)&&!p.includes(m)&&p.push(m);console.error(`[search-server] Chroma ranked ${p.length} observations by semantic relevance`),p.length>0&&(t=y.getObservationsByIds(p,{limit:s.limit||20}),t.sort((m,_)=>p.indexOf(m.id)-p.indexOf(_.id)))}}catch(d){console.error("[search-server] Chroma ranking failed, using SQLite order:",d.message)}if(t.length===0&&o.length===0){console.error("[search-server] Using SQLite-only file search");let d=R.findByFile(e,s);t=d.observations,o=d.sessions}let n=t.length+o.length;if(n===0)return{content:[{type:"text",text:`No results found for file "${e}"`}]};let c;if(r==="index"){let d=`Found ${n} result(s) for file "${e}": + +`,l=[];t.forEach((u,p)=>{l.push(D(u,p))}),o.forEach((u,p)=>{l.push(P(u,p+t.length))}),c=d+l.join(` + +`)+v()}else{let d=[];t.forEach((l,u)=>{d.push(w(l,u))}),o.forEach((l,u)=>{d.push(G(l,u+t.length))}),c=d.join(` + +--- + +`)}return{content:[{type:"text",text:c}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"find_by_type",description:'Find observations of a specific type (decision, bugfix, feature, refactor, discovery, change). IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:i.object({type:i.union([i.enum(["decision","bugfix","feature","refactor","discovery","change"]),i.array(i.enum(["decision","bugfix","feature","refactor","discovery","change"]))]).describe("Observation type(s) to filter by"),format:i.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),project:i.string().optional().describe("Filter by project name"),dateRange:i.object({start:i.union([i.string(),i.number()]).optional(),end:i.union([i.string(),i.number()]).optional()}).optional().describe("Filter by date range"),limit:i.number().min(1).max(100).default(20).describe("Maximum results. IMPORTANT: Start with 3-5 to avoid exceeding MCP token limits, even in index mode."),offset:i.number().min(0).default(0).describe("Number of results to skip"),orderBy:i.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async a=>{try{let{type:e,format:r="index",...s}=a,t=Array.isArray(e)?e.join(", "):e,o=[];if(N)try{console.error("[search-server] Using metadata-first + semantic ranking for type search");let c=R.findByType(e,s);if(console.error(`[search-server] Found ${c.length} observations with type "${t}"`),c.length>0){let d=c.map(p=>p.id),l=await A(t,Math.min(d.length,100)),u=[];for(let p of l.ids)d.includes(p)&&!u.includes(p)&&u.push(p);console.error(`[search-server] Chroma ranked ${u.length} results by semantic relevance`),u.length>0&&(o=y.getObservationsByIds(u,{limit:s.limit||20}),o.sort((p,m)=>u.indexOf(p.id)-u.indexOf(m.id)))}}catch(c){console.error("[search-server] Chroma ranking failed, using SQLite order:",c.message)}if(o.length===0&&(console.error("[search-server] Using SQLite-only type search"),o=R.findByType(e,s)),o.length===0)return{content:[{type:"text",text:`No observations found with type "${t}"`}]};let n;if(r==="index"){let c=`Found ${o.length} observation(s) with type "${t}": + +`,d=o.map((l,u)=>D(l,u));n=c+d.join(` + +`)+v()}else n=o.map((d,l)=>w(d,l)).join(` + +--- + +`);return{content:[{type:"text",text:n}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"get_recent_context",description:"Get recent session context including summaries and observations for a project",inputSchema:i.object({project:i.string().optional().describe("Project name (defaults to current working directory basename)"),limit:i.number().min(1).max(10).default(3).describe("Number of recent sessions to retrieve")}),handler:async a=>{try{let e=a.project||ne(process.cwd()),r=a.limit||3,s=y.getRecentSessionsWithStatus(e,r);if(s.length===0)return{content:[{type:"text",text:`# Recent Session Context + +No previous sessions found for project "${e}".`}]};let t=[];t.push("# Recent Session Context"),t.push(""),t.push(`Showing last ${s.length} session(s) for **${e}**:`),t.push("");for(let o of s)if(o.sdk_session_id){if(t.push("---"),t.push(""),o.has_summary){let n=y.getSummaryForSession(o.sdk_session_id);if(n){let c=n.prompt_number?` (Prompt #${n.prompt_number})`:"";if(t.push(`**Summary${c}**`),t.push(""),n.request&&t.push(`**Request:** ${n.request}`),n.completed&&t.push(`**Completed:** ${n.completed}`),n.learned&&t.push(`**Learned:** ${n.learned}`),n.next_steps&&t.push(`**Next Steps:** ${n.next_steps}`),n.files_read)try{let l=JSON.parse(n.files_read);Array.isArray(l)&&l.length>0&&t.push(`**Files Read:** ${l.join(", ")}`)}catch{n.files_read.trim()&&t.push(`**Files Read:** ${n.files_read}`)}if(n.files_edited)try{let l=JSON.parse(n.files_edited);Array.isArray(l)&&l.length>0&&t.push(`**Files Edited:** ${l.join(", ")}`)}catch{n.files_edited.trim()&&t.push(`**Files Edited:** ${n.files_edited}`)}let d=new Date(n.created_at).toLocaleString();t.push(`**Date:** ${d}`)}}else if(o.status==="active"){t.push("**In Progress**"),t.push(""),o.user_prompt&&t.push(`**Request:** ${o.user_prompt}`);let n=y.getObservationsForSession(o.sdk_session_id);if(n.length>0){t.push(""),t.push(`**Observations (${n.length}):**`);for(let d of n)t.push(`- ${d.title}`)}else t.push(""),t.push("*No observations yet*");t.push(""),t.push("**Status:** Active - summary pending");let c=new Date(o.started_at).toLocaleString();t.push(`**Date:** ${c}`)}else{t.push(`**${o.status.charAt(0).toUpperCase()+o.status.slice(1)}**`),t.push(""),o.user_prompt&&t.push(`**Request:** ${o.user_prompt}`),t.push(""),t.push(`**Status:** ${o.status} - no summary available`);let n=new Date(o.started_at).toLocaleString();t.push(`**Date:** ${n}`)}t.push("")}return{content:[{type:"text",text:t.join(` +`)}]}}catch(e){return{content:[{type:"text",text:`Failed to get recent context: ${e.message}`}],isError:!0}}}},{name:"search_user_prompts",description:'Search raw user prompts with full-text search. Use this to find what the user actually said/requested across all sessions. IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:i.object({query:i.string().describe("Search query for FTS5 full-text search"),format:i.enum(["index","full"]).default("index").describe('Output format: "index" for truncated prompts/dates (default, RECOMMENDED for initial search), "full" for complete prompt text (use only after reviewing index results)'),project:i.string().optional().describe("Filter by project name"),dateRange:i.object({start:i.union([i.string(),i.number()]).optional(),end:i.union([i.string(),i.number()]).optional()}).optional().describe("Filter by date range"),limit:i.number().min(1).max(100).default(20).describe("Maximum number of results"),offset:i.number().min(0).default(0).describe("Number of results to skip"),orderBy:i.enum(["relevance","date_desc","date_asc"]).default("relevance").describe("Sort order")}),handler:async a=>{try{let{query:e,format:r="index",...s}=a,t=R.searchUserPrompts(e,s);if(t.length===0)return{content:[{type:"text",text:`No user prompts found matching "${e}"`}]};let o;if(r==="index"){let n=`Found ${t.length} user prompt(s) matching "${e}": + +`,c=t.map((d,l)=>ie(d,l));o=n+c.join(` + +`)+v()}else o=t.map((c,d)=>ae(c,d)).join(` + +--- + +`);return{content:[{type:"text",text:o}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}}],M=new Q({name:"claude-mem-search",version:"1.0.0"},{capabilities:{tools:{}}});M.setRequestHandler(te,async()=>({tools:H.map(a=>({name:a.name,description:a.description,inputSchema:re(a.inputSchema)}))}));M.setRequestHandler(se,async a=>{let e=H.find(r=>r.name===a.params.name);if(!e)throw new Error(`Unknown tool: ${a.params.name}`);try{return await e.handler(a.params.arguments||{})}catch(r){return{content:[{type:"text",text:`Tool execution failed: ${r.message}`}],isError:!0}}});async function de(){let a=new z;await M.connect(a),console.error("[search-server] Claude-mem search server started"),setTimeout(async()=>{try{console.error("[search-server] Initializing Chroma client...");let e=new ee({command:"uvx",args:["chroma-mcp","--client-type","persistent","--data-dir",B]}),r=new Z({name:"claude-mem-search-chroma-client",version:"1.0.0"},{capabilities:{}});await r.connect(e),N=r,console.error("[search-server] Chroma client connected successfully")}catch(e){console.error("[search-server] Failed to initialize Chroma client:",e.message),console.error("[search-server] Falling back to FTS5-only search"),N=null}},0)}de().catch(a=>{console.error("[search-server] Fatal error:",a),process.exit(1)}); diff --git a/scripts/build-hooks.js b/scripts/build-hooks.js index 8ce82091..aa2cb834 100644 --- a/scripts/build-hooks.js +++ b/scripts/build-hooks.js @@ -110,23 +110,19 @@ async function buildHooks() { await build({ entryPoints: [SEARCH_SERVER.source], bundle: true, - platform: 'node', - target: 'node18', format: 'esm', - outfile: `${hooksDir}/${SEARCH_SERVER.name}.js`, + platform: 'node', + outfile: `${hooksDir}/${SEARCH_SERVER.name}.mjs`, minify: true, - external: ['better-sqlite3'], - define: { - '__DEFAULT_PACKAGE_VERSION__': `"${version}"` - }, + packages: 'external', banner: { js: '#!/usr/bin/env node' } }); // Make search server executable - fs.chmodSync(`${hooksDir}/${SEARCH_SERVER.name}.js`, 0o755); - const searchStats = fs.statSync(`${hooksDir}/${SEARCH_SERVER.name}.js`); + fs.chmodSync(`${hooksDir}/${SEARCH_SERVER.name}.mjs`, 0o755); + const searchStats = fs.statSync(`${hooksDir}/${SEARCH_SERVER.name}.mjs`); console.log(`āœ“ search-server built (${(searchStats.size / 1024).toFixed(2)} KB)`); console.log('\nāœ… All hooks, worker service, and search server built successfully!'); diff --git a/src/servers/search-server.ts b/src/servers/search-server.ts index 1f696516..ba883e9f 100644 --- a/src/servers/search-server.ts +++ b/src/servers/search-server.ts @@ -35,7 +35,6 @@ try { /** * Query Chroma vector database via MCP - * Parses Python dict-like responses from Chroma MCP server */ async function queryChroma( query: string, @@ -59,65 +58,31 @@ async function queryChroma( const resultText = result.content[0]?.text || ''; - // Parse Python dict-like output using regex - // Format: {'ids': [[...]], 'distances': [[...]], 'metadatas': [[...]]} + // Parse JSON response + let parsed: any; + try { + parsed = JSON.parse(resultText); + } catch (error) { + console.error('[search-server] Failed to parse Chroma response as JSON:', error); + return { ids: [], distances: [], metadatas: [] }; + } - // Extract IDs (nested array format) - const idsMatch = resultText.match(/'ids':\s*\[\[(.*?)\]\]/s); + // Extract unique observation IDs from document IDs const ids: number[] = []; - if (idsMatch) { - const idsContent = idsMatch[1]; - // Match quoted strings (Chroma doc IDs like 'obs_123_title') - const idMatches = idsContent.match(/'([^']*(?:\\'[^']*)*)'/g) || []; - for (const idMatch of idMatches) { - const docId = idMatch.slice(1, -1); - // Extract sqlite_id from document ID (format: obs_{id}_title) - const sqliteIdMatch = docId.match(/obs_(\d+)_/); - if (sqliteIdMatch) { - const sqliteId = parseInt(sqliteIdMatch[1], 10); - if (!ids.includes(sqliteId)) { - ids.push(sqliteId); - } + const docIds = parsed.ids?.[0] || []; + for (const docId of docIds) { + // Extract sqlite_id from document ID (format: obs_{id}_narrative, obs_{id}_fact_0, etc) + const match = docId.match(/obs_(\d+)_/); + if (match) { + const sqliteId = parseInt(match[1], 10); + if (!ids.includes(sqliteId)) { + ids.push(sqliteId); } } } - // Extract distances (nested array format) - const distancesMatch = resultText.match(/'distances':\s*\[\[([\d.,\s]+)\]\]/s); - const distances: number[] = []; - if (distancesMatch) { - const distancesContent = distancesMatch[1]; - const distanceValues = distancesContent.split(',').map(d => parseFloat(d.trim())).filter(d => !isNaN(d)); - distances.push(...distanceValues); - } - - // Extract metadatas (nested array format) - const metasMatch = resultText.match(/'metadatas':\s*\[\[(.*?)\]\]/s); - const metadatas: any[] = []; - if (metasMatch) { - const metasContent = metasMatch[1]; - // Parse each metadata dict - const metaObjMatches = metasContent.match(/\{[^}]+\}/g) || []; - for (const metaStr of metaObjMatches) { - const meta: any = {}; - // Extract sqlite_id - const sqliteIdMatch = metaStr.match(/'sqlite_id':\s*(\d+)/); - if (sqliteIdMatch) { - meta.sqlite_id = parseInt(sqliteIdMatch[1], 10); - } - // Extract type - const typeMatch = metaStr.match(/'type':\s*'([^']+)'/); - if (typeMatch) { - meta.type = typeMatch[1]; - } - // Extract created_at_epoch - const epochMatch = metaStr.match(/'created_at_epoch':\s*(\d+)/); - if (epochMatch) { - meta.created_at_epoch = parseInt(epochMatch[1], 10); - } - metadatas.push(meta); - } - } + const distances = parsed.distances?.[0] || []; + const metadatas = parsed.metadatas?.[0] || []; return { ids, distances, metadatas }; } @@ -1095,32 +1060,36 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => { // Start the server async function main() { - // Initialize Chroma client - try { - console.error('[search-server] Initializing Chroma client...'); - const chromaTransport = new StdioClientTransport({ - command: 'uvx', - args: ['chroma-mcp', '--client-type', 'persistent', '--data-dir', VECTOR_DB_DIR] - }); - - chromaClient = new Client({ - name: 'claude-mem-search-chroma-client', - version: '1.0.0' - }, { - capabilities: {} - }); - - await chromaClient.connect(chromaTransport); - console.error('[search-server] Chroma client connected successfully'); - } catch (error: any) { - console.error('[search-server] Failed to initialize Chroma client:', error.message); - console.error('[search-server] Falling back to FTS5-only search'); - chromaClient = null; - } - + // Start the MCP server FIRST (critical - must start before blocking operations) const transport = new StdioServerTransport(); await server.connect(transport); console.error('[search-server] Claude-mem search server started'); + + // Initialize Chroma client in background (non-blocking) + setTimeout(async () => { + try { + console.error('[search-server] Initializing Chroma client...'); + const chromaTransport = new StdioClientTransport({ + command: 'uvx', + args: ['chroma-mcp', '--client-type', 'persistent', '--data-dir', VECTOR_DB_DIR] + }); + + const client = new Client({ + name: 'claude-mem-search-chroma-client', + version: '1.0.0' + }, { + capabilities: {} + }); + + await client.connect(chromaTransport); + chromaClient = client; + console.error('[search-server] Chroma client connected successfully'); + } catch (error: any) { + console.error('[search-server] Failed to initialize Chroma client:', error.message); + console.error('[search-server] Falling back to FTS5-only search'); + chromaClient = null; + } + }, 0); } main().catch((error) => {