octocode-mcp 2.3.19 → 2.3.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
1
2
|
import e,{z as r,ZodFirstPartyTypeKind as t,ZodType as a}from"zod";import s from"node:process";import o from"node-cache";import n from"crypto";import{exec as i}from"child_process";import{promisify as c}from"util";import{platform as l}from"os";import{minify as u}from"terser";import{transform as d}from"@babel/core";const p="2025-06-18",h=[p,"2025-03-26","2024-11-05","2024-10-07"],m="2.0",f=r.union([r.string(),r.number().int()]),g=r.string(),v=r.object({progressToken:r.optional(f)}).passthrough(),y=r.object({_meta:r.optional(v)}).passthrough(),b=r.object({method:r.string(),params:r.optional(y)}),w=r.object({_meta:r.optional(r.object({}).passthrough())}).passthrough(),P=r.object({method:r.string(),params:r.optional(w)}),_=r.object({_meta:r.optional(r.object({}).passthrough())}).passthrough(),E=r.union([r.string(),r.number().int()]),S=r.object({jsonrpc:r.literal(m),id:E}).merge(b).strict(),$=r.object({jsonrpc:r.literal(m)}).merge(P).strict(),x=r.object({jsonrpc:r.literal(m),id:E,result:_}).strict(),k=e=>x.safeParse(e).success;var R;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError"}(R||(R={}));const j=r.object({jsonrpc:r.literal(m),id:E,error:r.object({code:r.number().int(),message:r.string(),data:r.optional(r.unknown())})}).strict(),T=r.union([S,$,x,j]),A=_.strict(),O=P.extend({method:r.literal("notifications/cancelled"),params:w.extend({requestId:E,reason:r.string().optional()})}),F=r.object({name:r.string(),title:r.optional(r.string())}).passthrough(),C=F.extend({version:r.string()}),I=r.object({experimental:r.optional(r.object({}).passthrough()),sampling:r.optional(r.object({}).passthrough()),elicitation:r.optional(r.object({}).passthrough()),roots:r.optional(r.object({listChanged:r.optional(r.boolean())}).passthrough())}).passthrough(),q=b.extend({method:r.literal("initialize"),params:y.extend({protocolVersion:r.string(),capabilities:I,clientInfo:C})}),N=r.object({experimental:r.optional(r.object({}).passthrough()),logging:r.optional(r.object({}).passthrough()),completions:r.optional(r.object({}).passthrough()),prompts:r.optional(r.object({listChanged:r.optional(r.boolean())}).passthrough()),resources:r.optional(r.object({subscribe:r.optional(r.boolean()),listChanged:r.optional(r.boolean())}).passthrough()),tools:r.optional(r.object({listChanged:r.optional(r.boolean())}).passthrough())}).passthrough(),D=_.extend({protocolVersion:r.string(),capabilities:N,serverInfo:C,instructions:r.optional(r.string())}),H=P.extend({method:r.literal("notifications/initialized")}),L=b.extend({method:r.literal("ping")}),U=r.object({progress:r.number(),total:r.optional(r.number()),message:r.optional(r.string())}).passthrough(),z=P.extend({method:r.literal("notifications/progress"),params:w.merge(U).extend({progressToken:f})}),M=b.extend({params:y.extend({cursor:r.optional(g)}).optional()}),Q=_.extend({nextCursor:r.optional(g)}),V=r.object({uri:r.string(),mimeType:r.optional(r.string()),_meta:r.optional(r.object({}).passthrough())}).passthrough(),Z=V.extend({text:r.string()}),B=V.extend({blob:r.string().base64()}),G=F.extend({uri:r.string(),description:r.optional(r.string()),mimeType:r.optional(r.string()),_meta:r.optional(r.object({}).passthrough())}),J=F.extend({uriTemplate:r.string(),description:r.optional(r.string()),mimeType:r.optional(r.string()),_meta:r.optional(r.object({}).passthrough())}),K=M.extend({method:r.literal("resources/list")}),W=Q.extend({resources:r.array(G)}),Y=M.extend({method:r.literal("resources/templates/list")}),X=Q.extend({resourceTemplates:r.array(J)}),ee=b.extend({method:r.literal("resources/read"),params:y.extend({uri:r.string()})}),re=_.extend({contents:r.array(r.union([Z,B]))}),te=P.extend({method:r.literal("notifications/resources/list_changed")}),ae=b.extend({method:r.literal("resources/subscribe"),params:y.extend({uri:r.string()})}),se=b.extend({method:r.literal("resources/unsubscribe"),params:y.extend({uri:r.string()})}),oe=P.extend({method:r.literal("notifications/resources/updated"),params:w.extend({uri:r.string()})}),ne=r.object({name:r.string(),description:r.optional(r.string()),required:r.optional(r.boolean())}).passthrough(),ie=F.extend({description:r.optional(r.string()),arguments:r.optional(r.array(ne)),_meta:r.optional(r.object({}).passthrough())}),ce=M.extend({method:r.literal("prompts/list")}),le=Q.extend({prompts:r.array(ie)}),ue=b.extend({method:r.literal("prompts/get"),params:y.extend({name:r.string(),arguments:r.optional(r.record(r.string()))})}),de=r.object({type:r.literal("text"),text:r.string(),_meta:r.optional(r.object({}).passthrough())}).passthrough(),pe=r.object({type:r.literal("image"),data:r.string().base64(),mimeType:r.string(),_meta:r.optional(r.object({}).passthrough())}).passthrough(),he=r.object({type:r.literal("audio"),data:r.string().base64(),mimeType:r.string(),_meta:r.optional(r.object({}).passthrough())}).passthrough(),me=r.object({type:r.literal("resource"),resource:r.union([Z,B]),_meta:r.optional(r.object({}).passthrough())}).passthrough(),fe=G.extend({type:r.literal("resource_link")}),ge=r.union([de,pe,he,fe,me]),ve=r.object({role:r.enum(["user","assistant"]),content:ge}).passthrough(),ye=_.extend({description:r.optional(r.string()),messages:r.array(ve)}),be=P.extend({method:r.literal("notifications/prompts/list_changed")}),we=r.object({title:r.optional(r.string()),readOnlyHint:r.optional(r.boolean()),destructiveHint:r.optional(r.boolean()),idempotentHint:r.optional(r.boolean()),openWorldHint:r.optional(r.boolean())}).passthrough(),Pe=F.extend({description:r.optional(r.string()),inputSchema:r.object({type:r.literal("object"),properties:r.optional(r.object({}).passthrough()),required:r.optional(r.array(r.string()))}).passthrough(),outputSchema:r.optional(r.object({type:r.literal("object"),properties:r.optional(r.object({}).passthrough()),required:r.optional(r.array(r.string()))}).passthrough()),annotations:r.optional(we),_meta:r.optional(r.object({}).passthrough())}),_e=M.extend({method:r.literal("tools/list")}),Ee=Q.extend({tools:r.array(Pe)}),Se=_.extend({content:r.array(ge).default([]),structuredContent:r.object({}).passthrough().optional(),isError:r.optional(r.boolean())});Se.or(_.extend({toolResult:r.unknown()}));const $e=b.extend({method:r.literal("tools/call"),params:y.extend({name:r.string(),arguments:r.optional(r.record(r.unknown()))})}),xe=P.extend({method:r.literal("notifications/tools/list_changed")}),ke=r.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Re=b.extend({method:r.literal("logging/setLevel"),params:y.extend({level:ke})}),je=P.extend({method:r.literal("notifications/message"),params:w.extend({level:ke,logger:r.optional(r.string()),data:r.unknown()})}),Te=r.object({name:r.string().optional()}).passthrough(),Ae=r.object({hints:r.optional(r.array(Te)),costPriority:r.optional(r.number().min(0).max(1)),speedPriority:r.optional(r.number().min(0).max(1)),intelligencePriority:r.optional(r.number().min(0).max(1))}).passthrough(),Oe=r.object({role:r.enum(["user","assistant"]),content:r.union([de,pe,he])}).passthrough(),Fe=b.extend({method:r.literal("sampling/createMessage"),params:y.extend({messages:r.array(Oe),systemPrompt:r.optional(r.string()),includeContext:r.optional(r.enum(["none","thisServer","allServers"])),temperature:r.optional(r.number()),maxTokens:r.number().int(),stopSequences:r.optional(r.array(r.string())),metadata:r.optional(r.object({}).passthrough()),modelPreferences:r.optional(Ae)})}),Ce=_.extend({model:r.string(),stopReason:r.optional(r.enum(["endTurn","stopSequence","maxTokens"]).or(r.string())),role:r.enum(["user","assistant"]),content:r.discriminatedUnion("type",[de,pe,he])}),Ie=r.object({type:r.literal("boolean"),title:r.optional(r.string()),description:r.optional(r.string()),default:r.optional(r.boolean())}).passthrough(),qe=r.object({type:r.literal("string"),title:r.optional(r.string()),description:r.optional(r.string()),minLength:r.optional(r.number()),maxLength:r.optional(r.number()),format:r.optional(r.enum(["email","uri","date","date-time"]))}).passthrough(),Ne=r.object({type:r.enum(["number","integer"]),title:r.optional(r.string()),description:r.optional(r.string()),minimum:r.optional(r.number()),maximum:r.optional(r.number())}).passthrough(),De=r.object({type:r.literal("string"),title:r.optional(r.string()),description:r.optional(r.string()),enum:r.array(r.string()),enumNames:r.optional(r.array(r.string()))}).passthrough(),He=r.union([Ie,qe,Ne,De]),Le=b.extend({method:r.literal("elicitation/create"),params:y.extend({message:r.string(),requestedSchema:r.object({type:r.literal("object"),properties:r.record(r.string(),He),required:r.optional(r.array(r.string()))}).passthrough()})}),Ue=_.extend({action:r.enum(["accept","decline","cancel"]),content:r.optional(r.record(r.string(),r.unknown()))}),ze=r.object({type:r.literal("ref/resource"),uri:r.string()}).passthrough(),Me=r.object({type:r.literal("ref/prompt"),name:r.string()}).passthrough(),Qe=b.extend({method:r.literal("completion/complete"),params:y.extend({ref:r.union([Me,ze]),argument:r.object({name:r.string(),value:r.string()}).passthrough(),context:r.optional(r.object({arguments:r.optional(r.record(r.string(),r.string()))}))})}),Ve=_.extend({completion:r.object({values:r.array(r.string()).max(100),total:r.optional(r.number().int()),hasMore:r.optional(r.boolean())}).passthrough()}),Ze=r.object({uri:r.string().startsWith("file://"),name:r.optional(r.string()),_meta:r.optional(r.object({}).passthrough())}).passthrough(),Be=b.extend({method:r.literal("roots/list")}),Ge=_.extend({roots:r.array(Ze)}),Je=P.extend({method:r.literal("notifications/roots/list_changed")});r.union([L,q,Qe,Re,ue,ce,K,Y,ee,ae,se,$e,_e]),r.union([O,z,H,Je]),r.union([A,Ce,Ue,Ge]),r.union([L,Fe,Le,Be]),r.union([O,z,je,oe,te,xe,be]),r.union([A,D,Ve,ye,le,W,X,re,Se,Ee]);class Ke extends Error{constructor(e,r,t){super(`MCP error ${e}: ${r}`),this.code=e,this.data=t,this.name="McpError"}}class We{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.setNotificationHandler(O,e=>{const r=this._requestHandlerAbortControllers.get(e.params.requestId);null==r||r.abort(e.params.reason)}),this.setNotificationHandler(z,e=>{this._onprogress(e)}),this.setRequestHandler(L,e=>({}))}_setupTimeout(e,r,t,a,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(a,r),startTime:Date.now(),timeout:r,maxTotalTimeout:t,resetTimeoutOnProgress:s,onTimeout:a})}_resetTimeout(e){const r=this._timeoutInfo.get(e);if(!r)return!1;const t=Date.now()-r.startTime;if(r.maxTotalTimeout&&t>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),new Ke(R.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:t});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){const r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,t,a;this._transport=e;const s=null===(r=this.transport)||void 0===r?void 0:r.onclose;this._transport.onclose=()=>{null==s||s(),this._onclose()};const o=null===(t=this.transport)||void 0===t?void 0:t.onerror;this._transport.onerror=e=>{null==o||o(e),this._onerror(e)};const n=null===(a=this._transport)||void 0===a?void 0:a.onmessage;this._transport.onmessage=(e,r)=>{var t;null==n||n(e,r),k(e)||(t=e,j.safeParse(t).success)?this._onresponse(e):(e=>S.safeParse(e).success)(e)?this._onrequest(e,r):(e=>$.safeParse(e).success)(e)?this._onnotification(e):this._onerror(new Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){var e;const r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._transport=void 0,null===(e=this.onclose)||void 0===e||e.call(this);const t=new Ke(R.ConnectionClosed,"Connection closed");for(const e of r.values())e(t)}_onerror(e){var r;null===(r=this.onerror)||void 0===r||r.call(this,e)}_onnotification(e){var r;const t=null!==(r=this._notificationHandlers.get(e.method))&&void 0!==r?r:this.fallbackNotificationHandler;void 0!==t&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,r){var t,a,s,o;const n=null!==(t=this._requestHandlers.get(e.method))&&void 0!==t?t:this.fallbackRequestHandler;if(void 0===n)return void(null===(a=this._transport)||void 0===a||a.send({jsonrpc:"2.0",id:e.id,error:{code:R.MethodNotFound,message:"Method not found"}}).catch(e=>this._onerror(new Error(`Failed to send an error response: ${e}`))));const i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);const c={signal:i.signal,sessionId:null===(s=this._transport)||void 0===s?void 0:s.sessionId,_meta:null===(o=e.params)||void 0===o?void 0:o._meta,sendNotification:r=>this.notification(r,{relatedRequestId:e.id}),sendRequest:(r,t,a)=>this.request(r,t,{...a,relatedRequestId:e.id}),authInfo:null==r?void 0:r.authInfo,requestId:e.id,requestInfo:null==r?void 0:r.requestInfo};Promise.resolve().then(()=>n(e,c)).then(r=>{var t;if(!i.signal.aborted)return null===(t=this._transport)||void 0===t?void 0:t.send({result:r,jsonrpc:"2.0",id:e.id})},r=>{var t,a;if(!i.signal.aborted)return null===(t=this._transport)||void 0===t?void 0:t.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(r.code)?r.code:R.InternalError,message:null!==(a=r.message)&&void 0!==a?a:"Internal error"}})}).catch(e=>this._onerror(new Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:r,...t}=e.params,a=Number(r),s=this._progressHandlers.get(a);if(!s)return void this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));const o=this._responseHandlers.get(a),n=this._timeoutInfo.get(a);if(n&&o&&n.resetTimeoutOnProgress)try{this._resetTimeout(a)}catch(e){return void o(e)}s(t)}_onresponse(e){const r=Number(e.id),t=this._responseHandlers.get(r);void 0!==t?(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),k(e)?t(e):t(new Ke(e.error.code,e.error.message,e.error.data))):this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`))}get transport(){return this._transport}async close(){var e;await(null===(e=this._transport)||void 0===e?void 0:e.close())}request(e,r,t){const{relatedRequestId:a,resumptionToken:s,onresumptiontoken:o}=null!=t?t:{};return new Promise((n,i)=>{var c,l,u,d,p,h;if(!this._transport)return void i(new Error("Not connected"));!0===(null===(c=this._options)||void 0===c?void 0:c.enforceStrictCapabilities)&&this.assertCapabilityForMethod(e.method),null===(l=null==t?void 0:t.signal)||void 0===l||l.throwIfAborted();const m=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:m};(null==t?void 0:t.onprogress)&&(this._progressHandlers.set(m,t.onprogress),f.params={...e.params,_meta:{...(null===(u=e.params)||void 0===u?void 0:u._meta)||{},progressToken:m}});const g=e=>{var r;this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),null===(r=this._transport)||void 0===r||r.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(e)}},{relatedRequestId:a,resumptionToken:s,onresumptiontoken:o}).catch(e=>this._onerror(new Error(`Failed to send cancellation: ${e}`))),i(e)};this._responseHandlers.set(m,e=>{var a;if(!(null===(a=null==t?void 0:t.signal)||void 0===a?void 0:a.aborted)){if(e instanceof Error)return i(e);try{const t=r.parse(e.result);n(t)}catch(e){i(e)}}}),null===(d=null==t?void 0:t.signal)||void 0===d||d.addEventListener("abort",()=>{var e;g(null===(e=null==t?void 0:t.signal)||void 0===e?void 0:e.reason)});const v=null!==(p=null==t?void 0:t.timeout)&&void 0!==p?p:6e4;this._setupTimeout(m,v,null==t?void 0:t.maxTotalTimeout,()=>g(new Ke(R.RequestTimeout,"Request timed out",{timeout:v})),null!==(h=null==t?void 0:t.resetTimeoutOnProgress)&&void 0!==h&&h),this._transport.send(f,{relatedRequestId:a,resumptionToken:s,onresumptiontoken:o}).catch(e=>{this._cleanupTimeout(m),i(e)})})}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const t={...e,jsonrpc:"2.0"};await this._transport.send(t,r)}setRequestHandler(e,r){const t=e.shape.method.value;this.assertRequestHandlerCapability(t),this._requestHandlers.set(t,(t,a)=>Promise.resolve(r(e.parse(t),a)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){this._notificationHandlers.set(e.shape.method.value,t=>Promise.resolve(r(e.parse(t))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}function Ye(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Xe,er,rr,tr,ar,sr,or,nr,ir,cr={exports:{}};function lr(){return Xe||(Xe=1,function(e){function r(){for(var e=arguments.length,r=Array(e),t=0;t<e;t++)r[t]=arguments[t];if(r.length>1){r[0]=r[0].slice(0,-1);for(var a=r.length-1,s=1;s<a;++s)r[s]=r[s].slice(1,-1);return r[a]=r[a].slice(1),r.join("")}return r[0]}function t(e){return"(?:"+e+")"}function a(e){return void 0===e?"undefined":null===e?"null":Object.prototype.toString.call(e).split(" ").pop().split("]").shift().toLowerCase()}function s(e){return e.toUpperCase()}function o(e){var a="[A-Za-z]",s="[0-9]",o=r(s,"[A-Fa-f]"),n=t(t("%[EFef]"+o+"%"+o+o+"%"+o+o)+"|"+t("%[89A-Fa-f]"+o+"%"+o+o)+"|"+t("%"+o+o)),i="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",c=r("[\\:\\/\\?\\#\\[\\]\\@]",i),l=e?"[\\uE000-\\uF8FF]":"[]",u=r(a,s,"[\\-\\.\\_\\~]",e?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]");t(a+r(a,s,"[\\+\\-\\.]")+"*"),t(t(n+"|"+r(u,i,"[\\:]"))+"*");var d=t(t("25[0-5]")+"|"+t("2[0-4]"+s)+"|"+t("1"+s+s)+"|"+t("0?[1-9]"+s)+"|0?0?"+s),p=t(d+"\\."+d+"\\."+d+"\\."+d),h=t(o+"{1,4}"),m=t(t(h+"\\:"+h)+"|"+p),f=t(t(h+"\\:")+"{6}"+m),g=t("\\:\\:"+t(h+"\\:")+"{5}"+m),v=t(t(h)+"?\\:\\:"+t(h+"\\:")+"{4}"+m),y=t(t(t(h+"\\:")+"{0,1}"+h)+"?\\:\\:"+t(h+"\\:")+"{3}"+m),b=t(t(t(h+"\\:")+"{0,2}"+h)+"?\\:\\:"+t(h+"\\:")+"{2}"+m),w=t(t(t(h+"\\:")+"{0,3}"+h)+"?\\:\\:"+h+"\\:"+m),P=t(t(t(h+"\\:")+"{0,4}"+h)+"?\\:\\:"+m),_=t(t(t(h+"\\:")+"{0,5}"+h)+"?\\:\\:"+h),E=t(t(t(h+"\\:")+"{0,6}"+h)+"?\\:\\:"),S=t([f,g,v,y,b,w,P,_,E].join("|")),$=t(t(u+"|"+n)+"+");t("[vV]"+o+"+\\."+r(u,i,"[\\:]")+"+"),t(t(n+"|"+r(u,i))+"*");var x=t(n+"|"+r(u,i,"[\\:\\@]"));return t(t(n+"|"+r(u,i,"[\\@]"))+"+"),t(t(x+"|"+r("[\\/\\?]",l))+"*"),{NOT_SCHEME:new RegExp(r("[^]",a,s,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(r("[^\\%\\:]",u,i),"g"),NOT_HOST:new RegExp(r("[^\\%\\[\\]\\:]",u,i),"g"),NOT_PATH:new RegExp(r("[^\\%\\/\\:\\@]",u,i),"g"),NOT_PATH_NOSCHEME:new RegExp(r("[^\\%\\/\\@]",u,i),"g"),NOT_QUERY:new RegExp(r("[^\\%]",u,i,"[\\:\\@\\/\\?]",l),"g"),NOT_FRAGMENT:new RegExp(r("[^\\%]",u,i,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(r("[^]",u,i),"g"),UNRESERVED:new RegExp(u,"g"),OTHER_CHARS:new RegExp(r("[^\\%]",u,c),"g"),PCT_ENCODED:new RegExp(n,"g"),IPV4ADDRESS:new RegExp("^("+p+")$"),IPV6ADDRESS:new RegExp("^\\[?("+S+")"+t(t("\\%25|\\%(?!"+o+"{2})")+"("+$+")")+"?\\]?$")}}var n=o(!1),i=o(!0),c=function(e,r){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,r){var t=[],a=!0,s=!1,o=void 0;try{for(var n,i=e[Symbol.iterator]();!(a=(n=i.next()).done)&&(t.push(n.value),!r||t.length!==r);a=!0);}catch(e){s=!0,o=e}finally{try{!a&&i.return&&i.return()}finally{if(s)throw o}}return t}(e,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")},l=2147483647,u=36,d=/^xn--/,p=/[^\0-\x7E]/,h=/[\x2E\u3002\uFF0E\uFF61]/g,m={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},f=Math.floor,g=String.fromCharCode;function v(e){throw new RangeError(m[e])}function y(e,r){var t=e.split("@"),a="";return t.length>1&&(a=t[0]+"@",e=t[1]),a+function(e,r){for(var t=[],a=e.length;a--;)t[a]=r(e[a]);return t}((e=e.replace(h,".")).split("."),r).join(".")}function b(e){for(var r=[],t=0,a=e.length;t<a;){var s=e.charCodeAt(t++);if(s>=55296&&s<=56319&&t<a){var o=e.charCodeAt(t++);56320==(64512&o)?r.push(((1023&s)<<10)+(1023&o)+65536):(r.push(s),t--)}else r.push(s)}return r}var w=function(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:u},P=function(e,r){return e+22+75*(e<26)-((0!=r)<<5)},_=function(e,r,t){var a=0;for(e=t?f(e/700):e>>1,e+=f(e/r);e>455;a+=u)e=f(e/35);return f(a+36*e/(e+38))},E=function(e){var r=[],t=e.length,a=0,s=128,o=72,n=e.lastIndexOf("-");n<0&&(n=0);for(var i=0;i<n;++i)e.charCodeAt(i)>=128&&v("not-basic"),r.push(e.charCodeAt(i));for(var c=n>0?n+1:0;c<t;){for(var d=a,p=1,h=u;;h+=u){c>=t&&v("invalid-input");var m=w(e.charCodeAt(c++));(m>=u||m>f((l-a)/p))&&v("overflow"),a+=m*p;var g=h<=o?1:h>=o+26?26:h-o;if(m<g)break;var y=u-g;p>f(l/y)&&v("overflow"),p*=y}var b=r.length+1;o=_(a-d,b,0==d),f(a/b)>l-s&&v("overflow"),s+=f(a/b),a%=b,r.splice(a++,0,s)}return String.fromCodePoint.apply(String,r)},S=function(e){var r=[],t=(e=b(e)).length,a=128,s=0,o=72,n=!0,i=!1,c=void 0;try{for(var d,p=e[Symbol.iterator]();!(n=(d=p.next()).done);n=!0){var h=d.value;h<128&&r.push(g(h))}}catch(e){i=!0,c=e}finally{try{!n&&p.return&&p.return()}finally{if(i)throw c}}var m=r.length,y=m;for(m&&r.push("-");y<t;){var w=l,E=!0,S=!1,$=void 0;try{for(var x,k=e[Symbol.iterator]();!(E=(x=k.next()).done);E=!0){var R=x.value;R>=a&&R<w&&(w=R)}}catch(e){S=!0,$=e}finally{try{!E&&k.return&&k.return()}finally{if(S)throw $}}var j=y+1;w-a>f((l-s)/j)&&v("overflow"),s+=(w-a)*j,a=w;var T=!0,A=!1,O=void 0;try{for(var F,C=e[Symbol.iterator]();!(T=(F=C.next()).done);T=!0){var I=F.value;if(I<a&&++s>l&&v("overflow"),I==a){for(var q=s,N=u;;N+=u){var D=N<=o?1:N>=o+26?26:N-o;if(q<D)break;var H=q-D,L=u-D;r.push(g(P(D+H%L,0))),q=f(H/L)}r.push(g(P(q,0))),o=_(s,j,y==m),s=0,++y}}}catch(e){A=!0,O=e}finally{try{!T&&C.return&&C.return()}finally{if(A)throw O}}++s,++a}return r.join("")},$=function(e){return y(e,function(e){return p.test(e)?"xn--"+S(e):e})},x=function(e){return y(e,function(e){return d.test(e)?E(e.slice(4).toLowerCase()):e})},k={};function R(e){var r=e.charCodeAt(0);return r<16?"%0"+r.toString(16).toUpperCase():r<128?"%"+r.toString(16).toUpperCase():r<2048?"%"+(r>>6|192).toString(16).toUpperCase()+"%"+(63&r|128).toString(16).toUpperCase():"%"+(r>>12|224).toString(16).toUpperCase()+"%"+(r>>6&63|128).toString(16).toUpperCase()+"%"+(63&r|128).toString(16).toUpperCase()}function j(e){for(var r="",t=0,a=e.length;t<a;){var s=parseInt(e.substr(t+1,2),16);if(s<128)r+=String.fromCharCode(s),t+=3;else if(s>=194&&s<224){if(a-t>=6){var o=parseInt(e.substr(t+4,2),16);r+=String.fromCharCode((31&s)<<6|63&o)}else r+=e.substr(t,6);t+=6}else if(s>=224){if(a-t>=9){var n=parseInt(e.substr(t+4,2),16),i=parseInt(e.substr(t+7,2),16);r+=String.fromCharCode((15&s)<<12|(63&n)<<6|63&i)}else r+=e.substr(t,9);t+=9}else r+=e.substr(t,3),t+=3}return r}function T(e,r){function t(e){var t=j(e);return t.match(r.UNRESERVED)?t:e}return e.scheme&&(e.scheme=String(e.scheme).replace(r.PCT_ENCODED,t).toLowerCase().replace(r.NOT_SCHEME,"")),void 0!==e.userinfo&&(e.userinfo=String(e.userinfo).replace(r.PCT_ENCODED,t).replace(r.NOT_USERINFO,R).replace(r.PCT_ENCODED,s)),void 0!==e.host&&(e.host=String(e.host).replace(r.PCT_ENCODED,t).toLowerCase().replace(r.NOT_HOST,R).replace(r.PCT_ENCODED,s)),void 0!==e.path&&(e.path=String(e.path).replace(r.PCT_ENCODED,t).replace(e.scheme?r.NOT_PATH:r.NOT_PATH_NOSCHEME,R).replace(r.PCT_ENCODED,s)),void 0!==e.query&&(e.query=String(e.query).replace(r.PCT_ENCODED,t).replace(r.NOT_QUERY,R).replace(r.PCT_ENCODED,s)),void 0!==e.fragment&&(e.fragment=String(e.fragment).replace(r.PCT_ENCODED,t).replace(r.NOT_FRAGMENT,R).replace(r.PCT_ENCODED,s)),e}function A(e){return e.replace(/^0*(.*)/,"$1")||"0"}function O(e,r){var t=e.match(r.IPV4ADDRESS)||[],a=c(t,2)[1];return a?a.split(".").map(A).join("."):e}function F(e,r){var t=e.match(r.IPV6ADDRESS)||[],a=c(t,3),s=a[1],o=a[2];if(s){for(var n=s.toLowerCase().split("::").reverse(),i=c(n,2),l=i[0],u=i[1],d=u?u.split(":").map(A):[],p=l.split(":").map(A),h=r.IPV4ADDRESS.test(p[p.length-1]),m=h?7:8,f=p.length-m,g=Array(m),v=0;v<m;++v)g[v]=d[v]||p[f+v]||"";h&&(g[m-1]=O(g[m-1],r));var y=g.reduce(function(e,r,t){if(!r||"0"===r){var a=e[e.length-1];a&&a.index+a.length===t?a.length++:e.push({index:t,length:1})}return e},[]).sort(function(e,r){return r.length-e.length})[0],b=void 0;if(y&&y.length>1){var w=g.slice(0,y.index),P=g.slice(y.index+y.length);b=w.join(":")+"::"+P.join(":")}else b=g.join(":");return o&&(b+="%"+o),b}return e}var C=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,I=void 0==="".match(/(){0}/)[1];function q(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},t={},a=!1!==r.iri?i:n;"suffix"===r.reference&&(e=(r.scheme?r.scheme+":":"")+"//"+e);var s=e.match(C);if(s){I?(t.scheme=s[1],t.userinfo=s[3],t.host=s[4],t.port=parseInt(s[5],10),t.path=s[6]||"",t.query=s[7],t.fragment=s[8],isNaN(t.port)&&(t.port=s[5])):(t.scheme=s[1]||void 0,t.userinfo=-1!==e.indexOf("@")?s[3]:void 0,t.host=-1!==e.indexOf("//")?s[4]:void 0,t.port=parseInt(s[5],10),t.path=s[6]||"",t.query=-1!==e.indexOf("?")?s[7]:void 0,t.fragment=-1!==e.indexOf("#")?s[8]:void 0,isNaN(t.port)&&(t.port=e.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?s[4]:void 0)),t.host&&(t.host=F(O(t.host,a),a)),void 0!==t.scheme||void 0!==t.userinfo||void 0!==t.host||void 0!==t.port||t.path||void 0!==t.query?void 0===t.scheme?t.reference="relative":void 0===t.fragment?t.reference="absolute":t.reference="uri":t.reference="same-document",r.reference&&"suffix"!==r.reference&&r.reference!==t.reference&&(t.error=t.error||"URI is not a "+r.reference+" reference.");var o=k[(r.scheme||t.scheme||"").toLowerCase()];if(r.unicodeSupport||o&&o.unicodeSupport)T(t,a);else{if(t.host&&(r.domainHost||o&&o.domainHost))try{t.host=$(t.host.replace(a.PCT_ENCODED,j).toLowerCase())}catch(e){t.error=t.error||"Host's domain name can not be converted to ASCII via punycode: "+e}T(t,n)}o&&o.parse&&o.parse(t,r)}else t.error=t.error||"URI can not be parsed.";return t}var N=/^\.\.?\//,D=/^\/\.(\/|$)/,H=/^\/\.\.(\/|$)/,L=/^\/?(?:.|\n)*?(?=\/|$)/;function U(e){for(var r=[];e.length;)if(e.match(N))e=e.replace(N,"");else if(e.match(D))e=e.replace(D,"/");else if(e.match(H))e=e.replace(H,"/"),r.pop();else if("."===e||".."===e)e="";else{var t=e.match(L);if(!t)throw new Error("Unexpected dot segment condition");var a=t[0];e=e.slice(a.length),r.push(a)}return r.join("")}function z(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},t=r.iri?i:n,a=[],s=k[(r.scheme||e.scheme||"").toLowerCase()];if(s&&s.serialize&&s.serialize(e,r),e.host)if(t.IPV6ADDRESS.test(e.host));else if(r.domainHost||s&&s.domainHost)try{e.host=r.iri?x(e.host):$(e.host.replace(t.PCT_ENCODED,j).toLowerCase())}catch(t){e.error=e.error||"Host's domain name can not be converted to "+(r.iri?"Unicode":"ASCII")+" via punycode: "+t}T(e,t),"suffix"!==r.reference&&e.scheme&&(a.push(e.scheme),a.push(":"));var o=function(e,r){var t=!1!==r.iri?i:n,a=[];return void 0!==e.userinfo&&(a.push(e.userinfo),a.push("@")),void 0!==e.host&&a.push(F(O(String(e.host),t),t).replace(t.IPV6ADDRESS,function(e,r,t){return"["+r+(t?"%25"+t:"")+"]"})),"number"!=typeof e.port&&"string"!=typeof e.port||(a.push(":"),a.push(String(e.port))),a.length?a.join(""):void 0}(e,r);if(void 0!==o&&("suffix"!==r.reference&&a.push("//"),a.push(o),e.path&&"/"!==e.path.charAt(0)&&a.push("/")),void 0!==e.path){var c=e.path;r.absolutePath||s&&s.absolutePath||(c=U(c)),void 0===o&&(c=c.replace(/^\/\//,"/%2F")),a.push(c)}return void 0!==e.query&&(a.push("?"),a.push(e.query)),void 0!==e.fragment&&(a.push("#"),a.push(e.fragment)),a.join("")}function M(e,r){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a={};return arguments[3]||(e=q(z(e,t),t),r=q(z(r,t),t)),!(t=t||{}).tolerant&&r.scheme?(a.scheme=r.scheme,a.userinfo=r.userinfo,a.host=r.host,a.port=r.port,a.path=U(r.path||""),a.query=r.query):(void 0!==r.userinfo||void 0!==r.host||void 0!==r.port?(a.userinfo=r.userinfo,a.host=r.host,a.port=r.port,a.path=U(r.path||""),a.query=r.query):(r.path?("/"===r.path.charAt(0)?a.path=U(r.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?a.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+r.path:a.path=r.path:a.path="/"+r.path,a.path=U(a.path)),a.query=r.query):(a.path=e.path,void 0!==r.query?a.query=r.query:a.query=e.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=r.fragment,a}function Q(e,r){return e&&e.toString().replace(r&&r.iri?i.PCT_ENCODED:n.PCT_ENCODED,j)}var V={scheme:"http",domainHost:!0,parse:function(e,r){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e},serialize:function(e,r){var t="https"===String(e.scheme).toLowerCase();return e.port!==(t?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}},Z={scheme:"https",domainHost:V.domainHost,parse:V.parse,serialize:V.serialize};function B(e){return"boolean"==typeof e.secure?e.secure:"wss"===String(e.scheme).toLowerCase()}var G={scheme:"ws",domainHost:!0,parse:function(e,r){var t=e;return t.secure=B(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t},serialize:function(e,r){if(e.port!==(B(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){var t=e.resourceName.split("?"),a=c(t,2),s=a[0],o=a[1];e.path=s&&"/"!==s?s:void 0,e.query=o,e.resourceName=void 0}return e.fragment=void 0,e}},J={scheme:"wss",domainHost:G.domainHost,parse:G.parse,serialize:G.serialize},K={},W="[A-Za-z0-9\\-\\.\\_\\~\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]",Y="[0-9A-Fa-f]",X=t(t("%[EFef]"+Y+"%"+Y+Y+"%"+Y+Y)+"|"+t("%[89A-Fa-f]"+Y+"%"+Y+Y)+"|"+t("%"+Y+Y)),ee=r("[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",'[\\"\\\\]'),re=new RegExp(W,"g"),te=new RegExp(X,"g"),ae=new RegExp(r("[^]","[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]","[\\.]",'[\\"]',ee),"g"),se=new RegExp(r("[^]",W,"[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"),"g"),oe=se;function ne(e){var r=j(e);return r.match(re)?r:e}var ie={scheme:"mailto",parse:function(e,r){var t=e,a=t.to=t.path?t.path.split(","):[];if(t.path=void 0,t.query){for(var s=!1,o={},n=t.query.split("&"),i=0,c=n.length;i<c;++i){var l=n[i].split("=");switch(l[0]){case"to":for(var u=l[1].split(","),d=0,p=u.length;d<p;++d)a.push(u[d]);break;case"subject":t.subject=Q(l[1],r);break;case"body":t.body=Q(l[1],r);break;default:s=!0,o[Q(l[0],r)]=Q(l[1],r)}}s&&(t.headers=o)}t.query=void 0;for(var h=0,m=a.length;h<m;++h){var f=a[h].split("@");if(f[0]=Q(f[0]),r.unicodeSupport)f[1]=Q(f[1],r).toLowerCase();else try{f[1]=$(Q(f[1],r).toLowerCase())}catch(e){t.error=t.error||"Email address's domain name can not be converted to ASCII via punycode: "+e}a[h]=f.join("@")}return t},serialize:function(e,r){var t,a=e,o=null!=(t=e.to)?t instanceof Array?t:"number"!=typeof t.length||t.split||t.setInterval||t.call?[t]:Array.prototype.slice.call(t):[];if(o){for(var n=0,i=o.length;n<i;++n){var c=String(o[n]),l=c.lastIndexOf("@"),u=c.slice(0,l).replace(te,ne).replace(te,s).replace(ae,R),d=c.slice(l+1);try{d=r.iri?x(d):$(Q(d,r).toLowerCase())}catch(e){a.error=a.error||"Email address's domain name can not be converted to "+(r.iri?"Unicode":"ASCII")+" via punycode: "+e}o[n]=u+"@"+d}a.path=o.join(",")}var p=e.headers=e.headers||{};e.subject&&(p.subject=e.subject),e.body&&(p.body=e.body);var h=[];for(var m in p)p[m]!==K[m]&&h.push(m.replace(te,ne).replace(te,s).replace(se,R)+"="+p[m].replace(te,ne).replace(te,s).replace(oe,R));return h.length&&(a.query=h.join("&")),a}},ce=/^([^\:]+)\:(.*)/,le={scheme:"urn",parse:function(e,r){var t=e.path&&e.path.match(ce),a=e;if(t){var s=r.scheme||a.scheme||"urn",o=t[1].toLowerCase(),n=t[2],i=s+":"+(r.nid||o),c=k[i];a.nid=o,a.nss=n,a.path=void 0,c&&(a=c.parse(a,r))}else a.error=a.error||"URN can not be parsed.";return a},serialize:function(e,r){var t=r.scheme||e.scheme||"urn",a=e.nid,s=t+":"+(r.nid||a),o=k[s];o&&(e=o.serialize(e,r));var n=e,i=e.nss;return n.path=(a||r.nid)+":"+i,n}},ue=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,de={scheme:"urn:uuid",parse:function(e,r){var t=e;return t.uuid=t.nss,t.nss=void 0,r.tolerant||t.uuid&&t.uuid.match(ue)||(t.error=t.error||"UUID is not valid."),t},serialize:function(e,r){var t=e;return t.nss=(e.uuid||"").toLowerCase(),t}};k[V.scheme]=V,k[Z.scheme]=Z,k[G.scheme]=G,k[J.scheme]=J,k[ie.scheme]=ie,k[le.scheme]=le,k[de.scheme]=de,e.SCHEMES=k,e.pctEncChar=R,e.pctDecChars=j,e.parse=q,e.removeDotSegments=U,e.serialize=z,e.resolveComponents=M,e.resolve=function(e,r,t){var a=function(e,r){var t=e;if(r)for(var a in r)t[a]=r[a];return t}({scheme:"null"},t);return z(M(q(e,a),q(r,a),a,!0),a)},e.normalize=function(e,r){return"string"==typeof e?e=z(q(e,r),r):"object"===a(e)&&(e=q(z(e,r),r)),e},e.equal=function(e,r,t){return"string"==typeof e?e=z(q(e,t),t):"object"===a(e)&&(e=z(e,t)),"string"==typeof r?r=z(q(r,t),t):"object"===a(r)&&(r=z(r,t)),e===r},e.escapeComponent=function(e,r){return e&&e.toString().replace(r&&r.iri?i.ESCAPE:n.ESCAPE,R)},e.unescapeComponent=Q,Object.defineProperty(e,"__esModule",{value:!0})}(cr.exports)),cr.exports}function ur(){return rr?er:(rr=1,er=function e(r,t){if(r===t)return!0;if(r&&t&&"object"==typeof r&&"object"==typeof t){if(r.constructor!==t.constructor)return!1;var a,s,o;if(Array.isArray(r)){if((a=r.length)!=t.length)return!1;for(s=a;0!==s--;)if(!e(r[s],t[s]))return!1;return!0}if(r.constructor===RegExp)return r.source===t.source&&r.flags===t.flags;if(r.valueOf!==Object.prototype.valueOf)return r.valueOf()===t.valueOf();if(r.toString!==Object.prototype.toString)return r.toString()===t.toString();if((a=(o=Object.keys(r)).length)!==Object.keys(t).length)return!1;for(s=a;0!==s--;)if(!Object.prototype.hasOwnProperty.call(t,o[s]))return!1;for(s=a;0!==s--;){var n=o[s];if(!e(r[n],t[n]))return!1}return!0}return r!=r&&t!=t})}function dr(){if(or)return sr;function e(e,r,t,a){var s=a?" !== ":" === ",o=a?" || ":" && ",n=a?"!":"",i=a?"":"!";switch(e){case"null":return r+s+"null";case"array":return n+"Array.isArray("+r+")";case"object":return"("+n+r+o+"typeof "+r+s+'"object"'+o+i+"Array.isArray("+r+"))";case"integer":return"(typeof "+r+s+'"number"'+o+i+"("+r+" % 1)"+o+r+s+r+(t?o+n+"isFinite("+r+")":"")+")";case"number":return"(typeof "+r+s+'"'+e+'"'+(t?o+n+"isFinite("+r+")":"")+")";default:return"typeof "+r+s+'"'+e+'"'}}or=1,sr={copy:function(e,r){for(var t in r=r||{},e)r[t]=e[t];return r},checkDataType:e,checkDataTypes:function(r,a,s){if(1===r.length)return e(r[0],a,s,!0);var o="",n=t(r);for(var i in n.array&&n.object&&(o=n.null?"(":"(!"+a+" || ",o+="typeof "+a+' !== "object")',delete n.null,delete n.array,delete n.object),n.number&&delete n.integer,n)o+=(o?" && ":"")+e(i,a,s,!0);return o},coerceToTypes:function(e,t){if(Array.isArray(t)){for(var a=[],s=0;s<t.length;s++){var o=t[s];(r[o]||"array"===e&&"array"===o)&&(a[a.length]=o)}if(a.length)return a}else{if(r[t])return[t];if("array"===e&&"array"===t)return["array"]}},toHash:t,getProperty:o,escapeQuotes:n,equal:ur(),ucs2length:ar?tr:(ar=1,tr=function(e){for(var r,t=0,a=e.length,s=0;s<a;)t++,(r=e.charCodeAt(s++))>=55296&&r<=56319&&s<a&&56320==(64512&(r=e.charCodeAt(s)))&&s++;return t}),varOccurences:function(e,r){r+="[^0-9]";var t=e.match(new RegExp(r,"g"));return t?t.length:0},varReplace:function(e,r,t){return r+="([^0-9])",t=t.replace(/\$/g,"$$$$"),e.replace(new RegExp(r,"g"),t+"$1")},schemaHasRules:function(e,r){if("boolean"==typeof e)return!e;for(var t in e)if(r[t])return!0},schemaHasRulesExcept:function(e,r,t){if("boolean"==typeof e)return!e&&"not"!=t;for(var a in e)if(a!=t&&r[a])return!0},schemaUnknownRules:function(e,r){if("boolean"!=typeof e)for(var t in e)if(!r[t])return t},toQuotedString:i,getPathExpr:function(e,r,t,a){return u(e,t?"'/' + "+r+(a?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):a?"'[' + "+r+" + ']'":"'[\\'' + "+r+" + '\\']'")},getPath:function(e,r,t){return u(e,i(t?"/"+d(r):o(r)))},getData:function(e,r,t){var a,s,n,i;if(""===e)return"rootData";if("/"==e[0]){if(!c.test(e))throw new Error("Invalid JSON-pointer: "+e);s=e,n="rootData"}else{if(!(i=e.match(l)))throw new Error("Invalid JSON-pointer: "+e);if(a=+i[1],"#"==(s=i[2])){if(a>=r)throw new Error("Cannot access property/index "+a+" levels up, current level is "+r);return t[r-a]}if(a>r)throw new Error("Cannot access data "+a+" levels up, current level is "+r);if(n="data"+(r-a||""),!s)return n}for(var u=n,d=s.split("/"),h=0;h<d.length;h++){var m=d[h];m&&(u+=" && "+(n+=o(p(m))))}return u},unescapeFragment:function(e){return p(decodeURIComponent(e))},unescapeJsonPointer:p,escapeFragment:function(e){return encodeURIComponent(d(e))},escapeJsonPointer:d};var r=t(["string","number","integer","boolean","null"]);function t(e){for(var r={},t=0;t<e.length;t++)r[e[t]]=!0;return r}var a=/^[a-z$_][a-z$_0-9]*$/i,s=/'|\\/g;function o(e){return"number"==typeof e?"["+e+"]":a.test(e)?"."+e:"['"+n(e)+"']"}function n(e){return e.replace(s,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function i(e){return"'"+n(e)+"'"}var c=/^\/(?:[^~]|~0|~1)*$/,l=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function u(e,r){return'""'==e?r:(e+" + "+r).replace(/([^\\])' \+ '/g,"$1")}function d(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function p(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}return sr}function pr(){if(ir)return nr;ir=1;var e=dr();return nr=function(r){e.copy(r,this)}}var hr,mr,fr,gr,vr,yr,br,wr,Pr,_r,Er,Sr={exports:{}};function $r(){if(hr)return Sr.exports;hr=1;var e=Sr.exports=function(e,t,a){"function"==typeof t&&(a=t,t={}),r(t,"function"==typeof(a=t.cb||a)?a:a.pre||function(){},a.post||function(){},e,"",e)};function r(a,s,o,n,i,c,l,u,d,p){if(n&&"object"==typeof n&&!Array.isArray(n)){for(var h in s(n,i,c,l,u,d,p),n){var m=n[h];if(Array.isArray(m)){if(h in e.arrayKeywords)for(var f=0;f<m.length;f++)r(a,s,o,m[f],i+"/"+h+"/"+f,c,i,h,n,f)}else if(h in e.propsKeywords){if(m&&"object"==typeof m)for(var g in m)r(a,s,o,m[g],i+"/"+h+"/"+t(g),c,i,h,n,g)}else(h in e.keywords||a.allKeys&&!(h in e.skipKeywords))&&r(a,s,o,m,i+"/"+h,c,i,h,n)}o(n,i,c,l,u,d,p)}}function t(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}return e.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0},e.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},e.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},e.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},Sr.exports}function xr(){if(fr)return mr;fr=1;var e=lr(),r=ur(),t=dr(),a=pr(),s=$r();function o(e,r,t){var s=this._refs[t];if("string"==typeof s){if(!this._refs[s])return o.call(this,e,r,s);s=this._refs[s]}if((s=s||this._schemas[t])instanceof a)return d(s.schema,this._opts.inlineRefs)?s.schema:s.validate||this._compile(s);var i,c,l,u=n.call(this,r,t);return u&&(i=u.schema,r=u.root,l=u.baseId),i instanceof a?c=i.validate||e.call(this,i.schema,r,void 0,l):void 0!==i&&(c=d(i,this._opts.inlineRefs)?i:e.call(this,i,r,void 0,l)),c}function n(r,t){var s=e.parse(t),o=f(s),n=m(this._getId(r.schema));if(0===Object.keys(r.schema).length||o!==n){var c=v(o),u=this._refs[c];if("string"==typeof u)return i.call(this,r,u,s);if(u instanceof a)u.validate||this._compile(u),r=u;else{if(!((u=this._schemas[c])instanceof a))return;if(u.validate||this._compile(u),c==v(t))return{schema:u,root:r,baseId:n};r=u}if(!r.schema)return;n=m(this._getId(r.schema))}return l.call(this,s,n,r.schema,r)}function i(e,r,t){var a=n.call(this,e,r);if(a){var s=a.schema,o=a.baseId;e=a.root;var i=this._getId(s);return i&&(o=y(o,i)),l.call(this,t,o,s,e)}}mr=o,o.normalizeId=v,o.fullPath=m,o.url=y,o.ids=function(a){var o=v(this._getId(a)),n={"":o},i={"":m(o,!1)},c={},l=this;return s(a,{allKeys:!0},function(a,s,o,u,d,p,h){if(""!==s){var m=l._getId(a),f=n[u],g=i[u]+"/"+d;if(void 0!==h&&(g+="/"+("number"==typeof h?h:t.escapeFragment(h))),"string"==typeof m){m=f=v(f?e.resolve(f,m):m);var y=l._refs[m];if("string"==typeof y&&(y=l._refs[y]),y&&y.schema){if(!r(a,y.schema))throw new Error('id "'+m+'" resolves to more than one schema')}else if(m!=v(g))if("#"==m[0]){if(c[m]&&!r(a,c[m]))throw new Error('id "'+m+'" resolves to more than one schema');c[m]=a}else l._refs[m]=g}n[s]=f,i[s]=g}}),c},o.inlineRef=d,o.schema=n;var c=t.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function l(e,r,a,s){if(e.fragment=e.fragment||"","/"==e.fragment.slice(0,1)){for(var o=e.fragment.split("/"),i=1;i<o.length;i++){var l=o[i];if(l){if(void 0===(a=a[l=t.unescapeFragment(l)]))break;var u;if(!c[l]&&((u=this._getId(a))&&(r=y(r,u)),a.$ref)){var d=y(r,a.$ref),p=n.call(this,s,d);p&&(a=p.schema,s=p.root,r=p.baseId)}}}return void 0!==a&&a!==s.schema?{schema:a,root:s,baseId:r}:void 0}}var u=t.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function d(e,r){return!1!==r&&(void 0===r||!0===r?p(e):r?h(e)<=r:void 0)}function p(e){var r;if(Array.isArray(e)){for(var t=0;t<e.length;t++)if("object"==typeof(r=e[t])&&!p(r))return!1}else for(var a in e){if("$ref"==a)return!1;if("object"==typeof(r=e[a])&&!p(r))return!1}return!0}function h(e){var r,t=0;if(Array.isArray(e)){for(var a=0;a<e.length;a++)if("object"==typeof(r=e[a])&&(t+=h(r)),t==1/0)return 1/0}else for(var s in e){if("$ref"==s)return 1/0;if(u[s])t++;else if("object"==typeof(r=e[s])&&(t+=h(r)+1),t==1/0)return 1/0}return t}function m(r,t){return!1!==t&&(r=v(r)),f(e.parse(r))}function f(r){return e.serialize(r).split("#")[0]+"#"}var g=/#\/?$/;function v(e){return e?e.replace(g,""):""}function y(r,t){return t=v(t),e.resolve(r,t)}return mr}function kr(){if(vr)return gr;vr=1;var e=xr();function r(t,a,s){this.message=s||r.message(t,a),this.missingRef=e.url(t,a),this.missingSchema=e.normalizeId(e.fullPath(this.missingRef))}function t(e){return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}return gr={Validation:t(function(e){this.message="validation failed",this.errors=e,this.ajv=this.validation=!0}),MissingRef:t(r)},r.message=function(e,r){return"can't resolve reference "+r+" from id "+e},gr}function Rr(){return br||(br=1,yr=function(e,r){r||(r={}),"function"==typeof r&&(r={cmp:r});var t,a="boolean"==typeof r.cycles&&r.cycles,s=r.cmp&&(t=r.cmp,function(e){return function(r,a){var s={key:r,value:e[r]},o={key:a,value:e[a]};return t(s,o)}}),o=[];return function e(r){if(r&&r.toJSON&&"function"==typeof r.toJSON&&(r=r.toJSON()),void 0!==r){if("number"==typeof r)return isFinite(r)?""+r:"null";if("object"!=typeof r)return JSON.stringify(r);var t,n;if(Array.isArray(r)){for(n="[",t=0;t<r.length;t++)t&&(n+=","),n+=e(r[t])||"null";return n+"]"}if(null===r)return"null";if(-1!==o.indexOf(r)){if(a)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var i=o.push(r)-1,c=Object.keys(r).sort(s&&s(r));for(n="",t=0;t<c.length;t++){var l=c[t],u=e(r[l]);u&&(n&&(n+=","),n+=JSON.stringify(l)+":"+u)}return o.splice(i,1),"{"+n+"}"}}(e)}),yr}function jr(){return Pr||(Pr=1,wr=function(e,r,t){var a="",s=!0===e.schema.$async,o=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),n=e.self._getId(e.schema);if(e.opts.strictKeywords){var i=e.util.schemaUnknownRules(e.schema,e.RULES.keywords);if(i){var c="unknown keyword: "+i;if("log"!==e.opts.strictKeywords)throw new Error(c);e.logger.warn(c)}}if(e.isTop&&(a+=" var validate = ",s&&(e.async=!0,a+="async "),a+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",n&&(e.opts.sourceCode||e.opts.processCode)&&(a+=" /*# sourceURL="+n+" */ ")),"boolean"==typeof e.schema||!o&&!e.schema.$ref){r="false schema";var l=e.level,u=e.dataLevel,d=e.schema[r],p=e.schemaPath+e.util.getProperty(r),h=e.errSchemaPath+"/"+r,m=!e.opts.allErrors,f="data"+(u||""),g="valid"+l;if(!1===e.schema){e.isTop?m=!0:a+=" var "+g+" = false; ",(V=V||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'false schema' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'boolean schema is false' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),a+=" } "):a+=" {} ";var v=a;a=V.pop(),!e.compositeRule&&m?e.async?a+=" throw new ValidationError(["+v+"]); ":a+=" validate.errors = ["+v+"]; return false; ":a+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else e.isTop?a+=s?" return data; ":" validate.errors = null; return true; ":a+=" var "+g+" = true; ";return e.isTop&&(a+=" }; return validate; "),a}if(e.isTop){var y=e.isTop;if(l=e.level=0,u=e.dataLevel=0,f="data",e.rootId=e.resolve.fullPath(e.self._getId(e.root.schema)),e.baseId=e.baseId||e.rootId,delete e.isTop,e.dataPathArr=[""],void 0!==e.schema.default&&e.opts.useDefaults&&e.opts.strictDefaults){var b="default is ignored in the schema root";if("log"!==e.opts.strictDefaults)throw new Error(b);e.logger.warn(b)}a+=" var vErrors = null; ",a+=" var errors = 0; ",a+=" if (rootData === undefined) rootData = data; "}else{if(l=e.level,f="data"+((u=e.dataLevel)||""),n&&(e.baseId=e.resolve.url(e.baseId,n)),s&&!e.async)throw new Error("async schema in sync schema");a+=" var errs_"+l+" = errors;"}g="valid"+l,m=!e.opts.allErrors;var w="",P="",_=e.schema.type,E=Array.isArray(_);if(_&&e.opts.nullable&&!0===e.schema.nullable&&(E?-1==_.indexOf("null")&&(_=_.concat("null")):"null"!=_&&(_=[_,"null"],E=!0)),E&&1==_.length&&(_=_[0],E=!1),e.schema.$ref&&o){if("fail"==e.opts.extendRefs)throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)');!0!==e.opts.extendRefs&&(o=!1,e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"'))}if(e.schema.$comment&&e.opts.$comment&&(a+=" "+e.RULES.all.$comment.code(e,"$comment")),_){if(e.opts.coerceTypes)var S=e.util.coerceToTypes(e.opts.coerceTypes,_);var $=e.RULES.types[_];if(S||E||!0===$||$&&!W($)){p=e.schemaPath+".type",h=e.errSchemaPath+"/type",p=e.schemaPath+".type",h=e.errSchemaPath+"/type";var x=E?"checkDataTypes":"checkDataType";if(a+=" if ("+e.util[x](_,f,e.opts.strictNumbers,!0)+") { ",S){var k="dataType"+l,R="coerced"+l;a+=" var "+k+" = typeof "+f+"; var "+R+" = undefined; ","array"==e.opts.coerceTypes&&(a+=" if ("+k+" == 'object' && Array.isArray("+f+") && "+f+".length == 1) { "+f+" = "+f+"[0]; "+k+" = typeof "+f+"; if ("+e.util.checkDataType(e.schema.type,f,e.opts.strictNumbers)+") "+R+" = "+f+"; } "),a+=" if ("+R+" !== undefined) ; ";var j=S;if(j)for(var T,A=-1,O=j.length-1;A<O;)"string"==(T=j[A+=1])?a+=" else if ("+k+" == 'number' || "+k+" == 'boolean') "+R+" = '' + "+f+"; else if ("+f+" === null) "+R+" = ''; ":"number"==T||"integer"==T?(a+=" else if ("+k+" == 'boolean' || "+f+" === null || ("+k+" == 'string' && "+f+" && "+f+" == +"+f+" ","integer"==T&&(a+=" && !("+f+" % 1)"),a+=")) "+R+" = +"+f+"; "):"boolean"==T?a+=" else if ("+f+" === 'false' || "+f+" === 0 || "+f+" === null) "+R+" = false; else if ("+f+" === 'true' || "+f+" === 1) "+R+" = true; ":"null"==T?a+=" else if ("+f+" === '' || "+f+" === 0 || "+f+" === false) "+R+" = null; ":"array"==e.opts.coerceTypes&&"array"==T&&(a+=" else if ("+k+" == 'string' || "+k+" == 'number' || "+k+" == 'boolean' || "+f+" == null) "+R+" = ["+f+"]; ");a+=" else { ",(V=V||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { type: '",a+=E?""+_.join(","):""+_,a+="' } ",!1!==e.opts.messages&&(a+=" , message: 'should be ",a+=E?""+_.join(","):""+_,a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+p+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),a+=" } "):a+=" {} ",v=a,a=V.pop(),!e.compositeRule&&m?e.async?a+=" throw new ValidationError(["+v+"]); ":a+=" validate.errors = ["+v+"]; return false; ":a+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } if ("+R+" !== undefined) { ";var F=u?"data"+(u-1||""):"parentData";a+=" "+f+" = "+R+"; ",u||(a+="if ("+F+" !== undefined)"),a+=" "+F+"["+(u?e.dataPathArr[u]:"parentDataProperty")+"] = "+R+"; } "}else(V=V||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { type: '",a+=E?""+_.join(","):""+_,a+="' } ",!1!==e.opts.messages&&(a+=" , message: 'should be ",a+=E?""+_.join(","):""+_,a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+p+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),a+=" } "):a+=" {} ",v=a,a=V.pop(),!e.compositeRule&&m?e.async?a+=" throw new ValidationError(["+v+"]); ":a+=" validate.errors = ["+v+"]; return false; ":a+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";a+=" } "}}if(e.schema.$ref&&!o)a+=" "+e.RULES.all.$ref.code(e,"$ref")+" ",m&&(a+=" } if (errors === ",a+=y?"0":"errs_"+l,a+=") { ",P+="}");else{var C=e.RULES;if(C)for(var I=-1,q=C.length-1;I<q;)if(W($=C[I+=1])){if($.type&&(a+=" if ("+e.util.checkDataType($.type,f,e.opts.strictNumbers)+") { "),e.opts.useDefaults)if("object"==$.type&&e.schema.properties){d=e.schema.properties;var N=Object.keys(d);if(N)for(var D,H=-1,L=N.length-1;H<L;)if(void 0!==(M=d[D=N[H+=1]]).default){var U=f+e.util.getProperty(D);if(e.compositeRule){if(e.opts.strictDefaults){if(b="default is ignored for: "+U,"log"!==e.opts.strictDefaults)throw new Error(b);e.logger.warn(b)}}else a+=" if ("+U+" === undefined ","empty"==e.opts.useDefaults&&(a+=" || "+U+" === null || "+U+" === '' "),a+=" ) "+U+" = ","shared"==e.opts.useDefaults?a+=" "+e.useDefault(M.default)+" ":a+=" "+JSON.stringify(M.default)+" ",a+="; "}}else if("array"==$.type&&Array.isArray(e.schema.items)){var z=e.schema.items;if(z){A=-1;for(var M,Q=z.length-1;A<Q;)if(void 0!==(M=z[A+=1]).default)if(U=f+"["+A+"]",e.compositeRule){if(e.opts.strictDefaults){if(b="default is ignored for: "+U,"log"!==e.opts.strictDefaults)throw new Error(b);e.logger.warn(b)}}else a+=" if ("+U+" === undefined ","empty"==e.opts.useDefaults&&(a+=" || "+U+" === null || "+U+" === '' "),a+=" ) "+U+" = ","shared"==e.opts.useDefaults?a+=" "+e.useDefault(M.default)+" ":a+=" "+JSON.stringify(M.default)+" ",a+="; "}}var V,Z=$.rules;if(Z)for(var B,G=-1,J=Z.length-1;G<J;)if(Y(B=Z[G+=1])){var K=B.code(e,B.keyword,$.type);K&&(a+=" "+K+" ",m&&(w+="}"))}if(m&&(a+=" "+w+" ",w=""),$.type&&(a+=" } ",_&&_===$.type&&!S))a+=" else { ",p=e.schemaPath+".type",h=e.errSchemaPath+"/type",(V=V||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { type: '",a+=E?""+_.join(","):""+_,a+="' } ",!1!==e.opts.messages&&(a+=" , message: 'should be ",a+=E?""+_.join(","):""+_,a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+p+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),a+=" } "):a+=" {} ",v=a,a=V.pop(),!e.compositeRule&&m?e.async?a+=" throw new ValidationError(["+v+"]); ":a+=" validate.errors = ["+v+"]; return false; ":a+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ";m&&(a+=" if (errors === ",a+=y?"0":"errs_"+l,a+=") { ",P+="}")}}function W(e){for(var r=e.rules,t=0;t<r.length;t++)if(Y(r[t]))return!0}function Y(r){return void 0!==e.schema[r.keyword]||r.implements&&function(r){for(var t=r.implements,a=0;a<t.length;a++)if(void 0!==e.schema[t[a]])return!0}(r)}return m&&(a+=" "+P+" "),y?(s?(a+=" if (errors === 0) return data; ",a+=" else throw new ValidationError(vErrors); "):(a+=" validate.errors = vErrors; ",a+=" return errors === 0; "),a+=" }; return validate;"):a+=" var "+g+" = errors === errs_"+l+";",a}),wr}function Tr(){if(Er)return _r;Er=1;var e=xr(),r=dr(),t=kr(),a=Rr(),s=jr(),o=r.ucs2length,n=ur(),i=t.Validation;function c(e,r,t){var a=u.call(this,e,r,t);return a>=0?{index:a,compiling:!0}:(a=this._compilations.length,this._compilations[a]={schema:e,root:r,baseId:t},{index:a,compiling:!1})}function l(e,r,t){var a=u.call(this,e,r,t);a>=0&&this._compilations.splice(a,1)}function u(e,r,t){for(var a=0;a<this._compilations.length;a++){var s=this._compilations[a];if(s.schema==e&&s.root==r&&s.baseId==t)return a}return-1}function d(e,t){return"var pattern"+e+" = new RegExp("+r.toQuotedString(t[e])+");"}function p(e){return"var default"+e+" = defaults["+e+"];"}function h(e,r){return void 0===r[e]?"":"var refVal"+e+" = refVal["+e+"];"}function m(e){return"var customRule"+e+" = customRules["+e+"];"}function f(e,r){if(!e.length)return"";for(var t="",a=0;a<e.length;a++)t+=r(a,e);return t}return _r=function u(g,v,y,b){var w=this,P=this._opts,_=[void 0],E={},S=[],$={},x=[],k={},R=[];v=v||{schema:g,refVal:_,refs:E};var j=c.call(this,g,v,b),T=this._compilations[j.index];if(j.compiling)return T.callValidate=function e(){var r=T.validate,t=r.apply(this,arguments);return e.errors=r.errors,t};var A=this._formats,O=this.RULES;try{var F=I(g,v,y,b);T.validate=F;var C=T.callValidate;return C&&(C.schema=F.schema,C.errors=null,C.refs=F.refs,C.refVal=F.refVal,C.root=F.root,C.$async=F.$async,P.sourceCode&&(C.source=F.source)),F}finally{l.call(this,g,v,b)}function I(a,c,l,g){var y=!c||c&&c.schema==a;if(c.schema!=v.schema)return u.call(w,a,c,l,g);var b,$=!0===a.$async,k=s({isTop:!0,schema:a,isRoot:y,baseId:g,root:c,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:t.MissingRef,RULES:O,validate:s,util:r,resolve:e,resolveRef:q,usePattern:H,useDefault:L,useCustomRule:U,opts:P,formats:A,logger:w.logger,self:w});k=f(_,h)+f(S,d)+f(x,p)+f(R,m)+k,P.processCode&&(k=P.processCode(k,a));try{b=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",k)(w,O,A,v,_,x,R,n,o,i),_[0]=b}catch(e){throw w.logger.error("Error compiling schema, function code:",k),e}return b.schema=a,b.errors=null,b.refs=E,b.refVal=_,b.root=y?b:c,$&&(b.$async=!0),!0===P.sourceCode&&(b.source={code:k,patterns:S,defaults:x}),b}function q(r,t,a){t=e.url(r,t);var s,o,n=E[t];if(void 0!==n)return D(s=_[n],o="refVal["+n+"]");if(!a&&v.refs){var i=v.refs[t];if(void 0!==i)return D(s=v.refVal[i],o=N(t,s))}o=N(t);var c=e.call(w,I,v,t);if(void 0===c){var l=y&&y[t];l&&(c=e.inlineRef(l,P.inlineRefs)?l:u.call(w,l,v,y,r))}if(void 0!==c)return function(e,r){var t=E[e];_[t]=r}(t,c),D(c,o);!function(e){delete E[e]}(t)}function N(e,r){var t=_.length;return _[t]=r,E[e]=t,"refVal"+t}function D(e,r){return"object"==typeof e||"boolean"==typeof e?{code:r,schema:e,inline:!0}:{code:r,$async:e&&!!e.$async}}function H(e){var r=$[e];return void 0===r&&(r=$[e]=S.length,S[r]=e),"pattern"+r}function L(e){switch(typeof e){case"boolean":case"number":return""+e;case"string":return r.toQuotedString(e);case"object":if(null===e)return"null";var t=a(e),s=k[t];return void 0===s&&(s=k[t]=x.length,x[s]=e),"default"+s}}function U(e,r,t,a){if(!1!==w._opts.validateSchema){var s=e.definition.dependencies;if(s&&!s.every(function(e){return Object.prototype.hasOwnProperty.call(t,e)}))throw new Error("parent schema must have all required keywords: "+s.join(","));var o=e.definition.validateSchema;if(o&&!o(r)){var n="keyword schema is invalid: "+w.errorsText(o.errors);if("log"!=w._opts.validateSchema)throw new Error(n);w.logger.error(n)}}var i,c=e.definition.compile,l=e.definition.inline,u=e.definition.macro;if(c)i=c.call(w,r,t,a);else if(u)i=u.call(w,r,t,a),!1!==P.validateSchema&&w.validateSchema(i,!0);else if(l)i=l.call(w,a,e.keyword,r,t);else if(!(i=e.definition.validate))return;if(void 0===i)throw new Error('custom keyword "'+e.keyword+'"failed to compile');var d=R.length;return R[d]=i,{code:"customRule"+d,validate:i}}},_r}var Ar,Or,Fr,Cr,Ir,qr,Nr,Dr,Hr,Lr,Ur,zr,Mr,Qr,Vr,Zr,Br,Gr,Jr,Kr,Wr,Yr,Xr,et,rt,tt,at,st,ot,nt,it,ct,lt,ut,dt,pt,ht,mt,ft,gt,vt,yt,bt,wt,Pt,_t,Et,St,$t,xt,kt,Rt,jt,Tt,At,Ot,Ft,Ct,It,qt={exports:{}};function Nt(){return at||(at=1,tt=function(e,r,t){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[r],c=e.schemaPath+e.util.getProperty(r),l=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,d="data"+(n||""),p=e.opts.$data&&i&&i.$data;p?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i;var h="maximum"==r,m=h?"exclusiveMaximum":"exclusiveMinimum",f=e.schema[m],g=e.opts.$data&&f&&f.$data,v=h?"<":">",y=h?">":"<",b=void 0;if(!p&&"number"!=typeof i&&void 0!==i)throw new Error(r+" must be number");if(!g&&void 0!==f&&"number"!=typeof f&&"boolean"!=typeof f)throw new Error(m+" must be number or boolean");if(g){var w,P=e.util.getData(f.$data,n,e.dataPathArr),_="exclusive"+o,E="exclType"+o,S="exclIsNumber"+o,$="' + "+(k="op"+o)+" + '";s+=" var schemaExcl"+o+" = "+P+"; ",s+=" var "+_+"; var "+E+" = typeof "+(P="schemaExcl"+o)+"; if ("+E+" != 'boolean' && "+E+" != 'undefined' && "+E+" != 'number') { ",b=m,(w=w||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(b||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: {} ",!1!==e.opts.messages&&(s+=" , message: '"+m+" should be boolean' "),e.opts.verbose&&(s+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),s+=" } "):s+=" {} ";var x=s;s=w.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+x+"]); ":s+=" validate.errors = ["+x+"]; return false; ":s+=" var err = "+x+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } else if ( ",p&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+E+" == 'number' ? ( ("+_+" = "+a+" === undefined || "+P+" "+v+"= "+a+") ? "+d+" "+y+"= "+P+" : "+d+" "+y+" "+a+" ) : ( ("+_+" = "+P+" === true) ? "+d+" "+y+"= "+a+" : "+d+" "+y+" "+a+" ) || "+d+" !== "+d+") { var op"+o+" = "+_+" ? '"+v+"' : '"+v+"='; ",void 0===i&&(b=m,l=e.errSchemaPath+"/"+m,a=P,p=g)}else if($=v,(S="number"==typeof f)&&p){var k="'"+$+"'";s+=" if ( ",p&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" ( "+a+" === undefined || "+f+" "+v+"= "+a+" ? "+d+" "+y+"= "+f+" : "+d+" "+y+" "+a+" ) || "+d+" !== "+d+") { "}else S&&void 0===i?(_=!0,b=m,l=e.errSchemaPath+"/"+m,a=f,y+="="):(S&&(a=Math[h?"min":"max"](f,i)),f===(!S||a)?(_=!0,b=m,l=e.errSchemaPath+"/"+m,y+="="):(_=!1,$+="=")),k="'"+$+"'",s+=" if ( ",p&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+d+" "+y+" "+a+" || "+d+" !== "+d+") { ";return b=b||r,(w=w||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(b||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { comparison: "+k+", limit: "+a+", exclusive: "+_+" } ",!1!==e.opts.messages&&(s+=" , message: 'should be "+$+" ",s+=p?"' + "+a:a+"'"),e.opts.verbose&&(s+=" , schema: ",s+=p?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),s+=" } "):s+=" {} ",x=s,s=w.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+x+"]); ":s+=" validate.errors = ["+x+"]; return false; ":s+=" var err = "+x+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } ",u&&(s+=" else { "),s}),tt}function Dt(){return ot||(ot=1,st=function(e,r,t){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[r],c=e.schemaPath+e.util.getProperty(r),l=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,d="data"+(n||""),p=e.opts.$data&&i&&i.$data;if(p?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,!p&&"number"!=typeof i)throw new Error(r+" must be number");s+="if ( ",p&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+d+".length "+("maxItems"==r?">":"<")+" "+a+") { ";var h=r,m=m||[];m.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(h||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have ",s+="maxItems"==r?"more":"fewer",s+=" than ",s+=p?"' + "+a+" + '":""+i,s+=" items' "),e.opts.verbose&&(s+=" , schema: ",s+=p?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),s+=" } "):s+=" {} ";var f=s;return s=m.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+f+"]); ":s+=" validate.errors = ["+f+"]; return false; ":s+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",u&&(s+=" else { "),s}),st}function Ht(){return it||(it=1,nt=function(e,r,t){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[r],c=e.schemaPath+e.util.getProperty(r),l=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,d="data"+(n||""),p=e.opts.$data&&i&&i.$data;if(p?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,!p&&"number"!=typeof i)throw new Error(r+" must be number");var h="maxLength"==r?">":"<";s+="if ( ",p&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),!1===e.opts.unicode?s+=" "+d+".length ":s+=" ucs2length("+d+") ",s+=" "+h+" "+a+") { ";var m=r,f=f||[];f.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(m||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT be ",s+="maxLength"==r?"longer":"shorter",s+=" than ",s+=p?"' + "+a+" + '":""+i,s+=" characters' "),e.opts.verbose&&(s+=" , schema: ",s+=p?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),s+=" } "):s+=" {} ";var g=s;return s=f.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+g+"]); ":s+=" validate.errors = ["+g+"]; return false; ":s+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",u&&(s+=" else { "),s}),nt}function Lt(){return lt||(lt=1,ct=function(e,r,t){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[r],c=e.schemaPath+e.util.getProperty(r),l=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,d="data"+(n||""),p=e.opts.$data&&i&&i.$data;if(p?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,!p&&"number"!=typeof i)throw new Error(r+" must be number");s+="if ( ",p&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" Object.keys("+d+").length "+("maxProperties"==r?">":"<")+" "+a+") { ";var h=r,m=m||[];m.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(h||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have ",s+="maxProperties"==r?"more":"fewer",s+=" than ",s+=p?"' + "+a+" + '":""+i,s+=" properties' "),e.opts.verbose&&(s+=" , schema: ",s+=p?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),s+=" } "):s+=" {} ";var f=s;return s=m.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+f+"]); ":s+=" validate.errors = ["+f+"]; return false; ":s+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",u&&(s+=" else { "),s}),ct}function Ut(){if(jt)return Rt;jt=1;var e=(kt||(kt=1,xt={$ref:(Ir||(Ir=1,Cr=function(e,r,t){var a,s,o=" ",n=e.level,i=e.dataLevel,c=e.schema[r],l=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,d="data"+(i||""),p="valid"+n;if("#"==c||"#/"==c)e.isRoot?(a=e.async,s="validate"):(a=!0===e.root.schema.$async,s="root.refVal[0]");else{var h=e.resolveRef(e.baseId,c,e.isRoot);if(void 0===h){var m=e.MissingRefError.message(e.baseId,c);if("fail"==e.opts.missingRefs){e.logger.error(m),(y=y||[]).push(o),o="",!1!==e.createErrors?(o+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { ref: '"+e.util.escapeQuotes(c)+"' } ",!1!==e.opts.messages&&(o+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(c)+"' "),e.opts.verbose&&(o+=" , schema: "+e.util.toQuotedString(c)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),o+=" } "):o+=" {} ";var f=o;o=y.pop(),!e.compositeRule&&u?e.async?o+=" throw new ValidationError(["+f+"]); ":o+=" validate.errors = ["+f+"]; return false; ":o+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u&&(o+=" if (false) { ")}else{if("ignore"!=e.opts.missingRefs)throw new e.MissingRefError(e.baseId,c,m);e.logger.warn(m),u&&(o+=" if (true) { ")}}else if(h.inline){var g=e.util.copy(e);g.level++;var v="valid"+g.level;g.schema=h.schema,g.schemaPath="",g.errSchemaPath=c,o+=" "+e.validate(g).replace(/validate\.schema/g,h.code)+" ",u&&(o+=" if ("+v+") { ")}else a=!0===h.$async||e.async&&!1!==h.$async,s=h.code}if(s){var y;(y=y||[]).push(o),o="",e.opts.passContext?o+=" "+s+".call(this, ":o+=" "+s+"( ",o+=" "+d+", (dataPath || '')",'""'!=e.errorPath&&(o+=" + "+e.errorPath);var b=o+=" , "+(i?"data"+(i-1||""):"parentData")+" , "+(i?e.dataPathArr[i]:"parentDataProperty")+", rootData) ";if(o=y.pop(),a){if(!e.async)throw new Error("async schema referenced by sync schema");u&&(o+=" var "+p+"; "),o+=" try { await "+b+"; ",u&&(o+=" "+p+" = true; "),o+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",u&&(o+=" "+p+" = false; "),o+=" } ",u&&(o+=" if ("+p+") { ")}else o+=" if (!"+b+") { if (vErrors === null) vErrors = "+s+".errors; else vErrors = vErrors.concat("+s+".errors); errors = vErrors.length; } ",u&&(o+=" else { ")}return o}),Cr),allOf:(Nr||(Nr=1,qr=function(e,r,t){var a=" ",s=e.schema[r],o=e.schemaPath+e.util.getProperty(r),n=e.errSchemaPath+"/"+r,i=!e.opts.allErrors,c=e.util.copy(e),l="";c.level++;var u="valid"+c.level,d=c.baseId,p=!0,h=s;if(h)for(var m,f=-1,g=h.length-1;f<g;)m=h[f+=1],(e.opts.strictKeywords?"object"==typeof m&&Object.keys(m).length>0||!1===m:e.util.schemaHasRules(m,e.RULES.all))&&(p=!1,c.schema=m,c.schemaPath=o+"["+f+"]",c.errSchemaPath=n+"/"+f,a+=" "+e.validate(c)+" ",c.baseId=d,i&&(a+=" if ("+u+") { ",l+="}"));return i&&(a+=p?" if (true) { ":" "+l.slice(0,-1)+" "),a}),qr),anyOf:(Hr||(Hr=1,Dr=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[r],i=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,u="data"+(o||""),d="valid"+s,p="errs__"+s,h=e.util.copy(e),m="";h.level++;var f="valid"+h.level,g=n.every(function(r){return e.opts.strictKeywords?"object"==typeof r&&Object.keys(r).length>0||!1===r:e.util.schemaHasRules(r,e.RULES.all)});if(g){var v=h.baseId;a+=" var "+p+" = errors; var "+d+" = false; ";var y=e.compositeRule;e.compositeRule=h.compositeRule=!0;var b=n;if(b)for(var w,P=-1,_=b.length-1;P<_;)w=b[P+=1],h.schema=w,h.schemaPath=i+"["+P+"]",h.errSchemaPath=c+"/"+P,a+=" "+e.validate(h)+" ",h.baseId=v,a+=" "+d+" = "+d+" || "+f+"; if (!"+d+") { ",m+="}";e.compositeRule=h.compositeRule=y,a+=" "+m+" if (!"+d+") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'anyOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should match some schema in anyOf' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&l&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),a+=" } else { errors = "+p+"; if (vErrors !== null) { if ("+p+") vErrors.length = "+p+"; else vErrors = null; } ",e.opts.allErrors&&(a+=" } ")}else l&&(a+=" if (true) { ");return a}),Dr),$comment:(Ur||(Ur=1,Lr=function(e,r,t){var a=" ",s=e.schema[r],o=e.errSchemaPath+"/"+r;e.opts.allErrors;var n=e.util.toQuotedString(s);return!0===e.opts.$comment?a+=" console.log("+n+");":"function"==typeof e.opts.$comment&&(a+=" self._opts.$comment("+n+", "+e.util.toQuotedString(o)+", validate.root.schema);"),a}),Lr),const:(Mr||(Mr=1,zr=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[r],i=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,u="data"+(o||""),d="valid"+s,p=e.opts.$data&&n&&n.$data;p&&(a+=" var schema"+s+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; "),p||(a+=" var schema"+s+" = validate.schema"+i+";"),a+="var "+d+" = equal("+u+", schema"+s+"); if (!"+d+") { ";var h=h||[];h.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'const' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValue: schema"+s+" } ",!1!==e.opts.messages&&(a+=" , message: 'should be equal to constant' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var m=a;return a=h.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+m+"]); ":a+=" validate.errors = ["+m+"]; return false; ":a+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" }",l&&(a+=" else { "),a}),zr),contains:(Vr||(Vr=1,Qr=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[r],i=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,u="data"+(o||""),d="valid"+s,p="errs__"+s,h=e.util.copy(e);h.level++;var m="valid"+h.level,f="i"+s,g=h.dataLevel=e.dataLevel+1,v="data"+g,y=e.baseId,b=e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all);if(a+="var "+p+" = errors;var "+d+";",b){var w=e.compositeRule;e.compositeRule=h.compositeRule=!0,h.schema=n,h.schemaPath=i,h.errSchemaPath=c,a+=" var "+m+" = false; for (var "+f+" = 0; "+f+" < "+u+".length; "+f+"++) { ",h.errorPath=e.util.getPathExpr(e.errorPath,f,e.opts.jsonPointers,!0);var P=u+"["+f+"]";h.dataPathArr[g]=f;var _=e.validate(h);h.baseId=y,e.util.varOccurences(_,v)<2?a+=" "+e.util.varReplace(_,v,P)+" ":a+=" var "+v+" = "+P+"; "+_+" ",a+=" if ("+m+") break; } ",e.compositeRule=h.compositeRule=w,a+=" if (!"+m+") {"}else a+=" if ("+u+".length == 0) {";var E=E||[];E.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should contain a valid item' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var S=a;return a=E.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+S+"]); ":a+=" validate.errors = ["+S+"]; return false; ":a+=" var err = "+S+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { ",b&&(a+=" errors = "+p+"; if (vErrors !== null) { if ("+p+") vErrors.length = "+p+"; else vErrors = null; } "),e.opts.allErrors&&(a+=" } "),a}),Qr),dependencies:(Br||(Br=1,Zr=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[r],i=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,u="data"+(o||""),d="errs__"+s,p=e.util.copy(e),h="";p.level++;var m="valid"+p.level,f={},g={},v=e.opts.ownProperties;for(P in n)if("__proto__"!=P){var y=n[P],b=Array.isArray(y)?g:f;b[P]=y}a+="var "+d+" = errors;";var w=e.errorPath;for(var P in a+="var missing"+s+";",g)if((b=g[P]).length){if(a+=" if ( "+u+e.util.getProperty(P)+" !== undefined ",v&&(a+=" && Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(P)+"') "),l){a+=" && ( ";var _=b;if(_)for(var E=-1,S=_.length-1;E<S;)T=_[E+=1],E&&(a+=" || "),a+=" ( ( "+(C=u+(F=e.util.getProperty(T)))+" === undefined ",v&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(T)+"') "),a+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?T:F)+") ) ";a+=")) { ";var $="missing"+s,x="' + "+$+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(w,$,!0):w+" + "+$);var k=k||[];k.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(P)+"', missingProperty: '"+x+"', depsCount: "+b.length+", deps: '"+e.util.escapeQuotes(1==b.length?b[0]:b.join(", "))+"' } ",!1!==e.opts.messages&&(a+=" , message: 'should have ",1==b.length?a+="property "+e.util.escapeQuotes(b[0]):a+="properties "+e.util.escapeQuotes(b.join(", ")),a+=" when property "+e.util.escapeQuotes(P)+" is present' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var R=a;a=k.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+R+"]); ":a+=" validate.errors = ["+R+"]; return false; ":a+=" var err = "+R+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else{a+=" ) { ";var j=b;if(j)for(var T,A=-1,O=j.length-1;A<O;){T=j[A+=1];var F=e.util.getProperty(T),C=(x=e.util.escapeQuotes(T),u+F);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(w,T,e.opts.jsonPointers)),a+=" if ( "+C+" === undefined ",v&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(T)+"') "),a+=") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(P)+"', missingProperty: '"+x+"', depsCount: "+b.length+", deps: '"+e.util.escapeQuotes(1==b.length?b[0]:b.join(", "))+"' } ",!1!==e.opts.messages&&(a+=" , message: 'should have ",1==b.length?a+="property "+e.util.escapeQuotes(b[0]):a+="properties "+e.util.escapeQuotes(b.join(", ")),a+=" when property "+e.util.escapeQuotes(P)+" is present' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}a+=" } ",l&&(h+="}",a+=" else { ")}e.errorPath=w;var I=p.baseId;for(var P in f)y=f[P],(e.opts.strictKeywords?"object"==typeof y&&Object.keys(y).length>0||!1===y:e.util.schemaHasRules(y,e.RULES.all))&&(a+=" "+m+" = true; if ( "+u+e.util.getProperty(P)+" !== undefined ",v&&(a+=" && Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(P)+"') "),a+=") { ",p.schema=y,p.schemaPath=i+e.util.getProperty(P),p.errSchemaPath=c+"/"+e.util.escapeFragment(P),a+=" "+e.validate(p)+" ",p.baseId=I,a+=" } ",l&&(a+=" if ("+m+") { ",h+="}"));return l&&(a+=" "+h+" if ("+d+" == errors) {"),a}),Zr),enum:(Jr||(Jr=1,Gr=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[r],i=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,u="data"+(o||""),d="valid"+s,p=e.opts.$data&&n&&n.$data;p&&(a+=" var schema"+s+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ");var h="i"+s,m="schema"+s;p||(a+=" var "+m+" = validate.schema"+i+";"),a+="var "+d+";",p&&(a+=" if (schema"+s+" === undefined) "+d+" = true; else if (!Array.isArray(schema"+s+")) "+d+" = false; else {"),a+=d+" = false;for (var "+h+"=0; "+h+"<"+m+".length; "+h+"++) if (equal("+u+", "+m+"["+h+"])) { "+d+" = true; break; }",p&&(a+=" } "),a+=" if (!"+d+") { ";var f=f||[];f.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValues: schema"+s+" } ",!1!==e.opts.messages&&(a+=" , message: 'should be equal to one of the allowed values' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var g=a;return a=f.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+g+"]); ":a+=" validate.errors = ["+g+"]; return false; ":a+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" }",l&&(a+=" else { "),a}),Gr),format:(Wr||(Wr=1,Kr=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[r],i=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,u="data"+(o||"");if(!1===e.opts.format)return l&&(a+=" if (true) { "),a;var d,p=e.opts.$data&&n&&n.$data;p?(a+=" var schema"+s+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ",d="schema"+s):d=n;var h=e.opts.unknownFormats,m=Array.isArray(h);if(p)a+=" var "+(f="format"+s)+" = formats["+d+"]; var "+(g="isObject"+s)+" = typeof "+f+" == 'object' && !("+f+" instanceof RegExp) && "+f+".validate; var "+(v="formatType"+s)+" = "+g+" && "+f+".type || 'string'; if ("+g+") { ",e.async&&(a+=" var async"+s+" = "+f+".async; "),a+=" "+f+" = "+f+".validate; } if ( ",p&&(a+=" ("+d+" !== undefined && typeof "+d+" != 'string') || "),a+=" (","ignore"!=h&&(a+=" ("+d+" && !"+f+" ",m&&(a+=" && self._opts.unknownFormats.indexOf("+d+") == -1 "),a+=") || "),a+=" ("+f+" && "+v+" == '"+t+"' && !(typeof "+f+" == 'function' ? ",e.async?a+=" (async"+s+" ? await "+f+"("+u+") : "+f+"("+u+")) ":a+=" "+f+"("+u+") ",a+=" : "+f+".test("+u+"))))) {";else{var f;if(!(f=e.formats[n])){if("ignore"==h)return e.logger.warn('unknown format "'+n+'" ignored in schema at path "'+e.errSchemaPath+'"'),l&&(a+=" if (true) { "),a;if(m&&h.indexOf(n)>=0)return l&&(a+=" if (true) { "),a;throw new Error('unknown format "'+n+'" is used in schema at path "'+e.errSchemaPath+'"')}var g,v=(g="object"==typeof f&&!(f instanceof RegExp)&&f.validate)&&f.type||"string";if(g){var y=!0===f.async;f=f.validate}if(v!=t)return l&&(a+=" if (true) { "),a;if(y){if(!e.async)throw new Error("async format in sync schema");a+=" if (!(await "+(b="formats"+e.util.getProperty(n)+".validate")+"("+u+"))) { "}else{a+=" if (! ";var b="formats"+e.util.getProperty(n);g&&(b+=".validate"),a+="function"==typeof f?" "+b+"("+u+") ":" "+b+".test("+u+") ",a+=") { "}}var w=w||[];w.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { format: ",a+=p?""+d:""+e.util.toQuotedString(n),a+=" } ",!1!==e.opts.messages&&(a+=" , message: 'should match format \"",a+=p?"' + "+d+" + '":""+e.util.escapeQuotes(n),a+="\"' "),e.opts.verbose&&(a+=" , schema: ",a+=p?"validate.schema"+i:""+e.util.toQuotedString(n),a+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var P=a;return a=w.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+P+"]); ":a+=" validate.errors = ["+P+"]; return false; ":a+=" var err = "+P+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ",l&&(a+=" else { "),a}),Kr),if:(Xr||(Xr=1,Yr=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[r],i=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,u="data"+(o||""),d="valid"+s,p="errs__"+s,h=e.util.copy(e);h.level++;var m="valid"+h.level,f=e.schema.then,g=e.schema.else,v=void 0!==f&&(e.opts.strictKeywords?"object"==typeof f&&Object.keys(f).length>0||!1===f:e.util.schemaHasRules(f,e.RULES.all)),y=void 0!==g&&(e.opts.strictKeywords?"object"==typeof g&&Object.keys(g).length>0||!1===g:e.util.schemaHasRules(g,e.RULES.all)),b=h.baseId;if(v||y){var w;h.createErrors=!1,h.schema=n,h.schemaPath=i,h.errSchemaPath=c,a+=" var "+p+" = errors; var "+d+" = true; ";var P=e.compositeRule;e.compositeRule=h.compositeRule=!0,a+=" "+e.validate(h)+" ",h.baseId=b,h.createErrors=!0,a+=" errors = "+p+"; if (vErrors !== null) { if ("+p+") vErrors.length = "+p+"; else vErrors = null; } ",e.compositeRule=h.compositeRule=P,v?(a+=" if ("+m+") { ",h.schema=e.schema.then,h.schemaPath=e.schemaPath+".then",h.errSchemaPath=e.errSchemaPath+"/then",a+=" "+e.validate(h)+" ",h.baseId=b,a+=" "+d+" = "+m+"; ",v&&y?a+=" var "+(w="ifClause"+s)+" = 'then'; ":w="'then'",a+=" } ",y&&(a+=" else { ")):a+=" if (!"+m+") { ",y&&(h.schema=e.schema.else,h.schemaPath=e.schemaPath+".else",h.errSchemaPath=e.errSchemaPath+"/else",a+=" "+e.validate(h)+" ",h.baseId=b,a+=" "+d+" = "+m+"; ",v&&y?a+=" var "+(w="ifClause"+s)+" = 'else'; ":w="'else'",a+=" } "),a+=" if (!"+d+") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'if' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { failingKeyword: "+w+" } ",!1!==e.opts.messages&&(a+=" , message: 'should match \"' + "+w+" + '\" schema' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&l&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),a+=" } ",l&&(a+=" else { ")}else l&&(a+=" if (true) { ");return a}),Yr),items:(rt||(rt=1,et=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[r],i=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,u="data"+(o||""),d="valid"+s,p="errs__"+s,h=e.util.copy(e),m="";h.level++;var f="valid"+h.level,g="i"+s,v=h.dataLevel=e.dataLevel+1,y="data"+v,b=e.baseId;if(a+="var "+p+" = errors;var "+d+";",Array.isArray(n)){var w=e.schema.additionalItems;if(!1===w){a+=" "+d+" = "+u+".length <= "+n.length+"; ";var P=c;c=e.errSchemaPath+"/additionalItems",a+=" if (!"+d+") { ";var _=_||[];_.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+n.length+" } ",!1!==e.opts.messages&&(a+=" , message: 'should NOT have more than "+n.length+" items' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var E=a;a=_.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+E+"]); ":a+=" validate.errors = ["+E+"]; return false; ":a+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ",c=P,l&&(m+="}",a+=" else { ")}var S=n;if(S)for(var $,x=-1,k=S.length-1;x<k;)if($=S[x+=1],e.opts.strictKeywords?"object"==typeof $&&Object.keys($).length>0||!1===$:e.util.schemaHasRules($,e.RULES.all)){a+=" "+f+" = true; if ("+u+".length > "+x+") { ";var R=u+"["+x+"]";h.schema=$,h.schemaPath=i+"["+x+"]",h.errSchemaPath=c+"/"+x,h.errorPath=e.util.getPathExpr(e.errorPath,x,e.opts.jsonPointers,!0),h.dataPathArr[v]=x;var j=e.validate(h);h.baseId=b,e.util.varOccurences(j,y)<2?a+=" "+e.util.varReplace(j,y,R)+" ":a+=" var "+y+" = "+R+"; "+j+" ",a+=" } ",l&&(a+=" if ("+f+") { ",m+="}")}"object"==typeof w&&(e.opts.strictKeywords?"object"==typeof w&&Object.keys(w).length>0||!1===w:e.util.schemaHasRules(w,e.RULES.all))&&(h.schema=w,h.schemaPath=e.schemaPath+".additionalItems",h.errSchemaPath=e.errSchemaPath+"/additionalItems",a+=" "+f+" = true; if ("+u+".length > "+n.length+") { for (var "+g+" = "+n.length+"; "+g+" < "+u+".length; "+g+"++) { ",h.errorPath=e.util.getPathExpr(e.errorPath,g,e.opts.jsonPointers,!0),R=u+"["+g+"]",h.dataPathArr[v]=g,j=e.validate(h),h.baseId=b,e.util.varOccurences(j,y)<2?a+=" "+e.util.varReplace(j,y,R)+" ":a+=" var "+y+" = "+R+"; "+j+" ",l&&(a+=" if (!"+f+") break; "),a+=" } } ",l&&(a+=" if ("+f+") { ",m+="}"))}else(e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all))&&(h.schema=n,h.schemaPath=i,h.errSchemaPath=c,a+=" for (var "+g+" = 0; "+g+" < "+u+".length; "+g+"++) { ",h.errorPath=e.util.getPathExpr(e.errorPath,g,e.opts.jsonPointers,!0),R=u+"["+g+"]",h.dataPathArr[v]=g,j=e.validate(h),h.baseId=b,e.util.varOccurences(j,y)<2?a+=" "+e.util.varReplace(j,y,R)+" ":a+=" var "+y+" = "+R+"; "+j+" ",l&&(a+=" if (!"+f+") break; "),a+=" }");return l&&(a+=" "+m+" if ("+p+" == errors) {"),a}),et),maximum:Nt(),minimum:Nt(),maxItems:Dt(),minItems:Dt(),maxLength:Ht(),minLength:Ht(),maxProperties:Lt(),minProperties:Lt(),multipleOf:(dt||(dt=1,ut=function(e,r,t){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[r],c=e.schemaPath+e.util.getProperty(r),l=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,d="data"+(n||""),p=e.opts.$data&&i&&i.$data;if(p?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,!p&&"number"!=typeof i)throw new Error(r+" must be number");s+="var division"+o+";if (",p&&(s+=" "+a+" !== undefined && ( typeof "+a+" != 'number' || "),s+=" (division"+o+" = "+d+" / "+a+", ",e.opts.multipleOfPrecision?s+=" Math.abs(Math.round(division"+o+") - division"+o+") > 1e-"+e.opts.multipleOfPrecision+" ":s+=" division"+o+" !== parseInt(division"+o+") ",s+=" ) ",p&&(s+=" ) "),s+=" ) { ";var h=h||[];h.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { multipleOf: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should be multiple of ",s+=p?"' + "+a:a+"'"),e.opts.verbose&&(s+=" , schema: ",s+=p?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),s+=" } "):s+=" {} ";var m=s;return s=h.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+m+"]); ":s+=" validate.errors = ["+m+"]; return false; ":s+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",u&&(s+=" else { "),s}),ut),not:(ht||(ht=1,pt=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[r],i=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,u="data"+(o||""),d="errs__"+s,p=e.util.copy(e);p.level++;var h="valid"+p.level;if(e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all)){p.schema=n,p.schemaPath=i,p.errSchemaPath=c,a+=" var "+d+" = errors; ";var m,f=e.compositeRule;e.compositeRule=p.compositeRule=!0,p.createErrors=!1,p.opts.allErrors&&(m=p.opts.allErrors,p.opts.allErrors=!1),a+=" "+e.validate(p)+" ",p.createErrors=!0,m&&(p.opts.allErrors=m),e.compositeRule=p.compositeRule=f,a+=" if ("+h+") { ";var g=g||[];g.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should NOT be valid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var v=a;a=g.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+v+"]); ":a+=" validate.errors = ["+v+"]; return false; ":a+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; } ",e.opts.allErrors&&(a+=" } ")}else a+=" var err = ",!1!==e.createErrors?(a+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should NOT be valid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",l&&(a+=" if (false) { ");return a}),pt),oneOf:(ft||(ft=1,mt=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[r],i=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,u="data"+(o||""),d="valid"+s,p="errs__"+s,h=e.util.copy(e),m="";h.level++;var f="valid"+h.level,g=h.baseId,v="prevValid"+s,y="passingSchemas"+s;a+="var "+p+" = errors , "+v+" = false , "+d+" = false , "+y+" = null; ";var b=e.compositeRule;e.compositeRule=h.compositeRule=!0;var w=n;if(w)for(var P,_=-1,E=w.length-1;_<E;)P=w[_+=1],(e.opts.strictKeywords?"object"==typeof P&&Object.keys(P).length>0||!1===P:e.util.schemaHasRules(P,e.RULES.all))?(h.schema=P,h.schemaPath=i+"["+_+"]",h.errSchemaPath=c+"/"+_,a+=" "+e.validate(h)+" ",h.baseId=g):a+=" var "+f+" = true; ",_&&(a+=" if ("+f+" && "+v+") { "+d+" = false; "+y+" = ["+y+", "+_+"]; } else { ",m+="}"),a+=" if ("+f+") { "+d+" = "+v+" = true; "+y+" = "+_+"; }";return e.compositeRule=h.compositeRule=b,a+=m+"if (!"+d+") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { passingSchemas: "+y+" } ",!1!==e.opts.messages&&(a+=" , message: 'should match exactly one schema in oneOf' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&l&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),a+="} else { errors = "+p+"; if (vErrors !== null) { if ("+p+") vErrors.length = "+p+"; else vErrors = null; }",e.opts.allErrors&&(a+=" } "),a}),mt),pattern:(vt||(vt=1,gt=function(e,r,t){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[r],c=e.schemaPath+e.util.getProperty(r),l=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,d="data"+(n||""),p=e.opts.$data&&i&&i.$data;p?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,s+="if ( ",p&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'string') || "),s+=" !"+(p?"(new RegExp("+a+"))":e.usePattern(i))+".test("+d+") ) { ";var h=h||[];h.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { pattern: ",s+=p?""+a:""+e.util.toQuotedString(i),s+=" } ",!1!==e.opts.messages&&(s+=" , message: 'should match pattern \"",s+=p?"' + "+a+" + '":""+e.util.escapeQuotes(i),s+="\"' "),e.opts.verbose&&(s+=" , schema: ",s+=p?"validate.schema"+c:""+e.util.toQuotedString(i),s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),s+=" } "):s+=" {} ";var m=s;return s=h.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+m+"]); ":s+=" validate.errors = ["+m+"]; return false; ":s+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",u&&(s+=" else { "),s}),gt),properties:(bt||(bt=1,yt=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[r],i=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,u="data"+(o||""),d="errs__"+s,p=e.util.copy(e),h="";p.level++;var m="valid"+p.level,f="key"+s,g="idx"+s,v=p.dataLevel=e.dataLevel+1,y="data"+v,b="dataProperties"+s,w=Object.keys(n||{}).filter(F),P=e.schema.patternProperties||{},_=Object.keys(P).filter(F),E=e.schema.additionalProperties,S=w.length||_.length,$=!1===E,x="object"==typeof E&&Object.keys(E).length,k=e.opts.removeAdditional,R=$||x||k,j=e.opts.ownProperties,T=e.baseId,A=e.schema.required;if(A&&(!e.opts.$data||!A.$data)&&A.length<e.opts.loopRequired)var O=e.util.toHash(A);function F(e){return"__proto__"!==e}if(a+="var "+d+" = errors;var "+m+" = true;",j&&(a+=" var "+b+" = undefined;"),R){if(a+=j?" "+b+" = "+b+" || Object.keys("+u+"); for (var "+g+"=0; "+g+"<"+b+".length; "+g+"++) { var "+f+" = "+b+"["+g+"]; ":" for (var "+f+" in "+u+") { ",S){if(a+=" var isAdditional"+s+" = !(false ",w.length)if(w.length>8)a+=" || validate.schema"+i+".hasOwnProperty("+f+") ";else{var C=w;if(C)for(var I=-1,q=C.length-1;I<q;)J=C[I+=1],a+=" || "+f+" == "+e.util.toQuotedString(J)+" "}if(_.length){var N=_;if(N)for(var D=-1,H=N.length-1;D<H;)oe=N[D+=1],a+=" || "+e.usePattern(oe)+".test("+f+") "}a+=" ); if (isAdditional"+s+") { "}if("all"==k)a+=" delete "+u+"["+f+"]; ";else{var L=e.errorPath,U="' + "+f+" + '";if(e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(e.errorPath,f,e.opts.jsonPointers)),$)if(k)a+=" delete "+u+"["+f+"]; ";else{a+=" "+m+" = false; ";var z=c;c=e.errSchemaPath+"/additionalProperties",(te=te||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'additionalProperties' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { additionalProperty: '"+U+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is an invalid additional property":a+="should NOT have additional properties",a+="' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var M=a;a=te.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+M+"]); ":a+=" validate.errors = ["+M+"]; return false; ":a+=" var err = "+M+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=z,l&&(a+=" break; ")}else if(x)if("failing"==k){a+=" var "+d+" = errors; ";var Q=e.compositeRule;e.compositeRule=p.compositeRule=!0,p.schema=E,p.schemaPath=e.schemaPath+".additionalProperties",p.errSchemaPath=e.errSchemaPath+"/additionalProperties",p.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,f,e.opts.jsonPointers);var V=u+"["+f+"]";p.dataPathArr[v]=f;var Z=e.validate(p);p.baseId=T,e.util.varOccurences(Z,y)<2?a+=" "+e.util.varReplace(Z,y,V)+" ":a+=" var "+y+" = "+V+"; "+Z+" ",a+=" if (!"+m+") { errors = "+d+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+u+"["+f+"]; } ",e.compositeRule=p.compositeRule=Q}else p.schema=E,p.schemaPath=e.schemaPath+".additionalProperties",p.errSchemaPath=e.errSchemaPath+"/additionalProperties",p.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,f,e.opts.jsonPointers),V=u+"["+f+"]",p.dataPathArr[v]=f,Z=e.validate(p),p.baseId=T,e.util.varOccurences(Z,y)<2?a+=" "+e.util.varReplace(Z,y,V)+" ":a+=" var "+y+" = "+V+"; "+Z+" ",l&&(a+=" if (!"+m+") break; ");e.errorPath=L}S&&(a+=" } "),a+=" } ",l&&(a+=" if ("+m+") { ",h+="}")}var B=e.opts.useDefaults&&!e.compositeRule;if(w.length){var G=w;if(G)for(var J,K=-1,W=G.length-1;K<W;){var Y=n[J=G[K+=1]];if(e.opts.strictKeywords?"object"==typeof Y&&Object.keys(Y).length>0||!1===Y:e.util.schemaHasRules(Y,e.RULES.all)){var X=e.util.getProperty(J),ee=(V=u+X,B&&void 0!==Y.default);if(p.schema=Y,p.schemaPath=i+X,p.errSchemaPath=c+"/"+e.util.escapeFragment(J),p.errorPath=e.util.getPath(e.errorPath,J,e.opts.jsonPointers),p.dataPathArr[v]=e.util.toQuotedString(J),Z=e.validate(p),p.baseId=T,e.util.varOccurences(Z,y)<2){Z=e.util.varReplace(Z,y,V);var re=V}else re=y,a+=" var "+y+" = "+V+"; ";if(ee)a+=" "+Z+" ";else{if(O&&O[J]){a+=" if ( "+re+" === undefined ",j&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(J)+"') "),a+=") { "+m+" = false; ",L=e.errorPath,z=c;var te,ae=e.util.escapeQuotes(J);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(L,J,e.opts.jsonPointers)),c=e.errSchemaPath+"/required",(te=te||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+ae+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+ae+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",M=a,a=te.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+M+"]); ":a+=" validate.errors = ["+M+"]; return false; ":a+=" var err = "+M+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=z,e.errorPath=L,a+=" } else { "}else l?(a+=" if ( "+re+" === undefined ",j&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(J)+"') "),a+=") { "+m+" = true; } else { "):(a+=" if ("+re+" !== undefined ",j&&(a+=" && Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(J)+"') "),a+=" ) { ");a+=" "+Z+" } "}}l&&(a+=" if ("+m+") { ",h+="}")}}if(_.length){var se=_;if(se)for(var oe,ne=-1,ie=se.length-1;ne<ie;)Y=P[oe=se[ne+=1]],(e.opts.strictKeywords?"object"==typeof Y&&Object.keys(Y).length>0||!1===Y:e.util.schemaHasRules(Y,e.RULES.all))&&(p.schema=Y,p.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty(oe),p.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment(oe),a+=j?" "+b+" = "+b+" || Object.keys("+u+"); for (var "+g+"=0; "+g+"<"+b+".length; "+g+"++) { var "+f+" = "+b+"["+g+"]; ":" for (var "+f+" in "+u+") { ",a+=" if ("+e.usePattern(oe)+".test("+f+")) { ",p.errorPath=e.util.getPathExpr(e.errorPath,f,e.opts.jsonPointers),V=u+"["+f+"]",p.dataPathArr[v]=f,Z=e.validate(p),p.baseId=T,e.util.varOccurences(Z,y)<2?a+=" "+e.util.varReplace(Z,y,V)+" ":a+=" var "+y+" = "+V+"; "+Z+" ",l&&(a+=" if (!"+m+") break; "),a+=" } ",l&&(a+=" else "+m+" = true; "),a+=" } ",l&&(a+=" if ("+m+") { ",h+="}"))}return l&&(a+=" "+h+" if ("+d+" == errors) {"),a}),yt),propertyNames:(Pt||(Pt=1,wt=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[r],i=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,u="data"+(o||""),d="errs__"+s,p=e.util.copy(e);p.level++;var h="valid"+p.level;if(a+="var "+d+" = errors;",e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all)){p.schema=n,p.schemaPath=i,p.errSchemaPath=c;var m="key"+s,f="idx"+s,g="i"+s,v="' + "+m+" + '",y="data"+(p.dataLevel=e.dataLevel+1),b="dataProperties"+s,w=e.opts.ownProperties,P=e.baseId;w&&(a+=" var "+b+" = undefined; "),a+=w?" "+b+" = "+b+" || Object.keys("+u+"); for (var "+f+"=0; "+f+"<"+b+".length; "+f+"++) { var "+m+" = "+b+"["+f+"]; ":" for (var "+m+" in "+u+") { ",a+=" var startErrs"+s+" = errors; ";var _=m,E=e.compositeRule;e.compositeRule=p.compositeRule=!0;var S=e.validate(p);p.baseId=P,e.util.varOccurences(S,y)<2?a+=" "+e.util.varReplace(S,y,_)+" ":a+=" var "+y+" = "+_+"; "+S+" ",e.compositeRule=p.compositeRule=E,a+=" if (!"+h+") { for (var "+g+"=startErrs"+s+"; "+g+"<errors; "+g+"++) { vErrors["+g+"].propertyName = "+m+"; } var err = ",!1!==e.createErrors?(a+=" { keyword: 'propertyNames' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { propertyName: '"+v+"' } ",!1!==e.opts.messages&&(a+=" , message: 'property name \\'"+v+"\\' is invalid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&l&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),l&&(a+=" break; "),a+=" } }"}return l&&(a+=" if ("+d+" == errors) {"),a}),wt),required:(Et||(Et=1,_t=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[r],i=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,u="data"+(o||""),d="valid"+s,p=e.opts.$data&&n&&n.$data;p&&(a+=" var schema"+s+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ");var h="schema"+s;if(!p)if(n.length<e.opts.loopRequired&&e.schema.properties&&Object.keys(e.schema.properties).length){var m=[],f=n;if(f)for(var g,v=-1,y=f.length-1;v<y;){g=f[v+=1];var b=e.schema.properties[g];b&&(e.opts.strictKeywords?"object"==typeof b&&Object.keys(b).length>0||!1===b:e.util.schemaHasRules(b,e.RULES.all))||(m[m.length]=g)}}else m=n;if(p||m.length){var w=e.errorPath,P=p||m.length>=e.opts.loopRequired,_=e.opts.ownProperties;if(l)if(a+=" var missing"+s+"; ",P){p||(a+=" var "+h+" = validate.schema"+i+"; ");var E="' + "+(j="schema"+s+"["+(k="i"+s)+"]")+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(w,j,e.opts.jsonPointers)),a+=" var "+d+" = true; ",p&&(a+=" if (schema"+s+" === undefined) "+d+" = true; else if (!Array.isArray(schema"+s+")) "+d+" = false; else {"),a+=" for (var "+k+" = 0; "+k+" < "+h+".length; "+k+"++) { "+d+" = "+u+"["+h+"["+k+"]] !== undefined ",_&&(a+=" && Object.prototype.hasOwnProperty.call("+u+", "+h+"["+k+"]) "),a+="; if (!"+d+") break; } ",p&&(a+=" } "),a+=" if (!"+d+") { ",($=$||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var S=a;a=$.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+S+"]); ":a+=" validate.errors = ["+S+"]; return false; ":a+=" var err = "+S+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { "}else{a+=" if ( ";var $,x=m;if(x)for(var k=-1,R=x.length-1;k<R;)A=x[k+=1],k&&(a+=" || "),a+=" ( ( "+(I=u+(C=e.util.getProperty(A)))+" === undefined ",_&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(A)+"') "),a+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?A:C)+") ) ";a+=") { ",E="' + "+(j="missing"+s)+" + '",e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(w,j,!0):w+" + "+j),($=$||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",S=a,a=$.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+S+"]); ":a+=" validate.errors = ["+S+"]; return false; ":a+=" var err = "+S+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { "}else if(P){var j;p||(a+=" var "+h+" = validate.schema"+i+"; "),E="' + "+(j="schema"+s+"["+(k="i"+s)+"]")+" + '",e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(w,j,e.opts.jsonPointers)),p&&(a+=" if ("+h+" && !Array.isArray("+h+")) { var err = ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+h+" !== undefined) { "),a+=" for (var "+k+" = 0; "+k+" < "+h+".length; "+k+"++) { if ("+u+"["+h+"["+k+"]] === undefined ",_&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", "+h+"["+k+"]) "),a+=") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",p&&(a+=" } ")}else{var T=m;if(T)for(var A,O=-1,F=T.length-1;O<F;){A=T[O+=1];var C=e.util.getProperty(A),I=(E=e.util.escapeQuotes(A),u+C);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(w,A,e.opts.jsonPointers)),a+=" if ( "+I+" === undefined ",_&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(A)+"') "),a+=") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}e.errorPath=w}else l&&(a+=" if (true) {");return a}),_t),uniqueItems:($t||($t=1,St=function(e,r,t){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[r],c=e.schemaPath+e.util.getProperty(r),l=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,d="data"+(n||""),p="valid"+o,h=e.opts.$data&&i&&i.$data;if(h?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,(i||h)&&!1!==e.opts.uniqueItems){h&&(s+=" var "+p+"; if ("+a+" === false || "+a+" === undefined) "+p+" = true; else if (typeof "+a+" != 'boolean') "+p+" = false; else { "),s+=" var i = "+d+".length , "+p+" = true , j; if (i > 1) { ";var m=e.schema.items&&e.schema.items.type,f=Array.isArray(m);if(!m||"object"==m||"array"==m||f&&(m.indexOf("object")>=0||m.indexOf("array")>=0))s+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+d+"[i], "+d+"[j])) { "+p+" = false; break outer; } } } ";else{s+=" var itemIndices = {}, item; for (;i--;) { var item = "+d+"[i]; ";var g="checkDataType"+(f?"s":"");s+=" if ("+e.util[g](m,"item",e.opts.strictNumbers,!0)+") continue; ",f&&(s+=" if (typeof item == 'string') item = '\"' + item; "),s+=" if (typeof itemIndices[item] == 'number') { "+p+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}s+=" } ",h&&(s+=" } "),s+=" if (!"+p+") { ";var v=v||[];v.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { i: i, j: j } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),s+=" } "):s+=" {} ";var y=s;s=v.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+y+"]); ":s+=" validate.errors = ["+y+"]; return false; ":s+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } ",u&&(s+=" else { ")}else u&&(s+=" if (true) { ");return s}),St),validate:jr()}),xt),r=dr().toHash;return Rt=function(){var t=[{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"]}],a=["type","$comment"];return t.all=r(a),t.types=r(["number","integer","string","array","object","boolean","null"]),t.forEach(function(r){r.rules=r.rules.map(function(r){var s;if("object"==typeof r){var o=Object.keys(r)[0];s=r[o],r=o,s.forEach(function(e){a.push(e),t.all[e]=!0})}return a.push(r),t.all[r]={keyword:r,code:e[r],implements:s}}),t.all.$comment={keyword:"$comment",code:e.$comment},r.type&&(t.types[r.type]=r)}),t.keywords=r(a.concat(["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"])),t.custom={},t},Rt}function zt(){if(Ft)return Ot;Ft=1;var e=kr().MissingRef;return Ot=function r(t,a,s){var o=this;if("function"!=typeof this._opts.loadSchema)throw new Error("options.loadSchema should be a function");"function"==typeof a&&(s=a,a=void 0);var n=i(t).then(function(){var e=o._addSchema(t,void 0,a);return e.validate||c(e)});return s&&n.then(function(e){s(null,e)},s),n;function i(e){var t=e.$schema;return t&&!o.getSchema(t)?r.call(o,{$ref:t},!0):Promise.resolve()}function c(r){try{return o._compile(r)}catch(t){if(t instanceof e)return function(e){var t=e.missingSchema;if(l(t))throw new Error("Schema "+t+" is loaded but "+e.missingRef+" cannot be resolved");var s=o._loadingSchemas[t];return s||(s=o._loadingSchemas[t]=o._opts.loadSchema(t)).then(n,n),s.then(function(e){if(!l(t))return i(e).then(function(){l(t)||o.addSchema(e,t,void 0,a)})}).then(function(){return c(r)});function n(){delete o._loadingSchemas[t]}function l(e){return o._refs[e]||o._schemas[e]}}(t);throw t}}},Ot}var Mt,Qt,Vt,Zt,Bt={$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 Gt,Jt,Kt={$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},Wt=function(){if(Jt)return Gt;Jt=1;var e=Tr(),r=xr(),t=function(){if(Ar)return qt.exports;Ar=1;var e=qt.exports=function(){this._cache={}};return e.prototype.put=function(e,r){this._cache[e]=r},e.prototype.get=function(e){return this._cache[e]},e.prototype.del=function(e){delete this._cache[e]},e.prototype.clear=function(){this._cache={}},qt.exports}(),a=pr(),s=Rr(),o=function(){if(Fr)return Or;Fr=1;var e=dr(),r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,t=[0,31,28,31,30,31,30,31,31,30,31,30,31],a=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,s=/^(?=.{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,o=/^(?:[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,n=/^(?:(?:[^\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,i=/^(?:(?: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,c=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,l=/^(?:\/(?:[^~/]|~0|~1)*)*$/,u=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,d=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function p(r){return r="full"==r?"full":"fast",e.copy(p[r])}function h(e){var a=e.match(r);if(!a)return!1;var s=+a[1],o=+a[2],n=+a[3];return o>=1&&o<=12&&n>=1&&n<=(2==o&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(s)?29:t[o])}function m(e,r){var t=e.match(a);if(!t)return!1;var s=t[1],o=t[2],n=t[3],i=t[5];return(s<=23&&o<=59&&n<=59||23==s&&59==o&&60==n)&&(!r||i)}Or=p,p.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":n,url:i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,hostname:s,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:y,uuid:c,"json-pointer":l,"json-pointer-uri-fragment":u,"relative-json-pointer":d},p.full={date:h,time:m,"date-time":function(e){var r=e.split(f);return 2==r.length&&h(r[0])&&m(r[1],!0)},uri:function(e){return g.test(e)&&o.test(e)},"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":n,url:i,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:s,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:y,uuid:c,"json-pointer":l,"json-pointer-uri-fragment":u,"relative-json-pointer":d};var f=/t|\s/i,g=/\/|:/,v=/[^\\]\\Z/;function y(e){if(v.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}}return Or}(),n=Ut(),i=function(){if(At)return Tt;At=1;var e=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"];return Tt=function(r,t){for(var a=0;a<t.length;a++){r=JSON.parse(JSON.stringify(r));var s,o=t[a].split("/"),n=r;for(s=1;s<o.length;s++)n=n[o[s]];for(s=0;s<e.length;s++){var i=e[s],c=n[i];c&&(n[i]={anyOf:[c,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]})}}return r}}(),c=dr();Gt=m,m.prototype.validate=function(e,r){var t;if("string"==typeof e){if(!(t=this.getSchema(e)))throw new Error('no schema with key or ref "'+e+'"')}else{var a=this._addSchema(e);t=a.validate||this._compile(a)}var s=t(r);return!0!==t.$async&&(this.errors=t.errors),s},m.prototype.compile=function(e,r){var t=this._addSchema(e,void 0,r);return t.validate||this._compile(t)},m.prototype.addSchema=function(e,t,a,s){if(Array.isArray(e)){for(var o=0;o<e.length;o++)this.addSchema(e[o],void 0,a,s);return this}var n=this._getId(e);if(void 0!==n&&"string"!=typeof n)throw new Error("schema id must be string");return w(this,t=r.normalizeId(t||n)),this._schemas[t]=this._addSchema(e,a,s,!0),this},m.prototype.addMetaSchema=function(e,r,t){return this.addSchema(e,r,t,!0),this},m.prototype.validateSchema=function(e,r){var t,a,s=e.$schema;if(void 0!==s&&"string"!=typeof s)throw new Error("$schema must be a string");if(!(s=s||this._opts.defaultMeta||(a=(t=this)._opts.meta,t._opts.defaultMeta="object"==typeof a?t._getId(a)||a:t.getSchema(d)?d:void 0,t._opts.defaultMeta)))return this.logger.warn("meta-schema not available"),this.errors=null,!0;var o=this.validate(s,e);if(!o&&r){var n="schema is invalid: "+this.errorsText();if("log"!=this._opts.validateSchema)throw new Error(n);this.logger.error(n)}return o},m.prototype.getSchema=function(t){var s=f(this,t);switch(typeof s){case"object":return s.validate||this._compile(s);case"string":return this.getSchema(s);case"undefined":return function(t,s){var o=r.schema.call(t,{schema:{}},s);if(o){var n=o.schema,i=o.root,c=o.baseId,l=e.call(t,n,i,void 0,c);return t._fragments[s]=new a({ref:s,fragment:!0,schema:n,root:i,baseId:c,validate:l}),l}}(this,t)}},m.prototype.removeSchema=function(e){if(e instanceof RegExp)return g(this,this._schemas,e),g(this,this._refs,e),this;switch(typeof e){case"undefined":return g(this,this._schemas),g(this,this._refs),this._cache.clear(),this;case"string":var t=f(this,e);return t&&this._cache.del(t.cacheKey),delete this._schemas[e],delete this._refs[e],this;case"object":var a=this._opts.serialize,s=a?a(e):e;this._cache.del(s);var o=this._getId(e);o&&(o=r.normalizeId(o),delete this._schemas[o],delete this._refs[o])}return this},m.prototype.addFormat=function(e,r){return"string"==typeof r&&(r=new RegExp(r)),this._formats[e]=r,this},m.prototype.errorsText=function(e,r){if(!(e=e||this.errors))return"No errors";for(var t=void 0===(r=r||{}).separator?", ":r.separator,a=void 0===r.dataVar?"data":r.dataVar,s="",o=0;o<e.length;o++){var n=e[o];n&&(s+=a+n.dataPath+" "+n.message+t)}return s.slice(0,-t.length)},m.prototype._addSchema=function(e,t,s,o){if("object"!=typeof e&&"boolean"!=typeof e)throw new Error("schema should be object or boolean");var n=this._opts.serialize,i=n?n(e):e,c=this._cache.get(i);if(c)return c;o=o||!1!==this._opts.addUsedSchema;var l=r.normalizeId(this._getId(e));l&&o&&w(this,l);var u,d=!1!==this._opts.validateSchema&&!t;d&&!(u=l&&l==r.normalizeId(e.$schema))&&this.validateSchema(e,!0);var p=r.ids.call(this,e),h=new a({id:l,schema:e,localRefs:p,cacheKey:i,meta:s});return"#"!=l[0]&&o&&(this._refs[l]=h),this._cache.put(i,h),d&&u&&this.validateSchema(e,!0),h},m.prototype._compile=function(r,t){if(r.compiling)return r.validate=o,o.schema=r.schema,o.errors=null,o.root=t||o,!0===r.schema.$async&&(o.$async=!0),o;var a,s;r.compiling=!0,r.meta&&(a=this._opts,this._opts=this._metaOpts);try{s=e.call(this,r.schema,t,r.localRefs)}catch(e){throw delete r.validate,e}finally{r.compiling=!1,r.meta&&(this._opts=a)}return r.validate=s,r.refs=s.refs,r.refVal=s.refVal,r.root=s.root,s;function o(){var e=r.validate,t=e.apply(this,arguments);return o.errors=e.errors,t}},m.prototype.compileAsync=zt();var l=function(){if(Zt)return Vt;Zt=1;var e=/^[a-z_$][a-z0-9_$-]*$/i,r=(It||(It=1,Ct=function(e,r,t){var a,s,o=" ",n=e.level,i=e.dataLevel,c=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,p="data"+(i||""),h="valid"+n,m="errs__"+n,f=e.opts.$data&&c&&c.$data;f?(o+=" var schema"+n+" = "+e.util.getData(c.$data,i,e.dataPathArr)+"; ",s="schema"+n):s=c;var g,v,y,b,w,P=this,_="definition"+n,E=P.definition,S="";if(f&&E.$data){w="keywordValidate"+n;var $=E.validateSchema;o+=" var "+_+" = RULES.custom['"+r+"'].definition; var "+w+" = "+_+".validate;"}else{if(!(b=e.useCustomRule(P,c,e.schema,e)))return;s="validate.schema"+l,w=b.code,g=E.compile,v=E.inline,y=E.macro}var x=w+".errors",k="i"+n,R="ruleErr"+n,j=E.async;if(j&&!e.async)throw new Error("async keyword in sync schema");if(v||y||(o+=x+" = null;"),o+="var "+m+" = errors;var "+h+";",f&&E.$data&&(S+="}",o+=" if ("+s+" === undefined) { "+h+" = true; } else { ",$&&(S+="}",o+=" "+h+" = "+_+".validateSchema("+s+"); if ("+h+") { ")),v)E.statements?o+=" "+b.validate+" ":o+=" "+h+" = "+b.validate+"; ";else if(y){var T=e.util.copy(e);S="",T.level++;var A="valid"+T.level;T.schema=b.validate,T.schemaPath="";var O=e.compositeRule;e.compositeRule=T.compositeRule=!0;var F=e.validate(T).replace(/validate\.schema/g,w);e.compositeRule=T.compositeRule=O,o+=" "+F}else{(N=N||[]).push(o),o="",o+=" "+w+".call( ",e.opts.passContext?o+="this":o+="self",g||!1===E.schema?o+=" , "+p+" ":o+=" , "+s+" , "+p+" , validate.schema"+e.schemaPath+" ",o+=" , (dataPath || '')",'""'!=e.errorPath&&(o+=" + "+e.errorPath);var C=i?"data"+(i-1||""):"parentData",I=i?e.dataPathArr[i]:"parentDataProperty",q=o+=" , "+C+" , "+I+" , rootData ) ";o=N.pop(),!1===E.errors?(o+=" "+h+" = ",j&&(o+="await "),o+=q+"; "):o+=j?" var "+(x="customErrors"+n)+" = null; try { "+h+" = await "+q+"; } catch (e) { "+h+" = false; if (e instanceof ValidationError) "+x+" = e.errors; else throw e; } ":" "+x+" = null; "+h+" = "+q+"; "}if(E.modifying&&(o+=" if ("+C+") "+p+" = "+C+"["+I+"];"),o+=""+S,E.valid)d&&(o+=" if (true) { ");else{var N;o+=" if ( ",void 0===E.valid?(o+=" !",o+=y?""+A:""+h):o+=" "+!E.valid+" ",o+=") { ",a=P.keyword,(N=N||[]).push(o),o="",(N=N||[]).push(o),o="",!1!==e.createErrors?(o+=" { keyword: '"+(a||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { keyword: '"+P.keyword+"' } ",!1!==e.opts.messages&&(o+=" , message: 'should pass \""+P.keyword+"\" keyword validation' "),e.opts.verbose&&(o+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+p+" "),o+=" } "):o+=" {} ";var D=o;o=N.pop(),!e.compositeRule&&d?e.async?o+=" throw new ValidationError(["+D+"]); ":o+=" validate.errors = ["+D+"]; return false; ":o+=" var err = "+D+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";var H=o;o=N.pop(),v?E.errors?"full"!=E.errors&&(o+=" for (var "+k+"="+m+"; "+k+"<errors; "+k+"++) { var "+R+" = vErrors["+k+"]; if ("+R+".dataPath === undefined) "+R+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+R+".schemaPath === undefined) { "+R+'.schemaPath = "'+u+'"; } ',e.opts.verbose&&(o+=" "+R+".schema = "+s+"; "+R+".data = "+p+"; "),o+=" } "):!1===E.errors?o+=" "+H+" ":(o+=" if ("+m+" == errors) { "+H+" } else { for (var "+k+"="+m+"; "+k+"<errors; "+k+"++) { var "+R+" = vErrors["+k+"]; if ("+R+".dataPath === undefined) "+R+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+R+".schemaPath === undefined) { "+R+'.schemaPath = "'+u+'"; } ',e.opts.verbose&&(o+=" "+R+".schema = "+s+"; "+R+".data = "+p+"; "),o+=" } } "):y?(o+=" var err = ",!1!==e.createErrors?(o+=" { keyword: '"+(a||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { keyword: '"+P.keyword+"' } ",!1!==e.opts.messages&&(o+=" , message: 'should pass \""+P.keyword+"\" keyword validation' "),e.opts.verbose&&(o+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+p+" "),o+=" } "):o+=" {} ",o+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?o+=" throw new ValidationError(vErrors); ":o+=" validate.errors = vErrors; return false; ")):!1===E.errors?o+=" "+H+" ":(o+=" if (Array.isArray("+x+")) { if (vErrors === null) vErrors = "+x+"; else vErrors = vErrors.concat("+x+"); errors = vErrors.length; for (var "+k+"="+m+"; "+k+"<errors; "+k+"++) { var "+R+" = vErrors["+k+"]; if ("+R+".dataPath === undefined) "+R+".dataPath = (dataPath || '') + "+e.errorPath+"; "+R+'.schemaPath = "'+u+'"; ',e.opts.verbose&&(o+=" "+R+".schema = "+s+"; "+R+".data = "+p+"; "),o+=" } } else { "+H+" } "),o+=" } ",d&&(o+=" else { ")}return o}),Ct),t=function(){if(Qt)return Mt;Qt=1;var e=Bt;return Mt={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:e.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:e.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"}]}}}}();return Vt={add:function(t,a){var s=this.RULES;if(s.keywords[t])throw new Error("Keyword "+t+" is already defined");if(!e.test(t))throw new Error("Keyword "+t+" is not a valid identifier");if(a){this.validateKeyword(a,!0);var o=a.type;if(Array.isArray(o))for(var n=0;n<o.length;n++)c(t,o[n],a);else c(t,o,a);var i=a.metaSchema;i&&(a.$data&&this._opts.$data&&(i={anyOf:[i,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}),a.validateSchema=this.compile(i,!0))}function c(e,t,a){for(var o,n=0;n<s.length;n++){var i=s[n];if(i.type==t){o=i;break}}o||(o={type:t,rules:[]},s.push(o));var c={keyword:e,definition:a,custom:!0,code:r,implements:a.implements};o.rules.push(c),s.custom[e]=c}return s.keywords[t]=s.all[t]=!0,this},get:function(e){var r=this.RULES.custom[e];return r?r.definition:this.RULES.keywords[e]||!1},remove:function(e){var r=this.RULES;delete r.keywords[e],delete r.all[e],delete r.custom[e];for(var t=0;t<r.length;t++)for(var a=r[t].rules,s=0;s<a.length;s++)if(a[s].keyword==e){a.splice(s,1);break}return this},validate:function e(r,a){e.errors=null;var s=this._validateKeyword=this._validateKeyword||this.compile(t,!0);if(s(r))return!0;if(e.errors=s.errors,a)throw new Error("custom keyword definition is invalid: "+this.errorsText(s.errors));return!1}},Vt}();m.prototype.addKeyword=l.add,m.prototype.getKeyword=l.get,m.prototype.removeKeyword=l.remove,m.prototype.validateKeyword=l.validate;var u=kr();m.ValidationError=u.Validation,m.MissingRefError=u.MissingRef,m.$dataMetaSchema=i;var d="http://json-schema.org/draft-07/schema",p=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],h=["/properties"];function m(e){if(!(this instanceof m))return new m(e);e=this._opts=c.copy(e)||{},function(e){var r=e._opts.logger;if(!1===r)e.logger={log:P,warn:P,error:P};else{if(void 0===r&&(r=console),!("object"==typeof r&&r.log&&r.warn&&r.error))throw new Error("logger must implement log, warn and error methods");e.logger=r}}(this),this._schemas={},this._refs={},this._fragments={},this._formats=o(e.format),this._cache=e.cache||new t,this._loadingSchemas={},this._compilations=[],this.RULES=n(),this._getId=function(e){switch(e.schemaId){case"auto":return b;case"id":return v;default:return y}}(e),e.loopRequired=e.loopRequired||1/0,"property"==e.errorDataPath&&(e._errorDataPathProperty=!0),void 0===e.serialize&&(e.serialize=s),this._metaOpts=function(e){for(var r=c.copy(e._opts),t=0;t<p.length;t++)delete r[p[t]];return r}(this),e.formats&&function(e){for(var r in e._opts.formats){var t=e._opts.formats[r];e.addFormat(r,t)}}(this),e.keywords&&function(e){for(var r in e._opts.keywords){var t=e._opts.keywords[r];e.addKeyword(r,t)}}(this),function(e){var r;if(e._opts.$data&&(r=Kt,e.addMetaSchema(r,r.$id,!0)),!1!==e._opts.meta){var t=Bt;e._opts.$data&&(t=i(t,h)),e.addMetaSchema(t,d,!0),e._refs["http://json-schema.org/schema"]=d}}(this),"object"==typeof e.meta&&this.addMetaSchema(e.meta),e.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),function(e){var r=e._opts.schemas;if(r)if(Array.isArray(r))e.addSchema(r);else for(var t in r)e.addSchema(r[t],t)}(this)}function f(e,t){return t=r.normalizeId(t),e._schemas[t]||e._refs[t]||e._fragments[t]}function g(e,r,t){for(var a in r){var s=r[a];s.meta||t&&!t.test(a)||(e._cache.del(s.cacheKey),delete r[a])}}function v(e){return e.$id&&this.logger.warn("schema $id ignored",e.$id),e.id}function y(e){return e.id&&this.logger.warn("schema id ignored",e.id),e.$id}function b(e){if(e.$id&&e.id&&e.$id!=e.id)throw new Error("schema $id is different from id");return e.$id||e.id}function w(e,r){if(e._schemas[r]||e._refs[r])throw new Error('schema with key or id "'+r+'" already exists')}function P(){}return Gt}(),Yt=Ye(Wt);class Xt extends We{constructor(e,r){var t;super(r),this._serverInfo=e,this._capabilities=null!==(t=null==r?void 0:r.capabilities)&&void 0!==t?t:{},this._instructions=null==r?void 0:r.instructions,this.setRequestHandler(q,e=>this._oninitialize(e)),this.setNotificationHandler(H,()=>{var e;return null===(e=this.oninitialized)||void 0===e?void 0:e.call(this)})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");var r,t;this._capabilities=(r=this._capabilities,t=e,Object.entries(t).reduce((e,[r,t])=>(e[r]=t&&"object"==typeof t&&e[r]?{...e[r],...t}:t,e),{...r}))}assertCapabilityForMethod(e){var r,t,a;switch(e){case"sampling/createMessage":if(!(null===(r=this._clientCapabilities)||void 0===r?void 0:r.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!(null===(t=this._clientCapabilities)||void 0===t?void 0:t.elicitation))throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!(null===(a=this._clientCapabilities)||void 0===a?void 0:a.roots))throw new Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`)}}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})`)}}async _oninitialize(e){const r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:h.includes(r)?r:p,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"},A)}async createMessage(e,r){return this.request({method:"sampling/createMessage",params:e},Ce,r)}async elicitInput(e,r){const t=await this.request({method:"elicitation/create",params:e},Ue,r);if("accept"===t.action&&t.content)try{const r=new Yt,a=r.compile(e.requestedSchema);if(!a(t.content))throw new Ke(R.InvalidParams,`Elicitation response content does not match requested schema: ${r.errorsText(a.errors)}`)}catch(e){if(e instanceof Ke)throw e;throw new Ke(R.InternalError,`Error validating elicitation response: ${e}`)}return t}async listRoots(e,r){return this.request({method:"roots/list",params:e},Ge,r)}async sendLoggingMessage(e){return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}const ea=Symbol("Let zodToJsonSchema decide on which parser to use"),ra={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"};function ta(e,r,t,a){a?.errorMessages&&t&&(e.errorMessage={...e.errorMessage,[r]:t})}function aa(e,r,t,a,s){e[r]=t,ta(e,r,a,s)}const sa=(e,r)=>{let t=0;for(;t<e.length&&t<r.length&&e[t]===r[t];t++);return[(e.length-t).toString(),...r.slice(t)].join("/")};function oa(e){if("openAi"!==e.target)return{};const r=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?sa(r,e.currentPath):r.join("/")}}function na(e,r){return Oa(e.type._def,r)}function ia(e,r,t){const a=t??r.dateStrategy;if(Array.isArray(a))return{anyOf:a.map((t,a)=>ia(e,r,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 ca(e,r)}}const ca=(e,r)=>{const t={type:"integer",format:"unix-time"};if("openApi3"===r.target)return t;for(const a of e.checks)switch(a.kind){case"min":aa(t,"minimum",a.value,a.message,r);break;case"max":aa(t,"maximum",a.value,a.message,r)}return t};let la;const ua=/^[cC][^\s-]{8,}$/,da=/^[0-9a-z]+$/,pa=/^[0-9A-HJKMNP-TV-Z]{26}$/,ha=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,ma=()=>(void 0===la&&(la=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),la),fa=/^(?:(?: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])$/,ga=/^(([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])$/,va=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ya=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ba=/^[a-zA-Z0-9_-]{21}$/,wa=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function Pa(e,r){const t={type:"string"};if(e.checks)for(const a of e.checks)switch(a.kind){case"min":aa(t,"minLength","number"==typeof t.minLength?Math.max(t.minLength,a.value):a.value,a.message,r);break;case"max":aa(t,"maxLength","number"==typeof t.maxLength?Math.min(t.maxLength,a.value):a.value,a.message,r);break;case"email":switch(r.emailStrategy){case"format:email":Sa(t,"email",a.message,r);break;case"format:idn-email":Sa(t,"idn-email",a.message,r);break;case"pattern:zod":$a(t,ha,a.message,r)}break;case"url":Sa(t,"uri",a.message,r);break;case"uuid":Sa(t,"uuid",a.message,r);break;case"regex":$a(t,a.regex,a.message,r);break;case"cuid":$a(t,ua,a.message,r);break;case"cuid2":$a(t,da,a.message,r);break;case"startsWith":$a(t,RegExp(`^${_a(a.value,r)}`),a.message,r);break;case"endsWith":$a(t,RegExp(`${_a(a.value,r)}$`),a.message,r);break;case"datetime":Sa(t,"date-time",a.message,r);break;case"date":Sa(t,"date",a.message,r);break;case"time":Sa(t,"time",a.message,r);break;case"duration":Sa(t,"duration",a.message,r);break;case"length":aa(t,"minLength","number"==typeof t.minLength?Math.max(t.minLength,a.value):a.value,a.message,r),aa(t,"maxLength","number"==typeof t.maxLength?Math.min(t.maxLength,a.value):a.value,a.message,r);break;case"includes":$a(t,RegExp(_a(a.value,r)),a.message,r);break;case"ip":"v6"!==a.version&&Sa(t,"ipv4",a.message,r),"v4"!==a.version&&Sa(t,"ipv6",a.message,r);break;case"base64url":$a(t,ya,a.message,r);break;case"jwt":$a(t,wa,a.message,r);break;case"cidr":"v6"!==a.version&&$a(t,fa,a.message,r),"v4"!==a.version&&$a(t,ga,a.message,r);break;case"emoji":$a(t,ma(),a.message,r);break;case"ulid":$a(t,pa,a.message,r);break;case"base64":switch(r.base64Strategy){case"format:binary":Sa(t,"binary",a.message,r);break;case"contentEncoding:base64":aa(t,"contentEncoding","base64",a.message,r);break;case"pattern:zod":$a(t,va,a.message,r)}break;case"nanoid":$a(t,ba,a.message,r)}return t}function _a(e,r){return"escape"===r.patternStrategy?function(e){let r="";for(let t=0;t<e.length;t++)Ea.has(e[t])||(r+="\\"),r+=e[t];return r}(e):e}const Ea=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Sa(e,r,t,a){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&a.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:r,...t&&a.errorMessages&&{errorMessage:{format:t}}})):aa(e,"format",r,t,a)}function $a(e,r,t,a){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&a.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:xa(r,a),...t&&a.errorMessages&&{errorMessage:{pattern:t}}})):aa(e,"pattern",xa(r,a),t,a)}function xa(e,r){if(!r.applyRegexFlags||!e.flags)return e.source;const t=e.flags.includes("i"),a=e.flags.includes("m"),s=e.flags.includes("s"),o=t?e.source.toLowerCase():e.source;let n="",i=!1,c=!1,l=!1;for(let e=0;e<o.length;e++)if(i)n+=o[e],i=!1;else{if(t)if(c){if(o[e].match(/[a-z]/)){l?(n+=o[e],n+=`${o[e-2]}-${o[e]}`.toUpperCase(),l=!1):"-"===o[e+1]&&o[e+2]?.match(/[a-z]/)?(n+=o[e],l=!0):n+=`${o[e]}${o[e].toUpperCase()}`;continue}}else if(o[e].match(/[a-z]/)){n+=`[${o[e]}${o[e].toUpperCase()}]`;continue}if(a){if("^"===o[e]){n+="(^|(?<=[\r\n]))";continue}if("$"===o[e]){n+="($|(?=[\r\n]))";continue}}s&&"."===o[e]?n+=c?`${o[e]}\r\n`:`[${o[e]}\r\n]`:(n+=o[e],"\\"===o[e]?i=!0:c&&"]"===o[e]?c=!1:c||"["!==o[e]||(c=!0))}try{new RegExp(n)}catch{return e.source}return n}function ka(e,r){if(r.target,"openApi3"===r.target&&e.keyType?._def.typeName===t.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((t,a)=>({...t,[a]:Oa(e.valueType._def,{...r,currentPath:[...r.currentPath,"properties",a]})??oa(r)}),{}),additionalProperties:r.rejectedAdditionalProperties};const a={type:"object",additionalProperties:Oa(e.valueType._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]})??r.allowedAdditionalProperties};if("openApi3"===r.target)return a;if(e.keyType?._def.typeName===t.ZodString&&e.keyType._def.checks?.length){const{type:t,...s}=Pa(e.keyType._def,r);return{...a,propertyNames:s}}if(e.keyType?._def.typeName===t.ZodEnum)return{...a,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===t.ZodBranded&&e.keyType._def.type._def.typeName===t.ZodString&&e.keyType._def.type._def.checks?.length){const{type:t,...s}=na(e.keyType._def,r);return{...a,propertyNames:s}}return a}const Ra={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},ja=(e,r)=>{const t=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,t)=>Oa(e._def,{...r,currentPath:[...r.currentPath,"anyOf",`${t}`]})).filter(e=>!!e&&(!r.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return t.length?{anyOf:t}:void 0};function Ta(e){try{return e.isOptional()}catch{return!0}}const Aa=(e,r,a)=>{switch(r){case t.ZodString:return Pa(e,a);case t.ZodNumber:return function(e,r){const t={type:"number"};if(!e.checks)return t;for(const a of e.checks)switch(a.kind){case"int":t.type="integer",ta(t,"type",a.message,r);break;case"min":"jsonSchema7"===r.target?a.inclusive?aa(t,"minimum",a.value,a.message,r):aa(t,"exclusiveMinimum",a.value,a.message,r):(a.inclusive||(t.exclusiveMinimum=!0),aa(t,"minimum",a.value,a.message,r));break;case"max":"jsonSchema7"===r.target?a.inclusive?aa(t,"maximum",a.value,a.message,r):aa(t,"exclusiveMaximum",a.value,a.message,r):(a.inclusive||(t.exclusiveMaximum=!0),aa(t,"maximum",a.value,a.message,r));break;case"multipleOf":aa(t,"multipleOf",a.value,a.message,r)}return t}(e,a);case t.ZodObject:return function(e,r){const t="openAi"===r.target,a={type:"object",properties:{}},s=[],o=e.shape();for(const e in o){let n=o[e];if(void 0===n||void 0===n._def)continue;let i=Ta(n);i&&t&&("ZodOptional"===n._def.typeName&&(n=n._def.innerType),n.isNullable()||(n=n.nullable()),i=!1);const c=Oa(n._def,{...r,currentPath:[...r.currentPath,"properties",e],propertyPath:[...r.currentPath,"properties",e]});void 0!==c&&(a.properties[e]=c,i||s.push(e))}s.length&&(a.required=s);const n=function(e,r){if("ZodNever"!==e.catchall._def.typeName)return Oa(e.catchall._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return r.allowedAdditionalProperties;case"strict":return r.rejectedAdditionalProperties;case"strip":return"strict"===r.removeAdditionalStrategy?r.allowedAdditionalProperties:r.rejectedAdditionalProperties}}(e,r);return void 0!==n&&(a.additionalProperties=n),a}(e,a);case t.ZodBigInt:return function(e,r){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const a of e.checks)switch(a.kind){case"min":"jsonSchema7"===r.target?a.inclusive?aa(t,"minimum",a.value,a.message,r):aa(t,"exclusiveMinimum",a.value,a.message,r):(a.inclusive||(t.exclusiveMinimum=!0),aa(t,"minimum",a.value,a.message,r));break;case"max":"jsonSchema7"===r.target?a.inclusive?aa(t,"maximum",a.value,a.message,r):aa(t,"exclusiveMaximum",a.value,a.message,r):(a.inclusive||(t.exclusiveMaximum=!0),aa(t,"maximum",a.value,a.message,r));break;case"multipleOf":aa(t,"multipleOf",a.value,a.message,r)}return t}(e,a);case t.ZodBoolean:return{type:"boolean"};case t.ZodDate:return ia(e,a);case t.ZodUndefined:return function(e){return{not:oa(e)}}(a);case t.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(a);case t.ZodArray:return function(e,r){const a={type:"array"};return e.type?._def&&e.type?._def?.typeName!==t.ZodAny&&(a.items=Oa(e.type._def,{...r,currentPath:[...r.currentPath,"items"]})),e.minLength&&aa(a,"minItems",e.minLength.value,e.minLength.message,r),e.maxLength&&aa(a,"maxItems",e.maxLength.value,e.maxLength.message,r),e.exactLength&&(aa(a,"minItems",e.exactLength.value,e.exactLength.message,r),aa(a,"maxItems",e.exactLength.value,e.exactLength.message,r)),a}(e,a);case t.ZodUnion:case t.ZodDiscriminatedUnion:return function(e,r){if("openApi3"===r.target)return ja(e,r);const t=e.options instanceof Map?Array.from(e.options.values()):e.options;if(t.every(e=>e._def.typeName in Ra&&(!e._def.checks||!e._def.checks.length))){const e=t.reduce((e,r)=>{const t=Ra[r._def.typeName];return t&&!e.includes(t)?[...e,t]:e},[]);return{type:e.length>1?e:e[0]}}if(t.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){const e=t.reduce((e,r)=>{const t=typeof r._def.value;switch(t){case"string":case"number":case"boolean":return[...e,t];case"bigint":return[...e,"integer"];case"object":if(null===r._def.value)return[...e,"null"];default:return e}},[]);if(e.length===t.length){const r=e.filter((e,r,t)=>t.indexOf(e)===r);return{type:r.length>1?r:r[0],enum:t.reduce((e,r)=>e.includes(r._def.value)?e:[...e,r._def.value],[])}}}else if(t.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:t.reduce((e,r)=>[...e,...r._def.values.filter(r=>!e.includes(r))],[])};return ja(e,r)}(e,a);case t.ZodIntersection:return function(e,r){const t=[Oa(e.left._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),Oa(e.right._def,{...r,currentPath:[...r.currentPath,"allOf","1"]})].filter(e=>!!e);let a="jsonSchema2019-09"===r.target?{unevaluatedProperties:!1}:void 0;const s=[];return t.forEach(e=>{if("type"in(r=e)&&"string"===r.type||!("allOf"in r)){let r=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:t,...a}=e;r=a}else a=void 0;s.push(r)}else s.push(...e.allOf),void 0===e.unevaluatedProperties&&(a=void 0);var r}),s.length?{allOf:s,...a}:void 0}(e,a);case t.ZodTuple:return function(e,r){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,t)=>Oa(e._def,{...r,currentPath:[...r.currentPath,"items",`${t}`]})).reduce((e,r)=>void 0===r?e:[...e,r],[]),additionalItems:Oa(e.rest._def,{...r,currentPath:[...r.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,t)=>Oa(e._def,{...r,currentPath:[...r.currentPath,"items",`${t}`]})).reduce((e,r)=>void 0===r?e:[...e,r],[])}}(e,a);case t.ZodRecord:return ka(e,a);case t.ZodLiteral:return function(e,r){const t=typeof e.value;return"bigint"!==t&&"number"!==t&&"boolean"!==t&&"string"!==t?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===r.target?{type:"bigint"===t?"integer":t,enum:[e.value]}:{type:"bigint"===t?"integer":t,const:e.value}}(e,a);case t.ZodEnum:return function(e){return{type:"string",enum:Array.from(e.values)}}(e);case t.ZodNativeEnum:return function(e){const r=e.values,t=Object.keys(e.values).filter(e=>"number"!=typeof r[r[e]]).map(e=>r[e]),a=Array.from(new Set(t.map(e=>typeof e)));return{type:1===a.length?"string"===a[0]?"string":"number":["string","number"],enum:t}}(e);case t.ZodNullable:return function(e,r){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===r.target?{type:Ra[e.innerType._def.typeName],nullable:!0}:{type:[Ra[e.innerType._def.typeName],"null"]};if("openApi3"===r.target){const t=Oa(e.innerType._def,{...r,currentPath:[...r.currentPath]});return t&&"$ref"in t?{allOf:[t],nullable:!0}:t&&{...t,nullable:!0}}const t=Oa(e.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}(e,a);case t.ZodOptional:return((e,r)=>{if(r.currentPath.toString()===r.propertyPath?.toString())return Oa(e.innerType._def,r);const t=Oa(e.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","1"]});return t?{anyOf:[{not:oa(r)},t]}:oa(r)})(e,a);case t.ZodMap:return function(e,r){return"record"===r.mapStrategy?ka(e,r):{type:"array",maxItems:125,items:{type:"array",items:[Oa(e.keyType._def,{...r,currentPath:[...r.currentPath,"items","items","0"]})||oa(r),Oa(e.valueType._def,{...r,currentPath:[...r.currentPath,"items","items","1"]})||oa(r)],minItems:2,maxItems:2}}}(e,a);case t.ZodSet:return function(e,r){const t={type:"array",uniqueItems:!0,items:Oa(e.valueType._def,{...r,currentPath:[...r.currentPath,"items"]})};return e.minSize&&aa(t,"minItems",e.minSize.value,e.minSize.message,r),e.maxSize&&aa(t,"maxItems",e.maxSize.value,e.maxSize.message,r),t}(e,a);case t.ZodLazy:return()=>e.getter()._def;case t.ZodPromise:return function(e,r){return Oa(e.type._def,r)}(e,a);case t.ZodNaN:case t.ZodNever:return function(e){return"openAi"===e.target?void 0:{not:oa({...e,currentPath:[...e.currentPath,"not"]})}}(a);case t.ZodEffects:return function(e,r){return"input"===r.effectStrategy?Oa(e.schema._def,r):oa(r)}(e,a);case t.ZodAny:return oa(a);case t.ZodUnknown:return function(e){return oa(e)}(a);case t.ZodDefault:return function(e,r){return{...Oa(e.innerType._def,r),default:e.defaultValue()}}(e,a);case t.ZodBranded:return na(e,a);case t.ZodReadonly:case t.ZodCatch:return((e,r)=>Oa(e.innerType._def,r))(e,a);case t.ZodPipeline:return((e,r)=>{if("input"===r.pipeStrategy)return Oa(e.in._def,r);if("output"===r.pipeStrategy)return Oa(e.out._def,r);const t=Oa(e.in._def,{...r,currentPath:[...r.currentPath,"allOf","0"]});return{allOf:[t,Oa(e.out._def,{...r,currentPath:[...r.currentPath,"allOf",t?"1":"0"]})].filter(e=>void 0!==e)}})(e,a);case t.ZodFunction:case t.ZodVoid:case t.ZodSymbol:default:return}};function Oa(e,r,t=!1){const a=r.seen.get(e);if(r.override){const s=r.override?.(e,r,a,t);if(s!==ea)return s}if(a&&!t){const e=Fa(a,r);if(void 0!==e)return e}const s={def:e,path:r.currentPath,jsonSchema:void 0};r.seen.set(e,s);const o=Aa(e,e.typeName,r),n="function"==typeof o?Oa(o(),r):o;if(n&&Ca(e,r,n),r.postProcess){const t=r.postProcess(n,e,r);return s.jsonSchema=n,t}return s.jsonSchema=n,n}const Fa=(e,r)=>{switch(r.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:sa(r.currentPath,e.path)};case"none":case"seen":return e.path.length<r.currentPath.length&&e.path.every((e,t)=>r.currentPath[t]===e)||"seen"===r.$refStrategy?oa(r):void 0}},Ca=(e,r,t)=>(e.description&&(t.description=e.description,r.markdownDescription&&(t.markdownDescription=e.description)),t),Ia=(e,r)=>{const t=(e=>{const r=(e=>"string"==typeof e?{...ra,name:e}:{...ra,...e})(e),t=void 0!==r.name?[...r.basePath,r.definitionPath,r.name]:r.basePath;return{...r,flags:{hasReferencedOpenAiAnyType:!1},currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(r.definitions).map(([e,t])=>[t._def,{def:t._def,path:[...r.basePath,r.definitionPath,e],jsonSchema:void 0}]))}})(r);let a="object"==typeof r&&r.definitions?Object.entries(r.definitions).reduce((e,[r,a])=>({...e,[r]:Oa(a._def,{...t,currentPath:[...t.basePath,t.definitionPath,r]},!0)??oa(t)}),{}):void 0;const s="string"==typeof r?r:"title"===r?.nameStrategy?void 0:r?.name,o=Oa(e._def,void 0===s?t:{...t,currentPath:[...t.basePath,t.definitionPath,s]},!1)??oa(t),n="object"==typeof r&&void 0!==r.name&&"title"===r.nameStrategy?r.name:void 0;void 0!==n&&(o.title=n),t.flags.hasReferencedOpenAiAnyType&&(a||(a={}),a[t.openAiAnyTypeName]||(a[t.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===t.$refStrategy?"1":[...t.basePath,t.definitionPath,t.openAiAnyTypeName].join("/")}}));const i=void 0===s?a?{...o,[t.definitionPath]:a}:o:{$ref:[..."relative"===t.$refStrategy?[]:t.basePath,t.definitionPath,s].join("/"),[t.definitionPath]:{...a,[s]:o}};return"jsonSchema7"===t.target?i.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==t.target&&"openAi"!==t.target||(i.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===t.target&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type)),i};var qa;!function(e){e.Completable="McpCompletable"}(qa||(qa={}));class Na extends a{_parse(e){const{ctx:r}=this._processInputParams(e),t=r.data;return this._def.type._parse({data:t,path:r.path,parent:r})}unwrap(){return this._def.type}}function Da(e){if(!e)return{};const{errorMap:r,invalid_type_error:t,required_error:a,description:s}=e;if(r&&(t||a))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return r?{errorMap:r,description:s}:{errorMap:(r,s)=>{var o,n;const{message:i}=e;return"invalid_enum_value"===r.code?{message:null!=i?i:s.defaultError}:void 0===s.data?{message:null!==(o=null!=i?i:a)&&void 0!==o?o:s.defaultError}:"invalid_type"!==r.code?{message:s.defaultError}:{message:null!==(n=null!=i?i:t)&&void 0!==n?n:s.defaultError}},description:s}}Na.create=(e,r)=>new Na({type:e,typeName:qa.Completable,complete:r.complete,...Da(r)});class Ha{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Xt(e,r)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(_e.shape.method.value),this.server.assertCanSetRequestHandler($e.shape.method.value),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(_e,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{const t={name:e,title:r.title,description:r.description,inputSchema:r.inputSchema?Ia(r.inputSchema,{strictUnions:!0}):La,annotations:r.annotations};return r.outputSchema&&(t.outputSchema=Ia(r.outputSchema,{strictUnions:!0})),t})})),this.server.setRequestHandler($e,async(e,r)=>{const t=this._registeredTools[e.params.name];if(!t)throw new Ke(R.InvalidParams,`Tool ${e.params.name} not found`);if(!t.enabled)throw new Ke(R.InvalidParams,`Tool ${e.params.name} disabled`);let a;if(t.inputSchema){const s=await t.inputSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new Ke(R.InvalidParams,`Invalid arguments for tool ${e.params.name}: ${s.error.message}`);const o=s.data,n=t.callback;try{a=await Promise.resolve(n(o,r))}catch(e){a={content:[{type:"text",text:e instanceof Error?e.message:String(e)}],isError:!0}}}else{const e=t.callback;try{a=await Promise.resolve(e(r))}catch(e){a={content:[{type:"text",text:e instanceof Error?e.message:String(e)}],isError:!0}}}if(t.outputSchema&&!a.isError){if(!a.structuredContent)throw new Ke(R.InvalidParams,`Tool ${e.params.name} has an output schema but no structured content was provided`);const r=await t.outputSchema.safeParseAsync(a.structuredContent);if(!r.success)throw new Ke(R.InvalidParams,`Invalid structured content for tool ${e.params.name}: ${r.error.message}`)}return a}),this._toolHandlersInitialized=!0)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Qe.shape.method.value),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Qe,async e=>{switch(e.params.ref.type){case"ref/prompt":return this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return this.handleResourceCompletion(e,e.params.ref);default:throw new Ke(R.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){const t=this._registeredPrompts[r.name];if(!t)throw new Ke(R.InvalidParams,`Prompt ${r.name} not found`);if(!t.enabled)throw new Ke(R.InvalidParams,`Prompt ${r.name} disabled`);if(!t.argsSchema)return Qa;const a=t.argsSchema.shape[e.params.argument.name];if(!(a instanceof Na))return Qa;const s=a._def;return Ma(await s.complete(e.params.argument.value,e.params.context))}async handleResourceCompletion(e,r){const t=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===r.uri);if(!t){if(this._registeredResources[r.uri])return Qa;throw new Ke(R.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const a=t.resourceTemplate.completeCallback(e.params.argument.name);return a?Ma(await a(e.params.argument.value,e.params.context)):Qa}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(K.shape.method.value),this.server.assertCanSetRequestHandler(Y.shape.method.value),this.server.assertCanSetRequestHandler(ee.shape.method.value),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(K,async(e,r)=>{const t=Object.entries(this._registeredResources).filter(([e,r])=>r.enabled).map(([e,r])=>({uri:e,name:r.name,...r.metadata})),a=[];for(const e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;const t=await e.resourceTemplate.listCallback(r);for(const r of t.resources)a.push({...e.metadata,...r})}return{resources:[...t,...a]}}),this.server.setRequestHandler(Y,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,r])=>({name:e,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(ee,async(e,r)=>{const t=new URL(e.params.uri),a=this._registeredResources[t.toString()];if(a){if(!a.enabled)throw new Ke(R.InvalidParams,`Resource ${t} disabled`);return a.readCallback(t,r)}for(const e of Object.values(this._registeredResourceTemplates)){const a=e.resourceTemplate.uriTemplate.match(t.toString());if(a)return e.readCallback(t,a,r)}throw new Ke(R.InvalidParams,`Resource ${t} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(ce.shape.method.value),this.server.assertCanSetRequestHandler(ue.shape.method.value),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ce,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>{return{name:e,title:r.title,description:r.description,arguments:r.argsSchema?(t=r.argsSchema,Object.entries(t.shape).map(([e,r])=>({name:e,description:r.description,required:!r.isOptional()}))):void 0};var t})})),this.server.setRequestHandler(ue,async(e,r)=>{const t=this._registeredPrompts[e.params.name];if(!t)throw new Ke(R.InvalidParams,`Prompt ${e.params.name} not found`);if(!t.enabled)throw new Ke(R.InvalidParams,`Prompt ${e.params.name} disabled`);if(t.argsSchema){const a=await t.argsSchema.safeParseAsync(e.params.arguments);if(!a.success)throw new Ke(R.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${a.error.message}`);const s=a.data,o=t.callback;return await Promise.resolve(o(s,r))}{const e=t.callback;return await Promise.resolve(e(r))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(e,r,...t){let a;"object"==typeof t[0]&&(a=t.shift());const s=t[0];if("string"==typeof r){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const t=this._createRegisteredResource(e,void 0,r,a,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),t}{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const t=this._createRegisteredResourceTemplate(e,void 0,r,a,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),t}}registerResource(e,r,t,a){if("string"==typeof r){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const s=this._createRegisteredResource(e,t.title,r,t,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const s=this._createRegisteredResourceTemplate(e,t.title,r,t,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,t,a,s){const o={name:e,title:r,metadata:a,readCallback:s,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({uri:null}),update:e=>{void 0!==e.uri&&e.uri!==t&&(delete this._registeredResources[t],e.uri&&(this._registeredResources[e.uri]=o)),void 0!==e.name&&(o.name=e.name),void 0!==e.title&&(o.title=e.title),void 0!==e.metadata&&(o.metadata=e.metadata),void 0!==e.callback&&(o.readCallback=e.callback),void 0!==e.enabled&&(o.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[t]=o,o}_createRegisteredResourceTemplate(e,r,t,a,s){const o={resourceTemplate:t,title:r,metadata:a,readCallback:s,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:r=>{void 0!==r.name&&r.name!==e&&(delete this._registeredResourceTemplates[e],r.name&&(this._registeredResourceTemplates[r.name]=o)),void 0!==r.title&&(o.title=r.title),void 0!==r.template&&(o.resourceTemplate=r.template),void 0!==r.metadata&&(o.metadata=r.metadata),void 0!==r.callback&&(o.readCallback=r.callback),void 0!==r.enabled&&(o.enabled=r.enabled),this.sendResourceListChanged()}};return this._registeredResourceTemplates[e]=o,o}_createRegisteredPrompt(e,t,a,s,o){const n={title:t,description:a,argsSchema:void 0===s?void 0:r.object(s),callback:o,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=n)),void 0!==t.title&&(n.title=t.title),void 0!==t.description&&(n.description=t.description),void 0!==t.argsSchema&&(n.argsSchema=r.object(t.argsSchema)),void 0!==t.callback&&(n.callback=t.callback),void 0!==t.enabled&&(n.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=n,n}_createRegisteredTool(e,t,a,s,o,n,i){const c={title:t,description:a,inputSchema:void 0===s?void 0:r.object(s),outputSchema:void 0===o?void 0:r.object(o),annotations:n,callback:i,enabled:!0,disable:()=>c.update({enabled:!1}),enable:()=>c.update({enabled:!0}),remove:()=>c.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=c)),void 0!==t.title&&(c.title=t.title),void 0!==t.description&&(c.description=t.description),void 0!==t.paramsSchema&&(c.inputSchema=r.object(t.paramsSchema)),void 0!==t.callback&&(c.callback=t.callback),void 0!==t.annotations&&(c.annotations=t.annotations),void 0!==t.enabled&&(c.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=c,this.setToolRequestHandlers(),this.sendToolListChanged(),c}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let t,a,s;if("string"==typeof r[0]&&(t=r.shift()),r.length>1){const e=r[0];Ua(e)?(a=r.shift(),r.length>1&&"object"==typeof r[0]&&null!==r[0]&&!Ua(r[0])&&(s=r.shift())):"object"==typeof e&&null!==e&&(s=r.shift())}const o=r[0];return this._createRegisteredTool(e,void 0,t,a,void 0,s,o)}registerTool(e,r,t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);const{title:a,description:s,inputSchema:o,outputSchema:n,annotations:i}=r;return this._createRegisteredTool(e,a,s,o,n,i,t)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let t,a;"string"==typeof r[0]&&(t=r.shift()),r.length>1&&(a=r.shift());const s=r[0],o=this._createRegisteredPrompt(e,void 0,t,a,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}registerPrompt(e,r,t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);const{title:a,description:s,argsSchema:o}=r,n=this._createRegisteredPrompt(e,a,s,o,t);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),n}isConnected(){return void 0!==this.server.transport}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}const La={type:"object",properties:{}};function Ua(e){return"object"==typeof e&&null!==e&&(0===Object.keys(e).length||Object.values(e).some(za))}function za(e){return null!==e&&"object"==typeof e&&"parse"in e&&"function"==typeof e.parse&&"safeParse"in e&&"function"==typeof e.safeParse}function Ma(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const Qa={completion:{values:[],hasMore:!1}};class Va{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf("\n");if(-1===e)return null;const r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),function(e){return T.parse(JSON.parse(e))}(r)}clear(){this._buffer=void 0}}class Za{constructor(e=s.stdin,r=s.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Va,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{var r;null===(r=this.onerror)||void 0===r||r.call(this,e)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(var e,r;;)try{const r=this._readBuffer.readMessage();if(null===r)break;null===(e=this.onmessage)||void 0===e||e.call(this,r)}catch(e){null===(r=this.onerror)||void 0===r||r.call(this,e)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),0===this._stdin.listenerCount("data")&&this._stdin.pause(),this._readBuffer.clear(),null===(e=this.onclose)||void 0===e||e.call(this)}send(e){return new Promise(r=>{const t=function(e){return JSON.stringify(e)+"\n"}(e);this._stdout.write(t)?r():this._stdout.once("drain",r)})}}const Ba=new o({stdTTL:86400,checkperiod:3600,maxKeys:1e3,deleteOnExpire:!0});function Ga(e,r){const t=JSON.stringify(r,Object.keys(r).sort());return`v1-${e}:${n.createHash("md5").update(t).digest("hex")}`}async function Ja(e,r){const t=Ba.get(e);if(t)return t;const a=await r();return a.isError||Ba.set(e,a),a}const Ka=c(i),Wa=["view","search","ping","config","whoami"],Ya=["search","api","auth","org","pr","repo"];function Xa(e,r){return{content:[{type:"text",text:`${e}: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}function es(e){if("win32"!==l()){const e=process.env.SHELL||"/bin/sh";return{shell:e,shellEnv:e,type:"unix"}}return"powershell"===e?{shell:"powershell.exe",shellEnv:"powershell.exe",type:"powershell"}:{shell:"cmd.exe",shellEnv:"cmd.exe",type:"cmd"}}function rs(e,r){switch(r||(r="win32"===l()?"cmd":"unix"),r){case"powershell":return function(e){return/[\s&<>|;`$@"'()[\]{}]/.test(e)?`'${e.replace(/'/g,"''")}'`:e}(e);case"cmd":return function(e){return/[\s&<>|^"]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}(e);default:return function(e){return/[;&|<>$`\\*?()[\]{}^~\s]/.test(e)?`'${e.replace(/'/g,"'\"'\"'")}'`:e}(e)}}async function ts(e,r=[],t={}){if(!function(e){return Wa.includes(e)}(e))return Xa("Command not registered",new Error(`NPM command '${e}' is not in the allowed list`));const a=es(t.windowsShell),s=`npm ${e} ${r.map(e=>rs(e,a.type)).join(" ")}`,o=()=>ss(s,"npm",t,a);return t.cache?Ja(Ga("npm-exec",{command:e,args:r,shell:a.type}),o):o()}async function as(e,r=[],t={}){if(!function(e){return Ya.includes(e)}(e))return Xa("Command not registered",new Error(`GitHub command '${e}' is not in the allowed list`));const a=es(t.windowsShell),s=`gh ${e} ${r.map(e=>rs(e,a.type)).join(" ")}`,o=()=>ss(s,"github",t,a);return t.cache?Ja(Ga("gh-exec",{command:e,args:r,shell:a.type}),o):o()}async function ss(e,r,t={},a){try{const s="npm"===r?3e4:6e4,o=a||es(t.windowsShell),n={timeout:t.timeout||s,maxBuffer:5242880,cwd:t.cwd,env:{...process.env,...t.env},encoding:"utf-8",shell:o.shell},{stdout:i,stderr:c}=await Ka(e,n);if("npm"===r?c&&!c.includes("npm WARN")&&!c.includes("npm notice"):c&&!c.includes("Warning:")&&!c.includes("notice:")&&""!==c.trim())return Xa("npm"===r?"NPM command error":"GitHub CLI command error",new Error(c));let u=i;try{u=JSON.parse(i)}catch{}return function(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],isError:!1}}({command:e,result:u,timestamp:(new Date).toISOString(),type:r,platform:l(),shell:o.shell,shellType:o.type,...c&&{warning:c}})}catch(e){return Xa("npm"===r?"Failed to execute NPM command":"Failed to execute GitHub CLI command",e)}}function os(e){const{data:r,error:t}=e;if(t)return{content:[{type:"text",text:"string"==typeof t?t:t.message||"Unknown error"}],isError:!0};try{return{content:[{type:"text",text:JSON.stringify(r,null,2)}],isError:!1}}catch(e){return{content:[{type:"text",text:`JSON serialization failed: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}}function ns(e){const r=new Date(e);return`${r.getDate().toString().padStart(2,"0")}/${(r.getMonth()+1).toString().padStart(2,"0")}/${r.getFullYear()}`}function is(e){const r=e.match(/github\.com\/([^/]+\/[^/]+)/);return r?r[1]:e}function cs(e){if(0===e)return"0 B";const r=Math.floor(Math.log(e)/Math.log(1024));return`${Math.round(e/Math.pow(1024,r))} ${["B","KB","MB","GB"][r]}`}function ls(e){const r=e.match(/github\.com\/[^/]+\/[^/]+\/(?:blob|commit)\/[^/]+\/(.+)$/);return r?r[1]:e}function us(e,r=100){const t=e.replace(/\s+/g," ").trim();if(t.length<=r)return t;const a=t.substring(0,r),s=a.lastIndexOf(" ");return s>.7*r?a.substring(0,s)+"…":a+"…"}const ds="Rate limit exceeded - use specific filters (owner, language) or wait",ps="Package search failed - try different keywords",hs="Query too long (max 256 chars) - simplify search terms",ms="Query required - provide search keywords",fs="No results found. Try this progression:\n1. Remove ALL filters and search with just one keyword\n2. Break into several queries with minimal query and filters\n3. Use api_status_check to verify access to private repos",gs="Start with simple keywords, then refine based on results",vs="Begin with basic terms, analyze results, then add filters",ys='Discovery strategies:\n• Functional search: "validation", "testing", "charts"\n• Ecosystem search: "react", "typescript", "node"\n• Use github_search_repositories for related projects',bs="Try these alternatives:\n• Try with dashes instead of underscores\n• Try without dashes\n• Try scoped package format\n• Use npm_package_search for discovery";function ws(e){const{baseError:r,suggestion:t}=e,a=Array.isArray(r)?r:[r],s=Array.isArray(t)?t:t?[t]:[];let o=a.join("\n");return s.length>0&&(o+="\n\nSuggestion: "+s.join("\n")),o}function Ps(e=!0){return e?ds:"Rate limit exceeded - wait or add filters"}function _s(e="code"){switch(e){case"repositories":return"No repositories found - try simpler query or different filters";case"commits":return"No commits found - try simpler query or different filters";case"issues":return"No issues found - try simpler query or different filters";case"pull_requests":return"No pull requests found - try simpler query or different filters";case"packages":return"No packages found";default:return"No results found - try simpler query or different filters"}}function Es(e="code"){switch(e){case"repositories":return"Repository search failed - check connection or query";case"commits":return"Commit search failed";case"issues":return"Issue search failed - check auth or simplify query";case"pull_requests":return"PR search failed - check access and query syntax";case"packages":return ps;default:return"Search failed - check connection or simplify query"}}function Ss(e){const r=[];return e.includes("_")&&r.push(`• Try with dashes: "${e.replace(/_/g,"-")}"`),e.includes("-")&&r.push(`• Try without dashes: "${e.replace(/-/g,"")}"`),!e.includes("/")&&e.length>2&&r.push(`• Try scoped format: "@${e.slice(0,3)}/${e}"`),`Package not found on NPM registry: "${e}"\n\n${r.length>0?r.join("\n")+"\n\n":""}${bs}\n\n${ys}`}const $s="api_status_check",xs="github_fetch_content",ks="github_search_code",Rs="github_search_commits",js="github_search_issues",Ts="github_search_pull_requests",As="github_search_repositories",Os="github_view_repo_structure",Fs="npm_package_search",Cs="npm_view_package",Is={[Fs]:{fallbackTools:[{tool:As,reason:"to find repositories by topic or language"},{tool:ks,reason:"to search for package usage examples"}],nextSteps:[{tool:Cs,reason:"to get detailed package information and repository URL"},{tool:Os,reason:"to explore the package source code structure"}]},[Cs]:{fallbackTools:[{tool:Fs,reason:"to discover similar packages"},{tool:As,reason:"to find the repository directly"}],nextSteps:[{tool:Os,reason:"to explore repository structure"},{tool:xs,reason:"to read specific files like README or package.json"},{tool:ks,reason:"to find usage examples"}]},[As]:{fallbackTools:[{tool:Fs,reason:"if searching for packages or libraries"},{tool:ks,reason:"to search within repository contents"}],nextSteps:[{tool:Os,reason:"to explore repository contents"},{tool:js,reason:"to check open issues and discussions"},{tool:Cs,reason:"if repository is an NPM package"}]},[ks]:{fallbackTools:[{tool:Fs,reason:"if searching for package implementations"},{tool:As,reason:"to find repositories by topic"},{tool:$s,reason:"if no results (might be private repos)",condition:"no_results"}],nextSteps:[{tool:xs,reason:"to view full file contents"},{tool:Os,reason:"to explore repository structure"}],prerequisites:[{tool:Os,reason:"to verify file paths before searching"}]},[xs]:{fallbackTools:[{tool:Os,reason:"to verify correct file path"},{tool:ks,reason:"to search for similar files"}],nextSteps:[{tool:Os,reason:"to explore related files"},{tool:ks,reason:"to find usage examples"}],prerequisites:[{tool:Os,reason:"to verify file exists and get correct path"}]},[Os]:{fallbackTools:[{tool:As,reason:"to find the correct repository"},{tool:$s,reason:"if access denied (check authentication)",condition:"access_denied"}],nextSteps:[{tool:xs,reason:"to read specific files"},{tool:ks,reason:"to search within the repository"}]},[Rs]:{fallbackTools:[{tool:As,reason:"to find repositories first"},{tool:js,reason:"to find related discussions"}],nextSteps:[{tool:xs,reason:"to view files from specific commits using returned commit SHAs as branch parameter"},{tool:ks,reason:"to find current implementation"}]},[js]:{fallbackTools:[{tool:Ts,reason:"to find related PRs"},{tool:As,reason:"to find the repository first"}],nextSteps:[{tool:Ts,reason:"to find solutions or implementations"},{tool:ks,reason:"to find related code"}]},[Ts]:{fallbackTools:[{tool:js,reason:"to find related issues"},{tool:Rs,reason:"to find specific commit SHAs from PR for file viewing"}],nextSteps:[{tool:xs,reason:"to view PR files using head/base branch names or commit SHAs"},{tool:ks,reason:"to find current implementation"}]},[$s]:{fallbackTools:[],nextSteps:[{tool:As,reason:"to search accessible repositories"},{tool:Fs,reason:"to search public packages"}]}};function qs(e,r){const t=Is[e];return t?{fallback:t.fallbackTools.filter(e=>{if(!e.condition)return!0;switch(e.condition){case"no_results":return"no_results"===r.errorType;case"access_denied":return"access_denied"===r.errorType;default:return!0}}),nextSteps:r.hasResults?t.nextSteps:[],prerequisites:t.prerequisites||[]}:{fallback:[],nextSteps:[],prerequisites:[]}}function Ns(e,r){return 0===r.length?"":`\n\nCurrent tool: ${e}\nAlternative tools:\n${r.map(({tool:e,reason:r})=>`• Use ${e} ${r}`).join("\n")}`}const Ds="apiStatusCheck";function Hs(e){if(!e.isError&&e.content?.[0]?.text)try{const r=e.content[0].text;if("string"==typeof r){const e=JSON.parse(r);return"object"==typeof e&&null!==e?e:null}}catch(e){return null}return null}function Ls(e){e.registerTool(Ds,{description:"Check user status: GitHub/NPM connections, organizations, and current timestamp. Essential for understanding user's data access and API capabilities.",inputSchema:{},annotations:{title:"Check API Connections and Github Organizations",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async()=>{try{let e=!1,r=[],t=!1,a="";try{const t=await as("auth",["status"]);if(!t.isError){const a=Hs(t);if("string"==typeof a?.result&&(a.result.includes("Logged in")||a.result.includes("github.com"))){e=!0;try{const e=Hs(await as("org",["list","--limit=50"],{cache:!1})),t="string"==typeof e?.result?e.result:"";"string"==typeof t&&(r=t.split("\n").map(e=>e.trim()).filter(e=>e.length>0))}catch(e){}}}}catch(r){if(r instanceof Error&&(r.message.includes("JSON parsing failed")||r.message.includes("Unexpected error")||r.stack?.includes("mockImplementationOnce")))throw r;e=!1}try{if(!(await ts("whoami",[],{timeout:5e3})).isError){t=!0;const e=Hs(await ts("config",["get","registry"],{timeout:3e3}));a="string"==typeof e?.result?e.result.trim():"https://registry.npmjs.org/"}}catch(e){if(e instanceof Error&&(e.message.includes("Unexpected error")||e.stack?.includes("mockImplementationOnce")))throw e;t=!1}const{nextSteps:s}=qs($s,{hasResults:!0}),o=["Use user organizations to search private repositories when requested - verify access by checking query and repository structure"];return s.length>0&&(o.push("Next steps:"),s.forEach(({tool:e,reason:r})=>{o.push(`- ${e}: ${r}`)})),os({data:{timestamp:(new Date).toISOString(),login:{github:{connected:e,user_organizations:r},npm:{connected:t,registry:a||"https://registry.npmjs.org/"},hints:o}}})}catch(e){const{nextSteps:r}=qs($s,{}),t=Ns($s,r);return os({error:ws({baseError:["API Status Check Failed",`Error: ${e instanceof Error?e.message:"Unknown error"}`,"","This usually indicates a system configuration issue. Please verify GitHub CLI and NPM are properly installed."],suggestion:t})})}})}const Us="githubSearchCode";function zs(r){r.registerTool(Us,{description:"Search code across GitHub repositories using GitHub CLI.\n\nChoose one search method:\n- exactQuery: exact phrase matching\n- queryTerms: array of terms (space-separated, AND logic)\n\nUse filters to narrow results after initial broad searches.",inputSchema:{exactQuery:e.string().optional().describe("Exact phrase/word to search for"),queryTerms:e.array(e.string()).optional().describe("Array of search terms joined with spaces (AND logic)"),language:e.string().optional().describe("Programming language filter. Narrows search to specific language files."),owner:e.union([e.string(),e.array(e.string())]).optional().describe("Repository owner/organization name(s). Organization-wide search."),repo:e.union([e.string(),e.array(e.string())]).optional().describe("Repository filter. Use with owner or full format."),filename:e.string().optional().describe("Target specific filename or pattern."),extension:e.string().optional().describe("File extension filter. Alternative to language parameter."),match:e.enum(["file","path"]).optional().describe("Search scope: file for file content (default), path for filenames/paths."),size:e.string().regex(/^(>=?\d+|<=?\d+|\d+\.\.\d+|\d+)$/,'Invalid size format. Use: ">N", ">=N", "<N", "<=N", "N..M", or exact number').optional().describe('File size filter in KB. Format: ">N" (larger), "<N" (smaller), "N..M" (range).'),limit:e.number().int().min(1).max(100).optional().default(30).describe("Maximum number of results to return (1-100).")},annotations:{title:"GitHub Code Search - Smart & Efficient",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0}},async e=>{const r=!!e.exactQuery,t=e.queryTerms&&e.queryTerms.length>0;if(!r&&!t)return os({error:"One search parameter required: exactQuery OR queryTerms"});if(r&&t)return os({error:"Use either exactQuery OR queryTerms, not both. Choose one search approach."});try{const r=await async function(e){return Ja(Ga("gh-code",e),async()=>{try{const r=function(e){const r=["code"];if(e.exactQuery)r.push(e.exactQuery);else if(e.queryTerms&&e.queryTerms.length>0){const t=e.queryTerms.join(" ");r.push(t)}e.language&&r.push(`--language=${e.language}`),e.repo?(Array.isArray(e.repo)?e.repo:[e.repo]).forEach(t=>{e.owner&&!t.includes("/")?(Array.isArray(e.owner)?e.owner:[e.owner]).forEach(e=>r.push(`--repo=${e}/${t}`)):r.push(`--repo=${t}`)}):e.owner&&(Array.isArray(e.owner)?e.owner:[e.owner]).forEach(e=>r.push(`--owner=${e}`)),e.filename&&r.push(`--filename=${e.filename}`),e.extension&&r.push(`--extension=${e.extension}`),e.size&&r.push(`--size=${e.size}`),e.match&&r.push(`--match=${e.match}`);const t=e.limit||30;return r.push(`--limit=${t}`),r.push("--json=repository,path,textMatches,sha,url"),r}(e);return await as("search",r,{cache:!1})}catch(e){return Ms(e.message||"")}})}(e);if(r.isError)return r;const t=JSON.parse(r.content[0].text).result,a=Array.isArray(t)?t:[];if(0===a.length){let r=fs;return(e.language||e.owner||e.filename||e.extension)&&(r=fs),os({error:ws({baseError:_s("code"),suggestion:r})})}const s=function(e){const r=function(e){if(0===e.length)return null;const r=e[0].repository;return e.every(e=>e.repository.nameWithOwner===r.nameWithOwner)?r:null}(e),t={items:e.map(e=>({path:e.path,matches:e.textMatches?.map(e=>({context:us(e.fragment,120),positions:e.matches?.map(e=>Array.isArray(e.indices)&&e.indices.length>=2?[e.indices[0],e.indices[1]]:[0,0])||[]}))||[],url:r?e.path:ls(e.url),repository:{nameWithOwner:e.repository.nameWithOwner,url:e.repository.url}})),total_count:e.length};return r&&(t.repository={name:r.nameWithOwner,url:is(r.url)}),t}(a);return os({data:s})}catch(e){return Ms(e.message||"")}})}function Ms(e){return e.includes("rate limit")||e.includes("403")?os({error:"GitHub API rate limit reached. Try again in 5-10 minutes, or use these strategies:\n• Search fewer terms per query\n• Use owner/repo filters to narrow scope\n• Try npm package search for package-related queries\n• Use separate searches instead of complex queries"}):e.includes("authentication")||e.includes("401")?os({error:"GitHub authentication required. Fix with:\n1. Run: gh auth login\n2. Verify access: gh auth status\n3. For private repos: use api_status_check to verify org access"}):e.includes("timed out")||e.includes("network")?os({error:"Network timeout. Try these alternatives:\n• Reduce search scope with owner or language filters\n• Use github_search_repos to find repositories first\n• Try npm package search for package discovery\n• Check network connection and retry"}):e.includes("validation failed")||e.includes("Invalid query")?os({error:'Invalid search query. Common fixes:\n• Remove special characters: ()[]{}*?^$|.\\\n• Use quotes only for exact phrases: "error handling"\n• Avoid escaped quotes: use term instead of "term"\n• Try broader terms: "react" instead of "React.Component"'}):e.includes("repository not found")||e.includes("owner not found")?os({error:"Repository/owner not found. Discovery strategies:\n• Use github_search_repos to find correct names\n• Check for typos in owner/repo names\n• Try without owner filter for broader search\n• Use npm package search if looking for packages"}):e.includes("JSON")?os({error:"GitHub CLI response parsing failed. System issue - try:\n• Update GitHub CLI: gh extension upgrade\n• Retry in a few moments\n• Use github_search_repos as alternative\n• Check gh auth status for authentication"}):os({error:`Code search failed: ${e}\n\nProgressive recovery strategy:\n1. Try broader search terms\n2. Use github_search_repos to find repositories\n3. Use npm package search for package-related queries\n4. Check github CLI status: gh auth status`})}function Qs(e){const r=e.split(".").pop()?.toLowerCase(),t=e.split("/").pop()?.toLowerCase();if("dockerfile"===t||"makefile"===t||"jenkinsfile"===t)return t;if("build"===t||"build.bazel"===t)return"starlark";if("cmakelists.txt"===t)return"cmake";switch(r){case"html":case"htm":return"html";case"css":return"css";case"less":return"less";case"scss":return"scss";case"sass":return"sass";case"styl":case"stylus":return"stylus";case"json":return"json";case"xml":case"svg":case"xaml":return"xml";case"md":case"markdown":return"markdown";case"yml":case"yaml":return"yaml";case"toml":return"toml";case"ini":case"conf":case"config":return"config";case"env":return"env";case"properties":return"properties";case"sql":return"sql";case"sh":case"bash":return"shell";case"py":return"python";case"rb":return"ruby";case"go":return"go";case"java":return"java";case"kt":case"kts":return"kotlin";case"scala":return"scala";case"swift":return"swift";case"dart":return"dart";case"c":case"cpp":case"cc":case"cxx":case"h":case"hpp":return"c";case"cs":return"csharp";case"php":return"php";case"pl":case"pm":return"perl";case"lua":return"lua";case"r":return"r";case"rs":return"rust";case"hbs":case"handlebars":return"handlebars";case"ejs":return"ejs";case"pug":case"jade":return"pug";case"mustache":return"mustache";case"twig":return"twig";case"j2":case"jinja":case"jinja2":return"jinja";case"erb":return"erb";case"vue":return"vue";case"svelte":return"svelte";case"graphql":case"gql":return"graphql";case"proto":return"protobuf";case"csv":return"csv";case"tf":case"tfvars":return"terraform";case"pp":return"puppet";case"gd":return"gdscript";case"coffee":return"coffeescript";case"haml":return"haml";case"slim":return"slim";case"nim":return"nim";case"fs":case"fsx":return"fsharp";case"hs":case"lhs":return"haskell";case"rst":return"restructuredtext";case"ls":return"livescript";case"elm":return"elm";case"star":case"bzl":return"starlark";case"cmake":return"cmake";default:return"text"}}function Vs(e,r){try{const t=Qs(r);let a=e,s=!1;switch(t){case"html":case"xml":a=a.replace(/<!--[\s\S]*?-->/g,""),a=a.replace(/\s+/g," "),a=a.replace(/>\s+</g,"><");break;case"css":case"less":case"scss":case"stylus":a=a.replace(/\/\*[\s\S]*?\*\//g,""),a=a.replace(/^\s*\/\/.*$/gm,""),a=a.replace(/\s+/g," "),a=a.replace(/\s*([{}:;,])\s*/g,"$1");break;case"sass":a=a.replace(/\/\*[\s\S]*?\*\//g,""),a=a.replace(/^\s*\/\/.*$/gm,""),a=a.replace(/[ \t]+$/gm,""),a=a.replace(/\n\s*\n\s*\n+/g,"\n\n");break;case"json":try{const e=JSON.parse(a);a=JSON.stringify(e)}catch{a=a.replace(/\s+/g," "),s=!0}break;case"yaml":a=a.replace(/^\s*#.*$/gm,""),a=a.replace(/[ \t]+$/gm,""),a=a.replace(/\n\s*\n\s*\n+/g,"\n\n"),a=a.replace(/^(\s*)[ ]{4,}/gm,"$1 ");break;case"toml":case"shell":case"dockerfile":case"ruby":case"perl":case"r":case"gdscript":case"puppet":a=a.replace(/^\s*#.*$/gm,""),a=a.replace(/^\s*\n/gm,"");break;case"config":case"ini":case"env":case"properties":a=a.replace(/^\s*[#;].*$/gm,""),a=a.replace(/^\s*\n/gm,"");break;case"sql":a=a.replace(/--.*$/gm,""),a=a.replace(/\/\*[\s\S]*?\*\//g,""),a=a.replace(/\s+/g," ");break;case"makefile":a=a.replace(/^\s*#.*$/gm,""),a=a.replace(/[ ]+$/gm,""),a=a.replace(/\n\s*\n\s*\n+/g,"\n\n");break;case"python":case"coffeescript":case"livescript":case"nim":case"starlark":case"cmake":a=a.replace(/^\s*#.*$/gm,""),a=a.replace(/[ \t]+$/gm,""),a=a.replace(/\n\s*\n\s*\n+/g,"\n\n");break;case"go":case"java":case"kotlin":case"scala":case"swift":case"dart":case"c":case"csharp":case"rust":case"jenkinsfile":a=a.replace(/^\s*\/\/.*$/gm,""),a=a.replace(/\/\*[\s\S]*?\*\//g,""),a=a.replace(/\s+/g," ");break;case"php":a=a.replace(/^\s*\/\/.*$/gm,""),a=a.replace(/^\s*#.*$/gm,""),a=a.replace(/\/\*[\s\S]*?\*\//g,""),a=a.replace(/\s+/g," ");break;case"lua":a=a.replace(/^\s*--.*$/gm,""),a=a.replace(/--\[\[[\s\S]*?\]\]/g,""),a=a.replace(/\s+/g," ");break;case"handlebars":case"mustache":a=a.replace(/\{\{!--[\s\S]*?--\}\}/g,""),a=a.replace(/\{\{![\s\S]*?\}\}/g,""),a=a.replace(/\s+/g," ");break;case"ejs":case"erb":a=a.replace(/<%#[\s\S]*?%>/g,""),a=a.replace(/\s+/g," ");break;case"pug":a=a.replace(/^\s*\/\/.*$/gm,""),a=a.replace(/^\s*\/\/-.*$/gm,""),a=a.replace(/[ \t]+$/gm,"");break;case"twig":case"jinja":a=a.replace(/\{#[\s\S]*?#\}/g,""),a=a.replace(/\s+/g," ");break;case"vue":case"svelte":a=a.replace(/<!--[\s\S]*?-->/g,""),a=a.replace(/\s+/g," ");break;case"graphql":default:a=a.replace(/^\s*#.*$/gm,""),a=a.replace(/\s+/g," ");break;case"protobuf":a=a.replace(/^\s*\/\/.*$/gm,""),a=a.replace(/\s+/g," ");break;case"csv":a=a.replace(/[ \t]+$/gm,""),a=a.replace(/^\s*\n/gm,"");break;case"terraform":a=a.replace(/^\s*#.*$/gm,""),a=a.replace(/^\s*\/\/.*$/gm,""),a=a.replace(/\/\*[\s\S]*?\*\//g,""),a=a.replace(/\s+/g," ");break;case"markdown":a=a.replace(/[ \t]+$/gm,""),a=a.replace(/\n{3,}/g,"\n\n"),a=a.replace(/([^\n])[ \t]{3,}/g,"$1 ");break;case"fsharp":a=a.replace(/^\s*\/\/.*$/gm,""),a=a.replace(/\(\*[\s\S]*?\*\)/g,""),a=a.replace(/[ \t]+$/gm,""),a=a.replace(/\n\s*\n\s*\n+/g,"\n\n");break;case"haskell":case"elm":a=a.replace(/^\s*--.*$/gm,""),a=a.replace(/\{-[\s\S]*?-\}/g,""),a=a.replace(/[ \t]+$/gm,""),a=a.replace(/\n\s*\n\s*\n+/g,"\n\n");break;case"haml":a=a.replace(/^\s*-#.*$/gm,""),a=a.replace(/^\s*\/.*$/gm,""),a=a.replace(/[ \t]+$/gm,""),a=a.replace(/\n\s*\n\s*\n+/g,"\n\n");break;case"slim":a=a.replace(/^\s*\/.*$/gm,""),a=a.replace(/[ \t]+$/gm,""),a=a.replace(/\n\s*\n\s*\n+/g,"\n\n");break;case"restructuredtext":a=a.replace(/^\s*\.\.\s+[^:]*$/gm,""),a=a.replace(/[ \t]+$/gm,""),a=a.replace(/\n\s*\n\s*\n+/g,"\n\n")}return a=a.trim(),s||function(e,r){const t=Qs(r);try{switch(t){case"json":return JSON.parse(e),!0;case"yaml":return!e.includes("\t")&&e.split("\n").every(e=>""===e.trim()||!e.startsWith(" ")||e.match(/^\s+[^\s]/));case"xml":return(e.match(/<[^/>]+>/g)||[]).length===(e.match(/<\/[^>]+>/g)||[]).length+(e.match(/<[^>]+\/>/g)||[]).length;default:return!0}}catch{return!1}}(a,r)?{content:a,failed:!1}:{content:e,failed:!0}}catch(e){return{content:`DEBUG: Generic minification failed for ${r}. Error: ${e.message}`,failed:!0}}}async function Zs(e,r){if(function(e){const r=e.split(".").pop()?.toLowerCase();return["js","ts","jsx","tsx","mjs","cjs"].includes(r||"")}(r)){const t=await async function(e,r){try{let t=e;const a=function(e){const r=e.split(".").pop()?.toLowerCase();return["ts","tsx"].includes(r||"")}(r),s=function(e){const r=e.split(".").pop()?.toLowerCase();return["jsx","tsx"].includes(r||"")}(r),o=!a&&function(e){return!!(e.includes("@flow")||e.includes("// @flow")||e.includes("/* @flow */")||/\$FlowFixMe/.test(e)||/\$FlowIssue/.test(e))||[/import\s+type\s+\w/.test(e),/export\s+type\s+\w/.test(e),/:\s*\?\w+/.test(e),/:\s*\w+\s*\|/.test(e),/\w+\s*:\s*\w+\s*=>/.test(e)].filter(Boolean).length>=2}(e);if(a||s||o){const n=[];a&&n.push("@babel/preset-typescript"),s&&n.push("@babel/preset-react"),o&&n.push("@babel/preset-flow");try{const i=await d(e,{presets:n,filename:r,retainLines:!1,compact:!1,babelrc:!1,configFile:!1});if(!i?.code)return{content:`DEBUG: No code returned. FilePath: ${r}, isTS: ${a}, isJSX: ${s}, isFlow: ${o}, presets: ${JSON.stringify(n)}`,failed:!0};t=i.code}catch(e){return{content:`DEBUG: Transform error for ${r}. isTS: ${a}, isJSX: ${s}, isFlow: ${o}, presets: ${JSON.stringify(n)}, error: ${e.message}`,failed:!0}}}return{content:(await u(t,{compress:{drop_console:!1,drop_debugger:!1,pure_funcs:[],global_defs:{},sequences:!0,conditionals:!0,comparisons:!0,evaluate:!0,booleans:!0,loops:!1,unused:!1,hoist_funs:!1,hoist_vars:!1,dead_code:!0,side_effects:!1},mangle:!1,format:{comments:!1,beautify:!1,semicolons:!0},sourceMap:!1,parse:{bare_returns:!0,html5_comments:!0,shebang:!0}})).code||e,failed:!1}}catch(e){return{content:`DEBUG: JavaScript minification failed for ${r}. Error: ${e.message}. Stack: ${e.stack}`,failed:!0}}}(e,r);if(t.failed){const t=Vs(e,r);return t.failed?{content:e,failed:!0,type:"failed"}:{content:t.content,failed:!1,type:"generic"}}return{content:t.content,failed:!1,type:"javascript"}}{const t=Vs(e,r);return t.failed?{content:e,failed:!0,type:"failed"}:{content:t.content,failed:!1,type:"generic"}}}const Bs="githubGetFileContent";function Gs(r){r.registerTool(Bs,{description:"Fetches the content of a file from a GitHub repository. Automatically falls back between main/master branches if not found.",inputSchema:{owner:e.string().min(1).max(100).regex(/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$/).describe("Repository owner/organization name (e.g., 'facebook', 'microsoft'). Do NOT include repository name here."),repo:e.string().min(1).max(100).regex(/^[a-zA-Z0-9._-]+$/).describe("Repository name only (e.g., 'react', 'vscode'). Do NOT include owner/org prefix."),branch:e.string().min(1).max(255).regex(/^[^\s]+$/).describe("Branch name, tag name, OR commit SHA. Tool will automatically try 'main' and 'master' if specified branch is not found."),filePath:e.string().min(1).describe("File path from repository root (e.g., 'src/index.js', 'README.md', 'docs/api.md'). Do NOT start with slash."),startLine:e.number().int().min(1).optional().describe("Starting line number (1-based) for partial file access."),endLine:e.number().int().min(1).optional().describe("Ending line number (1-based) for partial file access."),contextLines:e.number().int().min(0).max(50).optional().default(5).describe("Context lines around target range. Default: 5."),minified:e.boolean().default(!0).describe("Optimize content for token efficiency (enabled by default).")},annotations:{title:"GitHub File Content - Partial Access (Default/Recommended)",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0}},async e=>{try{return await async function(e){return Ja(Ga("gh-file-content",e),async()=>{const{owner:r,repo:t,branch:a,filePath:s}=e;try{a.match(/^[0-9a-f]{40}$/);const o=`/repos/${r}/${t}/contents/${s}?ref=${a}`,n=await as("api",[o],{cache:!1});if(n.isError){if(n.content[0].text.includes("404")&&("main"===a||"master"===a)){const o="main"===a?"master":"main",n=`/repos/${r}/${t}/contents/${s}?ref=${o}`,i=await as("api",[n],{cache:!1});if(!i.isError)return await Js(i,r,t,o,s,e.minified,e.startLine,e.endLine,e.contextLines)}return n}return await Js(n,r,t,a,s,e.minified,e.startLine,e.endLine,e.contextLines)}catch(e){return os({error:`Error fetching file content: ${e}`})}})}(e)}catch(e){return os({error:"Failed to fetch file. Verify path with github_get_contents first"})}})}async function Js(e,r,t,a,s,o,n,i,c=5){const l=JSON.parse(e.content[0].text).result;if(Array.isArray(l))return os({error:"Path is a directory. Use github_view_repo_structure to list directory contents"});const u="number"==typeof l.size?l.size:0;if(u>307200)return os({error:`File too large (${Math.round(u/1024)}KB > ${Math.round(300)}KB). Use githubSearchCode to search within the file or use startLine/endLine parameters to get specific sections`});if(!l.content)return os({error:"File is empty - no content to display"});const d=l.content.replace(/\s/g,"");if(!d)return os({error:"File is empty - no content to display"});let p;try{const e=Buffer.from(d,"base64");if(-1!==e.indexOf(0))return os({error:"Binary file detected. Cannot display as text - download directly from GitHub"});p=e.toString("utf-8")}catch(e){return os({error:"Failed to decode file. Encoding may not be supported (expected UTF-8)"})}let h,m,f=p,g=!1,v=!1;const y=p.split("\n"),b=y.length;if(void 0!==n){if(n<1||n>b)return os({error:`Invalid startLine ${n}. File has ${b} lines. Use line numbers between 1 and ${b}.`});const e=Math.max(1,n-c),r=i?Math.min(b,i+c):Math.min(b,n+c);if(void 0!==i){if(i<n)return os({error:`Invalid range: endLine (${i}) must be greater than or equal to startLine (${n}).`});if(i>b)return os({error:`Invalid endLine ${i}. File has ${b} lines. Use line numbers between 1 and ${b}.`})}const t=y.slice(e-1,r);h=e,m=r,g=!0,f=t.map((r,t)=>{const a=e+t;return`${a>=n&&(void 0===i||a<=i)?"→":" "}${a.toString().padStart(4)}: ${r}`}).join("\n"),v=!0}let w=!1,P="none";if(o)if(v){const e=f.split("\n").map(e=>{const r=e.match(/^[→ ]\s*\d+:\s*(.*)$/);return r?r[1]:e}).join("\n"),r=await Zs(e,s);r.failed?w=!0:(f=`Lines ${h}-${m} (minified):\n${r.content}`,P=r.type)}else{const e=await Zs(f,s);f=e.content,w=e.failed,P=e.type}return os({data:{filePath:s,owner:r,repo:t,branch:a,content:f,totalLines:b,requestedStartLine:n,requestedEndLine:i,requestedContextLines:c,...g&&{startLine:h,endLine:m,isPartial:g},...o&&{minified:!w,minificationFailed:w,minificationType:P}}})}const Ks="githubSearchRepositories";function Ws(r){r.registerTool(Ks,{description:"Search GitHub repositories using gh search repos CLI.\n\nTHREE SEARCH APPROACHES:\n- exactQuery: Single exact phrase/word search\n- queryTerms: Multiple search terms (broader coverage) \n- topic: Find repositories by technology/subject\n\nBEST PRACTICES:\n- Use exactQuery for specific repository names\n- Use queryTerms with minimal words for broader results\n- Use topic for technology/subject discovery\n- Use owner for organization exploration\n- Use filters (language, stars, forks) for refinement\n\nMultiple focused searches work better than complex single queries.",inputSchema:{exactQuery:e.string().optional().describe("Single exact phrase/word search"),queryTerms:e.array(e.string()).optional().describe("Multiple search terms for broader coverage"),owner:e.union([e.string(),e.array(e.string())]).optional().describe("Repository owner/organization name(s). Search within specific organizations or users."),language:e.string().optional().describe("Programming language filter. Filters repositories by primary language."),stars:e.union([e.number().int().min(0),e.string().regex(/^(>=?\d+|<=?\d+|\d+\.\.\d+|\d+)$/,'Invalid format. Use: ">N", ">=N", "<N", "<=N", "N..M", or exact number')]).optional().describe('Star count filter. Format: ">N" (more than), "<N" (less than), "N..M" (range).'),topic:e.union([e.string(),e.array(e.string())]).optional().describe("Find repositories by technology/subject"),forks:e.union([e.number().int().min(0),e.string().regex(/^(>=?\d+|<=?\d+|\d+\.\.\d+|\d+)$/,'Invalid format. Use: ">N", ">=N", "<N", "<=N", "N..M", or exact number')]).optional().describe('Fork count filter. Format: ">N" (more than), "<N" (less than), "N..M" (range).'),"number-topics":e.union([e.number().int().min(0),e.string().regex(/^(>=?\d+|<=?\d+|\d+\.\.\d+|\d+)$/,'Invalid format. Use: ">5", ">=3", "<10", "<=2", "3..10", or exact number "5"')]).optional().describe('Number of topics filter. Format: ">5" (many topics), ">=3" (at least 3), "<10" (few topics), "1..3" (range), "5" (exact).'),license:e.union([e.string(),e.array(e.string())]).optional().describe("License filter. Filter repositories by license type."),archived:e.boolean().optional().describe("Archive status filter. false (active repos only), true (archived repos only)."),"include-forks":e.enum(["false","true","only"]).optional().describe('Fork inclusion. "false" (exclude forks), "true" (include forks), "only" (forks only).'),visibility:e.enum(["public","private","internal"]).optional().describe("Repository visibility."),created:e.string().regex(/^(>=?\d{4}-\d{2}-\d{2}|<=?\d{4}-\d{2}-\d{2}|\d{4}-\d{2}-\d{2}\.\.\d{4}-\d{2}-\d{2}|\d{4}-\d{2}-\d{2})$/,'Invalid date format. Use: ">2020-01-01", ">=2020-01-01", "<2023-12-31", "<=2023-12-31", "2020-01-01..2023-12-31", or exact date "2023-01-01"').optional().describe('Repository creation date filter. Format: ">2020-01-01" (after), ">=2020-01-01" (on or after), "<2023-12-31" (before), "<=2023-12-31" (on or before), "2020-01-01..2023-12-31" (range), "2023-01-01" (exact).'),updated:e.string().regex(/^(>=?\d{4}-\d{2}-\d{2}|<=?\d{4}-\d{2}-\d{2}|\d{4}-\d{2}-\d{2}\.\.\d{4}-\d{2}-\d{2}|\d{4}-\d{2}-\d{2})$/,'Invalid date format. Use: ">2024-01-01", ">=2024-01-01", "<2022-01-01", "<=2022-01-01", "2023-01-01..2024-12-31", or exact date "2024-01-01"').optional().describe('Last updated date filter. Format: ">2024-01-01" (recently updated), ">=2024-01-01" (on or after), "<2022-01-01" (not recently updated), "2023-01-01..2024-12-31" (range).'),size:e.string().regex(/^(>=?\d+|<=?\d+|\d+\.\.\d+|\d+)$/,'Invalid size format. Use: ">1000", ">=500", "<100", "<=50", "100..1000", or exact number "500"').optional().describe('Repository size filter in KB. Format: ">1000" (large projects), ">=500" (medium-large), "<100" (small projects), "<=50" (tiny), "100..1000" (medium range), "500" (exact).'),"good-first-issues":e.union([e.number().int().min(0),e.string().regex(/^(>=?\d+|<=?\d+|\d+\.\.\d+|\d+)$/,'Invalid format. Use: number, ">5", ">=10", "<20", "<=15", or "5..20"')]).optional().describe('Good first issues count. Format: ">5" (many beginner issues), "1..10" (some beginner issues).'),"help-wanted-issues":e.union([e.number().int().min(0),e.string().regex(/^(>=?\d+|<=?\d+|\d+\.\.\d+|\d+)$/,'Invalid format. Use: number, ">5", ">=10", "<20", "<=15", or "5..20"')]).optional().describe('Help wanted issues count. Format: ">10" (many help wanted), "1..5" (some help wanted).'),followers:e.union([e.number().int().min(0),e.string().regex(/^(>=?\d+|<=?\d+|\d+\.\.\d+|\d+)$/,'Invalid format. Use: ">1000", ">=500", "<100", "<=50", "100..1000", or exact number "500"')]).optional().describe('Repository owner followers count. Format: ">1000" (popular developers), ">=500" (established developers), "<100" (smaller developers), "100..1000" (range).'),match:e.union([e.enum(["name","description","readme"]),e.array(e.enum(["name","description","readme"]))]).optional().describe("Search scope. Where to search: name, description, or readme content."),sort:e.enum(["forks","help-wanted-issues","stars","updated","best-match"]).optional().default("best-match").describe("Sort criteria."),order:e.enum(["asc","desc"]).optional().default("desc").describe("Sort order direction."),limit:e.number().int().min(1).max(100).optional().default(30).describe("Maximum number of repositories to return (1-100).")},annotations:{title:"GitHub Repository Search",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0}},async e=>{const r=!!e.exactQuery,t=e.queryTerms&&e.queryTerms.length>0;if(r&&t)return os({error:"Use either exactQuery OR queryTerms, not both. Choose one search approach."});try{const r=e.exactQuery?function(e){let r,t,a=e;const s=[/github\.com\/([^\\s]+)\/([^\\s]+)/i,/\b([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])\/([a-zA-Z0-9][a-zA-Z0-9\-.]*[a-zA-Z0-9])\b/,/@([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])\/([a-zA-Z0-9][a-zA-Z0-9\-.]*[a-zA-Z0-9])/];for(const e of s){const s=a.match(e);if(s){r=s[1],t=s[2],a=a.replace(s[0],"").trim();break}}return{extractedOwner:r,extractedRepo:t,cleanedQuery:a||e}}(e.exactQuery):e.queryTerms?{cleanedQuery:e.queryTerms.join(" "),extractedOwner:void 0,extractedRepo:void 0}:{cleanedQuery:"",extractedOwner:void 0,extractedRepo:void 0};let t=e.owner;r.extractedOwner&&!t&&(t=r.extractedOwner);const a={...e,exactQuery:e.exactQuery?r.cleanedQuery:void 0,queryTerms:e.queryTerms,owner:t};if(!(a.exactQuery?.trim()||a.queryTerms&&a.queryTerms.length>0||a.owner||a.language||a.topic||a.stars||a.forks))return os({error:'Repository search requires at least one filter. Try:\n• Topic search: { topic: "react" }\n• Exact search: { exactQuery: "cli shell" } \n• Multiple terms: { queryTerms: ["react", "hooks"] }\n• Organization: { owner: "microsoft" }\n• Language filter: { language: "go" }\n\nAlternative: Use npm search for package discovery.'});const s=await Ys(a);if(s.isError){const e=s.content?.[0]?.text||"";return e.includes("rate limit")?os({error:"GitHub API rate limit exceeded. Alternatives:\n• Use npm search for package discovery\n• Remove quality filters (stars/forks) \n• Search fewer organizations\n• Wait 5-10 minutes and retry"}):e.includes("authentication")?os({error:"Authentication required:\n• Run: gh auth login\n• For private repos: use api_status_check tool\n• Public repos work without auth\n\nAlternative: Use npm search for packages."}):s}if(!(JSON.parse(s.content[0].text).total_count>0)){const e=[];return a.exactQuery&&e.push("• Try broader search terms"),a.language&&e.push("• Remove language filter"),(a.stars||a.forks)&&e.push("• Lower quality thresholds"),a.topic||e.push('• Try topic search: { topic: "react" }'),a.owner&&e.push("• Remove owner filter for global search"),e.push("• Use npm search for package discovery"),os({error:`No repositories found. Try:\n${e.join("\n")}`})}if(a.owner&&!a.visibility){const e={...a,visibility:"private"},r=await Ys(e);if(!r.isError){const e=JSON.parse(r.content[0].text);if(e.total_count>0)return os({data:{...e,note:"Found results in private repositories within the specified organization."}})}}return s}catch(e){return os({error:Es("repositories")})}})}async function Ys(e){return Ja(Ga("gh-repos",e),async()=>{try{const{command:r,args:t}=function(e){const r=["repos"];let t="";e.exactQuery?(r.push(e.exactQuery.trim()),t=e.exactQuery.trim()):e.queryTerms&&e.queryTerms.length>0&&(e.queryTerms.forEach(e=>r.push(e.trim())),t=e.queryTerms.join(" "));const a=t&&/\b(stars|language|org|repo|topic|user|created|updated|size|license|archived|fork|good-first-issues|help-wanted-issues):/i.test(t);r.push("--json=name,fullName,description,language,stargazersCount,forksCount,updatedAt,createdAt,url,owner,isPrivate,license,hasIssues,openIssuesCount,isArchived,isFork,visibility");const s=(t,a,s=!0,o)=>{const n=e[t];void 0!==n&&s&&(Array.isArray(n)?r.push(`--${a}=${n.join(",")}`):o?r.push(`--${a}=${o(n)}`):r.push(`--${a}=${n.toString()}`))};s("owner","owner",!a),s("language","language",!a),s("forks","forks",!a,e=>"number"==typeof e?e.toString():e.trim()),s("topic","topic",!a),s("number-topics","number-topics",!0,e=>"number"==typeof e?e.toString():e.trim()),s("stars","stars",!a,e=>"number"==typeof e?e.toString():e.trim()),s("archived","archived"),s("include-forks","include-forks"),s("visibility","visibility"),s("license","license"),s("created","created"),s("updated","updated"),s("size","size"),s("good-first-issues","good-first-issues",!0,e=>"number"==typeof e?e.toString():e),s("help-wanted-issues","help-wanted-issues",!0,e=>"number"==typeof e?e.toString():e),s("followers","followers",!0,e=>"number"==typeof e?e.toString():e.trim()),s("match","match");const o=e.sort||"best-match";"best-match"!==o&&r.push(`--sort=${o}`),s("order","order");const n=e.limit||30;return r.push(`--limit=${n}`),{command:"search",args:r}}(e),a=await as(r,t,{cache:!1});if(a.isError)return a;const s=JSON.parse(a.content[0].text).result;if(!Array.isArray(s)||0===s.length)return os({error:_s("repositories")});const o={totalFound:0,languages:new Set,avgStars:0,recentlyUpdated:0,topStarred:[]};o.totalFound=s.length;let n=0;const i=new Date,c=new Date(i.getTime()-2592e6);return s.forEach(e=>{if(e.language&&o.languages.add(e.language),"number"==typeof e.stargazersCount&&(n+=e.stargazersCount),e.updatedAt){const r=new Date(e.updatedAt);!isNaN(r.getTime())&&r>c&&o.recentlyUpdated++}}),o.avgStars=s.length>0?Math.round(n/s.length):0,o.topStarred=s.map(e=>({name:e.fullName||e.name,stars:e.stargazersCount||0,description:e.description||"No description",language:e.language||"Unknown",url:e.url,forks:e.forksCount||0,isPrivate:e.isPrivate||!1,isArchived:e.isArchived||!1,isFork:e.isFork||!1,topics:[],license:e.license?.name||null,hasIssues:e.hasIssues||!1,openIssuesCount:e.openIssuesCount||0,createdAt:ns(e.createdAt),updatedAt:ns(e.updatedAt),visibility:e.visibility||"public",owner:e.owner?.login||e.owner})),os({data:{total_count:o.totalFound,...o.totalFound>0?{repositories:o.topStarred,summary:{languages:Array.from(o.languages).slice(0,10),avgStars:o.avgStars,recentlyUpdated:o.recentlyUpdated}}:{repositories:[]}}})}catch(e){return os({error:Es("repositories")})}})}const Xs="githubSearchCommits";function eo(r){r.registerTool(Xs,{description:'Search GitHub commits by message, author, hash, or date. Returns SHAs for github_fetch_content (branch=SHA). Can fetch commit content changes (diffs/patches) when getChangesContent=true.\n\nSEARCH OPTIONS:\n1. Query-based search:\n - exactQuery: Exact phrase matching (e.g., "bug fix")\n - queryTerms: Multiple keywords with AND logic (e.g., ["readme", "typo"])\n - orTerms: Keywords with OR logic (e.g., ["bug", "fix"] finds commits with either)\n - Combine: queryTerms=["api"] + orTerms=["auth", "login"] = api AND (auth OR login)\n\n2. Filter-only search (no query required):\n - Search by author, committer, hash, date, etc.\n - Example: Just committer="monalisa" to find all commits by that user\n - Example: Search by commit hash (including head_sha/base_sha from a PR): hash="<sha>"\n\n3. Combined search:\n - Mix queries with filters for precise results\n - Example: queryTerms=["fix"] + author="jane" + author-date=">2023-01-01"\n\nEXAMPLES:\n• Search commits with "readme" AND "typo": queryTerms=["readme", "typo"]\n• Search exact phrase "bug fix": exactQuery="bug fix"\n• Search by committer only: committer="monalisa"\n• Search by author name: author-name="Jane Doe"\n• Search by commit hash (including head_sha/base_sha from a PR): hash="8dd03144ffdc6c0d486d6b705f9c7fba871ee7c3"\n• Search before date: author-date="<2022-02-01"\n\nCONTENT FETCHING:\n- Set getChangesContent=true to fetch actual commit changes:\n • Gets file diffs and patches for up to 10 commits\n • Shows changed files, additions, deletions\n • Includes code patches (first 1000 chars)\n • Works for both public AND private repositories\n • Most effective when owner and repo are specified',inputSchema:{exactQuery:e.string().optional().describe('Exact phrase to search for in commit messages (e.g., "bug fix")'),queryTerms:e.array(e.string()).optional().describe('Array of search terms with AND logic (e.g., ["readme", "typo"] finds commits with both words)'),orTerms:e.array(e.string()).optional().describe('Array of search terms with OR logic (e.g., ["bug", "fix"] finds commits with either word)'),owner:e.string().optional().describe("Repository owner (use with repo param)"),repo:e.string().optional().describe("Repository name (use with owner param)"),author:e.string().optional().describe('GitHub username of commit author (e.g., "octocat")'),"author-name":e.string().optional().describe("Full name of commit author"),"author-email":e.string().optional().describe("Email of commit author"),committer:e.string().optional().describe('GitHub username of committer (e.g., "monalisa")'),"committer-name":e.string().optional().describe("Full name of committer"),"committer-email":e.string().optional().describe("Email of committer"),"author-date":e.string().optional().describe('Filter by author date (e.g., "<2022-02-01", ">2020-01-01", "2020-01-01..2021-01-01")'),"committer-date":e.string().optional().describe('Filter by commit date (e.g., "<2022-02-01", ">2020-01-01", "2020-01-01..2021-01-01")'),hash:e.string().optional().describe("Commit SHA (full or partial, including head_sha/base_sha from a PR as returned by github_search_pull_requests)"),parent:e.string().optional().describe("Parent commit SHA"),tree:e.string().optional().describe("Tree SHA"),merge:e.boolean().optional().describe("Only merge commits (true) or exclude them (false)"),visibility:e.enum(["public","private","internal"]).optional().describe("Repository visibility filter"),limit:e.number().int().min(1).max(50).optional().default(25).describe("Maximum number of results to fetch"),sort:e.enum(["author-date","committer-date"]).optional().describe("Sort by date field"),order:e.enum(["asc","desc"]).optional().default("desc").describe("Sort order"),getChangesContent:e.boolean().optional().default(!1).describe("Set to true to fetch actual commit changes (diffs/patches). Works for both public and private repositories, most effective with owner and repo specified. Limited to first 10 commits for rate limiting.")},annotations:{title:"GitHub Commit Search - Smart & Effective",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0}},async e=>{const r=!!e.exactQuery,t=e.queryTerms&&e.queryTerms.length>0,a=e.orTerms&&e.orTerms.length>0,s=!!(e.author||e.committer||e["author-name"]||e["committer-name"]||e["author-email"]||e["committer-email"]||e.hash||e.parent||e.tree||e["author-date"]||e["committer-date"]||void 0!==e.merge||e.visibility||e.owner&&e.repo);if(!(r||t||a||s))return os({error:"At least one search parameter required: exactQuery, queryTerms, orTerms, or filters (author, committer, hash, date, etc.)"});if(r&&(t||a))return os({error:"exactQuery cannot be combined with queryTerms or orTerms. Use exactQuery alone or combine queryTerms + orTerms."});try{const r=await async function(e){return Ja(Ga("gh-commits",e),async()=>{try{const r=function(e){const r=["commits"];if(e.exactQuery)r.push(e.exactQuery);else if(e.queryTerms||e.orTerms){const t=[];if(e.queryTerms&&e.queryTerms.length>0){const r=e.queryTerms.map(e=>/[()[\\]{}*?^$|.\\\\+]/.test(e)?`"${e}"`:e);t.push(...r)}if(e.orTerms&&e.orTerms.length>0){const r=e.orTerms.map(e=>/[()[\\]{}*?^$|.\\\\+]/.test(e)?`"${e}"`:e);if(1===r.length)t.push(r[0]);else{const e=`(${r.join(" OR ")})`;t.push(e)}}t.length>0&&r.push(t.join(" "))}return e.owner&&e.repo?r.push(`--repo=${e.owner}/${e.repo}`):e.owner&&r.push(`--owner=${e.owner}`),e.author&&r.push(`--author=${e.author}`),e["author-name"]&&r.push(`--author-name=${e["author-name"]}`),e["author-email"]&&r.push(`--author-email=${e["author-email"]}`),e.committer&&r.push(`--committer=${e.committer}`),e["committer-name"]&&r.push(`--committer-name=${e["committer-name"]}`),e["committer-email"]&&r.push(`--committer-email=${e["committer-email"]}`),e["author-date"]&&r.push(`--author-date=${e["author-date"]}`),e["committer-date"]&&r.push(`--committer-date=${e["committer-date"]}`),e.hash&&r.push(`--hash=${e.hash}`),e.parent&&r.push(`--parent=${e.parent}`),e.tree&&r.push(`--tree=${e.tree}`),void 0!==e.merge&&r.push("--merge"),e.visibility&&r.push(`--visibility=${e.visibility}`),e.sort&&r.push(`--sort=${e.sort}`),e.order&&r.push(`--order=${e.order}`),e.limit&&r.push(`--limit=${e.limit}`),r.push("--json=sha,commit,author,committer,repository,url,parents"),r}(e);return await as("search",r,{cache:!1})}catch(e){const r=e.message||"";return r.includes("authentication")?os({error:"GitHub authentication required - run api_status_check tool"}):r.includes("rate limit")?os({error:Ps(!1)}):os({error:Es("commits")})}})}(e);if(r.isError)return r;const t=JSON.parse(r.content[0].text).result,a=Array.isArray(t)?t:[];if(0===a.length){const r=[];let t=!1;const a=[];if(e.owner&&e.repo&&a.push("repo"),e.author&&a.push("author"),e["author-email"]&&a.push("author-email"),e.hash&&a.push("hash"),e["author-date"]&&a.push("date"),e.visibility&&a.push("visibility"),t=a.length>0,e.exactQuery){const t=e.exactQuery.trim().split(" ");t.length>1&&r.push(`Try queryTerms instead: ["${t[0]}", "${t[1]}"] for broader results`)}if(e.queryTerms&&e.queryTerms.length>2){const t=e.queryTerms.slice(0,2);r.push(`Try fewer terms: ["${t.join('", "')}"] instead of ${e.queryTerms.length} terms`)}return t&&(a.length>1?r.push(`Remove some filters (currently: ${a.join(", ")}) and keep only the most important one`):r.push(`Remove the ${a[0]} filter and search more broadly`)),e.exactQuery||e.queryTerms||!t||r.push('Add search terms: use queryTerms: ["term1", "term2"] with your filters'),e.queryTerms&&1===e.queryTerms.length&&r.push("For OR operations, run separate searches for each term instead of complex queries"),0===r.length&&r.push("Try different keywords or ask the user to be more specific about what commits they're looking for"),os({error:`${_s("commits")}\n\nTry these simplified searches:\n${r.map(e=>`• ${e}`).join("\n")}\n\nOr ask the user:\n• "What specific type of commits are you looking for?" \n• "Can you provide different keywords to search for?"\n• "Should I search in a specific repository instead?"\n\nSearch techniques to try:\n• Use exactQuery for phrases: "bug fix", "exact phrase"\n• Use queryTerms for multiple terms: ["term1", "term2"] (AND logic)\n• For OR operations: run separate searches for each term\n• Combine with filters: author, repo, date filters\n\nAlternative tools:\n• Use github_search_code for file-specific commits\n• Use github_search_repos to find repositories first`})}const s=await async function(e,r){const t=function(e){if(0===e.length)return null;const r=e[0].repository;return e.every(e=>e.repository.fullName===r.fullName)?r:null}(e),a=r.getChangesContent&&r.owner&&r.repo,s=new Map;if(a&&e.length>0){const t=e.slice(0,10).map(e=>e.sha).map(async e=>{try{const t=await as("api",[`/repos/${r.owner}/${r.repo}/commits/${e}`],{cache:!1});if(!t.isError)return{sha:e,commitData:JSON.parse(t.content[0].text).result}}catch(e){}return{sha:e,commitData:null}});(await Promise.all(t)).forEach(({sha:e,commitData:r})=>{r&&s.set(e,r)})}const o={commits:e.map(e=>{const r={sha:e.sha,message:(o=e.commit?.message??"",o.split("\n")[0].trim()),author:e.commit?.author?.name??e.author?.login??"Unknown",date:ns(e.commit?.author?.date??""),repository:t?void 0:is(e.repository?.url||""),url:t?e.sha:`${is(e.repository?.url||"")}@${e.sha}`};var o;if(a&&s.has(e.sha)){const t=s.get(e.sha),a=t.files||[];r.diff={changed_files:a.length,additions:t.stats?.additions||0,deletions:t.stats?.deletions||0,total_changes:t.stats?.total||0,files:a.map(e=>({filename:e.filename,status:e.status,additions:e.additions,deletions:e.deletions,changes:e.changes,patch:e.patch?e.patch.substring(0,1e3)+(e.patch.length>1e3?"...":""):void 0})).slice(0,5)}}return r}).map(e=>{const r={};return Object.entries(e).forEach(([e,t])=>{void 0!==t&&(r[e]=t)}),r}),total_count:e.length};return t&&(o.repository={name:t.fullName,description:t.description}),o}(a,e);return os({data:s})}catch(e){const r=e.message||"";return r.includes("authentication")?os({error:"GitHub authentication required - run api_status_check tool"}):r.includes("rate limit")?os({error:Ps(!1)}):os({error:Es("commits")})}})}const ro="githubSearchPullRequests";function to(r){r.registerTool(ro,{description:'Search GitHub PRs by keywords, state, or author. Returns head/base SHAs for github_fetch_content (branch=SHA). Can fetch all PR commits with changes using getCommitData=true.\n\nSEARCH STRATEGY FOR BEST RESULTS:\n- Use minimal search terms for broader coverage (2-3 words max)\n- Separate searches for different aspects vs complex queries \n- Use filters to narrow scope after getting initial results\n- Use getCommitData=true to get all commits in PR with file changes\n- Use github_search_commits with head_sha/base_sha from results to get code changes\n\nCOMMIT DATA FETCHING (getCommitData=true):\n- Fetches all commits in the PR using \'gh pr view --json commits\'\n- For each commit, fetches detailed changes using GitHub API\n- Shows commit SHA, message, author, and file changes\n- Includes up to 10 commits per PR with detailed diffs\n- Each commit shows changed files with additions/deletions/patches\n- Example: Shows individual commits like "Fix bug in component" with specific file changes\n\nEXAMPLE OUTPUT WITH getCommitData=true:\n{\n "commits": {\n "total_count": 3,\n "commits": [\n {\n "sha": "abc123",\n "message": "Fix bug in component", \n "author": "username",\n "diff": {\n "changed_files": 2,\n "additions": 15,\n "deletions": 3,\n "files": [...]\n }\n }\n ]\n }\n}\n\nNOTE: The head_sha and base_sha fields in the PR results can be used as the \'hash\' parameter in github_search_commits to look up the exact commit and get actual code changes.',inputSchema:{query:e.string().min(1,"Search query is required and cannot be empty").describe("Search query for PR content (keep minimal for broader results)"),owner:e.string().optional().describe("Repository owner (use with repo param)"),repo:e.string().optional().describe("Repository name (use with owner param)"),author:e.string().optional().describe("GitHub username of PR author"),assignee:e.string().optional().describe("GitHub username of assignee"),mentions:e.string().optional().describe("PRs mentioning this user"),commenter:e.string().optional().describe("User who commented on PR"),involves:e.string().optional().describe("User involved in any way"),"reviewed-by":e.string().optional().describe("User who reviewed the PR"),"review-requested":e.string().optional().describe("User/team requested for review"),state:e.enum(["open","closed"]).optional().describe("Filter by state: open or closed"),head:e.string().optional().describe("Filter on head branch name"),base:e.string().optional().describe("Filter on base branch name"),language:e.string().optional().describe("Repository language"),created:e.string().optional().describe("Filter by created date (e.g., >2020-01-01)"),updated:e.string().optional().describe("Filter by updated date (e.g., >2020-01-01)"),"merged-at":e.string().optional().describe("Filter by merged date (e.g., >2020-01-01)"),closed:e.string().optional().describe("Filter by closed date (e.g., >2020-01-01)"),draft:e.boolean().optional().describe("Filter by draft state"),checks:e.enum(["pending","success","failure"]).optional().describe("Filter by checks status"),merged:e.boolean().optional().describe("Filter by merged state"),review:e.enum(["none","required","approved","changes_requested"]).optional().describe("Filter by review status"),app:e.string().optional().describe("Filter by GitHub App author"),archived:e.boolean().optional().describe("Filter by repository archived state"),comments:e.number().optional().describe("Filter by number of comments"),interactions:e.number().optional().describe("Total interactions (reactions + comments)"),"team-mentions":e.string().optional().describe("Filter by team mentions"),reactions:e.number().optional().describe("Filter by number of reactions"),locked:e.boolean().optional().describe("Filter by locked conversation status"),"no-assignee":e.boolean().optional().describe("Filter by missing assignee"),"no-label":e.boolean().optional().describe("Filter by missing label"),"no-milestone":e.boolean().optional().describe("Filter by missing milestone"),"no-project":e.boolean().optional().describe("Filter by missing project"),label:e.union([e.string(),e.array(e.string())]).optional().describe("Filter by label"),milestone:e.string().optional().describe("Milestone title"),project:e.string().optional().describe("Project board owner/number"),visibility:e.enum(["public","private","internal"]).optional().describe("Repository visibility"),match:e.array(e.enum(["title","body","comments"])).optional().describe("Restrict search to specific fields"),limit:e.number().int().min(1).max(100).optional().default(30).describe("Maximum number of results to fetch"),sort:e.enum(["comments","reactions","reactions-+1","reactions--1","reactions-smile","reactions-thinking_face","reactions-heart","reactions-tada","interactions","created","updated"]).optional().describe("Sort fetched results"),order:e.enum(["asc","desc"]).optional().default("desc").describe("Order of results (requires --sort)"),getCommitData:e.boolean().optional().default(!1).describe("Set to true to fetch all commits in the PR with their changes. Shows commit messages, authors, and file changes.")},annotations:{title:"GitHub PR Search - Smart & Effective",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0}},async e=>{if(!e.query?.trim())return os({error:`${ms} ${vs}`});if(e.query.length>256)return os({error:hs});try{return await async function(e){return Ja(Ga("gh-prs",e),async()=>{const{command:r,args:t}=function(e){if(e.owner&&e.repo)return function(e){const r=["list","--repo",`${e.owner}/${e.repo}`,"--json","number,title,headRefName,headRefOid,baseRefName,baseRefOid,state,author,labels,createdAt,updatedAt,url,comments,isDraft","--limit",String(Math.min(e.limit||30,100))];return e.state&&r.push("--state",e.state),e.author&&r.push("--author",e.author),e.assignee&&r.push("--assignee",e.assignee),e.head&&r.push("--head",e.head),e.base&&r.push("--base",e.base),e.label&&(Array.isArray(e.label)?e.label:[e.label]).forEach(e=>{r.push("--label",e)}),{command:"pr",args:r}}(e);const r=[e.query?.trim()||""];e.owner&&r.push(`org:${e.owner}`);const t={author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,involves:e.involves,state:e.state,created:e.created,updated:e.updated,closed:e.closed,language:e.language};Object.entries(t).forEach(([e,t])=>{t&&r.push(`${e}:${t}`)}),e["reviewed-by"]&&r.push(`reviewed-by:${e["reviewed-by"]}`),e["review-requested"]&&r.push(`review-requested:${e["review-requested"]}`),e.head&&r.push(`head:${e.head}`),e.base&&r.push(`base:${e.base}`),e["merged-at"]&&r.push(`merged:${e["merged-at"]}`),void 0!==e.draft&&r.push(`draft:${e.draft}`),e.checks&&r.push(`status:${e.checks}`),void 0!==e.merged&&r.push("is:"+(e.merged?"merged":"unmerged")),e.review&&r.push(`review:${e.review}`),e.app&&r.push(`app:${e.app}`),void 0!==e.archived&&r.push(`archived:${e.archived}`),e.comments&&r.push(`comments:${e.comments}`),e.interactions&&r.push(`interactions:${e.interactions}`),e.reactions&&r.push(`reactions:${e.reactions}`),e.locked&&r.push("is:locked"),e.visibility&&r.push(`is:${e.visibility}`),e["team-mentions"]&&r.push(`team:${e["team-mentions"]}`),e["no-assignee"]&&r.push("no:assignee"),e["no-label"]&&r.push("no:label"),e["no-milestone"]&&r.push("no:milestone"),e["no-project"]&&r.push("no:project"),e.label&&(Array.isArray(e.label)?e.label:[e.label]).forEach(e=>r.push(`label:"${e}"`)),e.milestone&&r.push(`milestone:"${e.milestone}"`),e.project&&r.push(`project:${e.project}`),e.match&&e.match.forEach(e=>r.push(`in:${e}`)),r.push("type:pr");const a=r.filter(Boolean).join(" "),s=Math.min(e.limit||30,100);let o=`search/issues?q=${encodeURIComponent(a)}&per_page=${s}`;return e.sort&&(o+=`&sort=${e.sort}`),e.order&&(o+=`&order=${e.order}`),{command:"api",args:[o]}}(e),a=await as(r,t,{cache:!1});if(a.isError){const r=a.content[0].text;if(e.owner&&e.repo){if(r.includes("404")){const r=await as("api",[`/repos/${e.owner}/${e.repo}`],{cache:!1});if(r.isError)return os({error:`Repository "${e.owner}/${e.repo}" not found. Use github_search_repositories to find the correct repository name.`});if(e.head||e.base)try{const t=JSON.parse(r.content[0].text),a=t.result?.default_branch||"main";let s="";if(e.head&&e.head!==a&&(s=`\n\nNote: Branch "${e.head}" may not exist. Repository default branch is "${a}".`,s+=`\nTry searching without head branch filter or use head="${a}".`),e.base&&e.base!==a&&(s+=`\n\nNote: Branch "${e.base}" may not exist. Repository default branch is "${a}".`,s+=`\nTry searching without base branch filter or use base="${a}".`),s)return os({error:_s("pull_requests")+s})}catch(e){}}if(r.includes("rate limit")||r.includes("API rate limit"))return os({error:ds})}return a}const s=JSON.parse(a.content[0].text),o=Array.isArray(s.result),n=o?s.result:s.result?.items||[];if(0===n.length){const r=[];let t=!1;const a=[];if(e.owner&&e.repo&&a.push("repo"),e.author&&a.push("author"),e.state&&a.push("state"),e.label&&a.push("label"),e.head&&a.push("head-branch"),e.base&&a.push("base-branch"),e.assignee&&a.push("assignee"),e.created&&a.push("date"),t=a.length>0,e.query&&e.query.trim().split(" ").length>2){const t=e.query.trim().split(" ").slice(0,1).join(" ");r.push(`Try simpler search: "${t}" instead of "${e.query}"`)}return t&&(a.length>2?r.push(`Remove some filters (currently: ${a.join(", ")}) and keep only the most important ones`):a.length>1?r.push(`Remove one filter (currently: ${a.join(", ")}) to broaden search`):r.push(`Remove the ${a[0]} filter and search more broadly`)),!e.query&&t&&r.push('Add basic search terms like "fix", "feature", "bug", or "update" with your filters'),e.owner||e.repo||r.push("Try searching in a specific repository first using owner and repo parameters"),0===r.length&&r.push("Try different keywords or ask the user to be more specific about what PRs they're looking for"),os({error:`${_s("pull_requests")}\n\nTry these simplified searches:\n${r.map(e=>`• ${e}`).join("\n")}\n\nOr ask the user:\n• "What specific type of pull requests are you looking for?"\n• "Can you provide different keywords to search for?"\n• "Should I search in a specific repository instead?"\n• "Are you looking for open or closed PRs?"\n\nAlternative tools:\n• Use github_search_code for PR-related file changes\n• Use github_search_repos to find repositories first`})}const i=await Promise.all(n.map(async r=>{if(o){const t={number:r.number,title:r.title,state:r.state?.toLowerCase()||"unknown",author:r.author?.login||"",repository:`${e.owner}/${e.repo}`,labels:r.labels?.map(e=>e.name)||[],created_at:ns(r.createdAt),updated_at:ns(r.updatedAt),url:r.url,comments:r.comments||0,reactions:0,draft:r.isDraft||!1};if(r.headRefName&&(t.head=r.headRefName),r.headRefOid&&(t.head_sha=r.headRefOid),r.baseRefName&&(t.base=r.baseRefName),r.baseRefOid&&(t.base_sha=r.baseRefOid),e.getCommitData&&e.owner&&e.repo){const a=await ao(e.owner,e.repo,r.number);a&&(t.commits=a)}return t}const t={number:r.number,title:r.title,state:r.state,author:r.user?.login||"",repository:r.repository_url?.split("/").slice(-2).join("/")||"unknown",labels:r.labels?.map(e=>e.name)||[],created_at:ns(r.created_at),updated_at:ns(r.updated_at),url:r.html_url,comments:r.comments,reactions:r.reactions?.total_count||0,draft:r.draft};if(r.merged_at&&(t.merged_at=r.merged_at),r.closed_at&&(t.closed_at=ns(r.closed_at)),r.head?.ref&&(t.head=r.head.ref),r.base?.ref&&(t.base=r.base.ref),e.getCommitData&&e.owner&&e.repo){const a=await ao(e.owner,e.repo,r.number);a&&(t.commits=a)}return t})),c={results:i,total_count:o?i.length:s.result?.total_count||i.length};let l="";return 0===i.length&&e.owner&&e.repo&&(e.head||e.base)&&(l="\n\nNote: No PRs found with specified branch filters. Consider removing head/base filters or checking if branches exist."),os({data:c,...l&&{message:l}})})}(e)}catch(e){return os({error:Es("pull_requests")})}})}async function ao(e,r,t){try{const a=await as("pr",["view",t.toString(),"--json","commits","--repo",`${e}/${r}`],{cache:!1});if(a.isError)return null;const s=JSON.parse(a.content[0].text),o=s.result?.commits||[];if(0===o.length)return null;const n=await Promise.all(o.slice(0,10).map(async t=>{try{const a=await as("api",[`repos/${e}/${r}/commits/${t.oid}`],{cache:!1});if(!a.isError){const s=JSON.parse(a.content[0].text).result;return{sha:t.oid,message:t.messageHeadline,author:t.authors?.[0]?.login||t.authors?.[0]?.name||"Unknown",url:`https://github.com/${e}/${r}/commit/${t.oid}`,authoredDate:t.authoredDate,diff:s.files?{changed_files:s.files.length,additions:s.stats?.additions||0,deletions:s.stats?.deletions||0,total_changes:s.stats?.total||0,files:s.files.slice(0,5).map(e=>({filename:e.filename,status:e.status,additions:e.additions,deletions:e.deletions,changes:e.changes,patch:e.patch?e.patch.substring(0,1e3)+(e.patch.length>1e3?"...":""):void 0}))}:void 0}}}catch(a){return{sha:t.oid,message:t.messageHeadline,author:t.authors?.[0]?.login||t.authors?.[0]?.name||"Unknown",url:`https://github.com/${e}/${r}/commit/${t.oid}`,authoredDate:t.authoredDate}}}));return{total_count:o.length,commits:n.filter(Boolean)}}catch(e){return null}}const so="npmPackageSearch";function oo(r){r.registerTool(so,{description:"Search NPM packages using 'npm search' command. Discover packages by functionality keywords and explore alternatives.\n\n**WHEN TO USE**: Use when users ask questions about npm packages or need to discover packages - provides package discovery and ecosystem insights.\n\n**KEY INSIGHTS**:\n- Another code search mechanism for npm packages (along github repository search)\n- Repo discovery by npm packages search\n- Package descriptions, keywords, and version information\n- Can be used undesrsant npm depndencies better\n\n**SEARCH STRATEGY**:\n- Use broad functional terms for best discovery\n- Single keywords work better than complex phrases\n- Multiple searches reveal ecosystem alternatives\n- Combine with npm_view_package for detailed analysis of discovered packages",inputSchema:{queries:e.union([e.string(),e.array(e.string())]).describe('Search terms for NPM packages (e.g., "react hooks", ["typescript", "eslint"], "data visualization"). Use functionality keywords rather than exact package names for best results.'),searchLimit:e.number().int().min(1).max(50).optional().default(20).describe("Results limit per query (1-50). Default: 20")},annotations:{title:"NPM Package Search",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0}},async e=>{try{const r=Array.isArray(e.queries)?e.queries:[e.queries],t=e.searchLimit||20,a=[];for(const e of r)try{const r=await ts("search",[e,`--searchlimit=${t}`,"--json"],{cache:!0});if(!r.isError&&r.content?.[0]?.text){const e=io(r.content[0].text);a.push(...e)}else r.isError}catch(e){}const s=function(e){const r=new Set;return e.filter(e=>!r.has(e.name)&&(r.add(e.name),!0))}(a);if(s.length>0){const{nextSteps:e}=qs(Fs,{hasResults:!0}),r=[];return e.length>0&&(r.push("Next steps:"),e.forEach(({tool:e,reason:t})=>{r.push(`• Use ${e} ${t}`)})),os({data:{total_count:s.length,results:s,hints:r.length>0?r:void 0}})}const o=r.some(e=>e.includes("-")||e.includes("@")||e.length>15),n=r.some(e=>["react","vue","angular","express","fastify"].some(r=>e.toLowerCase().includes(r)));let i=['• Try broader functional terms: "testing" instead of "jest-unit-test"',"• Remove version numbers or specific constraints",'• Use single keywords: "http" instead of "http-client-library"'];o&&(i=['• Use simpler terms: "validation" instead of "schema-validation-library"','• Try category terms: "database", "testing", "auth"',...i.slice(1)]),n&&i.unshift('• Try specific framework searches: "react hooks", "vue components"'),i.push("• Use github_search_repos with topic filters for project discovery"),i.push("• Check npm registry status: https://status.npmjs.org");const{fallback:c}=qs(Fs,{errorType:"no_results"}),l=Ns(Fs,c);return os({error:ws({baseError:Ss(r.join(", ")),suggestion:[i.join("\n"),l]})})}catch(e){const r=e instanceof Error?e.message:String(e);if(r.includes("network")||r.includes("timeout")||r.includes("ENOTFOUND")){const{fallback:e}=qs(Fs,{});return os({error:ws({baseError:"NPM registry connection failed",suggestion:["• Check internet connection and npm registry status","• Try fewer search terms to reduce load","• Retry in a few moments",Ns(Fs,e)]})})}if(r.includes("command not found")||r.includes("npm")){const{fallback:e}=qs(Fs,{});return os({error:ws({baseError:"NPM CLI issue detected",suggestion:["• Verify NPM installation: npm --version","• Update NPM: npm install -g npm@latest","• Check PATH environment variable",Ns(Fs,e)]})})}if(r.includes("permission")||r.includes("403")||r.includes("401")){const{fallback:e}=qs(Fs,{errorType:"access_denied"});return os({error:ws({baseError:"NPM permission issue",suggestion:["• Check npm login status: npm whoami","• Use public registry search without auth","• Verify npm registry configuration",Ns(Fs,e)]})})}const{fallback:t}=qs(Fs,{});return os({error:ws({baseError:ps,suggestion:[`Error details: ${r}`,"","Fallback strategies:","• Check npm status and retry","• Use broader search terms",Ns(Fs,t)]})})}})}function no(e){const r=e.description||null,t=r&&r.length>100?r.substring(0,100)+"...":r,a=(e.keywords||[]).slice(0,10);return{name:e.name||"",version:e.version||"",description:t,keywords:a,repository:e.links?.repository||e.repository?.url||null}}function io(e){try{const r=JSON.parse(e).result;let t=[];return Array.isArray(r)?t=r:r?.objects&&Array.isArray(r.objects)?t=r.objects.map(e=>e.package||e):r?.results&&Array.isArray(r.results)&&(t=r.results),t.map(no)}catch(e){return[]}}const co="githubViewRepoStructure";function lo(r){r.registerTool(co,{description:"Explore GitHub repository structure and validate repository access.\n\nPROJECT UNDERSTANDING:\n- Try to understand more by the structure of the project and the files in the project\n- Identify key directories and file patterns\n- fetch important files for better understanding\n\nIMPORTANT:\n- verify default branch (use main or master if can't find default branch)\n- verify path before calling the tool to avoid errors\n- Start with root path to understand actual repository structure and then navigate to specific directories based on research needs\n- Check repository's default branch as it varies between repositories\n- Verify path exists - don't assume repository structure\n- Verify repository existence and accessibility\n- Validate paths before accessing specific files. Use github search code to find correct paths if unsure\n\n",inputSchema:{owner:e.string().min(1).max(100).regex(/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$/,"Invalid GitHub username/org format").describe('Repository owner/organization name (e.g., "facebook", "microsoft"). Do NOT include repository name.'),repo:e.string().min(1).max(100).regex(/^[a-zA-Z0-9._-]+$/,"Invalid repository name format").describe("Repository name under a organization. "),branch:e.string().min(1).max(255).regex(/^[^\s]+$/,"Branch name cannot contain spaces").describe("Branch name. Default branch varies between repositories. Tool will automatically try default branch if specified branch is not found, but it is more efficient to verify the correct branch first."),path:e.string().optional().default("").refine(e=>!e.includes(".."),"Path traversal not allowed").refine(e=>e.length<=500,"Path too long").describe("Directory path within repository. Start with empty path to see actual repository structure first. Do not assume repository structure or nested paths exist. Do not start with slash. Verify path exists before using specific directories.")},annotations:{title:"GitHub Repository Explorer",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0}},async e=>{try{return await async function(e){return Ja(Ga("gh-repo-structure",e),async()=>{const{owner:r,repo:t,branch:a,path:s=""}=e;try{const e=s.startsWith("/")?s.substring(1):s,o=e?`/repos/${r}/${t}/contents/${e}?ref=${a}`:`/repos/${r}/${t}/contents?ref=${a}`,n=await as("api",[o],{cache:!1});if(!n.isError){const s=JSON.parse(n.content[0].text).result;return uo(r,t,a,e,Array.isArray(s)?s:[s])}const i=n.content[0].text,c=await as("api",[`/repos/${r}/${t}`],{cache:!1});if(c.isError)return function(e,r,t){return t.includes("404")?os({error:`Repository "${e}/${r}" not found. It might have been deleted, renamed, or made private. Use github_search_code to find current location.`}):t.includes("403")?os({error:`Repository "${e}/${r}" exists but access is denied. Repository might be private or archived. Use api_status_check to verify permissions.`}):os({error:`Failed to access repository "${e}/${r}": ${t}. Verify repository exists and is accessible.`})}(r,t,c.content[0].text);if(i.includes("404")){let s="main",o=!1;try{s=JSON.parse(c.content[0].text).default_branch||"main",o=!0}catch(e){}if(o&&s!==a){const a=`/repos/${r}/${t}/contents/${e}?ref=${s}`,o=await as("api",[a],{cache:!1});if(!o.isError){const a=JSON.parse(o.content[0].text).result;return uo(r,t,s,e,Array.isArray(a)?a:[a])}}const n=["main","master","develop"],i=[a];o&&i.push(s);for(const a of n){if(i.includes(a))continue;const s=`/repos/${r}/${t}/contents/${e}?ref=${a}`,o=await as("api",[s],{cache:!1});if(i.push(a),!o.isError){const s=JSON.parse(o.content[0].text).result;return uo(r,t,a,e,Array.isArray(s)?s:[s])}}return function(e,r,t,a,s,o){const n=o?`\nRepository default branch: "${s}"`:"\nCould not determine default branch - repository info unavailable";return os(t?{error:`Path "${t}" not found in any branch (tried: ${a.join(", ")}).${n}\n\nQuick solution: Use the correct branch name:\n{"owner": "${e}", "repo": "${r}", "branch": "${s}", "path": "${t}"}\n\nAlternative solutions:\n• Search for path: github_search_code with query="path:${t}" owner="${e}"\n• Search for directory: github_search_code with query="${t.split("/").pop()}" owner="${e}"\n• Check root structure: github_view_repo_structure with {"owner": "${e}", "repo": "${r}", "branch": "${s}", "path": ""}`}:{error:`Repository "${e}/${r}" structure not accessible in any branch (tried: ${a.join(", ")}).${n}\n\nRepository might be empty, private, or you might not have sufficient permissions.\n\nAlternative solutions:\n• Verify permissions: api_status_check\n• Search accessible repos: github_search_code with owner="${e}"\n• Try different branch: github_view_repo_structure with {"owner": "${e}", "repo": "${r}", "branch": "${s}", "path": ""}`})}(r,t,e,i,s,o)}return function(e,r,t){return t.includes("403")||t.includes("Forbidden")?os({error:`Access denied to "${e}/${r}". Repository exists but might be private/archived. Use api_status_check to verify permissions, or github_search_code with owner="${e}" to find accessible repositories.`}):os({error:`Failed to access "${e}/${r}": ${t}. Check network connection and repository permissions.`})}(r,t,i)}catch(e){return os({error:`Failed to access repository "${r}/${t}": ${e instanceof Error?e.message:String(e)}. Verify repository name, permissions, and network connection.`})}})}(e)}catch(e){return os({error:`Failed to explore repository. ${e instanceof Error?e.message:"Unknown error"}. Verify repository exists and is accessible`})}})}function uo(e,r,t,a,s){const o=s.slice(0,100);o.sort((e,r)=>e.type!==r.type?"dir"===e.type?-1:1:e.name.localeCompare(r.name));const n=o.filter(e=>"file"===e.type).map(e=>({name:e.name,size:e.size,url:e.path})),i=o.filter(e=>"dir"===e.type).map(e=>({name:e.name,url:e.path}));return os({data:{repository:`${e}/${r}`,branch:t,path:a||"/",githubBasePath:`https://api.github.com/repos/${e}/${r}/contents/`,files:{count:n.length,files:n},folders:{count:i.length,folders:i}}})}const po="githubSearchIssues";function ho(r){r.registerTool(po,{description:"Search GitHub issues for bug reports, feature requests, and discussions. Find issues by keywords, state, labels, author, or repository. Returns issue details including body content for effective issue tracking and analysis.",inputSchema:{query:e.string().min(1,"Search query is required and cannot be empty").describe('Search terms. Start simple: "error", "crash". Use quotes for exact phrases.'),owner:e.string().min(1).optional().describe('Repository owner/organization name only (e.g., "facebook", "microsoft"). Do NOT include repository name. Must be used with repo parameter for repository-specific searches.'),repo:e.string().optional().describe('Repository name only (e.g., "react", "vscode"). Do NOT include owner prefix. Must be used together with owner parameter.'),app:e.string().optional().describe("GitHub App that created the issue"),archived:e.boolean().optional().describe("Include archived repositories"),assignee:e.string().optional().describe("GitHub username of assignee"),author:e.string().optional().describe("GitHub username of issue creator"),closed:e.string().regex(/^(>=?\d{4}-\d{2}-\d{2}|<=?\d{4}-\d{2}-\d{2}|\d{4}-\d{2}-\d{2}\.\.\d{4}-\d{2}-\d{2}|\d{4}-\d{2}-\d{2})$/,'Invalid date format. Use: ">2020-01-01", ">=2020-01-01", "<2023-12-31", "<=2023-12-31", "2020-01-01..2023-12-31", or exact date "2023-01-01"').optional().describe('When closed. Format: ">2020-01-01" (after), ">=2020-01-01" (on or after), "<2023-12-31" (before), "2020-01-01..2023-12-31" (range)'),commenter:e.string().optional().describe("User who commented on issue"),comments:e.union([e.number().int().min(0),e.string().regex(/^(>=?\d+|<=?\d+|\d+\.\.\d+|\d+)$/,'Invalid format. Use: ">10", ">=5", "<20", "<=15", "5..20", or exact number "10"')]).optional().describe('Comment count filter. Format: ">10" (many comments), ">=5" (at least 5), "<5" (few comments), "5..10" (range), "10" (exact)'),created:e.string().regex(/^(>=?\d{4}-\d{2}-\d{2}|<=?\d{4}-\d{2}-\d{2}|\d{4}-\d{2}-\d{2}\.\.\d{4}-\d{2}-\d{2}|\d{4}-\d{2}-\d{2})$/,'Invalid date format. Use: ">2020-01-01", ">=2020-01-01", "<2023-12-31", "<=2023-12-31", "2020-01-01..2023-12-31", or exact date "2023-01-01"').optional().describe('When created. Format: ">2020-01-01" (after), ">=2020-01-01" (on or after), "<2023-12-31" (before), "2020-01-01..2023-12-31" (range)'),"include-prs":e.boolean().optional().describe("Include pull requests. Default: false"),interactions:e.union([e.number().int().min(0),e.string().regex(/^(>=?\d+|<=?\d+|\d+\.\.\d+|\d+)$/,'Invalid format. Use: ">100", ">=50", "<200", "<=150", "50..200", or exact number "100"')]).optional().describe('Total interactions (reactions + comments) filter. Format: ">100" (highly engaged), ">=50" (moderately engaged), "<20" (low engagement), "50..200" (range)'),involves:e.string().optional().describe("User involved in any way"),label:e.union([e.string(),e.array(e.string())]).optional().describe("Label names. Can be single string or array."),language:e.string().optional().describe("Repository language"),locked:e.boolean().optional().describe("Conversation locked status"),match:e.enum(["title","body","comments"]).optional().describe("Search scope. Default: title and body"),mentions:e.string().optional().describe("Issues mentioning this user"),milestone:e.string().optional().describe("Milestone name"),"no-assignee":e.boolean().optional().describe("Issues without assignee"),"no-label":e.boolean().optional().describe("Issues without labels"),"no-milestone":e.boolean().optional().describe("Issues without milestone"),"no-project":e.boolean().optional().describe("Issues not in projects"),project:e.string().optional().describe("Project board number"),reactions:e.union([e.number().int().min(0),e.string().regex(/^(>=?\d+|<=?\d+|\d+\.\.\d+|\d+)$/,'Invalid format. Use: ">10", ">=5", "<50", "<=25", "5..50", or exact number "10"')]).optional().describe('Reaction count filter. Format: ">10" (popular), ">=5" (some reactions), "<50" (moderate), "5..50" (range), "10" (exact)'),state:e.enum(["open","closed"]).optional().describe("Issue state. Default: all"),"team-mentions":e.string().optional().describe("Team mentioned in issue (@org/team-name)"),updated:e.string().regex(/^(>=?\d{4}-\d{2}-\d{2}|<=?\d{4}-\d{2}-\d{2}|\d{4}-\d{2}-\d{2}\.\.\d{4}-\d{2}-\d{2}|\d{4}-\d{2}-\d{2})$/,'Invalid date format. Use: ">2020-01-01", ">=2020-01-01", "<2023-12-31", "<=2023-12-31", "2020-01-01..2023-12-31", or exact date "2023-01-01"').optional().describe('When updated. Format: ">2020-01-01" (after), ">=2020-01-01" (on or after), "<2023-12-31" (before), "2020-01-01..2023-12-31" (range)'),visibility:e.enum(["public","private","internal"]).optional().describe("Repository visibility"),sort:e.enum(["comments","created","interactions","reactions","reactions-+1","reactions--1","reactions-heart","reactions-smile","reactions-tada","reactions-thinking_face","updated","best-match"]).optional().describe("Sort by activity or reactions. Default: best match"),order:e.enum(["asc","desc"]).optional().default("desc").describe("Sort order. Default: desc"),limit:e.number().int().min(1).max(50).optional().default(25).describe("Results limit (1-50). Default: 25")},annotations:{title:"GitHub Issues Search - Bug & Feature Discovery",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0}},async e=>{if(!e.query?.trim())return os({error:`${ms} ${gs}`});if(e.query.length>256)return os({error:hs});try{return await async function(e){return Ja(Ga("gh-issues",e),async()=>{const{command:r,args:t}=function(e){const r=["issues"];if(e.query?.trim()&&r.push(e.query.trim()),e.app&&r.push("--app",e.app),void 0!==e.archived&&r.push("--archived",e.archived.toString()),e.assignee&&r.push("--assignee",e.assignee),e.author&&r.push("--author",e.author),e.closed&&r.push("--closed",e.closed),e.commenter&&r.push("--commenter",e.commenter),e.comments&&r.push("--comments",e.comments.toString()),e.created&&r.push("--created",e.created),e["include-prs"]&&r.push("--include-prs"),e.interactions&&r.push("--interactions",e.interactions.toString()),e.involves&&r.push("--involves",e.involves),e.label){const t=Array.isArray(e.label)?e.label:[e.label];r.push("--label",t.join(","))}e.language&&r.push("--language",e.language),e.locked&&r.push("--locked"),e.match&&r.push("--match",e.match),e.mentions&&r.push("--mentions",e.mentions),e.milestone&&r.push("--milestone",e.milestone),e["no-assignee"]&&r.push("--no-assignee"),e["no-label"]&&r.push("--no-label"),e["no-milestone"]&&r.push("--no-milestone"),e["no-project"]&&r.push("--no-project"),e.owner&&e.repo?r.push("--repo",`${e.owner}/${e.repo}`):e.owner&&r.push("--owner",e.owner),e.project&&r.push("--project",e.project),e.reactions&&r.push("--reactions",e.reactions.toString()),e.state&&r.push("--state",e.state),e["team-mentions"]&&r.push("--team-mentions",e["team-mentions"]),e.updated&&r.push("--updated",e.updated),e.visibility&&r.push("--visibility",e.visibility),e.sort&&r.push("--sort",e.sort),e.order&&r.push("--order",e.order);const t=Math.min(e.limit||25,100);return r.push("--limit",t.toString()),r.push("--json","assignees,author,authorAssociation,closedAt,commentsCount,createdAt,id,isLocked,isPullRequest,labels,number,repository,state,title,updatedAt,url"),{command:"search",args:r}}(e),a=await as(r,t,{cache:!1});if(a.isError)return a;const s=JSON.parse(a.content[0].text).result,o=(Array.isArray(s)?s:s.items||[]).map(e=>{const r=e.repository?.nameWithOwner||e.repository?.full_name||"unknown",t=r.includes("/")?r.split("/")[1]:r;return{number:e.number,title:e.title,state:e.state,author:"string"==typeof e.author?{login:e.author}:{login:e.author?.login||"",id:e.author?.id,url:e.author?.url,type:e.author?.type,is_bot:e.author?.is_bot},repository:{name:t,nameWithOwner:r},labels:e.labels?.map(e=>"string"==typeof e?{name:e}:{name:e.name,color:e.color,description:e.description,id:e.id})||[],createdAt:e.createdAt||e.created_at,updatedAt:e.updatedAt||e.updated_at,url:e.url||e.html_url,commentsCount:e.commentsCount??e.comments??0,reactions:e.reactions?.total_count||0,created_at:ns(e.createdAt||e.created_at),updated_at:ns(e.updatedAt||e.updated_at)}}),n=await Promise.all(o.map(async e=>{try{const{nameWithOwner:r}=e.repository,[t,a]=r.split("/"),s=await as("api",[`/repos/${t}/${a}/issues/${e.number}`],{cache:!1});if(!s.isError){const r=JSON.parse(s.content[0].text).result;return{...e,body:r.body||"",assignees:r.assignees?.map(e=>({login:e.login,id:e.id?.toString(),url:e.html_url,type:e.type,is_bot:"Bot"===e.type}))||[],authorAssociation:r.author_association,closedAt:r.closed_at,isLocked:r.locked,author:r.user?{login:r.user.login,id:r.user.id?.toString(),url:r.user.html_url,type:r.user.type,is_bot:"Bot"===r.user.type}:e.author,labels:r.labels?.map(e=>({name:e.name,color:e.color,description:e.description,id:e.id?.toString()}))||e.labels,createdAt:r.created_at,updatedAt:r.updated_at,id:r.id?.toString(),isPullRequest:void 0!==r.pull_request,commentsCount:r.comments,closed_at:r.closed_at?ns(r.closed_at):void 0}}return{...e,body:""}}catch(r){return{...e,body:""}}}));if(0===n.length){const r=[];if("closed"===e.state&&r.push("• Try state:open or remove state filter"),e.author&&(r.push("• Remove author filter for broader search"),r.push(`• Use github_search_code to find ${e.author}'s contributions`)),e.label){const t=Array.isArray(e.label)?e.label:[e.label];r.push("• Try broader labels or remove label filter"),r.push(`• Search for label variations: ${t.map(e=>`"${e}"`).join(", ")}`)}return e.owner&&e.repo?(r.push("• Check repository name spelling"),r.push("• Use github_view_repo_structure to verify repository exists")):e.owner&&(r.push("• Remove owner filter for global search"),r.push("• Use github_search_repos to find organization repositories")),(e.created||e.updated)&&r.push("• Expand date range or remove date filters"),r.push("• Try broader search terms"),r.push("• Use github_search_pull_requests for related development activity"),r.push("• Use github_search_code to find implementation patterns"),os({error:`No issues found for query: "${e.query}"\n\nTry these alternatives:\n${r.join("\n")}\n\nDiscovery strategies:\n• Broader terms: "error" instead of "TypeError"\n• Remove filters: state, labels, author\n• Related searches: pull requests, code implementations`})}return os({data:{results:n}})})}(e)}catch(e){const r=e instanceof Error?e.message:"";return r.includes("authentication")?os({error:"GitHub authentication required - run api_status_check tool"}):r.includes("rate limit")?os({error:Ps(!1)}):os({error:Es("issues")})}})}const mo="npmViewPackage";function fo(r){r.registerTool(mo,{description:"View NPM package information using 'npm view' command. Supports field-specific queries and GitHub repository discovery.\n\n**WHEN TO USE**: Use when users ask questions about npm packages - provides comprehensive package data and insights.\n\n**KEY INSIGHTS**:\n- Git repository URL for source code exploration\n- Package exports structure (understand API surface and dependencies)\n- Dependencies/devDependencies for ecosystem analysis\n- Version history, size, performance metrics\n- License and author information\n\n**CAPABILITIES**:\n- Full package info: npm view <package> --json (optimized format)\n- Single field: npm view <package> <field> (version, description, license)\n- Multiple fields: filtered JSON response for specific fields\n- Repository URLs for GitHub integration and source code analysis",inputSchema:{packageName:e.string().min(1).describe('NPM package name (e.g., "react", "express", "@types/node"). Include @ prefix for scoped packages.'),field:e.string().optional().describe('Optional field to get specific information (e.g., "version", "description", "license"). If not provided, returns full package info.'),match:e.union([e.enum(["version","description","license","author","homepage","repository","dependencies","devDependencies","keywords","main","scripts","engines","files","publishConfig","dist-tags","time"]),e.array(e.enum(["version","description","license","author","homepage","repository","dependencies","devDependencies","keywords","main","scripts","engines","files","publishConfig","dist-tags","time"]))]).optional().describe('Specific field(s) to retrieve. Can be single field or array of fields. Examples: "version", ["version", "description"], ["dependencies", "devDependencies"]. When used, returns only the specified fields. use repository to get the repository url in github')},annotations:{title:"NPM Package Analyzer",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0}},async e=>{try{const r=await async function(e,r,t){return Ja(Ga("npm-view",{packageName:e,field:r,match:t}),async()=>{try{const t=r?[e,r]:[e,"--json"];return await ts("view",t,{cache:!1})}catch(e){return(e.message||"").includes("404")?os({error:"Package not found on NPM registry. Verify the exact package name"}):os({error:"Failed to execute NPM command. Check npm installation"})}})}(e.packageName,e.field,e.match);if(r.isError)return r;if(e.field){const t=r.content[0].text,a=JSON.parse(t).result;return os({data:{field:e.field,value:a,package:e.packageName}})}if(e.match){const t=JSON.parse(r.content[0].text).result,a=Array.isArray(e.match)?e.match:[e.match],s={};return a.forEach(e=>{void 0!==t[e]&&(s[e]=t[e])}),os({data:{package:e.packageName,fields:a,values:s}})}const t=function(e){const r=e.repository?.url||e.repositoryGitUrl||"",t=r?is(r):"",a=e.exports?function(e){if("string"==typeof e)return{main:e};if("object"==typeof e){const r={};if(e["."]){const t=e["."];"string"==typeof t?r.main=t:t.default?r.main=t.default:t.import&&(r.main=t.import)}(e["./types"]||e["."]&&"object"==typeof e["."]&&e["."].types)&&(r.types=e["./types"]||e["."].types);let t=0;for(const[a,s]of Object.entries(e))t>=3||"."===a||"./types"===a||a.includes("package.json")||a.includes("node_modules")||(r[a]="object"==typeof s&&s.default||s,t++);return r}return{main:"index.js"}}(e.exports):void 0,s=e.time||{},o=Array.isArray(e.versions)?e.versions:[],n=o.slice(-5).map(e=>({version:e,date:s[e]?ns(s[e]):"Unknown"})),i={name:e.name,version:e.version,description:e.description||"",license:e.license||"Unknown",repository:t,size:cs(e.dist?.unpackedSize||0),created:s.created?ns(s.created):"Unknown",updated:s.modified?ns(s.modified):"Unknown",versions:n,stats:{total_versions:o.length,weekly_downloads:e.weeklyDownloads}};return a&&Object.keys(a).length>0&&(i.exports=a),i}(JSON.parse(r.content[0].text).result);return os({data:t})}catch(r){const t=r.message||"";if(t.includes("not found")||t.includes("404")){const r=e.packageName,t=e.field?` (field: ${e.field})`:"",a=e.match?` (match: ${Array.isArray(e.match)?e.match.join(", "):e.match})`:"",s=t||a,o=[];return r.includes("_")&&o.push(`• Try with dashes: "${r.replace(/_/g,"-")}"`),r.includes("-")&&o.push(`• Try without dashes: "${r.replace(/-/g,"")}"`),!r.startsWith("@")&&r.includes("/")&&o.push(`• Try scoped package: "@${r}"`),r.startsWith("@")&&o.push(`• Try without scope: "${r.split("/")[1]}"`),e.field&&(o.push("• Try without field parameter to get full package info"),o.push("• Common fields: version, description, license, dependencies")),e.match&&(o.push("• Try without match parameter to get full package info"),o.push('• Try single field instead of multiple: field: "version"'),o.push("• Common fields: version, description, license, dependencies")),o.push("• Use npm_package_search for discovery"),o.push("• Use github_search_repos to find source repository"),o.push("• Check exact spelling on npmjs.com"),os({error:`Package "${r}"${s} not found on NPM registry.\n\nTry these alternatives:\n${o.join("\n")}\n\nDiscovery workflow:\n1. Use npm_package_search with functional terms\n2. Use github_search_repos for related projects\n3. Verify exact package name on npmjs.com`})}return t.includes("network")||t.includes("timeout")||t.includes("ENOTFOUND")?os({error:`NPM registry connection failed. Alternative strategies:\n• Check internet connection and npm registry status\n• Use github_search_repos to find package repository\n• Try npm_package_search for broader discovery\n• Visit https://npmjs.com/${e.packageName} directly\n• Retry in a few moments`}):t.includes("command not found")||t.includes("npm")?os({error:`NPM CLI issue. Quick fixes:\n• Verify NPM installation: npm --version\n• Update NPM: npm install -g npm@latest \n• Use github_search_repos to find package repository\n• Check PATH environment variable\n• Try web interface: https://npmjs.com/${e.packageName}`}):t.includes("permission")||t.includes("403")||t.includes("401")?os({error:`NPM registry access issue. Try these solutions:\n• Check npm configuration: npm config get registry\n• Use public registry: npm config set registry https://registry.npmjs.org/\n• Try github_search_repos for package source code\n• Visit package page: https://npmjs.com/${e.packageName}`}):os({error:`Failed to fetch package "${e.packageName}": ${t}\n\nFallback strategies:\n• Use npm_package_search for similar packages\n• Use github_search_repos with package name as query\n• Check package on web: https://npmjs.com/${e.packageName}\n• Verify npm status: https://status.npmjs.org\n• Try alternative package managers (yarn info, pnpm view)`})}})}const go={name:"octocode-mcp",version:"1.0.0",description:"You are an expert code research assistant specialized in using gh cli and npm cli to search for code and repositories for insights, research, analysis and code generation.\nUse all tools to their full potential and be able to use them in a chain to get the best results.\n\nCORE RESEARCH PHILOSOPHY:\n Understand the user's prompt and the context of the prompt\n Plan multi-tool sequences before execution\n Build comprehensive understanding progressively\n Provide actionable insights based on data patterns\n Get quality data from the most relevant sources\n WHen creating new code or docs be smart and don't just copy-paste areas\n Never make up data or information and don't hallucinate and don't use sensitive data or information\n Readr docs and implementaion files to understand patterns and best practices\n Be able to explain, generate code, generate docs and have quality context to be able to imply users prompts\n If not sure ask the user for more information or ask the user to provide more details or research directions\n Always give references (repo, file, line number..) and actual examples\n Check for quality data and repositories. Be critical for quality and accuracy of code and docs\n\nCORE FLOW PHILOSOPHY:\n Review all tools and use them efficiently\n PACKAGE-FIRST: When packages mentioned → start with NPM tools to bridge to GitHub\n CROSS-REFERENCE: Always connect packages to repositories and repositories to packages\n PROGRESSIVE: Start broad, refine gradually, use multiple separate searches\n TOKEN-EFFICIENT: Use partial file access by default, full files only when necessary\n\nNo Results Strategy:\n See error messages with suggestions\n BROADEN search terms (remove filters). be more specific.\n Try ALTERNATIVE tools and see error messages for more information for fallbacks "};(async function(){try{const e=new Ha(go);!function(e){const r=[{name:Ds,fn:Ls},{name:Us,fn:zs},{name:Bs,fn:Gs},{name:Ks,fn:Ws},{name:Xs,fn:eo},{name:ro,fn:to},{name:so,fn:oo},{name:co,fn:lo},{name:po,fn:ho},{name:mo,fn:fo}];let t=0;for(const a of r)try{a.fn(e),t++}catch(e){}if(0===t)throw new Error("No tools were successfully registered")}(e);const r=new Za;await e.connect(r),process.stdout.uncork(),process.stderr.uncork();const t=async()=>{try{Ba.flushAll(),await Promise.race([e.close(),new Promise((e,r)=>setTimeout(()=>r(new Error("Server close timeout")),5e3))]),process.exit(0)}catch(e){process.exit(1)}};process.on("SIGINT",t),process.on("SIGTERM",t),process.stdin.on("close",async()=>{await t()}),process.on("uncaughtException",()=>{t()}),process.on("unhandledRejection",()=>{t()}),process.stdin.resume()}catch(e){process.exit(1)}})().catch(()=>{process.exit(1)});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "octocode-mcp",
|
|
3
|
-
"version": "2.3.
|
|
3
|
+
"version": "2.3.20",
|
|
4
4
|
"description": "Model Context Protocol (MCP) server for advanced GitHub repository analysis, code discovery, and npm package exploration. Provides AI assistants with powerful tools to search, analyze, and understand codebases across GitHub and npm ecosystems.",
|
|
5
5
|
"author": "Guy Bary <guybary@gmail.com>",
|
|
6
6
|
"homepage": "https://octocode.ai",
|