@superglue/cli 1.1.243 → 1.1.245
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/.claude-plugin/plugin.json +1 -1
- package/dist/cli.js +27 -26
- package/dist/skills/superglue/SKILL.md +16 -15
- package/dist/skills/superglue/references/superglue-email.md +100 -0
- package/package.json +1 -1
- package/skills/superglue/SKILL.md +16 -15
- package/skills/superglue/references/superglue-email.md +100 -0
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
"use strict";var r6=Object.create;var Uh=Object.defineProperty;var n6=Object.getOwnPropertyDescriptor;var i6=Object.getOwnPropertyNames;var o6=Object.getPrototypeOf,s6=Object.prototype.hasOwnProperty;var ft=(t,e)=>()=>(t&&(e=t(t=0)),e);var y=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),yD=(t,e)=>{for(var r in e)Uh(t,r,{get:e[r],enumerable:!0})},ED=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of i6(e))!s6.call(t,i)&&i!==r&&Uh(t,i,{get:()=>e[i],enumerable:!(n=n6(e,i))||n.enumerable});return t};var Be=(t,e,r)=>(r=t!=null?r6(o6(t)):{},ED(e||!t||!t.__esModule?Uh(r,"default",{value:t,enumerable:!0}):r,t)),DC=t=>ED(Uh({},"__esModule",{value:!0}),t);var RC=y(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.MAX_FOLLOW_UPS=Fn.FOLLOW_UPS_PREFIX=void 0;Fn.splitFollowUps=kC;Fn.getMessageFollowUps=c6;Fn.getPartDisplayText=l6;Fn.FOLLOW_UPS_PREFIX="Follow-ups:";Fn.MAX_FOLLOW_UPS=3;var a6=/\[([^[\]\n]+)\]/g;function kC(t,{streaming:e=!1}={}){let r=t.trimEnd(),n=r.lastIndexOf(`
|
|
3
|
-
`)+1,i=r.slice(n);return i.startsWith(Fn.FOLLOW_UPS_PREFIX)||e&&i.length>0&&Fn.FOLLOW_UPS_PREFIX.startsWith(i)?{reply:r.slice(0,n).trimEnd(),followUps:[...i.matchAll(a6)].map(s=>s[1].trim()).filter(Boolean).slice(0,Fn.MAX_FOLLOW_UPS)}:{reply:t,followUps:[]}}function c6(t){if(t.role!=="assistant")return[];let e=[...t.parts??[]].reverse().find(r=>r.type==="content"&&r.content?.trim());return kC(e?.content??t.content).followUps}function l6(t,e){return t.role!=="assistant"?e:kC(e,{streaming:!!t.isStreaming}).reply}});var pn=y(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.PLAYBOOK_LIMITS=F.MCP_SERVER_AUTH_MODES=F.TEAMS_CHANNEL_STARTER_PROMPTS=F.AGENT_REQUEST_BUSY_STATUSES=F.NEXT_STEP_LINK_ACTIONS=F.NEXT_STEP_LINK_PARAMS=F.NEXT_STEP_STATUSES=F.AGENT_SESSION_TEAMS_METADATA_KEY=F.AGENT_SESSION_PREPARATION_METADATA_KEY=F.AGENT_SESSION_USER_OPENED_METADATA_KEY=F.AGENT_SESSION_RESOURCE_KINDS=F.AGENT_MESSAGE_SCHEMA_VERSION=F.AGENT_APPROVAL_MODES=F.ConfirmationAction=F.LOADABLE_MARKDOWN_NAMES=F.SKILL_REFERENCE_NAMES=F.SKILL_BODY_NAMES=F.AGENT_CHECKLIST_MAX_LABEL_CHARS=F.AGENT_CHECKLIST_MAX_ITEMS=F.AGENT_CHECKLIST_MIN_ITEMS=F.AGENT_TOOLS=F.AGENT_NATIVE_TOOLS=F.MEMORY_AGENT_TYPES=F.PLAYGROUND_TOOL_DRAFT_ID=F.AgentType=F.FileStatus=F.MAX_BULK_RESOURCE_SHARE_OPERATIONS=F.MAX_BULK_MUTATION_IDS=F.SERVER_MANAGED_CONFIG_FIELDS=F.RunExecutionKind=F.RequestSource=F.RunStatus=F.LogLevel=F.AuthType=F.FileType=F.CacheMode=F.HttpMethod=F.SupportedFileType=F.AGENT_SESSION_BACKGROUND_JOBS_METADATA_KEY=F.AGENT_BACKGROUND_JOB_STATUSES=F.RUN_COMMAND_EFFECT_KINDS=F.CONNECTION_PROTOCOLS=F.TURN_CONTEXT_BLOCK_TYPES=void 0;F.isRequestConfig=u6;F.isTransformConfig=d6;F.isAgentSessionOpenedByUser=kD;F.isAgentSessionHiddenUntilOpened=A6;F.TURN_CONTEXT_BLOCK_TYPES=["connections","playbooks","project","background-job","approval-mode"];F.CONNECTION_PROTOCOLS=["http","postgres","mssql","redis","mongodb","sftp","smb","odbc","script","suitecloud"];F.RUN_COMMAND_EFFECT_KINDS=["tool","tool_state","system","connection","project","schedule","session","briefing","mcp_server","role","playbook","share","org_settings","design_system","file","memory","visual","checklist","browser"];F.AGENT_BACKGROUND_JOB_STATUSES=["running","completed","failed","stopped","lost"];F.AGENT_SESSION_BACKGROUND_JOBS_METADATA_KEY="backgroundJobs";var ID;(function(t){t.JSON="JSON",t.CSV="CSV",t.XML="XML",t.HTML="HTML",t.YAML="YAML",t.EXCEL="EXCEL",t.PDF="PDF",t.DOCX="DOCX",t.PPTX="PPTX",t.ZIP="ZIP",t.GZIP="GZIP",t.QBM="QBM",t.BINARY="BINARY",t.RAW="RAW",t.AUTO="AUTO"})(ID||(F.SupportedFileType=ID={}));var CD;(function(t){t.GET="GET",t.POST="POST",t.PUT="PUT",t.DELETE="DELETE",t.PATCH="PATCH",t.HEAD="HEAD",t.OPTIONS="OPTIONS"})(CD||(F.HttpMethod=CD={}));var bD;(function(t){t.ENABLED="ENABLED",t.READONLY="READONLY",t.WRITEONLY="WRITEONLY",t.DISABLED="DISABLED"})(bD||(F.CacheMode=bD={}));var SD;(function(t){t.CSV="CSV",t.JSON="JSON",t.XML="XML",t.YAML="YAML",t.EXCEL="EXCEL",t.HTML="HTML",t.PDF="PDF",t.DOCX="DOCX",t.PPTX="PPTX",t.ZIP="ZIP",t.BINARY="BINARY",t.RAW="RAW",t.AUTO="AUTO"})(SD||(F.FileType=SD={}));var wD;(function(t){t.NONE="NONE",t.OAUTH2="OAUTH2",t.HEADER="HEADER",t.QUERY_PARAM="QUERY_PARAM"})(wD||(F.AuthType=wD={}));var _D;(function(t){t.DEBUG="DEBUG",t.INFO="INFO",t.WARN="WARN",t.ERROR="ERROR"})(_D||(F.LogLevel=_D={}));var BD;(function(t){t.RUNNING="RUNNING",t.SUCCESS="SUCCESS",t.FAILED="FAILED",t.ABORTED="ABORTED"})(BD||(F.RunStatus=BD={}));var vD;(function(t){t.API="api",t.FRONTEND="frontend",t.AGENT="agent",t.SCHEDULER="scheduler",t.MCP="mcp",t.TOOL_CHAIN="tool-chain",t.WEBHOOK="webhook",t.CLI="cli"})(vD||(F.RequestSource=vD={}));var QD;(function(t){t.FULL="full",t.DRAFT="draft",t.SINGLE_STEP="single-step"})(QD||(F.RunExecutionKind=QD={}));F.SERVER_MANAGED_CONFIG_FIELDS=["version","createdByUserId","createdAt","updatedAt","lastUsedAt"];F.MAX_BULK_MUTATION_IDS=100;F.MAX_BULK_RESOURCE_SHARE_OPERATIONS=1e3;function u6(t){return!t||typeof t!="object"?!1:t.type==="request"||!("type"in t)||t.type===void 0}function d6(t){return t?.type==="transform"}var TD;(function(t){t.PENDING="PENDING",t.UPLOADING="UPLOADING",t.PROCESSING="PROCESSING",t.COMPLETED="COMPLETED",t.FAILED="FAILED"})(TD||(F.FileStatus=TD={}));var ys;(function(t){t.MAIN="main",t.PLAYGROUND="playground",t.PLAYBOOK_PLAYGROUND="playbook_playground",t.FILE_PLAYGROUND="file_playground",t.ACCESS_RULES="access_rules",t.CONNECTION_PLAYGROUND="connection_playground"})(ys||(F.AgentType=ys={}));F.PLAYGROUND_TOOL_DRAFT_ID="@playground-draft";F.MEMORY_AGENT_TYPES=[ys.MAIN];F.AGENT_NATIVE_TOOLS=["run_command","load_skill","connect","setup_gateway","setup_oauth_app","request_permissions"];F.AGENT_TOOLS={[ys.MAIN]:[...F.AGENT_NATIVE_TOOLS],[ys.PLAYGROUND]:[...F.AGENT_NATIVE_TOOLS],[ys.PLAYBOOK_PLAYGROUND]:[...F.AGENT_NATIVE_TOOLS],[ys.FILE_PLAYGROUND]:[...F.AGENT_NATIVE_TOOLS],[ys.ACCESS_RULES]:[...F.AGENT_NATIVE_TOOLS],[ys.CONNECTION_PLAYGROUND]:[...F.AGENT_NATIVE_TOOLS]};F.AGENT_CHECKLIST_MIN_ITEMS=4;F.AGENT_CHECKLIST_MAX_ITEMS=15;F.AGENT_CHECKLIST_MAX_LABEL_CHARS=120;F.SKILL_BODY_NAMES=["superglue-info","tools","connections","access-management","tool-deployment","notifications","artifacts","playbooks","projects","superglue-brain","email","workspace-apps","meetings","design-system","demos","chat-visuals","acumatica","netsuite","sage-intacct","microsoft-dynamics"];F.SKILL_REFERENCE_NAMES=["http","graphql","postgres","mssql","odbc","redis","mongodb","sftp-smb","suitecloud","project-preparation","acumatica-configuration","microsoft-dynamics-dependencies","power-automate","sage-intacct-configuration","quickbooks-desktop-files","office-files","tool-files","tunnel-handling","browser","artifacts-html","artifacts-excel"];F.LOADABLE_MARKDOWN_NAMES=[...F.SKILL_BODY_NAMES,...F.SKILL_REFERENCE_NAMES];var DD;(function(t){t.CONFIRMED="confirmed",t.DECLINED="declined",t.OAUTH_SUCCESS="oauth_success",t.OAUTH_FAILURE="oauth_failure"})(DD||(F.ConfirmationAction=DD={}));F.AGENT_APPROVAL_MODES=["ask","act"];F.AGENT_MESSAGE_SCHEMA_VERSION=1;F.AGENT_SESSION_RESOURCE_KINDS=["tool","system","playbook","file","briefing","credential"];F.AGENT_SESSION_USER_OPENED_METADATA_KEY="userOpened";F.AGENT_SESSION_PREPARATION_METADATA_KEY="taskPreparation";F.AGENT_SESSION_TEAMS_METADATA_KEY="teams";function kD(t){return t[F.AGENT_SESSION_USER_OPENED_METADATA_KEY]===!0}function A6(t){return(t.resourceBinding?.kind==="briefing"||t.metadata[F.AGENT_SESSION_PREPARATION_METADATA_KEY]===!0)&&!kD(t.metadata)}F.NEXT_STEP_STATUSES=["open","started","done"];F.NEXT_STEP_LINK_PARAMS={id:"nextStep",action:"nextStepAction"};F.NEXT_STEP_LINK_ACTIONS=["start","done"];F.AGENT_REQUEST_BUSY_STATUSES=["queued","claimed","running","cancelling"];F.TEAMS_CHANNEL_STARTER_PROMPTS=[{title:"What is the project status?",description:"Progress, blockers, owners and dates"},{title:"What is waiting on me?",description:"Ask superglue anything in plain words"},{title:"Recap the last meeting",description:"Recap a meeting and update the tasks"}];F.MCP_SERVER_AUTH_MODES=["oauth","creator_api_key"];F.PLAYBOOK_LIMITS={name:120,whenToRun:500,instructions:1e5,compiledRender:512e3}});var cc=y(wr=>{"use strict";var RD;Object.defineProperty(wr,"__esModule",{value:!0});wr.globalConfig=wr.$ZodEncodeError=wr.$ZodAsyncError=wr.$brand=wr.NEVER=void 0;wr.$constructor=p6;wr.config=h6;wr.NEVER=Object.freeze({status:"aborted"});function p6(t,e,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let l=s.prototype,u=Object.keys(l);for(let d=0;d<u.length;d++){let A=u[d];A in a||(a[A]=l[A].bind(a))}}let i=r?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:t});function s(a){var c;let l=r?.Parent?new o:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(s,"name",{value:t}),s}wr.$brand=Symbol("zod_brand");var NC=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};wr.$ZodAsyncError=NC;var OC=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};wr.$ZodEncodeError=OC;(RD=globalThis).__zod_globalConfig??(RD.__zod_globalConfig={});wr.globalConfig=globalThis.__zod_globalConfig;function h6(t){return t&&Object.assign(wr.globalConfig,t),wr.globalConfig}});var pe=y(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.Class=ne.BIGINT_FORMAT_RANGES=ne.NUMBER_FORMAT_RANGES=ne.primitiveTypes=ne.propertyKeyTypes=ne.getParsedType=ne.allowsEval=ne.captureStackTrace=void 0;ne.assertEqual=g6;ne.assertNotEqual=m6;ne.assertIs=y6;ne.assertNever=E6;ne.assert=I6;ne.getEnumValues=C6;ne.joinValues=b6;ne.jsonStringifyReplacer=S6;ne.cached=OD;ne.nullish=w6;ne.cleanRegex=_6;ne.floatSafeRemainder=B6;ne.defineLazy=v6;ne.objectClone=Q6;ne.assignProp=ia;ne.mergeDefs=Es;ne.cloneDef=T6;ne.getElementAtPath=D6;ne.promiseAllObject=k6;ne.randomString=R6;ne.esc=N6;ne.slugify=O6;ne.isObject=xC;ne.isPlainObject=Mh;ne.shallowClone=x6;ne.numKeys=U6;ne.escapeRegex=P6;ne.clone=oa;ne.normalizeParams=L6;ne.createTransparentProxy=$6;ne.stringifyPrimitive=xD;ne.optionalKeys=F6;ne.pick=j6;ne.omit=z6;ne.extend=q6;ne.safeExtend=H6;ne.merge=G6;ne.partial=Y6;ne.required=V6;ne.aborted=W6;ne.explicitlyAborted=J6;ne.prefixIssues=Z6;ne.unwrapMessage=$d;ne.finalizeIssue=K6;ne.getSizableOrigin=X6;ne.getLengthableOrigin=e3;ne.parsedType=t3;ne.issue=r3;ne.cleanEnum=n3;ne.base64ToUint8Array=UD;ne.uint8ArrayToBase64=MD;ne.base64urlToUint8Array=i3;ne.uint8ArrayToBase64url=o3;ne.hexToUint8Array=s3;ne.uint8ArrayToHex=a3;var f6=cc();function g6(t){return t}function m6(t){return t}function y6(t){}function E6(t){throw new Error("Unexpected value in exhaustive check")}function I6(t){}function C6(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,i])=>e.indexOf(+n)===-1).map(([n,i])=>i)}function b6(t,e="|"){return t.map(r=>xD(r)).join(e)}function S6(t,e){return typeof e=="bigint"?e.toString():e}function OD(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function w6(t){return t==null}function _6(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function B6(t,e){let r=t/e,n=Math.round(r),i=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<i?0:r-n}var ND=Symbol("evaluating");function v6(t,e,r){let n;Object.defineProperty(t,e,{get(){if(n!==ND)return n===void 0&&(n=ND,n=r()),n},set(i){Object.defineProperty(t,e,{value:i})},configurable:!0})}function Q6(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function ia(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Es(...t){let e={};for(let r of t){let n=Object.getOwnPropertyDescriptors(r);Object.assign(e,n)}return Object.defineProperties({},e)}function T6(t){return Es(t._zod.def)}function D6(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function k6(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let i={};for(let o=0;o<e.length;o++)i[e[o]]=n[o];return i})}function R6(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function N6(t){return JSON.stringify(t)}function O6(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}ne.captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function xC(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}ne.allowsEval=OD(()=>{if(f6.globalConfig.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Mh(t){if(xC(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(xC(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function x6(t){return Mh(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function U6(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var M6=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}};ne.getParsedType=M6;ne.propertyKeyTypes=new Set(["string","number","symbol"]);ne.primitiveTypes=new Set(["string","number","bigint","boolean","symbol","undefined"]);function P6(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function oa(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function L6(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function $6(t){let e;return new Proxy({},{get(r,n,i){return e??(e=t()),Reflect.get(e,n,i)},set(r,n,i,o){return e??(e=t()),Reflect.set(e,n,i,o)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,i){return e??(e=t()),Reflect.defineProperty(e,n,i)}})}function xD(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function F6(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}ne.NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};ne.BIGINT_FORMAT_RANGES={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function j6(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let o=Es(t._zod.def,{get shape(){let s={};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(s[a]=r.shape[a])}return ia(this,"shape",s),s},checks:[]});return oa(t,o)}function z6(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let o=Es(t._zod.def,{get shape(){let s={...t._zod.def.shape};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete s[a]}return ia(this,"shape",s),s},checks:[]});return oa(t,o)}function q6(t,e){if(!Mh(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0){let o=t._zod.def.shape;for(let s in e)if(Object.getOwnPropertyDescriptor(o,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let i=Es(t._zod.def,{get shape(){let o={...t._zod.def.shape,...e};return ia(this,"shape",o),o}});return oa(t,i)}function H6(t,e){if(!Mh(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=Es(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e};return ia(this,"shape",n),n}});return oa(t,r)}function G6(t,e){if(t._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=Es(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return ia(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return oa(t,r)}function Y6(t,e,r){let i=e._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=Es(e._zod.def,{get shape(){let a=e._zod.def.shape,c={...a};if(r)for(let l in r){if(!(l in a))throw new Error(`Unrecognized key: "${l}"`);r[l]&&(c[l]=t?new t({type:"optional",innerType:a[l]}):a[l])}else for(let l in a)c[l]=t?new t({type:"optional",innerType:a[l]}):a[l];return ia(this,"shape",c),c},checks:[]});return oa(e,s)}function V6(t,e,r){let n=Es(e._zod.def,{get shape(){let i=e._zod.def.shape,o={...i};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:i[s]}))}else for(let s in i)o[s]=new t({type:"nonoptional",innerType:i[s]});return ia(this,"shape",o),o}});return oa(e,n)}function W6(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function J6(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue===!1)return!0;return!1}function Z6(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function $d(t){return typeof t=="string"?t:t?.message}function K6(t,e,r){let n=t.message?t.message:$d(t.inst?._zod.def?.error?.(t))??$d(e?.error?.(t))??$d(r.customError?.(t))??$d(r.localeError?.(t))??"Invalid input",{inst:i,continue:o,input:s,...a}=t;return a.path??(a.path=[]),a.message=n,e?.reportInput&&(a.input=s),a}function X6(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function e3(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function t3(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let r=t;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return e}function r3(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function n3(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function UD(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function MD(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function i3(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-e.length%4)%4);return UD(e+r)}function o3(t){return MD(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function s3(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)r[n/2]=Number.parseInt(e.slice(n,n+2),16);return r}function a3(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var UC=class{constructor(...e){}};ne.Class=UC});var MC=y(Ir=>{"use strict";var c3=Ir&&Ir.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),l3=Ir&&Ir.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),u3=Ir&&Ir.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&c3(e,t,r);return l3(e,t),e};Object.defineProperty(Ir,"__esModule",{value:!0});Ir.$ZodRealError=Ir.$ZodError=void 0;Ir.flattenError=A3;Ir.formatError=p3;Ir.treeifyError=h3;Ir.toDotPath=$D;Ir.prettifyError=f3;var PD=cc(),d3=u3(pe()),LD=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,d3.jsonStringifyReplacer,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})};Ir.$ZodError=(0,PD.$constructor)("$ZodError",LD);Ir.$ZodRealError=(0,PD.$constructor)("$ZodError",LD,{Parent:Error});function A3(t,e=r=>r.message){let r={},n=[];for(let i of t.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(e(i))):n.push(e(i));return{formErrors:n,fieldErrors:r}}function p3(t,e=r=>r.message){let r={_errors:[]},n=(i,o=[])=>{for(let s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>n({issues:a},[...o,...s.path]));else if(s.code==="invalid_key")n({issues:s.issues},[...o,...s.path]);else if(s.code==="invalid_element")n({issues:s.issues},[...o,...s.path]);else{let a=[...o,...s.path];if(a.length===0)r._errors.push(e(s));else{let c=r,l=0;for(;l<a.length;){let u=a[l];l===a.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(e(s))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}}};return n(t),r}function h3(t,e=r=>r.message){let r={errors:[]},n=(i,o=[])=>{var s,a;for(let c of i.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map(l=>n({issues:l},[...o,...c.path]));else if(c.code==="invalid_key")n({issues:c.issues},[...o,...c.path]);else if(c.code==="invalid_element")n({issues:c.issues},[...o,...c.path]);else{let l=[...o,...c.path];if(l.length===0){r.errors.push(e(c));continue}let u=r,d=0;for(;d<l.length;){let A=l[d],p=d===l.length-1;typeof A=="string"?(u.properties??(u.properties={}),(s=u.properties)[A]??(s[A]={errors:[]}),u=u.properties[A]):(u.items??(u.items=[]),(a=u.items)[A]??(a[A]={errors:[]}),u=u.items[A]),p&&u.errors.push(e(c)),d++}}};return n(t),r}function $D(t){let e=[],r=t.map(n=>typeof n=="object"?n.key:n);for(let n of r)typeof n=="number"?e.push(`[${n}]`):typeof n=="symbol"?e.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?e.push(`[${JSON.stringify(n)}]`):(e.length&&e.push("."),e.push(n));return e.join("")}function f3(t){let e=[],r=[...t.issues].sort((n,i)=>(n.path??[]).length-(i.path??[]).length);for(let n of r)e.push(`\u2716 ${n.message}`),n.path?.length&&e.push(` \u2192 at ${$D(n.path)}`);return e.join(`
|
|
4
|
-
`)}});var LC=y(Z=>{"use strict";var g3=Z&&Z.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),m3=Z&&Z.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),PC=Z&&Z.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&g3(e,t,r);return m3(e,t),e};Object.defineProperty(Z,"__esModule",{value:!0});Z.safeDecodeAsync=Z._safeDecodeAsync=Z.safeEncodeAsync=Z._safeEncodeAsync=Z.safeDecode=Z._safeDecode=Z.safeEncode=Z._safeEncode=Z.decodeAsync=Z._decodeAsync=Z.encodeAsync=Z._encodeAsync=Z.decode=Z._decode=Z.encode=Z._encode=Z.safeParseAsync=Z._safeParseAsync=Z.safeParse=Z._safeParse=Z.parseAsync=Z._parseAsync=Z.parse=Z._parse=void 0;var Ol=PC(cc()),hn=PC(MC()),xl=PC(pe()),y3=t=>(e,r,n,i)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Ol.$ZodAsyncError;if(s.issues.length){let a=new(i?.Err??t)(s.issues.map(c=>xl.finalizeIssue(c,o,Ol.config())));throw xl.captureStackTrace(a,i?.callee),a}return s.value};Z._parse=y3;Z.parse=(0,Z._parse)(hn.$ZodRealError);var E3=t=>async(e,r,n,i)=>{let o=n?{...n,async:!0}:{async:!0},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(i?.Err??t)(s.issues.map(c=>xl.finalizeIssue(c,o,Ol.config())));throw xl.captureStackTrace(a,i?.callee),a}return s.value};Z._parseAsync=E3;Z.parseAsync=(0,Z._parseAsync)(hn.$ZodRealError);var I3=t=>(e,r,n)=>{let i=n?{...n,async:!1}:{async:!1},o=e._zod.run({value:r,issues:[]},i);if(o instanceof Promise)throw new Ol.$ZodAsyncError;return o.issues.length?{success:!1,error:new(t??hn.$ZodError)(o.issues.map(s=>xl.finalizeIssue(s,i,Ol.config())))}:{success:!0,data:o.value}};Z._safeParse=I3;Z.safeParse=(0,Z._safeParse)(hn.$ZodRealError);var C3=t=>async(e,r,n)=>{let i=n?{...n,async:!0}:{async:!0},o=e._zod.run({value:r,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(s=>xl.finalizeIssue(s,i,Ol.config())))}:{success:!0,data:o.value}};Z._safeParseAsync=C3;Z.safeParseAsync=(0,Z._safeParseAsync)(hn.$ZodRealError);var b3=t=>(e,r,n)=>{let i=n?{...n,direction:"backward"}:{direction:"backward"};return(0,Z._parse)(t)(e,r,i)};Z._encode=b3;Z.encode=(0,Z._encode)(hn.$ZodRealError);var S3=t=>(e,r,n)=>(0,Z._parse)(t)(e,r,n);Z._decode=S3;Z.decode=(0,Z._decode)(hn.$ZodRealError);var w3=t=>async(e,r,n)=>{let i=n?{...n,direction:"backward"}:{direction:"backward"};return(0,Z._parseAsync)(t)(e,r,i)};Z._encodeAsync=w3;Z.encodeAsync=(0,Z._encodeAsync)(hn.$ZodRealError);var _3=t=>async(e,r,n)=>(0,Z._parseAsync)(t)(e,r,n);Z._decodeAsync=_3;Z.decodeAsync=(0,Z._decodeAsync)(hn.$ZodRealError);var B3=t=>(e,r,n)=>{let i=n?{...n,direction:"backward"}:{direction:"backward"};return(0,Z._safeParse)(t)(e,r,i)};Z._safeEncode=B3;Z.safeEncode=(0,Z._safeEncode)(hn.$ZodRealError);var v3=t=>(e,r,n)=>(0,Z._safeParse)(t)(e,r,n);Z._safeDecode=v3;Z.safeDecode=(0,Z._safeDecode)(hn.$ZodRealError);var Q3=t=>async(e,r,n)=>{let i=n?{...n,direction:"backward"}:{direction:"backward"};return(0,Z._safeParseAsync)(t)(e,r,i)};Z._safeEncodeAsync=Q3;Z.safeEncodeAsync=(0,Z._safeEncodeAsync)(hn.$ZodRealError);var T3=t=>async(e,r,n)=>(0,Z._safeParseAsync)(t)(e,r,n);Z._safeDecodeAsync=T3;Z.safeDecodeAsync=(0,Z._safeDecodeAsync)(hn.$ZodRealError)});var Ph=y(O=>{"use strict";var D3=O&&O.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),k3=O&&O.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),R3=O&&O.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&D3(e,t,r);return k3(e,t),e};Object.defineProperty(O,"__esModule",{value:!0});O.sha256_base64url=O.sha256_base64=O.sha256_hex=O.sha1_base64url=O.sha1_base64=O.sha1_hex=O.md5_base64url=O.md5_base64=O.md5_hex=O.hex=O.uppercase=O.lowercase=O.undefined=O.null=O.boolean=O.number=O.integer=O.bigint=O.string=O.date=O.e164=O.httpProtocol=O.domain=O.hostname=O.base64url=O.base64=O.cidrv6=O.cidrv4=O.mac=O.ipv6=O.ipv4=O.browserEmail=O.idnEmail=O.unicodeEmail=O.rfc5322Email=O.html5Email=O.email=O.uuid7=O.uuid6=O.uuid4=O.uuid=O.guid=O.extendedDuration=O.duration=O.nanoid=O.ksuid=O.xid=O.ulid=O.cuid2=O.cuid=void 0;O.sha512_base64url=O.sha512_base64=O.sha512_hex=O.sha384_base64url=O.sha384_base64=O.sha384_hex=void 0;O.emoji=U3;O.time=P3;O.datetime=L3;var N3=R3(pe());O.cuid=/^[cC][0-9a-z]{6,}$/;O.cuid2=/^[0-9a-z]+$/;O.ulid=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;O.xid=/^[0-9a-vA-V]{20}$/;O.ksuid=/^[A-Za-z0-9]{27}$/;O.nanoid=/^[a-zA-Z0-9_-]{21}$/;O.duration=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;O.extendedDuration=/^[-+]?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)?)??$/;O.guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;var O3=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;O.uuid=O3;O.uuid4=(0,O.uuid)(4);O.uuid6=(0,O.uuid)(6);O.uuid7=(0,O.uuid)(7);O.email=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;O.html5Email=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;O.rfc5322Email=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;O.unicodeEmail=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u;O.idnEmail=O.unicodeEmail;O.browserEmail=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;var x3="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function U3(){return new RegExp(x3,"u")}O.ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;O.ipv6=/^(([0-9a-fA-F]{1,4}:){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}|:))$/;var M3=t=>{let e=N3.escapeRegex(t??":");return new RegExp(`^(?:[0-9A-F]{2}${e}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${e}){5}[0-9a-f]{2}$`)};O.mac=M3;O.cidrv4=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/;O.cidrv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;O.base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;O.base64url=/^[A-Za-z0-9_-]*$/;O.hostname=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;O.domain=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;O.httpProtocol=/^https?$/;O.e164=/^\+[1-9]\d{6,14}$/;var FD="(?:(?:\\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])))";O.date=new RegExp(`^${FD}$`);function jD(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function P3(t){return new RegExp(`^${jD(t)}$`)}function L3(t){let e=jD({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${FD}T(?:${n})$`)}var $3=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};O.string=$3;O.bigint=/^-?\d+n?$/;O.integer=/^-?\d+$/;O.number=/^-?\d+(?:\.\d+)?$/;O.boolean=/^(?:true|false)$/i;var F3=/^null$/i;O.null=F3;var j3=/^undefined$/i;O.undefined=j3;O.lowercase=/^[^A-Z]*$/;O.uppercase=/^[^a-z]*$/;O.hex=/^[0-9a-fA-F]*$/;function Fd(t,e){return new RegExp(`^[A-Za-z0-9+/]{${t}}${e}$`)}function jd(t){return new RegExp(`^[A-Za-z0-9_-]{${t}}$`)}O.md5_hex=/^[0-9a-fA-F]{32}$/;O.md5_base64=Fd(22,"==");O.md5_base64url=jd(22);O.sha1_hex=/^[0-9a-fA-F]{40}$/;O.sha1_base64=Fd(27,"=");O.sha1_base64url=jd(27);O.sha256_hex=/^[0-9a-fA-F]{64}$/;O.sha256_base64=Fd(43,"=");O.sha256_base64url=jd(43);O.sha384_hex=/^[0-9a-fA-F]{96}$/;O.sha384_base64=Fd(64,"");O.sha384_base64url=jd(64);O.sha512_hex=/^[0-9a-fA-F]{128}$/;O.sha512_base64=Fd(86,"==");O.sha512_base64url=jd(86)});var Lh=y(ie=>{"use strict";var z3=ie&&ie.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),q3=ie&&ie.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),$C=ie&&ie.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&z3(e,t,r);return q3(e,t),e};Object.defineProperty(ie,"__esModule",{value:!0});ie.$ZodCheckOverwrite=ie.$ZodCheckMimeType=ie.$ZodCheckProperty=ie.$ZodCheckEndsWith=ie.$ZodCheckStartsWith=ie.$ZodCheckIncludes=ie.$ZodCheckUpperCase=ie.$ZodCheckLowerCase=ie.$ZodCheckRegex=ie.$ZodCheckStringFormat=ie.$ZodCheckLengthEquals=ie.$ZodCheckMinLength=ie.$ZodCheckMaxLength=ie.$ZodCheckSizeEquals=ie.$ZodCheckMinSize=ie.$ZodCheckMaxSize=ie.$ZodCheckBigIntFormat=ie.$ZodCheckNumberFormat=ie.$ZodCheckMultipleOf=ie.$ZodCheckGreaterThan=ie.$ZodCheckLessThan=ie.$ZodCheck=void 0;var xt=$C(cc()),FC=$C(Ph()),nr=$C(pe());ie.$ZodCheck=xt.$constructor("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])});var qD={number:"number",bigint:"bigint",object:"date"};ie.$ZodCheckLessThan=xt.$constructor("$ZodCheckLessThan",(t,e)=>{ie.$ZodCheck.init(t,e);let r=qD[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,o=(e.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(e.inclusive?i.maximum=e.value:i.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}});ie.$ZodCheckGreaterThan=xt.$constructor("$ZodCheckGreaterThan",(t,e)=>{ie.$ZodCheck.init(t,e);let r=qD[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,o=(e.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(e.inclusive?i.minimum=e.value:i.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}});ie.$ZodCheckMultipleOf=xt.$constructor("$ZodCheckMultipleOf",(t,e)=>{ie.$ZodCheck.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):nr.floatSafeRemainder(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}});ie.$ZodCheckNumberFormat=xt.$constructor("$ZodCheckNumberFormat",(t,e)=>{ie.$ZodCheck.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[i,o]=nr.NUMBER_FORMAT_RANGES[e.format];t._zod.onattach.push(s=>{let a=s._zod.bag;a.format=e.format,a.minimum=i,a.maximum=o,r&&(a.pattern=FC.integer)}),t._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!e.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!e.abort});return}}a<i&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:t,continue:!e.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:t,continue:!e.abort})}});ie.$ZodCheckBigIntFormat=xt.$constructor("$ZodCheckBigIntFormat",(t,e)=>{ie.$ZodCheck.init(t,e);let[r,n]=nr.BIGINT_FORMAT_RANGES[e.format];t._zod.onattach.push(i=>{let o=i._zod.bag;o.format=e.format,o.minimum=r,o.maximum=n}),t._zod.check=i=>{let o=i.value;o<r&&i.issues.push({origin:"bigint",input:o,code:"too_small",minimum:r,inclusive:!0,inst:t,continue:!e.abort}),o>n&&i.issues.push({origin:"bigint",input:o,code:"too_big",maximum:n,inclusive:!0,inst:t,continue:!e.abort})}});ie.$ZodCheckMaxSize=xt.$constructor("$ZodCheckMaxSize",(t,e)=>{var r;ie.$ZodCheck.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!nr.nullish(i)&&i.size!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<i&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let i=n.value;i.size<=e.maximum||n.issues.push({origin:nr.getSizableOrigin(i),code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}});ie.$ZodCheckMinSize=xt.$constructor("$ZodCheckMinSize",(t,e)=>{var r;ie.$ZodCheck.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!nr.nullish(i)&&i.size!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>i&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let i=n.value;i.size>=e.minimum||n.issues.push({origin:nr.getSizableOrigin(i),code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}});ie.$ZodCheckSizeEquals=xt.$constructor("$ZodCheckSizeEquals",(t,e)=>{var r;ie.$ZodCheck.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!nr.nullish(i)&&i.size!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=e.size,i.maximum=e.size,i.size=e.size}),t._zod.check=n=>{let i=n.value,o=i.size;if(o===e.size)return;let s=o>e.size;n.issues.push({origin:nr.getSizableOrigin(i),...s?{code:"too_big",maximum:e.size}:{code:"too_small",minimum:e.size},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}});ie.$ZodCheckMaxLength=xt.$constructor("$ZodCheckMaxLength",(t,e)=>{var r;ie.$ZodCheck.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!nr.nullish(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<i&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let i=n.value;if(i.length<=e.maximum)return;let s=nr.getLengthableOrigin(i);n.issues.push({origin:s,code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}});ie.$ZodCheckMinLength=xt.$constructor("$ZodCheckMinLength",(t,e)=>{var r;ie.$ZodCheck.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!nr.nullish(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>i&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let i=n.value;if(i.length>=e.minimum)return;let s=nr.getLengthableOrigin(i);n.issues.push({origin:s,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}});ie.$ZodCheckLengthEquals=xt.$constructor("$ZodCheckLengthEquals",(t,e)=>{var r;ie.$ZodCheck.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!nr.nullish(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=e.length,i.maximum=e.length,i.length=e.length}),t._zod.check=n=>{let i=n.value,o=i.length;if(o===e.length)return;let s=nr.getLengthableOrigin(i),a=o>e.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}});ie.$ZodCheckStringFormat=xt.$constructor("$ZodCheckStringFormat",(t,e)=>{var r,n;ie.$ZodCheck.init(t,e),t._zod.onattach.push(i=>{let o=i._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=i=>{e.pattern.lastIndex=0,!e.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:e.format,input:i.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})});ie.$ZodCheckRegex=xt.$constructor("$ZodCheckRegex",(t,e)=>{ie.$ZodCheckStringFormat.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}});ie.$ZodCheckLowerCase=xt.$constructor("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=FC.lowercase),ie.$ZodCheckStringFormat.init(t,e)});ie.$ZodCheckUpperCase=xt.$constructor("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=FC.uppercase),ie.$ZodCheckStringFormat.init(t,e)});ie.$ZodCheckIncludes=xt.$constructor("$ZodCheckIncludes",(t,e)=>{ie.$ZodCheck.init(t,e);let r=nr.escapeRegex(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(i=>{let o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=i=>{i.value.includes(e.includes,e.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:i.value,inst:t,continue:!e.abort})}});ie.$ZodCheckStartsWith=xt.$constructor("$ZodCheckStartsWith",(t,e)=>{ie.$ZodCheck.init(t,e);let r=new RegExp(`^${nr.escapeRegex(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}});ie.$ZodCheckEndsWith=xt.$constructor("$ZodCheckEndsWith",(t,e)=>{ie.$ZodCheck.init(t,e);let r=new RegExp(`.*${nr.escapeRegex(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});function zD(t,e,r){t.issues.length&&e.issues.push(...nr.prefixIssues(r,t.issues))}ie.$ZodCheckProperty=xt.$constructor("$ZodCheckProperty",(t,e)=>{ie.$ZodCheck.init(t,e),t._zod.check=r=>{let n=e.schema._zod.run({value:r.value[e.property],issues:[]},{});if(n instanceof Promise)return n.then(i=>zD(i,r,e.property));zD(n,r,e.property)}});ie.$ZodCheckMimeType=xt.$constructor("$ZodCheckMimeType",(t,e)=>{ie.$ZodCheck.init(t,e);let r=new Set(e.mime);t._zod.onattach.push(n=>{n._zod.bag.mime=e.mime}),t._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:e.mime,input:n.value.type,inst:t,continue:!e.abort})}});ie.$ZodCheckOverwrite=xt.$constructor("$ZodCheckOverwrite",(t,e)=>{ie.$ZodCheck.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var zC=y($h=>{"use strict";Object.defineProperty($h,"__esModule",{value:!0});$h.Doc=void 0;var jC=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
3
|
+
`)+1,i=r.slice(n);return i.startsWith(Fn.FOLLOW_UPS_PREFIX)||e&&i.length>0&&Fn.FOLLOW_UPS_PREFIX.startsWith(i)?{reply:r.slice(0,n).trimEnd(),followUps:[...i.matchAll(a6)].map(s=>s[1].trim()).filter(Boolean).slice(0,Fn.MAX_FOLLOW_UPS)}:{reply:t,followUps:[]}}function c6(t){if(t.role!=="assistant")return[];let e=[...t.parts??[]].reverse().find(r=>r.type==="content"&&r.content?.trim());return kC(e?.content??t.content).followUps}function l6(t,e){return t.role!=="assistant"?e:kC(e,{streaming:!!t.isStreaming}).reply}});var pn=y(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.PLAYBOOK_LIMITS=F.MCP_SERVER_AUTH_MODES=F.TEAMS_CHANNEL_STARTER_PROMPTS=F.AGENT_REQUEST_BUSY_STATUSES=F.NEXT_STEP_LINK_ACTIONS=F.NEXT_STEP_LINK_PARAMS=F.NEXT_STEP_STATUSES=F.AGENT_SESSION_TEAMS_METADATA_KEY=F.AGENT_SESSION_PREPARATION_METADATA_KEY=F.AGENT_SESSION_USER_OPENED_METADATA_KEY=F.AGENT_SESSION_RESOURCE_KINDS=F.AGENT_MESSAGE_SCHEMA_VERSION=F.AGENT_APPROVAL_MODES=F.ConfirmationAction=F.LOADABLE_MARKDOWN_NAMES=F.SKILL_REFERENCE_NAMES=F.SKILL_BODY_NAMES=F.AGENT_CHECKLIST_MAX_LABEL_CHARS=F.AGENT_CHECKLIST_MAX_ITEMS=F.AGENT_CHECKLIST_MIN_ITEMS=F.AGENT_TOOLS=F.AGENT_NATIVE_TOOLS=F.MEMORY_AGENT_TYPES=F.PLAYGROUND_TOOL_DRAFT_ID=F.AgentType=F.FileStatus=F.MAX_BULK_RESOURCE_SHARE_OPERATIONS=F.MAX_BULK_MUTATION_IDS=F.SERVER_MANAGED_CONFIG_FIELDS=F.RunExecutionKind=F.RequestSource=F.RunStatus=F.LogLevel=F.AuthType=F.FileType=F.CacheMode=F.HttpMethod=F.SupportedFileType=F.AGENT_SESSION_BACKGROUND_JOBS_METADATA_KEY=F.AGENT_BACKGROUND_JOB_STATUSES=F.RUN_COMMAND_EFFECT_KINDS=F.CONNECTION_PROTOCOLS=F.TURN_CONTEXT_BLOCK_TYPES=void 0;F.isRequestConfig=u6;F.isTransformConfig=d6;F.isAgentSessionOpenedByUser=kD;F.isAgentSessionHiddenUntilOpened=A6;F.TURN_CONTEXT_BLOCK_TYPES=["connections","playbooks","project","background-job","approval-mode"];F.CONNECTION_PROTOCOLS=["http","postgres","mssql","redis","mongodb","sftp","smb","odbc","script","suitecloud"];F.RUN_COMMAND_EFFECT_KINDS=["tool","tool_state","system","connection","project","schedule","session","briefing","mcp_server","role","playbook","share","org_settings","design_system","file","memory","visual","checklist","browser"];F.AGENT_BACKGROUND_JOB_STATUSES=["running","completed","failed","stopped","lost"];F.AGENT_SESSION_BACKGROUND_JOBS_METADATA_KEY="backgroundJobs";var ID;(function(t){t.JSON="JSON",t.CSV="CSV",t.XML="XML",t.HTML="HTML",t.YAML="YAML",t.EXCEL="EXCEL",t.PDF="PDF",t.DOCX="DOCX",t.PPTX="PPTX",t.ZIP="ZIP",t.GZIP="GZIP",t.QBM="QBM",t.BINARY="BINARY",t.RAW="RAW",t.AUTO="AUTO"})(ID||(F.SupportedFileType=ID={}));var CD;(function(t){t.GET="GET",t.POST="POST",t.PUT="PUT",t.DELETE="DELETE",t.PATCH="PATCH",t.HEAD="HEAD",t.OPTIONS="OPTIONS"})(CD||(F.HttpMethod=CD={}));var bD;(function(t){t.ENABLED="ENABLED",t.READONLY="READONLY",t.WRITEONLY="WRITEONLY",t.DISABLED="DISABLED"})(bD||(F.CacheMode=bD={}));var SD;(function(t){t.CSV="CSV",t.JSON="JSON",t.XML="XML",t.YAML="YAML",t.EXCEL="EXCEL",t.HTML="HTML",t.PDF="PDF",t.DOCX="DOCX",t.PPTX="PPTX",t.ZIP="ZIP",t.BINARY="BINARY",t.RAW="RAW",t.AUTO="AUTO"})(SD||(F.FileType=SD={}));var wD;(function(t){t.NONE="NONE",t.OAUTH2="OAUTH2",t.HEADER="HEADER",t.QUERY_PARAM="QUERY_PARAM"})(wD||(F.AuthType=wD={}));var _D;(function(t){t.DEBUG="DEBUG",t.INFO="INFO",t.WARN="WARN",t.ERROR="ERROR"})(_D||(F.LogLevel=_D={}));var BD;(function(t){t.RUNNING="RUNNING",t.SUCCESS="SUCCESS",t.FAILED="FAILED",t.ABORTED="ABORTED"})(BD||(F.RunStatus=BD={}));var vD;(function(t){t.API="api",t.FRONTEND="frontend",t.AGENT="agent",t.SCHEDULER="scheduler",t.MCP="mcp",t.TOOL_CHAIN="tool-chain",t.WEBHOOK="webhook",t.CLI="cli"})(vD||(F.RequestSource=vD={}));var QD;(function(t){t.FULL="full",t.DRAFT="draft",t.SINGLE_STEP="single-step"})(QD||(F.RunExecutionKind=QD={}));F.SERVER_MANAGED_CONFIG_FIELDS=["version","createdByUserId","createdAt","updatedAt","lastUsedAt"];F.MAX_BULK_MUTATION_IDS=100;F.MAX_BULK_RESOURCE_SHARE_OPERATIONS=1e3;function u6(t){return!t||typeof t!="object"?!1:t.type==="request"||!("type"in t)||t.type===void 0}function d6(t){return t?.type==="transform"}var TD;(function(t){t.PENDING="PENDING",t.UPLOADING="UPLOADING",t.PROCESSING="PROCESSING",t.COMPLETED="COMPLETED",t.FAILED="FAILED"})(TD||(F.FileStatus=TD={}));var ys;(function(t){t.MAIN="main",t.PLAYGROUND="playground",t.PLAYBOOK_PLAYGROUND="playbook_playground",t.FILE_PLAYGROUND="file_playground",t.ACCESS_RULES="access_rules",t.CONNECTION_PLAYGROUND="connection_playground"})(ys||(F.AgentType=ys={}));F.PLAYGROUND_TOOL_DRAFT_ID="@playground-draft";F.MEMORY_AGENT_TYPES=[ys.MAIN];F.AGENT_NATIVE_TOOLS=["run_command","load_skill","connect","setup_gateway","setup_oauth_app","request_permissions"];F.AGENT_TOOLS={[ys.MAIN]:[...F.AGENT_NATIVE_TOOLS],[ys.PLAYGROUND]:[...F.AGENT_NATIVE_TOOLS],[ys.PLAYBOOK_PLAYGROUND]:[...F.AGENT_NATIVE_TOOLS],[ys.FILE_PLAYGROUND]:[...F.AGENT_NATIVE_TOOLS],[ys.ACCESS_RULES]:[...F.AGENT_NATIVE_TOOLS],[ys.CONNECTION_PLAYGROUND]:[...F.AGENT_NATIVE_TOOLS]};F.AGENT_CHECKLIST_MIN_ITEMS=4;F.AGENT_CHECKLIST_MAX_ITEMS=15;F.AGENT_CHECKLIST_MAX_LABEL_CHARS=120;F.SKILL_BODY_NAMES=["superglue-info","tools","connections","access-management","tool-deployment","notifications","artifacts","playbooks","projects","superglue-brain","email","workspace-apps","meetings","design-system","demos","chat-visuals","acumatica","netsuite","sage-intacct","microsoft-dynamics"];F.SKILL_REFERENCE_NAMES=["http","graphql","postgres","mssql","odbc","redis","mongodb","sftp-smb","suitecloud","project-preparation","acumatica-configuration","microsoft-dynamics-dependencies","power-automate","sage-intacct-configuration","quickbooks-desktop-files","office-files","tool-files","tunnel-handling","browser","artifacts-html","artifacts-excel","superglue-email"];F.LOADABLE_MARKDOWN_NAMES=[...F.SKILL_BODY_NAMES,...F.SKILL_REFERENCE_NAMES];var DD;(function(t){t.CONFIRMED="confirmed",t.DECLINED="declined",t.OAUTH_SUCCESS="oauth_success",t.OAUTH_FAILURE="oauth_failure"})(DD||(F.ConfirmationAction=DD={}));F.AGENT_APPROVAL_MODES=["ask","act"];F.AGENT_MESSAGE_SCHEMA_VERSION=1;F.AGENT_SESSION_RESOURCE_KINDS=["tool","system","playbook","file","briefing","credential"];F.AGENT_SESSION_USER_OPENED_METADATA_KEY="userOpened";F.AGENT_SESSION_PREPARATION_METADATA_KEY="taskPreparation";F.AGENT_SESSION_TEAMS_METADATA_KEY="teams";function kD(t){return t[F.AGENT_SESSION_USER_OPENED_METADATA_KEY]===!0}function A6(t){return(t.resourceBinding?.kind==="briefing"||t.metadata[F.AGENT_SESSION_PREPARATION_METADATA_KEY]===!0)&&!kD(t.metadata)}F.NEXT_STEP_STATUSES=["open","started","done"];F.NEXT_STEP_LINK_PARAMS={id:"nextStep",action:"nextStepAction"};F.NEXT_STEP_LINK_ACTIONS=["start","done"];F.AGENT_REQUEST_BUSY_STATUSES=["queued","claimed","running","cancelling"];F.TEAMS_CHANNEL_STARTER_PROMPTS=[{title:"What is the project status?",description:"Progress, blockers, owners and dates"},{title:"What is waiting on me?",description:"Ask superglue anything in plain words"},{title:"Recap the last meeting",description:"Recap a meeting and update the tasks"}];F.MCP_SERVER_AUTH_MODES=["oauth","creator_api_key"];F.PLAYBOOK_LIMITS={name:120,whenToRun:500,instructions:1e5,compiledRender:512e3}});var cc=y(wr=>{"use strict";var RD;Object.defineProperty(wr,"__esModule",{value:!0});wr.globalConfig=wr.$ZodEncodeError=wr.$ZodAsyncError=wr.$brand=wr.NEVER=void 0;wr.$constructor=p6;wr.config=h6;wr.NEVER=Object.freeze({status:"aborted"});function p6(t,e,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let l=s.prototype,u=Object.keys(l);for(let d=0;d<u.length;d++){let A=u[d];A in a||(a[A]=l[A].bind(a))}}let i=r?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:t});function s(a){var c;let l=r?.Parent?new o:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(s,"name",{value:t}),s}wr.$brand=Symbol("zod_brand");var NC=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};wr.$ZodAsyncError=NC;var OC=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};wr.$ZodEncodeError=OC;(RD=globalThis).__zod_globalConfig??(RD.__zod_globalConfig={});wr.globalConfig=globalThis.__zod_globalConfig;function h6(t){return t&&Object.assign(wr.globalConfig,t),wr.globalConfig}});var pe=y(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.Class=ne.BIGINT_FORMAT_RANGES=ne.NUMBER_FORMAT_RANGES=ne.primitiveTypes=ne.propertyKeyTypes=ne.getParsedType=ne.allowsEval=ne.captureStackTrace=void 0;ne.assertEqual=g6;ne.assertNotEqual=m6;ne.assertIs=y6;ne.assertNever=E6;ne.assert=I6;ne.getEnumValues=C6;ne.joinValues=b6;ne.jsonStringifyReplacer=S6;ne.cached=OD;ne.nullish=w6;ne.cleanRegex=_6;ne.floatSafeRemainder=B6;ne.defineLazy=v6;ne.objectClone=Q6;ne.assignProp=ia;ne.mergeDefs=Es;ne.cloneDef=T6;ne.getElementAtPath=D6;ne.promiseAllObject=k6;ne.randomString=R6;ne.esc=N6;ne.slugify=O6;ne.isObject=xC;ne.isPlainObject=Mh;ne.shallowClone=x6;ne.numKeys=U6;ne.escapeRegex=P6;ne.clone=oa;ne.normalizeParams=L6;ne.createTransparentProxy=$6;ne.stringifyPrimitive=xD;ne.optionalKeys=F6;ne.pick=j6;ne.omit=z6;ne.extend=q6;ne.safeExtend=H6;ne.merge=G6;ne.partial=Y6;ne.required=V6;ne.aborted=W6;ne.explicitlyAborted=J6;ne.prefixIssues=Z6;ne.unwrapMessage=$d;ne.finalizeIssue=K6;ne.getSizableOrigin=X6;ne.getLengthableOrigin=e3;ne.parsedType=t3;ne.issue=r3;ne.cleanEnum=n3;ne.base64ToUint8Array=UD;ne.uint8ArrayToBase64=MD;ne.base64urlToUint8Array=i3;ne.uint8ArrayToBase64url=o3;ne.hexToUint8Array=s3;ne.uint8ArrayToHex=a3;var f6=cc();function g6(t){return t}function m6(t){return t}function y6(t){}function E6(t){throw new Error("Unexpected value in exhaustive check")}function I6(t){}function C6(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,i])=>e.indexOf(+n)===-1).map(([n,i])=>i)}function b6(t,e="|"){return t.map(r=>xD(r)).join(e)}function S6(t,e){return typeof e=="bigint"?e.toString():e}function OD(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function w6(t){return t==null}function _6(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function B6(t,e){let r=t/e,n=Math.round(r),i=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<i?0:r-n}var ND=Symbol("evaluating");function v6(t,e,r){let n;Object.defineProperty(t,e,{get(){if(n!==ND)return n===void 0&&(n=ND,n=r()),n},set(i){Object.defineProperty(t,e,{value:i})},configurable:!0})}function Q6(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function ia(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Es(...t){let e={};for(let r of t){let n=Object.getOwnPropertyDescriptors(r);Object.assign(e,n)}return Object.defineProperties({},e)}function T6(t){return Es(t._zod.def)}function D6(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function k6(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let i={};for(let o=0;o<e.length;o++)i[e[o]]=n[o];return i})}function R6(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function N6(t){return JSON.stringify(t)}function O6(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}ne.captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function xC(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}ne.allowsEval=OD(()=>{if(f6.globalConfig.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Mh(t){if(xC(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(xC(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function x6(t){return Mh(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function U6(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var M6=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}};ne.getParsedType=M6;ne.propertyKeyTypes=new Set(["string","number","symbol"]);ne.primitiveTypes=new Set(["string","number","bigint","boolean","symbol","undefined"]);function P6(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function oa(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function L6(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function $6(t){let e;return new Proxy({},{get(r,n,i){return e??(e=t()),Reflect.get(e,n,i)},set(r,n,i,o){return e??(e=t()),Reflect.set(e,n,i,o)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,i){return e??(e=t()),Reflect.defineProperty(e,n,i)}})}function xD(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function F6(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}ne.NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};ne.BIGINT_FORMAT_RANGES={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function j6(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let o=Es(t._zod.def,{get shape(){let s={};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(s[a]=r.shape[a])}return ia(this,"shape",s),s},checks:[]});return oa(t,o)}function z6(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let o=Es(t._zod.def,{get shape(){let s={...t._zod.def.shape};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete s[a]}return ia(this,"shape",s),s},checks:[]});return oa(t,o)}function q6(t,e){if(!Mh(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0){let o=t._zod.def.shape;for(let s in e)if(Object.getOwnPropertyDescriptor(o,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let i=Es(t._zod.def,{get shape(){let o={...t._zod.def.shape,...e};return ia(this,"shape",o),o}});return oa(t,i)}function H6(t,e){if(!Mh(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=Es(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e};return ia(this,"shape",n),n}});return oa(t,r)}function G6(t,e){if(t._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=Es(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return ia(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return oa(t,r)}function Y6(t,e,r){let i=e._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=Es(e._zod.def,{get shape(){let a=e._zod.def.shape,c={...a};if(r)for(let l in r){if(!(l in a))throw new Error(`Unrecognized key: "${l}"`);r[l]&&(c[l]=t?new t({type:"optional",innerType:a[l]}):a[l])}else for(let l in a)c[l]=t?new t({type:"optional",innerType:a[l]}):a[l];return ia(this,"shape",c),c},checks:[]});return oa(e,s)}function V6(t,e,r){let n=Es(e._zod.def,{get shape(){let i=e._zod.def.shape,o={...i};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:i[s]}))}else for(let s in i)o[s]=new t({type:"nonoptional",innerType:i[s]});return ia(this,"shape",o),o}});return oa(e,n)}function W6(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function J6(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue===!1)return!0;return!1}function Z6(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function $d(t){return typeof t=="string"?t:t?.message}function K6(t,e,r){let n=t.message?t.message:$d(t.inst?._zod.def?.error?.(t))??$d(e?.error?.(t))??$d(r.customError?.(t))??$d(r.localeError?.(t))??"Invalid input",{inst:i,continue:o,input:s,...a}=t;return a.path??(a.path=[]),a.message=n,e?.reportInput&&(a.input=s),a}function X6(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function e3(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function t3(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let r=t;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return e}function r3(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function n3(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function UD(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function MD(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function i3(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-e.length%4)%4);return UD(e+r)}function o3(t){return MD(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function s3(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)r[n/2]=Number.parseInt(e.slice(n,n+2),16);return r}function a3(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var UC=class{constructor(...e){}};ne.Class=UC});var MC=y(Ir=>{"use strict";var c3=Ir&&Ir.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),l3=Ir&&Ir.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),u3=Ir&&Ir.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&c3(e,t,r);return l3(e,t),e};Object.defineProperty(Ir,"__esModule",{value:!0});Ir.$ZodRealError=Ir.$ZodError=void 0;Ir.flattenError=A3;Ir.formatError=p3;Ir.treeifyError=h3;Ir.toDotPath=$D;Ir.prettifyError=f3;var PD=cc(),d3=u3(pe()),LD=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,d3.jsonStringifyReplacer,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})};Ir.$ZodError=(0,PD.$constructor)("$ZodError",LD);Ir.$ZodRealError=(0,PD.$constructor)("$ZodError",LD,{Parent:Error});function A3(t,e=r=>r.message){let r={},n=[];for(let i of t.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(e(i))):n.push(e(i));return{formErrors:n,fieldErrors:r}}function p3(t,e=r=>r.message){let r={_errors:[]},n=(i,o=[])=>{for(let s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>n({issues:a},[...o,...s.path]));else if(s.code==="invalid_key")n({issues:s.issues},[...o,...s.path]);else if(s.code==="invalid_element")n({issues:s.issues},[...o,...s.path]);else{let a=[...o,...s.path];if(a.length===0)r._errors.push(e(s));else{let c=r,l=0;for(;l<a.length;){let u=a[l];l===a.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(e(s))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}}};return n(t),r}function h3(t,e=r=>r.message){let r={errors:[]},n=(i,o=[])=>{var s,a;for(let c of i.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map(l=>n({issues:l},[...o,...c.path]));else if(c.code==="invalid_key")n({issues:c.issues},[...o,...c.path]);else if(c.code==="invalid_element")n({issues:c.issues},[...o,...c.path]);else{let l=[...o,...c.path];if(l.length===0){r.errors.push(e(c));continue}let u=r,d=0;for(;d<l.length;){let A=l[d],p=d===l.length-1;typeof A=="string"?(u.properties??(u.properties={}),(s=u.properties)[A]??(s[A]={errors:[]}),u=u.properties[A]):(u.items??(u.items=[]),(a=u.items)[A]??(a[A]={errors:[]}),u=u.items[A]),p&&u.errors.push(e(c)),d++}}};return n(t),r}function $D(t){let e=[],r=t.map(n=>typeof n=="object"?n.key:n);for(let n of r)typeof n=="number"?e.push(`[${n}]`):typeof n=="symbol"?e.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?e.push(`[${JSON.stringify(n)}]`):(e.length&&e.push("."),e.push(n));return e.join("")}function f3(t){let e=[],r=[...t.issues].sort((n,i)=>(n.path??[]).length-(i.path??[]).length);for(let n of r)e.push(`\u2716 ${n.message}`),n.path?.length&&e.push(` \u2192 at ${$D(n.path)}`);return e.join(`
|
|
4
|
+
`)}});var LC=y(Z=>{"use strict";var g3=Z&&Z.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),m3=Z&&Z.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),PC=Z&&Z.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&g3(e,t,r);return m3(e,t),e};Object.defineProperty(Z,"__esModule",{value:!0});Z.safeDecodeAsync=Z._safeDecodeAsync=Z.safeEncodeAsync=Z._safeEncodeAsync=Z.safeDecode=Z._safeDecode=Z.safeEncode=Z._safeEncode=Z.decodeAsync=Z._decodeAsync=Z.encodeAsync=Z._encodeAsync=Z.decode=Z._decode=Z.encode=Z._encode=Z.safeParseAsync=Z._safeParseAsync=Z.safeParse=Z._safeParse=Z.parseAsync=Z._parseAsync=Z.parse=Z._parse=void 0;var Ol=PC(cc()),hn=PC(MC()),xl=PC(pe()),y3=t=>(e,r,n,i)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Ol.$ZodAsyncError;if(s.issues.length){let a=new(i?.Err??t)(s.issues.map(c=>xl.finalizeIssue(c,o,Ol.config())));throw xl.captureStackTrace(a,i?.callee),a}return s.value};Z._parse=y3;Z.parse=(0,Z._parse)(hn.$ZodRealError);var E3=t=>async(e,r,n,i)=>{let o=n?{...n,async:!0}:{async:!0},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(i?.Err??t)(s.issues.map(c=>xl.finalizeIssue(c,o,Ol.config())));throw xl.captureStackTrace(a,i?.callee),a}return s.value};Z._parseAsync=E3;Z.parseAsync=(0,Z._parseAsync)(hn.$ZodRealError);var I3=t=>(e,r,n)=>{let i=n?{...n,async:!1}:{async:!1},o=e._zod.run({value:r,issues:[]},i);if(o instanceof Promise)throw new Ol.$ZodAsyncError;return o.issues.length?{success:!1,error:new(t??hn.$ZodError)(o.issues.map(s=>xl.finalizeIssue(s,i,Ol.config())))}:{success:!0,data:o.value}};Z._safeParse=I3;Z.safeParse=(0,Z._safeParse)(hn.$ZodRealError);var C3=t=>async(e,r,n)=>{let i=n?{...n,async:!0}:{async:!0},o=e._zod.run({value:r,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(s=>xl.finalizeIssue(s,i,Ol.config())))}:{success:!0,data:o.value}};Z._safeParseAsync=C3;Z.safeParseAsync=(0,Z._safeParseAsync)(hn.$ZodRealError);var b3=t=>(e,r,n)=>{let i=n?{...n,direction:"backward"}:{direction:"backward"};return(0,Z._parse)(t)(e,r,i)};Z._encode=b3;Z.encode=(0,Z._encode)(hn.$ZodRealError);var S3=t=>(e,r,n)=>(0,Z._parse)(t)(e,r,n);Z._decode=S3;Z.decode=(0,Z._decode)(hn.$ZodRealError);var w3=t=>async(e,r,n)=>{let i=n?{...n,direction:"backward"}:{direction:"backward"};return(0,Z._parseAsync)(t)(e,r,i)};Z._encodeAsync=w3;Z.encodeAsync=(0,Z._encodeAsync)(hn.$ZodRealError);var _3=t=>async(e,r,n)=>(0,Z._parseAsync)(t)(e,r,n);Z._decodeAsync=_3;Z.decodeAsync=(0,Z._decodeAsync)(hn.$ZodRealError);var B3=t=>(e,r,n)=>{let i=n?{...n,direction:"backward"}:{direction:"backward"};return(0,Z._safeParse)(t)(e,r,i)};Z._safeEncode=B3;Z.safeEncode=(0,Z._safeEncode)(hn.$ZodRealError);var v3=t=>(e,r,n)=>(0,Z._safeParse)(t)(e,r,n);Z._safeDecode=v3;Z.safeDecode=(0,Z._safeDecode)(hn.$ZodRealError);var Q3=t=>async(e,r,n)=>{let i=n?{...n,direction:"backward"}:{direction:"backward"};return(0,Z._safeParseAsync)(t)(e,r,i)};Z._safeEncodeAsync=Q3;Z.safeEncodeAsync=(0,Z._safeEncodeAsync)(hn.$ZodRealError);var T3=t=>async(e,r,n)=>(0,Z._safeParseAsync)(t)(e,r,n);Z._safeDecodeAsync=T3;Z.safeDecodeAsync=(0,Z._safeDecodeAsync)(hn.$ZodRealError)});var Ph=y(O=>{"use strict";var D3=O&&O.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),k3=O&&O.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),R3=O&&O.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&D3(e,t,r);return k3(e,t),e};Object.defineProperty(O,"__esModule",{value:!0});O.sha256_base64url=O.sha256_base64=O.sha256_hex=O.sha1_base64url=O.sha1_base64=O.sha1_hex=O.md5_base64url=O.md5_base64=O.md5_hex=O.hex=O.uppercase=O.lowercase=O.undefined=O.null=O.boolean=O.number=O.integer=O.bigint=O.string=O.date=O.e164=O.httpProtocol=O.domain=O.hostname=O.base64url=O.base64=O.cidrv6=O.cidrv4=O.mac=O.ipv6=O.ipv4=O.browserEmail=O.idnEmail=O.unicodeEmail=O.rfc5322Email=O.html5Email=O.email=O.uuid7=O.uuid6=O.uuid4=O.uuid=O.guid=O.extendedDuration=O.duration=O.nanoid=O.ksuid=O.xid=O.ulid=O.cuid2=O.cuid=void 0;O.sha512_base64url=O.sha512_base64=O.sha512_hex=O.sha384_base64url=O.sha384_base64=O.sha384_hex=void 0;O.emoji=U3;O.time=P3;O.datetime=L3;var N3=R3(pe());O.cuid=/^[cC][0-9a-z]{6,}$/;O.cuid2=/^[0-9a-z]+$/;O.ulid=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;O.xid=/^[0-9a-vA-V]{20}$/;O.ksuid=/^[A-Za-z0-9]{27}$/;O.nanoid=/^[a-zA-Z0-9_-]{21}$/;O.duration=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;O.extendedDuration=/^[-+]?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)?)??$/;O.guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;var O3=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;O.uuid=O3;O.uuid4=(0,O.uuid)(4);O.uuid6=(0,O.uuid)(6);O.uuid7=(0,O.uuid)(7);O.email=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;O.html5Email=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;O.rfc5322Email=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;O.unicodeEmail=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u;O.idnEmail=O.unicodeEmail;O.browserEmail=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;var x3="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function U3(){return new RegExp(x3,"u")}O.ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;O.ipv6=/^(([0-9a-fA-F]{1,4}:){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}|:))$/;var M3=t=>{let e=N3.escapeRegex(t??":");return new RegExp(`^(?:[0-9A-F]{2}${e}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${e}){5}[0-9a-f]{2}$`)};O.mac=M3;O.cidrv4=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/;O.cidrv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;O.base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;O.base64url=/^[A-Za-z0-9_-]*$/;O.hostname=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;O.domain=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;O.httpProtocol=/^https?$/;O.e164=/^\+[1-9]\d{6,14}$/;var FD="(?:(?:\\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])))";O.date=new RegExp(`^${FD}$`);function jD(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function P3(t){return new RegExp(`^${jD(t)}$`)}function L3(t){let e=jD({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${FD}T(?:${n})$`)}var $3=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};O.string=$3;O.bigint=/^-?\d+n?$/;O.integer=/^-?\d+$/;O.number=/^-?\d+(?:\.\d+)?$/;O.boolean=/^(?:true|false)$/i;var F3=/^null$/i;O.null=F3;var j3=/^undefined$/i;O.undefined=j3;O.lowercase=/^[^A-Z]*$/;O.uppercase=/^[^a-z]*$/;O.hex=/^[0-9a-fA-F]*$/;function Fd(t,e){return new RegExp(`^[A-Za-z0-9+/]{${t}}${e}$`)}function jd(t){return new RegExp(`^[A-Za-z0-9_-]{${t}}$`)}O.md5_hex=/^[0-9a-fA-F]{32}$/;O.md5_base64=Fd(22,"==");O.md5_base64url=jd(22);O.sha1_hex=/^[0-9a-fA-F]{40}$/;O.sha1_base64=Fd(27,"=");O.sha1_base64url=jd(27);O.sha256_hex=/^[0-9a-fA-F]{64}$/;O.sha256_base64=Fd(43,"=");O.sha256_base64url=jd(43);O.sha384_hex=/^[0-9a-fA-F]{96}$/;O.sha384_base64=Fd(64,"");O.sha384_base64url=jd(64);O.sha512_hex=/^[0-9a-fA-F]{128}$/;O.sha512_base64=Fd(86,"==");O.sha512_base64url=jd(86)});var Lh=y(ie=>{"use strict";var z3=ie&&ie.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),q3=ie&&ie.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),$C=ie&&ie.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&z3(e,t,r);return q3(e,t),e};Object.defineProperty(ie,"__esModule",{value:!0});ie.$ZodCheckOverwrite=ie.$ZodCheckMimeType=ie.$ZodCheckProperty=ie.$ZodCheckEndsWith=ie.$ZodCheckStartsWith=ie.$ZodCheckIncludes=ie.$ZodCheckUpperCase=ie.$ZodCheckLowerCase=ie.$ZodCheckRegex=ie.$ZodCheckStringFormat=ie.$ZodCheckLengthEquals=ie.$ZodCheckMinLength=ie.$ZodCheckMaxLength=ie.$ZodCheckSizeEquals=ie.$ZodCheckMinSize=ie.$ZodCheckMaxSize=ie.$ZodCheckBigIntFormat=ie.$ZodCheckNumberFormat=ie.$ZodCheckMultipleOf=ie.$ZodCheckGreaterThan=ie.$ZodCheckLessThan=ie.$ZodCheck=void 0;var xt=$C(cc()),FC=$C(Ph()),ir=$C(pe());ie.$ZodCheck=xt.$constructor("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])});var qD={number:"number",bigint:"bigint",object:"date"};ie.$ZodCheckLessThan=xt.$constructor("$ZodCheckLessThan",(t,e)=>{ie.$ZodCheck.init(t,e);let r=qD[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,o=(e.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(e.inclusive?i.maximum=e.value:i.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}});ie.$ZodCheckGreaterThan=xt.$constructor("$ZodCheckGreaterThan",(t,e)=>{ie.$ZodCheck.init(t,e);let r=qD[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,o=(e.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(e.inclusive?i.minimum=e.value:i.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}});ie.$ZodCheckMultipleOf=xt.$constructor("$ZodCheckMultipleOf",(t,e)=>{ie.$ZodCheck.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):ir.floatSafeRemainder(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}});ie.$ZodCheckNumberFormat=xt.$constructor("$ZodCheckNumberFormat",(t,e)=>{ie.$ZodCheck.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[i,o]=ir.NUMBER_FORMAT_RANGES[e.format];t._zod.onattach.push(s=>{let a=s._zod.bag;a.format=e.format,a.minimum=i,a.maximum=o,r&&(a.pattern=FC.integer)}),t._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!e.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!e.abort});return}}a<i&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:t,continue:!e.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:t,continue:!e.abort})}});ie.$ZodCheckBigIntFormat=xt.$constructor("$ZodCheckBigIntFormat",(t,e)=>{ie.$ZodCheck.init(t,e);let[r,n]=ir.BIGINT_FORMAT_RANGES[e.format];t._zod.onattach.push(i=>{let o=i._zod.bag;o.format=e.format,o.minimum=r,o.maximum=n}),t._zod.check=i=>{let o=i.value;o<r&&i.issues.push({origin:"bigint",input:o,code:"too_small",minimum:r,inclusive:!0,inst:t,continue:!e.abort}),o>n&&i.issues.push({origin:"bigint",input:o,code:"too_big",maximum:n,inclusive:!0,inst:t,continue:!e.abort})}});ie.$ZodCheckMaxSize=xt.$constructor("$ZodCheckMaxSize",(t,e)=>{var r;ie.$ZodCheck.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!ir.nullish(i)&&i.size!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<i&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let i=n.value;i.size<=e.maximum||n.issues.push({origin:ir.getSizableOrigin(i),code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}});ie.$ZodCheckMinSize=xt.$constructor("$ZodCheckMinSize",(t,e)=>{var r;ie.$ZodCheck.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!ir.nullish(i)&&i.size!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>i&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let i=n.value;i.size>=e.minimum||n.issues.push({origin:ir.getSizableOrigin(i),code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}});ie.$ZodCheckSizeEquals=xt.$constructor("$ZodCheckSizeEquals",(t,e)=>{var r;ie.$ZodCheck.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!ir.nullish(i)&&i.size!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=e.size,i.maximum=e.size,i.size=e.size}),t._zod.check=n=>{let i=n.value,o=i.size;if(o===e.size)return;let s=o>e.size;n.issues.push({origin:ir.getSizableOrigin(i),...s?{code:"too_big",maximum:e.size}:{code:"too_small",minimum:e.size},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}});ie.$ZodCheckMaxLength=xt.$constructor("$ZodCheckMaxLength",(t,e)=>{var r;ie.$ZodCheck.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!ir.nullish(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<i&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let i=n.value;if(i.length<=e.maximum)return;let s=ir.getLengthableOrigin(i);n.issues.push({origin:s,code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}});ie.$ZodCheckMinLength=xt.$constructor("$ZodCheckMinLength",(t,e)=>{var r;ie.$ZodCheck.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!ir.nullish(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>i&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let i=n.value;if(i.length>=e.minimum)return;let s=ir.getLengthableOrigin(i);n.issues.push({origin:s,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}});ie.$ZodCheckLengthEquals=xt.$constructor("$ZodCheckLengthEquals",(t,e)=>{var r;ie.$ZodCheck.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!ir.nullish(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=e.length,i.maximum=e.length,i.length=e.length}),t._zod.check=n=>{let i=n.value,o=i.length;if(o===e.length)return;let s=ir.getLengthableOrigin(i),a=o>e.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}});ie.$ZodCheckStringFormat=xt.$constructor("$ZodCheckStringFormat",(t,e)=>{var r,n;ie.$ZodCheck.init(t,e),t._zod.onattach.push(i=>{let o=i._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=i=>{e.pattern.lastIndex=0,!e.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:e.format,input:i.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})});ie.$ZodCheckRegex=xt.$constructor("$ZodCheckRegex",(t,e)=>{ie.$ZodCheckStringFormat.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}});ie.$ZodCheckLowerCase=xt.$constructor("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=FC.lowercase),ie.$ZodCheckStringFormat.init(t,e)});ie.$ZodCheckUpperCase=xt.$constructor("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=FC.uppercase),ie.$ZodCheckStringFormat.init(t,e)});ie.$ZodCheckIncludes=xt.$constructor("$ZodCheckIncludes",(t,e)=>{ie.$ZodCheck.init(t,e);let r=ir.escapeRegex(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(i=>{let o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=i=>{i.value.includes(e.includes,e.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:i.value,inst:t,continue:!e.abort})}});ie.$ZodCheckStartsWith=xt.$constructor("$ZodCheckStartsWith",(t,e)=>{ie.$ZodCheck.init(t,e);let r=new RegExp(`^${ir.escapeRegex(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}});ie.$ZodCheckEndsWith=xt.$constructor("$ZodCheckEndsWith",(t,e)=>{ie.$ZodCheck.init(t,e);let r=new RegExp(`.*${ir.escapeRegex(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});function zD(t,e,r){t.issues.length&&e.issues.push(...ir.prefixIssues(r,t.issues))}ie.$ZodCheckProperty=xt.$constructor("$ZodCheckProperty",(t,e)=>{ie.$ZodCheck.init(t,e),t._zod.check=r=>{let n=e.schema._zod.run({value:r.value[e.property],issues:[]},{});if(n instanceof Promise)return n.then(i=>zD(i,r,e.property));zD(n,r,e.property)}});ie.$ZodCheckMimeType=xt.$constructor("$ZodCheckMimeType",(t,e)=>{ie.$ZodCheck.init(t,e);let r=new Set(e.mime);t._zod.onattach.push(n=>{n._zod.bag.mime=e.mime}),t._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:e.mime,input:n.value.type,inst:t,continue:!e.abort})}});ie.$ZodCheckOverwrite=xt.$constructor("$ZodCheckOverwrite",(t,e)=>{ie.$ZodCheck.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var zC=y($h=>{"use strict";Object.defineProperty($h,"__esModule",{value:!0});$h.Doc=void 0;var jC=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
5
5
|
`).filter(s=>s),i=Math.min(...n.map(s=>s.length-s.trimStart().length)),o=n.map(s=>s.slice(i)).map(s=>" ".repeat(this.indent*2)+s);for(let s of o)this.content.push(s)}compile(){let e=Function,r=this?.args,i=[...(this?.content??[""]).map(o=>` ${o}`)];return new e(...r,i.join(`
|
|
6
6
|
`))}};$h.Doc=jC});var qC=y(Fh=>{"use strict";Object.defineProperty(Fh,"__esModule",{value:!0});Fh.version=void 0;Fh.version={major:4,minor:4,patch:3}});var YC=y(w=>{"use strict";var H3=w&&w.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),G3=w&&w.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Gh=w&&w.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&H3(e,t,r);return G3(e,t),e};Object.defineProperty(w,"__esModule",{value:!0});w.$ZodTuple=w.$ZodIntersection=w.$ZodDiscriminatedUnion=w.$ZodXor=w.$ZodUnion=w.$ZodObjectJIT=w.$ZodObject=w.$ZodArray=w.$ZodDate=w.$ZodVoid=w.$ZodNever=w.$ZodUnknown=w.$ZodAny=w.$ZodNull=w.$ZodUndefined=w.$ZodSymbol=w.$ZodBigIntFormat=w.$ZodBigInt=w.$ZodBoolean=w.$ZodNumberFormat=w.$ZodNumber=w.$ZodCustomStringFormat=w.$ZodJWT=w.$ZodE164=w.$ZodBase64URL=w.$ZodBase64=w.$ZodCIDRv6=w.$ZodCIDRv4=w.$ZodMAC=w.$ZodIPv6=w.$ZodIPv4=w.$ZodISODuration=w.$ZodISOTime=w.$ZodISODate=w.$ZodISODateTime=w.$ZodKSUID=w.$ZodXID=w.$ZodULID=w.$ZodCUID2=w.$ZodCUID=w.$ZodNanoID=w.$ZodEmoji=w.$ZodURL=w.$ZodEmail=w.$ZodUUID=w.$ZodGUID=w.$ZodStringFormat=w.$ZodString=w.clone=w.$ZodType=void 0;w.$ZodCustom=w.$ZodLazy=w.$ZodPromise=w.$ZodFunction=w.$ZodTemplateLiteral=w.$ZodReadonly=w.$ZodPreprocess=w.$ZodCodec=w.$ZodPipe=w.$ZodNaN=w.$ZodCatch=w.$ZodSuccess=w.$ZodNonOptional=w.$ZodPrefault=w.$ZodDefault=w.$ZodNullable=w.$ZodExactOptional=w.$ZodOptional=w.$ZodTransform=w.$ZodFile=w.$ZodLiteral=w.$ZodEnum=w.$ZodSet=w.$ZodMap=w.$ZodRecord=void 0;w.isValidBase64=GC;w.isValidBase64URL=ok;w.isValidJWT=sk;var Yh=Gh(Lh()),G=Gh(cc()),Y3=zC(),Ul=LC(),Ze=Gh(Ph()),Y=Gh(pe()),V3=qC();w.$ZodType=G.$constructor("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=V3.version;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let i of n)for(let o of i._zod.onattach)o(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let i=(s,a,c)=>{let l=Y.aborted(s),u;for(let d of a){if(d._zod.def.when){if(Y.explicitlyAborted(s)||!d._zod.def.when(s))continue}else if(l)continue;let A=s.issues.length,p=d._zod.check(s);if(p instanceof Promise&&c?.async===!1)throw new G.$ZodAsyncError;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==A&&(l||(l=Y.aborted(s,A)))});else{if(s.issues.length===A)continue;l||(l=Y.aborted(s,A))}}return u?u.then(()=>s):s},o=(s,a,c)=>{if(Y.aborted(s))return s.aborted=!0,s;let l=i(a,n,c);if(l instanceof Promise){if(c.async===!1)throw new G.$ZodAsyncError;return l.then(u=>t._zod.parse(u,c))}return t._zod.parse(l,c)};t._zod.run=(s,a)=>{if(a.skipChecks)return t._zod.parse(s,a);if(a.direction==="backward"){let l=t._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return l instanceof Promise?l.then(u=>o(u,s,a)):o(l,s,a)}let c=t._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new G.$ZodAsyncError;return c.then(l=>i(l,n,a))}return i(c,n,a)}}Y.defineLazy(t,"~standard",()=>({validate:i=>{try{let o=(0,Ul.safeParse)(t,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return(0,Ul.safeParseAsync)(t,i).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))});var W3=pe();Object.defineProperty(w,"clone",{enumerable:!0,get:function(){return W3.clone}});w.$ZodString=G.$constructor("$ZodString",(t,e)=>{w.$ZodType.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Ze.string(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}});w.$ZodStringFormat=G.$constructor("$ZodStringFormat",(t,e)=>{Yh.$ZodCheckStringFormat.init(t,e),w.$ZodString.init(t,e)});w.$ZodGUID=G.$constructor("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Ze.guid),w.$ZodStringFormat.init(t,e)});w.$ZodUUID=G.$constructor("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Ze.uuid(n))}else e.pattern??(e.pattern=Ze.uuid());w.$ZodStringFormat.init(t,e)});w.$ZodEmail=G.$constructor("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Ze.email),w.$ZodStringFormat.init(t,e)});w.$ZodURL=G.$constructor("$ZodURL",(t,e)=>{w.$ZodStringFormat.init(t,e),t._zod.check=r=>{try{let n=r.value.trim();if(!e.normalize&&e.protocol?.source===Ze.httpProtocol.source&&!/^https?:\/\//i.test(n)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:t,continue:!e.abort});return}let i=new URL(n);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),e.normalize?r.value=i.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}});w.$ZodEmoji=G.$constructor("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Ze.emoji()),w.$ZodStringFormat.init(t,e)});w.$ZodNanoID=G.$constructor("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Ze.nanoid),w.$ZodStringFormat.init(t,e)});w.$ZodCUID=G.$constructor("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Ze.cuid),w.$ZodStringFormat.init(t,e)});w.$ZodCUID2=G.$constructor("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Ze.cuid2),w.$ZodStringFormat.init(t,e)});w.$ZodULID=G.$constructor("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Ze.ulid),w.$ZodStringFormat.init(t,e)});w.$ZodXID=G.$constructor("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Ze.xid),w.$ZodStringFormat.init(t,e)});w.$ZodKSUID=G.$constructor("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Ze.ksuid),w.$ZodStringFormat.init(t,e)});w.$ZodISODateTime=G.$constructor("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Ze.datetime(e)),w.$ZodStringFormat.init(t,e)});w.$ZodISODate=G.$constructor("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Ze.date),w.$ZodStringFormat.init(t,e)});w.$ZodISOTime=G.$constructor("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Ze.time(e)),w.$ZodStringFormat.init(t,e)});w.$ZodISODuration=G.$constructor("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Ze.duration),w.$ZodStringFormat.init(t,e)});w.$ZodIPv4=G.$constructor("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Ze.ipv4),w.$ZodStringFormat.init(t,e),t._zod.bag.format="ipv4"});w.$ZodIPv6=G.$constructor("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Ze.ipv6),w.$ZodStringFormat.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}});w.$ZodMAC=G.$constructor("$ZodMAC",(t,e)=>{e.pattern??(e.pattern=Ze.mac(e.delimiter)),w.$ZodStringFormat.init(t,e),t._zod.bag.format="mac"});w.$ZodCIDRv4=G.$constructor("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Ze.cidrv4),w.$ZodStringFormat.init(t,e)});w.$ZodCIDRv6=G.$constructor("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Ze.cidrv6),w.$ZodStringFormat.init(t,e),t._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[i,o]=n;if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${i}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function GC(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}w.$ZodBase64=G.$constructor("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Ze.base64),w.$ZodStringFormat.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{GC(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function ok(t){if(!Ze.base64url.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return GC(r)}w.$ZodBase64URL=G.$constructor("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Ze.base64url),w.$ZodStringFormat.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{ok(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}});w.$ZodE164=G.$constructor("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Ze.e164),w.$ZodStringFormat.init(t,e)});function sk(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let i=JSON.parse(atob(n));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||e&&(!("alg"in i)||i.alg!==e))}catch{return!1}}w.$ZodJWT=G.$constructor("$ZodJWT",(t,e)=>{w.$ZodStringFormat.init(t,e),t._zod.check=r=>{sk(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});w.$ZodCustomStringFormat=G.$constructor("$ZodCustomStringFormat",(t,e)=>{w.$ZodStringFormat.init(t,e),t._zod.check=r=>{e.fn(r.value)||r.issues.push({code:"invalid_format",format:e.format,input:r.value,inst:t,continue:!e.abort})}});w.$ZodNumber=G.$constructor("$ZodNumber",(t,e)=>{w.$ZodType.init(t,e),t._zod.pattern=t._zod.bag.pattern??Ze.number,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;let o=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:t,...o?{received:o}:{}}),r}});w.$ZodNumberFormat=G.$constructor("$ZodNumberFormat",(t,e)=>{Yh.$ZodCheckNumberFormat.init(t,e),w.$ZodNumber.init(t,e)});w.$ZodBoolean=G.$constructor("$ZodBoolean",(t,e)=>{w.$ZodType.init(t,e),t._zod.pattern=Ze.boolean,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let i=r.value;return typeof i=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:t}),r}});w.$ZodBigInt=G.$constructor("$ZodBigInt",(t,e)=>{w.$ZodType.init(t,e),t._zod.pattern=Ze.bigint,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:t}),r}});w.$ZodBigIntFormat=G.$constructor("$ZodBigIntFormat",(t,e)=>{Yh.$ZodCheckBigIntFormat.init(t,e),w.$ZodBigInt.init(t,e)});w.$ZodSymbol=G.$constructor("$ZodSymbol",(t,e)=>{w.$ZodType.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;return typeof i=="symbol"||r.issues.push({expected:"symbol",code:"invalid_type",input:i,inst:t}),r}});w.$ZodUndefined=G.$constructor("$ZodUndefined",(t,e)=>{w.$ZodType.init(t,e),t._zod.pattern=Ze.undefined,t._zod.values=new Set([void 0]),t._zod.parse=(r,n)=>{let i=r.value;return typeof i>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:i,inst:t}),r}});w.$ZodNull=G.$constructor("$ZodNull",(t,e)=>{w.$ZodType.init(t,e),t._zod.pattern=Ze.null,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let i=r.value;return i===null||r.issues.push({expected:"null",code:"invalid_type",input:i,inst:t}),r}});w.$ZodAny=G.$constructor("$ZodAny",(t,e)=>{w.$ZodType.init(t,e),t._zod.parse=r=>r});w.$ZodUnknown=G.$constructor("$ZodUnknown",(t,e)=>{w.$ZodType.init(t,e),t._zod.parse=r=>r});w.$ZodNever=G.$constructor("$ZodNever",(t,e)=>{w.$ZodType.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});w.$ZodVoid=G.$constructor("$ZodVoid",(t,e)=>{w.$ZodType.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;return typeof i>"u"||r.issues.push({expected:"void",code:"invalid_type",input:i,inst:t}),r}});w.$ZodDate=G.$constructor("$ZodDate",(t,e)=>{w.$ZodType.init(t,e),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=new Date(r.value)}catch{}let i=r.value,o=i instanceof Date;return o&&!Number.isNaN(i.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:i,...o?{received:"Invalid Date"}:{},inst:t}),r}});function HD(t,e,r){t.issues.length&&e.issues.push(...Y.prefixIssues(r,t.issues)),e.value[r]=t.value}w.$ZodArray=G.$constructor("$ZodArray",(t,e)=>{w.$ZodType.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:t}),r;r.value=Array(i.length);let o=[];for(let s=0;s<i.length;s++){let a=i[s],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?o.push(c.then(l=>HD(l,r,s))):HD(c,r,s)}return o.length?Promise.all(o).then(()=>r):r}});function Hh(t,e,r,n,i,o){let s=r in n;if(t.issues.length){if(i&&o&&!s)return;e.issues.push(...Y.prefixIssues(r,t.issues))}if(!s&&!i){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}t.value===void 0?s&&(e.value[r]=void 0):e.value[r]=t.value}function ak(t){let e=Object.keys(t.shape);for(let n of e)if(!t.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=Y.optionalKeys(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function ck(t,e,r,n,i,o){let s=[],a=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin==="optional",d=c.optout==="optional";for(let A in e){if(A==="__proto__"||a.has(A))continue;if(l==="never"){s.push(A);continue}let p=c.run({value:e[A],issues:[]},n);p instanceof Promise?t.push(p.then(h=>Hh(h,r,A,e,u,d))):Hh(p,r,A,e,u,d)}return s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:e,inst:o}),t.length?Promise.all(t).then(()=>r):r}w.$ZodObject=G.$constructor("$ZodObject",(t,e)=>{if(w.$ZodType.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let c={...a};return Object.defineProperty(e,"shape",{value:c}),c}})}let n=Y.cached(()=>ak(e));Y.defineLazy(t._zod,"propValues",()=>{let a=e.shape,c={};for(let l in a){let u=a[l]._zod;if(u.values){c[l]??(c[l]=new Set);for(let d of u.values)c[l].add(d)}}return c});let i=Y.isObject,o=e.catchall,s;t._zod.parse=(a,c)=>{s??(s=n.value);let l=a.value;if(!i(l))return a.issues.push({expected:"object",code:"invalid_type",input:l,inst:t}),a;a.value={};let u=[],d=s.shape;for(let A of s.keys){let p=d[A],h=p._zod.optin==="optional",f=p._zod.optout==="optional",E=p._zod.run({value:l[A],issues:[]},c);E instanceof Promise?u.push(E.then(S=>Hh(S,a,A,l,h,f))):Hh(E,a,A,l,h,f)}return o?ck(u,l,a,c,n.value,t):u.length?Promise.all(u).then(()=>a):a}});w.$ZodObjectJIT=G.$constructor("$ZodObjectJIT",(t,e)=>{w.$ZodObject.init(t,e);let r=t._zod.parse,n=Y.cached(()=>ak(e)),i=A=>{let p=new Y3.Doc(["shape","payload","ctx"]),h=n.value,f=_=>{let v=Y.esc(_);return`shape[${v}]._zod.run({ value: input[${v}], issues: [] }, ctx)`};p.write("const input = payload.value;");let E=Object.create(null),S=0;for(let _ of h.keys)E[_]=`key_${S++}`;p.write("const newResult = {};");for(let _ of h.keys){let v=E[_],T=Y.esc(_),L=A[_],k=L?._zod?.optin==="optional",P=L?._zod?.optout==="optional";p.write(`const ${v} = ${f(_)};`),k&&P?p.write(`
|
|
7
7
|
if (${v}.issues.length) {
|
|
@@ -98,11 +98,11 @@ _Interactive visual in superglue._`}}function ooe(t){return[t.title?`**${t.title
|
|
|
98
98
|
`)}});var soe,aO,sO,aoe,coe,loe,uoe,cO=ft(()=>{"use strict";soe=t=>{let e=sO(t,0);if(e===void 0||!coe(t[e]))return;let r=sO(t,e+1);if(r!==void 0)return loe(t,e,r)},aO=soe,sO=(t,e)=>{for(let r=e;r<t.length;r+=1){let n=t[r];if(!aoe(n))return r}},aoe=t=>t===" "||t===" "||t===`
|
|
99
99
|
`||t==="\r",coe=t=>t==="{"||t==="[",loe=(t,e,r)=>{let n;for(let i=r-1;i>e;i-=1){let o=t[i];if(o==="\r")return;if(o===`
|
|
100
100
|
`)return uoe(n);if(n===void 0)n=o;else if(n[0]===o)n+=o;else return}},uoe=t=>t===void 0?0:t[0]===" "?t.length:t});var lO,fb,doe,Aoe,uO=ft(()=>{"use strict";lO=(t,e)=>{let r=fb(t,"toPrecision",e,e);return r===void 0?fb(t,"toExponential",e,e):r},fb=(t,e,r,n)=>{let o=t[e](n).replace(doe,"$1").replace(Aoe,"$1");return o.length<=r?o:n===1?void 0:fb(t,e,r,n-1)},doe=/(e)\+/iu,Aoe=/\.?0*($|e)/iu});var AO,poe,hoe,dO,pO=ft(()=>{"use strict";AO=(t,e)=>{if(typeof t!="string")throw new TypeError(`Input must be a JSON string: ${t}`);poe(e)},poe=t=>{if(hoe(t),t<0)throw new TypeError(`"maxSize" argument must be positive: ${t}`);if(t<dO)throw new TypeError(`"maxSize" argument must be at least ${dO}: ${t}`)},hoe=t=>{if(t===void 0)throw new TypeError('"maxSize" argument must be defined');if(!Number.isInteger(t))throw new TypeError(`"maxSize" argument must be an integer: ${t}`)},dO=7});var hg,hO,fg,foe,goe,moe,yoe,fO,Eoe,Ioe,Coe,boe,Soe,woe,gb=ft(()=>{"use strict";hg=(t,e,r)=>{let n=fO(e,r);return hO(t,e,n)},hO=(t,e,r)=>{if(r>=e)return r;let n=t[r];return n>=Soe&&n<=woe?hO(t,e,r+1):r},fg=(t,e,r)=>{if(r===void 0)return r;let n=fO(e,r);return foe(t,n)},foe=(t,e)=>goe(t,e)?e-3:moe(t,e)?e-2:yoe(t,e)?e-1:e,goe=(t,e)=>e>=3&&t[e-3]>=Eoe&&t[e-3]<=Ioe,moe=(t,e)=>e>=2&&t[e-2]>=Coe,yoe=(t,e)=>e>=1&&t[e-1]>=boe,fO=(t,e)=>e<0||Object.is(e,-0)?Math.max(t+e,0):e,Eoe=240,Ioe=244,Coe=224,boe=194,Soe=128,woe=191});var gO,mO=ft(()=>{"use strict";gb();gO=(t,e,r)=>{let n=globalThis.Buffer.from(t),i=hg(n,n.length,e),o=fg(n,n.length,r);return i===0&&o>=n.length?n.toString():n.toString("utf8",i,o)}});var yO,EO=ft(()=>{"use strict";yO=/[\uD800-\uDFFF]/gu});var gg,Boe,Eb=ft(()=>{"use strict";EO();gg=t=>Boe(t)?t.replace(yO,"\uFFFD"):t,Boe=t=>{for(let e=0;e<t.length;e+=1){let r=t.codePointAt(e);if(r>=55296&&r<=57343)return!0}return!1}});var Ib,IO=ft(()=>{"use strict";Ib=({input:t,targetByteCount:e,firstStartSurrogate:r,lastStartSurrogate:n,firstEndSurrogate:i,lastEndSurrogate:o,increment:s,canBacktrack:a,shift:c,charIndexInit:l})=>{let u=l,d=u,A=0;for(;A<e;u+=s){d=u;let h=t.charCodeAt(u);if(Number.isNaN(h))break;if(h<=127){A+=1;continue}if(h<=2047){A+=2;continue}if(A+=3,h<r||h>n)continue;let f=t.charCodeAt(u+s);Number.isNaN(f)||f<i||f>o||(A+=1,u+=s)}return(a&&A>e?d:u)+c}});var Cb,koe,Roe,CO=ft(()=>{"use strict";IO();Cb=(t,e,r)=>e<0||Object.is(e,-0)?Roe(t,e,r):koe(t,e,r),koe=(t,e,r)=>Ib({input:t,targetByteCount:e,firstStartSurrogate:55296,lastStartSurrogate:56319,firstEndSurrogate:56320,lastEndSurrogate:57343,increment:1,canBacktrack:r,shift:0,charIndexInit:0}),Roe=(t,e,r)=>Ib({input:t,targetByteCount:-e,firstStartSurrogate:56320,lastStartSurrogate:57343,firstEndSurrogate:55296,lastEndSurrogate:56319,increment:-1,canBacktrack:!r,shift:1,charIndexInit:t.length-1})});var mg,Noe,bO=ft(()=>{"use strict";Eb();CO();mg=(t,e,r)=>{let n=Cb(t,e,!1),i=Noe(t,r),o=n===0&&i===void 0?t:t.slice(n,i);return gg(o)},Noe=(t,e)=>{if(e===void 0)return e;let r=Cb(t,e,!0);return r===t.length?void 0:r}});var wO,Ooe,bb,SO,xoe,Uoe,yg,_O=ft(()=>{"use strict";gb();wO=(t,e,r)=>{let{textEncoder:n,textDecoder:i}=Ooe(),o=xoe(t),{written:s}=n.encodeInto(t,o),a=hg(o,s,e),c=fg(o,s,r),l=c===void 0?s:Math.min(c,s),u=o.subarray(a,l);return i.decode(u)},Ooe=()=>(bb===void 0&&(bb=new globalThis.TextEncoder,SO=new globalThis.TextDecoder("utf8",{fatal:!1})),{textEncoder:bb,textDecoder:SO}),xoe=t=>{let e=t.length*3;return e>Uoe?new Uint8Array(e):((yg===void 0||yg.length<e)&&(yg=new Uint8Array(e)),yg)},Uoe=1e5});var BO,Sb,vO,QO=ft(()=>{"use strict";BO=(t,e)=>{if(e===void 0)return e;let r=Sb(t,e);return r>=t.length*vO?void 0:r},Sb=(t,e)=>e<=t.length*-vO?0:e,vO=4});var TO,Moe,Poe,DO,kO=ft(()=>{"use strict";TO=(t,e,r)=>{if(typeof t!="string")throw new TypeError(`First argument must be a string: ${t}`);Moe(e),Poe(r)},Moe=t=>{if(t===void 0)throw new TypeError("Second argument is required.");DO("Second",t)},Poe=t=>{t!==void 0&&DO("Third",t)},DO=(t,e)=>{if(!Number.isInteger(e))throw new TypeError(`${t} argument must be an integer: ${e}`)}});var RO,Loe,wb,NO=ft(()=>{"use strict";RO=t=>{let e=!0,r=0;for(let n=0;n<wb;n+=1){let i=Loe(t,n);i<=127||(e&&(e=!1),i>2047&&(r+=1))}return{asciiOnly:e,longCharsPercentage:r/wb}},Loe=(t,e)=>{let r=wb-1,n=1-(r-e)/r,i=Math.round(n*(t.length-1));return t.charCodeAt(i)},wb=50});var $oe,OO,Foe,joe,zoe,qoe,xO,UO=ft(()=>{"use strict";mO();bO();_O();QO();Eb();kO();NO();$oe=(t,e,r)=>{if(TO(t,e,r),t==="")return t;let n=Sb(t,e),i=BO(t,r);return i===void 0&&Object.is(n,0)?gg(t):Foe(t,n,i)},OO=$oe,Foe=(t,e,r)=>{if(t.length<=joe)return mg(t,e,r);let{asciiOnly:n,longCharsPercentage:i}=RO(t);return n?qoe(t,e,r):i>=zoe?mg(t,e,r):xO(t,e,r)},joe=200,zoe=.4,qoe=(t,e,r)=>"Buffer"in globalThis&&"from"in globalThis.Buffer?gO(t,e,r):xO(t,e,r),xO=(t,e,r)=>"TextEncoder"in globalThis?wO(t,e,r):mg(t,e,r)});var PO,Hoe,Goe,Yoe,Voe,rA,MO,LO=ft(()=>{"use strict";UO();PO=(t,e)=>{let r=JSON.stringify(t),n=Yoe(r),i=OO(n,0,e-MO.length-rA.length*2),s=`${Hoe(i)}${MO}`;return Voe(s)},Hoe=t=>t.replace(Goe,""),Goe=/(\\|\\u[0-9a-fA-F]{0,3})$/u,Yoe=t=>t.slice(rA.length,-rA.length),Voe=t=>`${rA}${t}${rA}`,rA='"',MO="..."});var $O,FO=ft(()=>{"use strict";$O=t=>globalThis.Buffer.byteLength(t)});var _b,Woe,Joe,Zoe,Koe,Xoe,ese,jO=ft(()=>{"use strict";_b=t=>{let e=t.length,r=e;for(let n=0;n<e;n+=1){let i=t.charCodeAt(n);if(i<=Woe)continue;if(i<=Joe){r+=1;continue}if(r+=2,i<Zoe||i>Koe)continue;let o=t.charCodeAt(n+1);o<Xoe||o>ese||(n+=1)}return r},Woe=127,Joe=2047,Zoe=55296,Koe=56319,Xoe=56320,ese=57343});var zO,tse,rse,nse,Eg,qO=ft(()=>{"use strict";zO=()=>tse.bind(void 0,new TextEncoder),tse=(t,e)=>{let r=rse(e);return t.encodeInto(e,r).written},rse=t=>{let e=t.length*3;return e>nse?new Uint8Array(e):((Eg===void 0||Eg.length<e)&&(Eg=new Uint8Array(e)),Eg)},nse=1e5});var ose,sse,HO,GO=ft(()=>{"use strict";FO();jO();qO();ose=()=>"Buffer"in globalThis&&"byteLength"in globalThis.Buffer?$O:"TextEncoder"in globalThis?sse.bind(void 0,zO()):_b,sse=(t,e)=>e.length<100?_b(e):t(e),HO=ose()});var YO,ase,cse,lse,use,Bb,VO=ft(()=>{"use strict";GO();YO=t=>{if(t===null)return ase;if(t===!0)return cse;if(t===!1)return lse;let e=typeof t;return e==="object"?use:e==="number"?JSON.stringify(t).length:Bb(t)},ase=4,cse=4,lse=5,use=2,Bb=t=>HO(JSON.stringify(t))});var Ig,JO,ZO,KO,dse,XO,WO,ex,Ase,nA=ft(()=>{"use strict";VO();Ig=({size:t,increment:e,maxSize:r,truncatedProps:n,path:i,value:o})=>{let s=t+e,a=s>r;return a?{size:t,stop:a,truncatedProps:[...n,{path:i,value:o}]}:{size:s,stop:a,truncatedProps:n}},JO=t=>YO(t),ZO=(t,e,r)=>{let n=XO({empty:t,indent:e,depth:r,keySpaceSize:0}),i=ex(t);return n+i},KO=({key:t,empty:e,indent:r,depth:n})=>{let i=XO({empty:e,indent:r,depth:n,keySpaceSize:1}),o=Bb(t),s=ex(e);return i+o+dse+s},dse=1,XO=({empty:t,indent:e,depth:r,keySpaceSize:n})=>{if(e===void 0)return 0;let i=WO+e*(r+1),o=t?WO+e*r:0;return n+i+o},WO=1,ex=t=>t?0:Ase,Ase=1});var Cg,pse,vb=ft(()=>{"use strict";nA();Cg=({parent:t,truncatedProps:e,path:r,increment:n,maxSize:i,key:o,empty:s,size:a,truncateValue:c,indent:l,depth:u})=>{let d=t[o],A=[...r,o],{size:p,stop:h,truncatedProps:f}=Ig({size:a,increment:n,maxSize:i,truncatedProps:e,path:A,value:d});return h?{empty:s,size:p,truncatedProps:f}:pse({value:d,truncatedProps:e,path:A,maxSize:i,empty:s,size:a,newSize:p,truncateValue:c,indent:l,depth:u})},pse=({value:t,truncatedProps:e,path:r,maxSize:n,empty:i,size:o,newSize:s,truncateValue:a,indent:c,depth:l})=>{let{value:u,size:d,truncatedProps:A}=a({value:t,truncatedProps:e,path:r,size:s,maxSize:n,indent:c,depth:l+1});return u===void 0?{empty:i,size:o,truncatedProps:A}:{empty:!1,size:d,value:u,truncatedProps:A}}});var tx,rx=ft(()=>{"use strict";vb();nA();tx=({array:t,truncatedProps:e,path:r,size:n,maxSize:i,truncateValue:o,indent:s,depth:a})=>{let c=[],l={empty:!0,size:n,truncatedProps:e};for(let u=0;u<t.length;u+=1){let d=ZO(l.empty,s,a);l=Cg({parent:t,truncatedProps:l.truncatedProps,path:r,increment:d,maxSize:i,key:u,empty:l.empty,size:l.size,truncateValue:o,indent:s,depth:a}),l.value!==void 0&&c.push(l.value)}return{value:c,size:l.size,truncatedProps:l.truncatedProps}}});var nx,ix=ft(()=>{"use strict";vb();nA();nx=({object:t,truncatedProps:e,path:r,size:n,maxSize:i,truncateValue:o,indent:s,depth:a})=>{let c={},l={empty:!0,size:n,truncatedProps:e};for(let u in t){let d=KO({key:u,empty:l.empty,indent:s,depth:a});l=Cg({parent:t,truncatedProps:l.truncatedProps,path:r,increment:d,maxSize:i,key:u,empty:l.empty,size:l.size,truncateValue:o,indent:s,depth:a}),l.value!==void 0&&(c[u]=l.value)}return{value:c,size:l.size,truncatedProps:l.truncatedProps}}});var bg,hse,ox=ft(()=>{"use strict";rx();ix();nA();bg=({value:t,truncatedProps:e,path:r,size:n,maxSize:i,indent:o,depth:s})=>{let a=JO(t),{size:c,stop:l,truncatedProps:u}=Ig({size:n,increment:a,maxSize:i,truncatedProps:e,path:r,value:t});return l?{value:void 0,size:c,truncatedProps:u}:hse({value:t,truncatedProps:u,path:r,size:c,maxSize:i,indent:o,depth:s})},hse=({value:t,truncatedProps:e,path:r,size:n,maxSize:i,indent:o,depth:s})=>typeof t!="object"||t===null?{value:t,size:n,truncatedProps:e}:Array.isArray(t)?tx({array:t,truncatedProps:e,path:r,size:n,maxSize:i,truncateValue:bg,indent:o,depth:s}):nx({object:t,truncatedProps:e,path:r,size:n,maxSize:i,truncateValue:bg,indent:o,depth:s})});var sx={};yD(sx,{default:()=>gse});var fse,gse,mse,yse,Ese,ax=ft(()=>{"use strict";cO();uO();pO();LO();ox();fse=(t,e)=>{AO(t,e);let r=mse(t),n=yse(t),{value:i,truncatedProps:o}=bg({value:n,truncatedProps:[],path:[],size:0,maxSize:e,indent:r,depth:0});return{jsonString:Ese({newValue:i,value:n,maxSize:e,indent:r}),truncatedProps:o}},gse=fse,mse=t=>{let e=aO(t);return typeof e=="string"?e.length:e},yse=t=>{try{return JSON.parse(t)}catch(e){throw new TypeError(`Invalid JSON string: "${t}"
|
|
101
|
-
${e.message}`)}},Ese=({newValue:t,value:e,maxSize:r,indent:n})=>t!==void 0?JSON.stringify(t,void 0,n):typeof e=="number"?lO(e,r):PO(e,r)});var lx=y(cx=>{"use strict";Object.defineProperty(cx,"__esModule",{value:!0})});var sa=y(Sg=>{"use strict";Object.defineProperty(Sg,"__esModule",{value:!0});Sg.CronField=void 0;var Qb=class t{#e=!1;#t=!1;#n=!1;#i=[];options={rawValue:""};static get min(){throw new Error("min must be overridden")}static get max(){throw new Error("max must be overridden")}static get chars(){return Object.freeze([])}static get validChars(){return/^[?,*\dH/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}static get constraints(){return{min:this.min,max:this.max,chars:this.chars,validChars:this.validChars}}constructor(e,r={rawValue:""}){if(!Array.isArray(e))throw new Error(`${this.constructor.name} Validation error, values is not an array`);if(!(e.length>0))throw new Error(`${this.constructor.name} Validation error, values contains no values`);this.options={...r,rawValue:r.rawValue??""},this.#i=e.sort(t.sorter),this.#n=this.options.wildcard!==void 0?this.options.wildcard:this.#o(),this.#e=this.options.rawValue.includes("L")||e.includes("L"),this.#t=this.options.rawValue.includes("?")||e.includes("?")}get min(){return this.constructor.min}get max(){return this.constructor.max}get chars(){return this.constructor.chars}get hasLastChar(){return this.#e}get hasQuestionMarkChar(){return this.#t}get isWildcard(){return this.#n}get values(){return this.#i}static sorter(e,r){let n=typeof e=="number",i=typeof r=="number";return n&&i?e-r:!n&&!i?e.localeCompare(r):n?-1:1}static findNearestValueInList(e,r,n=!1){if(n){for(let i=e.length-1;i>=0;i--)if(e[i]<r)return e[i];return null}for(let i=0;i<e.length;i++)if(e[i]>r)return e[i];return null}findNearestValue(e,r=!1){return this.constructor.findNearestValueInList(this.values,e,r)}serialize(){return{wildcard:this.#n,values:this.#i}}validate(){let e,r=this.chars.length>0?` or chars ${this.chars.join("")}`:"",n=a=>c=>new RegExp(`^\\d{0,2}${c}$`).test(a),i=a=>(e=a,typeof a=="number"?a>=this.min&&a<=this.max:this.chars.some(n(a)));if(!this.#i.every(i))throw new Error(`${this.constructor.name} Validation error, got value ${e} expected range ${this.min}-${this.max}${r}`);let s=this.#i.find((a,c)=>this.#i.indexOf(a)!==c);if(s)throw new Error(`${this.constructor.name} Validation error, duplicate values found: ${s}`)}#o(){return this.options.rawValue.length>0?["*","?"].includes(this.options.rawValue):Array.from({length:this.max-this.min+1},(e,r)=>r+this.min).every(e=>this.#i.includes(e))}};Sg.CronField=Qb});var ux=y(wg=>{"use strict";Object.defineProperty(wg,"__esModule",{value:!0});wg.CronDayOfMonth=void 0;var Ise=sa(),Cse=1,bse=31,Sse=Object.freeze(["L"]),Tb=class extends Ise.CronField{static get min(){return Cse}static get max(){return bse}static get chars(){return Sse}static get validChars(){return/^[?,*\dLH/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}constructor(e,r){super(e,r),this.validate()}get values(){return super.values}};wg.CronDayOfMonth=Tb});var dx=y(_g=>{"use strict";Object.defineProperty(_g,"__esModule",{value:!0});_g.CronDayOfWeek=void 0;var wse=sa(),_se=0,Bse=7,vse=Object.freeze(["L"]),Db=class extends wse.CronField{static get min(){return _se}static get max(){return Bse}static get chars(){return vse}static get validChars(){return/^[?,*\dLH#/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}constructor(e,r){super(e,r),this.validate()}get values(){return super.values}get nthDay(){return this.options.nthDayOfWeek??0}};_g.CronDayOfWeek=Db});var Ax=y(Bg=>{"use strict";Object.defineProperty(Bg,"__esModule",{value:!0});Bg.CronHour=void 0;var Qse=sa(),Tse=0,Dse=23,kse=Object.freeze([]),kb=class extends Qse.CronField{static get min(){return Tse}static get max(){return Dse}static get chars(){return kse}constructor(e,r){super(e,r),this.validate()}get values(){return super.values}};Bg.CronHour=kb});var px=y(vg=>{"use strict";Object.defineProperty(vg,"__esModule",{value:!0});vg.CronMinute=void 0;var Rse=sa(),Nse=0,Ose=59,xse=Object.freeze([]),Rb=class extends Rse.CronField{static get min(){return Nse}static get max(){return Ose}static get chars(){return xse}constructor(e,r){super(e,r),this.validate()}get values(){return super.values}};vg.CronMinute=Rb});var zU=y(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});var bs=class extends Error{},jb=class extends bs{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},zb=class extends bs{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},qb=class extends bs{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},la=class extends bs{},xg=class extends bs{constructor(e){super(`Invalid unit ${e}`)}},dr=class extends bs{},$o=class extends bs{constructor(){super("Zone is an abstract class")}},ee="numeric",_i="short",yn="long",Ug={year:ee,month:ee,day:ee},qx={year:ee,month:_i,day:ee},Use={year:ee,month:_i,day:ee,weekday:_i},Hx={year:ee,month:yn,day:ee},Gx={year:ee,month:yn,day:ee,weekday:yn},Yx={hour:ee,minute:ee},Vx={hour:ee,minute:ee,second:ee},Wx={hour:ee,minute:ee,second:ee,timeZoneName:_i},Jx={hour:ee,minute:ee,second:ee,timeZoneName:yn},Zx={hour:ee,minute:ee,hourCycle:"h23"},Kx={hour:ee,minute:ee,second:ee,hourCycle:"h23"},Xx={hour:ee,minute:ee,second:ee,hourCycle:"h23",timeZoneName:_i},eU={hour:ee,minute:ee,second:ee,hourCycle:"h23",timeZoneName:yn},tU={year:ee,month:ee,day:ee,hour:ee,minute:ee},rU={year:ee,month:ee,day:ee,hour:ee,minute:ee,second:ee},nU={year:ee,month:_i,day:ee,hour:ee,minute:ee},iU={year:ee,month:_i,day:ee,hour:ee,minute:ee,second:ee},Mse={year:ee,month:_i,day:ee,weekday:_i,hour:ee,minute:ee},oU={year:ee,month:yn,day:ee,hour:ee,minute:ee,timeZoneName:_i},sU={year:ee,month:yn,day:ee,hour:ee,minute:ee,second:ee,timeZoneName:_i},aU={year:ee,month:yn,day:ee,weekday:yn,hour:ee,minute:ee,timeZoneName:yn},cU={year:ee,month:yn,day:ee,weekday:yn,hour:ee,minute:ee,second:ee,timeZoneName:yn},da=class{get type(){throw new $o}get name(){throw new $o}get ianaName(){return this.name}get isUniversal(){throw new $o}offsetName(e,r){throw new $o}formatOffset(e,r){throw new $o}offset(e){throw new $o}equals(e){throw new $o}get isValid(){throw new $o}},Nb=null,lA=class t extends da{static get instance(){return Nb===null&&(Nb=new t),Nb}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return EU(e,r,n)}formatOffset(e,r){return cA(this.offset(e),r)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}},Hb=new Map;function Pse(t){let e=Hb.get(t);return e===void 0&&(e=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"}),Hb.set(t,e)),e}var Lse={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function $se(t,e){let r=t.format(e).replace(/\u200E/g,""),n=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(r),[,i,o,s,a,c,l,u]=n;return[s,i,o,a,c,l,u]}function Fse(t,e){let r=t.formatToParts(e),n=[];for(let i=0;i<r.length;i++){let{type:o,value:s}=r[i],a=Lse[o];o==="era"?n[a]=s:Qe(a)||(n[a]=parseInt(s,10))}return n}var Ob=new Map,Ss=class t extends da{static create(e){let r=Ob.get(e);return r===void 0&&Ob.set(e,r=new t(e)),r}static resetCache(){Ob.clear(),Hb.clear()}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=t.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return EU(e,r,n,this.name)}formatOffset(e,r){return cA(this.offset(e),r)}offset(e){if(!this.valid)return NaN;let r=new Date(e);if(isNaN(r))return NaN;let n=Pse(this.name),[i,o,s,a,c,l,u]=n.formatToParts?Fse(n,r):$se(n,r);a==="BC"&&(i=-Math.abs(i)+1);let A=zg({year:i,month:o,day:s,hour:c===24?0:c,minute:l,second:u,millisecond:0}),p=+r,h=p%1e3;return p-=h>=0?h:1e3+h,(A-p)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}},hx={};function jse(t,e={}){let r=JSON.stringify([t,e]),n=hx[r];return n||(n=new Intl.ListFormat(t,e),hx[r]=n),n}var Gb=new Map;function Yb(t,e={}){let r=JSON.stringify([t,e]),n=Gb.get(r);return n===void 0&&(n=new Intl.DateTimeFormat(t,e),Gb.set(r,n)),n}var Vb=new Map;function zse(t,e={}){let r=JSON.stringify([t,e]),n=Vb.get(r);return n===void 0&&(n=new Intl.NumberFormat(t,e),Vb.set(r,n)),n}var Wb=new Map;function qse(t,e={}){let{base:r,...n}=e,i=JSON.stringify([t,n]),o=Wb.get(i);return o===void 0&&(o=new Intl.RelativeTimeFormat(t,e),Wb.set(i,o)),o}var oA=null;function Hse(){return oA||(oA=new Intl.DateTimeFormat().resolvedOptions().locale,oA)}var Jb=new Map;function lU(t){let e=Jb.get(t);return e===void 0&&(e=new Intl.DateTimeFormat(t).resolvedOptions(),Jb.set(t,e)),e}var Zb=new Map;function Gse(t){let e=Zb.get(t);if(!e){let r=new Intl.Locale(t);e="getWeekInfo"in r?r.getWeekInfo():r.weekInfo,"minimalDays"in e||(e={...uU,...e}),Zb.set(t,e)}return e}function Yse(t){let e=t.indexOf("-x-");e!==-1&&(t=t.substring(0,e));let r=t.indexOf("-u-");if(r===-1)return[t];{let n,i;try{n=Yb(t).resolvedOptions(),i=t}catch{let c=t.substring(0,r);n=Yb(c).resolvedOptions(),i=c}let{numberingSystem:o,calendar:s}=n;return[i,o,s]}}function Vse(t,e,r){return(r||e)&&(t.includes("-u-")||(t+="-u"),r&&(t+=`-ca-${r}`),e&&(t+=`-nu-${e}`)),t}function Wse(t){let e=[];for(let r=1;r<=12;r++){let n=Bt.utc(2009,r,1);e.push(t(n))}return e}function Jse(t){let e=[];for(let r=1;r<=7;r++){let n=Bt.utc(2016,11,13+r);e.push(t(n))}return e}function Qg(t,e,r,n){let i=t.listingMode();return i==="error"?null:i==="en"?r(e):n(e)}function Zse(t){return t.numberingSystem&&t.numberingSystem!=="latn"?!1:t.numberingSystem==="latn"||!t.locale||t.locale.startsWith("en")||lU(t.locale).numberingSystem==="latn"}var Kb=class{constructor(e,r,n){this.padTo=n.padTo||0,this.floor=n.floor||!1;let{padTo:i,floor:o,...s}=n;if(!r||Object.keys(s).length>0){let a={useGrouping:!1,...n};n.padTo>0&&(a.minimumIntegerDigits=n.padTo),this.inf=zse(e,a)}}format(e){if(this.inf){let r=this.floor?Math.floor(e):e;return this.inf.format(r)}else{let r=this.floor?Math.floor(e):lS(e,3);return Wt(r,this.padTo)}}},Xb=class{constructor(e,r,n){this.opts=n,this.originalZone=void 0;let i;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){let s=-1*(e.offset/60),a=s>=0?`Etc/GMT+${s}`:`Etc/GMT${s}`;e.offset!==0&&Ss.create(a).valid?(i=a,this.dt=e):(i="UTC",this.dt=e.offset===0?e:e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type==="system"?this.dt=e:e.zone.type==="iana"?(this.dt=e,i=e.zone.name):(i="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);let o={...this.opts};o.timeZone=o.timeZone||i,this.dtf=Yb(r,o)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){let e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(r=>{if(r.type==="timeZoneName"){let n=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...r,value:n}}else return r}):e}resolvedOptions(){return this.dtf.resolvedOptions()}},eS=class{constructor(e,r,n){this.opts={style:"long",...n},!r&&mU()&&(this.rtf=qse(e,n))}format(e,r){return this.rtf?this.rtf.format(e,r):yae(r,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,r){return this.rtf?this.rtf.formatToParts(e,r):[]}},uU={firstDay:1,minimalDays:4,weekend:[6,7]},mt=class t{static fromOpts(e){return t.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,r,n,i,o=!1){let s=e||yt.defaultLocale,a=s||(o?"en-US":Hse()),c=r||yt.defaultNumberingSystem,l=n||yt.defaultOutputCalendar,u=rS(i)||yt.defaultWeekSettings;return new t(a,c,l,u,s)}static resetCache(){oA=null,Gb.clear(),Vb.clear(),Wb.clear(),Jb.clear(),Zb.clear()}static fromObject({locale:e,numberingSystem:r,outputCalendar:n,weekSettings:i}={}){return t.create(e,r,n,i)}constructor(e,r,n,i,o){let[s,a,c]=Yse(e);this.locale=s,this.numberingSystem=r||a||null,this.outputCalendar=n||c||null,this.weekSettings=i,this.intl=Vse(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=o,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=Zse(this)),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),r=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&r?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:t.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,rS(e.weekSettings)||this.weekSettings,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,r=!1){return Qg(this,e,bU,()=>{let n=this.intl==="ja"||this.intl.startsWith("ja-");r&=!n;let i=r?{month:e,day:"numeric"}:{month:e},o=r?"format":"standalone";if(!this.monthsCache[o][e]){let s=n?a=>this.dtFormatter(a,i).format():a=>this.extract(a,i,"month");this.monthsCache[o][e]=Wse(s)}return this.monthsCache[o][e]})}weekdays(e,r=!1){return Qg(this,e,_U,()=>{let n=r?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},i=r?"format":"standalone";return this.weekdaysCache[i][e]||(this.weekdaysCache[i][e]=Jse(o=>this.extract(o,n,"weekday"))),this.weekdaysCache[i][e]})}meridiems(){return Qg(this,void 0,()=>BU,()=>{if(!this.meridiemCache){let e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[Bt.utc(2016,11,13,9),Bt.utc(2016,11,13,19)].map(r=>this.extract(r,e,"dayperiod"))}return this.meridiemCache})}eras(e){return Qg(this,e,vU,()=>{let r={era:e};return this.eraCache[e]||(this.eraCache[e]=[Bt.utc(-40,1,1),Bt.utc(2017,1,1)].map(n=>this.extract(n,r,"era"))),this.eraCache[e]})}extract(e,r,n){let i=this.dtFormatter(e,r),o=i.formatToParts(),s=o.find(a=>a.type.toLowerCase()===n);return s?s.value:null}numberFormatter(e={}){return new Kb(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,r={}){return new Xb(e,this.intl,r)}relFormatter(e={}){return new eS(this.intl,this.isEnglish(),e)}listFormatter(e={}){return jse(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||lU(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:yU()?Gse(this.locale):uU}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}toString(){return`Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`}},xb=null,En=class t extends da{static get utcInstance(){return xb===null&&(xb=new t(0)),xb}static instance(e){return e===0?t.utcInstance:new t(e)}static parseSpecifier(e){if(e){let r=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(r)return new t(qg(r[1],r[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${cA(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${cA(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,r){return cA(this.fixed,r)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}},Mg=class extends da{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}};function ca(t,e){if(Qe(t)||t===null)return e;if(t instanceof da)return t;if(nae(t)){let r=t.toLowerCase();return r==="default"?e:r==="local"||r==="system"?lA.instance:r==="utc"||r==="gmt"?En.utcInstance:En.parseSpecifier(r)||Ss.create(t)}else return ua(t)?En.instance(t):typeof t=="object"&&"offset"in t&&typeof t.offset=="function"?t:new Mg(t)}var oS={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},fx={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},Kse=oS.hanidec.replace(/[\[|\]]/g,"").split("");function Xse(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(t[r].search(oS.hanidec)!==-1)e+=Kse.indexOf(t[r]);else for(let i in fx){let[o,s]=fx[i];n>=o&&n<=s&&(e+=n-o)}}return parseInt(e,10)}else return e}var tS=new Map;function eae(){tS.clear()}function Si({numberingSystem:t},e=""){let r=t||"latn",n=tS.get(r);n===void 0&&(n=new Map,tS.set(r,n));let i=n.get(e);return i===void 0&&(i=new RegExp(`${oS[r]}${e}`),n.set(e,i)),i}var gx=()=>Date.now(),mx="system",yx=null,Ex=null,Ix=null,Cx=60,bx,Sx=null,yt=class{static get now(){return gx}static set now(e){gx=e}static set defaultZone(e){mx=e}static get defaultZone(){return ca(mx,lA.instance)}static get defaultLocale(){return yx}static set defaultLocale(e){yx=e}static get defaultNumberingSystem(){return Ex}static set defaultNumberingSystem(e){Ex=e}static get defaultOutputCalendar(){return Ix}static set defaultOutputCalendar(e){Ix=e}static get defaultWeekSettings(){return Sx}static set defaultWeekSettings(e){Sx=rS(e)}static get twoDigitCutoffYear(){return Cx}static set twoDigitCutoffYear(e){Cx=e%100}static get throwOnInvalid(){return bx}static set throwOnInvalid(e){bx=e}static resetCaches(){mt.resetCache(),Ss.resetCache(),Bt.resetCache(),eae()}},mn=class{constructor(e,r){this.reason=e,this.explanation=r}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}},dU=[0,31,59,90,120,151,181,212,243,273,304,334],AU=[0,31,60,91,121,152,182,213,244,274,305,335];function Wn(t,e){return new mn("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function sS(t,e,r){let n=new Date(Date.UTC(t,e-1,r));t<100&&t>=0&&n.setUTCFullYear(n.getUTCFullYear()-1900);let i=n.getUTCDay();return i===0?7:i}function pU(t,e,r){return r+(dA(t)?AU:dU)[e-1]}function hU(t,e){let r=dA(t)?AU:dU,n=r.findIndex(o=>o<e),i=e-r[n];return{month:n+1,day:i}}function aS(t,e){return(t-e+7)%7+1}function Pg(t,e=4,r=1){let{year:n,month:i,day:o}=t,s=pU(n,i,o),a=aS(sS(n,i,o),r),c=Math.floor((s-a+14-e)/7),l;return c<1?(l=n-1,c=uA(l,e,r)):c>uA(n,e,r)?(l=n+1,c=1):l=n,{weekYear:l,weekNumber:c,weekday:a,...Hg(t)}}function wx(t,e=4,r=1){let{weekYear:n,weekNumber:i,weekday:o}=t,s=aS(sS(n,1,e),r),a=Yl(n),c=i*7+o-s-7+e,l;c<1?(l=n-1,c+=Yl(l)):c>a?(l=n+1,c-=Yl(n)):l=n;let{month:u,day:d}=hU(l,c);return{year:l,month:u,day:d,...Hg(t)}}function Ub(t){let{year:e,month:r,day:n}=t,i=pU(e,r,n);return{year:e,ordinal:i,...Hg(t)}}function _x(t){let{year:e,ordinal:r}=t,{month:n,day:i}=hU(e,r);return{year:e,month:n,day:i,...Hg(t)}}function Bx(t,e){if(!Qe(t.localWeekday)||!Qe(t.localWeekNumber)||!Qe(t.localWeekYear)){if(!Qe(t.weekday)||!Qe(t.weekNumber)||!Qe(t.weekYear))throw new la("Cannot mix locale-based week fields with ISO-based week fields");return Qe(t.localWeekday)||(t.weekday=t.localWeekday),Qe(t.localWeekNumber)||(t.weekNumber=t.localWeekNumber),Qe(t.localWeekYear)||(t.weekYear=t.localWeekYear),delete t.localWeekday,delete t.localWeekNumber,delete t.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function tae(t,e=4,r=1){let n=jg(t.weekYear),i=Jn(t.weekNumber,1,uA(t.weekYear,e,r)),o=Jn(t.weekday,1,7);return n?i?o?!1:Wn("weekday",t.weekday):Wn("week",t.weekNumber):Wn("weekYear",t.weekYear)}function rae(t){let e=jg(t.year),r=Jn(t.ordinal,1,Yl(t.year));return e?r?!1:Wn("ordinal",t.ordinal):Wn("year",t.year)}function fU(t){let e=jg(t.year),r=Jn(t.month,1,12),n=Jn(t.day,1,Lg(t.year,t.month));return e?r?n?!1:Wn("day",t.day):Wn("month",t.month):Wn("year",t.year)}function gU(t){let{hour:e,minute:r,second:n,millisecond:i}=t,o=Jn(e,0,23)||e===24&&r===0&&n===0&&i===0,s=Jn(r,0,59),a=Jn(n,0,59),c=Jn(i,0,999);return o?s?a?c?!1:Wn("millisecond",i):Wn("second",n):Wn("minute",r):Wn("hour",e)}function Qe(t){return typeof t>"u"}function ua(t){return typeof t=="number"}function jg(t){return typeof t=="number"&&t%1===0}function nae(t){return typeof t=="string"}function iae(t){return Object.prototype.toString.call(t)==="[object Date]"}function mU(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function yU(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function oae(t){return Array.isArray(t)?t:[t]}function vx(t,e,r){if(t.length!==0)return t.reduce((n,i)=>{let o=[e(i),i];return n&&r(n[0],o[0])===n[0]?n:o},null)[1]}function sae(t,e){return e.reduce((r,n)=>(r[n]=t[n],r),{})}function Wl(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function rS(t){if(t==null)return null;if(typeof t!="object")throw new dr("Week settings must be an object");if(!Jn(t.firstDay,1,7)||!Jn(t.minimalDays,1,7)||!Array.isArray(t.weekend)||t.weekend.some(e=>!Jn(e,1,7)))throw new dr("Invalid week settings");return{firstDay:t.firstDay,minimalDays:t.minimalDays,weekend:Array.from(t.weekend)}}function Jn(t,e,r){return jg(t)&&t>=e&&t<=r}function aae(t,e){return t-e*Math.floor(t/e)}function Wt(t,e=2){let r=t<0,n;return r?n="-"+(""+-t).padStart(e,"0"):n=(""+t).padStart(e,"0"),n}function aa(t){if(!(Qe(t)||t===null||t===""))return parseInt(t,10)}function dc(t){if(!(Qe(t)||t===null||t===""))return parseFloat(t)}function cS(t){if(!(Qe(t)||t===null||t==="")){let e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function lS(t,e,r="round"){let n=10**e;switch(r){case"expand":return t>0?Math.ceil(t*n)/n:Math.floor(t*n)/n;case"trunc":return Math.trunc(t*n)/n;case"round":return Math.round(t*n)/n;case"floor":return Math.floor(t*n)/n;case"ceil":return Math.ceil(t*n)/n;default:throw new RangeError(`Value rounding ${r} is out of range`)}}function dA(t){return t%4===0&&(t%100!==0||t%400===0)}function Yl(t){return dA(t)?366:365}function Lg(t,e){let r=aae(e-1,12)+1,n=t+(e-r)/12;return r===2?dA(n)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][r-1]}function zg(t){let e=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second,t.millisecond);return t.year<100&&t.year>=0&&(e=new Date(e),e.setUTCFullYear(t.year,t.month-1,t.day)),+e}function Qx(t,e,r){return-aS(sS(t,1,e),r)+e-1}function uA(t,e=4,r=1){let n=Qx(t,e,r),i=Qx(t+1,e,r);return(Yl(t)-n+i)/7}function nS(t){return t>99?t:t>yt.twoDigitCutoffYear?1900+t:2e3+t}function EU(t,e,r,n=null){let i=new Date(t),o={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};n&&(o.timeZone=n);let s={timeZoneName:e,...o},a=new Intl.DateTimeFormat(r,s).formatToParts(i).find(c=>c.type.toLowerCase()==="timezonename");return a?a.value:null}function qg(t,e){let r=parseInt(t,10);Number.isNaN(r)&&(r=0);let n=parseInt(e,10)||0,i=r<0||Object.is(r,-0)?-n:n;return r*60+i}function IU(t){let e=Number(t);if(typeof t=="boolean"||t===""||!Number.isFinite(e))throw new dr(`Invalid unit value ${t}`);return e}function $g(t,e){let r={};for(let n in t)if(Wl(t,n)){let i=t[n];if(i==null)continue;r[e(n)]=IU(i)}return r}function cA(t,e){let r=Math.trunc(Math.abs(t/60)),n=Math.trunc(Math.abs(t%60)),i=t>=0?"+":"-";switch(e){case"short":return`${i}${Wt(r,2)}:${Wt(n,2)}`;case"narrow":return`${i}${r}${n>0?`:${n}`:""}`;case"techie":return`${i}${Wt(r,2)}${Wt(n,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function Hg(t){return sae(t,["hour","minute","second","millisecond"])}var cae=["January","February","March","April","May","June","July","August","September","October","November","December"],CU=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],lae=["J","F","M","A","M","J","J","A","S","O","N","D"];function bU(t){switch(t){case"narrow":return[...lae];case"short":return[...CU];case"long":return[...cae];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}var SU=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],wU=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],uae=["M","T","W","T","F","S","S"];function _U(t){switch(t){case"narrow":return[...uae];case"short":return[...wU];case"long":return[...SU];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var BU=["AM","PM"],dae=["Before Christ","Anno Domini"],Aae=["BC","AD"],pae=["B","A"];function vU(t){switch(t){case"narrow":return[...pae];case"short":return[...Aae];case"long":return[...dae];default:return null}}function hae(t){return BU[t.hour<12?0:1]}function fae(t,e){return _U(e)[t.weekday-1]}function gae(t,e){return bU(e)[t.month-1]}function mae(t,e){return vU(e)[t.year<0?0:1]}function yae(t,e,r="always",n=!1){let i={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},o=["hours","minutes","seconds"].indexOf(t)===-1;if(r==="auto"&&o){let d=t==="days";switch(e){case 1:return d?"tomorrow":`next ${i[t][0]}`;case-1:return d?"yesterday":`last ${i[t][0]}`;case 0:return d?"today":`this ${i[t][0]}`}}let s=Object.is(e,-0)||e<0,a=Math.abs(e),c=a===1,l=i[t],u=n?c?l[1]:l[2]||l[1]:c?i[t][0]:t;return s?`${a} ${u} ago`:`in ${a} ${u}`}function Tx(t,e){let r="";for(let n of t)n.literal?r+=n.val:r+=e(n.val);return r}var Eae={D:Ug,DD:qx,DDD:Hx,DDDD:Gx,t:Yx,tt:Vx,ttt:Wx,tttt:Jx,T:Zx,TT:Kx,TTT:Xx,TTTT:eU,f:tU,ff:nU,fff:oU,ffff:aU,F:rU,FF:iU,FFF:sU,FFFF:cU},gn=class t{static create(e,r={}){return new t(e,r)}static parseFormat(e){let r=null,n="",i=!1,o=[];for(let s=0;s<e.length;s++){let a=e.charAt(s);a==="'"?((n.length>0||i)&&o.push({literal:i||/^\s+$/.test(n),val:n===""?"'":n}),r=null,n="",i=!i):i||a===r?n+=a:(n.length>0&&o.push({literal:/^\s+$/.test(n),val:n}),n=a,r=a)}return n.length>0&&o.push({literal:i||/^\s+$/.test(n),val:n}),o}static macroTokenToFormatOpts(e){return Eae[e]}constructor(e,r){this.opts=r,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,r){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...r}).format()}dtFormatter(e,r={}){return this.loc.dtFormatter(e,{...this.opts,...r})}formatDateTime(e,r){return this.dtFormatter(e,r).format()}formatDateTimeParts(e,r){return this.dtFormatter(e,r).formatToParts()}formatInterval(e,r){return this.dtFormatter(e.start,r).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,r){return this.dtFormatter(e,r).resolvedOptions()}num(e,r=0,n=void 0){if(this.opts.forceSimple)return Wt(e,r);let i={...this.opts};return r>0&&(i.padTo=r),n&&(i.signDisplay=n),this.loc.numberFormatter(i).format(e)}formatDateTimeFromString(e,r){let n=this.loc.listingMode()==="en",i=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",o=(p,h)=>this.loc.extract(e,p,h),s=p=>e.isOffsetFixed&&e.offset===0&&p.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,p.format):"",a=()=>n?hae(e):o({hour:"numeric",hourCycle:"h12"},"dayperiod"),c=(p,h)=>n?gae(e,p):o(h?{month:p}:{month:p,day:"numeric"},"month"),l=(p,h)=>n?fae(e,p):o(h?{weekday:p}:{weekday:p,month:"long",day:"numeric"},"weekday"),u=p=>{let h=t.macroTokenToFormatOpts(p);return h?this.formatWithSystemDefault(e,h):p},d=p=>n?mae(e,p):o({era:p},"era"),A=p=>{switch(p){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return s({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return s({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return s({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return a();case"d":return i?o({day:"numeric"},"day"):this.num(e.day);case"dd":return i?o({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return l("short",!0);case"cccc":return l("long",!0);case"ccccc":return l("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return l("short",!1);case"EEEE":return l("long",!1);case"EEEEE":return l("narrow",!1);case"L":return i?o({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return i?o({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return c("short",!0);case"LLLL":return c("long",!0);case"LLLLL":return c("narrow",!0);case"M":return i?o({month:"numeric"},"month"):this.num(e.month);case"MM":return i?o({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return c("short",!1);case"MMMM":return c("long",!1);case"MMMMM":return c("narrow",!1);case"y":return i?o({year:"numeric"},"year"):this.num(e.year);case"yy":return i?o({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return i?o({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return i?o({year:"numeric"},"year"):this.num(e.year,6);case"G":return d("short");case"GG":return d("long");case"GGGGG":return d("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return u(p)}};return Tx(t.parseFormat(r),A)}formatDurationFromString(e,r){let n=this.opts.signMode==="negativeLargestOnly"?-1:1,i=u=>{switch(u[0]){case"S":return"milliseconds";case"s":return"seconds";case"m":return"minutes";case"h":return"hours";case"d":return"days";case"w":return"weeks";case"M":return"months";case"y":return"years";default:return null}},o=(u,d)=>A=>{let p=i(A);if(p){let h=d.isNegativeDuration&&p!==d.largestUnit?n:1,f;return this.opts.signMode==="negativeLargestOnly"&&p!==d.largestUnit?f="never":this.opts.signMode==="all"?f="always":f="auto",this.num(u.get(p)*h,A.length,f)}else return A},s=t.parseFormat(r),a=s.reduce((u,{literal:d,val:A})=>d?u:u.concat(A),[]),c=e.shiftTo(...a.map(i).filter(u=>u)),l={isNegativeDuration:c<0,largestUnit:Object.keys(c.values)[0]};return Tx(s,o(c,l))}},QU=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Jl(...t){let e=t.reduce((r,n)=>r+n.source,"");return RegExp(`^${e}$`)}function Zl(...t){return e=>t.reduce(([r,n,i],o)=>{let[s,a,c]=o(e,i);return[{...r,...s},a||n,c]},[{},null,1]).slice(0,2)}function Kl(t,...e){if(t==null)return[null,null];for(let[r,n]of e){let i=r.exec(t);if(i)return n(i)}return[null,null]}function TU(...t){return(e,r)=>{let n={},i;for(i=0;i<t.length;i++)n[t[i]]=aa(e[r+i]);return[n,null,r+i]}}var DU=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,Iae=`(?:${DU.source}?(?:\\[(${QU.source})\\])?)?`,uS=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,kU=RegExp(`${uS.source}${Iae}`),dS=RegExp(`(?:[Tt]${kU.source})?`),Cae=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,bae=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Sae=/(\d{4})-?(\d{3})/,wae=TU("weekYear","weekNumber","weekDay"),_ae=TU("year","ordinal"),Bae=/(\d{4})-(\d\d)-(\d\d)/,RU=RegExp(`${uS.source} ?(?:${DU.source}|(${QU.source}))?`),vae=RegExp(`(?: ${RU.source})?`);function Vl(t,e,r){let n=t[e];return Qe(n)?r:aa(n)}function Qae(t,e){return[{year:Vl(t,e),month:Vl(t,e+1,1),day:Vl(t,e+2,1)},null,e+3]}function Xl(t,e){return[{hours:Vl(t,e,0),minutes:Vl(t,e+1,0),seconds:Vl(t,e+2,0),milliseconds:cS(t[e+3])},null,e+4]}function AA(t,e){let r=!t[e]&&!t[e+1],n=qg(t[e+1],t[e+2]),i=r?null:En.instance(n);return[{},i,e+3]}function pA(t,e){let r=t[e]?Ss.create(t[e]):null;return[{},r,e+1]}var Tae=RegExp(`^T?${uS.source}$`),Dae=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function kae(t){let[e,r,n,i,o,s,a,c,l]=t,u=e[0]==="-",d=c&&c[0]==="-",A=(p,h=!1)=>p!==void 0&&(h||p&&u)?-p:p;return[{years:A(dc(r)),months:A(dc(n)),weeks:A(dc(i)),days:A(dc(o)),hours:A(dc(s)),minutes:A(dc(a)),seconds:A(dc(c),c==="-0"),milliseconds:A(cS(l),d)}]}var Rae={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function AS(t,e,r,n,i,o,s){let a={year:e.length===2?nS(aa(e)):aa(e),month:CU.indexOf(r)+1,day:aa(n),hour:aa(i),minute:aa(o)};return s&&(a.second=aa(s)),t&&(a.weekday=t.length>3?SU.indexOf(t)+1:wU.indexOf(t)+1),a}var Nae=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function Oae(t){let[,e,r,n,i,o,s,a,c,l,u,d]=t,A=AS(e,i,n,r,o,s,a),p;return c?p=Rae[c]:l?p=0:p=qg(u,d),[A,new En(p)]}function xae(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var Uae=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,Mae=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,Pae=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function Dx(t){let[,e,r,n,i,o,s,a]=t;return[AS(e,i,n,r,o,s,a),En.utcInstance]}function Lae(t){let[,e,r,n,i,o,s,a]=t;return[AS(e,a,r,n,i,o,s),En.utcInstance]}var $ae=Jl(Cae,dS),Fae=Jl(bae,dS),jae=Jl(Sae,dS),zae=Jl(kU),NU=Zl(Qae,Xl,AA,pA),qae=Zl(wae,Xl,AA,pA),Hae=Zl(_ae,Xl,AA,pA),Gae=Zl(Xl,AA,pA);function Yae(t){return Kl(t,[$ae,NU],[Fae,qae],[jae,Hae],[zae,Gae])}function Vae(t){return Kl(xae(t),[Nae,Oae])}function Wae(t){return Kl(t,[Uae,Dx],[Mae,Dx],[Pae,Lae])}function Jae(t){return Kl(t,[Dae,kae])}var Zae=Zl(Xl);function Kae(t){return Kl(t,[Tae,Zae])}var Xae=Jl(Bae,vae),ece=Jl(RU),tce=Zl(Xl,AA,pA);function rce(t){return Kl(t,[Xae,NU],[ece,tce])}var kx="Invalid Duration",OU={weeks:{days:7,hours:168,minutes:10080,seconds:10080*60,milliseconds:10080*60*1e3},days:{hours:24,minutes:1440,seconds:1440*60,milliseconds:1440*60*1e3},hours:{minutes:60,seconds:3600,milliseconds:3600*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},nce={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:2184,minutes:2184*60,seconds:2184*60*60,milliseconds:2184*60*60*1e3},months:{weeks:4,days:30,hours:720,minutes:720*60,seconds:720*60*60,milliseconds:720*60*60*1e3},...OU},Vn=146097/400,ql=146097/4800,ice={years:{quarters:4,months:12,weeks:Vn/7,days:Vn,hours:Vn*24,minutes:Vn*24*60,seconds:Vn*24*60*60,milliseconds:Vn*24*60*60*1e3},quarters:{months:3,weeks:Vn/28,days:Vn/4,hours:Vn*24/4,minutes:Vn*24*60/4,seconds:Vn*24*60*60/4,milliseconds:Vn*24*60*60*1e3/4},months:{weeks:ql/7,days:ql,hours:ql*24,minutes:ql*24*60,seconds:ql*24*60*60,milliseconds:ql*24*60*60*1e3},...OU},pc=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],oce=pc.slice(0).reverse();function Cs(t,e,r=!1){let n={values:r?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy,matrix:e.matrix||t.matrix};return new ir(n)}function xU(t,e){var r;let n=(r=e.milliseconds)!=null?r:0;for(let i of oce.slice(1))e[i]&&(n+=e[i]*t[i].milliseconds);return n}function Rx(t,e){let r=xU(t,e)<0?-1:1;pc.reduceRight((n,i)=>{if(Qe(e[i]))return n;if(n){let o=e[n]*r,s=t[i][n],a=Math.floor(o/s);e[i]+=a*r,e[n]-=a*s*r}return i},null),pc.reduce((n,i)=>{if(Qe(e[i]))return n;if(n){let o=e[n]%1;e[n]-=o,e[i]+=o*t[n][i]}return i},null)}function Nx(t){let e={};for(let[r,n]of Object.entries(t))n!==0&&(e[r]=n);return e}var ir=class t{constructor(e){let r=e.conversionAccuracy==="longterm"||!1,n=r?ice:nce;e.matrix&&(n=e.matrix),this.values=e.values,this.loc=e.loc||mt.create(),this.conversionAccuracy=r?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=n,this.isLuxonDuration=!0}static fromMillis(e,r){return t.fromObject({milliseconds:e},r)}static fromObject(e,r={}){if(e==null||typeof e!="object")throw new dr(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new t({values:$g(e,t.normalizeUnit),loc:mt.fromObject(r),conversionAccuracy:r.conversionAccuracy,matrix:r.matrix})}static fromDurationLike(e){if(ua(e))return t.fromMillis(e);if(t.isDuration(e))return e;if(typeof e=="object")return t.fromObject(e);throw new dr(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,r){let[n]=Jae(e);return n?t.fromObject(n,r):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,r){let[n]=Kae(e);return n?t.fromObject(n,r):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,r=null){if(!e)throw new dr("need to specify a reason the Duration is invalid");let n=e instanceof mn?e:new mn(e,r);if(yt.throwOnInvalid)throw new qb(n);return new t({invalid:n})}static normalizeUnit(e){let r={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!r)throw new xg(e);return r}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,r={}){let n={...r,floor:r.round!==!1&&r.floor!==!1};return this.isValid?gn.create(this.loc,n).formatDurationFromString(this,e):kx}toHuman(e={}){if(!this.isValid)return kx;let r=e.showZeros!==!1,n=pc.map(i=>{let o=this.values[i];return Qe(o)||o===0&&!r?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:i.slice(0,-1)}).format(o)}).filter(i=>i);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(n)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=lS(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let r=this.toMillis();return r<0||r>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},Bt.fromMillis(r,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?xU(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;let r=t.fromDurationLike(e),n={};for(let i of pc)(Wl(r.values,i)||Wl(this.values,i))&&(n[i]=r.get(i)+this.get(i));return Cs(this,{values:n},!0)}minus(e){if(!this.isValid)return this;let r=t.fromDurationLike(e);return this.plus(r.negate())}mapUnits(e){if(!this.isValid)return this;let r={};for(let n of Object.keys(this.values))r[n]=IU(e(this.values[n],n));return Cs(this,{values:r},!0)}get(e){return this[t.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let r={...this.values,...$g(e,t.normalizeUnit)};return Cs(this,{values:r})}reconfigure({locale:e,numberingSystem:r,conversionAccuracy:n,matrix:i}={}){let s={loc:this.loc.clone({locale:e,numberingSystem:r}),matrix:i,conversionAccuracy:n};return Cs(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return Rx(this.matrix,e),Cs(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=Nx(this.normalize().shiftToAll().toObject());return Cs(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(s=>t.normalizeUnit(s));let r={},n={},i=this.toObject(),o;for(let s of pc)if(e.indexOf(s)>=0){o=s;let a=0;for(let l in n)a+=this.matrix[l][s]*n[l],n[l]=0;ua(i[s])&&(a+=i[s]);let c=Math.trunc(a);r[s]=c,n[s]=(a*1e3-c*1e3)/1e3}else ua(i[s])&&(n[s]=i[s]);for(let s in n)n[s]!==0&&(r[o]+=s===o?n[s]:n[s]/this.matrix[o][s]);return Rx(this.matrix,r),Cs(this,{values:r},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;let e={};for(let r of Object.keys(this.values))e[r]=this.values[r]===0?0:-this.values[r];return Cs(this,{values:e},!0)}removeZeros(){if(!this.isValid)return this;let e=Nx(this.values);return Cs(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function r(n,i){return n===void 0||n===0?i===void 0||i===0:n===i}for(let n of pc)if(!r(this.values[n],e.values[n]))return!1;return!0}},Hl="Invalid Interval";function sce(t,e){return!t||!t.isValid?fc.invalid("missing or invalid start"):!e||!e.isValid?fc.invalid("missing or invalid end"):e<t?fc.invalid("end before start",`The end of an interval must be after its start, but you had start=${t.toISO()} and end=${e.toISO()}`):null}var fc=class t{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,r=null){if(!e)throw new dr("need to specify a reason the Interval is invalid");let n=e instanceof mn?e:new mn(e,r);if(yt.throwOnInvalid)throw new zb(n);return new t({invalid:n})}static fromDateTimes(e,r){let n=iA(e),i=iA(r),o=sce(n,i);return o??new t({start:n,end:i})}static after(e,r){let n=ir.fromDurationLike(r),i=iA(e);return t.fromDateTimes(i,i.plus(n))}static before(e,r){let n=ir.fromDurationLike(r),i=iA(e);return t.fromDateTimes(i.minus(n),i)}static fromISO(e,r){let[n,i]=(e||"").split("/",2);if(n&&i){let o,s;try{o=Bt.fromISO(n,r),s=o.isValid}catch{s=!1}let a,c;try{a=Bt.fromISO(i,r),c=a.isValid}catch{c=!1}if(s&&c)return t.fromDateTimes(o,a);if(s){let l=ir.fromISO(i,r);if(l.isValid)return t.after(o,l)}else if(c){let l=ir.fromISO(n,r);if(l.isValid)return t.before(a,l)}}return t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get lastDateTime(){return this.isValid&&this.e?this.e.minus(1):null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds",r){if(!this.isValid)return NaN;let n=this.start.startOf(e,r),i;return r!=null&&r.useLocaleWeeks?i=this.end.reconfigure({locale:n.locale}):i=this.end,i=i.startOf(e,r),Math.floor(i.diff(n,e).get(e))+(i.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:r}={}){return this.isValid?t.fromDateTimes(e||this.s,r||this.e):this}splitAt(...e){if(!this.isValid)return[];let r=e.map(iA).filter(s=>this.contains(s)).sort((s,a)=>s.toMillis()-a.toMillis()),n=[],{s:i}=this,o=0;for(;i<this.e;){let s=r[o]||this.e,a=+s>+this.e?this.e:s;n.push(t.fromDateTimes(i,a)),i=a,o+=1}return n}splitBy(e){let r=ir.fromDurationLike(e);if(!this.isValid||!r.isValid||r.as("milliseconds")===0)return[];let{s:n}=this,i=1,o,s=[];for(;n<this.e;){let a=this.start.plus(r.mapUnits(c=>c*i));o=+a>+this.e?this.e:a,s.push(t.fromDateTimes(n,o)),n=o,i+=1}return s}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;let r=this.s>e.s?this.s:e.s,n=this.e<e.e?this.e:e.e;return r>=n?null:t.fromDateTimes(r,n)}union(e){if(!this.isValid)return this;let r=this.s<e.s?this.s:e.s,n=this.e>e.e?this.e:e.e;return t.fromDateTimes(r,n)}static merge(e){let[r,n]=e.sort((i,o)=>i.s-o.s).reduce(([i,o],s)=>o?o.overlaps(s)||o.abutsStart(s)?[i,o.union(s)]:[i.concat([o]),s]:[i,s],[[],null]);return n&&r.push(n),r}static xor(e){let r=null,n=0,i=[],o=e.map(c=>[{time:c.s,type:"s"},{time:c.e,type:"e"}]),s=Array.prototype.concat(...o),a=s.sort((c,l)=>c.time-l.time);for(let c of a)n+=c.type==="s"?1:-1,n===1?r=c.time:(r&&+r!=+c.time&&i.push(t.fromDateTimes(r,c.time)),r=null);return t.merge(i)}difference(...e){return t.xor([this].concat(e)).map(r=>this.intersection(r)).filter(r=>r&&!r.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:Hl}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(e=Ug,r={}){return this.isValid?gn.create(this.s.loc.clone(r),e).formatInterval(this):Hl}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:Hl}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Hl}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:Hl}toFormat(e,{separator:r=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${r}${this.e.toFormat(e)}`:Hl}toDuration(e,r){return this.isValid?this.e.diff(this.s,e,r):ir.invalid(this.invalidReason)}mapEndpoints(e){return t.fromDateTimes(e(this.s),e(this.e))}},hc=class{static hasDST(e=yt.defaultZone){let r=Bt.now().setZone(e).set({month:12});return!e.isUniversal&&r.offset!==r.set({month:6}).offset}static isValidIANAZone(e){return Ss.isValidZone(e)}static normalizeZone(e){return ca(e,yt.defaultZone)}static getStartOfWeek({locale:e=null,locObj:r=null}={}){return(r||mt.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:r=null}={}){return(r||mt.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:r=null}={}){return(r||mt.create(e)).getWeekendDays().slice()}static months(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null,outputCalendar:o="gregory"}={}){return(i||mt.create(r,n,o)).months(e)}static monthsFormat(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null,outputCalendar:o="gregory"}={}){return(i||mt.create(r,n,o)).months(e,!0)}static weekdays(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null}={}){return(i||mt.create(r,n,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null}={}){return(i||mt.create(r,n,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return mt.create(e).meridiems()}static eras(e="short",{locale:r=null}={}){return mt.create(r,null,"gregory").eras(e)}static features(){return{relative:mU(),localeWeek:yU()}}};function Ox(t,e){let r=i=>i.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),n=r(e)-r(t);return Math.floor(ir.fromMillis(n).as("days"))}function ace(t,e,r){let n=[["years",(c,l)=>l.year-c.year],["quarters",(c,l)=>l.quarter-c.quarter+(l.year-c.year)*4],["months",(c,l)=>l.month-c.month+(l.year-c.year)*12],["weeks",(c,l)=>{let u=Ox(c,l);return(u-u%7)/7}],["days",Ox]],i={},o=t,s,a;for(let[c,l]of n)r.indexOf(c)>=0&&(s=c,i[c]=l(t,e),a=o.plus(i),a>e?(i[c]--,t=o.plus(i),t>e&&(a=t,i[c]--,t=o.plus(i))):t=a);return[t,i,a,s]}function cce(t,e,r,n){let[i,o,s,a]=ace(t,e,r),c=e-i,l=r.filter(d=>["hours","minutes","seconds","milliseconds"].indexOf(d)>=0);l.length===0&&(s<e&&(s=i.plus({[a]:1})),s!==i&&(o[a]=(o[a]||0)+c/(s-i)));let u=ir.fromObject(o,n);return l.length>0?ir.fromMillis(c,n).shiftTo(...l).plus(u):u}var lce="missing Intl.DateTimeFormat.formatToParts support";function nt(t,e=r=>r){return{regex:t,deser:([r])=>e(Xse(r))}}var uce="\xA0",UU=`[ ${uce}]`,MU=new RegExp(UU,"g");function dce(t){return t.replace(/\./g,"\\.?").replace(MU,UU)}function xx(t){return t.replace(/\./g,"").replace(MU," ").toLowerCase()}function wi(t,e){return t===null?null:{regex:RegExp(t.map(dce).join("|")),deser:([r])=>t.findIndex(n=>xx(r)===xx(n))+e}}function Ux(t,e){return{regex:t,deser:([,r,n])=>qg(r,n),groups:e}}function Tg(t){return{regex:t,deser:([e])=>e}}function Ace(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function pce(t,e){let r=Si(e),n=Si(e,"{2}"),i=Si(e,"{3}"),o=Si(e,"{4}"),s=Si(e,"{6}"),a=Si(e,"{1,2}"),c=Si(e,"{1,3}"),l=Si(e,"{1,6}"),u=Si(e,"{1,9}"),d=Si(e,"{2,4}"),A=Si(e,"{4,6}"),p=E=>({regex:RegExp(Ace(E.val)),deser:([S])=>S,literal:!0}),f=(E=>{if(t.literal)return p(E);switch(E.val){case"G":return wi(e.eras("short"),0);case"GG":return wi(e.eras("long"),0);case"y":return nt(l);case"yy":return nt(d,nS);case"yyyy":return nt(o);case"yyyyy":return nt(A);case"yyyyyy":return nt(s);case"M":return nt(a);case"MM":return nt(n);case"MMM":return wi(e.months("short",!0),1);case"MMMM":return wi(e.months("long",!0),1);case"L":return nt(a);case"LL":return nt(n);case"LLL":return wi(e.months("short",!1),1);case"LLLL":return wi(e.months("long",!1),1);case"d":return nt(a);case"dd":return nt(n);case"o":return nt(c);case"ooo":return nt(i);case"HH":return nt(n);case"H":return nt(a);case"hh":return nt(n);case"h":return nt(a);case"mm":return nt(n);case"m":return nt(a);case"q":return nt(a);case"qq":return nt(n);case"s":return nt(a);case"ss":return nt(n);case"S":return nt(c);case"SSS":return nt(i);case"u":return Tg(u);case"uu":return Tg(a);case"uuu":return nt(r);case"a":return wi(e.meridiems(),0);case"kkkk":return nt(o);case"kk":return nt(d,nS);case"W":return nt(a);case"WW":return nt(n);case"E":case"c":return nt(r);case"EEE":return wi(e.weekdays("short",!1),1);case"EEEE":return wi(e.weekdays("long",!1),1);case"ccc":return wi(e.weekdays("short",!0),1);case"cccc":return wi(e.weekdays("long",!0),1);case"Z":case"ZZ":return Ux(new RegExp(`([+-]${a.source})(?::(${n.source}))?`),2);case"ZZZ":return Ux(new RegExp(`([+-]${a.source})(${n.source})?`),2);case"z":return Tg(/[a-z_+-/]{1,256}?/i);case" ":return Tg(/[^\S\n\r]/);default:return p(E)}})(t)||{invalidReason:lce};return f.token=t,f}var hce={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function fce(t,e,r){let{type:n,value:i}=t;if(n==="literal"){let c=/^\s+$/.test(i);return{literal:!c,val:c?" ":i}}let o=e[n],s=n;n==="hour"&&(e.hour12!=null?s=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?s="hour12":s="hour24":s=r.hour12?"hour12":"hour24");let a=hce[s];if(typeof a=="object"&&(a=a[o]),a)return{literal:!1,val:a}}function gce(t){return[`^${t.map(r=>r.regex).reduce((r,n)=>`${r}(${n.source})`,"")}$`,t]}function mce(t,e,r){let n=t.match(e);if(n){let i={},o=1;for(let s in r)if(Wl(r,s)){let a=r[s],c=a.groups?a.groups+1:1;!a.literal&&a.token&&(i[a.token.val[0]]=a.deser(n.slice(o,o+c))),o+=c}return[n,i]}else return[n,{}]}function yce(t){let e=o=>{switch(o){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},r=null,n;return Qe(t.z)||(r=Ss.create(t.z)),Qe(t.Z)||(r||(r=new En(t.Z)),n=t.Z),Qe(t.q)||(t.M=(t.q-1)*3+1),Qe(t.h)||(t.h<12&&t.a===1?t.h+=12:t.h===12&&t.a===0&&(t.h=0)),t.G===0&&t.y&&(t.y=-t.y),Qe(t.u)||(t.S=cS(t.u)),[Object.keys(t).reduce((o,s)=>{let a=e(s);return a&&(o[a]=t[s]),o},{}),r,n]}var Mb=null;function Ece(){return Mb||(Mb=Bt.fromMillis(1555555555555)),Mb}function Ice(t,e){if(t.literal)return t;let r=gn.macroTokenToFormatOpts(t.val),n=$U(r,e);return n==null||n.includes(void 0)?t:n}function PU(t,e){return Array.prototype.concat(...t.map(r=>Ice(r,e)))}var Fg=class{constructor(e,r){if(this.locale=e,this.format=r,this.tokens=PU(gn.parseFormat(r),e),this.units=this.tokens.map(n=>pce(n,e)),this.disqualifyingUnit=this.units.find(n=>n.invalidReason),!this.disqualifyingUnit){let[n,i]=gce(this.units);this.regex=RegExp(n,"i"),this.handlers=i}}explainFromTokens(e){if(this.isValid){let[r,n]=mce(e,this.regex,this.handlers),[i,o,s]=n?yce(n):[null,null,void 0];if(Wl(n,"a")&&Wl(n,"H"))throw new la("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:this.tokens,regex:this.regex,rawMatches:r,matches:n,result:i,zone:o,specificOffset:s}}else return{input:e,tokens:this.tokens,invalidReason:this.invalidReason}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}};function LU(t,e,r){return new Fg(t,r).explainFromTokens(e)}function Cce(t,e,r){let{result:n,zone:i,specificOffset:o,invalidReason:s}=LU(t,e,r);return[n,i,o,s]}function $U(t,e){if(!t)return null;let n=gn.create(e,t).dtFormatter(Ece()),i=n.formatToParts(),o=n.resolvedOptions();return i.map(s=>fce(s,t,o))}var Pb="Invalid DateTime",Mx=864e13;function sA(t){return new mn("unsupported zone",`the zone "${t.name}" is not supported`)}function Lb(t){return t.weekData===null&&(t.weekData=Pg(t.c)),t.weekData}function $b(t){return t.localWeekData===null&&(t.localWeekData=Pg(t.c,t.loc.getMinDaysInFirstWeek(),t.loc.getStartOfWeek())),t.localWeekData}function Ac(t,e){let r={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new Bt({...r,...e,old:r})}function FU(t,e,r){let n=t-e*60*1e3,i=r.offset(n);if(e===i)return[n,e];n-=(i-e)*60*1e3;let o=r.offset(n);return i===o?[n,i]:[t-Math.min(i,o)*60*1e3,Math.max(i,o)]}function Dg(t,e){t+=e*60*1e3;let r=new Date(t);return{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate(),hour:r.getUTCHours(),minute:r.getUTCMinutes(),second:r.getUTCSeconds(),millisecond:r.getUTCMilliseconds()}}function Rg(t,e,r){return FU(zg(t),e,r)}function Px(t,e){let r=t.o,n=t.c.year+Math.trunc(e.years),i=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,o={...t.c,year:n,month:i,day:Math.min(t.c.day,Lg(n,i))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},s=ir.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),a=zg(o),[c,l]=FU(a,r,t.zone);return s!==0&&(c+=s,l=t.zone.offset(c)),{ts:c,o:l}}function Gl(t,e,r,n,i,o){let{setZone:s,zone:a}=r;if(t&&Object.keys(t).length!==0||e){let c=e||a,l=Bt.fromObject(t,{...r,zone:c,specificOffset:o});return s?l:l.setZone(a)}else return Bt.invalid(new mn("unparsable",`the input "${i}" can't be parsed as ${n}`))}function kg(t,e,r=!0){return t.isValid?gn.create(mt.create("en-US"),{allowZ:r,forceSimple:!0}).formatDateTimeFromString(t,e):null}function Fb(t,e,r){let n=t.c.year>9999||t.c.year<0,i="";if(n&&t.c.year>=0&&(i+="+"),i+=Wt(t.c.year,n?6:4),r==="year")return i;if(e){if(i+="-",i+=Wt(t.c.month),r==="month")return i;i+="-"}else if(i+=Wt(t.c.month),r==="month")return i;return i+=Wt(t.c.day),i}function Lx(t,e,r,n,i,o,s){let a=!r||t.c.millisecond!==0||t.c.second!==0,c="";switch(s){case"day":case"month":case"year":break;default:if(c+=Wt(t.c.hour),s==="hour")break;if(e){if(c+=":",c+=Wt(t.c.minute),s==="minute")break;a&&(c+=":",c+=Wt(t.c.second))}else{if(c+=Wt(t.c.minute),s==="minute")break;a&&(c+=Wt(t.c.second))}if(s==="second")break;a&&(!n||t.c.millisecond!==0)&&(c+=".",c+=Wt(t.c.millisecond,3))}return i&&(t.isOffsetFixed&&t.offset===0&&!o?c+="Z":t.o<0?(c+="-",c+=Wt(Math.trunc(-t.o/60)),c+=":",c+=Wt(Math.trunc(-t.o%60))):(c+="+",c+=Wt(Math.trunc(t.o/60)),c+=":",c+=Wt(Math.trunc(t.o%60)))),o&&(c+="["+t.zone.ianaName+"]"),c}var jU={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},bce={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Sce={ordinal:1,hour:0,minute:0,second:0,millisecond:0},Ng=["year","month","day","hour","minute","second","millisecond"],wce=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],_ce=["year","ordinal","hour","minute","second","millisecond"];function Og(t){let e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[t.toLowerCase()];if(!e)throw new xg(t);return e}function $x(t){switch(t.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return Og(t)}}function Bce(t){if(aA===void 0&&(aA=yt.now()),t.type!=="iana")return t.offset(aA);let e=t.name,r=iS.get(e);return r===void 0&&(r=t.offset(aA),iS.set(e,r)),r}function Fx(t,e){let r=ca(e.zone,yt.defaultZone);if(!r.isValid)return Bt.invalid(sA(r));let n=mt.fromObject(e),i,o;if(Qe(t.year))i=yt.now();else{for(let c of Ng)Qe(t[c])&&(t[c]=jU[c]);let s=fU(t)||gU(t);if(s)return Bt.invalid(s);let a=Bce(r);[i,o]=Rg(t,a,r)}return new Bt({ts:i,zone:r,loc:n,o})}function jx(t,e,r){let n=Qe(r.round)?!0:r.round,i=Qe(r.rounding)?"trunc":r.rounding,o=(a,c)=>(a=lS(a,n||r.calendary?0:2,r.calendary?"round":i),e.loc.clone(r).relFormatter(r).format(a,c)),s=a=>r.calendary?e.hasSame(t,a)?0:e.startOf(a).diff(t.startOf(a),a).get(a):e.diff(t,a).get(a);if(r.unit)return o(s(r.unit),r.unit);for(let a of r.units){let c=s(a);if(Math.abs(c)>=1)return o(c,a)}return o(t>e?-0:0,r.units[r.units.length-1])}function zx(t){let e={},r;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],r=Array.from(t).slice(0,t.length-1)):r=Array.from(t),[e,r]}var aA,iS=new Map,Bt=class t{constructor(e){let r=e.zone||yt.defaultZone,n=e.invalid||(Number.isNaN(e.ts)?new mn("invalid input"):null)||(r.isValid?null:sA(r));this.ts=Qe(e.ts)?yt.now():e.ts;let i=null,o=null;if(!n)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(r))[i,o]=[e.old.c,e.old.o];else{let a=ua(e.o)&&!e.old?e.o:r.offset(this.ts);i=Dg(this.ts,a),n=Number.isNaN(i.year)?new mn("invalid input"):null,i=n?null:i,o=n?null:a}this._zone=r,this.loc=e.loc||mt.create(),this.invalid=n,this.weekData=null,this.localWeekData=null,this.c=i,this.o=o,this.isLuxonDateTime=!0}static now(){return new t({})}static local(){let[e,r]=zx(arguments),[n,i,o,s,a,c,l]=r;return Fx({year:n,month:i,day:o,hour:s,minute:a,second:c,millisecond:l},e)}static utc(){let[e,r]=zx(arguments),[n,i,o,s,a,c,l]=r;return e.zone=En.utcInstance,Fx({year:n,month:i,day:o,hour:s,minute:a,second:c,millisecond:l},e)}static fromJSDate(e,r={}){let n=iae(e)?e.valueOf():NaN;if(Number.isNaN(n))return t.invalid("invalid input");let i=ca(r.zone,yt.defaultZone);return i.isValid?new t({ts:n,zone:i,loc:mt.fromObject(r)}):t.invalid(sA(i))}static fromMillis(e,r={}){if(ua(e))return e<-Mx||e>Mx?t.invalid("Timestamp out of range"):new t({ts:e,zone:ca(r.zone,yt.defaultZone),loc:mt.fromObject(r)});throw new dr(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,r={}){if(ua(e))return new t({ts:e*1e3,zone:ca(r.zone,yt.defaultZone),loc:mt.fromObject(r)});throw new dr("fromSeconds requires a numerical input")}static fromObject(e,r={}){e=e||{};let n=ca(r.zone,yt.defaultZone);if(!n.isValid)return t.invalid(sA(n));let i=mt.fromObject(r),o=$g(e,$x),{minDaysInFirstWeek:s,startOfWeek:a}=Bx(o,i),c=yt.now(),l=Qe(r.specificOffset)?n.offset(c):r.specificOffset,u=!Qe(o.ordinal),d=!Qe(o.year),A=!Qe(o.month)||!Qe(o.day),p=d||A,h=o.weekYear||o.weekNumber;if((p||u)&&h)throw new la("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(A&&u)throw new la("Can't mix ordinal dates with month/day");let f=h||o.weekday&&!p,E,S,B=Dg(c,l);f?(E=wce,S=bce,B=Pg(B,s,a)):u?(E=_ce,S=Sce,B=Ub(B)):(E=Ng,S=jU);let _=!1;for(let K of E){let Ae=o[K];Qe(Ae)?_?o[K]=S[K]:o[K]=B[K]:_=!0}let v=f?tae(o,s,a):u?rae(o):fU(o),T=v||gU(o);if(T)return t.invalid(T);let L=f?wx(o,s,a):u?_x(o):o,[k,P]=Rg(L,l,n),U=new t({ts:k,zone:n,o:P,loc:i});return o.weekday&&p&&e.weekday!==U.weekday?t.invalid("mismatched weekday",`you can't specify both a weekday of ${o.weekday} and a date of ${U.toISO()}`):U.isValid?U:t.invalid(U.invalid)}static fromISO(e,r={}){let[n,i]=Yae(e);return Gl(n,i,r,"ISO 8601",e)}static fromRFC2822(e,r={}){let[n,i]=Vae(e);return Gl(n,i,r,"RFC 2822",e)}static fromHTTP(e,r={}){let[n,i]=Wae(e);return Gl(n,i,r,"HTTP",r)}static fromFormat(e,r,n={}){if(Qe(e)||Qe(r))throw new dr("fromFormat requires an input string and a format");let{locale:i=null,numberingSystem:o=null}=n,s=mt.fromOpts({locale:i,numberingSystem:o,defaultToEN:!0}),[a,c,l,u]=Cce(s,e,r);return u?t.invalid(u):Gl(a,c,n,`format ${r}`,e,l)}static fromString(e,r,n={}){return t.fromFormat(e,r,n)}static fromSQL(e,r={}){let[n,i]=rce(e);return Gl(n,i,r,"SQL",e)}static invalid(e,r=null){if(!e)throw new dr("need to specify a reason the DateTime is invalid");let n=e instanceof mn?e:new mn(e,r);if(yt.throwOnInvalid)throw new jb(n);return new t({invalid:n})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,r={}){let n=$U(e,mt.fromObject(r));return n?n.map(i=>i?i.val:null).join(""):null}static expandFormat(e,r={}){return PU(gn.parseFormat(e),mt.fromObject(r)).map(i=>i.val).join("")}static resetCache(){aA=void 0,iS.clear()}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?Lb(this).weekYear:NaN}get weekNumber(){return this.isValid?Lb(this).weekNumber:NaN}get weekday(){return this.isValid?Lb(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?$b(this).weekday:NaN}get localWeekNumber(){return this.isValid?$b(this).weekNumber:NaN}get localWeekYear(){return this.isValid?$b(this).weekYear:NaN}get ordinal(){return this.isValid?Ub(this.c).ordinal:NaN}get monthShort(){return this.isValid?hc.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?hc.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?hc.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?hc.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];let e=864e5,r=6e4,n=zg(this.c),i=this.zone.offset(n-e),o=this.zone.offset(n+e),s=this.zone.offset(n-i*r),a=this.zone.offset(n-o*r);if(s===a)return[this];let c=n-s*r,l=n-a*r,u=Dg(c,s),d=Dg(l,a);return u.hour===d.hour&&u.minute===d.minute&&u.second===d.second&&u.millisecond===d.millisecond?[Ac(this,{ts:c}),Ac(this,{ts:l})]:[this]}get isInLeapYear(){return dA(this.year)}get daysInMonth(){return Lg(this.year,this.month)}get daysInYear(){return this.isValid?Yl(this.year):NaN}get weeksInWeekYear(){return this.isValid?uA(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?uA(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){let{locale:r,numberingSystem:n,calendar:i}=gn.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:r,numberingSystem:n,outputCalendar:i}}toUTC(e=0,r={}){return this.setZone(En.instance(e),r)}toLocal(){return this.setZone(yt.defaultZone)}setZone(e,{keepLocalTime:r=!1,keepCalendarTime:n=!1}={}){if(e=ca(e,yt.defaultZone),e.equals(this.zone))return this;if(e.isValid){let i=this.ts;if(r||n){let o=e.offset(this.ts),s=this.toObject();[i]=Rg(s,o,e)}return Ac(this,{ts:i,zone:e})}else return t.invalid(sA(e))}reconfigure({locale:e,numberingSystem:r,outputCalendar:n}={}){let i=this.loc.clone({locale:e,numberingSystem:r,outputCalendar:n});return Ac(this,{loc:i})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let r=$g(e,$x),{minDaysInFirstWeek:n,startOfWeek:i}=Bx(r,this.loc),o=!Qe(r.weekYear)||!Qe(r.weekNumber)||!Qe(r.weekday),s=!Qe(r.ordinal),a=!Qe(r.year),c=!Qe(r.month)||!Qe(r.day),l=a||c,u=r.weekYear||r.weekNumber;if((l||s)&&u)throw new la("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(c&&s)throw new la("Can't mix ordinal dates with month/day");let d;o?d=wx({...Pg(this.c,n,i),...r},n,i):Qe(r.ordinal)?(d={...this.toObject(),...r},Qe(r.day)&&(d.day=Math.min(Lg(d.year,d.month),d.day))):d=_x({...Ub(this.c),...r});let[A,p]=Rg(d,this.o,this.zone);return Ac(this,{ts:A,o:p})}plus(e){if(!this.isValid)return this;let r=ir.fromDurationLike(e);return Ac(this,Px(this,r))}minus(e){if(!this.isValid)return this;let r=ir.fromDurationLike(e).negate();return Ac(this,Px(this,r))}startOf(e,{useLocaleWeeks:r=!1}={}){if(!this.isValid)return this;let n={},i=ir.normalizeUnit(e);switch(i){case"years":n.month=1;case"quarters":case"months":n.day=1;case"weeks":case"days":n.hour=0;case"hours":n.minute=0;case"minutes":n.second=0;case"seconds":n.millisecond=0;break}if(i==="weeks")if(r){let o=this.loc.getStartOfWeek(),{weekday:s}=this;s<o&&(n.weekNumber=this.weekNumber-1),n.weekday=o}else n.weekday=1;if(i==="quarters"){let o=Math.ceil(this.month/3);n.month=(o-1)*3+1}return this.set(n)}endOf(e,r){return this.isValid?this.plus({[e]:1}).startOf(e,r).minus(1):this}toFormat(e,r={}){return this.isValid?gn.create(this.loc.redefaultToEN(r)).formatDateTimeFromString(this,e):Pb}toLocaleString(e=Ug,r={}){return this.isValid?gn.create(this.loc.clone(r),e).formatDateTime(this):Pb}toLocaleParts(e={}){return this.isValid?gn.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:r=!1,suppressMilliseconds:n=!1,includeOffset:i=!0,extendedZone:o=!1,precision:s="milliseconds"}={}){if(!this.isValid)return null;s=Og(s);let a=e==="extended",c=Fb(this,a,s);return Ng.indexOf(s)>=3&&(c+="T"),c+=Lx(this,a,r,n,i,o,s),c}toISODate({format:e="extended",precision:r="day"}={}){return this.isValid?Fb(this,e==="extended",Og(r)):null}toISOWeekDate(){return kg(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:r=!1,includeOffset:n=!0,includePrefix:i=!1,extendedZone:o=!1,format:s="extended",precision:a="milliseconds"}={}){return this.isValid?(a=Og(a),(i&&Ng.indexOf(a)>=3?"T":"")+Lx(this,s==="extended",r,e,n,o,a)):null}toRFC2822(){return kg(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return kg(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?Fb(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:r=!1,includeOffsetSpace:n=!0}={}){let i="HH:mm:ss.SSS";return(r||e)&&(n&&(i+=" "),r?i+="z":e&&(i+="ZZ")),kg(this,i,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():Pb}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};let r={...this.c};return e.includeConfig&&(r.outputCalendar=this.outputCalendar,r.numberingSystem=this.loc.numberingSystem,r.locale=this.loc.locale),r}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,r="milliseconds",n={}){if(!this.isValid||!e.isValid)return ir.invalid("created by diffing an invalid DateTime");let i={locale:this.locale,numberingSystem:this.numberingSystem,...n},o=oae(r).map(ir.normalizeUnit),s=e.valueOf()>this.valueOf(),a=s?this:e,c=s?e:this,l=cce(a,c,o,i);return s?l.negate():l}diffNow(e="milliseconds",r={}){return this.diff(t.now(),e,r)}until(e){return this.isValid?fc.fromDateTimes(this,e):this}hasSame(e,r,n){if(!this.isValid)return!1;let i=e.valueOf(),o=this.setZone(e.zone,{keepLocalTime:!0});return o.startOf(r,n)<=i&&i<=o.endOf(r,n)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;let r=e.base||t.fromObject({},{zone:this.zone}),n=e.padding?this<r?-e.padding:e.padding:0,i=["years","months","days","hours","minutes","seconds"],o=e.unit;return Array.isArray(e.unit)&&(i=e.unit,o=void 0),jx(r,this.plus(n),{...e,numeric:"always",units:i,unit:o})}toRelativeCalendar(e={}){return this.isValid?jx(e.base||t.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(t.isDateTime))throw new dr("min requires all arguments be DateTimes");return vx(e,r=>r.valueOf(),Math.min)}static max(...e){if(!e.every(t.isDateTime))throw new dr("max requires all arguments be DateTimes");return vx(e,r=>r.valueOf(),Math.max)}static fromFormatExplain(e,r,n={}){let{locale:i=null,numberingSystem:o=null}=n,s=mt.fromOpts({locale:i,numberingSystem:o,defaultToEN:!0});return LU(s,e,r)}static fromStringExplain(e,r,n={}){return t.fromFormatExplain(e,r,n)}static buildFormatParser(e,r={}){let{locale:n=null,numberingSystem:i=null}=r,o=mt.fromOpts({locale:n,numberingSystem:i,defaultToEN:!0});return new Fg(o,e)}static fromFormatParser(e,r,n={}){if(Qe(e)||Qe(r))throw new dr("fromFormatParser requires an input string and a format parser");let{locale:i=null,numberingSystem:o=null}=n,s=mt.fromOpts({locale:i,numberingSystem:o,defaultToEN:!0});if(!s.equals(r.locale))throw new dr(`fromFormatParser called with a locale of ${s}, but the format parser was created for ${r.locale}`);let{result:a,zone:c,specificOffset:l,invalidReason:u}=r.explainFromTokens(e);return u?t.invalid(u):Gl(a,c,n,`format ${r.format}`,e,l)}static get DATE_SHORT(){return Ug}static get DATE_MED(){return qx}static get DATE_MED_WITH_WEEKDAY(){return Use}static get DATE_FULL(){return Hx}static get DATE_HUGE(){return Gx}static get TIME_SIMPLE(){return Yx}static get TIME_WITH_SECONDS(){return Vx}static get TIME_WITH_SHORT_OFFSET(){return Wx}static get TIME_WITH_LONG_OFFSET(){return Jx}static get TIME_24_SIMPLE(){return Zx}static get TIME_24_WITH_SECONDS(){return Kx}static get TIME_24_WITH_SHORT_OFFSET(){return Xx}static get TIME_24_WITH_LONG_OFFSET(){return eU}static get DATETIME_SHORT(){return tU}static get DATETIME_SHORT_WITH_SECONDS(){return rU}static get DATETIME_MED(){return nU}static get DATETIME_MED_WITH_SECONDS(){return iU}static get DATETIME_MED_WITH_WEEKDAY(){return Mse}static get DATETIME_FULL(){return oU}static get DATETIME_FULL_WITH_SECONDS(){return sU}static get DATETIME_HUGE(){return aU}static get DATETIME_HUGE_WITH_SECONDS(){return cU}};function iA(t){if(Bt.isDateTime(t))return t;if(t&&t.valueOf&&ua(t.valueOf()))return Bt.fromJSDate(t);if(t&&typeof t=="object")return Bt.fromObject(t);throw new dr(`Unknown datetime argument: ${t}, of type ${typeof t}`)}var vce="3.7.2";In.DateTime=Bt;In.Duration=ir;In.FixedOffsetZone=En;In.IANAZone=Ss;In.Info=hc;In.Interval=fc;In.InvalidZone=Mg;In.Settings=yt;In.SystemZone=lA;In.VERSION=vce;In.Zone=da});var Vg=y(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.CronDate=Or.DAYS_IN_MONTH=Or.DateMathOp=Or.TimeUnit=void 0;var gc=zU(),Br;(function(t){t.Second="Second",t.Minute="Minute",t.Hour="Hour",t.Day="Day",t.Month="Month",t.Year="Year"})(Br||(Or.TimeUnit=Br={}));var Gg;(function(t){t.Add="Add",t.Subtract="Subtract"})(Gg||(Or.DateMathOp=Gg={}));Or.DAYS_IN_MONTH=Object.freeze([31,29,31,30,31,30,31,31,30,31,30,31]);var Yg=class t{#e;#t=null;#n=null;#i={add:{[Br.Year]:this.addYear.bind(this),[Br.Month]:this.addMonth.bind(this),[Br.Day]:this.addDay.bind(this),[Br.Hour]:this.addHour.bind(this),[Br.Minute]:this.addMinute.bind(this),[Br.Second]:this.addSecond.bind(this)},subtract:{[Br.Year]:this.subtractYear.bind(this),[Br.Month]:this.subtractMonth.bind(this),[Br.Day]:this.subtractDay.bind(this),[Br.Hour]:this.subtractHour.bind(this),[Br.Minute]:this.subtractMinute.bind(this),[Br.Second]:this.subtractSecond.bind(this)}};constructor(e,r){let n={zone:r};if(e?e instanceof t?(this.#e=e.#e,this.#t=e.#t,this.#n=e.#n):e instanceof Date?this.#e=gc.DateTime.fromJSDate(e,n):typeof e=="number"?this.#e=gc.DateTime.fromMillis(e,n):(this.#e=gc.DateTime.fromISO(e,n),this.#e.isValid||(this.#e=gc.DateTime.fromRFC2822(e,n)),this.#e.isValid||(this.#e=gc.DateTime.fromSQL(e,n)),this.#e.isValid||(this.#e=gc.DateTime.fromFormat(e,"EEE, d MMM yyyy HH:mm:ss",n))):this.#e=gc.DateTime.local(),!this.#e.isValid)throw new Error(`CronDate: unhandled timestamp: ${e}`);r&&r!==this.#e.zoneName&&(this.#e=this.#e.setZone(r))}static#o(e){return e%4===0&&e%100!==0||e%400===0}get dstStart(){return this.#t}set dstStart(e){this.#t=e}get dstEnd(){return this.#n}set dstEnd(e){this.#n=e}addYear(){this.#e=this.#e.plus({years:1})}addMonth(){this.#e=this.#e.plus({months:1}).startOf("month")}addDay(){this.#e=this.#e.plus({days:1}).startOf("day")}addHour(){this.#e=this.#e.plus({hours:1}).startOf("hour")}addMinute(){this.#e=this.#e.plus({minutes:1}).startOf("minute")}addSecond(){this.#e=this.#e.plus({seconds:1})}subtractYear(){this.#e=this.#e.minus({years:1})}subtractMonth(){this.#e=this.#e.minus({months:1}).endOf("month").startOf("second")}subtractDay(){this.#e=this.#e.minus({days:1}).endOf("day").startOf("second")}subtractHour(){this.#e=this.#e.minus({hours:1}).endOf("hour").startOf("second")}subtractMinute(){this.#e=this.#e.minus({minutes:1}).endOf("minute").startOf("second")}subtractSecond(){this.#e=this.#e.minus({seconds:1})}addUnit(e){this.#i.add[e]()}subtractUnit(e){this.#i.subtract[e]()}invokeDateOperation(e,r){if(e===Gg.Add){this.addUnit(r);return}if(e===Gg.Subtract){this.subtractUnit(r);return}throw new Error(`Invalid verb: ${e}`)}getDate(){return this.#e.day}getFullYear(){return this.#e.year}getDay(){let e=this.#e.weekday;return e===7?0:e}getMonth(){return this.#e.month-1}getHours(){return this.#e.hour}getMinutes(){return this.#e.minute}getSeconds(){return this.#e.second}getMilliseconds(){return this.#e.millisecond}getUTCOffset(){return this.#e.offset}setStartOfDay(){this.#e=this.#e.startOf("day")}setEndOfDay(){this.#e=this.#e.endOf("day")}getTime(){return this.#e.valueOf()}getUTCDate(){return this.#r().day}getUTCFullYear(){return this.#r().year}getUTCDay(){let e=this.#r().weekday;return e===7?0:e}getUTCMonth(){return this.#r().month-1}getUTCHours(){return this.#r().hour}getUTCMinutes(){return this.#r().minute}getUTCSeconds(){return this.#r().second}toISOString(){return this.#e.toUTC().toISO()}toJSON(){return this.#e.toJSON()}setDate(e){this.#e=this.#e.set({day:e})}setFullYear(e){this.#e=this.#e.set({year:e})}setDay(e){this.#e=this.#e.set({weekday:e})}setMonth(e){this.#e=this.#e.set({month:e+1})}setHours(e){this.#e=this.#e.set({hour:e})}setMinutes(e){this.#e=this.#e.set({minute:e})}setSeconds(e){this.#e=this.#e.set({second:e})}setMilliseconds(e){this.#e=this.#e.set({millisecond:e})}toString(){return this.toDate().toString()}toDate(){return this.#e.toJSDate()}isLastDayOfMonth(){let{day:e,month:r}=this.#e;if(r===2){let n=t.#o(this.#e.year);return e===Or.DAYS_IN_MONTH[r-1]-(n?0:1)}return e===Or.DAYS_IN_MONTH[r-1]}isLastWeekdayOfMonth(){let{day:e,month:r}=this.#e,n;return r===2?n=Or.DAYS_IN_MONTH[r-1]-(t.#o(this.#e.year)?0:1):n=Or.DAYS_IN_MONTH[r-1],e>n-7}applyDateOperation(e,r,n){if(r===Br.Month||r===Br.Day){this.invokeDateOperation(e,r);return}let i=this.getHours();this.invokeDateOperation(e,r);let o=this.getHours(),s=o-i;s===2?n!==24&&(this.dstStart=o):s===0&&this.getMinutes()===0&&this.getSeconds()===0&&n!==24&&(this.dstEnd=o)}#r(){return this.#e.toUTC()}};Or.CronDate=Yg;Or.default=Yg});var qU=y(Wg=>{"use strict";Object.defineProperty(Wg,"__esModule",{value:!0});Wg.CronMonth=void 0;var Qce=Vg(),Tce=sa(),Dce=1,kce=12,Rce=Object.freeze([]),pS=class extends Tce.CronField{static get min(){return Dce}static get max(){return kce}static get chars(){return Rce}static get daysInMonth(){return Qce.DAYS_IN_MONTH}constructor(e,r){super(e,r),this.validate()}get values(){return super.values}};Wg.CronMonth=pS});var HU=y(Jg=>{"use strict";Object.defineProperty(Jg,"__esModule",{value:!0});Jg.CronSecond=void 0;var Nce=sa(),Oce=0,xce=59,Uce=Object.freeze([]),hS=class extends Nce.CronField{static get min(){return Oce}static get max(){return xce}static get chars(){return Uce}constructor(e,r){super(e,r),this.validate()}get values(){return super.values}};Jg.CronSecond=hS});var Zg=y(Vr=>{"use strict";var Mce=Vr&&Vr.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Aa=Vr&&Vr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Mce(e,t,r)};Object.defineProperty(Vr,"__esModule",{value:!0});Aa(lx(),Vr);Aa(ux(),Vr);Aa(dx(),Vr);Aa(sa(),Vr);Aa(Ax(),Vr);Aa(px(),Vr);Aa(qU(),Vr);Aa(HU(),Vr)});var gS=y(Kg=>{"use strict";Object.defineProperty(Kg,"__esModule",{value:!0});Kg.CronFieldCollection=void 0;var Zn=Zg(),fS=class t{#e;#t;#n;#i;#o;#r;static from(e,r){return new t({second:this.resolveField(Zn.CronSecond,e.second,r.second),minute:this.resolveField(Zn.CronMinute,e.minute,r.minute),hour:this.resolveField(Zn.CronHour,e.hour,r.hour),dayOfMonth:this.resolveField(Zn.CronDayOfMonth,e.dayOfMonth,r.dayOfMonth),month:this.resolveField(Zn.CronMonth,e.month,r.month),dayOfWeek:this.resolveField(Zn.CronDayOfWeek,e.dayOfWeek,r.dayOfWeek)})}static resolveField(e,r,n){return n?n instanceof Zn.CronField?n:new e(n):r}constructor({second:e,minute:r,hour:n,dayOfMonth:i,month:o,dayOfWeek:s}){if(!e)throw new Error("Validation error, Field second is missing");if(!r)throw new Error("Validation error, Field minute is missing");if(!n)throw new Error("Validation error, Field hour is missing");if(!i)throw new Error("Validation error, Field dayOfMonth is missing");if(!o)throw new Error("Validation error, Field month is missing");if(!s)throw new Error("Validation error, Field dayOfWeek is missing");if(o.values.length===1&&!i.hasLastChar&&!(parseInt(i.values[0],10)<=Zn.CronMonth.daysInMonth[o.values[0]-1]))throw new Error("Invalid explicit day of month definition");this.#e=e,this.#t=r,this.#n=n,this.#o=o,this.#r=s,this.#i=i}get second(){return this.#e}get minute(){return this.#t}get hour(){return this.#n}get dayOfMonth(){return this.#i}get month(){return this.#o}get dayOfWeek(){return this.#r}static compactField(e){if(e.length===0)return[];let r=[],n;return e.forEach((i,o,s)=>{if(n===void 0){n={start:i,count:1};return}let a=s[o-1]||n.start,c=s[o+1];if(i==="L"||i==="W"){r.push(n),r.push({start:i,count:1}),n=void 0;return}if(n.step===void 0&&c!==void 0){let l=i-a,u=c-i;if(l<=u){n={...n,count:2,end:i,step:l};return}n.step=1}i-(n.end??0)===n.step?(n.count++,n.end=i):(n.count===1?r.push({start:n.start,count:1}):n.count===2?(r.push({start:n.start,count:1}),r.push({start:n.end??a,count:1})):r.push(n),n={start:i,count:1})}),n&&r.push(n),r}static#c(e,r,n){let i=r.step;return i?i===1&&r.start===e.min&&r.end&&r.end>=n?e.hasQuestionMarkChar?"?":"*":i!==1&&r.start===e.min&&r.end&&r.end>=n-i+1?`*/${i}`:null:null}static#s(e,r){let n=e.step;if(n===1)return`${e.start}-${e.end}`;let i=e.start===0?e.count-1:e.count;if(!n)throw new Error("Unexpected range step");if(!e.end)throw new Error("Unexpected range end");if(n*i>e.end){let o=(a,c)=>{if(typeof e.start!="number")throw new Error("Unexpected range start");return c%n===0?e.start+c:null};if(typeof e.start!="number")throw new Error("Unexpected range start");let s={length:e.end-e.start+1};return Array.from(s,o).filter(a=>a!==null).join(",")}return e.end===r-n+1?`${e.start}/${n}`:`${e.start}-${e.end}/${n}`}stringifyField(e){let r=e.max,n=e.values;if(e instanceof Zn.CronDayOfWeek){r=6;let o=this.#r.values;n=o[o.length-1]===7?o.slice(0,-1):o}e instanceof Zn.CronDayOfMonth&&(r=this.#o.values.length===1?Zn.CronMonth.daysInMonth[this.#o.values[0]-1]:e.max);let i=t.compactField(n);if(i.length===1){let o=t.#c(e,i[0],r);if(o)return o}return i.map(o=>{let s=o.count===1?o.start.toString():t.#s(o,r);return e instanceof Zn.CronDayOfWeek&&e.nthDay>0?`${s}#${e.nthDay}`:s}).join(",")}stringify(e=!1){let r=[];return e&&r.push(this.stringifyField(this.#e)),r.push(this.stringifyField(this.#t),this.stringifyField(this.#n),this.stringifyField(this.#i),this.stringifyField(this.#o),this.stringifyField(this.#r)),r.join(" ")}serialize(){return{second:this.#e.serialize(),minute:this.#t.serialize(),hour:this.#n.serialize(),dayOfMonth:this.#i.serialize(),month:this.#o.serialize(),dayOfWeek:this.#r.serialize()}}};Kg.CronFieldCollection=fS});var mS=y(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.CronExpression=Kn.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE=Kn.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE=void 0;var Ut=Vg();Kn.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE="Out of the time span range";Kn.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE="Invalid expression, loop limit exceeded";var GU=1e4,Xg=class t{#e;#t;#n;#i;#o;#r;#c=null;#s=!1;constructor(e,r){this.#e=r,this.#t=r.tz,this.#i=r.startDate?new Ut.CronDate(r.startDate,this.#t):null,this.#o=r.endDate?new Ut.CronDate(r.endDate,this.#t):null;let n=r.currentDate??r.startDate;if(n){let i=new Ut.CronDate(n,this.#t);this.#i&&i.getTime()<this.#i.getTime()?n=this.#i:this.#o&&i.getTime()>this.#o.getTime()&&(n=this.#o)}this.#n=new Ut.CronDate(n,this.#t),this.#r=e}get fields(){return this.#r}static fieldsToExpression(e,r){return new t(e,r||{})}static#a(e,r){return r.some(n=>n===e)}#l(e,r){return e[r?e.length-1:0]}#d(e){let r=`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()}`;if(this.#c===r)return this.#s;let n=new Ut.CronDate(e);n.setStartOfDay();let i=new Ut.CronDate(e);return i.setEndOfDay(),this.#c=r,this.#s=n.getUTCOffset()!==i.getUTCOffset(),this.#s}#A(e,r,n){let i=this.#r.second.values,o=e.getSeconds(),s=this.#r.second.findNearestValue(o,n);if(s!==null){e.setSeconds(s);return}e.applyDateOperation(r,Ut.TimeUnit.Minute,this.#r.hour.values.length),e.setSeconds(this.#l(i,n))}#p(e,r,n){let i=this.#r.minute.values,o=this.#r.second.values,s=e.getMinutes(),a=this.#r.minute.findNearestValue(s,n);if(a!==null){e.setMinutes(a),e.setSeconds(this.#l(o,n));return}e.applyDateOperation(r,Ut.TimeUnit.Hour,this.#r.hour.values.length),e.setMinutes(this.#l(i,n)),e.setSeconds(this.#l(o,n))}static#h(e,r){let n=r.isLastWeekdayOfMonth();return e.some(i=>{let o=parseInt(i.toString().charAt(0),10)%7;if(Number.isNaN(o))throw new Error(`Invalid last weekday of the month expression: ${i}`);return r.getDay()===o&&n})}next(){return this.#g()}prev(){return this.#g(!0)}hasNext(){let e=this.#n;try{return this.#g(),!0}catch{return!1}finally{this.#n=e}}hasPrev(){let e=this.#n;try{return this.#g(!0),!0}catch{return!1}finally{this.#n=e}}take(e){let r=[];if(e>=0)for(let n=0;n<e;n++)try{r.push(this.next())}catch{return r}else for(let n=0;n>e;n--)try{r.push(this.prev())}catch{return r}return r}reset(e){this.#n=new Ut.CronDate(e||this.#e.currentDate)}stringify(e=!1){return this.#r.stringify(e)}includesDate(e){let{second:r,minute:n,hour:i,month:o}=this.#r,s=new Ut.CronDate(e,this.#t);return!(!r.values.includes(s.getSeconds())||!n.values.includes(s.getMinutes())||!i.values.includes(s.getHours())||!o.values.includes(s.getMonth()+1)||!this.#u(s)||this.#r.dayOfWeek.nthDay>0&&Math.ceil(s.getDate()/7)!==this.#r.dayOfWeek.nthDay)}toString(){return this.#e.expression||this.stringify(!0)}#u(e){let r=this.#r.dayOfMonth.isWildcard,n=!r,i=this.#r.dayOfWeek.isWildcard,o=!i,s=t.#a(e.getDate(),this.#r.dayOfMonth.values)||this.#r.dayOfMonth.hasLastChar&&e.isLastDayOfMonth(),a=t.#a(e.getDay(),this.#r.dayOfWeek.values)||this.#r.dayOfWeek.hasLastChar&&t.#h(this.#r.dayOfWeek.values,e);return!!(n&&o&&(s||a)||s&&!o||r&&!i&&a)}#m(e,r,n){let i=this.#r.hour.values,o=i,s=e.getHours(),a=t.#a(s,i),c=e.dstStart===s,l=e.dstEnd===s;if(c)return t.#a(s-1,i)?!0:(e.invokeDateOperation(r,Ut.TimeUnit.Hour),!1);if(l&&!n)return e.dstEnd=null,e.applyDateOperation(Ut.DateMathOp.Add,Ut.TimeUnit.Hour,o.length),!1;if(a)return!0;e.dstStart=null;let u=this.#r.hour.findNearestValue(s,n);if(u===null)return e.applyDateOperation(r,Ut.TimeUnit.Day,o.length),!1;if(this.#d(e)){let d=n?s-u:u-s;for(let A=0;A<d;A++)e.applyDateOperation(r,Ut.TimeUnit.Hour,o.length)}else e.setHours(u);return e.setMinutes(this.#l(this.#r.minute.values,n)),e.setSeconds(this.#l(this.#r.second.values,n)),!1}#f(e){if(!this.#i&&!this.#o)return;let r=e.getTime();if(this.#i&&r<this.#i.getTime())throw new Error(Kn.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE);if(this.#o&&r>this.#o.getTime())throw new Error(Kn.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE)}#g(e=!1){let r=e?Ut.DateMathOp.Subtract:Ut.DateMathOp.Add,n=new Ut.CronDate(this.#n),i=n.getTime(),o=0;for(;++o<GU;){if(this.#f(n),!this.#u(n)){n.applyDateOperation(r,Ut.TimeUnit.Day,this.#r.hour.values.length);continue}if(!(this.#r.dayOfWeek.nthDay<=0||Math.ceil(n.getDate()/7)===this.#r.dayOfWeek.nthDay)){n.applyDateOperation(r,Ut.TimeUnit.Day,this.#r.hour.values.length);continue}if(!t.#a(n.getMonth()+1,this.#r.month.values)){n.applyDateOperation(r,Ut.TimeUnit.Month,this.#r.hour.values.length);continue}if(this.#m(n,r,e)){if(!t.#a(n.getMinutes(),this.#r.minute.values)){this.#p(n,r,e);continue}if(!t.#a(n.getSeconds(),this.#r.second.values)){this.#A(n,r,e);continue}if(i===n.getTime()){(r==="Add"||n.getMilliseconds()===0)&&n.applyDateOperation(r,Ut.TimeUnit.Second,this.#r.hour.values.length);continue}break}}if(o>GU)throw new Error(Kn.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE);return n.getMilliseconds()!==0&&n.setMilliseconds(0),this.#n=n,n}[Symbol.iterator](){return{next:()=>({value:this.#g(),done:!this.hasNext()})}}};Kn.CronExpression=Xg;Kn.default=Xg});var YU=y(yS=>{"use strict";Object.defineProperty(yS,"__esModule",{value:!0});yS.seededRandom=$ce;function Pce(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t.charCodeAt(r),e=Math.imul(e,16777619);return()=>e>>>0}function Lce(t){return()=>{let e=t+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}function $ce(t){let e=t?Pce(t)():Math.floor(Math.random()*1e10);return Lce(e)}});var em=y(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.CronExpressionParser=ti.DayOfWeek=ti.Months=ti.CronUnit=ti.PredefinedExpressions=void 0;var Fce=gS(),jce=mS(),zce=YU(),Xn=Zg(),ES;(function(t){t["@yearly"]="0 0 0 1 1 *",t["@annually"]="0 0 0 1 1 *",t["@monthly"]="0 0 0 1 * *",t["@weekly"]="0 0 0 * * 0",t["@daily"]="0 0 0 * * *",t["@hourly"]="0 0 * * * *",t["@minutely"]="0 * * * * *",t["@secondly"]="* * * * * *",t["@weekdays"]="0 0 0 * * 1-5",t["@weekends"]="0 0 0 * * 0,6"})(ES||(ti.PredefinedExpressions=ES={}));var ei;(function(t){t.Second="Second",t.Minute="Minute",t.Hour="Hour",t.DayOfMonth="DayOfMonth",t.Month="Month",t.DayOfWeek="DayOfWeek"})(ei||(ti.CronUnit=ei={}));var IS;(function(t){t[t.jan=1]="jan",t[t.feb=2]="feb",t[t.mar=3]="mar",t[t.apr=4]="apr",t[t.may=5]="may",t[t.jun=6]="jun",t[t.jul=7]="jul",t[t.aug=8]="aug",t[t.sep=9]="sep",t[t.oct=10]="oct",t[t.nov=11]="nov",t[t.dec=12]="dec"})(IS||(ti.Months=IS={}));var CS;(function(t){t[t.sun=0]="sun",t[t.mon=1]="mon",t[t.tue=2]="tue",t[t.wed=3]="wed",t[t.thu=4]="thu",t[t.fri=5]="fri",t[t.sat=6]="sat"})(CS||(ti.DayOfWeek=CS={}));var bS=class t{static parse(e,r={}){let{strict:n=!1,hashSeed:i}=r,o=(0,zce.seededRandom)(i);e=ES[e]||e;let s=t.#e(e,n);if(!(s.dayOfMonth==="*"||s.dayOfWeek==="*"||!n))throw new Error("Cannot use both dayOfMonth and dayOfWeek together in strict mode!");let a=t.#t(ei.Second,s.second,Xn.CronSecond.constraints,o),c=t.#t(ei.Minute,s.minute,Xn.CronMinute.constraints,o),l=t.#t(ei.Hour,s.hour,Xn.CronHour.constraints,o),u=t.#t(ei.Month,s.month,Xn.CronMonth.constraints,o),d=t.#t(ei.DayOfMonth,s.dayOfMonth,Xn.CronDayOfMonth.constraints,o),{dayOfWeek:A,nthDayOfWeek:p}=t.#d(s.dayOfWeek),h=t.#t(ei.DayOfWeek,A,Xn.CronDayOfWeek.constraints,o),f=new Fce.CronFieldCollection({second:new Xn.CronSecond(a,{rawValue:s.second}),minute:new Xn.CronMinute(c,{rawValue:s.minute}),hour:new Xn.CronHour(l,{rawValue:s.hour}),dayOfMonth:new Xn.CronDayOfMonth(d,{rawValue:s.dayOfMonth}),month:new Xn.CronMonth(u,{rawValue:s.month}),dayOfWeek:new Xn.CronDayOfWeek(h,{rawValue:s.dayOfWeek,nthDayOfWeek:p})});return new jce.CronExpression(f,{...r,expression:e})}static#e(e,r){if(r&&!e.length)throw new Error("Invalid cron expression");e=e||"0 * * * * *";let n=e.trim().split(/\s+/);if(r&&n.length<6)throw new Error("Invalid cron expression, expected 6 fields");if(n.length>6)throw new Error("Invalid cron expression, too many fields");let i=["*","*","*","*","*","0"];n.length<i.length&&n.unshift(...i.slice(n.length));let[o,s,a,c,l,u]=n;return{second:o,minute:s,hour:a,dayOfMonth:c,month:l,dayOfWeek:u}}static#t(e,r,n,i){if((e===ei.Month||e===ei.DayOfWeek)&&(r=r.replace(/[a-z]{3}/gi,o=>{o=o.toLowerCase();let s=IS[o]||CS[o];if(s===void 0)throw new Error(`Validation error, cannot resolve alias "${o}"`);return s.toString()})),!n.validChars.test(r))throw new Error(`Invalid characters, got value: ${r}`);return r=this.#n(r,n),r=this.#i(r,n,i),this.#o(e,r,n)}static#n(e,r){return e.replace(/[*?]/g,r.min+"-"+r.max)}static#i(e,r,n){let i=n();return e.replace(/H(?:\((\d+)-(\d+)\))?(?:\/(\d+))?/g,(o,s,a,c)=>{if(s&&a&&c){let l=parseInt(s,10),u=parseInt(a,10),d=parseInt(c,10);if(l>u)throw new Error(`Invalid range: ${l}-${u}, min > max`);if(d<=0)throw new Error(`Invalid step: ${d}, must be positive`);let A=Math.max(l,r.min),p=Math.floor(i*d),h=[];for(let f=Math.floor(A/d)*d+p;f<=u;f+=d)f>=A&&h.push(f);return h.join(",")}else if(s&&a){let l=parseInt(s,10),u=parseInt(a,10);if(l>u)throw new Error(`Invalid range: ${l}-${u}, min > max`);return String(Math.floor(i*(u-l+1))+l)}else if(c){let l=parseInt(c,10);if(l<=0)throw new Error(`Invalid step: ${l}, must be positive`);let u=Math.floor(i*l),d=[];for(let A=Math.floor(r.min/l)*l+u;A<=r.max;A+=l)A>=r.min&&d.push(A);return d.join(",")}else return String(Math.floor(i*(r.max-r.min+1)+r.min))})}static#o(e,r,n){let i=[];function o(a,c){if(Array.isArray(a))i.push(...a);else if(t.#A(c,a))i.push(a);else{let l=parseInt(a.toString(),10);if(!(l>=c.min&&l<=c.max))throw new Error(`Constraint error, got value ${a} expected range ${c.min}-${c.max}`);i.push(e===ei.DayOfWeek?l%7:a)}}return r.split(",").forEach(a=>{if(!(a.length>0))throw new Error("Invalid list value format");o(t.#r(e,a,n),n)}),i}static#r(e,r,n){let i=r.split("/");if(i.length>2)throw new Error(`Invalid repeat: ${r}`);return i.length===2?(isNaN(parseInt(i[0],10))||(i[0]=`${i[0]}-${n.max}`),t.#l(e,i[0],parseInt(i[1],10),n)):t.#l(e,r,1,n)}static#c(e,r,n){if(!(!isNaN(e)&&!isNaN(r)&&e>=n.min&&r<=n.max))throw new Error(`Constraint error, got range ${e}-${r} expected range ${n.min}-${n.max}`);if(e>r)throw new Error(`Invalid range: ${e}-${r}, min(${e}) > max(${r})`)}static#s(e){if(!(!isNaN(e)&&e>0))throw new Error(`Constraint error, cannot repeat at every ${e} time.`)}static#a(e,r,n,i){let o=[];e===ei.DayOfWeek&&n%7===0&&o.push(0);for(let s=r;s<=n;s+=i)o.indexOf(s)===-1&&o.push(s);return o}static#l(e,r,n,i){let o=r.split("-");if(o.length<=1)return isNaN(+r)?r:+r;let[s,a]=o.map(c=>parseInt(c,10));return this.#c(s,a,i),this.#s(n),this.#a(e,s,a,n)}static#d(e){let r=e.split("#");if(r.length<=1)return{dayOfWeek:r[0]};let n=+r[r.length-1],i=e.match(/([,-/])/);if(i!==null)throw new Error(`Constraint error, invalid dayOfWeek \`#\` and \`${i?.[0]}\` special characters are incompatible`);if(!(r.length<=2&&!isNaN(n)&&n>=1&&n<=5))throw new Error("Constraint error, invalid dayOfWeek occurrence number (#)");return{dayOfWeek:r[0],nthDayOfWeek:n}}static#A(e,r){return e.chars.some(n=>r.toString().includes(n))}};ti.CronExpressionParser=bS});var VU=y(Fo=>{"use strict";var qce=Fo&&Fo.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Hce=Fo&&Fo.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Gce=Fo&&Fo.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),i=0;i<n.length;i++)n[i]!=="default"&&qce(r,e,n[i]);return Hce(r,e),r}})();Object.defineProperty(Fo,"__esModule",{value:!0});Fo.CronFileParser=void 0;var Yce=em(),SS=class t{static async parseFile(e){let{readFile:r}=await Promise.resolve().then(()=>Gce(require("fs/promises"))),n=await r(e,"utf8");return t.#e(n)}static parseFileSync(e){let{readFileSync:r}=require("fs"),n=r(e,"utf8");return t.#e(n)}static#e(e){let r=e.split(`
|
|
102
|
-
`),n={variables:{},expressions:[],errors:{}};for(let i of r){let o=i.trim();if(o.length===0||o.startsWith("#"))continue;let s=o.match(/^(.*)=(.*)$/);if(s){let[,a,c]=s;n.variables[a]=c.replace(/["']/g,"");continue}try{let a=t.#t(o);n.expressions.push(a.interval)}catch(a){n.errors[o]=a}}return n}static#t(e){let r=e.split(" ");return{interval:Yce.CronExpressionParser.parse(r.slice(0,5).join(" ")),command:r.slice(5,r.length)}}};Fo.CronFileParser=SS});var WU=y(Ar=>{"use strict";var Vce=Ar&&Ar.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Wce=Ar&&Ar.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Vce(e,t,r)};Object.defineProperty(Ar,"__esModule",{value:!0});Ar.CronFileParser=Ar.CronExpressionParser=Ar.CronExpression=Ar.CronFieldCollection=Ar.CronDate=void 0;var Jce=em(),Zce=Vg();Object.defineProperty(Ar,"CronDate",{enumerable:!0,get:function(){return Zce.CronDate}});var Kce=gS();Object.defineProperty(Ar,"CronFieldCollection",{enumerable:!0,get:function(){return Kce.CronFieldCollection}});var Xce=mS();Object.defineProperty(Ar,"CronExpression",{enumerable:!0,get:function(){return Xce.CronExpression}});var ele=em();Object.defineProperty(Ar,"CronExpressionParser",{enumerable:!0,get:function(){return ele.CronExpressionParser}});var tle=VU();Object.defineProperty(Ar,"CronFileParser",{enumerable:!0,get:function(){return tle.CronFileParser}});Wce(Zg(),Ar);Ar.default=Jce.CronExpressionParser});var Bi=y(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.Err=Wr.Valid=Wr.err=Wr.valid=void 0;var rle=t=>new tm(t);Wr.valid=rle;var nle=t=>new rm(t);Wr.err=nle;var tm=class{constructor(e){this.value=e}isValid(){return!0}isError(){return!this.isValid()}getValue(){return this.value}getError(){throw new Error("Tried to get error from a valid.")}map(e){return(0,Wr.valid)(e(this.value))}mapErr(e){return(0,Wr.valid)(this.value)}};Wr.Valid=tm;var rm=class{constructor(e){this.error=e}isError(){return!0}isValid(){return!this.isError()}getValue(){throw new Error("Tried to get success value from an error.")}getError(){return this.error}map(e){return(0,Wr.err)(this.error)}mapErr(e){return(0,Wr.err)(e(this.error))}};Wr.Err=rm});var vi=y(JU=>{"use strict";Object.defineProperty(JU,"__esModule",{value:!0})});var pa=y(wS=>{"use strict";Object.defineProperty(wS,"__esModule",{value:!0});jo();var Oe=Bi();vi();var ile=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],ole=["sun","mon","tue","wed","thu","fri","sat"],sle=(t,e)=>e[t].lowerLimit===e.preset[t].minValue&&e[t].upperLimit===e.preset[t].maxValue,hA=(t,e,r)=>{if(e==="months"&&r.useAliases&&ile.indexOf(t.toLowerCase())!==-1||e==="daysOfWeek"&&r.useAliases&&ole.indexOf(t.toLowerCase())!==-1)return(0,Oe.valid)(!0);let n=Number(t);if(Number.isNaN(n))return(0,Oe.err)(`Element '${t}' of ${e} field is invalid.`);if(n%1!==0)return(0,Oe.err)(`Element '${t}' of ${e} field is not an integer.`);let{lowerLimit:i}=r[e],{upperLimit:o}=r[e];return i&&n<i?(0,Oe.err)(`Number '${n}' of ${e} field is smaller than lower limit '${i}'.`):o&&n>o?(0,Oe.err)(`Number '${n}' of ${e} field is bigger than upper limit '${o}'.`):(0,Oe.valid)(!0)},ale=(t,e,r)=>{if(t==="*")return sle(e,r)?(0,Oe.valid)(!0):(0,Oe.err)(`Field ${e} uses wildcard '*', but is limited to ${r[e].lowerLimit}-${r[e].upperLimit}.`);if(t==="")return(0,Oe.err)(`One of the elements is empty in ${e} field.`);if(e==="daysOfMonth"&&r.useLastDayOfMonth&&t==="L")return(0,Oe.valid)(!0);if(e==="daysOfWeek"&&r.useLastDayOfWeek&&t.endsWith("L")){let n=t.slice(0,-1);return n===""?(0,Oe.valid)(!0):hA(n,e,r)}if(e==="daysOfMonth"&&r.useNearestWeekday&&t.endsWith("W")){let n=t.slice(0,-1);return n===""?(0,Oe.err)("The 'W' must be preceded by a day."):r.useLastDayOfMonth&&n==="L"?(0,Oe.valid)(!0):hA(n,e,r)}if(e==="daysOfWeek"&&r.useNthWeekdayOfMonth&&t.indexOf("#")!==-1){let[n,i,...o]=t.split("#");if(o.length!==0)return(0,Oe.err)(`Unexpected number of '#' in ${t}, can only be used once.`);let s=Number(i);return!i||Number.isNaN(s)?(0,Oe.err)(`Unexpected value following the '#' symbol, a positive number was expected but found ${i}.`):s>5?(0,Oe.err)("Number of occurrence of the day of the week cannot be greater than 5."):hA(n,e,r)}return hA(t,e,r)},ZU=(t,e,r,n)=>t==="*"?(0,Oe.err)(`'*' can't be part of a range in ${e} field.`):t===""?(0,Oe.err)(`One of the range elements is empty in ${e} field.`):r.useLastDayOfMonth&&e==="daysOfMonth"&&t==="L"&&n===0?(0,Oe.valid)(!0):hA(t,e,r),cle=(t,e,r)=>{let n=t.split("-");if(n.length>2)return(0,Oe.err)(`List element '${t}' is not valid. (More than one '-').`);if(n.length===1)return ale(n[0],e,r);if(n.length===2){let i=ZU(n[0],e,r,0),o=ZU(n[1],e,r,1);return i.isError()?i:o.isError()?o:Number(n[0])>Number(n[1])?(0,Oe.err)(`Lower range end '${n[0]}' is bigger than upper range end '${n[1]}' of ${e} field.`):(0,Oe.valid)(!0)}return(0,Oe.err)("Some other error in checkFirstStepElement (rangeArray less than 1)")},lle=(t,e,r)=>{let n=t.split("/");if(n.length>2)return(0,Oe.err)(`List element '${t}' is not valid. (More than one '/').`);if(!r.allowStepping)return(0,Oe.err)("Stepping ('/') is not allowed.");let i=cle(n[0],e,r);if(i.isError())return i;if(n.length===2){let o=n[1];if(!o)return(0,Oe.err)(`Second step element '${o}' of '${t}' is not valid (doesnt exist).`);if(Number.isNaN(Number(o)))return(0,Oe.err)(`Second step element '${o}' of '${t}' is not valid (not a number).`);let s=Number(o);if(s===0)return(0,Oe.err)(`Second step element '${o}' of '${t}' cannot be zero.`);if(s<0)return(0,Oe.err)(`Second step element '${o}' of '${t}' cannot be negative.`);if(s%1!==0)return(0,Oe.err)(`Second step element '${o}' of '${t}' is not an integer.`);let{lowerLimit:a,upperLimit:c}=r[e];if(c&&s>c)return(0,Oe.err)(`Second step element '${o}' of '${t}' is bigger than the upper limit '${c}'.`);let l=n[0].split("-");if(l.length===2){let u=Number(l[0]),d=Number(l[1]);if(!Number.isNaN(u)&&!Number.isNaN(d)){if(s<=0)return(0,Oe.err)(`Step value '${o}' must be greater than 0.`);let A=d-u+1;if(s>=A)return(0,Oe.err)(`Step value '${o}' is too large for the range '${u}-${d}'.`)}}}return(0,Oe.valid)(!0)},ule=(t,e,r)=>{if(!["seconds","minutes","hours","daysOfMonth","months","daysOfWeek","years"].includes(e))return(0,Oe.err)([`Cron field type '${e}' does not exist.`]);if(t==="?")return e==="daysOfMonth"||e==="daysOfWeek"?r.useBlankDay?(0,Oe.valid)(!0):(0,Oe.err)([`useBlankDay is not enabled, but is used in ${e} field.`]):(0,Oe.err)([`blank notation is not allowed in ${e} field.`]);let n=t.split(","),i=[];if(n.forEach(s=>{i.push(lle(s,e,r))}),i.every(s=>s.isValid()))return(0,Oe.valid)(!0);let o=[];return i.forEach(s=>{s.isError()&&o.push(s.getError())}),(0,Oe.err)(o)};wS.default=ule});var KU=y(fA=>{"use strict";var dle=fA&&fA.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(fA,"__esModule",{value:!0});jo();var Ale=Bi(),ple=dle(pa());vi();var hle=(t,e)=>{if(!t.seconds)return(0,Ale.err)(["seconds field is undefined, but useSeconds options is enabled."]);let{seconds:r}=t;return(0,ple.default)(r,"seconds",e)};fA.default=hle});var XU=y(gA=>{"use strict";var fle=gA&&gA.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(gA,"__esModule",{value:!0});jo();var gle=Bi(),mle=fle(pa());vi();var yle=(t,e)=>{if(!t.minutes)return(0,gle.err)(["minutes field is undefined."]);let{minutes:r}=t;return(0,mle.default)(r,"minutes",e)};gA.default=yle});var eM=y(mA=>{"use strict";var Ele=mA&&mA.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(mA,"__esModule",{value:!0});jo();var Ile=Bi(),Cle=Ele(pa());vi();var ble=(t,e)=>{if(!t.hours)return(0,Ile.err)(["hours field is undefined."]);let{hours:r}=t;return(0,Cle.default)(r,"hours",e)};mA.default=ble});var tM=y(EA=>{"use strict";var Sle=EA&&EA.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(EA,"__esModule",{value:!0});jo();var yA=Bi(),wle=Sle(pa());vi();var _le=(t,e)=>{if(!t.daysOfMonth)return(0,yA.err)(["daysOfMonth field is undefined."]);let{daysOfMonth:r}=t;return e.allowOnlyOneBlankDayField&&e.useBlankDay&&t.daysOfMonth==="?"&&t.daysOfWeek==="?"?(0,yA.err)(["Cannot use blank value in daysOfMonth and daysOfWeek field when allowOnlyOneBlankDayField option is enabled."]):e.mustHaveBlankDayField&&t.daysOfMonth!=="?"&&t.daysOfWeek!=="?"?(0,yA.err)(["Cannot specify both daysOfMonth and daysOfWeek field when mustHaveBlankDayField option is enabled."]):e.useLastDayOfMonth&&t.daysOfMonth.indexOf("L")!==-1&&t.daysOfMonth.match(/[,/]/)?(0,yA.err)(["Cannot specify last day of month with lists, or ranges (symbols ,/)."]):e.useNearestWeekday&&t.daysOfMonth.indexOf("W")!==-1&&t.daysOfMonth.match(/[,/-]/)?(0,yA.err)(["Cannot specify nearest weekday with lists, steps or ranges (symbols ,-/)."]):(0,wle.default)(r,"daysOfMonth",e)};EA.default=_le});var rM=y(IA=>{"use strict";var Ble=IA&&IA.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(IA,"__esModule",{value:!0});jo();var vle=Bi(),Qle=Ble(pa());vi();var Tle=(t,e)=>{if(!t.months)return(0,vle.err)(["months field is undefined."]);let{months:r}=t;return(0,Qle.default)(r,"months",e)};IA.default=Tle});var nM=y(bA=>{"use strict";var Dle=bA&&bA.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(bA,"__esModule",{value:!0});jo();var CA=Bi(),kle=Dle(pa());vi();var Rle=(t,e)=>{if(!t.daysOfWeek)return(0,CA.err)(["daysOfWeek field is undefined."]);let{daysOfWeek:r}=t;return e.allowOnlyOneBlankDayField&&t.daysOfMonth==="?"&&t.daysOfWeek==="?"?(0,CA.err)(["Cannot use blank value in daysOfMonth and daysOfWeek field when allowOnlyOneBlankDayField option is enabled."]):e.mustHaveBlankDayField&&t.daysOfMonth!=="?"&&t.daysOfWeek!=="?"?(0,CA.err)(["Cannot specify both daysOfMonth and daysOfWeek field when mustHaveBlankDayField option is enabled."]):e.useLastDayOfWeek&&t.daysOfWeek.indexOf("L")!==-1&&t.daysOfWeek.match(/[,/-]/)?(0,CA.err)(["Cannot specify last day of week with lists, steps or ranges (symbols ,-/)."]):e.useNthWeekdayOfMonth&&t.daysOfWeek.indexOf("#")!==-1&&t.daysOfWeek.match(/[,/-]/)?(0,CA.err)(["Cannot specify Nth weekday of month with lists, steps or ranges (symbols ,-/)."]):(0,kle.default)(r,"daysOfWeek",e)};bA.default=Rle});var iM=y(SA=>{"use strict";var Nle=SA&&SA.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(SA,"__esModule",{value:!0});jo();var Ole=Bi(),xle=Nle(pa());vi();var Ule=(t,e)=>{if(!t.years)return(0,Ole.err)(["years field is undefined, but useYears option is enabled."]);let{years:r}=t;return(0,xle.default)(r,"years",e)};SA.default=Ule});var uM=y((Oje,lM)=>{"use strict";function mc(t){this._maxSize=t,this.clear()}mc.prototype.clear=function(){this._size=0,this._values=Object.create(null)};mc.prototype.get=function(t){return this._values[t]};mc.prototype.set=function(t,e){return this._size>=this._maxSize&&this.clear(),t in this._values||this._size++,this._values[t]=e};var Mle=/[^.^\]^[]+|(?=\[\]|\.\.)/g,cM=/^\d+$/,Ple=/^\d/,Lle=/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g,$le=/^\s*(['"]?)(.*?)(\1)\s*$/,vS=512,oM=new mc(vS),sM=new mc(vS),aM=new mc(vS);lM.exports={Cache:mc,split:BS,normalizePath:_S,setter:function(t){var e=_S(t);return sM.get(t)||sM.set(t,function(n,i){for(var o=0,s=e.length,a=n;o<s-1;){var c=e[o];if(c==="__proto__"||c==="constructor"||c==="prototype")return n;a=a[e[o++]]}a[e[o]]=i})},getter:function(t,e){var r=_S(t);return aM.get(t)||aM.set(t,function(i){for(var o=0,s=r.length;o<s;)if(i!=null||!e)i=i[r[o++]];else return;return i})},join:function(t){return t.reduce(function(e,r){return e+(QS(r)||cM.test(r)?"["+r+"]":(e?".":"")+r)},"")},forEach:function(t,e,r){Fle(Array.isArray(t)?t:BS(t),e,r)}};function _S(t){return oM.get(t)||oM.set(t,BS(t).map(function(e){return e.replace($le,"$2")}))}function BS(t){return t.match(Mle)||[""]}function Fle(t,e,r){var n=t.length,i,o,s,a;for(o=0;o<n;o++)i=t[o],i&&(qle(i)&&(i='"'+i+'"'),a=QS(i),s=!a&&/^\d+$/.test(i),e.call(r,i,a,s,o,t))}function QS(t){return typeof t=="string"&&t&&["'",'"'].indexOf(t.charAt(0))!==-1}function jle(t){return t.match(Ple)&&!t.match(cM)}function zle(t){return Lle.test(t)}function qle(t){return!QS(t)&&(jle(t)||zle(t))}});var pM=y((xje,AM)=>{"use strict";var Hle=/[A-Z\xc0-\xd6\xd8-\xde]?[a-z\xdf-\xf6\xf8-\xff]+(?:['’](?:d|ll|m|re|s|t|ve))?(?=[\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000]|[A-Z\xc0-\xd6\xd8-\xde]|$)|(?:[A-Z\xc0-\xd6\xd8-\xde]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])+(?:['’](?:D|LL|M|RE|S|T|VE))?(?=[\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000]|[A-Z\xc0-\xd6\xd8-\xde](?:[a-z\xdf-\xf6\xf8-\xff]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])|$)|[A-Z\xc0-\xd6\xd8-\xde]?(?:[a-z\xdf-\xf6\xf8-\xff]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])+(?:['’](?:d|ll|m|re|s|t|ve))?|[A-Z\xc0-\xd6\xd8-\xde]+(?:['’](?:D|LL|M|RE|S|T|VE))?|\d*(?:1ST|2ND|3RD|(?![123])\dTH)(?=\b|[a-z_])|\d*(?:1st|2nd|3rd|(?![123])\dth)(?=\b|[A-Z_])|\d+|(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]|\ud83c[\udffb-\udfff])?(?:\u200d(?:[^\ud800-\udfff]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]|\ud83c[\udffb-\udfff])?)*/g,nm=t=>t.match(Hle)||[],im=t=>t[0].toUpperCase()+t.slice(1),TS=(t,e)=>nm(t).join(e).toLowerCase(),dM=t=>nm(t).reduce((e,r)=>`${e}${e?r[0].toUpperCase()+r.slice(1).toLowerCase():r.toLowerCase()}`,""),Gle=t=>im(dM(t)),Yle=t=>TS(t,"_"),Vle=t=>TS(t,"-"),Wle=t=>im(TS(t," ")),Jle=t=>nm(t).map(im).join(" ");AM.exports={words:nm,upperFirst:im,camelCase:dM,pascalCase:Gle,snakeCase:Yle,kebabCase:Vle,sentenceCase:Wle,titleCase:Jle}});var fM=y((Uje,DS)=>{"use strict";DS.exports=function(t){return hM(Zle(t),t)};DS.exports.array=hM;function hM(t,e){var r=t.length,n=new Array(r),i={},o=r,s=Kle(e),a=Xle(t);for(e.forEach(function(l){if(!a.has(l[0])||!a.has(l[1]))throw new Error("Unknown node. There is an unknown node in the supplied edges.")});o--;)i[o]||c(t[o],o,new Set);return n;function c(l,u,d){if(d.has(l)){var A;try{A=", node was:"+JSON.stringify(l)}catch{A=""}throw new Error("Cyclic dependency"+A)}if(!a.has(l))throw new Error("Found unknown node. Make sure to provided all involved nodes. Unknown node: "+JSON.stringify(l));if(!i[u]){i[u]=!0;var p=s.get(l)||new Set;if(p=Array.from(p),u=p.length){d.add(l);do{var h=p[--u];c(h,a.get(h),d)}while(u);d.delete(l)}n[--r]=l}}}function Zle(t){for(var e=new Set,r=0,n=t.length;r<n;r++){var i=t[r];e.add(i[0]),e.add(i[1])}return Array.from(e)}function Kle(t){for(var e=new Map,r=0,n=t.length;r<n;r++){var i=t[r];e.has(i[0])||e.set(i[0],new Set),e.has(i[1])||e.set(i[1],new Set),e.get(i[0]).add(i[1])}return e}function Xle(t){for(var e=new Map,r=0,n=t.length;r<n;r++)e.set(t[r],r);return e}});var MS={};yD(MS,{ArraySchema:()=>DA,BooleanSchema:()=>BA,DateSchema:()=>ru,LazySchema:()=>Am,MixedSchema:()=>_A,NumberSchema:()=>QA,ObjectSchema:()=>TA,Schema:()=>pr,StringSchema:()=>vA,TupleSchema:()=>kA,ValidationError:()=>or,addMethod:()=>Due,array:()=>PM,bool:()=>kM,boolean:()=>kM,date:()=>US,defaultLocale:()=>vM,getIn:()=>OS,isSchema:()=>yc,lazy:()=>Que,mixed:()=>DM,number:()=>NM,object:()=>MM,printValue:()=>qo,reach:()=>cue,ref:()=>aue,setLocale:()=>Tue,string:()=>RM,tuple:()=>LM});function oue(t){return t!=+t?"NaN":t===0&&1/t<0?"-0":""+t}function gM(t,e=!1){if(t==null||t===!0||t===!1)return""+t;let r=typeof t;if(r==="number")return oue(t);if(r==="string")return e?`"${t}"`:t;if(r==="function")return"[Function "+(t.name||"anonymous")+"]";if(r==="symbol")return nue.call(t).replace(iue,"Symbol($1)");let n=eue.call(t).slice(8,-1);return n==="Date"?isNaN(t.getTime())?""+t:t.toISOString(t):n==="Error"||t instanceof Error?"["+tue.call(t)+"]":n==="RegExp"?rue.call(t):null}function qo(t,e){let r=gM(t,e);return r!==null?r:JSON.stringify(t,function(n,i){let o=gM(this[n],e);return o!==null?o:i},2)}function bM(t){return t==null?[]:[].concat(t)}function aue(t,e){return new Ho(t,e)}function eu(t){function e({value:r,path:n="",options:i,originalValue:o,schema:s},a,c){let{name:l,test:u,params:d,message:A,skipAbsent:p}=t,{parent:h,context:f,abortEarly:E=s.spec.abortEarly,disableStackTrace:S=s.spec.disableStackTrace}=i,B={value:r,parent:h,context:f};function _(Ae={}){let Re=QM(Object.assign({value:r,originalValue:o,label:s.spec.label,path:Ae.path||n,spec:s.spec,disableStackTrace:Ae.disableStackTrace||S},d,Ae.params),B),Ge=new or(or.formatError(Ae.message||A,Re),r,Re.path,Ae.type||l,Re.disableStackTrace);return Ge.params=Re,Ge}let v=E?a:c,T={path:n,parent:h,type:l,from:i.from,createError:_,resolve(Ae){return TM(Ae,B)},options:i,originalValue:o,schema:s},L=Ae=>{or.isError(Ae)?v(Ae):Ae?c(null):v(_())},k=Ae=>{or.isError(Ae)?v(Ae):a(Ae)};if(p&&Qi(r))return L(!0);let U;try{var K;if(U=u.call(T,r,T),typeof((K=U)==null?void 0:K.then)=="function"){if(i.sync)throw new Error(`Validation test of type: "${T.type}" returned a Promise during a synchronous validate. This test will finish after the validate call has returned`);return Promise.resolve(U).then(L,k)}}catch(Ae){k(Ae);return}L(U)}return e.OPTIONS=t,e}function QM(t,e){if(!t)return t;for(let r of Object.keys(t))t[r]=TM(t[r],e);return t}function TM(t,e){return Ho.isRef(t)?t.getValue(e.value,e.parent,e.context):t}function OS(t,e,r,n=r){let i,o,s;return e?((0,ri.forEach)(e,(a,c,l)=>{let u=c?a.slice(1,a.length-1):a;t=t.resolve({context:n,parent:i,value:r});let d=t.type==="tuple",A=l?parseInt(u,10):0;if(t.innerType||d){if(d&&!l)throw new Error(`Yup.reach cannot implicitly index into a tuple type. the path part "${s}" must contain an index to the tuple element, e.g. "${s}[0]"`);if(r&&A>=r.length)throw new Error(`Yup.reach cannot resolve an array item at index: ${a}, in the path: ${e}. because there is no value at that index. `);i=r,r=r&&r[A],t=d?t.spec.types[A]:t.innerType}if(!l){if(!t.fields||!t.fields[u])throw new Error(`The schema does not contain the path: ${e}. (failed at: ${s} which is a type: "${t.type}")`);i=r,r=r&&r[u],t=t.fields[u]}o=u,s=c?"["+a+"]":"."+a}),{schema:t,parent:i,parentPath:o}):{parent:i,parentPath:e,schema:t}}function cue(t,e,r,n){return OS(t,e,r,n).schema}function tu(t,e=new Map){if(yc(t)||!t||typeof t!="object")return t;if(e.has(t))return e.get(t);let r;if(t instanceof Date)r=new Date(t.getTime()),e.set(t,r);else if(t instanceof RegExp)r=new RegExp(t),e.set(t,r);else if(Array.isArray(t)){r=new Array(t.length),e.set(t,r);for(let n=0;n<t.length;n++)r[n]=tu(t[n],e)}else if(t instanceof Map){r=new Map,e.set(t,r);for(let[n,i]of t.entries())r.set(n,tu(i,e))}else if(t instanceof Set){r=new Set,e.set(t,r);for(let n of t)r.add(tu(n,e))}else if(t instanceof Object){r={},e.set(t,r);for(let[n,i]of Object.entries(t))r[n]=tu(i,e)}else throw Error(`Unable to clone ${t}`);return r}function lue(t){if(!(t!=null&&t.length))return;let e=[],r="",n=!1,i=!1;for(let o=0;o<t.length;o++){let s=t[o];if(s==="["&&!i){r&&(e.push(...r.split(".").filter(Boolean)),r=""),n=!0;continue}if(s==="]"&&!i){r&&(/^\d+$/.test(r)?e.push(r):e.push(r.replace(/^"|"$/g,"")),r=""),n=!1;continue}if(s==='"'){i=!i;continue}if(s==="."&&!n&&!i){r&&(e.push(r),r="");continue}r+=s}return r&&e.push(...r.split(".").filter(Boolean)),e}function uue(t,e){let r=e?`${e}.${t.path}`:t.path;return t.errors.map(n=>({message:n,path:lue(r)}))}function xS(t,e){var r;if(!((r=t.inner)!=null&&r.length)&&t.errors.length)return uue(t,e);let n=e?`${e}.${t.path}`:t.path;return t.inner.flatMap(i=>xS(i,n))}function DM(t){return new _A(t)}function kM(){return new BA}function pue(t){let e=NS(t);if(!e)return Date.parse?Date.parse(t):Number.NaN;if(e.z===void 0&&e.plusMinus===void 0)return new Date(e.year,e.month,e.day,e.hour,e.minute,e.second,e.millisecond).valueOf();let r=0;return e.z!=="Z"&&e.plusMinus!==void 0&&(r=e.hourOffset*60+e.minuteOffset,e.plusMinus==="+"&&(r=0-r)),Date.UTC(e.year,e.month,e.day,e.hour,e.minute+r,e.second,e.millisecond)}function NS(t){var e,r;let n=Aue.exec(t);return n?{year:ws(n[1]),month:ws(n[2],1)-1,day:ws(n[3],1),hour:ws(n[4]),minute:ws(n[5]),second:ws(n[6]),millisecond:n[7]?ws(n[7].substring(0,3)):0,precision:(e=(r=n[7])==null?void 0:r.length)!=null?e:void 0,z:n[8]||void 0,plusMinus:n[9]||void 0,hourOffset:ws(n[10]),minuteOffset:ws(n[11])}:null}function ws(t,e=0){return Number(t)||e}function RM(){return new vA}function NM(){return new QA}function US(){return new ru}function _ue(t,e=[]){let r=[],n=new Set,i=new Set(e.map(([s,a])=>`${s}-${a}`));function o(s,a){let c=(0,ri.split)(s)[0];n.add(c),i.has(`${a}-${c}`)||r.push([a,c])}for(let s of Object.keys(t)){let a=t[s];n.add(s),Ho.isRef(a)&&a.isSibling?o(a.path,s):yc(a)&&"deps"in a&&a.deps.forEach(c=>o(c,s))}return CM.default.array(Array.from(n),r).reverse()}function mM(t,e){let r=1/0;return t.some((n,i)=>{var o;if((o=e.path)!=null&&o.includes(n))return r=i,!0}),r}function xM(t){return(e,r)=>mM(t,e)-mM(t,r)}function cm(t){if("fields"in t){let e={};for(let[r,n]of Object.entries(t.fields))e[r]=cm(n);return t.setFields(e)}if(t.type==="array"){let e=t.optional();return e.innerType&&(e.innerType=cm(e.innerType)),e}return t.type==="tuple"?t.optional().clone({types:t.spec.types.map(cm)}):"optional"in t?t.optional():t}function EM(t,e){let r=Object.keys(t.fields);return Object.keys(e).filter(n=>r.indexOf(n)===-1)}function MM(t){return new TA(t)}function PM(t){return new DA(t)}function LM(t){return new kA(t)}function Que(t){return new Am(t)}function IM(t){try{return t()}catch(e){if(or.isError(e))return Promise.reject(e);throw e}}function Tue(t){Object.keys(t).forEach(e=>{Object.keys(t[e]).forEach(r=>{vM[e][r]=t[e][r]})})}function Due(t,e,r){if(!t||!yc(t.prototype))throw new TypeError("You must provide a yup schema constructor function");if(typeof e!="string")throw new TypeError("A Method name must be provided");if(typeof r!="function")throw new TypeError("Method function must be provided");t.prototype[e]=r}var ri,wA,CM,eue,tue,rue,nue,iue,SM,wM,_M,sue,lm,or,zo,Jr,ha,kS,RS,sm,am,BM,vM,yc,um,om,Ho,Qi,dm,pr,due,_A,BA,Aue,hue,fue,gue,mue,yue,Eue,Iue,Cue,bue,vA,Sue,QA,OM,wue,ru,UM,Bue,yM,vue,TA,DA,kA,Am,PS=ft(()=>{"use strict";ri=Be(uM()),wA=Be(pM()),CM=Be(fM()),eue=Object.prototype.toString,tue=Error.prototype.toString,rue=RegExp.prototype.toString,nue=typeof Symbol<"u"?Symbol.prototype.toString:()=>"",iue=/^Symbol\((.*)\)(.*)$/;sue=/\$\{\s*(\w+)\s*\}/g;SM=Symbol.toStringTag;lm=class{constructor(e,r,n,i){this.name=void 0,this.message=void 0,this.value=void 0,this.path=void 0,this.type=void 0,this.params=void 0,this.errors=void 0,this.inner=void 0,this[SM]="Error",this.name="ValidationError",this.value=r,this.path=n,this.type=i,this.errors=[],this.inner=[],bM(e).forEach(o=>{if(or.isError(o)){this.errors.push(...o.errors);let s=o.inner.length?o.inner:[o];this.inner.push(...s)}else this.errors.push(o)}),this.message=this.errors.length>1?`${this.errors.length} errors occurred`:this.errors[0]}};wM=Symbol.hasInstance;_M=Symbol.toStringTag;or=class t extends Error{static formatError(e,r){let n=r.label||r.path||"this";return r=Object.assign({},r,{path:n,originalPath:r.path}),typeof e=="string"?e.replace(sue,(i,o)=>qo(r[o])):typeof e=="function"?e(r):e}static isError(e){return e&&e.name==="ValidationError"}constructor(e,r,n,i,o){let s=new lm(e,r,n,i);if(o)return s;super(),this.value=void 0,this.path=void 0,this.type=void 0,this.params=void 0,this.errors=[],this.inner=[],this[_M]="Error",this.name=s.name,this.message=s.message,this.type=s.type,this.value=s.value,this.path=s.path,this.errors=s.errors,this.inner=s.inner,Error.captureStackTrace&&Error.captureStackTrace(this,t)}static[wM](e){return lm[Symbol.hasInstance](e)||super[Symbol.hasInstance](e)}},zo={default:"${path} is invalid",required:"${path} is a required field",defined:"${path} must be defined",notNull:"${path} cannot be null",oneOf:"${path} must be one of the following values: ${values}",notOneOf:"${path} must not be one of the following values: ${values}",notType:({path:t,type:e,value:r,originalValue:n})=>{let i=n!=null&&n!==r?` (cast from the value \`${qo(n,!0)}\`).`:".";return e!=="mixed"?`${t} must be a \`${e}\` type, but the final value was: \`${qo(r,!0)}\``+i:`${t} must match the configured type. The validated value was: \`${qo(r,!0)}\``+i}},Jr={length:"${path} must be exactly ${length} characters",min:"${path} must be at least ${min} characters",max:"${path} must be at most ${max} characters",matches:'${path} must match the following: "${regex}"',email:"${path} must be a valid email",url:"${path} must be a valid URL",uuid:"${path} must be a valid UUID",datetime:"${path} must be a valid ISO date-time",datetime_precision:"${path} must be a valid ISO date-time with a sub-second precision of exactly ${precision} digits",datetime_offset:'${path} must be a valid ISO date-time with UTC "Z" timezone',trim:"${path} must be a trimmed string",lowercase:"${path} must be a lowercase string",uppercase:"${path} must be a upper case string"},ha={min:"${path} must be greater than or equal to ${min}",max:"${path} must be less than or equal to ${max}",lessThan:"${path} must be less than ${less}",moreThan:"${path} must be greater than ${more}",positive:"${path} must be a positive number",negative:"${path} must be a negative number",integer:"${path} must be an integer"},kS={min:"${path} field must be later than ${min}",max:"${path} field must be at earlier than ${max}"},RS={isValue:"${path} field must be ${value}"},sm={noUnknown:"${path} field has unspecified keys: ${unknown}",exact:"${path} object contains unknown properties: ${properties}"},am={min:"${path} field must have at least ${min} items",max:"${path} field must have less than or equal to ${max} items",length:"${path} must have ${length} items"},BM={notType:t=>{let{path:e,value:r,spec:n}=t,i=n.types.length;if(Array.isArray(r)){if(r.length<i)return`${e} tuple value has too few items, expected a length of ${i} but got ${r.length} for value: \`${qo(r,!0)}\``;if(r.length>i)return`${e} tuple value has too many items, expected a length of ${i} but got ${r.length} for value: \`${qo(r,!0)}\``}return or.formatError(zo.notType,t)}},vM=Object.assign(Object.create(null),{mixed:zo,string:Jr,number:ha,date:kS,object:sm,array:am,boolean:RS,tuple:BM}),yc=t=>t&&t.__isYupSchema__,um=class t{static fromOptions(e,r){if(!r.then&&!r.otherwise)throw new TypeError("either `then:` or `otherwise:` is required for `when()` conditions");let{is:n,then:i,otherwise:o}=r,s=typeof n=="function"?n:(...a)=>a.every(c=>c===n);return new t(e,(a,c)=>{var l;let u=s(...a)?i:o;return(l=u?.(c))!=null?l:c})}constructor(e,r){this.fn=void 0,this.refs=e,this.refs=e,this.fn=r}resolve(e,r){let n=this.refs.map(o=>o.getValue(r?.value,r?.parent,r?.context)),i=this.fn(n,e,r);if(i===void 0||i===e)return e;if(!yc(i))throw new TypeError("conditions must return a schema object");return i.resolve(r)}},om={context:"$",value:"."};Ho=class{constructor(e,r={}){if(this.key=void 0,this.isContext=void 0,this.isValue=void 0,this.isSibling=void 0,this.path=void 0,this.getter=void 0,this.map=void 0,typeof e!="string")throw new TypeError("ref must be a string, got: "+e);if(this.key=e.trim(),e==="")throw new TypeError("ref must be a non-empty string");this.isContext=this.key[0]===om.context,this.isValue=this.key[0]===om.value,this.isSibling=!this.isContext&&!this.isValue;let n=this.isContext?om.context:this.isValue?om.value:"";this.path=this.key.slice(n.length),this.getter=this.path&&(0,ri.getter)(this.path,!0),this.map=r.map}getValue(e,r,n){let i=this.isContext?n:this.isValue?e:r;return this.getter&&(i=this.getter(i||{})),this.map&&(i=this.map(i)),i}cast(e,r){return this.getValue(e,r?.parent,r?.context)}resolve(){return this}describe(){return{type:"ref",key:this.key}}toString(){return`Ref(${this.key})`}static isRef(e){return e&&e.__isYupRef}};Ho.prototype.__isYupRef=!0;Qi=t=>t==null;dm=class t extends Set{describe(){let e=[];for(let r of this.values())e.push(Ho.isRef(r)?r.describe():r);return e}resolveAll(e){let r=[];for(let n of this.values())r.push(e(n));return r}clone(){return new t(this.values())}merge(e,r){let n=this.clone();return e.forEach(i=>n.add(i)),r.forEach(i=>n.delete(i)),n}};pr=class{constructor(e){this.type=void 0,this.deps=[],this.tests=void 0,this.transforms=void 0,this.conditions=[],this._mutate=void 0,this.internalTests={},this._whitelist=new dm,this._blacklist=new dm,this.exclusiveTests=Object.create(null),this._typeCheck=void 0,this.spec=void 0,this.tests=[],this.transforms=[],this.withMutation(()=>{this.typeError(zo.notType)}),this.type=e.type,this._typeCheck=e.check,this.spec=Object.assign({strip:!1,strict:!1,abortEarly:!0,recursive:!0,disableStackTrace:!1,nullable:!1,optional:!0,coerce:!0},e?.spec),this.withMutation(r=>{r.nonNullable()})}get _type(){return this.type}clone(e){if(this._mutate)return e&&Object.assign(this.spec,e),this;let r=Object.create(Object.getPrototypeOf(this));return r.type=this.type,r._typeCheck=this._typeCheck,r._whitelist=this._whitelist.clone(),r._blacklist=this._blacklist.clone(),r.internalTests=Object.assign({},this.internalTests),r.exclusiveTests=Object.assign({},this.exclusiveTests),r.deps=[...this.deps],r.conditions=[...this.conditions],r.tests=[...this.tests],r.transforms=[...this.transforms],r.spec=tu(Object.assign({},this.spec,e)),r}label(e){let r=this.clone();return r.spec.label=e,r}meta(...e){if(e.length===0)return this.spec.meta;let r=this.clone();return r.spec.meta=Object.assign(r.spec.meta||{},e[0]),r}withMutation(e){let r=this._mutate;this._mutate=!0;let n=e(this);return this._mutate=r,n}concat(e){if(!e||e===this)return this;if(e.type!==this.type&&this.type!=="mixed")throw new TypeError(`You cannot \`concat()\` schema's of different types: ${this.type} and ${e.type}`);let r=this,n=e.clone(),i=Object.assign({},r.spec,n.spec);return n.spec=i,n.internalTests=Object.assign({},r.internalTests,n.internalTests),n._whitelist=r._whitelist.merge(e._whitelist,e._blacklist),n._blacklist=r._blacklist.merge(e._blacklist,e._whitelist),n.tests=r.tests,n.exclusiveTests=r.exclusiveTests,n.withMutation(o=>{e.tests.forEach(s=>{o.test(s.OPTIONS)})}),n.transforms=[...r.transforms,...n.transforms],n}isType(e){return e==null?!!(this.spec.nullable&&e===null||this.spec.optional&&e===void 0):this._typeCheck(e)}resolve(e){let r=this;if(r.conditions.length){let n=r.conditions;r=r.clone(),r.conditions=[],r=n.reduce((i,o)=>o.resolve(i,e),r),r=r.resolve(e)}return r}resolveOptions(e){var r,n,i,o;return Object.assign({},e,{from:e.from||[],strict:(r=e.strict)!=null?r:this.spec.strict,abortEarly:(n=e.abortEarly)!=null?n:this.spec.abortEarly,recursive:(i=e.recursive)!=null?i:this.spec.recursive,disableStackTrace:(o=e.disableStackTrace)!=null?o:this.spec.disableStackTrace})}cast(e,r={}){let n=this.resolve(Object.assign({},r,{value:e})),i=r.assert==="ignore-optionality",o=n._cast(e,r);if(r.assert!==!1&&!n.isType(o)){if(i&&Qi(o))return o;let s=qo(e),a=qo(o);throw new TypeError(`The value of ${r.path||"field"} could not be cast to a value that satisfies the schema type: "${n.type}".
|
|
101
|
+
${e.message}`)}},Ese=({newValue:t,value:e,maxSize:r,indent:n})=>t!==void 0?JSON.stringify(t,void 0,n):typeof e=="number"?lO(e,r):PO(e,r)});var lx=y(cx=>{"use strict";Object.defineProperty(cx,"__esModule",{value:!0})});var sa=y(Sg=>{"use strict";Object.defineProperty(Sg,"__esModule",{value:!0});Sg.CronField=void 0;var Qb=class t{#e=!1;#t=!1;#n=!1;#i=[];options={rawValue:""};static get min(){throw new Error("min must be overridden")}static get max(){throw new Error("max must be overridden")}static get chars(){return Object.freeze([])}static get validChars(){return/^[?,*\dH/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}static get constraints(){return{min:this.min,max:this.max,chars:this.chars,validChars:this.validChars}}constructor(e,r={rawValue:""}){if(!Array.isArray(e))throw new Error(`${this.constructor.name} Validation error, values is not an array`);if(!(e.length>0))throw new Error(`${this.constructor.name} Validation error, values contains no values`);this.options={...r,rawValue:r.rawValue??""},this.#i=e.sort(t.sorter),this.#n=this.options.wildcard!==void 0?this.options.wildcard:this.#o(),this.#e=this.options.rawValue.includes("L")||e.includes("L"),this.#t=this.options.rawValue.includes("?")||e.includes("?")}get min(){return this.constructor.min}get max(){return this.constructor.max}get chars(){return this.constructor.chars}get hasLastChar(){return this.#e}get hasQuestionMarkChar(){return this.#t}get isWildcard(){return this.#n}get values(){return this.#i}static sorter(e,r){let n=typeof e=="number",i=typeof r=="number";return n&&i?e-r:!n&&!i?e.localeCompare(r):n?-1:1}static findNearestValueInList(e,r,n=!1){if(n){for(let i=e.length-1;i>=0;i--)if(e[i]<r)return e[i];return null}for(let i=0;i<e.length;i++)if(e[i]>r)return e[i];return null}findNearestValue(e,r=!1){return this.constructor.findNearestValueInList(this.values,e,r)}serialize(){return{wildcard:this.#n,values:this.#i}}validate(){let e,r=this.chars.length>0?` or chars ${this.chars.join("")}`:"",n=a=>c=>new RegExp(`^\\d{0,2}${c}$`).test(a),i=a=>(e=a,typeof a=="number"?a>=this.min&&a<=this.max:this.chars.some(n(a)));if(!this.#i.every(i))throw new Error(`${this.constructor.name} Validation error, got value ${e} expected range ${this.min}-${this.max}${r}`);let s=this.#i.find((a,c)=>this.#i.indexOf(a)!==c);if(s)throw new Error(`${this.constructor.name} Validation error, duplicate values found: ${s}`)}#o(){return this.options.rawValue.length>0?["*","?"].includes(this.options.rawValue):Array.from({length:this.max-this.min+1},(e,r)=>r+this.min).every(e=>this.#i.includes(e))}};Sg.CronField=Qb});var ux=y(wg=>{"use strict";Object.defineProperty(wg,"__esModule",{value:!0});wg.CronDayOfMonth=void 0;var Ise=sa(),Cse=1,bse=31,Sse=Object.freeze(["L"]),Tb=class extends Ise.CronField{static get min(){return Cse}static get max(){return bse}static get chars(){return Sse}static get validChars(){return/^[?,*\dLH/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}constructor(e,r){super(e,r),this.validate()}get values(){return super.values}};wg.CronDayOfMonth=Tb});var dx=y(_g=>{"use strict";Object.defineProperty(_g,"__esModule",{value:!0});_g.CronDayOfWeek=void 0;var wse=sa(),_se=0,Bse=7,vse=Object.freeze(["L"]),Db=class extends wse.CronField{static get min(){return _se}static get max(){return Bse}static get chars(){return vse}static get validChars(){return/^[?,*\dLH#/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}constructor(e,r){super(e,r),this.validate()}get values(){return super.values}get nthDay(){return this.options.nthDayOfWeek??0}};_g.CronDayOfWeek=Db});var Ax=y(Bg=>{"use strict";Object.defineProperty(Bg,"__esModule",{value:!0});Bg.CronHour=void 0;var Qse=sa(),Tse=0,Dse=23,kse=Object.freeze([]),kb=class extends Qse.CronField{static get min(){return Tse}static get max(){return Dse}static get chars(){return kse}constructor(e,r){super(e,r),this.validate()}get values(){return super.values}};Bg.CronHour=kb});var px=y(vg=>{"use strict";Object.defineProperty(vg,"__esModule",{value:!0});vg.CronMinute=void 0;var Rse=sa(),Nse=0,Ose=59,xse=Object.freeze([]),Rb=class extends Rse.CronField{static get min(){return Nse}static get max(){return Ose}static get chars(){return xse}constructor(e,r){super(e,r),this.validate()}get values(){return super.values}};vg.CronMinute=Rb});var zU=y(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});var bs=class extends Error{},jb=class extends bs{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},zb=class extends bs{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},qb=class extends bs{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},la=class extends bs{},xg=class extends bs{constructor(e){super(`Invalid unit ${e}`)}},dr=class extends bs{},$o=class extends bs{constructor(){super("Zone is an abstract class")}},ee="numeric",_i="short",yn="long",Ug={year:ee,month:ee,day:ee},qx={year:ee,month:_i,day:ee},Use={year:ee,month:_i,day:ee,weekday:_i},Hx={year:ee,month:yn,day:ee},Gx={year:ee,month:yn,day:ee,weekday:yn},Yx={hour:ee,minute:ee},Vx={hour:ee,minute:ee,second:ee},Wx={hour:ee,minute:ee,second:ee,timeZoneName:_i},Jx={hour:ee,minute:ee,second:ee,timeZoneName:yn},Zx={hour:ee,minute:ee,hourCycle:"h23"},Kx={hour:ee,minute:ee,second:ee,hourCycle:"h23"},Xx={hour:ee,minute:ee,second:ee,hourCycle:"h23",timeZoneName:_i},eU={hour:ee,minute:ee,second:ee,hourCycle:"h23",timeZoneName:yn},tU={year:ee,month:ee,day:ee,hour:ee,minute:ee},rU={year:ee,month:ee,day:ee,hour:ee,minute:ee,second:ee},nU={year:ee,month:_i,day:ee,hour:ee,minute:ee},iU={year:ee,month:_i,day:ee,hour:ee,minute:ee,second:ee},Mse={year:ee,month:_i,day:ee,weekday:_i,hour:ee,minute:ee},oU={year:ee,month:yn,day:ee,hour:ee,minute:ee,timeZoneName:_i},sU={year:ee,month:yn,day:ee,hour:ee,minute:ee,second:ee,timeZoneName:_i},aU={year:ee,month:yn,day:ee,weekday:yn,hour:ee,minute:ee,timeZoneName:yn},cU={year:ee,month:yn,day:ee,weekday:yn,hour:ee,minute:ee,second:ee,timeZoneName:yn},da=class{get type(){throw new $o}get name(){throw new $o}get ianaName(){return this.name}get isUniversal(){throw new $o}offsetName(e,r){throw new $o}formatOffset(e,r){throw new $o}offset(e){throw new $o}equals(e){throw new $o}get isValid(){throw new $o}},Nb=null,lA=class t extends da{static get instance(){return Nb===null&&(Nb=new t),Nb}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return EU(e,r,n)}formatOffset(e,r){return cA(this.offset(e),r)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}},Hb=new Map;function Pse(t){let e=Hb.get(t);return e===void 0&&(e=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"}),Hb.set(t,e)),e}var Lse={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function $se(t,e){let r=t.format(e).replace(/\u200E/g,""),n=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(r),[,i,o,s,a,c,l,u]=n;return[s,i,o,a,c,l,u]}function Fse(t,e){let r=t.formatToParts(e),n=[];for(let i=0;i<r.length;i++){let{type:o,value:s}=r[i],a=Lse[o];o==="era"?n[a]=s:Qe(a)||(n[a]=parseInt(s,10))}return n}var Ob=new Map,Ss=class t extends da{static create(e){let r=Ob.get(e);return r===void 0&&Ob.set(e,r=new t(e)),r}static resetCache(){Ob.clear(),Hb.clear()}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=t.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return EU(e,r,n,this.name)}formatOffset(e,r){return cA(this.offset(e),r)}offset(e){if(!this.valid)return NaN;let r=new Date(e);if(isNaN(r))return NaN;let n=Pse(this.name),[i,o,s,a,c,l,u]=n.formatToParts?Fse(n,r):$se(n,r);a==="BC"&&(i=-Math.abs(i)+1);let A=zg({year:i,month:o,day:s,hour:c===24?0:c,minute:l,second:u,millisecond:0}),p=+r,h=p%1e3;return p-=h>=0?h:1e3+h,(A-p)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}},hx={};function jse(t,e={}){let r=JSON.stringify([t,e]),n=hx[r];return n||(n=new Intl.ListFormat(t,e),hx[r]=n),n}var Gb=new Map;function Yb(t,e={}){let r=JSON.stringify([t,e]),n=Gb.get(r);return n===void 0&&(n=new Intl.DateTimeFormat(t,e),Gb.set(r,n)),n}var Vb=new Map;function zse(t,e={}){let r=JSON.stringify([t,e]),n=Vb.get(r);return n===void 0&&(n=new Intl.NumberFormat(t,e),Vb.set(r,n)),n}var Wb=new Map;function qse(t,e={}){let{base:r,...n}=e,i=JSON.stringify([t,n]),o=Wb.get(i);return o===void 0&&(o=new Intl.RelativeTimeFormat(t,e),Wb.set(i,o)),o}var oA=null;function Hse(){return oA||(oA=new Intl.DateTimeFormat().resolvedOptions().locale,oA)}var Jb=new Map;function lU(t){let e=Jb.get(t);return e===void 0&&(e=new Intl.DateTimeFormat(t).resolvedOptions(),Jb.set(t,e)),e}var Zb=new Map;function Gse(t){let e=Zb.get(t);if(!e){let r=new Intl.Locale(t);e="getWeekInfo"in r?r.getWeekInfo():r.weekInfo,"minimalDays"in e||(e={...uU,...e}),Zb.set(t,e)}return e}function Yse(t){let e=t.indexOf("-x-");e!==-1&&(t=t.substring(0,e));let r=t.indexOf("-u-");if(r===-1)return[t];{let n,i;try{n=Yb(t).resolvedOptions(),i=t}catch{let c=t.substring(0,r);n=Yb(c).resolvedOptions(),i=c}let{numberingSystem:o,calendar:s}=n;return[i,o,s]}}function Vse(t,e,r){return(r||e)&&(t.includes("-u-")||(t+="-u"),r&&(t+=`-ca-${r}`),e&&(t+=`-nu-${e}`)),t}function Wse(t){let e=[];for(let r=1;r<=12;r++){let n=Bt.utc(2009,r,1);e.push(t(n))}return e}function Jse(t){let e=[];for(let r=1;r<=7;r++){let n=Bt.utc(2016,11,13+r);e.push(t(n))}return e}function Qg(t,e,r,n){let i=t.listingMode();return i==="error"?null:i==="en"?r(e):n(e)}function Zse(t){return t.numberingSystem&&t.numberingSystem!=="latn"?!1:t.numberingSystem==="latn"||!t.locale||t.locale.startsWith("en")||lU(t.locale).numberingSystem==="latn"}var Kb=class{constructor(e,r,n){this.padTo=n.padTo||0,this.floor=n.floor||!1;let{padTo:i,floor:o,...s}=n;if(!r||Object.keys(s).length>0){let a={useGrouping:!1,...n};n.padTo>0&&(a.minimumIntegerDigits=n.padTo),this.inf=zse(e,a)}}format(e){if(this.inf){let r=this.floor?Math.floor(e):e;return this.inf.format(r)}else{let r=this.floor?Math.floor(e):lS(e,3);return Wt(r,this.padTo)}}},Xb=class{constructor(e,r,n){this.opts=n,this.originalZone=void 0;let i;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){let s=-1*(e.offset/60),a=s>=0?`Etc/GMT+${s}`:`Etc/GMT${s}`;e.offset!==0&&Ss.create(a).valid?(i=a,this.dt=e):(i="UTC",this.dt=e.offset===0?e:e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type==="system"?this.dt=e:e.zone.type==="iana"?(this.dt=e,i=e.zone.name):(i="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);let o={...this.opts};o.timeZone=o.timeZone||i,this.dtf=Yb(r,o)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){let e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(r=>{if(r.type==="timeZoneName"){let n=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...r,value:n}}else return r}):e}resolvedOptions(){return this.dtf.resolvedOptions()}},eS=class{constructor(e,r,n){this.opts={style:"long",...n},!r&&mU()&&(this.rtf=qse(e,n))}format(e,r){return this.rtf?this.rtf.format(e,r):yae(r,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,r){return this.rtf?this.rtf.formatToParts(e,r):[]}},uU={firstDay:1,minimalDays:4,weekend:[6,7]},mt=class t{static fromOpts(e){return t.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,r,n,i,o=!1){let s=e||yt.defaultLocale,a=s||(o?"en-US":Hse()),c=r||yt.defaultNumberingSystem,l=n||yt.defaultOutputCalendar,u=rS(i)||yt.defaultWeekSettings;return new t(a,c,l,u,s)}static resetCache(){oA=null,Gb.clear(),Vb.clear(),Wb.clear(),Jb.clear(),Zb.clear()}static fromObject({locale:e,numberingSystem:r,outputCalendar:n,weekSettings:i}={}){return t.create(e,r,n,i)}constructor(e,r,n,i,o){let[s,a,c]=Yse(e);this.locale=s,this.numberingSystem=r||a||null,this.outputCalendar=n||c||null,this.weekSettings=i,this.intl=Vse(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=o,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=Zse(this)),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),r=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&r?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:t.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,rS(e.weekSettings)||this.weekSettings,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,r=!1){return Qg(this,e,bU,()=>{let n=this.intl==="ja"||this.intl.startsWith("ja-");r&=!n;let i=r?{month:e,day:"numeric"}:{month:e},o=r?"format":"standalone";if(!this.monthsCache[o][e]){let s=n?a=>this.dtFormatter(a,i).format():a=>this.extract(a,i,"month");this.monthsCache[o][e]=Wse(s)}return this.monthsCache[o][e]})}weekdays(e,r=!1){return Qg(this,e,_U,()=>{let n=r?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},i=r?"format":"standalone";return this.weekdaysCache[i][e]||(this.weekdaysCache[i][e]=Jse(o=>this.extract(o,n,"weekday"))),this.weekdaysCache[i][e]})}meridiems(){return Qg(this,void 0,()=>BU,()=>{if(!this.meridiemCache){let e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[Bt.utc(2016,11,13,9),Bt.utc(2016,11,13,19)].map(r=>this.extract(r,e,"dayperiod"))}return this.meridiemCache})}eras(e){return Qg(this,e,vU,()=>{let r={era:e};return this.eraCache[e]||(this.eraCache[e]=[Bt.utc(-40,1,1),Bt.utc(2017,1,1)].map(n=>this.extract(n,r,"era"))),this.eraCache[e]})}extract(e,r,n){let i=this.dtFormatter(e,r),o=i.formatToParts(),s=o.find(a=>a.type.toLowerCase()===n);return s?s.value:null}numberFormatter(e={}){return new Kb(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,r={}){return new Xb(e,this.intl,r)}relFormatter(e={}){return new eS(this.intl,this.isEnglish(),e)}listFormatter(e={}){return jse(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||lU(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:yU()?Gse(this.locale):uU}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}toString(){return`Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`}},xb=null,En=class t extends da{static get utcInstance(){return xb===null&&(xb=new t(0)),xb}static instance(e){return e===0?t.utcInstance:new t(e)}static parseSpecifier(e){if(e){let r=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(r)return new t(qg(r[1],r[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${cA(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${cA(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,r){return cA(this.fixed,r)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}},Mg=class extends da{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}};function ca(t,e){if(Qe(t)||t===null)return e;if(t instanceof da)return t;if(nae(t)){let r=t.toLowerCase();return r==="default"?e:r==="local"||r==="system"?lA.instance:r==="utc"||r==="gmt"?En.utcInstance:En.parseSpecifier(r)||Ss.create(t)}else return ua(t)?En.instance(t):typeof t=="object"&&"offset"in t&&typeof t.offset=="function"?t:new Mg(t)}var oS={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},fx={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},Kse=oS.hanidec.replace(/[\[|\]]/g,"").split("");function Xse(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(t[r].search(oS.hanidec)!==-1)e+=Kse.indexOf(t[r]);else for(let i in fx){let[o,s]=fx[i];n>=o&&n<=s&&(e+=n-o)}}return parseInt(e,10)}else return e}var tS=new Map;function eae(){tS.clear()}function Si({numberingSystem:t},e=""){let r=t||"latn",n=tS.get(r);n===void 0&&(n=new Map,tS.set(r,n));let i=n.get(e);return i===void 0&&(i=new RegExp(`${oS[r]}${e}`),n.set(e,i)),i}var gx=()=>Date.now(),mx="system",yx=null,Ex=null,Ix=null,Cx=60,bx,Sx=null,yt=class{static get now(){return gx}static set now(e){gx=e}static set defaultZone(e){mx=e}static get defaultZone(){return ca(mx,lA.instance)}static get defaultLocale(){return yx}static set defaultLocale(e){yx=e}static get defaultNumberingSystem(){return Ex}static set defaultNumberingSystem(e){Ex=e}static get defaultOutputCalendar(){return Ix}static set defaultOutputCalendar(e){Ix=e}static get defaultWeekSettings(){return Sx}static set defaultWeekSettings(e){Sx=rS(e)}static get twoDigitCutoffYear(){return Cx}static set twoDigitCutoffYear(e){Cx=e%100}static get throwOnInvalid(){return bx}static set throwOnInvalid(e){bx=e}static resetCaches(){mt.resetCache(),Ss.resetCache(),Bt.resetCache(),eae()}},mn=class{constructor(e,r){this.reason=e,this.explanation=r}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}},dU=[0,31,59,90,120,151,181,212,243,273,304,334],AU=[0,31,60,91,121,152,182,213,244,274,305,335];function Wn(t,e){return new mn("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function sS(t,e,r){let n=new Date(Date.UTC(t,e-1,r));t<100&&t>=0&&n.setUTCFullYear(n.getUTCFullYear()-1900);let i=n.getUTCDay();return i===0?7:i}function pU(t,e,r){return r+(dA(t)?AU:dU)[e-1]}function hU(t,e){let r=dA(t)?AU:dU,n=r.findIndex(o=>o<e),i=e-r[n];return{month:n+1,day:i}}function aS(t,e){return(t-e+7)%7+1}function Pg(t,e=4,r=1){let{year:n,month:i,day:o}=t,s=pU(n,i,o),a=aS(sS(n,i,o),r),c=Math.floor((s-a+14-e)/7),l;return c<1?(l=n-1,c=uA(l,e,r)):c>uA(n,e,r)?(l=n+1,c=1):l=n,{weekYear:l,weekNumber:c,weekday:a,...Hg(t)}}function wx(t,e=4,r=1){let{weekYear:n,weekNumber:i,weekday:o}=t,s=aS(sS(n,1,e),r),a=Yl(n),c=i*7+o-s-7+e,l;c<1?(l=n-1,c+=Yl(l)):c>a?(l=n+1,c-=Yl(n)):l=n;let{month:u,day:d}=hU(l,c);return{year:l,month:u,day:d,...Hg(t)}}function Ub(t){let{year:e,month:r,day:n}=t,i=pU(e,r,n);return{year:e,ordinal:i,...Hg(t)}}function _x(t){let{year:e,ordinal:r}=t,{month:n,day:i}=hU(e,r);return{year:e,month:n,day:i,...Hg(t)}}function Bx(t,e){if(!Qe(t.localWeekday)||!Qe(t.localWeekNumber)||!Qe(t.localWeekYear)){if(!Qe(t.weekday)||!Qe(t.weekNumber)||!Qe(t.weekYear))throw new la("Cannot mix locale-based week fields with ISO-based week fields");return Qe(t.localWeekday)||(t.weekday=t.localWeekday),Qe(t.localWeekNumber)||(t.weekNumber=t.localWeekNumber),Qe(t.localWeekYear)||(t.weekYear=t.localWeekYear),delete t.localWeekday,delete t.localWeekNumber,delete t.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function tae(t,e=4,r=1){let n=jg(t.weekYear),i=Jn(t.weekNumber,1,uA(t.weekYear,e,r)),o=Jn(t.weekday,1,7);return n?i?o?!1:Wn("weekday",t.weekday):Wn("week",t.weekNumber):Wn("weekYear",t.weekYear)}function rae(t){let e=jg(t.year),r=Jn(t.ordinal,1,Yl(t.year));return e?r?!1:Wn("ordinal",t.ordinal):Wn("year",t.year)}function fU(t){let e=jg(t.year),r=Jn(t.month,1,12),n=Jn(t.day,1,Lg(t.year,t.month));return e?r?n?!1:Wn("day",t.day):Wn("month",t.month):Wn("year",t.year)}function gU(t){let{hour:e,minute:r,second:n,millisecond:i}=t,o=Jn(e,0,23)||e===24&&r===0&&n===0&&i===0,s=Jn(r,0,59),a=Jn(n,0,59),c=Jn(i,0,999);return o?s?a?c?!1:Wn("millisecond",i):Wn("second",n):Wn("minute",r):Wn("hour",e)}function Qe(t){return typeof t>"u"}function ua(t){return typeof t=="number"}function jg(t){return typeof t=="number"&&t%1===0}function nae(t){return typeof t=="string"}function iae(t){return Object.prototype.toString.call(t)==="[object Date]"}function mU(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function yU(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function oae(t){return Array.isArray(t)?t:[t]}function vx(t,e,r){if(t.length!==0)return t.reduce((n,i)=>{let o=[e(i),i];return n&&r(n[0],o[0])===n[0]?n:o},null)[1]}function sae(t,e){return e.reduce((r,n)=>(r[n]=t[n],r),{})}function Wl(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function rS(t){if(t==null)return null;if(typeof t!="object")throw new dr("Week settings must be an object");if(!Jn(t.firstDay,1,7)||!Jn(t.minimalDays,1,7)||!Array.isArray(t.weekend)||t.weekend.some(e=>!Jn(e,1,7)))throw new dr("Invalid week settings");return{firstDay:t.firstDay,minimalDays:t.minimalDays,weekend:Array.from(t.weekend)}}function Jn(t,e,r){return jg(t)&&t>=e&&t<=r}function aae(t,e){return t-e*Math.floor(t/e)}function Wt(t,e=2){let r=t<0,n;return r?n="-"+(""+-t).padStart(e,"0"):n=(""+t).padStart(e,"0"),n}function aa(t){if(!(Qe(t)||t===null||t===""))return parseInt(t,10)}function dc(t){if(!(Qe(t)||t===null||t===""))return parseFloat(t)}function cS(t){if(!(Qe(t)||t===null||t==="")){let e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function lS(t,e,r="round"){let n=10**e;switch(r){case"expand":return t>0?Math.ceil(t*n)/n:Math.floor(t*n)/n;case"trunc":return Math.trunc(t*n)/n;case"round":return Math.round(t*n)/n;case"floor":return Math.floor(t*n)/n;case"ceil":return Math.ceil(t*n)/n;default:throw new RangeError(`Value rounding ${r} is out of range`)}}function dA(t){return t%4===0&&(t%100!==0||t%400===0)}function Yl(t){return dA(t)?366:365}function Lg(t,e){let r=aae(e-1,12)+1,n=t+(e-r)/12;return r===2?dA(n)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][r-1]}function zg(t){let e=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second,t.millisecond);return t.year<100&&t.year>=0&&(e=new Date(e),e.setUTCFullYear(t.year,t.month-1,t.day)),+e}function Qx(t,e,r){return-aS(sS(t,1,e),r)+e-1}function uA(t,e=4,r=1){let n=Qx(t,e,r),i=Qx(t+1,e,r);return(Yl(t)-n+i)/7}function nS(t){return t>99?t:t>yt.twoDigitCutoffYear?1900+t:2e3+t}function EU(t,e,r,n=null){let i=new Date(t),o={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};n&&(o.timeZone=n);let s={timeZoneName:e,...o},a=new Intl.DateTimeFormat(r,s).formatToParts(i).find(c=>c.type.toLowerCase()==="timezonename");return a?a.value:null}function qg(t,e){let r=parseInt(t,10);Number.isNaN(r)&&(r=0);let n=parseInt(e,10)||0,i=r<0||Object.is(r,-0)?-n:n;return r*60+i}function IU(t){let e=Number(t);if(typeof t=="boolean"||t===""||!Number.isFinite(e))throw new dr(`Invalid unit value ${t}`);return e}function $g(t,e){let r={};for(let n in t)if(Wl(t,n)){let i=t[n];if(i==null)continue;r[e(n)]=IU(i)}return r}function cA(t,e){let r=Math.trunc(Math.abs(t/60)),n=Math.trunc(Math.abs(t%60)),i=t>=0?"+":"-";switch(e){case"short":return`${i}${Wt(r,2)}:${Wt(n,2)}`;case"narrow":return`${i}${r}${n>0?`:${n}`:""}`;case"techie":return`${i}${Wt(r,2)}${Wt(n,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function Hg(t){return sae(t,["hour","minute","second","millisecond"])}var cae=["January","February","March","April","May","June","July","August","September","October","November","December"],CU=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],lae=["J","F","M","A","M","J","J","A","S","O","N","D"];function bU(t){switch(t){case"narrow":return[...lae];case"short":return[...CU];case"long":return[...cae];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}var SU=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],wU=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],uae=["M","T","W","T","F","S","S"];function _U(t){switch(t){case"narrow":return[...uae];case"short":return[...wU];case"long":return[...SU];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var BU=["AM","PM"],dae=["Before Christ","Anno Domini"],Aae=["BC","AD"],pae=["B","A"];function vU(t){switch(t){case"narrow":return[...pae];case"short":return[...Aae];case"long":return[...dae];default:return null}}function hae(t){return BU[t.hour<12?0:1]}function fae(t,e){return _U(e)[t.weekday-1]}function gae(t,e){return bU(e)[t.month-1]}function mae(t,e){return vU(e)[t.year<0?0:1]}function yae(t,e,r="always",n=!1){let i={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},o=["hours","minutes","seconds"].indexOf(t)===-1;if(r==="auto"&&o){let d=t==="days";switch(e){case 1:return d?"tomorrow":`next ${i[t][0]}`;case-1:return d?"yesterday":`last ${i[t][0]}`;case 0:return d?"today":`this ${i[t][0]}`}}let s=Object.is(e,-0)||e<0,a=Math.abs(e),c=a===1,l=i[t],u=n?c?l[1]:l[2]||l[1]:c?i[t][0]:t;return s?`${a} ${u} ago`:`in ${a} ${u}`}function Tx(t,e){let r="";for(let n of t)n.literal?r+=n.val:r+=e(n.val);return r}var Eae={D:Ug,DD:qx,DDD:Hx,DDDD:Gx,t:Yx,tt:Vx,ttt:Wx,tttt:Jx,T:Zx,TT:Kx,TTT:Xx,TTTT:eU,f:tU,ff:nU,fff:oU,ffff:aU,F:rU,FF:iU,FFF:sU,FFFF:cU},gn=class t{static create(e,r={}){return new t(e,r)}static parseFormat(e){let r=null,n="",i=!1,o=[];for(let s=0;s<e.length;s++){let a=e.charAt(s);a==="'"?((n.length>0||i)&&o.push({literal:i||/^\s+$/.test(n),val:n===""?"'":n}),r=null,n="",i=!i):i||a===r?n+=a:(n.length>0&&o.push({literal:/^\s+$/.test(n),val:n}),n=a,r=a)}return n.length>0&&o.push({literal:i||/^\s+$/.test(n),val:n}),o}static macroTokenToFormatOpts(e){return Eae[e]}constructor(e,r){this.opts=r,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,r){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...r}).format()}dtFormatter(e,r={}){return this.loc.dtFormatter(e,{...this.opts,...r})}formatDateTime(e,r){return this.dtFormatter(e,r).format()}formatDateTimeParts(e,r){return this.dtFormatter(e,r).formatToParts()}formatInterval(e,r){return this.dtFormatter(e.start,r).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,r){return this.dtFormatter(e,r).resolvedOptions()}num(e,r=0,n=void 0){if(this.opts.forceSimple)return Wt(e,r);let i={...this.opts};return r>0&&(i.padTo=r),n&&(i.signDisplay=n),this.loc.numberFormatter(i).format(e)}formatDateTimeFromString(e,r){let n=this.loc.listingMode()==="en",i=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",o=(p,h)=>this.loc.extract(e,p,h),s=p=>e.isOffsetFixed&&e.offset===0&&p.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,p.format):"",a=()=>n?hae(e):o({hour:"numeric",hourCycle:"h12"},"dayperiod"),c=(p,h)=>n?gae(e,p):o(h?{month:p}:{month:p,day:"numeric"},"month"),l=(p,h)=>n?fae(e,p):o(h?{weekday:p}:{weekday:p,month:"long",day:"numeric"},"weekday"),u=p=>{let h=t.macroTokenToFormatOpts(p);return h?this.formatWithSystemDefault(e,h):p},d=p=>n?mae(e,p):o({era:p},"era"),A=p=>{switch(p){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return s({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return s({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return s({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return a();case"d":return i?o({day:"numeric"},"day"):this.num(e.day);case"dd":return i?o({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return l("short",!0);case"cccc":return l("long",!0);case"ccccc":return l("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return l("short",!1);case"EEEE":return l("long",!1);case"EEEEE":return l("narrow",!1);case"L":return i?o({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return i?o({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return c("short",!0);case"LLLL":return c("long",!0);case"LLLLL":return c("narrow",!0);case"M":return i?o({month:"numeric"},"month"):this.num(e.month);case"MM":return i?o({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return c("short",!1);case"MMMM":return c("long",!1);case"MMMMM":return c("narrow",!1);case"y":return i?o({year:"numeric"},"year"):this.num(e.year);case"yy":return i?o({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return i?o({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return i?o({year:"numeric"},"year"):this.num(e.year,6);case"G":return d("short");case"GG":return d("long");case"GGGGG":return d("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return u(p)}};return Tx(t.parseFormat(r),A)}formatDurationFromString(e,r){let n=this.opts.signMode==="negativeLargestOnly"?-1:1,i=u=>{switch(u[0]){case"S":return"milliseconds";case"s":return"seconds";case"m":return"minutes";case"h":return"hours";case"d":return"days";case"w":return"weeks";case"M":return"months";case"y":return"years";default:return null}},o=(u,d)=>A=>{let p=i(A);if(p){let h=d.isNegativeDuration&&p!==d.largestUnit?n:1,f;return this.opts.signMode==="negativeLargestOnly"&&p!==d.largestUnit?f="never":this.opts.signMode==="all"?f="always":f="auto",this.num(u.get(p)*h,A.length,f)}else return A},s=t.parseFormat(r),a=s.reduce((u,{literal:d,val:A})=>d?u:u.concat(A),[]),c=e.shiftTo(...a.map(i).filter(u=>u)),l={isNegativeDuration:c<0,largestUnit:Object.keys(c.values)[0]};return Tx(s,o(c,l))}},QU=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Jl(...t){let e=t.reduce((r,n)=>r+n.source,"");return RegExp(`^${e}$`)}function Zl(...t){return e=>t.reduce(([r,n,i],o)=>{let[s,a,c]=o(e,i);return[{...r,...s},a||n,c]},[{},null,1]).slice(0,2)}function Kl(t,...e){if(t==null)return[null,null];for(let[r,n]of e){let i=r.exec(t);if(i)return n(i)}return[null,null]}function TU(...t){return(e,r)=>{let n={},i;for(i=0;i<t.length;i++)n[t[i]]=aa(e[r+i]);return[n,null,r+i]}}var DU=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,Iae=`(?:${DU.source}?(?:\\[(${QU.source})\\])?)?`,uS=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,kU=RegExp(`${uS.source}${Iae}`),dS=RegExp(`(?:[Tt]${kU.source})?`),Cae=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,bae=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Sae=/(\d{4})-?(\d{3})/,wae=TU("weekYear","weekNumber","weekDay"),_ae=TU("year","ordinal"),Bae=/(\d{4})-(\d\d)-(\d\d)/,RU=RegExp(`${uS.source} ?(?:${DU.source}|(${QU.source}))?`),vae=RegExp(`(?: ${RU.source})?`);function Vl(t,e,r){let n=t[e];return Qe(n)?r:aa(n)}function Qae(t,e){return[{year:Vl(t,e),month:Vl(t,e+1,1),day:Vl(t,e+2,1)},null,e+3]}function Xl(t,e){return[{hours:Vl(t,e,0),minutes:Vl(t,e+1,0),seconds:Vl(t,e+2,0),milliseconds:cS(t[e+3])},null,e+4]}function AA(t,e){let r=!t[e]&&!t[e+1],n=qg(t[e+1],t[e+2]),i=r?null:En.instance(n);return[{},i,e+3]}function pA(t,e){let r=t[e]?Ss.create(t[e]):null;return[{},r,e+1]}var Tae=RegExp(`^T?${uS.source}$`),Dae=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function kae(t){let[e,r,n,i,o,s,a,c,l]=t,u=e[0]==="-",d=c&&c[0]==="-",A=(p,h=!1)=>p!==void 0&&(h||p&&u)?-p:p;return[{years:A(dc(r)),months:A(dc(n)),weeks:A(dc(i)),days:A(dc(o)),hours:A(dc(s)),minutes:A(dc(a)),seconds:A(dc(c),c==="-0"),milliseconds:A(cS(l),d)}]}var Rae={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function AS(t,e,r,n,i,o,s){let a={year:e.length===2?nS(aa(e)):aa(e),month:CU.indexOf(r)+1,day:aa(n),hour:aa(i),minute:aa(o)};return s&&(a.second=aa(s)),t&&(a.weekday=t.length>3?SU.indexOf(t)+1:wU.indexOf(t)+1),a}var Nae=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function Oae(t){let[,e,r,n,i,o,s,a,c,l,u,d]=t,A=AS(e,i,n,r,o,s,a),p;return c?p=Rae[c]:l?p=0:p=qg(u,d),[A,new En(p)]}function xae(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var Uae=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,Mae=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,Pae=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function Dx(t){let[,e,r,n,i,o,s,a]=t;return[AS(e,i,n,r,o,s,a),En.utcInstance]}function Lae(t){let[,e,r,n,i,o,s,a]=t;return[AS(e,a,r,n,i,o,s),En.utcInstance]}var $ae=Jl(Cae,dS),Fae=Jl(bae,dS),jae=Jl(Sae,dS),zae=Jl(kU),NU=Zl(Qae,Xl,AA,pA),qae=Zl(wae,Xl,AA,pA),Hae=Zl(_ae,Xl,AA,pA),Gae=Zl(Xl,AA,pA);function Yae(t){return Kl(t,[$ae,NU],[Fae,qae],[jae,Hae],[zae,Gae])}function Vae(t){return Kl(xae(t),[Nae,Oae])}function Wae(t){return Kl(t,[Uae,Dx],[Mae,Dx],[Pae,Lae])}function Jae(t){return Kl(t,[Dae,kae])}var Zae=Zl(Xl);function Kae(t){return Kl(t,[Tae,Zae])}var Xae=Jl(Bae,vae),ece=Jl(RU),tce=Zl(Xl,AA,pA);function rce(t){return Kl(t,[Xae,NU],[ece,tce])}var kx="Invalid Duration",OU={weeks:{days:7,hours:168,minutes:10080,seconds:10080*60,milliseconds:10080*60*1e3},days:{hours:24,minutes:1440,seconds:1440*60,milliseconds:1440*60*1e3},hours:{minutes:60,seconds:3600,milliseconds:3600*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},nce={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:2184,minutes:2184*60,seconds:2184*60*60,milliseconds:2184*60*60*1e3},months:{weeks:4,days:30,hours:720,minutes:720*60,seconds:720*60*60,milliseconds:720*60*60*1e3},...OU},Vn=146097/400,ql=146097/4800,ice={years:{quarters:4,months:12,weeks:Vn/7,days:Vn,hours:Vn*24,minutes:Vn*24*60,seconds:Vn*24*60*60,milliseconds:Vn*24*60*60*1e3},quarters:{months:3,weeks:Vn/28,days:Vn/4,hours:Vn*24/4,minutes:Vn*24*60/4,seconds:Vn*24*60*60/4,milliseconds:Vn*24*60*60*1e3/4},months:{weeks:ql/7,days:ql,hours:ql*24,minutes:ql*24*60,seconds:ql*24*60*60,milliseconds:ql*24*60*60*1e3},...OU},pc=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],oce=pc.slice(0).reverse();function Cs(t,e,r=!1){let n={values:r?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy,matrix:e.matrix||t.matrix};return new or(n)}function xU(t,e){var r;let n=(r=e.milliseconds)!=null?r:0;for(let i of oce.slice(1))e[i]&&(n+=e[i]*t[i].milliseconds);return n}function Rx(t,e){let r=xU(t,e)<0?-1:1;pc.reduceRight((n,i)=>{if(Qe(e[i]))return n;if(n){let o=e[n]*r,s=t[i][n],a=Math.floor(o/s);e[i]+=a*r,e[n]-=a*s*r}return i},null),pc.reduce((n,i)=>{if(Qe(e[i]))return n;if(n){let o=e[n]%1;e[n]-=o,e[i]+=o*t[n][i]}return i},null)}function Nx(t){let e={};for(let[r,n]of Object.entries(t))n!==0&&(e[r]=n);return e}var or=class t{constructor(e){let r=e.conversionAccuracy==="longterm"||!1,n=r?ice:nce;e.matrix&&(n=e.matrix),this.values=e.values,this.loc=e.loc||mt.create(),this.conversionAccuracy=r?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=n,this.isLuxonDuration=!0}static fromMillis(e,r){return t.fromObject({milliseconds:e},r)}static fromObject(e,r={}){if(e==null||typeof e!="object")throw new dr(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new t({values:$g(e,t.normalizeUnit),loc:mt.fromObject(r),conversionAccuracy:r.conversionAccuracy,matrix:r.matrix})}static fromDurationLike(e){if(ua(e))return t.fromMillis(e);if(t.isDuration(e))return e;if(typeof e=="object")return t.fromObject(e);throw new dr(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,r){let[n]=Jae(e);return n?t.fromObject(n,r):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,r){let[n]=Kae(e);return n?t.fromObject(n,r):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,r=null){if(!e)throw new dr("need to specify a reason the Duration is invalid");let n=e instanceof mn?e:new mn(e,r);if(yt.throwOnInvalid)throw new qb(n);return new t({invalid:n})}static normalizeUnit(e){let r={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!r)throw new xg(e);return r}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,r={}){let n={...r,floor:r.round!==!1&&r.floor!==!1};return this.isValid?gn.create(this.loc,n).formatDurationFromString(this,e):kx}toHuman(e={}){if(!this.isValid)return kx;let r=e.showZeros!==!1,n=pc.map(i=>{let o=this.values[i];return Qe(o)||o===0&&!r?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:i.slice(0,-1)}).format(o)}).filter(i=>i);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(n)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=lS(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let r=this.toMillis();return r<0||r>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},Bt.fromMillis(r,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?xU(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;let r=t.fromDurationLike(e),n={};for(let i of pc)(Wl(r.values,i)||Wl(this.values,i))&&(n[i]=r.get(i)+this.get(i));return Cs(this,{values:n},!0)}minus(e){if(!this.isValid)return this;let r=t.fromDurationLike(e);return this.plus(r.negate())}mapUnits(e){if(!this.isValid)return this;let r={};for(let n of Object.keys(this.values))r[n]=IU(e(this.values[n],n));return Cs(this,{values:r},!0)}get(e){return this[t.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let r={...this.values,...$g(e,t.normalizeUnit)};return Cs(this,{values:r})}reconfigure({locale:e,numberingSystem:r,conversionAccuracy:n,matrix:i}={}){let s={loc:this.loc.clone({locale:e,numberingSystem:r}),matrix:i,conversionAccuracy:n};return Cs(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return Rx(this.matrix,e),Cs(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=Nx(this.normalize().shiftToAll().toObject());return Cs(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(s=>t.normalizeUnit(s));let r={},n={},i=this.toObject(),o;for(let s of pc)if(e.indexOf(s)>=0){o=s;let a=0;for(let l in n)a+=this.matrix[l][s]*n[l],n[l]=0;ua(i[s])&&(a+=i[s]);let c=Math.trunc(a);r[s]=c,n[s]=(a*1e3-c*1e3)/1e3}else ua(i[s])&&(n[s]=i[s]);for(let s in n)n[s]!==0&&(r[o]+=s===o?n[s]:n[s]/this.matrix[o][s]);return Rx(this.matrix,r),Cs(this,{values:r},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;let e={};for(let r of Object.keys(this.values))e[r]=this.values[r]===0?0:-this.values[r];return Cs(this,{values:e},!0)}removeZeros(){if(!this.isValid)return this;let e=Nx(this.values);return Cs(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function r(n,i){return n===void 0||n===0?i===void 0||i===0:n===i}for(let n of pc)if(!r(this.values[n],e.values[n]))return!1;return!0}},Hl="Invalid Interval";function sce(t,e){return!t||!t.isValid?fc.invalid("missing or invalid start"):!e||!e.isValid?fc.invalid("missing or invalid end"):e<t?fc.invalid("end before start",`The end of an interval must be after its start, but you had start=${t.toISO()} and end=${e.toISO()}`):null}var fc=class t{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,r=null){if(!e)throw new dr("need to specify a reason the Interval is invalid");let n=e instanceof mn?e:new mn(e,r);if(yt.throwOnInvalid)throw new zb(n);return new t({invalid:n})}static fromDateTimes(e,r){let n=iA(e),i=iA(r),o=sce(n,i);return o??new t({start:n,end:i})}static after(e,r){let n=or.fromDurationLike(r),i=iA(e);return t.fromDateTimes(i,i.plus(n))}static before(e,r){let n=or.fromDurationLike(r),i=iA(e);return t.fromDateTimes(i.minus(n),i)}static fromISO(e,r){let[n,i]=(e||"").split("/",2);if(n&&i){let o,s;try{o=Bt.fromISO(n,r),s=o.isValid}catch{s=!1}let a,c;try{a=Bt.fromISO(i,r),c=a.isValid}catch{c=!1}if(s&&c)return t.fromDateTimes(o,a);if(s){let l=or.fromISO(i,r);if(l.isValid)return t.after(o,l)}else if(c){let l=or.fromISO(n,r);if(l.isValid)return t.before(a,l)}}return t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get lastDateTime(){return this.isValid&&this.e?this.e.minus(1):null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds",r){if(!this.isValid)return NaN;let n=this.start.startOf(e,r),i;return r!=null&&r.useLocaleWeeks?i=this.end.reconfigure({locale:n.locale}):i=this.end,i=i.startOf(e,r),Math.floor(i.diff(n,e).get(e))+(i.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:r}={}){return this.isValid?t.fromDateTimes(e||this.s,r||this.e):this}splitAt(...e){if(!this.isValid)return[];let r=e.map(iA).filter(s=>this.contains(s)).sort((s,a)=>s.toMillis()-a.toMillis()),n=[],{s:i}=this,o=0;for(;i<this.e;){let s=r[o]||this.e,a=+s>+this.e?this.e:s;n.push(t.fromDateTimes(i,a)),i=a,o+=1}return n}splitBy(e){let r=or.fromDurationLike(e);if(!this.isValid||!r.isValid||r.as("milliseconds")===0)return[];let{s:n}=this,i=1,o,s=[];for(;n<this.e;){let a=this.start.plus(r.mapUnits(c=>c*i));o=+a>+this.e?this.e:a,s.push(t.fromDateTimes(n,o)),n=o,i+=1}return s}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;let r=this.s>e.s?this.s:e.s,n=this.e<e.e?this.e:e.e;return r>=n?null:t.fromDateTimes(r,n)}union(e){if(!this.isValid)return this;let r=this.s<e.s?this.s:e.s,n=this.e>e.e?this.e:e.e;return t.fromDateTimes(r,n)}static merge(e){let[r,n]=e.sort((i,o)=>i.s-o.s).reduce(([i,o],s)=>o?o.overlaps(s)||o.abutsStart(s)?[i,o.union(s)]:[i.concat([o]),s]:[i,s],[[],null]);return n&&r.push(n),r}static xor(e){let r=null,n=0,i=[],o=e.map(c=>[{time:c.s,type:"s"},{time:c.e,type:"e"}]),s=Array.prototype.concat(...o),a=s.sort((c,l)=>c.time-l.time);for(let c of a)n+=c.type==="s"?1:-1,n===1?r=c.time:(r&&+r!=+c.time&&i.push(t.fromDateTimes(r,c.time)),r=null);return t.merge(i)}difference(...e){return t.xor([this].concat(e)).map(r=>this.intersection(r)).filter(r=>r&&!r.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:Hl}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(e=Ug,r={}){return this.isValid?gn.create(this.s.loc.clone(r),e).formatInterval(this):Hl}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:Hl}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Hl}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:Hl}toFormat(e,{separator:r=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${r}${this.e.toFormat(e)}`:Hl}toDuration(e,r){return this.isValid?this.e.diff(this.s,e,r):or.invalid(this.invalidReason)}mapEndpoints(e){return t.fromDateTimes(e(this.s),e(this.e))}},hc=class{static hasDST(e=yt.defaultZone){let r=Bt.now().setZone(e).set({month:12});return!e.isUniversal&&r.offset!==r.set({month:6}).offset}static isValidIANAZone(e){return Ss.isValidZone(e)}static normalizeZone(e){return ca(e,yt.defaultZone)}static getStartOfWeek({locale:e=null,locObj:r=null}={}){return(r||mt.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:r=null}={}){return(r||mt.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:r=null}={}){return(r||mt.create(e)).getWeekendDays().slice()}static months(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null,outputCalendar:o="gregory"}={}){return(i||mt.create(r,n,o)).months(e)}static monthsFormat(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null,outputCalendar:o="gregory"}={}){return(i||mt.create(r,n,o)).months(e,!0)}static weekdays(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null}={}){return(i||mt.create(r,n,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null}={}){return(i||mt.create(r,n,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return mt.create(e).meridiems()}static eras(e="short",{locale:r=null}={}){return mt.create(r,null,"gregory").eras(e)}static features(){return{relative:mU(),localeWeek:yU()}}};function Ox(t,e){let r=i=>i.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),n=r(e)-r(t);return Math.floor(or.fromMillis(n).as("days"))}function ace(t,e,r){let n=[["years",(c,l)=>l.year-c.year],["quarters",(c,l)=>l.quarter-c.quarter+(l.year-c.year)*4],["months",(c,l)=>l.month-c.month+(l.year-c.year)*12],["weeks",(c,l)=>{let u=Ox(c,l);return(u-u%7)/7}],["days",Ox]],i={},o=t,s,a;for(let[c,l]of n)r.indexOf(c)>=0&&(s=c,i[c]=l(t,e),a=o.plus(i),a>e?(i[c]--,t=o.plus(i),t>e&&(a=t,i[c]--,t=o.plus(i))):t=a);return[t,i,a,s]}function cce(t,e,r,n){let[i,o,s,a]=ace(t,e,r),c=e-i,l=r.filter(d=>["hours","minutes","seconds","milliseconds"].indexOf(d)>=0);l.length===0&&(s<e&&(s=i.plus({[a]:1})),s!==i&&(o[a]=(o[a]||0)+c/(s-i)));let u=or.fromObject(o,n);return l.length>0?or.fromMillis(c,n).shiftTo(...l).plus(u):u}var lce="missing Intl.DateTimeFormat.formatToParts support";function nt(t,e=r=>r){return{regex:t,deser:([r])=>e(Xse(r))}}var uce="\xA0",UU=`[ ${uce}]`,MU=new RegExp(UU,"g");function dce(t){return t.replace(/\./g,"\\.?").replace(MU,UU)}function xx(t){return t.replace(/\./g,"").replace(MU," ").toLowerCase()}function wi(t,e){return t===null?null:{regex:RegExp(t.map(dce).join("|")),deser:([r])=>t.findIndex(n=>xx(r)===xx(n))+e}}function Ux(t,e){return{regex:t,deser:([,r,n])=>qg(r,n),groups:e}}function Tg(t){return{regex:t,deser:([e])=>e}}function Ace(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function pce(t,e){let r=Si(e),n=Si(e,"{2}"),i=Si(e,"{3}"),o=Si(e,"{4}"),s=Si(e,"{6}"),a=Si(e,"{1,2}"),c=Si(e,"{1,3}"),l=Si(e,"{1,6}"),u=Si(e,"{1,9}"),d=Si(e,"{2,4}"),A=Si(e,"{4,6}"),p=E=>({regex:RegExp(Ace(E.val)),deser:([S])=>S,literal:!0}),f=(E=>{if(t.literal)return p(E);switch(E.val){case"G":return wi(e.eras("short"),0);case"GG":return wi(e.eras("long"),0);case"y":return nt(l);case"yy":return nt(d,nS);case"yyyy":return nt(o);case"yyyyy":return nt(A);case"yyyyyy":return nt(s);case"M":return nt(a);case"MM":return nt(n);case"MMM":return wi(e.months("short",!0),1);case"MMMM":return wi(e.months("long",!0),1);case"L":return nt(a);case"LL":return nt(n);case"LLL":return wi(e.months("short",!1),1);case"LLLL":return wi(e.months("long",!1),1);case"d":return nt(a);case"dd":return nt(n);case"o":return nt(c);case"ooo":return nt(i);case"HH":return nt(n);case"H":return nt(a);case"hh":return nt(n);case"h":return nt(a);case"mm":return nt(n);case"m":return nt(a);case"q":return nt(a);case"qq":return nt(n);case"s":return nt(a);case"ss":return nt(n);case"S":return nt(c);case"SSS":return nt(i);case"u":return Tg(u);case"uu":return Tg(a);case"uuu":return nt(r);case"a":return wi(e.meridiems(),0);case"kkkk":return nt(o);case"kk":return nt(d,nS);case"W":return nt(a);case"WW":return nt(n);case"E":case"c":return nt(r);case"EEE":return wi(e.weekdays("short",!1),1);case"EEEE":return wi(e.weekdays("long",!1),1);case"ccc":return wi(e.weekdays("short",!0),1);case"cccc":return wi(e.weekdays("long",!0),1);case"Z":case"ZZ":return Ux(new RegExp(`([+-]${a.source})(?::(${n.source}))?`),2);case"ZZZ":return Ux(new RegExp(`([+-]${a.source})(${n.source})?`),2);case"z":return Tg(/[a-z_+-/]{1,256}?/i);case" ":return Tg(/[^\S\n\r]/);default:return p(E)}})(t)||{invalidReason:lce};return f.token=t,f}var hce={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function fce(t,e,r){let{type:n,value:i}=t;if(n==="literal"){let c=/^\s+$/.test(i);return{literal:!c,val:c?" ":i}}let o=e[n],s=n;n==="hour"&&(e.hour12!=null?s=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?s="hour12":s="hour24":s=r.hour12?"hour12":"hour24");let a=hce[s];if(typeof a=="object"&&(a=a[o]),a)return{literal:!1,val:a}}function gce(t){return[`^${t.map(r=>r.regex).reduce((r,n)=>`${r}(${n.source})`,"")}$`,t]}function mce(t,e,r){let n=t.match(e);if(n){let i={},o=1;for(let s in r)if(Wl(r,s)){let a=r[s],c=a.groups?a.groups+1:1;!a.literal&&a.token&&(i[a.token.val[0]]=a.deser(n.slice(o,o+c))),o+=c}return[n,i]}else return[n,{}]}function yce(t){let e=o=>{switch(o){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},r=null,n;return Qe(t.z)||(r=Ss.create(t.z)),Qe(t.Z)||(r||(r=new En(t.Z)),n=t.Z),Qe(t.q)||(t.M=(t.q-1)*3+1),Qe(t.h)||(t.h<12&&t.a===1?t.h+=12:t.h===12&&t.a===0&&(t.h=0)),t.G===0&&t.y&&(t.y=-t.y),Qe(t.u)||(t.S=cS(t.u)),[Object.keys(t).reduce((o,s)=>{let a=e(s);return a&&(o[a]=t[s]),o},{}),r,n]}var Mb=null;function Ece(){return Mb||(Mb=Bt.fromMillis(1555555555555)),Mb}function Ice(t,e){if(t.literal)return t;let r=gn.macroTokenToFormatOpts(t.val),n=$U(r,e);return n==null||n.includes(void 0)?t:n}function PU(t,e){return Array.prototype.concat(...t.map(r=>Ice(r,e)))}var Fg=class{constructor(e,r){if(this.locale=e,this.format=r,this.tokens=PU(gn.parseFormat(r),e),this.units=this.tokens.map(n=>pce(n,e)),this.disqualifyingUnit=this.units.find(n=>n.invalidReason),!this.disqualifyingUnit){let[n,i]=gce(this.units);this.regex=RegExp(n,"i"),this.handlers=i}}explainFromTokens(e){if(this.isValid){let[r,n]=mce(e,this.regex,this.handlers),[i,o,s]=n?yce(n):[null,null,void 0];if(Wl(n,"a")&&Wl(n,"H"))throw new la("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:this.tokens,regex:this.regex,rawMatches:r,matches:n,result:i,zone:o,specificOffset:s}}else return{input:e,tokens:this.tokens,invalidReason:this.invalidReason}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}};function LU(t,e,r){return new Fg(t,r).explainFromTokens(e)}function Cce(t,e,r){let{result:n,zone:i,specificOffset:o,invalidReason:s}=LU(t,e,r);return[n,i,o,s]}function $U(t,e){if(!t)return null;let n=gn.create(e,t).dtFormatter(Ece()),i=n.formatToParts(),o=n.resolvedOptions();return i.map(s=>fce(s,t,o))}var Pb="Invalid DateTime",Mx=864e13;function sA(t){return new mn("unsupported zone",`the zone "${t.name}" is not supported`)}function Lb(t){return t.weekData===null&&(t.weekData=Pg(t.c)),t.weekData}function $b(t){return t.localWeekData===null&&(t.localWeekData=Pg(t.c,t.loc.getMinDaysInFirstWeek(),t.loc.getStartOfWeek())),t.localWeekData}function Ac(t,e){let r={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new Bt({...r,...e,old:r})}function FU(t,e,r){let n=t-e*60*1e3,i=r.offset(n);if(e===i)return[n,e];n-=(i-e)*60*1e3;let o=r.offset(n);return i===o?[n,i]:[t-Math.min(i,o)*60*1e3,Math.max(i,o)]}function Dg(t,e){t+=e*60*1e3;let r=new Date(t);return{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate(),hour:r.getUTCHours(),minute:r.getUTCMinutes(),second:r.getUTCSeconds(),millisecond:r.getUTCMilliseconds()}}function Rg(t,e,r){return FU(zg(t),e,r)}function Px(t,e){let r=t.o,n=t.c.year+Math.trunc(e.years),i=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,o={...t.c,year:n,month:i,day:Math.min(t.c.day,Lg(n,i))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},s=or.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),a=zg(o),[c,l]=FU(a,r,t.zone);return s!==0&&(c+=s,l=t.zone.offset(c)),{ts:c,o:l}}function Gl(t,e,r,n,i,o){let{setZone:s,zone:a}=r;if(t&&Object.keys(t).length!==0||e){let c=e||a,l=Bt.fromObject(t,{...r,zone:c,specificOffset:o});return s?l:l.setZone(a)}else return Bt.invalid(new mn("unparsable",`the input "${i}" can't be parsed as ${n}`))}function kg(t,e,r=!0){return t.isValid?gn.create(mt.create("en-US"),{allowZ:r,forceSimple:!0}).formatDateTimeFromString(t,e):null}function Fb(t,e,r){let n=t.c.year>9999||t.c.year<0,i="";if(n&&t.c.year>=0&&(i+="+"),i+=Wt(t.c.year,n?6:4),r==="year")return i;if(e){if(i+="-",i+=Wt(t.c.month),r==="month")return i;i+="-"}else if(i+=Wt(t.c.month),r==="month")return i;return i+=Wt(t.c.day),i}function Lx(t,e,r,n,i,o,s){let a=!r||t.c.millisecond!==0||t.c.second!==0,c="";switch(s){case"day":case"month":case"year":break;default:if(c+=Wt(t.c.hour),s==="hour")break;if(e){if(c+=":",c+=Wt(t.c.minute),s==="minute")break;a&&(c+=":",c+=Wt(t.c.second))}else{if(c+=Wt(t.c.minute),s==="minute")break;a&&(c+=Wt(t.c.second))}if(s==="second")break;a&&(!n||t.c.millisecond!==0)&&(c+=".",c+=Wt(t.c.millisecond,3))}return i&&(t.isOffsetFixed&&t.offset===0&&!o?c+="Z":t.o<0?(c+="-",c+=Wt(Math.trunc(-t.o/60)),c+=":",c+=Wt(Math.trunc(-t.o%60))):(c+="+",c+=Wt(Math.trunc(t.o/60)),c+=":",c+=Wt(Math.trunc(t.o%60)))),o&&(c+="["+t.zone.ianaName+"]"),c}var jU={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},bce={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Sce={ordinal:1,hour:0,minute:0,second:0,millisecond:0},Ng=["year","month","day","hour","minute","second","millisecond"],wce=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],_ce=["year","ordinal","hour","minute","second","millisecond"];function Og(t){let e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[t.toLowerCase()];if(!e)throw new xg(t);return e}function $x(t){switch(t.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return Og(t)}}function Bce(t){if(aA===void 0&&(aA=yt.now()),t.type!=="iana")return t.offset(aA);let e=t.name,r=iS.get(e);return r===void 0&&(r=t.offset(aA),iS.set(e,r)),r}function Fx(t,e){let r=ca(e.zone,yt.defaultZone);if(!r.isValid)return Bt.invalid(sA(r));let n=mt.fromObject(e),i,o;if(Qe(t.year))i=yt.now();else{for(let c of Ng)Qe(t[c])&&(t[c]=jU[c]);let s=fU(t)||gU(t);if(s)return Bt.invalid(s);let a=Bce(r);[i,o]=Rg(t,a,r)}return new Bt({ts:i,zone:r,loc:n,o})}function jx(t,e,r){let n=Qe(r.round)?!0:r.round,i=Qe(r.rounding)?"trunc":r.rounding,o=(a,c)=>(a=lS(a,n||r.calendary?0:2,r.calendary?"round":i),e.loc.clone(r).relFormatter(r).format(a,c)),s=a=>r.calendary?e.hasSame(t,a)?0:e.startOf(a).diff(t.startOf(a),a).get(a):e.diff(t,a).get(a);if(r.unit)return o(s(r.unit),r.unit);for(let a of r.units){let c=s(a);if(Math.abs(c)>=1)return o(c,a)}return o(t>e?-0:0,r.units[r.units.length-1])}function zx(t){let e={},r;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],r=Array.from(t).slice(0,t.length-1)):r=Array.from(t),[e,r]}var aA,iS=new Map,Bt=class t{constructor(e){let r=e.zone||yt.defaultZone,n=e.invalid||(Number.isNaN(e.ts)?new mn("invalid input"):null)||(r.isValid?null:sA(r));this.ts=Qe(e.ts)?yt.now():e.ts;let i=null,o=null;if(!n)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(r))[i,o]=[e.old.c,e.old.o];else{let a=ua(e.o)&&!e.old?e.o:r.offset(this.ts);i=Dg(this.ts,a),n=Number.isNaN(i.year)?new mn("invalid input"):null,i=n?null:i,o=n?null:a}this._zone=r,this.loc=e.loc||mt.create(),this.invalid=n,this.weekData=null,this.localWeekData=null,this.c=i,this.o=o,this.isLuxonDateTime=!0}static now(){return new t({})}static local(){let[e,r]=zx(arguments),[n,i,o,s,a,c,l]=r;return Fx({year:n,month:i,day:o,hour:s,minute:a,second:c,millisecond:l},e)}static utc(){let[e,r]=zx(arguments),[n,i,o,s,a,c,l]=r;return e.zone=En.utcInstance,Fx({year:n,month:i,day:o,hour:s,minute:a,second:c,millisecond:l},e)}static fromJSDate(e,r={}){let n=iae(e)?e.valueOf():NaN;if(Number.isNaN(n))return t.invalid("invalid input");let i=ca(r.zone,yt.defaultZone);return i.isValid?new t({ts:n,zone:i,loc:mt.fromObject(r)}):t.invalid(sA(i))}static fromMillis(e,r={}){if(ua(e))return e<-Mx||e>Mx?t.invalid("Timestamp out of range"):new t({ts:e,zone:ca(r.zone,yt.defaultZone),loc:mt.fromObject(r)});throw new dr(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,r={}){if(ua(e))return new t({ts:e*1e3,zone:ca(r.zone,yt.defaultZone),loc:mt.fromObject(r)});throw new dr("fromSeconds requires a numerical input")}static fromObject(e,r={}){e=e||{};let n=ca(r.zone,yt.defaultZone);if(!n.isValid)return t.invalid(sA(n));let i=mt.fromObject(r),o=$g(e,$x),{minDaysInFirstWeek:s,startOfWeek:a}=Bx(o,i),c=yt.now(),l=Qe(r.specificOffset)?n.offset(c):r.specificOffset,u=!Qe(o.ordinal),d=!Qe(o.year),A=!Qe(o.month)||!Qe(o.day),p=d||A,h=o.weekYear||o.weekNumber;if((p||u)&&h)throw new la("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(A&&u)throw new la("Can't mix ordinal dates with month/day");let f=h||o.weekday&&!p,E,S,B=Dg(c,l);f?(E=wce,S=bce,B=Pg(B,s,a)):u?(E=_ce,S=Sce,B=Ub(B)):(E=Ng,S=jU);let _=!1;for(let K of E){let Ae=o[K];Qe(Ae)?_?o[K]=S[K]:o[K]=B[K]:_=!0}let v=f?tae(o,s,a):u?rae(o):fU(o),T=v||gU(o);if(T)return t.invalid(T);let L=f?wx(o,s,a):u?_x(o):o,[k,P]=Rg(L,l,n),U=new t({ts:k,zone:n,o:P,loc:i});return o.weekday&&p&&e.weekday!==U.weekday?t.invalid("mismatched weekday",`you can't specify both a weekday of ${o.weekday} and a date of ${U.toISO()}`):U.isValid?U:t.invalid(U.invalid)}static fromISO(e,r={}){let[n,i]=Yae(e);return Gl(n,i,r,"ISO 8601",e)}static fromRFC2822(e,r={}){let[n,i]=Vae(e);return Gl(n,i,r,"RFC 2822",e)}static fromHTTP(e,r={}){let[n,i]=Wae(e);return Gl(n,i,r,"HTTP",r)}static fromFormat(e,r,n={}){if(Qe(e)||Qe(r))throw new dr("fromFormat requires an input string and a format");let{locale:i=null,numberingSystem:o=null}=n,s=mt.fromOpts({locale:i,numberingSystem:o,defaultToEN:!0}),[a,c,l,u]=Cce(s,e,r);return u?t.invalid(u):Gl(a,c,n,`format ${r}`,e,l)}static fromString(e,r,n={}){return t.fromFormat(e,r,n)}static fromSQL(e,r={}){let[n,i]=rce(e);return Gl(n,i,r,"SQL",e)}static invalid(e,r=null){if(!e)throw new dr("need to specify a reason the DateTime is invalid");let n=e instanceof mn?e:new mn(e,r);if(yt.throwOnInvalid)throw new jb(n);return new t({invalid:n})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,r={}){let n=$U(e,mt.fromObject(r));return n?n.map(i=>i?i.val:null).join(""):null}static expandFormat(e,r={}){return PU(gn.parseFormat(e),mt.fromObject(r)).map(i=>i.val).join("")}static resetCache(){aA=void 0,iS.clear()}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?Lb(this).weekYear:NaN}get weekNumber(){return this.isValid?Lb(this).weekNumber:NaN}get weekday(){return this.isValid?Lb(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?$b(this).weekday:NaN}get localWeekNumber(){return this.isValid?$b(this).weekNumber:NaN}get localWeekYear(){return this.isValid?$b(this).weekYear:NaN}get ordinal(){return this.isValid?Ub(this.c).ordinal:NaN}get monthShort(){return this.isValid?hc.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?hc.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?hc.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?hc.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];let e=864e5,r=6e4,n=zg(this.c),i=this.zone.offset(n-e),o=this.zone.offset(n+e),s=this.zone.offset(n-i*r),a=this.zone.offset(n-o*r);if(s===a)return[this];let c=n-s*r,l=n-a*r,u=Dg(c,s),d=Dg(l,a);return u.hour===d.hour&&u.minute===d.minute&&u.second===d.second&&u.millisecond===d.millisecond?[Ac(this,{ts:c}),Ac(this,{ts:l})]:[this]}get isInLeapYear(){return dA(this.year)}get daysInMonth(){return Lg(this.year,this.month)}get daysInYear(){return this.isValid?Yl(this.year):NaN}get weeksInWeekYear(){return this.isValid?uA(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?uA(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){let{locale:r,numberingSystem:n,calendar:i}=gn.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:r,numberingSystem:n,outputCalendar:i}}toUTC(e=0,r={}){return this.setZone(En.instance(e),r)}toLocal(){return this.setZone(yt.defaultZone)}setZone(e,{keepLocalTime:r=!1,keepCalendarTime:n=!1}={}){if(e=ca(e,yt.defaultZone),e.equals(this.zone))return this;if(e.isValid){let i=this.ts;if(r||n){let o=e.offset(this.ts),s=this.toObject();[i]=Rg(s,o,e)}return Ac(this,{ts:i,zone:e})}else return t.invalid(sA(e))}reconfigure({locale:e,numberingSystem:r,outputCalendar:n}={}){let i=this.loc.clone({locale:e,numberingSystem:r,outputCalendar:n});return Ac(this,{loc:i})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let r=$g(e,$x),{minDaysInFirstWeek:n,startOfWeek:i}=Bx(r,this.loc),o=!Qe(r.weekYear)||!Qe(r.weekNumber)||!Qe(r.weekday),s=!Qe(r.ordinal),a=!Qe(r.year),c=!Qe(r.month)||!Qe(r.day),l=a||c,u=r.weekYear||r.weekNumber;if((l||s)&&u)throw new la("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(c&&s)throw new la("Can't mix ordinal dates with month/day");let d;o?d=wx({...Pg(this.c,n,i),...r},n,i):Qe(r.ordinal)?(d={...this.toObject(),...r},Qe(r.day)&&(d.day=Math.min(Lg(d.year,d.month),d.day))):d=_x({...Ub(this.c),...r});let[A,p]=Rg(d,this.o,this.zone);return Ac(this,{ts:A,o:p})}plus(e){if(!this.isValid)return this;let r=or.fromDurationLike(e);return Ac(this,Px(this,r))}minus(e){if(!this.isValid)return this;let r=or.fromDurationLike(e).negate();return Ac(this,Px(this,r))}startOf(e,{useLocaleWeeks:r=!1}={}){if(!this.isValid)return this;let n={},i=or.normalizeUnit(e);switch(i){case"years":n.month=1;case"quarters":case"months":n.day=1;case"weeks":case"days":n.hour=0;case"hours":n.minute=0;case"minutes":n.second=0;case"seconds":n.millisecond=0;break}if(i==="weeks")if(r){let o=this.loc.getStartOfWeek(),{weekday:s}=this;s<o&&(n.weekNumber=this.weekNumber-1),n.weekday=o}else n.weekday=1;if(i==="quarters"){let o=Math.ceil(this.month/3);n.month=(o-1)*3+1}return this.set(n)}endOf(e,r){return this.isValid?this.plus({[e]:1}).startOf(e,r).minus(1):this}toFormat(e,r={}){return this.isValid?gn.create(this.loc.redefaultToEN(r)).formatDateTimeFromString(this,e):Pb}toLocaleString(e=Ug,r={}){return this.isValid?gn.create(this.loc.clone(r),e).formatDateTime(this):Pb}toLocaleParts(e={}){return this.isValid?gn.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:r=!1,suppressMilliseconds:n=!1,includeOffset:i=!0,extendedZone:o=!1,precision:s="milliseconds"}={}){if(!this.isValid)return null;s=Og(s);let a=e==="extended",c=Fb(this,a,s);return Ng.indexOf(s)>=3&&(c+="T"),c+=Lx(this,a,r,n,i,o,s),c}toISODate({format:e="extended",precision:r="day"}={}){return this.isValid?Fb(this,e==="extended",Og(r)):null}toISOWeekDate(){return kg(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:r=!1,includeOffset:n=!0,includePrefix:i=!1,extendedZone:o=!1,format:s="extended",precision:a="milliseconds"}={}){return this.isValid?(a=Og(a),(i&&Ng.indexOf(a)>=3?"T":"")+Lx(this,s==="extended",r,e,n,o,a)):null}toRFC2822(){return kg(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return kg(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?Fb(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:r=!1,includeOffsetSpace:n=!0}={}){let i="HH:mm:ss.SSS";return(r||e)&&(n&&(i+=" "),r?i+="z":e&&(i+="ZZ")),kg(this,i,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():Pb}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};let r={...this.c};return e.includeConfig&&(r.outputCalendar=this.outputCalendar,r.numberingSystem=this.loc.numberingSystem,r.locale=this.loc.locale),r}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,r="milliseconds",n={}){if(!this.isValid||!e.isValid)return or.invalid("created by diffing an invalid DateTime");let i={locale:this.locale,numberingSystem:this.numberingSystem,...n},o=oae(r).map(or.normalizeUnit),s=e.valueOf()>this.valueOf(),a=s?this:e,c=s?e:this,l=cce(a,c,o,i);return s?l.negate():l}diffNow(e="milliseconds",r={}){return this.diff(t.now(),e,r)}until(e){return this.isValid?fc.fromDateTimes(this,e):this}hasSame(e,r,n){if(!this.isValid)return!1;let i=e.valueOf(),o=this.setZone(e.zone,{keepLocalTime:!0});return o.startOf(r,n)<=i&&i<=o.endOf(r,n)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;let r=e.base||t.fromObject({},{zone:this.zone}),n=e.padding?this<r?-e.padding:e.padding:0,i=["years","months","days","hours","minutes","seconds"],o=e.unit;return Array.isArray(e.unit)&&(i=e.unit,o=void 0),jx(r,this.plus(n),{...e,numeric:"always",units:i,unit:o})}toRelativeCalendar(e={}){return this.isValid?jx(e.base||t.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(t.isDateTime))throw new dr("min requires all arguments be DateTimes");return vx(e,r=>r.valueOf(),Math.min)}static max(...e){if(!e.every(t.isDateTime))throw new dr("max requires all arguments be DateTimes");return vx(e,r=>r.valueOf(),Math.max)}static fromFormatExplain(e,r,n={}){let{locale:i=null,numberingSystem:o=null}=n,s=mt.fromOpts({locale:i,numberingSystem:o,defaultToEN:!0});return LU(s,e,r)}static fromStringExplain(e,r,n={}){return t.fromFormatExplain(e,r,n)}static buildFormatParser(e,r={}){let{locale:n=null,numberingSystem:i=null}=r,o=mt.fromOpts({locale:n,numberingSystem:i,defaultToEN:!0});return new Fg(o,e)}static fromFormatParser(e,r,n={}){if(Qe(e)||Qe(r))throw new dr("fromFormatParser requires an input string and a format parser");let{locale:i=null,numberingSystem:o=null}=n,s=mt.fromOpts({locale:i,numberingSystem:o,defaultToEN:!0});if(!s.equals(r.locale))throw new dr(`fromFormatParser called with a locale of ${s}, but the format parser was created for ${r.locale}`);let{result:a,zone:c,specificOffset:l,invalidReason:u}=r.explainFromTokens(e);return u?t.invalid(u):Gl(a,c,n,`format ${r.format}`,e,l)}static get DATE_SHORT(){return Ug}static get DATE_MED(){return qx}static get DATE_MED_WITH_WEEKDAY(){return Use}static get DATE_FULL(){return Hx}static get DATE_HUGE(){return Gx}static get TIME_SIMPLE(){return Yx}static get TIME_WITH_SECONDS(){return Vx}static get TIME_WITH_SHORT_OFFSET(){return Wx}static get TIME_WITH_LONG_OFFSET(){return Jx}static get TIME_24_SIMPLE(){return Zx}static get TIME_24_WITH_SECONDS(){return Kx}static get TIME_24_WITH_SHORT_OFFSET(){return Xx}static get TIME_24_WITH_LONG_OFFSET(){return eU}static get DATETIME_SHORT(){return tU}static get DATETIME_SHORT_WITH_SECONDS(){return rU}static get DATETIME_MED(){return nU}static get DATETIME_MED_WITH_SECONDS(){return iU}static get DATETIME_MED_WITH_WEEKDAY(){return Mse}static get DATETIME_FULL(){return oU}static get DATETIME_FULL_WITH_SECONDS(){return sU}static get DATETIME_HUGE(){return aU}static get DATETIME_HUGE_WITH_SECONDS(){return cU}};function iA(t){if(Bt.isDateTime(t))return t;if(t&&t.valueOf&&ua(t.valueOf()))return Bt.fromJSDate(t);if(t&&typeof t=="object")return Bt.fromObject(t);throw new dr(`Unknown datetime argument: ${t}, of type ${typeof t}`)}var vce="3.7.2";In.DateTime=Bt;In.Duration=or;In.FixedOffsetZone=En;In.IANAZone=Ss;In.Info=hc;In.Interval=fc;In.InvalidZone=Mg;In.Settings=yt;In.SystemZone=lA;In.VERSION=vce;In.Zone=da});var Vg=y(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.CronDate=Or.DAYS_IN_MONTH=Or.DateMathOp=Or.TimeUnit=void 0;var gc=zU(),Br;(function(t){t.Second="Second",t.Minute="Minute",t.Hour="Hour",t.Day="Day",t.Month="Month",t.Year="Year"})(Br||(Or.TimeUnit=Br={}));var Gg;(function(t){t.Add="Add",t.Subtract="Subtract"})(Gg||(Or.DateMathOp=Gg={}));Or.DAYS_IN_MONTH=Object.freeze([31,29,31,30,31,30,31,31,30,31,30,31]);var Yg=class t{#e;#t=null;#n=null;#i={add:{[Br.Year]:this.addYear.bind(this),[Br.Month]:this.addMonth.bind(this),[Br.Day]:this.addDay.bind(this),[Br.Hour]:this.addHour.bind(this),[Br.Minute]:this.addMinute.bind(this),[Br.Second]:this.addSecond.bind(this)},subtract:{[Br.Year]:this.subtractYear.bind(this),[Br.Month]:this.subtractMonth.bind(this),[Br.Day]:this.subtractDay.bind(this),[Br.Hour]:this.subtractHour.bind(this),[Br.Minute]:this.subtractMinute.bind(this),[Br.Second]:this.subtractSecond.bind(this)}};constructor(e,r){let n={zone:r};if(e?e instanceof t?(this.#e=e.#e,this.#t=e.#t,this.#n=e.#n):e instanceof Date?this.#e=gc.DateTime.fromJSDate(e,n):typeof e=="number"?this.#e=gc.DateTime.fromMillis(e,n):(this.#e=gc.DateTime.fromISO(e,n),this.#e.isValid||(this.#e=gc.DateTime.fromRFC2822(e,n)),this.#e.isValid||(this.#e=gc.DateTime.fromSQL(e,n)),this.#e.isValid||(this.#e=gc.DateTime.fromFormat(e,"EEE, d MMM yyyy HH:mm:ss",n))):this.#e=gc.DateTime.local(),!this.#e.isValid)throw new Error(`CronDate: unhandled timestamp: ${e}`);r&&r!==this.#e.zoneName&&(this.#e=this.#e.setZone(r))}static#o(e){return e%4===0&&e%100!==0||e%400===0}get dstStart(){return this.#t}set dstStart(e){this.#t=e}get dstEnd(){return this.#n}set dstEnd(e){this.#n=e}addYear(){this.#e=this.#e.plus({years:1})}addMonth(){this.#e=this.#e.plus({months:1}).startOf("month")}addDay(){this.#e=this.#e.plus({days:1}).startOf("day")}addHour(){this.#e=this.#e.plus({hours:1}).startOf("hour")}addMinute(){this.#e=this.#e.plus({minutes:1}).startOf("minute")}addSecond(){this.#e=this.#e.plus({seconds:1})}subtractYear(){this.#e=this.#e.minus({years:1})}subtractMonth(){this.#e=this.#e.minus({months:1}).endOf("month").startOf("second")}subtractDay(){this.#e=this.#e.minus({days:1}).endOf("day").startOf("second")}subtractHour(){this.#e=this.#e.minus({hours:1}).endOf("hour").startOf("second")}subtractMinute(){this.#e=this.#e.minus({minutes:1}).endOf("minute").startOf("second")}subtractSecond(){this.#e=this.#e.minus({seconds:1})}addUnit(e){this.#i.add[e]()}subtractUnit(e){this.#i.subtract[e]()}invokeDateOperation(e,r){if(e===Gg.Add){this.addUnit(r);return}if(e===Gg.Subtract){this.subtractUnit(r);return}throw new Error(`Invalid verb: ${e}`)}getDate(){return this.#e.day}getFullYear(){return this.#e.year}getDay(){let e=this.#e.weekday;return e===7?0:e}getMonth(){return this.#e.month-1}getHours(){return this.#e.hour}getMinutes(){return this.#e.minute}getSeconds(){return this.#e.second}getMilliseconds(){return this.#e.millisecond}getUTCOffset(){return this.#e.offset}setStartOfDay(){this.#e=this.#e.startOf("day")}setEndOfDay(){this.#e=this.#e.endOf("day")}getTime(){return this.#e.valueOf()}getUTCDate(){return this.#r().day}getUTCFullYear(){return this.#r().year}getUTCDay(){let e=this.#r().weekday;return e===7?0:e}getUTCMonth(){return this.#r().month-1}getUTCHours(){return this.#r().hour}getUTCMinutes(){return this.#r().minute}getUTCSeconds(){return this.#r().second}toISOString(){return this.#e.toUTC().toISO()}toJSON(){return this.#e.toJSON()}setDate(e){this.#e=this.#e.set({day:e})}setFullYear(e){this.#e=this.#e.set({year:e})}setDay(e){this.#e=this.#e.set({weekday:e})}setMonth(e){this.#e=this.#e.set({month:e+1})}setHours(e){this.#e=this.#e.set({hour:e})}setMinutes(e){this.#e=this.#e.set({minute:e})}setSeconds(e){this.#e=this.#e.set({second:e})}setMilliseconds(e){this.#e=this.#e.set({millisecond:e})}toString(){return this.toDate().toString()}toDate(){return this.#e.toJSDate()}isLastDayOfMonth(){let{day:e,month:r}=this.#e;if(r===2){let n=t.#o(this.#e.year);return e===Or.DAYS_IN_MONTH[r-1]-(n?0:1)}return e===Or.DAYS_IN_MONTH[r-1]}isLastWeekdayOfMonth(){let{day:e,month:r}=this.#e,n;return r===2?n=Or.DAYS_IN_MONTH[r-1]-(t.#o(this.#e.year)?0:1):n=Or.DAYS_IN_MONTH[r-1],e>n-7}applyDateOperation(e,r,n){if(r===Br.Month||r===Br.Day){this.invokeDateOperation(e,r);return}let i=this.getHours();this.invokeDateOperation(e,r);let o=this.getHours(),s=o-i;s===2?n!==24&&(this.dstStart=o):s===0&&this.getMinutes()===0&&this.getSeconds()===0&&n!==24&&(this.dstEnd=o)}#r(){return this.#e.toUTC()}};Or.CronDate=Yg;Or.default=Yg});var qU=y(Wg=>{"use strict";Object.defineProperty(Wg,"__esModule",{value:!0});Wg.CronMonth=void 0;var Qce=Vg(),Tce=sa(),Dce=1,kce=12,Rce=Object.freeze([]),pS=class extends Tce.CronField{static get min(){return Dce}static get max(){return kce}static get chars(){return Rce}static get daysInMonth(){return Qce.DAYS_IN_MONTH}constructor(e,r){super(e,r),this.validate()}get values(){return super.values}};Wg.CronMonth=pS});var HU=y(Jg=>{"use strict";Object.defineProperty(Jg,"__esModule",{value:!0});Jg.CronSecond=void 0;var Nce=sa(),Oce=0,xce=59,Uce=Object.freeze([]),hS=class extends Nce.CronField{static get min(){return Oce}static get max(){return xce}static get chars(){return Uce}constructor(e,r){super(e,r),this.validate()}get values(){return super.values}};Jg.CronSecond=hS});var Zg=y(Vr=>{"use strict";var Mce=Vr&&Vr.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Aa=Vr&&Vr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Mce(e,t,r)};Object.defineProperty(Vr,"__esModule",{value:!0});Aa(lx(),Vr);Aa(ux(),Vr);Aa(dx(),Vr);Aa(sa(),Vr);Aa(Ax(),Vr);Aa(px(),Vr);Aa(qU(),Vr);Aa(HU(),Vr)});var gS=y(Kg=>{"use strict";Object.defineProperty(Kg,"__esModule",{value:!0});Kg.CronFieldCollection=void 0;var Zn=Zg(),fS=class t{#e;#t;#n;#i;#o;#r;static from(e,r){return new t({second:this.resolveField(Zn.CronSecond,e.second,r.second),minute:this.resolveField(Zn.CronMinute,e.minute,r.minute),hour:this.resolveField(Zn.CronHour,e.hour,r.hour),dayOfMonth:this.resolveField(Zn.CronDayOfMonth,e.dayOfMonth,r.dayOfMonth),month:this.resolveField(Zn.CronMonth,e.month,r.month),dayOfWeek:this.resolveField(Zn.CronDayOfWeek,e.dayOfWeek,r.dayOfWeek)})}static resolveField(e,r,n){return n?n instanceof Zn.CronField?n:new e(n):r}constructor({second:e,minute:r,hour:n,dayOfMonth:i,month:o,dayOfWeek:s}){if(!e)throw new Error("Validation error, Field second is missing");if(!r)throw new Error("Validation error, Field minute is missing");if(!n)throw new Error("Validation error, Field hour is missing");if(!i)throw new Error("Validation error, Field dayOfMonth is missing");if(!o)throw new Error("Validation error, Field month is missing");if(!s)throw new Error("Validation error, Field dayOfWeek is missing");if(o.values.length===1&&!i.hasLastChar&&!(parseInt(i.values[0],10)<=Zn.CronMonth.daysInMonth[o.values[0]-1]))throw new Error("Invalid explicit day of month definition");this.#e=e,this.#t=r,this.#n=n,this.#o=o,this.#r=s,this.#i=i}get second(){return this.#e}get minute(){return this.#t}get hour(){return this.#n}get dayOfMonth(){return this.#i}get month(){return this.#o}get dayOfWeek(){return this.#r}static compactField(e){if(e.length===0)return[];let r=[],n;return e.forEach((i,o,s)=>{if(n===void 0){n={start:i,count:1};return}let a=s[o-1]||n.start,c=s[o+1];if(i==="L"||i==="W"){r.push(n),r.push({start:i,count:1}),n=void 0;return}if(n.step===void 0&&c!==void 0){let l=i-a,u=c-i;if(l<=u){n={...n,count:2,end:i,step:l};return}n.step=1}i-(n.end??0)===n.step?(n.count++,n.end=i):(n.count===1?r.push({start:n.start,count:1}):n.count===2?(r.push({start:n.start,count:1}),r.push({start:n.end??a,count:1})):r.push(n),n={start:i,count:1})}),n&&r.push(n),r}static#c(e,r,n){let i=r.step;return i?i===1&&r.start===e.min&&r.end&&r.end>=n?e.hasQuestionMarkChar?"?":"*":i!==1&&r.start===e.min&&r.end&&r.end>=n-i+1?`*/${i}`:null:null}static#s(e,r){let n=e.step;if(n===1)return`${e.start}-${e.end}`;let i=e.start===0?e.count-1:e.count;if(!n)throw new Error("Unexpected range step");if(!e.end)throw new Error("Unexpected range end");if(n*i>e.end){let o=(a,c)=>{if(typeof e.start!="number")throw new Error("Unexpected range start");return c%n===0?e.start+c:null};if(typeof e.start!="number")throw new Error("Unexpected range start");let s={length:e.end-e.start+1};return Array.from(s,o).filter(a=>a!==null).join(",")}return e.end===r-n+1?`${e.start}/${n}`:`${e.start}-${e.end}/${n}`}stringifyField(e){let r=e.max,n=e.values;if(e instanceof Zn.CronDayOfWeek){r=6;let o=this.#r.values;n=o[o.length-1]===7?o.slice(0,-1):o}e instanceof Zn.CronDayOfMonth&&(r=this.#o.values.length===1?Zn.CronMonth.daysInMonth[this.#o.values[0]-1]:e.max);let i=t.compactField(n);if(i.length===1){let o=t.#c(e,i[0],r);if(o)return o}return i.map(o=>{let s=o.count===1?o.start.toString():t.#s(o,r);return e instanceof Zn.CronDayOfWeek&&e.nthDay>0?`${s}#${e.nthDay}`:s}).join(",")}stringify(e=!1){let r=[];return e&&r.push(this.stringifyField(this.#e)),r.push(this.stringifyField(this.#t),this.stringifyField(this.#n),this.stringifyField(this.#i),this.stringifyField(this.#o),this.stringifyField(this.#r)),r.join(" ")}serialize(){return{second:this.#e.serialize(),minute:this.#t.serialize(),hour:this.#n.serialize(),dayOfMonth:this.#i.serialize(),month:this.#o.serialize(),dayOfWeek:this.#r.serialize()}}};Kg.CronFieldCollection=fS});var mS=y(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.CronExpression=Kn.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE=Kn.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE=void 0;var Ut=Vg();Kn.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE="Out of the time span range";Kn.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE="Invalid expression, loop limit exceeded";var GU=1e4,Xg=class t{#e;#t;#n;#i;#o;#r;#c=null;#s=!1;constructor(e,r){this.#e=r,this.#t=r.tz,this.#i=r.startDate?new Ut.CronDate(r.startDate,this.#t):null,this.#o=r.endDate?new Ut.CronDate(r.endDate,this.#t):null;let n=r.currentDate??r.startDate;if(n){let i=new Ut.CronDate(n,this.#t);this.#i&&i.getTime()<this.#i.getTime()?n=this.#i:this.#o&&i.getTime()>this.#o.getTime()&&(n=this.#o)}this.#n=new Ut.CronDate(n,this.#t),this.#r=e}get fields(){return this.#r}static fieldsToExpression(e,r){return new t(e,r||{})}static#a(e,r){return r.some(n=>n===e)}#l(e,r){return e[r?e.length-1:0]}#d(e){let r=`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()}`;if(this.#c===r)return this.#s;let n=new Ut.CronDate(e);n.setStartOfDay();let i=new Ut.CronDate(e);return i.setEndOfDay(),this.#c=r,this.#s=n.getUTCOffset()!==i.getUTCOffset(),this.#s}#A(e,r,n){let i=this.#r.second.values,o=e.getSeconds(),s=this.#r.second.findNearestValue(o,n);if(s!==null){e.setSeconds(s);return}e.applyDateOperation(r,Ut.TimeUnit.Minute,this.#r.hour.values.length),e.setSeconds(this.#l(i,n))}#p(e,r,n){let i=this.#r.minute.values,o=this.#r.second.values,s=e.getMinutes(),a=this.#r.minute.findNearestValue(s,n);if(a!==null){e.setMinutes(a),e.setSeconds(this.#l(o,n));return}e.applyDateOperation(r,Ut.TimeUnit.Hour,this.#r.hour.values.length),e.setMinutes(this.#l(i,n)),e.setSeconds(this.#l(o,n))}static#h(e,r){let n=r.isLastWeekdayOfMonth();return e.some(i=>{let o=parseInt(i.toString().charAt(0),10)%7;if(Number.isNaN(o))throw new Error(`Invalid last weekday of the month expression: ${i}`);return r.getDay()===o&&n})}next(){return this.#g()}prev(){return this.#g(!0)}hasNext(){let e=this.#n;try{return this.#g(),!0}catch{return!1}finally{this.#n=e}}hasPrev(){let e=this.#n;try{return this.#g(!0),!0}catch{return!1}finally{this.#n=e}}take(e){let r=[];if(e>=0)for(let n=0;n<e;n++)try{r.push(this.next())}catch{return r}else for(let n=0;n>e;n--)try{r.push(this.prev())}catch{return r}return r}reset(e){this.#n=new Ut.CronDate(e||this.#e.currentDate)}stringify(e=!1){return this.#r.stringify(e)}includesDate(e){let{second:r,minute:n,hour:i,month:o}=this.#r,s=new Ut.CronDate(e,this.#t);return!(!r.values.includes(s.getSeconds())||!n.values.includes(s.getMinutes())||!i.values.includes(s.getHours())||!o.values.includes(s.getMonth()+1)||!this.#u(s)||this.#r.dayOfWeek.nthDay>0&&Math.ceil(s.getDate()/7)!==this.#r.dayOfWeek.nthDay)}toString(){return this.#e.expression||this.stringify(!0)}#u(e){let r=this.#r.dayOfMonth.isWildcard,n=!r,i=this.#r.dayOfWeek.isWildcard,o=!i,s=t.#a(e.getDate(),this.#r.dayOfMonth.values)||this.#r.dayOfMonth.hasLastChar&&e.isLastDayOfMonth(),a=t.#a(e.getDay(),this.#r.dayOfWeek.values)||this.#r.dayOfWeek.hasLastChar&&t.#h(this.#r.dayOfWeek.values,e);return!!(n&&o&&(s||a)||s&&!o||r&&!i&&a)}#m(e,r,n){let i=this.#r.hour.values,o=i,s=e.getHours(),a=t.#a(s,i),c=e.dstStart===s,l=e.dstEnd===s;if(c)return t.#a(s-1,i)?!0:(e.invokeDateOperation(r,Ut.TimeUnit.Hour),!1);if(l&&!n)return e.dstEnd=null,e.applyDateOperation(Ut.DateMathOp.Add,Ut.TimeUnit.Hour,o.length),!1;if(a)return!0;e.dstStart=null;let u=this.#r.hour.findNearestValue(s,n);if(u===null)return e.applyDateOperation(r,Ut.TimeUnit.Day,o.length),!1;if(this.#d(e)){let d=n?s-u:u-s;for(let A=0;A<d;A++)e.applyDateOperation(r,Ut.TimeUnit.Hour,o.length)}else e.setHours(u);return e.setMinutes(this.#l(this.#r.minute.values,n)),e.setSeconds(this.#l(this.#r.second.values,n)),!1}#f(e){if(!this.#i&&!this.#o)return;let r=e.getTime();if(this.#i&&r<this.#i.getTime())throw new Error(Kn.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE);if(this.#o&&r>this.#o.getTime())throw new Error(Kn.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE)}#g(e=!1){let r=e?Ut.DateMathOp.Subtract:Ut.DateMathOp.Add,n=new Ut.CronDate(this.#n),i=n.getTime(),o=0;for(;++o<GU;){if(this.#f(n),!this.#u(n)){n.applyDateOperation(r,Ut.TimeUnit.Day,this.#r.hour.values.length);continue}if(!(this.#r.dayOfWeek.nthDay<=0||Math.ceil(n.getDate()/7)===this.#r.dayOfWeek.nthDay)){n.applyDateOperation(r,Ut.TimeUnit.Day,this.#r.hour.values.length);continue}if(!t.#a(n.getMonth()+1,this.#r.month.values)){n.applyDateOperation(r,Ut.TimeUnit.Month,this.#r.hour.values.length);continue}if(this.#m(n,r,e)){if(!t.#a(n.getMinutes(),this.#r.minute.values)){this.#p(n,r,e);continue}if(!t.#a(n.getSeconds(),this.#r.second.values)){this.#A(n,r,e);continue}if(i===n.getTime()){(r==="Add"||n.getMilliseconds()===0)&&n.applyDateOperation(r,Ut.TimeUnit.Second,this.#r.hour.values.length);continue}break}}if(o>GU)throw new Error(Kn.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE);return n.getMilliseconds()!==0&&n.setMilliseconds(0),this.#n=n,n}[Symbol.iterator](){return{next:()=>({value:this.#g(),done:!this.hasNext()})}}};Kn.CronExpression=Xg;Kn.default=Xg});var YU=y(yS=>{"use strict";Object.defineProperty(yS,"__esModule",{value:!0});yS.seededRandom=$ce;function Pce(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t.charCodeAt(r),e=Math.imul(e,16777619);return()=>e>>>0}function Lce(t){return()=>{let e=t+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}function $ce(t){let e=t?Pce(t)():Math.floor(Math.random()*1e10);return Lce(e)}});var em=y(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.CronExpressionParser=ti.DayOfWeek=ti.Months=ti.CronUnit=ti.PredefinedExpressions=void 0;var Fce=gS(),jce=mS(),zce=YU(),Xn=Zg(),ES;(function(t){t["@yearly"]="0 0 0 1 1 *",t["@annually"]="0 0 0 1 1 *",t["@monthly"]="0 0 0 1 * *",t["@weekly"]="0 0 0 * * 0",t["@daily"]="0 0 0 * * *",t["@hourly"]="0 0 * * * *",t["@minutely"]="0 * * * * *",t["@secondly"]="* * * * * *",t["@weekdays"]="0 0 0 * * 1-5",t["@weekends"]="0 0 0 * * 0,6"})(ES||(ti.PredefinedExpressions=ES={}));var ei;(function(t){t.Second="Second",t.Minute="Minute",t.Hour="Hour",t.DayOfMonth="DayOfMonth",t.Month="Month",t.DayOfWeek="DayOfWeek"})(ei||(ti.CronUnit=ei={}));var IS;(function(t){t[t.jan=1]="jan",t[t.feb=2]="feb",t[t.mar=3]="mar",t[t.apr=4]="apr",t[t.may=5]="may",t[t.jun=6]="jun",t[t.jul=7]="jul",t[t.aug=8]="aug",t[t.sep=9]="sep",t[t.oct=10]="oct",t[t.nov=11]="nov",t[t.dec=12]="dec"})(IS||(ti.Months=IS={}));var CS;(function(t){t[t.sun=0]="sun",t[t.mon=1]="mon",t[t.tue=2]="tue",t[t.wed=3]="wed",t[t.thu=4]="thu",t[t.fri=5]="fri",t[t.sat=6]="sat"})(CS||(ti.DayOfWeek=CS={}));var bS=class t{static parse(e,r={}){let{strict:n=!1,hashSeed:i}=r,o=(0,zce.seededRandom)(i);e=ES[e]||e;let s=t.#e(e,n);if(!(s.dayOfMonth==="*"||s.dayOfWeek==="*"||!n))throw new Error("Cannot use both dayOfMonth and dayOfWeek together in strict mode!");let a=t.#t(ei.Second,s.second,Xn.CronSecond.constraints,o),c=t.#t(ei.Minute,s.minute,Xn.CronMinute.constraints,o),l=t.#t(ei.Hour,s.hour,Xn.CronHour.constraints,o),u=t.#t(ei.Month,s.month,Xn.CronMonth.constraints,o),d=t.#t(ei.DayOfMonth,s.dayOfMonth,Xn.CronDayOfMonth.constraints,o),{dayOfWeek:A,nthDayOfWeek:p}=t.#d(s.dayOfWeek),h=t.#t(ei.DayOfWeek,A,Xn.CronDayOfWeek.constraints,o),f=new Fce.CronFieldCollection({second:new Xn.CronSecond(a,{rawValue:s.second}),minute:new Xn.CronMinute(c,{rawValue:s.minute}),hour:new Xn.CronHour(l,{rawValue:s.hour}),dayOfMonth:new Xn.CronDayOfMonth(d,{rawValue:s.dayOfMonth}),month:new Xn.CronMonth(u,{rawValue:s.month}),dayOfWeek:new Xn.CronDayOfWeek(h,{rawValue:s.dayOfWeek,nthDayOfWeek:p})});return new jce.CronExpression(f,{...r,expression:e})}static#e(e,r){if(r&&!e.length)throw new Error("Invalid cron expression");e=e||"0 * * * * *";let n=e.trim().split(/\s+/);if(r&&n.length<6)throw new Error("Invalid cron expression, expected 6 fields");if(n.length>6)throw new Error("Invalid cron expression, too many fields");let i=["*","*","*","*","*","0"];n.length<i.length&&n.unshift(...i.slice(n.length));let[o,s,a,c,l,u]=n;return{second:o,minute:s,hour:a,dayOfMonth:c,month:l,dayOfWeek:u}}static#t(e,r,n,i){if((e===ei.Month||e===ei.DayOfWeek)&&(r=r.replace(/[a-z]{3}/gi,o=>{o=o.toLowerCase();let s=IS[o]||CS[o];if(s===void 0)throw new Error(`Validation error, cannot resolve alias "${o}"`);return s.toString()})),!n.validChars.test(r))throw new Error(`Invalid characters, got value: ${r}`);return r=this.#n(r,n),r=this.#i(r,n,i),this.#o(e,r,n)}static#n(e,r){return e.replace(/[*?]/g,r.min+"-"+r.max)}static#i(e,r,n){let i=n();return e.replace(/H(?:\((\d+)-(\d+)\))?(?:\/(\d+))?/g,(o,s,a,c)=>{if(s&&a&&c){let l=parseInt(s,10),u=parseInt(a,10),d=parseInt(c,10);if(l>u)throw new Error(`Invalid range: ${l}-${u}, min > max`);if(d<=0)throw new Error(`Invalid step: ${d}, must be positive`);let A=Math.max(l,r.min),p=Math.floor(i*d),h=[];for(let f=Math.floor(A/d)*d+p;f<=u;f+=d)f>=A&&h.push(f);return h.join(",")}else if(s&&a){let l=parseInt(s,10),u=parseInt(a,10);if(l>u)throw new Error(`Invalid range: ${l}-${u}, min > max`);return String(Math.floor(i*(u-l+1))+l)}else if(c){let l=parseInt(c,10);if(l<=0)throw new Error(`Invalid step: ${l}, must be positive`);let u=Math.floor(i*l),d=[];for(let A=Math.floor(r.min/l)*l+u;A<=r.max;A+=l)A>=r.min&&d.push(A);return d.join(",")}else return String(Math.floor(i*(r.max-r.min+1)+r.min))})}static#o(e,r,n){let i=[];function o(a,c){if(Array.isArray(a))i.push(...a);else if(t.#A(c,a))i.push(a);else{let l=parseInt(a.toString(),10);if(!(l>=c.min&&l<=c.max))throw new Error(`Constraint error, got value ${a} expected range ${c.min}-${c.max}`);i.push(e===ei.DayOfWeek?l%7:a)}}return r.split(",").forEach(a=>{if(!(a.length>0))throw new Error("Invalid list value format");o(t.#r(e,a,n),n)}),i}static#r(e,r,n){let i=r.split("/");if(i.length>2)throw new Error(`Invalid repeat: ${r}`);return i.length===2?(isNaN(parseInt(i[0],10))||(i[0]=`${i[0]}-${n.max}`),t.#l(e,i[0],parseInt(i[1],10),n)):t.#l(e,r,1,n)}static#c(e,r,n){if(!(!isNaN(e)&&!isNaN(r)&&e>=n.min&&r<=n.max))throw new Error(`Constraint error, got range ${e}-${r} expected range ${n.min}-${n.max}`);if(e>r)throw new Error(`Invalid range: ${e}-${r}, min(${e}) > max(${r})`)}static#s(e){if(!(!isNaN(e)&&e>0))throw new Error(`Constraint error, cannot repeat at every ${e} time.`)}static#a(e,r,n,i){let o=[];e===ei.DayOfWeek&&n%7===0&&o.push(0);for(let s=r;s<=n;s+=i)o.indexOf(s)===-1&&o.push(s);return o}static#l(e,r,n,i){let o=r.split("-");if(o.length<=1)return isNaN(+r)?r:+r;let[s,a]=o.map(c=>parseInt(c,10));return this.#c(s,a,i),this.#s(n),this.#a(e,s,a,n)}static#d(e){let r=e.split("#");if(r.length<=1)return{dayOfWeek:r[0]};let n=+r[r.length-1],i=e.match(/([,-/])/);if(i!==null)throw new Error(`Constraint error, invalid dayOfWeek \`#\` and \`${i?.[0]}\` special characters are incompatible`);if(!(r.length<=2&&!isNaN(n)&&n>=1&&n<=5))throw new Error("Constraint error, invalid dayOfWeek occurrence number (#)");return{dayOfWeek:r[0],nthDayOfWeek:n}}static#A(e,r){return e.chars.some(n=>r.toString().includes(n))}};ti.CronExpressionParser=bS});var VU=y(Fo=>{"use strict";var qce=Fo&&Fo.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Hce=Fo&&Fo.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Gce=Fo&&Fo.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),i=0;i<n.length;i++)n[i]!=="default"&&qce(r,e,n[i]);return Hce(r,e),r}})();Object.defineProperty(Fo,"__esModule",{value:!0});Fo.CronFileParser=void 0;var Yce=em(),SS=class t{static async parseFile(e){let{readFile:r}=await Promise.resolve().then(()=>Gce(require("fs/promises"))),n=await r(e,"utf8");return t.#e(n)}static parseFileSync(e){let{readFileSync:r}=require("fs"),n=r(e,"utf8");return t.#e(n)}static#e(e){let r=e.split(`
|
|
102
|
+
`),n={variables:{},expressions:[],errors:{}};for(let i of r){let o=i.trim();if(o.length===0||o.startsWith("#"))continue;let s=o.match(/^(.*)=(.*)$/);if(s){let[,a,c]=s;n.variables[a]=c.replace(/["']/g,"");continue}try{let a=t.#t(o);n.expressions.push(a.interval)}catch(a){n.errors[o]=a}}return n}static#t(e){let r=e.split(" ");return{interval:Yce.CronExpressionParser.parse(r.slice(0,5).join(" ")),command:r.slice(5,r.length)}}};Fo.CronFileParser=SS});var WU=y(Ar=>{"use strict";var Vce=Ar&&Ar.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Wce=Ar&&Ar.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Vce(e,t,r)};Object.defineProperty(Ar,"__esModule",{value:!0});Ar.CronFileParser=Ar.CronExpressionParser=Ar.CronExpression=Ar.CronFieldCollection=Ar.CronDate=void 0;var Jce=em(),Zce=Vg();Object.defineProperty(Ar,"CronDate",{enumerable:!0,get:function(){return Zce.CronDate}});var Kce=gS();Object.defineProperty(Ar,"CronFieldCollection",{enumerable:!0,get:function(){return Kce.CronFieldCollection}});var Xce=mS();Object.defineProperty(Ar,"CronExpression",{enumerable:!0,get:function(){return Xce.CronExpression}});var ele=em();Object.defineProperty(Ar,"CronExpressionParser",{enumerable:!0,get:function(){return ele.CronExpressionParser}});var tle=VU();Object.defineProperty(Ar,"CronFileParser",{enumerable:!0,get:function(){return tle.CronFileParser}});Wce(Zg(),Ar);Ar.default=Jce.CronExpressionParser});var Bi=y(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.Err=Wr.Valid=Wr.err=Wr.valid=void 0;var rle=t=>new tm(t);Wr.valid=rle;var nle=t=>new rm(t);Wr.err=nle;var tm=class{constructor(e){this.value=e}isValid(){return!0}isError(){return!this.isValid()}getValue(){return this.value}getError(){throw new Error("Tried to get error from a valid.")}map(e){return(0,Wr.valid)(e(this.value))}mapErr(e){return(0,Wr.valid)(this.value)}};Wr.Valid=tm;var rm=class{constructor(e){this.error=e}isError(){return!0}isValid(){return!this.isError()}getValue(){throw new Error("Tried to get success value from an error.")}getError(){return this.error}map(e){return(0,Wr.err)(this.error)}mapErr(e){return(0,Wr.err)(e(this.error))}};Wr.Err=rm});var vi=y(JU=>{"use strict";Object.defineProperty(JU,"__esModule",{value:!0})});var pa=y(wS=>{"use strict";Object.defineProperty(wS,"__esModule",{value:!0});jo();var Oe=Bi();vi();var ile=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],ole=["sun","mon","tue","wed","thu","fri","sat"],sle=(t,e)=>e[t].lowerLimit===e.preset[t].minValue&&e[t].upperLimit===e.preset[t].maxValue,hA=(t,e,r)=>{if(e==="months"&&r.useAliases&&ile.indexOf(t.toLowerCase())!==-1||e==="daysOfWeek"&&r.useAliases&&ole.indexOf(t.toLowerCase())!==-1)return(0,Oe.valid)(!0);let n=Number(t);if(Number.isNaN(n))return(0,Oe.err)(`Element '${t}' of ${e} field is invalid.`);if(n%1!==0)return(0,Oe.err)(`Element '${t}' of ${e} field is not an integer.`);let{lowerLimit:i}=r[e],{upperLimit:o}=r[e];return i&&n<i?(0,Oe.err)(`Number '${n}' of ${e} field is smaller than lower limit '${i}'.`):o&&n>o?(0,Oe.err)(`Number '${n}' of ${e} field is bigger than upper limit '${o}'.`):(0,Oe.valid)(!0)},ale=(t,e,r)=>{if(t==="*")return sle(e,r)?(0,Oe.valid)(!0):(0,Oe.err)(`Field ${e} uses wildcard '*', but is limited to ${r[e].lowerLimit}-${r[e].upperLimit}.`);if(t==="")return(0,Oe.err)(`One of the elements is empty in ${e} field.`);if(e==="daysOfMonth"&&r.useLastDayOfMonth&&t==="L")return(0,Oe.valid)(!0);if(e==="daysOfWeek"&&r.useLastDayOfWeek&&t.endsWith("L")){let n=t.slice(0,-1);return n===""?(0,Oe.valid)(!0):hA(n,e,r)}if(e==="daysOfMonth"&&r.useNearestWeekday&&t.endsWith("W")){let n=t.slice(0,-1);return n===""?(0,Oe.err)("The 'W' must be preceded by a day."):r.useLastDayOfMonth&&n==="L"?(0,Oe.valid)(!0):hA(n,e,r)}if(e==="daysOfWeek"&&r.useNthWeekdayOfMonth&&t.indexOf("#")!==-1){let[n,i,...o]=t.split("#");if(o.length!==0)return(0,Oe.err)(`Unexpected number of '#' in ${t}, can only be used once.`);let s=Number(i);return!i||Number.isNaN(s)?(0,Oe.err)(`Unexpected value following the '#' symbol, a positive number was expected but found ${i}.`):s>5?(0,Oe.err)("Number of occurrence of the day of the week cannot be greater than 5."):hA(n,e,r)}return hA(t,e,r)},ZU=(t,e,r,n)=>t==="*"?(0,Oe.err)(`'*' can't be part of a range in ${e} field.`):t===""?(0,Oe.err)(`One of the range elements is empty in ${e} field.`):r.useLastDayOfMonth&&e==="daysOfMonth"&&t==="L"&&n===0?(0,Oe.valid)(!0):hA(t,e,r),cle=(t,e,r)=>{let n=t.split("-");if(n.length>2)return(0,Oe.err)(`List element '${t}' is not valid. (More than one '-').`);if(n.length===1)return ale(n[0],e,r);if(n.length===2){let i=ZU(n[0],e,r,0),o=ZU(n[1],e,r,1);return i.isError()?i:o.isError()?o:Number(n[0])>Number(n[1])?(0,Oe.err)(`Lower range end '${n[0]}' is bigger than upper range end '${n[1]}' of ${e} field.`):(0,Oe.valid)(!0)}return(0,Oe.err)("Some other error in checkFirstStepElement (rangeArray less than 1)")},lle=(t,e,r)=>{let n=t.split("/");if(n.length>2)return(0,Oe.err)(`List element '${t}' is not valid. (More than one '/').`);if(!r.allowStepping)return(0,Oe.err)("Stepping ('/') is not allowed.");let i=cle(n[0],e,r);if(i.isError())return i;if(n.length===2){let o=n[1];if(!o)return(0,Oe.err)(`Second step element '${o}' of '${t}' is not valid (doesnt exist).`);if(Number.isNaN(Number(o)))return(0,Oe.err)(`Second step element '${o}' of '${t}' is not valid (not a number).`);let s=Number(o);if(s===0)return(0,Oe.err)(`Second step element '${o}' of '${t}' cannot be zero.`);if(s<0)return(0,Oe.err)(`Second step element '${o}' of '${t}' cannot be negative.`);if(s%1!==0)return(0,Oe.err)(`Second step element '${o}' of '${t}' is not an integer.`);let{lowerLimit:a,upperLimit:c}=r[e];if(c&&s>c)return(0,Oe.err)(`Second step element '${o}' of '${t}' is bigger than the upper limit '${c}'.`);let l=n[0].split("-");if(l.length===2){let u=Number(l[0]),d=Number(l[1]);if(!Number.isNaN(u)&&!Number.isNaN(d)){if(s<=0)return(0,Oe.err)(`Step value '${o}' must be greater than 0.`);let A=d-u+1;if(s>=A)return(0,Oe.err)(`Step value '${o}' is too large for the range '${u}-${d}'.`)}}}return(0,Oe.valid)(!0)},ule=(t,e,r)=>{if(!["seconds","minutes","hours","daysOfMonth","months","daysOfWeek","years"].includes(e))return(0,Oe.err)([`Cron field type '${e}' does not exist.`]);if(t==="?")return e==="daysOfMonth"||e==="daysOfWeek"?r.useBlankDay?(0,Oe.valid)(!0):(0,Oe.err)([`useBlankDay is not enabled, but is used in ${e} field.`]):(0,Oe.err)([`blank notation is not allowed in ${e} field.`]);let n=t.split(","),i=[];if(n.forEach(s=>{i.push(lle(s,e,r))}),i.every(s=>s.isValid()))return(0,Oe.valid)(!0);let o=[];return i.forEach(s=>{s.isError()&&o.push(s.getError())}),(0,Oe.err)(o)};wS.default=ule});var KU=y(fA=>{"use strict";var dle=fA&&fA.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(fA,"__esModule",{value:!0});jo();var Ale=Bi(),ple=dle(pa());vi();var hle=(t,e)=>{if(!t.seconds)return(0,Ale.err)(["seconds field is undefined, but useSeconds options is enabled."]);let{seconds:r}=t;return(0,ple.default)(r,"seconds",e)};fA.default=hle});var XU=y(gA=>{"use strict";var fle=gA&&gA.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(gA,"__esModule",{value:!0});jo();var gle=Bi(),mle=fle(pa());vi();var yle=(t,e)=>{if(!t.minutes)return(0,gle.err)(["minutes field is undefined."]);let{minutes:r}=t;return(0,mle.default)(r,"minutes",e)};gA.default=yle});var eM=y(mA=>{"use strict";var Ele=mA&&mA.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(mA,"__esModule",{value:!0});jo();var Ile=Bi(),Cle=Ele(pa());vi();var ble=(t,e)=>{if(!t.hours)return(0,Ile.err)(["hours field is undefined."]);let{hours:r}=t;return(0,Cle.default)(r,"hours",e)};mA.default=ble});var tM=y(EA=>{"use strict";var Sle=EA&&EA.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(EA,"__esModule",{value:!0});jo();var yA=Bi(),wle=Sle(pa());vi();var _le=(t,e)=>{if(!t.daysOfMonth)return(0,yA.err)(["daysOfMonth field is undefined."]);let{daysOfMonth:r}=t;return e.allowOnlyOneBlankDayField&&e.useBlankDay&&t.daysOfMonth==="?"&&t.daysOfWeek==="?"?(0,yA.err)(["Cannot use blank value in daysOfMonth and daysOfWeek field when allowOnlyOneBlankDayField option is enabled."]):e.mustHaveBlankDayField&&t.daysOfMonth!=="?"&&t.daysOfWeek!=="?"?(0,yA.err)(["Cannot specify both daysOfMonth and daysOfWeek field when mustHaveBlankDayField option is enabled."]):e.useLastDayOfMonth&&t.daysOfMonth.indexOf("L")!==-1&&t.daysOfMonth.match(/[,/]/)?(0,yA.err)(["Cannot specify last day of month with lists, or ranges (symbols ,/)."]):e.useNearestWeekday&&t.daysOfMonth.indexOf("W")!==-1&&t.daysOfMonth.match(/[,/-]/)?(0,yA.err)(["Cannot specify nearest weekday with lists, steps or ranges (symbols ,-/)."]):(0,wle.default)(r,"daysOfMonth",e)};EA.default=_le});var rM=y(IA=>{"use strict";var Ble=IA&&IA.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(IA,"__esModule",{value:!0});jo();var vle=Bi(),Qle=Ble(pa());vi();var Tle=(t,e)=>{if(!t.months)return(0,vle.err)(["months field is undefined."]);let{months:r}=t;return(0,Qle.default)(r,"months",e)};IA.default=Tle});var nM=y(bA=>{"use strict";var Dle=bA&&bA.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(bA,"__esModule",{value:!0});jo();var CA=Bi(),kle=Dle(pa());vi();var Rle=(t,e)=>{if(!t.daysOfWeek)return(0,CA.err)(["daysOfWeek field is undefined."]);let{daysOfWeek:r}=t;return e.allowOnlyOneBlankDayField&&t.daysOfMonth==="?"&&t.daysOfWeek==="?"?(0,CA.err)(["Cannot use blank value in daysOfMonth and daysOfWeek field when allowOnlyOneBlankDayField option is enabled."]):e.mustHaveBlankDayField&&t.daysOfMonth!=="?"&&t.daysOfWeek!=="?"?(0,CA.err)(["Cannot specify both daysOfMonth and daysOfWeek field when mustHaveBlankDayField option is enabled."]):e.useLastDayOfWeek&&t.daysOfWeek.indexOf("L")!==-1&&t.daysOfWeek.match(/[,/-]/)?(0,CA.err)(["Cannot specify last day of week with lists, steps or ranges (symbols ,-/)."]):e.useNthWeekdayOfMonth&&t.daysOfWeek.indexOf("#")!==-1&&t.daysOfWeek.match(/[,/-]/)?(0,CA.err)(["Cannot specify Nth weekday of month with lists, steps or ranges (symbols ,-/)."]):(0,kle.default)(r,"daysOfWeek",e)};bA.default=Rle});var iM=y(SA=>{"use strict";var Nle=SA&&SA.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(SA,"__esModule",{value:!0});jo();var Ole=Bi(),xle=Nle(pa());vi();var Ule=(t,e)=>{if(!t.years)return(0,Ole.err)(["years field is undefined, but useYears option is enabled."]);let{years:r}=t;return(0,xle.default)(r,"years",e)};SA.default=Ule});var uM=y((Oje,lM)=>{"use strict";function mc(t){this._maxSize=t,this.clear()}mc.prototype.clear=function(){this._size=0,this._values=Object.create(null)};mc.prototype.get=function(t){return this._values[t]};mc.prototype.set=function(t,e){return this._size>=this._maxSize&&this.clear(),t in this._values||this._size++,this._values[t]=e};var Mle=/[^.^\]^[]+|(?=\[\]|\.\.)/g,cM=/^\d+$/,Ple=/^\d/,Lle=/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g,$le=/^\s*(['"]?)(.*?)(\1)\s*$/,vS=512,oM=new mc(vS),sM=new mc(vS),aM=new mc(vS);lM.exports={Cache:mc,split:BS,normalizePath:_S,setter:function(t){var e=_S(t);return sM.get(t)||sM.set(t,function(n,i){for(var o=0,s=e.length,a=n;o<s-1;){var c=e[o];if(c==="__proto__"||c==="constructor"||c==="prototype")return n;a=a[e[o++]]}a[e[o]]=i})},getter:function(t,e){var r=_S(t);return aM.get(t)||aM.set(t,function(i){for(var o=0,s=r.length;o<s;)if(i!=null||!e)i=i[r[o++]];else return;return i})},join:function(t){return t.reduce(function(e,r){return e+(QS(r)||cM.test(r)?"["+r+"]":(e?".":"")+r)},"")},forEach:function(t,e,r){Fle(Array.isArray(t)?t:BS(t),e,r)}};function _S(t){return oM.get(t)||oM.set(t,BS(t).map(function(e){return e.replace($le,"$2")}))}function BS(t){return t.match(Mle)||[""]}function Fle(t,e,r){var n=t.length,i,o,s,a;for(o=0;o<n;o++)i=t[o],i&&(qle(i)&&(i='"'+i+'"'),a=QS(i),s=!a&&/^\d+$/.test(i),e.call(r,i,a,s,o,t))}function QS(t){return typeof t=="string"&&t&&["'",'"'].indexOf(t.charAt(0))!==-1}function jle(t){return t.match(Ple)&&!t.match(cM)}function zle(t){return Lle.test(t)}function qle(t){return!QS(t)&&(jle(t)||zle(t))}});var pM=y((xje,AM)=>{"use strict";var Hle=/[A-Z\xc0-\xd6\xd8-\xde]?[a-z\xdf-\xf6\xf8-\xff]+(?:['’](?:d|ll|m|re|s|t|ve))?(?=[\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000]|[A-Z\xc0-\xd6\xd8-\xde]|$)|(?:[A-Z\xc0-\xd6\xd8-\xde]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])+(?:['’](?:D|LL|M|RE|S|T|VE))?(?=[\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000]|[A-Z\xc0-\xd6\xd8-\xde](?:[a-z\xdf-\xf6\xf8-\xff]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])|$)|[A-Z\xc0-\xd6\xd8-\xde]?(?:[a-z\xdf-\xf6\xf8-\xff]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])+(?:['’](?:d|ll|m|re|s|t|ve))?|[A-Z\xc0-\xd6\xd8-\xde]+(?:['’](?:D|LL|M|RE|S|T|VE))?|\d*(?:1ST|2ND|3RD|(?![123])\dTH)(?=\b|[a-z_])|\d*(?:1st|2nd|3rd|(?![123])\dth)(?=\b|[A-Z_])|\d+|(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]|\ud83c[\udffb-\udfff])?(?:\u200d(?:[^\ud800-\udfff]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]|\ud83c[\udffb-\udfff])?)*/g,nm=t=>t.match(Hle)||[],im=t=>t[0].toUpperCase()+t.slice(1),TS=(t,e)=>nm(t).join(e).toLowerCase(),dM=t=>nm(t).reduce((e,r)=>`${e}${e?r[0].toUpperCase()+r.slice(1).toLowerCase():r.toLowerCase()}`,""),Gle=t=>im(dM(t)),Yle=t=>TS(t,"_"),Vle=t=>TS(t,"-"),Wle=t=>im(TS(t," ")),Jle=t=>nm(t).map(im).join(" ");AM.exports={words:nm,upperFirst:im,camelCase:dM,pascalCase:Gle,snakeCase:Yle,kebabCase:Vle,sentenceCase:Wle,titleCase:Jle}});var fM=y((Uje,DS)=>{"use strict";DS.exports=function(t){return hM(Zle(t),t)};DS.exports.array=hM;function hM(t,e){var r=t.length,n=new Array(r),i={},o=r,s=Kle(e),a=Xle(t);for(e.forEach(function(l){if(!a.has(l[0])||!a.has(l[1]))throw new Error("Unknown node. There is an unknown node in the supplied edges.")});o--;)i[o]||c(t[o],o,new Set);return n;function c(l,u,d){if(d.has(l)){var A;try{A=", node was:"+JSON.stringify(l)}catch{A=""}throw new Error("Cyclic dependency"+A)}if(!a.has(l))throw new Error("Found unknown node. Make sure to provided all involved nodes. Unknown node: "+JSON.stringify(l));if(!i[u]){i[u]=!0;var p=s.get(l)||new Set;if(p=Array.from(p),u=p.length){d.add(l);do{var h=p[--u];c(h,a.get(h),d)}while(u);d.delete(l)}n[--r]=l}}}function Zle(t){for(var e=new Set,r=0,n=t.length;r<n;r++){var i=t[r];e.add(i[0]),e.add(i[1])}return Array.from(e)}function Kle(t){for(var e=new Map,r=0,n=t.length;r<n;r++){var i=t[r];e.has(i[0])||e.set(i[0],new Set),e.has(i[1])||e.set(i[1],new Set),e.get(i[0]).add(i[1])}return e}function Xle(t){for(var e=new Map,r=0,n=t.length;r<n;r++)e.set(t[r],r);return e}});var MS={};yD(MS,{ArraySchema:()=>DA,BooleanSchema:()=>BA,DateSchema:()=>ru,LazySchema:()=>Am,MixedSchema:()=>_A,NumberSchema:()=>QA,ObjectSchema:()=>TA,Schema:()=>pr,StringSchema:()=>vA,TupleSchema:()=>kA,ValidationError:()=>sr,addMethod:()=>Due,array:()=>PM,bool:()=>kM,boolean:()=>kM,date:()=>US,defaultLocale:()=>vM,getIn:()=>OS,isSchema:()=>yc,lazy:()=>Que,mixed:()=>DM,number:()=>NM,object:()=>MM,printValue:()=>qo,reach:()=>cue,ref:()=>aue,setLocale:()=>Tue,string:()=>RM,tuple:()=>LM});function oue(t){return t!=+t?"NaN":t===0&&1/t<0?"-0":""+t}function gM(t,e=!1){if(t==null||t===!0||t===!1)return""+t;let r=typeof t;if(r==="number")return oue(t);if(r==="string")return e?`"${t}"`:t;if(r==="function")return"[Function "+(t.name||"anonymous")+"]";if(r==="symbol")return nue.call(t).replace(iue,"Symbol($1)");let n=eue.call(t).slice(8,-1);return n==="Date"?isNaN(t.getTime())?""+t:t.toISOString(t):n==="Error"||t instanceof Error?"["+tue.call(t)+"]":n==="RegExp"?rue.call(t):null}function qo(t,e){let r=gM(t,e);return r!==null?r:JSON.stringify(t,function(n,i){let o=gM(this[n],e);return o!==null?o:i},2)}function bM(t){return t==null?[]:[].concat(t)}function aue(t,e){return new Ho(t,e)}function eu(t){function e({value:r,path:n="",options:i,originalValue:o,schema:s},a,c){let{name:l,test:u,params:d,message:A,skipAbsent:p}=t,{parent:h,context:f,abortEarly:E=s.spec.abortEarly,disableStackTrace:S=s.spec.disableStackTrace}=i,B={value:r,parent:h,context:f};function _(Ae={}){let Re=QM(Object.assign({value:r,originalValue:o,label:s.spec.label,path:Ae.path||n,spec:s.spec,disableStackTrace:Ae.disableStackTrace||S},d,Ae.params),B),Ge=new sr(sr.formatError(Ae.message||A,Re),r,Re.path,Ae.type||l,Re.disableStackTrace);return Ge.params=Re,Ge}let v=E?a:c,T={path:n,parent:h,type:l,from:i.from,createError:_,resolve(Ae){return TM(Ae,B)},options:i,originalValue:o,schema:s},L=Ae=>{sr.isError(Ae)?v(Ae):Ae?c(null):v(_())},k=Ae=>{sr.isError(Ae)?v(Ae):a(Ae)};if(p&&Qi(r))return L(!0);let U;try{var K;if(U=u.call(T,r,T),typeof((K=U)==null?void 0:K.then)=="function"){if(i.sync)throw new Error(`Validation test of type: "${T.type}" returned a Promise during a synchronous validate. This test will finish after the validate call has returned`);return Promise.resolve(U).then(L,k)}}catch(Ae){k(Ae);return}L(U)}return e.OPTIONS=t,e}function QM(t,e){if(!t)return t;for(let r of Object.keys(t))t[r]=TM(t[r],e);return t}function TM(t,e){return Ho.isRef(t)?t.getValue(e.value,e.parent,e.context):t}function OS(t,e,r,n=r){let i,o,s;return e?((0,ri.forEach)(e,(a,c,l)=>{let u=c?a.slice(1,a.length-1):a;t=t.resolve({context:n,parent:i,value:r});let d=t.type==="tuple",A=l?parseInt(u,10):0;if(t.innerType||d){if(d&&!l)throw new Error(`Yup.reach cannot implicitly index into a tuple type. the path part "${s}" must contain an index to the tuple element, e.g. "${s}[0]"`);if(r&&A>=r.length)throw new Error(`Yup.reach cannot resolve an array item at index: ${a}, in the path: ${e}. because there is no value at that index. `);i=r,r=r&&r[A],t=d?t.spec.types[A]:t.innerType}if(!l){if(!t.fields||!t.fields[u])throw new Error(`The schema does not contain the path: ${e}. (failed at: ${s} which is a type: "${t.type}")`);i=r,r=r&&r[u],t=t.fields[u]}o=u,s=c?"["+a+"]":"."+a}),{schema:t,parent:i,parentPath:o}):{parent:i,parentPath:e,schema:t}}function cue(t,e,r,n){return OS(t,e,r,n).schema}function tu(t,e=new Map){if(yc(t)||!t||typeof t!="object")return t;if(e.has(t))return e.get(t);let r;if(t instanceof Date)r=new Date(t.getTime()),e.set(t,r);else if(t instanceof RegExp)r=new RegExp(t),e.set(t,r);else if(Array.isArray(t)){r=new Array(t.length),e.set(t,r);for(let n=0;n<t.length;n++)r[n]=tu(t[n],e)}else if(t instanceof Map){r=new Map,e.set(t,r);for(let[n,i]of t.entries())r.set(n,tu(i,e))}else if(t instanceof Set){r=new Set,e.set(t,r);for(let n of t)r.add(tu(n,e))}else if(t instanceof Object){r={},e.set(t,r);for(let[n,i]of Object.entries(t))r[n]=tu(i,e)}else throw Error(`Unable to clone ${t}`);return r}function lue(t){if(!(t!=null&&t.length))return;let e=[],r="",n=!1,i=!1;for(let o=0;o<t.length;o++){let s=t[o];if(s==="["&&!i){r&&(e.push(...r.split(".").filter(Boolean)),r=""),n=!0;continue}if(s==="]"&&!i){r&&(/^\d+$/.test(r)?e.push(r):e.push(r.replace(/^"|"$/g,"")),r=""),n=!1;continue}if(s==='"'){i=!i;continue}if(s==="."&&!n&&!i){r&&(e.push(r),r="");continue}r+=s}return r&&e.push(...r.split(".").filter(Boolean)),e}function uue(t,e){let r=e?`${e}.${t.path}`:t.path;return t.errors.map(n=>({message:n,path:lue(r)}))}function xS(t,e){var r;if(!((r=t.inner)!=null&&r.length)&&t.errors.length)return uue(t,e);let n=e?`${e}.${t.path}`:t.path;return t.inner.flatMap(i=>xS(i,n))}function DM(t){return new _A(t)}function kM(){return new BA}function pue(t){let e=NS(t);if(!e)return Date.parse?Date.parse(t):Number.NaN;if(e.z===void 0&&e.plusMinus===void 0)return new Date(e.year,e.month,e.day,e.hour,e.minute,e.second,e.millisecond).valueOf();let r=0;return e.z!=="Z"&&e.plusMinus!==void 0&&(r=e.hourOffset*60+e.minuteOffset,e.plusMinus==="+"&&(r=0-r)),Date.UTC(e.year,e.month,e.day,e.hour,e.minute+r,e.second,e.millisecond)}function NS(t){var e,r;let n=Aue.exec(t);return n?{year:ws(n[1]),month:ws(n[2],1)-1,day:ws(n[3],1),hour:ws(n[4]),minute:ws(n[5]),second:ws(n[6]),millisecond:n[7]?ws(n[7].substring(0,3)):0,precision:(e=(r=n[7])==null?void 0:r.length)!=null?e:void 0,z:n[8]||void 0,plusMinus:n[9]||void 0,hourOffset:ws(n[10]),minuteOffset:ws(n[11])}:null}function ws(t,e=0){return Number(t)||e}function RM(){return new vA}function NM(){return new QA}function US(){return new ru}function _ue(t,e=[]){let r=[],n=new Set,i=new Set(e.map(([s,a])=>`${s}-${a}`));function o(s,a){let c=(0,ri.split)(s)[0];n.add(c),i.has(`${a}-${c}`)||r.push([a,c])}for(let s of Object.keys(t)){let a=t[s];n.add(s),Ho.isRef(a)&&a.isSibling?o(a.path,s):yc(a)&&"deps"in a&&a.deps.forEach(c=>o(c,s))}return CM.default.array(Array.from(n),r).reverse()}function mM(t,e){let r=1/0;return t.some((n,i)=>{var o;if((o=e.path)!=null&&o.includes(n))return r=i,!0}),r}function xM(t){return(e,r)=>mM(t,e)-mM(t,r)}function cm(t){if("fields"in t){let e={};for(let[r,n]of Object.entries(t.fields))e[r]=cm(n);return t.setFields(e)}if(t.type==="array"){let e=t.optional();return e.innerType&&(e.innerType=cm(e.innerType)),e}return t.type==="tuple"?t.optional().clone({types:t.spec.types.map(cm)}):"optional"in t?t.optional():t}function EM(t,e){let r=Object.keys(t.fields);return Object.keys(e).filter(n=>r.indexOf(n)===-1)}function MM(t){return new TA(t)}function PM(t){return new DA(t)}function LM(t){return new kA(t)}function Que(t){return new Am(t)}function IM(t){try{return t()}catch(e){if(sr.isError(e))return Promise.reject(e);throw e}}function Tue(t){Object.keys(t).forEach(e=>{Object.keys(t[e]).forEach(r=>{vM[e][r]=t[e][r]})})}function Due(t,e,r){if(!t||!yc(t.prototype))throw new TypeError("You must provide a yup schema constructor function");if(typeof e!="string")throw new TypeError("A Method name must be provided");if(typeof r!="function")throw new TypeError("Method function must be provided");t.prototype[e]=r}var ri,wA,CM,eue,tue,rue,nue,iue,SM,wM,_M,sue,lm,sr,zo,Jr,ha,kS,RS,sm,am,BM,vM,yc,um,om,Ho,Qi,dm,pr,due,_A,BA,Aue,hue,fue,gue,mue,yue,Eue,Iue,Cue,bue,vA,Sue,QA,OM,wue,ru,UM,Bue,yM,vue,TA,DA,kA,Am,PS=ft(()=>{"use strict";ri=Be(uM()),wA=Be(pM()),CM=Be(fM()),eue=Object.prototype.toString,tue=Error.prototype.toString,rue=RegExp.prototype.toString,nue=typeof Symbol<"u"?Symbol.prototype.toString:()=>"",iue=/^Symbol\((.*)\)(.*)$/;sue=/\$\{\s*(\w+)\s*\}/g;SM=Symbol.toStringTag;lm=class{constructor(e,r,n,i){this.name=void 0,this.message=void 0,this.value=void 0,this.path=void 0,this.type=void 0,this.params=void 0,this.errors=void 0,this.inner=void 0,this[SM]="Error",this.name="ValidationError",this.value=r,this.path=n,this.type=i,this.errors=[],this.inner=[],bM(e).forEach(o=>{if(sr.isError(o)){this.errors.push(...o.errors);let s=o.inner.length?o.inner:[o];this.inner.push(...s)}else this.errors.push(o)}),this.message=this.errors.length>1?`${this.errors.length} errors occurred`:this.errors[0]}};wM=Symbol.hasInstance;_M=Symbol.toStringTag;sr=class t extends Error{static formatError(e,r){let n=r.label||r.path||"this";return r=Object.assign({},r,{path:n,originalPath:r.path}),typeof e=="string"?e.replace(sue,(i,o)=>qo(r[o])):typeof e=="function"?e(r):e}static isError(e){return e&&e.name==="ValidationError"}constructor(e,r,n,i,o){let s=new lm(e,r,n,i);if(o)return s;super(),this.value=void 0,this.path=void 0,this.type=void 0,this.params=void 0,this.errors=[],this.inner=[],this[_M]="Error",this.name=s.name,this.message=s.message,this.type=s.type,this.value=s.value,this.path=s.path,this.errors=s.errors,this.inner=s.inner,Error.captureStackTrace&&Error.captureStackTrace(this,t)}static[wM](e){return lm[Symbol.hasInstance](e)||super[Symbol.hasInstance](e)}},zo={default:"${path} is invalid",required:"${path} is a required field",defined:"${path} must be defined",notNull:"${path} cannot be null",oneOf:"${path} must be one of the following values: ${values}",notOneOf:"${path} must not be one of the following values: ${values}",notType:({path:t,type:e,value:r,originalValue:n})=>{let i=n!=null&&n!==r?` (cast from the value \`${qo(n,!0)}\`).`:".";return e!=="mixed"?`${t} must be a \`${e}\` type, but the final value was: \`${qo(r,!0)}\``+i:`${t} must match the configured type. The validated value was: \`${qo(r,!0)}\``+i}},Jr={length:"${path} must be exactly ${length} characters",min:"${path} must be at least ${min} characters",max:"${path} must be at most ${max} characters",matches:'${path} must match the following: "${regex}"',email:"${path} must be a valid email",url:"${path} must be a valid URL",uuid:"${path} must be a valid UUID",datetime:"${path} must be a valid ISO date-time",datetime_precision:"${path} must be a valid ISO date-time with a sub-second precision of exactly ${precision} digits",datetime_offset:'${path} must be a valid ISO date-time with UTC "Z" timezone',trim:"${path} must be a trimmed string",lowercase:"${path} must be a lowercase string",uppercase:"${path} must be a upper case string"},ha={min:"${path} must be greater than or equal to ${min}",max:"${path} must be less than or equal to ${max}",lessThan:"${path} must be less than ${less}",moreThan:"${path} must be greater than ${more}",positive:"${path} must be a positive number",negative:"${path} must be a negative number",integer:"${path} must be an integer"},kS={min:"${path} field must be later than ${min}",max:"${path} field must be at earlier than ${max}"},RS={isValue:"${path} field must be ${value}"},sm={noUnknown:"${path} field has unspecified keys: ${unknown}",exact:"${path} object contains unknown properties: ${properties}"},am={min:"${path} field must have at least ${min} items",max:"${path} field must have less than or equal to ${max} items",length:"${path} must have ${length} items"},BM={notType:t=>{let{path:e,value:r,spec:n}=t,i=n.types.length;if(Array.isArray(r)){if(r.length<i)return`${e} tuple value has too few items, expected a length of ${i} but got ${r.length} for value: \`${qo(r,!0)}\``;if(r.length>i)return`${e} tuple value has too many items, expected a length of ${i} but got ${r.length} for value: \`${qo(r,!0)}\``}return sr.formatError(zo.notType,t)}},vM=Object.assign(Object.create(null),{mixed:zo,string:Jr,number:ha,date:kS,object:sm,array:am,boolean:RS,tuple:BM}),yc=t=>t&&t.__isYupSchema__,um=class t{static fromOptions(e,r){if(!r.then&&!r.otherwise)throw new TypeError("either `then:` or `otherwise:` is required for `when()` conditions");let{is:n,then:i,otherwise:o}=r,s=typeof n=="function"?n:(...a)=>a.every(c=>c===n);return new t(e,(a,c)=>{var l;let u=s(...a)?i:o;return(l=u?.(c))!=null?l:c})}constructor(e,r){this.fn=void 0,this.refs=e,this.refs=e,this.fn=r}resolve(e,r){let n=this.refs.map(o=>o.getValue(r?.value,r?.parent,r?.context)),i=this.fn(n,e,r);if(i===void 0||i===e)return e;if(!yc(i))throw new TypeError("conditions must return a schema object");return i.resolve(r)}},om={context:"$",value:"."};Ho=class{constructor(e,r={}){if(this.key=void 0,this.isContext=void 0,this.isValue=void 0,this.isSibling=void 0,this.path=void 0,this.getter=void 0,this.map=void 0,typeof e!="string")throw new TypeError("ref must be a string, got: "+e);if(this.key=e.trim(),e==="")throw new TypeError("ref must be a non-empty string");this.isContext=this.key[0]===om.context,this.isValue=this.key[0]===om.value,this.isSibling=!this.isContext&&!this.isValue;let n=this.isContext?om.context:this.isValue?om.value:"";this.path=this.key.slice(n.length),this.getter=this.path&&(0,ri.getter)(this.path,!0),this.map=r.map}getValue(e,r,n){let i=this.isContext?n:this.isValue?e:r;return this.getter&&(i=this.getter(i||{})),this.map&&(i=this.map(i)),i}cast(e,r){return this.getValue(e,r?.parent,r?.context)}resolve(){return this}describe(){return{type:"ref",key:this.key}}toString(){return`Ref(${this.key})`}static isRef(e){return e&&e.__isYupRef}};Ho.prototype.__isYupRef=!0;Qi=t=>t==null;dm=class t extends Set{describe(){let e=[];for(let r of this.values())e.push(Ho.isRef(r)?r.describe():r);return e}resolveAll(e){let r=[];for(let n of this.values())r.push(e(n));return r}clone(){return new t(this.values())}merge(e,r){let n=this.clone();return e.forEach(i=>n.add(i)),r.forEach(i=>n.delete(i)),n}};pr=class{constructor(e){this.type=void 0,this.deps=[],this.tests=void 0,this.transforms=void 0,this.conditions=[],this._mutate=void 0,this.internalTests={},this._whitelist=new dm,this._blacklist=new dm,this.exclusiveTests=Object.create(null),this._typeCheck=void 0,this.spec=void 0,this.tests=[],this.transforms=[],this.withMutation(()=>{this.typeError(zo.notType)}),this.type=e.type,this._typeCheck=e.check,this.spec=Object.assign({strip:!1,strict:!1,abortEarly:!0,recursive:!0,disableStackTrace:!1,nullable:!1,optional:!0,coerce:!0},e?.spec),this.withMutation(r=>{r.nonNullable()})}get _type(){return this.type}clone(e){if(this._mutate)return e&&Object.assign(this.spec,e),this;let r=Object.create(Object.getPrototypeOf(this));return r.type=this.type,r._typeCheck=this._typeCheck,r._whitelist=this._whitelist.clone(),r._blacklist=this._blacklist.clone(),r.internalTests=Object.assign({},this.internalTests),r.exclusiveTests=Object.assign({},this.exclusiveTests),r.deps=[...this.deps],r.conditions=[...this.conditions],r.tests=[...this.tests],r.transforms=[...this.transforms],r.spec=tu(Object.assign({},this.spec,e)),r}label(e){let r=this.clone();return r.spec.label=e,r}meta(...e){if(e.length===0)return this.spec.meta;let r=this.clone();return r.spec.meta=Object.assign(r.spec.meta||{},e[0]),r}withMutation(e){let r=this._mutate;this._mutate=!0;let n=e(this);return this._mutate=r,n}concat(e){if(!e||e===this)return this;if(e.type!==this.type&&this.type!=="mixed")throw new TypeError(`You cannot \`concat()\` schema's of different types: ${this.type} and ${e.type}`);let r=this,n=e.clone(),i=Object.assign({},r.spec,n.spec);return n.spec=i,n.internalTests=Object.assign({},r.internalTests,n.internalTests),n._whitelist=r._whitelist.merge(e._whitelist,e._blacklist),n._blacklist=r._blacklist.merge(e._blacklist,e._whitelist),n.tests=r.tests,n.exclusiveTests=r.exclusiveTests,n.withMutation(o=>{e.tests.forEach(s=>{o.test(s.OPTIONS)})}),n.transforms=[...r.transforms,...n.transforms],n}isType(e){return e==null?!!(this.spec.nullable&&e===null||this.spec.optional&&e===void 0):this._typeCheck(e)}resolve(e){let r=this;if(r.conditions.length){let n=r.conditions;r=r.clone(),r.conditions=[],r=n.reduce((i,o)=>o.resolve(i,e),r),r=r.resolve(e)}return r}resolveOptions(e){var r,n,i,o;return Object.assign({},e,{from:e.from||[],strict:(r=e.strict)!=null?r:this.spec.strict,abortEarly:(n=e.abortEarly)!=null?n:this.spec.abortEarly,recursive:(i=e.recursive)!=null?i:this.spec.recursive,disableStackTrace:(o=e.disableStackTrace)!=null?o:this.spec.disableStackTrace})}cast(e,r={}){let n=this.resolve(Object.assign({},r,{value:e})),i=r.assert==="ignore-optionality",o=n._cast(e,r);if(r.assert!==!1&&!n.isType(o)){if(i&&Qi(o))return o;let s=qo(e),a=qo(o);throw new TypeError(`The value of ${r.path||"field"} could not be cast to a value that satisfies the schema type: "${n.type}".
|
|
103
103
|
|
|
104
104
|
attempted value: ${s}
|
|
105
|
-
`+(a!==s?`result of cast: ${a}`:""))}return o}_cast(e,r){let n=e===void 0?e:this.transforms.reduce((i,o)=>o.call(this,i,e,this,r),e);return n===void 0&&(n=this.getDefault(r)),n}_validate(e,r={},n,i){let{path:o,originalValue:s=e,strict:a=this.spec.strict}=r,c=e;a||(c=this._cast(c,Object.assign({assert:!1},r)));let l=[];for(let u of Object.values(this.internalTests))u&&l.push(u);this.runTests({path:o,value:c,originalValue:s,options:r,tests:l},n,u=>{if(u.length)return i(u,c);this.runTests({path:o,value:c,originalValue:s,options:r,tests:this.tests},n,i)})}runTests(e,r,n){let i=!1,{tests:o,value:s,originalValue:a,path:c,options:l}=e,u=f=>{i||(i=!0,r(f,s))},d=f=>{i||(i=!0,n(f,s))},A=o.length,p=[];if(!A)return d([]);let h={value:s,originalValue:a,path:c,options:l,schema:this};for(let f=0;f<o.length;f++){let E=o[f];E(h,u,function(B){B&&(Array.isArray(B)?p.push(...B):p.push(B)),--A<=0&&d(p)})}}asNestedTest({key:e,index:r,parent:n,parentPath:i,originalParent:o,options:s}){let a=e??r;if(a==null)throw TypeError("Must include `key` or `index` for nested validations");let c=typeof a=="number",l=n[a],u=Object.assign({},s,{strict:!0,parent:n,value:l,originalValue:o[a],key:void 0,[c?"index":"key"]:a,path:c||a.includes(".")?`${i||""}[${c?a:`"${a}"`}]`:(i?`${i}.`:"")+e});return(d,A,p)=>this.resolve(u)._validate(l,u,A,p)}validate(e,r){var n;let i=this.resolve(Object.assign({},r,{value:e})),o=(n=r?.disableStackTrace)!=null?n:i.spec.disableStackTrace;return new Promise((s,a)=>i._validate(e,r,(c,l)=>{or.isError(c)&&(c.value=l),a(c)},(c,l)=>{c.length?a(new or(c,l,void 0,void 0,o)):s(l)}))}validateSync(e,r){var n;let i=this.resolve(Object.assign({},r,{value:e})),o,s=(n=r?.disableStackTrace)!=null?n:i.spec.disableStackTrace;return i._validate(e,Object.assign({},r,{sync:!0}),(a,c)=>{throw or.isError(a)&&(a.value=c),a},(a,c)=>{if(a.length)throw new or(a,e,void 0,void 0,s);o=c}),o}isValid(e,r){return this.validate(e,r).then(()=>!0,n=>{if(or.isError(n))return!1;throw n})}isValidSync(e,r){try{return this.validateSync(e,r),!0}catch(n){if(or.isError(n))return!1;throw n}}_getDefault(e){let r=this.spec.default;return r==null?r:typeof r=="function"?r.call(this,e):tu(r)}getDefault(e){return this.resolve(e||{})._getDefault(e)}default(e){return arguments.length===0?this._getDefault():this.clone({default:e})}strict(e=!0){return this.clone({strict:e})}nullability(e,r){let n=this.clone({nullable:e});return n.internalTests.nullable=eu({message:r,name:"nullable",test(i){return i===null?this.schema.spec.nullable:!0}}),n}optionality(e,r){let n=this.clone({optional:e});return n.internalTests.optionality=eu({message:r,name:"optionality",test(i){return i===void 0?this.schema.spec.optional:!0}}),n}optional(){return this.optionality(!0)}defined(e=zo.defined){return this.optionality(!1,e)}nullable(){return this.nullability(!0)}nonNullable(e=zo.notNull){return this.nullability(!1,e)}required(e=zo.required){return this.clone().withMutation(r=>r.nonNullable(e).defined(e))}notRequired(){return this.clone().withMutation(e=>e.nullable().optional())}transform(e){let r=this.clone();return r.transforms.push(e),r}test(...e){let r;if(e.length===1?typeof e[0]=="function"?r={test:e[0]}:r=e[0]:e.length===2?r={name:e[0],test:e[1]}:r={name:e[0],message:e[1],test:e[2]},r.message===void 0&&(r.message=zo.default),typeof r.test!="function")throw new TypeError("`test` is a required parameters");let n=this.clone(),i=eu(r),o=r.exclusive||r.name&&n.exclusiveTests[r.name]===!0;if(r.exclusive&&!r.name)throw new TypeError("Exclusive tests must provide a unique `name` identifying the test");return r.name&&(n.exclusiveTests[r.name]=!!r.exclusive),n.tests=n.tests.filter(s=>!(s.OPTIONS.name===r.name&&(o||s.OPTIONS.test===i.OPTIONS.test))),n.tests.push(i),n}when(e,r){!Array.isArray(e)&&typeof e!="string"&&(r=e,e=".");let n=this.clone(),i=bM(e).map(o=>new Ho(o));return i.forEach(o=>{o.isSibling&&n.deps.push(o.key)}),n.conditions.push(typeof r=="function"?new um(i,r):um.fromOptions(i,r)),n}typeError(e){let r=this.clone();return r.internalTests.typeError=eu({message:e,name:"typeError",skipAbsent:!0,test(n){return this.schema._typeCheck(n)?!0:this.createError({params:{type:this.schema.type}})}}),r}oneOf(e,r=zo.oneOf){let n=this.clone();return e.forEach(i=>{n._whitelist.add(i),n._blacklist.delete(i)}),n.internalTests.whiteList=eu({message:r,name:"oneOf",skipAbsent:!0,test(i){let o=this.schema._whitelist,s=o.resolveAll(this.resolve);return s.includes(i)?!0:this.createError({params:{values:Array.from(o).join(", "),resolved:s}})}}),n}notOneOf(e,r=zo.notOneOf){let n=this.clone();return e.forEach(i=>{n._blacklist.add(i),n._whitelist.delete(i)}),n.internalTests.blacklist=eu({message:r,name:"notOneOf",test(i){let o=this.schema._blacklist,s=o.resolveAll(this.resolve);return s.includes(i)?this.createError({params:{values:Array.from(o).join(", "),resolved:s}}):!0}}),n}strip(e=!0){let r=this.clone();return r.spec.strip=e,r}describe(e){let r=(e?this.resolve(e):this).clone(),{label:n,meta:i,optional:o,nullable:s}=r.spec;return{meta:i,label:n,optional:o,nullable:s,default:r.getDefault(e),type:r.type,oneOf:r._whitelist.describe(),notOneOf:r._blacklist.describe(),tests:r.tests.filter((c,l,u)=>u.findIndex(d=>d.OPTIONS.name===c.OPTIONS.name)===l).map(c=>{let l=c.OPTIONS.params&&e?QM(Object.assign({},c.OPTIONS.params),e):c.OPTIONS.params;return{name:c.OPTIONS.name,params:l}})}}get"~standard"(){let e=this;return{version:1,vendor:"yup",async validate(n){try{return{value:await e.validate(n,{abortEarly:!1})}}catch(i){if(i instanceof or)return{issues:xS(i)};throw i}}}}};pr.prototype.__isYupSchema__=!0;for(let t of["validate","validateSync"])pr.prototype[`${t}At`]=function(e,r,n={}){let{parent:i,parentPath:o,schema:s}=OS(this,e,r,n.context);return s[t](i&&i[o],Object.assign({},n,{parent:i,path:e}))};for(let t of["equals","is"])pr.prototype[t]=pr.prototype.oneOf;for(let t of["not","nope"])pr.prototype[t]=pr.prototype.notOneOf;due=()=>!0;_A=class extends pr{constructor(e){super(typeof e=="function"?{type:"mixed",check:e}:Object.assign({type:"mixed",check:due},e))}};DM.prototype=_A.prototype;BA=class extends pr{constructor(){super({type:"boolean",check(e){return e instanceof Boolean&&(e=e.valueOf()),typeof e=="boolean"}}),this.withMutation(()=>{this.transform((e,r)=>{if(this.spec.coerce&&!this.isType(e)){if(/^(true|1)$/i.test(String(e)))return!0;if(/^(false|0)$/i.test(String(e)))return!1}return e})})}isTrue(e=RS.isValue){return this.test({message:e,name:"is-value",exclusive:!0,params:{value:"true"},test(r){return Qi(r)||r===!0}})}isFalse(e=RS.isValue){return this.test({message:e,name:"is-value",exclusive:!0,params:{value:"false"},test(r){return Qi(r)||r===!1}})}default(e){return super.default(e)}defined(e){return super.defined(e)}optional(){return super.optional()}required(e){return super.required(e)}notRequired(){return super.notRequired()}nullable(){return super.nullable()}nonNullable(e){return super.nonNullable(e)}strip(e){return super.strip(e)}};kM.prototype=BA.prototype;Aue=/^(\d{4}|[+-]\d{6})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:[ T]?(\d{2}):?(\d{2})(?::?(\d{2})(?:[,.](\d{1,}))?)?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?)?)?$/;hue=/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,fue=/^((https?|ftp):)?\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,gue=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,mue="^\\d{4}-\\d{2}-\\d{2}",yue="\\d{2}:\\d{2}:\\d{2}",Eue="(([+-]\\d{2}(:?\\d{2})?)|Z)",Iue=new RegExp(`${mue}T${yue}(\\.\\d+)?${Eue}$`),Cue=t=>Qi(t)||t===t.trim(),bue={}.toString();vA=class extends pr{constructor(){super({type:"string",check(e){return e instanceof String&&(e=e.valueOf()),typeof e=="string"}}),this.withMutation(()=>{this.transform((e,r)=>{if(!this.spec.coerce||this.isType(e)||Array.isArray(e))return e;let n=e!=null&&e.toString?e.toString():e;return n===bue?e:n})})}required(e){return super.required(e).withMutation(r=>r.test({message:e||zo.required,name:"required",skipAbsent:!0,test:n=>!!n.length}))}notRequired(){return super.notRequired().withMutation(e=>(e.tests=e.tests.filter(r=>r.OPTIONS.name!=="required"),e))}length(e,r=Jr.length){return this.test({message:r,name:"length",exclusive:!0,params:{length:e},skipAbsent:!0,test(n){return n.length===this.resolve(e)}})}min(e,r=Jr.min){return this.test({message:r,name:"min",exclusive:!0,params:{min:e},skipAbsent:!0,test(n){return n.length>=this.resolve(e)}})}max(e,r=Jr.max){return this.test({name:"max",exclusive:!0,message:r,params:{max:e},skipAbsent:!0,test(n){return n.length<=this.resolve(e)}})}matches(e,r){let n=!1,i,o;return r&&(typeof r=="object"?{excludeEmptyString:n=!1,message:i,name:o}=r:i=r),this.test({name:o||"matches",message:i||Jr.matches,params:{regex:e},skipAbsent:!0,test:s=>s===""&&n||s.search(e)!==-1})}email(e=Jr.email){return this.matches(hue,{name:"email",message:e,excludeEmptyString:!0})}url(e=Jr.url){return this.matches(fue,{name:"url",message:e,excludeEmptyString:!0})}uuid(e=Jr.uuid){return this.matches(gue,{name:"uuid",message:e,excludeEmptyString:!1})}datetime(e){let r="",n,i;return e&&(typeof e=="object"?{message:r="",allowOffset:n=!1,precision:i=void 0}=e:r=e),this.matches(Iue,{name:"datetime",message:r||Jr.datetime,excludeEmptyString:!0}).test({name:"datetime_offset",message:r||Jr.datetime_offset,params:{allowOffset:n},skipAbsent:!0,test:o=>{if(!o||n)return!0;let s=NS(o);return s?!!s.z:!1}}).test({name:"datetime_precision",message:r||Jr.datetime_precision,params:{precision:i},skipAbsent:!0,test:o=>{if(!o||i==null)return!0;let s=NS(o);return s?s.precision===i:!1}})}ensure(){return this.default("").transform(e=>e===null?"":e)}trim(e=Jr.trim){return this.transform(r=>r!=null?r.trim():r).test({message:e,name:"trim",test:Cue})}lowercase(e=Jr.lowercase){return this.transform(r=>Qi(r)?r:r.toLowerCase()).test({message:e,name:"string_case",exclusive:!0,skipAbsent:!0,test:r=>Qi(r)||r===r.toLowerCase()})}uppercase(e=Jr.uppercase){return this.transform(r=>Qi(r)?r:r.toUpperCase()).test({message:e,name:"string_case",exclusive:!0,skipAbsent:!0,test:r=>Qi(r)||r===r.toUpperCase()})}};RM.prototype=vA.prototype;Sue=t=>t!=+t;QA=class extends pr{constructor(){super({type:"number",check(e){return e instanceof Number&&(e=e.valueOf()),typeof e=="number"&&!Sue(e)}}),this.withMutation(()=>{this.transform((e,r)=>{if(!this.spec.coerce)return e;let n=e;if(typeof n=="string"){if(n=n.replace(/\s/g,""),n==="")return NaN;n=+n}return this.isType(n)||n===null?n:parseFloat(n)})})}min(e,r=ha.min){return this.test({message:r,name:"min",exclusive:!0,params:{min:e},skipAbsent:!0,test(n){return n>=this.resolve(e)}})}max(e,r=ha.max){return this.test({message:r,name:"max",exclusive:!0,params:{max:e},skipAbsent:!0,test(n){return n<=this.resolve(e)}})}lessThan(e,r=ha.lessThan){return this.test({message:r,name:"max",exclusive:!0,params:{less:e},skipAbsent:!0,test(n){return n<this.resolve(e)}})}moreThan(e,r=ha.moreThan){return this.test({message:r,name:"min",exclusive:!0,params:{more:e},skipAbsent:!0,test(n){return n>this.resolve(e)}})}positive(e=ha.positive){return this.moreThan(0,e)}negative(e=ha.negative){return this.lessThan(0,e)}integer(e=ha.integer){return this.test({name:"integer",message:e,skipAbsent:!0,test:r=>Number.isInteger(r)})}truncate(){return this.transform(e=>Qi(e)?e:e|0)}round(e){var r;let n=["ceil","floor","round","trunc"];if(e=((r=e)==null?void 0:r.toLowerCase())||"round",e==="trunc")return this.truncate();if(n.indexOf(e.toLowerCase())===-1)throw new TypeError("Only valid options for round() are: "+n.join(", "));return this.transform(i=>Qi(i)?i:Math[e](i))}};NM.prototype=QA.prototype;OM=new Date(""),wue=t=>Object.prototype.toString.call(t)==="[object Date]";ru=class t extends pr{constructor(){super({type:"date",check(e){return wue(e)&&!isNaN(e.getTime())}}),this.withMutation(()=>{this.transform((e,r)=>!this.spec.coerce||this.isType(e)||e===null?e:(e=pue(e),isNaN(e)?t.INVALID_DATE:new Date(e)))})}prepareParam(e,r){let n;if(Ho.isRef(e))n=e;else{let i=this.cast(e);if(!this._typeCheck(i))throw new TypeError(`\`${r}\` must be a Date or a value that can be \`cast()\` to a Date`);n=i}return n}min(e,r=kS.min){let n=this.prepareParam(e,"min");return this.test({message:r,name:"min",exclusive:!0,params:{min:e},skipAbsent:!0,test(i){return i>=this.resolve(n)}})}max(e,r=kS.max){let n=this.prepareParam(e,"max");return this.test({message:r,name:"max",exclusive:!0,params:{max:e},skipAbsent:!0,test(i){return i<=this.resolve(n)}})}};ru.INVALID_DATE=OM;US.prototype=ru.prototype;US.INVALID_DATE=OM;UM=(t,e,r)=>{if(typeof t!="string")return t;let n=t;try{n=JSON.parse(t)}catch{}return r.isType(n)?n:t};Bue=(t,e)=>{let r=[...(0,ri.normalizePath)(e)];if(r.length===1)return r[0]in t;let n=r.pop(),i=(0,ri.getter)((0,ri.join)(r),!0)(t);return!!(i&&n in i)},yM=t=>Object.prototype.toString.call(t)==="[object Object]";vue=xM([]);TA=class extends pr{constructor(e){super({type:"object",check(r){return yM(r)||typeof r=="function"}}),this.fields=Object.create(null),this._sortErrors=vue,this._nodes=[],this._excludedEdges=[],this.withMutation(()=>{e&&this.shape(e)})}_cast(e,r={}){var n;let i=super._cast(e,r);if(i===void 0)return this.getDefault(r);if(!this._typeCheck(i))return i;let o=this.fields,s=(n=r.stripUnknown)!=null?n:this.spec.noUnknown,a=[].concat(this._nodes,Object.keys(i).filter(d=>!this._nodes.includes(d))),c={},l=Object.assign({},r,{parent:c,__validating:r.__validating||!1}),u=!1;for(let d of a){let A=o[d],p=d in i,h=i[d];if(A){let f;l.path=(r.path?`${r.path}.`:"")+d,A=A.resolve({value:h,context:r.context,parent:c});let E=A instanceof pr?A.spec:void 0,S=E?.strict;if(E!=null&&E.strip){u=u||d in i;continue}f=!r.__validating||!S?A.cast(h,l):h,f!==void 0&&(c[d]=f)}else p&&!s&&(c[d]=h);(p!==d in c||c[d]!==h)&&(u=!0)}return u?c:i}_validate(e,r={},n,i){let{from:o=[],originalValue:s=e,recursive:a=this.spec.recursive}=r;r.from=[{schema:this,value:s},...o],r.__validating=!0,r.originalValue=s,super._validate(e,r,n,(c,l)=>{if(!a||!yM(l)){i(c,l);return}s=s||l;let u=[];for(let d of this._nodes){let A=this.fields[d];!A||Ho.isRef(A)||u.push(A.asNestedTest({options:r,key:d,parent:l,parentPath:r.path,originalParent:s}))}this.runTests({tests:u,value:l,originalValue:s,options:r},n,d=>{i(d.sort(this._sortErrors).concat(c),l)})})}clone(e){let r=super.clone(e);return r.fields=Object.assign({},this.fields),r._nodes=this._nodes,r._excludedEdges=this._excludedEdges,r._sortErrors=this._sortErrors,r}concat(e){let r=super.concat(e),n=r.fields;for(let[i,o]of Object.entries(this.fields)){let s=n[i];n[i]=s===void 0?o:s}return r.withMutation(i=>i.setFields(n,[...this._excludedEdges,...e._excludedEdges]))}_getDefault(e){if("default"in this.spec)return super._getDefault(e);if(!this._nodes.length)return;let r={};return this._nodes.forEach(n=>{var i;let o=this.fields[n],s=e;(i=s)!=null&&i.value&&(s=Object.assign({},s,{parent:s.value,value:s.value[n]})),r[n]=o&&"getDefault"in o?o.getDefault(s):void 0}),r}setFields(e,r){let n=this.clone();return n.fields=e,n._nodes=_ue(e,r),n._sortErrors=xM(Object.keys(e)),r&&(n._excludedEdges=r),n}shape(e,r=[]){return this.clone().withMutation(n=>{let i=n._excludedEdges;return r.length&&(Array.isArray(r[0])||(r=[r]),i=[...n._excludedEdges,...r]),n.setFields(Object.assign(n.fields,e),i)})}partial(){let e={};for(let[r,n]of Object.entries(this.fields))e[r]="optional"in n&&n.optional instanceof Function?n.optional():n;return this.setFields(e)}deepPartial(){return cm(this)}pick(e){let r={};for(let n of e)this.fields[n]&&(r[n]=this.fields[n]);return this.setFields(r,this._excludedEdges.filter(([n,i])=>e.includes(n)&&e.includes(i)))}omit(e){let r=[];for(let n of Object.keys(this.fields))e.includes(n)||r.push(n);return this.pick(r)}from(e,r,n){let i=(0,ri.getter)(e,!0);return this.transform(o=>{if(!o)return o;let s=o;return Bue(o,e)&&(s=Object.assign({},o),n||delete s[e],s[r]=i(o)),s})}json(){return this.transform(UM)}exact(e){return this.test({name:"exact",exclusive:!0,message:e||sm.exact,test(r){if(r==null)return!0;let n=EM(this.schema,r);return n.length===0||this.createError({params:{properties:n.join(", ")}})}})}stripUnknown(){return this.clone({noUnknown:!0})}noUnknown(e=!0,r=sm.noUnknown){typeof e!="boolean"&&(r=e,e=!0);let n=this.test({name:"noUnknown",exclusive:!0,message:r,test(i){if(i==null)return!0;let o=EM(this.schema,i);return!e||o.length===0||this.createError({params:{unknown:o.join(", ")}})}});return n.spec.noUnknown=e,n}unknown(e=!0,r=sm.noUnknown){return this.noUnknown(!e,r)}transformKeys(e){return this.transform(r=>{if(!r)return r;let n={};for(let i of Object.keys(r))n[e(i)]=r[i];return n})}camelCase(){return this.transformKeys(wA.camelCase)}snakeCase(){return this.transformKeys(wA.snakeCase)}constantCase(){return this.transformKeys(e=>(0,wA.snakeCase)(e).toUpperCase())}describe(e){let r=(e?this.resolve(e):this).clone(),n=super.describe(e);n.fields={};for(let[o,s]of Object.entries(r.fields)){var i;let a=e;(i=a)!=null&&i.value&&(a=Object.assign({},a,{parent:a.value,value:a.value[o]})),n.fields[o]=s.describe(a)}return n}};MM.prototype=TA.prototype;DA=class extends pr{constructor(e){super({type:"array",spec:{types:e},check(r){return Array.isArray(r)}}),this.innerType=void 0,this.innerType=e}_cast(e,r){let n=super._cast(e,r);if(!this._typeCheck(n)||!this.innerType)return n;let i=!1,o=n.map((s,a)=>{let c=this.innerType.cast(s,Object.assign({},r,{path:`${r.path||""}[${a}]`,parent:n,originalValue:s,value:s,index:a}));return c!==s&&(i=!0),c});return i?o:n}_validate(e,r={},n,i){var o;let s=this.innerType,a=(o=r.recursive)!=null?o:this.spec.recursive;r.originalValue!=null&&r.originalValue,super._validate(e,r,n,(c,l)=>{var u;if(!a||!s||!this._typeCheck(l)){i(c,l);return}let d=new Array(l.length);for(let p=0;p<l.length;p++){var A;d[p]=s.asNestedTest({options:r,index:p,parent:l,parentPath:r.path,originalParent:(A=r.originalValue)!=null?A:e})}this.runTests({value:l,tests:d,originalValue:(u=r.originalValue)!=null?u:e,options:r},n,p=>i(p.concat(c),l))})}clone(e){let r=super.clone(e);return r.innerType=this.innerType,r}json(){return this.transform(UM)}concat(e){let r=super.concat(e);return r.innerType=this.innerType,e.innerType&&(r.innerType=r.innerType?r.innerType.concat(e.innerType):e.innerType),r}of(e){let r=this.clone();if(!yc(e))throw new TypeError("`array.of()` sub-schema must be a valid yup schema not: "+qo(e));return r.innerType=e,r.spec=Object.assign({},r.spec,{types:e}),r}length(e,r=am.length){return this.test({message:r,name:"length",exclusive:!0,params:{length:e},skipAbsent:!0,test(n){return n.length===this.resolve(e)}})}min(e,r){return r=r||am.min,this.test({message:r,name:"min",exclusive:!0,params:{min:e},skipAbsent:!0,test(n){return n.length>=this.resolve(e)}})}max(e,r){return r=r||am.max,this.test({message:r,name:"max",exclusive:!0,params:{max:e},skipAbsent:!0,test(n){return n.length<=this.resolve(e)}})}ensure(){return this.default(()=>[]).transform((e,r)=>this._typeCheck(e)?e:r==null?[]:[].concat(r))}compact(e){let r=e?(n,i,o)=>!e(n,i,o):n=>!!n;return this.transform(n=>n!=null?n.filter(r):n)}describe(e){let r=(e?this.resolve(e):this).clone(),n=super.describe(e);if(r.innerType){var i;let o=e;(i=o)!=null&&i.value&&(o=Object.assign({},o,{parent:o.value,value:o.value[0]})),n.innerType=r.innerType.describe(o)}return n}};PM.prototype=DA.prototype;kA=class extends pr{constructor(e){super({type:"tuple",spec:{types:e},check(r){let n=this.spec.types;return Array.isArray(r)&&r.length===n.length}}),this.withMutation(()=>{this.typeError(BM.notType)})}_cast(e,r){let{types:n}=this.spec,i=super._cast(e,r);if(!this._typeCheck(i))return i;let o=!1,s=n.map((a,c)=>{let l=a.cast(i[c],Object.assign({},r,{path:`${r.path||""}[${c}]`,parent:i,originalValue:i[c],value:i[c],index:c}));return l!==i[c]&&(o=!0),l});return o?s:i}_validate(e,r={},n,i){let o=this.spec.types;super._validate(e,r,n,(s,a)=>{var c;if(!this._typeCheck(a)){i(s,a);return}let l=[];for(let[d,A]of o.entries()){var u;l[d]=A.asNestedTest({options:r,index:d,parent:a,parentPath:r.path,originalParent:(u=r.originalValue)!=null?u:e})}this.runTests({value:a,tests:l,originalValue:(c=r.originalValue)!=null?c:e,options:r},n,d=>i(d.concat(s),a))})}describe(e){let r=(e?this.resolve(e):this).clone(),n=super.describe(e);return n.innerType=r.spec.types.map((i,o)=>{var s;let a=e;return(s=a)!=null&&s.value&&(a=Object.assign({},a,{parent:a.value,value:a.value[o]})),i.describe(a)}),n}};LM.prototype=kA.prototype;Am=class t{constructor(e){this.type="lazy",this.__isYupSchema__=!0,this.spec=void 0,this._resolve=(r,n={})=>{let i=this.builder(r,n);if(!yc(i))throw new TypeError("lazy() functions must return a valid schema");return this.spec.optional&&(i=i.optional()),i.resolve(n)},this.builder=e,this.spec={meta:void 0,optional:!1}}clone(e){let r=new t(this.builder);return r.spec=Object.assign({},this.spec,e),r}optionality(e){return this.clone({optional:e})}optional(){return this.optionality(!0)}resolve(e){return this._resolve(e.value,e)}cast(e,r){return this._resolve(e,r).cast(e,r)}asNestedTest(e){let{key:r,index:n,parent:i,options:o}=e,s=i[n??r];return this._resolve(s,Object.assign({},o,{value:s,parent:i})).asNestedTest(e)}validate(e,r){return IM(()=>this._resolve(e,r).validate(e,r))}validateSync(e,r){return this._resolve(e,r).validateSync(e,r)}validateAt(e,r,n){return IM(()=>this._resolve(r,n).validateAt(e,r,n))}validateSyncAt(e,r,n){return this._resolve(r,n).validateSyncAt(e,r,n)}isValid(e,r){try{return this._resolve(e,r).isValid(e,r)}catch(n){if(or.isError(n))return Promise.resolve(!1);throw n}}isValidSync(e,r){return this._resolve(e,r).isValidSync(e,r)}describe(e){return e?this.resolve(e).describe(e):{type:"lazy",meta:this.spec.meta,label:void 0}}meta(...e){if(e.length===0)return this.spec.meta;let r=this.clone();return r.spec.meta=Object.assign(r.spec.meta||{},e[0]),r}get"~standard"(){let e=this;return{version:1,vendor:"yup",async validate(n){try{return{value:await e.validate(n,{abortEarly:!1})}}catch(i){if(or.isError(i))return{issues:xS(i)};throw i}}}}}});var $M=y(LS=>{"use strict";Object.defineProperty(LS,"__esModule",{value:!0});LS.default=[{name:"npm-node-cron",preset:{presetId:"npm-node-cron",useSeconds:!0,useYears:!1,useAliases:!0,useBlankDay:!1,allowOnlyOneBlankDayField:!1,mustHaveBlankDayField:!1,useLastDayOfMonth:!1,useLastDayOfWeek:!1,useNearestWeekday:!1,useNthWeekdayOfMonth:!1,seconds:{minValue:0,maxValue:59},minutes:{minValue:0,maxValue:59},hours:{minValue:0,maxValue:23},daysOfMonth:{minValue:1,maxValue:31},months:{minValue:0,maxValue:11},daysOfWeek:{minValue:0,maxValue:6},years:{minValue:1970,maxValue:2099}}},{name:"aws-cloud-watch",preset:{presetId:"aws-cloud-watch",useSeconds:!1,useYears:!0,useAliases:!0,useBlankDay:!0,allowOnlyOneBlankDayField:!0,mustHaveBlankDayField:!0,useLastDayOfMonth:!0,useLastDayOfWeek:!0,useNearestWeekday:!0,useNthWeekdayOfMonth:!0,seconds:{minValue:0,maxValue:59},minutes:{minValue:0,maxValue:59},hours:{minValue:0,maxValue:23},daysOfMonth:{minValue:1,maxValue:31},months:{minValue:1,maxValue:12},daysOfWeek:{minValue:1,maxValue:7},years:{minValue:1970,maxValue:2199}}},{name:"npm-cron-schedule",preset:{presetId:"npm-cron-schedule",useSeconds:!0,useYears:!1,useAliases:!0,useBlankDay:!1,allowOnlyOneBlankDayField:!1,mustHaveBlankDayField:!1,useLastDayOfMonth:!1,useLastDayOfWeek:!1,useNearestWeekday:!1,useNthWeekdayOfMonth:!1,seconds:{minValue:0,maxValue:59},minutes:{minValue:0,maxValue:59},hours:{minValue:0,maxValue:23},daysOfMonth:{minValue:1,maxValue:31},months:{minValue:1,maxValue:12},daysOfWeek:{minValue:0,maxValue:7},years:{minValue:1970,maxValue:2099}}}]});var qM=y(sr=>{"use strict";var kue=sr&&sr.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Rue=sr&&sr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Nue=sr&&sr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&kue(e,t,r);return Rue(e,t),e},Oue=sr&&sr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(sr,"__esModule",{value:!0});sr.validateOptions=sr.registerOptionPreset=sr.getOptionPresets=sr.getOptionPreset=void 0;var J=Nue((PS(),DC(MS)));PS();var nu=Bi(),FM=Oue($M());vi();var Ec={default:{presetId:"default",useSeconds:!1,useYears:!1,useAliases:!1,useBlankDay:!1,allowOnlyOneBlankDayField:!1,allowStepping:!0,mustHaveBlankDayField:!1,useLastDayOfMonth:!1,useLastDayOfWeek:!1,useNearestWeekday:!1,useNthWeekdayOfMonth:!1,seconds:{minValue:0,maxValue:59},minutes:{minValue:0,maxValue:59},hours:{minValue:0,maxValue:23},daysOfMonth:{minValue:0,maxValue:31},months:{minValue:0,maxValue:12},daysOfWeek:{minValue:0,maxValue:7},years:{minValue:1970,maxValue:2099}}},zM=J.object({presetId:J.string().required(),useSeconds:J.boolean().required(),useYears:J.boolean().required(),useAliases:J.boolean(),useBlankDay:J.boolean().required(),allowOnlyOneBlankDayField:J.boolean().required(),allowStepping:J.boolean(),mustHaveBlankDayField:J.boolean(),useLastDayOfMonth:J.boolean(),useLastDayOfWeek:J.boolean(),useNearestWeekday:J.boolean(),useNthWeekdayOfMonth:J.boolean(),seconds:J.object({minValue:J.number().min(0).required(),maxValue:J.number().min(0).required(),lowerLimit:J.number().min(0),upperLimit:J.number().min(0)}).required(),minutes:J.object({minValue:J.number().min(0).required(),maxValue:J.number().min(0).required(),lowerLimit:J.number().min(0),upperLimit:J.number().min(0)}).required(),hours:J.object({minValue:J.number().min(0).required(),maxValue:J.number().min(0).required(),lowerLimit:J.number().min(0),upperLimit:J.number().min(0)}).required(),daysOfMonth:J.object({minValue:J.number().min(0).required(),maxValue:J.number().min(0).required(),lowerLimit:J.number().min(0),upperLimit:J.number().min(0)}).required(),months:J.object({minValue:J.number().min(0).required(),maxValue:J.number().min(0).required(),lowerLimit:J.number().min(0),upperLimit:J.number().min(0)}).required(),daysOfWeek:J.object({minValue:J.number().min(0).required(),maxValue:J.number().min(0).required(),lowerLimit:J.number().min(0),upperLimit:J.number().min(0)}).required(),years:J.object({minValue:J.number().min(0).required(),maxValue:J.number().min(0).required(),lowerLimit:J.number().min(0),upperLimit:J.number().min(0)}).required()}).required(),xue=t=>Ec[t]?(0,nu.valid)(Ec[t]):(0,nu.err)(`Option preset '${t}' not found.`);sr.getOptionPreset=xue;var Uue=()=>Ec;sr.getOptionPresets=Uue;var Mue=(t,e)=>{Ec[t]=zM.validateSync(e,{strict:!1,abortEarly:!1,stripUnknown:!0,recursive:!0})};sr.registerOptionPreset=Mue;function Pue(){for(let t=0;t<FM.default.length;t+=1){let{name:e,preset:r}=FM.default[t];(0,sr.registerOptionPreset)(e,r)}}Pue();var jM=new Map;function Lue(t,e){var r;return t+((r=JSON.stringify(e))!==null&&r!==void 0?r:"")}function $ue(t){return J.object({presetId:J.string().required(),preset:zM.required(),useSeconds:J.boolean().required(),useYears:J.boolean().required(),useAliases:J.boolean(),useBlankDay:J.boolean().required(),allowOnlyOneBlankDayField:J.boolean().required(),allowStepping:J.boolean(),mustHaveBlankDayField:J.boolean(),useLastDayOfMonth:J.boolean(),useLastDayOfWeek:J.boolean(),useNearestWeekday:J.boolean(),useNthWeekdayOfMonth:J.boolean(),seconds:J.object({lowerLimit:J.number().min(t.seconds.minValue).max(t.seconds.maxValue),upperLimit:J.number().min(t.seconds.minValue).max(t.seconds.maxValue)}).required(),minutes:J.object({lowerLimit:J.number().min(t.minutes.minValue).max(t.minutes.maxValue),upperLimit:J.number().min(t.minutes.minValue).max(t.minutes.maxValue)}).required(),hours:J.object({lowerLimit:J.number().min(t.hours.minValue).max(t.hours.maxValue),upperLimit:J.number().min(t.hours.minValue).max(t.hours.maxValue)}).required(),daysOfMonth:J.object({lowerLimit:J.number().min(t.daysOfMonth.minValue).max(t.daysOfMonth.maxValue),upperLimit:J.number().min(t.daysOfMonth.minValue).max(t.daysOfMonth.maxValue)}).required(),months:J.object({lowerLimit:J.number().min(t.months.minValue).max(t.months.maxValue),upperLimit:J.number().min(t.months.minValue).max(t.months.maxValue)}).required(),daysOfWeek:J.object({lowerLimit:J.number().min(t.daysOfWeek.minValue).max(t.daysOfWeek.maxValue),upperLimit:J.number().min(t.daysOfWeek.minValue).max(t.daysOfWeek.maxValue)}).required(),years:J.object({lowerLimit:J.number().min(t.years.minValue).max(t.years.maxValue),upperLimit:J.number().min(t.years.minValue).max(t.years.maxValue)}).required()}).required()}function Fue(t,e){var r,n,i,o,s,a,c,l,u,d,A,p,h,f,E,S,B,_,v,T,L;let k=Object.assign(Object.assign({presetId:t.presetId,preset:t},{useSeconds:t.useSeconds,useYears:t.useYears,useAliases:(r=t.useAliases)!==null&&r!==void 0?r:!1,useBlankDay:t.useBlankDay,allowOnlyOneBlankDayField:t.allowOnlyOneBlankDayField,allowStepping:(n=t.allowStepping)!==null&&n!==void 0?n:!0,mustHaveBlankDayField:(i=t.mustHaveBlankDayField)!==null&&i!==void 0?i:!1,useLastDayOfMonth:(o=t.useLastDayOfMonth)!==null&&o!==void 0?o:!1,useLastDayOfWeek:(s=t.useLastDayOfWeek)!==null&&s!==void 0?s:!1,useNearestWeekday:(a=t.useNearestWeekday)!==null&&a!==void 0?a:!1,useNthWeekdayOfMonth:(c=t.useNthWeekdayOfMonth)!==null&&c!==void 0?c:!1,seconds:{lowerLimit:(l=t.seconds.lowerLimit)!==null&&l!==void 0?l:t.seconds.minValue,upperLimit:(u=t.seconds.upperLimit)!==null&&u!==void 0?u:t.seconds.maxValue},minutes:{lowerLimit:(d=t.minutes.lowerLimit)!==null&&d!==void 0?d:t.minutes.minValue,upperLimit:(A=t.minutes.upperLimit)!==null&&A!==void 0?A:t.minutes.maxValue},hours:{lowerLimit:(p=t.hours.lowerLimit)!==null&&p!==void 0?p:t.hours.minValue,upperLimit:(h=t.hours.upperLimit)!==null&&h!==void 0?h:t.hours.maxValue},daysOfMonth:{lowerLimit:(f=t.daysOfMonth.lowerLimit)!==null&&f!==void 0?f:t.daysOfMonth.minValue,upperLimit:(E=t.daysOfMonth.upperLimit)!==null&&E!==void 0?E:t.daysOfMonth.maxValue},months:{lowerLimit:(S=t.months.lowerLimit)!==null&&S!==void 0?S:t.months.minValue,upperLimit:(B=t.months.upperLimit)!==null&&B!==void 0?B:t.months.maxValue},daysOfWeek:{lowerLimit:(_=t.daysOfWeek.lowerLimit)!==null&&_!==void 0?_:t.daysOfWeek.minValue,upperLimit:(v=t.daysOfWeek.upperLimit)!==null&&v!==void 0?v:t.daysOfWeek.maxValue},years:{lowerLimit:(T=t.years.lowerLimit)!==null&&T!==void 0?T:t.years.minValue,upperLimit:(L=t.years.upperLimit)!==null&&L!==void 0?L:t.years.maxValue}}),e);return $ue(t).validateSync(k,{strict:!1,abortEarly:!1,stripUnknown:!0,recursive:!0})}var jue=t=>{try{let e;if(t.preset)if(typeof t.preset=="string"){if(!Ec[t.preset])return(0,nu.err)([`Option preset ${t.preset} does not exist.`]);e=Ec[t.preset]}else e=t.preset;else e=Ec.default;let r=Lue(e.presetId,t.override),n=jM.get(r);if(n)return(0,nu.valid)(n);let i=Fue(e,t.override);return jM.set(r,i),(0,nu.valid)(i)}catch(e){return(0,nu.err)(e.errors)}};sr.validateOptions=jue});var jo=y(RA=>{"use strict";var Cc=RA&&RA.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(RA,"__esModule",{value:!0});var Ic=Bi(),zue=Cc(KU()),que=Cc(XU()),Hue=Cc(eM()),Gue=Cc(tM()),Yue=Cc(rM()),Vue=Cc(nM()),Wue=Cc(iM()),Jue=qM();vi();var Zue=(t,e)=>{let r=t.trim().split(" ");if(e.useSeconds&&e.useYears&&r.length!==7)return(0,Ic.err)(`Expected 7 values, but got ${r.length}.`);if((e.useSeconds&&!e.useYears||e.useYears&&!e.useSeconds)&&r.length!==6)return(0,Ic.err)(`Expected 6 values, but got ${r.length}.`);if(!e.useSeconds&&!e.useYears&&r.length!==5)return(0,Ic.err)(`Expected 5 values, but got ${r.length}.`);let n={seconds:e.useSeconds?r[0]:void 0,minutes:r[e.useSeconds?1:0],hours:r[e.useSeconds?2:1],daysOfMonth:r[e.useSeconds?3:2],months:r[e.useSeconds?4:3],daysOfWeek:r[e.useSeconds?5:4],years:e.useYears?r[e.useSeconds?6:5]:void 0};return(0,Ic.valid)(n)},Kue=(t,e={})=>{let r=(0,Jue.validateOptions)(e);if(r.isError())return r;let n=r.getValue(),i=Zue(t,n);if(i.isError())return(0,Ic.err)([`${i.getError()} (Input cron: '${t}')`]);let o=i.getValue(),s=[];if(n.useSeconds&&s.push((0,zue.default)(o,n)),s.push((0,que.default)(o,n)),s.push((0,Hue.default)(o,n)),s.push((0,Gue.default)(o,n)),s.push((0,Yue.default)(o,n)),s.push((0,Vue.default)(o,n)),n.useYears&&s.push((0,Wue.default)(o,n)),s.every(c=>c.isValid()))return(0,Ic.valid)(o);let a=[];return s.forEach(c=>{c.isError()&&c.getError().forEach(l=>{a.push(l)})}),a.forEach((c,l)=>{a[l]=`${c} (Input cron: '${t}')`}),(0,Ic.err)(a)};RA.default=Kue});var NA=y(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.parseUTCDate=pm;xr.requireUTCDate=HM;xr.toUTCISOString=GM;xr.toOptionalUTCISOString=sde;xr.utcNow=YM;xr.utcNowISOString=ade;xr.getUTCTimestampMs=VM;xr.parsePersistedTimestamp=hm;xr.getPersistedTimestampMs=cde;xr.formatPersistedTimestamp=WM;xr.formatCompactPersistedTimestamp=lde;xr.formatPersistedDate=JM;xr.formatRelativePersistedTimestamp=ude;var Xue=/(Z|[+-]\d{2}(?::?\d{2})?)$/i,ede=/^\d{4}-\d{2}-\d{2}$/,tde=/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}/,rde={year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"},nde={month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"},ide={year:"numeric",month:"short",day:"numeric"};function ode(t){let e=t.trim();return e&&(ede.test(e)?`${e}T00:00:00.000Z`:Xue.test(e)?e:tde.test(e)?`${e.replace(" ","T")}Z`:e)}function pm(t){if(t==null||t==="")return;let e=typeof t=="string"?ode(t):t instanceof Date||typeof t=="number"&&Number.isFinite(t)?t:void 0;if(e===void 0)return;let r=new Date(e);return Number.isNaN(r.getTime())?void 0:r}function HM(t,e="timestamp"){let r=pm(t);if(!r)throw new Error(`Invalid ${e}`);return r}function GM(t,e="timestamp"){return HM(t,e).toISOString()}function sde(t,e="timestamp"){if(!(t==null||t===""))return GM(t,e)}function YM(){return new Date}function ade(){return YM().toISOString()}function VM(t){let e=pm(t);return e?e.getTime():Number.NEGATIVE_INFINITY}function hm(t){return pm(t)}function cde(t){return VM(t)}function WM(t,e=rde,r="-"){let n=hm(t);return n?n.toLocaleString(void 0,e):r}function lde(t,e="-"){return WM(t,nde,e)}function JM(t,e="-"){let r=hm(t);return r?r.toLocaleDateString(void 0,ide):e}function ude(t,e=""){let r=hm(t);if(!r)return e;let n=Date.now()-r.getTime(),i=Math.floor(n/6e4);if(i<1)return"just now";if(i<60)return`${i}m ago`;let o=Math.floor(i/60);if(o<24)return`${o}h ago`;let s=Math.floor(o/24);return s<30?`${s}d ago`:JM(r,e)}});var KM=y(iu=>{"use strict";var dde=iu&&iu.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(iu,"__esModule",{value:!0});iu.calculateNextRun=hde;iu.validateCronExpression=fde;var Ade=WU(),pde=dde(jo()),ZM=NA();function hde(t,e,r){let n=r||(0,ZM.utcNow)(),o=Ade.CronExpressionParser.parse(t,{currentDate:n,tz:e}).next().toDate();return(0,ZM.parseUTCDate)(o.toISOString())||o}function fde(t){try{return(0,pde.default)(t,{preset:"default",override:{useSeconds:!1,useYears:!1,useAliases:!1,allowStepping:!0,useLastDayOfMonth:!1,useLastDayOfWeek:!1,useNearestWeekday:!1}}).isValid()}catch{return!1}}});var OA=y(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});bc.DEFAULT_TIMEZONE=void 0;bc.isValidTimezone=XM;bc.getRuntimeTimezone=gde;bc.DEFAULT_TIMEZONE="UTC";function XM(t){try{return new Intl.DateTimeFormat("en-US",{timeZone:t}),!0}catch{return!1}}function gde(){let t=Intl.DateTimeFormat().resolvedOptions().timeZone;return t&&XM(t)?t:bc.DEFAULT_TIMEZONE}});var eP=y($S=>{"use strict";Object.defineProperty($S,"__esModule",{value:!0});$S.getConfiguredModelContextLength=yde;var mde=2e5;function yde(){return mde}});var tP=y(FS=>{"use strict";Object.defineProperty(FS,"__esModule",{value:!0});FS.getModelOutputTokenLimit=Ide;var Ede={"claude-fable-5":128e3,"claude-mythos-5":128e3,"claude-opus-5":128e3,"claude-sonnet-5":128e3,"claude-opus-4-8":128e3,"claude-opus-4-7":128e3,"claude-opus-4-6":128e3,"claude-sonnet-4-6":64e3,"claude-haiku-4-5":64e3,"claude-opus-4-5":64e3,"claude-sonnet-4-5":64e3,"gpt-6.1-sol":128e3,"gpt-5":128e3,"gpt-4.1":32768,"gpt-4o":16384,"gemini-2.5-flash":65536,"gemini-2.5-pro":65536};function Ide(t){let e=t.model.toLowerCase();return Object.entries(Ede).find(([n])=>e.includes(n))?.[1]}});var Ti=y(M=>{"use strict";var Cde=M&&M.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),ym=M&&M.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Cde(e,t,r)},bde=M&&M.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(M,"__esModule",{value:!0});M.MAX_OBJECT_PREVIEW_KEYS=M.MAX_TRUNCATION_DEPTH=M.MAX_ARRAY_PREVIEW_ITEMS=M.MAX_STRING_PREVIEW_LENGTH=M.MAX_INLINE_RESULT_PREVIEW_BYTES=M.FULLY_MASKED_CREDENTIAL_VALUE=M.maskCredentialValue=M.isSensitiveCredentialKey=M.CREDENTIAL_KEY_VALIDATION_DESCRIPTION=M.CREDENTIAL_KEY_PATTERN=M.ALLOWED_FILE_EXTENSIONS=void 0;M.mapPlaybookToDraftConfig=Bde;M.mapPlaybookDraftToInput=vde;M.inferProtocolFromUrl=oP;M.getSuiteCloudOperation=sP;M.isNetSuiteRestletUrl=aP;M.isSuiteCloudWrite=Tde;M.isAbortError=Dde;M.getToolInputSchemaSections=Nde;M.buildToolInputSchemaSections=xde;M.flattenAndNamespaceCredentials=Mde;M.flattenAndNamespaceSystemUrls=Pde;M.slugify=Lde;M.generateUniqueId=$de;M.resolveOAuthCertAndKey=Fde;M.isArrowFunction=lP;M.assertValidArrowFunction=jde;M.normalizeCredentialKey=uP;M.isValidCredentialKey=dP;M.getCredentialKeyValidationError=AP;M.getInvalidCredentialKeyNames=qde;M.hasCredentialValue=pP;M.hasCredentialKeyValue=Yde;M.getCredentialKeyMetadata=Vde;M.isFullyMaskedCredentialValue=hP;M.maskCredentialSetValues=Wde;M.restoreMaskedCredentialValues=Jde;M.isMaskedValue=Zde;M.maskCredentials=fP;M.buildSensitiveCredentialMap=Kde;M.redactKnownCredentialValues=zS;M.estimateDataSize=rAe;M.truncateValue=fm;M.sampleResultObject=gP;M.safeStringify=qS;M.coerceDate=gm;M.normalizeToolCallDates=mP;M.normalizeMessageDates=HS;M.cloneMessagesWithDates=nAe;M.applyAgentCompactionToMessages=iAe;M.redactUrlCredentials=oAe;M.getToolVisuals=GS;M.getReplacedVisualIds=yP;M.getMessageVisuals=EP;M.getMessageContent=IP;M.getMessageToolCalls=YS;M.hasMessageText=bP;M.hasAssistantOutput=SP;M.isEmptyAssistantMessage=VS;M.isRenderableAgentMessage=aAe;M.pruneEmptyAssistantMessages=cAe;M.getMeaningfulMessages=lAe;M.truncateForLLM=uAe;M.truncateHeadTail=dAe;M.getErrorMessage=AAe;M.pickReferencedExecutionFiles=pAe;M.normalizeToolDiff=wP;M.normalizeToolDiffs=hAe;M.composeUrl=fAe;M.truncateRunResult=yAe;M.getToolSystemIds=EAe;M.getCredentialPlaceholderKeysForSystem=CAe;M.getUnscopedCallPlaceholderError=wAe;M.formatLabel=_Ae;var iP=pg(),Sde=RC(),wde=pn(),_de=bde((ax(),DC(sx)));ym(KM(),M);ym(OA(),M);ym(eP(),M);ym(tP(),M);function Bde(t){return{name:t.name,whenToRun:t.whenToRun,instructions:t.instructions}}function vde(t){return{name:t.name,whenToRun:t.whenToRun,instructions:t.instructions}}function oP(t){return t.startsWith("postgres://")||t.startsWith("postgresql://")?"postgres":t.startsWith("mssql://")||t.startsWith("sqlserver://")?"mssql":t.startsWith("redis://")||t.startsWith("rediss://")?"redis":t.startsWith("mongodb://")||t.startsWith("mongodb+srv://")?"mongodb":t.startsWith("ftp://")||t.startsWith("ftps://")||t.startsWith("sftp://")?"sftp":t.startsWith("smb://")?"smb":t.startsWith("odbc://")?"odbc":t.startsWith("script://")?"script":t.startsWith("suitecloud://")?"suitecloud":"http"}var rP=new Set(["listObjects","importObjects","listFiles","importFiles","validate","preview"]);function sP(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch{return}let r=e&&typeof e=="object"?e.operation:void 0;return typeof r=="string"?r:void 0}var Qde=new Set(["deploy","callRestlet","cleanupScripts"]);function jS(t){let e=typeof t=="string"?t:JSON.stringify(t??"");return e.includes("<<")||e.includes("{{")}var nP=/^https?:\/\/[^/?#]*\.restlets\.api\.netsuite\.com(?:[:/?#]|$)|\/app\/site\/hosting\/restlet\.nl/i;function aP(t){if(nP.test(t.trim()))return!0;let e;try{e=new URL(t.trim())}catch{return!1}let r=e.pathname;try{r=decodeURIComponent(r)}catch{}return nP.test(`${e.protocol}//${e.hostname.replace(/\.$/,"")}${r.replace(/\/{2,}/g,"/")}`)}function Tde({url:t,body:e}){if(typeof t!="string")return!1;if(aP(t))return!0;let r=sP(e);return oP(t)!=="suitecloud"?jS(t)&&r!==void 0&&(jS(r)||rP.has(r)||Qde.has(r)):jS(e)?!0:r===void 0||!rP.has(r)}function Dde(t){return t?typeof t=="string"?t.startsWith("AbortError:"):t instanceof DOMException?t.name==="AbortError":t instanceof Error?t.name==="AbortError"||t.message.startsWith("AbortError:"):!1:!1}M.ALLOWED_FILE_EXTENSIONS=[".json",".csv",".txt",".xml",".xlsx",".xls",".pdf",".docx",".pptx",".zip",".gz",".yaml",".yml",".py",".ts",".tsx",".js",".jsx",".java",".go",".rs",".rb",".php",".c",".cpp",".h",".hpp",".cs",".swift",".kt",".scala",".sh",".bash",".sql",".html",".css",".scss",".md",".rst"];function kde(t){if(!t)return null;if(typeof t=="string")try{return JSON.parse(t)}catch{return null}return t}function cP(t){return structuredClone(t)}function Rde(t,e){if(!t||typeof t!="object")return t;let r=cP(t),n=r&&typeof r=="object"&&r.properties&&typeof r.properties=="object"?r.properties:void 0;if(!n)return r;let i=!1;for(let a of e)a in n&&(delete n[a],i=!0);if(!i)return r;if(Array.isArray(r.required)){let a=r.required.filter(c=>!e.includes(c));a.length>0?r.required=a:delete r.required}Object.keys(n).length===0&&delete r.properties;let o=r.properties&&typeof r.properties=="object"?Object.keys(r.properties):[],s=Array.isArray(r.allOf)&&r.allOf.length>0||Array.isArray(r.anyOf)&&r.anyOf.length>0||Array.isArray(r.oneOf)&&r.oneOf.length>0||!!r.patternProperties||!!r.additionalProperties;return o.length===0&&!s?null:r}function Nde(t){let e=kde(t),r=e&&typeof e=="object"&&e.properties?e.properties:void 0,n=r&&typeof r=="object"?Object.keys(r):[],i=!!(r?.payload&&r?.credentials&&n.every(o=>["payload","credentials"].includes(o)));return e?i?{rawSchema:e,payloadSchema:r?.payload||null,filesSchema:null,credentialsSchema:r?.credentials||null,hasNestedSections:!0}:{rawSchema:e,payloadSchema:Rde(e,["__files"]),filesSchema:r?.__files||null,credentialsSchema:null,hasNestedSections:!1}:{rawSchema:null,payloadSchema:null,filesSchema:null,credentialsSchema:null,hasNestedSections:!1}}function Ode(t){return!!(t&&typeof t=="object"&&Array.isArray(t.required)&&t.required.length>0)}function xde({payloadSchema:t,filesSchema:e}){if(!!!e)return t||void 0;let n=t&&typeof t=="object"?cP(t):{type:"object",properties:{}},i=n.properties&&typeof n.properties=="object"?{...n.properties}:{};i.__files=e,n.type=n.type||"object",n.properties=i;let o=Array.isArray(n.required)?n.required.filter(s=>s!=="__files"):[];return Ode(e)&&o.push("__files"),o.length>0?n.required=Array.from(new Set(o)):delete n.required,n}var Ude=t=>t!=null&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Date);function Mde(t){return t.reduce((e,r)=>(Object.entries(r.credentials||{}).forEach(([n,i])=>{e[`${r.id}_${n}`]=i}),e),{})}function Pde(t){return t.reduce((e,r)=>(r.url&&(e[`${r.id}_url`]=r.url),e),{})}function Lde(t){return t.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"system"}async function $de({baseId:t,exists:e}){if(!await e(t))return t;let r=1,n=t.match(/(.*)-(\d+)$/),i=t;for(n&&(i=n[1],r=parseInt(n[2],10)+1);;){let o=`${i}-${r}`;if(!await e(o))return o;r++}}function Fde(t,e){let r=null,n=null;try{t&&e&&(r=JSON.parse(t),n=JSON.parse(e))}catch{return{cert:{content:void 0,filename:void 0},key:{content:void 0,filename:void 0}}}return{cert:r,key:n}}function lP(t){let e=(t||"").trim();return e?/^\s*(async\s+)?(\([^)]*\)|[a-zA-Z_$][a-zA-Z0-9_$]*)\s*=>/.test(e):!1}function jde(t){let e=(t||"").trim();if(!e)return`(sourceData) => {
|
|
105
|
+
`+(a!==s?`result of cast: ${a}`:""))}return o}_cast(e,r){let n=e===void 0?e:this.transforms.reduce((i,o)=>o.call(this,i,e,this,r),e);return n===void 0&&(n=this.getDefault(r)),n}_validate(e,r={},n,i){let{path:o,originalValue:s=e,strict:a=this.spec.strict}=r,c=e;a||(c=this._cast(c,Object.assign({assert:!1},r)));let l=[];for(let u of Object.values(this.internalTests))u&&l.push(u);this.runTests({path:o,value:c,originalValue:s,options:r,tests:l},n,u=>{if(u.length)return i(u,c);this.runTests({path:o,value:c,originalValue:s,options:r,tests:this.tests},n,i)})}runTests(e,r,n){let i=!1,{tests:o,value:s,originalValue:a,path:c,options:l}=e,u=f=>{i||(i=!0,r(f,s))},d=f=>{i||(i=!0,n(f,s))},A=o.length,p=[];if(!A)return d([]);let h={value:s,originalValue:a,path:c,options:l,schema:this};for(let f=0;f<o.length;f++){let E=o[f];E(h,u,function(B){B&&(Array.isArray(B)?p.push(...B):p.push(B)),--A<=0&&d(p)})}}asNestedTest({key:e,index:r,parent:n,parentPath:i,originalParent:o,options:s}){let a=e??r;if(a==null)throw TypeError("Must include `key` or `index` for nested validations");let c=typeof a=="number",l=n[a],u=Object.assign({},s,{strict:!0,parent:n,value:l,originalValue:o[a],key:void 0,[c?"index":"key"]:a,path:c||a.includes(".")?`${i||""}[${c?a:`"${a}"`}]`:(i?`${i}.`:"")+e});return(d,A,p)=>this.resolve(u)._validate(l,u,A,p)}validate(e,r){var n;let i=this.resolve(Object.assign({},r,{value:e})),o=(n=r?.disableStackTrace)!=null?n:i.spec.disableStackTrace;return new Promise((s,a)=>i._validate(e,r,(c,l)=>{sr.isError(c)&&(c.value=l),a(c)},(c,l)=>{c.length?a(new sr(c,l,void 0,void 0,o)):s(l)}))}validateSync(e,r){var n;let i=this.resolve(Object.assign({},r,{value:e})),o,s=(n=r?.disableStackTrace)!=null?n:i.spec.disableStackTrace;return i._validate(e,Object.assign({},r,{sync:!0}),(a,c)=>{throw sr.isError(a)&&(a.value=c),a},(a,c)=>{if(a.length)throw new sr(a,e,void 0,void 0,s);o=c}),o}isValid(e,r){return this.validate(e,r).then(()=>!0,n=>{if(sr.isError(n))return!1;throw n})}isValidSync(e,r){try{return this.validateSync(e,r),!0}catch(n){if(sr.isError(n))return!1;throw n}}_getDefault(e){let r=this.spec.default;return r==null?r:typeof r=="function"?r.call(this,e):tu(r)}getDefault(e){return this.resolve(e||{})._getDefault(e)}default(e){return arguments.length===0?this._getDefault():this.clone({default:e})}strict(e=!0){return this.clone({strict:e})}nullability(e,r){let n=this.clone({nullable:e});return n.internalTests.nullable=eu({message:r,name:"nullable",test(i){return i===null?this.schema.spec.nullable:!0}}),n}optionality(e,r){let n=this.clone({optional:e});return n.internalTests.optionality=eu({message:r,name:"optionality",test(i){return i===void 0?this.schema.spec.optional:!0}}),n}optional(){return this.optionality(!0)}defined(e=zo.defined){return this.optionality(!1,e)}nullable(){return this.nullability(!0)}nonNullable(e=zo.notNull){return this.nullability(!1,e)}required(e=zo.required){return this.clone().withMutation(r=>r.nonNullable(e).defined(e))}notRequired(){return this.clone().withMutation(e=>e.nullable().optional())}transform(e){let r=this.clone();return r.transforms.push(e),r}test(...e){let r;if(e.length===1?typeof e[0]=="function"?r={test:e[0]}:r=e[0]:e.length===2?r={name:e[0],test:e[1]}:r={name:e[0],message:e[1],test:e[2]},r.message===void 0&&(r.message=zo.default),typeof r.test!="function")throw new TypeError("`test` is a required parameters");let n=this.clone(),i=eu(r),o=r.exclusive||r.name&&n.exclusiveTests[r.name]===!0;if(r.exclusive&&!r.name)throw new TypeError("Exclusive tests must provide a unique `name` identifying the test");return r.name&&(n.exclusiveTests[r.name]=!!r.exclusive),n.tests=n.tests.filter(s=>!(s.OPTIONS.name===r.name&&(o||s.OPTIONS.test===i.OPTIONS.test))),n.tests.push(i),n}when(e,r){!Array.isArray(e)&&typeof e!="string"&&(r=e,e=".");let n=this.clone(),i=bM(e).map(o=>new Ho(o));return i.forEach(o=>{o.isSibling&&n.deps.push(o.key)}),n.conditions.push(typeof r=="function"?new um(i,r):um.fromOptions(i,r)),n}typeError(e){let r=this.clone();return r.internalTests.typeError=eu({message:e,name:"typeError",skipAbsent:!0,test(n){return this.schema._typeCheck(n)?!0:this.createError({params:{type:this.schema.type}})}}),r}oneOf(e,r=zo.oneOf){let n=this.clone();return e.forEach(i=>{n._whitelist.add(i),n._blacklist.delete(i)}),n.internalTests.whiteList=eu({message:r,name:"oneOf",skipAbsent:!0,test(i){let o=this.schema._whitelist,s=o.resolveAll(this.resolve);return s.includes(i)?!0:this.createError({params:{values:Array.from(o).join(", "),resolved:s}})}}),n}notOneOf(e,r=zo.notOneOf){let n=this.clone();return e.forEach(i=>{n._blacklist.add(i),n._whitelist.delete(i)}),n.internalTests.blacklist=eu({message:r,name:"notOneOf",test(i){let o=this.schema._blacklist,s=o.resolveAll(this.resolve);return s.includes(i)?this.createError({params:{values:Array.from(o).join(", "),resolved:s}}):!0}}),n}strip(e=!0){let r=this.clone();return r.spec.strip=e,r}describe(e){let r=(e?this.resolve(e):this).clone(),{label:n,meta:i,optional:o,nullable:s}=r.spec;return{meta:i,label:n,optional:o,nullable:s,default:r.getDefault(e),type:r.type,oneOf:r._whitelist.describe(),notOneOf:r._blacklist.describe(),tests:r.tests.filter((c,l,u)=>u.findIndex(d=>d.OPTIONS.name===c.OPTIONS.name)===l).map(c=>{let l=c.OPTIONS.params&&e?QM(Object.assign({},c.OPTIONS.params),e):c.OPTIONS.params;return{name:c.OPTIONS.name,params:l}})}}get"~standard"(){let e=this;return{version:1,vendor:"yup",async validate(n){try{return{value:await e.validate(n,{abortEarly:!1})}}catch(i){if(i instanceof sr)return{issues:xS(i)};throw i}}}}};pr.prototype.__isYupSchema__=!0;for(let t of["validate","validateSync"])pr.prototype[`${t}At`]=function(e,r,n={}){let{parent:i,parentPath:o,schema:s}=OS(this,e,r,n.context);return s[t](i&&i[o],Object.assign({},n,{parent:i,path:e}))};for(let t of["equals","is"])pr.prototype[t]=pr.prototype.oneOf;for(let t of["not","nope"])pr.prototype[t]=pr.prototype.notOneOf;due=()=>!0;_A=class extends pr{constructor(e){super(typeof e=="function"?{type:"mixed",check:e}:Object.assign({type:"mixed",check:due},e))}};DM.prototype=_A.prototype;BA=class extends pr{constructor(){super({type:"boolean",check(e){return e instanceof Boolean&&(e=e.valueOf()),typeof e=="boolean"}}),this.withMutation(()=>{this.transform((e,r)=>{if(this.spec.coerce&&!this.isType(e)){if(/^(true|1)$/i.test(String(e)))return!0;if(/^(false|0)$/i.test(String(e)))return!1}return e})})}isTrue(e=RS.isValue){return this.test({message:e,name:"is-value",exclusive:!0,params:{value:"true"},test(r){return Qi(r)||r===!0}})}isFalse(e=RS.isValue){return this.test({message:e,name:"is-value",exclusive:!0,params:{value:"false"},test(r){return Qi(r)||r===!1}})}default(e){return super.default(e)}defined(e){return super.defined(e)}optional(){return super.optional()}required(e){return super.required(e)}notRequired(){return super.notRequired()}nullable(){return super.nullable()}nonNullable(e){return super.nonNullable(e)}strip(e){return super.strip(e)}};kM.prototype=BA.prototype;Aue=/^(\d{4}|[+-]\d{6})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:[ T]?(\d{2}):?(\d{2})(?::?(\d{2})(?:[,.](\d{1,}))?)?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?)?)?$/;hue=/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,fue=/^((https?|ftp):)?\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,gue=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,mue="^\\d{4}-\\d{2}-\\d{2}",yue="\\d{2}:\\d{2}:\\d{2}",Eue="(([+-]\\d{2}(:?\\d{2})?)|Z)",Iue=new RegExp(`${mue}T${yue}(\\.\\d+)?${Eue}$`),Cue=t=>Qi(t)||t===t.trim(),bue={}.toString();vA=class extends pr{constructor(){super({type:"string",check(e){return e instanceof String&&(e=e.valueOf()),typeof e=="string"}}),this.withMutation(()=>{this.transform((e,r)=>{if(!this.spec.coerce||this.isType(e)||Array.isArray(e))return e;let n=e!=null&&e.toString?e.toString():e;return n===bue?e:n})})}required(e){return super.required(e).withMutation(r=>r.test({message:e||zo.required,name:"required",skipAbsent:!0,test:n=>!!n.length}))}notRequired(){return super.notRequired().withMutation(e=>(e.tests=e.tests.filter(r=>r.OPTIONS.name!=="required"),e))}length(e,r=Jr.length){return this.test({message:r,name:"length",exclusive:!0,params:{length:e},skipAbsent:!0,test(n){return n.length===this.resolve(e)}})}min(e,r=Jr.min){return this.test({message:r,name:"min",exclusive:!0,params:{min:e},skipAbsent:!0,test(n){return n.length>=this.resolve(e)}})}max(e,r=Jr.max){return this.test({name:"max",exclusive:!0,message:r,params:{max:e},skipAbsent:!0,test(n){return n.length<=this.resolve(e)}})}matches(e,r){let n=!1,i,o;return r&&(typeof r=="object"?{excludeEmptyString:n=!1,message:i,name:o}=r:i=r),this.test({name:o||"matches",message:i||Jr.matches,params:{regex:e},skipAbsent:!0,test:s=>s===""&&n||s.search(e)!==-1})}email(e=Jr.email){return this.matches(hue,{name:"email",message:e,excludeEmptyString:!0})}url(e=Jr.url){return this.matches(fue,{name:"url",message:e,excludeEmptyString:!0})}uuid(e=Jr.uuid){return this.matches(gue,{name:"uuid",message:e,excludeEmptyString:!1})}datetime(e){let r="",n,i;return e&&(typeof e=="object"?{message:r="",allowOffset:n=!1,precision:i=void 0}=e:r=e),this.matches(Iue,{name:"datetime",message:r||Jr.datetime,excludeEmptyString:!0}).test({name:"datetime_offset",message:r||Jr.datetime_offset,params:{allowOffset:n},skipAbsent:!0,test:o=>{if(!o||n)return!0;let s=NS(o);return s?!!s.z:!1}}).test({name:"datetime_precision",message:r||Jr.datetime_precision,params:{precision:i},skipAbsent:!0,test:o=>{if(!o||i==null)return!0;let s=NS(o);return s?s.precision===i:!1}})}ensure(){return this.default("").transform(e=>e===null?"":e)}trim(e=Jr.trim){return this.transform(r=>r!=null?r.trim():r).test({message:e,name:"trim",test:Cue})}lowercase(e=Jr.lowercase){return this.transform(r=>Qi(r)?r:r.toLowerCase()).test({message:e,name:"string_case",exclusive:!0,skipAbsent:!0,test:r=>Qi(r)||r===r.toLowerCase()})}uppercase(e=Jr.uppercase){return this.transform(r=>Qi(r)?r:r.toUpperCase()).test({message:e,name:"string_case",exclusive:!0,skipAbsent:!0,test:r=>Qi(r)||r===r.toUpperCase()})}};RM.prototype=vA.prototype;Sue=t=>t!=+t;QA=class extends pr{constructor(){super({type:"number",check(e){return e instanceof Number&&(e=e.valueOf()),typeof e=="number"&&!Sue(e)}}),this.withMutation(()=>{this.transform((e,r)=>{if(!this.spec.coerce)return e;let n=e;if(typeof n=="string"){if(n=n.replace(/\s/g,""),n==="")return NaN;n=+n}return this.isType(n)||n===null?n:parseFloat(n)})})}min(e,r=ha.min){return this.test({message:r,name:"min",exclusive:!0,params:{min:e},skipAbsent:!0,test(n){return n>=this.resolve(e)}})}max(e,r=ha.max){return this.test({message:r,name:"max",exclusive:!0,params:{max:e},skipAbsent:!0,test(n){return n<=this.resolve(e)}})}lessThan(e,r=ha.lessThan){return this.test({message:r,name:"max",exclusive:!0,params:{less:e},skipAbsent:!0,test(n){return n<this.resolve(e)}})}moreThan(e,r=ha.moreThan){return this.test({message:r,name:"min",exclusive:!0,params:{more:e},skipAbsent:!0,test(n){return n>this.resolve(e)}})}positive(e=ha.positive){return this.moreThan(0,e)}negative(e=ha.negative){return this.lessThan(0,e)}integer(e=ha.integer){return this.test({name:"integer",message:e,skipAbsent:!0,test:r=>Number.isInteger(r)})}truncate(){return this.transform(e=>Qi(e)?e:e|0)}round(e){var r;let n=["ceil","floor","round","trunc"];if(e=((r=e)==null?void 0:r.toLowerCase())||"round",e==="trunc")return this.truncate();if(n.indexOf(e.toLowerCase())===-1)throw new TypeError("Only valid options for round() are: "+n.join(", "));return this.transform(i=>Qi(i)?i:Math[e](i))}};NM.prototype=QA.prototype;OM=new Date(""),wue=t=>Object.prototype.toString.call(t)==="[object Date]";ru=class t extends pr{constructor(){super({type:"date",check(e){return wue(e)&&!isNaN(e.getTime())}}),this.withMutation(()=>{this.transform((e,r)=>!this.spec.coerce||this.isType(e)||e===null?e:(e=pue(e),isNaN(e)?t.INVALID_DATE:new Date(e)))})}prepareParam(e,r){let n;if(Ho.isRef(e))n=e;else{let i=this.cast(e);if(!this._typeCheck(i))throw new TypeError(`\`${r}\` must be a Date or a value that can be \`cast()\` to a Date`);n=i}return n}min(e,r=kS.min){let n=this.prepareParam(e,"min");return this.test({message:r,name:"min",exclusive:!0,params:{min:e},skipAbsent:!0,test(i){return i>=this.resolve(n)}})}max(e,r=kS.max){let n=this.prepareParam(e,"max");return this.test({message:r,name:"max",exclusive:!0,params:{max:e},skipAbsent:!0,test(i){return i<=this.resolve(n)}})}};ru.INVALID_DATE=OM;US.prototype=ru.prototype;US.INVALID_DATE=OM;UM=(t,e,r)=>{if(typeof t!="string")return t;let n=t;try{n=JSON.parse(t)}catch{}return r.isType(n)?n:t};Bue=(t,e)=>{let r=[...(0,ri.normalizePath)(e)];if(r.length===1)return r[0]in t;let n=r.pop(),i=(0,ri.getter)((0,ri.join)(r),!0)(t);return!!(i&&n in i)},yM=t=>Object.prototype.toString.call(t)==="[object Object]";vue=xM([]);TA=class extends pr{constructor(e){super({type:"object",check(r){return yM(r)||typeof r=="function"}}),this.fields=Object.create(null),this._sortErrors=vue,this._nodes=[],this._excludedEdges=[],this.withMutation(()=>{e&&this.shape(e)})}_cast(e,r={}){var n;let i=super._cast(e,r);if(i===void 0)return this.getDefault(r);if(!this._typeCheck(i))return i;let o=this.fields,s=(n=r.stripUnknown)!=null?n:this.spec.noUnknown,a=[].concat(this._nodes,Object.keys(i).filter(d=>!this._nodes.includes(d))),c={},l=Object.assign({},r,{parent:c,__validating:r.__validating||!1}),u=!1;for(let d of a){let A=o[d],p=d in i,h=i[d];if(A){let f;l.path=(r.path?`${r.path}.`:"")+d,A=A.resolve({value:h,context:r.context,parent:c});let E=A instanceof pr?A.spec:void 0,S=E?.strict;if(E!=null&&E.strip){u=u||d in i;continue}f=!r.__validating||!S?A.cast(h,l):h,f!==void 0&&(c[d]=f)}else p&&!s&&(c[d]=h);(p!==d in c||c[d]!==h)&&(u=!0)}return u?c:i}_validate(e,r={},n,i){let{from:o=[],originalValue:s=e,recursive:a=this.spec.recursive}=r;r.from=[{schema:this,value:s},...o],r.__validating=!0,r.originalValue=s,super._validate(e,r,n,(c,l)=>{if(!a||!yM(l)){i(c,l);return}s=s||l;let u=[];for(let d of this._nodes){let A=this.fields[d];!A||Ho.isRef(A)||u.push(A.asNestedTest({options:r,key:d,parent:l,parentPath:r.path,originalParent:s}))}this.runTests({tests:u,value:l,originalValue:s,options:r},n,d=>{i(d.sort(this._sortErrors).concat(c),l)})})}clone(e){let r=super.clone(e);return r.fields=Object.assign({},this.fields),r._nodes=this._nodes,r._excludedEdges=this._excludedEdges,r._sortErrors=this._sortErrors,r}concat(e){let r=super.concat(e),n=r.fields;for(let[i,o]of Object.entries(this.fields)){let s=n[i];n[i]=s===void 0?o:s}return r.withMutation(i=>i.setFields(n,[...this._excludedEdges,...e._excludedEdges]))}_getDefault(e){if("default"in this.spec)return super._getDefault(e);if(!this._nodes.length)return;let r={};return this._nodes.forEach(n=>{var i;let o=this.fields[n],s=e;(i=s)!=null&&i.value&&(s=Object.assign({},s,{parent:s.value,value:s.value[n]})),r[n]=o&&"getDefault"in o?o.getDefault(s):void 0}),r}setFields(e,r){let n=this.clone();return n.fields=e,n._nodes=_ue(e,r),n._sortErrors=xM(Object.keys(e)),r&&(n._excludedEdges=r),n}shape(e,r=[]){return this.clone().withMutation(n=>{let i=n._excludedEdges;return r.length&&(Array.isArray(r[0])||(r=[r]),i=[...n._excludedEdges,...r]),n.setFields(Object.assign(n.fields,e),i)})}partial(){let e={};for(let[r,n]of Object.entries(this.fields))e[r]="optional"in n&&n.optional instanceof Function?n.optional():n;return this.setFields(e)}deepPartial(){return cm(this)}pick(e){let r={};for(let n of e)this.fields[n]&&(r[n]=this.fields[n]);return this.setFields(r,this._excludedEdges.filter(([n,i])=>e.includes(n)&&e.includes(i)))}omit(e){let r=[];for(let n of Object.keys(this.fields))e.includes(n)||r.push(n);return this.pick(r)}from(e,r,n){let i=(0,ri.getter)(e,!0);return this.transform(o=>{if(!o)return o;let s=o;return Bue(o,e)&&(s=Object.assign({},o),n||delete s[e],s[r]=i(o)),s})}json(){return this.transform(UM)}exact(e){return this.test({name:"exact",exclusive:!0,message:e||sm.exact,test(r){if(r==null)return!0;let n=EM(this.schema,r);return n.length===0||this.createError({params:{properties:n.join(", ")}})}})}stripUnknown(){return this.clone({noUnknown:!0})}noUnknown(e=!0,r=sm.noUnknown){typeof e!="boolean"&&(r=e,e=!0);let n=this.test({name:"noUnknown",exclusive:!0,message:r,test(i){if(i==null)return!0;let o=EM(this.schema,i);return!e||o.length===0||this.createError({params:{unknown:o.join(", ")}})}});return n.spec.noUnknown=e,n}unknown(e=!0,r=sm.noUnknown){return this.noUnknown(!e,r)}transformKeys(e){return this.transform(r=>{if(!r)return r;let n={};for(let i of Object.keys(r))n[e(i)]=r[i];return n})}camelCase(){return this.transformKeys(wA.camelCase)}snakeCase(){return this.transformKeys(wA.snakeCase)}constantCase(){return this.transformKeys(e=>(0,wA.snakeCase)(e).toUpperCase())}describe(e){let r=(e?this.resolve(e):this).clone(),n=super.describe(e);n.fields={};for(let[o,s]of Object.entries(r.fields)){var i;let a=e;(i=a)!=null&&i.value&&(a=Object.assign({},a,{parent:a.value,value:a.value[o]})),n.fields[o]=s.describe(a)}return n}};MM.prototype=TA.prototype;DA=class extends pr{constructor(e){super({type:"array",spec:{types:e},check(r){return Array.isArray(r)}}),this.innerType=void 0,this.innerType=e}_cast(e,r){let n=super._cast(e,r);if(!this._typeCheck(n)||!this.innerType)return n;let i=!1,o=n.map((s,a)=>{let c=this.innerType.cast(s,Object.assign({},r,{path:`${r.path||""}[${a}]`,parent:n,originalValue:s,value:s,index:a}));return c!==s&&(i=!0),c});return i?o:n}_validate(e,r={},n,i){var o;let s=this.innerType,a=(o=r.recursive)!=null?o:this.spec.recursive;r.originalValue!=null&&r.originalValue,super._validate(e,r,n,(c,l)=>{var u;if(!a||!s||!this._typeCheck(l)){i(c,l);return}let d=new Array(l.length);for(let p=0;p<l.length;p++){var A;d[p]=s.asNestedTest({options:r,index:p,parent:l,parentPath:r.path,originalParent:(A=r.originalValue)!=null?A:e})}this.runTests({value:l,tests:d,originalValue:(u=r.originalValue)!=null?u:e,options:r},n,p=>i(p.concat(c),l))})}clone(e){let r=super.clone(e);return r.innerType=this.innerType,r}json(){return this.transform(UM)}concat(e){let r=super.concat(e);return r.innerType=this.innerType,e.innerType&&(r.innerType=r.innerType?r.innerType.concat(e.innerType):e.innerType),r}of(e){let r=this.clone();if(!yc(e))throw new TypeError("`array.of()` sub-schema must be a valid yup schema not: "+qo(e));return r.innerType=e,r.spec=Object.assign({},r.spec,{types:e}),r}length(e,r=am.length){return this.test({message:r,name:"length",exclusive:!0,params:{length:e},skipAbsent:!0,test(n){return n.length===this.resolve(e)}})}min(e,r){return r=r||am.min,this.test({message:r,name:"min",exclusive:!0,params:{min:e},skipAbsent:!0,test(n){return n.length>=this.resolve(e)}})}max(e,r){return r=r||am.max,this.test({message:r,name:"max",exclusive:!0,params:{max:e},skipAbsent:!0,test(n){return n.length<=this.resolve(e)}})}ensure(){return this.default(()=>[]).transform((e,r)=>this._typeCheck(e)?e:r==null?[]:[].concat(r))}compact(e){let r=e?(n,i,o)=>!e(n,i,o):n=>!!n;return this.transform(n=>n!=null?n.filter(r):n)}describe(e){let r=(e?this.resolve(e):this).clone(),n=super.describe(e);if(r.innerType){var i;let o=e;(i=o)!=null&&i.value&&(o=Object.assign({},o,{parent:o.value,value:o.value[0]})),n.innerType=r.innerType.describe(o)}return n}};PM.prototype=DA.prototype;kA=class extends pr{constructor(e){super({type:"tuple",spec:{types:e},check(r){let n=this.spec.types;return Array.isArray(r)&&r.length===n.length}}),this.withMutation(()=>{this.typeError(BM.notType)})}_cast(e,r){let{types:n}=this.spec,i=super._cast(e,r);if(!this._typeCheck(i))return i;let o=!1,s=n.map((a,c)=>{let l=a.cast(i[c],Object.assign({},r,{path:`${r.path||""}[${c}]`,parent:i,originalValue:i[c],value:i[c],index:c}));return l!==i[c]&&(o=!0),l});return o?s:i}_validate(e,r={},n,i){let o=this.spec.types;super._validate(e,r,n,(s,a)=>{var c;if(!this._typeCheck(a)){i(s,a);return}let l=[];for(let[d,A]of o.entries()){var u;l[d]=A.asNestedTest({options:r,index:d,parent:a,parentPath:r.path,originalParent:(u=r.originalValue)!=null?u:e})}this.runTests({value:a,tests:l,originalValue:(c=r.originalValue)!=null?c:e,options:r},n,d=>i(d.concat(s),a))})}describe(e){let r=(e?this.resolve(e):this).clone(),n=super.describe(e);return n.innerType=r.spec.types.map((i,o)=>{var s;let a=e;return(s=a)!=null&&s.value&&(a=Object.assign({},a,{parent:a.value,value:a.value[o]})),i.describe(a)}),n}};LM.prototype=kA.prototype;Am=class t{constructor(e){this.type="lazy",this.__isYupSchema__=!0,this.spec=void 0,this._resolve=(r,n={})=>{let i=this.builder(r,n);if(!yc(i))throw new TypeError("lazy() functions must return a valid schema");return this.spec.optional&&(i=i.optional()),i.resolve(n)},this.builder=e,this.spec={meta:void 0,optional:!1}}clone(e){let r=new t(this.builder);return r.spec=Object.assign({},this.spec,e),r}optionality(e){return this.clone({optional:e})}optional(){return this.optionality(!0)}resolve(e){return this._resolve(e.value,e)}cast(e,r){return this._resolve(e,r).cast(e,r)}asNestedTest(e){let{key:r,index:n,parent:i,options:o}=e,s=i[n??r];return this._resolve(s,Object.assign({},o,{value:s,parent:i})).asNestedTest(e)}validate(e,r){return IM(()=>this._resolve(e,r).validate(e,r))}validateSync(e,r){return this._resolve(e,r).validateSync(e,r)}validateAt(e,r,n){return IM(()=>this._resolve(r,n).validateAt(e,r,n))}validateSyncAt(e,r,n){return this._resolve(r,n).validateSyncAt(e,r,n)}isValid(e,r){try{return this._resolve(e,r).isValid(e,r)}catch(n){if(sr.isError(n))return Promise.resolve(!1);throw n}}isValidSync(e,r){return this._resolve(e,r).isValidSync(e,r)}describe(e){return e?this.resolve(e).describe(e):{type:"lazy",meta:this.spec.meta,label:void 0}}meta(...e){if(e.length===0)return this.spec.meta;let r=this.clone();return r.spec.meta=Object.assign(r.spec.meta||{},e[0]),r}get"~standard"(){let e=this;return{version:1,vendor:"yup",async validate(n){try{return{value:await e.validate(n,{abortEarly:!1})}}catch(i){if(sr.isError(i))return{issues:xS(i)};throw i}}}}}});var $M=y(LS=>{"use strict";Object.defineProperty(LS,"__esModule",{value:!0});LS.default=[{name:"npm-node-cron",preset:{presetId:"npm-node-cron",useSeconds:!0,useYears:!1,useAliases:!0,useBlankDay:!1,allowOnlyOneBlankDayField:!1,mustHaveBlankDayField:!1,useLastDayOfMonth:!1,useLastDayOfWeek:!1,useNearestWeekday:!1,useNthWeekdayOfMonth:!1,seconds:{minValue:0,maxValue:59},minutes:{minValue:0,maxValue:59},hours:{minValue:0,maxValue:23},daysOfMonth:{minValue:1,maxValue:31},months:{minValue:0,maxValue:11},daysOfWeek:{minValue:0,maxValue:6},years:{minValue:1970,maxValue:2099}}},{name:"aws-cloud-watch",preset:{presetId:"aws-cloud-watch",useSeconds:!1,useYears:!0,useAliases:!0,useBlankDay:!0,allowOnlyOneBlankDayField:!0,mustHaveBlankDayField:!0,useLastDayOfMonth:!0,useLastDayOfWeek:!0,useNearestWeekday:!0,useNthWeekdayOfMonth:!0,seconds:{minValue:0,maxValue:59},minutes:{minValue:0,maxValue:59},hours:{minValue:0,maxValue:23},daysOfMonth:{minValue:1,maxValue:31},months:{minValue:1,maxValue:12},daysOfWeek:{minValue:1,maxValue:7},years:{minValue:1970,maxValue:2199}}},{name:"npm-cron-schedule",preset:{presetId:"npm-cron-schedule",useSeconds:!0,useYears:!1,useAliases:!0,useBlankDay:!1,allowOnlyOneBlankDayField:!1,mustHaveBlankDayField:!1,useLastDayOfMonth:!1,useLastDayOfWeek:!1,useNearestWeekday:!1,useNthWeekdayOfMonth:!1,seconds:{minValue:0,maxValue:59},minutes:{minValue:0,maxValue:59},hours:{minValue:0,maxValue:23},daysOfMonth:{minValue:1,maxValue:31},months:{minValue:1,maxValue:12},daysOfWeek:{minValue:0,maxValue:7},years:{minValue:1970,maxValue:2099}}}]});var qM=y(ar=>{"use strict";var kue=ar&&ar.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Rue=ar&&ar.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Nue=ar&&ar.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&kue(e,t,r);return Rue(e,t),e},Oue=ar&&ar.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ar,"__esModule",{value:!0});ar.validateOptions=ar.registerOptionPreset=ar.getOptionPresets=ar.getOptionPreset=void 0;var J=Nue((PS(),DC(MS)));PS();var nu=Bi(),FM=Oue($M());vi();var Ec={default:{presetId:"default",useSeconds:!1,useYears:!1,useAliases:!1,useBlankDay:!1,allowOnlyOneBlankDayField:!1,allowStepping:!0,mustHaveBlankDayField:!1,useLastDayOfMonth:!1,useLastDayOfWeek:!1,useNearestWeekday:!1,useNthWeekdayOfMonth:!1,seconds:{minValue:0,maxValue:59},minutes:{minValue:0,maxValue:59},hours:{minValue:0,maxValue:23},daysOfMonth:{minValue:0,maxValue:31},months:{minValue:0,maxValue:12},daysOfWeek:{minValue:0,maxValue:7},years:{minValue:1970,maxValue:2099}}},zM=J.object({presetId:J.string().required(),useSeconds:J.boolean().required(),useYears:J.boolean().required(),useAliases:J.boolean(),useBlankDay:J.boolean().required(),allowOnlyOneBlankDayField:J.boolean().required(),allowStepping:J.boolean(),mustHaveBlankDayField:J.boolean(),useLastDayOfMonth:J.boolean(),useLastDayOfWeek:J.boolean(),useNearestWeekday:J.boolean(),useNthWeekdayOfMonth:J.boolean(),seconds:J.object({minValue:J.number().min(0).required(),maxValue:J.number().min(0).required(),lowerLimit:J.number().min(0),upperLimit:J.number().min(0)}).required(),minutes:J.object({minValue:J.number().min(0).required(),maxValue:J.number().min(0).required(),lowerLimit:J.number().min(0),upperLimit:J.number().min(0)}).required(),hours:J.object({minValue:J.number().min(0).required(),maxValue:J.number().min(0).required(),lowerLimit:J.number().min(0),upperLimit:J.number().min(0)}).required(),daysOfMonth:J.object({minValue:J.number().min(0).required(),maxValue:J.number().min(0).required(),lowerLimit:J.number().min(0),upperLimit:J.number().min(0)}).required(),months:J.object({minValue:J.number().min(0).required(),maxValue:J.number().min(0).required(),lowerLimit:J.number().min(0),upperLimit:J.number().min(0)}).required(),daysOfWeek:J.object({minValue:J.number().min(0).required(),maxValue:J.number().min(0).required(),lowerLimit:J.number().min(0),upperLimit:J.number().min(0)}).required(),years:J.object({minValue:J.number().min(0).required(),maxValue:J.number().min(0).required(),lowerLimit:J.number().min(0),upperLimit:J.number().min(0)}).required()}).required(),xue=t=>Ec[t]?(0,nu.valid)(Ec[t]):(0,nu.err)(`Option preset '${t}' not found.`);ar.getOptionPreset=xue;var Uue=()=>Ec;ar.getOptionPresets=Uue;var Mue=(t,e)=>{Ec[t]=zM.validateSync(e,{strict:!1,abortEarly:!1,stripUnknown:!0,recursive:!0})};ar.registerOptionPreset=Mue;function Pue(){for(let t=0;t<FM.default.length;t+=1){let{name:e,preset:r}=FM.default[t];(0,ar.registerOptionPreset)(e,r)}}Pue();var jM=new Map;function Lue(t,e){var r;return t+((r=JSON.stringify(e))!==null&&r!==void 0?r:"")}function $ue(t){return J.object({presetId:J.string().required(),preset:zM.required(),useSeconds:J.boolean().required(),useYears:J.boolean().required(),useAliases:J.boolean(),useBlankDay:J.boolean().required(),allowOnlyOneBlankDayField:J.boolean().required(),allowStepping:J.boolean(),mustHaveBlankDayField:J.boolean(),useLastDayOfMonth:J.boolean(),useLastDayOfWeek:J.boolean(),useNearestWeekday:J.boolean(),useNthWeekdayOfMonth:J.boolean(),seconds:J.object({lowerLimit:J.number().min(t.seconds.minValue).max(t.seconds.maxValue),upperLimit:J.number().min(t.seconds.minValue).max(t.seconds.maxValue)}).required(),minutes:J.object({lowerLimit:J.number().min(t.minutes.minValue).max(t.minutes.maxValue),upperLimit:J.number().min(t.minutes.minValue).max(t.minutes.maxValue)}).required(),hours:J.object({lowerLimit:J.number().min(t.hours.minValue).max(t.hours.maxValue),upperLimit:J.number().min(t.hours.minValue).max(t.hours.maxValue)}).required(),daysOfMonth:J.object({lowerLimit:J.number().min(t.daysOfMonth.minValue).max(t.daysOfMonth.maxValue),upperLimit:J.number().min(t.daysOfMonth.minValue).max(t.daysOfMonth.maxValue)}).required(),months:J.object({lowerLimit:J.number().min(t.months.minValue).max(t.months.maxValue),upperLimit:J.number().min(t.months.minValue).max(t.months.maxValue)}).required(),daysOfWeek:J.object({lowerLimit:J.number().min(t.daysOfWeek.minValue).max(t.daysOfWeek.maxValue),upperLimit:J.number().min(t.daysOfWeek.minValue).max(t.daysOfWeek.maxValue)}).required(),years:J.object({lowerLimit:J.number().min(t.years.minValue).max(t.years.maxValue),upperLimit:J.number().min(t.years.minValue).max(t.years.maxValue)}).required()}).required()}function Fue(t,e){var r,n,i,o,s,a,c,l,u,d,A,p,h,f,E,S,B,_,v,T,L;let k=Object.assign(Object.assign({presetId:t.presetId,preset:t},{useSeconds:t.useSeconds,useYears:t.useYears,useAliases:(r=t.useAliases)!==null&&r!==void 0?r:!1,useBlankDay:t.useBlankDay,allowOnlyOneBlankDayField:t.allowOnlyOneBlankDayField,allowStepping:(n=t.allowStepping)!==null&&n!==void 0?n:!0,mustHaveBlankDayField:(i=t.mustHaveBlankDayField)!==null&&i!==void 0?i:!1,useLastDayOfMonth:(o=t.useLastDayOfMonth)!==null&&o!==void 0?o:!1,useLastDayOfWeek:(s=t.useLastDayOfWeek)!==null&&s!==void 0?s:!1,useNearestWeekday:(a=t.useNearestWeekday)!==null&&a!==void 0?a:!1,useNthWeekdayOfMonth:(c=t.useNthWeekdayOfMonth)!==null&&c!==void 0?c:!1,seconds:{lowerLimit:(l=t.seconds.lowerLimit)!==null&&l!==void 0?l:t.seconds.minValue,upperLimit:(u=t.seconds.upperLimit)!==null&&u!==void 0?u:t.seconds.maxValue},minutes:{lowerLimit:(d=t.minutes.lowerLimit)!==null&&d!==void 0?d:t.minutes.minValue,upperLimit:(A=t.minutes.upperLimit)!==null&&A!==void 0?A:t.minutes.maxValue},hours:{lowerLimit:(p=t.hours.lowerLimit)!==null&&p!==void 0?p:t.hours.minValue,upperLimit:(h=t.hours.upperLimit)!==null&&h!==void 0?h:t.hours.maxValue},daysOfMonth:{lowerLimit:(f=t.daysOfMonth.lowerLimit)!==null&&f!==void 0?f:t.daysOfMonth.minValue,upperLimit:(E=t.daysOfMonth.upperLimit)!==null&&E!==void 0?E:t.daysOfMonth.maxValue},months:{lowerLimit:(S=t.months.lowerLimit)!==null&&S!==void 0?S:t.months.minValue,upperLimit:(B=t.months.upperLimit)!==null&&B!==void 0?B:t.months.maxValue},daysOfWeek:{lowerLimit:(_=t.daysOfWeek.lowerLimit)!==null&&_!==void 0?_:t.daysOfWeek.minValue,upperLimit:(v=t.daysOfWeek.upperLimit)!==null&&v!==void 0?v:t.daysOfWeek.maxValue},years:{lowerLimit:(T=t.years.lowerLimit)!==null&&T!==void 0?T:t.years.minValue,upperLimit:(L=t.years.upperLimit)!==null&&L!==void 0?L:t.years.maxValue}}),e);return $ue(t).validateSync(k,{strict:!1,abortEarly:!1,stripUnknown:!0,recursive:!0})}var jue=t=>{try{let e;if(t.preset)if(typeof t.preset=="string"){if(!Ec[t.preset])return(0,nu.err)([`Option preset ${t.preset} does not exist.`]);e=Ec[t.preset]}else e=t.preset;else e=Ec.default;let r=Lue(e.presetId,t.override),n=jM.get(r);if(n)return(0,nu.valid)(n);let i=Fue(e,t.override);return jM.set(r,i),(0,nu.valid)(i)}catch(e){return(0,nu.err)(e.errors)}};ar.validateOptions=jue});var jo=y(RA=>{"use strict";var Cc=RA&&RA.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(RA,"__esModule",{value:!0});var Ic=Bi(),zue=Cc(KU()),que=Cc(XU()),Hue=Cc(eM()),Gue=Cc(tM()),Yue=Cc(rM()),Vue=Cc(nM()),Wue=Cc(iM()),Jue=qM();vi();var Zue=(t,e)=>{let r=t.trim().split(" ");if(e.useSeconds&&e.useYears&&r.length!==7)return(0,Ic.err)(`Expected 7 values, but got ${r.length}.`);if((e.useSeconds&&!e.useYears||e.useYears&&!e.useSeconds)&&r.length!==6)return(0,Ic.err)(`Expected 6 values, but got ${r.length}.`);if(!e.useSeconds&&!e.useYears&&r.length!==5)return(0,Ic.err)(`Expected 5 values, but got ${r.length}.`);let n={seconds:e.useSeconds?r[0]:void 0,minutes:r[e.useSeconds?1:0],hours:r[e.useSeconds?2:1],daysOfMonth:r[e.useSeconds?3:2],months:r[e.useSeconds?4:3],daysOfWeek:r[e.useSeconds?5:4],years:e.useYears?r[e.useSeconds?6:5]:void 0};return(0,Ic.valid)(n)},Kue=(t,e={})=>{let r=(0,Jue.validateOptions)(e);if(r.isError())return r;let n=r.getValue(),i=Zue(t,n);if(i.isError())return(0,Ic.err)([`${i.getError()} (Input cron: '${t}')`]);let o=i.getValue(),s=[];if(n.useSeconds&&s.push((0,zue.default)(o,n)),s.push((0,que.default)(o,n)),s.push((0,Hue.default)(o,n)),s.push((0,Gue.default)(o,n)),s.push((0,Yue.default)(o,n)),s.push((0,Vue.default)(o,n)),n.useYears&&s.push((0,Wue.default)(o,n)),s.every(c=>c.isValid()))return(0,Ic.valid)(o);let a=[];return s.forEach(c=>{c.isError()&&c.getError().forEach(l=>{a.push(l)})}),a.forEach((c,l)=>{a[l]=`${c} (Input cron: '${t}')`}),(0,Ic.err)(a)};RA.default=Kue});var NA=y(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.parseUTCDate=pm;xr.requireUTCDate=HM;xr.toUTCISOString=GM;xr.toOptionalUTCISOString=sde;xr.utcNow=YM;xr.utcNowISOString=ade;xr.getUTCTimestampMs=VM;xr.parsePersistedTimestamp=hm;xr.getPersistedTimestampMs=cde;xr.formatPersistedTimestamp=WM;xr.formatCompactPersistedTimestamp=lde;xr.formatPersistedDate=JM;xr.formatRelativePersistedTimestamp=ude;var Xue=/(Z|[+-]\d{2}(?::?\d{2})?)$/i,ede=/^\d{4}-\d{2}-\d{2}$/,tde=/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}/,rde={year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"},nde={month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"},ide={year:"numeric",month:"short",day:"numeric"};function ode(t){let e=t.trim();return e&&(ede.test(e)?`${e}T00:00:00.000Z`:Xue.test(e)?e:tde.test(e)?`${e.replace(" ","T")}Z`:e)}function pm(t){if(t==null||t==="")return;let e=typeof t=="string"?ode(t):t instanceof Date||typeof t=="number"&&Number.isFinite(t)?t:void 0;if(e===void 0)return;let r=new Date(e);return Number.isNaN(r.getTime())?void 0:r}function HM(t,e="timestamp"){let r=pm(t);if(!r)throw new Error(`Invalid ${e}`);return r}function GM(t,e="timestamp"){return HM(t,e).toISOString()}function sde(t,e="timestamp"){if(!(t==null||t===""))return GM(t,e)}function YM(){return new Date}function ade(){return YM().toISOString()}function VM(t){let e=pm(t);return e?e.getTime():Number.NEGATIVE_INFINITY}function hm(t){return pm(t)}function cde(t){return VM(t)}function WM(t,e=rde,r="-"){let n=hm(t);return n?n.toLocaleString(void 0,e):r}function lde(t,e="-"){return WM(t,nde,e)}function JM(t,e="-"){let r=hm(t);return r?r.toLocaleDateString(void 0,ide):e}function ude(t,e=""){let r=hm(t);if(!r)return e;let n=Date.now()-r.getTime(),i=Math.floor(n/6e4);if(i<1)return"just now";if(i<60)return`${i}m ago`;let o=Math.floor(i/60);if(o<24)return`${o}h ago`;let s=Math.floor(o/24);return s<30?`${s}d ago`:JM(r,e)}});var KM=y(iu=>{"use strict";var dde=iu&&iu.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(iu,"__esModule",{value:!0});iu.calculateNextRun=hde;iu.validateCronExpression=fde;var Ade=WU(),pde=dde(jo()),ZM=NA();function hde(t,e,r){let n=r||(0,ZM.utcNow)(),o=Ade.CronExpressionParser.parse(t,{currentDate:n,tz:e}).next().toDate();return(0,ZM.parseUTCDate)(o.toISOString())||o}function fde(t){try{return(0,pde.default)(t,{preset:"default",override:{useSeconds:!1,useYears:!1,useAliases:!1,allowStepping:!0,useLastDayOfMonth:!1,useLastDayOfWeek:!1,useNearestWeekday:!1}}).isValid()}catch{return!1}}});var OA=y(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});bc.DEFAULT_TIMEZONE=void 0;bc.isValidTimezone=XM;bc.getRuntimeTimezone=gde;bc.DEFAULT_TIMEZONE="UTC";function XM(t){try{return new Intl.DateTimeFormat("en-US",{timeZone:t}),!0}catch{return!1}}function gde(){let t=Intl.DateTimeFormat().resolvedOptions().timeZone;return t&&XM(t)?t:bc.DEFAULT_TIMEZONE}});var eP=y($S=>{"use strict";Object.defineProperty($S,"__esModule",{value:!0});$S.getConfiguredModelContextLength=yde;var mde=2e5;function yde(){return mde}});var tP=y(FS=>{"use strict";Object.defineProperty(FS,"__esModule",{value:!0});FS.getModelOutputTokenLimit=Ide;var Ede={"claude-fable-5":128e3,"claude-mythos-5":128e3,"claude-opus-5":128e3,"claude-sonnet-5":128e3,"claude-opus-4-8":128e3,"claude-opus-4-7":128e3,"claude-opus-4-6":128e3,"claude-sonnet-4-6":64e3,"claude-haiku-4-5":64e3,"claude-opus-4-5":64e3,"claude-sonnet-4-5":64e3,"gpt-6.1-sol":128e3,"gpt-5":128e3,"gpt-4.1":32768,"gpt-4o":16384,"gemini-2.5-flash":65536,"gemini-2.5-pro":65536};function Ide(t){let e=t.model.toLowerCase();return Object.entries(Ede).find(([n])=>e.includes(n))?.[1]}});var Ti=y(M=>{"use strict";var Cde=M&&M.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),ym=M&&M.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Cde(e,t,r)},bde=M&&M.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(M,"__esModule",{value:!0});M.MAX_OBJECT_PREVIEW_KEYS=M.MAX_TRUNCATION_DEPTH=M.MAX_ARRAY_PREVIEW_ITEMS=M.MAX_STRING_PREVIEW_LENGTH=M.MAX_INLINE_RESULT_PREVIEW_BYTES=M.FULLY_MASKED_CREDENTIAL_VALUE=M.maskCredentialValue=M.isSensitiveCredentialKey=M.CREDENTIAL_KEY_VALIDATION_DESCRIPTION=M.CREDENTIAL_KEY_PATTERN=M.ALLOWED_FILE_EXTENSIONS=void 0;M.mapPlaybookToDraftConfig=Bde;M.mapPlaybookDraftToInput=vde;M.inferProtocolFromUrl=oP;M.getSuiteCloudOperation=sP;M.isNetSuiteRestletUrl=aP;M.isSuiteCloudWrite=Tde;M.isAbortError=Dde;M.getToolInputSchemaSections=Nde;M.buildToolInputSchemaSections=xde;M.flattenAndNamespaceCredentials=Mde;M.flattenAndNamespaceSystemUrls=Pde;M.slugify=Lde;M.generateUniqueId=$de;M.resolveOAuthCertAndKey=Fde;M.isArrowFunction=lP;M.assertValidArrowFunction=jde;M.normalizeCredentialKey=uP;M.isValidCredentialKey=dP;M.getCredentialKeyValidationError=AP;M.getInvalidCredentialKeyNames=qde;M.hasCredentialValue=pP;M.hasCredentialKeyValue=Yde;M.getCredentialKeyMetadata=Vde;M.isFullyMaskedCredentialValue=hP;M.maskCredentialSetValues=Wde;M.restoreMaskedCredentialValues=Jde;M.isMaskedValue=Zde;M.maskCredentials=fP;M.buildSensitiveCredentialMap=Kde;M.redactKnownCredentialValues=zS;M.estimateDataSize=rAe;M.truncateValue=fm;M.sampleResultObject=gP;M.safeStringify=qS;M.coerceDate=gm;M.normalizeToolCallDates=mP;M.normalizeMessageDates=HS;M.cloneMessagesWithDates=nAe;M.applyAgentCompactionToMessages=iAe;M.redactUrlCredentials=oAe;M.getToolVisuals=GS;M.getReplacedVisualIds=yP;M.getMessageVisuals=EP;M.getMessageContent=IP;M.getMessageToolCalls=YS;M.hasMessageText=bP;M.hasAssistantOutput=SP;M.isEmptyAssistantMessage=VS;M.isRenderableAgentMessage=aAe;M.pruneEmptyAssistantMessages=cAe;M.getMeaningfulMessages=lAe;M.truncateForLLM=uAe;M.truncateHeadTail=dAe;M.getErrorMessage=AAe;M.pickReferencedExecutionFiles=pAe;M.normalizeToolDiff=wP;M.normalizeToolDiffs=hAe;M.composeUrl=fAe;M.truncateRunResult=yAe;M.getToolSystemIds=EAe;M.getCredentialPlaceholderKeysForSystem=CAe;M.getUnscopedCallPlaceholderError=wAe;M.formatLabel=_Ae;var iP=pg(),Sde=RC(),wde=pn(),_de=bde((ax(),DC(sx)));ym(KM(),M);ym(OA(),M);ym(eP(),M);ym(tP(),M);function Bde(t){return{name:t.name,whenToRun:t.whenToRun,instructions:t.instructions}}function vde(t){return{name:t.name,whenToRun:t.whenToRun,instructions:t.instructions}}function oP(t){return t.startsWith("postgres://")||t.startsWith("postgresql://")?"postgres":t.startsWith("mssql://")||t.startsWith("sqlserver://")?"mssql":t.startsWith("redis://")||t.startsWith("rediss://")?"redis":t.startsWith("mongodb://")||t.startsWith("mongodb+srv://")?"mongodb":t.startsWith("ftp://")||t.startsWith("ftps://")||t.startsWith("sftp://")?"sftp":t.startsWith("smb://")?"smb":t.startsWith("odbc://")?"odbc":t.startsWith("script://")?"script":t.startsWith("suitecloud://")?"suitecloud":"http"}var rP=new Set(["listObjects","importObjects","listFiles","importFiles","validate","preview"]);function sP(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch{return}let r=e&&typeof e=="object"?e.operation:void 0;return typeof r=="string"?r:void 0}var Qde=new Set(["deploy","callRestlet","cleanupScripts"]);function jS(t){let e=typeof t=="string"?t:JSON.stringify(t??"");return e.includes("<<")||e.includes("{{")}var nP=/^https?:\/\/[^/?#]*\.restlets\.api\.netsuite\.com(?:[:/?#]|$)|\/app\/site\/hosting\/restlet\.nl/i;function aP(t){if(nP.test(t.trim()))return!0;let e;try{e=new URL(t.trim())}catch{return!1}let r=e.pathname;try{r=decodeURIComponent(r)}catch{}return nP.test(`${e.protocol}//${e.hostname.replace(/\.$/,"")}${r.replace(/\/{2,}/g,"/")}`)}function Tde({url:t,body:e}){if(typeof t!="string")return!1;if(aP(t))return!0;let r=sP(e);return oP(t)!=="suitecloud"?jS(t)&&r!==void 0&&(jS(r)||rP.has(r)||Qde.has(r)):jS(e)?!0:r===void 0||!rP.has(r)}function Dde(t){return t?typeof t=="string"?t.startsWith("AbortError:"):t instanceof DOMException?t.name==="AbortError":t instanceof Error?t.name==="AbortError"||t.message.startsWith("AbortError:"):!1:!1}M.ALLOWED_FILE_EXTENSIONS=[".json",".csv",".txt",".xml",".xlsx",".xls",".pdf",".docx",".pptx",".zip",".gz",".yaml",".yml",".py",".ts",".tsx",".js",".jsx",".java",".go",".rs",".rb",".php",".c",".cpp",".h",".hpp",".cs",".swift",".kt",".scala",".sh",".bash",".sql",".html",".css",".scss",".md",".rst"];function kde(t){if(!t)return null;if(typeof t=="string")try{return JSON.parse(t)}catch{return null}return t}function cP(t){return structuredClone(t)}function Rde(t,e){if(!t||typeof t!="object")return t;let r=cP(t),n=r&&typeof r=="object"&&r.properties&&typeof r.properties=="object"?r.properties:void 0;if(!n)return r;let i=!1;for(let a of e)a in n&&(delete n[a],i=!0);if(!i)return r;if(Array.isArray(r.required)){let a=r.required.filter(c=>!e.includes(c));a.length>0?r.required=a:delete r.required}Object.keys(n).length===0&&delete r.properties;let o=r.properties&&typeof r.properties=="object"?Object.keys(r.properties):[],s=Array.isArray(r.allOf)&&r.allOf.length>0||Array.isArray(r.anyOf)&&r.anyOf.length>0||Array.isArray(r.oneOf)&&r.oneOf.length>0||!!r.patternProperties||!!r.additionalProperties;return o.length===0&&!s?null:r}function Nde(t){let e=kde(t),r=e&&typeof e=="object"&&e.properties?e.properties:void 0,n=r&&typeof r=="object"?Object.keys(r):[],i=!!(r?.payload&&r?.credentials&&n.every(o=>["payload","credentials"].includes(o)));return e?i?{rawSchema:e,payloadSchema:r?.payload||null,filesSchema:null,credentialsSchema:r?.credentials||null,hasNestedSections:!0}:{rawSchema:e,payloadSchema:Rde(e,["__files"]),filesSchema:r?.__files||null,credentialsSchema:null,hasNestedSections:!1}:{rawSchema:null,payloadSchema:null,filesSchema:null,credentialsSchema:null,hasNestedSections:!1}}function Ode(t){return!!(t&&typeof t=="object"&&Array.isArray(t.required)&&t.required.length>0)}function xde({payloadSchema:t,filesSchema:e}){if(!!!e)return t||void 0;let n=t&&typeof t=="object"?cP(t):{type:"object",properties:{}},i=n.properties&&typeof n.properties=="object"?{...n.properties}:{};i.__files=e,n.type=n.type||"object",n.properties=i;let o=Array.isArray(n.required)?n.required.filter(s=>s!=="__files"):[];return Ode(e)&&o.push("__files"),o.length>0?n.required=Array.from(new Set(o)):delete n.required,n}var Ude=t=>t!=null&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Date);function Mde(t){return t.reduce((e,r)=>(Object.entries(r.credentials||{}).forEach(([n,i])=>{e[`${r.id}_${n}`]=i}),e),{})}function Pde(t){return t.reduce((e,r)=>(r.url&&(e[`${r.id}_url`]=r.url),e),{})}function Lde(t){return t.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"system"}async function $de({baseId:t,exists:e}){if(!await e(t))return t;let r=1,n=t.match(/(.*)-(\d+)$/),i=t;for(n&&(i=n[1],r=parseInt(n[2],10)+1);;){let o=`${i}-${r}`;if(!await e(o))return o;r++}}function Fde(t,e){let r=null,n=null;try{t&&e&&(r=JSON.parse(t),n=JSON.parse(e))}catch{return{cert:{content:void 0,filename:void 0},key:{content:void 0,filename:void 0}}}return{cert:r,key:n}}function lP(t){let e=(t||"").trim();return e?/^\s*(async\s+)?(\([^)]*\)|[a-zA-Z_$][a-zA-Z0-9_$]*)\s*=>/.test(e):!1}function jde(t){let e=(t||"").trim();if(!e)return`(sourceData) => {
|
|
106
106
|
return {};
|
|
107
107
|
}`;if(e==="$")return`(sourceData) => {
|
|
108
108
|
return sourceData;
|
|
@@ -110,7 +110,7 @@ attempted value: ${s}
|
|
|
110
110
|
|
|
111
111
|
`)}function YS(t){return(t.parts||[]).flatMap(e=>e.type==="tool"&&e.tool?[e.tool]:[])}function bP(t){return CP(t)!==""}function SP(t){return bP(t)?!0:YS(t).length>0}function VS(t){return t.role==="assistant"&&!t.isStreaming&&!SP(t)}function aAe(t){return t.role==="system"||t.isHidden?!1:!VS(t)}function cAe(t){return t.filter(e=>!VS(e))}function lAe(t){return t.filter(e=>{let r=IP(e),n=YS(e).length>0;return(r||n)&&!(e.id==="1"&&!r)})}function uAe(t,e=5e3,r=10){if(t==null)return"null";if(typeof t=="string")return t.length<=e?t:t.slice(0,e)+"... [truncated]";let n=qS(t);if(n.length<=e)return n;let i=gP(t,r),o=qS(i);return o.length<=e?o:o.slice(0,e)+"... [truncated]"}function dAe(t,e){if(t.length<=e)return t;let r=Math.ceil(e/2),n=Math.floor(e/2),i=t.length-r-n;return`${t.slice(0,r)}
|
|
112
112
|
... [${i} characters omitted] ...
|
|
113
|
-
${t.slice(t.length-n)}`}function AAe(t){return t instanceof Error?t.message:typeof t=="string"?t:typeof t=="object"&&t!==null&&"message"in t?String(t.message):String(t)}function pAe(t,e){if(!e||Object.keys(e).length===0)return{};let r=/file::([^,\s)}\]"']+)/g,n=typeof t=="string"?t:JSON.stringify(t||{}),i=[...new Set([...n.matchAll(r)].map(o=>{let s=o[1];return s.endsWith(".raw")?s=s.slice(0,-4):s.endsWith(".base64")?s=s.slice(0,-7):s.endsWith(".extracted")&&(s=s.slice(0,-10)),s}))];return Object.fromEntries(i.flatMap(o=>e[o]?[[o,e[o]]]:[]))}function wP(t){if(t.op==="remove"||t.value===void 0||typeof t.value!="string")return t;if(t.path==="/inputSchema"||t.path==="/outputSchema"||t.path.startsWith("/inputSchema/properties/")||t.path.startsWith("/outputSchema/properties/")||t.path.match(/^\/steps\/\d+\/config\/pagination$/)||t.path.match(/^\/steps\/\d+\/config\/headers$/)||t.path.match(/^\/steps\/\d+\/config\/queryParams$/))try{return{...t,value:JSON.parse(t.value)}}catch{return t}return t}function hAe(t){return t.map(e=>wP(e))}function fAe(t,e){t||(t=""),e||(e=""),/^(https?|postgres(ql)?|ftp(s)?|sftp|smb|file):\/\//i.test(t)||(t=`https://${t}`);let r=t.endsWith("/")?t.slice(0,-1):t,n=e.startsWith("/")?e.slice(1):e;return`${r}/${n}`}var gAe=new Set(["data","stepResults","toolPayload","rawData","transformedData"]),mAe=8e4;function yAe(t,e=mAe){if(t==null)return t;let r=t;if(typeof t=="string"){if(t.length<=e)return t;try{r=JSON.parse(t)}catch{return{_truncated:!0,_message:"String result too large to parse",_size:t.length}}}if(typeof r!="object")return r;let n=0,i=0,o=(s,a=0)=>{if(a>20||s===null||typeof s!="object")return s;if(Array.isArray(s))return s.map(l=>o(l,a+1));let c={};for(let[l,u]of Object.entries(s))if(gAe.has(l)&&u!==null&&typeof u=="object"){let d=JSON.stringify(u);if(d.length>e){i+=d.length;try{let{jsonString:A,truncatedProps:p}=(0,_de.default)(d,e);c[l]=JSON.parse(A),n+=p.length}catch{c[l]=u}}else c[l]=u}else c[l]=o(u,a+1);return c};try{if(JSON.stringify(r).length<=e)return r;let a=o(r);return n>0&&typeof a=="object"&&a!==null&&(a._note=`Result truncated: ${n} items omitted (original ${i} characters)`),a}catch{return{_truncated:!0,_message:"Result too large to display"}}}function EAe(t){if(!t.steps)return[];let e=new Set;for(let r of t.steps)r.config&&(0,wde.isRequestConfig)(r.config)&&r.config.systemId&&e.add(r.config.systemId);return Array.from(e)}function mm(t,e,r=new WeakSet){if(typeof t=="string"){e.push(t);return}if(!(!t||typeof t!="object")&&!r.has(t)){if(r.add(t),Array.isArray(t)){for(let n of t)mm(n,e,r);return}for(let n of Object.values(t))mm(n,e,r)}}function IAe(t){let e=[];for(let r of t.matchAll(/<<([\s\S]*?)>>/g)){let n=r[1].trim();n&&e.push(n)}for(let r of t.matchAll(/{{\s*([^{}\s]+)\s*}}/g)){let n=r[1].trim();n&&e.push(n)}return e}function CAe(t,e){let r=[];mm(t,r);let n=`${e}_`,i=new Set;for(let o of r)for(let s of IAe(o)){if(!s.startsWith(n))continue;let a=s.slice(n.length);!a||a==="url"||!M.CREDENTIAL_KEY_PATTERN.test(a)||i.add(a)}return[...i]}var bAe=/^\s*(async\s+)?(\([^)]*\)|[a-zA-Z_$][a-zA-Z0-9_$]*)\s*=>/,SAe=new Set(["sg_auth_email","sg_auth_jwt"]);function wAe({config:t,systemId:e}){let r=[];mm(t,r);let n=e?`${e}_`:null,i=new Set;for(let l of r)for(let u of l.matchAll(/<<([\s\S]*?)>>/g)){let d=u[1].trim();d&&(n&&d.startsWith(n)||bAe.test(d)||SAe.has(d)||i.add(d))}if(i.size===0)return null;let o=[...i].map(l=>`<<${l}>>`).join(", "),s=`Unresolved placeholder${i.size===1?"":"s"} ${o}`;if(!n)return`${s}. Secret placeholders need systemId and the form <<systemId_secretName>>. Nothing was sent.`;let a=[...i].filter(l=>M.CREDENTIAL_KEY_PATTERN.test(l)).map(l=>`<<${n}${l}>>`),c=a.length>0?`Secret placeholders are namespaced by system: use ${a.join(", ")}.`:`Secret placeholders are namespaced by system as <<${n}secretName>>.`;return`${s}. ${c} Nothing was sent.`}function _Ae(t){return t.replace(/([a-z])([A-Z])|([A-Z]{2,})([A-Z][a-z])/g,"$1$3 $2$4").replace(/[_-]/g," ").replace(/\b\w/g,e=>e.toUpperCase()).replace(/\b(Id|Url|Api|Ui)\b/g,e=>e.toUpperCase())}});var TP=y(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.AGENT_CONTEXT_MEMORY_MESSAGE_ID_PREFIX=void 0;Mt.applyToolMutation=_P;Mt.mutateToolCallInMessages=vAe;Mt.buildStreamingAssistantMessage=BP;Mt.parseToolOutput=vP;Mt.parseAgentStreamEventLine=TAe;Mt.stopActiveTool=QP;Mt.appendContentToMessage=WS;Mt.updateMessageWithData=au;Mt.findAwaitingConfirmationToolCallIds=DAe;Mt.declineAwaitingConfirmationTools=kAe;Mt.findAndResumeMessageWithTool=RAe;Mt.serializeMessageForPersistence=OAe;Mt.isTurnContextBlockMessage=JS;Mt.normalizeAgentSessionForkMessages=UAe;Mt.normalizeAgentSessionImportMessages=MAe;Mt.createAgentTranscriptState=PAe;Mt.applyAgentStreamChunk=LAe;var BAe=pn(),Im=Ti();function _P(t,e){let r=e.frontendOutput!==void 0?e.frontendOutput:t.frontendOutput;return{...t,...e.input!==void 0?{input:e.input}:{},...e.result!==void 0?{result:e.result}:{},...e.status!==void 0?{status:e.status}:{},...e.startTime!==void 0?{startTime:e.startTime}:{},...e.endTime!==void 0?{endTime:e.endTime}:{},...e.error!==void 0?{error:e.error||void 0}:{},...r!==void 0?{frontendOutput:r}:{},...e.llmOutput!==void 0?{llmOutput:e.llmOutput}:{},...e.resultMetadata!==void 0?{resultMetadata:e.resultMetadata}:{},...e.confirmationState!==void 0?{confirmationState:e.confirmationState===null?void 0:e.confirmationState}:{},...e.confirmationData!==void 0?{confirmationData:e.confirmationData===null?void 0:e.confirmationData}:{}}}function vAe(t,e,r){return t.map(n=>{let i=!1,o=n.parts?.map(s=>s.type!=="tool"||!s.tool||s.tool.id!==e?s:(i=!0,{...s,tool:_P(s.tool,r)}));return i&&o?{...n,parts:o}:n})}function BP(t){return{id:t,content:"",role:"assistant",timestamp:new Date,parts:[{type:"content",content:"",id:"content-0"}],isStreaming:!0}}function QAe(){return{status:"declined",endTime:new Date,confirmationState:"declined",confirmationData:{reason:"new_user_message",message:"Rejected: the user sent a new message instead of confirming this action. The proposed changes were NOT applied."}}}function vP(t){if(!t)return null;if(typeof t=="string")try{let e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}return typeof t=="object"&&!Array.isArray(t)?t:null}function TAe(t){if(!t.startsWith("data: "))return null;try{let e=JSON.parse(t.slice(6));return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function QP(t){return t.status==="running"||t.status==="pending"||t.status==="awaiting_confirmation"?{...t,status:"stopped",endTime:new Date,confirmationState:void 0,confirmationData:void 0}:t}function WS(t,e){if(!e)return t;let r=[...t.parts||[]],n=r[r.length-1];return n?.type==="content"?r[r.length-1]={...n,content:(n.content||"")+e}:r.push({type:"content",content:e,id:`content-${r.length}`}),{...t,parts:r,content:""}}function au(t,e,r){if(t.id!==r.id)return t;switch(e.type){case"content":return WS(t,e.content||"");case"tool_call_start":{let n=t.parts?.find(l=>l.type==="tool"&&l.tool?.id===e.toolCall.id)?.tool,i=e.toolCall.input??n?.input,o=e.executionMode==="confirm"?"awaiting_confirmation":i?"running":"pending",s={...n,id:e.toolCall.id,name:e.toolCall.name,input:i,status:o,startTime:n?.startTime||new Date,...n?.confirmationState!==void 0?{confirmationState:n.confirmationState}:{},...n?.confirmationData!==void 0?{confirmationData:n.confirmationData}:{}},a=[...t.parts||[]],c=a.findIndex(l=>l.type==="tool"&&l.tool?.id===e.toolCall.id);return c===-1?a.push({type:"tool",tool:s,id:`tool-${e.toolCall.id}`}):a[c]={...a[c],tool:s},{...t,parts:a,content:""}}case"tool_call_input":{let n=i=>i.id===e.toolCall.id&&e.toolCall.input!==void 0?{...i,input:e.toolCall.input}:i;return{...t,parts:t.parts?.map(i=>i.type==="tool"&&i.tool?{...i,tool:n(i.tool)}:i)}}case"run_command_effect":{let n=e.effect;if(n?.kind!=="visual"&&n?.kind!=="checklist"||typeof e.toolCallId!="string")return t;let i=o=>{if(o.id!==e.toolCallId)return o;let s=vP(o.frontendOutput)??{},a=(s.effects??[]).filter(c=>c.id!==n.id);return{...o,frontendOutput:{...s,effects:[...a,n]}}};return{...t,parts:t.parts?.map(o=>o.type==="tool"&&o.tool?{...o,tool:i(o.tool)}:o)}}case"tool_call_update":{let n=t.parts?.map(i=>i.type==="tool"&&i.tool?.id===e.toolCall.id?{...i,tool:{...i.tool,executionTraceId:e.toolCall.executionTraceId??i.tool.executionTraceId,status:i.tool.status==="pending"?"running":i.tool.status}}:i)||[];return{...t,parts:n}}case"tool_call_complete":{let n=t.parts?.find(h=>h.type==="tool"&&h.tool?.id===e.toolCall.id)?.tool,i=n?.status==="completed"||n?.status==="declined",o=e.toolCall.result!==void 0||e.toolCall.frontendOutput!==void 0||e.toolCall.status!==void 0||e.toolCall.confirmationState!==void 0||e.toolCall.confirmationData!==void 0;if(i&&!o)return t;let s=null;try{s=typeof e.toolCall.frontendOutput=="string"?JSON.parse(e.toolCall.frontendOutput):e.toolCall.frontendOutput}catch{}let a=s?.success===!1&&s?.error,c=e.toolCall.result?.outcome,l=c==="failure"?"error":c==="rejected"?"declined":c==="aborted"?"stopped":c==="success"?"completed":void 0,u=e.toolCall.status||l||"completed";a&&u==="completed"&&(u="error");let d=u==="awaiting_confirmation",A={...e.toolCall.input!==void 0?{input:e.toolCall.input}:{},...e.toolCall.result!==void 0?{result:e.toolCall.result}:{},status:u,frontendOutput:e.toolCall.frontendOutput,llmOutput:e.toolCall.llmOutput,resultMetadata:e.toolCall.resultMetadata,error:c==="failure"?e.toolCall.result.error.message:a?s.error:null,endTime:d?void 0:new Date,...e.toolCall.confirmationState!==void 0?{confirmationState:e.toolCall.confirmationState}:{},...e.toolCall.confirmationData!==void 0?{confirmationData:e.toolCall.confirmationData}:{}},p=t.parts?.map(h=>h.type==="tool"&&h.tool?.id===e.toolCall.id?{...h,tool:{...h.tool,...A}}:h)||[];return{...t,parts:p}}case"done":{if(!t.isStreaming)return t;let n=(t.parts||[]).map(i=>i.type==="tool"&&i.tool&&i.tool.status!=="awaiting_confirmation"?{...i,tool:QP(i.tool)}:i);return{...t,isStreaming:!1,parts:n,content:""}}default:return t}}function DAe(t){let e=new Set;for(let r of t)for(let n of(0,Im.getMessageToolCalls)(r))n.status==="awaiting_confirmation"&&e.add(n.id);return[...e]}function kAe(t){let e=QAe();return t.map(r=>({...r,parts:r.parts?.map(n=>n.type==="tool"&&n.tool?.status==="awaiting_confirmation"?{...n,tool:{...n.tool,...e}}:n)}))}function RAe(t,e){let r=t.find(i=>i.parts?.some(o=>o.type==="tool"&&o.tool?.id===e));return r?{messages:t.map(i=>i.id===r.id?{...i,isStreaming:!0}:i),targetMessage:{...r,isStreaming:!0}}:{messages:t,targetMessage:null}}function NAe(t){return{id:t.id,name:t.name,status:t.status,input:t.input,result:t.result,frontendOutput:t.frontendOutput,llmOutput:t.llmOutput,resultMetadata:t.resultMetadata,error:t.error,startTime:t.startTime,endTime:t.endTime,confirmationState:t.confirmationState,confirmationData:t.confirmationData}}function OAe(t){let{isStreaming:e,tools:r,...n}=t;return JSON.parse((0,Im.safeStringify)({...n,...t.parts?{parts:t.parts.map(i=>i.type==="tool"&&i.tool?{...i,tool:NAe(i.tool)}:i)}:{}},0))}Mt.AGENT_CONTEXT_MEMORY_MESSAGE_ID_PREFIX="context-memory-";var xAe=["artifacts"];function JS(t){let e=t.contextType??"";return BAe.TURN_CONTEXT_BLOCK_TYPES.includes(e)||xAe.includes(e)}function UAe(t){return t.filter(e=>e.role!=="system"&&e.contextType!=="memory_notes"&&!JS(e)&&!e.id.startsWith(Mt.AGENT_CONTEXT_MEMORY_MESSAGE_ID_PREFIX)).map(e=>({...e,stale:void 0,isStreaming:void 0}))}function MAe(t){return t.filter(e=>!e.stale&&!e.isStreaming&&e.contextType!=="memory_notes"&&!JS(e)&&!!e.id)}function PAe(t=[],e=null){return{messages:t,assistantMessageId:e,outcome:"streaming"}}function Em(t,e){return(0,Im.getMessageToolCalls)(t).some(r=>r.id===e)}function su(t,e){let r=t.assistantMessageId?t.messages.find(i=>i.id===t.assistantMessageId):void 0;if(r)return{state:t,target:r};let n=BP(t.assistantMessageId??e.createAssistantMessageId());return{state:{...t,messages:[...t.messages,n],assistantMessageId:n.id},target:n}}function LAe(t,e,r){switch(e.type){case"system_message":{if(!e.systemMessage)return t;let n={id:e.systemMessage.id,role:"system",content:e.systemMessage.content,timestamp:new Date};return{...t,messages:[n,...t.messages]}}case"assistant_message_start":{if(!e.assistantMessageId)return t;let n=t.assistantMessageId?t.messages.find(o=>o.id===t.assistantMessageId):void 0;return t.messages.find(o=>o.id===e.assistantMessageId)?{...t,assistantMessageId:e.assistantMessageId,messages:t.messages.filter(o=>!n||n.id===e.assistantMessageId||o.id!==n.id).map(o=>o.id===e.assistantMessageId?{...o,isStreaming:!0}:o)}:n?{...t,assistantMessageId:e.assistantMessageId,messages:t.messages.map(o=>o.id===n.id?{...o,id:e.assistantMessageId,isStreaming:!0}:o)}:{...t,assistantMessageId:e.assistantMessageId}}case"context_message":{if(!e.contextMessage)return t;let n={id:e.contextMessage.id,role:"user",content:e.contextMessage.content,timestamp:new Date,...e.contextMessage.isHidden?{isHidden:!0}:{},...e.contextMessage.attachedFiles?.length?{attachedFiles:e.contextMessage.attachedFiles}:{}};return{...t,assistantMessageId:null,messages:[...t.messages.map(i=>i.id===t.assistantMessageId?{...i,isStreaming:!1}:i),n]}}case"context_usage":case"compaction_start":return t;case"compaction_complete":{if(!e.compaction)return t;let n=(0,Im.applyAgentCompactionToMessages)(t.messages,e.compaction),i=e.compaction.memoryMessage?t.assistantMessageId:null;return!i||!n.some(o=>o.id===i)?{...t,messages:n}:{...t,assistantMessageId:null,messages:n.map(o=>o.id===i?{...o,isStreaming:!1}:o)}}case"content":{let n=su(t,r);return{...n.state,messages:n.state.messages.map(i=>i.id===n.target.id?WS(i,e.content||""):i)}}case"error":{let n=su(t,r);return{...n.state,outcome:"failed",messages:n.state.messages.map(i=>i.id!==n.target.id?i:{...i,parts:[...i.parts||[],{type:"error",content:e.content,errorDetails:e.errorDetails,id:`error-${i.parts?.length??0}`}],isStreaming:!1})}}case"tool_call_start":case"tool_call_update":{if(!e.toolCall)return t;let n=e.type==="tool_call_start"?null:t.messages.find(o=>Em(o,e.toolCall.id))??null,i=n?{state:t,target:n}:su(t,r);return{...i.state,messages:i.state.messages.map(o=>au(o,e,i.target))}}case"run_command_effect":{let n=e.toolCallId;if(!n)return t;let i=t.messages.find(o=>Em(o,n));return i?{...t,messages:t.messages.map(o=>au(o,e,i))}:t}case"tool_call_input":{if(!e.toolCall)return t;let n=t.messages.find(i=>Em(i,e.toolCall.id));return n?{...t,messages:t.messages.map(i=>au(i,e,n))}:t}case"tool_call_complete":{if(!e.toolCall)return t;let n=t.messages.find(o=>Em(o,e.toolCall.id)),i=n?{state:t,target:n}:su(t,r);return{...i.state,messages:i.state.messages.map(o=>au(o,e,i.target))}}case"paused":{let n=su(t,r);return{...n.state,outcome:"paused",messages:n.state.messages.map(i=>i.id===n.target.id?{...i,isStreaming:!1}:i)}}case"done":{let n=su(t,r);return{...n.state,outcome:t.outcome==="failed"?"failed":"completed",messages:n.state.messages.map(i=>au(i,e,n.target))}}default:return t}}});var ZS=y(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.AGENT_SESSION_PERMISSIONS_METADATA_KEY=Di.AGENT_PERMISSION_SCOPE_TYPES=void 0;Di.readSessionPermissionGrants=$Ae;Di.httpOperationMatches=RP;Di.findCoveringGrant=GAe;Di.describePermission=VAe;Di.AGENT_PERMISSION_SCOPE_TYPES=["system_write","tool_run","connection_edit","access_edit","org_settings_edit","org_memory_edit","file_delete","browser_use"];Di.AGENT_SESSION_PERMISSIONS_METADATA_KEY="permissionGrants";function $Ae(t){let e=t[Di.AGENT_SESSION_PERMISSIONS_METADATA_KEY];return Array.isArray(e)?e:[]}function kP(t){let e=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*");return new RegExp(`^${e}$`,"i")}function DP(t,e){let r=t.replace(/\/+$/,"").split("/").slice(1),n=e.replace(/\/+$/,"").split("/").slice(1);for(let i=0;i<r.length;i++){let o=r[i];if(o==="**")return!0;if(i>=n.length||!kP(o).test(decodeURIComponent(n[i])))return!1}return r.length===n.length}function FAe(t,e){let r=e?.replace(/\/+$/,"");return r?t===r?"/":t.startsWith(`${r}/`)?t.slice(r.length):null:null}function RP(t,e){let r=t.trim(),n=r.indexOf(" ");if(n===-1)return!1;let i=r.slice(0,n).toUpperCase();if(i!=="*"&&i!==e.method.toUpperCase())return!1;let o=r.slice(n+1).trim(),s=FAe(e.path,e.basePath);return DP(o,e.path)||s!==null&&DP(o,s)}function jAe(t,e){return t.connectionId?t.connectionId===e.connectionId:t.host.toLowerCase()===e.host.toLowerCase()}function zAe(t,e){let r=t.trim();return e.kind==="http"?RP(r,e):r.includes(" ")?!1:r==="*"||e.name!==""&&kP(r).test(e.name)}function qAe(t,e){return(t.operations??[]).some(r=>zAe(r,e.operation))}function HAe(t,e){if(t.type!==e.type)return!1;switch(e.type){case"system_write":return jAe(t,e)&&qAe(t,e);case"tool_run":return t.toolIds.includes(e.toolId);case"connection_edit":{let{connectionIds:r}=t;return!r?.length||r.includes(e.connectionId)}default:return!0}}function GAe(t,e){return t.find(r=>HAe(r.scope,e))}function YAe(t){return t.kind==="http"?`${t.method.toUpperCase()} ${t.path}`:t.name||"an operation superglue cannot read"}function VAe(t){switch(t.type){case"system_write":{let e="operation"in t?YAe(t.operation):t.operations?.join(", ");return`system_write on ${t.connectionId??t.host}${e?` (${e})`:""}`}case"tool_run":return`tool_run on ${"toolId"in t?t.toolId:t.toolIds.join(", ")}`;case"connection_edit":{let e="connectionId"in t?[t.connectionId]:t.connectionIds;return`connection_edit${e?.length?` on ${e.join(", ")}`:""}`}default:return t.type}}});var Cm=y(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.PROJECT_LABEL_COLOR_PATTERN=Pt.PROJECT_LABEL_COLORS=Pt.PROJECT_LIMITS=Pt.PROJECT_TASK_STATUSES=Pt.PROJECT_RESOURCE_TYPES=void 0;Pt.isProjectResourceType=WAe;Pt.nextProjectLabelColor=JAe;Pt.projectResourceKey=ZAe;Pt.daysUntilTaskDue=OP;Pt.formatTaskDueDate=KAe;Pt.groupByContext=XAe;Pt.PROJECT_RESOURCE_TYPES=["file","tool"];function WAe(t){return Pt.PROJECT_RESOURCE_TYPES.includes(t)}Pt.PROJECT_TASK_STATUSES=["not_started","in_progress","waiting","done"];Pt.PROJECT_LIMITS={name:80,description:500,taskName:120,taskDescription:1e4,labelName:40,labels:50,taskLabels:10};Pt.PROJECT_LABEL_COLORS=["#6b7280","#ef4444","#f97316","#eab308","#22c55e","#14b8a6","#3b82f6","#6366f1","#a855f7","#ec4899"];Pt.PROJECT_LABEL_COLOR_PATTERN=/^#[0-9a-f]{6}$/;function JAe(t){let e=new Set(t.map(r=>r.color));return Pt.PROJECT_LABEL_COLORS.find(r=>!e.has(r))??Pt.PROJECT_LABEL_COLORS[t.length%Pt.PROJECT_LABEL_COLORS.length]}function ZAe(t){return`${t.type}:${t.id}`}function NP(t){let e=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date);return new Date(`${e}T00:00:00Z`)}function OP(t,e){let r=new Date(`${t}T00:00:00Z`);return Math.round((r.getTime()-NP(e).getTime())/864e5)}function KAe(t,e){let r=new Date(`${t}T00:00:00Z`),n=NP(e),i=OP(t,e);return i===0?"Due today":i===1?"Due tomorrow":i===-1?"Due yesterday":i<-1?`${-i} days overdue`:i<7?`Due ${r.toLocaleDateString(void 0,{weekday:"long",timeZone:"UTC"})}`:`Due ${r.toLocaleDateString(void 0,{day:"numeric",month:"short",timeZone:"UTC",...r.getUTCFullYear()===n.getUTCFullYear()?{}:{year:"numeric"}})}`}function XAe(t){let e=new Map;for(let r of t)e.set(r.context,[...e.get(r.context)??[],r]);return[...e].map(([r,n])=>({context:r,items:n})).sort((r,n)=>+!!r.context-+!!n.context)}});var bm=y(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.RESOURCE_KINDS=Cn.RESOURCE_DEFINITIONS=void 0;Cn.isResourceKind=epe;Cn.getResourceDefinition=tpe;Cn.getResourceAppPath=rpe;Cn.RESOURCE_DEFINITIONS={tool:{label:"Tool",pluralLabel:"Tools",collectionKey:"tools",appPath:"/tools",hasDetailPage:!0,memberDefaultPermission:"editor",pickerDefaultPermission:"editor"},credential:{label:"Connection",pluralLabel:"Connections",collectionKey:"credentials",appPath:"/connections",hasDetailPage:!0,pickerDefaultPermission:"viewer"},playbook:{label:"Playbook",pluralLabel:"Playbooks",collectionKey:"playbooks",appPath:"/brain/playbooks",hasDetailPage:!0,pickerDefaultPermission:"editor"},file:{label:"File",pluralLabel:"Files",collectionKey:"files",appPath:"/brain/files",hasDetailPage:!0,pickerDefaultPermission:"viewer"},project:{label:"Project",pluralLabel:"Projects",collectionKey:"projects",appPath:"/brain/projects",hasDetailPage:!0,pickerDefaultPermission:"viewer"}};Cn.RESOURCE_KINDS=Object.keys(Cn.RESOURCE_DEFINITIONS);function epe(t){return typeof t=="string"&&Object.prototype.hasOwnProperty.call(Cn.RESOURCE_DEFINITIONS,t)}function tpe(t){return Cn.RESOURCE_DEFINITIONS[t]}function rpe(t,e){let r=Cn.RESOURCE_DEFINITIONS[t];return r.hasDetailPage?`${r.appPath}/${encodeURIComponent(e)}`:r.appPath}});var PP=y(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});Sc.SDK_ERROR_DETAILS_SCHEMA=Sc.SDK_OUTPUT_CONTRACTS=void 0;Sc.toSdkJsonSchema=spe;var m=lc(),npe=Cm(),ipe=bm(),ope=pn();function spe({schema:t}){return m.z.toJSONSchema(t,{target:"draft-7",io:"output",unrepresentable:"any"})}var xP=m.z.looseObject({statusCode:m.z.number(),headers:m.z.record(m.z.string(),m.z.union([m.z.string(),m.z.array(m.z.string())])),omittedHeaderCount:m.z.number().optional()}),UP=m.z.looseObject({vfsPath:m.z.string(),storedBytes:m.z.number(),originalOutputBytes:m.z.number(),storageTruncated:m.z.boolean()}),MP=m.z.object({action:m.z.enum(["approve","reject","oauth_success","oauth_failure"]),source:m.z.enum(["user","automatic"])});function ar(t){return m.z.looseObject({toolCallId:m.z.string(),toolName:m.z.string(),outcome:m.z.literal("success"),confirmation:MP.optional(),data:t})}var KS={http:xP.optional(),connection:m.z.looseObject({id:m.z.string(),name:m.z.string(),isOwner:m.z.boolean()}).optional().describe("The connection the call ran with."),auth:m.z.looseObject({applied:m.z.enum(["bearer","basic","explicit","none","unavailable"]),header:m.z.string().optional(),placeholders:m.z.array(m.z.string()),reason:m.z.string().optional()}).optional().describe("How authentication was sent: a default Bearer or Basic header, the request's own explicit placeholders, none, or unavailable with the reason. placeholders lists the connection's <<systemId_secretName>> strings."),secretPlaceholders:m.z.looseObject({keys:m.z.array(m.z.string()),resolved:m.z.boolean()}).optional()},ape=m.z.discriminatedUnion("protocol",[m.z.looseObject({protocol:m.z.enum(["postgres","odbc"]),data:m.z.array(m.z.record(m.z.string(),m.z.unknown())).describe("Returned database rows."),...KS}),m.z.looseObject({protocol:m.z.literal("mssql"),data:m.z.union([m.z.array(m.z.record(m.z.string(),m.z.unknown())),m.z.array(m.z.array(m.z.record(m.z.string(),m.z.unknown()))),m.z.looseObject({rowsAffected:m.z.array(m.z.number())})]).describe("One recordset, multiple recordsets, or affected row counts."),...KS}),m.z.looseObject({protocol:m.z.enum(ope.CONNECTION_PROTOCOLS.filter(t=>t!=="postgres"&&t!=="mssql"&&t!=="odbc")),data:m.z.unknown().describe("Complete protocol response payload. Preserve sibling fields, including files and metadata; do not unwrap a nested data field."),...KS})]),cpe=m.z.union([m.z.looseObject({tools:m.z.array(m.z.unknown()).describe("All tools from every tools/list page, each with name and inputSchema.")}),m.z.looseObject({result:m.z.looseObject({content:m.z.array(m.z.unknown()).optional(),structuredContent:m.z.unknown().optional(),isError:m.z.boolean().optional()}).describe("The tools/call result with content blocks and optional structuredContent.")})]),lpe=m.z.looseObject({url:m.z.string().describe("The requested URL."),status:m.z.number(),statusText:m.z.string(),headers:m.z.record(m.z.string(),m.z.string()),body:m.z.string().describe("Response body bytes, base64-encoded."),systemId:m.z.string().optional().describe("The system whose connection authenticated the request."),connection:m.z.looseObject({id:m.z.string(),name:m.z.string(),isOwner:m.z.boolean()}).optional().describe("The connection the request ran with.")}),upe=m.z.looseObject({stepId:m.z.string(),success:m.z.boolean(),data:m.z.unknown().optional(),error:m.z.string().nullable().optional(),http:xP.optional(),stepFileKeys:m.z.array(m.z.string()).optional()}),dpe=m.z.looseObject({toolId:m.z.string(),success:m.z.boolean(),run:m.z.looseObject({id:m.z.string()}).optional(),data:m.z.unknown().optional().describe("Tool output, determined by its output transform."),error:m.z.string().optional(),stepResults:m.z.array(upe),fileArtifacts:m.z.array(m.z.looseObject({fileKey:m.z.string(),filename:m.z.string(),contentType:m.z.string(),size:m.z.number(),downloadUrl:m.z.string().optional()})).optional(),warnings:m.z.array(m.z.string()).optional(),inputSchema:m.z.unknown().optional(),resultMetadata:UP.optional()}),Ape=ar(m.z.looseObject({resource:m.z.looseObject({id:m.z.string(),name:m.z.string().optional(),path:m.z.string().optional(),version:m.z.union([m.z.number(),m.z.string()]).optional()}),created:m.z.boolean(),projectId:m.z.string().optional(),projectAttribution:m.z.looseObject({attached:m.z.boolean(),projectId:m.z.string(),projectName:m.z.string().optional(),resource:m.z.looseObject({type:m.z.enum(npe.PROJECT_RESOURCE_TYPES),id:m.z.string()}),error:m.z.string().optional()}).optional()}));Sc.SDK_OUTPUT_CONTRACTS={assignSessionToProject:{name:"SuperglueSessionProjectResult",schema:ar(m.z.object({sessionId:m.z.string(),projectId:m.z.string().nullable()})),description:"Returns the saved session ID and project ID, or null when unassigned. Throws SuperglueError on failure."},callSystem:{name:"SuperglueCallSystemResult",schema:ape,description:"Returns the complete protocol payload in data, available HTTP metadata, the connection used, and how authentication was sent. Throws SuperglueError on failure; details contains the canonical result and unprojected execution output."},callMcp:{name:"SuperglueCallMcpResult",schema:cpe,description:"Returns { tools } when tool is omitted, or { result } from tools/call. Throws SuperglueError on HTTP, JSON-RPC, or result.isError failures; details.result.data contains statusCode, rpcError, or the failed result. On result.isError or invalid params, the error message ends with the called tool's input schema when it can be read; large schemas are shortened."},systemFetch:{name:"SuperglueSystemFetchResult",schema:lpe,description:"Returns the raw HTTP response: status, headers, and the base64 body. HTTP error statuses are returned, not thrown. Throws SuperglueError when the request cannot be authenticated or sent."},runTool:{name:"SuperglueRunToolResult",schema:dpe,description:"Returns successful tool output, step results, files, and available result reference. Throws SuperglueError on failure; details.result.data preserves this result shape with success: false, the error, and available run and step results. details.resultMetadata references the saved failed result when available."},writeResource:{name:"SuperglueWriteResult",schema:Ape,description:"Returns saved resource identity and path, creation status, and available project attribution. Throws SuperglueError on failure."},installBundle:{name:"SuperglueBundleInstallResult",schema:ar(m.z.looseObject({bundleId:m.z.string(),system:m.z.looseObject({id:m.z.string(),name:m.z.string(),requiredCredentialKeys:m.z.array(m.z.string()),hasUserCredentials:m.z.boolean()}),tools:m.z.array(m.z.looseObject({id:m.z.string(),name:m.z.string().optional()})),mcpServer:m.z.looseObject({id:m.z.string(),name:m.z.string()}).optional(),playbook:m.z.looseObject({id:m.z.string(),name:m.z.string()}).optional()})),description:"Returns the installed system ID, tool, MCP server, and playbook identities, the secret names the user must supply, and whether the user has a complete connection. Throws SuperglueError on failure."},stopBackgroundJob:{name:"SuperglueStopBackgroundJobResult",schema:ar(m.z.looseObject({job:m.z.looseObject({id:m.z.string(),status:m.z.string(),elapsedMs:m.z.number(),exitCode:m.z.number().optional()})})),description:"Returns the job's status, run time, and exit code after it ended, or status running when the stop is still in progress. Throws SuperglueError when the session has no such running job."},setToolState:{name:"SuperglueToolStateResult",schema:ar(m.z.looseObject({resource:m.z.looseObject({id:m.z.string()}),action:m.z.enum(["set","reset"])})),description:"Returns the saved tool identity and state action. Throws SuperglueError on failure."},shareResource:{name:"SuperglueShareResult",schema:ar(m.z.looseObject({resource:m.z.looseObject({kind:m.z.enum(ipe.RESOURCE_KINDS),id:m.z.string()})})),description:"Returns the shared resource identity. Throws SuperglueError on failure."},useChecklist:{name:"SuperglueChecklistResult",schema:ar(m.z.strictObject({visible:m.z.boolean(),done:m.z.number(),total:m.z.number()})),description:"Returns whether the session checklist is visible and its completed and total milestone counts. The progress panel updates immediately. Throws SuperglueError on failure."},showVisual:{name:"SuperglueShowVisualResult",schema:ar(m.z.looseObject({visualId:m.z.string(),check:m.z.looseObject({errors:m.z.array(m.z.string()),blockedRequests:m.z.array(m.z.string()),dataCalls:m.z.array(m.z.string()),contentHeight:m.z.number().optional(),timedOut:m.z.boolean()}).optional(),checkSkipped:m.z.string().optional(),screenshots:m.z.array(m.z.string()).optional()})),description:"Returns the visualId shown to the user. For a custom visual, check holds the test-browser result, and screenshots lists the labels of the screenshots attached to this command's result for you. Throws SuperglueError ETOOL when the visual fails its check; error.details.result.data.check then holds the errors."},notifyUser:{name:"SuperglueNotifyResult",schema:ar(m.z.looseObject({nextStepIds:m.z.array(m.z.string())})),description:"Returns the nextStepIds of the saved actions, in action order. Throws SuperglueError on failure."},writeOrgSettings:{name:"SuperglueOrgSettingsResult",schema:ar(m.z.looseObject({updated:m.z.array(m.z.enum(["name","preferences","notifications"])),notificationTest:m.z.looseObject({channel:m.z.enum(["slack","email"]),sent:m.z.boolean(),error:m.z.string().optional()}).optional()})),description:"Returns updated settings and any notification test result. Throws SuperglueError on failure."},writeDesignSystem:{name:"SuperglueDesignSystemResult",schema:ar(m.z.looseObject({updated:m.z.array(m.z.enum(["tokens","guidelines","logo"])),added:m.z.array(m.z.looseObject({id:m.z.string(),kind:m.z.enum(["logo","font","template","reference"]),name:m.z.string()})),changed:m.z.array(m.z.string()),removed:m.z.array(m.z.string())})),description:"Returns the changed design-system parts and file ids. Throws SuperglueError on failure."},importDesignSystemFromUrl:{name:"SuperglueDesignSystemImportResult",schema:ar(m.z.looseObject({url:m.z.string(),title:m.z.string().nullable(),tokens:m.z.looseObject({}),palette:m.z.array(m.z.looseObject({color:m.z.string(),weight:m.z.number()})),fonts:m.z.array(m.z.looseObject({family:m.z.string(),usage:m.z.array(m.z.string()),source:m.z.string()})),fontFiles:m.z.array(m.z.looseObject({file:m.z.string(),family:m.z.string().describe("CSS family name the website uses"),roles:m.z.array(m.z.string()),weight:m.z.string(),style:m.z.enum(["normal","italic"])})),logos:m.z.array(m.z.looseObject({file:m.z.string(),source:m.z.string(),width:m.z.number(),height:m.z.number(),light:m.z.boolean().describe("Light artwork meant for dark backgrounds")})),screenshot:m.z.string().nullable()})),description:"Returns a proposed design system from the website; font files, logos, and the screenshot are file:: session uploads. Throws SuperglueError on failure."},browser:{name:"SuperglueBrowserResult",schema:ar(m.z.looseObject({url:m.z.string(),title:m.z.string(),snapshot:m.z.string().optional(),closed:m.z.boolean().optional(),newSession:m.z.boolean().optional(),tabs:m.z.array(m.z.looseObject({index:m.z.number(),url:m.z.string(),title:m.z.string(),active:m.z.boolean()})).optional(),dialog:m.z.looseObject({type:m.z.string(),message:m.z.string(),defaultValue:m.z.string().optional()}).optional(),fileChooser:m.z.looseObject({multiple:m.z.boolean()}).optional(),downloads:m.z.array(m.z.looseObject({filename:m.z.string(),bytes:m.z.number(),path:m.z.string().optional(),error:m.z.string().optional()})).optional()})),description:"Returns the page URL and title after the action, and for every action except screenshot and close the page snapshot: an accessibility tree in which each element has a [ref=...], such as e12 or f1e12, for the next click, type, select, or upload. tabs lists every open tab when more than one is open. dialog is set while a JavaScript alert, confirm, or prompt waits for an answer; the page is paused until the dialog action answers it, and no snapshot is returned. fileChooser is set when the page opened a file picker; answer it with upload without ref. downloads lists files the page downloaded since the last action, saved as Brain files in this chat's Files at path; read one with vfs.readBinary({ path }). A download over the upload size limit has error instead of path and is not saved. newSession is true when this call started a new browser session: the tabs of the last session are reopened at their saved URLs, but unsaved form input and page state are gone, and cookies and sign-ins are kept. screenshot attaches a JPEG of the viewport to this command's result for you. Typed secret values are replaced by their placeholder in every returned text. Throws SuperglueError when the action fails."},readQbm:{name:"SuperglueReadQbmResult",schema:ar(m.z.looseObject({folder:m.z.string(),objects:m.z.array(m.z.looseObject({type:m.z.string(),files:m.z.array(m.z.string()),records:m.z.number()})),rawTables:m.z.array(m.z.looseObject({table:m.z.string(),files:m.z.array(m.z.string()),rows:m.z.number()})),encryptedValues:m.z.array(m.z.looseObject({table:m.z.string(),column:m.z.string(),values:m.z.number()})),unmappedCodes:m.z.array(m.z.looseObject({field:m.z.string(),code:m.z.string(),records:m.z.number()})).optional(),attachments:m.z.looseObject({documents:m.z.number(),note:m.z.string()}).optional(),rejectedRows:m.z.array(m.z.looseObject({table:m.z.string(),rows:m.z.number()})).optional()})),description:"Returns the folder that holds the extracted files, record counts per object type and raw table, encrypted columns, codes the reader cannot decode, and expected attachments. The folder also holds coverage.json.raw with the same summary plus the mapped source tables. Throws SuperglueError on failure."},readDocument:{name:"SuperglueReadDocumentResult",schema:ar(m.z.looseObject({headings:m.z.array(m.z.looseObject({level:m.z.number(),text:m.z.string()})),markdown:m.z.string()})),description:"Returns every heading with its level and the Markdown of the document or of the requested section. Throws SuperglueError when the file is not a Word file or no heading matches the section."},readSlides:{name:"SuperglueReadSlidesResult",schema:ar(m.z.looseObject({slideCount:m.z.number(),slides:m.z.array(m.z.looseObject({number:m.z.number(),title:m.z.string(),hidden:m.z.boolean(),text:m.z.string(),notes:m.z.string(),tables:m.z.number(),charts:m.z.number(),images:m.z.number(),markdown:m.z.string()}))})),description:"Returns the slide count and the requested slides with title, text in reading order, speaker notes, table, chart, and image counts, and Markdown. Throws SuperglueError when the file is not a PowerPoint file or a slide does not exist."},readSheet:{name:"SuperglueReadSheetResult",schema:ar(m.z.looseObject({sheet:m.z.looseObject({name:m.z.string(),hidden:m.z.boolean(),range:m.z.string().nullable(),rows:m.z.number(),columns:m.z.number(),formulas:m.z.number(),mergedRanges:m.z.number(),charts:m.z.number(),images:m.z.number()}),range:m.z.string().nullable(),cells:m.z.array(m.z.looseObject({address:m.z.string(),value:m.z.union([m.z.string(),m.z.number(),m.z.boolean(),m.z.null()]),text:m.z.string(),formula:m.z.string().optional()}))})),description:"Returns the sheet summary and every non-empty cell in the range with address, stored value, displayed text, and formula. A formula without a stored result has value null. Throws SuperglueError when the sheet or range does not exist."},findInFile:{name:"SuperglueFindInFileResult",schema:ar(m.z.looseObject({matches:m.z.array(m.z.looseObject({location:m.z.string(),text:m.z.string()}))})),description:"Returns every match with its location and surrounding text; an empty list when nothing matches. Throws SuperglueError when the file is not a Word, PowerPoint, or Excel file."},renderPage:{name:"SuperglueRenderPageResult",schema:ar(m.z.looseObject({label:m.z.string(),screenshots:m.z.array(m.z.string())})),description:"Shows the rendered page to the model after the command and returns its label. Throws SuperglueError when the page, slide, or sheet does not exist."},previewFile:{name:"SuperglueFilePreviewResult",schema:m.z.looseObject({draftId:m.z.string(),bytes:m.z.number()}),description:"Returns the HTML draft identity and byte count. Throws SuperglueError on failure."}};var ppe=m.z.looseObject({code:m.z.string(),path:m.z.array(m.z.union([m.z.string(),m.z.number(),m.z.symbol()])),message:m.z.string()});Sc.SDK_ERROR_DETAILS_SCHEMA=m.z.discriminatedUnion("kind",[m.z.looseObject({kind:m.z.literal("tool_result"),resultMetadata:UP.optional(),result:m.z.looseObject({toolCallId:m.z.string(),toolName:m.z.string(),outcome:m.z.enum(["success","failure","rejected","aborted"]),confirmation:MP.optional(),error:m.z.looseObject({message:m.z.string()}).optional(),data:m.z.unknown().optional()}),output:m.z.unknown().describe("Unprojected execution output, including the original error and any available response data or metadata.")}),m.z.looseObject({kind:m.z.enum(["input_validation","output_validation"]),toolName:m.z.string(),issues:m.z.array(ppe),output:m.z.unknown().optional()}),m.z.looseObject({kind:m.z.literal("permission"),toolName:m.z.string(),missing:m.z.array(m.z.looseObject({type:m.z.string()}))})])});var JP=y(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.SERVER_OWNED_SESSION_RESOURCE_KINDS=ke.AgentRequestValidationError=ke.AGENT_TOOL_CONTINUATION_ACTION_BY_CONFIRMATION_STATE=ke.AGENT_TOOL_CONTINUATION_ACTIONS=ke.AGENT_IDENTIFIER_PATTERN=ke.AGENT_REQUEST_LIMITS=void 0;ke.validateAgentRequestPayload=HP;ke.validateResourceBinding=GP;ke.validateClientResourceBinding=YP;ke.validateAgentSessionIdentity=VP;ke.validateAgentSessionTarget=WP;ke.validateAgentRequestSubmission=Ipe;ke.isAgentMessagePayload=Cpe;ke.isAgentToolContinuationPayload=bpe;var _s=pn();ke.AGENT_REQUEST_LIMITS={messageContentChars:5e4,identifierChars:256,attachedFiles:20,toolContinuations:20,continuationInputChars:1e5,frontendDraftsChars:2e6,accessRulesContextChars:2e6,pendingMessagesPerSession:10};ke.AGENT_IDENTIFIER_PATTERN=/^[A-Za-z0-9._-]+$/;ke.AGENT_TOOL_CONTINUATION_ACTIONS=["approve","reject","oauth_success","oauth_failure"];ke.AGENT_TOOL_CONTINUATION_ACTION_BY_CONFIRMATION_STATE={[_s.ConfirmationAction.CONFIRMED]:"approve",[_s.ConfirmationAction.DECLINED]:"reject",[_s.ConfirmationAction.OAUTH_SUCCESS]:"oauth_success",[_s.ConfirmationAction.OAUTH_FAILURE]:"oauth_failure"};var Sm=class extends Error{constructor(e){super(e),this.name="AgentRequestValidationError"}};ke.AgentRequestValidationError=Sm;function lt(t){throw new Sm(t)}function Go(t,e){return(!t||typeof t!="object"||Array.isArray(t))&<(`${e} must be an object`),t}function wc(t,e){(typeof t!="string"||!t.trim())&<(`${e} must be a non-empty string`);let r=t.trim();return r.length>ke.AGENT_REQUEST_LIMITS.identifierChars&<(`${e} exceeds ${ke.AGENT_REQUEST_LIMITS.identifierChars} characters`),ke.AGENT_IDENTIFIER_PATTERN.test(r)||lt(`${e} may only contain letters, numbers, dots, underscores, and hyphens`),r}function hpe(t,e){return typeof t!="boolean"&<(`${e} must be a boolean`),t}function XS(t,e){try{return JSON.stringify(t).length}catch{return lt(`${e} must be JSON-serializable`)}}function fpe(t,e){if(t!==void 0)return Array.isArray(t)||lt(`${e} must be an array`),t.length>ke.AGENT_REQUEST_LIMITS.attachedFiles&<(`${e} exceeds ${ke.AGENT_REQUEST_LIMITS.attachedFiles} entries`),t.map((r,n)=>{let i=Go(r,`${e}[${n}]`);return{...i,key:wc(i.key,`${e}[${n}].key`)}})}function LP({value:t,label:e,requireHidden:r}){let n=Go(t,e),i=wc(n.id,`${e}.id`);typeof n.content!="string"&<(`${e}.content must be a string`);let o=n.content;o.length>ke.AGENT_REQUEST_LIMITS.messageContentChars&<(`${e}.content exceeds ${ke.AGENT_REQUEST_LIMITS.messageContentChars} characters`);let s=hpe(n.isHidden,`${e}.isHidden`);r&&!s&<(`${e}.isHidden must be true`);let a=fpe(n.attachedFiles,`${e}.attachedFiles`);return!o.trim()&&!a?.length&<(`${e}.content may only be empty when an attachment is present`),{id:i,content:o,isHidden:s,...a?{attachedFiles:a}:{}}}function FP(t){if(t===void 0)return;let e=Go(t,"frontendDrafts");return XS(e,"frontendDrafts")>ke.AGENT_REQUEST_LIMITS.frontendDraftsChars&<(`frontendDrafts exceeds ${ke.AGENT_REQUEST_LIMITS.frontendDraftsChars} characters`),e}function jP(t){if(t===void 0)return;let e=Go(t,"accessRulesContext");return XS(e,"accessRulesContext")>ke.AGENT_REQUEST_LIMITS.accessRulesContextChars&<(`accessRulesContext exceeds ${ke.AGENT_REQUEST_LIMITS.accessRulesContextChars} characters`),e}function zP(t){if(t!==void 0)return(typeof t!="string"||!_s.AGENT_APPROVAL_MODES.includes(t))&<(`request.approvalMode must be one of: ${_s.AGENT_APPROVAL_MODES.join(", ")}`),t}function qP(t,e){let r=Go(t,e),n=wc(r.toolCallId,`${e}.toolCallId`);return(typeof r.action!="string"||!ke.AGENT_TOOL_CONTINUATION_ACTIONS.includes(r.action))&<(`${e}.action must be one of: ${ke.AGENT_TOOL_CONTINUATION_ACTIONS.join(", ")}`),r.input!==void 0&&XS(r.input,`${e}.input`)>ke.AGENT_REQUEST_LIMITS.continuationInputChars&<(`${e}.input exceeds ${ke.AGENT_REQUEST_LIMITS.continuationInputChars} characters`),{toolCallId:n,action:r.action,...r.input!==void 0?{input:r.input}:{}}}function gpe(t){if(t===void 0)return;(!Array.isArray(t)||t.length===0)&<("request.toolContinuations must be a non-empty array"),t.length>ke.AGENT_REQUEST_LIMITS.toolContinuations&<(`request.toolContinuations exceeds ${ke.AGENT_REQUEST_LIMITS.toolContinuations} entries`);let e=t.map((r,n)=>qP(r,`request.toolContinuations[${n}]`));return new Set(e.map(({toolCallId:r})=>r)).size!==e.length&<("request.toolContinuations must not contain duplicate toolCallId values"),e}function $P(t,e){if(t===void 0)return;(typeof t!="string"||!t.trim())&<(`${e} must be a non-empty string`);let r=t.trim();return r.length>ke.AGENT_REQUEST_LIMITS.messageContentChars&<(`${e} exceeds ${ke.AGENT_REQUEST_LIMITS.messageContentChars} characters`),r}var mpe=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ype(t){let e=LP({value:t.message,label:"request.message"}),r=$P(t.title,"request.title"),n=$P(t.titleInput,"request.titleInput"),i=t.hiddenSteeringMessage===void 0?void 0:LP({value:t.hiddenSteeringMessage,label:"request.hiddenSteeringMessage",requireHidden:!0});i&&i.id===e.id&<("request.hiddenSteeringMessage.id must differ from request.message.id");let o=gpe(t.toolContinuations),s=zP(t.approvalMode),a=FP(t.frontendDrafts),c=jP(t.accessRulesContext);return t.nextStepId!==void 0&&(typeof t.nextStepId!="string"||!mpe.test(t.nextStepId))&<("request.nextStepId must be a UUID"),{kind:"message",message:e,...t.nextStepId?{nextStepId:t.nextStepId}:{},...i?{hiddenSteeringMessage:i}:{},...r?{title:r}:{},...n?{titleInput:n}:{},...o?{toolContinuations:o}:{},...s?{approvalMode:s}:{},...a?{frontendDrafts:a}:{},...c?{accessRulesContext:c}:{}}}function Epe(t){let e=qP(t,"request"),r=zP(t.approvalMode),n=FP(t.frontendDrafts),i=jP(t.accessRulesContext);return{kind:"tool_continuation",...e,...r?{approvalMode:r}:{},...n?{frontendDrafts:n}:{},...i?{accessRulesContext:i}:{}}}function HP(t){let e=Go(t,"request");return e.kind==="message"?ype(e):e.kind==="tool_continuation"?Epe(e):lt('request.kind must be "message" or "tool_continuation"')}function GP(t,e){let r=Go(t,e);return(typeof r.kind!="string"||!_s.AGENT_SESSION_RESOURCE_KINDS.includes(r.kind))&<(`${e}.kind must be one of: ${_s.AGENT_SESSION_RESOURCE_KINDS.join(", ")}`),{kind:r.kind,id:wc(r.id,`${e}.id`)}}ke.SERVER_OWNED_SESSION_RESOURCE_KINDS=["briefing"];function YP(t,e){let r=GP(t,e);return ke.SERVER_OWNED_SESSION_RESOURCE_KINDS.includes(r.kind)&<(`${e}.kind "${r.kind}" is assigned by the server`),r}function VP(t,e="session.createIfMissing"){let r=Go(t,e),n=r.projectId===void 0?void 0:wc(r.projectId,`${e}.projectId`),i=r.taskId===void 0?void 0:wc(r.taskId,`${e}.taskId`);i&&!n&<(`${e}.taskId requires ${e}.projectId`);let o=Object.values(_s.AgentType);(typeof r.agentId!="string"||!o.includes(r.agentId))&<(`${e}.agentId must be one of: ${o.join(", ")}`);let s=r.resourceBinding===void 0?void 0:YP(r.resourceBinding,`${e}.resourceBinding`);return{agentId:r.agentId,...n?{projectId:n}:{},...i?{taskId:i}:{},...s?{resourceBinding:s}:{}}}function WP(t){let e=Go(t,"session"),r=e.createIfMissing===void 0?void 0:VP(e.createIfMissing);return{id:wc(e.id,"session.id"),...r?{createIfMissing:r}:{}}}function Ipe(t){let e=Go(t,"body");return{session:WP(e.session),request:HP(e.request)}}function Cpe(t){return t.kind==="message"}function bpe(t){return t.kind==="tool_continuation"}});var KP=y($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.ARTIFACT_EXPORT_FORMATS=$e.ARTIFACT_RESPONSE_RESERVED_FIELD_NAMES=$e.ARTIFACT_RESPONSE_PATCH_DEBOUNCE_MS=$e.MAX_SPREADSHEET_ARTIFACT_BYTES=$e.MAX_HTML_ARTIFACT_IMAGE_BYTES=$e.MAX_HTML_ARTIFACT_BYTES=$e.MAX_SPREADSHEET_CELL_TEXT_LENGTH=$e.MAX_SPREADSHEET_SHEET_NAME_LENGTH=$e.MAX_SPREADSHEET_GRID_CELLS=$e.MAX_SPREADSHEET_SHEETS=$e.SPREADSHEET_CELL_TYPES=$e.XLSX_CONTENT_TYPE=$e.HTML_CONTENT_TYPE=void 0;$e.brainFileDisplayTitle=Spe;$e.brainFileKind=wpe;$e.isValidSpreadsheetCell=vpe;$e.isArtifactExportFormat=Qpe;$e.isArtifactExportFormatForKind=Tpe;var ZP=lc();$e.HTML_CONTENT_TYPE="text/html";$e.XLSX_CONTENT_TYPE="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";function Spe(t){return t.replace(/\.[a-z][a-z0-9]{0,7}$/i,"")||t}function wpe({fileName:t,contentType:e}){let r=e?.split(";")[0].trim().toLowerCase(),n=t.toLowerCase().match(/\.([a-z0-9]+)$/)?.[1];return r===$e.HTML_CONTENT_TYPE||n==="html"||n==="htm"?"html":r===$e.XLSX_CONTENT_TYPE||n==="xlsx"?"spreadsheet":"file"}$e.SPREADSHEET_CELL_TYPES=["text","integer","number","percent","currency","boolean","date","datetime"];$e.MAX_SPREADSHEET_SHEETS=20;$e.MAX_SPREADSHEET_GRID_CELLS=1e6;$e.MAX_SPREADSHEET_SHEET_NAME_LENGTH=31;$e.MAX_SPREADSHEET_CELL_TEXT_LENGTH=32767;var _pe=ZP.z.iso.date(),Bpe=ZP.z.iso.datetime({offset:!0});function vpe(t,e){return t===null?!0:e==="text"?typeof t=="string"&&t.length<=$e.MAX_SPREADSHEET_CELL_TEXT_LENGTH:e==="boolean"?typeof t=="boolean":["integer","number","percent","currency"].includes(e)?typeof t=="number"&&Number.isFinite(t)&&(e!=="integer"||Number.isInteger(t)):typeof t!="string"?!1:(e==="datetime"?Bpe:_pe).safeParse(t).success}$e.MAX_HTML_ARTIFACT_BYTES=1024*1024;$e.MAX_HTML_ARTIFACT_IMAGE_BYTES=12*1024*1024;$e.MAX_SPREADSHEET_ARTIFACT_BYTES=10*1024*1024;$e.ARTIFACT_RESPONSE_PATCH_DEBOUNCE_MS=300;$e.ARTIFACT_RESPONSE_RESERVED_FIELD_NAMES=new Set(["__proto__","constructor","prototype"]);$e.ARTIFACT_EXPORT_FORMATS=["pdf","docx","xlsx","pptx"];function Qpe(t){return $e.ARTIFACT_EXPORT_FORMATS.some(e=>e===t)}function Tpe(t,e,r=!1){return t==="spreadsheet"?e==="xlsx":r?e==="pdf"||e==="pptx":e!=="pptx"}});var nL=y(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.API_KEY_ACTION_LABELS=it.API_KEY_SURFACE_LABELS=it.API_KEY_SCOPES=it.API_KEY_SURFACE_ACTIONS=it.API_KEY_ACTIONS=it.API_KEY_SURFACES=void 0;it.getApiKeySurface=eL;it.getApiKeyAction=tL;it.getApiKeySurfaceActions=ew;it.parseApiKeyScopes=rL;it.validateApiKeyScopesInput=Npe;it.isApiKeyScopeAllowed=Ope;it.formatApiKeyScopes=xpe;it.API_KEY_SURFACES=["api","mcp"];it.API_KEY_ACTIONS=["read","write","execute"];it.API_KEY_SURFACE_ACTIONS={api:it.API_KEY_ACTIONS,mcp:["execute"]};it.API_KEY_SCOPES=it.API_KEY_SURFACES.flatMap(t=>it.API_KEY_SURFACE_ACTIONS[t].map(e=>`${t}:${e}`));it.API_KEY_SURFACE_LABELS={api:"API & CLI",mcp:"MCP"};it.API_KEY_ACTION_LABELS={read:"Read",write:"Write",execute:"Execute"};var XP=new Set(it.API_KEY_SCOPES),Dpe={"/v1/tools":["read"],"/v1/tools/:toolId/run":["execute"],"/v1/authenticate":["write"],"/v1/memory-notes":["read","write"]},kpe=new Set(["/v1/api-keys","/v1/api-keys/:id","/v1/api-keys/:id/reveal"]),Rpe=new Set(["/v1/me"]);function eL(t){let e=t.split("?")[0];return e==="/mcp"||e.startsWith("/mcp/")?"mcp":"api"}function tL(t){return t==="read"?"read":t==="execute"?"execute":"write"}function ew(t,e){return it.API_KEY_SURFACE_ACTIONS[e].filter(r=>(t||[]).includes(`${e}:${r}`))}function rL(t){if(!Array.isArray(t))return null;let e=[...new Set(t.filter(r=>XP.has(r)))];return e.length>0?e:null}function Npe(t){if(t==null)return{scopes:null};let e=`Valid scopes: ${it.API_KEY_SCOPES.join(", ")}. Use null for full access.`;if(!Array.isArray(t)||t.length===0)return{error:`scopes must be a non-empty array of API key scopes. ${e}`};let r=t.filter(n=>!XP.has(n));return r.length>0?{error:`Unknown API key scope(s): ${r.map(String).join(", ")}. ${e}`}:{scopes:rL(t)}}function Ope({scopes:t,path:e,type:r}){if(!t||t.length===0)return!0;let n=e.split("?")[0];if(kpe.has(n))return!1;if(Rpe.has(n))return!0;let i=tL(r),o=eL(n);return o==="api"&&Dpe[n]?.some(s=>s===r)&&ew(t,"mcp").length>0?!0:t.includes(`${o}:${i}`)}function xpe(t){return!t||t.length===0?"Full access":it.API_KEY_SURFACES.map(e=>({surface:e,actions:ew(t,e)})).filter(e=>e.actions.length>0).map(e=>it.API_KEY_SURFACE_ACTIONS[e.surface].length===1?it.API_KEY_SURFACE_LABELS[e.surface]:`${it.API_KEY_SURFACE_LABELS[e.surface]} ${e.actions.join("/")}`).join(", ")}});var iL=y(tw=>{"use strict";Object.defineProperty(tw,"__esModule",{value:!0});tw.isValidEmail=Upe;function Upe(t){return/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.[a-zA-Z]{1,}$/.test(t)}});var sL=y(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.GATEWAY_UNINSTALL_COMMANDS=Jt.GATEWAY_API_KEY_NAME_PREFIX=Jt.GATEWAY_TARGET_NAME_PATTERN=Jt.GATEWAY_DOWNLOAD_BASE_URL=Jt.GATEWAY_INSTALL_TOKEN_PREFIX=void 0;Jt.getGatewayServerUrl=oL;Jt.buildGatewayInstallToken=Ppe;Jt.buildGatewayInstallCommand=Lpe;Jt.getGatewayApiKeyName=$pe;Jt.GATEWAY_INSTALL_TOKEN_PREFIX="sgi1.";Jt.GATEWAY_DOWNLOAD_BASE_URL="https://downloads.superglue.cloud";Jt.GATEWAY_TARGET_NAME_PATTERN=/^[a-z0-9]([a-z0-9_-]{0,61}[a-z0-9])?$/;function oL(t){let e=new URL(t);return e.protocol=e.protocol==="http:"?"ws:":"wss:",e.pathname=`${e.pathname.replace(/\/+$/,"")}/ws/tunnels`,e.search="",e.hash="",e.toString()}function Mpe(t){let e=new TextEncoder().encode(t),r="";for(let n of e)r+=String.fromCharCode(n);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ppe(t){let e={v:1,serverUrl:oL(t.apiEndpoint),tunnelId:t.tunnelId,apiKey:t.apiKey,targets:t.targets,enableScriptRunner:t.enableScriptRunner};return Jt.GATEWAY_INSTALL_TOKEN_PREFIX+Mpe(JSON.stringify(e))}function Lpe(t,e){return t==="windows"?[`$install = { ${["$ErrorActionPreference = 'Stop'","[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor 3072","$ProgressPreference = 'SilentlyContinue'","$gateway = Join-Path $env:TEMP 'superglue-gateway.exe'","Remove-Item $gateway -Force -ErrorAction SilentlyContinue",`Invoke-WebRequest -UseBasicParsing '${Jt.GATEWAY_DOWNLOAD_BASE_URL}/superglue-gateway-windows.exe' -OutFile $gateway`,`'${e}' | & $gateway install -`].join("; ")} }`,`if (([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { & $install } else { Start-Process powershell -Verb RunAs -ErrorAction Stop -ArgumentList "-NoExit -Command & {$install}"; 'Continue in the administrator PowerShell window.' }`].join("; "):["d=$(mktemp -d)",`u="${Jt.GATEWAY_DOWNLOAD_BASE_URL}/superglue-gateway-linux-$(uname -m | sed 's/aarch64/arm64/')"`,'s=$([ "$(id -u)" -eq 0 ] || echo sudo)','{ if command -v curl >/dev/null; then curl -fsSL -o "$d/superglue-gateway" "$u"; else wget -qO "$d/superglue-gateway" "$u"; fi; }','$s install -m 0755 "$d/superglue-gateway" /usr/local/bin/superglue-gateway',`echo '${e}' | $s /usr/local/bin/superglue-gateway install -`].join(" && ")}Jt.GATEWAY_API_KEY_NAME_PREFIX="Gateway: ";function $pe(t){return Jt.GATEWAY_API_KEY_NAME_PREFIX+t}Jt.GATEWAY_UNINSTALL_COMMANDS={windows:'& "C:\\Program Files\\superglue Gateway\\superglue-gateway.exe" uninstall',linux:"sudo /usr/local/bin/superglue-gateway uninstall"}});var sw=y(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.OAUTH_TOKEN_CREDENTIAL_KEYS=Fe.OAUTH_CONFIG_CREDENTIAL_KEYS=void 0;Fe.hasMeaningfulValue=hr;Fe.stringValue=fr;Fe.validateOAuthConnection=Wpe;Fe.formatOAuthConnectionDisabledReason=Zpe;Fe.objectValue=vs;Fe.parseScopes=UA;Fe.normalizeGrantType=MA;Fe.normalizeOAuthClientMode=ow;Fe.normalizeSystemAuthentication=Zr;Fe.resolveOAuthClientMode=Xpe;Fe.flattenSystemAuthentication=lL;Fe.maskedFlatSystemAuthentication=ehe;Fe.isMaskedSecretValue=uL;Fe.pickAgentAuthInputFields=the;Fe.maskSystemAuthenticationForResponse=rhe;Fe.restoreMaskedClientSecret=nhe;Fe.mapAgentAuthInput=dL;Fe.mergeAgentAuthInput=phe;Fe.getAuthenticationConfigCredentialKeys=hhe;Fe.getCredentialRequirements=fhe;Fe.isCredentialRequirementSatisfied=AL;Fe.hasUnsatisfiedCredentialRequirements=ghe;Fe.updateAuthenticationEditorField=mhe;Fe.validateOAuthAuthenticationConfigPlacement=yhe;Fe.authenticationToLegacyCredentials=pL;Fe.isRuntimeCredentialMetadataKey=Ehe;Fe.buildRuntimeCredentialsFromAuthentication=Ihe;Fe.resolveOAuthConfigFromAuthentication=Che;Fe.toCredentialInputValue=bhe;var fa=Ti();Fe.OAUTH_CONFIG_CREDENTIAL_KEYS=["auth_url","authUrl","token_url","tokenUrl","token_uri","scopes","scope","grant_type","grantType","oauthClientMode","client_id","clientId","client_secret","clientSecret","tokenAuthMethod","tokenContentType","usePKCE","extraHeaders","extraBodyParams"];var wm=["host","port","database","path","homeDirectory"],cL=["type","oauthClientMode","grantType","authUrl","tokenUrl","scopes","clientId","clientSecret","tokenAuthMethod","tokenContentType","usePKCE","extraHeaders","extraBodyParams","resource","protocol",...wm],Fpe=new Set(cL),jpe="type, oauthClientMode, grantType, authUrl, tokenUrl, scopes, clientId, clientSecret, tokenAuthMethod, tokenContentType, usePKCE, extraHeaders, extraBodyParams, resource, protocol, host, port, database, path, homeDirectory",zpe=["grantType","authUrl","tokenUrl","scopes","clientId","clientSecret"],qpe={grantType:["grantType","grant_type"],authUrl:["authUrl","auth_url"],tokenUrl:["tokenUrl","token_url","token_uri"],scopes:["scopes","scope"],clientId:["clientId","client_id"],clientSecret:["clientSecret","client_secret"]},iw=["tokenAuthMethod","tokenContentType","usePKCE","extraHeaders","extraBodyParams","resource"],Hpe=new Set(zpe);Fe.OAUTH_TOKEN_CREDENTIAL_KEYS=["access_token","accessToken","refresh_token","refreshToken","expires_at","expiresAt","expires_in","expiresIn","expiry","token_type","tokenType"];var Gpe=new Set(Fe.OAUTH_TOKEN_CREDENTIAL_KEYS);function _c(t){return Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0))}function rw({config:t,key:e,value:r}){let n={...t||{}};return hr(r)?n[e]=r:delete n[e],Object.keys(n).length>0?n:void 0}function hr(t){return(0,fa.hasCredentialValue)(t)}function fr(t){if(hr(t))return typeof t=="string"?t:String(t)}var Ype={"grant_type authorization_code or client_credentials":"authorization_code or client_credentials",client_id:"client ID",token_url:"token URL",auth_url:"authorization URL","client_secret or usePKCE":"client secret or PKCE","client_secret or oauth_cert + oauth_key":"client secret or OAuth certificate and key"};function Bs(...t){return t.find(e=>hr(e))}function Vpe(t){return t===!0||t==="true"}function Wpe(t){let e=t||{},r=fr(Bs(e.grant_type,e.grantType)),n=r==="client_credentials"?"client_credentials":"authorization_code",i=r&&r!=="authorization_code"&&r!=="client_credentials",o=Bs(e.client_id,e.clientId),s=Bs(e.client_secret,e.clientSecret),a=Bs(e.auth_url,e.authUrl),c=Bs(e.token_url,e.tokenUrl,e.token_uri),l=Bs(e.oauth_cert,e.oauthCert),u=Bs(e.oauth_key,e.oauthKey),d=hr(l)&&hr(u)||e.hasServerSideCertificateCredentials===!0,A=e.hasServerSideClientSecret===!0,p=hr(s)||A,h=Vpe(Bs(e.usePKCE,e.usePkce)),f=[];return i&&f.push("grant_type authorization_code or client_credentials"),hr(o)||f.push("client_id"),hr(c)||f.push("token_url"),n==="client_credentials"?!p&&!d&&f.push("client_secret or oauth_cert + oauth_key"):(hr(a)||f.push("auth_url"),!p&&!h&&f.push("client_secret or usePKCE")),{grantType:n,hasAccessToken:hr(Bs(e.access_token,e.accessToken)),hasCertificateCredentials:d,isReadyToConnect:f.length===0,missingFields:f,usePKCE:h}}function Jpe(t){return t.length<=1?t[0]||"":t.length===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t[t.length-1]}`}function Zpe(t){if(!t||t.isReadyToConnect)return null;let e=t.missingFields.map(r=>Ype[r]||r);return`OAuth connection is disabled because ${Jpe(e)} ${e.length===1?"is":"are"} missing.`}function vs(t){if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Yo(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function UA(t){if(Array.isArray(t))return t.map(String).filter(Boolean);if(hr(t)){if(typeof t=="string"){let e=t.trim().split(/[,\s]+/).map(r=>r.trim()).filter(Boolean);return e.length>0?e:void 0}return[String(t)]}}function MA(t){let e=fr(t);if(e==="authorization_code"||e==="client_credentials"||e==="password"||e==="service_account"||e==="custom")return e;if(e)return"custom"}function ow(t){return t==="managed"||t==="dynamic"||t==="custom"?t:void 0}function Kpe(t){let e=Object.entries(t).filter(([r])=>!Hpe.has(r));return e.length>0?Object.fromEntries(e):void 0}function cu(t,e,r){for(let i of qpe[r])if(r==="scopes"&&Array.isArray(t[i])||hr(t[i]))return t[i];let n=vs(t.client);return r==="clientId"&&hr(n?.id)?n.id:r==="clientSecret"&&hr(n?.secret)?n.secret:e[r]}function Zr(t){if(!t)return;let e=t;if(e.type==="oauth2"){let r=vs(e.config)||{},n=Kpe(r)||{};return _c({type:"oauth2",oauthClientMode:ow(e.oauthClientMode),grantType:MA(cu(e,r,"grantType")),authUrl:fr(cu(e,r,"authUrl")),tokenUrl:fr(cu(e,r,"tokenUrl")),scopes:UA(cu(e,r,"scopes")),oauthAppId:fr(e.oauthAppId),clientId:fr(cu(e,r,"clientId")),clientSecret:fr(cu(e,r,"clientSecret")),config:Object.keys(n).length>0?n:void 0})}return e.type==="connection_string"?_c({type:"connection_string",protocol:e.protocol,config:vs(e.config??e.components)}):e.type==="api_key"||e.type==="basic_auth"||e.type==="none"?_c({type:e.type,config:vs(e.config)}):{type:"none"}}function Xpe({authentication:t,templateManaged:e,templateRegistrationUrl:r}){let n=Zr(t);return n?.type!=="oauth2"?"custom":n.oauthAppId?.startsWith("managed:")?"managed":n.oauthClientMode?n.oauthClientMode==="managed"&&!e?"custom":n.oauthClientMode:r?"dynamic":e&&!n.clientSecret?"managed":"custom"}function lL(t){let e=Zr(t);if(!e)return;let{config:r,scopes:n,oauthAppId:i,...o}=e,s={};return r&&typeof r=="object"&&Object.assign(s,r),Object.assign(s,o),Array.isArray(n)?s.scopes=n.join(" "):n!==void 0&&(s.scopes=n),s}function nw(t,e=""){return t==null?t:Array.isArray(t)?t.map(r=>nw(r)):typeof t=="object"?Object.fromEntries(Object.entries(t).map(([r,n])=>[r,nw(n,r)])):e&&(0,fa.isSensitiveCredentialKey)(e)?(0,fa.maskCredentialValue)(e,t):t}function ehe(t){let e=lL(t);if(e)return nw(e)}function uL(t){return(0,fa.isMaskedValue)(t)||(0,fa.isFullyMaskedCredentialValue)(t)}function the(t){let e=vs(t);if(!e)return;let r={};for(let n of cL){if(!Yo(e,n))continue;let i=e[n];i!==void 0&&(r[n]=i)}return r}function rhe(t){return!t||t.type!=="oauth2"||!hr(t.clientSecret)?t:{...t,clientSecret:fa.FULLY_MASKED_CREDENTIAL_VALUE}}function nhe({incoming:t,existing:e}){if(!t||t.type!=="oauth2"||!uL(t.clientSecret))return t;let r=e?.type==="oauth2"?e.clientSecret:void 0;return{...t,clientSecret:r}}function ihe(t){if(t==="none"||t==="api_key"||t==="basic_auth"||t==="oauth2"||t==="connection_string")return t}function ohe(t){let e=wm.flatMap(r=>{if(!Yo(t,r))return[];let n=t[r];return hr(n)?[[r,n]]:[]});return e.length>0?Object.fromEntries(e):void 0}function she(t){return wm.filter(e=>Yo(t,e))}function ahe(t){let e=wm.flatMap(r=>Yo(t,r)?[[r,t[r]]]:[]);return e.length>0?Object.fromEntries(e):void 0}function che(t){let e=new Set(["oauthClientMode","grantType","authUrl","tokenUrl","scopes","clientId","clientSecret",...iw]);return Object.keys(t).filter(r=>e.has(r))}function dL(t){if(t==null)return{};let e=vs(t);if(!e)return{error:"auth must be an object."};let r=ihe(e.type);if(!r)return{error:"auth.type is required."};let n=Object.keys(e).filter(a=>!Fpe.has(a));if(n.length>0)return{error:`Unknown auth field(s): ${n.join(", ")}. Accepted: ${jpe}.`};let i=she(e);if(r!=="connection_string"&&i.length>0)return{error:`Connection auth field(s) require auth.type 'connection_string': ${i.join(", ")}.`};let o=che(e);if(r!=="oauth2"&&o.length>0)return{error:`OAuth auth field(s) require auth.type 'oauth2': ${o.join(", ")}.`};if(r!=="oauth2"){let a=ohe(e);return{authentication:_c({type:r,protocol:r==="connection_string"?e.protocol:void 0,config:a})}}let s={...Object.fromEntries(iw.flatMap(a=>{if(!Yo(e,a))return[];let c=e[a];return hr(c)?[[a,c]]:[]}))};return{authentication:_c({type:"oauth2",oauthClientMode:ow(e.oauthClientMode),grantType:MA(e.grantType),authUrl:fr(e.authUrl),tokenUrl:fr(e.tokenUrl),scopes:UA(e.scopes),clientId:fr(e.clientId),clientSecret:fr(e.clientSecret),config:Object.keys(s).length>0?s:void 0})}}function Bc(t){return t===""||t===null||t===void 0}function xA(t,e,r,n){if(Yo(e,r)){if(Bc(e[r])){delete t[n];return}t[n]=fr(e[r])}}function lhe(t,e){if(Yo(e,"scopes")){if(Bc(e.scopes)){delete t.scopes;return}t.scopes=UA(e.scopes)}}function uhe(t,e){if(Yo(e,"grantType")){if(Bc(e.grantType)){delete t.grantType;return}t.grantType=MA(e.grantType)}}function dhe(t,e,r){if(Yo(e,r)){if(Bc(e[r])){delete t[r];return}t[r]=e[r]}}function Ahe(t,e){if(Bc(e))return;let r=vs(e);if(!r)return t;let n={...t||{}};for(let[i,o]of Object.entries(r))Bc(o)?delete n[i]:n[i]=o;return Object.keys(n).length>0?n:void 0}function phe(t,e){let r=dL(e);if(r.error)return Zr(t)||{type:"none"};let n=r.authentication||{type:"none"},i=vs(e)||{},o=Zr(t),s=o?.type===n.type;if(n.type!=="oauth2"){let d=ahe(i),A=s&&o?{...o}:{type:n.type};return n.type==="connection_string"&&Yo(i,"protocol")&&(Bc(i.protocol)?delete A.protocol:A.protocol=i.protocol),d&&(A.config=Ahe(o?.config,d)),Zr(A)||{type:n.type}}let c={...s&&o?.type==="oauth2"?{...o,config:{...o.config||{}}}:{type:"oauth2",config:{}}};xA(c,i,"oauthClientMode","oauthClientMode"),uhe(c,i),xA(c,i,"authUrl","authUrl"),xA(c,i,"tokenUrl","tokenUrl"),lhe(c,i),xA(c,i,"clientId","clientId"),xA(c,i,"clientSecret","clientSecret");let u={...c.config||{}};for(let d of iw)dhe(u,i,d);return c.config=Object.keys(u).length>0?u:void 0,Zr(c)||{type:"oauth2"}}function hhe(t){let e=Zr(t);if(!e)return[];let r=new Set;for(let n of Object.keys(e.config||{}))r.add(n);return e.type==="oauth2"&&(e.grantType&&(r.add("grant_type"),r.add("grantType")),e.authUrl&&(r.add("auth_url"),r.add("authUrl")),e.tokenUrl&&(r.add("token_url"),r.add("tokenUrl"),r.add("token_uri")),e.scopes&&(r.add("scopes"),r.add("scope")),e.clientId&&(r.add("client_id"),r.add("clientId")),e.clientSecret&&(r.add("client_secret"),r.add("clientSecret"))),[...r]}function fhe(t){let e=Zr(t);if(!e||e.type!=="connection_string")return[];let r={type:"field",field:{key:"username",aliases:["user"]}},n={type:"field",field:{key:"password"}};switch(e.protocol){case"sftp":return[r,{type:"oneOf",fields:[{key:"password"},{key:"privateKey"}]},{type:"field",field:{key:"passphrase"},optional:!0}];case"smb":return[r,n,{type:"field",field:{key:"domain"},optional:!0}];case"sqlserver":return[{type:"field",field:{key:"user",aliases:["username"]}},n];default:return[r,n]}}function aL(t,e){return(0,fa.hasCredentialValue)(e[t.key])?!0:(t.aliases??[]).some(r=>(0,fa.hasCredentialValue)(e[r]))}function AL(t,e){return t.optional?!0:t.type==="field"?aL(t.field,e):t.fields.some(r=>aL(r,e))}function ghe(t,e){let r=e||{};return t.some(n=>!AL(n,r))}function mhe({authentication:t,path:e,value:r}){let n=Zr(t)||{type:"none"};if(n.type==="oauth2"){if(e==="oauth2.grantType")return{...n,grantType:MA(r)};if(e==="oauth2.authUrl")return{...n,authUrl:fr(r)};if(e==="oauth2.tokenUrl")return{...n,tokenUrl:fr(r)};if(e==="oauth2.scopes")return{...n,scopes:UA(r)??[]};if(e==="oauth2.clientId")return{...n,clientId:fr(r)};if(e==="oauth2.clientSecret")return{...n,clientSecret:fr(r)};if(e.startsWith("oauth2.config.")){let o=e.slice(14);return{...n,config:rw({config:n.config,key:o,value:r})}}}if(n.type==="connection_string"){if(e==="connection.protocol")return{...n,protocol:fr(r)};if(e.startsWith("connection.config.")){let o=e.slice(18);return{...n,config:rw({config:n.config,key:o,value:r})}}}let i=`${n.type}.config.`;if(e.startsWith(i)){let o=e.slice(i.length);return{...n,config:rw({config:n.config,key:o,value:r})}}return n}function yhe({authentication:t,credentials:e}){if(Zr(t)?.type!=="oauth2"||!e||typeof e!="object"||Array.isArray(e))return null;let n=Object.keys(e).filter(i=>Fe.OAUTH_CONFIG_CREDENTIAL_KEYS.includes(i));return n.length===0?null:`OAuth configuration keys belong in auth, not credentials: ${n.join(", ")}. Move OAuth client ID to auth.clientId, client secret to auth.clientSecret, auth URL to auth.authUrl, token URL to auth.tokenUrl, scopes to auth.scopes, grant type to auth.grantType, and token request settings to auth fields such as tokenAuthMethod/usePKCE/extraHeaders. Runtime OAuth access and refresh tokens are created by connect OAuth authorization.`}function pL(t){let e=Zr(t);return e?e.type==="oauth2"?_c({...e.config||{},grant_type:e.grantType,auth_url:e.authUrl,token_url:e.tokenUrl,scopes:e.scopes?.join(" "),client_id:e.clientId,client_secret:e.clientSecret}):e.type==="connection_string"?e.config||{}:e.config||{}:{}}function Ehe(t){return Gpe.has(t.trim())}function Ihe({authentication:t,credentials:e}){let r=pL(t);return Zr(t)?.type==="oauth2"?{...e||{},...r}:{...r,...e||{}}}function Che({input:t,authentication:e,templateOAuth:r}){let n=Zr(e),i=n?.type==="oauth2"?n:void 0,o=i?.config||{},s=t||{},a=(...c)=>c.find(l=>l!=null);return _c({grant_type:a(s.grantType,s.grant_type,i?.grantType,r?.grant_type)||"authorization_code",scopes:a(s.scopes,i?.scopes?.join(" "),r?.scopes),client_id:a(s.clientId,s.client_id,i?.clientId),client_secret:a(s.clientSecret,s.client_secret,i?.clientSecret),auth_url:a(s.authUrl,s.auth_url,i?.authUrl,r?.authUrl),token_url:a(s.tokenUrl,s.token_url,i?.tokenUrl,r?.tokenUrl),resource:a(s.resource,o.resource,r?.resource),tokenAuthMethod:a(s.tokenAuthMethod,o.tokenAuthMethod,r?.tokenAuthMethod),tokenContentType:a(s.tokenContentType,o.tokenContentType,r?.tokenContentType),usePKCE:a(s.usePKCE,o.usePKCE,r?.usePKCE),extraHeaders:a(s.extraHeaders,o.extraHeaders,r?.extraHeaders),extraBodyParams:a(s.extraBodyParams,o.extraBodyParams,r?.extraBodyParams)})}function bhe(t){if(t==null)return"";if(typeof t=="string")return t;let e=JSON.stringify(t);return e===void 0?String(t):e}});var NL=y(Vo=>{"use strict";Object.defineProperty(Vo,"__esModule",{value:!0});Vo.bundles=void 0;Vo.buildBundleAgentLaunch=Ohe;Vo.getBundle=xhe;Vo.listBundles=Uhe;var She="https://sandbox.api.sap.com/s4hanacloud/sap/opu/odata/sap",whe="<<(p) => { const value = p['sage_intacct_entity_id']; if (!value) return ''; const escaped = String(value).replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('\"', '"').replaceAll(\"'\", '''); return `<locationid>${escaped}</locationid>`; }>>",hL="<<() => crypto.randomUUID()>>";function Lt(t){return`<?xml version="1.0" encoding="UTF-8"?><request><control><senderid><<sage_intacct_sender_id>></senderid><password><<sage_intacct_sender_password>></password><controlid>${hL}</controlid><uniqueid>false</uniqueid><dtdversion>3.0</dtdversion></control><operation><authentication><login><userid><<sage_intacct_user_id>></userid><companyid><<sage_intacct_company_id>></companyid><password><<sage_intacct_user_password>></password>${whe}</login></authentication><content><function controlid="${hL}">${t}</function></content></operation></request>`}function ga({stepId:t,objectNameExpression:e,collectionName:r,mapExpression:n,includeTotalCount:i=!1}){let o=i?"Number(data && data.TOTALCOUNT ? data.TOTALCOUNT : rows.length)":"rows.length",s=n?`rows.map(${n})`:"rows";return`(sourceData) => { const response = sourceData.${t} && sourceData.${t}.data ? sourceData.${t}.data.RESPONSE : undefined; const control = response ? response.CONTROL : undefined; const operation = response ? response.OPERATION : undefined; const authentication = operation ? operation.AUTHENTICATION : undefined; const result = operation ? operation.RESULT : undefined; const statuses = [control && control.STATUS, authentication && authentication.STATUS, result && result.STATUS].filter(Boolean).map((value) => String(value).toLowerCase()); if (statuses.includes('failure')) { const message = (result && result.ERRORMESSAGE) || (authentication && authentication.ERR ? authentication.ERR.ERRORMESSAGE : undefined) || (control && control.ERR ? control.ERR.ERRORMESSAGE : undefined); const rawErrors = message ? message.ERROR : undefined; const errors = Array.isArray(rawErrors) ? rawErrors : (rawErrors ? [rawErrors] : []); const details = errors.map((error) => [error.ERRORNO, error.DESCRIPTION2 || error.DESCRIPTION, error.CORRECTION].filter(Boolean).join(' - ')).filter(Boolean); const supportIds = errors.map((error) => error.SUPPORTID).filter(Boolean); const suffix = supportIds.length ? \` Sage support ID: \${supportIds.join(', ')}.\` : ''; throw new Error(\`Sage Intacct request failed\${details.length ? \`: \${details.join('; ')}\` : '.'}\${suffix}\`); } const data = result ? result.DATA : undefined; const objectName = ${e}; const raw = data ? data[objectName] : undefined; const rows = (Array.isArray(raw) ? raw : (raw ? [raw] : [])).slice(0, (sourceData && sourceData.maxResults) ?? ${i?"1000":"200"}); return { total: ${o}, ${r}: ${s} }; }`}var ma=`const esc = (value) => String(value).replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", ''');`,fL="const toIntacctDate = (value) => { const match = String(value).match(/^(\\d{4})-(\\d{2})-(\\d{2})/); if (!match) throw new Error('Dates must be in YYYY-MM-DD format.'); return match[2] + '/' + match[3] + '/' + match[1]; };",gL="const assertBalanced = (lines) => { const balance = lines.reduce((sum, line) => sum + (line.type === 'credit' ? -1 : 1) * Math.abs(Number(line.amount)), 0); if (Math.abs(balance) > 0.005) throw new Error('Journal lines must balance: debits minus credits is ' + balance.toFixed(2) + '.'); };",mL=`const lineXml = (line) => { const amount = Number(line.amount); if (!Number.isFinite(amount) || amount <= 0) throw new Error('Every journal line needs a positive amount.'); const type = line.type === 'credit' ? -1 : line.type === 'debit' ? 1 : null; if (type === null) throw new Error("Every journal line needs type 'debit' or 'credit'."); if (!line.accountNo) throw new Error('Every journal line needs accountNo.'); let xml = '<GLENTRY><ACCOUNTNO>' + esc(line.accountNo) + '</ACCOUNTNO><TR_TYPE>' + type + '</TR_TYPE><TRX_AMOUNT>' + amount + '</TRX_AMOUNT>'; if (line.department) xml += '<DEPARTMENT>' + esc(line.department) + '</DEPARTMENT>'; if (line.location) xml += '<LOCATION>' + esc(line.location) + '</LOCATION>'; if (line.memo) xml += '<DESCRIPTION>' + esc(line.memo) + '</DESCRIPTION>'; return xml + '</GLENTRY>'; };`;function lu({stepId:t,objectName:e}){return`(sourceData) => { const response = sourceData.${t} && sourceData.${t}.data ? sourceData.${t}.data.RESPONSE : undefined; const control = response ? response.CONTROL : undefined; const operation = response ? response.OPERATION : undefined; const authentication = operation ? operation.AUTHENTICATION : undefined; const result = operation ? operation.RESULT : undefined; const statuses = [control && control.STATUS, authentication && authentication.STATUS, result && result.STATUS].filter(Boolean).map((value) => String(value).toLowerCase()); if (statuses.includes('failure')) { const message = (result && result.ERRORMESSAGE) || (authentication && authentication.ERR ? authentication.ERR.ERRORMESSAGE : undefined) || (control && control.ERR ? control.ERR.ERRORMESSAGE : undefined); const rawErrors = message ? message.ERROR : undefined; const errors = Array.isArray(rawErrors) ? rawErrors : (rawErrors ? [rawErrors] : []); const details = errors.map((error) => [error.ERRORNO, error.DESCRIPTION2 || error.DESCRIPTION, error.CORRECTION].filter(Boolean).join(' - ')).filter(Boolean); const supportIds = errors.map((error) => error.SUPPORTID).filter(Boolean); const suffix = supportIds.length ? \` Sage support ID: \${supportIds.join(', ')}.\` : ''; throw new Error(\`Sage Intacct request failed\${details.length ? \`: \${details.join('; ')}\` : '.'}\${suffix}\`); } const data = result ? result.DATA : undefined; const raw = data ? (data.${e} || data.${e.toLowerCase()}) : undefined; const record = Array.isArray(raw) ? raw[0] : raw; return { recordNo: record && record.RECORDNO ? Number(record.RECORDNO) : undefined, record }; }`}var FA="netsuite",lw=100,$A=1e4,km=String.raw`<<(p) => { const url = String(p['netsuite_url'] || ''); if (!url || url.includes('{accountId}')) throw new Error('NetSuite is not connected yet: set the account ID so the system URL is https://<account>.suitetalk.api.netsuite.com/services/rest'); return url.replace(/\/+$/, ''); }>>`,Rm={Authorization:"Bearer <<netsuite_access_token>>",Accept:"application/json"},uw=String.raw`const has = (value) => value !== undefined && value !== null && value !== ''; const nsId = (value, name) => { const text = String(value ?? '').trim(); if (!/^-?\d+$/.test(text)) throw new Error(name + ' must be a NetSuite internal ID.'); return text; }; const nsDate = (value, name) => { const text = String(value ?? '').trim(); if (!/^\d{4}-\d{2}-\d{2}$/.test(text)) throw new Error(name + ' must be a date in YYYY-MM-DD format.'); return text; }; const ref = (value, name) => ({ id: nsId(value, name) });`,_he=String.raw`const str = (value) => (value === undefined || value === null || value === '' ? null : String(value)); const num = (value) => (value === undefined || value === null || value === '' ? null : Number(value)); const bool = (value) => value === 'T' || value === true; const ids = (value) => (value === undefined || value === null || value === '' ? [] : String(value).split(',').map((part) => part.trim()).filter(Boolean)); const status = (value) => (value ? String(value).replace(/^[^:]*:\s*/, '') : null);`,yL=String.raw`const stripLinks = (value) => { if (Array.isArray(value)) return value.map(stripLinks); if (value && typeof value === 'object') { const result = {}; for (const [key, entry] of Object.entries(value)) { if (key !== 'links') result[key] = stripLinks(entry); } return result; } return value; };`,Bhe={type:"integer",minimum:1,maximum:$A,description:`Maximum number of records to return (max ${$A}). Defaults to ${lw}. The result always reports the full match count in total, so use maxResults 1 to count. Prefer filters over large values: big results can exceed an AI client's tool output limit.`},vhe={type:"boolean",description:"Only return active records. Defaults to false (inactive records are included)."},Qhe={type:"string",description:"Optional subsidiary internal ID to filter by."},The={type:"string",description:"Optional earliest transaction date as YYYY-MM-DD."},Dhe={type:"string",description:"Optional latest transaction date as YYYY-MM-DD."},khe={type:"object",description:"Optional extra NetSuite REST field values merged into the record body as-is, e.g. custom fields like { custentity_region: 'EMEA' } or references like { terms: { id: '2' } }. Fields that this tool's own inputs set are rejected; use those inputs instead.",properties:{},additionalProperties:!0},PA=t=>({input:"activeOnly",kind:"flag",clause:`${t}.isinactive = 'F'`,schema:vhe}),LA=t=>({input:"subsidiaryId",kind:"id",clause:`${t}.subsidiary = $`,schema:Qhe}),aw=[{input:"fromDate",kind:"date",clause:"t.trandate >= TO_DATE('$', 'YYYY-MM-DD')",schema:The},{input:"toDate",kind:"date",clause:"t.trandate <= TO_DATE('$', 'YYYY-MM-DD')",schema:Dhe}];function Rhe(t){let e=`p[${JSON.stringify(t.input)}]`;if(t.kind==="flag")return`if (${e} === true || ${e} === 'true') where.push(${JSON.stringify(t.clause)});`;let[r,n]=t.clause.split("$");if(t.kind==="enum")return`if (has(${e})) { const allowed = ${JSON.stringify(t.values)}; if (!allowed.includes(String(${e}))) throw new Error(${JSON.stringify(`${t.input} must be one of: ${t.values.join(", ")}.`)}); where.push(${JSON.stringify(r)} + String(${e}) + ${JSON.stringify(n)}); }`;if(t.kind==="prefix")return`if (has(${e})) { const text = String(${e}).trim(); if (!/^[A-Za-z0-9._-]{1,40}$/.test(text)) throw new Error(${JSON.stringify(`${t.input} may only contain letters, digits, dots, underscores and hyphens.`)}); where.push(${JSON.stringify(r)} + text + ${JSON.stringify(n)}); }`;let i=t.kind==="id"?"nsId":"nsDate";return`if (has(${e})) where.push(${JSON.stringify(r)} + ${i}(${e}, ${JSON.stringify(t.input)}) + ${JSON.stringify(n)});`}function ya({id:t,name:e,shortName:r,instruction:n,stepId:i,collection:o,select:s,baseWhere:a=[],orderBy:c,filters:l=[],properties:u={},required:d=[],mapRow:A}){let p=typeof s=="string"?JSON.stringify(s):s.js,h=`<<(p) => { ${uw} const where = ${JSON.stringify(a)}; ${l.map(Rhe).join(" ")} return JSON.stringify({ q: ${p} + (where.length ? ' WHERE ' + where.join(' AND ') : '') + ${JSON.stringify(` ORDER BY ${c}`)} }); }>>`;return{id:t,name:e,shortName:r,instruction:`${n} Rows are ordered by internal ID. If more than ${$A} rows match, narrow with the filters or page with the SuiteQL query tool (ORDER BY id, WHERE id > last id).`,inputSchema:{type:"object",properties:{...u,maxResults:Bhe,...Object.fromEntries(l.map(f=>[f.input,f.schema]))},...d.length>0?{required:d}:{},additionalProperties:!1},steps:[{id:i,instruction:"Run the SuiteQL query page by page.",config:{type:"request",systemId:FA,url:`${km}/query/v1/suiteql`,method:"POST",headers:{...Rm,"Content-Type":"application/json",Prefer:"transient"},queryParams:{limit:"1000",offset:"<<offset>>"},body:h,pagination:{type:"offsetBased",pageSize:"1000",stopCondition:`(response, pageInfo, sourceData) => { if (sourceData && ["offset", "limit", "page"].some((key) => sourceData[key] !== undefined)) throw new Error("offset, limit and page are not inputs of this tool: use maxResults and the filters."); const page = response && response.data ? response.data : {}; const merged = pageInfo && pageInfo.mergedResult && Array.isArray(pageInfo.mergedResult.items) ? pageInfo.mergedResult.items.length : 0; const max = Math.min(Math.max(Math.floor(Number(sourceData && sourceData.maxResults)) || ${lw}, 1), ${$A}); return page.hasMore !== true || merged >= max; }`}}}],outputTransform:`(sourceData) => { ${_he} const raw = sourceData.${i} ? sourceData.${i}.data : undefined; const pages = Array.isArray(raw) ? raw : (raw ? [raw] : []); const items = pages.flatMap((page) => (page && Array.isArray(page.items) ? page.items : [])); const last = pages.length ? pages[pages.length - 1] : {}; const max = Math.min(Math.max(Math.floor(Number(sourceData.maxResults)) || ${lw}, 1), ${$A}); const rows = items.slice(0, max).map(${A}).map((row) => Object.fromEntries(Object.entries(row).filter((entry) => entry[1] !== null))); const total = last && last.totalResults !== undefined ? Number(last.totalResults) : items.length; return { total, returned: rows.length, hasMore: total > rows.length, ${o}: rows }; }`}}function Kr({id:t,name:e,shortName:r,instruction:n,stepId:i,recordType:o,mode:s,properties:a,required:c,body:l,replaceSublist:u}){let d=[...new Set(Array.from(l.matchAll(/record\.([A-Za-z0-9_]+)\s*=/g)).map(p=>p[1]))],A=s==="create"?`/record/v1/${o}`:`/record/v1/${o}/<<(p) => { ${uw} return nsId(p.internalId, 'internalId'); }>>`;return{id:t,name:e,shortName:r,instruction:n,inputSchema:{type:"object",properties:{...s==="update"?{internalId:{type:"string",description:`Internal ID of the ${o} to update.`}}:{},...a,fields:khe},required:s==="update"?["internalId",...c]:c,additionalProperties:!1},steps:[{id:i,instruction:`${s==="create"?"Create":"Update"} the ${o} record.`,modify:!0,config:{type:"request",systemId:FA,url:`${km}${A}`,method:s==="create"?"POST":"PATCH",headers:{...Rm,"Content-Type":"application/json","X-NetSuite-idempotency-key":"<<() => crypto.randomUUID()>>"},...u?{queryParams:{replace:`<<(p) => (Array.isArray(p[${JSON.stringify(u.input)}]) && p[${JSON.stringify(u.input)}].length > 0 ? ${JSON.stringify(u.sublist)} : undefined)>>`}}:{},body:`<<(p) => { ${uw} const record = {}; ${l} if (p.fields && typeof p.fields === 'object' && !Array.isArray(p.fields)) { const managed = ${JSON.stringify(d)}; const reserved = Object.keys(p.fields).filter((key) => managed.includes(key)); if (reserved.length > 0) throw new Error('fields may not set ' + reserved.join(', ') + ': use this tool\\'s own inputs for them.'); Object.assign(record, p.fields); } if (Object.keys(record).length === 0) throw new Error('Provide at least one field to ${s}.'); return JSON.stringify(record); }>>`,captureHttpResponse:!0}}],outputTransform:s==="create"?`(sourceData) => { const step = sourceData.${i} || {}; const location = step.http && step.http.headers ? String(step.http.headers.location || '') : ''; const match = location.match(/\\/record\\/v1\\/[^/]+\\/([^/?#]+)/); if (!match) throw new Error('NetSuite did not return the location of the new ${o}.'); return { id: decodeURIComponent(match[1]), recordType: '${o}' }; }`:`(sourceData) => ({ id: String(sourceData.internalId).trim(), recordType: '${o}', updated: true })`}}var EL=String.raw`const lines = Array.isArray(p.lines) ? p.lines : []; let balance = 0; const items = lines.map((line, index) => { const amount = Number(line && line.amount); if (!Number.isFinite(amount) || amount <= 0) throw new Error('lines[' + index + '].amount must be a positive number.'); if (line.type !== 'debit' && line.type !== 'credit') throw new Error("lines[" + index + "].type must be 'debit' or 'credit'."); balance += line.type === 'debit' ? amount : -amount; const item = { account: ref(line.accountId, 'lines[' + index + '].accountId') }; item[line.type] = amount; if (has(line.memo)) item.memo = String(line.memo); if (has(line.departmentId)) item.department = ref(line.departmentId, 'lines[' + index + '].departmentId'); if (has(line.classId)) item.class = ref(line.classId, 'lines[' + index + '].classId'); if (has(line.locationId)) item.location = ref(line.locationId, 'lines[' + index + '].locationId'); if (has(line.entityId)) item.entity = ref(line.entityId, 'lines[' + index + '].entityId'); return item; }); if (lines.length > 0 && Math.abs(balance) > 0.005) throw new Error('Journal lines must balance: debits minus credits is ' + balance.toFixed(2) + '.'); if (items.length > 0) record.line = { items };`,IL=String.raw`if (has(p.subsidiaryId)) record.subsidiary = ref(p.subsidiaryId, 'subsidiaryId'); if (has(p.date)) record.tranDate = nsDate(p.date, 'date'); if (has(p.memo)) record.memo = String(p.memo); if (has(p.currencyId)) record.currency = ref(p.currencyId, 'currencyId'); if (has(p.externalId)) record.externalId = String(p.externalId);`,CL={type:"object",properties:{accountId:{type:"string",description:"GL account internal ID."},type:{type:"string",enum:["debit","credit"]},amount:{type:"number",description:"Positive amount."},memo:{type:"string",description:"Optional line memo."},departmentId:{type:"string",description:"Optional department internal ID."},classId:{type:"string",description:"Optional class internal ID."},locationId:{type:"string",description:"Optional location internal ID."},entityId:{type:"string",description:"Optional customer, vendor or employee internal ID for the line."}},required:["accountId","type","amount"],additionalProperties:!1},bL=t=>({subsidiaryId:{type:"string",description:t==="create"?"Subsidiary internal ID. Required in OneWorld accounts.":"Optional new subsidiary internal ID."},date:{type:"string",description:t==="create"?"Transaction date as YYYY-MM-DD.":"Optional new transaction date as YYYY-MM-DD."},memo:{type:"string",description:"Journal entry memo."},currencyId:{type:"string",description:"Optional currency internal ID."},externalId:{type:"string",description:"Optional external ID."}}),_m=String.raw`if (p.isPerson === true || p.isPerson === 'true') record.isPerson = true; if (p.isPerson === false || p.isPerson === 'false') record.isPerson = false; if (has(p.entityId)) record.entityId = String(p.entityId); if (has(p.companyName)) record.companyName = String(p.companyName); if (has(p.firstName)) record.firstName = String(p.firstName); if (has(p.lastName)) record.lastName = String(p.lastName); if (has(p.subsidiaryId)) record.subsidiary = ref(p.subsidiaryId, 'subsidiaryId'); if (has(p.email)) record.email = String(p.email); if (has(p.phone)) record.phone = String(p.phone); if (has(p.currencyId)) record.currency = ref(p.currencyId, 'currencyId'); if (has(p.externalId)) record.externalId = String(p.externalId); if (p.isInactive === true || p.isInactive === 'true') record.isInactive = true; if (p.isInactive === false || p.isInactive === 'false') record.isInactive = false;`;function Bm(t){return{companyName:{type:"string",description:`Company name of the ${t}.`},isPerson:{type:"boolean",description:`True when the ${t} is an individual; then set firstName and lastName.`},firstName:{type:"string",description:"First name for an individual."},lastName:{type:"string",description:"Last name for an individual."},entityId:{type:"string",description:`${t==="customer"?"Customer":"Vendor"} ID. Omit when auto-numbering assigns it.`},subsidiaryId:{type:"string",description:"Primary subsidiary internal ID. Required on create in OneWorld accounts."},email:{type:"string",description:"Email address."},phone:{type:"string",description:"Phone number."},currencyId:{type:"string",description:"Primary currency internal ID."},externalId:{type:"string",description:"Optional external ID."}}}var vm={isInactive:{type:"boolean",description:"Set true to inactivate, false to reactivate."}},Qm=String.raw`if (Array.isArray(p.subsidiaryIds) && p.subsidiaryIds.length > 0) record.subsidiary = { items: p.subsidiaryIds.map((value, index) => ref(value, 'subsidiaryIds[' + index + ']')) }; if (p.includeChildren === true || p.includeChildren === 'true') record.includeChildren = true; if (p.includeChildren === false || p.includeChildren === 'false') record.includeChildren = false;`,kL={subsidiaryIds:{type:"array",items:{type:"string"},description:"Subsidiary internal IDs the record is available in. On update the list replaces the current subsidiaries."},includeChildren:{type:"boolean",description:"Also make the record available to child subsidiaries."}},dw=["AcctPay","AcctRec","Bank","COGS","CredCard","DeferExpense","DeferRevenue","Equity","Expense","FixedAsset","Income","LongTermLiab","NonPosting","OthAsset","OthCurrAsset","OthCurrLiab","OthExpense","OthIncome","Stat","UnbilledRec"],SL=String.raw`if (has(p.acctNumber)) record.acctNumber = String(p.acctNumber); if (has(p.acctName)) record.acctName = String(p.acctName); if (has(p.acctType)) record.acctType = { id: String(p.acctType) }; if (has(p.parentId)) record.parent = ref(p.parentId, 'parentId'); if (has(p.description)) record.description = String(p.description); if (has(p.currencyId)) record.currency = ref(p.currencyId, 'currencyId'); if (has(p.externalId)) record.externalId = String(p.externalId); if (p.isInactive === true || p.isInactive === 'true') record.isInactive = true; if (p.isInactive === false || p.isInactive === 'false') record.isInactive = false;`,wL={acctNumber:{type:"string",description:"Account number."},acctName:{type:"string",description:"Account name."},acctType:{type:"string",enum:dw,description:"NetSuite account type."},parentId:{type:"string",description:"Optional parent account internal ID."},description:{type:"string",description:"Optional description."},currencyId:{type:"string",description:"Optional currency internal ID (bank and credit card accounts)."},externalId:{type:"string",description:"Optional external ID."},...kL},_L=String.raw`if (has(p.name)) record.name = String(p.name); if (has(p.parentId)) record.parent = ref(p.parentId, 'parentId'); if (has(p.externalId)) record.externalId = String(p.externalId); if (p.isInactive === true || p.isInactive === 'true') record.isInactive = true; if (p.isInactive === false || p.isInactive === 'false') record.isInactive = false;`,BL={name:{type:"string",description:"Department name."},parentId:{type:"string",description:"Optional parent department internal ID."},externalId:{type:"string",description:"Optional external ID."},...kL},Tm=t=>String.raw`if (has(p.${t})) record.entity = ref(p.${t}, '${t}'); if (has(p.subsidiaryId)) record.subsidiary = ref(p.subsidiaryId, 'subsidiaryId'); if (has(p.date)) record.tranDate = nsDate(p.date, 'date'); if (has(p.dueDate)) record.dueDate = nsDate(p.dueDate, 'dueDate'); if (has(p.memo)) record.memo = String(p.memo); if (has(p.currencyId)) record.currency = ref(p.currencyId, 'currencyId'); if (has(p.termsId)) record.terms = ref(p.termsId, 'termsId'); if (has(p.departmentId)) record.department = ref(p.departmentId, 'departmentId'); if (has(p.classId)) record.class = ref(p.classId, 'classId'); if (has(p.locationId)) record.location = ref(p.locationId, 'locationId'); if (has(p.externalId)) record.externalId = String(p.externalId);`,Dm=t=>({subsidiaryId:{type:"string",description:t==="create"?"Optional subsidiary internal ID; defaults to the entity's subsidiary.":"Optional new subsidiary internal ID."},date:{type:"string",description:t==="create"?"Transaction date as YYYY-MM-DD.":"Optional new transaction date as YYYY-MM-DD."},dueDate:{type:"string",description:"Optional due date as YYYY-MM-DD."},memo:{type:"string",description:"Optional memo."},currencyId:{type:"string",description:"Optional currency internal ID."},termsId:{type:"string",description:"Optional payment terms internal ID."},departmentId:{type:"string",description:"Optional header department internal ID."},classId:{type:"string",description:"Optional header class internal ID."},locationId:{type:"string",description:"Optional header location internal ID."},externalId:{type:"string",description:"Optional external ID."}}),RL=String.raw`if (has(line.departmentId)) item.department = ref(line.departmentId, 'lines[' + index + '].departmentId'); if (has(line.classId)) item.class = ref(line.classId, 'lines[' + index + '].classId'); if (has(line.locationId)) item.location = ref(line.locationId, 'lines[' + index + '].locationId');`,vL=String.raw`if (Array.isArray(p.lines) && p.lines.length > 0) record.item = { items: p.lines.map((line, index) => { const item = { item: ref(line && line.itemId, 'lines[' + index + '].itemId') }; if (has(line.quantity)) { const quantity = Number(line.quantity); if (!Number.isFinite(quantity)) throw new Error('lines[' + index + '].quantity must be a number.'); item.quantity = quantity; } if (has(line.rate)) { const rate = Number(line.rate); if (!Number.isFinite(rate)) throw new Error('lines[' + index + '].rate must be a number.'); item.rate = rate; } if (has(line.amount)) { const amount = Number(line.amount); if (!Number.isFinite(amount)) throw new Error('lines[' + index + '].amount must be a number.'); item.amount = amount; } if (has(line.description)) item.description = String(line.description); if (has(line.taxCodeId)) item.taxCode = ref(line.taxCodeId, 'lines[' + index + '].taxCodeId'); ${RL} return item; }) };`,QL={type:"object",properties:{itemId:{type:"string",description:"Item internal ID."},quantity:{type:"number",description:"Optional quantity. Defaults to 1."},rate:{type:"number",description:"Optional unit price; defaults to the item price."},amount:{type:"number",description:"Optional line amount."},description:{type:"string",description:"Optional line description."},taxCodeId:{type:"string",description:"Optional tax code internal ID."},departmentId:{type:"string",description:"Optional department internal ID."},classId:{type:"string",description:"Optional class internal ID. Some accounts ignore line classes on invoices; check the saved record."},locationId:{type:"string",description:"Optional location internal ID."}},required:["itemId"],additionalProperties:!1},TL=String.raw`if (Array.isArray(p.lines) && p.lines.length > 0) record.expense = { items: p.lines.map((line, index) => { const amount = Number(line && line.amount); if (!Number.isFinite(amount) || amount <= 0) throw new Error('lines[' + index + '].amount must be a positive number.'); const item = { account: ref(line.accountId, 'lines[' + index + '].accountId'), amount }; if (has(line.memo)) item.memo = String(line.memo); ${RL} return item; }) };`,DL={type:"object",properties:{accountId:{type:"string",description:"Expense account internal ID."},amount:{type:"number",description:"Positive amount."},memo:{type:"string",description:"Optional line memo."},departmentId:{type:"string",description:"Optional department internal ID."},classId:{type:"string",description:"Optional class internal ID."},locationId:{type:"string",description:"Optional location internal ID."}},required:["accountId","amount"],additionalProperties:!1},vc="Re-running this tool creates another record; it is not idempotent.",Nhe=[ya({id:"netsuite-list-accounts",name:"List NetSuite chart of accounts",shortName:"Chart of accounts",instruction:"Lists general ledger accounts (the chart of accounts) from NetSuite with number, name, type, parent and subsidiaries. Useful for validating an imported chart of accounts.",stepId:"queryAccounts",collection:"accounts",select:"SELECT a.id, a.acctnumber, a.accountsearchdisplaynamecopy AS name, a.fullname, a.accttype, a.parent, a.subsidiary, cur.symbol AS currency, a.description, a.issummary, a.isinactive FROM account a LEFT JOIN currency cur ON cur.id = a.currency",orderBy:"a.id",filters:[PA("a"),{input:"accountType",kind:"enum",values:dw,clause:"a.accttype = '$'",schema:{type:"string",enum:dw,description:"Only accounts of this NetSuite account type, e.g. Bank or Expense."}},{input:"numberPrefix",kind:"prefix",clause:"a.acctnumber LIKE '$%'",schema:{type:"string",description:"Only accounts whose number starts with this value, e.g. 1000 or 60."}}],mapRow:"(row) => ({ id: row.id, number: str(row.acctnumber), name: str(row.name), fullName: str(row.fullname), type: str(row.accttype), parentId: str(row.parent), subsidiaryIds: ids(row.subsidiary), currency: str(row.currency), description: str(row.description), isSummary: bool(row.issummary), isInactive: bool(row.isinactive) })"}),ya({id:"netsuite-list-customers",name:"List NetSuite customers",shortName:"Customers",instruction:"Lists customer records from NetSuite with subsidiary, currency and open balance. Useful for verifying migrated AR master data.",stepId:"queryCustomers",collection:"customers",select:"SELECT c.id, c.entityid, c.companyname, c.isperson, c.firstname, c.lastname, c.email, c.phone, c.subsidiary, BUILTIN.DF(c.subsidiary) AS subsidiaryname, cur.symbol AS currency, c.balancesearch, c.overduebalancesearch, c.isinactive, TO_CHAR(c.datecreated, 'YYYY-MM-DD') AS datecreated, TO_CHAR(c.lastmodifieddate, 'YYYY-MM-DD') AS lastmodified FROM customer c LEFT JOIN currency cur ON cur.id = c.currency",orderBy:"c.id",filters:[PA("c"),LA("c")],mapRow:"(row) => ({ id: row.id, entityId: str(row.entityid), companyName: str(row.companyname), isPerson: bool(row.isperson), firstName: str(row.firstname), lastName: str(row.lastname), email: str(row.email), phone: str(row.phone), subsidiaryId: str(row.subsidiary), subsidiary: str(row.subsidiaryname), currency: str(row.currency), balance: num(row.balancesearch), overdueBalance: num(row.overduebalancesearch), isInactive: bool(row.isinactive), createdOn: str(row.datecreated), modifiedOn: str(row.lastmodified) })"}),ya({id:"netsuite-list-vendors",name:"List NetSuite vendors",shortName:"Vendors",instruction:"Lists vendor records from NetSuite with subsidiary, currency and balance. Useful for verifying migrated AP master data.",stepId:"queryVendors",collection:"vendors",select:"SELECT v.id, v.entityid, v.companyname, v.isperson, v.firstname, v.lastname, v.email, v.phone, v.subsidiary, BUILTIN.DF(v.subsidiary) AS subsidiaryname, cur.symbol AS currency, v.balance, v.isinactive, TO_CHAR(v.datecreated, 'YYYY-MM-DD') AS datecreated, TO_CHAR(v.lastmodifieddate, 'YYYY-MM-DD') AS lastmodified FROM vendor v LEFT JOIN currency cur ON cur.id = v.currency",orderBy:"v.id",filters:[PA("v"),LA("v")],mapRow:"(row) => ({ id: row.id, entityId: str(row.entityid), companyName: str(row.companyname), isPerson: bool(row.isperson), firstName: str(row.firstname), lastName: str(row.lastname), email: str(row.email), phone: str(row.phone), subsidiaryId: str(row.subsidiary), subsidiary: str(row.subsidiaryname), currency: str(row.currency), balance: num(row.balance), isInactive: bool(row.isinactive), createdOn: str(row.datecreated), modifiedOn: str(row.lastmodified) })"}),ya({id:"netsuite-list-journal-entries",name:"List NetSuite journal entries",shortName:"Journal entries",instruction:"Lists journal entry lines from NetSuite, one row per GL line and accounting book with journal, date, period, account, debit, credit and dimensions. Useful for verifying opening balances and postings at cutover.",stepId:"queryJournalLines",collection:"journalLines",select:"SELECT t.id AS journalid, t.tranid, TO_CHAR(t.trandate, 'YYYY-MM-DD') AS trandate, BUILTIN.DF(t.postingperiod) AS period, t.subsidiary, BUILTIN.DF(t.status) AS status, t.posting, t.memo AS journalmemo, cur.symbol AS currency, tl.id AS lineid, tal.accountingbook, tal.account, a.acctnumber, a.accountsearchdisplaynamecopy AS accountname, tal.debit, tal.credit, tl.memo, tl.department, tl.class, tl.location, tl.entity FROM transaction t JOIN transactionline tl ON tl.transaction = t.id JOIN transactionaccountingline tal ON tal.transaction = tl.transaction AND tal.transactionline = tl.id JOIN account a ON a.id = tal.account LEFT JOIN currency cur ON cur.id = t.currency",baseWhere:["t.type = 'Journal'"],orderBy:"t.id, tl.id, tal.accountingbook",filters:[...aw,LA("t")],mapRow:"(row) => ({ journalId: row.journalid, tranId: str(row.tranid), date: str(row.trandate), period: str(row.period), subsidiaryId: str(row.subsidiary), status: status(row.status), posting: bool(row.posting), journalMemo: str(row.journalmemo), currency: str(row.currency), line: num(row.lineid), accountingBookId: str(row.accountingbook), accountId: str(row.account), accountNumber: str(row.acctnumber), accountName: str(row.accountname), debit: num(row.debit), credit: num(row.credit), memo: str(row.memo), departmentId: str(row.department), classId: str(row.class), locationId: str(row.location), entityId: str(row.entity) })"}),ya({id:"netsuite-list-invoices",name:"List NetSuite invoices",shortName:"Invoices",instruction:"Lists customer invoices from NetSuite with customer, dates, status, total and amount due. Useful for verifying migrated open AR at go-live.",stepId:"queryInvoices",collection:"invoices",select:"SELECT t.id, t.tranid, t.entity, BUILTIN.DF(t.entity) AS customername, TO_CHAR(t.trandate, 'YYYY-MM-DD') AS trandate, TO_CHAR(t.duedate, 'YYYY-MM-DD') AS duedate, BUILTIN.DF(t.status) AS status, cur.symbol AS currency, t.foreigntotal, t.foreignamountunpaid, t.subsidiary, t.memo FROM transaction t LEFT JOIN currency cur ON cur.id = t.currency",baseWhere:["t.type = 'CustInvc'"],orderBy:"t.id",filters:[...aw,LA("t"),{input:"openOnly",kind:"flag",clause:"t.status = 'A'",schema:{type:"boolean",description:"Only return open (unpaid) invoices."}}],mapRow:"(row) => ({ id: row.id, tranId: str(row.tranid), customerId: str(row.entity), customer: str(row.customername), date: str(row.trandate), dueDate: str(row.duedate), status: status(row.status), currency: str(row.currency), total: num(row.foreigntotal), amountDue: num(row.foreignamountunpaid), subsidiaryId: str(row.subsidiary), memo: str(row.memo) })"}),ya({id:"netsuite-list-vendor-bills",name:"List NetSuite vendor bills",shortName:"Vendor bills",instruction:"Lists vendor bills from NetSuite with vendor, dates, status, approval status, total and amount due. Useful for verifying migrated open AP at go-live.",stepId:"queryBills",collection:"bills",select:"SELECT t.id, t.tranid, t.entity, BUILTIN.DF(t.entity) AS vendorname, TO_CHAR(t.trandate, 'YYYY-MM-DD') AS trandate, TO_CHAR(t.duedate, 'YYYY-MM-DD') AS duedate, BUILTIN.DF(t.status) AS status, BUILTIN.DF(t.approvalstatus) AS approvalstatus, cur.symbol AS currency, t.foreigntotal, t.foreignamountunpaid, t.subsidiary, t.memo FROM transaction t LEFT JOIN currency cur ON cur.id = t.currency",baseWhere:["t.type = 'VendBill'"],orderBy:"t.id",filters:[...aw,LA("t"),{input:"openOnly",kind:"flag",clause:"t.status = 'A'",schema:{type:"boolean",description:"Only return open bills (approved and not fully paid)."}}],mapRow:"(row) => ({ id: row.id, referenceNo: str(row.tranid), vendorId: str(row.entity), vendor: str(row.vendorname), date: str(row.trandate), dueDate: str(row.duedate), status: status(row.status), approvalStatus: str(row.approvalstatus), currency: str(row.currency), total: row.foreigntotal === undefined ? null : Math.abs(Number(row.foreigntotal)), amountDue: num(row.foreignamountunpaid), subsidiaryId: str(row.subsidiary), memo: str(row.memo) })"}),ya({id:"netsuite-list-dimensions",name:"List NetSuite departments, classes or locations",shortName:"Departments, classes, locations",instruction:"Lists department, class or location records from NetSuite with hierarchy and subsidiaries. Useful for validating the dimension setup after an implementation and for finding the internal IDs the write tools need.",stepId:"queryDimensions",collection:"records",properties:{dimension:{type:"string",enum:["department","class","location"],description:"Which dimension to list."}},required:["dimension"],select:{js:String.raw`'SELECT d.id, d.name, d.fullname, d.parent, d.subsidiary, d.includechildren, d.isinactive FROM ' + (() => { const table = { department: 'department', class: 'classification', location: 'location' }[String(p.dimension || '')]; if (!table) throw new Error("dimension must be 'department', 'class' or 'location'."); return table; })() + ' d'`},orderBy:"d.id",filters:[PA("d")],mapRow:"(row) => ({ id: row.id, name: str(row.name), fullName: str(row.fullname), parentId: str(row.parent), subsidiaryIds: ids(row.subsidiary), includeChildren: bool(row.includechildren), isInactive: bool(row.isinactive) })"}),ya({id:"netsuite-list-subsidiaries",name:"List NetSuite subsidiaries",shortName:"Subsidiaries",instruction:"Lists subsidiaries from NetSuite with hierarchy, country, base currency and elimination flag. Most create tools need a subsidiary ID from this list in OneWorld accounts.",stepId:"querySubsidiaries",collection:"subsidiaries",select:"SELECT s.id, s.name, s.fullname, s.parent, s.country, cur.symbol AS currency, s.iselimination, s.isinactive FROM subsidiary s LEFT JOIN currency cur ON cur.id = s.currency",orderBy:"s.id",filters:[PA("s")],mapRow:"(row) => ({ id: row.id, name: str(row.name), fullName: str(row.fullname), parentId: str(row.parent), country: str(row.country), currency: str(row.currency), isElimination: bool(row.iselimination), isInactive: bool(row.isinactive) })"}),{id:"netsuite-suiteql-query",name:"Run a NetSuite SuiteQL query",shortName:"SuiteQL query",instruction:"Runs a read-only SuiteQL SELECT query against NetSuite, for any record type, join or aggregate outside the prebuilt lists (for example items, employees, transaction lines or custom records). The workhorse tool for migration validation. Returns up to 1000 rows in one call with the total row count and hasMore; values are strings as NetSuite returns them.",inputSchema:{type:"object",properties:{query:{type:"string",description:`SuiteQL SELECT statement, e.g. "SELECT id, itemid, displayname FROM item WHERE isinactive = 'F' ORDER BY id". Dates come back in the user's date format; use TO_CHAR(field, 'YYYY-MM-DD') for ISO dates and BUILTIN.DF(field) for display names. For more than 1000 rows, page by key: ORDER BY id and add WHERE id > <last id>. Common columns: account (id, acctnumber, accountsearchdisplaynamecopy as the name, fullname, accttype, isinactive; there is no acctname column), customer (id, entityid, companyname, email, subsidiary, balancesearch, isinactive), vendor (id, entityid, companyname, email, subsidiary, balance, isinactive), transaction (id, tranid, type, trandate, entity, status, foreigntotal, foreignamountunpaid, subsidiary). Alias tables and qualify columns: FROM transaction t ... t.subsidiary works, an unqualified subsidiary fails.`},maxResults:{type:"integer",minimum:1,maximum:1e3,description:"Maximum number of rows to return (max 1000). Defaults to 100."}},required:["query"],additionalProperties:!1},steps:[{id:"runSuiteQl",instruction:"Run the SuiteQL query.",config:{type:"request",systemId:FA,url:`${km}/query/v1/suiteql`,method:"POST",headers:{...Rm,"Content-Type":"application/json",Prefer:"transient"},queryParams:{limit:"<<(p) => Math.min(Math.max(Math.floor(Number(p.maxResults)) || 100, 2), 1000)>>",offset:"0"},body:String.raw`<<(p) => { const query = String(p.query || '').trim(); if (!/^(select|with)\b/i.test(query)) throw new Error('query must be a SuiteQL SELECT statement.'); return JSON.stringify({ q: query }); }>>`}}],outputTransform:`(sourceData) => { ${yL} const data = sourceData.runSuiteQl && sourceData.runSuiteQl.data ? sourceData.runSuiteQl.data : {}; const items = Array.isArray(data.items) ? data.items : []; const max = Math.min(Math.max(Math.floor(Number(sourceData.maxResults)) || 100, 1), 1000); const records = stripLinks(items.slice(0, max)); const total = data.totalResults !== undefined ? Number(data.totalResults) : items.length; return { total, returned: records.length, hasMore: total > records.length, records }; }`},{id:"netsuite-get-record",name:"Get a NetSuite record",shortName:"Get record",instruction:"Fetches one NetSuite record of any type by internal ID or external ID through the REST record API, including its sublists such as transaction lines. Useful for inspecting a record in full before or after a write.",inputSchema:{type:"object",properties:{recordType:{type:"string",description:'REST record type, e.g. "customer", "vendor", "invoice", "vendorbill", "journalentry", "account", "department" or a custom record like "customrecord_x".'},internalId:{type:"string",description:"Internal ID of the record."},externalId:{type:"string",description:"External ID of the record, used when internalId is not set."},expandSubResources:{type:"boolean",description:"Include sublists and subrecords inline. Defaults to true."}},required:["recordType"],additionalProperties:!1},steps:[{id:"getRecord",instruction:"Fetch the record from the REST record API.",config:{type:"request",systemId:FA,url:`${km}/record/v1/<<(p) => { const type = String(p.recordType || '').trim().toLowerCase(); if (!/^[a-z][a-z0-9_]*$/.test(type)) throw new Error('recordType must contain only letters, numbers and underscores.'); return type; }>>/<<(p) => { if (p.internalId !== undefined && p.internalId !== null && p.internalId !== '') { const id = String(p.internalId).trim(); if (!/^-?\\d+$/.test(id)) throw new Error('internalId must be a NetSuite internal ID.'); return id; } if (p.externalId !== undefined && p.externalId !== null && p.externalId !== '') return 'eid:' + encodeURIComponent(String(p.externalId)); throw new Error('Provide internalId or externalId.'); }>>`,method:"GET",headers:Rm,queryParams:{expandSubResources:"<<(p) => (p.expandSubResources === false || p.expandSubResources === 'false' ? 'false' : 'true')>>"}}}],outputTransform:`(sourceData) => { ${yL} const record = sourceData.getRecord ? sourceData.getRecord.data : undefined; if (!record || typeof record !== 'object') throw new Error('NetSuite returned no record.'); return { record: stripLinks(record) }; }`},Kr({id:"netsuite-create-journal-entry",name:"Create NetSuite journal entry",shortName:"Create journal entry",instruction:`Creates a journal entry in NetSuite through the REST record API. Debit and credit lines must balance. Returns the new internal ID. ${vc}`,stepId:"createJournalEntry",recordType:"journalentry",mode:"create",properties:{...bL("create"),lines:{type:"array",description:"Journal lines. Debit and credit totals must balance.",items:CL}},required:["date","lines"],body:`${IL} if (!Array.isArray(p.lines) || p.lines.length < 2) throw new Error('lines must contain at least two journal lines.'); ${EL}`}),Kr({id:"netsuite-update-journal-entry",name:"Update NetSuite journal entry",shortName:"Update journal entry",instruction:"Updates an existing NetSuite journal entry by internal ID. Only the provided fields change. When lines are provided they replace all existing lines and must balance. Entries in closed periods refuse updates.",stepId:"updateJournalEntry",recordType:"journalentry",mode:"update",properties:{...bL("update"),lines:{type:"array",description:"Optional replacement lines. When set, they replace every existing line and must balance.",items:CL}},required:[],body:`${IL} if (Array.isArray(p.lines) && p.lines.length < 2) throw new Error('lines must contain at least two journal lines; omit lines to keep the current ones.'); ${EL}`,replaceSublist:{input:"lines",sublist:"line"}}),Kr({id:"netsuite-create-vendor",name:"Create NetSuite vendor",shortName:"Create vendor",instruction:`Creates a vendor record in NetSuite. OneWorld accounts need a subsidiaryId. Omit entityId when auto-numbering assigns it. ${vc}`,stepId:"createVendor",recordType:"vendor",mode:"create",properties:Bm("vendor"),required:[],body:`if (!has(p.companyName) && !((p.isPerson === true || p.isPerson === 'true') && has(p.lastName))) throw new Error('Provide companyName, or isPerson with lastName.'); ${_m}`}),Kr({id:"netsuite-update-vendor",name:"Update NetSuite vendor",shortName:"Update vendor",instruction:"Updates an existing NetSuite vendor by internal ID. Only the provided fields change; set isInactive to inactivate or reactivate it.",stepId:"updateVendor",recordType:"vendor",mode:"update",properties:{...Bm("vendor"),...vm},required:[],body:_m}),Kr({id:"netsuite-create-customer",name:"Create NetSuite customer",shortName:"Create customer",instruction:`Creates a customer record in NetSuite. OneWorld accounts need a subsidiaryId. Omit entityId when auto-numbering assigns it. ${vc}`,stepId:"createCustomer",recordType:"customer",mode:"create",properties:Bm("customer"),required:[],body:`if (!has(p.companyName) && !((p.isPerson === true || p.isPerson === 'true') && has(p.lastName))) throw new Error('Provide companyName, or isPerson with lastName.'); ${_m}`}),Kr({id:"netsuite-update-customer",name:"Update NetSuite customer",shortName:"Update customer",instruction:"Updates an existing NetSuite customer by internal ID. Only the provided fields change; set isInactive to inactivate or reactivate it.",stepId:"updateCustomer",recordType:"customer",mode:"update",properties:{...Bm("customer"),...vm},required:[],body:_m}),Kr({id:"netsuite-create-account",name:"Create NetSuite GL account",shortName:"Create GL account",instruction:`Creates a general ledger account in NetSuite's chart of accounts. ${vc}`,stepId:"createAccount",recordType:"account",mode:"create",properties:wL,required:["acctName","acctType"],body:`if (!has(p.acctName) || !has(p.acctType)) throw new Error('acctName and acctType are required.'); ${SL} ${Qm}`}),Kr({id:"netsuite-update-account",name:"Update NetSuite GL account",shortName:"Update GL account",instruction:"Updates an existing NetSuite GL account by internal ID. Only the provided fields change; set isInactive to inactivate or reactivate it. Accounts with transactions may refuse a type change.",stepId:"updateAccount",recordType:"account",mode:"update",properties:{...wL,...vm},required:[],body:`${SL} ${Qm}`}),Kr({id:"netsuite-create-invoice",name:"Create NetSuite invoice",shortName:"Create invoice",instruction:`Creates a customer invoice in NetSuite with item lines. Item, tax and posting rules of the account apply. ${vc}`,stepId:"createInvoice",recordType:"invoice",mode:"create",properties:{customerId:{type:"string",description:"Customer internal ID."},...Dm("create"),lines:{type:"array",description:"Item lines.",items:QL}},required:["customerId","lines"],body:`if (!Array.isArray(p.lines) || p.lines.length === 0) throw new Error('lines must contain at least one item line.'); ${Tm("customerId")} ${vL}`}),Kr({id:"netsuite-update-invoice",name:"Update NetSuite invoice",shortName:"Update invoice",instruction:"Updates an existing NetSuite invoice by internal ID. Only the provided fields change. When lines are provided they replace all existing item lines. Paid invoices and closed periods may refuse updates.",stepId:"updateInvoice",recordType:"invoice",mode:"update",properties:{customerId:{type:"string",description:"Optional new customer internal ID."},...Dm("update"),lines:{type:"array",description:"Optional replacement item lines; they replace every existing item line.",items:QL}},required:[],body:`if (Array.isArray(p.lines) && p.lines.length === 0) throw new Error('lines must contain at least one item line; omit lines to keep the current ones.'); ${Tm("customerId")} ${vL}`,replaceSublist:{input:"lines",sublist:"item"}}),Kr({id:"netsuite-create-vendor-bill",name:"Create NetSuite vendor bill",shortName:"Create vendor bill",instruction:`Creates a vendor bill in NetSuite with expense lines. Approval routing of the account applies. ${vc}`,stepId:"createVendorBill",recordType:"vendorbill",mode:"create",properties:{vendorId:{type:"string",description:"Vendor internal ID."},referenceNo:{type:"string",description:"Optional vendor invoice reference number."},...Dm("create"),lines:{type:"array",description:"Expense lines.",items:DL}},required:["vendorId","lines"],body:`if (!Array.isArray(p.lines) || p.lines.length === 0) throw new Error('lines must contain at least one expense line.'); ${Tm("vendorId")} if (has(p.referenceNo)) record.tranId = String(p.referenceNo); ${TL}`}),Kr({id:"netsuite-update-vendor-bill",name:"Update NetSuite vendor bill",shortName:"Update vendor bill",instruction:"Updates an existing NetSuite vendor bill by internal ID. Only the provided fields change. When lines are provided they replace all existing expense lines. Paid bills and closed periods may refuse updates.",stepId:"updateVendorBill",recordType:"vendorbill",mode:"update",properties:{vendorId:{type:"string",description:"Optional new vendor internal ID."},referenceNo:{type:"string",description:"Optional vendor invoice reference number."},...Dm("update"),lines:{type:"array",description:"Optional replacement expense lines; they replace every existing expense line.",items:DL}},required:[],body:`if (Array.isArray(p.lines) && p.lines.length === 0) throw new Error('lines must contain at least one expense line; omit lines to keep the current ones.'); ${Tm("vendorId")} if (has(p.referenceNo)) record.tranId = String(p.referenceNo); ${TL}`,replaceSublist:{input:"lines",sublist:"expense"}}),Kr({id:"netsuite-create-department",name:"Create NetSuite department",shortName:"Create department",instruction:`Creates a department in NetSuite. Without subsidiaryIds NetSuite assigns the parent subsidiary. ${vc}`,stepId:"createDepartment",recordType:"department",mode:"create",properties:BL,required:["name"],body:`if (!has(p.name)) throw new Error('name is required.'); ${_L} ${Qm}`}),Kr({id:"netsuite-update-department",name:"Update NetSuite department",shortName:"Update department",instruction:"Updates an existing NetSuite department by internal ID. Only the provided fields change; set isInactive to inactivate or reactivate it.",stepId:"updateDepartment",recordType:"department",mode:"update",properties:{...BL,...vm},required:[],body:`${_L} ${Qm}`})],cw={sap_s4hana:{bundleId:"sap_s4hana",templateId:"sap_s4hana",systemId:"sap_s4hana",displayName:"SAP S/4HANA",description:"Read business partners, sales orders, products and purchase orders from SAP.",systemUrl:She,credentialHint:"Works instantly with SAP's demo data. Add your own key later for your live system.",requiredCredentialKeys:["api_key"],demoCredentials:{api_key:"K8reTgiKCCaqvAPWC4cOjqqiLdLE8dqz"},mcpServer:{name:"sap",displayName:"SAP S/4HANA",description:"Business partners, sales orders, products and purchase orders from SAP."},installMcpServer:!0,agentLaunch:{userPrompt:"I just installed the SAP S/4HANA bundle. What can I do with it?",nextSteps:"Your first reply must be short: SAP is connected to free demo data and works right now, so offer to run one tool immediately as proof. No credential collection is needed to start. If they want their own data: their own free key comes from https://api.sap.com (SAP Business Accelerator Hub), collected and saved directly with a connect field, never via the Connections page; the system URL can then be switched to their own SAP host. Do not list the installed tools, do not add tips or explain SAP concepts unless asked."},tools:[{id:"sap-list-business-partners",name:"List SAP business partners",shortName:"Business partners",instruction:"Lists business partners (customers, suppliers, contacts) from SAP S/4HANA. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{filter:{type:"string",description:`Optional OData $filter expression, e.g. "BusinessPartnerCategory eq '2'" for organizations.`},maxResults:{type:"integer",description:"Maximum number of business partners to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"fetchBusinessPartners",instruction:"Fetch business partners, paging through results with $skip.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/API_BUSINESS_PARTNER/A_BusinessPartner",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$top:"<<pageSize>>",$skip:"<<offset>>",$filter:"<<filter>>",$select:"BusinessPartner,BusinessPartnerFullName,BusinessPartnerCategory,BusinessPartnerGrouping,CreationDate"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const d = (v) => { if (typeof v !== 'string' || !v.startsWith('/Date(')) return v; const n = parseInt(v.slice(6), 10); return Number.isFinite(n) ? new Date(n).toISOString().slice(0, 10) : v; }; const rows = (sourceData.fetchBusinessPartners?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 200); return { total: rows.length, businessPartners: rows.map((r) => ({ id: r.BusinessPartner, name: r.BusinessPartnerFullName, category: r.BusinessPartnerCategory, grouping: r.BusinessPartnerGrouping, createdOn: d(r.CreationDate) })) }; }"},{id:"sap-list-sales-orders",name:"List SAP sales orders",shortName:"Sales orders",instruction:"Lists sales orders from SAP S/4HANA with their net amount, currency and sold-to party. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{filter:{type:"string",description:`Optional OData $filter expression, e.g. "SalesOrderType eq 'OR'" or "TotalNetAmount gt 1000".`},maxResults:{type:"integer",description:"Maximum number of sales orders to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"fetchSalesOrders",instruction:"Fetch sales orders, paging through results with $skip.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/API_SALES_ORDER_SRV/A_SalesOrder",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$top:"<<pageSize>>",$skip:"<<offset>>",$filter:"<<filter>>",$select:"SalesOrder,SalesOrderType,SoldToParty,TotalNetAmount,TransactionCurrency,SalesOrderDate,OverallSDProcessStatus"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const d = (v) => { if (typeof v !== 'string' || !v.startsWith('/Date(')) return v; const n = parseInt(v.slice(6), 10); return Number.isFinite(n) ? new Date(n).toISOString().slice(0, 10) : v; }; const rows = (sourceData.fetchSalesOrders?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 200); return { total: rows.length, salesOrders: rows.map((r) => ({ id: r.SalesOrder, type: r.SalesOrderType, soldToParty: r.SoldToParty, netAmount: Number(r.TotalNetAmount), currency: r.TransactionCurrency, orderDate: d(r.SalesOrderDate), status: r.OverallSDProcessStatus })) }; }"},{id:"sap-list-products",name:"List SAP products",shortName:"Products",instruction:"Lists products (materials) from SAP S/4HANA with their type, group and base unit. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{filter:{type:"string",description:`Optional OData $filter expression, e.g. "ProductType eq 'FERT'" for finished goods.`},maxResults:{type:"integer",description:"Maximum number of products to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"fetchProducts",instruction:"Fetch products, paging through results with $skip.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/API_PRODUCT_SRV/A_Product",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$top:"<<pageSize>>",$skip:"<<offset>>",$filter:"<<filter>>",$expand:"to_Description",$select:"Product,ProductType,ProductGroup,BaseUnit,GrossWeight,WeightUnit,CreationDate,to_Description/Language,to_Description/ProductDescription"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const d = (v) => { if (typeof v !== 'string' || !v.startsWith('/Date(')) return v; const n = parseInt(v.slice(6), 10); return Number.isFinite(n) ? new Date(n).toISOString().slice(0, 10) : v; }; const nameOf = (r) => { const list = r.to_Description?.results ?? []; const hit = list.find((x) => x.Language === 'EN') ?? list[0]; return hit?.ProductDescription; }; const rows = (sourceData.fetchProducts?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 200); return { total: rows.length, products: rows.map((r) => ({ id: r.Product, name: nameOf(r), type: r.ProductType, group: r.ProductGroup, baseUnit: r.BaseUnit, grossWeight: Number(r.GrossWeight), weightUnit: r.WeightUnit, createdOn: d(r.CreationDate) })) }; }"},{id:"sap-list-purchase-orders",name:"List SAP purchase orders",shortName:"Purchase orders",instruction:"Lists purchase orders from SAP S/4HANA with their supplier, currency and creation date. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{filter:{type:"string",description:`Optional OData $filter expression, e.g. "PurchaseOrderType eq 'NB'" for standard orders.`},maxResults:{type:"integer",description:"Maximum number of purchase orders to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"fetchPurchaseOrders",instruction:"Fetch purchase orders, paging through results with $skip.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/API_PURCHASEORDER_PROCESS_SRV/A_PurchaseOrder",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$top:"<<pageSize>>",$skip:"<<offset>>",$filter:"<<filter>>",$select:"PurchaseOrder,PurchaseOrderType,Supplier,PurchaseOrderDate,DocumentCurrency,CreatedByUser"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const d = (v) => { if (typeof v !== 'string' || !v.startsWith('/Date(')) return v; const n = parseInt(v.slice(6), 10); return Number.isFinite(n) ? new Date(n).toISOString().slice(0, 10) : v; }; const rows = (sourceData.fetchPurchaseOrders?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 200); return { total: rows.length, purchaseOrders: rows.map((r) => ({ id: r.PurchaseOrder, type: r.PurchaseOrderType, supplier: r.Supplier, orderDate: d(r.PurchaseOrderDate), currency: r.DocumentCurrency, createdBy: r.CreatedByUser })) }; }"},{id:"sap-list-gl-accounts",name:"List SAP chart of accounts",shortName:"Chart of accounts",instruction:"Lists general ledger accounts (the chart of accounts) from SAP S/4HANA. Supports an optional OData $filter, e.g. by ChartOfAccounts.",inputSchema:{type:"object",properties:{filter:{type:"string",description:`Optional OData $filter expression, e.g. "ChartOfAccounts eq 'YCOA'" or "GLAccountType eq 'X'".`},maxResults:{type:"integer",description:"Maximum number of accounts to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"fetchGLAccounts",instruction:"Fetch GL accounts, paging through results with $skip.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/API_GLACCOUNTINCHARTOFACCOUNTS_SRV/A_GLAccountInChartOfAccounts",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$top:"<<pageSize>>",$skip:"<<offset>>",$filter:`<<(p) => p.filter ? "ChartOfAccounts ne '' and (" + p.filter + ")" : "ChartOfAccounts ne ''">>`,$expand:"to_Text",$select:"GLAccount,ChartOfAccounts,GLAccountType,GLAccountGroup,IsBalanceSheetAccount,AccountIsBlockedForPosting,to_Text/Language,to_Text/GLAccountName"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const nameOf = (r) => { const list = r.to_Text?.results ?? []; const hit = list.find((x) => x.Language === 'EN') ?? list[0]; return hit?.GLAccountName; }; const rows = (sourceData.fetchGLAccounts?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 200); return { total: rows.length, accounts: rows.map((r) => ({ account: r.GLAccount, name: nameOf(r), chartOfAccounts: r.ChartOfAccounts, type: r.GLAccountType, group: r.GLAccountGroup, isBalanceSheet: r.IsBalanceSheetAccount, blockedForPosting: r.AccountIsBlockedForPosting })) }; }"},{id:"sap-list-billing-documents",name:"List SAP billing documents",shortName:"Billing documents",instruction:"Lists billing documents (invoices, credit memos) from SAP S/4HANA with amount, currency and sold-to party. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{filter:{type:"string",description:`Optional OData $filter expression, e.g. "BillingDocumentType eq 'F2'" or "TotalNetAmount gt 1000".`},maxResults:{type:"integer",description:"Maximum number of billing documents to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"fetchBillingDocuments",instruction:"Fetch billing documents, paging through results with $skip.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/API_BILLING_DOCUMENT_SRV/A_BillingDocument",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$top:"<<pageSize>>",$skip:"<<offset>>",$filter:"<<filter>>",$select:"BillingDocument,BillingDocumentType,SoldToParty,TotalNetAmount,TransactionCurrency,BillingDocumentDate"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const d = (v) => { if (typeof v !== 'string' || !v.startsWith('/Date(')) return v; const n = parseInt(v.slice(6), 10); return Number.isFinite(n) ? new Date(n).toISOString().slice(0, 10) : v; }; const rows = (sourceData.fetchBillingDocuments?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 200); return { total: rows.length, billingDocuments: rows.map((r) => ({ id: r.BillingDocument, type: r.BillingDocumentType, soldToParty: r.SoldToParty, netAmount: Number(r.TotalNetAmount), currency: r.TransactionCurrency, date: d(r.BillingDocumentDate) })) }; }"},{id:"sap-list-journal-entry-items",name:"List SAP journal entry line items",shortName:"Journal entries",instruction:"Lists journal entry line items (accounting document items) from SAP S/4HANA with company code, GL account, amount and posting date. Filter by CompanyCode, FiscalYear or PostingDate to keep results focused. Useful for verifying opening balances at cutover.",inputSchema:{type:"object",properties:{filter:{type:"string",description:`Optional OData $filter expression, e.g. "CompanyCode eq '1010' and FiscalYear eq '2026'".`},maxResults:{type:"integer",description:"Maximum number of line items to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"fetchJournalItems",instruction:"Fetch accounting document line items, paging through results with $skip.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/API_OPLACCTGDOCITEMCUBE_SRV/A_OperationalAcctgDocItemCube",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$top:"<<pageSize>>",$skip:"<<offset>>",$filter:"<<filter>>",$select:"AccountingDocument,CompanyCode,FiscalYear,GLAccount,AmountInCompanyCodeCurrency,PostingDate"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const d = (v) => { if (typeof v !== 'string' || !v.startsWith('/Date(')) return v; const n = parseInt(v.slice(6), 10); return Number.isFinite(n) ? new Date(n).toISOString().slice(0, 10) : v; }; const rows = (sourceData.fetchJournalItems?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 200); return { total: rows.length, journalItems: rows.map((r) => ({ document: r.AccountingDocument, companyCode: r.CompanyCode, fiscalYear: r.FiscalYear, account: r.GLAccount, amount: Number(r.AmountInCompanyCodeCurrency), postingDate: d(r.PostingDate) })) }; }"},{id:"sap-query-odata",name:"Query any SAP OData service",shortName:"Query any service",instruction:"Queries any SAP S/4HANA OData service and entity set (for example API_PRODUCT_SRV/A_ProductDescription or API_SALES_ORDER_SRV/A_SalesOrderItem) with optional $select and $filter. The workhorse tool for data checks beyond the prebuilt lists.",inputSchema:{type:"object",properties:{servicePath:{type:"string",description:'Service and entity set in SERVICE/EntitySet form, e.g. "API_SALES_ORDER_SRV/A_SalesOrderItem".'},select:{type:"string",description:"Comma-separated OData $select field list. Omit for all fields."},filter:{type:"string",description:"Optional OData $filter expression."},maxResults:{type:"integer",description:"Maximum number of records to return. Defaults to 100."}},required:["servicePath"],additionalProperties:!0},steps:[{id:"queryService",instruction:"Query the requested OData service and entity set.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/<<servicePath>>",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$select:"<<select>>",$filter:"<<filter>>",$top:"<<pageSize>>",$skip:"<<offset>>"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 100; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const rows = (sourceData.queryService?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 100); return { total: rows.length, records: rows.map((r) => { const { __metadata, ...rest } = r; return rest; }) }; }"}]},sage100:{bundleId:"sage100",templateId:"sage100",systemId:"sage100",displayName:"Sage 100",description:"Connect on-premises Sage 100 through the superglue Secure Gateway, with a guided setup playbook and a connection test against the Business Object Interface.",systemUrl:"script://runner/vbs32",credentialHint:"Your assistant first helps you connect a Secure Gateway on your Sage 100 server, then collects your Sage company and user details.",requiredCredentialKeys:["sage_home","sage_company","sage_user","sage_password"],mcpServer:{name:"sage-100",displayName:"Sage 100",description:"Sage 100 Business Object Interface access through the Secure Gateway."},installMcpServer:!1,playbook:{id:"sage100-native-integration",name:"Sage 100 Native Integration (BOI)",whenToRun:"Use when connecting a Sage 100 installation to superglue, testing that connection, or building tools that read or write Sage 100 data through the Business Object Interface.",inputs:"A Sage 100 installation on a Windows machine the user can access; a superglue API key for the gateway; the Sage company code, a Sage user with module access, and the path to the MAS90\\Home directory; the business outcome once connected.",instructions:"First check /org/tunnels for a connected gateway with a runner target. If none is connected, guide the user step by step: download the Windows gateway from https://downloads.superglue.cloud/superglue-gateway-windows.exe onto the machine where Sage 100 and Workstation Setup are installed (the gateway must run there, ProvideX.Script is a local 32-bit COM class), create a config.yaml next to it with a tunnel_id, the server_url ending in /ws/tunnels (wss://api.superglue.cloud/ws/tunnels for hosted superglue), an API key from the API Keys page, and the line enable_script_runner: true, then run the executable. That flag is required: it opts the gateway into running Sage scripts (it is code execution on their machine, so it is off by default), and it is what registers the built-in runner target. No targets section is needed. If a tunnel is connected but has no runner target, the gateway is either missing enable_script_runner: true or is an outdated build; have the user add the flag and restart, or download the current gateway from the same URL. When the tunnel with the runner target appears, attach it to the Sage 100 connection with tools.writeConnection (tunnel with that tunnelId) and keep the URL script://runner/vbs32. Collect sage_home (full path to the MAS90\\Home directory, for example C:\\Sage\\Sage100\\MAS90\\Home, not the MAS90 directory itself), sage_company, sage_user and sage_password through the secure credential form. Then run the Test Sage 100 connection tool once and interpret the result: retVal 0 failures carry the Sage reason in sLastErrorMsg (wrong credentials, missing role access, wrong company code); COM error 0x80040154 means the gateway is not running on a machine with Sage 100 Workstation Setup; a no-license message means all Sage user seats are in use. For new capabilities, build tools whose steps use the script protocol with VBScript in the body: log on with SY_Session, set module context before touching data (nSetDate with YYYYMMDD dates, nSetModule, nLookupTask, nSetProgram), use _svc service objects for reads and _bus business objects for writes, and always release the session with nCleanup and DropObject so the license seat frees up. For reads, set each key segment with nSetKeyValue then nFind for a single record, or browse with nMoveFirst and nMoveNext, and read each field with nGetValue passing a variable that receives the value. To write a document that has lines, such as a sales order, get the header _bus object, set the header fields, get its oLines object, call nAddLine, set the line fields, then call nWrite on the header to commit the header and its lines together. A write fails with a lock error if the record is open in the Sage desktop or held by another session, so report the lock message instead of retrying. Each running script briefly consumes a Sage user seat. Ask for explicit approval before any script that writes to Sage, and warn that records open in the Sage desktop UI cause lock errors.",completionCriteria:"The gateway is connected, the installed Sage 100 system has the tunnel attached and credentials saved, and the connection test returned company data from Sage 100. Any additional requested capability works end to end, with writes explicitly approved before they ran."},agentLaunch:{userPrompt:"I just installed the Sage 100 integration. Help me connect my Sage 100 server.",nextSteps:"Your first reply must be short: one line confirming the Sage 100 integration and setup playbook are installed, then start the connection flow. Check /org/tunnels for a connected gateway with a runner target first. If none exists, walk the user through it one step at a time: download https://downloads.superglue.cloud/superglue-gateway-windows.exe onto the Windows machine where Sage 100 is installed and Workstation Setup has run, create a config.yaml next to it with tunnel_id, server_url (wss://api.superglue.cloud/ws/tunnels for hosted superglue), an API key from the API Keys page, and the line enable_script_runner: true, then run it. That flag is required: it opts the gateway into running scripts on their machine (off by default because it is code execution) and is what registers the runner target. No targets are needed in the config. If a tunnel is connected but has no runner target, the gateway is missing enable_script_runner: true or is an outdated build: have the user add the flag and restart, or download the current one from the same URL. Wait for the user to confirm, then verify the tunnel appears and attach it to the Sage 100 connection with tools.writeConnection tunnel, keeping the URL script://runner/vbs32. Use connect with the connection id and fields to save sage_home (full path to the MAS90\\Home directory, for example C:\\Sage\\Sage100\\MAS90\\Home, not MAS90 itself), sage_company (for example ABC for the demo company), sage_user and sage_password. Never send the user to the Connections page. Then run the Test Sage 100 connection tool once. If it fails, explain the specific cause in plain language before retrying. Mention that each test briefly uses one Sage user license seat. Do not list tools or add tips unless asked."},tools:[{id:"sage100-test-connection",name:"Test Sage 100 connection",shortName:"Connection test",instruction:"Logs on to Sage 100 through the Secure Gateway, opens the configured company, and reads the first customer record to verify the Business Object Interface end to end. Briefly consumes one Sage user license seat.",steps:[{id:"testConnection",instruction:"Run a VBScript through the gateway script runner that logs on via SY_Session, sets A/R module context, and reads the first customer.",config:{type:"request",systemId:"sage100",url:"<<sage100_url>>",method:"POST",body:["Option Explicit","On Error Resume Next","Dim oScript, oSS, oCust, retVal, custNo, custName, today",'Set oScript = CreateObject("ProvideX.Script")','FailOnErr "CREATE", " (Sage 100 Workstation Setup has not registered ProvideX.Script on this machine; the gateway must run on a prepared Sage 100 machine)"','oScript.Init "<<sage100_sage_home>>"','FailOnErr "INIT", " (sage_home must be the full path to the MAS90\\Home directory, not MAS90 itself)"','Set oSS = oScript.NewObject("SY_Session")','FailOnErr "SESSION", ""','retVal = oSS.nSetUser("<<sage100_sage_user>>", "<<sage100_sage_password>>")','FailOnErr "LOGON", ""',"If retVal = 0 Then",' WScript.Echo "LOGON FAILED: " & oSS.sLastErrorMsg'," WScript.Quit 1","End If",'retVal = oSS.nSetCompany("<<sage100_sage_company>>")','FailOnErr "COMPANY", ""',"If retVal = 0 Then",' WScript.Echo "COMPANY FAILED: " & oSS.sLastErrorMsg'," oSS.nCleanup"," oSS.DropObject"," WScript.Quit 1","End If",'today = Year(Date) & Right("0" & Month(Date), 2) & Right("0" & Day(Date), 2)','retVal = oSS.nSetDate("A/R", today)','FailOnErr "DATE", ""','retVal = oSS.nSetModule("A/R")','FailOnErr "MODULE", ""','retVal = oSS.nSetProgram(oSS.nLookupTask("AR_Customer_ui"))','FailOnErr "TASK", ""',"If retVal = 0 Then",' WScript.Echo "TASK FAILED: " & oSS.sLastErrorMsg'," oSS.nCleanup"," oSS.DropObject"," WScript.Quit 1","End If",'Set oCust = oScript.NewObject("AR_Customer_svc", oSS)','FailOnErr "CUSTOMER OBJECT", ""',"retVal = oCust.nMoveFirst()",'FailOnErr "READ", ""',"If retVal = 0 Then",' WScript.Echo "READ FAILED: " & oCust.sLastErrorMsg',"Else",' custNo = "" : custName = ""',' retVal = oCust.nGetValue("CustomerNo$", custNo)',' retVal = oCust.nGetValue("CustomerName$", custName)',' FailOnErr "READ VALUE", " (ByRef value marshalling failed)"',' WScript.Echo "CONNECTED - company <<sage100_sage_company>>, first customer: " & custNo & " / " & custName',"End If","oCust.DropObject","oSS.nCleanup","oSS.DropObject","If retVal = 0 Then WScript.Quit 1","","Sub FailOnErr(stage, hint)"," If Err.Number <> 0 Then",' WScript.Echo stage & " FAILED: [0x" & Hex(Err.Number) & "] " & Err.Description & hint'," WScript.Quit 1"," End If","End Sub"].join(`
|
|
113
|
+
${t.slice(t.length-n)}`}function AAe(t){return t instanceof Error?t.message:typeof t=="string"?t:typeof t=="object"&&t!==null&&"message"in t?String(t.message):String(t)}function pAe(t,e){if(!e||Object.keys(e).length===0)return{};let r=/file::([^,\s)}\]"']+)/g,n=typeof t=="string"?t:JSON.stringify(t||{}),i=[...new Set([...n.matchAll(r)].map(o=>{let s=o[1];return s.endsWith(".raw")?s=s.slice(0,-4):s.endsWith(".base64")?s=s.slice(0,-7):s.endsWith(".extracted")&&(s=s.slice(0,-10)),s}))];return Object.fromEntries(i.flatMap(o=>e[o]?[[o,e[o]]]:[]))}function wP(t){if(t.op==="remove"||t.value===void 0||typeof t.value!="string")return t;if(t.path==="/inputSchema"||t.path==="/outputSchema"||t.path.startsWith("/inputSchema/properties/")||t.path.startsWith("/outputSchema/properties/")||t.path.match(/^\/steps\/\d+\/config\/pagination$/)||t.path.match(/^\/steps\/\d+\/config\/headers$/)||t.path.match(/^\/steps\/\d+\/config\/queryParams$/))try{return{...t,value:JSON.parse(t.value)}}catch{return t}return t}function hAe(t){return t.map(e=>wP(e))}function fAe(t,e){t||(t=""),e||(e=""),/^(https?|postgres(ql)?|ftp(s)?|sftp|smb|file):\/\//i.test(t)||(t=`https://${t}`);let r=t.endsWith("/")?t.slice(0,-1):t,n=e.startsWith("/")?e.slice(1):e;return`${r}/${n}`}var gAe=new Set(["data","stepResults","toolPayload","rawData","transformedData"]),mAe=8e4;function yAe(t,e=mAe){if(t==null)return t;let r=t;if(typeof t=="string"){if(t.length<=e)return t;try{r=JSON.parse(t)}catch{return{_truncated:!0,_message:"String result too large to parse",_size:t.length}}}if(typeof r!="object")return r;let n=0,i=0,o=(s,a=0)=>{if(a>20||s===null||typeof s!="object")return s;if(Array.isArray(s))return s.map(l=>o(l,a+1));let c={};for(let[l,u]of Object.entries(s))if(gAe.has(l)&&u!==null&&typeof u=="object"){let d=JSON.stringify(u);if(d.length>e){i+=d.length;try{let{jsonString:A,truncatedProps:p}=(0,_de.default)(d,e);c[l]=JSON.parse(A),n+=p.length}catch{c[l]=u}}else c[l]=u}else c[l]=o(u,a+1);return c};try{if(JSON.stringify(r).length<=e)return r;let a=o(r);return n>0&&typeof a=="object"&&a!==null&&(a._note=`Result truncated: ${n} items omitted (original ${i} characters)`),a}catch{return{_truncated:!0,_message:"Result too large to display"}}}function EAe(t){if(!t.steps)return[];let e=new Set;for(let r of t.steps)r.config&&(0,wde.isRequestConfig)(r.config)&&r.config.systemId&&e.add(r.config.systemId);return Array.from(e)}function mm(t,e,r=new WeakSet){if(typeof t=="string"){e.push(t);return}if(!(!t||typeof t!="object")&&!r.has(t)){if(r.add(t),Array.isArray(t)){for(let n of t)mm(n,e,r);return}for(let n of Object.values(t))mm(n,e,r)}}function IAe(t){let e=[];for(let r of t.matchAll(/<<([\s\S]*?)>>/g)){let n=r[1].trim();n&&e.push(n)}for(let r of t.matchAll(/{{\s*([^{}\s]+)\s*}}/g)){let n=r[1].trim();n&&e.push(n)}return e}function CAe(t,e){let r=[];mm(t,r);let n=`${e}_`,i=new Set;for(let o of r)for(let s of IAe(o)){if(!s.startsWith(n))continue;let a=s.slice(n.length);!a||a==="url"||!M.CREDENTIAL_KEY_PATTERN.test(a)||i.add(a)}return[...i]}var bAe=/^\s*(async\s+)?(\([^)]*\)|[a-zA-Z_$][a-zA-Z0-9_$]*)\s*=>/,SAe=new Set(["sg_auth_email","sg_auth_jwt"]);function wAe({config:t,systemId:e}){let r=[];mm(t,r);let n=e?`${e}_`:null,i=new Set;for(let l of r)for(let u of l.matchAll(/<<([\s\S]*?)>>/g)){let d=u[1].trim();d&&(n&&d.startsWith(n)||bAe.test(d)||SAe.has(d)||i.add(d))}if(i.size===0)return null;let o=[...i].map(l=>`<<${l}>>`).join(", "),s=`Unresolved placeholder${i.size===1?"":"s"} ${o}`;if(!n)return`${s}. Secret placeholders need systemId and the form <<systemId_secretName>>. Nothing was sent.`;let a=[...i].filter(l=>M.CREDENTIAL_KEY_PATTERN.test(l)).map(l=>`<<${n}${l}>>`),c=a.length>0?`Secret placeholders are namespaced by system: use ${a.join(", ")}.`:`Secret placeholders are namespaced by system as <<${n}secretName>>.`;return`${s}. ${c} Nothing was sent.`}function _Ae(t){return t.replace(/([a-z])([A-Z])|([A-Z]{2,})([A-Z][a-z])/g,"$1$3 $2$4").replace(/[_-]/g," ").replace(/\b\w/g,e=>e.toUpperCase()).replace(/\b(Id|Url|Api|Ui)\b/g,e=>e.toUpperCase())}});var TP=y(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.AGENT_CONTEXT_MEMORY_MESSAGE_ID_PREFIX=void 0;Mt.applyToolMutation=_P;Mt.mutateToolCallInMessages=vAe;Mt.buildStreamingAssistantMessage=BP;Mt.parseToolOutput=vP;Mt.parseAgentStreamEventLine=TAe;Mt.stopActiveTool=QP;Mt.appendContentToMessage=WS;Mt.updateMessageWithData=au;Mt.findAwaitingConfirmationToolCallIds=DAe;Mt.declineAwaitingConfirmationTools=kAe;Mt.findAndResumeMessageWithTool=RAe;Mt.serializeMessageForPersistence=OAe;Mt.isTurnContextBlockMessage=JS;Mt.normalizeAgentSessionForkMessages=UAe;Mt.normalizeAgentSessionImportMessages=MAe;Mt.createAgentTranscriptState=PAe;Mt.applyAgentStreamChunk=LAe;var BAe=pn(),Im=Ti();function _P(t,e){let r=e.frontendOutput!==void 0?e.frontendOutput:t.frontendOutput;return{...t,...e.input!==void 0?{input:e.input}:{},...e.result!==void 0?{result:e.result}:{},...e.status!==void 0?{status:e.status}:{},...e.startTime!==void 0?{startTime:e.startTime}:{},...e.endTime!==void 0?{endTime:e.endTime}:{},...e.error!==void 0?{error:e.error||void 0}:{},...r!==void 0?{frontendOutput:r}:{},...e.llmOutput!==void 0?{llmOutput:e.llmOutput}:{},...e.resultMetadata!==void 0?{resultMetadata:e.resultMetadata}:{},...e.confirmationState!==void 0?{confirmationState:e.confirmationState===null?void 0:e.confirmationState}:{},...e.confirmationData!==void 0?{confirmationData:e.confirmationData===null?void 0:e.confirmationData}:{}}}function vAe(t,e,r){return t.map(n=>{let i=!1,o=n.parts?.map(s=>s.type!=="tool"||!s.tool||s.tool.id!==e?s:(i=!0,{...s,tool:_P(s.tool,r)}));return i&&o?{...n,parts:o}:n})}function BP(t){return{id:t,content:"",role:"assistant",timestamp:new Date,parts:[{type:"content",content:"",id:"content-0"}],isStreaming:!0}}function QAe(){return{status:"declined",endTime:new Date,confirmationState:"declined",confirmationData:{reason:"new_user_message",message:"Rejected: the user sent a new message instead of confirming this action. The proposed changes were NOT applied."}}}function vP(t){if(!t)return null;if(typeof t=="string")try{let e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}return typeof t=="object"&&!Array.isArray(t)?t:null}function TAe(t){if(!t.startsWith("data: "))return null;try{let e=JSON.parse(t.slice(6));return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function QP(t){return t.status==="running"||t.status==="pending"||t.status==="awaiting_confirmation"?{...t,status:"stopped",endTime:new Date,confirmationState:void 0,confirmationData:void 0}:t}function WS(t,e){if(!e)return t;let r=[...t.parts||[]],n=r[r.length-1];return n?.type==="content"?r[r.length-1]={...n,content:(n.content||"")+e}:r.push({type:"content",content:e,id:`content-${r.length}`}),{...t,parts:r,content:""}}function au(t,e,r){if(t.id!==r.id)return t;switch(e.type){case"content":return WS(t,e.content||"");case"tool_call_start":{let n=t.parts?.find(l=>l.type==="tool"&&l.tool?.id===e.toolCall.id)?.tool,i=e.toolCall.input??n?.input,o=e.executionMode==="confirm"?"awaiting_confirmation":i?"running":"pending",s={...n,id:e.toolCall.id,name:e.toolCall.name,input:i,status:o,startTime:n?.startTime||new Date,...n?.confirmationState!==void 0?{confirmationState:n.confirmationState}:{},...n?.confirmationData!==void 0?{confirmationData:n.confirmationData}:{}},a=[...t.parts||[]],c=a.findIndex(l=>l.type==="tool"&&l.tool?.id===e.toolCall.id);return c===-1?a.push({type:"tool",tool:s,id:`tool-${e.toolCall.id}`}):a[c]={...a[c],tool:s},{...t,parts:a,content:""}}case"tool_call_input":{let n=i=>i.id===e.toolCall.id&&e.toolCall.input!==void 0?{...i,input:e.toolCall.input}:i;return{...t,parts:t.parts?.map(i=>i.type==="tool"&&i.tool?{...i,tool:n(i.tool)}:i)}}case"run_command_effect":{let n=e.effect;if(n?.kind!=="visual"&&n?.kind!=="checklist"||typeof e.toolCallId!="string")return t;let i=o=>{if(o.id!==e.toolCallId)return o;let s=vP(o.frontendOutput)??{},a=(s.effects??[]).filter(c=>c.id!==n.id);return{...o,frontendOutput:{...s,effects:[...a,n]}}};return{...t,parts:t.parts?.map(o=>o.type==="tool"&&o.tool?{...o,tool:i(o.tool)}:o)}}case"tool_call_update":{let n=t.parts?.map(i=>i.type==="tool"&&i.tool?.id===e.toolCall.id?{...i,tool:{...i.tool,executionTraceId:e.toolCall.executionTraceId??i.tool.executionTraceId,status:i.tool.status==="pending"?"running":i.tool.status}}:i)||[];return{...t,parts:n}}case"tool_call_complete":{let n=t.parts?.find(h=>h.type==="tool"&&h.tool?.id===e.toolCall.id)?.tool,i=n?.status==="completed"||n?.status==="declined",o=e.toolCall.result!==void 0||e.toolCall.frontendOutput!==void 0||e.toolCall.status!==void 0||e.toolCall.confirmationState!==void 0||e.toolCall.confirmationData!==void 0;if(i&&!o)return t;let s=null;try{s=typeof e.toolCall.frontendOutput=="string"?JSON.parse(e.toolCall.frontendOutput):e.toolCall.frontendOutput}catch{}let a=s?.success===!1&&s?.error,c=e.toolCall.result?.outcome,l=c==="failure"?"error":c==="rejected"?"declined":c==="aborted"?"stopped":c==="success"?"completed":void 0,u=e.toolCall.status||l||"completed";a&&u==="completed"&&(u="error");let d=u==="awaiting_confirmation",A={...e.toolCall.input!==void 0?{input:e.toolCall.input}:{},...e.toolCall.result!==void 0?{result:e.toolCall.result}:{},status:u,frontendOutput:e.toolCall.frontendOutput,llmOutput:e.toolCall.llmOutput,resultMetadata:e.toolCall.resultMetadata,error:c==="failure"?e.toolCall.result.error.message:a?s.error:null,endTime:d?void 0:new Date,...e.toolCall.confirmationState!==void 0?{confirmationState:e.toolCall.confirmationState}:{},...e.toolCall.confirmationData!==void 0?{confirmationData:e.toolCall.confirmationData}:{}},p=t.parts?.map(h=>h.type==="tool"&&h.tool?.id===e.toolCall.id?{...h,tool:{...h.tool,...A}}:h)||[];return{...t,parts:p}}case"done":{if(!t.isStreaming)return t;let n=(t.parts||[]).map(i=>i.type==="tool"&&i.tool&&i.tool.status!=="awaiting_confirmation"?{...i,tool:QP(i.tool)}:i);return{...t,isStreaming:!1,parts:n,content:""}}default:return t}}function DAe(t){let e=new Set;for(let r of t)for(let n of(0,Im.getMessageToolCalls)(r))n.status==="awaiting_confirmation"&&e.add(n.id);return[...e]}function kAe(t){let e=QAe();return t.map(r=>({...r,parts:r.parts?.map(n=>n.type==="tool"&&n.tool?.status==="awaiting_confirmation"?{...n,tool:{...n.tool,...e}}:n)}))}function RAe(t,e){let r=t.find(i=>i.parts?.some(o=>o.type==="tool"&&o.tool?.id===e));return r?{messages:t.map(i=>i.id===r.id?{...i,isStreaming:!0}:i),targetMessage:{...r,isStreaming:!0}}:{messages:t,targetMessage:null}}function NAe(t){return{id:t.id,name:t.name,status:t.status,input:t.input,result:t.result,frontendOutput:t.frontendOutput,llmOutput:t.llmOutput,resultMetadata:t.resultMetadata,error:t.error,startTime:t.startTime,endTime:t.endTime,confirmationState:t.confirmationState,confirmationData:t.confirmationData}}function OAe(t){let{isStreaming:e,tools:r,...n}=t;return JSON.parse((0,Im.safeStringify)({...n,...t.parts?{parts:t.parts.map(i=>i.type==="tool"&&i.tool?{...i,tool:NAe(i.tool)}:i)}:{}},0))}Mt.AGENT_CONTEXT_MEMORY_MESSAGE_ID_PREFIX="context-memory-";var xAe=["artifacts"];function JS(t){let e=t.contextType??"";return BAe.TURN_CONTEXT_BLOCK_TYPES.includes(e)||xAe.includes(e)}function UAe(t){return t.filter(e=>e.role!=="system"&&e.contextType!=="memory_notes"&&!JS(e)&&!e.id.startsWith(Mt.AGENT_CONTEXT_MEMORY_MESSAGE_ID_PREFIX)).map(e=>({...e,stale:void 0,isStreaming:void 0}))}function MAe(t){return t.filter(e=>!e.stale&&!e.isStreaming&&e.contextType!=="memory_notes"&&!JS(e)&&!!e.id)}function PAe(t=[],e=null){return{messages:t,assistantMessageId:e,outcome:"streaming"}}function Em(t,e){return(0,Im.getMessageToolCalls)(t).some(r=>r.id===e)}function su(t,e){let r=t.assistantMessageId?t.messages.find(i=>i.id===t.assistantMessageId):void 0;if(r)return{state:t,target:r};let n=BP(t.assistantMessageId??e.createAssistantMessageId());return{state:{...t,messages:[...t.messages,n],assistantMessageId:n.id},target:n}}function LAe(t,e,r){switch(e.type){case"system_message":{if(!e.systemMessage)return t;let n={id:e.systemMessage.id,role:"system",content:e.systemMessage.content,timestamp:new Date};return{...t,messages:[n,...t.messages]}}case"assistant_message_start":{if(!e.assistantMessageId)return t;let n=t.assistantMessageId?t.messages.find(o=>o.id===t.assistantMessageId):void 0;return t.messages.find(o=>o.id===e.assistantMessageId)?{...t,assistantMessageId:e.assistantMessageId,messages:t.messages.filter(o=>!n||n.id===e.assistantMessageId||o.id!==n.id).map(o=>o.id===e.assistantMessageId?{...o,isStreaming:!0}:o)}:n?{...t,assistantMessageId:e.assistantMessageId,messages:t.messages.map(o=>o.id===n.id?{...o,id:e.assistantMessageId,isStreaming:!0}:o)}:{...t,assistantMessageId:e.assistantMessageId}}case"context_message":{if(!e.contextMessage)return t;let n={id:e.contextMessage.id,role:"user",content:e.contextMessage.content,timestamp:new Date,...e.contextMessage.isHidden?{isHidden:!0}:{},...e.contextMessage.attachedFiles?.length?{attachedFiles:e.contextMessage.attachedFiles}:{}};return{...t,assistantMessageId:null,messages:[...t.messages.map(i=>i.id===t.assistantMessageId?{...i,isStreaming:!1}:i),n]}}case"context_usage":case"compaction_start":return t;case"compaction_complete":{if(!e.compaction)return t;let n=(0,Im.applyAgentCompactionToMessages)(t.messages,e.compaction),i=e.compaction.memoryMessage?t.assistantMessageId:null;return!i||!n.some(o=>o.id===i)?{...t,messages:n}:{...t,assistantMessageId:null,messages:n.map(o=>o.id===i?{...o,isStreaming:!1}:o)}}case"content":{let n=su(t,r);return{...n.state,messages:n.state.messages.map(i=>i.id===n.target.id?WS(i,e.content||""):i)}}case"error":{let n=su(t,r);return{...n.state,outcome:"failed",messages:n.state.messages.map(i=>i.id!==n.target.id?i:{...i,parts:[...i.parts||[],{type:"error",content:e.content,errorDetails:e.errorDetails,id:`error-${i.parts?.length??0}`}],isStreaming:!1})}}case"tool_call_start":case"tool_call_update":{if(!e.toolCall)return t;let n=e.type==="tool_call_start"?null:t.messages.find(o=>Em(o,e.toolCall.id))??null,i=n?{state:t,target:n}:su(t,r);return{...i.state,messages:i.state.messages.map(o=>au(o,e,i.target))}}case"run_command_effect":{let n=e.toolCallId;if(!n)return t;let i=t.messages.find(o=>Em(o,n));return i?{...t,messages:t.messages.map(o=>au(o,e,i))}:t}case"tool_call_input":{if(!e.toolCall)return t;let n=t.messages.find(i=>Em(i,e.toolCall.id));return n?{...t,messages:t.messages.map(i=>au(i,e,n))}:t}case"tool_call_complete":{if(!e.toolCall)return t;let n=t.messages.find(o=>Em(o,e.toolCall.id)),i=n?{state:t,target:n}:su(t,r);return{...i.state,messages:i.state.messages.map(o=>au(o,e,i.target))}}case"paused":{let n=su(t,r);return{...n.state,outcome:"paused",messages:n.state.messages.map(i=>i.id===n.target.id?{...i,isStreaming:!1}:i)}}case"done":{let n=su(t,r);return{...n.state,outcome:t.outcome==="failed"?"failed":"completed",messages:n.state.messages.map(i=>au(i,e,n.target))}}default:return t}}});var ZS=y(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.AGENT_SESSION_PERMISSIONS_METADATA_KEY=Di.AGENT_PERMISSION_SCOPE_TYPES=void 0;Di.readSessionPermissionGrants=$Ae;Di.httpOperationMatches=RP;Di.findCoveringGrant=GAe;Di.describePermission=VAe;Di.AGENT_PERMISSION_SCOPE_TYPES=["system_write","tool_run","connection_edit","access_edit","org_settings_edit","org_memory_edit","file_delete","browser_use"];Di.AGENT_SESSION_PERMISSIONS_METADATA_KEY="permissionGrants";function $Ae(t){let e=t[Di.AGENT_SESSION_PERMISSIONS_METADATA_KEY];return Array.isArray(e)?e:[]}function kP(t){let e=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*");return new RegExp(`^${e}$`,"i")}function DP(t,e){let r=t.replace(/\/+$/,"").split("/").slice(1),n=e.replace(/\/+$/,"").split("/").slice(1);for(let i=0;i<r.length;i++){let o=r[i];if(o==="**")return!0;if(i>=n.length||!kP(o).test(decodeURIComponent(n[i])))return!1}return r.length===n.length}function FAe(t,e){let r=e?.replace(/\/+$/,"");return r?t===r?"/":t.startsWith(`${r}/`)?t.slice(r.length):null:null}function RP(t,e){let r=t.trim(),n=r.indexOf(" ");if(n===-1)return!1;let i=r.slice(0,n).toUpperCase();if(i!=="*"&&i!==e.method.toUpperCase())return!1;let o=r.slice(n+1).trim(),s=FAe(e.path,e.basePath);return DP(o,e.path)||s!==null&&DP(o,s)}function jAe(t,e){return t.connectionId?t.connectionId===e.connectionId:t.host.toLowerCase()===e.host.toLowerCase()}function zAe(t,e){let r=t.trim();return e.kind==="http"?RP(r,e):r.includes(" ")?!1:r==="*"||e.name!==""&&kP(r).test(e.name)}function qAe(t,e){return(t.operations??[]).some(r=>zAe(r,e.operation))}function HAe(t,e){if(t.type!==e.type)return!1;switch(e.type){case"system_write":return jAe(t,e)&&qAe(t,e);case"tool_run":return t.toolIds.includes(e.toolId);case"connection_edit":{let{connectionIds:r}=t;return!r?.length||r.includes(e.connectionId)}default:return!0}}function GAe(t,e){return t.find(r=>HAe(r.scope,e))}function YAe(t){return t.kind==="http"?`${t.method.toUpperCase()} ${t.path}`:t.name||"an operation superglue cannot read"}function VAe(t){switch(t.type){case"system_write":{let e="operation"in t?YAe(t.operation):t.operations?.join(", ");return`system_write on ${t.connectionId??t.host}${e?` (${e})`:""}`}case"tool_run":return`tool_run on ${"toolId"in t?t.toolId:t.toolIds.join(", ")}`;case"connection_edit":{let e="connectionId"in t?[t.connectionId]:t.connectionIds;return`connection_edit${e?.length?` on ${e.join(", ")}`:""}`}default:return t.type}}});var Cm=y(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.PROJECT_LABEL_COLOR_PATTERN=Pt.PROJECT_LABEL_COLORS=Pt.PROJECT_LIMITS=Pt.PROJECT_TASK_STATUSES=Pt.PROJECT_RESOURCE_TYPES=void 0;Pt.isProjectResourceType=WAe;Pt.nextProjectLabelColor=JAe;Pt.projectResourceKey=ZAe;Pt.daysUntilTaskDue=OP;Pt.formatTaskDueDate=KAe;Pt.groupByContext=XAe;Pt.PROJECT_RESOURCE_TYPES=["file","tool"];function WAe(t){return Pt.PROJECT_RESOURCE_TYPES.includes(t)}Pt.PROJECT_TASK_STATUSES=["not_started","in_progress","waiting","done"];Pt.PROJECT_LIMITS={name:80,description:500,taskName:120,taskDescription:1e4,labelName:40,labels:50,taskLabels:10};Pt.PROJECT_LABEL_COLORS=["#6b7280","#ef4444","#f97316","#eab308","#22c55e","#14b8a6","#3b82f6","#6366f1","#a855f7","#ec4899"];Pt.PROJECT_LABEL_COLOR_PATTERN=/^#[0-9a-f]{6}$/;function JAe(t){let e=new Set(t.map(r=>r.color));return Pt.PROJECT_LABEL_COLORS.find(r=>!e.has(r))??Pt.PROJECT_LABEL_COLORS[t.length%Pt.PROJECT_LABEL_COLORS.length]}function ZAe(t){return`${t.type}:${t.id}`}function NP(t){let e=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date);return new Date(`${e}T00:00:00Z`)}function OP(t,e){let r=new Date(`${t}T00:00:00Z`);return Math.round((r.getTime()-NP(e).getTime())/864e5)}function KAe(t,e){let r=new Date(`${t}T00:00:00Z`),n=NP(e),i=OP(t,e);return i===0?"Due today":i===1?"Due tomorrow":i===-1?"Due yesterday":i<-1?`${-i} days overdue`:i<7?`Due ${r.toLocaleDateString(void 0,{weekday:"long",timeZone:"UTC"})}`:`Due ${r.toLocaleDateString(void 0,{day:"numeric",month:"short",timeZone:"UTC",...r.getUTCFullYear()===n.getUTCFullYear()?{}:{year:"numeric"}})}`}function XAe(t){let e=new Map;for(let r of t)e.set(r.context,[...e.get(r.context)??[],r]);return[...e].map(([r,n])=>({context:r,items:n})).sort((r,n)=>+!!r.context-+!!n.context)}});var bm=y(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.RESOURCE_KINDS=Cn.RESOURCE_DEFINITIONS=void 0;Cn.isResourceKind=epe;Cn.getResourceDefinition=tpe;Cn.getResourceAppPath=rpe;Cn.RESOURCE_DEFINITIONS={tool:{label:"Tool",pluralLabel:"Tools",collectionKey:"tools",appPath:"/tools",hasDetailPage:!0,memberDefaultPermission:"editor",pickerDefaultPermission:"editor"},credential:{label:"Connection",pluralLabel:"Connections",collectionKey:"credentials",appPath:"/connections",hasDetailPage:!0,pickerDefaultPermission:"viewer"},playbook:{label:"Playbook",pluralLabel:"Playbooks",collectionKey:"playbooks",appPath:"/brain/playbooks",hasDetailPage:!0,pickerDefaultPermission:"editor"},file:{label:"File",pluralLabel:"Files",collectionKey:"files",appPath:"/brain/files",hasDetailPage:!0,pickerDefaultPermission:"viewer"},project:{label:"Project",pluralLabel:"Projects",collectionKey:"projects",appPath:"/brain/projects",hasDetailPage:!0,pickerDefaultPermission:"viewer"}};Cn.RESOURCE_KINDS=Object.keys(Cn.RESOURCE_DEFINITIONS);function epe(t){return typeof t=="string"&&Object.prototype.hasOwnProperty.call(Cn.RESOURCE_DEFINITIONS,t)}function tpe(t){return Cn.RESOURCE_DEFINITIONS[t]}function rpe(t,e){let r=Cn.RESOURCE_DEFINITIONS[t];return r.hasDetailPage?`${r.appPath}/${encodeURIComponent(e)}`:r.appPath}});var PP=y(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});Sc.SDK_ERROR_DETAILS_SCHEMA=Sc.SDK_OUTPUT_CONTRACTS=void 0;Sc.toSdkJsonSchema=spe;var m=lc(),npe=Cm(),ipe=bm(),ope=pn();function spe({schema:t}){return m.z.toJSONSchema(t,{target:"draft-7",io:"output",unrepresentable:"any"})}var xP=m.z.looseObject({statusCode:m.z.number(),headers:m.z.record(m.z.string(),m.z.union([m.z.string(),m.z.array(m.z.string())])),omittedHeaderCount:m.z.number().optional()}),UP=m.z.looseObject({vfsPath:m.z.string(),storedBytes:m.z.number(),originalOutputBytes:m.z.number(),storageTruncated:m.z.boolean()}),MP=m.z.object({action:m.z.enum(["approve","reject","oauth_success","oauth_failure"]),source:m.z.enum(["user","automatic"])});function Jt(t){return m.z.looseObject({toolCallId:m.z.string(),toolName:m.z.string(),outcome:m.z.literal("success"),confirmation:MP.optional(),data:t})}var KS={http:xP.optional(),connection:m.z.looseObject({id:m.z.string(),name:m.z.string(),isOwner:m.z.boolean()}).optional().describe("The connection the call ran with."),auth:m.z.looseObject({applied:m.z.enum(["bearer","basic","explicit","none","unavailable"]),header:m.z.string().optional(),placeholders:m.z.array(m.z.string()),reason:m.z.string().optional()}).optional().describe("How authentication was sent: a default Bearer or Basic header, the request's own explicit placeholders, none, or unavailable with the reason. placeholders lists the connection's <<systemId_secretName>> strings."),secretPlaceholders:m.z.looseObject({keys:m.z.array(m.z.string()),resolved:m.z.boolean()}).optional()},ape=m.z.discriminatedUnion("protocol",[m.z.looseObject({protocol:m.z.enum(["postgres","odbc"]),data:m.z.array(m.z.record(m.z.string(),m.z.unknown())).describe("Returned database rows."),...KS}),m.z.looseObject({protocol:m.z.literal("mssql"),data:m.z.union([m.z.array(m.z.record(m.z.string(),m.z.unknown())),m.z.array(m.z.array(m.z.record(m.z.string(),m.z.unknown()))),m.z.looseObject({rowsAffected:m.z.array(m.z.number())})]).describe("One recordset, multiple recordsets, or affected row counts."),...KS}),m.z.looseObject({protocol:m.z.enum(ope.CONNECTION_PROTOCOLS.filter(t=>t!=="postgres"&&t!=="mssql"&&t!=="odbc")),data:m.z.unknown().describe("Complete protocol response payload. Preserve sibling fields, including files and metadata; do not unwrap a nested data field."),...KS})]),cpe=m.z.union([m.z.looseObject({tools:m.z.array(m.z.unknown()).describe("All tools from every tools/list page, each with name and inputSchema.")}),m.z.looseObject({result:m.z.looseObject({content:m.z.array(m.z.unknown()).optional(),structuredContent:m.z.unknown().optional(),isError:m.z.boolean().optional()}).describe("The tools/call result with content blocks and optional structuredContent.")})]),lpe=m.z.looseObject({url:m.z.string().describe("The requested URL."),status:m.z.number(),statusText:m.z.string(),headers:m.z.record(m.z.string(),m.z.string()),body:m.z.string().describe("Response body bytes, base64-encoded."),systemId:m.z.string().optional().describe("The system whose connection authenticated the request."),connection:m.z.looseObject({id:m.z.string(),name:m.z.string(),isOwner:m.z.boolean()}).optional().describe("The connection the request ran with.")}),upe=m.z.looseObject({stepId:m.z.string(),success:m.z.boolean(),data:m.z.unknown().optional(),error:m.z.string().nullable().optional(),http:xP.optional(),stepFileKeys:m.z.array(m.z.string()).optional()}),dpe=m.z.looseObject({toolId:m.z.string(),success:m.z.boolean(),run:m.z.looseObject({id:m.z.string()}).optional(),data:m.z.unknown().optional().describe("Tool output, determined by its output transform."),error:m.z.string().optional(),stepResults:m.z.array(upe),fileArtifacts:m.z.array(m.z.looseObject({fileKey:m.z.string(),filename:m.z.string(),contentType:m.z.string(),size:m.z.number(),downloadUrl:m.z.string().optional()})).optional(),warnings:m.z.array(m.z.string()).optional(),inputSchema:m.z.unknown().optional(),resultMetadata:UP.optional()}),Ape=Jt(m.z.looseObject({resource:m.z.looseObject({id:m.z.string(),name:m.z.string().optional(),path:m.z.string().optional(),version:m.z.union([m.z.number(),m.z.string()]).optional()}),created:m.z.boolean(),projectId:m.z.string().optional(),projectAttribution:m.z.looseObject({attached:m.z.boolean(),projectId:m.z.string(),projectName:m.z.string().optional(),resource:m.z.looseObject({type:m.z.enum(npe.PROJECT_RESOURCE_TYPES),id:m.z.string()}),error:m.z.string().optional()}).optional()}));Sc.SDK_OUTPUT_CONTRACTS={assignSessionToProject:{name:"SuperglueSessionProjectResult",schema:Jt(m.z.object({sessionId:m.z.string(),projectId:m.z.string().nullable()})),description:"Returns the saved session ID and project ID, or null when unassigned. Throws SuperglueError on failure."},callSystem:{name:"SuperglueCallSystemResult",schema:ape,description:"Returns the complete protocol payload in data, available HTTP metadata, the connection used, and how authentication was sent. Throws SuperglueError on failure; details contains the canonical result and unprojected execution output."},callMcp:{name:"SuperglueCallMcpResult",schema:cpe,description:"Returns { tools } when tool is omitted, or { result } from tools/call. Throws SuperglueError on HTTP, JSON-RPC, or result.isError failures; details.result.data contains statusCode, rpcError, or the failed result. On result.isError or invalid params, the error message ends with the called tool's input schema when it can be read; large schemas are shortened."},systemFetch:{name:"SuperglueSystemFetchResult",schema:lpe,description:"Returns the raw HTTP response: status, headers, and the base64 body. HTTP error statuses are returned, not thrown. Throws SuperglueError when the request cannot be authenticated or sent."},runTool:{name:"SuperglueRunToolResult",schema:dpe,description:"Returns successful tool output, step results, files, and available result reference. Throws SuperglueError on failure; details.result.data preserves this result shape with success: false, the error, and available run and step results. details.resultMetadata references the saved failed result when available."},writeResource:{name:"SuperglueWriteResult",schema:Ape,description:"Returns saved resource identity and path, creation status, and available project attribution. Throws SuperglueError on failure."},installBundle:{name:"SuperglueBundleInstallResult",schema:Jt(m.z.looseObject({bundleId:m.z.string(),system:m.z.looseObject({id:m.z.string(),name:m.z.string(),requiredCredentialKeys:m.z.array(m.z.string()),hasUserCredentials:m.z.boolean()}),tools:m.z.array(m.z.looseObject({id:m.z.string(),name:m.z.string().optional()})),mcpServer:m.z.looseObject({id:m.z.string(),name:m.z.string()}).optional(),playbook:m.z.looseObject({id:m.z.string(),name:m.z.string()}).optional()})),description:"Returns the installed system ID, tool, MCP server, and playbook identities, the secret names the user must supply, and whether the user has a complete connection. Throws SuperglueError on failure."},stopBackgroundJob:{name:"SuperglueStopBackgroundJobResult",schema:Jt(m.z.looseObject({job:m.z.looseObject({id:m.z.string(),status:m.z.string(),elapsedMs:m.z.number(),exitCode:m.z.number().optional()})})),description:"Returns the job's status, run time, and exit code after it ended, or status running when the stop is still in progress. Throws SuperglueError when the session has no such running job."},setToolState:{name:"SuperglueToolStateResult",schema:Jt(m.z.looseObject({resource:m.z.looseObject({id:m.z.string()}),action:m.z.enum(["set","reset"])})),description:"Returns the saved tool identity and state action. Throws SuperglueError on failure."},shareResource:{name:"SuperglueShareResult",schema:Jt(m.z.looseObject({resource:m.z.looseObject({kind:m.z.enum(ipe.RESOURCE_KINDS),id:m.z.string()})})),description:"Returns the shared resource identity. Throws SuperglueError on failure."},useChecklist:{name:"SuperglueChecklistResult",schema:Jt(m.z.strictObject({visible:m.z.boolean(),done:m.z.number(),total:m.z.number()})),description:"Returns whether the session checklist is visible and its completed and total milestone counts. The progress panel updates immediately. Throws SuperglueError on failure."},showVisual:{name:"SuperglueShowVisualResult",schema:Jt(m.z.looseObject({visualId:m.z.string(),check:m.z.looseObject({errors:m.z.array(m.z.string()),blockedRequests:m.z.array(m.z.string()),dataCalls:m.z.array(m.z.string()),contentHeight:m.z.number().optional(),timedOut:m.z.boolean()}).optional(),checkSkipped:m.z.string().optional(),screenshots:m.z.array(m.z.string()).optional()})),description:"Returns the visualId shown to the user. For a custom visual, check holds the test-browser result, and screenshots lists the labels of the screenshots attached to this command's result for you. Throws SuperglueError ETOOL when the visual fails its check; error.details.result.data.check then holds the errors."},notifyUser:{name:"SuperglueNotifyResult",schema:Jt(m.z.looseObject({nextStepIds:m.z.array(m.z.string())})),description:"Returns the nextStepIds of the saved actions, in action order. Throws SuperglueError on failure."},sendEmail:{name:"SuperglueSendEmailResult",schema:Jt(m.z.looseObject({replyTo:m.z.string().describe("The sender's address, where replies go."),to:m.z.array(m.z.string()),cc:m.z.array(m.z.string()),attachments:m.z.array(m.z.looseObject({filename:m.z.string(),bytes:m.z.number()}))})),description:"Returns the normalized recipients and the attached files with their decoded sizes. Throws SuperglueError on failure."},writeOrgSettings:{name:"SuperglueOrgSettingsResult",schema:Jt(m.z.looseObject({updated:m.z.array(m.z.enum(["name","preferences","notifications"])),notificationTest:m.z.looseObject({channel:m.z.enum(["slack","email"]),sent:m.z.boolean(),error:m.z.string().optional()}).optional()})),description:"Returns updated settings and any notification test result. Throws SuperglueError on failure."},writeDesignSystem:{name:"SuperglueDesignSystemResult",schema:Jt(m.z.looseObject({updated:m.z.array(m.z.enum(["tokens","guidelines","logo"])),added:m.z.array(m.z.looseObject({id:m.z.string(),kind:m.z.enum(["logo","font","template","reference"]),name:m.z.string()})),changed:m.z.array(m.z.string()),removed:m.z.array(m.z.string())})),description:"Returns the changed design-system parts and file ids. Throws SuperglueError on failure."},importDesignSystemFromUrl:{name:"SuperglueDesignSystemImportResult",schema:Jt(m.z.looseObject({url:m.z.string(),title:m.z.string().nullable(),tokens:m.z.looseObject({}),palette:m.z.array(m.z.looseObject({color:m.z.string(),weight:m.z.number()})),fonts:m.z.array(m.z.looseObject({family:m.z.string(),usage:m.z.array(m.z.string()),source:m.z.string()})),fontFiles:m.z.array(m.z.looseObject({file:m.z.string(),family:m.z.string().describe("CSS family name the website uses"),roles:m.z.array(m.z.string()),weight:m.z.string(),style:m.z.enum(["normal","italic"])})),logos:m.z.array(m.z.looseObject({file:m.z.string(),source:m.z.string(),width:m.z.number(),height:m.z.number(),light:m.z.boolean().describe("Light artwork meant for dark backgrounds")})),screenshot:m.z.string().nullable()})),description:"Returns a proposed design system from the website; font files, logos, and the screenshot are file:: session uploads. Throws SuperglueError on failure."},browser:{name:"SuperglueBrowserResult",schema:Jt(m.z.looseObject({url:m.z.string(),title:m.z.string(),snapshot:m.z.string().optional(),closed:m.z.boolean().optional(),newSession:m.z.boolean().optional(),tabs:m.z.array(m.z.looseObject({index:m.z.number(),url:m.z.string(),title:m.z.string(),active:m.z.boolean()})).optional(),dialog:m.z.looseObject({type:m.z.string(),message:m.z.string(),defaultValue:m.z.string().optional()}).optional(),fileChooser:m.z.looseObject({multiple:m.z.boolean()}).optional(),downloads:m.z.array(m.z.looseObject({filename:m.z.string(),bytes:m.z.number(),path:m.z.string().optional(),error:m.z.string().optional()})).optional()})),description:"Returns the page URL and title after the action, and for every action except screenshot and close the page snapshot: an accessibility tree in which each element has a [ref=...], such as e12 or f1e12, for the next click, type, select, or upload. tabs lists every open tab when more than one is open. dialog is set while a JavaScript alert, confirm, or prompt waits for an answer; the page is paused until the dialog action answers it, and no snapshot is returned. fileChooser is set when the page opened a file picker; answer it with upload without ref. downloads lists files the page downloaded since the last action, saved as Brain files in this chat's Files at path; read one with vfs.readBinary({ path }). A download over the upload size limit has error instead of path and is not saved. newSession is true when this call started a new browser session: the tabs of the last session are reopened at their saved URLs, but unsaved form input and page state are gone, and cookies and sign-ins are kept. screenshot attaches a JPEG of the viewport to this command's result for you. Typed secret values are replaced by their placeholder in every returned text. Throws SuperglueError when the action fails."},readQbm:{name:"SuperglueReadQbmResult",schema:Jt(m.z.looseObject({folder:m.z.string(),objects:m.z.array(m.z.looseObject({type:m.z.string(),files:m.z.array(m.z.string()),records:m.z.number()})),rawTables:m.z.array(m.z.looseObject({table:m.z.string(),files:m.z.array(m.z.string()),rows:m.z.number()})),encryptedValues:m.z.array(m.z.looseObject({table:m.z.string(),column:m.z.string(),values:m.z.number()})),unmappedCodes:m.z.array(m.z.looseObject({field:m.z.string(),code:m.z.string(),records:m.z.number()})).optional(),attachments:m.z.looseObject({documents:m.z.number(),note:m.z.string()}).optional(),rejectedRows:m.z.array(m.z.looseObject({table:m.z.string(),rows:m.z.number()})).optional()})),description:"Returns the folder that holds the extracted files, record counts per object type and raw table, encrypted columns, codes the reader cannot decode, and expected attachments. The folder also holds coverage.json.raw with the same summary plus the mapped source tables. Throws SuperglueError on failure."},readDocument:{name:"SuperglueReadDocumentResult",schema:Jt(m.z.looseObject({headings:m.z.array(m.z.looseObject({level:m.z.number(),text:m.z.string()})),markdown:m.z.string()})),description:"Returns every heading with its level and the Markdown of the document or of the requested section. Throws SuperglueError when the file is not a Word file or no heading matches the section."},readSlides:{name:"SuperglueReadSlidesResult",schema:Jt(m.z.looseObject({slideCount:m.z.number(),slides:m.z.array(m.z.looseObject({number:m.z.number(),title:m.z.string(),hidden:m.z.boolean(),text:m.z.string(),notes:m.z.string(),tables:m.z.number(),charts:m.z.number(),images:m.z.number(),markdown:m.z.string()}))})),description:"Returns the slide count and the requested slides with title, text in reading order, speaker notes, table, chart, and image counts, and Markdown. Throws SuperglueError when the file is not a PowerPoint file or a slide does not exist."},readSheet:{name:"SuperglueReadSheetResult",schema:Jt(m.z.looseObject({sheet:m.z.looseObject({name:m.z.string(),hidden:m.z.boolean(),range:m.z.string().nullable(),rows:m.z.number(),columns:m.z.number(),formulas:m.z.number(),mergedRanges:m.z.number(),charts:m.z.number(),images:m.z.number()}),range:m.z.string().nullable(),cells:m.z.array(m.z.looseObject({address:m.z.string(),value:m.z.union([m.z.string(),m.z.number(),m.z.boolean(),m.z.null()]),text:m.z.string(),formula:m.z.string().optional()}))})),description:"Returns the sheet summary and every non-empty cell in the range with address, stored value, displayed text, and formula. A formula without a stored result has value null. Throws SuperglueError when the sheet or range does not exist."},findInFile:{name:"SuperglueFindInFileResult",schema:Jt(m.z.looseObject({matches:m.z.array(m.z.looseObject({location:m.z.string(),text:m.z.string()}))})),description:"Returns every match with its location and surrounding text; an empty list when nothing matches. Throws SuperglueError when the file is not a Word, PowerPoint, or Excel file."},renderPage:{name:"SuperglueRenderPageResult",schema:Jt(m.z.looseObject({label:m.z.string(),screenshots:m.z.array(m.z.string())})),description:"Shows the rendered page to the model after the command and returns its label. Throws SuperglueError when the page, slide, or sheet does not exist."},previewFile:{name:"SuperglueFilePreviewResult",schema:m.z.looseObject({draftId:m.z.string(),bytes:m.z.number()}),description:"Returns the HTML draft identity and byte count. Throws SuperglueError on failure."}};var ppe=m.z.looseObject({code:m.z.string(),path:m.z.array(m.z.union([m.z.string(),m.z.number(),m.z.symbol()])),message:m.z.string()});Sc.SDK_ERROR_DETAILS_SCHEMA=m.z.discriminatedUnion("kind",[m.z.looseObject({kind:m.z.literal("tool_result"),resultMetadata:UP.optional(),result:m.z.looseObject({toolCallId:m.z.string(),toolName:m.z.string(),outcome:m.z.enum(["success","failure","rejected","aborted"]),confirmation:MP.optional(),error:m.z.looseObject({message:m.z.string()}).optional(),data:m.z.unknown().optional()}),output:m.z.unknown().describe("Unprojected execution output, including the original error and any available response data or metadata.")}),m.z.looseObject({kind:m.z.enum(["input_validation","output_validation"]),toolName:m.z.string(),issues:m.z.array(ppe),output:m.z.unknown().optional()}),m.z.looseObject({kind:m.z.literal("permission"),toolName:m.z.string(),missing:m.z.array(m.z.looseObject({type:m.z.string()}))})])});var JP=y(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.SERVER_OWNED_SESSION_RESOURCE_KINDS=ke.AgentRequestValidationError=ke.AGENT_TOOL_CONTINUATION_ACTION_BY_CONFIRMATION_STATE=ke.AGENT_TOOL_CONTINUATION_ACTIONS=ke.AGENT_IDENTIFIER_PATTERN=ke.AGENT_REQUEST_LIMITS=void 0;ke.validateAgentRequestPayload=HP;ke.validateResourceBinding=GP;ke.validateClientResourceBinding=YP;ke.validateAgentSessionIdentity=VP;ke.validateAgentSessionTarget=WP;ke.validateAgentRequestSubmission=Ipe;ke.isAgentMessagePayload=Cpe;ke.isAgentToolContinuationPayload=bpe;var _s=pn();ke.AGENT_REQUEST_LIMITS={messageContentChars:5e4,identifierChars:256,attachedFiles:20,toolContinuations:20,continuationInputChars:1e5,frontendDraftsChars:2e6,accessRulesContextChars:2e6,pendingMessagesPerSession:10};ke.AGENT_IDENTIFIER_PATTERN=/^[A-Za-z0-9._-]+$/;ke.AGENT_TOOL_CONTINUATION_ACTIONS=["approve","reject","oauth_success","oauth_failure"];ke.AGENT_TOOL_CONTINUATION_ACTION_BY_CONFIRMATION_STATE={[_s.ConfirmationAction.CONFIRMED]:"approve",[_s.ConfirmationAction.DECLINED]:"reject",[_s.ConfirmationAction.OAUTH_SUCCESS]:"oauth_success",[_s.ConfirmationAction.OAUTH_FAILURE]:"oauth_failure"};var Sm=class extends Error{constructor(e){super(e),this.name="AgentRequestValidationError"}};ke.AgentRequestValidationError=Sm;function lt(t){throw new Sm(t)}function Go(t,e){return(!t||typeof t!="object"||Array.isArray(t))&<(`${e} must be an object`),t}function wc(t,e){(typeof t!="string"||!t.trim())&<(`${e} must be a non-empty string`);let r=t.trim();return r.length>ke.AGENT_REQUEST_LIMITS.identifierChars&<(`${e} exceeds ${ke.AGENT_REQUEST_LIMITS.identifierChars} characters`),ke.AGENT_IDENTIFIER_PATTERN.test(r)||lt(`${e} may only contain letters, numbers, dots, underscores, and hyphens`),r}function hpe(t,e){return typeof t!="boolean"&<(`${e} must be a boolean`),t}function XS(t,e){try{return JSON.stringify(t).length}catch{return lt(`${e} must be JSON-serializable`)}}function fpe(t,e){if(t!==void 0)return Array.isArray(t)||lt(`${e} must be an array`),t.length>ke.AGENT_REQUEST_LIMITS.attachedFiles&<(`${e} exceeds ${ke.AGENT_REQUEST_LIMITS.attachedFiles} entries`),t.map((r,n)=>{let i=Go(r,`${e}[${n}]`);return{...i,key:wc(i.key,`${e}[${n}].key`)}})}function LP({value:t,label:e,requireHidden:r}){let n=Go(t,e),i=wc(n.id,`${e}.id`);typeof n.content!="string"&<(`${e}.content must be a string`);let o=n.content;o.length>ke.AGENT_REQUEST_LIMITS.messageContentChars&<(`${e}.content exceeds ${ke.AGENT_REQUEST_LIMITS.messageContentChars} characters`);let s=hpe(n.isHidden,`${e}.isHidden`);r&&!s&<(`${e}.isHidden must be true`);let a=fpe(n.attachedFiles,`${e}.attachedFiles`);return!o.trim()&&!a?.length&<(`${e}.content may only be empty when an attachment is present`),{id:i,content:o,isHidden:s,...a?{attachedFiles:a}:{}}}function FP(t){if(t===void 0)return;let e=Go(t,"frontendDrafts");return XS(e,"frontendDrafts")>ke.AGENT_REQUEST_LIMITS.frontendDraftsChars&<(`frontendDrafts exceeds ${ke.AGENT_REQUEST_LIMITS.frontendDraftsChars} characters`),e}function jP(t){if(t===void 0)return;let e=Go(t,"accessRulesContext");return XS(e,"accessRulesContext")>ke.AGENT_REQUEST_LIMITS.accessRulesContextChars&<(`accessRulesContext exceeds ${ke.AGENT_REQUEST_LIMITS.accessRulesContextChars} characters`),e}function zP(t){if(t!==void 0)return(typeof t!="string"||!_s.AGENT_APPROVAL_MODES.includes(t))&<(`request.approvalMode must be one of: ${_s.AGENT_APPROVAL_MODES.join(", ")}`),t}function qP(t,e){let r=Go(t,e),n=wc(r.toolCallId,`${e}.toolCallId`);return(typeof r.action!="string"||!ke.AGENT_TOOL_CONTINUATION_ACTIONS.includes(r.action))&<(`${e}.action must be one of: ${ke.AGENT_TOOL_CONTINUATION_ACTIONS.join(", ")}`),r.input!==void 0&&XS(r.input,`${e}.input`)>ke.AGENT_REQUEST_LIMITS.continuationInputChars&<(`${e}.input exceeds ${ke.AGENT_REQUEST_LIMITS.continuationInputChars} characters`),{toolCallId:n,action:r.action,...r.input!==void 0?{input:r.input}:{}}}function gpe(t){if(t===void 0)return;(!Array.isArray(t)||t.length===0)&<("request.toolContinuations must be a non-empty array"),t.length>ke.AGENT_REQUEST_LIMITS.toolContinuations&<(`request.toolContinuations exceeds ${ke.AGENT_REQUEST_LIMITS.toolContinuations} entries`);let e=t.map((r,n)=>qP(r,`request.toolContinuations[${n}]`));return new Set(e.map(({toolCallId:r})=>r)).size!==e.length&<("request.toolContinuations must not contain duplicate toolCallId values"),e}function $P(t,e){if(t===void 0)return;(typeof t!="string"||!t.trim())&<(`${e} must be a non-empty string`);let r=t.trim();return r.length>ke.AGENT_REQUEST_LIMITS.messageContentChars&<(`${e} exceeds ${ke.AGENT_REQUEST_LIMITS.messageContentChars} characters`),r}var mpe=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ype(t){let e=LP({value:t.message,label:"request.message"}),r=$P(t.title,"request.title"),n=$P(t.titleInput,"request.titleInput"),i=t.hiddenSteeringMessage===void 0?void 0:LP({value:t.hiddenSteeringMessage,label:"request.hiddenSteeringMessage",requireHidden:!0});i&&i.id===e.id&<("request.hiddenSteeringMessage.id must differ from request.message.id");let o=gpe(t.toolContinuations),s=zP(t.approvalMode),a=FP(t.frontendDrafts),c=jP(t.accessRulesContext);return t.nextStepId!==void 0&&(typeof t.nextStepId!="string"||!mpe.test(t.nextStepId))&<("request.nextStepId must be a UUID"),{kind:"message",message:e,...t.nextStepId?{nextStepId:t.nextStepId}:{},...i?{hiddenSteeringMessage:i}:{},...r?{title:r}:{},...n?{titleInput:n}:{},...o?{toolContinuations:o}:{},...s?{approvalMode:s}:{},...a?{frontendDrafts:a}:{},...c?{accessRulesContext:c}:{}}}function Epe(t){let e=qP(t,"request"),r=zP(t.approvalMode),n=FP(t.frontendDrafts),i=jP(t.accessRulesContext);return{kind:"tool_continuation",...e,...r?{approvalMode:r}:{},...n?{frontendDrafts:n}:{},...i?{accessRulesContext:i}:{}}}function HP(t){let e=Go(t,"request");return e.kind==="message"?ype(e):e.kind==="tool_continuation"?Epe(e):lt('request.kind must be "message" or "tool_continuation"')}function GP(t,e){let r=Go(t,e);return(typeof r.kind!="string"||!_s.AGENT_SESSION_RESOURCE_KINDS.includes(r.kind))&<(`${e}.kind must be one of: ${_s.AGENT_SESSION_RESOURCE_KINDS.join(", ")}`),{kind:r.kind,id:wc(r.id,`${e}.id`)}}ke.SERVER_OWNED_SESSION_RESOURCE_KINDS=["briefing"];function YP(t,e){let r=GP(t,e);return ke.SERVER_OWNED_SESSION_RESOURCE_KINDS.includes(r.kind)&<(`${e}.kind "${r.kind}" is assigned by the server`),r}function VP(t,e="session.createIfMissing"){let r=Go(t,e),n=r.projectId===void 0?void 0:wc(r.projectId,`${e}.projectId`),i=r.taskId===void 0?void 0:wc(r.taskId,`${e}.taskId`);i&&!n&<(`${e}.taskId requires ${e}.projectId`);let o=Object.values(_s.AgentType);(typeof r.agentId!="string"||!o.includes(r.agentId))&<(`${e}.agentId must be one of: ${o.join(", ")}`);let s=r.resourceBinding===void 0?void 0:YP(r.resourceBinding,`${e}.resourceBinding`);return{agentId:r.agentId,...n?{projectId:n}:{},...i?{taskId:i}:{},...s?{resourceBinding:s}:{}}}function WP(t){let e=Go(t,"session"),r=e.createIfMissing===void 0?void 0:VP(e.createIfMissing);return{id:wc(e.id,"session.id"),...r?{createIfMissing:r}:{}}}function Ipe(t){let e=Go(t,"body");return{session:WP(e.session),request:HP(e.request)}}function Cpe(t){return t.kind==="message"}function bpe(t){return t.kind==="tool_continuation"}});var KP=y($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.ARTIFACT_EXPORT_FORMATS=$e.ARTIFACT_RESPONSE_RESERVED_FIELD_NAMES=$e.ARTIFACT_RESPONSE_PATCH_DEBOUNCE_MS=$e.MAX_SPREADSHEET_ARTIFACT_BYTES=$e.MAX_HTML_ARTIFACT_IMAGE_BYTES=$e.MAX_HTML_ARTIFACT_BYTES=$e.MAX_SPREADSHEET_CELL_TEXT_LENGTH=$e.MAX_SPREADSHEET_SHEET_NAME_LENGTH=$e.MAX_SPREADSHEET_GRID_CELLS=$e.MAX_SPREADSHEET_SHEETS=$e.SPREADSHEET_CELL_TYPES=$e.XLSX_CONTENT_TYPE=$e.HTML_CONTENT_TYPE=void 0;$e.brainFileDisplayTitle=Spe;$e.brainFileKind=wpe;$e.isValidSpreadsheetCell=vpe;$e.isArtifactExportFormat=Qpe;$e.isArtifactExportFormatForKind=Tpe;var ZP=lc();$e.HTML_CONTENT_TYPE="text/html";$e.XLSX_CONTENT_TYPE="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";function Spe(t){return t.replace(/\.[a-z][a-z0-9]{0,7}$/i,"")||t}function wpe({fileName:t,contentType:e}){let r=e?.split(";")[0].trim().toLowerCase(),n=t.toLowerCase().match(/\.([a-z0-9]+)$/)?.[1];return r===$e.HTML_CONTENT_TYPE||n==="html"||n==="htm"?"html":r===$e.XLSX_CONTENT_TYPE||n==="xlsx"?"spreadsheet":"file"}$e.SPREADSHEET_CELL_TYPES=["text","integer","number","percent","currency","boolean","date","datetime"];$e.MAX_SPREADSHEET_SHEETS=20;$e.MAX_SPREADSHEET_GRID_CELLS=1e6;$e.MAX_SPREADSHEET_SHEET_NAME_LENGTH=31;$e.MAX_SPREADSHEET_CELL_TEXT_LENGTH=32767;var _pe=ZP.z.iso.date(),Bpe=ZP.z.iso.datetime({offset:!0});function vpe(t,e){return t===null?!0:e==="text"?typeof t=="string"&&t.length<=$e.MAX_SPREADSHEET_CELL_TEXT_LENGTH:e==="boolean"?typeof t=="boolean":["integer","number","percent","currency"].includes(e)?typeof t=="number"&&Number.isFinite(t)&&(e!=="integer"||Number.isInteger(t)):typeof t!="string"?!1:(e==="datetime"?Bpe:_pe).safeParse(t).success}$e.MAX_HTML_ARTIFACT_BYTES=1024*1024;$e.MAX_HTML_ARTIFACT_IMAGE_BYTES=12*1024*1024;$e.MAX_SPREADSHEET_ARTIFACT_BYTES=10*1024*1024;$e.ARTIFACT_RESPONSE_PATCH_DEBOUNCE_MS=300;$e.ARTIFACT_RESPONSE_RESERVED_FIELD_NAMES=new Set(["__proto__","constructor","prototype"]);$e.ARTIFACT_EXPORT_FORMATS=["pdf","docx","xlsx","pptx"];function Qpe(t){return $e.ARTIFACT_EXPORT_FORMATS.some(e=>e===t)}function Tpe(t,e,r=!1){return t==="spreadsheet"?e==="xlsx":r?e==="pdf"||e==="pptx":e!=="pptx"}});var nL=y(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.API_KEY_ACTION_LABELS=it.API_KEY_SURFACE_LABELS=it.API_KEY_SCOPES=it.API_KEY_SURFACE_ACTIONS=it.API_KEY_ACTIONS=it.API_KEY_SURFACES=void 0;it.getApiKeySurface=eL;it.getApiKeyAction=tL;it.getApiKeySurfaceActions=ew;it.parseApiKeyScopes=rL;it.validateApiKeyScopesInput=Npe;it.isApiKeyScopeAllowed=Ope;it.formatApiKeyScopes=xpe;it.API_KEY_SURFACES=["api","mcp"];it.API_KEY_ACTIONS=["read","write","execute"];it.API_KEY_SURFACE_ACTIONS={api:it.API_KEY_ACTIONS,mcp:["execute"]};it.API_KEY_SCOPES=it.API_KEY_SURFACES.flatMap(t=>it.API_KEY_SURFACE_ACTIONS[t].map(e=>`${t}:${e}`));it.API_KEY_SURFACE_LABELS={api:"API & CLI",mcp:"MCP"};it.API_KEY_ACTION_LABELS={read:"Read",write:"Write",execute:"Execute"};var XP=new Set(it.API_KEY_SCOPES),Dpe={"/v1/tools":["read"],"/v1/tools/:toolId":["read"],"/v1/tools/:toolId/run":["execute"],"/v1/authenticate":["write"],"/v1/memory-notes":["read","write"]},kpe=new Set(["/v1/api-keys","/v1/api-keys/:id","/v1/api-keys/:id/reveal"]),Rpe=new Set(["/v1/me"]);function eL(t){let e=t.split("?")[0];return e==="/mcp"||e.startsWith("/mcp/")?"mcp":"api"}function tL(t){return t==="read"?"read":t==="execute"?"execute":"write"}function ew(t,e){return it.API_KEY_SURFACE_ACTIONS[e].filter(r=>(t||[]).includes(`${e}:${r}`))}function rL(t){if(!Array.isArray(t))return null;let e=[...new Set(t.filter(r=>XP.has(r)))];return e.length>0?e:null}function Npe(t){if(t==null)return{scopes:null};let e=`Valid scopes: ${it.API_KEY_SCOPES.join(", ")}. Use null for full access.`;if(!Array.isArray(t)||t.length===0)return{error:`scopes must be a non-empty array of API key scopes. ${e}`};let r=t.filter(n=>!XP.has(n));return r.length>0?{error:`Unknown API key scope(s): ${r.map(String).join(", ")}. ${e}`}:{scopes:rL(t)}}function Ope({scopes:t,path:e,type:r}){if(!t||t.length===0)return!0;let n=e.split("?")[0];if(kpe.has(n))return!1;if(Rpe.has(n))return!0;let i=tL(r),o=eL(n);return o==="api"&&Dpe[n]?.some(s=>s===r)&&ew(t,"mcp").length>0?!0:t.includes(`${o}:${i}`)}function xpe(t){return!t||t.length===0?"Full access":it.API_KEY_SURFACES.map(e=>({surface:e,actions:ew(t,e)})).filter(e=>e.actions.length>0).map(e=>it.API_KEY_SURFACE_ACTIONS[e.surface].length===1?it.API_KEY_SURFACE_LABELS[e.surface]:`${it.API_KEY_SURFACE_LABELS[e.surface]} ${e.actions.join("/")}`).join(", ")}});var iL=y(tw=>{"use strict";Object.defineProperty(tw,"__esModule",{value:!0});tw.isValidEmail=Upe;function Upe(t){return/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.[a-zA-Z]{1,}$/.test(t)}});var sL=y(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.GATEWAY_UNINSTALL_COMMANDS=Zt.GATEWAY_API_KEY_NAME_PREFIX=Zt.GATEWAY_TARGET_NAME_PATTERN=Zt.GATEWAY_DOWNLOAD_BASE_URL=Zt.GATEWAY_INSTALL_TOKEN_PREFIX=void 0;Zt.getGatewayServerUrl=oL;Zt.buildGatewayInstallToken=Ppe;Zt.buildGatewayInstallCommand=Lpe;Zt.getGatewayApiKeyName=$pe;Zt.GATEWAY_INSTALL_TOKEN_PREFIX="sgi1.";Zt.GATEWAY_DOWNLOAD_BASE_URL="https://downloads.superglue.cloud";Zt.GATEWAY_TARGET_NAME_PATTERN=/^[a-z0-9]([a-z0-9_-]{0,61}[a-z0-9])?$/;function oL(t){let e=new URL(t);return e.protocol=e.protocol==="http:"?"ws:":"wss:",e.pathname=`${e.pathname.replace(/\/+$/,"")}/ws/tunnels`,e.search="",e.hash="",e.toString()}function Mpe(t){let e=new TextEncoder().encode(t),r="";for(let n of e)r+=String.fromCharCode(n);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ppe(t){let e={v:1,serverUrl:oL(t.apiEndpoint),tunnelId:t.tunnelId,apiKey:t.apiKey,targets:t.targets,enableScriptRunner:t.enableScriptRunner};return Zt.GATEWAY_INSTALL_TOKEN_PREFIX+Mpe(JSON.stringify(e))}function Lpe(t,e){return t==="windows"?[`$install = { ${["$ErrorActionPreference = 'Stop'","[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor 3072","$ProgressPreference = 'SilentlyContinue'","$gateway = Join-Path $env:TEMP 'superglue-gateway.exe'","Remove-Item $gateway -Force -ErrorAction SilentlyContinue",`Invoke-WebRequest -UseBasicParsing '${Zt.GATEWAY_DOWNLOAD_BASE_URL}/superglue-gateway-windows.exe' -OutFile $gateway`,`'${e}' | & $gateway install -`].join("; ")} }`,`if (([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { & $install } else { Start-Process powershell -Verb RunAs -ErrorAction Stop -ArgumentList "-NoExit -Command & {$install}"; 'Continue in the administrator PowerShell window.' }`].join("; "):["d=$(mktemp -d)",`u="${Zt.GATEWAY_DOWNLOAD_BASE_URL}/superglue-gateway-linux-$(uname -m | sed 's/aarch64/arm64/')"`,'s=$([ "$(id -u)" -eq 0 ] || echo sudo)','{ if command -v curl >/dev/null; then curl -fsSL -o "$d/superglue-gateway" "$u"; else wget -qO "$d/superglue-gateway" "$u"; fi; }','$s install -m 0755 "$d/superglue-gateway" /usr/local/bin/superglue-gateway',`echo '${e}' | $s /usr/local/bin/superglue-gateway install -`].join(" && ")}Zt.GATEWAY_API_KEY_NAME_PREFIX="Gateway: ";function $pe(t){return Zt.GATEWAY_API_KEY_NAME_PREFIX+t}Zt.GATEWAY_UNINSTALL_COMMANDS={windows:'& "C:\\Program Files\\superglue Gateway\\superglue-gateway.exe" uninstall',linux:"sudo /usr/local/bin/superglue-gateway uninstall"}});var sw=y(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.OAUTH_TOKEN_CREDENTIAL_KEYS=Fe.OAUTH_CONFIG_CREDENTIAL_KEYS=void 0;Fe.hasMeaningfulValue=hr;Fe.stringValue=fr;Fe.validateOAuthConnection=Wpe;Fe.formatOAuthConnectionDisabledReason=Zpe;Fe.objectValue=vs;Fe.parseScopes=UA;Fe.normalizeGrantType=MA;Fe.normalizeOAuthClientMode=ow;Fe.normalizeSystemAuthentication=Zr;Fe.resolveOAuthClientMode=Xpe;Fe.flattenSystemAuthentication=lL;Fe.maskedFlatSystemAuthentication=ehe;Fe.isMaskedSecretValue=uL;Fe.pickAgentAuthInputFields=the;Fe.maskSystemAuthenticationForResponse=rhe;Fe.restoreMaskedClientSecret=nhe;Fe.mapAgentAuthInput=dL;Fe.mergeAgentAuthInput=phe;Fe.getAuthenticationConfigCredentialKeys=hhe;Fe.getCredentialRequirements=fhe;Fe.isCredentialRequirementSatisfied=AL;Fe.hasUnsatisfiedCredentialRequirements=ghe;Fe.updateAuthenticationEditorField=mhe;Fe.validateOAuthAuthenticationConfigPlacement=yhe;Fe.authenticationToLegacyCredentials=pL;Fe.isRuntimeCredentialMetadataKey=Ehe;Fe.buildRuntimeCredentialsFromAuthentication=Ihe;Fe.resolveOAuthConfigFromAuthentication=Che;Fe.toCredentialInputValue=bhe;var fa=Ti();Fe.OAUTH_CONFIG_CREDENTIAL_KEYS=["auth_url","authUrl","token_url","tokenUrl","token_uri","scopes","scope","grant_type","grantType","oauthClientMode","client_id","clientId","client_secret","clientSecret","tokenAuthMethod","tokenContentType","usePKCE","extraHeaders","extraBodyParams"];var wm=["host","port","database","path","homeDirectory"],cL=["type","oauthClientMode","grantType","authUrl","tokenUrl","scopes","clientId","clientSecret","tokenAuthMethod","tokenContentType","usePKCE","extraHeaders","extraBodyParams","resource","protocol",...wm],Fpe=new Set(cL),jpe="type, oauthClientMode, grantType, authUrl, tokenUrl, scopes, clientId, clientSecret, tokenAuthMethod, tokenContentType, usePKCE, extraHeaders, extraBodyParams, resource, protocol, host, port, database, path, homeDirectory",zpe=["grantType","authUrl","tokenUrl","scopes","clientId","clientSecret"],qpe={grantType:["grantType","grant_type"],authUrl:["authUrl","auth_url"],tokenUrl:["tokenUrl","token_url","token_uri"],scopes:["scopes","scope"],clientId:["clientId","client_id"],clientSecret:["clientSecret","client_secret"]},iw=["tokenAuthMethod","tokenContentType","usePKCE","extraHeaders","extraBodyParams","resource"],Hpe=new Set(zpe);Fe.OAUTH_TOKEN_CREDENTIAL_KEYS=["access_token","accessToken","refresh_token","refreshToken","expires_at","expiresAt","expires_in","expiresIn","expiry","token_type","tokenType"];var Gpe=new Set(Fe.OAUTH_TOKEN_CREDENTIAL_KEYS);function _c(t){return Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0))}function rw({config:t,key:e,value:r}){let n={...t||{}};return hr(r)?n[e]=r:delete n[e],Object.keys(n).length>0?n:void 0}function hr(t){return(0,fa.hasCredentialValue)(t)}function fr(t){if(hr(t))return typeof t=="string"?t:String(t)}var Ype={"grant_type authorization_code or client_credentials":"authorization_code or client_credentials",client_id:"client ID",token_url:"token URL",auth_url:"authorization URL","client_secret or usePKCE":"client secret or PKCE","client_secret or oauth_cert + oauth_key":"client secret or OAuth certificate and key"};function Bs(...t){return t.find(e=>hr(e))}function Vpe(t){return t===!0||t==="true"}function Wpe(t){let e=t||{},r=fr(Bs(e.grant_type,e.grantType)),n=r==="client_credentials"?"client_credentials":"authorization_code",i=r&&r!=="authorization_code"&&r!=="client_credentials",o=Bs(e.client_id,e.clientId),s=Bs(e.client_secret,e.clientSecret),a=Bs(e.auth_url,e.authUrl),c=Bs(e.token_url,e.tokenUrl,e.token_uri),l=Bs(e.oauth_cert,e.oauthCert),u=Bs(e.oauth_key,e.oauthKey),d=hr(l)&&hr(u)||e.hasServerSideCertificateCredentials===!0,A=e.hasServerSideClientSecret===!0,p=hr(s)||A,h=Vpe(Bs(e.usePKCE,e.usePkce)),f=[];return i&&f.push("grant_type authorization_code or client_credentials"),hr(o)||f.push("client_id"),hr(c)||f.push("token_url"),n==="client_credentials"?!p&&!d&&f.push("client_secret or oauth_cert + oauth_key"):(hr(a)||f.push("auth_url"),!p&&!h&&f.push("client_secret or usePKCE")),{grantType:n,hasAccessToken:hr(Bs(e.access_token,e.accessToken)),hasCertificateCredentials:d,isReadyToConnect:f.length===0,missingFields:f,usePKCE:h}}function Jpe(t){return t.length<=1?t[0]||"":t.length===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t[t.length-1]}`}function Zpe(t){if(!t||t.isReadyToConnect)return null;let e=t.missingFields.map(r=>Ype[r]||r);return`OAuth connection is disabled because ${Jpe(e)} ${e.length===1?"is":"are"} missing.`}function vs(t){if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Yo(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function UA(t){if(Array.isArray(t))return t.map(String).filter(Boolean);if(hr(t)){if(typeof t=="string"){let e=t.trim().split(/[,\s]+/).map(r=>r.trim()).filter(Boolean);return e.length>0?e:void 0}return[String(t)]}}function MA(t){let e=fr(t);if(e==="authorization_code"||e==="client_credentials"||e==="password"||e==="service_account"||e==="custom")return e;if(e)return"custom"}function ow(t){return t==="managed"||t==="dynamic"||t==="custom"?t:void 0}function Kpe(t){let e=Object.entries(t).filter(([r])=>!Hpe.has(r));return e.length>0?Object.fromEntries(e):void 0}function cu(t,e,r){for(let i of qpe[r])if(r==="scopes"&&Array.isArray(t[i])||hr(t[i]))return t[i];let n=vs(t.client);return r==="clientId"&&hr(n?.id)?n.id:r==="clientSecret"&&hr(n?.secret)?n.secret:e[r]}function Zr(t){if(!t)return;let e=t;if(e.type==="oauth2"){let r=vs(e.config)||{},n=Kpe(r)||{};return _c({type:"oauth2",oauthClientMode:ow(e.oauthClientMode),grantType:MA(cu(e,r,"grantType")),authUrl:fr(cu(e,r,"authUrl")),tokenUrl:fr(cu(e,r,"tokenUrl")),scopes:UA(cu(e,r,"scopes")),oauthAppId:fr(e.oauthAppId),clientId:fr(cu(e,r,"clientId")),clientSecret:fr(cu(e,r,"clientSecret")),config:Object.keys(n).length>0?n:void 0})}return e.type==="connection_string"?_c({type:"connection_string",protocol:e.protocol,config:vs(e.config??e.components)}):e.type==="api_key"||e.type==="basic_auth"||e.type==="none"?_c({type:e.type,config:vs(e.config)}):{type:"none"}}function Xpe({authentication:t,templateManaged:e,templateRegistrationUrl:r}){let n=Zr(t);return n?.type!=="oauth2"?"custom":n.oauthAppId?.startsWith("managed:")?"managed":n.oauthClientMode?n.oauthClientMode==="managed"&&!e?"custom":n.oauthClientMode:r?"dynamic":e&&!n.clientSecret?"managed":"custom"}function lL(t){let e=Zr(t);if(!e)return;let{config:r,scopes:n,oauthAppId:i,...o}=e,s={};return r&&typeof r=="object"&&Object.assign(s,r),Object.assign(s,o),Array.isArray(n)?s.scopes=n.join(" "):n!==void 0&&(s.scopes=n),s}function nw(t,e=""){return t==null?t:Array.isArray(t)?t.map(r=>nw(r)):typeof t=="object"?Object.fromEntries(Object.entries(t).map(([r,n])=>[r,nw(n,r)])):e&&(0,fa.isSensitiveCredentialKey)(e)?(0,fa.maskCredentialValue)(e,t):t}function ehe(t){let e=lL(t);if(e)return nw(e)}function uL(t){return(0,fa.isMaskedValue)(t)||(0,fa.isFullyMaskedCredentialValue)(t)}function the(t){let e=vs(t);if(!e)return;let r={};for(let n of cL){if(!Yo(e,n))continue;let i=e[n];i!==void 0&&(r[n]=i)}return r}function rhe(t){return!t||t.type!=="oauth2"||!hr(t.clientSecret)?t:{...t,clientSecret:fa.FULLY_MASKED_CREDENTIAL_VALUE}}function nhe({incoming:t,existing:e}){if(!t||t.type!=="oauth2"||!uL(t.clientSecret))return t;let r=e?.type==="oauth2"?e.clientSecret:void 0;return{...t,clientSecret:r}}function ihe(t){if(t==="none"||t==="api_key"||t==="basic_auth"||t==="oauth2"||t==="connection_string")return t}function ohe(t){let e=wm.flatMap(r=>{if(!Yo(t,r))return[];let n=t[r];return hr(n)?[[r,n]]:[]});return e.length>0?Object.fromEntries(e):void 0}function she(t){return wm.filter(e=>Yo(t,e))}function ahe(t){let e=wm.flatMap(r=>Yo(t,r)?[[r,t[r]]]:[]);return e.length>0?Object.fromEntries(e):void 0}function che(t){let e=new Set(["oauthClientMode","grantType","authUrl","tokenUrl","scopes","clientId","clientSecret",...iw]);return Object.keys(t).filter(r=>e.has(r))}function dL(t){if(t==null)return{};let e=vs(t);if(!e)return{error:"auth must be an object."};let r=ihe(e.type);if(!r)return{error:"auth.type is required."};let n=Object.keys(e).filter(a=>!Fpe.has(a));if(n.length>0)return{error:`Unknown auth field(s): ${n.join(", ")}. Accepted: ${jpe}.`};let i=she(e);if(r!=="connection_string"&&i.length>0)return{error:`Connection auth field(s) require auth.type 'connection_string': ${i.join(", ")}.`};let o=che(e);if(r!=="oauth2"&&o.length>0)return{error:`OAuth auth field(s) require auth.type 'oauth2': ${o.join(", ")}.`};if(r!=="oauth2"){let a=ohe(e);return{authentication:_c({type:r,protocol:r==="connection_string"?e.protocol:void 0,config:a})}}let s={...Object.fromEntries(iw.flatMap(a=>{if(!Yo(e,a))return[];let c=e[a];return hr(c)?[[a,c]]:[]}))};return{authentication:_c({type:"oauth2",oauthClientMode:ow(e.oauthClientMode),grantType:MA(e.grantType),authUrl:fr(e.authUrl),tokenUrl:fr(e.tokenUrl),scopes:UA(e.scopes),clientId:fr(e.clientId),clientSecret:fr(e.clientSecret),config:Object.keys(s).length>0?s:void 0})}}function Bc(t){return t===""||t===null||t===void 0}function xA(t,e,r,n){if(Yo(e,r)){if(Bc(e[r])){delete t[n];return}t[n]=fr(e[r])}}function lhe(t,e){if(Yo(e,"scopes")){if(Bc(e.scopes)){delete t.scopes;return}t.scopes=UA(e.scopes)}}function uhe(t,e){if(Yo(e,"grantType")){if(Bc(e.grantType)){delete t.grantType;return}t.grantType=MA(e.grantType)}}function dhe(t,e,r){if(Yo(e,r)){if(Bc(e[r])){delete t[r];return}t[r]=e[r]}}function Ahe(t,e){if(Bc(e))return;let r=vs(e);if(!r)return t;let n={...t||{}};for(let[i,o]of Object.entries(r))Bc(o)?delete n[i]:n[i]=o;return Object.keys(n).length>0?n:void 0}function phe(t,e){let r=dL(e);if(r.error)return Zr(t)||{type:"none"};let n=r.authentication||{type:"none"},i=vs(e)||{},o=Zr(t),s=o?.type===n.type;if(n.type!=="oauth2"){let d=ahe(i),A=s&&o?{...o}:{type:n.type};return n.type==="connection_string"&&Yo(i,"protocol")&&(Bc(i.protocol)?delete A.protocol:A.protocol=i.protocol),d&&(A.config=Ahe(o?.config,d)),Zr(A)||{type:n.type}}let c={...s&&o?.type==="oauth2"?{...o,config:{...o.config||{}}}:{type:"oauth2",config:{}}};xA(c,i,"oauthClientMode","oauthClientMode"),uhe(c,i),xA(c,i,"authUrl","authUrl"),xA(c,i,"tokenUrl","tokenUrl"),lhe(c,i),xA(c,i,"clientId","clientId"),xA(c,i,"clientSecret","clientSecret");let u={...c.config||{}};for(let d of iw)dhe(u,i,d);return c.config=Object.keys(u).length>0?u:void 0,Zr(c)||{type:"oauth2"}}function hhe(t){let e=Zr(t);if(!e)return[];let r=new Set;for(let n of Object.keys(e.config||{}))r.add(n);return e.type==="oauth2"&&(e.grantType&&(r.add("grant_type"),r.add("grantType")),e.authUrl&&(r.add("auth_url"),r.add("authUrl")),e.tokenUrl&&(r.add("token_url"),r.add("tokenUrl"),r.add("token_uri")),e.scopes&&(r.add("scopes"),r.add("scope")),e.clientId&&(r.add("client_id"),r.add("clientId")),e.clientSecret&&(r.add("client_secret"),r.add("clientSecret"))),[...r]}function fhe(t){let e=Zr(t);if(!e||e.type!=="connection_string")return[];let r={type:"field",field:{key:"username",aliases:["user"]}},n={type:"field",field:{key:"password"}};switch(e.protocol){case"sftp":return[r,{type:"oneOf",fields:[{key:"password"},{key:"privateKey"}]},{type:"field",field:{key:"passphrase"},optional:!0}];case"smb":return[r,n,{type:"field",field:{key:"domain"},optional:!0}];case"sqlserver":return[{type:"field",field:{key:"user",aliases:["username"]}},n];default:return[r,n]}}function aL(t,e){return(0,fa.hasCredentialValue)(e[t.key])?!0:(t.aliases??[]).some(r=>(0,fa.hasCredentialValue)(e[r]))}function AL(t,e){return t.optional?!0:t.type==="field"?aL(t.field,e):t.fields.some(r=>aL(r,e))}function ghe(t,e){let r=e||{};return t.some(n=>!AL(n,r))}function mhe({authentication:t,path:e,value:r}){let n=Zr(t)||{type:"none"};if(n.type==="oauth2"){if(e==="oauth2.grantType")return{...n,grantType:MA(r)};if(e==="oauth2.authUrl")return{...n,authUrl:fr(r)};if(e==="oauth2.tokenUrl")return{...n,tokenUrl:fr(r)};if(e==="oauth2.scopes")return{...n,scopes:UA(r)??[]};if(e==="oauth2.clientId")return{...n,clientId:fr(r)};if(e==="oauth2.clientSecret")return{...n,clientSecret:fr(r)};if(e.startsWith("oauth2.config.")){let o=e.slice(14);return{...n,config:rw({config:n.config,key:o,value:r})}}}if(n.type==="connection_string"){if(e==="connection.protocol")return{...n,protocol:fr(r)};if(e.startsWith("connection.config.")){let o=e.slice(18);return{...n,config:rw({config:n.config,key:o,value:r})}}}let i=`${n.type}.config.`;if(e.startsWith(i)){let o=e.slice(i.length);return{...n,config:rw({config:n.config,key:o,value:r})}}return n}function yhe({authentication:t,credentials:e}){if(Zr(t)?.type!=="oauth2"||!e||typeof e!="object"||Array.isArray(e))return null;let n=Object.keys(e).filter(i=>Fe.OAUTH_CONFIG_CREDENTIAL_KEYS.includes(i));return n.length===0?null:`OAuth configuration keys belong in auth, not credentials: ${n.join(", ")}. Move OAuth client ID to auth.clientId, client secret to auth.clientSecret, auth URL to auth.authUrl, token URL to auth.tokenUrl, scopes to auth.scopes, grant type to auth.grantType, and token request settings to auth fields such as tokenAuthMethod/usePKCE/extraHeaders. Runtime OAuth access and refresh tokens are created by connect OAuth authorization.`}function pL(t){let e=Zr(t);return e?e.type==="oauth2"?_c({...e.config||{},grant_type:e.grantType,auth_url:e.authUrl,token_url:e.tokenUrl,scopes:e.scopes?.join(" "),client_id:e.clientId,client_secret:e.clientSecret}):e.type==="connection_string"?e.config||{}:e.config||{}:{}}function Ehe(t){return Gpe.has(t.trim())}function Ihe({authentication:t,credentials:e}){let r=pL(t);return Zr(t)?.type==="oauth2"?{...e||{},...r}:{...r,...e||{}}}function Che({input:t,authentication:e,templateOAuth:r}){let n=Zr(e),i=n?.type==="oauth2"?n:void 0,o=i?.config||{},s=t||{},a=(...c)=>c.find(l=>l!=null);return _c({grant_type:a(s.grantType,s.grant_type,i?.grantType,r?.grant_type)||"authorization_code",scopes:a(s.scopes,i?.scopes?.join(" "),r?.scopes),client_id:a(s.clientId,s.client_id,i?.clientId),client_secret:a(s.clientSecret,s.client_secret,i?.clientSecret),auth_url:a(s.authUrl,s.auth_url,i?.authUrl,r?.authUrl),token_url:a(s.tokenUrl,s.token_url,i?.tokenUrl,r?.tokenUrl),resource:a(s.resource,o.resource,r?.resource),tokenAuthMethod:a(s.tokenAuthMethod,o.tokenAuthMethod,r?.tokenAuthMethod),tokenContentType:a(s.tokenContentType,o.tokenContentType,r?.tokenContentType),usePKCE:a(s.usePKCE,o.usePKCE,r?.usePKCE),extraHeaders:a(s.extraHeaders,o.extraHeaders,r?.extraHeaders),extraBodyParams:a(s.extraBodyParams,o.extraBodyParams,r?.extraBodyParams)})}function bhe(t){if(t==null)return"";if(typeof t=="string")return t;let e=JSON.stringify(t);return e===void 0?String(t):e}});var NL=y(Vo=>{"use strict";Object.defineProperty(Vo,"__esModule",{value:!0});Vo.bundles=void 0;Vo.buildBundleAgentLaunch=Ohe;Vo.getBundle=xhe;Vo.listBundles=Uhe;var She="https://sandbox.api.sap.com/s4hanacloud/sap/opu/odata/sap",whe="<<(p) => { const value = p['sage_intacct_entity_id']; if (!value) return ''; const escaped = String(value).replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('\"', '"').replaceAll(\"'\", '''); return `<locationid>${escaped}</locationid>`; }>>",hL="<<() => crypto.randomUUID()>>";function Lt(t){return`<?xml version="1.0" encoding="UTF-8"?><request><control><senderid><<sage_intacct_sender_id>></senderid><password><<sage_intacct_sender_password>></password><controlid>${hL}</controlid><uniqueid>false</uniqueid><dtdversion>3.0</dtdversion></control><operation><authentication><login><userid><<sage_intacct_user_id>></userid><companyid><<sage_intacct_company_id>></companyid><password><<sage_intacct_user_password>></password>${whe}</login></authentication><content><function controlid="${hL}">${t}</function></content></operation></request>`}function ga({stepId:t,objectNameExpression:e,collectionName:r,mapExpression:n,includeTotalCount:i=!1}){let o=i?"Number(data && data.TOTALCOUNT ? data.TOTALCOUNT : rows.length)":"rows.length",s=n?`rows.map(${n})`:"rows";return`(sourceData) => { const response = sourceData.${t} && sourceData.${t}.data ? sourceData.${t}.data.RESPONSE : undefined; const control = response ? response.CONTROL : undefined; const operation = response ? response.OPERATION : undefined; const authentication = operation ? operation.AUTHENTICATION : undefined; const result = operation ? operation.RESULT : undefined; const statuses = [control && control.STATUS, authentication && authentication.STATUS, result && result.STATUS].filter(Boolean).map((value) => String(value).toLowerCase()); if (statuses.includes('failure')) { const message = (result && result.ERRORMESSAGE) || (authentication && authentication.ERR ? authentication.ERR.ERRORMESSAGE : undefined) || (control && control.ERR ? control.ERR.ERRORMESSAGE : undefined); const rawErrors = message ? message.ERROR : undefined; const errors = Array.isArray(rawErrors) ? rawErrors : (rawErrors ? [rawErrors] : []); const details = errors.map((error) => [error.ERRORNO, error.DESCRIPTION2 || error.DESCRIPTION, error.CORRECTION].filter(Boolean).join(' - ')).filter(Boolean); const supportIds = errors.map((error) => error.SUPPORTID).filter(Boolean); const suffix = supportIds.length ? \` Sage support ID: \${supportIds.join(', ')}.\` : ''; throw new Error(\`Sage Intacct request failed\${details.length ? \`: \${details.join('; ')}\` : '.'}\${suffix}\`); } const data = result ? result.DATA : undefined; const objectName = ${e}; const raw = data ? data[objectName] : undefined; const rows = (Array.isArray(raw) ? raw : (raw ? [raw] : [])).slice(0, (sourceData && sourceData.maxResults) ?? ${i?"1000":"200"}); return { total: ${o}, ${r}: ${s} }; }`}var ma=`const esc = (value) => String(value).replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", ''');`,fL="const toIntacctDate = (value) => { const match = String(value).match(/^(\\d{4})-(\\d{2})-(\\d{2})/); if (!match) throw new Error('Dates must be in YYYY-MM-DD format.'); return match[2] + '/' + match[3] + '/' + match[1]; };",gL="const assertBalanced = (lines) => { const balance = lines.reduce((sum, line) => sum + (line.type === 'credit' ? -1 : 1) * Math.abs(Number(line.amount)), 0); if (Math.abs(balance) > 0.005) throw new Error('Journal lines must balance: debits minus credits is ' + balance.toFixed(2) + '.'); };",mL=`const lineXml = (line) => { const amount = Number(line.amount); if (!Number.isFinite(amount) || amount <= 0) throw new Error('Every journal line needs a positive amount.'); const type = line.type === 'credit' ? -1 : line.type === 'debit' ? 1 : null; if (type === null) throw new Error("Every journal line needs type 'debit' or 'credit'."); if (!line.accountNo) throw new Error('Every journal line needs accountNo.'); let xml = '<GLENTRY><ACCOUNTNO>' + esc(line.accountNo) + '</ACCOUNTNO><TR_TYPE>' + type + '</TR_TYPE><TRX_AMOUNT>' + amount + '</TRX_AMOUNT>'; if (line.department) xml += '<DEPARTMENT>' + esc(line.department) + '</DEPARTMENT>'; if (line.location) xml += '<LOCATION>' + esc(line.location) + '</LOCATION>'; if (line.memo) xml += '<DESCRIPTION>' + esc(line.memo) + '</DESCRIPTION>'; return xml + '</GLENTRY>'; };`;function lu({stepId:t,objectName:e}){return`(sourceData) => { const response = sourceData.${t} && sourceData.${t}.data ? sourceData.${t}.data.RESPONSE : undefined; const control = response ? response.CONTROL : undefined; const operation = response ? response.OPERATION : undefined; const authentication = operation ? operation.AUTHENTICATION : undefined; const result = operation ? operation.RESULT : undefined; const statuses = [control && control.STATUS, authentication && authentication.STATUS, result && result.STATUS].filter(Boolean).map((value) => String(value).toLowerCase()); if (statuses.includes('failure')) { const message = (result && result.ERRORMESSAGE) || (authentication && authentication.ERR ? authentication.ERR.ERRORMESSAGE : undefined) || (control && control.ERR ? control.ERR.ERRORMESSAGE : undefined); const rawErrors = message ? message.ERROR : undefined; const errors = Array.isArray(rawErrors) ? rawErrors : (rawErrors ? [rawErrors] : []); const details = errors.map((error) => [error.ERRORNO, error.DESCRIPTION2 || error.DESCRIPTION, error.CORRECTION].filter(Boolean).join(' - ')).filter(Boolean); const supportIds = errors.map((error) => error.SUPPORTID).filter(Boolean); const suffix = supportIds.length ? \` Sage support ID: \${supportIds.join(', ')}.\` : ''; throw new Error(\`Sage Intacct request failed\${details.length ? \`: \${details.join('; ')}\` : '.'}\${suffix}\`); } const data = result ? result.DATA : undefined; const raw = data ? (data.${e} || data.${e.toLowerCase()}) : undefined; const record = Array.isArray(raw) ? raw[0] : raw; return { recordNo: record && record.RECORDNO ? Number(record.RECORDNO) : undefined, record }; }`}var FA="netsuite",lw=100,$A=1e4,km=String.raw`<<(p) => { const url = String(p['netsuite_url'] || ''); if (!url || url.includes('{accountId}')) throw new Error('NetSuite is not connected yet: set the account ID so the system URL is https://<account>.suitetalk.api.netsuite.com/services/rest'); return url.replace(/\/+$/, ''); }>>`,Rm={Authorization:"Bearer <<netsuite_access_token>>",Accept:"application/json"},uw=String.raw`const has = (value) => value !== undefined && value !== null && value !== ''; const nsId = (value, name) => { const text = String(value ?? '').trim(); if (!/^-?\d+$/.test(text)) throw new Error(name + ' must be a NetSuite internal ID.'); return text; }; const nsDate = (value, name) => { const text = String(value ?? '').trim(); if (!/^\d{4}-\d{2}-\d{2}$/.test(text)) throw new Error(name + ' must be a date in YYYY-MM-DD format.'); return text; }; const ref = (value, name) => ({ id: nsId(value, name) });`,_he=String.raw`const str = (value) => (value === undefined || value === null || value === '' ? null : String(value)); const num = (value) => (value === undefined || value === null || value === '' ? null : Number(value)); const bool = (value) => value === 'T' || value === true; const ids = (value) => (value === undefined || value === null || value === '' ? [] : String(value).split(',').map((part) => part.trim()).filter(Boolean)); const status = (value) => (value ? String(value).replace(/^[^:]*:\s*/, '') : null);`,yL=String.raw`const stripLinks = (value) => { if (Array.isArray(value)) return value.map(stripLinks); if (value && typeof value === 'object') { const result = {}; for (const [key, entry] of Object.entries(value)) { if (key !== 'links') result[key] = stripLinks(entry); } return result; } return value; };`,Bhe={type:"integer",minimum:1,maximum:$A,description:`Maximum number of records to return (max ${$A}). Defaults to ${lw}. The result always reports the full match count in total, so use maxResults 1 to count. Prefer filters over large values: big results can exceed an AI client's tool output limit.`},vhe={type:"boolean",description:"Only return active records. Defaults to false (inactive records are included)."},Qhe={type:"string",description:"Optional subsidiary internal ID to filter by."},The={type:"string",description:"Optional earliest transaction date as YYYY-MM-DD."},Dhe={type:"string",description:"Optional latest transaction date as YYYY-MM-DD."},khe={type:"object",description:"Optional extra NetSuite REST field values merged into the record body as-is, e.g. custom fields like { custentity_region: 'EMEA' } or references like { terms: { id: '2' } }. Fields that this tool's own inputs set are rejected; use those inputs instead.",properties:{},additionalProperties:!0},PA=t=>({input:"activeOnly",kind:"flag",clause:`${t}.isinactive = 'F'`,schema:vhe}),LA=t=>({input:"subsidiaryId",kind:"id",clause:`${t}.subsidiary = $`,schema:Qhe}),aw=[{input:"fromDate",kind:"date",clause:"t.trandate >= TO_DATE('$', 'YYYY-MM-DD')",schema:The},{input:"toDate",kind:"date",clause:"t.trandate <= TO_DATE('$', 'YYYY-MM-DD')",schema:Dhe}];function Rhe(t){let e=`p[${JSON.stringify(t.input)}]`;if(t.kind==="flag")return`if (${e} === true || ${e} === 'true') where.push(${JSON.stringify(t.clause)});`;let[r,n]=t.clause.split("$");if(t.kind==="enum")return`if (has(${e})) { const allowed = ${JSON.stringify(t.values)}; if (!allowed.includes(String(${e}))) throw new Error(${JSON.stringify(`${t.input} must be one of: ${t.values.join(", ")}.`)}); where.push(${JSON.stringify(r)} + String(${e}) + ${JSON.stringify(n)}); }`;if(t.kind==="prefix")return`if (has(${e})) { const text = String(${e}).trim(); if (!/^[A-Za-z0-9._-]{1,40}$/.test(text)) throw new Error(${JSON.stringify(`${t.input} may only contain letters, digits, dots, underscores and hyphens.`)}); where.push(${JSON.stringify(r)} + text + ${JSON.stringify(n)}); }`;let i=t.kind==="id"?"nsId":"nsDate";return`if (has(${e})) where.push(${JSON.stringify(r)} + ${i}(${e}, ${JSON.stringify(t.input)}) + ${JSON.stringify(n)});`}function ya({id:t,name:e,shortName:r,instruction:n,stepId:i,collection:o,select:s,baseWhere:a=[],orderBy:c,filters:l=[],properties:u={},required:d=[],mapRow:A}){let p=typeof s=="string"?JSON.stringify(s):s.js,h=`<<(p) => { ${uw} const where = ${JSON.stringify(a)}; ${l.map(Rhe).join(" ")} return JSON.stringify({ q: ${p} + (where.length ? ' WHERE ' + where.join(' AND ') : '') + ${JSON.stringify(` ORDER BY ${c}`)} }); }>>`;return{id:t,name:e,shortName:r,instruction:`${n} Rows are ordered by internal ID. If more than ${$A} rows match, narrow with the filters or page with the SuiteQL query tool (ORDER BY id, WHERE id > last id).`,inputSchema:{type:"object",properties:{...u,maxResults:Bhe,...Object.fromEntries(l.map(f=>[f.input,f.schema]))},...d.length>0?{required:d}:{},additionalProperties:!1},steps:[{id:i,instruction:"Run the SuiteQL query page by page.",config:{type:"request",systemId:FA,url:`${km}/query/v1/suiteql`,method:"POST",headers:{...Rm,"Content-Type":"application/json",Prefer:"transient"},queryParams:{limit:"1000",offset:"<<offset>>"},body:h,pagination:{type:"offsetBased",pageSize:"1000",stopCondition:`(response, pageInfo, sourceData) => { if (sourceData && ["offset", "limit", "page"].some((key) => sourceData[key] !== undefined)) throw new Error("offset, limit and page are not inputs of this tool: use maxResults and the filters."); const page = response && response.data ? response.data : {}; const merged = pageInfo && pageInfo.mergedResult && Array.isArray(pageInfo.mergedResult.items) ? pageInfo.mergedResult.items.length : 0; const max = Math.min(Math.max(Math.floor(Number(sourceData && sourceData.maxResults)) || ${lw}, 1), ${$A}); return page.hasMore !== true || merged >= max; }`}}}],outputTransform:`(sourceData) => { ${_he} const raw = sourceData.${i} ? sourceData.${i}.data : undefined; const pages = Array.isArray(raw) ? raw : (raw ? [raw] : []); const items = pages.flatMap((page) => (page && Array.isArray(page.items) ? page.items : [])); const last = pages.length ? pages[pages.length - 1] : {}; const max = Math.min(Math.max(Math.floor(Number(sourceData.maxResults)) || ${lw}, 1), ${$A}); const rows = items.slice(0, max).map(${A}).map((row) => Object.fromEntries(Object.entries(row).filter((entry) => entry[1] !== null))); const total = last && last.totalResults !== undefined ? Number(last.totalResults) : items.length; return { total, returned: rows.length, hasMore: total > rows.length, ${o}: rows }; }`}}function Kr({id:t,name:e,shortName:r,instruction:n,stepId:i,recordType:o,mode:s,properties:a,required:c,body:l,replaceSublist:u}){let d=[...new Set(Array.from(l.matchAll(/record\.([A-Za-z0-9_]+)\s*=/g)).map(p=>p[1]))],A=s==="create"?`/record/v1/${o}`:`/record/v1/${o}/<<(p) => { ${uw} return nsId(p.internalId, 'internalId'); }>>`;return{id:t,name:e,shortName:r,instruction:n,inputSchema:{type:"object",properties:{...s==="update"?{internalId:{type:"string",description:`Internal ID of the ${o} to update.`}}:{},...a,fields:khe},required:s==="update"?["internalId",...c]:c,additionalProperties:!1},steps:[{id:i,instruction:`${s==="create"?"Create":"Update"} the ${o} record.`,modify:!0,config:{type:"request",systemId:FA,url:`${km}${A}`,method:s==="create"?"POST":"PATCH",headers:{...Rm,"Content-Type":"application/json","X-NetSuite-idempotency-key":"<<() => crypto.randomUUID()>>"},...u?{queryParams:{replace:`<<(p) => (Array.isArray(p[${JSON.stringify(u.input)}]) && p[${JSON.stringify(u.input)}].length > 0 ? ${JSON.stringify(u.sublist)} : undefined)>>`}}:{},body:`<<(p) => { ${uw} const record = {}; ${l} if (p.fields && typeof p.fields === 'object' && !Array.isArray(p.fields)) { const managed = ${JSON.stringify(d)}; const reserved = Object.keys(p.fields).filter((key) => managed.includes(key)); if (reserved.length > 0) throw new Error('fields may not set ' + reserved.join(', ') + ': use this tool\\'s own inputs for them.'); Object.assign(record, p.fields); } if (Object.keys(record).length === 0) throw new Error('Provide at least one field to ${s}.'); return JSON.stringify(record); }>>`,captureHttpResponse:!0}}],outputTransform:s==="create"?`(sourceData) => { const step = sourceData.${i} || {}; const location = step.http && step.http.headers ? String(step.http.headers.location || '') : ''; const match = location.match(/\\/record\\/v1\\/[^/]+\\/([^/?#]+)/); if (!match) throw new Error('NetSuite did not return the location of the new ${o}.'); return { id: decodeURIComponent(match[1]), recordType: '${o}' }; }`:`(sourceData) => ({ id: String(sourceData.internalId).trim(), recordType: '${o}', updated: true })`}}var EL=String.raw`const lines = Array.isArray(p.lines) ? p.lines : []; let balance = 0; const items = lines.map((line, index) => { const amount = Number(line && line.amount); if (!Number.isFinite(amount) || amount <= 0) throw new Error('lines[' + index + '].amount must be a positive number.'); if (line.type !== 'debit' && line.type !== 'credit') throw new Error("lines[" + index + "].type must be 'debit' or 'credit'."); balance += line.type === 'debit' ? amount : -amount; const item = { account: ref(line.accountId, 'lines[' + index + '].accountId') }; item[line.type] = amount; if (has(line.memo)) item.memo = String(line.memo); if (has(line.departmentId)) item.department = ref(line.departmentId, 'lines[' + index + '].departmentId'); if (has(line.classId)) item.class = ref(line.classId, 'lines[' + index + '].classId'); if (has(line.locationId)) item.location = ref(line.locationId, 'lines[' + index + '].locationId'); if (has(line.entityId)) item.entity = ref(line.entityId, 'lines[' + index + '].entityId'); return item; }); if (lines.length > 0 && Math.abs(balance) > 0.005) throw new Error('Journal lines must balance: debits minus credits is ' + balance.toFixed(2) + '.'); if (items.length > 0) record.line = { items };`,IL=String.raw`if (has(p.subsidiaryId)) record.subsidiary = ref(p.subsidiaryId, 'subsidiaryId'); if (has(p.date)) record.tranDate = nsDate(p.date, 'date'); if (has(p.memo)) record.memo = String(p.memo); if (has(p.currencyId)) record.currency = ref(p.currencyId, 'currencyId'); if (has(p.externalId)) record.externalId = String(p.externalId);`,CL={type:"object",properties:{accountId:{type:"string",description:"GL account internal ID."},type:{type:"string",enum:["debit","credit"]},amount:{type:"number",description:"Positive amount."},memo:{type:"string",description:"Optional line memo."},departmentId:{type:"string",description:"Optional department internal ID."},classId:{type:"string",description:"Optional class internal ID."},locationId:{type:"string",description:"Optional location internal ID."},entityId:{type:"string",description:"Optional customer, vendor or employee internal ID for the line."}},required:["accountId","type","amount"],additionalProperties:!1},bL=t=>({subsidiaryId:{type:"string",description:t==="create"?"Subsidiary internal ID. Required in OneWorld accounts.":"Optional new subsidiary internal ID."},date:{type:"string",description:t==="create"?"Transaction date as YYYY-MM-DD.":"Optional new transaction date as YYYY-MM-DD."},memo:{type:"string",description:"Journal entry memo."},currencyId:{type:"string",description:"Optional currency internal ID."},externalId:{type:"string",description:"Optional external ID."}}),_m=String.raw`if (p.isPerson === true || p.isPerson === 'true') record.isPerson = true; if (p.isPerson === false || p.isPerson === 'false') record.isPerson = false; if (has(p.entityId)) record.entityId = String(p.entityId); if (has(p.companyName)) record.companyName = String(p.companyName); if (has(p.firstName)) record.firstName = String(p.firstName); if (has(p.lastName)) record.lastName = String(p.lastName); if (has(p.subsidiaryId)) record.subsidiary = ref(p.subsidiaryId, 'subsidiaryId'); if (has(p.email)) record.email = String(p.email); if (has(p.phone)) record.phone = String(p.phone); if (has(p.currencyId)) record.currency = ref(p.currencyId, 'currencyId'); if (has(p.externalId)) record.externalId = String(p.externalId); if (p.isInactive === true || p.isInactive === 'true') record.isInactive = true; if (p.isInactive === false || p.isInactive === 'false') record.isInactive = false;`;function Bm(t){return{companyName:{type:"string",description:`Company name of the ${t}.`},isPerson:{type:"boolean",description:`True when the ${t} is an individual; then set firstName and lastName.`},firstName:{type:"string",description:"First name for an individual."},lastName:{type:"string",description:"Last name for an individual."},entityId:{type:"string",description:`${t==="customer"?"Customer":"Vendor"} ID. Omit when auto-numbering assigns it.`},subsidiaryId:{type:"string",description:"Primary subsidiary internal ID. Required on create in OneWorld accounts."},email:{type:"string",description:"Email address."},phone:{type:"string",description:"Phone number."},currencyId:{type:"string",description:"Primary currency internal ID."},externalId:{type:"string",description:"Optional external ID."}}}var vm={isInactive:{type:"boolean",description:"Set true to inactivate, false to reactivate."}},Qm=String.raw`if (Array.isArray(p.subsidiaryIds) && p.subsidiaryIds.length > 0) record.subsidiary = { items: p.subsidiaryIds.map((value, index) => ref(value, 'subsidiaryIds[' + index + ']')) }; if (p.includeChildren === true || p.includeChildren === 'true') record.includeChildren = true; if (p.includeChildren === false || p.includeChildren === 'false') record.includeChildren = false;`,kL={subsidiaryIds:{type:"array",items:{type:"string"},description:"Subsidiary internal IDs the record is available in. On update the list replaces the current subsidiaries."},includeChildren:{type:"boolean",description:"Also make the record available to child subsidiaries."}},dw=["AcctPay","AcctRec","Bank","COGS","CredCard","DeferExpense","DeferRevenue","Equity","Expense","FixedAsset","Income","LongTermLiab","NonPosting","OthAsset","OthCurrAsset","OthCurrLiab","OthExpense","OthIncome","Stat","UnbilledRec"],SL=String.raw`if (has(p.acctNumber)) record.acctNumber = String(p.acctNumber); if (has(p.acctName)) record.acctName = String(p.acctName); if (has(p.acctType)) record.acctType = { id: String(p.acctType) }; if (has(p.parentId)) record.parent = ref(p.parentId, 'parentId'); if (has(p.description)) record.description = String(p.description); if (has(p.currencyId)) record.currency = ref(p.currencyId, 'currencyId'); if (has(p.externalId)) record.externalId = String(p.externalId); if (p.isInactive === true || p.isInactive === 'true') record.isInactive = true; if (p.isInactive === false || p.isInactive === 'false') record.isInactive = false;`,wL={acctNumber:{type:"string",description:"Account number."},acctName:{type:"string",description:"Account name."},acctType:{type:"string",enum:dw,description:"NetSuite account type."},parentId:{type:"string",description:"Optional parent account internal ID."},description:{type:"string",description:"Optional description."},currencyId:{type:"string",description:"Optional currency internal ID (bank and credit card accounts)."},externalId:{type:"string",description:"Optional external ID."},...kL},_L=String.raw`if (has(p.name)) record.name = String(p.name); if (has(p.parentId)) record.parent = ref(p.parentId, 'parentId'); if (has(p.externalId)) record.externalId = String(p.externalId); if (p.isInactive === true || p.isInactive === 'true') record.isInactive = true; if (p.isInactive === false || p.isInactive === 'false') record.isInactive = false;`,BL={name:{type:"string",description:"Department name."},parentId:{type:"string",description:"Optional parent department internal ID."},externalId:{type:"string",description:"Optional external ID."},...kL},Tm=t=>String.raw`if (has(p.${t})) record.entity = ref(p.${t}, '${t}'); if (has(p.subsidiaryId)) record.subsidiary = ref(p.subsidiaryId, 'subsidiaryId'); if (has(p.date)) record.tranDate = nsDate(p.date, 'date'); if (has(p.dueDate)) record.dueDate = nsDate(p.dueDate, 'dueDate'); if (has(p.memo)) record.memo = String(p.memo); if (has(p.currencyId)) record.currency = ref(p.currencyId, 'currencyId'); if (has(p.termsId)) record.terms = ref(p.termsId, 'termsId'); if (has(p.departmentId)) record.department = ref(p.departmentId, 'departmentId'); if (has(p.classId)) record.class = ref(p.classId, 'classId'); if (has(p.locationId)) record.location = ref(p.locationId, 'locationId'); if (has(p.externalId)) record.externalId = String(p.externalId);`,Dm=t=>({subsidiaryId:{type:"string",description:t==="create"?"Optional subsidiary internal ID; defaults to the entity's subsidiary.":"Optional new subsidiary internal ID."},date:{type:"string",description:t==="create"?"Transaction date as YYYY-MM-DD.":"Optional new transaction date as YYYY-MM-DD."},dueDate:{type:"string",description:"Optional due date as YYYY-MM-DD."},memo:{type:"string",description:"Optional memo."},currencyId:{type:"string",description:"Optional currency internal ID."},termsId:{type:"string",description:"Optional payment terms internal ID."},departmentId:{type:"string",description:"Optional header department internal ID."},classId:{type:"string",description:"Optional header class internal ID."},locationId:{type:"string",description:"Optional header location internal ID."},externalId:{type:"string",description:"Optional external ID."}}),RL=String.raw`if (has(line.departmentId)) item.department = ref(line.departmentId, 'lines[' + index + '].departmentId'); if (has(line.classId)) item.class = ref(line.classId, 'lines[' + index + '].classId'); if (has(line.locationId)) item.location = ref(line.locationId, 'lines[' + index + '].locationId');`,vL=String.raw`if (Array.isArray(p.lines) && p.lines.length > 0) record.item = { items: p.lines.map((line, index) => { const item = { item: ref(line && line.itemId, 'lines[' + index + '].itemId') }; if (has(line.quantity)) { const quantity = Number(line.quantity); if (!Number.isFinite(quantity)) throw new Error('lines[' + index + '].quantity must be a number.'); item.quantity = quantity; } if (has(line.rate)) { const rate = Number(line.rate); if (!Number.isFinite(rate)) throw new Error('lines[' + index + '].rate must be a number.'); item.rate = rate; } if (has(line.amount)) { const amount = Number(line.amount); if (!Number.isFinite(amount)) throw new Error('lines[' + index + '].amount must be a number.'); item.amount = amount; } if (has(line.description)) item.description = String(line.description); if (has(line.taxCodeId)) item.taxCode = ref(line.taxCodeId, 'lines[' + index + '].taxCodeId'); ${RL} return item; }) };`,QL={type:"object",properties:{itemId:{type:"string",description:"Item internal ID."},quantity:{type:"number",description:"Optional quantity. Defaults to 1."},rate:{type:"number",description:"Optional unit price; defaults to the item price."},amount:{type:"number",description:"Optional line amount."},description:{type:"string",description:"Optional line description."},taxCodeId:{type:"string",description:"Optional tax code internal ID."},departmentId:{type:"string",description:"Optional department internal ID."},classId:{type:"string",description:"Optional class internal ID. Some accounts ignore line classes on invoices; check the saved record."},locationId:{type:"string",description:"Optional location internal ID."}},required:["itemId"],additionalProperties:!1},TL=String.raw`if (Array.isArray(p.lines) && p.lines.length > 0) record.expense = { items: p.lines.map((line, index) => { const amount = Number(line && line.amount); if (!Number.isFinite(amount) || amount <= 0) throw new Error('lines[' + index + '].amount must be a positive number.'); const item = { account: ref(line.accountId, 'lines[' + index + '].accountId'), amount }; if (has(line.memo)) item.memo = String(line.memo); ${RL} return item; }) };`,DL={type:"object",properties:{accountId:{type:"string",description:"Expense account internal ID."},amount:{type:"number",description:"Positive amount."},memo:{type:"string",description:"Optional line memo."},departmentId:{type:"string",description:"Optional department internal ID."},classId:{type:"string",description:"Optional class internal ID."},locationId:{type:"string",description:"Optional location internal ID."}},required:["accountId","amount"],additionalProperties:!1},vc="Re-running this tool creates another record; it is not idempotent.",Nhe=[ya({id:"netsuite-list-accounts",name:"List NetSuite chart of accounts",shortName:"Chart of accounts",instruction:"Lists general ledger accounts (the chart of accounts) from NetSuite with number, name, type, parent and subsidiaries. Useful for validating an imported chart of accounts.",stepId:"queryAccounts",collection:"accounts",select:"SELECT a.id, a.acctnumber, a.accountsearchdisplaynamecopy AS name, a.fullname, a.accttype, a.parent, a.subsidiary, cur.symbol AS currency, a.description, a.issummary, a.isinactive FROM account a LEFT JOIN currency cur ON cur.id = a.currency",orderBy:"a.id",filters:[PA("a"),{input:"accountType",kind:"enum",values:dw,clause:"a.accttype = '$'",schema:{type:"string",enum:dw,description:"Only accounts of this NetSuite account type, e.g. Bank or Expense."}},{input:"numberPrefix",kind:"prefix",clause:"a.acctnumber LIKE '$%'",schema:{type:"string",description:"Only accounts whose number starts with this value, e.g. 1000 or 60."}}],mapRow:"(row) => ({ id: row.id, number: str(row.acctnumber), name: str(row.name), fullName: str(row.fullname), type: str(row.accttype), parentId: str(row.parent), subsidiaryIds: ids(row.subsidiary), currency: str(row.currency), description: str(row.description), isSummary: bool(row.issummary), isInactive: bool(row.isinactive) })"}),ya({id:"netsuite-list-customers",name:"List NetSuite customers",shortName:"Customers",instruction:"Lists customer records from NetSuite with subsidiary, currency and open balance. Useful for verifying migrated AR master data.",stepId:"queryCustomers",collection:"customers",select:"SELECT c.id, c.entityid, c.companyname, c.isperson, c.firstname, c.lastname, c.email, c.phone, c.subsidiary, BUILTIN.DF(c.subsidiary) AS subsidiaryname, cur.symbol AS currency, c.balancesearch, c.overduebalancesearch, c.isinactive, TO_CHAR(c.datecreated, 'YYYY-MM-DD') AS datecreated, TO_CHAR(c.lastmodifieddate, 'YYYY-MM-DD') AS lastmodified FROM customer c LEFT JOIN currency cur ON cur.id = c.currency",orderBy:"c.id",filters:[PA("c"),LA("c")],mapRow:"(row) => ({ id: row.id, entityId: str(row.entityid), companyName: str(row.companyname), isPerson: bool(row.isperson), firstName: str(row.firstname), lastName: str(row.lastname), email: str(row.email), phone: str(row.phone), subsidiaryId: str(row.subsidiary), subsidiary: str(row.subsidiaryname), currency: str(row.currency), balance: num(row.balancesearch), overdueBalance: num(row.overduebalancesearch), isInactive: bool(row.isinactive), createdOn: str(row.datecreated), modifiedOn: str(row.lastmodified) })"}),ya({id:"netsuite-list-vendors",name:"List NetSuite vendors",shortName:"Vendors",instruction:"Lists vendor records from NetSuite with subsidiary, currency and balance. Useful for verifying migrated AP master data.",stepId:"queryVendors",collection:"vendors",select:"SELECT v.id, v.entityid, v.companyname, v.isperson, v.firstname, v.lastname, v.email, v.phone, v.subsidiary, BUILTIN.DF(v.subsidiary) AS subsidiaryname, cur.symbol AS currency, v.balance, v.isinactive, TO_CHAR(v.datecreated, 'YYYY-MM-DD') AS datecreated, TO_CHAR(v.lastmodifieddate, 'YYYY-MM-DD') AS lastmodified FROM vendor v LEFT JOIN currency cur ON cur.id = v.currency",orderBy:"v.id",filters:[PA("v"),LA("v")],mapRow:"(row) => ({ id: row.id, entityId: str(row.entityid), companyName: str(row.companyname), isPerson: bool(row.isperson), firstName: str(row.firstname), lastName: str(row.lastname), email: str(row.email), phone: str(row.phone), subsidiaryId: str(row.subsidiary), subsidiary: str(row.subsidiaryname), currency: str(row.currency), balance: num(row.balance), isInactive: bool(row.isinactive), createdOn: str(row.datecreated), modifiedOn: str(row.lastmodified) })"}),ya({id:"netsuite-list-journal-entries",name:"List NetSuite journal entries",shortName:"Journal entries",instruction:"Lists journal entry lines from NetSuite, one row per GL line and accounting book with journal, date, period, account, debit, credit and dimensions. Useful for verifying opening balances and postings at cutover.",stepId:"queryJournalLines",collection:"journalLines",select:"SELECT t.id AS journalid, t.tranid, TO_CHAR(t.trandate, 'YYYY-MM-DD') AS trandate, BUILTIN.DF(t.postingperiod) AS period, t.subsidiary, BUILTIN.DF(t.status) AS status, t.posting, t.memo AS journalmemo, cur.symbol AS currency, tl.id AS lineid, tal.accountingbook, tal.account, a.acctnumber, a.accountsearchdisplaynamecopy AS accountname, tal.debit, tal.credit, tl.memo, tl.department, tl.class, tl.location, tl.entity FROM transaction t JOIN transactionline tl ON tl.transaction = t.id JOIN transactionaccountingline tal ON tal.transaction = tl.transaction AND tal.transactionline = tl.id JOIN account a ON a.id = tal.account LEFT JOIN currency cur ON cur.id = t.currency",baseWhere:["t.type = 'Journal'"],orderBy:"t.id, tl.id, tal.accountingbook",filters:[...aw,LA("t")],mapRow:"(row) => ({ journalId: row.journalid, tranId: str(row.tranid), date: str(row.trandate), period: str(row.period), subsidiaryId: str(row.subsidiary), status: status(row.status), posting: bool(row.posting), journalMemo: str(row.journalmemo), currency: str(row.currency), line: num(row.lineid), accountingBookId: str(row.accountingbook), accountId: str(row.account), accountNumber: str(row.acctnumber), accountName: str(row.accountname), debit: num(row.debit), credit: num(row.credit), memo: str(row.memo), departmentId: str(row.department), classId: str(row.class), locationId: str(row.location), entityId: str(row.entity) })"}),ya({id:"netsuite-list-invoices",name:"List NetSuite invoices",shortName:"Invoices",instruction:"Lists customer invoices from NetSuite with customer, dates, status, total and amount due. Useful for verifying migrated open AR at go-live.",stepId:"queryInvoices",collection:"invoices",select:"SELECT t.id, t.tranid, t.entity, BUILTIN.DF(t.entity) AS customername, TO_CHAR(t.trandate, 'YYYY-MM-DD') AS trandate, TO_CHAR(t.duedate, 'YYYY-MM-DD') AS duedate, BUILTIN.DF(t.status) AS status, cur.symbol AS currency, t.foreigntotal, t.foreignamountunpaid, t.subsidiary, t.memo FROM transaction t LEFT JOIN currency cur ON cur.id = t.currency",baseWhere:["t.type = 'CustInvc'"],orderBy:"t.id",filters:[...aw,LA("t"),{input:"openOnly",kind:"flag",clause:"t.status = 'A'",schema:{type:"boolean",description:"Only return open (unpaid) invoices."}}],mapRow:"(row) => ({ id: row.id, tranId: str(row.tranid), customerId: str(row.entity), customer: str(row.customername), date: str(row.trandate), dueDate: str(row.duedate), status: status(row.status), currency: str(row.currency), total: num(row.foreigntotal), amountDue: num(row.foreignamountunpaid), subsidiaryId: str(row.subsidiary), memo: str(row.memo) })"}),ya({id:"netsuite-list-vendor-bills",name:"List NetSuite vendor bills",shortName:"Vendor bills",instruction:"Lists vendor bills from NetSuite with vendor, dates, status, approval status, total and amount due. Useful for verifying migrated open AP at go-live.",stepId:"queryBills",collection:"bills",select:"SELECT t.id, t.tranid, t.entity, BUILTIN.DF(t.entity) AS vendorname, TO_CHAR(t.trandate, 'YYYY-MM-DD') AS trandate, TO_CHAR(t.duedate, 'YYYY-MM-DD') AS duedate, BUILTIN.DF(t.status) AS status, BUILTIN.DF(t.approvalstatus) AS approvalstatus, cur.symbol AS currency, t.foreigntotal, t.foreignamountunpaid, t.subsidiary, t.memo FROM transaction t LEFT JOIN currency cur ON cur.id = t.currency",baseWhere:["t.type = 'VendBill'"],orderBy:"t.id",filters:[...aw,LA("t"),{input:"openOnly",kind:"flag",clause:"t.status = 'A'",schema:{type:"boolean",description:"Only return open bills (approved and not fully paid)."}}],mapRow:"(row) => ({ id: row.id, referenceNo: str(row.tranid), vendorId: str(row.entity), vendor: str(row.vendorname), date: str(row.trandate), dueDate: str(row.duedate), status: status(row.status), approvalStatus: str(row.approvalstatus), currency: str(row.currency), total: row.foreigntotal === undefined ? null : Math.abs(Number(row.foreigntotal)), amountDue: num(row.foreignamountunpaid), subsidiaryId: str(row.subsidiary), memo: str(row.memo) })"}),ya({id:"netsuite-list-dimensions",name:"List NetSuite departments, classes or locations",shortName:"Departments, classes, locations",instruction:"Lists department, class or location records from NetSuite with hierarchy and subsidiaries. Useful for validating the dimension setup after an implementation and for finding the internal IDs the write tools need.",stepId:"queryDimensions",collection:"records",properties:{dimension:{type:"string",enum:["department","class","location"],description:"Which dimension to list."}},required:["dimension"],select:{js:String.raw`'SELECT d.id, d.name, d.fullname, d.parent, d.subsidiary, d.includechildren, d.isinactive FROM ' + (() => { const table = { department: 'department', class: 'classification', location: 'location' }[String(p.dimension || '')]; if (!table) throw new Error("dimension must be 'department', 'class' or 'location'."); return table; })() + ' d'`},orderBy:"d.id",filters:[PA("d")],mapRow:"(row) => ({ id: row.id, name: str(row.name), fullName: str(row.fullname), parentId: str(row.parent), subsidiaryIds: ids(row.subsidiary), includeChildren: bool(row.includechildren), isInactive: bool(row.isinactive) })"}),ya({id:"netsuite-list-subsidiaries",name:"List NetSuite subsidiaries",shortName:"Subsidiaries",instruction:"Lists subsidiaries from NetSuite with hierarchy, country, base currency and elimination flag. Most create tools need a subsidiary ID from this list in OneWorld accounts.",stepId:"querySubsidiaries",collection:"subsidiaries",select:"SELECT s.id, s.name, s.fullname, s.parent, s.country, cur.symbol AS currency, s.iselimination, s.isinactive FROM subsidiary s LEFT JOIN currency cur ON cur.id = s.currency",orderBy:"s.id",filters:[PA("s")],mapRow:"(row) => ({ id: row.id, name: str(row.name), fullName: str(row.fullname), parentId: str(row.parent), country: str(row.country), currency: str(row.currency), isElimination: bool(row.iselimination), isInactive: bool(row.isinactive) })"}),{id:"netsuite-suiteql-query",name:"Run a NetSuite SuiteQL query",shortName:"SuiteQL query",instruction:"Runs a read-only SuiteQL SELECT query against NetSuite, for any record type, join or aggregate outside the prebuilt lists (for example items, employees, transaction lines or custom records). The workhorse tool for migration validation. Returns up to 1000 rows in one call with the total row count and hasMore; values are strings as NetSuite returns them.",inputSchema:{type:"object",properties:{query:{type:"string",description:`SuiteQL SELECT statement, e.g. "SELECT id, itemid, displayname FROM item WHERE isinactive = 'F' ORDER BY id". Dates come back in the user's date format; use TO_CHAR(field, 'YYYY-MM-DD') for ISO dates and BUILTIN.DF(field) for display names. For more than 1000 rows, page by key: ORDER BY id and add WHERE id > <last id>. Common columns: account (id, acctnumber, accountsearchdisplaynamecopy as the name, fullname, accttype, isinactive; there is no acctname column), customer (id, entityid, companyname, email, subsidiary, balancesearch, isinactive), vendor (id, entityid, companyname, email, subsidiary, balance, isinactive), transaction (id, tranid, type, trandate, entity, status, foreigntotal, foreignamountunpaid, subsidiary). Alias tables and qualify columns: FROM transaction t ... t.subsidiary works, an unqualified subsidiary fails.`},maxResults:{type:"integer",minimum:1,maximum:1e3,description:"Maximum number of rows to return (max 1000). Defaults to 100."}},required:["query"],additionalProperties:!1},steps:[{id:"runSuiteQl",instruction:"Run the SuiteQL query.",config:{type:"request",systemId:FA,url:`${km}/query/v1/suiteql`,method:"POST",headers:{...Rm,"Content-Type":"application/json",Prefer:"transient"},queryParams:{limit:"<<(p) => Math.min(Math.max(Math.floor(Number(p.maxResults)) || 100, 2), 1000)>>",offset:"0"},body:String.raw`<<(p) => { const query = String(p.query || '').trim(); if (!/^(select|with)\b/i.test(query)) throw new Error('query must be a SuiteQL SELECT statement.'); return JSON.stringify({ q: query }); }>>`}}],outputTransform:`(sourceData) => { ${yL} const data = sourceData.runSuiteQl && sourceData.runSuiteQl.data ? sourceData.runSuiteQl.data : {}; const items = Array.isArray(data.items) ? data.items : []; const max = Math.min(Math.max(Math.floor(Number(sourceData.maxResults)) || 100, 1), 1000); const records = stripLinks(items.slice(0, max)); const total = data.totalResults !== undefined ? Number(data.totalResults) : items.length; return { total, returned: records.length, hasMore: total > records.length, records }; }`},{id:"netsuite-get-record",name:"Get a NetSuite record",shortName:"Get record",instruction:"Fetches one NetSuite record of any type by internal ID or external ID through the REST record API, including its sublists such as transaction lines. Useful for inspecting a record in full before or after a write.",inputSchema:{type:"object",properties:{recordType:{type:"string",description:'REST record type, e.g. "customer", "vendor", "invoice", "vendorbill", "journalentry", "account", "department" or a custom record like "customrecord_x".'},internalId:{type:"string",description:"Internal ID of the record."},externalId:{type:"string",description:"External ID of the record, used when internalId is not set."},expandSubResources:{type:"boolean",description:"Include sublists and subrecords inline. Defaults to true."}},required:["recordType"],additionalProperties:!1},steps:[{id:"getRecord",instruction:"Fetch the record from the REST record API.",config:{type:"request",systemId:FA,url:`${km}/record/v1/<<(p) => { const type = String(p.recordType || '').trim().toLowerCase(); if (!/^[a-z][a-z0-9_]*$/.test(type)) throw new Error('recordType must contain only letters, numbers and underscores.'); return type; }>>/<<(p) => { if (p.internalId !== undefined && p.internalId !== null && p.internalId !== '') { const id = String(p.internalId).trim(); if (!/^-?\\d+$/.test(id)) throw new Error('internalId must be a NetSuite internal ID.'); return id; } if (p.externalId !== undefined && p.externalId !== null && p.externalId !== '') return 'eid:' + encodeURIComponent(String(p.externalId)); throw new Error('Provide internalId or externalId.'); }>>`,method:"GET",headers:Rm,queryParams:{expandSubResources:"<<(p) => (p.expandSubResources === false || p.expandSubResources === 'false' ? 'false' : 'true')>>"}}}],outputTransform:`(sourceData) => { ${yL} const record = sourceData.getRecord ? sourceData.getRecord.data : undefined; if (!record || typeof record !== 'object') throw new Error('NetSuite returned no record.'); return { record: stripLinks(record) }; }`},Kr({id:"netsuite-create-journal-entry",name:"Create NetSuite journal entry",shortName:"Create journal entry",instruction:`Creates a journal entry in NetSuite through the REST record API. Debit and credit lines must balance. Returns the new internal ID. ${vc}`,stepId:"createJournalEntry",recordType:"journalentry",mode:"create",properties:{...bL("create"),lines:{type:"array",description:"Journal lines. Debit and credit totals must balance.",items:CL}},required:["date","lines"],body:`${IL} if (!Array.isArray(p.lines) || p.lines.length < 2) throw new Error('lines must contain at least two journal lines.'); ${EL}`}),Kr({id:"netsuite-update-journal-entry",name:"Update NetSuite journal entry",shortName:"Update journal entry",instruction:"Updates an existing NetSuite journal entry by internal ID. Only the provided fields change. When lines are provided they replace all existing lines and must balance. Entries in closed periods refuse updates.",stepId:"updateJournalEntry",recordType:"journalentry",mode:"update",properties:{...bL("update"),lines:{type:"array",description:"Optional replacement lines. When set, they replace every existing line and must balance.",items:CL}},required:[],body:`${IL} if (Array.isArray(p.lines) && p.lines.length < 2) throw new Error('lines must contain at least two journal lines; omit lines to keep the current ones.'); ${EL}`,replaceSublist:{input:"lines",sublist:"line"}}),Kr({id:"netsuite-create-vendor",name:"Create NetSuite vendor",shortName:"Create vendor",instruction:`Creates a vendor record in NetSuite. OneWorld accounts need a subsidiaryId. Omit entityId when auto-numbering assigns it. ${vc}`,stepId:"createVendor",recordType:"vendor",mode:"create",properties:Bm("vendor"),required:[],body:`if (!has(p.companyName) && !((p.isPerson === true || p.isPerson === 'true') && has(p.lastName))) throw new Error('Provide companyName, or isPerson with lastName.'); ${_m}`}),Kr({id:"netsuite-update-vendor",name:"Update NetSuite vendor",shortName:"Update vendor",instruction:"Updates an existing NetSuite vendor by internal ID. Only the provided fields change; set isInactive to inactivate or reactivate it.",stepId:"updateVendor",recordType:"vendor",mode:"update",properties:{...Bm("vendor"),...vm},required:[],body:_m}),Kr({id:"netsuite-create-customer",name:"Create NetSuite customer",shortName:"Create customer",instruction:`Creates a customer record in NetSuite. OneWorld accounts need a subsidiaryId. Omit entityId when auto-numbering assigns it. ${vc}`,stepId:"createCustomer",recordType:"customer",mode:"create",properties:Bm("customer"),required:[],body:`if (!has(p.companyName) && !((p.isPerson === true || p.isPerson === 'true') && has(p.lastName))) throw new Error('Provide companyName, or isPerson with lastName.'); ${_m}`}),Kr({id:"netsuite-update-customer",name:"Update NetSuite customer",shortName:"Update customer",instruction:"Updates an existing NetSuite customer by internal ID. Only the provided fields change; set isInactive to inactivate or reactivate it.",stepId:"updateCustomer",recordType:"customer",mode:"update",properties:{...Bm("customer"),...vm},required:[],body:_m}),Kr({id:"netsuite-create-account",name:"Create NetSuite GL account",shortName:"Create GL account",instruction:`Creates a general ledger account in NetSuite's chart of accounts. ${vc}`,stepId:"createAccount",recordType:"account",mode:"create",properties:wL,required:["acctName","acctType"],body:`if (!has(p.acctName) || !has(p.acctType)) throw new Error('acctName and acctType are required.'); ${SL} ${Qm}`}),Kr({id:"netsuite-update-account",name:"Update NetSuite GL account",shortName:"Update GL account",instruction:"Updates an existing NetSuite GL account by internal ID. Only the provided fields change; set isInactive to inactivate or reactivate it. Accounts with transactions may refuse a type change.",stepId:"updateAccount",recordType:"account",mode:"update",properties:{...wL,...vm},required:[],body:`${SL} ${Qm}`}),Kr({id:"netsuite-create-invoice",name:"Create NetSuite invoice",shortName:"Create invoice",instruction:`Creates a customer invoice in NetSuite with item lines. Item, tax and posting rules of the account apply. ${vc}`,stepId:"createInvoice",recordType:"invoice",mode:"create",properties:{customerId:{type:"string",description:"Customer internal ID."},...Dm("create"),lines:{type:"array",description:"Item lines.",items:QL}},required:["customerId","lines"],body:`if (!Array.isArray(p.lines) || p.lines.length === 0) throw new Error('lines must contain at least one item line.'); ${Tm("customerId")} ${vL}`}),Kr({id:"netsuite-update-invoice",name:"Update NetSuite invoice",shortName:"Update invoice",instruction:"Updates an existing NetSuite invoice by internal ID. Only the provided fields change. When lines are provided they replace all existing item lines. Paid invoices and closed periods may refuse updates.",stepId:"updateInvoice",recordType:"invoice",mode:"update",properties:{customerId:{type:"string",description:"Optional new customer internal ID."},...Dm("update"),lines:{type:"array",description:"Optional replacement item lines; they replace every existing item line.",items:QL}},required:[],body:`if (Array.isArray(p.lines) && p.lines.length === 0) throw new Error('lines must contain at least one item line; omit lines to keep the current ones.'); ${Tm("customerId")} ${vL}`,replaceSublist:{input:"lines",sublist:"item"}}),Kr({id:"netsuite-create-vendor-bill",name:"Create NetSuite vendor bill",shortName:"Create vendor bill",instruction:`Creates a vendor bill in NetSuite with expense lines. Approval routing of the account applies. ${vc}`,stepId:"createVendorBill",recordType:"vendorbill",mode:"create",properties:{vendorId:{type:"string",description:"Vendor internal ID."},referenceNo:{type:"string",description:"Optional vendor invoice reference number."},...Dm("create"),lines:{type:"array",description:"Expense lines.",items:DL}},required:["vendorId","lines"],body:`if (!Array.isArray(p.lines) || p.lines.length === 0) throw new Error('lines must contain at least one expense line.'); ${Tm("vendorId")} if (has(p.referenceNo)) record.tranId = String(p.referenceNo); ${TL}`}),Kr({id:"netsuite-update-vendor-bill",name:"Update NetSuite vendor bill",shortName:"Update vendor bill",instruction:"Updates an existing NetSuite vendor bill by internal ID. Only the provided fields change. When lines are provided they replace all existing expense lines. Paid bills and closed periods may refuse updates.",stepId:"updateVendorBill",recordType:"vendorbill",mode:"update",properties:{vendorId:{type:"string",description:"Optional new vendor internal ID."},referenceNo:{type:"string",description:"Optional vendor invoice reference number."},...Dm("update"),lines:{type:"array",description:"Optional replacement expense lines; they replace every existing expense line.",items:DL}},required:[],body:`if (Array.isArray(p.lines) && p.lines.length === 0) throw new Error('lines must contain at least one expense line; omit lines to keep the current ones.'); ${Tm("vendorId")} if (has(p.referenceNo)) record.tranId = String(p.referenceNo); ${TL}`,replaceSublist:{input:"lines",sublist:"expense"}}),Kr({id:"netsuite-create-department",name:"Create NetSuite department",shortName:"Create department",instruction:`Creates a department in NetSuite. Without subsidiaryIds NetSuite assigns the parent subsidiary. ${vc}`,stepId:"createDepartment",recordType:"department",mode:"create",properties:BL,required:["name"],body:`if (!has(p.name)) throw new Error('name is required.'); ${_L} ${Qm}`}),Kr({id:"netsuite-update-department",name:"Update NetSuite department",shortName:"Update department",instruction:"Updates an existing NetSuite department by internal ID. Only the provided fields change; set isInactive to inactivate or reactivate it.",stepId:"updateDepartment",recordType:"department",mode:"update",properties:{...BL,...vm},required:[],body:`${_L} ${Qm}`})],cw={sap_s4hana:{bundleId:"sap_s4hana",templateId:"sap_s4hana",systemId:"sap_s4hana",displayName:"SAP S/4HANA",description:"Read business partners, sales orders, products and purchase orders from SAP.",systemUrl:She,credentialHint:"Works instantly with SAP's demo data. Add your own key later for your live system.",requiredCredentialKeys:["api_key"],demoCredentials:{api_key:"K8reTgiKCCaqvAPWC4cOjqqiLdLE8dqz"},mcpServer:{name:"sap",displayName:"SAP S/4HANA",description:"Business partners, sales orders, products and purchase orders from SAP."},installMcpServer:!0,agentLaunch:{userPrompt:"I just installed the SAP S/4HANA bundle. What can I do with it?",nextSteps:"Your first reply must be short: SAP is connected to free demo data and works right now, so offer to run one tool immediately as proof. No credential collection is needed to start. If they want their own data: their own free key comes from https://api.sap.com (SAP Business Accelerator Hub), collected and saved directly with a connect field, never via the Connections page; the system URL can then be switched to their own SAP host. Do not list the installed tools, do not add tips or explain SAP concepts unless asked."},tools:[{id:"sap-list-business-partners",name:"List SAP business partners",shortName:"Business partners",instruction:"Lists business partners (customers, suppliers, contacts) from SAP S/4HANA. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{filter:{type:"string",description:`Optional OData $filter expression, e.g. "BusinessPartnerCategory eq '2'" for organizations.`},maxResults:{type:"integer",description:"Maximum number of business partners to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"fetchBusinessPartners",instruction:"Fetch business partners, paging through results with $skip.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/API_BUSINESS_PARTNER/A_BusinessPartner",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$top:"<<pageSize>>",$skip:"<<offset>>",$filter:"<<filter>>",$select:"BusinessPartner,BusinessPartnerFullName,BusinessPartnerCategory,BusinessPartnerGrouping,CreationDate"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const d = (v) => { if (typeof v !== 'string' || !v.startsWith('/Date(')) return v; const n = parseInt(v.slice(6), 10); return Number.isFinite(n) ? new Date(n).toISOString().slice(0, 10) : v; }; const rows = (sourceData.fetchBusinessPartners?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 200); return { total: rows.length, businessPartners: rows.map((r) => ({ id: r.BusinessPartner, name: r.BusinessPartnerFullName, category: r.BusinessPartnerCategory, grouping: r.BusinessPartnerGrouping, createdOn: d(r.CreationDate) })) }; }"},{id:"sap-list-sales-orders",name:"List SAP sales orders",shortName:"Sales orders",instruction:"Lists sales orders from SAP S/4HANA with their net amount, currency and sold-to party. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{filter:{type:"string",description:`Optional OData $filter expression, e.g. "SalesOrderType eq 'OR'" or "TotalNetAmount gt 1000".`},maxResults:{type:"integer",description:"Maximum number of sales orders to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"fetchSalesOrders",instruction:"Fetch sales orders, paging through results with $skip.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/API_SALES_ORDER_SRV/A_SalesOrder",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$top:"<<pageSize>>",$skip:"<<offset>>",$filter:"<<filter>>",$select:"SalesOrder,SalesOrderType,SoldToParty,TotalNetAmount,TransactionCurrency,SalesOrderDate,OverallSDProcessStatus"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const d = (v) => { if (typeof v !== 'string' || !v.startsWith('/Date(')) return v; const n = parseInt(v.slice(6), 10); return Number.isFinite(n) ? new Date(n).toISOString().slice(0, 10) : v; }; const rows = (sourceData.fetchSalesOrders?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 200); return { total: rows.length, salesOrders: rows.map((r) => ({ id: r.SalesOrder, type: r.SalesOrderType, soldToParty: r.SoldToParty, netAmount: Number(r.TotalNetAmount), currency: r.TransactionCurrency, orderDate: d(r.SalesOrderDate), status: r.OverallSDProcessStatus })) }; }"},{id:"sap-list-products",name:"List SAP products",shortName:"Products",instruction:"Lists products (materials) from SAP S/4HANA with their type, group and base unit. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{filter:{type:"string",description:`Optional OData $filter expression, e.g. "ProductType eq 'FERT'" for finished goods.`},maxResults:{type:"integer",description:"Maximum number of products to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"fetchProducts",instruction:"Fetch products, paging through results with $skip.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/API_PRODUCT_SRV/A_Product",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$top:"<<pageSize>>",$skip:"<<offset>>",$filter:"<<filter>>",$expand:"to_Description",$select:"Product,ProductType,ProductGroup,BaseUnit,GrossWeight,WeightUnit,CreationDate,to_Description/Language,to_Description/ProductDescription"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const d = (v) => { if (typeof v !== 'string' || !v.startsWith('/Date(')) return v; const n = parseInt(v.slice(6), 10); return Number.isFinite(n) ? new Date(n).toISOString().slice(0, 10) : v; }; const nameOf = (r) => { const list = r.to_Description?.results ?? []; const hit = list.find((x) => x.Language === 'EN') ?? list[0]; return hit?.ProductDescription; }; const rows = (sourceData.fetchProducts?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 200); return { total: rows.length, products: rows.map((r) => ({ id: r.Product, name: nameOf(r), type: r.ProductType, group: r.ProductGroup, baseUnit: r.BaseUnit, grossWeight: Number(r.GrossWeight), weightUnit: r.WeightUnit, createdOn: d(r.CreationDate) })) }; }"},{id:"sap-list-purchase-orders",name:"List SAP purchase orders",shortName:"Purchase orders",instruction:"Lists purchase orders from SAP S/4HANA with their supplier, currency and creation date. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{filter:{type:"string",description:`Optional OData $filter expression, e.g. "PurchaseOrderType eq 'NB'" for standard orders.`},maxResults:{type:"integer",description:"Maximum number of purchase orders to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"fetchPurchaseOrders",instruction:"Fetch purchase orders, paging through results with $skip.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/API_PURCHASEORDER_PROCESS_SRV/A_PurchaseOrder",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$top:"<<pageSize>>",$skip:"<<offset>>",$filter:"<<filter>>",$select:"PurchaseOrder,PurchaseOrderType,Supplier,PurchaseOrderDate,DocumentCurrency,CreatedByUser"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const d = (v) => { if (typeof v !== 'string' || !v.startsWith('/Date(')) return v; const n = parseInt(v.slice(6), 10); return Number.isFinite(n) ? new Date(n).toISOString().slice(0, 10) : v; }; const rows = (sourceData.fetchPurchaseOrders?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 200); return { total: rows.length, purchaseOrders: rows.map((r) => ({ id: r.PurchaseOrder, type: r.PurchaseOrderType, supplier: r.Supplier, orderDate: d(r.PurchaseOrderDate), currency: r.DocumentCurrency, createdBy: r.CreatedByUser })) }; }"},{id:"sap-list-gl-accounts",name:"List SAP chart of accounts",shortName:"Chart of accounts",instruction:"Lists general ledger accounts (the chart of accounts) from SAP S/4HANA. Supports an optional OData $filter, e.g. by ChartOfAccounts.",inputSchema:{type:"object",properties:{filter:{type:"string",description:`Optional OData $filter expression, e.g. "ChartOfAccounts eq 'YCOA'" or "GLAccountType eq 'X'".`},maxResults:{type:"integer",description:"Maximum number of accounts to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"fetchGLAccounts",instruction:"Fetch GL accounts, paging through results with $skip.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/API_GLACCOUNTINCHARTOFACCOUNTS_SRV/A_GLAccountInChartOfAccounts",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$top:"<<pageSize>>",$skip:"<<offset>>",$filter:`<<(p) => p.filter ? "ChartOfAccounts ne '' and (" + p.filter + ")" : "ChartOfAccounts ne ''">>`,$expand:"to_Text",$select:"GLAccount,ChartOfAccounts,GLAccountType,GLAccountGroup,IsBalanceSheetAccount,AccountIsBlockedForPosting,to_Text/Language,to_Text/GLAccountName"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const nameOf = (r) => { const list = r.to_Text?.results ?? []; const hit = list.find((x) => x.Language === 'EN') ?? list[0]; return hit?.GLAccountName; }; const rows = (sourceData.fetchGLAccounts?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 200); return { total: rows.length, accounts: rows.map((r) => ({ account: r.GLAccount, name: nameOf(r), chartOfAccounts: r.ChartOfAccounts, type: r.GLAccountType, group: r.GLAccountGroup, isBalanceSheet: r.IsBalanceSheetAccount, blockedForPosting: r.AccountIsBlockedForPosting })) }; }"},{id:"sap-list-billing-documents",name:"List SAP billing documents",shortName:"Billing documents",instruction:"Lists billing documents (invoices, credit memos) from SAP S/4HANA with amount, currency and sold-to party. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{filter:{type:"string",description:`Optional OData $filter expression, e.g. "BillingDocumentType eq 'F2'" or "TotalNetAmount gt 1000".`},maxResults:{type:"integer",description:"Maximum number of billing documents to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"fetchBillingDocuments",instruction:"Fetch billing documents, paging through results with $skip.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/API_BILLING_DOCUMENT_SRV/A_BillingDocument",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$top:"<<pageSize>>",$skip:"<<offset>>",$filter:"<<filter>>",$select:"BillingDocument,BillingDocumentType,SoldToParty,TotalNetAmount,TransactionCurrency,BillingDocumentDate"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const d = (v) => { if (typeof v !== 'string' || !v.startsWith('/Date(')) return v; const n = parseInt(v.slice(6), 10); return Number.isFinite(n) ? new Date(n).toISOString().slice(0, 10) : v; }; const rows = (sourceData.fetchBillingDocuments?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 200); return { total: rows.length, billingDocuments: rows.map((r) => ({ id: r.BillingDocument, type: r.BillingDocumentType, soldToParty: r.SoldToParty, netAmount: Number(r.TotalNetAmount), currency: r.TransactionCurrency, date: d(r.BillingDocumentDate) })) }; }"},{id:"sap-list-journal-entry-items",name:"List SAP journal entry line items",shortName:"Journal entries",instruction:"Lists journal entry line items (accounting document items) from SAP S/4HANA with company code, GL account, amount and posting date. Filter by CompanyCode, FiscalYear or PostingDate to keep results focused. Useful for verifying opening balances at cutover.",inputSchema:{type:"object",properties:{filter:{type:"string",description:`Optional OData $filter expression, e.g. "CompanyCode eq '1010' and FiscalYear eq '2026'".`},maxResults:{type:"integer",description:"Maximum number of line items to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"fetchJournalItems",instruction:"Fetch accounting document line items, paging through results with $skip.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/API_OPLACCTGDOCITEMCUBE_SRV/A_OperationalAcctgDocItemCube",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$top:"<<pageSize>>",$skip:"<<offset>>",$filter:"<<filter>>",$select:"AccountingDocument,CompanyCode,FiscalYear,GLAccount,AmountInCompanyCodeCurrency,PostingDate"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const d = (v) => { if (typeof v !== 'string' || !v.startsWith('/Date(')) return v; const n = parseInt(v.slice(6), 10); return Number.isFinite(n) ? new Date(n).toISOString().slice(0, 10) : v; }; const rows = (sourceData.fetchJournalItems?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 200); return { total: rows.length, journalItems: rows.map((r) => ({ document: r.AccountingDocument, companyCode: r.CompanyCode, fiscalYear: r.FiscalYear, account: r.GLAccount, amount: Number(r.AmountInCompanyCodeCurrency), postingDate: d(r.PostingDate) })) }; }"},{id:"sap-query-odata",name:"Query any SAP OData service",shortName:"Query any service",instruction:"Queries any SAP S/4HANA OData service and entity set (for example API_PRODUCT_SRV/A_ProductDescription or API_SALES_ORDER_SRV/A_SalesOrderItem) with optional $select and $filter. The workhorse tool for data checks beyond the prebuilt lists.",inputSchema:{type:"object",properties:{servicePath:{type:"string",description:'Service and entity set in SERVICE/EntitySet form, e.g. "API_SALES_ORDER_SRV/A_SalesOrderItem".'},select:{type:"string",description:"Comma-separated OData $select field list. Omit for all fields."},filter:{type:"string",description:"Optional OData $filter expression."},maxResults:{type:"integer",description:"Maximum number of records to return. Defaults to 100."}},required:["servicePath"],additionalProperties:!0},steps:[{id:"queryService",instruction:"Query the requested OData service and entity set.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/<<servicePath>>",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$select:"<<select>>",$filter:"<<filter>>",$top:"<<pageSize>>",$skip:"<<offset>>"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 100; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const rows = (sourceData.queryService?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 100); return { total: rows.length, records: rows.map((r) => { const { __metadata, ...rest } = r; return rest; }) }; }"}]},sage100:{bundleId:"sage100",templateId:"sage100",systemId:"sage100",displayName:"Sage 100",description:"Connect on-premises Sage 100 through the superglue Secure Gateway, with a guided setup playbook and a connection test against the Business Object Interface.",systemUrl:"script://runner/vbs32",credentialHint:"Your assistant first helps you connect a Secure Gateway on your Sage 100 server, then collects your Sage company and user details.",requiredCredentialKeys:["sage_home","sage_company","sage_user","sage_password"],mcpServer:{name:"sage-100",displayName:"Sage 100",description:"Sage 100 Business Object Interface access through the Secure Gateway."},installMcpServer:!1,playbook:{id:"sage100-native-integration",name:"Sage 100 Native Integration (BOI)",whenToRun:"Use when connecting a Sage 100 installation to superglue, testing that connection, or building tools that read or write Sage 100 data through the Business Object Interface.",inputs:"A Sage 100 installation on a Windows machine the user can access; a superglue API key for the gateway; the Sage company code, a Sage user with module access, and the path to the MAS90\\Home directory; the business outcome once connected.",instructions:"First check /org/tunnels for a connected gateway with a runner target. If none is connected, guide the user step by step: download the Windows gateway from https://downloads.superglue.cloud/superglue-gateway-windows.exe onto the machine where Sage 100 and Workstation Setup are installed (the gateway must run there, ProvideX.Script is a local 32-bit COM class), create a config.yaml next to it with a tunnel_id, the server_url ending in /ws/tunnels (wss://api.superglue.cloud/ws/tunnels for hosted superglue), an API key from the API Keys page, and the line enable_script_runner: true, then run the executable. That flag is required: it opts the gateway into running Sage scripts (it is code execution on their machine, so it is off by default), and it is what registers the built-in runner target. No targets section is needed. If a tunnel is connected but has no runner target, the gateway is either missing enable_script_runner: true or is an outdated build; have the user add the flag and restart, or download the current gateway from the same URL. When the tunnel with the runner target appears, attach it to the Sage 100 connection with tools.writeConnection (tunnel with that tunnelId) and keep the URL script://runner/vbs32. Collect sage_home (full path to the MAS90\\Home directory, for example C:\\Sage\\Sage100\\MAS90\\Home, not the MAS90 directory itself), sage_company, sage_user and sage_password through the secure credential form. Then run the Test Sage 100 connection tool once and interpret the result: retVal 0 failures carry the Sage reason in sLastErrorMsg (wrong credentials, missing role access, wrong company code); COM error 0x80040154 means the gateway is not running on a machine with Sage 100 Workstation Setup; a no-license message means all Sage user seats are in use. For new capabilities, build tools whose steps use the script protocol with VBScript in the body: log on with SY_Session, set module context before touching data (nSetDate with YYYYMMDD dates, nSetModule, nLookupTask, nSetProgram), use _svc service objects for reads and _bus business objects for writes, and always release the session with nCleanup and DropObject so the license seat frees up. For reads, set each key segment with nSetKeyValue then nFind for a single record, or browse with nMoveFirst and nMoveNext, and read each field with nGetValue passing a variable that receives the value. To write a document that has lines, such as a sales order, get the header _bus object, set the header fields, get its oLines object, call nAddLine, set the line fields, then call nWrite on the header to commit the header and its lines together. A write fails with a lock error if the record is open in the Sage desktop or held by another session, so report the lock message instead of retrying. Each running script briefly consumes a Sage user seat. Ask for explicit approval before any script that writes to Sage, and warn that records open in the Sage desktop UI cause lock errors.",completionCriteria:"The gateway is connected, the installed Sage 100 system has the tunnel attached and credentials saved, and the connection test returned company data from Sage 100. Any additional requested capability works end to end, with writes explicitly approved before they ran."},agentLaunch:{userPrompt:"I just installed the Sage 100 integration. Help me connect my Sage 100 server.",nextSteps:"Your first reply must be short: one line confirming the Sage 100 integration and setup playbook are installed, then start the connection flow. Check /org/tunnels for a connected gateway with a runner target first. If none exists, walk the user through it one step at a time: download https://downloads.superglue.cloud/superglue-gateway-windows.exe onto the Windows machine where Sage 100 is installed and Workstation Setup has run, create a config.yaml next to it with tunnel_id, server_url (wss://api.superglue.cloud/ws/tunnels for hosted superglue), an API key from the API Keys page, and the line enable_script_runner: true, then run it. That flag is required: it opts the gateway into running scripts on their machine (off by default because it is code execution) and is what registers the runner target. No targets are needed in the config. If a tunnel is connected but has no runner target, the gateway is missing enable_script_runner: true or is an outdated build: have the user add the flag and restart, or download the current one from the same URL. Wait for the user to confirm, then verify the tunnel appears and attach it to the Sage 100 connection with tools.writeConnection tunnel, keeping the URL script://runner/vbs32. Use connect with the connection id and fields to save sage_home (full path to the MAS90\\Home directory, for example C:\\Sage\\Sage100\\MAS90\\Home, not MAS90 itself), sage_company (for example ABC for the demo company), sage_user and sage_password. Never send the user to the Connections page. Then run the Test Sage 100 connection tool once. If it fails, explain the specific cause in plain language before retrying. Mention that each test briefly uses one Sage user license seat. Do not list tools or add tips unless asked."},tools:[{id:"sage100-test-connection",name:"Test Sage 100 connection",shortName:"Connection test",instruction:"Logs on to Sage 100 through the Secure Gateway, opens the configured company, and reads the first customer record to verify the Business Object Interface end to end. Briefly consumes one Sage user license seat.",steps:[{id:"testConnection",instruction:"Run a VBScript through the gateway script runner that logs on via SY_Session, sets A/R module context, and reads the first customer.",config:{type:"request",systemId:"sage100",url:"<<sage100_url>>",method:"POST",body:["Option Explicit","On Error Resume Next","Dim oScript, oSS, oCust, retVal, custNo, custName, today",'Set oScript = CreateObject("ProvideX.Script")','FailOnErr "CREATE", " (Sage 100 Workstation Setup has not registered ProvideX.Script on this machine; the gateway must run on a prepared Sage 100 machine)"','oScript.Init "<<sage100_sage_home>>"','FailOnErr "INIT", " (sage_home must be the full path to the MAS90\\Home directory, not MAS90 itself)"','Set oSS = oScript.NewObject("SY_Session")','FailOnErr "SESSION", ""','retVal = oSS.nSetUser("<<sage100_sage_user>>", "<<sage100_sage_password>>")','FailOnErr "LOGON", ""',"If retVal = 0 Then",' WScript.Echo "LOGON FAILED: " & oSS.sLastErrorMsg'," WScript.Quit 1","End If",'retVal = oSS.nSetCompany("<<sage100_sage_company>>")','FailOnErr "COMPANY", ""',"If retVal = 0 Then",' WScript.Echo "COMPANY FAILED: " & oSS.sLastErrorMsg'," oSS.nCleanup"," oSS.DropObject"," WScript.Quit 1","End If",'today = Year(Date) & Right("0" & Month(Date), 2) & Right("0" & Day(Date), 2)','retVal = oSS.nSetDate("A/R", today)','FailOnErr "DATE", ""','retVal = oSS.nSetModule("A/R")','FailOnErr "MODULE", ""','retVal = oSS.nSetProgram(oSS.nLookupTask("AR_Customer_ui"))','FailOnErr "TASK", ""',"If retVal = 0 Then",' WScript.Echo "TASK FAILED: " & oSS.sLastErrorMsg'," oSS.nCleanup"," oSS.DropObject"," WScript.Quit 1","End If",'Set oCust = oScript.NewObject("AR_Customer_svc", oSS)','FailOnErr "CUSTOMER OBJECT", ""',"retVal = oCust.nMoveFirst()",'FailOnErr "READ", ""',"If retVal = 0 Then",' WScript.Echo "READ FAILED: " & oCust.sLastErrorMsg',"Else",' custNo = "" : custName = ""',' retVal = oCust.nGetValue("CustomerNo$", custNo)',' retVal = oCust.nGetValue("CustomerName$", custName)',' FailOnErr "READ VALUE", " (ByRef value marshalling failed)"',' WScript.Echo "CONNECTED - company <<sage100_sage_company>>, first customer: " & custNo & " / " & custName',"End If","oCust.DropObject","oSS.nCleanup","oSS.DropObject","If retVal = 0 Then WScript.Quit 1","","Sub FailOnErr(stage, hint)"," If Err.Number <> 0 Then",' WScript.Echo stage & " FAILED: [0x" & Hex(Err.Number) & "] " & Err.Description & hint'," WScript.Quit 1"," End If","End Sub"].join(`
|
|
114
114
|
`)}}]}]},sage_intacct:{bundleId:"sage_intacct",templateId:"sage_intacct",systemId:"sage_intacct",displayName:"Sage Intacct",description:"Install a Sage Intacct system, eight read/query tools, fourteen write tools and a native integration playbook.",systemUrl:"https://api.intacct.com/ia/xml/xmlgw.phtml",credentialHint:"Works instantly with a Sage Intacct demo company. Enter your company ID and API user credentials to use your own company. Web Services sender credentials are preconfigured.",requiredCredentialKeys:["sender_id","sender_password","user_id","user_password","company_id"],demoCredentials:{company_id:"IndexCommerceMPP-DEV",user_id:"superglue",user_password:"Linux123___"},mcpServer:{name:"sage-intacct",displayName:"Sage Intacct",description:"Chart of accounts, customers, vendors, journal entries and ad-hoc object queries from Sage Intacct, plus create and update tools for GL accounts, journal entries, invoices, bills, departments, vendors and customers."},installMcpServer:!1,playbook:{id:"sage-intacct-native-integration",name:"Sage Intacct Native Integration",whenToRun:"Use when connecting, validating, querying or extending a Sage Intacct integration through XML Web Services.",inputs:"A configured Sage Intacct system; the object or business process to work with; optional Location/Entity ID for multi-entity companies; validation criteria and desired output.",instructions:"Use the installed read-only tools for chart of accounts, customers, vendors, journal entries, invoices, bills and departments. Use Query any Sage Intacct object for supported objects outside the named library. Use the installed create and update tools for GL accounts, journal entries, invoices, bills, departments, vendors and customers only after the user explicitly confirms the exact records to write; the create tools are not idempotent and re-running them duplicates records. Apply the configured Location/Entity ID when present. Verify every XML Web Services response at control, authentication and function-result level, and preserve Sage support IDs in failures. For other objects or operations, inspect Sage object documentation, create separate least-privilege tools, validate them in a development company and require explicit user confirmation before modifying Sage data.",completionCriteria:"The requested Sage data, write result or validation result is returned; entity scope is correct; Sage XML failures are surfaced as failures with support IDs; no Sage data is modified unless the user explicitly requested and confirmed the write."},agentLaunch:{userPrompt:"I just installed the Sage Intacct integration. What can I do with it?",nextSteps:"Your first reply must be short: one line confirming the Sage Intacct integration and native integration playbook are installed, then collect credentials. The Web Services sender credentials are already configured. Use connect with this system's connection id and fields to save user_id, user_password and company_id, plus optional entity_id when the user wants to target one entity in a multi-entity company. Never send the user to the Connections page. The user id and password are an API user login in the company; company id is the Intacct company id. Once saved, offer one read-only test run. Do not list the installed tools or add tips unless asked. The query tool accepts other supported Intacct object names, and additional read or write tools can be built beyond the default library. The installed create and update tools modify Sage data; run them only after the user confirms the exact records to write."},tools:[{id:"sage-intacct-list-accounts",name:"List Sage Intacct chart of accounts",shortName:"Chart of accounts",instruction:"Lists general ledger accounts (the chart of accounts) from Sage Intacct via the XML Web Services API. Useful for validating an imported chart of accounts after a migration.",inputSchema:{type:"object",properties:{maxResults:{type:"integer",description:"Maximum number of records to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"queryAccounts",instruction:"Query GLACCOUNT records via readByQuery-style paging.",config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:Lt("<query><object>GLACCOUNT</object><select><field>RECORDNO</field><field>ACCOUNTNO</field><field>TITLE</field><field>ACCOUNTTYPE</field><field>NORMALBALANCE</field><field>STATUS</field></select><pagesize><<pageSize>></pagesize><offset><<offset>></offset></query>"),pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const dig = (o) => o && o.RESPONSE && o.RESPONSE.OPERATION && o.RESPONSE.OPERATION.RESULT ? o.RESPONSE.OPERATION.RESULT.DATA : undefined; const cur = dig(response && response.data); const cr = cur ? cur.GLACCOUNT : undefined; const rows = Array.isArray(cr) ? cr : (cr ? [cr] : []); const mr = dig(pageInfo && pageInfo.mergedResult); const mraw = mr ? mr.GLACCOUNT : undefined; const fetched = Array.isArray(mraw) ? mraw.length : (mraw ? 1 : 0); const max = (sourceData && sourceData.maxResults) ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:ga({stepId:"queryAccounts",objectNameExpression:"'GLACCOUNT'",collectionName:"accounts",mapExpression:"(record) => ({ recordNo: record.RECORDNO, account: record.ACCOUNTNO, name: record.TITLE, type: record.ACCOUNTTYPE, normalBalance: record.NORMALBALANCE, status: record.STATUS })"})},{id:"sage-intacct-list-customers",name:"List Sage Intacct customers",shortName:"Customers",instruction:"Lists customer master records from Sage Intacct accounts receivable. Useful for verifying migrated AR master data.",inputSchema:{type:"object",properties:{maxResults:{type:"integer",description:"Maximum number of records to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"queryCustomers",instruction:"Query CUSTOMER records.",config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:Lt("<query><object>CUSTOMER</object><select><field>RECORDNO</field><field>CUSTOMERID</field><field>NAME</field><field>STATUS</field><field>WHENCREATED</field></select><pagesize><<pageSize>></pagesize><offset><<offset>></offset></query>"),pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const dig = (o) => o && o.RESPONSE && o.RESPONSE.OPERATION && o.RESPONSE.OPERATION.RESULT ? o.RESPONSE.OPERATION.RESULT.DATA : undefined; const cur = dig(response && response.data); const cr = cur ? cur.CUSTOMER : undefined; const rows = Array.isArray(cr) ? cr : (cr ? [cr] : []); const mr = dig(pageInfo && pageInfo.mergedResult); const mraw = mr ? mr.CUSTOMER : undefined; const fetched = Array.isArray(mraw) ? mraw.length : (mraw ? 1 : 0); const max = (sourceData && sourceData.maxResults) ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:ga({stepId:"queryCustomers",objectNameExpression:"'CUSTOMER'",collectionName:"customers",mapExpression:"(record) => ({ recordNo: record.RECORDNO, customerId: record.CUSTOMERID, name: record.NAME, status: record.STATUS, createdOn: record.WHENCREATED })"})},{id:"sage-intacct-list-vendors",name:"List Sage Intacct vendors",shortName:"Vendors",instruction:"Lists vendor master records from Sage Intacct accounts payable. Useful for verifying migrated AP master data.",inputSchema:{type:"object",properties:{maxResults:{type:"integer",description:"Maximum number of records to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"queryVendors",instruction:"Query VENDOR records.",config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:Lt("<query><object>VENDOR</object><select><field>RECORDNO</field><field>VENDORID</field><field>NAME</field><field>STATUS</field><field>WHENCREATED</field></select><pagesize><<pageSize>></pagesize><offset><<offset>></offset></query>"),pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const dig = (o) => o && o.RESPONSE && o.RESPONSE.OPERATION && o.RESPONSE.OPERATION.RESULT ? o.RESPONSE.OPERATION.RESULT.DATA : undefined; const cur = dig(response && response.data); const cr = cur ? cur.VENDOR : undefined; const rows = Array.isArray(cr) ? cr : (cr ? [cr] : []); const mr = dig(pageInfo && pageInfo.mergedResult); const mraw = mr ? mr.VENDOR : undefined; const fetched = Array.isArray(mraw) ? mraw.length : (mraw ? 1 : 0); const max = (sourceData && sourceData.maxResults) ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:ga({stepId:"queryVendors",objectNameExpression:"'VENDOR'",collectionName:"vendors",mapExpression:"(record) => ({ recordNo: record.RECORDNO, vendorId: record.VENDORID, name: record.NAME, status: record.STATUS, createdOn: record.WHENCREATED })"})},{id:"sage-intacct-list-journal-entries",name:"List Sage Intacct journal entries",shortName:"Journal entries",instruction:"Lists general ledger entries from Sage Intacct with account, type and amount. Useful for verifying opening balances and postings at cutover.",inputSchema:{type:"object",properties:{maxResults:{type:"integer",description:"Maximum number of records to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"queryJournalEntries",instruction:"Query GLENTRY records.",config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:Lt("<query><object>GLENTRY</object><select><field>RECORDNO</field><field>BATCHNO</field><field>ACCOUNTNO</field><field>TR_TYPE</field><field>AMOUNT</field><field>ENTRY_DATE</field></select><pagesize><<pageSize>></pagesize><offset><<offset>></offset></query>"),pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const dig = (o) => o && o.RESPONSE && o.RESPONSE.OPERATION && o.RESPONSE.OPERATION.RESULT ? o.RESPONSE.OPERATION.RESULT.DATA : undefined; const cur = dig(response && response.data); const cr = cur ? cur.GLENTRY : undefined; const rows = Array.isArray(cr) ? cr : (cr ? [cr] : []); const mr = dig(pageInfo && pageInfo.mergedResult); const mraw = mr ? mr.GLENTRY : undefined; const fetched = Array.isArray(mraw) ? mraw.length : (mraw ? 1 : 0); const max = (sourceData && sourceData.maxResults) ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:ga({stepId:"queryJournalEntries",objectNameExpression:"'GLENTRY'",collectionName:"journalEntries",mapExpression:"(record) => ({ recordNo: record.RECORDNO, batch: record.BATCHNO, account: record.ACCOUNTNO, type: record.TR_TYPE, amount: Number(record.AMOUNT), date: record.ENTRY_DATE })"})},{id:"sage-intacct-list-invoices",name:"List Sage Intacct invoices",shortName:"Invoices",instruction:"Lists accounts receivable invoices from Sage Intacct. Useful for verifying migrated open AR at go-live.",inputSchema:{type:"object",properties:{maxResults:{type:"integer",description:"Maximum number of records to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"queryInvoices",instruction:"Query ARINVOICE records.",config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:Lt("<query><object>ARINVOICE</object><select><field>RECORDNO</field><field>RECORDID</field><field>CUSTOMERID</field><field>TOTALDUE</field><field>WHENCREATED</field><field>STATE</field></select><pagesize><<pageSize>></pagesize><offset><<offset>></offset></query>"),pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const dig = (o) => o && o.RESPONSE && o.RESPONSE.OPERATION && o.RESPONSE.OPERATION.RESULT ? o.RESPONSE.OPERATION.RESULT.DATA : undefined; const cur = dig(response && response.data); const cr = cur ? cur.ARINVOICE : undefined; const rows = Array.isArray(cr) ? cr : (cr ? [cr] : []); const mr = dig(pageInfo && pageInfo.mergedResult); const mraw = mr ? mr.ARINVOICE : undefined; const fetched = Array.isArray(mraw) ? mraw.length : (mraw ? 1 : 0); const max = (sourceData && sourceData.maxResults) ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:ga({stepId:"queryInvoices",objectNameExpression:"'ARINVOICE'",collectionName:"invoices",mapExpression:"(record) => ({ recordNo: record.RECORDNO, invoiceId: record.RECORDID, customerId: record.CUSTOMERID, totalDue: Number(record.TOTALDUE), createdOn: record.WHENCREATED, state: record.STATE })"})},{id:"sage-intacct-list-bills",name:"List Sage Intacct bills",shortName:"Bills",instruction:"Lists accounts payable bills from Sage Intacct. Useful for verifying migrated open AP at go-live.",inputSchema:{type:"object",properties:{maxResults:{type:"integer",description:"Maximum number of records to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"queryBills",instruction:"Query APBILL records.",config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:Lt("<query><object>APBILL</object><select><field>RECORDNO</field><field>RECORDID</field><field>VENDORID</field><field>TOTALDUE</field><field>WHENCREATED</field><field>STATE</field></select><pagesize><<pageSize>></pagesize><offset><<offset>></offset></query>"),pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const dig = (o) => o && o.RESPONSE && o.RESPONSE.OPERATION && o.RESPONSE.OPERATION.RESULT ? o.RESPONSE.OPERATION.RESULT.DATA : undefined; const cur = dig(response && response.data); const cr = cur ? cur.APBILL : undefined; const rows = Array.isArray(cr) ? cr : (cr ? [cr] : []); const mr = dig(pageInfo && pageInfo.mergedResult); const mraw = mr ? mr.APBILL : undefined; const fetched = Array.isArray(mraw) ? mraw.length : (mraw ? 1 : 0); const max = (sourceData && sourceData.maxResults) ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:ga({stepId:"queryBills",objectNameExpression:"'APBILL'",collectionName:"bills",mapExpression:"(record) => ({ recordNo: record.RECORDNO, billId: record.RECORDID, vendorId: record.VENDORID, totalDue: Number(record.TOTALDUE), createdOn: record.WHENCREATED, state: record.STATE })"})},{id:"sage-intacct-list-departments",name:"List Sage Intacct departments",shortName:"Departments",instruction:"Lists department dimensions from Sage Intacct. Useful for validating the dimension setup after an implementation.",inputSchema:{type:"object",properties:{maxResults:{type:"integer",description:"Maximum number of records to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"queryDepartments",instruction:"Query DEPARTMENT records.",config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:Lt("<query><object>DEPARTMENT</object><select><field>RECORDNO</field><field>DEPARTMENTID</field><field>TITLE</field><field>STATUS</field></select><pagesize><<pageSize>></pagesize><offset><<offset>></offset></query>"),pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const dig = (o) => o && o.RESPONSE && o.RESPONSE.OPERATION && o.RESPONSE.OPERATION.RESULT ? o.RESPONSE.OPERATION.RESULT.DATA : undefined; const cur = dig(response && response.data); const cr = cur ? cur.DEPARTMENT : undefined; const rows = Array.isArray(cr) ? cr : (cr ? [cr] : []); const mr = dig(pageInfo && pageInfo.mergedResult); const mraw = mr ? mr.DEPARTMENT : undefined; const fetched = Array.isArray(mraw) ? mraw.length : (mraw ? 1 : 0); const max = (sourceData && sourceData.maxResults) ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:ga({stepId:"queryDepartments",objectNameExpression:"'DEPARTMENT'",collectionName:"departments",mapExpression:"(record) => ({ recordNo: record.RECORDNO, departmentId: record.DEPARTMENTID, name: record.TITLE, status: record.STATUS })"})},{id:"sage-intacct-query-object",name:"Query any Sage Intacct object",shortName:"Query any object",instruction:"Queries any Sage Intacct object by name (for example GLACCOUNT, PROJECT, GLENTRY, ARINVOICE) using the XML Web Services readByQuery, with an optional Intacct query filter. The workhorse tool for migration validation beyond the prebuilt lists. Returns up to 1000 records in one call.",inputSchema:{type:"object",properties:{object:{type:"string",description:'Intacct object name, e.g. "GLACCOUNT", "PROJECT", "GLENTRY", "ARINVOICE".'},query:{type:"string",description:`Optional Intacct query filter, e.g. "STATUS = 'active'". Leave empty to return all records.`},maxResults:{type:"integer",description:"Maximum number of records to return (max 1000). Defaults to 100."}},required:["object"],additionalProperties:!0},steps:[{id:"queryObject",instruction:"Run readByQuery for the requested object.",config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:Lt("<readByQuery><object><<(p) => { const value = String(p.object || '').toUpperCase(); if (!/^[A-Z][A-Z0-9_]*$/.test(value)) throw new Error('Sage Intacct object must contain only letters, numbers, and underscores.'); return value; }>></object><fields>*</fields><query><<(p) => String(p.query || '').replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')>></query><pagesize><<(p) => Math.min(Math.max(Number(p.maxResults) || 100, 1), 1000)>></pagesize></readByQuery>")}}],outputTransform:ga({stepId:"queryObject",objectNameExpression:"(sourceData && sourceData.object ? String(sourceData.object) : '').toUpperCase()",collectionName:"records",includeTotalCount:!0})},{id:"sage-intacct-create-journal-entry",name:"Create Sage Intacct journal entry",shortName:"Create journal entry",instruction:"Creates a journal entry (GLBATCH with GLENTRY lines) in Sage Intacct via the XML Web Services API. Debits and credits must balance. Re-running this tool creates another journal entry; it is not idempotent.",inputSchema:{type:"object",properties:{journal:{type:"string",description:'Journal symbol, e.g. "GJ". Defaults to GJ.'},date:{type:"string",description:"Posting date as YYYY-MM-DD."},title:{type:"string",description:"Journal entry description."},lines:{type:"array",description:"Journal lines. Debit and credit totals must balance.",items:{type:"object",properties:{accountNo:{type:"string",description:"GL account number."},type:{type:"string",enum:["debit","credit"]},amount:{type:"number",description:"Positive amount."},department:{type:"string",description:"Optional department ID."},location:{type:"string",description:"Optional location ID."},memo:{type:"string",description:"Optional line description."}},required:["accountNo","type","amount"],additionalProperties:!0}}},required:["date","title","lines"],additionalProperties:!0},steps:[{id:"createJournalEntry",instruction:"Create the GLBATCH record.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:Lt(`<create><GLBATCH><JOURNAL><<(sourceData) => { ${ma} return esc(sourceData.journal || 'GJ'); }>></JOURNAL><BATCH_DATE><<(sourceData) => { ${fL} return toIntacctDate(sourceData.date); }>></BATCH_DATE><BATCH_TITLE><<(sourceData) => { ${ma} return esc(sourceData.title); }>></BATCH_TITLE><ENTRIES><<(sourceData) => { ${ma} ${mL} ${gL} const lines = Array.isArray(sourceData.lines) ? sourceData.lines : []; if (lines.length === 0) throw new Error('lines must contain at least one journal line.'); assertBalanced(lines); return lines.map(lineXml).join(''); }>></ENTRIES></GLBATCH></create>`)}}],outputTransform:lu({stepId:"createJournalEntry",objectName:"GLBATCH"})},{id:"sage-intacct-update-journal-entry",name:"Update Sage Intacct journal entry",shortName:"Update journal entry",instruction:"Updates an existing journal entry (GLBATCH) in Sage Intacct by record number. Posted or locked entries may refuse updates. When lines are provided they replace all existing lines of the entry.",inputSchema:{type:"object",properties:{recordNo:{type:"integer",description:"RECORDNO of the journal entry to update."},journal:{type:"string",description:"Optional new journal symbol."},date:{type:"string",description:"Optional new posting date as YYYY-MM-DD."},title:{type:"string",description:"Optional new description."},lines:{type:"array",description:"Optional replacement lines. When set, they replace every existing line and must balance.",items:{type:"object",properties:{accountNo:{type:"string",description:"GL account number."},type:{type:"string",enum:["debit","credit"]},amount:{type:"number",description:"Positive amount."},department:{type:"string",description:"Optional department ID."},location:{type:"string",description:"Optional location ID."},memo:{type:"string",description:"Optional line description."}},required:["accountNo","type","amount"],additionalProperties:!0}}},required:["recordNo"],additionalProperties:!0},steps:[{id:"updateJournalEntry",instruction:"Update the GLBATCH record.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:Lt(`<update><GLBATCH><RECORDNO><<(sourceData) => { const recordNo = Number(sourceData.recordNo); if (!Number.isInteger(recordNo) || recordNo <= 0) throw new Error('recordNo must be a positive integer.'); return recordNo; }>></RECORDNO><<(sourceData) => { ${ma} ${fL} ${mL} ${gL} let xml = ''; if (sourceData.journal) xml += '<JOURNAL>' + esc(sourceData.journal) + '</JOURNAL>'; if (sourceData.date) xml += '<BATCH_DATE>' + toIntacctDate(sourceData.date) + '</BATCH_DATE>'; if (sourceData.title) xml += '<BATCH_TITLE>' + esc(sourceData.title) + '</BATCH_TITLE>'; if (Array.isArray(sourceData.lines) && sourceData.lines.length > 0) { assertBalanced(sourceData.lines); xml += '<ENTRIES>' + sourceData.lines.map(lineXml).join('') + '</ENTRIES>'; } if (!xml) throw new Error('Provide at least one field to update.'); return xml; }>></GLBATCH></update>`)}}],outputTransform:lu({stepId:"updateJournalEntry",objectName:"GLBATCH"})},{id:"sage-intacct-create-vendor",name:"Create Sage Intacct vendor",shortName:"Create vendor",instruction:"Creates a vendor master record in Sage Intacct via the XML Web Services API. Omit vendorId when the company uses vendor auto-numbering. Re-running this tool creates another vendor; it is not idempotent.",inputSchema:{type:"object",properties:{vendorId:{type:"string",description:"Vendor ID. Omit when auto-numbering assigns it."},name:{type:"string",description:"Vendor name."},taxId:{type:"string",description:"Optional tax ID."}},required:["name"],additionalProperties:!0},steps:[{id:"createVendor",instruction:"Create the VENDOR record.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:Lt(`<create><VENDOR><<(sourceData) => { ${ma} if (!sourceData.name) throw new Error('name is required.'); let xml = ''; if (sourceData.vendorId) xml += '<VENDORID>' + esc(sourceData.vendorId) + '</VENDORID>'; xml += '<NAME>' + esc(sourceData.name) + '</NAME>'; if (sourceData.taxId) xml += '<TAXID>' + esc(sourceData.taxId) + '</TAXID>'; return xml; }>></VENDOR></create>`)}}],outputTransform:lu({stepId:"createVendor",objectName:"VENDOR"})},{id:"sage-intacct-update-vendor",name:"Update Sage Intacct vendor",shortName:"Update vendor",instruction:"Updates an existing vendor master record in Sage Intacct by record number. Only the provided fields change.",inputSchema:{type:"object",properties:{recordNo:{type:"integer",description:"RECORDNO of the vendor to update."},name:{type:"string",description:"Optional new vendor name."},status:{type:"string",enum:["active","inactive"]},taxId:{type:"string",description:"Optional new tax ID."}},required:["recordNo"],additionalProperties:!0},steps:[{id:"updateVendor",instruction:"Update the VENDOR record.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:Lt(`<update><VENDOR><RECORDNO><<(sourceData) => { const recordNo = Number(sourceData.recordNo); if (!Number.isInteger(recordNo) || recordNo <= 0) throw new Error('recordNo must be a positive integer.'); return recordNo; }>></RECORDNO><<(sourceData) => { ${ma} let xml = ''; if (sourceData.name) xml += '<NAME>' + esc(sourceData.name) + '</NAME>'; if (sourceData.status) xml += '<STATUS>' + esc(sourceData.status) + '</STATUS>'; if (sourceData.taxId) xml += '<TAXID>' + esc(sourceData.taxId) + '</TAXID>'; if (!xml) throw new Error('Provide at least one field to update.'); return xml; }>></VENDOR></update>`)}}],outputTransform:lu({stepId:"updateVendor",objectName:"VENDOR"})},{id:"sage-intacct-create-customer",name:"Create Sage Intacct customer",shortName:"Create customer",instruction:"Creates a customer master record in Sage Intacct via the XML Web Services API. Omit customerId when the company uses customer auto-numbering. Re-running this tool creates another customer; it is not idempotent.",inputSchema:{type:"object",properties:{customerId:{type:"string",description:"Customer ID. Omit when auto-numbering assigns it."},name:{type:"string",description:"Customer name."},taxId:{type:"string",description:"Optional tax ID."}},required:["name"],additionalProperties:!0},steps:[{id:"createCustomer",instruction:"Create the CUSTOMER record.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:Lt(`<create><CUSTOMER><<(sourceData) => { ${ma} if (!sourceData.name) throw new Error('name is required.'); let xml = ''; if (sourceData.customerId) xml += '<CUSTOMERID>' + esc(sourceData.customerId) + '</CUSTOMERID>'; xml += '<NAME>' + esc(sourceData.name) + '</NAME>'; if (sourceData.taxId) xml += '<TAXID>' + esc(sourceData.taxId) + '</TAXID>'; return xml; }>></CUSTOMER></create>`)}}],outputTransform:lu({stepId:"createCustomer",objectName:"CUSTOMER"})},{id:"sage-intacct-update-customer",name:"Update Sage Intacct customer",shortName:"Update customer",instruction:"Updates an existing customer master record in Sage Intacct by record number. Only the provided fields change.",inputSchema:{type:"object",properties:{recordNo:{type:"integer",description:"RECORDNO of the customer to update."},name:{type:"string",description:"Optional new customer name."},status:{type:"string",enum:["active","inactive"]},taxId:{type:"string",description:"Optional new tax ID."}},required:["recordNo"],additionalProperties:!0},steps:[{id:"updateCustomer",instruction:"Update the CUSTOMER record.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:Lt(`<update><CUSTOMER><RECORDNO><<(sourceData) => { const recordNo = Number(sourceData.recordNo); if (!Number.isInteger(recordNo) || recordNo <= 0) throw new Error('recordNo must be a positive integer.'); return recordNo; }>></RECORDNO><<(sourceData) => { ${ma} let xml = ''; if (sourceData.name) xml += '<NAME>' + esc(sourceData.name) + '</NAME>'; if (sourceData.status) xml += '<STATUS>' + esc(sourceData.status) + '</STATUS>'; if (sourceData.taxId) xml += '<TAXID>' + esc(sourceData.taxId) + '</TAXID>'; if (!xml) throw new Error('Provide at least one field to update.'); return xml; }>></CUSTOMER></update>`)}}],outputTransform:lu({stepId:"updateCustomer",objectName:"CUSTOMER"})},{id:"sage-intacct-create-account",name:"Create Sage Intacct GL account",shortName:"Create GL account",instruction:"Creates a general ledger account in Sage Intacct via the XML Web Services API. Re-running this tool creates another account; it is not idempotent.",inputSchema:{type:"object",required:["accountNo","title","normalBalance","accountType"],properties:{title:{type:"string"},accountNo:{type:"string"},accountType:{type:"string",enum:["balancesheet","incomestatement"]},normalBalance:{type:"string",enum:["debit","credit"]},closingType:{type:"string",enum:["non-closing account","closing account"],description:"Period-end closing type. Defaults to non-closing account."},closingAccountNo:{type:"string",description:"Account to close into. Sage requires it when closingType is closing account."}}},steps:[{id:"createAccount",instruction:"Create the GLACCOUNT record via the Sage Intacct XML API.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:Lt(`<create><GLACCOUNT><<(sourceData) => { const esc = (value) => String(value).replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", '''); if (!sourceData.accountNo) throw new Error('accountNo is required.'); if (!sourceData.title) throw new Error('title is required.'); let xml = '<ACCOUNTNO>' + esc(sourceData.accountNo) + '</ACCOUNTNO>'; xml += '<TITLE>' + esc(sourceData.title) + '</TITLE>'; xml += '<NORMALBALANCE>' + esc(sourceData.normalBalance || 'debit') + '</NORMALBALANCE>'; xml += '<ACCOUNTTYPE>' + esc(sourceData.accountType || 'balancesheet') + '</ACCOUNTTYPE>'; xml += '<CLOSINGTYPE>' + esc(sourceData.closingType || 'non-closing account') + '</CLOSINGTYPE>'; if (sourceData.closingAccountNo) xml += '<CLOSINGACCOUNTNO>' + esc(sourceData.closingAccountNo) + '</CLOSINGACCOUNTNO>'; return xml; }>></GLACCOUNT></create>`)}}],outputTransform:"(sourceData) => { const response = sourceData.createAccount && sourceData.createAccount.data ? sourceData.createAccount.data.RESPONSE : undefined; const control = response ? response.CONTROL : undefined; const operation = response ? response.OPERATION : undefined; const authentication = operation ? operation.AUTHENTICATION : undefined; const result = operation ? operation.RESULT : undefined; const statuses = [control && control.STATUS, authentication && authentication.STATUS, result && result.STATUS].filter(Boolean).map((value) => String(value).toLowerCase()); if (statuses.includes('failure')) { const message = (result && result.ERRORMESSAGE) || (authentication && authentication.ERR ? authentication.ERR.ERRORMESSAGE : undefined) || (control && control.ERR ? control.ERR.ERRORMESSAGE : undefined); const rawErrors = message ? message.ERROR : undefined; const errors = Array.isArray(rawErrors) ? rawErrors : (rawErrors ? [rawErrors] : []); const details = errors.map((error) => [error.ERRORNO, error.DESCRIPTION2 || error.DESCRIPTION, error.CORRECTION].filter(Boolean).join(' - ')).filter(Boolean); const supportIds = errors.map((error) => error.SUPPORTID).filter(Boolean); const suffix = supportIds.length ? ` Sage support ID: ${supportIds.join(', ')}.` : ''; throw new Error(`Sage Intacct request failed${details.length ? `: ${details.join('; ')}` : '.'}${suffix}`); } const data = result ? result.DATA : undefined; const raw = data ? (data.GLACCOUNT || data.glaccount) : undefined; const record = Array.isArray(raw) ? raw[0] : raw; return { recordNo: record && record.RECORDNO ? Number(record.RECORDNO) : undefined, record }; }"},{id:"sage-intacct-update-account",name:"Update Sage Intacct GL account",shortName:"Update GL account",instruction:"Updates an existing general ledger account in Sage Intacct by account number. Only the provided fields change.",inputSchema:{type:"object",required:["accountNo"],properties:{title:{type:"string"},accountNo:{type:"string"},accountType:{type:"string",enum:["balancesheet","incomestatement"]},normalBalance:{type:"string",enum:["debit","credit"]},status:{type:"string",enum:["active","inactive"]}}},steps:[{id:"updateAccount",instruction:"Update the GLACCOUNT record by account number.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:Lt(`<update><GLACCOUNT><ACCOUNTNO><<(sourceData) => { const esc = (value) => String(value).replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", '''); if (!sourceData.accountNo) throw new Error('accountNo is required.'); return esc(sourceData.accountNo); }>></ACCOUNTNO><<(sourceData) => { const esc = (value) => String(value).replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", '''); let xml = ''; if (sourceData.title) xml += '<TITLE>' + esc(sourceData.title) + '</TITLE>'; if (sourceData.normalBalance) xml += '<NORMALBALANCE>' + esc(sourceData.normalBalance) + '</NORMALBALANCE>'; if (sourceData.accountType) xml += '<ACCOUNTTYPE>' + esc(sourceData.accountType) + '</ACCOUNTTYPE>'; if (sourceData.status) xml += '<STATUS>' + esc(sourceData.status) + '</STATUS>'; if (!xml) throw new Error('Provide at least one field to update.'); return xml; }>></GLACCOUNT></update>`)}}],outputTransform:"(sourceData) => { const response = sourceData.updateAccount && sourceData.updateAccount.data ? sourceData.updateAccount.data.RESPONSE : undefined; const control = response ? response.CONTROL : undefined; const operation = response ? response.OPERATION : undefined; const authentication = operation ? operation.AUTHENTICATION : undefined; const result = operation ? operation.RESULT : undefined; const statuses = [control && control.STATUS, authentication && authentication.STATUS, result && result.STATUS].filter(Boolean).map((value) => String(value).toLowerCase()); if (statuses.includes('failure')) { const message = (result && result.ERRORMESSAGE) || (authentication && authentication.ERR ? authentication.ERR.ERRORMESSAGE : undefined) || (control && control.ERR ? control.ERR.ERRORMESSAGE : undefined); const rawErrors = message ? message.ERROR : undefined; const errors = Array.isArray(rawErrors) ? rawErrors : (rawErrors ? [rawErrors] : []); const details = errors.map((error) => [error.ERRORNO, error.DESCRIPTION2 || error.DESCRIPTION, error.CORRECTION].filter(Boolean).join(' - ')).filter(Boolean); const supportIds = errors.map((error) => error.SUPPORTID).filter(Boolean); const suffix = supportIds.length ? ` Sage support ID: ${supportIds.join(', ')}.` : ''; throw new Error(`Sage Intacct request failed${details.length ? `: ${details.join('; ')}` : '.'}${suffix}`); } const data = result ? result.DATA : undefined; const raw = data ? (data.GLACCOUNT || data.glaccount) : undefined; const record = Array.isArray(raw) ? raw[0] : raw; return { accountNo: sourceData.accountNo, record }; }"},{id:"sage-intacct-create-invoice",name:"Create Sage Intacct AR invoice",shortName:"Create invoice",instruction:"Creates an AR invoice in Sage Intacct via the XML Web Services API. Requires a customer ID, transaction date, and at least one line item with a GL account and amount. Re-running creates another invoice; it is not idempotent.",inputSchema:{type:"object",required:["customerId","dateCreated","dateDue","lines"],properties:{lines:{type:"array",items:{type:"object",required:["glAccountNo","amount"],properties:{memo:{type:"string"},amount:{type:"number"},glAccountNo:{type:"string"},departmentId:{type:"string"},locationId:{type:"string"},vendorId:{type:"string"},customerId:{type:"string"},projectId:{type:"string"}}}},dateDue:{type:"string"},customerId:{type:"string"},dateCreated:{type:"string"},datePosted:{type:"string"},termName:{type:"string"},description:{type:"string"}}},steps:[{id:"createInvoice",instruction:"Create the ARINVOICE record with line items.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:Lt("<create><ARINVOICE><<(sourceData) => { const esc = (value) => String(value).replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('\"', '"').replaceAll(\"'\", '''); if (!sourceData.customerId) throw new Error('customerId is required.'); if (!sourceData.dateCreated) throw new Error('dateCreated is required (YYYY-MM-DD).'); const lines = Array.isArray(sourceData.lines) ? sourceData.lines : []; if (lines.length === 0) throw new Error('lines must contain at least one invoice line.'); const match = String(sourceData.dateCreated).match(/^(\\d{4})-(\\d{2})-(\\d{2})/); const dateXml = match ? `<WHENCREATED><YEAR>${match[1]}</YEAR><MONTH>${match[2]}</MONTH><DAY>${match[3]}</DAY></WHENCREATED>` : `<WHENCREATED>${esc(sourceData.dateCreated)}</WHENCREATED>`; let xml = '<CUSTOMERID>' + esc(sourceData.customerId) + '</CUSTOMERID>'; xml += dateXml; if (sourceData.datePosted) { const mp = String(sourceData.datePosted).match(/^(\\d{4})-(\\d{2})-(\\d{2})/); if (mp) xml += `<WHENPOSTED><YEAR>${mp[1]}</YEAR><MONTH>${mp[2]}</MONTH><DAY>${mp[3]}</DAY></WHENPOSTED>`; } if (sourceData.dateDue) { const md = String(sourceData.dateDue).match(/^(\\d{4})-(\\d{2})-(\\d{2})/); if (md) xml += `<WHENDUE><YEAR>${md[1]}</YEAR><MONTH>${md[2]}</MONTH><DAY>${md[3]}</DAY></WHENDUE>`; } else if (sourceData.termName) { xml += '<TERMNAME>' + esc(sourceData.termName) + '</TERMNAME>'; } if (sourceData.description) xml += '<DESCRIPTION>' + esc(sourceData.description) + '</DESCRIPTION>'; xml += '<ARINVOICEITEMS>'; lines.forEach((line) => { if (!line.glAccountNo) throw new Error('Each line requires glAccountNo.'); if (line.amount == null) throw new Error('Each line requires amount.'); xml += '<ARINVOICEITEM>'; xml += '<ACCOUNTNO>' + esc(line.glAccountNo) + '</ACCOUNTNO>'; xml += '<AMOUNT>' + Number(line.amount) + '</AMOUNT>'; if (line.memo) xml += '<MEMO>' + esc(line.memo) + '</MEMO>'; if (line.departmentId) xml += '<DEPARTMENTID>' + esc(line.departmentId) + '</DEPARTMENTID>'; if (line.locationId) xml += '<LOCATIONID>' + esc(line.locationId) + '</LOCATIONID>'; if (line.vendorId) xml += '<VENDORID>' + esc(line.vendorId) + '</VENDORID>'; if (line.customerId) xml += '<CUSTOMERID>' + esc(line.customerId) + '</CUSTOMERID>'; if (line.projectId) xml += '<PROJECTID>' + esc(line.projectId) + '</PROJECTID>'; xml += '</ARINVOICEITEM>'; }); xml += '</ARINVOICEITEMS>'; return xml; }>></ARINVOICE></create>")}}],outputTransform:"(sourceData) => { const response = sourceData.createInvoice && sourceData.createInvoice.data ? sourceData.createInvoice.data.RESPONSE : undefined; const control = response ? response.CONTROL : undefined; const operation = response ? response.OPERATION : undefined; const authentication = operation ? operation.AUTHENTICATION : undefined; const result = operation ? operation.RESULT : undefined; const statuses = [control && control.STATUS, authentication && authentication.STATUS, result && result.STATUS].filter(Boolean).map((value) => String(value).toLowerCase()); if (statuses.includes('failure')) { const message = (result && result.ERRORMESSAGE) || (authentication && authentication.ERR ? authentication.ERR.ERRORMESSAGE : undefined) || (control && control.ERR ? control.ERR.ERRORMESSAGE : undefined); const rawErrors = message ? message.ERROR : undefined; const errors = Array.isArray(rawErrors) ? rawErrors : (rawErrors ? [rawErrors] : []); const details = errors.map((error) => [error.ERRORNO, error.DESCRIPTION2 || error.DESCRIPTION, error.CORRECTION].filter(Boolean).join(' - ')).filter(Boolean); const supportIds = errors.map((error) => error.SUPPORTID).filter(Boolean); const suffix = supportIds.length ? ` Sage support ID: ${supportIds.join(', ')}.` : ''; throw new Error(`Sage Intacct request failed${details.length ? `: ${details.join('; ')}` : '.'}${suffix}`); } const data = result ? result.DATA : undefined; const raw = data ? (data.ARINVOICE || data.arinvoice) : undefined; const record = Array.isArray(raw) ? raw[0] : raw; return { recordNo: record && record.RECORDNO ? Number(record.RECORDNO) : undefined, record }; }"},{id:"sage-intacct-update-invoice",name:"Update Sage Intacct AR invoice",shortName:"Update invoice",instruction:"Updates an existing AR invoice in Sage Intacct by record number. Only the provided fields change. Line items can be added or updated by line number.",inputSchema:{type:"object",required:["recordNo"],properties:{recordNo:{type:"integer"},description:{type:"string"},customerId:{type:"string"},dateCreated:{type:"string"},dateDue:{type:"string"},termName:{type:"string"},lines:{type:"array",items:{type:"object",properties:{lineNo:{type:"integer"},memo:{type:"string"},amount:{type:"number"},glAccountNo:{type:"string"},departmentId:{type:"string"},locationId:{type:"string"},vendorId:{type:"string"},customerId:{type:"string"},projectId:{type:"string"}}}}}},steps:[{id:"updateInvoice",instruction:"Update the ARINVOICE record by RECORDNO.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:Lt("<update><ARINVOICE><RECORDNO><<(sourceData) => { const recordNo = Number(sourceData.recordNo); if (!Number.isInteger(recordNo) || recordNo <= 0) throw new Error('recordNo must be a positive integer.'); return recordNo; }>></RECORDNO><<(sourceData) => { const esc = (value) => String(value).replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('\"', '"').replaceAll(\"'\", '''); let xml = ''; if (sourceData.customerId) xml += '<CUSTOMERID>' + esc(sourceData.customerId) + '</CUSTOMERID>'; if (sourceData.dateCreated) { const match = String(sourceData.dateCreated).match(/^(\\d{4})-(\\d{2})-(\\d{2})/); if (match) xml += `<WHENCREATED><YEAR>${match[1]}</YEAR><MONTH>${match[2]}</MONTH><DAY>${match[3]}</DAY></WHENCREATED>`; } if (sourceData.dateDue) { const md = String(sourceData.dateDue).match(/^(\\d{4})-(\\d{2})-(\\d{2})/); if (md) xml += `<WHENDUE><YEAR>${md[1]}</YEAR><MONTH>${md[2]}</MONTH><DAY>${md[3]}</DAY></WHENDUE>`; } if (sourceData.termName) xml += '<TERMNAME>' + esc(sourceData.termName) + '</TERMNAME>'; if (sourceData.description) xml += '<DESCRIPTION>' + esc(sourceData.description) + '</DESCRIPTION>'; const lines = Array.isArray(sourceData.lines) ? sourceData.lines : []; if (lines.length > 0) { xml += '<ARINVOICEITEMS>'; lines.forEach((line) => { xml += '<ARINVOICEITEM>'; if (line.lineNo) xml += '<LINE_NO>' + Number(line.lineNo) + '</LINE_NO>'; if (line.glAccountNo) xml += '<ACCOUNTNO>' + esc(line.glAccountNo) + '</ACCOUNTNO>'; if (line.amount != null) xml += '<AMOUNT>' + Number(line.amount) + '</AMOUNT>'; if (line.memo) xml += '<MEMO>' + esc(line.memo) + '</MEMO>'; if (line.departmentId) xml += '<DEPARTMENTID>' + esc(line.departmentId) + '</DEPARTMENTID>'; if (line.locationId) xml += '<LOCATIONID>' + esc(line.locationId) + '</LOCATIONID>'; if (line.vendorId) xml += '<VENDORID>' + esc(line.vendorId) + '</VENDORID>'; if (line.customerId) xml += '<CUSTOMERID>' + esc(line.customerId) + '</CUSTOMERID>'; if (line.projectId) xml += '<PROJECTID>' + esc(line.projectId) + '</PROJECTID>'; xml += '</ARINVOICEITEM>'; }); xml += '</ARINVOICEITEMS>'; } if (!xml && lines.length === 0) throw new Error('Provide at least one field to update.'); return xml; }>></ARINVOICE></update>")}}],outputTransform:"(sourceData) => { const response = sourceData.updateInvoice && sourceData.updateInvoice.data ? sourceData.updateInvoice.data.RESPONSE : undefined; const control = response ? response.CONTROL : undefined; const operation = response ? response.OPERATION : undefined; const authentication = operation ? operation.AUTHENTICATION : undefined; const result = operation ? operation.RESULT : undefined; const statuses = [control && control.STATUS, authentication && authentication.STATUS, result && result.STATUS].filter(Boolean).map((value) => String(value).toLowerCase()); if (statuses.includes('failure')) { const message = (result && result.ERRORMESSAGE) || (authentication && authentication.ERR ? authentication.ERR.ERRORMESSAGE : undefined) || (control && control.ERR ? control.ERR.ERRORMESSAGE : undefined); const rawErrors = message ? message.ERROR : undefined; const errors = Array.isArray(rawErrors) ? rawErrors : (rawErrors ? [rawErrors] : []); const details = errors.map((error) => [error.ERRORNO, error.DESCRIPTION2 || error.DESCRIPTION, error.CORRECTION].filter(Boolean).join(' - ')).filter(Boolean); const supportIds = errors.map((error) => error.SUPPORTID).filter(Boolean); const suffix = supportIds.length ? ` Sage support ID: ${supportIds.join(', ')}.` : ''; throw new Error(`Sage Intacct request failed${details.length ? `: ${details.join('; ')}` : '.'}${suffix}`); } const data = result ? result.DATA : undefined; const raw = data ? (data.ARINVOICE || data.arinvoice) : undefined; const record = Array.isArray(raw) ? raw[0] : raw; return { recordNo: sourceData.recordNo, record }; }"},{id:"sage-intacct-create-bill",name:"Create Sage Intacct AP bill",shortName:"Create bill",instruction:"Creates an AP bill in Sage Intacct via the XML Web Services API. Requires a vendor ID, transaction date, and at least one line item with a GL account and amount. Re-running creates another bill; it is not idempotent.",inputSchema:{type:"object",required:["lines","dateDue","vendorId","dateCreated"],properties:{lines:{type:"array",items:{type:"object",required:["glAccountNo","amount"],properties:{memo:{type:"string"},amount:{type:"number"},glAccountNo:{type:"string"},departmentId:{type:"string"},locationId:{type:"string"},vendorId:{type:"string"},customerId:{type:"string"},projectId:{type:"string"}}}},dateDue:{type:"string"},vendorId:{type:"string"},dateCreated:{type:"string"},datePosted:{type:"string"},termName:{type:"string"},description:{type:"string"}}},steps:[{id:"createBill",instruction:"Create the APBILL record with line items.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:Lt(`<create><APBILL><<(sourceData) => { const esc = (value) => String(value).replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", '''); if (!sourceData.vendorId) throw new Error('vendorId is required.'); if (!sourceData.dateCreated) throw new Error('dateCreated is required (YYYY-MM-DD).'); const lines = Array.isArray(sourceData.lines) ? sourceData.lines : []; if (lines.length === 0) throw new Error('lines must contain at least one bill line.'); const match = String(sourceData.dateCreated).match(/^(\\d{4})-(\\d{2})-(\\d{2})/); const dateStr = match ? match[2] + '/' + match[3] + '/' + match[1] : sourceData.dateCreated; let xml = '<VENDORID>' + esc(sourceData.vendorId) + '</VENDORID>'; xml += '<WHENCREATED>' + esc(dateStr) + '</WHENCREATED>'; if (sourceData.datePosted) { const mp = String(sourceData.datePosted).match(/^(\\d{4})-(\\d{2})-(\\d{2})/); xml += '<WHENPOSTED>' + esc(mp ? mp[2] + '/' + mp[3] + '/' + mp[1] : sourceData.datePosted) + '</WHENPOSTED>'; } if (sourceData.dateDue) { const md = String(sourceData.dateDue).match(/^(\\d{4})-(\\d{2})-(\\d{2})/); xml += '<WHENDUE>' + esc(md ? md[2] + '/' + md[3] + '/' + md[1] : sourceData.dateDue) + '</WHENDUE>'; } else if (sourceData.termName) { xml += '<TERMNAME>' + esc(sourceData.termName) + '</TERMNAME>'; } if (sourceData.description) xml += '<DESCRIPTION>' + esc(sourceData.description) + '</DESCRIPTION>'; xml += '<APBILLITEMS>'; lines.forEach((line) => { if (!line.glAccountNo) throw new Error('Each line requires glAccountNo.'); if (line.amount == null) throw new Error('Each line requires amount.'); xml += '<APBILLITEM>'; xml += '<ACCOUNTNO>' + esc(line.glAccountNo) + '</ACCOUNTNO>'; xml += '<AMOUNT>' + Number(line.amount) + '</AMOUNT>'; if (line.memo) xml += '<MEMO>' + esc(line.memo) + '</MEMO>'; if (line.departmentId) xml += '<DEPARTMENTID>' + esc(line.departmentId) + '</DEPARTMENTID>'; if (line.locationId) xml += '<LOCATIONID>' + esc(line.locationId) + '</LOCATIONID>'; if (line.vendorId) xml += '<VENDORID>' + esc(line.vendorId) + '</VENDORID>'; if (line.customerId) xml += '<CUSTOMERID>' + esc(line.customerId) + '</CUSTOMERID>'; if (line.projectId) xml += '<PROJECTID>' + esc(line.projectId) + '</PROJECTID>'; xml += '</APBILLITEM>'; }); xml += '</APBILLITEMS>'; return xml; }>></APBILL></create>`)}}],outputTransform:"(sourceData) => { const response = sourceData.createBill && sourceData.createBill.data ? sourceData.createBill.data.RESPONSE : undefined; const control = response ? response.CONTROL : undefined; const operation = response ? response.OPERATION : undefined; const authentication = operation ? operation.AUTHENTICATION : undefined; const result = operation ? operation.RESULT : undefined; const statuses = [control && control.STATUS, authentication && authentication.STATUS, result && result.STATUS].filter(Boolean).map((value) => String(value).toLowerCase()); if (statuses.includes('failure')) { const message = (result && result.ERRORMESSAGE) || (authentication && authentication.ERR ? authentication.ERR.ERRORMESSAGE : undefined) || (control && control.ERR ? control.ERR.ERRORMESSAGE : undefined); const rawErrors = message ? message.ERROR : undefined; const errors = Array.isArray(rawErrors) ? rawErrors : (rawErrors ? [rawErrors] : []); const details = errors.map((error) => [error.ERRORNO, error.DESCRIPTION2 || error.DESCRIPTION, error.CORRECTION].filter(Boolean).join(' - ')).filter(Boolean); const supportIds = errors.map((error) => error.SUPPORTID).filter(Boolean); const suffix = supportIds.length ? ` Sage support ID: ${supportIds.join(', ')}.` : ''; throw new Error(`Sage Intacct request failed${details.length ? `: ${details.join('; ')}` : '.'}${suffix}`); } const data = result ? result.DATA : undefined; const raw = data ? (data.APBILL || data.apbill) : undefined; const record = Array.isArray(raw) ? raw[0] : raw; return { recordNo: record && record.RECORDNO ? Number(record.RECORDNO) : undefined, record }; }"},{id:"sage-intacct-update-bill",name:"Update Sage Intacct AP bill",shortName:"Update bill",instruction:"Updates an existing AP bill in Sage Intacct by record number. Only the provided fields change. Line items can be added or updated by line number.",inputSchema:{type:"object",required:["recordNo"],properties:{recordNo:{type:"integer"},description:{type:"string"},vendorId:{type:"string"},dateCreated:{type:"string"},dateDue:{type:"string"},termName:{type:"string"},lines:{type:"array",items:{type:"object",properties:{lineNo:{type:"integer"},memo:{type:"string"},amount:{type:"number"},glAccountNo:{type:"string"},departmentId:{type:"string"},locationId:{type:"string"},vendorId:{type:"string"},customerId:{type:"string"},projectId:{type:"string"}}}}}},steps:[{id:"updateBill",instruction:"Update the APBILL record by RECORDNO.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:Lt(`<update><APBILL><RECORDNO><<(sourceData) => { const recordNo = Number(sourceData.recordNo); if (!Number.isInteger(recordNo) || recordNo <= 0) throw new Error('recordNo must be a positive integer.'); return recordNo; }>></RECORDNO><<(sourceData) => { const esc = (value) => String(value).replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", '''); let xml = ''; if (sourceData.vendorId) xml += '<VENDORID>' + esc(sourceData.vendorId) + '</VENDORID>'; if (sourceData.dateCreated) { const match = String(sourceData.dateCreated).match(/^(\\d{4})-(\\d{2})-(\\d{2})/); xml += '<WHENCREATED>' + esc(match ? match[2] + '/' + match[3] + '/' + match[1] : sourceData.dateCreated) + '</WHENCREATED>'; } if (sourceData.dateDue) { const md = String(sourceData.dateDue).match(/^(\\d{4})-(\\d{2})-(\\d{2})/); xml += '<WHENDUE>' + esc(md ? md[2] + '/' + md[3] + '/' + md[1] : sourceData.dateDue) + '</WHENDUE>'; } if (sourceData.termName) xml += '<TERMNAME>' + esc(sourceData.termName) + '</TERMNAME>'; if (sourceData.description) xml += '<DESCRIPTION>' + esc(sourceData.description) + '</DESCRIPTION>'; const lines = Array.isArray(sourceData.lines) ? sourceData.lines : []; if (lines.length > 0) { xml += '<APBILLITEMS>'; lines.forEach((line) => { xml += '<APBILLITEM>'; if (line.lineNo) xml += '<LINE_NO>' + Number(line.lineNo) + '</LINE_NO>'; if (line.glAccountNo) xml += '<ACCOUNTNO>' + esc(line.glAccountNo) + '</ACCOUNTNO>'; if (line.amount != null) xml += '<AMOUNT>' + Number(line.amount) + '</AMOUNT>'; if (line.memo) xml += '<MEMO>' + esc(line.memo) + '</MEMO>'; if (line.departmentId) xml += '<DEPARTMENTID>' + esc(line.departmentId) + '</DEPARTMENTID>'; if (line.locationId) xml += '<LOCATIONID>' + esc(line.locationId) + '</LOCATIONID>'; if (line.vendorId) xml += '<VENDORID>' + esc(line.vendorId) + '</VENDORID>'; if (line.customerId) xml += '<CUSTOMERID>' + esc(line.customerId) + '</CUSTOMERID>'; if (line.projectId) xml += '<PROJECTID>' + esc(line.projectId) + '</PROJECTID>'; xml += '</APBILLITEM>'; }); xml += '</APBILLITEMS>'; } if (!xml && lines.length === 0) throw new Error('Provide at least one field to update.'); return xml; }>></APBILL></update>`)}}],outputTransform:"(sourceData) => { const response = sourceData.updateBill && sourceData.updateBill.data ? sourceData.updateBill.data.RESPONSE : undefined; const control = response ? response.CONTROL : undefined; const operation = response ? response.OPERATION : undefined; const authentication = operation ? operation.AUTHENTICATION : undefined; const result = operation ? operation.RESULT : undefined; const statuses = [control && control.STATUS, authentication && authentication.STATUS, result && result.STATUS].filter(Boolean).map((value) => String(value).toLowerCase()); if (statuses.includes('failure')) { const message = (result && result.ERRORMESSAGE) || (authentication && authentication.ERR ? authentication.ERR.ERRORMESSAGE : undefined) || (control && control.ERR ? control.ERR.ERRORMESSAGE : undefined); const rawErrors = message ? message.ERROR : undefined; const errors = Array.isArray(rawErrors) ? rawErrors : (rawErrors ? [rawErrors] : []); const details = errors.map((error) => [error.ERRORNO, error.DESCRIPTION2 || error.DESCRIPTION, error.CORRECTION].filter(Boolean).join(' - ')).filter(Boolean); const supportIds = errors.map((error) => error.SUPPORTID).filter(Boolean); const suffix = supportIds.length ? ` Sage support ID: ${supportIds.join(', ')}.` : ''; throw new Error(`Sage Intacct request failed${details.length ? `: ${details.join('; ')}` : '.'}${suffix}`); } const data = result ? result.DATA : undefined; const raw = data ? (data.APBILL || data.apbill) : undefined; const record = Array.isArray(raw) ? raw[0] : raw; return { recordNo: sourceData.recordNo, record }; }"},{id:"sage-intacct-create-department",name:"Create Sage Intacct department",shortName:"Create department",instruction:"Creates a department in Sage Intacct via the XML Web Services API. Requires a department ID and title. Re-running creates another department; it is not idempotent.",inputSchema:{type:"object",required:["departmentId","title"],properties:{title:{type:"string"},departmentId:{type:"string"}}},steps:[{id:"createDepartment",instruction:"Create the DEPARTMENT record.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:Lt(`<create><DEPARTMENT><<(sourceData) => { const esc = (value) => String(value).replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", '''); if (!sourceData.departmentId) throw new Error('departmentId is required.'); if (!sourceData.title) throw new Error('title is required.'); let xml = '<DEPARTMENTID>' + esc(sourceData.departmentId) + '</DEPARTMENTID>'; xml += '<TITLE>' + esc(sourceData.title) + '</TITLE>'; if (sourceData.parentId) xml += '<PARENTID>' + esc(sourceData.parentId) + '</PARENTID>'; if (sourceData.status) xml += '<STATUS>' + esc(sourceData.status) + '</STATUS>'; return xml; }>></DEPARTMENT></create>`)}}],outputTransform:"(sourceData) => { const response = sourceData.createDepartment && sourceData.createDepartment.data ? sourceData.createDepartment.data.RESPONSE : undefined; const control = response ? response.CONTROL : undefined; const operation = response ? response.OPERATION : undefined; const authentication = operation ? operation.AUTHENTICATION : undefined; const result = operation ? operation.RESULT : undefined; const statuses = [control && control.STATUS, authentication && authentication.STATUS, result && result.STATUS].filter(Boolean).map((value) => String(value).toLowerCase()); if (statuses.includes('failure')) { const message = (result && result.ERRORMESSAGE) || (authentication && authentication.ERR ? authentication.ERR.ERRORMESSAGE : undefined) || (control && control.ERR ? control.ERR.ERRORMESSAGE : undefined); const rawErrors = message ? message.ERROR : undefined; const errors = Array.isArray(rawErrors) ? rawErrors : (rawErrors ? [rawErrors] : []); const details = errors.map((error) => [error.ERRORNO, error.DESCRIPTION2 || error.DESCRIPTION, error.CORRECTION].filter(Boolean).join(' - ')).filter(Boolean); const supportIds = errors.map((error) => error.SUPPORTID).filter(Boolean); const suffix = supportIds.length ? ` Sage support ID: ${supportIds.join(', ')}.` : ''; throw new Error(`Sage Intacct request failed${details.length ? `: ${details.join('; ')}` : '.'}${suffix}`); } const data = result ? result.DATA : undefined; const raw = data ? (data.DEPARTMENT || data.department) : undefined; const record = Array.isArray(raw) ? raw[0] : raw; return { recordNo: record && record.RECORDNO ? Number(record.RECORDNO) : undefined, record }; }"},{id:"sage-intacct-update-department",name:"Update Sage Intacct department",shortName:"Update department",instruction:"Updates an existing department in Sage Intacct by record number. Only the provided fields change.",inputSchema:{type:"object",required:["recordNo"],properties:{title:{type:"string"},recordNo:{type:"integer"},parentId:{type:"string"},status:{type:"string",enum:["active","inactive"]}}},steps:[{id:"updateDepartment",instruction:"Update the DEPARTMENT record by RECORDNO.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:Lt(`<update><DEPARTMENT><RECORDNO><<(sourceData) => { const recordNo = Number(sourceData.recordNo); if (!Number.isInteger(recordNo) || recordNo <= 0) throw new Error('recordNo must be a positive integer.'); return recordNo; }>></RECORDNO><<(sourceData) => { const esc = (value) => String(value).replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", '''); let xml = ''; if (sourceData.title) xml += '<TITLE>' + esc(sourceData.title) + '</TITLE>'; if (sourceData.parentId) xml += '<PARENTID>' + esc(sourceData.parentId) + '</PARENTID>'; if (sourceData.status) xml += '<STATUS>' + esc(sourceData.status) + '</STATUS>'; if (!xml) throw new Error('Provide at least one field to update.'); return xml; }>></DEPARTMENT></update>`)}}],outputTransform:"(sourceData) => { const response = sourceData.updateDepartment && sourceData.updateDepartment.data ? sourceData.updateDepartment.data.RESPONSE : undefined; const control = response ? response.CONTROL : undefined; const operation = response ? response.OPERATION : undefined; const authentication = operation ? operation.AUTHENTICATION : undefined; const result = operation ? operation.RESULT : undefined; const statuses = [control && control.STATUS, authentication && authentication.STATUS, result && result.STATUS].filter(Boolean).map((value) => String(value).toLowerCase()); if (statuses.includes('failure')) { const message = (result && result.ERRORMESSAGE) || (authentication && authentication.ERR ? authentication.ERR.ERRORMESSAGE : undefined) || (control && control.ERR ? control.ERR.ERRORMESSAGE : undefined); const rawErrors = message ? message.ERROR : undefined; const errors = Array.isArray(rawErrors) ? rawErrors : (rawErrors ? [rawErrors] : []); const details = errors.map((error) => [error.ERRORNO, error.DESCRIPTION2 || error.DESCRIPTION, error.CORRECTION].filter(Boolean).join(' - ')).filter(Boolean); const supportIds = errors.map((error) => error.SUPPORTID).filter(Boolean); const suffix = supportIds.length ? ` Sage support ID: ${supportIds.join(', ')}.` : ''; throw new Error(`Sage Intacct request failed${details.length ? `: ${details.join('; ')}` : '.'}${suffix}`); } const data = result ? result.DATA : undefined; const raw = data ? (data.DEPARTMENT || data.department) : undefined; const record = Array.isArray(raw) ? raw[0] : raw; return { recordNo: sourceData.recordNo, record }; }"}]},dynamics365_sales:{bundleId:"dynamics365_sales",templateId:"dynamics365_sales",systemId:"dynamics365_sales",displayName:"Dynamics 365 Sales",description:"Read accounts, contacts and the sales pipeline from Dynamics 365 Sales.",systemUrl:"https://<<api_host>>/api/data/v9.2",credentialHint:"Set api_host to your environment host, then connect with Microsoft OAuth. Your assistant walks you through it.",requiredCredentialKeys:["api_host","access_token"],mcpServer:{name:"dynamics-sales",displayName:"Dynamics 365 Sales",description:"Accounts, contacts, opportunity pipeline and ad-hoc Dataverse queries from Dynamics 365 Sales."},installMcpServer:!0,agentLaunch:{userPrompt:"I just installed the Dynamics 365 Sales bundle. What can I do with it?",nextSteps:'Your first reply must be short: one line confirming the Dynamics MCP server is installed, then ask for their environment host in chat (like contoso.crm.dynamics.com \u2014 it is not a secret, so never collect it through a secure form; form values are redacted and you cannot read them back). When they reply, save it with tools.writeConnection passing secrets: { api_host: "<their host>" } directly, without asking for secure inputs. Then start Microsoft OAuth with connect and substitute the same host into the scopes yourself \u2014 set auth.scopes to "https://<host>/user_impersonation offline_access", never the <<api_host>> placeholder, which Microsoft rejects. OAuth fills access_token automatically; never send the user to the Connections page and never suggest the az CLI. Once connected, the MCP server is ready; offer one test run. Do not list the installed tools, do not add tips unless asked. If asked later: OAuth refresh is automatic, the query tool accepts any Dataverse entity set, and record totals above 5000 are reported as capped by Dataverse rather than exact.'},tools:[{id:"dynamics-list-accounts",name:"List Dynamics 365 accounts",shortName:"Accounts",instruction:"Lists account records from Dynamics 365 with name, account number and creation date. Supports an optional OData $filter. Useful for validating migrated accounts.",inputSchema:{type:"object",properties:{filter:{type:"string",description:`Optional OData $filter expression, e.g. "createdon gt 2026-01-01T00:00:00Z" or "contains(name,'GmbH')".`},maxResults:{type:"integer",description:"Maximum number of accounts to return in one call. Defaults to 100."}},additionalProperties:!0},steps:[{id:"fetchAccounts",instruction:"Fetch accounts from the Dataverse Web API.",config:{type:"request",systemId:"dynamics365_sales",url:"https://<<dynamics365_sales_api_host>>/api/data/v9.2/accounts",method:"GET",headers:{Authorization:"Bearer <<dynamics365_sales_access_token>>",Accept:"application/json","OData-MaxVersion":"4.0","OData-Version":"4.0","If-None-Match":"null"},queryParams:{$select:"name,accountnumber,telephone1,websiteurl,createdon,modifiedon",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchAccounts?.data ?? {}; const rows = data.value ?? []; const capped = data["@Microsoft.Dynamics.CRM.totalrecordcountlimitexceeded"] === true; return { total: capped ? null : (data["@odata.count"] ?? rows.length), totalCapped: capped, returned: rows.length, accounts: rows.map((r) => ({ id: r.accountid, name: r.name, accountNumber: r.accountnumber, phone: r.telephone1, website: r.websiteurl, createdOn: r.createdon, modifiedOn: r.modifiedon })) }; }'},{id:"dynamics-list-contacts",name:"List Dynamics 365 contacts",shortName:"Contacts",instruction:"Lists contact records from Dynamics 365 with name, email and creation date. Supports an optional OData $filter. Useful for validating migrated contacts.",inputSchema:{type:"object",properties:{filter:{type:"string",description:'Optional OData $filter expression, e.g. "emailaddress1 eq null" to find contacts missing an email.'},maxResults:{type:"integer",description:"Maximum number of contacts to return in one call. Defaults to 100."}},additionalProperties:!0},steps:[{id:"fetchContacts",instruction:"Fetch contacts from the Dataverse Web API.",config:{type:"request",systemId:"dynamics365_sales",url:"https://<<dynamics365_sales_api_host>>/api/data/v9.2/contacts",method:"GET",headers:{Authorization:"Bearer <<dynamics365_sales_access_token>>",Accept:"application/json","OData-MaxVersion":"4.0","OData-Version":"4.0","If-None-Match":"null"},queryParams:{$select:"fullname,emailaddress1,telephone1,jobtitle,createdon,modifiedon",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchContacts?.data ?? {}; const rows = data.value ?? []; const capped = data["@Microsoft.Dynamics.CRM.totalrecordcountlimitexceeded"] === true; return { total: capped ? null : (data["@odata.count"] ?? rows.length), totalCapped: capped, returned: rows.length, contacts: rows.map((r) => ({ id: r.contactid, name: r.fullname, email: r.emailaddress1, phone: r.telephone1, jobTitle: r.jobtitle, createdOn: r.createdon, modifiedOn: r.modifiedon })) }; }'},{id:"dynamics-open-opportunities",name:"List Dynamics 365 open opportunities",shortName:"Open opportunities",instruction:"Lists open opportunities from Dynamics 365 with estimated value and close date. Supports an optional additional OData $filter. Useful for pipeline verification during UAT.",inputSchema:{type:"object",properties:{filter:{type:"string",description:'Optional additional OData $filter combined with the open-state filter, e.g. "estimatedvalue gt 10000".'},maxResults:{type:"integer",description:"Maximum number of opportunities to return in one call. Defaults to 100."}},additionalProperties:!0},steps:[{id:"fetchOpportunities",instruction:"Fetch open opportunities from the Dataverse Web API.",config:{type:"request",systemId:"dynamics365_sales",url:"https://<<dynamics365_sales_api_host>>/api/data/v9.2/opportunities",method:"GET",headers:{Authorization:"Bearer <<dynamics365_sales_access_token>>",Accept:"application/json","OData-MaxVersion":"4.0","OData-Version":"4.0","If-None-Match":"null"},queryParams:{$select:"name,estimatedvalue,estimatedclosedate,createdon,statecode,_parentaccountid_value",$filter:'<<(p) => p.filter ? "statecode eq 0 and (" + p.filter + ")" : "statecode eq 0">>',$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchOpportunities?.data ?? {}; const rows = data.value ?? []; const capped = data["@Microsoft.Dynamics.CRM.totalrecordcountlimitexceeded"] === true; return { total: capped ? null : (data["@odata.count"] ?? rows.length), totalCapped: capped, returned: rows.length, opportunities: rows.map((r) => ({ id: r.opportunityid, name: r.name, estimatedValue: r.estimatedvalue, estimatedCloseDate: r.estimatedclosedate, accountId: r._parentaccountid_value, createdOn: r.createdon })) }; }'},{id:"dynamics-list-leads",name:"List Dynamics 365 leads",shortName:"Leads",instruction:"Lists lead records from Dynamics 365 with subject, name and company. Supports an optional OData $filter. Useful for validating migrated leads.",inputSchema:{type:"object",properties:{filter:{type:"string",description:'Optional OData $filter expression, e.g. "statecode eq 0" for open leads.'},maxResults:{type:"integer",description:"Maximum number of records to return in one call. Defaults to 100."}},additionalProperties:!0},steps:[{id:"fetchLeads",instruction:"Fetch leads from the Dataverse Web API.",config:{type:"request",systemId:"dynamics365_sales",url:"https://<<dynamics365_sales_api_host>>/api/data/v9.2/leads",method:"GET",headers:{Authorization:"Bearer <<dynamics365_sales_access_token>>",Accept:"application/json","OData-MaxVersion":"4.0","OData-Version":"4.0","If-None-Match":"null"},queryParams:{$select:"subject,fullname,companyname,statecode,createdon,modifiedon",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchLeads?.data ?? {}; const rows = data.value ?? []; const capped = data["@Microsoft.Dynamics.CRM.totalrecordcountlimitexceeded"] === true; return { total: capped ? null : (data["@odata.count"] ?? rows.length), totalCapped: capped, returned: rows.length, records: rows.map((r) => ({ id: r.leadid, subject: r.subject, name: r.fullname, company: r.companyname, state: r.statecode, createdOn: r.createdon, modifiedOn: r.modifiedon })) }; }'},{id:"dynamics-list-cases",name:"List Dynamics 365 cases",shortName:"Cases",instruction:"Lists case (incident) records from Dynamics 365 with title, ticket number and status. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{filter:{type:"string",description:'Optional OData $filter expression, e.g. "statecode eq 0" for active cases.'},maxResults:{type:"integer",description:"Maximum number of records to return in one call. Defaults to 100."}},additionalProperties:!0},steps:[{id:"fetchCases",instruction:"Fetch incidents from the Dataverse Web API.",config:{type:"request",systemId:"dynamics365_sales",url:"https://<<dynamics365_sales_api_host>>/api/data/v9.2/incidents",method:"GET",headers:{Authorization:"Bearer <<dynamics365_sales_access_token>>",Accept:"application/json","OData-MaxVersion":"4.0","OData-Version":"4.0","If-None-Match":"null"},queryParams:{$select:"title,ticketnumber,statecode,createdon,_customerid_value",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchCases?.data ?? {}; const rows = data.value ?? []; const capped = data["@Microsoft.Dynamics.CRM.totalrecordcountlimitexceeded"] === true; return { total: capped ? null : (data["@odata.count"] ?? rows.length), totalCapped: capped, returned: rows.length, records: rows.map((r) => ({ id: r.incidentid, title: r.title, ticketNumber: r.ticketnumber, state: r.statecode, customerId: r._customerid_value, createdOn: r.createdon })) }; }'},{id:"dynamics-list-users",name:"List Dynamics 365 users",shortName:"Users",instruction:"Lists system users from Dynamics 365 with name, email and disabled state. Useful for owner-mapping checks during migrations.",inputSchema:{type:"object",properties:{filter:{type:"string",description:'Optional OData $filter expression, e.g. "isdisabled eq false" for active users.'},maxResults:{type:"integer",description:"Maximum number of records to return in one call. Defaults to 100."}},additionalProperties:!0},steps:[{id:"fetchUsers",instruction:"Fetch systemusers from the Dataverse Web API.",config:{type:"request",systemId:"dynamics365_sales",url:"https://<<dynamics365_sales_api_host>>/api/data/v9.2/systemusers",method:"GET",headers:{Authorization:"Bearer <<dynamics365_sales_access_token>>",Accept:"application/json","OData-MaxVersion":"4.0","OData-Version":"4.0","If-None-Match":"null"},queryParams:{$select:"fullname,internalemailaddress,isdisabled,createdon",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchUsers?.data ?? {}; const rows = data.value ?? []; const capped = data["@Microsoft.Dynamics.CRM.totalrecordcountlimitexceeded"] === true; return { total: capped ? null : (data["@odata.count"] ?? rows.length), totalCapped: capped, returned: rows.length, records: rows.map((r) => ({ id: r.systemuserid, name: r.fullname, email: r.internalemailaddress, disabled: r.isdisabled, createdOn: r.createdon })) }; }'},{id:"dynamics-list-products",name:"List Dynamics 365 products",shortName:"Products",instruction:"Lists product catalog records from Dynamics 365 with name, number and state. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{filter:{type:"string",description:'Optional OData $filter expression, e.g. "statecode eq 0" for active products.'},maxResults:{type:"integer",description:"Maximum number of records to return in one call. Defaults to 100."}},additionalProperties:!0},steps:[{id:"fetchProducts",instruction:"Fetch products from the Dataverse Web API.",config:{type:"request",systemId:"dynamics365_sales",url:"https://<<dynamics365_sales_api_host>>/api/data/v9.2/products",method:"GET",headers:{Authorization:"Bearer <<dynamics365_sales_access_token>>",Accept:"application/json","OData-MaxVersion":"4.0","OData-Version":"4.0","If-None-Match":"null"},queryParams:{$select:"name,productnumber,statecode,createdon",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchProducts?.data ?? {}; const rows = data.value ?? []; const capped = data["@Microsoft.Dynamics.CRM.totalrecordcountlimitexceeded"] === true; return { total: capped ? null : (data["@odata.count"] ?? rows.length), totalCapped: capped, returned: rows.length, records: rows.map((r) => ({ id: r.productid, name: r.name, number: r.productnumber, state: r.statecode, createdOn: r.createdon })) }; }'},{id:"dynamics-query-dataverse",name:"Query any Dynamics 365 entity",shortName:"Query any entity",instruction:'Queries any Dataverse entity set. Required input: entitySet \u2014 the plural entity set name, e.g. "leads", "systemusers", "incidents". Optional inputs: select (OData $select field list), filter (OData $filter expression), maxResults (record cap, default 100). The workhorse tool for CRM migration validation and data quality checks beyond the prebuilt lists.',inputSchema:{type:"object",properties:{entitySet:{type:"string",description:'Dataverse entity set name (plural), e.g. "leads", "systemusers", "incidents".'},select:{type:"string",description:'Comma-separated OData $select field list, e.g. "subject,createdon". Omit for all fields.'},filter:{type:"string",description:"Optional OData $filter expression."},maxResults:{type:"integer",description:"Maximum number of records to return in one call. Defaults to 100."}},required:["entitySet"],additionalProperties:!0},steps:[{id:"queryEntity",instruction:"Query the requested Dataverse entity set.",config:{type:"request",systemId:"dynamics365_sales",url:"https://<<dynamics365_sales_api_host>>/api/data/v9.2/<<entitySet>>",method:"GET",headers:{Authorization:"Bearer <<dynamics365_sales_access_token>>",Accept:"application/json","OData-MaxVersion":"4.0","OData-Version":"4.0","If-None-Match":"null"},queryParams:{$select:"<<select>>",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.queryEntity?.data ?? {}; const rows = data.value ?? []; const capped = data["@Microsoft.Dynamics.CRM.totalrecordcountlimitexceeded"] === true; return { total: capped ? null : (data["@odata.count"] ?? rows.length), totalCapped: capped, returned: rows.length, records: rows }; }'}]},dynamics365_business_central:{bundleId:"dynamics365_business_central",templateId:"dynamics365_business_central",systemId:"dynamics365_business_central",displayName:"Dynamics 365 Business Central",description:"Read companies, customers, vendors and the chart of accounts from Business Central.",systemUrl:"https://api.businesscentral.dynamics.com/v2.0/<<environment>>/api/v2.0",credentialHint:"Connect your Business Central environment. Your assistant walks you through it.",requiredCredentialKeys:["environment","access_token"],oauthSignIn:!0,mcpServer:{name:"business-central",displayName:"Dynamics 365 Business Central",description:"Companies, customers, vendors, chart of accounts and ad-hoc entity queries from Business Central."},installMcpServer:!0,agentLaunch:{userPrompt:"I just installed the Dynamics 365 Business Central bundle. What can I do with it?",nextSteps:"Your first reply must be short: one line confirming the Business Central MCP server is installed, then collect the credentials. Use connect with this system's connection id and fields to save environment (their BC environment name, usually production or sandbox) and access_token; never send the user to the Connections page. Fastest token: az account get-access-token --resource https://api.businesscentral.dynamics.com. Once saved, the MCP server is ready; run the companies tool as the test, because its result contains the company id every other tool needs. Do not list the installed tools, do not add tips unless asked. If asked later: tokens expire after about an hour, so a 401 means refresh access_token; the query tool accepts any Business Central entity set like items or salesInvoices."},tools:[{id:"business-central-list-companies",name:"List Business Central companies",shortName:"Companies",instruction:"Lists the companies in the Business Central environment. Run this first: every other Business Central tool needs a companyId from this list.",inputSchema:{type:"object",properties:{},additionalProperties:!0},steps:[{id:"fetchCompanies",instruction:"Fetch the companies in this environment.",config:{type:"request",systemId:"dynamics365_business_central",url:"https://api.businesscentral.dynamics.com/v2.0/<<dynamics365_business_central_environment>>/api/v2.0/companies",method:"GET",headers:{Authorization:"Bearer <<dynamics365_business_central_access_token>>",Accept:"application/json","Data-Access-Intent":"ReadOnly"}}}],outputTransform:"(sourceData) => { const rows = sourceData.fetchCompanies?.data?.value ?? []; return { total: rows.length, companies: rows.map((r) => ({ companyId: r.id, name: r.name, displayName: r.displayName })) }; }"},{id:"business-central-list-customers",name:"List Business Central customers",shortName:"Customers",instruction:"Lists customer master records from a Business Central company. Requires a companyId from the companies tool. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company id (GUID) from the companies tool."},filter:{type:"string",description:`Optional OData $filter expression, e.g. "blocked ne ''" or "contains(displayName,'GmbH')".`},maxResults:{type:"integer",description:"Maximum number of customers to return in one call. Defaults to 100."}},required:["companyId"],additionalProperties:!0},steps:[{id:"fetchCustomers",instruction:"Fetch customers for the given company.",config:{type:"request",systemId:"dynamics365_business_central",url:"https://api.businesscentral.dynamics.com/v2.0/<<dynamics365_business_central_environment>>/api/v2.0/companies(<<companyId>>)/customers",method:"GET",headers:{Authorization:"Bearer <<dynamics365_business_central_access_token>>",Accept:"application/json","Data-Access-Intent":"ReadOnly"},queryParams:{$select:"id,number,displayName,email,phoneNumber,blocked,lastModifiedDateTime",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchCustomers?.data ?? {}; const rows = data.value ?? []; return { total: data["@odata.count"] ?? rows.length, customers: rows.map((r) => ({ id: r.id, number: r.number, name: r.displayName, email: r.email, phone: r.phoneNumber, blocked: r.blocked, lastModified: r.lastModifiedDateTime })) }; }'},{id:"business-central-list-vendors",name:"List Business Central vendors",shortName:"Vendors",instruction:"Lists vendor master records from a Business Central company. Requires a companyId from the companies tool. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company id (GUID) from the companies tool."},filter:{type:"string",description:"Optional OData $filter expression."},maxResults:{type:"integer",description:"Maximum number of vendors to return in one call. Defaults to 100."}},required:["companyId"],additionalProperties:!0},steps:[{id:"fetchVendors",instruction:"Fetch vendors for the given company.",config:{type:"request",systemId:"dynamics365_business_central",url:"https://api.businesscentral.dynamics.com/v2.0/<<dynamics365_business_central_environment>>/api/v2.0/companies(<<companyId>>)/vendors",method:"GET",headers:{Authorization:"Bearer <<dynamics365_business_central_access_token>>",Accept:"application/json","Data-Access-Intent":"ReadOnly"},queryParams:{$select:"id,number,displayName,email,phoneNumber,blocked,lastModifiedDateTime",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchVendors?.data ?? {}; const rows = data.value ?? []; return { total: data["@odata.count"] ?? rows.length, vendors: rows.map((r) => ({ id: r.id, number: r.number, name: r.displayName, email: r.email, phone: r.phoneNumber, blocked: r.blocked, lastModified: r.lastModifiedDateTime })) }; }'},{id:"business-central-list-accounts",name:"List Business Central chart of accounts",shortName:"Chart of accounts",instruction:"Lists general ledger accounts (the chart of accounts) from a Business Central company. Requires a companyId from the companies tool. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company id (GUID) from the companies tool."},filter:{type:"string",description:`Optional OData $filter expression, e.g. "category eq 'Assets'".`},maxResults:{type:"integer",description:"Maximum number of accounts to return in one call. Defaults to 200."}},required:["companyId"],additionalProperties:!0},steps:[{id:"fetchAccounts",instruction:"Fetch general ledger accounts for the given company.",config:{type:"request",systemId:"dynamics365_business_central",url:"https://api.businesscentral.dynamics.com/v2.0/<<dynamics365_business_central_environment>>/api/v2.0/companies(<<companyId>>)/accounts",method:"GET",headers:{Authorization:"Bearer <<dynamics365_business_central_access_token>>",Accept:"application/json","Data-Access-Intent":"ReadOnly"},queryParams:{$select:"id,number,displayName,category,subCategory,blocked,accountType",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 200>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchAccounts?.data ?? {}; const rows = data.value ?? []; return { total: data["@odata.count"] ?? rows.length, accounts: rows.map((r) => ({ id: r.id, number: r.number, name: r.displayName, category: r.category, subCategory: r.subCategory, type: r.accountType, blocked: r.blocked })) }; }'},{id:"business-central-list-items",name:"List Business Central items",shortName:"Items",instruction:"Lists item (product) master records from a Business Central company. Requires a companyId from the companies tool. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company id (GUID) from the companies tool."},filter:{type:"string",description:`Optional OData $filter expression, e.g. "type eq 'Inventory'".`},maxResults:{type:"integer",description:"Maximum number of items to return in one call. Defaults to 100."}},required:["companyId"],additionalProperties:!0},steps:[{id:"fetchItems",instruction:"Fetch items for the given company.",config:{type:"request",systemId:"dynamics365_business_central",url:"https://api.businesscentral.dynamics.com/v2.0/<<dynamics365_business_central_environment>>/api/v2.0/companies(<<companyId>>)/items",method:"GET",headers:{Authorization:"Bearer <<dynamics365_business_central_access_token>>",Accept:"application/json","Data-Access-Intent":"ReadOnly"},queryParams:{$select:"id,number,displayName,type,unitPrice,inventory,blocked,lastModifiedDateTime",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchItems?.data ?? {}; const rows = data.value ?? []; return { total: data["@odata.count"] ?? rows.length, items: rows.map((r) => ({ id: r.id, number: r.number, name: r.displayName, type: r.type, unitPrice: r.unitPrice, inventory: r.inventory, blocked: r.blocked })) }; }'},{id:"business-central-list-sales-invoices",name:"List Business Central sales invoices",shortName:"Sales invoices",instruction:"Lists sales invoices from a Business Central company with customer, total and status. Requires a companyId from the companies tool. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company id (GUID) from the companies tool."},filter:{type:"string",description:`Optional OData $filter expression, e.g. "status eq 'Open'".`},maxResults:{type:"integer",description:"Maximum number of invoices to return in one call. Defaults to 100."}},required:["companyId"],additionalProperties:!0},steps:[{id:"fetchSalesInvoices",instruction:"Fetch sales invoices for the given company.",config:{type:"request",systemId:"dynamics365_business_central",url:"https://api.businesscentral.dynamics.com/v2.0/<<dynamics365_business_central_environment>>/api/v2.0/companies(<<companyId>>)/salesInvoices",method:"GET",headers:{Authorization:"Bearer <<dynamics365_business_central_access_token>>",Accept:"application/json","Data-Access-Intent":"ReadOnly"},queryParams:{$select:"id,number,customerName,invoiceDate,totalAmountIncludingTax,currencyCode,status",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchSalesInvoices?.data ?? {}; const rows = data.value ?? []; return { total: data["@odata.count"] ?? rows.length, invoices: rows.map((r) => ({ id: r.id, number: r.number, customer: r.customerName, date: r.invoiceDate, total: r.totalAmountIncludingTax, currency: r.currencyCode, status: r.status })) }; }'},{id:"business-central-list-gl-entries",name:"List Business Central general ledger entries",shortName:"GL entries",instruction:"Lists general ledger entries from a Business Central company with account, amounts and posting date. Requires a companyId from the companies tool. Filter by postingDate to verify opening balances at cutover.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company id (GUID) from the companies tool."},filter:{type:"string",description:'Optional OData $filter expression, e.g. "postingDate ge 2026-01-01".'},maxResults:{type:"integer",description:"Maximum number of entries to return in one call. Defaults to 200."}},required:["companyId"],additionalProperties:!0},steps:[{id:"fetchGLEntries",instruction:"Fetch general ledger entries for the given company.",config:{type:"request",systemId:"dynamics365_business_central",url:"https://api.businesscentral.dynamics.com/v2.0/<<dynamics365_business_central_environment>>/api/v2.0/companies(<<companyId>>)/generalLedgerEntries",method:"GET",headers:{Authorization:"Bearer <<dynamics365_business_central_access_token>>",Accept:"application/json","Data-Access-Intent":"ReadOnly"},queryParams:{$select:"id,entryNumber,postingDate,documentNumber,accountNumber,description,debitAmount,creditAmount",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 200>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchGLEntries?.data ?? {}; const rows = data.value ?? []; return { total: data["@odata.count"] ?? rows.length, entries: rows.map((r) => ({ entryNumber: r.entryNumber, postingDate: r.postingDate, document: r.documentNumber, account: r.accountNumber, description: r.description, debit: r.debitAmount, credit: r.creditAmount })) }; }'},{id:"business-central-query-entity",name:"Query any Business Central entity",shortName:"Query any entity",instruction:"Queries any Business Central entity set by name (for example items, salesInvoices, generalLedgerEntries) within a company, with optional OData $select and $filter. The workhorse tool for migration validation beyond the prebuilt lists.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company id (GUID) from the companies tool."},entitySet:{type:"string",description:'Business Central entity set name, e.g. "items", "salesInvoices", "generalLedgerEntries".'},select:{type:"string",description:"Comma-separated OData $select field list. Omit for all fields."},filter:{type:"string",description:"Optional OData $filter expression."},maxResults:{type:"integer",description:"Maximum number of records to return in one call. Defaults to 100."}},required:["companyId","entitySet"],additionalProperties:!0},steps:[{id:"queryEntity",instruction:"Query the requested entity set for the given company.",config:{type:"request",systemId:"dynamics365_business_central",url:"https://api.businesscentral.dynamics.com/v2.0/<<dynamics365_business_central_environment>>/api/v2.0/companies(<<companyId>>)/<<entitySet>>",method:"GET",headers:{Authorization:"Bearer <<dynamics365_business_central_access_token>>",Accept:"application/json","Data-Access-Intent":"ReadOnly"},queryParams:{$select:"<<select>>",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.queryEntity?.data ?? {}; const rows = data.value ?? []; return { total: data["@odata.count"] ?? rows.length, records: rows }; }'}]},netsuite:{bundleId:"netsuite",templateId:"netsuite",systemId:FA,displayName:"NetSuite",description:"Install a NetSuite system, ten read/query tools, fourteen write tools and a native integration playbook.",systemUrl:"https://{accountId}.suitetalk.api.netsuite.com/services/rest",credentialHint:"Connects through your own NetSuite integration record with OAuth 2.0. Your assistant asks for the account ID and the integration record's client ID and secret, then opens the NetSuite sign-in.",requiredCredentialKeys:["access_token"],oauthSignIn:!0,mcpServer:{name:"netsuite",displayName:"NetSuite",description:"Chart of accounts, customers, vendors, journal entries, invoices, vendor bills, subsidiaries and dimensions from NetSuite, SuiteQL queries and record lookups, plus create and update tools for journal entries, vendors, customers, GL accounts, invoices, vendor bills and departments."},installMcpServer:!1,playbook:{id:"netsuite-native-integration",name:"NetSuite Native Integration",whenToRun:"Use when connecting, validating, querying or extending a NetSuite integration through REST Web Services and SuiteQL.",inputs:"A NetSuite connection with an OAuth sign-in; the record type or business process to work with; subsidiary scope for OneWorld accounts; validation criteria and desired output.",instructions:"Use the installed read-only tools for the chart of accounts, customers, vendors, journal entry lines, invoices, vendor bills, departments, subsidiaries, classes and locations. Use the SuiteQL query tool for any other record type, join or aggregate, and the get-record tool to inspect one record in full. Use the installed create and update tools for journal entries, vendors, customers, GL accounts, invoices, vendor bills and departments only after the user explicitly confirms the exact records to write; the create tools are not idempotent and re-running them duplicates records. Reference other records by internal ID from the list tools, and pass a subsidiary on OneWorld accounts. Surface NetSuite error details (o:errorDetails) as failures. For other record types or operations, inspect the account's metadata catalog, create separate least-privilege tools, validate them in a sandbox account and require explicit user confirmation before modifying NetSuite data.",completionCriteria:"The requested NetSuite data, write result or validation result is returned; subsidiary scope is correct; NetSuite errors are surfaced as failures with their details; no NetSuite data is modified unless the user explicitly requested and confirmed the write."},agentLaunch:{userPrompt:"I just installed the NetSuite integration. What can I do with it?",nextSteps:`Your first reply must be short: one line confirming the NetSuite integration and native integration playbook are installed. If the user already has a NetSuite connection with an OAuth sign-in under this system id, offer one read-only test run and stop. Otherwise connect it in this order. 1) Ask in chat for the NetSuite account ID (Setup > Company > Company Information, like 1234567 or 1234567_SB1 for a sandbox; it is not a secret). 2) Build the host from it in lowercase with "_" replaced by "-" (1234567_SB1 becomes 1234567-sb1). 3) Call connect with this system id, the user's existing NetSuite connection id if one exists, url https://<host>.suitetalk.api.netsuite.com/services/rest, and auth type oauth2 with oauthClientMode custom, authUrl https://<host>.app.netsuite.com/app/login/oauth2/authorize.nl and tokenUrl https://<host>.suitetalk.api.netsuite.com/services/rest/auth/oauth2/v1/token. Confirm no {accountId} remains in url, authUrl, or tokenUrl before calling it. If /org/oauth-apps/ lists an app for this NetSuite account, pass its oauthAppId; otherwise the card collects the client ID and client secret of their NetSuite integration record and then runs the OAuth sign-in. If they have no integration record yet, explain before calling connect: Setup > Integration > Manage Integrations > New, enable Authorization Code Grant with the REST Web Services and RESTlets scopes, set the redirect URI to the superglue OAuth callback URL exactly, and copy the client ID and secret shown once after saving; the NetSuite role needs REST Web Services and Log in using OAuth 2.0 Access Tokens permissions. Once connected, the integration is ready; offer one read-only test run. Do not list the installed tools or add tips unless asked. If asked later: the sign-in lasts seven days and a 401 means signing in again through connect with the connection id; the SuiteQL tool reads any record type; the installed create and update tools modify NetSuite data, so run them only after the user confirms the exact records to write.`},tools:Nhe}};Vo.bundles={...cw,sage_intacct_mcp:{...cw.sage_intacct,bundleId:"sage_intacct_mcp",description:"Install the Sage Intacct integration and an OAuth-protected MCP server for its read/query and write tools.",installMcpServer:!0},netsuite_mcp:{...cw.netsuite,bundleId:"netsuite_mcp",description:"Install the NetSuite integration and an OAuth-protected MCP server for its read/query and write tools.",installMcpServer:!0}};function Ohe({bundle:t,install:e}){let r=e.tools.map(s=>` - ${s.id}${s.name?` (${s.name})`:""}`).join(`
|
|
115
115
|
`),n=e.system.requiredCredentialKeys.join(", "),i=e.mcpServer?[` - MCP server: ${e.mcpServer.name} (id: ${e.mcpServer.id})`,"","Silently load the connections and tool-deployment skills before replying. Do not narrate the skill loads.","","The MCP server card is already visible in this conversation with the server URL, its tools, and the client export options for Claude, Cursor, Langdock and curl. Do not describe or reproduce client setup in prose; point at the card."]:["","Silently load the connections skill before replying. Do not narrate the skill load."],o=[`The user just installed the "${t.displayName}" ${e.mcpServer?"MCP server and integration":"integration"} from the superglue website. Everything below already exists. Do not create, rebuild or duplicate any of it.`,"","Installed:",` - System ID: ${e.system.id} (${e.system.name}) at ${t.systemUrl}`," - Tools:",r,e.playbook?` - Playbook: ${e.playbook.name} (id: ${e.playbook.id})`:void 0,...i,"",e.system.hasUserCredentials?t.demoCredentials?"The connection is preloaded with shared demo secrets, so every tool works right now without any setup.":"The user already has a connection with every required secret.":`The user has no connection with every required secret yet, so no tool will run until the user adds the missing values. Required secret names: ${n}. ${t.credentialHint}`,t.agentLaunch.nextSteps,"","The user already saw this inventory on the install screen. Do not repeat it back to them."];return{userPrompt:t.agentLaunch.userPrompt,hiddenStarterMessage:o.filter(s=>s!==void 0).join(`
|
|
116
116
|
`)}}function xhe(t){return typeof t!="string"||!Object.prototype.hasOwnProperty.call(Vo.bundles,t)?null:Vo.bundles[t]}function Uhe(){return Object.values(Vo.bundles)}});var PL=y(Um=>{"use strict";Object.defineProperty(Um,"__esModule",{value:!0});Um.chatVisualArtifactTitle=ML;Um.chatVisualToArtifactHtml=Ghe;var bn=pg(),OL=120,Mhe={stats:"Key numbers",chart:"Chart",flow:"Flow",steps:"Steps",table:"Table",mapping:"Field mapping",migration:"Migration status",reconcile:"Reconciliation",timeline:"Timeline",cards:"Overview",diagram:"Diagram",image:"Images",callout:"Note",custom:"Visual",lesson:"Lesson"},Phe={success:"sg-success",failed:"sg-error",warning:"sg-warning",running:"sg-info"},Lhe={positive:"sg-success",negative:"sg-error",warning:"sg-warning",neutral:""},$he={info:"",success:"sg-success",warning:"sg-warning",error:"sg-error"},Fhe=["main{max-width:960px;margin:0 auto;padding:32px 24px}","h1{margin:0 0 6px}","h2{margin:28px 0 10px}",".sg-visual-caption{margin:0 0 24px}",".sg-visual-body{overflow-wrap:break-word}",".sg-visual-body pre{white-space:pre-wrap;background:var(--sg-surface);border:1px solid var(--sg-line);border-radius:var(--sg-radius);padding:12px 14px}",".sg-card h3{margin:0 0 4px;font-size:1rem}",".sg-card p{margin:4px 0 0}"].join("");function ge(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Nm(t){return ge(t).replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>").replace(/(^|[^*\w])\*([^*\s][^*]*)\*/g,"$1<em>$2</em>").replace(/\[([^\]]+)\]\((https:\/\/[^\s)]+)\)/g,'<a href="$2">$1</a>')}function xm(t){return t.trim().split(/\n\s*\n/).map(e=>{let r=e.split(`
|
|
@@ -787,9 +787,9 @@ window.addEventListener("load",schedule);
|
|
|
787
787
|
renderState();
|
|
788
788
|
renderSubmissionState("idle");
|
|
789
789
|
post("ready", {});
|
|
790
|
-
})();`});var Zo=y(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.findXmlTagEnd=zA;Jo.parseXmlDocument=t$;Jo.streamXmlElements=Yfe;Jo.xmlChild=r$;Jo.xmlChildren=Pm;Jo.xmlPath=Vfe;Jo.xmlText=n$;Jo.officeDocumentFormat=Wfe;var qfe={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"},Hfe={"http://schemas.openxmlformats.org/spreadsheetml/2006/main":"","http://purl.oclc.org/ooxml/spreadsheetml/main":"","http://schemas.openxmlformats.org/package/2006/relationships":"","http://schemas.openxmlformats.org/wordprocessingml/2006/main":"w","http://purl.oclc.org/ooxml/wordprocessingml/main":"w","http://schemas.openxmlformats.org/drawingml/2006/main":"a","http://purl.oclc.org/ooxml/drawingml/main":"a","http://schemas.openxmlformats.org/presentationml/2006/main":"p","http://purl.oclc.org/ooxml/presentationml/main":"p","http://schemas.openxmlformats.org/officeDocument/2006/relationships":"r","http://purl.oclc.org/ooxml/officeDocument/relationships":"r","http://schemas.openxmlformats.org/drawingml/2006/chart":"c","http://purl.oclc.org/ooxml/drawingml/chart":"c","http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing":"xdr","http://purl.oclc.org/ooxml/drawingml/spreadsheetDrawing":"xdr","http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing":"wp","http://purl.oclc.org/ooxml/drawingml/wordprocessingDrawing":"wp","http://schemas.openxmlformats.org/drawingml/2006/picture":"pic","http://purl.oclc.org/ooxml/drawingml/picture":"pic","http://schemas.openxmlformats.org/drawingml/2006/diagram":"dgm","http://schemas.openxmlformats.org/markup-compatibility/2006":"mc","urn:schemas-microsoft-com:vml":"v"};function mw(t,e,r){let n=t.indexOf(":"),i=n===-1?"":t.slice(0,n);if(i==="xml"||i==="xmlns"||t==="xmlns"||!r&&n===-1)return t;let o=e.get(i),s=o===void 0?void 0:Hfe[o];if(s===void 0)return t;let a=n===-1?t:t.slice(n+1);return s?`${s}:${a}`:a}function e$(t){return t.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi,(e,r)=>{if(r[0]!=="#")return qfe[r]??e;let n=r[1]==="x"||r[1]==="X"?parseInt(r.slice(2),16):Number(r.slice(1));return Number.isInteger(n)&&n>=0&&n<=1114111?String.fromCodePoint(n):e})}function Gfe(t){let e={};for(let r of t.matchAll(/([^\s=/]+)\s*=\s*("([^"]*)"|'([^']*)')/g))e[r[1]]=e$(r[3]??r[4]??"");return e}function zA(t,e){let r=null;for(let n=e;n<t.length;n+=1){let i=t[n];if(r)i===r&&(r=null);else if(i==='"'||i==="'")r=i;else if(i===">")return n}return-1}function t$(t){let e={type:"element",name:"#document",attributes:{},children:[]},r=[e],n=[new Map],i=0;for(;i<t.length;){let o=r[r.length-1],s=t.indexOf("<",i),a=s===-1?t.length:s;if(a>i&&o.children.push({type:"text",text:e$(t.slice(i,a))}),s===-1)break;if(t.startsWith("<!--",s)){let f=t.indexOf("-->",s+4);i=f===-1?t.length:f+3;continue}if(t.startsWith("<![CDATA[",s)){let f=t.indexOf("]]>",s+9);o.children.push({type:"text",text:t.slice(s+9,f===-1?t.length:f)}),i=f===-1?t.length:f+3;continue}if(t[s+1]==="?"||t[s+1]==="!"){let f=t.indexOf(">",s);i=f===-1?t.length:f+1;continue}let c=zA(t,s+1);if(c===-1)throw new Error("Malformed XML: unterminated tag");if(t[s+1]==="/"){let f=mw(t.slice(s+2,c).trim(),n[n.length-1],!0),E=r.map(S=>S.name).lastIndexOf(f);if(E<=0)throw new Error(`Malformed XML: unexpected </${f}>`);r.length=E,n.length=E,i=c+1;continue}let l=t[c-1]==="/",u=t.slice(s+1,l?c-1:c),d=/^[^\s/>]+/.exec(u);if(!d)throw new Error("Malformed XML: missing tag name");let A=Gfe(u.slice(d[0].length)),p=new Map(n[n.length-1]);for(let[f,E]of Object.entries(A))f==="xmlns"?p.set("",E):f.startsWith("xmlns:")&&p.set(f.slice(6),E);let h={type:"element",name:mw(d[0],p,!0),attributes:Object.fromEntries(Object.entries(A).map(([f,E])=>[mw(f,p,!1),E])),children:[]};o.children.push(h),l||(r.push(h),n.push(p)),i=c+1}return e}function yw(t){return Pm(t$(t))[0]}function Yfe({xml:t,container:e,element:r}){let n=new RegExp(`<([\\w.-]+:)?${e}(?=[\\s/>])`).exec(t),i=n?zA(t,n.index+1):-1,o=/<(?![?!])([^\s/>]+)/.exec(t);if(!n||!o||i===-1||t[i-1]==="/")return{root:yw(t),elements:function*(){}};let s=n[1]??"",a=`</${s}${e}>`,c=t.indexOf(a,i);if(c===-1)throw new Error(`Malformed XML: unterminated <${e}>`);let l=o.index===n.index,u=zA(t,o.index+1),d=l?t.slice(n.index,i+1):`${t.slice(o.index,u+1)}${t.slice(n.index,i+1)}`,A=l?a:`${a}</${o[1]}>`,p=`<${s}${r}`,h=`</${s}${r}>`;return{root:yw(t.slice(0,i+1)+t.slice(c)),*elements(){let f=i+1;for(;;){let E=t.indexOf(p,f);if(E===-1||E>=c)return;let S=t[E+p.length];if(S!==">"&&S!=="/"&&!/\s/.test(S)){f=E+p.length;continue}let B=zA(t,E+1);if(B===-1)throw new Error(`Malformed XML: unterminated <${r}>`);let _=t[B-1]==="/"?B+1:t.indexOf(h,B);if(_===-1)throw new Error(`Malformed XML: unterminated <${r}>`);let v=t[B-1]==="/"?_:_+h.length,T=yw(d+t.slice(E,v)+A),L=Pm(l?T:Pm(T)[0])[0];L&&(yield L),f=v}}}}function r$(t,e){return t?.children.find(r=>r.type==="element"&&r.name===e)}function Pm(t,e){return t?t.children.filter(r=>r.type==="element"&&(e===void 0||r.name===e)):[]}function Vfe(t,...e){return e.reduce((r,n)=>r$(r,n),t)}function n$(t){return t.children.map(e=>e.type==="text"?e.text:n$(e)).join("")}function Wfe(t){let e=t.toLowerCase().match(/\.([a-z0-9]+)$/)?.[1];return e==="docx"||e==="pptx"?e:null}});var Ts=y(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.OfficePackage=Zt.escAttr=Zt.esc=void 0;Zt.attr=Xr;Zt.numberAttr=o$;Zt.isOn=Kfe;Zt.readOfficeTheme=ege;Zt.tintedColor=tge;Zt.drawingColor=rge;Zt.fontStack=nge;Zt.styleAttribute=ige;Zt.officeHtmlDocument=oge;var i$=du(),Ur=Zo(),Jfe={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",svg:"image/svg+xml",webp:"image/webp"},Zfe={black:"000000",white:"FFFFFF",red:"FF0000",green:"008000",blue:"0000FF",yellow:"FFFF00",gray:"808080",grey:"808080",darkGray:"A9A9A9",lightGray:"D3D3D3"};Zt.esc=i$.escapeText;Zt.escAttr=i$.escapeAttribute;function Xr(t,e){return t?.attributes[e]}function o$(t,e){let r=t?.attributes[e];if(r===void 0)return;let n=Number(r);return Number.isFinite(n)?n:void 0}function Kfe(t){if(!t)return!1;let e=t.attributes["w:val"]??t.attributes.val;return e===void 0||!["0","false","off","none"].includes(e)}var Ew=class{constructor(e){this.zip=e,this.images=new Map,this.xml=new Map,this.relationships=new Map}readXml(e){let r=this.xml.get(e);if(r)return r;let n=(async()=>{let i=this.zip.file(e);if(!i)return;let o=(0,Ur.parseXmlDocument)(await i.async("string"));return(0,Ur.xmlChildren)(o)[0]})();return this.xml.set(e,n),n}async readText(e){return this.zip.file(e)?.async("string")}rels(e){let r=this.relationships.get(e);if(r)return r;let n=(async()=>{let i=e.slice(0,e.lastIndexOf("/")+1),o=e.slice(e.lastIndexOf("/")+1),s=await this.readXml(`${i}_rels/${o}.rels`),a=new Map;for(let c of(0,Ur.xmlChildren)(s,"Relationship")){let l=Xr(c,"Id"),u=Xr(c,"Target");if(!l||!u)continue;let d=Xr(c,"TargetMode")==="External";a.set(l,{type:Xr(c,"Type")??"",target:d?u:Xfe(i,u),external:d})}return a})();return this.relationships.set(e,n),n}async relatedPart(e,r){for(let n of(await this.rels(e)).values())if(!n.external&&n.type.endsWith(r))return n.target}image(e){let r=this.images.get(e);if(r)return r;let n=e.toLowerCase().match(/\.([a-z0-9]+)$/)?.[1]??"",i=Jfe[n],o=this.zip.file(e),s=i&&o?o.async("base64").then(a=>`data:${i};base64,${a}`):Promise.resolve(void 0);return this.images.set(e,s),s}async relatedPartById(e,r){if(!r)return;let n=(await this.rels(e)).get(r);return n&&!n.external?n.target:void 0}async relatedImage(e,r){let n=await this.relatedPartById(e,r);return n?this.image(n):void 0}};Zt.OfficePackage=Ew;function Xfe(t,e){let r=(e.startsWith("/")?e.slice(1):t+e).split("/"),n=[];for(let i of r)i===".."?n.pop():i&&i!=="."&&n.push(i);return n.join("/")}async function ege(t,e){let r=e?await t.readXml(e):void 0,n=(0,Ur.xmlChild)(r,"a:themeElements"),i=(0,Ur.xmlChild)(n,"a:clrScheme"),o={};for(let a of(0,Ur.xmlChildren)(i)){let c=(0,Ur.xmlChild)(a,"a:srgbClr")??(0,Ur.xmlChild)(a,"a:sysClr"),l=Xr(c,"lastClr")??Xr(c,"val");l&&(o[a.name.replace(/^a:/,"")]=l)}let s=(0,Ur.xmlChild)(n,"a:fontScheme");return{colors:o,majorFont:Xr((0,Ur.xmlChild)((0,Ur.xmlChild)(s,"a:majorFont"),"a:latin"),"typeface")??"",minorFont:Xr((0,Ur.xmlChild)((0,Ur.xmlChild)(s,"a:minorFont"),"a:latin"),"typeface")??""}}function s$(t){let e=parseInt(t.padStart(6,"0").slice(0,6),16);return[e>>16&255,e>>8&255,e&255]}function a$([t,e,r]){let n=t/255,i=e/255,o=r/255,s=Math.max(n,i,o),a=Math.min(n,i,o),c=(s+a)/2;if(s===a)return[0,0,c];let l=s-a,u=c>.5?l/(2-s-a):l/(s+a);return[(s===n?(i-o)/l+(i<o?6:0):s===i?(o-n)/l+2:(n-i)/l+4)/6,u,c]}function c$([t,e,r]){if(e===0){let s=Math.round(r*255);return[s,s,s]}let n=r<.5?r*(1+e):r+e-r*e,i=2*r-n,o=s=>{let a=t+s;return a<0&&(a+=1),a>1&&(a-=1),a<1/6?i+(n-i)*6*a:a<1/2?n:a<2/3?i+(n-i)*(2/3-a)*6:i};return[o(1/3),o(0),o(-1/3)].map(s=>Math.round(s*255))}function tge(t,e){let r=a$(s$(t));return r[2]=e<0?r[2]*(1+e):r[2]*(1-e)+e,`#${c$(r).map(n=>n.toString(16).padStart(2,"0")).join("")}`}function rge({element:t,theme:e,colorMap:r,placeholderColor:n}){let i=t?(0,Ur.xmlChildren)(t)[0]:void 0;if(!i)return;let o;if(i.name==="a:srgbClr")o=Xr(i,"val");else if(i.name==="a:sysClr")o=Xr(i,"lastClr")??Xr(i,"val");else if(i.name==="a:prstClr")o=Zfe[Xr(i,"val")??""];else if(i.name==="a:schemeClr"){let c=Xr(i,"val")??"";c==="phClr"?o=n:o=e.colors[r?.[c]??c]??e.colors[c]}if(!o||!/^[0-9a-f]{6}$/i.test(o))return;let s=s$(o),a=1;for(let c of(0,Ur.xmlChildren)(i)){let l=(o$(c,"val")??0)/1e5;if(c.name==="a:lumMod"||c.name==="a:lumOff"){let u=a$(s);u[2]=c.name==="a:lumMod"?u[2]*l:u[2]+l,u[2]=Math.min(1,Math.max(0,u[2])),s=c$(u)}else c.name==="a:tint"?s=s.map(u=>Math.round(255-(255-u)*l)):c.name==="a:shade"?s=s.map(u=>Math.round(u*l)):c.name==="a:alpha"&&(a=l)}return a<1?`rgba(${s.join(",")},${Math.round(a*1e3)/1e3})`:`#${s.map(c=>c.toString(16).padStart(2,"0")).join("")}`}function nge(t){let e=t?.replace(/["\\<>;{}\u0000-\u001f\u007f]/g,"");return e?`"${e}", Calibri, Arial, sans-serif`:""}function ige(t){let e=Object.entries(t).filter(([,r])=>r!==void 0&&r!=="").map(([r,n])=>`${r}:${n}`).join(";");return e?` style="${(0,Zt.escAttr)(e)}"`:""}function oge({title:t,css:e,body:r}){let n=["default-src 'none'","script-src 'none'","style-src 'unsafe-inline'","img-src data:","font-src data:","connect-src 'none'","base-uri 'none'","form-action 'none'"].join("; ");return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="referrer" content="no-referrer"><meta http-equiv="Content-Security-Policy" content="${(0,Zt.escAttr)(n)}"><title>${(0,Zt.esc)(t)}</title><style>${e}</style></head><body>${r}</body></html>`}});var Dc=y(Lm=>{"use strict";Object.defineProperty(Lm,"__esModule",{value:!0});Lm.readChartData=Age;Lm.renderChartSvg=pge;var ki=Ts(),je=Zo(),l$={"c:barChart":"column","c:bar3DChart":"column","c:lineChart":"line","c:line3DChart":"line","c:areaChart":"area","c:area3DChart":"area","c:pieChart":"pie","c:pie3DChart":"pie","c:doughnutChart":"doughnut"},u$=["accent1","accent2","accent3","accent4","accent5","accent6"],Ia=1e3,d$=1048576,sge="#595959",A$="#d9d9d9";function Tc(t){let e=(0,je.xmlPath)(t,"c:strRef","c:strCache")??(0,je.xmlPath)(t,"c:numRef","c:numCache")??(0,je.xmlChild)(t,"c:strLit")??(0,je.xmlChild)(t,"c:numLit")??(0,je.xmlPath)(t,"c:multiLvlStrRef","c:multiLvlStrCache","c:lvl"),r=(0,je.xmlChildren)(e,"c:pt").map((s,a)=>({point:s,index:Number(s.attributes.idx??a)})).filter(({index:s})=>Number.isInteger(s)&&s>=0&&s<d$),n=Number((0,je.xmlChild)(e,"c:ptCount")?.attributes.val??d$),i=r.filter(({index:s})=>s<n),o=Array(i.reduce((s,{index:a})=>Math.max(s,a+1),0)).fill("");for(let{point:s,index:a}of i){let c=(0,je.xmlChild)(s,"c:v");o[a]=c?(0,je.xmlText)(c):""}return o}function age(t){if(t<=0)return 1;let e=10**Math.floor(Math.log10(t));return([1,2,2.5,5,10].find(n=>n*e>=t)??10)*e}function cge(t){return Math.abs(t)>=1e6?`${Math.round(t/1e5)/10}M`:Math.abs(t)>=1e4?`${Math.round(t/100)/10}K`:String(Math.round(t*100)/100)}function Au({x:t,y:e,value:r,size:n,anchor:i="middle",weight:o="400"}){return`<text x="${t}" y="${e}" font-size="${n}" font-weight="${o}" text-anchor="${i}" fill="${sge}">${(0,ki.esc)(r)}</text>`}function lge(t,e){let r=Math.min(220,Ia/Math.max(t.length,1)),n=Ia/2-r*t.length/2;return t.map((i,o)=>{let s=n+o*r;return`<rect x="${s}" y="${e-14}" width="16" height="16" fill="${(0,ki.escAttr)(i.color)}"/>${Au({x:s+24,y:e,value:i.name,size:20,anchor:"start"})}`}).join("")}function uge({kind:t,series:e,stacked:r,percent:n,height:i,top:o,bottom:s}){let a=e[0].categories,c=Math.max(a.length,...e.map(k=>k.values.length)),l=Array.from({length:c},(k,P)=>e.reduce((U,K)=>U+Math.max(K.values[P]??0,0),0)),u=n?100:age((r?l:e.flatMap(k=>k.values)).reduce((k,P)=>Math.max(k,P),-1/0)),d=90,A=Ia-30,p=o,h=i-s,f=t==="bar",E=f?A-d:h-p,S=f?h-p:A-d,B=k=>k/u*E,_=S/Math.max(c,1),v="";for(let k=0;k<=4;k+=1){let P=u/4*k,U=B(P),K=n?`${P}%`:cge(P);v+=f?`<line x1="${d+U}" y1="${p}" x2="${d+U}" y2="${h}" stroke="${A$}"/>${Au({x:d+U,y:h+26,value:K,size:18})}`:`<line x1="${d}" y1="${h-U}" x2="${A}" y2="${h-U}" stroke="${A$}"/>${Au({x:d-10,y:h-U+6,value:K,size:18,anchor:"end"})}`}for(let k=0;k<c;k+=1){let P=a[k]??String(k+1);v+=Au(f?{x:d-10,y:p+_*(k+.5)+6,value:P,size:18,anchor:"end"}:{x:d+_*(k+.5),y:h+26,value:P,size:18})}if(t==="line"||t==="area"){for(let k of e){let P=k.values.map((U,K)=>`${d+_*(K+.5)},${h-B(U)}`);v+=t==="area"?`<polygon points="${d+_*.5},${h} ${P.join(" ")} ${d+_*(k.values.length-.5)},${h}" fill="${(0,ki.escAttr)(k.color)}" fill-opacity="0.6"/>`:`<polyline points="${P.join(" ")}" fill="none" stroke="${(0,ki.escAttr)(k.color)}" stroke-width="4"/>`}return v}let T=_*.7,L=r?T:T/e.length;for(let k=0;k<c;k+=1){let P=0;e.forEach((U,K)=>{let Ae=Math.max(U.values[k]??0,0),Re=n&&l[k]?Ae/l[k]*100:Ae,Ge=B(Re),tt=_*k+(_-T)/2+(r?0:L*K);v+=f?`<rect x="${d+P}" y="${p+tt}" width="${Ge}" height="${L}" fill="${(0,ki.escAttr)(U.color)}"/>`:`<rect x="${d+tt}" y="${h-P-Ge}" width="${L}" height="${Ge}" fill="${(0,ki.escAttr)(U.color)}"/>`,r&&(P+=Ge)})}return v}function dge({series:t,doughnut:e,height:r,top:n,bottom:i}){let o=t.values.reduce((d,A)=>d+Math.max(A,0),0);if(o<=0)return"";let s=Math.min(Ia,r-n-i)/2-10,a=Ia/2,c=n+(r-n-i)/2,l=-Math.PI/2,u="";return t.values.forEach((d,A)=>{let p=Math.max(d,0)/o*Math.PI*2,h=l+p,f=p>Math.PI?1:0,E=a+s*Math.cos(l),S=c+s*Math.sin(l),B=a+s*Math.cos(h),_=c+s*Math.sin(h);u+=p>=Math.PI*2-1e-4?`<circle cx="${a}" cy="${c}" r="${s}" fill="${(0,ki.escAttr)(Iw(t,A))}"/>`:`<path d="M${a},${c} L${E},${S} A${s},${s} 0 ${f} 1 ${B},${_} Z" fill="${(0,ki.escAttr)(Iw(t,A))}" stroke="#fff" stroke-width="2"/>`,l=h}),e&&(u+=`<circle cx="${a}" cy="${c}" r="${s*.5}" fill="#fff"/>`),u}var p$=["#4472c4","#ed7d31","#a5a5a5","#ffc000","#5b9bd5","#70ad47"];function Iw(t,e){return t.pointColors[e]}function h$(t){return(0,je.xmlPath)(t,"c:spPr","a:solidFill")??(0,je.xmlPath)(t,"c:spPr","a:ln","a:solidFill")}function f$({index:t,theme:e,colorMap:r}){let n={type:"element",name:"a:solidFill",attributes:{},children:[{type:"element",name:"a:schemeClr",attributes:{val:u$[t%u$.length]},children:[]}]};return(0,ki.drawingColor)({element:n,theme:e,colorMap:r})??p$[t%p$.length]}function g$(t){let e=(0,je.xmlChild)(t,"c:title");return e?(0,je.xmlChildren)((0,je.xmlPath)(e,"c:tx","c:rich"),"a:p").map(r=>(0,je.xmlText)(r)).join(" ").trim():""}function Age(t){let e=(0,je.xmlChild)(t,"c:chart"),r=(0,je.xmlChild)(e,"c:plotArea");if(!r)return;let n=(0,je.xmlChildren)(r).filter(i=>i.name.startsWith("c:")&&i.name.endsWith("Chart")).flatMap(i=>(0,je.xmlChildren)(i,"c:ser")).map((i,o)=>({name:Tc((0,je.xmlChild)(i,"c:tx")).join(" ")||`Series ${o+1}`,categories:Tc((0,je.xmlChild)(i,"c:cat")??(0,je.xmlChild)(i,"c:xVal")),values:Tc((0,je.xmlChild)(i,"c:val")??(0,je.xmlChild)(i,"c:yVal"))}));return{title:g$(e),series:n}}function pge({root:t,theme:e,colorMap:r,aspect:n}){let i=(0,je.xmlChild)(t,"c:chart"),o=(0,je.xmlChild)(i,"c:plotArea"),s=(0,je.xmlChildren)(o).find(v=>l$[v.name]);if(!s)return;let c=(0,je.xmlChild)(s,"c:barDir")?.attributes.val==="bar"?"bar":l$[s.name],l=(0,je.xmlChild)(s,"c:grouping")?.attributes.val??"clustered",u=(0,je.xmlChildren)(s,"c:ser").map((v,T)=>{let L=Tc((0,je.xmlChild)(v,"c:val")).map(P=>Number(P)||0),k=new Map((0,je.xmlChildren)(v,"c:dPt").map(P=>[Number((0,je.xmlChild)(P,"c:idx")?.attributes.val??-1),(0,ki.drawingColor)({element:h$(P),theme:e,colorMap:r})]));return{name:Tc((0,je.xmlChild)(v,"c:tx")).join(" ")||`Series ${T+1}`,categories:Tc((0,je.xmlChild)(v,"c:cat")),values:L,color:(0,ki.drawingColor)({element:h$(v),theme:e,colorMap:r})??f$({index:T,theme:e,colorMap:r}),pointColors:Array.from({length:Math.max(L.length,Tc((0,je.xmlChild)(v,"c:cat")).length)},(P,U)=>k.get(U)??f$({index:U,theme:e,colorMap:r}))}});if(u.length===0)return;let d=Math.round(Ia*n),A=g$(i),p=!A&&(0,je.xmlChild)(i,"c:autoTitleDeleted")?.attributes.val!=="1"&&u.length===1?u[0].name:"",h=A||p,f=c==="pie"||c==="doughnut",E=f?u[0].categories.map((v,T)=>({name:v,color:Iw(u[0],T)})):u.length>1?u.map(({name:v,color:T})=>({name:v,color:T})):[],S=h?60:20,B=(E.length>0?50:0)+(f?10:40),_=f?dge({series:u[0],doughnut:c==="doughnut",height:d,top:S,bottom:B}):uge({kind:c,series:u,stacked:l==="stacked"||l==="percentStacked",percent:l==="percentStacked",height:d,top:S,bottom:B});return`<svg viewBox="0 0 ${Ia} ${d}" preserveAspectRatio="xMidYMid meet" font-family="Calibri, Arial, sans-serif" style="width:100%;height:100%">${h?Au({x:Ia/2,y:38,value:h,size:28,weight:"600"}):""}${_}${E.length>0?lge(E,d-18):""}</svg>`}});var I$=y(ww=>{"use strict";Object.defineProperty(ww,"__esModule",{value:!0});ww.renderDocx=Ege;var le=Zo(),z=Ts(),hge=Dc(),$m="word/document.xml",bw="<!--sg-page-break-->",m$=12700,fge={yellow:"#ffff00",green:"#00ff00",cyan:"#00ffff",magenta:"#ff00ff",blue:"#0000ff",red:"#ff0000",darkBlue:"#000080",darkCyan:"#008080",darkGreen:"#008000",darkMagenta:"#800080",darkRed:"#800000",darkYellow:"#808000",darkGray:"#808080",lightGray:"#c0c0c0",black:"#000000",white:"#ffffff"},gge={"\uF0B7":"\u2022","\uF0A7":"\u25AA","\uF0D8":"\u27A2","\uF0FC":"\u2713","\uF076":"\u2756","\uF06E":"\u25A0","\uF06C":"\u25CF","\uF071":"\u2751",o:"\u25E6"},mge={left:"left",start:"left",center:"center",right:"right",end:"right",both:"justify",distribute:"justify"};function qA(t){let e=new Map;for(let r of t)for(let n of r instanceof Map?r.values():(0,le.xmlChildren)(r)){let i=e.get(n.name);e.set(n.name,i?{...n,attributes:{...i.attributes,...n.attributes}}:n)}return e}function HA(t,e){for(let r of(0,le.xmlChildren)(t)){if(r.name===e)return r;let n=HA(r,e);if(n)return n}}function pu(t,e){let r=(0,z.attr)(t,"w:val");if(!t||!r)return;if(r==="nil"||r==="none")return"none";let n=Math.max(((0,z.numberAttr)(t,"w:sz")??4)/8,.5),i=(0,z.attr)(t,"w:color"),o=r==="double"?"double":r.includes("dash")?"dashed":r==="dotted"?"dotted":"solid",s=i&&/^[0-9a-f]{6}$/i.test(i)?`#${i}`:"#000";return`max(1px, ${e(n)}) ${o} ${s}`}function Cw(t){let e=(0,z.attr)(t,"w:fill");return e&&e!=="auto"&&/^[0-9a-f]{6}$/i.test(e)?`#${e}`:void 0}function y$(t){let e=[[1e3,"m"],[900,"cm"],[500,"d"],[400,"cd"],[100,"c"],[90,"xc"],[50,"l"],[40,"xl"],[10,"x"],[9,"ix"],[5,"v"],[4,"iv"],[1,"i"]],r=t,n="";for(let[i,o]of e)for(;r>=i;)n+=o,r-=i;return n}function E$(t){return String.fromCharCode(97+(t-1)%26).repeat(Math.floor((t-1)/26)+1)}function yge(t,e){return e==="lowerLetter"?E$(t):e==="upperLetter"?E$(t).toUpperCase():e==="lowerRoman"?y$(t):e==="upperRoman"?y$(t).toUpperCase():e==="decimalZero"?String(t).padStart(2,"0"):e==="none"?"":String(t)}var Sw=class{constructor(e,r,n,i){this.officePackage=e,this.theme=r,this.page=n,this.part=i,this.styles=new Map,this.abstractNumbering=new Map,this.numbering=new Map,this.counters=new Map,this.pt=o=>`${Math.round(o/this.page.width*1e6)/1e4}cqw`}twips(e){return e===void 0?void 0:this.pt(e/20)}loadStyles(e){let r=(0,le.xmlChild)(e,"w:docDefaults");this.defaultRunProps=(0,le.xmlChild)((0,le.xmlChild)(r,"w:rPrDefault"),"w:rPr"),this.defaultParagraphProps=(0,le.xmlChild)((0,le.xmlChild)(r,"w:pPrDefault"),"w:pPr");for(let n of(0,le.xmlChildren)(e,"w:style")){let i=(0,z.attr)(n,"w:styleId");if(!i)continue;let o=["1","true"].includes((0,z.attr)(n,"w:default")??"");(0,z.attr)(n,"w:type")==="paragraph"&&o&&(this.defaultParagraphStyle=i);let s=(0,z.attr)((0,le.xmlChild)(n,"w:basedOn"),"w:val");this.styles.set(i,{...s?{basedOn:s}:{},...(0,le.xmlChild)(n,"w:pPr")?{pPr:(0,le.xmlChild)(n,"w:pPr")}:{},...(0,le.xmlChild)(n,"w:rPr")?{rPr:(0,le.xmlChild)(n,"w:rPr")}:{},...(0,le.xmlChild)(n,"w:tblPr")?{tblPr:(0,le.xmlChild)(n,"w:tblPr")}:{}})}}loadNumbering(e){for(let r of(0,le.xmlChildren)(e,"w:abstractNum")){let n=new Map;for(let o of(0,le.xmlChildren)(r,"w:lvl"))n.set((0,z.numberAttr)(o,"w:ilvl")??0,{format:(0,z.attr)((0,le.xmlChild)(o,"w:numFmt"),"w:val")??"decimal",text:(0,z.attr)((0,le.xmlChild)(o,"w:lvlText"),"w:val")??"",start:(0,z.numberAttr)((0,le.xmlChild)(o,"w:start"),"w:val")??1,...(0,le.xmlChild)(o,"w:pPr")?{pPr:(0,le.xmlChild)(o,"w:pPr")}:{},...(0,le.xmlChild)(o,"w:rPr")?{rPr:(0,le.xmlChild)(o,"w:rPr")}:{}});let i=(0,z.attr)(r,"w:abstractNumId");i&&this.abstractNumbering.set(i,n)}for(let r of(0,le.xmlChildren)(e,"w:num")){let n=(0,z.attr)(r,"w:numId"),i=(0,z.attr)((0,le.xmlChild)(r,"w:abstractNumId"),"w:val");if(!n||!i)continue;let o=new Map;for(let s of(0,le.xmlChildren)(r,"w:lvlOverride")){let a=(0,z.numberAttr)((0,le.xmlChild)(s,"w:startOverride"),"w:val");a!==void 0&&o.set((0,z.numberAttr)(s,"w:ilvl")??0,a)}this.numbering.set(n,{abstractId:i,overrides:o})}}styleChain(e){let r=[],n=new Set,i=e;for(;i&&!n.has(i);){n.add(i);let o=this.styles.get(i);if(!o)break;r.unshift(o),i=o.basedOn}return r}paragraphStyleId(e){return(0,z.attr)((0,le.xmlChild)(e,"w:pStyle"),"w:val")??this.defaultParagraphStyle}runProps(e,r){let n=this.styleChain(this.paragraphStyleId(e)),i=this.styleChain((0,z.attr)((0,le.xmlChild)(r,"w:rStyle"),"w:val"));return qA([this.defaultRunProps,...n.map(o=>o.rPr),...i.map(o=>o.rPr),r])}fontFamily(e){let r=e.get("w:rFonts"),n=(0,z.attr)(r,"w:ascii")??(0,z.attr)(r,"w:hAnsi");if(n)return(0,z.fontStack)(n);let i=(0,z.attr)(r,"w:asciiTheme")??(0,z.attr)(r,"w:hAnsiTheme");if(i)return(0,z.fontStack)(i.startsWith("major")?this.theme.majorFont:this.theme.minorFont)}runCss(e){let r=[e.has("w:u")&&(0,z.attr)(e.get("w:u"),"w:val")!=="none"?"underline":"",(0,z.isOn)(e.get("w:strike"))||(0,z.isOn)(e.get("w:dstrike"))?"line-through":""].filter(Boolean),n=(0,z.numberAttr)(e.get("w:sz"),"w:val"),i=(0,z.attr)(e.get("w:color"),"w:val"),o=(0,z.attr)(e.get("w:vertAlign"),"w:val"),s=(0,z.attr)(e.get("w:highlight"),"w:val"),a=(0,z.numberAttr)(e.get("w:spacing"),"w:val");return{"font-weight":e.has("w:b")?(0,z.isOn)(e.get("w:b"))?"700":"400":void 0,"font-style":e.has("w:i")?(0,z.isOn)(e.get("w:i"))?"italic":"normal":void 0,"text-decoration":r.length>0?r.join(" "):void 0,color:i&&i!=="auto"&&/^[0-9a-f]{6}$/i.test(i)?`#${i}`:void 0,"font-size":n!==void 0?this.pt(n/2*(o==="superscript"||o==="subscript"?.65:1)):void 0,"font-family":this.fontFamily(e),background:(s?fge[s]:void 0)??Cw(e.get("w:shd")),"vertical-align":o==="superscript"?"super":o==="subscript"?"sub":void 0,"text-transform":(0,z.isOn)(e.get("w:caps"))?"uppercase":void 0,"font-variant":(0,z.isOn)(e.get("w:smallCaps"))?"small-caps":void 0,"letter-spacing":a?this.twips(a):void 0,display:(0,z.isOn)(e.get("w:vanish"))?"none":void 0}}numberingLevel(e){let r=e.get("w:numPr"),n=(0,z.attr)((0,le.xmlChild)(r,"w:numId"),"w:val");if(!n||n==="0")return;let i=this.numbering.get(n),o=i?this.abstractNumbering.get(i.abstractId):void 0,s=(0,z.numberAttr)((0,le.xmlChild)(r,"w:ilvl"),"w:val")??0,a=o?.get(s);if(!(!i||!o||!a))return{numId:n,num:i,levels:o,level:s,definition:a}}numberingMarker(e){let{numId:r,num:n,levels:i,level:o,definition:s}=e,a=n.overrides.size>0?`num:${r}`:`abstract:${n.abstractId}`,c=this.counters.get(a)??[],l=u=>n.overrides.get(u)??i.get(u)?.start??1;return c[o]=c[o]===void 0?l(o):c[o]+1,c.length=o+1,this.counters.set(a,c),s.format==="bullet"?gge[s.text]??(s.text.charCodeAt(0)>=61440?"\u2022":s.text):s.text.replace(/%(\d)/g,(u,d)=>{let A=Number(d)-1;return yge(c[A]??l(A),i.get(A)?.format??"decimal")})}gap(){return bw}async image(e){let r=HA(e,"a:blip"),n=HA(e,"v:imagedata"),i=HA(e,"wp:extent"),o=(0,z.numberAttr)(i,"cx"),s=(0,z.numberAttr)(i,"cy"),a={width:o?this.pt(o/m$):void 0,height:s?this.pt(s/m$):void 0},c=await this.officePackage.relatedPartById(this.part,(0,z.attr)(HA(e,"c:chart"),"r:id"));if(c){let u=(0,hge.renderChartSvg)({root:await this.officePackage.readXml(c),theme:this.theme,colorMap:{},aspect:o&&s?s/o:.6});return u?`<span class="chart"${(0,z.styleAttribute)(a)}>${u}</span>`:""}let l=await this.officePackage.relatedImage(this.part,(0,z.attr)(r,"r:embed")??(0,z.attr)(n,"r:id"));return l?`<img src="${(0,z.escAttr)(l)}" alt=""${(0,z.styleAttribute)(a)}>`:""}async inline(e,r,n){let i="";for(let o of(0,le.xmlChildren)(e)){if(o.name==="w:pPr"||o.name==="mc:Fallback"||o.name==="w:p")continue;if(o.name!=="w:r"){i+=await this.inline(o,r,n);continue}let s=(0,z.styleAttribute)(this.runCss(this.runProps(r,(0,le.xmlChild)(o,"w:rPr"))));for(let a of(0,le.xmlChildren)(o))if(a.name==="w:t"){let c=a.children.map(l=>l.type==="text"?l.text:"").join("");c&&(n.text=!0),i+=`<span${s}>${(0,z.esc)(c)}</span>`}else if(a.name==="w:tab")i+=`<span class="tab"${s}> </span>`;else if(a.name==="w:br"||a.name==="w:cr")(0,z.attr)(a,"w:type")==="page"?n.breaks.push(n.text?"after":"before"):i+="<br>";else if(a.name==="w:drawing"||a.name==="w:pict"||a.name==="mc:AlternateContent"){let c=await this.image(a);c&&(n.objects=!0,i+=c)}}return i}async paragraph(e){let r=(0,le.xmlChild)(e,"w:pPr"),n=qA([this.defaultParagraphProps,...this.styleChain(this.paragraphStyleId(r)).map(T=>T.pPr)]),i=this.numberingLevel(qA([n,r])),o=qA([n,i?.definition.pPr,r]),s=this.runProps(r,(0,le.xmlChild)(r,"w:rPr")),a={objects:!1,breaks:[],text:!1},c=await this.inline(e,r,a),l=o.get("w:spacing"),u=o.get("w:ind"),d=(0,z.numberAttr)(l,"w:line"),A=(0,z.attr)(l,"w:lineRule")??"auto",p=(0,z.numberAttr)(u,"w:hanging"),h=(0,z.numberAttr)(u,"w:firstLine"),f=this.runCss(s),E=(0,z.styleAttribute)({"text-align":mge[(0,z.attr)(o.get("w:jc"),"w:val")??""],"margin-top":(0,z.attr)(l,"w:beforeAutospacing")==="1"?this.pt(14):this.twips((0,z.numberAttr)(l,"w:before")),"margin-bottom":(0,z.attr)(l,"w:afterAutospacing")==="1"?this.pt(14):this.twips((0,z.numberAttr)(l,"w:after")),"line-height":d===void 0?void 0:A==="auto"?String(Math.round(d/240*1.15*1e3)/1e3):this.twips(d),"margin-left":this.twips((0,z.numberAttr)(u,"w:left")??(0,z.numberAttr)(u,"w:start")),"margin-right":this.twips((0,z.numberAttr)(u,"w:right")??(0,z.numberAttr)(u,"w:end")),"text-indent":p?`-${this.twips(p)}`:this.twips(h),background:Cw(o.get("w:shd")),"border-top":pu((0,le.xmlChild)(o.get("w:pBdr"),"w:top"),this.pt),"border-bottom":pu((0,le.xmlChild)(o.get("w:pBdr"),"w:bottom"),this.pt),"font-size":f["font-size"],"font-family":f["font-family"],color:f.color}),S=i?`<span class="marker"${(0,z.styleAttribute)({...this.runCss(this.runProps(r,i.definition.rPr)),"min-width":p?this.twips(p):void 0})}>${(0,z.esc)(this.numberingMarker(i))}${p?"":" "}</span>`:"",B=`<div class="p"${E}>${S}${c}<br></div>`,_=(0,z.isOn)(o.get("w:pageBreakBefore"))||a.breaks.includes("before"),v=a.breaks.includes("after")||!!(0,le.xmlChild)(r,"w:sectPr");return`${_?this.gap():""}${B}${v?this.gap():""}`}async table(e){let r=(0,le.xmlChild)(e,"w:tblPr"),n=(0,z.attr)((0,le.xmlChild)(r,"w:tblStyle"),"w:val"),i=qA([...this.styleChain(n).map(u=>u.tblPr),r]),o=i.get("w:tblBorders"),s=u=>pu((0,le.xmlChild)(o,`w:${u}`),this.pt)??(u==="left"?pu((0,le.xmlChild)(o,"w:start"),this.pt):void 0)??(u==="right"?pu((0,le.xmlChild)(o,"w:end"),this.pt):void 0),a=(0,le.xmlChildren)((0,le.xmlChild)(e,"w:tblGrid"),"w:gridCol").map(u=>(0,z.numberAttr)(u,"w:w")??0),c=(0,le.xmlChildren)(e,"w:tr").map(u=>{let d=0;return{row:u,cells:(0,le.xmlChildren)(u,"w:tc").map(A=>{let p=(0,le.xmlChild)(A,"w:tcPr"),h=(0,z.numberAttr)((0,le.xmlChild)(p,"w:gridSpan"),"w:val")??1,f=(0,le.xmlChild)(p,"w:vMerge"),E={cell:A,tcPr:p,column:d,span:h,merge:f?(0,z.attr)(f,"w:val")==="restart"?"restart":"continue":null};return d+=h,E})}}),l=`<table${(0,z.styleAttribute)({"border-collapse":"collapse","margin-left":this.twips((0,z.numberAttr)(i.get("w:tblInd"),"w:w")),"margin-right":(0,z.attr)(i.get("w:jc"),"w:val")==="center"?"auto":void 0,...(0,z.attr)(i.get("w:jc"),"w:val")==="center"?{"margin-left":"auto"}:{}})}><colgroup>${a.map(u=>`<col${(0,z.styleAttribute)({width:this.twips(u)})}>`).join("")}</colgroup>`;for(let[u,{row:d,cells:A}]of c.entries()){let p=(0,z.numberAttr)((0,le.xmlChild)((0,le.xmlChild)(d,"w:trPr"),"w:trHeight"),"w:val");l+=`<tr${(0,z.styleAttribute)({height:this.twips(p)})}>`;for(let h of A){if(h.merge==="continue")continue;let f=1;if(h.merge==="restart")for(let T of c.slice(u+1)){if(!T.cells.some(L=>L.column===h.column&&L.merge==="continue"))break;f+=1}let E=(0,le.xmlChild)(h.tcPr,"w:tcBorders"),S=u+f===c.length,B=h.column+h.span>=a.length,_=(T,L)=>pu((0,le.xmlChild)(E,`w:${T}`),this.pt)??L,v=(0,z.attr)((0,le.xmlChild)(h.tcPr,"w:vAlign"),"w:val");l+=`<td${h.span>1?` colspan="${h.span}"`:""}${f>1?` rowspan="${f}"`:""}${(0,z.styleAttribute)({"border-top":_("top",s(u===0?"top":"insideH")),"border-bottom":_("bottom",s(S?"bottom":"insideH")),"border-left":_("left",h.column===0?s("left"):s("insideV")),"border-right":_("right",s(B?"right":"insideV")),background:Cw((0,le.xmlChild)(h.tcPr,"w:shd")),"vertical-align":v==="center"?"middle":v==="bottom"?"bottom":"top"})}>${(await this.blocks(h.cell)).split(bw).join("")}</td>`}l+="</tr>"}return`${l}</table>`}async blocks(e){let r="";for(let n of(0,le.xmlChildren)(e))n.name==="w:p"?r+=await this.paragraph(n):n.name==="w:tbl"?r+=await this.table(n):n.name==="w:sdt"?r+=await this.blocks((0,le.xmlChild)(n,"w:sdtContent")??n):n.name==="w:customXml"||n.name==="w:ins"?r+=await this.blocks(n):n.name==="mc:AlternateContent"&&(r+=await this.blocks((0,le.xmlChild)(n,"mc:Choice")??n));return r}};async function Ege({officePackage:t,title:e}){let r=await t.readXml($m),n=(0,le.xmlChild)(r,"w:body");if(!r||!n)throw new Error("The file has no Word document body");let i=(0,le.xmlChildren)(n,"w:sectPr").slice(-1)[0],o=(0,le.xmlChild)(i,"w:pgSz"),s=(0,le.xmlChild)(i,"w:pgMar"),a={width:((0,z.numberAttr)(o,"w:w")??12240)/20,height:((0,z.numberAttr)(o,"w:h")??15840)/20,top:Math.abs((0,z.numberAttr)(s,"w:top")??1440)/20,right:((0,z.numberAttr)(s,"w:right")??1440)/20,bottom:Math.abs((0,z.numberAttr)(s,"w:bottom")??1440)/20,left:((0,z.numberAttr)(s,"w:left")??1440)/20},c=await(0,z.readOfficeTheme)(t,await t.relatedPart($m,"/theme")),l=await t.readXml("word/styles.xml"),u=await t.readXml("word/numbering.xml"),d=async(T,L)=>{let k=new Sw(t,c,a,T);return k.loadStyles(l),k.loadNumbering(u),k.blocks(L)},A=async(T,L)=>{let k=(0,le.xmlChildren)(i,T).find(K=>(0,z.attr)(K,"w:type")===L),P=await t.relatedPartById($m,(0,z.attr)(k,"r:id")),U=P?await t.readXml(P):void 0;return P&&U?d(P,U):""},h=((0,z.isOn)((0,le.xmlChild)(i,"w:titlePg"))?await A("w:headerReference","first"):"")||await A("w:headerReference","default"),f=await A("w:footerReference","default"),E=await d($m,n),S=((0,z.numberAttr)(s,"w:header")??720)/20,B=((0,z.numberAttr)(s,"w:footer")??720)/20,_=T=>`${Math.round(T/a.width*1e6)/1e4}cqw`,v=["html,body{margin:0;background:transparent}","body{padding:24px 24px 32px;font-family:Calibri,Arial,sans-serif;color:#000}",`.sheet{max-width:${a.width}pt;margin:0 auto;container-type:inline-size}`,`.page{position:relative;box-sizing:border-box;background:#fff;width:100cqw;min-height:${_(a.height)};padding:${_(a.top)} ${_(a.right)} ${_(a.bottom)} ${_(a.left)};font-size:${_(10)};box-shadow:0 1px 2px rgb(0 0 0/.08),0 2px 8px rgb(0 0 0/.06);overflow-wrap:break-word}`,".p{margin:0}",".p span{white-space:pre-wrap}",".tab{white-space:pre;tab-size:4}",".marker{display:inline-block;text-indent:0;white-space:pre}",".page+.page{margin-top:24px}","img{max-width:100%;vertical-align:bottom}","table{max-width:100%}",`td{padding:0 ${_(5.4)};box-sizing:border-box}`,".chart{display:inline-block;max-width:100%}",`.header,.footer{position:absolute;left:${_(a.left)};right:${_(a.right)}}`,`.header{top:${_(S)}}`,`.footer{bottom:${_(B)}}`].join(`
|
|
790
|
+
})();`});var Zo=y(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.findXmlTagEnd=zA;Jo.parseXmlDocument=t$;Jo.streamXmlElements=Yfe;Jo.xmlChild=r$;Jo.xmlChildren=Pm;Jo.xmlPath=Vfe;Jo.xmlText=n$;Jo.officeDocumentFormat=Wfe;var qfe={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"},Hfe={"http://schemas.openxmlformats.org/spreadsheetml/2006/main":"","http://purl.oclc.org/ooxml/spreadsheetml/main":"","http://schemas.openxmlformats.org/package/2006/relationships":"","http://schemas.openxmlformats.org/wordprocessingml/2006/main":"w","http://purl.oclc.org/ooxml/wordprocessingml/main":"w","http://schemas.openxmlformats.org/drawingml/2006/main":"a","http://purl.oclc.org/ooxml/drawingml/main":"a","http://schemas.openxmlformats.org/presentationml/2006/main":"p","http://purl.oclc.org/ooxml/presentationml/main":"p","http://schemas.openxmlformats.org/officeDocument/2006/relationships":"r","http://purl.oclc.org/ooxml/officeDocument/relationships":"r","http://schemas.openxmlformats.org/drawingml/2006/chart":"c","http://purl.oclc.org/ooxml/drawingml/chart":"c","http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing":"xdr","http://purl.oclc.org/ooxml/drawingml/spreadsheetDrawing":"xdr","http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing":"wp","http://purl.oclc.org/ooxml/drawingml/wordprocessingDrawing":"wp","http://schemas.openxmlformats.org/drawingml/2006/picture":"pic","http://purl.oclc.org/ooxml/drawingml/picture":"pic","http://schemas.openxmlformats.org/drawingml/2006/diagram":"dgm","http://schemas.openxmlformats.org/markup-compatibility/2006":"mc","urn:schemas-microsoft-com:vml":"v"};function mw(t,e,r){let n=t.indexOf(":"),i=n===-1?"":t.slice(0,n);if(i==="xml"||i==="xmlns"||t==="xmlns"||!r&&n===-1)return t;let o=e.get(i),s=o===void 0?void 0:Hfe[o];if(s===void 0)return t;let a=n===-1?t:t.slice(n+1);return s?`${s}:${a}`:a}function e$(t){return t.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi,(e,r)=>{if(r[0]!=="#")return qfe[r]??e;let n=r[1]==="x"||r[1]==="X"?parseInt(r.slice(2),16):Number(r.slice(1));return Number.isInteger(n)&&n>=0&&n<=1114111?String.fromCodePoint(n):e})}function Gfe(t){let e={};for(let r of t.matchAll(/([^\s=/]+)\s*=\s*("([^"]*)"|'([^']*)')/g))e[r[1]]=e$(r[3]??r[4]??"");return e}function zA(t,e){let r=null;for(let n=e;n<t.length;n+=1){let i=t[n];if(r)i===r&&(r=null);else if(i==='"'||i==="'")r=i;else if(i===">")return n}return-1}function t$(t){let e={type:"element",name:"#document",attributes:{},children:[]},r=[e],n=[new Map],i=0;for(;i<t.length;){let o=r[r.length-1],s=t.indexOf("<",i),a=s===-1?t.length:s;if(a>i&&o.children.push({type:"text",text:e$(t.slice(i,a))}),s===-1)break;if(t.startsWith("<!--",s)){let f=t.indexOf("-->",s+4);i=f===-1?t.length:f+3;continue}if(t.startsWith("<![CDATA[",s)){let f=t.indexOf("]]>",s+9);o.children.push({type:"text",text:t.slice(s+9,f===-1?t.length:f)}),i=f===-1?t.length:f+3;continue}if(t[s+1]==="?"||t[s+1]==="!"){let f=t.indexOf(">",s);i=f===-1?t.length:f+1;continue}let c=zA(t,s+1);if(c===-1)throw new Error("Malformed XML: unterminated tag");if(t[s+1]==="/"){let f=mw(t.slice(s+2,c).trim(),n[n.length-1],!0),E=r.map(S=>S.name).lastIndexOf(f);if(E<=0)throw new Error(`Malformed XML: unexpected </${f}>`);r.length=E,n.length=E,i=c+1;continue}let l=t[c-1]==="/",u=t.slice(s+1,l?c-1:c),d=/^[^\s/>]+/.exec(u);if(!d)throw new Error("Malformed XML: missing tag name");let A=Gfe(u.slice(d[0].length)),p=new Map(n[n.length-1]);for(let[f,E]of Object.entries(A))f==="xmlns"?p.set("",E):f.startsWith("xmlns:")&&p.set(f.slice(6),E);let h={type:"element",name:mw(d[0],p,!0),attributes:Object.fromEntries(Object.entries(A).map(([f,E])=>[mw(f,p,!1),E])),children:[]};o.children.push(h),l||(r.push(h),n.push(p)),i=c+1}return e}function yw(t){return Pm(t$(t))[0]}function Yfe({xml:t,container:e,element:r}){let n=new RegExp(`<([\\w.-]+:)?${e}(?=[\\s/>])`).exec(t),i=n?zA(t,n.index+1):-1,o=/<(?![?!])([^\s/>]+)/.exec(t);if(!n||!o||i===-1||t[i-1]==="/")return{root:yw(t),elements:function*(){}};let s=n[1]??"",a=`</${s}${e}>`,c=t.indexOf(a,i);if(c===-1)throw new Error(`Malformed XML: unterminated <${e}>`);let l=o.index===n.index,u=zA(t,o.index+1),d=l?t.slice(n.index,i+1):`${t.slice(o.index,u+1)}${t.slice(n.index,i+1)}`,A=l?a:`${a}</${o[1]}>`,p=`<${s}${r}`,h=`</${s}${r}>`;return{root:yw(t.slice(0,i+1)+t.slice(c)),*elements(){let f=i+1;for(;;){let E=t.indexOf(p,f);if(E===-1||E>=c)return;let S=t[E+p.length];if(S!==">"&&S!=="/"&&!/\s/.test(S)){f=E+p.length;continue}let B=zA(t,E+1);if(B===-1)throw new Error(`Malformed XML: unterminated <${r}>`);let _=t[B-1]==="/"?B+1:t.indexOf(h,B);if(_===-1)throw new Error(`Malformed XML: unterminated <${r}>`);let v=t[B-1]==="/"?_:_+h.length,T=yw(d+t.slice(E,v)+A),L=Pm(l?T:Pm(T)[0])[0];L&&(yield L),f=v}}}}function r$(t,e){return t?.children.find(r=>r.type==="element"&&r.name===e)}function Pm(t,e){return t?t.children.filter(r=>r.type==="element"&&(e===void 0||r.name===e)):[]}function Vfe(t,...e){return e.reduce((r,n)=>r$(r,n),t)}function n$(t){return t.children.map(e=>e.type==="text"?e.text:n$(e)).join("")}function Wfe(t){let e=t.toLowerCase().match(/\.([a-z0-9]+)$/)?.[1];return e==="docx"||e==="pptx"?e:null}});var Ts=y(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.OfficePackage=Kt.escAttr=Kt.esc=void 0;Kt.attr=Xr;Kt.numberAttr=o$;Kt.isOn=Kfe;Kt.readOfficeTheme=ege;Kt.tintedColor=tge;Kt.drawingColor=rge;Kt.fontStack=nge;Kt.styleAttribute=ige;Kt.officeHtmlDocument=oge;var i$=du(),Ur=Zo(),Jfe={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",svg:"image/svg+xml",webp:"image/webp"},Zfe={black:"000000",white:"FFFFFF",red:"FF0000",green:"008000",blue:"0000FF",yellow:"FFFF00",gray:"808080",grey:"808080",darkGray:"A9A9A9",lightGray:"D3D3D3"};Kt.esc=i$.escapeText;Kt.escAttr=i$.escapeAttribute;function Xr(t,e){return t?.attributes[e]}function o$(t,e){let r=t?.attributes[e];if(r===void 0)return;let n=Number(r);return Number.isFinite(n)?n:void 0}function Kfe(t){if(!t)return!1;let e=t.attributes["w:val"]??t.attributes.val;return e===void 0||!["0","false","off","none"].includes(e)}var Ew=class{constructor(e){this.zip=e,this.images=new Map,this.xml=new Map,this.relationships=new Map}readXml(e){let r=this.xml.get(e);if(r)return r;let n=(async()=>{let i=this.zip.file(e);if(!i)return;let o=(0,Ur.parseXmlDocument)(await i.async("string"));return(0,Ur.xmlChildren)(o)[0]})();return this.xml.set(e,n),n}async readText(e){return this.zip.file(e)?.async("string")}rels(e){let r=this.relationships.get(e);if(r)return r;let n=(async()=>{let i=e.slice(0,e.lastIndexOf("/")+1),o=e.slice(e.lastIndexOf("/")+1),s=await this.readXml(`${i}_rels/${o}.rels`),a=new Map;for(let c of(0,Ur.xmlChildren)(s,"Relationship")){let l=Xr(c,"Id"),u=Xr(c,"Target");if(!l||!u)continue;let d=Xr(c,"TargetMode")==="External";a.set(l,{type:Xr(c,"Type")??"",target:d?u:Xfe(i,u),external:d})}return a})();return this.relationships.set(e,n),n}async relatedPart(e,r){for(let n of(await this.rels(e)).values())if(!n.external&&n.type.endsWith(r))return n.target}image(e){let r=this.images.get(e);if(r)return r;let n=e.toLowerCase().match(/\.([a-z0-9]+)$/)?.[1]??"",i=Jfe[n],o=this.zip.file(e),s=i&&o?o.async("base64").then(a=>`data:${i};base64,${a}`):Promise.resolve(void 0);return this.images.set(e,s),s}async relatedPartById(e,r){if(!r)return;let n=(await this.rels(e)).get(r);return n&&!n.external?n.target:void 0}async relatedImage(e,r){let n=await this.relatedPartById(e,r);return n?this.image(n):void 0}};Kt.OfficePackage=Ew;function Xfe(t,e){let r=(e.startsWith("/")?e.slice(1):t+e).split("/"),n=[];for(let i of r)i===".."?n.pop():i&&i!=="."&&n.push(i);return n.join("/")}async function ege(t,e){let r=e?await t.readXml(e):void 0,n=(0,Ur.xmlChild)(r,"a:themeElements"),i=(0,Ur.xmlChild)(n,"a:clrScheme"),o={};for(let a of(0,Ur.xmlChildren)(i)){let c=(0,Ur.xmlChild)(a,"a:srgbClr")??(0,Ur.xmlChild)(a,"a:sysClr"),l=Xr(c,"lastClr")??Xr(c,"val");l&&(o[a.name.replace(/^a:/,"")]=l)}let s=(0,Ur.xmlChild)(n,"a:fontScheme");return{colors:o,majorFont:Xr((0,Ur.xmlChild)((0,Ur.xmlChild)(s,"a:majorFont"),"a:latin"),"typeface")??"",minorFont:Xr((0,Ur.xmlChild)((0,Ur.xmlChild)(s,"a:minorFont"),"a:latin"),"typeface")??""}}function s$(t){let e=parseInt(t.padStart(6,"0").slice(0,6),16);return[e>>16&255,e>>8&255,e&255]}function a$([t,e,r]){let n=t/255,i=e/255,o=r/255,s=Math.max(n,i,o),a=Math.min(n,i,o),c=(s+a)/2;if(s===a)return[0,0,c];let l=s-a,u=c>.5?l/(2-s-a):l/(s+a);return[(s===n?(i-o)/l+(i<o?6:0):s===i?(o-n)/l+2:(n-i)/l+4)/6,u,c]}function c$([t,e,r]){if(e===0){let s=Math.round(r*255);return[s,s,s]}let n=r<.5?r*(1+e):r+e-r*e,i=2*r-n,o=s=>{let a=t+s;return a<0&&(a+=1),a>1&&(a-=1),a<1/6?i+(n-i)*6*a:a<1/2?n:a<2/3?i+(n-i)*(2/3-a)*6:i};return[o(1/3),o(0),o(-1/3)].map(s=>Math.round(s*255))}function tge(t,e){let r=a$(s$(t));return r[2]=e<0?r[2]*(1+e):r[2]*(1-e)+e,`#${c$(r).map(n=>n.toString(16).padStart(2,"0")).join("")}`}function rge({element:t,theme:e,colorMap:r,placeholderColor:n}){let i=t?(0,Ur.xmlChildren)(t)[0]:void 0;if(!i)return;let o;if(i.name==="a:srgbClr")o=Xr(i,"val");else if(i.name==="a:sysClr")o=Xr(i,"lastClr")??Xr(i,"val");else if(i.name==="a:prstClr")o=Zfe[Xr(i,"val")??""];else if(i.name==="a:schemeClr"){let c=Xr(i,"val")??"";c==="phClr"?o=n:o=e.colors[r?.[c]??c]??e.colors[c]}if(!o||!/^[0-9a-f]{6}$/i.test(o))return;let s=s$(o),a=1;for(let c of(0,Ur.xmlChildren)(i)){let l=(o$(c,"val")??0)/1e5;if(c.name==="a:lumMod"||c.name==="a:lumOff"){let u=a$(s);u[2]=c.name==="a:lumMod"?u[2]*l:u[2]+l,u[2]=Math.min(1,Math.max(0,u[2])),s=c$(u)}else c.name==="a:tint"?s=s.map(u=>Math.round(255-(255-u)*l)):c.name==="a:shade"?s=s.map(u=>Math.round(u*l)):c.name==="a:alpha"&&(a=l)}return a<1?`rgba(${s.join(",")},${Math.round(a*1e3)/1e3})`:`#${s.map(c=>c.toString(16).padStart(2,"0")).join("")}`}function nge(t){let e=t?.replace(/["\\<>;{}\u0000-\u001f\u007f]/g,"");return e?`"${e}", Calibri, Arial, sans-serif`:""}function ige(t){let e=Object.entries(t).filter(([,r])=>r!==void 0&&r!=="").map(([r,n])=>`${r}:${n}`).join(";");return e?` style="${(0,Kt.escAttr)(e)}"`:""}function oge({title:t,css:e,body:r}){let n=["default-src 'none'","script-src 'none'","style-src 'unsafe-inline'","img-src data:","font-src data:","connect-src 'none'","base-uri 'none'","form-action 'none'"].join("; ");return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="referrer" content="no-referrer"><meta http-equiv="Content-Security-Policy" content="${(0,Kt.escAttr)(n)}"><title>${(0,Kt.esc)(t)}</title><style>${e}</style></head><body>${r}</body></html>`}});var Dc=y(Lm=>{"use strict";Object.defineProperty(Lm,"__esModule",{value:!0});Lm.readChartData=Age;Lm.renderChartSvg=pge;var ki=Ts(),je=Zo(),l$={"c:barChart":"column","c:bar3DChart":"column","c:lineChart":"line","c:line3DChart":"line","c:areaChart":"area","c:area3DChart":"area","c:pieChart":"pie","c:pie3DChart":"pie","c:doughnutChart":"doughnut"},u$=["accent1","accent2","accent3","accent4","accent5","accent6"],Ia=1e3,d$=1048576,sge="#595959",A$="#d9d9d9";function Tc(t){let e=(0,je.xmlPath)(t,"c:strRef","c:strCache")??(0,je.xmlPath)(t,"c:numRef","c:numCache")??(0,je.xmlChild)(t,"c:strLit")??(0,je.xmlChild)(t,"c:numLit")??(0,je.xmlPath)(t,"c:multiLvlStrRef","c:multiLvlStrCache","c:lvl"),r=(0,je.xmlChildren)(e,"c:pt").map((s,a)=>({point:s,index:Number(s.attributes.idx??a)})).filter(({index:s})=>Number.isInteger(s)&&s>=0&&s<d$),n=Number((0,je.xmlChild)(e,"c:ptCount")?.attributes.val??d$),i=r.filter(({index:s})=>s<n),o=Array(i.reduce((s,{index:a})=>Math.max(s,a+1),0)).fill("");for(let{point:s,index:a}of i){let c=(0,je.xmlChild)(s,"c:v");o[a]=c?(0,je.xmlText)(c):""}return o}function age(t){if(t<=0)return 1;let e=10**Math.floor(Math.log10(t));return([1,2,2.5,5,10].find(n=>n*e>=t)??10)*e}function cge(t){return Math.abs(t)>=1e6?`${Math.round(t/1e5)/10}M`:Math.abs(t)>=1e4?`${Math.round(t/100)/10}K`:String(Math.round(t*100)/100)}function Au({x:t,y:e,value:r,size:n,anchor:i="middle",weight:o="400"}){return`<text x="${t}" y="${e}" font-size="${n}" font-weight="${o}" text-anchor="${i}" fill="${sge}">${(0,ki.esc)(r)}</text>`}function lge(t,e){let r=Math.min(220,Ia/Math.max(t.length,1)),n=Ia/2-r*t.length/2;return t.map((i,o)=>{let s=n+o*r;return`<rect x="${s}" y="${e-14}" width="16" height="16" fill="${(0,ki.escAttr)(i.color)}"/>${Au({x:s+24,y:e,value:i.name,size:20,anchor:"start"})}`}).join("")}function uge({kind:t,series:e,stacked:r,percent:n,height:i,top:o,bottom:s}){let a=e[0].categories,c=Math.max(a.length,...e.map(k=>k.values.length)),l=Array.from({length:c},(k,P)=>e.reduce((U,K)=>U+Math.max(K.values[P]??0,0),0)),u=n?100:age((r?l:e.flatMap(k=>k.values)).reduce((k,P)=>Math.max(k,P),-1/0)),d=90,A=Ia-30,p=o,h=i-s,f=t==="bar",E=f?A-d:h-p,S=f?h-p:A-d,B=k=>k/u*E,_=S/Math.max(c,1),v="";for(let k=0;k<=4;k+=1){let P=u/4*k,U=B(P),K=n?`${P}%`:cge(P);v+=f?`<line x1="${d+U}" y1="${p}" x2="${d+U}" y2="${h}" stroke="${A$}"/>${Au({x:d+U,y:h+26,value:K,size:18})}`:`<line x1="${d}" y1="${h-U}" x2="${A}" y2="${h-U}" stroke="${A$}"/>${Au({x:d-10,y:h-U+6,value:K,size:18,anchor:"end"})}`}for(let k=0;k<c;k+=1){let P=a[k]??String(k+1);v+=Au(f?{x:d-10,y:p+_*(k+.5)+6,value:P,size:18,anchor:"end"}:{x:d+_*(k+.5),y:h+26,value:P,size:18})}if(t==="line"||t==="area"){for(let k of e){let P=k.values.map((U,K)=>`${d+_*(K+.5)},${h-B(U)}`);v+=t==="area"?`<polygon points="${d+_*.5},${h} ${P.join(" ")} ${d+_*(k.values.length-.5)},${h}" fill="${(0,ki.escAttr)(k.color)}" fill-opacity="0.6"/>`:`<polyline points="${P.join(" ")}" fill="none" stroke="${(0,ki.escAttr)(k.color)}" stroke-width="4"/>`}return v}let T=_*.7,L=r?T:T/e.length;for(let k=0;k<c;k+=1){let P=0;e.forEach((U,K)=>{let Ae=Math.max(U.values[k]??0,0),Re=n&&l[k]?Ae/l[k]*100:Ae,Ge=B(Re),tt=_*k+(_-T)/2+(r?0:L*K);v+=f?`<rect x="${d+P}" y="${p+tt}" width="${Ge}" height="${L}" fill="${(0,ki.escAttr)(U.color)}"/>`:`<rect x="${d+tt}" y="${h-P-Ge}" width="${L}" height="${Ge}" fill="${(0,ki.escAttr)(U.color)}"/>`,r&&(P+=Ge)})}return v}function dge({series:t,doughnut:e,height:r,top:n,bottom:i}){let o=t.values.reduce((d,A)=>d+Math.max(A,0),0);if(o<=0)return"";let s=Math.min(Ia,r-n-i)/2-10,a=Ia/2,c=n+(r-n-i)/2,l=-Math.PI/2,u="";return t.values.forEach((d,A)=>{let p=Math.max(d,0)/o*Math.PI*2,h=l+p,f=p>Math.PI?1:0,E=a+s*Math.cos(l),S=c+s*Math.sin(l),B=a+s*Math.cos(h),_=c+s*Math.sin(h);u+=p>=Math.PI*2-1e-4?`<circle cx="${a}" cy="${c}" r="${s}" fill="${(0,ki.escAttr)(Iw(t,A))}"/>`:`<path d="M${a},${c} L${E},${S} A${s},${s} 0 ${f} 1 ${B},${_} Z" fill="${(0,ki.escAttr)(Iw(t,A))}" stroke="#fff" stroke-width="2"/>`,l=h}),e&&(u+=`<circle cx="${a}" cy="${c}" r="${s*.5}" fill="#fff"/>`),u}var p$=["#4472c4","#ed7d31","#a5a5a5","#ffc000","#5b9bd5","#70ad47"];function Iw(t,e){return t.pointColors[e]}function h$(t){return(0,je.xmlPath)(t,"c:spPr","a:solidFill")??(0,je.xmlPath)(t,"c:spPr","a:ln","a:solidFill")}function f$({index:t,theme:e,colorMap:r}){let n={type:"element",name:"a:solidFill",attributes:{},children:[{type:"element",name:"a:schemeClr",attributes:{val:u$[t%u$.length]},children:[]}]};return(0,ki.drawingColor)({element:n,theme:e,colorMap:r})??p$[t%p$.length]}function g$(t){let e=(0,je.xmlChild)(t,"c:title");return e?(0,je.xmlChildren)((0,je.xmlPath)(e,"c:tx","c:rich"),"a:p").map(r=>(0,je.xmlText)(r)).join(" ").trim():""}function Age(t){let e=(0,je.xmlChild)(t,"c:chart"),r=(0,je.xmlChild)(e,"c:plotArea");if(!r)return;let n=(0,je.xmlChildren)(r).filter(i=>i.name.startsWith("c:")&&i.name.endsWith("Chart")).flatMap(i=>(0,je.xmlChildren)(i,"c:ser")).map((i,o)=>({name:Tc((0,je.xmlChild)(i,"c:tx")).join(" ")||`Series ${o+1}`,categories:Tc((0,je.xmlChild)(i,"c:cat")??(0,je.xmlChild)(i,"c:xVal")),values:Tc((0,je.xmlChild)(i,"c:val")??(0,je.xmlChild)(i,"c:yVal"))}));return{title:g$(e),series:n}}function pge({root:t,theme:e,colorMap:r,aspect:n}){let i=(0,je.xmlChild)(t,"c:chart"),o=(0,je.xmlChild)(i,"c:plotArea"),s=(0,je.xmlChildren)(o).find(v=>l$[v.name]);if(!s)return;let c=(0,je.xmlChild)(s,"c:barDir")?.attributes.val==="bar"?"bar":l$[s.name],l=(0,je.xmlChild)(s,"c:grouping")?.attributes.val??"clustered",u=(0,je.xmlChildren)(s,"c:ser").map((v,T)=>{let L=Tc((0,je.xmlChild)(v,"c:val")).map(P=>Number(P)||0),k=new Map((0,je.xmlChildren)(v,"c:dPt").map(P=>[Number((0,je.xmlChild)(P,"c:idx")?.attributes.val??-1),(0,ki.drawingColor)({element:h$(P),theme:e,colorMap:r})]));return{name:Tc((0,je.xmlChild)(v,"c:tx")).join(" ")||`Series ${T+1}`,categories:Tc((0,je.xmlChild)(v,"c:cat")),values:L,color:(0,ki.drawingColor)({element:h$(v),theme:e,colorMap:r})??f$({index:T,theme:e,colorMap:r}),pointColors:Array.from({length:Math.max(L.length,Tc((0,je.xmlChild)(v,"c:cat")).length)},(P,U)=>k.get(U)??f$({index:U,theme:e,colorMap:r}))}});if(u.length===0)return;let d=Math.round(Ia*n),A=g$(i),p=!A&&(0,je.xmlChild)(i,"c:autoTitleDeleted")?.attributes.val!=="1"&&u.length===1?u[0].name:"",h=A||p,f=c==="pie"||c==="doughnut",E=f?u[0].categories.map((v,T)=>({name:v,color:Iw(u[0],T)})):u.length>1?u.map(({name:v,color:T})=>({name:v,color:T})):[],S=h?60:20,B=(E.length>0?50:0)+(f?10:40),_=f?dge({series:u[0],doughnut:c==="doughnut",height:d,top:S,bottom:B}):uge({kind:c,series:u,stacked:l==="stacked"||l==="percentStacked",percent:l==="percentStacked",height:d,top:S,bottom:B});return`<svg viewBox="0 0 ${Ia} ${d}" preserveAspectRatio="xMidYMid meet" font-family="Calibri, Arial, sans-serif" style="width:100%;height:100%">${h?Au({x:Ia/2,y:38,value:h,size:28,weight:"600"}):""}${_}${E.length>0?lge(E,d-18):""}</svg>`}});var I$=y(ww=>{"use strict";Object.defineProperty(ww,"__esModule",{value:!0});ww.renderDocx=Ege;var le=Zo(),z=Ts(),hge=Dc(),$m="word/document.xml",bw="<!--sg-page-break-->",m$=12700,fge={yellow:"#ffff00",green:"#00ff00",cyan:"#00ffff",magenta:"#ff00ff",blue:"#0000ff",red:"#ff0000",darkBlue:"#000080",darkCyan:"#008080",darkGreen:"#008000",darkMagenta:"#800080",darkRed:"#800000",darkYellow:"#808000",darkGray:"#808080",lightGray:"#c0c0c0",black:"#000000",white:"#ffffff"},gge={"\uF0B7":"\u2022","\uF0A7":"\u25AA","\uF0D8":"\u27A2","\uF0FC":"\u2713","\uF076":"\u2756","\uF06E":"\u25A0","\uF06C":"\u25CF","\uF071":"\u2751",o:"\u25E6"},mge={left:"left",start:"left",center:"center",right:"right",end:"right",both:"justify",distribute:"justify"};function qA(t){let e=new Map;for(let r of t)for(let n of r instanceof Map?r.values():(0,le.xmlChildren)(r)){let i=e.get(n.name);e.set(n.name,i?{...n,attributes:{...i.attributes,...n.attributes}}:n)}return e}function HA(t,e){for(let r of(0,le.xmlChildren)(t)){if(r.name===e)return r;let n=HA(r,e);if(n)return n}}function pu(t,e){let r=(0,z.attr)(t,"w:val");if(!t||!r)return;if(r==="nil"||r==="none")return"none";let n=Math.max(((0,z.numberAttr)(t,"w:sz")??4)/8,.5),i=(0,z.attr)(t,"w:color"),o=r==="double"?"double":r.includes("dash")?"dashed":r==="dotted"?"dotted":"solid",s=i&&/^[0-9a-f]{6}$/i.test(i)?`#${i}`:"#000";return`max(1px, ${e(n)}) ${o} ${s}`}function Cw(t){let e=(0,z.attr)(t,"w:fill");return e&&e!=="auto"&&/^[0-9a-f]{6}$/i.test(e)?`#${e}`:void 0}function y$(t){let e=[[1e3,"m"],[900,"cm"],[500,"d"],[400,"cd"],[100,"c"],[90,"xc"],[50,"l"],[40,"xl"],[10,"x"],[9,"ix"],[5,"v"],[4,"iv"],[1,"i"]],r=t,n="";for(let[i,o]of e)for(;r>=i;)n+=o,r-=i;return n}function E$(t){return String.fromCharCode(97+(t-1)%26).repeat(Math.floor((t-1)/26)+1)}function yge(t,e){return e==="lowerLetter"?E$(t):e==="upperLetter"?E$(t).toUpperCase():e==="lowerRoman"?y$(t):e==="upperRoman"?y$(t).toUpperCase():e==="decimalZero"?String(t).padStart(2,"0"):e==="none"?"":String(t)}var Sw=class{constructor(e,r,n,i){this.officePackage=e,this.theme=r,this.page=n,this.part=i,this.styles=new Map,this.abstractNumbering=new Map,this.numbering=new Map,this.counters=new Map,this.pt=o=>`${Math.round(o/this.page.width*1e6)/1e4}cqw`}twips(e){return e===void 0?void 0:this.pt(e/20)}loadStyles(e){let r=(0,le.xmlChild)(e,"w:docDefaults");this.defaultRunProps=(0,le.xmlChild)((0,le.xmlChild)(r,"w:rPrDefault"),"w:rPr"),this.defaultParagraphProps=(0,le.xmlChild)((0,le.xmlChild)(r,"w:pPrDefault"),"w:pPr");for(let n of(0,le.xmlChildren)(e,"w:style")){let i=(0,z.attr)(n,"w:styleId");if(!i)continue;let o=["1","true"].includes((0,z.attr)(n,"w:default")??"");(0,z.attr)(n,"w:type")==="paragraph"&&o&&(this.defaultParagraphStyle=i);let s=(0,z.attr)((0,le.xmlChild)(n,"w:basedOn"),"w:val");this.styles.set(i,{...s?{basedOn:s}:{},...(0,le.xmlChild)(n,"w:pPr")?{pPr:(0,le.xmlChild)(n,"w:pPr")}:{},...(0,le.xmlChild)(n,"w:rPr")?{rPr:(0,le.xmlChild)(n,"w:rPr")}:{},...(0,le.xmlChild)(n,"w:tblPr")?{tblPr:(0,le.xmlChild)(n,"w:tblPr")}:{}})}}loadNumbering(e){for(let r of(0,le.xmlChildren)(e,"w:abstractNum")){let n=new Map;for(let o of(0,le.xmlChildren)(r,"w:lvl"))n.set((0,z.numberAttr)(o,"w:ilvl")??0,{format:(0,z.attr)((0,le.xmlChild)(o,"w:numFmt"),"w:val")??"decimal",text:(0,z.attr)((0,le.xmlChild)(o,"w:lvlText"),"w:val")??"",start:(0,z.numberAttr)((0,le.xmlChild)(o,"w:start"),"w:val")??1,...(0,le.xmlChild)(o,"w:pPr")?{pPr:(0,le.xmlChild)(o,"w:pPr")}:{},...(0,le.xmlChild)(o,"w:rPr")?{rPr:(0,le.xmlChild)(o,"w:rPr")}:{}});let i=(0,z.attr)(r,"w:abstractNumId");i&&this.abstractNumbering.set(i,n)}for(let r of(0,le.xmlChildren)(e,"w:num")){let n=(0,z.attr)(r,"w:numId"),i=(0,z.attr)((0,le.xmlChild)(r,"w:abstractNumId"),"w:val");if(!n||!i)continue;let o=new Map;for(let s of(0,le.xmlChildren)(r,"w:lvlOverride")){let a=(0,z.numberAttr)((0,le.xmlChild)(s,"w:startOverride"),"w:val");a!==void 0&&o.set((0,z.numberAttr)(s,"w:ilvl")??0,a)}this.numbering.set(n,{abstractId:i,overrides:o})}}styleChain(e){let r=[],n=new Set,i=e;for(;i&&!n.has(i);){n.add(i);let o=this.styles.get(i);if(!o)break;r.unshift(o),i=o.basedOn}return r}paragraphStyleId(e){return(0,z.attr)((0,le.xmlChild)(e,"w:pStyle"),"w:val")??this.defaultParagraphStyle}runProps(e,r){let n=this.styleChain(this.paragraphStyleId(e)),i=this.styleChain((0,z.attr)((0,le.xmlChild)(r,"w:rStyle"),"w:val"));return qA([this.defaultRunProps,...n.map(o=>o.rPr),...i.map(o=>o.rPr),r])}fontFamily(e){let r=e.get("w:rFonts"),n=(0,z.attr)(r,"w:ascii")??(0,z.attr)(r,"w:hAnsi");if(n)return(0,z.fontStack)(n);let i=(0,z.attr)(r,"w:asciiTheme")??(0,z.attr)(r,"w:hAnsiTheme");if(i)return(0,z.fontStack)(i.startsWith("major")?this.theme.majorFont:this.theme.minorFont)}runCss(e){let r=[e.has("w:u")&&(0,z.attr)(e.get("w:u"),"w:val")!=="none"?"underline":"",(0,z.isOn)(e.get("w:strike"))||(0,z.isOn)(e.get("w:dstrike"))?"line-through":""].filter(Boolean),n=(0,z.numberAttr)(e.get("w:sz"),"w:val"),i=(0,z.attr)(e.get("w:color"),"w:val"),o=(0,z.attr)(e.get("w:vertAlign"),"w:val"),s=(0,z.attr)(e.get("w:highlight"),"w:val"),a=(0,z.numberAttr)(e.get("w:spacing"),"w:val");return{"font-weight":e.has("w:b")?(0,z.isOn)(e.get("w:b"))?"700":"400":void 0,"font-style":e.has("w:i")?(0,z.isOn)(e.get("w:i"))?"italic":"normal":void 0,"text-decoration":r.length>0?r.join(" "):void 0,color:i&&i!=="auto"&&/^[0-9a-f]{6}$/i.test(i)?`#${i}`:void 0,"font-size":n!==void 0?this.pt(n/2*(o==="superscript"||o==="subscript"?.65:1)):void 0,"font-family":this.fontFamily(e),background:(s?fge[s]:void 0)??Cw(e.get("w:shd")),"vertical-align":o==="superscript"?"super":o==="subscript"?"sub":void 0,"text-transform":(0,z.isOn)(e.get("w:caps"))?"uppercase":void 0,"font-variant":(0,z.isOn)(e.get("w:smallCaps"))?"small-caps":void 0,"letter-spacing":a?this.twips(a):void 0,display:(0,z.isOn)(e.get("w:vanish"))?"none":void 0}}numberingLevel(e){let r=e.get("w:numPr"),n=(0,z.attr)((0,le.xmlChild)(r,"w:numId"),"w:val");if(!n||n==="0")return;let i=this.numbering.get(n),o=i?this.abstractNumbering.get(i.abstractId):void 0,s=(0,z.numberAttr)((0,le.xmlChild)(r,"w:ilvl"),"w:val")??0,a=o?.get(s);if(!(!i||!o||!a))return{numId:n,num:i,levels:o,level:s,definition:a}}numberingMarker(e){let{numId:r,num:n,levels:i,level:o,definition:s}=e,a=n.overrides.size>0?`num:${r}`:`abstract:${n.abstractId}`,c=this.counters.get(a)??[],l=u=>n.overrides.get(u)??i.get(u)?.start??1;return c[o]=c[o]===void 0?l(o):c[o]+1,c.length=o+1,this.counters.set(a,c),s.format==="bullet"?gge[s.text]??(s.text.charCodeAt(0)>=61440?"\u2022":s.text):s.text.replace(/%(\d)/g,(u,d)=>{let A=Number(d)-1;return yge(c[A]??l(A),i.get(A)?.format??"decimal")})}gap(){return bw}async image(e){let r=HA(e,"a:blip"),n=HA(e,"v:imagedata"),i=HA(e,"wp:extent"),o=(0,z.numberAttr)(i,"cx"),s=(0,z.numberAttr)(i,"cy"),a={width:o?this.pt(o/m$):void 0,height:s?this.pt(s/m$):void 0},c=await this.officePackage.relatedPartById(this.part,(0,z.attr)(HA(e,"c:chart"),"r:id"));if(c){let u=(0,hge.renderChartSvg)({root:await this.officePackage.readXml(c),theme:this.theme,colorMap:{},aspect:o&&s?s/o:.6});return u?`<span class="chart"${(0,z.styleAttribute)(a)}>${u}</span>`:""}let l=await this.officePackage.relatedImage(this.part,(0,z.attr)(r,"r:embed")??(0,z.attr)(n,"r:id"));return l?`<img src="${(0,z.escAttr)(l)}" alt=""${(0,z.styleAttribute)(a)}>`:""}async inline(e,r,n){let i="";for(let o of(0,le.xmlChildren)(e)){if(o.name==="w:pPr"||o.name==="mc:Fallback"||o.name==="w:p")continue;if(o.name!=="w:r"){i+=await this.inline(o,r,n);continue}let s=(0,z.styleAttribute)(this.runCss(this.runProps(r,(0,le.xmlChild)(o,"w:rPr"))));for(let a of(0,le.xmlChildren)(o))if(a.name==="w:t"){let c=a.children.map(l=>l.type==="text"?l.text:"").join("");c&&(n.text=!0),i+=`<span${s}>${(0,z.esc)(c)}</span>`}else if(a.name==="w:tab")i+=`<span class="tab"${s}> </span>`;else if(a.name==="w:br"||a.name==="w:cr")(0,z.attr)(a,"w:type")==="page"?n.breaks.push(n.text?"after":"before"):i+="<br>";else if(a.name==="w:drawing"||a.name==="w:pict"||a.name==="mc:AlternateContent"){let c=await this.image(a);c&&(n.objects=!0,i+=c)}}return i}async paragraph(e){let r=(0,le.xmlChild)(e,"w:pPr"),n=qA([this.defaultParagraphProps,...this.styleChain(this.paragraphStyleId(r)).map(T=>T.pPr)]),i=this.numberingLevel(qA([n,r])),o=qA([n,i?.definition.pPr,r]),s=this.runProps(r,(0,le.xmlChild)(r,"w:rPr")),a={objects:!1,breaks:[],text:!1},c=await this.inline(e,r,a),l=o.get("w:spacing"),u=o.get("w:ind"),d=(0,z.numberAttr)(l,"w:line"),A=(0,z.attr)(l,"w:lineRule")??"auto",p=(0,z.numberAttr)(u,"w:hanging"),h=(0,z.numberAttr)(u,"w:firstLine"),f=this.runCss(s),E=(0,z.styleAttribute)({"text-align":mge[(0,z.attr)(o.get("w:jc"),"w:val")??""],"margin-top":(0,z.attr)(l,"w:beforeAutospacing")==="1"?this.pt(14):this.twips((0,z.numberAttr)(l,"w:before")),"margin-bottom":(0,z.attr)(l,"w:afterAutospacing")==="1"?this.pt(14):this.twips((0,z.numberAttr)(l,"w:after")),"line-height":d===void 0?void 0:A==="auto"?String(Math.round(d/240*1.15*1e3)/1e3):this.twips(d),"margin-left":this.twips((0,z.numberAttr)(u,"w:left")??(0,z.numberAttr)(u,"w:start")),"margin-right":this.twips((0,z.numberAttr)(u,"w:right")??(0,z.numberAttr)(u,"w:end")),"text-indent":p?`-${this.twips(p)}`:this.twips(h),background:Cw(o.get("w:shd")),"border-top":pu((0,le.xmlChild)(o.get("w:pBdr"),"w:top"),this.pt),"border-bottom":pu((0,le.xmlChild)(o.get("w:pBdr"),"w:bottom"),this.pt),"font-size":f["font-size"],"font-family":f["font-family"],color:f.color}),S=i?`<span class="marker"${(0,z.styleAttribute)({...this.runCss(this.runProps(r,i.definition.rPr)),"min-width":p?this.twips(p):void 0})}>${(0,z.esc)(this.numberingMarker(i))}${p?"":" "}</span>`:"",B=`<div class="p"${E}>${S}${c}<br></div>`,_=(0,z.isOn)(o.get("w:pageBreakBefore"))||a.breaks.includes("before"),v=a.breaks.includes("after")||!!(0,le.xmlChild)(r,"w:sectPr");return`${_?this.gap():""}${B}${v?this.gap():""}`}async table(e){let r=(0,le.xmlChild)(e,"w:tblPr"),n=(0,z.attr)((0,le.xmlChild)(r,"w:tblStyle"),"w:val"),i=qA([...this.styleChain(n).map(u=>u.tblPr),r]),o=i.get("w:tblBorders"),s=u=>pu((0,le.xmlChild)(o,`w:${u}`),this.pt)??(u==="left"?pu((0,le.xmlChild)(o,"w:start"),this.pt):void 0)??(u==="right"?pu((0,le.xmlChild)(o,"w:end"),this.pt):void 0),a=(0,le.xmlChildren)((0,le.xmlChild)(e,"w:tblGrid"),"w:gridCol").map(u=>(0,z.numberAttr)(u,"w:w")??0),c=(0,le.xmlChildren)(e,"w:tr").map(u=>{let d=0;return{row:u,cells:(0,le.xmlChildren)(u,"w:tc").map(A=>{let p=(0,le.xmlChild)(A,"w:tcPr"),h=(0,z.numberAttr)((0,le.xmlChild)(p,"w:gridSpan"),"w:val")??1,f=(0,le.xmlChild)(p,"w:vMerge"),E={cell:A,tcPr:p,column:d,span:h,merge:f?(0,z.attr)(f,"w:val")==="restart"?"restart":"continue":null};return d+=h,E})}}),l=`<table${(0,z.styleAttribute)({"border-collapse":"collapse","margin-left":this.twips((0,z.numberAttr)(i.get("w:tblInd"),"w:w")),"margin-right":(0,z.attr)(i.get("w:jc"),"w:val")==="center"?"auto":void 0,...(0,z.attr)(i.get("w:jc"),"w:val")==="center"?{"margin-left":"auto"}:{}})}><colgroup>${a.map(u=>`<col${(0,z.styleAttribute)({width:this.twips(u)})}>`).join("")}</colgroup>`;for(let[u,{row:d,cells:A}]of c.entries()){let p=(0,z.numberAttr)((0,le.xmlChild)((0,le.xmlChild)(d,"w:trPr"),"w:trHeight"),"w:val");l+=`<tr${(0,z.styleAttribute)({height:this.twips(p)})}>`;for(let h of A){if(h.merge==="continue")continue;let f=1;if(h.merge==="restart")for(let T of c.slice(u+1)){if(!T.cells.some(L=>L.column===h.column&&L.merge==="continue"))break;f+=1}let E=(0,le.xmlChild)(h.tcPr,"w:tcBorders"),S=u+f===c.length,B=h.column+h.span>=a.length,_=(T,L)=>pu((0,le.xmlChild)(E,`w:${T}`),this.pt)??L,v=(0,z.attr)((0,le.xmlChild)(h.tcPr,"w:vAlign"),"w:val");l+=`<td${h.span>1?` colspan="${h.span}"`:""}${f>1?` rowspan="${f}"`:""}${(0,z.styleAttribute)({"border-top":_("top",s(u===0?"top":"insideH")),"border-bottom":_("bottom",s(S?"bottom":"insideH")),"border-left":_("left",h.column===0?s("left"):s("insideV")),"border-right":_("right",s(B?"right":"insideV")),background:Cw((0,le.xmlChild)(h.tcPr,"w:shd")),"vertical-align":v==="center"?"middle":v==="bottom"?"bottom":"top"})}>${(await this.blocks(h.cell)).split(bw).join("")}</td>`}l+="</tr>"}return`${l}</table>`}async blocks(e){let r="";for(let n of(0,le.xmlChildren)(e))n.name==="w:p"?r+=await this.paragraph(n):n.name==="w:tbl"?r+=await this.table(n):n.name==="w:sdt"?r+=await this.blocks((0,le.xmlChild)(n,"w:sdtContent")??n):n.name==="w:customXml"||n.name==="w:ins"?r+=await this.blocks(n):n.name==="mc:AlternateContent"&&(r+=await this.blocks((0,le.xmlChild)(n,"mc:Choice")??n));return r}};async function Ege({officePackage:t,title:e}){let r=await t.readXml($m),n=(0,le.xmlChild)(r,"w:body");if(!r||!n)throw new Error("The file has no Word document body");let i=(0,le.xmlChildren)(n,"w:sectPr").slice(-1)[0],o=(0,le.xmlChild)(i,"w:pgSz"),s=(0,le.xmlChild)(i,"w:pgMar"),a={width:((0,z.numberAttr)(o,"w:w")??12240)/20,height:((0,z.numberAttr)(o,"w:h")??15840)/20,top:Math.abs((0,z.numberAttr)(s,"w:top")??1440)/20,right:((0,z.numberAttr)(s,"w:right")??1440)/20,bottom:Math.abs((0,z.numberAttr)(s,"w:bottom")??1440)/20,left:((0,z.numberAttr)(s,"w:left")??1440)/20},c=await(0,z.readOfficeTheme)(t,await t.relatedPart($m,"/theme")),l=await t.readXml("word/styles.xml"),u=await t.readXml("word/numbering.xml"),d=async(T,L)=>{let k=new Sw(t,c,a,T);return k.loadStyles(l),k.loadNumbering(u),k.blocks(L)},A=async(T,L)=>{let k=(0,le.xmlChildren)(i,T).find(K=>(0,z.attr)(K,"w:type")===L),P=await t.relatedPartById($m,(0,z.attr)(k,"r:id")),U=P?await t.readXml(P):void 0;return P&&U?d(P,U):""},h=((0,z.isOn)((0,le.xmlChild)(i,"w:titlePg"))?await A("w:headerReference","first"):"")||await A("w:headerReference","default"),f=await A("w:footerReference","default"),E=await d($m,n),S=((0,z.numberAttr)(s,"w:header")??720)/20,B=((0,z.numberAttr)(s,"w:footer")??720)/20,_=T=>`${Math.round(T/a.width*1e6)/1e4}cqw`,v=["html,body{margin:0;background:transparent}","body{padding:24px 24px 32px;font-family:Calibri,Arial,sans-serif;color:#000}",`.sheet{max-width:${a.width}pt;margin:0 auto;container-type:inline-size}`,`.page{position:relative;box-sizing:border-box;background:#fff;width:100cqw;min-height:${_(a.height)};padding:${_(a.top)} ${_(a.right)} ${_(a.bottom)} ${_(a.left)};font-size:${_(10)};box-shadow:0 1px 2px rgb(0 0 0/.08),0 2px 8px rgb(0 0 0/.06);overflow-wrap:break-word}`,".p{margin:0}",".p span{white-space:pre-wrap}",".tab{white-space:pre;tab-size:4}",".marker{display:inline-block;text-indent:0;white-space:pre}",".page+.page{margin-top:24px}","img{max-width:100%;vertical-align:bottom}","table{max-width:100%}",`td{padding:0 ${_(5.4)};box-sizing:border-box}`,".chart{display:inline-block;max-width:100%}",`.header,.footer{position:absolute;left:${_(a.left)};right:${_(a.right)}}`,`.header{top:${_(S)}}`,`.footer{bottom:${_(B)}}`].join(`
|
|
791
791
|
`);return(0,z.officeHtmlDocument)({title:e,css:v,body:`<div class="sheet">${E.split(bw).map((T,L,k)=>`<div class="page">${h&&L===0?`<div class="header">${h}</div>`:""}${T}${f&&L===k.length-1?`<div class="footer">${f}</div>`:""}</div>`).join("")}</div>`})}});var b$=y(vw=>{"use strict";Object.defineProperty(vw,"__esModule",{value:!0});vw.renderPptx=Dge;var j=Zo(),H=Ts(),Ige=Dc(),_w=t=>t,Cge={"a:buNone":"bullet","a:buAutoNum":"bullet","a:buChar":"bullet","a:buBlip":"bullet","a:buClrTx":"bulletColor","a:buClr":"bulletColor","a:buSzTx":"bulletSize","a:buSzPct":"bulletSize","a:buSzPts":"bulletSize","a:buFontTx":"bulletFont","a:buFont":"bulletFont","a:solidFill":"fill","a:noFill":"fill","a:gradFill":"fill","a:blipFill":"fill","a:pattFill":"fill","a:normAutofit":"autofit","a:noAutofit":"autofit","a:spAutoFit":"autofit"},bge={l:"left",ctr:"center",r:"right",just:"justify",dist:"justify",justLow:"justify"},Sge={"\xA7":"\u25AA",\u00D8:"\u27A2",\u00FC:"\u2713",q:"\u2751",l:"\u25CF",n:"\u25A0",v:"\u2756",o:"\u25A1","":"\u2022","\xB7":"\u2022"},wge={triangle:"polygon(50% 0,100% 100%,0 100%)",rtTriangle:"polygon(0 0,100% 100%,0 100%)",diamond:"polygon(50% 0,100% 50%,50% 100%,0 50%)",parallelogram:"polygon(25% 0,100% 0,75% 100%,0 100%)",trapezoid:"polygon(25% 0,75% 0,100% 100%,0 100%)",pentagon:"polygon(50% 0,100% 38%,82% 100%,18% 100%,0 38%)",hexagon:"polygon(25% 0,75% 0,100% 50%,75% 100%,25% 100%,0 50%)",octagon:"polygon(29% 0,71% 0,100% 29%,100% 71%,71% 100%,29% 100%,0 71%,0 29%)",homePlate:"polygon(0 0,80% 0,100% 50%,80% 100%,0 100%)",chevron:"polygon(0 0,80% 0,100% 50%,80% 100%,0 100%,20% 50%)",rightArrow:"polygon(0 25%,70% 25%,70% 0,100% 50%,70% 100%,70% 75%,0 75%)",leftArrow:"polygon(30% 0,30% 25%,100% 25%,100% 75%,30% 75%,30% 100%,0 50%)",upArrow:"polygon(50% 0,100% 30%,75% 30%,75% 100%,25% 100%,25% 30%,0 30%)",downArrow:"polygon(25% 0,75% 0,75% 70%,100% 70%,50% 100%,0 70%,25% 70%)"},_ge="{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}",Bge=(0,j.xmlChildren)((0,j.parseXmlDocument)(['<a:tblStyle styleId="{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}">','<a:wholeTbl><a:tcTxStyle><a:schemeClr val="dk1"/></a:tcTxStyle><a:tcStyle><a:tcBdr>',...["left","right","top","bottom","insideH","insideV"].map(t=>`<a:${t}><a:ln w="12700"><a:solidFill><a:schemeClr val="lt1"/></a:solidFill></a:ln></a:${t}>`),'</a:tcBdr><a:fill><a:solidFill><a:schemeClr val="accent1"><a:tint val="20000"/></a:schemeClr></a:solidFill></a:fill></a:tcStyle></a:wholeTbl>','<a:band1H><a:tcStyle><a:fill><a:solidFill><a:schemeClr val="accent1"><a:tint val="40000"/></a:schemeClr></a:solidFill></a:fill></a:tcStyle></a:band1H>','<a:band1V><a:tcStyle><a:fill><a:solidFill><a:schemeClr val="accent1"><a:tint val="40000"/></a:schemeClr></a:solidFill></a:fill></a:tcStyle></a:band1V>',...["lastCol","firstCol","lastRow","firstRow"].map(t=>`<a:${t}><a:tcTxStyle b="on"><a:schemeClr val="lt1"/></a:tcTxStyle><a:tcStyle><a:fill><a:solidFill><a:schemeClr val="accent1"/></a:solidFill></a:fill></a:tcStyle></a:${t}>`),"</a:tblStyle>"].join("")))[0],vge="This object is not shown in the preview.",C$=new Set(["a:srgbClr","a:schemeClr","a:sysClr","a:prstClr"]);function YA(t,e){return{type:"element",name:t,attributes:{},children:e}}function Qge(t){let e=(0,j.xmlChildren)((0,j.xmlPath)(t,"p:style","a:fontRef"))[0];return e?YA("a:defRPr",[YA("a:solidFill",[e])]):void 0}function Ds(t){let e={attributes:{},children:new Map};for(let r of t)if(r){Object.assign(e.attributes,r.attributes);for(let n of(0,j.xmlChildren)(r))e.children.set(Cge[n.name]??n.name,n)}return e}function fu(t){let e=(0,j.xmlChild)(t,"p:nvSpPr")??(0,j.xmlChild)(t,"p:nvPicPr")??(0,j.xmlChild)(t,"p:nvGraphicFramePr"),r=(0,j.xmlPath)(e,"p:nvPr","p:ph");if(r)return{type:(0,H.attr)(r,"type")??"obj",...(0,H.attr)(r,"idx")!==void 0?{idx:(0,H.attr)(r,"idx")}:{}}}function jm(t){return t==="ctrTitle"||t==="title"?"title":t==="dt"||t==="ftr"||t==="sldNum"?t:"body"}function GA(t,e,r){let n=t.filter(o=>fu(o));if(!r&&e.idx!==void 0){let o=n.find(s=>fu(s)?.idx===e.idx);if(o)return o}let i=r?jm(e.type):e.type;return n.find(o=>{let s=fu(o);return(r?jm(s.type):s.type)===i})}function hu(t){return(0,j.xmlPath)(t,"p:spPr","a:xfrm")??(0,j.xmlPath)(t,"p:grpSpPr","a:xfrm")??(0,j.xmlChild)(t,"p:xfrm")}function Fm(t){let e=(0,j.xmlChild)(t,"a:off"),r=(0,j.xmlChild)(t,"a:ext");if(!(!e||!r))return{x:(0,H.numberAttr)(e,"x")??0,y:(0,H.numberAttr)(e,"y")??0,width:(0,H.numberAttr)(r,"cx")??0,height:(0,H.numberAttr)(r,"cy")??0}}function Tge(t,e){let r=o=>String.fromCharCode(97+(o-1)%26),n=o=>{let s=[[1e3,"m"],[900,"cm"],[500,"d"],[400,"cd"],[100,"c"],[90,"xc"],[50,"l"],[40,"xl"],[10,"x"],[9,"ix"],[5,"v"],[4,"iv"],[1,"i"]],a=o,c="";for(let[l,u]of s)for(;a>=l;)c+=u,a-=l;return c},i=e.startsWith("alphaLc")?r(t):e.startsWith("alphaUc")?r(t).toUpperCase():e.startsWith("romanLc")?n(t):e.startsWith("romanUc")?n(t).toUpperCase():String(t);return e.endsWith("ParenBoth")?`(${i})`:e.endsWith("ParenR")?`${i})`:e.endsWith("Plain")?i:`${i}.`}var Bw=class{constructor(e,r,n,i){this.officePackage=e,this.slideWidth=r,this.defaultTextStyle=n,this.tableStyles=i}cq(e){return`${Math.round(e/this.slideWidth*100*1e4)/1e4}cqw`}pt(e){return this.cq(e*12700)}color(e,r,n){return(0,H.drawingColor)({element:r,theme:e.theme,colorMap:e.colorMap,...n?{placeholderColor:n}:{}})}async fill(e,r,n){if(r){if(r.name==="a:noFill")return"transparent";if(r.name==="a:solidFill")return this.color(e,r,n);if(r.name==="a:gradFill"){let i=(0,j.xmlChildren)((0,j.xmlChild)(r,"a:gsLst"),"a:gs").map(s=>{let a=this.color(e,s,n);return a?`${a} ${((0,H.numberAttr)(s,"pos")??0)/1e3}%`:""}).filter(Boolean);return i.length===0?void 0:i.length===1?i[0].split(" ")[0]:`linear-gradient(${((0,H.numberAttr)((0,j.xmlChild)(r,"a:lin"),"ang")??0)/6e4+90}deg,${i.join(",")})`}if(r.name==="a:blipFill"){let i=await this.officePackage.relatedImage(e.part,(0,H.attr)((0,j.xmlChild)(r,"a:blip"),"r:embed"));return i?`center/100% 100% no-repeat url("${i}")`:void 0}}}defaultTextColor(e){let r=e.theme.colors[e.colorMap.tx1??"dk1"];return r&&/^[0-9a-f]{6}$/i.test(r)?`#${r}`:"#000"}styleRefColor(e,r,n){let i=(0,j.xmlPath)(r,"p:style",n);if(!(!i||(0,H.attr)(i,"idx")==="0"))return this.color(e,i)}textStyleLevels({context:e,shape:r,placeholder:n,level:i,styleRunProps:o}){let s=`a:lvl${i+1}pPr`,a=n?GA(e.masterShapes,n,!0):void 0,c=n?GA(e.layoutShapes,n,!1):void 0,l=n&&jm(n.type)==="title"?"p:titleStyle":n&&jm(n.type)==="body"?"p:bodyStyle":"p:otherStyle";return[(0,j.xmlChild)(this.defaultTextStyle,s),(0,j.xmlChild)((0,j.xmlChild)(e.textStyles,l),s),(0,j.xmlChild)((0,j.xmlPath)(a,"p:txBody","a:lstStyle"),s),(0,j.xmlChild)((0,j.xmlPath)(c,"p:txBody","a:lstStyle"),s),o?YA(s,[o]):void 0,(0,j.xmlChild)((0,j.xmlPath)(r,"p:txBody","a:lstStyle"),s)].filter(u=>u!==void 0)}runCss(e,r,n){let i=Number(r.attributes.sz??1800)/100*n,o=Number(r.attributes.baseline??0),s=(0,H.attr)(r.children.get("a:latin"),"typeface"),a=s==="+mj-lt"?e.theme.majorFont:s==="+mn-lt"||!s?e.theme.minorFont:s,c=r.children.get("fill"),l=[r.attributes.u&&r.attributes.u!=="none"?"underline":"",r.attributes.strike&&r.attributes.strike!=="noStrike"?"line-through":""].filter(Boolean),u=r.children.get("a:highlight");return{"font-size":this.pt(o?i*.65:i),"font-weight":r.attributes.b==="1"||r.attributes.b==="true"?"700":"400","font-style":r.attributes.i==="1"||r.attributes.i==="true"?"italic":"normal","text-decoration":l.length>0?l.join(" "):void 0,color:c?.name==="a:solidFill"?this.color(e,c):c?.name==="a:noFill"?"transparent":void 0,"font-family":(0,H.fontStack)(a),"text-transform":r.attributes.cap==="all"?"uppercase":void 0,"font-variant":r.attributes.cap==="small"?"small-caps":void 0,"vertical-align":o>0?"super":o<0?"sub":void 0,"letter-spacing":r.attributes.spc?this.pt(Number(r.attributes.spc)/100):void 0,background:u?this.color(e,u):void 0}}async textBody({context:e,shape:r,body:n,placeholder:i,inheritedBodies:o,styleRunProps:s,defaultColor:a}){let c=Ds([...o,(0,j.xmlChild)(n,"a:bodyPr")]),l=c.children.get("autofit"),u=l?.name==="a:normAutofit"?((0,H.numberAttr)(l,"fontScale")??1e5)/1e5:1,d=l?.name==="a:normAutofit"?((0,H.numberAttr)(l,"lnSpcReduction")??0)/1e5:0,A=[],p="";for(let S of(0,j.xmlChildren)(n,"a:p")){let B=(0,j.xmlChild)(S,"a:pPr"),_=Math.min(Math.max(Math.trunc(Number((0,H.attr)(B,"lvl")??0))||0,0),8),v=this.textStyleLevels({context:e,shape:r,placeholder:i,level:_,styleRunProps:s}),T=Ds([...v,B]),L=v.map(pt=>(0,j.xmlChild)(pt,"a:defRPr")),k=(0,j.xmlChildren)(S).filter(pt=>pt.name==="a:r"||pt.name==="a:fld"||pt.name==="a:br"),P=k.find(pt=>pt.name!=="a:br"),U=Ds([...L,(0,j.xmlChild)(B,"a:defRPr"),(0,j.xmlChild)(P??S,P?"a:rPr":"a:endParaRPr")]),K=this.runCss(e,U,u),Ae=Number(U.attributes.sz??1800)/100*u,Re="";for(let pt of k){if(pt.name==="a:br"){Re+="<br>";continue}let An=Ds([...L,(0,j.xmlChild)(B,"a:defRPr"),(0,j.xmlChild)(pt,"a:rPr")]),Ci=(0,j.xmlChild)(pt,"a:t");Ci&&(Re+=`<span${(0,H.styleAttribute)(this.runCss(e,An,u))}>${(0,H.esc)((0,j.xmlText)(Ci))}</span>`)}let Ge=T.children.get("bullet"),tt=k.some(pt=>pt.name!=="a:br"),Ht="";if(tt&&(A.length=Ge?.name==="a:buAutoNum"?_+1:_),tt&&Ge&&Ge.name!=="a:buNone"){let pt="";if(Ge.name==="a:buChar"){let ra=(0,H.attr)(Ge,"char")??"\u2022",Nl=(0,H.attr)(T.children.get("bulletFont"),"typeface")??"";pt=/wingdings|symbol/i.test(Nl)?Sge[ra]??"\u2022":ra}else Ge.name==="a:buAutoNum"?(A[_]=(A[_]??((0,H.numberAttr)(Ge,"startAt")??1)-1)+1,pt=Tge(A[_],(0,H.attr)(Ge,"type")??"arabicPeriod")):pt="\u2022";let An=T.children.get("bulletSize"),Ci=An?.name==="a:buSzPct"?Ae*(((0,H.numberAttr)(An,"val")??1e5)/1e5):An?.name==="a:buSzPts"?((0,H.numberAttr)(An,"val")??1800)/100*u:Ae,$n=T.children.get("bulletColor"),gs=Number(T.attributes.indent??0);Ht=`<span class="marker"${(0,H.styleAttribute)({"font-size":this.pt(Ci),color:$n?.name==="a:buClr"?this.color(e,$n):K.color,"font-family":/wingdings|symbol/i.test((0,H.attr)(T.children.get("bulletFont"),"typeface")??"")?void 0:K["font-family"],"min-width":gs<0?this.cq(-gs):void 0})}>${(0,H.esc)(pt)}${gs<0?"":" "}</span>`}let Nt=T.children.get("a:lnSpc"),kr=(0,H.numberAttr)((0,j.xmlChild)(Nt,"a:spcPct"),"val"),qr=(0,H.numberAttr)((0,j.xmlChild)(Nt,"a:spcPts"),"val"),Dt=pt=>{let An=T.children.get(pt),Ci=(0,H.numberAttr)((0,j.xmlChild)(An,"a:spcPts"),"val"),$n=(0,H.numberAttr)((0,j.xmlChild)(An,"a:spcPct"),"val");if(Ci!==void 0)return this.pt(Ci/100*(1-d));if($n!==void 0)return`${$n/1e5*1.2}em`};p+=`<div class="tp"${(0,H.styleAttribute)({"text-align":bge[T.attributes.algn??"l"],"margin-left":T.attributes.marL?this.cq(Number(T.attributes.marL)):void 0,"text-indent":T.attributes.indent?this.cq(Number(T.attributes.indent)):void 0,"margin-top":Dt("a:spcBef"),"margin-bottom":Dt("a:spcAft"),"line-height":qr!==void 0?this.pt(qr/100*u):String(Math.round((kr??1e5)/1e5*(1-d)*1.2*1e3)/1e3),"font-size":K["font-size"],"font-family":K["font-family"],color:K.color??a})}>${Ht}${Re}<br></div>`}let h=c.attributes.anchor??"t",f=(S,B)=>this.cq(Number(c.attributes[S]??B)),E=c.attributes.vert;return`<div class="tx"${(0,H.styleAttribute)({"justify-content":h==="ctr"?"center":h==="b"?"flex-end":"flex-start",padding:`${f("tIns",45720)} ${f("rIns",91440)} ${f("bIns",45720)} ${f("lIns",91440)}`,"white-space":c.attributes.wrap==="none"?"pre":void 0,"writing-mode":E==="vert"||E==="eaVert"?"vertical-rl":E==="vert270"?"vertical-lr":void 0,color:a})}>${p}</div>`}boxStyle(e,r,n){let i=((0,H.numberAttr)(r,"rot")??0)/6e4,o=[i?`rotate(${i}deg)`:"",n&&(0,H.attr)(r,"flipH")==="1"?"scaleX(-1)":"",n&&(0,H.attr)(r,"flipV")==="1"?"scaleY(-1)":""].filter(Boolean);return{left:this.cq(e.x),top:this.cq(e.y),width:this.cq(e.width),height:this.cq(e.height),transform:o.length>0?o.join(" "):void 0}}async shape(e,r,n){let i=fu(r),o=i?GA(e.layoutShapes,i,!1):void 0,s=i?GA(e.masterShapes,i,!0):void 0,a=hu(r)??hu(o)??hu(s),c=Fm(a);if(!c)return"";let l=n(c),u=(0,j.xmlChild)(r,"p:spPr"),d=(0,H.attr)((0,j.xmlChild)(u,"a:prstGeom"),"prst")??"rect",A=this.styleRefColor(e,r,"a:fillRef"),p=this.styleRefColor(e,r,"a:lnRef"),h=Ds([u]).children.get("fill"),f=h?await this.fill(e,h,A):A,E=(0,j.xmlChild)(u,"a:ln"),S=Ds([E]).children.get("fill"),B=((0,H.numberAttr)(E,"w")??9525)/12700,_=S?.name==="a:noFill"?void 0:S?.name==="a:solidFill"?this.color(e,S,p):p,v=((0,H.attr)((0,j.xmlChild)(E,"a:prstDash"),"val")??"solid")!=="solid";if(/^(line|straightConnector\d|bentConnector\d|curvedConnector\d)$/.test(d)){if(!_)return"";let U=(0,H.attr)(a,"flipH")==="1",K=(0,H.attr)(a,"flipV")==="1";return`<svg class="sp" viewBox="0 0 100 100" preserveAspectRatio="none"${(0,H.styleAttribute)({...this.boxStyle(l,a,!1),overflow:"visible"})}><line x1="${U?100:0}" y1="${K?100:0}" x2="${U?0:100}" y2="${K?0:100}" stroke="${(0,H.escAttr)(_)}" style="${(0,H.escAttr)(`stroke-width:${this.pt(B)}`)}" vector-effect="non-scaling-stroke"${v?' stroke-dasharray="4 3"':""}/></svg>`}let T=(0,H.attr)((0,j.xmlChildren)((0,j.xmlPath)(u,"a:prstGeom","a:avLst"),"a:gd")[0],"fmla"),L=T?Number(/^val (\d+)$/.exec(T)?.[1]??16667):16667,k=(0,j.xmlChild)(r,"p:txBody"),P=k?await this.textBody({context:e,shape:r,body:k,placeholder:i,inheritedBodies:[(0,j.xmlPath)(s,"p:txBody","a:bodyPr"),(0,j.xmlPath)(o,"p:txBody","a:bodyPr")],styleRunProps:Qge(r),defaultColor:this.defaultTextColor(e)}):"";return`<div class="sp"${(0,H.styleAttribute)({...this.boxStyle(l,a,!1),background:f,border:_?`${this.pt(B)} ${v?"dashed":"solid"} ${_}`:void 0,"border-radius":d==="ellipse"?"50%":d==="roundRect"?this.cq(Math.min(l.width,l.height)*(L/1e5)):void 0,"clip-path":wge[d]})}>${P}</div>`}async picture(e,r,n){let i=fu(r),o=i?GA(e.layoutShapes,i,!1):void 0,s=hu(r)??hu(o),a=Fm(s),c=(0,j.xmlChild)(r,"p:blipFill"),l=await this.officePackage.relatedImage(e.part,(0,H.attr)((0,j.xmlChild)(c,"a:blip"),"r:embed"));if(!a||!l)return"";let u=(0,j.xmlChild)(c,"a:srcRect"),d=((0,H.numberAttr)(u,"l")??0)/1e5,A=((0,H.numberAttr)(u,"t")??0)/1e5,p=((0,H.numberAttr)(u,"r")??0)/1e5,h=((0,H.numberAttr)(u,"b")??0)/1e5,f=Math.max(1-d-p,.01),E=Math.max(1-A-h,.01),S=(0,H.attr)((0,j.xmlPath)(r,"p:spPr","a:prstGeom"),"prst");return`<div class="sp"${(0,H.styleAttribute)({...this.boxStyle(n(a),s,!0),overflow:"hidden","border-radius":S==="ellipse"?"50%":void 0})}><img src="${(0,H.escAttr)(l)}" alt=""${(0,H.styleAttribute)({position:"absolute",left:`${-d/f*100}%`,top:`${-A/E*100}%`,width:`${100/f}%`,height:`${100/E}%`})}></div>`}tableStyle(e){return(0,j.xmlChildren)(this.tableStyles,"a:tblStyle").find(r=>(0,H.attr)(r,"styleId")===e)??(e===_ge?Bge:void 0)}async graphicFrame(e,r,n){let i=hu(r),o=Fm(i);if(!o)return"";let s=n(o),a=(0,j.xmlPath)(r,"a:graphic","a:graphicData","a:tbl");if(!a){let E=await this.officePackage.relatedPartById(e.part,(0,H.attr)((0,j.xmlPath)(r,"a:graphic","a:graphicData","c:chart"),"r:id")),S=E?(0,Ige.renderChartSvg)({root:await this.officePackage.readXml(E),theme:e.theme,colorMap:e.colorMap,aspect:s.height/Math.max(s.width,1)}):void 0;return S?`<div class="sp"${(0,H.styleAttribute)(this.boxStyle(s,i,!1))}>${S}</div>`:`<div class="sp unshown"${(0,H.styleAttribute)(this.boxStyle(s,i,!1))}><span>${(0,H.esc)(vge)}</span></div>`}let c=(0,j.xmlChild)(a,"a:tblPr"),l=(0,j.xmlChild)(c,"a:tableStyleId"),u=l?this.tableStyle((0,j.xmlText)(l)):void 0,d=E=>(0,H.attr)(c,E)==="1"||(0,H.attr)(c,E)==="true",A=(0,j.xmlChildren)((0,j.xmlChild)(a,"a:tblGrid"),"a:gridCol").map(E=>(0,H.numberAttr)(E,"w")??0),p=(0,j.xmlChildren)(a,"a:tr"),h=(E,S)=>{let B=["a:wholeTbl"],_=E-(d("firstRow")?1:0);return d("bandRow")&&_>=0&&B.push(_%2===0?"a:band1H":"a:band2H"),d("bandCol")&&B.push(S%2===0?"a:band1V":"a:band2V"),d("firstCol")&&S===0&&B.push("a:firstCol"),d("lastCol")&&S===A.length-1&&B.push("a:lastCol"),d("lastRow")&&E===p.length-1&&B.push("a:lastRow"),d("firstRow")&&E===0&&B.push("a:firstRow"),B.map(v=>(0,j.xmlChild)(u,v)).filter(Boolean)},f=`<table class="sp tbl"${(0,H.styleAttribute)({left:this.cq(s.x),top:this.cq(s.y),width:this.cq(s.width)})}><colgroup>${A.map(E=>`<col${(0,H.styleAttribute)({width:this.cq(E)})}>`).join("")}</colgroup>`;for(let[E,S]of p.entries()){f+=`<tr${(0,H.styleAttribute)({height:this.cq((0,H.numberAttr)(S,"h")??0)})}>`;for(let[B,_]of(0,j.xmlChildren)(S,"a:tc").entries()){if((0,H.attr)(_,"hMerge")==="1"||(0,H.attr)(_,"vMerge")==="1")continue;let v=(0,j.xmlChild)(_,"a:tcPr"),T=h(E,B),L=T.map(Dt=>(0,j.xmlPath)(Dt,"a:tcStyle","a:fill")).filter(Boolean).slice(-1)[0],k=Ds([v]).children.get("fill"),P=k?await this.fill(e,k):await this.fill(e,(0,j.xmlChildren)(L)[0]),U=T.map(Dt=>(0,j.xmlChild)(Dt,"a:tcTxStyle")).filter(Dt=>Dt!==void 0),K=U.map(Dt=>(0,j.xmlChildren)(Dt).find(pt=>C$.has(pt.name))??(0,j.xmlChildren)((0,j.xmlChild)(Dt,"a:fontRef")).find(pt=>C$.has(pt.name))).filter(Dt=>Dt!==void 0).slice(-1)[0],Ae=U.some(Dt=>(0,H.attr)(Dt,"b")==="on"),Re={...YA("a:defRPr",K?[YA("a:solidFill",[K])]:[]),attributes:Ae?{b:"1"}:{}},Ge=T.map(Dt=>(0,j.xmlPath)(Dt,"a:tcStyle","a:tcBdr")),tt=(Dt,pt,An)=>{let Ci=(0,j.xmlChild)(v,`a:ln${Dt[0].toUpperCase()}`),$n=Ge.map(_C=>(0,j.xmlChild)((0,j.xmlChild)(_C,An?`a:${Dt}`:`a:${pt}`),"a:ln")).filter(Boolean).slice(-1)[0],gs=Ci??$n;if(!gs)return;let ra=Ds([gs]).children.get("fill");if(!ra||ra.name==="a:noFill")return"none";let Nl=this.color(e,ra);return Nl?`${this.pt(((0,H.numberAttr)(gs,"w")??12700)/12700)} solid ${Nl}`:void 0},Ht=(0,H.numberAttr)(_,"gridSpan")??1,Nt=(0,H.numberAttr)(_,"rowSpan")??1,kr=(0,j.xmlChild)(_,"a:txBody"),qr=kr?await this.textBody({context:e,shape:_,body:kr,placeholder:void 0,inheritedBodies:[],styleRunProps:Re,defaultColor:this.defaultTextColor(e)}):"";f+=`<td${Ht>1?` colspan="${Ht}"`:""}${Nt>1?` rowspan="${Nt}"`:""}${(0,H.styleAttribute)({background:P,"border-top":tt("top","insideH",E===0),"border-bottom":tt("bottom","insideH",E+Nt>=p.length),"border-left":tt("left","insideV",B===0),"border-right":tt("right","insideV",B+Ht>=A.length),"vertical-align":(0,H.attr)(v,"anchor")==="ctr"?"middle":(0,H.attr)(v,"anchor")==="b"?"bottom":"top"})}>${qr}</td>`}f+="</tr>"}return`${f}</table>`}async shapes(e,r,n,i){let o="";for(let s of(0,j.xmlChildren)(r)){let a=(0,j.xmlChildren)(s).find(c=>c.name.startsWith("p:nv"));if((0,H.attr)((0,j.xmlChild)(a,"p:cNvPr"),"hidden")!=="1"&&!(!i&&fu(s))){if(s.name==="p:sp"||s.name==="p:cxnSp")o+=await this.shape(e,s,n);else if(s.name==="p:pic")o+=await this.picture(e,s,n);else if(s.name==="p:graphicFrame")o+=await this.graphicFrame(e,s,n);else if(s.name==="p:grpSp"){let c=(0,j.xmlPath)(s,"p:grpSpPr","a:xfrm"),l=Fm(c),u=(0,j.xmlChild)(c,"a:chOff"),d=(0,j.xmlChild)(c,"a:chExt"),A=l&&d?l.width/((0,H.numberAttr)(d,"cx")||l.width||1):1,p=l&&d?l.height/((0,H.numberAttr)(d,"cy")||l.height||1):1,h=l?f=>n({x:l.x+(f.x-((0,H.numberAttr)(u,"x")??0))*A,y:l.y+(f.y-((0,H.numberAttr)(u,"y")??0))*p,width:f.width*A,height:f.height*p}):n;o+=await this.shapes(e,s,h,i)}else if(s.name==="mc:AlternateContent"){let c=(0,j.xmlChild)(s,"mc:Fallback"),l=c&&(0,j.xmlChildren)(c).every(u=>u.name==="p:pic");o+=await this.shapes(e,l?c:(0,j.xmlChild)(s,"mc:Choice"),n,i)}}}return o}async background(e,r){for(let{part:n,root:i}of r){let o=(0,j.xmlPath)(i,"p:cSld","p:bg");if(!o)continue;let s={...e,part:n},a=(0,j.xmlChild)(o,"p:bgPr");if(a){let l=Ds([a]).children.get("fill");return this.fill(s,l)}let c=(0,j.xmlChild)(o,"p:bgRef");if(c)return this.color(s,c)}}async slide(e){let r=await this.officePackage.readXml(e);if(!r)return"";let n=await this.officePackage.relatedPart(e,"/slideLayout"),i=n?await this.officePackage.readXml(n):void 0,o=n?await this.officePackage.relatedPart(n,"/slideMaster"):void 0,s=o?await this.officePackage.readXml(o):void 0,a=await(0,H.readOfficeTheme)(this.officePackage,o?await this.officePackage.relatedPart(o,"/theme"):void 0),c=(0,j.xmlPath)(i,"p:cSld","p:spTree"),l=(0,j.xmlPath)(s,"p:cSld","p:spTree"),u={part:e,layoutShapes:(0,j.xmlChildren)(c),masterShapes:(0,j.xmlChildren)(l),textStyles:(0,j.xmlChild)(s,"p:txStyles"),theme:a,colorMap:(0,j.xmlChild)(s,"p:clrMap")?.attributes??{}},d=await this.background(u,[{part:e,root:r},...n?[{part:n,root:i}]:[],...o?[{part:o,root:s}]:[]]),A=(0,H.attr)(r,"showMasterSp")!=="0",p=A&&o&&(0,H.attr)(i,"showMasterSp")!=="0"?await this.shapes({...u,part:o},l,_w,!1):"",h=A&&n?await this.shapes({...u,part:n},c,_w,!1):"",f=await this.shapes(u,(0,j.xmlPath)(r,"p:cSld","p:spTree"),_w,!0);return`<section class="slide"${(0,H.styleAttribute)({background:d??"#fff","font-family":(0,H.fontStack)(a.minorFont)})}>${p}${h}${f}</section>`}};async function Dge({officePackage:t,title:e,slide:r}){let n="ppt/presentation.xml",i=await t.readXml(n);if(!i)throw new Error("The file has no PowerPoint presentation");let o=(0,j.xmlChild)(i,"p:sldSz"),s=(0,H.numberAttr)(o,"cx")??12192e3,a=(0,H.numberAttr)(o,"cy")??6858e3,c=await t.rels(n),l=(0,j.xmlChildren)((0,j.xmlChild)(i,"p:sldIdLst"),"p:sldId").map(p=>c.get((0,H.attr)(p,"r:id")??"")?.target).filter(p=>p!==void 0),u=new Bw(t,s,(0,j.xmlChild)(i,"p:defaultTextStyle"),await t.readXml("ppt/tableStyles.xml"));if(r!==void 0&&(r<1||r>l.length))throw new Error(`Slide ${r} does not exist. The presentation has ${l.length} slides.`);let d="";for(let p of r===void 0?l:[l[r-1]])d+=await u.slide(p);let A=["html,body{margin:0;background:transparent}","body{padding:24px 24px 8px;color:#000}",`.slide{position:relative;container-type:inline-size;width:100%;max-width:1100px;aspect-ratio:${s}/${a};margin:0 auto 24px;overflow:hidden;box-shadow:0 1px 2px rgb(0 0 0/.08),0 2px 8px rgb(0 0 0/.06)}`,".sp{position:absolute;box-sizing:border-box;margin:0}",".tx{display:flex;flex-direction:column;box-sizing:border-box;height:100%;overflow:visible}",".tp{margin:0;overflow-wrap:break-word}",".tp span{white-space:pre-wrap}",".marker{display:inline-block;text-indent:0;white-space:pre}",".tbl{border-collapse:collapse;table-layout:fixed}",".tbl td{padding:0;overflow:hidden}",".unshown{display:flex;align-items:center;justify-content:center;border:1px dashed #9ca3af;color:#6b7280;font:12px/1.4 system-ui,sans-serif;text-align:center;padding:8px}"].join(`
|
|
792
|
-
`);return(0,H.officeHtmlDocument)({title:e,css:A,body:d})}});var T$=y(gu=>{"use strict";Object.defineProperty(gu,"__esModule",{value:!0});gu.BUILT_IN_FORMATS=void 0;gu.formatCellNumber=Uge;gu.formatCellText=Mge;gu.BUILT_IN_FORMATS={0:"General",1:"0",2:"0.00",3:"#,##0",4:"#,##0.00",5:'"$"#,##0_);("$"#,##0)',6:'"$"#,##0_);[Red]("$"#,##0)',7:'"$"#,##0.00_);("$"#,##0.00)',8:'"$"#,##0.00_);[Red]("$"#,##0.00)',9:"0%",10:"0.00%",11:"0.00E+00",12:"# ?/?",13:"# ??/??",14:"SHORT_DATE",15:"d-mmm-yy",16:"d-mmm",17:"mmm-yy",18:"h:mm AM/PM",19:"h:mm:ss AM/PM",20:"h:mm",21:"h:mm:ss",22:"SHORT_DATE h:mm",37:"#,##0 ;(#,##0)",38:"#,##0 ;[Red](#,##0)",39:"#,##0.00;(#,##0.00)",40:"#,##0.00;[Red](#,##0.00)",41:'_(* #,##0_);_(* \\(#,##0\\);_(* "-"_);_(@_)',42:'_("$"* #,##0_);_("$"* \\(#,##0\\);_("$"* "-"_);_(@_)',43:'_(* #,##0.00_);_(* \\(#,##0.00\\);_(* "-"??_);_(@_)',44:'_("$"* #,##0.00_);_("$"* \\(#,##0.00\\);_("$"* "-"??_);_(@_)',45:"mm:ss",46:"[h]:mm:ss",47:"mm:ss.0",48:"##0.0E+0",49:"@"};var S$={black:"#000000",blue:"#0000ff",cyan:"#00ffff",green:"#00ff00",magenta:"#ff00ff",red:"#ff0000",white:"#ffffff",yellow:"#ffff00"},Qw=["January","February","March","April","May","June","July","August","September","October","November","December"],w$=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function v$(t){let e=[],r="",n=!1,i=!1;for(let o=0;o<t.length;o+=1){let s=t[o];if(s==="\\"&&!n){r+=s+(t[o+1]??""),o+=1;continue}if(s==='"'&&(n=!n),!n&&s==="["&&(i=!0),!n&&s==="]"&&(i=!1),s===";"&&!n&&!i){e.push(r),r="";continue}r+=s}return e.push(r),e}function Tw(t){let e=[],r,n=!1,i=o=>{let s=e[e.length-1];s?.kind==="literal"?s.value+=o:e.push({kind:"literal",value:o})};for(let o=0;o<t.length;o+=1){let s=t[o],a=/^(AM\/PM|A\/P|General|E[+-])/i.exec(t.slice(o));if(a){e.push({kind:"code",value:a[0].toLowerCase()}),o+=a[0].length-1;continue}if(s==='"'){let c=t.indexOf('"',o+1);i(t.slice(o+1,c===-1?t.length:c)),o=c===-1?t.length:c}else if(s==="\\")i(t[o+1]??""),o+=1;else if(s==="_")i(" "),o+=1;else if(s==="*")o+=1;else if(s==="["){let c=t.indexOf("]",o),l=t.slice(o+1,c===-1?t.length:c);o=c===-1?t.length:c,/^\$/.test(l)?i(l.slice(1).split("-")[0]):S$[l.toLowerCase()]?r=S$[l.toLowerCase()]:/^(h+|m+|s+)$/i.test(l)&&(n=!0,e.push({kind:"code",value:`[${l.toLowerCase()}]`}))}else/[0#?.,%]/.test(s)||/[dmyhs]/i.test(s)||s==="@"?e.push({kind:"code",value:s}):i(s)}return{tokens:e,...r?{color:r}:{},elapsed:n}}function kge(t){return t.some(e=>e.kind==="code"&&/^[dmyhs]$|^\[/i.test(e.value))}function Q$(t,e){let r=e?t+1462:t,n=Math.round((r-25569)*86400*1e3);return new Date(n)}function kc(t,e){return String(t).padStart(e,"0")}function _$(t,e,r,n){let i=Q$(t,r),o=[],{tokens:s}=Tw(e),a="",c=()=>{if(!a)return;let A=/am\/pm|a\/p|\[h+\]|\[m+\]|\[s+\]|yyyy|yy|mmmmm|mmmm|mmm|mm|m|dddd|ddd|dd|d|hh|h|ss|s|\.0+|./gi;for(let p of a.match(A)??[])o.push({token:p});a=""};for(let A of s)A.kind==="literal"?(c(),o.push({token:A.value,literal:!0})):a+=A.value;c();let l=o.some(A=>!A.literal&&/^(am\/pm|a\/p)$/i.test(A.token)),u=i.getUTCHours(),d=Math.round(t*86400);return o.map((A,p)=>{if(A.literal)return A.token;let h=A.token.toLowerCase(),f=o.slice(0,p).reverse().find(B=>!B.literal&&/^\[?[hms]/i.test(B.token)),E=o.slice(p+1).find(B=>!B.literal&&/^\[?[hms]/i.test(B.token)),S=f&&/^\[?h/i.test(f.token)||E&&/^\[?s/i.test(E.token);if(n&&h.startsWith("[h"))return String(Math.floor(d/3600));if(n&&h.startsWith("[m"))return String(Math.floor(d/60));if(n&&h.startsWith("[s"))return String(d);switch(h){case"yyyy":return String(i.getUTCFullYear());case"yy":return kc(i.getUTCFullYear()%100,2);case"mmmmm":return Qw[i.getUTCMonth()][0];case"mmmm":return Qw[i.getUTCMonth()];case"mmm":return Qw[i.getUTCMonth()].slice(0,3);case"mm":return kc(S?i.getUTCMinutes():i.getUTCMonth()+1,2);case"m":return String(S?i.getUTCMinutes():i.getUTCMonth()+1);case"dddd":return w$[i.getUTCDay()];case"ddd":return w$[i.getUTCDay()].slice(0,3);case"dd":return kc(i.getUTCDate(),2);case"d":return String(i.getUTCDate());case"hh":return kc(l?u%12||12:u,2);case"h":return String(l?u%12||12:u);case"ss":return kc(i.getUTCSeconds(),2);case"s":return String(i.getUTCSeconds());case"am/pm":return u<12?"AM":"PM";case"a/p":return u<12?"A":"P";default:return h.startsWith(".")?`.${String(i.getUTCMilliseconds()).padStart(3,"0").slice(0,h.length-1)}`:A.token}}).join("")}function zm(t){if(Number.isInteger(t)&&Math.abs(t)<1e11)return String(t);let e=Math.abs(t);return e!==0&&(e>=1e11||e<1e-9)?t.toExponential(5).replace(/\.?0+e/,"E").replace("e","E"):String(Number(t.toPrecision(10)))}function Rge(t,e){let r=+`${t}e${e}`;return Number.isFinite(r)?Math.round(r)/10**e:t}var Ko=/^[0#?]$/;function Nge(t,e){let r=t.filter(s=>Ko.test(s.value)).length,n=e==="0"?"":e,i=0,o="";for(let s=t.length-1;s>=0;s-=1){let a=t[s];if(!Ko.test(a.value)){o=(a.kind==="literal"?a.value:"")+o;continue}i+=1;let c=n.slice(-1);n=n.slice(0,-1);let l=c||(a.value==="0"?"0":a.value==="?"?" ":"");o=(i===r?n+l:l)+o,i===r&&(n="")}return o}function Oge(t,e){let r=-1,n=0;return t.forEach((i,o)=>{Ko.test(i.value)&&((e[n]!=="0"||i.value==="0")&&(r=o),n+=1)}),n=0,t.map((i,o)=>{if(!Ko.test(i.value))return i.kind==="literal"?i.value:"";let s=e[n];return n+=1,o>r?i.value==="?"?" ":"":s}).join("")}function xge(t,e){if(e.some(k=>k.value==="general"))return e.map(k=>k.value==="general"?zm(t):k.value).join("");let r=e.map((k,P)=>k.kind==="code"&&Ko.test(k.value)?P:-1).filter(k=>k!==-1);if(r.length===0)return e.map(k=>k.value==="@"?zm(t):k.value).join("");let n=t*100**e.filter(k=>k.kind==="code"&&k.value==="%").length,i=r[0],o=r[r.length-1],s=e.findIndex(k=>k.value==="e+"||k.value==="e-"),a=s===-1?o:s-1,c=e.slice(i,a+1),l=c.findIndex(k=>k.kind==="code"&&k.value==="."),u=l===-1?c:c.slice(0,l),d=l===-1?[]:c.slice(l+1),A=c.reduce((k,P,U)=>Ko.test(P.value)?U:k,-1),p=e.slice(i+A+1,s===-1?void 0:s).filter(k=>k.kind==="code"&&k.value===",").length;n/=1e3**p;let h=u.some((k,P)=>k.value===","&&u.slice(P+1).some(U=>Ko.test(U.value))),f=d.filter(k=>Ko.test(k.value)).length,E=e.slice(0,i).map(k=>k.value).join(""),S=e.slice((s===-1?o:e.length)+1).filter(k=>k.value!==",").map(k=>k.value).join("");if(s!==-1){let k=e.slice(s+1).filter(Re=>Ko.test(Re.value)).length||1,[P,U]=n.toExponential(f).split("e"),K=Number(U),Ae=K<0?"-":e[s].value==="e+"?"+":"";return`${E}${P}E${Ae}${kc(Math.abs(K),k)}${S}`}let[B,_=""]=Rge(n,f).toFixed(f).split("."),v=u.filter(k=>k.value!==","),T=h?`${v.slice(0,v.findIndex(k=>Ko.test(k.value))).map(k=>k.value).join("")}${(B==="0"&&!u.some(k=>k.value==="0")?"":B.padStart(u.filter(k=>k.value==="0").length,"0")).replace(/\B(?=(\d{3})+(?!\d))/g,",")}`:Nge(v,B),L=l===-1?"":`.${Oge(d,_)}`;return`${E}${T}${L}${S}`}function B$(t,e){return new Intl.DateTimeFormat(void 0,{year:"numeric",month:"numeric",day:"numeric",timeZone:"UTC"}).format(Q$(t,e))}function Uge({value:t,code:e,date1904:r}){if(!e||/^general$/i.test(e))return{text:zm(t)};if(e==="SHORT_DATE")return{text:B$(t,r)};if(e==="SHORT_DATE h:mm")return{text:`${B$(t,r)} ${_$(t,"h:mm",r,!1)}`};let n=v$(e);if(n.map(A=>/^\[[<>=]/.test(A.trim())).some(Boolean))return{text:zm(t)};let o=n[0],s=t;t<0&&n.length>1?(o=n[1],s=Math.abs(t)):t===0&&n.length>2&&(o=n[2]);let{tokens:a,color:c,elapsed:l}=Tw(o);if(a.every(A=>A.kind==="literal"))return{text:a.map(A=>A.value).join(""),...c?{color:c}:{}};if(kge(a))return{text:_$(s,o,r,l),...c?{color:c}:{}};let u=xge(Math.abs(s),a);return{text:`${s<0&&!(t<0&&n.length>1)?"-":""}${u}`,...c?{color:c}:{}}}function Mge({value:t,code:e}){let r=v$(e),n=r.length>=4?r[3]:r.find(s=>s.includes("@"));if(!n)return{text:t};let{tokens:i,color:o}=Tw(n);return{text:i.map(s=>s.kind==="code"&&s.value==="@"?t:s.value).join(""),...o?{color:o}:{}}}});var Gm=y(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.WorkbookStyles=Kt.MAX_PREVIEW_COLUMNS=Kt.MAX_PREVIEW_ROWS=void 0;Kt.columnName=xw;Kt.parseReference=Uw;Kt.readWorksheet=N$;Kt.parseCell=x$;Kt.openWorkbook=U$;Kt.loadXlsx=Vge;var Pge=Dc(),W=Ts(),kw=T$(),te=Zo();Kt.MAX_PREVIEW_ROWS=2e3;Kt.MAX_PREVIEW_COLUMNS=200;var Ow=1048576,R$=16384,Lge=/("(?:[^"]|"")*"|'(?:[^']|'')*')/,$ge=/(^|[^A-Za-z0-9_.])(\$?)([A-Z]{1,3})(\$?)(\d{1,7})(?![A-Za-z0-9_(])/g,VA="xl/workbook.xml",qm=40,Dw=20,Ca=9525,Fge=["lt1","dk1","lt2","dk2","accent1","accent2","accent3","accent4","accent5","accent6","hlink","folHlink"],jge=["000000","FFFFFF","FF0000","00FF00","0000FF","FFFF00","FF00FF","00FFFF","000000","FFFFFF","FF0000","00FF00","0000FF","FFFF00","FF00FF","00FFFF","800000","008000","000080","808000","800080","008080","C0C0C0","808080","9999FF","993366","FFFFCC","CCFFFF","660066","FF8080","0066CC","CCCCFF","000080","FF00FF","FFFF00","00FFFF","800080","800000","008080","0000FF","00CCFF","CCFFFF","CCFFCC","FFFF99","99CCFF","FF99CC","CC99FF","FFCC99","3366FF","33CCCC","99CC00","FFCC00","FF9900","FF6600","666699","969696","003366","339966","003300","333300","993300","993366","333399","333333"],zge={thin:"1px solid",hair:"1px solid",medium:"2px solid",thick:"3px solid",dashed:"1px dashed",mediumDashed:"2px dashed",dotted:"1px dotted",double:"3px double",dashDot:"1px dashed",mediumDashDot:"2px dashed",dashDotDot:"1px dotted",mediumDashDotDot:"2px dotted",slantDashDot:"2px dashed"},D$={left:"left",center:"center",centerContinuous:"center",right:"right",justify:"justify",distributed:"justify",fill:"left"},qge={top:"top",center:"middle",justify:"middle",distributed:"middle",bottom:"bottom"};function xw(t){let e="",r=t+1;for(;r>0;){let n=(r-1)%26;e=String.fromCharCode(65+n)+e,r=Math.floor((r-1)/26)}return e}function Rw(t){return t.toUpperCase().split("").reduce((e,r)=>e*26+r.charCodeAt(0)-64,0)-1}function Uw(t){let e=/^\$?([A-Z]{1,3})\$?(\d{1,7})$/i.exec(t);if(!e)return;let r=Number(e[2])-1,n=Rw(e[1]);if(!(r<0||r>=Ow||n>=R$))return{row:r,column:n}}function Hge({formula:t,rows:e,columns:r}){return t.split(Lge).map((n,i)=>i%2===1?n:n.replace($ge,(o,s,a,c,l,u)=>{let d=a?Rw(c):Rw(c)+r,A=l?Number(u):Number(u)+e;return d<0||d>=R$||A<1||A>Ow?`${s}#REF!`:`${s}${a}${xw(d)}${l}${A}`})).join("")}function*Gge(t){let e=new Map,r=(i,o,s)=>{let a=(0,te.xmlChild)(i,"f");if(!a)return;let c=(0,te.xmlText)(a);if((0,W.attr)(a,"t")!=="shared")return c||void 0;let l=(0,W.attr)(a,"si")??"";if(c)return e.set(l,{formula:c,row:o,column:s}),c;let u=e.get(l);return u?Hge({formula:u.formula,rows:o-u.row,columns:s-u.column}):void 0},n=-1;for(let i of t){let o=(0,W.numberAttr)(i,"r"),s=o!==void 0&&Number.isInteger(o)&&o>=1&&o<=Ow?o-1:n+1;n=s;let a=[],c=0;for(let l of(0,te.xmlChildren)(i,"c")){let u=Uw((0,W.attr)(l,"r")??"")??{row:s,column:c};c=u.column+1;let d=r(l,u.row,u.column);a.push({element:l,...u,...d?{formula:d}:{}})}yield{element:i,index:s,cells:a}}}async function N$(t,e){let r=await t.readText(e);if(r===void 0)throw new Error(`The workbook has no worksheet part ${e}`);let{root:n,elements:i}=(0,te.streamXmlElements)({xml:r,container:"sheetData",element:"row"});if(!n)throw new Error(`The worksheet part ${e} is empty`);return{worksheet:n,rows:()=>Gge(i())}}function Yge({text:t,html:e,width:r,fontSize:n}){let i=(Number.parseFloat(n)||11)*4/3*.55,o=r-6;return t.length*i<=o?e:"#".repeat(Math.max(1,Math.floor(o/i)))}function ba(t,e){let r=(0,te.xmlChild)(t,e);return r&&Number((0,te.xmlText)(r))||0}function k$(t){return Math.max(0,Math.trunc(t*7+5))}var Hm=class{constructor(e){this.theme=e,this.fonts=[],this.fills=[],this.borders=[],this.formats=[],this.numberFormats=new Map}color(e){if(!e||(0,W.attr)(e,"auto")==="1")return;let r,n=(0,W.attr)(e,"rgb");n&&/^[0-9a-f]{6,8}$/i.test(n)&&(r=n.slice(-6));let i=(0,W.numberAttr)(e,"theme");i!==void 0&&(r=this.theme.colors[Fge[i]??""]);let o=(0,W.numberAttr)(e,"indexed");if(o!==void 0&&(r=jge[o]),!r||!/^[0-9a-f]{6}$/i.test(r))return;let s=(0,W.numberAttr)(e,"tint");return s?(0,W.tintedColor)(r,s):`#${r.toLowerCase()}`}load(e){for(let r of(0,te.xmlChildren)((0,te.xmlChild)(e,"numFmts"),"numFmt")){let n=(0,W.numberAttr)(r,"numFmtId"),i=(0,W.attr)(r,"formatCode");n!==void 0&&i!==void 0&&this.numberFormats.set(n,i)}this.fonts=(0,te.xmlChildren)((0,te.xmlChild)(e,"fonts"),"font").map(r=>{let n=(0,te.xmlChild)(r,"u"),i=(0,W.numberAttr)((0,te.xmlChild)(r,"sz"),"val"),o=(0,W.attr)((0,te.xmlChild)(r,"name"),"val"),s=a=>!!a&&!["0","false"].includes((0,W.attr)(a,"val")??"");return{css:{"font-weight":s((0,te.xmlChild)(r,"b"))?"700":void 0,"font-style":s((0,te.xmlChild)(r,"i"))?"italic":void 0,"text-decoration":[n&&(0,W.attr)(n,"val")!=="none"?"underline":"",s((0,te.xmlChild)(r,"strike"))?"line-through":""].filter(Boolean).join(" ")||void 0,"font-size":i?`${i}pt`:void 0,"font-family":o?(0,W.fontStack)(o):void 0,color:this.color((0,te.xmlChild)(r,"color"))}}}),this.fills=(0,te.xmlChildren)((0,te.xmlChild)(e,"fills"),"fill").map(r=>{let n=(0,te.xmlChild)(r,"patternFill");if(n){let o=(0,W.attr)(n,"patternType");return!o||o==="none"||o==="gray125"?void 0:this.color((0,te.xmlChild)(n,"fgColor"))??this.color((0,te.xmlChild)(n,"bgColor"))}let i=(0,te.xmlChildren)((0,te.xmlChild)(r,"gradientFill"),"stop");return i.length>0?this.color((0,te.xmlChild)(i[0],"color")):void 0}),this.borders=(0,te.xmlChildren)((0,te.xmlChild)(e,"borders"),"border").map(r=>{let n=i=>{let o=(0,te.xmlChild)(r,i),s=zge[(0,W.attr)(o,"style")??""];return s?`${s} ${this.color((0,te.xmlChild)(o,"color"))??"#000"}`:void 0};return{"border-left":n("left")??n("start"),"border-right":n("right")??n("end"),"border-top":n("top"),"border-bottom":n("bottom")}}),this.formats=(0,te.xmlChildren)((0,te.xmlChild)(e,"cellXfs"),"xf").map(r=>{let n=(0,te.xmlChild)(r,"alignment"),i=(0,W.attr)(n,"horizontal"),o=(0,W.numberAttr)(n,"indent"),s=(0,W.numberAttr)(r,"numFmtId")??0;return{numberFormat:this.numberFormats.get(s)??kw.BUILT_IN_FORMATS[s]??"General",css:{...this.fonts[(0,W.numberAttr)(r,"fontId")??0]?.css,background:this.fills[(0,W.numberAttr)(r,"fillId")??0],...this.borders[(0,W.numberAttr)(r,"borderId")??0],"vertical-align":qge[(0,W.attr)(n,"vertical")??"bottom"],"padding-left":o?`${3+o*9}px`:void 0},...i&&D$[i]?{horizontal:D$[i]}:{},wrap:(0,W.attr)(n,"wrapText")==="1"||(0,W.attr)(n,"wrapText")==="true"}})}format(e){return this.formats[e??0]??this.formats[0]??{numberFormat:"General",css:{},wrap:!1}}defaultFont(){return this.fonts[0]?.css??{}}};Kt.WorkbookStyles=Hm;function O$(t,e){if(!t)return{html:"",text:""};let r=(0,te.xmlChildren)(t,"r");if(r.length===0){let o=(0,te.xmlChildren)(t,"t").map(te.xmlText).join("");return{html:(0,W.esc)(o),text:o}}let n="",i="";for(let o of r){let s=(0,te.xmlChildren)(o,"t").map(te.xmlText).join(""),a=(0,te.xmlChild)(o,"rPr"),c=(0,W.numberAttr)((0,te.xmlChild)(a,"sz"),"val");n+=`<span${(0,W.styleAttribute)({"font-weight":(0,te.xmlChild)(a,"b")?"700":void 0,"font-style":(0,te.xmlChild)(a,"i")?"italic":void 0,"text-decoration":(0,te.xmlChild)(a,"u")?"underline":void 0,"font-size":c?`${c}pt`:void 0,color:e.color((0,te.xmlChild)(a,"color"))})}>${(0,W.esc)(s)}</span>`,i+=s}return{html:n,text:i}}function x$({context:t,cell:{element:e,row:r,column:n,formula:i}}){let o=t.styles.format((0,W.numberAttr)(e,"s")),s=(0,W.attr)(e,"t")??"n",a=(0,te.xmlChild)(e,"v"),c=a?(0,te.xmlText)(a):void 0,l={row:r,column:n,format:o,...i?{formula:i}:{}};if(s==="s"&&c!==void 0){let A=t.sharedStrings[Number(c)]??{html:"",text:""};return{...l,...A,value:A.text,kind:"text"}}if(s==="inlineStr"){let A=O$((0,te.xmlChild)(e,"is"),t.styles);return{...l,...A,value:A.text,kind:"text"}}if((c===void 0||c==="")&&i){let A=`=${i}`;return{...l,html:(0,W.esc)(A),text:A,value:null,kind:"text",color:"#8c8c8c"}}if(c===void 0||c==="")return{...l,html:"",text:"",value:null,kind:"empty"};if(s==="b"){let A=c==="1"?"TRUE":"FALSE";return{...l,html:A,text:A,value:c==="1",kind:"boolean"}}if(s==="e")return{...l,html:(0,W.esc)(c),text:c,value:c,kind:"error"};if(s==="str"||s==="d"){let A=(0,kw.formatCellText)({value:c,code:o.numberFormat});return{...l,html:(0,W.esc)(A.text),text:A.text,value:c,kind:"text",...A.color?{color:A.color}:{}}}let u=Number(c);if(!Number.isFinite(u))return{...l,html:(0,W.esc)(c),text:c,value:c,kind:"text"};let d=(0,kw.formatCellNumber)({value:u,code:o.numberFormat,date1904:t.date1904});return{...l,html:(0,W.esc)(d.text),text:d.text,value:u,kind:"number",...d.color?{color:d.color}:{}}}var Nw=class{constructor(e){this.context=e,this.officePackage=e.officePackage,this.styles=e.styles,this.theme=e.theme}cell(e){return x$({context:this.context,cell:e})}async drawings({part:e,worksheet:r,columnOffsets:n,rowOffsets:i}){let o=await this.officePackage.relatedPartById(e,(0,W.attr)((0,te.xmlChild)(r,"drawing"),"r:id")),s=o?await this.officePackage.readXml(o):void 0;if(!o||!s)return"";let a="";for(let c of(0,te.xmlChildren)(s)){let l=(0,te.xmlChild)(c,"xdr:from"),u=(0,te.xmlChild)(c,"xdr:to"),d=v=>({x:n(ba(v,"xdr:col"))+ba(v,"xdr:colOff")/Ca,y:i(ba(v,"xdr:row"))+ba(v,"xdr:rowOff")/Ca}),A=(0,te.xmlChild)(c,"xdr:pos"),p=l?d(l):{x:qm+((0,W.numberAttr)(A,"x")??0)/Ca,y:Dw+((0,W.numberAttr)(A,"y")??0)/Ca},h=(0,te.xmlChild)(c,"xdr:ext"),f=u?d(u):{x:p.x+((0,W.numberAttr)(h,"cx")??0)/Ca,y:p.y+((0,W.numberAttr)(h,"cy")??0)/Ca},E=(0,W.styleAttribute)({left:`${p.x}px`,top:`${p.y}px`,width:`${Math.max(f.x-p.x,1)}px`,height:`${Math.max(f.y-p.y,1)}px`}),S=(0,te.xmlChild)(c,"xdr:pic");if(S){let v=await this.officePackage.relatedImage(o,(0,W.attr)((0,te.xmlPath)(S,"xdr:blipFill","a:blip"),"r:embed"));v&&(a+=`<img class="drawing" src="${(0,W.escAttr)(v)}" alt=""${E}>`);continue}let B=(0,te.xmlPath)((0,te.xmlChild)(c,"xdr:graphicFrame"),"a:graphic","a:graphicData","c:chart"),_=await this.officePackage.relatedPartById(o,(0,W.attr)(B,"r:id"));if(_){let v=(0,Pge.renderChartSvg)({root:await this.officePackage.readXml(_),theme:this.theme,colorMap:{},aspect:Math.max(f.y-p.y,1)/Math.max(f.x-p.x,1)});v&&(a+=`<div class="drawing chart"${E}>${v}</div>`)}}return a}async drawingExtent({part:e,worksheet:r,defaultWidth:n,defaultHeight:i}){let o=await this.officePackage.relatedPartById(e,(0,W.attr)((0,te.xmlChild)(r,"drawing"),"r:id")),s=o?await this.officePackage.readXml(o):void 0,a=0,c=0;for(let l of(0,te.xmlChildren)(s)){let u=(0,te.xmlChild)(l,"xdr:from"),d=(0,te.xmlChild)(l,"xdr:to"),A=(0,te.xmlChild)(l,"xdr:ext"),p=d?ba(d,"xdr:col"):ba(u??l,"xdr:col")+Math.ceil(((0,W.numberAttr)(A,"cx")??0)/Ca/n),h=d?ba(d,"xdr:row"):ba(u??l,"xdr:row")+Math.ceil(((0,W.numberAttr)(A,"cy")??0)/Ca/i);c=Math.max(c,p+1),a=Math.max(a,h+1)}return{rows:a,columns:c}}async render(e,r){let{worksheet:n,rows:i}=await N$(this.officePackage,e),o=(0,te.xmlChild)(n,"sheetFormatPr"),s=k$((0,W.numberAttr)(o,"defaultColWidth")??((0,W.numberAttr)(o,"baseColWidth")??8)+.43),a=((0,W.numberAttr)(o,"defaultRowHeight")??15)*4/3,c=new Map,l=new Set;for(let se of(0,te.xmlChildren)((0,te.xmlChild)(n,"cols"),"col")){let ht=((0,W.numberAttr)(se,"min")??1)-1,ms=Math.min(((0,W.numberAttr)(se,"max")??ht+1)-1,Kt.MAX_PREVIEW_COLUMNS+50);for(let Hr=ht;Hr<=ms;Hr+=1){((0,W.attr)(se,"hidden")==="1"||(0,W.attr)(se,"hidden")==="true")&&l.add(Hr);let Ot=(0,W.numberAttr)(se,"width");Ot!==void 0&&c.set(Hr,k$(Ot))}}let u=new Map,d=0,A=0;for(let{element:se,index:ht,cells:ms}of i()){let Hr=new Map,Ot=!1;for(let rt of ms)!(0,te.xmlChild)(rt.element,"v")&&!(0,te.xmlChild)(rt.element,"is")&&!(0,te.xmlChild)(rt.element,"f")&&!(0,W.numberAttr)(rt.element,"s")||(Ot=!0,A=Math.max(A,rt.column+1),!(ht>=Kt.MAX_PREVIEW_ROWS||rt.column>=Kt.MAX_PREVIEW_COLUMNS)&&Hr.set(rt.column,this.cell({...rt,row:ht})));if(Ot&&(d=Math.max(d,ht+1)),ht>=Kt.MAX_PREVIEW_ROWS)continue;let Fi=(0,W.numberAttr)(se,"ht");u.set(ht,{...Fi!==void 0?{height:Fi*4/3}:{},hidden:(0,W.attr)(se,"hidden")==="1"||(0,W.attr)(se,"hidden")==="true",cells:Hr})}let p=(0,te.xmlChildren)((0,te.xmlChild)(n,"mergeCells"),"mergeCell").map(se=>((0,W.attr)(se,"ref")??"").split(":").map(Uw)).filter(se=>se.length===2&&!!se[0]&&!!se[1]);for(let[,se]of p)d=Math.max(d,se.row+1),A=Math.max(A,se.column+1);let h=await this.drawingExtent({part:e,worksheet:n,defaultWidth:s,defaultHeight:a}),f=Math.min(Math.max(d,h.rows),Kt.MAX_PREVIEW_ROWS),E=Math.min(Math.max(A,h.columns),Kt.MAX_PREVIEW_COLUMNS),S=new Map,B=new Set;for(let[se,ht]of p){let ms=0,Hr=0;for(let Ot=se.row;Ot<=Math.min(ht.row,f-1);Ot+=1)u.get(Ot)?.hidden||(ms+=1);for(let Ot=se.column;Ot<=Math.min(ht.column,E-1);Ot+=1)l.has(Ot)||(Hr+=1);S.set(`${se.row}:${se.column}`,{rowSpan:ms,columnSpan:Hr});for(let Ot=se.row;Ot<=Math.min(ht.row,f-1);Ot+=1)for(let Fi=se.column;Fi<=Math.min(ht.column,E-1);Fi+=1)(Ot!==se.row||Fi!==se.column)&&B.add(`${Ot}:${Fi}`)}let _=Array.from({length:E},(se,ht)=>ht).filter(se=>!l.has(se)),v=Array.from({length:f},(se,ht)=>ht).filter(se=>!u.get(se)?.hidden),T=se=>c.get(se)??s,L=se=>u.get(se)?.height??a,k=new Map,P=qm;for(let se=0;se<E;se+=1)k.set(se,P),l.has(se)||(P+=T(se));let U=new Map,K=Dw;for(let se=0;se<f;se+=1)U.set(se,K),u.get(se)?.hidden||(K+=L(se));let Ae=se=>k.get(se)??P+(se-E)*s,Re=se=>U.get(se)??K+(se-f)*a,Ge=(0,te.xmlPath)(n,"sheetViews","sheetView"),tt=(0,W.attr)(Ge,"showGridLines")!=="0",Ht=(0,te.xmlChild)(Ge,"pane"),Nt=(0,W.attr)(Ht,"state")==="frozen"||(0,W.attr)(Ht,"state")==="frozenSplit",kr=Nt?(0,W.numberAttr)(Ht,"ySplit")??0:0,qr=Nt?(0,W.numberAttr)(Ht,"xSplit")??0:0,Dt=se=>se<kr?`${Re(se)}px`:void 0,pt=se=>se<qr?`${Ae(se)}px`:void 0,An=qm+_.reduce((se,ht)=>se+T(ht),0),Ci=this.styles.defaultFont()["font-size"]??"11pt",$n="";for(let[se,ht]of v.entries()){let ms=u.get(ht);$n+=`<tr${(0,W.styleAttribute)({height:`${L(ht)}px`})}><th class="rh"${(0,W.styleAttribute)({top:Dt(ht),"z-index":ht<kr?"4":void 0})}>${ht+1}</th>`;for(let[Hr,Ot]of _.entries()){let Fi=`${ht}:${Ot}`;if(B.has(Fi))continue;let rt=ms?.cells.get(Ot),na=S.get(Fi),xh=_[Hr+1],gD=xh===void 0?void 0:ms?.cells.get(xh),WZ=xh===void 0||!!(gD&&gD.kind!=="empty")||B.has(`${ht}:${xh}`),mD=rt?.format.horizontal??(rt?.kind==="number"?"right":rt?.kind==="boolean"||rt?.kind==="error"?"center":void 0),BC=Dt(ht),vC=pt(Ot),JZ=BC!==void 0||vC!==void 0,ZZ=(0,W.styleAttribute)({...rt?.format.css,...rt?.color?{color:rt.color}:{},"text-align":mD,"white-space":rt?rt.format.wrap?"pre-wrap":"pre":void 0,overflow:rt&&!(rt.format.wrap||WZ||na||mD==="right")?"visible":rt?"hidden":void 0,...JZ?{position:"sticky",top:BC,left:vC,"z-index":BC!==void 0&&vC!==void 0?"3":"2",background:rt?.format.css.background??"#fff"}:{}}),KZ=na?`${na.columnSpan>1?` colspan="${na.columnSpan}"`:""}${na.rowSpan>1?` rowspan="${na.rowSpan}"`:""}`:"",XZ=v.slice(se,se+(na?.rowSpan??1)).reduce((QC,TC)=>QC+L(TC),0),e6=_.slice(Hr,Hr+(na?.columnSpan??1)).reduce((QC,TC)=>QC+T(TC),0),t6=rt?.kind==="number"&&!rt.format.wrap?Yge({text:rt.text,html:rt.html,width:e6,fontSize:rt.format.css["font-size"]??Ci}):rt?.format.wrap&&rt.html?`<div class="clip"${(0,W.styleAttribute)({"max-height":`${XZ-1}px`})}>${rt.html}</div>`:rt?.html??"";$n+=`<td${KZ}${ZZ}>${t6}</td>`}$n+="</tr>"}let gs=await this.drawings({part:e,worksheet:n,columnOffsets:Ae,rowOffsets:Re}),ra=`<tr class="ch"><th class="corner"></th>${_.map(se=>`<th>${xw(se)}</th>`).join("")}</tr>`,Nl=["html,body{margin:0;background:#fff}","body{font-family:Calibri,Arial,sans-serif;font-size:11pt;color:#000}",".wrap{position:relative;display:inline-block;min-width:100%}",`table{border-collapse:separate;border-spacing:0;table-layout:fixed;width:${An}px}`,`td{padding:0 3px;line-height:1.2;${tt?"border-right:1px solid #e3e3e3;border-bottom:1px solid #e3e3e3;":""}box-sizing:border-box}`,"th{position:sticky;z-index:5;background:#f3f3f3;color:#555;font:400 11px/1 system-ui,sans-serif;border-right:1px solid #d4d4d4;border-bottom:1px solid #d4d4d4;text-align:center;padding:0;box-sizing:border-box}",`.ch th{top:0;height:${Dw}px}`,".rh{left:0;z-index:3}",".corner{left:0;z-index:6}",".drawing{position:absolute;z-index:1}",".clip{overflow:hidden}",".chart{background:#fff;border:1px solid #d9d9d9;box-sizing:border-box}"].join(`
|
|
792
|
+
`);return(0,H.officeHtmlDocument)({title:e,css:A,body:d})}});var T$=y(gu=>{"use strict";Object.defineProperty(gu,"__esModule",{value:!0});gu.BUILT_IN_FORMATS=void 0;gu.formatCellNumber=Uge;gu.formatCellText=Mge;gu.BUILT_IN_FORMATS={0:"General",1:"0",2:"0.00",3:"#,##0",4:"#,##0.00",5:'"$"#,##0_);("$"#,##0)',6:'"$"#,##0_);[Red]("$"#,##0)',7:'"$"#,##0.00_);("$"#,##0.00)',8:'"$"#,##0.00_);[Red]("$"#,##0.00)',9:"0%",10:"0.00%",11:"0.00E+00",12:"# ?/?",13:"# ??/??",14:"SHORT_DATE",15:"d-mmm-yy",16:"d-mmm",17:"mmm-yy",18:"h:mm AM/PM",19:"h:mm:ss AM/PM",20:"h:mm",21:"h:mm:ss",22:"SHORT_DATE h:mm",37:"#,##0 ;(#,##0)",38:"#,##0 ;[Red](#,##0)",39:"#,##0.00;(#,##0.00)",40:"#,##0.00;[Red](#,##0.00)",41:'_(* #,##0_);_(* \\(#,##0\\);_(* "-"_);_(@_)',42:'_("$"* #,##0_);_("$"* \\(#,##0\\);_("$"* "-"_);_(@_)',43:'_(* #,##0.00_);_(* \\(#,##0.00\\);_(* "-"??_);_(@_)',44:'_("$"* #,##0.00_);_("$"* \\(#,##0.00\\);_("$"* "-"??_);_(@_)',45:"mm:ss",46:"[h]:mm:ss",47:"mm:ss.0",48:"##0.0E+0",49:"@"};var S$={black:"#000000",blue:"#0000ff",cyan:"#00ffff",green:"#00ff00",magenta:"#ff00ff",red:"#ff0000",white:"#ffffff",yellow:"#ffff00"},Qw=["January","February","March","April","May","June","July","August","September","October","November","December"],w$=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function v$(t){let e=[],r="",n=!1,i=!1;for(let o=0;o<t.length;o+=1){let s=t[o];if(s==="\\"&&!n){r+=s+(t[o+1]??""),o+=1;continue}if(s==='"'&&(n=!n),!n&&s==="["&&(i=!0),!n&&s==="]"&&(i=!1),s===";"&&!n&&!i){e.push(r),r="";continue}r+=s}return e.push(r),e}function Tw(t){let e=[],r,n=!1,i=o=>{let s=e[e.length-1];s?.kind==="literal"?s.value+=o:e.push({kind:"literal",value:o})};for(let o=0;o<t.length;o+=1){let s=t[o],a=/^(AM\/PM|A\/P|General|E[+-])/i.exec(t.slice(o));if(a){e.push({kind:"code",value:a[0].toLowerCase()}),o+=a[0].length-1;continue}if(s==='"'){let c=t.indexOf('"',o+1);i(t.slice(o+1,c===-1?t.length:c)),o=c===-1?t.length:c}else if(s==="\\")i(t[o+1]??""),o+=1;else if(s==="_")i(" "),o+=1;else if(s==="*")o+=1;else if(s==="["){let c=t.indexOf("]",o),l=t.slice(o+1,c===-1?t.length:c);o=c===-1?t.length:c,/^\$/.test(l)?i(l.slice(1).split("-")[0]):S$[l.toLowerCase()]?r=S$[l.toLowerCase()]:/^(h+|m+|s+)$/i.test(l)&&(n=!0,e.push({kind:"code",value:`[${l.toLowerCase()}]`}))}else/[0#?.,%]/.test(s)||/[dmyhs]/i.test(s)||s==="@"?e.push({kind:"code",value:s}):i(s)}return{tokens:e,...r?{color:r}:{},elapsed:n}}function kge(t){return t.some(e=>e.kind==="code"&&/^[dmyhs]$|^\[/i.test(e.value))}function Q$(t,e){let r=e?t+1462:t,n=Math.round((r-25569)*86400*1e3);return new Date(n)}function kc(t,e){return String(t).padStart(e,"0")}function _$(t,e,r,n){let i=Q$(t,r),o=[],{tokens:s}=Tw(e),a="",c=()=>{if(!a)return;let A=/am\/pm|a\/p|\[h+\]|\[m+\]|\[s+\]|yyyy|yy|mmmmm|mmmm|mmm|mm|m|dddd|ddd|dd|d|hh|h|ss|s|\.0+|./gi;for(let p of a.match(A)??[])o.push({token:p});a=""};for(let A of s)A.kind==="literal"?(c(),o.push({token:A.value,literal:!0})):a+=A.value;c();let l=o.some(A=>!A.literal&&/^(am\/pm|a\/p)$/i.test(A.token)),u=i.getUTCHours(),d=Math.round(t*86400);return o.map((A,p)=>{if(A.literal)return A.token;let h=A.token.toLowerCase(),f=o.slice(0,p).reverse().find(B=>!B.literal&&/^\[?[hms]/i.test(B.token)),E=o.slice(p+1).find(B=>!B.literal&&/^\[?[hms]/i.test(B.token)),S=f&&/^\[?h/i.test(f.token)||E&&/^\[?s/i.test(E.token);if(n&&h.startsWith("[h"))return String(Math.floor(d/3600));if(n&&h.startsWith("[m"))return String(Math.floor(d/60));if(n&&h.startsWith("[s"))return String(d);switch(h){case"yyyy":return String(i.getUTCFullYear());case"yy":return kc(i.getUTCFullYear()%100,2);case"mmmmm":return Qw[i.getUTCMonth()][0];case"mmmm":return Qw[i.getUTCMonth()];case"mmm":return Qw[i.getUTCMonth()].slice(0,3);case"mm":return kc(S?i.getUTCMinutes():i.getUTCMonth()+1,2);case"m":return String(S?i.getUTCMinutes():i.getUTCMonth()+1);case"dddd":return w$[i.getUTCDay()];case"ddd":return w$[i.getUTCDay()].slice(0,3);case"dd":return kc(i.getUTCDate(),2);case"d":return String(i.getUTCDate());case"hh":return kc(l?u%12||12:u,2);case"h":return String(l?u%12||12:u);case"ss":return kc(i.getUTCSeconds(),2);case"s":return String(i.getUTCSeconds());case"am/pm":return u<12?"AM":"PM";case"a/p":return u<12?"A":"P";default:return h.startsWith(".")?`.${String(i.getUTCMilliseconds()).padStart(3,"0").slice(0,h.length-1)}`:A.token}}).join("")}function zm(t){if(Number.isInteger(t)&&Math.abs(t)<1e11)return String(t);let e=Math.abs(t);return e!==0&&(e>=1e11||e<1e-9)?t.toExponential(5).replace(/\.?0+e/,"E").replace("e","E"):String(Number(t.toPrecision(10)))}function Rge(t,e){let r=+`${t}e${e}`;return Number.isFinite(r)?Math.round(r)/10**e:t}var Ko=/^[0#?]$/;function Nge(t,e){let r=t.filter(s=>Ko.test(s.value)).length,n=e==="0"?"":e,i=0,o="";for(let s=t.length-1;s>=0;s-=1){let a=t[s];if(!Ko.test(a.value)){o=(a.kind==="literal"?a.value:"")+o;continue}i+=1;let c=n.slice(-1);n=n.slice(0,-1);let l=c||(a.value==="0"?"0":a.value==="?"?" ":"");o=(i===r?n+l:l)+o,i===r&&(n="")}return o}function Oge(t,e){let r=-1,n=0;return t.forEach((i,o)=>{Ko.test(i.value)&&((e[n]!=="0"||i.value==="0")&&(r=o),n+=1)}),n=0,t.map((i,o)=>{if(!Ko.test(i.value))return i.kind==="literal"?i.value:"";let s=e[n];return n+=1,o>r?i.value==="?"?" ":"":s}).join("")}function xge(t,e){if(e.some(k=>k.value==="general"))return e.map(k=>k.value==="general"?zm(t):k.value).join("");let r=e.map((k,P)=>k.kind==="code"&&Ko.test(k.value)?P:-1).filter(k=>k!==-1);if(r.length===0)return e.map(k=>k.value==="@"?zm(t):k.value).join("");let n=t*100**e.filter(k=>k.kind==="code"&&k.value==="%").length,i=r[0],o=r[r.length-1],s=e.findIndex(k=>k.value==="e+"||k.value==="e-"),a=s===-1?o:s-1,c=e.slice(i,a+1),l=c.findIndex(k=>k.kind==="code"&&k.value==="."),u=l===-1?c:c.slice(0,l),d=l===-1?[]:c.slice(l+1),A=c.reduce((k,P,U)=>Ko.test(P.value)?U:k,-1),p=e.slice(i+A+1,s===-1?void 0:s).filter(k=>k.kind==="code"&&k.value===",").length;n/=1e3**p;let h=u.some((k,P)=>k.value===","&&u.slice(P+1).some(U=>Ko.test(U.value))),f=d.filter(k=>Ko.test(k.value)).length,E=e.slice(0,i).map(k=>k.value).join(""),S=e.slice((s===-1?o:e.length)+1).filter(k=>k.value!==",").map(k=>k.value).join("");if(s!==-1){let k=e.slice(s+1).filter(Re=>Ko.test(Re.value)).length||1,[P,U]=n.toExponential(f).split("e"),K=Number(U),Ae=K<0?"-":e[s].value==="e+"?"+":"";return`${E}${P}E${Ae}${kc(Math.abs(K),k)}${S}`}let[B,_=""]=Rge(n,f).toFixed(f).split("."),v=u.filter(k=>k.value!==","),T=h?`${v.slice(0,v.findIndex(k=>Ko.test(k.value))).map(k=>k.value).join("")}${(B==="0"&&!u.some(k=>k.value==="0")?"":B.padStart(u.filter(k=>k.value==="0").length,"0")).replace(/\B(?=(\d{3})+(?!\d))/g,",")}`:Nge(v,B),L=l===-1?"":`.${Oge(d,_)}`;return`${E}${T}${L}${S}`}function B$(t,e){return new Intl.DateTimeFormat(void 0,{year:"numeric",month:"numeric",day:"numeric",timeZone:"UTC"}).format(Q$(t,e))}function Uge({value:t,code:e,date1904:r}){if(!e||/^general$/i.test(e))return{text:zm(t)};if(e==="SHORT_DATE")return{text:B$(t,r)};if(e==="SHORT_DATE h:mm")return{text:`${B$(t,r)} ${_$(t,"h:mm",r,!1)}`};let n=v$(e);if(n.map(A=>/^\[[<>=]/.test(A.trim())).some(Boolean))return{text:zm(t)};let o=n[0],s=t;t<0&&n.length>1?(o=n[1],s=Math.abs(t)):t===0&&n.length>2&&(o=n[2]);let{tokens:a,color:c,elapsed:l}=Tw(o);if(a.every(A=>A.kind==="literal"))return{text:a.map(A=>A.value).join(""),...c?{color:c}:{}};if(kge(a))return{text:_$(s,o,r,l),...c?{color:c}:{}};let u=xge(Math.abs(s),a);return{text:`${s<0&&!(t<0&&n.length>1)?"-":""}${u}`,...c?{color:c}:{}}}function Mge({value:t,code:e}){let r=v$(e),n=r.length>=4?r[3]:r.find(s=>s.includes("@"));if(!n)return{text:t};let{tokens:i,color:o}=Tw(n);return{text:i.map(s=>s.kind==="code"&&s.value==="@"?t:s.value).join(""),...o?{color:o}:{}}}});var Gm=y(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.WorkbookStyles=Xt.MAX_PREVIEW_COLUMNS=Xt.MAX_PREVIEW_ROWS=void 0;Xt.columnName=xw;Xt.parseReference=Uw;Xt.readWorksheet=N$;Xt.parseCell=x$;Xt.openWorkbook=U$;Xt.loadXlsx=Vge;var Pge=Dc(),W=Ts(),kw=T$(),te=Zo();Xt.MAX_PREVIEW_ROWS=2e3;Xt.MAX_PREVIEW_COLUMNS=200;var Ow=1048576,R$=16384,Lge=/("(?:[^"]|"")*"|'(?:[^']|'')*')/,$ge=/(^|[^A-Za-z0-9_.])(\$?)([A-Z]{1,3})(\$?)(\d{1,7})(?![A-Za-z0-9_(])/g,VA="xl/workbook.xml",qm=40,Dw=20,Ca=9525,Fge=["lt1","dk1","lt2","dk2","accent1","accent2","accent3","accent4","accent5","accent6","hlink","folHlink"],jge=["000000","FFFFFF","FF0000","00FF00","0000FF","FFFF00","FF00FF","00FFFF","000000","FFFFFF","FF0000","00FF00","0000FF","FFFF00","FF00FF","00FFFF","800000","008000","000080","808000","800080","008080","C0C0C0","808080","9999FF","993366","FFFFCC","CCFFFF","660066","FF8080","0066CC","CCCCFF","000080","FF00FF","FFFF00","00FFFF","800080","800000","008080","0000FF","00CCFF","CCFFFF","CCFFCC","FFFF99","99CCFF","FF99CC","CC99FF","FFCC99","3366FF","33CCCC","99CC00","FFCC00","FF9900","FF6600","666699","969696","003366","339966","003300","333300","993300","993366","333399","333333"],zge={thin:"1px solid",hair:"1px solid",medium:"2px solid",thick:"3px solid",dashed:"1px dashed",mediumDashed:"2px dashed",dotted:"1px dotted",double:"3px double",dashDot:"1px dashed",mediumDashDot:"2px dashed",dashDotDot:"1px dotted",mediumDashDotDot:"2px dotted",slantDashDot:"2px dashed"},D$={left:"left",center:"center",centerContinuous:"center",right:"right",justify:"justify",distributed:"justify",fill:"left"},qge={top:"top",center:"middle",justify:"middle",distributed:"middle",bottom:"bottom"};function xw(t){let e="",r=t+1;for(;r>0;){let n=(r-1)%26;e=String.fromCharCode(65+n)+e,r=Math.floor((r-1)/26)}return e}function Rw(t){return t.toUpperCase().split("").reduce((e,r)=>e*26+r.charCodeAt(0)-64,0)-1}function Uw(t){let e=/^\$?([A-Z]{1,3})\$?(\d{1,7})$/i.exec(t);if(!e)return;let r=Number(e[2])-1,n=Rw(e[1]);if(!(r<0||r>=Ow||n>=R$))return{row:r,column:n}}function Hge({formula:t,rows:e,columns:r}){return t.split(Lge).map((n,i)=>i%2===1?n:n.replace($ge,(o,s,a,c,l,u)=>{let d=a?Rw(c):Rw(c)+r,A=l?Number(u):Number(u)+e;return d<0||d>=R$||A<1||A>Ow?`${s}#REF!`:`${s}${a}${xw(d)}${l}${A}`})).join("")}function*Gge(t){let e=new Map,r=(i,o,s)=>{let a=(0,te.xmlChild)(i,"f");if(!a)return;let c=(0,te.xmlText)(a);if((0,W.attr)(a,"t")!=="shared")return c||void 0;let l=(0,W.attr)(a,"si")??"";if(c)return e.set(l,{formula:c,row:o,column:s}),c;let u=e.get(l);return u?Hge({formula:u.formula,rows:o-u.row,columns:s-u.column}):void 0},n=-1;for(let i of t){let o=(0,W.numberAttr)(i,"r"),s=o!==void 0&&Number.isInteger(o)&&o>=1&&o<=Ow?o-1:n+1;n=s;let a=[],c=0;for(let l of(0,te.xmlChildren)(i,"c")){let u=Uw((0,W.attr)(l,"r")??"")??{row:s,column:c};c=u.column+1;let d=r(l,u.row,u.column);a.push({element:l,...u,...d?{formula:d}:{}})}yield{element:i,index:s,cells:a}}}async function N$(t,e){let r=await t.readText(e);if(r===void 0)throw new Error(`The workbook has no worksheet part ${e}`);let{root:n,elements:i}=(0,te.streamXmlElements)({xml:r,container:"sheetData",element:"row"});if(!n)throw new Error(`The worksheet part ${e} is empty`);return{worksheet:n,rows:()=>Gge(i())}}function Yge({text:t,html:e,width:r,fontSize:n}){let i=(Number.parseFloat(n)||11)*4/3*.55,o=r-6;return t.length*i<=o?e:"#".repeat(Math.max(1,Math.floor(o/i)))}function ba(t,e){let r=(0,te.xmlChild)(t,e);return r&&Number((0,te.xmlText)(r))||0}function k$(t){return Math.max(0,Math.trunc(t*7+5))}var Hm=class{constructor(e){this.theme=e,this.fonts=[],this.fills=[],this.borders=[],this.formats=[],this.numberFormats=new Map}color(e){if(!e||(0,W.attr)(e,"auto")==="1")return;let r,n=(0,W.attr)(e,"rgb");n&&/^[0-9a-f]{6,8}$/i.test(n)&&(r=n.slice(-6));let i=(0,W.numberAttr)(e,"theme");i!==void 0&&(r=this.theme.colors[Fge[i]??""]);let o=(0,W.numberAttr)(e,"indexed");if(o!==void 0&&(r=jge[o]),!r||!/^[0-9a-f]{6}$/i.test(r))return;let s=(0,W.numberAttr)(e,"tint");return s?(0,W.tintedColor)(r,s):`#${r.toLowerCase()}`}load(e){for(let r of(0,te.xmlChildren)((0,te.xmlChild)(e,"numFmts"),"numFmt")){let n=(0,W.numberAttr)(r,"numFmtId"),i=(0,W.attr)(r,"formatCode");n!==void 0&&i!==void 0&&this.numberFormats.set(n,i)}this.fonts=(0,te.xmlChildren)((0,te.xmlChild)(e,"fonts"),"font").map(r=>{let n=(0,te.xmlChild)(r,"u"),i=(0,W.numberAttr)((0,te.xmlChild)(r,"sz"),"val"),o=(0,W.attr)((0,te.xmlChild)(r,"name"),"val"),s=a=>!!a&&!["0","false"].includes((0,W.attr)(a,"val")??"");return{css:{"font-weight":s((0,te.xmlChild)(r,"b"))?"700":void 0,"font-style":s((0,te.xmlChild)(r,"i"))?"italic":void 0,"text-decoration":[n&&(0,W.attr)(n,"val")!=="none"?"underline":"",s((0,te.xmlChild)(r,"strike"))?"line-through":""].filter(Boolean).join(" ")||void 0,"font-size":i?`${i}pt`:void 0,"font-family":o?(0,W.fontStack)(o):void 0,color:this.color((0,te.xmlChild)(r,"color"))}}}),this.fills=(0,te.xmlChildren)((0,te.xmlChild)(e,"fills"),"fill").map(r=>{let n=(0,te.xmlChild)(r,"patternFill");if(n){let o=(0,W.attr)(n,"patternType");return!o||o==="none"||o==="gray125"?void 0:this.color((0,te.xmlChild)(n,"fgColor"))??this.color((0,te.xmlChild)(n,"bgColor"))}let i=(0,te.xmlChildren)((0,te.xmlChild)(r,"gradientFill"),"stop");return i.length>0?this.color((0,te.xmlChild)(i[0],"color")):void 0}),this.borders=(0,te.xmlChildren)((0,te.xmlChild)(e,"borders"),"border").map(r=>{let n=i=>{let o=(0,te.xmlChild)(r,i),s=zge[(0,W.attr)(o,"style")??""];return s?`${s} ${this.color((0,te.xmlChild)(o,"color"))??"#000"}`:void 0};return{"border-left":n("left")??n("start"),"border-right":n("right")??n("end"),"border-top":n("top"),"border-bottom":n("bottom")}}),this.formats=(0,te.xmlChildren)((0,te.xmlChild)(e,"cellXfs"),"xf").map(r=>{let n=(0,te.xmlChild)(r,"alignment"),i=(0,W.attr)(n,"horizontal"),o=(0,W.numberAttr)(n,"indent"),s=(0,W.numberAttr)(r,"numFmtId")??0;return{numberFormat:this.numberFormats.get(s)??kw.BUILT_IN_FORMATS[s]??"General",css:{...this.fonts[(0,W.numberAttr)(r,"fontId")??0]?.css,background:this.fills[(0,W.numberAttr)(r,"fillId")??0],...this.borders[(0,W.numberAttr)(r,"borderId")??0],"vertical-align":qge[(0,W.attr)(n,"vertical")??"bottom"],"padding-left":o?`${3+o*9}px`:void 0},...i&&D$[i]?{horizontal:D$[i]}:{},wrap:(0,W.attr)(n,"wrapText")==="1"||(0,W.attr)(n,"wrapText")==="true"}})}format(e){return this.formats[e??0]??this.formats[0]??{numberFormat:"General",css:{},wrap:!1}}defaultFont(){return this.fonts[0]?.css??{}}};Xt.WorkbookStyles=Hm;function O$(t,e){if(!t)return{html:"",text:""};let r=(0,te.xmlChildren)(t,"r");if(r.length===0){let o=(0,te.xmlChildren)(t,"t").map(te.xmlText).join("");return{html:(0,W.esc)(o),text:o}}let n="",i="";for(let o of r){let s=(0,te.xmlChildren)(o,"t").map(te.xmlText).join(""),a=(0,te.xmlChild)(o,"rPr"),c=(0,W.numberAttr)((0,te.xmlChild)(a,"sz"),"val");n+=`<span${(0,W.styleAttribute)({"font-weight":(0,te.xmlChild)(a,"b")?"700":void 0,"font-style":(0,te.xmlChild)(a,"i")?"italic":void 0,"text-decoration":(0,te.xmlChild)(a,"u")?"underline":void 0,"font-size":c?`${c}pt`:void 0,color:e.color((0,te.xmlChild)(a,"color"))})}>${(0,W.esc)(s)}</span>`,i+=s}return{html:n,text:i}}function x$({context:t,cell:{element:e,row:r,column:n,formula:i}}){let o=t.styles.format((0,W.numberAttr)(e,"s")),s=(0,W.attr)(e,"t")??"n",a=(0,te.xmlChild)(e,"v"),c=a?(0,te.xmlText)(a):void 0,l={row:r,column:n,format:o,...i?{formula:i}:{}};if(s==="s"&&c!==void 0){let A=t.sharedStrings[Number(c)]??{html:"",text:""};return{...l,...A,value:A.text,kind:"text"}}if(s==="inlineStr"){let A=O$((0,te.xmlChild)(e,"is"),t.styles);return{...l,...A,value:A.text,kind:"text"}}if((c===void 0||c==="")&&i){let A=`=${i}`;return{...l,html:(0,W.esc)(A),text:A,value:null,kind:"text",color:"#8c8c8c"}}if(c===void 0||c==="")return{...l,html:"",text:"",value:null,kind:"empty"};if(s==="b"){let A=c==="1"?"TRUE":"FALSE";return{...l,html:A,text:A,value:c==="1",kind:"boolean"}}if(s==="e")return{...l,html:(0,W.esc)(c),text:c,value:c,kind:"error"};if(s==="str"||s==="d"){let A=(0,kw.formatCellText)({value:c,code:o.numberFormat});return{...l,html:(0,W.esc)(A.text),text:A.text,value:c,kind:"text",...A.color?{color:A.color}:{}}}let u=Number(c);if(!Number.isFinite(u))return{...l,html:(0,W.esc)(c),text:c,value:c,kind:"text"};let d=(0,kw.formatCellNumber)({value:u,code:o.numberFormat,date1904:t.date1904});return{...l,html:(0,W.esc)(d.text),text:d.text,value:u,kind:"number",...d.color?{color:d.color}:{}}}var Nw=class{constructor(e){this.context=e,this.officePackage=e.officePackage,this.styles=e.styles,this.theme=e.theme}cell(e){return x$({context:this.context,cell:e})}async drawings({part:e,worksheet:r,columnOffsets:n,rowOffsets:i}){let o=await this.officePackage.relatedPartById(e,(0,W.attr)((0,te.xmlChild)(r,"drawing"),"r:id")),s=o?await this.officePackage.readXml(o):void 0;if(!o||!s)return"";let a="";for(let c of(0,te.xmlChildren)(s)){let l=(0,te.xmlChild)(c,"xdr:from"),u=(0,te.xmlChild)(c,"xdr:to"),d=v=>({x:n(ba(v,"xdr:col"))+ba(v,"xdr:colOff")/Ca,y:i(ba(v,"xdr:row"))+ba(v,"xdr:rowOff")/Ca}),A=(0,te.xmlChild)(c,"xdr:pos"),p=l?d(l):{x:qm+((0,W.numberAttr)(A,"x")??0)/Ca,y:Dw+((0,W.numberAttr)(A,"y")??0)/Ca},h=(0,te.xmlChild)(c,"xdr:ext"),f=u?d(u):{x:p.x+((0,W.numberAttr)(h,"cx")??0)/Ca,y:p.y+((0,W.numberAttr)(h,"cy")??0)/Ca},E=(0,W.styleAttribute)({left:`${p.x}px`,top:`${p.y}px`,width:`${Math.max(f.x-p.x,1)}px`,height:`${Math.max(f.y-p.y,1)}px`}),S=(0,te.xmlChild)(c,"xdr:pic");if(S){let v=await this.officePackage.relatedImage(o,(0,W.attr)((0,te.xmlPath)(S,"xdr:blipFill","a:blip"),"r:embed"));v&&(a+=`<img class="drawing" src="${(0,W.escAttr)(v)}" alt=""${E}>`);continue}let B=(0,te.xmlPath)((0,te.xmlChild)(c,"xdr:graphicFrame"),"a:graphic","a:graphicData","c:chart"),_=await this.officePackage.relatedPartById(o,(0,W.attr)(B,"r:id"));if(_){let v=(0,Pge.renderChartSvg)({root:await this.officePackage.readXml(_),theme:this.theme,colorMap:{},aspect:Math.max(f.y-p.y,1)/Math.max(f.x-p.x,1)});v&&(a+=`<div class="drawing chart"${E}>${v}</div>`)}}return a}async drawingExtent({part:e,worksheet:r,defaultWidth:n,defaultHeight:i}){let o=await this.officePackage.relatedPartById(e,(0,W.attr)((0,te.xmlChild)(r,"drawing"),"r:id")),s=o?await this.officePackage.readXml(o):void 0,a=0,c=0;for(let l of(0,te.xmlChildren)(s)){let u=(0,te.xmlChild)(l,"xdr:from"),d=(0,te.xmlChild)(l,"xdr:to"),A=(0,te.xmlChild)(l,"xdr:ext"),p=d?ba(d,"xdr:col"):ba(u??l,"xdr:col")+Math.ceil(((0,W.numberAttr)(A,"cx")??0)/Ca/n),h=d?ba(d,"xdr:row"):ba(u??l,"xdr:row")+Math.ceil(((0,W.numberAttr)(A,"cy")??0)/Ca/i);c=Math.max(c,p+1),a=Math.max(a,h+1)}return{rows:a,columns:c}}async render(e,r){let{worksheet:n,rows:i}=await N$(this.officePackage,e),o=(0,te.xmlChild)(n,"sheetFormatPr"),s=k$((0,W.numberAttr)(o,"defaultColWidth")??((0,W.numberAttr)(o,"baseColWidth")??8)+.43),a=((0,W.numberAttr)(o,"defaultRowHeight")??15)*4/3,c=new Map,l=new Set;for(let se of(0,te.xmlChildren)((0,te.xmlChild)(n,"cols"),"col")){let ht=((0,W.numberAttr)(se,"min")??1)-1,ms=Math.min(((0,W.numberAttr)(se,"max")??ht+1)-1,Xt.MAX_PREVIEW_COLUMNS+50);for(let Hr=ht;Hr<=ms;Hr+=1){((0,W.attr)(se,"hidden")==="1"||(0,W.attr)(se,"hidden")==="true")&&l.add(Hr);let Ot=(0,W.numberAttr)(se,"width");Ot!==void 0&&c.set(Hr,k$(Ot))}}let u=new Map,d=0,A=0;for(let{element:se,index:ht,cells:ms}of i()){let Hr=new Map,Ot=!1;for(let rt of ms)!(0,te.xmlChild)(rt.element,"v")&&!(0,te.xmlChild)(rt.element,"is")&&!(0,te.xmlChild)(rt.element,"f")&&!(0,W.numberAttr)(rt.element,"s")||(Ot=!0,A=Math.max(A,rt.column+1),!(ht>=Xt.MAX_PREVIEW_ROWS||rt.column>=Xt.MAX_PREVIEW_COLUMNS)&&Hr.set(rt.column,this.cell({...rt,row:ht})));if(Ot&&(d=Math.max(d,ht+1)),ht>=Xt.MAX_PREVIEW_ROWS)continue;let Fi=(0,W.numberAttr)(se,"ht");u.set(ht,{...Fi!==void 0?{height:Fi*4/3}:{},hidden:(0,W.attr)(se,"hidden")==="1"||(0,W.attr)(se,"hidden")==="true",cells:Hr})}let p=(0,te.xmlChildren)((0,te.xmlChild)(n,"mergeCells"),"mergeCell").map(se=>((0,W.attr)(se,"ref")??"").split(":").map(Uw)).filter(se=>se.length===2&&!!se[0]&&!!se[1]);for(let[,se]of p)d=Math.max(d,se.row+1),A=Math.max(A,se.column+1);let h=await this.drawingExtent({part:e,worksheet:n,defaultWidth:s,defaultHeight:a}),f=Math.min(Math.max(d,h.rows),Xt.MAX_PREVIEW_ROWS),E=Math.min(Math.max(A,h.columns),Xt.MAX_PREVIEW_COLUMNS),S=new Map,B=new Set;for(let[se,ht]of p){let ms=0,Hr=0;for(let Ot=se.row;Ot<=Math.min(ht.row,f-1);Ot+=1)u.get(Ot)?.hidden||(ms+=1);for(let Ot=se.column;Ot<=Math.min(ht.column,E-1);Ot+=1)l.has(Ot)||(Hr+=1);S.set(`${se.row}:${se.column}`,{rowSpan:ms,columnSpan:Hr});for(let Ot=se.row;Ot<=Math.min(ht.row,f-1);Ot+=1)for(let Fi=se.column;Fi<=Math.min(ht.column,E-1);Fi+=1)(Ot!==se.row||Fi!==se.column)&&B.add(`${Ot}:${Fi}`)}let _=Array.from({length:E},(se,ht)=>ht).filter(se=>!l.has(se)),v=Array.from({length:f},(se,ht)=>ht).filter(se=>!u.get(se)?.hidden),T=se=>c.get(se)??s,L=se=>u.get(se)?.height??a,k=new Map,P=qm;for(let se=0;se<E;se+=1)k.set(se,P),l.has(se)||(P+=T(se));let U=new Map,K=Dw;for(let se=0;se<f;se+=1)U.set(se,K),u.get(se)?.hidden||(K+=L(se));let Ae=se=>k.get(se)??P+(se-E)*s,Re=se=>U.get(se)??K+(se-f)*a,Ge=(0,te.xmlPath)(n,"sheetViews","sheetView"),tt=(0,W.attr)(Ge,"showGridLines")!=="0",Ht=(0,te.xmlChild)(Ge,"pane"),Nt=(0,W.attr)(Ht,"state")==="frozen"||(0,W.attr)(Ht,"state")==="frozenSplit",kr=Nt?(0,W.numberAttr)(Ht,"ySplit")??0:0,qr=Nt?(0,W.numberAttr)(Ht,"xSplit")??0:0,Dt=se=>se<kr?`${Re(se)}px`:void 0,pt=se=>se<qr?`${Ae(se)}px`:void 0,An=qm+_.reduce((se,ht)=>se+T(ht),0),Ci=this.styles.defaultFont()["font-size"]??"11pt",$n="";for(let[se,ht]of v.entries()){let ms=u.get(ht);$n+=`<tr${(0,W.styleAttribute)({height:`${L(ht)}px`})}><th class="rh"${(0,W.styleAttribute)({top:Dt(ht),"z-index":ht<kr?"4":void 0})}>${ht+1}</th>`;for(let[Hr,Ot]of _.entries()){let Fi=`${ht}:${Ot}`;if(B.has(Fi))continue;let rt=ms?.cells.get(Ot),na=S.get(Fi),xh=_[Hr+1],gD=xh===void 0?void 0:ms?.cells.get(xh),WZ=xh===void 0||!!(gD&&gD.kind!=="empty")||B.has(`${ht}:${xh}`),mD=rt?.format.horizontal??(rt?.kind==="number"?"right":rt?.kind==="boolean"||rt?.kind==="error"?"center":void 0),BC=Dt(ht),vC=pt(Ot),JZ=BC!==void 0||vC!==void 0,ZZ=(0,W.styleAttribute)({...rt?.format.css,...rt?.color?{color:rt.color}:{},"text-align":mD,"white-space":rt?rt.format.wrap?"pre-wrap":"pre":void 0,overflow:rt&&!(rt.format.wrap||WZ||na||mD==="right")?"visible":rt?"hidden":void 0,...JZ?{position:"sticky",top:BC,left:vC,"z-index":BC!==void 0&&vC!==void 0?"3":"2",background:rt?.format.css.background??"#fff"}:{}}),KZ=na?`${na.columnSpan>1?` colspan="${na.columnSpan}"`:""}${na.rowSpan>1?` rowspan="${na.rowSpan}"`:""}`:"",XZ=v.slice(se,se+(na?.rowSpan??1)).reduce((QC,TC)=>QC+L(TC),0),e6=_.slice(Hr,Hr+(na?.columnSpan??1)).reduce((QC,TC)=>QC+T(TC),0),t6=rt?.kind==="number"&&!rt.format.wrap?Yge({text:rt.text,html:rt.html,width:e6,fontSize:rt.format.css["font-size"]??Ci}):rt?.format.wrap&&rt.html?`<div class="clip"${(0,W.styleAttribute)({"max-height":`${XZ-1}px`})}>${rt.html}</div>`:rt?.html??"";$n+=`<td${KZ}${ZZ}>${t6}</td>`}$n+="</tr>"}let gs=await this.drawings({part:e,worksheet:n,columnOffsets:Ae,rowOffsets:Re}),ra=`<tr class="ch"><th class="corner"></th>${_.map(se=>`<th>${xw(se)}</th>`).join("")}</tr>`,Nl=["html,body{margin:0;background:#fff}","body{font-family:Calibri,Arial,sans-serif;font-size:11pt;color:#000}",".wrap{position:relative;display:inline-block;min-width:100%}",`table{border-collapse:separate;border-spacing:0;table-layout:fixed;width:${An}px}`,`td{padding:0 3px;line-height:1.2;${tt?"border-right:1px solid #e3e3e3;border-bottom:1px solid #e3e3e3;":""}box-sizing:border-box}`,"th{position:sticky;z-index:5;background:#f3f3f3;color:#555;font:400 11px/1 system-ui,sans-serif;border-right:1px solid #d4d4d4;border-bottom:1px solid #d4d4d4;text-align:center;padding:0;box-sizing:border-box}",`.ch th{top:0;height:${Dw}px}`,".rh{left:0;z-index:3}",".corner{left:0;z-index:6}",".drawing{position:absolute;z-index:1}",".clip{overflow:hidden}",".chart{background:#fff;border:1px solid #d9d9d9;box-sizing:border-box}"].join(`
|
|
793
793
|
`),_C=(0,W.officeHtmlDocument)({title:r,css:Nl,body:`<div class="wrap"${(0,W.styleAttribute)(this.styles.defaultFont())}><table><colgroup><col${(0,W.styleAttribute)({width:`${qm}px`})}>${_.map(se=>`<col${(0,W.styleAttribute)({width:`${T(se)}px`})}>`).join("")}</colgroup><thead>${ra}</thead><tbody>${$n}</tbody></table>${gs}</div>`});return{name:r,html:_C,rowCount:d,columnCount:A,shownRows:f,shownColumns:E}}};async function U$(t){let e=await t.readXml(VA);if(!e)throw new Error("The file has no Excel workbook");let r=await(0,W.readOfficeTheme)(t,await t.relatedPart(VA,"/theme")),n=new Hm(r),i=await t.relatedPart(VA,"/styles");n.load(i?await t.readXml(i):void 0);let o=await t.relatedPart(VA,"/sharedStrings"),s=o?await t.readText(o):void 0,a=s?Array.from((0,te.streamXmlElements)({xml:s,container:"sst",element:"si"}).elements(),u=>O$(u,n)):[],c=(0,te.xmlChild)(e,"workbookPr"),l=[];for(let u of(0,te.xmlChildren)((0,te.xmlChild)(e,"sheets"),"sheet")){let d=await t.relatedPartById(VA,(0,W.attr)(u,"r:id"));!d||!d.includes("worksheets/")||l.push({name:(0,W.attr)(u,"name")??`Sheet ${l.length+1}`,part:d,hidden:(0,W.attr)(u,"state")==="hidden"||(0,W.attr)(u,"state")==="veryHidden"})}return{officePackage:t,styles:n,sharedStrings:a,theme:r,date1904:(0,W.attr)(c,"date1904")==="1"||(0,W.attr)(c,"date1904")==="true",sheets:l}}async function Vge({officePackage:t}){let e=await U$(t),r=new Nw(e),n=e.sheets.filter(i=>!i.hidden).map(i=>({name:i.name,render:()=>r.render(i.part,i.name)}));if(n.length===0)throw new Error("The workbook has no visible worksheets");return n}});var Ym=y(WA=>{"use strict";Object.defineProperty(WA,"__esModule",{value:!0});WA.cleanText=Wge;WA.markdownTable=P$;WA.chartMarkdown=Jge;function Wge(t){return t.replace(/[\u000b\r]/g,`
|
|
794
794
|
`).replace(/[ \t]+/g," ").trim()}function M$(t){return t.replace(/\|/g,"\\|").replace(/\n+/g," ").trim()}function P$(t){if(t.length===0)return"";let e=t.reduce((n,i)=>Math.max(n,i.length),0),r=t.map(n=>[...n,...Array(e-n.length).fill("")]);return[`| ${r[0].map(M$).join(" | ")} |`,`| ${r[0].map(()=>"---").join(" | ")} |`,...r.slice(1).map(n=>`| ${n.map(M$).join(" | ")} |`)].join(`
|
|
795
795
|
`)}function Jge(t){let e=[t.title?`Chart: ${t.title}`:"Chart"],r=t.series.find(i=>i.categories.length>0)?.categories??[],n=Math.max(r.length,...t.series.map(i=>i.values.length),0);return t.series.length>0&&n>0&&e.push(P$([["Category",...t.series.map(i=>i.name)],...Array.from({length:n},(i,o)=>[r[o]??String(o+1),...t.series.map(s=>s.values[o]??"")])])),e.join(`
|
|
@@ -2100,7 +2100,7 @@ ${A(B)}\r
|
|
|
2100
2100
|
Content-Type: ${B.type||"application/octet-stream"}\r
|
|
2101
2101
|
\r
|
|
2102
2102
|
`);p.push(_,B,h),typeof B.size=="number"?s+=_.byteLength+B.size+h.byteLength:f=!0}let E=tE.encode(`--${l}--\r
|
|
2103
|
-
`);p.push(E),s+=E.byteLength,f&&(s=null),o=t,i=async function*(){for(let S of p)S.stream?yield*S.stream():yield S},a=`multipart/form-data; boundary=${l}`}else if(Oi.is.Blob(t))o=t,s=t.size,t.type&&(a=t.type);else if(typeof t[Symbol.asyncIterator]=="function"){if(e)throw new TypeError("keepalive");if(BB.isDisturbed(t)||t.locked)throw new TypeError("Response body object should not be disturbed or locked");r=Oi.is.ReadableStream(t)?t:hve(t)}return(typeof o=="string"||Ive(o))&&(i=()=>(s=typeof o=="string"?Buffer.byteLength(o):o.length,o)),i!=null&&(async()=>{let l=i(),u=l?.[Symbol.asyncIterator]?.();if(u)for await(let d of u){if(_B(r))break;d.length&&n.enqueue(new Uint8Array(d))}else l?.length&&!_B(r)&&n.enqueue(typeof l=="string"?tE.encode(l):new Uint8Array(l));queueMicrotask(()=>fve(n))})(),[{stream:r,source:o,length:s},a]}function Dve(t,e=!1){return Oi.is.ReadableStream(t)&&(wB(!BB.isDisturbed(t),"The body has already been consumed."),wB(!t.locked,"The stream is locked.")),Lz(t,e)}function kve(t){let{0:e,1:r}=t.stream.tee();return t.stream=e,{stream:r,length:t.length,source:t.source}}function Rve(t,e){return{blob(){return Lu(this,n=>{let i=Pz(e(this));return i===null?i="":i&&(i=Cve(i)),new Blob([n],{type:i})},t,e)},arrayBuffer(){return Lu(this,n=>new Uint8Array(n).buffer,t,e)},text(){return Lu(this,_ve,t,e)},json(){return Lu(this,wve,t,e)},formData(){return Lu(this,n=>{let i=Pz(e(this));if(i!==null)switch(i.essence){case"multipart/form-data":{let o=bve(n,i),s=new Mz;return yve(s,o),s}case"application/x-www-form-urlencoded":{let o=new URLSearchParams(n.toString()),s=new Mz;for(let[a,c]of o)s.append(a,c);return s}}throw new TypeError('Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".')},t,e)},bytes(){return Lu(this,n=>new Uint8Array(n),t,e)}}}function Nve(t,e){Object.assign(t.prototype,Rve(t,e))}function Lu(t,e,r,n){try{Oi.brandCheck(t,r)}catch(a){return Promise.reject(a)}if(t=n(t),$z(t))return Promise.reject(new TypeError("Body is unusable: Body has already been read"));let i=Sve(),o=i.reject,s=a=>{try{i.resolve(e(a))}catch(c){o(c)}};return t.body==null?(s(Buffer.allocUnsafe(0)),i.promise):(gve(t.body,s,o),i.promise)}function $z(t){let e=t.body;return e!=null&&(e.stream.locked||BB.isDisturbed(e.stream))}function Pz(t){let e=t.headersList,r=mve(e);return r==="failure"?null:r}Fz.exports={extractBody:Lz,safelyExtractBody:Dve,cloneBody:kve,mixinBody:Nve,streamRegistry:Tve,bodyUnusable:$z}});var rq=y((Fze,tq)=>{"use strict";var be=require("assert"),ye=De(),{channels:jz}=Ra(),vB=a_(),{RequestContentLengthMismatchError:Vc,ResponseContentLengthMismatchError:zz,RequestAbortedError:Zz,InvalidArgumentError:Ove,HeadersTimeoutError:xve,HeadersOverflowError:Uve,SocketError:Wc,InformationalError:Fu,BodyTimeoutError:Mve,HTTPParserError:Pve,ResponseExceededMaxSizeError:Lve}=_e(),{kUrl:Kz,kReset:rn,kClient:sE,kParser:bt,kBlocking:Op,kRunning:Xt,kPending:OB,kSize:qz,kWriting:xa,kQueue:xi,kNoRef:Rp,kKeepAliveDefaultTimeout:$ve,kHostHeader:Fve,kPendingIdx:jve,kRunningIdx:ui,kError:Pr,kPipelining:iE,kSocket:Jc,kKeepAliveTimeoutValue:aE,kMaxHeadersSize:zve,kKeepAliveMaxTimeout:qve,kKeepAliveTimeoutThreshold:Hve,kHeadersTimeout:Gve,kBodyTimeout:Yve,kStrictContentLength:DB,kMaxRequests:Hz,kCounter:Vve,kMaxResponseSize:Wve,kOnError:Gz,kResume:$s,kHTTPContext:Xz,kClosed:kB}=ut(),Tn=F2(),Yz=Buffer.alloc(0),rE=Buffer[Symbol.species],Jve=ye.removeAllListeners,Zc=Symbol("kIdleSocketValidation"),ju=Symbol("kIdleSocketValidationTimeout"),xB=Symbol("kSocketUsed"),QB;function Zve(){let t=process.env.JEST_WORKER_ID?eB():void 0,e,r=!0;if(process.arch==="ppc64"){let[n,i]=process.versions.node.split(".").map(o=>parseInt(o,10));(n<24||n===24&&i<12)&&(r=!1)}if(process.env.UNDICI_NO_WASM_SIMD==="1"?r=!1:process.env.UNDICI_NO_WASM_SIMD==="0"&&(r=!0),r)try{e=new WebAssembly.Module(q2())}catch{}return e||(e=new WebAssembly.Module(t||eB())),new WebAssembly.Instance(e,{env:{wasm_on_url:(n,i,o)=>0,wasm_on_status:(n,i,o)=>{be(zt.ptr===n);let s=i-ts+es.byteOffset;return zt.onStatus(new rE(es.buffer,s,o))},wasm_on_message_begin:n=>(be(zt.ptr===n),zt.onMessageBegin()),wasm_on_header_field:(n,i,o)=>{be(zt.ptr===n);let s=i-ts+es.byteOffset;return zt.onHeaderField(new rE(es.buffer,s,o))},wasm_on_header_value:(n,i,o)=>{be(zt.ptr===n);let s=i-ts+es.byteOffset;return zt.onHeaderValue(new rE(es.buffer,s,o))},wasm_on_headers_complete:(n,i,o,s)=>(be(zt.ptr===n),zt.onHeadersComplete(i,o===1,s===1)),wasm_on_body:(n,i,o)=>{be(zt.ptr===n);let s=i-ts+es.byteOffset;return zt.onBody(new rE(es.buffer,s,o))},wasm_on_message_complete:n=>(be(zt.ptr===n),zt.onMessageComplete())}})}var TB=null,zt=null,es=null,nE=0,ts=null,Kve=0,Np=1,zu=2|Np,oE=4|Np,RB=8|Kve,NB=class{constructor(e,r,{exports:n}){this.llhttp=n,this.ptr=this.llhttp.llhttp_alloc(Tn.TYPE.RESPONSE),this.client=e,this.socket=r,this.timeout=null,this.timeoutWeakRef=new WeakRef(this),this.timeoutValue=null,this.timeoutType=null,this.statusCode=0,this.statusText="",this.upgrade=!1,this.headers=[],this.headersSize=0,this.headersMaxSize=e[zve],this.shouldKeepAlive=!1,this.paused=!1,this.resume=this.resume.bind(this),this.bytesRead=0,this.keepAlive="",this.contentLength="",this.connection="",this.maxResponseSize=e[Wve]}setTimeout(e,r){e!==this.timeoutValue||r&Np^this.timeoutType&Np?(this.timeout&&(vB.clearTimeout(this.timeout),this.timeout=null),e&&(r&Np?this.timeout=vB.setFastTimeout(Vz,e,this.timeoutWeakRef):(this.timeout=setTimeout(Vz,e,this.timeoutWeakRef),this.timeout?.unref())),this.timeoutValue=e):this.timeout&&this.timeout.refresh&&this.timeout.refresh(),this.timeoutType=r}resume(){this.socket.destroyed||!this.paused||(be(this.ptr!=null),be(zt===null),this.llhttp.llhttp_resume(this.ptr),be(this.timeoutType===oE),this.timeout&&this.timeout.refresh&&this.timeout.refresh(),this.paused=!1,this.execute(this.socket.read()||Yz),this.readMore())}readMore(){for(;!this.paused&&this.ptr;){let e=this.socket.read();if(e===null)break;this.execute(e)}}execute(e){be(zt===null),be(this.ptr!=null),be(!this.paused);let{socket:r,llhttp:n}=this;e.length>nE&&(ts&&n.free(ts),nE=Math.ceil(e.length/4096)*4096,ts=n.malloc(nE)),new Uint8Array(n.memory.buffer,ts,nE).set(e);try{let i;try{es=e,zt=this,i=n.llhttp_execute(this.ptr,ts,e.length)}finally{zt=null,es=null}if(i!==Tn.ERROR.OK){let o=e.subarray(n.llhttp_get_error_pos(this.ptr)-ts);if(i===Tn.ERROR.PAUSED_UPGRADE)this.onUpgrade(o);else if(i===Tn.ERROR.PAUSED)this.paused=!0,r.unshift(o);else throw this.createError(i,o)}}catch(i){ye.destroy(r,i)}}finish(){be(zt===null),be(this.ptr!=null),be(!this.paused);let{llhttp:e}=this,r;try{zt=this,r=e.llhttp_finish(this.ptr)}finally{zt=null}return r===Tn.ERROR.OK?null:r===Tn.ERROR.PAUSED||r===Tn.ERROR.PAUSED_UPGRADE?(this.paused=!0,null):this.createError(r,Yz)}createError(e,r){let{llhttp:n,contentLength:i,bytesRead:o}=this;if(i&&o!==parseInt(i,10))return new zz;let s=n.llhttp_get_error_reason(this.ptr),a="";if(s){let c=new Uint8Array(n.memory.buffer,s).indexOf(0);a="Response does not match the HTTP/1.1 protocol ("+Buffer.from(n.memory.buffer,s,c).toString()+")"}return new Pve(a,Tn.ERROR[e],r)}destroy(){be(zt===null),be(this.ptr!=null),this.llhttp.llhttp_free(this.ptr),this.ptr=null,this.timeout&&vB.clearTimeout(this.timeout),this.timeout=null,this.timeoutValue=null,this.timeoutType=null,this.paused=!1}onStatus(e){return this.statusText=e.toString(),0}onMessageBegin(){let{socket:e,client:r}=this;if(e.destroyed)return-1;if(r[Xt]===0)return ye.destroy(e,new Wc("bad response",ye.getSocketInfo(e))),-1;let n=r[xi][r[ui]];return n?(n.onResponseStarted(),0):-1}onHeaderField(e){let r=this.headers.length;return(r&1)===0?this.headers.push(e):this.headers[r-1]=Buffer.concat([this.headers[r-1],e]),this.trackHeader(e.length),0}onHeaderValue(e){let r=this.headers.length;(r&1)===1?(this.headers.push(e),r+=1):this.headers[r-1]=Buffer.concat([this.headers[r-1],e]);let n=this.headers[r-2];if(n.length===10){let i=ye.bufferToLowerCasedHeaderName(n);i==="keep-alive"?this.keepAlive+=e.toString():i==="connection"&&(this.connection+=e.toString())}else n.length===14&&ye.bufferToLowerCasedHeaderName(n)==="content-length"&&(this.contentLength+=e.toString());return this.trackHeader(e.length),0}trackHeader(e){this.headersSize+=e,this.headersSize>=this.headersMaxSize&&ye.destroy(this.socket,new Uve)}onUpgrade(e){let{upgrade:r,client:n,socket:i,headers:o,statusCode:s,statusText:a}=this;be(r),be(n[Jc]===i),be(!i.destroyed),be(!this.paused),be((o.length&1)===0);let c=n[xi][n[ui]];be(c),be(c.upgrade||c.method==="CONNECT"),this.statusCode=0,this.statusText="",this.shouldKeepAlive=!1,this.headers=[],this.headersSize=0,i.unshift(e),i[bt].destroy(),i[bt]=null,i[sE]=null,i[Pr]=null,Jve(i),n[Jc]=null,n[Xz]=null,n[xi][n[ui]++]=null,n.emit("disconnect",n[Kz],[n],new Fu("upgrade"));try{c.onUpgrade(s,o,i,a)}catch(l){ye.errorRequest(n,c,l),ye.destroy(i,l)}n[$s]()}onHeadersComplete(e,r,n){let{client:i,socket:o,headers:s,statusText:a}=this;if(o.destroyed)return-1;if(i[Xt]===0)return ye.destroy(o,new Wc("bad response",ye.getSocketInfo(o))),-1;let c=i[xi][i[ui]];if(!c)return-1;if(be(!this.upgrade),be(this.statusCode<200),e===100)return ye.destroy(o,new Wc("bad response",ye.getSocketInfo(o))),-1;if(r&&!c.upgrade)return ye.destroy(o,new Wc("bad upgrade",ye.getSocketInfo(o))),-1;if(be(this.timeoutType===zu),this.statusCode=e,this.shouldKeepAlive=n||c.method==="HEAD"&&!o[rn]&&this.connection.toLowerCase()==="keep-alive",this.statusCode>=200){let u=c.bodyTimeout!=null?c.bodyTimeout:i[Yve];this.setTimeout(u,oE)}else this.timeout&&this.timeout.refresh&&this.timeout.refresh();if(c.method==="CONNECT")return be(i[Xt]===1),this.upgrade=!0,2;if(r)return be(i[Xt]===1),this.upgrade=!0,2;if(be((this.headers.length&1)===0),this.headers=[],this.headersSize=0,this.shouldKeepAlive&&i[iE]){let u=this.keepAlive?ye.parseKeepAliveTimeout(this.keepAlive):null;if(u!=null){let d=Math.min(u-i[Hve],i[qve]);d<=0?o[rn]=!0:i[aE]=d}else i[aE]=i[$ve]}else o[rn]=!0;let l=c.onHeaders(e,s,this.resume,a)===!1;return c.aborted?-1:c.method==="HEAD"||e<200?1:(o[Op]&&(o[Op]=!1,i[$s]()),l?Tn.ERROR.PAUSED:0)}onBody(e){let{client:r,socket:n,statusCode:i,maxResponseSize:o}=this;if(n.destroyed)return-1;let s=r[xi][r[ui]];return be(s),be(this.timeoutType===oE),this.timeout&&this.timeout.refresh&&this.timeout.refresh(),be(i>=200),o>-1&&this.bytesRead+e.length>o?(ye.destroy(n,new Lve),-1):(this.bytesRead+=e.length,s.onData(e)===!1?Tn.ERROR.PAUSED:0)}onMessageComplete(){let{client:e,socket:r,statusCode:n,upgrade:i,headers:o,contentLength:s,bytesRead:a,shouldKeepAlive:c}=this;if(r.destroyed&&(!n||c))return-1;if(i)return 0;be(n>=100),be((this.headers.length&1)===0);let l=e[xi][e[ui]];if(be(l),this.statusCode=0,this.statusText="",this.bytesRead=0,this.contentLength="",this.keepAlive="",this.connection="",this.headers=[],this.headersSize=0,n<200)return 0;if(l.method!=="HEAD"&&s&&a!==parseInt(s,10))return ye.destroy(r,new zz),-1;if(l.onComplete(o),e[xi][e[ui]++]=null,r[xB]=e[OB]===0,r[xa])return be(e[Xt]===0),ye.destroy(r,new Fu("reset")),Tn.ERROR.PAUSED;if(c){if(r[rn]&&e[Xt]===0)return ye.destroy(r,new Fu("reset")),Tn.ERROR.PAUSED;e[iE]==null||e[iE]===1?setImmediate(e[$s]):e[$s]()}else return ye.destroy(r,new Fu("reset")),Tn.ERROR.PAUSED;return 0}};function Vz(t){let e=t.deref();if(!e)return;let{socket:r,timeoutType:n,client:i,paused:o}=e;n===zu?(!r[xa]||r.writableNeedDrain||i[Xt]>1)&&(be(!o,"cannot be paused while waiting for headers"),ye.destroy(r,new xve)):n===oE?o||ye.destroy(r,new Mve):n===RB&&(be(i[Xt]===0&&i[aE]),ye.destroy(r,new Fu("socket idle timeout")))}function Xve(t,e){if(t[Jc]=e,TB||(TB=Zve()),e.errored)throw e.errored;if(e.destroyed)throw new Wc("destroyed");return e[Rp]=!1,e[xa]=!1,e[rn]=!1,e[Op]=!1,e[Zc]=0,e[ju]=null,e[xB]=!1,e[bt]=new NB(t,e,TB),ye.addListener(e,"error",eQe),ye.addListener(e,"readable",tQe),ye.addListener(e,"end",rQe),ye.addListener(e,"close",nQe),e[kB]=!1,e.on("close",iQe),{version:"h1",defaultPipelining:1,write(r){return cQe(t,r)},resume(){sQe(t)},destroy(r,n){e[kB]?queueMicrotask(n):(e.on("close",n),e.destroy(r))},get destroyed(){return e.destroyed},busy(r){return!!(e[xa]||e[rn]||e[Op]||e[Zc]===1||r&&(t[Xt]>0&&!r.idempotent||t[Xt]>0&&(r.upgrade||r.method==="CONNECT")||t[Xt]>0&&ye.bodyLength(r.body)!==0&&(ye.isStream(r.body)||ye.isAsyncIterable(r.body)||ye.isFormDataLike(r.body))))}}}function eQe(t){be(t.code!=="ERR_TLS_CERT_ALTNAME_INVALID");let e=this[bt];if(t.code==="ECONNRESET"&&e.statusCode&&!e.shouldKeepAlive){let r=e.finish();r&&(this[Pr]=r,this[sE][Gz](r));return}this[Pr]=t,this[sE][Gz](t)}function tQe(){this[bt]?.readMore()}function rQe(){let t=this[bt];if(t.statusCode&&!t.shouldKeepAlive){let e=t.finish();e&&ye.destroy(this,e);return}ye.destroy(this,new Wc("other side closed",ye.getSocketInfo(this)))}function nQe(){let t=this[bt];eq(this),t&&(!this[Pr]&&t.statusCode&&!t.shouldKeepAlive&&(this[Pr]=t.finish()||this[Pr]),this[bt].destroy(),this[bt]=null);let e=this[Pr]||new Wc("closed",ye.getSocketInfo(this)),r=this[sE];if(r[Jc]=null,r[Xz]=null,r.destroyed){be(r[OB]===0);let n=r[xi].splice(r[ui]);for(let i=0;i<n.length;i++){let o=n[i];ye.errorRequest(r,o,e)}}else if(r[Xt]>0&&e.code!=="UND_ERR_INFO"){let n=r[xi][r[ui]];r[xi][r[ui]++]=null,ye.errorRequest(r,n,e)}r[jve]=r[ui],be(r[Xt]===0),r.emit("disconnect",r[Kz],[r],e),r[$s]()}function iQe(){this[kB]=!0}function eq(t){t[ju]&&(clearImmediate(t[ju]),t[ju]=null),t[Zc]=0}function oQe(t,e){e[Zc]=1,e[ju]=setImmediate(()=>{e[ju]=null,e[Zc]=2,t[Jc]===e&&!e.destroyed&&t[$s]()})}function sQe(t){let e=t[Jc];if(e&&!e.destroyed){if(t[qz]===0?!e[Rp]&&e.unref&&(e.unref(),e[Rp]=!0):e[Rp]&&e.ref&&(e.ref(),e[Rp]=!1),t[Xt]===0&&t[OB]>0&&e[xB]){if(e[Zc]===0)return oQe(t,e),e[bt].readMore(),e.destroyed,void 0;if(e[Zc]===1)return e[bt].readMore(),e.destroyed,void 0}if(t[Xt]===0&&(e[bt].readMore(),e.destroyed))return;if(t[qz]===0)e[bt].timeoutType!==RB&&e[bt].setTimeout(t[aE],RB);else if(t[Xt]>0&&e[bt].statusCode<200&&e[bt].timeoutType!==zu){let r=t[xi][t[ui]],n=r.headersTimeout!=null?r.headersTimeout:t[Gve];e[bt].setTimeout(n,zu)}}}function aQe(t){return t!=="GET"&&t!=="HEAD"&&t!=="OPTIONS"&&t!=="TRACE"&&t!=="CONNECT"}function cQe(t,e){let{method:r,path:n,host:i,upgrade:o,blocking:s,reset:a}=e,{body:c,headers:l,contentLength:u}=e,d=r==="PUT"||r==="POST"||r==="PATCH"||r==="QUERY"||r==="PROPFIND"||r==="PROPPATCH";if(ye.isFormDataLike(c)){QB||(QB=$u().extractBody);let[E,S]=QB(c);e.contentType==null&&l.push("content-type",S),c=E.stream,u=E.length}else if(ye.isBlobLike(c)&&e.contentType==null){let E=c.type;if(E){let S=`${E}`;if(!ye.isValidHeaderValue(S))return ye.errorRequest(t,e,new Ove("invalid content-type header")),!1;l.push("content-type",S)}}c&&typeof c.read=="function"&&c.read(0);let A=ye.bodyLength(c);if(u=A??u,u===null&&(u=e.contentLength),u===0&&!d&&(u=null),aQe(r)&&u>0&&e.contentLength!==null&&e.contentLength!==u){if(t[DB])return ye.errorRequest(t,e,new Vc),!1;process.emitWarning(new Vc)}let p=t[Jc];eq(p);let h=E=>{e.aborted||e.completed||(ye.errorRequest(t,e,E||new Zz),ye.destroy(c),ye.destroy(p,new Fu("aborted")))};try{e.onConnect(h)}catch(E){ye.errorRequest(t,e,E)}if(e.aborted)return!1;r==="HEAD"&&(p[rn]=!0),(o||r==="CONNECT")&&(p[rn]=!0),a!=null&&(p[rn]=a),t[Hz]&&p[Vve]++>=t[Hz]&&(p[rn]=!0),s&&(p[Op]=!0),p.setTypeOfService&&p.setTypeOfService(e.typeOfService);let f=`${r} ${n} HTTP/1.1\r
|
|
2103
|
+
`);p.push(E),s+=E.byteLength,f&&(s=null),o=t,i=async function*(){for(let S of p)S.stream?yield*S.stream():yield S},a=`multipart/form-data; boundary=${l}`}else if(Oi.is.Blob(t))o=t,s=t.size,t.type&&(a=t.type);else if(typeof t[Symbol.asyncIterator]=="function"){if(e)throw new TypeError("keepalive");if(BB.isDisturbed(t)||t.locked)throw new TypeError("Response body object should not be disturbed or locked");r=Oi.is.ReadableStream(t)?t:hve(t)}return(typeof o=="string"||Ive(o))&&(i=()=>(s=typeof o=="string"?Buffer.byteLength(o):o.length,o)),i!=null&&(async()=>{let l=i(),u=l?.[Symbol.asyncIterator]?.();if(u)for await(let d of u){if(_B(r))break;d.length&&n.enqueue(new Uint8Array(d))}else l?.length&&!_B(r)&&n.enqueue(typeof l=="string"?tE.encode(l):new Uint8Array(l));queueMicrotask(()=>fve(n))})(),[{stream:r,source:o,length:s},a]}function Dve(t,e=!1){return Oi.is.ReadableStream(t)&&(wB(!BB.isDisturbed(t),"The body has already been consumed."),wB(!t.locked,"The stream is locked.")),Lz(t,e)}function kve(t){let{0:e,1:r}=t.stream.tee();return t.stream=e,{stream:r,length:t.length,source:t.source}}function Rve(t,e){return{blob(){return Lu(this,n=>{let i=Pz(e(this));return i===null?i="":i&&(i=Cve(i)),new Blob([n],{type:i})},t,e)},arrayBuffer(){return Lu(this,n=>new Uint8Array(n).buffer,t,e)},text(){return Lu(this,_ve,t,e)},json(){return Lu(this,wve,t,e)},formData(){return Lu(this,n=>{let i=Pz(e(this));if(i!==null)switch(i.essence){case"multipart/form-data":{let o=bve(n,i),s=new Mz;return yve(s,o),s}case"application/x-www-form-urlencoded":{let o=new URLSearchParams(n.toString()),s=new Mz;for(let[a,c]of o)s.append(a,c);return s}}throw new TypeError('Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".')},t,e)},bytes(){return Lu(this,n=>new Uint8Array(n),t,e)}}}function Nve(t,e){Object.assign(t.prototype,Rve(t,e))}function Lu(t,e,r,n){try{Oi.brandCheck(t,r)}catch(a){return Promise.reject(a)}if(t=n(t),$z(t))return Promise.reject(new TypeError("Body is unusable: Body has already been read"));let i=Sve(),o=i.reject,s=a=>{try{i.resolve(e(a))}catch(c){o(c)}};return t.body==null?(s(Buffer.allocUnsafe(0)),i.promise):(gve(t.body,s,o),i.promise)}function $z(t){let e=t.body;return e!=null&&(e.stream.locked||BB.isDisturbed(e.stream))}function Pz(t){let e=t.headersList,r=mve(e);return r==="failure"?null:r}Fz.exports={extractBody:Lz,safelyExtractBody:Dve,cloneBody:kve,mixinBody:Nve,streamRegistry:Tve,bodyUnusable:$z}});var rq=y((Fze,tq)=>{"use strict";var be=require("assert"),ye=De(),{channels:jz}=Ra(),vB=a_(),{RequestContentLengthMismatchError:Vc,ResponseContentLengthMismatchError:zz,RequestAbortedError:Zz,InvalidArgumentError:Ove,HeadersTimeoutError:xve,HeadersOverflowError:Uve,SocketError:Wc,InformationalError:Fu,BodyTimeoutError:Mve,HTTPParserError:Pve,ResponseExceededMaxSizeError:Lve}=_e(),{kUrl:Kz,kReset:rn,kClient:sE,kParser:bt,kBlocking:Op,kRunning:er,kPending:OB,kSize:qz,kWriting:xa,kQueue:xi,kNoRef:Rp,kKeepAliveDefaultTimeout:$ve,kHostHeader:Fve,kPendingIdx:jve,kRunningIdx:ui,kError:Pr,kPipelining:iE,kSocket:Jc,kKeepAliveTimeoutValue:aE,kMaxHeadersSize:zve,kKeepAliveMaxTimeout:qve,kKeepAliveTimeoutThreshold:Hve,kHeadersTimeout:Gve,kBodyTimeout:Yve,kStrictContentLength:DB,kMaxRequests:Hz,kCounter:Vve,kMaxResponseSize:Wve,kOnError:Gz,kResume:$s,kHTTPContext:Xz,kClosed:kB}=ut(),Tn=F2(),Yz=Buffer.alloc(0),rE=Buffer[Symbol.species],Jve=ye.removeAllListeners,Zc=Symbol("kIdleSocketValidation"),ju=Symbol("kIdleSocketValidationTimeout"),xB=Symbol("kSocketUsed"),QB;function Zve(){let t=process.env.JEST_WORKER_ID?eB():void 0,e,r=!0;if(process.arch==="ppc64"){let[n,i]=process.versions.node.split(".").map(o=>parseInt(o,10));(n<24||n===24&&i<12)&&(r=!1)}if(process.env.UNDICI_NO_WASM_SIMD==="1"?r=!1:process.env.UNDICI_NO_WASM_SIMD==="0"&&(r=!0),r)try{e=new WebAssembly.Module(q2())}catch{}return e||(e=new WebAssembly.Module(t||eB())),new WebAssembly.Instance(e,{env:{wasm_on_url:(n,i,o)=>0,wasm_on_status:(n,i,o)=>{be(zt.ptr===n);let s=i-ts+es.byteOffset;return zt.onStatus(new rE(es.buffer,s,o))},wasm_on_message_begin:n=>(be(zt.ptr===n),zt.onMessageBegin()),wasm_on_header_field:(n,i,o)=>{be(zt.ptr===n);let s=i-ts+es.byteOffset;return zt.onHeaderField(new rE(es.buffer,s,o))},wasm_on_header_value:(n,i,o)=>{be(zt.ptr===n);let s=i-ts+es.byteOffset;return zt.onHeaderValue(new rE(es.buffer,s,o))},wasm_on_headers_complete:(n,i,o,s)=>(be(zt.ptr===n),zt.onHeadersComplete(i,o===1,s===1)),wasm_on_body:(n,i,o)=>{be(zt.ptr===n);let s=i-ts+es.byteOffset;return zt.onBody(new rE(es.buffer,s,o))},wasm_on_message_complete:n=>(be(zt.ptr===n),zt.onMessageComplete())}})}var TB=null,zt=null,es=null,nE=0,ts=null,Kve=0,Np=1,zu=2|Np,oE=4|Np,RB=8|Kve,NB=class{constructor(e,r,{exports:n}){this.llhttp=n,this.ptr=this.llhttp.llhttp_alloc(Tn.TYPE.RESPONSE),this.client=e,this.socket=r,this.timeout=null,this.timeoutWeakRef=new WeakRef(this),this.timeoutValue=null,this.timeoutType=null,this.statusCode=0,this.statusText="",this.upgrade=!1,this.headers=[],this.headersSize=0,this.headersMaxSize=e[zve],this.shouldKeepAlive=!1,this.paused=!1,this.resume=this.resume.bind(this),this.bytesRead=0,this.keepAlive="",this.contentLength="",this.connection="",this.maxResponseSize=e[Wve]}setTimeout(e,r){e!==this.timeoutValue||r&Np^this.timeoutType&Np?(this.timeout&&(vB.clearTimeout(this.timeout),this.timeout=null),e&&(r&Np?this.timeout=vB.setFastTimeout(Vz,e,this.timeoutWeakRef):(this.timeout=setTimeout(Vz,e,this.timeoutWeakRef),this.timeout?.unref())),this.timeoutValue=e):this.timeout&&this.timeout.refresh&&this.timeout.refresh(),this.timeoutType=r}resume(){this.socket.destroyed||!this.paused||(be(this.ptr!=null),be(zt===null),this.llhttp.llhttp_resume(this.ptr),be(this.timeoutType===oE),this.timeout&&this.timeout.refresh&&this.timeout.refresh(),this.paused=!1,this.execute(this.socket.read()||Yz),this.readMore())}readMore(){for(;!this.paused&&this.ptr;){let e=this.socket.read();if(e===null)break;this.execute(e)}}execute(e){be(zt===null),be(this.ptr!=null),be(!this.paused);let{socket:r,llhttp:n}=this;e.length>nE&&(ts&&n.free(ts),nE=Math.ceil(e.length/4096)*4096,ts=n.malloc(nE)),new Uint8Array(n.memory.buffer,ts,nE).set(e);try{let i;try{es=e,zt=this,i=n.llhttp_execute(this.ptr,ts,e.length)}finally{zt=null,es=null}if(i!==Tn.ERROR.OK){let o=e.subarray(n.llhttp_get_error_pos(this.ptr)-ts);if(i===Tn.ERROR.PAUSED_UPGRADE)this.onUpgrade(o);else if(i===Tn.ERROR.PAUSED)this.paused=!0,r.unshift(o);else throw this.createError(i,o)}}catch(i){ye.destroy(r,i)}}finish(){be(zt===null),be(this.ptr!=null),be(!this.paused);let{llhttp:e}=this,r;try{zt=this,r=e.llhttp_finish(this.ptr)}finally{zt=null}return r===Tn.ERROR.OK?null:r===Tn.ERROR.PAUSED||r===Tn.ERROR.PAUSED_UPGRADE?(this.paused=!0,null):this.createError(r,Yz)}createError(e,r){let{llhttp:n,contentLength:i,bytesRead:o}=this;if(i&&o!==parseInt(i,10))return new zz;let s=n.llhttp_get_error_reason(this.ptr),a="";if(s){let c=new Uint8Array(n.memory.buffer,s).indexOf(0);a="Response does not match the HTTP/1.1 protocol ("+Buffer.from(n.memory.buffer,s,c).toString()+")"}return new Pve(a,Tn.ERROR[e],r)}destroy(){be(zt===null),be(this.ptr!=null),this.llhttp.llhttp_free(this.ptr),this.ptr=null,this.timeout&&vB.clearTimeout(this.timeout),this.timeout=null,this.timeoutValue=null,this.timeoutType=null,this.paused=!1}onStatus(e){return this.statusText=e.toString(),0}onMessageBegin(){let{socket:e,client:r}=this;if(e.destroyed)return-1;if(r[er]===0)return ye.destroy(e,new Wc("bad response",ye.getSocketInfo(e))),-1;let n=r[xi][r[ui]];return n?(n.onResponseStarted(),0):-1}onHeaderField(e){let r=this.headers.length;return(r&1)===0?this.headers.push(e):this.headers[r-1]=Buffer.concat([this.headers[r-1],e]),this.trackHeader(e.length),0}onHeaderValue(e){let r=this.headers.length;(r&1)===1?(this.headers.push(e),r+=1):this.headers[r-1]=Buffer.concat([this.headers[r-1],e]);let n=this.headers[r-2];if(n.length===10){let i=ye.bufferToLowerCasedHeaderName(n);i==="keep-alive"?this.keepAlive+=e.toString():i==="connection"&&(this.connection+=e.toString())}else n.length===14&&ye.bufferToLowerCasedHeaderName(n)==="content-length"&&(this.contentLength+=e.toString());return this.trackHeader(e.length),0}trackHeader(e){this.headersSize+=e,this.headersSize>=this.headersMaxSize&&ye.destroy(this.socket,new Uve)}onUpgrade(e){let{upgrade:r,client:n,socket:i,headers:o,statusCode:s,statusText:a}=this;be(r),be(n[Jc]===i),be(!i.destroyed),be(!this.paused),be((o.length&1)===0);let c=n[xi][n[ui]];be(c),be(c.upgrade||c.method==="CONNECT"),this.statusCode=0,this.statusText="",this.shouldKeepAlive=!1,this.headers=[],this.headersSize=0,i.unshift(e),i[bt].destroy(),i[bt]=null,i[sE]=null,i[Pr]=null,Jve(i),n[Jc]=null,n[Xz]=null,n[xi][n[ui]++]=null,n.emit("disconnect",n[Kz],[n],new Fu("upgrade"));try{c.onUpgrade(s,o,i,a)}catch(l){ye.errorRequest(n,c,l),ye.destroy(i,l)}n[$s]()}onHeadersComplete(e,r,n){let{client:i,socket:o,headers:s,statusText:a}=this;if(o.destroyed)return-1;if(i[er]===0)return ye.destroy(o,new Wc("bad response",ye.getSocketInfo(o))),-1;let c=i[xi][i[ui]];if(!c)return-1;if(be(!this.upgrade),be(this.statusCode<200),e===100)return ye.destroy(o,new Wc("bad response",ye.getSocketInfo(o))),-1;if(r&&!c.upgrade)return ye.destroy(o,new Wc("bad upgrade",ye.getSocketInfo(o))),-1;if(be(this.timeoutType===zu),this.statusCode=e,this.shouldKeepAlive=n||c.method==="HEAD"&&!o[rn]&&this.connection.toLowerCase()==="keep-alive",this.statusCode>=200){let u=c.bodyTimeout!=null?c.bodyTimeout:i[Yve];this.setTimeout(u,oE)}else this.timeout&&this.timeout.refresh&&this.timeout.refresh();if(c.method==="CONNECT")return be(i[er]===1),this.upgrade=!0,2;if(r)return be(i[er]===1),this.upgrade=!0,2;if(be((this.headers.length&1)===0),this.headers=[],this.headersSize=0,this.shouldKeepAlive&&i[iE]){let u=this.keepAlive?ye.parseKeepAliveTimeout(this.keepAlive):null;if(u!=null){let d=Math.min(u-i[Hve],i[qve]);d<=0?o[rn]=!0:i[aE]=d}else i[aE]=i[$ve]}else o[rn]=!0;let l=c.onHeaders(e,s,this.resume,a)===!1;return c.aborted?-1:c.method==="HEAD"||e<200?1:(o[Op]&&(o[Op]=!1,i[$s]()),l?Tn.ERROR.PAUSED:0)}onBody(e){let{client:r,socket:n,statusCode:i,maxResponseSize:o}=this;if(n.destroyed)return-1;let s=r[xi][r[ui]];return be(s),be(this.timeoutType===oE),this.timeout&&this.timeout.refresh&&this.timeout.refresh(),be(i>=200),o>-1&&this.bytesRead+e.length>o?(ye.destroy(n,new Lve),-1):(this.bytesRead+=e.length,s.onData(e)===!1?Tn.ERROR.PAUSED:0)}onMessageComplete(){let{client:e,socket:r,statusCode:n,upgrade:i,headers:o,contentLength:s,bytesRead:a,shouldKeepAlive:c}=this;if(r.destroyed&&(!n||c))return-1;if(i)return 0;be(n>=100),be((this.headers.length&1)===0);let l=e[xi][e[ui]];if(be(l),this.statusCode=0,this.statusText="",this.bytesRead=0,this.contentLength="",this.keepAlive="",this.connection="",this.headers=[],this.headersSize=0,n<200)return 0;if(l.method!=="HEAD"&&s&&a!==parseInt(s,10))return ye.destroy(r,new zz),-1;if(l.onComplete(o),e[xi][e[ui]++]=null,r[xB]=e[OB]===0,r[xa])return be(e[er]===0),ye.destroy(r,new Fu("reset")),Tn.ERROR.PAUSED;if(c){if(r[rn]&&e[er]===0)return ye.destroy(r,new Fu("reset")),Tn.ERROR.PAUSED;e[iE]==null||e[iE]===1?setImmediate(e[$s]):e[$s]()}else return ye.destroy(r,new Fu("reset")),Tn.ERROR.PAUSED;return 0}};function Vz(t){let e=t.deref();if(!e)return;let{socket:r,timeoutType:n,client:i,paused:o}=e;n===zu?(!r[xa]||r.writableNeedDrain||i[er]>1)&&(be(!o,"cannot be paused while waiting for headers"),ye.destroy(r,new xve)):n===oE?o||ye.destroy(r,new Mve):n===RB&&(be(i[er]===0&&i[aE]),ye.destroy(r,new Fu("socket idle timeout")))}function Xve(t,e){if(t[Jc]=e,TB||(TB=Zve()),e.errored)throw e.errored;if(e.destroyed)throw new Wc("destroyed");return e[Rp]=!1,e[xa]=!1,e[rn]=!1,e[Op]=!1,e[Zc]=0,e[ju]=null,e[xB]=!1,e[bt]=new NB(t,e,TB),ye.addListener(e,"error",eQe),ye.addListener(e,"readable",tQe),ye.addListener(e,"end",rQe),ye.addListener(e,"close",nQe),e[kB]=!1,e.on("close",iQe),{version:"h1",defaultPipelining:1,write(r){return cQe(t,r)},resume(){sQe(t)},destroy(r,n){e[kB]?queueMicrotask(n):(e.on("close",n),e.destroy(r))},get destroyed(){return e.destroyed},busy(r){return!!(e[xa]||e[rn]||e[Op]||e[Zc]===1||r&&(t[er]>0&&!r.idempotent||t[er]>0&&(r.upgrade||r.method==="CONNECT")||t[er]>0&&ye.bodyLength(r.body)!==0&&(ye.isStream(r.body)||ye.isAsyncIterable(r.body)||ye.isFormDataLike(r.body))))}}}function eQe(t){be(t.code!=="ERR_TLS_CERT_ALTNAME_INVALID");let e=this[bt];if(t.code==="ECONNRESET"&&e.statusCode&&!e.shouldKeepAlive){let r=e.finish();r&&(this[Pr]=r,this[sE][Gz](r));return}this[Pr]=t,this[sE][Gz](t)}function tQe(){this[bt]?.readMore()}function rQe(){let t=this[bt];if(t.statusCode&&!t.shouldKeepAlive){let e=t.finish();e&&ye.destroy(this,e);return}ye.destroy(this,new Wc("other side closed",ye.getSocketInfo(this)))}function nQe(){let t=this[bt];eq(this),t&&(!this[Pr]&&t.statusCode&&!t.shouldKeepAlive&&(this[Pr]=t.finish()||this[Pr]),this[bt].destroy(),this[bt]=null);let e=this[Pr]||new Wc("closed",ye.getSocketInfo(this)),r=this[sE];if(r[Jc]=null,r[Xz]=null,r.destroyed){be(r[OB]===0);let n=r[xi].splice(r[ui]);for(let i=0;i<n.length;i++){let o=n[i];ye.errorRequest(r,o,e)}}else if(r[er]>0&&e.code!=="UND_ERR_INFO"){let n=r[xi][r[ui]];r[xi][r[ui]++]=null,ye.errorRequest(r,n,e)}r[jve]=r[ui],be(r[er]===0),r.emit("disconnect",r[Kz],[r],e),r[$s]()}function iQe(){this[kB]=!0}function eq(t){t[ju]&&(clearImmediate(t[ju]),t[ju]=null),t[Zc]=0}function oQe(t,e){e[Zc]=1,e[ju]=setImmediate(()=>{e[ju]=null,e[Zc]=2,t[Jc]===e&&!e.destroyed&&t[$s]()})}function sQe(t){let e=t[Jc];if(e&&!e.destroyed){if(t[qz]===0?!e[Rp]&&e.unref&&(e.unref(),e[Rp]=!0):e[Rp]&&e.ref&&(e.ref(),e[Rp]=!1),t[er]===0&&t[OB]>0&&e[xB]){if(e[Zc]===0)return oQe(t,e),e[bt].readMore(),e.destroyed,void 0;if(e[Zc]===1)return e[bt].readMore(),e.destroyed,void 0}if(t[er]===0&&(e[bt].readMore(),e.destroyed))return;if(t[qz]===0)e[bt].timeoutType!==RB&&e[bt].setTimeout(t[aE],RB);else if(t[er]>0&&e[bt].statusCode<200&&e[bt].timeoutType!==zu){let r=t[xi][t[ui]],n=r.headersTimeout!=null?r.headersTimeout:t[Gve];e[bt].setTimeout(n,zu)}}}function aQe(t){return t!=="GET"&&t!=="HEAD"&&t!=="OPTIONS"&&t!=="TRACE"&&t!=="CONNECT"}function cQe(t,e){let{method:r,path:n,host:i,upgrade:o,blocking:s,reset:a}=e,{body:c,headers:l,contentLength:u}=e,d=r==="PUT"||r==="POST"||r==="PATCH"||r==="QUERY"||r==="PROPFIND"||r==="PROPPATCH";if(ye.isFormDataLike(c)){QB||(QB=$u().extractBody);let[E,S]=QB(c);e.contentType==null&&l.push("content-type",S),c=E.stream,u=E.length}else if(ye.isBlobLike(c)&&e.contentType==null){let E=c.type;if(E){let S=`${E}`;if(!ye.isValidHeaderValue(S))return ye.errorRequest(t,e,new Ove("invalid content-type header")),!1;l.push("content-type",S)}}c&&typeof c.read=="function"&&c.read(0);let A=ye.bodyLength(c);if(u=A??u,u===null&&(u=e.contentLength),u===0&&!d&&(u=null),aQe(r)&&u>0&&e.contentLength!==null&&e.contentLength!==u){if(t[DB])return ye.errorRequest(t,e,new Vc),!1;process.emitWarning(new Vc)}let p=t[Jc];eq(p);let h=E=>{e.aborted||e.completed||(ye.errorRequest(t,e,E||new Zz),ye.destroy(c),ye.destroy(p,new Fu("aborted")))};try{e.onConnect(h)}catch(E){ye.errorRequest(t,e,E)}if(e.aborted)return!1;r==="HEAD"&&(p[rn]=!0),(o||r==="CONNECT")&&(p[rn]=!0),a!=null&&(p[rn]=a),t[Hz]&&p[Vve]++>=t[Hz]&&(p[rn]=!0),s&&(p[Op]=!0),p.setTypeOfService&&p.setTypeOfService(e.typeOfService);let f=`${r} ${n} HTTP/1.1\r
|
|
2104
2104
|
`;if(typeof i=="string"?f+=`host: ${i}\r
|
|
2105
2105
|
`:f+=t[Fve],o?f+=`connection: upgrade\r
|
|
2106
2106
|
upgrade: ${o}\r
|
|
@@ -2108,14 +2108,14 @@ upgrade: ${o}\r
|
|
|
2108
2108
|
`:f+=`connection: close\r
|
|
2109
2109
|
`,Array.isArray(l))for(let E=0;E<l.length;E+=2){let S=l[E+0],B=l[E+1];if(Array.isArray(B))for(let _=0;_<B.length;_++)f+=`${S}: ${B[_]}\r
|
|
2110
2110
|
`;else f+=`${S}: ${B}\r
|
|
2111
|
-
`}return jz.sendHeaders.hasSubscribers&&jz.sendHeaders.publish({request:e,headers:f,socket:p}),!c||A===0?Wz(h,null,t,e,p,u,f,d):ye.isBuffer(c)?Wz(h,c,t,e,p,u,f,d):ye.isBlobLike(c)?typeof c.stream=="function"?Jz(h,c.stream(),t,e,p,u,f,d):uQe(h,c,t,e,p,u,f,d):ye.isStream(c)?lQe(h,c,t,e,p,u,f,d):ye.isIterable(c)?Jz(h,c,t,e,p,u,f,d):be(!1),!0}function lQe(t,e,r,n,i,o,s,a){be(o!==0||r[
|
|
2111
|
+
`}return jz.sendHeaders.hasSubscribers&&jz.sendHeaders.publish({request:e,headers:f,socket:p}),!c||A===0?Wz(h,null,t,e,p,u,f,d):ye.isBuffer(c)?Wz(h,c,t,e,p,u,f,d):ye.isBlobLike(c)?typeof c.stream=="function"?Jz(h,c.stream(),t,e,p,u,f,d):uQe(h,c,t,e,p,u,f,d):ye.isStream(c)?lQe(h,c,t,e,p,u,f,d):ye.isIterable(c)?Jz(h,c,t,e,p,u,f,d):be(!1),!0}function lQe(t,e,r,n,i,o,s,a){be(o!==0||r[er]===0,"stream body cannot be pipelined");let c=!1,l=new cE({abort:t,socket:i,request:n,contentLength:o,client:r,expectsPayload:a,header:s}),u=function(h){if(!c)try{!l.write(h)&&this.pause&&this.pause()}catch(f){ye.destroy(this,f)}},d=function(){c||e.resume&&e.resume()},A=function(){if(queueMicrotask(()=>{e.removeListener("error",p)}),!c){let h=new Zz;queueMicrotask(()=>p(h))}},p=function(h){if(!c){if(c=!0,be(i.destroyed||i[xa]&&r[er]<=1),i.off("drain",d).off("error",p),e.removeListener("data",u).removeListener("end",p).removeListener("close",A),!h)try{l.end()}catch(f){h=f}l.destroy(h),h&&(h.code!=="UND_ERR_INFO"||h.message!=="reset")?ye.destroy(e,h):ye.destroy(e)}};e.on("data",u).on("end",p).on("error",p).on("close",A),e.resume&&e.resume(),i.on("drain",d).on("error",p),e.errorEmitted??e.errored?setImmediate(p,e.errored):(e.endEmitted??e.readableEnded)&&setImmediate(p,null),(e.closeEmitted??e.closed)&&setImmediate(A)}function Wz(t,e,r,n,i,o,s,a){try{e?ye.isBuffer(e)&&(be(o===e.byteLength,"buffer body must have content length"),i.cork(),i.write(`${s}content-length: ${o}\r
|
|
2112
2112
|
\r
|
|
2113
2113
|
`,"latin1"),i.write(e),i.uncork(),n.onBodySent(e),!a&&n.reset!==!1&&(i[rn]=!0)):o===0?i.write(`${s}content-length: 0\r
|
|
2114
2114
|
\r
|
|
2115
2115
|
`,"latin1"):(be(o===null,"no body must not have content length"),i.write(`${s}\r
|
|
2116
2116
|
`,"latin1")),n.onRequestSent(),r[$s]()}catch(c){t(c)}}async function uQe(t,e,r,n,i,o,s,a){be(o===e.size,"blob body must have content length");try{if(o!=null&&o!==e.size)throw new Vc;let c=Buffer.from(await e.arrayBuffer());i.cork(),i.write(`${s}content-length: ${o}\r
|
|
2117
2117
|
\r
|
|
2118
|
-
`,"latin1"),i.write(c),i.uncork(),n.onBodySent(c),n.onRequestSent(),!a&&n.reset!==!1&&(i[rn]=!0),r[$s]()}catch(c){t(c)}}async function Jz(t,e,r,n,i,o,s,a){be(o!==0||r[
|
|
2118
|
+
`,"latin1"),i.write(c),i.uncork(),n.onBodySent(c),n.onRequestSent(),!a&&n.reset!==!1&&(i[rn]=!0),r[$s]()}catch(c){t(c)}}async function Jz(t,e,r,n,i,o,s,a){be(o!==0||r[er]===0,"iterator body cannot be pipelined");let c=null;function l(){if(c){let A=c;c=null,A()}}let u=()=>new Promise((A,p)=>{be(c===null),i[Pr]?p(i[Pr]):c=A});i.on("close",l).on("drain",l);let d=new cE({abort:t,socket:i,request:n,contentLength:o,client:r,expectsPayload:a,header:s});try{for await(let A of e){if(i[Pr])throw i[Pr];d.write(A)||await u()}d.end()}catch(A){d.destroy(A)}finally{i.off("close",l).off("drain",l)}}var cE=class{constructor({abort:e,socket:r,request:n,contentLength:i,client:o,expectsPayload:s,header:a}){this.socket=r,this.request=n,this.contentLength=i,this.client=o,this.bytesWritten=0,this.expectsPayload=s,this.header=a,this.abort=e,r[xa]=!0}write(e){let{socket:r,request:n,contentLength:i,client:o,bytesWritten:s,expectsPayload:a,header:c}=this;if(r[Pr])throw r[Pr];if(r.destroyed)return!1;let l=Buffer.byteLength(e);if(!l)return!0;if(i!==null&&s+l>i){if(o[DB])throw new Vc;process.emitWarning(new Vc)}r.cork(),s===0&&(!a&&n.reset!==!1&&(r[rn]=!0),i===null?r.write(`${c}transfer-encoding: chunked\r
|
|
2119
2119
|
`,"latin1"):r.write(`${c}content-length: ${i}\r
|
|
2120
2120
|
\r
|
|
2121
2121
|
`,"latin1")),i===null&&r.write(`\r
|
|
@@ -2126,7 +2126,7 @@ ${l.toString(16)}\r
|
|
|
2126
2126
|
`,"latin1"):r===null&&e.write(`\r
|
|
2127
2127
|
0\r
|
|
2128
2128
|
\r
|
|
2129
|
-
`,"latin1"),r!==null&&i!==r){if(n[DB])throw new Vc;process.emitWarning(new Vc)}e[bt].timeout&&e[bt].timeoutType===zu&&e[bt].timeout.refresh&&e[bt].timeout.refresh(),n[$s]()}}destroy(e){let{socket:r,client:n,abort:i}=this;r[xa]=!1,e&&(be(n[
|
|
2129
|
+
`,"latin1"),r!==null&&i!==r){if(n[DB])throw new Vc;process.emitWarning(new Vc)}e[bt].timeout&&e[bt].timeoutType===zu&&e[bt].timeout.refresh&&e[bt].timeout.refresh(),n[$s]()}}destroy(e){let{socket:r,client:n,abort:i}=this;r[xa]=!1,e&&(be(n[er]<=1,"pipeline should only contain this request"),i(e))}};tq.exports=Xve});var dq=y((jze,uq)=>{"use strict";var Ai=require("assert"),{pipeline:dQe}=require("stream"),Ue=De(),{RequestContentLengthMismatchError:LB,RequestAbortedError:AQe,SocketError:$p,InformationalError:Ua,InvalidArgumentError:pQe,HeadersTimeoutError:hQe,BodyTimeoutError:fQe}=_e(),{kUrl:Lp,kReset:dE,kClient:Dn,kRunning:Fp,kPending:gQe,kQueue:Up,kPendingIdx:Kc,kRunningIdx:rs,kError:kn,kSocket:Rt,kStrictContentLength:mQe,kOnError:qu,kMaxConcurrentStreams:$B,kPingInterval:nq,kHTTP2Session:Fs,kHTTP2InitialWindowSize:yQe,kHTTP2ConnectionWindowSize:EQe,kResume:ns,kSize:IQe,kHTTPContext:jB,kClosed:FB,kBodyTimeout:CQe,kHeadersTimeout:bQe,kEnableConnectProtocol:Mp,kRemoteSettings:Pp,kHTTP2Stream:lE,kHTTP2SessionState:zB}=ut(),{channels:iq}=Ra(),di=Symbol("open streams"),oq,uE;try{uE=require("http2")}catch{uE={constants:{}}}var{constants:{HTTP2_HEADER_AUTHORITY:SQe,HTTP2_HEADER_METHOD:sq,HTTP2_HEADER_PATH:aq,HTTP2_HEADER_SCHEME:UB,HTTP2_HEADER_CONTENT_LENGTH:wQe,HTTP2_HEADER_EXPECT:_Qe,HTTP2_HEADER_STATUS:MB,HTTP2_HEADER_PROTOCOL:BQe,NGHTTP2_REFUSED_STREAM:vQe,NGHTTP2_CANCEL:QQe}}=uE;function PB(t){let e=[];for(let[r,n]of Object.entries(t))if(Array.isArray(n))for(let i of n)e.push(Buffer.from(r),Buffer.from(i));else e.push(Buffer.from(r),Buffer.from(n));return e}function TQe(t,e){t[Rt]=e;let r=t[yQe],n=t[EQe],i=uE.connect(t[Lp],{createConnection:()=>e,peerMaxConcurrentStreams:t[$B],settings:{enablePush:!1,...r!=null?{initialWindowSize:r}:null}});return t[Rt]=e,i[di]=0,i[Dn]=t,i[Rt]=e,i[zB]={ping:{interval:t[nq]===0?null:setInterval(NQe,t[nq],i).unref()}},i[Mp]=!1,i[Pp]=!1,n&&Ue.addListener(i,"connect",kQe.bind(i,n)),Ue.addListener(i,"error",OQe),Ue.addListener(i,"frameError",xQe),Ue.addListener(i,"end",UQe),Ue.addListener(i,"goaway",MQe),Ue.addListener(i,"close",PQe),Ue.addListener(i,"remoteSettings",RQe),i.unref(),t[Fs]=i,e[Fs]=i,Ue.addListener(e,"error",$Qe),Ue.addListener(e,"end",FQe),Ue.addListener(e,"close",LQe),e[FB]=!1,e.on("close",jQe),{version:"h2",defaultPipelining:1/0,write(o){return qQe(t,o)},resume(){DQe(t)},destroy(o,s){e[FB]?queueMicrotask(s):e.destroy(o).on("close",s)},get destroyed(){return e.destroyed},busy(o){if(o!=null)if(t[Fp]>0){if(o.idempotent===!1||(o.upgrade==="websocket"||o.method==="CONNECT")&&i[Pp]===!1||Ue.bodyLength(o.body)!==0&&(Ue.isStream(o.body)||Ue.isAsyncIterable(o.body)||Ue.isFormDataLike(o.body)))return!0}else return(o.upgrade==="websocket"||o.method==="CONNECT")&&i[Pp]===!1;return!1}}}function DQe(t){let e=t[Rt];e?.destroyed===!1&&(t[IQe]===0?(e.unref(),t[Fs].unref()):(e.ref(),t[Fs].ref()))}function kQe(t){try{typeof this.setLocalWindowSize=="function"&&this.setLocalWindowSize(t)}catch{}}function RQe(t){if(this[Dn][$B]=t.maxConcurrentStreams??this[Dn][$B],this[Pp]===!0&&this[Mp]===!0&&t.enableConnectProtocol===!1){let e=new Ua("HTTP/2: Server disabled extended CONNECT protocol against RFC-8441");this[Rt][kn]=e,this[Dn][qu](e);return}this[Mp]=t.enableConnectProtocol??this[Mp],this[Pp]=!0,this[Dn][ns]()}function NQe(t){let e=t[zB];if((t.closed||t.destroyed)&&e.ping.interval!=null){clearInterval(e.ping.interval),e.ping.interval=null;return}t.ping(r.bind(t));function r(n,i){let o=this[Dn],s=this[Dn];if(n!=null){let a=new Ua(`HTTP/2: "PING" errored - type ${n.message}`);s[kn]=a,o[qu](a)}else o.emit("ping",i)}}function OQe(t){Ai(t.code!=="ERR_TLS_CERT_ALTNAME_INVALID"),this[Rt][kn]=t,this[Dn][qu](t)}function xQe(t,e,r){if(r===0){let n=new Ua(`HTTP/2: "frameError" received - type ${t}, code ${e}`);this[Rt][kn]=n,this[Dn][qu](n)}}function UQe(){let t=new $p("other side closed",Ue.getSocketInfo(this[Rt]));this.destroy(t),Ue.destroy(this[Rt],t)}function xp(t,e,r=!1){let n=t[Up],i=t[rs];if(i<t[Kc]&&n[i]===e){n[i]=null,t[rs]=i+1;return}let o=n.indexOf(e,i);o===-1||o>=t[Kc]||(n.splice(o,1),t[Kc]--,r&&t[Kc]<t[rs]&&(t[Kc]=t[rs]))}function MQe(t){let e=this[kn]||new $p(`HTTP/2: "GOAWAY" frame received with code ${t}`,Ue.getSocketInfo(this[Rt])),r=this[Dn];if(r[Rt]=null,r[jB]=null,this.close(),this[Fs]=null,Ue.destroy(this[Rt],e),r[rs]<r[Up].length){let n=r[Up][r[rs]];r[Up][r[rs]++]=null,n!=null&&Ue.errorRequest(r,n,e),r[Kc]=r[rs]}Ai(r[Fp]===0),r.emit("disconnect",r[Lp],[r],e),r.emit("connectionError",r[Lp],[r],e),r[ns]()}function PQe(){let{[Dn]:t,[zB]:e}=this,{[Rt]:r}=t,n=this[Rt][kn]||this[kn]||new $p("closed",Ue.getSocketInfo(r));if(t[Rt]=null,t[jB]=null,e.ping.interval!=null&&(clearInterval(e.ping.interval),e.ping.interval=null),t.destroyed){Ai(t[gQe]===0);let i=t[Up].splice(t[rs]);for(let o=0;o<i.length;o++){let s=i[o];s!=null&&Ue.errorRequest(t,s,n)}}}function LQe(){let t=this[kn]||new $p("closed",Ue.getSocketInfo(this)),e=this[Fs][Dn];e[Rt]=null,e[jB]=null,this[Fs]!==null&&this[Fs].destroy(t),e[Kc]=e[rs],Ai(e[Fp]===0),e.emit("disconnect",e[Lp],[e],t),e[ns]()}function $Qe(t){Ai(t.code!=="ERR_TLS_CERT_ALTNAME_INVALID"),this[kn]=t,this[Dn][qu](t)}function FQe(){Ue.destroy(this,new $p("other side closed",Ue.getSocketInfo(this)))}function jQe(){this[FB]=!0}function zQe(t){return t!=="GET"&&t!=="HEAD"&&t!=="OPTIONS"&&t!=="TRACE"&&t!=="CONNECT"}function qQe(t,e){let r=e.headersTimeout??t[bQe],n=e.bodyTimeout??t[CQe],i=t[Fs],{method:o,path:s,host:a,upgrade:c,expectContinue:l,signal:u,protocol:d,headers:A}=e,{body:p}=e;if(c!=null&&c!=="websocket")return Ue.errorRequest(t,e,new pQe(`Custom upgrade "${c}" not supported over HTTP/2`)),!1;let h={};for(let P=0;P<A.length;P+=2){let U=A[P+0],K=A[P+1];if(U==="cookie"){h[U]!=null?h[U]=Array.isArray(h[U])?(h[U].push(K),h[U]):[h[U],K]:h[U]=K;continue}if(Array.isArray(K))for(let Ae=0;Ae<K.length;Ae++)h[U]?h[U]+=`, ${K[Ae]}`:h[U]=K[Ae];else h[U]?h[U]+=`, ${K}`:h[U]=K}let f=null,{hostname:E,port:S}=t[Lp];h[SQe]=a||`${E}${S?`:${S}`:""}`,h[sq]=o;let B=P=>{e.aborted||e.completed||(P=P||new AQe,Ue.errorRequest(t,e,P),f!=null&&(f.removeAllListeners("data"),f.close(),t[qu](P),xp(t,e),t[ns]()),Ue.destroy(p,P))};try{e.onConnect(B)}catch(P){Ue.errorRequest(t,e,P)}if(e.aborted)return!1;if(c||o==="CONNECT")return i.ref(),c==="websocket"?i[Mp]===!1?(Ue.errorRequest(t,e,new Ua("HTTP/2: Extended CONNECT protocol not supported by server")),i.unref(),!1):(h[sq]="CONNECT",h[BQe]="websocket",h[aq]=s,d==="ws:"||d==="wss:"?h[UB]=d==="ws:"?"http":"https":h[UB]=d==="http:"?"http":"https",f=i.request(h,{endStream:!1,signal:u}),f[lE]=!0,++i[di],f.once("response",(P,U)=>{let{[MB]:K,...Ae}=P;try{e.onUpgrade(K,PB(Ae),f)}catch(Re){B(Re);return}xp(t,e)}),f.on("error",()=>{(f.rstCode===vQe||f.rstCode===QQe)&&B(new Ua(`HTTP/2: "stream error" received - code ${f.rstCode}`))}),f.once("close",()=>{i[di]-=1,i[di]===0&&i.unref()}),f.setTimeout(r),!0):(f=i.request(h,{endStream:!1,signal:u}),f[lE]=!0,++i[di],f.on("response",P=>{let{[MB]:U,...K}=P;try{e.onUpgrade(U,PB(K),f)}catch(Ae){B(Ae);return}xp(t,e)}),f.on("error",B),f.once("close",()=>{i[di]-=1,i[di]===0&&i.unref()}),f.setTimeout(r),!0);h[aq]=s,h[UB]=d==="http:"?"http":"https";let _=o==="PUT"||o==="POST"||o==="PATCH";p&&typeof p.read=="function"&&p.read(0);let v=Ue.bodyLength(p);if(Ue.isFormDataLike(p)){oq??=$u().extractBody;let[P,U]=oq(p);h["content-type"]=U,p=P.stream,v=P.length}if(v==null&&(v=e.contentLength),_||(v=null),zQe(o)&&v>0&&e.contentLength!=null&&e.contentLength!==v){if(t[mQe])return Ue.errorRequest(t,e,new LB),!1;process.emitWarning(new LB)}if(v!=null&&(Ai(p||v===0,"no body must not have content length"),h[wQe]=`${v}`),i.ref(),iq.sendHeaders.hasSubscribers){let P="";for(let U in h)P+=`${U}: ${h[U]}\r
|
|
2130
2130
|
`;iq.sendHeaders.publish({request:e,headers:P,socket:i[Rt]})}let T=o==="GET"||o==="HEAD"||p===null;l?(h[_Qe]="100-continue",f=i.request(h,{endStream:T,signal:u}),f[lE]=!0,f.once("continue",k)):(f=i.request(h,{endStream:T,signal:u}),f[lE]=!0,k()),++i[di],f.setTimeout(r);let L=!1;return f.once("response",P=>{let{[MB]:U,...K}=P;if(e.onResponseStarted(),L=!0,f.setTimeout(n),e.aborted){f.removeAllListeners("data");return}e.onHeaders(Number(U),PB(K),f.resume.bind(f),"")===!1&&f.pause(),f.on("data",Ae=>{e.aborted||e.completed||e.onData(Ae)===!1&&f.pause()})}),f.once("end",()=>{f.removeAllListeners("data"),L?(!e.aborted&&!e.completed&&e.onComplete({}),xp(t,e),t[ns]()):(B(new Ua("HTTP/2: stream half-closed (remote)")),xp(t,e,!0),t[ns]())}),f.once("close",()=>{f.removeAllListeners("data"),i[di]-=1,i[di]===0&&i.unref(),!e.aborted&&!e.completed&&B(new Ua("HTTP/2: stream closed before the response was complete"))}),f.once("error",function(P){f.removeAllListeners("data"),B(P)}),f.once("frameError",(P,U)=>{f.removeAllListeners("data"),B(new Ua(`HTTP/2: "frameError" received - type ${P}, code ${U}`))}),f.on("aborted",()=>{f.removeAllListeners("data")}),f.on("timeout",()=>{let P=L?new fQe(`HTTP/2: "body timeout after ${n}"`):new hQe(`HTTP/2: "headers timeout after ${r}"`);f.removeAllListeners("data"),i[di]-=1,i[di]===0&&i.unref(),B(P)}),f.once("trailers",P=>{e.aborted||e.completed||(f.removeAllListeners("data"),e.onComplete(P))}),!0;function k(){!p||v===0?cq(B,f,null,t,e,t[Rt],v,_):Ue.isBuffer(p)?cq(B,f,p,t,e,t[Rt],v,_):Ue.isBlobLike(p)?typeof p.stream=="function"?lq(B,f,p.stream(),t,e,t[Rt],v,_):GQe(B,f,p,t,e,t[Rt],v,_):Ue.isStream(p)?HQe(B,t[Rt],_,f,p,t,e,v):Ue.isIterable(p)?lq(B,f,p,t,e,t[Rt],v,_):Ai(!1)}}function cq(t,e,r,n,i,o,s,a){try{r!=null&&Ue.isBuffer(r)&&(Ai(s===r.byteLength,"buffer body must have content length"),e.cork(),e.write(r),e.uncork(),e.end(),i.onBodySent(r)),a||(o[dE]=!0),i.onRequestSent(),n[ns]()}catch(c){t(c)}}function HQe(t,e,r,n,i,o,s,a){Ai(a!==0||o[Fp]===0,"stream body cannot be pipelined");let c=dQe(i,n,u=>{u?(Ue.destroy(c,u),t(u)):(Ue.removeAllListeners(c),s.onRequestSent(),r||(e[dE]=!0),o[ns]())});Ue.addListener(c,"data",l);function l(u){s.onBodySent(u)}}async function GQe(t,e,r,n,i,o,s,a){Ai(s===r.size,"blob body must have content length");try{if(s!=null&&s!==r.size)throw new LB;let c=Buffer.from(await r.arrayBuffer());e.cork(),e.write(c),e.uncork(),e.end(),i.onBodySent(c),i.onRequestSent(),a||(o[dE]=!0),n[ns]()}catch(c){t(c)}}async function lq(t,e,r,n,i,o,s,a){Ai(s!==0||n[Fp]===0,"iterator body cannot be pipelined");let c=null;function l(){if(c){let d=c;c=null,d()}}let u=()=>new Promise((d,A)=>{Ai(c===null),o[kn]?A(o[kn]):c=d});e.on("close",l).on("drain",l);try{for await(let d of r){if(o[kn])throw o[kn];let A=e.write(d);i.onBodySent(d),A||await u()}e.end(),i.onRequestSent(),a||(o[dE]=!0),n[ns]()}catch(d){t(d)}finally{e.off("close",l).off("drain",l)}}uq.exports=TQe});var $a=y((zze,Eq)=>{"use strict";var js=require("assert"),fq=require("net"),jp=require("http"),Xc=De(),{ClientStats:YQe}=U_(),{channels:Hu}=Ra(),VQe=T2(),WQe=zc(),{InvalidArgumentError:St,InformationalError:JQe,ClientDestroyedError:ZQe}=_e(),KQe=qc(),{kUrl:is,kServerName:La,kClient:XQe,kBusy:HB,kConnect:eTe,kResuming:el,kRunning:Gp,kPending:Yp,kSize:zp,kQueue:Ui,kConnected:tTe,kConnecting:Gu,kNeedDrain:Pa,kKeepAliveDefaultTimeout:Aq,kHostHeader:rTe,kPendingIdx:Mi,kRunningIdx:qs,kError:nTe,kPipelining:AE,kKeepAliveTimeoutValue:iTe,kMaxHeadersSize:oTe,kKeepAliveMaxTimeout:sTe,kKeepAliveTimeoutThreshold:aTe,kHeadersTimeout:cTe,kBodyTimeout:lTe,kStrictContentLength:uTe,kConnector:qp,kMaxRequests:GB,kCounter:dTe,kClose:ATe,kDestroy:pTe,kDispatch:hTe,kLocalAddress:Hp,kMaxResponseSize:fTe,kOnError:gTe,kHTTPContext:Vt,kMaxConcurrentStreams:mTe,kHTTP2InitialWindowSize:yTe,kHTTP2ConnectionWindowSize:ETe,kResume:zs,kPingInterval:ITe}=ut(),CTe=rq(),bTe=dq(),Ma=Symbol("kClosedResolve"),STe=jp&&jp.maxHeaderSize&&Number.isInteger(jp.maxHeaderSize)&&jp.maxHeaderSize>0?()=>jp.maxHeaderSize:()=>{throw new St("http module not available or http.maxHeaderSize invalid")},pq=()=>{};function gq(t){return t[AE]??t[Vt]?.defaultPipelining??1}var YB=class extends WQe{constructor(e,{maxHeaderSize:r,headersTimeout:n,socketTimeout:i,requestTimeout:o,connectTimeout:s,bodyTimeout:a,idleTimeout:c,keepAlive:l,keepAliveTimeout:u,maxKeepAliveTimeout:d,keepAliveMaxTimeout:A,keepAliveTimeoutThreshold:p,socketPath:h,pipelining:f,tls:E,strictContentLength:S,maxCachedSessions:B,connect:_,maxRequestsPerClient:v,localAddress:T,maxResponseSize:L,autoSelectFamily:k,autoSelectFamilyAttemptTimeout:P,maxConcurrentStreams:U,allowH2:K,useH2c:Ae,initialWindowSize:Re,connectionWindowSize:Ge,pingInterval:tt,webSocket:Ht}={}){if(l!==void 0)throw new St("unsupported keepAlive, use pipelining=0 instead");if(i!==void 0)throw new St("unsupported socketTimeout, use headersTimeout & bodyTimeout instead");if(o!==void 0)throw new St("unsupported requestTimeout, use headersTimeout & bodyTimeout instead");if(c!==void 0)throw new St("unsupported idleTimeout, use keepAliveTimeout instead");if(d!==void 0)throw new St("unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead");if(r!=null){if(!Number.isInteger(r)||r<1)throw new St("invalid maxHeaderSize")}else r=STe();if(h!=null&&typeof h!="string")throw new St("invalid socketPath");if(s!=null&&(!Number.isFinite(s)||s<0))throw new St("invalid connectTimeout");if(u!=null&&(!Number.isFinite(u)||u<=0))throw new St("invalid keepAliveTimeout");if(A!=null&&(!Number.isFinite(A)||A<=0))throw new St("invalid keepAliveMaxTimeout");if(p!=null&&!Number.isFinite(p))throw new St("invalid keepAliveTimeoutThreshold");if(n!=null&&(!Number.isInteger(n)||n<0))throw new St("headersTimeout must be a positive integer or zero");if(a!=null&&(!Number.isInteger(a)||a<0))throw new St("bodyTimeout must be a positive integer or zero");if(_!=null&&typeof _!="function"&&typeof _!="object")throw new St("connect must be a function or an object");if(v!=null&&(!Number.isInteger(v)||v<0))throw new St("maxRequestsPerClient must be a positive number");if(T!=null&&(typeof T!="string"||fq.isIP(T)===0))throw new St("localAddress must be valid string IP address");if(L!=null&&(!Number.isInteger(L)||L<-1))throw new St("maxResponseSize must be a positive number");if(P!=null&&(!Number.isInteger(P)||P<-1))throw new St("autoSelectFamilyAttemptTimeout must be a positive number");if(K!=null&&typeof K!="boolean")throw new St("allowH2 must be a valid boolean value");if(U!=null&&(typeof U!="number"||U<1))throw new St("maxConcurrentStreams must be a positive integer, greater than 0");if(Ae!=null&&typeof Ae!="boolean")throw new St("useH2c must be a valid boolean value");if(Re!=null&&(!Number.isInteger(Re)||Re<1))throw new St("initialWindowSize must be a positive integer, greater than 0");if(Ge!=null&&(!Number.isInteger(Ge)||Ge<1))throw new St("connectionWindowSize must be a positive integer, greater than 0");if(tt!=null&&(typeof tt!="number"||!Number.isInteger(tt)||tt<0))throw new St("pingInterval must be a positive integer, greater or equal to 0");if(super({webSocket:Ht}),typeof _!="function")_=KQe({...E,maxCachedSessions:B,allowH2:K,useH2c:Ae,socketPath:h,timeout:s,...typeof k=="boolean"?{autoSelectFamily:k,autoSelectFamilyAttemptTimeout:P}:void 0,..._});else{let Nt=_;_=(kr,qr)=>Nt({...kr,...h!=null?{socketPath:h}:null,...K!=null?{allowH2:K}:null},qr)}this[is]=Xc.parseOrigin(e),this[qp]=_,this[AE]=f??1,this[oTe]=r,this[Aq]=u??4e3,this[sTe]=A??6e5,this[aTe]=p??2e3,this[iTe]=this[Aq],this[La]=null,this[Hp]=T??null,this[el]=0,this[Pa]=0,this[rTe]=`host: ${this[is].hostname}${this[is].port?`:${this[is].port}`:""}\r
|
|
2131
2131
|
`,this[lTe]=a??3e5,this[cTe]=n??3e5,this[uTe]=S??!0,this[GB]=v,this[Ma]=null,this[fTe]=L>-1?L:-1,this[Vt]=null,this[mTe]=U??100,this[yTe]=Re??262144,this[ETe]=Ge??524288,this[ITe]=tt??6e4,this[Ui]=[],this[qs]=0,this[Mi]=0,this[zs]=Nt=>VB(this,Nt),this[gTe]=Nt=>mq(this,Nt)}get pipelining(){return this[AE]}set pipelining(e){this[AE]=e,this[zs](!0)}get stats(){return new YQe(this)}get[Yp](){return this[Ui].length-this[Mi]}get[Gp](){return this[Mi]-this[qs]}get[zp](){return this[Ui].length-this[qs]}get[tTe](){return!!this[Vt]&&!this[Gu]&&!this[Vt].destroyed}get[HB](){return!!(this[Vt]?.busy(null)||this[zp]>=(gq(this)||1)||this[Yp]>0)}[eTe](e){yq(this),this.once("connect",e)}[hTe](e,r){let n=new VQe(this[is].origin,e,r);return this[Ui].push(n),this[el]||(Xc.bodyLength(n.body)==null&&Xc.isIterable(n.body)?(this[el]=1,queueMicrotask(()=>VB(this))):this[zs](!0)),this[el]&&this[Pa]!==2&&this[HB]&&(this[Pa]=2),this[Pa]<2}[ATe](){return new Promise(e=>{this[zp]?this[Ma]=e:e(null)})}[pTe](e){return new Promise(r=>{let n=this[Ui].splice(this[Mi]);for(let o=0;o<n.length;o++){let s=n[o];s!=null&&Xc.errorRequest(this,s,e)}let i=()=>{this[Ma]&&(this[Ma](),this[Ma]=null),r(null)};this[Vt]?(this[Vt].destroy(e,i),this[Vt]=null):queueMicrotask(i),this[zs]()})}};function mq(t,e){if(t[Gp]===0&&e.code!=="UND_ERR_INFO"&&e.code!=="UND_ERR_SOCKET"){js(t[Mi]===t[qs]);let r=t[Ui].splice(t[qs]);for(let n=0;n<r.length;n++){let i=r[n];i!=null&&Xc.errorRequest(t,i,e)}js(t[zp]===0)}}function yq(t){js(!t[Gu]),js(!t[Vt]);let{host:e,hostname:r,protocol:n,port:i}=t[is];if(r[0]==="["){let o=r.indexOf("]");js(o!==-1);let s=r.substring(1,o);js(fq.isIPv6(s)),r=s}t[Gu]=!0,Hu.beforeConnect.hasSubscribers&&Hu.beforeConnect.publish({connectParams:{host:e,hostname:r,protocol:n,port:i,version:t[Vt]?.version,servername:t[La],localAddress:t[Hp]},connector:t[qp]});try{t[qp]({host:e,hostname:r,protocol:n,port:i,servername:t[La],localAddress:t[Hp]},(o,s)=>{if(o){qB(t,o,{host:e,hostname:r,protocol:n,port:i}),t[zs]();return}if(t.destroyed){Xc.destroy(s.on("error",pq),new ZQe),t[zs]();return}js(s);try{t[Vt]=s.alpnProtocol==="h2"?bTe(t,s):CTe(t,s)}catch(a){s.destroy().on("error",pq),qB(t,a,{host:e,hostname:r,protocol:n,port:i}),t[zs]();return}t[Gu]=!1,s[dTe]=0,s[GB]=t[GB],s[XQe]=t,s[nTe]=null,Hu.connected.hasSubscribers&&Hu.connected.publish({connectParams:{host:e,hostname:r,protocol:n,port:i,version:t[Vt]?.version,servername:t[La],localAddress:t[Hp]},connector:t[qp],socket:s}),t.emit("connect",t[is],[t]),t[zs]()})}catch(o){qB(t,o,{host:e,hostname:r,protocol:n,port:i}),t[zs]()}}function qB(t,e,{host:r,hostname:n,protocol:i,port:o}){if(!t.destroyed){if(t[Gu]=!1,Hu.connectError.hasSubscribers&&Hu.connectError.publish({connectParams:{host:r,hostname:n,protocol:i,port:o,version:t[Vt]?.version,servername:t[La],localAddress:t[Hp]},connector:t[qp],error:e}),e.code==="ERR_TLS_CERT_ALTNAME_INVALID")for(js(t[Gp]===0);t[Yp]>0&&t[Ui][t[Mi]].servername===t[La];){let s=t[Ui][t[Mi]++];Xc.errorRequest(t,s,e)}else mq(t,e);t.emit("connectionError",t[is],[t],e)}}function hq(t){t[Pa]=0,t.emit("drain",t[is],[t])}function VB(t,e){t[el]!==2&&(t[el]=2,wTe(t,e),t[el]=0,t[qs]>256&&(t[Ui].splice(0,t[qs]),t[Mi]-=t[qs],t[qs]=0))}function wTe(t,e){for(;;){if(t.destroyed){js(t[Yp]===0);return}if(t[Ma]&&!t[zp]){t[Ma](),t[Ma]=null;return}if(t[Vt]&&t[Vt].resume(),t[HB])t[Pa]=2;else if(t[Pa]===2){e?(t[Pa]=1,queueMicrotask(()=>hq(t))):hq(t);continue}if(t[Yp]===0||t[Gp]>=(gq(t)||1))return;let r=t[Ui][t[Mi]];if(r===null)return;if(t[is].protocol==="https:"&&t[La]!==r.servername){if(t[Gp]>0)return;t[La]=r.servername,t[Vt]?.destroy(new JQe("servername changed"),()=>{t[Vt]=null,VB(t)})}if(t[Gu])return;if(!t[Vt]){yq(t);return}if(t[Vt].destroyed||t[Vt].busy(r))return;!r.aborted&&t[Vt].write(r)?t[Mi]++:t[Ui].splice(t[Mi],1)}}Eq.exports=YB});var WB=y((Hze,Iq)=>{"use strict";var pE=class{bottom=0;top=0;list=new Array(2048).fill(void 0);next=null;isEmpty(){return this.top===this.bottom}isFull(){return(this.top+1&2047)===this.bottom}push(e){this.list[this.top]=e,this.top=this.top+1&2047}shift(){let e=this.list[this.bottom];return e===void 0?null:(this.list[this.bottom]=void 0,this.bottom=this.bottom+1&2047,e)}};Iq.exports=class{constructor(){this.head=this.tail=new pE}isEmpty(){return this.head.isEmpty()}push(e){this.head.isFull()&&(this.head=this.head.next=new pE),this.head.push(e)}shift(){let e=this.tail,r=e.shift();return e.isEmpty()&&e.next!==null&&(this.tail=e.next,e.next=null),r}}});var hE=y((Gze,Tq)=>{"use strict";var{PoolStats:_Te}=U_(),BTe=zc(),vTe=WB(),{kConnected:JB,kSize:Cq,kRunning:bq,kPending:Sq,kQueued:Vp,kBusy:QTe,kFree:TTe,kUrl:DTe,kClose:kTe,kDestroy:RTe,kDispatch:NTe}=ut(),yr=Symbol("clients"),Lr=Symbol("needDrain"),Wp=Symbol("queue"),ZB=Symbol("closed resolve"),KB=Symbol("onDrain"),wq=Symbol("onConnect"),_q=Symbol("onDisconnect"),Bq=Symbol("onConnectionError"),XB=Symbol("get dispatcher"),vq=Symbol("add client"),Qq=Symbol("remove client"),ev=class extends BTe{[Wp]=new vTe;[Vp]=0;[yr]=[];[Lr]=!1;[KB](e,r,n){let i=this[Wp],o=!1;for(;!o;){let s=i.shift();if(!s)break;this[Vp]--,o=!e.dispatch(s.opts,s.handler)}if(e[Lr]=o,!o&&this[Lr]&&(this[Lr]=!1,this.emit("drain",r,[this,...n])),this[ZB]&&i.isEmpty()){let s=[];for(let a=0;a<this[yr].length;a++){let c=this[yr][a];c.destroyed||s.push(c.close())}return Promise.all(s).then(this[ZB])}}[wq]=(e,r)=>{this.emit("connect",e,[this,...r])};[_q]=(e,r,n)=>{this.emit("disconnect",e,[this,...r],n)};[Bq]=(e,r,n)=>{this.emit("connectionError",e,[this,...r],n)};get[QTe](){return this[Lr]}get[JB](){let e=0;for(let{[JB]:r}of this[yr])e+=r;return e}get[TTe](){let e=0;for(let{[JB]:r,[Lr]:n}of this[yr])e+=r&&!n;return e}get[Sq](){let e=this[Vp];for(let{[Sq]:r}of this[yr])e+=r;return e}get[bq](){let e=0;for(let{[bq]:r}of this[yr])e+=r;return e}get[Cq](){let e=this[Vp];for(let{[Cq]:r}of this[yr])e+=r;return e}get stats(){return new _Te(this)}[kTe](){if(this[Wp].isEmpty()){let e=[];for(let r=0;r<this[yr].length;r++){let n=this[yr][r];n.destroyed||e.push(n.close())}return Promise.all(e)}else return new Promise(e=>{this[ZB]=e})}[RTe](e){for(;;){let n=this[Wp].shift();if(!n)break;n.handler.onError(e)}let r=new Array(this[yr].length);for(let n=0;n<this[yr].length;n++)r[n]=this[yr][n].destroy(e);return Promise.all(r)}[NTe](e,r){let n=this[XB]();return n?n.dispatch(e,r)||(n[Lr]=!0,this[Lr]=!this[XB]()):(this[Lr]=!0,this[Wp].push({opts:e,handler:r}),this[Vp]++),!this[Lr]}[vq](e){return e.on("drain",this[KB].bind(this,e)).on("connect",this[wq]).on("disconnect",this[_q]).on("connectionError",this[Bq]),this[yr].push(e),this[Lr]&&queueMicrotask(()=>{this[Lr]&&this[KB](e,e[DTe],[e,this])}),this}[Qq](e){e.close(()=>{let r=this[yr].indexOf(e);r!==-1&&this[yr].splice(r,1)}),this[Lr]=this[yr].some(r=>!r[Lr]&&r.closed!==!0&&r.destroyed!==!0)}};Tq.exports={PoolBase:ev,kClients:yr,kNeedDrain:Lr,kAddClient:vq,kRemoveClient:Qq,kGetDispatcher:XB}});var tl=y((Yze,Nq)=>{"use strict";var{PoolBase:OTe,kClients:fE,kNeedDrain:xTe,kAddClient:UTe,kGetDispatcher:MTe,kRemoveClient:PTe}=hE(),LTe=$a(),{InvalidArgumentError:tv}=_e(),Dq=De(),{kUrl:kq}=ut(),$Te=qc(),gE=Symbol("options"),rv=Symbol("connections"),Rq=Symbol("factory");function FTe(t,e){return new LTe(t,e)}var nv=class extends OTe{constructor(e,{connections:r,factory:n=FTe,connect:i,connectTimeout:o,tls:s,maxCachedSessions:a,socketPath:c,autoSelectFamily:l,autoSelectFamilyAttemptTimeout:u,allowH2:d,clientTtl:A,...p}={}){if(r!=null&&(!Number.isFinite(r)||r<0))throw new tv("invalid connections");if(typeof n!="function")throw new tv("factory must be a function.");if(i!=null&&typeof i!="function"&&typeof i!="object")throw new tv("connect must be a function or an object");typeof i!="function"&&(i=$Te({...s,maxCachedSessions:a,allowH2:d,socketPath:c,timeout:o,...typeof l=="boolean"?{autoSelectFamily:l,autoSelectFamilyAttemptTimeout:u}:void 0,...i})),super(p),this[rv]=r||null,this[kq]=Dq.parseOrigin(e),this[gE]={...Dq.deepClone(p),connect:i,allowH2:d,clientTtl:A,socketPath:c},this[gE].interceptors=p.interceptors?{...p.interceptors}:void 0,this[Rq]=n,this.on("connect",(h,f)=>{if(A!=null&&A>0)for(let E of f)Object.assign(E,{ttl:Date.now()})}),this.on("connectionError",(h,f,E)=>{for(let S of f){let B=this[fE].indexOf(S);B!==-1&&this[fE].splice(B,1)}})}[MTe](){let e=this[gE].clientTtl;for(let r of this[fE])if(e!=null&&e>0&&r.ttl&&Date.now()-r.ttl>e)this[PTe](r);else if(!r[xTe])return r;if(!this[rv]||this[fE].length<this[rv]){let r=this[Rq](this[kq],this[gE]);return this[UTe](r),r}}};Nq.exports=nv});var Mq=y((Vze,Uq)=>{"use strict";var{BalancedPoolMissingUpstreamError:jTe,InvalidArgumentError:zTe}=_e(),{PoolBase:qTe,kClients:br,kNeedDrain:Jp,kAddClient:HTe,kRemoveClient:GTe,kGetDispatcher:YTe}=hE(),VTe=tl(),{kUrl:mE}=ut(),yE=De(),Oq=Symbol("factory"),Zp=Symbol("options"),xq=Symbol("kGreatestCommonDivisor"),rl=Symbol("kCurrentWeight"),nl=Symbol("kIndex"),pi=Symbol("kWeight"),EE=Symbol("kMaxWeightPerServer"),IE=Symbol("kErrorPenalty");function WTe(t,e){if(t===0)return e;for(;e!==0;){let r=e;e=t%e,t=r}return t}function JTe(t,e){return new VTe(t,e)}var iv=class extends qTe{constructor(e=[],{factory:r=JTe,connect:n,tls:i,...o}={}){if(typeof r!="function")throw new zTe("factory must be a function.");super(o),n&&typeof n!="function"&&(n={...n}),i&&typeof i!="function"&&(i={...i}),this[Zp]={...yE.deepClone(o),connect:n,tls:i},this[Zp].interceptors=o.interceptors?{...o.interceptors}:void 0,this[nl]=-1,this[rl]=0,this[EE]=this[Zp].maxWeightPerServer||100,this[IE]=this[Zp].errorPenalty||15,Array.isArray(e)||(e=[e]),this[Oq]=r;for(let s of e)this.addUpstream(s);this._updateBalancedPoolStats()}addUpstream(e){let r=yE.parseOrigin(e).origin;if(this[br].find(i=>i[mE].origin===r&&i.closed!==!0&&i.destroyed!==!0))return this;let n=this[Oq](r,this[Zp]);this[HTe](n),n.on("connect",()=>{n[pi]=Math.min(this[EE],n[pi]+this[IE])}),n.on("connectionError",()=>{n[pi]=Math.max(1,n[pi]-this[IE]),this._updateBalancedPoolStats()}),n.on("disconnect",(...i)=>{let o=i[2];o&&o.code==="UND_ERR_SOCKET"&&(n[pi]=Math.max(1,n[pi]-this[IE]),this._updateBalancedPoolStats())});for(let i of this[br])i[pi]=this[EE];return this._updateBalancedPoolStats(),this}_updateBalancedPoolStats(){let e=0;for(let r=0;r<this[br].length;r++)e=WTe(this[br][r][pi],e);this[xq]=e}removeUpstream(e){let r=yE.parseOrigin(e).origin,n=this[br].find(i=>i[mE].origin===r&&i.closed!==!0&&i.destroyed!==!0);return n&&this[GTe](n),this}getUpstream(e){let r=yE.parseOrigin(e).origin;return this[br].find(n=>n[mE].origin===r&&n.closed!==!0&&n.destroyed!==!0)}get upstreams(){return this[br].filter(e=>e.closed!==!0&&e.destroyed!==!0).map(e=>e[mE].origin)}[YTe](){if(this[br].length===0)throw new jTe;if(!this[br].find(o=>!o[Jp]&&o.closed!==!0&&o.destroyed!==!0)||this[br].map(o=>o[Jp]).reduce((o,s)=>o&&s,!0))return;let n=0,i=this[br].findIndex(o=>!o[Jp]);for(;n++<this[br].length;){this[nl]=(this[nl]+1)%this[br].length;let o=this[br][this[nl]];if(o[pi]>this[br][i][pi]&&!o[Jp]&&(i=this[nl]),this[nl]===0&&(this[rl]=this[rl]-this[xq],this[rl]<=0&&(this[rl]=this[EE])),o[pi]>=this[rl]&&!o[Jp])return o}return this[rl]=this[br][i][pi],this[nl]=i,this[br][i]}};Uq.exports=iv});var Fq=y((Wze,$q)=>{"use strict";var{PoolBase:ZTe,kClients:CE,kNeedDrain:KTe,kAddClient:Pq,kGetDispatcher:XTe,kRemoveClient:eDe}=hE(),tDe=$a(),{InvalidArgumentError:ov}=_e(),Lq=De(),{kUrl:sv}=ut(),rDe=qc(),Kp=Symbol("options"),av=Symbol("connections"),cv=Symbol("factory"),bE=Symbol("index");function nDe(t,e){return new tDe(t,e)}var lv=class extends ZTe{constructor(e,{connections:r,factory:n=nDe,connect:i,connectTimeout:o,tls:s,maxCachedSessions:a,socketPath:c,autoSelectFamily:l,autoSelectFamilyAttemptTimeout:u,allowH2:d,clientTtl:A,...p}={}){if(r!=null&&(!Number.isFinite(r)||r<0))throw new ov("invalid connections");if(typeof n!="function")throw new ov("factory must be a function.");if(i!=null&&typeof i!="function"&&typeof i!="object")throw new ov("connect must be a function or an object");typeof i!="function"&&(i=rDe({...s,maxCachedSessions:a,allowH2:d,socketPath:c,timeout:o,...typeof l=="boolean"?{autoSelectFamily:l,autoSelectFamilyAttemptTimeout:u}:void 0,...i})),super(),this[av]=r||null,this[sv]=Lq.parseOrigin(e),this[Kp]={...Lq.deepClone(p),connect:i,allowH2:d,clientTtl:A,socketPath:c},this[Kp].interceptors=p.interceptors?{...p.interceptors}:void 0,this[cv]=n,this[bE]=-1,this.on("connect",(h,f)=>{if(A!=null&&A>0)for(let E of f)Object.assign(E,{ttl:Date.now()})}),this.on("connectionError",(h,f,E)=>{for(let S of f){let B=this[CE].indexOf(S);B!==-1&&this[CE].splice(B,1)}})}[XTe](){let e=this[Kp].clientTtl,r=this[CE].length;if(r===0){let i=this[cv](this[sv],this[Kp]);return this[Pq](i),i}let n=0;for(;n<r;){this[bE]=(this[bE]+1)%r;let i=this[CE][this[bE]];if(e!=null&&e>0&&i.ttl&&Date.now()-i.ttl>e){this[eDe](i),n++;continue}if(!i[KTe])return i;n++}if(!this[av]||r<this[av]){let i=this[cv](this[sv],this[Kp]);return this[Pq](i),i}}};$q.exports=lv});var il=y((Jze,Vq)=>{"use strict";var{InvalidArgumentError:SE,MaxOriginsReachedError:iDe}=_e(),{kClients:hi,kRunning:jq,kClose:oDe,kDestroy:sDe,kDispatch:aDe,kUrl:cDe}=ut(),lDe=zc(),uDe=tl(),dDe=$a(),ADe=De(),zq=Symbol("onConnect"),qq=Symbol("onDisconnect"),Hq=Symbol("onConnectionError"),Gq=Symbol("onDrain"),Yq=Symbol("factory"),uv=Symbol("options"),Xp=Symbol("origins");function pDe(t,e){return e&&e.connections===1?new dDe(t,e):new uDe(t,e)}var dv=class extends lDe{constructor({factory:e=pDe,maxOrigins:r=1/0,connect:n,...i}={}){if(typeof e!="function")throw new SE("factory must be a function.");if(n!=null&&typeof n!="function"&&typeof n!="object")throw new SE("connect must be a function or an object");if(typeof r!="number"||Number.isNaN(r)||r<=0)throw new SE("maxOrigins must be a number greater than 0");super(i),n&&typeof n!="function"&&(n={...n}),this[uv]={...ADe.deepClone(i),maxOrigins:r,connect:n},this[Yq]=e,this[hi]=new Map,this[Xp]=new Set,this[Gq]=(o,s)=>{this.emit("drain",o,[this,...s])},this[zq]=(o,s)=>{this.emit("connect",o,[this,...s])},this[qq]=(o,s,a)=>{this.emit("disconnect",o,[this,...s],a)},this[Hq]=(o,s,a)=>{this.emit("connectionError",o,[this,...s],a)}}get[jq](){let e=0;for(let{dispatcher:r}of this[hi].values())e+=r[jq];return e}[aDe](e,r){let n;if(e.origin&&(typeof e.origin=="string"||e.origin instanceof URL))n=String(e.origin);else throw new SE("opts.origin must be a non-empty string or URL.");if(this[Xp].size>=this[uv].maxOrigins&&!this[Xp].has(n))throw new iDe;let i=this[hi].get(n),o=i&&i.dispatcher;if(!o){let s=a=>{let c=this[hi].get(n);c&&(a&&(c.count-=1),c.count<=0&&(this[hi].delete(n),c.dispatcher.destroyed||c.dispatcher.close()),this[Xp].delete(n))};o=this[Yq](e.origin,this[uv]).on("drain",this[Gq]).on("connect",(a,c)=>{let l=this[hi].get(n);l&&(l.count+=1),this[zq](a,c)}).on("disconnect",(a,c,l)=>{s(!0),this[qq](a,c,l)}).on("connectionError",(a,c,l)=>{s(!1),this[Hq](a,c,l)}),this[hi].set(n,{count:0,dispatcher:o}),this[Xp].add(n)}return o.dispatch(e,r)}[oDe](){let e=[];for(let{dispatcher:r}of this[hi].values())e.push(r.close());return this[hi].clear(),Promise.all(e)}[sDe](e){let r=[];for(let{dispatcher:n}of this[hi].values())r.push(n.destroy(e));return this[hi].clear(),Promise.all(r)}get stats(){let e={};for(let{dispatcher:r}of this[hi].values())r.stats&&(e[r[cDe].origin]=r.stats);return e}};Vq.exports=dv});var Zq=y((Zze,Jq)=>{"use strict";var{Buffer:ja}=require("buffer"),Av=require("net"),{InvalidArgumentError:Fa}=_e();function hDe(t){if(Av.isIPv4(t)){let r=t.split(".").map(Number);return{type:1,buffer:ja.from(r)}}if(Av.isIPv6(t))return{type:4,buffer:Wq(t)};let e=ja.from(t,"utf8");if(e.length>255)throw new Fa("Domain name too long (max 255 bytes)");return{type:3,buffer:ja.concat([ja.from([e.length]),e])}}function Wq(t){let e=ja.alloc(16),r=t;if(t.includes(".")){let i=t.lastIndexOf(":"),o=t.slice(i+1);if(Av.isIPv4(o)){let s=o.split(".").map(Number),a=(s[0]<<8|s[1]).toString(16),c=(s[2]<<8|s[3]).toString(16);r=`${t.slice(0,i)}:${a}:${c}`}}let n=r.indexOf("::");if(n!==-1){let i=r.slice(0,n),o=r.slice(n+2),s=i===""?[]:i.split(":"),a=o===""?[]:o.split(":"),c=0;for(let l of s)e.writeUInt16BE(parseInt(l,16),c),c+=2;c=16-a.length*2;for(let l of a)e.writeUInt16BE(parseInt(l,16),c),c+=2}else{let i=r.split(":");for(let o=0;o<i.length;o++)e.writeUInt16BE(parseInt(i[o],16),o*2)}return e}function fDe(t,e,r){let n=ja.allocUnsafe(2);return n.writeUInt16BE(r,0),ja.concat([ja.from([t]),e,n])}function gDe(t,e=0){if(t.length<e+1)throw new Fa("Buffer too small to contain address type");let r=t[e],n,i=e+1;switch(r){case 1:{if(t.length<i+6)throw new Fa("Buffer too small for IPv4 address");n=Array.from(t.subarray(i,i+4)).join("."),i+=4;break}case 3:{if(t.length<i+1)throw new Fa("Buffer too small for domain length");let s=t[i];if(i+=1,t.length<i+s+2)throw new Fa("Buffer too small for domain address");n=t.subarray(i,i+s).toString("utf8"),i+=s;break}case 4:{if(t.length<i+18)throw new Fa("Buffer too small for IPv6 address");let s=[];for(let a=0;a<8;a++){let c=t.readUInt16BE(i+a*2);s.push(c.toString(16))}n=s.join(":"),i+=16;break}default:throw new Fa(`Invalid address type: ${r}`)}if(t.length<i+2)throw new Fa("Buffer too small for port");let o=t.readUInt16BE(i);return i+=2,{address:n,port:o,bytesRead:i-e}}function mDe(t){let r={1:"General SOCKS server failure",2:"Connection not allowed by ruleset",3:"Network unreachable",4:"Host unreachable",5:"Connection refused",6:"TTL expired",7:"Command not supported",8:"Address type not supported"}[t]||`Unknown SOCKS5 error code: ${t}`,n=new Error(r);return n.code=`SOCKS5_${t}`,n}Jq.exports={parseAddress:hDe,parseIPv6:Wq,buildAddressBuffer:fDe,parseResponseAddress:gDe,createReplyError:mDe}});var tH=y((Kze,eH)=>{"use strict";var{EventEmitter:yDe}=require("events"),{Buffer:ol}=require("buffer"),{InvalidArgumentError:Yu,Socks5ProxyError:za}=_e(),{debuglog:EDe}=require("util"),{parseAddress:IDe}=Zq(),Hs=EDe("undici:socks5"),Kq=ol.alloc(0),wE=5,Vu={NO_AUTH:0,GSSAPI:1,USERNAME_PASSWORD:2,NO_ACCEPTABLE:255},Xq={CONNECT:1,BIND:2,UDP_ASSOCIATE:3},sl={IPV4:1,DOMAIN:3,IPV6:4},os={SUCCEEDED:0,GENERAL_FAILURE:1,CONNECTION_NOT_ALLOWED:2,NETWORK_UNREACHABLE:3,HOST_UNREACHABLE:4,CONNECTION_REFUSED:5,TTL_EXPIRED:6,COMMAND_NOT_SUPPORTED:7,ADDRESS_TYPE_NOT_SUPPORTED:8},Qr={INITIAL:"initial",HANDSHAKING:"handshaking",AUTHENTICATING:"authenticating",AUTHENTICATED:"authenticated",CONNECTING:"connecting",CONNECTED:"connected",ERROR:"error",CLOSED:"closed"},pv=class extends yDe{constructor(e,r={}){if(super(),!e)throw new Yu("socket is required");this.socket=e,this.options=r,this.state=Qr.INITIAL,this.buffer=Kq,this.onSocketData=this.onData.bind(this),this.onSocketError=this.onError.bind(this),this.onSocketClose=this.onClose.bind(this),this.authMethods=[],r.username&&r.password&&this.authMethods.push(Vu.USERNAME_PASSWORD),this.authMethods.push(Vu.NO_AUTH),this.socket.on("data",this.onSocketData),this.socket.on("error",this.onSocketError),this.socket.on("close",this.onSocketClose)}onData(e){Hs("received data",e.length,"bytes in state",this.state),this.buffer=ol.concat([this.buffer,e]);try{switch(this.state){case Qr.HANDSHAKING:this.handleHandshakeResponse();break;case Qr.AUTHENTICATING:this.handleAuthResponse();break;case Qr.CONNECTING:this.handleConnectResponse();break}}catch(r){this.onError(r)}}onError(e){Hs("socket error",e),this.state=Qr.ERROR,this.emit("error",e),this.destroy()}onClose(){Hs("socket closed"),this.state=Qr.CLOSED,this.emit("close")}destroy(){this.socket&&!this.socket.destroyed&&this.socket.destroy()}markAuthenticated(){this.state=Qr.AUTHENTICATED,this.emit("authenticated")}handshake(){if(this.state!==Qr.INITIAL)throw new Yu("Handshake already started");Hs("starting handshake with",this.authMethods.length,"auth methods"),this.state=Qr.HANDSHAKING;let e=ol.alloc(2+this.authMethods.length);e[0]=wE,e[1]=this.authMethods.length,this.authMethods.forEach((r,n)=>{e[2+n]=r}),this.socket.write(e)}handleHandshakeResponse(){if(this.buffer.length<2)return;let e=this.buffer[0],r=this.buffer[1];if(e!==wE)throw new za(`Invalid SOCKS version: ${e}`,"UND_ERR_SOCKS5_VERSION");if(r===Vu.NO_ACCEPTABLE)throw new za("No acceptable authentication method","UND_ERR_SOCKS5_AUTH_REJECTED");if(this.buffer=this.buffer.subarray(2),Hs("server selected auth method",r),r===Vu.NO_AUTH)this.markAuthenticated();else if(r===Vu.USERNAME_PASSWORD)this.state=Qr.AUTHENTICATING,this.sendAuthRequest();else throw new za(`Unsupported authentication method: ${r}`,"UND_ERR_SOCKS5_AUTH_METHOD")}sendAuthRequest(){let{username:e,password:r}=this.options;if(!e||!r)throw new Yu("Username and password required for authentication");Hs("sending username/password auth");let n=ol.from(e),i=ol.from(r);if(n.length>255||i.length>255)throw new Yu("Username or password too long");let o=ol.alloc(3+n.length+i.length);o[0]=1,o[1]=n.length,n.copy(o,2),o[2+n.length]=i.length,i.copy(o,3+n.length),this.socket.write(o)}handleAuthResponse(){if(this.buffer.length<2)return;let e=this.buffer[0],r=this.buffer[1];if(e!==1)throw new za(`Invalid auth sub-negotiation version: ${e}`,"UND_ERR_SOCKS5_AUTH_VERSION");if(r!==0)throw new za("Authentication failed","UND_ERR_SOCKS5_AUTH_FAILED");this.buffer=this.buffer.subarray(2),Hs("authentication successful"),this.markAuthenticated()}connect(e,r){if(this.state===Qr.CONNECTING||this.state===Qr.CONNECTED)throw new Yu("Connection already in progress");if(this.state!==Qr.AUTHENTICATED)throw new Yu("Client must be authenticated before CONNECT");Hs("connecting to",e,r),this.state=Qr.CONNECTING;let n=this.buildConnectRequest(Xq.CONNECT,e,r);this.socket.write(n)}buildConnectRequest(e,r,n){let{type:i,buffer:o}=IDe(r),s=ol.alloc(4+o.length+2);return s[0]=wE,s[1]=e,s[2]=0,s[3]=i,o.copy(s,4),s.writeUInt16BE(n,4+o.length),s}handleConnectResponse(){if(this.buffer.length<4)return;let e=this.buffer[0],r=this.buffer[1],n=this.buffer[3];if(e!==wE)throw new za(`Invalid SOCKS version in reply: ${e}`,"UND_ERR_SOCKS5_REPLY_VERSION");let i=4;if(n===sl.IPV4)i+=6;else if(n===sl.DOMAIN){if(this.buffer.length<5)return;i+=1+this.buffer[4]+2}else if(n===sl.IPV6)i+=18;else throw new za(`Invalid address type in reply: ${n}`,"UND_ERR_SOCKS5_ADDR_TYPE");if(this.buffer.length<i)return;if(r!==os.SUCCEEDED){let c=this.getReplyErrorMessage(r);throw new za(`SOCKS5 connection failed: ${c}`,`UND_ERR_SOCKS5_REPLY_${r}`)}let o,s=4;if(n===sl.IPV4)o=Array.from(this.buffer.subarray(s,s+4)).join("."),s+=4;else if(n===sl.DOMAIN){let c=this.buffer[s];s+=1,o=this.buffer.subarray(s,s+c).toString(),s+=c}else if(n===sl.IPV6){let c=[];for(let l=0;l<8;l++){let u=this.buffer.readUInt16BE(s+l*2);c.push(u.toString(16))}o=c.join(":"),s+=16}let a=this.buffer.readUInt16BE(s);this.buffer=Kq,this.state=Qr.CONNECTED,this.socket.removeListener("data",this.onSocketData),Hs("connected, bound address:",o,"port:",a),this.emit("connected",{address:o,port:a})}getReplyErrorMessage(e){switch(e){case os.GENERAL_FAILURE:return"General SOCKS server failure";case os.CONNECTION_NOT_ALLOWED:return"Connection not allowed by ruleset";case os.NETWORK_UNREACHABLE:return"Network unreachable";case os.HOST_UNREACHABLE:return"Host unreachable";case os.CONNECTION_REFUSED:return"Connection refused";case os.TTL_EXPIRED:return"TTL expired";case os.COMMAND_NOT_SUPPORTED:return"Command not supported";case os.ADDRESS_TYPE_NOT_SUPPORTED:return"Address type not supported";default:return`Unknown error code: ${e}`}}};eH.exports={Socks5Client:pv,AUTH_METHODS:Vu,COMMANDS:Xq,ADDRESS_TYPES:sl,REPLY_CODES:os,STATES:Qr}});var yv=y((Xze,lH)=>{"use strict";var{URL:rH}=require("url"),hv,CDe=zc(),{InvalidArgumentError:nH}=_e(),{Socks5Client:bDe,STATES:SDe}=tH(),{kDispatch:iH,kClose:wDe,kDestroy:_De}=ut(),BDe=tl(),vDe=qc(),{debuglog:QDe}=require("util"),qa=QDe("undici:socks5-proxy"),fv=Symbol("proxy url"),TDe=Symbol("proxy headers"),oH=Symbol("proxy auth"),sH=Symbol("proxy protocol"),al=Symbol("pools"),aH=Symbol("connector"),gv=Symbol("request tls settings"),cH=!1,mv=class extends CDe{constructor(e,r={}){if(super(),cH||(process.emitWarning("SOCKS5 proxy support is experimental and subject to change","ExperimentalWarning"),cH=!0),!e)throw new nH("Proxy URL is mandatory");let n=typeof e=="string"?new rH(e):e;if(n.protocol!=="socks5:"&&n.protocol!=="socks:")throw new nH("Proxy URL must use socks5:// or socks:// protocol");this[fv]=n,this[TDe]=r.headers||{},this[sH]=r.proxyTls?"https:":"http:",this[gv]=r.requestTls,this[oH]={username:r.username||(n.username?decodeURIComponent(n.username):null),password:r.password||(n.password?decodeURIComponent(n.password):null)},this[aH]=r.connect||vDe({...r.proxyTls,servername:r.proxyTls?.servername||n.hostname}),this[al]=new Map}async createSocks5Connection(e,r){let n=this[fv].hostname,i=parseInt(this[fv].port)||1080;qa("creating SOCKS5 connection to",n,i);let o=await new Promise((a,c)=>{this[aH]({hostname:n,host:n,port:i,protocol:this[sH]},(l,u)=>{l?c(l):a(u)})}),s=new bDe(o,this[oH]);return s.on("error",a=>{qa("SOCKS5 error:",a),o.destroy()}),await s.handshake(),await new Promise((a,c)=>{let l=setTimeout(()=>{c(new Error("SOCKS5 authentication timeout"))},5e3),u=()=>{clearTimeout(l),s.removeListener("error",d),a()},d=A=>{clearTimeout(l),s.removeListener("authenticated",u),c(A)};s.state===SDe.AUTHENTICATED?(clearTimeout(l),a()):(s.once("authenticated",u),s.once("error",d))}),await s.connect(e,r),await new Promise((a,c)=>{let l=setTimeout(()=>{c(new Error("SOCKS5 connection timeout"))},5e3),u=A=>{qa("SOCKS5 tunnel established to",e,r,"via",A),clearTimeout(l),s.removeListener("error",d),a()},d=A=>{clearTimeout(l),s.removeListener("connected",u),c(A)};s.once("connected",u),s.once("error",d)}),o}[iH](e,r){let{origin:n}=e;qa("dispatching request to",n,"via SOCKS5");try{let i=String(n),o=this[al].get(i);return(!o||o.destroyed||o.closed)&&(o=new BDe(n,{pipelining:e.pipelining,connections:e.connections,connect:async(s,a)=>{try{let c=new rH(n),l=c.hostname,u=parseInt(c.port)||(c.protocol==="https:"?443:80);qa("establishing SOCKS5 connection to",l,u);let d=await this.createSocks5Connection(l,u),A=d;c.protocol==="https:"&&(hv||(hv=require("tls")),qa("upgrading to TLS"),A=hv.connect({...this[gv],socket:d,servername:this[gv]?.servername||l}),await new Promise((p,h)=>{A.once("secureConnect",p),A.once("error",h)})),a(null,A)}catch(c){qa("SOCKS5 connection error:",c),a(c)}}}),this[al].set(i,o)),o[iH](e,r)}catch(i){if(qa("dispatch error:",i),typeof r.onResponseError=="function")return r.onResponseError(null,i),!1;if(typeof r.onError=="function")return r.onError(i),!1;throw i}}async[wDe](){let e=[];for(let r of this[al].values())e.push(r.close());this[al].clear(),await Promise.all(e)}async[_De](e){let r=[];for(let n of this[al].values())r.push(n.destroy(e));this[al].clear(),await Promise.all(r)}};lH.exports=mv});var bv=y((eqe,CH)=>{"use strict";var{kProxy:Wu,kClose:gH,kDestroy:mH,kDispatch:uH}=ut(),DDe=il(),yH=tl(),EH=zc(),{InvalidArgumentError:cl,RequestAbortedError:kDe,SecureProxyConnectionError:RDe}=_e(),dH=qc(),IH=$a(),{channels:AH}=Ra(),NDe=yv(),_E=Symbol("proxy agent"),Ha=Symbol("proxy client"),Gs=Symbol("proxy headers"),Ev=Symbol("request tls settings"),pH=Symbol("proxy tls settings"),hH=Symbol("connect endpoint function"),fH=Symbol("tunnel proxy");function ODe(t){return t==="https:"?443:80}function xDe(t,e){return new yH(t,e)}var UDe=()=>{};function MDe(t,e){return e.connections===1?new IH(t,e):new yH(t,e)}var Iv=class extends EH{#e;constructor(e,{headers:r={},connect:n,factory:i}){if(!e)throw new cl("Proxy URL is mandatory");super(),this[Gs]=r,i?this.#e=i(e,{connect:n}):this.#e=new IH(e,{connect:n})}[uH](e,r){let n=r.onHeaders;r.onHeaders=function(a,c,l){if(a===407){typeof r.onError=="function"&&r.onError(new cl("Proxy Authentication Required (407)"));return}n&&n.call(this,a,c,l)};let{origin:i,path:o="/",headers:s={}}=e;if(e.path=i+o,!("host"in s)&&!("Host"in s)){let{host:a}=new URL(i);s.host=a}return e.headers={...this[Gs],...s},this.#e[uH](e,r)}[gH](){return this.#e.close()}[mH](e){return this.#e.destroy(e)}},Cv=class extends EH{constructor(e){if(!e||typeof e=="object"&&!(e instanceof URL)&&!e.uri)throw new cl("Proxy uri is mandatory");let{clientFactory:r=xDe}=e;if(typeof r!="function")throw new cl("Proxy opts.clientFactory must be a function.");let{proxyTunnel:n=!0}=e;super();let i=this.#e(e),{href:o,origin:s,port:a,protocol:c,username:l,password:u,hostname:d}=i;if(this[Wu]={uri:o,protocol:c},this[Ev]=e.requestTls,this[pH]=e.proxyTls,this[Gs]=e.headers||{},this[fH]=n,e.auth&&e.token)throw new cl("opts.auth cannot be used in combination with opts.token");e.auth?this[Gs]["proxy-authorization"]=`Basic ${e.auth}`:e.token?this[Gs]["proxy-authorization"]=e.token:l&&u&&(this[Gs]["proxy-authorization"]=`Basic ${Buffer.from(`${decodeURIComponent(l)}:${decodeURIComponent(u)}`).toString("base64")}`);let A=dH({...e.proxyTls});this[hH]=dH({...e.requestTls});let p=e.factory||MDe,h=(f,E)=>{let{protocol:S}=new URL(f);return this[Wu].protocol==="socks5:"||this[Wu].protocol==="socks:"?new NDe(this[Wu].uri,{headers:this[Gs],connect:A,factory:p,username:e.username||l,password:e.password||u,proxyTls:e.proxyTls,requestTls:e.requestTls}):!this[fH]&&S==="http:"&&this[Wu].protocol==="http:"?new Iv(this[Wu].uri,{headers:this[Gs],connect:A,factory:p}):p(f,E)};c==="socks5:"||c==="socks:"?this[Ha]=null:this[Ha]=r(i,{connect:A}),this[_E]=new DDe({...e,factory:h,connect:async(f,E)=>{if(!this[Ha]){E(new cl("Cannot establish tunnel connection without a proxy client"));return}let S=f.host;f.port||(S+=`:${ODe(f.protocol)}`);try{let B={origin:s,port:a,path:S,signal:f.signal,headers:{...this[Gs],host:f.host,...f.connections==null||f.connections>0?{"proxy-connection":"keep-alive"}:{}},servername:this[pH]?.servername||d},{socket:_,statusCode:v}=await this[Ha].connect(B);if(v!==200){_.on("error",UDe).destroy(),E(new kDe(`Proxy response (${v}) !== 200 when HTTP Tunneling`));return}if(AH.proxyConnected.hasSubscribers&&AH.proxyConnected.publish({socket:_,connectParams:B}),f.protocol!=="https:"){E(null,_);return}let T;this[Ev]?T=this[Ev].servername:T=f.servername,this[hH]({...f,servername:T,httpSocket:_},E)}catch(B){B.code==="ERR_TLS_CERT_ALTNAME_INVALID"?E(new RDe(B)):E(B)}}})}dispatch(e,r){let n=PDe(e.headers);if(LDe(n),n&&!("host"in n)&&!("Host"in n)){let{host:i}=new URL(e.origin);n.host=i}return this[_E].dispatch({...e,headers:n},r)}#e(e){return typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e.uri)}[gH](){let e=[this[_E].close()];return this[Ha]&&e.push(this[Ha].close()),Promise.all(e)}[mH](){let e=[this[_E].destroy()];return this[Ha]&&e.push(this[Ha].destroy()),Promise.all(e)}};function PDe(t){if(Array.isArray(t)){let e={};for(let r=0;r<t.length;r+=2)e[t[r]]=t[r+1];return e}return t}function LDe(t){if(t&&Object.keys(t).find(r=>r.toLowerCase()==="proxy-authorization"))throw new cl("Proxy-Authorization should be sent in ProxyAgent constructor")}CH.exports=Cv});var BH=y((tqe,_H)=>{"use strict";var $De=zc(),{kClose:FDe,kDestroy:jDe,kClosed:bH,kDestroyed:SH,kDispatch:zDe,kNoProxyAgent:eh,kHttpProxyAgent:Ga,kHttpsProxyAgent:ll}=ut(),wH=bv(),qDe=il(),HDe={"http:":80,"https:":443},Sv=class extends $De{#e=null;#t=null;#n=null;constructor(e={}){super(),this.#n=e;let{httpProxy:r,httpsProxy:n,noProxy:i,...o}=e;this[eh]=new qDe(o);let s=r??process.env.http_proxy??process.env.HTTP_PROXY;s?this[Ga]=new wH({...o,uri:s}):this[Ga]=this[eh];let a=n??process.env.https_proxy??process.env.HTTPS_PROXY;a?this[ll]=new wH({...o,uri:a}):this[ll]=this[Ga],this.#r()}[zDe](e,r){let n=new URL(e.origin);return this.#i(n).dispatch(e,r)}[FDe](){return Promise.all([this[eh].close(),!this[Ga][bH]&&this[Ga].close(),!this[ll][bH]&&this[ll].close()])}[jDe](e){return Promise.all([this[eh].destroy(e),!this[Ga][SH]&&this[Ga].destroy(e),!this[ll][SH]&&this[ll].destroy(e)])}#i(e){let{protocol:r,host:n,port:i}=e;return n=n.replace(/:\d*$/,"").toLowerCase(),i=Number.parseInt(i,10)||HDe[r]||0,this.#o(n,i)?r==="https:"?this[ll]:this[Ga]:this[eh]}#o(e,r){if(this.#c&&this.#r(),this.#t.length===0)return!0;if(this.#e==="*")return!1;for(let n=0;n<this.#t.length;n++){let i=this.#t[n];if(!(i.port&&i.port!==r)&&(e===i.hostname||e.slice(-(i.hostname.length+1))===`.${i.hostname}`))return!1}return!0}#r(){let e=this.#n.noProxy??this.#s,r=e.split(/[,\s]/),n=[];for(let i=0;i<r.length;i++){let o=r[i];if(!o)continue;let s=o.match(/^(.+):(\d+)$/);n.push({hostname:(s?s[1]:o).replace(/^\*?\./,"").toLowerCase(),port:s?Number.parseInt(s[2],10):0})}this.#e=e,this.#t=n}get#c(){return this.#n.noProxy!==void 0?!1:this.#e!==this.#s}get#s(){return process.env.no_proxy??process.env.NO_PROXY??""}};_H.exports=Sv});var BE=y((rqe,kH)=>{"use strict";var th=require("assert"),{kRetryHandlerDefaultRetry:vH}=ut(),{RequestRetryError:ul}=_e(),GDe=Sp(),{isDisturbed:QH,parseRangeHeader:TH,wrapRequestBody:YDe}=De();function VDe(t){let e=new Date(t).getTime();return isNaN(e)?0:e-Date.now()}function DH(t,e,r,n){let i=t["content-length"];if(i==null||!Number.isFinite(e.start)||!Number.isFinite(e.end))return;let o=Number(i),s=e.end-e.start+1;if(!Number.isFinite(o)||o!==s)throw new ul("Content-Length mismatch",r,{headers:t,data:{count:n}})}var wv=class{#e=!1;#t=null;set target(e){this.#t=e,this.#e&&e?.pause()}get target(){return this.#t}pause(){this.#e=!0,this.#t?.pause()}resume(){this.#e=!1,this.#t?.resume()}abort(e){this.#t?.abort(e)}get paused(){return this.#e||(this.#t?.paused??!1)}get aborted(){return this.#t?.aborted??!1}get reason(){return this.#t?.reason??null}get rawHeaders(){return this.#t?.rawHeaders??null}set rawHeaders(e){this.#t&&(this.#t.rawHeaders=e)}get rawTrailers(){return this.#t?.rawTrailers??null}set rawTrailers(e){this.#t&&(this.#t.rawTrailers=e)}},_v=class t{constructor(e,{dispatch:r,handler:n}){let{retryOptions:i,...o}=e,{retry:s,maxRetries:a,maxTimeout:c,minTimeout:l,timeoutFactor:u,methods:d,errorCodes:A,retryAfter:p,statusCodes:h,throwOnError:f}=i??{};this.error=null,this.dispatch=r,this.handler=GDe.wrap(n),this.opts={...o,body:YDe(e.body)},this.retryOpts={throwOnError:f??!0,retry:s??t[vH],retryAfter:p??!0,maxTimeout:c??30*1e3,minTimeout:l??500,timeoutFactor:u??2,maxRetries:a??5,methods:d??["GET","HEAD","OPTIONS","PUT","DELETE","TRACE"],statusCodes:h??[500,502,503,504,429],errorCodes:A??["ECONNRESET","ECONNREFUSED","ENOTFOUND","ENETDOWN","ENETUNREACH","EHOSTDOWN","EHOSTUNREACH","EPIPE","UND_ERR_SOCKET"]},this.retryCount=0,this.retryCountCheckpoint=0,this.headersSent=!1,this.start=0,this.end=null,this.etag=null,this.controllerProxy=new wv}onResponseStartWithRetry(e,r,n,i,o){if(this.retryOpts.throwOnError){this.retryOpts.statusCodes.includes(r)===!1?this.headersSent?this.handler.onResponseError?.(this.controllerProxy,o):(this.headersSent=!0,this.checkpointResponseEnd(n),this.handler.onResponseStart?.(this.controllerProxy,r,n,i)):this.error=o;return}if(QH(this.opts.body)){this.headersSent=!0,this.checkpointResponseEnd(n),this.handler.onResponseStart?.(this.controllerProxy,r,n,i);return}function s(a){if(a){this.headersSent?this.handler.onResponseError?.(this.controllerProxy,a):(this.headersSent=!0,this.checkpointResponseEnd(n),this.handler.onResponseStart?.(this.controllerProxy,r,n,i)),e.resume();return}this.error=o,e.resume()}e.pause(),this.retryOpts.retry(o,{state:{counter:this.retryCount},opts:{retryOptions:this.retryOpts,...this.opts}},s.bind(this))}checkpointResponseEnd(e){if(this.end==null&&this.opts.method!=="HEAD"){let r=e["content-length"];this.end=r!=null?Number(r)-1:null,th(this.end==null||Number.isFinite(this.end),"invalid content-length"),this.resume=this.end!=null}}onRequestStart(e,r){this.controllerProxy.target=e,this.headersSent||this.handler.onRequestStart?.(this.controllerProxy,r)}onRequestUpgrade(e,r,n,i){this.handler.onRequestUpgrade?.(this.controllerProxy,r,n,i)}static[vH](e,{state:r,opts:n},i){let{statusCode:o,code:s,headers:a}=e,{method:c,retryOptions:l}=n,{maxRetries:u,minTimeout:d,maxTimeout:A,timeoutFactor:p,statusCodes:h,errorCodes:f,methods:E}=l,{counter:S}=r;if(s&&s!=="UND_ERR_REQ_RETRY"&&!f.includes(s)){i(e);return}if(Array.isArray(E)&&!E.includes(c)){i(e);return}if(o!=null&&Array.isArray(h)&&!h.includes(o)){i(e);return}if(S>u){i(e);return}let B=a?.["retry-after"];B&&(B=Number(B),B=Number.isNaN(B)?VDe(a["retry-after"]):B*1e3);let _=B>0?Math.min(B,A):Math.min(d*p**(S-1),A);setTimeout(()=>i(null),_)}onResponseStart(e,r,n,i){if(this.error=null,this.retryCount+=1,r>=300){let o=new ul("Request failed",r,{headers:n,data:{count:this.retryCount}});this.onResponseStartWithRetry(e,r,n,i,o);return}if(this.headersSent){if(r!==206&&(this.start>0||r!==200))throw new ul("server does not support the range header and the payload was partially consumed",r,{headers:n,data:{count:this.retryCount}});let o=TH(n["content-range"]);if(!o)throw new ul("Content-Range mismatch",r,{headers:n,data:{count:this.retryCount}});if(this.etag!=null&&this.etag!==n.etag)throw new ul("ETag mismatch",r,{headers:n,data:{count:this.retryCount}});DH(n,o,r,this.retryCount);let{start:s,size:a,end:c=a?a-1:null}=o;if(this.start!==s||this.end!=null&&this.end!==c)throw new ul("Content-Range mismatch",r,{headers:n,data:{count:this.retryCount}});return}if(this.end==null){if(r===206){let o=TH(n["content-range"]);if(o==null){this.headersSent=!0,this.handler.onResponseStart?.(this.controllerProxy,r,n,i);return}DH(n,o,r,this.retryCount);let{start:s,size:a,end:c=a?a-1:null}=o;th(s!=null&&Number.isFinite(s),"content-range mismatch"),th(c!=null&&Number.isFinite(c),"invalid content-length"),this.start=s,this.end=c}if(this.end==null){let o=n["content-length"];this.end=o!=null?Number(o)-1:null}th(Number.isFinite(this.start)),th(this.end==null||Number.isFinite(this.end),"invalid content-length"),this.resume=!0,this.etag=n.etag!=null?n.etag:null,this.etag!=null&&this.etag[0]==="W"&&this.etag[1]==="/"&&(this.etag=null),this.headersSent=!0,this.handler.onResponseStart?.(this.controllerProxy,r,n,i)}else throw new ul("Request failed",r,{headers:n,data:{count:this.retryCount}})}onResponseData(e,r){this.error||(this.start+=r.length,this.handler.onResponseData?.(this.controllerProxy,r))}onResponseEnd(e,r){if(this.error&&this.retryOpts.throwOnError)throw this.error;if(!this.error)return this.retryCount=0,this.handler.onResponseEnd?.(this.controllerProxy,r);this.retry()}retry(){if(this.start!==0){let e={range:`bytes=${this.start}-${this.end??""}`};this.etag!=null&&(e["if-match"]=this.etag),this.opts={...this.opts,headers:{...this.opts.headers,...e}}}try{this.retryCountCheckpoint=this.retryCount,this.dispatch(this.opts,this)}catch(e){this.handler.onResponseError?.(this.controllerProxy,e)}}onResponseError(e,r){if(e?.aborted||QH(this.opts.body)||this.headersSent&&!this.resume){this.handler.onResponseError?.(this.controllerProxy,r);return}function n(i){if(!i){this.retry();return}this.handler?.onResponseError?.(this.controllerProxy,i)}this.retryCount-this.retryCountCheckpoint>0?this.retryCount=this.retryCountCheckpoint+(this.retryCount-this.retryCountCheckpoint):this.retryCount+=1,this.retryOpts.retry(r,{state:{counter:this.retryCount},opts:{retryOptions:this.retryOpts,...this.opts}},n.bind(this))}};kH.exports=_v});var NH=y((nqe,RH)=>{"use strict";var WDe=wp(),JDe=BE(),Bv=class extends WDe{#e=null;#t=null;constructor(e,r={}){super(r),this.#e=e,this.#t=r}dispatch(e,r){let n=new JDe({...e,retryOptions:this.#t},{dispatch:this.#e.dispatch.bind(this.#e),handler:r});return this.#e.dispatch(e,n)}close(){return this.#e.close()}destroy(){return this.#e.destroy()}};RH.exports=Bv});var UH=y((iqe,xH)=>{"use strict";var{InvalidArgumentError:OH}=_e(),ZDe=$a(),vv=class extends ZDe{constructor(e,r){if(typeof e=="string"&&(e=new URL(e)),e.protocol!=="http:")throw new OH("h2c-client: Only h2c protocol is supported");let{maxConcurrentStreams:n,pipelining:i,...o}=r??{},s=100,a=100;if(n!=null&&Number.isInteger(n)&&n>0&&(s=n),i!=null&&Number.isInteger(i)&&i>0&&(a=i),a>s)throw new OH("h2c-client: pipelining cannot be greater than maxConcurrentStreams");super(e,{...o,maxConcurrentStreams:s,pipelining:a,allowH2:!0,useH2c:!0})}};xH.exports=vv});var HH=y((oqe,qH)=>{"use strict";var $H=require("assert"),{Readable:KDe}=require("stream"),{RequestAbortedError:FH,NotSupportedError:XDe,InvalidArgumentError:eke,AbortError:vE}=_e(),jH=De(),{ReadableStreamFrom:tke}=De(),Rn=Symbol("kConsume"),QE=Symbol("kReading"),dl=Symbol("kBody"),MH=Symbol("kAbort"),zH=Symbol("kContentType"),Qv=Symbol("kContentLength"),Tv=Symbol("kUsed"),TE=Symbol("kBytesRead"),rke=()=>{},Dv=class extends KDe{constructor({resume:e,abort:r,contentType:n="",contentLength:i,highWaterMark:o=64*1024}){super({autoDestroy:!0,read:e,highWaterMark:o}),this._readableState.dataEmitted=!1,this[MH]=r,this[Rn]=null,this[TE]=0,this[dl]=null,this[Tv]=!1,this[zH]=n,this[Qv]=Number.isFinite(i)?i:null,this[QE]=!1}_destroy(e,r){!e&&!this._readableState.endEmitted&&(e=new FH),e&&this[MH](),this[Tv]?r(e):setImmediate(r,e)}on(e,r){return(e==="data"||e==="readable")&&(this[QE]=!0,this[Tv]=!0),super.on(e,r)}addListener(e,r){return this.on(e,r)}off(e,r){let n=super.off(e,r);return(e==="data"||e==="readable")&&(this[QE]=this.listenerCount("data")>0||this.listenerCount("readable")>0),n}removeListener(e,r){return this.off(e,r)}push(e){return e&&(this[TE]+=e.length,this[Rn])?(Rv(this[Rn],e),this[QE]?super.push(e):!0):super.push(e)}text(){return rh(this,"text")}json(){return rh(this,"json")}blob(){return rh(this,"blob")}bytes(){return rh(this,"bytes")}arrayBuffer(){return rh(this,"arrayBuffer")}async formData(){throw new XDe}get bodyUsed(){return jH.isDisturbed(this)}get body(){return this[dl]||(this[dl]=tke(this),this[Rn]&&(this[dl].getReader(),$H(this[dl].locked))),this[dl]}dump(e){let r=e?.signal;if(r!=null&&(typeof r!="object"||!("aborted"in r)))return Promise.reject(new eke("signal must be an AbortSignal"));let n=e?.limit&&Number.isFinite(e.limit)?e.limit:128*1024;return r?.aborted?Promise.reject(r.reason??new vE):this._readableState.closeEmitted?Promise.resolve(null):new Promise((i,o)=>{if((this[Qv]&&this[Qv]>n||this[TE]>n)&&this.destroy(new vE),r){let s=()=>{this.destroy(r.reason??new vE)};r.addEventListener("abort",s),this.on("close",function(){r.removeEventListener("abort",s),r.aborted?o(r.reason??new vE):i(null)})}else this.on("close",i);this.on("error",rke).on("data",()=>{this[TE]>n&&this.destroy()}).resume()})}setEncoding(e){return Buffer.isEncoding(e)&&(this._readableState.encoding=e),this}};function nke(t){return t[dl]?.locked===!0||t[Rn]!==null}function ike(t){return jH.isDisturbed(t)||nke(t)}function rh(t,e){return $H(!t[Rn]),new Promise((r,n)=>{if(ike(t)){let i=t._readableState;i.destroyed&&i.closeEmitted===!1?t.on("error",n).on("close",()=>{n(new TypeError("unusable"))}):n(i.errored??new TypeError("unusable"))}else queueMicrotask(()=>{t[Rn]={type:e,stream:t,resolve:r,reject:n,length:0,body:[]},t.on("error",function(i){Nv(this[Rn],i)}).on("close",function(){this[Rn].body!==null&&Nv(this[Rn],new FH)}),oke(t[Rn])})})}function oke(t){if(t.body===null)return;let{_readableState:e}=t.stream;if(e.bufferIndex){let r=e.bufferIndex,n=e.buffer.length;for(let i=r;i<n;i++)Rv(t,e.buffer[i])}else for(let r of e.buffer)Rv(t,r);for(e.endEmitted?LH(this[Rn],this._readableState.encoding):t.stream.on("end",function(){LH(this[Rn],this._readableState.encoding)}),t.stream.resume();t.stream.read()!=null;);}function kv(t,e,r){if(t.length===0||e===0)return"";let n=t.length===1?t[0]:Buffer.concat(t,e),i=n.length,o=i>2&&n[0]===239&&n[1]===187&&n[2]===191?3:0;return!r||r==="utf8"||r==="utf-8"?n.utf8Slice(o,i):n.subarray(o,i).toString(r)}function PH(t,e){if(t.length===0||e===0)return new Uint8Array(0);if(t.length===1)return new Uint8Array(t[0]);let r=new Uint8Array(Buffer.allocUnsafeSlow(e).buffer),n=0;for(let i=0;i<t.length;++i){let o=t[i];r.set(o,n),n+=o.length}return r}function LH(t,e){let{type:r,body:n,resolve:i,stream:o,length:s}=t;try{r==="text"?i(kv(n,s,e)):r==="json"?i(JSON.parse(kv(n,s,e))):r==="arrayBuffer"?i(PH(n,s).buffer):r==="blob"?i(new Blob(n,{type:o[zH]})):r==="bytes"&&i(PH(n,s)),Nv(t)}catch(a){o.destroy(a)}}function Rv(t,e){t.length+=e.length,t.body.push(e)}function Nv(t,e){t.body!==null&&(e?t.reject(e):t.resolve(),t.type=null,t.stream=null,t.resolve=null,t.reject=null,t.length=0,t.body=null)}qH.exports={Readable:Dv,chunksDecode:kv}});var VH=y((sqe,Ov)=>{"use strict";var ske=require("assert"),{AsyncResource:ake}=require("async_hooks"),{Readable:cke}=HH(),{InvalidArgumentError:Ju,RequestAbortedError:GH}=_e(),fi=De();function nh(){}var DE=class extends ake{constructor(e,r){if(!e||typeof e!="object")throw new Ju("invalid opts");let{signal:n,method:i,opaque:o,body:s,onInfo:a,responseHeaders:c,highWaterMark:l}=e;try{if(typeof r!="function")throw new Ju("invalid callback");if(l!=null&&(!Number.isFinite(l)||l<0))throw new Ju("invalid highWaterMark");if(n&&typeof n.on!="function"&&typeof n.addEventListener!="function")throw new Ju("signal must be an EventEmitter or EventTarget");if(i==="CONNECT")throw new Ju("invalid method");if(a&&typeof a!="function")throw new Ju("invalid onInfo callback");super("UNDICI_REQUEST")}catch(u){throw fi.isStream(s)&&fi.destroy(s.on("error",nh),u),u}this.method=i,this.responseHeaders=c||null,this.opaque=o||null,this.callback=r,this.res=null,this.abort=null,this.body=s,this.trailers={},this.context=null,this.onInfo=a||null,this.highWaterMark=l,this.reason=null,this.removeAbortListener=null,n?.aborted?this.reason=n.reason??new GH:n&&(this.removeAbortListener=fi.addAbortListener(n,()=>{this.reason=n.reason??new GH,this.res?fi.destroy(this.res.on("error",nh),this.reason):this.abort&&this.abort(this.reason)}))}onConnect(e,r){if(this.reason){e(this.reason);return}ske(this.callback),this.abort=e,this.context=r}onHeaders(e,r,n,i){let{callback:o,opaque:s,abort:a,context:c,responseHeaders:l,highWaterMark:u}=this,d=l==="raw"?fi.parseRawHeaders(r):fi.parseHeaders(r);if(e<200){this.onInfo&&this.onInfo({statusCode:e,headers:d});return}let A=l==="raw"?fi.parseHeaders(r):d,p=A["content-type"],h=A["content-length"],f=new cke({resume:n,abort:a,contentType:p,contentLength:this.method!=="HEAD"&&h?Number(h):null,highWaterMark:u});if(this.removeAbortListener&&(f.on("close",this.removeAbortListener),this.removeAbortListener=null),this.callback=null,this.res=f,o!==null)try{this.runInAsyncScope(o,null,null,{statusCode:e,statusText:i,headers:d,trailers:this.trailers,opaque:s,body:f,context:c})}catch(E){this.res=null,fi.destroy(f.on("error",nh),E),queueMicrotask(()=>{throw E})}}onData(e){return this.res.push(e)}onComplete(e){fi.parseHeaders(e,this.trailers),this.res.push(null)}onError(e){let{res:r,callback:n,body:i,opaque:o}=this;n&&(this.callback=null,queueMicrotask(()=>{this.runInAsyncScope(n,null,e,{opaque:o})})),r&&(this.res=null,queueMicrotask(()=>{fi.destroy(r.on("error",nh),e)})),i&&(this.body=null,fi.isStream(i)&&(i.on("error",nh),fi.destroy(i,e))),this.removeAbortListener&&(this.removeAbortListener(),this.removeAbortListener=null)}};function YH(t,e){if(e===void 0)return new Promise((r,n)=>{YH.call(this,t,(i,o)=>i?n(i):r(o))});try{let r=new DE(t,e);this.dispatch(t,r)}catch(r){if(typeof e!="function")throw r;let n=t?.opaque;queueMicrotask(()=>e(r,{opaque:n}))}}Ov.exports=YH;Ov.exports.RequestHandler=DE});var ih=y((aqe,ZH)=>{"use strict";var{addAbortListener:lke}=De(),{RequestAbortedError:uke}=_e(),Zu=Symbol("kListener"),ss=Symbol("kSignal");function WH(t){t.abort?t.abort(t[ss]?.reason):t.reason=t[ss]?.reason??new uke,JH(t)}function dke(t,e){if(t.reason=null,t[ss]=null,t[Zu]=null,!!e){if(e.aborted){WH(t);return}t[ss]=e,t[Zu]=()=>{WH(t)},lke(t[ss],t[Zu])}}function JH(t){t[ss]&&("removeEventListener"in t[ss]?t[ss].removeEventListener("abort",t[Zu]):t[ss].removeListener("abort",t[Zu]),t[ss]=null,t[Zu]=null)}ZH.exports={addSignal:dke,removeSignal:JH}});var tG=y((cqe,eG)=>{"use strict";var Ake=require("assert"),{finished:pke}=require("stream"),{AsyncResource:hke}=require("async_hooks"),{InvalidArgumentError:Ku,InvalidReturnValueError:fke}=_e(),Ys=De(),{addSignal:gke,removeSignal:KH}=ih();function mke(){}var xv=class extends hke{constructor(e,r,n){if(!e||typeof e!="object")throw new Ku("invalid opts");let{signal:i,method:o,opaque:s,body:a,onInfo:c,responseHeaders:l}=e;try{if(typeof n!="function")throw new Ku("invalid callback");if(typeof r!="function")throw new Ku("invalid factory");if(i&&typeof i.on!="function"&&typeof i.addEventListener!="function")throw new Ku("signal must be an EventEmitter or EventTarget");if(o==="CONNECT")throw new Ku("invalid method");if(c&&typeof c!="function")throw new Ku("invalid onInfo callback");super("UNDICI_STREAM")}catch(u){throw Ys.isStream(a)&&Ys.destroy(a.on("error",mke),u),u}this.responseHeaders=l||null,this.opaque=s||null,this.factory=r,this.callback=n,this.res=null,this.abort=null,this.context=null,this.trailers=null,this.body=a,this.onInfo=c||null,Ys.isStream(a)&&a.on("error",u=>{this.onError(u)}),gke(this,i)}onConnect(e,r){if(this.reason){e(this.reason);return}Ake(this.callback),this.abort=e,this.context=r}onHeaders(e,r,n,i){let{factory:o,opaque:s,context:a,responseHeaders:c}=this,l=c==="raw"?Ys.parseRawHeaders(r):Ys.parseHeaders(r);if(e<200){this.onInfo&&this.onInfo({statusCode:e,headers:l});return}if(this.factory=null,o===null)return;let u=this.runInAsyncScope(o,null,{statusCode:e,headers:l,opaque:s,context:a});if(!u||typeof u.write!="function"||typeof u.end!="function"||typeof u.on!="function")throw new fke("expected Writable");return pke(u,{readable:!1},A=>{let{callback:p,res:h,opaque:f,trailers:E,abort:S}=this;this.res=null,(A||!h?.readable)&&Ys.destroy(h,A),this.callback=null,this.runInAsyncScope(p,null,A||null,{opaque:f,trailers:E}),A&&S()}),u.on("drain",n),this.res=u,(u.writableNeedDrain!==void 0?u.writableNeedDrain:u._writableState?.needDrain)!==!0}onData(e){let{res:r}=this;return r?r.write(e):!0}onComplete(e){let{res:r}=this;KH(this),r&&(this.trailers=Ys.parseHeaders(e),r.end())}onError(e){let{res:r,callback:n,opaque:i,body:o}=this;KH(this),this.factory=null,r?(this.res=null,Ys.destroy(r,e)):n&&(this.callback=null,queueMicrotask(()=>{this.runInAsyncScope(n,null,e,{opaque:i})})),o&&(this.body=null,Ys.destroy(o,e))}};function XH(t,e,r){if(r===void 0)return new Promise((n,i)=>{XH.call(this,t,e,(o,s)=>o?i(o):n(s))});try{let n=new xv(t,e,r);this.dispatch(t,n)}catch(n){if(typeof r!="function")throw n;let i=t?.opaque;queueMicrotask(()=>r(n,{opaque:i}))}}eG.exports=XH});var oG=y((lqe,iG)=>{"use strict";var{Readable:nG,Duplex:yke,PassThrough:Eke}=require("stream"),Ike=require("assert"),{AsyncResource:Cke}=require("async_hooks"),{InvalidArgumentError:oh,InvalidReturnValueError:bke,RequestAbortedError:Uv}=_e(),as=De(),{addSignal:Ske,removeSignal:wke}=ih();function rG(){}var Xu=Symbol("resume"),Mv=class extends nG{constructor(){super({autoDestroy:!0}),this[Xu]=null}_read(){let{[Xu]:e}=this;e&&(this[Xu]=null,e())}_destroy(e,r){this._read(),r(e)}},Pv=class extends nG{constructor(e){super({autoDestroy:!0}),this[Xu]=e}_read(){this[Xu]()}_destroy(e,r){!e&&!this._readableState.endEmitted&&(e=new Uv),r(e)}},Lv=class extends Cke{constructor(e,r){if(!e||typeof e!="object")throw new oh("invalid opts");if(typeof r!="function")throw new oh("invalid handler");let{signal:n,method:i,opaque:o,onInfo:s,responseHeaders:a}=e;if(n&&typeof n.on!="function"&&typeof n.addEventListener!="function")throw new oh("signal must be an EventEmitter or EventTarget");if(i==="CONNECT")throw new oh("invalid method");if(s&&typeof s!="function")throw new oh("invalid onInfo callback");super("UNDICI_PIPELINE"),this.opaque=o||null,this.responseHeaders=a||null,this.handler=r,this.abort=null,this.context=null,this.onInfo=s||null,this.req=new Mv().on("error",rG),this.ret=new yke({readableObjectMode:e.objectMode,autoDestroy:!0,read:()=>{let{body:c}=this;c?.resume&&c.resume()},write:(c,l,u)=>{let{req:d}=this;d.push(c,l)||d._readableState.destroyed?u():d[Xu]=u},destroy:(c,l)=>{let{body:u,req:d,res:A,ret:p,abort:h}=this;!c&&!p._readableState.endEmitted&&(c=new Uv),h&&c&&h(),as.destroy(u,c),as.destroy(d,c),as.destroy(A,c),wke(this),l(c)}}).on("prefinish",()=>{let{req:c}=this;c.push(null)}),this.res=null,Ske(this,n)}onConnect(e,r){let{res:n}=this;if(this.reason){e(this.reason);return}Ike(!n,"pipeline cannot be retried"),this.abort=e,this.context=r}onHeaders(e,r,n){let{opaque:i,handler:o,context:s}=this;if(e<200){if(this.onInfo){let c=this.responseHeaders==="raw"?as.parseRawHeaders(r):as.parseHeaders(r);this.onInfo({statusCode:e,headers:c})}return}this.res=new Pv(n);let a;try{this.handler=null;let c=this.responseHeaders==="raw"?as.parseRawHeaders(r):as.parseHeaders(r);a=this.runInAsyncScope(o,null,{statusCode:e,headers:c,opaque:i,body:this.res,context:s})}catch(c){throw this.res.on("error",rG),c}if(!a||typeof a.on!="function")throw new bke("expected Readable");a.on("data",c=>{let{ret:l,body:u}=this;!l.push(c)&&u.pause&&u.pause()}).on("error",c=>{let{ret:l}=this;as.destroy(l,c)}).on("end",()=>{let{ret:c}=this;c.push(null)}).on("close",()=>{let{ret:c}=this;c._readableState.ended||as.destroy(c,new Uv)}),this.body=a}onData(e){let{res:r}=this;return r.push(e)}onComplete(e){let{res:r}=this;r.push(null)}onError(e){let{ret:r}=this;this.handler=null,as.destroy(r,e)}};function _ke(t,e){try{let r=new Lv(t,e);return this.dispatch({...t,body:r.req},r),r.ret}catch(r){return new Eke().destroy(r)}}iG.exports=_ke});var dG=y((uqe,uG)=>{"use strict";var{InvalidArgumentError:$v,SocketError:Bke}=_e(),{AsyncResource:vke}=require("async_hooks"),sG=require("assert"),aG=De(),{kHTTP2Stream:Qke}=ut(),{addSignal:Tke,removeSignal:cG}=ih(),Fv=class extends vke{constructor(e,r){if(!e||typeof e!="object")throw new $v("invalid opts");if(typeof r!="function")throw new $v("invalid callback");let{signal:n,opaque:i,responseHeaders:o}=e;if(n&&typeof n.on!="function"&&typeof n.addEventListener!="function")throw new $v("signal must be an EventEmitter or EventTarget");super("UNDICI_UPGRADE"),this.responseHeaders=o||null,this.opaque=i||null,this.callback=r,this.abort=null,this.context=null,Tke(this,n)}onConnect(e,r){if(this.reason){e(this.reason);return}sG(this.callback),this.abort=e,this.context=null}onHeaders(){throw new Bke("bad upgrade",null)}onUpgrade(e,r,n){sG(n[Qke]===!0?e===200:e===101);let{callback:i,opaque:o,context:s}=this;cG(this),this.callback=null;let a=this.responseHeaders==="raw"?aG.parseRawHeaders(r):aG.parseHeaders(r);this.runInAsyncScope(i,null,null,{headers:a,socket:n,opaque:o,context:s})}onError(e){let{callback:r,opaque:n}=this;cG(this),r&&(this.callback=null,queueMicrotask(()=>{this.runInAsyncScope(r,null,e,{opaque:n})}))}};function lG(t,e){if(e===void 0)return new Promise((r,n)=>{lG.call(this,t,(i,o)=>i?n(i):r(o))});try{let r=new Fv(t,e),n={...t,method:t.method||"GET",upgrade:t.protocol||"Websocket"};this.dispatch(n,r)}catch(r){if(typeof e!="function")throw r;let n=t?.opaque;queueMicrotask(()=>e(r,{opaque:n}))}}uG.exports=lG});var gG=y((dqe,fG)=>{"use strict";var Dke=require("assert"),{AsyncResource:kke}=require("async_hooks"),{InvalidArgumentError:jv,SocketError:Rke}=_e(),AG=De(),{addSignal:Nke,removeSignal:pG}=ih(),zv=class extends kke{constructor(e,r){if(!e||typeof e!="object")throw new jv("invalid opts");if(typeof r!="function")throw new jv("invalid callback");let{signal:n,opaque:i,responseHeaders:o}=e;if(n&&typeof n.on!="function"&&typeof n.addEventListener!="function")throw new jv("signal must be an EventEmitter or EventTarget");super("UNDICI_CONNECT"),this.opaque=i||null,this.responseHeaders=o||null,this.callback=r,this.abort=null,Nke(this,n)}onConnect(e,r){if(this.reason){e(this.reason);return}Dke(this.callback),this.abort=e,this.context=r}onHeaders(){throw new Rke("bad connect",null)}onUpgrade(e,r,n){let{callback:i,opaque:o,context:s}=this;pG(this),this.callback=null;let a=r;a!=null&&(a=this.responseHeaders==="raw"?AG.parseRawHeaders(r):AG.parseHeaders(r)),this.runInAsyncScope(i,null,null,{statusCode:e,headers:a,socket:n,opaque:o,context:s})}onError(e){let{callback:r,opaque:n}=this;pG(this),r&&(this.callback=null,queueMicrotask(()=>{this.runInAsyncScope(r,null,e,{opaque:n})}))}};function hG(t,e){if(e===void 0)return new Promise((r,n)=>{hG.call(this,t,(i,o)=>i?n(i):r(o))});try{let r=new zv(t,e),n={...t,method:"CONNECT"};this.dispatch(n,r)}catch(r){if(typeof e!="function")throw r;let n=t?.opaque;queueMicrotask(()=>e(r,{opaque:n}))}}fG.exports=hG});var mG=y((Aqe,ed)=>{"use strict";ed.exports.request=VH();ed.exports.stream=tG();ed.exports.pipeline=oG();ed.exports.upgrade=dG();ed.exports.connect=gG()});var Hv=y((pqe,EG)=>{"use strict";var{UndiciError:Oke}=_e(),yG=Symbol.for("undici.error.UND_MOCK_ERR_MOCK_NOT_MATCHED"),qv=class extends Oke{constructor(e){super(e),this.name="MockNotMatchedError",this.message=e||"The request does not match any registered mock dispatches",this.code="UND_MOCK_ERR_MOCK_NOT_MATCHED"}static[Symbol.hasInstance](e){return e&&e[yG]===!0}get[yG](){return!0}};EG.exports={MockNotMatchedError:qv}});var Al=y((hqe,IG)=>{"use strict";IG.exports={kAgent:Symbol("agent"),kOptions:Symbol("options"),kFactory:Symbol("factory"),kDispatches:Symbol("dispatches"),kDispatchKey:Symbol("dispatch key"),kDefaultHeaders:Symbol("default headers"),kDefaultTrailers:Symbol("default trailers"),kContentLength:Symbol("content length"),kMockAgent:Symbol("mock agent"),kMockAgentSet:Symbol("mock agent set"),kMockAgentGet:Symbol("mock agent get"),kMockDispatch:Symbol("mock dispatch"),kClose:Symbol("close"),kOriginalClose:Symbol("original agent close"),kOriginalDispatch:Symbol("original dispatch"),kOrigin:Symbol("origin"),kIsMockActive:Symbol("is mock active"),kNetConnect:Symbol("net connect"),kGetNetConnect:Symbol("get net connect"),kConnected:Symbol("connected"),kIgnoreTrailingSlash:Symbol("ignore trailing slash"),kMockAgentMockCallHistoryInstance:Symbol("mock agent mock call history name"),kMockAgentRegisterCallHistory:Symbol("mock agent register mock call history"),kMockAgentAddCallHistoryLog:Symbol("mock agent add call history log"),kMockAgentIsCallHistoryEnabled:Symbol("mock agent is call history enabled"),kMockAgentAcceptsNonStandardSearchParameters:Symbol("mock agent accepts non standard search parameters"),kMockCallHistoryAddLog:Symbol("mock call history add log"),kTotalDispatchCount:Symbol("total dispatch count")}});var sh=y((fqe,kG)=>{"use strict";var{MockNotMatchedError:td}=Hv(),{kDispatches:pl,kMockAgent:xke,kOriginalDispatch:Uke,kOrigin:Mke,kGetNetConnect:Pke,kTotalDispatchCount:Vv}=Al(),{serializePathWithQuery:Lke}=De(),{STATUS_CODES:$ke}=require("http"),{types:{isPromise:Fke}}=require("util"),{InvalidArgumentError:Gv}=_e();function cs(t,e){return typeof t=="string"?t===e:t instanceof RegExp?t.test(e):typeof t=="function"?t(e)===!0:!1}function bG(t){return Object.fromEntries(Object.entries(t).map(([e,r])=>[e.toLocaleLowerCase(),r]))}function SG(t,e){if(Array.isArray(t)){for(let r=0;r<t.length;r+=2)if(t[r].toLocaleLowerCase()===e.toLocaleLowerCase())return t[r+1];return}else return typeof t.get=="function"?t.get(e):bG(t)[e.toLocaleLowerCase()]}function Zv(t){let e=t.slice(),r=[];for(let n=0;n<e.length;n+=2)r.push([e[n],e[n+1]]);return Object.fromEntries(r)}function wG(t,e){if(typeof t.headers=="function")return Array.isArray(e)&&(e=Zv(e)),t.headers(e?bG(e):{});if(typeof t.headers>"u")return!0;if(typeof e!="object"||typeof t.headers!="object")return!1;for(let[r,n]of Object.entries(t.headers)){let i=SG(e,r);if(!cs(n,i))return!1}return!0}function jke(t){if(typeof t!="string")return t;let e=new URLSearchParams(t),r=new URLSearchParams;for(let[n,i]of e.entries()){if(n=n.replace("[]",""),/^(['"]).*\1$/.test(i)){r.append(n,i);continue}if(i.includes(",")){let s=i.split(",");for(let a of s)r.append(n,a);continue}r.append(n,i)}return r}function Yv(t){if(typeof t!="string")return t;let e=t.split("?",3);if(e.length!==2)return t;let r=new URLSearchParams(e.pop());return r.sort(),[...e,r.toString()].join("?")}function zke(t,{path:e,method:r,body:n,headers:i}){let o=cs(t.path,e),s=cs(t.method,r),a=typeof t.body<"u"?cs(t.body,n):!0,c=wG(t,i);return o&&s&&a&&c}function _G(t){return Buffer.isBuffer(t)||t instanceof Uint8Array||t instanceof ArrayBuffer?t:typeof t=="object"?JSON.stringify(t):t?t.toString():""}function BG(t,e){let r=e.query?Lke(e.path,e.query):e.path,n=typeof r=="string"?Yv(r):r,i=CG(n),o=t.filter(({consumed:s})=>!s).filter(({path:s,ignoreTrailingSlash:a})=>a?cs(CG(Yv(s)),i):cs(Yv(s),n));if(o.length===0)throw new td(`Mock dispatch not matched for path '${n}'`);if(o=o.filter(({method:s})=>cs(s,e.method)),o.length===0)throw new td(`Mock dispatch not matched for method '${e.method}' on path '${n}'`);if(o=o.filter(({body:s})=>typeof s<"u"?cs(s,e.body):!0),o.length===0)throw new td(`Mock dispatch not matched for body '${e.body}' on path '${n}'`);if(o=o.filter(s=>wG(s,e.headers)),o.length===0){let s=typeof e.headers=="object"?JSON.stringify(e.headers):e.headers;throw new td(`Mock dispatch not matched for headers '${s}' on path '${n}'`)}return o[0]}function qke(t,e,r,n){let i={timesInvoked:0,times:1,persist:!1,consumed:!1,...n},o=typeof r=="function"?{callback:r}:{...r},s={...i,...e,pending:!0,data:{error:null,...o}};return t.push(s),t[Vv]=(t[Vv]||0)+1,s}function Wv(t,e){let r=t.findIndex(n=>n.consumed?zke(n,e):!1);r!==-1&&t.splice(r,1)}function CG(t){for(;t.endsWith("/");)t=t.slice(0,-1);return t.length===0&&(t="/"),t}function vG(t){let{path:e,method:r,body:n,headers:i,query:o}=t;return{path:e,method:r,body:n,headers:i,query:o}}function Jv(t){let e=Object.keys(t),r=[];for(let n=0;n<e.length;++n){let i=e[n],o=t[i],s=Buffer.from(`${i}`);if(Array.isArray(o))for(let a=0;a<o.length;++a)r.push(s,Buffer.from(`${o[a]}`));else r.push(s,Buffer.from(`${o}`))}return r}function QG(t){return $ke[t]||"unknown"}async function Hke(t){let e=[];for await(let r of t)e.push(r);return Buffer.concat(e).toString("utf8")}function TG(t,e){let r=vG(t),n=BG(this[pl],r);n.timesInvoked++,n.data.callback&&(n.data={...n.data,...n.data.callback(t)});let{data:{statusCode:i,data:o,headers:s,trailers:a,error:c},delay:l,persist:u}=n,{timesInvoked:d,times:A}=n;if(n.consumed=!u&&d>=A,n.pending=d<A,c!==null)return Wv(this[pl],r),e.onError(c),!0;let p=!1,h=null;function f(B){p||(p=!0,h!==null&&(clearTimeout(h),h=null),e.onError(B))}e.onConnect?.(f,null),typeof l=="number"&&l>0?h=setTimeout(()=>{h=null,E(this[pl])},l):E(this[pl]);function E(B,_=o){if(p)return;let v=Array.isArray(t.headers)?Zv(t.headers):t.headers,T=typeof _=="function"?_({...t,headers:v}):_;if(Fke(T))return T.then(U=>E(B,U));if(p)return;let L=_G(T),k=Jv(s),P=Jv(a);e.onHeaders?.(i,k,S,QG(i)),e.onData?.(Buffer.from(L)),e.onComplete?.(P),Wv(B,r)}function S(){}return!0}function Gke(){let t=this[xke],e=this[Mke],r=this[Uke];return function(i,o){if(t.isMockActive)try{TG.call(this,i,o)}catch(s){if(s.code==="UND_MOCK_ERR_MOCK_NOT_MATCHED"){let a=t[Pke](),c=this[pl][Vv]||this[pl].length,u=`, ${this[pl].filter(({consumed:d})=>!d).length} interceptor(s) remaining out of ${c} defined`;if(a===!1)throw new td(`${s.message}: subsequent request to origin ${e} was not allowed (net.connect disabled)${u}`);if(DG(a,e))r.call(this,i,o);else throw new td(`${s.message}: subsequent request to origin ${e} was not allowed (net.connect is not enabled for this origin)${u}`)}else throw s}else r.call(this,i,o)}}function DG(t,e){let r=new URL(e);return t===!0?!0:!!(Array.isArray(t)&&t.some(n=>cs(n,r.host)))}function Yke(t){return typeof t!="string"&&!(t instanceof URL)?t:t instanceof URL?t.origin:t.toLowerCase()}function Vke(t){let{agent:e,...r}=t;if("enableCallHistory"in r&&typeof r.enableCallHistory!="boolean")throw new Gv("options.enableCallHistory must to be a boolean");if("acceptNonStandardSearchParameters"in r&&typeof r.acceptNonStandardSearchParameters!="boolean")throw new Gv("options.acceptNonStandardSearchParameters must to be a boolean");if("ignoreTrailingSlash"in r&&typeof r.ignoreTrailingSlash!="boolean")throw new Gv("options.ignoreTrailingSlash must to be a boolean");return r}kG.exports={getResponseData:_G,getMockDispatch:BG,addMockDispatch:qke,deleteMockDispatch:Wv,buildKey:vG,generateKeyValues:Jv,matchValue:cs,getResponse:Hke,getStatusText:QG,mockDispatch:TG,buildMockDispatch:Gke,checkNetConnect:DG,buildAndValidateMockOptions:Vke,getHeaderByName:SG,buildHeadersFromArray:Zv,normalizeSearchParams:jke,normalizeOrigin:Yke}});var iQ=y((gqe,nQ)=>{"use strict";var{getResponseData:Wke,buildKey:Jke,addMockDispatch:Kv}=sh(),{kDispatches:kE,kDispatchKey:RE,kDefaultHeaders:Xv,kDefaultTrailers:eQ,kContentLength:tQ,kMockDispatch:NE,kIgnoreTrailingSlash:OE}=Al(),{InvalidArgumentError:ls}=_e(),{serializePathWithQuery:Zke}=De(),rd=class{constructor(e){this[NE]=e}delay(e){if(typeof e!="number"||!Number.isInteger(e)||e<=0)throw new ls("waitInMs must be a valid integer > 0");return this[NE].delay=e,this}persist(){return this[NE].persist=!0,this}times(e){if(typeof e!="number"||!Number.isInteger(e)||e<=0)throw new ls("repeatTimes must be a valid integer > 0");return this[NE].times=e,this}},rQ=class{constructor(e,r){if(typeof e!="object")throw new ls("opts must be an object");if(typeof e.path>"u")throw new ls("opts.path must be defined");if(typeof e.method>"u"&&(e.method="GET"),typeof e.path=="string")if(e.query)e.path=Zke(e.path,e.query);else{let n=new URL(e.path,"data://");e.path=n.pathname+n.search}typeof e.method=="string"&&(e.method=e.method.toUpperCase()),this[RE]=Jke(e),this[kE]=r,this[OE]=e.ignoreTrailingSlash??!1,this[Xv]={},this[eQ]={},this[tQ]=!1}createMockScopeDispatchData({statusCode:e,data:r,responseOptions:n}){let i=Wke(r),o=this[tQ]?{"content-length":i.length}:{},s={...this[Xv],...o,...n.headers},a={...this[eQ],...n.trailers};return{statusCode:e,data:r,headers:s,trailers:a}}validateReplyParameters(e){if(typeof e.statusCode>"u")throw new ls("statusCode must be defined");if(typeof e.responseOptions!="object"||e.responseOptions===null)throw new ls("responseOptions must be an object")}reply(e){if(typeof e=="function"){let o=a=>{let c=e(a);if(typeof c!="object"||c===null)throw new ls("reply options callback must return an object");let l={data:"",responseOptions:{},...c};return this.validateReplyParameters(l),{...this.createMockScopeDispatchData(l)}},s=Kv(this[kE],this[RE],o,{ignoreTrailingSlash:this[OE]});return new rd(s)}let r={statusCode:e,data:arguments[1]===void 0?"":arguments[1],responseOptions:arguments[2]===void 0?{}:arguments[2]};this.validateReplyParameters(r);let n=this.createMockScopeDispatchData(r),i=Kv(this[kE],this[RE],n,{ignoreTrailingSlash:this[OE]});return new rd(i)}replyWithError(e){if(typeof e>"u")throw new ls("error must be defined");let r=Kv(this[kE],this[RE],{error:e},{ignoreTrailingSlash:this[OE]});return new rd(r)}defaultReplyHeaders(e){if(typeof e>"u")throw new ls("headers must be defined");return this[Xv]=e,this}defaultReplyTrailers(e){if(typeof e>"u")throw new ls("trailers must be defined");return this[eQ]=e,this}replyContentLength(){return this[tQ]=!0,this}};nQ.exports.MockInterceptor=rQ;nQ.exports.MockScope=rd});var cQ=y((mqe,PG)=>{"use strict";var{promisify:Kke}=require("util"),Xke=$a(),{buildMockDispatch:eRe}=sh(),{kDispatches:oQ,kMockAgent:RG,kClose:NG,kOriginalClose:OG,kOrigin:xG,kOriginalDispatch:tRe,kConnected:sQ,kIgnoreTrailingSlash:UG}=Al(),{MockInterceptor:rRe}=iQ(),MG=ut(),{InvalidArgumentError:nRe}=_e(),aQ=class extends Xke{constructor(e,r){if(!r||!r.agent||typeof r.agent.dispatch!="function")throw new nRe("Argument opts.agent must implement Agent");super(e,r),this[RG]=r.agent,this[xG]=e,this[UG]=r.ignoreTrailingSlash??!1,this[oQ]=[],this[sQ]=1,this[tRe]=this.dispatch,this[OG]=this.close.bind(this),this.dispatch=eRe.call(this),this.close=this[NG]}get[MG.kConnected](){return this[sQ]}intercept(e){return new rRe(e&&{ignoreTrailingSlash:this[UG],...e},this[oQ])}cleanMocks(){this[oQ]=[]}async[NG](){await Kke(this[OG])(),this[sQ]=0,this[RG][MG.kClients].delete(this[xG])}};PG.exports=aQ});var dQ=y((yqe,uQ)=>{"use strict";var{kMockCallHistoryAddLog:iRe}=Al(),{InvalidArgumentError:Wa}=_e();function Ya(t,e,r,n,i){switch(e.operator){case"OR":return n.push(...r(t,i)),n;case"AND":return r(t,n);default:throw new Wa("options.operator must to be a case insensitive string equal to 'OR' or 'AND'")}}function oRe(t={}){let e={};if("operator"in t){if(typeof t.operator!="string"||t.operator.toUpperCase()!=="OR"&&t.operator.toUpperCase()!=="AND")throw new Wa("options.operator must to be a case insensitive string equal to 'OR' or 'AND'");return{...e,operator:t.operator.toUpperCase()}}return e}function Va(t){return(e,r)=>{if(typeof e=="string"||e==null)return r.filter(n=>n[t]===e);if(e instanceof RegExp)return r.filter(n=>e.test(n[t]));throw new Wa(`${t} parameter should be one of string, regexp, undefined or null`)}}function sRe(t){try{let e=new URL(t.path,t.origin);return e.search.length!==0||(e.search=new URLSearchParams(t.query).toString()),e}catch(e){throw new Wa("An error occurred when computing MockCallHistoryLog.url",{cause:e})}}var xE=class{constructor(e={}){this.body=e.body,this.headers=e.headers,this.method=e.method;let r=sRe(e);this.fullUrl=r.toString(),this.origin=r.origin,this.path=r.pathname,this.searchParams=Object.fromEntries(r.searchParams),this.protocol=r.protocol,this.host=r.host,this.port=r.port,this.hash=r.hash}toMap(){return new Map([["protocol",this.protocol],["host",this.host],["port",this.port],["origin",this.origin],["path",this.path],["hash",this.hash],["searchParams",this.searchParams],["fullUrl",this.fullUrl],["method",this.method],["body",this.body],["headers",this.headers]])}toString(){let e={betweenKeyValueSeparator:"->",betweenPairSeparator:"|"},r="";return this.toMap().forEach((n,i)=>{(typeof n=="string"||n===void 0||n===null)&&(r=`${r}${i}${e.betweenKeyValueSeparator}${n}${e.betweenPairSeparator}`),(typeof n=="object"&&n!==null||Array.isArray(n))&&(r=`${r}${i}${e.betweenKeyValueSeparator}${JSON.stringify(n)}${e.betweenPairSeparator}`)}),r.slice(0,-1)}},lQ=class{logs=[];calls(){return this.logs}firstCall(){return this.logs.at(0)}lastCall(){return this.logs.at(-1)}nthCall(e){if(typeof e!="number")throw new Wa("nthCall must be called with a number");if(!Number.isInteger(e))throw new Wa("nthCall must be called with an integer");if(Math.sign(e)!==1)throw new Wa("nthCall must be called with a positive value. use firstCall or lastCall instead");return this.logs.at(e-1)}filterCalls(e,r){if(this.logs.length===0)return this.logs;if(typeof e=="function")return this.logs.filter(e);if(e instanceof RegExp)return this.logs.filter(n=>e.test(n.toString()));if(typeof e=="object"&&e!==null){if(Object.keys(e).length===0)return this.logs;let n={operator:"OR",...oRe(r)},i=n.operator==="AND"?this.logs:[];return"protocol"in e&&(i=Ya(e.protocol,n,this.filterCallsByProtocol,i,this.logs)),"host"in e&&(i=Ya(e.host,n,this.filterCallsByHost,i,this.logs)),"port"in e&&(i=Ya(e.port,n,this.filterCallsByPort,i,this.logs)),"origin"in e&&(i=Ya(e.origin,n,this.filterCallsByOrigin,i,this.logs)),"path"in e&&(i=Ya(e.path,n,this.filterCallsByPath,i,this.logs)),"hash"in e&&(i=Ya(e.hash,n,this.filterCallsByHash,i,this.logs)),"fullUrl"in e&&(i=Ya(e.fullUrl,n,this.filterCallsByFullUrl,i,this.logs)),"method"in e&&(i=Ya(e.method,n,this.filterCallsByMethod,i,this.logs)),[...new Set(i)]}throw new Wa("criteria parameter should be one of function, regexp, or object")}filterCallsByProtocol=Va.call(this,"protocol");filterCallsByHost=Va.call(this,"host");filterCallsByPort=Va.call(this,"port");filterCallsByOrigin=Va.call(this,"origin");filterCallsByPath=Va.call(this,"path");filterCallsByHash=Va.call(this,"hash");filterCallsByFullUrl=Va.call(this,"fullUrl");filterCallsByMethod=Va.call(this,"method");clear(){this.logs=[]}[iRe](e){let r=new xE(e);return this.logs.push(r),r}*[Symbol.iterator](){for(let e of this.calls())yield e}};uQ.exports.MockCallHistory=lQ;uQ.exports.MockCallHistoryLog=xE});var fQ=y((Eqe,HG)=>{"use strict";var{promisify:aRe}=require("util"),cRe=tl(),{buildMockDispatch:lRe}=sh(),{kDispatches:AQ,kMockAgent:LG,kClose:$G,kOriginalClose:FG,kOrigin:jG,kOriginalDispatch:uRe,kConnected:pQ,kIgnoreTrailingSlash:zG}=Al(),{MockInterceptor:dRe}=iQ(),qG=ut(),{InvalidArgumentError:ARe}=_e(),hQ=class extends cRe{constructor(e,r){if(!r||!r.agent||typeof r.agent.dispatch!="function")throw new ARe("Argument opts.agent must implement Agent");super(e,r),this[LG]=r.agent,this[jG]=e,this[zG]=r.ignoreTrailingSlash??!1,this[AQ]=[],this[pQ]=1,this[uRe]=this.dispatch,this[FG]=this.close.bind(this),this.dispatch=lRe.call(this),this.close=this[$G]}get[qG.kConnected](){return this[pQ]}intercept(e){return new dRe(e&&{ignoreTrailingSlash:this[zG],...e},this[AQ])}cleanMocks(){this[AQ]=[]}async[$G](){await aRe(this[FG])(),this[pQ]=0,this[LG][qG.kClients].delete(this[jG])}};HG.exports=hQ});var YG=y((Cqe,GG)=>{"use strict";var{Transform:pRe}=require("stream"),{Console:hRe}=require("console"),fRe=process.versions.icu?"\u2705":"Y ",gRe=process.versions.icu?"\u274C":"N ";GG.exports=class{constructor({disableColors:e}={}){this.transform=new pRe({transform(r,n,i){i(null,r)}}),this.logger=new hRe({stdout:this.transform,inspectOptions:{colors:!e&&!process.env.CI}})}format(e){let r=e.map(({method:n,path:i,data:{statusCode:o},persist:s,times:a,timesInvoked:c,origin:l})=>({Method:n,Origin:l,Path:i,"Status code":o,Persistent:s?fRe:gRe,Invocations:c,Remaining:s?1/0:a-c}));return this.logger.table(r),this.transform.read().toString()}}});var IQ=y((bqe,eY)=>{"use strict";var{kClients:hl}=ut(),mRe=il(),{kAgent:gQ,kMockAgentSet:UE,kMockAgentGet:VG,kDispatches:mQ,kIsMockActive:ME,kNetConnect:fl,kGetNetConnect:yRe,kOptions:PE,kFactory:LE,kMockAgentRegisterCallHistory:yQ,kMockAgentIsCallHistoryEnabled:ah,kMockAgentAddCallHistoryLog:WG,kMockAgentMockCallHistoryInstance:nd,kMockAgentAcceptsNonStandardSearchParameters:JG,kMockCallHistoryAddLog:ERe,kIgnoreTrailingSlash:ZG}=Al(),IRe=cQ(),CRe=fQ(),{matchValue:bRe,normalizeSearchParams:SRe,buildAndValidateMockOptions:wRe,normalizeOrigin:KG}=sh(),{InvalidArgumentError:XG,UndiciError:_Re}=_e(),BRe=wp(),vRe=YG(),{MockCallHistory:QRe}=dQ(),EQ=class extends BRe{constructor(e={}){super(e);let r=wRe(e);if(this[fl]=!0,this[ME]=!0,this[ah]=r.enableCallHistory??!1,this[JG]=r.acceptNonStandardSearchParameters??!1,this[ZG]=r.ignoreTrailingSlash??!1,e?.agent&&typeof e.agent.dispatch!="function")throw new XG("Argument opts.agent must implement Agent");let n=e?.agent?e.agent:new mRe(e);this[gQ]=n,this[hl]=n[hl],this[PE]=r,this[ah]&&this[yQ]()}get(e){let r=KG(e),n=this[ZG]?r.replace(/\/$/,""):r,i=this[VG](n);return i||(i=this[LE](n),this[UE](n,i)),i}dispatch(e,r){e.origin=KG(e.origin),this.get(e.origin),this[WG](e);let n=this[JG],i={...e};if(n&&i.path){let[o,s]=i.path.split("?"),a=SRe(s,n);i.path=`${o}?${a}`}return this[gQ].dispatch(i,r)}async close(){this.clearCallHistory(),await this[gQ].close(),this[hl].clear()}deactivate(){this[ME]=!1}activate(){this[ME]=!0}enableNetConnect(e){if(typeof e=="string"||typeof e=="function"||e instanceof RegExp)Array.isArray(this[fl])?this[fl].push(e):this[fl]=[e];else if(typeof e>"u")this[fl]=!0;else throw new XG("Unsupported matcher. Must be one of String|Function|RegExp.")}disableNetConnect(){this[fl]=!1}enableCallHistory(){return this[ah]=!0,this}disableCallHistory(){return this[ah]=!1,this}getCallHistory(){return this[nd]}clearCallHistory(){this[nd]!==void 0&&this[nd].clear()}get isMockActive(){return this[ME]}[yQ](){this[nd]===void 0&&(this[nd]=new QRe)}[WG](e){this[ah]&&(this[yQ](),this[nd][ERe](e))}[UE](e,r){this[hl].set(e,{count:0,dispatcher:r})}[LE](e){let r=Object.assign({agent:this},this[PE]);return this[PE]&&this[PE].connections===1?new IRe(e,r):new CRe(e,r)}[VG](e){let r=this[hl].get(e);if(r?.dispatcher)return r.dispatcher;if(typeof e!="string"){let n=this[LE]("http://localhost:9999");return this[UE](e,n),n}for(let[n,i]of Array.from(this[hl]))if(i&&typeof n!="string"&&bRe(n,e)){let o=this[LE](e);return this[UE](e,o),o[mQ]=i.dispatcher[mQ],o}}[yRe](){return this[fl]}pendingInterceptors(){let e=this[hl];return Array.from(e.entries()).flatMap(([r,n])=>n.dispatcher[mQ].map(i=>({...i,origin:r}))).filter(({pending:r})=>r)}assertNoPendingInterceptors({pendingInterceptorsFormatter:e=new vRe}={}){let r=this.pendingInterceptors();if(r.length!==0)throw new _Re(r.length===1?`1 interceptor is pending:
|
|
2132
2132
|
|
|
@@ -2215,13 +2215,13 @@ ${e.format(r)}`.trim())}};eY.exports=EQ});var CQ=y((Sqe,iY)=>{"use strict";var{I
|
|
|
2215
2215
|
ORDER BY cachedAt ASC
|
|
2216
2216
|
LIMIT ?
|
|
2217
2217
|
)
|
|
2218
|
-
`)}close(){this.#n.close()}get(e){KQ(e);let r=this.#p(e);return r?{body:r.body?Buffer.from(r.body.buffer,r.body.byteOffset,r.body.byteLength):void 0,statusCode:r.statusCode,statusMessage:r.statusMessage,headers:r.headers?JSON.parse(r.headers):void 0,etag:r.etag?r.etag:void 0,vary:r.vary?JSON.parse(r.vary):void 0,cacheControlDirectives:r.cacheControlDirectives?JSON.parse(r.cacheControlDirectives):void 0,cachedAt:r.cachedAt,staleAt:r.staleAt,deleteAt:r.deleteAt}:void 0}set(e,r){KQ(e);let n=this.#A(e),i=Array.isArray(r.body)?Buffer.concat(r.body):r.body,o=i?.byteLength;if(o&&o>this.#e)return;let s=this.#p(e,!0);s?this.#o.run(i,r.deleteAt,r.statusCode,r.statusMessage,r.headers?JSON.stringify(r.headers):null,r.etag?r.etag:null,r.cacheControlDirectives?JSON.stringify(r.cacheControlDirectives):null,r.cachedAt,r.staleAt,s.id):(this.#r.run(n,e.method,i,r.deleteAt,r.statusCode,r.statusMessage,r.headers?JSON.stringify(r.headers):null,r.etag?r.etag:null,r.cacheControlDirectives?JSON.stringify(r.cacheControlDirectives):null,r.vary?JSON.stringify(r.vary):null,r.cachedAt,r.staleAt),this.#d())}createWriteStream(e,r){KQ(e),YOe(r);let n=0,i=[],o=this;return new GOe({decodeStrings:!0,write(s,a,c){n+=s.byteLength,n<o.#e?i.push(s):this.destroy(),c()},final(s){o.set(e,{...r,body:i}),s()}})}delete(e){if(typeof e!="object")throw new TypeError(`expected key to be object, got ${typeof e}`);this.#s.run(this.#A(e))}#d(){if(Number.isFinite(this.#t)&&this.size<=this.#t)return 0;{let e=this.#c.run(Date.now()).changes;if(e)return e}{let e=this.#l?.run(Math.max(Math.floor(this.#t*.1),1)).changes;if(e)return e}return 0}get size(){let{total:e}=this.#a.get();return e}#A(e){return`${e.origin}/${e.path}`}#p(e,r=!1){let n=this.#A(e),{headers:i,method:o}=e,s=this.#i.all(n,o);if(s.length===0)return;let a=Date.now();for(let c of s){if(a>=c.deleteAt&&!r)continue;let l=!0;if(c.vary){let u=JSON.parse(c.vary);for(let d in u)if(!VOe(i[d],u[d])){l=!1;break}}if(l)return c}}};function VOe(t,e){if(t==null&&e==null)return!0;if(t==null&&e!=null||t!=null&&e==null)return!1;if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}return t===e}});var Il=y((Gqe,MV)=>{"use strict";var{kConstruct:WOe}=ut(),{kEnumerableProperty:cd}=De(),{iteratorMixin:JOe,isValidHeaderName:hh,isValidHeaderValue:RV}=Qn(),{webidl:He}=Cr(),eT=require("assert"),GE=require("util");function kV(t){return t===10||t===13||t===9||t===32}function NV(t){let e=0,r=t.length;for(;r>e&&kV(t.charCodeAt(r-1));)--r;for(;r>e&&kV(t.charCodeAt(e));)++e;return e===0&&r===t.length?t:t.substring(e,r)}function OV(t,e){if(Array.isArray(e))for(let r=0;r<e.length;++r){let n=e[r];if(n.length!==2)throw He.errors.exception({header:"Headers constructor",message:`expected name/value pair to be length 2, found ${n.length}.`});tT(t,n[0],n[1])}else if(typeof e=="object"&&e!==null){let r=Object.keys(e);for(let n=0;n<r.length;++n)tT(t,r[n],e[r[n]])}else throw He.errors.conversionFailed({prefix:"Headers constructor",argument:"Argument 1",types:["sequence<sequence<ByteString>>","record<ByteString, ByteString>"]})}function tT(t,e,r){if(r=NV(r),hh(e)){if(!RV(r))throw He.errors.invalidArgument({prefix:"Headers.append",value:r,type:"header value"})}else throw He.errors.invalidArgument({prefix:"Headers.append",value:e,type:"header name"});if(UV(t)==="immutable")throw new TypeError("immutable");return VE(t).append(e,r,!1)}function ZOe(t){let e=VE(t);if(!e)return[];if(e.sortedMap)return e.sortedMap;let r=[],n=e.toSortedArray(),i=e.cookies;if(i===null||i.length===1)return e.sortedMap=n;for(let o=0;o<n.length;++o){let{0:s,1:a}=n[o];if(s==="set-cookie")for(let c=0;c<i.length;++c)r.push([s,i[c]]);else r.push([s,a])}return e.sortedMap=r}function xV(t,e){return t[0]<e[0]?-1:1}var YE=class t{cookies=null;sortedMap;headersMap;constructor(e){e instanceof t?(this.headersMap=new Map(e.headersMap),this.sortedMap=e.sortedMap,this.cookies=e.cookies===null?null:[...e.cookies]):(this.headersMap=new Map(e),this.sortedMap=null)}contains(e,r){return this.headersMap.has(r?e:e.toLowerCase())}clear(){this.headersMap.clear(),this.sortedMap=null,this.cookies=null}append(e,r,n){this.sortedMap=null;let i=n?e:e.toLowerCase(),o=this.headersMap.get(i);if(o){let s=i==="cookie"?"; ":", ";this.headersMap.set(i,{name:o.name,value:`${o.value}${s}${r}`})}else this.headersMap.set(i,{name:e,value:r});i==="set-cookie"&&(this.cookies??=[]).push(r)}set(e,r,n){this.sortedMap=null;let i=n?e:e.toLowerCase();i==="set-cookie"&&(this.cookies=[r]),this.headersMap.set(i,{name:e,value:r})}delete(e,r){this.sortedMap=null,r||(e=e.toLowerCase()),e==="set-cookie"&&(this.cookies=null),this.headersMap.delete(e)}get(e,r){return this.headersMap.get(r?e:e.toLowerCase())?.value??null}*[Symbol.iterator](){for(let{0:e,1:{value:r}}of this.headersMap)yield[e,r]}get entries(){let e={};if(this.headersMap.size!==0)for(let{name:r,value:n}of this.headersMap.values())e[r]=n;return e}rawValues(){return this.headersMap.values()}get entriesList(){let e=[];if(this.headersMap.size!==0)for(let{0:r,1:{name:n,value:i}}of this.headersMap)if(r==="set-cookie")for(let o of this.cookies)e.push([n,o]);else e.push([n,i]);return e}toSortedArray(){let e=this.headersMap.size,r=new Array(e);if(e<=32){if(e===0)return r;let n=this.headersMap[Symbol.iterator](),i=n.next().value;r[0]=[i[0],i[1].value],eT(i[1].value!==null);for(let o=1,s=0,a=0,c=0,l=0,u,d;o<e;++o){for(d=n.next().value,u=r[o]=[d[0],d[1].value],eT(u[1]!==null),c=0,a=o;c<a;)l=c+(a-c>>1),r[l][0]<=u[0]?c=l+1:a=l;if(o!==l){for(s=o;s>c;)r[s]=r[--s];r[c]=u}}if(!n.next().done)throw new TypeError("Unreachable");return r}else{let n=0;for(let{0:i,1:{value:o}}of this.headersMap)r[n++]=[i,o],eT(o!==null);return r.sort(xV)}}},Pi=class t{#e;#t;constructor(e=void 0){He.util.markAsUncloneable(this),e!==WOe&&(this.#t=new YE,this.#e="none",e!==void 0&&(e=He.converters.HeadersInit(e,"Headers constructor","init"),OV(this,e)))}append(e,r){He.brandCheck(this,t),He.argumentLengthCheck(arguments,2,"Headers.append");let n="Headers.append";return e=He.converters.ByteString(e,n,"name"),r=He.converters.ByteString(r,n,"value"),tT(this,e,r)}delete(e){if(He.brandCheck(this,t),He.argumentLengthCheck(arguments,1,"Headers.delete"),e=He.converters.ByteString(e,"Headers.delete","name"),!hh(e))throw He.errors.invalidArgument({prefix:"Headers.delete",value:e,type:"header name"});if(this.#e==="immutable")throw new TypeError("immutable");this.#t.contains(e,!1)&&this.#t.delete(e,!1)}get(e){He.brandCheck(this,t),He.argumentLengthCheck(arguments,1,"Headers.get");let r="Headers.get";if(e=He.converters.ByteString(e,r,"name"),!hh(e))throw He.errors.invalidArgument({prefix:r,value:e,type:"header name"});return this.#t.get(e,!1)}has(e){He.brandCheck(this,t),He.argumentLengthCheck(arguments,1,"Headers.has");let r="Headers.has";if(e=He.converters.ByteString(e,r,"name"),!hh(e))throw He.errors.invalidArgument({prefix:r,value:e,type:"header name"});return this.#t.contains(e,!1)}set(e,r){He.brandCheck(this,t),He.argumentLengthCheck(arguments,2,"Headers.set");let n="Headers.set";if(e=He.converters.ByteString(e,n,"name"),r=He.converters.ByteString(r,n,"value"),r=NV(r),hh(e)){if(!RV(r))throw He.errors.invalidArgument({prefix:n,value:r,type:"header value"})}else throw He.errors.invalidArgument({prefix:n,value:e,type:"header name"});if(this.#e==="immutable")throw new TypeError("immutable");this.#t.set(e,r,!1)}getSetCookie(){He.brandCheck(this,t);let e=this.#t.cookies;return e?[...e]:[]}[GE.inspect.custom](e,r){return r.depth??=e,`Headers ${GE.formatWithOptions(r,this.#t.entries)}`}static getHeadersGuard(e){return e.#e}static setHeadersGuard(e,r){e.#e=r}static getHeadersList(e){return e.#t}static setHeadersList(e,r){e.#t=r}},{getHeadersGuard:UV,setHeadersGuard:KOe,getHeadersList:VE,setHeadersList:XOe}=Pi;Reflect.deleteProperty(Pi,"getHeadersGuard");Reflect.deleteProperty(Pi,"setHeadersGuard");Reflect.deleteProperty(Pi,"getHeadersList");Reflect.deleteProperty(Pi,"setHeadersList");JOe("Headers",Pi,ZOe,0,1);Object.defineProperties(Pi.prototype,{append:cd,delete:cd,get:cd,has:cd,set:cd,getSetCookie:cd,[Symbol.toStringTag]:{value:"Headers",configurable:!0},[GE.inspect.custom]:{enumerable:!1}});He.converters.HeadersInit=function(t,e,r){if(He.util.Type(t)===He.util.Types.OBJECT){let n=Reflect.get(t,Symbol.iterator);if(!GE.types.isProxy(t)&&n===Pi.prototype.entries)try{return VE(t).entriesList}catch{}return typeof n=="function"?He.converters["sequence<sequence<ByteString>>"](t,e,r,n.bind(t)):He.converters["record<ByteString, ByteString>"](t,e,r)}throw He.errors.conversionFailed({prefix:"Headers constructor",argument:"Argument 1",types:["sequence<sequence<ByteString>>","record<ByteString, ByteString>"]})};MV.exports={fill:OV,compareHeaderName:xV,Headers:Pi,HeadersList:YE,getHeadersGuard:UV,setHeadersGuard:KOe,setHeadersList:XOe,getHeadersList:VE}});var gh=y((Yqe,WV)=>{"use strict";var{Headers:zV,HeadersList:PV,fill:exe,getHeadersGuard:txe,setHeadersGuard:qV,setHeadersList:HV}=Il(),{extractBody:LV,cloneBody:rxe,mixinBody:nxe,streamRegistry:GV,bodyUnusable:ixe}=$u(),YV=De(),$V=require("util"),{kEnumerableProperty:On}=YV,{isValidReasonPhrase:oxe,isCancelled:sxe,isAborted:axe,isErrorLike:cxe,environmentSettingsObject:lxe}=Qn(),{redirectStatusSet:uxe,nullBodyStatus:dxe}=Bp(),{webidl:ze}=Cr(),{URLSerializer:FV}=ci(),{kConstruct:JE}=ut(),rT=require("assert"),{isomorphicEncode:Axe,serializeJavascriptValueToJSONString:pxe}=Ms(),hxe=new TextEncoder("utf-8"),xn=class t{#e;#t;static error(){return fh(ZE(),"immutable")}static json(e,r=void 0){ze.argumentLengthCheck(arguments,1,"Response.json"),r!==null&&(r=ze.converters.ResponseInit(r));let n=hxe.encode(pxe(e)),i=LV(n),o=fh(ld({}),"response");return jV(o,r,{body:i[0],type:"application/json"}),o}static redirect(e,r=302){ze.argumentLengthCheck(arguments,1,"Response.redirect"),e=ze.converters.USVString(e),r=ze.converters["unsigned short"](r);let n;try{n=new URL(e,lxe.settingsObject.baseUrl)}catch(s){throw new TypeError(`Failed to parse URL from ${e}`,{cause:s})}if(!uxe.has(r))throw new RangeError(`Invalid status code ${r}`);let i=fh(ld({}),"immutable");i.#t.status=r;let o=Axe(FV(n));return i.#t.headersList.append("location",o,!0),i}constructor(e=null,r=void 0){if(ze.util.markAsUncloneable(this),e===JE)return;e!==null&&(e=ze.converters.BodyInit(e,"Response","body")),r=ze.converters.ResponseInit(r),this.#t=ld({}),this.#e=new zV(JE),qV(this.#e,"response"),HV(this.#e,this.#t.headersList);let n=null;if(e!=null){let[i,o]=LV(e);n={body:i,type:o}}jV(this,r,n)}get type(){return ze.brandCheck(this,t),this.#t.type}get url(){ze.brandCheck(this,t);let e=this.#t.urlList,r=e[e.length-1]??null;return r===null?"":FV(r,!0)}get redirected(){return ze.brandCheck(this,t),this.#t.urlList.length>1}get status(){return ze.brandCheck(this,t),this.#t.status}get ok(){return ze.brandCheck(this,t),this.#t.status>=200&&this.#t.status<=299}get statusText(){return ze.brandCheck(this,t),this.#t.statusText}get headers(){return ze.brandCheck(this,t),this.#e}get body(){return ze.brandCheck(this,t),this.#t.body?this.#t.body.stream:null}get bodyUsed(){return ze.brandCheck(this,t),!!this.#t.body&&YV.isDisturbed(this.#t.body.stream)}clone(){if(ze.brandCheck(this,t),ixe(this.#t))throw ze.errors.exception({header:"Response.clone",message:"Body has already been consumed."});let e=nT(this.#t);return this.#t.urlList.length!==0&&this.#t.body?.stream&&GV.register(this,new WeakRef(this.#t.body.stream)),fh(e,txe(this.#e))}[$V.inspect.custom](e,r){r.depth===null&&(r.depth=2),r.colors??=!0;let n={status:this.status,statusText:this.statusText,headers:this.headers,body:this.body,bodyUsed:this.bodyUsed,ok:this.ok,redirected:this.redirected,type:this.type,url:this.url};return`Response ${$V.formatWithOptions(r,n)}`}static getResponseHeaders(e){return e.#e}static setResponseHeaders(e,r){e.#e=r}static getResponseState(e){return e.#t}static setResponseState(e,r){e.#t=r}},{getResponseHeaders:fxe,setResponseHeaders:gxe,getResponseState:Cl,setResponseState:mxe}=xn;Reflect.deleteProperty(xn,"getResponseHeaders");Reflect.deleteProperty(xn,"setResponseHeaders");Reflect.deleteProperty(xn,"getResponseState");Reflect.deleteProperty(xn,"setResponseState");nxe(xn,Cl);Object.defineProperties(xn.prototype,{type:On,url:On,status:On,ok:On,redirected:On,statusText:On,headers:On,clone:On,body:On,bodyUsed:On,[Symbol.toStringTag]:{value:"Response",configurable:!0}});Object.defineProperties(xn,{json:On,redirect:On,error:On});function nT(t){if(t.internalResponse)return VV(nT(t.internalResponse),t.type);let e=ld({...t,body:null});return t.body!=null&&(e.body=rxe(t.body)),e}function ld(t){return{aborted:!1,rangeRequested:!1,timingAllowPassed:!1,requestIncludesCredentials:!1,type:"default",status:200,timingInfo:null,cacheState:"",statusText:"",...t,headersList:t?.headersList?new PV(t?.headersList):new PV,urlList:t?.urlList?[...t.urlList]:[]}}function ZE(t){let e=cxe(t);return ld({type:"error",status:0,error:e?t:new Error(t&&String(t)),aborted:t&&t.name==="AbortError"})}function yxe(t){return t.type==="error"&&t.status===0}function WE(t,e){return e={internalResponse:t,...e},new Proxy(t,{get(r,n){return n in e?e[n]:r[n]},set(r,n,i){return rT(!(n in e)),r[n]=i,!0}})}function VV(t,e){if(e==="basic")return WE(t,{type:"basic",headersList:t.headersList});if(e==="cors")return WE(t,{type:"cors",headersList:t.headersList});if(e==="opaque")return WE(t,{type:"opaque",urlList:[],status:0,statusText:"",body:null});if(e==="opaqueredirect")return WE(t,{type:"opaqueredirect",status:0,statusText:"",headersList:[],body:null});rT(!1)}function Exe(t,e=null){return rT(sxe(t)),axe(t)?ZE(Object.assign(new DOMException("The operation was aborted.","AbortError"),{cause:e})):ZE(Object.assign(new DOMException("Request was cancelled."),{cause:e}))}function jV(t,e,r){if(e.status!==null&&(e.status<200||e.status>599))throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.');if("statusText"in e&&e.statusText!=null&&!oxe(String(e.statusText)))throw new TypeError("Invalid statusText");if("status"in e&&e.status!=null&&(Cl(t).status=e.status),"statusText"in e&&e.statusText!=null&&(Cl(t).statusText=e.statusText),"headers"in e&&e.headers!=null&&exe(fxe(t),e.headers),r){if(dxe.includes(t.status))throw ze.errors.exception({header:"Response constructor",message:`Invalid response status code ${t.status}`});Cl(t).body=r.body,r.type!=null&&!Cl(t).headersList.contains("content-type",!0)&&Cl(t).headersList.append("content-type",r.type,!0)}}function fh(t,e){let r=new xn(JE);mxe(r,t);let n=new zV(JE);return gxe(r,n),HV(n,t.headersList),qV(n,e),t.urlList.length!==0&&t.body?.stream&&GV.register(r,new WeakRef(t.body.stream)),r}ze.converters.XMLHttpRequestBodyInit=function(t,e,r){return typeof t=="string"?ze.converters.USVString(t,e,r):ze.is.Blob(t)||ze.is.BufferSource(t)||ze.is.FormData(t)||ze.is.URLSearchParams(t)?t:ze.converters.DOMString(t,e,r)};ze.converters.BodyInit=function(t,e,r){return ze.is.ReadableStream(t)||t?.[Symbol.asyncIterator]?t:ze.converters.XMLHttpRequestBodyInit(t,e,r)};ze.converters.ResponseInit=ze.dictionaryConverter([{key:"status",converter:ze.converters["unsigned short"],defaultValue:()=>200},{key:"statusText",converter:ze.converters.ByteString,defaultValue:()=>""},{key:"headers",converter:ze.converters.HeadersInit}]);ze.is.Response=ze.util.MakeTypeAssertion(xn);WV.exports={isNetworkError:yxe,makeNetworkError:ZE,makeResponse:ld,makeAppropriateNetworkError:Exe,filterResponse:VV,Response:xn,cloneResponse:nT,fromInnerResponse:fh,getResponseState:Cl}});var ud=y((Vqe,l4)=>{"use strict";var{extractBody:Ixe,mixinBody:Cxe,cloneBody:bxe,bodyUnusable:JV}=$u(),{Headers:r4,fill:Sxe,HeadersList:eI,setHeadersGuard:iT,getHeadersGuard:wxe,setHeadersList:n4,getHeadersList:ZV}=Il(),XE=De(),KV=require("util"),{isValidHTTPToken:_xe,sameOrigin:XV,environmentSettingsObject:KE}=Qn(),{forbiddenMethodsSet:Bxe,corsSafeListedMethodsSet:vxe,referrerPolicy:Qxe,requestRedirect:Txe,requestMode:Dxe,requestCredentials:kxe,requestCache:Rxe,requestDuplex:Nxe}=Bp(),{kEnumerableProperty:er,normalizedMethodRecordsBase:Oxe,normalizedMethodRecords:xxe}=XE,{webidl:Se}=Cr(),{URLSerializer:Uxe}=ci(),{kConstruct:tI}=ut(),Mxe=require("assert"),{getMaxListeners:i4,setMaxListeners:Pxe,defaultMaxListeners:Lxe}=require("events"),$xe=Symbol("abortController"),o4=new FinalizationRegistry(({signal:t,abort:e})=>{t.removeEventListener("abort",e)}),rI=new WeakMap,oT;try{oT=i4(new AbortController().signal)>0}catch{oT=!1}function e4(t){return e;function e(){let r=t.deref();if(r!==void 0){o4.unregister(e),this.removeEventListener("abort",e),r.abort(this.reason);let n=rI.get(r.signal);if(n!==void 0){if(n.size!==0){for(let i of n){let o=i.deref();o!==void 0&&o.abort(this.reason)}n.clear()}rI.delete(r.signal)}}}}var t4=!1,sn=class t{#e;#t;#n;#i;constructor(e,r=void 0){if(Se.util.markAsUncloneable(this),e===tI)return;Se.argumentLengthCheck(arguments,1,"Request constructor"),e=Se.converters.RequestInfo(e),r=Se.converters.RequestInit(r);let i=null,o=null,s=KE.settingsObject.baseUrl,a=null;if(typeof e=="string"){this.#t=r.dispatcher;let S;try{S=new URL(e,s)}catch(B){throw new TypeError("Failed to parse URL from "+e,{cause:B})}if(S.username||S.password)throw new TypeError("Request cannot be constructed from a URL that includes credentials: "+e);i=nI({urlList:[S]}),o="cors"}else Mxe(Se.is.Request(e)),i=e.#i,a=e.#e,this.#t=r.dispatcher||e.#t;let c=KE.settingsObject.origin,l="client";if(i.window?.constructor?.name==="EnvironmentSettingsObject"&&XV(i.window,c)&&(l=i.window),r.window!=null)throw new TypeError(`'window' option '${l}' must be null`);"window"in r&&(l="no-window"),i=nI({method:i.method,headersList:i.headersList,unsafeRequest:i.unsafeRequest,client:KE.settingsObject,window:l,priority:i.priority,origin:i.origin,referrer:i.referrer,referrerPolicy:i.referrerPolicy,mode:i.mode,credentials:i.credentials,cache:i.cache,redirect:i.redirect,integrity:i.integrity,keepalive:i.keepalive,reloadNavigation:i.reloadNavigation,historyNavigation:i.historyNavigation,urlList:[...i.urlList]});let u=Object.keys(r).length!==0;if(u&&(i.mode==="navigate"&&(i.mode="same-origin"),i.reloadNavigation=!1,i.historyNavigation=!1,i.origin="client",i.referrer="client",i.referrerPolicy="",i.url=i.urlList[i.urlList.length-1],i.urlList=[i.url]),r.referrer!==void 0){let S=r.referrer;if(S==="")i.referrer="no-referrer";else{let B;try{B=new URL(S,s)}catch(_){throw new TypeError(`Referrer "${S}" is not a valid URL.`,{cause:_})}B.protocol==="about:"&&B.hostname==="client"||c&&!XV(B,KE.settingsObject.baseUrl)?i.referrer="client":i.referrer=B}}r.referrerPolicy!==void 0&&(i.referrerPolicy=r.referrerPolicy);let d;if(r.mode!==void 0?d=r.mode:d=o,d==="navigate")throw Se.errors.exception({header:"Request constructor",message:"invalid request mode navigate."});if(d!=null&&(i.mode=d),r.credentials!==void 0&&(i.credentials=r.credentials),r.cache!==void 0&&(i.cache=r.cache),i.cache==="only-if-cached"&&i.mode!=="same-origin")throw new TypeError("'only-if-cached' can be set only with 'same-origin' mode");if(r.redirect!==void 0&&(i.redirect=r.redirect),r.integrity!=null&&(i.integrity=String(r.integrity)),r.keepalive!==void 0&&(i.keepalive=!!r.keepalive),r.method!==void 0){let S=r.method,B=xxe[S];if(B!==void 0)i.method=B;else{if(!_xe(S))throw new TypeError(`'${S}' is not a valid HTTP method.`);let _=S.toUpperCase();if(Bxe.has(_))throw new TypeError(`'${S}' HTTP method is unsupported.`);S=Oxe[_]??S,i.method=S}!t4&&i.method==="patch"&&(process.emitWarning("Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.",{code:"UNDICI-FETCH-patch"}),t4=!0)}r.signal!==void 0&&(a=r.signal),this.#i=i;let A=new AbortController;if(this.#e=A.signal,a!=null)if(a.aborted)A.abort(a.reason);else{this[$xe]=A;let S=new WeakRef(A),B=e4(S);oT&&i4(a)===Lxe&&Pxe(1500,a),XE.addAbortListener(a,B),o4.register(A,{signal:a,abort:B},B)}if(this.#n=new r4(tI),n4(this.#n,i.headersList),iT(this.#n,"request"),d==="no-cors"){if(!vxe.has(i.method))throw new TypeError(`'${i.method} is unsupported in no-cors mode.`);iT(this.#n,"request-no-cors")}if(u){let S=ZV(this.#n),B=r.headers!==void 0?r.headers:new eI(S);if(S.clear(),B instanceof eI){for(let{name:_,value:v}of B.rawValues())S.append(_,v,!1);S.cookies=B.cookies}else Sxe(this.#n,B)}let p=Se.is.Request(e)?e.#i.body:null;if((r.body!=null||p!=null)&&(i.method==="GET"||i.method==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body.");let h=null;if(r.body!=null){let[S,B]=Ixe(r.body,i.keepalive);h=S,B&&!ZV(this.#n).contains("content-type",!0)&&this.#n.append("content-type",B,!0)}let f=h??p;if(f!=null&&f.source==null){if(h!=null&&r.duplex==null)throw new TypeError("RequestInit: duplex option is required when sending a body.");if(i.mode!=="same-origin"&&i.mode!=="cors")throw new TypeError('If request is made from ReadableStream, mode should be "same-origin" or "cors"');i.useCORSPreflightFlag=!0}let E=f;if(h==null&&p!=null){if(JV(e.#i))throw new TypeError("Cannot construct a Request with a Request object that has already been used.");let S=new TransformStream;p.stream.pipeThrough(S),E={source:p.source,length:p.length,stream:S.readable}}this.#i.body=E}get method(){return Se.brandCheck(this,t),this.#i.method}get url(){return Se.brandCheck(this,t),Uxe(this.#i.url)}get headers(){return Se.brandCheck(this,t),this.#n}get destination(){return Se.brandCheck(this,t),this.#i.destination}get referrer(){return Se.brandCheck(this,t),this.#i.referrer==="no-referrer"?"":this.#i.referrer==="client"?"about:client":this.#i.referrer.toString()}get referrerPolicy(){return Se.brandCheck(this,t),this.#i.referrerPolicy}get mode(){return Se.brandCheck(this,t),this.#i.mode}get credentials(){return Se.brandCheck(this,t),this.#i.credentials}get cache(){return Se.brandCheck(this,t),this.#i.cache}get redirect(){return Se.brandCheck(this,t),this.#i.redirect}get integrity(){return Se.brandCheck(this,t),this.#i.integrity}get keepalive(){return Se.brandCheck(this,t),this.#i.keepalive}get isReloadNavigation(){return Se.brandCheck(this,t),this.#i.reloadNavigation}get isHistoryNavigation(){return Se.brandCheck(this,t),this.#i.historyNavigation}get signal(){return Se.brandCheck(this,t),this.#e}get body(){return Se.brandCheck(this,t),this.#i.body?this.#i.body.stream:null}get bodyUsed(){return Se.brandCheck(this,t),!!this.#i.body&&XE.isDisturbed(this.#i.body.stream)}get duplex(){return Se.brandCheck(this,t),"half"}clone(){if(Se.brandCheck(this,t),JV(this.#i))throw new TypeError("unusable");let e=a4(this.#i),r=new AbortController;if(this.signal.aborted)r.abort(this.signal.reason);else{let n=rI.get(this.signal);n===void 0&&(n=new Set,rI.set(this.signal,n));let i=new WeakRef(r);n.add(i),XE.addAbortListener(r.signal,e4(i))}return c4(e,this.#t,r.signal,wxe(this.#n))}[KV.inspect.custom](e,r){r.depth===null&&(r.depth=2),r.colors??=!0;let n={method:this.method,url:this.url,headers:this.headers,destination:this.destination,referrer:this.referrer,referrerPolicy:this.referrerPolicy,mode:this.mode,credentials:this.credentials,cache:this.cache,redirect:this.redirect,integrity:this.integrity,keepalive:this.keepalive,isReloadNavigation:this.isReloadNavigation,isHistoryNavigation:this.isHistoryNavigation,signal:this.signal};return`Request ${KV.formatWithOptions(r,n)}`}static setRequestSignal(e,r){return e.#e=r,e}static getRequestDispatcher(e){return e.#t}static setRequestDispatcher(e,r){e.#t=r}static setRequestHeaders(e,r){e.#n=r}static getRequestState(e){return e.#i}static setRequestState(e,r){e.#i=r}},{setRequestSignal:Fxe,getRequestDispatcher:jxe,setRequestDispatcher:zxe,setRequestHeaders:qxe,getRequestState:s4,setRequestState:Hxe}=sn;Reflect.deleteProperty(sn,"setRequestSignal");Reflect.deleteProperty(sn,"getRequestDispatcher");Reflect.deleteProperty(sn,"setRequestDispatcher");Reflect.deleteProperty(sn,"setRequestHeaders");Reflect.deleteProperty(sn,"getRequestState");Reflect.deleteProperty(sn,"setRequestState");Cxe(sn,s4);function nI(t){return{method:t.method??"GET",localURLsOnly:t.localURLsOnly??!1,unsafeRequest:t.unsafeRequest??!1,body:t.body??null,client:t.client??null,reservedClient:t.reservedClient??null,replacesClientId:t.replacesClientId??"",window:t.window??"client",keepalive:t.keepalive??!1,serviceWorkers:t.serviceWorkers??"all",initiator:t.initiator??"",destination:t.destination??"",priority:t.priority??null,origin:t.origin??"client",policyContainer:t.policyContainer??"client",referrer:t.referrer??"client",referrerPolicy:t.referrerPolicy??"",mode:t.mode??"no-cors",useCORSPreflightFlag:t.useCORSPreflightFlag??!1,credentials:t.credentials??"same-origin",useCredentials:t.useCredentials??!1,cache:t.cache??"default",redirect:t.redirect??"follow",integrity:t.integrity??"",cryptoGraphicsNonceMetadata:t.cryptoGraphicsNonceMetadata??"",parserMetadata:t.parserMetadata??"",reloadNavigation:t.reloadNavigation??!1,historyNavigation:t.historyNavigation??!1,userActivation:t.userActivation??!1,taintedOrigin:t.taintedOrigin??!1,redirectCount:t.redirectCount??0,responseTainting:t.responseTainting??"basic",preventNoCacheCacheControlHeaderModification:t.preventNoCacheCacheControlHeaderModification??!1,done:t.done??!1,timingAllowFailed:t.timingAllowFailed??!1,useURLCredentials:t.useURLCredentials??void 0,traversableForUserPrompts:t.traversableForUserPrompts??"client",urlList:t.urlList,url:t.urlList[0],headersList:t.headersList?new eI(t.headersList):new eI}}function a4(t){let e=nI({...t,body:null});return t.body!=null&&(e.body=bxe(t.body)),e}function c4(t,e,r,n){let i=new sn(tI);Hxe(i,t),zxe(i,e),Fxe(i,r);let o=new r4(tI);return qxe(i,o),n4(o,t.headersList),iT(o,n),i}Object.defineProperties(sn.prototype,{method:er,url:er,headers:er,redirect:er,clone:er,signal:er,duplex:er,destination:er,body:er,bodyUsed:er,isHistoryNavigation:er,isReloadNavigation:er,keepalive:er,integrity:er,cache:er,credentials:er,attribute:er,referrerPolicy:er,referrer:er,mode:er,[Symbol.toStringTag]:{value:"Request",configurable:!0}});Se.is.Request=Se.util.MakeTypeAssertion(sn);Se.converters.RequestInfo=function(t){return typeof t=="string"?Se.converters.USVString(t):Se.is.Request(t)?t:Se.converters.USVString(t)};Se.converters.RequestInit=Se.dictionaryConverter([{key:"method",converter:Se.converters.ByteString},{key:"headers",converter:Se.converters.HeadersInit},{key:"body",converter:Se.nullableConverter(Se.converters.BodyInit)},{key:"referrer",converter:Se.converters.USVString},{key:"referrerPolicy",converter:Se.converters.DOMString,allowedValues:Qxe},{key:"mode",converter:Se.converters.DOMString,allowedValues:Dxe},{key:"credentials",converter:Se.converters.DOMString,allowedValues:kxe},{key:"cache",converter:Se.converters.DOMString,allowedValues:Rxe},{key:"redirect",converter:Se.converters.DOMString,allowedValues:Txe},{key:"integrity",converter:Se.converters.DOMString},{key:"keepalive",converter:Se.converters.boolean},{key:"signal",converter:Se.nullableConverter(t=>Se.converters.AbortSignal(t,"RequestInit","signal"))},{key:"window",converter:Se.converters.any},{key:"duplex",converter:Se.converters.DOMString,allowedValues:Nxe},{key:"dispatcher",converter:Se.converters.any},{key:"priority",converter:Se.converters.DOMString,allowedValues:["high","low","auto"],defaultValue:()=>"auto"}]);l4.exports={Request:sn,makeRequest:nI,fromInnerRequest:c4,cloneRequest:a4,getRequestDispatcher:jxe,getRequestState:s4}});var m4=y((Wqe,g4)=>{"use strict";var Gxe=require("assert"),{runtimeFeatures:d4}=Ps(),bl=new Map([["sha256",0],["sha384",1],["sha512",2]]),sT;if(d4.has("crypto")){sT=require("crypto");let t=sT.getHashes();t.length===0&&bl.clear();for(let e of bl.keys())t.includes(e)===!1&&bl.delete(e)}else bl.clear();var u4=Map.prototype.get.bind(bl),aT=Map.prototype.has.bind(bl),Yxe=d4.has("crypto")===!1||bl.size===0?()=>!0:(t,e)=>{let r=p4(e);if(r.length===0)return!0;let n=A4(r);for(let i of n){let o=i.alg,s=i.val,a=h4(o,t);if(f4(a,s))return!0}return!1};function A4(t){let e=[],r=null;for(let n of t){if(Gxe(aT(n.alg),"Invalid SRI hash algorithm token"),e.length===0){e.push(n),r=n;continue}let i=r.alg,o=u4(i),s=n.alg,a=u4(s);a<o||(a>o?(r=n,e[0]=n,e.length=1):e.push(n))}return e}function p4(t){let e=[];for(let r of t.split(" ")){let i=r.split("?",1)[0],o="",s=[i.slice(0,6),i.slice(7)],a=s[0];if(!aT(a))continue;s[1]&&(o=s[1]);let c={alg:a,val:o};e.push(c)}return e}var h4=(t,e)=>sT.hash(t,e,"base64");function f4(t,e){let r=t.length;r!==0&&t[r-1]==="="&&(r-=1),r!==0&&t[r-1]==="="&&(r-=1);let n=e.length;if(n!==0&&e[n-1]==="="&&(n-=1),n!==0&&e[n-1]==="="&&(n-=1),r!==n)return!1;for(let i=0;i<r;++i)if(!(t[i]===e[i]||t[i]==="+"&&e[i]==="-"||t[i]==="/"&&e[i]==="_"))return!1;return!0}g4.exports={applyAlgorithmToBytes:h4,bytesMatch:Yxe,caseSensitiveMatch:f4,isValidSRIHashAlgorithm:aT,getStrongestMetadata:A4,parseMetadata:p4}});var Eh=y((Jqe,k4)=>{"use strict";var{makeNetworkError:At,makeAppropriateNetworkError:mh,filterResponse:cT,makeResponse:iI,fromInnerResponse:Vxe,getResponseState:Wxe}=gh(),{HeadersList:lT}=Il(),{Request:Jxe,cloneRequest:Zxe,getRequestDispatcher:Kxe,getRequestState:Xxe}=ud(),Li=require("zlib"),{makePolicyContainer:eUe,clonePolicyContainer:tUe,requestBadPort:rUe,TAOCheck:nUe,appendRequestOriginHeader:iUe,responseLocationURL:oUe,requestCurrentURL:Un,setRequestReferrerPolicyOnRedirect:sUe,tryUpgradeRequestToAPotentiallyTrustworthyURL:aUe,createOpaqueTimingInfo:fT,appendFetchMetadata:cUe,corsCheck:lUe,crossOriginResourcePolicyCheck:uUe,determineRequestsReferrer:dUe,coarsenedSharedCurrentTime:yh,sameOrigin:pT,isCancelled:Ja,isAborted:y4,isErrorLike:AUe,fullyReadBody:pUe,readableStreamClose:hUe,urlIsLocal:fUe,urlIsHttpHttpsScheme:cI,urlHasHttpsScheme:gUe,clampAndCoarsenConnectionTimingInfo:mUe,simpleRangeHeaderValue:yUe,buildContentRange:EUe,createInflate:IUe,extractMimeType:CUe,hasAuthenticationEntry:bUe,includesCredentials:E4,isTraversableNavigable:SUe}=Qn(),Sl=require("assert"),{safelyExtractBody:lI,extractBody:I4}=$u(),{redirectStatusSet:w4,nullBodyStatus:_4,safeMethodsSet:wUe,requestBodyHeader:_Ue,subresourceSet:BUe}=Bp(),vUe=require("events"),{Readable:QUe,pipeline:TUe,finished:DUe,isErrored:kUe,isReadable:oI}=require("stream"),{addAbortListener:RUe,bufferToLowerCasedHeaderName:C4}=De(),{dataURLProcessor:NUe,serializeAMimeType:OUe,minimizeSupportedMimeType:xUe}=ci(),{getGlobalDispatcher:UUe}=FE(),{webidl:gT}=Cr(),{STATUS_CODES:b4}=require("http"),{bytesMatch:MUe}=m4(),{createDeferredPromise:PUe}=kp(),{isomorphicEncode:sI}=Ms(),{runtimeFeatures:LUe}=Ps(),$Ue=LUe.has("zstd"),FUe=["GET","HEAD"],jUe=typeof __UNDICI_IS_NODE__<"u"||typeof esbuildDetection<"u"?"node":"undici",uT,aI=class extends vUe{constructor(e){super(),this.dispatcher=e,this.connection=null,this.dump=!1,this.state="ongoing"}terminate(e){this.state==="ongoing"&&(this.state="terminated",this.connection?.destroy(e),this.emit("terminated",e))}abort(e){this.state==="ongoing"&&(this.state="aborted",e||(e=new DOMException("The operation was aborted.","AbortError")),this.serializedAbortReason=e,this.connection?.destroy(e),this.emit("terminated",e))}};function zUe(t){B4(t,"fetch")}function qUe(t,e=void 0){gT.argumentLengthCheck(arguments,1,"globalThis.fetch");let r=PUe(),n;try{n=new Jxe(t,e)}catch(u){return r.reject(u),r.promise}let i=Xxe(n);if(n.signal.aborted)return dT(r,i,null,n.signal.reason,null),r.promise;i.client.globalObject?.constructor?.name==="ServiceWorkerGlobalScope"&&(i.serviceWorkers="none");let s=null,a=!1,c=null;return RUe(n.signal,()=>{a=!0,Sl(c!=null),c.abort(n.signal.reason);let u=s?.deref();dT(r,i,u,n.signal.reason,c.controller)}),c=Q4({request:i,processResponseEndOfBody:zUe,processResponse:u=>{if(!a){if(u.aborted){dT(r,i,s,c.serializedAbortReason,c.controller);return}if(u.type==="error"){r.reject(new TypeError("fetch failed",{cause:u.error}));return}s=new WeakRef(Vxe(u,"immutable")),r.resolve(s.deref()),r=null}},dispatcher:Kxe(n),requestObject:n}),r.promise}function B4(t,e="other"){if(t.type==="error"&&t.aborted||!t.urlList?.length)return;let r=t.urlList[0],n=t.timingInfo,i=t.cacheState;cI(r)&&n!==null&&(t.timingAllowPassed||(n=fT({startTime:n.startTime}),i=""),n.endTime=yh(),t.timingInfo=n,v4(n,r.href,e,globalThis,i,"",t.status))}var v4=performance.markResourceTiming;function dT(t,e,r,n,i){if(t&&t.reject(n),e.body?.stream!=null&&oI(e.body.stream)&&e.body.stream.cancel(n).catch(s=>{if(s.code!=="ERR_INVALID_STATE")throw s}),r==null)return;let o=Wxe(r);o.body?.stream!=null&&oI(o.body.stream)&&i.error(n)}function Q4({request:t,processRequestBodyChunkLength:e,processRequestEndOfBody:r,processResponse:n,processResponseEndOfBody:i,processResponseConsumeBody:o,useParallelQueue:s=!1,dispatcher:a=UUe(),requestObject:c=null}){Sl(a);let l=null,u=!1;t.client!=null&&(l=t.client.globalObject,u=t.client.crossOriginIsolatedCapability);let d=yh(u),A=fT({startTime:d}),p={controller:new aI(a),request:t,timingInfo:A,processRequestBodyChunkLength:e,processRequestEndOfBody:r,processResponse:n,processResponseConsumeBody:o,processResponseEndOfBody:i,taskDestination:l,crossOriginIsolatedCapability:u,requestObject:c};return Sl(!t.body||t.body.stream),t.window==="client"&&(t.window=t.client?.globalObject?.constructor?.name==="Window"?t.client:"no-window"),t.origin==="client"&&(t.origin=t.client.origin),t.policyContainer==="client"&&(t.client!=null?t.policyContainer=tUe(t.client.policyContainer):t.policyContainer=eUe()),t.headersList.contains("accept",!0)||t.headersList.append("accept","*/*",!0),t.headersList.contains("accept-language",!0)||t.headersList.append("accept-language","*",!0),t.priority,BUe.has(t.destination),T4(p,!1),p.controller}async function T4(t,e){try{let r=t.request,n=null;if(r.localURLsOnly&&!fUe(Un(r))&&(n=At("local URLs only")),aUe(r),rUe(r)==="blocked"&&(n=At("bad port")),r.referrerPolicy===""&&(r.referrerPolicy=r.policyContainer.referrerPolicy),r.referrer!=="no-referrer"&&(r.referrer=dUe(r)),n===null){let o=Un(r);pT(o,r.url)&&r.responseTainting==="basic"||o.protocol==="data:"||r.mode==="navigate"||r.mode==="websocket"?(r.responseTainting="basic",n=await S4(t)):r.mode==="same-origin"?n=At('request mode cannot be "same-origin"'):r.mode==="no-cors"?r.redirect!=="follow"?n=At('redirect mode cannot be "follow" for "no-cors" request'):(r.responseTainting="opaque",n=await S4(t)):cI(Un(r))?(r.responseTainting="cors",n=await D4(t)):n=At("URL scheme must be a HTTP(S) scheme")}if(e)return n;n.status!==0&&!n.internalResponse&&(r.responseTainting,r.responseTainting==="basic"?n=cT(n,"basic"):r.responseTainting==="cors"?n=cT(n,"cors"):r.responseTainting==="opaque"?n=cT(n,"opaque"):Sl(!1));let i=n.status===0?n:n.internalResponse;if(i.urlList.length===0&&i.urlList.push(...r.urlList),r.timingAllowFailed||(n.timingAllowPassed=!0),n.type==="opaque"&&i.status===206&&i.rangeRequested&&!r.headers.contains("range",!0)&&(n=i=At()),n.status!==0&&(r.method==="HEAD"||r.method==="CONNECT"||_4.includes(i.status))&&(i.body=null,t.controller.dump=!0),r.integrity){let o=a=>AT(t,At(a));if(r.responseTainting==="opaque"||n.body==null){o(n.error);return}let s=a=>{if(!MUe(a,r.integrity)){o("integrity mismatch");return}n.body=lI(a)[0],AT(t,n)};pUe(n.body,s,o)}else AT(t,n)}catch(r){t.controller.terminate(r)}}function S4(t){if(Ja(t)&&t.request.redirectCount===0)return Promise.resolve(mh(t));let{request:e}=t,{protocol:r}=Un(e);switch(r){case"about:":return Promise.resolve(At("about scheme is not supported"));case"blob:":{uT||(uT=require("buffer").resolveObjectURL);let n=Un(e);if(n.search.length!==0)return Promise.resolve(At("NetworkError when attempting to fetch resource."));let i=uT(n.toString());if(e.method!=="GET"||!gT.is.Blob(i))return Promise.resolve(At("invalid method"));let o=iI(),s=i.size,a=sI(`${s}`),c=i.type;if(e.headersList.contains("range",!0)){o.rangeRequested=!0;let l=e.headersList.get("range",!0),u=yUe(l,!0);if(u==="failure")return Promise.resolve(At("failed to fetch the data URL"));let{rangeStartValue:d,rangeEndValue:A}=u;if(d===null)d=s-A,A=d+A-1;else{if(d>=s)return Promise.resolve(At("Range start is greater than the blob's size."));(A===null||A>=s)&&(A=s-1)}let p=i.slice(d,A+1,c),h=I4(p);o.body=h[0];let f=sI(`${p.size}`),E=EUe(d,A,s);o.status=206,o.statusText="Partial Content",o.headersList.set("content-length",f,!0),o.headersList.set("content-type",c,!0),o.headersList.set("content-range",E,!0)}else{let l=I4(i);o.statusText="OK",o.body=l[0],o.headersList.set("content-length",a,!0),o.headersList.set("content-type",c,!0)}return Promise.resolve(o)}case"data:":{let n=Un(e),i=NUe(n);if(i==="failure")return Promise.resolve(At("failed to fetch the data URL"));let o=OUe(i.mimeType);return Promise.resolve(iI({statusText:"OK",headersList:[["content-type",{name:"Content-Type",value:o}]],body:lI(i.body)[0]}))}case"file:":return Promise.resolve(At("not implemented... yet..."));case"http:":case"https:":return D4(t).catch(n=>At(n));default:return Promise.resolve(At("unknown scheme"))}}function HUe(t,e){t.request.done=!0,t.processResponseDone!=null&&queueMicrotask(()=>t.processResponseDone(e))}function AT(t,e){let r=t.timingInfo,n=()=>{let o=Date.now();t.request.destination==="document"&&(t.controller.fullTimingInfo=r),t.controller.reportTimingSteps=()=>{if(!cI(t.request.url))return;r.endTime=o;let a=e.cacheState,c=e.bodyInfo;e.timingAllowPassed||(r=fT(r),a="");let l=0;if(t.request.mode!=="navigate"||!e.hasCrossOriginRedirects){l=e.status;let u=CUe(e.headersList);u!=="failure"&&(c.contentType=xUe(u))}t.request.initiatorType!=null&&v4(r,t.request.url.href,t.request.initiatorType,globalThis,a,c,l)};let s=()=>{t.request.done=!0,t.processResponseEndOfBody!=null&&queueMicrotask(()=>t.processResponseEndOfBody(e)),t.request.initiatorType!=null&&t.controller.reportTimingSteps()};queueMicrotask(()=>s())};t.processResponse!=null&&queueMicrotask(()=>{t.processResponse(e),t.processResponse=null});let i=e.type==="error"?e:e.internalResponse??e;i.body==null?n():DUe(i.body.stream,()=>{n()})}async function D4(t){let e=t.request,r=null,n=null,i=t.timingInfo;if(e.serviceWorkers,r===null){if(e.redirect==="follow"&&(e.serviceWorkers="none"),n=r=await hT(t),e.responseTainting==="cors"&&lUe(e,r)==="failure")return At("cors failure");nUe(e,r)==="failure"&&(e.timingAllowFailed=!0)}return(e.responseTainting==="opaque"||r.type==="opaque")&&uUe(e.origin,e.client,e.destination,n)==="blocked"?At("blocked"):(w4.has(n.status)&&(e.redirect!=="manual"&&t.controller.connection.destroy(void 0,!1),e.redirect==="error"?r=At("unexpected redirect"):e.redirect==="manual"?r=n:e.redirect==="follow"?r=await GUe(t,r):Sl(!1)),r.timingInfo=i,r)}function GUe(t,e){let r=t.request,n=e.internalResponse?e.internalResponse:e,i;try{if(i=oUe(n,Un(r).hash),i==null)return e}catch(s){return Promise.resolve(At(s))}if(!cI(i))return Promise.resolve(At("URL scheme must be a HTTP(S) scheme"));if(r.redirectCount===20)return Promise.resolve(At("redirect count exceeded"));if(r.redirectCount+=1,r.mode==="cors"&&(i.username||i.password)&&!pT(r,i))return Promise.resolve(At('cross origin not allowed for request mode "cors"'));if(r.responseTainting==="cors"&&(i.username||i.password))return Promise.resolve(At('URL cannot contain credentials for request mode "cors"'));if(n.status!==303&&r.body!=null&&r.body.source==null)return Promise.resolve(At());if([301,302].includes(n.status)&&r.method==="POST"||n.status===303&&!FUe.includes(r.method)){r.method="GET",r.body=null;for(let s of _Ue)r.headersList.delete(s)}pT(Un(r),i)||(r.headersList.delete("authorization",!0),r.headersList.delete("proxy-authorization",!0),r.headersList.delete("cookie",!0),r.headersList.delete("host",!0)),r.body!=null&&(Sl(r.body.source!=null),r.body=lI(r.body.source)[0]);let o=t.timingInfo;return o.redirectEndTime=o.postRedirectStartTime=yh(t.crossOriginIsolatedCapability),o.redirectStartTime===0&&(o.redirectStartTime=o.startTime),r.urlList.push(i),sUe(r,n),T4(t,!0)}async function hT(t,e=!1,r=!1){let n=t.request,i=null,o=null,s=null,a=null,c=!1;n.window==="no-window"&&n.redirect==="error"?(i=t,o=n):(o=Zxe(n),i={...t},i.request=o);let l=n.credentials==="include"||n.credentials==="same-origin"&&n.responseTainting==="basic",u=o.body?o.body.length:null,d=null;if(o.body==null&&["POST","PUT"].includes(o.method)&&(d="0"),u!=null&&(d=sI(`${u}`)),d!=null&&!o.headersList.contains("content-length",!0)&&o.headersList.append("content-length",d,!0),u!=null&&o.keepalive,gT.is.URL(o.referrer)&&o.headersList.append("referer",sI(o.referrer.href),!0),iUe(o),cUe(o),o.headersList.contains("user-agent",!0)||o.headersList.append("user-agent",jUe,!0),o.cache==="default"&&(o.headersList.contains("if-modified-since",!0)||o.headersList.contains("if-none-match",!0)||o.headersList.contains("if-unmodified-since",!0)||o.headersList.contains("if-match",!0)||o.headersList.contains("if-range",!0))&&(o.cache="no-store"),o.cache==="no-cache"&&!o.preventNoCacheCacheControlHeaderModification&&!o.headersList.contains("cache-control",!0)&&o.headersList.append("cache-control","max-age=0",!0),(o.cache==="no-store"||o.cache==="reload")&&(o.headersList.contains("pragma",!0)||o.headersList.append("pragma","no-cache",!0),o.headersList.contains("cache-control",!0)||o.headersList.append("cache-control","no-cache",!0)),o.headersList.contains("range",!0)&&o.headersList.append("accept-encoding","identity",!0),o.headersList.contains("accept-encoding",!0)||(gUe(Un(o))?o.headersList.append("accept-encoding","br, gzip, deflate",!0):o.headersList.append("accept-encoding","gzip, deflate",!0)),o.headersList.delete("host",!0),l&&!o.headersList.contains("authorization",!0)){let A=null;if(!(bUe(o)&&(o.useURLCredentials===void 0||!E4(Un(o))))){if(E4(Un(o))&&e){let{username:p,password:h}=Un(o);A=`Basic ${Buffer.from(`${p}:${h}`).toString("base64")}`}}A!==null&&o.headersList.append("Authorization",A,!1)}if(a==null&&(o.cache="no-store"),o.cache!=="no-store"&&o.cache,s==null){if(o.cache==="only-if-cached")return At("only if cached");let A=await YUe(i,l,r);!wUe.has(o.method)&&A.status>=200&&A.status<=399,c&&A.status,s==null&&(s=A)}if(s.urlList=[...o.urlList],o.headersList.contains("range",!0)&&(s.rangeRequested=!0),s.requestIncludesCredentials=l,s.status===401&&o.responseTainting!=="cors"&&l&&(n.useURLCredentials!==void 0||SUe(n.traversableForUserPrompts))){if(n.body!=null){if(n.body.source==null)return s;n.body=lI(n.body.source)[0]}if(n.useURLCredentials===void 0||e)return Ja(t)?mh(t):s;t.controller.connection.destroy(),s=await hT(t,!0)}if(s.status===407)return n.window==="no-window"?At():Ja(t)?mh(t):At("proxy authentication required");if(s.status===421&&!r&&(n.body==null||n.body.source!=null)){if(Ja(t))return mh(t);t.controller.connection.destroy(),s=await hT(t,e,!0)}return s}async function YUe(t,e=!1,r=!1){Sl(!t.controller.connection||t.controller.connection.destroyed),t.controller.connection={abort:null,destroyed:!1,destroy(h,f=!0){this.destroyed||(this.destroyed=!0,f&&this.abort?.(h??new DOMException("The operation was aborted.","AbortError")))}};let n=t.request,i=null,o=t.timingInfo;null==null&&(n.cache="no-store");let a=r?"yes":"no";n.mode;let c=null;if(n.body==null&&t.processRequestEndOfBody)queueMicrotask(()=>t.processRequestEndOfBody());else if(n.body!=null){let h=async function*(S){Ja(t)||(yield S,t.processRequestBodyChunkLength?.(S.byteLength))},f=()=>{Ja(t)||t.processRequestEndOfBody&&t.processRequestEndOfBody()},E=S=>{Ja(t)||(S.name==="AbortError"?t.controller.abort():t.controller.terminate(S))};c=(async function*(){try{for await(let S of n.body.stream)yield*h(S);f()}catch(S){E(S)}})()}try{let{body:h,status:f,statusText:E,headersList:S,socket:B}=await p({body:c});if(B)i=iI({status:f,statusText:E,headersList:S,socket:B});else{let _=h[Symbol.asyncIterator]();t.controller.next=()=>_.next(),i=iI({status:f,statusText:E,headersList:S})}}catch(h){return h.name==="AbortError"?(t.controller.connection.destroy(),mh(t,h)):At(h)}let l=()=>t.controller.resume(),u=h=>{Ja(t)||t.controller.abort(h)},d=new ReadableStream({start(h){t.controller.controller=h},pull:l,cancel:u,type:"bytes"});i.body={stream:d,source:null,length:null},t.controller.resume||t.controller.on("terminated",A),t.controller.resume=async()=>{for(;;){let h,f;try{let{done:S,value:B}=await t.controller.next();if(y4(t))break;h=S?void 0:B}catch(S){t.controller.ended&&!o.encodedBodySize?h=void 0:(h=S,f=!0)}if(h===void 0){hUe(t.controller.controller),HUe(t,i);return}if(o.decodedBodySize+=h?.byteLength??0,f){t.controller.terminate(h);return}let E=new Uint8Array(h);if(E.byteLength&&t.controller.controller.enqueue(E),kUe(d)){t.controller.terminate();return}if(t.controller.controller.desiredSize<=0)return}};function A(h){y4(t)?(i.aborted=!0,oI(d)&&t.controller.controller.error(t.controller.serializedAbortReason)):oI(d)&&t.controller.controller.error(new TypeError("terminated",{cause:AUe(h)?h:void 0})),t.controller.connection.destroy()}return i;function p({body:h}){let f=Un(n),E=t.controller.dispatcher,S=f.pathname+f.search,B=f.search.length===0&&f.href[f.href.length-f.hash.length-1]==="?";return new Promise((_,v)=>E.dispatch({path:B?`${S}?`:S,origin:f.origin,method:n.method,body:E.isMockActive?n.body&&(n.body.source||n.body.stream):h,headers:n.headersList.entries,maxRedirections:0,upgrade:n.mode==="websocket"?"websocket":void 0},{body:null,abort:null,onConnect(T){let{connection:L}=t.controller;o.finalConnectionTimingInfo=mUe(void 0,o.postRedirectStartTime,t.crossOriginIsolatedCapability),L.destroyed?T(new DOMException("The operation was aborted.","AbortError")):(t.controller.on("terminated",T),this.abort=L.abort=T),o.finalNetworkRequestStartTime=yh(t.crossOriginIsolatedCapability)},onResponseStarted(){o.finalNetworkResponseStartTime=yh(t.crossOriginIsolatedCapability)},onHeaders(T,L,k,P){if(T<200)return!1;let U=new lT;for(let tt=0;tt<L.length;tt+=2){let Ht=C4(L[tt]),Nt=L[tt+1];if(Array.isArray(Nt)&&!Buffer.isBuffer(L[tt+1]))for(let kr of Nt)U.append(Ht,kr.toString("latin1"),!0);else U.append(Ht,Nt.toString("latin1"),!0)}let K=U.get("location",!0);this.body=new QUe({read:k});let Ae=K&&n.redirect==="follow"&&w4.has(T),Re=[];if(n.method!=="HEAD"&&n.method!=="CONNECT"&&!_4.includes(T)&&!Ae){let tt=U.get("content-encoding",!0),Ht=tt?tt.toLowerCase().split(","):[],Nt=5;if(Ht.length>Nt)return v(new Error(`too many content-encodings in response: ${Ht.length}, maximum allowed is ${Nt}`)),!0;for(let kr=Ht.length-1;kr>=0;--kr){let qr=Ht[kr].trim();if(qr==="x-gzip"||qr==="gzip")Re.push(Li.createGunzip({flush:Li.constants.Z_SYNC_FLUSH,finishFlush:Li.constants.Z_SYNC_FLUSH}));else if(qr==="deflate")Re.push(IUe({flush:Li.constants.Z_SYNC_FLUSH,finishFlush:Li.constants.Z_SYNC_FLUSH}));else if(qr==="br")Re.push(Li.createBrotliDecompress({flush:Li.constants.BROTLI_OPERATION_FLUSH,finishFlush:Li.constants.BROTLI_OPERATION_FLUSH}));else if(qr==="zstd"&&$Ue)Re.push(Li.createZstdDecompress({flush:Li.constants.ZSTD_e_continue,finishFlush:Li.constants.ZSTD_e_end}));else{Re.length=0;break}}}let Ge=this.onError.bind(this);return _({status:T,statusText:P,headersList:U,body:Re.length?TUe(this.body,...Re,tt=>{tt&&this.onError(tt)}).on("error",Ge):this.body.on("error",Ge)}),!0},onData(T){if(t.controller.dump)return;let L=T;return o.encodedBodySize+=L.byteLength,this.body.push(L)},onComplete(){this.abort&&t.controller.off("terminated",this.abort),t.controller.ended=!0,this.body.push(null)},onError(T){this.abort&&t.controller.off("terminated",this.abort),this.body?.destroy(T),t.controller.terminate(T),v(T)},onRequestUpgrade(T,L,k,P){if(P.session!=null&&L!==200||P.session==null&&L!==101)return!1;let U=new lT;for(let[K,Ae]of Object.entries(k)){if(Ae==null)continue;let Re=K.toLowerCase();if(Array.isArray(Ae))for(let Ge of Ae)U.append(Re,String(Ge),!0);else U.append(Re,String(Ae),!0)}return _({status:L,statusText:b4[L],headersList:U,socket:P}),!0},onUpgrade(T,L,k){if(k.session!=null&&T!==200||k.session==null&&T!==101)return!1;let P=new lT;for(let U=0;U<L.length;U+=2){let K=C4(L[U]),Ae=L[U+1];if(Array.isArray(Ae)&&!Buffer.isBuffer(L[U+1]))for(let Re of Ae)P.append(K,Re.toString("latin1"),!0);else P.append(K,Ae.toString("latin1"),!0)}return _({status:T,statusText:b4[T],headersList:P,socket:k}),!0}}))}}k4.exports={fetch:qUe,Fetch:aI,fetching:Q4,finalizeAndReportTiming:B4}});var O4=y((Zqe,N4)=>{"use strict";var VUe=require("assert"),{URLSerializer:R4}=ci(),{isValidHeaderName:WUe}=Qn();function JUe(t,e,r=!1){let n=R4(t,r),i=R4(e,r);return n===i}function ZUe(t){VUe(t!==null);let e=[];for(let r of t.split(","))r=r.trim(),WUe(r)&&e.push(r);return e}N4.exports={urlEquals:JUe,getFieldValues:ZUe}});var P4=y((Kqe,M4)=>{"use strict";var mT=require("assert"),{kConstruct:KUe}=ut(),{urlEquals:XUe,getFieldValues:yT}=O4(),{kEnumerableProperty:wl,isDisturbed:eMe}=De(),{webidl:fe}=Cr(),{cloneResponse:x4,fromInnerResponse:tMe,getResponseState:rMe}=gh(),{Request:Ih,fromInnerRequest:nMe,getRequestState:As}=ud(),{fetching:iMe}=Eh(),{urlIsHttpHttpsScheme:uI,readAllBytes:oMe}=Qn(),{createDeferredPromise:dd}=kp(),dI=class t{#e;constructor(){arguments[0]!==KUe&&fe.illegalConstructor(),fe.util.markAsUncloneable(this),this.#e=arguments[1]}async match(e,r={}){fe.brandCheck(this,t);let n="Cache.match";fe.argumentLengthCheck(arguments,1,n),e=fe.converters.RequestInfo(e),r=fe.converters.CacheQueryOptions(r,n,"options");let i=this.#o(e,r,1);if(i.length!==0)return i[0]}async matchAll(e=void 0,r={}){fe.brandCheck(this,t);let n="Cache.matchAll";return e!==void 0&&(e=fe.converters.RequestInfo(e)),r=fe.converters.CacheQueryOptions(r,n,"options"),this.#o(e,r)}async add(e){fe.brandCheck(this,t),fe.argumentLengthCheck(arguments,1,"Cache.add"),e=fe.converters.RequestInfo(e);let n=[e];return await this.addAll(n)}async addAll(e){fe.brandCheck(this,t);let r="Cache.addAll";fe.argumentLengthCheck(arguments,1,r);let n=[],i=[];for(let A of e){if(A===void 0)throw fe.errors.conversionFailed({prefix:r,argument:"Argument 1",types:["undefined is not allowed"]});if(A=fe.converters.RequestInfo(A),typeof A=="string")continue;let p=As(A);if(!uI(p.url)||p.method!=="GET")throw fe.errors.exception({header:r,message:"Expected http/s scheme when method is not GET."})}let o=[];for(let A of e){let p=As(new Ih(A));if(!uI(p.url))throw fe.errors.exception({header:r,message:"Expected http/s scheme."});p.initiator="fetch",p.destination="subresource",i.push(p);let h=dd();o.push(iMe({request:p,processResponse(f){if(f.type==="error"||f.status===206||f.status<200||f.status>299)h.reject(fe.errors.exception({header:"Cache.addAll",message:"Received an invalid status code or the request failed."}));else if(f.headersList.contains("vary")){let E=yT(f.headersList.get("vary"));for(let S of E)if(S==="*"){h.reject(fe.errors.exception({header:"Cache.addAll",message:"invalid vary field value"}));for(let B of o)B.abort();return}}},processResponseEndOfBody(f){if(f.aborted){h.reject(new DOMException("aborted","AbortError"));return}h.resolve(f)}})),n.push(h.promise)}let a=await Promise.all(n),c=[],l=0;for(let A of a){let p={type:"put",request:i[l],response:A};c.push(p),l++}let u=dd(),d=null;try{this.#t(c)}catch(A){d=A}return queueMicrotask(()=>{d===null?u.resolve(void 0):u.reject(d)}),u.promise}async put(e,r){fe.brandCheck(this,t);let n="Cache.put";fe.argumentLengthCheck(arguments,2,n),e=fe.converters.RequestInfo(e),r=fe.converters.Response(r,n,"response");let i=null;if(fe.is.Request(e)?i=As(e):i=As(new Ih(e)),!uI(i.url)||i.method!=="GET")throw fe.errors.exception({header:n,message:"Expected an http/s scheme when method is not GET"});let o=rMe(r);if(o.status===206)throw fe.errors.exception({header:n,message:"Got 206 status"});if(o.headersList.contains("vary")){let p=yT(o.headersList.get("vary"));for(let h of p)if(h==="*")throw fe.errors.exception({header:n,message:"Got * vary field value"})}if(o.body&&(eMe(o.body.stream)||o.body.stream.locked))throw fe.errors.exception({header:n,message:"Response body is locked or disturbed"});let s=x4(o),a=dd();if(o.body!=null){let h=o.body.stream.getReader();oMe(h,a.resolve,a.reject)}else a.resolve(void 0);let c=[],l={type:"put",request:i,response:s};c.push(l);let u=await a.promise;s.body!=null&&(s.body.source=u);let d=dd(),A=null;try{this.#t(c)}catch(p){A=p}return queueMicrotask(()=>{A===null?d.resolve():d.reject(A)}),d.promise}async delete(e,r={}){fe.brandCheck(this,t);let n="Cache.delete";fe.argumentLengthCheck(arguments,1,n),e=fe.converters.RequestInfo(e),r=fe.converters.CacheQueryOptions(r,n,"options");let i=null;if(fe.is.Request(e)){if(i=As(e),i.method!=="GET"&&!r.ignoreMethod)return!1}else mT(typeof e=="string"),i=As(new Ih(e));let o=[],s={type:"delete",request:i,options:r};o.push(s);let a=dd(),c=null,l;try{l=this.#t(o)}catch(u){c=u}return queueMicrotask(()=>{c===null?a.resolve(!!l?.length):a.reject(c)}),a.promise}async keys(e=void 0,r={}){fe.brandCheck(this,t);let n="Cache.keys";e!==void 0&&(e=fe.converters.RequestInfo(e)),r=fe.converters.CacheQueryOptions(r,n,"options");let i=null;if(e!==void 0)if(fe.is.Request(e)){if(i=As(e),i.method!=="GET"&&!r.ignoreMethod)return[]}else typeof e=="string"&&(i=As(new Ih(e)));let o=dd(),s=[];if(e===void 0)for(let a of this.#e)s.push(a[0]);else{let a=this.#n(i,r);for(let c of a)s.push(c[0])}return queueMicrotask(()=>{let a=[];for(let c of s){let l=nMe(c,void 0,new AbortController().signal,"immutable");a.push(l)}o.resolve(Object.freeze(a))}),o.promise}#t(e){let r=this.#e,n=[...r],i=[],o=[];try{for(let s of e){if(s.type!=="delete"&&s.type!=="put")throw fe.errors.exception({header:"Cache.#batchCacheOperations",message:'operation type does not match "delete" or "put"'});if(s.type==="delete"&&s.response!=null)throw fe.errors.exception({header:"Cache.#batchCacheOperations",message:"delete operation should not have an associated response"});if(this.#n(s.request,s.options,i).length)throw new DOMException("???","InvalidStateError");let a;if(s.type==="delete"){if(a=this.#n(s.request,s.options),a.length===0)return[];for(let c of a){let l=r.indexOf(c);mT(l!==-1),r.splice(l,1)}}else if(s.type==="put"){if(s.response==null)throw fe.errors.exception({header:"Cache.#batchCacheOperations",message:"put operation should have an associated response"});let c=s.request;if(!uI(c.url))throw fe.errors.exception({header:"Cache.#batchCacheOperations",message:"expected http or https scheme"});if(c.method!=="GET")throw fe.errors.exception({header:"Cache.#batchCacheOperations",message:"not get method"});if(s.options!=null)throw fe.errors.exception({header:"Cache.#batchCacheOperations",message:"options must not be defined"});a=this.#n(s.request);for(let l of a){let u=r.indexOf(l);mT(u!==-1),r.splice(u,1)}r.push([s.request,s.response]),i.push([s.request,s.response])}o.push([s.request,s.response])}return o}catch(s){throw this.#e.length=0,this.#e=n,s}}#n(e,r,n){let i=[],o=n??this.#e;for(let s of o){let[a,c]=s;this.#i(e,a,c,r)&&i.push(s)}return i}#i(e,r,n=null,i){let o=new URL(e.url),s=new URL(r.url);if(i?.ignoreSearch&&(s.search="",o.search=""),!XUe(o,s,!0))return!1;if(n==null||i?.ignoreVary||!n.headersList.contains("vary"))return!0;let a=yT(n.headersList.get("vary"));for(let c of a){if(c==="*")return!1;let l=r.headersList.get(c),u=e.headersList.get(c);if(l!==u)return!1}return!0}#o(e,r,n=1/0){let i=null;if(e!==void 0)if(fe.is.Request(e)){if(i=As(e),i.method!=="GET"&&!r.ignoreMethod)return[]}else typeof e=="string"&&(i=As(new Ih(e)));let o=[];if(e===void 0)for(let a of this.#e)o.push(a[1]);else{let a=this.#n(i,r);for(let c of a)o.push(c[1])}let s=[];for(let a of o){let c=tMe(x4(a),"immutable");if(s.push(c),s.length>=n)break}return Object.freeze(s)}};Object.defineProperties(dI.prototype,{[Symbol.toStringTag]:{value:"Cache",configurable:!0},match:wl,matchAll:wl,add:wl,addAll:wl,put:wl,delete:wl,keys:wl});var U4=[{key:"ignoreSearch",converter:fe.converters.boolean,defaultValue:()=>!1},{key:"ignoreMethod",converter:fe.converters.boolean,defaultValue:()=>!1},{key:"ignoreVary",converter:fe.converters.boolean,defaultValue:()=>!1}];fe.converters.CacheQueryOptions=fe.dictionaryConverter(U4);fe.converters.MultiCacheQueryOptions=fe.dictionaryConverter([...U4,{key:"cacheName",converter:fe.converters.DOMString}]);fe.converters.Response=fe.interfaceConverter(fe.is.Response,"Response");fe.converters["sequence<RequestInfo>"]=fe.sequenceConverter(fe.converters.RequestInfo);M4.exports={Cache:dI}});var $4=y((Xqe,L4)=>{"use strict";var{Cache:AI}=P4(),{webidl:Tr}=Cr(),{kEnumerableProperty:Ch}=De(),{kConstruct:bh}=ut(),pI=class t{#e=new Map;constructor(){arguments[0]!==bh&&Tr.illegalConstructor(),Tr.util.markAsUncloneable(this)}async match(e,r={}){if(Tr.brandCheck(this,t),Tr.argumentLengthCheck(arguments,1,"CacheStorage.match"),e=Tr.converters.RequestInfo(e),r=Tr.converters.MultiCacheQueryOptions(r),r.cacheName!=null){if(this.#e.has(r.cacheName)){let n=this.#e.get(r.cacheName);return await new AI(bh,n).match(e,r)}}else for(let n of this.#e.values()){let o=await new AI(bh,n).match(e,r);if(o!==void 0)return o}}async has(e){Tr.brandCheck(this,t);let r="CacheStorage.has";return Tr.argumentLengthCheck(arguments,1,r),e=Tr.converters.DOMString(e,r,"cacheName"),this.#e.has(e)}async open(e){Tr.brandCheck(this,t);let r="CacheStorage.open";if(Tr.argumentLengthCheck(arguments,1,r),e=Tr.converters.DOMString(e,r,"cacheName"),this.#e.has(e)){let i=this.#e.get(e);return new AI(bh,i)}let n=[];return this.#e.set(e,n),new AI(bh,n)}async delete(e){Tr.brandCheck(this,t);let r="CacheStorage.delete";return Tr.argumentLengthCheck(arguments,1,r),e=Tr.converters.DOMString(e,r,"cacheName"),this.#e.delete(e)}async keys(){return Tr.brandCheck(this,t),[...this.#e.keys()]}};Object.defineProperties(pI.prototype,{[Symbol.toStringTag]:{value:"CacheStorage",configurable:!0},match:Ch,has:Ch,open:Ch,delete:Ch,keys:Ch});L4.exports={CacheStorage:pI}});var j4=y((eHe,F4)=>{"use strict";F4.exports={maxAttributeValueSize:1024,maxNameValuePairSize:4096}});var CT=y((tHe,G4)=>{"use strict";function sMe(t){for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r>=0&&r<=8||r>=10&&r<=31||r===127)return!0}return!1}function ET(t){for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r<33||r>126||r===34||r===40||r===41||r===60||r===62||r===64||r===44||r===59||r===58||r===92||r===47||r===91||r===93||r===63||r===61||r===123||r===125)throw new Error("Invalid cookie name")}}function IT(t){let e=t.length,r=0;if(t[0]==='"'){if(e===1||t[e-1]!=='"')throw new Error("Invalid cookie value");--e,++r}for(;r<e;){let n=t.charCodeAt(r++);if(n<33||n>126||n===34||n===44||n===59||n===92)throw new Error("Invalid cookie value")}}function q4(t){for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r<32||r>126||r===59)throw new Error("Invalid cookie path")}}function z4(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}function aMe(t){if(t===" ")return;if(t.length>255)throw new Error("Invalid cookie domain");let e=0;for(let r=0;r<t.length;++r){let n=t.charCodeAt(r);if(n===46){if(e===0)throw new Error("Invalid cookie domain");if(t.charCodeAt(r-1)===45)throw new Error("Invalid cookie domain");e=0;continue}if(e===0&&!z4(n))throw new Error("Invalid cookie domain");if(!z4(n)&&n!==45)throw new Error("Invalid cookie domain");if(++e>63)throw new Error("Invalid cookie domain")}if(e===0||t.charCodeAt(t.length-1)===45)throw new Error("Invalid cookie domain")}var cMe=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],lMe=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],hI=Array(61).fill(0).map((t,e)=>e.toString().padStart(2,"0"));function H4(t){return typeof t=="number"&&(t=new Date(t)),`${cMe[t.getUTCDay()]}, ${hI[t.getUTCDate()]} ${lMe[t.getUTCMonth()]} ${t.getUTCFullYear()} ${hI[t.getUTCHours()]}:${hI[t.getUTCMinutes()]}:${hI[t.getUTCSeconds()]} GMT`}function uMe(t){if(t<0)throw new Error("Invalid cookie max-age")}function dMe(t){if(t.name.length===0)return null;ET(t.name),IT(t.value);let e=[`${t.name}=${t.value}`];t.name.startsWith("__Secure-")&&(t.secure=!0),t.name.startsWith("__Host-")&&(t.secure=!0,t.domain=null,t.path="/"),t.secure&&e.push("Secure"),t.httpOnly&&e.push("HttpOnly"),typeof t.maxAge=="number"&&(uMe(t.maxAge),e.push(`Max-Age=${t.maxAge}`)),t.domain&&(aMe(t.domain),e.push(`Domain=${t.domain}`)),t.path&&(q4(t.path),e.push(`Path=${t.path}`)),t.expires&&t.expires.toString()!=="Invalid Date"&&e.push(`Expires=${H4(t.expires)}`),t.sameSite&&e.push(`SameSite=${t.sameSite}`);for(let r of t.unparsed){if(!r.includes("="))throw new Error("Invalid unparsed");let[n,...i]=r.split("="),o=n.trim(),s=i.join("=");ET(o),IT(s),e.push(`${o}=${s}`)}return e.join("; ")}G4.exports={isCTLExcludingHtab:sMe,validateCookieName:ET,validateCookiePath:q4,validateCookieValue:IT,toIMFDate:H4,stringify:dMe}});var V4=y((rHe,Y4)=>{"use strict";var{collectASequenceOfCodePointsFast:fI}=Ms(),{maxNameValuePairSize:AMe,maxAttributeValueSize:pMe}=j4(),{isCTLExcludingHtab:hMe}=CT(),fMe=require("assert");function gMe(t){if(hMe(t))return null;let e="",r="",n="",i="";if(t.includes(";")){let o={position:0};e=fI(";",t,o),r=t.slice(o.position)}else e=t;if(!e.includes("="))i=e;else{let o={position:0};n=fI("=",e,o),i=e.slice(o.position+1)}return n=n.trim(),i=i.trim(),n.length+i.length>AMe?null:{name:n,value:i,...Ad(r)}}function Ad(t,e={}){if(t.length===0)return e;fMe(t[0]===";"),t=t.slice(1);let r="";t.includes(";")?(r=fI(";",t,{position:0}),t=t.slice(r.length)):(r=t,t="");let n="",i="";if(r.includes("=")){let s={position:0};n=fI("=",r,s),i=r.slice(s.position+1)}else n=r;if(n=n.trim(),i=i.trim(),i.length>pMe)return Ad(t,e);let o=n.toLowerCase();if(o==="expires"){let s=new Date(i);e.expires=s}else if(o==="max-age"){let s=i.charCodeAt(0);if((s<48||s>57)&&i[0]!=="-"||!/^\d+$/.test(i))return Ad(t,e);let a=Number(i);e.maxAge=a}else if(o==="domain"){let s=i;s[0]==="."&&(s=s.slice(1)),s=s.toLowerCase(),e.domain=s}else if(o==="path"){let s="";i.length===0||i[0]!=="/"?s="/":s=i,e.path=s}else if(o==="secure")e.secure=!0;else if(o==="httponly")e.httpOnly=!0;else if(o==="samesite"){let s=i.toLowerCase();s==="none"?e.sameSite="None":s==="strict"?e.sameSite="Strict":s==="lax"&&(e.sameSite="Lax")}else e.unparsed??=[],e.unparsed.push(`${n}=${i}`);return Ad(t,e)}Y4.exports={parseSetCookie:gMe,parseUnparsedAttributes:Ad}});var K4=y((nHe,Z4)=>{"use strict";var{parseSetCookie:W4}=V4(),{stringify:mMe}=CT(),{webidl:We}=Cr(),{Headers:yMe}=Il(),gI=We.brandCheckMultiple([yMe,globalThis.Headers].filter(Boolean));function EMe(t){We.argumentLengthCheck(arguments,1,"getCookies"),gI(t);let e=t.get("cookie"),r={};if(!e)return r;for(let n of e.split(";")){let[i,...o]=n.split("=");r[i.trim()]=o.join("=")}return r}function IMe(t,e,r){gI(t);let n="deleteCookie";We.argumentLengthCheck(arguments,2,n),e=We.converters.DOMString(e,n,"name"),r=We.converters.DeleteCookieAttributes(r),J4(t,{name:e,value:"",expires:new Date(0),...r})}function CMe(t){We.argumentLengthCheck(arguments,1,"getSetCookies"),gI(t);let e=t.getSetCookie();return e?e.map(r=>W4(r)):[]}function bMe(t){return t=We.converters.DOMString(t),W4(t)}function J4(t,e){We.argumentLengthCheck(arguments,2,"setCookie"),gI(t),e=We.converters.Cookie(e);let r=mMe(e);r&&t.append("set-cookie",r,!0)}We.converters.DeleteCookieAttributes=We.dictionaryConverter([{converter:We.nullableConverter(We.converters.DOMString),key:"path",defaultValue:()=>null},{converter:We.nullableConverter(We.converters.DOMString),key:"domain",defaultValue:()=>null}]);We.converters.Cookie=We.dictionaryConverter([{converter:We.converters.DOMString,key:"name"},{converter:We.converters.DOMString,key:"value"},{converter:We.nullableConverter(t=>typeof t=="number"?We.converters["unsigned long long"](t):new Date(t)),key:"expires",defaultValue:()=>null},{converter:We.nullableConverter(We.converters["long long"]),key:"maxAge",defaultValue:()=>null},{converter:We.nullableConverter(We.converters.DOMString),key:"domain",defaultValue:()=>null},{converter:We.nullableConverter(We.converters.DOMString),key:"path",defaultValue:()=>null},{converter:We.nullableConverter(We.converters.boolean),key:"secure",defaultValue:()=>null},{converter:We.nullableConverter(We.converters.boolean),key:"httpOnly",defaultValue:()=>null},{converter:We.converters.USVString,key:"sameSite",allowedValues:["Strict","Lax","None"]},{converter:We.sequenceConverter(We.converters.DOMString),key:"unparsed",defaultValue:()=>[]}]);Z4.exports={getCookies:EMe,deleteCookie:IMe,getSetCookies:CMe,setCookie:J4,parseCookie:bMe}});var EI=y((iHe,eW)=>{"use strict";var{webidl:me}=Cr(),{kEnumerableProperty:an}=De(),{kConstruct:X4}=ut(),pd=class t extends Event{#e;constructor(e,r={}){if(e===X4){super(arguments[1],arguments[2]),me.util.markAsUncloneable(this);return}let n="MessageEvent constructor";me.argumentLengthCheck(arguments,1,n),e=me.converters.DOMString(e,n,"type"),r=me.converters.MessageEventInit(r,n,"eventInitDict"),super(e,r),this.#e=r,me.util.markAsUncloneable(this)}get data(){return me.brandCheck(this,t),this.#e.data}get origin(){return me.brandCheck(this,t),this.#e.origin}get lastEventId(){return me.brandCheck(this,t),this.#e.lastEventId}get source(){return me.brandCheck(this,t),this.#e.source}get ports(){return me.brandCheck(this,t),Object.isFrozen(this.#e.ports)||Object.freeze(this.#e.ports),this.#e.ports}initMessageEvent(e,r=!1,n=!1,i=null,o="",s="",a=null,c=[]){return me.brandCheck(this,t),me.argumentLengthCheck(arguments,1,"MessageEvent.initMessageEvent"),new t(e,{bubbles:r,cancelable:n,data:i,origin:o,lastEventId:s,source:a,ports:c})}static createFastMessageEvent(e,r){let n=new t(X4,e,r);return n.#e=r,n.#e.data??=null,n.#e.origin??="",n.#e.lastEventId??="",n.#e.source??=null,n.#e.ports??=[],n}},{createFastMessageEvent:SMe}=pd;delete pd.createFastMessageEvent;var mI=class t extends Event{#e;constructor(e,r={}){let n="CloseEvent constructor";me.argumentLengthCheck(arguments,1,n),e=me.converters.DOMString(e,n,"type"),r=me.converters.CloseEventInit(r),super(e,r),this.#e=r,me.util.markAsUncloneable(this)}get wasClean(){return me.brandCheck(this,t),this.#e.wasClean}get code(){return me.brandCheck(this,t),this.#e.code}get reason(){return me.brandCheck(this,t),this.#e.reason}},yI=class t extends Event{#e;constructor(e,r){let n="ErrorEvent constructor";me.argumentLengthCheck(arguments,1,n),super(e,r),me.util.markAsUncloneable(this),e=me.converters.DOMString(e,n,"type"),r=me.converters.ErrorEventInit(r??{}),this.#e=r}get message(){return me.brandCheck(this,t),this.#e.message}get filename(){return me.brandCheck(this,t),this.#e.filename}get lineno(){return me.brandCheck(this,t),this.#e.lineno}get colno(){return me.brandCheck(this,t),this.#e.colno}get error(){return me.brandCheck(this,t),this.#e.error}};Object.defineProperties(pd.prototype,{[Symbol.toStringTag]:{value:"MessageEvent",configurable:!0},data:an,origin:an,lastEventId:an,source:an,ports:an,initMessageEvent:an});Object.defineProperties(mI.prototype,{[Symbol.toStringTag]:{value:"CloseEvent",configurable:!0},reason:an,code:an,wasClean:an});Object.defineProperties(yI.prototype,{[Symbol.toStringTag]:{value:"ErrorEvent",configurable:!0},message:an,filename:an,lineno:an,colno:an,error:an});me.converters.MessagePort=me.interfaceConverter(me.is.MessagePort,"MessagePort");me.converters["sequence<MessagePort>"]=me.sequenceConverter(me.converters.MessagePort);var bT=[{key:"bubbles",converter:me.converters.boolean,defaultValue:()=>!1},{key:"cancelable",converter:me.converters.boolean,defaultValue:()=>!1},{key:"composed",converter:me.converters.boolean,defaultValue:()=>!1}];me.converters.MessageEventInit=me.dictionaryConverter([...bT,{key:"data",converter:me.converters.any,defaultValue:()=>null},{key:"origin",converter:me.converters.USVString,defaultValue:()=>""},{key:"lastEventId",converter:me.converters.DOMString,defaultValue:()=>""},{key:"source",converter:me.nullableConverter(me.converters.MessagePort),defaultValue:()=>null},{key:"ports",converter:me.converters["sequence<MessagePort>"],defaultValue:()=>[]}]);me.converters.CloseEventInit=me.dictionaryConverter([...bT,{key:"wasClean",converter:me.converters.boolean,defaultValue:()=>!1},{key:"code",converter:me.converters["unsigned short"],defaultValue:()=>0},{key:"reason",converter:me.converters.USVString,defaultValue:()=>""}]);me.converters.ErrorEventInit=me.dictionaryConverter([...bT,{key:"message",converter:me.converters.DOMString,defaultValue:()=>""},{key:"filename",converter:me.converters.USVString,defaultValue:()=>""},{key:"lineno",converter:me.converters["unsigned long"],defaultValue:()=>0},{key:"colno",converter:me.converters["unsigned long"],defaultValue:()=>0},{key:"error",converter:me.converters.any}]);eW.exports={MessageEvent:pd,CloseEvent:mI,ErrorEvent:yI,createFastMessageEvent:SMe}});var Za=y((oHe,tW)=>{"use strict";var wMe="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",_Me={enumerable:!0,writable:!1,configurable:!1},BMe={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},vMe={SENT:1,RECEIVED:2},QMe={CONTINUATION:0,TEXT:1,BINARY:2,CLOSE:8,PING:9,PONG:10},TMe=65535,DMe={INFO:0,PAYLOADLENGTH_16:2,PAYLOADLENGTH_64:3,READ_DATA:4},kMe=Buffer.allocUnsafe(0),RMe={text:1,typedArray:2,arrayBuffer:3,blob:4};tW.exports={uid:wMe,sentCloseFrameState:vMe,staticPropertyDescriptors:_Me,states:BMe,opcodes:QMe,maxUnsigned16Bit:TMe,parserStates:DMe,emptyBuffer:kMe,sendHints:RMe}});var _l=y((sHe,sW)=>{"use strict";var{states:II,opcodes:hd}=Za(),{isUtf8:NMe}=require("buffer"),{removeHTTPWhitespace:rW}=ci(),{collectASequenceOfCodePointsFast:OMe}=Ms();function xMe(t){return t===II.CONNECTING}function UMe(t){return t===II.OPEN}function MMe(t){return t===II.CLOSING}function PMe(t){return t===II.CLOSED}function LMe(t,e,r=(i,o)=>new Event(i,o),n={}){let i=r(t,n);e.dispatchEvent(i)}function $Me(t,e,r){t.onMessage(e,r)}function FMe(t){return t.byteLength===t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}function jMe(t){if(t.length===0)return!1;for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r<33||r>126||r===34||r===40||r===41||r===44||r===47||r===58||r===59||r===60||r===61||r===62||r===63||r===64||r===91||r===92||r===93||r===123||r===125)return!1}return!0}function zMe(t){return t>=1e3&&t<1015?t!==1004&&t!==1005&&t!==1006:t>=3e3&&t<=4999}function nW(t){return t===hd.CLOSE||t===hd.PING||t===hd.PONG}function iW(t){return t===hd.CONTINUATION}function oW(t){return t===hd.TEXT||t===hd.BINARY}function qMe(t){return oW(t)||iW(t)||nW(t)}function HMe(t){let e={position:0},r=new Map;for(;e.position<t.length;){let n=OMe(";",t,e),[i,o=""]=n.split("=",2);r.set(rW(i,!0,!1),rW(o,!1,!0)),e.position++}return r}function GMe(t){if(t.length===0)return!1;for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(n<48||n>57)return!1}let e=Number.parseInt(t,10);return e>=8&&e<=15}function YMe(t,e){let r;try{r=new URL(t,e)}catch(n){throw new DOMException(n,"SyntaxError")}if(r.protocol==="http:"?r.protocol="ws:":r.protocol==="https:"&&(r.protocol="wss:"),r.protocol!=="ws:"&&r.protocol!=="wss:")throw new DOMException("expected a ws: or wss: url","SyntaxError");if(r.hash.length||r.href.endsWith("#"))throw new DOMException("hash","SyntaxError");return r}function VMe(t,e){if(t!==null&&t!==1e3&&(t<3e3||t>4999))throw new DOMException("invalid code","InvalidAccessError");if(e!==null){let r=Buffer.byteLength(e);if(r>123)throw new DOMException(`Reason must be less than 123 bytes; received ${r}`,"SyntaxError")}}var WMe=(()=>{if(typeof process.versions.icu=="string"){let t=new TextDecoder("utf-8",{fatal:!0});return t.decode.bind(t)}return function(t){if(NMe(t))return t.toString("utf-8");throw new TypeError("Invalid utf-8 received.")}})();sW.exports={isConnecting:xMe,isEstablished:UMe,isClosing:MMe,isClosed:PMe,fireEvent:LMe,isValidSubprotocol:jMe,isValidStatusCode:zMe,websocketMessageReceived:$Me,utf8Decode:WMe,isControlFrame:nW,isContinuationFrame:iW,isTextBinaryFrame:oW,isValidOpcode:qMe,parseExtensions:HMe,isValidClientWindowBits:GMe,toArrayBuffer:FMe,getURLRecord:YMe,validateCloseCodeAndReason:VMe}});var gd=y((aHe,cW)=>{"use strict";var{runtimeFeatures:JMe}=Ps(),{maxUnsigned16Bit:aW,opcodes:ZMe}=Za(),CI=8*1024,Sh=null,fd=CI,KMe=JMe.has("crypto")?require("crypto").randomFillSync:function(e,r,n){for(let i=0;i<e.length;++i)e[i]=Math.random()*255|0;return e};function ST(){return fd===CI&&(fd=0,KMe(Sh??=Buffer.allocUnsafeSlow(CI),0,CI)),[Sh[fd++],Sh[fd++],Sh[fd++],Sh[fd++]]}var wT=class{constructor(e){this.frameData=e}createFrame(e){let r=this.frameData,n=ST(),i=r?.byteLength??0,o=i,s=6;i>aW?(s+=8,o=127):i>125&&(s+=2,o=126);let a=Buffer.allocUnsafe(i+s);a[0]=a[1]=0,a[0]|=128,a[0]=(a[0]&240)+e;a[s-4]=n[0],a[s-3]=n[1],a[s-2]=n[2],a[s-1]=n[3],a[1]=o,o===126?a.writeUInt16BE(i,2):o===127&&(a[2]=a[3]=0,a.writeUIntBE(i,4,6)),a[1]|=128;for(let c=0;c<i;++c)a[s+c]=r[c]^n[c&3];return a}static createFastTextFrame(e){let r=ST(),n=e.length;for(let a=0;a<n;++a)e[a]^=r[a&3];let i=n,o=6;n>aW?(o+=8,i=127):n>125&&(o+=2,i=126);let s=Buffer.allocUnsafeSlow(o);return s[0]=128|ZMe.TEXT,s[1]=i|128,s[o-4]=r[0],s[o-3]=r[1],s[o-2]=r[2],s[o-1]=r[3],i===126?s.writeUInt16BE(n,2):i===127&&(s[2]=s[3]=0,s.writeUIntBE(n,4,6)),[s,e]}};cW.exports={WebsocketFrameSend:wT,generateMask:ST}});var bI=y((cHe,hW)=>{"use strict";var{uid:XMe,states:_T,sentCloseFrameState:BT,emptyBuffer:lW,opcodes:ePe}=Za(),{parseExtensions:tPe,isClosed:rPe,isClosing:nPe,isEstablished:AW,isConnecting:iPe,validateCloseCodeAndReason:oPe}=_l(),{makeRequest:sPe}=ud(),{fetching:aPe}=Eh(),{Headers:cPe,getHeadersList:lPe}=Il(),{getDecodeSplit:uPe}=Qn(),{WebsocketFrameSend:dPe}=gd(),APe=require("assert"),{runtimeFeatures:pPe}=Ps(),uW=pPe.has("crypto")?require("crypto"):null,dW=!1;function hPe(t,e,r,n,i){let o=t;o.protocol=t.protocol==="ws:"?"http:":"https:";let s=sPe({urlList:[o],client:r,serviceWorkers:"none",referrer:"no-referrer",mode:"websocket",credentials:"include",cache:"no-store",redirect:"error",useURLCredentials:!0});if(i.headers){let u=lPe(new cPe(i.headers));s.headersList=u}let a=uW.randomBytes(16).toString("base64");s.headersList.append("sec-websocket-key",a,!0),s.headersList.append("sec-websocket-version","13",!0);for(let u of e)s.headersList.append("sec-websocket-protocol",u,!0);return s.headersList.append("sec-websocket-extensions","permessage-deflate; client_max_window_bits",!0),aPe({request:s,useParallelQueue:!0,dispatcher:i.dispatcher,processResponse(u){if(u.type==="error"||u.status!==101){if(u.socket?.session==null){Ka(n,u,1002,"Received network error or non-101 status code.",u.error);return}if(u.status!==200){Ka(n,u,1002,"Received network error or non-200 status code.",u.error);return}}if(dW===!1&&u.socket?.session!=null&&(process.emitWarning("WebSocket over HTTP2 is experimental, and subject to change.","ExperimentalWarning"),dW=!0),e.length!==0&&!u.headersList.get("Sec-WebSocket-Protocol")){Ka(n,u,1002,"Server did not respond with sent protocols.");return}if(u.socket.session==null&&u.headersList.get("Upgrade")?.toLowerCase()!=="websocket"){Ka(n,u,1002,'Server did not set Upgrade header to "websocket".');return}if(u.socket.session==null&&u.headersList.get("Connection")?.toLowerCase()!=="upgrade"){Ka(n,u,1002,'Server did not set Connection header to "upgrade".');return}let d=u.headersList.get("Sec-WebSocket-Accept"),A=uW.hash("sha1",a+XMe,"base64");if(d!==A){Ka(n,u,1002,"Incorrect hash received in Sec-WebSocket-Accept header.");return}let p=u.headersList.get("Sec-WebSocket-Extensions"),h;if(p!==null&&(h=tPe(p),!h.has("permessage-deflate"))){Ka(n,u,1002,"Sec-WebSocket-Extensions header does not match.");return}let f=u.headersList.get("Sec-WebSocket-Protocol");if(f!==null){let E=uPe("sec-websocket-protocol",s.headersList);if(E===null||!E.includes(f)){Ka(n,u,1002,"Protocol was not set in the opening handshake.");return}}u.socket.on("data",n.onSocketData),u.socket.on("close",n.onSocketClose),u.socket.on("error",n.onSocketError),n.wasEverConnected=!0,n.onConnectionEstablished(u,h)}})}function pW(t,e,r,n=!1){if(e??=null,r??="",n&&oPe(e,r),!(rPe(t.readyState)||nPe(t.readyState)))if(!AW(t.readyState))vT(t),t.readyState=_T.CLOSING;else if(!t.closeState.has(BT.SENT)&&!t.closeState.has(BT.RECEIVED)){let i=new dPe;r.length!==0&&e===null&&(e=1e3),APe(e===null||Number.isInteger(e)),e===null&&r.length===0?i.frameData=lW:e!==null&&r===null?(i.frameData=Buffer.allocUnsafe(2),i.frameData.writeUInt16BE(e,0)):e!==null&&r!==null?(i.frameData=Buffer.allocUnsafe(2+Buffer.byteLength(r)),i.frameData.writeUInt16BE(e,0),i.frameData.write(r,2,"utf-8")):i.frameData=lW,t.socket.write(i.createFrame(ePe.CLOSE)),t.closeState.add(BT.SENT),t.readyState=_T.CLOSING}else t.readyState=_T.CLOSING}function Ka(t,e,r,n,i){e.socket?.session!=null&&!e.socket.destroyed&&e.socket.destroy(),vT(t,r,n,i)}function vT(t,e,r,n){AW(t.readyState)&&pW(t,e,r,!1),t.controller.abort(),iPe(t.readyState)?t.onSocketClose():t.socket?.destroyed===!1&&t.socket.destroy()}hW.exports={establishWebSocketConnection:hPe,failWebsocketConnection:vT,closeWebSocketConnection:pW}});var gW=y((lHe,fW)=>{"use strict";var{createInflateRaw:fPe,Z_DEFAULT_WINDOWBITS:gPe}=require("zlib"),{isValidClientWindowBits:mPe}=_l(),{MessageSizeExceededError:yPe}=_e(),EPe=Buffer.from([0,0,255,255]),SI=Symbol("kBuffer"),wh=Symbol("kLength"),QT=class{#e;#t={};#n=0;constructor(e,r){this.#t.serverNoContextTakeover=e.has("server_no_context_takeover"),this.#t.serverMaxWindowBits=e.get("server_max_window_bits"),this.#n=r.maxPayloadSize}decompress(e,r,n){if(!this.#e){let i=gPe;if(this.#t.serverMaxWindowBits){if(!mPe(this.#t.serverMaxWindowBits)){n(new Error("Invalid server_max_window_bits"));return}i=Number.parseInt(this.#t.serverMaxWindowBits)}try{this.#e=fPe({windowBits:i})}catch(o){n(o);return}this.#e[SI]=[],this.#e[wh]=0,this.#e.on("data",o=>{if(this.#e[wh]+=o.length,this.#n>0&&this.#e[wh]>this.#n){n(new yPe),this.#e.removeAllListeners(),this.#e.destroy(),this.#e=null;return}this.#e[SI].push(o)}),this.#e.on("error",o=>{this.#e=null,n(o)})}this.#e.write(e),r&&this.#e.write(EPe),this.#e.flush(()=>{if(!this.#e)return;let i=Buffer.concat(this.#e[SI],this.#e[wh]);this.#e[SI].length=0,this.#e[wh]=0,n(null,i)})}};fW.exports={PerMessageDeflate:QT}});var RT=y((uHe,CW)=>{"use strict";var{Writable:IPe}=require("stream"),CPe=require("assert"),{parserStates:cn,opcodes:md,states:bPe,emptyBuffer:mW,sentCloseFrameState:_h}=Za(),{isValidStatusCode:SPe,isValidOpcode:wPe,websocketMessageReceived:yW,utf8Decode:_Pe,isControlFrame:TT,isTextBinaryFrame:DT,isContinuationFrame:BPe}=_l(),{failWebsocketConnection:Dr}=bI(),{WebsocketFrameSend:EW}=gd(),{PerMessageDeflate:vPe}=gW(),{MessageSizeExceededError:IW}=_e(),kT=class extends IPe{#e=[];#t=0;#n=0;#i=!1;#o=cn.INFO;#r={};#c=[];#s;#a;#l;#d;constructor(e,r,n={}){super(),this.#a=e,this.#s=r??new Map,this.#l=n.maxFragments??0,this.#d=n.maxPayloadSize??0,this.#s.has("permessage-deflate")&&this.#s.set("permessage-deflate",new vPe(r,n))}_write(e,r,n){this.#e.push(e),this.#n+=e.length,this.#i=!0,this.run(n)}#A(){return this.#d>0&&!TT(this.#r.opcode)&&this.#r.payloadLength+this.#t>this.#d?(Dr(this.#a,1009,"Payload size exceeds maximum allowed size"),!1):!0}run(e){for(;this.#i;)if(this.#o===cn.INFO){if(this.#n<2)return e();let r=this.consume(2),n=(r[0]&128)!==0,i=r[0]&15,o=(r[1]&128)===128,s=!n&&i!==md.CONTINUATION,a=r[1]&127,c=r[0]&64,l=r[0]&32,u=r[0]&16;if(!wPe(i))return Dr(this.#a,1002,"Invalid opcode received"),e();if(o)return Dr(this.#a,1002,"Frame cannot be masked"),e();if(c!==0&&!this.#s.has("permessage-deflate")){Dr(this.#a,1002,"Expected RSV1 to be clear.");return}if(l!==0||u!==0){Dr(this.#a,1002,"RSV1, RSV2, RSV3 must be clear");return}if(s&&!DT(i)){Dr(this.#a,1002,"Invalid frame type was fragmented.");return}if(DT(i)&&this.#c.length>0){Dr(this.#a,1002,"Expected continuation frame");return}if(this.#r.fragmented&&s){Dr(this.#a,1002,"Fragmented frame exceeded 125 bytes.");return}if((a>125||s)&&TT(i)){Dr(this.#a,1002,"Control frame either too large or fragmented");return}if(BPe(i)&&this.#c.length===0&&!this.#r.compressed){Dr(this.#a,1002,"Unexpected continuation frame");return}if(a<=125){if(this.#r.payloadLength=a,this.#o=cn.READ_DATA,!this.#A())return}else a===126?this.#o=cn.PAYLOADLENGTH_16:a===127&&(this.#o=cn.PAYLOADLENGTH_64);DT(i)&&(this.#r.binaryType=i,this.#r.compressed=c!==0),this.#r.opcode=i,this.#r.masked=o,this.#r.fin=n,this.#r.fragmented=s}else if(this.#o===cn.PAYLOADLENGTH_16){if(this.#n<2)return e();let r=this.consume(2);if(this.#r.payloadLength=r.readUInt16BE(0),this.#o=cn.READ_DATA,!this.#A())return}else if(this.#o===cn.PAYLOADLENGTH_64){if(this.#n<8)return e();let r=this.consume(8),n=r.readUInt32BE(0),i=r.readUInt32BE(4);if(n!==0||i>2**31-1){Dr(this.#a,1009,"Received payload length > 2^31 bytes.");return}if(this.#r.payloadLength=i,this.#o=cn.READ_DATA,!this.#A())return}else if(this.#o===cn.READ_DATA){if(this.#n<this.#r.payloadLength)return e();let r=this.consume(this.#r.payloadLength);if(TT(this.#r.opcode))this.#i=this.parseControlFrame(r),this.#o=cn.INFO;else if(this.#r.compressed){this.#s.get("permessage-deflate").decompress(r,this.#r.fin,(n,i)=>{if(n){let o=n instanceof IW?1009:1007;Dr(this.#a,o,n.message);return}if(this.writeFragments(i)){if(this.#d>0&&this.#t>this.#d){Dr(this.#a,1009,new IW().message);return}if(!this.#r.fin){this.#o=cn.INFO,this.#i=!0,this.run(e);return}yW(this.#a,this.#r.binaryType,this.consumeFragments()),this.#i=!0,this.#o=cn.INFO,this.run(e)}},this.#t),this.#i=!1;break}else{if(!this.writeFragments(r))return;!this.#r.fragmented&&this.#r.fin&&yW(this.#a,this.#r.binaryType,this.consumeFragments()),this.#o=cn.INFO}}}consume(e){if(e>this.#n)throw new Error("Called consume() before buffers satiated.");if(e===0)return mW;this.#n-=e;let r=this.#e[0];if(r.length>e)return this.#e[0]=r.subarray(e,r.length),r.subarray(0,e);if(r.length===e)return this.#e.shift();{let n=0,i=Buffer.allocUnsafeSlow(e);for(;n!==e;){let o=this.#e[0],s=o.length;if(s+n===e){i.set(this.#e.shift(),n);break}else if(s+n>e){i.set(o.subarray(0,e-n),n),this.#e[0]=o.subarray(e-n);break}else i.set(this.#e.shift(),n),n+=s}return i}}writeFragments(e){return this.#l>0&&this.#c.length===this.#l?(Dr(this.#a,1008,"Too many message fragments"),!1):(this.#t+=e.length,this.#c.push(e),!0)}consumeFragments(){let e=this.#c;if(e.length===1)return this.#t=0,e.shift();let r=0,n=Buffer.allocUnsafeSlow(this.#t);for(let i=0;i<e.length;++i){let o=e[i];n.set(o,r),r+=o.length}return this.#c=[],this.#t=0,n}parseCloseBody(e){CPe(e.length!==1);let r;if(e.length>=2&&(r=e.readUInt16BE(0)),r!==void 0&&!SPe(r))return{code:1002,reason:"Invalid status code",error:!0};let n=e.subarray(2);n[0]===239&&n[1]===187&&n[2]===191&&(n=n.subarray(3));try{n=_Pe(n)}catch{return{code:1007,reason:"Invalid UTF-8",error:!0}}return{code:r,reason:n,error:!1}}parseControlFrame(e){let{opcode:r,payloadLength:n}=this.#r;if(r===md.CLOSE){if(n===1)return Dr(this.#a,1002,"Received close frame with a 1-byte body."),!1;if(this.#r.closeInfo=this.parseCloseBody(e),this.#r.closeInfo.error){let{code:i,reason:o}=this.#r.closeInfo;return Dr(this.#a,i,o),!1}if(!this.#a.closeState.has(_h.SENT)&&!this.#a.closeState.has(_h.RECEIVED)){let i=mW;this.#r.closeInfo.code&&(i=Buffer.allocUnsafe(2),i.writeUInt16BE(this.#r.closeInfo.code,0));let o=new EW(i);this.#a.socket.write(o.createFrame(md.CLOSE)),this.#a.closeState.add(_h.SENT)}return this.#a.readyState=bPe.CLOSING,this.#a.closeState.add(_h.RECEIVED),!1}else if(r===md.PING){if(!this.#a.closeState.has(_h.RECEIVED)){let i=new EW(e);this.#a.socket.write(i.createFrame(md.PONG)),this.#a.onPing(e)}}else r===md.PONG&&this.#a.onPong(e);return!0}get closingInfo(){return this.#r.closeInfo}};CW.exports={ByteParser:kT}});var _W=y((dHe,wW)=>{"use strict";var{WebsocketFrameSend:SW}=gd(),{opcodes:bW,sendHints:Bl}=Za(),QPe=WB(),OT=class{#e=new QPe;#t=!1;#n;constructor(e){this.#n=e}add(e,r,n){if(n!==Bl.blob){if(this.#t){let o={promise:null,callback:r,frame:NT(e,n)};this.#e.push(o)}else if(n===Bl.text){let{0:o,1:s}=SW.createFastTextFrame(e);this.#n.cork(),this.#n.write(o),this.#n.write(s,r),this.#n.uncork()}else this.#n.write(NT(e,n),r);return}let i={promise:e.arrayBuffer().then(o=>{i.promise=null,i.frame=NT(o,n)}),callback:r,frame:null};this.#e.push(i),this.#t||this.#i()}async#i(){this.#t=!0;let e=this.#e;for(;!e.isEmpty();){let r=e.shift();r.promise!==null&&await r.promise,this.#n.write(r.frame,r.callback),r.callback=r.frame=null}this.#t=!1}};function NT(t,e){return new SW(TPe(t,e)).createFrame(e===Bl.text?bW.TEXT:bW.BINARY)}function TPe(t,e){switch(e){case Bl.text:case Bl.typedArray:return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);case Bl.arrayBuffer:case Bl.blob:return new Uint8Array(t)}}wW.exports={SendQueue:OT}});var kW=y((AHe,DW)=>{"use strict";var{isArrayBuffer:DPe}=require("util/types"),{webidl:Ee}=Cr(),{URLSerializer:kPe}=ci(),{environmentSettingsObject:BW}=Qn(),{staticPropertyDescriptors:Xa,states:Ws,sentCloseFrameState:xT,sendHints:wI,opcodes:UT}=Za(),{isConnecting:RPe,isEstablished:vW,isClosing:QW,isClosed:NPe,isValidSubprotocol:OPe,fireEvent:_I,utf8Decode:xPe,toArrayBuffer:UPe,getURLRecord:MPe}=_l(),{establishWebSocketConnection:PPe,closeWebSocketConnection:LPe,failWebsocketConnection:TW}=bI(),{ByteParser:$Pe}=RT(),{kEnumerableProperty:gi}=De(),{getGlobalDispatcher:FPe}=FE(),{ErrorEvent:jPe,CloseEvent:zPe,createFastMessageEvent:qPe}=EI(),{SendQueue:HPe}=_W(),{WebsocketFrameSend:GPe}=gd(),{channels:ps}=Ra();function YPe(t){return typeof t?.address=="function"?t.address():typeof t?.session?.socket?.address=="function"?t.session.socket.address():null}var $r=class t extends EventTarget{#e={open:null,error:null,close:null,message:null};#t=0;#n="";#i="";#o;#r={onConnectionEstablished:(e,r)=>this.#l(e,r),onMessage:(e,r)=>this.#d(e,r),onParserError:e=>TW(this.#r,null,e.message),onParserDrain:()=>this.#A(),onSocketData:e=>{this.#a.write(e)||this.#r.socket.pause()},onSocketError:e=>{this.#r.readyState=Ws.CLOSING,ps.socketError.hasSubscribers&&ps.socketError.publish(e),this.#r.socket.destroy()},onSocketClose:()=>this.#p(),onPing:e=>{ps.ping.hasSubscribers&&ps.ping.publish({payload:e,websocket:this})},onPong:e=>{ps.pong.hasSubscribers&&ps.pong.publish({payload:e,websocket:this})},readyState:Ws.CONNECTING,socket:null,closeState:new Set,controller:null,wasEverConnected:!1};#c;#s;#a;constructor(e,r=[]){super(),Ee.util.markAsUncloneable(this);let n="WebSocket constructor";Ee.argumentLengthCheck(arguments,1,n);let i=Ee.converters["DOMString or sequence<DOMString> or WebSocketInit"](r,n,"options");e=Ee.converters.USVString(e),r=i.protocols;let o=BW.settingsObject.baseUrl,s=MPe(e,o);if(typeof r=="string"&&(r=[r]),r.length!==new Set(r.map(c=>c.toLowerCase())).size)throw new DOMException("Invalid Sec-WebSocket-Protocol value","SyntaxError");if(r.length>0&&!r.every(c=>OPe(c)))throw new DOMException("Invalid Sec-WebSocket-Protocol value","SyntaxError");this.#c=new URL(s.href);let a=BW.settingsObject;this.#r.controller=PPe(s,r,a,this.#r,i),this.#r.readyState=t.CONNECTING,this.#s="blob"}close(e=void 0,r=void 0){Ee.brandCheck(this,t),e!==void 0&&(e=Ee.converters["unsigned short"](e,"WebSocket.close","code",Ee.attributes.Clamp)),r!==void 0&&(r=Ee.converters.USVString(r)),e??=null,r??="",LPe(this.#r,e,r,!0)}send(e){Ee.brandCheck(this,t);let r="WebSocket.send";if(Ee.argumentLengthCheck(arguments,1,r),e=Ee.converters.WebSocketSendData(e,r,"data"),RPe(this.#r.readyState))throw new DOMException("Sent before connected.","InvalidStateError");if(!(!vW(this.#r.readyState)||QW(this.#r.readyState)))if(typeof e=="string"){let n=Buffer.from(e);this.#t+=n.byteLength,this.#o.add(n,()=>{this.#t-=n.byteLength},wI.text)}else DPe(e)?(this.#t+=e.byteLength,this.#o.add(e,()=>{this.#t-=e.byteLength},wI.arrayBuffer)):ArrayBuffer.isView(e)?(this.#t+=e.byteLength,this.#o.add(e,()=>{this.#t-=e.byteLength},wI.typedArray)):Ee.is.Blob(e)&&(this.#t+=e.size,this.#o.add(e,()=>{this.#t-=e.size},wI.blob))}get readyState(){return Ee.brandCheck(this,t),this.#r.readyState}get bufferedAmount(){return Ee.brandCheck(this,t),this.#t}get url(){return Ee.brandCheck(this,t),kPe(this.#c)}get extensions(){return Ee.brandCheck(this,t),this.#i}get protocol(){return Ee.brandCheck(this,t),this.#n}get onopen(){return Ee.brandCheck(this,t),this.#e.open}set onopen(e){Ee.brandCheck(this,t),this.#e.open&&this.removeEventListener("open",this.#e.open);let r=Ee.converters.EventHandlerNonNull(e);r!==null?(this.addEventListener("open",r),this.#e.open=e):this.#e.open=null}get onerror(){return Ee.brandCheck(this,t),this.#e.error}set onerror(e){Ee.brandCheck(this,t),this.#e.error&&this.removeEventListener("error",this.#e.error);let r=Ee.converters.EventHandlerNonNull(e);r!==null?(this.addEventListener("error",r),this.#e.error=e):this.#e.error=null}get onclose(){return Ee.brandCheck(this,t),this.#e.close}set onclose(e){Ee.brandCheck(this,t),this.#e.close&&this.removeEventListener("close",this.#e.close);let r=Ee.converters.EventHandlerNonNull(e);r!==null?(this.addEventListener("close",r),this.#e.close=e):this.#e.close=null}get onmessage(){return Ee.brandCheck(this,t),this.#e.message}set onmessage(e){Ee.brandCheck(this,t),this.#e.message&&this.removeEventListener("message",this.#e.message);let r=Ee.converters.EventHandlerNonNull(e);r!==null?(this.addEventListener("message",r),this.#e.message=e):this.#e.message=null}get binaryType(){return Ee.brandCheck(this,t),this.#s}set binaryType(e){Ee.brandCheck(this,t),e!=="blob"&&e!=="arraybuffer"?this.#s="blob":this.#s=e}#l(e,r){this.#r.socket=e.socket;let n=this.#r.controller.dispatcher?.webSocketOptions,i=n?.maxFragments,o=n?.maxPayloadSize,s=new $Pe(this.#r,r,{maxFragments:i,maxPayloadSize:o});s.on("drain",()=>this.#r.onParserDrain()),s.on("error",l=>this.#r.onParserError(l)),this.#a=s,this.#o=new HPe(e.socket),this.#r.readyState=Ws.OPEN;let a=e.headersList.get("sec-websocket-extensions");a!==null&&(this.#i=a);let c=e.headersList.get("sec-websocket-protocol");if(c!==null&&(this.#n=c),_I("open",this),ps.open.hasSubscribers){let l=e.headersList.entries;ps.open.publish({address:YPe(e.socket),protocol:this.#n,extensions:this.#i,websocket:this,handshakeResponse:{status:e.status,statusText:e.statusText,headers:l}})}}#d(e,r){if(this.#r.readyState!==Ws.OPEN)return;let n;if(e===UT.TEXT)try{n=xPe(r)}catch{TW(this.#r,1007,"Received invalid UTF-8 in text frame.");return}else e===UT.BINARY&&(this.#s==="blob"?n=new Blob([r]):n=UPe(r));_I("message",this,qPe,{origin:this.#c.origin,data:n})}#A(){this.#r.socket.resume()}#p(){let e=this.#r.closeState.has(xT.SENT)&&this.#r.closeState.has(xT.RECEIVED),r=1005,n="",i=this.#a?.closingInfo;i&&!i.error&&(r=i.code??1005,n=i.reason),this.#r.readyState=Ws.CLOSED,this.#r.closeState.has(xT.RECEIVED)||(r=1006,_I("error",this,(o,s)=>new jPe(o,s),{error:new TypeError(n)})),_I("close",this,(o,s)=>new zPe(o,s),{wasClean:e,code:r,reason:n}),ps.close.hasSubscribers&&ps.close.publish({websocket:this,code:r,reason:n})}static ping(e,r){if(Buffer.isBuffer(r)){if(r.length>125)throw new TypeError("A PING frame cannot have a body larger than 125 bytes.")}else if(r!==void 0)throw new TypeError("Expected buffer payload");let n=e.#r.readyState;if(vW(n)&&!QW(n)&&!NPe(n)){let i=new GPe(r);e.#r.socket.write(i.createFrame(UT.PING))}}},{ping:VPe}=$r;Reflect.deleteProperty($r,"ping");$r.CONNECTING=$r.prototype.CONNECTING=Ws.CONNECTING;$r.OPEN=$r.prototype.OPEN=Ws.OPEN;$r.CLOSING=$r.prototype.CLOSING=Ws.CLOSING;$r.CLOSED=$r.prototype.CLOSED=Ws.CLOSED;Object.defineProperties($r.prototype,{CONNECTING:Xa,OPEN:Xa,CLOSING:Xa,CLOSED:Xa,url:gi,readyState:gi,bufferedAmount:gi,onopen:gi,onerror:gi,onclose:gi,close:gi,onmessage:gi,binaryType:gi,send:gi,extensions:gi,protocol:gi,[Symbol.toStringTag]:{value:"WebSocket",writable:!1,enumerable:!1,configurable:!0}});Object.defineProperties($r,{CONNECTING:Xa,OPEN:Xa,CLOSING:Xa,CLOSED:Xa});Ee.converters["sequence<DOMString>"]=Ee.sequenceConverter(Ee.converters.DOMString);Ee.converters["DOMString or sequence<DOMString>"]=function(t,e,r){return Ee.util.Type(t)===Ee.util.Types.OBJECT&&Symbol.iterator in t?Ee.converters["sequence<DOMString>"](t):Ee.converters.DOMString(t,e,r)};Ee.converters.WebSocketInit=Ee.dictionaryConverter([{key:"protocols",converter:Ee.converters["DOMString or sequence<DOMString>"],defaultValue:()=>[]},{key:"dispatcher",converter:Ee.converters.any,defaultValue:()=>FPe()},{key:"headers",converter:Ee.nullableConverter(Ee.converters.HeadersInit)}]);Ee.converters["DOMString or sequence<DOMString> or WebSocketInit"]=function(t){return Ee.util.Type(t)===Ee.util.Types.OBJECT&&!(Symbol.iterator in t)?Ee.converters.WebSocketInit(t):{protocols:Ee.converters["DOMString or sequence<DOMString>"](t)}};Ee.converters.WebSocketSendData=function(t){return Ee.util.Type(t)===Ee.util.Types.OBJECT&&(Ee.is.Blob(t)||Ee.is.BufferSource(t))?t:Ee.converters.USVString(t)};DW.exports={WebSocket:$r,ping:VPe}});var MT=y((pHe,OW)=>{"use strict";var{webidl:BI}=Cr(),{validateCloseCodeAndReason:WPe}=_l(),{kConstruct:RW}=ut(),{kEnumerableProperty:NW}=De();function JPe(){class t extends DOMException{get reason(){return""}}return new t().reason!==void 0?DOMException:new Proxy(DOMException,{construct(e,r,n){let i=Reflect.construct(e,r,e);return Object.setPrototypeOf(i,n.prototype),i}})}var vl=class t extends JPe(){#e;#t;constructor(e="",r=void 0){if(e=BI.converters.DOMString(e,"WebSocketError","message"),super(e,"WebSocketError"),r===RW)return;r!==null&&(r=BI.converters.WebSocketCloseInfo(r));let n=r.closeCode??null,i=r.reason??"";WPe(n,i),i.length!==0&&n===null&&(n=1e3),this.#e=n,this.#t=i}get closeCode(){return this.#e}get reason(){return this.#t}static createUnvalidatedWebSocketError(e,r,n){let i=new t(e,RW);return i.#e=r,i.#t=n,i}},{createUnvalidatedWebSocketError:ZPe}=vl;delete vl.createUnvalidatedWebSocketError;Object.defineProperties(vl.prototype,{closeCode:NW,reason:NW,[Symbol.toStringTag]:{value:"WebSocketError",writable:!1,enumerable:!1,configurable:!0}});BI.is.WebSocketError=BI.util.MakeTypeAssertion(vl);OW.exports={WebSocketError:vl,createUnvalidatedWebSocketError:ZPe}});var LW=y((hHe,PW)=>{"use strict";var{createDeferredPromise:PT}=kp(),{environmentSettingsObject:xW}=Qn(),{states:yd,opcodes:vI,sentCloseFrameState:Ed}=Za(),{webidl:qt}=Cr(),{getURLRecord:KPe,isValidSubprotocol:XPe,isEstablished:eLe,utf8Decode:tLe}=_l(),{establishWebSocketConnection:rLe,failWebsocketConnection:LT,closeWebSocketConnection:$T}=bI(),{channels:UW}=Ra(),{WebsocketFrameSend:nLe}=gd(),{ByteParser:iLe}=RT(),{WebSocketError:oLe,createUnvalidatedWebSocketError:sLe}=MT(),{kEnumerableProperty:QI}=De(),{utf8DecodeBytes:aLe}=Vy(),MW=!1,TI=class{#e;#t;#n;#i;#o;#r;#c=!1;#s={onConnectionEstablished:(e,r)=>this.#d(e,r),onMessage:(e,r)=>this.#A(e,r),onParserError:e=>LT(this.#s,null,e.message),onParserDrain:()=>this.#s.socket.resume(),onSocketData:e=>{this.#a.write(e)||this.#s.socket.pause()},onSocketError:e=>{this.#s.readyState=yd.CLOSING,UW.socketError.hasSubscribers&&UW.socketError.publish(e),this.#s.socket.destroy()},onSocketClose:()=>this.#p(),onPing:()=>{},onPong:()=>{},readyState:yd.CONNECTING,socket:null,closeState:new Set,controller:null,wasEverConnected:!1};#a;constructor(e,r=void 0){MW||(process.emitWarning("WebSocketStream is experimental! Expect it to change at any time.",{code:"UNDICI-WSS"}),MW=!0),qt.argumentLengthCheck(arguments,1,"WebSocket"),e=qt.converters.USVString(e),r!==null&&(r=qt.converters.WebSocketStreamOptions(r));let n=xW.settingsObject.baseUrl,i=KPe(e,n),o=r.protocols;if(o.length!==new Set(o.map(a=>a.toLowerCase())).size)throw new DOMException("Invalid Sec-WebSocket-Protocol value","SyntaxError");if(o.length>0&&!o.every(a=>XPe(a)))throw new DOMException("Invalid Sec-WebSocket-Protocol value","SyntaxError");if(this.#e=i.toString(),this.#t=PT(),this.#n=PT(),r.signal!=null){let a=r.signal;if(a.aborted){this.#t.reject(a.reason),this.#n.reject(a.reason);return}a.addEventListener("abort",()=>{eLe(this.#s.readyState)||(LT(this.#s),this.#s.readyState=yd.CLOSING,this.#t.reject(a.reason),this.#n.reject(a.reason),this.#c=!0)},{once:!0})}let s=xW.settingsObject;this.#s.controller=rLe(i,o,s,this.#s,r)}get url(){return this.#e.toString()}get opened(){return this.#t.promise}get closed(){return this.#n.promise}close(e=void 0){e!==null&&(e=qt.converters.WebSocketCloseInfo(e));let r=e.closeCode??null,n=e.reason;$T(this.#s,r,n,!0)}#l(e){e=qt.converters.WebSocketStreamWrite(e);let r=PT(),n=null,i=null;if(qt.is.BufferSource(e))n=new Uint8Array(ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e.slice()),i=vI.BINARY;else{let o;try{o=qt.converters.DOMString(e)}catch(s){return r.reject(s),r.promise}n=new TextEncoder().encode(o),i=vI.TEXT}if(!this.#s.closeState.has(Ed.SENT)&&!this.#s.closeState.has(Ed.RECEIVED)){let o=new nLe(n);this.#s.socket.write(o.createFrame(i),()=>{r.resolve(void 0)})}return r.promise}#d(e,r){this.#s.socket=e.socket;let n=this.#s.controller.dispatcher?.webSocketOptions?.maxFragments,i=this.#s.controller.dispatcher?.webSocketOptions?.maxPayloadSize,o=new iLe(this.#s,r,{maxFragments:n,maxPayloadSize:i});o.on("drain",()=>this.#s.onParserDrain()),o.on("error",u=>this.#s.onParserError(u)),this.#a=o,this.#s.readyState=yd.OPEN;let s=r??"",a=e.headersList.get("sec-websocket-protocol")??"",c=new ReadableStream({start:u=>{this.#o=u},cancel:u=>this.#u(u)}),l=new WritableStream({start:u=>{this.#r=u},write:u=>this.#l(u),close:()=>$T(this.#s,null,null),abort:u=>this.#h(u)});this.#i=c,this.#t.resolve({extensions:s,protocol:a,readable:c,writable:l})}#A(e,r){if(this.#s.readyState!==yd.OPEN)return;let n;if(e===vI.TEXT)try{n=tLe(r)}catch{LT(this.#s,1007,"Received invalid UTF-8 in text frame.");return}else e===vI.BINARY&&(n=new Uint8Array(r.buffer,r.byteOffset,r.byteLength));this.#o.enqueue(n)}#p(){let e=this.#s.closeState.has(Ed.SENT)&&this.#s.closeState.has(Ed.RECEIVED);if(this.#s.readyState=yd.CLOSED,this.#c)return;this.#s.wasEverConnected||this.#t.reject(new oLe("Socket never opened"));let r=this.#a?.closingInfo,n=r?.code??1005;!this.#s.closeState.has(Ed.SENT)&&!this.#s.closeState.has(Ed.RECEIVED)&&(n=1006);let i=r?.reason==null?"":aLe(Buffer.from(r.reason));if(e)this.#o.close(),this.#r.error(new DOMException("A closed WebSocketStream cannot be written to","InvalidStateError")),this.#n.resolve({closeCode:n,reason:i});else{let o=sLe("unclean close",n,i);this.#o?.error(o),this.#r?.error(o),this.#n.reject(o)}}#h(e){let r=null,n="";qt.is.WebSocketError(e)&&(r=e.closeCode,n=e.reason),$T(this.#s,r,n)}#u(e){this.#h(e)}};Object.defineProperties(TI.prototype,{url:QI,opened:QI,closed:QI,close:QI,[Symbol.toStringTag]:{value:"WebSocketStream",writable:!1,enumerable:!1,configurable:!0}});qt.converters.WebSocketStreamOptions=qt.dictionaryConverter([{key:"protocols",converter:qt.sequenceConverter(qt.converters.USVString),defaultValue:()=>[]},{key:"signal",converter:qt.nullableConverter(qt.converters.AbortSignal),defaultValue:()=>null}]);qt.converters.WebSocketCloseInfo=qt.dictionaryConverter([{key:"closeCode",converter:t=>qt.converters["unsigned short"](t,qt.attributes.EnforceRange)},{key:"reason",converter:qt.converters.USVString,defaultValue:()=>""}]);qt.converters.WebSocketStreamWrite=function(t){return typeof t=="string"?qt.converters.USVString(t):qt.converters.BufferSource(t)};PW.exports={WebSocketStream:TI}});var FW=y((fHe,$W)=>{"use strict";function cLe(t){return t.indexOf("\0")===-1}function lLe(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(t.charCodeAt(e)<48||t.charCodeAt(e)>57)return!1;return!0}$W.exports={isValidLastEventId:cLe,isASCIINumber:lLe}});var zW=y((gHe,jW)=>{"use strict";var{Transform:uLe}=require("stream"),{isASCIINumber:dLe,isValidLastEventId:ALe}=FW(),Id=[239,187,191],FT=10,DI=13,pLe=58,hLe=32,fLe=Buffer.from("data"),gLe=Buffer.from("event"),mLe=Buffer.from("id"),yLe=Buffer.from("retry");function ELe(t,e){if(e>=t.length)return!1;for(let r=e;r<t.length;r++)if(t[r]<48||t[r]>57)return!1;return!0}function ILe(t,e){for(let r=e;r<t.length;r++)if(t[r]===0)return!1;return!0}function kI(t,e,r){if(e!==r.length)return!1;for(let n=0;n<e;n++)if(t[n]!==r[n])return!1;return!0}var jT=class extends uLe{state;checkBOM=!0;crlfCheck=!1;eventEndCheck=!1;chunks=[];chunkIndex=0;pos=0;lineChunkIndex=0;linePos=0;event={data:void 0,event:void 0,id:void 0,retry:void 0};constructor(e={}){e.readableObjectMode=!0,super(e),this.state=e.eventSourceSettings||{},e.push&&(this.push=e.push)}_transform(e,r,n){if(e.length===0){n();return}if(this.chunks.push(e),this.checkBOM&&this.handleBOM()){n();return}for(;this.hasCurrentByte();){let i=this.currentByte();if(this.eventEndCheck){if(this.crlfCheck){if(i===FT){this.crlfCheck=!1,this.consumeCurrentByte();continue}this.crlfCheck=!1}if(i===FT||i===DI){i===DI&&(this.crlfCheck=!0),this.consumeCurrentByte(),this.hasPendingEvent()&&this.processEvent(this.event),this.clearEvent();continue}this.eventEndCheck=!1;continue}if(i===FT||i===DI){i===DI&&(this.crlfCheck=!0),this.parseLine(this.readLine(),this.event),this.consumeCurrentByte(),this.eventEndCheck=!0;continue}this.advanceCursor()}n()}parseLine(e,r){if(e.length===0)return;let n=e.indexOf(pLe);if(n===0)return;let i=e.length,o=e.length;if(n!==-1&&(i=n,o=n+1,e[o]===hLe&&++o),kI(e,i,fLe)){let s=e.toString("utf8",o);r.data===void 0?r.data=s:r.data+=`
|
|
2218
|
+
`)}close(){this.#n.close()}get(e){KQ(e);let r=this.#p(e);return r?{body:r.body?Buffer.from(r.body.buffer,r.body.byteOffset,r.body.byteLength):void 0,statusCode:r.statusCode,statusMessage:r.statusMessage,headers:r.headers?JSON.parse(r.headers):void 0,etag:r.etag?r.etag:void 0,vary:r.vary?JSON.parse(r.vary):void 0,cacheControlDirectives:r.cacheControlDirectives?JSON.parse(r.cacheControlDirectives):void 0,cachedAt:r.cachedAt,staleAt:r.staleAt,deleteAt:r.deleteAt}:void 0}set(e,r){KQ(e);let n=this.#A(e),i=Array.isArray(r.body)?Buffer.concat(r.body):r.body,o=i?.byteLength;if(o&&o>this.#e)return;let s=this.#p(e,!0);s?this.#o.run(i,r.deleteAt,r.statusCode,r.statusMessage,r.headers?JSON.stringify(r.headers):null,r.etag?r.etag:null,r.cacheControlDirectives?JSON.stringify(r.cacheControlDirectives):null,r.cachedAt,r.staleAt,s.id):(this.#r.run(n,e.method,i,r.deleteAt,r.statusCode,r.statusMessage,r.headers?JSON.stringify(r.headers):null,r.etag?r.etag:null,r.cacheControlDirectives?JSON.stringify(r.cacheControlDirectives):null,r.vary?JSON.stringify(r.vary):null,r.cachedAt,r.staleAt),this.#d())}createWriteStream(e,r){KQ(e),YOe(r);let n=0,i=[],o=this;return new GOe({decodeStrings:!0,write(s,a,c){n+=s.byteLength,n<o.#e?i.push(s):this.destroy(),c()},final(s){o.set(e,{...r,body:i}),s()}})}delete(e){if(typeof e!="object")throw new TypeError(`expected key to be object, got ${typeof e}`);this.#s.run(this.#A(e))}#d(){if(Number.isFinite(this.#t)&&this.size<=this.#t)return 0;{let e=this.#c.run(Date.now()).changes;if(e)return e}{let e=this.#l?.run(Math.max(Math.floor(this.#t*.1),1)).changes;if(e)return e}return 0}get size(){let{total:e}=this.#a.get();return e}#A(e){return`${e.origin}/${e.path}`}#p(e,r=!1){let n=this.#A(e),{headers:i,method:o}=e,s=this.#i.all(n,o);if(s.length===0)return;let a=Date.now();for(let c of s){if(a>=c.deleteAt&&!r)continue;let l=!0;if(c.vary){let u=JSON.parse(c.vary);for(let d in u)if(!VOe(i[d],u[d])){l=!1;break}}if(l)return c}}};function VOe(t,e){if(t==null&&e==null)return!0;if(t==null&&e!=null||t!=null&&e==null)return!1;if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}return t===e}});var Il=y((Gqe,MV)=>{"use strict";var{kConstruct:WOe}=ut(),{kEnumerableProperty:cd}=De(),{iteratorMixin:JOe,isValidHeaderName:hh,isValidHeaderValue:RV}=Qn(),{webidl:He}=Cr(),eT=require("assert"),GE=require("util");function kV(t){return t===10||t===13||t===9||t===32}function NV(t){let e=0,r=t.length;for(;r>e&&kV(t.charCodeAt(r-1));)--r;for(;r>e&&kV(t.charCodeAt(e));)++e;return e===0&&r===t.length?t:t.substring(e,r)}function OV(t,e){if(Array.isArray(e))for(let r=0;r<e.length;++r){let n=e[r];if(n.length!==2)throw He.errors.exception({header:"Headers constructor",message:`expected name/value pair to be length 2, found ${n.length}.`});tT(t,n[0],n[1])}else if(typeof e=="object"&&e!==null){let r=Object.keys(e);for(let n=0;n<r.length;++n)tT(t,r[n],e[r[n]])}else throw He.errors.conversionFailed({prefix:"Headers constructor",argument:"Argument 1",types:["sequence<sequence<ByteString>>","record<ByteString, ByteString>"]})}function tT(t,e,r){if(r=NV(r),hh(e)){if(!RV(r))throw He.errors.invalidArgument({prefix:"Headers.append",value:r,type:"header value"})}else throw He.errors.invalidArgument({prefix:"Headers.append",value:e,type:"header name"});if(UV(t)==="immutable")throw new TypeError("immutable");return VE(t).append(e,r,!1)}function ZOe(t){let e=VE(t);if(!e)return[];if(e.sortedMap)return e.sortedMap;let r=[],n=e.toSortedArray(),i=e.cookies;if(i===null||i.length===1)return e.sortedMap=n;for(let o=0;o<n.length;++o){let{0:s,1:a}=n[o];if(s==="set-cookie")for(let c=0;c<i.length;++c)r.push([s,i[c]]);else r.push([s,a])}return e.sortedMap=r}function xV(t,e){return t[0]<e[0]?-1:1}var YE=class t{cookies=null;sortedMap;headersMap;constructor(e){e instanceof t?(this.headersMap=new Map(e.headersMap),this.sortedMap=e.sortedMap,this.cookies=e.cookies===null?null:[...e.cookies]):(this.headersMap=new Map(e),this.sortedMap=null)}contains(e,r){return this.headersMap.has(r?e:e.toLowerCase())}clear(){this.headersMap.clear(),this.sortedMap=null,this.cookies=null}append(e,r,n){this.sortedMap=null;let i=n?e:e.toLowerCase(),o=this.headersMap.get(i);if(o){let s=i==="cookie"?"; ":", ";this.headersMap.set(i,{name:o.name,value:`${o.value}${s}${r}`})}else this.headersMap.set(i,{name:e,value:r});i==="set-cookie"&&(this.cookies??=[]).push(r)}set(e,r,n){this.sortedMap=null;let i=n?e:e.toLowerCase();i==="set-cookie"&&(this.cookies=[r]),this.headersMap.set(i,{name:e,value:r})}delete(e,r){this.sortedMap=null,r||(e=e.toLowerCase()),e==="set-cookie"&&(this.cookies=null),this.headersMap.delete(e)}get(e,r){return this.headersMap.get(r?e:e.toLowerCase())?.value??null}*[Symbol.iterator](){for(let{0:e,1:{value:r}}of this.headersMap)yield[e,r]}get entries(){let e={};if(this.headersMap.size!==0)for(let{name:r,value:n}of this.headersMap.values())e[r]=n;return e}rawValues(){return this.headersMap.values()}get entriesList(){let e=[];if(this.headersMap.size!==0)for(let{0:r,1:{name:n,value:i}}of this.headersMap)if(r==="set-cookie")for(let o of this.cookies)e.push([n,o]);else e.push([n,i]);return e}toSortedArray(){let e=this.headersMap.size,r=new Array(e);if(e<=32){if(e===0)return r;let n=this.headersMap[Symbol.iterator](),i=n.next().value;r[0]=[i[0],i[1].value],eT(i[1].value!==null);for(let o=1,s=0,a=0,c=0,l=0,u,d;o<e;++o){for(d=n.next().value,u=r[o]=[d[0],d[1].value],eT(u[1]!==null),c=0,a=o;c<a;)l=c+(a-c>>1),r[l][0]<=u[0]?c=l+1:a=l;if(o!==l){for(s=o;s>c;)r[s]=r[--s];r[c]=u}}if(!n.next().done)throw new TypeError("Unreachable");return r}else{let n=0;for(let{0:i,1:{value:o}}of this.headersMap)r[n++]=[i,o],eT(o!==null);return r.sort(xV)}}},Pi=class t{#e;#t;constructor(e=void 0){He.util.markAsUncloneable(this),e!==WOe&&(this.#t=new YE,this.#e="none",e!==void 0&&(e=He.converters.HeadersInit(e,"Headers constructor","init"),OV(this,e)))}append(e,r){He.brandCheck(this,t),He.argumentLengthCheck(arguments,2,"Headers.append");let n="Headers.append";return e=He.converters.ByteString(e,n,"name"),r=He.converters.ByteString(r,n,"value"),tT(this,e,r)}delete(e){if(He.brandCheck(this,t),He.argumentLengthCheck(arguments,1,"Headers.delete"),e=He.converters.ByteString(e,"Headers.delete","name"),!hh(e))throw He.errors.invalidArgument({prefix:"Headers.delete",value:e,type:"header name"});if(this.#e==="immutable")throw new TypeError("immutable");this.#t.contains(e,!1)&&this.#t.delete(e,!1)}get(e){He.brandCheck(this,t),He.argumentLengthCheck(arguments,1,"Headers.get");let r="Headers.get";if(e=He.converters.ByteString(e,r,"name"),!hh(e))throw He.errors.invalidArgument({prefix:r,value:e,type:"header name"});return this.#t.get(e,!1)}has(e){He.brandCheck(this,t),He.argumentLengthCheck(arguments,1,"Headers.has");let r="Headers.has";if(e=He.converters.ByteString(e,r,"name"),!hh(e))throw He.errors.invalidArgument({prefix:r,value:e,type:"header name"});return this.#t.contains(e,!1)}set(e,r){He.brandCheck(this,t),He.argumentLengthCheck(arguments,2,"Headers.set");let n="Headers.set";if(e=He.converters.ByteString(e,n,"name"),r=He.converters.ByteString(r,n,"value"),r=NV(r),hh(e)){if(!RV(r))throw He.errors.invalidArgument({prefix:n,value:r,type:"header value"})}else throw He.errors.invalidArgument({prefix:n,value:e,type:"header name"});if(this.#e==="immutable")throw new TypeError("immutable");this.#t.set(e,r,!1)}getSetCookie(){He.brandCheck(this,t);let e=this.#t.cookies;return e?[...e]:[]}[GE.inspect.custom](e,r){return r.depth??=e,`Headers ${GE.formatWithOptions(r,this.#t.entries)}`}static getHeadersGuard(e){return e.#e}static setHeadersGuard(e,r){e.#e=r}static getHeadersList(e){return e.#t}static setHeadersList(e,r){e.#t=r}},{getHeadersGuard:UV,setHeadersGuard:KOe,getHeadersList:VE,setHeadersList:XOe}=Pi;Reflect.deleteProperty(Pi,"getHeadersGuard");Reflect.deleteProperty(Pi,"setHeadersGuard");Reflect.deleteProperty(Pi,"getHeadersList");Reflect.deleteProperty(Pi,"setHeadersList");JOe("Headers",Pi,ZOe,0,1);Object.defineProperties(Pi.prototype,{append:cd,delete:cd,get:cd,has:cd,set:cd,getSetCookie:cd,[Symbol.toStringTag]:{value:"Headers",configurable:!0},[GE.inspect.custom]:{enumerable:!1}});He.converters.HeadersInit=function(t,e,r){if(He.util.Type(t)===He.util.Types.OBJECT){let n=Reflect.get(t,Symbol.iterator);if(!GE.types.isProxy(t)&&n===Pi.prototype.entries)try{return VE(t).entriesList}catch{}return typeof n=="function"?He.converters["sequence<sequence<ByteString>>"](t,e,r,n.bind(t)):He.converters["record<ByteString, ByteString>"](t,e,r)}throw He.errors.conversionFailed({prefix:"Headers constructor",argument:"Argument 1",types:["sequence<sequence<ByteString>>","record<ByteString, ByteString>"]})};MV.exports={fill:OV,compareHeaderName:xV,Headers:Pi,HeadersList:YE,getHeadersGuard:UV,setHeadersGuard:KOe,setHeadersList:XOe,getHeadersList:VE}});var gh=y((Yqe,WV)=>{"use strict";var{Headers:zV,HeadersList:PV,fill:exe,getHeadersGuard:txe,setHeadersGuard:qV,setHeadersList:HV}=Il(),{extractBody:LV,cloneBody:rxe,mixinBody:nxe,streamRegistry:GV,bodyUnusable:ixe}=$u(),YV=De(),$V=require("util"),{kEnumerableProperty:On}=YV,{isValidReasonPhrase:oxe,isCancelled:sxe,isAborted:axe,isErrorLike:cxe,environmentSettingsObject:lxe}=Qn(),{redirectStatusSet:uxe,nullBodyStatus:dxe}=Bp(),{webidl:ze}=Cr(),{URLSerializer:FV}=ci(),{kConstruct:JE}=ut(),rT=require("assert"),{isomorphicEncode:Axe,serializeJavascriptValueToJSONString:pxe}=Ms(),hxe=new TextEncoder("utf-8"),xn=class t{#e;#t;static error(){return fh(ZE(),"immutable")}static json(e,r=void 0){ze.argumentLengthCheck(arguments,1,"Response.json"),r!==null&&(r=ze.converters.ResponseInit(r));let n=hxe.encode(pxe(e)),i=LV(n),o=fh(ld({}),"response");return jV(o,r,{body:i[0],type:"application/json"}),o}static redirect(e,r=302){ze.argumentLengthCheck(arguments,1,"Response.redirect"),e=ze.converters.USVString(e),r=ze.converters["unsigned short"](r);let n;try{n=new URL(e,lxe.settingsObject.baseUrl)}catch(s){throw new TypeError(`Failed to parse URL from ${e}`,{cause:s})}if(!uxe.has(r))throw new RangeError(`Invalid status code ${r}`);let i=fh(ld({}),"immutable");i.#t.status=r;let o=Axe(FV(n));return i.#t.headersList.append("location",o,!0),i}constructor(e=null,r=void 0){if(ze.util.markAsUncloneable(this),e===JE)return;e!==null&&(e=ze.converters.BodyInit(e,"Response","body")),r=ze.converters.ResponseInit(r),this.#t=ld({}),this.#e=new zV(JE),qV(this.#e,"response"),HV(this.#e,this.#t.headersList);let n=null;if(e!=null){let[i,o]=LV(e);n={body:i,type:o}}jV(this,r,n)}get type(){return ze.brandCheck(this,t),this.#t.type}get url(){ze.brandCheck(this,t);let e=this.#t.urlList,r=e[e.length-1]??null;return r===null?"":FV(r,!0)}get redirected(){return ze.brandCheck(this,t),this.#t.urlList.length>1}get status(){return ze.brandCheck(this,t),this.#t.status}get ok(){return ze.brandCheck(this,t),this.#t.status>=200&&this.#t.status<=299}get statusText(){return ze.brandCheck(this,t),this.#t.statusText}get headers(){return ze.brandCheck(this,t),this.#e}get body(){return ze.brandCheck(this,t),this.#t.body?this.#t.body.stream:null}get bodyUsed(){return ze.brandCheck(this,t),!!this.#t.body&&YV.isDisturbed(this.#t.body.stream)}clone(){if(ze.brandCheck(this,t),ixe(this.#t))throw ze.errors.exception({header:"Response.clone",message:"Body has already been consumed."});let e=nT(this.#t);return this.#t.urlList.length!==0&&this.#t.body?.stream&&GV.register(this,new WeakRef(this.#t.body.stream)),fh(e,txe(this.#e))}[$V.inspect.custom](e,r){r.depth===null&&(r.depth=2),r.colors??=!0;let n={status:this.status,statusText:this.statusText,headers:this.headers,body:this.body,bodyUsed:this.bodyUsed,ok:this.ok,redirected:this.redirected,type:this.type,url:this.url};return`Response ${$V.formatWithOptions(r,n)}`}static getResponseHeaders(e){return e.#e}static setResponseHeaders(e,r){e.#e=r}static getResponseState(e){return e.#t}static setResponseState(e,r){e.#t=r}},{getResponseHeaders:fxe,setResponseHeaders:gxe,getResponseState:Cl,setResponseState:mxe}=xn;Reflect.deleteProperty(xn,"getResponseHeaders");Reflect.deleteProperty(xn,"setResponseHeaders");Reflect.deleteProperty(xn,"getResponseState");Reflect.deleteProperty(xn,"setResponseState");nxe(xn,Cl);Object.defineProperties(xn.prototype,{type:On,url:On,status:On,ok:On,redirected:On,statusText:On,headers:On,clone:On,body:On,bodyUsed:On,[Symbol.toStringTag]:{value:"Response",configurable:!0}});Object.defineProperties(xn,{json:On,redirect:On,error:On});function nT(t){if(t.internalResponse)return VV(nT(t.internalResponse),t.type);let e=ld({...t,body:null});return t.body!=null&&(e.body=rxe(t.body)),e}function ld(t){return{aborted:!1,rangeRequested:!1,timingAllowPassed:!1,requestIncludesCredentials:!1,type:"default",status:200,timingInfo:null,cacheState:"",statusText:"",...t,headersList:t?.headersList?new PV(t?.headersList):new PV,urlList:t?.urlList?[...t.urlList]:[]}}function ZE(t){let e=cxe(t);return ld({type:"error",status:0,error:e?t:new Error(t&&String(t)),aborted:t&&t.name==="AbortError"})}function yxe(t){return t.type==="error"&&t.status===0}function WE(t,e){return e={internalResponse:t,...e},new Proxy(t,{get(r,n){return n in e?e[n]:r[n]},set(r,n,i){return rT(!(n in e)),r[n]=i,!0}})}function VV(t,e){if(e==="basic")return WE(t,{type:"basic",headersList:t.headersList});if(e==="cors")return WE(t,{type:"cors",headersList:t.headersList});if(e==="opaque")return WE(t,{type:"opaque",urlList:[],status:0,statusText:"",body:null});if(e==="opaqueredirect")return WE(t,{type:"opaqueredirect",status:0,statusText:"",headersList:[],body:null});rT(!1)}function Exe(t,e=null){return rT(sxe(t)),axe(t)?ZE(Object.assign(new DOMException("The operation was aborted.","AbortError"),{cause:e})):ZE(Object.assign(new DOMException("Request was cancelled."),{cause:e}))}function jV(t,e,r){if(e.status!==null&&(e.status<200||e.status>599))throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.');if("statusText"in e&&e.statusText!=null&&!oxe(String(e.statusText)))throw new TypeError("Invalid statusText");if("status"in e&&e.status!=null&&(Cl(t).status=e.status),"statusText"in e&&e.statusText!=null&&(Cl(t).statusText=e.statusText),"headers"in e&&e.headers!=null&&exe(fxe(t),e.headers),r){if(dxe.includes(t.status))throw ze.errors.exception({header:"Response constructor",message:`Invalid response status code ${t.status}`});Cl(t).body=r.body,r.type!=null&&!Cl(t).headersList.contains("content-type",!0)&&Cl(t).headersList.append("content-type",r.type,!0)}}function fh(t,e){let r=new xn(JE);mxe(r,t);let n=new zV(JE);return gxe(r,n),HV(n,t.headersList),qV(n,e),t.urlList.length!==0&&t.body?.stream&&GV.register(r,new WeakRef(t.body.stream)),r}ze.converters.XMLHttpRequestBodyInit=function(t,e,r){return typeof t=="string"?ze.converters.USVString(t,e,r):ze.is.Blob(t)||ze.is.BufferSource(t)||ze.is.FormData(t)||ze.is.URLSearchParams(t)?t:ze.converters.DOMString(t,e,r)};ze.converters.BodyInit=function(t,e,r){return ze.is.ReadableStream(t)||t?.[Symbol.asyncIterator]?t:ze.converters.XMLHttpRequestBodyInit(t,e,r)};ze.converters.ResponseInit=ze.dictionaryConverter([{key:"status",converter:ze.converters["unsigned short"],defaultValue:()=>200},{key:"statusText",converter:ze.converters.ByteString,defaultValue:()=>""},{key:"headers",converter:ze.converters.HeadersInit}]);ze.is.Response=ze.util.MakeTypeAssertion(xn);WV.exports={isNetworkError:yxe,makeNetworkError:ZE,makeResponse:ld,makeAppropriateNetworkError:Exe,filterResponse:VV,Response:xn,cloneResponse:nT,fromInnerResponse:fh,getResponseState:Cl}});var ud=y((Vqe,l4)=>{"use strict";var{extractBody:Ixe,mixinBody:Cxe,cloneBody:bxe,bodyUnusable:JV}=$u(),{Headers:r4,fill:Sxe,HeadersList:eI,setHeadersGuard:iT,getHeadersGuard:wxe,setHeadersList:n4,getHeadersList:ZV}=Il(),XE=De(),KV=require("util"),{isValidHTTPToken:_xe,sameOrigin:XV,environmentSettingsObject:KE}=Qn(),{forbiddenMethodsSet:Bxe,corsSafeListedMethodsSet:vxe,referrerPolicy:Qxe,requestRedirect:Txe,requestMode:Dxe,requestCredentials:kxe,requestCache:Rxe,requestDuplex:Nxe}=Bp(),{kEnumerableProperty:tr,normalizedMethodRecordsBase:Oxe,normalizedMethodRecords:xxe}=XE,{webidl:Se}=Cr(),{URLSerializer:Uxe}=ci(),{kConstruct:tI}=ut(),Mxe=require("assert"),{getMaxListeners:i4,setMaxListeners:Pxe,defaultMaxListeners:Lxe}=require("events"),$xe=Symbol("abortController"),o4=new FinalizationRegistry(({signal:t,abort:e})=>{t.removeEventListener("abort",e)}),rI=new WeakMap,oT;try{oT=i4(new AbortController().signal)>0}catch{oT=!1}function e4(t){return e;function e(){let r=t.deref();if(r!==void 0){o4.unregister(e),this.removeEventListener("abort",e),r.abort(this.reason);let n=rI.get(r.signal);if(n!==void 0){if(n.size!==0){for(let i of n){let o=i.deref();o!==void 0&&o.abort(this.reason)}n.clear()}rI.delete(r.signal)}}}}var t4=!1,sn=class t{#e;#t;#n;#i;constructor(e,r=void 0){if(Se.util.markAsUncloneable(this),e===tI)return;Se.argumentLengthCheck(arguments,1,"Request constructor"),e=Se.converters.RequestInfo(e),r=Se.converters.RequestInit(r);let i=null,o=null,s=KE.settingsObject.baseUrl,a=null;if(typeof e=="string"){this.#t=r.dispatcher;let S;try{S=new URL(e,s)}catch(B){throw new TypeError("Failed to parse URL from "+e,{cause:B})}if(S.username||S.password)throw new TypeError("Request cannot be constructed from a URL that includes credentials: "+e);i=nI({urlList:[S]}),o="cors"}else Mxe(Se.is.Request(e)),i=e.#i,a=e.#e,this.#t=r.dispatcher||e.#t;let c=KE.settingsObject.origin,l="client";if(i.window?.constructor?.name==="EnvironmentSettingsObject"&&XV(i.window,c)&&(l=i.window),r.window!=null)throw new TypeError(`'window' option '${l}' must be null`);"window"in r&&(l="no-window"),i=nI({method:i.method,headersList:i.headersList,unsafeRequest:i.unsafeRequest,client:KE.settingsObject,window:l,priority:i.priority,origin:i.origin,referrer:i.referrer,referrerPolicy:i.referrerPolicy,mode:i.mode,credentials:i.credentials,cache:i.cache,redirect:i.redirect,integrity:i.integrity,keepalive:i.keepalive,reloadNavigation:i.reloadNavigation,historyNavigation:i.historyNavigation,urlList:[...i.urlList]});let u=Object.keys(r).length!==0;if(u&&(i.mode==="navigate"&&(i.mode="same-origin"),i.reloadNavigation=!1,i.historyNavigation=!1,i.origin="client",i.referrer="client",i.referrerPolicy="",i.url=i.urlList[i.urlList.length-1],i.urlList=[i.url]),r.referrer!==void 0){let S=r.referrer;if(S==="")i.referrer="no-referrer";else{let B;try{B=new URL(S,s)}catch(_){throw new TypeError(`Referrer "${S}" is not a valid URL.`,{cause:_})}B.protocol==="about:"&&B.hostname==="client"||c&&!XV(B,KE.settingsObject.baseUrl)?i.referrer="client":i.referrer=B}}r.referrerPolicy!==void 0&&(i.referrerPolicy=r.referrerPolicy);let d;if(r.mode!==void 0?d=r.mode:d=o,d==="navigate")throw Se.errors.exception({header:"Request constructor",message:"invalid request mode navigate."});if(d!=null&&(i.mode=d),r.credentials!==void 0&&(i.credentials=r.credentials),r.cache!==void 0&&(i.cache=r.cache),i.cache==="only-if-cached"&&i.mode!=="same-origin")throw new TypeError("'only-if-cached' can be set only with 'same-origin' mode");if(r.redirect!==void 0&&(i.redirect=r.redirect),r.integrity!=null&&(i.integrity=String(r.integrity)),r.keepalive!==void 0&&(i.keepalive=!!r.keepalive),r.method!==void 0){let S=r.method,B=xxe[S];if(B!==void 0)i.method=B;else{if(!_xe(S))throw new TypeError(`'${S}' is not a valid HTTP method.`);let _=S.toUpperCase();if(Bxe.has(_))throw new TypeError(`'${S}' HTTP method is unsupported.`);S=Oxe[_]??S,i.method=S}!t4&&i.method==="patch"&&(process.emitWarning("Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.",{code:"UNDICI-FETCH-patch"}),t4=!0)}r.signal!==void 0&&(a=r.signal),this.#i=i;let A=new AbortController;if(this.#e=A.signal,a!=null)if(a.aborted)A.abort(a.reason);else{this[$xe]=A;let S=new WeakRef(A),B=e4(S);oT&&i4(a)===Lxe&&Pxe(1500,a),XE.addAbortListener(a,B),o4.register(A,{signal:a,abort:B},B)}if(this.#n=new r4(tI),n4(this.#n,i.headersList),iT(this.#n,"request"),d==="no-cors"){if(!vxe.has(i.method))throw new TypeError(`'${i.method} is unsupported in no-cors mode.`);iT(this.#n,"request-no-cors")}if(u){let S=ZV(this.#n),B=r.headers!==void 0?r.headers:new eI(S);if(S.clear(),B instanceof eI){for(let{name:_,value:v}of B.rawValues())S.append(_,v,!1);S.cookies=B.cookies}else Sxe(this.#n,B)}let p=Se.is.Request(e)?e.#i.body:null;if((r.body!=null||p!=null)&&(i.method==="GET"||i.method==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body.");let h=null;if(r.body!=null){let[S,B]=Ixe(r.body,i.keepalive);h=S,B&&!ZV(this.#n).contains("content-type",!0)&&this.#n.append("content-type",B,!0)}let f=h??p;if(f!=null&&f.source==null){if(h!=null&&r.duplex==null)throw new TypeError("RequestInit: duplex option is required when sending a body.");if(i.mode!=="same-origin"&&i.mode!=="cors")throw new TypeError('If request is made from ReadableStream, mode should be "same-origin" or "cors"');i.useCORSPreflightFlag=!0}let E=f;if(h==null&&p!=null){if(JV(e.#i))throw new TypeError("Cannot construct a Request with a Request object that has already been used.");let S=new TransformStream;p.stream.pipeThrough(S),E={source:p.source,length:p.length,stream:S.readable}}this.#i.body=E}get method(){return Se.brandCheck(this,t),this.#i.method}get url(){return Se.brandCheck(this,t),Uxe(this.#i.url)}get headers(){return Se.brandCheck(this,t),this.#n}get destination(){return Se.brandCheck(this,t),this.#i.destination}get referrer(){return Se.brandCheck(this,t),this.#i.referrer==="no-referrer"?"":this.#i.referrer==="client"?"about:client":this.#i.referrer.toString()}get referrerPolicy(){return Se.brandCheck(this,t),this.#i.referrerPolicy}get mode(){return Se.brandCheck(this,t),this.#i.mode}get credentials(){return Se.brandCheck(this,t),this.#i.credentials}get cache(){return Se.brandCheck(this,t),this.#i.cache}get redirect(){return Se.brandCheck(this,t),this.#i.redirect}get integrity(){return Se.brandCheck(this,t),this.#i.integrity}get keepalive(){return Se.brandCheck(this,t),this.#i.keepalive}get isReloadNavigation(){return Se.brandCheck(this,t),this.#i.reloadNavigation}get isHistoryNavigation(){return Se.brandCheck(this,t),this.#i.historyNavigation}get signal(){return Se.brandCheck(this,t),this.#e}get body(){return Se.brandCheck(this,t),this.#i.body?this.#i.body.stream:null}get bodyUsed(){return Se.brandCheck(this,t),!!this.#i.body&&XE.isDisturbed(this.#i.body.stream)}get duplex(){return Se.brandCheck(this,t),"half"}clone(){if(Se.brandCheck(this,t),JV(this.#i))throw new TypeError("unusable");let e=a4(this.#i),r=new AbortController;if(this.signal.aborted)r.abort(this.signal.reason);else{let n=rI.get(this.signal);n===void 0&&(n=new Set,rI.set(this.signal,n));let i=new WeakRef(r);n.add(i),XE.addAbortListener(r.signal,e4(i))}return c4(e,this.#t,r.signal,wxe(this.#n))}[KV.inspect.custom](e,r){r.depth===null&&(r.depth=2),r.colors??=!0;let n={method:this.method,url:this.url,headers:this.headers,destination:this.destination,referrer:this.referrer,referrerPolicy:this.referrerPolicy,mode:this.mode,credentials:this.credentials,cache:this.cache,redirect:this.redirect,integrity:this.integrity,keepalive:this.keepalive,isReloadNavigation:this.isReloadNavigation,isHistoryNavigation:this.isHistoryNavigation,signal:this.signal};return`Request ${KV.formatWithOptions(r,n)}`}static setRequestSignal(e,r){return e.#e=r,e}static getRequestDispatcher(e){return e.#t}static setRequestDispatcher(e,r){e.#t=r}static setRequestHeaders(e,r){e.#n=r}static getRequestState(e){return e.#i}static setRequestState(e,r){e.#i=r}},{setRequestSignal:Fxe,getRequestDispatcher:jxe,setRequestDispatcher:zxe,setRequestHeaders:qxe,getRequestState:s4,setRequestState:Hxe}=sn;Reflect.deleteProperty(sn,"setRequestSignal");Reflect.deleteProperty(sn,"getRequestDispatcher");Reflect.deleteProperty(sn,"setRequestDispatcher");Reflect.deleteProperty(sn,"setRequestHeaders");Reflect.deleteProperty(sn,"getRequestState");Reflect.deleteProperty(sn,"setRequestState");Cxe(sn,s4);function nI(t){return{method:t.method??"GET",localURLsOnly:t.localURLsOnly??!1,unsafeRequest:t.unsafeRequest??!1,body:t.body??null,client:t.client??null,reservedClient:t.reservedClient??null,replacesClientId:t.replacesClientId??"",window:t.window??"client",keepalive:t.keepalive??!1,serviceWorkers:t.serviceWorkers??"all",initiator:t.initiator??"",destination:t.destination??"",priority:t.priority??null,origin:t.origin??"client",policyContainer:t.policyContainer??"client",referrer:t.referrer??"client",referrerPolicy:t.referrerPolicy??"",mode:t.mode??"no-cors",useCORSPreflightFlag:t.useCORSPreflightFlag??!1,credentials:t.credentials??"same-origin",useCredentials:t.useCredentials??!1,cache:t.cache??"default",redirect:t.redirect??"follow",integrity:t.integrity??"",cryptoGraphicsNonceMetadata:t.cryptoGraphicsNonceMetadata??"",parserMetadata:t.parserMetadata??"",reloadNavigation:t.reloadNavigation??!1,historyNavigation:t.historyNavigation??!1,userActivation:t.userActivation??!1,taintedOrigin:t.taintedOrigin??!1,redirectCount:t.redirectCount??0,responseTainting:t.responseTainting??"basic",preventNoCacheCacheControlHeaderModification:t.preventNoCacheCacheControlHeaderModification??!1,done:t.done??!1,timingAllowFailed:t.timingAllowFailed??!1,useURLCredentials:t.useURLCredentials??void 0,traversableForUserPrompts:t.traversableForUserPrompts??"client",urlList:t.urlList,url:t.urlList[0],headersList:t.headersList?new eI(t.headersList):new eI}}function a4(t){let e=nI({...t,body:null});return t.body!=null&&(e.body=bxe(t.body)),e}function c4(t,e,r,n){let i=new sn(tI);Hxe(i,t),zxe(i,e),Fxe(i,r);let o=new r4(tI);return qxe(i,o),n4(o,t.headersList),iT(o,n),i}Object.defineProperties(sn.prototype,{method:tr,url:tr,headers:tr,redirect:tr,clone:tr,signal:tr,duplex:tr,destination:tr,body:tr,bodyUsed:tr,isHistoryNavigation:tr,isReloadNavigation:tr,keepalive:tr,integrity:tr,cache:tr,credentials:tr,attribute:tr,referrerPolicy:tr,referrer:tr,mode:tr,[Symbol.toStringTag]:{value:"Request",configurable:!0}});Se.is.Request=Se.util.MakeTypeAssertion(sn);Se.converters.RequestInfo=function(t){return typeof t=="string"?Se.converters.USVString(t):Se.is.Request(t)?t:Se.converters.USVString(t)};Se.converters.RequestInit=Se.dictionaryConverter([{key:"method",converter:Se.converters.ByteString},{key:"headers",converter:Se.converters.HeadersInit},{key:"body",converter:Se.nullableConverter(Se.converters.BodyInit)},{key:"referrer",converter:Se.converters.USVString},{key:"referrerPolicy",converter:Se.converters.DOMString,allowedValues:Qxe},{key:"mode",converter:Se.converters.DOMString,allowedValues:Dxe},{key:"credentials",converter:Se.converters.DOMString,allowedValues:kxe},{key:"cache",converter:Se.converters.DOMString,allowedValues:Rxe},{key:"redirect",converter:Se.converters.DOMString,allowedValues:Txe},{key:"integrity",converter:Se.converters.DOMString},{key:"keepalive",converter:Se.converters.boolean},{key:"signal",converter:Se.nullableConverter(t=>Se.converters.AbortSignal(t,"RequestInit","signal"))},{key:"window",converter:Se.converters.any},{key:"duplex",converter:Se.converters.DOMString,allowedValues:Nxe},{key:"dispatcher",converter:Se.converters.any},{key:"priority",converter:Se.converters.DOMString,allowedValues:["high","low","auto"],defaultValue:()=>"auto"}]);l4.exports={Request:sn,makeRequest:nI,fromInnerRequest:c4,cloneRequest:a4,getRequestDispatcher:jxe,getRequestState:s4}});var m4=y((Wqe,g4)=>{"use strict";var Gxe=require("assert"),{runtimeFeatures:d4}=Ps(),bl=new Map([["sha256",0],["sha384",1],["sha512",2]]),sT;if(d4.has("crypto")){sT=require("crypto");let t=sT.getHashes();t.length===0&&bl.clear();for(let e of bl.keys())t.includes(e)===!1&&bl.delete(e)}else bl.clear();var u4=Map.prototype.get.bind(bl),aT=Map.prototype.has.bind(bl),Yxe=d4.has("crypto")===!1||bl.size===0?()=>!0:(t,e)=>{let r=p4(e);if(r.length===0)return!0;let n=A4(r);for(let i of n){let o=i.alg,s=i.val,a=h4(o,t);if(f4(a,s))return!0}return!1};function A4(t){let e=[],r=null;for(let n of t){if(Gxe(aT(n.alg),"Invalid SRI hash algorithm token"),e.length===0){e.push(n),r=n;continue}let i=r.alg,o=u4(i),s=n.alg,a=u4(s);a<o||(a>o?(r=n,e[0]=n,e.length=1):e.push(n))}return e}function p4(t){let e=[];for(let r of t.split(" ")){let i=r.split("?",1)[0],o="",s=[i.slice(0,6),i.slice(7)],a=s[0];if(!aT(a))continue;s[1]&&(o=s[1]);let c={alg:a,val:o};e.push(c)}return e}var h4=(t,e)=>sT.hash(t,e,"base64");function f4(t,e){let r=t.length;r!==0&&t[r-1]==="="&&(r-=1),r!==0&&t[r-1]==="="&&(r-=1);let n=e.length;if(n!==0&&e[n-1]==="="&&(n-=1),n!==0&&e[n-1]==="="&&(n-=1),r!==n)return!1;for(let i=0;i<r;++i)if(!(t[i]===e[i]||t[i]==="+"&&e[i]==="-"||t[i]==="/"&&e[i]==="_"))return!1;return!0}g4.exports={applyAlgorithmToBytes:h4,bytesMatch:Yxe,caseSensitiveMatch:f4,isValidSRIHashAlgorithm:aT,getStrongestMetadata:A4,parseMetadata:p4}});var Eh=y((Jqe,k4)=>{"use strict";var{makeNetworkError:At,makeAppropriateNetworkError:mh,filterResponse:cT,makeResponse:iI,fromInnerResponse:Vxe,getResponseState:Wxe}=gh(),{HeadersList:lT}=Il(),{Request:Jxe,cloneRequest:Zxe,getRequestDispatcher:Kxe,getRequestState:Xxe}=ud(),Li=require("zlib"),{makePolicyContainer:eUe,clonePolicyContainer:tUe,requestBadPort:rUe,TAOCheck:nUe,appendRequestOriginHeader:iUe,responseLocationURL:oUe,requestCurrentURL:Un,setRequestReferrerPolicyOnRedirect:sUe,tryUpgradeRequestToAPotentiallyTrustworthyURL:aUe,createOpaqueTimingInfo:fT,appendFetchMetadata:cUe,corsCheck:lUe,crossOriginResourcePolicyCheck:uUe,determineRequestsReferrer:dUe,coarsenedSharedCurrentTime:yh,sameOrigin:pT,isCancelled:Ja,isAborted:y4,isErrorLike:AUe,fullyReadBody:pUe,readableStreamClose:hUe,urlIsLocal:fUe,urlIsHttpHttpsScheme:cI,urlHasHttpsScheme:gUe,clampAndCoarsenConnectionTimingInfo:mUe,simpleRangeHeaderValue:yUe,buildContentRange:EUe,createInflate:IUe,extractMimeType:CUe,hasAuthenticationEntry:bUe,includesCredentials:E4,isTraversableNavigable:SUe}=Qn(),Sl=require("assert"),{safelyExtractBody:lI,extractBody:I4}=$u(),{redirectStatusSet:w4,nullBodyStatus:_4,safeMethodsSet:wUe,requestBodyHeader:_Ue,subresourceSet:BUe}=Bp(),vUe=require("events"),{Readable:QUe,pipeline:TUe,finished:DUe,isErrored:kUe,isReadable:oI}=require("stream"),{addAbortListener:RUe,bufferToLowerCasedHeaderName:C4}=De(),{dataURLProcessor:NUe,serializeAMimeType:OUe,minimizeSupportedMimeType:xUe}=ci(),{getGlobalDispatcher:UUe}=FE(),{webidl:gT}=Cr(),{STATUS_CODES:b4}=require("http"),{bytesMatch:MUe}=m4(),{createDeferredPromise:PUe}=kp(),{isomorphicEncode:sI}=Ms(),{runtimeFeatures:LUe}=Ps(),$Ue=LUe.has("zstd"),FUe=["GET","HEAD"],jUe=typeof __UNDICI_IS_NODE__<"u"||typeof esbuildDetection<"u"?"node":"undici",uT,aI=class extends vUe{constructor(e){super(),this.dispatcher=e,this.connection=null,this.dump=!1,this.state="ongoing"}terminate(e){this.state==="ongoing"&&(this.state="terminated",this.connection?.destroy(e),this.emit("terminated",e))}abort(e){this.state==="ongoing"&&(this.state="aborted",e||(e=new DOMException("The operation was aborted.","AbortError")),this.serializedAbortReason=e,this.connection?.destroy(e),this.emit("terminated",e))}};function zUe(t){B4(t,"fetch")}function qUe(t,e=void 0){gT.argumentLengthCheck(arguments,1,"globalThis.fetch");let r=PUe(),n;try{n=new Jxe(t,e)}catch(u){return r.reject(u),r.promise}let i=Xxe(n);if(n.signal.aborted)return dT(r,i,null,n.signal.reason,null),r.promise;i.client.globalObject?.constructor?.name==="ServiceWorkerGlobalScope"&&(i.serviceWorkers="none");let s=null,a=!1,c=null;return RUe(n.signal,()=>{a=!0,Sl(c!=null),c.abort(n.signal.reason);let u=s?.deref();dT(r,i,u,n.signal.reason,c.controller)}),c=Q4({request:i,processResponseEndOfBody:zUe,processResponse:u=>{if(!a){if(u.aborted){dT(r,i,s,c.serializedAbortReason,c.controller);return}if(u.type==="error"){r.reject(new TypeError("fetch failed",{cause:u.error}));return}s=new WeakRef(Vxe(u,"immutable")),r.resolve(s.deref()),r=null}},dispatcher:Kxe(n),requestObject:n}),r.promise}function B4(t,e="other"){if(t.type==="error"&&t.aborted||!t.urlList?.length)return;let r=t.urlList[0],n=t.timingInfo,i=t.cacheState;cI(r)&&n!==null&&(t.timingAllowPassed||(n=fT({startTime:n.startTime}),i=""),n.endTime=yh(),t.timingInfo=n,v4(n,r.href,e,globalThis,i,"",t.status))}var v4=performance.markResourceTiming;function dT(t,e,r,n,i){if(t&&t.reject(n),e.body?.stream!=null&&oI(e.body.stream)&&e.body.stream.cancel(n).catch(s=>{if(s.code!=="ERR_INVALID_STATE")throw s}),r==null)return;let o=Wxe(r);o.body?.stream!=null&&oI(o.body.stream)&&i.error(n)}function Q4({request:t,processRequestBodyChunkLength:e,processRequestEndOfBody:r,processResponse:n,processResponseEndOfBody:i,processResponseConsumeBody:o,useParallelQueue:s=!1,dispatcher:a=UUe(),requestObject:c=null}){Sl(a);let l=null,u=!1;t.client!=null&&(l=t.client.globalObject,u=t.client.crossOriginIsolatedCapability);let d=yh(u),A=fT({startTime:d}),p={controller:new aI(a),request:t,timingInfo:A,processRequestBodyChunkLength:e,processRequestEndOfBody:r,processResponse:n,processResponseConsumeBody:o,processResponseEndOfBody:i,taskDestination:l,crossOriginIsolatedCapability:u,requestObject:c};return Sl(!t.body||t.body.stream),t.window==="client"&&(t.window=t.client?.globalObject?.constructor?.name==="Window"?t.client:"no-window"),t.origin==="client"&&(t.origin=t.client.origin),t.policyContainer==="client"&&(t.client!=null?t.policyContainer=tUe(t.client.policyContainer):t.policyContainer=eUe()),t.headersList.contains("accept",!0)||t.headersList.append("accept","*/*",!0),t.headersList.contains("accept-language",!0)||t.headersList.append("accept-language","*",!0),t.priority,BUe.has(t.destination),T4(p,!1),p.controller}async function T4(t,e){try{let r=t.request,n=null;if(r.localURLsOnly&&!fUe(Un(r))&&(n=At("local URLs only")),aUe(r),rUe(r)==="blocked"&&(n=At("bad port")),r.referrerPolicy===""&&(r.referrerPolicy=r.policyContainer.referrerPolicy),r.referrer!=="no-referrer"&&(r.referrer=dUe(r)),n===null){let o=Un(r);pT(o,r.url)&&r.responseTainting==="basic"||o.protocol==="data:"||r.mode==="navigate"||r.mode==="websocket"?(r.responseTainting="basic",n=await S4(t)):r.mode==="same-origin"?n=At('request mode cannot be "same-origin"'):r.mode==="no-cors"?r.redirect!=="follow"?n=At('redirect mode cannot be "follow" for "no-cors" request'):(r.responseTainting="opaque",n=await S4(t)):cI(Un(r))?(r.responseTainting="cors",n=await D4(t)):n=At("URL scheme must be a HTTP(S) scheme")}if(e)return n;n.status!==0&&!n.internalResponse&&(r.responseTainting,r.responseTainting==="basic"?n=cT(n,"basic"):r.responseTainting==="cors"?n=cT(n,"cors"):r.responseTainting==="opaque"?n=cT(n,"opaque"):Sl(!1));let i=n.status===0?n:n.internalResponse;if(i.urlList.length===0&&i.urlList.push(...r.urlList),r.timingAllowFailed||(n.timingAllowPassed=!0),n.type==="opaque"&&i.status===206&&i.rangeRequested&&!r.headers.contains("range",!0)&&(n=i=At()),n.status!==0&&(r.method==="HEAD"||r.method==="CONNECT"||_4.includes(i.status))&&(i.body=null,t.controller.dump=!0),r.integrity){let o=a=>AT(t,At(a));if(r.responseTainting==="opaque"||n.body==null){o(n.error);return}let s=a=>{if(!MUe(a,r.integrity)){o("integrity mismatch");return}n.body=lI(a)[0],AT(t,n)};pUe(n.body,s,o)}else AT(t,n)}catch(r){t.controller.terminate(r)}}function S4(t){if(Ja(t)&&t.request.redirectCount===0)return Promise.resolve(mh(t));let{request:e}=t,{protocol:r}=Un(e);switch(r){case"about:":return Promise.resolve(At("about scheme is not supported"));case"blob:":{uT||(uT=require("buffer").resolveObjectURL);let n=Un(e);if(n.search.length!==0)return Promise.resolve(At("NetworkError when attempting to fetch resource."));let i=uT(n.toString());if(e.method!=="GET"||!gT.is.Blob(i))return Promise.resolve(At("invalid method"));let o=iI(),s=i.size,a=sI(`${s}`),c=i.type;if(e.headersList.contains("range",!0)){o.rangeRequested=!0;let l=e.headersList.get("range",!0),u=yUe(l,!0);if(u==="failure")return Promise.resolve(At("failed to fetch the data URL"));let{rangeStartValue:d,rangeEndValue:A}=u;if(d===null)d=s-A,A=d+A-1;else{if(d>=s)return Promise.resolve(At("Range start is greater than the blob's size."));(A===null||A>=s)&&(A=s-1)}let p=i.slice(d,A+1,c),h=I4(p);o.body=h[0];let f=sI(`${p.size}`),E=EUe(d,A,s);o.status=206,o.statusText="Partial Content",o.headersList.set("content-length",f,!0),o.headersList.set("content-type",c,!0),o.headersList.set("content-range",E,!0)}else{let l=I4(i);o.statusText="OK",o.body=l[0],o.headersList.set("content-length",a,!0),o.headersList.set("content-type",c,!0)}return Promise.resolve(o)}case"data:":{let n=Un(e),i=NUe(n);if(i==="failure")return Promise.resolve(At("failed to fetch the data URL"));let o=OUe(i.mimeType);return Promise.resolve(iI({statusText:"OK",headersList:[["content-type",{name:"Content-Type",value:o}]],body:lI(i.body)[0]}))}case"file:":return Promise.resolve(At("not implemented... yet..."));case"http:":case"https:":return D4(t).catch(n=>At(n));default:return Promise.resolve(At("unknown scheme"))}}function HUe(t,e){t.request.done=!0,t.processResponseDone!=null&&queueMicrotask(()=>t.processResponseDone(e))}function AT(t,e){let r=t.timingInfo,n=()=>{let o=Date.now();t.request.destination==="document"&&(t.controller.fullTimingInfo=r),t.controller.reportTimingSteps=()=>{if(!cI(t.request.url))return;r.endTime=o;let a=e.cacheState,c=e.bodyInfo;e.timingAllowPassed||(r=fT(r),a="");let l=0;if(t.request.mode!=="navigate"||!e.hasCrossOriginRedirects){l=e.status;let u=CUe(e.headersList);u!=="failure"&&(c.contentType=xUe(u))}t.request.initiatorType!=null&&v4(r,t.request.url.href,t.request.initiatorType,globalThis,a,c,l)};let s=()=>{t.request.done=!0,t.processResponseEndOfBody!=null&&queueMicrotask(()=>t.processResponseEndOfBody(e)),t.request.initiatorType!=null&&t.controller.reportTimingSteps()};queueMicrotask(()=>s())};t.processResponse!=null&&queueMicrotask(()=>{t.processResponse(e),t.processResponse=null});let i=e.type==="error"?e:e.internalResponse??e;i.body==null?n():DUe(i.body.stream,()=>{n()})}async function D4(t){let e=t.request,r=null,n=null,i=t.timingInfo;if(e.serviceWorkers,r===null){if(e.redirect==="follow"&&(e.serviceWorkers="none"),n=r=await hT(t),e.responseTainting==="cors"&&lUe(e,r)==="failure")return At("cors failure");nUe(e,r)==="failure"&&(e.timingAllowFailed=!0)}return(e.responseTainting==="opaque"||r.type==="opaque")&&uUe(e.origin,e.client,e.destination,n)==="blocked"?At("blocked"):(w4.has(n.status)&&(e.redirect!=="manual"&&t.controller.connection.destroy(void 0,!1),e.redirect==="error"?r=At("unexpected redirect"):e.redirect==="manual"?r=n:e.redirect==="follow"?r=await GUe(t,r):Sl(!1)),r.timingInfo=i,r)}function GUe(t,e){let r=t.request,n=e.internalResponse?e.internalResponse:e,i;try{if(i=oUe(n,Un(r).hash),i==null)return e}catch(s){return Promise.resolve(At(s))}if(!cI(i))return Promise.resolve(At("URL scheme must be a HTTP(S) scheme"));if(r.redirectCount===20)return Promise.resolve(At("redirect count exceeded"));if(r.redirectCount+=1,r.mode==="cors"&&(i.username||i.password)&&!pT(r,i))return Promise.resolve(At('cross origin not allowed for request mode "cors"'));if(r.responseTainting==="cors"&&(i.username||i.password))return Promise.resolve(At('URL cannot contain credentials for request mode "cors"'));if(n.status!==303&&r.body!=null&&r.body.source==null)return Promise.resolve(At());if([301,302].includes(n.status)&&r.method==="POST"||n.status===303&&!FUe.includes(r.method)){r.method="GET",r.body=null;for(let s of _Ue)r.headersList.delete(s)}pT(Un(r),i)||(r.headersList.delete("authorization",!0),r.headersList.delete("proxy-authorization",!0),r.headersList.delete("cookie",!0),r.headersList.delete("host",!0)),r.body!=null&&(Sl(r.body.source!=null),r.body=lI(r.body.source)[0]);let o=t.timingInfo;return o.redirectEndTime=o.postRedirectStartTime=yh(t.crossOriginIsolatedCapability),o.redirectStartTime===0&&(o.redirectStartTime=o.startTime),r.urlList.push(i),sUe(r,n),T4(t,!0)}async function hT(t,e=!1,r=!1){let n=t.request,i=null,o=null,s=null,a=null,c=!1;n.window==="no-window"&&n.redirect==="error"?(i=t,o=n):(o=Zxe(n),i={...t},i.request=o);let l=n.credentials==="include"||n.credentials==="same-origin"&&n.responseTainting==="basic",u=o.body?o.body.length:null,d=null;if(o.body==null&&["POST","PUT"].includes(o.method)&&(d="0"),u!=null&&(d=sI(`${u}`)),d!=null&&!o.headersList.contains("content-length",!0)&&o.headersList.append("content-length",d,!0),u!=null&&o.keepalive,gT.is.URL(o.referrer)&&o.headersList.append("referer",sI(o.referrer.href),!0),iUe(o),cUe(o),o.headersList.contains("user-agent",!0)||o.headersList.append("user-agent",jUe,!0),o.cache==="default"&&(o.headersList.contains("if-modified-since",!0)||o.headersList.contains("if-none-match",!0)||o.headersList.contains("if-unmodified-since",!0)||o.headersList.contains("if-match",!0)||o.headersList.contains("if-range",!0))&&(o.cache="no-store"),o.cache==="no-cache"&&!o.preventNoCacheCacheControlHeaderModification&&!o.headersList.contains("cache-control",!0)&&o.headersList.append("cache-control","max-age=0",!0),(o.cache==="no-store"||o.cache==="reload")&&(o.headersList.contains("pragma",!0)||o.headersList.append("pragma","no-cache",!0),o.headersList.contains("cache-control",!0)||o.headersList.append("cache-control","no-cache",!0)),o.headersList.contains("range",!0)&&o.headersList.append("accept-encoding","identity",!0),o.headersList.contains("accept-encoding",!0)||(gUe(Un(o))?o.headersList.append("accept-encoding","br, gzip, deflate",!0):o.headersList.append("accept-encoding","gzip, deflate",!0)),o.headersList.delete("host",!0),l&&!o.headersList.contains("authorization",!0)){let A=null;if(!(bUe(o)&&(o.useURLCredentials===void 0||!E4(Un(o))))){if(E4(Un(o))&&e){let{username:p,password:h}=Un(o);A=`Basic ${Buffer.from(`${p}:${h}`).toString("base64")}`}}A!==null&&o.headersList.append("Authorization",A,!1)}if(a==null&&(o.cache="no-store"),o.cache!=="no-store"&&o.cache,s==null){if(o.cache==="only-if-cached")return At("only if cached");let A=await YUe(i,l,r);!wUe.has(o.method)&&A.status>=200&&A.status<=399,c&&A.status,s==null&&(s=A)}if(s.urlList=[...o.urlList],o.headersList.contains("range",!0)&&(s.rangeRequested=!0),s.requestIncludesCredentials=l,s.status===401&&o.responseTainting!=="cors"&&l&&(n.useURLCredentials!==void 0||SUe(n.traversableForUserPrompts))){if(n.body!=null){if(n.body.source==null)return s;n.body=lI(n.body.source)[0]}if(n.useURLCredentials===void 0||e)return Ja(t)?mh(t):s;t.controller.connection.destroy(),s=await hT(t,!0)}if(s.status===407)return n.window==="no-window"?At():Ja(t)?mh(t):At("proxy authentication required");if(s.status===421&&!r&&(n.body==null||n.body.source!=null)){if(Ja(t))return mh(t);t.controller.connection.destroy(),s=await hT(t,e,!0)}return s}async function YUe(t,e=!1,r=!1){Sl(!t.controller.connection||t.controller.connection.destroyed),t.controller.connection={abort:null,destroyed:!1,destroy(h,f=!0){this.destroyed||(this.destroyed=!0,f&&this.abort?.(h??new DOMException("The operation was aborted.","AbortError")))}};let n=t.request,i=null,o=t.timingInfo;null==null&&(n.cache="no-store");let a=r?"yes":"no";n.mode;let c=null;if(n.body==null&&t.processRequestEndOfBody)queueMicrotask(()=>t.processRequestEndOfBody());else if(n.body!=null){let h=async function*(S){Ja(t)||(yield S,t.processRequestBodyChunkLength?.(S.byteLength))},f=()=>{Ja(t)||t.processRequestEndOfBody&&t.processRequestEndOfBody()},E=S=>{Ja(t)||(S.name==="AbortError"?t.controller.abort():t.controller.terminate(S))};c=(async function*(){try{for await(let S of n.body.stream)yield*h(S);f()}catch(S){E(S)}})()}try{let{body:h,status:f,statusText:E,headersList:S,socket:B}=await p({body:c});if(B)i=iI({status:f,statusText:E,headersList:S,socket:B});else{let _=h[Symbol.asyncIterator]();t.controller.next=()=>_.next(),i=iI({status:f,statusText:E,headersList:S})}}catch(h){return h.name==="AbortError"?(t.controller.connection.destroy(),mh(t,h)):At(h)}let l=()=>t.controller.resume(),u=h=>{Ja(t)||t.controller.abort(h)},d=new ReadableStream({start(h){t.controller.controller=h},pull:l,cancel:u,type:"bytes"});i.body={stream:d,source:null,length:null},t.controller.resume||t.controller.on("terminated",A),t.controller.resume=async()=>{for(;;){let h,f;try{let{done:S,value:B}=await t.controller.next();if(y4(t))break;h=S?void 0:B}catch(S){t.controller.ended&&!o.encodedBodySize?h=void 0:(h=S,f=!0)}if(h===void 0){hUe(t.controller.controller),HUe(t,i);return}if(o.decodedBodySize+=h?.byteLength??0,f){t.controller.terminate(h);return}let E=new Uint8Array(h);if(E.byteLength&&t.controller.controller.enqueue(E),kUe(d)){t.controller.terminate();return}if(t.controller.controller.desiredSize<=0)return}};function A(h){y4(t)?(i.aborted=!0,oI(d)&&t.controller.controller.error(t.controller.serializedAbortReason)):oI(d)&&t.controller.controller.error(new TypeError("terminated",{cause:AUe(h)?h:void 0})),t.controller.connection.destroy()}return i;function p({body:h}){let f=Un(n),E=t.controller.dispatcher,S=f.pathname+f.search,B=f.search.length===0&&f.href[f.href.length-f.hash.length-1]==="?";return new Promise((_,v)=>E.dispatch({path:B?`${S}?`:S,origin:f.origin,method:n.method,body:E.isMockActive?n.body&&(n.body.source||n.body.stream):h,headers:n.headersList.entries,maxRedirections:0,upgrade:n.mode==="websocket"?"websocket":void 0},{body:null,abort:null,onConnect(T){let{connection:L}=t.controller;o.finalConnectionTimingInfo=mUe(void 0,o.postRedirectStartTime,t.crossOriginIsolatedCapability),L.destroyed?T(new DOMException("The operation was aborted.","AbortError")):(t.controller.on("terminated",T),this.abort=L.abort=T),o.finalNetworkRequestStartTime=yh(t.crossOriginIsolatedCapability)},onResponseStarted(){o.finalNetworkResponseStartTime=yh(t.crossOriginIsolatedCapability)},onHeaders(T,L,k,P){if(T<200)return!1;let U=new lT;for(let tt=0;tt<L.length;tt+=2){let Ht=C4(L[tt]),Nt=L[tt+1];if(Array.isArray(Nt)&&!Buffer.isBuffer(L[tt+1]))for(let kr of Nt)U.append(Ht,kr.toString("latin1"),!0);else U.append(Ht,Nt.toString("latin1"),!0)}let K=U.get("location",!0);this.body=new QUe({read:k});let Ae=K&&n.redirect==="follow"&&w4.has(T),Re=[];if(n.method!=="HEAD"&&n.method!=="CONNECT"&&!_4.includes(T)&&!Ae){let tt=U.get("content-encoding",!0),Ht=tt?tt.toLowerCase().split(","):[],Nt=5;if(Ht.length>Nt)return v(new Error(`too many content-encodings in response: ${Ht.length}, maximum allowed is ${Nt}`)),!0;for(let kr=Ht.length-1;kr>=0;--kr){let qr=Ht[kr].trim();if(qr==="x-gzip"||qr==="gzip")Re.push(Li.createGunzip({flush:Li.constants.Z_SYNC_FLUSH,finishFlush:Li.constants.Z_SYNC_FLUSH}));else if(qr==="deflate")Re.push(IUe({flush:Li.constants.Z_SYNC_FLUSH,finishFlush:Li.constants.Z_SYNC_FLUSH}));else if(qr==="br")Re.push(Li.createBrotliDecompress({flush:Li.constants.BROTLI_OPERATION_FLUSH,finishFlush:Li.constants.BROTLI_OPERATION_FLUSH}));else if(qr==="zstd"&&$Ue)Re.push(Li.createZstdDecompress({flush:Li.constants.ZSTD_e_continue,finishFlush:Li.constants.ZSTD_e_end}));else{Re.length=0;break}}}let Ge=this.onError.bind(this);return _({status:T,statusText:P,headersList:U,body:Re.length?TUe(this.body,...Re,tt=>{tt&&this.onError(tt)}).on("error",Ge):this.body.on("error",Ge)}),!0},onData(T){if(t.controller.dump)return;let L=T;return o.encodedBodySize+=L.byteLength,this.body.push(L)},onComplete(){this.abort&&t.controller.off("terminated",this.abort),t.controller.ended=!0,this.body.push(null)},onError(T){this.abort&&t.controller.off("terminated",this.abort),this.body?.destroy(T),t.controller.terminate(T),v(T)},onRequestUpgrade(T,L,k,P){if(P.session!=null&&L!==200||P.session==null&&L!==101)return!1;let U=new lT;for(let[K,Ae]of Object.entries(k)){if(Ae==null)continue;let Re=K.toLowerCase();if(Array.isArray(Ae))for(let Ge of Ae)U.append(Re,String(Ge),!0);else U.append(Re,String(Ae),!0)}return _({status:L,statusText:b4[L],headersList:U,socket:P}),!0},onUpgrade(T,L,k){if(k.session!=null&&T!==200||k.session==null&&T!==101)return!1;let P=new lT;for(let U=0;U<L.length;U+=2){let K=C4(L[U]),Ae=L[U+1];if(Array.isArray(Ae)&&!Buffer.isBuffer(L[U+1]))for(let Re of Ae)P.append(K,Re.toString("latin1"),!0);else P.append(K,Ae.toString("latin1"),!0)}return _({status:T,statusText:b4[T],headersList:P,socket:k}),!0}}))}}k4.exports={fetch:qUe,Fetch:aI,fetching:Q4,finalizeAndReportTiming:B4}});var O4=y((Zqe,N4)=>{"use strict";var VUe=require("assert"),{URLSerializer:R4}=ci(),{isValidHeaderName:WUe}=Qn();function JUe(t,e,r=!1){let n=R4(t,r),i=R4(e,r);return n===i}function ZUe(t){VUe(t!==null);let e=[];for(let r of t.split(","))r=r.trim(),WUe(r)&&e.push(r);return e}N4.exports={urlEquals:JUe,getFieldValues:ZUe}});var P4=y((Kqe,M4)=>{"use strict";var mT=require("assert"),{kConstruct:KUe}=ut(),{urlEquals:XUe,getFieldValues:yT}=O4(),{kEnumerableProperty:wl,isDisturbed:eMe}=De(),{webidl:fe}=Cr(),{cloneResponse:x4,fromInnerResponse:tMe,getResponseState:rMe}=gh(),{Request:Ih,fromInnerRequest:nMe,getRequestState:As}=ud(),{fetching:iMe}=Eh(),{urlIsHttpHttpsScheme:uI,readAllBytes:oMe}=Qn(),{createDeferredPromise:dd}=kp(),dI=class t{#e;constructor(){arguments[0]!==KUe&&fe.illegalConstructor(),fe.util.markAsUncloneable(this),this.#e=arguments[1]}async match(e,r={}){fe.brandCheck(this,t);let n="Cache.match";fe.argumentLengthCheck(arguments,1,n),e=fe.converters.RequestInfo(e),r=fe.converters.CacheQueryOptions(r,n,"options");let i=this.#o(e,r,1);if(i.length!==0)return i[0]}async matchAll(e=void 0,r={}){fe.brandCheck(this,t);let n="Cache.matchAll";return e!==void 0&&(e=fe.converters.RequestInfo(e)),r=fe.converters.CacheQueryOptions(r,n,"options"),this.#o(e,r)}async add(e){fe.brandCheck(this,t),fe.argumentLengthCheck(arguments,1,"Cache.add"),e=fe.converters.RequestInfo(e);let n=[e];return await this.addAll(n)}async addAll(e){fe.brandCheck(this,t);let r="Cache.addAll";fe.argumentLengthCheck(arguments,1,r);let n=[],i=[];for(let A of e){if(A===void 0)throw fe.errors.conversionFailed({prefix:r,argument:"Argument 1",types:["undefined is not allowed"]});if(A=fe.converters.RequestInfo(A),typeof A=="string")continue;let p=As(A);if(!uI(p.url)||p.method!=="GET")throw fe.errors.exception({header:r,message:"Expected http/s scheme when method is not GET."})}let o=[];for(let A of e){let p=As(new Ih(A));if(!uI(p.url))throw fe.errors.exception({header:r,message:"Expected http/s scheme."});p.initiator="fetch",p.destination="subresource",i.push(p);let h=dd();o.push(iMe({request:p,processResponse(f){if(f.type==="error"||f.status===206||f.status<200||f.status>299)h.reject(fe.errors.exception({header:"Cache.addAll",message:"Received an invalid status code or the request failed."}));else if(f.headersList.contains("vary")){let E=yT(f.headersList.get("vary"));for(let S of E)if(S==="*"){h.reject(fe.errors.exception({header:"Cache.addAll",message:"invalid vary field value"}));for(let B of o)B.abort();return}}},processResponseEndOfBody(f){if(f.aborted){h.reject(new DOMException("aborted","AbortError"));return}h.resolve(f)}})),n.push(h.promise)}let a=await Promise.all(n),c=[],l=0;for(let A of a){let p={type:"put",request:i[l],response:A};c.push(p),l++}let u=dd(),d=null;try{this.#t(c)}catch(A){d=A}return queueMicrotask(()=>{d===null?u.resolve(void 0):u.reject(d)}),u.promise}async put(e,r){fe.brandCheck(this,t);let n="Cache.put";fe.argumentLengthCheck(arguments,2,n),e=fe.converters.RequestInfo(e),r=fe.converters.Response(r,n,"response");let i=null;if(fe.is.Request(e)?i=As(e):i=As(new Ih(e)),!uI(i.url)||i.method!=="GET")throw fe.errors.exception({header:n,message:"Expected an http/s scheme when method is not GET"});let o=rMe(r);if(o.status===206)throw fe.errors.exception({header:n,message:"Got 206 status"});if(o.headersList.contains("vary")){let p=yT(o.headersList.get("vary"));for(let h of p)if(h==="*")throw fe.errors.exception({header:n,message:"Got * vary field value"})}if(o.body&&(eMe(o.body.stream)||o.body.stream.locked))throw fe.errors.exception({header:n,message:"Response body is locked or disturbed"});let s=x4(o),a=dd();if(o.body!=null){let h=o.body.stream.getReader();oMe(h,a.resolve,a.reject)}else a.resolve(void 0);let c=[],l={type:"put",request:i,response:s};c.push(l);let u=await a.promise;s.body!=null&&(s.body.source=u);let d=dd(),A=null;try{this.#t(c)}catch(p){A=p}return queueMicrotask(()=>{A===null?d.resolve():d.reject(A)}),d.promise}async delete(e,r={}){fe.brandCheck(this,t);let n="Cache.delete";fe.argumentLengthCheck(arguments,1,n),e=fe.converters.RequestInfo(e),r=fe.converters.CacheQueryOptions(r,n,"options");let i=null;if(fe.is.Request(e)){if(i=As(e),i.method!=="GET"&&!r.ignoreMethod)return!1}else mT(typeof e=="string"),i=As(new Ih(e));let o=[],s={type:"delete",request:i,options:r};o.push(s);let a=dd(),c=null,l;try{l=this.#t(o)}catch(u){c=u}return queueMicrotask(()=>{c===null?a.resolve(!!l?.length):a.reject(c)}),a.promise}async keys(e=void 0,r={}){fe.brandCheck(this,t);let n="Cache.keys";e!==void 0&&(e=fe.converters.RequestInfo(e)),r=fe.converters.CacheQueryOptions(r,n,"options");let i=null;if(e!==void 0)if(fe.is.Request(e)){if(i=As(e),i.method!=="GET"&&!r.ignoreMethod)return[]}else typeof e=="string"&&(i=As(new Ih(e)));let o=dd(),s=[];if(e===void 0)for(let a of this.#e)s.push(a[0]);else{let a=this.#n(i,r);for(let c of a)s.push(c[0])}return queueMicrotask(()=>{let a=[];for(let c of s){let l=nMe(c,void 0,new AbortController().signal,"immutable");a.push(l)}o.resolve(Object.freeze(a))}),o.promise}#t(e){let r=this.#e,n=[...r],i=[],o=[];try{for(let s of e){if(s.type!=="delete"&&s.type!=="put")throw fe.errors.exception({header:"Cache.#batchCacheOperations",message:'operation type does not match "delete" or "put"'});if(s.type==="delete"&&s.response!=null)throw fe.errors.exception({header:"Cache.#batchCacheOperations",message:"delete operation should not have an associated response"});if(this.#n(s.request,s.options,i).length)throw new DOMException("???","InvalidStateError");let a;if(s.type==="delete"){if(a=this.#n(s.request,s.options),a.length===0)return[];for(let c of a){let l=r.indexOf(c);mT(l!==-1),r.splice(l,1)}}else if(s.type==="put"){if(s.response==null)throw fe.errors.exception({header:"Cache.#batchCacheOperations",message:"put operation should have an associated response"});let c=s.request;if(!uI(c.url))throw fe.errors.exception({header:"Cache.#batchCacheOperations",message:"expected http or https scheme"});if(c.method!=="GET")throw fe.errors.exception({header:"Cache.#batchCacheOperations",message:"not get method"});if(s.options!=null)throw fe.errors.exception({header:"Cache.#batchCacheOperations",message:"options must not be defined"});a=this.#n(s.request);for(let l of a){let u=r.indexOf(l);mT(u!==-1),r.splice(u,1)}r.push([s.request,s.response]),i.push([s.request,s.response])}o.push([s.request,s.response])}return o}catch(s){throw this.#e.length=0,this.#e=n,s}}#n(e,r,n){let i=[],o=n??this.#e;for(let s of o){let[a,c]=s;this.#i(e,a,c,r)&&i.push(s)}return i}#i(e,r,n=null,i){let o=new URL(e.url),s=new URL(r.url);if(i?.ignoreSearch&&(s.search="",o.search=""),!XUe(o,s,!0))return!1;if(n==null||i?.ignoreVary||!n.headersList.contains("vary"))return!0;let a=yT(n.headersList.get("vary"));for(let c of a){if(c==="*")return!1;let l=r.headersList.get(c),u=e.headersList.get(c);if(l!==u)return!1}return!0}#o(e,r,n=1/0){let i=null;if(e!==void 0)if(fe.is.Request(e)){if(i=As(e),i.method!=="GET"&&!r.ignoreMethod)return[]}else typeof e=="string"&&(i=As(new Ih(e)));let o=[];if(e===void 0)for(let a of this.#e)o.push(a[1]);else{let a=this.#n(i,r);for(let c of a)o.push(c[1])}let s=[];for(let a of o){let c=tMe(x4(a),"immutable");if(s.push(c),s.length>=n)break}return Object.freeze(s)}};Object.defineProperties(dI.prototype,{[Symbol.toStringTag]:{value:"Cache",configurable:!0},match:wl,matchAll:wl,add:wl,addAll:wl,put:wl,delete:wl,keys:wl});var U4=[{key:"ignoreSearch",converter:fe.converters.boolean,defaultValue:()=>!1},{key:"ignoreMethod",converter:fe.converters.boolean,defaultValue:()=>!1},{key:"ignoreVary",converter:fe.converters.boolean,defaultValue:()=>!1}];fe.converters.CacheQueryOptions=fe.dictionaryConverter(U4);fe.converters.MultiCacheQueryOptions=fe.dictionaryConverter([...U4,{key:"cacheName",converter:fe.converters.DOMString}]);fe.converters.Response=fe.interfaceConverter(fe.is.Response,"Response");fe.converters["sequence<RequestInfo>"]=fe.sequenceConverter(fe.converters.RequestInfo);M4.exports={Cache:dI}});var $4=y((Xqe,L4)=>{"use strict";var{Cache:AI}=P4(),{webidl:Tr}=Cr(),{kEnumerableProperty:Ch}=De(),{kConstruct:bh}=ut(),pI=class t{#e=new Map;constructor(){arguments[0]!==bh&&Tr.illegalConstructor(),Tr.util.markAsUncloneable(this)}async match(e,r={}){if(Tr.brandCheck(this,t),Tr.argumentLengthCheck(arguments,1,"CacheStorage.match"),e=Tr.converters.RequestInfo(e),r=Tr.converters.MultiCacheQueryOptions(r),r.cacheName!=null){if(this.#e.has(r.cacheName)){let n=this.#e.get(r.cacheName);return await new AI(bh,n).match(e,r)}}else for(let n of this.#e.values()){let o=await new AI(bh,n).match(e,r);if(o!==void 0)return o}}async has(e){Tr.brandCheck(this,t);let r="CacheStorage.has";return Tr.argumentLengthCheck(arguments,1,r),e=Tr.converters.DOMString(e,r,"cacheName"),this.#e.has(e)}async open(e){Tr.brandCheck(this,t);let r="CacheStorage.open";if(Tr.argumentLengthCheck(arguments,1,r),e=Tr.converters.DOMString(e,r,"cacheName"),this.#e.has(e)){let i=this.#e.get(e);return new AI(bh,i)}let n=[];return this.#e.set(e,n),new AI(bh,n)}async delete(e){Tr.brandCheck(this,t);let r="CacheStorage.delete";return Tr.argumentLengthCheck(arguments,1,r),e=Tr.converters.DOMString(e,r,"cacheName"),this.#e.delete(e)}async keys(){return Tr.brandCheck(this,t),[...this.#e.keys()]}};Object.defineProperties(pI.prototype,{[Symbol.toStringTag]:{value:"CacheStorage",configurable:!0},match:Ch,has:Ch,open:Ch,delete:Ch,keys:Ch});L4.exports={CacheStorage:pI}});var j4=y((eHe,F4)=>{"use strict";F4.exports={maxAttributeValueSize:1024,maxNameValuePairSize:4096}});var CT=y((tHe,G4)=>{"use strict";function sMe(t){for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r>=0&&r<=8||r>=10&&r<=31||r===127)return!0}return!1}function ET(t){for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r<33||r>126||r===34||r===40||r===41||r===60||r===62||r===64||r===44||r===59||r===58||r===92||r===47||r===91||r===93||r===63||r===61||r===123||r===125)throw new Error("Invalid cookie name")}}function IT(t){let e=t.length,r=0;if(t[0]==='"'){if(e===1||t[e-1]!=='"')throw new Error("Invalid cookie value");--e,++r}for(;r<e;){let n=t.charCodeAt(r++);if(n<33||n>126||n===34||n===44||n===59||n===92)throw new Error("Invalid cookie value")}}function q4(t){for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r<32||r>126||r===59)throw new Error("Invalid cookie path")}}function z4(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}function aMe(t){if(t===" ")return;if(t.length>255)throw new Error("Invalid cookie domain");let e=0;for(let r=0;r<t.length;++r){let n=t.charCodeAt(r);if(n===46){if(e===0)throw new Error("Invalid cookie domain");if(t.charCodeAt(r-1)===45)throw new Error("Invalid cookie domain");e=0;continue}if(e===0&&!z4(n))throw new Error("Invalid cookie domain");if(!z4(n)&&n!==45)throw new Error("Invalid cookie domain");if(++e>63)throw new Error("Invalid cookie domain")}if(e===0||t.charCodeAt(t.length-1)===45)throw new Error("Invalid cookie domain")}var cMe=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],lMe=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],hI=Array(61).fill(0).map((t,e)=>e.toString().padStart(2,"0"));function H4(t){return typeof t=="number"&&(t=new Date(t)),`${cMe[t.getUTCDay()]}, ${hI[t.getUTCDate()]} ${lMe[t.getUTCMonth()]} ${t.getUTCFullYear()} ${hI[t.getUTCHours()]}:${hI[t.getUTCMinutes()]}:${hI[t.getUTCSeconds()]} GMT`}function uMe(t){if(t<0)throw new Error("Invalid cookie max-age")}function dMe(t){if(t.name.length===0)return null;ET(t.name),IT(t.value);let e=[`${t.name}=${t.value}`];t.name.startsWith("__Secure-")&&(t.secure=!0),t.name.startsWith("__Host-")&&(t.secure=!0,t.domain=null,t.path="/"),t.secure&&e.push("Secure"),t.httpOnly&&e.push("HttpOnly"),typeof t.maxAge=="number"&&(uMe(t.maxAge),e.push(`Max-Age=${t.maxAge}`)),t.domain&&(aMe(t.domain),e.push(`Domain=${t.domain}`)),t.path&&(q4(t.path),e.push(`Path=${t.path}`)),t.expires&&t.expires.toString()!=="Invalid Date"&&e.push(`Expires=${H4(t.expires)}`),t.sameSite&&e.push(`SameSite=${t.sameSite}`);for(let r of t.unparsed){if(!r.includes("="))throw new Error("Invalid unparsed");let[n,...i]=r.split("="),o=n.trim(),s=i.join("=");ET(o),IT(s),e.push(`${o}=${s}`)}return e.join("; ")}G4.exports={isCTLExcludingHtab:sMe,validateCookieName:ET,validateCookiePath:q4,validateCookieValue:IT,toIMFDate:H4,stringify:dMe}});var V4=y((rHe,Y4)=>{"use strict";var{collectASequenceOfCodePointsFast:fI}=Ms(),{maxNameValuePairSize:AMe,maxAttributeValueSize:pMe}=j4(),{isCTLExcludingHtab:hMe}=CT(),fMe=require("assert");function gMe(t){if(hMe(t))return null;let e="",r="",n="",i="";if(t.includes(";")){let o={position:0};e=fI(";",t,o),r=t.slice(o.position)}else e=t;if(!e.includes("="))i=e;else{let o={position:0};n=fI("=",e,o),i=e.slice(o.position+1)}return n=n.trim(),i=i.trim(),n.length+i.length>AMe?null:{name:n,value:i,...Ad(r)}}function Ad(t,e={}){if(t.length===0)return e;fMe(t[0]===";"),t=t.slice(1);let r="";t.includes(";")?(r=fI(";",t,{position:0}),t=t.slice(r.length)):(r=t,t="");let n="",i="";if(r.includes("=")){let s={position:0};n=fI("=",r,s),i=r.slice(s.position+1)}else n=r;if(n=n.trim(),i=i.trim(),i.length>pMe)return Ad(t,e);let o=n.toLowerCase();if(o==="expires"){let s=new Date(i);e.expires=s}else if(o==="max-age"){let s=i.charCodeAt(0);if((s<48||s>57)&&i[0]!=="-"||!/^\d+$/.test(i))return Ad(t,e);let a=Number(i);e.maxAge=a}else if(o==="domain"){let s=i;s[0]==="."&&(s=s.slice(1)),s=s.toLowerCase(),e.domain=s}else if(o==="path"){let s="";i.length===0||i[0]!=="/"?s="/":s=i,e.path=s}else if(o==="secure")e.secure=!0;else if(o==="httponly")e.httpOnly=!0;else if(o==="samesite"){let s=i.toLowerCase();s==="none"?e.sameSite="None":s==="strict"?e.sameSite="Strict":s==="lax"&&(e.sameSite="Lax")}else e.unparsed??=[],e.unparsed.push(`${n}=${i}`);return Ad(t,e)}Y4.exports={parseSetCookie:gMe,parseUnparsedAttributes:Ad}});var K4=y((nHe,Z4)=>{"use strict";var{parseSetCookie:W4}=V4(),{stringify:mMe}=CT(),{webidl:We}=Cr(),{Headers:yMe}=Il(),gI=We.brandCheckMultiple([yMe,globalThis.Headers].filter(Boolean));function EMe(t){We.argumentLengthCheck(arguments,1,"getCookies"),gI(t);let e=t.get("cookie"),r={};if(!e)return r;for(let n of e.split(";")){let[i,...o]=n.split("=");r[i.trim()]=o.join("=")}return r}function IMe(t,e,r){gI(t);let n="deleteCookie";We.argumentLengthCheck(arguments,2,n),e=We.converters.DOMString(e,n,"name"),r=We.converters.DeleteCookieAttributes(r),J4(t,{name:e,value:"",expires:new Date(0),...r})}function CMe(t){We.argumentLengthCheck(arguments,1,"getSetCookies"),gI(t);let e=t.getSetCookie();return e?e.map(r=>W4(r)):[]}function bMe(t){return t=We.converters.DOMString(t),W4(t)}function J4(t,e){We.argumentLengthCheck(arguments,2,"setCookie"),gI(t),e=We.converters.Cookie(e);let r=mMe(e);r&&t.append("set-cookie",r,!0)}We.converters.DeleteCookieAttributes=We.dictionaryConverter([{converter:We.nullableConverter(We.converters.DOMString),key:"path",defaultValue:()=>null},{converter:We.nullableConverter(We.converters.DOMString),key:"domain",defaultValue:()=>null}]);We.converters.Cookie=We.dictionaryConverter([{converter:We.converters.DOMString,key:"name"},{converter:We.converters.DOMString,key:"value"},{converter:We.nullableConverter(t=>typeof t=="number"?We.converters["unsigned long long"](t):new Date(t)),key:"expires",defaultValue:()=>null},{converter:We.nullableConverter(We.converters["long long"]),key:"maxAge",defaultValue:()=>null},{converter:We.nullableConverter(We.converters.DOMString),key:"domain",defaultValue:()=>null},{converter:We.nullableConverter(We.converters.DOMString),key:"path",defaultValue:()=>null},{converter:We.nullableConverter(We.converters.boolean),key:"secure",defaultValue:()=>null},{converter:We.nullableConverter(We.converters.boolean),key:"httpOnly",defaultValue:()=>null},{converter:We.converters.USVString,key:"sameSite",allowedValues:["Strict","Lax","None"]},{converter:We.sequenceConverter(We.converters.DOMString),key:"unparsed",defaultValue:()=>[]}]);Z4.exports={getCookies:EMe,deleteCookie:IMe,getSetCookies:CMe,setCookie:J4,parseCookie:bMe}});var EI=y((iHe,eW)=>{"use strict";var{webidl:me}=Cr(),{kEnumerableProperty:an}=De(),{kConstruct:X4}=ut(),pd=class t extends Event{#e;constructor(e,r={}){if(e===X4){super(arguments[1],arguments[2]),me.util.markAsUncloneable(this);return}let n="MessageEvent constructor";me.argumentLengthCheck(arguments,1,n),e=me.converters.DOMString(e,n,"type"),r=me.converters.MessageEventInit(r,n,"eventInitDict"),super(e,r),this.#e=r,me.util.markAsUncloneable(this)}get data(){return me.brandCheck(this,t),this.#e.data}get origin(){return me.brandCheck(this,t),this.#e.origin}get lastEventId(){return me.brandCheck(this,t),this.#e.lastEventId}get source(){return me.brandCheck(this,t),this.#e.source}get ports(){return me.brandCheck(this,t),Object.isFrozen(this.#e.ports)||Object.freeze(this.#e.ports),this.#e.ports}initMessageEvent(e,r=!1,n=!1,i=null,o="",s="",a=null,c=[]){return me.brandCheck(this,t),me.argumentLengthCheck(arguments,1,"MessageEvent.initMessageEvent"),new t(e,{bubbles:r,cancelable:n,data:i,origin:o,lastEventId:s,source:a,ports:c})}static createFastMessageEvent(e,r){let n=new t(X4,e,r);return n.#e=r,n.#e.data??=null,n.#e.origin??="",n.#e.lastEventId??="",n.#e.source??=null,n.#e.ports??=[],n}},{createFastMessageEvent:SMe}=pd;delete pd.createFastMessageEvent;var mI=class t extends Event{#e;constructor(e,r={}){let n="CloseEvent constructor";me.argumentLengthCheck(arguments,1,n),e=me.converters.DOMString(e,n,"type"),r=me.converters.CloseEventInit(r),super(e,r),this.#e=r,me.util.markAsUncloneable(this)}get wasClean(){return me.brandCheck(this,t),this.#e.wasClean}get code(){return me.brandCheck(this,t),this.#e.code}get reason(){return me.brandCheck(this,t),this.#e.reason}},yI=class t extends Event{#e;constructor(e,r){let n="ErrorEvent constructor";me.argumentLengthCheck(arguments,1,n),super(e,r),me.util.markAsUncloneable(this),e=me.converters.DOMString(e,n,"type"),r=me.converters.ErrorEventInit(r??{}),this.#e=r}get message(){return me.brandCheck(this,t),this.#e.message}get filename(){return me.brandCheck(this,t),this.#e.filename}get lineno(){return me.brandCheck(this,t),this.#e.lineno}get colno(){return me.brandCheck(this,t),this.#e.colno}get error(){return me.brandCheck(this,t),this.#e.error}};Object.defineProperties(pd.prototype,{[Symbol.toStringTag]:{value:"MessageEvent",configurable:!0},data:an,origin:an,lastEventId:an,source:an,ports:an,initMessageEvent:an});Object.defineProperties(mI.prototype,{[Symbol.toStringTag]:{value:"CloseEvent",configurable:!0},reason:an,code:an,wasClean:an});Object.defineProperties(yI.prototype,{[Symbol.toStringTag]:{value:"ErrorEvent",configurable:!0},message:an,filename:an,lineno:an,colno:an,error:an});me.converters.MessagePort=me.interfaceConverter(me.is.MessagePort,"MessagePort");me.converters["sequence<MessagePort>"]=me.sequenceConverter(me.converters.MessagePort);var bT=[{key:"bubbles",converter:me.converters.boolean,defaultValue:()=>!1},{key:"cancelable",converter:me.converters.boolean,defaultValue:()=>!1},{key:"composed",converter:me.converters.boolean,defaultValue:()=>!1}];me.converters.MessageEventInit=me.dictionaryConverter([...bT,{key:"data",converter:me.converters.any,defaultValue:()=>null},{key:"origin",converter:me.converters.USVString,defaultValue:()=>""},{key:"lastEventId",converter:me.converters.DOMString,defaultValue:()=>""},{key:"source",converter:me.nullableConverter(me.converters.MessagePort),defaultValue:()=>null},{key:"ports",converter:me.converters["sequence<MessagePort>"],defaultValue:()=>[]}]);me.converters.CloseEventInit=me.dictionaryConverter([...bT,{key:"wasClean",converter:me.converters.boolean,defaultValue:()=>!1},{key:"code",converter:me.converters["unsigned short"],defaultValue:()=>0},{key:"reason",converter:me.converters.USVString,defaultValue:()=>""}]);me.converters.ErrorEventInit=me.dictionaryConverter([...bT,{key:"message",converter:me.converters.DOMString,defaultValue:()=>""},{key:"filename",converter:me.converters.USVString,defaultValue:()=>""},{key:"lineno",converter:me.converters["unsigned long"],defaultValue:()=>0},{key:"colno",converter:me.converters["unsigned long"],defaultValue:()=>0},{key:"error",converter:me.converters.any}]);eW.exports={MessageEvent:pd,CloseEvent:mI,ErrorEvent:yI,createFastMessageEvent:SMe}});var Za=y((oHe,tW)=>{"use strict";var wMe="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",_Me={enumerable:!0,writable:!1,configurable:!1},BMe={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},vMe={SENT:1,RECEIVED:2},QMe={CONTINUATION:0,TEXT:1,BINARY:2,CLOSE:8,PING:9,PONG:10},TMe=65535,DMe={INFO:0,PAYLOADLENGTH_16:2,PAYLOADLENGTH_64:3,READ_DATA:4},kMe=Buffer.allocUnsafe(0),RMe={text:1,typedArray:2,arrayBuffer:3,blob:4};tW.exports={uid:wMe,sentCloseFrameState:vMe,staticPropertyDescriptors:_Me,states:BMe,opcodes:QMe,maxUnsigned16Bit:TMe,parserStates:DMe,emptyBuffer:kMe,sendHints:RMe}});var _l=y((sHe,sW)=>{"use strict";var{states:II,opcodes:hd}=Za(),{isUtf8:NMe}=require("buffer"),{removeHTTPWhitespace:rW}=ci(),{collectASequenceOfCodePointsFast:OMe}=Ms();function xMe(t){return t===II.CONNECTING}function UMe(t){return t===II.OPEN}function MMe(t){return t===II.CLOSING}function PMe(t){return t===II.CLOSED}function LMe(t,e,r=(i,o)=>new Event(i,o),n={}){let i=r(t,n);e.dispatchEvent(i)}function $Me(t,e,r){t.onMessage(e,r)}function FMe(t){return t.byteLength===t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}function jMe(t){if(t.length===0)return!1;for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r<33||r>126||r===34||r===40||r===41||r===44||r===47||r===58||r===59||r===60||r===61||r===62||r===63||r===64||r===91||r===92||r===93||r===123||r===125)return!1}return!0}function zMe(t){return t>=1e3&&t<1015?t!==1004&&t!==1005&&t!==1006:t>=3e3&&t<=4999}function nW(t){return t===hd.CLOSE||t===hd.PING||t===hd.PONG}function iW(t){return t===hd.CONTINUATION}function oW(t){return t===hd.TEXT||t===hd.BINARY}function qMe(t){return oW(t)||iW(t)||nW(t)}function HMe(t){let e={position:0},r=new Map;for(;e.position<t.length;){let n=OMe(";",t,e),[i,o=""]=n.split("=",2);r.set(rW(i,!0,!1),rW(o,!1,!0)),e.position++}return r}function GMe(t){if(t.length===0)return!1;for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(n<48||n>57)return!1}let e=Number.parseInt(t,10);return e>=8&&e<=15}function YMe(t,e){let r;try{r=new URL(t,e)}catch(n){throw new DOMException(n,"SyntaxError")}if(r.protocol==="http:"?r.protocol="ws:":r.protocol==="https:"&&(r.protocol="wss:"),r.protocol!=="ws:"&&r.protocol!=="wss:")throw new DOMException("expected a ws: or wss: url","SyntaxError");if(r.hash.length||r.href.endsWith("#"))throw new DOMException("hash","SyntaxError");return r}function VMe(t,e){if(t!==null&&t!==1e3&&(t<3e3||t>4999))throw new DOMException("invalid code","InvalidAccessError");if(e!==null){let r=Buffer.byteLength(e);if(r>123)throw new DOMException(`Reason must be less than 123 bytes; received ${r}`,"SyntaxError")}}var WMe=(()=>{if(typeof process.versions.icu=="string"){let t=new TextDecoder("utf-8",{fatal:!0});return t.decode.bind(t)}return function(t){if(NMe(t))return t.toString("utf-8");throw new TypeError("Invalid utf-8 received.")}})();sW.exports={isConnecting:xMe,isEstablished:UMe,isClosing:MMe,isClosed:PMe,fireEvent:LMe,isValidSubprotocol:jMe,isValidStatusCode:zMe,websocketMessageReceived:$Me,utf8Decode:WMe,isControlFrame:nW,isContinuationFrame:iW,isTextBinaryFrame:oW,isValidOpcode:qMe,parseExtensions:HMe,isValidClientWindowBits:GMe,toArrayBuffer:FMe,getURLRecord:YMe,validateCloseCodeAndReason:VMe}});var gd=y((aHe,cW)=>{"use strict";var{runtimeFeatures:JMe}=Ps(),{maxUnsigned16Bit:aW,opcodes:ZMe}=Za(),CI=8*1024,Sh=null,fd=CI,KMe=JMe.has("crypto")?require("crypto").randomFillSync:function(e,r,n){for(let i=0;i<e.length;++i)e[i]=Math.random()*255|0;return e};function ST(){return fd===CI&&(fd=0,KMe(Sh??=Buffer.allocUnsafeSlow(CI),0,CI)),[Sh[fd++],Sh[fd++],Sh[fd++],Sh[fd++]]}var wT=class{constructor(e){this.frameData=e}createFrame(e){let r=this.frameData,n=ST(),i=r?.byteLength??0,o=i,s=6;i>aW?(s+=8,o=127):i>125&&(s+=2,o=126);let a=Buffer.allocUnsafe(i+s);a[0]=a[1]=0,a[0]|=128,a[0]=(a[0]&240)+e;a[s-4]=n[0],a[s-3]=n[1],a[s-2]=n[2],a[s-1]=n[3],a[1]=o,o===126?a.writeUInt16BE(i,2):o===127&&(a[2]=a[3]=0,a.writeUIntBE(i,4,6)),a[1]|=128;for(let c=0;c<i;++c)a[s+c]=r[c]^n[c&3];return a}static createFastTextFrame(e){let r=ST(),n=e.length;for(let a=0;a<n;++a)e[a]^=r[a&3];let i=n,o=6;n>aW?(o+=8,i=127):n>125&&(o+=2,i=126);let s=Buffer.allocUnsafeSlow(o);return s[0]=128|ZMe.TEXT,s[1]=i|128,s[o-4]=r[0],s[o-3]=r[1],s[o-2]=r[2],s[o-1]=r[3],i===126?s.writeUInt16BE(n,2):i===127&&(s[2]=s[3]=0,s.writeUIntBE(n,4,6)),[s,e]}};cW.exports={WebsocketFrameSend:wT,generateMask:ST}});var bI=y((cHe,hW)=>{"use strict";var{uid:XMe,states:_T,sentCloseFrameState:BT,emptyBuffer:lW,opcodes:ePe}=Za(),{parseExtensions:tPe,isClosed:rPe,isClosing:nPe,isEstablished:AW,isConnecting:iPe,validateCloseCodeAndReason:oPe}=_l(),{makeRequest:sPe}=ud(),{fetching:aPe}=Eh(),{Headers:cPe,getHeadersList:lPe}=Il(),{getDecodeSplit:uPe}=Qn(),{WebsocketFrameSend:dPe}=gd(),APe=require("assert"),{runtimeFeatures:pPe}=Ps(),uW=pPe.has("crypto")?require("crypto"):null,dW=!1;function hPe(t,e,r,n,i){let o=t;o.protocol=t.protocol==="ws:"?"http:":"https:";let s=sPe({urlList:[o],client:r,serviceWorkers:"none",referrer:"no-referrer",mode:"websocket",credentials:"include",cache:"no-store",redirect:"error",useURLCredentials:!0});if(i.headers){let u=lPe(new cPe(i.headers));s.headersList=u}let a=uW.randomBytes(16).toString("base64");s.headersList.append("sec-websocket-key",a,!0),s.headersList.append("sec-websocket-version","13",!0);for(let u of e)s.headersList.append("sec-websocket-protocol",u,!0);return s.headersList.append("sec-websocket-extensions","permessage-deflate; client_max_window_bits",!0),aPe({request:s,useParallelQueue:!0,dispatcher:i.dispatcher,processResponse(u){if(u.type==="error"||u.status!==101){if(u.socket?.session==null){Ka(n,u,1002,"Received network error or non-101 status code.",u.error);return}if(u.status!==200){Ka(n,u,1002,"Received network error or non-200 status code.",u.error);return}}if(dW===!1&&u.socket?.session!=null&&(process.emitWarning("WebSocket over HTTP2 is experimental, and subject to change.","ExperimentalWarning"),dW=!0),e.length!==0&&!u.headersList.get("Sec-WebSocket-Protocol")){Ka(n,u,1002,"Server did not respond with sent protocols.");return}if(u.socket.session==null&&u.headersList.get("Upgrade")?.toLowerCase()!=="websocket"){Ka(n,u,1002,'Server did not set Upgrade header to "websocket".');return}if(u.socket.session==null&&u.headersList.get("Connection")?.toLowerCase()!=="upgrade"){Ka(n,u,1002,'Server did not set Connection header to "upgrade".');return}let d=u.headersList.get("Sec-WebSocket-Accept"),A=uW.hash("sha1",a+XMe,"base64");if(d!==A){Ka(n,u,1002,"Incorrect hash received in Sec-WebSocket-Accept header.");return}let p=u.headersList.get("Sec-WebSocket-Extensions"),h;if(p!==null&&(h=tPe(p),!h.has("permessage-deflate"))){Ka(n,u,1002,"Sec-WebSocket-Extensions header does not match.");return}let f=u.headersList.get("Sec-WebSocket-Protocol");if(f!==null){let E=uPe("sec-websocket-protocol",s.headersList);if(E===null||!E.includes(f)){Ka(n,u,1002,"Protocol was not set in the opening handshake.");return}}u.socket.on("data",n.onSocketData),u.socket.on("close",n.onSocketClose),u.socket.on("error",n.onSocketError),n.wasEverConnected=!0,n.onConnectionEstablished(u,h)}})}function pW(t,e,r,n=!1){if(e??=null,r??="",n&&oPe(e,r),!(rPe(t.readyState)||nPe(t.readyState)))if(!AW(t.readyState))vT(t),t.readyState=_T.CLOSING;else if(!t.closeState.has(BT.SENT)&&!t.closeState.has(BT.RECEIVED)){let i=new dPe;r.length!==0&&e===null&&(e=1e3),APe(e===null||Number.isInteger(e)),e===null&&r.length===0?i.frameData=lW:e!==null&&r===null?(i.frameData=Buffer.allocUnsafe(2),i.frameData.writeUInt16BE(e,0)):e!==null&&r!==null?(i.frameData=Buffer.allocUnsafe(2+Buffer.byteLength(r)),i.frameData.writeUInt16BE(e,0),i.frameData.write(r,2,"utf-8")):i.frameData=lW,t.socket.write(i.createFrame(ePe.CLOSE)),t.closeState.add(BT.SENT),t.readyState=_T.CLOSING}else t.readyState=_T.CLOSING}function Ka(t,e,r,n,i){e.socket?.session!=null&&!e.socket.destroyed&&e.socket.destroy(),vT(t,r,n,i)}function vT(t,e,r,n){AW(t.readyState)&&pW(t,e,r,!1),t.controller.abort(),iPe(t.readyState)?t.onSocketClose():t.socket?.destroyed===!1&&t.socket.destroy()}hW.exports={establishWebSocketConnection:hPe,failWebsocketConnection:vT,closeWebSocketConnection:pW}});var gW=y((lHe,fW)=>{"use strict";var{createInflateRaw:fPe,Z_DEFAULT_WINDOWBITS:gPe}=require("zlib"),{isValidClientWindowBits:mPe}=_l(),{MessageSizeExceededError:yPe}=_e(),EPe=Buffer.from([0,0,255,255]),SI=Symbol("kBuffer"),wh=Symbol("kLength"),QT=class{#e;#t={};#n=0;constructor(e,r){this.#t.serverNoContextTakeover=e.has("server_no_context_takeover"),this.#t.serverMaxWindowBits=e.get("server_max_window_bits"),this.#n=r.maxPayloadSize}decompress(e,r,n){if(!this.#e){let i=gPe;if(this.#t.serverMaxWindowBits){if(!mPe(this.#t.serverMaxWindowBits)){n(new Error("Invalid server_max_window_bits"));return}i=Number.parseInt(this.#t.serverMaxWindowBits)}try{this.#e=fPe({windowBits:i})}catch(o){n(o);return}this.#e[SI]=[],this.#e[wh]=0,this.#e.on("data",o=>{if(this.#e[wh]+=o.length,this.#n>0&&this.#e[wh]>this.#n){n(new yPe),this.#e.removeAllListeners(),this.#e.destroy(),this.#e=null;return}this.#e[SI].push(o)}),this.#e.on("error",o=>{this.#e=null,n(o)})}this.#e.write(e),r&&this.#e.write(EPe),this.#e.flush(()=>{if(!this.#e)return;let i=Buffer.concat(this.#e[SI],this.#e[wh]);this.#e[SI].length=0,this.#e[wh]=0,n(null,i)})}};fW.exports={PerMessageDeflate:QT}});var RT=y((uHe,CW)=>{"use strict";var{Writable:IPe}=require("stream"),CPe=require("assert"),{parserStates:cn,opcodes:md,states:bPe,emptyBuffer:mW,sentCloseFrameState:_h}=Za(),{isValidStatusCode:SPe,isValidOpcode:wPe,websocketMessageReceived:yW,utf8Decode:_Pe,isControlFrame:TT,isTextBinaryFrame:DT,isContinuationFrame:BPe}=_l(),{failWebsocketConnection:Dr}=bI(),{WebsocketFrameSend:EW}=gd(),{PerMessageDeflate:vPe}=gW(),{MessageSizeExceededError:IW}=_e(),kT=class extends IPe{#e=[];#t=0;#n=0;#i=!1;#o=cn.INFO;#r={};#c=[];#s;#a;#l;#d;constructor(e,r,n={}){super(),this.#a=e,this.#s=r??new Map,this.#l=n.maxFragments??0,this.#d=n.maxPayloadSize??0,this.#s.has("permessage-deflate")&&this.#s.set("permessage-deflate",new vPe(r,n))}_write(e,r,n){this.#e.push(e),this.#n+=e.length,this.#i=!0,this.run(n)}#A(){return this.#d>0&&!TT(this.#r.opcode)&&this.#r.payloadLength+this.#t>this.#d?(Dr(this.#a,1009,"Payload size exceeds maximum allowed size"),!1):!0}run(e){for(;this.#i;)if(this.#o===cn.INFO){if(this.#n<2)return e();let r=this.consume(2),n=(r[0]&128)!==0,i=r[0]&15,o=(r[1]&128)===128,s=!n&&i!==md.CONTINUATION,a=r[1]&127,c=r[0]&64,l=r[0]&32,u=r[0]&16;if(!wPe(i))return Dr(this.#a,1002,"Invalid opcode received"),e();if(o)return Dr(this.#a,1002,"Frame cannot be masked"),e();if(c!==0&&!this.#s.has("permessage-deflate")){Dr(this.#a,1002,"Expected RSV1 to be clear.");return}if(l!==0||u!==0){Dr(this.#a,1002,"RSV1, RSV2, RSV3 must be clear");return}if(s&&!DT(i)){Dr(this.#a,1002,"Invalid frame type was fragmented.");return}if(DT(i)&&this.#c.length>0){Dr(this.#a,1002,"Expected continuation frame");return}if(this.#r.fragmented&&s){Dr(this.#a,1002,"Fragmented frame exceeded 125 bytes.");return}if((a>125||s)&&TT(i)){Dr(this.#a,1002,"Control frame either too large or fragmented");return}if(BPe(i)&&this.#c.length===0&&!this.#r.compressed){Dr(this.#a,1002,"Unexpected continuation frame");return}if(a<=125){if(this.#r.payloadLength=a,this.#o=cn.READ_DATA,!this.#A())return}else a===126?this.#o=cn.PAYLOADLENGTH_16:a===127&&(this.#o=cn.PAYLOADLENGTH_64);DT(i)&&(this.#r.binaryType=i,this.#r.compressed=c!==0),this.#r.opcode=i,this.#r.masked=o,this.#r.fin=n,this.#r.fragmented=s}else if(this.#o===cn.PAYLOADLENGTH_16){if(this.#n<2)return e();let r=this.consume(2);if(this.#r.payloadLength=r.readUInt16BE(0),this.#o=cn.READ_DATA,!this.#A())return}else if(this.#o===cn.PAYLOADLENGTH_64){if(this.#n<8)return e();let r=this.consume(8),n=r.readUInt32BE(0),i=r.readUInt32BE(4);if(n!==0||i>2**31-1){Dr(this.#a,1009,"Received payload length > 2^31 bytes.");return}if(this.#r.payloadLength=i,this.#o=cn.READ_DATA,!this.#A())return}else if(this.#o===cn.READ_DATA){if(this.#n<this.#r.payloadLength)return e();let r=this.consume(this.#r.payloadLength);if(TT(this.#r.opcode))this.#i=this.parseControlFrame(r),this.#o=cn.INFO;else if(this.#r.compressed){this.#s.get("permessage-deflate").decompress(r,this.#r.fin,(n,i)=>{if(n){let o=n instanceof IW?1009:1007;Dr(this.#a,o,n.message);return}if(this.writeFragments(i)){if(this.#d>0&&this.#t>this.#d){Dr(this.#a,1009,new IW().message);return}if(!this.#r.fin){this.#o=cn.INFO,this.#i=!0,this.run(e);return}yW(this.#a,this.#r.binaryType,this.consumeFragments()),this.#i=!0,this.#o=cn.INFO,this.run(e)}},this.#t),this.#i=!1;break}else{if(!this.writeFragments(r))return;!this.#r.fragmented&&this.#r.fin&&yW(this.#a,this.#r.binaryType,this.consumeFragments()),this.#o=cn.INFO}}}consume(e){if(e>this.#n)throw new Error("Called consume() before buffers satiated.");if(e===0)return mW;this.#n-=e;let r=this.#e[0];if(r.length>e)return this.#e[0]=r.subarray(e,r.length),r.subarray(0,e);if(r.length===e)return this.#e.shift();{let n=0,i=Buffer.allocUnsafeSlow(e);for(;n!==e;){let o=this.#e[0],s=o.length;if(s+n===e){i.set(this.#e.shift(),n);break}else if(s+n>e){i.set(o.subarray(0,e-n),n),this.#e[0]=o.subarray(e-n);break}else i.set(this.#e.shift(),n),n+=s}return i}}writeFragments(e){return this.#l>0&&this.#c.length===this.#l?(Dr(this.#a,1008,"Too many message fragments"),!1):(this.#t+=e.length,this.#c.push(e),!0)}consumeFragments(){let e=this.#c;if(e.length===1)return this.#t=0,e.shift();let r=0,n=Buffer.allocUnsafeSlow(this.#t);for(let i=0;i<e.length;++i){let o=e[i];n.set(o,r),r+=o.length}return this.#c=[],this.#t=0,n}parseCloseBody(e){CPe(e.length!==1);let r;if(e.length>=2&&(r=e.readUInt16BE(0)),r!==void 0&&!SPe(r))return{code:1002,reason:"Invalid status code",error:!0};let n=e.subarray(2);n[0]===239&&n[1]===187&&n[2]===191&&(n=n.subarray(3));try{n=_Pe(n)}catch{return{code:1007,reason:"Invalid UTF-8",error:!0}}return{code:r,reason:n,error:!1}}parseControlFrame(e){let{opcode:r,payloadLength:n}=this.#r;if(r===md.CLOSE){if(n===1)return Dr(this.#a,1002,"Received close frame with a 1-byte body."),!1;if(this.#r.closeInfo=this.parseCloseBody(e),this.#r.closeInfo.error){let{code:i,reason:o}=this.#r.closeInfo;return Dr(this.#a,i,o),!1}if(!this.#a.closeState.has(_h.SENT)&&!this.#a.closeState.has(_h.RECEIVED)){let i=mW;this.#r.closeInfo.code&&(i=Buffer.allocUnsafe(2),i.writeUInt16BE(this.#r.closeInfo.code,0));let o=new EW(i);this.#a.socket.write(o.createFrame(md.CLOSE)),this.#a.closeState.add(_h.SENT)}return this.#a.readyState=bPe.CLOSING,this.#a.closeState.add(_h.RECEIVED),!1}else if(r===md.PING){if(!this.#a.closeState.has(_h.RECEIVED)){let i=new EW(e);this.#a.socket.write(i.createFrame(md.PONG)),this.#a.onPing(e)}}else r===md.PONG&&this.#a.onPong(e);return!0}get closingInfo(){return this.#r.closeInfo}};CW.exports={ByteParser:kT}});var _W=y((dHe,wW)=>{"use strict";var{WebsocketFrameSend:SW}=gd(),{opcodes:bW,sendHints:Bl}=Za(),QPe=WB(),OT=class{#e=new QPe;#t=!1;#n;constructor(e){this.#n=e}add(e,r,n){if(n!==Bl.blob){if(this.#t){let o={promise:null,callback:r,frame:NT(e,n)};this.#e.push(o)}else if(n===Bl.text){let{0:o,1:s}=SW.createFastTextFrame(e);this.#n.cork(),this.#n.write(o),this.#n.write(s,r),this.#n.uncork()}else this.#n.write(NT(e,n),r);return}let i={promise:e.arrayBuffer().then(o=>{i.promise=null,i.frame=NT(o,n)}),callback:r,frame:null};this.#e.push(i),this.#t||this.#i()}async#i(){this.#t=!0;let e=this.#e;for(;!e.isEmpty();){let r=e.shift();r.promise!==null&&await r.promise,this.#n.write(r.frame,r.callback),r.callback=r.frame=null}this.#t=!1}};function NT(t,e){return new SW(TPe(t,e)).createFrame(e===Bl.text?bW.TEXT:bW.BINARY)}function TPe(t,e){switch(e){case Bl.text:case Bl.typedArray:return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);case Bl.arrayBuffer:case Bl.blob:return new Uint8Array(t)}}wW.exports={SendQueue:OT}});var kW=y((AHe,DW)=>{"use strict";var{isArrayBuffer:DPe}=require("util/types"),{webidl:Ee}=Cr(),{URLSerializer:kPe}=ci(),{environmentSettingsObject:BW}=Qn(),{staticPropertyDescriptors:Xa,states:Ws,sentCloseFrameState:xT,sendHints:wI,opcodes:UT}=Za(),{isConnecting:RPe,isEstablished:vW,isClosing:QW,isClosed:NPe,isValidSubprotocol:OPe,fireEvent:_I,utf8Decode:xPe,toArrayBuffer:UPe,getURLRecord:MPe}=_l(),{establishWebSocketConnection:PPe,closeWebSocketConnection:LPe,failWebsocketConnection:TW}=bI(),{ByteParser:$Pe}=RT(),{kEnumerableProperty:gi}=De(),{getGlobalDispatcher:FPe}=FE(),{ErrorEvent:jPe,CloseEvent:zPe,createFastMessageEvent:qPe}=EI(),{SendQueue:HPe}=_W(),{WebsocketFrameSend:GPe}=gd(),{channels:ps}=Ra();function YPe(t){return typeof t?.address=="function"?t.address():typeof t?.session?.socket?.address=="function"?t.session.socket.address():null}var $r=class t extends EventTarget{#e={open:null,error:null,close:null,message:null};#t=0;#n="";#i="";#o;#r={onConnectionEstablished:(e,r)=>this.#l(e,r),onMessage:(e,r)=>this.#d(e,r),onParserError:e=>TW(this.#r,null,e.message),onParserDrain:()=>this.#A(),onSocketData:e=>{this.#a.write(e)||this.#r.socket.pause()},onSocketError:e=>{this.#r.readyState=Ws.CLOSING,ps.socketError.hasSubscribers&&ps.socketError.publish(e),this.#r.socket.destroy()},onSocketClose:()=>this.#p(),onPing:e=>{ps.ping.hasSubscribers&&ps.ping.publish({payload:e,websocket:this})},onPong:e=>{ps.pong.hasSubscribers&&ps.pong.publish({payload:e,websocket:this})},readyState:Ws.CONNECTING,socket:null,closeState:new Set,controller:null,wasEverConnected:!1};#c;#s;#a;constructor(e,r=[]){super(),Ee.util.markAsUncloneable(this);let n="WebSocket constructor";Ee.argumentLengthCheck(arguments,1,n);let i=Ee.converters["DOMString or sequence<DOMString> or WebSocketInit"](r,n,"options");e=Ee.converters.USVString(e),r=i.protocols;let o=BW.settingsObject.baseUrl,s=MPe(e,o);if(typeof r=="string"&&(r=[r]),r.length!==new Set(r.map(c=>c.toLowerCase())).size)throw new DOMException("Invalid Sec-WebSocket-Protocol value","SyntaxError");if(r.length>0&&!r.every(c=>OPe(c)))throw new DOMException("Invalid Sec-WebSocket-Protocol value","SyntaxError");this.#c=new URL(s.href);let a=BW.settingsObject;this.#r.controller=PPe(s,r,a,this.#r,i),this.#r.readyState=t.CONNECTING,this.#s="blob"}close(e=void 0,r=void 0){Ee.brandCheck(this,t),e!==void 0&&(e=Ee.converters["unsigned short"](e,"WebSocket.close","code",Ee.attributes.Clamp)),r!==void 0&&(r=Ee.converters.USVString(r)),e??=null,r??="",LPe(this.#r,e,r,!0)}send(e){Ee.brandCheck(this,t);let r="WebSocket.send";if(Ee.argumentLengthCheck(arguments,1,r),e=Ee.converters.WebSocketSendData(e,r,"data"),RPe(this.#r.readyState))throw new DOMException("Sent before connected.","InvalidStateError");if(!(!vW(this.#r.readyState)||QW(this.#r.readyState)))if(typeof e=="string"){let n=Buffer.from(e);this.#t+=n.byteLength,this.#o.add(n,()=>{this.#t-=n.byteLength},wI.text)}else DPe(e)?(this.#t+=e.byteLength,this.#o.add(e,()=>{this.#t-=e.byteLength},wI.arrayBuffer)):ArrayBuffer.isView(e)?(this.#t+=e.byteLength,this.#o.add(e,()=>{this.#t-=e.byteLength},wI.typedArray)):Ee.is.Blob(e)&&(this.#t+=e.size,this.#o.add(e,()=>{this.#t-=e.size},wI.blob))}get readyState(){return Ee.brandCheck(this,t),this.#r.readyState}get bufferedAmount(){return Ee.brandCheck(this,t),this.#t}get url(){return Ee.brandCheck(this,t),kPe(this.#c)}get extensions(){return Ee.brandCheck(this,t),this.#i}get protocol(){return Ee.brandCheck(this,t),this.#n}get onopen(){return Ee.brandCheck(this,t),this.#e.open}set onopen(e){Ee.brandCheck(this,t),this.#e.open&&this.removeEventListener("open",this.#e.open);let r=Ee.converters.EventHandlerNonNull(e);r!==null?(this.addEventListener("open",r),this.#e.open=e):this.#e.open=null}get onerror(){return Ee.brandCheck(this,t),this.#e.error}set onerror(e){Ee.brandCheck(this,t),this.#e.error&&this.removeEventListener("error",this.#e.error);let r=Ee.converters.EventHandlerNonNull(e);r!==null?(this.addEventListener("error",r),this.#e.error=e):this.#e.error=null}get onclose(){return Ee.brandCheck(this,t),this.#e.close}set onclose(e){Ee.brandCheck(this,t),this.#e.close&&this.removeEventListener("close",this.#e.close);let r=Ee.converters.EventHandlerNonNull(e);r!==null?(this.addEventListener("close",r),this.#e.close=e):this.#e.close=null}get onmessage(){return Ee.brandCheck(this,t),this.#e.message}set onmessage(e){Ee.brandCheck(this,t),this.#e.message&&this.removeEventListener("message",this.#e.message);let r=Ee.converters.EventHandlerNonNull(e);r!==null?(this.addEventListener("message",r),this.#e.message=e):this.#e.message=null}get binaryType(){return Ee.brandCheck(this,t),this.#s}set binaryType(e){Ee.brandCheck(this,t),e!=="blob"&&e!=="arraybuffer"?this.#s="blob":this.#s=e}#l(e,r){this.#r.socket=e.socket;let n=this.#r.controller.dispatcher?.webSocketOptions,i=n?.maxFragments,o=n?.maxPayloadSize,s=new $Pe(this.#r,r,{maxFragments:i,maxPayloadSize:o});s.on("drain",()=>this.#r.onParserDrain()),s.on("error",l=>this.#r.onParserError(l)),this.#a=s,this.#o=new HPe(e.socket),this.#r.readyState=Ws.OPEN;let a=e.headersList.get("sec-websocket-extensions");a!==null&&(this.#i=a);let c=e.headersList.get("sec-websocket-protocol");if(c!==null&&(this.#n=c),_I("open",this),ps.open.hasSubscribers){let l=e.headersList.entries;ps.open.publish({address:YPe(e.socket),protocol:this.#n,extensions:this.#i,websocket:this,handshakeResponse:{status:e.status,statusText:e.statusText,headers:l}})}}#d(e,r){if(this.#r.readyState!==Ws.OPEN)return;let n;if(e===UT.TEXT)try{n=xPe(r)}catch{TW(this.#r,1007,"Received invalid UTF-8 in text frame.");return}else e===UT.BINARY&&(this.#s==="blob"?n=new Blob([r]):n=UPe(r));_I("message",this,qPe,{origin:this.#c.origin,data:n})}#A(){this.#r.socket.resume()}#p(){let e=this.#r.closeState.has(xT.SENT)&&this.#r.closeState.has(xT.RECEIVED),r=1005,n="",i=this.#a?.closingInfo;i&&!i.error&&(r=i.code??1005,n=i.reason),this.#r.readyState=Ws.CLOSED,this.#r.closeState.has(xT.RECEIVED)||(r=1006,_I("error",this,(o,s)=>new jPe(o,s),{error:new TypeError(n)})),_I("close",this,(o,s)=>new zPe(o,s),{wasClean:e,code:r,reason:n}),ps.close.hasSubscribers&&ps.close.publish({websocket:this,code:r,reason:n})}static ping(e,r){if(Buffer.isBuffer(r)){if(r.length>125)throw new TypeError("A PING frame cannot have a body larger than 125 bytes.")}else if(r!==void 0)throw new TypeError("Expected buffer payload");let n=e.#r.readyState;if(vW(n)&&!QW(n)&&!NPe(n)){let i=new GPe(r);e.#r.socket.write(i.createFrame(UT.PING))}}},{ping:VPe}=$r;Reflect.deleteProperty($r,"ping");$r.CONNECTING=$r.prototype.CONNECTING=Ws.CONNECTING;$r.OPEN=$r.prototype.OPEN=Ws.OPEN;$r.CLOSING=$r.prototype.CLOSING=Ws.CLOSING;$r.CLOSED=$r.prototype.CLOSED=Ws.CLOSED;Object.defineProperties($r.prototype,{CONNECTING:Xa,OPEN:Xa,CLOSING:Xa,CLOSED:Xa,url:gi,readyState:gi,bufferedAmount:gi,onopen:gi,onerror:gi,onclose:gi,close:gi,onmessage:gi,binaryType:gi,send:gi,extensions:gi,protocol:gi,[Symbol.toStringTag]:{value:"WebSocket",writable:!1,enumerable:!1,configurable:!0}});Object.defineProperties($r,{CONNECTING:Xa,OPEN:Xa,CLOSING:Xa,CLOSED:Xa});Ee.converters["sequence<DOMString>"]=Ee.sequenceConverter(Ee.converters.DOMString);Ee.converters["DOMString or sequence<DOMString>"]=function(t,e,r){return Ee.util.Type(t)===Ee.util.Types.OBJECT&&Symbol.iterator in t?Ee.converters["sequence<DOMString>"](t):Ee.converters.DOMString(t,e,r)};Ee.converters.WebSocketInit=Ee.dictionaryConverter([{key:"protocols",converter:Ee.converters["DOMString or sequence<DOMString>"],defaultValue:()=>[]},{key:"dispatcher",converter:Ee.converters.any,defaultValue:()=>FPe()},{key:"headers",converter:Ee.nullableConverter(Ee.converters.HeadersInit)}]);Ee.converters["DOMString or sequence<DOMString> or WebSocketInit"]=function(t){return Ee.util.Type(t)===Ee.util.Types.OBJECT&&!(Symbol.iterator in t)?Ee.converters.WebSocketInit(t):{protocols:Ee.converters["DOMString or sequence<DOMString>"](t)}};Ee.converters.WebSocketSendData=function(t){return Ee.util.Type(t)===Ee.util.Types.OBJECT&&(Ee.is.Blob(t)||Ee.is.BufferSource(t))?t:Ee.converters.USVString(t)};DW.exports={WebSocket:$r,ping:VPe}});var MT=y((pHe,OW)=>{"use strict";var{webidl:BI}=Cr(),{validateCloseCodeAndReason:WPe}=_l(),{kConstruct:RW}=ut(),{kEnumerableProperty:NW}=De();function JPe(){class t extends DOMException{get reason(){return""}}return new t().reason!==void 0?DOMException:new Proxy(DOMException,{construct(e,r,n){let i=Reflect.construct(e,r,e);return Object.setPrototypeOf(i,n.prototype),i}})}var vl=class t extends JPe(){#e;#t;constructor(e="",r=void 0){if(e=BI.converters.DOMString(e,"WebSocketError","message"),super(e,"WebSocketError"),r===RW)return;r!==null&&(r=BI.converters.WebSocketCloseInfo(r));let n=r.closeCode??null,i=r.reason??"";WPe(n,i),i.length!==0&&n===null&&(n=1e3),this.#e=n,this.#t=i}get closeCode(){return this.#e}get reason(){return this.#t}static createUnvalidatedWebSocketError(e,r,n){let i=new t(e,RW);return i.#e=r,i.#t=n,i}},{createUnvalidatedWebSocketError:ZPe}=vl;delete vl.createUnvalidatedWebSocketError;Object.defineProperties(vl.prototype,{closeCode:NW,reason:NW,[Symbol.toStringTag]:{value:"WebSocketError",writable:!1,enumerable:!1,configurable:!0}});BI.is.WebSocketError=BI.util.MakeTypeAssertion(vl);OW.exports={WebSocketError:vl,createUnvalidatedWebSocketError:ZPe}});var LW=y((hHe,PW)=>{"use strict";var{createDeferredPromise:PT}=kp(),{environmentSettingsObject:xW}=Qn(),{states:yd,opcodes:vI,sentCloseFrameState:Ed}=Za(),{webidl:qt}=Cr(),{getURLRecord:KPe,isValidSubprotocol:XPe,isEstablished:eLe,utf8Decode:tLe}=_l(),{establishWebSocketConnection:rLe,failWebsocketConnection:LT,closeWebSocketConnection:$T}=bI(),{channels:UW}=Ra(),{WebsocketFrameSend:nLe}=gd(),{ByteParser:iLe}=RT(),{WebSocketError:oLe,createUnvalidatedWebSocketError:sLe}=MT(),{kEnumerableProperty:QI}=De(),{utf8DecodeBytes:aLe}=Vy(),MW=!1,TI=class{#e;#t;#n;#i;#o;#r;#c=!1;#s={onConnectionEstablished:(e,r)=>this.#d(e,r),onMessage:(e,r)=>this.#A(e,r),onParserError:e=>LT(this.#s,null,e.message),onParserDrain:()=>this.#s.socket.resume(),onSocketData:e=>{this.#a.write(e)||this.#s.socket.pause()},onSocketError:e=>{this.#s.readyState=yd.CLOSING,UW.socketError.hasSubscribers&&UW.socketError.publish(e),this.#s.socket.destroy()},onSocketClose:()=>this.#p(),onPing:()=>{},onPong:()=>{},readyState:yd.CONNECTING,socket:null,closeState:new Set,controller:null,wasEverConnected:!1};#a;constructor(e,r=void 0){MW||(process.emitWarning("WebSocketStream is experimental! Expect it to change at any time.",{code:"UNDICI-WSS"}),MW=!0),qt.argumentLengthCheck(arguments,1,"WebSocket"),e=qt.converters.USVString(e),r!==null&&(r=qt.converters.WebSocketStreamOptions(r));let n=xW.settingsObject.baseUrl,i=KPe(e,n),o=r.protocols;if(o.length!==new Set(o.map(a=>a.toLowerCase())).size)throw new DOMException("Invalid Sec-WebSocket-Protocol value","SyntaxError");if(o.length>0&&!o.every(a=>XPe(a)))throw new DOMException("Invalid Sec-WebSocket-Protocol value","SyntaxError");if(this.#e=i.toString(),this.#t=PT(),this.#n=PT(),r.signal!=null){let a=r.signal;if(a.aborted){this.#t.reject(a.reason),this.#n.reject(a.reason);return}a.addEventListener("abort",()=>{eLe(this.#s.readyState)||(LT(this.#s),this.#s.readyState=yd.CLOSING,this.#t.reject(a.reason),this.#n.reject(a.reason),this.#c=!0)},{once:!0})}let s=xW.settingsObject;this.#s.controller=rLe(i,o,s,this.#s,r)}get url(){return this.#e.toString()}get opened(){return this.#t.promise}get closed(){return this.#n.promise}close(e=void 0){e!==null&&(e=qt.converters.WebSocketCloseInfo(e));let r=e.closeCode??null,n=e.reason;$T(this.#s,r,n,!0)}#l(e){e=qt.converters.WebSocketStreamWrite(e);let r=PT(),n=null,i=null;if(qt.is.BufferSource(e))n=new Uint8Array(ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e.slice()),i=vI.BINARY;else{let o;try{o=qt.converters.DOMString(e)}catch(s){return r.reject(s),r.promise}n=new TextEncoder().encode(o),i=vI.TEXT}if(!this.#s.closeState.has(Ed.SENT)&&!this.#s.closeState.has(Ed.RECEIVED)){let o=new nLe(n);this.#s.socket.write(o.createFrame(i),()=>{r.resolve(void 0)})}return r.promise}#d(e,r){this.#s.socket=e.socket;let n=this.#s.controller.dispatcher?.webSocketOptions?.maxFragments,i=this.#s.controller.dispatcher?.webSocketOptions?.maxPayloadSize,o=new iLe(this.#s,r,{maxFragments:n,maxPayloadSize:i});o.on("drain",()=>this.#s.onParserDrain()),o.on("error",u=>this.#s.onParserError(u)),this.#a=o,this.#s.readyState=yd.OPEN;let s=r??"",a=e.headersList.get("sec-websocket-protocol")??"",c=new ReadableStream({start:u=>{this.#o=u},cancel:u=>this.#u(u)}),l=new WritableStream({start:u=>{this.#r=u},write:u=>this.#l(u),close:()=>$T(this.#s,null,null),abort:u=>this.#h(u)});this.#i=c,this.#t.resolve({extensions:s,protocol:a,readable:c,writable:l})}#A(e,r){if(this.#s.readyState!==yd.OPEN)return;let n;if(e===vI.TEXT)try{n=tLe(r)}catch{LT(this.#s,1007,"Received invalid UTF-8 in text frame.");return}else e===vI.BINARY&&(n=new Uint8Array(r.buffer,r.byteOffset,r.byteLength));this.#o.enqueue(n)}#p(){let e=this.#s.closeState.has(Ed.SENT)&&this.#s.closeState.has(Ed.RECEIVED);if(this.#s.readyState=yd.CLOSED,this.#c)return;this.#s.wasEverConnected||this.#t.reject(new oLe("Socket never opened"));let r=this.#a?.closingInfo,n=r?.code??1005;!this.#s.closeState.has(Ed.SENT)&&!this.#s.closeState.has(Ed.RECEIVED)&&(n=1006);let i=r?.reason==null?"":aLe(Buffer.from(r.reason));if(e)this.#o.close(),this.#r.error(new DOMException("A closed WebSocketStream cannot be written to","InvalidStateError")),this.#n.resolve({closeCode:n,reason:i});else{let o=sLe("unclean close",n,i);this.#o?.error(o),this.#r?.error(o),this.#n.reject(o)}}#h(e){let r=null,n="";qt.is.WebSocketError(e)&&(r=e.closeCode,n=e.reason),$T(this.#s,r,n)}#u(e){this.#h(e)}};Object.defineProperties(TI.prototype,{url:QI,opened:QI,closed:QI,close:QI,[Symbol.toStringTag]:{value:"WebSocketStream",writable:!1,enumerable:!1,configurable:!0}});qt.converters.WebSocketStreamOptions=qt.dictionaryConverter([{key:"protocols",converter:qt.sequenceConverter(qt.converters.USVString),defaultValue:()=>[]},{key:"signal",converter:qt.nullableConverter(qt.converters.AbortSignal),defaultValue:()=>null}]);qt.converters.WebSocketCloseInfo=qt.dictionaryConverter([{key:"closeCode",converter:t=>qt.converters["unsigned short"](t,qt.attributes.EnforceRange)},{key:"reason",converter:qt.converters.USVString,defaultValue:()=>""}]);qt.converters.WebSocketStreamWrite=function(t){return typeof t=="string"?qt.converters.USVString(t):qt.converters.BufferSource(t)};PW.exports={WebSocketStream:TI}});var FW=y((fHe,$W)=>{"use strict";function cLe(t){return t.indexOf("\0")===-1}function lLe(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(t.charCodeAt(e)<48||t.charCodeAt(e)>57)return!1;return!0}$W.exports={isValidLastEventId:cLe,isASCIINumber:lLe}});var zW=y((gHe,jW)=>{"use strict";var{Transform:uLe}=require("stream"),{isASCIINumber:dLe,isValidLastEventId:ALe}=FW(),Id=[239,187,191],FT=10,DI=13,pLe=58,hLe=32,fLe=Buffer.from("data"),gLe=Buffer.from("event"),mLe=Buffer.from("id"),yLe=Buffer.from("retry");function ELe(t,e){if(e>=t.length)return!1;for(let r=e;r<t.length;r++)if(t[r]<48||t[r]>57)return!1;return!0}function ILe(t,e){for(let r=e;r<t.length;r++)if(t[r]===0)return!1;return!0}function kI(t,e,r){if(e!==r.length)return!1;for(let n=0;n<e;n++)if(t[n]!==r[n])return!1;return!0}var jT=class extends uLe{state;checkBOM=!0;crlfCheck=!1;eventEndCheck=!1;chunks=[];chunkIndex=0;pos=0;lineChunkIndex=0;linePos=0;event={data:void 0,event:void 0,id:void 0,retry:void 0};constructor(e={}){e.readableObjectMode=!0,super(e),this.state=e.eventSourceSettings||{},e.push&&(this.push=e.push)}_transform(e,r,n){if(e.length===0){n();return}if(this.chunks.push(e),this.checkBOM&&this.handleBOM()){n();return}for(;this.hasCurrentByte();){let i=this.currentByte();if(this.eventEndCheck){if(this.crlfCheck){if(i===FT){this.crlfCheck=!1,this.consumeCurrentByte();continue}this.crlfCheck=!1}if(i===FT||i===DI){i===DI&&(this.crlfCheck=!0),this.consumeCurrentByte(),this.hasPendingEvent()&&this.processEvent(this.event),this.clearEvent();continue}this.eventEndCheck=!1;continue}if(i===FT||i===DI){i===DI&&(this.crlfCheck=!0),this.parseLine(this.readLine(),this.event),this.consumeCurrentByte(),this.eventEndCheck=!0;continue}this.advanceCursor()}n()}parseLine(e,r){if(e.length===0)return;let n=e.indexOf(pLe);if(n===0)return;let i=e.length,o=e.length;if(n!==-1&&(i=n,o=n+1,e[o]===hLe&&++o),kI(e,i,fLe)){let s=e.toString("utf8",o);r.data===void 0?r.data=s:r.data+=`
|
|
2219
2219
|
${s}`;return}if(kI(e,i,yLe)){ELe(e,o)&&(r.retry=e.toString("utf8",o));return}if(kI(e,i,mLe)){ILe(e,o)&&(r.id=e.toString("utf8",o));return}if(kI(e,i,gLe)){let s=e.toString("utf8",o);s.length>0&&(r.event=s)}}processEvent(e){e.retry&&dLe(e.retry)&&(this.state.reconnectionTime=parseInt(e.retry,10)),e.id!==void 0&&ALe(e.id)&&(this.state.lastEventId=e.id),e.data!==void 0&&this.push({type:e.event||"message",options:{data:e.data,lastEventId:this.state.lastEventId,origin:this.state.origin}})}clearEvent(){this.event.data=void 0,this.event.event=void 0,this.event.id=void 0,this.event.retry=void 0}hasPendingEvent(){return this.event.data!==void 0||this.event.event!==void 0||this.event.id!==void 0||this.event.retry!==void 0}hasCurrentByte(){return this.chunkIndex<this.chunks.length&&this.pos<this.chunks[this.chunkIndex].length}currentByte(){return this.chunks[this.chunkIndex][this.pos]}consumeCurrentByte(){this.advanceCursor(),this.syncLineStartToCursor()}advanceCursor(){for(this.pos++;this.chunkIndex<this.chunks.length&&this.pos>=this.chunks[this.chunkIndex].length;)this.chunkIndex++,this.pos=0}syncLineStartToCursor(){this.lineChunkIndex=this.chunkIndex,this.linePos=this.pos,this.dropConsumedChunks()}dropConsumedChunks(){for(;this.lineChunkIndex>0;)this.chunks.shift(),this.lineChunkIndex--,this.chunkIndex--;this.chunkIndex===this.chunks.length&&(this.chunks.length=0,this.chunkIndex=0,this.pos=0,this.lineChunkIndex=0,this.linePos=0)}readLine(){if(this.lineChunkIndex===this.chunkIndex)return this.chunks[this.chunkIndex].subarray(this.linePos,this.pos);let e=[],r=0;for(let n=this.lineChunkIndex;n<=this.chunkIndex;n++){let i=this.chunks[n],o=n===this.lineChunkIndex?this.linePos:0,s=n===this.chunkIndex?this.pos:i.length,a=i.subarray(o,s);r+=a.length,e.push(a)}return Buffer.concat(e,r)}peekBufferedByte(e){let r=this.lineChunkIndex,n=this.linePos;for(;r<this.chunks.length;){let i=this.chunks[r],o=i.length-n;if(e<o)return i[n+e];e-=o,r++,n=0}}discardLeadingBytes(e){for(;e>0&&this.lineChunkIndex<this.chunks.length;){let n=this.chunks[this.lineChunkIndex].length-this.linePos;e<n?(this.linePos+=e,e=0):(e-=n,this.lineChunkIndex++,this.linePos=0)}this.chunkIndex=this.lineChunkIndex,this.pos=this.linePos,this.dropConsumedChunks()}handleBOM(){let e=this.peekBufferedByte(0),r=this.peekBufferedByte(1),n=this.peekBufferedByte(2);return r===void 0?(e===Id[0]||(this.checkBOM=!1),!0):n===void 0?e===Id[0]&&r===Id[1]?!0:(this.checkBOM=!1,!1):(e===Id[0]&&r===Id[1]&&n===Id[2]&&this.discardLeadingBytes(3),this.checkBOM=!1,!this.hasCurrentByte())}};jW.exports={EventSourceStream:jT}});var ZW=y((mHe,JW)=>{"use strict";var{pipeline:CLe}=require("stream"),{fetching:bLe}=Eh(),{makeRequest:SLe}=ud(),{webidl:Fr}=Cr(),{EventSourceStream:wLe}=zW(),{parseMIMEType:_Le}=ci(),{createFastMessageEvent:BLe}=EI(),{isNetworkError:qW}=gh(),{kEnumerableProperty:Ql}=De(),{environmentSettingsObject:HW}=Qn(),GW=!1,YW=3e3,Bh=0,VW=1,vh=2,vLe="anonymous",QLe="use-credentials",Cd=class t extends EventTarget{#e={open:null,error:null,message:null};#t;#n=!1;#i=Bh;#o=null;#r=null;#c;#s;constructor(e,r={}){super(),Fr.util.markAsUncloneable(this);let n="EventSource constructor";Fr.argumentLengthCheck(arguments,1,n),GW||(GW=!0,process.emitWarning("EventSource is experimental, expect them to change at any time.",{code:"UNDICI-ES"})),e=Fr.converters.USVString(e),r=Fr.converters.EventSourceInitDict(r,n,"eventSourceInitDict"),this.#c=r.node.dispatcher||r.dispatcher,this.#s={lastEventId:"",reconnectionTime:r.node.reconnectionTime};let i=HW,o;try{o=new URL(e,i.settingsObject.baseUrl),this.#s.origin=o.origin}catch(c){throw new DOMException(c,"SyntaxError")}this.#t=o.href;let s=vLe;r.withCredentials===!0&&(s=QLe,this.#n=!0);let a={redirect:"follow",keepalive:!0,mode:"cors",credentials:s==="anonymous"?"same-origin":"omit",referrer:"no-referrer"};a.client=HW.settingsObject,a.headersList=[["accept",{name:"accept",value:"text/event-stream"}]],a.cache="no-store",a.initiator="other",a.urlList=[new URL(this.#t)],this.#o=SLe(a),this.#a()}get readyState(){return this.#i}get url(){return this.#t}get withCredentials(){return this.#n}#a(){if(this.#i===vh)return;this.#i=Bh;let e={request:this.#o,dispatcher:this.#c},r=n=>{if(!qW(n))return this.#l()};e.processResponseEndOfBody=r,e.processResponse=n=>{if(qW(n))if(n.aborted){this.close(),this.dispatchEvent(new Event("error"));return}else{this.#l();return}let i=n.headersList.get("content-type",!0),o=i!==null?_Le(i):"failure",s=o!=="failure"&&o.essence==="text/event-stream";if(n.status!==200||s===!1){this.close(),this.dispatchEvent(new Event("error"));return}this.#i=VW,this.dispatchEvent(new Event("open")),this.#s.origin=n.urlList[n.urlList.length-1].origin;let a=new wLe({eventSourceSettings:this.#s,push:c=>{this.dispatchEvent(BLe(c.type,c.options))}});CLe(n.body.stream,a,c=>{c?.aborted===!1&&(this.close(),this.dispatchEvent(new Event("error")))})},this.#r=bLe(e)}#l(){this.#i!==vh&&(this.#i=Bh,this.dispatchEvent(new Event("error")),setTimeout(()=>{this.#i===Bh&&(this.#s.lastEventId.length&&this.#o.headersList.set("last-event-id",this.#s.lastEventId,!0),this.#a())},this.#s.reconnectionTime)?.unref())}close(){Fr.brandCheck(this,t),this.#i!==vh&&(this.#i=vh,this.#r.abort(),this.#o=null)}get onopen(){return this.#e.open}set onopen(e){this.#e.open&&this.removeEventListener("open",this.#e.open);let r=Fr.converters.EventHandlerNonNull(e);r!==null?(this.addEventListener("open",r),this.#e.open=e):this.#e.open=null}get onmessage(){return this.#e.message}set onmessage(e){this.#e.message&&this.removeEventListener("message",this.#e.message);let r=Fr.converters.EventHandlerNonNull(e);r!==null?(this.addEventListener("message",r),this.#e.message=e):this.#e.message=null}get onerror(){return this.#e.error}set onerror(e){this.#e.error&&this.removeEventListener("error",this.#e.error);let r=Fr.converters.EventHandlerNonNull(e);r!==null?(this.addEventListener("error",r),this.#e.error=e):this.#e.error=null}},WW={CONNECTING:{__proto__:null,configurable:!1,enumerable:!0,value:Bh,writable:!1},OPEN:{__proto__:null,configurable:!1,enumerable:!0,value:VW,writable:!1},CLOSED:{__proto__:null,configurable:!1,enumerable:!0,value:vh,writable:!1}};Object.defineProperties(Cd,WW);Object.defineProperties(Cd.prototype,WW);Object.defineProperties(Cd.prototype,{close:Ql,onerror:Ql,onmessage:Ql,onopen:Ql,readyState:Ql,url:Ql,withCredentials:Ql});Fr.converters.EventSourceInitDict=Fr.dictionaryConverter([{key:"withCredentials",converter:Fr.converters.boolean,defaultValue:()=>!1},{key:"dispatcher",converter:Fr.converters.any},{key:"node",converter:Fr.dictionaryConverter([{key:"reconnectionTime",converter:Fr.converters["unsigned long"],defaultValue:()=>YW},{key:"dispatcher",converter:Fr.converters.any}]),defaultValue:()=>({})}]);JW.exports={EventSource:Cd,defaultReconnectionTime:YW}});var nJ=y((yHe,ae)=>{"use strict";var TLe=$a(),XW=wp(),DLe=tl(),kLe=Mq(),RLe=Fq(),NLe=il(),OLe=bv(),xLe=yv(),ULe=BH(),MLe=NH(),PLe=UH(),eJ=_e(),NI=De(),{InvalidArgumentError:RI}=eJ,bd=mG(),LLe=qc(),$Le=cQ(),{MockCallHistory:FLe,MockCallHistoryLog:jLe}=dQ(),zLe=IQ(),qLe=fQ(),HLe=gY(),GLe=Hv(),YLe=BE(),{getGlobalDispatcher:tJ,setGlobalDispatcher:VLe}=FE(),WLe=id(),JLe=QQ();Object.assign(XW.prototype,bd);ae.exports.Dispatcher=XW;ae.exports.Client=TLe;ae.exports.Pool=DLe;ae.exports.BalancedPool=kLe;ae.exports.RoundRobinPool=RLe;ae.exports.Agent=NLe;ae.exports.ProxyAgent=OLe;ae.exports.Socks5ProxyAgent=xLe;ae.exports.EnvHttpProxyAgent=ULe;ae.exports.RetryAgent=MLe;ae.exports.H2CClient=PLe;ae.exports.RetryHandler=YLe;ae.exports.DecoratorHandler=WLe;ae.exports.RedirectHandler=JLe;ae.exports.interceptors={redirect:vY(),responseError:TY(),retry:kY(),dump:OY(),dns:PY(),cache:gV(),decompress:bV(),deduplicate:vV()};ae.exports.cacheStores={MemoryCacheStore:jQ()};var ZLe=DV();ae.exports.cacheStores.SqliteCacheStore=ZLe;ae.exports.buildConnector=LLe;ae.exports.errors=eJ;ae.exports.util={parseHeaders:NI.parseHeaders,headerNameToString:NI.headerNameToString};function Qh(t){return(e,r,n)=>{if(typeof r=="function"&&(n=r,r=null),!e||typeof e!="string"&&typeof e!="object"&&!(e instanceof URL))throw new RI("invalid url");if(r!=null&&typeof r!="object")throw new RI("invalid opts");if(r&&r.path!=null){if(typeof r.path!="string")throw new RI("invalid opts.path");let s=r.path;r.path.startsWith("/")||(s=`/${s}`),e=new URL(NI.parseOrigin(e).origin+s)}else r||(r=typeof e=="object"?e:{}),e=NI.parseURL(e);let{agent:i,dispatcher:o=tJ()}=r;if(i)throw new RI("unsupported opts.agent. Did you mean opts.client?");return t.call(o,{...r,origin:e.origin,path:e.search?`${e.pathname}${e.search}`:e.pathname,method:r.method||(r.body?"PUT":"GET")},n)}}ae.exports.setGlobalDispatcher=VLe;ae.exports.getGlobalDispatcher=tJ;var KLe=Eh().fetch,KW=typeof __filename<"u"?__filename:void 0;function rJ(t,e){if(!t||typeof t!="object")return;let r=typeof t.stack=="string"?t.stack:"",n=e.replace(/\\/g,"/");if(r&&(r.includes(e)||r.includes(n)))return;let i={};if(Error.captureStackTrace(i,rJ),!i.stack)return;let o=i.stack.split(`
|
|
2220
2220
|
`).slice(1).join(`
|
|
2221
2221
|
`);t.stack=r?`${r}
|
|
2222
|
-
${o}`:i.stack}ae.exports.fetch=function(e,r=void 0){return KLe(e,r).catch(n=>{throw KW?rJ(n,KW):n&&typeof n=="object"&&Error.captureStackTrace(n,ae.exports.fetch),n})};ae.exports.Headers=Il().Headers;ae.exports.Response=gh().Response;ae.exports.Request=ud().Request;ae.exports.FormData=eE().FormData;var{setGlobalOrigin:XLe,getGlobalOrigin:e$e}=nB();ae.exports.setGlobalOrigin=XLe;ae.exports.getGlobalOrigin=e$e;var{CacheStorage:t$e}=$4(),{kConstruct:r$e}=ut();ae.exports.caches=new t$e(r$e);var{deleteCookie:n$e,getCookies:i$e,getSetCookies:o$e,setCookie:s$e,parseCookie:a$e}=K4();ae.exports.deleteCookie=n$e;ae.exports.getCookies=i$e;ae.exports.getSetCookies=o$e;ae.exports.setCookie=s$e;ae.exports.parseCookie=a$e;var{parseMIMEType:c$e,serializeAMimeType:l$e}=ci();ae.exports.parseMIMEType=c$e;ae.exports.serializeAMimeType=l$e;var{CloseEvent:u$e,ErrorEvent:d$e,MessageEvent:A$e}=EI(),{WebSocket:p$e,ping:h$e}=kW();ae.exports.WebSocket=p$e;ae.exports.CloseEvent=u$e;ae.exports.ErrorEvent=d$e;ae.exports.MessageEvent=A$e;ae.exports.ping=h$e;ae.exports.WebSocketStream=LW().WebSocketStream;ae.exports.WebSocketError=MT().WebSocketError;ae.exports.request=Qh(bd.request);ae.exports.stream=Qh(bd.stream);ae.exports.pipeline=Qh(bd.pipeline);ae.exports.connect=Qh(bd.connect);ae.exports.upgrade=Qh(bd.upgrade);ae.exports.MockClient=$Le;ae.exports.MockCallHistory=FLe;ae.exports.MockCallHistoryLog=jLe;ae.exports.MockPool=qLe;ae.exports.MockAgent=zLe;ae.exports.SnapshotAgent=HLe;ae.exports.mockErrors=GLe;var{EventSource:f$e}=ZW();ae.exports.EventSource=f$e;function g$e(){globalThis.fetch=ae.exports.fetch,globalThis.Headers=ae.exports.Headers,globalThis.Response=ae.exports.Response,globalThis.Request=ae.exports.Request,globalThis.FormData=ae.exports.FormData,globalThis.WebSocket=ae.exports.WebSocket,globalThis.CloseEvent=ae.exports.CloseEvent,globalThis.ErrorEvent=ae.exports.ErrorEvent,globalThis.MessageEvent=ae.exports.MessageEvent,globalThis.EventSource=ae.exports.EventSource}ae.exports.install=g$e});var oJ=y(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});wd.SuperglueClient=wd.SuperglueHttpError=void 0;var Sd=pn(),ln=fw(),m$e=X0(),y$e=gj(),E$e=Ti(),Js=NA(),I$e=OA(),Dh=14400*1e3,Th;if(typeof globalThis.process<"u"&&globalThis.process.versions?.node)try{let{Agent:t}=nJ();Th=new t({headersTimeout:Dh,bodyTimeout:Dh})}catch{}function iJ(t){if(t?.aborted)throw t.reason??new DOMException("Aborted","AbortError")}var OI=class extends Error{constructor(e,r,n,i){super(e),this.status=r,this.code=n,this.details=i,this.name="SuperglueHttpError"}};wd.SuperglueHttpError=OI;var zT=class{constructor({apiKey:e,apiEndpoint:r,onInfrastructureError:n,refreshToken:i,sseTokenProvider:o,tokenProvider:s}){if(!e&&!s)throw new Error("SuperglueClient requires either apiKey or tokenProvider");this.tokenProvider=s??(async()=>e),this.apiEndpoint=r??"https://api.superglue.cloud",this.sseManager=new m$e.SSELogSubscriptionManager(this.apiEndpoint,o??this.tokenProvider,i),this.onInfrastructureError=n,this.refreshToken=i}async getApiKey(){return this.tokenProvider()}async fetchWithAuthRetry(e,r){let n=await this.getApiKey(),i=await e(n);if(i.status!==401||!this.refreshToken)return i;iJ(r);let o=await this.refreshToken();return iJ(r),!o||o===n?i:(i.body?.cancel(),e(o))}isInfrastructureError(e){return(0,E$e.isAbortError)(e)?!1:!!(e instanceof TypeError&&e.message.toLowerCase().includes("fetch")||e instanceof Error&&e.name==="TimeoutError")}async restRequest(e,r,n,i,o){let a=await(await this.restResponse({method:e,path:r,body:n,extraHeaders:i,requestInit:o})).text();if(a)return JSON.parse(a)}async restData(...e){return(await this.restRequest(...e)).data}async restResponse({method:e,path:r,body:n,extraHeaders:i,requestInit:o}){let s=`${this.apiEndpoint.replace(/\/$/,"")}${r}`,a=n!=null,c=typeof FormData<"u"&&n instanceof FormData,l=u=>{let d={Authorization:`Bearer ${u}`,...i};return a&&!c&&e!=="GET"&&(d["Content-Type"]="application/json"),fetch(s,{...o,method:e,headers:d,body:a?c?n:JSON.stringify(n):void 0,signal:o?.signal??AbortSignal.timeout(Dh),...Th?{dispatcher:Th}:{}})};return this.sendAuthorized(l,o?.signal)}async sendAuthorized(e,r){let n;try{n=await this.fetchWithAuthRetry(e,r)}catch(i){throw this.isInfrastructureError(i)&&this.onInfrastructureError?.(),i}if(!n.ok)throw await this.buildHttpError(n);return n}async uploadFiles(e,r){if(typeof r?.process!="boolean")throw new Error("process must be a boolean");if(e.length===0)return[];let n=e.map(u=>({...u,contentLength:u.contentLength??this.getUploadContentLength(u.content)})),o=(await this.restRequest("POST","/v1/files/uploads",{process:r.process,...r.allowUnprocessed?{allowUnprocessed:!0}:{},files:n.map(({fileName:u,contentType:d,contentLength:A})=>({fileName:u,contentLength:A,...d?{contentType:d}:{}}))})).data.files;if(o.length!==n.length)throw await Promise.all(o.map(u=>this.deleteFileUpload(u.id).catch(()=>{}))),new Error("Upload response did not match the selected files");let s=await Promise.allSettled(o.map(async(u,d)=>{let A=n[d],p=await fetch(u.uploadUrl,{method:"PUT",body:A.content,headers:{...u.uploadHeaders,...A.contentType?{"Content-Type":A.contentType}:{}},signal:AbortSignal.timeout(Math.min(Dh,u.expiresIn*1e3))});if(!p.ok)throw new Error(`Upload failed for ${A.fileName}: ${p.status} ${p.statusText}`);return u.id})),a=s.flatMap(u=>u.status==="fulfilled"?[u.value]:[]),c=new Map;if(a.length>0)try{let u=await this.restRequest("POST","/v1/files/uploads/complete",{fileIds:a});c=new Map(u.data.files.map(d=>[d.id,d]))}catch(u){c=new Map(a.map(d=>[d,{id:d,fileName:n[o.findIndex(A=>A.id===d)]?.fileName||d,contentLength:n[o.findIndex(A=>A.id===d)]?.contentLength||0,status:"failed",error:u instanceof Error?u.message:String(u)}]))}let l=o.map((u,d)=>{let A=s[d],p=n[d];return A.status==="rejected"?{id:u.id,fileName:p.fileName,contentLength:p.contentLength,status:"failed",error:A.reason instanceof Error?A.reason.message:String(A.reason)}:c.get(u.id)||{id:u.id,fileName:p.fileName,contentLength:p.contentLength,status:"failed",error:"Upload completion returned no result"}});return await Promise.all(l.filter(u=>u.status==="failed").map(u=>this.deleteFileUpload(u.id).catch(()=>{}))),l}async deleteFileUpload(e){await this.restRequest("DELETE",`/v1/files/uploads/${encodeURIComponent(e)}`)}getUploadContentLength(e){return typeof e=="string"?new TextEncoder().encode(e).byteLength:e instanceof Uint8Array?e.byteLength:e.size}async buildHttpError(e){e.status>=500&&this.onInfrastructureError?.();let r=await e.text(),n=`HTTP ${e.status}: ${r}`,i,o;try{let s=JSON.parse(r);s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),typeof s?.code=="string"&&(i=s.code);let a=s.error;typeof a=="string"?n=a:a&&typeof a=="object"&&(n=a.message||JSON.stringify(a))}catch{}return new OI(n,e.status,i,o)}async streamRequest(e,r,n){let i=e.includes("?")?"&":"?",o=`${this.apiEndpoint.replace(/\/$/,"")}${e}${i}stream=true`,s=l=>fetch(o,{method:"POST",headers:{Authorization:`Bearer ${l}`,Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(r),signal:n??AbortSignal.timeout(Dh),...Th?{dispatcher:Th}:{}}),a;try{a=await this.fetchWithAuthRetry(s,n)}catch(l){throw this.isInfrastructureError(l)&&this.onInfrastructureError?.(),l}if(!a.ok)throw await this.buildHttpError(a);if(!(a.headers.get("content-type")||"").includes("text/event-stream")){let l=await a.text();return l?JSON.parse(l):void 0}try{return await(0,y$e.consumeEventStreamResult)(a)}catch(l){throw this.isInfrastructureError(l)&&this.onInfrastructureError?.(),l}}async subscribeToLogsSSE(e={}){return this.sseManager.subscribeToLogs(e)}async disconnect(){await this.sseManager.disconnect()}async listMemoryNotes(e={}){let r=new URLSearchParams;e.scope&&r.set("scope",e.scope),e.query&&r.set("query",e.query);let n=r.toString();return this.restData("GET",`/v1/memory-notes${n?`?${n}`:""}`)}async createMemoryNote(e){return this.restData("POST","/v1/memory-notes",e)}async updateMemoryNote(e,r){return this.restData("PATCH",`/v1/memory-notes/${encodeURIComponent(e)}`,r)}async deleteMemoryNote(e){await this.restRequest("DELETE",`/v1/memory-notes/${encodeURIComponent(e)}`)}async clearMemoryNotes(e){return(await this.restRequest("DELETE",`/v1/memory-notes?scope=${e}`)).data.deleted}async getMe(){return this.restRequest("GET","/v1/me")}async completeOnboarding(){return this.restRequest("POST","/v1/me/onboarding/complete")}async runTool(e){let r=await this.restRequest("POST",`/v1/tools/${encodeURIComponent(e.toolId)}/run`,{inputs:e.payload,files:e.files,credentials:e.credentials,includeStepResultData:e.includeStepResultData,options:e.options,runId:e.runId,stateFixture:e.stateFixture},void 0,e.signal?{signal:e.signal}:void 0);return{success:r.status==="success",data:r.data,error:r.error,tool:r.tool,stepResults:r.stepResults?.map(n=>({...n}))||[],...r.fileArtifacts&&r.fileArtifacts.length>0?{fileArtifacts:r.fileArtifacts}:{},...r.metadata?.warnings?.length?{warnings:r.metadata.warnings}:{}}}async runToolConfig(e){let r=e.createRun?"/v1/tools/run?createRun=true":"/v1/tools/run",n=await this.restRequest("POST",r,{tool:e.tool,payload:e.payload,files:e.files,credentials:e.credentials,includeStepResultData:e.includeStepResultData,options:e.options,runId:e.runId,stateFixture:e.stateFixture,executionKind:e.executionKind,parentToolId:e.parentToolId,draftId:e.draftId},e.traceId?{"X-Trace-Id":e.traceId}:void 0,e.signal?{signal:e.signal}:void 0);return{success:n.status?n.status==="success":n.success??!1,data:n.data,error:n.error,tool:n.tool||e.tool,stepResults:n.stepResults?.map(o=>({...o}))||[],...n.fileArtifacts&&n.fileArtifacts.length>0?{fileArtifacts:n.fileArtifacts}:{},...n.metadata?.warnings?.length?{warnings:n.metadata.warnings}:{}}}async abortToolExecution(e){return{success:!0,runId:(await this.restRequest("POST",`/v1/runs/${encodeURIComponent(e)}/cancel`)).runId}}async executeStep({step:e,payload:r,files:n,previousResults:i,credentials:o,credentialsList:s,options:a,runId:c,systemIds:l,connectionId:u,systemAuth:d,createRun:A,parentToolId:p,stepIndex:h,stepId:f,signal:E,stream:S}){let B={step:e,payload:r,files:n,previousResults:i,credentials:o,credentialsList:s,options:a,runId:c,systemIds:l,connectionId:u,systemAuth:d,createRun:A,parentToolId:p,stepIndex:h,stepId:f};return S?this.streamRequest("/v1/tools/step/run",B,E):this.restRequest("POST","/v1/tools/step/run",B,void 0,E?{signal:E}:void 0)}async abortStep(e){return this.restRequest("POST","/v1/tools/step/abort",{runId:e})}async executeTransformOnly({outputTransform:e,outputSchema:r,inputSchema:n,payload:i,files:o,stepResults:s,options:a,runId:c,createRun:l,parentToolId:u,stepId:d,signal:A,stream:p}){let h={outputTransform:e,outputSchema:r,inputSchema:n,payload:i,files:o,stepResults:s,options:a,runId:c,createRun:l,parentToolId:u,stepId:d};return p?this.streamRequest("/v1/tools/transform/run",h,A):this.restRequest("POST","/v1/tools/transform/run",h,void 0,A?{signal:A}:void 0)}async createRun({toolId:e,toolConfig:r,toolResult:n,stepResults:i,toolPayload:o,status:s,error:a,startedAt:c,completedAt:l,executionKind:u,parentToolId:d,draftId:A}){return this.restRequest("POST","/v1/runs",{toolId:e,toolConfig:r,toolResult:n,stepResults:i,toolPayload:o,status:s,error:a,startedAt:(0,Js.toUTCISOString)(c,"run.startedAt"),completedAt:(0,Js.toUTCISOString)(l,"run.completedAt"),executionKind:u,parentToolId:d,draftId:A})}async checkRunLimit(){return this.restData("POST","/v1/runs/check-limit")}async extract({file:e,envelope:r}){if(!e)throw new Error("File must be provided for extract.");let n=new FormData;n.append("file",e);let i=r?"/v1/extract?envelope=true":"/v1/extract";return this.restRequest("POST",i,n)}mapOpenAPIRunToRun(e){let r={running:Sd.RunStatus.RUNNING,success:Sd.RunStatus.SUCCESS,failed:Sd.RunStatus.FAILED,aborted:Sd.RunStatus.ABORTED};return{runId:e.runId??e.id,toolId:e.toolId,tool:e.tool,systemIds:e.systemIds,status:r[e.status]??Sd.RunStatus.FAILED,toolPayload:e.toolPayload,data:e.data,toolResult:e.data,error:e.error,stepResults:e.stepResults,options:e.options,requestSource:e.requestSource,traceId:e.traceId,resultStorageUri:e.resultStorageUri,userId:e.userId,userEmail:e.userEmail,userName:e.userName,metadata:{...e.metadata,executionKind:e.metadata?.executionKind??Sd.RunExecutionKind.FULL},fileArtifacts:e.fileArtifacts}}mapOpenAPIScheduleToToolSchedule(e){return{...e,lastRunAt:e.lastRunAt?(0,Js.requireUTCDate)(e.lastRunAt,"schedule.lastRunAt"):void 0,nextRunAt:(0,Js.requireUTCDate)(e.nextRunAt,"schedule.nextRunAt"),createdAt:(0,Js.requireUTCDate)(e.createdAt,"schedule.createdAt"),updatedAt:(0,Js.requireUTCDate)(e.updatedAt,"schedule.updatedAt")}}async listRuns(e={}){let r=(0,ln.createSearchListQueryParams)(e);e.toolId!==void 0&&r.set("toolId",e.toolId),e.searchUserIds?.length&&r.set("searchUserIds",e.searchUserIds.join(",")),e.includeTotal!==void 0&&r.set("includeTotal",String(e.includeTotal)),e.startedAfter!==void 0&&r.set("startedAfter",e.startedAfter instanceof Date?(0,Js.toUTCISOString)(e.startedAfter,"run.startedAfter"):e.startedAfter),e.statuses!==void 0?r.set("status",e.statuses.join(",")):e.status!==void 0&&r.set("status",e.status),e.requestSources!==void 0&&r.set("requestSources",e.requestSources.join(",")),e.executionKinds!==void 0&&r.set("executionKinds",e.executionKinds.join(",")),e.userId!==void 0&&r.set("userId",e.userId),e.systemId!==void 0&&r.set("systemId",e.systemId),e.systemIds!==void 0&&r.set("systemIds",e.systemIds.join(","));let n=r.size>0?`?${r.toString()}`:"",i=await this.restRequest("GET",`/v1/runs${n}`,void 0,void 0,{signal:e.signal});return{data:i.data.map(o=>this.mapOpenAPIRunToRun(o)),total:i.total,page:i.page,limit:i.limit,hasMore:i.hasMore}}async getActivityCounts(e){let r=new URLSearchParams;e?.from&&r.set("from",e.from instanceof Date?(0,Js.toUTCISOString)(e.from,"activity.from"):e.from),e?.to&&r.set("to",e.to instanceof Date?(0,Js.toUTCISOString)(e.to,"activity.to"):e.to);let n=r.toString();return(await this.restRequest("GET",`/v1/activity/counts${n?`?${n}`:""}`,void 0,void 0,{signal:e?.signal})).counts}async getRun(e){try{let r=await this.restRequest("GET",`/v1/runs/${encodeURIComponent(e)}`);return this.mapOpenAPIRunToRun(r)}catch(r){if(r.message?.includes("404")||r.message?.includes("not found"))return null;throw r}}async getTool(e){try{return await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}`)}catch(r){if(r.message?.includes("404")||r.message?.includes("not found")||r.message?.includes("403")||r.message?.includes("not allowed"))return null;throw r}}async getToolState(e){return(await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}/state`)).state}async setToolState(e,r){await this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}/state`,{state:r})}async deleteToolState(e){return(await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}/state`)).deletedKeys}async archiveTool(e,r=!0){return this.updateTool(e,{archived:r})}async bulkArchiveTools(e,r=!0){return this.restRequest("POST","/v1/tools/bulk/archive",{ids:e,archived:r})}async bulkDeleteTools(e){return this.restRequest("POST","/v1/tools/bulk/delete",{ids:e})}async listTools(e={}){let r=(0,ln.createListQueryParams)(e);e.includeArchived!==void 0&&r.set("includeArchived",String(e.includeArchived));let n=r.size>0?`?${r.toString()}`:"";return this.restRequest("GET",`/v1/tools${n}`)}async listAllTools(e={}){return(0,ln.listAllPages)((r,n)=>this.listTools({...e,page:r,limit:n}))}async createTool(e,r){return this.restRequest("POST","/v1/tools",{...r,id:e})}async updateTool(e,r){return this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}`,r)}async deleteTool(e){try{return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}`),!0}catch(r){if(r.message?.includes("404"))return!1;throw r}}async renameTool(e,r){return this.restRequest("POST",`/v1/tools/${encodeURIComponent(e)}/rename`,{newId:r})}async getWorkflow(e){return this.getTool(e)}async archiveWorkflow(e,r=!0){return this.upsertWorkflow(e,{archived:r})}async createWorkflow(e,r){return this.createTool(e,r)}async updateWorkflow(e,r){return this.updateTool(e,r)}async upsertWorkflow(e,r){return await this.getTool(e)?this.updateTool(e,r):this.createTool(e,r)}async deleteWorkflow(e){return this.deleteTool(e)}async renameWorkflow(e,r){return this.renameTool(e,r)}async listProjectSummaries(e={}){let r=(0,ln.createSearchListQueryParams)(e);return r.set("includeResources","false"),e.includeArchived!==void 0&&r.set("includeArchived",String(e.includeArchived)),this.restRequest("GET",`/v1/projects?${r.toString()}`)}async listAllProjectSummaries({includeArchived:e}={}){return(0,ln.listAllPages)((r,n)=>this.listProjectSummaries({page:r,limit:n,...e!==void 0?{includeArchived:e}:{}}))}async listAllProjectTasks(e){return(0,ln.listAllPages)((r,n)=>this.restRequest("GET",`/v1/projects/${encodeURIComponent(e)}/tasks?page=${r}&limit=${n}`))}async saveProjectTask({projectId:e,taskId:r,input:n}){let i=`/v1/projects/${encodeURIComponent(e)}/tasks${r?`/${encodeURIComponent(r)}`:""}`;return this.restData(r?"PATCH":"POST",i,n)}async listAllProjectLabels(e){return(0,ln.listAllPages)((r,n)=>this.restRequest("GET",`/v1/projects/${encodeURIComponent(e)}/labels?page=${r}&limit=${n}`))}async saveProjectLabel({projectId:e,labelId:r,input:n}){let i=`/v1/projects/${encodeURIComponent(e)}/labels${r?`/${encodeURIComponent(r)}`:""}`;return this.restData(r?"PATCH":"POST",i,n)}async deleteProjectLabel({projectId:e,labelId:r}){await this.restRequest("DELETE",`/v1/projects/${encodeURIComponent(e)}/labels/${encodeURIComponent(r)}`)}async listSchedules(e={}){let r=(0,ln.createListQueryParams)(e),n=r.size>0?`?${r.toString()}`:"",i=e.toolId?`/v1/tools/${encodeURIComponent(e.toolId)}/schedules${n}`:`/v1/schedules${n}`,o=await this.restRequest("GET",i);return{...o,data:o.data.map(s=>this.mapOpenAPIScheduleToToolSchedule(s))}}async listAllSchedules(e={}){return(0,ln.listAllPages)((r,n)=>this.listSchedules({...e,page:r,limit:n}))}async getToolSchedule(e,r){try{let n=await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(r)}`);return this.mapOpenAPIScheduleToToolSchedule(n)}catch(n){if(n.message?.includes("404")||n.message?.includes("not found"))return null;throw n}}async createToolSchedule(e,r){let n=await this.restRequest("POST",`/v1/tools/${encodeURIComponent(e)}/schedules`,{...r,timezone:r.timezone||(0,I$e.getRuntimeTimezone)()});return this.mapOpenAPIScheduleToToolSchedule(n)}async updateToolSchedule(e,r,n){let i=await this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(r)}`,n);return this.mapOpenAPIScheduleToToolSchedule(i)}async deleteToolSchedule(e,r){return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(r)}`),!0}async bulkSetSchedulesEnabled(e,r){return this.restRequest("POST","/v1/schedules/bulk/enable",{ids:e,enabled:r})}async bulkDeleteSchedules(e){return this.restRequest("POST","/v1/schedules/bulk/delete",{ids:e})}async listConnections(e={}){let r=(0,ln.createListQueryParams)(e);e.systemId!==void 0&&r.set("systemId",e.systemId);let n=r.size>0?`?${r.toString()}`:"";return this.restRequest("GET",`/v1/connections${n}`)}async listAllConnections(e={}){return(0,ln.listAllPages)((r,n)=>this.listConnections({...e,page:r,limit:n}))}async createOAuthApp(e){return this.restData("POST","/v1/oauth-apps",e)}async updateOAuthApp(e,r){return this.restData("PUT",`/v1/oauth-apps/${encodeURIComponent(e)}`,r)}async deleteOAuthApp(e){await this.restRequest("DELETE",`/v1/oauth-apps/${encodeURIComponent(e)}`)}async listOAuthApps({systemId:e}={}){return(0,ln.listAllPages)(async(r,n)=>{let i=new URLSearchParams({page:String(r),limit:String(n),...e?{systemId:e}:{}});return this.restRequest("GET",`/v1/oauth-apps?${i}`)})}async getConnectionSetup(e){return this.restData("GET",`/v1/connections/setup/${encodeURIComponent(e)}`)}async createConnection(e){return this.restData("POST","/v1/connections",e)}async replaceConnection(e,r){return this.restData("PUT",`/v1/connections/${encodeURIComponent(e)}`,{credentials:r})}async updateConnection(e,r){return this.restData("PATCH",`/v1/connections/${encodeURIComponent(e)}`,r)}async deleteConnection(e){await this.restRequest("DELETE",`/v1/connections/${encodeURIComponent(e)}`)}async setDefaultConnection(e){await this.restRequest("POST",`/v1/connections/${encodeURIComponent(e)}/default`)}async listSystems(e={}){let r=(0,ln.createListQueryParams)(e),n=r.size>0?`?${r.toString()}`:"";return this.restRequest("GET",`/v1/systems${n}`)}async listAllSystems(e={}){return(0,ln.listAllPages)((r,n)=>this.listSystems({...e,page:r,limit:n}))}async createOAuthExchange(e){return(await this.restRequest("POST","/v1/oauth/exchanges",e)).data}async completeOAuthExchange(e,r){return(await this.restRequest("POST",`/v1/oauth/exchanges/${encodeURIComponent(e)}/complete`,r)).data}async describeOAuthProviderPage(e){return(await this.restRequest("POST",`/v1/oauth/exchanges/${encodeURIComponent(e)}/provider-page`)).data}async generateCredentialsLink(e){try{return{success:!0,credentialsUrl:(await this.restRequest("POST","/v1/authenticate",e||{})).data.credentialsUrl}}catch(r){return{success:!1,error:r.message}}}};wd.SuperglueClient=zT});var aJ=y(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.UnquotedKeyStrategy=tr.TripleQuoteStrategy=tr.TrailingCommaStrategy=tr.SingleQuoteStrategy=tr.PythonLiteralStrategy=tr.CommentStrategy=tr.ResilientJsonParser=tr.RepairStrategy=void 0;tr.parseJsonResilient=C$e;tr.parseJSON=b$e;var $i=class{validate(e){try{return JSON.parse(e),!0}catch{return!1}}};tr.RepairStrategy=$i;var xI=class extends $i{constructor(){super(...arguments),this.name="TripleQuoteRepair",this.description="Converts triple-quoted strings to proper JSON, parsing nested JSON content"}canApply(e){return/"""/.test(e)}apply(e){return e.replace(/"""([\s\S]*?)"""/g,(r,n)=>{let i=n.trim();if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{let s=JSON.parse(i);return JSON.stringify(s)}catch{return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`})}};tr.TripleQuoteStrategy=xI;var UI=class extends $i{constructor(){super(...arguments),this.name="PythonLiteralRepair",this.description="Converts Python literals to JavaScript equivalents"}canApply(e){return/\b(None|True|False)\b/.test(e)}apply(e){return e.replace(/\bNone\b/g,"null").replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false")}};tr.PythonLiteralStrategy=UI;var MI=class extends $i{constructor(){super(...arguments),this.name="TrailingCommaRepair",this.description="Removes trailing commas from objects and arrays"}canApply(e){return/,\s*[}\]]/.test(e)}apply(e){return e.replace(/,(\s*[}\]])/g,"$1")}};tr.TrailingCommaStrategy=MI;var PI=class extends $i{constructor(){super(...arguments),this.name="SingleQuoteRepair",this.description="Converts single quotes to double quotes"}canApply(e){return/[{,]\s*'[^']*'\s*:/.test(e)||/:\s*'[^']*'/.test(e)}apply(e){let r=e.replace(/([{,]\s*)'([^']+)'(\s*:)/g,'$1"$2"$3');return r=r.replace(/(:\s*)'([^']+)'(\s*[,}])/g,'$1"$2"$3'),r}};tr.SingleQuoteStrategy=PI;var LI=class extends $i{constructor(){super(...arguments),this.name="UnquotedKeyRepair",this.description="Adds quotes to unquoted object keys"}canApply(e){return/[{,]\s*[a-zA-Z_$][a-zA-Z0-9_$]*\s*:/.test(e)}apply(e){return e.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)(\s*:)/g,'$1"$2"$3')}};tr.UnquotedKeyStrategy=LI;var $I=class extends $i{constructor(){super(...arguments),this.name="CommentRemoval",this.description="Removes JavaScript-style comments"}canApply(e){return/\/\/.*$|\/\*[\s\S]*?\*\//m.test(e)}apply(e){let r=e.replace(/\/\/.*$/gm,"");return r=r.replace(/\/\*[\s\S]*?\*\//g,""),r}};tr.CommentStrategy=$I;var qT=class extends $i{constructor(){super(...arguments),this.name="UnescapedControlCharactersRepair",this.description="Escapes unescaped control characters (newlines, tabs, etc.) in JSON strings"}canApply(e){try{return JSON.parse(e),!1}catch(r){let n=r.message||"";return n.includes("control character")||n.includes("Bad control")||n.includes("Unexpected token")&&/[\n\r\t]/.test(e)}}apply(e){let r="",n=!1,i=!1;for(let o=0;o<e.length;o++){let s=e[o],a=o>0?e[o-1]:"";if(i){r+=s,i=!1;continue}if(s==="\\"&&n){r+=s,i=!0;continue}if(s==='"'&&a!=="\\"){n=!n,r+=s;continue}if(n)switch(s){case`
|
|
2223
|
-
`:r+="\\n";break;case"\r":r+="\\r";break;case" ":r+="\\t";break;case"\b":r+="\\b";break;case"\f":r+="\\f";break;default:let c=s.charCodeAt(0);c<32?r+="\\u"+("0000"+c.toString(16)).slice(-4):r+=s}else r+=s}return r}},HT=class extends $i{constructor(){super(...arguments),this.name="TrailingCharactersRepair",this.description="Removes trailing characters after valid JSON structure"}canApply(e){let r=e.trim();if(!r.startsWith("{")&&!r.startsWith("["))return!1;let n=0,i=0,o=!1,s=!1;for(let a=0;a<r.length;a++){let c=r[a];if(o)s?s=!1:c==="\\"?s=!0:c==='"'&&(o=!1);else if(c==='"')o=!0;else if(c==="{")n++;else if(c==="}"){if(n--,n===0&&i===0&&a>0&&a<r.length-1)return!0}else if(c==="[")i++;else if(c==="]"&&(i--,i===0&&n===0&&a>0&&a<r.length-1))return!0}return!1}apply(e){let r=e.trim(),n=0,i=0,o=!1,s=!1,a=-1;for(let c=0;c<r.length;c++){let l=r[c];if(o)s?s=!1:l==="\\"?s=!0:l==='"'&&(o=!1);else if(l==='"')o=!0;else if(l==="{")n++;else if(l==="}"){if(n--,n===0&&i===0&&c>0){a=c;break}}else if(l==="[")i++;else if(l==="]"&&(i--,i===0&&n===0&&c>0)){a=c;break}}return a>0&&a<r.length-1?r.substring(0,a+1):e}},kh=class{constructor(e={}){this.strategies=[],this.repairLog=[],this.options={attemptRepair:!0,maxDepth:10,preserveStringsOnFailure:!1,logRepairs:!1,...e},this.initializeDefaultStrategies(),e.customStrategies&&this.strategies.push(...e.customStrategies)}initializeDefaultStrategies(){this.strategies=[new xI,new PI,new qT,new HT,new UI,new MI,new LI,new $I]}parse(e){let r=Date.now();this.repairLog=[];let n=e instanceof Buffer?e.toString("utf8"):String(e);try{return{success:!0,data:JSON.parse(n),metadata:{parseTime:Date.now()-r,strategiesApplied:[]}}}catch(s){if(!this.options.attemptRepair)return{success:!1,error:`JSON parse error: ${s}`,metadata:{parseTime:Date.now()-r}}}let i=n,o=[];for(let s of this.strategies)if(s.canApply(i)){let a=i;if(i=s.apply(i),a!==i){o.push(s.name),this.repairLog.push(s.description),this.options.logRepairs&&console.log(`Applied ${s.name}: ${s.description}`);try{return{success:!0,data:JSON.parse(i),repairs:this.repairLog,metadata:{parseTime:Date.now()-r,strategiesApplied:o}}}catch{}}}try{return{success:!0,data:JSON.parse(i),repairs:this.repairLog,metadata:{parseTime:Date.now()-r,strategiesApplied:o}}}catch(s){let a=this.aggressiveFallback(i);return a.success?{...a,repairs:[...this.repairLog,"Applied aggressive fallback"],metadata:{parseTime:Date.now()-r,strategiesApplied:[...o,"AggressiveFallback"]}}:{success:!1,error:`Failed to parse JSON after applying ${o.length} strategies: ${s}`,repairs:this.repairLog,metadata:{parseTime:Date.now()-r,strategiesApplied:o}}}}aggressiveFallback(e){try{let r=e.indexOf("{"),n=e.indexOf("[");if(r===-1&&n===-1)return{success:!1,error:"No JSON-like structure found"};let i=r===-1?n:n===-1?r:Math.min(r,n),o=e.substring(i);for(let a of this.strategies)a.canApply(o)&&(o=a.apply(o));return{success:!0,data:JSON.parse(o)}}catch(r){return{success:!1,error:`Aggressive fallback failed: ${r}`}}}addStrategy(e){this.strategies.push(e)}removeStrategy(e){this.strategies=this.strategies.filter(r=>r.name!==e)}getStrategies(){return this.strategies.map(e=>e.name)}};
|
|
2224
|
-
`,{mode:384})}function zI(t,e){let r=Zs.join(Ks(e),"drafts");if(un.existsSync(r)||un.mkdirSync(r,{recursive:!0}),t.output.mode==="stdout+file"){let n=Zs.resolve(t.output.directory);un.existsSync(n)||un.mkdirSync(n,{recursive:!0})}}var XT=Be(jr());var YT=Be(require("readline"));var yJ=require("child_process"),EJ=require("util");var gJ={name:"@superglue/cli",version:"1.1.
|
|
2222
|
+
${o}`:i.stack}ae.exports.fetch=function(e,r=void 0){return KLe(e,r).catch(n=>{throw KW?rJ(n,KW):n&&typeof n=="object"&&Error.captureStackTrace(n,ae.exports.fetch),n})};ae.exports.Headers=Il().Headers;ae.exports.Response=gh().Response;ae.exports.Request=ud().Request;ae.exports.FormData=eE().FormData;var{setGlobalOrigin:XLe,getGlobalOrigin:e$e}=nB();ae.exports.setGlobalOrigin=XLe;ae.exports.getGlobalOrigin=e$e;var{CacheStorage:t$e}=$4(),{kConstruct:r$e}=ut();ae.exports.caches=new t$e(r$e);var{deleteCookie:n$e,getCookies:i$e,getSetCookies:o$e,setCookie:s$e,parseCookie:a$e}=K4();ae.exports.deleteCookie=n$e;ae.exports.getCookies=i$e;ae.exports.getSetCookies=o$e;ae.exports.setCookie=s$e;ae.exports.parseCookie=a$e;var{parseMIMEType:c$e,serializeAMimeType:l$e}=ci();ae.exports.parseMIMEType=c$e;ae.exports.serializeAMimeType=l$e;var{CloseEvent:u$e,ErrorEvent:d$e,MessageEvent:A$e}=EI(),{WebSocket:p$e,ping:h$e}=kW();ae.exports.WebSocket=p$e;ae.exports.CloseEvent=u$e;ae.exports.ErrorEvent=d$e;ae.exports.MessageEvent=A$e;ae.exports.ping=h$e;ae.exports.WebSocketStream=LW().WebSocketStream;ae.exports.WebSocketError=MT().WebSocketError;ae.exports.request=Qh(bd.request);ae.exports.stream=Qh(bd.stream);ae.exports.pipeline=Qh(bd.pipeline);ae.exports.connect=Qh(bd.connect);ae.exports.upgrade=Qh(bd.upgrade);ae.exports.MockClient=$Le;ae.exports.MockCallHistory=FLe;ae.exports.MockCallHistoryLog=jLe;ae.exports.MockPool=qLe;ae.exports.MockAgent=zLe;ae.exports.SnapshotAgent=HLe;ae.exports.mockErrors=GLe;var{EventSource:f$e}=ZW();ae.exports.EventSource=f$e;function g$e(){globalThis.fetch=ae.exports.fetch,globalThis.Headers=ae.exports.Headers,globalThis.Response=ae.exports.Response,globalThis.Request=ae.exports.Request,globalThis.FormData=ae.exports.FormData,globalThis.WebSocket=ae.exports.WebSocket,globalThis.CloseEvent=ae.exports.CloseEvent,globalThis.ErrorEvent=ae.exports.ErrorEvent,globalThis.MessageEvent=ae.exports.MessageEvent,globalThis.EventSource=ae.exports.EventSource}ae.exports.install=g$e});var oJ=y(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});wd.SuperglueClient=wd.SuperglueHttpError=void 0;var Sd=pn(),ln=fw(),m$e=X0(),y$e=gj(),E$e=Ti(),Js=NA(),I$e=OA(),Dh=14400*1e3,Th;if(typeof globalThis.process<"u"&&globalThis.process.versions?.node)try{let{Agent:t}=nJ();Th=new t({headersTimeout:Dh,bodyTimeout:Dh})}catch{}function iJ(t){if(t?.aborted)throw t.reason??new DOMException("Aborted","AbortError")}var OI=class extends Error{constructor(e,r,n,i){super(e),this.status=r,this.code=n,this.details=i,this.name="SuperglueHttpError"}};wd.SuperglueHttpError=OI;var zT=class{constructor({apiKey:e,apiEndpoint:r,onInfrastructureError:n,refreshToken:i,sseTokenProvider:o,tokenProvider:s}){if(!e&&!s)throw new Error("SuperglueClient requires either apiKey or tokenProvider");this.tokenProvider=s??(async()=>e),this.apiEndpoint=r??"https://api.superglue.cloud",this.sseManager=new m$e.SSELogSubscriptionManager(this.apiEndpoint,o??this.tokenProvider,i),this.onInfrastructureError=n,this.refreshToken=i}async getApiKey(){return this.tokenProvider()}async fetchWithAuthRetry(e,r){let n=await this.getApiKey(),i=await e(n);if(i.status!==401||!this.refreshToken)return i;iJ(r);let o=await this.refreshToken();return iJ(r),!o||o===n?i:(i.body?.cancel(),e(o))}isInfrastructureError(e){return(0,E$e.isAbortError)(e)?!1:!!(e instanceof TypeError&&e.message.toLowerCase().includes("fetch")||e instanceof Error&&e.name==="TimeoutError")}async restRequest(e,r,n,i,o){let a=await(await this.restResponse({method:e,path:r,body:n,extraHeaders:i,requestInit:o})).text();if(a)return JSON.parse(a)}async restData(...e){return(await this.restRequest(...e)).data}async restResponse({method:e,path:r,body:n,extraHeaders:i,requestInit:o}){let s=`${this.apiEndpoint.replace(/\/$/,"")}${r}`,a=n!=null,c=typeof FormData<"u"&&n instanceof FormData,l=u=>{let d={Authorization:`Bearer ${u}`,...i};return a&&!c&&e!=="GET"&&(d["Content-Type"]="application/json"),fetch(s,{...o,method:e,headers:d,body:a?c?n:JSON.stringify(n):void 0,signal:o?.signal??AbortSignal.timeout(Dh),...Th?{dispatcher:Th}:{}})};return this.sendAuthorized(l,o?.signal)}async sendAuthorized(e,r){let n;try{n=await this.fetchWithAuthRetry(e,r)}catch(i){throw this.isInfrastructureError(i)&&this.onInfrastructureError?.(),i}if(!n.ok)throw await this.buildHttpError(n);return n}async uploadFiles(e,r){if(typeof r?.process!="boolean")throw new Error("process must be a boolean");if(e.length===0)return[];let n=e.map(u=>({...u,contentLength:u.contentLength??this.getUploadContentLength(u.content)})),o=(await this.restRequest("POST","/v1/files/uploads",{process:r.process,...r.allowUnprocessed?{allowUnprocessed:!0}:{},files:n.map(({fileName:u,contentType:d,contentLength:A})=>({fileName:u,contentLength:A,...d?{contentType:d}:{}}))})).data.files;if(o.length!==n.length)throw await Promise.all(o.map(u=>this.deleteFileUpload(u.id).catch(()=>{}))),new Error("Upload response did not match the selected files");let s=await Promise.allSettled(o.map(async(u,d)=>{let A=n[d],p=await fetch(u.uploadUrl,{method:"PUT",body:A.content,headers:{...u.uploadHeaders,...A.contentType?{"Content-Type":A.contentType}:{}},signal:AbortSignal.timeout(Math.min(Dh,u.expiresIn*1e3))});if(!p.ok)throw new Error(`Upload failed for ${A.fileName}: ${p.status} ${p.statusText}`);return u.id})),a=s.flatMap(u=>u.status==="fulfilled"?[u.value]:[]),c=new Map;if(a.length>0)try{let u=await this.restRequest("POST","/v1/files/uploads/complete",{fileIds:a});c=new Map(u.data.files.map(d=>[d.id,d]))}catch(u){c=new Map(a.map(d=>[d,{id:d,fileName:n[o.findIndex(A=>A.id===d)]?.fileName||d,contentLength:n[o.findIndex(A=>A.id===d)]?.contentLength||0,status:"failed",error:u instanceof Error?u.message:String(u)}]))}let l=o.map((u,d)=>{let A=s[d],p=n[d];return A.status==="rejected"?{id:u.id,fileName:p.fileName,contentLength:p.contentLength,status:"failed",error:A.reason instanceof Error?A.reason.message:String(A.reason)}:c.get(u.id)||{id:u.id,fileName:p.fileName,contentLength:p.contentLength,status:"failed",error:"Upload completion returned no result"}});return await Promise.all(l.filter(u=>u.status==="failed").map(u=>this.deleteFileUpload(u.id).catch(()=>{}))),l}async deleteFileUpload(e){await this.restRequest("DELETE",`/v1/files/uploads/${encodeURIComponent(e)}`)}getUploadContentLength(e){return typeof e=="string"?new TextEncoder().encode(e).byteLength:e instanceof Uint8Array?e.byteLength:e.size}async buildHttpError(e){e.status>=500&&this.onInfrastructureError?.();let r=await e.text(),n=`HTTP ${e.status}: ${r}`,i,o;try{let s=JSON.parse(r);s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),typeof s?.code=="string"&&(i=s.code);let a=s.error;typeof a=="string"?n=a:a&&typeof a=="object"&&(n=a.message||JSON.stringify(a))}catch{}return new OI(n,e.status,i,o)}async streamRequest(e,r,n){let i=e.includes("?")?"&":"?",o=`${this.apiEndpoint.replace(/\/$/,"")}${e}${i}stream=true`,s=l=>fetch(o,{method:"POST",headers:{Authorization:`Bearer ${l}`,Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(r),signal:n??AbortSignal.timeout(Dh),...Th?{dispatcher:Th}:{}}),a;try{a=await this.fetchWithAuthRetry(s,n)}catch(l){throw this.isInfrastructureError(l)&&this.onInfrastructureError?.(),l}if(!a.ok)throw await this.buildHttpError(a);if(!(a.headers.get("content-type")||"").includes("text/event-stream")){let l=await a.text();return l?JSON.parse(l):void 0}try{return await(0,y$e.consumeEventStreamResult)(a)}catch(l){throw this.isInfrastructureError(l)&&this.onInfrastructureError?.(),l}}async subscribeToLogsSSE(e={}){return this.sseManager.subscribeToLogs(e)}async disconnect(){await this.sseManager.disconnect()}async listMemoryNotes(e={}){let r=new URLSearchParams;e.scope&&r.set("scope",e.scope),e.query&&r.set("query",e.query);let n=r.toString();return this.restData("GET",`/v1/memory-notes${n?`?${n}`:""}`)}async createMemoryNote(e){return this.restData("POST","/v1/memory-notes",e)}async updateMemoryNote(e,r){return this.restData("PATCH",`/v1/memory-notes/${encodeURIComponent(e)}`,r)}async deleteMemoryNote(e){await this.restRequest("DELETE",`/v1/memory-notes/${encodeURIComponent(e)}`)}async clearMemoryNotes(e){return(await this.restRequest("DELETE",`/v1/memory-notes?scope=${e}`)).data.deleted}async getMe(){return this.restRequest("GET","/v1/me")}async completeOnboarding(){return this.restRequest("POST","/v1/me/onboarding/complete")}async runTool(e){let r=await this.restRequest("POST",`/v1/tools/${encodeURIComponent(e.toolId)}/run`,{inputs:e.payload,files:e.files,credentials:e.credentials,includeStepResultData:e.includeStepResultData,options:e.options,runId:e.runId,stateFixture:e.stateFixture},void 0,e.signal?{signal:e.signal}:void 0);return{success:r.status==="success",data:r.data,error:r.error,tool:r.tool,stepResults:r.stepResults?.map(n=>({...n}))||[],...r.fileArtifacts&&r.fileArtifacts.length>0?{fileArtifacts:r.fileArtifacts}:{},...r.metadata?.warnings?.length?{warnings:r.metadata.warnings}:{}}}async runToolConfig(e){let r=e.createRun?"/v1/tools/run?createRun=true":"/v1/tools/run",n=await this.restRequest("POST",r,{tool:e.tool,payload:e.payload,files:e.files,credentials:e.credentials,includeStepResultData:e.includeStepResultData,options:e.options,runId:e.runId,stateFixture:e.stateFixture,executionKind:e.executionKind,parentToolId:e.parentToolId,draftId:e.draftId},e.traceId?{"X-Trace-Id":e.traceId}:void 0,e.signal?{signal:e.signal}:void 0);return{success:n.status?n.status==="success":n.success??!1,data:n.data,error:n.error,tool:n.tool||e.tool,stepResults:n.stepResults?.map(o=>({...o}))||[],...n.fileArtifacts&&n.fileArtifacts.length>0?{fileArtifacts:n.fileArtifacts}:{},...n.metadata?.warnings?.length?{warnings:n.metadata.warnings}:{}}}async abortToolExecution(e){return{success:!0,runId:(await this.restRequest("POST",`/v1/runs/${encodeURIComponent(e)}/cancel`)).runId}}async executeStep({step:e,payload:r,files:n,previousResults:i,credentials:o,credentialsList:s,options:a,runId:c,systemIds:l,connectionId:u,systemAuth:d,createRun:A,parentToolId:p,stepIndex:h,stepId:f,signal:E,stream:S}){let B={step:e,payload:r,files:n,previousResults:i,credentials:o,credentialsList:s,options:a,runId:c,systemIds:l,connectionId:u,systemAuth:d,createRun:A,parentToolId:p,stepIndex:h,stepId:f};return S?this.streamRequest("/v1/tools/step/run",B,E):this.restRequest("POST","/v1/tools/step/run",B,void 0,E?{signal:E}:void 0)}async abortStep(e){return this.restRequest("POST","/v1/tools/step/abort",{runId:e})}async executeTransformOnly({outputTransform:e,outputSchema:r,inputSchema:n,payload:i,files:o,stepResults:s,options:a,runId:c,createRun:l,parentToolId:u,stepId:d,signal:A,stream:p}){let h={outputTransform:e,outputSchema:r,inputSchema:n,payload:i,files:o,stepResults:s,options:a,runId:c,createRun:l,parentToolId:u,stepId:d};return p?this.streamRequest("/v1/tools/transform/run",h,A):this.restRequest("POST","/v1/tools/transform/run",h,void 0,A?{signal:A}:void 0)}async createRun({toolId:e,toolConfig:r,toolResult:n,stepResults:i,toolPayload:o,status:s,error:a,startedAt:c,completedAt:l,executionKind:u,parentToolId:d,draftId:A}){return this.restRequest("POST","/v1/runs",{toolId:e,toolConfig:r,toolResult:n,stepResults:i,toolPayload:o,status:s,error:a,startedAt:(0,Js.toUTCISOString)(c,"run.startedAt"),completedAt:(0,Js.toUTCISOString)(l,"run.completedAt"),executionKind:u,parentToolId:d,draftId:A})}async checkRunLimit(){return this.restData("POST","/v1/runs/check-limit")}async extract({file:e,envelope:r}){if(!e)throw new Error("File must be provided for extract.");let n=new FormData;n.append("file",e);let i=r?"/v1/extract?envelope=true":"/v1/extract";return this.restRequest("POST",i,n)}mapOpenAPIRunToRun(e){let r={running:Sd.RunStatus.RUNNING,success:Sd.RunStatus.SUCCESS,failed:Sd.RunStatus.FAILED,aborted:Sd.RunStatus.ABORTED};return{runId:e.runId??e.id,toolId:e.toolId,tool:e.tool,systemIds:e.systemIds,status:r[e.status]??Sd.RunStatus.FAILED,toolPayload:e.toolPayload,data:e.data,toolResult:e.data,error:e.error,stepResults:e.stepResults,options:e.options,requestSource:e.requestSource,traceId:e.traceId,resultStorageUri:e.resultStorageUri,userId:e.userId,userEmail:e.userEmail,userName:e.userName,metadata:{...e.metadata,executionKind:e.metadata?.executionKind??Sd.RunExecutionKind.FULL},fileArtifacts:e.fileArtifacts}}mapOpenAPIScheduleToToolSchedule(e){return{...e,lastRunAt:e.lastRunAt?(0,Js.requireUTCDate)(e.lastRunAt,"schedule.lastRunAt"):void 0,nextRunAt:(0,Js.requireUTCDate)(e.nextRunAt,"schedule.nextRunAt"),createdAt:(0,Js.requireUTCDate)(e.createdAt,"schedule.createdAt"),updatedAt:(0,Js.requireUTCDate)(e.updatedAt,"schedule.updatedAt")}}async listRuns(e={}){let r=(0,ln.createSearchListQueryParams)(e);e.toolId!==void 0&&r.set("toolId",e.toolId),e.searchUserIds?.length&&r.set("searchUserIds",e.searchUserIds.join(",")),e.includeTotal!==void 0&&r.set("includeTotal",String(e.includeTotal)),e.startedAfter!==void 0&&r.set("startedAfter",e.startedAfter instanceof Date?(0,Js.toUTCISOString)(e.startedAfter,"run.startedAfter"):e.startedAfter),e.statuses!==void 0?r.set("status",e.statuses.join(",")):e.status!==void 0&&r.set("status",e.status),e.requestSources!==void 0&&r.set("requestSources",e.requestSources.join(",")),e.executionKinds!==void 0&&r.set("executionKinds",e.executionKinds.join(",")),e.userId!==void 0&&r.set("userId",e.userId),e.systemId!==void 0&&r.set("systemId",e.systemId),e.systemIds!==void 0&&r.set("systemIds",e.systemIds.join(","));let n=r.size>0?`?${r.toString()}`:"",i=await this.restRequest("GET",`/v1/runs${n}`,void 0,void 0,{signal:e.signal});return{data:i.data.map(o=>this.mapOpenAPIRunToRun(o)),total:i.total,page:i.page,limit:i.limit,hasMore:i.hasMore}}async getActivityCounts(e){let r=new URLSearchParams;e?.from&&r.set("from",e.from instanceof Date?(0,Js.toUTCISOString)(e.from,"activity.from"):e.from),e?.to&&r.set("to",e.to instanceof Date?(0,Js.toUTCISOString)(e.to,"activity.to"):e.to);let n=r.toString();return(await this.restRequest("GET",`/v1/activity/counts${n?`?${n}`:""}`,void 0,void 0,{signal:e?.signal})).counts}async getRun(e){try{let r=await this.restRequest("GET",`/v1/runs/${encodeURIComponent(e)}`);return this.mapOpenAPIRunToRun(r)}catch(r){if(r.message?.includes("404")||r.message?.includes("not found"))return null;throw r}}async getTool(e){try{return await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}`)}catch(r){if(r.message?.includes("404")||r.message?.includes("not found")||r.message?.includes("403")||r.message?.includes("not allowed"))return null;throw r}}async getToolState(e){return(await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}/state`)).state}async setToolState(e,r){await this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}/state`,{state:r})}async deleteToolState(e){return(await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}/state`)).deletedKeys}async archiveTool(e,r=!0){return this.updateTool(e,{archived:r})}async bulkArchiveTools(e,r=!0){return this.restRequest("POST","/v1/tools/bulk/archive",{ids:e,archived:r})}async bulkDeleteTools(e){return this.restRequest("POST","/v1/tools/bulk/delete",{ids:e})}async listTools(e={}){let r=(0,ln.createListQueryParams)(e);e.includeArchived!==void 0&&r.set("includeArchived",String(e.includeArchived));let n=r.size>0?`?${r.toString()}`:"";return this.restRequest("GET",`/v1/tools${n}`)}async listAllTools(e={}){return(0,ln.listAllPages)((r,n)=>this.listTools({...e,page:r,limit:n}))}async createTool(e,r){return this.restRequest("POST","/v1/tools",{...r,id:e})}async updateTool(e,r){return this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}`,r)}async deleteTool(e){try{return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}`),!0}catch(r){if(r.message?.includes("404"))return!1;throw r}}async renameTool(e,r){return this.restRequest("POST",`/v1/tools/${encodeURIComponent(e)}/rename`,{newId:r})}async getWorkflow(e){return this.getTool(e)}async archiveWorkflow(e,r=!0){return this.upsertWorkflow(e,{archived:r})}async createWorkflow(e,r){return this.createTool(e,r)}async updateWorkflow(e,r){return this.updateTool(e,r)}async upsertWorkflow(e,r){return await this.getTool(e)?this.updateTool(e,r):this.createTool(e,r)}async deleteWorkflow(e){return this.deleteTool(e)}async renameWorkflow(e,r){return this.renameTool(e,r)}async listProjectSummaries(e={}){let r=(0,ln.createSearchListQueryParams)(e);return r.set("includeResources","false"),e.includeArchived!==void 0&&r.set("includeArchived",String(e.includeArchived)),this.restRequest("GET",`/v1/projects?${r.toString()}`)}async listAllProjectSummaries({includeArchived:e}={}){return(0,ln.listAllPages)((r,n)=>this.listProjectSummaries({page:r,limit:n,...e!==void 0?{includeArchived:e}:{}}))}async listAllProjectTasks(e){return(0,ln.listAllPages)((r,n)=>this.restRequest("GET",`/v1/projects/${encodeURIComponent(e)}/tasks?page=${r}&limit=${n}`))}async saveProjectTask({projectId:e,taskId:r,input:n}){let i=`/v1/projects/${encodeURIComponent(e)}/tasks${r?`/${encodeURIComponent(r)}`:""}`;return this.restData(r?"PATCH":"POST",i,n)}async listAllProjectLabels(e){return(0,ln.listAllPages)((r,n)=>this.restRequest("GET",`/v1/projects/${encodeURIComponent(e)}/labels?page=${r}&limit=${n}`))}async saveProjectLabel({projectId:e,labelId:r,input:n}){let i=`/v1/projects/${encodeURIComponent(e)}/labels${r?`/${encodeURIComponent(r)}`:""}`;return this.restData(r?"PATCH":"POST",i,n)}async deleteProjectLabel({projectId:e,labelId:r}){await this.restRequest("DELETE",`/v1/projects/${encodeURIComponent(e)}/labels/${encodeURIComponent(r)}`)}async listSchedules(e={}){let r=(0,ln.createListQueryParams)(e),n=r.size>0?`?${r.toString()}`:"",i=e.toolId?`/v1/tools/${encodeURIComponent(e.toolId)}/schedules${n}`:`/v1/schedules${n}`,o=await this.restRequest("GET",i);return{...o,data:o.data.map(s=>this.mapOpenAPIScheduleToToolSchedule(s))}}async listAllSchedules(e={}){return(0,ln.listAllPages)((r,n)=>this.listSchedules({...e,page:r,limit:n}))}async getToolSchedule(e,r){try{let n=await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(r)}`);return this.mapOpenAPIScheduleToToolSchedule(n)}catch(n){if(n.message?.includes("404")||n.message?.includes("not found"))return null;throw n}}async createToolSchedule(e,r){let n=await this.restRequest("POST",`/v1/tools/${encodeURIComponent(e)}/schedules`,{...r,timezone:r.timezone||(0,I$e.getRuntimeTimezone)()});return this.mapOpenAPIScheduleToToolSchedule(n)}async updateToolSchedule(e,r,n){let i=await this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(r)}`,n);return this.mapOpenAPIScheduleToToolSchedule(i)}async deleteToolSchedule(e,r){return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(r)}`),!0}async bulkSetSchedulesEnabled(e,r){return this.restRequest("POST","/v1/schedules/bulk/enable",{ids:e,enabled:r})}async bulkDeleteSchedules(e){return this.restRequest("POST","/v1/schedules/bulk/delete",{ids:e})}async listConnections(e={}){let r=(0,ln.createListQueryParams)(e);e.systemId!==void 0&&r.set("systemId",e.systemId);let n=r.size>0?`?${r.toString()}`:"";return this.restRequest("GET",`/v1/connections${n}`)}async listAllConnections(e={}){return(0,ln.listAllPages)((r,n)=>this.listConnections({...e,page:r,limit:n}))}async createOAuthApp(e){return this.restData("POST","/v1/oauth-apps",e)}async updateOAuthApp(e,r){return this.restData("PUT",`/v1/oauth-apps/${encodeURIComponent(e)}`,r)}async deleteOAuthApp(e){await this.restRequest("DELETE",`/v1/oauth-apps/${encodeURIComponent(e)}`)}async listOAuthApps({systemId:e}={}){return(0,ln.listAllPages)(async(r,n)=>{let i=new URLSearchParams({page:String(r),limit:String(n),...e?{systemId:e}:{}});return this.restRequest("GET",`/v1/oauth-apps?${i}`)})}async getConnectionSetup(e){return this.restData("GET",`/v1/connections/setup/${encodeURIComponent(e)}`)}async createConnection(e){return this.restData("POST","/v1/connections",e)}async replaceConnection(e,r){return this.restData("PUT",`/v1/connections/${encodeURIComponent(e)}`,{credentials:r})}async updateConnection(e,r){return this.restData("PATCH",`/v1/connections/${encodeURIComponent(e)}`,r)}async deleteConnection(e){await this.restRequest("DELETE",`/v1/connections/${encodeURIComponent(e)}`)}async setDefaultConnection(e){await this.restRequest("POST",`/v1/connections/${encodeURIComponent(e)}/default`)}async listSystems(e={}){let r=(0,ln.createListQueryParams)(e),n=r.size>0?`?${r.toString()}`:"";return this.restRequest("GET",`/v1/systems${n}`)}async listAllSystems(e={}){return(0,ln.listAllPages)((r,n)=>this.listSystems({...e,page:r,limit:n}))}async createOAuthExchange(e){return(await this.restRequest("POST","/v1/oauth/exchanges",e)).data}async completeOAuthExchange(e,r){return(await this.restRequest("POST",`/v1/oauth/exchanges/${encodeURIComponent(e)}/complete`,r)).data}async describeOAuthProviderPage(e){return(await this.restRequest("POST",`/v1/oauth/exchanges/${encodeURIComponent(e)}/provider-page`)).data}async generateCredentialsLink(e){try{return{success:!0,credentialsUrl:(await this.restRequest("POST","/v1/authenticate",e||{})).data.credentialsUrl}}catch(r){return{success:!1,error:r.message}}}};wd.SuperglueClient=zT});var aJ=y(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.UnquotedKeyStrategy=rr.TripleQuoteStrategy=rr.TrailingCommaStrategy=rr.SingleQuoteStrategy=rr.PythonLiteralStrategy=rr.CommentStrategy=rr.ResilientJsonParser=rr.RepairStrategy=void 0;rr.parseJsonResilient=C$e;rr.parseJSON=b$e;var $i=class{validate(e){try{return JSON.parse(e),!0}catch{return!1}}};rr.RepairStrategy=$i;var xI=class extends $i{constructor(){super(...arguments),this.name="TripleQuoteRepair",this.description="Converts triple-quoted strings to proper JSON, parsing nested JSON content"}canApply(e){return/"""/.test(e)}apply(e){return e.replace(/"""([\s\S]*?)"""/g,(r,n)=>{let i=n.trim();if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{let s=JSON.parse(i);return JSON.stringify(s)}catch{return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`})}};rr.TripleQuoteStrategy=xI;var UI=class extends $i{constructor(){super(...arguments),this.name="PythonLiteralRepair",this.description="Converts Python literals to JavaScript equivalents"}canApply(e){return/\b(None|True|False)\b/.test(e)}apply(e){return e.replace(/\bNone\b/g,"null").replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false")}};rr.PythonLiteralStrategy=UI;var MI=class extends $i{constructor(){super(...arguments),this.name="TrailingCommaRepair",this.description="Removes trailing commas from objects and arrays"}canApply(e){return/,\s*[}\]]/.test(e)}apply(e){return e.replace(/,(\s*[}\]])/g,"$1")}};rr.TrailingCommaStrategy=MI;var PI=class extends $i{constructor(){super(...arguments),this.name="SingleQuoteRepair",this.description="Converts single quotes to double quotes"}canApply(e){return/[{,]\s*'[^']*'\s*:/.test(e)||/:\s*'[^']*'/.test(e)}apply(e){let r=e.replace(/([{,]\s*)'([^']+)'(\s*:)/g,'$1"$2"$3');return r=r.replace(/(:\s*)'([^']+)'(\s*[,}])/g,'$1"$2"$3'),r}};rr.SingleQuoteStrategy=PI;var LI=class extends $i{constructor(){super(...arguments),this.name="UnquotedKeyRepair",this.description="Adds quotes to unquoted object keys"}canApply(e){return/[{,]\s*[a-zA-Z_$][a-zA-Z0-9_$]*\s*:/.test(e)}apply(e){return e.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)(\s*:)/g,'$1"$2"$3')}};rr.UnquotedKeyStrategy=LI;var $I=class extends $i{constructor(){super(...arguments),this.name="CommentRemoval",this.description="Removes JavaScript-style comments"}canApply(e){return/\/\/.*$|\/\*[\s\S]*?\*\//m.test(e)}apply(e){let r=e.replace(/\/\/.*$/gm,"");return r=r.replace(/\/\*[\s\S]*?\*\//g,""),r}};rr.CommentStrategy=$I;var qT=class extends $i{constructor(){super(...arguments),this.name="UnescapedControlCharactersRepair",this.description="Escapes unescaped control characters (newlines, tabs, etc.) in JSON strings"}canApply(e){try{return JSON.parse(e),!1}catch(r){let n=r.message||"";return n.includes("control character")||n.includes("Bad control")||n.includes("Unexpected token")&&/[\n\r\t]/.test(e)}}apply(e){let r="",n=!1,i=!1;for(let o=0;o<e.length;o++){let s=e[o],a=o>0?e[o-1]:"";if(i){r+=s,i=!1;continue}if(s==="\\"&&n){r+=s,i=!0;continue}if(s==='"'&&a!=="\\"){n=!n,r+=s;continue}if(n)switch(s){case`
|
|
2223
|
+
`:r+="\\n";break;case"\r":r+="\\r";break;case" ":r+="\\t";break;case"\b":r+="\\b";break;case"\f":r+="\\f";break;default:let c=s.charCodeAt(0);c<32?r+="\\u"+("0000"+c.toString(16)).slice(-4):r+=s}else r+=s}return r}},HT=class extends $i{constructor(){super(...arguments),this.name="TrailingCharactersRepair",this.description="Removes trailing characters after valid JSON structure"}canApply(e){let r=e.trim();if(!r.startsWith("{")&&!r.startsWith("["))return!1;let n=0,i=0,o=!1,s=!1;for(let a=0;a<r.length;a++){let c=r[a];if(o)s?s=!1:c==="\\"?s=!0:c==='"'&&(o=!1);else if(c==='"')o=!0;else if(c==="{")n++;else if(c==="}"){if(n--,n===0&&i===0&&a>0&&a<r.length-1)return!0}else if(c==="[")i++;else if(c==="]"&&(i--,i===0&&n===0&&a>0&&a<r.length-1))return!0}return!1}apply(e){let r=e.trim(),n=0,i=0,o=!1,s=!1,a=-1;for(let c=0;c<r.length;c++){let l=r[c];if(o)s?s=!1:l==="\\"?s=!0:l==='"'&&(o=!1);else if(l==='"')o=!0;else if(l==="{")n++;else if(l==="}"){if(n--,n===0&&i===0&&c>0){a=c;break}}else if(l==="[")i++;else if(l==="]"&&(i--,i===0&&n===0&&c>0)){a=c;break}}return a>0&&a<r.length-1?r.substring(0,a+1):e}},kh=class{constructor(e={}){this.strategies=[],this.repairLog=[],this.options={attemptRepair:!0,maxDepth:10,preserveStringsOnFailure:!1,logRepairs:!1,...e},this.initializeDefaultStrategies(),e.customStrategies&&this.strategies.push(...e.customStrategies)}initializeDefaultStrategies(){this.strategies=[new xI,new PI,new qT,new HT,new UI,new MI,new LI,new $I]}parse(e){let r=Date.now();this.repairLog=[];let n=e instanceof Buffer?e.toString("utf8"):String(e);try{return{success:!0,data:JSON.parse(n),metadata:{parseTime:Date.now()-r,strategiesApplied:[]}}}catch(s){if(!this.options.attemptRepair)return{success:!1,error:`JSON parse error: ${s}`,metadata:{parseTime:Date.now()-r}}}let i=n,o=[];for(let s of this.strategies)if(s.canApply(i)){let a=i;if(i=s.apply(i),a!==i){o.push(s.name),this.repairLog.push(s.description),this.options.logRepairs&&console.log(`Applied ${s.name}: ${s.description}`);try{return{success:!0,data:JSON.parse(i),repairs:this.repairLog,metadata:{parseTime:Date.now()-r,strategiesApplied:o}}}catch{}}}try{return{success:!0,data:JSON.parse(i),repairs:this.repairLog,metadata:{parseTime:Date.now()-r,strategiesApplied:o}}}catch(s){let a=this.aggressiveFallback(i);return a.success?{...a,repairs:[...this.repairLog,"Applied aggressive fallback"],metadata:{parseTime:Date.now()-r,strategiesApplied:[...o,"AggressiveFallback"]}}:{success:!1,error:`Failed to parse JSON after applying ${o.length} strategies: ${s}`,repairs:this.repairLog,metadata:{parseTime:Date.now()-r,strategiesApplied:o}}}}aggressiveFallback(e){try{let r=e.indexOf("{"),n=e.indexOf("[");if(r===-1&&n===-1)return{success:!1,error:"No JSON-like structure found"};let i=r===-1?n:n===-1?r:Math.min(r,n),o=e.substring(i);for(let a of this.strategies)a.canApply(o)&&(o=a.apply(o));return{success:!0,data:JSON.parse(o)}}catch(r){return{success:!1,error:`Aggressive fallback failed: ${r}`}}}addStrategy(e){this.strategies.push(e)}removeStrategy(e){this.strategies=this.strategies.filter(r=>r.name!==e)}getStrategies(){return this.strategies.map(e=>e.name)}};rr.ResilientJsonParser=kh;var sJ=new kh;function C$e(t,e){return(e?new kh(e):sJ).parse(t)}function b$e(t){let e=sJ.parse(t);if(e.success)return e.repairs&&e.repairs.length>0&&console.log("JSON parsed with repairs:",e.repairs),e.data;throw new Error(`Failed to parse JSON: ${e.error}`)}});var lJ=y(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.MANAGED_OAUTH_APP_PREFIX=void 0;Er.projectOAuthAppAuthentication=_$e;Er.withoutOAuthAppOwnedFields=B$e;Er.hasOAuthClientChanged=v$e;Er.isDynamicOAuthConfiguration=Q$e;Er.isReusableOAuthAppForTemplate=T$e;Er.findOrganizationOAuthApp=D$e;Er.getManagedOAuthTemplateId=cJ;Er.getOAuthAppSharedConfiguration=k$e;Er.copyOAuthAppConfiguration=R$e;Er.encryptConnectionAuthentication=N$e;Er.decryptConnectionAuthentication=O$e;Er.isManagedOAuthEndpointAllowed=x$e;var S$e=Ty(),w$e=Ti();function _$e(t){let{clientSecret:e,config:r,...n}=t,{extraHeaders:i,extraBodyParams:o,...s}=r??{};return{...n,...r?{config:s}:{}}}function B$e(t){if(!t.oauthAppId)return t;let{clientId:e,clientSecret:r,tokenUrl:n,...i}=t;return cJ(t)&&n?{...i,tokenUrl:n}:i}function v$e(t,e){return t.type!=="oauth2"?!1:e.type!=="oauth2"?!0:t.oauthAppId||e.oauthAppId?t.oauthAppId!==e.oauthAppId:t.clientId!==e.clientId}Er.MANAGED_OAUTH_APP_PREFIX="managed:";function Q$e({authentication:t,template:e}){return t.oauthClientMode==="dynamic"||!!e?.oauth?.registrationUrl&&!t.clientSecret}function T$e({app:t,template:e}){return!e?.oauth?.registrationUrl||!!t.clientSecretHash}function D$e({apps:t,systemId:e,templateId:r}){return t.filter(n=>n.source==="organization"&&(n.systemId===e||r!==void 0&&n.templateId===r)).sort((n,i)=>(n.createdAt??"").localeCompare(i.createdAt??""))[0]}function cJ(t){if(t?.type==="oauth2")return t.oauthAppId?.startsWith(Er.MANAGED_OAUTH_APP_PREFIX)?t.oauthAppId.slice(Er.MANAGED_OAUTH_APP_PREFIX.length):void 0}function k$e(t){let{grantType:e,scopes:r,oauthAppId:n,...i}=t;return i}function R$e({appAuthentication:t,authentication:e}){if(e?.type!=="oauth2")return{...t};let r=Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0));return{...t,...r,config:{...t.config,...e.config}}}function N$e({authentication:t,encrypt:e}){if(t.type!=="oauth2")return t;let r={...t,config:{...t.config}};t.clientSecret!==void 0&&(r.clientSecret=e({value:t.clientSecret}).value);for(let n of["extraHeaders","extraBodyParams"]){let i=t.config?.[n];i!==void 0&&(r.config[n]=e({value:(0,w$e.safeStringify)(i)}).value)}return r}function O$e({authentication:t,decrypt:e}){if(t.type!=="oauth2")return t;let r={...t,config:{...t.config}};t.clientSecret!==void 0&&(r.clientSecret=e({value:t.clientSecret}).value);for(let n of["extraHeaders","extraBodyParams"]){let i=t.config?.[n];typeof i=="string"&&(r.config[n]=JSON.parse(e({value:i}).value))}return r}function x$e({templateId:t,endpoint:e,url:r}){let n=S$e.systems[t]?.oauth,i=n?.[e];if(!n?.managed||!i)return!1;try{let o=new URL(r),s=new URL(i);return o.protocol!=="https:"||o.port||o.username||o.password||o.hash||o.pathname!==s.pathname?!1:o.hostname===s.hostname||(n.managedEndpointHosts??[]).some(a=>a.startsWith("*.")?o.hostname.endsWith(a.slice(1)):o.hostname===a)}catch{return!1}}});var dJ=y(uJ=>{"use strict";Object.defineProperty(uJ,"__esModule",{value:!0})});var jr=y(re=>{"use strict";var U$e=re&&re.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),ue=re&&re.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&U$e(e,t,r)};Object.defineProperty(re,"__esModule",{value:!0});re.SSELogSubscriptionManager=re.SuperglueHttpError=re.SuperglueClient=void 0;ue(RC(),re);ue(TP(),re);ue(ZS(),re);ue(PP(),re);ue(JP(),re);ue(KP(),re);ue(nL(),re);ue(iL(),re);ue(sL(),re);ue(sw(),re);ue(NL(),re);ue(pg(),re);ue(PL(),re);ue(LL(),re);ue($L(),re);ue(FL(),re);ue(fw(),re);ue(zL(),re);ue(GL(),re);ue(du(),re);ue(XL(),re);ue(gw(),re);ue(V$(),re);ue(Hw(),re);ue(Ww(),re);ue(J$(),re);ue(Z$(),re);ue(X$(),re);ue(VF(),re);ue(JF(),re);ue(ZF(),re);ue(XF(),re);ue(e1(),re);ue(g1(),re);ue(w0(),re);ue(Km(),re);ue(S0(),re);ue(C1(),re);ue(S1(),re);ue(R0(),re);ue(k1(),re);ue(Cm(),re);ue(P1(),re);ue($1(),re);ue(bm(),re);ue(b0(),re);ue(rj(),re);ue(nj(),re);ue(Ty(),re);ue(aj(),re);ue(cj(),re);ue(lj(),re);ue(Aj(),re);ue(hj(),re);ue(pn(),re);ue(Ti(),re);ue(fj(),re);ue(H0(),re);ue(NA(),re);ue(OA(),re);var AJ=oJ();Object.defineProperty(re,"SuperglueClient",{enumerable:!0,get:function(){return AJ.SuperglueClient}});Object.defineProperty(re,"SuperglueHttpError",{enumerable:!0,get:function(){return AJ.SuperglueHttpError}});var M$e=X0();Object.defineProperty(re,"SSELogSubscriptionManager",{enumerable:!0,get:function(){return M$e.SSELogSubscriptionManager}});ue(aJ(),re);ue(lJ(),re);ue(dJ(),re)});var wC=require("commander");var un=Be(require("fs")),fJ=Be(require("os")),Zs=Be(require("path")),Rh=Be(jr()),pJ=new Set(["runner","builder","admin"]),hJ={output:{mode:"stdout",directory:".superglue/output"},preset:"admin"};function Ks(t){let e=Zs.join(process.cwd(),".superglue"),r=fJ.homedir();if(!r)return e;let n=Zs.join(r,".superglue");return t===!0?e:t===!1?n:un.existsSync(Zs.join(e,"config.json"))?e:n}function GT(t){return Zs.join(Ks(t),"config.json")}function FI(t){let e=GT(t);if(!un.existsSync(e))return{};try{return JSON.parse(un.readFileSync(e,"utf-8"))}catch{return{}}}function _d(t){let e=FI(),r=t.apiKey||(0,Rh.readProcessEnvironmentValue)("SUPERGLUE_API_KEY")||e.apiKey||"",n=t.endpoint||(0,Rh.readProcessEnvironmentValue)("SUPERGLUE_API_ENDPOINT")||e.endpoint||"https://api.superglue.cloud",i=(0,Rh.readProcessEnvironmentValue)("SUPERGLUE_WEB_ENDPOINT")||e.webEndpoint||n.replace(/:3002\b/,":3001").replace(/api\.superglue/,"app.superglue"),o=(0,Rh.readProcessEnvironmentValue)("SUPERGLUE_CLI_PRESET"),s=o&&pJ.has(o)?o:e.preset&&pJ.has(e.preset)?e.preset:"admin";return{...hJ,...e,apiKey:r,endpoint:n,webEndpoint:i,preset:s,output:{...hJ.output,...e.output}}}function jI(t,e){let r=Ks(e);un.existsSync(r)||un.mkdirSync(r,{recursive:!0}),un.writeFileSync(Zs.join(r,"config.json"),JSON.stringify(t,null,2)+`
|
|
2224
|
+
`,{mode:384})}function zI(t,e){let r=Zs.join(Ks(e),"drafts");if(un.existsSync(r)||un.mkdirSync(r,{recursive:!0}),t.output.mode==="stdout+file"){let n=Zs.resolve(t.output.directory);un.existsSync(n)||un.mkdirSync(n,{recursive:!0})}}var XT=Be(jr());var YT=Be(require("readline"));var yJ=require("child_process"),EJ=require("util");var gJ={name:"@superglue/cli",version:"1.1.245",bin:{sg:"./dist/cli.js"},files:[".claude-plugin/","dist/","skills/","LICENSE"],dependencies:{commander:"15.0.0-0","fast-json-patch":"3.1.1"},devDependencies:{"@superglue/shared":"file:../shared","@types/node":"25.5.0",tsup:"8.5.1",typescript:"5.8.3"},scripts:{build:"tsup && (cp -r skills dist/ 2>/dev/null || true)",dev:"tsup --watch","type-check":"tsc --noEmit",prepublishOnly:"npm run build"},publishConfig:{access:"public"}};var L$e=(0,EJ.promisify)(yJ.exec),zr=gJ.version;function mJ(t){let e=t.match(/^(\d+)(?:-(.+))?$/);return e?{numeric:parseInt(e[1],10),prerelease:e[2]||null}:{numeric:0,prerelease:t}}function HI(t,e){let r=t.split("."),n=e.split("."),i=Math.max(r.length,n.length);for(let o=0;o<i;o++){let s=mJ(r[o]||"0"),a=mJ(n[o]||"0");if(s.numeric<a.numeric)return-1;if(s.numeric>a.numeric||s.prerelease===null&&a.prerelease!==null)return 1;if(s.prerelease!==null&&a.prerelease===null)return-1;if(s.prerelease!==null&&a.prerelease!==null){if(s.prerelease<a.prerelease)return-1;if(s.prerelease>a.prerelease)return 1}}return 0}async function GI(){try{let t=await fetch("https://registry.npmjs.org/@superglue/cli/latest",{signal:AbortSignal.timeout(5e3)});return t.ok&&(await t.json()).version||null}catch{return null}}var qI=null;function IJ(){Ie()&&(qI=GI())}async function CJ(){if(!(!Ie()||!qI)){try{let t=new Promise(r=>{setTimeout(()=>r(null),2e3).unref()}),e=await Promise.race([qI,t]);e&&HI(zr,e)<0&&(console.error(""),console.error(`${C.cyan}${C.bold} Update available: ${zr} \u2192 ${e}${C.reset}`),console.error(`${C.cyan} Run ${C.bold}sg update${C.reset}${C.cyan} to upgrade${C.reset}`),console.error(""))}catch{}qI=null}}async function bJ(){let t=await GI();if(!t)return{success:!1,message:"Could not fetch latest version from npm"};if(HI(zr,t)>=0)return{success:!0,message:`Already on latest version (${zr})`};try{return await L$e("npm install -g @superglue/cli@latest"),{success:!0,message:`Updated from ${zr} to ${t}`}}catch(e){return{success:!1,message:`Update failed: ${e.message}. Try manually: npm install -g @superglue/cli@latest`}}}var Ie=()=>process.argv.includes("--table")&&process.stdout.isTTY,mi=()=>process.argv.includes("--full"),C={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m"};function SJ(t,e){let r=e||t;return`\x1B]8;;${t}\x07${C.underline}${C.cyan}${r}${C.reset}\x1B]8;;\x07`}function wJ(){if(!Ie())return;let t=C.reset,e=C.dim,r="\x1B[47;30m",n=[" #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@- "," =@@@- @@@@ "," @@@ @@% "," -@@ @@@@= @@@ @@@ @@@@@#@ @@@@@@@ @@@@@@@ @@@@@@ @@@ @@@ @@@ @@@@@@* %@@ "," @@ @@@ *@ @@@ @@@ @@@ :@@ @@@ @@@ -@@ @@@ @% @@@ @@@ @@@ @@* @@# "," #@@ @@@# @@@ @@@ @@@ :@@ @@@ @@@ -@@ @@@ @@@ @@@ @@@ @@* @@ "," @@- @@@@= @@@ @@@ @@@@@@@ @@@@@@ @@@@@@@ @@@ @@% @@@ @@@ @@@ @@@@@. @@."," #@% .@@@@ @@@ @@@ @@@ @@@ @@@ -@@ @@@ @@% @@@ @@@ @@@ @@* @@ "," @@ @ @@@ @@@ @@@ @@@ @@@ @@@ -@@ @@@ @@% @@@ @@@ @@@ @@* *@@ "," -@@ @@@@= @@@@@@ @@@ @@@@@@@ @@@ -@@ @@@@@@ @@@@@@% @@@@@@. @@@@@@* #@@ "," :@@* @@@ "," %@@@ =@@@. "," :@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@% "];console.log(""),n.forEach(i=>{let o=i.search(/\S/),s=i.length-[...i].reverse().join("").search(/\S/)-1;if(o===-1)return console.log(" "+i);let a=i.slice(0,o),c=i.slice(o,s+1).split("").map(u=>u===" "?" ":"\u2588").join(""),l=i.slice(s+1);console.log(` ${a}${r}${c}${t}${l}`)}),console.log(` ${e} CLI v${zr}${t}`),console.log("")}function nr(t){if(!Ie())return{stop:()=>{},update:()=>{},log:()=>{}};let e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],r=0,n=t,i=()=>process.stdout.write("\r\x1B[2K"),o=()=>{process.stdout.write(`\r ${C.cyan}${e[r++%e.length]}${C.reset} ${n}`)},s=setInterval(o,80);return{update:a=>{n=a},log:a=>{i(),console.log(` ${C.dim}\u2502${C.reset} ${a}`),o()},stop:a=>{clearInterval(s),i(),a&&console.log(` ${a}`)}}}function de(t){Ie()?YI(t):console.log(JSON.stringify(t,null,2))}function Me(t,e){Ie()?(console.log(` ${C.green}\u2713${C.reset} ${t}`),e&&YI(e,4)):console.log(JSON.stringify({success:!0,message:t,...e&&typeof e=="object"?e:{data:e}}))}function D(t,e){Ie()?(console.error(` ${C.red}\u2717${C.reset} ${t}`),e&&YI(e,4)):console.error(JSON.stringify({success:!1,error:t,details:e}))}function Mn(t){Ie()&&console.log(` ${C.dim}${t}${C.reset}`)}function Tl(t){Ie()&&(console.log(`
|
|
2225
2225
|
${C.bold}${C.cyan}${t}${C.reset}`),console.log(` ${C.dim}${"\u2500".repeat(t.length)}${C.reset}`))}function lr(t,e,r){if(!Ie()){console.log(JSON.stringify({success:!0,total:r?.total??t.length,items:t}));return}if(t.length===0){console.log(`
|
|
2226
2226
|
${C.dim}0 results${C.reset}
|
|
2227
2227
|
`);return}let n=e||Object.keys(t[0]),i=mi()?1/0:60,o=n.map(u=>Math.min(i,Math.max(u.length,...t.map(d=>String(d[u]??"").replace(/[\n\r]+/g," ").trim().length))));console.log("");let s=n.map((u,d)=>`${C.bold}${C.cyan}${u.toUpperCase().padEnd(o[d])}${C.reset}`).join(" ");console.log(` ${s}`);let a=o.map(u=>`${C.dim}${"\u2500".repeat(u)}${C.reset}`).join(`${C.dim}\u2500\u2500${C.reset}`);console.log(` ${a}`);for(let u of t){let d=n.map((A,p)=>{let h=String(u[A]??"").replace(/[\n\r]+/g," ").trim();if(h.length>i){let E=`\u2026 (${h.length})`;h=h.slice(0,Math.max(0,i-E.length))+`${C.dim}${E}${C.reset}`}return A==="status"?`${{success:C.green,running:C.yellow,failed:C.red,aborted:C.red,error:C.red,pending:C.dim}[h.toLowerCase()]||""}${h.padEnd(o[p])}${C.reset}`:h.padEnd(o[p])}).join(" ");console.log(` ${d}`)}let c=r?.total??t.length,l=c===t.length?`${t.length} result${t.length===1?"":"s"}`:`${t.length} of ${c} result${c===1?"":"s"}`;console.log(`
|
|
@@ -2234,8 +2234,8 @@ ${o}`:i.stack}ae.exports.fetch=function(e,r=void 0){return KLe(e,r).catch(n=>{th
|
|
|
2234
2234
|
`);process.stdout.write(`\x1B[${e.length-1}A\r`)};return console.log(`
|
|
2235
2235
|
${C.bold}${t}${C.reset} ${C.dim}(\u2191/\u2193 to select, enter to confirm)${C.reset}`),i(),new Promise(s=>{process.stdin.setRawMode(!0),process.stdin.resume();let a=c=>{let l=c.toString();if(l==="\r"||l===`
|
|
2236
2236
|
`){process.stdin.setRawMode(!1),process.stdin.removeListener("data",a),process.stdin.pause(),s(n);return}if(l===""&&(process.stdin.setRawMode(!1),process.exit(130)),l==="\x1B[A"||l==="k")n=(n-1+e.length)%e.length;else if(l==="\x1B[B"||l==="j")n=(n+1)%e.length;else return;o(),i()};process.stdin.on("data",a)})}var dn=Be(require("fs")),KI=Be(require("path"));var VT=6e4,JI=new Map;function Dl(t){return t.replace(/\/+$/,"")}function F$e(t){let e=Number(t)*1e3;if(!(!Number.isFinite(e)||e<=0))return new Date(Date.now()+e).toISOString()}function j$e(t,e){let r=Date.parse(t.updatedAt);if(!Number.isFinite(r))return VT;let n=e-r;return!Number.isFinite(n)||n<=0?VT:Math.min(VT,Math.floor(n/2))}function z$e(t){if(!t.tokens.accessToken)return!1;if(!t.tokens.expiresAt)return!0;let e=Date.parse(t.tokens.expiresAt);return Number.isFinite(e)&&e-j$e(t,e)>Date.now()}function ZI(t){return typeof t=="string"&&t.length>0}function Bd(){return KI.join(Ks(!1),"auth.json")}function WT(){let t=Bd();if(!dn.existsSync(t))return null;try{let e=JSON.parse(dn.readFileSync(t,"utf-8"));return!e||typeof e!="object"||!ZI(e.endpoint)||!ZI(e.webEndpoint)||!ZI(e.client?.clientId)||!ZI(e.tokens?.accessToken)?null:e}catch{return null}}function JT(t){let e=Bd(),r=KI.dirname(e);dn.existsSync(r)||dn.mkdirSync(r,{recursive:!0}),dn.writeFileSync(e,JSON.stringify(t,null,2)+`
|
|
2237
|
-
`,{mode:384}),dn.chmodSync(e,384)}function TJ(){let t=Bd();return dn.existsSync(t)?(dn.rmSync(t),!0):!1}function vJ(t){let e=WT();return e&&Dl(e.endpoint)===Dl(t)?e:null}function ZT(t){let e=t.tokenResponse.access_token;if(!e)throw new Error("OAuth token response did not include an access token");let r=new Date().toISOString();return{endpoint:Dl(t.endpoint),webEndpoint:Dl(t.webEndpoint),...t.tokenEndpoint?{tokenEndpoint:Dl(t.tokenEndpoint)}:{},client:t.client,tokens:{accessToken:e,refreshToken:t.tokenResponse.refresh_token||t.previousRefreshToken,expiresAt:F$e(t.tokenResponse.expires_in),scope:t.tokenResponse.scope,tokenType:t.tokenResponse.token_type},createdAt:r,updatedAt:r}}function q$e(t){return t.tokenEndpointAuthMethod?t.tokenEndpointAuthMethod:t.clientSecret?"client_secret_basic":"none"}function QJ(t){return new URLSearchParams({credential:t}).toString().slice(11)}function KT(t,e){let r=new URLSearchParams(e),n={"Content-Type":"application/x-www-form-urlencoded"},i=q$e(t);if(i==="client_secret_basic"){if(!t.clientSecret)throw new Error("OAuth client_secret_basic authentication requires a client secret.");let o=`${QJ(t.clientId)}:${QJ(t.clientSecret)}`;return n.Authorization=`Basic ${Buffer.from(o,"utf8").toString("base64")}`,{body:r,headers:n}}if(r.set("client_id",t.clientId),i==="client_secret_post"){if(!t.clientSecret)throw new Error("OAuth client_secret_post authentication requires a client secret.");r.set("client_secret",t.clientSecret)}return{body:r,headers:n}}async function XI(t,e=`HTTP ${t.status}`){let r=await t.json().catch(()=>({}));if(!t.ok){let n=r.error_description||r.error||e;throw new Error(n)}return r}async function H$e(t){if(!t.tokens.refreshToken)throw new Error("OAuth session expired. Run `sg login` to authenticate again.");let e=KT(t.client,{grant_type:"refresh_token",refresh_token:t.tokens.refreshToken}),r=await fetch(t.tokenEndpoint||`${Dl(t.endpoint)}/oauth2/token`,{method:"POST",headers:e.headers,body:e.body}),n=await XI(r,`OAuth token request failed (${r.status})`),i={...ZT({endpoint:t.endpoint,webEndpoint:t.webEndpoint,tokenEndpoint:t.tokenEndpoint,client:t.client,tokenResponse:n,previousRefreshToken:t.tokens.refreshToken}),createdAt:t.createdAt};return JT(i),i}function G$e(t){let e=Dl(t.endpoint),r=JI.get(e);if(r)return r;let n=H$e(t).finally(()=>{JI.get(e)===n&&JI.delete(e)});return JI.set(e,n),n}function DJ(t){return vJ(t.endpoint)?async()=>{let r=vJ(t.endpoint);if(!r)throw new Error("No OAuth session found. Run `sg login` to authenticate.");return z$e(r)?r.tokens.accessToken:(await G$e(r)).tokens.accessToken}:null}function eC(t){if(t.apiKey)return new XT.SuperglueClient({apiKey:t.apiKey,apiEndpoint:t.endpoint});let e=DJ(t);return e||(D("No authentication configured. Run `sg login`. For headless/API-key auth, set SUPERGLUE_API_KEY or pass --api-key. For custom/self-hosted instances, also set SUPERGLUE_API_ENDPOINT or pass --endpoint."),process.exit(1)),new XT.SuperglueClient({tokenProvider:e,apiEndpoint:t.endpoint})}var ec=Be(require("fs")),kl=Be(require("path")),kJ=Be(require("os")),eD=require("commander"),vd=Be(jr());function RJ(t){t.command("init",{hidden:!0}).description("Legacy API-key setup for headless environments").option("--web-endpoint <url>","Web endpoint for OAuth callbacks").addOption(new eD.Option("--output-mode <mode>","Output mode: stdout or stdout+file").choices(["stdout","stdout+file"]).default("stdout")).option("--output-dir <dir>","Output directory for stdout+file mode",".superglue/output").option("--global","Save config globally (~/.superglue/) instead of locally").addOption(new eD.Option("--preset <preset>","Capability preset: runner, builder, or admin").choices(["runner","builder","admin"]).default("admin")).action(async function(e){let r=this.parent?.opts()??{},n=r.apiKey||(0,vd.readProcessEnvironmentValue)("SUPERGLUE_API_KEY"),i=r.endpoint||(0,vd.readProcessEnvironmentValue)("SUPERGLUE_API_ENDPOINT"),o=n||!process.stdin.isTTY,s,a,c,l,u,d,A;if(o){s=n,s||(D("API key is required (--api-key or SUPERGLUE_API_KEY)"),process.exit(1)),a=i||"https://api.superglue.cloud";let B=a.replace(/:3002\b/,":3001").replace(/api\.superglue/,"app.superglue");c=e.webEndpoint||B,l=e.outputMode==="stdout+file"?"stdout+file":"stdout",u=e.outputDir,d=!e.global,A=e.preset;let _=
|
|
2238
|
-
`),Tl("Authentication"),console.log(` ${C.dim}Get your API key at${C.reset} ${SJ("https://app.superglue.cloud/api-keys")}`),console.log(""),s=await BJ(" API Key"),s||(D("API key is required"),process.exit(1)),a=await VI(" API Endpoint",i||"https://api.superglue.cloud");let B=a.replace(/:3002\b/,":3001").replace(/api\.superglue/,"app.superglue");c=await VI(" Web Endpoint (for OAuth callbacks)",B);let _=
|
|
2237
|
+
`,{mode:384}),dn.chmodSync(e,384)}function TJ(){let t=Bd();return dn.existsSync(t)?(dn.rmSync(t),!0):!1}function vJ(t){let e=WT();return e&&Dl(e.endpoint)===Dl(t)?e:null}function ZT(t){let e=t.tokenResponse.access_token;if(!e)throw new Error("OAuth token response did not include an access token");let r=new Date().toISOString();return{endpoint:Dl(t.endpoint),webEndpoint:Dl(t.webEndpoint),...t.tokenEndpoint?{tokenEndpoint:Dl(t.tokenEndpoint)}:{},client:t.client,tokens:{accessToken:e,refreshToken:t.tokenResponse.refresh_token||t.previousRefreshToken,expiresAt:F$e(t.tokenResponse.expires_in),scope:t.tokenResponse.scope,tokenType:t.tokenResponse.token_type},createdAt:r,updatedAt:r}}function q$e(t){return t.tokenEndpointAuthMethod?t.tokenEndpointAuthMethod:t.clientSecret?"client_secret_basic":"none"}function QJ(t){return new URLSearchParams({credential:t}).toString().slice(11)}function KT(t,e){let r=new URLSearchParams(e),n={"Content-Type":"application/x-www-form-urlencoded"},i=q$e(t);if(i==="client_secret_basic"){if(!t.clientSecret)throw new Error("OAuth client_secret_basic authentication requires a client secret.");let o=`${QJ(t.clientId)}:${QJ(t.clientSecret)}`;return n.Authorization=`Basic ${Buffer.from(o,"utf8").toString("base64")}`,{body:r,headers:n}}if(r.set("client_id",t.clientId),i==="client_secret_post"){if(!t.clientSecret)throw new Error("OAuth client_secret_post authentication requires a client secret.");r.set("client_secret",t.clientSecret)}return{body:r,headers:n}}async function XI(t,e=`HTTP ${t.status}`){let r=await t.json().catch(()=>({}));if(!t.ok){let n=r.error_description||r.error||e;throw new Error(n)}return r}async function H$e(t){if(!t.tokens.refreshToken)throw new Error("OAuth session expired. Run `sg login` to authenticate again.");let e=KT(t.client,{grant_type:"refresh_token",refresh_token:t.tokens.refreshToken}),r=await fetch(t.tokenEndpoint||`${Dl(t.endpoint)}/oauth2/token`,{method:"POST",headers:e.headers,body:e.body}),n=await XI(r,`OAuth token request failed (${r.status})`),i={...ZT({endpoint:t.endpoint,webEndpoint:t.webEndpoint,tokenEndpoint:t.tokenEndpoint,client:t.client,tokenResponse:n,previousRefreshToken:t.tokens.refreshToken}),createdAt:t.createdAt};return JT(i),i}function G$e(t){let e=Dl(t.endpoint),r=JI.get(e);if(r)return r;let n=H$e(t).finally(()=>{JI.get(e)===n&&JI.delete(e)});return JI.set(e,n),n}function DJ(t){return vJ(t.endpoint)?async()=>{let r=vJ(t.endpoint);if(!r)throw new Error("No OAuth session found. Run `sg login` to authenticate.");return z$e(r)?r.tokens.accessToken:(await G$e(r)).tokens.accessToken}:null}function eC(t){if(t.apiKey)return new XT.SuperglueClient({apiKey:t.apiKey,apiEndpoint:t.endpoint});let e=DJ(t);return e||(D("No authentication configured. Run `sg login`. For headless/API-key auth, set SUPERGLUE_API_KEY or pass --api-key. For custom/self-hosted instances, also set SUPERGLUE_API_ENDPOINT or pass --endpoint."),process.exit(1)),new XT.SuperglueClient({tokenProvider:e,apiEndpoint:t.endpoint})}var ec=Be(require("fs")),kl=Be(require("path")),kJ=Be(require("os")),eD=require("commander"),vd=Be(jr());function RJ(t){t.command("init",{hidden:!0}).description("Legacy API-key setup for headless environments").option("--web-endpoint <url>","Web endpoint for OAuth callbacks").addOption(new eD.Option("--output-mode <mode>","Output mode: stdout or stdout+file").choices(["stdout","stdout+file"]).default("stdout")).option("--output-dir <dir>","Output directory for stdout+file mode",".superglue/output").option("--global","Save config globally (~/.superglue/) instead of locally").addOption(new eD.Option("--preset <preset>","Capability preset: runner, builder, or admin").choices(["runner","builder","admin"]).default("admin")).action(async function(e){let r=this.parent?.opts()??{},n=r.apiKey||(0,vd.readProcessEnvironmentValue)("SUPERGLUE_API_KEY"),i=r.endpoint||(0,vd.readProcessEnvironmentValue)("SUPERGLUE_API_ENDPOINT"),o=n||!process.stdin.isTTY,s,a,c,l,u,d,A;if(o){s=n,s||(D("API key is required (--api-key or SUPERGLUE_API_KEY)"),process.exit(1)),a=i||"https://api.superglue.cloud";let B=a.replace(/:3002\b/,":3001").replace(/api\.superglue/,"app.superglue");c=e.webEndpoint||B,l=e.outputMode==="stdout+file"?"stdout+file":"stdout",u=e.outputDir,d=!e.global,A=e.preset;let _=nr("Verifying connection...");try{await new vd.SuperglueClient({apiKey:s,apiEndpoint:a}).listSystems({limit:1}),_.stop(`${C.green}\u2713${C.reset} Connected to ${C.bold}${a}${C.reset}`)}catch(v){_.stop(`${C.red}\u2717${C.reset} Connection failed`),D(v.message),process.exit(1)}}else{wJ(),console.log(` ${C.bold}Legacy superglue API-key setup${C.reset}`),console.log(` ${C.dim}For normal interactive setup, use ${C.reset}${C.cyan}sg login${C.reset}${C.dim}.${C.reset}
|
|
2238
|
+
`),Tl("Authentication"),console.log(` ${C.dim}Get your API key at${C.reset} ${SJ("https://app.superglue.cloud/api-keys")}`),console.log(""),s=await BJ(" API Key"),s||(D("API key is required"),process.exit(1)),a=await VI(" API Endpoint",i||"https://api.superglue.cloud");let B=a.replace(/:3002\b/,":3001").replace(/api\.superglue/,"app.superglue");c=await VI(" Web Endpoint (for OAuth callbacks)",B);let _=nr("Verifying connection...");try{await new vd.SuperglueClient({apiKey:s,apiEndpoint:a}).listSystems({limit:1}),_.stop(`${C.green}\u2713${C.reset} Connected to ${C.bold}${a}${C.reset}`)}catch(K){_.stop(`${C.red}\u2717${C.reset} Connection failed`),D(K.message),process.exit(1)}Tl("Output Preferences"),l=await WI("Output mode",["stdout only \u2014 print results to terminal","stdout + file \u2014 also save results as JSON files"],0)===1?"stdout+file":"stdout",u=".superglue/output",l==="stdout+file"&&(u=await VI(" Output directory",".superglue/output")),Tl("Config Location");let T=kJ.homedir(),L=kl.join(process.cwd(),".superglue"),k=kl.join(T,".superglue");d=await WI("Where to save config?",[`Project (${L}) \u2014 config stays with this project`,`Global (${k}) \u2014 shared across all projects`],0)===0,Tl("Capability Preset");let U=await WI("What should this CLI be able to do?",["runner \u2014 run saved tools by ID (agent-safe, read-only)","builder \u2014 run + build tools, call systems (no system management)","admin \u2014 full access (default)"],2);A=["runner","builder","admin"][U]}let p={apiKey:s,endpoint:a,webEndpoint:c,output:{mode:l,directory:u},preset:A};jI(p,d),zI(p,d);let h=Ks(d),f=d?".superglue/config.json":kl.join(h,"config.json"),E=kl.join(process.cwd(),".gitignore"),S=[];if(l==="stdout+file"&&!kl.isAbsolute(u)&&S.push(`${u}/`),d&&S.push(".superglue/drafts/",".superglue/config.json"),S.length>0)if(ec.existsSync(E)){let B=ec.readFileSync(E,"utf-8"),_=S.filter(v=>!B.includes(v));_.length>0&&(ec.appendFileSync(E,`
|
|
2239
2239
|
# superglue CLI
|
|
2240
2240
|
`+_.join(`
|
|
2241
2241
|
`)+`
|
|
@@ -2243,7 +2243,7 @@ ${o}`:i.stack}ae.exports.fetch=function(e,r=void 0){return KLe(e,r).catch(n=>{th
|
|
|
2243
2243
|
`+S.join(`
|
|
2244
2244
|
`)+`
|
|
2245
2245
|
`),Mn("Created .gitignore"));console.log(""),Me(`Config saved to ${C.bold}${f}${C.reset}`),d&&Me(`Created ${C.bold}.superglue/drafts/${C.reset}`),l==="stdout+file"&&Me(`Created ${C.bold}${u}/${C.reset}`),console.log(""),console.log(` ${C.bold}You're all set!${C.reset} Try these commands:
|
|
2246
|
-
`),console.log(` ${C.cyan}sg system list${C.reset} ${C.dim}\u2014 see your connected systems${C.reset}`),console.log(` ${C.cyan}sg tool list${C.reset} ${C.dim}\u2014 see your saved tools${C.reset}`),console.log(` ${C.cyan}sg run list${C.reset} ${C.dim}\u2014 see recent executions${C.reset}`),console.log("")})}var Qd=Be(require("crypto")),UJ=Be(require("http")),rC=Be(jr());var NJ=require("child_process");function tC(t){let e=process.platform,r=e==="darwin"?"open":e==="win32"?"rundll32":"xdg-open",n=e==="win32"?["url.dll,FileProtocolHandler",t]:[t];try{let i=(0,NJ.spawn)(r,n,{detached:!0,stdio:"ignore"});i.on("error",()=>{}),i.unref()}catch{}}var MJ="openid profile email offline_access",tD="127.0.0.1",Y$e=45454,V$e=300*1e3;function tc(t){return t.replace(/\/+$/,"")}function OJ(t){return t.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function W$e(){let t=OJ(Qd.randomBytes(32)),e=OJ(Qd.createHash("sha256").update(t).digest());return{verifier:t,challenge:e}}async function xJ(t,e){return new Promise((r,n)=>{let i=s=>{t.off("listening",o),n(s)},o=()=>{t.off("error",i);let s=t.address();r(s.port)};t.once("error",i),t.once("listening",o),t.listen(e,tD)})}async function J$e(t){let e=null,r,n,i=new Promise((a,c)=>{r=a,n=c}),o=UJ.createServer((a,c)=>{let l=new URL(a.url||"/",`http://${a.headers.host||tD}`);if(l.pathname!=="/callback"){c.writeHead(404,{"Content-Type":"text/plain"}),c.end("Not found");return}let u=l.searchParams.get("error"),d=l.searchParams.get("error_description"),A=l.searchParams.get("code"),p=l.searchParams.get("state");if(u){c.writeHead(400,{"Content-Type":"text/html"}),c.end("<h2>superglue CLI login failed</h2><p>You can close this window.</p>"),n(new Error(d||u));return}if(!A||!p||p!==t){c.writeHead(400,{"Content-Type":"text/html"}),c.end("<h2>superglue CLI login failed</h2><p>You can close this window.</p>"),n(new Error("OAuth callback was missing a valid code or state."));return}c.writeHead(200,{"Content-Type":"text/html"}),c.end("<h2>superglue CLI login complete</h2><p>You can close this window.</p>"),r({code:A,state:p})}),s;try{s=await xJ(o,Y$e)}catch(a){if(a?.code!=="EADDRINUSE")throw a;s=await xJ(o,0)}return e=setTimeout(()=>{n(new Error("Login timed out waiting for the browser callback."))},V$e),e.unref(),{redirectUri:`http://${tD}:${s}/callback`,waitForCallback:async()=>{try{return await i}finally{e&&clearTimeout(e)}},close:()=>new Promise(a=>{e&&clearTimeout(e),o.close(()=>a())})}}async function Z$e(t,e){let r={authorization_endpoint:`${tc(t.webEndpoint)}/api/auth/oauth2/authorize`,token_endpoint:`${tc(t.endpoint)}/oauth2/token`,registration_endpoint:`${tc(t.endpoint)}/oauth2/register`};try{let n=await fetch(`${tc(t.endpoint)}/.well-known/openid-configuration`);if(!n.ok)return r;let i=await n.json();return{authorization_endpoint:e?.useConfiguredAuthorizationEndpoint?r.authorization_endpoint:i.authorization_endpoint||r.authorization_endpoint,token_endpoint:i.token_endpoint||r.token_endpoint,registration_endpoint:i.registration_endpoint||r.registration_endpoint}}catch{return r}}async function K$e(t,e){let r=await fetch(t.registration_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({redirect_uris:[e],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:"superglue CLI",client_uri:"https://superglue.ai/docs/getting-started/cli-skills/",scope:MJ,software_id:"superglue-cli",software_version:zr})}),n=await XI(r);if(!n.client_id)throw new Error("OAuth registration did not return a client_id.");return{clientId:n.client_id,clientSecret:n.client_secret,tokenEndpointAuthMethod:n.token_endpoint_auth_method,redirectUris:n.redirect_uris?.length?n.redirect_uris:[e]}}function X$e(t){let e=new URL(t.metadata.authorization_endpoint);return e.searchParams.set("response_type","code"),e.searchParams.set("client_id",t.clientId),e.searchParams.set("redirect_uri",t.redirectUri),e.searchParams.set("scope",MJ),e.searchParams.set("state",t.state),e.searchParams.set("code_challenge",t.codeChallenge),e.searchParams.set("code_challenge_method","S256"),e.searchParams.set("prompt","consent"),e.toString()}async function eFe(t){let e=KT(t.client,{grant_type:"authorization_code",code:t.code,redirect_uri:t.redirectUri,code_verifier:t.codeVerifier}),r=await fetch(t.metadata.token_endpoint,{method:"POST",headers:e.headers,body:e.body});return XI(r)}function tFe(t,e){let r=t.parent?.opts()??{},n=_d({apiKey:void 0,endpoint:r.endpoint});return{...n,webEndpoint:e.webEndpoint||n.webEndpoint}}function rFe(t){return!!(t.webEndpoint||(0,rC.readProcessEnvironmentValue)("SUPERGLUE_WEB_ENDPOINT")||typeof FI().webEndpoint=="string")}function nFe(t,e){let r=FI(e),n={...t,...r,apiKey:typeof r.apiKey=="string"?r.apiKey:"",endpoint:tc(t.endpoint),webEndpoint:tc(t.webEndpoint),output:{...t.output,...r.output},preset:t.preset};return jI(n,e),zI(n,e),GT(e)}async function iFe(t,e){return new rC.SuperglueClient({apiKey:e,apiEndpoint:t.endpoint}).getMe()}function PJ(t){t.command("login").description("Authenticate the superglue CLI through the browser").option("--web-endpoint <url>","superglue web app endpoint").option("--no-browser","Print the login URL instead of opening a browser").option("--save-config","Persist endpoint settings to config.json").option("--global","Save endpoint config globally (~/.superglue/config.json)").action(async function(e){let r=tFe(this,e),n=rr("Preparing browser login..."),i=null;try{let o=await Z$e(r,{useConfiguredAuthorizationEndpoint:rFe(e)}),s=Qd.randomUUID(),a=W$e();i=await J$e(s);let c=await K$e(o,i.redirectUri),l=X$e({metadata:o,clientId:c.clientId,redirectUri:i.redirectUri,state:s,codeChallenge:a.challenge});n.stop(),e.browser!==!1&&(tC(l),Mn("Opened browser for superglue login.")),console.log(""),console.log(` ${C.dim}Login URL:${C.reset} ${l}`),console.log("");let u=await i.waitForCallback(),d=await eFe({metadata:o,client:c,redirectUri:i.redirectUri,code:u.code,codeVerifier:a.verifier}),A=ZT({endpoint:r.endpoint,webEndpoint:r.webEndpoint,tokenEndpoint:o.token_endpoint,client:c,tokenResponse:d}),p=await iFe(r,A.tokens.accessToken);JT(A);let h=e.saveConfig?nFe(r,e.global?!1:void 0):void 0;Me(`Logged in to ${r.endpoint}`,{authPath:Bd(),configPath:h,orgId:p.orgId,userId:p.userId,roleIds:p.roleIds})}catch(o){n.stop(),D(o?.message||"Login failed"),process.exit(1)}finally{await i?.close()}}),t.command("logout").description("Remove the stored OAuth session from auth.json").action(()=>{let e=TJ();Me(e?"Logged out":"No OAuth session found",{authPath:Bd()})}),t.command("whoami").description("Show the authenticated superglue user and organization").action(async function(){let e=this.parent?.opts()??{},r=_d({apiKey:e.apiKey,endpoint:e.endpoint}),n=WT(),i=r.apiKey?"api_key":n&&tc(n.endpoint)===tc(r.endpoint)?"oauth":"none";i==="none"&&(D("No authentication configured. Run `sg login`."),process.exit(1));let o=eC(r);try{let s=await o.getMe();de({success:!0,authType:i,endpoint:r.endpoint,userId:s.userId,orgId:s.orgId,orgName:s.orgName,roleIds:s.roleIds})}catch(s){D(s?.message||"Failed to fetch current user"),process.exit(1)}})}var LJ={runner:{commands:new Set(["init","tool.run","tool.find","system.find","mcp.find","schedule.list","run.list","run.get","project.list","project.task.list","project.label.list","skill","update"]),toolRunModes:new Set(["tool"])},builder:{commands:new Set(["init","tool.run","tool.find","tool.build","tool.edit","tool.save","tool.state","system.call","system.connection","system.find","system.oauth","mcp.find","mcp.create","mcp.edit","schedule.list","schedule.create","schedule.edit","run.list","run.get","project.list","project.task.list","project.task.create","project.task.edit","project.label.list","project.label.create","project.label.edit","skill","update"]),toolRunModes:new Set(["tool","config","config-file","draft"])},admin:{commands:new Set(["*"]),toolRunModes:new Set(["tool","config","config-file","draft"])}};function yi(t,e){let r=LJ[t];return r.commands.has("*")||r.commands.has(e)}function $J(t,e){return LJ[t].toolRunModes.has(e)}function Ei(t,e){return`'sg ${t.replace(/\./g," ")}' is not available in the '${e}' preset. Change preset in .superglue/config.json or set SUPERGLUE_CLI_PRESET.`}var aC=Be(require("fs")),zJ=Be(require("crypto")),cC=Be(jr());var Ii=Be(require("fs")),rD=Be(require("path"));function FJ(){return rD.join(Ks(),"drafts")}function oFe(t){return Buffer.from(t,"utf-8").toString("base64url")}function Xs(t){return rD.join(FJ(),`${oFe(t)}.json`)}function nC(t){let e=FJ();Ii.existsSync(e)||Ii.mkdirSync(e,{recursive:!0}),Ii.writeFileSync(Xs(t.draftId),JSON.stringify(t,null,2))}function Td(t){let e=Xs(t);if(!Ii.existsSync(e))return null;try{return JSON.parse(Ii.readFileSync(e,"utf-8"))}catch{return null}}function jJ(t){let e=Xs(t);Ii.existsSync(e)&&Ii.unlinkSync(e)}var iC=Be(require("fs")),oC=Be(require("path"));async function Dd(t,e){if(!t||t.length===0)return{};let r={};for(let n of t){let i=n.indexOf("=");i===-1&&(console.error(`Invalid --file format: "${n}". Expected key=path`),process.exit(1));let o=n.slice(0,i),s=oC.resolve(n.slice(i+1));iC.existsSync(s)||(console.error(`File not found: ${s}`),process.exit(1));let a=iC.readFileSync(s),c=new Blob([a]),l=new File([c],oC.basename(s));try{let u=await e.extract({file:l});if(u.file?.parseError&&u.data===void 0)throw new Error(u.file.parseError);r[o]=u.data}catch(u){console.error(`Failed to extract file "${o}" (${s}): ${u.message}`),process.exit(1)}}return r}function nD(t,e){if(typeof t=="string"&&t.startsWith("file::")){let r=t.slice(6);if(!(r in e))throw new Error(`File reference 'file::${r}' not found. Available: ${Object.keys(e).join(", ")||"(none)"}`);return e[r]}if(Array.isArray(t))return t.map(r=>nD(r,e));if(t&&typeof t=="object"){let r={};for(let[n,i]of Object.entries(t))r[n]=nD(i,e);return r}return t}function sC(t,e){if(!t)return{success:!0,resolved:t};try{return{success:!0,resolved:nD(t,e)}}catch(r){return{success:!1,error:r.message}}}function qJ(t,e){t.command("build").description("Build a new superglue tool from a configuration").option("--config <file>","JSON config file for the tool").option("--id <id>","Tool ID in kebab-case").option("--instruction <text>","Brief human-readable tool instruction").option("--steps <file>","JSON file containing steps array").option("--output-transform <code>","JS output transform function").option("--output-schema <file>","JSON file for output schema").option("--payload <json>","Sample payload JSON").option("--file <key=path...>","File references (key=path)",(r,n)=>(n.push(r),n),[]).addHelpText("after",`
|
|
2246
|
+
`),console.log(` ${C.cyan}sg system list${C.reset} ${C.dim}\u2014 see your connected systems${C.reset}`),console.log(` ${C.cyan}sg tool list${C.reset} ${C.dim}\u2014 see your saved tools${C.reset}`),console.log(` ${C.cyan}sg run list${C.reset} ${C.dim}\u2014 see recent executions${C.reset}`),console.log("")})}var Qd=Be(require("crypto")),UJ=Be(require("http")),rC=Be(jr());var NJ=require("child_process");function tC(t){let e=process.platform,r=e==="darwin"?"open":e==="win32"?"rundll32":"xdg-open",n=e==="win32"?["url.dll,FileProtocolHandler",t]:[t];try{let i=(0,NJ.spawn)(r,n,{detached:!0,stdio:"ignore"});i.on("error",()=>{}),i.unref()}catch{}}var MJ="openid profile email offline_access",tD="127.0.0.1",Y$e=45454,V$e=300*1e3;function tc(t){return t.replace(/\/+$/,"")}function OJ(t){return t.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function W$e(){let t=OJ(Qd.randomBytes(32)),e=OJ(Qd.createHash("sha256").update(t).digest());return{verifier:t,challenge:e}}async function xJ(t,e){return new Promise((r,n)=>{let i=s=>{t.off("listening",o),n(s)},o=()=>{t.off("error",i);let s=t.address();r(s.port)};t.once("error",i),t.once("listening",o),t.listen(e,tD)})}async function J$e(t){let e=null,r,n,i=new Promise((a,c)=>{r=a,n=c}),o=UJ.createServer((a,c)=>{let l=new URL(a.url||"/",`http://${a.headers.host||tD}`);if(l.pathname!=="/callback"){c.writeHead(404,{"Content-Type":"text/plain"}),c.end("Not found");return}let u=l.searchParams.get("error"),d=l.searchParams.get("error_description"),A=l.searchParams.get("code"),p=l.searchParams.get("state");if(u){c.writeHead(400,{"Content-Type":"text/html"}),c.end("<h2>superglue CLI login failed</h2><p>You can close this window.</p>"),n(new Error(d||u));return}if(!A||!p||p!==t){c.writeHead(400,{"Content-Type":"text/html"}),c.end("<h2>superglue CLI login failed</h2><p>You can close this window.</p>"),n(new Error("OAuth callback was missing a valid code or state."));return}c.writeHead(200,{"Content-Type":"text/html"}),c.end("<h2>superglue CLI login complete</h2><p>You can close this window.</p>"),r({code:A,state:p})}),s;try{s=await xJ(o,Y$e)}catch(a){if(a?.code!=="EADDRINUSE")throw a;s=await xJ(o,0)}return e=setTimeout(()=>{n(new Error("Login timed out waiting for the browser callback."))},V$e),e.unref(),{redirectUri:`http://${tD}:${s}/callback`,waitForCallback:async()=>{try{return await i}finally{e&&clearTimeout(e)}},close:()=>new Promise(a=>{e&&clearTimeout(e),o.close(()=>a())})}}async function Z$e(t,e){let r={authorization_endpoint:`${tc(t.webEndpoint)}/api/auth/oauth2/authorize`,token_endpoint:`${tc(t.endpoint)}/oauth2/token`,registration_endpoint:`${tc(t.endpoint)}/oauth2/register`};try{let n=await fetch(`${tc(t.endpoint)}/.well-known/openid-configuration`);if(!n.ok)return r;let i=await n.json();return{authorization_endpoint:e?.useConfiguredAuthorizationEndpoint?r.authorization_endpoint:i.authorization_endpoint||r.authorization_endpoint,token_endpoint:i.token_endpoint||r.token_endpoint,registration_endpoint:i.registration_endpoint||r.registration_endpoint}}catch{return r}}async function K$e(t,e){let r=await fetch(t.registration_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({redirect_uris:[e],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:"superglue CLI",client_uri:"https://superglue.ai/docs/getting-started/cli-skills/",scope:MJ,software_id:"superglue-cli",software_version:zr})}),n=await XI(r);if(!n.client_id)throw new Error("OAuth registration did not return a client_id.");return{clientId:n.client_id,clientSecret:n.client_secret,tokenEndpointAuthMethod:n.token_endpoint_auth_method,redirectUris:n.redirect_uris?.length?n.redirect_uris:[e]}}function X$e(t){let e=new URL(t.metadata.authorization_endpoint);return e.searchParams.set("response_type","code"),e.searchParams.set("client_id",t.clientId),e.searchParams.set("redirect_uri",t.redirectUri),e.searchParams.set("scope",MJ),e.searchParams.set("state",t.state),e.searchParams.set("code_challenge",t.codeChallenge),e.searchParams.set("code_challenge_method","S256"),e.searchParams.set("prompt","consent"),e.toString()}async function eFe(t){let e=KT(t.client,{grant_type:"authorization_code",code:t.code,redirect_uri:t.redirectUri,code_verifier:t.codeVerifier}),r=await fetch(t.metadata.token_endpoint,{method:"POST",headers:e.headers,body:e.body});return XI(r)}function tFe(t,e){let r=t.parent?.opts()??{},n=_d({apiKey:void 0,endpoint:r.endpoint});return{...n,webEndpoint:e.webEndpoint||n.webEndpoint}}function rFe(t){return!!(t.webEndpoint||(0,rC.readProcessEnvironmentValue)("SUPERGLUE_WEB_ENDPOINT")||typeof FI().webEndpoint=="string")}function nFe(t,e){let r=FI(e),n={...t,...r,apiKey:typeof r.apiKey=="string"?r.apiKey:"",endpoint:tc(t.endpoint),webEndpoint:tc(t.webEndpoint),output:{...t.output,...r.output},preset:t.preset};return jI(n,e),zI(n,e),GT(e)}async function iFe(t,e){return new rC.SuperglueClient({apiKey:e,apiEndpoint:t.endpoint}).getMe()}function PJ(t){t.command("login").description("Authenticate the superglue CLI through the browser").option("--web-endpoint <url>","superglue web app endpoint").option("--no-browser","Print the login URL instead of opening a browser").option("--save-config","Persist endpoint settings to config.json").option("--global","Save endpoint config globally (~/.superglue/config.json)").action(async function(e){let r=tFe(this,e),n=nr("Preparing browser login..."),i=null;try{let o=await Z$e(r,{useConfiguredAuthorizationEndpoint:rFe(e)}),s=Qd.randomUUID(),a=W$e();i=await J$e(s);let c=await K$e(o,i.redirectUri),l=X$e({metadata:o,clientId:c.clientId,redirectUri:i.redirectUri,state:s,codeChallenge:a.challenge});n.stop(),e.browser!==!1&&(tC(l),Mn("Opened browser for superglue login.")),console.log(""),console.log(` ${C.dim}Login URL:${C.reset} ${l}`),console.log("");let u=await i.waitForCallback(),d=await eFe({metadata:o,client:c,redirectUri:i.redirectUri,code:u.code,codeVerifier:a.verifier}),A=ZT({endpoint:r.endpoint,webEndpoint:r.webEndpoint,tokenEndpoint:o.token_endpoint,client:c,tokenResponse:d}),p=await iFe(r,A.tokens.accessToken);JT(A);let h=e.saveConfig?nFe(r,e.global?!1:void 0):void 0;Me(`Logged in to ${r.endpoint}`,{authPath:Bd(),configPath:h,orgId:p.orgId,userId:p.userId,roleIds:p.roleIds})}catch(o){n.stop(),D(o?.message||"Login failed"),process.exit(1)}finally{await i?.close()}}),t.command("logout").description("Remove the stored OAuth session from auth.json").action(()=>{let e=TJ();Me(e?"Logged out":"No OAuth session found",{authPath:Bd()})}),t.command("whoami").description("Show the authenticated superglue user and organization").action(async function(){let e=this.parent?.opts()??{},r=_d({apiKey:e.apiKey,endpoint:e.endpoint}),n=WT(),i=r.apiKey?"api_key":n&&tc(n.endpoint)===tc(r.endpoint)?"oauth":"none";i==="none"&&(D("No authentication configured. Run `sg login`."),process.exit(1));let o=eC(r);try{let s=await o.getMe();de({success:!0,authType:i,endpoint:r.endpoint,userId:s.userId,orgId:s.orgId,orgName:s.orgName,roleIds:s.roleIds})}catch(s){D(s?.message||"Failed to fetch current user"),process.exit(1)}})}var LJ={runner:{commands:new Set(["init","tool.run","tool.find","system.find","mcp.find","schedule.list","run.list","run.get","project.list","project.task.list","project.label.list","skill","update"]),toolRunModes:new Set(["tool"])},builder:{commands:new Set(["init","tool.run","tool.find","tool.build","tool.edit","tool.save","tool.state","system.call","system.connection","system.find","system.oauth","mcp.find","mcp.create","mcp.edit","schedule.list","schedule.create","schedule.edit","run.list","run.get","project.list","project.task.list","project.task.create","project.task.edit","project.label.list","project.label.create","project.label.edit","skill","update"]),toolRunModes:new Set(["tool","config","config-file","draft"])},admin:{commands:new Set(["*"]),toolRunModes:new Set(["tool","config","config-file","draft"])}};function yi(t,e){let r=LJ[t];return r.commands.has("*")||r.commands.has(e)}function $J(t,e){return LJ[t].toolRunModes.has(e)}function Ei(t,e){return`'sg ${t.replace(/\./g," ")}' is not available in the '${e}' preset. Change preset in .superglue/config.json or set SUPERGLUE_CLI_PRESET.`}var aC=Be(require("fs")),zJ=Be(require("crypto")),cC=Be(jr());var Ii=Be(require("fs")),rD=Be(require("path"));function FJ(){return rD.join(Ks(),"drafts")}function oFe(t){return Buffer.from(t,"utf-8").toString("base64url")}function Xs(t){return rD.join(FJ(),`${oFe(t)}.json`)}function nC(t){let e=FJ();Ii.existsSync(e)||Ii.mkdirSync(e,{recursive:!0}),Ii.writeFileSync(Xs(t.draftId),JSON.stringify(t,null,2))}function Td(t){let e=Xs(t);if(!Ii.existsSync(e))return null;try{return JSON.parse(Ii.readFileSync(e,"utf-8"))}catch{return null}}function jJ(t){let e=Xs(t);Ii.existsSync(e)&&Ii.unlinkSync(e)}var iC=Be(require("fs")),oC=Be(require("path"));async function Dd(t,e){if(!t||t.length===0)return{};let r={};for(let n of t){let i=n.indexOf("=");i===-1&&(console.error(`Invalid --file format: "${n}". Expected key=path`),process.exit(1));let o=n.slice(0,i),s=oC.resolve(n.slice(i+1));iC.existsSync(s)||(console.error(`File not found: ${s}`),process.exit(1));let a=iC.readFileSync(s),c=new Blob([a]),l=new File([c],oC.basename(s));try{let u=await e.extract({file:l});if(u.file?.parseError&&u.data===void 0)throw new Error(u.file.parseError);r[o]=u.data}catch(u){console.error(`Failed to extract file "${o}" (${s}): ${u.message}`),process.exit(1)}}return r}function nD(t,e){if(typeof t=="string"&&t.startsWith("file::")){let r=t.slice(6);if(!(r in e))throw new Error(`File reference 'file::${r}' not found. Available: ${Object.keys(e).join(", ")||"(none)"}`);return e[r]}if(Array.isArray(t))return t.map(r=>nD(r,e));if(t&&typeof t=="object"){let r={};for(let[n,i]of Object.entries(t))r[n]=nD(i,e);return r}return t}function sC(t,e){if(!t)return{success:!0,resolved:t};try{return{success:!0,resolved:nD(t,e)}}catch(r){return{success:!1,error:r.message}}}function qJ(t,e){t.command("build").description("Build a new superglue tool from a configuration").option("--config <file>","JSON config file for the tool").option("--id <id>","Tool ID in kebab-case").option("--instruction <text>","Brief human-readable tool instruction").option("--steps <file>","JSON file containing steps array").option("--output-transform <code>","JS output transform function").option("--output-schema <file>","JSON file for output schema").option("--payload <json>","Sample payload JSON").option("--file <key=path...>","File references (key=path)",(r,n)=>(n.push(r),n),[]).addHelpText("after",`
|
|
2247
2247
|
Run 'sg skill' for the full tool-building reference.
|
|
2248
2248
|
|
|
2249
2249
|
Workflow: build \u2192 run --draft \u2192 edit --draft (if needed) \u2192 save --draft
|
|
@@ -2257,7 +2257,7 @@ Returns: { success, data, error? }
|
|
|
2257
2257
|
a seeded run never saves state changes. Use 'sg tool state set' to set real state.
|
|
2258
2258
|
|
|
2259
2259
|
Run 'sg skill' for payload syntax, variable references, and data selectors.
|
|
2260
|
-
`).action(async n=>{let{config:i,client:o}=e(),s=[n.tool,n.draft,n.config,n.configFile].filter(Boolean);s.length===0&&(D("Provide one of --tool, --draft, --config, or --config-file. Run 'sg skill' for usage examples."),process.exit(1)),s.length>1&&(D("Only one of --tool, --draft, --config, or --config-file can be used"),process.exit(1));let a=n.tool?"tool":n.draft?"draft":n.configFile?"config-file":"config";$J(r,a)||(D(`--${a} is not available in the '${r}' preset. Use --tool <id> to run a saved tool, or change preset to 'builder' or 'admin'.`),process.exit(1));let c=await Dd(n.file,o),l;try{l=n.payloadFile?JSON.parse(hs.readFileSync(n.payloadFile,"utf-8")):n.payload?JSON.parse(n.payload):void 0}catch(_){D(`Invalid payload JSON: ${_.message}. Run 'sg skill' for payload syntax.`),process.exit(1)}if(l){let _=sC(l,c);_.success||(D(_.error),process.exit(1)),l=_.resolved}let u;if(n.stateFixture!==void 0||n.stateFixtureFile!==void 0){n.stateFixture!==void 0&&n.stateFixtureFile!==void 0&&(D("Only one of --state-fixture or --state-fixture-file can be used"),process.exit(1));let _;try{_=JSON.parse(n.stateFixtureFile?hs.readFileSync(n.stateFixtureFile,"utf-8"):n.stateFixture)}catch(v){D(`Invalid state fixture JSON: ${v.message}`),process.exit(1)}(_===null||typeof _!="object"||Array.isArray(_))&&(D("--state-fixture must be a plain JSON object"),process.exit(1)),u=_}let d,A=n.tool||n.draft||"inline-config",p=HJ.randomUUID(),h;if(n.timeout!==void 0){let _=Number(n.timeout);(!Number.isInteger(_)||_<1e3)&&(D("--timeout must be an integer of at least 1000 (milliseconds)"),process.exit(1)),h=_}let f=
|
|
2260
|
+
`).action(async n=>{let{config:i,client:o}=e(),s=[n.tool,n.draft,n.config,n.configFile].filter(Boolean);s.length===0&&(D("Provide one of --tool, --draft, --config, or --config-file. Run 'sg skill' for usage examples."),process.exit(1)),s.length>1&&(D("Only one of --tool, --draft, --config, or --config-file can be used"),process.exit(1));let a=n.tool?"tool":n.draft?"draft":n.configFile?"config-file":"config";$J(r,a)||(D(`--${a} is not available in the '${r}' preset. Use --tool <id> to run a saved tool, or change preset to 'builder' or 'admin'.`),process.exit(1));let c=await Dd(n.file,o),l;try{l=n.payloadFile?JSON.parse(hs.readFileSync(n.payloadFile,"utf-8")):n.payload?JSON.parse(n.payload):void 0}catch(_){D(`Invalid payload JSON: ${_.message}. Run 'sg skill' for payload syntax.`),process.exit(1)}if(l){let _=sC(l,c);_.success||(D(_.error),process.exit(1)),l=_.resolved}let u;if(n.stateFixture!==void 0||n.stateFixtureFile!==void 0){n.stateFixture!==void 0&&n.stateFixtureFile!==void 0&&(D("Only one of --state-fixture or --state-fixture-file can be used"),process.exit(1));let _;try{_=JSON.parse(n.stateFixtureFile?hs.readFileSync(n.stateFixtureFile,"utf-8"):n.stateFixture)}catch(v){D(`Invalid state fixture JSON: ${v.message}`),process.exit(1)}(_===null||typeof _!="object"||Array.isArray(_))&&(D("--state-fixture must be a plain JSON object"),process.exit(1)),u=_}let d,A=n.tool||n.draft||"inline-config",p=HJ.randomUUID(),h;if(n.timeout!==void 0){let _=Number(n.timeout);(!Number.isInteger(_)||_<1e3)&&(D("--timeout must be an integer of at least 1000 (milliseconds)"),process.exit(1)),h=_}let f=nr(`Running ${C.bold}${A}${C.reset}...`),E=await o.subscribeToLogsSSE({traceId:p,onLog:_=>f.log(`${C.dim}${_.message}${C.reset}`)}).catch(()=>({unsubscribe:()=>{}})),S=async(_,v)=>{try{let T=await o.runToolConfig({tool:_,payload:l,includeStepResultData:n.includeStepResults===!0,options:{requestSource:kd.RequestSource.CLI,timeout:h},traceId:p,createRun:!0,executionKind:v.executionKind,parentToolId:v.parentToolId,draftId:v.draftId,stateFixture:u});return E.unsubscribe(),f.stop(),T}catch(T){E.unsubscribe(),f.stop(),D(T.message),process.exit(1)}};if(n.tool)try{d=await o.runTool({toolId:n.tool,payload:l,includeStepResultData:n.includeStepResults===!0,options:{requestSource:kd.RequestSource.CLI,traceId:p,timeout:h},stateFixture:u}),E.unsubscribe(),f.stop()}catch(_){E.unsubscribe(),f.stop(),D(_.message),process.exit(1)}else if(n.config||n.configFile){let _;try{_=n.configFile?JSON.parse(hs.readFileSync(n.configFile,"utf-8")):JSON.parse(n.config)}catch(v){E.unsubscribe(),f.stop(),D(`Invalid tool config JSON: ${v.message}. Run 'sg skill' for the full tool-building reference.`),process.exit(1)}d=await S(_,{executionKind:kd.RunExecutionKind.FULL})}else{let _=Td(n.draft);_||(E.unsubscribe(),f.stop(),D(`Draft not found: ${n.draft}`),process.exit(1)),d=await S(_.config,{executionKind:kd.RunExecutionKind.DRAFT,draftId:_.draftId,parentToolId:_.config?.id})}let B={success:d.success,data:d.data,...d.error?{error:d.error}:{},...d.warnings?.length?{warnings:d.warnings}:{},...d.fileArtifacts&&d.fileArtifacts.length>0?{fileArtifacts:d.fileArtifacts}:{},...n.includeStepResults&&d.stepResults?{stepResults:d.stepResults}:{},...n.includeConfig&&d.tool?{config:d.tool}:{},...d.important_notice?{important_notice:d.important_notice}:{}};if(de(B),d.fileArtifacts&&d.fileArtifacts.length>0&&Mn(`${d.fileArtifacts.length} file(s) available \u2014 use the downloadUrl from the output to download`),i.output.mode==="stdout+file"){let _=Rd.resolve(i.output.directory);hs.existsSync(_)||hs.mkdirSync(_,{recursive:!0});let v=n.tool||n.draft||"inline-config",L=`${Rd.basename(v).replace(/[^a-zA-Z0-9_-]/g,"_")}-${Date.now()}.json`;hs.writeFileSync(Rd.join(_,L),JSON.stringify(B,null,2))}d.success||process.exit(1)})}var lC=Be(require("fs")),YJ=Be(jr()),VJ=Be(require("fast-json-patch"));function WJ(t,e){t.command("edit").description("Edit a tool using JSON Patch operations").option("--draft <id>","Draft ID to edit").option("--tool <id>","Saved tool ID to edit").option("--patches <json-or-file>","JSON Patch array (inline JSON or file path)").addHelpText("after",`
|
|
2261
2261
|
Patches use JSON Patch (RFC 6902) format:
|
|
2262
2262
|
[{"op":"replace","path":"/steps/0/config/url","value":"https://..."}]
|
|
2263
2263
|
|
|
@@ -2265,7 +2265,7 @@ Provide --draft or --tool. Editing a saved tool creates a new draft.
|
|
|
2265
2265
|
Returns: { success, draftId, draftPath, diffs }
|
|
2266
2266
|
|
|
2267
2267
|
Run 'sg skill' for common patch patterns and the build\u2192run\u2192edit\u2192save workflow.
|
|
2268
|
-
`).action(async r=>{!r.draft&&!r.tool&&(D("Provide --draft or --tool"),process.exit(1)),r.patches||(D("--patches is required"),process.exit(1));let n;try{let u=lC.existsSync(r.patches)?lC.readFileSync(r.patches,"utf-8"):r.patches;n=JSON.parse(u),Array.isArray(n)||(n=[n])}catch(u){D(`Invalid patches: ${u.message}`),process.exit(1)}let i,o;if(r.tool)try{let{client:u}=e(),d=await u.getWorkflow(r.tool);d||(D(`Tool not found: ${r.tool}`),process.exit(1)),i=d,o=`fix-${r.tool}-${Date.now()}`}catch(u){D(u.message),process.exit(1)}else{let u=Td(r.draft);u||(D(`Draft not found: ${r.draft}`),process.exit(1)),i=u.config,o=r.draft}let s;try{let u=JSON.parse(JSON.stringify(i)),d=VJ.applyPatch(u,n,!0,!0);s=(0,YJ.normalizeToolSchemas)(d.newDocument||u)}catch(u){D(`Patch failed: ${u.message}`),process.exit(1)}let a=n.map(u=>({op:u.op,path:u.path,..."value"in u?{value:u.value}:{},..."from"in u&&u.from?{from:u.from}:{}}));Ie()&&(Tl("Proposed Changes"),console.log(_J(a)),console.log(""));let c={draftId:o,config:{...s,instruction:s.instruction??i.instruction,updatedAt:new Date().toISOString()},systemIds:s.systemIds||[],instruction:s.instruction??"",createdAt:new Date().toISOString()};nC(c);let l=Xs(o);Ie()?(Me(`Draft updated: ${C.bold}${o}${C.reset}`),console.log(` ${C.dim}draft file:${C.reset} ${l}`),console.log("")):de({success:!0,draftId:o,draftPath:l,diffs:a})})}function JJ(t,e){t.command("save").description("Persist a draft tool to the database").requiredOption("--draft <id>","Draft ID to save").option("--id <customId>","Custom ID for the saved tool").action(async r=>{let{config:n,client:i}=e(),o=Td(r.draft);o||(D(`Draft not found: ${r.draft}`),process.exit(1));let s=r.id||o.config.id,a=Xs(r.draft),c=
|
|
2268
|
+
`).action(async r=>{!r.draft&&!r.tool&&(D("Provide --draft or --tool"),process.exit(1)),r.patches||(D("--patches is required"),process.exit(1));let n;try{let u=lC.existsSync(r.patches)?lC.readFileSync(r.patches,"utf-8"):r.patches;n=JSON.parse(u),Array.isArray(n)||(n=[n])}catch(u){D(`Invalid patches: ${u.message}`),process.exit(1)}let i,o;if(r.tool)try{let{client:u}=e(),d=await u.getWorkflow(r.tool);d||(D(`Tool not found: ${r.tool}`),process.exit(1)),i=d,o=`fix-${r.tool}-${Date.now()}`}catch(u){D(u.message),process.exit(1)}else{let u=Td(r.draft);u||(D(`Draft not found: ${r.draft}`),process.exit(1)),i=u.config,o=r.draft}let s;try{let u=JSON.parse(JSON.stringify(i)),d=VJ.applyPatch(u,n,!0,!0);s=(0,YJ.normalizeToolSchemas)(d.newDocument||u)}catch(u){D(`Patch failed: ${u.message}`),process.exit(1)}let a=n.map(u=>({op:u.op,path:u.path,..."value"in u?{value:u.value}:{},..."from"in u&&u.from?{from:u.from}:{}}));Ie()&&(Tl("Proposed Changes"),console.log(_J(a)),console.log(""));let c={draftId:o,config:{...s,instruction:s.instruction??i.instruction,updatedAt:new Date().toISOString()},systemIds:s.systemIds||[],instruction:s.instruction??"",createdAt:new Date().toISOString()};nC(c);let l=Xs(o);Ie()?(Me(`Draft updated: ${C.bold}${o}${C.reset}`),console.log(` ${C.dim}draft file:${C.reset} ${l}`),console.log("")):de({success:!0,draftId:o,draftPath:l,diffs:a})})}function JJ(t,e){t.command("save").description("Persist a draft tool to the database").requiredOption("--draft <id>","Draft ID to save").option("--id <customId>","Custom ID for the saved tool").action(async r=>{let{config:n,client:i}=e(),o=Td(r.draft);o||(D(`Draft not found: ${r.draft}`),process.exit(1));let s=r.id||o.config.id,a=Xs(r.draft),c=nr(`Saving tool ${C.bold}${s}${C.reset}...`);try{let l=await i.upsertWorkflow(s,{...o.config,id:s});jJ(r.draft),c.stop();let u=n.endpoint;Ie()?(Me(`Tool saved: ${C.bold}${l.id}${C.reset}`),console.log(` ${C.dim}webhook:${C.reset} ${u}/v1/hooks/${l.id}`),console.log(` ${C.dim}draft ${r.draft} deleted:${C.reset} ${a}`),console.log("")):de({success:!0,toolId:l.id,deletedDraftPath:a,webhookUrl:`${u}/v1/hooks/${l.id}?token=YOUR_API_KEY`})}catch(l){c.stop(),D(l.message),process.exit(1)}})}var ZJ=Be(jr());async function uC({fetchPage:t,limit:e,offset:r}){let n=Math.floor(r/e)+1,i=r%e,o=await t(n,e),s=o.data.slice(i);if(s.length<e&&r+s.length<o.total){let a=await t(n+1,e);s.push(...a.data.slice(0,e-s.length))}return{items:s,total:o.total,hasMore:r+s.length<o.total}}function KJ(t,e){t.command("list").description("List all tools").option("--limit <n>","Max results","25").option("--offset <n>","Skip first N results","0").action(async r=>{let{client:n}=e();try{let i=Math.min(Math.max(parseInt(r.limit,10)||25,1),ZJ.LIST_MAX_LIMIT),o=Math.max(parseInt(r.offset,10)||0,0),{items:s,total:a,hasMore:c}=await uC({limit:i,offset:o,fetchPage:(d,A)=>n.listTools({limit:A,page:d})}),l=mi(),u=s.map(d=>({id:d.id,instruction:l?d.instruction||"":(d.instruction||"").slice(0,60),steps:d.steps?.length||0}));Ie()?lr(u,["id","instruction","steps"],{total:a}):de({success:!0,total:a,hasMore:c,items:u})}catch(i){D(i.message),process.exit(1)}}),t.command("find [query]").description("Find tools by query or exact ID").option("--id <exactId>","Exact tool ID lookup").option("--fields <fields>","Comma-separated top-level fields to return (requires --id), e.g. instruction,inputSchema").action(async(r,n)=>{let{client:i}=e();try{if(n.fields&&!n.id&&(D("--fields requires --id (field selection only applies to exact-ID lookups)"),process.exit(1)),n.id){let l=await i.getWorkflow(n.id);if(l||(D(`Tool not found: ${n.id}`),process.exit(1)),n.fields){let u=n.fields.split(",").map(h=>h.trim()).filter(Boolean),d=Object.keys(l),A=u.filter(h=>!d.includes(h)),p=Object.fromEntries(u.filter(h=>d.includes(h)).map(h=>[h,l[h]]));de({success:!0,tool:p,...A.length?{unknownFields:A,availableFields:d}:{}});return}de({success:!0,tool:l});return}let o=(r||"").trim()||"*",s=await i.listAllTools(),a=o==="*"?s:(()=>{let l=o.toLowerCase().split(/\s+/).filter(A=>A.length>0),d=s.map(A=>{let p=[A.id,A.name,A.instruction].filter(Boolean).join(" ").toLowerCase();return{tool:A,score:l.filter(h=>p.includes(h)).length}}).filter(A=>A.score>0);return d.sort((A,p)=>p.score-A.score),d.map(A=>A.tool)})(),c=mi();de({success:!0,total:a.length,items:a.map(l=>({id:l.id,instruction:c?l.instruction||"":(l.instruction||"").slice(0,80),steps:l.steps?.length||0}))})}catch(o){D(o.message),process.exit(1)}})}var XJ=Be(require("fs"));function sFe(t){!t.state&&!t.stateFile&&(D("Provide --state <json> or --state-file <path>"),process.exit(1)),t.state&&t.stateFile&&(D("Only one of --state or --state-file can be used"),process.exit(1));let e;try{e=JSON.parse(t.stateFile?XJ.readFileSync(t.stateFile,"utf-8"):t.state)}catch(r){D(`Invalid state JSON: ${r.message}`),process.exit(1)}return(e===null||typeof e!="object"||Array.isArray(e))&&(D("State must be a plain JSON object"),process.exit(1)),e}function eZ(t,e){let r=t.command("state").description("Inspect, set, or reset a saved tool's persistent state");r.command("get <toolId>").description("Show the tool's current persistent state").action(async n=>{let{client:i}=e();try{let o=await i.getToolState(n);de({success:!0,toolId:n,state:o})}catch(o){D(o.message),process.exit(1)}}),r.command("set <toolId>").description("Replace the tool's persistent state (full replace)").option("--state <json>","Replacement state JSON object").option("--state-file <path>","Replacement state JSON file").addHelpText("after",`
|
|
2269
2269
|
Replaces all keys, subject to the same key and size limits as run-time state writes.
|
|
2270
2270
|
State is stored unencrypted; never put credential values in it.
|
|
2271
2271
|
`).action(async(n,i)=>{let{client:o}=e(),s=sFe(i);try{await o.setToolState(n,s),de({success:!0,toolId:n,keyCount:Object.keys(s).length})}catch(a){D(a.message),process.exit(1)}}),r.command("reset <toolId>").description("Delete all persistent state keys so the next run cold-starts").action(async n=>{let{client:i}=e();try{let o=await i.deleteToolState(n);de({success:!0,toolId:n,deletedKeys:o})}catch(o){D(o.message),process.exit(1)}})}function dC(t,e,r,n,i){yi(n,r)?i():t.command(e,{hidden:!0}).allowUnknownOption().allowExcessArguments(!0).action(()=>{D(Ei(r,n)),process.exit(1)})}function tZ(t,e,r){let n=t.command("tool").description("Manage superglue tools").addHelpText("after",`
|
|
@@ -2340,13 +2340,13 @@ Without --connection-id, these commands target your default owned connection for
|
|
|
2340
2340
|
system ID, or your oldest owned one. --connection-id targets any connection you can
|
|
2341
2341
|
access under that system ID. Saving a connection under a new system ID makes that
|
|
2342
2342
|
namespace discoverable.
|
|
2343
|
-
`);r.command("list").description("List the connections you can access under a system ID").requiredOption("--system-id <id>","System ID").action(async n=>{let{client:i}=e(),o=Nd(n.systemId);try{let a=(await i.listAllConnections({systemId:o})).map(c=>({connectionId:c.id,connectionName:c.name,isOwner:c.isOwner,isDefault:c.isDefault,permission:c.permission,authType:c.authentication?.type||"none",...c.url?{url:c.url}:{},credentialKeys:c.credentialKeys}));Ie()?lr(a,["connectionId","connectionName","isOwner","isDefault","permission","authType"],{total:a.length}):de({success:!0,systemId:o,total:a.length,hasMore:!1,items:a})}catch(s){D(s.message),process.exit(1)}}),r.command("get").description("Get your connection for a system ID").requiredOption("--system-id <id>","System ID").option("--connection-id <id>","Connection ID within --system-id").action(async n=>{let{client:i}=e(),o=Nd(n.systemId);try{let s=await fs(i,o,n.connectionId);de({success:!0,data:oD({systemId:o,set:s})})}catch(s){D(s.message),process.exit(1)}}),r.command("set").description("Create or update your connection for a system ID").requiredOption("--system-id <id>","System ID").option("--connection-id <id>","Connection ID within --system-id").option("--credentials <json>","Replace stored secrets, including OAuth tokens, with this JSON object; omit to preserve them.").option("--url <url>","Base url of the connection, resolved by <<systemId_url>>. Pass an empty string to clear.").option("--authentication <json>",'Auth config JSON, e.g. {"type":"api_key"} or {"type":"oauth2","clientId":"...","tokenUrl":"..."}. Required when creating a connection; {"type":"none"} for unauthenticated systems.').option("--tunnel-id <id>","Secure Gateway tunnel id for private systems. Pass an empty string to remove the binding.").option("--usage-instructions <text>","Guidance for using this connection; replaces the stored text. Pass an empty string to clear.").option("--oauth-app-id <id>","Link an OAuth app from sg system oauth-apps; empty string detaches. Existing tokens stay unchanged.").action(async n=>{let{client:i}=e(),o=Nd(n.systemId),s,a;try{s=n.credentials===void 0?void 0:aZ(n.credentials,"--credentials"),n.authentication!==void 0&&(a=aZ(n.authentication,"--authentication"))}catch(u){D(`Invalid JSON option: ${u.message}`),process.exit(1)}let c=n.tunnelId===void 0?void 0:n.tunnelId?{tunnelId:n.tunnelId}:null,l=
|
|
2343
|
+
`);r.command("list").description("List the connections you can access under a system ID").requiredOption("--system-id <id>","System ID").action(async n=>{let{client:i}=e(),o=Nd(n.systemId);try{let a=(await i.listAllConnections({systemId:o})).map(c=>({connectionId:c.id,connectionName:c.name,isOwner:c.isOwner,isDefault:c.isDefault,permission:c.permission,authType:c.authentication?.type||"none",...c.url?{url:c.url}:{},credentialKeys:c.credentialKeys}));Ie()?lr(a,["connectionId","connectionName","isOwner","isDefault","permission","authType"],{total:a.length}):de({success:!0,systemId:o,total:a.length,hasMore:!1,items:a})}catch(s){D(s.message),process.exit(1)}}),r.command("get").description("Get your connection for a system ID").requiredOption("--system-id <id>","System ID").option("--connection-id <id>","Connection ID within --system-id").action(async n=>{let{client:i}=e(),o=Nd(n.systemId);try{let s=await fs(i,o,n.connectionId);de({success:!0,data:oD({systemId:o,set:s})})}catch(s){D(s.message),process.exit(1)}}),r.command("set").description("Create or update your connection for a system ID").requiredOption("--system-id <id>","System ID").option("--connection-id <id>","Connection ID within --system-id").option("--credentials <json>","Replace stored secrets, including OAuth tokens, with this JSON object; omit to preserve them.").option("--url <url>","Base url of the connection, resolved by <<systemId_url>>. Pass an empty string to clear.").option("--authentication <json>",'Auth config JSON, e.g. {"type":"api_key"} or {"type":"oauth2","clientId":"...","tokenUrl":"..."}. Required when creating a connection; {"type":"none"} for unauthenticated systems.').option("--tunnel-id <id>","Secure Gateway tunnel id for private systems. Pass an empty string to remove the binding.").option("--usage-instructions <text>","Guidance for using this connection; replaces the stored text. Pass an empty string to clear.").option("--oauth-app-id <id>","Link an OAuth app from sg system oauth-apps; empty string detaches. Existing tokens stay unchanged.").action(async n=>{let{client:i}=e(),o=Nd(n.systemId),s,a;try{s=n.credentials===void 0?void 0:aZ(n.credentials,"--credentials"),n.authentication!==void 0&&(a=aZ(n.authentication,"--authentication"))}catch(u){D(`Invalid JSON option: ${u.message}`),process.exit(1)}let c=n.tunnelId===void 0?void 0:n.tunnelId?{tunnelId:n.tunnelId}:null,l=nr(`Saving connection for ${C.bold}${o}${C.reset}...`);try{let u=await nZ({client:i,systemId:o,credentials:s,url:n.url,authentication:a,tunnel:c,usageInstructions:n.usageInstructions,oauthAppId:n.oauthAppId,connectionId:n.connectionId});l.stop(),Ie()?Me(`Connection saved for ${C.bold}${o}${C.reset}`,{keys:uFe(u?.credentialKeys||[])||"(none)"}):de({success:!0,data:oD({systemId:o,set:u})})}catch(u){l.stop(),D(u.message),process.exit(1)}}),r.command("clear").description("Remove runtime secrets (keys, passwords, tokens) from your connection for a system ID; OAuth client configuration stays").requiredOption("--system-id <id>","System ID").option("--connection-id <id>","Connection ID within --system-id").action(async n=>{let{client:i}=e(),o=Nd(n.systemId),s=nr(`Clearing connection secrets for ${C.bold}${o}${C.reset}...`);try{let a=await iZ(i,o,n.connectionId);s.stop(),Ie()?Me(`Connection secrets cleared for ${C.bold}${o}${C.reset}`):de({success:!0,data:oD({systemId:o,set:a})})}catch(a){s.stop(),D(a.message),process.exit(1)}})}var Sr=Be(jr());async function dFe({client:t,systemId:e,connectionId:r}){try{let n=await fs(t,e,r);return{hasToken:(0,Sr.hasCredentialKeyValue)(n?.credentialKeys,"access_token"),updatedAt:n?.updatedAt?.toString()}}catch{return{hasToken:!1}}}async function AFe({client:t,systemId:e,connectionId:r,baseline:n,timeoutMs:i=3e5,intervalMs:o=2e3}){let s=Date.now();for(;Date.now()-s<i;){await new Promise(a=>setTimeout(a,o));try{let a=await fs(t,e,r);if(!(0,Sr.hasCredentialKeyValue)(a?.credentialKeys,"access_token"))continue;if(!n.hasToken||a?.updatedAt?.toString()!==n.updatedAt)return!0}catch{}}return!1}function pFe(t,e){let r=(0,Sr.findTemplateForSystem)(t),n=r?.template?.oauth,i=(0,Sr.resolveOAuthConfigFromAuthentication)({input:e,authentication:t.authentication,templateOAuth:n}),o=(0,Sr.stringValue)(i.client_secret);return{templateMatch:r,clientId:(0,Sr.stringValue)(i.client_id),clientSecret:(0,Sr.isMaskedSecretValue)(o)?void 0:o,authUrl:(0,Sr.stringValue)(i.auth_url),tokenUrl:(0,Sr.stringValue)(i.token_url),grantType:(0,Sr.stringValue)(i.grant_type)||"authorization_code",scopes:typeof i.scopes=="string"?i.scopes:void 0,tokenConfig:(0,Sr.getOAuthTokenExchangeConfig)(t)}}function lZ(t,e){t.command("oauth").description("Authenticate a system via OAuth; tokens land in your connection").requiredOption("--system-id <id>","System ID").option("--connection-id <id>","Connection ID within --system-id; defaults to your own").option("--scopes <scopes>","Replace default OAuth scopes; use an empty string for none").option("--auth-url <url>","OAuth authorization URL").option("--token-url <url>","OAuth token URL").option("--grant-type <type>","Grant type").action(async r=>{let{config:n,client:i}=e(),o=Nd(r.systemId),s,a;try{let T=await fs(i,o,r.connectionId);a=T?.id,s={id:o,name:o,url:T?.url??"",credentials:{},authentication:T?.authentication,tags:[]}}catch(T){D(T.message),process.exit(1)}let{templateMatch:c,clientId:l,clientSecret:u,authUrl:d,tokenUrl:A,grantType:p,scopes:h,tokenConfig:f}=pFe(s,r);if(!l&&!c?.template.oauth?.managed&&(D(`Missing OAuth clientId. Add it to system authentication:
|
|
2344
2344
|
|
|
2345
2345
|
sg system connection set --system-id ${o} --credentials '{}' --authentication '{"type":"oauth2","clientId":"YOUR_CLIENT_ID","clientSecret":"YOUR_CLIENT_SECRET"}'`),process.exit(1)),A||(D(`Missing tokenUrl. Provide --token-url or add it to authentication:
|
|
2346
2346
|
|
|
2347
|
-
sg system connection set --system-id ${o} --credentials '{}' --authentication '{"type":"oauth2","tokenUrl":"https://..."}'`),process.exit(1)),p==="client_credentials"){let T=
|
|
2347
|
+
sg system connection set --system-id ${o} --credentials '{}' --authentication '{"type":"oauth2","tokenUrl":"https://..."}'`),process.exit(1)),p==="client_credentials"){let T=nr("Exchanging client credentials...");try{let L=await i.createOAuthExchange({systemId:o,credentialsId:a,grantType:"client_credentials",redirectUri:`${n.webEndpoint.replace(/\/$/,"")}/api/auth/callback`,tokenUrl:A,clientId:l,clientSecret:u,templateId:u?void 0:c?.key,scopes:h,tokenAuthMethod:f.tokenAuthMethod,tokenContentType:f.tokenContentType,extraHeaders:f.extraHeaders,extraBodyParams:f.extraBodyParams,tokenDestination:"user_credentials",returnTokens:!1}),k=await i.completeOAuthExchange(L.oauthExchangeId,{state:L.state});if(k.type==="oauth-success"&&k.saved){T.stop(),Me(`OAuth client_credentials flow completed for ${C.bold}${o}${C.reset}`);return}T.stop(),D(k.message||"Token exchange failed"),process.exit(1)}catch(L){T.stop(),D(L.message),process.exit(1)}}d||(D(`Missing authUrl for authorization_code flow. Provide --auth-url or add it to authentication:
|
|
2348
2348
|
|
|
2349
|
-
sg system connection set --system-id ${o} --credentials '{}' --authentication '{"type":"oauth2","authUrl":"https://..."}'`),process.exit(1));let E=await dFe({client:i,systemId:o,connectionId:a}),S=`${n.webEndpoint.replace(/\/$/,"")}/api/auth/callback`,B;try{B=await i.createOAuthExchange({systemId:o,credentialsId:a,grantType:"authorization_code",redirectUri:S,authUrl:d,tokenUrl:A,clientId:l,clientSecret:u,templateId:u?void 0:c?.key,scopes:h,tokenAuthMethod:f.tokenAuthMethod,tokenContentType:f.tokenContentType,extraHeaders:f.extraHeaders,extraBodyParams:f.extraBodyParams,tokenDestination:"user_credentials",returnTokens:!1})}catch(T){D(`Failed to initialize OAuth exchange: ${T.message}`),process.exit(1)}B.authorizationUrl||(D("OAuth exchange did not return an authorization URL"),process.exit(1)),tC(B.authorizationUrl),Ie()&&(console.log(""),console.log(` ${C.dim}Authorization URL:${C.reset} ${B.authorizationUrl}`),console.log(""));let _=
|
|
2349
|
+
sg system connection set --system-id ${o} --credentials '{}' --authentication '{"type":"oauth2","authUrl":"https://..."}'`),process.exit(1));let E=await dFe({client:i,systemId:o,connectionId:a}),S=`${n.webEndpoint.replace(/\/$/,"")}/api/auth/callback`,B;try{B=await i.createOAuthExchange({systemId:o,credentialsId:a,grantType:"authorization_code",redirectUri:S,authUrl:d,tokenUrl:A,clientId:l,clientSecret:u,templateId:u?void 0:c?.key,scopes:h,tokenAuthMethod:f.tokenAuthMethod,tokenContentType:f.tokenContentType,extraHeaders:f.extraHeaders,extraBodyParams:f.extraBodyParams,tokenDestination:"user_credentials",returnTokens:!1})}catch(T){D(`Failed to initialize OAuth exchange: ${T.message}`),process.exit(1)}B.authorizationUrl||(D("OAuth exchange did not return an authorization URL"),process.exit(1)),tC(B.authorizationUrl),Ie()&&(console.log(""),console.log(` ${C.dim}Authorization URL:${C.reset} ${B.authorizationUrl}`),console.log(""));let _=nr("Waiting for browser authentication..."),v=await AFe({client:i,systemId:o,connectionId:a,baseline:E});_.stop(),v?Me(`OAuth authentication successful for ${C.bold}${o}${C.reset}`):(D("Authentication timed out (5 minutes)"),process.exit(1))})}function sD(t,e,r,n,i){yi(n,r)?i():t.command(e,{hidden:!0}).allowUnknownOption().allowExcessArguments(!0).action(()=>{D(Ei(r,n)),process.exit(1)})}function uZ(t,e,r){let n=t.command("system").description("Manage superglue systems").addHelpText("after",`
|
|
2350
2350
|
Skill References:
|
|
2351
2351
|
sg skill Full guide (system setup, credentials, OAuth)
|
|
2352
2352
|
sg skill postgres PostgreSQL connection and schema introspection
|
|
@@ -2408,7 +2408,7 @@ Auth modes:
|
|
|
2408
2408
|
creator_api_key Headless/private clients authenticate with an API key assigned to the creator.
|
|
2409
2409
|
|
|
2410
2410
|
Output: JSON by default. Use --table for human-readable, --full to disable truncation.
|
|
2411
|
-
`);if(yi(r,"mcp.find"))CZ(n,e),IZ(n,e);else for(let i of["list","find"])n.command(i,{hidden:!0}).allowUnknownOption().allowExcessArguments(!0).action(()=>{D(Ei("mcp.find",r)),process.exit(1)});bZ(n,"create","mcp.create",r,()=>mZ(n,e)),bZ(n,"edit","mcp.edit",r,()=>EZ(n,e))}function wZ(t,e){t.command("list").description("List recent runs").option("--tool <id>","Filter by tool ID").option("--status <statuses>","Comma-separated statuses").option("--source <sources>","Comma-separated request sources").option("--user <userId>","Filter by user ID").option("--system-id <id>","Filter by system ID").option("--limit <n>","Max results","10").option("--offset <n>","Skip first N results","0").action(async r=>{let{client:n}=e();try{let i=Math.min(Math.max(parseInt(r.limit,10)||10,1),50),o=Math.max(parseInt(r.offset,10)||0,0),s=Math.ceil((o+1)/i),a=r.source?.split(",").filter(Boolean),c=await n.listRuns({toolId:r.tool,limit:i,page:s,status:r.status,requestSources:a,userId:r.user,systemId:r.systemId});Ie()?(c.total>0&&Mn(`${c.total} total runs${r.tool?` for ${C.bold}${r.tool}${C.reset}`:""}`),lr(c.data.map(l=>({runId:(l.runId||"").slice(0,12),toolId:l.toolId||"",status:l.status||"",source:l.requestSource||""})),["runId","toolId","status","source"],{total:c.total})):de({success:!0,total:c.total,items:c.data.map(l=>({runId:l.runId,toolId:l.toolId,status:l.status,requestSource:l.requestSource,error:l.error}))})}catch(i){D(i.message),process.exit(1)}})}function lD(t){if(t==null)return t;let e;try{e=typeof t=="string"?t:JSON.stringify(t)}catch{e=String(t)}return e.length<=500?t:{_truncated:!0,_size:e.length,_preview:e.slice(0,500)}}function _Z(t,e){t.command("get <runId>").description("Get details of a specific run").option("--fetch-results","Include complete run data (alias for --full)").action(async(r,n)=>{let{client:i}=e();try{let o=await i.getRun(r);o||(D(`Run not found: ${r}`),process.exit(1));let s=mi()||n.fetchResults===!0,a=o.fileArtifacts;de({success:!0,run:{runId:o.runId,toolId:o.toolId,status:o.status,error:o.error,...o.metadata?.warnings?.length?{warnings:o.metadata.warnings}:{},toolPayload:s?o.toolPayload:lD(o.toolPayload),data:s?o.data:lD(o.data),requestSource:o.requestSource,...o.stepResults?{stepResults:s?o.stepResults:lD(o.stepResults)}:{},...a&&a.length>0?{fileArtifacts:a.map(c=>({fileKey:c.fileKey,filename:c.filename,contentType:c.contentType,size:c.size}))}:{}}}),a&&a.length>0&&Mn(`${a.length} file(s) available \u2014 download with: sg run download ${r}`)}catch(o){D(o.message),process.exit(1)}})}var ic=Be(require("fs")),ta=Be(require("path"));function EFe(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function BZ(t,e){t.command("download <runId> [fileKey]").description("Download file artifacts from a run").option("--output-dir <path>","Target directory",".").action(async(r,n,i)=>{let{client:o}=e();try{let s=await o.getRun(r);s||(D(`Run not found: ${r}`),process.exit(1));let a=s.fileArtifacts||[];a.length===0&&(D(`No file artifacts for run ${r}`),process.exit(1));let c=n?a.filter(u=>u.fileKey===n):a;c.length===0&&(D(`File artifact not found: ${n}`),Mn(`Available file artifacts: ${a.map(u=>u.fileKey).join(", ")}`),process.exit(1));let l=ta.resolve(i.outputDir);ic.existsSync(l)||ic.mkdirSync(l,{recursive:!0});for(let u of c){let d=u.downloadUrl;if(!d){D(`No download URL for ${u.fileKey} \u2014 file storage may not be configured`);continue}let A=
|
|
2411
|
+
`);if(yi(r,"mcp.find"))CZ(n,e),IZ(n,e);else for(let i of["list","find"])n.command(i,{hidden:!0}).allowUnknownOption().allowExcessArguments(!0).action(()=>{D(Ei("mcp.find",r)),process.exit(1)});bZ(n,"create","mcp.create",r,()=>mZ(n,e)),bZ(n,"edit","mcp.edit",r,()=>EZ(n,e))}function wZ(t,e){t.command("list").description("List recent runs").option("--tool <id>","Filter by tool ID").option("--status <statuses>","Comma-separated statuses").option("--source <sources>","Comma-separated request sources").option("--user <userId>","Filter by user ID").option("--system-id <id>","Filter by system ID").option("--limit <n>","Max results","10").option("--offset <n>","Skip first N results","0").action(async r=>{let{client:n}=e();try{let i=Math.min(Math.max(parseInt(r.limit,10)||10,1),50),o=Math.max(parseInt(r.offset,10)||0,0),s=Math.ceil((o+1)/i),a=r.source?.split(",").filter(Boolean),c=await n.listRuns({toolId:r.tool,limit:i,page:s,status:r.status,requestSources:a,userId:r.user,systemId:r.systemId});Ie()?(c.total>0&&Mn(`${c.total} total runs${r.tool?` for ${C.bold}${r.tool}${C.reset}`:""}`),lr(c.data.map(l=>({runId:(l.runId||"").slice(0,12),toolId:l.toolId||"",status:l.status||"",source:l.requestSource||""})),["runId","toolId","status","source"],{total:c.total})):de({success:!0,total:c.total,items:c.data.map(l=>({runId:l.runId,toolId:l.toolId,status:l.status,requestSource:l.requestSource,error:l.error}))})}catch(i){D(i.message),process.exit(1)}})}function lD(t){if(t==null)return t;let e;try{e=typeof t=="string"?t:JSON.stringify(t)}catch{e=String(t)}return e.length<=500?t:{_truncated:!0,_size:e.length,_preview:e.slice(0,500)}}function _Z(t,e){t.command("get <runId>").description("Get details of a specific run").option("--fetch-results","Include complete run data (alias for --full)").action(async(r,n)=>{let{client:i}=e();try{let o=await i.getRun(r);o||(D(`Run not found: ${r}`),process.exit(1));let s=mi()||n.fetchResults===!0,a=o.fileArtifacts;de({success:!0,run:{runId:o.runId,toolId:o.toolId,status:o.status,error:o.error,...o.metadata?.warnings?.length?{warnings:o.metadata.warnings}:{},toolPayload:s?o.toolPayload:lD(o.toolPayload),data:s?o.data:lD(o.data),requestSource:o.requestSource,...o.stepResults?{stepResults:s?o.stepResults:lD(o.stepResults)}:{},...a&&a.length>0?{fileArtifacts:a.map(c=>({fileKey:c.fileKey,filename:c.filename,contentType:c.contentType,size:c.size}))}:{}}}),a&&a.length>0&&Mn(`${a.length} file(s) available \u2014 download with: sg run download ${r}`)}catch(o){D(o.message),process.exit(1)}})}var ic=Be(require("fs")),ta=Be(require("path"));function EFe(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function BZ(t,e){t.command("download <runId> [fileKey]").description("Download file artifacts from a run").option("--output-dir <path>","Target directory",".").action(async(r,n,i)=>{let{client:o}=e();try{let s=await o.getRun(r);s||(D(`Run not found: ${r}`),process.exit(1));let a=s.fileArtifacts||[];a.length===0&&(D(`No file artifacts for run ${r}`),process.exit(1));let c=n?a.filter(u=>u.fileKey===n):a;c.length===0&&(D(`File artifact not found: ${n}`),Mn(`Available file artifacts: ${a.map(u=>u.fileKey).join(", ")}`),process.exit(1));let l=ta.resolve(i.outputDir);ic.existsSync(l)||ic.mkdirSync(l,{recursive:!0});for(let u of c){let d=u.downloadUrl;if(!d){D(`No download URL for ${u.fileKey} \u2014 file storage may not be configured`);continue}let A=nr(`Downloading ${u.filename}...`);try{let p=await fetch(d);if(!p.ok){A.stop(),D(`Download failed for ${u.filename}: HTTP ${p.status}`);continue}let h=Buffer.from(await p.arrayBuffer()),f=ta.basename(u.filename),E=!f||f==="."||f===".."?"download":f,S=ta.join(l,E);if(ic.existsSync(S)){let B=ta.extname(E),_=E.slice(0,E.length-B.length),v=1;for(;ic.existsSync(S);)S=ta.join(l,`${_}_${v}${B}`),v++}ic.writeFileSync(S,h),A.stop(),Me(`Downloaded ${u.filename} (${EFe(h.length)}) \u2192 ${S}`)}catch(p){A.stop(),D(`Download failed for ${u.filename}: ${p.message}`)}}}catch(s){D(s.message),process.exit(1)}})}function vZ(t,e,r){let n=t.command("run").description("View tool execution runs").addHelpText("after",`
|
|
2412
2412
|
Quick Reference:
|
|
2413
2413
|
sg run list List recent runs (default 10)
|
|
2414
2414
|
sg run list --tool <id> --status failed Filter by tool and/or status
|
|
@@ -2477,7 +2477,7 @@ Task order is per status column. --position is the 0-based index in the column:
|
|
|
2477
2477
|
Labels belong to one project. Set them on tasks by ID with --labels; --clear-labels removes them.
|
|
2478
2478
|
|
|
2479
2479
|
Output: JSON by default. Use --table for human-readable, --full to include task descriptions in lists.
|
|
2480
|
-
`),i=n.command("task").description("Manage project tasks"),o=n.command("label").description("Manage project task labels");oc(n,"list","project.list",r,()=>$Z(n,e)),oc(i,"list","project.task.list",r,()=>qZ(i,e)),oc(i,"create","project.task.create",r,()=>FZ(i,e)),oc(i,"edit","project.task.edit",r,()=>jZ(i,e)),oc(o,"list","project.label.list",r,()=>UZ(o,e)),oc(o,"create","project.label.create",r,()=>MZ(o,e)),oc(o,"edit","project.label.edit",r,()=>PZ(o,e)),oc(o,"delete","project.label.delete",r,()=>LZ(o,e))}function GZ(t){t.command("update").description("Update the superglue CLI to the latest version").option("--check","Only check for updates, don't install").action(async e=>{if(e.check){let i=
|
|
2480
|
+
`),i=n.command("task").description("Manage project tasks"),o=n.command("label").description("Manage project task labels");oc(n,"list","project.list",r,()=>$Z(n,e)),oc(i,"list","project.task.list",r,()=>qZ(i,e)),oc(i,"create","project.task.create",r,()=>FZ(i,e)),oc(i,"edit","project.task.edit",r,()=>jZ(i,e)),oc(o,"list","project.label.list",r,()=>UZ(o,e)),oc(o,"create","project.label.create",r,()=>MZ(o,e)),oc(o,"edit","project.label.edit",r,()=>PZ(o,e)),oc(o,"delete","project.label.delete",r,()=>LZ(o,e))}function GZ(t){t.command("update").description("Update the superglue CLI to the latest version").option("--check","Only check for updates, don't install").action(async e=>{if(e.check){let i=nr("Checking for updates..."),o=await GI();i.stop(),o||(D("Could not fetch latest version from npm"),process.exit(1)),HI(zr,o)>=0?Me(`You're on the latest version (${zr})`):(console.log(""),console.log(` ${C.dim}Current version:${C.reset} ${zr}`),console.log(` ${C.green}Latest version:${C.reset} ${o}`),console.log(""),console.log(` Run ${C.bold}sg update${C.reset} to upgrade`),console.log(""));return}let r=nr("Updating @superglue/cli..."),n=await bJ();r.stop(),n.success?Me(n.message):(D(n.message),process.exit(1))})}var ac=Be(require("fs")),sc=Be(require("path"));var fD=ac.existsSync(sc.resolve(__dirname,"skills/superglue"))?sc.resolve(__dirname,"skills/superglue"):sc.resolve(__dirname,"../../skills/superglue");function YZ(t){t.command("skill").description("Print the superglue skill reference (SKILL.md) for AI agents").argument("[topic]","Optional topic: references/<topic>.md (e.g. postgres, http, integration)").action(e=>{let r=e?sc.join(fD,"references",`${e}.md`):sc.join(fD,"SKILL.md");if(!ac.existsSync(r)){if(e){let n=sc.join(fD,"references"),i=ac.existsSync(n)?ac.readdirSync(n).filter(o=>o.endsWith(".md")).map(o=>o.replace(".md","")):[];D(`Topic not found: ${e}. Available: ${i.join(", ")||"none"}`)}else D(`Skill file not found: ${r}`);process.exit(1)}process.stdout.write(ac.readFileSync(r,"utf-8"))})}function bFe(t){let e=["--api-key","--endpoint"],r=["--table","--full","--json","-h","--help","-V","--version"],n=2;for(;n<t.length;){let i=t[n];if(e.includes(i))n+=2;else if(r.includes(i))n+=1;else if(i.startsWith("-"))n+=1;else return i}}function VZ(t,e){for(let r=0;r<t.length;r++){let n=t[r];if(n.startsWith(`${e}=`))return n.slice(e.length+1);if(n===e&&r+1<t.length)return t[r+1]}}var Ln=new wC.Command;Ln.name("sg").description("superglue CLI \u2014 build, run, and manage integration tools and MCP servers").version(zr).option("--api-key <key>","superglue API key for headless auth").option("--endpoint <url>","superglue API endpoint").option("--table","human-readable table output (default: JSON)").option("--full","disable truncation of large fields").addOption(new wC.Option("--json").hideHelp()).addHelpText("after",`
|
|
2481
2481
|
IMPORTANT FOR AI AGENTS:
|
|
2482
2482
|
Before using the sg CLI, you MUST read the skill reference for complete usage
|
|
2483
2483
|
instructions, patterns, and examples:
|
|
@@ -2496,6 +2496,7 @@ IMPORTANT FOR AI AGENTS:
|
|
|
2496
2496
|
sg skill suitecloud NetSuite SuiteCloud validate, preview, deploy
|
|
2497
2497
|
sg skill file-handling File detection, parsing, references, uploads
|
|
2498
2498
|
sg skill access-rules RBAC roles, tool/connection permissions (enterprise)
|
|
2499
|
+
sg skill superglue-email Custom emails with attachments through superglue
|
|
2499
2500
|
|
|
2500
2501
|
The main skill reference covers: tool building, system setup, OAuth flows,
|
|
2501
2502
|
credential handling, variable syntax, data selectors, and common pitfalls.
|