@iflow-ai/iflow-cli 0.2.24-beta.1 → 0.2.24
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/bundle/iflow.js +7 -7
- package/package.json +1 -1
package/bundle/iflow.js
CHANGED
|
@@ -410,14 +410,14 @@ ${JSON.stringify(f,null,2)}`),f.usage&&(this.lastUsageMetadata={total_tokens:f.u
|
|
|
410
410
|
\u8FD9\u4E2A\u662F\u9519\u8BEF\u7684json\u683C\u5F0F\uFF1A
|
|
411
411
|
${e}
|
|
412
412
|
|
|
413
|
-
\u8BF7\u76F4\u63A5\u8F93\u51FA\u4E00\u4E2A\u6B63\u786E\u7684json\u683C\u5F0F\uFF1A`;try{let n=await fetch("https://apis.iflow.cn/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:"QWen3-4B",messages:[{role:"user",content:r}],temperature:.1,max_tokens:1e3})});if(!n.ok)throw new Error(`API error: ${n.status}`);let i=await n.json();if(!i||!i.choices||!Array.isArray(i.choices)||i.choices.length===0)throw new Error("Invalid response format - missing or empty choices array");let o=i.choices[0]?.message?.content;if(!o||typeof o!="string")throw new Error("Invalid response - missing or invalid message content");let s=o.trim();if(s.startsWith("```json")?s=s.replace(/^```json\s*/,"").replace(/\s*```$/,""):s.startsWith("```")&&(s=s.replace(/^```\s*/,"").replace(/\s*```$/,"")),!s)throw new Error("Fixed JSON is empty after processing");return JSON.parse(s)}catch(n){throw i5(n),console.error("QWen JSON fix failed:",n),n}}extractTextFromRequest(e){let r="";if(e.contents){let n=Array.isArray(e.contents)?e.contents:[e.contents];for(let i of n)if(i&&typeof i=="object"&&"parts"in i&&i.parts){let o=Array.isArray(i.parts)?i.parts:[i.parts];for(let s of o)if(s&&typeof s=="object"&&"text"in s&&s.text)r+=s.text+" ";else if(s.functionResponse&&s.functionResponse.response)for(let[a,c]of Object.entries(s.functionResponse.response))c!=null&&(r+=String(c)+" ")}}return r+=e.config?.systemInstruction,r.trim()}extractTextFromEmbedRequest(e){if(e.contents){let r=Array.isArray(e.contents)?e.contents:[e.contents];for(let n of r)if(typeof n=="object"&&n!==null&&"parts"in n&&n.parts){let i=Array.isArray(n.parts)?n.parts:[n.parts];for(let o of i)if(typeof o=="object"&&o!==null&&"text"in o&&o.text)return o.text}else{if(typeof n=="string")return n;if(typeof n=="object"&&n!==null&&"text"in n&&n.text)return n.text}}return""}extractSystemInstruction(e){let r="";if(typeof e=="string")r=e;else if(Array.isArray(e)){for(let n of e)typeof n=="object"&&n!==null&&"text"in n&&n.text&&(r+=n.text+" ");r=r.trim()}else if(typeof e=="object"&&e!==null)if("parts"in e&&e.parts){let n=Array.isArray(e.parts)?e.parts:[e.parts];for(let i of n)typeof i=="object"&&i!==null&&"text"in i&&i.text&&(r+=i.text+" ");r=r.trim()}else"text"in e&&e.text&&(r=e.text);return r}convertToOpenAITools(e){if(!e||e.length===0)return[];let r=[];for(let n of e)if(n.functionDeclarations&&Array.isArray(n.functionDeclarations))for(let i of n.functionDeclarations)r.push({type:"function",function:{name:i.name||"",description:i.description,parameters:this.convertParameters(i.parameters||i.parametersJsonSchema)}});return r}convertParameters(e){if(!e)return;let r={STRING:"string",INTEGER:"integer",NUMBER:"number",BOOLEAN:"boolean",OBJECT:"object",ARRAY:"array"};if(typeof e=="object"&&e.type){if(typeof e.type=="string"&&(r[e.type]?e.type=r[e.type]:e.type=e.type.toLowerCase()),e.properties)for(let i in e.properties){let o=e.properties[i],s={};o.type&&(s.type=r[o.type]),o.description&&(s.description=o.description),e.properties[i]=s}return e.items&&(e.items=this.convertParameters(e.items)),e}let n=i=>{if(!i)return;let o={};if(i.type)switch(i.type){case"STRING":o.type="string";break;case"INTEGER":o.type="integer";break;case"NUMBER":o.type="number";break;case"BOOLEAN":o.type="boolean";break;case"OBJECT":o.type="object";break;case"ARRAY":o.type="array";break;default:o.type=i.type.toLowerCase()}if(o.type="object",i.description&&(o.description=i.description),i.enum&&(o.enum=i.enum),i.properties){o.properties={};for(let[s,a]of Object.entries(i.properties))o.properties[s]=n(a)}return i.items&&(o.items=n(i.items)),i.required&&(o.required=i.required),o};return n(e)}mapFinishReason(e){switch(e){case"stop":return mw.STOP;case"length":return mw.MAX_TOKENS;case"content_filter":return mw.SAFETY;case"tool_calls":return mw.MALFORMED_FUNCTION_CALL;default:return mw.OTHER}}convertResponseSchema(e){if(e)return e.type==="object"||e.type==="OBJECT"?{type:"json_schema",json_schema:{name:e.name||"",description:e.description||"",schema:this.convertSchemaToJsonSchema(e),strict:!0}}:{type:"json_schema",json_schema:{name:"response_schema",description:"Generated response schema",schema:this.convertSchemaToJsonSchema(e),strict:!0}}}convertSchemaToJsonSchema(e){if(!e)return{};let r={};if(e.type)switch(e.type){case"STRING":r.type="string";break;case"INTEGER":r.type="integer";break;case"NUMBER":r.type="number";break;case"BOOLEAN":r.type="boolean";break;case"OBJECT":r.type="object";break;case"ARRAY":r.type="array";break;default:r.type=typeof e.type=="string"?e.type.toLowerCase():e.type}if(e.description&&(r.description=e.description),e.enum&&(r.enum=e.enum),e.properties){r.properties={};for(let[n,i]of Object.entries(e.properties))r.properties[n]=this.convertSchemaToJsonSchema(i)}return e.items&&(r.items=this.convertSchemaToJsonSchema(e.items)),e.required&&(r.required=e.required),r.type==="object"&&!("additionalProperties"in r)&&(r.additionalProperties=!1),r}}});var S3,ed,oq,sq,LX,o5=Ie(()=>{"use strict";S3="Qwen3-Coder",ed="Qwen3-Coder",oq="text-embedding-v1",sq="gemini-2.5-flash-lite",LX="https://apis.iflow.cn/v1"});async function qke(t,e,r,n){if(e===Ar.LOGIN_WITH_IFLOW){let i=await PB(e,r),o=await q8();if(!o)throw new Error("No API key found. Please re-authenticate.");let s=r.getContentGeneratorConfig();return new iq({model:r.getModel(),apiKey:o,baseUrl:s?.baseUrl||LX,authType:e,debugMode:r.getDebugMode(),multimodalModelName:"qwen-vl-max",config:r})}if(e===Ar.CLOUD_SHELL){let i=await PB(e,r),o=await DIt(i);return new C7(i,o.projectId,t,n,o.userTier)}throw new Error(`Unsupported authType: ${e}`)}var Hke=Ie(()=>{"use strict";N6();Ew();RIt();ghe();Qke();o5();});function Zbn(t){return t.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase()}function V8(t){let e=Zbn(t),r=`IFLOW_${t}`;if(process.env[r])return process.env[r];let n=`IFLOW_${e}`;if(process.env[n])return process.env[n];let i=`iflow_${t}`;if(process.env[i])return process.env[i];let o=`iflow_${e}`;if(process.env[o])return process.env[o]}function UX(){return V8("apiKey")}function QX(){return V8("baseUrl")||V8("url")}function qX(){return V8("modelName")||V8("model")}function YIt(t){let e=V8(t);if(e===void 0)return;let r=e.toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1}function JIt(t){let e=V8(t);if(e===void 0)return;let r=Number(e);return isNaN(r)?void 0:r}function KIt(t){let e=V8(t);if(e!==void 0)return e.split(",").map(r=>r.trim()).filter(r=>r.length>0)}function Bhe(){return!!(UX()||QX()||qX())}function Gke(){let t={},e=["theme","selectedAuthType","sandbox","toolDiscoveryCommand","toolCallCommand","mcpServerCommand","contextFileName","preferredEditor","apiKey","baseUrl","modelName","searchApiKey","multimodalModelName","memoryImportFormat"],r=["useExternalAuth","showMemoryUsage","usageStatisticsEnabled","autoConfigureMaxOldSpaceSize","hideWindowTitle","hideTips","hideBanner","vimMode","ideModeFeature","ideMode","disableAutoUpdate","skipNextSpeakerCheck","useRipgrep"],n=["maxSessionTurns","memoryDiscoveryMaxDirs","tokensLimit","compressionTokenThreshold","shellTimeout"],i=["coreTools","excludeTools","allowMCPServers","excludeMCPServers"];return e.forEach(o=>{let s=V8(o);s!==void 0&&(t[o]=s)}),r.forEach(o=>{let s=YIt(o);s!==void 0&&(t[o]=s)}),n.forEach(o=>{let s=JIt(o);s!==void 0&&(t[o]=s)}),i.forEach(o=>{let s=KIt(o);s!==void 0&&(t[o]=s)}),t}function e9n(){return{apiKey:UX(),baseUrl:QX(),model:qX()}}var Vke=Ie(()=>{"use strict";});async function $ke(t,e,r){await XQ()&&(await mhe()||console.log("OAuth2 credentials cleared due to expiration. Please authenticate when prompted."));let i=process.env.GEMINI_API_KEY,o=process.env.GOOGLE_API_KEY,s=process.env.GOOGLE_CLOUD_PROJECT,a=process.env.GOOGLE_CLOUD_LOCATION,c=UX(),u=QX(),f=qX(),d=r?.apiKey||c,p=r?.baseUrl||u||t9n[e],h=t.getModel()||f||S3,g={model:h,authType:e,proxy:t?.getProxy(),debugMode:t?.getDebugMode(),config:t};return e===Ar.CLOUD_SHELL?g:e===Ar.LOGIN_WITH_IFLOW?(g.baseUrl=p||LX,g.multimodalModelName="qwen-vl-max",g):([...q1,Ar.OPENAI_COMPATIBLE].includes(e)&&d&&(g.apiKey=d,g.baseUrl=p,g.model=h),g)}async function Wke(t,e,r){let i={headers:{"User-Agent":`iFlowCLI/0.2.24-beta.1 (${process.platform}; ${process.arch})`}};if(t.authType&&[...q1,Ar.IDEA_LAB].includes(t.authType)||t.authType===Ar.OPENAI_COMPATIBLE)return new iq({...t,config:e});if(t.authType===Ar.LOGIN_WITH_IFLOW||t.authType===Ar.CLOUD_SHELL)return qke(i,t.authType,e,r);if([...q1,Ar.OPENAI_COMPATIBLE].includes(t.authType)||t.authType===Ar.USE_GEMINI||t.authType===Ar.USE_VERTEX_AI)return new ohe({apiKey:t.apiKey===""?void 0:t.apiKey,vertexai:t.vertexai,httpOptions:i}).models;throw new Error(`Error creating contentGenerator: Unsupported authType: ${t.authType}`)}var Ar,q1,t9n,N6=Ie(()=>{"use strict";Kl();Hke();o5();Qke();Vke();Ew();(function(t){t.LOGIN_WITH_IFLOW="oauth-iflow",t.USE_GEMINI="gemini-api-key",t.USE_VERTEX_AI="vertex-ai",t.CLOUD_SHELL="cloud-shell",t.IFLOW="iflow",t.IDEA_LAB="idealab",t.OPENAI_COMPATIBLE="openai-compatible"})(Ar||(Ar={}));q1=[Ar.IFLOW],t9n={[Ar.IDEA_LAB]:"https://idealab.alibaba-inc.com/api/openai/v1",[Ar.IFLOW]:LX}});var Nhe,XIt=Ie(()=>{"use strict";Nhe=class{prompts=new Map;registerPrompt(e){if(this.prompts.has(e.name)){let r=`${e.serverName}_${e.name}`;console.warn(`Prompt with name "${e.name}" is already registered. Renaming to "${r}".`),this.prompts.set(r,{...e,name:r})}else this.prompts.set(e.name,e)}getAllPrompts(){return Array.from(this.prompts.values()).sort((e,r)=>e.name.localeCompare(r.name))}getPrompt(e){return this.prompts.get(e)}getPromptsByServer(e){let r=[];for(let n of this.prompts.values())n.serverName===e&&r.push(n);return r.sort((n,i)=>n.name.localeCompare(i.name))}clear(){this.prompts.clear()}removePromptsByServer(e){for(let[r,n]of this.prompts.entries())n.serverName===e&&this.prompts.delete(r)}}});var jo,fn,zo,Yo,wf=Ie(()=>{"use strict";jo=class{name;displayName;description;icon;kind;parameterSchema;isOutputMarkdown;canUpdateOutput;aliases;constructor(e,r,n,i,o,s,a=!0,c=!1,u=[]){this.name=e,this.displayName=r,this.description=n,this.icon=i,this.kind=o,this.parameterSchema=s,this.isOutputMarkdown=a,this.canUpdateOutput=c,this.aliases=u}get schema(){return{name:this.name,description:this.description,parameters:this.parameterSchema}}validateToolParams(e){return null}getDescription(e){return JSON.stringify(e)}shouldConfirmExecute(e,r){return Promise.resolve(!1)}toolLocations(e){return[]}};(function(t){t.ProceedOnce="proceed_once",t.ProceedAlways="proceed_always",t.ProceedAlwaysServer="proceed_always_server",t.ProceedAlwaysTool="proceed_always_tool",t.ModifyWithEditor="modify_with_editor",t.Cancel="cancel"})(fn||(fn={}));(function(t){t.FileSearch="fileSearch",t.Folder="folder",t.Globe="globe",t.Hammer="hammer",t.LightBulb="lightBulb",t.Pencil="pencil",t.Regex="regex",t.Terminal="terminal"})(zo||(zo={}));(function(t){t.Read="read",t.Edit="edit",t.Delete="delete",t.Move="move",t.Search="search",t.Execute="execute",t.Think="think",t.Fetch="fetch",t.Other="other"})(Yo||(Yo={}))});function qB(t,e){let r=new WeakSet;return JSON.stringify(t,(n,i)=>{if(typeof i=="object"&&i!==null){if(r.has(i))return"[Circular]";r.add(i)}return i},e)}var Ohe=Ie(()=>{"use strict";});var Ic,Mhe=Ie(()=>{"use strict";(function(t){t.INVALID_TOOL_PARAMS="invalid_tool_params",t.UNKNOWN="unknown",t.UNHANDLED_EXCEPTION="unhandled_exception",t.TOOL_NOT_REGISTERED="tool_not_registered",t.EXECUTION_FAILED="execution_failed",t.FILE_NOT_FOUND="file_not_found",t.FILE_WRITE_FAILURE="file_write_failure",t.READ_CONTENT_FAILURE="read_content_failure",t.ATTEMPT_TO_CREATE_EXISTING_FILE="attempt_to_create_existing_file",t.FILE_TOO_LARGE="file_too_large",t.PERMISSION_DENIED="permission_denied",t.NO_SPACE_LEFT="no_space_left",t.TARGET_IS_DIRECTORY="target_is_directory",t.PATH_NOT_IN_WORKSPACE="path_not_in_workspace",t.SEARCH_PATH_NOT_FOUND="search_path_not_found",t.SEARCH_PATH_NOT_A_DIRECTORY="search_path_not_a_directory",t.EDIT_PREPARATION_FAILURE="edit_preparation_failure",t.EDIT_NO_OCCURRENCE_FOUND="edit_no_occurrence_found",t.EDIT_EXPECTED_OCCURRENCE_MISMATCH="edit_expected_occurrence_mismatch",t.EDIT_NO_CHANGE="edit_no_change",t.GLOB_EXECUTION_ERROR="glob_execution_error",t.GREP_EXECUTION_ERROR="grep_execution_error",t.LS_EXECUTION_ERROR="ls_execution_error",t.PATH_IS_NOT_A_DIRECTORY="path_is_not_a_directory",t.MCP_TOOL_ERROR="mcp_tool_error",t.MEMORY_TOOL_EXECUTION_ERROR="memory_tool_execution_error",t.READ_MANY_FILES_SEARCH_ERROR="read_many_files_search_error",t.DISCOVERED_TOOL_EXECUTION_ERROR="discovered_tool_execution_error",t.WEB_FETCH_NO_URL_IN_PROMPT="web_fetch_no_url_in_prompt",t.WEB_FETCH_FALLBACK_FAILED="web_fetch_fallback_failed",t.WEB_FETCH_PROCESSING_ERROR="web_fetch_processing_error",t.WEB_SEARCH_FAILED="web_search_failed"})(Ic||(Ic={}))});function r9n(t){return{text:t.text}}function n9n(t,e){return[{text:`[Tool '${e}' provided the following ${t.type} data with mime-type: ${t.mimeType}]`},{inlineData:{mimeType:t.mimeType,data:t.data}}]}function i9n(t,e){let r=t.resource;if(r?.text)return{text:r.text};if(r?.blob){let n=r.mimeType||"application/octet-stream";return[{text:`[Tool '${e}' provided the following embedded resource with mime-type: ${n}]`},{inlineData:{mimeType:n,data:r.blob}}]}return null}function o9n(t){return{text:`Resource Link: ${t.title||t.name} at ${t.uri}`}}function s9n(t){let e=t?.[0]?.functionResponse,r=e?.response?.content,n=e?.name||"unknown tool";return Array.isArray(r)?r.flatMap(o=>{switch(o.type){case"text":return r9n(o);case"image":case"audio":return n9n(o,n);case"resource":return i9n(o,n);case"resource_link":return o9n(o);default:return null}}).filter(o=>o!==null):[{text:"[Error: Could not parse tool response]"}]}function a9n(t){let e=t?.[0]?.functionResponse?.response?.content;return Array.isArray(e)?e.map(n=>{switch(n.type){case"text":return n.text;case"image":return`[Image: ${n.mimeType}]`;case"audio":return`[Audio: ${n.mimeType}]`;case"resource_link":return`[Link to ${n.title||n.name}: ${n.uri}]`;case"resource":return n.resource?.text?n.resource.text:`[Embedded Resource: ${n.resource?.mimeType||"unknown type"}]`;default:return`[Unknown content type: ${n.type}]`}}).join(`
|
|
413
|
+
\u8BF7\u76F4\u63A5\u8F93\u51FA\u4E00\u4E2A\u6B63\u786E\u7684json\u683C\u5F0F\uFF1A`;try{let n=await fetch("https://apis.iflow.cn/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:"QWen3-4B",messages:[{role:"user",content:r}],temperature:.1,max_tokens:1e3})});if(!n.ok)throw new Error(`API error: ${n.status}`);let i=await n.json();if(!i||!i.choices||!Array.isArray(i.choices)||i.choices.length===0)throw new Error("Invalid response format - missing or empty choices array");let o=i.choices[0]?.message?.content;if(!o||typeof o!="string")throw new Error("Invalid response - missing or invalid message content");let s=o.trim();if(s.startsWith("```json")?s=s.replace(/^```json\s*/,"").replace(/\s*```$/,""):s.startsWith("```")&&(s=s.replace(/^```\s*/,"").replace(/\s*```$/,"")),!s)throw new Error("Fixed JSON is empty after processing");return JSON.parse(s)}catch(n){throw i5(n),console.error("QWen JSON fix failed:",n),n}}extractTextFromRequest(e){let r="";if(e.contents){let n=Array.isArray(e.contents)?e.contents:[e.contents];for(let i of n)if(i&&typeof i=="object"&&"parts"in i&&i.parts){let o=Array.isArray(i.parts)?i.parts:[i.parts];for(let s of o)if(s&&typeof s=="object"&&"text"in s&&s.text)r+=s.text+" ";else if(s.functionResponse&&s.functionResponse.response)for(let[a,c]of Object.entries(s.functionResponse.response))c!=null&&(r+=String(c)+" ")}}return r+=e.config?.systemInstruction,r.trim()}extractTextFromEmbedRequest(e){if(e.contents){let r=Array.isArray(e.contents)?e.contents:[e.contents];for(let n of r)if(typeof n=="object"&&n!==null&&"parts"in n&&n.parts){let i=Array.isArray(n.parts)?n.parts:[n.parts];for(let o of i)if(typeof o=="object"&&o!==null&&"text"in o&&o.text)return o.text}else{if(typeof n=="string")return n;if(typeof n=="object"&&n!==null&&"text"in n&&n.text)return n.text}}return""}extractSystemInstruction(e){let r="";if(typeof e=="string")r=e;else if(Array.isArray(e)){for(let n of e)typeof n=="object"&&n!==null&&"text"in n&&n.text&&(r+=n.text+" ");r=r.trim()}else if(typeof e=="object"&&e!==null)if("parts"in e&&e.parts){let n=Array.isArray(e.parts)?e.parts:[e.parts];for(let i of n)typeof i=="object"&&i!==null&&"text"in i&&i.text&&(r+=i.text+" ");r=r.trim()}else"text"in e&&e.text&&(r=e.text);return r}convertToOpenAITools(e){if(!e||e.length===0)return[];let r=[];for(let n of e)if(n.functionDeclarations&&Array.isArray(n.functionDeclarations))for(let i of n.functionDeclarations)r.push({type:"function",function:{name:i.name||"",description:i.description,parameters:this.convertParameters(i.parameters||i.parametersJsonSchema)}});return r}convertParameters(e){if(!e)return;let r={STRING:"string",INTEGER:"integer",NUMBER:"number",BOOLEAN:"boolean",OBJECT:"object",ARRAY:"array"};if(typeof e=="object"&&e.type){if(typeof e.type=="string"&&(r[e.type]?e.type=r[e.type]:e.type=e.type.toLowerCase()),e.properties)for(let i in e.properties){let o=e.properties[i],s={};o.type&&(s.type=r[o.type]),o.description&&(s.description=o.description),e.properties[i]=s}return e.items&&(e.items=this.convertParameters(e.items)),e}let n=i=>{if(!i)return;let o={};if(i.type)switch(i.type){case"STRING":o.type="string";break;case"INTEGER":o.type="integer";break;case"NUMBER":o.type="number";break;case"BOOLEAN":o.type="boolean";break;case"OBJECT":o.type="object";break;case"ARRAY":o.type="array";break;default:o.type=i.type.toLowerCase()}if(o.type="object",i.description&&(o.description=i.description),i.enum&&(o.enum=i.enum),i.properties){o.properties={};for(let[s,a]of Object.entries(i.properties))o.properties[s]=n(a)}return i.items&&(o.items=n(i.items)),i.required&&(o.required=i.required),o};return n(e)}mapFinishReason(e){switch(e){case"stop":return mw.STOP;case"length":return mw.MAX_TOKENS;case"content_filter":return mw.SAFETY;case"tool_calls":return mw.MALFORMED_FUNCTION_CALL;default:return mw.OTHER}}convertResponseSchema(e){if(e)return e.type==="object"||e.type==="OBJECT"?{type:"json_schema",json_schema:{name:e.name||"",description:e.description||"",schema:this.convertSchemaToJsonSchema(e),strict:!0}}:{type:"json_schema",json_schema:{name:"response_schema",description:"Generated response schema",schema:this.convertSchemaToJsonSchema(e),strict:!0}}}convertSchemaToJsonSchema(e){if(!e)return{};let r={};if(e.type)switch(e.type){case"STRING":r.type="string";break;case"INTEGER":r.type="integer";break;case"NUMBER":r.type="number";break;case"BOOLEAN":r.type="boolean";break;case"OBJECT":r.type="object";break;case"ARRAY":r.type="array";break;default:r.type=typeof e.type=="string"?e.type.toLowerCase():e.type}if(e.description&&(r.description=e.description),e.enum&&(r.enum=e.enum),e.properties){r.properties={};for(let[n,i]of Object.entries(e.properties))r.properties[n]=this.convertSchemaToJsonSchema(i)}return e.items&&(r.items=this.convertSchemaToJsonSchema(e.items)),e.required&&(r.required=e.required),r.type==="object"&&!("additionalProperties"in r)&&(r.additionalProperties=!1),r}}});var S3,ed,oq,sq,LX,o5=Ie(()=>{"use strict";S3="Qwen3-Coder",ed="Qwen3-Coder",oq="text-embedding-v1",sq="gemini-2.5-flash-lite",LX="https://apis.iflow.cn/v1"});async function qke(t,e,r,n){if(e===Ar.LOGIN_WITH_IFLOW){let i=await PB(e,r),o=await q8();if(!o)throw new Error("No API key found. Please re-authenticate.");let s=r.getContentGeneratorConfig();return new iq({model:r.getModel(),apiKey:o,baseUrl:s?.baseUrl||LX,authType:e,debugMode:r.getDebugMode(),multimodalModelName:"qwen-vl-max",config:r})}if(e===Ar.CLOUD_SHELL){let i=await PB(e,r),o=await DIt(i);return new C7(i,o.projectId,t,n,o.userTier)}throw new Error(`Unsupported authType: ${e}`)}var Hke=Ie(()=>{"use strict";N6();Ew();RIt();ghe();Qke();o5();});function Zbn(t){return t.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase()}function V8(t){let e=Zbn(t),r=`IFLOW_${t}`;if(process.env[r])return process.env[r];let n=`IFLOW_${e}`;if(process.env[n])return process.env[n];let i=`iflow_${t}`;if(process.env[i])return process.env[i];let o=`iflow_${e}`;if(process.env[o])return process.env[o]}function UX(){return V8("apiKey")}function QX(){return V8("baseUrl")||V8("url")}function qX(){return V8("modelName")||V8("model")}function YIt(t){let e=V8(t);if(e===void 0)return;let r=e.toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1}function JIt(t){let e=V8(t);if(e===void 0)return;let r=Number(e);return isNaN(r)?void 0:r}function KIt(t){let e=V8(t);if(e!==void 0)return e.split(",").map(r=>r.trim()).filter(r=>r.length>0)}function Bhe(){return!!(UX()||QX()||qX())}function Gke(){let t={},e=["theme","selectedAuthType","sandbox","toolDiscoveryCommand","toolCallCommand","mcpServerCommand","contextFileName","preferredEditor","apiKey","baseUrl","modelName","searchApiKey","multimodalModelName","memoryImportFormat"],r=["useExternalAuth","showMemoryUsage","usageStatisticsEnabled","autoConfigureMaxOldSpaceSize","hideWindowTitle","hideTips","hideBanner","vimMode","ideModeFeature","ideMode","disableAutoUpdate","skipNextSpeakerCheck","useRipgrep"],n=["maxSessionTurns","memoryDiscoveryMaxDirs","tokensLimit","compressionTokenThreshold","shellTimeout"],i=["coreTools","excludeTools","allowMCPServers","excludeMCPServers"];return e.forEach(o=>{let s=V8(o);s!==void 0&&(t[o]=s)}),r.forEach(o=>{let s=YIt(o);s!==void 0&&(t[o]=s)}),n.forEach(o=>{let s=JIt(o);s!==void 0&&(t[o]=s)}),i.forEach(o=>{let s=KIt(o);s!==void 0&&(t[o]=s)}),t}function e9n(){return{apiKey:UX(),baseUrl:QX(),model:qX()}}var Vke=Ie(()=>{"use strict";});async function $ke(t,e,r){await XQ()&&(await mhe()||console.log("OAuth2 credentials cleared due to expiration. Please authenticate when prompted."));let i=process.env.GEMINI_API_KEY,o=process.env.GOOGLE_API_KEY,s=process.env.GOOGLE_CLOUD_PROJECT,a=process.env.GOOGLE_CLOUD_LOCATION,c=UX(),u=QX(),f=qX(),d=r?.apiKey||c,p=r?.baseUrl||u||t9n[e],h=t.getModel()||f||S3,g={model:h,authType:e,proxy:t?.getProxy(),debugMode:t?.getDebugMode(),config:t};return e===Ar.CLOUD_SHELL?g:e===Ar.LOGIN_WITH_IFLOW?(g.baseUrl=p||LX,g.multimodalModelName="qwen-vl-max",g):([...q1,Ar.OPENAI_COMPATIBLE].includes(e)&&d&&(g.apiKey=d,g.baseUrl=p,g.model=h),g)}async function Wke(t,e,r){let i={headers:{"User-Agent":`iFlowCLI/0.2.24 (${process.platform}; ${process.arch})`}};if(t.authType&&[...q1,Ar.IDEA_LAB].includes(t.authType)||t.authType===Ar.OPENAI_COMPATIBLE)return new iq({...t,config:e});if(t.authType===Ar.LOGIN_WITH_IFLOW||t.authType===Ar.CLOUD_SHELL)return qke(i,t.authType,e,r);if([...q1,Ar.OPENAI_COMPATIBLE].includes(t.authType)||t.authType===Ar.USE_GEMINI||t.authType===Ar.USE_VERTEX_AI)return new ohe({apiKey:t.apiKey===""?void 0:t.apiKey,vertexai:t.vertexai,httpOptions:i}).models;throw new Error(`Error creating contentGenerator: Unsupported authType: ${t.authType}`)}var Ar,q1,t9n,N6=Ie(()=>{"use strict";Kl();Hke();o5();Qke();Vke();Ew();(function(t){t.LOGIN_WITH_IFLOW="oauth-iflow",t.USE_GEMINI="gemini-api-key",t.USE_VERTEX_AI="vertex-ai",t.CLOUD_SHELL="cloud-shell",t.IFLOW="iflow",t.IDEA_LAB="idealab",t.OPENAI_COMPATIBLE="openai-compatible"})(Ar||(Ar={}));q1=[Ar.IFLOW],t9n={[Ar.IDEA_LAB]:"https://idealab.alibaba-inc.com/api/openai/v1",[Ar.IFLOW]:LX}});var Nhe,XIt=Ie(()=>{"use strict";Nhe=class{prompts=new Map;registerPrompt(e){if(this.prompts.has(e.name)){let r=`${e.serverName}_${e.name}`;console.warn(`Prompt with name "${e.name}" is already registered. Renaming to "${r}".`),this.prompts.set(r,{...e,name:r})}else this.prompts.set(e.name,e)}getAllPrompts(){return Array.from(this.prompts.values()).sort((e,r)=>e.name.localeCompare(r.name))}getPrompt(e){return this.prompts.get(e)}getPromptsByServer(e){let r=[];for(let n of this.prompts.values())n.serverName===e&&r.push(n);return r.sort((n,i)=>n.name.localeCompare(i.name))}clear(){this.prompts.clear()}removePromptsByServer(e){for(let[r,n]of this.prompts.entries())n.serverName===e&&this.prompts.delete(r)}}});var jo,fn,zo,Yo,wf=Ie(()=>{"use strict";jo=class{name;displayName;description;icon;kind;parameterSchema;isOutputMarkdown;canUpdateOutput;aliases;constructor(e,r,n,i,o,s,a=!0,c=!1,u=[]){this.name=e,this.displayName=r,this.description=n,this.icon=i,this.kind=o,this.parameterSchema=s,this.isOutputMarkdown=a,this.canUpdateOutput=c,this.aliases=u}get schema(){return{name:this.name,description:this.description,parameters:this.parameterSchema}}validateToolParams(e){return null}getDescription(e){return JSON.stringify(e)}shouldConfirmExecute(e,r){return Promise.resolve(!1)}toolLocations(e){return[]}};(function(t){t.ProceedOnce="proceed_once",t.ProceedAlways="proceed_always",t.ProceedAlwaysServer="proceed_always_server",t.ProceedAlwaysTool="proceed_always_tool",t.ModifyWithEditor="modify_with_editor",t.Cancel="cancel"})(fn||(fn={}));(function(t){t.FileSearch="fileSearch",t.Folder="folder",t.Globe="globe",t.Hammer="hammer",t.LightBulb="lightBulb",t.Pencil="pencil",t.Regex="regex",t.Terminal="terminal"})(zo||(zo={}));(function(t){t.Read="read",t.Edit="edit",t.Delete="delete",t.Move="move",t.Search="search",t.Execute="execute",t.Think="think",t.Fetch="fetch",t.Other="other"})(Yo||(Yo={}))});function qB(t,e){let r=new WeakSet;return JSON.stringify(t,(n,i)=>{if(typeof i=="object"&&i!==null){if(r.has(i))return"[Circular]";r.add(i)}return i},e)}var Ohe=Ie(()=>{"use strict";});var Ic,Mhe=Ie(()=>{"use strict";(function(t){t.INVALID_TOOL_PARAMS="invalid_tool_params",t.UNKNOWN="unknown",t.UNHANDLED_EXCEPTION="unhandled_exception",t.TOOL_NOT_REGISTERED="tool_not_registered",t.EXECUTION_FAILED="execution_failed",t.FILE_NOT_FOUND="file_not_found",t.FILE_WRITE_FAILURE="file_write_failure",t.READ_CONTENT_FAILURE="read_content_failure",t.ATTEMPT_TO_CREATE_EXISTING_FILE="attempt_to_create_existing_file",t.FILE_TOO_LARGE="file_too_large",t.PERMISSION_DENIED="permission_denied",t.NO_SPACE_LEFT="no_space_left",t.TARGET_IS_DIRECTORY="target_is_directory",t.PATH_NOT_IN_WORKSPACE="path_not_in_workspace",t.SEARCH_PATH_NOT_FOUND="search_path_not_found",t.SEARCH_PATH_NOT_A_DIRECTORY="search_path_not_a_directory",t.EDIT_PREPARATION_FAILURE="edit_preparation_failure",t.EDIT_NO_OCCURRENCE_FOUND="edit_no_occurrence_found",t.EDIT_EXPECTED_OCCURRENCE_MISMATCH="edit_expected_occurrence_mismatch",t.EDIT_NO_CHANGE="edit_no_change",t.GLOB_EXECUTION_ERROR="glob_execution_error",t.GREP_EXECUTION_ERROR="grep_execution_error",t.LS_EXECUTION_ERROR="ls_execution_error",t.PATH_IS_NOT_A_DIRECTORY="path_is_not_a_directory",t.MCP_TOOL_ERROR="mcp_tool_error",t.MEMORY_TOOL_EXECUTION_ERROR="memory_tool_execution_error",t.READ_MANY_FILES_SEARCH_ERROR="read_many_files_search_error",t.DISCOVERED_TOOL_EXECUTION_ERROR="discovered_tool_execution_error",t.WEB_FETCH_NO_URL_IN_PROMPT="web_fetch_no_url_in_prompt",t.WEB_FETCH_FALLBACK_FAILED="web_fetch_fallback_failed",t.WEB_FETCH_PROCESSING_ERROR="web_fetch_processing_error",t.WEB_SEARCH_FAILED="web_search_failed"})(Ic||(Ic={}))});function r9n(t){return{text:t.text}}function n9n(t,e){return[{text:`[Tool '${e}' provided the following ${t.type} data with mime-type: ${t.mimeType}]`},{inlineData:{mimeType:t.mimeType,data:t.data}}]}function i9n(t,e){let r=t.resource;if(r?.text)return{text:r.text};if(r?.blob){let n=r.mimeType||"application/octet-stream";return[{text:`[Tool '${e}' provided the following embedded resource with mime-type: ${n}]`},{inlineData:{mimeType:n,data:r.blob}}]}return null}function o9n(t){return{text:`Resource Link: ${t.title||t.name} at ${t.uri}`}}function s9n(t){let e=t?.[0]?.functionResponse,r=e?.response?.content,n=e?.name||"unknown tool";return Array.isArray(r)?r.flatMap(o=>{switch(o.type){case"text":return r9n(o);case"image":case"audio":return n9n(o,n);case"resource":return i9n(o,n);case"resource_link":return o9n(o);default:return null}}).filter(o=>o!==null):[{text:"[Error: Could not parse tool response]"}]}function a9n(t){let e=t?.[0]?.functionResponse?.response?.content;return Array.isArray(e)?e.map(n=>{switch(n.type){case"text":return n.text;case"image":return`[Image: ${n.mimeType}]`;case"audio":return`[Audio: ${n.mimeType}]`;case"resource_link":return`[Link to ${n.title||n.name}: ${n.uri}]`;case"resource":return n.resource?.text?n.resource.text:`[Embedded Resource: ${n.resource?.mimeType||"unknown type"}]`;default:return`[Unknown content type: ${n.type}]`}}).join(`
|
|
414
414
|
`):"```json\n"+JSON.stringify(t,null,2)+"\n```"}function ZIt(t){let e=t.replace(/[^a-zA-Z0-9_.-]/g,"_");return e.length>63&&(e=e.slice(0,28)+"___"+e.slice(-32)),e}var nm,HX=Ie(()=>{"use strict";Ohe();Mhe();wf();Kl();nm=class t extends jo{mcpTool;serverName;serverToolName;parameterSchemaJson;timeout;trust;static allowlist=new Set;constructor(e,r,n,i,o,s,a,c){super(c??ZIt(n),`${n} (${r} MCP Server)`,i,zo.Hammer,Yo.Other,{type:ir.OBJECT},!0,!1),this.mcpTool=e,this.serverName=r,this.serverToolName=n,this.parameterSchemaJson=o,this.timeout=s,this.trust=a}asFullyQualifiedTool(){return new t(this.mcpTool,this.serverName,this.serverToolName,this.description,this.parameterSchemaJson,this.timeout,this.trust,`${this.serverName}__${this.serverToolName}`)}get schema(){return{name:this.name,description:this.description,parametersJsonSchema:this.parameterSchemaJson}}async shouldConfirmExecute(e,r){let n=this.serverName,i=`${this.serverName}.${this.serverToolName}`;return this.trust||t.allowlist.has(n)||t.allowlist.has(i)?!1:{type:"mcp",title:"Confirm MCP Tool Execution",serverName:this.serverName,toolName:this.serverToolName,toolDisplayName:this.name,onConfirm:async s=>{s===fn.ProceedAlwaysServer?t.allowlist.add(n):s===fn.ProceedAlwaysTool&&t.allowlist.add(i)}}}isMCPToolError(e){let n=e?.[0]?.functionResponse?.response;if(n){let i=n?.error,o=i?.isError;if(i&&(o===!0||o==="true"))return!0}return!1}async execute(e){let{callId:r,...n}=e,i=[{name:this.serverToolName,args:n}],o=await this.mcpTool.callTool(i);if(this.isMCPToolError(o)){let a=`MCP tool '${this.serverToolName}' reported tool error for function call: ${qB(i[0])} with response: ${qB(o)}`;return{llmContent:a,returnDisplay:`Error: MCP tool '${this.serverToolName}' reported an error.`,error:{message:a,type:Ic.MCP_TOOL_ERROR}}}return{llmContent:s9n(o),returnDisplay:a9n(o)}}}});var tDt=N((R_o,eDt)=>{"use strict";eDt.exports=function(e){return e.map(function(r){return r===""?"''":r&&typeof r=="object"?r.op.replace(/(.)/g,"\\$1"):/["\s\\]/.test(r)&&!/'/.test(r)?"'"+r.replace(/(['])/g,"\\$1")+"'":/["'\s]/.test(r)?'"'+r.replace(/(["\\$`!])/g,"\\$1")+'"':String(r).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g,"$1\\$2")}).join(" ")}});var lDt=N((B_o,aDt)=>{"use strict";var sDt="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",rDt=new RegExp("^"+sDt+"$"),nDt="|&;()<> \\t",l9n='"((\\\\"|[^"])*?)"',c9n="'((\\\\'|[^'])*?)'",u9n=/^#$/,iDt="'",oDt='"',jke="$",HB="",f9n=4294967296;for(zke=0;zke<4;zke++)HB+=(f9n*Math.random()).toString(16);var zke,d9n=new RegExp("^"+HB);function p9n(t,e){for(var r=e.lastIndex,n=[],i;i=e.exec(t);)n.push(i),e.lastIndex===i.index&&(e.lastIndex+=1);return e.lastIndex=r,n}function h9n(t,e,r){var n=typeof t=="function"?t(r):t[r];return typeof n>"u"&&r!=""?n="":typeof n>"u"&&(n="$"),typeof n=="object"?e+HB+JSON.stringify(n)+HB:e+n}function m9n(t,e,r){r||(r={});var n=r.escape||"\\",i="(\\"+n+`['"`+nDt+`]|[^\\s'"`+nDt+"])+",o=new RegExp(["("+sDt+")","("+i+"|"+l9n+"|"+c9n+")+"].join("|"),"g"),s=p9n(t,o);if(s.length===0)return[];e||(e={});var a=!1;return s.map(function(c){var u=c[0];if(!u||a)return;if(rDt.test(u))return{op:u};var f=!1,d=!1,p="",h=!1,g;function A(){g+=1;var S,x,T=u.charAt(g);if(T==="{"){if(g+=1,u.charAt(g)==="}")throw new Error("Bad substitution: "+u.slice(g-2,g+1));if(S=u.indexOf("}",g),S<0)throw new Error("Bad substitution: "+u.slice(g));x=u.slice(g,S),g=S}else if(/[*@#?$!_-]/.test(T))x=T,g+=1;else{var B=u.slice(g);S=B.match(/[^\w\d_]/),S?(x=B.slice(0,S.index),g+=S.index-1):(x=B,g=u.length)}return h9n(e,"",x)}for(g=0;g<u.length;g++){var y=u.charAt(g);if(h=h||!f&&(y==="*"||y==="?"),d)p+=y,d=!1;else if(f)y===f?f=!1:f==iDt?p+=y:y===n?(g+=1,y=u.charAt(g),y===oDt||y===n||y===jke?p+=y:p+=n+y):y===jke?p+=A():p+=y;else if(y===oDt||y===iDt)f=y;else{if(rDt.test(y))return{op:u};if(u9n.test(y)){a=!0;var v={comment:t.slice(c.index+g+1)};return p.length?[p,v]:[v]}else y===n?d=!0:y===jke?p+=A():p+=y}}return h?{op:"glob",pattern:p}:p}).reduce(function(c,u){return typeof u>"u"?c:c.concat(u)},[])}aDt.exports=function(e,r,n){var i=m9n(e,r,n);return typeof r!="function"?i:i.reduce(function(o,s){if(typeof s=="object")return o.concat(s);var a=s.split(RegExp("("+HB+".*?"+HB+")","g"));return a.length===1?o.concat(a[0]):o.concat(a.filter(Boolean).map(function(c){return d9n.test(c)?JSON.parse(c.split(HB)[1]):c}))},[])}});var khe=N(Yke=>{"use strict";Yke.quote=tDt();Yke.parse=lDt()});var Ws,Jke,yn,$8,GX=Ie(()=>{(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},t.getValidEnumValues=i=>{let o=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return t.objectValues(s)},t.objectValues=i=>t.objectKeys(i).map(function(o){return i[o]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},t.find=(i,o)=>{for(let s of i)if(o(s))return s},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(Ws||(Ws={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Jke||(Jke={}));yn=Ws.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),$8=t=>{switch(typeof t){case"undefined":return yn.undefined;case"string":return yn.string;case"number":return Number.isNaN(t)?yn.nan:yn.number;case"boolean":return yn.boolean;case"function":return yn.function;case"bigint":return yn.bigint;case"symbol":return yn.symbol;case"object":return Array.isArray(t)?yn.array:t===null?yn.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?yn.promise:typeof Map<"u"&&t instanceof Map?yn.map:typeof Set<"u"&&t instanceof Set?yn.set:typeof Date<"u"&&t instanceof Date?yn.date:yn.object;default:return yn.unknown}}});var Pr,g9n,H1,Fhe=Ie(()=>{GX();Pr=Ws.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),g9n=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),H1=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,c=0;for(;c<s.path.length;){let u=s.path[c];c===s.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(s))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return i(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ws.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};H1.create=t=>new H1(t)});var A9n,_7,Kke=Ie(()=>{Fhe();GX();A9n=(t,e)=>{let r;switch(t.code){case Pr.invalid_type:t.received===yn.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case Pr.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Ws.jsonStringifyReplacer)}`;break;case Pr.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ws.joinValues(t.keys,", ")}`;break;case Pr.invalid_union:r="Invalid input";break;case Pr.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ws.joinValues(t.options)}`;break;case Pr.invalid_enum_value:r=`Invalid enum value. Expected ${Ws.joinValues(t.options)}, received '${t.received}'`;break;case Pr.invalid_arguments:r="Invalid function arguments";break;case Pr.invalid_return_type:r="Invalid function return type";break;case Pr.invalid_date:r="Invalid date";break;case Pr.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:Ws.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case Pr.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case Pr.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case Pr.custom:r="Invalid input";break;case Pr.invalid_intersection_types:r="Intersection results could not be merged";break;case Pr.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case Pr.not_finite:r="Number must be finite";break;default:r=e.defaultError,Ws.assertNever(t)}return{message:r}},_7=A9n});function y9n(t){cDt=t}function aq(){return cDt}var cDt,Phe=Ie(()=>{Kke();cDt=_7});function ln(t,e){let r=aq(),n=VX({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===_7?void 0:_7].filter(i=>!!i)});t.common.issues.push(n)}var VX,E9n,im,Hi,GB,eg,Lhe,Uhe,Cw,lq,Xke=Ie(()=>{Phe();Kke();VX=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,o=[...r,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(s,{data:e,defaultError:a}).message;return{...i,path:o,message:a}},E9n=[];im=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return Hi;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return Hi;o.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:e.value,value:n}}},Hi=Object.freeze({status:"aborted"}),GB=t=>({status:"dirty",value:t}),eg=t=>({status:"valid",value:t}),Lhe=t=>t.status==="aborted",Uhe=t=>t.status==="dirty",Cw=t=>t.status==="valid",lq=t=>typeof Promise<"u"&&t instanceof Promise});var uDt=Ie(()=>{});var Zn,fDt=Ie(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Zn||(Zn={}))});function os(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(s,a)=>{let{message:c}=t;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}function mDt(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function F9n(t){return new RegExp(`^${mDt(t)}$`)}function gDt(t){let e=`${hDt}T${mDt(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function P9n(t,e){return!!((e==="v4"||!e)&&D9n.test(t)||(e==="v6"||!e)&&B9n.test(t))}function L9n(t,e){if(!x9n.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function U9n(t,e){return!!((e==="v4"||!e)&&R9n.test(t)||(e==="v6"||!e)&&N9n.test(t))}function Q9n(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(t.toFixed(i).replace(".","")),s=Number.parseInt(e.toFixed(i).replace(".",""));return o%s/10**i}function cq(t){if(t instanceof G1){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=O6.create(cq(n))}return new G1({...t._def,shape:()=>e})}else return t instanceof w7?new w7({...t._def,type:cq(t.element)}):t instanceof O6?O6.create(cq(t.unwrap())):t instanceof j8?j8.create(cq(t.unwrap())):t instanceof W8?W8.create(t.items.map(e=>cq(e))):t}function eFe(t,e){let r=$8(t),n=$8(e);if(t===e)return{valid:!0,data:t};if(r===yn.object&&n===yn.object){let i=Ws.objectKeys(e),o=Ws.objectKeys(t).filter(a=>i.indexOf(a)!==-1),s={...t,...e};for(let a of o){let c=eFe(t[a],e[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===yn.array&&n===yn.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let o=0;o<t.length;o++){let s=t[o],a=e[o],c=eFe(s,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===yn.date&&n===yn.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function ADt(t,e){return new eN({values:t,typeName:Xi.ZodEnum,...os(e)})}function pDt(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function yDt(t,e={},r){return t?_w.create().superRefine((n,i)=>{let o=t(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=pDt(e,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=pDt(e,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):_w.create()}var M6,dDt,ys,v9n,C9n,b9n,_9n,S9n,x9n,w9n,T9n,I9n,Zke,D9n,R9n,B9n,N9n,O9n,M9n,hDt,k9n,bw,VB,$B,WB,jB,uq,zB,YB,_w,x7,s5,fq,w7,G1,JB,S7,Qhe,KB,W8,qhe,dq,pq,Hhe,XB,ZB,eN,tN,Sw,k6,O6,j8,rN,nN,hq,q9n,$X,WX,iN,H9n,Xi,G9n,EDt,vDt,V9n,$9n,CDt,W9n,j9n,z9n,Y9n,J9n,K9n,X9n,Z9n,e7n,t7n,r7n,n7n,i7n,o7n,s7n,a7n,l7n,c7n,u7n,f7n,d7n,p7n,h7n,m7n,g7n,A7n,y7n,E7n,v7n,C7n,b7n,_7n,S7n,x7n,bDt=Ie(()=>{Fhe();Phe();fDt();Xke();GX();M6=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},dDt=(t,e)=>{if(Cw(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new H1(t.common.issues);return this._error=r,this._error}}};ys=class{get description(){return this._def.description}_getType(e){return $8(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:$8(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new im,ctx:{common:e.parent.common,data:e.data,parsedType:$8(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(lq(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:$8(e)},i=this._parseSync({data:e,path:n.path,parent:n});return dDt(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:$8(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Cw(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Cw(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:$8(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(lq(i)?i:Promise.resolve(i));return dDt(n,o)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let s=e(i),a=()=>o.addIssue({code:Pr.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(c=>c?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new k6({schema:this,typeName:Xi.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return O6.create(this,this._def)}nullable(){return j8.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return w7.create(this)}promise(){return Sw.create(this,this._def)}or(e){return JB.create([this,e],this._def)}and(e){return KB.create(this,e,this._def)}transform(e){return new k6({...os(this._def),schema:this,typeName:Xi.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new rN({...os(this._def),innerType:this,defaultValue:r,typeName:Xi.ZodDefault})}brand(){return new $X({typeName:Xi.ZodBranded,type:this,...os(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new nN({...os(this._def),innerType:this,catchValue:r,typeName:Xi.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return WX.create(this,e)}readonly(){return iN.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},v9n=/^c[^\s-]{8,}$/i,C9n=/^[0-9a-z]+$/,b9n=/^[0-9A-HJKMNP-TV-Z]{26}$/i,_9n=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,S9n=/^[a-z0-9_-]{21}$/i,x9n=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,w9n=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,T9n=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,I9n="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",D9n=/^(?:(?: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])$/,R9n=/^(?:(?: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])$/,B9n=/^(([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]))$/,N9n=/^(([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])$/,O9n=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,M9n=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,hDt="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",k9n=new RegExp(`^${hDt}$`);bw=class t extends ys{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==yn.string){let o=this._getOrReturnCtx(e);return ln(o,{code:Pr.invalid_type,expected:yn.string,received:o.parsedType}),Hi}let n=new im,i;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),ln(i,{code:Pr.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(i=this._getOrReturnCtx(e,i),ln(i,{code:Pr.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=e.data.length>o.value,a=e.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(e,i),s?ln(i,{code:Pr.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&ln(i,{code:Pr.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")T9n.test(e.data)||(i=this._getOrReturnCtx(e,i),ln(i,{validation:"email",code:Pr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Zke||(Zke=new RegExp(I9n,"u")),Zke.test(e.data)||(i=this._getOrReturnCtx(e,i),ln(i,{validation:"emoji",code:Pr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")_9n.test(e.data)||(i=this._getOrReturnCtx(e,i),ln(i,{validation:"uuid",code:Pr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")S9n.test(e.data)||(i=this._getOrReturnCtx(e,i),ln(i,{validation:"nanoid",code:Pr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")v9n.test(e.data)||(i=this._getOrReturnCtx(e,i),ln(i,{validation:"cuid",code:Pr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")C9n.test(e.data)||(i=this._getOrReturnCtx(e,i),ln(i,{validation:"cuid2",code:Pr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")b9n.test(e.data)||(i=this._getOrReturnCtx(e,i),ln(i,{validation:"ulid",code:Pr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),ln(i,{validation:"url",code:Pr.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),ln(i,{validation:"regex",code:Pr.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(e,i),ln(i,{code:Pr.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(i=this._getOrReturnCtx(e,i),ln(i,{code:Pr.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),ln(i,{code:Pr.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?gDt(o).test(e.data)||(i=this._getOrReturnCtx(e,i),ln(i,{code:Pr.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?k9n.test(e.data)||(i=this._getOrReturnCtx(e,i),ln(i,{code:Pr.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?F9n(o).test(e.data)||(i=this._getOrReturnCtx(e,i),ln(i,{code:Pr.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?w9n.test(e.data)||(i=this._getOrReturnCtx(e,i),ln(i,{validation:"duration",code:Pr.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?P9n(e.data,o.version)||(i=this._getOrReturnCtx(e,i),ln(i,{validation:"ip",code:Pr.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?L9n(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),ln(i,{validation:"jwt",code:Pr.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?U9n(e.data,o.version)||(i=this._getOrReturnCtx(e,i),ln(i,{validation:"cidr",code:Pr.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?O9n.test(e.data)||(i=this._getOrReturnCtx(e,i),ln(i,{validation:"base64",code:Pr.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?M9n.test(e.data)||(i=this._getOrReturnCtx(e,i),ln(i,{validation:"base64url",code:Pr.invalid_string,message:o.message}),n.dirty()):Ws.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:Pr.invalid_string,...Zn.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Zn.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Zn.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Zn.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Zn.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Zn.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Zn.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Zn.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Zn.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Zn.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Zn.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Zn.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Zn.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Zn.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Zn.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Zn.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Zn.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...Zn.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...Zn.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...Zn.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...Zn.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...Zn.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...Zn.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...Zn.errToObj(r)})}nonempty(e){return this.min(1,Zn.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};bw.create=t=>new bw({checks:[],typeName:Xi.ZodString,coerce:t?.coerce??!1,...os(t)});VB=class t extends ys{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==yn.number){let o=this._getOrReturnCtx(e);return ln(o,{code:Pr.invalid_type,expected:yn.number,received:o.parsedType}),Hi}let n,i=new im;for(let o of this._def.checks)o.kind==="int"?Ws.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),ln(n,{code:Pr.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),ln(n,{code:Pr.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),ln(n,{code:Pr.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?Q9n(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),ln(n,{code:Pr.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),ln(n,{code:Pr.not_finite,message:o.message}),i.dirty()):Ws.assertNever(o);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,Zn.toString(r))}gt(e,r){return this.setLimit("min",e,!1,Zn.toString(r))}lte(e,r){return this.setLimit("max",e,!0,Zn.toString(r))}lt(e,r){return this.setLimit("max",e,!1,Zn.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:Zn.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Zn.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Zn.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Zn.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Zn.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Zn.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:Zn.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:Zn.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Zn.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Zn.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Ws.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};VB.create=t=>new VB({checks:[],typeName:Xi.ZodNumber,coerce:t?.coerce||!1,...os(t)});$B=class t extends ys{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==yn.bigint)return this._getInvalidInput(e);let n,i=new im;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),ln(n,{code:Pr.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),ln(n,{code:Pr.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),ln(n,{code:Pr.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):Ws.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return ln(r,{code:Pr.invalid_type,expected:yn.bigint,received:r.parsedType}),Hi}gte(e,r){return this.setLimit("min",e,!0,Zn.toString(r))}gt(e,r){return this.setLimit("min",e,!1,Zn.toString(r))}lte(e,r){return this.setLimit("max",e,!0,Zn.toString(r))}lt(e,r){return this.setLimit("max",e,!1,Zn.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:Zn.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Zn.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Zn.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Zn.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Zn.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:Zn.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};$B.create=t=>new $B({checks:[],typeName:Xi.ZodBigInt,coerce:t?.coerce??!1,...os(t)});WB=class extends ys{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==yn.boolean){let n=this._getOrReturnCtx(e);return ln(n,{code:Pr.invalid_type,expected:yn.boolean,received:n.parsedType}),Hi}return eg(e.data)}};WB.create=t=>new WB({typeName:Xi.ZodBoolean,coerce:t?.coerce||!1,...os(t)});jB=class t extends ys{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==yn.date){let o=this._getOrReturnCtx(e);return ln(o,{code:Pr.invalid_type,expected:yn.date,received:o.parsedType}),Hi}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return ln(o,{code:Pr.invalid_date}),Hi}let n=new im,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),ln(i,{code:Pr.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(i=this._getOrReturnCtx(e,i),ln(i,{code:Pr.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Ws.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:Zn.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:Zn.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};jB.create=t=>new jB({checks:[],coerce:t?.coerce||!1,typeName:Xi.ZodDate,...os(t)});uq=class extends ys{_parse(e){if(this._getType(e)!==yn.symbol){let n=this._getOrReturnCtx(e);return ln(n,{code:Pr.invalid_type,expected:yn.symbol,received:n.parsedType}),Hi}return eg(e.data)}};uq.create=t=>new uq({typeName:Xi.ZodSymbol,...os(t)});zB=class extends ys{_parse(e){if(this._getType(e)!==yn.undefined){let n=this._getOrReturnCtx(e);return ln(n,{code:Pr.invalid_type,expected:yn.undefined,received:n.parsedType}),Hi}return eg(e.data)}};zB.create=t=>new zB({typeName:Xi.ZodUndefined,...os(t)});YB=class extends ys{_parse(e){if(this._getType(e)!==yn.null){let n=this._getOrReturnCtx(e);return ln(n,{code:Pr.invalid_type,expected:yn.null,received:n.parsedType}),Hi}return eg(e.data)}};YB.create=t=>new YB({typeName:Xi.ZodNull,...os(t)});_w=class extends ys{constructor(){super(...arguments),this._any=!0}_parse(e){return eg(e.data)}};_w.create=t=>new _w({typeName:Xi.ZodAny,...os(t)});x7=class extends ys{constructor(){super(...arguments),this._unknown=!0}_parse(e){return eg(e.data)}};x7.create=t=>new x7({typeName:Xi.ZodUnknown,...os(t)});s5=class extends ys{_parse(e){let r=this._getOrReturnCtx(e);return ln(r,{code:Pr.invalid_type,expected:yn.never,received:r.parsedType}),Hi}};s5.create=t=>new s5({typeName:Xi.ZodNever,...os(t)});fq=class extends ys{_parse(e){if(this._getType(e)!==yn.undefined){let n=this._getOrReturnCtx(e);return ln(n,{code:Pr.invalid_type,expected:yn.void,received:n.parsedType}),Hi}return eg(e.data)}};fq.create=t=>new fq({typeName:Xi.ZodVoid,...os(t)});w7=class t extends ys{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==yn.array)return ln(r,{code:Pr.invalid_type,expected:yn.array,received:r.parsedType}),Hi;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(ln(r,{code:s?Pr.too_big:Pr.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(ln(r,{code:Pr.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(ln(r,{code:Pr.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new M6(r,s,r.path,a)))).then(s=>im.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new M6(r,s,r.path,a)));return im.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:Zn.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:Zn.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:Zn.toString(r)}})}nonempty(e){return this.min(1,e)}};w7.create=(t,e)=>new w7({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Xi.ZodArray,...os(e)});G1=class t extends ys{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=Ws.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==yn.object){let u=this._getOrReturnCtx(e);return ln(u,{code:Pr.invalid_type,expected:yn.object,received:u.parsedType}),Hi}let{status:n,ctx:i}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof s5&&this._def.unknownKeys==="strip"))for(let u in i.data)s.includes(u)||a.push(u);let c=[];for(let u of s){let f=o[u],d=i.data[u];c.push({key:{status:"valid",value:u},value:f._parse(new M6(i,d,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof s5){let u=this._def.unknownKeys;if(u==="passthrough")for(let f of a)c.push({key:{status:"valid",value:f},value:{status:"valid",value:i.data[f]}});else if(u==="strict")a.length>0&&(ln(i,{code:Pr.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let f of a){let d=i.data[f];c.push({key:{status:"valid",value:f},value:u._parse(new M6(i,d,i.path,f)),alwaysSet:f in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let f of c){let d=await f.key,p=await f.value;u.push({key:d,value:p,alwaysSet:f.alwaysSet})}return u}).then(u=>im.mergeObjectSync(n,u)):im.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return Zn.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:Zn.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Xi.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of Ws.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of Ws.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return cq(this)}partial(e){let r={};for(let n of Ws.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of Ws.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof O6;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return ADt(Ws.objectKeys(this.shape))}};G1.create=(t,e)=>new G1({shape:()=>t,unknownKeys:"strip",catchall:s5.create(),typeName:Xi.ZodObject,...os(e)});G1.strictCreate=(t,e)=>new G1({shape:()=>t,unknownKeys:"strict",catchall:s5.create(),typeName:Xi.ZodObject,...os(e)});G1.lazycreate=(t,e)=>new G1({shape:t,unknownKeys:"strip",catchall:s5.create(),typeName:Xi.ZodObject,...os(e)});JB=class extends ys{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new H1(a.ctx.common.issues));return ln(r,{code:Pr.invalid_union,unionErrors:s}),Hi}if(r.common.async)return Promise.all(n.map(async o=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},f=c._parseSync({data:r.data,path:r.path,parent:u});if(f.status==="valid")return f;f.status==="dirty"&&!o&&(o={result:f,ctx:u}),u.common.issues.length&&s.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(c=>new H1(c));return ln(r,{code:Pr.invalid_union,unionErrors:a}),Hi}}get options(){return this._def.options}};JB.create=(t,e)=>new JB({options:t,typeName:Xi.ZodUnion,...os(e)});S7=t=>t instanceof XB?S7(t.schema):t instanceof k6?S7(t.innerType()):t instanceof ZB?[t.value]:t instanceof eN?t.options:t instanceof tN?Ws.objectValues(t.enum):t instanceof rN?S7(t._def.innerType):t instanceof zB?[void 0]:t instanceof YB?[null]:t instanceof O6?[void 0,...S7(t.unwrap())]:t instanceof j8?[null,...S7(t.unwrap())]:t instanceof $X||t instanceof iN?S7(t.unwrap()):t instanceof nN?S7(t._def.innerType):[],Qhe=class t extends ys{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==yn.object)return ln(r,{code:Pr.invalid_type,expected:yn.object,received:r.parsedType}),Hi;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(ln(r,{code:Pr.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Hi)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let o of r){let s=S7(o.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of s){if(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,o)}}return new t({typeName:Xi.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...os(n)})}};KB=class extends ys{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(o,s)=>{if(Lhe(o)||Lhe(s))return Hi;let a=eFe(o.value,s.value);return a.valid?((Uhe(o)||Uhe(s))&&r.dirty(),{status:r.value,value:a.data}):(ln(n,{code:Pr.invalid_intersection_types}),Hi)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};KB.create=(t,e,r)=>new KB({left:t,right:e,typeName:Xi.ZodIntersection,...os(r)});W8=class t extends ys{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==yn.array)return ln(n,{code:Pr.invalid_type,expected:yn.array,received:n.parsedType}),Hi;if(n.data.length<this._def.items.length)return ln(n,{code:Pr.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Hi;!this._def.rest&&n.data.length>this._def.items.length&&(ln(n,{code:Pr.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((s,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new M6(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>im.mergeArray(r,s)):im.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};W8.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new W8({items:t,typeName:Xi.ZodTuple,rest:null,...os(e)})};qhe=class t extends ys{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==yn.object)return ln(n,{code:Pr.invalid_type,expected:yn.object,received:n.parsedType}),Hi;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new M6(n,a,n.path,a)),value:s._parse(new M6(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?im.mergeObjectAsync(r,i):im.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ys?new t({keyType:e,valueType:r,typeName:Xi.ZodRecord,...os(n)}):new t({keyType:bw.create(),valueType:e,typeName:Xi.ZodRecord,...os(r)})}},dq=class extends ys{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==yn.map)return ln(n,{code:Pr.invalid_type,expected:yn.map,received:n.parsedType}),Hi;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new M6(n,a,n.path,[u,"key"])),value:o._parse(new M6(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of s){let u=await c.key,f=await c.value;if(u.status==="aborted"||f.status==="aborted")return Hi;(u.status==="dirty"||f.status==="dirty")&&r.dirty(),a.set(u.value,f.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of s){let u=c.key,f=c.value;if(u.status==="aborted"||f.status==="aborted")return Hi;(u.status==="dirty"||f.status==="dirty")&&r.dirty(),a.set(u.value,f.value)}return{status:r.value,value:a}}}};dq.create=(t,e,r)=>new dq({valueType:e,keyType:t,typeName:Xi.ZodMap,...os(r)});pq=class t extends ys{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==yn.set)return ln(n,{code:Pr.invalid_type,expected:yn.set,received:n.parsedType}),Hi;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(ln(n,{code:Pr.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(ln(n,{code:Pr.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function s(c){let u=new Set;for(let f of c){if(f.status==="aborted")return Hi;f.status==="dirty"&&r.dirty(),u.add(f.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new M6(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>s(c)):s(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:Zn.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:Zn.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};pq.create=(t,e)=>new pq({valueType:t,minSize:null,maxSize:null,typeName:Xi.ZodSet,...os(e)});Hhe=class t extends ys{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==yn.function)return ln(r,{code:Pr.invalid_type,expected:yn.function,received:r.parsedType}),Hi;function n(a,c){return VX({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,aq(),_7].filter(u=>!!u),issueData:{code:Pr.invalid_arguments,argumentsError:c}})}function i(a,c){return VX({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,aq(),_7].filter(u=>!!u),issueData:{code:Pr.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof Sw){let a=this;return eg(async function(...c){let u=new H1([]),f=await a._def.args.parseAsync(c,o).catch(h=>{throw u.addIssue(n(c,h)),u}),d=await Reflect.apply(s,this,f);return await a._def.returns._def.type.parseAsync(d,o).catch(h=>{throw u.addIssue(i(d,h)),u})})}else{let a=this;return eg(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new H1([n(c,u.error)]);let f=Reflect.apply(s,this,u.data),d=a._def.returns.safeParse(f,o);if(!d.success)throw new H1([i(f,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:W8.create(e).rest(x7.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||W8.create([]).rest(x7.create()),returns:r||x7.create(),typeName:Xi.ZodFunction,...os(n)})}},XB=class extends ys{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};XB.create=(t,e)=>new XB({getter:t,typeName:Xi.ZodLazy,...os(e)});ZB=class extends ys{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return ln(r,{received:r.data,code:Pr.invalid_literal,expected:this._def.value}),Hi}return{status:"valid",value:e.data}}get value(){return this._def.value}};ZB.create=(t,e)=>new ZB({value:t,typeName:Xi.ZodLiteral,...os(e)});eN=class t extends ys{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return ln(r,{expected:Ws.joinValues(n),received:r.parsedType,code:Pr.invalid_type}),Hi}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return ln(r,{received:r.data,code:Pr.invalid_enum_value,options:n}),Hi}return eg(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};eN.create=ADt;tN=class extends ys{_parse(e){let r=Ws.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==yn.string&&n.parsedType!==yn.number){let i=Ws.objectValues(r);return ln(n,{expected:Ws.joinValues(i),received:n.parsedType,code:Pr.invalid_type}),Hi}if(this._cache||(this._cache=new Set(Ws.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=Ws.objectValues(r);return ln(n,{received:n.data,code:Pr.invalid_enum_value,options:i}),Hi}return eg(e.data)}get enum(){return this._def.values}};tN.create=(t,e)=>new tN({values:t,typeName:Xi.ZodNativeEnum,...os(e)});Sw=class extends ys{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==yn.promise&&r.common.async===!1)return ln(r,{code:Pr.invalid_type,expected:yn.promise,received:r.parsedType}),Hi;let n=r.parsedType===yn.promise?r.data:Promise.resolve(r.data);return eg(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Sw.create=(t,e)=>new Sw({type:t,typeName:Xi.ZodPromise,...os(e)});k6=class extends ys{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Xi.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:s=>{ln(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return Hi;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?Hi:c.status==="dirty"?GB(c.value):r.value==="dirty"?GB(c.value):c});{if(r.value==="aborted")return Hi;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?Hi:a.status==="dirty"?GB(a.value):r.value==="dirty"?GB(a.value):a}}if(i.type==="refinement"){let s=a=>{let c=i.refinement(a,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?Hi:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?Hi:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Cw(s))return Hi;let a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>Cw(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):Hi);Ws.assertNever(i)}};k6.create=(t,e,r)=>new k6({schema:t,typeName:Xi.ZodEffects,effect:e,...os(r)});k6.createWithPreprocess=(t,e,r)=>new k6({schema:e,effect:{type:"preprocess",transform:t},typeName:Xi.ZodEffects,...os(r)});O6=class extends ys{_parse(e){return this._getType(e)===yn.undefined?eg(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};O6.create=(t,e)=>new O6({innerType:t,typeName:Xi.ZodOptional,...os(e)});j8=class extends ys{_parse(e){return this._getType(e)===yn.null?eg(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};j8.create=(t,e)=>new j8({innerType:t,typeName:Xi.ZodNullable,...os(e)});rN=class extends ys{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===yn.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};rN.create=(t,e)=>new rN({innerType:t,typeName:Xi.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...os(e)});nN=class extends ys{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return lq(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new H1(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new H1(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};nN.create=(t,e)=>new nN({innerType:t,typeName:Xi.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...os(e)});hq=class extends ys{_parse(e){if(this._getType(e)!==yn.nan){let n=this._getOrReturnCtx(e);return ln(n,{code:Pr.invalid_type,expected:yn.nan,received:n.parsedType}),Hi}return{status:"valid",value:e.data}}};hq.create=t=>new hq({typeName:Xi.ZodNaN,...os(t)});q9n=Symbol("zod_brand"),$X=class extends ys{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},WX=class t extends ys{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?Hi:o.status==="dirty"?(r.dirty(),GB(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?Hi:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:Xi.ZodPipeline})}},iN=class extends ys{_parse(e){let r=this._def.innerType._parse(e),n=i=>(Cw(i)&&(i.value=Object.freeze(i.value)),i);return lq(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};iN.create=(t,e)=>new iN({innerType:t,typeName:Xi.ZodReadonly,...os(e)});H9n={object:G1.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Xi||(Xi={}));G9n=(t,e={message:`Input not instance of ${t.name}`})=>yDt(r=>r instanceof t,e),EDt=bw.create,vDt=VB.create,V9n=hq.create,$9n=$B.create,CDt=WB.create,W9n=jB.create,j9n=uq.create,z9n=zB.create,Y9n=YB.create,J9n=_w.create,K9n=x7.create,X9n=s5.create,Z9n=fq.create,e7n=w7.create,t7n=G1.create,r7n=G1.strictCreate,n7n=JB.create,i7n=Qhe.create,o7n=KB.create,s7n=W8.create,a7n=qhe.create,l7n=dq.create,c7n=pq.create,u7n=Hhe.create,f7n=XB.create,d7n=ZB.create,p7n=eN.create,h7n=tN.create,m7n=Sw.create,g7n=k6.create,A7n=O6.create,y7n=j8.create,E7n=k6.createWithPreprocess,v7n=WX.create,C7n=()=>EDt().optional(),b7n=()=>vDt().optional(),_7n=()=>CDt().optional(),S7n={string:(t=>bw.create({...t,coerce:!0})),number:(t=>VB.create({...t,coerce:!0})),boolean:(t=>WB.create({...t,coerce:!0})),bigint:(t=>$B.create({...t,coerce:!0})),date:(t=>jB.create({...t,coerce:!0}))},x7n=Hi});var fe={};L1(fe,{BRAND:()=>q9n,DIRTY:()=>GB,EMPTY_PATH:()=>E9n,INVALID:()=>Hi,NEVER:()=>x7n,OK:()=>eg,ParseStatus:()=>im,Schema:()=>ys,ZodAny:()=>_w,ZodArray:()=>w7,ZodBigInt:()=>$B,ZodBoolean:()=>WB,ZodBranded:()=>$X,ZodCatch:()=>nN,ZodDate:()=>jB,ZodDefault:()=>rN,ZodDiscriminatedUnion:()=>Qhe,ZodEffects:()=>k6,ZodEnum:()=>eN,ZodError:()=>H1,ZodFirstPartyTypeKind:()=>Xi,ZodFunction:()=>Hhe,ZodIntersection:()=>KB,ZodIssueCode:()=>Pr,ZodLazy:()=>XB,ZodLiteral:()=>ZB,ZodMap:()=>dq,ZodNaN:()=>hq,ZodNativeEnum:()=>tN,ZodNever:()=>s5,ZodNull:()=>YB,ZodNullable:()=>j8,ZodNumber:()=>VB,ZodObject:()=>G1,ZodOptional:()=>O6,ZodParsedType:()=>yn,ZodPipeline:()=>WX,ZodPromise:()=>Sw,ZodReadonly:()=>iN,ZodRecord:()=>qhe,ZodSchema:()=>ys,ZodSet:()=>pq,ZodString:()=>bw,ZodSymbol:()=>uq,ZodTransformer:()=>k6,ZodTuple:()=>W8,ZodType:()=>ys,ZodUndefined:()=>zB,ZodUnion:()=>JB,ZodUnknown:()=>x7,ZodVoid:()=>fq,addIssueToContext:()=>ln,any:()=>J9n,array:()=>e7n,bigint:()=>$9n,boolean:()=>CDt,coerce:()=>S7n,custom:()=>yDt,date:()=>W9n,datetimeRegex:()=>gDt,defaultErrorMap:()=>_7,discriminatedUnion:()=>i7n,effect:()=>g7n,enum:()=>p7n,function:()=>u7n,getErrorMap:()=>aq,getParsedType:()=>$8,instanceof:()=>G9n,intersection:()=>o7n,isAborted:()=>Lhe,isAsync:()=>lq,isDirty:()=>Uhe,isValid:()=>Cw,late:()=>H9n,lazy:()=>f7n,literal:()=>d7n,makeIssue:()=>VX,map:()=>l7n,nan:()=>V9n,nativeEnum:()=>h7n,never:()=>X9n,null:()=>Y9n,nullable:()=>y7n,number:()=>vDt,object:()=>t7n,objectUtil:()=>Jke,oboolean:()=>_7n,onumber:()=>b7n,optional:()=>A7n,ostring:()=>C7n,pipeline:()=>v7n,preprocess:()=>E7n,promise:()=>m7n,quotelessJson:()=>g9n,record:()=>a7n,set:()=>c7n,setErrorMap:()=>y9n,strictObject:()=>r7n,string:()=>EDt,symbol:()=>j9n,transformer:()=>g7n,tuple:()=>s7n,undefined:()=>z9n,union:()=>n7n,unknown:()=>K9n,util:()=>Ws,void:()=>Z9n});var tFe=Ie(()=>{Phe();Xke();uDt();GX();bDt();Fhe()});var xw=Ie(()=>{tFe();tFe()});var mq,_Dt,Ghe,SDt,xDt,w7n,L6,V1,jX,z8,U6,Vhe,wDt,$he,TDt,IDt,DDt,zX,F6,RDt,BDt,ww,oN,Whe,YX,NDt,T7n,I7n,D7n,rFe,ODt,MDt,jhe,R7n,zhe,Yhe,Jhe,kDt,FDt,nFe,PDt,LDt,B7n,N7n,iFe,O7n,oFe,M7n,sFe,k7n,F7n,P7n,L7n,U7n,Q7n,q7n,JX,H7n,aFe,lFe,cFe,G7n,V7n,UDt,$7n,KX,W7n,j7n,z7n,Y7n,uFe,Khe,sSo,J7n,K7n,QDt,X7n,Z7n,e_n,t_n,r_n,n_n,i_n,o_n,s_n,a_n,l_n,c_n,u_n,f_n,d_n,p_n,h_n,fFe,m_n,Xhe,g_n,A_n,aSo,lSo,cSo,uSo,fSo,dSo,P6,Tw=Ie(()=>{xw();mq="2025-06-18",_Dt=[mq,"2025-03-26","2024-11-05","2024-10-07"],Ghe="2.0",SDt=fe.union([fe.string(),fe.number().int()]),xDt=fe.string(),w7n=fe.object({progressToken:fe.optional(SDt)}).passthrough(),L6=fe.object({_meta:fe.optional(w7n)}).passthrough(),V1=fe.object({method:fe.string(),params:fe.optional(L6)}),jX=fe.object({_meta:fe.optional(fe.object({}).passthrough())}).passthrough(),z8=fe.object({method:fe.string(),params:fe.optional(jX)}),U6=fe.object({_meta:fe.optional(fe.object({}).passthrough())}).passthrough(),Vhe=fe.union([fe.string(),fe.number().int()]),wDt=fe.object({jsonrpc:fe.literal(Ghe),id:Vhe}).merge(V1).strict(),$he=t=>wDt.safeParse(t).success,TDt=fe.object({jsonrpc:fe.literal(Ghe)}).merge(z8).strict(),IDt=t=>TDt.safeParse(t).success,DDt=fe.object({jsonrpc:fe.literal(Ghe),id:Vhe,result:U6}).strict(),zX=t=>DDt.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError"})(F6||(F6={}));RDt=fe.object({jsonrpc:fe.literal(Ghe),id:Vhe,error:fe.object({code:fe.number().int(),message:fe.string(),data:fe.optional(fe.unknown())})}).strict(),BDt=t=>RDt.safeParse(t).success,ww=fe.union([wDt,TDt,DDt,RDt]),oN=U6.strict(),Whe=z8.extend({method:fe.literal("notifications/cancelled"),params:jX.extend({requestId:Vhe,reason:fe.string().optional()})}),YX=fe.object({name:fe.string(),title:fe.optional(fe.string())}).passthrough(),NDt=YX.extend({version:fe.string()}),T7n=fe.object({experimental:fe.optional(fe.object({}).passthrough()),sampling:fe.optional(fe.object({}).passthrough()),elicitation:fe.optional(fe.object({}).passthrough()),roots:fe.optional(fe.object({listChanged:fe.optional(fe.boolean())}).passthrough())}).passthrough(),I7n=V1.extend({method:fe.literal("initialize"),params:L6.extend({protocolVersion:fe.string(),capabilities:T7n,clientInfo:NDt})}),D7n=fe.object({experimental:fe.optional(fe.object({}).passthrough()),logging:fe.optional(fe.object({}).passthrough()),completions:fe.optional(fe.object({}).passthrough()),prompts:fe.optional(fe.object({listChanged:fe.optional(fe.boolean())}).passthrough()),resources:fe.optional(fe.object({subscribe:fe.optional(fe.boolean()),listChanged:fe.optional(fe.boolean())}).passthrough()),tools:fe.optional(fe.object({listChanged:fe.optional(fe.boolean())}).passthrough())}).passthrough(),rFe=U6.extend({protocolVersion:fe.string(),capabilities:D7n,serverInfo:NDt,instructions:fe.optional(fe.string())}),ODt=z8.extend({method:fe.literal("notifications/initialized")}),MDt=t=>ODt.safeParse(t).success,jhe=V1.extend({method:fe.literal("ping")}),R7n=fe.object({progress:fe.number(),total:fe.optional(fe.number()),message:fe.optional(fe.string())}).passthrough(),zhe=z8.extend({method:fe.literal("notifications/progress"),params:jX.merge(R7n).extend({progressToken:SDt})}),Yhe=V1.extend({params:L6.extend({cursor:fe.optional(xDt)}).optional()}),Jhe=U6.extend({nextCursor:fe.optional(xDt)}),kDt=fe.object({uri:fe.string(),mimeType:fe.optional(fe.string()),_meta:fe.optional(fe.object({}).passthrough())}).passthrough(),FDt=kDt.extend({text:fe.string()}),nFe=fe.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),PDt=kDt.extend({blob:nFe}),LDt=YX.extend({uri:fe.string(),description:fe.optional(fe.string()),mimeType:fe.optional(fe.string()),_meta:fe.optional(fe.object({}).passthrough())}),B7n=YX.extend({uriTemplate:fe.string(),description:fe.optional(fe.string()),mimeType:fe.optional(fe.string()),_meta:fe.optional(fe.object({}).passthrough())}),N7n=Yhe.extend({method:fe.literal("resources/list")}),iFe=Jhe.extend({resources:fe.array(LDt)}),O7n=Yhe.extend({method:fe.literal("resources/templates/list")}),oFe=Jhe.extend({resourceTemplates:fe.array(B7n)}),M7n=V1.extend({method:fe.literal("resources/read"),params:L6.extend({uri:fe.string()})}),sFe=U6.extend({contents:fe.array(fe.union([FDt,PDt]))}),k7n=z8.extend({method:fe.literal("notifications/resources/list_changed")}),F7n=V1.extend({method:fe.literal("resources/subscribe"),params:L6.extend({uri:fe.string()})}),P7n=V1.extend({method:fe.literal("resources/unsubscribe"),params:L6.extend({uri:fe.string()})}),L7n=z8.extend({method:fe.literal("notifications/resources/updated"),params:jX.extend({uri:fe.string()})}),U7n=fe.object({name:fe.string(),description:fe.optional(fe.string()),required:fe.optional(fe.boolean())}).passthrough(),Q7n=YX.extend({description:fe.optional(fe.string()),arguments:fe.optional(fe.array(U7n)),_meta:fe.optional(fe.object({}).passthrough())}),q7n=Yhe.extend({method:fe.literal("prompts/list")}),JX=Jhe.extend({prompts:fe.array(Q7n)}),H7n=V1.extend({method:fe.literal("prompts/get"),params:L6.extend({name:fe.string(),arguments:fe.optional(fe.record(fe.string()))})}),aFe=fe.object({type:fe.literal("text"),text:fe.string(),_meta:fe.optional(fe.object({}).passthrough())}).passthrough(),lFe=fe.object({type:fe.literal("image"),data:nFe,mimeType:fe.string(),_meta:fe.optional(fe.object({}).passthrough())}).passthrough(),cFe=fe.object({type:fe.literal("audio"),data:nFe,mimeType:fe.string(),_meta:fe.optional(fe.object({}).passthrough())}).passthrough(),G7n=fe.object({type:fe.literal("resource"),resource:fe.union([FDt,PDt]),_meta:fe.optional(fe.object({}).passthrough())}).passthrough(),V7n=LDt.extend({type:fe.literal("resource_link")}),UDt=fe.union([aFe,lFe,cFe,V7n,G7n]),$7n=fe.object({role:fe.enum(["user","assistant"]),content:UDt}).passthrough(),KX=U6.extend({description:fe.optional(fe.string()),messages:fe.array($7n)}),W7n=z8.extend({method:fe.literal("notifications/prompts/list_changed")}),j7n=fe.object({title:fe.optional(fe.string()),readOnlyHint:fe.optional(fe.boolean()),destructiveHint:fe.optional(fe.boolean()),idempotentHint:fe.optional(fe.boolean()),openWorldHint:fe.optional(fe.boolean())}).passthrough(),z7n=YX.extend({description:fe.optional(fe.string()),inputSchema:fe.object({type:fe.literal("object"),properties:fe.optional(fe.object({}).passthrough()),required:fe.optional(fe.array(fe.string()))}).passthrough(),outputSchema:fe.optional(fe.object({type:fe.literal("object"),properties:fe.optional(fe.object({}).passthrough()),required:fe.optional(fe.array(fe.string()))}).passthrough()),annotations:fe.optional(j7n),_meta:fe.optional(fe.object({}).passthrough())}),Y7n=Yhe.extend({method:fe.literal("tools/list")}),uFe=Jhe.extend({tools:fe.array(z7n)}),Khe=U6.extend({content:fe.array(UDt).default([]),structuredContent:fe.object({}).passthrough().optional(),isError:fe.optional(fe.boolean())}),sSo=Khe.or(U6.extend({toolResult:fe.unknown()})),J7n=V1.extend({method:fe.literal("tools/call"),params:L6.extend({name:fe.string(),arguments:fe.optional(fe.record(fe.unknown()))})}),K7n=z8.extend({method:fe.literal("notifications/tools/list_changed")}),QDt=fe.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),X7n=V1.extend({method:fe.literal("logging/setLevel"),params:L6.extend({level:QDt})}),Z7n=z8.extend({method:fe.literal("notifications/message"),params:jX.extend({level:QDt,logger:fe.optional(fe.string()),data:fe.unknown()})}),e_n=fe.object({name:fe.string().optional()}).passthrough(),t_n=fe.object({hints:fe.optional(fe.array(e_n)),costPriority:fe.optional(fe.number().min(0).max(1)),speedPriority:fe.optional(fe.number().min(0).max(1)),intelligencePriority:fe.optional(fe.number().min(0).max(1))}).passthrough(),r_n=fe.object({role:fe.enum(["user","assistant"]),content:fe.union([aFe,lFe,cFe])}).passthrough(),n_n=V1.extend({method:fe.literal("sampling/createMessage"),params:L6.extend({messages:fe.array(r_n),systemPrompt:fe.optional(fe.string()),includeContext:fe.optional(fe.enum(["none","thisServer","allServers"])),temperature:fe.optional(fe.number()),maxTokens:fe.number().int(),stopSequences:fe.optional(fe.array(fe.string())),metadata:fe.optional(fe.object({}).passthrough()),modelPreferences:fe.optional(t_n)})}),i_n=U6.extend({model:fe.string(),stopReason:fe.optional(fe.enum(["endTurn","stopSequence","maxTokens"]).or(fe.string())),role:fe.enum(["user","assistant"]),content:fe.discriminatedUnion("type",[aFe,lFe,cFe])}),o_n=fe.object({type:fe.literal("boolean"),title:fe.optional(fe.string()),description:fe.optional(fe.string()),default:fe.optional(fe.boolean())}).passthrough(),s_n=fe.object({type:fe.literal("string"),title:fe.optional(fe.string()),description:fe.optional(fe.string()),minLength:fe.optional(fe.number()),maxLength:fe.optional(fe.number()),format:fe.optional(fe.enum(["email","uri","date","date-time"]))}).passthrough(),a_n=fe.object({type:fe.enum(["number","integer"]),title:fe.optional(fe.string()),description:fe.optional(fe.string()),minimum:fe.optional(fe.number()),maximum:fe.optional(fe.number())}).passthrough(),l_n=fe.object({type:fe.literal("string"),title:fe.optional(fe.string()),description:fe.optional(fe.string()),enum:fe.array(fe.string()),enumNames:fe.optional(fe.array(fe.string()))}).passthrough(),c_n=fe.union([o_n,s_n,a_n,l_n]),u_n=V1.extend({method:fe.literal("elicitation/create"),params:L6.extend({message:fe.string(),requestedSchema:fe.object({type:fe.literal("object"),properties:fe.record(fe.string(),c_n),required:fe.optional(fe.array(fe.string()))}).passthrough()})}),f_n=U6.extend({action:fe.enum(["accept","decline","cancel"]),content:fe.optional(fe.record(fe.string(),fe.unknown()))}),d_n=fe.object({type:fe.literal("ref/resource"),uri:fe.string()}).passthrough(),p_n=fe.object({type:fe.literal("ref/prompt"),name:fe.string()}).passthrough(),h_n=V1.extend({method:fe.literal("completion/complete"),params:L6.extend({ref:fe.union([p_n,d_n]),argument:fe.object({name:fe.string(),value:fe.string()}).passthrough(),context:fe.optional(fe.object({arguments:fe.optional(fe.record(fe.string(),fe.string()))}))})}),fFe=U6.extend({completion:fe.object({values:fe.array(fe.string()).max(100),total:fe.optional(fe.number().int()),hasMore:fe.optional(fe.boolean())}).passthrough()}),m_n=fe.object({uri:fe.string().startsWith("file://"),name:fe.optional(fe.string()),_meta:fe.optional(fe.object({}).passthrough())}).passthrough(),Xhe=V1.extend({method:fe.literal("roots/list")}),g_n=U6.extend({roots:fe.array(m_n)}),A_n=z8.extend({method:fe.literal("notifications/roots/list_changed")}),aSo=fe.union([jhe,I7n,h_n,X7n,H7n,q7n,N7n,O7n,M7n,F7n,P7n,J7n,Y7n]),lSo=fe.union([Whe,zhe,ODt,A_n]),cSo=fe.union([oN,i_n,f_n,g_n]),uSo=fe.union([jhe,n_n,u_n,Xhe]),fSo=fe.union([Whe,zhe,Z7n,L7n,k7n,K7n,W7n]),dSo=fe.union([oN,rFe,fFe,KX,JX,iFe,oFe,sFe,Khe,uFe]),P6=class extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}}});function qDt(t,e){return Object.entries(e).reduce((r,[n,i])=>(i&&typeof i=="object"?r[n]=r[n]?{...r[n],...i}:i:r[n]=i,r),{...t})}var y_n,Zhe,HDt=Ie(()=>{Tw();y_n=6e4,Zhe=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(Whe,r=>{let n=this._requestHandlerAbortControllers.get(r.params.requestId);n?.abort(r.params.reason)}),this.setNotificationHandler(zhe,r=>{this._onprogress(r)}),this.setRequestHandler(jhe,r=>({}))}_setupTimeout(e,r,n,i,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:i})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),new P6(F6.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,n,i;this._transport=e;let o=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{o?.(),this._onclose()};let s=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=c=>{s?.(c),this._onerror(c)};let a=(i=this._transport)===null||i===void 0?void 0:i.onmessage;this._transport.onmessage=(c,u)=>{a?.(c,u),zX(c)||BDt(c)?this._onresponse(c):$he(c)?this._onrequest(c,u):IDt(c)?this._onnotification(c):this._onerror(new Error(`Unknown message type: ${JSON.stringify(c)}`))},await this._transport.start()}_onclose(){var e;let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let n=new P6(F6.ConnectionClosed,"Connection closed");for(let i of r.values())i(n)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;let n=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(e,r){var n,i;let o=(n=this._requestHandlers.get(e.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,s=this._transport;if(o===void 0){s?.send({jsonrpc:"2.0",id:e.id,error:{code:F6.MethodNotFound,message:"Method not found"}}).catch(u=>this._onerror(new Error(`Failed to send an error response: ${u}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let c={signal:a.signal,sessionId:s?.sessionId,_meta:(i=e.params)===null||i===void 0?void 0:i._meta,sendNotification:u=>this.notification(u,{relatedRequestId:e.id}),sendRequest:(u,f,d)=>this.request(u,f,{...d,relatedRequestId:e.id}),authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo};Promise.resolve().then(()=>o(e,c)).then(u=>{if(!a.signal.aborted)return s?.send({result:u,jsonrpc:"2.0",id:e.id})},u=>{var f;if(!a.signal.aborted)return s?.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:F6.InternalError,message:(f=u.message)!==null&&f!==void 0?f:"Internal error"}})}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,i=Number(r),o=this._progressHandlers.get(i);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(i),a=this._timeoutInfo.get(i);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(c){s(c);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),zX(e))n(e);else{let i=new P6(e.error.code,e.error.message,e.error.data);n(i)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,r,n){let{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}=n??{};return new Promise((a,c)=>{var u,f,d,p,h,g;if(!this._transport){c(new Error("Not connected"));return}((u=this._options)===null||u===void 0?void 0:u.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(f=n?.signal)===null||f===void 0||f.throwIfAborted();let A=this._requestMessageId++,y={...e,jsonrpc:"2.0",id:A};n?.onprogress&&(this._progressHandlers.set(A,n.onprogress),y.params={...e.params,_meta:{...((d=e.params)===null||d===void 0?void 0:d._meta)||{},progressToken:A}});let v=T=>{var B;this._responseHandlers.delete(A),this._progressHandlers.delete(A),this._cleanupTimeout(A),(B=this._transport)===null||B===void 0||B.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:A,reason:String(T)}},{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}).catch(P=>this._onerror(new Error(`Failed to send cancellation: ${P}`))),c(T)};this._responseHandlers.set(A,T=>{var B;if(!(!((B=n?.signal)===null||B===void 0)&&B.aborted)){if(T instanceof Error)return c(T);try{let P=r.parse(T.result);a(P)}catch(P){c(P)}}}),(p=n?.signal)===null||p===void 0||p.addEventListener("abort",()=>{var T;v((T=n?.signal)===null||T===void 0?void 0:T.reason)});let S=(h=n?.timeout)!==null&&h!==void 0?h:y_n,x=()=>v(new P6(F6.RequestTimeout,"Request timed out",{timeout:S}));this._setupTimeout(A,S,n?.maxTotalTimeout,x,(g=n?.resetTimeoutOnProgress)!==null&&g!==void 0?g:!1),this._transport.send(y,{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}).catch(T=>{this._cleanupTimeout(A),c(T)})})}async notification(e,r){var n,i;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((i=(n=this._options)===null||n===void 0?void 0:n.debouncedNotificationMethods)!==null&&i!==void 0?i:[]).includes(e.method)&&!e.params&&!r?.relatedRequestId){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var c;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let u={...e,jsonrpc:"2.0"};(c=this._transport)===null||c===void 0||c.send(u,r).catch(f=>this._onerror(f))});return}let a={...e,jsonrpc:"2.0"};await this._transport.send(a,r)}setRequestHandler(e,r){let n=e.shape.method.value;this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,o)=>Promise.resolve(r(e.parse(i),o)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){this._notificationHandlers.set(e.shape.method.value,n=>Promise.resolve(r(e.parse(n))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}});var VDt=N((e0e,GDt)=>{(function(t,e){typeof e0e=="object"&&typeof GDt<"u"?e(e0e):typeof define=="function"&&define.amd?define(["exports"],e):e(t.URI=t.URI||{})})(e0e,(function(t){"use strict";function e(){for(var at=arguments.length,Je=Array(at),dt=0;dt<at;dt++)Je[dt]=arguments[dt];if(Je.length>1){Je[0]=Je[0].slice(0,-1);for(var wt=Je.length-1,mt=1;mt<wt;++mt)Je[mt]=Je[mt].slice(1,-1);return Je[wt]=Je[wt].slice(1),Je.join("")}else return Je[0]}function r(at){return"(?:"+at+")"}function n(at){return at===void 0?"undefined":at===null?"null":Object.prototype.toString.call(at).split(" ").pop().split("]").shift().toLowerCase()}function i(at){return at.toUpperCase()}function o(at){return at!=null?at instanceof Array?at:typeof at.length!="number"||at.split||at.setInterval||at.call?[at]:Array.prototype.slice.call(at):[]}function s(at,Je){var dt=at;if(Je)for(var wt in Je)dt[wt]=Je[wt];return dt}function a(at){var Je="[A-Za-z]",dt="[\\x0D]",wt="[0-9]",mt="[\\x22]",yr=e(wt,"[A-Fa-f]"),Br="[\\x0A]",Yr="[\\x20]",an=r(r("%[EFef]"+yr+"%"+yr+yr+"%"+yr+yr)+"|"+r("%[89A-Fa-f]"+yr+"%"+yr+yr)+"|"+r("%"+yr+yr)),vn="[\\:\\/\\?\\#\\[\\]\\@]",Wn="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",ki=e(vn,Wn),Qi=at?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",_n=at?"[\\uE000-\\uF8FF]":"[]",Si=e(Je,wt,"[\\-\\.\\_\\~]",Qi),xi=r(Je+e(Je,wt,"[\\+\\-\\.]")+"*"),zi=r(r(an+"|"+e(Si,Wn,"[\\:]"))+"*"),Vl=r(r("25[0-5]")+"|"+r("2[0-4]"+wt)+"|"+r("1"+wt+wt)+"|"+r("[1-9]"+wt)+"|"+wt),Qs=r(r("25[0-5]")+"|"+r("2[0-4]"+wt)+"|"+r("1"+wt+wt)+"|"+r("0?[1-9]"+wt)+"|0?0?"+wt),qs=r(Qs+"\\."+Qs+"\\."+Qs+"\\."+Qs),Bi=r(yr+"{1,4}"),$l=r(r(Bi+"\\:"+Bi)+"|"+qs),Go=r(r(Bi+"\\:")+"{6}"+$l),In=r("\\:\\:"+r(Bi+"\\:")+"{5}"+$l),Lc=r(r(Bi)+"?\\:\\:"+r(Bi+"\\:")+"{4}"+$l),Na=r(r(r(Bi+"\\:")+"{0,1}"+Bi)+"?\\:\\:"+r(Bi+"\\:")+"{3}"+$l),Fo=r(r(r(Bi+"\\:")+"{0,2}"+Bi)+"?\\:\\:"+r(Bi+"\\:")+"{2}"+$l),Uc=r(r(r(Bi+"\\:")+"{0,3}"+Bi)+"?\\:\\:"+Bi+"\\:"+$l),ga=r(r(r(Bi+"\\:")+"{0,4}"+Bi)+"?\\:\\:"+$l),Ts=r(r(r(Bi+"\\:")+"{0,5}"+Bi)+"?\\:\\:"+Bi),al=r(r(r(Bi+"\\:")+"{0,6}"+Bi)+"?\\:\\:"),Ve=r([Go,In,Lc,Na,Fo,Uc,ga,Ts,al].join("|")),We=r(r(Si+"|"+an)+"+"),At=r(Ve+"\\%25"+We),xt=r(Ve+r("\\%25|\\%(?!"+yr+"{2})")+We),Mt=r("[vV]"+yr+"+\\."+e(Si,Wn,"[\\:]")+"+"),tr=r("\\["+r(xt+"|"+Ve+"|"+Mt)+"\\]"),vr=r(r(an+"|"+e(Si,Wn))+"*"),ur=r(tr+"|"+qs+"(?!"+vr+")|"+vr),xr=r(wt+"*"),Tr=r(r(zi+"@")+"?"+ur+r("\\:"+xr)+"?"),kr=r(an+"|"+e(Si,Wn,"[\\:\\@]")),Sn=r(kr+"*"),uo=r(kr+"+"),Is=r(r(an+"|"+e(Si,Wn,"[\\@]"))+"+"),wi=r(r("\\/"+Sn)+"*"),ja=r("\\/"+r(uo+wi)+"?"),Oa=r(Is+wi),Uf=r(uo+wi),Wl="(?!"+kr+")",bh=r(wi+"|"+ja+"|"+Oa+"|"+Uf+"|"+Wl),rp=r(r(kr+"|"+e("[\\/\\?]",_n))+"*"),jl=r(r(kr+"|[\\/\\?]")+"*"),P0=r(r("\\/\\/"+Tr+wi)+"|"+ja+"|"+Uf+"|"+Wl),L0=r(xi+"\\:"+P0+r("\\?"+rp)+"?"+r("\\#"+jl)+"?"),np=r(r("\\/\\/"+Tr+wi)+"|"+ja+"|"+Oa+"|"+Wl),_c=r(np+r("\\?"+rp)+"?"+r("\\#"+jl)+"?"),Qp=r(L0+"|"+_c),Qf=r(xi+"\\:"+P0+r("\\?"+rp)+"?"),mf="^("+xi+")\\:"+r(r("\\/\\/("+r("("+zi+")@")+"?("+ur+")"+r("\\:("+xr+")")+"?)")+"?("+wi+"|"+ja+"|"+Uf+"|"+Wl+")")+r("\\?("+rp+")")+"?"+r("\\#("+jl+")")+"?$",qp="^(){0}"+r(r("\\/\\/("+r("("+zi+")@")+"?("+ur+")"+r("\\:("+xr+")")+"?)")+"?("+wi+"|"+ja+"|"+Oa+"|"+Wl+")")+r("\\?("+rp+")")+"?"+r("\\#("+jl+")")+"?$",U0="^("+xi+")\\:"+r(r("\\/\\/("+r("("+zi+")@")+"?("+ur+")"+r("\\:("+xr+")")+"?)")+"?("+wi+"|"+ja+"|"+Uf+"|"+Wl+")")+r("\\?("+rp+")")+"?$",nu="^"+r("\\#("+jl+")")+"?$",t2="^"+r("("+zi+")@")+"?("+ur+")"+r("\\:("+xr+")")+"?$";return{NOT_SCHEME:new RegExp(e("[^]",Je,wt,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(e("[^\\%\\:]",Si,Wn),"g"),NOT_HOST:new RegExp(e("[^\\%\\[\\]\\:]",Si,Wn),"g"),NOT_PATH:new RegExp(e("[^\\%\\/\\:\\@]",Si,Wn),"g"),NOT_PATH_NOSCHEME:new RegExp(e("[^\\%\\/\\@]",Si,Wn),"g"),NOT_QUERY:new RegExp(e("[^\\%]",Si,Wn,"[\\:\\@\\/\\?]",_n),"g"),NOT_FRAGMENT:new RegExp(e("[^\\%]",Si,Wn,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(e("[^]",Si,Wn),"g"),UNRESERVED:new RegExp(Si,"g"),OTHER_CHARS:new RegExp(e("[^\\%]",Si,ki),"g"),PCT_ENCODED:new RegExp(an,"g"),IPV4ADDRESS:new RegExp("^("+qs+")$"),IPV6ADDRESS:new RegExp("^\\[?("+Ve+")"+r(r("\\%25|\\%(?!"+yr+"{2})")+"("+We+")")+"?\\]?$")}}var c=a(!1),u=a(!0),f=(function(){function at(Je,dt){var wt=[],mt=!0,yr=!1,Br=void 0;try{for(var Yr=Je[Symbol.iterator](),an;!(mt=(an=Yr.next()).done)&&(wt.push(an.value),!(dt&&wt.length===dt));mt=!0);}catch(vn){yr=!0,Br=vn}finally{try{!mt&&Yr.return&&Yr.return()}finally{if(yr)throw Br}}return wt}return function(Je,dt){if(Array.isArray(Je))return Je;if(Symbol.iterator in Object(Je))return at(Je,dt);throw new TypeError("Invalid attempt to destructure non-iterable instance")}})(),d=function(at){if(Array.isArray(at)){for(var Je=0,dt=Array(at.length);Je<at.length;Je++)dt[Je]=at[Je];return dt}else return Array.from(at)},p=2147483647,h=36,g=1,A=26,y=38,v=700,S=72,x=128,T="-",B=/^xn--/,P=/[^\0-\x7E]/,L=/[\x2E\u3002\uFF0E\uFF61]/g,q={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},I=h-g,U=Math.floor,O=String.fromCharCode;function Q(at){throw new RangeError(q[at])}function F(at,Je){for(var dt=[],wt=at.length;wt--;)dt[wt]=Je(at[wt]);return dt}function M(at,Je){var dt=at.split("@"),wt="";dt.length>1&&(wt=dt[0]+"@",at=dt[1]),at=at.replace(L,".");var mt=at.split("."),yr=F(mt,Je).join(".");return wt+yr}function V(at){for(var Je=[],dt=0,wt=at.length;dt<wt;){var mt=at.charCodeAt(dt++);if(mt>=55296&&mt<=56319&&dt<wt){var yr=at.charCodeAt(dt++);(yr&64512)==56320?Je.push(((mt&1023)<<10)+(yr&1023)+65536):(Je.push(mt),dt--)}else Je.push(mt)}return Je}var G=function(Je){return String.fromCodePoint.apply(String,d(Je))},j=function(Je){return Je-48<10?Je-22:Je-65<26?Je-65:Je-97<26?Je-97:h},$=function(Je,dt){return Je+22+75*(Je<26)-((dt!=0)<<5)},re=function(Je,dt,wt){var mt=0;for(Je=wt?U(Je/v):Je>>1,Je+=U(Je/dt);Je>I*A>>1;mt+=h)Je=U(Je/I);return U(mt+(I+1)*Je/(Je+y))},K=function(Je){var dt=[],wt=Je.length,mt=0,yr=x,Br=S,Yr=Je.lastIndexOf(T);Yr<0&&(Yr=0);for(var an=0;an<Yr;++an)Je.charCodeAt(an)>=128&&Q("not-basic"),dt.push(Je.charCodeAt(an));for(var vn=Yr>0?Yr+1:0;vn<wt;){for(var Wn=mt,ki=1,Qi=h;;Qi+=h){vn>=wt&&Q("invalid-input");var _n=j(Je.charCodeAt(vn++));(_n>=h||_n>U((p-mt)/ki))&&Q("overflow"),mt+=_n*ki;var Si=Qi<=Br?g:Qi>=Br+A?A:Qi-Br;if(_n<Si)break;var xi=h-Si;ki>U(p/xi)&&Q("overflow"),ki*=xi}var zi=dt.length+1;Br=re(mt-Wn,zi,Wn==0),U(mt/zi)>p-yr&&Q("overflow"),yr+=U(mt/zi),mt%=zi,dt.splice(mt++,0,yr)}return String.fromCodePoint.apply(String,dt)},me=function(Je){var dt=[];Je=V(Je);var wt=Je.length,mt=x,yr=0,Br=S,Yr=!0,an=!1,vn=void 0;try{for(var Wn=Je[Symbol.iterator](),ki;!(Yr=(ki=Wn.next()).done);Yr=!0){var Qi=ki.value;Qi<128&&dt.push(O(Qi))}}catch(xt){an=!0,vn=xt}finally{try{!Yr&&Wn.return&&Wn.return()}finally{if(an)throw vn}}var _n=dt.length,Si=_n;for(_n&&dt.push(T);Si<wt;){var xi=p,zi=!0,Vl=!1,Qs=void 0;try{for(var qs=Je[Symbol.iterator](),Bi;!(zi=(Bi=qs.next()).done);zi=!0){var $l=Bi.value;$l>=mt&&$l<xi&&(xi=$l)}}catch(xt){Vl=!0,Qs=xt}finally{try{!zi&&qs.return&&qs.return()}finally{if(Vl)throw Qs}}var Go=Si+1;xi-mt>U((p-yr)/Go)&&Q("overflow"),yr+=(xi-mt)*Go,mt=xi;var In=!0,Lc=!1,Na=void 0;try{for(var Fo=Je[Symbol.iterator](),Uc;!(In=(Uc=Fo.next()).done);In=!0){var ga=Uc.value;if(ga<mt&&++yr>p&&Q("overflow"),ga==mt){for(var Ts=yr,al=h;;al+=h){var Ve=al<=Br?g:al>=Br+A?A:al-Br;if(Ts<Ve)break;var We=Ts-Ve,At=h-Ve;dt.push(O($(Ve+We%At,0))),Ts=U(We/At)}dt.push(O($(Ts,0))),Br=re(yr,Go,Si==_n),yr=0,++Si}}}catch(xt){Lc=!0,Na=xt}finally{try{!In&&Fo.return&&Fo.return()}finally{if(Lc)throw Na}}++yr,++mt}return dt.join("")},ve=function(Je){return M(Je,function(dt){return B.test(dt)?K(dt.slice(4).toLowerCase()):dt})},Ae=function(Je){return M(Je,function(dt){return P.test(dt)?"xn--"+me(dt):dt})},Se={version:"2.1.0",ucs2:{decode:V,encode:G},decode:K,encode:me,toASCII:Ae,toUnicode:ve},xe={};function pe(at){var Je=at.charCodeAt(0),dt=void 0;return Je<16?dt="%0"+Je.toString(16).toUpperCase():Je<128?dt="%"+Je.toString(16).toUpperCase():Je<2048?dt="%"+(Je>>6|192).toString(16).toUpperCase()+"%"+(Je&63|128).toString(16).toUpperCase():dt="%"+(Je>>12|224).toString(16).toUpperCase()+"%"+(Je>>6&63|128).toString(16).toUpperCase()+"%"+(Je&63|128).toString(16).toUpperCase(),dt}function Ee(at){for(var Je="",dt=0,wt=at.length;dt<wt;){var mt=parseInt(at.substr(dt+1,2),16);if(mt<128)Je+=String.fromCharCode(mt),dt+=3;else if(mt>=194&&mt<224){if(wt-dt>=6){var yr=parseInt(at.substr(dt+4,2),16);Je+=String.fromCharCode((mt&31)<<6|yr&63)}else Je+=at.substr(dt,6);dt+=6}else if(mt>=224){if(wt-dt>=9){var Br=parseInt(at.substr(dt+4,2),16),Yr=parseInt(at.substr(dt+7,2),16);Je+=String.fromCharCode((mt&15)<<12|(Br&63)<<6|Yr&63)}else Je+=at.substr(dt,9);dt+=9}else Je+=at.substr(dt,3),dt+=3}return Je}function he(at,Je){function dt(wt){var mt=Ee(wt);return mt.match(Je.UNRESERVED)?mt:wt}return at.scheme&&(at.scheme=String(at.scheme).replace(Je.PCT_ENCODED,dt).toLowerCase().replace(Je.NOT_SCHEME,"")),at.userinfo!==void 0&&(at.userinfo=String(at.userinfo).replace(Je.PCT_ENCODED,dt).replace(Je.NOT_USERINFO,pe).replace(Je.PCT_ENCODED,i)),at.host!==void 0&&(at.host=String(at.host).replace(Je.PCT_ENCODED,dt).toLowerCase().replace(Je.NOT_HOST,pe).replace(Je.PCT_ENCODED,i)),at.path!==void 0&&(at.path=String(at.path).replace(Je.PCT_ENCODED,dt).replace(at.scheme?Je.NOT_PATH:Je.NOT_PATH_NOSCHEME,pe).replace(Je.PCT_ENCODED,i)),at.query!==void 0&&(at.query=String(at.query).replace(Je.PCT_ENCODED,dt).replace(Je.NOT_QUERY,pe).replace(Je.PCT_ENCODED,i)),at.fragment!==void 0&&(at.fragment=String(at.fragment).replace(Je.PCT_ENCODED,dt).replace(Je.NOT_FRAGMENT,pe).replace(Je.PCT_ENCODED,i)),at}function ee(at){return at.replace(/^0*(.*)/,"$1")||"0"}function de(at,Je){var dt=at.match(Je.IPV4ADDRESS)||[],wt=f(dt,2),mt=wt[1];return mt?mt.split(".").map(ee).join("."):at}function X(at,Je){var dt=at.match(Je.IPV6ADDRESS)||[],wt=f(dt,3),mt=wt[1],yr=wt[2];if(mt){for(var Br=mt.toLowerCase().split("::").reverse(),Yr=f(Br,2),an=Yr[0],vn=Yr[1],Wn=vn?vn.split(":").map(ee):[],ki=an.split(":").map(ee),Qi=Je.IPV4ADDRESS.test(ki[ki.length-1]),_n=Qi?7:8,Si=ki.length-_n,xi=Array(_n),zi=0;zi<_n;++zi)xi[zi]=Wn[zi]||ki[Si+zi]||"";Qi&&(xi[_n-1]=de(xi[_n-1],Je));var Vl=xi.reduce(function(Go,In,Lc){if(!In||In==="0"){var Na=Go[Go.length-1];Na&&Na.index+Na.length===Lc?Na.length++:Go.push({index:Lc,length:1})}return Go},[]),Qs=Vl.sort(function(Go,In){return In.length-Go.length})[0],qs=void 0;if(Qs&&Qs.length>1){var Bi=xi.slice(0,Qs.index),$l=xi.slice(Qs.index+Qs.length);qs=Bi.join(":")+"::"+$l.join(":")}else qs=xi.join(":");return yr&&(qs+="%"+yr),qs}else return at}var oe=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,ge="".match(/(){0}/)[1]===void 0;function le(at){var Je=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},dt={},wt=Je.iri!==!1?u:c;Je.reference==="suffix"&&(at=(Je.scheme?Je.scheme+":":"")+"//"+at);var mt=at.match(oe);if(mt){ge?(dt.scheme=mt[1],dt.userinfo=mt[3],dt.host=mt[4],dt.port=parseInt(mt[5],10),dt.path=mt[6]||"",dt.query=mt[7],dt.fragment=mt[8],isNaN(dt.port)&&(dt.port=mt[5])):(dt.scheme=mt[1]||void 0,dt.userinfo=at.indexOf("@")!==-1?mt[3]:void 0,dt.host=at.indexOf("//")!==-1?mt[4]:void 0,dt.port=parseInt(mt[5],10),dt.path=mt[6]||"",dt.query=at.indexOf("?")!==-1?mt[7]:void 0,dt.fragment=at.indexOf("#")!==-1?mt[8]:void 0,isNaN(dt.port)&&(dt.port=at.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?mt[4]:void 0)),dt.host&&(dt.host=X(de(dt.host,wt),wt)),dt.scheme===void 0&&dt.userinfo===void 0&&dt.host===void 0&&dt.port===void 0&&!dt.path&&dt.query===void 0?dt.reference="same-document":dt.scheme===void 0?dt.reference="relative":dt.fragment===void 0?dt.reference="absolute":dt.reference="uri",Je.reference&&Je.reference!=="suffix"&&Je.reference!==dt.reference&&(dt.error=dt.error||"URI is not a "+Je.reference+" reference.");var yr=xe[(Je.scheme||dt.scheme||"").toLowerCase()];if(!Je.unicodeSupport&&(!yr||!yr.unicodeSupport)){if(dt.host&&(Je.domainHost||yr&&yr.domainHost))try{dt.host=Se.toASCII(dt.host.replace(wt.PCT_ENCODED,Ee).toLowerCase())}catch(Br){dt.error=dt.error||"Host's domain name can not be converted to ASCII via punycode: "+Br}he(dt,c)}else he(dt,wt);yr&&yr.parse&&yr.parse(dt,Je)}else dt.error=dt.error||"URI can not be parsed.";return dt}function J(at,Je){var dt=Je.iri!==!1?u:c,wt=[];return at.userinfo!==void 0&&(wt.push(at.userinfo),wt.push("@")),at.host!==void 0&&wt.push(X(de(String(at.host),dt),dt).replace(dt.IPV6ADDRESS,function(mt,yr,Br){return"["+yr+(Br?"%25"+Br:"")+"]"})),(typeof at.port=="number"||typeof at.port=="string")&&(wt.push(":"),wt.push(String(at.port))),wt.length?wt.join(""):void 0}var ne=/^\.\.?\//,we=/^\/\.(\/|$)/,ye=/^\/\.\.(\/|$)/,Z=/^\/?(?:.|\n)*?(?=\/|$)/;function Re(at){for(var Je=[];at.length;)if(at.match(ne))at=at.replace(ne,"");else if(at.match(we))at=at.replace(we,"/");else if(at.match(ye))at=at.replace(ye,"/"),Je.pop();else if(at==="."||at==="..")at="";else{var dt=at.match(Z);if(dt){var wt=dt[0];at=at.slice(wt.length),Je.push(wt)}else throw new Error("Unexpected dot segment condition")}return Je.join("")}function Qe(at){var Je=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},dt=Je.iri?u:c,wt=[],mt=xe[(Je.scheme||at.scheme||"").toLowerCase()];if(mt&&mt.serialize&&mt.serialize(at,Je),at.host&&!dt.IPV6ADDRESS.test(at.host)){if(Je.domainHost||mt&&mt.domainHost)try{at.host=Je.iri?Se.toUnicode(at.host):Se.toASCII(at.host.replace(dt.PCT_ENCODED,Ee).toLowerCase())}catch(Yr){at.error=at.error||"Host's domain name can not be converted to "+(Je.iri?"Unicode":"ASCII")+" via punycode: "+Yr}}he(at,dt),Je.reference!=="suffix"&&at.scheme&&(wt.push(at.scheme),wt.push(":"));var yr=J(at,Je);if(yr!==void 0&&(Je.reference!=="suffix"&&wt.push("//"),wt.push(yr),at.path&&at.path.charAt(0)!=="/"&&wt.push("/")),at.path!==void 0){var Br=at.path;!Je.absolutePath&&(!mt||!mt.absolutePath)&&(Br=Re(Br)),yr===void 0&&(Br=Br.replace(/^\/\//,"/%2F")),wt.push(Br)}return at.query!==void 0&&(wt.push("?"),wt.push(at.query)),at.fragment!==void 0&&(wt.push("#"),wt.push(at.fragment)),wt.join("")}function qe(at,Je){var dt=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},wt=arguments[3],mt={};return wt||(at=le(Qe(at,dt),dt),Je=le(Qe(Je,dt),dt)),dt=dt||{},!dt.tolerant&&Je.scheme?(mt.scheme=Je.scheme,mt.userinfo=Je.userinfo,mt.host=Je.host,mt.port=Je.port,mt.path=Re(Je.path||""),mt.query=Je.query):(Je.userinfo!==void 0||Je.host!==void 0||Je.port!==void 0?(mt.userinfo=Je.userinfo,mt.host=Je.host,mt.port=Je.port,mt.path=Re(Je.path||""),mt.query=Je.query):(Je.path?(Je.path.charAt(0)==="/"?mt.path=Re(Je.path):((at.userinfo!==void 0||at.host!==void 0||at.port!==void 0)&&!at.path?mt.path="/"+Je.path:at.path?mt.path=at.path.slice(0,at.path.lastIndexOf("/")+1)+Je.path:mt.path=Je.path,mt.path=Re(mt.path)),mt.query=Je.query):(mt.path=at.path,Je.query!==void 0?mt.query=Je.query:mt.query=at.query),mt.userinfo=at.userinfo,mt.host=at.host,mt.port=at.port),mt.scheme=at.scheme),mt.fragment=Je.fragment,mt}function Ge(at,Je,dt){var wt=s({scheme:"null"},dt);return Qe(qe(le(at,wt),le(Je,wt),wt,!0),wt)}function ce(at,Je){return typeof at=="string"?at=Qe(le(at,Je),Je):n(at)==="object"&&(at=le(Qe(at,Je),Je)),at}function Ne(at,Je,dt){return typeof at=="string"?at=Qe(le(at,dt),dt):n(at)==="object"&&(at=Qe(at,dt)),typeof Je=="string"?Je=Qe(le(Je,dt),dt):n(Je)==="object"&&(Je=Qe(Je,dt)),at===Je}function Me(at,Je){return at&&at.toString().replace(!Je||!Je.iri?c.ESCAPE:u.ESCAPE,pe)}function Fe(at,Je){return at&&at.toString().replace(!Je||!Je.iri?c.PCT_ENCODED:u.PCT_ENCODED,Ee)}var Ke={scheme:"http",domainHost:!0,parse:function(Je,dt){return Je.host||(Je.error=Je.error||"HTTP URIs must have a host."),Je},serialize:function(Je,dt){var wt=String(Je.scheme).toLowerCase()==="https";return(Je.port===(wt?443:80)||Je.port==="")&&(Je.port=void 0),Je.path||(Je.path="/"),Je}},rt={scheme:"https",domainHost:Ke.domainHost,parse:Ke.parse,serialize:Ke.serialize};function pt(at){return typeof at.secure=="boolean"?at.secure:String(at.scheme).toLowerCase()==="wss"}var yt={scheme:"ws",domainHost:!0,parse:function(Je,dt){var wt=Je;return wt.secure=pt(wt),wt.resourceName=(wt.path||"/")+(wt.query?"?"+wt.query:""),wt.path=void 0,wt.query=void 0,wt},serialize:function(Je,dt){if((Je.port===(pt(Je)?443:80)||Je.port==="")&&(Je.port=void 0),typeof Je.secure=="boolean"&&(Je.scheme=Je.secure?"wss":"ws",Je.secure=void 0),Je.resourceName){var wt=Je.resourceName.split("?"),mt=f(wt,2),yr=mt[0],Br=mt[1];Je.path=yr&&yr!=="/"?yr:void 0,Je.query=Br,Je.resourceName=void 0}return Je.fragment=void 0,Je}},It={scheme:"wss",domainHost:yt.domainHost,parse:yt.parse,serialize:yt.serialize},hr={},Nr=!0,Le="[A-Za-z0-9\\-\\.\\_\\~"+(Nr?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",ct="[0-9A-Fa-f]",ut=r(r("%[EFef]"+ct+"%"+ct+ct+"%"+ct+ct)+"|"+r("%[89A-Fa-f]"+ct+"%"+ct+ct)+"|"+r("%"+ct+ct)),Ut="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",Ht="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",Ft=e(Ht,'[\\"\\\\]'),Qt="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",Zt=new RegExp(Le,"g"),Jt=new RegExp(ut,"g"),cn=new RegExp(e("[^]",Ut,"[\\.]",'[\\"]',Ft),"g"),Qr=new RegExp(e("[^]",Le,Qt),"g"),Zr=Qr;function tn(at){var Je=Ee(at);return Je.match(Zt)?Je:at}var Jn={scheme:"mailto",parse:function(Je,dt){var wt=Je,mt=wt.to=wt.path?wt.path.split(","):[];if(wt.path=void 0,wt.query){for(var yr=!1,Br={},Yr=wt.query.split("&"),an=0,vn=Yr.length;an<vn;++an){var Wn=Yr[an].split("=");switch(Wn[0]){case"to":for(var ki=Wn[1].split(","),Qi=0,_n=ki.length;Qi<_n;++Qi)mt.push(ki[Qi]);break;case"subject":wt.subject=Fe(Wn[1],dt);break;case"body":wt.body=Fe(Wn[1],dt);break;default:yr=!0,Br[Fe(Wn[0],dt)]=Fe(Wn[1],dt);break}}yr&&(wt.headers=Br)}wt.query=void 0;for(var Si=0,xi=mt.length;Si<xi;++Si){var zi=mt[Si].split("@");if(zi[0]=Fe(zi[0]),dt.unicodeSupport)zi[1]=Fe(zi[1],dt).toLowerCase();else try{zi[1]=Se.toASCII(Fe(zi[1],dt).toLowerCase())}catch(Vl){wt.error=wt.error||"Email address's domain name can not be converted to ASCII via punycode: "+Vl}mt[Si]=zi.join("@")}return wt},serialize:function(Je,dt){var wt=Je,mt=o(Je.to);if(mt){for(var yr=0,Br=mt.length;yr<Br;++yr){var Yr=String(mt[yr]),an=Yr.lastIndexOf("@"),vn=Yr.slice(0,an).replace(Jt,tn).replace(Jt,i).replace(cn,pe),Wn=Yr.slice(an+1);try{Wn=dt.iri?Se.toUnicode(Wn):Se.toASCII(Fe(Wn,dt).toLowerCase())}catch(Si){wt.error=wt.error||"Email address's domain name can not be converted to "+(dt.iri?"Unicode":"ASCII")+" via punycode: "+Si}mt[yr]=vn+"@"+Wn}wt.path=mt.join(",")}var ki=Je.headers=Je.headers||{};Je.subject&&(ki.subject=Je.subject),Je.body&&(ki.body=Je.body);var Qi=[];for(var _n in ki)ki[_n]!==hr[_n]&&Qi.push(_n.replace(Jt,tn).replace(Jt,i).replace(Qr,pe)+"="+ki[_n].replace(Jt,tn).replace(Jt,i).replace(Zr,pe));return Qi.length&&(wt.query=Qi.join("&")),wt}},ri=/^([^\:]+)\:(.*)/,kn={scheme:"urn",parse:function(Je,dt){var wt=Je.path&&Je.path.match(ri),mt=Je;if(wt){var yr=dt.scheme||mt.scheme||"urn",Br=wt[1].toLowerCase(),Yr=wt[2],an=yr+":"+(dt.nid||Br),vn=xe[an];mt.nid=Br,mt.nss=Yr,mt.path=void 0,vn&&(mt=vn.parse(mt,dt))}else mt.error=mt.error||"URN can not be parsed.";return mt},serialize:function(Je,dt){var wt=dt.scheme||Je.scheme||"urn",mt=Je.nid,yr=wt+":"+(dt.nid||mt),Br=xe[yr];Br&&(Je=Br.serialize(Je,dt));var Yr=Je,an=Je.nss;return Yr.path=(mt||dt.nid)+":"+an,Yr}},ni=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,Ui={scheme:"urn:uuid",parse:function(Je,dt){var wt=Je;return wt.uuid=wt.nss,wt.nss=void 0,!dt.tolerant&&(!wt.uuid||!wt.uuid.match(ni))&&(wt.error=wt.error||"UUID is not valid."),wt},serialize:function(Je,dt){var wt=Je;return wt.nss=(Je.uuid||"").toLowerCase(),wt}};xe[Ke.scheme]=Ke,xe[rt.scheme]=rt,xe[yt.scheme]=yt,xe[It.scheme]=It,xe[Jn.scheme]=Jn,xe[kn.scheme]=kn,xe[Ui.scheme]=Ui,t.SCHEMES=xe,t.pctEncChar=pe,t.pctDecChars=Ee,t.parse=le,t.removeDotSegments=Re,t.serialize=Qe,t.resolveComponents=qe,t.resolve=Ge,t.normalize=ce,t.equal=Ne,t.escapeComponent=Me,t.unescapeComponent=Fe,Object.defineProperty(t,"__esModule",{value:!0})}))});var gq=N((gSo,$Dt)=>{"use strict";$Dt.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,i,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(i=n;i--!==0;)if(!t(e[i],r[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[i]))return!1;for(i=n;i--!==0;){var s=o[i];if(!t(e[s],r[s]))return!1}return!0}return e!==e&&r!==r}});var jDt=N((ASo,WDt)=>{"use strict";WDt.exports=function(e){for(var r=0,n=e.length,i=0,o;i<n;)r++,o=e.charCodeAt(i++),o>=55296&&o<=56319&&i<n&&(o=e.charCodeAt(i),(o&64512)==56320&&i++);return r}});var sN=N((ySo,JDt)=>{"use strict";JDt.exports={copy:E_n,checkDataType:dFe,checkDataTypes:v_n,coerceToTypes:C_n,toHash:hFe,getProperty:mFe,escapeQuotes:gFe,equal:gq(),ucs2length:jDt(),varOccurences:S_n,varReplace:x_n,schemaHasRules:w_n,schemaHasRulesExcept:T_n,schemaUnknownRules:I_n,toQuotedString:pFe,getPathExpr:D_n,getPath:R_n,getData:O_n,unescapeFragment:M_n,unescapeJsonPointer:yFe,escapeFragment:k_n,escapeJsonPointer:AFe};function E_n(t,e){e=e||{};for(var r in t)e[r]=t[r];return e}function dFe(t,e,r,n){var i=n?" !== ":" === ",o=n?" || ":" && ",s=n?"!":"",a=n?"":"!";switch(t){case"null":return e+i+"null";case"array":return s+"Array.isArray("+e+")";case"object":return"("+s+e+o+"typeof "+e+i+'"object"'+o+a+"Array.isArray("+e+"))";case"integer":return"(typeof "+e+i+'"number"'+o+a+"("+e+" % 1)"+o+e+i+e+(r?o+s+"isFinite("+e+")":"")+")";case"number":return"(typeof "+e+i+'"'+t+'"'+(r?o+s+"isFinite("+e+")":"")+")";default:return"typeof "+e+i+'"'+t+'"'}}function v_n(t,e,r){switch(t.length){case 1:return dFe(t[0],e,r,!0);default:var n="",i=hFe(t);i.array&&i.object&&(n=i.null?"(":"(!"+e+" || ",n+="typeof "+e+' !== "object")',delete i.null,delete i.array,delete i.object),i.number&&delete i.integer;for(var o in i)n+=(n?" && ":"")+dFe(o,e,r,!0);return n}}var zDt=hFe(["string","number","integer","boolean","null"]);function C_n(t,e){if(Array.isArray(e)){for(var r=[],n=0;n<e.length;n++){var i=e[n];(zDt[i]||t==="array"&&i==="array")&&(r[r.length]=i)}if(r.length)return r}else{if(zDt[e])return[e];if(t==="array"&&e==="array")return["array"]}}function hFe(t){for(var e={},r=0;r<t.length;r++)e[t[r]]=!0;return e}var b_n=/^[a-z$_][a-z$_0-9]*$/i,__n=/'|\\/g;function mFe(t){return typeof t=="number"?"["+t+"]":b_n.test(t)?"."+t:"['"+gFe(t)+"']"}function gFe(t){return t.replace(__n,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function S_n(t,e){e+="[^0-9]";var r=t.match(new RegExp(e,"g"));return r?r.length:0}function x_n(t,e,r){return e+="([^0-9])",r=r.replace(/\$/g,"$$$$"),t.replace(new RegExp(e,"g"),r+"$1")}function w_n(t,e){if(typeof t=="boolean")return!t;for(var r in t)if(e[r])return!0}function T_n(t,e,r){if(typeof t=="boolean")return!t&&r!="not";for(var n in t)if(n!=r&&e[n])return!0}function I_n(t,e){if(typeof t!="boolean"){for(var r in t)if(!e[r])return r}}function pFe(t){return"'"+gFe(t)+"'"}function D_n(t,e,r,n){var i=r?"'/' + "+e+(n?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):n?"'[' + "+e+" + ']'":"'[\\'' + "+e+" + '\\']'";return YDt(t,i)}function R_n(t,e,r){var n=pFe(r?"/"+AFe(e):mFe(e));return YDt(t,n)}var B_n=/^\/(?:[^~]|~0|~1)*$/,N_n=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function O_n(t,e,r){var n,i,o,s;if(t==="")return"rootData";if(t[0]=="/"){if(!B_n.test(t))throw new Error("Invalid JSON-pointer: "+t);i=t,o="rootData"}else{if(s=t.match(N_n),!s)throw new Error("Invalid JSON-pointer: "+t);if(n=+s[1],i=s[2],i=="#"){if(n>=e)throw new Error("Cannot access property/index "+n+" levels up, current level is "+e);return r[e-n]}if(n>e)throw new Error("Cannot access data "+n+" levels up, current level is "+e);if(o="data"+(e-n||""),!i)return o}for(var a=o,c=i.split("/"),u=0;u<c.length;u++){var f=c[u];f&&(o+=mFe(yFe(f)),a+=" && "+o)}return a}function YDt(t,e){return t=='""'?e:(t+" + "+e).replace(/([^\\])' \+ '/g,"$1")}function M_n(t){return yFe(decodeURIComponent(t))}function k_n(t){return encodeURIComponent(AFe(t))}function AFe(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function yFe(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}});var EFe=N((ESo,KDt)=>{"use strict";var F_n=sN();KDt.exports=P_n;function P_n(t){F_n.copy(t,this)}});var ZDt=N((vSo,XDt)=>{"use strict";var Iw=XDt.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},i=r.post||function(){};t0e(e,n,i,t,"",t)};Iw.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0};Iw.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Iw.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Iw.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function t0e(t,e,r,n,i,o,s,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,i,o,s,a,c,u);for(var f in n){var d=n[f];if(Array.isArray(d)){if(f in Iw.arrayKeywords)for(var p=0;p<d.length;p++)t0e(t,e,r,d[p],i+"/"+f+"/"+p,o,i,f,n,p)}else if(f in Iw.propsKeywords){if(d&&typeof d=="object")for(var h in d)t0e(t,e,r,d[h],i+"/"+f+"/"+L_n(h),o,i,f,n,h)}else(f in Iw.keywords||t.allKeys&&!(f in Iw.skipKeywords))&&t0e(t,e,r,d,i+"/"+f,o,i,f,n)}r(n,i,o,s,a,c,u)}}function L_n(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var a0e=N((CSo,nRt)=>{"use strict";var XX=VDt(),eRt=gq(),o0e=sN(),r0e=EFe(),U_n=ZDt();nRt.exports=Rw;Rw.normalizeId=Dw;Rw.fullPath=n0e;Rw.url=i0e;Rw.ids=V_n;Rw.inlineRef=vFe;Rw.schema=s0e;function Rw(t,e,r){var n=this._refs[r];if(typeof n=="string")if(this._refs[n])n=this._refs[n];else return Rw.call(this,t,e,n);if(n=n||this._schemas[r],n instanceof r0e)return vFe(n.schema,this._opts.inlineRefs)?n.schema:n.validate||this._compile(n);var i=s0e.call(this,e,r),o,s,a;return i&&(o=i.schema,e=i.root,a=i.baseId),o instanceof r0e?s=o.validate||t.call(this,o.schema,e,void 0,a):o!==void 0&&(s=vFe(o,this._opts.inlineRefs)?o:t.call(this,o,e,void 0,a)),s}function s0e(t,e){var r=XX.parse(e),n=rRt(r),i=n0e(this._getId(t.schema));if(Object.keys(t.schema).length===0||n!==i){var o=Dw(n),s=this._refs[o];if(typeof s=="string")return Q_n.call(this,t,s,r);if(s instanceof r0e)s.validate||this._compile(s),t=s;else if(s=this._schemas[o],s instanceof r0e){if(s.validate||this._compile(s),o==Dw(e))return{schema:s,root:t,baseId:i};t=s}else return;if(!t.schema)return;i=n0e(this._getId(t.schema))}return tRt.call(this,r,i,t.schema,t)}function Q_n(t,e,r){var n=s0e.call(this,t,e);if(n){var i=n.schema,o=n.baseId;t=n.root;var s=this._getId(i);return s&&(o=i0e(o,s)),tRt.call(this,r,o,i,t)}}var q_n=o0e.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function tRt(t,e,r,n){if(t.fragment=t.fragment||"",t.fragment.slice(0,1)=="/"){for(var i=t.fragment.split("/"),o=1;o<i.length;o++){var s=i[o];if(s){if(s=o0e.unescapeFragment(s),r=r[s],r===void 0)break;var a;if(!q_n[s]&&(a=this._getId(r),a&&(e=i0e(e,a)),r.$ref)){var c=i0e(e,r.$ref),u=s0e.call(this,n,c);u&&(r=u.schema,n=u.root,e=u.baseId)}}}if(r!==void 0&&r!==n.schema)return{schema:r,root:n,baseId:e}}}var H_n=o0e.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function vFe(t,e){if(e===!1)return!1;if(e===void 0||e===!0)return CFe(t);if(e)return bFe(t)<=e}function CFe(t){var e;if(Array.isArray(t)){for(var r=0;r<t.length;r++)if(e=t[r],typeof e=="object"&&!CFe(e))return!1}else for(var n in t)if(n=="$ref"||(e=t[n],typeof e=="object"&&!CFe(e)))return!1;return!0}function bFe(t){var e=0,r;if(Array.isArray(t)){for(var n=0;n<t.length;n++)if(r=t[n],typeof r=="object"&&(e+=bFe(r)),e==1/0)return 1/0}else for(var i in t){if(i=="$ref")return 1/0;if(H_n[i])e++;else if(r=t[i],typeof r=="object"&&(e+=bFe(r)+1),e==1/0)return 1/0}return e}function n0e(t,e){e!==!1&&(t=Dw(t));var r=XX.parse(t);return rRt(r)}function rRt(t){return XX.serialize(t).split("#")[0]+"#"}var G_n=/#\/?$/;function Dw(t){return t?t.replace(G_n,""):""}function i0e(t,e){return e=Dw(e),XX.resolve(t,e)}function V_n(t){var e=Dw(this._getId(t)),r={"":e},n={"":n0e(e,!1)},i={},o=this;return U_n(t,{allKeys:!0},function(s,a,c,u,f,d,p){if(a!==""){var h=o._getId(s),g=r[u],A=n[u]+"/"+f;if(p!==void 0&&(A+="/"+(typeof p=="number"?p:o0e.escapeFragment(p))),typeof h=="string"){h=g=Dw(g?XX.resolve(g,h):h);var y=o._refs[h];if(typeof y=="string"&&(y=o._refs[y]),y&&y.schema){if(!eRt(s,y.schema))throw new Error('id "'+h+'" resolves to more than one schema')}else if(h!=Dw(A))if(h[0]=="#"){if(i[h]&&!eRt(s,i[h]))throw new Error('id "'+h+'" resolves to more than one schema');i[h]=s}else o._refs[h]=A}r[a]=g,n[a]=A}}),i}});var l0e=N((bSo,oRt)=>{"use strict";var _Fe=a0e();oRt.exports={Validation:iRt($_n),MissingRef:iRt(SFe)};function $_n(t){this.message="validation failed",this.errors=t,this.ajv=this.validation=!0}SFe.message=function(t,e){return"can't resolve reference "+e+" from id "+t};function SFe(t,e,r){this.message=r||SFe.message(t,e),this.missingRef=_Fe.url(t,e),this.missingSchema=_Fe.normalizeId(_Fe.fullPath(this.missingRef))}function iRt(t){return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}});var xFe=N((_So,sRt)=>{"use strict";sRt.exports=function(t,e){e||(e={}),typeof e=="function"&&(e={cmp:e});var r=typeof e.cycles=="boolean"?e.cycles:!1,n=e.cmp&&(function(o){return function(s){return function(a,c){var u={key:a,value:s[a]},f={key:c,value:s[c]};return o(u,f)}}})(e.cmp),i=[];return(function o(s){if(s&&s.toJSON&&typeof s.toJSON=="function"&&(s=s.toJSON()),s!==void 0){if(typeof s=="number")return isFinite(s)?""+s:"null";if(typeof s!="object")return JSON.stringify(s);var a,c;if(Array.isArray(s)){for(c="[",a=0;a<s.length;a++)a&&(c+=","),c+=o(s[a])||"null";return c+"]"}if(s===null)return"null";if(i.indexOf(s)!==-1){if(r)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var u=i.push(s)-1,f=Object.keys(s).sort(n&&n(s));for(c="",a=0;a<f.length;a++){var d=f[a],p=o(s[d]);p&&(c&&(c+=","),c+=JSON.stringify(d)+":"+p)}return i.splice(u,1),"{"+c+"}"}})(t)}});var wFe=N((SSo,aRt)=>{"use strict";aRt.exports=function(e,r,n){var i="",o=e.schema.$async===!0,s=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),a=e.self._getId(e.schema);if(e.opts.strictKeywords){var c=e.util.schemaUnknownRules(e.schema,e.RULES.keywords);if(c){var u="unknown keyword: "+c;if(e.opts.strictKeywords==="log")e.logger.warn(u);else throw new Error(u)}}if(e.isTop&&(i+=" var validate = ",o&&(e.async=!0,i+="async "),i+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",a&&(e.opts.sourceCode||e.opts.processCode)&&(i+=" "+("/*# sourceURL="+a+" */")+" ")),typeof e.schema=="boolean"||!(s||e.schema.$ref)){var r="false schema",f=e.level,d=e.dataLevel,p=e.schema[r],h=e.schemaPath+e.util.getProperty(r),g=e.errSchemaPath+"/"+r,B=!e.opts.allErrors,q,A="data"+(d||""),T="valid"+f;if(e.schema===!1){e.isTop?B=!0:i+=" var "+T+" = false; ";var y=y||[];y.push(i),i="",e.createErrors!==!1?(i+=" { keyword: '"+(q||"false schema")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(g)+" , params: {} ",e.opts.messages!==!1&&(i+=" , message: 'boolean schema is false' "),e.opts.verbose&&(i+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+A+" "),i+=" } "):i+=" {} ";var v=i;i=y.pop(),!e.compositeRule&&B?e.async?i+=" throw new ValidationError(["+v+"]); ":i+=" validate.errors = ["+v+"]; return false; ":i+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else e.isTop?o?i+=" return data; ":i+=" validate.errors = null; return true; ":i+=" var "+T+" = true; ";return e.isTop&&(i+=" }; return validate; "),i}if(e.isTop){var S=e.isTop,f=e.level=0,d=e.dataLevel=0,A="data";if(e.rootId=e.resolve.fullPath(e.self._getId(e.root.schema)),e.baseId=e.baseId||e.rootId,delete e.isTop,e.dataPathArr=[""],e.schema.default!==void 0&&e.opts.useDefaults&&e.opts.strictDefaults){var x="default is ignored in the schema root";if(e.opts.strictDefaults==="log")e.logger.warn(x);else throw new Error(x)}i+=" var vErrors = null; ",i+=" var errors = 0; ",i+=" if (rootData === undefined) rootData = data; "}else{var f=e.level,d=e.dataLevel,A="data"+(d||"");if(a&&(e.baseId=e.resolve.url(e.baseId,a)),o&&!e.async)throw new Error("async schema in sync schema");i+=" var errs_"+f+" = errors;"}var T="valid"+f,B=!e.opts.allErrors,P="",L="",q,I=e.schema.type,U=Array.isArray(I);if(I&&e.opts.nullable&&e.schema.nullable===!0&&(U?I.indexOf("null")==-1&&(I=I.concat("null")):I!="null"&&(I=[I,"null"],U=!0)),U&&I.length==1&&(I=I[0],U=!1),e.schema.$ref&&s){if(e.opts.extendRefs=="fail")throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)');e.opts.extendRefs!==!0&&(s=!1,e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"'))}if(e.schema.$comment&&e.opts.$comment&&(i+=" "+e.RULES.all.$comment.code(e,"$comment")),I){if(e.opts.coerceTypes)var O=e.util.coerceToTypes(e.opts.coerceTypes,I);var Q=e.RULES.types[I];if(O||U||Q===!0||Q&&!Z(Q)){var h=e.schemaPath+".type",g=e.errSchemaPath+"/type",h=e.schemaPath+".type",g=e.errSchemaPath+"/type",F=U?"checkDataTypes":"checkDataType";if(i+=" if ("+e.util[F](I,A,e.opts.strictNumbers,!0)+") { ",O){var M="dataType"+f,V="coerced"+f;i+=" var "+M+" = typeof "+A+"; var "+V+" = undefined; ",e.opts.coerceTypes=="array"&&(i+=" if ("+M+" == 'object' && Array.isArray("+A+") && "+A+".length == 1) { "+A+" = "+A+"[0]; "+M+" = typeof "+A+"; if ("+e.util.checkDataType(e.schema.type,A,e.opts.strictNumbers)+") "+V+" = "+A+"; } "),i+=" if ("+V+" !== undefined) ; ";var G=O;if(G)for(var j,$=-1,re=G.length-1;$<re;)j=G[$+=1],j=="string"?i+=" else if ("+M+" == 'number' || "+M+" == 'boolean') "+V+" = '' + "+A+"; else if ("+A+" === null) "+V+" = ''; ":j=="number"||j=="integer"?(i+=" else if ("+M+" == 'boolean' || "+A+" === null || ("+M+" == 'string' && "+A+" && "+A+" == +"+A+" ",j=="integer"&&(i+=" && !("+A+" % 1)"),i+=")) "+V+" = +"+A+"; "):j=="boolean"?i+=" else if ("+A+" === 'false' || "+A+" === 0 || "+A+" === null) "+V+" = false; else if ("+A+" === 'true' || "+A+" === 1) "+V+" = true; ":j=="null"?i+=" else if ("+A+" === '' || "+A+" === 0 || "+A+" === false) "+V+" = null; ":e.opts.coerceTypes=="array"&&j=="array"&&(i+=" else if ("+M+" == 'string' || "+M+" == 'number' || "+M+" == 'boolean' || "+A+" == null) "+V+" = ["+A+"]; ");i+=" else { ";var y=y||[];y.push(i),i="",e.createErrors!==!1?(i+=" { keyword: '"+(q||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(g)+" , params: { type: '",U?i+=""+I.join(","):i+=""+I,i+="' } ",e.opts.messages!==!1&&(i+=" , message: 'should be ",U?i+=""+I.join(","):i+=""+I,i+="' "),e.opts.verbose&&(i+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+A+" "),i+=" } "):i+=" {} ";var v=i;i=y.pop(),!e.compositeRule&&B?e.async?i+=" throw new ValidationError(["+v+"]); ":i+=" validate.errors = ["+v+"]; return false; ":i+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } if ("+V+" !== undefined) { ";var K=d?"data"+(d-1||""):"parentData",me=d?e.dataPathArr[d]:"parentDataProperty";i+=" "+A+" = "+V+"; ",d||(i+="if ("+K+" !== undefined)"),i+=" "+K+"["+me+"] = "+V+"; } "}else{var y=y||[];y.push(i),i="",e.createErrors!==!1?(i+=" { keyword: '"+(q||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(g)+" , params: { type: '",U?i+=""+I.join(","):i+=""+I,i+="' } ",e.opts.messages!==!1&&(i+=" , message: 'should be ",U?i+=""+I.join(","):i+=""+I,i+="' "),e.opts.verbose&&(i+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+A+" "),i+=" } "):i+=" {} ";var v=i;i=y.pop(),!e.compositeRule&&B?e.async?i+=" throw new ValidationError(["+v+"]); ":i+=" validate.errors = ["+v+"]; return false; ":i+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}i+=" } "}}if(e.schema.$ref&&!s)i+=" "+e.RULES.all.$ref.code(e,"$ref")+" ",B&&(i+=" } if (errors === ",S?i+="0":i+="errs_"+f,i+=") { ",L+="}");else{var ve=e.RULES;if(ve){for(var Q,Ae=-1,Se=ve.length-1;Ae<Se;)if(Q=ve[Ae+=1],Z(Q)){if(Q.type&&(i+=" if ("+e.util.checkDataType(Q.type,A,e.opts.strictNumbers)+") { "),e.opts.useDefaults){if(Q.type=="object"&&e.schema.properties){var p=e.schema.properties,xe=Object.keys(p),pe=xe;if(pe)for(var Ee,he=-1,ee=pe.length-1;he<ee;){Ee=pe[he+=1];var de=p[Ee];if(de.default!==void 0){var X=A+e.util.getProperty(Ee);if(e.compositeRule){if(e.opts.strictDefaults){var x="default is ignored for: "+X;if(e.opts.strictDefaults==="log")e.logger.warn(x);else throw new Error(x)}}else i+=" if ("+X+" === undefined ",e.opts.useDefaults=="empty"&&(i+=" || "+X+" === null || "+X+" === '' "),i+=" ) "+X+" = ",e.opts.useDefaults=="shared"?i+=" "+e.useDefault(de.default)+" ":i+=" "+JSON.stringify(de.default)+" ",i+="; "}}}else if(Q.type=="array"&&Array.isArray(e.schema.items)){var oe=e.schema.items;if(oe){for(var de,$=-1,ge=oe.length-1;$<ge;)if(de=oe[$+=1],de.default!==void 0){var X=A+"["+$+"]";if(e.compositeRule){if(e.opts.strictDefaults){var x="default is ignored for: "+X;if(e.opts.strictDefaults==="log")e.logger.warn(x);else throw new Error(x)}}else i+=" if ("+X+" === undefined ",e.opts.useDefaults=="empty"&&(i+=" || "+X+" === null || "+X+" === '' "),i+=" ) "+X+" = ",e.opts.useDefaults=="shared"?i+=" "+e.useDefault(de.default)+" ":i+=" "+JSON.stringify(de.default)+" ",i+="; "}}}}var le=Q.rules;if(le){for(var J,ne=-1,we=le.length-1;ne<we;)if(J=le[ne+=1],Re(J)){var ye=J.code(e,J.keyword,Q.type);ye&&(i+=" "+ye+" ",B&&(P+="}"))}}if(B&&(i+=" "+P+" ",P=""),Q.type&&(i+=" } ",I&&I===Q.type&&!O)){i+=" else { ";var h=e.schemaPath+".type",g=e.errSchemaPath+"/type",y=y||[];y.push(i),i="",e.createErrors!==!1?(i+=" { keyword: '"+(q||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(g)+" , params: { type: '",U?i+=""+I.join(","):i+=""+I,i+="' } ",e.opts.messages!==!1&&(i+=" , message: 'should be ",U?i+=""+I.join(","):i+=""+I,i+="' "),e.opts.verbose&&(i+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+A+" "),i+=" } "):i+=" {} ";var v=i;i=y.pop(),!e.compositeRule&&B?e.async?i+=" throw new ValidationError(["+v+"]); ":i+=" validate.errors = ["+v+"]; return false; ":i+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } "}B&&(i+=" if (errors === ",S?i+="0":i+="errs_"+f,i+=") { ",L+="}")}}}B&&(i+=" "+L+" "),S?(o?(i+=" if (errors === 0) return data; ",i+=" else throw new ValidationError(vErrors); "):(i+=" validate.errors = vErrors; ",i+=" return errors === 0; "),i+=" }; return validate;"):i+=" var "+T+" = errors === errs_"+f+";";function Z(qe){for(var Ge=qe.rules,ce=0;ce<Ge.length;ce++)if(Re(Ge[ce]))return!0}function Re(qe){return e.schema[qe.keyword]!==void 0||qe.implements&&Qe(qe)}function Qe(qe){for(var Ge=qe.implements,ce=0;ce<Ge.length;ce++)if(e.schema[Ge[ce]]!==void 0)return!0}return i}});var dRt=N((xSo,fRt)=>{"use strict";var c0e=a0e(),f0e=sN(),cRt=l0e(),W_n=xFe(),lRt=wFe(),j_n=f0e.ucs2length,z_n=gq(),Y_n=cRt.Validation;fRt.exports=TFe;function TFe(t,e,r,n){var i=this,o=this._opts,s=[void 0],a={},c=[],u={},f=[],d={},p=[];e=e||{schema:t,refVal:s,refs:a};var h=J_n.call(this,t,e,n),g=this._compilations[h.index];if(h.compiling)return g.callValidate=x;var A=this._formats,y=this.RULES;try{var v=T(t,e,r,n);g.validate=v;var S=g.callValidate;return S&&(S.schema=v.schema,S.errors=null,S.refs=v.refs,S.refVal=v.refVal,S.root=v.root,S.$async=v.$async,o.sourceCode&&(S.source=v.source)),v}finally{K_n.call(this,t,e,n)}function x(){var F=g.validate,M=F.apply(this,arguments);return x.errors=F.errors,M}function T(F,M,V,G){var j=!M||M&&M.schema==F;if(M.schema!=e.schema)return TFe.call(i,F,M,V,G);var $=F.$async===!0,re=lRt({isTop:!0,schema:F,isRoot:j,baseId:G,root:M,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:cRt.MissingRef,RULES:y,validate:lRt,util:f0e,resolve:c0e,resolveRef:B,usePattern:U,useDefault:O,useCustomRule:Q,opts:o,formats:A,logger:i.logger,self:i});re=u0e(s,eSn)+u0e(c,X_n)+u0e(f,Z_n)+u0e(p,tSn)+re,o.processCode&&(re=o.processCode(re,F));var K;try{var me=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",re);K=me(i,y,A,e,s,f,p,z_n,j_n,Y_n),s[0]=K}catch(ve){throw i.logger.error("Error compiling schema, function code:",re),ve}return K.schema=F,K.errors=null,K.refs=a,K.refVal=s,K.root=j?K:M,$&&(K.$async=!0),o.sourceCode===!0&&(K.source={code:re,patterns:c,defaults:f}),K}function B(F,M,V){M=c0e.url(F,M);var G=a[M],j,$;if(G!==void 0)return j=s[G],$="refVal["+G+"]",I(j,$);if(!V&&e.refs){var re=e.refs[M];if(re!==void 0)return j=e.refVal[re],$=P(M,j),I(j,$)}$=P(M);var K=c0e.call(i,T,e,M);if(K===void 0){var me=r&&r[M];me&&(K=c0e.inlineRef(me,o.inlineRefs)?me:TFe.call(i,me,e,r,F))}if(K===void 0)L(M);else return q(M,K),I(K,$)}function P(F,M){var V=s.length;return s[V]=M,a[F]=V,"refVal"+V}function L(F){delete a[F]}function q(F,M){var V=a[F];s[V]=M}function I(F,M){return typeof F=="object"||typeof F=="boolean"?{code:M,schema:F,inline:!0}:{code:M,$async:F&&!!F.$async}}function U(F){var M=u[F];return M===void 0&&(M=u[F]=c.length,c[M]=F),"pattern"+M}function O(F){switch(typeof F){case"boolean":case"number":return""+F;case"string":return f0e.toQuotedString(F);case"object":if(F===null)return"null";var M=W_n(F),V=d[M];return V===void 0&&(V=d[M]=f.length,f[V]=F),"default"+V}}function Q(F,M,V,G){if(i._opts.validateSchema!==!1){var j=F.definition.dependencies;if(j&&!j.every(function(pe){return Object.prototype.hasOwnProperty.call(V,pe)}))throw new Error("parent schema must have all required keywords: "+j.join(","));var $=F.definition.validateSchema;if($){var re=$(M);if(!re){var K="keyword schema is invalid: "+i.errorsText($.errors);if(i._opts.validateSchema=="log")i.logger.error(K);else throw new Error(K)}}}var me=F.definition.compile,ve=F.definition.inline,Ae=F.definition.macro,Se;if(me)Se=me.call(i,M,V,G);else if(Ae)Se=Ae.call(i,M,V,G),o.validateSchema!==!1&&i.validateSchema(Se,!0);else if(ve)Se=ve.call(i,G,F.keyword,M,V);else if(Se=F.definition.validate,!Se)return;if(Se===void 0)throw new Error('custom keyword "'+F.keyword+'"failed to compile');var xe=p.length;return p[xe]=Se,{code:"customRule"+xe,validate:Se}}}function J_n(t,e,r){var n=uRt.call(this,t,e,r);return n>=0?{index:n,compiling:!0}:(n=this._compilations.length,this._compilations[n]={schema:t,root:e,baseId:r},{index:n,compiling:!1})}function K_n(t,e,r){var n=uRt.call(this,t,e,r);n>=0&&this._compilations.splice(n,1)}function uRt(t,e,r){for(var n=0;n<this._compilations.length;n++){var i=this._compilations[n];if(i.schema==t&&i.root==e&&i.baseId==r)return n}return-1}function X_n(t,e){return"var pattern"+t+" = new RegExp("+f0e.toQuotedString(e[t])+");"}function Z_n(t){return"var default"+t+" = defaults["+t+"];"}function eSn(t,e){return e[t]===void 0?"":"var refVal"+t+" = refVal["+t+"];"}function tSn(t){return"var customRule"+t+" = customRules["+t+"];"}function u0e(t,e){if(!t.length)return"";for(var r="",n=0;n<t.length;n++)r+=e(n,t);return r}});var hRt=N((wSo,pRt)=>{"use strict";var d0e=pRt.exports=function(){this._cache={}};d0e.prototype.put=function(e,r){this._cache[e]=r};d0e.prototype.get=function(e){return this._cache[e]};d0e.prototype.del=function(e){delete this._cache[e]};d0e.prototype.clear=function(){this._cache={}}});var wRt=N((TSo,xRt)=>{"use strict";var rSn=sN(),nSn=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,iSn=[0,31,28,31,30,31,30,31,31,30,31,30,31],oSn=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,mRt=/^(?=.{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,sSn=/^(?:[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,aSn=/^(?:[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,gRt=/^(?:(?:[^\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,ARt=/^(?:(?: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,yRt=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,ERt=/^(?:\/(?:[^~/]|~0|~1)*)*$/,vRt=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,CRt=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;xRt.exports=p0e;function p0e(t){return t=t=="full"?"full":"fast",rSn.copy(p0e[t])}p0e.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":gRt,url:ARt,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:mRt,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:SRt,uuid:yRt,"json-pointer":ERt,"json-pointer-uri-fragment":vRt,"relative-json-pointer":CRt};p0e.full={date:bRt,time:_Rt,"date-time":uSn,uri:dSn,"uri-reference":aSn,"uri-template":gRt,url:ARt,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:mRt,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:SRt,uuid:yRt,"json-pointer":ERt,"json-pointer-uri-fragment":vRt,"relative-json-pointer":CRt};function lSn(t){return t%4===0&&(t%100!==0||t%400===0)}function bRt(t){var e=t.match(nSn);if(!e)return!1;var r=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n==2&&lSn(r)?29:iSn[n])}function _Rt(t,e){var r=t.match(oSn);if(!r)return!1;var n=r[1],i=r[2],o=r[3],s=r[5];return(n<=23&&i<=59&&o<=59||n==23&&i==59&&o==60)&&(!e||s)}var cSn=/t|\s/i;function uSn(t){var e=t.split(cSn);return e.length==2&&bRt(e[0])&&_Rt(e[1],!0)}var fSn=/\/|:/;function dSn(t){return fSn.test(t)&&sSn.test(t)}var pSn=/[^\\]\\Z/;function SRt(t){if(pSn.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var IRt=N((ISo,TRt)=>{"use strict";TRt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(s||""),d="valid"+o,p,h;if(a=="#"||a=="#/")e.isRoot?(p=e.async,h="validate"):(p=e.root.schema.$async===!0,h="root.refVal[0]");else{var g=e.resolveRef(e.baseId,a,e.isRoot);if(g===void 0){var A=e.MissingRefError.message(e.baseId,a);if(e.opts.missingRefs=="fail"){e.logger.error(A);var y=y||[];y.push(i),i="",e.createErrors!==!1?(i+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { ref: '"+e.util.escapeQuotes(a)+"' } ",e.opts.messages!==!1&&(i+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(a)+"' "),e.opts.verbose&&(i+=" , schema: "+e.util.toQuotedString(a)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),i+=" } "):i+=" {} ";var v=i;i=y.pop(),!e.compositeRule&&u?e.async?i+=" throw new ValidationError(["+v+"]); ":i+=" validate.errors = ["+v+"]; return false; ":i+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u&&(i+=" if (false) { ")}else if(e.opts.missingRefs=="ignore")e.logger.warn(A),u&&(i+=" if (true) { ");else throw new e.MissingRefError(e.baseId,a,A)}else if(g.inline){var S=e.util.copy(e);S.level++;var x="valid"+S.level;S.schema=g.schema,S.schemaPath="",S.errSchemaPath=a;var T=e.validate(S).replace(/validate\.schema/g,g.code);i+=" "+T+" ",u&&(i+=" if ("+x+") { ")}else p=g.$async===!0||e.async&&g.$async!==!1,h=g.code}if(h){var y=y||[];y.push(i),i="",e.opts.passContext?i+=" "+h+".call(this, ":i+=" "+h+"( ",i+=" "+f+", (dataPath || '')",e.errorPath!='""'&&(i+=" + "+e.errorPath);var B=s?"data"+(s-1||""):"parentData",P=s?e.dataPathArr[s]:"parentDataProperty";i+=" , "+B+" , "+P+", rootData) ";var L=i;if(i=y.pop(),p){if(!e.async)throw new Error("async schema referenced by sync schema");u&&(i+=" var "+d+"; "),i+=" try { await "+L+"; ",u&&(i+=" "+d+" = true; "),i+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",u&&(i+=" "+d+" = false; "),i+=" } ",u&&(i+=" if ("+d+") { ")}else i+=" if (!"+L+") { if (vErrors === null) vErrors = "+h+".errors; else vErrors = vErrors.concat("+h+".errors); errors = vErrors.length; } ",u&&(i+=" else { ")}return i}});var RRt=N((DSo,DRt)=>{"use strict";DRt.exports=function(e,r,n){var i=" ",o=e.schema[r],s=e.schemaPath+e.util.getProperty(r),a=e.errSchemaPath+"/"+r,c=!e.opts.allErrors,u=e.util.copy(e),f="";u.level++;var d="valid"+u.level,p=u.baseId,h=!0,g=o;if(g)for(var A,y=-1,v=g.length-1;y<v;)A=g[y+=1],(e.opts.strictKeywords?typeof A=="object"&&Object.keys(A).length>0||A===!1:e.util.schemaHasRules(A,e.RULES.all))&&(h=!1,u.schema=A,u.schemaPath=s+"["+y+"]",u.errSchemaPath=a+"/"+y,i+=" "+e.validate(u)+" ",u.baseId=p,c&&(i+=" if ("+d+") { ",f+="}"));return c&&(h?i+=" if (true) { ":i+=" "+f.slice(0,-1)+" "),i}});var NRt=N((RSo,BRt)=>{"use strict";BRt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,f=!e.opts.allErrors,d="data"+(s||""),p="valid"+o,h="errs__"+o,g=e.util.copy(e),A="";g.level++;var y="valid"+g.level,v=a.every(function(q){return e.opts.strictKeywords?typeof q=="object"&&Object.keys(q).length>0||q===!1:e.util.schemaHasRules(q,e.RULES.all)});if(v){var S=g.baseId;i+=" var "+h+" = errors; var "+p+" = false; ";var x=e.compositeRule;e.compositeRule=g.compositeRule=!0;var T=a;if(T)for(var B,P=-1,L=T.length-1;P<L;)B=T[P+=1],g.schema=B,g.schemaPath=c+"["+P+"]",g.errSchemaPath=u+"/"+P,i+=" "+e.validate(g)+" ",g.baseId=S,i+=" "+p+" = "+p+" || "+y+"; if (!"+p+") { ",A+="}";e.compositeRule=g.compositeRule=x,i+=" "+A+" if (!"+p+") { var err = ",e.createErrors!==!1?(i+=" { keyword: 'anyOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(i+=" , message: 'should match some schema in anyOf' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ",i+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&f&&(e.async?i+=" throw new ValidationError(vErrors); ":i+=" validate.errors = vErrors; return false; "),i+=" } else { errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } ",e.opts.allErrors&&(i+=" } ")}else f&&(i+=" if (true) { ");return i}});var MRt=N((BSo,ORt)=>{"use strict";ORt.exports=function(e,r,n){var i=" ",o=e.schema[r],s=e.errSchemaPath+"/"+r,a=!e.opts.allErrors,c=e.util.toQuotedString(o);return e.opts.$comment===!0?i+=" console.log("+c+");":typeof e.opts.$comment=="function"&&(i+=" self._opts.$comment("+c+", "+e.util.toQuotedString(s)+", validate.root.schema);"),i}});var FRt=N((NSo,kRt)=>{"use strict";kRt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,f=!e.opts.allErrors,d="data"+(s||""),p="valid"+o,h=e.opts.$data&&a&&a.$data,g;h?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",g="schema"+o):g=a,h||(i+=" var schema"+o+" = validate.schema"+c+";"),i+="var "+p+" = equal("+d+", schema"+o+"); if (!"+p+") { ";var A=A||[];A.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'const' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { allowedValue: schema"+o+" } ",e.opts.messages!==!1&&(i+=" , message: 'should be equal to constant' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var y=i;return i=A.pop(),!e.compositeRule&&f?e.async?i+=" throw new ValidationError(["+y+"]); ":i+=" validate.errors = ["+y+"]; return false; ":i+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" }",f&&(i+=" else { "),i}});var LRt=N((OSo,PRt)=>{"use strict";PRt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,f=!e.opts.allErrors,d="data"+(s||""),p="valid"+o,h="errs__"+o,g=e.util.copy(e),A="";g.level++;var y="valid"+g.level,v="i"+o,S=g.dataLevel=e.dataLevel+1,x="data"+S,T=e.baseId,B=e.opts.strictKeywords?typeof a=="object"&&Object.keys(a).length>0||a===!1:e.util.schemaHasRules(a,e.RULES.all);if(i+="var "+h+" = errors;var "+p+";",B){var P=e.compositeRule;e.compositeRule=g.compositeRule=!0,g.schema=a,g.schemaPath=c,g.errSchemaPath=u,i+=" var "+y+" = false; for (var "+v+" = 0; "+v+" < "+d+".length; "+v+"++) { ",g.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers,!0);var L=d+"["+v+"]";g.dataPathArr[S]=v;var q=e.validate(g);g.baseId=T,e.util.varOccurences(q,x)<2?i+=" "+e.util.varReplace(q,x,L)+" ":i+=" var "+x+" = "+L+"; "+q+" ",i+=" if ("+y+") break; } ",e.compositeRule=g.compositeRule=P,i+=" "+A+" if (!"+y+") {"}else i+=" if ("+d+".length == 0) {";var I=I||[];I.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(i+=" , message: 'should contain a valid item' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var U=i;return i=I.pop(),!e.compositeRule&&f?e.async?i+=" throw new ValidationError(["+U+"]); ":i+=" validate.errors = ["+U+"]; return false; ":i+=" var err = "+U+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } else { ",B&&(i+=" errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } "),e.opts.allErrors&&(i+=" } "),i}});var QRt=N((MSo,URt)=>{"use strict";URt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,f=!e.opts.allErrors,d="data"+(s||""),p="errs__"+o,h=e.util.copy(e),g="";h.level++;var A="valid"+h.level,y={},v={},S=e.opts.ownProperties;for(P in a)if(P!="__proto__"){var x=a[P],T=Array.isArray(x)?v:y;T[P]=x}i+="var "+p+" = errors;";var B=e.errorPath;i+="var missing"+o+";";for(var P in v)if(T=v[P],T.length){if(i+=" if ( "+d+e.util.getProperty(P)+" !== undefined ",S&&(i+=" && Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(P)+"') "),f){i+=" && ( ";var L=T;if(L)for(var q,I=-1,U=L.length-1;I<U;){q=L[I+=1],I&&(i+=" || ");var O=e.util.getProperty(q),Q=d+O;i+=" ( ( "+Q+" === undefined ",S&&(i+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(q)+"') "),i+=") && (missing"+o+" = "+e.util.toQuotedString(e.opts.jsonPointers?q:O)+") ) "}i+=")) { ";var F="missing"+o,M="' + "+F+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(B,F,!0):B+" + "+F);var V=V||[];V.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { property: '"+e.util.escapeQuotes(P)+"', missingProperty: '"+M+"', depsCount: "+T.length+", deps: '"+e.util.escapeQuotes(T.length==1?T[0]:T.join(", "))+"' } ",e.opts.messages!==!1&&(i+=" , message: 'should have ",T.length==1?i+="property "+e.util.escapeQuotes(T[0]):i+="properties "+e.util.escapeQuotes(T.join(", ")),i+=" when property "+e.util.escapeQuotes(P)+" is present' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var G=i;i=V.pop(),!e.compositeRule&&f?e.async?i+=" throw new ValidationError(["+G+"]); ":i+=" validate.errors = ["+G+"]; return false; ":i+=" var err = "+G+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else{i+=" ) { ";var j=T;if(j)for(var q,$=-1,re=j.length-1;$<re;){q=j[$+=1];var O=e.util.getProperty(q),M=e.util.escapeQuotes(q),Q=d+O;e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(B,q,e.opts.jsonPointers)),i+=" if ( "+Q+" === undefined ",S&&(i+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(q)+"') "),i+=") { var err = ",e.createErrors!==!1?(i+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { property: '"+e.util.escapeQuotes(P)+"', missingProperty: '"+M+"', depsCount: "+T.length+", deps: '"+e.util.escapeQuotes(T.length==1?T[0]:T.join(", "))+"' } ",e.opts.messages!==!1&&(i+=" , message: 'should have ",T.length==1?i+="property "+e.util.escapeQuotes(T[0]):i+="properties "+e.util.escapeQuotes(T.join(", ")),i+=" when property "+e.util.escapeQuotes(P)+" is present' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ",i+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}i+=" } ",f&&(g+="}",i+=" else { ")}e.errorPath=B;var K=h.baseId;for(var P in y){var x=y[P];(e.opts.strictKeywords?typeof x=="object"&&Object.keys(x).length>0||x===!1:e.util.schemaHasRules(x,e.RULES.all))&&(i+=" "+A+" = true; if ( "+d+e.util.getProperty(P)+" !== undefined ",S&&(i+=" && Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(P)+"') "),i+=") { ",h.schema=x,h.schemaPath=c+e.util.getProperty(P),h.errSchemaPath=u+"/"+e.util.escapeFragment(P),i+=" "+e.validate(h)+" ",h.baseId=K,i+=" } ",f&&(i+=" if ("+A+") { ",g+="}"))}return f&&(i+=" "+g+" if ("+p+" == errors) {"),i}});var HRt=N((kSo,qRt)=>{"use strict";qRt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,f=!e.opts.allErrors,d="data"+(s||""),p="valid"+o,h=e.opts.$data&&a&&a.$data,g;h?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",g="schema"+o):g=a;var A="i"+o,y="schema"+o;h||(i+=" var "+y+" = validate.schema"+c+";"),i+="var "+p+";",h&&(i+=" if (schema"+o+" === undefined) "+p+" = true; else if (!Array.isArray(schema"+o+")) "+p+" = false; else {"),i+=""+p+" = false;for (var "+A+"=0; "+A+"<"+y+".length; "+A+"++) if (equal("+d+", "+y+"["+A+"])) { "+p+" = true; break; }",h&&(i+=" } "),i+=" if (!"+p+") { ";var v=v||[];v.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { allowedValues: schema"+o+" } ",e.opts.messages!==!1&&(i+=" , message: 'should be equal to one of the allowed values' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var S=i;return i=v.pop(),!e.compositeRule&&f?e.async?i+=" throw new ValidationError(["+S+"]); ":i+=" validate.errors = ["+S+"]; return false; ":i+=" var err = "+S+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" }",f&&(i+=" else { "),i}});var VRt=N((FSo,GRt)=>{"use strict";GRt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,f=!e.opts.allErrors,d="data"+(s||"");if(e.opts.format===!1)return f&&(i+=" if (true) { "),i;var p=e.opts.$data&&a&&a.$data,h;p?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",h="schema"+o):h=a;var g=e.opts.unknownFormats,A=Array.isArray(g);if(p){var y="format"+o,v="isObject"+o,S="formatType"+o;i+=" var "+y+" = formats["+h+"]; var "+v+" = typeof "+y+" == 'object' && !("+y+" instanceof RegExp) && "+y+".validate; var "+S+" = "+v+" && "+y+".type || 'string'; if ("+v+") { ",e.async&&(i+=" var async"+o+" = "+y+".async; "),i+=" "+y+" = "+y+".validate; } if ( ",p&&(i+=" ("+h+" !== undefined && typeof "+h+" != 'string') || "),i+=" (",g!="ignore"&&(i+=" ("+h+" && !"+y+" ",A&&(i+=" && self._opts.unknownFormats.indexOf("+h+") == -1 "),i+=") || "),i+=" ("+y+" && "+S+" == '"+n+"' && !(typeof "+y+" == 'function' ? ",e.async?i+=" (async"+o+" ? await "+y+"("+d+") : "+y+"("+d+")) ":i+=" "+y+"("+d+") ",i+=" : "+y+".test("+d+"))))) {"}else{var y=e.formats[a];if(!y){if(g=="ignore")return e.logger.warn('unknown format "'+a+'" ignored in schema at path "'+e.errSchemaPath+'"'),f&&(i+=" if (true) { "),i;if(A&&g.indexOf(a)>=0)return f&&(i+=" if (true) { "),i;throw new Error('unknown format "'+a+'" is used in schema at path "'+e.errSchemaPath+'"')}var v=typeof y=="object"&&!(y instanceof RegExp)&&y.validate,S=v&&y.type||"string";if(v){var x=y.async===!0;y=y.validate}if(S!=n)return f&&(i+=" if (true) { "),i;if(x){if(!e.async)throw new Error("async format in sync schema");var T="formats"+e.util.getProperty(a)+".validate";i+=" if (!(await "+T+"("+d+"))) { "}else{i+=" if (! ";var T="formats"+e.util.getProperty(a);v&&(T+=".validate"),typeof y=="function"?i+=" "+T+"("+d+") ":i+=" "+T+".test("+d+") ",i+=") { "}}var B=B||[];B.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { format: ",p?i+=""+h:i+=""+e.util.toQuotedString(a),i+=" } ",e.opts.messages!==!1&&(i+=` , message: 'should match format "`,p?i+="' + "+h+" + '":i+=""+e.util.escapeQuotes(a),i+=`"' `),e.opts.verbose&&(i+=" , schema: ",p?i+="validate.schema"+c:i+=""+e.util.toQuotedString(a),i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var P=i;return i=B.pop(),!e.compositeRule&&f?e.async?i+=" throw new ValidationError(["+P+"]); ":i+=" validate.errors = ["+P+"]; return false; ":i+=" var err = "+P+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } ",f&&(i+=" else { "),i}});var WRt=N((PSo,$Rt)=>{"use strict";$Rt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,f=!e.opts.allErrors,d="data"+(s||""),p="valid"+o,h="errs__"+o,g=e.util.copy(e);g.level++;var A="valid"+g.level,y=e.schema.then,v=e.schema.else,S=y!==void 0&&(e.opts.strictKeywords?typeof y=="object"&&Object.keys(y).length>0||y===!1:e.util.schemaHasRules(y,e.RULES.all)),x=v!==void 0&&(e.opts.strictKeywords?typeof v=="object"&&Object.keys(v).length>0||v===!1:e.util.schemaHasRules(v,e.RULES.all)),T=g.baseId;if(S||x){var B;g.createErrors=!1,g.schema=a,g.schemaPath=c,g.errSchemaPath=u,i+=" var "+h+" = errors; var "+p+" = true; ";var P=e.compositeRule;e.compositeRule=g.compositeRule=!0,i+=" "+e.validate(g)+" ",g.baseId=T,g.createErrors=!0,i+=" errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } ",e.compositeRule=g.compositeRule=P,S?(i+=" if ("+A+") { ",g.schema=e.schema.then,g.schemaPath=e.schemaPath+".then",g.errSchemaPath=e.errSchemaPath+"/then",i+=" "+e.validate(g)+" ",g.baseId=T,i+=" "+p+" = "+A+"; ",S&&x?(B="ifClause"+o,i+=" var "+B+" = 'then'; "):B="'then'",i+=" } ",x&&(i+=" else { ")):i+=" if (!"+A+") { ",x&&(g.schema=e.schema.else,g.schemaPath=e.schemaPath+".else",g.errSchemaPath=e.errSchemaPath+"/else",i+=" "+e.validate(g)+" ",g.baseId=T,i+=" "+p+" = "+A+"; ",S&&x?(B="ifClause"+o,i+=" var "+B+" = 'else'; "):B="'else'",i+=" } "),i+=" if (!"+p+") { var err = ",e.createErrors!==!1?(i+=" { keyword: 'if' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { failingKeyword: "+B+" } ",e.opts.messages!==!1&&(i+=` , message: 'should match "' + `+B+` + '" schema' `),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ",i+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&f&&(e.async?i+=" throw new ValidationError(vErrors); ":i+=" validate.errors = vErrors; return false; "),i+=" } ",f&&(i+=" else { ")}else f&&(i+=" if (true) { ");return i}});var zRt=N((LSo,jRt)=>{"use strict";jRt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,f=!e.opts.allErrors,d="data"+(s||""),p="valid"+o,h="errs__"+o,g=e.util.copy(e),A="";g.level++;var y="valid"+g.level,v="i"+o,S=g.dataLevel=e.dataLevel+1,x="data"+S,T=e.baseId;if(i+="var "+h+" = errors;var "+p+";",Array.isArray(a)){var B=e.schema.additionalItems;if(B===!1){i+=" "+p+" = "+d+".length <= "+a.length+"; ";var P=u;u=e.errSchemaPath+"/additionalItems",i+=" if (!"+p+") { ";var L=L||[];L.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+a.length+" } ",e.opts.messages!==!1&&(i+=" , message: 'should NOT have more than "+a.length+" items' "),e.opts.verbose&&(i+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var q=i;i=L.pop(),!e.compositeRule&&f?e.async?i+=" throw new ValidationError(["+q+"]); ":i+=" validate.errors = ["+q+"]; return false; ":i+=" var err = "+q+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } ",u=P,f&&(A+="}",i+=" else { ")}var I=a;if(I){for(var U,O=-1,Q=I.length-1;O<Q;)if(U=I[O+=1],e.opts.strictKeywords?typeof U=="object"&&Object.keys(U).length>0||U===!1:e.util.schemaHasRules(U,e.RULES.all)){i+=" "+y+" = true; if ("+d+".length > "+O+") { ";var F=d+"["+O+"]";g.schema=U,g.schemaPath=c+"["+O+"]",g.errSchemaPath=u+"/"+O,g.errorPath=e.util.getPathExpr(e.errorPath,O,e.opts.jsonPointers,!0),g.dataPathArr[S]=O;var M=e.validate(g);g.baseId=T,e.util.varOccurences(M,x)<2?i+=" "+e.util.varReplace(M,x,F)+" ":i+=" var "+x+" = "+F+"; "+M+" ",i+=" } ",f&&(i+=" if ("+y+") { ",A+="}")}}if(typeof B=="object"&&(e.opts.strictKeywords?typeof B=="object"&&Object.keys(B).length>0||B===!1:e.util.schemaHasRules(B,e.RULES.all))){g.schema=B,g.schemaPath=e.schemaPath+".additionalItems",g.errSchemaPath=e.errSchemaPath+"/additionalItems",i+=" "+y+" = true; if ("+d+".length > "+a.length+") { for (var "+v+" = "+a.length+"; "+v+" < "+d+".length; "+v+"++) { ",g.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers,!0);var F=d+"["+v+"]";g.dataPathArr[S]=v;var M=e.validate(g);g.baseId=T,e.util.varOccurences(M,x)<2?i+=" "+e.util.varReplace(M,x,F)+" ":i+=" var "+x+" = "+F+"; "+M+" ",f&&(i+=" if (!"+y+") break; "),i+=" } } ",f&&(i+=" if ("+y+") { ",A+="}")}}else if(e.opts.strictKeywords?typeof a=="object"&&Object.keys(a).length>0||a===!1:e.util.schemaHasRules(a,e.RULES.all)){g.schema=a,g.schemaPath=c,g.errSchemaPath=u,i+=" for (var "+v+" = 0; "+v+" < "+d+".length; "+v+"++) { ",g.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers,!0);var F=d+"["+v+"]";g.dataPathArr[S]=v;var M=e.validate(g);g.baseId=T,e.util.varOccurences(M,x)<2?i+=" "+e.util.varReplace(M,x,F)+" ":i+=" var "+x+" = "+F+"; "+M+" ",f&&(i+=" if (!"+y+") break; "),i+=" }"}return f&&(i+=" "+A+" if ("+h+" == errors) {"),i}});var IFe=N((USo,YRt)=>{"use strict";YRt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,f=!e.opts.allErrors,T,d="data"+(s||""),p=e.opts.$data&&a&&a.$data,h;p?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",h="schema"+o):h=a;var g=r=="maximum",A=g?"exclusiveMaximum":"exclusiveMinimum",y=e.schema[A],v=e.opts.$data&&y&&y.$data,S=g?"<":">",x=g?">":"<",T=void 0;if(!(p||typeof a=="number"||a===void 0))throw new Error(r+" must be number");if(!(v||y===void 0||typeof y=="number"||typeof y=="boolean"))throw new Error(A+" must be number or boolean");if(v){var B=e.util.getData(y.$data,s,e.dataPathArr),P="exclusive"+o,L="exclType"+o,q="exclIsNumber"+o,I="op"+o,U="' + "+I+" + '";i+=" var schemaExcl"+o+" = "+B+"; ",B="schemaExcl"+o,i+=" var "+P+"; var "+L+" = typeof "+B+"; if ("+L+" != 'boolean' && "+L+" != 'undefined' && "+L+" != 'number') { ";var T=A,O=O||[];O.push(i),i="",e.createErrors!==!1?(i+=" { keyword: '"+(T||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(i+=" , message: '"+A+" should be boolean' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var Q=i;i=O.pop(),!e.compositeRule&&f?e.async?i+=" throw new ValidationError(["+Q+"]); ":i+=" validate.errors = ["+Q+"]; return false; ":i+=" var err = "+Q+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } else if ( ",p&&(i+=" ("+h+" !== undefined && typeof "+h+" != 'number') || "),i+=" "+L+" == 'number' ? ( ("+P+" = "+h+" === undefined || "+B+" "+S+"= "+h+") ? "+d+" "+x+"= "+B+" : "+d+" "+x+" "+h+" ) : ( ("+P+" = "+B+" === true) ? "+d+" "+x+"= "+h+" : "+d+" "+x+" "+h+" ) || "+d+" !== "+d+") { var op"+o+" = "+P+" ? '"+S+"' : '"+S+"='; ",a===void 0&&(T=A,u=e.errSchemaPath+"/"+A,h=B,p=v)}else{var q=typeof y=="number",U=S;if(q&&p){var I="'"+U+"'";i+=" if ( ",p&&(i+=" ("+h+" !== undefined && typeof "+h+" != 'number') || "),i+=" ( "+h+" === undefined || "+y+" "+S+"= "+h+" ? "+d+" "+x+"= "+y+" : "+d+" "+x+" "+h+" ) || "+d+" !== "+d+") { "}else{q&&a===void 0?(P=!0,T=A,u=e.errSchemaPath+"/"+A,h=y,x+="="):(q&&(h=Math[g?"min":"max"](y,a)),y===(q?h:!0)?(P=!0,T=A,u=e.errSchemaPath+"/"+A,x+="="):(P=!1,U+="="));var I="'"+U+"'";i+=" if ( ",p&&(i+=" ("+h+" !== undefined && typeof "+h+" != 'number') || "),i+=" "+d+" "+x+" "+h+" || "+d+" !== "+d+") { "}}T=T||r;var O=O||[];O.push(i),i="",e.createErrors!==!1?(i+=" { keyword: '"+(T||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { comparison: "+I+", limit: "+h+", exclusive: "+P+" } ",e.opts.messages!==!1&&(i+=" , message: 'should be "+U+" ",p?i+="' + "+h:i+=""+h+"'"),e.opts.verbose&&(i+=" , schema: ",p?i+="validate.schema"+c:i+=""+a,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var Q=i;return i=O.pop(),!e.compositeRule&&f?e.async?i+=" throw new ValidationError(["+Q+"]); ":i+=" validate.errors = ["+Q+"]; return false; ":i+=" var err = "+Q+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } ",f&&(i+=" else { "),i}});var DFe=N((QSo,JRt)=>{"use strict";JRt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,f=!e.opts.allErrors,A,d="data"+(s||""),p=e.opts.$data&&a&&a.$data,h;if(p?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",h="schema"+o):h=a,!(p||typeof a=="number"))throw new Error(r+" must be number");var g=r=="maxItems"?">":"<";i+="if ( ",p&&(i+=" ("+h+" !== undefined && typeof "+h+" != 'number') || "),i+=" "+d+".length "+g+" "+h+") { ";var A=r,y=y||[];y.push(i),i="",e.createErrors!==!1?(i+=" { keyword: '"+(A||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+h+" } ",e.opts.messages!==!1&&(i+=" , message: 'should NOT have ",r=="maxItems"?i+="more":i+="fewer",i+=" than ",p?i+="' + "+h+" + '":i+=""+a,i+=" items' "),e.opts.verbose&&(i+=" , schema: ",p?i+="validate.schema"+c:i+=""+a,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var v=i;return i=y.pop(),!e.compositeRule&&f?e.async?i+=" throw new ValidationError(["+v+"]); ":i+=" validate.errors = ["+v+"]; return false; ":i+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",f&&(i+=" else { "),i}});var RFe=N((qSo,KRt)=>{"use strict";KRt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,f=!e.opts.allErrors,A,d="data"+(s||""),p=e.opts.$data&&a&&a.$data,h;if(p?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",h="schema"+o):h=a,!(p||typeof a=="number"))throw new Error(r+" must be number");var g=r=="maxLength"?">":"<";i+="if ( ",p&&(i+=" ("+h+" !== undefined && typeof "+h+" != 'number') || "),e.opts.unicode===!1?i+=" "+d+".length ":i+=" ucs2length("+d+") ",i+=" "+g+" "+h+") { ";var A=r,y=y||[];y.push(i),i="",e.createErrors!==!1?(i+=" { keyword: '"+(A||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+h+" } ",e.opts.messages!==!1&&(i+=" , message: 'should NOT be ",r=="maxLength"?i+="longer":i+="shorter",i+=" than ",p?i+="' + "+h+" + '":i+=""+a,i+=" characters' "),e.opts.verbose&&(i+=" , schema: ",p?i+="validate.schema"+c:i+=""+a,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var v=i;return i=y.pop(),!e.compositeRule&&f?e.async?i+=" throw new ValidationError(["+v+"]); ":i+=" validate.errors = ["+v+"]; return false; ":i+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",f&&(i+=" else { "),i}});var BFe=N((HSo,XRt)=>{"use strict";XRt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,f=!e.opts.allErrors,A,d="data"+(s||""),p=e.opts.$data&&a&&a.$data,h;if(p?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",h="schema"+o):h=a,!(p||typeof a=="number"))throw new Error(r+" must be number");var g=r=="maxProperties"?">":"<";i+="if ( ",p&&(i+=" ("+h+" !== undefined && typeof "+h+" != 'number') || "),i+=" Object.keys("+d+").length "+g+" "+h+") { ";var A=r,y=y||[];y.push(i),i="",e.createErrors!==!1?(i+=" { keyword: '"+(A||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+h+" } ",e.opts.messages!==!1&&(i+=" , message: 'should NOT have ",r=="maxProperties"?i+="more":i+="fewer",i+=" than ",p?i+="' + "+h+" + '":i+=""+a,i+=" properties' "),e.opts.verbose&&(i+=" , schema: ",p?i+="validate.schema"+c:i+=""+a,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var v=i;return i=y.pop(),!e.compositeRule&&f?e.async?i+=" throw new ValidationError(["+v+"]); ":i+=" validate.errors = ["+v+"]; return false; ":i+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",f&&(i+=" else { "),i}});var eBt=N((GSo,ZRt)=>{"use strict";ZRt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,f=!e.opts.allErrors,d="data"+(s||""),p=e.opts.$data&&a&&a.$data,h;if(p?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",h="schema"+o):h=a,!(p||typeof a=="number"))throw new Error(r+" must be number");i+="var division"+o+";if (",p&&(i+=" "+h+" !== undefined && ( typeof "+h+" != 'number' || "),i+=" (division"+o+" = "+d+" / "+h+", ",e.opts.multipleOfPrecision?i+=" Math.abs(Math.round(division"+o+") - division"+o+") > 1e-"+e.opts.multipleOfPrecision+" ":i+=" division"+o+" !== parseInt(division"+o+") ",i+=" ) ",p&&(i+=" ) "),i+=" ) { ";var g=g||[];g.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { multipleOf: "+h+" } ",e.opts.messages!==!1&&(i+=" , message: 'should be multiple of ",p?i+="' + "+h:i+=""+h+"'"),e.opts.verbose&&(i+=" , schema: ",p?i+="validate.schema"+c:i+=""+a,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var A=i;return i=g.pop(),!e.compositeRule&&f?e.async?i+=" throw new ValidationError(["+A+"]); ":i+=" validate.errors = ["+A+"]; return false; ":i+=" var err = "+A+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",f&&(i+=" else { "),i}});var rBt=N((VSo,tBt)=>{"use strict";tBt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,f=!e.opts.allErrors,d="data"+(s||""),p="errs__"+o,h=e.util.copy(e);h.level++;var g="valid"+h.level;if(e.opts.strictKeywords?typeof a=="object"&&Object.keys(a).length>0||a===!1:e.util.schemaHasRules(a,e.RULES.all)){h.schema=a,h.schemaPath=c,h.errSchemaPath=u,i+=" var "+p+" = errors; ";var A=e.compositeRule;e.compositeRule=h.compositeRule=!0,h.createErrors=!1;var y;h.opts.allErrors&&(y=h.opts.allErrors,h.opts.allErrors=!1),i+=" "+e.validate(h)+" ",h.createErrors=!0,y&&(h.opts.allErrors=y),e.compositeRule=h.compositeRule=A,i+=" if ("+g+") { ";var v=v||[];v.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(i+=" , message: 'should NOT be valid' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var S=i;i=v.pop(),!e.compositeRule&&f?e.async?i+=" throw new ValidationError(["+S+"]); ":i+=" validate.errors = ["+S+"]; return false; ":i+=" var err = "+S+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } else { errors = "+p+"; if (vErrors !== null) { if ("+p+") vErrors.length = "+p+"; else vErrors = null; } ",e.opts.allErrors&&(i+=" } ")}else i+=" var err = ",e.createErrors!==!1?(i+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(i+=" , message: 'should NOT be valid' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ",i+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",f&&(i+=" if (false) { ");return i}});var iBt=N(($So,nBt)=>{"use strict";nBt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,f=!e.opts.allErrors,d="data"+(s||""),p="valid"+o,h="errs__"+o,g=e.util.copy(e),A="";g.level++;var y="valid"+g.level,v=g.baseId,S="prevValid"+o,x="passingSchemas"+o;i+="var "+h+" = errors , "+S+" = false , "+p+" = false , "+x+" = null; ";var T=e.compositeRule;e.compositeRule=g.compositeRule=!0;var B=a;if(B)for(var P,L=-1,q=B.length-1;L<q;)P=B[L+=1],(e.opts.strictKeywords?typeof P=="object"&&Object.keys(P).length>0||P===!1:e.util.schemaHasRules(P,e.RULES.all))?(g.schema=P,g.schemaPath=c+"["+L+"]",g.errSchemaPath=u+"/"+L,i+=" "+e.validate(g)+" ",g.baseId=v):i+=" var "+y+" = true; ",L&&(i+=" if ("+y+" && "+S+") { "+p+" = false; "+x+" = ["+x+", "+L+"]; } else { ",A+="}"),i+=" if ("+y+") { "+p+" = "+S+" = true; "+x+" = "+L+"; }";return e.compositeRule=g.compositeRule=T,i+=""+A+"if (!"+p+") { var err = ",e.createErrors!==!1?(i+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { passingSchemas: "+x+" } ",e.opts.messages!==!1&&(i+=" , message: 'should match exactly one schema in oneOf' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ",i+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&f&&(e.async?i+=" throw new ValidationError(vErrors); ":i+=" validate.errors = vErrors; return false; "),i+="} else { errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; }",e.opts.allErrors&&(i+=" } "),i}});var sBt=N((WSo,oBt)=>{"use strict";oBt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,f=!e.opts.allErrors,d="data"+(s||""),p=e.opts.$data&&a&&a.$data,h;p?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",h="schema"+o):h=a;var g=p?"(new RegExp("+h+"))":e.usePattern(a);i+="if ( ",p&&(i+=" ("+h+" !== undefined && typeof "+h+" != 'string') || "),i+=" !"+g+".test("+d+") ) { ";var A=A||[];A.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { pattern: ",p?i+=""+h:i+=""+e.util.toQuotedString(a),i+=" } ",e.opts.messages!==!1&&(i+=` , message: 'should match pattern "`,p?i+="' + "+h+" + '":i+=""+e.util.escapeQuotes(a),i+=`"' `),e.opts.verbose&&(i+=" , schema: ",p?i+="validate.schema"+c:i+=""+e.util.toQuotedString(a),i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var y=i;return i=A.pop(),!e.compositeRule&&f?e.async?i+=" throw new ValidationError(["+y+"]); ":i+=" validate.errors = ["+y+"]; return false; ":i+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",f&&(i+=" else { "),i}});var lBt=N((jSo,aBt)=>{"use strict";aBt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,f=!e.opts.allErrors,d="data"+(s||""),p="errs__"+o,h=e.util.copy(e),g="";h.level++;var A="valid"+h.level,y="key"+o,v="idx"+o,S=h.dataLevel=e.dataLevel+1,x="data"+S,T="dataProperties"+o,B=Object.keys(a||{}).filter($),P=e.schema.patternProperties||{},L=Object.keys(P).filter($),q=e.schema.additionalProperties,I=B.length||L.length,U=q===!1,O=typeof q=="object"&&Object.keys(q).length,Q=e.opts.removeAdditional,F=U||O||Q,M=e.opts.ownProperties,V=e.baseId,G=e.schema.required;if(G&&!(e.opts.$data&&G.$data)&&G.length<e.opts.loopRequired)var j=e.util.toHash(G);function $(Fe){return Fe!=="__proto__"}if(i+="var "+p+" = errors;var "+A+" = true;",M&&(i+=" var "+T+" = undefined;"),F){if(M?i+=" "+T+" = "+T+" || Object.keys("+d+"); for (var "+v+"=0; "+v+"<"+T+".length; "+v+"++) { var "+y+" = "+T+"["+v+"]; ":i+=" for (var "+y+" in "+d+") { ",I){if(i+=" var isAdditional"+o+" = !(false ",B.length)if(B.length>8)i+=" || validate.schema"+c+".hasOwnProperty("+y+") ";else{var re=B;if(re)for(var K,me=-1,ve=re.length-1;me<ve;)K=re[me+=1],i+=" || "+y+" == "+e.util.toQuotedString(K)+" "}if(L.length){var Ae=L;if(Ae)for(var Se,xe=-1,pe=Ae.length-1;xe<pe;)Se=Ae[xe+=1],i+=" || "+e.usePattern(Se)+".test("+y+") "}i+=" ); if (isAdditional"+o+") { "}if(Q=="all")i+=" delete "+d+"["+y+"]; ";else{var Ee=e.errorPath,he="' + "+y+" + '";if(e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(e.errorPath,y,e.opts.jsonPointers)),U)if(Q)i+=" delete "+d+"["+y+"]; ";else{i+=" "+A+" = false; ";var ee=u;u=e.errSchemaPath+"/additionalProperties";var de=de||[];de.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'additionalProperties' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { additionalProperty: '"+he+"' } ",e.opts.messages!==!1&&(i+=" , message: '",e.opts._errorDataPathProperty?i+="is an invalid additional property":i+="should NOT have additional properties",i+="' "),e.opts.verbose&&(i+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var X=i;i=de.pop(),!e.compositeRule&&f?e.async?i+=" throw new ValidationError(["+X+"]); ":i+=" validate.errors = ["+X+"]; return false; ":i+=" var err = "+X+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u=ee,f&&(i+=" break; ")}else if(O)if(Q=="failing"){i+=" var "+p+" = errors; ";var oe=e.compositeRule;e.compositeRule=h.compositeRule=!0,h.schema=q,h.schemaPath=e.schemaPath+".additionalProperties",h.errSchemaPath=e.errSchemaPath+"/additionalProperties",h.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,y,e.opts.jsonPointers);var ge=d+"["+y+"]";h.dataPathArr[S]=y;var le=e.validate(h);h.baseId=V,e.util.varOccurences(le,x)<2?i+=" "+e.util.varReplace(le,x,ge)+" ":i+=" var "+x+" = "+ge+"; "+le+" ",i+=" if (!"+A+") { errors = "+p+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+d+"["+y+"]; } ",e.compositeRule=h.compositeRule=oe}else{h.schema=q,h.schemaPath=e.schemaPath+".additionalProperties",h.errSchemaPath=e.errSchemaPath+"/additionalProperties",h.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,y,e.opts.jsonPointers);var ge=d+"["+y+"]";h.dataPathArr[S]=y;var le=e.validate(h);h.baseId=V,e.util.varOccurences(le,x)<2?i+=" "+e.util.varReplace(le,x,ge)+" ":i+=" var "+x+" = "+ge+"; "+le+" ",f&&(i+=" if (!"+A+") break; ")}e.errorPath=Ee}I&&(i+=" } "),i+=" } ",f&&(i+=" if ("+A+") { ",g+="}")}var J=e.opts.useDefaults&&!e.compositeRule;if(B.length){var ne=B;if(ne)for(var K,we=-1,ye=ne.length-1;we<ye;){K=ne[we+=1];var Z=a[K];if(e.opts.strictKeywords?typeof Z=="object"&&Object.keys(Z).length>0||Z===!1:e.util.schemaHasRules(Z,e.RULES.all)){var Re=e.util.getProperty(K),ge=d+Re,Qe=J&&Z.default!==void 0;h.schema=Z,h.schemaPath=c+Re,h.errSchemaPath=u+"/"+e.util.escapeFragment(K),h.errorPath=e.util.getPath(e.errorPath,K,e.opts.jsonPointers),h.dataPathArr[S]=e.util.toQuotedString(K);var le=e.validate(h);if(h.baseId=V,e.util.varOccurences(le,x)<2){le=e.util.varReplace(le,x,ge);var qe=ge}else{var qe=x;i+=" var "+x+" = "+ge+"; "}if(Qe)i+=" "+le+" ";else{if(j&&j[K]){i+=" if ( "+qe+" === undefined ",M&&(i+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(K)+"') "),i+=") { "+A+" = false; ";var Ee=e.errorPath,ee=u,Ge=e.util.escapeQuotes(K);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(Ee,K,e.opts.jsonPointers)),u=e.errSchemaPath+"/required";var de=de||[];de.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+Ge+"' } ",e.opts.messages!==!1&&(i+=" , message: '",e.opts._errorDataPathProperty?i+="is a required property":i+="should have required property \\'"+Ge+"\\'",i+="' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var X=i;i=de.pop(),!e.compositeRule&&f?e.async?i+=" throw new ValidationError(["+X+"]); ":i+=" validate.errors = ["+X+"]; return false; ":i+=" var err = "+X+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u=ee,e.errorPath=Ee,i+=" } else { "}else f?(i+=" if ( "+qe+" === undefined ",M&&(i+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(K)+"') "),i+=") { "+A+" = true; } else { "):(i+=" if ("+qe+" !== undefined ",M&&(i+=" && Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(K)+"') "),i+=" ) { ");i+=" "+le+" } "}}f&&(i+=" if ("+A+") { ",g+="}")}}if(L.length){var ce=L;if(ce)for(var Se,Ne=-1,Me=ce.length-1;Ne<Me;){Se=ce[Ne+=1];var Z=P[Se];if(e.opts.strictKeywords?typeof Z=="object"&&Object.keys(Z).length>0||Z===!1:e.util.schemaHasRules(Z,e.RULES.all)){h.schema=Z,h.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty(Se),h.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment(Se),M?i+=" "+T+" = "+T+" || Object.keys("+d+"); for (var "+v+"=0; "+v+"<"+T+".length; "+v+"++) { var "+y+" = "+T+"["+v+"]; ":i+=" for (var "+y+" in "+d+") { ",i+=" if ("+e.usePattern(Se)+".test("+y+")) { ",h.errorPath=e.util.getPathExpr(e.errorPath,y,e.opts.jsonPointers);var ge=d+"["+y+"]";h.dataPathArr[S]=y;var le=e.validate(h);h.baseId=V,e.util.varOccurences(le,x)<2?i+=" "+e.util.varReplace(le,x,ge)+" ":i+=" var "+x+" = "+ge+"; "+le+" ",f&&(i+=" if (!"+A+") break; "),i+=" } ",f&&(i+=" else "+A+" = true; "),i+=" } ",f&&(i+=" if ("+A+") { ",g+="}")}}}return f&&(i+=" "+g+" if ("+p+" == errors) {"),i}});var uBt=N((zSo,cBt)=>{"use strict";cBt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,f=!e.opts.allErrors,d="data"+(s||""),p="errs__"+o,h=e.util.copy(e),g="";h.level++;var A="valid"+h.level;if(i+="var "+p+" = errors;",e.opts.strictKeywords?typeof a=="object"&&Object.keys(a).length>0||a===!1:e.util.schemaHasRules(a,e.RULES.all)){h.schema=a,h.schemaPath=c,h.errSchemaPath=u;var y="key"+o,v="idx"+o,S="i"+o,x="' + "+y+" + '",T=h.dataLevel=e.dataLevel+1,B="data"+T,P="dataProperties"+o,L=e.opts.ownProperties,q=e.baseId;L&&(i+=" var "+P+" = undefined; "),L?i+=" "+P+" = "+P+" || Object.keys("+d+"); for (var "+v+"=0; "+v+"<"+P+".length; "+v+"++) { var "+y+" = "+P+"["+v+"]; ":i+=" for (var "+y+" in "+d+") { ",i+=" var startErrs"+o+" = errors; ";var I=y,U=e.compositeRule;e.compositeRule=h.compositeRule=!0;var O=e.validate(h);h.baseId=q,e.util.varOccurences(O,B)<2?i+=" "+e.util.varReplace(O,B,I)+" ":i+=" var "+B+" = "+I+"; "+O+" ",e.compositeRule=h.compositeRule=U,i+=" if (!"+A+") { for (var "+S+"=startErrs"+o+"; "+S+"<errors; "+S+"++) { vErrors["+S+"].propertyName = "+y+"; } var err = ",e.createErrors!==!1?(i+=" { keyword: 'propertyNames' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { propertyName: '"+x+"' } ",e.opts.messages!==!1&&(i+=" , message: 'property name \\'"+x+"\\' is invalid' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ",i+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&f&&(e.async?i+=" throw new ValidationError(vErrors); ":i+=" validate.errors = vErrors; return false; "),f&&(i+=" break; "),i+=" } }"}return f&&(i+=" "+g+" if ("+p+" == errors) {"),i}});var dBt=N((YSo,fBt)=>{"use strict";fBt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,f=!e.opts.allErrors,d="data"+(s||""),p="valid"+o,h=e.opts.$data&&a&&a.$data,g;h?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",g="schema"+o):g=a;var A="schema"+o;if(!h)if(a.length<e.opts.loopRequired&&e.schema.properties&&Object.keys(e.schema.properties).length){var y=[],v=a;if(v)for(var S,x=-1,T=v.length-1;x<T;){S=v[x+=1];var B=e.schema.properties[S];B&&(e.opts.strictKeywords?typeof B=="object"&&Object.keys(B).length>0||B===!1:e.util.schemaHasRules(B,e.RULES.all))||(y[y.length]=S)}}else var y=a;if(h||y.length){var P=e.errorPath,L=h||y.length>=e.opts.loopRequired,q=e.opts.ownProperties;if(f)if(i+=" var missing"+o+"; ",L){h||(i+=" var "+A+" = validate.schema"+c+"; ");var I="i"+o,U="schema"+o+"["+I+"]",O="' + "+U+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(P,U,e.opts.jsonPointers)),i+=" var "+p+" = true; ",h&&(i+=" if (schema"+o+" === undefined) "+p+" = true; else if (!Array.isArray(schema"+o+")) "+p+" = false; else {"),i+=" for (var "+I+" = 0; "+I+" < "+A+".length; "+I+"++) { "+p+" = "+d+"["+A+"["+I+"]] !== undefined ",q&&(i+=" && Object.prototype.hasOwnProperty.call("+d+", "+A+"["+I+"]) "),i+="; if (!"+p+") break; } ",h&&(i+=" } "),i+=" if (!"+p+") { ";var Q=Q||[];Q.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+O+"' } ",e.opts.messages!==!1&&(i+=" , message: '",e.opts._errorDataPathProperty?i+="is a required property":i+="should have required property \\'"+O+"\\'",i+="' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var F=i;i=Q.pop(),!e.compositeRule&&f?e.async?i+=" throw new ValidationError(["+F+"]); ":i+=" validate.errors = ["+F+"]; return false; ":i+=" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } else { "}else{i+=" if ( ";var M=y;if(M)for(var V,I=-1,G=M.length-1;I<G;){V=M[I+=1],I&&(i+=" || ");var j=e.util.getProperty(V),$=d+j;i+=" ( ( "+$+" === undefined ",q&&(i+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(V)+"') "),i+=") && (missing"+o+" = "+e.util.toQuotedString(e.opts.jsonPointers?V:j)+") ) "}i+=") { ";var U="missing"+o,O="' + "+U+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(P,U,!0):P+" + "+U);var Q=Q||[];Q.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+O+"' } ",e.opts.messages!==!1&&(i+=" , message: '",e.opts._errorDataPathProperty?i+="is a required property":i+="should have required property \\'"+O+"\\'",i+="' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var F=i;i=Q.pop(),!e.compositeRule&&f?e.async?i+=" throw new ValidationError(["+F+"]); ":i+=" validate.errors = ["+F+"]; return false; ":i+=" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } else { "}else if(L){h||(i+=" var "+A+" = validate.schema"+c+"; ");var I="i"+o,U="schema"+o+"["+I+"]",O="' + "+U+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(P,U,e.opts.jsonPointers)),h&&(i+=" if ("+A+" && !Array.isArray("+A+")) { var err = ",e.createErrors!==!1?(i+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+O+"' } ",e.opts.messages!==!1&&(i+=" , message: '",e.opts._errorDataPathProperty?i+="is a required property":i+="should have required property \\'"+O+"\\'",i+="' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ",i+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+A+" !== undefined) { "),i+=" for (var "+I+" = 0; "+I+" < "+A+".length; "+I+"++) { if ("+d+"["+A+"["+I+"]] === undefined ",q&&(i+=" || ! Object.prototype.hasOwnProperty.call("+d+", "+A+"["+I+"]) "),i+=") { var err = ",e.createErrors!==!1?(i+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+O+"' } ",e.opts.messages!==!1&&(i+=" , message: '",e.opts._errorDataPathProperty?i+="is a required property":i+="should have required property \\'"+O+"\\'",i+="' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ",i+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",h&&(i+=" } ")}else{var re=y;if(re)for(var V,K=-1,me=re.length-1;K<me;){V=re[K+=1];var j=e.util.getProperty(V),O=e.util.escapeQuotes(V),$=d+j;e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(P,V,e.opts.jsonPointers)),i+=" if ( "+$+" === undefined ",q&&(i+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(V)+"') "),i+=") { var err = ",e.createErrors!==!1?(i+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+O+"' } ",e.opts.messages!==!1&&(i+=" , message: '",e.opts._errorDataPathProperty?i+="is a required property":i+="should have required property \\'"+O+"\\'",i+="' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ",i+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}e.errorPath=P}else f&&(i+=" if (true) {");return i}});var hBt=N((JSo,pBt)=>{"use strict";pBt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,f=!e.opts.allErrors,d="data"+(s||""),p="valid"+o,h=e.opts.$data&&a&&a.$data,g;if(h?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",g="schema"+o):g=a,(a||h)&&e.opts.uniqueItems!==!1){h&&(i+=" var "+p+"; if ("+g+" === false || "+g+" === undefined) "+p+" = true; else if (typeof "+g+" != 'boolean') "+p+" = false; else { "),i+=" var i = "+d+".length , "+p+" = true , j; if (i > 1) { ";var A=e.schema.items&&e.schema.items.type,y=Array.isArray(A);if(!A||A=="object"||A=="array"||y&&(A.indexOf("object")>=0||A.indexOf("array")>=0))i+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+d+"[i], "+d+"[j])) { "+p+" = false; break outer; } } } ";else{i+=" var itemIndices = {}, item; for (;i--;) { var item = "+d+"[i]; ";var v="checkDataType"+(y?"s":"");i+=" if ("+e.util[v](A,"item",e.opts.strictNumbers,!0)+") continue; ",y&&(i+=` if (typeof item == 'string') item = '"' + item; `),i+=" if (typeof itemIndices[item] == 'number') { "+p+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}i+=" } ",h&&(i+=" } "),i+=" if (!"+p+") { ";var S=S||[];S.push(i),i="",e.createErrors!==!1?(i+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { i: i, j: j } ",e.opts.messages!==!1&&(i+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(i+=" , schema: ",h?i+="validate.schema"+c:i+=""+a,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var x=i;i=S.pop(),!e.compositeRule&&f?e.async?i+=" throw new ValidationError(["+x+"]); ":i+=" validate.errors = ["+x+"]; return false; ":i+=" var err = "+x+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } ",f&&(i+=" else { ")}else f&&(i+=" if (true) { ");return i}});var gBt=N((KSo,mBt)=>{"use strict";mBt.exports={$ref:IRt(),allOf:RRt(),anyOf:NRt(),$comment:MRt(),const:FRt(),contains:LRt(),dependencies:QRt(),enum:HRt(),format:VRt(),if:WRt(),items:zRt(),maximum:IFe(),minimum:IFe(),maxItems:DFe(),minItems:DFe(),maxLength:RFe(),minLength:RFe(),maxProperties:BFe(),minProperties:BFe(),multipleOf:eBt(),not:rBt(),oneOf:iBt(),pattern:sBt(),properties:lBt(),propertyNames:uBt(),required:dBt(),uniqueItems:hBt(),validate:wFe()}});var EBt=N((XSo,yBt)=>{"use strict";var ABt=gBt(),NFe=sN().toHash;yBt.exports=function(){var e=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}],r=["type","$comment"],n=["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"],i=["number","integer","string","array","object","boolean","null"];return e.all=NFe(r),e.types=NFe(i),e.forEach(function(o){o.rules=o.rules.map(function(s){var a;if(typeof s=="object"){var c=Object.keys(s)[0];a=s[c],s=c,a.forEach(function(f){r.push(f),e.all[f]=!0})}r.push(s);var u=e.all[s]={keyword:s,code:ABt[s],implements:a};return u}),e.all.$comment={keyword:"$comment",code:ABt.$comment},o.type&&(e.types[o.type]=o)}),e.keywords=NFe(r.concat(n)),e.custom={},e}});var bBt=N((ZSo,CBt)=>{"use strict";var vBt=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"];CBt.exports=function(t,e){for(var r=0;r<e.length;r++){t=JSON.parse(JSON.stringify(t));var n=e[r].split("/"),i=t,o;for(o=1;o<n.length;o++)i=i[n[o]];for(o=0;o<vBt.length;o++){var s=vBt[o],a=i[s];a&&(i[s]={anyOf:[a,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]})}}return t}});var xBt=N((exo,SBt)=>{"use strict";var hSn=l0e().MissingRef;SBt.exports=_Bt;function _Bt(t,e,r){var n=this;if(typeof this._opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");typeof e=="function"&&(r=e,e=void 0);var i=o(t).then(function(){var a=n._addSchema(t,void 0,e);return a.validate||s(a)});return r&&i.then(function(a){r(null,a)},r),i;function o(a){var c=a.$schema;return c&&!n.getSchema(c)?_Bt.call(n,{$ref:c},!0):Promise.resolve()}function s(a){try{return n._compile(a)}catch(u){if(u instanceof hSn)return c(u);throw u}function c(u){var f=u.missingSchema;if(h(f))throw new Error("Schema "+f+" is loaded but "+u.missingRef+" cannot be resolved");var d=n._loadingSchemas[f];return d||(d=n._loadingSchemas[f]=n._opts.loadSchema(f),d.then(p,p)),d.then(function(g){if(!h(f))return o(g).then(function(){h(f)||n.addSchema(g,f,void 0,e)})}).then(function(){return s(a)});function p(){delete n._loadingSchemas[f]}function h(g){return n._refs[g]||n._schemas[g]}}}}});var TBt=N((txo,wBt)=>{"use strict";wBt.exports=function(e,r,n){var i=" ",o=e.level,s=e.dataLevel,a=e.schema[r],c=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,f=!e.opts.allErrors,d,p="data"+(s||""),h="valid"+o,g="errs__"+o,A=e.opts.$data&&a&&a.$data,y;A?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",y="schema"+o):y=a;var v=this,S="definition"+o,x=v.definition,T="",B,P,L,q,I;if(A&&x.$data){I="keywordValidate"+o;var U=x.validateSchema;i+=" var "+S+" = RULES.custom['"+r+"'].definition; var "+I+" = "+S+".validate;"}else{if(q=e.useCustomRule(v,a,e.schema,e),!q)return;y="validate.schema"+c,I=q.code,B=x.compile,P=x.inline,L=x.macro}var O=I+".errors",Q="i"+o,F="ruleErr"+o,M=x.async;if(M&&!e.async)throw new Error("async keyword in sync schema");if(P||L||(i+=""+O+" = null;"),i+="var "+g+" = errors;var "+h+";",A&&x.$data&&(T+="}",i+=" if ("+y+" === undefined) { "+h+" = true; } else { ",U&&(T+="}",i+=" "+h+" = "+S+".validateSchema("+y+"); if ("+h+") { ")),P)x.statements?i+=" "+q.validate+" ":i+=" "+h+" = "+q.validate+"; ";else if(L){var V=e.util.copy(e),T="";V.level++;var G="valid"+V.level;V.schema=q.validate,V.schemaPath="";var j=e.compositeRule;e.compositeRule=V.compositeRule=!0;var $=e.validate(V).replace(/validate\.schema/g,I);e.compositeRule=V.compositeRule=j,i+=" "+$}else{var re=re||[];re.push(i),i="",i+=" "+I+".call( ",e.opts.passContext?i+="this":i+="self",B||x.schema===!1?i+=" , "+p+" ":i+=" , "+y+" , "+p+" , validate.schema"+e.schemaPath+" ",i+=" , (dataPath || '')",e.errorPath!='""'&&(i+=" + "+e.errorPath);var K=s?"data"+(s-1||""):"parentData",me=s?e.dataPathArr[s]:"parentDataProperty";i+=" , "+K+" , "+me+" , rootData ) ";var ve=i;i=re.pop(),x.errors===!1?(i+=" "+h+" = ",M&&(i+="await "),i+=""+ve+"; "):M?(O="customErrors"+o,i+=" var "+O+" = null; try { "+h+" = await "+ve+"; } catch (e) { "+h+" = false; if (e instanceof ValidationError) "+O+" = e.errors; else throw e; } "):i+=" "+O+" = null; "+h+" = "+ve+"; "}if(x.modifying&&(i+=" if ("+K+") "+p+" = "+K+"["+me+"];"),i+=""+T,x.valid)f&&(i+=" if (true) { ");else{i+=" if ( ",x.valid===void 0?(i+=" !",L?i+=""+G:i+=""+h):i+=" "+!x.valid+" ",i+=") { ",d=v.keyword;var re=re||[];re.push(i),i="";var re=re||[];re.push(i),i="",e.createErrors!==!1?(i+=" { keyword: '"+(d||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { keyword: '"+v.keyword+"' } ",e.opts.messages!==!1&&(i+=` , message: 'should pass "`+v.keyword+`" keyword validation' `),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+p+" "),i+=" } "):i+=" {} ";var Ae=i;i=re.pop(),!e.compositeRule&&f?e.async?i+=" throw new ValidationError(["+Ae+"]); ":i+=" validate.errors = ["+Ae+"]; return false; ":i+=" var err = "+Ae+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";var Se=i;i=re.pop(),P?x.errors?x.errors!="full"&&(i+=" for (var "+Q+"="+g+"; "+Q+"<errors; "+Q+"++) { var "+F+" = vErrors["+Q+"]; if ("+F+".dataPath === undefined) "+F+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+F+".schemaPath === undefined) { "+F+'.schemaPath = "'+u+'"; } ',e.opts.verbose&&(i+=" "+F+".schema = "+y+"; "+F+".data = "+p+"; "),i+=" } "):x.errors===!1?i+=" "+Se+" ":(i+=" if ("+g+" == errors) { "+Se+" } else { for (var "+Q+"="+g+"; "+Q+"<errors; "+Q+"++) { var "+F+" = vErrors["+Q+"]; if ("+F+".dataPath === undefined) "+F+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+F+".schemaPath === undefined) { "+F+'.schemaPath = "'+u+'"; } ',e.opts.verbose&&(i+=" "+F+".schema = "+y+"; "+F+".data = "+p+"; "),i+=" } } "):L?(i+=" var err = ",e.createErrors!==!1?(i+=" { keyword: '"+(d||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { keyword: '"+v.keyword+"' } ",e.opts.messages!==!1&&(i+=` , message: 'should pass "`+v.keyword+`" keyword validation' `),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+p+" "),i+=" } "):i+=" {} ",i+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&f&&(e.async?i+=" throw new ValidationError(vErrors); ":i+=" validate.errors = vErrors; return false; ")):x.errors===!1?i+=" "+Se+" ":(i+=" if (Array.isArray("+O+")) { if (vErrors === null) vErrors = "+O+"; else vErrors = vErrors.concat("+O+"); errors = vErrors.length; for (var "+Q+"="+g+"; "+Q+"<errors; "+Q+"++) { var "+F+" = vErrors["+Q+"]; if ("+F+".dataPath === undefined) "+F+".dataPath = (dataPath || '') + "+e.errorPath+"; "+F+'.schemaPath = "'+u+'"; ',e.opts.verbose&&(i+=" "+F+".schema = "+y+"; "+F+".data = "+p+"; "),i+=" } } else { "+Se+" } "),i+=" } ",f&&(i+=" else { ")}return i}});var OFe=N((rxo,mSn)=>{mSn.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var RBt=N((nxo,DBt)=>{"use strict";var IBt=OFe();DBt.exports={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:IBt.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:IBt.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}}});var NBt=N((ixo,BBt)=>{"use strict";var gSn=/^[a-z_$][a-z0-9_$-]*$/i,ASn=TBt(),ySn=RBt();BBt.exports={add:ESn,get:vSn,remove:CSn,validate:MFe};function ESn(t,e){var r=this.RULES;if(r.keywords[t])throw new Error("Keyword "+t+" is already defined");if(!gSn.test(t))throw new Error("Keyword "+t+" is not a valid identifier");if(e){this.validateKeyword(e,!0);var n=e.type;if(Array.isArray(n))for(var i=0;i<n.length;i++)s(t,n[i],e);else s(t,n,e);var o=e.metaSchema;o&&(e.$data&&this._opts.$data&&(o={anyOf:[o,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}),e.validateSchema=this.compile(o,!0))}r.keywords[t]=r.all[t]=!0;function s(a,c,u){for(var f,d=0;d<r.length;d++){var p=r[d];if(p.type==c){f=p;break}}f||(f={type:c,rules:[]},r.push(f));var h={keyword:a,definition:u,custom:!0,code:ASn,implements:u.implements};f.rules.push(h),r.custom[a]=h}return this}function vSn(t){var e=this.RULES.custom[t];return e?e.definition:this.RULES.keywords[t]||!1}function CSn(t){var e=this.RULES;delete e.keywords[t],delete e.all[t],delete e.custom[t];for(var r=0;r<e.length;r++)for(var n=e[r].rules,i=0;i<n.length;i++)if(n[i].keyword==t){n.splice(i,1);break}return this}function MFe(t,e){MFe.errors=null;var r=this._validateKeyword=this._validateKeyword||this.compile(ySn,!0);if(r(t))return!0;if(MFe.errors=r.errors,e)throw new Error("custom keyword definition is invalid: "+this.errorsText(r.errors));return!1}});var OBt=N((oxo,bSn)=>{bSn.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON Schema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var GBt=N((sxo,HBt)=>{"use strict";var kBt=dRt(),aN=a0e(),_Sn=hRt(),FBt=EFe(),SSn=xFe(),xSn=wRt(),wSn=EBt(),PBt=bBt(),LBt=sN();HBt.exports=td;td.prototype.validate=ISn;td.prototype.compile=DSn;td.prototype.addSchema=RSn;td.prototype.addMetaSchema=BSn;td.prototype.validateSchema=NSn;td.prototype.getSchema=MSn;td.prototype.removeSchema=FSn;td.prototype.addFormat=VSn;td.prototype.errorsText=GSn;td.prototype._addSchema=PSn;td.prototype._compile=LSn;td.prototype.compileAsync=xBt();var g0e=NBt();td.prototype.addKeyword=g0e.add;td.prototype.getKeyword=g0e.get;td.prototype.removeKeyword=g0e.remove;td.prototype.validateKeyword=g0e.validate;var UBt=l0e();td.ValidationError=UBt.Validation;td.MissingRefError=UBt.MissingRef;td.$dataMetaSchema=PBt;var m0e="http://json-schema.org/draft-07/schema",MBt=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],TSn=["/properties"];function td(t){if(!(this instanceof td))return new td(t);t=this._opts=LBt.copy(t)||{},JSn(this),this._schemas={},this._refs={},this._fragments={},this._formats=xSn(t.format),this._cache=t.cache||new _Sn,this._loadingSchemas={},this._compilations=[],this.RULES=wSn(),this._getId=USn(t),t.loopRequired=t.loopRequired||1/0,t.errorDataPath=="property"&&(t._errorDataPathProperty=!0),t.serialize===void 0&&(t.serialize=SSn),this._metaOpts=YSn(this),t.formats&&jSn(this),t.keywords&&zSn(this),$Sn(this),typeof t.meta=="object"&&this.addMetaSchema(t.meta),t.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),WSn(this)}function ISn(t,e){var r;if(typeof t=="string"){if(r=this.getSchema(t),!r)throw new Error('no schema with key or ref "'+t+'"')}else{var n=this._addSchema(t);r=n.validate||this._compile(n)}var i=r(e);return r.$async!==!0&&(this.errors=r.errors),i}function DSn(t,e){var r=this._addSchema(t,void 0,e);return r.validate||this._compile(r)}function RSn(t,e,r,n){if(Array.isArray(t)){for(var i=0;i<t.length;i++)this.addSchema(t[i],void 0,r,n);return this}var o=this._getId(t);if(o!==void 0&&typeof o!="string")throw new Error("schema id must be string");return e=aN.normalizeId(e||o),qBt(this,e),this._schemas[e]=this._addSchema(t,r,n,!0),this}function BSn(t,e,r){return this.addSchema(t,e,r,!0),this}function NSn(t,e){var r=t.$schema;if(r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this._opts.defaultMeta||OSn(this),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;var n=this.validate(r,t);if(!n&&e){var i="schema is invalid: "+this.errorsText();if(this._opts.validateSchema=="log")this.logger.error(i);else throw new Error(i)}return n}function OSn(t){var e=t._opts.meta;return t._opts.defaultMeta=typeof e=="object"?t._getId(e)||e:t.getSchema(m0e)?m0e:void 0,t._opts.defaultMeta}function MSn(t){var e=QBt(this,t);switch(typeof e){case"object":return e.validate||this._compile(e);case"string":return this.getSchema(e);case"undefined":return kSn(this,t)}}function kSn(t,e){var r=aN.schema.call(t,{schema:{}},e);if(r){var n=r.schema,i=r.root,o=r.baseId,s=kBt.call(t,n,i,void 0,o);return t._fragments[e]=new FBt({ref:e,fragment:!0,schema:n,root:i,baseId:o,validate:s}),s}}function QBt(t,e){return e=aN.normalizeId(e),t._schemas[e]||t._refs[e]||t._fragments[e]}function FSn(t){if(t instanceof RegExp)return h0e(this,this._schemas,t),h0e(this,this._refs,t),this;switch(typeof t){case"undefined":return h0e(this,this._schemas),h0e(this,this._refs),this._cache.clear(),this;case"string":var e=QBt(this,t);return e&&this._cache.del(e.cacheKey),delete this._schemas[t],delete this._refs[t],this;case"object":var r=this._opts.serialize,n=r?r(t):t;this._cache.del(n);var i=this._getId(t);i&&(i=aN.normalizeId(i),delete this._schemas[i],delete this._refs[i])}return this}function h0e(t,e,r){for(var n in e){var i=e[n];!i.meta&&(!r||r.test(n))&&(t._cache.del(i.cacheKey),delete e[n])}}function PSn(t,e,r,n){if(typeof t!="object"&&typeof t!="boolean")throw new Error("schema should be object or boolean");var i=this._opts.serialize,o=i?i(t):t,s=this._cache.get(o);if(s)return s;n=n||this._opts.addUsedSchema!==!1;var a=aN.normalizeId(this._getId(t));a&&n&&qBt(this,a);var c=this._opts.validateSchema!==!1&&!e,u;c&&!(u=a&&a==aN.normalizeId(t.$schema))&&this.validateSchema(t,!0);var f=aN.ids.call(this,t),d=new FBt({id:a,schema:t,localRefs:f,cacheKey:o,meta:r});return a[0]!="#"&&n&&(this._refs[a]=d),this._cache.put(o,d),c&&u&&this.validateSchema(t,!0),d}function LSn(t,e){if(t.compiling)return t.validate=i,i.schema=t.schema,i.errors=null,i.root=e||i,t.schema.$async===!0&&(i.$async=!0),i;t.compiling=!0;var r;t.meta&&(r=this._opts,this._opts=this._metaOpts);var n;try{n=kBt.call(this,t.schema,e,t.localRefs)}catch(o){throw delete t.validate,o}finally{t.compiling=!1,t.meta&&(this._opts=r)}return t.validate=n,t.refs=n.refs,t.refVal=n.refVal,t.root=n.root,n;function i(){var o=t.validate,s=o.apply(this,arguments);return i.errors=o.errors,s}}function USn(t){switch(t.schemaId){case"auto":return HSn;case"id":return QSn;default:return qSn}}function QSn(t){return t.$id&&this.logger.warn("schema $id ignored",t.$id),t.id}function qSn(t){return t.id&&this.logger.warn("schema id ignored",t.id),t.$id}function HSn(t){if(t.$id&&t.id&&t.$id!=t.id)throw new Error("schema $id is different from id");return t.$id||t.id}function GSn(t,e){if(t=t||this.errors,!t)return"No errors";e=e||{};for(var r=e.separator===void 0?", ":e.separator,n=e.dataVar===void 0?"data":e.dataVar,i="",o=0;o<t.length;o++){var s=t[o];s&&(i+=n+s.dataPath+" "+s.message+r)}return i.slice(0,-r.length)}function VSn(t,e){return typeof e=="string"&&(e=new RegExp(e)),this._formats[t]=e,this}function $Sn(t){var e;if(t._opts.$data&&(e=OBt(),t.addMetaSchema(e,e.$id,!0)),t._opts.meta!==!1){var r=OFe();t._opts.$data&&(r=PBt(r,TSn)),t.addMetaSchema(r,m0e,!0),t._refs["http://json-schema.org/schema"]=m0e}}function WSn(t){var e=t._opts.schemas;if(e)if(Array.isArray(e))t.addSchema(e);else for(var r in e)t.addSchema(e[r],r)}function jSn(t){for(var e in t._opts.formats){var r=t._opts.formats[e];t.addFormat(e,r)}}function zSn(t){for(var e in t._opts.keywords){var r=t._opts.keywords[e];t.addKeyword(e,r)}}function qBt(t,e){if(t._schemas[e]||t._refs[e])throw new Error('schema with key or id "'+e+'" already exists')}function YSn(t){for(var e=LBt.copy(t._opts),r=0;r<MBt.length;r++)delete e[MBt[r]];return e}function JSn(t){var e=t._opts.logger;if(e===!1)t.logger={log:kFe,warn:kFe,error:kFe};else{if(e===void 0&&(e=console),!(typeof e=="object"&&e.log&&e.warn&&e.error))throw new Error("logger must implement log, warn and error methods");t.logger=e}}function kFe(){}});var VBt,x3,Aq=Ie(()=>{HDt();Tw();VBt=Ye(GBt(),1),x3=class extends Zhe{constructor(e,r){var n;super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=(n=r?.capabilities)!==null&&n!==void 0?n:{},this._ajv=new VBt.default}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=qDt(this._capabilities,e)}assertCapability(e,r){var n;if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n[e]))throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:mq,capabilities:this._capabilities,clientInfo:this._clientInfo}},rFe,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!_Dt.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"})}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,n,i,o,s;switch(e){case"logging/setLevel":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((i=this._serverCapabilities)===null||i===void 0)&&i.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((s=this._serverCapabilities)===null||s===void 0)&&s.completions))throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){var r;switch(e){case"notifications/roots/list_changed":if(!(!((r=this._capabilities.roots)===null||r===void 0)&&r.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},oN,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},fFe,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},oN,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},KX,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},JX,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},iFe,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},oFe,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},sFe,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},oN,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},oN,r)}async callTool(e,r=Khe,n){let i=await this.request({method:"tools/call",params:e},r,n),o=this.getToolOutputValidator(e.name);if(o){if(!i.structuredContent&&!i.isError)throw new P6(F6.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(i.structuredContent)try{if(!o(i.structuredContent))throw new P6(F6.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(o.errors)}`)}catch(s){throw s instanceof P6?s:new P6(F6.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}return i}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(let r of e)if(r.outputSchema)try{let n=this._ajv.compile(r.outputSchema);this._cachedToolOutputValidators.set(r.name,n)}catch{}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let n=await this.request({method:"tools/list",params:e},uFe,r);return this.cacheToolOutputSchemas(n.tools),n}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}});var YBt=N((uxo,zBt)=>{zBt.exports=jBt;jBt.sync=XSn;var $Bt=Be("fs");function KSn(t,e){var r=e.pathExt!==void 0?e.pathExt:process.env.PATHEXT;if(!r||(r=r.split(";"),r.indexOf("")!==-1))return!0;for(var n=0;n<r.length;n++){var i=r[n].toLowerCase();if(i&&t.substr(-i.length).toLowerCase()===i)return!0}return!1}function WBt(t,e,r){return!t.isSymbolicLink()&&!t.isFile()?!1:KSn(e,r)}function jBt(t,e,r){$Bt.stat(t,function(n,i){r(n,n?!1:WBt(i,t,e))})}function XSn(t,e){return WBt($Bt.statSync(t),t,e)}});var eNt=N((fxo,ZBt)=>{ZBt.exports=KBt;KBt.sync=ZSn;var JBt=Be("fs");function KBt(t,e,r){JBt.stat(t,function(n,i){r(n,n?!1:XBt(i,e))})}function ZSn(t,e){return XBt(JBt.statSync(t),e)}function XBt(t,e){return t.isFile()&&exn(t,e)}function exn(t,e){var r=t.mode,n=t.uid,i=t.gid,o=e.uid!==void 0?e.uid:process.getuid&&process.getuid(),s=e.gid!==void 0?e.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8),u=parseInt("001",8),f=a|c,d=r&u||r&c&&i===s||r&a&&n===o||r&f&&o===0;return d}});var rNt=N((pxo,tNt)=>{var dxo=Be("fs"),A0e;process.platform==="win32"||global.TESTING_WINDOWS?A0e=YBt():A0e=eNt();tNt.exports=FFe;FFe.sync=txn;function FFe(t,e,r){if(typeof e=="function"&&(r=e,e={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(n,i){FFe(t,e||{},function(o,s){o?i(o):n(s)})})}A0e(t,e||{},function(n,i){n&&(n.code==="EACCES"||e&&e.ignoreErrors)&&(n=null,i=!1),r(n,i)})}function txn(t,e){try{return A0e.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var cNt=N((hxo,lNt)=>{var yq=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",nNt=Be("path"),rxn=yq?";":":",iNt=rNt(),oNt=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),sNt=(t,e)=>{let r=e.colon||rxn,n=t.match(/\//)||yq&&t.match(/\\/)?[""]:[...yq?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],i=yq?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",o=yq?i.split(r):[""];return yq&&t.indexOf(".")!==-1&&o[0]!==""&&o.unshift(""),{pathEnv:n,pathExt:o,pathExtExe:i}},aNt=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});let{pathEnv:n,pathExt:i,pathExtExe:o}=sNt(t,e),s=[],a=u=>new Promise((f,d)=>{if(u===n.length)return e.all&&s.length?f(s):d(oNt(t));let p=n[u],h=/^".*"$/.test(p)?p.slice(1,-1):p,g=nNt.join(h,t),A=!h&&/^\.[\\\/]/.test(t)?t.slice(0,2)+g:g;f(c(A,u,0))}),c=(u,f,d)=>new Promise((p,h)=>{if(d===i.length)return p(a(f+1));let g=i[d];iNt(u+g,{pathExt:o},(A,y)=>{if(!A&&y)if(e.all)s.push(u+g);else return p(u+g);return p(c(u,f,d+1))})});return r?a(0).then(u=>r(null,u),r):a(0)},nxn=(t,e)=>{e=e||{};let{pathEnv:r,pathExt:n,pathExtExe:i}=sNt(t,e),o=[];for(let s=0;s<r.length;s++){let a=r[s],c=/^".*"$/.test(a)?a.slice(1,-1):a,u=nNt.join(c,t),f=!c&&/^\.[\\\/]/.test(t)?t.slice(0,2)+u:u;for(let d=0;d<n.length;d++){let p=f+n[d];try{if(iNt.sync(p,{pathExt:i}))if(e.all)o.push(p);else return p}catch{}}}if(e.all&&o.length)return o;if(e.nothrow)return null;throw oNt(t)};lNt.exports=aNt;aNt.sync=nxn});var fNt=N((mxo,PFe)=>{"use strict";var uNt=(t={})=>{let e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};PFe.exports=uNt;PFe.exports.default=uNt});var mNt=N((gxo,hNt)=>{"use strict";var dNt=Be("path"),ixn=cNt(),oxn=fNt();function pNt(t,e){let r=t.options.env||process.env,n=process.cwd(),i=t.options.cwd!=null,o=i&&process.chdir!==void 0&&!process.chdir.disabled;if(o)try{process.chdir(t.options.cwd)}catch{}let s;try{s=ixn.sync(t.command,{path:r[oxn({env:r})],pathExt:e?dNt.delimiter:void 0})}catch{}finally{o&&process.chdir(n)}return s&&(s=dNt.resolve(i?t.options.cwd:"",s)),s}function sxn(t){return pNt(t)||pNt(t,!0)}hNt.exports=sxn});var gNt=N((Axo,UFe)=>{"use strict";var LFe=/([()\][%!^"`<>&|;, *?])/g;function axn(t){return t=t.replace(LFe,"^$1"),t}function lxn(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(LFe,"^$1"),e&&(t=t.replace(LFe,"^$1")),t}UFe.exports.command=axn;UFe.exports.argument=lxn});var yNt=N((yxo,ANt)=>{"use strict";ANt.exports=/^#!(.*)/});var vNt=N((Exo,ENt)=>{"use strict";var cxn=yNt();ENt.exports=(t="")=>{let e=t.match(cxn);if(!e)return null;let[r,n]=e[0].replace(/#! ?/,"").split(" "),i=r.split("/").pop();return i==="env"?n:n?`${i} ${n}`:i}});var bNt=N((vxo,CNt)=>{"use strict";var QFe=Be("fs"),uxn=vNt();function fxn(t){let r=Buffer.alloc(150),n;try{n=QFe.openSync(t,"r"),QFe.readSync(n,r,0,150,0),QFe.closeSync(n)}catch{}return uxn(r.toString())}CNt.exports=fxn});var wNt=N((Cxo,xNt)=>{"use strict";var dxn=Be("path"),_Nt=mNt(),SNt=gNt(),pxn=bNt(),hxn=process.platform==="win32",mxn=/\.(?:com|exe)$/i,gxn=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Axn(t){t.file=_Nt(t);let e=t.file&&pxn(t.file);return e?(t.args.unshift(t.file),t.command=e,_Nt(t)):t.file}function yxn(t){if(!hxn)return t;let e=Axn(t),r=!mxn.test(e);if(t.options.forceShell||r){let n=gxn.test(e);t.command=dxn.normalize(t.command),t.command=SNt.command(t.command),t.args=t.args.map(o=>SNt.argument(o,n));let i=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${i}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}function Exn(t,e,r){e&&!Array.isArray(e)&&(r=e,e=null),e=e?e.slice(0):[],r=Object.assign({},r);let n={command:t,args:e,options:r,file:void 0,original:{command:t,args:e}};return r.shell?n:yxn(n)}xNt.exports=Exn});var DNt=N((bxo,INt)=>{"use strict";var qFe=process.platform==="win32";function HFe(t,e){return Object.assign(new Error(`${e} ${t.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${t.command}`,path:t.command,spawnargs:t.args})}function vxn(t,e){if(!qFe)return;let r=t.emit;t.emit=function(n,i){if(n==="exit"){let o=TNt(i,e);if(o)return r.call(t,"error",o)}return r.apply(t,arguments)}}function TNt(t,e){return qFe&&t===1&&!e.file?HFe(e.original,"spawn"):null}function Cxn(t,e){return qFe&&t===1&&!e.file?HFe(e.original,"spawnSync"):null}INt.exports={hookChildProcess:vxn,verifyENOENT:TNt,verifyENOENTSync:Cxn,notFoundError:HFe}});var NNt=N((_xo,Eq)=>{"use strict";var RNt=Be("child_process"),GFe=wNt(),VFe=DNt();function BNt(t,e,r){let n=GFe(t,e,r),i=RNt.spawn(n.command,n.args,n.options);return VFe.hookChildProcess(i,n),i}function bxn(t,e,r){let n=GFe(t,e,r),i=RNt.spawnSync(n.command,n.args,n.options);return i.error=i.error||VFe.verifyENOENTSync(i.status,n),i}Eq.exports=BNt;Eq.exports.spawn=BNt;Eq.exports.sync=bxn;Eq.exports._parse=GFe;Eq.exports._enoent=VFe});function _xn(t){return ww.parse(JSON.parse(t))}function ONt(t){return JSON.stringify(t)+`
|
|
415
415
|
`}var y0e,MNt=Ie(()=>{Tw();y0e=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
416
416
|
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),_xn(r)}clear(){this._buffer=void 0}}});import E0e from"node:process";import{PassThrough as Sxn}from"node:stream";function wxn(){let t={};for(let e of xxn){let r=E0e.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}function Txn(){return"type"in E0e}var kNt,xxn,vq,$Fe=Ie(()=>{kNt=Ye(NNt(),1);MNt();xxn=E0e.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];vq=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new y0e,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new Sxn)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{var n,i,o,s,a;this._process=(0,kNt.default)(this._serverParams.command,(n=this._serverParams.args)!==null&&n!==void 0?n:[],{env:{...wxn(),...this._serverParams.env},stdio:["pipe","pipe",(i=this._serverParams.stderr)!==null&&i!==void 0?i:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:E0e.platform==="win32"&&Txn(),cwd:this._serverParams.cwd}),this._process.on("error",c=>{var u,f;if(c.name==="AbortError"){(u=this.onclose)===null||u===void 0||u.call(this);return}r(c),(f=this.onerror)===null||f===void 0||f.call(this,c)}),this._process.on("spawn",()=>{e()}),this._process.on("close",c=>{var u;this._process=void 0,(u=this.onclose)===null||u===void 0||u.call(this)}),(o=this._process.stdin)===null||o===void 0||o.on("error",c=>{var u;(u=this.onerror)===null||u===void 0||u.call(this,c)}),(s=this._process.stdout)===null||s===void 0||s.on("data",c=>{this._readBuffer.append(c),this.processReadBuffer()}),(a=this._process.stdout)===null||a===void 0||a.on("error",c=>{var u;(u=this.onerror)===null||u===void 0||u.call(this,c)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,r;return this._stderrStream?this._stderrStream:(r=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&r!==void 0?r:null}get pid(){var e,r;return(r=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&r!==void 0?r:null}processReadBuffer(){for(var e,r;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(r=this.onerror)===null||r===void 0||r.call(this,n)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(r=>{var n;if(!(!((n=this._process)===null||n===void 0)&&n.stdin))throw new Error("Not connected");let i=ONt(e);this._process.stdin.write(i)?r():this._process.stdin.once("drain",r)})}}});function WFe(t){}function C0e(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:e=WFe,onError:r=WFe,onRetry:n=WFe,onComment:i}=t,o="",s=!0,a,c="",u="";function f(A){let y=s?A.replace(/^\xEF\xBB\xBF/,""):A,[v,S]=Ixn(`${o}${y}`);for(let x of v)d(x);o=S,s=!1}function d(A){if(A===""){h();return}if(A.startsWith(":")){i&&i(A.slice(A.startsWith(": ")?2:1));return}let y=A.indexOf(":");if(y!==-1){let v=A.slice(0,y),S=A[y+1]===" "?2:1,x=A.slice(y+S);p(v,x,A);return}p(A,"",A)}function p(A,y,v){switch(A){case"event":u=y;break;case"data":c=`${c}${y}
|
|
417
417
|
`;break;case"id":a=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?n(parseInt(y,10)):r(new v0e(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:v}));break;default:r(new v0e(`Unknown field "${A.length>20?`${A.slice(0,20)}\u2026`:A}"`,{type:"unknown-field",field:A,value:y,line:v}));break}}function h(){c.length>0&&e({id:a,event:u||void 0,data:c.endsWith(`
|
|
418
418
|
`)?c.slice(0,-1):c}),a=void 0,c="",u=""}function g(A={}){o&&A.consume&&d(o),s=!0,a=void 0,c="",u="",o=""}return{feed:f,reset:g}}function Ixn(t){let e=[],r="",n=0;for(;n<t.length;){let i=t.indexOf("\r",n),o=t.indexOf(`
|
|
419
419
|
`,n),s=-1;if(i!==-1&&o!==-1?s=Math.min(i,o):i!==-1?i===t.length-1?s=-1:s=i:o!==-1&&(s=o),s===-1){r=t.slice(n);break}else{let a=t.slice(n,s);e.push(a),n=s+1,t[n-1]==="\r"&&t[n]===`
|
|
420
|
-
`&&n++}}return[e,r]}var v0e,jFe=Ie(()=>{v0e=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}});function Dxn(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function zFe(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(zFe).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${zFe(t.cause)}`:t.message:`${t}`}function FNt(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}function Rxn(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var _0e,LNt,rPe,js,Zp,Xu,T7,$1,lN,Cq,b0e,S0e,tZ,Sq,rZ,Bw,bq,xq,_q,ZX,a5,YFe,JFe,KFe,PNt,XFe,ZFe,eZ,ePe,tPe,cN,UNt=Ie(()=>{jFe();_0e=class extends Event{constructor(e,r){var n,i;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(i=r?.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(FNt(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(FNt(this),r)}};LNt=t=>{throw TypeError(t)},rPe=(t,e,r)=>e.has(t)||LNt("Cannot "+r),js=(t,e,r)=>(rPe(t,e,"read from private field"),r?r.call(t):e.get(t)),Zp=(t,e,r)=>e.has(t)?LNt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Xu=(t,e,r,n)=>(rPe(t,e,"write to private field"),e.set(t,r),r),T7=(t,e,r)=>(rPe(t,e,"access private method"),r),cN=class extends EventTarget{constructor(e,r){var n,i;super(),Zp(this,a5),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Zp(this,$1),Zp(this,lN),Zp(this,Cq),Zp(this,b0e),Zp(this,S0e),Zp(this,tZ),Zp(this,Sq),Zp(this,rZ,null),Zp(this,Bw),Zp(this,bq),Zp(this,xq,null),Zp(this,_q,null),Zp(this,ZX,null),Zp(this,JFe,async o=>{var s;js(this,bq).reset();let{body:a,redirected:c,status:u,headers:f}=o;if(u===204){T7(this,a5,eZ).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?Xu(this,Cq,new URL(o.url)):Xu(this,Cq,void 0),u!==200){T7(this,a5,eZ).call(this,`Non-200 status code (${u})`,u);return}if(!(f.get("content-type")||"").startsWith("text/event-stream")){T7(this,a5,eZ).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(js(this,$1)===this.CLOSED)return;Xu(this,$1,this.OPEN);let d=new Event("open");if((s=js(this,ZX))==null||s.call(this,d),this.dispatchEvent(d),typeof a!="object"||!a||!("getReader"in a)){T7(this,a5,eZ).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let p=new TextDecoder,h=a.getReader(),g=!0;do{let{done:A,value:y}=await h.read();y&&js(this,bq).feed(p.decode(y,{stream:!A})),A&&(g=!1,js(this,bq).reset(),T7(this,a5,ePe).call(this))}while(g)}),Zp(this,KFe,o=>{Xu(this,Bw,void 0),!(o.name==="AbortError"||o.type==="aborted")&&T7(this,a5,ePe).call(this,zFe(o))}),Zp(this,XFe,o=>{typeof o.id=="string"&&Xu(this,rZ,o.id);let s=new MessageEvent(o.event||"message",{data:o.data,origin:js(this,Cq)?js(this,Cq).origin:js(this,lN).origin,lastEventId:o.id||""});js(this,_q)&&(!o.event||o.event==="message")&&js(this,_q).call(this,s),this.dispatchEvent(s)}),Zp(this,ZFe,o=>{Xu(this,tZ,o)}),Zp(this,tPe,()=>{Xu(this,Sq,void 0),js(this,$1)===this.CONNECTING&&T7(this,a5,YFe).call(this)});try{if(e instanceof URL)Xu(this,lN,e);else if(typeof e=="string")Xu(this,lN,new URL(e,Rxn()));else throw new Error("Invalid URL")}catch{throw Dxn("An invalid or illegal string was specified")}Xu(this,bq,C0e({onEvent:js(this,XFe),onRetry:js(this,ZFe)})),Xu(this,$1,this.CONNECTING),Xu(this,tZ,3e3),Xu(this,S0e,(n=r?.fetch)!=null?n:globalThis.fetch),Xu(this,b0e,(i=r?.withCredentials)!=null?i:!1),T7(this,a5,YFe).call(this)}get readyState(){return js(this,$1)}get url(){return js(this,lN).href}get withCredentials(){return js(this,b0e)}get onerror(){return js(this,xq)}set onerror(e){Xu(this,xq,e)}get onmessage(){return js(this,_q)}set onmessage(e){Xu(this,_q,e)}get onopen(){return js(this,ZX)}set onopen(e){Xu(this,ZX,e)}addEventListener(e,r,n){let i=r;super.addEventListener(e,i,n)}removeEventListener(e,r,n){let i=r;super.removeEventListener(e,i,n)}close(){js(this,Sq)&&clearTimeout(js(this,Sq)),js(this,$1)!==this.CLOSED&&(js(this,Bw)&&js(this,Bw).abort(),Xu(this,$1,this.CLOSED),Xu(this,Bw,void 0))}};$1=new WeakMap,lN=new WeakMap,Cq=new WeakMap,b0e=new WeakMap,S0e=new WeakMap,tZ=new WeakMap,Sq=new WeakMap,rZ=new WeakMap,Bw=new WeakMap,bq=new WeakMap,xq=new WeakMap,_q=new WeakMap,ZX=new WeakMap,a5=new WeakSet,YFe=function(){Xu(this,$1,this.CONNECTING),Xu(this,Bw,new AbortController),js(this,S0e)(js(this,lN),T7(this,a5,PNt).call(this)).then(js(this,JFe)).catch(js(this,KFe))},JFe=new WeakMap,KFe=new WeakMap,PNt=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...js(this,rZ)?{"Last-Event-ID":js(this,rZ)}:void 0},cache:"no-store",signal:(t=js(this,Bw))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},XFe=new WeakMap,ZFe=new WeakMap,eZ=function(t,e){var r;js(this,$1)!==this.CLOSED&&Xu(this,$1,this.CLOSED);let n=new _0e("error",{code:e,message:t});(r=js(this,xq))==null||r.call(this,n),this.dispatchEvent(n)},ePe=function(t,e){var r;if(js(this,$1)===this.CLOSED)return;Xu(this,$1,this.CONNECTING);let n=new _0e("error",{code:e,message:t});(r=js(this,xq))==null||r.call(this,n),this.dispatchEvent(n),Xu(this,Sq,setTimeout(js(this,tPe),js(this,tZ)))},tPe=new WeakMap,cN.CONNECTING=0,cN.OPEN=1,cN.CLOSED=2});async function Bxn(t){return(await nPe).getRandomValues(new Uint8Array(t))}async function Nxn(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r="",n=await Bxn(t);for(let i=0;i<t;i++){let o=n[i]%e.length;r+=e[o]}return r}async function Oxn(t){return await Nxn(t)}async function Mxn(t){let e=await(await nPe).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function iPe(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await Oxn(t),r=await Mxn(e);return{code_verifier:e,code_challenge:r}}var nPe,QNt=Ie(()=>{nPe=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto)});var Kh,qNt,oPe,kxn,HNt,sPe,GNt,Fxn,Pxn,VNt,kxo,Fxo,aPe=Ie(()=>{xw();Kh=fe.string().url().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:fe.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),fe.NEVER}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),qNt=fe.object({resource:fe.string().url(),authorization_servers:fe.array(Kh).optional(),jwks_uri:fe.string().url().optional(),scopes_supported:fe.array(fe.string()).optional(),bearer_methods_supported:fe.array(fe.string()).optional(),resource_signing_alg_values_supported:fe.array(fe.string()).optional(),resource_name:fe.string().optional(),resource_documentation:fe.string().optional(),resource_policy_uri:fe.string().url().optional(),resource_tos_uri:fe.string().url().optional(),tls_client_certificate_bound_access_tokens:fe.boolean().optional(),authorization_details_types_supported:fe.array(fe.string()).optional(),dpop_signing_alg_values_supported:fe.array(fe.string()).optional(),dpop_bound_access_tokens_required:fe.boolean().optional()}).passthrough(),oPe=fe.object({issuer:fe.string(),authorization_endpoint:Kh,token_endpoint:Kh,registration_endpoint:Kh.optional(),scopes_supported:fe.array(fe.string()).optional(),response_types_supported:fe.array(fe.string()),response_modes_supported:fe.array(fe.string()).optional(),grant_types_supported:fe.array(fe.string()).optional(),token_endpoint_auth_methods_supported:fe.array(fe.string()).optional(),token_endpoint_auth_signing_alg_values_supported:fe.array(fe.string()).optional(),service_documentation:Kh.optional(),revocation_endpoint:Kh.optional(),revocation_endpoint_auth_methods_supported:fe.array(fe.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:fe.array(fe.string()).optional(),introspection_endpoint:fe.string().optional(),introspection_endpoint_auth_methods_supported:fe.array(fe.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:fe.array(fe.string()).optional(),code_challenge_methods_supported:fe.array(fe.string()).optional()}).passthrough(),kxn=fe.object({issuer:fe.string(),authorization_endpoint:Kh,token_endpoint:Kh,userinfo_endpoint:Kh.optional(),jwks_uri:Kh,registration_endpoint:Kh.optional(),scopes_supported:fe.array(fe.string()).optional(),response_types_supported:fe.array(fe.string()),response_modes_supported:fe.array(fe.string()).optional(),grant_types_supported:fe.array(fe.string()).optional(),acr_values_supported:fe.array(fe.string()).optional(),subject_types_supported:fe.array(fe.string()),id_token_signing_alg_values_supported:fe.array(fe.string()),id_token_encryption_alg_values_supported:fe.array(fe.string()).optional(),id_token_encryption_enc_values_supported:fe.array(fe.string()).optional(),userinfo_signing_alg_values_supported:fe.array(fe.string()).optional(),userinfo_encryption_alg_values_supported:fe.array(fe.string()).optional(),userinfo_encryption_enc_values_supported:fe.array(fe.string()).optional(),request_object_signing_alg_values_supported:fe.array(fe.string()).optional(),request_object_encryption_alg_values_supported:fe.array(fe.string()).optional(),request_object_encryption_enc_values_supported:fe.array(fe.string()).optional(),token_endpoint_auth_methods_supported:fe.array(fe.string()).optional(),token_endpoint_auth_signing_alg_values_supported:fe.array(fe.string()).optional(),display_values_supported:fe.array(fe.string()).optional(),claim_types_supported:fe.array(fe.string()).optional(),claims_supported:fe.array(fe.string()).optional(),service_documentation:fe.string().optional(),claims_locales_supported:fe.array(fe.string()).optional(),ui_locales_supported:fe.array(fe.string()).optional(),claims_parameter_supported:fe.boolean().optional(),request_parameter_supported:fe.boolean().optional(),request_uri_parameter_supported:fe.boolean().optional(),require_request_uri_registration:fe.boolean().optional(),op_policy_uri:Kh.optional(),op_tos_uri:Kh.optional()}).passthrough(),HNt=kxn.merge(oPe.pick({code_challenge_methods_supported:!0})),sPe=fe.object({access_token:fe.string(),id_token:fe.string().optional(),token_type:fe.string(),expires_in:fe.number().optional(),scope:fe.string().optional(),refresh_token:fe.string().optional()}).strip(),GNt=fe.object({error:fe.string(),error_description:fe.string().optional(),error_uri:fe.string().optional()}),Fxn=fe.object({redirect_uris:fe.array(Kh),token_endpoint_auth_method:fe.string().optional(),grant_types:fe.array(fe.string()).optional(),response_types:fe.array(fe.string()).optional(),client_name:fe.string().optional(),client_uri:Kh.optional(),logo_uri:Kh.optional(),scope:fe.string().optional(),contacts:fe.array(fe.string()).optional(),tos_uri:Kh.optional(),policy_uri:fe.string().optional(),jwks_uri:Kh.optional(),jwks:fe.any().optional(),software_id:fe.string().optional(),software_version:fe.string().optional(),software_statement:fe.string().optional()}).strip(),Pxn=fe.object({client_id:fe.string(),client_secret:fe.string().optional(),client_id_issued_at:fe.number().optional(),client_secret_expires_at:fe.number().optional()}).strip(),VNt=Fxn.merge(Pxn),kxo=fe.object({error:fe.string(),error_description:fe.string().optional()}).strip(),Fxo=fe.object({token:fe.string(),token_type_hint:fe.string().optional()}).strip()});function $Nt(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function WNt({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return i.startsWith(o)}var jNt=Ie(()=>{});var Ep,nZ,uN,fN,dN,iZ,oZ,sZ,I7,aZ,lZ,cZ,uZ,fZ,dZ,pZ,hZ,zNt,YNt=Ie(()=>{Ep=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},nZ=class extends Ep{};nZ.errorCode="invalid_request";uN=class extends Ep{};uN.errorCode="invalid_client";fN=class extends Ep{};fN.errorCode="invalid_grant";dN=class extends Ep{};dN.errorCode="unauthorized_client";iZ=class extends Ep{};iZ.errorCode="unsupported_grant_type";oZ=class extends Ep{};oZ.errorCode="invalid_scope";sZ=class extends Ep{};sZ.errorCode="access_denied";I7=class extends Ep{};I7.errorCode="server_error";aZ=class extends Ep{};aZ.errorCode="temporarily_unavailable";lZ=class extends Ep{};lZ.errorCode="unsupported_response_type";cZ=class extends Ep{};cZ.errorCode="unsupported_token_type";uZ=class extends Ep{};uZ.errorCode="invalid_token";fZ=class extends Ep{};fZ.errorCode="method_not_allowed";dZ=class extends Ep{};dZ.errorCode="too_many_requests";pZ=class extends Ep{};pZ.errorCode="invalid_client_metadata";hZ=class extends Ep{};hZ.errorCode="insufficient_scope";zNt={[nZ.errorCode]:nZ,[uN.errorCode]:uN,[fN.errorCode]:fN,[dN.errorCode]:dN,[iZ.errorCode]:iZ,[oZ.errorCode]:oZ,[sZ.errorCode]:sZ,[I7.errorCode]:I7,[aZ.errorCode]:aZ,[lZ.errorCode]:lZ,[cZ.errorCode]:cZ,[uZ.errorCode]:uZ,[fZ.errorCode]:fZ,[dZ.errorCode]:dZ,[pZ.errorCode]:pZ,[hZ.errorCode]:hZ}});function KNt(t,e){let r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function XNt(t,e,r,n){let{client_id:i,client_secret:o}=e;switch(t){case"client_secret_basic":Lxn(i,o,r);return;case"client_secret_post":Uxn(i,o,n);return;case"none":Qxn(i,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function Lxn(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function Uxn(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function Qxn(t,e){e.set("client_id",t)}async function cPe(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=GNt.parse(JSON.parse(r)),{error:i,error_description:o,error_uri:s}=n,a=zNt[i]||I7;return new a(o||"",s)}catch(n){let i=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new I7(i)}}async function Nw(t,e){var r,n;try{return await lPe(t,e)}catch(i){if(i instanceof uN||i instanceof dN)return await((r=t.invalidateCredentials)===null||r===void 0?void 0:r.call(t,"all")),await lPe(t,e);if(i instanceof fN)return await((n=t.invalidateCredentials)===null||n===void 0?void 0:n.call(t,"tokens")),await lPe(t,e);throw i}}async function lPe(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:i,fetchFn:o}){let s,a;try{s=await Hxn(e,{resourceMetadataUrl:i},o),s.authorization_servers&&s.authorization_servers.length>0&&(a=s.authorization_servers[0])}catch{}a||(a=e);let c=await qxn(e,t,s),u=await jxn(a,{fetchFn:o}),f=await Promise.resolve(t.clientInformation());if(!f){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let A=await Yxn(a,{metadata:u,clientMetadata:t.clientMetadata,fetchFn:o});await t.saveClientInformation(A),f=A}if(r!==void 0){let A=await t.codeVerifier(),y=await fPe(a,{metadata:u,clientInformation:f,authorizationCode:r,codeVerifier:A,redirectUri:t.redirectUrl,resource:c,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(y),"AUTHORIZED"}let d=await t.tokens();if(d?.refresh_token)try{let A=await dPe(a,{metadata:u,clientInformation:f,refreshToken:d.refresh_token,resource:c,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(A),"AUTHORIZED"}catch(A){if(!(!(A instanceof Ep)||A instanceof I7))throw A}let p=t.state?await t.state():void 0,{authorizationUrl:h,codeVerifier:g}=await zxn(a,{metadata:u,clientInformation:f,state:p,redirectUrl:t.redirectUrl,scope:n||t.clientMetadata.scope,resource:c});return await t.saveCodeVerifier(g),await t.redirectToAuthorization(h),"REDIRECT"}async function qxn(t,e,r){let n=$Nt(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!WNt({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function mZ(t){let e=t.headers.get("WWW-Authenticate");if(!e)return;let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return;let o=/resource_metadata="([^"]*)"/.exec(e);if(o)try{return new URL(o[1])}catch{return}}async function Hxn(t,e,r=fetch){let n=await $xn(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return qNt.parse(await n.json())}async function uPe(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?uPe(t,void 0,r):void 0;throw n}}function Gxn(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function JNt(t,e,r=fetch){return await uPe(t,{"MCP-Protocol-Version":e},r)}function Vxn(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function $xn(t,e,r,n){var i,o;let s=new URL(t),a=(i=n?.protocolVersion)!==null&&i!==void 0?i:mq,c;if(n?.metadataUrl)c=new URL(n.metadataUrl);else{let f=Gxn(e,s.pathname);c=new URL(f,(o=n?.metadataServerUrl)!==null&&o!==void 0?o:s),c.search=s.search}let u=await JNt(c,a,r);if(!n?.metadataUrl&&Vxn(u,s.pathname)){let f=new URL(`/.well-known/${e}`,s);u=await JNt(f,a,r)}return u}function Wxn(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let i=e.pathname;return i.endsWith("/")&&(i=i.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${i}`,e.origin),type:"oidc"}),n.push({url:new URL(`${i}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function jxn(t,{fetchFn:e=fetch,protocolVersion:r=mq}={}){var n;let i={"MCP-Protocol-Version":r},o=Wxn(t);for(let{url:s,type:a}of o){let c=await uPe(s,i,e);if(c){if(!c.ok){if(c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}if(a==="oauth")return oPe.parse(await c.json());{let u=HNt.parse(await c.json());if(!(!((n=u.code_challenge_methods_supported)===null||n===void 0)&&n.includes("S256")))throw new Error(`Incompatible OIDC provider at ${s}: does not support S256 code challenge method required by MCP specification`);return u}}}}async function zxn(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:i,state:o,resource:s}){let a="code",c="S256",u;if(e){if(u=new URL(e.authorization_endpoint),!e.response_types_supported.includes(a))throw new Error(`Incompatible auth server: does not support response type ${a}`);if(!e.code_challenge_methods_supported||!e.code_challenge_methods_supported.includes(c))throw new Error(`Incompatible auth server: does not support code challenge method ${c}`)}else u=new URL("/authorize",t);let f=await iPe(),d=f.code_verifier,p=f.code_challenge;return u.searchParams.set("response_type",a),u.searchParams.set("client_id",r.client_id),u.searchParams.set("code_challenge",p),u.searchParams.set("code_challenge_method",c),u.searchParams.set("redirect_uri",String(n)),o&&u.searchParams.set("state",o),i&&u.searchParams.set("scope",i),i?.includes("offline_access")&&u.searchParams.append("prompt","consent"),s&&u.searchParams.set("resource",s.href),{authorizationUrl:u,codeVerifier:d}}async function fPe(t,{metadata:e,clientInformation:r,authorizationCode:n,codeVerifier:i,redirectUri:o,resource:s,addClientAuthentication:a,fetchFn:c}){var u;let f="authorization_code",d=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e?.grant_types_supported&&!e.grant_types_supported.includes(f))throw new Error(`Incompatible auth server: does not support grant type ${f}`);let p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),h=new URLSearchParams({grant_type:f,code:n,code_verifier:i,redirect_uri:String(o)});if(a)a(p,h,t,e);else{let A=(u=e?.token_endpoint_auth_methods_supported)!==null&&u!==void 0?u:[],y=KNt(r,A);XNt(y,r,p,h)}s&&h.set("resource",s.href);let g=await(c??fetch)(d,{method:"POST",headers:p,body:h});if(!g.ok)throw await cPe(g);return sPe.parse(await g.json())}async function dPe(t,{metadata:e,clientInformation:r,refreshToken:n,resource:i,addClientAuthentication:o,fetchFn:s}){var a;let c="refresh_token",u;if(e){if(u=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`)}else u=new URL("/token",t);let f=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),d=new URLSearchParams({grant_type:c,refresh_token:n});if(o)o(f,d,t,e);else{let h=(a=e?.token_endpoint_auth_methods_supported)!==null&&a!==void 0?a:[],g=KNt(r,h);XNt(g,r,f,d)}i&&d.set("resource",i.href);let p=await(s??fetch)(u,{method:"POST",headers:f,body:d});if(!p.ok)throw await cPe(p);return sPe.parse({refresh_token:n,...await p.json()})}async function Yxn(t,{metadata:e,clientMetadata:r,fetchFn:n}){let i;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(e.registration_endpoint)}else i=new URL("/register",t);let o=await(n??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await cPe(o);return VNt.parse(await o.json())}var W1,x0e=Ie(()=>{QNt();Tw();aPe();aPe();jNt();YNt();W1=class extends Error{constructor(e){super(e??"Unauthorized")}}});var pPe,wq,ZNt=Ie(()=>{UNt();Tw();x0e();pPe=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},wq=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch}async _authThenStart(){var e;if(!this._authProvider)throw new W1("No auth provider");let r;try{r=await Nw(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new W1;return await this._startOrAuth()}async _commonHeaders(){var e;let r={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(r.Authorization=`Bearer ${n.access_token}`)}return this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion),new Headers({...r,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}_startOrAuth(){var e,r,n;let i=(n=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((o,s)=>{this._eventSource=new cN(this._url.href,{...this._eventSourceInit,fetch:async(a,c)=>{let u=await this._commonHeaders();u.set("Accept","text/event-stream");let f=await i(a,{...c,headers:u});return f.status===401&&f.headers.has("www-authenticate")&&(this._resourceMetadataUrl=mZ(f)),f}}),this._abortController=new AbortController,this._eventSource.onerror=a=>{var c;if(a.code===401&&this._authProvider){this._authThenStart().then(o,s);return}let u=new pPe(a.code,a.message,a);s(u),(c=this.onerror)===null||c===void 0||c.call(this,u)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",a=>{var c;let u=a;try{if(this._endpoint=new URL(u.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(f){s(f),(c=this.onerror)===null||c===void 0||c.call(this,f),this.close();return}o()}),this._eventSource.onmessage=a=>{var c,u;let f=a,d;try{d=ww.parse(JSON.parse(f.data))}catch(p){(c=this.onerror)===null||c===void 0||c.call(this,p);return}(u=this.onmessage)===null||u===void 0||u.call(this,d)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new W1("No auth provider");if(await Nw(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new W1("Failed to authorize")}async close(){var e,r,n;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var r,n,i;if(!this._endpoint)throw new Error("Not connected");try{let o=await this._commonHeaders();o.set("content-type","application/json");let s={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},a=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,s);if(!a.ok){if(a.status===401&&this._authProvider){if(this._resourceMetadataUrl=mZ(a),await Nw(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new W1;return this.send(e)}let c=await a.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${a.status}): ${c}`)}}catch(o){throw(i=this.onerror)===null||i===void 0||i.call(this,o),o}}setProtocolVersion(e){this._protocolVersion=e}}});var w0e,eOt=Ie(()=>{jFe();w0e=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=C0e({onEvent:s=>{o.enqueue(s)},onError(s){e==="terminate"?o.error(s):typeof e=="function"&&e(s)},onRetry:r,onComment:n})},transform(o){i.feed(o)}})}}});var Jxn,gZ,Ow,hPe=Ie(()=>{Tw();x0e();eOt();Jxn={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},gZ=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Ow=class{constructor(e,r){var n;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:Jxn}async _authThenStart(){var e;if(!this._authProvider)throw new W1("No auth provider");let r;try{r=await Nw(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new W1;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let r={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(r.Authorization=`Bearer ${i.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}async _startOrAuthSse(e){var r,n,i;let{resumptionToken:o}=e;try{let s=await this._commonHeaders();s.set("Accept","text/event-stream"),o&&s.set("last-event-id",o);let a=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:s,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!a.ok){if(a.status===401&&this._authProvider)return await this._authThenStart();if(a.status===405)return;throw new gZ(a.status,`Failed to open SSE stream: ${a.statusText}`)}this._handleSseStream(a.body,e,!0)}catch(s){throw(i=this.onerror)===null||i===void 0||i.call(this,s),s}}_getNextReconnectionDelay(e){let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),i)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,r=0){var n;let i=this._reconnectionOptions.maxRetries;if(i>0&&r>=i){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${i}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{var a;(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:o}=r,s;(async()=>{var c,u,f,d;try{let p=e.pipeThrough(new TextDecoderStream).pipeThrough(new w0e).getReader();for(;;){let{value:h,done:g}=await p.read();if(g)break;if(h.id&&(s=h.id,i?.(h.id)),!h.event||h.event==="message")try{let A=ww.parse(JSON.parse(h.data));o!==void 0&&zX(A)&&(A.id=o),(c=this.onmessage)===null||c===void 0||c.call(this,A)}catch(A){(u=this.onerror)===null||u===void 0||u.call(this,A)}}}catch(p){if((f=this.onerror)===null||f===void 0||f.call(this,new Error(`SSE stream disconnected: ${p}`)),n&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(h){(d=this.onerror)===null||d===void 0||d.call(this,new Error(`Failed to reconnect: ${h instanceof Error?h.message:String(h)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new W1("No auth provider");if(await Nw(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new W1("Failed to authorize")}async close(){var e,r;(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var n,i,o,s;try{let{resumptionToken:a,onresumptiontoken:c}=r||{};if(a){this._startOrAuthSse({resumptionToken:a,replayMessageId:$he(e)?e.id:void 0}).catch(y=>{var v;return(v=this.onerror)===null||v===void 0?void 0:v.call(this,y)});return}let u=await this._commonHeaders();u.set("content-type","application/json"),u.set("accept","application/json, text/event-stream");let f={...this._requestInit,method:"POST",headers:u,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},d=await((i=this._fetch)!==null&&i!==void 0?i:fetch)(this._url,f),p=d.headers.get("mcp-session-id");if(p&&(this._sessionId=p),!d.ok){if(d.status===401&&this._authProvider){if(this._resourceMetadataUrl=mZ(d),await Nw(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new W1;return this.send(e)}let y=await d.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${d.status}): ${y}`)}if(d.status===202){MDt(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(y=>{var v;return(v=this.onerror)===null||v===void 0?void 0:v.call(this,y)});return}let g=(Array.isArray(e)?e:[e]).filter(y=>"method"in y&&"id"in y&&y.id!==void 0).length>0,A=d.headers.get("content-type");if(g)if(A?.includes("text/event-stream"))this._handleSseStream(d.body,{onresumptiontoken:c},!1);else if(A?.includes("application/json")){let y=await d.json(),v=Array.isArray(y)?y.map(S=>ww.parse(S)):[ww.parse(y)];for(let S of v)(o=this.onmessage)===null||o===void 0||o.call(this,S)}else throw new gZ(-1,`Unexpected content type: ${A}`)}catch(a){throw(s=this.onerror)===null||s===void 0||s.call(this,a),a}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,n;if(this._sessionId)try{let i=await this._commonHeaders(),o={...this._requestInit,method:"DELETE",headers:i,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},s=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,o);if(!s.ok&&s.status!==405)throw new gZ(s.status,`Failed to terminate session: ${s.statusText}`);this._sessionId=void 0}catch(i){throw(n=this.onerror)===null||n===void 0||n.call(this,i),i}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}});import{readFile as Kxn}from"node:fs/promises";var AZ,yZ,pN,mPe=Ie(()=>{"use strict";VU();x0e();(function(t){t.CLI_CONNECT="cli_connect",t.PING="ping",t.GET_ACTIVE_FILE="get_active_file",t.GET_FILE_CONTENT="get_file_content",t.GET_SELECTED_TEXT="get_selected_text",t.SHOW_DIFF="show_diff"})(AZ||(AZ={}));yZ=class extends Error{code;constructor(e,r){super(r),this.code=e}},pN=class{_websocket;_url;_authProvider;_websocketOptions;_WebSocket;_protocolVersion;_isClosed=!1;_specialIds=new Set;onclose;onerror;onmessage;sessionId;constructor(e,r){this._url=e,this._authProvider=r?.authProvider,this._websocketOptions=r?.websocketOptions,this._WebSocket=r?.WebSocket||i7.default}async start(){if(this._isClosed)throw new Error("Transport is closed");let e=null;if(this._authProvider)try{let i=await this._authProvider.tokens();i?.access_token&&(e=i.access_token)}catch(i){try{let o=await this._authProvider.clientInformation();if(o){let s=await this._authProvider.tokens();if(s?.refresh_token){let a=await dPe(this._url,{clientInformation:o,refreshToken:s.refresh_token,addClientAuthentication:this._authProvider.addClientAuthentication});await this._authProvider.saveTokens(a),a?.access_token&&(e=a.access_token)}}}catch{if(this._authProvider.redirectToAuthorization){let s=this._authProvider.redirectUrl;throw await this._authProvider.redirectToAuthorization(typeof s=="string"?new URL(s):s),new Error("Unauthorized: OAuth required")}throw i}}let r={...this._websocketOptions?.headers};e&&(r.Authorization=`Bearer ${e}`),this._protocolVersion&&(r["MCP-Protocol-Version"]=this._protocolVersion);let n=new URL(this._url.toString());return n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),new Promise((i,o)=>{try{let s={headers:r};this._websocket=new this._WebSocket(n.toString(),s),this._websocket.on("open",()=>{i()}),this._websocket.on("error",a=>{let c=a.code!==void 0?a.code:void 0;o(new yZ(c,`WebSocket error: ${a.message}`))}),this._websocket.on("message",async a=>{try{let c=a.toString(),u=JSON.parse(c);if(this._specialIds.has(Number(u.id))||u.type==="welcome")return;this.onmessage?.(await this._transformResponse(u))}catch(c){this.onerror?.(new Error(`Failed to parse WebSocket message: ${c instanceof Error?c.message:String(c)}`))}}),this._websocket.on("close",()=>{this._isClosed||(this._isClosed=!0,this.onclose?.())})}catch(s){o(new yZ(void 0,`Failed to create WebSocket: ${s}`))}})}async finishAuth(e){if(!this._authProvider)throw new Error("No auth provider configured");try{let r=await this._authProvider.clientInformation();if(r){let n=this._authProvider.redirectUrl.toString(),i=await fPe(this._url,{clientInformation:r,authorizationCode:e,codeVerifier:await this._authProvider.codeVerifier(),redirectUri:n,addClientAuthentication:this._authProvider.addClientAuthentication});await this._authProvider.saveTokens(i)}else throw new Error("Client information not available")}catch(r){throw new Error(`Failed to exchange authorization code for access token: ${r}`)}}async close(){this._isClosed=!0,this._websocket&&this._websocket.readyState===i7.default.OPEN?this._websocket.close():this.onclose?.()}async send(e){if(this._isClosed)throw new Error("Transport is closed");if(!this._websocket)throw new Error("Transport not started");if(this._websocket.readyState!==i7.default.OPEN)throw new Error("WebSocket is not open");try{if(e.method==="notifications/initialized")return;let r=await this._transformRequest(e),n=JSON.stringify(r);this._websocket.send(n)}catch(r){throw new yZ(void 0,`Failed to send message: ${r instanceof Error?r.message:String(r)}`)}}async _transformRequest(e){if(e.method==="initialize")return{type:AZ.CLI_CONNECT,id:e.id,timestamp:Date.now(),payload:{clientInfo:{version:"0.2.24-beta.1",platform:process.platform,workingDirectory:process.cwd()}}};if(e.method==="tools/call"&&e.params?.name==="openDiff"){let{arguments:r}=e.params||{},{filePath:n,newContent:i}=r||{};return{type:AZ.SHOW_DIFF,id:e.id,timestamp:Date.now(),payload:{originalText:await Kxn(n,"utf8"),modifiedText:i}}}return e}async _transformResponse(e){if(e.type==="connection_ack")return{jsonrpc:"2.0",id:e.id,result:{protocolVersion:"2024-11-05",capabilities:{logging:{},prompts:{},resources:{},tools:{}},serverInfo:{name:"JetBrains Plugin Server",title:"JetBrains Plugin Server",version:"1.0.0"}}};if(e.type==="selection_changed"){let r=await this._getSelectedText();return{jsonrpc:"2.0",method:"ide/contextUpdate",params:{workspaceState:{openFiles:[{path:e.payload.fileName,timestamp:Date.now(),isActive:!0,selectedText:r}]}}}}return e.type==="active_file_changed"?{jsonrpc:"2.0",method:"ide/contextUpdate",params:{workspaceState:{openFiles:[{path:e.payload.fileName,timestamp:Date.now(),isActive:!0}]}}}:e}async _getSelectedText(){if(!this._websocket)return"";let e=performance.now();return this._specialIds.add(e),this._websocket.send(JSON.stringify({type:AZ.GET_SELECTED_TEXT,id:e,timestamp:Date.now()})),new Promise((r,n)=>{this._websocket.once("message",i=>{try{let o=JSON.parse(i.toString());Number(o.id)===e&&(this._specialIds.delete(e),o.payload.success?r(o.payload.data.text):n(o.payload.error))}catch{r("")}})})}setProtocolVersion(e){this._protocolVersion=e}}});var tOt,T0e,rOt=Ie(()=>{"use strict";tOt=Ye(TX(),1);T0e=class{config;auth;redirectUrl="";clientMetadata={client_name:"iFlow CLI (Google ADC)",redirect_uris:[],grant_types:[],response_types:[],token_endpoint_auth_method:"none"};_clientInformation;constructor(e){this.config=e;let r=this.config?.oauth?.scopes;if(!r||r.length===0)throw new Error("Scopes must be provided in the oauth config for Google Credentials provider");this.auth=new tOt.GoogleAuth({scopes:r})}clientInformation(){return this._clientInformation}saveClientInformation(e){this._clientInformation=e}async tokens(){let r=await(await this.auth.getClient()).getAccessToken();if(!r.token){console.error("Failed to get access token from Google ADC");return}return{access_token:r.token,token_type:"Bearer"}}saveTokens(e){}redirectToAuthorization(e){}saveCodeVerifier(e){}codeVerifier(){return""}}});import{execFile as Xxn}from"node:child_process";import{promisify as Zxn}from"node:util";import{platform as ewn}from"node:os";import{URL as twn}from"node:url";function rwn(t){let e;try{e=new twn(t)}catch{throw new Error(`Invalid URL: ${t}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`Unsafe protocol: ${e.protocol}. Only HTTP and HTTPS are allowed.`);if(/[\r\n\x00-\x1f]/.test(t))throw new Error("URL contains invalid characters")}async function iOt(t){rwn(t);let e=ewn(),r,n;switch(e){case"darwin":r="open",n=[t];break;case"win32":r="powershell.exe",n=["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`Start-Process '${t.replace(/'/g,"''")}'`];break;case"linux":case"freebsd":case"openbsd":r="xdg-open",n=[t];break;default:throw new Error(`Unsupported platform: ${e}`)}let i={env:{...process.env,SHELL:void 0},detached:!0,stdio:"ignore"};try{await nOt(r,n,i)}catch(o){if((e==="linux"||e==="freebsd"||e==="openbsd")&&r==="xdg-open"){let s=["gnome-open","kde-open","firefox","chromium","google-chrome"];for(let a of s)try{await nOt(a,[t],i);return}catch{continue}}throw new Error(`Failed to open browser: ${o instanceof Error?o.message:"Unknown error"}`)}}var nOt,oOt=Ie(()=>{"use strict";nOt=Zxn(Xxn)});function Bs(t){return t instanceof Error&&"code"in t}function wr(t){if(t instanceof Error)return t.message;try{return String(t)}catch{return"Failed to get error details"}}function gPe(t){if(t&&typeof t=="object"&&"response"in t){let r=nwn(t);if(r.error&&r.error.message&&r.error.code)switch(r.error.code){case 400:return new D0e(r.error.message);case 401:return new Mw(r.error.message);case 403:return new I0e(r.error.message);default:}}return t}function nwn(t){return typeof t.response?.data=="string"?JSON.parse(t.response?.data):t.response?.data}var I0e,Mw,D0e,Zu=Ie(()=>{"use strict";I0e=class extends Error{},Mw=class extends Error{},D0e=class extends Error{}});import{promises as Tq}from"node:fs";import*as R0e from"node:path";import*as sOt from"node:os";var Xh,B0e=Ie(()=>{"use strict";Zu();Xh=class{static TOKEN_FILE="mcp-oauth-tokens.json";static CONFIG_DIR=".iflow";static getTokenFilePath(){let e=sOt.homedir();return R0e.join(e,this.CONFIG_DIR,this.TOKEN_FILE)}static async ensureConfigDir(){let e=R0e.dirname(this.getTokenFilePath());await Tq.mkdir(e,{recursive:!0})}static async loadTokens(){let e=new Map;try{let r=this.getTokenFilePath(),n=await Tq.readFile(r,"utf-8"),i=JSON.parse(n);for(let o of i)e.set(o.serverName,o)}catch(r){r.code!=="ENOENT"&&console.error(`Failed to load MCP OAuth tokens: ${wr(r)}`)}return e}static async saveToken(e,r,n,i,o){await this.ensureConfigDir();let s=await this.loadTokens(),a={serverName:e,token:r,clientId:n,tokenUrl:i,mcpServerUrl:o,updatedAt:Date.now()};s.set(e,a);let c=Array.from(s.values()),u=this.getTokenFilePath();try{await Tq.writeFile(u,JSON.stringify(c,null,2),{mode:384})}catch(f){throw console.error(`Failed to save MCP OAuth token: ${wr(f)}`),f}}static async getToken(e){return(await this.loadTokens()).get(e)||null}static async removeToken(e){let r=await this.loadTokens();if(r.delete(e)){let n=Array.from(r.values()),i=this.getTokenFilePath();try{n.length===0?await Tq.unlink(i):await Tq.writeFile(i,JSON.stringify(n,null,2),{mode:384})}catch(o){console.error(`Failed to remove MCP OAuth token: ${wr(o)}`)}}}static isTokenExpired(e){if(!e.expiresAt)return!1;let r=300*1e3;return Date.now()+r>=e.expiresAt}static async clearAllTokens(){try{let e=this.getTokenFilePath();await Tq.unlink(e)}catch(e){e.code!=="ENOENT"&&console.error(`Failed to clear MCP OAuth tokens: ${wr(e)}`)}}}});var Zh,N0e=Ie(()=>{"use strict";Zu();Zh=class{static buildWellKnownUrls(e){let r=new URL(e),n=`${r.protocol}//${r.host}`;return{protectedResource:new URL("/.well-known/oauth-protected-resource",n).toString(),authorizationServer:new URL("/.well-known/oauth-authorization-server",n).toString()}}static async fetchProtectedResourceMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return console.debug(`Failed to fetch protected resource metadata from ${e}: ${wr(r)}`),null}}static async fetchAuthorizationServerMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return console.debug(`Failed to fetch authorization server metadata from ${e}: ${wr(r)}`),null}}static metadataToOAuthConfig(e){return{authorizationUrl:e.authorization_endpoint,tokenUrl:e.token_endpoint,scopes:e.scopes_supported||[]}}static async discoverOAuthConfig(e){try{let r=this.buildWellKnownUrls(e),n=await this.fetchProtectedResourceMetadata(r.protectedResource);if(n?.authorization_servers?.length){let o=n.authorization_servers[0],s=new URL("/.well-known/oauth-authorization-server",o).toString(),a=await this.fetchAuthorizationServerMetadata(s);if(a){let c=this.metadataToOAuthConfig(a);return a.registration_endpoint&&console.log("Dynamic client registration is supported at:",a.registration_endpoint),c}}console.debug(`Trying OAuth discovery fallback at ${r.authorizationServer}`);let i=await this.fetchAuthorizationServerMetadata(r.authorizationServer);if(i){let o=this.metadataToOAuthConfig(i);return i.registration_endpoint&&console.log("Dynamic client registration is supported at:",i.registration_endpoint),o}return null}catch(r){return console.debug(`Failed to discover OAuth configuration: ${wr(r)}`),null}}static parseWWWAuthenticateHeader(e){let r=e.match(/resource_metadata="([^"]+)"/);return r?r[1]:null}static async discoverOAuthFromWWWAuthenticate(e){let r=this.parseWWWAuthenticateHeader(e);if(!r)return null;console.log(`Found resource metadata URI from www-authenticate header: ${r}`);let n=await this.fetchProtectedResourceMetadata(r);if(!n?.authorization_servers?.length)return null;let i=n.authorization_servers[0],o=new URL("/.well-known/oauth-authorization-server",i).toString(),s=await this.fetchAuthorizationServerMetadata(o);return s?(console.log("OAuth configuration discovered successfully from www-authenticate header"),this.metadataToOAuthConfig(s)):null}static extractBaseUrl(e){let r=new URL(e);return`${r.protocol}//${r.host}`}static isSSEEndpoint(e){return e.includes("/sse")||!e.includes("/mcp")}static buildResourceParameter(e){let r=new URL(e);return`${r.protocol}//${r.host}`}}});import*as aOt from"node:http";import*as EZ from"node:crypto";import{URL as APe}from"node:url";var w3,yPe=Ie(()=>{"use strict";oOt();B0e();Zu();N0e();w3=class{static REDIRECT_PORT=7777;static REDIRECT_PATH="/oauth/callback";static HTTP_OK=200;static HTTP_REDIRECT=302;static async registerClient(e,r){let i={client_name:"iFlow CLI MCP Client",redirect_uris:[r.redirectUri||`http://localhost:${this.REDIRECT_PORT}${this.REDIRECT_PATH}`],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none",code_challenge_method:["S256"],scope:r.scopes?.join(" ")||""},o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!o.ok){let s=await o.text();throw new Error(`Client registration failed: ${o.status} ${o.statusText} - ${s}`)}return await o.json()}static async discoverOAuthFromMCPServer(e){let r=Zh.extractBaseUrl(e);return Zh.discoverOAuthConfig(r)}static generatePKCEParams(){let e=EZ.randomBytes(32).toString("base64url"),r=EZ.createHash("sha256").update(e).digest("base64url"),n=EZ.randomBytes(16).toString("base64url");return{codeVerifier:e,codeChallenge:r,state:n}}static async startCallbackServer(e){return new Promise((r,n)=>{let i=aOt.createServer(async(o,s)=>{try{let a=new APe(o.url,`http://localhost:${this.REDIRECT_PORT}`);if(a.pathname!==this.REDIRECT_PATH){s.writeHead(404),s.end("Not found");return}let c=a.searchParams.get("code"),u=a.searchParams.get("state"),f=a.searchParams.get("error");if(f){s.writeHead(this.HTTP_OK,{"Content-Type":"text/html"}),s.end(`
|
|
420
|
+
`&&n++}}return[e,r]}var v0e,jFe=Ie(()=>{v0e=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}});function Dxn(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function zFe(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(zFe).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${zFe(t.cause)}`:t.message:`${t}`}function FNt(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}function Rxn(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var _0e,LNt,rPe,js,Zp,Xu,T7,$1,lN,Cq,b0e,S0e,tZ,Sq,rZ,Bw,bq,xq,_q,ZX,a5,YFe,JFe,KFe,PNt,XFe,ZFe,eZ,ePe,tPe,cN,UNt=Ie(()=>{jFe();_0e=class extends Event{constructor(e,r){var n,i;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(i=r?.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(FNt(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(FNt(this),r)}};LNt=t=>{throw TypeError(t)},rPe=(t,e,r)=>e.has(t)||LNt("Cannot "+r),js=(t,e,r)=>(rPe(t,e,"read from private field"),r?r.call(t):e.get(t)),Zp=(t,e,r)=>e.has(t)?LNt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Xu=(t,e,r,n)=>(rPe(t,e,"write to private field"),e.set(t,r),r),T7=(t,e,r)=>(rPe(t,e,"access private method"),r),cN=class extends EventTarget{constructor(e,r){var n,i;super(),Zp(this,a5),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Zp(this,$1),Zp(this,lN),Zp(this,Cq),Zp(this,b0e),Zp(this,S0e),Zp(this,tZ),Zp(this,Sq),Zp(this,rZ,null),Zp(this,Bw),Zp(this,bq),Zp(this,xq,null),Zp(this,_q,null),Zp(this,ZX,null),Zp(this,JFe,async o=>{var s;js(this,bq).reset();let{body:a,redirected:c,status:u,headers:f}=o;if(u===204){T7(this,a5,eZ).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?Xu(this,Cq,new URL(o.url)):Xu(this,Cq,void 0),u!==200){T7(this,a5,eZ).call(this,`Non-200 status code (${u})`,u);return}if(!(f.get("content-type")||"").startsWith("text/event-stream")){T7(this,a5,eZ).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(js(this,$1)===this.CLOSED)return;Xu(this,$1,this.OPEN);let d=new Event("open");if((s=js(this,ZX))==null||s.call(this,d),this.dispatchEvent(d),typeof a!="object"||!a||!("getReader"in a)){T7(this,a5,eZ).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let p=new TextDecoder,h=a.getReader(),g=!0;do{let{done:A,value:y}=await h.read();y&&js(this,bq).feed(p.decode(y,{stream:!A})),A&&(g=!1,js(this,bq).reset(),T7(this,a5,ePe).call(this))}while(g)}),Zp(this,KFe,o=>{Xu(this,Bw,void 0),!(o.name==="AbortError"||o.type==="aborted")&&T7(this,a5,ePe).call(this,zFe(o))}),Zp(this,XFe,o=>{typeof o.id=="string"&&Xu(this,rZ,o.id);let s=new MessageEvent(o.event||"message",{data:o.data,origin:js(this,Cq)?js(this,Cq).origin:js(this,lN).origin,lastEventId:o.id||""});js(this,_q)&&(!o.event||o.event==="message")&&js(this,_q).call(this,s),this.dispatchEvent(s)}),Zp(this,ZFe,o=>{Xu(this,tZ,o)}),Zp(this,tPe,()=>{Xu(this,Sq,void 0),js(this,$1)===this.CONNECTING&&T7(this,a5,YFe).call(this)});try{if(e instanceof URL)Xu(this,lN,e);else if(typeof e=="string")Xu(this,lN,new URL(e,Rxn()));else throw new Error("Invalid URL")}catch{throw Dxn("An invalid or illegal string was specified")}Xu(this,bq,C0e({onEvent:js(this,XFe),onRetry:js(this,ZFe)})),Xu(this,$1,this.CONNECTING),Xu(this,tZ,3e3),Xu(this,S0e,(n=r?.fetch)!=null?n:globalThis.fetch),Xu(this,b0e,(i=r?.withCredentials)!=null?i:!1),T7(this,a5,YFe).call(this)}get readyState(){return js(this,$1)}get url(){return js(this,lN).href}get withCredentials(){return js(this,b0e)}get onerror(){return js(this,xq)}set onerror(e){Xu(this,xq,e)}get onmessage(){return js(this,_q)}set onmessage(e){Xu(this,_q,e)}get onopen(){return js(this,ZX)}set onopen(e){Xu(this,ZX,e)}addEventListener(e,r,n){let i=r;super.addEventListener(e,i,n)}removeEventListener(e,r,n){let i=r;super.removeEventListener(e,i,n)}close(){js(this,Sq)&&clearTimeout(js(this,Sq)),js(this,$1)!==this.CLOSED&&(js(this,Bw)&&js(this,Bw).abort(),Xu(this,$1,this.CLOSED),Xu(this,Bw,void 0))}};$1=new WeakMap,lN=new WeakMap,Cq=new WeakMap,b0e=new WeakMap,S0e=new WeakMap,tZ=new WeakMap,Sq=new WeakMap,rZ=new WeakMap,Bw=new WeakMap,bq=new WeakMap,xq=new WeakMap,_q=new WeakMap,ZX=new WeakMap,a5=new WeakSet,YFe=function(){Xu(this,$1,this.CONNECTING),Xu(this,Bw,new AbortController),js(this,S0e)(js(this,lN),T7(this,a5,PNt).call(this)).then(js(this,JFe)).catch(js(this,KFe))},JFe=new WeakMap,KFe=new WeakMap,PNt=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...js(this,rZ)?{"Last-Event-ID":js(this,rZ)}:void 0},cache:"no-store",signal:(t=js(this,Bw))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},XFe=new WeakMap,ZFe=new WeakMap,eZ=function(t,e){var r;js(this,$1)!==this.CLOSED&&Xu(this,$1,this.CLOSED);let n=new _0e("error",{code:e,message:t});(r=js(this,xq))==null||r.call(this,n),this.dispatchEvent(n)},ePe=function(t,e){var r;if(js(this,$1)===this.CLOSED)return;Xu(this,$1,this.CONNECTING);let n=new _0e("error",{code:e,message:t});(r=js(this,xq))==null||r.call(this,n),this.dispatchEvent(n),Xu(this,Sq,setTimeout(js(this,tPe),js(this,tZ)))},tPe=new WeakMap,cN.CONNECTING=0,cN.OPEN=1,cN.CLOSED=2});async function Bxn(t){return(await nPe).getRandomValues(new Uint8Array(t))}async function Nxn(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r="",n=await Bxn(t);for(let i=0;i<t;i++){let o=n[i]%e.length;r+=e[o]}return r}async function Oxn(t){return await Nxn(t)}async function Mxn(t){let e=await(await nPe).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function iPe(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await Oxn(t),r=await Mxn(e);return{code_verifier:e,code_challenge:r}}var nPe,QNt=Ie(()=>{nPe=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto)});var Kh,qNt,oPe,kxn,HNt,sPe,GNt,Fxn,Pxn,VNt,kxo,Fxo,aPe=Ie(()=>{xw();Kh=fe.string().url().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:fe.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),fe.NEVER}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),qNt=fe.object({resource:fe.string().url(),authorization_servers:fe.array(Kh).optional(),jwks_uri:fe.string().url().optional(),scopes_supported:fe.array(fe.string()).optional(),bearer_methods_supported:fe.array(fe.string()).optional(),resource_signing_alg_values_supported:fe.array(fe.string()).optional(),resource_name:fe.string().optional(),resource_documentation:fe.string().optional(),resource_policy_uri:fe.string().url().optional(),resource_tos_uri:fe.string().url().optional(),tls_client_certificate_bound_access_tokens:fe.boolean().optional(),authorization_details_types_supported:fe.array(fe.string()).optional(),dpop_signing_alg_values_supported:fe.array(fe.string()).optional(),dpop_bound_access_tokens_required:fe.boolean().optional()}).passthrough(),oPe=fe.object({issuer:fe.string(),authorization_endpoint:Kh,token_endpoint:Kh,registration_endpoint:Kh.optional(),scopes_supported:fe.array(fe.string()).optional(),response_types_supported:fe.array(fe.string()),response_modes_supported:fe.array(fe.string()).optional(),grant_types_supported:fe.array(fe.string()).optional(),token_endpoint_auth_methods_supported:fe.array(fe.string()).optional(),token_endpoint_auth_signing_alg_values_supported:fe.array(fe.string()).optional(),service_documentation:Kh.optional(),revocation_endpoint:Kh.optional(),revocation_endpoint_auth_methods_supported:fe.array(fe.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:fe.array(fe.string()).optional(),introspection_endpoint:fe.string().optional(),introspection_endpoint_auth_methods_supported:fe.array(fe.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:fe.array(fe.string()).optional(),code_challenge_methods_supported:fe.array(fe.string()).optional()}).passthrough(),kxn=fe.object({issuer:fe.string(),authorization_endpoint:Kh,token_endpoint:Kh,userinfo_endpoint:Kh.optional(),jwks_uri:Kh,registration_endpoint:Kh.optional(),scopes_supported:fe.array(fe.string()).optional(),response_types_supported:fe.array(fe.string()),response_modes_supported:fe.array(fe.string()).optional(),grant_types_supported:fe.array(fe.string()).optional(),acr_values_supported:fe.array(fe.string()).optional(),subject_types_supported:fe.array(fe.string()),id_token_signing_alg_values_supported:fe.array(fe.string()),id_token_encryption_alg_values_supported:fe.array(fe.string()).optional(),id_token_encryption_enc_values_supported:fe.array(fe.string()).optional(),userinfo_signing_alg_values_supported:fe.array(fe.string()).optional(),userinfo_encryption_alg_values_supported:fe.array(fe.string()).optional(),userinfo_encryption_enc_values_supported:fe.array(fe.string()).optional(),request_object_signing_alg_values_supported:fe.array(fe.string()).optional(),request_object_encryption_alg_values_supported:fe.array(fe.string()).optional(),request_object_encryption_enc_values_supported:fe.array(fe.string()).optional(),token_endpoint_auth_methods_supported:fe.array(fe.string()).optional(),token_endpoint_auth_signing_alg_values_supported:fe.array(fe.string()).optional(),display_values_supported:fe.array(fe.string()).optional(),claim_types_supported:fe.array(fe.string()).optional(),claims_supported:fe.array(fe.string()).optional(),service_documentation:fe.string().optional(),claims_locales_supported:fe.array(fe.string()).optional(),ui_locales_supported:fe.array(fe.string()).optional(),claims_parameter_supported:fe.boolean().optional(),request_parameter_supported:fe.boolean().optional(),request_uri_parameter_supported:fe.boolean().optional(),require_request_uri_registration:fe.boolean().optional(),op_policy_uri:Kh.optional(),op_tos_uri:Kh.optional()}).passthrough(),HNt=kxn.merge(oPe.pick({code_challenge_methods_supported:!0})),sPe=fe.object({access_token:fe.string(),id_token:fe.string().optional(),token_type:fe.string(),expires_in:fe.number().optional(),scope:fe.string().optional(),refresh_token:fe.string().optional()}).strip(),GNt=fe.object({error:fe.string(),error_description:fe.string().optional(),error_uri:fe.string().optional()}),Fxn=fe.object({redirect_uris:fe.array(Kh),token_endpoint_auth_method:fe.string().optional(),grant_types:fe.array(fe.string()).optional(),response_types:fe.array(fe.string()).optional(),client_name:fe.string().optional(),client_uri:Kh.optional(),logo_uri:Kh.optional(),scope:fe.string().optional(),contacts:fe.array(fe.string()).optional(),tos_uri:Kh.optional(),policy_uri:fe.string().optional(),jwks_uri:Kh.optional(),jwks:fe.any().optional(),software_id:fe.string().optional(),software_version:fe.string().optional(),software_statement:fe.string().optional()}).strip(),Pxn=fe.object({client_id:fe.string(),client_secret:fe.string().optional(),client_id_issued_at:fe.number().optional(),client_secret_expires_at:fe.number().optional()}).strip(),VNt=Fxn.merge(Pxn),kxo=fe.object({error:fe.string(),error_description:fe.string().optional()}).strip(),Fxo=fe.object({token:fe.string(),token_type_hint:fe.string().optional()}).strip()});function $Nt(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function WNt({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return i.startsWith(o)}var jNt=Ie(()=>{});var Ep,nZ,uN,fN,dN,iZ,oZ,sZ,I7,aZ,lZ,cZ,uZ,fZ,dZ,pZ,hZ,zNt,YNt=Ie(()=>{Ep=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},nZ=class extends Ep{};nZ.errorCode="invalid_request";uN=class extends Ep{};uN.errorCode="invalid_client";fN=class extends Ep{};fN.errorCode="invalid_grant";dN=class extends Ep{};dN.errorCode="unauthorized_client";iZ=class extends Ep{};iZ.errorCode="unsupported_grant_type";oZ=class extends Ep{};oZ.errorCode="invalid_scope";sZ=class extends Ep{};sZ.errorCode="access_denied";I7=class extends Ep{};I7.errorCode="server_error";aZ=class extends Ep{};aZ.errorCode="temporarily_unavailable";lZ=class extends Ep{};lZ.errorCode="unsupported_response_type";cZ=class extends Ep{};cZ.errorCode="unsupported_token_type";uZ=class extends Ep{};uZ.errorCode="invalid_token";fZ=class extends Ep{};fZ.errorCode="method_not_allowed";dZ=class extends Ep{};dZ.errorCode="too_many_requests";pZ=class extends Ep{};pZ.errorCode="invalid_client_metadata";hZ=class extends Ep{};hZ.errorCode="insufficient_scope";zNt={[nZ.errorCode]:nZ,[uN.errorCode]:uN,[fN.errorCode]:fN,[dN.errorCode]:dN,[iZ.errorCode]:iZ,[oZ.errorCode]:oZ,[sZ.errorCode]:sZ,[I7.errorCode]:I7,[aZ.errorCode]:aZ,[lZ.errorCode]:lZ,[cZ.errorCode]:cZ,[uZ.errorCode]:uZ,[fZ.errorCode]:fZ,[dZ.errorCode]:dZ,[pZ.errorCode]:pZ,[hZ.errorCode]:hZ}});function KNt(t,e){let r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function XNt(t,e,r,n){let{client_id:i,client_secret:o}=e;switch(t){case"client_secret_basic":Lxn(i,o,r);return;case"client_secret_post":Uxn(i,o,n);return;case"none":Qxn(i,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function Lxn(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function Uxn(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function Qxn(t,e){e.set("client_id",t)}async function cPe(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=GNt.parse(JSON.parse(r)),{error:i,error_description:o,error_uri:s}=n,a=zNt[i]||I7;return new a(o||"",s)}catch(n){let i=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new I7(i)}}async function Nw(t,e){var r,n;try{return await lPe(t,e)}catch(i){if(i instanceof uN||i instanceof dN)return await((r=t.invalidateCredentials)===null||r===void 0?void 0:r.call(t,"all")),await lPe(t,e);if(i instanceof fN)return await((n=t.invalidateCredentials)===null||n===void 0?void 0:n.call(t,"tokens")),await lPe(t,e);throw i}}async function lPe(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:i,fetchFn:o}){let s,a;try{s=await Hxn(e,{resourceMetadataUrl:i},o),s.authorization_servers&&s.authorization_servers.length>0&&(a=s.authorization_servers[0])}catch{}a||(a=e);let c=await qxn(e,t,s),u=await jxn(a,{fetchFn:o}),f=await Promise.resolve(t.clientInformation());if(!f){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let A=await Yxn(a,{metadata:u,clientMetadata:t.clientMetadata,fetchFn:o});await t.saveClientInformation(A),f=A}if(r!==void 0){let A=await t.codeVerifier(),y=await fPe(a,{metadata:u,clientInformation:f,authorizationCode:r,codeVerifier:A,redirectUri:t.redirectUrl,resource:c,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(y),"AUTHORIZED"}let d=await t.tokens();if(d?.refresh_token)try{let A=await dPe(a,{metadata:u,clientInformation:f,refreshToken:d.refresh_token,resource:c,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(A),"AUTHORIZED"}catch(A){if(!(!(A instanceof Ep)||A instanceof I7))throw A}let p=t.state?await t.state():void 0,{authorizationUrl:h,codeVerifier:g}=await zxn(a,{metadata:u,clientInformation:f,state:p,redirectUrl:t.redirectUrl,scope:n||t.clientMetadata.scope,resource:c});return await t.saveCodeVerifier(g),await t.redirectToAuthorization(h),"REDIRECT"}async function qxn(t,e,r){let n=$Nt(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!WNt({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function mZ(t){let e=t.headers.get("WWW-Authenticate");if(!e)return;let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return;let o=/resource_metadata="([^"]*)"/.exec(e);if(o)try{return new URL(o[1])}catch{return}}async function Hxn(t,e,r=fetch){let n=await $xn(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return qNt.parse(await n.json())}async function uPe(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?uPe(t,void 0,r):void 0;throw n}}function Gxn(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function JNt(t,e,r=fetch){return await uPe(t,{"MCP-Protocol-Version":e},r)}function Vxn(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function $xn(t,e,r,n){var i,o;let s=new URL(t),a=(i=n?.protocolVersion)!==null&&i!==void 0?i:mq,c;if(n?.metadataUrl)c=new URL(n.metadataUrl);else{let f=Gxn(e,s.pathname);c=new URL(f,(o=n?.metadataServerUrl)!==null&&o!==void 0?o:s),c.search=s.search}let u=await JNt(c,a,r);if(!n?.metadataUrl&&Vxn(u,s.pathname)){let f=new URL(`/.well-known/${e}`,s);u=await JNt(f,a,r)}return u}function Wxn(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let i=e.pathname;return i.endsWith("/")&&(i=i.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${i}`,e.origin),type:"oidc"}),n.push({url:new URL(`${i}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function jxn(t,{fetchFn:e=fetch,protocolVersion:r=mq}={}){var n;let i={"MCP-Protocol-Version":r},o=Wxn(t);for(let{url:s,type:a}of o){let c=await uPe(s,i,e);if(c){if(!c.ok){if(c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}if(a==="oauth")return oPe.parse(await c.json());{let u=HNt.parse(await c.json());if(!(!((n=u.code_challenge_methods_supported)===null||n===void 0)&&n.includes("S256")))throw new Error(`Incompatible OIDC provider at ${s}: does not support S256 code challenge method required by MCP specification`);return u}}}}async function zxn(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:i,state:o,resource:s}){let a="code",c="S256",u;if(e){if(u=new URL(e.authorization_endpoint),!e.response_types_supported.includes(a))throw new Error(`Incompatible auth server: does not support response type ${a}`);if(!e.code_challenge_methods_supported||!e.code_challenge_methods_supported.includes(c))throw new Error(`Incompatible auth server: does not support code challenge method ${c}`)}else u=new URL("/authorize",t);let f=await iPe(),d=f.code_verifier,p=f.code_challenge;return u.searchParams.set("response_type",a),u.searchParams.set("client_id",r.client_id),u.searchParams.set("code_challenge",p),u.searchParams.set("code_challenge_method",c),u.searchParams.set("redirect_uri",String(n)),o&&u.searchParams.set("state",o),i&&u.searchParams.set("scope",i),i?.includes("offline_access")&&u.searchParams.append("prompt","consent"),s&&u.searchParams.set("resource",s.href),{authorizationUrl:u,codeVerifier:d}}async function fPe(t,{metadata:e,clientInformation:r,authorizationCode:n,codeVerifier:i,redirectUri:o,resource:s,addClientAuthentication:a,fetchFn:c}){var u;let f="authorization_code",d=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e?.grant_types_supported&&!e.grant_types_supported.includes(f))throw new Error(`Incompatible auth server: does not support grant type ${f}`);let p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),h=new URLSearchParams({grant_type:f,code:n,code_verifier:i,redirect_uri:String(o)});if(a)a(p,h,t,e);else{let A=(u=e?.token_endpoint_auth_methods_supported)!==null&&u!==void 0?u:[],y=KNt(r,A);XNt(y,r,p,h)}s&&h.set("resource",s.href);let g=await(c??fetch)(d,{method:"POST",headers:p,body:h});if(!g.ok)throw await cPe(g);return sPe.parse(await g.json())}async function dPe(t,{metadata:e,clientInformation:r,refreshToken:n,resource:i,addClientAuthentication:o,fetchFn:s}){var a;let c="refresh_token",u;if(e){if(u=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`)}else u=new URL("/token",t);let f=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),d=new URLSearchParams({grant_type:c,refresh_token:n});if(o)o(f,d,t,e);else{let h=(a=e?.token_endpoint_auth_methods_supported)!==null&&a!==void 0?a:[],g=KNt(r,h);XNt(g,r,f,d)}i&&d.set("resource",i.href);let p=await(s??fetch)(u,{method:"POST",headers:f,body:d});if(!p.ok)throw await cPe(p);return sPe.parse({refresh_token:n,...await p.json()})}async function Yxn(t,{metadata:e,clientMetadata:r,fetchFn:n}){let i;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(e.registration_endpoint)}else i=new URL("/register",t);let o=await(n??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await cPe(o);return VNt.parse(await o.json())}var W1,x0e=Ie(()=>{QNt();Tw();aPe();aPe();jNt();YNt();W1=class extends Error{constructor(e){super(e??"Unauthorized")}}});var pPe,wq,ZNt=Ie(()=>{UNt();Tw();x0e();pPe=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},wq=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch}async _authThenStart(){var e;if(!this._authProvider)throw new W1("No auth provider");let r;try{r=await Nw(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new W1;return await this._startOrAuth()}async _commonHeaders(){var e;let r={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(r.Authorization=`Bearer ${n.access_token}`)}return this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion),new Headers({...r,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}_startOrAuth(){var e,r,n;let i=(n=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((o,s)=>{this._eventSource=new cN(this._url.href,{...this._eventSourceInit,fetch:async(a,c)=>{let u=await this._commonHeaders();u.set("Accept","text/event-stream");let f=await i(a,{...c,headers:u});return f.status===401&&f.headers.has("www-authenticate")&&(this._resourceMetadataUrl=mZ(f)),f}}),this._abortController=new AbortController,this._eventSource.onerror=a=>{var c;if(a.code===401&&this._authProvider){this._authThenStart().then(o,s);return}let u=new pPe(a.code,a.message,a);s(u),(c=this.onerror)===null||c===void 0||c.call(this,u)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",a=>{var c;let u=a;try{if(this._endpoint=new URL(u.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(f){s(f),(c=this.onerror)===null||c===void 0||c.call(this,f),this.close();return}o()}),this._eventSource.onmessage=a=>{var c,u;let f=a,d;try{d=ww.parse(JSON.parse(f.data))}catch(p){(c=this.onerror)===null||c===void 0||c.call(this,p);return}(u=this.onmessage)===null||u===void 0||u.call(this,d)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new W1("No auth provider");if(await Nw(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new W1("Failed to authorize")}async close(){var e,r,n;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var r,n,i;if(!this._endpoint)throw new Error("Not connected");try{let o=await this._commonHeaders();o.set("content-type","application/json");let s={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},a=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,s);if(!a.ok){if(a.status===401&&this._authProvider){if(this._resourceMetadataUrl=mZ(a),await Nw(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new W1;return this.send(e)}let c=await a.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${a.status}): ${c}`)}}catch(o){throw(i=this.onerror)===null||i===void 0||i.call(this,o),o}}setProtocolVersion(e){this._protocolVersion=e}}});var w0e,eOt=Ie(()=>{jFe();w0e=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=C0e({onEvent:s=>{o.enqueue(s)},onError(s){e==="terminate"?o.error(s):typeof e=="function"&&e(s)},onRetry:r,onComment:n})},transform(o){i.feed(o)}})}}});var Jxn,gZ,Ow,hPe=Ie(()=>{Tw();x0e();eOt();Jxn={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},gZ=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Ow=class{constructor(e,r){var n;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:Jxn}async _authThenStart(){var e;if(!this._authProvider)throw new W1("No auth provider");let r;try{r=await Nw(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new W1;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let r={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(r.Authorization=`Bearer ${i.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}async _startOrAuthSse(e){var r,n,i;let{resumptionToken:o}=e;try{let s=await this._commonHeaders();s.set("Accept","text/event-stream"),o&&s.set("last-event-id",o);let a=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:s,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!a.ok){if(a.status===401&&this._authProvider)return await this._authThenStart();if(a.status===405)return;throw new gZ(a.status,`Failed to open SSE stream: ${a.statusText}`)}this._handleSseStream(a.body,e,!0)}catch(s){throw(i=this.onerror)===null||i===void 0||i.call(this,s),s}}_getNextReconnectionDelay(e){let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),i)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,r=0){var n;let i=this._reconnectionOptions.maxRetries;if(i>0&&r>=i){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${i}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{var a;(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:o}=r,s;(async()=>{var c,u,f,d;try{let p=e.pipeThrough(new TextDecoderStream).pipeThrough(new w0e).getReader();for(;;){let{value:h,done:g}=await p.read();if(g)break;if(h.id&&(s=h.id,i?.(h.id)),!h.event||h.event==="message")try{let A=ww.parse(JSON.parse(h.data));o!==void 0&&zX(A)&&(A.id=o),(c=this.onmessage)===null||c===void 0||c.call(this,A)}catch(A){(u=this.onerror)===null||u===void 0||u.call(this,A)}}}catch(p){if((f=this.onerror)===null||f===void 0||f.call(this,new Error(`SSE stream disconnected: ${p}`)),n&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(h){(d=this.onerror)===null||d===void 0||d.call(this,new Error(`Failed to reconnect: ${h instanceof Error?h.message:String(h)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new W1("No auth provider");if(await Nw(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new W1("Failed to authorize")}async close(){var e,r;(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var n,i,o,s;try{let{resumptionToken:a,onresumptiontoken:c}=r||{};if(a){this._startOrAuthSse({resumptionToken:a,replayMessageId:$he(e)?e.id:void 0}).catch(y=>{var v;return(v=this.onerror)===null||v===void 0?void 0:v.call(this,y)});return}let u=await this._commonHeaders();u.set("content-type","application/json"),u.set("accept","application/json, text/event-stream");let f={...this._requestInit,method:"POST",headers:u,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},d=await((i=this._fetch)!==null&&i!==void 0?i:fetch)(this._url,f),p=d.headers.get("mcp-session-id");if(p&&(this._sessionId=p),!d.ok){if(d.status===401&&this._authProvider){if(this._resourceMetadataUrl=mZ(d),await Nw(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new W1;return this.send(e)}let y=await d.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${d.status}): ${y}`)}if(d.status===202){MDt(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(y=>{var v;return(v=this.onerror)===null||v===void 0?void 0:v.call(this,y)});return}let g=(Array.isArray(e)?e:[e]).filter(y=>"method"in y&&"id"in y&&y.id!==void 0).length>0,A=d.headers.get("content-type");if(g)if(A?.includes("text/event-stream"))this._handleSseStream(d.body,{onresumptiontoken:c},!1);else if(A?.includes("application/json")){let y=await d.json(),v=Array.isArray(y)?y.map(S=>ww.parse(S)):[ww.parse(y)];for(let S of v)(o=this.onmessage)===null||o===void 0||o.call(this,S)}else throw new gZ(-1,`Unexpected content type: ${A}`)}catch(a){throw(s=this.onerror)===null||s===void 0||s.call(this,a),a}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,n;if(this._sessionId)try{let i=await this._commonHeaders(),o={...this._requestInit,method:"DELETE",headers:i,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},s=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,o);if(!s.ok&&s.status!==405)throw new gZ(s.status,`Failed to terminate session: ${s.statusText}`);this._sessionId=void 0}catch(i){throw(n=this.onerror)===null||n===void 0||n.call(this,i),i}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}});import{readFile as Kxn}from"node:fs/promises";var AZ,yZ,pN,mPe=Ie(()=>{"use strict";VU();x0e();(function(t){t.CLI_CONNECT="cli_connect",t.PING="ping",t.GET_ACTIVE_FILE="get_active_file",t.GET_FILE_CONTENT="get_file_content",t.GET_SELECTED_TEXT="get_selected_text",t.SHOW_DIFF="show_diff"})(AZ||(AZ={}));yZ=class extends Error{code;constructor(e,r){super(r),this.code=e}},pN=class{_websocket;_url;_authProvider;_websocketOptions;_WebSocket;_protocolVersion;_isClosed=!1;_specialIds=new Set;onclose;onerror;onmessage;sessionId;constructor(e,r){this._url=e,this._authProvider=r?.authProvider,this._websocketOptions=r?.websocketOptions,this._WebSocket=r?.WebSocket||i7.default}async start(){if(this._isClosed)throw new Error("Transport is closed");let e=null;if(this._authProvider)try{let i=await this._authProvider.tokens();i?.access_token&&(e=i.access_token)}catch(i){try{let o=await this._authProvider.clientInformation();if(o){let s=await this._authProvider.tokens();if(s?.refresh_token){let a=await dPe(this._url,{clientInformation:o,refreshToken:s.refresh_token,addClientAuthentication:this._authProvider.addClientAuthentication});await this._authProvider.saveTokens(a),a?.access_token&&(e=a.access_token)}}}catch{if(this._authProvider.redirectToAuthorization){let s=this._authProvider.redirectUrl;throw await this._authProvider.redirectToAuthorization(typeof s=="string"?new URL(s):s),new Error("Unauthorized: OAuth required")}throw i}}let r={...this._websocketOptions?.headers};e&&(r.Authorization=`Bearer ${e}`),this._protocolVersion&&(r["MCP-Protocol-Version"]=this._protocolVersion);let n=new URL(this._url.toString());return n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),new Promise((i,o)=>{try{let s={headers:r};this._websocket=new this._WebSocket(n.toString(),s),this._websocket.on("open",()=>{i()}),this._websocket.on("error",a=>{let c=a.code!==void 0?a.code:void 0;o(new yZ(c,`WebSocket error: ${a.message}`))}),this._websocket.on("message",async a=>{try{let c=a.toString(),u=JSON.parse(c);if(this._specialIds.has(Number(u.id))||u.type==="welcome")return;this.onmessage?.(await this._transformResponse(u))}catch(c){this.onerror?.(new Error(`Failed to parse WebSocket message: ${c instanceof Error?c.message:String(c)}`))}}),this._websocket.on("close",()=>{this._isClosed||(this._isClosed=!0,this.onclose?.())})}catch(s){o(new yZ(void 0,`Failed to create WebSocket: ${s}`))}})}async finishAuth(e){if(!this._authProvider)throw new Error("No auth provider configured");try{let r=await this._authProvider.clientInformation();if(r){let n=this._authProvider.redirectUrl.toString(),i=await fPe(this._url,{clientInformation:r,authorizationCode:e,codeVerifier:await this._authProvider.codeVerifier(),redirectUri:n,addClientAuthentication:this._authProvider.addClientAuthentication});await this._authProvider.saveTokens(i)}else throw new Error("Client information not available")}catch(r){throw new Error(`Failed to exchange authorization code for access token: ${r}`)}}async close(){this._isClosed=!0,this._websocket&&this._websocket.readyState===i7.default.OPEN?this._websocket.close():this.onclose?.()}async send(e){if(this._isClosed)throw new Error("Transport is closed");if(!this._websocket)throw new Error("Transport not started");if(this._websocket.readyState!==i7.default.OPEN)throw new Error("WebSocket is not open");try{if(e.method==="notifications/initialized")return;let r=await this._transformRequest(e),n=JSON.stringify(r);this._websocket.send(n)}catch(r){throw new yZ(void 0,`Failed to send message: ${r instanceof Error?r.message:String(r)}`)}}async _transformRequest(e){if(e.method==="initialize")return{type:AZ.CLI_CONNECT,id:e.id,timestamp:Date.now(),payload:{clientInfo:{version:"0.2.24",platform:process.platform,workingDirectory:process.cwd()}}};if(e.method==="tools/call"&&e.params?.name==="openDiff"){let{arguments:r}=e.params||{},{filePath:n,newContent:i}=r||{};return{type:AZ.SHOW_DIFF,id:e.id,timestamp:Date.now(),payload:{originalText:await Kxn(n,"utf8"),modifiedText:i}}}return e}async _transformResponse(e){if(e.type==="connection_ack")return{jsonrpc:"2.0",id:e.id,result:{protocolVersion:"2024-11-05",capabilities:{logging:{},prompts:{},resources:{},tools:{}},serverInfo:{name:"JetBrains Plugin Server",title:"JetBrains Plugin Server",version:"1.0.0"}}};if(e.type==="selection_changed"){let r=await this._getSelectedText();return{jsonrpc:"2.0",method:"ide/contextUpdate",params:{workspaceState:{openFiles:[{path:e.payload.fileName,timestamp:Date.now(),isActive:!0,selectedText:r}]}}}}return e.type==="active_file_changed"?{jsonrpc:"2.0",method:"ide/contextUpdate",params:{workspaceState:{openFiles:[{path:e.payload.fileName,timestamp:Date.now(),isActive:!0}]}}}:e}async _getSelectedText(){if(!this._websocket)return"";let e=performance.now();return this._specialIds.add(e),this._websocket.send(JSON.stringify({type:AZ.GET_SELECTED_TEXT,id:e,timestamp:Date.now()})),new Promise((r,n)=>{this._websocket.once("message",i=>{try{let o=JSON.parse(i.toString());Number(o.id)===e&&(this._specialIds.delete(e),o.payload.success?r(o.payload.data.text):n(o.payload.error))}catch{r("")}})})}setProtocolVersion(e){this._protocolVersion=e}}});var tOt,T0e,rOt=Ie(()=>{"use strict";tOt=Ye(TX(),1);T0e=class{config;auth;redirectUrl="";clientMetadata={client_name:"iFlow CLI (Google ADC)",redirect_uris:[],grant_types:[],response_types:[],token_endpoint_auth_method:"none"};_clientInformation;constructor(e){this.config=e;let r=this.config?.oauth?.scopes;if(!r||r.length===0)throw new Error("Scopes must be provided in the oauth config for Google Credentials provider");this.auth=new tOt.GoogleAuth({scopes:r})}clientInformation(){return this._clientInformation}saveClientInformation(e){this._clientInformation=e}async tokens(){let r=await(await this.auth.getClient()).getAccessToken();if(!r.token){console.error("Failed to get access token from Google ADC");return}return{access_token:r.token,token_type:"Bearer"}}saveTokens(e){}redirectToAuthorization(e){}saveCodeVerifier(e){}codeVerifier(){return""}}});import{execFile as Xxn}from"node:child_process";import{promisify as Zxn}from"node:util";import{platform as ewn}from"node:os";import{URL as twn}from"node:url";function rwn(t){let e;try{e=new twn(t)}catch{throw new Error(`Invalid URL: ${t}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`Unsafe protocol: ${e.protocol}. Only HTTP and HTTPS are allowed.`);if(/[\r\n\x00-\x1f]/.test(t))throw new Error("URL contains invalid characters")}async function iOt(t){rwn(t);let e=ewn(),r,n;switch(e){case"darwin":r="open",n=[t];break;case"win32":r="powershell.exe",n=["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`Start-Process '${t.replace(/'/g,"''")}'`];break;case"linux":case"freebsd":case"openbsd":r="xdg-open",n=[t];break;default:throw new Error(`Unsupported platform: ${e}`)}let i={env:{...process.env,SHELL:void 0},detached:!0,stdio:"ignore"};try{await nOt(r,n,i)}catch(o){if((e==="linux"||e==="freebsd"||e==="openbsd")&&r==="xdg-open"){let s=["gnome-open","kde-open","firefox","chromium","google-chrome"];for(let a of s)try{await nOt(a,[t],i);return}catch{continue}}throw new Error(`Failed to open browser: ${o instanceof Error?o.message:"Unknown error"}`)}}var nOt,oOt=Ie(()=>{"use strict";nOt=Zxn(Xxn)});function Bs(t){return t instanceof Error&&"code"in t}function wr(t){if(t instanceof Error)return t.message;try{return String(t)}catch{return"Failed to get error details"}}function gPe(t){if(t&&typeof t=="object"&&"response"in t){let r=nwn(t);if(r.error&&r.error.message&&r.error.code)switch(r.error.code){case 400:return new D0e(r.error.message);case 401:return new Mw(r.error.message);case 403:return new I0e(r.error.message);default:}}return t}function nwn(t){return typeof t.response?.data=="string"?JSON.parse(t.response?.data):t.response?.data}var I0e,Mw,D0e,Zu=Ie(()=>{"use strict";I0e=class extends Error{},Mw=class extends Error{},D0e=class extends Error{}});import{promises as Tq}from"node:fs";import*as R0e from"node:path";import*as sOt from"node:os";var Xh,B0e=Ie(()=>{"use strict";Zu();Xh=class{static TOKEN_FILE="mcp-oauth-tokens.json";static CONFIG_DIR=".iflow";static getTokenFilePath(){let e=sOt.homedir();return R0e.join(e,this.CONFIG_DIR,this.TOKEN_FILE)}static async ensureConfigDir(){let e=R0e.dirname(this.getTokenFilePath());await Tq.mkdir(e,{recursive:!0})}static async loadTokens(){let e=new Map;try{let r=this.getTokenFilePath(),n=await Tq.readFile(r,"utf-8"),i=JSON.parse(n);for(let o of i)e.set(o.serverName,o)}catch(r){r.code!=="ENOENT"&&console.error(`Failed to load MCP OAuth tokens: ${wr(r)}`)}return e}static async saveToken(e,r,n,i,o){await this.ensureConfigDir();let s=await this.loadTokens(),a={serverName:e,token:r,clientId:n,tokenUrl:i,mcpServerUrl:o,updatedAt:Date.now()};s.set(e,a);let c=Array.from(s.values()),u=this.getTokenFilePath();try{await Tq.writeFile(u,JSON.stringify(c,null,2),{mode:384})}catch(f){throw console.error(`Failed to save MCP OAuth token: ${wr(f)}`),f}}static async getToken(e){return(await this.loadTokens()).get(e)||null}static async removeToken(e){let r=await this.loadTokens();if(r.delete(e)){let n=Array.from(r.values()),i=this.getTokenFilePath();try{n.length===0?await Tq.unlink(i):await Tq.writeFile(i,JSON.stringify(n,null,2),{mode:384})}catch(o){console.error(`Failed to remove MCP OAuth token: ${wr(o)}`)}}}static isTokenExpired(e){if(!e.expiresAt)return!1;let r=300*1e3;return Date.now()+r>=e.expiresAt}static async clearAllTokens(){try{let e=this.getTokenFilePath();await Tq.unlink(e)}catch(e){e.code!=="ENOENT"&&console.error(`Failed to clear MCP OAuth tokens: ${wr(e)}`)}}}});var Zh,N0e=Ie(()=>{"use strict";Zu();Zh=class{static buildWellKnownUrls(e){let r=new URL(e),n=`${r.protocol}//${r.host}`;return{protectedResource:new URL("/.well-known/oauth-protected-resource",n).toString(),authorizationServer:new URL("/.well-known/oauth-authorization-server",n).toString()}}static async fetchProtectedResourceMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return console.debug(`Failed to fetch protected resource metadata from ${e}: ${wr(r)}`),null}}static async fetchAuthorizationServerMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return console.debug(`Failed to fetch authorization server metadata from ${e}: ${wr(r)}`),null}}static metadataToOAuthConfig(e){return{authorizationUrl:e.authorization_endpoint,tokenUrl:e.token_endpoint,scopes:e.scopes_supported||[]}}static async discoverOAuthConfig(e){try{let r=this.buildWellKnownUrls(e),n=await this.fetchProtectedResourceMetadata(r.protectedResource);if(n?.authorization_servers?.length){let o=n.authorization_servers[0],s=new URL("/.well-known/oauth-authorization-server",o).toString(),a=await this.fetchAuthorizationServerMetadata(s);if(a){let c=this.metadataToOAuthConfig(a);return a.registration_endpoint&&console.log("Dynamic client registration is supported at:",a.registration_endpoint),c}}console.debug(`Trying OAuth discovery fallback at ${r.authorizationServer}`);let i=await this.fetchAuthorizationServerMetadata(r.authorizationServer);if(i){let o=this.metadataToOAuthConfig(i);return i.registration_endpoint&&console.log("Dynamic client registration is supported at:",i.registration_endpoint),o}return null}catch(r){return console.debug(`Failed to discover OAuth configuration: ${wr(r)}`),null}}static parseWWWAuthenticateHeader(e){let r=e.match(/resource_metadata="([^"]+)"/);return r?r[1]:null}static async discoverOAuthFromWWWAuthenticate(e){let r=this.parseWWWAuthenticateHeader(e);if(!r)return null;console.log(`Found resource metadata URI from www-authenticate header: ${r}`);let n=await this.fetchProtectedResourceMetadata(r);if(!n?.authorization_servers?.length)return null;let i=n.authorization_servers[0],o=new URL("/.well-known/oauth-authorization-server",i).toString(),s=await this.fetchAuthorizationServerMetadata(o);return s?(console.log("OAuth configuration discovered successfully from www-authenticate header"),this.metadataToOAuthConfig(s)):null}static extractBaseUrl(e){let r=new URL(e);return`${r.protocol}//${r.host}`}static isSSEEndpoint(e){return e.includes("/sse")||!e.includes("/mcp")}static buildResourceParameter(e){let r=new URL(e);return`${r.protocol}//${r.host}`}}});import*as aOt from"node:http";import*as EZ from"node:crypto";import{URL as APe}from"node:url";var w3,yPe=Ie(()=>{"use strict";oOt();B0e();Zu();N0e();w3=class{static REDIRECT_PORT=7777;static REDIRECT_PATH="/oauth/callback";static HTTP_OK=200;static HTTP_REDIRECT=302;static async registerClient(e,r){let i={client_name:"iFlow CLI MCP Client",redirect_uris:[r.redirectUri||`http://localhost:${this.REDIRECT_PORT}${this.REDIRECT_PATH}`],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none",code_challenge_method:["S256"],scope:r.scopes?.join(" ")||""},o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!o.ok){let s=await o.text();throw new Error(`Client registration failed: ${o.status} ${o.statusText} - ${s}`)}return await o.json()}static async discoverOAuthFromMCPServer(e){let r=Zh.extractBaseUrl(e);return Zh.discoverOAuthConfig(r)}static generatePKCEParams(){let e=EZ.randomBytes(32).toString("base64url"),r=EZ.createHash("sha256").update(e).digest("base64url"),n=EZ.randomBytes(16).toString("base64url");return{codeVerifier:e,codeChallenge:r,state:n}}static async startCallbackServer(e){return new Promise((r,n)=>{let i=aOt.createServer(async(o,s)=>{try{let a=new APe(o.url,`http://localhost:${this.REDIRECT_PORT}`);if(a.pathname!==this.REDIRECT_PATH){s.writeHead(404),s.end("Not found");return}let c=a.searchParams.get("code"),u=a.searchParams.get("state"),f=a.searchParams.get("error");if(f){s.writeHead(this.HTTP_OK,{"Content-Type":"text/html"}),s.end(`
|
|
421
421
|
<html>
|
|
422
422
|
<body>
|
|
423
423
|
<h1>Authentication Failed</h1>
|
|
@@ -3089,7 +3089,7 @@ Content from @${U}:
|
|
|
3089
3089
|
`,e-1);return{line:r===-1?0:t.slice(0,r+1).match(/\n/g).length,column:e-r-1}}function W1t(t,e,{oneBased:r=!1}={}){if(typeof t!="string")throw new TypeError("Text parameter should be a string");if(!Number.isInteger(e))throw new TypeError("Index parameter should be an integer");if(e<0||e>t.length)throw new RangeError("Index out of bounds");let n=Hso(t,e);return r?{line:n.line+1,column:n.column+1}:n}var Gso=t=>`\\u{${t.codePointAt(0).toString(16)}}`,j1t=class t extends Error{name="JSONError";fileName;#e;#t;#r;#n;#o;constructor(e){if(typeof e=="string")super(),this.#r=e;else{let{jsonParseError:r,fileName:n,input:i}=e;super(void 0,{cause:r}),this.#e=i,this.#t=r,this.fileName=n}Error.captureStackTrace?.(this,t)}get message(){this.#r??=`${$so(this.#t.message)}${this.#e===""?" while parsing empty string":""}`;let{codeFrame:e}=this;return`${this.#r}${this.fileName?` in ${this.fileName}`:""}${e?`
|
|
3090
3090
|
|
|
3091
3091
|
${e}
|
|
3092
|
-
`:""}`}set message(e){this.#r=e}#i(e){if(!this.#t)return;let r=this.#e,n=Vso(r,this.#t.message);if(n)return(0,sjr.codeFrameColumns)(r,{start:n},{highlightCode:e})}get codeFrame(){return this.#n??=this.#i(!0),this.#n}get rawCodeFrame(){return this.#o??=this.#i(!1),this.#o}},Vso=(t,e)=>{let r=e.match(/in JSON at position (?<index>\d+)(?: \(line (?<line>\d+) column (?<column>\d+)\))?$/);if(!r)return;let{index:n,line:i,column:o}=r.groups;return i&&o?{line:Number(i),column:Number(o)}:W1t(t,Number(n),{oneBased:!0})},$so=t=>t.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(e,r,n)=>`"${n}"(${Gso(n)})`);function z1t(t,e,r){typeof e=="string"&&(r=e,e=void 0);try{return JSON.parse(t,e)}catch(n){throw new j1t({jsonParseError:n,fileName:r,input:t})}}var nzr=Ye(tzr(),1);import{fileURLToPath as Gao}from"node:url";function rzr(t){return t instanceof URL?Gao(t):t}var Wao=t=>$ao.resolve(rzr(t)??".","package.json"),jao=(t,e)=>{let r=typeof t=="string"?z1t(t):t;return e&&(0,nzr.default)(r),r};async function izr({cwd:t,normalize:e=!0}={}){let r=await Vao.readFile(Wao(t),"utf8");return jao(r,e)}async function ozr(t){let e=await kWr("package.json",t);if(e)return{packageJson:await izr({...t,cwd:zao.dirname(e)}),path:e}}import{fileURLToPath as Yao}from"url";import Jao from"path";var Kao=Yao(import.meta.url),Xao=Jao.dirname(Kao),Wxe;async function SY(){if(Wxe)return Wxe;let t=await ozr({cwd:Xao});if(t)return Wxe=t.packageJson,Wxe}async function LD(){let t=await SY();return"0.2.24
|
|
3092
|
+
`:""}`}set message(e){this.#r=e}#i(e){if(!this.#t)return;let r=this.#e,n=Vso(r,this.#t.message);if(n)return(0,sjr.codeFrameColumns)(r,{start:n},{highlightCode:e})}get codeFrame(){return this.#n??=this.#i(!0),this.#n}get rawCodeFrame(){return this.#o??=this.#i(!1),this.#o}},Vso=(t,e)=>{let r=e.match(/in JSON at position (?<index>\d+)(?: \(line (?<line>\d+) column (?<column>\d+)\))?$/);if(!r)return;let{index:n,line:i,column:o}=r.groups;return i&&o?{line:Number(i),column:Number(o)}:W1t(t,Number(n),{oneBased:!0})},$so=t=>t.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(e,r,n)=>`"${n}"(${Gso(n)})`);function z1t(t,e,r){typeof e=="string"&&(r=e,e=void 0);try{return JSON.parse(t,e)}catch(n){throw new j1t({jsonParseError:n,fileName:r,input:t})}}var nzr=Ye(tzr(),1);import{fileURLToPath as Gao}from"node:url";function rzr(t){return t instanceof URL?Gao(t):t}var Wao=t=>$ao.resolve(rzr(t)??".","package.json"),jao=(t,e)=>{let r=typeof t=="string"?z1t(t):t;return e&&(0,nzr.default)(r),r};async function izr({cwd:t,normalize:e=!0}={}){let r=await Vao.readFile(Wao(t),"utf8");return jao(r,e)}async function ozr(t){let e=await kWr("package.json",t);if(e)return{packageJson:await izr({...t,cwd:zao.dirname(e)}),path:e}}import{fileURLToPath as Yao}from"url";import Jao from"path";var Kao=Yao(import.meta.url),Xao=Jao.dirname(Kao),Wxe;async function SY(){if(Wxe)return Wxe;let t=await ozr({cwd:Xao});if(t)return Wxe=t.packageJson,Wxe}async function LD(){let t=await SY();return"0.2.24"}import CP from"node:process";var szr={name:"about",description:"show version info",kind:"built-in",action:async t=>{let e=CP.platform,r="no sandbox";CP.env.SANDBOX&&CP.env.SANDBOX!=="sandbox-exec"?r=CP.env.SANDBOX:CP.env.SANDBOX==="sandbox-exec"&&(r=`sandbox-exec (${CP.env.SEATBELT_PROFILE||"unknown"})`);let n=t.services.config?.getModel()||"Unknown",i=await LD(),o=t.services.settings.merged.selectedAuthType||"",s=CP.env.GOOGLE_CLOUD_PROJECT||"",a={type:"about",cliVersion:i,osVersion:e,sandboxEnv:r,modelVersion:n,selectedAuthType:o,gcpProject:s};t.ui.addItem(a,Date.now())}};sn();var zxe="\x1B[32m";var lzr="\x1B[31m",bv="\x1B[36m",Mm="\x1B[90m";var Ra="\x1B[0m";function jxe(t,e,r,n=!1){let i="";if(t.length===0)return i="\u{1F534} ",`${i}${e}
|
|
3093
3093
|
${lzr}No agents found${Ra}
|
|
3094
3094
|
`;i="\u{1F7E2} ";let o=`${i}${e}
|
|
3095
3095
|
`;for(let s of t)n?o+=Zao(s):o+=`${zxe}- ${s.agentType}${Ra}
|
|
@@ -3132,7 +3132,7 @@ ${Mm}Built-in agents (always available)${Ra}
|
|
|
3132
3132
|
${Mm}- general-purpose
|
|
3133
3133
|
${Ra}`;let c=n.length+i.length;t.ui.addItem({type:"info",text:`${zxe}Agents refreshed successfully. Found ${c} agents.${Ra}
|
|
3134
3134
|
|
|
3135
|
-
${zxe}${a.trim()}${Ra}`},Date.now())}catch(e){let r=wr(e);t.ui.addItem({type:"error",text:`${lzr}Error refreshing agents: ${r}${Ra}`},Date.now())}}},{name:"online",description:"Browse and install agents from online repository",kind:"built-in",action:(t,e)=>({type:"dialog",dialog:"agents-online"})},{name:"install",description:"Install a new agent with guided setup",kind:"built-in",action:(t,e)=>({type:"dialog",dialog:"agent-install"})}]};var uzr={name:"auth",description:"change the auth method",kind:"built-in",action:(t,e)=>({type:"dialog",dialog:"auth"})};JQ();import qS from"node:process";import elo from"node:os";var xY="
|
|
3135
|
+
${zxe}${a.trim()}${Ra}`},Date.now())}catch(e){let r=wr(e);t.ui.addItem({type:"error",text:`${lzr}Error refreshing agents: ${r}${Ra}`},Date.now())}}},{name:"online",description:"Browse and install agents from online repository",kind:"built-in",action:(t,e)=>({type:"dialog",dialog:"agents-online"})},{name:"install",description:"Install a new agent with guided setup",kind:"built-in",action:(t,e)=>({type:"dialog",dialog:"agent-install"})}]};var uzr={name:"auth",description:"change the auth method",kind:"built-in",action:(t,e)=>({type:"dialog",dialog:"auth"})};JQ();import qS from"node:process";import elo from"node:os";var xY="3f5fdbbe (local modifications)";sn();async function tlo(t,e){let r="https://apis.iflow.cn/v1/bug/report",i={content:JSON.stringify(t,null,2)},o={"Content-Type":"application/json"};e&&(o.Authorization=`Bearer ${e}`);try{let s=await fetch(r,{method:"POST",headers:o,body:JSON.stringify(i)});if(s.ok){let a=await s.json();return console.log("Bug report data sent successfully to endpoint"),a.success&&a.data?a.data:(console.warn("Unexpected response format from endpoint:",a),null)}else return console.warn(`Failed to send bug report to endpoint: ${s.status} ${s.statusText}`),null}catch(s){return console.warn("Failed to send bug report to endpoint:",s),null}}var fzr={name:"bug",description:"submit a bug report",kind:"built-in",action:async(t,e)=>{let r=(e||"").trim(),{config:n}=t.services,i=QB(),o=`${qS.platform} ${qS.version}`,s="no sandbox";qS.env.SANDBOX&&qS.env.SANDBOX!=="sandbox-exec"?s=qS.env.SANDBOX.replace(/^iflow-(?:code-)?/,""):qS.env.SANDBOX==="sandbox-exec"&&(s=`sandbox-exec (${qS.env.SEATBELT_PROFILE||"unknown"})`);let a=n?.getModel()||"Unknown",c=await LD(),u=hY(qS.memoryUsage().rss),f=i.getInMemoryErrors(),d="No recent errors";f.length>0&&(d=f.slice(-3).map(P=>`Error (${P.timestamp}):
|
|
3136
3136
|
${P.error}`).join(`
|
|
3137
3137
|
|
|
3138
3138
|
`));let p=elo.userInfo().username,h=B=>{if(!p)return B;let P=new RegExp(`/${p}/`,"g");return B.replace(P,"/user/")},g=`CLI Version: ${c}
|
|
@@ -3978,14 +3978,14 @@ ${Yin}
|
|
|
3978
3978
|
Run `+p1.cyan("{updateCommand}")+" to update",o=e.message||i;e.boxenOptions??={padding:1,margin:1,textAlignment:"center",borderColor:"yellow",borderStyle:"round"};let s=WIe(N4t(o,{packageName:this._packageName,currentVersion:this.update.current,latestVersion:this.update.latest,updateCommand:n}),e.boxenOptions);return e.defer===!1?console.error(s):gL.on("exit",()=>{console.error(s)}),this}};function M4t(t){let e=new Mue(t);return e.check(),e}var AL=Ye(Oz(),1);function K1o(t,e){if(!t)return e||null;if(!e)return t||null;let r=t.latest,n=e.latest;return AL.default.coerce(n)?.version===AL.default.coerce(r)?.version?t:AL.default.gt(n,r)?e:t}async function qan(){try{if(process.env.DEV==="true")return null;let t=await SY();if(!t||!t.name||!t.version)return null;let{name:e,version:r}=t,n=s=>M4t({pkg:{name:e,version:r},updateCheckInterval:0,shouldNotifyInNpmScript:!0,distTag:s}),i=r.includes("nightly"),o=r.includes("beta");if(i){let[s,a]=await Promise.all([n("nightly").fetchInfo(),n("latest").fetchInfo()]),c=K1o(s,a);if(c&&AL.default.gt(c.latest,r))return{message:`A new version of iFlow CLI is available! ${r} \u2192 ${c.latest}`,update:{...c,current:r}}}else if(o){let s=await n("beta").fetchInfo();if(s&&AL.default.gt(s.latest,r))return{message:`iFlow CLI beta update available! ${r} \u2192 ${s.latest}`,update:{...s,current:r}}}else{let s=await n("latest").fetchInfo();if(s&&AL.default.gt(s.latest,r))return{message:`iFlow CLI update available! ${r} \u2192 ${s.latest}`,update:{...s,current:r}}}return null}catch(t){return console.warn("Failed to check for updates: "+t),null}}VU();import NAo from"http";Pf();xw();import{EOL as TAo}from"node:os";xw();var yL={authenticate:"authenticate",initialize:"initialize",session_cancel:"session/cancel",session_load:"session/load",session_new:"session/new",session_prompt:"session/prompt"},Pue={fs_read_text_file:"fs/read_text_file",fs_write_text_file:"fs/write_text_file",session_request_permission:"session/request_permission",session_update:"session/update"},Han=1,X1o=fe.object({content:fe.string(),path:fe.string(),sessionId:fe.string()}),Z1o=fe.object({limit:fe.number().optional().nullable(),line:fe.number().optional().nullable(),path:fe.string(),sessionId:fe.string()}),eAo=fe.union([fe.literal("allow_once"),fe.literal("allow_always"),fe.literal("reject_once"),fe.literal("reject_always")]),tAo=fe.union([fe.literal("assistant"),fe.literal("user")]),rAo=fe.object({mimeType:fe.string().optional().nullable(),text:fe.string(),uri:fe.string()}),nAo=fe.object({blob:fe.string(),mimeType:fe.string().optional().nullable(),uri:fe.string()}),k4t=fe.union([fe.literal("read"),fe.literal("edit"),fe.literal("delete"),fe.literal("move"),fe.literal("search"),fe.literal("execute"),fe.literal("think"),fe.literal("fetch"),fe.literal("other")]),F4t=fe.union([fe.literal("pending"),fe.literal("in_progress"),fe.literal("completed"),fe.literal("failed")]),iAo=fe.null(),oAo=fe.object({content:fe.string()}),sAo=fe.union([fe.object({outcome:fe.literal("cancelled")}),fe.object({optionId:fe.string(),outcome:fe.literal("selected")})]),Gan=fe.object({sessionId:fe.string()}),U4t=fe.object({methodId:fe.string()}),aAo=fe.object({methodId:fe.string()}),lAo=fe.object({sessionId:fe.string()}),cAo=fe.null(),uAo=fe.union([fe.literal("end_turn"),fe.literal("max_tokens"),fe.literal("refusal"),fe.literal("cancelled")]),fAo=fe.object({stopReason:uAo}),P4t=fe.object({line:fe.number().optional().nullable(),path:fe.string()}),dAo=fe.object({content:fe.string(),priority:fe.union([fe.literal("high"),fe.literal("medium"),fe.literal("low")]),status:fe.union([fe.literal("pending"),fe.literal("in_progress"),fe.literal("completed")])}),pAo=fe.object({kind:eAo,name:fe.string(),optionId:fe.string()}),kue=fe.object({audience:fe.array(tAo).optional().nullable(),lastModified:fe.string().optional().nullable(),priority:fe.number().optional().nullable()}),hAo=fe.object({outcome:sAo}),mAo=fe.object({readTextFile:fe.boolean(),writeTextFile:fe.boolean()}),gAo=fe.object({name:fe.string(),value:fe.string()}),Van=fe.object({args:fe.array(fe.string()),command:fe.string(),env:fe.array(gAo),name:fe.string()}),AAo=fe.object({audio:fe.boolean().optional(),embeddedContext:fe.boolean().optional(),image:fe.boolean().optional()}),yAo=fe.object({loadSession:fe.boolean().optional(),promptCapabilities:AAo.optional()}),EAo=fe.object({description:fe.string().nullable(),id:fe.string(),name:fe.string()}),Ozs=fe.union([iAo,oAo,hAo]);var vAo=fe.union([rAo,nAo]),Q4t=fe.object({cwd:fe.string(),mcpServers:fe.array(Van)}),q4t=fe.object({cwd:fe.string(),mcpServers:fe.array(Van),sessionId:fe.string()}),CAo=fe.object({agentCapabilities:yAo,authMethods:fe.array(EAo),protocolVersion:fe.number()}),Fue=fe.union([fe.object({annotations:kue.optional().nullable(),text:fe.string(),type:fe.literal("text")}),fe.object({annotations:kue.optional().nullable(),data:fe.string(),mimeType:fe.string(),type:fe.literal("image")}),fe.object({annotations:kue.optional().nullable(),data:fe.string(),mimeType:fe.string(),type:fe.literal("audio")}),fe.object({annotations:kue.optional().nullable(),description:fe.string().optional().nullable(),mimeType:fe.string().optional().nullable(),name:fe.string(),size:fe.number().optional().nullable(),title:fe.string().optional().nullable(),type:fe.literal("resource_link"),uri:fe.string()}),fe.object({annotations:kue.optional().nullable(),resource:vAo,type:fe.literal("resource")})]),L4t=fe.union([fe.object({content:Fue,type:fe.literal("content"),args:fe.record(fe.unknown()).optional()}),fe.object({newText:fe.string(),oldText:fe.string().nullable(),path:fe.string(),type:fe.literal("diff"),args:fe.record(fe.unknown()).optional()})]),bAo=fe.object({content:fe.array(L4t).optional(),kind:k4t,locations:fe.array(P4t).optional(),rawInput:fe.unknown().optional(),status:F4t,title:fe.string(),toolCallId:fe.string()}),_Ao=fe.object({fs:mAo}),H4t=fe.object({prompt:fe.array(Fue),sessionId:fe.string()}),SAo=fe.union([fe.object({content:Fue,sessionUpdate:fe.literal("user_message_chunk")}),fe.object({content:Fue,sessionUpdate:fe.literal("agent_message_chunk"),agentId:fe.string().optional()}),fe.object({content:Fue,sessionUpdate:fe.literal("agent_thought_chunk"),agentId:fe.string().optional()}),fe.object({content:fe.array(L4t).optional(),kind:k4t,locations:fe.array(P4t).optional(),rawInput:fe.unknown().optional(),sessionUpdate:fe.literal("tool_call"),status:F4t,title:fe.string(),toolCallId:fe.string(),agentId:fe.string().optional()}),fe.object({content:fe.array(L4t).optional().nullable(),kind:k4t.optional().nullable(),locations:fe.array(P4t).optional().nullable(),rawInput:fe.unknown().optional(),sessionUpdate:fe.literal("tool_call_update"),status:F4t.optional().nullable(),title:fe.string().optional().nullable(),toolCallId:fe.string(),agentId:fe.string().optional()}),fe.object({entries:fe.array(dAo),sessionUpdate:fe.literal("plan")})]),Mzs=fe.union([CAo,aAo,lAo,cAo,fAo]),xAo=fe.object({options:fe.array(pAo),sessionId:fe.string(),toolCall:bAo}),G4t=fe.object({clientCapabilities:_Ao,protocolVersion:fe.number()}),kzs=fe.object({sessionId:fe.string(),update:SAo}),Fzs=fe.union([X1o,Z1o,xAo]),Pzs=fe.union([G4t,U4t,Q4t,q4t,H4t]);var OJ=class{#e;constructor(e,r,n){let i=e(this),o=async(s,a)=>{switch(s){case yL.initialize:{let c=G4t.parse(a);return i.initialize(c)}case yL.session_new:{let c=Q4t.parse(a);return i.newSession(c)}case yL.session_load:{if(!i.loadSession)throw a9.methodNotFound();let c=q4t.parse(a);return i.loadSession(c)}case yL.authenticate:{let c=U4t.parse(a);return i.authenticate(c)}case yL.session_prompt:{let c=H4t.parse(a);return i.prompt(c)}case yL.session_cancel:{let c=Gan.parse(a);return i.cancel(c)}default:throw a9.methodNotFound(s)}};this.#e=new V4t(o,r,n)}async sessionUpdate(e){return await this.#e.sendNotification(Pue.session_update,e)}async requestPermission(e){return await this.#e.sendRequest(Pue.session_request_permission,e)}async readTextFile(e){return await this.#e.sendRequest(Pue.fs_read_text_file,e)}async writeTextFile(e){return await this.#e.sendRequest(Pue.fs_write_text_file,e)}},V4t=class{#e=new Map;#t=0;#r;#n;#o=Promise.resolve();#i;constructor(e,r,n){this.#r=e,this.#n=r,this.#i=new TextEncoder,this.#c(n)}async#c(e){let r="",n=new TextDecoder;for await(let i of e){r+=n.decode(i,{stream:!0});let o=r.split(TAo);r=o.pop()||"";for(let s of o){let a=s.trim();if(a){let c=JSON.parse(a);this.#s(c)}}}}async#s(e){if("method"in e&&"id"in e){let r=await this.#a(e.method,e.params);await this.#l({jsonrpc:"2.0",id:e.id,...r})}else"method"in e?await this.#a(e.method,e.params):"id"in e&&this.#u(e)}async#a(e,r){try{return{result:await this.#r(e,r)??null}}catch(n){if(n instanceof a9)return n.toResult();if(n instanceof fe.ZodError)return a9.invalidParams(JSON.stringify(n.format(),void 0,2)).toResult();let i;return(n instanceof Error||typeof n=="object"&&n!=null&&"message"in n&&typeof n.message=="string")&&(i=n.message),a9.internalError(i).toResult()}}#u(e){let r=this.#e.get(e.id);r&&("result"in e?r.resolve(e.result):"error"in e&&r.reject(e.error),this.#e.delete(e.id))}async sendRequest(e,r){let n=this.#t++,i=new Promise((o,s)=>{this.#e.set(n,{resolve:o,reject:s})});return await this.#l({jsonrpc:"2.0",id:n,method:e,params:r}),i}async sendNotification(e,r){await this.#l({jsonrpc:"2.0",method:e,params:r})}async#l(e){let r=JSON.stringify(e)+`
|
|
3979
3979
|
`;return this.#o=this.#o.then(async()=>{let n=this.#n.getWriter();try{await n.write(this.#i.encode(r))}finally{n.releaseLock()}}).catch(n=>{console.error("ACP write error:",n)}),this.#o}},a9=class t extends Error{constructor(r,n,i){super(n);this.code=r;this.name="RequestError",i&&(this.data={details:i})}data;static parseError(r){return new t(-32700,"Parse error",r)}static invalidRequest(r){return new t(-32600,"Invalid request",r)}static methodNotFound(r){return new t(-32601,"Method not found",r)}static invalidParams(r){return new t(-32602,"Invalid params",r)}static internalError(r){return new t(-32603,"Internal error",r)}static authRequired(r){return new t(-32e3,"Authentication required",r)}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}};sn();var jIe=class{constructor(e,r,n,i){this.client=e;this.sessionId=r;this.capabilities=n;this.fallback=i}async readTextFile(e){return this.capabilities.readTextFile?(await this.client.readTextFile({path:e,sessionId:this.sessionId,line:null,limit:null})).content:this.fallback.readTextFile(e)}async writeTextFile(e,r){if(!this.capabilities.writeTextFile)return this.fallback.writeTextFile(e,r);await this.client.writeTextFile({path:e,content:r,sessionId:this.sessionId})}};Pf();xw();import{Readable as IAo,Writable as DAo}from"node:stream";import*as zan from"node:fs/promises";import*as JIe from"node:path";import{randomUUID as RAo}from"node:crypto";sn();sn();var zIe=class{constructor(e,r,n){this.client=e;this.eventEmitter=r;n&&(this.sessionId=n)}toolCallIdMap=new Map;agentIdMap=new Map;pendingToolCalls=new Map;eventUnsubscriber;isEnabled=!1;sessionId="default-session";enable(){this.isEnabled||(this.isEnabled=!0,this.eventUnsubscriber=this.eventEmitter.on(this.handleSubAgentEvent.bind(this)))}disable(){this.isEnabled&&(this.isEnabled=!1,this.eventUnsubscriber&&(this.eventUnsubscriber(),this.eventUnsubscriber=void 0),this.toolCallIdMap.clear(),this.agentIdMap.clear(),this.pendingToolCalls.clear())}async handleSubAgentEvent(e){if(this.isEnabled)try{switch(e.type){case bn.TOOL_CALL_REQUESTED:await this.handleToolCallRequested(e);break;case bn.TOOL_CALL_COMPLETED:await this.handleToolCallCompleted(e);break;case bn.TOOL_CALL_FAILED:await this.handleToolCallFailed(e);break;case bn.AGENT_STARTED:case bn.AGENT_COMPLETED:case bn.AGENT_FAILED:await this.handleAgentLifecycleEvent(e);break;default:break}}catch(r){console.error("[ACP SubAgent Adapter] Error handling event:",r)}}async handleToolCallRequested(e){if(e.type!==bn.TOOL_CALL_REQUESTED)return;let r=e.data,{callId:n,toolName:i,args:o,agentId:s}=r;try{this.agentIdMap.set(s,n);let a=this.client.sessionUpdate({sessionId:this.sessionId,update:{sessionUpdate:"tool_call",toolCallId:n,title:this.formatToolLabel(i,o),kind:this.getToolKind(i),status:"pending",locations:this.getToolLocations(i,o),agentId:s}}).then(()=>(this.toolCallIdMap.set(n,n),this.pendingToolCalls.delete(n),console.log(`[ACP Adapter] Tool call requested: ${i} (${n})`),n));this.pendingToolCalls.set(n,a),await a}catch(a){console.error(`[ACP Adapter] Failed to push tool call for ${i}:`,a),this.agentIdMap.delete(s),this.pendingToolCalls.delete(n)}}async findACPToolCallId(e,r){let n=this.toolCallIdMap.get(e);if(!n){let i=this.pendingToolCalls.get(e);if(i)try{n=await i}catch{console.warn(`[ACP Adapter] Failed to wait for pending tool call ID: ${e}`)}}if(!n){let i=this.agentIdMap.get(r);if(i&&(n=this.toolCallIdMap.get(i),!n)){let o=this.pendingToolCalls.get(i);if(o)try{n=await o}catch{console.warn(`[ACP Adapter] Failed to wait for pending tool call ID: ${i}`)}}}return n}async handleToolCallCompleted(e){if(e.type!==bn.TOOL_CALL_COMPLETED)return;let r=e.data,{callId:n,toolName:i,returnDisplay:o,duration:s,args:a}=r,c=await this.findACPToolCallId(n,e.agentId);if(!c){console.warn(`[ACP Adapter] No ACP tool call ID found for ${n}`);return}try{let u=this.formatToolResult(o,a);await this.client.sessionUpdate({sessionId:this.sessionId,update:{sessionUpdate:"tool_call_update",toolCallId:c,title:this.formatToolLabel(i,a),kind:this.getToolKind(i),status:"completed",content:[u],agentId:e.agentId}}),this.toolCallIdMap.delete(String(c)),console.log(`[ACP Adapter] Tool call completed: ${i} (${n}) in ${s||0}ms`)}catch(u){console.error(`[ACP Adapter] Failed to update completed tool call for ${i}:`,u)}}async handleToolCallFailed(e){if(e.type!==bn.TOOL_CALL_FAILED)return;let r=e.data,{callId:n,toolName:i,error:o,duration:s,args:a}=r,c=await this.findACPToolCallId(n,e.agentId);if(!c){console.warn(`[ACP Adapter] No ACP tool call ID found for ${n}`);return}try{await this.client.sessionUpdate({sessionId:this.sessionId,update:{sessionUpdate:"tool_call_update",toolCallId:c,title:this.formatToolLabel(i,a),kind:this.getToolKind(i),status:"failed",content:[{type:"content",content:{type:"text",text:`Error executing ${i}: ${o}`},args:a}],agentId:e.agentId}}),this.toolCallIdMap.delete(String(c)),console.log(`[ACP Adapter] Tool call failed: ${i} (${n}) after ${s||0}ms - ${o}`)}catch(u){console.error(`[ACP Adapter] Failed to update failed tool call for ${i}:`,u)}}getToolKind(e){return{read_file:"read",write_file:"edit",replace:"edit",multi_edit:"edit",run_shell_command:"execute",search_file_content:"search",glob:"search",list_directory:"read",web_fetch:"fetch",web_search:"search",google_web_search:"search",todo_write:"edit",todo_read:"read",task:"think",read_many_files:"read"}[e]||"other"}formatToolLabel(e,r){switch(e){case"read_file":return`Reading ${r.file_path||r.absolute_path||"file"}`;case"write_file":return`Writing ${r.file_path||r.absolute_path||"file"}`;case"replace":case"multi_edit":return`Editing ${r.file_path||r.absolute_path||"file"}`;case"run_shell_command":return`Running: ${typeof r.command=="string"?r.command.slice(0,50):"command"}`;case"search_file_content":return`Searching for "${r.pattern||"pattern"}"`;case"glob":return`Finding files: ${r.pattern||"pattern"}`;case"list_directory":return`Listing ${r.path||"directory"}`;case"web_fetch":return`Fetching ${r.url||"URL"}`;case"web_search":case"google_web_search":return`Searching: ${r.query||"query"}`;case"todo_write":return"Updating todos";case"todo_read":return"Reading todos";case"task":return`Task: ${r.description||"SubAgent task"}`;case"read_many_files":return`Reading multiple files: ${Array.isArray(r.paths)?r.paths.length:0} paths`;default:return`${e} tool`}}getToolLocations(e,r){if(r.file_path&&typeof r.file_path=="string")return[{path:r.file_path,line:typeof r.line_number=="number"?r.line_number:null}];if(r.path&&typeof r.path=="string")return[{path:r.path,line:null}]}formatToolResult(e,r){if(!e)return{type:"content",content:{type:"text",text:""},args:r};if(e&&typeof e=="object"&&"functionResponse"in e){let n=e;if(n.functionResponse?.response){let{output:i}=n.functionResponse.response;if(typeof i=="string")try{let o=JSON.parse(i);return{type:"content",content:{type:"text",text:"```json\n"+JSON.stringify(o,null,2)+"\n```"},args:r}}catch{return{type:"content",content:{type:"text",text:i},args:r}}if(typeof i=="object")return{type:"content",content:{type:"text",text:"```json\n"+JSON.stringify(i,null,2)+"\n```"},args:r}}}if(typeof e=="string")return{type:"content",content:{type:"text",text:e},args:r};if(e&&typeof e=="object"&&"fileDiff"in e&&"fileName"in e){let n=e;return{type:"diff",path:n.fileName,oldText:n.originalContent||null,newText:n.newContent||"",args:r}}try{return{type:"content",content:{type:"text",text:"```json\n"+JSON.stringify(e,null,2)+"\n```"},args:r}}catch{return{type:"content",content:{type:"text",text:String(e)},args:r}}}getActiveToolCallCount(){return this.toolCallIdMap.size}isAdapterEnabled(){return this.isEnabled}async handleAgentLifecycleEvent(e){let r=e.sessionConfig?.agentType||"unknown",n="";switch(e.type){case bn.AGENT_STARTED:n=`\u25B6\uFE0F ${r} Agent started`;break;case bn.AGENT_COMPLETED:n=`\u2705 ${r} Agent completed`;break;case bn.AGENT_FAILED:n=`\u274C ${r} Agent failed`;break;default:n=`\u26A0\uFE0F Unknown agent lifecycle event: ${e.type}`}if(n)try{await this.client.sessionUpdate({sessionId:this.sessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
3980
3980
|
${n}
|
|
3981
|
-
`},agentId:e.agentId}})}catch(i){console.warn("[ACP Adapter] Failed to stream agent lifecycle event:",i)}}};var $4t=class{createAdapter(e,r){return new zIe(e,r)}};function Wan(){Rb.register(new $4t)}async function Yan(t,e,r,n){Wan(),console.error("[iFlow ACP Agent] ACP adapter factory initialized");let i=DAo.toWeb(process.stdout),o=IAo.toWeb(process.stdin);console.log=console.error,console.info=console.error,console.debug=console.error,new OJ(s=>new Lue(t,e,r,n,s),i,o)}var Lue=class{constructor(e,r,n,i,o){this.config=e;this.settings=r;this.extensions=n;this.argv=i;this.client=o;this.setupTaskToolACPIntegration()}sessions=new Map;clientCapabilities;async setupTaskToolACPIntegration(){try{if(!this.config){console.error("[iFlow ACP Agent] Config not available for TaskTool ACP integration");return}let e=await this.config.getToolRegistry();if(!e){console.error("[iFlow ACP Agent] Tool registry not available for TaskTool ACP integration");return}let r=e.getTool("task");r&&"setACPClient"in r&&typeof r.setACPClient=="function"?(r.setACPClient(this.client),console.error("[iFlow ACP Agent] TaskTool ACP integration enabled successfully")):console.error("[iFlow ACP Agent] TaskTool not found or does not support ACP integration")}catch(e){console.error("[iFlow ACP Agent] Failed to setup TaskTool ACP integration:",e)}}async initialize(e){this.clientCapabilities=e.clientCapabilities;let r=[{id:Ar.LOGIN_WITH_IFLOW,name:"Log in with IFLOW",description:null},{id:Ar.IFLOW,name:"Use iFlow API key",description:"Requires setting the `IFLOW_API_KEY` environment variable"},{id:Ar.OPENAI_COMPATIBLE,name:"OpenAI Compatible API",description:"OpenAI Compatible API"}];return{protocolVersion:Han,authMethods:r,agentCapabilities:{loadSession:!1,promptCapabilities:{image:!0,audio:!0,embeddedContext:!0}}}}async authenticate({methodId:e}){let r=fe.nativeEnum(Ar).parse(e);return v7(),await this.config.refreshAuth(r),await this.settings.setValue("User","selectedAuthType",r),{methodId:r}}async newSession({cwd:e,mcpServers:r}){let n=RAo(),i=await this.newSessionConfig(n,e,r),o=!1;if(this.settings.merged.selectedAuthType)try{await i.refreshAuth(this.settings.merged.selectedAuthType,{apiKey:this.settings.merged.apiKey,baseUrl:this.settings.merged.baseUrl,modelName:this.settings.merged.modelName}),o=!0}catch(u){console.error(`Authentication failed: ${u}`)}if(!o)throw a9.authRequired();if(this.clientCapabilities?.fs){let u=new jIe(this.client,n,this.clientCapabilities.fs,i.getFileSystemService());i.setFileSystemService(u)}let a=await i.getGeminiClient().startChat(),c=new W4t(n,a,i,this.client);return this.sessions.set(n,c),{sessionId:n}}async newSessionConfig(e,r,n){let i={...this.settings.merged.mcpServers};for(let{command:a,args:c,env:u,name:f}of n){let d={};for(let{name:p,value:h}of u)d[p]=h;i[f]=new sce(a,c,d,r)}let o={...this.settings.merged,mcpServers:i},s=await WP(o,this.extensions,e,this.argv);return await s.initialize(),s}async cancel(e){let r=this.sessions.get(e.sessionId);if(!r)throw new Error(`Session not found: ${e.sessionId}`);await r.cancelPendingPrompt()}async prompt(e){let r=this.sessions.get(e.sessionId);if(!r)throw new Error(`Session not found: ${e.sessionId}`);return r.prompt(e)}},W4t=class{constructor(e,r,n,i){this.id=e;this.chat=r;this.config=n;this.client=i}pendingPrompt=null;async cancelPendingPrompt(){if(!this.pendingPrompt)throw new Error("Not currently generating");this.pendingPrompt.abort(),this.pendingPrompt=null}async prompt(e){this.pendingPrompt?.abort();let r=new AbortController;this.pendingPrompt=r;let n=Math.random().toString(16).slice(2),i=this.chat,s={role:"user",parts:await this.#e(e.prompt,r.signal)};for(;s!==null;){if(r.signal.aborted)return i.addHistory(s),{stopReason:"cancelled"};let a=[];try{let c=await i.sendMessageStream({message:s?.parts??[],config:{abortSignal:r.signal}},n);s=null;for await(let u of c){if(r.signal.aborted)return{stopReason:"cancelled"};if(u.candidates&&u.candidates.length>0){let f=u.candidates[0];for(let d of f.content?.parts??[]){if(!d.text)continue;let p={type:"text",text:d.text};this.sendUpdate({sessionUpdate:d.thought?"agent_thought_chunk":"agent_message_chunk",content:p})}}u.functionCalls&&a.push(...u.functionCalls)}}catch(c){throw Dse(c)===429?new a9(429,"Rate limit exceeded. Try again later."):c}if(a.length>0){let c=[];for(let u of a){let f=await this.runTool(r.signal,n,u),d=Array.isArray(f)?f:[f];for(let p of d)typeof p=="string"?c.push({text:p}):p&&c.push(p)}s={role:"user",parts:c}}}return{stopReason:"end_turn"}}async sendUpdate(e){let r={sessionId:this.id,update:e};await this.client.sessionUpdate(r)}async runTool(e,r,n){let i=n.id??`${n.name}-${Date.now()}`,o=n.args??{},s=Date.now(),a=f=>{let d=Date.now()-s;return J5(this.config,{"event.name":"tool_call","event.timestamp":new Date().toISOString(),prompt_id:r,function_name:n.name??"",function_args:o,duration_ms:d,success:!1,error:f.message}),[{functionResponse:{id:i,name:n.name??"",response:{error:f.message}}}]};if(!n.name)return a(new Error("Missing function name"));let u=(await this.config.getToolRegistry()).getTool(n.name);if(!u)return a(new Error(`Tool "${n.name}" not found in registry.`));try{let f=await u.shouldConfirmExecute(o,e);if(f){let g=[];f.type==="edit"&&g.push({type:"diff",path:f.fileName,oldText:f.originalContent,newText:f.newContent});let A={sessionId:this.id,options:BAo(f),toolCall:{toolCallId:i,status:"pending",title:u.getDescription(o),content:g,locations:u.toolLocations(o),kind:u.kind}},y=await this.client.requestPermission(A),v=y.outcome.outcome==="cancelled"?fn.Cancel:fe.nativeEnum(fn).parse(y.outcome.optionId);switch(await f.onConfirm(v),v){case fn.Cancel:return a(new Error(`Tool "${n.name}" was canceled by the user.`));case fn.ProceedOnce:case fn.ProceedAlways:case fn.ProceedAlwaysServer:case fn.ProceedAlwaysTool:case fn.ModifyWithEditor:break;default:{let S=v;throw new Error(`Unexpected: ${S}`)}}}else await this.sendUpdate({sessionUpdate:"tool_call",toolCallId:i,status:"in_progress",title:u.getDescription(o),content:[],locations:u.toolLocations(o),kind:u.kind});let d=await u.execute(o,e),p=jan(d,o);await this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:i,status:"completed",content:p?[p]:[]})
|
|
3981
|
+
`},agentId:e.agentId}})}catch(i){console.warn("[ACP Adapter] Failed to stream agent lifecycle event:",i)}}};var $4t=class{createAdapter(e,r){return new zIe(e,r)}};function Wan(){Rb.register(new $4t)}async function Yan(t,e,r,n){Wan(),console.error("[iFlow ACP Agent] ACP adapter factory initialized");let i=DAo.toWeb(process.stdout),o=IAo.toWeb(process.stdin);console.log=console.error,console.info=console.error,console.debug=console.error,new OJ(s=>new Lue(t,e,r,n,s),i,o)}var Lue=class{constructor(e,r,n,i,o){this.config=e;this.settings=r;this.extensions=n;this.argv=i;this.client=o;this.setupTaskToolACPIntegration()}sessions=new Map;clientCapabilities;async setupTaskToolACPIntegration(){try{if(!this.config){console.error("[iFlow ACP Agent] Config not available for TaskTool ACP integration");return}let e=await this.config.getToolRegistry();if(!e){console.error("[iFlow ACP Agent] Tool registry not available for TaskTool ACP integration");return}let r=e.getTool("task");r&&"setACPClient"in r&&typeof r.setACPClient=="function"?(r.setACPClient(this.client),console.error("[iFlow ACP Agent] TaskTool ACP integration enabled successfully")):console.error("[iFlow ACP Agent] TaskTool not found or does not support ACP integration")}catch(e){console.error("[iFlow ACP Agent] Failed to setup TaskTool ACP integration:",e)}}async initialize(e){this.clientCapabilities=e.clientCapabilities;let r=[{id:Ar.LOGIN_WITH_IFLOW,name:"Log in with IFLOW",description:null},{id:Ar.IFLOW,name:"Use iFlow API key",description:"Requires setting the `IFLOW_API_KEY` environment variable"},{id:Ar.OPENAI_COMPATIBLE,name:"OpenAI Compatible API",description:"OpenAI Compatible API"}];return{protocolVersion:Han,authMethods:r,agentCapabilities:{loadSession:!1,promptCapabilities:{image:!0,audio:!0,embeddedContext:!0}}}}async authenticate({methodId:e}){let r=fe.nativeEnum(Ar).parse(e);return v7(),await this.config.refreshAuth(r),await this.settings.setValue("User","selectedAuthType",r),{methodId:r}}async newSession({cwd:e,mcpServers:r}){let n=RAo(),i=await this.newSessionConfig(n,e,r),o=!1;if(this.settings.merged.selectedAuthType)try{await i.refreshAuth(this.settings.merged.selectedAuthType,{apiKey:this.settings.merged.apiKey,baseUrl:this.settings.merged.baseUrl,modelName:this.settings.merged.modelName}),o=!0}catch(u){console.error(`Authentication failed: ${u}`)}if(!o)throw a9.authRequired();if(this.clientCapabilities?.fs){let u=new jIe(this.client,n,this.clientCapabilities.fs,i.getFileSystemService());i.setFileSystemService(u)}let a=await i.getGeminiClient().startChat(),c=new W4t(n,a,i,this.client);return this.sessions.set(n,c),{sessionId:n}}async newSessionConfig(e,r,n){let i={...this.settings.merged.mcpServers};for(let{command:a,args:c,env:u,name:f}of n){let d={};for(let{name:p,value:h}of u)d[p]=h;i[f]=new sce(a,c,d,r)}let o={...this.settings.merged,mcpServers:i},s=await WP(o,this.extensions,e,this.argv);return await s.initialize(),s}async cancel(e){let r=this.sessions.get(e.sessionId);if(!r)throw new Error(`Session not found: ${e.sessionId}`);await r.cancelPendingPrompt()}async prompt(e){let r=this.sessions.get(e.sessionId);if(!r)throw new Error(`Session not found: ${e.sessionId}`);return r.prompt(e)}},W4t=class{constructor(e,r,n,i){this.id=e;this.chat=r;this.config=n;this.client=i}pendingPrompt=null;async cancelPendingPrompt(){if(!this.pendingPrompt)throw new Error("Not currently generating");this.pendingPrompt.abort(),this.pendingPrompt=null}async prompt(e){this.pendingPrompt?.abort();let r=new AbortController;this.pendingPrompt=r;let n=Math.random().toString(16).slice(2),i=this.chat,s={role:"user",parts:await this.#e(e.prompt,r.signal)};for(;s!==null;){if(r.signal.aborted)return i.addHistory(s),{stopReason:"cancelled"};let a=[];try{let c=await i.sendMessageStream({message:s?.parts??[],config:{abortSignal:r.signal}},n);s=null;for await(let u of c){if(r.signal.aborted)return{stopReason:"cancelled"};if(u.candidates&&u.candidates.length>0){let f=u.candidates[0];for(let d of f.content?.parts??[]){if(!d.text)continue;let p={type:"text",text:d.text};this.sendUpdate({sessionUpdate:d.thought?"agent_thought_chunk":"agent_message_chunk",content:p})}}u.functionCalls&&a.push(...u.functionCalls)}}catch(c){throw Dse(c)===429?new a9(429,"Rate limit exceeded. Try again later."):c}if(a.length>0){let c=[];for(let u of a){let f=await this.runTool(r.signal,n,u),d=Array.isArray(f)?f:[f];for(let p of d)typeof p=="string"?c.push({text:p}):p&&c.push(p)}s={role:"user",parts:c}}}return{stopReason:"end_turn"}}async sendUpdate(e){let r={sessionId:this.id,update:e};await this.client.sessionUpdate(r)}async runTool(e,r,n){let i=n.id??`${n.name}-${Date.now()}`,o=n.args??{},s=Date.now(),a=f=>{let d=Date.now()-s;return J5(this.config,{"event.name":"tool_call","event.timestamp":new Date().toISOString(),prompt_id:r,function_name:n.name??"",function_args:o,duration_ms:d,success:!1,error:f.message}),[{functionResponse:{id:i,name:n.name??"",response:{error:f.message}}}]};if(!n.name)return a(new Error("Missing function name"));let u=(await this.config.getToolRegistry()).getTool(n.name);if(!u)return a(new Error(`Tool "${n.name}" not found in registry.`));try{let f=await u.shouldConfirmExecute(o,e);if(f){let g=[];f.type==="edit"&&g.push({type:"diff",path:f.fileName,oldText:f.originalContent,newText:f.newContent});let A={sessionId:this.id,options:BAo(f),toolCall:{toolCallId:i,status:"pending",title:u.getDescription(o),content:g,locations:u.toolLocations(o),kind:u.kind}},y=await this.client.requestPermission(A),v=y.outcome.outcome==="cancelled"?fn.Cancel:fe.nativeEnum(fn).parse(y.outcome.optionId);switch(await f.onConfirm(v),v){case fn.Cancel:return a(new Error(`Tool "${n.name}" was canceled by the user.`));case fn.ProceedOnce:case fn.ProceedAlways:case fn.ProceedAlwaysServer:case fn.ProceedAlwaysTool:case fn.ModifyWithEditor:break;default:{let S=v;throw new Error(`Unexpected: ${S}`)}}}else await this.sendUpdate({sessionUpdate:"tool_call",toolCallId:i,status:"in_progress",title:u.getDescription(o),content:[],locations:u.toolLocations(o),kind:u.kind});let d=await u.execute(o,e),p=jan(d,o);await this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:i,status:"completed",content:p?[p]:[]});let h=Date.now()-s;return J5(this.config,{"event.name":"tool_call","event.timestamp":new Date().toISOString(),function_name:n.name,function_args:o,duration_ms:h,success:!0,prompt_id:r}),Nk(n.name,i,d.llmContent)}catch(f){let d=f instanceof Error?f:new Error(String(f));return await this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:i,status:"failed",content:[{type:"content",content:{type:"text",text:d.message}}]}),a(d)}}async#e(e,r){let n="file://",i=[],o=e.map(S=>{switch(S.type){case"text":return{text:S.text};case"image":case"audio":return{inlineData:{mimeType:S.mimeType,data:S.data}};case"resource_link":return S.uri.startsWith(n)?{fileData:{mimeData:S.mimeType,name:S.name,fileUri:S.uri.slice(n.length)}}:{text:`@${S.uri}`};case"resource":return i.push(S.resource),{text:`@${S.resource.uri}`};default:{let x=S;throw new Error(`Unexpected chunk type: '${x}'`)}}}),s=o.filter(S=>"fileData"in S);if(s.length===0&&i.length===0)return o;let a=new Map,c=this.config.getFileService(),u=this.config.getFileFilteringRespectGitIgnore(),f=[],d=[],p=[],h=await this.config.getToolRegistry(),g=h.getTool("read_many_files"),A=h.getTool("glob");if(!g)throw new Error("Error: read_many_files tool not found.");for(let S of s){let x=S.fileData.fileUri;if(c.shouldGitIgnoreFile(x)){p.push(x),console.warn(`Path ${x} is ${u?"git-ignored and will be skipped":"ignored by custom patterns"}.`);continue}let T=x,B=!1;try{let P=JIe.resolve(this.config.getTargetDir(),x);die(P,this.config.getTargetDir())?((await zan.stat(P)).isDirectory()?(T=x.endsWith("/")?`${x}**`:`${x}/**`,this.debug(`Path ${x} resolved to directory, using glob: ${T}`)):this.debug(`Path ${x} resolved to file: ${T}`),B=!0):this.debug(`Path ${x} is outside the project directory. Skipping.`)}catch(P){if(Bs(P)&&P.code==="ENOENT")if(this.config.getEnableRecursiveFileSearch()&&A){this.debug(`Path ${x} not found directly, attempting glob search.`);try{let L=await A.execute({pattern:`**/*${x}*`,path:this.config.getTargetDir()},r);if(L.llmContent&&typeof L.llmContent=="string"&&!L.llmContent.startsWith("No files found")&&!L.llmContent.startsWith("Error:")){let q=L.llmContent.split(`
|
|
3982
3982
|
`);if(q.length>1&&q[1]){let I=q[1].trim();T=JIe.relative(this.config.getTargetDir(),I),this.debug(`Glob search for ${x} found ${I}, using relative path: ${T}`),B=!0}else this.debug(`Glob search for '**/*${x}*' did not return a usable path. Path ${x} will be skipped.`)}else this.debug(`Glob search for '**/*${x}*' found no files or an error. Path ${x} will be skipped.`)}catch(L){console.error(`Error during glob search for ${x}: ${wr(L)}`)}}else this.debug(`Glob tool not found. Path ${x} will be skipped.`);else console.error(`Error stating path ${x}. Path ${x} will be skipped.`)}B&&(f.push(T),a.set(x,T),d.push(x))}let y="";for(let S=0;S<o.length;S++){let x=o[S];if("text"in x)y+=x.text;else{let T=x.fileData&&a.get(x.fileData.fileUri);if(S>0&&y.length>0&&!y.endsWith(" ")&&T){let B=o[S-1];("text"in B||"fileData"in B&&a.has(B.fileData.fileUri))&&(y+=" ")}T?y+=`@${T}`:(S>0&&y.length>0&&!y.endsWith(" ")&&!x.fileData?.fileUri.startsWith(" ")&&(y+=" "),x.fileData?.fileUri&&(y+=`@${x.fileData.fileUri}`))}}if(y=y.trim(),p.length>0){let S=u?"git-ignored":"custom-ignored";this.debug(`Ignored ${p.length} ${S} files: ${p.join(", ")}`)}let v=[{text:y}];if(f.length===0&&i.length===0)return console.warn("No valid file paths found in @ commands to read."),[{text:y}];if(f.length>0){let S={paths:f,respectGitIgnore:u},x=`${g.name}-${Date.now()}`;try{await this.sendUpdate({sessionUpdate:"tool_call",toolCallId:x,status:"in_progress",title:g.getDescription(S),content:[],locations:g.toolLocations(S),kind:g.kind});let T=await g.execute(S,r),B=jan(T)||{type:"content",content:{type:"text",text:`Successfully read: ${d.join(", ")}`}};if(await this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:x,status:"completed",content:B?[B]:[]}),Array.isArray(T.llmContent)){let P=/^--- (.*?) ---\n\n([\s\S]*?)\n\n$/;v.push({text:`
|
|
3983
3983
|
--- Content from referenced files ---`});for(let L of T.llmContent)if(typeof L=="string"){let q=P.exec(L);if(q){let I=q[1],U=q[2].trim();v.push({text:`
|
|
3984
3984
|
Content from @${I}:
|
|
3985
3985
|
`}),v.push({text:U})}else v.push({text:L})}else v.push(L)}else console.warn("read_many_files tool returned no content or empty content.")}catch(T){throw await this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:x,status:"failed",content:[{type:"content",content:{type:"text",text:`Error reading files (${d.join(", ")}): ${wr(T)}`}}]}),T}}if(i.length>0){v.push({text:`
|
|
3986
3986
|
--- Content from referenced context ---`});for(let S of i)v.push({text:`
|
|
3987
3987
|
Content from @${S.uri}:
|
|
3988
|
-
`}),"text"in S?v.push({text:S.text}):v.push({inlineData:{mimeType:S.mimeType??"application/octet-stream",data:S.blob}})}return v}debug(e){this.config.getDebugMode()&&console.warn(e)}
|
|
3988
|
+
`}),"text"in S?v.push({text:S.text}):v.push({inlineData:{mimeType:S.mimeType??"application/octet-stream",data:S.blob}})}return v}debug(e){this.config.getDebugMode()&&console.warn(e)}};function jan(t,e){if(t.error?.message)throw new Error(t.error.message);return t.returnDisplay?typeof t.returnDisplay=="string"?{type:"content",content:{type:"text",text:t.returnDisplay.replace(/\u001b\[[0-9;]*m/g,"")},args:e}:{type:"diff",path:t.returnDisplay.fileName,oldText:t.returnDisplay.originalContent,newText:t.returnDisplay.newContent,args:e}:null}var YIe=[{optionId:fn.ProceedOnce,name:"Allow",kind:"allow_once"},{optionId:fn.Cancel,name:"Reject",kind:"reject_once"}];function BAo(t){switch(t.type){case"edit":return[{optionId:fn.ProceedAlways,name:"Allow All Edits",kind:"allow_always"},...YIe];case"exec":return[{optionId:fn.ProceedAlways,name:`Always Allow ${t.rootCommand}`,kind:"allow_always"},...YIe];case"mcp":return[{optionId:fn.ProceedAlwaysServer,name:`Always Allow ${t.serverName}`,kind:"allow_always"},{optionId:fn.ProceedAlwaysTool,name:`Always Allow ${t.toolName}`,kind:"allow_always"},...YIe];case"info":return[{optionId:fn.ProceedAlways,name:"Always Allow",kind:"allow_always"},...YIe];default:{let e=t;throw new Error(`Unexpected: ${e}`)}}}sn();sn();var KIe=class{constructor(e,r){this.client=e;this.eventEmitter=r}toolCallIdMap=new Map;agentIdMap=new Map;pendingToolCalls=new Map;eventUnsubscriber;isEnabled=!1;enable(){this.isEnabled||(this.isEnabled=!0,this.eventUnsubscriber=this.eventEmitter.on(this.handleSubAgentEvent.bind(this)))}disable(){this.isEnabled&&(this.isEnabled=!1,this.eventUnsubscriber&&(this.eventUnsubscriber(),this.eventUnsubscriber=void 0),this.toolCallIdMap.clear(),this.agentIdMap.clear(),this.pendingToolCalls.clear())}async handleSubAgentEvent(e){if(this.isEnabled)try{switch(e.type){case bn.TOOL_CALL_REQUESTED:await this.handleToolCallRequested(e);break;case bn.TOOL_CALL_COMPLETED:await this.handleToolCallCompleted(e);break;case bn.TOOL_CALL_FAILED:await this.handleToolCallFailed(e);break;case bn.AGENT_STARTED:case bn.AGENT_COMPLETED:case bn.AGENT_FAILED:await this.handleAgentLifecycleEvent(e);break;default:break}}catch(r){console.error("[ACP SubAgent Adapter] Error handling event:",r)}}async handleToolCallRequested(e){if(e.type!==bn.TOOL_CALL_REQUESTED)return;let r=e.data,{callId:n,toolName:i,args:o,agentId:s}=r;try{this.agentIdMap.set(s,n);let a=this.client.pushToolCall({icon:this.getToolIcon(i),label:this.formatToolLabel(i,o),locations:this.getToolLocations(i,o),content:null}).then(c=>(this.toolCallIdMap.set(n,c.id),this.pendingToolCalls.delete(n),console.log(`[ACP Adapter] Tool call requested: ${i} (${n} -> ${c.id})`),c.id));this.pendingToolCalls.set(n,a),await a}catch(a){console.error(`[ACP Adapter] Failed to push tool call for ${i}:`,a),this.agentIdMap.delete(s),this.pendingToolCalls.delete(n)}}async handleToolCallExecuting(e){if(e.type!==bn.TOOL_CALL_EXECUTING)return;let r=e.data,{callId:n,toolName:i,args:o}=r,s=await this.findACPToolCallId(n,e.agentId);if(!s){console.warn(`[ACP Adapter] No ACP tool call ID found for ${n}`);return}try{await this.client.updateToolCall({toolCallId:s,status:"running",content:{type:"markdown",markdown:`Executing ${i}...`,args:o}}),console.log(`[ACP Adapter] Tool call executing: ${i} (${n})`)}catch(a){console.error(`[ACP Adapter] Failed to update tool call status for ${i}:`,a)}}async findACPToolCallId(e,r){let n=this.toolCallIdMap.get(e);if(!n){let i=this.pendingToolCalls.get(e);if(i)try{n=await i}catch{console.warn(`[ACP Adapter] Failed to wait for pending tool call ID: ${e}`)}}if(!n){let i=this.agentIdMap.get(r);if(i&&(n=this.toolCallIdMap.get(i),!n)){let o=this.pendingToolCalls.get(i);if(o)try{n=await o}catch{console.warn(`[ACP Adapter] Failed to wait for pending tool call ID: ${i}`)}}}return n}async handleToolCallCompleted(e){if(e.type!==bn.TOOL_CALL_COMPLETED)return;let r=e.data,{callId:n,toolName:i,returnDisplay:o,duration:s,args:a}=r,c=await this.findACPToolCallId(n,e.agentId);if(!c){console.warn(`[ACP Adapter] No ACP tool call ID found for ${n}`);return}try{let u=this.formatToolResult(o,a);await this.client.updateToolCall({toolCallId:c,status:"finished",content:u}),this.toolCallIdMap.delete(String(c)),console.log(`[ACP Adapter] Tool call completed: ${i} (${n}) in ${s||0}ms`)}catch(u){console.error(`[ACP Adapter] Failed to update completed tool call for ${i}:`,u)}}async handleToolCallFailed(e){if(e.type!==bn.TOOL_CALL_FAILED)return;let r=e.data,{callId:n,toolName:i,error:o,duration:s,args:a}=r,c=await this.findACPToolCallId(n,e.agentId);if(!c){console.warn(`[ACP Adapter] No ACP tool call ID found for ${n}`);return}try{await this.client.updateToolCall({toolCallId:c,status:"error",content:{type:"markdown",markdown:`Error executing ${i}: ${o}`,args:a}}),this.toolCallIdMap.delete(String(c)),console.log(`[ACP Adapter] Tool call failed: ${i} (${n}) after ${s||0}ms - ${o}`)}catch(u){console.error(`[ACP Adapter] Failed to update failed tool call for ${i}:`,u)}}getToolIcon(e){return{read_file:"\u{1F4D6}",write_file:"\u270F\uFE0F",replace:"\u{1F4DD}",multi_edit:"\u{1F4DD}",run_shell_command:"\u{1F4BB}",search_file_content:"\u{1F50D}",glob:"\u{1F5C2}\uFE0F",list_directory:"\u{1F4C1}",web_fetch:"\u{1F310}",web_search:"\u{1F50D}",google_web_search:"\u{1F50D}",todo_write:"\u{1F4CB}",todo_read:"\u{1F4CB}",task:"\u{1F916}",read_many_files:"\u{1F4DA}"}[e]||"\u{1F527}"}formatToolLabel(e,r){switch(e){case"read_file":return`Reading ${r.file_path||r.absolute_path||"file"}`;case"write_file":return`Writing ${r.file_path||r.absolute_path||"file"}`;case"replace":case"multi_edit":return`Editing ${r.file_path||r.absolute_path||"file"}`;case"run_shell_command":return`Running: ${r.command?.slice(0,50)||"command"}`;case"search_file_content":return`Searching for "${r.pattern||"pattern"}"`;case"glob":return`Finding files: ${r.pattern||"pattern"}`;case"list_directory":return`Listing ${r.path||"directory"}`;case"web_fetch":return`Fetching ${r.url||"URL"}`;case"web_search":case"google_web_search":return`Searching: ${r.query||"query"}`;case"todo_write":return"Updating todos";case"todo_read":return"Reading todos";case"task":return`Task: ${r.description||"SubAgent task"}`;case"read_many_files":return`Reading multiple files: ${r.paths?.length||0} paths`;default:return`${e} tool`}}getToolLocations(e,r){if(r.file_path&&typeof r.file_path=="string")return[{path:r.file_path,line:r.line_number||null}];if(r.path&&typeof r.path=="string")return[{path:r.path,line:null}]}formatToolResult(e,r){if(!e)return{type:"markdown",markdown:"",args:r};if(e&&e.functionResponse&&e.functionResponse.response){let{output:n}=e.functionResponse.response;if(typeof n=="string")try{let i=JSON.parse(n);return{type:"markdown",markdown:"```json\n"+JSON.stringify(i,null,2)+"\n```",args:r}}catch{return{type:"markdown",markdown:n,args:r}}if(typeof n=="object")return{type:"markdown",markdown:"```json\n"+JSON.stringify(n,null,2)+"\n```",args:r}}if(typeof e=="string")return{type:"markdown",markdown:e,args:r};if(e.fileDiff&&e.fileName)return{type:"diff",path:e.fileName,oldText:e.originalContent||null,newText:e.newContent||"",args:r};try{return{type:"markdown",markdown:"```json\n"+JSON.stringify(e,null,2)+"\n```",args:r}}catch{return{type:"markdown",markdown:String(e),args:r}}}getActiveToolCallCount(){return this.toolCallIdMap.size}isAdapterEnabled(){return this.isEnabled}async handleAgentLifecycleEvent(e){let r=e.sessionConfig?.agentType||"unknown",n="";switch(e.type){case bn.AGENT_STARTED:n=`\u25B6\uFE0F ${r} Agent started`;break;case bn.AGENT_COMPLETED:n=`\u2705 ${r} Agent completed`;break;case bn.AGENT_FAILED:n=`\u274C ${r} Agent failed`;break;default:n=`\u26A0\uFE0F Unknown agent lifecycle event: ${e.type}`}if(n)try{await this.client.streamAssistantMessageChunk({chunk:{text:`
|
|
3989
3989
|
${n}
|
|
3990
3990
|
`}})}catch(i){console.warn("[ACP Adapter] Failed to stream agent lifecycle event:",i)}}getEnhancedToolStatus(e,r){switch(r){case"scheduled":return"running";case"executing":return"running";case"success":return"finished";case"error":return"error";default:return"running"}}formatEnhancedToolResult(e,r,n){return r==="edit"&&e?.fileDiff?{type:"diff",path:e.fileName||"unknown file",oldText:e.originalContent||null,newText:e.newContent||"",args:n}:typeof e=="string"&&this.isCodeContent(e)?{type:"markdown",markdown:"```\n"+e+"\n```",args:n}:this.formatToolResult(e,n)}isCodeContent(e){return["def ","class ","function ","import ","export ","<?php","#!/bin/","<script","<?xml"].some(n=>e.includes(n))}};var j4t=class{createAdapter(e,r){return new KIe(e,r)}};function Jan(){Rb.register(new j4t)}async function Kan(t){let r=new TextEncoder,n=new TextDecoder,i=new WritableStream({write(d){try{t.send(n.decode(d))}catch{}}}),o=null,s=new ReadableStream({start(d){o=d},cancel(){o=null}});function a(d){}function c(){process.on("unhandledRejection",(p,h)=>{let g=`=========================================
|
|
3991
3991
|
This is an unexpected error. Please file a bug report using the /bug tool.
|
|
@@ -4001,7 +4001,7 @@ CRITICAL: Unhandled Promise Rejection!
|
|
|
4001
4001
|
=========================================
|
|
4002
4002
|
Reason: ${e}${e instanceof Error&&e.stack?`
|
|
4003
4003
|
Stack trace:
|
|
4004
|
-
${e.stack}`:""}`;Ta.emit("log-error",n),t||(t=!0,Ta.emit("open-debug-console"))})}function n3o(){console.log("\u{1F50D} Crash diagnostics enabled - Core dump and crash files will be generated on crash"),process.setUncaughtExceptionCaptureCallback(t=>{let e={timestamp:new Date().toISOString(),error:{name:t.name,message:t.message,stack:t.stack},memory:process.memoryUsage(),pid:process.pid,cwd:process.cwd(),nodeVersion:process.version,platform:process.platform,arch:process.arch,uptime:process.uptime(),env:{NODE_ENV:process.env.NODE_ENV,SANDBOX:process.env.SANDBOX,CLI_VERSION:"0.2.24
|
|
4004
|
+
${e.stack}`:""}`;Ta.emit("log-error",n),t||(t=!0,Ta.emit("open-debug-console"))})}function n3o(){console.log("\u{1F50D} Crash diagnostics enabled - Core dump and crash files will be generated on crash"),process.setUncaughtExceptionCaptureCallback(t=>{let e={timestamp:new Date().toISOString(),error:{name:t.name,message:t.message,stack:t.stack},memory:process.memoryUsage(),pid:process.pid,cwd:process.cwd(),nodeVersion:process.version,platform:process.platform,arch:process.arch,uptime:process.uptime(),env:{NODE_ENV:process.env.NODE_ENV,SANDBOX:process.env.SANDBOX,CLI_VERSION:"0.2.24"}},r=`crash-${Date.now()}-${process.pid}.json`,n=jAo.join(process.cwd(),r);try{XAo.writeFileSync(n,JSON.stringify(e,null,2)),console.error(`\u{1F4A5} Crash detected! Crash info written to: ${n}`),console.error("\u{1F4CB} Core dump will be generated...")}catch(i){console.error("\u274C Failed to write crash file:",i)}process.abort()}),process.on("warning",t=>{console.warn("\u26A0\uFE0F Node.js Warning:",{name:t.name,message:t.message,stack:t.stack})}),process.on("unhandledRejection",(t,e)=>{console.error("\u{1F6A8} Unhandled Promise Rejection detected:",{reason:t,promise:e.toString()})})}async function $ln(){r3o();let t=process.cwd(),e=Fc(t);if(!e.user.settings.cna){let f=await The();f&&e.setValue("User","cna",f)}if(await Lrn(),e.errors.length>0){for(let f of e.errors){let d=`Error in ${f.path}: ${f.message}`;process.env.NO_COLOR||(d=`\x1B[31m${d}\x1B[0m`),console.error(d),console.error(`Please fix ${f.path} and try again.`)}process.exit(1)}let r=await HTe(),n=JD(t),i=await WP(e.merged,n,$g.generateSessionId(),r);if(i.getDebugMode()&&n3o(),JAo.setDefaultResultOrder(ZAo(e.merged.dnsResolutionOrder)),r.promptInteractive&&!process.stdin.isTTY&&(console.error("Error: The --prompt-interactive flag is not supported when piping input from stdin."),process.exit(1)),i.getListExtensions()){console.debug("Installed extensions:");for(let f of n)console.debug(`- ${f.config.name}`);process.exit(0)}if(r._&&r._[0]==="agent"){let{agentCommand:f}=await Promise.resolve().then(()=>(Zyt(),krn)),d=(await Promise.resolve().then(()=>(gEt(),mEt))).default;await d().scriptName("iflow").command(f).help().version(!1).parse(),process.exit(0)}if(r._&&r._[0]==="commands"){let{commandsCommand:f}=await Promise.resolve().then(()=>(Kyt(),brn)),d=(await Promise.resolve().then(()=>(gEt(),mEt))).default;await d().scriptName("iflow").command(f).help().version(!1).parse(),process.exit(0)}e.merged.selectedAuthType||process.env.CLOUD_SHELL==="true"&&e.setValue("User","selectedAuthType",Ar.CLOUD_SHELL),fZr(i.getDebugMode()),await i.initialize();try{await i.setIdeModeAndSyncConnection(!0)}catch(f){console.error("Failed to connect to IDE server:",f)}if(Gl.loadCustomThemes(e.merged.customThemes),e.merged.theme&&(Gl.setActiveTheme(e.merged.theme)||console.warn(`Warning: Theme "${e.merged.theme}" not found.`)),!process.env.SANDBOX){let f=e.merged.autoConfigureMaxOldSpaceSize?e3o(i):[],d=i.getSandbox();if(d){if(e.merged.selectedAuthType&&!e.merged.useExternalAuth)try{let p=OP(e.merged.selectedAuthType);if(p)throw new Error(p);await i.refreshAuth(e.merged.selectedAuthType,{apiKey:e.merged.apiKey,baseUrl:e.merged.baseUrl,modelName:e.merged.modelName})}catch(p){console.error("Error authenticating:",p),process.exit(1)}await Cin(d,f,i),process.exit(0)}else f.length>0&&(await t3o(f),process.exit(0))}if(e.merged.selectedAuthType===Ar.LOGIN_WITH_IFLOW&&i.isBrowserLaunchSuppressed()&&await PB(e.merged.selectedAuthType,i),i.getExperimentalAcp())return i.getAcpPort()?await rln(i,e,n,r,i.getAcpPort()):Yan(i,e,n,r);let o=i.getQuestion(),s=[...await bin(),...await Sin(t)];if(!!r.promptInteractive||!!r.continue||!!r.resume||process.stdin.isTTY&&o?.length===0){console.clear();let f=await LD();Vln(Gln(t),e);let d,p=async()=>{try{if(console.clear(),Vln(Gln(t),e),process.stdin.isTTY&&(process.stdin.setRawMode(!0),process.stdin.resume()),d)try{d.unmount(),await new Promise(h=>process.nextTick(h))}catch(h){console.error("Error during unmount:",h)}d=ude((0,Hue.jsx)(AEt.default.StrictMode,{children:(0,Hue.jsx)(x6t,{config:i,settings:e,startupWarnings:s,version:f,continueMode:!!r.continue,resumeMode:!!r.resume,resumeSessionId:r.resume,fgMode:!0})}),{exitOnCtrlC:!1,stdout:mAt(),stdin:process.stdin,patchConsole:!0})}catch(h){console.error("Error during resume:",h)}};process.on("SIGCONT",p),oue(()=>{process.off("SIGCONT",p)}),process.stdin.isTTY&&(process.stdin.setRawMode(!0),process.stdin.resume()),d=ude((0,Hue.jsx)(AEt.default.StrictMode,{children:(0,Hue.jsx)(x6t,{config:i,settings:e,startupWarnings:s,version:f,continueMode:!!r.continue,resumeMode:!!r.resume,resumeSessionId:r.resume})}),{exitOnCtrlC:!1,stdout:mAt()}),e.merged.disableAutoUpdate||qan().then(h=>{rin(h,e,i.getProjectRoot())}).catch(h=>{i.getDebugMode()&&console.error("Update check failed:",h)}),oue(()=>d.unmount());return}!process.stdin.isTTY&&!o&&(o+=await Ain()),o||(console.error("No input provided via stdin."),process.exit(1));let c=Math.random().toString(16).slice(2);zz(i,{"event.name":"user_prompt","event.timestamp":new Date().toISOString(),prompt:o,prompt_id:c,auth_type:i.getContentGeneratorConfig()?.authType,prompt_length:o.length});let u=await i3o(i,n,e,r);await xin(u,o,c),process.exit(0)}function Vln(t,e){if(!e.merged.hideWindowTitle){let r=(process.env.CLI_TITLE||`iFlow - ${t}`).replace(/[\x00-\x1F\x7F]/g,"");process.stdout.write(`\x1B]2;${r}\x07`),process.on("exit",()=>{process.stdout.write("\x1B]2;\x07")})}}async function i3o(t,e,r,n){let i=t;if(t.getApprovalMode()!==ui.YOLO){let o=r.merged.excludeTools||[],s=[xu.Name,Ip.Name,ud.Name],a=[...new Set([...o,...s])],c={...r.merged,excludeTools:a},u={...n};i=await WP(c,e,t.getSessionId(),u),await i.initialize()}return await o3o(r.merged.selectedAuthType,i,r)}async function o3o(t,e,r){!t&&!process.env.GEMINI_API_KEY&&!Bhe()&&(console.error(`Please set an Auth method in your ${bP} or specify one of the following environment variables before running:
|
|
4005
4005
|
- apiKey, APIKEY, API_KEY, api_key
|
|
4006
4006
|
- baseUrl, BASEURL, BASE_URL, base_url
|
|
4007
4007
|
- modelName, MODELNAME, MODEL_NAME, model_name `),process.exit(1)),t||(Bhe()?t=Ar.IFLOW:t=Ar.IFLOW);let n=OP(t);return n!=null&&(console.error(n),process.exit(1)),await e.refreshAuth(t,{apiKey:r.merged.apiKey,baseUrl:r.merged.baseUrl,modelName:r.merged.modelName}),e}$ln().catch(t=>{console.error("An unexpected critical error occurred:"),t instanceof Error?console.error(t.stack):console.error(String(t)),process.exit(1)});
|