Files
claude-mem/plugin/scripts/search-server.mjs
Alex Newman c5e68a17c8 refactor: Clean up search architecture, remove experimental contextualize endpoint (#133)
* Refactor code structure for improved readability and maintainability

* Add test results for search API and related functionalities

- Created test result files for various search-related functionalities, including:
  - test-11-search-server-changes.json
  - test-12-context-hook-changes.json
  - test-13-worker-service-changes.json
  - test-14-patterns.json
  - test-15-gotchas.json
  - test-16-discoveries.json
  - test-17-all-bugfixes.json
  - test-18-all-features.json
  - test-19-all-decisions.json
  - test-20-session-search.json
  - test-21-prompt-search.json
  - test-22-decisions-endpoint.json
  - test-23-changes-endpoint.json
  - test-24-how-it-works-endpoint.json
  - test-25-contextualize-endpoint.json
  - test-26-timeline-around-observation.json
  - test-27-multi-param-combo.json
  - test-28-file-type-combo.json

- Each test result file captures specific search failures or outcomes, including issues with undefined properties and successful execution of search queries.
- Enhanced documentation of search architecture and testing strategies, ensuring compliance with established guidelines and improving overall search functionality.

* feat: Enhance unified search API with catch-all parameters and backward compatibility

- Implemented a unified search API at /api/search that accepts catch-all parameters for filtering by type, observation type, concepts, and files.
- Maintained backward compatibility by keeping granular endpoints functional while routing through the same infrastructure.
- Completed comprehensive testing of search capabilities with real-world query scenarios.

fix: Address missing debug output in search API query tests

- Flushed PM2 logs and executed search queries to verify functionality.
- Diagnosed absence of "Raw Chroma" debug messages in worker logs, indicating potential issues with logging or query processing.

refactor: Improve build and deployment pipeline for claude-mem plugin

- Successfully built and synced all hooks and services to the marketplace directory.
- Ensured all dependencies are installed and up-to-date in the deployment location.

feat: Implement hybrid search filters with 90-day recency window

- Enhanced search server to apply a 90-day recency filter to Chroma results before categorizing by document type.

fix: Correct parameter handling in searchUserPrompts method

- Added support for filter-only queries and improved dual-path logic for clarity.

refactor: Rename FTS5 method to clarify fallback status

- Renamed escapeFTS5 to escapeFTS5_fallback_when_chroma_unavailable to indicate its temporary usage.

feat: Introduce contextualize tool for comprehensive project overview

- Added a new tool to fetch recent observations, sessions, and user prompts, providing a quick project overview.

feat: Add semantic shortcut tools for common search patterns

- Implemented 'decisions', 'changes', and 'how_it_works' tools for convenient access to frequently searched observation categories.

feat: Unified timeline tool supports anchor and query modes

- Combined get_context_timeline and get_timeline_by_query into a single interface for timeline exploration.

feat: Unified search tool added to MCP server

- New tool queries all memory types simultaneously, providing combined chronological results for improved search efficiency.

* Refactor search functionality to clarify FTS5 fallback usage

- Updated `worker-service.cjs` to replace FTS5 fallback function with a more descriptive name and improved error handling.
- Enhanced documentation in `SKILL.md` to specify the unified API endpoint and clarify the behavior of the search engine, including the conditions under which FTS5 is used.
- Modified `search-server.ts` to provide clearer logging and descriptions regarding the fallback to FTS5 when UVX/Python is unavailable.
- Renamed and updated the `SessionSearch.ts` methods to reflect the conditions for using FTS5, emphasizing the lack of semantic understanding in fallback scenarios.

* feat: Add ID-based fetch endpoints and simplify mem-search skill

**Problem:**
- Search returns IDs but no way to fetch by ID
- Skill documentation was bloated with too many options
- Claude wasn't using IDs because we didn't tell it how

**Solution:**
1. Added three new HTTP endpoints:
   - GET /api/observation/:id
   - GET /api/session/:id
   - GET /api/prompt/:id

2. Completely rewrote SKILL.md:
   - Stripped complexity down to essentials
   - Clear 3-step prescriptive workflow: Search → Review IDs → Fetch by ID
   - Emphasized ID usage: "The IDs are there for a reason - USE THEM"
   - Removed confusing multi-endpoint documentation
   - Kept only unified search with filters

**Impact:**
- Token efficiency: Claude can now fetch full details only for relevant IDs
- Clarity: One clear workflow instead of 10+ options to choose from
- Usability: IDs are no longer wasted context - they're actionable

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* chore: Move internal docs to private directory

Moved POSTMORTEM and planning docs to ./private to exclude from PR reviews.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: Remove experimental contextualize endpoint

- Removed contextualize MCP tool from search-server (saves ~4KB)
- Disabled FTS5 fallback paths in SessionSearch (now vector-first)
- Cleaned up CLAUDE.md documentation
- Removed contextualize-rewrite-plan.md doc

Rationale:
- Contextualize is better suited as a skill (LLM-powered) than an endpoint
- Search API already provides vector search with configurable limits
- Created issue #132 to track future contextualize skill implementation

Changes:
- src/servers/search-server.ts: Removed contextualize tool definition
- src/services/sqlite/SessionSearch.ts: Disabled FTS5 fallback, added deprecation warnings
- CLAUDE.md: Cleaned up outdated skill documentation
- docs/: Removed contextualize plan document

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: Complete FTS5 cleanup - remove all deprecated search code

This completes the FTS5 cleanup work by removing all commented-out
FTS5 search code while preserving database tables for backward compatibility.

Changes:
- Removed 200+ lines of commented FTS5 search code from SessionSearch.ts
- Removed deprecated degraded_search_query__when_uvx_unavailable method
- Updated all method documentation to clarify vector-first architecture
- Updated class documentation to reflect filter-only query support
- Updated CLAUDE.md to remove FTS5 search references
- Clarified that FTS5 tables exist for backward compatibility only
- Updated "Why SQLite FTS5" section to "Why Vector-First Search"

Database impact: NONE - FTS5 tables remain intact for existing installations

Search architecture:
- ChromaDB: All text-based vector search queries
- SQLite: Filter-only queries (date ranges, metadata, no query text)
- FTS5 tables: Maintained but unused (backward compatibility)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: Remove all FTS5 fallback execution code from search-server

Completes the FTS5 cleanup by removing all fallback execution paths
that attempted to use FTS5 when ChromaDB was unavailable.

Changes:
- Removed all FTS5 fallback code execution paths
- When ChromaDB fails or is unavailable, return empty results with helpful error messages
- Updated all deprecated tool descriptions (search_observations, search_sessions, search_user_prompts)
- Changed error messages to indicate FTS5 fallback has been removed
- Added installation instructions for UVX/Python when vector search is unavailable
- Updated comments from "hybrid search" to "vector-first search"
- Removed ~100 lines of dead FTS5 fallback code

Database impact: NONE - FTS5 tables remain intact (backward compatibility)

Search behavior when ChromaDB unavailable:
- Text queries: Return empty results with error explaining ChromaDB is required
- Filter-only queries (no text): Continue to work via direct SQLite

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: Address PR 133 review feedback

Critical fixes:
- Remove contextualize endpoint from worker-service (route + handler)
- Fix build script logging to show correct .cjs extension (was .mjs)

Documentation improvements:
- Add comprehensive FTS5 retention rationale documentation
- Include v7.0.0 removal TODO for future cleanup

Testing:
- Build succeeds with correct output logging
- Worker restarts successfully (30th restart)
- Contextualize endpoint properly removed (404 response)
- Search endpoint verified working

This addresses all critical review feedback from PR 133.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-21 18:59:23 -05:00

664 lines
331 KiB
JavaScript
Executable File

#!/usr/bin/env node
var Hl=Object.create;var Vs=Object.defineProperty;var zl=Object.getOwnPropertyDescriptor;var Zl=Object.getOwnPropertyNames;var Gl=Object.getPrototypeOf,Ql=Object.prototype.hasOwnProperty;var Rt=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var H=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Wl=(s,e)=>{for(var r in e)Vs(s,r,{get:e[r],enumerable:!0})},Xl=(s,e,r,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of Zl(e))!Ql.call(s,t)&&t!==r&&Vs(s,t,{get:()=>e[t],enumerable:!(a=zl(e,t))||a.enumerable});return s};var Hs=(s,e,r)=>(r=s!=null?Hl(Gl(s)):{},Xl(e||!s||!s.__esModule?Vs(r,"default",{value:s,enumerable:!0}):r,s));var Gn=H((os,Zn)=>{(function(s,e){typeof os=="object"&&typeof Zn<"u"?e(os):typeof define=="function"&&define.amd?define(["exports"],e):e(s.URI=s.URI||{})})(os,(function(s){"use strict";function e(){for(var b=arguments.length,m=Array(b),E=0;E<b;E++)m[E]=arguments[E];if(m.length>1){m[0]=m[0].slice(0,-1);for(var P=m.length-1,O=1;O<P;++O)m[O]=m[O].slice(1,-1);return m[P]=m[P].slice(1),m.join("")}else return m[0]}function r(b){return"(?:"+b+")"}function a(b){return b===void 0?"undefined":b===null?"null":Object.prototype.toString.call(b).split(" ").pop().split("]").shift().toLowerCase()}function t(b){return b.toUpperCase()}function n(b){return b!=null?b instanceof Array?b:typeof b.length!="number"||b.split||b.setInterval||b.call?[b]:Array.prototype.slice.call(b):[]}function o(b,m){var E=b;if(m)for(var P in m)E[P]=m[P];return E}function i(b){var m="[A-Za-z]",E="[\\x0D]",P="[0-9]",O="[\\x22]",B=e(P,"[A-Fa-f]"),K="[\\x0A]",ae="[\\x20]",le=r(r("%[EFef]"+B+"%"+B+B+"%"+B+B)+"|"+r("%[89A-Fa-f]"+B+"%"+B+B)+"|"+r("%"+B+B)),Se="[\\:\\/\\?\\#\\[\\]\\@]",se="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",ve=e(Se,se),xe=b?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",fe=b?"[\\uE000-\\uF8FF]":"[]",ie=e(m,P,"[\\-\\.\\_\\~]",xe),ge=r(m+e(m,P,"[\\+\\-\\.]")+"*"),de=r(r(le+"|"+e(ie,se,"[\\:]"))+"*"),jt=r(r("25[0-5]")+"|"+r("2[0-4]"+P)+"|"+r("1"+P+P)+"|"+r("[1-9]"+P)+"|"+P),Be=r(r("25[0-5]")+"|"+r("2[0-4]"+P)+"|"+r("1"+P+P)+"|"+r("0?[1-9]"+P)+"|0?0?"+P),ze=r(Be+"\\."+Be+"\\."+Be+"\\."+Be),pe=r(B+"{1,4}"),Ve=r(r(pe+"\\:"+pe)+"|"+ze),Ze=r(r(pe+"\\:")+"{6}"+Ve),it=r("\\:\\:"+r(pe+"\\:")+"{5}"+Ve),Ft=r(r(pe)+"?\\:\\:"+r(pe+"\\:")+"{4}"+Ve),ft=r(r(r(pe+"\\:")+"{0,1}"+pe)+"?\\:\\:"+r(pe+"\\:")+"{3}"+Ve),wr=r(r(r(pe+"\\:")+"{0,2}"+pe)+"?\\:\\:"+r(pe+"\\:")+"{2}"+Ve),Br=r(r(r(pe+"\\:")+"{0,3}"+pe)+"?\\:\\:"+pe+"\\:"+Ve),Vr=r(r(r(pe+"\\:")+"{0,4}"+pe)+"?\\:\\:"+Ve),or=r(r(r(pe+"\\:")+"{0,5}"+pe)+"?\\:\\:"+pe),ir=r(r(r(pe+"\\:")+"{0,6}"+pe)+"?\\:\\:"),mt=r([Ze,it,Ft,ft,wr,Br,Vr,or,ir].join("|")),cr=r(r(ie+"|"+le)+"+"),qs=r(mt+"\\%25"+cr),Mt=r(mt+r("\\%25|\\%(?!"+B+"{2})")+cr),jl=r("[vV]"+B+"+\\."+e(ie,se,"[\\:]")+"+"),Fl=r("\\["+r(Mt+"|"+mt+"|"+jl)+"\\]"),mn=r(r(le+"|"+e(ie,se))+"*"),Pr=r(Fl+"|"+ze+"(?!"+mn+")|"+mn),Or=r(P+"*"),vn=r(r(de+"@")+"?"+Pr+r("\\:"+Or)+"?"),Ir=r(le+"|"+e(ie,se,"[\\:\\@]")),Ml=r(Ir+"*"),gn=r(Ir+"+"),Ul=r(r(le+"|"+e(ie,se,"[\\@]"))+"+"),vt=r(r("\\/"+Ml)+"*"),lr=r("\\/"+r(gn+vt)+"?"),Bs=r(Ul+vt),Hr=r(gn+vt),ur="(?!"+Ir+")",Sf=r(vt+"|"+lr+"|"+Bs+"|"+Hr+"|"+ur),dr=r(r(Ir+"|"+e("[\\/\\?]",fe))+"*"),$r=r(r(Ir+"|[\\/\\?]")+"*"),yn=r(r("\\/\\/"+vn+vt)+"|"+lr+"|"+Hr+"|"+ur),ql=r(ge+"\\:"+yn+r("\\?"+dr)+"?"+r("\\#"+$r)+"?"),Bl=r(r("\\/\\/"+vn+vt)+"|"+lr+"|"+Bs+"|"+ur),Vl=r(Bl+r("\\?"+dr)+"?"+r("\\#"+$r)+"?"),xf=r(ql+"|"+Vl),Rf=r(ge+"\\:"+yn+r("\\?"+dr)+"?"),Tf="^("+ge+")\\:"+r(r("\\/\\/("+r("("+de+")@")+"?("+Pr+")"+r("\\:("+Or+")")+"?)")+"?("+vt+"|"+lr+"|"+Hr+"|"+ur+")")+r("\\?("+dr+")")+"?"+r("\\#("+$r+")")+"?$",wf="^(){0}"+r(r("\\/\\/("+r("("+de+")@")+"?("+Pr+")"+r("\\:("+Or+")")+"?)")+"?("+vt+"|"+lr+"|"+Bs+"|"+ur+")")+r("\\?("+dr+")")+"?"+r("\\#("+$r+")")+"?$",Pf="^("+ge+")\\:"+r(r("\\/\\/("+r("("+de+")@")+"?("+Pr+")"+r("\\:("+Or+")")+"?)")+"?("+vt+"|"+lr+"|"+Hr+"|"+ur+")")+r("\\?("+dr+")")+"?$",Of="^"+r("\\#("+$r+")")+"?$",If="^"+r("("+de+")@")+"?("+Pr+")"+r("\\:("+Or+")")+"?$";return{NOT_SCHEME:new RegExp(e("[^]",m,P,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(e("[^\\%\\:]",ie,se),"g"),NOT_HOST:new RegExp(e("[^\\%\\[\\]\\:]",ie,se),"g"),NOT_PATH:new RegExp(e("[^\\%\\/\\:\\@]",ie,se),"g"),NOT_PATH_NOSCHEME:new RegExp(e("[^\\%\\/\\@]",ie,se),"g"),NOT_QUERY:new RegExp(e("[^\\%]",ie,se,"[\\:\\@\\/\\?]",fe),"g"),NOT_FRAGMENT:new RegExp(e("[^\\%]",ie,se,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(e("[^]",ie,se),"g"),UNRESERVED:new RegExp(ie,"g"),OTHER_CHARS:new RegExp(e("[^\\%]",ie,ve),"g"),PCT_ENCODED:new RegExp(le,"g"),IPV4ADDRESS:new RegExp("^("+ze+")$"),IPV6ADDRESS:new RegExp("^\\[?("+mt+")"+r(r("\\%25|\\%(?!"+B+"{2})")+"("+cr+")")+"?\\]?$")}}var l=i(!1),u=i(!0),p=(function(){function b(m,E){var P=[],O=!0,B=!1,K=void 0;try{for(var ae=m[Symbol.iterator](),le;!(O=(le=ae.next()).done)&&(P.push(le.value),!(E&&P.length===E));O=!0);}catch(Se){B=!0,K=Se}finally{try{!O&&ae.return&&ae.return()}finally{if(B)throw K}}return P}return function(m,E){if(Array.isArray(m))return m;if(Symbol.iterator in Object(m))return b(m,E);throw new TypeError("Invalid attempt to destructure non-iterable instance")}})(),h=function(b){if(Array.isArray(b)){for(var m=0,E=Array(b.length);m<b.length;m++)E[m]=b[m];return E}else return Array.from(b)},f=2147483647,d=36,g=1,v=26,y=38,_=700,R=72,S=128,w="-",x=/^xn--/,T=/[^\0-\x7E]/,N=/[\x2E\u3002\uFF0E\uFF61]/g,L={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},I=d-g,F=Math.floor,k=String.fromCharCode;function j(b){throw new RangeError(L[b])}function $(b,m){for(var E=[],P=b.length;P--;)E[P]=m(b[P]);return E}function A(b,m){var E=b.split("@"),P="";E.length>1&&(P=E[0]+"@",b=E[1]),b=b.replace(N,".");var O=b.split("."),B=$(O,m).join(".");return P+B}function M(b){for(var m=[],E=0,P=b.length;E<P;){var O=b.charCodeAt(E++);if(O>=55296&&O<=56319&&E<P){var B=b.charCodeAt(E++);(B&64512)==56320?m.push(((O&1023)<<10)+(B&1023)+65536):(m.push(O),E--)}else m.push(O)}return m}var ee=function(m){return String.fromCodePoint.apply(String,h(m))},W=function(m){return m-48<10?m-22:m-65<26?m-65:m-97<26?m-97:d},Y=function(m,E){return m+22+75*(m<26)-((E!=0)<<5)},Q=function(m,E,P){var O=0;for(m=P?F(m/_):m>>1,m+=F(m/E);m>I*v>>1;O+=d)m=F(m/I);return F(O+(I+1)*m/(m+y))},z=function(m){var E=[],P=m.length,O=0,B=S,K=R,ae=m.lastIndexOf(w);ae<0&&(ae=0);for(var le=0;le<ae;++le)m.charCodeAt(le)>=128&&j("not-basic"),E.push(m.charCodeAt(le));for(var Se=ae>0?ae+1:0;Se<P;){for(var se=O,ve=1,xe=d;;xe+=d){Se>=P&&j("invalid-input");var fe=W(m.charCodeAt(Se++));(fe>=d||fe>F((f-O)/ve))&&j("overflow"),O+=fe*ve;var ie=xe<=K?g:xe>=K+v?v:xe-K;if(fe<ie)break;var ge=d-ie;ve>F(f/ge)&&j("overflow"),ve*=ge}var de=E.length+1;K=Q(O-se,de,se==0),F(O/de)>f-B&&j("overflow"),B+=F(O/de),O%=de,E.splice(O++,0,B)}return String.fromCodePoint.apply(String,E)},he=function(m){var E=[];m=M(m);var P=m.length,O=S,B=0,K=R,ae=!0,le=!1,Se=void 0;try{for(var se=m[Symbol.iterator](),ve;!(ae=(ve=se.next()).done);ae=!0){var xe=ve.value;xe<128&&E.push(k(xe))}}catch(Mt){le=!0,Se=Mt}finally{try{!ae&&se.return&&se.return()}finally{if(le)throw Se}}var fe=E.length,ie=fe;for(fe&&E.push(w);ie<P;){var ge=f,de=!0,jt=!1,Be=void 0;try{for(var ze=m[Symbol.iterator](),pe;!(de=(pe=ze.next()).done);de=!0){var Ve=pe.value;Ve>=O&&Ve<ge&&(ge=Ve)}}catch(Mt){jt=!0,Be=Mt}finally{try{!de&&ze.return&&ze.return()}finally{if(jt)throw Be}}var Ze=ie+1;ge-O>F((f-B)/Ze)&&j("overflow"),B+=(ge-O)*Ze,O=ge;var it=!0,Ft=!1,ft=void 0;try{for(var wr=m[Symbol.iterator](),Br;!(it=(Br=wr.next()).done);it=!0){var Vr=Br.value;if(Vr<O&&++B>f&&j("overflow"),Vr==O){for(var or=B,ir=d;;ir+=d){var mt=ir<=K?g:ir>=K+v?v:ir-K;if(or<mt)break;var cr=or-mt,qs=d-mt;E.push(k(Y(mt+cr%qs,0))),or=F(cr/qs)}E.push(k(Y(or,0))),K=Q(B,Ze,ie==fe),B=0,++ie}}}catch(Mt){Ft=!0,ft=Mt}finally{try{!it&&wr.return&&wr.return()}finally{if(Ft)throw ft}}++B,++O}return E.join("")},Oe=function(m){return A(m,function(E){return x.test(E)?z(E.slice(4).toLowerCase()):E})},Ae=function(m){return A(m,function(E){return T.test(E)?"xn--"+he(E):E})},oe={version:"2.1.0",ucs2:{decode:M,encode:ee},decode:z,encode:he,toASCII:Ae,toUnicode:Oe},be={};function Re(b){var m=b.charCodeAt(0),E=void 0;return m<16?E="%0"+m.toString(16).toUpperCase():m<128?E="%"+m.toString(16).toUpperCase():m<2048?E="%"+(m>>6|192).toString(16).toUpperCase()+"%"+(m&63|128).toString(16).toUpperCase():E="%"+(m>>12|224).toString(16).toUpperCase()+"%"+(m>>6&63|128).toString(16).toUpperCase()+"%"+(m&63|128).toString(16).toUpperCase(),E}function De(b){for(var m="",E=0,P=b.length;E<P;){var O=parseInt(b.substr(E+1,2),16);if(O<128)m+=String.fromCharCode(O),E+=3;else if(O>=194&&O<224){if(P-E>=6){var B=parseInt(b.substr(E+4,2),16);m+=String.fromCharCode((O&31)<<6|B&63)}else m+=b.substr(E,6);E+=6}else if(O>=224){if(P-E>=9){var K=parseInt(b.substr(E+4,2),16),ae=parseInt(b.substr(E+7,2),16);m+=String.fromCharCode((O&15)<<12|(K&63)<<6|ae&63)}else m+=b.substr(E,9);E+=9}else m+=b.substr(E,3),E+=3}return m}function St(b,m){function E(P){var O=De(P);return O.match(m.UNRESERVED)?O:P}return b.scheme&&(b.scheme=String(b.scheme).replace(m.PCT_ENCODED,E).toLowerCase().replace(m.NOT_SCHEME,"")),b.userinfo!==void 0&&(b.userinfo=String(b.userinfo).replace(m.PCT_ENCODED,E).replace(m.NOT_USERINFO,Re).replace(m.PCT_ENCODED,t)),b.host!==void 0&&(b.host=String(b.host).replace(m.PCT_ENCODED,E).toLowerCase().replace(m.NOT_HOST,Re).replace(m.PCT_ENCODED,t)),b.path!==void 0&&(b.path=String(b.path).replace(m.PCT_ENCODED,E).replace(b.scheme?m.NOT_PATH:m.NOT_PATH_NOSCHEME,Re).replace(m.PCT_ENCODED,t)),b.query!==void 0&&(b.query=String(b.query).replace(m.PCT_ENCODED,E).replace(m.NOT_QUERY,Re).replace(m.PCT_ENCODED,t)),b.fragment!==void 0&&(b.fragment=String(b.fragment).replace(m.PCT_ENCODED,E).replace(m.NOT_FRAGMENT,Re).replace(m.PCT_ENCODED,t)),b}function pt(b){return b.replace(/^0*(.*)/,"$1")||"0"}function Ee(b,m){var E=b.match(m.IPV4ADDRESS)||[],P=p(E,2),O=P[1];return O?O.split(".").map(pt).join("."):b}function ye(b,m){var E=b.match(m.IPV6ADDRESS)||[],P=p(E,3),O=P[1],B=P[2];if(O){for(var K=O.toLowerCase().split("::").reverse(),ae=p(K,2),le=ae[0],Se=ae[1],se=Se?Se.split(":").map(pt):[],ve=le.split(":").map(pt),xe=m.IPV4ADDRESS.test(ve[ve.length-1]),fe=xe?7:8,ie=ve.length-fe,ge=Array(fe),de=0;de<fe;++de)ge[de]=se[de]||ve[ie+de]||"";xe&&(ge[fe-1]=Ee(ge[fe-1],m));var jt=ge.reduce(function(Ze,it,Ft){if(!it||it==="0"){var ft=Ze[Ze.length-1];ft&&ft.index+ft.length===Ft?ft.length++:Ze.push({index:Ft,length:1})}return Ze},[]),Be=jt.sort(function(Ze,it){return it.length-Ze.length})[0],ze=void 0;if(Be&&Be.length>1){var pe=ge.slice(0,Be.index),Ve=ge.slice(Be.index+Be.length);ze=pe.join(":")+"::"+Ve.join(":")}else ze=ge.join(":");return B&&(ze+="%"+B),ze}else return b}var Ct=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Ie="".match(/(){0}/)[1]===void 0;function ce(b){var m=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},E={},P=m.iri!==!1?u:l;m.reference==="suffix"&&(b=(m.scheme?m.scheme+":":"")+"//"+b);var O=b.match(Ct);if(O){Ie?(E.scheme=O[1],E.userinfo=O[3],E.host=O[4],E.port=parseInt(O[5],10),E.path=O[6]||"",E.query=O[7],E.fragment=O[8],isNaN(E.port)&&(E.port=O[5])):(E.scheme=O[1]||void 0,E.userinfo=b.indexOf("@")!==-1?O[3]:void 0,E.host=b.indexOf("//")!==-1?O[4]:void 0,E.port=parseInt(O[5],10),E.path=O[6]||"",E.query=b.indexOf("?")!==-1?O[7]:void 0,E.fragment=b.indexOf("#")!==-1?O[8]:void 0,isNaN(E.port)&&(E.port=b.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?O[4]:void 0)),E.host&&(E.host=ye(Ee(E.host,P),P)),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",m.reference&&m.reference!=="suffix"&&m.reference!==E.reference&&(E.error=E.error||"URI is not a "+m.reference+" reference.");var B=be[(m.scheme||E.scheme||"").toLowerCase()];if(!m.unicodeSupport&&(!B||!B.unicodeSupport)){if(E.host&&(m.domainHost||B&&B.domainHost))try{E.host=oe.toASCII(E.host.replace(P.PCT_ENCODED,De).toLowerCase())}catch(K){E.error=E.error||"Host's domain name can not be converted to ASCII via punycode: "+K}St(E,l)}else St(E,P);B&&B.parse&&B.parse(E,m)}else E.error=E.error||"URI can not be parsed.";return E}function xt(b,m){var E=m.iri!==!1?u:l,P=[];return b.userinfo!==void 0&&(P.push(b.userinfo),P.push("@")),b.host!==void 0&&P.push(ye(Ee(String(b.host),E),E).replace(E.IPV6ADDRESS,function(O,B,K){return"["+B+(K?"%25"+K:"")+"]"})),(typeof b.port=="number"||typeof b.port=="string")&&(P.push(":"),P.push(String(b.port))),P.length?P.join(""):void 0}var ht=/^\.\.?\//,kt=/^\/\.(\/|$)/,Lt=/^\/\.\.(\/|$)/,we=/^\/?(?:.|\n)*?(?=\/|$)/;function He(b){for(var m=[];b.length;)if(b.match(ht))b=b.replace(ht,"");else if(b.match(kt))b=b.replace(kt,"/");else if(b.match(Lt))b=b.replace(Lt,"/"),m.pop();else if(b==="."||b==="..")b="";else{var E=b.match(we);if(E){var P=E[0];b=b.slice(P.length),m.push(P)}else throw new Error("Unexpected dot segment condition")}return m.join("")}function je(b){var m=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},E=m.iri?u:l,P=[],O=be[(m.scheme||b.scheme||"").toLowerCase()];if(O&&O.serialize&&O.serialize(b,m),b.host&&!E.IPV6ADDRESS.test(b.host)){if(m.domainHost||O&&O.domainHost)try{b.host=m.iri?oe.toUnicode(b.host):oe.toASCII(b.host.replace(E.PCT_ENCODED,De).toLowerCase())}catch(ae){b.error=b.error||"Host's domain name can not be converted to "+(m.iri?"Unicode":"ASCII")+" via punycode: "+ae}}St(b,E),m.reference!=="suffix"&&b.scheme&&(P.push(b.scheme),P.push(":"));var B=xt(b,m);if(B!==void 0&&(m.reference!=="suffix"&&P.push("//"),P.push(B),b.path&&b.path.charAt(0)!=="/"&&P.push("/")),b.path!==void 0){var K=b.path;!m.absolutePath&&(!O||!O.absolutePath)&&(K=He(K)),B===void 0&&(K=K.replace(/^\/\//,"/%2F")),P.push(K)}return b.query!==void 0&&(P.push("?"),P.push(b.query)),b.fragment!==void 0&&(P.push("#"),P.push(b.fragment)),P.join("")}function Ce(b,m){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},P=arguments[3],O={};return P||(b=ce(je(b,E),E),m=ce(je(m,E),E)),E=E||{},!E.tolerant&&m.scheme?(O.scheme=m.scheme,O.userinfo=m.userinfo,O.host=m.host,O.port=m.port,O.path=He(m.path||""),O.query=m.query):(m.userinfo!==void 0||m.host!==void 0||m.port!==void 0?(O.userinfo=m.userinfo,O.host=m.host,O.port=m.port,O.path=He(m.path||""),O.query=m.query):(m.path?(m.path.charAt(0)==="/"?O.path=He(m.path):((b.userinfo!==void 0||b.host!==void 0||b.port!==void 0)&&!b.path?O.path="/"+m.path:b.path?O.path=b.path.slice(0,b.path.lastIndexOf("/")+1)+m.path:O.path=m.path,O.path=He(O.path)),O.query=m.query):(O.path=b.path,m.query!==void 0?O.query=m.query:O.query=b.query),O.userinfo=b.userinfo,O.host=b.host,O.port=b.port),O.scheme=b.scheme),O.fragment=m.fragment,O}function nt(b,m,E){var P=o({scheme:"null"},E);return je(Ce(ce(b,P),ce(m,P),P,!0),P)}function qe(b,m){return typeof b=="string"?b=je(ce(b,m),m):a(b)==="object"&&(b=ce(je(b,m),m)),b}function qr(b,m,E){return typeof b=="string"?b=je(ce(b,E),E):a(b)==="object"&&(b=je(b,E)),typeof m=="string"?m=je(ce(m,E),E):a(m)==="object"&&(m=je(m,E)),b===m}function Ms(b,m){return b&&b.toString().replace(!m||!m.iri?l.ESCAPE:u.ESCAPE,Re)}function et(b,m){return b&&b.toString().replace(!m||!m.iri?l.PCT_ENCODED:u.PCT_ENCODED,De)}var Rr={scheme:"http",domainHost:!0,parse:function(m,E){return m.host||(m.error=m.error||"HTTP URIs must have a host."),m},serialize:function(m,E){var P=String(m.scheme).toLowerCase()==="https";return(m.port===(P?443:80)||m.port==="")&&(m.port=void 0),m.path||(m.path="/"),m}},on={scheme:"https",domainHost:Rr.domainHost,parse:Rr.parse,serialize:Rr.serialize};function cn(b){return typeof b.secure=="boolean"?b.secure:String(b.scheme).toLowerCase()==="wss"}var Tr={scheme:"ws",domainHost:!0,parse:function(m,E){var P=m;return P.secure=cn(P),P.resourceName=(P.path||"/")+(P.query?"?"+P.query:""),P.path=void 0,P.query=void 0,P},serialize:function(m,E){if((m.port===(cn(m)?443:80)||m.port==="")&&(m.port=void 0),typeof m.secure=="boolean"&&(m.scheme=m.secure?"wss":"ws",m.secure=void 0),m.resourceName){var P=m.resourceName.split("?"),O=p(P,2),B=O[0],K=O[1];m.path=B&&B!=="/"?B:void 0,m.query=K,m.resourceName=void 0}return m.fragment=void 0,m}},ln={scheme:"wss",domainHost:Tr.domainHost,parse:Tr.parse,serialize:Tr.serialize},Tl={},wl=!0,un="[A-Za-z0-9\\-\\.\\_\\~"+(wl?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",ot="[0-9A-Fa-f]",Pl=r(r("%[EFef]"+ot+"%"+ot+ot+"%"+ot+ot)+"|"+r("%[89A-Fa-f]"+ot+"%"+ot+ot)+"|"+r("%"+ot+ot)),Ol="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",Il="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",$l=e(Il,'[\\"\\\\]'),Nl="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",Al=new RegExp(un,"g"),nr=new RegExp(Pl,"g"),Dl=new RegExp(e("[^]",Ol,"[\\.]",'[\\"]',$l),"g"),dn=new RegExp(e("[^]",un,Nl),"g"),Cl=dn;function Us(b){var m=De(b);return m.match(Al)?m:b}var pn={scheme:"mailto",parse:function(m,E){var P=m,O=P.to=P.path?P.path.split(","):[];if(P.path=void 0,P.query){for(var B=!1,K={},ae=P.query.split("&"),le=0,Se=ae.length;le<Se;++le){var se=ae[le].split("=");switch(se[0]){case"to":for(var ve=se[1].split(","),xe=0,fe=ve.length;xe<fe;++xe)O.push(ve[xe]);break;case"subject":P.subject=et(se[1],E);break;case"body":P.body=et(se[1],E);break;default:B=!0,K[et(se[0],E)]=et(se[1],E);break}}B&&(P.headers=K)}P.query=void 0;for(var ie=0,ge=O.length;ie<ge;++ie){var de=O[ie].split("@");if(de[0]=et(de[0]),E.unicodeSupport)de[1]=et(de[1],E).toLowerCase();else try{de[1]=oe.toASCII(et(de[1],E).toLowerCase())}catch(jt){P.error=P.error||"Email address's domain name can not be converted to ASCII via punycode: "+jt}O[ie]=de.join("@")}return P},serialize:function(m,E){var P=m,O=n(m.to);if(O){for(var B=0,K=O.length;B<K;++B){var ae=String(O[B]),le=ae.lastIndexOf("@"),Se=ae.slice(0,le).replace(nr,Us).replace(nr,t).replace(Dl,Re),se=ae.slice(le+1);try{se=E.iri?oe.toUnicode(se):oe.toASCII(et(se,E).toLowerCase())}catch(ie){P.error=P.error||"Email address's domain name can not be converted to "+(E.iri?"Unicode":"ASCII")+" via punycode: "+ie}O[B]=Se+"@"+se}P.path=O.join(",")}var ve=m.headers=m.headers||{};m.subject&&(ve.subject=m.subject),m.body&&(ve.body=m.body);var xe=[];for(var fe in ve)ve[fe]!==Tl[fe]&&xe.push(fe.replace(nr,Us).replace(nr,t).replace(dn,Re)+"="+ve[fe].replace(nr,Us).replace(nr,t).replace(Cl,Re));return xe.length&&(P.query=xe.join("&")),P}},kl=/^([^\:]+)\:(.*)/,hn={scheme:"urn",parse:function(m,E){var P=m.path&&m.path.match(kl),O=m;if(P){var B=E.scheme||O.scheme||"urn",K=P[1].toLowerCase(),ae=P[2],le=B+":"+(E.nid||K),Se=be[le];O.nid=K,O.nss=ae,O.path=void 0,Se&&(O=Se.parse(O,E))}else O.error=O.error||"URN can not be parsed.";return O},serialize:function(m,E){var P=E.scheme||m.scheme||"urn",O=m.nid,B=P+":"+(E.nid||O),K=be[B];K&&(m=K.serialize(m,E));var ae=m,le=m.nss;return ae.path=(O||E.nid)+":"+le,ae}},Ll=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,fn={scheme:"urn:uuid",parse:function(m,E){var P=m;return P.uuid=P.nss,P.nss=void 0,!E.tolerant&&(!P.uuid||!P.uuid.match(Ll))&&(P.error=P.error||"UUID is not valid."),P},serialize:function(m,E){var P=m;return P.nss=(m.uuid||"").toLowerCase(),P}};be[Rr.scheme]=Rr,be[on.scheme]=on,be[Tr.scheme]=Tr,be[ln.scheme]=ln,be[pn.scheme]=pn,be[hn.scheme]=hn,be[fn.scheme]=fn,s.SCHEMES=be,s.pctEncChar=Re,s.pctDecChars=De,s.parse=ce,s.removeDotSegments=He,s.serialize=je,s.resolveComponents=Ce,s.resolve=nt,s.normalize=qe,s.equal=qr,s.escapeComponent=Ms,s.unescapeComponent=et,Object.defineProperty(s,"__esModule",{value:!0})}))});var is=H((fm,Qn)=>{"use strict";Qn.exports=function s(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var a,t,n;if(Array.isArray(e)){if(a=e.length,a!=r.length)return!1;for(t=a;t--!==0;)if(!s(e[t],r[t]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(n=Object.keys(e),a=n.length,a!==Object.keys(r).length)return!1;for(t=a;t--!==0;)if(!Object.prototype.hasOwnProperty.call(r,n[t]))return!1;for(t=a;t--!==0;){var o=n[t];if(!s(e[o],r[o]))return!1}return!0}return e!==e&&r!==r}});var Xn=H((mm,Wn)=>{"use strict";Wn.exports=function(e){for(var r=0,a=e.length,t=0,n;t<a;)r++,n=e.charCodeAt(t++),n>=55296&&n<=56319&&t<a&&(n=e.charCodeAt(t),(n&64512)==56320&&t++);return r}});var rr=H((vm,Yn)=>{"use strict";Yn.exports={copy:Wd,checkDataType:ma,checkDataTypes:Xd,coerceToTypes:Kd,toHash:ga,getProperty:ya,escapeQuotes:_a,equal:is(),ucs2length:Xn(),varOccurences:ep,varReplace:tp,schemaHasRules:rp,schemaHasRulesExcept:sp,schemaUnknownRules:ap,toQuotedString:va,getPathExpr:np,getPath:op,getData:lp,unescapeFragment:up,unescapeJsonPointer:Ea,escapeFragment:dp,escapeJsonPointer:ba};function Wd(s,e){e=e||{};for(var r in s)e[r]=s[r];return e}function ma(s,e,r,a){var t=a?" !== ":" === ",n=a?" || ":" && ",o=a?"!":"",i=a?"":"!";switch(s){case"null":return e+t+"null";case"array":return o+"Array.isArray("+e+")";case"object":return"("+o+e+n+"typeof "+e+t+'"object"'+n+i+"Array.isArray("+e+"))";case"integer":return"(typeof "+e+t+'"number"'+n+i+"("+e+" % 1)"+n+e+t+e+(r?n+o+"isFinite("+e+")":"")+")";case"number":return"(typeof "+e+t+'"'+s+'"'+(r?n+o+"isFinite("+e+")":"")+")";default:return"typeof "+e+t+'"'+s+'"'}}function Xd(s,e,r){switch(s.length){case 1:return ma(s[0],e,r,!0);default:var a="",t=ga(s);t.array&&t.object&&(a=t.null?"(":"(!"+e+" || ",a+="typeof "+e+' !== "object")',delete t.null,delete t.array,delete t.object),t.number&&delete t.integer;for(var n in t)a+=(a?" && ":"")+ma(n,e,r,!0);return a}}var Kn=ga(["string","number","integer","boolean","null"]);function Kd(s,e){if(Array.isArray(e)){for(var r=[],a=0;a<e.length;a++){var t=e[a];(Kn[t]||s==="array"&&t==="array")&&(r[r.length]=t)}if(r.length)return r}else{if(Kn[e])return[e];if(s==="array"&&e==="array")return["array"]}}function ga(s){for(var e={},r=0;r<s.length;r++)e[s[r]]=!0;return e}var Jd=/^[a-z$_][a-z$_0-9]*$/i,Yd=/'|\\/g;function ya(s){return typeof s=="number"?"["+s+"]":Jd.test(s)?"."+s:"['"+_a(s)+"']"}function _a(s){return s.replace(Yd,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function ep(s,e){e+="[^0-9]";var r=s.match(new RegExp(e,"g"));return r?r.length:0}function tp(s,e,r){return e+="([^0-9])",r=r.replace(/\$/g,"$$$$"),s.replace(new RegExp(e,"g"),r+"$1")}function rp(s,e){if(typeof s=="boolean")return!s;for(var r in s)if(e[r])return!0}function sp(s,e,r){if(typeof s=="boolean")return!s&&r!="not";for(var a in s)if(a!=r&&e[a])return!0}function ap(s,e){if(typeof s!="boolean"){for(var r in s)if(!e[r])return r}}function va(s){return"'"+_a(s)+"'"}function np(s,e,r,a){var t=r?"'/' + "+e+(a?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):a?"'[' + "+e+" + ']'":"'[\\'' + "+e+" + '\\']'";return Jn(s,t)}function op(s,e,r){var a=va(r?"/"+ba(e):ya(e));return Jn(s,a)}var ip=/^\/(?:[^~]|~0|~1)*$/,cp=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function lp(s,e,r){var a,t,n,o;if(s==="")return"rootData";if(s[0]=="/"){if(!ip.test(s))throw new Error("Invalid JSON-pointer: "+s);t=s,n="rootData"}else{if(o=s.match(cp),!o)throw new Error("Invalid JSON-pointer: "+s);if(a=+o[1],t=o[2],t=="#"){if(a>=e)throw new Error("Cannot access property/index "+a+" levels up, current level is "+e);return r[e-a]}if(a>e)throw new Error("Cannot access data "+a+" levels up, current level is "+e);if(n="data"+(e-a||""),!t)return n}for(var i=n,l=t.split("/"),u=0;u<l.length;u++){var p=l[u];p&&(n+=ya(Ea(p)),i+=" && "+n)}return i}function Jn(s,e){return s=='""'?e:(s+" + "+e).replace(/([^\\])' \+ '/g,"$1")}function up(s){return Ea(decodeURIComponent(s))}function dp(s){return encodeURIComponent(ba(s))}function ba(s){return s.replace(/~/g,"~0").replace(/\//g,"~1")}function Ea(s){return s.replace(/~1/g,"/").replace(/~0/g,"~")}});var Sa=H((gm,eo)=>{"use strict";var pp=rr();eo.exports=hp;function hp(s){pp.copy(s,this)}});var ro=H((ym,to)=>{"use strict";var It=to.exports=function(s,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var a=typeof r=="function"?r:r.pre||function(){},t=r.post||function(){};cs(e,a,t,s,"",s)};It.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0};It.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};It.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};It.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 cs(s,e,r,a,t,n,o,i,l,u){if(a&&typeof a=="object"&&!Array.isArray(a)){e(a,t,n,o,i,l,u);for(var p in a){var h=a[p];if(Array.isArray(h)){if(p in It.arrayKeywords)for(var f=0;f<h.length;f++)cs(s,e,r,h[f],t+"/"+p+"/"+f,n,t,p,a,f)}else if(p in It.propsKeywords){if(h&&typeof h=="object")for(var d in h)cs(s,e,r,h[d],t+"/"+p+"/"+fp(d),n,t,p,a,d)}else(p in It.keywords||s.allKeys&&!(p in It.skipKeywords))&&cs(s,e,r,h,t+"/"+p,n,t,p,a)}r(a,t,n,o,i,l,u)}}function fp(s){return s.replace(/~/g,"~0").replace(/\//g,"~1")}});var fs=H((_m,oo)=>{"use strict";var Mr=Gn(),so=is(),ps=rr(),ls=Sa(),mp=ro();oo.exports=Nt;Nt.normalizeId=$t;Nt.fullPath=us;Nt.url=ds;Nt.ids=bp;Nt.inlineRef=xa;Nt.schema=hs;function Nt(s,e,r){var a=this._refs[r];if(typeof a=="string")if(this._refs[a])a=this._refs[a];else return Nt.call(this,s,e,a);if(a=a||this._schemas[r],a instanceof ls)return xa(a.schema,this._opts.inlineRefs)?a.schema:a.validate||this._compile(a);var t=hs.call(this,e,r),n,o,i;return t&&(n=t.schema,e=t.root,i=t.baseId),n instanceof ls?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 hs(s,e){var r=Mr.parse(e),a=no(r),t=us(this._getId(s.schema));if(Object.keys(s.schema).length===0||a!==t){var n=$t(a),o=this._refs[n];if(typeof o=="string")return vp.call(this,s,o,r);if(o instanceof ls)o.validate||this._compile(o),s=o;else if(o=this._schemas[n],o instanceof ls){if(o.validate||this._compile(o),n==$t(e))return{schema:o,root:s,baseId:t};s=o}else return;if(!s.schema)return;t=us(this._getId(s.schema))}return ao.call(this,r,t,s.schema,s)}function vp(s,e,r){var a=hs.call(this,s,e);if(a){var t=a.schema,n=a.baseId;s=a.root;var o=this._getId(t);return o&&(n=ds(n,o)),ao.call(this,r,n,t,s)}}var gp=ps.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function ao(s,e,r,a){if(s.fragment=s.fragment||"",s.fragment.slice(0,1)=="/"){for(var t=s.fragment.split("/"),n=1;n<t.length;n++){var o=t[n];if(o){if(o=ps.unescapeFragment(o),r=r[o],r===void 0)break;var i;if(!gp[o]&&(i=this._getId(r),i&&(e=ds(e,i)),r.$ref)){var l=ds(e,r.$ref),u=hs.call(this,a,l);u&&(r=u.schema,a=u.root,e=u.baseId)}}}if(r!==void 0&&r!==a.schema)return{schema:r,root:a,baseId:e}}}var yp=ps.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function xa(s,e){if(e===!1)return!1;if(e===void 0||e===!0)return Ra(s);if(e)return Ta(s)<=e}function Ra(s){var e;if(Array.isArray(s)){for(var r=0;r<s.length;r++)if(e=s[r],typeof e=="object"&&!Ra(e))return!1}else for(var a in s)if(a=="$ref"||(e=s[a],typeof e=="object"&&!Ra(e)))return!1;return!0}function Ta(s){var e=0,r;if(Array.isArray(s)){for(var a=0;a<s.length;a++)if(r=s[a],typeof r=="object"&&(e+=Ta(r)),e==1/0)return 1/0}else for(var t in s){if(t=="$ref")return 1/0;if(yp[t])e++;else if(r=s[t],typeof r=="object"&&(e+=Ta(r)+1),e==1/0)return 1/0}return e}function us(s,e){e!==!1&&(s=$t(s));var r=Mr.parse(s);return no(r)}function no(s){return Mr.serialize(s).split("#")[0]+"#"}var _p=/#\/?$/;function $t(s){return s?s.replace(_p,""):""}function ds(s,e){return e=$t(e),Mr.resolve(s,e)}function bp(s){var e=$t(this._getId(s)),r={"":e},a={"":us(e,!1)},t={},n=this;return mp(s,{allKeys:!0},function(o,i,l,u,p,h,f){if(i!==""){var d=n._getId(o),g=r[u],v=a[u]+"/"+p;if(f!==void 0&&(v+="/"+(typeof f=="number"?f:ps.escapeFragment(f))),typeof d=="string"){d=g=$t(g?Mr.resolve(g,d):d);var y=n._refs[d];if(typeof y=="string"&&(y=n._refs[y]),y&&y.schema){if(!so(o,y.schema))throw new Error('id "'+d+'" resolves to more than one schema')}else if(d!=$t(v))if(d[0]=="#"){if(t[d]&&!so(o,t[d]))throw new Error('id "'+d+'" resolves to more than one schema');t[d]=o}else n._refs[d]=v}r[i]=g,a[i]=v}}),t}});var ms=H((bm,co)=>{"use strict";var wa=fs();co.exports={Validation:io(Ep),MissingRef:io(Pa)};function Ep(s){this.message="validation failed",this.errors=s,this.ajv=this.validation=!0}Pa.message=function(s,e){return"can't resolve reference "+e+" from id "+s};function Pa(s,e,r){this.message=r||Pa.message(s,e),this.missingRef=wa.url(s,e),this.missingSchema=wa.normalizeId(wa.fullPath(this.missingRef))}function io(s){return s.prototype=Object.create(Error.prototype),s.prototype.constructor=s,s}});var Oa=H((Em,lo)=>{"use strict";lo.exports=function(s,e){e||(e={}),typeof e=="function"&&(e={cmp:e});var r=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]},p={key:l,value:o[l]};return n(u,p)}}})(e.cmp),t=[];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<o.length;i++)i&&(l+=","),l+=n(o[i])||"null";return l+"]"}if(o===null)return"null";if(t.indexOf(o)!==-1){if(r)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var u=t.push(o)-1,p=Object.keys(o).sort(a&&a(o));for(l="",i=0;i<p.length;i++){var h=p[i],f=n(o[h]);f&&(l&&(l+=","),l+=JSON.stringify(h)+":"+f)}return t.splice(u,1),"{"+l+"}"}})(s)}});var Ia=H((Sm,uo)=>{"use strict";uo.exports=function(e,r,a){var t="",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&&(t+=" var validate = ",n&&(e.async=!0,t+="async "),t+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",i&&(e.opts.sourceCode||e.opts.processCode)&&(t+=" "+("/*# sourceURL="+i+" */")+" ")),typeof e.schema=="boolean"||!(o||e.schema.$ref)){var r="false schema",p=e.level,h=e.dataLevel,f=e.schema[r],d=e.schemaPath+e.util.getProperty(r),g=e.errSchemaPath+"/"+r,x=!e.opts.allErrors,L,v="data"+(h||""),w="valid"+p;if(e.schema===!1){e.isTop?x=!0:t+=" var "+w+" = false; ";var y=y||[];y.push(t),t="",e.createErrors!==!1?(t+=" { keyword: '"+(L||"false schema")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(g)+" , params: {} ",e.opts.messages!==!1&&(t+=" , message: 'boolean schema is false' "),e.opts.verbose&&(t+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),t+=" } "):t+=" {} ";var _=t;t=y.pop(),!e.compositeRule&&x?e.async?t+=" throw new ValidationError(["+_+"]); ":t+=" validate.errors = ["+_+"]; return false; ":t+=" var err = "+_+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else e.isTop?n?t+=" return data; ":t+=" validate.errors = null; return true; ":t+=" var "+w+" = true; ";return e.isTop&&(t+=" }; return validate; "),t}if(e.isTop){var R=e.isTop,p=e.level=0,h=e.dataLevel=0,v="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 S="default is ignored in the schema root";if(e.opts.strictDefaults==="log")e.logger.warn(S);else throw new Error(S)}t+=" var vErrors = null; ",t+=" var errors = 0; ",t+=" if (rootData === undefined) rootData = data; "}else{var p=e.level,h=e.dataLevel,v="data"+(h||"");if(i&&(e.baseId=e.resolve.url(e.baseId,i)),n&&!e.async)throw new Error("async schema in sync schema");t+=" var errs_"+p+" = errors;"}var w="valid"+p,x=!e.opts.allErrors,T="",N="",L,I=e.schema.type,F=Array.isArray(I);if(I&&e.opts.nullable&&e.schema.nullable===!0&&(F?I.indexOf("null")==-1&&(I=I.concat("null")):I!="null"&&(I=[I,"null"],F=!0)),F&&I.length==1&&(I=I[0],F=!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&&(t+=" "+e.RULES.all.$comment.code(e,"$comment")),I){if(e.opts.coerceTypes)var k=e.util.coerceToTypes(e.opts.coerceTypes,I);var j=e.RULES.types[I];if(k||F||j===!0||j&&!we(j)){var d=e.schemaPath+".type",g=e.errSchemaPath+"/type",d=e.schemaPath+".type",g=e.errSchemaPath+"/type",$=F?"checkDataTypes":"checkDataType";if(t+=" if ("+e.util[$](I,v,e.opts.strictNumbers,!0)+") { ",k){var A="dataType"+p,M="coerced"+p;t+=" var "+A+" = typeof "+v+"; var "+M+" = undefined; ",e.opts.coerceTypes=="array"&&(t+=" if ("+A+" == 'object' && Array.isArray("+v+") && "+v+".length == 1) { "+v+" = "+v+"[0]; "+A+" = typeof "+v+"; if ("+e.util.checkDataType(e.schema.type,v,e.opts.strictNumbers)+") "+M+" = "+v+"; } "),t+=" if ("+M+" !== undefined) ; ";var ee=k;if(ee)for(var W,Y=-1,Q=ee.length-1;Y<Q;)W=ee[Y+=1],W=="string"?t+=" else if ("+A+" == 'number' || "+A+" == 'boolean') "+M+" = '' + "+v+"; else if ("+v+" === null) "+M+" = ''; ":W=="number"||W=="integer"?(t+=" else if ("+A+" == 'boolean' || "+v+" === null || ("+A+" == 'string' && "+v+" && "+v+" == +"+v+" ",W=="integer"&&(t+=" && !("+v+" % 1)"),t+=")) "+M+" = +"+v+"; "):W=="boolean"?t+=" else if ("+v+" === 'false' || "+v+" === 0 || "+v+" === null) "+M+" = false; else if ("+v+" === 'true' || "+v+" === 1) "+M+" = true; ":W=="null"?t+=" else if ("+v+" === '' || "+v+" === 0 || "+v+" === false) "+M+" = null; ":e.opts.coerceTypes=="array"&&W=="array"&&(t+=" else if ("+A+" == 'string' || "+A+" == 'number' || "+A+" == 'boolean' || "+v+" == null) "+M+" = ["+v+"]; ");t+=" else { ";var y=y||[];y.push(t),t="",e.createErrors!==!1?(t+=" { keyword: '"+(L||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(g)+" , params: { type: '",F?t+=""+I.join(","):t+=""+I,t+="' } ",e.opts.messages!==!1&&(t+=" , message: 'should be ",F?t+=""+I.join(","):t+=""+I,t+="' "),e.opts.verbose&&(t+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),t+=" } "):t+=" {} ";var _=t;t=y.pop(),!e.compositeRule&&x?e.async?t+=" throw new ValidationError(["+_+"]); ":t+=" validate.errors = ["+_+"]; return false; ":t+=" var err = "+_+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } if ("+M+" !== undefined) { ";var z=h?"data"+(h-1||""):"parentData",he=h?e.dataPathArr[h]:"parentDataProperty";t+=" "+v+" = "+M+"; ",h||(t+="if ("+z+" !== undefined)"),t+=" "+z+"["+he+"] = "+M+"; } "}else{var y=y||[];y.push(t),t="",e.createErrors!==!1?(t+=" { keyword: '"+(L||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(g)+" , params: { type: '",F?t+=""+I.join(","):t+=""+I,t+="' } ",e.opts.messages!==!1&&(t+=" , message: 'should be ",F?t+=""+I.join(","):t+=""+I,t+="' "),e.opts.verbose&&(t+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),t+=" } "):t+=" {} ";var _=t;t=y.pop(),!e.compositeRule&&x?e.async?t+=" throw new ValidationError(["+_+"]); ":t+=" validate.errors = ["+_+"]; return false; ":t+=" var err = "+_+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}t+=" } "}}if(e.schema.$ref&&!o)t+=" "+e.RULES.all.$ref.code(e,"$ref")+" ",x&&(t+=" } if (errors === ",R?t+="0":t+="errs_"+p,t+=") { ",N+="}");else{var Oe=e.RULES;if(Oe){for(var j,Ae=-1,oe=Oe.length-1;Ae<oe;)if(j=Oe[Ae+=1],we(j)){if(j.type&&(t+=" if ("+e.util.checkDataType(j.type,v,e.opts.strictNumbers)+") { "),e.opts.useDefaults){if(j.type=="object"&&e.schema.properties){var f=e.schema.properties,be=Object.keys(f),Re=be;if(Re)for(var De,St=-1,pt=Re.length-1;St<pt;){De=Re[St+=1];var Ee=f[De];if(Ee.default!==void 0){var ye=v+e.util.getProperty(De);if(e.compositeRule){if(e.opts.strictDefaults){var S="default is ignored for: "+ye;if(e.opts.strictDefaults==="log")e.logger.warn(S);else throw new Error(S)}}else t+=" if ("+ye+" === undefined ",e.opts.useDefaults=="empty"&&(t+=" || "+ye+" === null || "+ye+" === '' "),t+=" ) "+ye+" = ",e.opts.useDefaults=="shared"?t+=" "+e.useDefault(Ee.default)+" ":t+=" "+JSON.stringify(Ee.default)+" ",t+="; "}}}else if(j.type=="array"&&Array.isArray(e.schema.items)){var Ct=e.schema.items;if(Ct){for(var Ee,Y=-1,Ie=Ct.length-1;Y<Ie;)if(Ee=Ct[Y+=1],Ee.default!==void 0){var ye=v+"["+Y+"]";if(e.compositeRule){if(e.opts.strictDefaults){var S="default is ignored for: "+ye;if(e.opts.strictDefaults==="log")e.logger.warn(S);else throw new Error(S)}}else t+=" if ("+ye+" === undefined ",e.opts.useDefaults=="empty"&&(t+=" || "+ye+" === null || "+ye+" === '' "),t+=" ) "+ye+" = ",e.opts.useDefaults=="shared"?t+=" "+e.useDefault(Ee.default)+" ":t+=" "+JSON.stringify(Ee.default)+" ",t+="; "}}}}var ce=j.rules;if(ce){for(var xt,ht=-1,kt=ce.length-1;ht<kt;)if(xt=ce[ht+=1],He(xt)){var Lt=xt.code(e,xt.keyword,j.type);Lt&&(t+=" "+Lt+" ",x&&(T+="}"))}}if(x&&(t+=" "+T+" ",T=""),j.type&&(t+=" } ",I&&I===j.type&&!k)){t+=" else { ";var d=e.schemaPath+".type",g=e.errSchemaPath+"/type",y=y||[];y.push(t),t="",e.createErrors!==!1?(t+=" { keyword: '"+(L||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(g)+" , params: { type: '",F?t+=""+I.join(","):t+=""+I,t+="' } ",e.opts.messages!==!1&&(t+=" , message: 'should be ",F?t+=""+I.join(","):t+=""+I,t+="' "),e.opts.verbose&&(t+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),t+=" } "):t+=" {} ";var _=t;t=y.pop(),!e.compositeRule&&x?e.async?t+=" throw new ValidationError(["+_+"]); ":t+=" validate.errors = ["+_+"]; return false; ":t+=" var err = "+_+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } "}x&&(t+=" if (errors === ",R?t+="0":t+="errs_"+p,t+=") { ",N+="}")}}}x&&(t+=" "+N+" "),R?(n?(t+=" if (errors === 0) return data; ",t+=" else throw new ValidationError(vErrors); "):(t+=" validate.errors = vErrors; ",t+=" return errors === 0; "),t+=" }; return validate;"):t+=" var "+w+" = errors === errs_"+p+";";function we(Ce){for(var nt=Ce.rules,qe=0;qe<nt.length;qe++)if(He(nt[qe]))return!0}function He(Ce){return e.schema[Ce.keyword]!==void 0||Ce.implements&&je(Ce)}function je(Ce){for(var nt=Ce.implements,qe=0;qe<nt.length;qe++)if(e.schema[nt[qe]]!==void 0)return!0}return t}});var vo=H((xm,mo)=>{"use strict";var vs=fs(),ys=rr(),ho=ms(),Sp=Oa(),po=Ia(),xp=ys.ucs2length,Rp=is(),Tp=ho.Validation;mo.exports=$a;function $a(s,e,r,a){var t=this,n=this._opts,o=[void 0],i={},l=[],u={},p=[],h={},f=[];e=e||{schema:s,refVal:o,refs:i};var d=wp.call(this,s,e,a),g=this._compilations[d.index];if(d.compiling)return g.callValidate=S;var v=this._formats,y=this.RULES;try{var _=w(s,e,r,a);g.validate=_;var R=g.callValidate;return R&&(R.schema=_.schema,R.errors=null,R.refs=_.refs,R.refVal=_.refVal,R.root=_.root,R.$async=_.$async,n.sourceCode&&(R.source=_.source)),_}finally{Pp.call(this,s,e,a)}function S(){var $=g.validate,A=$.apply(this,arguments);return S.errors=$.errors,A}function w($,A,M,ee){var W=!A||A&&A.schema==$;if(A.schema!=e.schema)return $a.call(t,$,A,M,ee);var Y=$.$async===!0,Q=po({isTop:!0,schema:$,isRoot:W,baseId:ee,root:A,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:ho.MissingRef,RULES:y,validate:po,util:ys,resolve:vs,resolveRef:x,usePattern:F,useDefault:k,useCustomRule:j,opts:n,formats:v,logger:t.logger,self:t});Q=gs(o,$p)+gs(l,Op)+gs(p,Ip)+gs(f,Np)+Q,n.processCode&&(Q=n.processCode(Q,$));var z;try{var he=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",Q);z=he(t,y,v,e,o,p,f,Rp,xp,Tp),o[0]=z}catch(Oe){throw t.logger.error("Error compiling schema, function code:",Q),Oe}return z.schema=$,z.errors=null,z.refs=i,z.refVal=o,z.root=W?z:A,Y&&(z.$async=!0),n.sourceCode===!0&&(z.source={code:Q,patterns:l,defaults:p}),z}function x($,A,M){A=vs.url($,A);var ee=i[A],W,Y;if(ee!==void 0)return W=o[ee],Y="refVal["+ee+"]",I(W,Y);if(!M&&e.refs){var Q=e.refs[A];if(Q!==void 0)return W=e.refVal[Q],Y=T(A,W),I(W,Y)}Y=T(A);var z=vs.call(t,w,e,A);if(z===void 0){var he=r&&r[A];he&&(z=vs.inlineRef(he,n.inlineRefs)?he:$a.call(t,he,e,r,$))}if(z===void 0)N(A);else return L(A,z),I(z,Y)}function T($,A){var M=o.length;return o[M]=A,i[$]=M,"refVal"+M}function N($){delete i[$]}function L($,A){var M=i[$];o[M]=A}function I($,A){return typeof $=="object"||typeof $=="boolean"?{code:A,schema:$,inline:!0}:{code:A,$async:$&&!!$.$async}}function F($){var A=u[$];return A===void 0&&(A=u[$]=l.length,l[A]=$),"pattern"+A}function k($){switch(typeof $){case"boolean":case"number":return""+$;case"string":return ys.toQuotedString($);case"object":if($===null)return"null";var A=Sp($),M=h[A];return M===void 0&&(M=h[A]=p.length,p[M]=$),"default"+M}}function j($,A,M,ee){if(t._opts.validateSchema!==!1){var W=$.definition.dependencies;if(W&&!W.every(function(Re){return Object.prototype.hasOwnProperty.call(M,Re)}))throw new Error("parent schema must have all required keywords: "+W.join(","));var Y=$.definition.validateSchema;if(Y){var Q=Y(A);if(!Q){var z="keyword schema is invalid: "+t.errorsText(Y.errors);if(t._opts.validateSchema=="log")t.logger.error(z);else throw new Error(z)}}}var he=$.definition.compile,Oe=$.definition.inline,Ae=$.definition.macro,oe;if(he)oe=he.call(t,A,M,ee);else if(Ae)oe=Ae.call(t,A,M,ee),n.validateSchema!==!1&&t.validateSchema(oe,!0);else if(Oe)oe=Oe.call(t,ee,$.keyword,A,M);else if(oe=$.definition.validate,!oe)return;if(oe===void 0)throw new Error('custom keyword "'+$.keyword+'"failed to compile');var be=f.length;return f[be]=oe,{code:"customRule"+be,validate:oe}}}function wp(s,e,r){var a=fo.call(this,s,e,r);return a>=0?{index:a,compiling:!0}:(a=this._compilations.length,this._compilations[a]={schema:s,root:e,baseId:r},{index:a,compiling:!1})}function Pp(s,e,r){var a=fo.call(this,s,e,r);a>=0&&this._compilations.splice(a,1)}function fo(s,e,r){for(var a=0;a<this._compilations.length;a++){var t=this._compilations[a];if(t.schema==s&&t.root==e&&t.baseId==r)return a}return-1}function Op(s,e){return"var pattern"+s+" = new RegExp("+ys.toQuotedString(e[s])+");"}function Ip(s){return"var default"+s+" = defaults["+s+"];"}function $p(s,e){return e[s]===void 0?"":"var refVal"+s+" = refVal["+s+"];"}function Np(s){return"var customRule"+s+" = customRules["+s+"];"}function gs(s,e){if(!s.length)return"";for(var r="",a=0;a<s.length;a++)r+=e(a,s);return r}});var yo=H((Rm,go)=>{"use strict";var _s=go.exports=function(){this._cache={}};_s.prototype.put=function(e,r){this._cache[e]=r};_s.prototype.get=function(e){return this._cache[e]};_s.prototype.del=function(e){delete this._cache[e]};_s.prototype.clear=function(){this._cache={}}});var $o=H((Tm,Io)=>{"use strict";var Ap=rr(),Dp=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Cp=[0,31,28,31,30,31,30,31,31,30,31,30,31],kp=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,_o=/^(?=.{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,Lp=/^(?:[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,jp=/^(?:[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,bo=/^(?:(?:[^\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,Eo=/^(?:(?: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,So=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,xo=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Ro=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,To=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;Io.exports=bs;function bs(s){return s=s=="full"?"full":"fast",Ap.copy(bs[s])}bs.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":bo,url:Eo,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:_o,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:Oo,uuid:So,"json-pointer":xo,"json-pointer-uri-fragment":Ro,"relative-json-pointer":To};bs.full={date:wo,time:Po,"date-time":Up,uri:Bp,"uri-reference":jp,"uri-template":bo,url:Eo,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:_o,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:Oo,uuid:So,"json-pointer":xo,"json-pointer-uri-fragment":Ro,"relative-json-pointer":To};function Fp(s){return s%4===0&&(s%100!==0||s%400===0)}function wo(s){var e=s.match(Dp);if(!e)return!1;var r=+e[1],a=+e[2],t=+e[3];return a>=1&&a<=12&&t>=1&&t<=(a==2&&Fp(r)?29:Cp[a])}function Po(s,e){var r=s.match(kp);if(!r)return!1;var a=r[1],t=r[2],n=r[3],o=r[5];return(a<=23&&t<=59&&n<=59||a==23&&t==59&&n==60)&&(!e||o)}var Mp=/t|\s/i;function Up(s){var e=s.split(Mp);return e.length==2&&wo(e[0])&&Po(e[1],!0)}var qp=/\/|:/;function Bp(s){return qp.test(s)&&Lp.test(s)}var Vp=/[^\\]\\Z/;function Oo(s){if(Vp.test(s))return!1;try{return new RegExp(s),!0}catch{return!1}}});var Ao=H((wm,No)=>{"use strict";No.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,p="data"+(o||""),h="valid"+n,f,d;if(i=="#"||i=="#/")e.isRoot?(f=e.async,d="validate"):(f=e.root.schema.$async===!0,d="root.refVal[0]");else{var g=e.resolveRef(e.baseId,i,e.isRoot);if(g===void 0){var v=e.MissingRefError.message(e.baseId,i);if(e.opts.missingRefs=="fail"){e.logger.error(v);var y=y||[];y.push(t),t="",e.createErrors!==!1?(t+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { ref: '"+e.util.escapeQuotes(i)+"' } ",e.opts.messages!==!1&&(t+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(i)+"' "),e.opts.verbose&&(t+=" , schema: "+e.util.toQuotedString(i)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+p+" "),t+=" } "):t+=" {} ";var _=t;t=y.pop(),!e.compositeRule&&u?e.async?t+=" throw new ValidationError(["+_+"]); ":t+=" validate.errors = ["+_+"]; return false; ":t+=" var err = "+_+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u&&(t+=" if (false) { ")}else if(e.opts.missingRefs=="ignore")e.logger.warn(v),u&&(t+=" if (true) { ");else throw new e.MissingRefError(e.baseId,i,v)}else if(g.inline){var R=e.util.copy(e);R.level++;var S="valid"+R.level;R.schema=g.schema,R.schemaPath="",R.errSchemaPath=i;var w=e.validate(R).replace(/validate\.schema/g,g.code);t+=" "+w+" ",u&&(t+=" if ("+S+") { ")}else f=g.$async===!0||e.async&&g.$async!==!1,d=g.code}if(d){var y=y||[];y.push(t),t="",e.opts.passContext?t+=" "+d+".call(this, ":t+=" "+d+"( ",t+=" "+p+", (dataPath || '')",e.errorPath!='""'&&(t+=" + "+e.errorPath);var x=o?"data"+(o-1||""):"parentData",T=o?e.dataPathArr[o]:"parentDataProperty";t+=" , "+x+" , "+T+", rootData) ";var N=t;if(t=y.pop(),f){if(!e.async)throw new Error("async schema referenced by sync schema");u&&(t+=" var "+h+"; "),t+=" try { await "+N+"; ",u&&(t+=" "+h+" = true; "),t+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",u&&(t+=" "+h+" = false; "),t+=" } ",u&&(t+=" if ("+h+") { ")}else t+=" if (!"+N+") { if (vErrors === null) vErrors = "+d+".errors; else vErrors = vErrors.concat("+d+".errors); errors = vErrors.length; } ",u&&(t+=" else { ")}return t}});var Co=H((Pm,Do)=>{"use strict";Do.exports=function(e,r,a){var t=" ",n=e.schema[r],o=e.schemaPath+e.util.getProperty(r),i=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,u=e.util.copy(e),p="";u.level++;var h="valid"+u.level,f=u.baseId,d=!0,g=n;if(g)for(var v,y=-1,_=g.length-1;y<_;)v=g[y+=1],(e.opts.strictKeywords?typeof v=="object"&&Object.keys(v).length>0||v===!1:e.util.schemaHasRules(v,e.RULES.all))&&(d=!1,u.schema=v,u.schemaPath=o+"["+y+"]",u.errSchemaPath=i+"/"+y,t+=" "+e.validate(u)+" ",u.baseId=f,l&&(t+=" if ("+h+") { ",p+="}"));return l&&(d?t+=" if (true) { ":t+=" "+p.slice(0,-1)+" "),t}});var Lo=H((Om,ko)=>{"use strict";ko.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,p=!e.opts.allErrors,h="data"+(o||""),f="valid"+n,d="errs__"+n,g=e.util.copy(e),v="";g.level++;var y="valid"+g.level,_=i.every(function(L){return e.opts.strictKeywords?typeof L=="object"&&Object.keys(L).length>0||L===!1:e.util.schemaHasRules(L,e.RULES.all)});if(_){var R=g.baseId;t+=" var "+d+" = errors; var "+f+" = false; ";var S=e.compositeRule;e.compositeRule=g.compositeRule=!0;var w=i;if(w)for(var x,T=-1,N=w.length-1;T<N;)x=w[T+=1],g.schema=x,g.schemaPath=l+"["+T+"]",g.errSchemaPath=u+"/"+T,t+=" "+e.validate(g)+" ",g.baseId=R,t+=" "+f+" = "+f+" || "+y+"; if (!"+f+") { ",v+="}";e.compositeRule=g.compositeRule=S,t+=" "+v+" if (!"+f+") { var err = ",e.createErrors!==!1?(t+=" { keyword: 'anyOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(t+=" , message: 'should match some schema in anyOf' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ",t+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&p&&(e.async?t+=" throw new ValidationError(vErrors); ":t+=" validate.errors = vErrors; return false; "),t+=" } else { errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; } ",e.opts.allErrors&&(t+=" } ")}else p&&(t+=" if (true) { ");return t}});var Fo=H((Im,jo)=>{"use strict";jo.exports=function(e,r,a){var t=" ",n=e.schema[r],o=e.errSchemaPath+"/"+r,i=!e.opts.allErrors,l=e.util.toQuotedString(n);return e.opts.$comment===!0?t+=" console.log("+l+");":typeof e.opts.$comment=="function"&&(t+=" self._opts.$comment("+l+", "+e.util.toQuotedString(o)+", validate.root.schema);"),t}});var Uo=H(($m,Mo)=>{"use strict";Mo.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,p=!e.opts.allErrors,h="data"+(o||""),f="valid"+n,d=e.opts.$data&&i&&i.$data,g;d?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",g="schema"+n):g=i,d||(t+=" var schema"+n+" = validate.schema"+l+";"),t+="var "+f+" = equal("+h+", schema"+n+"); if (!"+f+") { ";var v=v||[];v.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'const' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { allowedValue: schema"+n+" } ",e.opts.messages!==!1&&(t+=" , message: 'should be equal to constant' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ";var y=t;return t=v.pop(),!e.compositeRule&&p?e.async?t+=" throw new ValidationError(["+y+"]); ":t+=" validate.errors = ["+y+"]; return false; ":t+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" }",p&&(t+=" else { "),t}});var Bo=H((Nm,qo)=>{"use strict";qo.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,p=!e.opts.allErrors,h="data"+(o||""),f="valid"+n,d="errs__"+n,g=e.util.copy(e),v="";g.level++;var y="valid"+g.level,_="i"+n,R=g.dataLevel=e.dataLevel+1,S="data"+R,w=e.baseId,x=e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all);if(t+="var "+d+" = errors;var "+f+";",x){var T=e.compositeRule;e.compositeRule=g.compositeRule=!0,g.schema=i,g.schemaPath=l,g.errSchemaPath=u,t+=" var "+y+" = false; for (var "+_+" = 0; "+_+" < "+h+".length; "+_+"++) { ",g.errorPath=e.util.getPathExpr(e.errorPath,_,e.opts.jsonPointers,!0);var N=h+"["+_+"]";g.dataPathArr[R]=_;var L=e.validate(g);g.baseId=w,e.util.varOccurences(L,S)<2?t+=" "+e.util.varReplace(L,S,N)+" ":t+=" var "+S+" = "+N+"; "+L+" ",t+=" if ("+y+") break; } ",e.compositeRule=g.compositeRule=T,t+=" "+v+" if (!"+y+") {"}else t+=" if ("+h+".length == 0) {";var I=I||[];I.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(t+=" , message: 'should contain a valid item' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ";var F=t;return t=I.pop(),!e.compositeRule&&p?e.async?t+=" throw new ValidationError(["+F+"]); ":t+=" validate.errors = ["+F+"]; return false; ":t+=" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } else { ",x&&(t+=" errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; } "),e.opts.allErrors&&(t+=" } "),t}});var Ho=H((Am,Vo)=>{"use strict";Vo.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,p=!e.opts.allErrors,h="data"+(o||""),f="errs__"+n,d=e.util.copy(e),g="";d.level++;var v="valid"+d.level,y={},_={},R=e.opts.ownProperties;for(T in i)if(T!="__proto__"){var S=i[T],w=Array.isArray(S)?_:y;w[T]=S}t+="var "+f+" = errors;";var x=e.errorPath;t+="var missing"+n+";";for(var T in _)if(w=_[T],w.length){if(t+=" if ( "+h+e.util.getProperty(T)+" !== undefined ",R&&(t+=" && Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(T)+"') "),p){t+=" && ( ";var N=w;if(N)for(var L,I=-1,F=N.length-1;I<F;){L=N[I+=1],I&&(t+=" || ");var k=e.util.getProperty(L),j=h+k;t+=" ( ( "+j+" === undefined ",R&&(t+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(L)+"') "),t+=") && (missing"+n+" = "+e.util.toQuotedString(e.opts.jsonPointers?L:k)+") ) "}t+=")) { ";var $="missing"+n,A="' + "+$+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(x,$,!0):x+" + "+$);var M=M||[];M.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { property: '"+e.util.escapeQuotes(T)+"', missingProperty: '"+A+"', depsCount: "+w.length+", deps: '"+e.util.escapeQuotes(w.length==1?w[0]:w.join(", "))+"' } ",e.opts.messages!==!1&&(t+=" , message: 'should have ",w.length==1?t+="property "+e.util.escapeQuotes(w[0]):t+="properties "+e.util.escapeQuotes(w.join(", ")),t+=" when property "+e.util.escapeQuotes(T)+" is present' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ";var ee=t;t=M.pop(),!e.compositeRule&&p?e.async?t+=" throw new ValidationError(["+ee+"]); ":t+=" validate.errors = ["+ee+"]; return false; ":t+=" var err = "+ee+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else{t+=" ) { ";var W=w;if(W)for(var L,Y=-1,Q=W.length-1;Y<Q;){L=W[Y+=1];var k=e.util.getProperty(L),A=e.util.escapeQuotes(L),j=h+k;e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(x,L,e.opts.jsonPointers)),t+=" if ( "+j+" === undefined ",R&&(t+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(L)+"') "),t+=") { var err = ",e.createErrors!==!1?(t+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { property: '"+e.util.escapeQuotes(T)+"', missingProperty: '"+A+"', depsCount: "+w.length+", deps: '"+e.util.escapeQuotes(w.length==1?w[0]:w.join(", "))+"' } ",e.opts.messages!==!1&&(t+=" , message: 'should have ",w.length==1?t+="property "+e.util.escapeQuotes(w[0]):t+="properties "+e.util.escapeQuotes(w.join(", ")),t+=" when property "+e.util.escapeQuotes(T)+" is present' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ",t+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}t+=" } ",p&&(g+="}",t+=" else { ")}e.errorPath=x;var z=d.baseId;for(var T in y){var S=y[T];(e.opts.strictKeywords?typeof S=="object"&&Object.keys(S).length>0||S===!1:e.util.schemaHasRules(S,e.RULES.all))&&(t+=" "+v+" = true; if ( "+h+e.util.getProperty(T)+" !== undefined ",R&&(t+=" && Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(T)+"') "),t+=") { ",d.schema=S,d.schemaPath=l+e.util.getProperty(T),d.errSchemaPath=u+"/"+e.util.escapeFragment(T),t+=" "+e.validate(d)+" ",d.baseId=z,t+=" } ",p&&(t+=" if ("+v+") { ",g+="}"))}return p&&(t+=" "+g+" if ("+f+" == errors) {"),t}});var Zo=H((Dm,zo)=>{"use strict";zo.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,p=!e.opts.allErrors,h="data"+(o||""),f="valid"+n,d=e.opts.$data&&i&&i.$data,g;d?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",g="schema"+n):g=i;var v="i"+n,y="schema"+n;d||(t+=" var "+y+" = validate.schema"+l+";"),t+="var "+f+";",d&&(t+=" if (schema"+n+" === undefined) "+f+" = true; else if (!Array.isArray(schema"+n+")) "+f+" = false; else {"),t+=""+f+" = false;for (var "+v+"=0; "+v+"<"+y+".length; "+v+"++) if (equal("+h+", "+y+"["+v+"])) { "+f+" = true; break; }",d&&(t+=" } "),t+=" if (!"+f+") { ";var _=_||[];_.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { allowedValues: schema"+n+" } ",e.opts.messages!==!1&&(t+=" , message: 'should be equal to one of the allowed values' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ";var R=t;return t=_.pop(),!e.compositeRule&&p?e.async?t+=" throw new ValidationError(["+R+"]); ":t+=" validate.errors = ["+R+"]; return false; ":t+=" var err = "+R+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" }",p&&(t+=" else { "),t}});var Qo=H((Cm,Go)=>{"use strict";Go.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,p=!e.opts.allErrors,h="data"+(o||"");if(e.opts.format===!1)return p&&(t+=" if (true) { "),t;var f=e.opts.$data&&i&&i.$data,d;f?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+n):d=i;var g=e.opts.unknownFormats,v=Array.isArray(g);if(f){var y="format"+n,_="isObject"+n,R="formatType"+n;t+=" var "+y+" = formats["+d+"]; var "+_+" = typeof "+y+" == 'object' && !("+y+" instanceof RegExp) && "+y+".validate; var "+R+" = "+_+" && "+y+".type || 'string'; if ("+_+") { ",e.async&&(t+=" var async"+n+" = "+y+".async; "),t+=" "+y+" = "+y+".validate; } if ( ",f&&(t+=" ("+d+" !== undefined && typeof "+d+" != 'string') || "),t+=" (",g!="ignore"&&(t+=" ("+d+" && !"+y+" ",v&&(t+=" && self._opts.unknownFormats.indexOf("+d+") == -1 "),t+=") || "),t+=" ("+y+" && "+R+" == '"+a+"' && !(typeof "+y+" == 'function' ? ",e.async?t+=" (async"+n+" ? await "+y+"("+h+") : "+y+"("+h+")) ":t+=" "+y+"("+h+") ",t+=" : "+y+".test("+h+"))))) {"}else{var y=e.formats[i];if(!y){if(g=="ignore")return e.logger.warn('unknown format "'+i+'" ignored in schema at path "'+e.errSchemaPath+'"'),p&&(t+=" if (true) { "),t;if(v&&g.indexOf(i)>=0)return p&&(t+=" if (true) { "),t;throw new Error('unknown format "'+i+'" is used in schema at path "'+e.errSchemaPath+'"')}var _=typeof y=="object"&&!(y instanceof RegExp)&&y.validate,R=_&&y.type||"string";if(_){var S=y.async===!0;y=y.validate}if(R!=a)return p&&(t+=" if (true) { "),t;if(S){if(!e.async)throw new Error("async format in sync schema");var w="formats"+e.util.getProperty(i)+".validate";t+=" if (!(await "+w+"("+h+"))) { "}else{t+=" if (! ";var w="formats"+e.util.getProperty(i);_&&(w+=".validate"),typeof y=="function"?t+=" "+w+"("+h+") ":t+=" "+w+".test("+h+") ",t+=") { "}}var x=x||[];x.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { format: ",f?t+=""+d:t+=""+e.util.toQuotedString(i),t+=" } ",e.opts.messages!==!1&&(t+=` , message: 'should match format "`,f?t+="' + "+d+" + '":t+=""+e.util.escapeQuotes(i),t+=`"' `),e.opts.verbose&&(t+=" , schema: ",f?t+="validate.schema"+l:t+=""+e.util.toQuotedString(i),t+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ";var T=t;return t=x.pop(),!e.compositeRule&&p?e.async?t+=" throw new ValidationError(["+T+"]); ":t+=" validate.errors = ["+T+"]; return false; ":t+=" var err = "+T+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } ",p&&(t+=" else { "),t}});var Xo=H((km,Wo)=>{"use strict";Wo.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,p=!e.opts.allErrors,h="data"+(o||""),f="valid"+n,d="errs__"+n,g=e.util.copy(e);g.level++;var v="valid"+g.level,y=e.schema.then,_=e.schema.else,R=y!==void 0&&(e.opts.strictKeywords?typeof y=="object"&&Object.keys(y).length>0||y===!1:e.util.schemaHasRules(y,e.RULES.all)),S=_!==void 0&&(e.opts.strictKeywords?typeof _=="object"&&Object.keys(_).length>0||_===!1:e.util.schemaHasRules(_,e.RULES.all)),w=g.baseId;if(R||S){var x;g.createErrors=!1,g.schema=i,g.schemaPath=l,g.errSchemaPath=u,t+=" var "+d+" = errors; var "+f+" = true; ";var T=e.compositeRule;e.compositeRule=g.compositeRule=!0,t+=" "+e.validate(g)+" ",g.baseId=w,g.createErrors=!0,t+=" errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; } ",e.compositeRule=g.compositeRule=T,R?(t+=" if ("+v+") { ",g.schema=e.schema.then,g.schemaPath=e.schemaPath+".then",g.errSchemaPath=e.errSchemaPath+"/then",t+=" "+e.validate(g)+" ",g.baseId=w,t+=" "+f+" = "+v+"; ",R&&S?(x="ifClause"+n,t+=" var "+x+" = 'then'; "):x="'then'",t+=" } ",S&&(t+=" else { ")):t+=" if (!"+v+") { ",S&&(g.schema=e.schema.else,g.schemaPath=e.schemaPath+".else",g.errSchemaPath=e.errSchemaPath+"/else",t+=" "+e.validate(g)+" ",g.baseId=w,t+=" "+f+" = "+v+"; ",R&&S?(x="ifClause"+n,t+=" var "+x+" = 'else'; "):x="'else'",t+=" } "),t+=" if (!"+f+") { var err = ",e.createErrors!==!1?(t+=" { keyword: 'if' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { failingKeyword: "+x+" } ",e.opts.messages!==!1&&(t+=` , message: 'should match "' + `+x+` + '" schema' `),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ",t+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&p&&(e.async?t+=" throw new ValidationError(vErrors); ":t+=" validate.errors = vErrors; return false; "),t+=" } ",p&&(t+=" else { ")}else p&&(t+=" if (true) { ");return t}});var Jo=H((Lm,Ko)=>{"use strict";Ko.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,p=!e.opts.allErrors,h="data"+(o||""),f="valid"+n,d="errs__"+n,g=e.util.copy(e),v="";g.level++;var y="valid"+g.level,_="i"+n,R=g.dataLevel=e.dataLevel+1,S="data"+R,w=e.baseId;if(t+="var "+d+" = errors;var "+f+";",Array.isArray(i)){var x=e.schema.additionalItems;if(x===!1){t+=" "+f+" = "+h+".length <= "+i.length+"; ";var T=u;u=e.errSchemaPath+"/additionalItems",t+=" if (!"+f+") { ";var N=N||[];N.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+i.length+" } ",e.opts.messages!==!1&&(t+=" , message: 'should NOT have more than "+i.length+" items' "),e.opts.verbose&&(t+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ";var L=t;t=N.pop(),!e.compositeRule&&p?e.async?t+=" throw new ValidationError(["+L+"]); ":t+=" validate.errors = ["+L+"]; return false; ":t+=" var err = "+L+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } ",u=T,p&&(v+="}",t+=" else { ")}var I=i;if(I){for(var F,k=-1,j=I.length-1;k<j;)if(F=I[k+=1],e.opts.strictKeywords?typeof F=="object"&&Object.keys(F).length>0||F===!1:e.util.schemaHasRules(F,e.RULES.all)){t+=" "+y+" = true; if ("+h+".length > "+k+") { ";var $=h+"["+k+"]";g.schema=F,g.schemaPath=l+"["+k+"]",g.errSchemaPath=u+"/"+k,g.errorPath=e.util.getPathExpr(e.errorPath,k,e.opts.jsonPointers,!0),g.dataPathArr[R]=k;var A=e.validate(g);g.baseId=w,e.util.varOccurences(A,S)<2?t+=" "+e.util.varReplace(A,S,$)+" ":t+=" var "+S+" = "+$+"; "+A+" ",t+=" } ",p&&(t+=" if ("+y+") { ",v+="}")}}if(typeof x=="object"&&(e.opts.strictKeywords?typeof x=="object"&&Object.keys(x).length>0||x===!1:e.util.schemaHasRules(x,e.RULES.all))){g.schema=x,g.schemaPath=e.schemaPath+".additionalItems",g.errSchemaPath=e.errSchemaPath+"/additionalItems",t+=" "+y+" = true; if ("+h+".length > "+i.length+") { for (var "+_+" = "+i.length+"; "+_+" < "+h+".length; "+_+"++) { ",g.errorPath=e.util.getPathExpr(e.errorPath,_,e.opts.jsonPointers,!0);var $=h+"["+_+"]";g.dataPathArr[R]=_;var A=e.validate(g);g.baseId=w,e.util.varOccurences(A,S)<2?t+=" "+e.util.varReplace(A,S,$)+" ":t+=" var "+S+" = "+$+"; "+A+" ",p&&(t+=" if (!"+y+") break; "),t+=" } } ",p&&(t+=" if ("+y+") { ",v+="}")}}else if(e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){g.schema=i,g.schemaPath=l,g.errSchemaPath=u,t+=" for (var "+_+" = 0; "+_+" < "+h+".length; "+_+"++) { ",g.errorPath=e.util.getPathExpr(e.errorPath,_,e.opts.jsonPointers,!0);var $=h+"["+_+"]";g.dataPathArr[R]=_;var A=e.validate(g);g.baseId=w,e.util.varOccurences(A,S)<2?t+=" "+e.util.varReplace(A,S,$)+" ":t+=" var "+S+" = "+$+"; "+A+" ",p&&(t+=" if (!"+y+") break; "),t+=" }"}return p&&(t+=" "+v+" if ("+d+" == errors) {"),t}});var Na=H((jm,Yo)=>{"use strict";Yo.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,p=!e.opts.allErrors,w,h="data"+(o||""),f=e.opts.$data&&i&&i.$data,d;f?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+n):d=i;var g=r=="maximum",v=g?"exclusiveMaximum":"exclusiveMinimum",y=e.schema[v],_=e.opts.$data&&y&&y.$data,R=g?"<":">",S=g?">":"<",w=void 0;if(!(f||typeof i=="number"||i===void 0))throw new Error(r+" must be number");if(!(_||y===void 0||typeof y=="number"||typeof y=="boolean"))throw new Error(v+" must be number or boolean");if(_){var x=e.util.getData(y.$data,o,e.dataPathArr),T="exclusive"+n,N="exclType"+n,L="exclIsNumber"+n,I="op"+n,F="' + "+I+" + '";t+=" var schemaExcl"+n+" = "+x+"; ",x="schemaExcl"+n,t+=" var "+T+"; var "+N+" = typeof "+x+"; if ("+N+" != 'boolean' && "+N+" != 'undefined' && "+N+" != 'number') { ";var w=v,k=k||[];k.push(t),t="",e.createErrors!==!1?(t+=" { keyword: '"+(w||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(t+=" , message: '"+v+" should be boolean' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ";var j=t;t=k.pop(),!e.compositeRule&&p?e.async?t+=" throw new ValidationError(["+j+"]); ":t+=" validate.errors = ["+j+"]; return false; ":t+=" var err = "+j+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } else if ( ",f&&(t+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),t+=" "+N+" == 'number' ? ( ("+T+" = "+d+" === undefined || "+x+" "+R+"= "+d+") ? "+h+" "+S+"= "+x+" : "+h+" "+S+" "+d+" ) : ( ("+T+" = "+x+" === true) ? "+h+" "+S+"= "+d+" : "+h+" "+S+" "+d+" ) || "+h+" !== "+h+") { var op"+n+" = "+T+" ? '"+R+"' : '"+R+"='; ",i===void 0&&(w=v,u=e.errSchemaPath+"/"+v,d=x,f=_)}else{var L=typeof y=="number",F=R;if(L&&f){var I="'"+F+"'";t+=" if ( ",f&&(t+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),t+=" ( "+d+" === undefined || "+y+" "+R+"= "+d+" ? "+h+" "+S+"= "+y+" : "+h+" "+S+" "+d+" ) || "+h+" !== "+h+") { "}else{L&&i===void 0?(T=!0,w=v,u=e.errSchemaPath+"/"+v,d=y,S+="="):(L&&(d=Math[g?"min":"max"](y,i)),y===(L?d:!0)?(T=!0,w=v,u=e.errSchemaPath+"/"+v,S+="="):(T=!1,F+="="));var I="'"+F+"'";t+=" if ( ",f&&(t+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),t+=" "+h+" "+S+" "+d+" || "+h+" !== "+h+") { "}}w=w||r;var k=k||[];k.push(t),t="",e.createErrors!==!1?(t+=" { keyword: '"+(w||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { comparison: "+I+", limit: "+d+", exclusive: "+T+" } ",e.opts.messages!==!1&&(t+=" , message: 'should be "+F+" ",f?t+="' + "+d:t+=""+d+"'"),e.opts.verbose&&(t+=" , schema: ",f?t+="validate.schema"+l:t+=""+i,t+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ";var j=t;return t=k.pop(),!e.compositeRule&&p?e.async?t+=" throw new ValidationError(["+j+"]); ":t+=" validate.errors = ["+j+"]; return false; ":t+=" var err = "+j+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } ",p&&(t+=" else { "),t}});var Aa=H((Fm,ei)=>{"use strict";ei.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,p=!e.opts.allErrors,v,h="data"+(o||""),f=e.opts.$data&&i&&i.$data,d;if(f?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+n):d=i,!(f||typeof i=="number"))throw new Error(r+" must be number");var g=r=="maxItems"?">":"<";t+="if ( ",f&&(t+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),t+=" "+h+".length "+g+" "+d+") { ";var v=r,y=y||[];y.push(t),t="",e.createErrors!==!1?(t+=" { keyword: '"+(v||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+d+" } ",e.opts.messages!==!1&&(t+=" , message: 'should NOT have ",r=="maxItems"?t+="more":t+="fewer",t+=" than ",f?t+="' + "+d+" + '":t+=""+i,t+=" items' "),e.opts.verbose&&(t+=" , schema: ",f?t+="validate.schema"+l:t+=""+i,t+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ";var _=t;return t=y.pop(),!e.compositeRule&&p?e.async?t+=" throw new ValidationError(["+_+"]); ":t+=" validate.errors = ["+_+"]; return false; ":t+=" var err = "+_+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+="} ",p&&(t+=" else { "),t}});var Da=H((Mm,ti)=>{"use strict";ti.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,p=!e.opts.allErrors,v,h="data"+(o||""),f=e.opts.$data&&i&&i.$data,d;if(f?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+n):d=i,!(f||typeof i=="number"))throw new Error(r+" must be number");var g=r=="maxLength"?">":"<";t+="if ( ",f&&(t+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),e.opts.unicode===!1?t+=" "+h+".length ":t+=" ucs2length("+h+") ",t+=" "+g+" "+d+") { ";var v=r,y=y||[];y.push(t),t="",e.createErrors!==!1?(t+=" { keyword: '"+(v||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+d+" } ",e.opts.messages!==!1&&(t+=" , message: 'should NOT be ",r=="maxLength"?t+="longer":t+="shorter",t+=" than ",f?t+="' + "+d+" + '":t+=""+i,t+=" characters' "),e.opts.verbose&&(t+=" , schema: ",f?t+="validate.schema"+l:t+=""+i,t+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ";var _=t;return t=y.pop(),!e.compositeRule&&p?e.async?t+=" throw new ValidationError(["+_+"]); ":t+=" validate.errors = ["+_+"]; return false; ":t+=" var err = "+_+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+="} ",p&&(t+=" else { "),t}});var Ca=H((Um,ri)=>{"use strict";ri.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,p=!e.opts.allErrors,v,h="data"+(o||""),f=e.opts.$data&&i&&i.$data,d;if(f?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+n):d=i,!(f||typeof i=="number"))throw new Error(r+" must be number");var g=r=="maxProperties"?">":"<";t+="if ( ",f&&(t+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),t+=" Object.keys("+h+").length "+g+" "+d+") { ";var v=r,y=y||[];y.push(t),t="",e.createErrors!==!1?(t+=" { keyword: '"+(v||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+d+" } ",e.opts.messages!==!1&&(t+=" , message: 'should NOT have ",r=="maxProperties"?t+="more":t+="fewer",t+=" than ",f?t+="' + "+d+" + '":t+=""+i,t+=" properties' "),e.opts.verbose&&(t+=" , schema: ",f?t+="validate.schema"+l:t+=""+i,t+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ";var _=t;return t=y.pop(),!e.compositeRule&&p?e.async?t+=" throw new ValidationError(["+_+"]); ":t+=" validate.errors = ["+_+"]; return false; ":t+=" var err = "+_+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+="} ",p&&(t+=" else { "),t}});var ai=H((qm,si)=>{"use strict";si.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,p=!e.opts.allErrors,h="data"+(o||""),f=e.opts.$data&&i&&i.$data,d;if(f?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+n):d=i,!(f||typeof i=="number"))throw new Error(r+" must be number");t+="var division"+n+";if (",f&&(t+=" "+d+" !== undefined && ( typeof "+d+" != 'number' || "),t+=" (division"+n+" = "+h+" / "+d+", ",e.opts.multipleOfPrecision?t+=" Math.abs(Math.round(division"+n+") - division"+n+") > 1e-"+e.opts.multipleOfPrecision+" ":t+=" division"+n+" !== parseInt(division"+n+") ",t+=" ) ",f&&(t+=" ) "),t+=" ) { ";var g=g||[];g.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { multipleOf: "+d+" } ",e.opts.messages!==!1&&(t+=" , message: 'should be multiple of ",f?t+="' + "+d:t+=""+d+"'"),e.opts.verbose&&(t+=" , schema: ",f?t+="validate.schema"+l:t+=""+i,t+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ";var v=t;return t=g.pop(),!e.compositeRule&&p?e.async?t+=" throw new ValidationError(["+v+"]); ":t+=" validate.errors = ["+v+"]; return false; ":t+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+="} ",p&&(t+=" else { "),t}});var oi=H((Bm,ni)=>{"use strict";ni.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,p=!e.opts.allErrors,h="data"+(o||""),f="errs__"+n,d=e.util.copy(e);d.level++;var g="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,t+=" var "+f+" = errors; ";var v=e.compositeRule;e.compositeRule=d.compositeRule=!0,d.createErrors=!1;var y;d.opts.allErrors&&(y=d.opts.allErrors,d.opts.allErrors=!1),t+=" "+e.validate(d)+" ",d.createErrors=!0,y&&(d.opts.allErrors=y),e.compositeRule=d.compositeRule=v,t+=" if ("+g+") { ";var _=_||[];_.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(t+=" , message: 'should NOT be valid' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ";var R=t;t=_.pop(),!e.compositeRule&&p?e.async?t+=" throw new ValidationError(["+R+"]); ":t+=" validate.errors = ["+R+"]; return false; ":t+=" var err = "+R+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } else { errors = "+f+"; if (vErrors !== null) { if ("+f+") vErrors.length = "+f+"; else vErrors = null; } ",e.opts.allErrors&&(t+=" } ")}else t+=" var err = ",e.createErrors!==!1?(t+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(t+=" , message: 'should NOT be valid' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ",t+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",p&&(t+=" if (false) { ");return t}});var ci=H((Vm,ii)=>{"use strict";ii.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,p=!e.opts.allErrors,h="data"+(o||""),f="valid"+n,d="errs__"+n,g=e.util.copy(e),v="";g.level++;var y="valid"+g.level,_=g.baseId,R="prevValid"+n,S="passingSchemas"+n;t+="var "+d+" = errors , "+R+" = false , "+f+" = false , "+S+" = null; ";var w=e.compositeRule;e.compositeRule=g.compositeRule=!0;var x=i;if(x)for(var T,N=-1,L=x.length-1;N<L;)T=x[N+=1],(e.opts.strictKeywords?typeof T=="object"&&Object.keys(T).length>0||T===!1:e.util.schemaHasRules(T,e.RULES.all))?(g.schema=T,g.schemaPath=l+"["+N+"]",g.errSchemaPath=u+"/"+N,t+=" "+e.validate(g)+" ",g.baseId=_):t+=" var "+y+" = true; ",N&&(t+=" if ("+y+" && "+R+") { "+f+" = false; "+S+" = ["+S+", "+N+"]; } else { ",v+="}"),t+=" if ("+y+") { "+f+" = "+R+" = true; "+S+" = "+N+"; }";return e.compositeRule=g.compositeRule=w,t+=""+v+"if (!"+f+") { var err = ",e.createErrors!==!1?(t+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { passingSchemas: "+S+" } ",e.opts.messages!==!1&&(t+=" , message: 'should match exactly one schema in oneOf' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ",t+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&p&&(e.async?t+=" throw new ValidationError(vErrors); ":t+=" validate.errors = vErrors; return false; "),t+="} else { errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; }",e.opts.allErrors&&(t+=" } "),t}});var ui=H((Hm,li)=>{"use strict";li.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,p=!e.opts.allErrors,h="data"+(o||""),f=e.opts.$data&&i&&i.$data,d;f?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+n):d=i;var g=f?"(new RegExp("+d+"))":e.usePattern(i);t+="if ( ",f&&(t+=" ("+d+" !== undefined && typeof "+d+" != 'string') || "),t+=" !"+g+".test("+h+") ) { ";var v=v||[];v.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { pattern: ",f?t+=""+d:t+=""+e.util.toQuotedString(i),t+=" } ",e.opts.messages!==!1&&(t+=` , message: 'should match pattern "`,f?t+="' + "+d+" + '":t+=""+e.util.escapeQuotes(i),t+=`"' `),e.opts.verbose&&(t+=" , schema: ",f?t+="validate.schema"+l:t+=""+e.util.toQuotedString(i),t+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ";var y=t;return t=v.pop(),!e.compositeRule&&p?e.async?t+=" throw new ValidationError(["+y+"]); ":t+=" validate.errors = ["+y+"]; return false; ":t+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+="} ",p&&(t+=" else { "),t}});var pi=H((zm,di)=>{"use strict";di.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,p=!e.opts.allErrors,h="data"+(o||""),f="errs__"+n,d=e.util.copy(e),g="";d.level++;var v="valid"+d.level,y="key"+n,_="idx"+n,R=d.dataLevel=e.dataLevel+1,S="data"+R,w="dataProperties"+n,x=Object.keys(i||{}).filter(Y),T=e.schema.patternProperties||{},N=Object.keys(T).filter(Y),L=e.schema.additionalProperties,I=x.length||N.length,F=L===!1,k=typeof L=="object"&&Object.keys(L).length,j=e.opts.removeAdditional,$=F||k||j,A=e.opts.ownProperties,M=e.baseId,ee=e.schema.required;if(ee&&!(e.opts.$data&&ee.$data)&&ee.length<e.opts.loopRequired)var W=e.util.toHash(ee);function Y(et){return et!=="__proto__"}if(t+="var "+f+" = errors;var "+v+" = true;",A&&(t+=" var "+w+" = undefined;"),$){if(A?t+=" "+w+" = "+w+" || Object.keys("+h+"); for (var "+_+"=0; "+_+"<"+w+".length; "+_+"++) { var "+y+" = "+w+"["+_+"]; ":t+=" for (var "+y+" in "+h+") { ",I){if(t+=" var isAdditional"+n+" = !(false ",x.length)if(x.length>8)t+=" || validate.schema"+l+".hasOwnProperty("+y+") ";else{var Q=x;if(Q)for(var z,he=-1,Oe=Q.length-1;he<Oe;)z=Q[he+=1],t+=" || "+y+" == "+e.util.toQuotedString(z)+" "}if(N.length){var Ae=N;if(Ae)for(var oe,be=-1,Re=Ae.length-1;be<Re;)oe=Ae[be+=1],t+=" || "+e.usePattern(oe)+".test("+y+") "}t+=" ); if (isAdditional"+n+") { "}if(j=="all")t+=" delete "+h+"["+y+"]; ";else{var De=e.errorPath,St="' + "+y+" + '";if(e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(e.errorPath,y,e.opts.jsonPointers)),F)if(j)t+=" delete "+h+"["+y+"]; ";else{t+=" "+v+" = false; ";var pt=u;u=e.errSchemaPath+"/additionalProperties";var Ee=Ee||[];Ee.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'additionalProperties' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { additionalProperty: '"+St+"' } ",e.opts.messages!==!1&&(t+=" , message: '",e.opts._errorDataPathProperty?t+="is an invalid additional property":t+="should NOT have additional properties",t+="' "),e.opts.verbose&&(t+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ";var ye=t;t=Ee.pop(),!e.compositeRule&&p?e.async?t+=" throw new ValidationError(["+ye+"]); ":t+=" validate.errors = ["+ye+"]; return false; ":t+=" var err = "+ye+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u=pt,p&&(t+=" break; ")}else if(k)if(j=="failing"){t+=" var "+f+" = errors; ";var Ct=e.compositeRule;e.compositeRule=d.compositeRule=!0,d.schema=L,d.schemaPath=e.schemaPath+".additionalProperties",d.errSchemaPath=e.errSchemaPath+"/additionalProperties",d.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,y,e.opts.jsonPointers);var Ie=h+"["+y+"]";d.dataPathArr[R]=y;var ce=e.validate(d);d.baseId=M,e.util.varOccurences(ce,S)<2?t+=" "+e.util.varReplace(ce,S,Ie)+" ":t+=" var "+S+" = "+Ie+"; "+ce+" ",t+=" if (!"+v+") { errors = "+f+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+h+"["+y+"]; } ",e.compositeRule=d.compositeRule=Ct}else{d.schema=L,d.schemaPath=e.schemaPath+".additionalProperties",d.errSchemaPath=e.errSchemaPath+"/additionalProperties",d.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,y,e.opts.jsonPointers);var Ie=h+"["+y+"]";d.dataPathArr[R]=y;var ce=e.validate(d);d.baseId=M,e.util.varOccurences(ce,S)<2?t+=" "+e.util.varReplace(ce,S,Ie)+" ":t+=" var "+S+" = "+Ie+"; "+ce+" ",p&&(t+=" if (!"+v+") break; ")}e.errorPath=De}I&&(t+=" } "),t+=" } ",p&&(t+=" if ("+v+") { ",g+="}")}var xt=e.opts.useDefaults&&!e.compositeRule;if(x.length){var ht=x;if(ht)for(var z,kt=-1,Lt=ht.length-1;kt<Lt;){z=ht[kt+=1];var we=i[z];if(e.opts.strictKeywords?typeof we=="object"&&Object.keys(we).length>0||we===!1:e.util.schemaHasRules(we,e.RULES.all)){var He=e.util.getProperty(z),Ie=h+He,je=xt&&we.default!==void 0;d.schema=we,d.schemaPath=l+He,d.errSchemaPath=u+"/"+e.util.escapeFragment(z),d.errorPath=e.util.getPath(e.errorPath,z,e.opts.jsonPointers),d.dataPathArr[R]=e.util.toQuotedString(z);var ce=e.validate(d);if(d.baseId=M,e.util.varOccurences(ce,S)<2){ce=e.util.varReplace(ce,S,Ie);var Ce=Ie}else{var Ce=S;t+=" var "+S+" = "+Ie+"; "}if(je)t+=" "+ce+" ";else{if(W&&W[z]){t+=" if ( "+Ce+" === undefined ",A&&(t+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(z)+"') "),t+=") { "+v+" = false; ";var De=e.errorPath,pt=u,nt=e.util.escapeQuotes(z);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(De,z,e.opts.jsonPointers)),u=e.errSchemaPath+"/required";var Ee=Ee||[];Ee.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+nt+"' } ",e.opts.messages!==!1&&(t+=" , message: '",e.opts._errorDataPathProperty?t+="is a required property":t+="should have required property \\'"+nt+"\\'",t+="' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ";var ye=t;t=Ee.pop(),!e.compositeRule&&p?e.async?t+=" throw new ValidationError(["+ye+"]); ":t+=" validate.errors = ["+ye+"]; return false; ":t+=" var err = "+ye+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u=pt,e.errorPath=De,t+=" } else { "}else p?(t+=" if ( "+Ce+" === undefined ",A&&(t+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(z)+"') "),t+=") { "+v+" = true; } else { "):(t+=" if ("+Ce+" !== undefined ",A&&(t+=" && Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(z)+"') "),t+=" ) { ");t+=" "+ce+" } "}}p&&(t+=" if ("+v+") { ",g+="}")}}if(N.length){var qe=N;if(qe)for(var oe,qr=-1,Ms=qe.length-1;qr<Ms;){oe=qe[qr+=1];var we=T[oe];if(e.opts.strictKeywords?typeof we=="object"&&Object.keys(we).length>0||we===!1:e.util.schemaHasRules(we,e.RULES.all)){d.schema=we,d.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty(oe),d.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment(oe),A?t+=" "+w+" = "+w+" || Object.keys("+h+"); for (var "+_+"=0; "+_+"<"+w+".length; "+_+"++) { var "+y+" = "+w+"["+_+"]; ":t+=" for (var "+y+" in "+h+") { ",t+=" if ("+e.usePattern(oe)+".test("+y+")) { ",d.errorPath=e.util.getPathExpr(e.errorPath,y,e.opts.jsonPointers);var Ie=h+"["+y+"]";d.dataPathArr[R]=y;var ce=e.validate(d);d.baseId=M,e.util.varOccurences(ce,S)<2?t+=" "+e.util.varReplace(ce,S,Ie)+" ":t+=" var "+S+" = "+Ie+"; "+ce+" ",p&&(t+=" if (!"+v+") break; "),t+=" } ",p&&(t+=" else "+v+" = true; "),t+=" } ",p&&(t+=" if ("+v+") { ",g+="}")}}}return p&&(t+=" "+g+" if ("+f+" == errors) {"),t}});var fi=H((Zm,hi)=>{"use strict";hi.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,p=!e.opts.allErrors,h="data"+(o||""),f="errs__"+n,d=e.util.copy(e),g="";d.level++;var v="valid"+d.level;if(t+="var "+f+" = 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 y="key"+n,_="idx"+n,R="i"+n,S="' + "+y+" + '",w=d.dataLevel=e.dataLevel+1,x="data"+w,T="dataProperties"+n,N=e.opts.ownProperties,L=e.baseId;N&&(t+=" var "+T+" = undefined; "),N?t+=" "+T+" = "+T+" || Object.keys("+h+"); for (var "+_+"=0; "+_+"<"+T+".length; "+_+"++) { var "+y+" = "+T+"["+_+"]; ":t+=" for (var "+y+" in "+h+") { ",t+=" var startErrs"+n+" = errors; ";var I=y,F=e.compositeRule;e.compositeRule=d.compositeRule=!0;var k=e.validate(d);d.baseId=L,e.util.varOccurences(k,x)<2?t+=" "+e.util.varReplace(k,x,I)+" ":t+=" var "+x+" = "+I+"; "+k+" ",e.compositeRule=d.compositeRule=F,t+=" if (!"+v+") { for (var "+R+"=startErrs"+n+"; "+R+"<errors; "+R+"++) { vErrors["+R+"].propertyName = "+y+"; } var err = ",e.createErrors!==!1?(t+=" { keyword: 'propertyNames' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { propertyName: '"+S+"' } ",e.opts.messages!==!1&&(t+=" , message: 'property name \\'"+S+"\\' is invalid' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ",t+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&p&&(e.async?t+=" throw new ValidationError(vErrors); ":t+=" validate.errors = vErrors; return false; "),p&&(t+=" break; "),t+=" } }"}return p&&(t+=" "+g+" if ("+f+" == errors) {"),t}});var vi=H((Gm,mi)=>{"use strict";mi.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,p=!e.opts.allErrors,h="data"+(o||""),f="valid"+n,d=e.opts.$data&&i&&i.$data,g;d?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",g="schema"+n):g=i;var v="schema"+n;if(!d)if(i.length<e.opts.loopRequired&&e.schema.properties&&Object.keys(e.schema.properties).length){var y=[],_=i;if(_)for(var R,S=-1,w=_.length-1;S<w;){R=_[S+=1];var x=e.schema.properties[R];x&&(e.opts.strictKeywords?typeof x=="object"&&Object.keys(x).length>0||x===!1:e.util.schemaHasRules(x,e.RULES.all))||(y[y.length]=R)}}else var y=i;if(d||y.length){var T=e.errorPath,N=d||y.length>=e.opts.loopRequired,L=e.opts.ownProperties;if(p)if(t+=" var missing"+n+"; ",N){d||(t+=" var "+v+" = validate.schema"+l+"; ");var I="i"+n,F="schema"+n+"["+I+"]",k="' + "+F+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(T,F,e.opts.jsonPointers)),t+=" var "+f+" = true; ",d&&(t+=" if (schema"+n+" === undefined) "+f+" = true; else if (!Array.isArray(schema"+n+")) "+f+" = false; else {"),t+=" for (var "+I+" = 0; "+I+" < "+v+".length; "+I+"++) { "+f+" = "+h+"["+v+"["+I+"]] !== undefined ",L&&(t+=" && Object.prototype.hasOwnProperty.call("+h+", "+v+"["+I+"]) "),t+="; if (!"+f+") break; } ",d&&(t+=" } "),t+=" if (!"+f+") { ";var j=j||[];j.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+k+"' } ",e.opts.messages!==!1&&(t+=" , message: '",e.opts._errorDataPathProperty?t+="is a required property":t+="should have required property \\'"+k+"\\'",t+="' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ";var $=t;t=j.pop(),!e.compositeRule&&p?e.async?t+=" throw new ValidationError(["+$+"]); ":t+=" validate.errors = ["+$+"]; return false; ":t+=" var err = "+$+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } else { "}else{t+=" if ( ";var A=y;if(A)for(var M,I=-1,ee=A.length-1;I<ee;){M=A[I+=1],I&&(t+=" || ");var W=e.util.getProperty(M),Y=h+W;t+=" ( ( "+Y+" === undefined ",L&&(t+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(M)+"') "),t+=") && (missing"+n+" = "+e.util.toQuotedString(e.opts.jsonPointers?M:W)+") ) "}t+=") { ";var F="missing"+n,k="' + "+F+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(T,F,!0):T+" + "+F);var j=j||[];j.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+k+"' } ",e.opts.messages!==!1&&(t+=" , message: '",e.opts._errorDataPathProperty?t+="is a required property":t+="should have required property \\'"+k+"\\'",t+="' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ";var $=t;t=j.pop(),!e.compositeRule&&p?e.async?t+=" throw new ValidationError(["+$+"]); ":t+=" validate.errors = ["+$+"]; return false; ":t+=" var err = "+$+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } else { "}else if(N){d||(t+=" var "+v+" = validate.schema"+l+"; ");var I="i"+n,F="schema"+n+"["+I+"]",k="' + "+F+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(T,F,e.opts.jsonPointers)),d&&(t+=" if ("+v+" && !Array.isArray("+v+")) { var err = ",e.createErrors!==!1?(t+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+k+"' } ",e.opts.messages!==!1&&(t+=" , message: '",e.opts._errorDataPathProperty?t+="is a required property":t+="should have required property \\'"+k+"\\'",t+="' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ",t+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+v+" !== undefined) { "),t+=" for (var "+I+" = 0; "+I+" < "+v+".length; "+I+"++) { if ("+h+"["+v+"["+I+"]] === undefined ",L&&(t+=" || ! Object.prototype.hasOwnProperty.call("+h+", "+v+"["+I+"]) "),t+=") { var err = ",e.createErrors!==!1?(t+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+k+"' } ",e.opts.messages!==!1&&(t+=" , message: '",e.opts._errorDataPathProperty?t+="is a required property":t+="should have required property \\'"+k+"\\'",t+="' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ",t+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",d&&(t+=" } ")}else{var Q=y;if(Q)for(var M,z=-1,he=Q.length-1;z<he;){M=Q[z+=1];var W=e.util.getProperty(M),k=e.util.escapeQuotes(M),Y=h+W;e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(T,M,e.opts.jsonPointers)),t+=" if ( "+Y+" === undefined ",L&&(t+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(M)+"') "),t+=") { var err = ",e.createErrors!==!1?(t+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+k+"' } ",e.opts.messages!==!1&&(t+=" , message: '",e.opts._errorDataPathProperty?t+="is a required property":t+="should have required property \\'"+k+"\\'",t+="' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ",t+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}e.errorPath=T}else p&&(t+=" if (true) {");return t}});var yi=H((Qm,gi)=>{"use strict";gi.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,p=!e.opts.allErrors,h="data"+(o||""),f="valid"+n,d=e.opts.$data&&i&&i.$data,g;if(d?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",g="schema"+n):g=i,(i||d)&&e.opts.uniqueItems!==!1){d&&(t+=" var "+f+"; if ("+g+" === false || "+g+" === undefined) "+f+" = true; else if (typeof "+g+" != 'boolean') "+f+" = false; else { "),t+=" var i = "+h+".length , "+f+" = true , j; if (i > 1) { ";var v=e.schema.items&&e.schema.items.type,y=Array.isArray(v);if(!v||v=="object"||v=="array"||y&&(v.indexOf("object")>=0||v.indexOf("array")>=0))t+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+h+"[i], "+h+"[j])) { "+f+" = false; break outer; } } } ";else{t+=" var itemIndices = {}, item; for (;i--;) { var item = "+h+"[i]; ";var _="checkDataType"+(y?"s":"");t+=" if ("+e.util[_](v,"item",e.opts.strictNumbers,!0)+") continue; ",y&&(t+=` if (typeof item == 'string') item = '"' + item; `),t+=" if (typeof itemIndices[item] == 'number') { "+f+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}t+=" } ",d&&(t+=" } "),t+=" if (!"+f+") { ";var R=R||[];R.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { i: i, j: j } ",e.opts.messages!==!1&&(t+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(t+=" , schema: ",d?t+="validate.schema"+l:t+=""+i,t+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),t+=" } "):t+=" {} ";var S=t;t=R.pop(),!e.compositeRule&&p?e.async?t+=" throw new ValidationError(["+S+"]); ":t+=" validate.errors = ["+S+"]; return false; ":t+=" var err = "+S+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } ",p&&(t+=" else { ")}else p&&(t+=" if (true) { ");return t}});var bi=H((Wm,_i)=>{"use strict";_i.exports={$ref:Ao(),allOf:Co(),anyOf:Lo(),$comment:Fo(),const:Uo(),contains:Bo(),dependencies:Ho(),enum:Zo(),format:Qo(),if:Xo(),items:Jo(),maximum:Na(),minimum:Na(),maxItems:Aa(),minItems:Aa(),maxLength:Da(),minLength:Da(),maxProperties:Ca(),minProperties:Ca(),multipleOf:ai(),not:oi(),oneOf:ci(),pattern:ui(),properties:pi(),propertyNames:fi(),required:vi(),uniqueItems:yi(),validate:Ia()}});var xi=H((Xm,Si)=>{"use strict";var Ei=bi(),ka=rr().toHash;Si.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"]}],r=["type","$comment"],a=["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"],t=["number","integer","string","array","object","boolean","null"];return e.all=ka(r),e.types=ka(t),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(p){r.push(p),e.all[p]=!0})}r.push(o);var u=e.all[o]={keyword:o,code:Ei[o],implements:i};return u}),e.all.$comment={keyword:"$comment",code:Ei.$comment},n.type&&(e.types[n.type]=n)}),e.keywords=ka(r.concat(a)),e.custom={},e}});var wi=H((Km,Ti)=>{"use strict";var Ri=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"];Ti.exports=function(s,e){for(var r=0;r<e.length;r++){s=JSON.parse(JSON.stringify(s));var a=e[r].split("/"),t=s,n;for(n=1;n<a.length;n++)t=t[a[n]];for(n=0;n<Ri.length;n++){var o=Ri[n],i=t[o];i&&(t[o]={anyOf:[i,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]})}}return s}});var Ii=H((Jm,Oi)=>{"use strict";var Hp=ms().MissingRef;Oi.exports=Pi;function Pi(s,e,r){var a=this;if(typeof this._opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");typeof e=="function"&&(r=e,e=void 0);var t=n(s).then(function(){var i=a._addSchema(s,void 0,e);return i.validate||o(i)});return r&&t.then(function(i){r(null,i)},r),t;function n(i){var l=i.$schema;return l&&!a.getSchema(l)?Pi.call(a,{$ref:l},!0):Promise.resolve()}function o(i){try{return a._compile(i)}catch(u){if(u instanceof Hp)return l(u);throw u}function l(u){var p=u.missingSchema;if(d(p))throw new Error("Schema "+p+" is loaded but "+u.missingRef+" cannot be resolved");var h=a._loadingSchemas[p];return h||(h=a._loadingSchemas[p]=a._opts.loadSchema(p),h.then(f,f)),h.then(function(g){if(!d(p))return n(g).then(function(){d(p)||a.addSchema(g,p,void 0,e)})}).then(function(){return o(i)});function f(){delete a._loadingSchemas[p]}function d(g){return a._refs[g]||a._schemas[g]}}}}});var Ni=H((Ym,$i)=>{"use strict";$i.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,p=!e.opts.allErrors,h,f="data"+(o||""),d="valid"+n,g="errs__"+n,v=e.opts.$data&&i&&i.$data,y;v?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",y="schema"+n):y=i;var _=this,R="definition"+n,S=_.definition,w="",x,T,N,L,I;if(v&&S.$data){I="keywordValidate"+n;var F=S.validateSchema;t+=" var "+R+" = RULES.custom['"+r+"'].definition; var "+I+" = "+R+".validate;"}else{if(L=e.useCustomRule(_,i,e.schema,e),!L)return;y="validate.schema"+l,I=L.code,x=S.compile,T=S.inline,N=S.macro}var k=I+".errors",j="i"+n,$="ruleErr"+n,A=S.async;if(A&&!e.async)throw new Error("async keyword in sync schema");if(T||N||(t+=""+k+" = null;"),t+="var "+g+" = errors;var "+d+";",v&&S.$data&&(w+="}",t+=" if ("+y+" === undefined) { "+d+" = true; } else { ",F&&(w+="}",t+=" "+d+" = "+R+".validateSchema("+y+"); if ("+d+") { ")),T)S.statements?t+=" "+L.validate+" ":t+=" "+d+" = "+L.validate+"; ";else if(N){var M=e.util.copy(e),w="";M.level++;var ee="valid"+M.level;M.schema=L.validate,M.schemaPath="";var W=e.compositeRule;e.compositeRule=M.compositeRule=!0;var Y=e.validate(M).replace(/validate\.schema/g,I);e.compositeRule=M.compositeRule=W,t+=" "+Y}else{var Q=Q||[];Q.push(t),t="",t+=" "+I+".call( ",e.opts.passContext?t+="this":t+="self",x||S.schema===!1?t+=" , "+f+" ":t+=" , "+y+" , "+f+" , validate.schema"+e.schemaPath+" ",t+=" , (dataPath || '')",e.errorPath!='""'&&(t+=" + "+e.errorPath);var z=o?"data"+(o-1||""):"parentData",he=o?e.dataPathArr[o]:"parentDataProperty";t+=" , "+z+" , "+he+" , rootData ) ";var Oe=t;t=Q.pop(),S.errors===!1?(t+=" "+d+" = ",A&&(t+="await "),t+=""+Oe+"; "):A?(k="customErrors"+n,t+=" var "+k+" = null; try { "+d+" = await "+Oe+"; } catch (e) { "+d+" = false; if (e instanceof ValidationError) "+k+" = e.errors; else throw e; } "):t+=" "+k+" = null; "+d+" = "+Oe+"; "}if(S.modifying&&(t+=" if ("+z+") "+f+" = "+z+"["+he+"];"),t+=""+w,S.valid)p&&(t+=" if (true) { ");else{t+=" if ( ",S.valid===void 0?(t+=" !",N?t+=""+ee:t+=""+d):t+=" "+!S.valid+" ",t+=") { ",h=_.keyword;var Q=Q||[];Q.push(t),t="";var Q=Q||[];Q.push(t),t="",e.createErrors!==!1?(t+=" { keyword: '"+(h||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { keyword: '"+_.keyword+"' } ",e.opts.messages!==!1&&(t+=` , message: 'should pass "`+_.keyword+`" keyword validation' `),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ";var Ae=t;t=Q.pop(),!e.compositeRule&&p?e.async?t+=" throw new ValidationError(["+Ae+"]); ":t+=" validate.errors = ["+Ae+"]; return false; ":t+=" var err = "+Ae+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";var oe=t;t=Q.pop(),T?S.errors?S.errors!="full"&&(t+=" for (var "+j+"="+g+"; "+j+"<errors; "+j+"++) { var "+$+" = vErrors["+j+"]; if ("+$+".dataPath === undefined) "+$+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+$+".schemaPath === undefined) { "+$+'.schemaPath = "'+u+'"; } ',e.opts.verbose&&(t+=" "+$+".schema = "+y+"; "+$+".data = "+f+"; "),t+=" } "):S.errors===!1?t+=" "+oe+" ":(t+=" if ("+g+" == errors) { "+oe+" } else { for (var "+j+"="+g+"; "+j+"<errors; "+j+"++) { var "+$+" = vErrors["+j+"]; if ("+$+".dataPath === undefined) "+$+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+$+".schemaPath === undefined) { "+$+'.schemaPath = "'+u+'"; } ',e.opts.verbose&&(t+=" "+$+".schema = "+y+"; "+$+".data = "+f+"; "),t+=" } } "):N?(t+=" var err = ",e.createErrors!==!1?(t+=" { keyword: '"+(h||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { keyword: '"+_.keyword+"' } ",e.opts.messages!==!1&&(t+=` , message: 'should pass "`+_.keyword+`" keyword validation' `),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ",t+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&p&&(e.async?t+=" throw new ValidationError(vErrors); ":t+=" validate.errors = vErrors; return false; ")):S.errors===!1?t+=" "+oe+" ":(t+=" if (Array.isArray("+k+")) { if (vErrors === null) vErrors = "+k+"; else vErrors = vErrors.concat("+k+"); errors = vErrors.length; for (var "+j+"="+g+"; "+j+"<errors; "+j+"++) { var "+$+" = vErrors["+j+"]; if ("+$+".dataPath === undefined) "+$+".dataPath = (dataPath || '') + "+e.errorPath+"; "+$+'.schemaPath = "'+u+'"; ',e.opts.verbose&&(t+=" "+$+".schema = "+y+"; "+$+".data = "+f+"; "),t+=" } } else { "+oe+" } "),t+=" } ",p&&(t+=" else { ")}return t}});var La=H((ev,zp)=>{zp.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=H((tv,Di)=>{"use strict";var Ai=La();Di.exports={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:Ai.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:Ai.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 Li=H((rv,ki)=>{"use strict";var Zp=/^[a-z_$][a-z0-9_$-]*$/i,Gp=Ni(),Qp=Ci();ki.exports={add:Wp,get:Xp,remove:Kp,validate:ja};function Wp(s,e){var r=this.RULES;if(r.keywords[s])throw new Error("Keyword "+s+" is already defined");if(!Zp.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 t=0;t<a.length;t++)o(s,a[t],e);else o(s,a,e);var n=e.metaSchema;n&&(e.$data&&this._opts.$data&&(n={anyOf:[n,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}),e.validateSchema=this.compile(n,!0))}r.keywords[s]=r.all[s]=!0;function o(i,l,u){for(var p,h=0;h<r.length;h++){var f=r[h];if(f.type==l){p=f;break}}p||(p={type:l,rules:[]},r.push(p));var d={keyword:i,definition:u,custom:!0,code:Gp,implements:u.implements};p.rules.push(d),r.custom[i]=d}return this}function Xp(s){var e=this.RULES.custom[s];return e?e.definition:this.RULES.keywords[s]||!1}function Kp(s){var e=this.RULES;delete e.keywords[s],delete e.all[s],delete e.custom[s];for(var r=0;r<e.length;r++)for(var a=e[r].rules,t=0;t<a.length;t++)if(a[t].keyword==s){a.splice(t,1);break}return this}function ja(s,e){ja.errors=null;var r=this._validateKeyword=this._validateKeyword||this.compile(Qp,!0);if(r(s))return!0;if(ja.errors=r.errors,e)throw new Error("custom keyword definition is invalid: "+this.errorsText(r.errors));return!1}});var ji=H((sv,Jp)=>{Jp.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=H((av,Zi)=>{"use strict";var Mi=vo(),sr=fs(),Yp=yo(),Ui=Sa(),eh=Oa(),th=$o(),rh=xi(),qi=wi(),Bi=rr();Zi.exports=_e;_e.prototype.validate=ah;_e.prototype.compile=nh;_e.prototype.addSchema=oh;_e.prototype.addMetaSchema=ih;_e.prototype.validateSchema=ch;_e.prototype.getSchema=uh;_e.prototype.removeSchema=ph;_e.prototype.addFormat=bh;_e.prototype.errorsText=_h;_e.prototype._addSchema=hh;_e.prototype._compile=fh;_e.prototype.compileAsync=Ii();var xs=Li();_e.prototype.addKeyword=xs.add;_e.prototype.getKeyword=xs.get;_e.prototype.removeKeyword=xs.remove;_e.prototype.validateKeyword=xs.validate;var Vi=ms();_e.ValidationError=Vi.Validation;_e.MissingRefError=Vi.MissingRef;_e.$dataMetaSchema=qi;var Ss="http://json-schema.org/draft-07/schema",Fi=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],sh=["/properties"];function _e(s){if(!(this instanceof _e))return new _e(s);s=this._opts=Bi.copy(s)||{},wh(this),this._schemas={},this._refs={},this._fragments={},this._formats=th(s.format),this._cache=s.cache||new Yp,this._loadingSchemas={},this._compilations=[],this.RULES=rh(),this._getId=mh(s),s.loopRequired=s.loopRequired||1/0,s.errorDataPath=="property"&&(s._errorDataPathProperty=!0),s.serialize===void 0&&(s.serialize=eh),this._metaOpts=Th(this),s.formats&&xh(this),s.keywords&&Rh(this),Eh(this),typeof s.meta=="object"&&this.addMetaSchema(s.meta),s.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),Sh(this)}function ah(s,e){var r;if(typeof s=="string"){if(r=this.getSchema(s),!r)throw new Error('no schema with key or ref "'+s+'"')}else{var a=this._addSchema(s);r=a.validate||this._compile(a)}var t=r(e);return r.$async!==!0&&(this.errors=r.errors),t}function nh(s,e){var r=this._addSchema(s,void 0,e);return r.validate||this._compile(r)}function oh(s,e,r,a){if(Array.isArray(s)){for(var t=0;t<s.length;t++)this.addSchema(s[t],void 0,r,a);return this}var n=this._getId(s);if(n!==void 0&&typeof n!="string")throw new Error("schema id must be string");return e=sr.normalizeId(e||n),zi(this,e),this._schemas[e]=this._addSchema(s,r,a,!0),this}function ih(s,e,r){return this.addSchema(s,e,r,!0),this}function ch(s,e){var r=s.$schema;if(r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this._opts.defaultMeta||lh(this),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;var a=this.validate(r,s);if(!a&&e){var t="schema is invalid: "+this.errorsText();if(this._opts.validateSchema=="log")this.logger.error(t);else throw new Error(t)}return a}function lh(s){var e=s._opts.meta;return s._opts.defaultMeta=typeof e=="object"?s._getId(e)||e:s.getSchema(Ss)?Ss:void 0,s._opts.defaultMeta}function uh(s){var e=Hi(this,s);switch(typeof e){case"object":return e.validate||this._compile(e);case"string":return this.getSchema(e);case"undefined":return dh(this,s)}}function dh(s,e){var r=sr.schema.call(s,{schema:{}},e);if(r){var a=r.schema,t=r.root,n=r.baseId,o=Mi.call(s,a,t,void 0,n);return s._fragments[e]=new Ui({ref:e,fragment:!0,schema:a,root:t,baseId:n,validate:o}),o}}function Hi(s,e){return e=sr.normalizeId(e),s._schemas[e]||s._refs[e]||s._fragments[e]}function ph(s){if(s instanceof RegExp)return Es(this,this._schemas,s),Es(this,this._refs,s),this;switch(typeof s){case"undefined":return Es(this,this._schemas),Es(this,this._refs),this._cache.clear(),this;case"string":var e=Hi(this,s);return e&&this._cache.del(e.cacheKey),delete this._schemas[s],delete this._refs[s],this;case"object":var r=this._opts.serialize,a=r?r(s):s;this._cache.del(a);var t=this._getId(s);t&&(t=sr.normalizeId(t),delete this._schemas[t],delete this._refs[t])}return this}function Es(s,e,r){for(var a in e){var t=e[a];!t.meta&&(!r||r.test(a))&&(s._cache.del(t.cacheKey),delete e[a])}}function hh(s,e,r,a){if(typeof s!="object"&&typeof s!="boolean")throw new Error("schema should be object or boolean");var t=this._opts.serialize,n=t?t(s):s,o=this._cache.get(n);if(o)return o;a=a||this._opts.addUsedSchema!==!1;var i=sr.normalizeId(this._getId(s));i&&a&&zi(this,i);var l=this._opts.validateSchema!==!1&&!e,u;l&&!(u=i&&i==sr.normalizeId(s.$schema))&&this.validateSchema(s,!0);var p=sr.ids.call(this,s),h=new Ui({id:i,schema:s,localRefs:p,cacheKey:n,meta:r});return i[0]!="#"&&a&&(this._refs[i]=h),this._cache.put(n,h),l&&u&&this.validateSchema(s,!0),h}function fh(s,e){if(s.compiling)return s.validate=t,t.schema=s.schema,t.errors=null,t.root=e||t,s.schema.$async===!0&&(t.$async=!0),t;s.compiling=!0;var r;s.meta&&(r=this._opts,this._opts=this._metaOpts);var a;try{a=Mi.call(this,s.schema,e,s.localRefs)}catch(n){throw delete s.validate,n}finally{s.compiling=!1,s.meta&&(this._opts=r)}return s.validate=a,s.refs=a.refs,s.refVal=a.refVal,s.root=a.root,a;function t(){var n=s.validate,o=n.apply(this,arguments);return t.errors=n.errors,o}}function mh(s){switch(s.schemaId){case"auto":return yh;case"id":return vh;default:return gh}}function vh(s){return s.$id&&this.logger.warn("schema $id ignored",s.$id),s.id}function gh(s){return s.id&&this.logger.warn("schema id ignored",s.id),s.$id}function yh(s){if(s.$id&&s.id&&s.$id!=s.id)throw new Error("schema $id is different from id");return s.$id||s.id}function _h(s,e){if(s=s||this.errors,!s)return"No errors";e=e||{};for(var r=e.separator===void 0?", ":e.separator,a=e.dataVar===void 0?"data":e.dataVar,t="",n=0;n<s.length;n++){var o=s[n];o&&(t+=a+o.dataPath+" "+o.message+r)}return t.slice(0,-r.length)}function bh(s,e){return typeof e=="string"&&(e=new RegExp(e)),this._formats[s]=e,this}function Eh(s){var e;if(s._opts.$data&&(e=ji(),s.addMetaSchema(e,e.$id,!0)),s._opts.meta!==!1){var r=La();s._opts.$data&&(r=qi(r,sh)),s.addMetaSchema(r,Ss,!0),s._refs["http://json-schema.org/schema"]=Ss}}function Sh(s){var e=s._opts.schemas;if(e)if(Array.isArray(e))s.addSchema(e);else for(var r in e)s.addSchema(e[r],r)}function xh(s){for(var e in s._opts.formats){var r=s._opts.formats[e];s.addFormat(e,r)}}function Rh(s){for(var e in s._opts.keywords){var r=s._opts.keywords[e];s.addKeyword(e,r)}}function zi(s,e){if(s._schemas[e]||s._refs[e])throw new Error('schema with key or id "'+e+'" already exists')}function Th(s){for(var e=Bi.copy(s._opts),r=0;r<Fi.length;r++)delete e[Fi[r]];return e}function wh(s){var e=s._opts.logger;if(e===!1)s.logger={log:Fa,warn:Fa,error:Fa};else{if(e===void 0&&(e=console),!(typeof e=="object"&&e.log&&e.warn&&e.error))throw new Error("logger must implement log, warn and error methods");s.logger=e}}function Fa(){}});var ec=H((vv,Yi)=>{Yi.exports=Ji;Ji.sync=Ih;var Xi=Rt("fs");function Oh(s,e){var r=e.pathExt!==void 0?e.pathExt:process.env.PATHEXT;if(!r||(r=r.split(";"),r.indexOf("")!==-1))return!0;for(var a=0;a<r.length;a++){var t=r[a].toLowerCase();if(t&&s.substr(-t.length).toLowerCase()===t)return!0}return!1}function Ki(s,e,r){return!s.isSymbolicLink()&&!s.isFile()?!1:Oh(e,r)}function Ji(s,e,r){Xi.stat(s,function(a,t){r(a,a?!1:Ki(t,s,e))})}function Ih(s,e){return Ki(Xi.statSync(s),s,e)}});var nc=H((gv,ac)=>{ac.exports=rc;rc.sync=$h;var tc=Rt("fs");function rc(s,e,r){tc.stat(s,function(a,t){r(a,a?!1:sc(t,e))})}function $h(s,e){return sc(tc.statSync(s),e)}function sc(s,e){return s.isFile()&&Nh(s,e)}function Nh(s,e){var r=s.mode,a=s.uid,t=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),p=i|l,h=r&u||r&l&&t===o||r&i&&a===n||r&p&&n===0;return h}});var ic=H((_v,oc)=>{var yv=Rt("fs"),Os;process.platform==="win32"||global.TESTING_WINDOWS?Os=ec():Os=nc();oc.exports=Ua;Ua.sync=Ah;function Ua(s,e,r){if(typeof e=="function"&&(r=e,e={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(a,t){Ua(s,e||{},function(n,o){n?t(n):a(o)})})}Os(s,e||{},function(a,t){a&&(a.code==="EACCES"||e&&e.ignoreErrors)&&(a=null,t=!1),r(a,t)})}function Ah(s,e){try{return Os.sync(s,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var fc=H((bv,hc)=>{var Sr=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",cc=Rt("path"),Dh=Sr?";":":",lc=ic(),uc=s=>Object.assign(new Error(`not found: ${s}`),{code:"ENOENT"}),dc=(s,e)=>{let r=e.colon||Dh,a=s.match(/\//)||Sr&&s.match(/\\/)?[""]:[...Sr?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],t=Sr?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",n=Sr?t.split(r):[""];return Sr&&s.indexOf(".")!==-1&&n[0]!==""&&n.unshift(""),{pathEnv:a,pathExt:n,pathExtExe:t}},pc=(s,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});let{pathEnv:a,pathExt:t,pathExtExe:n}=dc(s,e),o=[],i=u=>new Promise((p,h)=>{if(u===a.length)return e.all&&o.length?p(o):h(uc(s));let f=a[u],d=/^".*"$/.test(f)?f.slice(1,-1):f,g=cc.join(d,s),v=!d&&/^\.[\\\/]/.test(s)?s.slice(0,2)+g:g;p(l(v,u,0))}),l=(u,p,h)=>new Promise((f,d)=>{if(h===t.length)return f(i(p+1));let g=t[h];lc(u+g,{pathExt:n},(v,y)=>{if(!v&&y)if(e.all)o.push(u+g);else return f(u+g);return f(l(u,p,h+1))})});return r?i(0).then(u=>r(null,u),r):i(0)},Ch=(s,e)=>{e=e||{};let{pathEnv:r,pathExt:a,pathExtExe:t}=dc(s,e),n=[];for(let o=0;o<r.length;o++){let i=r[o],l=/^".*"$/.test(i)?i.slice(1,-1):i,u=cc.join(l,s),p=!l&&/^\.[\\\/]/.test(s)?s.slice(0,2)+u:u;for(let h=0;h<a.length;h++){let f=p+a[h];try{if(lc.sync(f,{pathExt:t}))if(e.all)n.push(f);else return f}catch{}}}if(e.all&&n.length)return n;if(e.nothrow)return null;throw uc(s)};hc.exports=pc;pc.sync=Ch});var vc=H((Ev,qa)=>{"use strict";var mc=(s={})=>{let e=s.env||process.env;return(s.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(a=>a.toUpperCase()==="PATH")||"Path"};qa.exports=mc;qa.exports.default=mc});var bc=H((Sv,_c)=>{"use strict";var gc=Rt("path"),kh=fc(),Lh=vc();function yc(s,e){let r=s.options.env||process.env,a=process.cwd(),t=s.options.cwd!=null,n=t&&process.chdir!==void 0&&!process.chdir.disabled;if(n)try{process.chdir(s.options.cwd)}catch{}let o;try{o=kh.sync(s.command,{path:r[Lh({env:r})],pathExt:e?gc.delimiter:void 0})}catch{}finally{n&&process.chdir(a)}return o&&(o=gc.resolve(t?s.options.cwd:"",o)),o}function jh(s){return yc(s)||yc(s,!0)}_c.exports=jh});var Ec=H((xv,Va)=>{"use strict";var Ba=/([()\][%!^"`<>&|;, *?])/g;function Fh(s){return s=s.replace(Ba,"^$1"),s}function Mh(s,e){return s=`${s}`,s=s.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),s=s.replace(/(?=(\\+?)?)\1$/,"$1$1"),s=`"${s}"`,s=s.replace(Ba,"^$1"),e&&(s=s.replace(Ba,"^$1")),s}Va.exports.command=Fh;Va.exports.argument=Mh});var xc=H((Rv,Sc)=>{"use strict";Sc.exports=/^#!(.*)/});var Tc=H((Tv,Rc)=>{"use strict";var Uh=xc();Rc.exports=(s="")=>{let e=s.match(Uh);if(!e)return null;let[r,a]=e[0].replace(/#! ?/,"").split(" "),t=r.split("/").pop();return t==="env"?a:a?`${t} ${a}`:t}});var Pc=H((wv,wc)=>{"use strict";var Ha=Rt("fs"),qh=Tc();function Bh(s){let r=Buffer.alloc(150),a;try{a=Ha.openSync(s,"r"),Ha.readSync(a,r,0,150,0),Ha.closeSync(a)}catch{}return qh(r.toString())}wc.exports=Bh});var Nc=H((Pv,$c)=>{"use strict";var Vh=Rt("path"),Oc=bc(),Ic=Ec(),Hh=Pc(),zh=process.platform==="win32",Zh=/\.(?:com|exe)$/i,Gh=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Qh(s){s.file=Oc(s);let e=s.file&&Hh(s.file);return e?(s.args.unshift(s.file),s.command=e,Oc(s)):s.file}function Wh(s){if(!zh)return s;let e=Qh(s),r=!Zh.test(e);if(s.options.forceShell||r){let a=Gh.test(e);s.command=Vh.normalize(s.command),s.command=Ic.command(s.command),s.args=s.args.map(n=>Ic.argument(n,a));let t=[s.command].concat(s.args).join(" ");s.args=["/d","/s","/c",`"${t}"`],s.command=process.env.comspec||"cmd.exe",s.options.windowsVerbatimArguments=!0}return s}function Xh(s,e,r){e&&!Array.isArray(e)&&(r=e,e=null),e=e?e.slice(0):[],r=Object.assign({},r);let a={command:s,args:e,options:r,file:void 0,original:{command:s,args:e}};return r.shell?a:Wh(a)}$c.exports=Xh});var Cc=H((Ov,Dc)=>{"use strict";var za=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 Kh(s,e){if(!za)return;let r=s.emit;s.emit=function(a,t){if(a==="exit"){let n=Ac(t,e);if(n)return r.call(s,"error",n)}return r.apply(s,arguments)}}function Ac(s,e){return za&&s===1&&!e.file?Za(e.original,"spawn"):null}function Jh(s,e){return za&&s===1&&!e.file?Za(e.original,"spawnSync"):null}Dc.exports={hookChildProcess:Kh,verifyENOENT:Ac,verifyENOENTSync:Jh,notFoundError:Za}});var jc=H((Iv,xr)=>{"use strict";var kc=Rt("child_process"),Ga=Nc(),Qa=Cc();function Lc(s,e,r){let a=Ga(s,e,r),t=kc.spawn(a.command,a.args,a.options);return Qa.hookChildProcess(t,a),t}function Yh(s,e,r){let a=Ga(s,e,r),t=kc.spawnSync(a.command,a.args,a.options);return t.error=t.error||Qa.verifyENOENTSync(t.status,a),t}xr.exports=Lc;xr.exports.spawn=Lc;xr.exports.sync=Yh;xr.exports._parse=Ga;xr.exports._enoent=Qa});var c={};Wl(c,{BRAND:()=>Su,DIRTY:()=>Ut,EMPTY_PATH:()=>eu,INVALID:()=>Z,NEVER:()=>od,OK:()=>$e,ParseStatus:()=>Pe,Schema:()=>J,ZodAny:()=>Pt,ZodArray:()=>bt,ZodBigInt:()=>Bt,ZodBoolean:()=>Vt,ZodBranded:()=>Ar,ZodCatch:()=>er,ZodDate:()=>Ht,ZodDefault:()=>Yt,ZodDiscriminatedUnion:()=>Gr,ZodEffects:()=>We,ZodEnum:()=>Kt,ZodError:()=>Fe,ZodFirstPartyTypeKind:()=>C,ZodFunction:()=>Wr,ZodIntersection:()=>Qt,ZodIssueCode:()=>D,ZodLazy:()=>Wt,ZodLiteral:()=>Xt,ZodMap:()=>gr,ZodNaN:()=>_r,ZodNativeEnum:()=>Jt,ZodNever:()=>tt,ZodNull:()=>Zt,ZodNullable:()=>ut,ZodNumber:()=>qt,ZodObject:()=>Me,ZodOptional:()=>Ge,ZodParsedType:()=>q,ZodPipeline:()=>Dr,ZodPromise:()=>Ot,ZodReadonly:()=>tr,ZodRecord:()=>Qr,ZodSchema:()=>J,ZodSet:()=>yr,ZodString:()=>wt,ZodSymbol:()=>mr,ZodTransformer:()=>We,ZodTuple:()=>lt,ZodType:()=>J,ZodUndefined:()=>zt,ZodUnion:()=>Gt,ZodUnknown:()=>_t,ZodVoid:()=>vr,addIssueToContext:()=>U,any:()=>Nu,array:()=>ku,bigint:()=>wu,boolean:()=>In,coerce:()=>nd,custom:()=>wn,date:()=>Pu,datetimeRegex:()=>Rn,defaultErrorMap:()=>gt,discriminatedUnion:()=>Mu,effect:()=>Ku,enum:()=>Qu,function:()=>zu,getErrorMap:()=>pr,getParsedType:()=>ct,instanceof:()=>Ru,intersection:()=>Uu,isAborted:()=>zr,isAsync:()=>hr,isDirty:()=>Zr,isValid:()=>Tt,late:()=>xu,lazy:()=>Zu,literal:()=>Gu,makeIssue:()=>Nr,map:()=>Vu,nan:()=>Tu,nativeEnum:()=>Wu,never:()=>Du,null:()=>$u,nullable:()=>Yu,number:()=>On,object:()=>Lu,objectUtil:()=>zs,oboolean:()=>ad,onumber:()=>sd,optional:()=>Ju,ostring:()=>rd,pipeline:()=>td,preprocess:()=>ed,promise:()=>Xu,quotelessJson:()=>Kl,record:()=>Bu,set:()=>Hu,setErrorMap:()=>Yl,strictObject:()=>ju,string:()=>Pn,symbol:()=>Ou,transformer:()=>Ku,tuple:()=>qu,undefined:()=>Iu,union:()=>Fu,unknown:()=>Au,util:()=>te,void:()=>Cu});var te;(function(s){s.assertEqual=t=>{};function e(t){}s.assertIs=e;function r(t){throw new Error}s.assertNever=r,s.arrayToEnum=t=>{let n={};for(let o of t)n[o]=o;return n},s.getValidEnumValues=t=>{let n=s.objectKeys(t).filter(i=>typeof t[t[i]]!="number"),o={};for(let i of n)o[i]=t[i];return s.objectValues(o)},s.objectValues=t=>s.objectKeys(t).map(function(n){return t[n]}),s.objectKeys=typeof Object.keys=="function"?t=>Object.keys(t):t=>{let n=[];for(let o in t)Object.prototype.hasOwnProperty.call(t,o)&&n.push(o);return n},s.find=(t,n)=>{for(let o of t)if(n(o))return o},s.isInteger=typeof Number.isInteger=="function"?t=>Number.isInteger(t):t=>typeof t=="number"&&Number.isFinite(t)&&Math.floor(t)===t;function a(t,n=" | "){return t.map(o=>typeof o=="string"?`'${o}'`:o).join(n)}s.joinValues=a,s.jsonStringifyReplacer=(t,n)=>typeof n=="bigint"?n.toString():n})(te||(te={}));var zs;(function(s){s.mergeShapes=(e,r)=>({...e,...r})})(zs||(zs={}));var q=te.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ct=s=>{switch(typeof s){case"undefined":return q.undefined;case"string":return q.string;case"number":return Number.isNaN(s)?q.nan:q.number;case"boolean":return q.boolean;case"function":return q.function;case"bigint":return q.bigint;case"symbol":return q.symbol;case"object":return Array.isArray(s)?q.array:s===null?q.null:s.then&&typeof s.then=="function"&&s.catch&&typeof s.catch=="function"?q.promise:typeof Map<"u"&&s instanceof Map?q.map:typeof Set<"u"&&s instanceof Set?q.set:typeof Date<"u"&&s instanceof Date?q.date:q.object;default:return q.unknown}};var D=te.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"]),Kl=s=>JSON.stringify(s,null,2).replace(/"([^"]+)":/g,"$1:"),Fe=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 r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(n){return n.message},a={_errors:[]},t=n=>{for(let o of n.issues)if(o.code==="invalid_union")o.unionErrors.map(t);else if(o.code==="invalid_return_type")t(o.returnTypeError);else if(o.code==="invalid_arguments")t(o.argumentsError);else if(o.path.length===0)a._errors.push(r(o));else{let i=a,l=0;for(;l<o.path.length;){let u=o.path[l];l===o.path.length-1?(i[u]=i[u]||{_errors:[]},i[u]._errors.push(r(o))):i[u]=i[u]||{_errors:[]},i=i[u],l++}}};return t(this),a}static assert(e){if(!(e instanceof s))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,te.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},a=[];for(let t of this.issues)if(t.path.length>0){let n=t.path[0];r[n]=r[n]||[],r[n].push(e(t))}else a.push(e(t));return{formErrors:a,fieldErrors:r}}get formErrors(){return this.flatten()}};Fe.create=s=>new Fe(s);var Jl=(s,e)=>{let r;switch(s.code){case D.invalid_type:s.received===q.undefined?r="Required":r=`Expected ${s.expected}, received ${s.received}`;break;case D.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(s.expected,te.jsonStringifyReplacer)}`;break;case D.unrecognized_keys:r=`Unrecognized key(s) in object: ${te.joinValues(s.keys,", ")}`;break;case D.invalid_union:r="Invalid input";break;case D.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${te.joinValues(s.options)}`;break;case D.invalid_enum_value:r=`Invalid enum value. Expected ${te.joinValues(s.options)}, received '${s.received}'`;break;case D.invalid_arguments:r="Invalid function arguments";break;case D.invalid_return_type:r="Invalid function return type";break;case D.invalid_date:r="Invalid date";break;case D.invalid_string:typeof s.validation=="object"?"includes"in s.validation?(r=`Invalid input: must include "${s.validation.includes}"`,typeof s.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${s.validation.position}`)):"startsWith"in s.validation?r=`Invalid input: must start with "${s.validation.startsWith}"`:"endsWith"in s.validation?r=`Invalid input: must end with "${s.validation.endsWith}"`:te.assertNever(s.validation):s.validation!=="regex"?r=`Invalid ${s.validation}`:r="Invalid";break;case D.too_small:s.type==="array"?r=`Array must contain ${s.exact?"exactly":s.inclusive?"at least":"more than"} ${s.minimum} element(s)`:s.type==="string"?r=`String must contain ${s.exact?"exactly":s.inclusive?"at least":"over"} ${s.minimum} character(s)`:s.type==="number"?r=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="bigint"?r=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="date"?r=`Date must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(s.minimum))}`:r="Invalid input";break;case D.too_big:s.type==="array"?r=`Array must contain ${s.exact?"exactly":s.inclusive?"at most":"less than"} ${s.maximum} element(s)`:s.type==="string"?r=`String must contain ${s.exact?"exactly":s.inclusive?"at most":"under"} ${s.maximum} character(s)`:s.type==="number"?r=`Number must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="bigint"?r=`BigInt must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="date"?r=`Date must be ${s.exact?"exactly":s.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(s.maximum))}`:r="Invalid input";break;case D.custom:r="Invalid input";break;case D.invalid_intersection_types:r="Intersection results could not be merged";break;case D.not_multiple_of:r=`Number must be a multiple of ${s.multipleOf}`;break;case D.not_finite:r="Number must be finite";break;default:r=e.defaultError,te.assertNever(s)}return{message:r}},gt=Jl;var _n=gt;function Yl(s){_n=s}function pr(){return _n}var Nr=s=>{let{data:e,path:r,errorMaps:a,issueData:t}=s,n=[...r,...t.path||[]],o={...t,path:n};if(t.message!==void 0)return{...t,path:n,message:t.message};let i="",l=a.filter(u=>!!u).slice().reverse();for(let u of l)i=u(o,{data:e,defaultError:i}).message;return{...t,path:n,message:i}},eu=[];function U(s,e){let r=pr(),a=Nr({issueData:e,data:s.data,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,r,r===gt?void 0:gt].filter(t=>!!t)});s.common.issues.push(a)}var Pe=class s{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let a=[];for(let t of r){if(t.status==="aborted")return Z;t.status==="dirty"&&e.dirty(),a.push(t.value)}return{status:e.value,value:a}}static async mergeObjectAsync(e,r){let a=[];for(let t of r){let n=await t.key,o=await t.value;a.push({key:n,value:o})}return s.mergeObjectSync(e,a)}static mergeObjectSync(e,r){let a={};for(let t of r){let{key:n,value:o}=t;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"||t.alwaysSet)&&(a[n.value]=o.value)}return{status:e.value,value:a}}},Z=Object.freeze({status:"aborted"}),Ut=s=>({status:"dirty",value:s}),$e=s=>({status:"valid",value:s}),zr=s=>s.status==="aborted",Zr=s=>s.status==="dirty",Tt=s=>s.status==="valid",hr=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 Qe=class{constructor(e,r,a,t){this._cachedPath=[],this.parent=e,this.data=r,this._path=a,this._key=t}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}},bn=(s,e)=>{if(Tt(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 r=new Fe(s.common.issues);return this._error=r,this._error}}};function X(s){if(!s)return{};let{errorMap:e,invalid_type_error:r,required_error:a,description:t}=s;if(e&&(r||a))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:t}:{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??r??i.defaultError}},description:t}}var J=class{get description(){return this._def.description}_getType(e){return ct(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:ct(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Pe,ctx:{common:e.parent.common,data:e.data,parsedType:ct(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(hr(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let a=this.safeParse(e,r);if(a.success)return a.data;throw a.error}safeParse(e,r){let a={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ct(e)},t=this._parseSync({data:e,path:a.path,parent:a});return bn(a,t)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ct(e)};if(!this["~standard"].async)try{let a=this._parseSync({data:e,path:[],parent:r});return Tt(a)?{value:a.value}:{issues:r.common.issues}}catch(a){a?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(a=>Tt(a)?{value:a.value}:{issues:r.common.issues})}async parseAsync(e,r){let a=await this.safeParseAsync(e,r);if(a.success)return a.data;throw a.error}async safeParseAsync(e,r){let a={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ct(e)},t=this._parse({data:e,path:a.path,parent:a}),n=await(hr(t)?t:Promise.resolve(t));return bn(a,n)}refine(e,r){let a=t=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(t):r;return this._refinement((t,n)=>{let o=e(t),i=()=>n.addIssue({code:D.custom,...a(t)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(i(),!1)):o?!0:(i(),!1)})}refinement(e,r){return this._refinement((a,t)=>e(a)?!0:(t.addIssue(typeof r=="function"?r(a,t):r),!1))}_refinement(e){return new We({schema:this,typeName:C.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Ge.create(this,this._def)}nullable(){return ut.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return bt.create(this)}promise(){return Ot.create(this,this._def)}or(e){return Gt.create([this,e],this._def)}and(e){return Qt.create(this,e,this._def)}transform(e){return new We({...X(this._def),schema:this,typeName:C.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Yt({...X(this._def),innerType:this,defaultValue:r,typeName:C.ZodDefault})}brand(){return new Ar({typeName:C.ZodBranded,type:this,...X(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new er({...X(this._def),innerType:this,catchValue:r,typeName:C.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Dr.create(this,e)}readonly(){return tr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},tu=/^c[^\s-]{8,}$/i,ru=/^[0-9a-z]+$/,su=/^[0-9A-HJKMNP-TV-Z]{26}$/i,au=/^[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,nu=/^[a-z0-9_-]{21}$/i,ou=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,iu=/^[-+]?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)?)??$/,cu=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,lu="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Zs,uu=/^(?:(?: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])$/,du=/^(?:(?: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])$/,pu=/^(([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]))$/,hu=/^(([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])$/,fu=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,mu=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Sn="((\\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])))",vu=new RegExp(`^${Sn}$`);function xn(s){let e="[0-5]\\d";s.precision?e=`${e}\\.\\d{${s.precision}}`:s.precision==null&&(e=`${e}(\\.\\d+)?`);let r=s.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function gu(s){return new RegExp(`^${xn(s)}$`)}function Rn(s){let e=`${Sn}T${xn(s)}`,r=[];return r.push(s.local?"Z?":"Z"),s.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function yu(s,e){return!!((e==="v4"||!e)&&uu.test(s)||(e==="v6"||!e)&&pu.test(s))}function _u(s,e){if(!ou.test(s))return!1;try{let[r]=s.split(".");if(!r)return!1;let a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),t=JSON.parse(atob(a));return!(typeof t!="object"||t===null||"typ"in t&&t?.typ!=="JWT"||!t.alg||e&&t.alg!==e)}catch{return!1}}function bu(s,e){return!!((e==="v4"||!e)&&du.test(s)||(e==="v6"||!e)&&hu.test(s))}var wt=class s extends J{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==q.string){let n=this._getOrReturnCtx(e);return U(n,{code:D.invalid_type,expected:q.string,received:n.parsedType}),Z}let a=new Pe,t;for(let n of this._def.checks)if(n.kind==="min")e.data.length<n.value&&(t=this._getOrReturnCtx(e,t),U(t,{code:D.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),a.dirty());else if(n.kind==="max")e.data.length>n.value&&(t=this._getOrReturnCtx(e,t),U(t,{code:D.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.length<n.value;(o||i)&&(t=this._getOrReturnCtx(e,t),o?U(t,{code:D.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):i&&U(t,{code:D.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),a.dirty())}else if(n.kind==="email")cu.test(e.data)||(t=this._getOrReturnCtx(e,t),U(t,{validation:"email",code:D.invalid_string,message:n.message}),a.dirty());else if(n.kind==="emoji")Zs||(Zs=new RegExp(lu,"u")),Zs.test(e.data)||(t=this._getOrReturnCtx(e,t),U(t,{validation:"emoji",code:D.invalid_string,message:n.message}),a.dirty());else if(n.kind==="uuid")au.test(e.data)||(t=this._getOrReturnCtx(e,t),U(t,{validation:"uuid",code:D.invalid_string,message:n.message}),a.dirty());else if(n.kind==="nanoid")nu.test(e.data)||(t=this._getOrReturnCtx(e,t),U(t,{validation:"nanoid",code:D.invalid_string,message:n.message}),a.dirty());else if(n.kind==="cuid")tu.test(e.data)||(t=this._getOrReturnCtx(e,t),U(t,{validation:"cuid",code:D.invalid_string,message:n.message}),a.dirty());else if(n.kind==="cuid2")ru.test(e.data)||(t=this._getOrReturnCtx(e,t),U(t,{validation:"cuid2",code:D.invalid_string,message:n.message}),a.dirty());else if(n.kind==="ulid")su.test(e.data)||(t=this._getOrReturnCtx(e,t),U(t,{validation:"ulid",code:D.invalid_string,message:n.message}),a.dirty());else if(n.kind==="url")try{new URL(e.data)}catch{t=this._getOrReturnCtx(e,t),U(t,{validation:"url",code:D.invalid_string,message:n.message}),a.dirty()}else n.kind==="regex"?(n.regex.lastIndex=0,n.regex.test(e.data)||(t=this._getOrReturnCtx(e,t),U(t,{validation:"regex",code:D.invalid_string,message:n.message}),a.dirty())):n.kind==="trim"?e.data=e.data.trim():n.kind==="includes"?e.data.includes(n.value,n.position)||(t=this._getOrReturnCtx(e,t),U(t,{code:D.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),a.dirty()):n.kind==="toLowerCase"?e.data=e.data.toLowerCase():n.kind==="toUpperCase"?e.data=e.data.toUpperCase():n.kind==="startsWith"?e.data.startsWith(n.value)||(t=this._getOrReturnCtx(e,t),U(t,{code:D.invalid_string,validation:{startsWith:n.value},message:n.message}),a.dirty()):n.kind==="endsWith"?e.data.endsWith(n.value)||(t=this._getOrReturnCtx(e,t),U(t,{code:D.invalid_string,validation:{endsWith:n.value},message:n.message}),a.dirty()):n.kind==="datetime"?Rn(n).test(e.data)||(t=this._getOrReturnCtx(e,t),U(t,{code:D.invalid_string,validation:"datetime",message:n.message}),a.dirty()):n.kind==="date"?vu.test(e.data)||(t=this._getOrReturnCtx(e,t),U(t,{code:D.invalid_string,validation:"date",message:n.message}),a.dirty()):n.kind==="time"?gu(n).test(e.data)||(t=this._getOrReturnCtx(e,t),U(t,{code:D.invalid_string,validation:"time",message:n.message}),a.dirty()):n.kind==="duration"?iu.test(e.data)||(t=this._getOrReturnCtx(e,t),U(t,{validation:"duration",code:D.invalid_string,message:n.message}),a.dirty()):n.kind==="ip"?yu(e.data,n.version)||(t=this._getOrReturnCtx(e,t),U(t,{validation:"ip",code:D.invalid_string,message:n.message}),a.dirty()):n.kind==="jwt"?_u(e.data,n.alg)||(t=this._getOrReturnCtx(e,t),U(t,{validation:"jwt",code:D.invalid_string,message:n.message}),a.dirty()):n.kind==="cidr"?bu(e.data,n.version)||(t=this._getOrReturnCtx(e,t),U(t,{validation:"cidr",code:D.invalid_string,message:n.message}),a.dirty()):n.kind==="base64"?fu.test(e.data)||(t=this._getOrReturnCtx(e,t),U(t,{validation:"base64",code:D.invalid_string,message:n.message}),a.dirty()):n.kind==="base64url"?mu.test(e.data)||(t=this._getOrReturnCtx(e,t),U(t,{validation:"base64url",code:D.invalid_string,message:n.message}),a.dirty()):te.assertNever(n);return{status:a.value,value:e.data}}_regex(e,r,a){return this.refinement(t=>e.test(t),{validation:r,code:D.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,r){return this._addCheck({kind:"regex",regex:e,...V.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...V.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...V.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...V.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...V.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...V.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...V.errToObj(r)})}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 r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};wt.create=s=>new wt({checks:[],typeName:C.ZodString,coerce:s?.coerce??!1,...X(s)});function Eu(s,e){let r=(s.toString().split(".")[1]||"").length,a=(e.toString().split(".")[1]||"").length,t=r>a?r:a,n=Number.parseInt(s.toFixed(t).replace(".","")),o=Number.parseInt(e.toFixed(t).replace(".",""));return n%o/10**t}var qt=class s extends J{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)!==q.number){let n=this._getOrReturnCtx(e);return U(n,{code:D.invalid_type,expected:q.number,received:n.parsedType}),Z}let a,t=new Pe;for(let n of this._def.checks)n.kind==="int"?te.isInteger(e.data)||(a=this._getOrReturnCtx(e,a),U(a,{code:D.invalid_type,expected:"integer",received:"float",message:n.message}),t.dirty()):n.kind==="min"?(n.inclusive?e.data<n.value:e.data<=n.value)&&(a=this._getOrReturnCtx(e,a),U(a,{code:D.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),t.dirty()):n.kind==="max"?(n.inclusive?e.data>n.value:e.data>=n.value)&&(a=this._getOrReturnCtx(e,a),U(a,{code:D.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),t.dirty()):n.kind==="multipleOf"?Eu(e.data,n.value)!==0&&(a=this._getOrReturnCtx(e,a),U(a,{code:D.not_multiple_of,multipleOf:n.value,message:n.message}),t.dirty()):n.kind==="finite"?Number.isFinite(e.data)||(a=this._getOrReturnCtx(e,a),U(a,{code:D.not_finite,message:n.message}),t.dirty()):te.assertNever(n);return{status:t.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,V.toString(r))}gt(e,r){return this.setLimit("min",e,!1,V.toString(r))}lte(e,r){return this.setLimit("max",e,!0,V.toString(r))}lt(e,r){return this.setLimit("max",e,!1,V.toString(r))}setLimit(e,r,a,t){return new s({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:a,message:V.toString(t)}]})}_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,r){return this._addCheck({kind:"multipleOf",value:e,message:V.toString(r)})}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 r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&te.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let a of this._def.checks){if(a.kind==="finite"||a.kind==="int"||a.kind==="multipleOf")return!0;a.kind==="min"?(r===null||a.value>r)&&(r=a.value):a.kind==="max"&&(e===null||a.value<e)&&(e=a.value)}return Number.isFinite(r)&&Number.isFinite(e)}};qt.create=s=>new qt({checks:[],typeName:C.ZodNumber,coerce:s?.coerce||!1,...X(s)});var Bt=class s extends J{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)!==q.bigint)return this._getInvalidInput(e);let a,t=new Pe;for(let n of this._def.checks)n.kind==="min"?(n.inclusive?e.data<n.value:e.data<=n.value)&&(a=this._getOrReturnCtx(e,a),U(a,{code:D.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),t.dirty()):n.kind==="max"?(n.inclusive?e.data>n.value:e.data>=n.value)&&(a=this._getOrReturnCtx(e,a),U(a,{code:D.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),t.dirty()):n.kind==="multipleOf"?e.data%n.value!==BigInt(0)&&(a=this._getOrReturnCtx(e,a),U(a,{code:D.not_multiple_of,multipleOf:n.value,message:n.message}),t.dirty()):te.assertNever(n);return{status:t.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return U(r,{code:D.invalid_type,expected:q.bigint,received:r.parsedType}),Z}gte(e,r){return this.setLimit("min",e,!0,V.toString(r))}gt(e,r){return this.setLimit("min",e,!1,V.toString(r))}lte(e,r){return this.setLimit("max",e,!0,V.toString(r))}lt(e,r){return this.setLimit("max",e,!1,V.toString(r))}setLimit(e,r,a,t){return new s({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:a,message:V.toString(t)}]})}_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,r){return this._addCheck({kind:"multipleOf",value:e,message:V.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Bt.create=s=>new Bt({checks:[],typeName:C.ZodBigInt,coerce:s?.coerce??!1,...X(s)});var Vt=class extends J{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==q.boolean){let a=this._getOrReturnCtx(e);return U(a,{code:D.invalid_type,expected:q.boolean,received:a.parsedType}),Z}return $e(e.data)}};Vt.create=s=>new Vt({typeName:C.ZodBoolean,coerce:s?.coerce||!1,...X(s)});var Ht=class s extends J{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==q.date){let n=this._getOrReturnCtx(e);return U(n,{code:D.invalid_type,expected:q.date,received:n.parsedType}),Z}if(Number.isNaN(e.data.getTime())){let n=this._getOrReturnCtx(e);return U(n,{code:D.invalid_date}),Z}let a=new Pe,t;for(let n of this._def.checks)n.kind==="min"?e.data.getTime()<n.value&&(t=this._getOrReturnCtx(e,t),U(t,{code:D.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),a.dirty()):n.kind==="max"?e.data.getTime()>n.value&&(t=this._getOrReturnCtx(e,t),U(t,{code:D.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),a.dirty()):te.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,r){return this._addCheck({kind:"min",value:e.getTime(),message:V.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:V.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Ht.create=s=>new Ht({checks:[],coerce:s?.coerce||!1,typeName:C.ZodDate,...X(s)});var mr=class extends J{_parse(e){if(this._getType(e)!==q.symbol){let a=this._getOrReturnCtx(e);return U(a,{code:D.invalid_type,expected:q.symbol,received:a.parsedType}),Z}return $e(e.data)}};mr.create=s=>new mr({typeName:C.ZodSymbol,...X(s)});var zt=class extends J{_parse(e){if(this._getType(e)!==q.undefined){let a=this._getOrReturnCtx(e);return U(a,{code:D.invalid_type,expected:q.undefined,received:a.parsedType}),Z}return $e(e.data)}};zt.create=s=>new zt({typeName:C.ZodUndefined,...X(s)});var Zt=class extends J{_parse(e){if(this._getType(e)!==q.null){let a=this._getOrReturnCtx(e);return U(a,{code:D.invalid_type,expected:q.null,received:a.parsedType}),Z}return $e(e.data)}};Zt.create=s=>new Zt({typeName:C.ZodNull,...X(s)});var Pt=class extends J{constructor(){super(...arguments),this._any=!0}_parse(e){return $e(e.data)}};Pt.create=s=>new Pt({typeName:C.ZodAny,...X(s)});var _t=class extends J{constructor(){super(...arguments),this._unknown=!0}_parse(e){return $e(e.data)}};_t.create=s=>new _t({typeName:C.ZodUnknown,...X(s)});var tt=class extends J{_parse(e){let r=this._getOrReturnCtx(e);return U(r,{code:D.invalid_type,expected:q.never,received:r.parsedType}),Z}};tt.create=s=>new tt({typeName:C.ZodNever,...X(s)});var vr=class extends J{_parse(e){if(this._getType(e)!==q.undefined){let a=this._getOrReturnCtx(e);return U(a,{code:D.invalid_type,expected:q.void,received:a.parsedType}),Z}return $e(e.data)}};vr.create=s=>new vr({typeName:C.ZodVoid,...X(s)});var bt=class s extends J{_parse(e){let{ctx:r,status:a}=this._processInputParams(e),t=this._def;if(r.parsedType!==q.array)return U(r,{code:D.invalid_type,expected:q.array,received:r.parsedType}),Z;if(t.exactLength!==null){let o=r.data.length>t.exactLength.value,i=r.data.length<t.exactLength.value;(o||i)&&(U(r,{code:o?D.too_big:D.too_small,minimum:i?t.exactLength.value:void 0,maximum:o?t.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:t.exactLength.message}),a.dirty())}if(t.minLength!==null&&r.data.length<t.minLength.value&&(U(r,{code:D.too_small,minimum:t.minLength.value,type:"array",inclusive:!0,exact:!1,message:t.minLength.message}),a.dirty()),t.maxLength!==null&&r.data.length>t.maxLength.value&&(U(r,{code:D.too_big,maximum:t.maxLength.value,type:"array",inclusive:!0,exact:!1,message:t.maxLength.message}),a.dirty()),r.common.async)return Promise.all([...r.data].map((o,i)=>t.type._parseAsync(new Qe(r,o,r.path,i)))).then(o=>Pe.mergeArray(a,o));let n=[...r.data].map((o,i)=>t.type._parseSync(new Qe(r,o,r.path,i)));return Pe.mergeArray(a,n)}get element(){return this._def.type}min(e,r){return new s({...this._def,minLength:{value:e,message:V.toString(r)}})}max(e,r){return new s({...this._def,maxLength:{value:e,message:V.toString(r)}})}length(e,r){return new s({...this._def,exactLength:{value:e,message:V.toString(r)}})}nonempty(e){return this.min(1,e)}};bt.create=(s,e)=>new bt({type:s,minLength:null,maxLength:null,exactLength:null,typeName:C.ZodArray,...X(e)});function fr(s){if(s instanceof Me){let e={};for(let r in s.shape){let a=s.shape[r];e[r]=Ge.create(fr(a))}return new Me({...s._def,shape:()=>e})}else return s instanceof bt?new bt({...s._def,type:fr(s.element)}):s instanceof Ge?Ge.create(fr(s.unwrap())):s instanceof ut?ut.create(fr(s.unwrap())):s instanceof lt?lt.create(s.items.map(e=>fr(e))):s}var Me=class s extends J{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=te.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==q.object){let u=this._getOrReturnCtx(e);return U(u,{code:D.invalid_type,expected:q.object,received:u.parsedType}),Z}let{status:a,ctx:t}=this._processInputParams(e),{shape:n,keys:o}=this._getCached(),i=[];if(!(this._def.catchall instanceof tt&&this._def.unknownKeys==="strip"))for(let u in t.data)o.includes(u)||i.push(u);let l=[];for(let u of o){let p=n[u],h=t.data[u];l.push({key:{status:"valid",value:u},value:p._parse(new Qe(t,h,t.path,u)),alwaysSet:u in t.data})}if(this._def.catchall instanceof tt){let u=this._def.unknownKeys;if(u==="passthrough")for(let p of i)l.push({key:{status:"valid",value:p},value:{status:"valid",value:t.data[p]}});else if(u==="strict")i.length>0&&(U(t,{code:D.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 p of i){let h=t.data[p];l.push({key:{status:"valid",value:p},value:u._parse(new Qe(t,h,t.path,p)),alwaysSet:p in t.data})}}return t.common.async?Promise.resolve().then(async()=>{let u=[];for(let p of l){let h=await p.key,f=await p.value;u.push({key:h,value:f,alwaysSet:p.alwaysSet})}return u}).then(u=>Pe.mergeObjectSync(a,u)):Pe.mergeObjectSync(a,l)}get shape(){return this._def.shape()}strict(e){return V.errToObj,new s({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,a)=>{let t=this._def.errorMap?.(r,a).message??a.defaultError;return r.code==="unrecognized_keys"?{message:V.errToObj(e).message??t}:{message:t}}}:{}})}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:C.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new s({...this._def,catchall:e})}pick(e){let r={};for(let a of te.objectKeys(e))e[a]&&this.shape[a]&&(r[a]=this.shape[a]);return new s({...this._def,shape:()=>r})}omit(e){let r={};for(let a of te.objectKeys(this.shape))e[a]||(r[a]=this.shape[a]);return new s({...this._def,shape:()=>r})}deepPartial(){return fr(this)}partial(e){let r={};for(let a of te.objectKeys(this.shape)){let t=this.shape[a];e&&!e[a]?r[a]=t:r[a]=t.optional()}return new s({...this._def,shape:()=>r})}required(e){let r={};for(let a of te.objectKeys(this.shape))if(e&&!e[a])r[a]=this.shape[a];else{let n=this.shape[a];for(;n instanceof Ge;)n=n._def.innerType;r[a]=n}return new s({...this._def,shape:()=>r})}keyof(){return Tn(te.objectKeys(this.shape))}};Me.create=(s,e)=>new Me({shape:()=>s,unknownKeys:"strip",catchall:tt.create(),typeName:C.ZodObject,...X(e)});Me.strictCreate=(s,e)=>new Me({shape:()=>s,unknownKeys:"strict",catchall:tt.create(),typeName:C.ZodObject,...X(e)});Me.lazycreate=(s,e)=>new Me({shape:s,unknownKeys:"strip",catchall:tt.create(),typeName:C.ZodObject,...X(e)});var Gt=class extends J{_parse(e){let{ctx:r}=this._processInputParams(e),a=this._def.options;function t(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 r.common.issues.push(...i.ctx.common.issues),i.result;let o=n.map(i=>new Fe(i.ctx.common.issues));return U(r,{code:D.invalid_union,unionErrors:o}),Z}if(r.common.async)return Promise.all(a.map(async n=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await n._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(t);{let n,o=[];for(let l of a){let u={...r,common:{...r.common,issues:[]},parent:null},p=l._parseSync({data:r.data,path:r.path,parent:u});if(p.status==="valid")return p;p.status==="dirty"&&!n&&(n={result:p,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(n)return r.common.issues.push(...n.ctx.common.issues),n.result;let i=o.map(l=>new Fe(l));return U(r,{code:D.invalid_union,unionErrors:i}),Z}}get options(){return this._def.options}};Gt.create=(s,e)=>new Gt({options:s,typeName:C.ZodUnion,...X(e)});var yt=s=>s instanceof Wt?yt(s.schema):s instanceof We?yt(s.innerType()):s instanceof Xt?[s.value]:s instanceof Kt?s.options:s instanceof Jt?te.objectValues(s.enum):s instanceof Yt?yt(s._def.innerType):s instanceof zt?[void 0]:s instanceof Zt?[null]:s instanceof Ge?[void 0,...yt(s.unwrap())]:s instanceof ut?[null,...yt(s.unwrap())]:s instanceof Ar||s instanceof tr?yt(s.unwrap()):s instanceof er?yt(s._def.innerType):[],Gr=class s extends J{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==q.object)return U(r,{code:D.invalid_type,expected:q.object,received:r.parsedType}),Z;let a=this.discriminator,t=r.data[a],n=this.optionsMap.get(t);return n?r.common.async?n._parseAsync({data:r.data,path:r.path,parent:r}):n._parseSync({data:r.data,path:r.path,parent:r}):(U(r,{code:D.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,r,a){let t=new Map;for(let n of r){let o=yt(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(t.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);t.set(i,n)}}return new s({typeName:C.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:t,...X(a)})}};function Gs(s,e){let r=ct(s),a=ct(e);if(s===e)return{valid:!0,data:s};if(r===q.object&&a===q.object){let t=te.objectKeys(e),n=te.objectKeys(s).filter(i=>t.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(r===q.array&&a===q.array){if(s.length!==e.length)return{valid:!1};let t=[];for(let n=0;n<s.length;n++){let o=s[n],i=e[n],l=Gs(o,i);if(!l.valid)return{valid:!1};t.push(l.data)}return{valid:!0,data:t}}else return r===q.date&&a===q.date&&+s==+e?{valid:!0,data:s}:{valid:!1}}var Qt=class extends J{_parse(e){let{status:r,ctx:a}=this._processInputParams(e),t=(n,o)=>{if(zr(n)||zr(o))return Z;let i=Gs(n.value,o.value);return i.valid?((Zr(n)||Zr(o))&&r.dirty(),{status:r.value,value:i.data}):(U(a,{code:D.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])=>t(n,o)):t(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}};Qt.create=(s,e,r)=>new Qt({left:s,right:e,typeName:C.ZodIntersection,...X(r)});var lt=class s extends J{_parse(e){let{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==q.array)return U(a,{code:D.invalid_type,expected:q.array,received:a.parsedType}),Z;if(a.data.length<this._def.items.length)return U(a,{code:D.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Z;!this._def.rest&&a.data.length>this._def.items.length&&(U(a,{code:D.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let n=[...a.data].map((o,i)=>{let l=this._def.items[i]||this._def.rest;return l?l._parse(new Qe(a,o,a.path,i)):null}).filter(o=>!!o);return a.common.async?Promise.all(n).then(o=>Pe.mergeArray(r,o)):Pe.mergeArray(r,n)}get items(){return this._def.items}rest(e){return new s({...this._def,rest:e})}};lt.create=(s,e)=>{if(!Array.isArray(s))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new lt({items:s,typeName:C.ZodTuple,rest:null,...X(e)})};var Qr=class s extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==q.object)return U(a,{code:D.invalid_type,expected:q.object,received:a.parsedType}),Z;let t=[],n=this._def.keyType,o=this._def.valueType;for(let i in a.data)t.push({key:n._parse(new Qe(a,i,a.path,i)),value:o._parse(new Qe(a,a.data[i],a.path,i)),alwaysSet:i in a.data});return a.common.async?Pe.mergeObjectAsync(r,t):Pe.mergeObjectSync(r,t)}get element(){return this._def.valueType}static create(e,r,a){return r instanceof J?new s({keyType:e,valueType:r,typeName:C.ZodRecord,...X(a)}):new s({keyType:wt.create(),valueType:e,typeName:C.ZodRecord,...X(r)})}},gr=class extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==q.map)return U(a,{code:D.invalid_type,expected:q.map,received:a.parsedType}),Z;let t=this._def.keyType,n=this._def.valueType,o=[...a.data.entries()].map(([i,l],u)=>({key:t._parse(new Qe(a,i,a.path,[u,"key"])),value:n._parse(new Qe(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,p=await l.value;if(u.status==="aborted"||p.status==="aborted")return Z;(u.status==="dirty"||p.status==="dirty")&&r.dirty(),i.set(u.value,p.value)}return{status:r.value,value:i}})}else{let i=new Map;for(let l of o){let u=l.key,p=l.value;if(u.status==="aborted"||p.status==="aborted")return Z;(u.status==="dirty"||p.status==="dirty")&&r.dirty(),i.set(u.value,p.value)}return{status:r.value,value:i}}}};gr.create=(s,e,r)=>new gr({valueType:e,keyType:s,typeName:C.ZodMap,...X(r)});var yr=class s extends J{_parse(e){let{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==q.set)return U(a,{code:D.invalid_type,expected:q.set,received:a.parsedType}),Z;let t=this._def;t.minSize!==null&&a.data.size<t.minSize.value&&(U(a,{code:D.too_small,minimum:t.minSize.value,type:"set",inclusive:!0,exact:!1,message:t.minSize.message}),r.dirty()),t.maxSize!==null&&a.data.size>t.maxSize.value&&(U(a,{code:D.too_big,maximum:t.maxSize.value,type:"set",inclusive:!0,exact:!1,message:t.maxSize.message}),r.dirty());let n=this._def.valueType;function o(l){let u=new Set;for(let p of l){if(p.status==="aborted")return Z;p.status==="dirty"&&r.dirty(),u.add(p.value)}return{status:r.value,value:u}}let i=[...a.data.values()].map((l,u)=>n._parse(new Qe(a,l,a.path,u)));return a.common.async?Promise.all(i).then(l=>o(l)):o(i)}min(e,r){return new s({...this._def,minSize:{value:e,message:V.toString(r)}})}max(e,r){return new s({...this._def,maxSize:{value:e,message:V.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};yr.create=(s,e)=>new yr({valueType:s,minSize:null,maxSize:null,typeName:C.ZodSet,...X(e)});var Wr=class s extends J{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==q.function)return U(r,{code:D.invalid_type,expected:q.function,received:r.parsedType}),Z;function a(i,l){return Nr({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,pr(),gt].filter(u=>!!u),issueData:{code:D.invalid_arguments,argumentsError:l}})}function t(i,l){return Nr({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,pr(),gt].filter(u=>!!u),issueData:{code:D.invalid_return_type,returnTypeError:l}})}let n={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof Ot){let i=this;return $e(async function(...l){let u=new Fe([]),p=await i._def.args.parseAsync(l,n).catch(d=>{throw u.addIssue(a(l,d)),u}),h=await Reflect.apply(o,this,p);return await i._def.returns._def.type.parseAsync(h,n).catch(d=>{throw u.addIssue(t(h,d)),u})})}else{let i=this;return $e(function(...l){let u=i._def.args.safeParse(l,n);if(!u.success)throw new Fe([a(l,u.error)]);let p=Reflect.apply(o,this,u.data),h=i._def.returns.safeParse(p,n);if(!h.success)throw new Fe([t(p,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new s({...this._def,args:lt.create(e).rest(_t.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,r,a){return new s({args:e||lt.create([]).rest(_t.create()),returns:r||_t.create(),typeName:C.ZodFunction,...X(a)})}},Wt=class extends J{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Wt.create=(s,e)=>new Wt({getter:s,typeName:C.ZodLazy,...X(e)});var Xt=class extends J{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return U(r,{received:r.data,code:D.invalid_literal,expected:this._def.value}),Z}return{status:"valid",value:e.data}}get value(){return this._def.value}};Xt.create=(s,e)=>new Xt({value:s,typeName:C.ZodLiteral,...X(e)});function Tn(s,e){return new Kt({values:s,typeName:C.ZodEnum,...X(e)})}var Kt=class s extends J{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),a=this._def.values;return U(r,{expected:te.joinValues(a),received:r.parsedType,code:D.invalid_type}),Z}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),a=this._def.values;return U(r,{received:r.data,code:D.invalid_enum_value,options:a}),Z}return $e(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return s.create(e,{...this._def,...r})}exclude(e,r=this._def){return s.create(this.options.filter(a=>!e.includes(a)),{...this._def,...r})}};Kt.create=Tn;var Jt=class extends J{_parse(e){let r=te.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(e);if(a.parsedType!==q.string&&a.parsedType!==q.number){let t=te.objectValues(r);return U(a,{expected:te.joinValues(t),received:a.parsedType,code:D.invalid_type}),Z}if(this._cache||(this._cache=new Set(te.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let t=te.objectValues(r);return U(a,{received:a.data,code:D.invalid_enum_value,options:t}),Z}return $e(e.data)}get enum(){return this._def.values}};Jt.create=(s,e)=>new Jt({values:s,typeName:C.ZodNativeEnum,...X(e)});var Ot=class extends J{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==q.promise&&r.common.async===!1)return U(r,{code:D.invalid_type,expected:q.promise,received:r.parsedType}),Z;let a=r.parsedType===q.promise?r.data:Promise.resolve(r.data);return $e(a.then(t=>this._def.type.parseAsync(t,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Ot.create=(s,e)=>new Ot({type:s,typeName:C.ZodPromise,...X(e)});var We=class extends J{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===C.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:a}=this._processInputParams(e),t=this._def.effect||null,n={addIssue:o=>{U(a,o),o.fatal?r.abort():r.dirty()},get path(){return a.path}};if(n.addIssue=n.addIssue.bind(n),t.type==="preprocess"){let o=t.transform(a.data,n);if(a.common.async)return Promise.resolve(o).then(async i=>{if(r.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"?Ut(l.value):r.value==="dirty"?Ut(l.value):l});{if(r.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"?Ut(i.value):r.value==="dirty"?Ut(i.value):i}}if(t.type==="refinement"){let o=i=>{let l=t.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"&&r.dirty(),o(i.value),{status:r.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"&&r.dirty(),o(i.value).then(()=>({status:r.value,value:i.value}))))}if(t.type==="transform")if(a.common.async===!1){let o=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!Tt(o))return Z;let i=t.transform(o.value,n);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:i}}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(o=>Tt(o)?Promise.resolve(t.transform(o.value,n)).then(i=>({status:r.value,value:i})):Z);te.assertNever(t)}};We.create=(s,e,r)=>new We({schema:s,typeName:C.ZodEffects,effect:e,...X(r)});We.createWithPreprocess=(s,e,r)=>new We({schema:e,effect:{type:"preprocess",transform:s},typeName:C.ZodEffects,...X(r)});var Ge=class extends J{_parse(e){return this._getType(e)===q.undefined?$e(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ge.create=(s,e)=>new Ge({innerType:s,typeName:C.ZodOptional,...X(e)});var ut=class extends J{_parse(e){return this._getType(e)===q.null?$e(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ut.create=(s,e)=>new ut({innerType:s,typeName:C.ZodNullable,...X(e)});var Yt=class extends J{_parse(e){let{ctx:r}=this._processInputParams(e),a=r.data;return r.parsedType===q.undefined&&(a=this._def.defaultValue()),this._def.innerType._parse({data:a,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Yt.create=(s,e)=>new Yt({innerType:s,typeName:C.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...X(e)});var er=class extends J{_parse(e){let{ctx:r}=this._processInputParams(e),a={...r,common:{...r.common,issues:[]}},t=this._def.innerType._parse({data:a.data,path:a.path,parent:{...a}});return hr(t)?t.then(n=>({status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new Fe(a.common.issues)},input:a.data})})):{status:"valid",value:t.status==="valid"?t.value:this._def.catchValue({get error(){return new Fe(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}};er.create=(s,e)=>new er({innerType:s,typeName:C.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...X(e)});var _r=class extends J{_parse(e){if(this._getType(e)!==q.nan){let a=this._getOrReturnCtx(e);return U(a,{code:D.invalid_type,expected:q.nan,received:a.parsedType}),Z}return{status:"valid",value:e.data}}};_r.create=s=>new _r({typeName:C.ZodNaN,...X(s)});var Su=Symbol("zod_brand"),Ar=class extends J{_parse(e){let{ctx:r}=this._processInputParams(e),a=r.data;return this._def.type._parse({data:a,path:r.path,parent:r})}unwrap(){return this._def.type}},Dr=class s extends J{_parse(e){let{status:r,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"?(r.dirty(),Ut(n.value)):this._def.out._parseAsync({data:n.value,path:a.path,parent:a})})();{let t=this._def.in._parseSync({data:a.data,path:a.path,parent:a});return t.status==="aborted"?Z:t.status==="dirty"?(r.dirty(),{status:"dirty",value:t.value}):this._def.out._parseSync({data:t.value,path:a.path,parent:a})}}static create(e,r){return new s({in:e,out:r,typeName:C.ZodPipeline})}},tr=class extends J{_parse(e){let r=this._def.innerType._parse(e),a=t=>(Tt(t)&&(t.value=Object.freeze(t.value)),t);return hr(r)?r.then(t=>a(t)):a(r)}unwrap(){return this._def.innerType}};tr.create=(s,e)=>new tr({innerType:s,typeName:C.ZodReadonly,...X(e)});function En(s,e){let r=typeof s=="function"?s(e):typeof s=="string"?{message:s}:s;return typeof r=="string"?{message:r}:r}function wn(s,e={},r){return s?Pt.create().superRefine((a,t)=>{let n=s(a);if(n instanceof Promise)return n.then(o=>{if(!o){let i=En(e,a),l=i.fatal??r??!0;t.addIssue({code:"custom",...i,fatal:l})}});if(!n){let o=En(e,a),i=o.fatal??r??!0;t.addIssue({code:"custom",...o,fatal:i})}}):Pt.create()}var xu={object:Me.lazycreate},C;(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"})(C||(C={}));var Ru=(s,e={message:`Input not instance of ${s.name}`})=>wn(r=>r instanceof s,e),Pn=wt.create,On=qt.create,Tu=_r.create,wu=Bt.create,In=Vt.create,Pu=Ht.create,Ou=mr.create,Iu=zt.create,$u=Zt.create,Nu=Pt.create,Au=_t.create,Du=tt.create,Cu=vr.create,ku=bt.create,Lu=Me.create,ju=Me.strictCreate,Fu=Gt.create,Mu=Gr.create,Uu=Qt.create,qu=lt.create,Bu=Qr.create,Vu=gr.create,Hu=yr.create,zu=Wr.create,Zu=Wt.create,Gu=Xt.create,Qu=Kt.create,Wu=Jt.create,Xu=Ot.create,Ku=We.create,Ju=Ge.create,Yu=ut.create,ed=We.createWithPreprocess,td=Dr.create,rd=()=>Pn().optional(),sd=()=>On().optional(),ad=()=>In().optional(),nd={string:(s=>wt.create({...s,coerce:!0})),number:(s=>qt.create({...s,coerce:!0})),boolean:(s=>Vt.create({...s,coerce:!0})),bigint:(s=>Bt.create({...s,coerce:!0})),date:(s=>Ht.create({...s,coerce:!0}))};var od=Z;var Cr="2025-06-18";var Xr=[Cr,"2025-03-26","2024-11-05","2024-10-07"],Kr="2.0",$n=c.union([c.string(),c.number().int()]),Nn=c.string(),id=c.object({progressToken:c.optional($n)}).passthrough(),Xe=c.object({_meta:c.optional(id)}).passthrough(),Ue=c.object({method:c.string(),params:c.optional(Xe)}),kr=c.object({_meta:c.optional(c.object({}).passthrough())}).passthrough(),dt=c.object({method:c.string(),params:c.optional(kr)}),Ke=c.object({_meta:c.optional(c.object({}).passthrough())}).passthrough(),Jr=c.union([c.string(),c.number().int()]),An=c.object({jsonrpc:c.literal(Kr),id:Jr}).merge(Ue).strict(),Dn=s=>An.safeParse(s).success,Cn=c.object({jsonrpc:c.literal(Kr)}).merge(dt).strict(),kn=s=>Cn.safeParse(s).success,Ln=c.object({jsonrpc:c.literal(Kr),id:Jr,result:Ke}).strict(),Qs=s=>Ln.safeParse(s).success,ke;(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"})(ke||(ke={}));var jn=c.object({jsonrpc:c.literal(Kr),id:Jr,error:c.object({code:c.number().int(),message:c.string(),data:c.optional(c.unknown())})}).strict(),Fn=s=>jn.safeParse(s).success,Mn=c.union([An,Cn,Ln,jn]),Et=Ke.strict(),Yr=dt.extend({method:c.literal("notifications/cancelled"),params:kr.extend({requestId:Jr,reason:c.string().optional()})}),cd=c.object({src:c.string(),mimeType:c.optional(c.string()),sizes:c.optional(c.array(c.string()))}).passthrough(),Lr=c.object({icons:c.array(cd).optional()}).passthrough(),jr=c.object({name:c.string(),title:c.optional(c.string())}).passthrough(),Un=jr.extend({version:c.string(),websiteUrl:c.optional(c.string())}).merge(Lr),ld=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(),Ws=Ue.extend({method:c.literal("initialize"),params:Xe.extend({protocolVersion:c.string(),capabilities:ld,clientInfo:Un})});var ud=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(),Xs=Ke.extend({protocolVersion:c.string(),capabilities:ud,serverInfo:Un,instructions:c.optional(c.string())}),Ks=dt.extend({method:c.literal("notifications/initialized")});var es=Ue.extend({method:c.literal("ping")}),dd=c.object({progress:c.number(),total:c.optional(c.number()),message:c.optional(c.string())}).passthrough(),ts=dt.extend({method:c.literal("notifications/progress"),params:kr.merge(dd).extend({progressToken:$n})}),rs=Ue.extend({params:Xe.extend({cursor:c.optional(Nn)}).optional()}),ss=Ke.extend({nextCursor:c.optional(Nn)}),qn=c.object({uri:c.string(),mimeType:c.optional(c.string()),_meta:c.optional(c.object({}).passthrough())}).passthrough(),Bn=qn.extend({text:c.string()}),Js=c.string().refine(s=>{try{return atob(s),!0}catch{return!1}},{message:"Invalid Base64 string"}),Vn=qn.extend({blob:Js}),Hn=jr.extend({uri:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),_meta:c.optional(c.object({}).passthrough())}).merge(Lr),pd=jr.extend({uriTemplate:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),_meta:c.optional(c.object({}).passthrough())}).merge(Lr),hd=rs.extend({method:c.literal("resources/list")}),Ys=ss.extend({resources:c.array(Hn)}),fd=rs.extend({method:c.literal("resources/templates/list")}),ea=ss.extend({resourceTemplates:c.array(pd)}),md=Ue.extend({method:c.literal("resources/read"),params:Xe.extend({uri:c.string()})}),ta=Ke.extend({contents:c.array(c.union([Bn,Vn]))}),vd=dt.extend({method:c.literal("notifications/resources/list_changed")}),gd=Ue.extend({method:c.literal("resources/subscribe"),params:Xe.extend({uri:c.string()})}),yd=Ue.extend({method:c.literal("resources/unsubscribe"),params:Xe.extend({uri:c.string()})}),_d=dt.extend({method:c.literal("notifications/resources/updated"),params:kr.extend({uri:c.string()})}),bd=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}).passthrough(),Ed=jr.extend({description:c.optional(c.string()),arguments:c.optional(c.array(bd)),_meta:c.optional(c.object({}).passthrough())}).merge(Lr),Sd=rs.extend({method:c.literal("prompts/list")}),ra=ss.extend({prompts:c.array(Ed)}),xd=Ue.extend({method:c.literal("prompts/get"),params:Xe.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(),Rd=c.object({type:c.literal("resource"),resource:c.union([Bn,Vn]),_meta:c.optional(c.object({}).passthrough())}).passthrough(),Td=Hn.extend({type:c.literal("resource_link")}),zn=c.union([sa,aa,na,Td,Rd]),wd=c.object({role:c.enum(["user","assistant"]),content:zn}).passthrough(),oa=Ke.extend({description:c.optional(c.string()),messages:c.array(wd)}),Pd=dt.extend({method:c.literal("notifications/prompts/list_changed")}),Od=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(),Id=jr.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(Od),_meta:c.optional(c.object({}).passthrough())}).merge(Lr),ia=rs.extend({method:c.literal("tools/list")}),ca=ss.extend({tools:c.array(Id)}),as=Ke.extend({content:c.array(zn).default([]),structuredContent:c.object({}).passthrough().optional(),isError:c.optional(c.boolean())}),am=as.or(Ke.extend({toolResult:c.unknown()})),la=Ue.extend({method:c.literal("tools/call"),params:Xe.extend({name:c.string(),arguments:c.optional(c.record(c.unknown()))})}),$d=dt.extend({method:c.literal("notifications/tools/list_changed")}),Fr=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),ua=Ue.extend({method:c.literal("logging/setLevel"),params:Xe.extend({level:Fr})}),Nd=dt.extend({method:c.literal("notifications/message"),params:kr.extend({level:Fr,logger:c.optional(c.string()),data:c.unknown()})}),Ad=c.object({name:c.string().optional()}).passthrough(),Dd=c.object({hints:c.optional(c.array(Ad)),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(),Cd=c.object({role:c.enum(["user","assistant"]),content:c.union([sa,aa,na])}).passthrough(),kd=Ue.extend({method:c.literal("sampling/createMessage"),params:Xe.extend({messages:c.array(Cd),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(Dd)})}),da=Ke.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])}),Ld=c.object({type:c.literal("boolean"),title:c.optional(c.string()),description:c.optional(c.string()),default:c.optional(c.boolean())}).passthrough(),jd=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(),Fd=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(),Md=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(),Ud=c.union([Ld,jd,Fd,Md]),qd=Ue.extend({method:c.literal("elicitation/create"),params:Xe.extend({message:c.string(),requestedSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Ud),required:c.optional(c.array(c.string()))}).passthrough()})}),pa=Ke.extend({action:c.enum(["accept","decline","cancel"]),content:c.optional(c.record(c.string(),c.unknown()))}),Bd=c.object({type:c.literal("ref/resource"),uri:c.string()}).passthrough();var Vd=c.object({type:c.literal("ref/prompt"),name:c.string()}).passthrough(),Hd=Ue.extend({method:c.literal("completion/complete"),params:Xe.extend({ref:c.union([Vd,Bd]),argument:c.object({name:c.string(),value:c.string()}).passthrough(),context:c.optional(c.object({arguments:c.optional(c.record(c.string(),c.string()))}))})}),ha=Ke.extend({completion:c.object({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())}).passthrough()}),zd=c.object({uri:c.string().startsWith("file://"),name:c.optional(c.string()),_meta:c.optional(c.object({}).passthrough())}).passthrough(),Zd=Ue.extend({method:c.literal("roots/list")}),fa=Ke.extend({roots:c.array(zd)}),Gd=dt.extend({method:c.literal("notifications/roots/list_changed")}),nm=c.union([es,Ws,Hd,ua,xd,Sd,hd,fd,md,gd,yd,la,ia]),om=c.union([Yr,ts,Ks,Gd]),im=c.union([Et,da,pa,fa]),cm=c.union([es,kd,qd,Zd]),lm=c.union([Yr,ts,Nd,_d,vd,$d,Pd]),um=c.union([Et,Xs,ha,oa,ra,Ys,ea,ta,as,ca]),Ne=class extends Error{constructor(e,r,a){super(`MCP error ${e}: ${r}`),this.code=e,this.data=a,this.name="McpError"}};var Qd=6e4,br=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(Yr,r=>{let a=this._requestHandlerAbortControllers.get(r.params.requestId);a?.abort(r.params.reason)}),this.setNotificationHandler(ts,r=>{this._onprogress(r)}),this.setRequestHandler(es,r=>({}))}_setupTimeout(e,r,a,t,n=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(t,r),startTime:Date.now(),timeout:r,maxTotalTimeout:a,resetTimeoutOnProgress:n,onTimeout:t})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let a=Date.now()-r.startTime;if(r.maxTotalTimeout&&a>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),new Ne(ke.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:a});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,a,t;this._transport=e;let n=(r=this.transport)===null||r===void 0?void 0:r.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=(t=this._transport)===null||t===void 0?void 0:t.onmessage;this._transport.onmessage=(l,u)=>{i?.(l,u),Qs(l)||Fn(l)?this._onresponse(l):Dn(l)?this._onrequest(l,u):kn(l)?this._onnotification(l):this._onerror(new Error(`Unknown message type: ${JSON.stringify(l)}`))},await this._transport.start()}_onclose(){var e;let r=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 Ne(ke.ConnectionClosed,"Connection closed");for(let t of r.values())t(a)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;let a=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;a!==void 0&&Promise.resolve().then(()=>a(e)).catch(t=>this._onerror(new Error(`Uncaught error in notification handler: ${t}`)))}_onrequest(e,r){var a,t;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:ke.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:(t=e.params)===null||t===void 0?void 0:t._meta,sendNotification:u=>this.notification(u,{relatedRequestId:e.id}),sendRequest:(u,p,h)=>this.request(u,p,{...h,relatedRequestId:e.id}),authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.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 p;if(!i.signal.aborted)return o?.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:ke.InternalError,message:(p=u.message)!==null&&p!==void 0?p:"Internal error"}})}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...a}=e.params,t=Number(r),n=this._progressHandlers.get(t);if(!n){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let o=this._responseHandlers.get(t),i=this._timeoutInfo.get(t);if(i&&o&&i.resetTimeoutOnProgress)try{this._resetTimeout(t)}catch(l){o(l);return}n(a)}_onresponse(e){let r=Number(e.id),a=this._responseHandlers.get(r);if(a===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),Qs(e))a(e);else{let t=new Ne(e.error.code,e.error.message,e.error.data);a(t)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,r,a){let{relatedRequestId:t,resumptionToken:n,onresumptiontoken:o}=a??{};return new Promise((i,l)=>{var u,p,h,f,d,g;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),(p=a?.signal)===null||p===void 0||p.throwIfAborted();let v=this._requestMessageId++,y={...e,jsonrpc:"2.0",id:v};a?.onprogress&&(this._progressHandlers.set(v,a.onprogress),y.params={...e.params,_meta:{...((h=e.params)===null||h===void 0?void 0:h._meta)||{},progressToken:v}});let _=w=>{var x;this._responseHandlers.delete(v),this._progressHandlers.delete(v),this._cleanupTimeout(v),(x=this._transport)===null||x===void 0||x.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:v,reason:String(w)}},{relatedRequestId:t,resumptionToken:n,onresumptiontoken:o}).catch(T=>this._onerror(new Error(`Failed to send cancellation: ${T}`))),l(w)};this._responseHandlers.set(v,w=>{var x;if(!(!((x=a?.signal)===null||x===void 0)&&x.aborted)){if(w instanceof Error)return l(w);try{let T=r.parse(w.result);i(T)}catch(T){l(T)}}}),(f=a?.signal)===null||f===void 0||f.addEventListener("abort",()=>{var w;_((w=a?.signal)===null||w===void 0?void 0:w.reason)});let R=(d=a?.timeout)!==null&&d!==void 0?d:Qd,S=()=>_(new Ne(ke.RequestTimeout,"Request timed out",{timeout:R}));this._setupTimeout(v,R,a?.maxTotalTimeout,S,(g=a?.resetTimeoutOnProgress)!==null&&g!==void 0?g:!1),this._transport.send(y,{relatedRequestId:t,resumptionToken:n,onresumptiontoken:o}).catch(w=>{this._cleanupTimeout(v),l(w)})})}async notification(e,r){var a,t;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((t=(a=this._options)===null||a===void 0?void 0:a.debouncedNotificationMethods)!==null&&t!==void 0?t:[]).includes(e.method)&&!e.params&&!r?.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,r).catch(p=>this._onerror(p))});return}let i={...e,jsonrpc:"2.0"};await this._transport.send(i,r)}setRequestHandler(e,r){let a=e.shape.method.value;this.assertRequestHandlerCapability(a),this._requestHandlers.set(a,(t,n)=>Promise.resolve(r(e.parse(t),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,r){this._notificationHandlers.set(e.shape.method.value,a=>Promise.resolve(r(e.parse(a))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function ns(s,e){return Object.entries(e).reduce((r,[a,t])=>(t&&typeof t=="object"?r[a]=r[a]?{...r[a],...t}:t:r[a]=t,r),{...s})}var Gi=Hs(Ma(),1),Rs=class extends br{constructor(e,r){var a;super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Fr.options.map((t,n)=>[t,n])),this.isMessageIgnored=(t,n)=>{let o=this._loggingLevels.get(n);return o?this.LOG_LEVEL_SEVERITY.get(t)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=(a=r?.capabilities)!==null&&a!==void 0?a:{},this._instructions=r?.instructions,this.setRequestHandler(Ws,t=>this._oninitialize(t)),this.setNotificationHandler(Ks,()=>{var t;return(t=this.oninitialized)===null||t===void 0?void 0:t.call(this)}),this._capabilities.logging&&this.setRequestHandler(ua,async(t,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}=t.params,u=Fr.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=ns(this._capabilities,e)}assertCapabilityForMethod(e){var r,a,t;switch(e){case"sampling/createMessage":if(!(!((r=this._clientCapabilities)===null||r===void 0)&&r.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(!(!((t=this._clientCapabilities)===null||t===void 0)&&t.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 r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Xr.includes(r)?r:Cr,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"},Et)}async createMessage(e,r){return this.request({method:"sampling/createMessage",params:e},da,r)}async elicitInput(e,r){let a=await this.request({method:"elicitation/create",params:e},pa,r);if(a.action==="accept"&&a.content)try{let t=new Gi.default,n=t.compile(e.requestedSchema);if(!n(a.content))throw new Ne(ke.InvalidParams,`Elicitation response content does not match requested schema: ${t.errorsText(n.errors)}`)}catch(t){throw t instanceof Ne?t:new Ne(ke.InternalError,`Error validating elicitation response: ${t}`)}return a}async listRoots(e,r){return this.request({method:"roots/list",params:e},fa,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};import Qi from"node:process";var Er=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Ph(r)}clear(){this._buffer=void 0}};function Ph(s){return Mn.parse(JSON.parse(s))}function Ts(s){return JSON.stringify(s)+`
`}var ws=class{constructor(e=Qi.stdin,r=Qi.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Er,this._started=!1,this._ondata=a=>{this._readBuffer.append(a),this.processReadBuffer()},this._onerror=a=>{var t;(t=this.onerror)===null||t===void 0||t.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,r;;)try{let a=this._readBuffer.readMessage();if(a===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,a)}catch(a){(r=this.onerror)===null||r===void 0||r.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(r=>{let a=Ts(e);this._stdout.write(a)?r():this._stdout.once("drain",r)})}};var Wi=Hs(Ma(),1),Ps=class extends br{constructor(e,r){var a;super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=(a=r?.capabilities)!==null&&a!==void 0?a:{},this._ajv=new Wi.default}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ns(this._capabilities,e)}assertCapability(e,r){var a;if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a[e]))throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let a=await this.request({method:"initialize",params:{protocolVersion:Cr,capabilities:this._capabilities,clientInfo:this._clientInfo}},Xs,r);if(a===void 0)throw new Error(`Server sent invalid initialize result: ${a}`);if(!Xr.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 r,a,t,n,o;switch(e){case"logging/setLevel":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.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(!(!((t=this._serverCapabilities)===null||t===void 0)&&t.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 r;switch(e){case"notifications/roots/list_changed":if(!(!((r=this._capabilities.roots)===null||r===void 0)&&r.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"},Et,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},ha,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},Et,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},oa,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},ra,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},Ys,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},ea,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},ta,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},Et,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},Et,r)}async callTool(e,r=as,a){let t=await this.request({method:"tools/call",params:e},r,a),n=this.getToolOutputValidator(e.name);if(n){if(!t.structuredContent&&!t.isError)throw new Ne(ke.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(t.structuredContent)try{if(!n(t.structuredContent))throw new Ne(ke.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(n.errors)}`)}catch(o){throw o instanceof Ne?o:new Ne(ke.InvalidParams,`Failed to validate structured content: ${o instanceof Error?o.message:String(o)}`)}}return t}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(let r of e)if(r.outputSchema)try{let a=this._ajv.compile(r.outputSchema);this._cachedToolOutputValidators.set(r.name,a)}catch{}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let a=await this.request({method:"tools/list",params:e},ca,r);return this.cacheToolOutputSchemas(a.tools),a}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var Fc=Hs(jc(),1);import $s from"node:process";import{PassThrough as ef}from"node:stream";var tf=$s.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function rf(){let s={};for(let e of tf){let r=$s.env[e];r!==void 0&&(r.startsWith("()")||(s[e]=r))}return s}var Is=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new Er,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new ef)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{var a,t,n,o,i;this._process=(0,Fc.default)(this._serverParams.command,(a=this._serverParams.args)!==null&&a!==void 0?a:[],{env:{...rf(),...this._serverParams.env},stdio:["pipe","pipe",(t=this._serverParams.stderr)!==null&&t!==void 0?t:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:$s.platform==="win32"&&sf(),cwd:this._serverParams.cwd}),this._process.on("error",l=>{var u,p;if(l.name==="AbortError"){(u=this.onclose)===null||u===void 0||u.call(this);return}r(l),(p=this.onerror)===null||p===void 0||p.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,r;return this._stderrStream?this._stderrStream:(r=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&r!==void 0?r:null}get pid(){var e,r;return(r=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&r!==void 0?r:null}processReadBuffer(){for(var e,r;;)try{let a=this._readBuffer.readMessage();if(a===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,a)}catch(a){(r=this.onerror)===null||r===void 0||r.call(this,a)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(r=>{var a;if(!(!((a=this._process)===null||a===void 0)&&a.stdin))throw new Error("Not connected");let t=Ts(e);this._process.stdin.write(t)?r():this._process.stdin.once("drain",r)})}};function sf(){return"type"in $s}var Uc=Symbol("Let zodToJsonSchema decide on which parser to use");var Mc={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"},qc=s=>typeof s=="string"?{...Mc,name:s}:{...Mc,...s};var Bc=s=>{let e=qc(s),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([a,t])=>[t._def,{def:t._def,path:[...e.basePath,e.definitionPath,a],jsonSchema:void 0}]))}};function Wa(s,e,r,a){a?.errorMessages&&r&&(s.errorMessage={...s.errorMessage,[e]:r})}function re(s,e,r,a,t){s[e]=r,Wa(s,e,a,t)}var Ns=(s,e)=>{let r=0;for(;r<s.length&&r<e.length&&s[r]===e[r];r++);return[(s.length-r).toString(),...e.slice(r)].join("/")};function me(s){if(s.target!=="openAi")return{};let e=[...s.basePath,s.definitionPath,s.openAiAnyTypeName];return s.flags.hasReferencedOpenAiAnyType=!0,{$ref:s.$refStrategy==="relative"?Ns(e,s.currentPath):e.join("/")}}function Vc(s,e){let r={type:"array"};return s.type?._def&&s.type?._def?.typeName!==C.ZodAny&&(r.items=G(s.type._def,{...e,currentPath:[...e.currentPath,"items"]})),s.minLength&&re(r,"minItems",s.minLength.value,s.minLength.message,e),s.maxLength&&re(r,"maxItems",s.maxLength.value,s.maxLength.message,e),s.exactLength&&(re(r,"minItems",s.exactLength.value,s.exactLength.message,e),re(r,"maxItems",s.exactLength.value,s.exactLength.message,e)),r}function Hc(s,e){let r={type:"integer",format:"int64"};if(!s.checks)return r;for(let a of s.checks)switch(a.kind){case"min":e.target==="jsonSchema7"?a.inclusive?re(r,"minimum",a.value,a.message,e):re(r,"exclusiveMinimum",a.value,a.message,e):(a.inclusive||(r.exclusiveMinimum=!0),re(r,"minimum",a.value,a.message,e));break;case"max":e.target==="jsonSchema7"?a.inclusive?re(r,"maximum",a.value,a.message,e):re(r,"exclusiveMaximum",a.value,a.message,e):(a.inclusive||(r.exclusiveMaximum=!0),re(r,"maximum",a.value,a.message,e));break;case"multipleOf":re(r,"multipleOf",a.value,a.message,e);break}return r}function zc(){return{type:"boolean"}}function As(s,e){return G(s.type._def,e)}var Zc=(s,e)=>G(s.innerType._def,e);function Xa(s,e,r){let a=r??e.dateStrategy;if(Array.isArray(a))return{anyOf:a.map((t,n)=>Xa(s,e,t))};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 af(s,e)}}var af=(s,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let a of s.checks)switch(a.kind){case"min":re(r,"minimum",a.value,a.message,e);break;case"max":re(r,"maximum",a.value,a.message,e);break}return r};function Gc(s,e){return{...G(s.innerType._def,e),default:s.defaultValue()}}function Qc(s,e){return e.effectStrategy==="input"?G(s.schema._def,e):me(e)}function Wc(s){return{type:"string",enum:Array.from(s.values)}}var nf=s=>"type"in s&&s.type==="string"?!1:"allOf"in s;function Xc(s,e){let r=[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,t=[];return r.forEach(n=>{if(nf(n))t.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;t.push(o)}}),t.length?{allOf:t,...a}:void 0}function Kc(s,e){let r=typeof s.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(s.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[s.value]}:{type:r==="bigint"?"integer":r,const:s.value}}var Ka,rt={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 Ds(s,e){let r={type:"string"};if(s.checks)for(let a of s.checks)switch(a.kind){case"min":re(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,a.value):a.value,a.message,e);break;case"max":re(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,a.value):a.value,a.message,e);break;case"email":switch(e.emailStrategy){case"format:email":st(r,"email",a.message,e);break;case"format:idn-email":st(r,"idn-email",a.message,e);break;case"pattern:zod":Le(r,rt.email,a.message,e);break}break;case"url":st(r,"uri",a.message,e);break;case"uuid":st(r,"uuid",a.message,e);break;case"regex":Le(r,a.regex,a.message,e);break;case"cuid":Le(r,rt.cuid,a.message,e);break;case"cuid2":Le(r,rt.cuid2,a.message,e);break;case"startsWith":Le(r,RegExp(`^${Ja(a.value,e)}`),a.message,e);break;case"endsWith":Le(r,RegExp(`${Ja(a.value,e)}$`),a.message,e);break;case"datetime":st(r,"date-time",a.message,e);break;case"date":st(r,"date",a.message,e);break;case"time":st(r,"time",a.message,e);break;case"duration":st(r,"duration",a.message,e);break;case"length":re(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,a.value):a.value,a.message,e),re(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,a.value):a.value,a.message,e);break;case"includes":{Le(r,RegExp(Ja(a.value,e)),a.message,e);break}case"ip":{a.version!=="v6"&&st(r,"ipv4",a.message,e),a.version!=="v4"&&st(r,"ipv6",a.message,e);break}case"base64url":Le(r,rt.base64url,a.message,e);break;case"jwt":Le(r,rt.jwt,a.message,e);break;case"cidr":{a.version!=="v6"&&Le(r,rt.ipv4Cidr,a.message,e),a.version!=="v4"&&Le(r,rt.ipv6Cidr,a.message,e);break}case"emoji":Le(r,rt.emoji(),a.message,e);break;case"ulid":{Le(r,rt.ulid,a.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{st(r,"binary",a.message,e);break}case"contentEncoding:base64":{re(r,"contentEncoding","base64",a.message,e);break}case"pattern:zod":{Le(r,rt.base64,a.message,e);break}}break}case"nanoid":Le(r,rt.nanoid,a.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Ja(s,e){return e.patternStrategy==="escape"?cf(s):s}var of=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function cf(s){let e="";for(let r=0;r<s.length;r++)of.has(s[r])||(e+="\\"),e+=s[r];return e}function st(s,e,r,a){s.format||s.anyOf?.some(t=>t.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,...r&&a.errorMessages&&{errorMessage:{format:r}}})):re(s,"format",e,r,a)}function Le(s,e,r,a){s.pattern||s.allOf?.some(t=>t.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:Jc(e,a),...r&&a.errorMessages&&{errorMessage:{pattern:r}}})):re(s,"pattern",Jc(e,a),r,a)}function Jc(s,e){if(!e.applyRegexFlags||!s.flags)return s.source;let r={i:s.flags.includes("i"),m:s.flags.includes("m"),s:s.flags.includes("s")},a=r.i?s.source.toLowerCase():s.source,t="",n=!1,o=!1,i=!1;for(let l=0;l<a.length;l++){if(n){t+=a[l],n=!1;continue}if(r.i){if(o){if(a[l].match(/[a-z]/)){i?(t+=a[l],t+=`${a[l-2]}-${a[l]}`.toUpperCase(),i=!1):a[l+1]==="-"&&a[l+2]?.match(/[a-z]/)?(t+=a[l],i=!0):t+=`${a[l]}${a[l].toUpperCase()}`;continue}}else if(a[l].match(/[a-z]/)){t+=`[${a[l]}${a[l].toUpperCase()}]`;continue}}if(r.m){if(a[l]==="^"){t+=`(^|(?<=[\r
]))`;continue}else if(a[l]==="$"){t+=`($|(?=[\r
]))`;continue}}if(r.s&&a[l]==="."){t+=o?`${a[l]}\r
`:`[${a[l]}\r
]`;continue}t+=a[l],a[l]==="\\"?n=!0:o&&a[l]==="]"?o=!1:!o&&a[l]==="["&&(o=!0)}try{new RegExp(t)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),s.source}return t}function Cs(s,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&s.keyType?._def.typeName===C.ZodEnum)return{type:"object",required:s.keyType._def.values,properties:s.keyType._def.values.reduce((a,t)=>({...a,[t]:G(s.valueType._def,{...e,currentPath:[...e.currentPath,"properties",t]})??me(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:G(s.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(s.keyType?._def.typeName===C.ZodString&&s.keyType._def.checks?.length){let{type:a,...t}=Ds(s.keyType._def,e);return{...r,propertyNames:t}}else{if(s.keyType?._def.typeName===C.ZodEnum)return{...r,propertyNames:{enum:s.keyType._def.values}};if(s.keyType?._def.typeName===C.ZodBranded&&s.keyType._def.type._def.typeName===C.ZodString&&s.keyType._def.type._def.checks?.length){let{type:a,...t}=As(s.keyType._def,e);return{...r,propertyNames:t}}}return r}function Yc(s,e){if(e.mapStrategy==="record")return Cs(s,e);let r=G(s.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||me(e),a=G(s.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||me(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,a],minItems:2,maxItems:2}}}function el(s){let e=s.values,a=Object.keys(s.values).filter(n=>typeof e[e[n]]!="number").map(n=>e[n]),t=Array.from(new Set(a.map(n=>typeof n)));return{type:t.length===1?t[0]==="string"?"string":"number":["string","number"],enum:a}}function tl(s){return s.target==="openAi"?void 0:{not:me({...s,currentPath:[...s.currentPath,"not"]})}}function rl(s){return s.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ur={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function al(s,e){if(e.target==="openApi3")return sl(s,e);let r=s.options instanceof Map?Array.from(s.options.values()):s.options;if(r.every(a=>a._def.typeName in Ur&&(!a._def.checks||!a._def.checks.length))){let a=r.reduce((t,n)=>{let o=Ur[n._def.typeName];return o&&!t.includes(o)?[...t,o]:t},[]);return{type:a.length>1?a:a[0]}}else if(r.every(a=>a._def.typeName==="ZodLiteral"&&!a.description)){let a=r.reduce((t,n)=>{let o=typeof n._def.value;switch(o){case"string":case"number":case"boolean":return[...t,o];case"bigint":return[...t,"integer"];case"object":if(n._def.value===null)return[...t,"null"];case"symbol":case"undefined":case"function":default:return t}},[]);if(a.length===r.length){let t=a.filter((n,o,i)=>i.indexOf(n)===o);return{type:t.length>1?t:t[0],enum:r.reduce((n,o)=>n.includes(o._def.value)?n:[...n,o._def.value],[])}}}else if(r.every(a=>a._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((a,t)=>[...a,...t._def.values.filter(n=>!a.includes(n))],[])};return sl(s,e)}var sl=(s,e)=>{let r=(s.options instanceof Map?Array.from(s.options.values()):s.options).map((a,t)=>G(a._def,{...e,currentPath:[...e.currentPath,"anyOf",`${t}`]})).filter(a=>!!a&&(!e.strictUnions||typeof a=="object"&&Object.keys(a).length>0));return r.length?{anyOf:r}:void 0};function nl(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:Ur[s.innerType._def.typeName],nullable:!0}:{type:[Ur[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 r=G(s.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function ol(s,e){let r={type:"number"};if(!s.checks)return r;for(let a of s.checks)switch(a.kind){case"int":r.type="integer",Wa(r,"type",a.message,e);break;case"min":e.target==="jsonSchema7"?a.inclusive?re(r,"minimum",a.value,a.message,e):re(r,"exclusiveMinimum",a.value,a.message,e):(a.inclusive||(r.exclusiveMinimum=!0),re(r,"minimum",a.value,a.message,e));break;case"max":e.target==="jsonSchema7"?a.inclusive?re(r,"maximum",a.value,a.message,e):re(r,"exclusiveMaximum",a.value,a.message,e):(a.inclusive||(r.exclusiveMaximum=!0),re(r,"maximum",a.value,a.message,e));break;case"multipleOf":re(r,"multipleOf",a.value,a.message,e);break}return r}function il(s,e){let r=e.target==="openAi",a={type:"object",properties:{}},t=[],n=s.shape();for(let i in n){let l=n[i];if(l===void 0||l._def===void 0)continue;let u=uf(l);u&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),u=!1);let p=G(l._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});p!==void 0&&(a.properties[i]=p,u||t.push(i))}t.length&&(a.required=t);let o=lf(s,e);return o!==void 0&&(a.additionalProperties=o),a}function lf(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 uf(s){try{return s.isOptional()}catch{return!0}}var cl=(s,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return G(s.innerType._def,e);let r=G(s.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:me(e)},r]}:me(e)};var ll=(s,e)=>{if(e.pipeStrategy==="input")return G(s.in._def,e);if(e.pipeStrategy==="output")return G(s.out._def,e);let r=G(s.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),a=G(s.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,a].filter(t=>t!==void 0)}};function ul(s,e){return G(s.type._def,e)}function dl(s,e){let a={type:"array",uniqueItems:!0,items:G(s.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return s.minSize&&re(a,"minItems",s.minSize.value,s.minSize.message,e),s.maxSize&&re(a,"maxItems",s.maxSize.value,s.maxSize.message,e),a}function pl(s,e){return s.rest?{type:"array",minItems:s.items.length,items:s.items.map((r,a)=>G(r._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((r,a)=>a===void 0?r:[...r,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((r,a)=>G(r._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((r,a)=>a===void 0?r:[...r,a],[])}}function hl(s){return{not:me(s)}}function fl(s){return me(s)}var ml=(s,e)=>G(s.innerType._def,e);var vl=(s,e,r)=>{switch(e){case C.ZodString:return Ds(s,r);case C.ZodNumber:return ol(s,r);case C.ZodObject:return il(s,r);case C.ZodBigInt:return Hc(s,r);case C.ZodBoolean:return zc();case C.ZodDate:return Xa(s,r);case C.ZodUndefined:return hl(r);case C.ZodNull:return rl(r);case C.ZodArray:return Vc(s,r);case C.ZodUnion:case C.ZodDiscriminatedUnion:return al(s,r);case C.ZodIntersection:return Xc(s,r);case C.ZodTuple:return pl(s,r);case C.ZodRecord:return Cs(s,r);case C.ZodLiteral:return Kc(s,r);case C.ZodEnum:return Wc(s);case C.ZodNativeEnum:return el(s);case C.ZodNullable:return nl(s,r);case C.ZodOptional:return cl(s,r);case C.ZodMap:return Yc(s,r);case C.ZodSet:return dl(s,r);case C.ZodLazy:return()=>s.getter()._def;case C.ZodPromise:return ul(s,r);case C.ZodNaN:case C.ZodNever:return tl(r);case C.ZodEffects:return Qc(s,r);case C.ZodAny:return me(r);case C.ZodUnknown:return fl(r);case C.ZodDefault:return Gc(s,r);case C.ZodBranded:return As(s,r);case C.ZodReadonly:return ml(s,r);case C.ZodCatch:return Zc(s,r);case C.ZodPipeline:return ll(s,r);case C.ZodFunction:case C.ZodVoid:case C.ZodSymbol:return;default:return(a=>{})(e)}};function G(s,e,r=!1){let a=e.seen.get(s);if(e.override){let i=e.override?.(s,e,a,r);if(i!==Uc)return i}if(a&&!r){let i=df(a,e);if(i!==void 0)return i}let t={def:s,path:e.currentPath,jsonSchema:void 0};e.seen.set(s,t);let n=vl(s,s.typeName,e),o=typeof n=="function"?G(n(),e):n;if(o&&pf(s,e,o),e.postProcess){let i=e.postProcess(o,s,e);return t.jsonSchema=o,i}return t.jsonSchema=o,o}var df=(s,e)=>{switch(e.$refStrategy){case"root":return{$ref:s.path.join("/")};case"relative":return{$ref:Ns(e.currentPath,s.path)};case"none":case"seen":return s.path.length<e.currentPath.length&&s.path.every((r,a)=>e.currentPath[a]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),me(e)):e.$refStrategy==="seen"?me(e):void 0}},pf=(s,e,r)=>(s.description&&(r.description=s.description,e.markdownDescription&&(r.markdownDescription=s.description)),r);var Ya=(s,e)=>{let r=Bc(e),a=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[u,p])=>({...l,[u]:G(p._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??me(r)}),{}):void 0,t=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,n=G(s._def,t===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,t]},!1)??me(r),o=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;o!==void 0&&(n.title=o),r.flags.hasReferencedOpenAiAnyType&&(a||(a={}),a[r.openAiAnyTypeName]||(a[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let i=t===void 0?a?{...n,[r.definitionPath]:a}:n:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,t].join("/"),[r.definitionPath]:{...a,[t]:n}};return r.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),r.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 bl}from"path";import gf from"better-sqlite3";import{join as Je,dirname as hf,basename as w_}from"path";import{homedir as gl}from"os";import{existsSync as $_,mkdirSync as ff}from"fs";import{fileURLToPath as mf}from"url";function vf(){return typeof __dirname<"u"?__dirname:hf(mf(import.meta.url))}var A_=vf(),at=process.env.CLAUDE_MEM_DATA_DIR||Je(gl(),".claude-mem"),en=process.env.CLAUDE_CONFIG_DIR||Je(gl(),".claude"),D_=Je(at,"archives"),C_=Je(at,"logs"),k_=Je(at,"trash"),L_=Je(at,"backups"),j_=Je(at,"settings.json"),ks=Je(at,"claude-mem.db"),yl=Je(at,"vector-db"),F_=Je(en,"settings.json"),M_=Je(en,"commands"),U_=Je(en,"CLAUDE.md");function Ls(s){ff(s,{recursive:!0})}var js=class{db;constructor(e){e||(Ls(at),e=ks),this.db=new gf(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,r,a="o"){let t=[];if(e.project&&(t.push(`${a}.project = ?`),r.push(e.project)),e.type)if(Array.isArray(e.type)){let n=e.type.map(()=>"?").join(",");t.push(`${a}.type IN (${n})`),r.push(...e.type)}else t.push(`${a}.type = ?`),r.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();t.push(`${a}.created_at_epoch >= ?`),r.push(i)}if(o){let i=typeof o=="number"?o:new Date(o).getTime();t.push(`${a}.created_at_epoch <= ?`),r.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&&(t.push(`(${o.join(" OR ")})`),r.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&&(t.push(`(${o.join(" OR ")})`),n.forEach(i=>{r.push(`%${i}%`,`%${i}%`)}))}return t.length>0?t.join(" AND "):""}buildOrderClause(e="relevance",r=!0,a="observations_fts"){switch(e){case"relevance":return r?`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,r={}){let a=[],{limit:t=50,offset:n=0,orderBy:o="relevance",...i}=r,l=this.escapeFTS5(e);a.push(l);let u=this.buildFilterClause(i,a,"o"),p=u?`AND ${u}`:"",h=this.buildOrderClause(o,!0),f=`
SELECT
o.*,
o.discovery_tokens,
observations_fts.rank as rank
FROM observations o
JOIN observations_fts ON o.id = observations_fts.rowid
WHERE observations_fts MATCH ?
${p}
${h}
LIMIT ? OFFSET ?
`;a.push(t,n);let d=this.db.prepare(f).all(...a);if(d.length>0){let g=Math.min(...d.map(_=>_.rank||0)),y=Math.max(...d.map(_=>_.rank||0))-g||1;d.forEach(_=>{_.rank!==void 0&&(_.score=1-(_.rank-g)/y)})}return d}searchSessions(e,r={}){let a=[],{limit:t=50,offset:n=0,orderBy:o="relevance",...i}=r,l=this.escapeFTS5(e);a.push(l);let u={...i};delete u.type;let p=this.buildFilterClause(u,a,"s"),g=`
SELECT
s.*,
s.discovery_tokens,
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 ?
${(p?`AND ${p}`:"").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(t,n);let v=this.db.prepare(g).all(...a);if(v.length>0){let y=Math.min(...v.map(S=>S.rank||0)),R=Math.max(...v.map(S=>S.rank||0))-y||1;v.forEach(S=>{S.rank!==void 0&&(S.score=1-(S.rank-y)/R)})}return v}findByConcept(e,r={}){let a=[],{limit:t=50,offset:n=0,orderBy:o="date_desc",...i}=r,l={...i,concepts:e},u=this.buildFilterClause(l,a,"o"),p=this.buildOrderClause(o,!1),h=`
SELECT o.*, o.discovery_tokens
FROM observations o
WHERE ${u}
${p}
LIMIT ? OFFSET ?
`;return a.push(t,n),this.db.prepare(h).all(...a)}findByFile(e,r={}){let a=[],{limit:t=50,offset:n=0,orderBy:o="date_desc",...i}=r,l={...i,files:e},u=this.buildFilterClause(l,a,"o"),p=this.buildOrderClause(o,!1),h=`
SELECT o.*, o.discovery_tokens
FROM observations o
WHERE ${u}
${p}
LIMIT ? OFFSET ?
`;a.push(t,n);let f=this.db.prepare(h).all(...a),d=[],g={...i};delete g.type;let v=[];if(g.project&&(v.push("s.project = ?"),d.push(g.project)),g.dateRange){let{start:R,end:S}=g.dateRange;if(R){let w=typeof R=="number"?R:new Date(R).getTime();v.push("s.created_at_epoch >= ?"),d.push(w)}if(S){let w=typeof S=="number"?S:new Date(S).getTime();v.push("s.created_at_epoch <= ?"),d.push(w)}}v.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 y=`
SELECT s.*, s.discovery_tokens
FROM session_summaries s
WHERE ${v.join(" AND ")}
ORDER BY s.created_at_epoch DESC
LIMIT ? OFFSET ?
`;d.push(t,n);let _=this.db.prepare(y).all(...d);return{observations:f,sessions:_}}findByType(e,r={}){let a=[],{limit:t=50,offset:n=0,orderBy:o="date_desc",...i}=r,l={...i,type:e},u=this.buildFilterClause(l,a,"o"),p=this.buildOrderClause(o,!1),h=`
SELECT o.*, o.discovery_tokens
FROM observations o
WHERE ${u}
${p}
LIMIT ? OFFSET ?
`;return a.push(t,n),this.db.prepare(h).all(...a)}searchUserPrompts(e,r={}){let a=[],{limit:t=20,offset:n=0,orderBy:o="relevance",...i}=r,l=this.escapeFTS5(e);a.push(l);let u=[];if(i.project&&(u.push("s.project = ?"),a.push(i.project)),i.dateRange){let{start:g,end:v}=i.dateRange;if(g){let y=typeof g=="number"?g:new Date(g).getTime();u.push("up.created_at_epoch >= ?"),a.push(y)}if(v){let y=typeof v=="number"?v:new Date(v).getTime();u.push("up.created_at_epoch <= ?"),a.push(y)}}let f=`
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(t,n);let d=this.db.prepare(f).all(...a);if(d.length>0){let g=Math.min(...d.map(_=>_.rank||0)),y=Math.max(...d.map(_=>_.rank||0))-g||1;d.forEach(_=>{_.rank!==void 0&&(_.score=1-(_.rank-g)/y)})}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 yf from"better-sqlite3";var tn=(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))(tn||{}),rn=class{level;useColor;constructor(){let e=process.env.CLAUDE_MEM_LOG_LEVEL?.toUpperCase()||"INFO";this.level=tn[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 a=typeof r=="string"?JSON.parse(r):r;if(e==="Bash"&&a.command){let t=a.command.length>50?a.command.substring(0,50)+"...":a.command;return`${e}(${t})`}if(e==="Read"&&a.file_path){let t=a.file_path.split("/").pop()||a.file_path;return`${e}(${t})`}if(e==="Edit"&&a.file_path){let t=a.file_path.split("/").pop()||a.file_path;return`${e}(${t})`}if(e==="Write"&&a.file_path){let t=a.file_path.split("/").pop()||a.file_path;return`${e}(${t})`}return e}catch{return e}}log(e,r,a,t,n){if(e<this.level)return;let o=new Date().toISOString().replace("T"," ").substring(0,23),i=tn[e].padEnd(5),l=r.padEnd(6),u="";t?.correlationId?u=`[${t.correlationId}] `:t?.sessionId&&(u=`[session-${t.sessionId}] `);let p="";n!=null&&(this.level===0&&typeof n=="object"?p=`
`+JSON.stringify(n,null,2):p=" "+this.formatData(n));let h="";if(t){let{sessionId:d,sdkSessionId:g,correlationId:v,...y}=t;Object.keys(y).length>0&&(h=` {${Object.entries(y).map(([R,S])=>`${R}=${S}`).join(", ")}}`)}let f=`[${o}] [${i}] [${l}] ${u}${a}${h}${p}`;e===3?console.error(f):console.log(f)}debug(e,r,a,t){this.log(0,e,r,a,t)}info(e,r,a,t){this.log(1,e,r,a,t)}warn(e,r,a,t){this.log(2,e,r,a,t)}error(e,r,a,t){this.log(3,e,r,a,t)}dataIn(e,r,a,t){this.info(e,`\u2192 ${r}`,a,t)}dataOut(e,r,a,t){this.info(e,`\u2190 ${r}`,a,t)}success(e,r,a,t){this.info(e,`\u2713 ${r}`,a,t)}failure(e,r,a,t){this.error(e,`\u2717 ${r}`,a,t)}timing(e,r,a,t){this.info(e,`\u23F1 ${r}`,t,{duration:`${a}ms`})}},_l=new rn;var Fs=class{db;constructor(){Ls(at),this.db=new yf(ks),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(),this.ensureDiscoveryTokensColumn()}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(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(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(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 a=this.db.pragma("table_info(observations)").find(t=>t.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(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(a){throw this.db.exec("ROLLBACK"),a}}catch(e){console.error("[SessionStore] Migration error (create user_prompts table):",e.message)}}ensureDiscoveryTokensColumn(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(11))return;this.db.pragma("table_info(observations)").some(o=>o.name==="discovery_tokens")||(this.db.exec("ALTER TABLE observations ADD COLUMN discovery_tokens INTEGER DEFAULT 0"),console.error("[SessionStore] Added discovery_tokens column to observations table")),this.db.pragma("table_info(session_summaries)").some(o=>o.name==="discovery_tokens")||(this.db.exec("ALTER TABLE session_summaries ADD COLUMN discovery_tokens INTEGER DEFAULT 0"),console.error("[SessionStore] Added discovery_tokens column to session_summaries table")),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(11,new Date().toISOString())}catch(e){throw console.error("[SessionStore] Discovery tokens migration error:",e.message),e}}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)}getAllRecentObservations(e=100){return this.db.prepare(`
SELECT id, type, title, subtitle, text, project, prompt_number, created_at, created_at_epoch
FROM observations
ORDER BY created_at_epoch DESC
LIMIT ?
`).all(e)}getAllRecentSummaries(e=50){return this.db.prepare(`
SELECT id, request, investigated, learned, completed, next_steps,
files_read, files_edited, notes, project, prompt_number,
created_at, created_at_epoch
FROM session_summaries
ORDER BY created_at_epoch DESC
LIMIT ?
`).all(e)}getAllRecentUserPrompts(e=100){return this.db.prepare(`
SELECT
up.id,
up.claude_session_id,
s.project,
up.prompt_number,
up.prompt_text,
up.created_at,
up.created_at_epoch
FROM user_prompts up
LEFT JOIN sdk_sessions s ON up.claude_session_id = s.claude_session_id
ORDER BY up.created_at_epoch DESC
LIMIT ?
`).all(e)}getAllProjects(){return this.db.prepare(`
SELECT DISTINCT project
FROM sdk_sessions
WHERE project IS NOT NULL AND project != ''
ORDER BY project ASC
`).all().map(a=>a.project)}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)}getObservationById(e){return this.db.prepare(`
SELECT *
FROM observations
WHERE id = ?
`).get(e)||null}getObservationsByIds(e,r={}){if(e.length===0)return[];let{orderBy:a="date_desc",limit:t}=r,n=a==="date_asc"?"ASC":"DESC",o=t?`LIMIT ${t}`:"",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),t=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=>t.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(t),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,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,a){let t=new Date,n=t.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,r,a,t.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,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?(_l.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,a){let t=new Date,n=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,a,t.toISOString(),n).lastInsertRowid}storeObservation(e,r,a,t,n=0){let o=new Date,i=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(),i),console.error(`[SessionStore] Auto-created session record for session_id: ${e}`));let h=this.db.prepare(`
INSERT INTO observations
(sdk_session_id, project, type, title, subtitle, facts, narrative, concepts,
files_read, files_modified, prompt_number, discovery_tokens, created_at, created_at_epoch)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(e,r,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),t||null,n,o.toISOString(),i);return{id:Number(h.lastInsertRowid),createdAtEpoch:i}}storeSummary(e,r,a,t,n=0){let o=new Date,i=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(),i),console.error(`[SessionStore] Auto-created session record for session_id: ${e}`));let h=this.db.prepare(`
INSERT INTO session_summaries
(sdk_session_id, project, request, investigated, learned, completed,
next_steps, notes, prompt_number, discovery_tokens, created_at, created_at_epoch)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(e,r,a.request,a.investigated,a.learned,a.completed,a.next_steps,a.notes,t||null,n,o.toISOString(),i);return{id:Number(h.lastInsertRowid),createdAtEpoch:i}}markSessionCompleted(e){let r=new Date,a=r.getTime();this.db.prepare(`
UPDATE sdk_sessions
SET status = 'completed', completed_at = ?, completed_at_epoch = ?
WHERE id = ?
`).run(r.toISOString(),a,e)}markSessionFailed(e){let r=new Date,a=r.getTime();this.db.prepare(`
UPDATE sdk_sessions
SET status = 'failed', completed_at = ?, completed_at_epoch = ?
WHERE id = ?
`).run(r.toISOString(),a,e)}getSessionSummariesByIds(e,r={}){if(e.length===0)return[];let{orderBy:a="date_desc",limit:t}=r,n=a==="date_asc"?"ASC":"DESC",o=t?`LIMIT ${t}`:"",i=e.map(()=>"?").join(",");return this.db.prepare(`
SELECT * FROM session_summaries
WHERE id IN (${i})
ORDER BY created_at_epoch ${n}
${o}
`).all(...e)}getUserPromptsByIds(e,r={}){if(e.length===0)return[];let{orderBy:a="date_desc",limit:t}=r,n=a==="date_asc"?"ASC":"DESC",o=t?`LIMIT ${t}`:"",i=e.map(()=>"?").join(",");return this.db.prepare(`
SELECT
up.*,
s.project,
s.sdk_session_id
FROM user_prompts up
JOIN sdk_sessions s ON up.claude_session_id = s.claude_session_id
WHERE up.id IN (${i})
ORDER BY up.created_at_epoch ${n}
${o}
`).all(...e)}getTimelineAroundTimestamp(e,r=10,a=10,t){return this.getTimelineAroundObservation(null,e,r,a,t)}getTimelineAroundObservation(e,r,a=10,t=10,n){let o=n?"AND project = ?":"",i=n?[n]:[],l,u;if(e!==null){let d=`
SELECT id, created_at_epoch
FROM observations
WHERE id <= ? ${o}
ORDER BY id DESC
LIMIT ?
`,g=`
SELECT id, created_at_epoch
FROM observations
WHERE id >= ? ${o}
ORDER BY id ASC
LIMIT ?
`;try{let v=this.db.prepare(d).all(e,...i,a+1),y=this.db.prepare(g).all(e,...i,t+1);if(v.length===0&&y.length===0)return{observations:[],sessions:[],prompts:[]};l=v.length>0?v[v.length-1].created_at_epoch:r,u=y.length>0?y[y.length-1].created_at_epoch:r}catch(v){return console.error("[SessionStore] Error getting boundary observations:",v.message),{observations:[],sessions:[],prompts:[]}}}else{let d=`
SELECT created_at_epoch
FROM observations
WHERE created_at_epoch <= ? ${o}
ORDER BY created_at_epoch DESC
LIMIT ?
`,g=`
SELECT created_at_epoch
FROM observations
WHERE created_at_epoch >= ? ${o}
ORDER BY created_at_epoch ASC
LIMIT ?
`;try{let v=this.db.prepare(d).all(r,...i,a),y=this.db.prepare(g).all(r,...i,t+1);if(v.length===0&&y.length===0)return{observations:[],sessions:[],prompts:[]};l=v.length>0?v[v.length-1].created_at_epoch:r,u=y.length>0?y[y.length-1].created_at_epoch:r}catch(v){return console.error("[SessionStore] Error getting boundary timestamps:",v.message),{observations:[],sessions:[],prompts:[]}}}let p=`
SELECT *
FROM observations
WHERE created_at_epoch >= ? AND created_at_epoch <= ? ${o}
ORDER BY created_at_epoch ASC
`,h=`
SELECT *
FROM session_summaries
WHERE created_at_epoch >= ? AND created_at_epoch <= ? ${o}
ORDER BY created_at_epoch ASC
`,f=`
SELECT up.*, s.project, s.sdk_session_id
FROM user_prompts up
JOIN sdk_sessions s ON up.claude_session_id = s.claude_session_id
WHERE up.created_at_epoch >= ? AND up.created_at_epoch <= ? ${o.replace("project","s.project")}
ORDER BY up.created_at_epoch ASC
`;try{let d=this.db.prepare(p).all(l,u,...i),g=this.db.prepare(h).all(l,u,...i),v=this.db.prepare(f).all(l,u,...i);return{observations:d,sessions:g.map(y=>({id:y.id,sdk_session_id:y.sdk_session_id,project:y.project,request:y.request,completed:y.completed,next_steps:y.next_steps,created_at:y.created_at,created_at_epoch:y.created_at_epoch})),prompts:v.map(y=>({id:y.id,claude_session_id:y.claude_session_id,project:y.project,prompt:y.prompt_text,created_at:y.created_at,created_at_epoch:y.created_at_epoch}))}}catch(d){return console.error("[SessionStore] Error querying timeline records:",d.message),{observations:[],sessions:[],prompts:[]}}}close(){this.db.close()}};var ue,ne,Te=null,_f="cm__claude-mem";try{ue=new js,ne=new Fs}catch(s){console.error("[search-server] Failed to initialize search:",s.message),process.exit(1)}async function Ye(s,e,r){if(!Te)throw new Error("Chroma client not initialized");let t=(await Te.callTool({name:"chroma_query_documents",arguments:{collection_name:_f,query_texts:[s],n_results:e,include:["documents","metadatas","distances"],where:r}})).content[0]?.text||"",n;try{n=JSON.parse(t)}catch(p){return console.error("[search-server] Failed to parse Chroma response as JSON:",p),{ids:[],distances:[],metadatas:[]}}let o=[],i=n.ids?.[0]||[];for(let p of i){let h=p.match(/obs_(\d+)_/),f=p.match(/summary_(\d+)_/),d=p.match(/prompt_(\d+)/),g=null;h?g=parseInt(h[1],10):f?g=parseInt(f[1],10):d&&(g=parseInt(d[1],10)),g!==null&&!o.includes(g)&&o.push(g)}let l=n.distances?.[0]||[],u=n.metadatas?.[0]||[];return{ids:o,distances:l,metadatas:u}}function ar(){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 At(s,e){let r=s.title||`Observation #${s.id}`,a=new Date(s.created_at_epoch).toLocaleString(),t=s.type?`[${s.type}]`:"";return`${e+1}. ${t} ${r}
Date: ${a}
Source: claude-mem://observation/${s.id}`}function sn(s,e){let r=s.request||`Session ${s.sdk_session_id?.substring(0,8)||"unknown"}`,a=new Date(s.created_at_epoch).toLocaleString();return`${e+1}. ${r}
Date: ${a}
Source: claude-mem://session/${s.sdk_session_id}`}function Dt(s){let e=s.title||`Observation #${s.id}`,r=[];r.push(`## ${e}`),r.push(`*Source: claude-mem://observation/${s.id}*`),r.push(""),s.subtitle&&(r.push(`**${s.subtitle}**`),r.push("")),s.narrative&&(r.push(s.narrative),r.push("")),s.text&&(r.push(s.text),r.push(""));let a=[];if(a.push(`Type: ${s.type}`),s.facts)try{let n=JSON.parse(s.facts);n.length>0&&a.push(`Facts: ${n.join("; ")}`)}catch{}if(s.concepts)try{let n=JSON.parse(s.concepts);n.length>0&&a.push(`Concepts: ${n.join(", ")}`)}catch{}if(s.files_read||s.files_modified){let n=[];if(s.files_read)try{n.push(...JSON.parse(s.files_read))}catch{}if(s.files_modified)try{n.push(...JSON.parse(s.files_modified))}catch{}n.length>0&&a.push(`Files: ${[...new Set(n)].join(", ")}`)}a.length>0&&(r.push("---"),r.push(a.join(" | ")));let t=new Date(s.created_at_epoch).toLocaleString();return r.push(""),r.push("---"),r.push(`Date: ${t}`),r.join(`
`)}function an(s){let e=s.request||`Session ${s.sdk_session_id?.substring(0,8)||"unknown"}`,r=[];r.push(`## ${e}`),r.push(`*Source: claude-mem://session/${s.sdk_session_id}*`),r.push(""),s.completed&&(r.push(`**Completed:** ${s.completed}`),r.push("")),s.learned&&(r.push(`**Learned:** ${s.learned}`),r.push("")),s.investigated&&(r.push(`**Investigated:** ${s.investigated}`),r.push("")),s.next_steps&&(r.push(`**Next Steps:** ${s.next_steps}`),r.push("")),s.notes&&(r.push(`**Notes:** ${s.notes}`),r.push(""));let a=[];if(s.files_read||s.files_edited){let n=[];if(s.files_read)try{n.push(...JSON.parse(s.files_read))}catch{}if(s.files_edited)try{n.push(...JSON.parse(s.files_edited))}catch{}n.length>0&&a.push(`Files: ${[...new Set(n)].join(", ")}`)}let t=new Date(s.created_at_epoch).toLocaleDateString();return a.push(`Date: ${t}`),a.length>0&&(r.push("---"),r.push(a.join(" | "))),r.join(`
`)}function El(s,e){let r=new Date(s.created_at_epoch).toLocaleString();return`${e+1}. "${s.prompt_text}"
Date: ${r} | Prompt #${s.prompt_number}
Source: claude-mem://user-prompt/${s.id}`}function Sl(s){let e=[];e.push(`## User Prompt #${s.prompt_number}`),e.push(`*Source: claude-mem://user-prompt/${s.id}*`),e.push(""),e.push(s.prompt_text),e.push(""),e.push("---");let r=new Date(s.created_at_epoch).toLocaleString();return e.push(`Date: ${r}`),e.join(`
`)}var bf=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("date_desc").describe("Sort order")}),xl=[{name:"search",description:'Unified search across all memory types (observations, sessions, and user prompts) using hybrid semantic + full-text search (ChromaDB primary, SQLite FTS5 fallback). Returns combined results from all document types. 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("Natural language search query (semantic ranking via ChromaDB, FTS5 fallback)"),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().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("date_desc").describe("Sort order")}),handler:async s=>{try{let{query:e,format:r="index",...a}=s,t=[],n=[],o=[];if(Te)try{console.error("[search-server] Using unified hybrid semantic search (all document types)");let h=await Ye(e,100);if(console.error(`[search-server] Chroma returned ${h.ids.length} semantic matches across all types`),h.ids.length>0){let f=Date.now()-7776e6,d=h.metadatas.map((_,R)=>({id:h.ids[R],meta:_,isRecent:_&&_.created_at_epoch>f})).filter(_=>_.isRecent);console.error(`[search-server] ${d.length} results within 90-day window`);let g=[],v=[],y=[];for(let _ of d){let R=_.meta?.doc_type;R==="observation"?g.push(_.id):R==="session_summary"?v.push(_.id):R==="user_prompt"&&y.push(_.id)}console.error(`[search-server] Categorized: ${g.length} obs, ${v.length} sessions, ${y.length} prompts`),g.length>0&&(t=ne.getObservationsByIds(g,{orderBy:"date_desc",limit:a.limit})),v.length>0&&(n=ne.getSessionSummariesByIds(v,{orderBy:"date_desc",limit:a.limit})),y.length>0&&(o=ne.getUserPromptsByIds(y,{orderBy:"date_desc",limit:a.limit})),console.error(`[search-server] Hydrated ${t.length} obs, ${n.length} sessions, ${o.length} prompts from SQLite`)}}catch(h){console.error("[search-server] Chroma query failed, falling back to FTS5:",h.message)}t.length===0&&n.length===0&&o.length===0&&(console.error("[search-server] Using FTS5 keyword search across all types"),t=ue.searchObservations(e,a),n=ue.searchSessions(e,a),o=ue.searchUserPrompts(e,a));let i=t.length+n.length+o.length;if(i===0)return{content:[{type:"text",text:`No results found matching "${e}"`}]};let l=[...t.map(h=>({type:"observation",data:h,epoch:h.created_at_epoch})),...n.map(h=>({type:"session",data:h,epoch:h.created_at_epoch})),...o.map(h=>({type:"prompt",data:h,epoch:h.created_at_epoch}))];a.orderBy==="date_desc"?l.sort((h,f)=>f.epoch-h.epoch):a.orderBy==="date_asc"&&l.sort((h,f)=>h.epoch-f.epoch);let u=l.slice(0,a.limit||20),p;if(r==="index"){let h=`Found ${i} result(s) matching "${e}" (${t.length} obs, ${n.length} sessions, ${o.length} prompts):
`,f=u.map((d,g)=>d.type==="observation"?At(d.data,g):d.type==="session"?sn(d.data,g):El(d.data,g));p=h+f.join(`
`)+ar()}else p=u.map(f=>f.type==="observation"?Dt(f.data):f.type==="session"?an(f.data):Sl(f.data)).join(`
---
`);return{content:[{type:"text",text:p}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"timeline",description:"Get a unified timeline of context around a specific point in time OR search query. Supports two modes: (1) anchor-based: provide observation ID, session ID, or timestamp to center timeline around; (2) query-based: provide natural language query to find relevant observation and center timeline around it. All record types (observations, sessions, prompts) are interleaved chronologically.",inputSchema:c.object({anchor:c.union([c.number(),c.string()]).optional().describe('Anchor point: observation ID (number), session ID (e.g., "S123"), or ISO timestamp. Use this OR query, not both.'),query:c.string().optional().describe("Natural language search query to find relevant observation as anchor. Use this OR anchor, not both."),depth_before:c.number().min(0).max(50).default(10).describe("Number of records to retrieve before anchor (default: 10)"),depth_after:c.number().min(0).max(50).default(10).describe("Number of records to retrieve after anchor (default: 10)"),project:c.string().optional().describe("Filter by project name")}),handler:async s=>{try{let g=function(x){return new Date(x).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})},v=function(x){return new Date(x).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})},y=function(x){return new Date(x).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})},_=function(x){return x?Math.ceil(x.length/4):0};var e=g,r=v,a=y,t=_;let{anchor:n,query:o,depth_before:i=10,depth_after:l=10,project:u}=s;if(!n&&!o)return{content:[{type:"text",text:'Error: Must provide either "anchor" or "query" parameter'}],isError:!0};if(n&&o)return{content:[{type:"text",text:'Error: Cannot provide both "anchor" and "query" parameters. Use one or the other.'}],isError:!0};let p,h,f;if(o){let x=[];if(Te)try{console.error("[search-server] Using hybrid semantic search for timeline query");let N=await Ye(o,100);if(console.error(`[search-server] Chroma returned ${N.ids.length} semantic matches`),N.ids.length>0){let L=Date.now()-7776e6,I=N.ids.filter((F,k)=>{let j=N.metadatas[k];return j&&j.created_at_epoch>L});I.length>0&&(x=ne.getObservationsByIds(I,{orderBy:"date_desc",limit:1}))}}catch(N){console.error("[search-server] Chroma query failed, falling back to FTS5:",N.message)}if(x.length===0&&(console.error("[search-server] Using FTS5 keyword search"),x=ue.searchObservations(o,{orderBy:"relevance",limit:1,project:u})),x.length===0)return{content:[{type:"text",text:`No observations found matching "${o}". Try a different search query.`}]};let T=x[0];p=T.id,h=T.created_at_epoch,console.error(`[search-server] Query mode: Using observation #${T.id} as timeline anchor`),f=ne.getTimelineAroundObservation(T.id,T.created_at_epoch,i,l,u)}else if(typeof n=="number"){let x=ne.getObservationById(n);if(!x)return{content:[{type:"text",text:`Observation #${n} not found`}],isError:!0};p=n,h=x.created_at_epoch,f=ne.getTimelineAroundObservation(n,h,i,l,u)}else if(typeof n=="string")if(n.startsWith("S")||n.startsWith("#S")){let x=n.replace(/^#?S/,""),T=parseInt(x,10),N=ne.getSessionSummariesByIds([T]);if(N.length===0)return{content:[{type:"text",text:`Session #${T} not found`}],isError:!0};h=N[0].created_at_epoch,p=`S${T}`,f=ne.getTimelineAroundTimestamp(h,i,l,u)}else{let x=new Date(n);if(isNaN(x.getTime()))return{content:[{type:"text",text:`Invalid timestamp: ${n}`}],isError:!0};h=x.getTime(),p=n,f=ne.getTimelineAroundTimestamp(h,i,l,u)}else return{content:[{type:"text",text:'Invalid anchor: must be observation ID (number), session ID (e.g., "S123"), or ISO timestamp'}],isError:!0};let d=[...f.observations.map(x=>({type:"observation",data:x,epoch:x.created_at_epoch})),...f.sessions.map(x=>({type:"session",data:x,epoch:x.created_at_epoch})),...f.prompts.map(x=>({type:"prompt",data:x,epoch:x.created_at_epoch}))];if(d.sort((x,T)=>x.epoch-T.epoch),d.length===0)return{content:[{type:"text",text:o?`Found observation matching "${o}", but no timeline context available (${i} records before, ${l} records after).`:`No context found around anchor (${i} records before, ${l} records after)`}]};let R=[];if(o){let x=d.find(N=>N.type==="observation"&&N.data.id===p),T=x?x.data.title||"Untitled":"Unknown";R.push(`# Timeline for query: "${o}"`),R.push(`**Anchor:** Observation #${p} - ${T}`)}else R.push(`# Timeline around anchor: ${p}`);R.push(`**Window:** ${i} records before \u2192 ${l} records after | **Items:** ${d.length} (${f.observations.length} obs, ${f.sessions.length} sessions, ${f.prompts.length} prompts)`),R.push(""),R.push("**Legend:** \u{1F3AF} session-request | \u{1F534} bugfix | \u{1F7E3} feature | \u{1F504} refactor | \u2705 change | \u{1F535} discovery | \u{1F9E0} decision"),R.push("");let S=new Map;for(let x of d){let T=g(x.epoch);S.has(T)||S.set(T,[]),S.get(T).push(x)}let w=Array.from(S.entries()).sort((x,T)=>{let N=new Date(x[0]).getTime(),L=new Date(T[0]).getTime();return N-L});for(let[x,T]of w){R.push(`### ${x}`),R.push("");let N=null,L="",I=!1;for(let F of T){let k=typeof p=="number"&&F.type==="observation"&&F.data.id===p||typeof p=="string"&&p.startsWith("S")&&F.type==="session"&&`S${F.data.id}`===p;if(F.type==="session"){I&&(R.push(""),I=!1,N=null,L="");let j=F.data,$=j.request||"Session summary",A=`claude-mem://session-summary/${j.id}`,M=k?" \u2190 **ANCHOR**":"";R.push(`**\u{1F3AF} #S${j.id}** ${$} (${y(F.epoch)}) [\u2192](${A})${M}`),R.push("")}else if(F.type==="prompt"){I&&(R.push(""),I=!1,N=null,L="");let j=F.data,$=j.prompt.length>100?j.prompt.substring(0,100)+"...":j.prompt;R.push(`**\u{1F4AC} User Prompt #${j.prompt_number}** (${y(F.epoch)})`),R.push(`> ${$}`),R.push("")}else if(F.type==="observation"){let j=F.data,$="General";$!==N&&(I&&R.push(""),R.push(`**${$}**`),R.push("| ID | Time | T | Title | Tokens |"),R.push("|----|------|---|-------|--------|"),N=$,I=!0,L="");let A="\u2022";switch(j.type){case"bugfix":A="\u{1F534}";break;case"feature":A="\u{1F7E3}";break;case"refactor":A="\u{1F504}";break;case"change":A="\u2705";break;case"discovery":A="\u{1F535}";break;case"decision":A="\u{1F9E0}";break}let M=v(F.epoch),ee=j.title||"Untitled",W=_(j.narrative),Q=M!==L?M:"\u2033";L=M;let z=k?" \u2190 **ANCHOR**":"";R.push(`| #${j.id} | ${Q} | ${A} | ${ee}${z} | ~${W} |`)}}I&&R.push("")}return{content:[{type:"text",text:R.join(`
`)}]}}catch(n){return{content:[{type:"text",text:`Timeline query failed: ${n.message}`}],isError:!0}}}},{name:"decisions",description:'Semantic shortcut to find decision-type observations. Returns observations where important architectural, technical, or process decisions were made. Equivalent to find_by_type with type="decision".',inputSchema:c.object({format:c.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default), "full" for complete details'),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("date_desc").describe("Sort order")}),handler:async s=>{try{let{format:e="index",...r}=s,a=[];if(Te)try{console.error("[search-server] Using metadata-first + semantic ranking for decisions");let n=ue.findByType("decision",r);if(n.length>0){let o=n.map(u=>u.id),i=await Ye("decision",Math.min(o.length,100)),l=[];for(let u of i.ids)o.includes(u)&&!l.includes(u)&&l.push(u);l.length>0&&(a=ne.getObservationsByIds(l,{limit:r.limit||20}),a.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(a.length===0&&(a=ue.findByType("decision",r)),a.length===0)return{content:[{type:"text",text:"No decision observations found"}]};let t;if(e==="index"){let n=`Found ${a.length} decision(s):
`,o=a.map((i,l)=>At(i,l));t=n+o.join(`
`)}else t=a.map(o=>Dt(o)).join(`
---
`);return{content:[{type:"text",text:t}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"changes",description:'Semantic shortcut to find change-related observations. Returns observations documenting what changed in the codebase, system behavior, or project state. Searches for type="change" OR concept="change" OR concept="what-changed".',inputSchema:c.object({format:c.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default), "full" for complete details'),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("date_desc").describe("Sort order")}),handler:async s=>{try{let{format:e="index",...r}=s,a=[];if(Te)try{console.error("[search-server] Using hybrid search for change-related observations");let n=ue.findByType("change",r),o=ue.findByConcept("change",r),i=ue.findByConcept("what-changed",r),l=new Set;if([...n,...o,...i].forEach(u=>l.add(u.id)),l.size>0){let u=Array.from(l),p=await Ye("what changed",Math.min(u.length,100)),h=[];for(let f of p.ids)u.includes(f)&&!h.includes(f)&&h.push(f);h.length>0&&(a=ne.getObservationsByIds(h,{limit:r.limit||20}),a.sort((f,d)=>h.indexOf(f.id)-h.indexOf(d.id)))}}catch(n){console.error("[search-server] Chroma ranking failed, using SQLite order:",n.message)}if(a.length===0){let n=ue.findByType("change",r),o=ue.findByConcept("change",r),i=ue.findByConcept("what-changed",r),l=new Set;[...n,...o,...i].forEach(u=>l.add(u.id)),a=Array.from(l).map(u=>n.find(p=>p.id===u)||o.find(p=>p.id===u)||i.find(p=>p.id===u)).filter(Boolean),a.sort((u,p)=>p.created_at_epoch-u.created_at_epoch),a=a.slice(0,r.limit||20)}if(a.length===0)return{content:[{type:"text",text:"No change-related observations found"}]};let t;if(e==="index"){let n=`Found ${a.length} change-related observation(s):
`,o=a.map((i,l)=>At(i,l));t=n+o.join(`
`)}else t=a.map(o=>Dt(o)).join(`
---
`);return{content:[{type:"text",text:t}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"how_it_works",description:'Semantic shortcut to find "how it works" explanations. Returns observations documenting system architecture, component interactions, data flow, and technical mechanisms. Searches for concept="how-it-works".',inputSchema:c.object({format:c.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default), "full" for complete details'),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("date_desc").describe("Sort order")}),handler:async s=>{try{let{format:e="index",...r}=s,a=[];if(Te)try{console.error("[search-server] Using metadata-first + semantic ranking for how-it-works");let n=ue.findByConcept("how-it-works",r);if(n.length>0){let o=n.map(u=>u.id),i=await Ye("how it works architecture",Math.min(o.length,100)),l=[];for(let u of i.ids)o.includes(u)&&!l.includes(u)&&l.push(u);l.length>0&&(a=ne.getObservationsByIds(l,{limit:r.limit||20}),a.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(a.length===0&&(a=ue.findByConcept("how-it-works",r)),a.length===0)return{content:[{type:"text",text:'No "how it works" observations found'}]};let t;if(e==="index"){let n=`Found ${a.length} "how it works" observation(s):
`,o=a.map((i,l)=>At(i,l));t=n+o.join(`
`)}else t=a.map(o=>Dt(o)).join(`
---
`);return{content:[{type:"text",text:t}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"contextualize",description:`Hybrid context builder that provides comprehensive project overview. Fetches recent observations (7), sessions (7), and user prompts (3), then builds a timeline around the newest activity. Perfect for quickly understanding "what's been happening" in a project.`,inputSchema:c.object({project:c.string().optional().describe("Project name (defaults to current working directory basename)"),observations_limit:c.number().min(1).max(20).default(7).describe("Number of recent observations to fetch (default: 7)"),sessions_limit:c.number().min(1).max(20).default(7).describe("Number of recent sessions to fetch (default: 7)"),prompts_limit:c.number().min(1).max(20).default(3).describe("Number of recent user prompts to fetch (default: 3)"),timeline_depth:c.number().min(0).max(50).default(5).describe("Timeline depth (records before and after newest item, default: 5)")}),handler:async s=>{try{let{project:a=bl(process.cwd()),observations_limit:t=7,sessions_limit:n=7,prompts_limit:o=3,timeline_depth:i=5}=s,l=ue.searchObservations("*",{project:a,orderBy:"date_desc",limit:t}),u=ue.searchSessions("*",{project:a,orderBy:"date_desc",limit:n}),p=ue.searchUserPrompts("*",{project:a,orderBy:"date_desc",limit:o}),h=[...l.map(_=>({type:"observation",data:_,epoch:_.created_at_epoch})),...u.map(_=>({type:"session",data:_,epoch:_.created_at_epoch})),...p.map(_=>({type:"prompt",data:_,epoch:_.created_at_epoch}))];if(h.length===0)return{content:[{type:"text",text:`# Project Context: ${a}
No activity found for this project.`}]};h.sort((_,R)=>R.epoch-_.epoch);let f=h[0],d=ne.getTimelineAroundTimestamp(f.epoch,i,i,a),g=[...d.observations.map(_=>({type:"observation",data:_,epoch:_.created_at_epoch})),...d.sessions.map(_=>({type:"session",data:_,epoch:_.created_at_epoch})),...d.prompts.map(_=>({type:"prompt",data:_,epoch:_.created_at_epoch}))];g.sort((_,R)=>_.epoch-R.epoch);let v=[];v.push(`# Project Context: ${a}`),v.push(""),v.push(`**Overview:** ${l.length} observations, ${u.length} sessions, ${p.length} prompts`);let y=new Date(f.epoch).toLocaleString();if(v.push(`**Latest Activity:** ${y}`),v.push(""),l.length>0){v.push(`## Recent Observations (${l.length})`),v.push("");for(let _=0;_<Math.min(3,l.length);_++){let R=l[_],S=new Date(R.created_at_epoch).toLocaleDateString(),w=R.type==="decision"?"\u{1F9E0}":R.type==="bugfix"?"\u{1F534}":R.type==="feature"?"\u{1F7E3}":R.type==="change"?"\u2705":R.type==="discovery"?"\u{1F535}":"\u2022";v.push(`${_+1}. ${w} ${R.title||"Untitled"} (${S})`)}l.length>3&&v.push(`... and ${l.length-3} more`),v.push("")}if(u.length>0){v.push(`## Recent Sessions (${u.length})`),v.push("");for(let _=0;_<Math.min(3,u.length);_++){let R=u[_],S=new Date(R.created_at_epoch).toLocaleDateString(),w=R.request||"Untitled session";v.push(`${_+1}. \u{1F3AF} ${w} (${S})`)}u.length>3&&v.push(`... and ${u.length-3} more`),v.push("")}if(p.length>0){v.push(`## Recent User Prompts (${p.length})`),v.push("");for(let _=0;_<p.length;_++){let R=p[_],S=new Date(R.created_at_epoch).toLocaleDateString(),w=R.prompt_text.length>60?R.prompt_text.substring(0,60)+"...":R.prompt_text;v.push(`${_+1}. \u{1F4AC} "${w}" (${S})`)}v.push("")}if(g.length>0){let _=function(x){return new Date(x).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})},R=function(x){return new Date(x).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})};var e=_,r=R;v.push(`## Activity Timeline (\xB1${i} records around latest)`),v.push("");let S=new Map;for(let x of g){let T=_(x.epoch);S.has(T)||S.set(T,[]),S.get(T).push(x)}let w=Array.from(S.entries()).sort((x,T)=>{let N=new Date(x[0]).getTime();return new Date(T[0]).getTime()-N});for(let[x,T]of w.slice(0,3)){v.push(`**${x}**`);for(let N of T.slice(0,5)){let L=R(N.epoch);if(N.type==="observation"){let I=N.data.type==="decision"?"\u{1F9E0}":N.data.type==="bugfix"?"\u{1F534}":N.data.type==="feature"?"\u{1F7E3}":N.data.type==="change"?"\u2705":N.data.type==="discovery"?"\u{1F535}":"\u2022",F=N.data.title||"Untitled";v.push(`- ${L} ${I} ${F}`)}else if(N.type==="session"){let I=N.data.request||"Session";v.push(`- ${L} \u{1F3AF} ${I}`)}else{let I=N.data.prompt.length>50?N.data.prompt.substring(0,50)+"...":N.data.prompt;v.push(`- ${L} \u{1F4AC} "${I}"`)}}v.push("")}}return v.push("---"),v.push("\u{1F4A1} Use `search`, `timeline`, `decisions`, `changes`, or `how_it_works` tools for deeper exploration"),{content:[{type:"text",text:v.join(`
`)}]}}catch(a){return{content:[{type:"text",text:`Context building failed: ${a.message}`}],isError:!0}}}},{name:"search_observations",description:'Search observations using hybrid semantic + full-text search (ChromaDB primary, SQLite FTS5 fallback). 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("Natural language search query (semantic ranking via ChromaDB, FTS5 fallback)"),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)'),...bf.shape}),handler:async s=>{try{let{query:e,format:r="index",...a}=s,t=[];if(Te)try{console.error("[search-server] Using hybrid semantic search (Chroma + SQLite)");let o=await Ye(e,100);if(console.error(`[search-server] Chroma returned ${o.ids.length} semantic matches`),o.ids.length>0){let i=Date.now()-7776e6,l=o.ids.filter((u,p)=>{let h=o.metadatas[p];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;t=ne.getObservationsByIds(l,{orderBy:"date_desc",limit:u}),console.error(`[search-server] Hydrated ${t.length} observations from SQLite`)}}}catch(o){console.error("[search-server] Chroma query failed, falling back to FTS5:",o.message)}if(t.length===0&&(console.error("[search-server] Using FTS5 keyword search"),t=ue.searchObservations(e,a)),t.length===0)return{content:[{type:"text",text:`No observations found matching "${e}"`}]};let n;if(r==="index"){let o=`Found ${t.length} observation(s) matching "${e}":
`,i=t.map((l,u)=>At(l,u));n=o+i.join(`
`)+ar()}else n=t.map(i=>Dt(i)).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 hybrid semantic + full-text search (ChromaDB primary, SQLite FTS5 fallback). 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("Natural language search query (semantic ranking via ChromaDB, FTS5 fallback)"),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("date_desc").describe("Sort order")}),handler:async s=>{try{let{query:e,format:r="index",...a}=s,t=[];if(Te)try{console.error("[search-server] Using hybrid semantic search for sessions");let o=await Ye(e,100,{doc_type:"session_summary"});if(console.error(`[search-server] Chroma returned ${o.ids.length} semantic matches`),o.ids.length>0){let i=Date.now()-7776e6,l=o.ids.filter((u,p)=>{let h=o.metadatas[p];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;t=ne.getSessionSummariesByIds(l,{orderBy:"date_desc",limit:u}),console.error(`[search-server] Hydrated ${t.length} sessions from SQLite`)}}}catch(o){console.error("[search-server] Chroma query failed, falling back to FTS5:",o.message)}if(t.length===0&&(console.error("[search-server] Using FTS5 keyword search"),t=ue.searchSessions(e,a)),t.length===0)return{content:[{type:"text",text:`No sessions found matching "${e}"`}]};let n;if(r==="index"){let o=`Found ${t.length} session(s) matching "${e}":
`,i=t.map((l,u)=>sn(l,u));n=o+i.join(`
`)+ar()}else n=t.map(i=>an(i)).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. Available concepts: "discovery", "problem-solution", "what-changed", "how-it-works", "pattern", "gotcha", "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({concept:c.string().describe("Concept tag to search for. Available: discovery, problem-solution, what-changed, how-it-works, pattern, gotcha, change"),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:r="index",...a}=s,t=[];if(Te)try{console.error("[search-server] Using metadata-first + semantic ranking for concept search");let o=ue.findByConcept(e,a);if(console.error(`[search-server] Found ${o.length} observations with concept "${e}"`),o.length>0){let i=o.map(p=>p.id),l=await Ye(e,Math.min(i.length,100)),u=[];for(let p of l.ids)i.includes(p)&&!u.includes(p)&&u.push(p);console.error(`[search-server] Chroma ranked ${u.length} results by semantic relevance`),u.length>0&&(t=ne.getObservationsByIds(u,{limit:a.limit||20}),t.sort((p,h)=>u.indexOf(p.id)-u.indexOf(h.id)))}}catch(o){console.error("[search-server] Chroma ranking failed, using SQLite order:",o.message)}if(t.length===0&&(console.error("[search-server] Using SQLite-only concept search"),t=ue.findByConcept(e,a)),t.length===0)return{content:[{type:"text",text:`No observations found with concept "${e}"`}]};let n;if(r==="index"){let o=`Found ${t.length} observation(s) with concept "${e}":
`,i=t.map((l,u)=>At(l,u));n=o+i.join(`
`)+ar()}else n=t.map(i=>Dt(i)).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:r="index",...a}=s,t=[],n=[];if(Te)try{console.error("[search-server] Using metadata-first + semantic ranking for file search");let l=ue.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(f=>f.id),p=await Ye(e,Math.min(u.length,100)),h=[];for(let f of p.ids)u.includes(f)&&!h.includes(f)&&h.push(f);console.error(`[search-server] Chroma ranked ${h.length} observations by semantic relevance`),h.length>0&&(t=ne.getObservationsByIds(h,{limit:a.limit||20}),t.sort((f,d)=>h.indexOf(f.id)-h.indexOf(d.id)))}}catch(l){console.error("[search-server] Chroma ranking failed, using SQLite order:",l.message)}if(t.length===0&&n.length===0){console.error("[search-server] Using SQLite-only file search");let l=ue.findByFile(e,a);t=l.observations,n=l.sessions}let o=t.length+n.length;if(o===0)return{content:[{type:"text",text:`No results found for file "${e}"`}]};let i;if(r==="index"){let l=`Found ${o} result(s) for file "${e}":
`,u=[];t.forEach((p,h)=>{u.push(At(p,h))}),n.forEach((p,h)=>{u.push(sn(p,h+t.length))}),i=l+u.join(`
`)+ar()}else{let l=[];t.forEach(u=>{l.push(Dt(u))}),n.forEach(u=>{l.push(an(u))}),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:r="index",...a}=s,t=Array.isArray(e)?e.join(", "):e,n=[];if(Te)try{console.error("[search-server] Using metadata-first + semantic ranking for type search");let i=ue.findByType(e,a);if(console.error(`[search-server] Found ${i.length} observations with type "${t}"`),i.length>0){let l=i.map(h=>h.id),u=await Ye(t,Math.min(l.length,100)),p=[];for(let h of u.ids)l.includes(h)&&!p.includes(h)&&p.push(h);console.error(`[search-server] Chroma ranked ${p.length} results by semantic relevance`),p.length>0&&(n=ne.getObservationsByIds(p,{limit:a.limit||20}),n.sort((h,f)=>p.indexOf(h.id)-p.indexOf(f.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=ue.findByType(e,a)),n.length===0)return{content:[{type:"text",text:`No observations found with type "${t}"`}]};let o;if(r==="index"){let i=`Found ${n.length} observation(s) with type "${t}":
`,l=n.map((u,p)=>At(u,p));o=i+l.join(`
`)+ar()}else o=n.map(l=>Dt(l)).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||bl(process.cwd()),r=s.limit||3,a=ne.getRecentSessionsWithStatus(e,r);if(a.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 ${a.length} session(s) for **${e}**:`),t.push("");for(let n of a)if(n.sdk_session_id){if(t.push("---"),t.push(""),n.has_summary){let o=ne.getSummaryForSession(n.sdk_session_id);if(o){let i=o.prompt_number?` (Prompt #${o.prompt_number})`:"";if(t.push(`**Summary${i}**`),t.push(""),o.request&&t.push(`**Request:** ${o.request}`),o.completed&&t.push(`**Completed:** ${o.completed}`),o.learned&&t.push(`**Learned:** ${o.learned}`),o.next_steps&&t.push(`**Next Steps:** ${o.next_steps}`),o.files_read)try{let u=JSON.parse(o.files_read);Array.isArray(u)&&u.length>0&&t.push(`**Files Read:** ${u.join(", ")}`)}catch{o.files_read.trim()&&t.push(`**Files Read:** ${o.files_read}`)}if(o.files_edited)try{let u=JSON.parse(o.files_edited);Array.isArray(u)&&u.length>0&&t.push(`**Files Edited:** ${u.join(", ")}`)}catch{o.files_edited.trim()&&t.push(`**Files Edited:** ${o.files_edited}`)}let l=new Date(o.created_at).toLocaleString();t.push(`**Date:** ${l}`)}}else if(n.status==="active"){t.push("**In Progress**"),t.push(""),n.user_prompt&&t.push(`**Request:** ${n.user_prompt}`);let o=ne.getObservationsForSession(n.sdk_session_id);if(o.length>0){t.push(""),t.push(`**Observations (${o.length}):**`);for(let l of o)t.push(`- ${l.title}`)}else t.push(""),t.push("*No observations yet*");t.push(""),t.push("**Status:** Active - summary pending");let i=new Date(n.started_at).toLocaleString();t.push(`**Date:** ${i}`)}else{t.push(`**${n.status.charAt(0).toUpperCase()+n.status.slice(1)}**`),t.push(""),n.user_prompt&&t.push(`**Request:** ${n.user_prompt}`),t.push(""),t.push(`**Status:** ${n.status} - no summary available`);let o=new Date(n.started_at).toLocaleString();t.push(`**Date:** ${o}`)}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 using hybrid semantic + full-text search (ChromaDB primary, SQLite FTS5 fallback). 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("Natural language search query (semantic ranking via ChromaDB, FTS5 fallback)"),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("date_desc").describe("Sort order")}),handler:async s=>{try{let{query:e,format:r="index",...a}=s,t=[];if(Te)try{console.error("[search-server] Using hybrid semantic search for user prompts");let o=await Ye(e,100,{doc_type:"user_prompt"});if(console.error(`[search-server] Chroma returned ${o.ids.length} semantic matches`),o.ids.length>0){let i=Date.now()-7776e6,l=o.ids.filter((u,p)=>{let h=o.metadatas[p];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;t=ne.getUserPromptsByIds(l,{orderBy:"date_desc",limit:u}),console.error(`[search-server] Hydrated ${t.length} user prompts from SQLite`)}}}catch(o){console.error("[search-server] Chroma query failed, falling back to FTS5:",o.message)}if(t.length===0&&(console.error("[search-server] Using FTS5 keyword search"),t=ue.searchUserPrompts(e,a)),t.length===0)return{content:[{type:"text",text:`No user prompts found matching "${e}"`}]};let n;if(r==="index"){let o=`Found ${t.length} user prompt(s) matching "${e}":
`,i=t.map((l,u)=>El(l,u));n=o+i.join(`
`)+ar()}else n=t.map(i=>Sl(i)).join(`
---
`);return{content:[{type:"text",text:n}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"get_context_timeline",description:'Get a unified timeline of context (observations, sessions, and prompts) around a specific point in time. All record types are interleaved chronologically. Useful for understanding "what was happening when X occurred". Returns depth_before records before anchor + anchor + depth_after records after (total: depth_before + 1 + depth_after mixed records).',inputSchema:c.object({anchor:c.union([c.number().describe("Observation ID to center timeline around"),c.string().describe("Session ID (format: S123) or ISO timestamp to center timeline around")]).describe('Anchor point: observation ID, session ID (e.g., "S123"), or ISO timestamp'),depth_before:c.number().min(0).max(50).default(10).describe("Number of records to retrieve before anchor, not including anchor (default: 10)"),depth_after:c.number().min(0).max(50).default(10).describe("Number of records to retrieve after anchor, not including anchor (default: 10)"),project:c.string().optional().describe("Filter by project name")}),handler:async s=>{try{let d=function(w){return new Date(w).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})},g=function(w){return new Date(w).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})},v=function(w){return new Date(w).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})},y=function(w){return w?Math.ceil(w.length/4):0};var e=d,r=g,a=v,t=y;let{anchor:n,depth_before:o=10,depth_after:i=10,project:l}=s,u,p=n,h;if(typeof n=="number"){let w=ne.getObservationById(n);if(!w)return{content:[{type:"text",text:`Observation #${n} not found`}],isError:!0};u=w.created_at_epoch,h=ne.getTimelineAroundObservation(n,u,o,i,l)}else if(typeof n=="string")if(n.startsWith("S")||n.startsWith("#S")){let w=n.replace(/^#?S/,""),x=parseInt(w,10),T=ne.getSessionSummariesByIds([x]);if(T.length===0)return{content:[{type:"text",text:`Session #${x} not found`}],isError:!0};u=T[0].created_at_epoch,p=`S${x}`,h=ne.getTimelineAroundTimestamp(u,o,i,l)}else{let w=new Date(n);if(isNaN(w.getTime()))return{content:[{type:"text",text:`Invalid timestamp: ${n}`}],isError:!0};u=w.getTime(),h=ne.getTimelineAroundTimestamp(u,o,i,l)}else return{content:[{type:"text",text:'Invalid anchor: must be observation ID (number), session ID (e.g., "S123"), or ISO timestamp'}],isError:!0};let f=[...h.observations.map(w=>({type:"observation",data:w,epoch:w.created_at_epoch})),...h.sessions.map(w=>({type:"session",data:w,epoch:w.created_at_epoch})),...h.prompts.map(w=>({type:"prompt",data:w,epoch:w.created_at_epoch}))];if(f.sort((w,x)=>w.epoch-x.epoch),f.length===0)return{content:[{type:"text",text:`No context found around ${new Date(u).toLocaleString()} (${o} records before, ${i} records after)`}]};let _=[];_.push(`# Timeline around anchor: ${p}`),_.push(`**Window:** ${o} records before \u2192 ${i} records after | **Items:** ${f.length} (${h.observations.length} obs, ${h.sessions.length} sessions, ${h.prompts.length} prompts)`),_.push(""),_.push("**Legend:** \u{1F3AF} session-request | \u{1F534} bugfix | \u{1F7E3} feature | \u{1F504} refactor | \u2705 change | \u{1F535} discovery | \u{1F9E0} decision"),_.push("");let R=new Map;for(let w of f){let x=d(w.epoch);R.has(x)||R.set(x,[]),R.get(x).push(w)}let S=Array.from(R.entries()).sort((w,x)=>{let T=new Date(w[0]).getTime(),N=new Date(x[0]).getTime();return T-N});for(let[w,x]of S){_.push(`### ${w}`),_.push("");let T=null,N="",L=!1;for(let I of x){let F=typeof p=="number"&&I.type==="observation"&&I.data.id===p||typeof p=="string"&&p.startsWith("S")&&I.type==="session"&&`S${I.data.id}`===p;if(I.type==="session"){L&&(_.push(""),L=!1,T=null,N="");let k=I.data,j=k.request||"Session summary",$=`claude-mem://session-summary/${k.id}`,A=F?" \u2190 **ANCHOR**":"";_.push(`**\u{1F3AF} #S${k.id}** ${j} (${v(I.epoch)}) [\u2192](${$})${A}`),_.push("")}else if(I.type==="prompt"){L&&(_.push(""),L=!1,T=null,N="");let k=I.data,j=k.prompt.length>100?k.prompt.substring(0,100)+"...":k.prompt;_.push(`**\u{1F4AC} User Prompt #${k.prompt_number}** (${v(I.epoch)})`),_.push(`> ${j}`),_.push("")}else if(I.type==="observation"){let k=I.data,j="General";j!==T&&(L&&_.push(""),_.push(`**${j}**`),_.push("| ID | Time | T | Title | Tokens |"),_.push("|----|------|---|-------|--------|"),T=j,L=!0,N="");let $="\u2022";switch(k.type){case"bugfix":$="\u{1F534}";break;case"feature":$="\u{1F7E3}";break;case"refactor":$="\u{1F504}";break;case"change":$="\u2705";break;case"discovery":$="\u{1F535}";break;case"decision":$="\u{1F9E0}";break}let A=g(I.epoch),M=k.title||"Untitled",ee=y(k.narrative),Y=A!==N?A:"\u2033";N=A;let Q=F?" \u2190 **ANCHOR**":"";_.push(`| #${k.id} | ${Y} | ${$} | ${M}${Q} | ~${ee} |`)}}L&&_.push("")}return{content:[{type:"text",text:_.join(`
`)}]}}catch(n){return{content:[{type:"text",text:`Timeline query failed: ${n.message}`}],isError:!0}}}},{name:"get_timeline_by_query",description:'Search for observations using natural language and get timeline context around the best match. Two modes: "auto" (default) automatically uses top result as timeline anchor; "interactive" returns top matches for you to choose from. This combines search + timeline into a single operation for faster context discovery.',inputSchema:c.object({query:c.string().describe("Natural language search query to find relevant observations"),mode:c.enum(["auto","interactive"]).default("auto").describe("auto: Automatically use top search result as timeline anchor. interactive: Show top N search results for manual anchor selection."),depth_before:c.number().min(0).max(50).default(10).describe("Number of timeline records before anchor (default: 10)"),depth_after:c.number().min(0).max(50).default(10).describe("Number of timeline records after anchor (default: 10)"),limit:c.number().min(1).max(20).default(5).describe("For interactive mode: number of top search results to display (default: 5)"),project:c.string().optional().describe("Filter by project name")}),handler:async s=>{try{let{query:n,mode:o="auto",depth_before:i=10,depth_after:l=10,limit:u=5,project:p}=s,h=[];if(Te)try{console.error("[search-server] Using hybrid semantic search for timeline query");let f=await Ye(n,100);if(console.error(`[search-server] Chroma returned ${f.ids.length} semantic matches`),f.ids.length>0){let d=Date.now()-7776e6,g=f.ids.filter((v,y)=>{let _=f.metadatas[y];return _&&_.created_at_epoch>d});console.error(`[search-server] ${g.length} results within 90-day window`),g.length>0&&(h=ne.getObservationsByIds(g,{orderBy:"date_desc",limit:o==="auto"?1:u}),console.error(`[search-server] Hydrated ${h.length} observations from SQLite`))}}catch(f){console.error("[search-server] Chroma query failed, falling back to FTS5:",f.message)}if(h.length===0&&(console.error("[search-server] Using FTS5 keyword search"),h=ue.searchObservations(n,{orderBy:"relevance",limit:o==="auto"?1:u,project:p})),h.length===0)return{content:[{type:"text",text:`No observations found matching "${n}". Try a different search query.`}]};if(o==="interactive"){let f=[];f.push("# Timeline Anchor Search Results"),f.push(""),f.push(`Found ${h.length} observation(s) matching "${n}"`),f.push(""),f.push("To get timeline context around any of these observations, use the `get_context_timeline` tool with the observation ID as the anchor."),f.push(""),f.push(`**Top ${h.length} matches:**`),f.push("");for(let d=0;d<h.length;d++){let g=h[d],v=g.title||`Observation #${g.id}`,y=new Date(g.created_at_epoch).toLocaleString(),_=g.type?`[${g.type}]`:"";f.push(`${d+1}. **${_} ${v}**`),f.push(` - ID: ${g.id}`),f.push(` - Date: ${y}`),g.subtitle&&f.push(` - ${g.subtitle}`),f.push(` - Source: claude-mem://observation/${g.id}`),f.push("")}return{content:[{type:"text",text:f.join(`
`)}]}}else{let v=function(T){return new Date(T).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})},y=function(T){return new Date(T).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})},_=function(T){return new Date(T).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})},R=function(T){return T?Math.ceil(T.length/4):0};var e=v,r=y,a=_,t=R;let f=h[0];console.error(`[search-server] Auto mode: Using observation #${f.id} as timeline anchor`);let d=ne.getTimelineAroundObservation(f.id,f.created_at_epoch,i,l,p),g=[...d.observations.map(T=>({type:"observation",data:T,epoch:T.created_at_epoch})),...d.sessions.map(T=>({type:"session",data:T,epoch:T.created_at_epoch})),...d.prompts.map(T=>({type:"prompt",data:T,epoch:T.created_at_epoch}))];if(g.sort((T,N)=>T.epoch-N.epoch),g.length===0)return{content:[{type:"text",text:`Found observation #${f.id} matching "${n}", but no timeline context available (${i} records before, ${l} records after).`}]};let S=[];S.push(`# Timeline for query: "${n}"`),S.push(`**Anchor:** Observation #${f.id} - ${f.title||"Untitled"}`),S.push(`**Window:** ${i} records before \u2192 ${l} records after | **Items:** ${g.length} (${d.observations.length} obs, ${d.sessions.length} sessions, ${d.prompts.length} prompts)`),S.push(""),S.push("**Legend:** \u{1F3AF} session-request | \u{1F534} bugfix | \u{1F7E3} feature | \u{1F504} refactor | \u2705 change | \u{1F535} discovery | \u{1F9E0} decision"),S.push("");let w=new Map;for(let T of g){let N=v(T.epoch);w.has(N)||w.set(N,[]),w.get(N).push(T)}let x=Array.from(w.entries()).sort((T,N)=>{let L=new Date(T[0]).getTime(),I=new Date(N[0]).getTime();return L-I});for(let[T,N]of x){S.push(`### ${T}`),S.push("");let L=null,I="",F=!1;for(let k of N){let j=k.type==="observation"&&k.data.id===f.id;if(k.type==="session"){F&&(S.push(""),F=!1,L=null,I="");let $=k.data,A=$.request||"Session summary",M=`claude-mem://session-summary/${$.id}`;S.push(`**\u{1F3AF} #S${$.id}** ${A} (${_(k.epoch)}) [\u2192](${M})`),S.push("")}else if(k.type==="prompt"){F&&(S.push(""),F=!1,L=null,I="");let $=k.data,A=$.prompt.length>100?$.prompt.substring(0,100)+"...":$.prompt;S.push(`**\u{1F4AC} User Prompt #${$.prompt_number}** (${_(k.epoch)})`),S.push(`> ${A}`),S.push("")}else if(k.type==="observation"){let $=k.data,A="General";A!==L&&(F&&S.push(""),S.push(`**${A}**`),S.push("| ID | Time | T | Title | Tokens |"),S.push("|----|------|---|-------|--------|"),L=A,F=!0,I="");let M="\u2022";switch($.type){case"bugfix":M="\u{1F534}";break;case"feature":M="\u{1F7E3}";break;case"refactor":M="\u{1F504}";break;case"change":M="\u2705";break;case"discovery":M="\u{1F535}";break;case"decision":M="\u{1F9E0}";break}let ee=y(k.epoch),W=$.title||"Untitled",Y=R($.narrative),z=ee!==I?ee:"\u2033";I=ee;let he=j?" \u2190 **ANCHOR**":"";S.push(`| #${$.id} | ${z} | ${M} | ${W}${he} | ~${Y} |`)}}F&&S.push("")}return{content:[{type:"text",text:S.join(`
`)}]}}}catch(n){return{content:[{type:"text",text:`Timeline query failed: ${n.message}`}],isError:!0}}}}],nn=new Rs({name:"claude-mem-search",version:"1.0.0"},{capabilities:{tools:{}}});nn.setRequestHandler(ia,async()=>({tools:xl.map(s=>({name:s.name,description:s.description,inputSchema:Ya(s.inputSchema)}))}));nn.setRequestHandler(la,async s=>{let e=xl.find(r=>r.name===s.params.name);if(!e)throw new Error(`Unknown tool: ${s.params.name}`);try{return await e.handler(s.params.arguments||{})}catch(r){return{content:[{type:"text",text:`Tool execution failed: ${r.message}`}],isError:!0}}});async function Rl(){if(console.error("[search-server] Shutting down..."),Te)try{await Te.close(),console.error("[search-server] Chroma client closed")}catch(s){console.error("[search-server] Error closing Chroma client:",s.message)}if(ue)try{ue.close(),console.error("[search-server] SessionSearch closed")}catch(s){console.error("[search-server] Error closing SessionSearch:",s.message)}if(ne)try{ne.close(),console.error("[search-server] SessionStore closed")}catch(s){console.error("[search-server] Error closing SessionStore:",s.message)}console.error("[search-server] Shutdown complete"),process.exit(0)}process.on("SIGTERM",Rl);process.on("SIGINT",Rl);async function Ef(){let s=new ws;await nn.connect(s),console.error("[search-server] Claude-mem search server started"),setTimeout(async()=>{try{console.error("[search-server] Initializing Chroma client...");let e=new Is({command:"uvx",args:["chroma-mcp","--client-type","persistent","--data-dir",yl],stderr:"ignore"}),r=new Ps({name:"claude-mem-search-chroma-client",version:"1.0.0"},{capabilities:{}});await r.connect(e),Te=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"),Te=null}},0)}Ef().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 *)
*/