@copilotkit/shared 1.51.3 → 1.51.4-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("graphql"),require("uuid"),require("zod")):"function"==typeof define&&define.amd?define(["exports","graphql","uuid","zod"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).CopilotKitShared={},e.GraphQL,e.UUID,e.Zod)}(this,function(e,t,r,n){"use strict";function o(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(r){if("default"!==r&&!(r in e)){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}})}),Object.freeze(e)}function i(e,t){const r=e.path?(n=t,e.path.split(".").reduce((e,t)=>null==e?void 0:e[t],n)):t;var n;switch(e.rule){case"AND":return e.conditions.every(e=>i(e,t));case"OR":return e.conditions.some(e=>i(e,t));case"NOT":return!e.conditions.every(e=>i(e,t));case"EQUALS":return r===e.value;case"NOT_EQUALS":return r!==e.value;case"GREATER_THAN":return r>e.value;case"LESS_THAN":return r<e.value;case"CONTAINS":return Array.isArray(r)&&r.includes(e.value);case"NOT_CONTAINS":return Array.isArray(r)&&!r.includes(e.value);case"MATCHES":return new RegExp(e.value).test(String(r));case"STARTS_WITH":return String(r).startsWith(e.value);case"ENDS_WITH":return String(r).endsWith(e.value);case"EXISTS":return null!=r;case"NOT_EXISTS":return null==r}}const s={primary:"#007acc",success:"#22c55e",feature:"#a855f7",cta:"#ef4444",info:"#06b6d4",inherit:"inherit",warning:"#f59e0b"},a={header:`color: ${s.warning}; font-weight: bold; font-size: 16px;`,section:`color: ${s.success}; font-weight: bold;`,highlight:`color: ${s.feature}; font-weight: bold;`,cta:`color: ${s.success}; font-weight: bold;`,info:`color: ${s.info}; font-weight: bold;`,link:`color: ${s.primary}; text-decoration: underline;`,body:`color: ${s.inherit};`,warning:`color: ${s.cta}; font-weight: bold;`};function c(){console.log("%cCopilotKit Warning%c\n\nuseCopilotChatHeadless_c provides full compatibility with CopilotKit's newly released Headless UI feature set. To enable this premium feature, add your public license key, available for free at:\n\n%chttps://cloud.copilotkit.ai%c\n\nAlternatively, useCopilotChat is available for basic programmatic control, and does not require an API key.\n\nTo learn more about premium features, read the documentation here:\n\n%chttps://docs.copilotkit.ai/premium%c",a.header,a.body,a.cta,a.body,a.link,a.body)}function l(e){console.log(`\n%cCopilotKit Warning%c \n\nIn order to use ${e}, you need to add your CopilotKit API key, available for free at https://cloud.copilotkit.ai.\n `.trim(),a.header,a.body)}function u(e,t){console.log(e,...t)}const h={success:e=>u(`%c✅ ${e}`,[a.section]),info:e=>u(`%cℹ️ ${e}`,[a.info]),feature:e=>u(`%c✨ ${e}`,[a.highlight]),cta:e=>u(`%c🚀 ${e}`,[a.cta]),logCopilotKitPlatformMessage:c,publicApiKeyRequired:l};var d,p;e.Severity=void 0,(d=e.Severity||(e.Severity={})).CRITICAL="critical",d.WARNING="warning",d.INFO="info",e.ErrorVisibility=void 0,(p=e.ErrorVisibility||(e.ErrorVisibility={})).BANNER="banner",p.TOAST="toast",p.SILENT="silent",p.DEV_ONLY="dev_only";const f={COPILOT_ERROR:"CopilotError",COPILOT_API_DISCOVERY_ERROR:"CopilotApiDiscoveryError",COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR:"CopilotKitRemoteEndpointDiscoveryError",COPILOT_KIT_AGENT_DISCOVERY_ERROR:"CopilotKitAgentDiscoveryError",COPILOT_KIT_LOW_LEVEL_ERROR:"CopilotKitLowLevelError",COPILOT_KIT_VERSION_MISMATCH_ERROR:"CopilotKitVersionMismatchError",RESOLVED_COPILOT_KIT_ERROR:"ResolvedCopilotKitError",CONFIGURATION_ERROR:"ConfigurationError",MISSING_PUBLIC_API_KEY_ERROR:"MissingPublicApiKeyError",UPGRADE_REQUIRED_ERROR:"UpgradeRequiredError"},g=[f.CONFIGURATION_ERROR,f.MISSING_PUBLIC_API_KEY_ERROR,f.UPGRADE_REQUIRED_ERROR,f.COPILOT_API_DISCOVERY_ERROR,f.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR,f.COPILOT_KIT_AGENT_DISCOVERY_ERROR],m=g;var y;e.CopilotKitErrorCode=void 0,(y=e.CopilotKitErrorCode||(e.CopilotKitErrorCode={})).NETWORK_ERROR="NETWORK_ERROR",y.NOT_FOUND="NOT_FOUND",y.AGENT_NOT_FOUND="AGENT_NOT_FOUND",y.API_NOT_FOUND="API_NOT_FOUND",y.REMOTE_ENDPOINT_NOT_FOUND="REMOTE_ENDPOINT_NOT_FOUND",y.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",y.MISUSE="MISUSE",y.UNKNOWN="UNKNOWN",y.VERSION_MISMATCH="VERSION_MISMATCH",y.CONFIGURATION_ERROR="CONFIGURATION_ERROR",y.MISSING_PUBLIC_API_KEY_ERROR="MISSING_PUBLIC_API_KEY_ERROR",y.UPGRADE_REQUIRED_ERROR="UPGRADE_REQUIRED_ERROR";const b="https://docs.copilotkit.ai",v=e=>`See more: [${e}](${e})`,E={[e.CopilotKitErrorCode.NETWORK_ERROR]:{statusCode:503,troubleshootingUrl:`${b}/troubleshooting/common-issues#i-am-getting-a-network-errors--api-not-found`,visibility:e.ErrorVisibility.BANNER,severity:e.Severity.CRITICAL},[e.CopilotKitErrorCode.NOT_FOUND]:{statusCode:404,troubleshootingUrl:`${b}/troubleshooting/common-issues#i-am-getting-a-network-errors--api-not-found`,visibility:e.ErrorVisibility.BANNER,severity:e.Severity.CRITICAL},[e.CopilotKitErrorCode.AGENT_NOT_FOUND]:{statusCode:500,troubleshootingUrl:`${b}/coagents/troubleshooting/common-issues#i-am-getting-agent-not-found-error`,visibility:e.ErrorVisibility.BANNER,severity:e.Severity.CRITICAL},[e.CopilotKitErrorCode.API_NOT_FOUND]:{statusCode:404,troubleshootingUrl:`${b}/troubleshooting/common-issues#i-am-getting-a-network-errors--api-not-found`,visibility:e.ErrorVisibility.BANNER,severity:e.Severity.CRITICAL},[e.CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND]:{statusCode:404,troubleshootingUrl:`${b}/troubleshooting/common-issues#i-am-getting-copilotkits-remote-endpoint-not-found-error`,visibility:e.ErrorVisibility.BANNER,severity:e.Severity.CRITICAL},[e.CopilotKitErrorCode.AUTHENTICATION_ERROR]:{statusCode:401,troubleshootingUrl:`${b}/troubleshooting/common-issues#authentication-errors`,visibility:e.ErrorVisibility.BANNER,severity:e.Severity.CRITICAL},[e.CopilotKitErrorCode.MISUSE]:{statusCode:400,troubleshootingUrl:null,visibility:e.ErrorVisibility.DEV_ONLY,severity:e.Severity.WARNING},[e.CopilotKitErrorCode.UNKNOWN]:{statusCode:500,visibility:e.ErrorVisibility.TOAST,severity:e.Severity.CRITICAL},[e.CopilotKitErrorCode.CONFIGURATION_ERROR]:{statusCode:400,troubleshootingUrl:null,severity:e.Severity.WARNING,visibility:e.ErrorVisibility.BANNER},[e.CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR]:{statusCode:400,troubleshootingUrl:null,severity:e.Severity.CRITICAL,visibility:e.ErrorVisibility.BANNER},[e.CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR]:{statusCode:402,troubleshootingUrl:null,severity:e.Severity.WARNING,visibility:e.ErrorVisibility.BANNER},[e.CopilotKitErrorCode.VERSION_MISMATCH]:{statusCode:400,troubleshootingUrl:null,visibility:e.ErrorVisibility.DEV_ONLY,severity:e.Severity.INFO}};class _ extends t.GraphQLError{constructor({message:t="Unknown error occurred",code:r,severity:n,visibility:o}){var i;const s=f.COPILOT_ERROR,a=E[r],{statusCode:c}=a,l=null!==(i=null!=o?o:a.visibility)&&void 0!==i?i:e.ErrorVisibility.TOAST,u=null!=n?n:"severity"in a?a.severity:void 0;super(t,{extensions:{name:s,statusCode:c,code:r,visibility:l,severity:u,troubleshootingUrl:"troubleshootingUrl"in a?a.troubleshootingUrl:null,originalError:{message:t,stack:(new Error).stack}}}),this.code=r,this.name=s,this.statusCode=c,this.severity=u,this.visibility=l}}const w=({reactCoreVersion:e,runtimeVersion:t,runtimeClientGqlVersion:r})=>`Version mismatch detected: @copilotkit/runtime@${null!=t?t:""} is not compatible with @copilotkit/react-core@${e} and @copilotkit/runtime-client-gql@${r}. Please ensure all installed copilotkit packages are on the same version.`;class R extends _{constructor(t={}){var r,n,o;const i=null!==(r=t.url)&&void 0!==r?r:"";let s="";(null==i?void 0:i.includes("/info"))?s="when fetching CopilotKit info":i.includes("/actions/execute")?s="when attempting to execute actions.":i.includes("/agents/state")?s="when attempting to get agent state.":i.includes("/agents/execute")&&(s="when attempting to execute agent(s).");const a=null!==(n=t.message)&&void 0!==n?n:t.url?`Failed to find CopilotKit API endpoint at url ${t.url} ${s}`:"Failed to find CopilotKit API endpoint.",c=null!==(o=t.code)&&void 0!==o?o:e.CopilotKitErrorCode.API_NOT_FOUND;super({message:`${a}.\n\n${v(E[c].troubleshootingUrl)}`,code:c}),this.name=f.COPILOT_API_DISCOVERY_ERROR}}class O extends R{constructor(t){var r;super({message:null!==(r=null==t?void 0:t.message)&&void 0!==r?r:(null==t?void 0:t.url)?`Failed to find or contact remote endpoint at url ${t.url}`:"Failed to find or contact remote endpoint",code:e.CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND}),this.name=f.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR}}class C extends _{constructor({error:t,url:r,message:n}){let o=e.CopilotKitErrorCode.NETWORK_ERROR;const i=t.code;super({message:null!=n?n:T({errorCode:i,url:r}),code:o}),this.name=f.COPILOT_KIT_LOW_LEVEL_ERROR}}class I extends _{constructor(t){super({message:t,code:e.CopilotKitErrorCode.CONFIGURATION_ERROR}),this.name=f.CONFIGURATION_ERROR,this.severity=e.Severity.WARNING}}function S(e){var t;return e instanceof _||e instanceof C||(null==e?void 0:e.name)&&e.name.includes("CopilotKit")||void 0!==(null===(t=null==e?void 0:e.extensions)||void 0===t?void 0:t.code)}const T=({errorCode:t,url:r})=>{const n=E[e.CopilotKitErrorCode.NETWORK_ERROR].troubleshootingUrl,o=(e=`Failed to fetch from url ${r}.`)=>`${e}.\n\nPossible reasons:\n- -The server may have an error preventing it from returning a response (Check the server logs for more info).\n- -The server might be down or unreachable\n- -There might be a network issue (e.g., DNS failure, connection timeout) \n- -The URL might be incorrect\n- -The server is not running on the specified port\n\n${v(n)}`;if(r.includes("/info"))return o(`Failed to fetch CopilotKit agents/action information from url ${r}.`);if(r.includes("/actions/execute"))return o(`Fetch call to ${r} to execute actions failed.`);if(r.includes("/agents/state"))return o(`Fetch call to ${r} to get agent state failed.`);if(r.includes("/agents/execute"))return o(`Fetch call to ${r} to execute agent(s) failed.`);switch(t){case"ECONNREFUSED":return`Connection to ${r} was refused. Ensure the server is running and accessible.\n\n${v(n)}`;case"ENOTFOUND":return`The server on ${r} could not be found. Check the URL or your network configuration.\n\n${v(E[e.CopilotKitErrorCode.NOT_FOUND].troubleshootingUrl)}`;case"ETIMEDOUT":return`The connection to ${r} timed out. The server might be overloaded or taking too long to respond.\n\n${v(n)}`;default:return}};function A(e){let t={};for(let r of e||[])t[r.name]=P(r);let r=[];for(let t of e||[])!1!==t.required&&r.push(t.name);return{type:"object",properties:t,required:r}}function k(e,t,r){const n={name:e,description:t.description};switch(r||(n.required=!1),t.type){case"string":return Object.assign(Object.assign(Object.assign({},n),{type:"string"}),t.enum&&{enum:t.enum});case"number":case"boolean":return Object.assign(Object.assign({},n),{type:t.type});case"object":if(t.properties){const e=[],r=t.required||[];for(const[n,o]of Object.entries(t.properties))e.push(k(n,o,r.includes(n)));return Object.assign(Object.assign({},n),{type:"object",attributes:e})}return Object.assign(Object.assign({},n),{type:"object"});case"array":if("object"===t.items.type&&"properties"in t.items){const e=[],r=t.items.required||[];for(const[n,o]of Object.entries(t.items.properties||{}))e.push(k(n,o,r.includes(n)));return Object.assign(Object.assign({},n),{type:"object[]",attributes:e})}if("array"===t.items.type)throw new Error("Nested arrays are not supported");return Object.assign(Object.assign({},n),{type:`${t.items.type}[]`});default:return Object.assign(Object.assign({},n),{type:"string"})}}function P(e){var t,r,n;switch(e.type){case"string":return Object.assign({type:"string",description:e.description},e.enum&&{enum:e.enum});case"number":case"boolean":return{type:e.type,description:e.description};case"object":case"object[]":const o=null===(t=e.attributes)||void 0===t?void 0:t.reduce((e,t)=>(e[t.name]=P(t),e),{}),i=null===(r=e.attributes)||void 0===r?void 0:r.filter(e=>!1!==e.required).map(e=>e.name);return"object[]"===e.type?{type:"array",items:Object.assign(Object.assign({type:"object"},o&&{properties:o}),i&&i.length>0&&{required:i}),description:e.description}:Object.assign(Object.assign({type:"object",description:e.description},o&&{properties:o}),i&&i.length>0&&{required:i});default:if(null===(n=e.type)||void 0===n?void 0:n.endsWith("[]")){return{type:"array",items:{type:e.type.slice(0,-2)},description:e.description}}return{type:"string",description:e.description}}}function N(e,t){if("object"===e.type){const r={};if(!e.properties||!Object.keys(e.properties).length)return t?n.z.object(r):n.z.object(r).optional();for(const[t,n]of Object.entries(e.properties))r[t]=N(n,!!e.required&&e.required.includes(t));let o=n.z.object(r).describe(e.description);return t?o:o.optional()}if("string"===e.type){let r=n.z.string().describe(e.description);return t?r:r.optional()}if("number"===e.type){let r=n.z.number().describe(e.description);return t?r:r.optional()}if("boolean"===e.type){let r=n.z.boolean().describe(e.description);return t?r:r.optional()}if("array"===e.type){let r=N(e.items,!0),o=n.z.array(r).describe(e.description);return t?o:o.optional()}throw new Error("Invalid JSON schema")}function x(e){if("function"==typeof e)return e.toString();if(Array.isArray(e))return e.map(x);if(null!==e&&"object"==typeof e){const t={};for(const r of Object.keys(e))t[r]=x(e[r]);return t}return e}const D="https://api.cloud.copilotkit.ai",K=`${D}/copilotkit/v1`;var M=function(e,t){return M=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},M(e,t)};function j(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}M(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var $=function(){return $=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},$.apply(this,arguments)};function U(e,t,r,n){return new(r||(r=Promise))(function(o,i){function s(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})}function L(e,t){var r,n,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(i=0)),i;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,n=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){i.label=a[1];break}if(6===a[0]&&i.label<o[1]){i.label=o[1],o=a;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(a);break}o[2]&&i.ops.pop(),i.trys.pop();continue}a=t.call(e,i)}catch(e){a=[6,e],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}function H(e,t,r){if(r||2===arguments.length)for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))}function W(e,t,r){t.split&&(t=t.split("."));for(var n,o,i=0,s=t.length,a=e;i<s&&"__proto__"!=(o=""+t[i++])&&"constructor"!==o&&"prototype"!==o;)a=a[o]=i===s?r:typeof(n=a[o])==typeof t?n:0*t[i]!=0||~(""+t[i]).indexOf(".")?{}:[]}"function"==typeof SuppressedError&&SuppressedError;var q=function(e){function t(t,r){var n=e.call(this,"".concat(t," ").concat(r))||this;return n.field=t,n}return j(t,e),t}(Error);function F(e){return"string"==typeof e}function V(e){return null!=e}function B(e){return"object"===Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}var J="is not a string",G="is not an object",z="is nil";function Y(e){!function(e){if(!V(e))throw new q("Event",z);if("object"!=typeof e)throw new q("Event",G)}(e),function(e){if(!F(e.type))throw new q(".type",J)}(e),function(e){if(!F(e.messageId))throw new q(".messageId",J)}(e),"track"===e.type&&(function(e){if(!F(e.event))throw new q(".event",J)}(e),function(e){if(!B(e.properties))throw new q(".properties",G)}(e)),["group","identify"].includes(e.type)&&function(e){if(!B(e.traits))throw new q(".traits",G)}(e)}var Q=function(e){var t,r;this.settings=e,this.createMessageId=e.createMessageId,this.onEventMethodCall=null!==(t=e.onEventMethodCall)&&void 0!==t?t:function(){},this.onFinishedEvent=null!==(r=e.onFinishedEvent)&&void 0!==r?r:function(){}},X=function(){function e(e){this.settings=new Q(e)}return e.prototype.track=function(e,t,r,n){return this.settings.onEventMethodCall({type:"track",options:r}),this.normalize($($({},this.baseEvent()),{event:e,type:"track",properties:null!=t?t:{},options:$({},r),integrations:$({},n)}))},e.prototype.page=function(e,t,r,n,o){var i;this.settings.onEventMethodCall({type:"page",options:n});var s={type:"page",properties:$({},r),options:$({},n),integrations:$({},o)};return null!==e&&(s.category=e,s.properties=null!==(i=s.properties)&&void 0!==i?i:{},s.properties.category=e),null!==t&&(s.name=t),this.normalize($($({},this.baseEvent()),s))},e.prototype.screen=function(e,t,r,n,o){this.settings.onEventMethodCall({type:"screen",options:n});var i={type:"screen",properties:$({},r),options:$({},n),integrations:$({},o)};return null!==e&&(i.category=e),null!==t&&(i.name=t),this.normalize($($({},this.baseEvent()),i))},e.prototype.identify=function(e,t,r,n){return this.settings.onEventMethodCall({type:"identify",options:r}),this.normalize($($({},this.baseEvent()),{type:"identify",userId:e,traits:null!=t?t:{},options:$({},r),integrations:n}))},e.prototype.group=function(e,t,r,n){return this.settings.onEventMethodCall({type:"group",options:r}),this.normalize($($({},this.baseEvent()),{type:"group",traits:null!=t?t:{},options:$({},r),integrations:$({},n),groupId:e}))},e.prototype.alias=function(e,t,r,n){this.settings.onEventMethodCall({type:"alias",options:r});var o={userId:e,type:"alias",options:$({},r),integrations:$({},n)};return null!==t&&(o.previousId=t),void 0===e?this.normalize($($({},o),this.baseEvent())):this.normalize($($({},this.baseEvent()),o))},e.prototype.baseEvent=function(){return{integrations:{},options:{}}},e.prototype.context=function(e){var t,r=["userId","anonymousId","timestamp","messageId"];delete e.integrations;var n=Object.keys(e),o=null!==(t=e.context)&&void 0!==t?t:{},i={};return n.forEach(function(t){"context"!==t&&(r.includes(t)?W(i,t,e[t]):W(o,t,e[t]))}),[o,i]},e.prototype.normalize=function(e){var t,r,n,o,i=Object.keys(null!==(t=e.integrations)&&void 0!==t?t:{}).reduce(function(t,r){var n,o;return $($({},t),((n={})[r]=Boolean(null===(o=e.integrations)||void 0===o?void 0:o[r]),n))},{});e.options=(n=e.options||{},o=function(e,t){return void 0!==t},Object.keys(n).filter(function(e){return o(e,n[e])}).reduce(function(e,t){return e[t]=n[t],e},{}));var s=$($({},i),null===(r=e.options)||void 0===r?void 0:r.integrations),a=e.options?this.context(e.options):[],c=a[0],l=a[1],u=e.options,h=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(r[n[o]]=e[n[o]])}return r}(e,["options"]),d=$($($($({timestamp:new Date},h),{context:c,integrations:s}),l),{messageId:u.messageId||this.settings.createMessageId()});return this.settings.onFinishedEvent(d),Y(d),d},e}();function Z(e,t){return new Promise(function(r,n){var o=setTimeout(function(){n(Error("Promise timed out"))},t);e.then(function(e){return clearTimeout(o),r(e)}).catch(n)})}function ee(e){return new Promise(function(t){return setTimeout(t,e)})}function te(e,t,r){return ee(r).then(function(){return Z(function(){try{return Promise.resolve(t(e))}catch(e){return Promise.reject(e)}}(),1e3)}).catch(function(t){null==e||e.log("warn","Callback Error",{error:t}),null==e||e.stats.increment("callback_error")}).then(function(){return e})}var re=function(){function e(e){var t;this.callbacks={},this.warned=!1,this.maxListeners=null!==(t=null==e?void 0:e.maxListeners)&&void 0!==t?t:10}return e.prototype.warnIfPossibleMemoryLeak=function(e){this.warned||this.maxListeners&&this.callbacks[e].length>this.maxListeners&&(console.warn("Event Emitter: Possible memory leak detected; ".concat(String(e)," has exceeded ").concat(this.maxListeners," listeners.")),this.warned=!0)},e.prototype.on=function(e,t){return this.callbacks[e]?(this.callbacks[e].push(t),this.warnIfPossibleMemoryLeak(e)):this.callbacks[e]=[t],this},e.prototype.once=function(e,t){var r=this,n=function(){for(var o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];r.off(e,n),t.apply(r,o)};return this.on(e,n),this},e.prototype.off=function(e,t){var r,n=(null!==(r=this.callbacks[e])&&void 0!==r?r:[]).filter(function(e){return e!==t});return this.callbacks[e]=n,this},e.prototype.emit=function(e){for(var t,r=this,n=[],o=1;o<arguments.length;o++)n[o-1]=arguments[o];return(null!==(t=this.callbacks[e])&&void 0!==t?t:[]).forEach(function(e){e.apply(r,n)}),this},e}();function ne(e){var t=Math.random()+1,r=e.minTimeout,n=void 0===r?500:r,o=e.factor,i=void 0===o?2:o,s=e.attempt,a=e.maxTimeout,c=void 0===a?1/0:a;return Math.min(t*n*Math.pow(i,s),c)}for(var oe,ie="onRemoveFromFuture",se=function(e){function t(t,r,n){var o=e.call(this)||this;return o.future=[],o.maxAttempts=t,o.queue=r,o.seen=null!=n?n:{},o}return j(t,e),t.prototype.push=function(){for(var e=this,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];var n=t.map(function(t){return!(e.updateAttempts(t)>e.maxAttempts||e.includes(t))&&(e.queue.push(t),!0)});return this.queue=this.queue.sort(function(t,r){return e.getAttempts(t)-e.getAttempts(r)}),n},t.prototype.pushWithBackoff=function(e,t){var r=this;if(void 0===t&&(t=0),0==t&&0===this.getAttempts(e))return this.push(e)[0];var n=this.updateAttempts(e);if(n>this.maxAttempts||this.includes(e))return!1;var o=ne({attempt:n-1});return t>0&&o<t&&(o=t),setTimeout(function(){r.queue.push(e),r.future=r.future.filter(function(t){return t.id!==e.id}),r.emit(ie)},o),this.future.push(e),!0},t.prototype.getAttempts=function(e){var t;return null!==(t=this.seen[e.id])&&void 0!==t?t:0},t.prototype.updateAttempts=function(e){return this.seen[e.id]=this.getAttempts(e)+1,this.getAttempts(e)},t.prototype.includes=function(e){return this.queue.includes(e)||this.future.includes(e)||Boolean(this.queue.find(function(t){return t.id===e.id}))||Boolean(this.future.find(function(t){return t.id===e.id}))},t.prototype.pop=function(){return this.queue.shift()},Object.defineProperty(t.prototype,"length",{get:function(){return this.queue.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"todo",{get:function(){return this.queue.length+this.future.length},enumerable:!1,configurable:!0}),t}(re),ae=256,ce=[];ae--;)ce[ae]=(ae+256).toString(16).substring(1);function le(){var e,t=0,r="";if(!oe||ae+16>256){for(oe=Array(t=256);t--;)oe[t]=256*Math.random()|0;t=ae=0}for(;t<16;t++)e=oe[ae+t],r+=6==t?ce[15&e|64]:8==t?ce[63&e|128]:ce[e],1&t&&t>1&&t<11&&(r+="-");return ae++,r}var ue=function(){function e(){this._logs=[]}return e.prototype.log=function(e,t,r){var n=new Date;this._logs.push({level:e,message:t,time:n,extras:r})},Object.defineProperty(e.prototype,"logs",{get:function(){return this._logs},enumerable:!1,configurable:!0}),e.prototype.flush=function(){if(this.logs.length>1){var e=this._logs.reduce(function(e,t){var r,n,o,i=$($({},t),{json:JSON.stringify(t.extras,null," "),extras:t.extras});delete i.time;var s=null!==(o=null===(n=t.time)||void 0===n?void 0:n.toISOString())&&void 0!==o?o:"";return e[s]&&(s="".concat(s,"-").concat(Math.random())),$($({},e),((r={})[s]=i,r))},{});console.table?console.table(e):console.log(e)}else this.logs.forEach(function(e){var t=e.level,r=e.message,n=e.extras;"info"===t||"debug"===t?console.log(r,null!=n?n:""):console[t](r,null!=n?n:"")});this._logs=[]},e}(),he=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return j(t,e),t.prototype.gauge=function(){},t.prototype.increment=function(){},t.prototype.flush=function(){},t.prototype.serialize=function(){return[]},t}(function(){function e(){this.metrics=[]}return e.prototype.increment=function(e,t,r){void 0===t&&(t=1),this.metrics.push({metric:e,value:t,tags:null!=r?r:[],type:"counter",timestamp:Date.now()})},e.prototype.gauge=function(e,t,r){this.metrics.push({metric:e,value:t,tags:null!=r?r:[],type:"gauge",timestamp:Date.now()})},e.prototype.flush=function(){var e=this.metrics.map(function(e){return $($({},e),{tags:e.tags.join(",")})});console.table?console.table(e):console.log(e),this.metrics=[]},e.prototype.serialize=function(){return this.metrics.map(function(e){return{m:e.metric,v:e.value,t:e.tags,k:(t=e.type,{gauge:"g",counter:"c"}[t]),e:e.timestamp};var t})},e}()),de=function(e){var t,r,n;this.retry=null===(t=e.retry)||void 0===t||t,this.type=null!==(r=e.type)&&void 0!==r?r:"plugin Error",this.reason=null!==(n=e.reason)&&void 0!==n?n:""},pe=function(){function e(e,t,r,n){void 0===t&&(t=le()),void 0===r&&(r=new he),void 0===n&&(n=new ue),this.attempts=0,this.event=e,this._id=t,this.logger=n,this.stats=r}return e.system=function(){},e.prototype.isSame=function(e){return e.id===this.id},e.prototype.cancel=function(e){if(e)throw e;throw new de({reason:"Context Cancel"})},e.prototype.log=function(e,t,r){this.logger.log(e,t,r)},Object.defineProperty(e.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),e.prototype.updateEvent=function(e,t){var r;if("integrations"===e.split(".")[0]){var n=e.split(".")[1];if(!1===(null===(r=this.event.integrations)||void 0===r?void 0:r[n]))return this.event}return W(this.event,e,t),this.event},e.prototype.failedDelivery=function(){return this._failedDelivery},e.prototype.setFailedDelivery=function(e){this._failedDelivery=e},e.prototype.logs=function(){return this.logger.logs},e.prototype.flush=function(){this.logger.flush(),this.stats.flush()},e.prototype.toJSON=function(){return{id:this._id,event:this.event,logs:this.logger.logs,metrics:this.stats.metrics}},e}();function fe(e,t){e.log("debug","plugin",{plugin:t.name});var r=(new Date).getTime(),n=t[e.event.type];return void 0===n?Promise.resolve(e):function(e){return U(this,void 0,void 0,function(){var t;return L(this,function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,e()];case 1:return[2,r.sent()];case 2:return t=r.sent(),[2,Promise.reject(t)];case 3:return[2]}})})}(function(){return n.apply(t,[e])}).then(function(e){var n=(new Date).getTime()-r;return e.stats.gauge("plugin_time",n,["plugin:".concat(t.name)]),e}).catch(function(r){if(r instanceof de&&"middleware_cancellation"===r.type)throw r;return r instanceof de?(e.log("warn",r.type,{plugin:t.name,error:r}),r):(e.log("error","plugin Error",{plugin:t.name,error:r}),e.stats.increment("plugin_error",1,["plugin:".concat(t.name)]),r)})}function ge(e,t){return fe(e,t).then(function(t){if(t instanceof pe)return t;e.log("debug","Context canceled"),e.stats.increment("context_canceled"),e.cancel(t)})}var me=function(e){function t(t){var r,n,o,i=e.call(this)||this;return i.criticalTasks=(o=0,{done:function(){return r},run:function(e){var t,i=e();return"object"==typeof(t=i)&&null!==t&&"then"in t&&"function"==typeof t.then&&(1===++o&&(r=new Promise(function(e){return n=e})),i.finally(function(){return 0===--o&&n()})),i}}),i.plugins=[],i.failedInitializations=[],i.flushing=!1,i.queue=t,i.queue.on(ie,function(){i.scheduleFlush(0)}),i}return j(t,e),t.prototype.register=function(e,t,r){return U(this,void 0,void 0,function(){var n,o,i=this;return L(this,function(s){switch(s.label){case 0:return this.plugins.push(t),n=function(r){i.failedInitializations.push(t.name),i.emit("initialization_failure",t),console.warn(t.name,r),e.log("warn","Failed to load destination",{plugin:t.name,error:r}),i.plugins=i.plugins.filter(function(e){return e!==t})},"destination"!==t.type||"Segment.io"===t.name?[3,1]:(t.load(e,r).catch(n),[3,4]);case 1:return s.trys.push([1,3,,4]),[4,t.load(e,r)];case 2:return s.sent(),[3,4];case 3:return o=s.sent(),n(o),[3,4];case 4:return[2]}})})},t.prototype.deregister=function(e,t,r){return U(this,void 0,void 0,function(){var n;return L(this,function(o){switch(o.label){case 0:return o.trys.push([0,3,,4]),t.unload?[4,Promise.resolve(t.unload(e,r))]:[3,2];case 1:o.sent(),o.label=2;case 2:return this.plugins=this.plugins.filter(function(e){return e.name!==t.name}),[3,4];case 3:return n=o.sent(),e.log("warn","Failed to unload destination",{plugin:t.name,error:n}),[3,4];case 4:return[2]}})})},t.prototype.dispatch=function(e){return U(this,void 0,void 0,function(){var t;return L(this,function(r){return e.log("debug","Dispatching"),e.stats.increment("message_dispatched"),this.queue.push(e),t=this.subscribeToDelivery(e),this.scheduleFlush(0),[2,t]})})},t.prototype.subscribeToDelivery=function(e){return U(this,void 0,void 0,function(){var t=this;return L(this,function(r){return[2,new Promise(function(r){var n=function(o,i){o.isSame(e)&&(t.off("flush",n),r(o))};t.on("flush",n)})]})})},t.prototype.dispatchSingle=function(e){return U(this,void 0,void 0,function(){var t=this;return L(this,function(r){return e.log("debug","Dispatching"),e.stats.increment("message_dispatched"),this.queue.updateAttempts(e),e.attempts=1,[2,this.deliver(e).catch(function(r){return t.enqueuRetry(r,e)?t.subscribeToDelivery(e):(e.setFailedDelivery({reason:r}),e)})]})})},t.prototype.isEmpty=function(){return 0===this.queue.length},t.prototype.scheduleFlush=function(e){var t=this;void 0===e&&(e=500),this.flushing||(this.flushing=!0,setTimeout(function(){t.flush().then(function(){setTimeout(function(){t.flushing=!1,t.queue.length&&t.scheduleFlush(0)},0)})},e))},t.prototype.deliver=function(e){return U(this,void 0,void 0,function(){var t,r,n,o;return L(this,function(i){switch(i.label){case 0:return[4,this.criticalTasks.done()];case 1:i.sent(),t=Date.now(),i.label=2;case 2:return i.trys.push([2,4,,5]),[4,this.flushOne(e)];case 3:return e=i.sent(),r=Date.now()-t,this.emit("delivery_success",e),e.stats.gauge("delivered",r),e.log("debug","Delivered",e.event),[2,e];case 4:throw n=i.sent(),o=n,e.log("error","Failed to deliver",o),this.emit("delivery_failure",e,o),e.stats.increment("delivery_failed"),n;case 5:return[2]}})})},t.prototype.enqueuRetry=function(e,t){return!(e instanceof de&&!e.retry)&&this.queue.pushWithBackoff(t)},t.prototype.flush=function(){return U(this,void 0,void 0,function(){var e,t;return L(this,function(r){switch(r.label){case 0:if(0===this.queue.length)return[2,[]];if(!(e=this.queue.pop()))return[2,[]];e.attempts=this.queue.getAttempts(e),r.label=1;case 1:return r.trys.push([1,3,,4]),[4,this.deliver(e)];case 2:return e=r.sent(),this.emit("flush",e,!0),[3,4];case 3:return t=r.sent(),this.enqueuRetry(t,e)||(e.setFailedDelivery({reason:t}),this.emit("flush",e,!1)),[2,[]];case 4:return[2,[e]]}})})},t.prototype.isReady=function(){return!0},t.prototype.availableExtensions=function(e){var t,r,n=this.plugins.filter(function(t){var r,n,o;if("destination"!==t.type&&"Segment.io"!==t.name)return!0;var i=void 0;return null===(r=t.alternativeNames)||void 0===r||r.forEach(function(t){void 0!==e[t]&&(i=e[t])}),null!==(o=null!==(n=e[t.name])&&void 0!==n?n:i)&&void 0!==o?o:!1!==("Segment.io"===t.name||e.All)}),o=(t="type",r={},n.forEach(function(e){var n,o,i=e[t];void 0!==(o="string"!=typeof i?JSON.stringify(i):i)&&(r[o]=H(H([],null!==(n=r[o])&&void 0!==n?n:[],!0),[e],!1))}),r),i=o.before,s=void 0===i?[]:i,a=o.enrichment,c=void 0===a?[]:a,l=o.destination,u=void 0===l?[]:l,h=o.after;return{before:s,enrichment:c,destinations:u,after:void 0===h?[]:h}},t.prototype.flushOne=function(e){var t,r;return U(this,void 0,void 0,function(){var n,o,i,s,a,c,l,u,h,d,p,f,g,m;return L(this,function(y){switch(y.label){case 0:if(!this.isReady())throw new Error("Not ready");e.attempts>1&&this.emit("delivery_retry",e),n=this.availableExtensions(null!==(t=e.event.integrations)&&void 0!==t?t:{}),o=n.before,i=n.enrichment,s=0,a=o,y.label=1;case 1:return s<a.length?(c=a[s],[4,ge(e,c)]):[3,4];case 2:(d=y.sent())instanceof pe&&(e=d),this.emit("message_enriched",e,c),y.label=3;case 3:return s++,[3,1];case 4:l=0,u=i,y.label=5;case 5:return l<u.length?(h=u[l],[4,fe(e,h)]):[3,8];case 6:(d=y.sent())instanceof pe&&(e=d),this.emit("message_enriched",e,h),y.label=7;case 7:return l++,[3,5];case 8:return p=this.availableExtensions(null!==(r=e.event.integrations)&&void 0!==r?r:{}),f=p.destinations,g=p.after,[4,new Promise(function(t,r){setTimeout(function(){var n=f.map(function(t){return fe(e,t)});Promise.all(n).then(t).catch(r)},0)})];case 9:return y.sent(),e.stats.increment("message_delivered"),this.emit("message_delivered",e),m=g.map(function(t){return fe(e,t)}),[4,Promise.all(m)];case 10:return y.sent(),[2,e]}})})},t}(re);const ye="2.3.0";class be{id=le();items=[];sizeInBytes=0;maxEventCount;constructor(e){this.maxEventCount=Math.max(1,e)}tryAdd(e){if(this.length===this.maxEventCount)return{success:!1,message:`Event limit of ${this.maxEventCount} has been exceeded.`};const t=this.calculateSize(e.context);return t>32768?{success:!1,message:"Event exceeds maximum event size of 32 KB"}:this.sizeInBytes+t>491520?{success:!1,message:"Event has caused batch size to exceed 480 KB"}:(this.items.push(e),this.sizeInBytes+=t,{success:!0})}get length(){return this.items.length}calculateSize(e){return encodeURI(JSON.stringify(e.event)).split(/%..|i/).length}getEvents(){return this.items.map(({context:e})=>e.event)}getContexts(){return this.items.map(e=>e.context)}resolveEvents(){this.items.forEach(({resolver:e,context:t})=>e(t))}}var ve=crypto;const Ee=e=>e instanceof CryptoKey,_e=new TextEncoder,we=new TextDecoder;const Re=e=>(e=>{let t=e;"string"==typeof t&&(t=_e.encode(t));const r=[];for(let e=0;e<t.length;e+=32768)r.push(String.fromCharCode.apply(null,t.subarray(e,e+32768)));return btoa(r.join(""))})(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),Oe=e=>{let t=e;t instanceof Uint8Array&&(t=we.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return(e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r})(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class Ce extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}Ce.code="ERR_JOSE_GENERIC";(class extends Ce{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n,this.payload=t}}).code="ERR_JWT_CLAIM_VALIDATION_FAILED";(class extends Ce{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n,this.payload=t}}).code="ERR_JWT_EXPIRED";(class extends Ce{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}).code="ERR_JOSE_ALG_NOT_ALLOWED";class Ie extends Ce{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}Ie.code="ERR_JOSE_NOT_SUPPORTED";(class extends Ce{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}).code="ERR_JWE_DECRYPTION_FAILED";(class extends Ce{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}).code="ERR_JWE_INVALID";class Se extends Ce{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}Se.code="ERR_JWS_INVALID";class Te extends Ce{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}Te.code="ERR_JWT_INVALID";(class extends Ce{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}).code="ERR_JWK_INVALID";(class extends Ce{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}).code="ERR_JWKS_INVALID";(class extends Ce{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}).code="ERR_JWKS_NO_MATCHING_KEY";(class extends Ce{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}).code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";(class extends Ce{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}).code="ERR_JWKS_TIMEOUT";function Ae(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function ke(e,t){return e.name===t}function Pe(e){return parseInt(e.name.slice(4),10)}function Ne(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!ke(e.algorithm,"HMAC"))throw Ae("HMAC");const r=parseInt(t.slice(2),10);if(Pe(e.algorithm.hash)!==r)throw Ae(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ke(e.algorithm,"RSASSA-PKCS1-v1_5"))throw Ae("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(Pe(e.algorithm.hash)!==r)throw Ae(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ke(e.algorithm,"RSA-PSS"))throw Ae("RSA-PSS");const r=parseInt(t.slice(2),10);if(Pe(e.algorithm.hash)!==r)throw Ae(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw Ae("Ed25519 or Ed448");break;case"Ed25519":if(!ke(e.algorithm,"Ed25519"))throw Ae("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!ke(e.algorithm,"ECDSA"))throw Ae("ECDSA");const r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw Ae(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const r=t.pop();e+=`one of ${t.join(", ")}, or ${r}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,r)}function xe(e,t,...r){if((r=r.filter(Boolean)).length>2){const t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}(class extends Ce{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}).code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";var De=(e,...t)=>xe("Key must be ",e,...t);function Ke(e,t,...r){return xe(`Key for the ${e} algorithm must be `,t,...r)}var Me=e=>!!Ee(e)||"KeyObject"===e?.[Symbol.toStringTag];const je=["CryptoKey"];function $e(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let r=e;for(;null!==Object.getPrototypeOf(r);)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(e)===r}function Ue(e){return $e(e)&&"string"==typeof e.kty}const Le=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=function(e){let t,r;switch(e.kty){case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new Ie('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new Ie('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new Ie('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new Ie('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),n=[t,e.ext??!1,e.key_ops??r],o={...e};return delete o.alg,delete o.use,ve.subtle.importKey("jwk",o,...n)},He=e=>Oe(e);let We;const qe=e=>"KeyObject"===e?.[Symbol.toStringTag],Fe=async(e,t,r,n,o=!1)=>{let i=e.get(t);if(i?.[n])return i[n];const s=await Le({...r,alg:n});return o&&Object.freeze(t),i?i[n]=s:e.set(t,{[n]:s}),s};var Ve=(e,t)=>{if(qe(e)){let r=e.export({format:"jwk"});return r.k?He(r.k):(We||(We=new WeakMap),Fe(We,e,r,t))}if(Ue(e)){if(e.k)return Oe(e.k);We||(We=new WeakMap);return Fe(We,e,e,t,!0)}return e};const Be=(e,t,r=0)=>{0===r&&(t.unshift(t.length),t.unshift(6));const n=e.indexOf(t[0],r);if(-1===n)return!1;const o=e.subarray(n,n+t.length);return o.length===t.length&&(o.every((e,r)=>e===t[r])||Be(e,t,n+1))},Je=e=>{switch(!0){case Be(e,[42,134,72,206,61,3,1,7]):return"P-256";case Be(e,[43,129,4,0,34]):return"P-384";case Be(e,[43,129,4,0,35]):return"P-521";case Be(e,[43,101,110]):return"X25519";case Be(e,[43,101,111]):return"X448";case Be(e,[43,101,112]):return"Ed25519";case Be(e,[43,101,113]):return"Ed448";default:throw new Ie("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},Ge=(e,t,r)=>(async(e,t,r,n)=>{let o,i;const s=new Uint8Array(atob(r.replace(e,"")).split("").map(e=>e.charCodeAt(0)));switch(n){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},i=["sign"];break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},i=["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":o={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},i=["decrypt","unwrapKey"];break;case"ES256":o={name:"ECDSA",namedCurve:"P-256"},i=["sign"];break;case"ES384":o={name:"ECDSA",namedCurve:"P-384"},i=["sign"];break;case"ES512":o={name:"ECDSA",namedCurve:"P-521"},i=["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const e=Je(s);o=e.startsWith("P-")?{name:"ECDH",namedCurve:e}:{name:e},i=["deriveBits"];break}case"Ed25519":o={name:"Ed25519"},i=["sign"];break;case"EdDSA":o={name:Je(s)},i=["sign"];break;default:throw new Ie('Invalid or unsupported "alg" (Algorithm) value')}return ve.subtle.importKey(t,s,o,!1,i)})(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t);const ze=e=>e?.[Symbol.toStringTag],Ye=(e,t,r)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(r))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},Qe=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&Ue(t)){if(function(e){return Ue(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&Ye(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Me(t))throw new TypeError(Ke(e,t,...je,"Uint8Array",n?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${ze(t)} instances for symmetric algorithms must be of type "secret"`)}};function Xe(e,t,r,n){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Qe(t,r,n,e):((e,t,r,n)=>{if(n&&Ue(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&Ye(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&Ye(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Me(t))throw new TypeError(Ke(e,t,...je,n?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${ze(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${ze(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${ze(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${ze(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${ze(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,n,e)}Xe.bind(void 0,!1);const Ze=Xe.bind(void 0,!0);var et=e=>Math.floor(e.getTime()/1e3);const tt=86400,rt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;var nt=e=>{const t=rt.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]);let n;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(60*r);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(3600*r);break;case"day":case"days":case"d":n=Math.round(r*tt);break;case"week":case"weeks":case"w":n=Math.round(604800*r);break;default:n=Math.round(31557600*r)}return"-"===t[1]||"ago"===t[4]?-n:n};const ot=async(e,t,r)=>{const n=await async function(e,t,r){if(t=await Ve(t,e),Ee(t))return Ne(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(De(t,...je));return ve.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(De(t,...je,"Uint8Array","JSON Web Key"))}(e,t,"sign");((e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}})(e,n);const o=await ve.subtle.sign(function(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new Ie(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e,n.algorithm),n,r);return new Uint8Array(o)};class it{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new Se("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!((...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let r;for(const e of t){const t=Object.keys(e);if(r&&0!==r.size)for(const e of t){if(r.has(e))return!1;r.add(e)}else r=new Set(t)}return!0})(this._protectedHeader,this._unprotectedHeader))throw new Se("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader},n=function(e,t,r,n,o){if(void 0!==o.crit&&void 0===n?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;i=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of n.crit){if(!i.has(t))throw new Ie(`Extension Header Parameter "${t}" is not recognized`);if(void 0===o[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(i.get(t)&&void 0===n[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(n.crit)}(Se,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r);let o=!0;if(n.has("b64")&&(o=this._protectedHeader.b64,"boolean"!=typeof o))throw new Se('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:i}=r;if("string"!=typeof i||!i)throw new Se('JWS "alg" (Algorithm) Header Parameter missing or invalid');Ze(i,e,"sign");let s,a=this._payload;o&&(a=_e.encode(Re(a))),s=this._protectedHeader?_e.encode(Re(JSON.stringify(this._protectedHeader))):_e.encode("");const c=function(...e){const t=e.reduce((e,{length:t})=>e+t,0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}(s,_e.encode("."),a),l=await ot(i,e,c),u={signature:Re(l),payload:""};return o&&(u.payload=we.decode(a)),this._unprotectedHeader&&(u.header=this._unprotectedHeader),this._protectedHeader&&(u.protected=we.decode(s)),u}}class st{constructor(e){this._flattened=new it(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const r=await this._flattened.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}function at(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class ct{constructor(e={}){if(!$e(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:at("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:at("setNotBefore",et(e))}:this._payload={...this._payload,nbf:et(new Date)+nt(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:at("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:at("setExpirationTime",et(e))}:this._payload={...this._payload,exp:et(new Date)+nt(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:et(new Date)}:e instanceof Date?this._payload={...this._payload,iat:at("setIssuedAt",et(e))}:this._payload="string"==typeof e?{...this._payload,iat:at("setIssuedAt",et(new Date)+nt(e))}:{...this._payload,iat:at("setIssuedAt",e)},this}}class lt extends ct{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new st(_e.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new Te("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}function ut(e){const t={};if(!e)return{};if(function(e){if("object"==typeof e&&null!==e&&"entries"in Object(e)&&"function"==typeof Object(e).entries)return!0;return!1}(e)){for(const[r,n]of e.entries())t[r.toLowerCase()]=n;return t}for(const[r,n]of Object.entries(e))t[r.toLowerCase()]=n;return t}class ht{alg="RS256";grantType="client_credentials";clientAssertionType="urn:ietf:params:oauth:client-assertion-type:jwt-bearer";clientId;clientKey;keyId;scope;authServer;httpClient;maxRetries;clockSkewInSeconds=0;accessToken;tokenEmitter=new re;retryCount;pollerTimer;constructor(e){this.keyId=e.keyId,this.clientId=e.clientId,this.clientKey=e.clientKey,this.authServer=e.authServer??"https://oauth2.segment.io",this.scope=e.scope??"tracking_api:write",this.httpClient=e.httpClient,this.maxRetries=e.maxRetries,this.tokenEmitter.on("access_token",e=>{"token"in e&&(this.accessToken=e.token)}),this.retryCount=0}stopPoller(){clearTimeout(this.pollerTimer)}async pollerLoop(){let e,t=25;try{e=await this.requestAccessToken()}catch(e){return this.handleTransientError({error:e})}if(!(e=>"function"==typeof e.text)(e))return this.handleInvalidCustomResponse();const r=ut(e.headers);if(r.date&&this.updateClockSkew(Date.parse(r.date)),200!==e.status)return 429===e.status?await this.handleRateLimited(e,r,t):[400,401,415].includes(e.status)?this.handleUnrecoverableErrors(e):this.handleTransientError({error:new Error(`[${e.status}] ${e.statusText}`)});try{const r=await e.text(),o=JSON.parse(r);if(n=o,!Boolean(n&&"object"==typeof n&&"access_token"in n&&"expires_in"in n&&"string"==typeof n.access_token&&"number"==typeof n.expires_in))throw new Error("Response did not contain a valid access_token and expires_in");return o.expires_at=Math.round(Date.now()/1e3)+o.expires_in,this.tokenEmitter.emit("access_token",{token:o}),this.retryCount=0,t=o.expires_in/2*1e3,this.queueNextPoll(t)}catch(e){return this.handleTransientError({error:e,forceEmitError:!0})}var n}handleTransientError({error:e,forceEmitError:t}){this.incrementRetries({error:e,forceEmitError:t});const r=ne({attempt:this.retryCount,minTimeout:25,maxTimeout:1e3});this.queueNextPoll(r)}handleInvalidCustomResponse(){this.tokenEmitter.emit("access_token",{error:new Error("HTTPClient does not implement response.text method")})}async handleRateLimited(e,t,r){if(this.incrementRetries({error:new Error(`[${e.status}] ${e.statusText}`)}),t["x-ratelimit-reset"]){const e=parseInt(t["x-ratelimit-reset"],10);r=isFinite(e)?e-Date.now()+1e3*this.clockSkewInSeconds:5e3,await ee(r),r=0}this.queueNextPoll(r)}handleUnrecoverableErrors(e){this.retryCount=0,this.tokenEmitter.emit("access_token",{error:new Error(`[${e.status}] ${e.statusText}`)}),this.stopPoller()}updateClockSkew(e){this.clockSkewInSeconds=(Date.now()-e)/1e3}incrementRetries({error:e,forceEmitError:t}){this.retryCount++,(t||this.retryCount%this.maxRetries===0)&&(this.retryCount=0,this.tokenEmitter.emit("access_token",{error:e}))}queueNextPoll(e){this.pollerTimer=setTimeout(()=>this.pollerLoop(),e),this.pollerTimer.unref&&this.pollerTimer.unref()}async requestAccessToken(){const e=le(),t=Math.round(Date.now()/1e3)-this.clockSkewInSeconds,r={iss:this.clientId,sub:this.clientId,aud:this.authServer,iat:t-5,exp:t+55,jti:e},n=await async function(e,t){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Ge(e,t)}(this.clientKey,"RS256"),o=await new lt(r).setProtectedHeader({alg:this.alg,kid:this.keyId,typ:"JWT"}).sign(n),i=`grant_type=${this.grantType}&client_assertion_type=${this.clientAssertionType}&client_assertion=${o}&scope=${this.scope}`,s={method:"POST",url:`${this.authServer}/token`,body:i,headers:{"Content-Type":"application/x-www-form-urlencoded"},httpRequestTimeout:1e4};return this.httpClient.makeRequest(s)}async getAccessToken(){return this.isValidToken(this.accessToken)?this.accessToken:(this.stopPoller(),this.pollerLoop().catch(()=>{}),new Promise((e,t)=>{this.tokenEmitter.once("access_token",r=>{"token"in r?e(r.token):t(r.error)})}))}clearToken(){this.accessToken=void 0}isValidToken(e){return null!=e&&e.expires_in<Date.now()/1e3}}function dt(e){return new Promise(t=>setTimeout(t,e))}function pt(){}class ft{pendingFlushTimeout;_batch;_flushInterval;_flushAt;_maxRetries;_url;_flushPendingItemsCount;_httpRequestTimeout;_emitter;_disable;_httpClient;_writeKey;_tokenManager;constructor({host:e,path:t,maxRetries:r,flushAt:n,flushInterval:o,writeKey:i,httpRequestTimeout:s,httpClient:a,disable:c,oauthSettings:l},u){this._emitter=u,this._maxRetries=r,this._flushAt=Math.max(n,1),this._flushInterval=o,this._url=((e,t)=>new URL(t||"",e).href.replace(/\/$/,""))(e??"https://api.segment.io",t??"/v1/batch"),this._httpRequestTimeout=s??1e4,this._disable=Boolean(c),this._httpClient=a,this._writeKey=i,l&&(this._tokenManager=new ht({...l,httpClient:l.httpClient??a,maxRetries:l.maxRetries??r}))}createBatch(){this.pendingFlushTimeout&&clearTimeout(this.pendingFlushTimeout);const e=new be(this._flushAt);return this._batch=e,this.pendingFlushTimeout=setTimeout(()=>{e===this._batch&&(this._batch=void 0),this.pendingFlushTimeout=void 0,e.length&&this.send(e).catch(pt)},this._flushInterval),e}clearBatch(){this.pendingFlushTimeout&&clearTimeout(this.pendingFlushTimeout),this._batch=void 0}flush(e){if(!e)return void(this._tokenManager&&this._tokenManager.stopPoller());if(this._flushPendingItemsCount=e,!this._batch)return;this._batch.length===e&&(this.send(this._batch).catch(pt).finally(()=>{this._tokenManager&&this._tokenManager.stopPoller()}),this.clearBatch())}enqueue(e){const t=this._batch??this.createBatch(),{promise:r,resolve:n}=function(){var e,t,r=!1,n=new Promise(function(n,o){e=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];r=!0,n.apply(void 0,e)},t=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];r=!0,o.apply(void 0,e)}});return{resolve:e,reject:t,promise:n,isSettled:function(){return r}}}(),o={context:e,resolver:n};if(t.tryAdd(o).success){const e=t.length===this._flushPendingItemsCount;return(t.length===this._flushAt||e)&&(this.send(t).catch(pt),this.clearBatch()),r}t.length&&(this.send(t).catch(pt),this.clearBatch());const i=this.createBatch(),s=i.tryAdd(o);if(s.success){return i.length===this._flushPendingItemsCount&&(this.send(i).catch(pt),this.clearBatch()),r}return e.setFailedDelivery({reason:new Error(s.message)}),Promise.resolve(e)}async send(e){this._flushPendingItemsCount&&(this._flushPendingItemsCount-=e.length);const t=e.getEvents(),r=this._maxRetries+1;let n=0;for(;n<r;){let o,i;n++;try{if(this._disable)return e.resolveEvents();let r;if(this._tokenManager){const e=await this._tokenManager.getAccessToken();e&&e.access_token&&(r=`Bearer ${e.access_token}`)}const n={"Content-Type":"application/json","User-Agent":"analytics-node-next/latest",...r?{Authorization:r}:{}},s={url:this._url,method:"POST",headers:n,body:JSON.stringify({batch:t,writeKey:this._writeKey,sentAt:new Date}),httpRequestTimeout:this._httpRequestTimeout};this._emitter.emit("http_request",{body:s.body,method:s.method,url:s.url,headers:s.headers});const a=await this._httpClient.makeRequest(s);if(a.status>=200&&a.status<300)return void e.resolveEvents();if(!this._tokenManager||400!==a.status&&401!==a.status&&403!==a.status){if(400===a.status)return void gt(e,new Error(`[${a.status}] ${a.statusText}`));if(429===a.status){if(a.headers&&"x-ratelimit-reset"in a.headers){const e=parseInt(a.headers["x-ratelimit-reset"],10);isFinite(e)&&(o=e-Date.now())}i=new Error(`[${a.status}] ${a.statusText}`)}else i=new Error(`[${a.status}] ${a.statusText}`)}else this._tokenManager.clearToken(),i=new Error(`[${a.status}] ${a.statusText}`)}catch(e){i=e}if(n===r)return void gt(e,i);await dt(o||ne({attempt:n,minTimeout:25,maxTimeout:1e3}))}}}function gt(e,t){e.getContexts().forEach(e=>e.setFailedDelivery({reason:t})),e.resolveEvents()}const mt=()=>"object"==typeof process&&process&&"object"==typeof process.env&&process.env&&"string"==typeof process.version?"node":"object"==typeof window?"browser":"undefined"!=typeof WebSocketPair?"cloudflare-worker":"string"==typeof EdgeRuntime?"vercel-edge":"undefined"!=typeof WorkerGlobalScope&&"function"==typeof importScripts?"web-worker":"unknown";function yt(e){function t(t){return function(e){e.updateEvent("context.library.name","@segment/analytics-node"),e.updateEvent("context.library.version",ye);const t=mt();"node"===t&&e.updateEvent("_metadata.nodeVersion",process.version),e.updateEvent("_metadata.jsRuntime",t)}(t),e.enqueue(t)}return{name:"Segment.io",type:"destination",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),alias:t,group:t,identify:t,page:t,screen:t,track:t}}const bt=()=>`node-next-${Date.now()}-${le()}`;class vt extends X{constructor(){super({createMessageId:bt,onFinishedEvent:e=>{!function(e){var t=".userId/anonymousId/previousId/groupId",r=function(e){var t,r,n;return null!==(n=null!==(r=null!==(t=e.userId)&&void 0!==t?t:e.anonymousId)&&void 0!==r?r:e.groupId)&&void 0!==n?n:e.previousId}(e);if(!V(r))throw new q(t,z);if(!F(r))throw new q(t,J)}(e)}})}}class Et extends pe{static system(){return new this({type:"track",event:"system"})}}const _t=async(e,t,r,n)=>{try{const i=new Et(e),s=await function(e,t,r,n){return U(this,void 0,void 0,function(){var o,i;return L(this,function(s){switch(s.label){case 0:return r.emit("dispatch_start",e),o=Date.now(),t.isEmpty()?[4,t.dispatchSingle(e)]:[3,2];case 1:return i=s.sent(),[3,4];case 2:return[4,t.dispatch(e)];case 3:i=s.sent(),s.label=4;case 4:return(null==n?void 0:n.callback)?[4,te(i,n.callback,(a=o,c=n.timeout,l=Date.now()-a,Math.max((null!=c?c:300)-l,0)))]:[3,6];case 5:i=s.sent(),s.label=6;case 6:return(null==n?void 0:n.debug)&&i.flush(),[2,i]}var a,c,l})})}(i,t,r,{...n?{callback:(o=n,e=>{const t=e.failedDelivery();return o(t?t.reason:void 0,e)})}:{}}),a=s.failedDelivery();a?r.emit("error",{code:"delivery_failure",reason:a.reason,ctx:s}):r.emit(e.type,s)}catch(e){r.emit("error",{code:"unknown",reason:e})}var o};class wt extends re{}class Rt extends se{constructor(){super(1,[])}getAttempts(e){return e.attempts??0}updateAttempts(e){return e.attempts=this.getAttempts(e)+1,this.getAttempts(e)}}class Ot extends me{constructor(){super(new Rt)}}class Ct{onabort=null;aborted=!1;eventEmitter=new re;toString(){return"[object AbortSignal]"}get[Symbol.toStringTag](){return"AbortSignal"}removeEventListener(...e){this.eventEmitter.off(...e)}addEventListener(...e){this.eventEmitter.on(...e)}dispatchEvent(e){const t={type:e,target:this},r=`on${e}`;"function"==typeof this[r]&&this[r](t),this.eventEmitter.emit(e,t)}}let It=class{signal=new Ct;abort(){this.signal.aborted||(this.signal.aborted=!0,this.signal.dispatchEvent("abort"))}toString(){return"[object AbortController]"}get[Symbol.toStringTag](){return"AbortController"}};const St=async(...e)=>{if(globalThis.fetch)return globalThis.fetch(...e);if("string"!=typeof EdgeRuntime)return(await Promise.resolve().then(function(){return lr})).default(...e);throw new Error("Invariant: an edge runtime that does not support fetch should not exist")};class Tt{_fetch;constructor(e){this._fetch=e??St}async makeRequest(e){const[t,r]=(e=>{if("cloudflare-worker"===mt())return[];const t=new(globalThis.AbortController||It),r=setTimeout(()=>{t.abort()},e);return r?.unref?.(),[t.signal,r]})(e.httpRequestTimeout),n={url:e.url,method:e.method,headers:e.headers,body:e.body,signal:t};return this._fetch(e.url,n).finally(()=>clearTimeout(r))}}class At extends wt{_eventFactory;_isClosed=!1;_pendingEvents=0;_closeAndFlushDefaultTimeout;_publisher;_isFlushing=!1;_queue;ready;constructor(e){super(),(e=>{if(!e.writeKey)throw new q("writeKey","writeKey is missing.")})(e),this._eventFactory=new vt,this._queue=new Ot;const t=e.flushInterval??1e4;this._closeAndFlushDefaultTimeout=1.25*t;const{plugin:r,publisher:n}=((e,t)=>{const r=new ft(e,t);return{publisher:r,plugin:yt(r)}})({writeKey:e.writeKey,host:e.host,path:e.path,maxRetries:e.maxRetries??3,flushAt:e.flushAt??e.maxEventsInBatch??15,httpRequestTimeout:e.httpRequestTimeout,disable:e.disable,flushInterval:t,httpClient:"function"==typeof e.httpClient?new Tt(e.httpClient):e.httpClient??new Tt,oauthSettings:e.oauthSettings},this);this._publisher=n,this.ready=this.register(r).then(()=>{}),this.emit("initialize",e),function(e){for(var t=e.constructor.prototype,r=0,n=Object.getOwnPropertyNames(t);r<n.length;r++){var o=n[r];if("constructor"!==o){var i=Object.getOwnPropertyDescriptor(e.constructor.prototype,o);i&&"function"==typeof i.value&&(e[o]=e[o].bind(e))}}}(this)}get VERSION(){return ye}closeAndFlush({timeout:e=this._closeAndFlushDefaultTimeout}={}){return this.flush({timeout:e,close:!0})}async flush({timeout:e,close:t=!1}={}){if(this._isFlushing)return void console.warn("Overlapping flush calls detected. Please wait for the previous flush to finish before calling .flush again");this._isFlushing=!0,t&&(this._isClosed=!0),this._publisher.flush(this._pendingEvents);const r=new Promise(e=>{this._pendingEvents?this.once("drained",()=>{e()}):e()}).finally(()=>{this._isFlushing=!1});return e?Z(r,e).catch(()=>{}):r}_dispatch(e,t){this._isClosed?this.emit("call_after_close",e):(this._pendingEvents++,_t(e,this._queue,this,t).catch(e=>e).finally(()=>{this._pendingEvents--,this._pendingEvents||this.emit("drained")}))}alias({userId:e,previousId:t,context:r,timestamp:n,integrations:o,messageId:i},s){const a=this._eventFactory.alias(e,t,{context:r,integrations:o,timestamp:n,messageId:i});this._dispatch(a,s)}group({timestamp:e,groupId:t,userId:r,anonymousId:n,traits:o={},context:i,integrations:s,messageId:a},c){const l=this._eventFactory.group(t,o,{context:i,anonymousId:n,userId:r,timestamp:e,integrations:s,messageId:a});this._dispatch(l,c)}identify({userId:e,anonymousId:t,traits:r={},context:n,timestamp:o,integrations:i,messageId:s},a){const c=this._eventFactory.identify(e,r,{context:n,anonymousId:t,userId:e,timestamp:o,integrations:i,messageId:s});this._dispatch(c,a)}page({userId:e,anonymousId:t,category:r,name:n,properties:o,context:i,timestamp:s,integrations:a,messageId:c},l){const u=this._eventFactory.page(r??null,n??null,o,{context:i,anonymousId:t,userId:e,timestamp:s,integrations:a,messageId:c});this._dispatch(u,l)}screen({userId:e,anonymousId:t,category:r,name:n,properties:o,context:i,timestamp:s,integrations:a,messageId:c},l){const u=this._eventFactory.screen(r??null,n??null,o,{context:i,anonymousId:t,userId:e,timestamp:s,integrations:a,messageId:c});this._dispatch(u,l)}track({userId:e,anonymousId:t,event:r,properties:n,context:o,timestamp:i,integrations:s,messageId:a},c){const l=this._eventFactory.track(r,n,{context:o,userId:e,anonymousId:t,timestamp:i,integrations:s,messageId:a});this._dispatch(l,c)}register(...e){return this._queue.criticalTasks.run(async()=>{const t=Et.system(),r=e.map(e=>this._queue.register(t,e,this));await Promise.all(r),this.emit("register",e.map(e=>e.name))})}async deregister(...e){const t=Et.system(),r=e.map(e=>{const r=this._queue.plugins.find(t=>t.name===e);if(r)return this._queue.deregister(t,r,this);t.log("warn",`plugin ${e} not found`)});await Promise.all(r),this.emit("deregister",e)}}var kt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Pt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Nt,xt,Dt,Kt,Mt,jt,$t,Ut,Lt,Ht,Wt,qt,Ft,Vt,Bt,Jt,Gt,zt={exports:{}};function Yt(){if(Kt)return Dt;Kt=1;const e=xt?Nt:(xt=1,Nt={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}),t={};for(const r of Object.keys(e))t[e[r]]=r;const r={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};Dt=r;for(const e of Object.keys(r)){if(!("channels"in r[e]))throw new Error("missing channels property: "+e);if(!("labels"in r[e]))throw new Error("missing channel labels property: "+e);if(r[e].labels.length!==r[e].channels)throw new Error("channel and label counts mismatch: "+e);const{channels:t,labels:n}=r[e];delete r[e].channels,delete r[e].labels,Object.defineProperty(r[e],"channels",{value:t}),Object.defineProperty(r[e],"labels",{value:n})}function n(e,t){return(e[0]-t[0])**2+(e[1]-t[1])**2+(e[2]-t[2])**2}return r.rgb.hsl=function(e){const t=e[0]/255,r=e[1]/255,n=e[2]/255,o=Math.min(t,r,n),i=Math.max(t,r,n),s=i-o;let a,c;i===o?a=0:t===i?a=(r-n)/s:r===i?a=2+(n-t)/s:n===i&&(a=4+(t-r)/s),a=Math.min(60*a,360),a<0&&(a+=360);const l=(o+i)/2;return c=i===o?0:l<=.5?s/(i+o):s/(2-i-o),[a,100*c,100*l]},r.rgb.hsv=function(e){let t,r,n,o,i;const s=e[0]/255,a=e[1]/255,c=e[2]/255,l=Math.max(s,a,c),u=l-Math.min(s,a,c),h=function(e){return(l-e)/6/u+.5};return 0===u?(o=0,i=0):(i=u/l,t=h(s),r=h(a),n=h(c),s===l?o=n-r:a===l?o=1/3+t-n:c===l&&(o=2/3+r-t),o<0?o+=1:o>1&&(o-=1)),[360*o,100*i,100*l]},r.rgb.hwb=function(e){const t=e[0],n=e[1];let o=e[2];const i=r.rgb.hsl(e)[0],s=1/255*Math.min(t,Math.min(n,o));return o=1-1/255*Math.max(t,Math.max(n,o)),[i,100*s,100*o]},r.rgb.cmyk=function(e){const t=e[0]/255,r=e[1]/255,n=e[2]/255,o=Math.min(1-t,1-r,1-n);return[100*((1-t-o)/(1-o)||0),100*((1-r-o)/(1-o)||0),100*((1-n-o)/(1-o)||0),100*o]},r.rgb.keyword=function(r){const o=t[r];if(o)return o;let i,s=1/0;for(const t of Object.keys(e)){const o=n(r,e[t]);o<s&&(s=o,i=t)}return i},r.keyword.rgb=function(t){return e[t]},r.rgb.xyz=function(e){let t=e[0]/255,r=e[1]/255,n=e[2]/255;t=t>.04045?((t+.055)/1.055)**2.4:t/12.92,r=r>.04045?((r+.055)/1.055)**2.4:r/12.92,n=n>.04045?((n+.055)/1.055)**2.4:n/12.92;return[100*(.4124*t+.3576*r+.1805*n),100*(.2126*t+.7152*r+.0722*n),100*(.0193*t+.1192*r+.9505*n)]},r.rgb.lab=function(e){const t=r.rgb.xyz(e);let n=t[0],o=t[1],i=t[2];n/=95.047,o/=100,i/=108.883,n=n>.008856?n**(1/3):7.787*n+16/116,o=o>.008856?o**(1/3):7.787*o+16/116,i=i>.008856?i**(1/3):7.787*i+16/116;return[116*o-16,500*(n-o),200*(o-i)]},r.hsl.rgb=function(e){const t=e[0]/360,r=e[1]/100,n=e[2]/100;let o,i,s;if(0===r)return s=255*n,[s,s,s];o=n<.5?n*(1+r):n+r-n*r;const a=2*n-o,c=[0,0,0];for(let e=0;e<3;e++)i=t+1/3*-(e-1),i<0&&i++,i>1&&i--,s=6*i<1?a+6*(o-a)*i:2*i<1?o:3*i<2?a+(o-a)*(2/3-i)*6:a,c[e]=255*s;return c},r.hsl.hsv=function(e){const t=e[0];let r=e[1]/100,n=e[2]/100,o=r;const i=Math.max(n,.01);n*=2,r*=n<=1?n:2-n,o*=i<=1?i:2-i;return[t,100*(0===n?2*o/(i+o):2*r/(n+r)),100*((n+r)/2)]},r.hsv.rgb=function(e){const t=e[0]/60,r=e[1]/100;let n=e[2]/100;const o=Math.floor(t)%6,i=t-Math.floor(t),s=255*n*(1-r),a=255*n*(1-r*i),c=255*n*(1-r*(1-i));switch(n*=255,o){case 0:return[n,c,s];case 1:return[a,n,s];case 2:return[s,n,c];case 3:return[s,a,n];case 4:return[c,s,n];case 5:return[n,s,a]}},r.hsv.hsl=function(e){const t=e[0],r=e[1]/100,n=e[2]/100,o=Math.max(n,.01);let i,s;s=(2-r)*n;const a=(2-r)*o;return i=r*o,i/=a<=1?a:2-a,i=i||0,s/=2,[t,100*i,100*s]},r.hwb.rgb=function(e){const t=e[0]/360;let r=e[1]/100,n=e[2]/100;const o=r+n;let i;o>1&&(r/=o,n/=o);const s=Math.floor(6*t),a=1-n;i=6*t-s,1&s&&(i=1-i);const c=r+i*(a-r);let l,u,h;switch(s){default:case 6:case 0:l=a,u=c,h=r;break;case 1:l=c,u=a,h=r;break;case 2:l=r,u=a,h=c;break;case 3:l=r,u=c,h=a;break;case 4:l=c,u=r,h=a;break;case 5:l=a,u=r,h=c}return[255*l,255*u,255*h]},r.cmyk.rgb=function(e){const t=e[0]/100,r=e[1]/100,n=e[2]/100,o=e[3]/100;return[255*(1-Math.min(1,t*(1-o)+o)),255*(1-Math.min(1,r*(1-o)+o)),255*(1-Math.min(1,n*(1-o)+o))]},r.xyz.rgb=function(e){const t=e[0]/100,r=e[1]/100,n=e[2]/100;let o,i,s;return o=3.2406*t+-1.5372*r+-.4986*n,i=-.9689*t+1.8758*r+.0415*n,s=.0557*t+-.204*r+1.057*n,o=o>.0031308?1.055*o**(1/2.4)-.055:12.92*o,i=i>.0031308?1.055*i**(1/2.4)-.055:12.92*i,s=s>.0031308?1.055*s**(1/2.4)-.055:12.92*s,o=Math.min(Math.max(0,o),1),i=Math.min(Math.max(0,i),1),s=Math.min(Math.max(0,s),1),[255*o,255*i,255*s]},r.xyz.lab=function(e){let t=e[0],r=e[1],n=e[2];t/=95.047,r/=100,n/=108.883,t=t>.008856?t**(1/3):7.787*t+16/116,r=r>.008856?r**(1/3):7.787*r+16/116,n=n>.008856?n**(1/3):7.787*n+16/116;return[116*r-16,500*(t-r),200*(r-n)]},r.lab.xyz=function(e){let t,r,n;r=(e[0]+16)/116,t=e[1]/500+r,n=r-e[2]/200;const o=r**3,i=t**3,s=n**3;return r=o>.008856?o:(r-16/116)/7.787,t=i>.008856?i:(t-16/116)/7.787,n=s>.008856?s:(n-16/116)/7.787,t*=95.047,r*=100,n*=108.883,[t,r,n]},r.lab.lch=function(e){const t=e[0],r=e[1],n=e[2];let o;o=360*Math.atan2(n,r)/2/Math.PI,o<0&&(o+=360);return[t,Math.sqrt(r*r+n*n),o]},r.lch.lab=function(e){const t=e[0],r=e[1],n=e[2]/360*2*Math.PI;return[t,r*Math.cos(n),r*Math.sin(n)]},r.rgb.ansi16=function(e,t=null){const[n,o,i]=e;let s=null===t?r.rgb.hsv(e)[2]:t;if(s=Math.round(s/50),0===s)return 30;let a=30+(Math.round(i/255)<<2|Math.round(o/255)<<1|Math.round(n/255));return 2===s&&(a+=60),a},r.hsv.ansi16=function(e){return r.rgb.ansi16(r.hsv.rgb(e),e[2])},r.rgb.ansi256=function(e){const t=e[0],r=e[1],n=e[2];if(t===r&&r===n)return t<8?16:t>248?231:Math.round((t-8)/247*24)+232;return 16+36*Math.round(t/255*5)+6*Math.round(r/255*5)+Math.round(n/255*5)},r.ansi16.rgb=function(e){let t=e%10;if(0===t||7===t)return e>50&&(t+=3.5),t=t/10.5*255,[t,t,t];const r=.5*(1+~~(e>50));return[(1&t)*r*255,(t>>1&1)*r*255,(t>>2&1)*r*255]},r.ansi256.rgb=function(e){if(e>=232){const t=10*(e-232)+8;return[t,t,t]}let t;e-=16;return[Math.floor(e/36)/5*255,Math.floor((t=e%36)/6)/5*255,t%6/5*255]},r.rgb.hex=function(e){const t=(((255&Math.round(e[0]))<<16)+((255&Math.round(e[1]))<<8)+(255&Math.round(e[2]))).toString(16).toUpperCase();return"000000".substring(t.length)+t},r.hex.rgb=function(e){const t=e.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!t)return[0,0,0];let r=t[0];3===t[0].length&&(r=r.split("").map(e=>e+e).join(""));const n=parseInt(r,16);return[n>>16&255,n>>8&255,255&n]},r.rgb.hcg=function(e){const t=e[0]/255,r=e[1]/255,n=e[2]/255,o=Math.max(Math.max(t,r),n),i=Math.min(Math.min(t,r),n),s=o-i;let a,c;return a=s<1?i/(1-s):0,c=s<=0?0:o===t?(r-n)/s%6:o===r?2+(n-t)/s:4+(t-r)/s,c/=6,c%=1,[360*c,100*s,100*a]},r.hsl.hcg=function(e){const t=e[1]/100,r=e[2]/100,n=r<.5?2*t*r:2*t*(1-r);let o=0;return n<1&&(o=(r-.5*n)/(1-n)),[e[0],100*n,100*o]},r.hsv.hcg=function(e){const t=e[1]/100,r=e[2]/100,n=t*r;let o=0;return n<1&&(o=(r-n)/(1-n)),[e[0],100*n,100*o]},r.hcg.rgb=function(e){const t=e[0]/360,r=e[1]/100,n=e[2]/100;if(0===r)return[255*n,255*n,255*n];const o=[0,0,0],i=t%1*6,s=i%1,a=1-s;let c=0;switch(Math.floor(i)){case 0:o[0]=1,o[1]=s,o[2]=0;break;case 1:o[0]=a,o[1]=1,o[2]=0;break;case 2:o[0]=0,o[1]=1,o[2]=s;break;case 3:o[0]=0,o[1]=a,o[2]=1;break;case 4:o[0]=s,o[1]=0,o[2]=1;break;default:o[0]=1,o[1]=0,o[2]=a}return c=(1-r)*n,[255*(r*o[0]+c),255*(r*o[1]+c),255*(r*o[2]+c)]},r.hcg.hsv=function(e){const t=e[1]/100,r=t+e[2]/100*(1-t);let n=0;return r>0&&(n=t/r),[e[0],100*n,100*r]},r.hcg.hsl=function(e){const t=e[1]/100,r=e[2]/100*(1-t)+.5*t;let n=0;return r>0&&r<.5?n=t/(2*r):r>=.5&&r<1&&(n=t/(2*(1-r))),[e[0],100*n,100*r]},r.hcg.hwb=function(e){const t=e[1]/100,r=t+e[2]/100*(1-t);return[e[0],100*(r-t),100*(1-r)]},r.hwb.hcg=function(e){const t=e[1]/100,r=1-e[2]/100,n=r-t;let o=0;return n<1&&(o=(r-n)/(1-n)),[e[0],100*n,100*o]},r.apple.rgb=function(e){return[e[0]/65535*255,e[1]/65535*255,e[2]/65535*255]},r.rgb.apple=function(e){return[e[0]/255*65535,e[1]/255*65535,e[2]/255*65535]},r.gray.rgb=function(e){return[e[0]/100*255,e[0]/100*255,e[0]/100*255]},r.gray.hsl=function(e){return[0,0,e[0]]},r.gray.hsv=r.gray.hsl,r.gray.hwb=function(e){return[0,100,e[0]]},r.gray.cmyk=function(e){return[0,0,0,e[0]]},r.gray.lab=function(e){return[e[0],0,0]},r.gray.hex=function(e){const t=255&Math.round(e[0]/100*255),r=((t<<16)+(t<<8)+t).toString(16).toUpperCase();return"000000".substring(r.length)+r},r.rgb.gray=function(e){return[(e[0]+e[1]+e[2])/3/255*100]},Dt}function Qt(){if(jt)return Mt;jt=1;const e=Yt();function t(t){const r=function(){const t={},r=Object.keys(e);for(let e=r.length,n=0;n<e;n++)t[r[n]]={distance:-1,parent:null};return t}(),n=[t];for(r[t].distance=0;n.length;){const t=n.pop(),o=Object.keys(e[t]);for(let e=o.length,i=0;i<e;i++){const e=o[i],s=r[e];-1===s.distance&&(s.distance=r[t].distance+1,s.parent=t,n.unshift(e))}}return r}function r(e,t){return function(r){return t(e(r))}}function n(t,n){const o=[n[t].parent,t];let i=e[n[t].parent][t],s=n[t].parent;for(;n[s].parent;)o.unshift(n[s].parent),i=r(e[n[s].parent][s],i),s=n[s].parent;return i.conversion=o,i}return Mt=function(e){const r=t(e),o={},i=Object.keys(r);for(let e=i.length,t=0;t<e;t++){const e=i[t];null!==r[e].parent&&(o[e]=n(e,r))}return o}}function Xt(){if(Ut)return $t;Ut=1;const e=Yt(),t=Qt(),r={};return Object.keys(e).forEach(n=>{r[n]={},Object.defineProperty(r[n],"channels",{value:e[n].channels}),Object.defineProperty(r[n],"labels",{value:e[n].labels});const o=t(n);Object.keys(o).forEach(e=>{const t=o[e];r[n][e]=function(e){const t=function(...t){const r=t[0];if(null==r)return r;r.length>1&&(t=r);const n=e(t);if("object"==typeof n)for(let e=n.length,t=0;t<e;t++)n[t]=Math.round(n[t]);return n};return"conversion"in e&&(t.conversion=e.conversion),t}(t),r[n][e].raw=function(e){const t=function(...t){const r=t[0];return null==r?r:(r.length>1&&(t=r),e(t))};return"conversion"in e&&(t.conversion=e.conversion),t}(t)})}),$t=r}function Zt(){return Lt||(Lt=1,function(e){const t=(e,t)=>(...r)=>`[${e(...r)+t}m`,r=(e,t)=>(...r)=>{const n=e(...r);return`[${38+t};5;${n}m`},n=(e,t)=>(...r)=>{const n=e(...r);return`[${38+t};2;${n[0]};${n[1]};${n[2]}m`},o=e=>e,i=(e,t,r)=>[e,t,r],s=(e,t,r)=>{Object.defineProperty(e,t,{get:()=>{const n=r();return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0}),n},enumerable:!0,configurable:!0})};let a;const c=(e,t,r,n)=>{void 0===a&&(a=Xt());const o=n?10:0,i={};for(const[n,s]of Object.entries(a)){const a="ansi16"===n?"ansi":n;n===t?i[a]=e(r,o):"object"==typeof s&&(i[a]=e(s[t],o))}return i};Object.defineProperty(e,"exports",{enumerable:!0,get:function(){const e=new Map,a={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};a.color.gray=a.color.blackBright,a.bgColor.bgGray=a.bgColor.bgBlackBright,a.color.grey=a.color.blackBright,a.bgColor.bgGrey=a.bgColor.bgBlackBright;for(const[t,r]of Object.entries(a)){for(const[t,n]of Object.entries(r))a[t]={open:`[${n[0]}m`,close:`[${n[1]}m`},r[t]=a[t],e.set(n[0],n[1]);Object.defineProperty(a,t,{value:r,enumerable:!1})}return Object.defineProperty(a,"codes",{value:e,enumerable:!1}),a.color.close="",a.bgColor.close="",s(a.color,"ansi",()=>c(t,"ansi16",o,!1)),s(a.color,"ansi256",()=>c(r,"ansi256",o,!1)),s(a.color,"ansi16m",()=>c(n,"rgb",i,!1)),s(a.bgColor,"ansi",()=>c(t,"ansi16",o,!0)),s(a.bgColor,"ansi256",()=>c(r,"ansi256",o,!0)),s(a.bgColor,"ansi16m",()=>c(n,"rgb",i,!0)),a}})}(zt)),zt.exports}function er(e,t="",r={}){for(let n in e){const o=t?`${t}.${n}`:n;"object"==typeof e[n]&&null!==e[n]?er(e[n],o,r):r[o]=e[n]}return r}!function(){if(Gt)return Jt;Gt=1;const e=Zt(),{stdout:t,stderr:r}=Wt?Ht:(Wt=1,Ht={stdout:!1,stderr:!1}),{stringReplaceAll:n,stringEncaseCRLFWithFirstIndex:o}=Ft?qt:(Ft=1,qt={stringReplaceAll:(e,t,r)=>{let n=e.indexOf(t);if(-1===n)return e;const o=t.length;let i=0,s="";do{s+=e.substr(i,n-i)+t+r,i=n+o,n=e.indexOf(t,i)}while(-1!==n);return s+=e.substr(i),s},stringEncaseCRLFWithFirstIndex:(e,t,r,n)=>{let o=0,i="";do{const s="\r"===e[n-1];i+=e.substr(o,(s?n-1:n)-o)+t+(s?"\r\n":"\n")+r,o=n+1,n=e.indexOf("\n",o)}while(-1!==n);return i+=e.substr(o),i}}),{isArray:i}=Array,s=["ansi","ansi","ansi256","ansi16m"],a=Object.create(null);class c{constructor(e){return l(e)}}const l=e=>{const r={};return((e,r={})=>{if(r.level&&!(Number.isInteger(r.level)&&r.level>=0&&r.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const n=t?t.level:0;e.level=void 0===r.level?n:r.level})(r,e),r.template=(...e)=>y(r.template,...e),Object.setPrototypeOf(r,u.prototype),Object.setPrototypeOf(r.template,r),r.template.constructor=()=>{throw new Error("`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.")},r.template.Instance=c,r.template};function u(e){return l(e)}for(const[t,r]of Object.entries(e))a[t]={get(){const e=f(this,p(r.open,r.close,this._styler),this._isEmpty);return Object.defineProperty(this,t,{value:e}),e}};a.visible={get(){const e=f(this,this._styler,!0);return Object.defineProperty(this,"visible",{value:e}),e}};const h=["rgb","hex","keyword","hsl","hsv","hwb","ansi","ansi256"];for(const t of h)a[t]={get(){const{level:r}=this;return function(...n){const o=p(e.color[s[r]][t](...n),e.color.close,this._styler);return f(this,o,this._isEmpty)}}};for(const t of h){a["bg"+t[0].toUpperCase()+t.slice(1)]={get(){const{level:r}=this;return function(...n){const o=p(e.bgColor[s[r]][t](...n),e.bgColor.close,this._styler);return f(this,o,this._isEmpty)}}}}const d=Object.defineProperties(()=>{},{...a,level:{enumerable:!0,get(){return this._generator.level},set(e){this._generator.level=e}}}),p=(e,t,r)=>{let n,o;return void 0===r?(n=e,o=t):(n=r.openAll+e,o=t+r.closeAll),{open:e,close:t,openAll:n,closeAll:o,parent:r}},f=(e,t,r)=>{const n=(...e)=>i(e[0])&&i(e[0].raw)?g(n,y(n,...e)):g(n,1===e.length?""+e[0]:e.join(" "));return Object.setPrototypeOf(n,d),n._generator=e,n._styler=t,n._isEmpty=r,n},g=(e,t)=>{if(e.level<=0||!t)return e._isEmpty?"":t;let r=e._styler;if(void 0===r)return t;const{openAll:i,closeAll:s}=r;if(-1!==t.indexOf(""))for(;void 0!==r;)t=n(t,r.close,r.open),r=r.parent;const a=t.indexOf("\n");return-1!==a&&(t=o(t,s,i,a)),i+t+s};let m;const y=(e,...t)=>{const[r]=t;if(!i(r)||!i(r.raw))return t.join(" ");const n=t.slice(1),o=[r.raw[0]];for(let e=1;e<r.length;e++)o.push(String(n[e-1]).replace(/[{}\\]/g,"\\$&"),String(r.raw[e]));return void 0===m&&(m=function(){if(Bt)return Vt;Bt=1;const e=/(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi,t=/(?:^|\.)(\w+)(?:\(([^)]*)\))?/g,r=/^(['"])((?:\\.|(?!\1)[^\\])*)\1$/,n=/\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi,o=new Map([["n","\n"],["r","\r"],["t","\t"],["b","\b"],["f","\f"],["v","\v"],["0","\0"],["\\","\\"],["e",""],["a",""]]);function i(e){const t="u"===e[0],r="{"===e[1];return t&&!r&&5===e.length||"x"===e[0]&&3===e.length?String.fromCharCode(parseInt(e.slice(1),16)):t&&r?String.fromCodePoint(parseInt(e.slice(2,-1),16)):o.get(e)||e}function s(e,t){const o=[],s=t.trim().split(/\s*,\s*/g);let a;for(const t of s){const s=Number(t);if(Number.isNaN(s)){if(!(a=t.match(r)))throw new Error(`Invalid Chalk template style argument: ${t} (in style '${e}')`);o.push(a[2].replace(n,(e,t,r)=>t?i(t):r))}else o.push(s)}return o}function a(e){t.lastIndex=0;const r=[];let n;for(;null!==(n=t.exec(e));){const e=n[1];if(n[2]){const t=s(e,n[2]);r.push([e].concat(t))}else r.push([e])}return r}function c(e,t){const r={};for(const e of t)for(const t of e.styles)r[t[0]]=e.inverse?null:t.slice(1);let n=e;for(const[e,t]of Object.entries(r))if(Array.isArray(t)){if(!(e in n))throw new Error(`Unknown Chalk style: ${e}`);n=t.length>0?n[e](...t):n[e]}return n}return Vt=(t,r)=>{const n=[],o=[];let s=[];if(r.replace(e,(e,r,l,u,h,d)=>{if(r)s.push(i(r));else if(u){const e=s.join("");s=[],o.push(0===n.length?e:c(t,n)(e)),n.push({inverse:l,styles:a(u)})}else if(h){if(0===n.length)throw new Error("Found extraneous } in Chalk template literal");o.push(c(t,n)(s.join(""))),s=[],n.pop()}else s.push(d)}),o.push(s.join("")),n.length>0){const e=`Chalk template literal is missing ${n.length} closing bracket${1===n.length?"":"s"} (\`}\`)`;throw new Error(e)}return o.join("")}}()),m(e,o.join(""))};Object.defineProperties(u.prototype,a);const b=u();b.supportsColor=t,b.stderr=u({level:r?r.level:0}),b.stderr.supportsColor=r,Jt=b}();var tr="1.51.3";const rr=`https://copilotkit.gateway.scarf.sh/${tr}`;var nr=new class{constructor(){}async logEvent(e){try{const t=new AbortController,r=setTimeout(()=>t.abort(),3e3),n=new URLSearchParams;Object.entries(e).forEach(([e,t])=>{null!=t&&n.append(e,String(t))});const o=`${rr}?${n.toString()}`,i=await fetch(o,{method:"GET",signal:t.signal});if(clearTimeout(r),!i.ok)throw new Error(`HTTP error! status: ${i.status}`)}catch(e){}}};function or(){return"true"===process.env.COPILOTKIT_TELEMETRY_DISABLED||"1"===process.env.COPILOTKIT_TELEMETRY_DISABLED||"true"===process.env.DO_NOT_TRACK||"1"===process.env.DO_NOT_TRACK}const ir=tr;var sr,ar={exports:{}};var cr=(sr||(sr=1,function(e,t){var r=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==kt)return kt;throw new Error("unable to locate global object")}();e.exports=t=r.fetch,r.fetch&&(t.default=r.fetch.bind(r)),t.Headers=r.Headers,t.Request=r.Request,t.Response=r.Response}(ar,ar.exports)),ar.exports),lr=o({__proto__:null,default:Pt(cr)},[cr]);e.BANNER_ERROR_NAMES=g,e.COPILOTKIT_VERSION=ir,e.COPILOT_CLOUD_API_URL=D,e.COPILOT_CLOUD_CHAT_URL=K,e.COPILOT_CLOUD_ERROR_NAMES=m,e.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER="X-CopilotCloud-Public-Api-Key",e.COPILOT_CLOUD_VERSION="v1",e.ConfigurationError=I,e.ConsoleColors=s,e.ConsoleStyles=a,e.CopilotKitAgentDiscoveryError=class extends _{constructor(t){const{agentName:r,availableAgents:n}=t,o=e.CopilotKitErrorCode.AGENT_NOT_FOUND,i=v(E[o].troubleshootingUrl);let s;if(n.length){const e=n.map(e=>e.name).join(", ");s=r?`Agent '${r}' was not found. Available agents are: ${e}. Please verify the agent name in your configuration and ensure it matches one of the available agents.\n\n${i}`:`The requested agent was not found. Available agents are: ${e}. Please verify the agent name in your configuration and ensure it matches one of the available agents.\n\n${i}`}else s=`${r?`Agent '${r}'`:"The requested agent"} was not found. Please set up at least one agent before proceeding. ${i}`;super({message:s,code:o}),this.name=f.COPILOT_KIT_AGENT_DISCOVERY_ERROR}},e.CopilotKitApiDiscoveryError=R,e.CopilotKitError=_,e.CopilotKitLowLevelError=C,e.CopilotKitMisuseError=class extends _{constructor({message:t,code:r=e.CopilotKitErrorCode.MISUSE}){const n="troubleshootingUrl"in E[r]&&E[r].troubleshootingUrl?v(E[r].troubleshootingUrl):null;super({message:n?`${t}.\n\n${n}`:t,code:r}),this.name=f.COPILOT_API_DISCOVERY_ERROR}},e.CopilotKitRemoteEndpointDiscoveryError=O,e.CopilotKitVersionMismatchError=class extends _{constructor({reactCoreVersion:t,runtimeVersion:r,runtimeClientGqlVersion:n}){const o=e.CopilotKitErrorCode.VERSION_MISMATCH;super({message:w({reactCoreVersion:t,runtimeVersion:r,runtimeClientGqlVersion:n}),code:o}),this.name=f.COPILOT_KIT_VERSION_MISMATCH_ERROR}},e.ERROR_CONFIG=E,e.ERROR_NAMES=f,e.MissingPublicApiKeyError=class extends I{constructor(t){super(t),this.name=f.MISSING_PUBLIC_API_KEY_ERROR,this.severity=e.Severity.CRITICAL}},e.ResolvedCopilotKitError=class extends _{constructor({status:t,message:r,code:n,isRemoteEndpoint:o,url:i}){let s=n;if(!s)switch(t){case 400:throw new R({message:r,url:i});case 404:throw o?new O({message:r,url:i}):new R({message:r,url:i});default:s=e.CopilotKitErrorCode.UNKNOWN}super({message:r,code:s}),this.name=f.RESOLVED_COPILOT_KIT_ERROR}},e.TelemetryClient=class{constructor({packageName:e,packageVersion:t,telemetryDisabled:n,telemetryBaseUrl:o,sampleRate:i}){if(this.globalProperties={},this.cloudConfiguration=null,this.telemetryDisabled=!1,this.sampleRate=.05,this.anonymousId=`anon_${r.v4()}`,this.packageName=e,this.packageVersion=t,this.telemetryDisabled=n||or(),this.telemetryDisabled)return;this.setSampleRate(i);const s=process.env.COPILOTKIT_SEGMENT_WRITE_KEY||"n7XAZtQCGS2v1vvBy3LgBCv2h3Y8whja";this.segment=new At({writeKey:s}),this.setGlobalProperties({"copilotkit.package.name":e,"copilotkit.package.version":t})}shouldSendEvent(){return Math.random()<this.sampleRate}async capture(e,t){if(!this.shouldSendEvent()||!this.segment)return;const r=er(t),n=Object.assign(Object.assign({},this.globalProperties),r),o=Object.keys(n).sort().reduce((e,t)=>(e[t]=n[t],e),{});this.segment.track({anonymousId:this.anonymousId,event:e,properties:Object.assign({},o)}),await nr.logEvent({event:e})}setGlobalProperties(e){const t=er(e);this.globalProperties=Object.assign(Object.assign({},this.globalProperties),t)}setCloudConfiguration(e){this.cloudConfiguration=e,this.setGlobalProperties({cloud:{publicApiKey:e.publicApiKey,baseUrl:e.baseUrl}})}setSampleRate(e){let t;if(t=null!=e?e:.05,process.env.COPILOTKIT_TELEMETRY_SAMPLE_RATE&&(t=parseFloat(process.env.COPILOTKIT_TELEMETRY_SAMPLE_RATE)),t<0||t>1)throw new Error("Sample rate must be between 0 and 1");this.sampleRate=t,this.setGlobalProperties({sampleRate:this.sampleRate,sampleRateAdjustmentFactor:1-this.sampleRate,sampleWeight:1/this.sampleRate})}},e.UpgradeRequiredError=class extends I{constructor(t){super(t),this.name=f.UPGRADE_REQUIRED_ERROR,this.severity=e.Severity.WARNING}},e.actionParametersToJsonSchema=A,e.convertJsonSchemaToZodSchema=N,e.dataToUUID=function(e,t){const n="e4b01160-ff74-4c6e-9b27-d53cd930fe8e",o=t?r.v5(t,n):n,i="string"==typeof e?e:JSON.stringify(x(e));return r.v5(i,o)},e.ensureStructuredError=function(e,t){return S(e)?e:t(e)},e.executeConditions=function({conditions:e,value:t}){return!(null==e?void 0:e.length)||e.every(e=>i(e,t))},e.getPossibleVersionMismatch=async function({runtimeVersion:e,runtimeClientGqlVersion:t}){if(e&&""!==e&&t)return ir!==e||ir!==t||e!==t?{runtimeVersion:e,runtimeClientGqlVersion:t,reactCoreVersion:ir,message:w({runtimeVersion:e,runtimeClientGqlVersion:t,reactCoreVersion:ir})}:void 0},e.getZodParameters=function(e){return e?N(A(e),!0):n.z.object({})},e.isMacOS=function(){return/Mac|iMac|Macintosh/i.test(navigator.userAgent)},e.isStructuredCopilotKitError=S,e.isTelemetryDisabled=or,e.isValidUUID=function(e){return r.validate(e)},e.jsonSchemaToActionParameters=function(e){if("object"!==e.type||!e.properties)return[];const t=[],r=e.required||[];for(const[n,o]of Object.entries(e.properties)){const e=k(n,o,r.includes(n));t.push(e)}return t},e.logCopilotKitPlatformMessage=c,e.logStyled=u,e.parseJson=function(e,t="unset"){try{return JSON.parse(e)}catch(e){return"unset"===t?null:t}},e.publicApiKeyRequired=l,e.randomId=function(){return"ck-"+r.v4()},e.randomUUID=function(){return r.v4()},e.readBody=async function(e){var t;const r="method"in e?e.method.toUpperCase():void 0;if("GET"!==r&&"HEAD"!==r&&"body"in e&&null!=e.body)try{return await e.clone().json()}catch(r){try{const t=await e.clone().text(),r=t.trim();if(0===r.length)return t;if(r.startsWith("{")||r.startsWith("["))try{return JSON.parse(r)}catch(e){return t}return t}catch(r){try{const r=null!==(t=e.clone().body)&&void 0!==t?t:null;if(!r)return;const n=r.getReader(),o=new TextDecoder;let i="";for(;;){const{done:e,value:t}=await n.read();if(e)break;i+="string"==typeof t?t:o.decode(t,{stream:!0})}i+=o.decode();const s=i.trim();if(0===s.length)return i;if(s.startsWith("{")||s.startsWith("["))try{return JSON.parse(s)}catch(e){return i}return i}catch(e){return}}}},e.styledConsole=h,e.tryMap=function(e,t){return e.reduce((e,r,n,o)=>{try{e.push(t(r,n,o))}catch(e){console.error(e)}return e},[])}});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("graphql"),require("uuid"),require("zod")):"function"==typeof define&&define.amd?define(["exports","graphql","uuid","zod"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).CopilotKitShared={},e.GraphQL,e.UUID,e.Zod)}(this,function(e,t,r,n){"use strict";function o(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(r){if("default"!==r&&!(r in e)){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}})}),Object.freeze(e)}function i(e,t){const r=e.path?(n=t,e.path.split(".").reduce((e,t)=>null==e?void 0:e[t],n)):t;var n;switch(e.rule){case"AND":return e.conditions.every(e=>i(e,t));case"OR":return e.conditions.some(e=>i(e,t));case"NOT":return!e.conditions.every(e=>i(e,t));case"EQUALS":return r===e.value;case"NOT_EQUALS":return r!==e.value;case"GREATER_THAN":return r>e.value;case"LESS_THAN":return r<e.value;case"CONTAINS":return Array.isArray(r)&&r.includes(e.value);case"NOT_CONTAINS":return Array.isArray(r)&&!r.includes(e.value);case"MATCHES":return new RegExp(e.value).test(String(r));case"STARTS_WITH":return String(r).startsWith(e.value);case"ENDS_WITH":return String(r).endsWith(e.value);case"EXISTS":return null!=r;case"NOT_EXISTS":return null==r}}const s={primary:"#007acc",success:"#22c55e",feature:"#a855f7",cta:"#ef4444",info:"#06b6d4",inherit:"inherit",warning:"#f59e0b"},a={header:`color: ${s.warning}; font-weight: bold; font-size: 16px;`,section:`color: ${s.success}; font-weight: bold;`,highlight:`color: ${s.feature}; font-weight: bold;`,cta:`color: ${s.success}; font-weight: bold;`,info:`color: ${s.info}; font-weight: bold;`,link:`color: ${s.primary}; text-decoration: underline;`,body:`color: ${s.inherit};`,warning:`color: ${s.cta}; font-weight: bold;`};function c(){console.log("%cCopilotKit Warning%c\n\nuseCopilotChatHeadless_c provides full compatibility with CopilotKit's newly released Headless UI feature set. To enable this premium feature, add your public license key, available for free at:\n\n%chttps://cloud.copilotkit.ai%c\n\nAlternatively, useCopilotChat is available for basic programmatic control, and does not require an API key.\n\nTo learn more about premium features, read the documentation here:\n\n%chttps://docs.copilotkit.ai/premium%c",a.header,a.body,a.cta,a.body,a.link,a.body)}function l(e){console.log(`\n%cCopilotKit Warning%c \n\nIn order to use ${e}, you need to add your CopilotKit API key, available for free at https://cloud.copilotkit.ai.\n `.trim(),a.header,a.body)}function u(e,t){console.log(e,...t)}const h={success:e=>u(`%c✅ ${e}`,[a.section]),info:e=>u(`%cℹ️ ${e}`,[a.info]),feature:e=>u(`%c✨ ${e}`,[a.highlight]),cta:e=>u(`%c🚀 ${e}`,[a.cta]),logCopilotKitPlatformMessage:c,publicApiKeyRequired:l};var d,p;e.Severity=void 0,(d=e.Severity||(e.Severity={})).CRITICAL="critical",d.WARNING="warning",d.INFO="info",e.ErrorVisibility=void 0,(p=e.ErrorVisibility||(e.ErrorVisibility={})).BANNER="banner",p.TOAST="toast",p.SILENT="silent",p.DEV_ONLY="dev_only";const f={COPILOT_ERROR:"CopilotError",COPILOT_API_DISCOVERY_ERROR:"CopilotApiDiscoveryError",COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR:"CopilotKitRemoteEndpointDiscoveryError",COPILOT_KIT_AGENT_DISCOVERY_ERROR:"CopilotKitAgentDiscoveryError",COPILOT_KIT_LOW_LEVEL_ERROR:"CopilotKitLowLevelError",COPILOT_KIT_VERSION_MISMATCH_ERROR:"CopilotKitVersionMismatchError",RESOLVED_COPILOT_KIT_ERROR:"ResolvedCopilotKitError",CONFIGURATION_ERROR:"ConfigurationError",MISSING_PUBLIC_API_KEY_ERROR:"MissingPublicApiKeyError",UPGRADE_REQUIRED_ERROR:"UpgradeRequiredError"},g=[f.CONFIGURATION_ERROR,f.MISSING_PUBLIC_API_KEY_ERROR,f.UPGRADE_REQUIRED_ERROR,f.COPILOT_API_DISCOVERY_ERROR,f.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR,f.COPILOT_KIT_AGENT_DISCOVERY_ERROR],m=g;var y;e.CopilotKitErrorCode=void 0,(y=e.CopilotKitErrorCode||(e.CopilotKitErrorCode={})).NETWORK_ERROR="NETWORK_ERROR",y.NOT_FOUND="NOT_FOUND",y.AGENT_NOT_FOUND="AGENT_NOT_FOUND",y.API_NOT_FOUND="API_NOT_FOUND",y.REMOTE_ENDPOINT_NOT_FOUND="REMOTE_ENDPOINT_NOT_FOUND",y.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",y.MISUSE="MISUSE",y.UNKNOWN="UNKNOWN",y.VERSION_MISMATCH="VERSION_MISMATCH",y.CONFIGURATION_ERROR="CONFIGURATION_ERROR",y.MISSING_PUBLIC_API_KEY_ERROR="MISSING_PUBLIC_API_KEY_ERROR",y.UPGRADE_REQUIRED_ERROR="UPGRADE_REQUIRED_ERROR";const b="https://docs.copilotkit.ai",v=e=>`See more: [${e}](${e})`,E={[e.CopilotKitErrorCode.NETWORK_ERROR]:{statusCode:503,troubleshootingUrl:`${b}/troubleshooting/common-issues#i-am-getting-a-network-errors--api-not-found`,visibility:e.ErrorVisibility.BANNER,severity:e.Severity.CRITICAL},[e.CopilotKitErrorCode.NOT_FOUND]:{statusCode:404,troubleshootingUrl:`${b}/troubleshooting/common-issues#i-am-getting-a-network-errors--api-not-found`,visibility:e.ErrorVisibility.BANNER,severity:e.Severity.CRITICAL},[e.CopilotKitErrorCode.AGENT_NOT_FOUND]:{statusCode:500,troubleshootingUrl:`${b}/coagents/troubleshooting/common-issues#i-am-getting-agent-not-found-error`,visibility:e.ErrorVisibility.BANNER,severity:e.Severity.CRITICAL},[e.CopilotKitErrorCode.API_NOT_FOUND]:{statusCode:404,troubleshootingUrl:`${b}/troubleshooting/common-issues#i-am-getting-a-network-errors--api-not-found`,visibility:e.ErrorVisibility.BANNER,severity:e.Severity.CRITICAL},[e.CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND]:{statusCode:404,troubleshootingUrl:`${b}/troubleshooting/common-issues#i-am-getting-copilotkits-remote-endpoint-not-found-error`,visibility:e.ErrorVisibility.BANNER,severity:e.Severity.CRITICAL},[e.CopilotKitErrorCode.AUTHENTICATION_ERROR]:{statusCode:401,troubleshootingUrl:`${b}/troubleshooting/common-issues#authentication-errors`,visibility:e.ErrorVisibility.BANNER,severity:e.Severity.CRITICAL},[e.CopilotKitErrorCode.MISUSE]:{statusCode:400,troubleshootingUrl:null,visibility:e.ErrorVisibility.DEV_ONLY,severity:e.Severity.WARNING},[e.CopilotKitErrorCode.UNKNOWN]:{statusCode:500,visibility:e.ErrorVisibility.TOAST,severity:e.Severity.CRITICAL},[e.CopilotKitErrorCode.CONFIGURATION_ERROR]:{statusCode:400,troubleshootingUrl:null,severity:e.Severity.WARNING,visibility:e.ErrorVisibility.BANNER},[e.CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR]:{statusCode:400,troubleshootingUrl:null,severity:e.Severity.CRITICAL,visibility:e.ErrorVisibility.BANNER},[e.CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR]:{statusCode:402,troubleshootingUrl:null,severity:e.Severity.WARNING,visibility:e.ErrorVisibility.BANNER},[e.CopilotKitErrorCode.VERSION_MISMATCH]:{statusCode:400,troubleshootingUrl:null,visibility:e.ErrorVisibility.DEV_ONLY,severity:e.Severity.INFO}};class _ extends t.GraphQLError{constructor({message:t="Unknown error occurred",code:r,severity:n,visibility:o}){var i;const s=f.COPILOT_ERROR,a=E[r],{statusCode:c}=a,l=null!==(i=null!=o?o:a.visibility)&&void 0!==i?i:e.ErrorVisibility.TOAST,u=null!=n?n:"severity"in a?a.severity:void 0;super(t,{extensions:{name:s,statusCode:c,code:r,visibility:l,severity:u,troubleshootingUrl:"troubleshootingUrl"in a?a.troubleshootingUrl:null,originalError:{message:t,stack:(new Error).stack}}}),this.code=r,this.name=s,this.statusCode=c,this.severity=u,this.visibility=l}}const w=({reactCoreVersion:e,runtimeVersion:t,runtimeClientGqlVersion:r})=>`Version mismatch detected: @copilotkit/runtime@${null!=t?t:""} is not compatible with @copilotkit/react-core@${e} and @copilotkit/runtime-client-gql@${r}. Please ensure all installed copilotkit packages are on the same version.`;class R extends _{constructor(t={}){var r,n,o;const i=null!==(r=t.url)&&void 0!==r?r:"";let s="";(null==i?void 0:i.includes("/info"))?s="when fetching CopilotKit info":i.includes("/actions/execute")?s="when attempting to execute actions.":i.includes("/agents/state")?s="when attempting to get agent state.":i.includes("/agents/execute")&&(s="when attempting to execute agent(s).");const a=null!==(n=t.message)&&void 0!==n?n:t.url?`Failed to find CopilotKit API endpoint at url ${t.url} ${s}`:"Failed to find CopilotKit API endpoint.",c=null!==(o=t.code)&&void 0!==o?o:e.CopilotKitErrorCode.API_NOT_FOUND;super({message:`${a}.\n\n${v(E[c].troubleshootingUrl)}`,code:c}),this.name=f.COPILOT_API_DISCOVERY_ERROR}}class O extends R{constructor(t){var r;super({message:null!==(r=null==t?void 0:t.message)&&void 0!==r?r:(null==t?void 0:t.url)?`Failed to find or contact remote endpoint at url ${t.url}`:"Failed to find or contact remote endpoint",code:e.CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND}),this.name=f.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR}}class C extends _{constructor({error:t,url:r,message:n}){let o=e.CopilotKitErrorCode.NETWORK_ERROR;const i=t.code;super({message:null!=n?n:T({errorCode:i,url:r}),code:o}),this.name=f.COPILOT_KIT_LOW_LEVEL_ERROR}}class I extends _{constructor(t){super({message:t,code:e.CopilotKitErrorCode.CONFIGURATION_ERROR}),this.name=f.CONFIGURATION_ERROR,this.severity=e.Severity.WARNING}}function S(e){var t;return e instanceof _||e instanceof C||(null==e?void 0:e.name)&&e.name.includes("CopilotKit")||void 0!==(null===(t=null==e?void 0:e.extensions)||void 0===t?void 0:t.code)}const T=({errorCode:t,url:r})=>{const n=E[e.CopilotKitErrorCode.NETWORK_ERROR].troubleshootingUrl,o=(e=`Failed to fetch from url ${r}.`)=>`${e}.\n\nPossible reasons:\n- -The server may have an error preventing it from returning a response (Check the server logs for more info).\n- -The server might be down or unreachable\n- -There might be a network issue (e.g., DNS failure, connection timeout) \n- -The URL might be incorrect\n- -The server is not running on the specified port\n\n${v(n)}`;if(r.includes("/info"))return o(`Failed to fetch CopilotKit agents/action information from url ${r}.`);if(r.includes("/actions/execute"))return o(`Fetch call to ${r} to execute actions failed.`);if(r.includes("/agents/state"))return o(`Fetch call to ${r} to get agent state failed.`);if(r.includes("/agents/execute"))return o(`Fetch call to ${r} to execute agent(s) failed.`);switch(t){case"ECONNREFUSED":return`Connection to ${r} was refused. Ensure the server is running and accessible.\n\n${v(n)}`;case"ENOTFOUND":return`The server on ${r} could not be found. Check the URL or your network configuration.\n\n${v(E[e.CopilotKitErrorCode.NOT_FOUND].troubleshootingUrl)}`;case"ETIMEDOUT":return`The connection to ${r} timed out. The server might be overloaded or taking too long to respond.\n\n${v(n)}`;default:return}};function A(e){let t={};for(let r of e||[])t[r.name]=P(r);let r=[];for(let t of e||[])!1!==t.required&&r.push(t.name);return{type:"object",properties:t,required:r}}function k(e,t,r){const n={name:e,description:t.description};switch(r||(n.required=!1),t.type){case"string":return Object.assign(Object.assign(Object.assign({},n),{type:"string"}),t.enum&&{enum:t.enum});case"number":case"boolean":return Object.assign(Object.assign({},n),{type:t.type});case"object":if(t.properties){const e=[],r=t.required||[];for(const[n,o]of Object.entries(t.properties))e.push(k(n,o,r.includes(n)));return Object.assign(Object.assign({},n),{type:"object",attributes:e})}return Object.assign(Object.assign({},n),{type:"object"});case"array":if("object"===t.items.type&&"properties"in t.items){const e=[],r=t.items.required||[];for(const[n,o]of Object.entries(t.items.properties||{}))e.push(k(n,o,r.includes(n)));return Object.assign(Object.assign({},n),{type:"object[]",attributes:e})}if("array"===t.items.type)throw new Error("Nested arrays are not supported");return Object.assign(Object.assign({},n),{type:`${t.items.type}[]`});default:return Object.assign(Object.assign({},n),{type:"string"})}}function P(e){var t,r,n;switch(e.type){case"string":return Object.assign({type:"string",description:e.description},e.enum&&{enum:e.enum});case"number":case"boolean":return{type:e.type,description:e.description};case"object":case"object[]":const o=null===(t=e.attributes)||void 0===t?void 0:t.reduce((e,t)=>(e[t.name]=P(t),e),{}),i=null===(r=e.attributes)||void 0===r?void 0:r.filter(e=>!1!==e.required).map(e=>e.name);return"object[]"===e.type?{type:"array",items:Object.assign(Object.assign({type:"object"},o&&{properties:o}),i&&i.length>0&&{required:i}),description:e.description}:Object.assign(Object.assign({type:"object",description:e.description},o&&{properties:o}),i&&i.length>0&&{required:i});default:if(null===(n=e.type)||void 0===n?void 0:n.endsWith("[]")){return{type:"array",items:{type:e.type.slice(0,-2)},description:e.description}}return{type:"string",description:e.description}}}function N(e,t){if("object"===e.type){const r={};if(!e.properties||!Object.keys(e.properties).length)return t?n.z.object(r):n.z.object(r).optional();for(const[t,n]of Object.entries(e.properties))r[t]=N(n,!!e.required&&e.required.includes(t));let o=n.z.object(r).describe(e.description);return t?o:o.optional()}if("string"===e.type){let r=n.z.string().describe(e.description);return t?r:r.optional()}if("number"===e.type){let r=n.z.number().describe(e.description);return t?r:r.optional()}if("boolean"===e.type){let r=n.z.boolean().describe(e.description);return t?r:r.optional()}if("array"===e.type){let r=N(e.items,!0),o=n.z.array(r).describe(e.description);return t?o:o.optional()}throw new Error("Invalid JSON schema")}function x(e){if("function"==typeof e)return e.toString();if(Array.isArray(e))return e.map(x);if(null!==e&&"object"==typeof e){const t={};for(const r of Object.keys(e))t[r]=x(e[r]);return t}return e}const D="https://api.cloud.copilotkit.ai",K=`${D}/copilotkit/v1`;var M=function(e,t){return M=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},M(e,t)};function j(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}M(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var $=function(){return $=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},$.apply(this,arguments)};function U(e,t,r,n){return new(r||(r=Promise))(function(o,i){function s(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})}function L(e,t){var r,n,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(i=0)),i;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,n=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){i.label=a[1];break}if(6===a[0]&&i.label<o[1]){i.label=o[1],o=a;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(a);break}o[2]&&i.ops.pop(),i.trys.pop();continue}a=t.call(e,i)}catch(e){a=[6,e],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}function H(e,t,r){if(r||2===arguments.length)for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))}function W(e,t,r){t.split&&(t=t.split("."));for(var n,o,i=0,s=t.length,a=e;i<s&&"__proto__"!=(o=""+t[i++])&&"constructor"!==o&&"prototype"!==o;)a=a[o]=i===s?r:typeof(n=a[o])==typeof t?n:0*t[i]!=0||~(""+t[i]).indexOf(".")?{}:[]}"function"==typeof SuppressedError&&SuppressedError;var q=function(e){function t(t,r){var n=e.call(this,"".concat(t," ").concat(r))||this;return n.field=t,n}return j(t,e),t}(Error);function F(e){return"string"==typeof e}function V(e){return null!=e}function B(e){return"object"===Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}var J="is not a string",G="is not an object",z="is nil";function Y(e){!function(e){if(!V(e))throw new q("Event",z);if("object"!=typeof e)throw new q("Event",G)}(e),function(e){if(!F(e.type))throw new q(".type",J)}(e),function(e){if(!F(e.messageId))throw new q(".messageId",J)}(e),"track"===e.type&&(function(e){if(!F(e.event))throw new q(".event",J)}(e),function(e){if(!B(e.properties))throw new q(".properties",G)}(e)),["group","identify"].includes(e.type)&&function(e){if(!B(e.traits))throw new q(".traits",G)}(e)}var Q=function(e){var t,r;this.settings=e,this.createMessageId=e.createMessageId,this.onEventMethodCall=null!==(t=e.onEventMethodCall)&&void 0!==t?t:function(){},this.onFinishedEvent=null!==(r=e.onFinishedEvent)&&void 0!==r?r:function(){}},X=function(){function e(e){this.settings=new Q(e)}return e.prototype.track=function(e,t,r,n){return this.settings.onEventMethodCall({type:"track",options:r}),this.normalize($($({},this.baseEvent()),{event:e,type:"track",properties:null!=t?t:{},options:$({},r),integrations:$({},n)}))},e.prototype.page=function(e,t,r,n,o){var i;this.settings.onEventMethodCall({type:"page",options:n});var s={type:"page",properties:$({},r),options:$({},n),integrations:$({},o)};return null!==e&&(s.category=e,s.properties=null!==(i=s.properties)&&void 0!==i?i:{},s.properties.category=e),null!==t&&(s.name=t),this.normalize($($({},this.baseEvent()),s))},e.prototype.screen=function(e,t,r,n,o){this.settings.onEventMethodCall({type:"screen",options:n});var i={type:"screen",properties:$({},r),options:$({},n),integrations:$({},o)};return null!==e&&(i.category=e),null!==t&&(i.name=t),this.normalize($($({},this.baseEvent()),i))},e.prototype.identify=function(e,t,r,n){return this.settings.onEventMethodCall({type:"identify",options:r}),this.normalize($($({},this.baseEvent()),{type:"identify",userId:e,traits:null!=t?t:{},options:$({},r),integrations:n}))},e.prototype.group=function(e,t,r,n){return this.settings.onEventMethodCall({type:"group",options:r}),this.normalize($($({},this.baseEvent()),{type:"group",traits:null!=t?t:{},options:$({},r),integrations:$({},n),groupId:e}))},e.prototype.alias=function(e,t,r,n){this.settings.onEventMethodCall({type:"alias",options:r});var o={userId:e,type:"alias",options:$({},r),integrations:$({},n)};return null!==t&&(o.previousId=t),void 0===e?this.normalize($($({},o),this.baseEvent())):this.normalize($($({},this.baseEvent()),o))},e.prototype.baseEvent=function(){return{integrations:{},options:{}}},e.prototype.context=function(e){var t,r=["userId","anonymousId","timestamp","messageId"];delete e.integrations;var n=Object.keys(e),o=null!==(t=e.context)&&void 0!==t?t:{},i={};return n.forEach(function(t){"context"!==t&&(r.includes(t)?W(i,t,e[t]):W(o,t,e[t]))}),[o,i]},e.prototype.normalize=function(e){var t,r,n,o,i=Object.keys(null!==(t=e.integrations)&&void 0!==t?t:{}).reduce(function(t,r){var n,o;return $($({},t),((n={})[r]=Boolean(null===(o=e.integrations)||void 0===o?void 0:o[r]),n))},{});e.options=(n=e.options||{},o=function(e,t){return void 0!==t},Object.keys(n).filter(function(e){return o(e,n[e])}).reduce(function(e,t){return e[t]=n[t],e},{}));var s=$($({},i),null===(r=e.options)||void 0===r?void 0:r.integrations),a=e.options?this.context(e.options):[],c=a[0],l=a[1],u=e.options,h=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(r[n[o]]=e[n[o]])}return r}(e,["options"]),d=$($($($({timestamp:new Date},h),{context:c,integrations:s}),l),{messageId:u.messageId||this.settings.createMessageId()});return this.settings.onFinishedEvent(d),Y(d),d},e}();function Z(e,t){return new Promise(function(r,n){var o=setTimeout(function(){n(Error("Promise timed out"))},t);e.then(function(e){return clearTimeout(o),r(e)}).catch(n)})}function ee(e){return new Promise(function(t){return setTimeout(t,e)})}function te(e,t,r){return ee(r).then(function(){return Z(function(){try{return Promise.resolve(t(e))}catch(e){return Promise.reject(e)}}(),1e3)}).catch(function(t){null==e||e.log("warn","Callback Error",{error:t}),null==e||e.stats.increment("callback_error")}).then(function(){return e})}var re=function(){function e(e){var t;this.callbacks={},this.warned=!1,this.maxListeners=null!==(t=null==e?void 0:e.maxListeners)&&void 0!==t?t:10}return e.prototype.warnIfPossibleMemoryLeak=function(e){this.warned||this.maxListeners&&this.callbacks[e].length>this.maxListeners&&(console.warn("Event Emitter: Possible memory leak detected; ".concat(String(e)," has exceeded ").concat(this.maxListeners," listeners.")),this.warned=!0)},e.prototype.on=function(e,t){return this.callbacks[e]?(this.callbacks[e].push(t),this.warnIfPossibleMemoryLeak(e)):this.callbacks[e]=[t],this},e.prototype.once=function(e,t){var r=this,n=function(){for(var o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];r.off(e,n),t.apply(r,o)};return this.on(e,n),this},e.prototype.off=function(e,t){var r,n=(null!==(r=this.callbacks[e])&&void 0!==r?r:[]).filter(function(e){return e!==t});return this.callbacks[e]=n,this},e.prototype.emit=function(e){for(var t,r=this,n=[],o=1;o<arguments.length;o++)n[o-1]=arguments[o];return(null!==(t=this.callbacks[e])&&void 0!==t?t:[]).forEach(function(e){e.apply(r,n)}),this},e}();function ne(e){var t=Math.random()+1,r=e.minTimeout,n=void 0===r?500:r,o=e.factor,i=void 0===o?2:o,s=e.attempt,a=e.maxTimeout,c=void 0===a?1/0:a;return Math.min(t*n*Math.pow(i,s),c)}for(var oe,ie="onRemoveFromFuture",se=function(e){function t(t,r,n){var o=e.call(this)||this;return o.future=[],o.maxAttempts=t,o.queue=r,o.seen=null!=n?n:{},o}return j(t,e),t.prototype.push=function(){for(var e=this,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];var n=t.map(function(t){return!(e.updateAttempts(t)>e.maxAttempts||e.includes(t))&&(e.queue.push(t),!0)});return this.queue=this.queue.sort(function(t,r){return e.getAttempts(t)-e.getAttempts(r)}),n},t.prototype.pushWithBackoff=function(e,t){var r=this;if(void 0===t&&(t=0),0==t&&0===this.getAttempts(e))return this.push(e)[0];var n=this.updateAttempts(e);if(n>this.maxAttempts||this.includes(e))return!1;var o=ne({attempt:n-1});return t>0&&o<t&&(o=t),setTimeout(function(){r.queue.push(e),r.future=r.future.filter(function(t){return t.id!==e.id}),r.emit(ie)},o),this.future.push(e),!0},t.prototype.getAttempts=function(e){var t;return null!==(t=this.seen[e.id])&&void 0!==t?t:0},t.prototype.updateAttempts=function(e){return this.seen[e.id]=this.getAttempts(e)+1,this.getAttempts(e)},t.prototype.includes=function(e){return this.queue.includes(e)||this.future.includes(e)||Boolean(this.queue.find(function(t){return t.id===e.id}))||Boolean(this.future.find(function(t){return t.id===e.id}))},t.prototype.pop=function(){return this.queue.shift()},Object.defineProperty(t.prototype,"length",{get:function(){return this.queue.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"todo",{get:function(){return this.queue.length+this.future.length},enumerable:!1,configurable:!0}),t}(re),ae=256,ce=[];ae--;)ce[ae]=(ae+256).toString(16).substring(1);function le(){var e,t=0,r="";if(!oe||ae+16>256){for(oe=Array(t=256);t--;)oe[t]=256*Math.random()|0;t=ae=0}for(;t<16;t++)e=oe[ae+t],r+=6==t?ce[15&e|64]:8==t?ce[63&e|128]:ce[e],1&t&&t>1&&t<11&&(r+="-");return ae++,r}var ue=function(){function e(){this._logs=[]}return e.prototype.log=function(e,t,r){var n=new Date;this._logs.push({level:e,message:t,time:n,extras:r})},Object.defineProperty(e.prototype,"logs",{get:function(){return this._logs},enumerable:!1,configurable:!0}),e.prototype.flush=function(){if(this.logs.length>1){var e=this._logs.reduce(function(e,t){var r,n,o,i=$($({},t),{json:JSON.stringify(t.extras,null," "),extras:t.extras});delete i.time;var s=null!==(o=null===(n=t.time)||void 0===n?void 0:n.toISOString())&&void 0!==o?o:"";return e[s]&&(s="".concat(s,"-").concat(Math.random())),$($({},e),((r={})[s]=i,r))},{});console.table?console.table(e):console.log(e)}else this.logs.forEach(function(e){var t=e.level,r=e.message,n=e.extras;"info"===t||"debug"===t?console.log(r,null!=n?n:""):console[t](r,null!=n?n:"")});this._logs=[]},e}(),he=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return j(t,e),t.prototype.gauge=function(){},t.prototype.increment=function(){},t.prototype.flush=function(){},t.prototype.serialize=function(){return[]},t}(function(){function e(){this.metrics=[]}return e.prototype.increment=function(e,t,r){void 0===t&&(t=1),this.metrics.push({metric:e,value:t,tags:null!=r?r:[],type:"counter",timestamp:Date.now()})},e.prototype.gauge=function(e,t,r){this.metrics.push({metric:e,value:t,tags:null!=r?r:[],type:"gauge",timestamp:Date.now()})},e.prototype.flush=function(){var e=this.metrics.map(function(e){return $($({},e),{tags:e.tags.join(",")})});console.table?console.table(e):console.log(e),this.metrics=[]},e.prototype.serialize=function(){return this.metrics.map(function(e){return{m:e.metric,v:e.value,t:e.tags,k:(t=e.type,{gauge:"g",counter:"c"}[t]),e:e.timestamp};var t})},e}()),de=function(e){var t,r,n;this.retry=null===(t=e.retry)||void 0===t||t,this.type=null!==(r=e.type)&&void 0!==r?r:"plugin Error",this.reason=null!==(n=e.reason)&&void 0!==n?n:""},pe=function(){function e(e,t,r,n){void 0===t&&(t=le()),void 0===r&&(r=new he),void 0===n&&(n=new ue),this.attempts=0,this.event=e,this._id=t,this.logger=n,this.stats=r}return e.system=function(){},e.prototype.isSame=function(e){return e.id===this.id},e.prototype.cancel=function(e){if(e)throw e;throw new de({reason:"Context Cancel"})},e.prototype.log=function(e,t,r){this.logger.log(e,t,r)},Object.defineProperty(e.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),e.prototype.updateEvent=function(e,t){var r;if("integrations"===e.split(".")[0]){var n=e.split(".")[1];if(!1===(null===(r=this.event.integrations)||void 0===r?void 0:r[n]))return this.event}return W(this.event,e,t),this.event},e.prototype.failedDelivery=function(){return this._failedDelivery},e.prototype.setFailedDelivery=function(e){this._failedDelivery=e},e.prototype.logs=function(){return this.logger.logs},e.prototype.flush=function(){this.logger.flush(),this.stats.flush()},e.prototype.toJSON=function(){return{id:this._id,event:this.event,logs:this.logger.logs,metrics:this.stats.metrics}},e}();function fe(e,t){e.log("debug","plugin",{plugin:t.name});var r=(new Date).getTime(),n=t[e.event.type];return void 0===n?Promise.resolve(e):function(e){return U(this,void 0,void 0,function(){var t;return L(this,function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,e()];case 1:return[2,r.sent()];case 2:return t=r.sent(),[2,Promise.reject(t)];case 3:return[2]}})})}(function(){return n.apply(t,[e])}).then(function(e){var n=(new Date).getTime()-r;return e.stats.gauge("plugin_time",n,["plugin:".concat(t.name)]),e}).catch(function(r){if(r instanceof de&&"middleware_cancellation"===r.type)throw r;return r instanceof de?(e.log("warn",r.type,{plugin:t.name,error:r}),r):(e.log("error","plugin Error",{plugin:t.name,error:r}),e.stats.increment("plugin_error",1,["plugin:".concat(t.name)]),r)})}function ge(e,t){return fe(e,t).then(function(t){if(t instanceof pe)return t;e.log("debug","Context canceled"),e.stats.increment("context_canceled"),e.cancel(t)})}var me=function(e){function t(t){var r,n,o,i=e.call(this)||this;return i.criticalTasks=(o=0,{done:function(){return r},run:function(e){var t,i=e();return"object"==typeof(t=i)&&null!==t&&"then"in t&&"function"==typeof t.then&&(1===++o&&(r=new Promise(function(e){return n=e})),i.finally(function(){return 0===--o&&n()})),i}}),i.plugins=[],i.failedInitializations=[],i.flushing=!1,i.queue=t,i.queue.on(ie,function(){i.scheduleFlush(0)}),i}return j(t,e),t.prototype.register=function(e,t,r){return U(this,void 0,void 0,function(){var n,o,i=this;return L(this,function(s){switch(s.label){case 0:return this.plugins.push(t),n=function(r){i.failedInitializations.push(t.name),i.emit("initialization_failure",t),console.warn(t.name,r),e.log("warn","Failed to load destination",{plugin:t.name,error:r}),i.plugins=i.plugins.filter(function(e){return e!==t})},"destination"!==t.type||"Segment.io"===t.name?[3,1]:(t.load(e,r).catch(n),[3,4]);case 1:return s.trys.push([1,3,,4]),[4,t.load(e,r)];case 2:return s.sent(),[3,4];case 3:return o=s.sent(),n(o),[3,4];case 4:return[2]}})})},t.prototype.deregister=function(e,t,r){return U(this,void 0,void 0,function(){var n;return L(this,function(o){switch(o.label){case 0:return o.trys.push([0,3,,4]),t.unload?[4,Promise.resolve(t.unload(e,r))]:[3,2];case 1:o.sent(),o.label=2;case 2:return this.plugins=this.plugins.filter(function(e){return e.name!==t.name}),[3,4];case 3:return n=o.sent(),e.log("warn","Failed to unload destination",{plugin:t.name,error:n}),[3,4];case 4:return[2]}})})},t.prototype.dispatch=function(e){return U(this,void 0,void 0,function(){var t;return L(this,function(r){return e.log("debug","Dispatching"),e.stats.increment("message_dispatched"),this.queue.push(e),t=this.subscribeToDelivery(e),this.scheduleFlush(0),[2,t]})})},t.prototype.subscribeToDelivery=function(e){return U(this,void 0,void 0,function(){var t=this;return L(this,function(r){return[2,new Promise(function(r){var n=function(o,i){o.isSame(e)&&(t.off("flush",n),r(o))};t.on("flush",n)})]})})},t.prototype.dispatchSingle=function(e){return U(this,void 0,void 0,function(){var t=this;return L(this,function(r){return e.log("debug","Dispatching"),e.stats.increment("message_dispatched"),this.queue.updateAttempts(e),e.attempts=1,[2,this.deliver(e).catch(function(r){return t.enqueuRetry(r,e)?t.subscribeToDelivery(e):(e.setFailedDelivery({reason:r}),e)})]})})},t.prototype.isEmpty=function(){return 0===this.queue.length},t.prototype.scheduleFlush=function(e){var t=this;void 0===e&&(e=500),this.flushing||(this.flushing=!0,setTimeout(function(){t.flush().then(function(){setTimeout(function(){t.flushing=!1,t.queue.length&&t.scheduleFlush(0)},0)})},e))},t.prototype.deliver=function(e){return U(this,void 0,void 0,function(){var t,r,n,o;return L(this,function(i){switch(i.label){case 0:return[4,this.criticalTasks.done()];case 1:i.sent(),t=Date.now(),i.label=2;case 2:return i.trys.push([2,4,,5]),[4,this.flushOne(e)];case 3:return e=i.sent(),r=Date.now()-t,this.emit("delivery_success",e),e.stats.gauge("delivered",r),e.log("debug","Delivered",e.event),[2,e];case 4:throw n=i.sent(),o=n,e.log("error","Failed to deliver",o),this.emit("delivery_failure",e,o),e.stats.increment("delivery_failed"),n;case 5:return[2]}})})},t.prototype.enqueuRetry=function(e,t){return!(e instanceof de&&!e.retry)&&this.queue.pushWithBackoff(t)},t.prototype.flush=function(){return U(this,void 0,void 0,function(){var e,t;return L(this,function(r){switch(r.label){case 0:if(0===this.queue.length)return[2,[]];if(!(e=this.queue.pop()))return[2,[]];e.attempts=this.queue.getAttempts(e),r.label=1;case 1:return r.trys.push([1,3,,4]),[4,this.deliver(e)];case 2:return e=r.sent(),this.emit("flush",e,!0),[3,4];case 3:return t=r.sent(),this.enqueuRetry(t,e)||(e.setFailedDelivery({reason:t}),this.emit("flush",e,!1)),[2,[]];case 4:return[2,[e]]}})})},t.prototype.isReady=function(){return!0},t.prototype.availableExtensions=function(e){var t,r,n=this.plugins.filter(function(t){var r,n,o;if("destination"!==t.type&&"Segment.io"!==t.name)return!0;var i=void 0;return null===(r=t.alternativeNames)||void 0===r||r.forEach(function(t){void 0!==e[t]&&(i=e[t])}),null!==(o=null!==(n=e[t.name])&&void 0!==n?n:i)&&void 0!==o?o:!1!==("Segment.io"===t.name||e.All)}),o=(t="type",r={},n.forEach(function(e){var n,o,i=e[t];void 0!==(o="string"!=typeof i?JSON.stringify(i):i)&&(r[o]=H(H([],null!==(n=r[o])&&void 0!==n?n:[],!0),[e],!1))}),r),i=o.before,s=void 0===i?[]:i,a=o.enrichment,c=void 0===a?[]:a,l=o.destination,u=void 0===l?[]:l,h=o.after;return{before:s,enrichment:c,destinations:u,after:void 0===h?[]:h}},t.prototype.flushOne=function(e){var t,r;return U(this,void 0,void 0,function(){var n,o,i,s,a,c,l,u,h,d,p,f,g,m;return L(this,function(y){switch(y.label){case 0:if(!this.isReady())throw new Error("Not ready");e.attempts>1&&this.emit("delivery_retry",e),n=this.availableExtensions(null!==(t=e.event.integrations)&&void 0!==t?t:{}),o=n.before,i=n.enrichment,s=0,a=o,y.label=1;case 1:return s<a.length?(c=a[s],[4,ge(e,c)]):[3,4];case 2:(d=y.sent())instanceof pe&&(e=d),this.emit("message_enriched",e,c),y.label=3;case 3:return s++,[3,1];case 4:l=0,u=i,y.label=5;case 5:return l<u.length?(h=u[l],[4,fe(e,h)]):[3,8];case 6:(d=y.sent())instanceof pe&&(e=d),this.emit("message_enriched",e,h),y.label=7;case 7:return l++,[3,5];case 8:return p=this.availableExtensions(null!==(r=e.event.integrations)&&void 0!==r?r:{}),f=p.destinations,g=p.after,[4,new Promise(function(t,r){setTimeout(function(){var n=f.map(function(t){return fe(e,t)});Promise.all(n).then(t).catch(r)},0)})];case 9:return y.sent(),e.stats.increment("message_delivered"),this.emit("message_delivered",e),m=g.map(function(t){return fe(e,t)}),[4,Promise.all(m)];case 10:return y.sent(),[2,e]}})})},t}(re);const ye="2.3.0";class be{id=le();items=[];sizeInBytes=0;maxEventCount;constructor(e){this.maxEventCount=Math.max(1,e)}tryAdd(e){if(this.length===this.maxEventCount)return{success:!1,message:`Event limit of ${this.maxEventCount} has been exceeded.`};const t=this.calculateSize(e.context);return t>32768?{success:!1,message:"Event exceeds maximum event size of 32 KB"}:this.sizeInBytes+t>491520?{success:!1,message:"Event has caused batch size to exceed 480 KB"}:(this.items.push(e),this.sizeInBytes+=t,{success:!0})}get length(){return this.items.length}calculateSize(e){return encodeURI(JSON.stringify(e.event)).split(/%..|i/).length}getEvents(){return this.items.map(({context:e})=>e.event)}getContexts(){return this.items.map(e=>e.context)}resolveEvents(){this.items.forEach(({resolver:e,context:t})=>e(t))}}var ve=crypto;const Ee=e=>e instanceof CryptoKey,_e=new TextEncoder,we=new TextDecoder;const Re=e=>(e=>{let t=e;"string"==typeof t&&(t=_e.encode(t));const r=[];for(let e=0;e<t.length;e+=32768)r.push(String.fromCharCode.apply(null,t.subarray(e,e+32768)));return btoa(r.join(""))})(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),Oe=e=>{let t=e;t instanceof Uint8Array&&(t=we.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return(e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r})(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class Ce extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}Ce.code="ERR_JOSE_GENERIC";(class extends Ce{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n,this.payload=t}}).code="ERR_JWT_CLAIM_VALIDATION_FAILED";(class extends Ce{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n,this.payload=t}}).code="ERR_JWT_EXPIRED";(class extends Ce{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}).code="ERR_JOSE_ALG_NOT_ALLOWED";class Ie extends Ce{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}Ie.code="ERR_JOSE_NOT_SUPPORTED";(class extends Ce{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}).code="ERR_JWE_DECRYPTION_FAILED";(class extends Ce{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}).code="ERR_JWE_INVALID";class Se extends Ce{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}Se.code="ERR_JWS_INVALID";class Te extends Ce{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}Te.code="ERR_JWT_INVALID";(class extends Ce{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}).code="ERR_JWK_INVALID";(class extends Ce{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}).code="ERR_JWKS_INVALID";(class extends Ce{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}).code="ERR_JWKS_NO_MATCHING_KEY";(class extends Ce{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}).code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";(class extends Ce{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}).code="ERR_JWKS_TIMEOUT";function Ae(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function ke(e,t){return e.name===t}function Pe(e){return parseInt(e.name.slice(4),10)}function Ne(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!ke(e.algorithm,"HMAC"))throw Ae("HMAC");const r=parseInt(t.slice(2),10);if(Pe(e.algorithm.hash)!==r)throw Ae(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ke(e.algorithm,"RSASSA-PKCS1-v1_5"))throw Ae("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(Pe(e.algorithm.hash)!==r)throw Ae(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ke(e.algorithm,"RSA-PSS"))throw Ae("RSA-PSS");const r=parseInt(t.slice(2),10);if(Pe(e.algorithm.hash)!==r)throw Ae(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw Ae("Ed25519 or Ed448");break;case"Ed25519":if(!ke(e.algorithm,"Ed25519"))throw Ae("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!ke(e.algorithm,"ECDSA"))throw Ae("ECDSA");const r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw Ae(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const r=t.pop();e+=`one of ${t.join(", ")}, or ${r}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,r)}function xe(e,t,...r){if((r=r.filter(Boolean)).length>2){const t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}(class extends Ce{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}).code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";var De=(e,...t)=>xe("Key must be ",e,...t);function Ke(e,t,...r){return xe(`Key for the ${e} algorithm must be `,t,...r)}var Me=e=>!!Ee(e)||"KeyObject"===e?.[Symbol.toStringTag];const je=["CryptoKey"];function $e(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let r=e;for(;null!==Object.getPrototypeOf(r);)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(e)===r}function Ue(e){return $e(e)&&"string"==typeof e.kty}const Le=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=function(e){let t,r;switch(e.kty){case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new Ie('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new Ie('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new Ie('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new Ie('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),n=[t,e.ext??!1,e.key_ops??r],o={...e};return delete o.alg,delete o.use,ve.subtle.importKey("jwk",o,...n)},He=e=>Oe(e);let We;const qe=e=>"KeyObject"===e?.[Symbol.toStringTag],Fe=async(e,t,r,n,o=!1)=>{let i=e.get(t);if(i?.[n])return i[n];const s=await Le({...r,alg:n});return o&&Object.freeze(t),i?i[n]=s:e.set(t,{[n]:s}),s};var Ve=(e,t)=>{if(qe(e)){let r=e.export({format:"jwk"});return r.k?He(r.k):(We||(We=new WeakMap),Fe(We,e,r,t))}if(Ue(e)){if(e.k)return Oe(e.k);We||(We=new WeakMap);return Fe(We,e,e,t,!0)}return e};const Be=(e,t,r=0)=>{0===r&&(t.unshift(t.length),t.unshift(6));const n=e.indexOf(t[0],r);if(-1===n)return!1;const o=e.subarray(n,n+t.length);return o.length===t.length&&(o.every((e,r)=>e===t[r])||Be(e,t,n+1))},Je=e=>{switch(!0){case Be(e,[42,134,72,206,61,3,1,7]):return"P-256";case Be(e,[43,129,4,0,34]):return"P-384";case Be(e,[43,129,4,0,35]):return"P-521";case Be(e,[43,101,110]):return"X25519";case Be(e,[43,101,111]):return"X448";case Be(e,[43,101,112]):return"Ed25519";case Be(e,[43,101,113]):return"Ed448";default:throw new Ie("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},Ge=(e,t,r)=>(async(e,t,r,n)=>{let o,i;const s=new Uint8Array(atob(r.replace(e,"")).split("").map(e=>e.charCodeAt(0)));switch(n){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},i=["sign"];break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},i=["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":o={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},i=["decrypt","unwrapKey"];break;case"ES256":o={name:"ECDSA",namedCurve:"P-256"},i=["sign"];break;case"ES384":o={name:"ECDSA",namedCurve:"P-384"},i=["sign"];break;case"ES512":o={name:"ECDSA",namedCurve:"P-521"},i=["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const e=Je(s);o=e.startsWith("P-")?{name:"ECDH",namedCurve:e}:{name:e},i=["deriveBits"];break}case"Ed25519":o={name:"Ed25519"},i=["sign"];break;case"EdDSA":o={name:Je(s)},i=["sign"];break;default:throw new Ie('Invalid or unsupported "alg" (Algorithm) value')}return ve.subtle.importKey(t,s,o,!1,i)})(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t);const ze=e=>e?.[Symbol.toStringTag],Ye=(e,t,r)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(r))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},Qe=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&Ue(t)){if(function(e){return Ue(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&Ye(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Me(t))throw new TypeError(Ke(e,t,...je,"Uint8Array",n?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${ze(t)} instances for symmetric algorithms must be of type "secret"`)}};function Xe(e,t,r,n){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Qe(t,r,n,e):((e,t,r,n)=>{if(n&&Ue(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&Ye(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&Ye(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Me(t))throw new TypeError(Ke(e,t,...je,n?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${ze(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${ze(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${ze(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${ze(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${ze(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,n,e)}Xe.bind(void 0,!1);const Ze=Xe.bind(void 0,!0);var et=e=>Math.floor(e.getTime()/1e3);const tt=86400,rt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;var nt=e=>{const t=rt.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]);let n;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(60*r);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(3600*r);break;case"day":case"days":case"d":n=Math.round(r*tt);break;case"week":case"weeks":case"w":n=Math.round(604800*r);break;default:n=Math.round(31557600*r)}return"-"===t[1]||"ago"===t[4]?-n:n};const ot=async(e,t,r)=>{const n=await async function(e,t,r){if(t=await Ve(t,e),Ee(t))return Ne(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(De(t,...je));return ve.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(De(t,...je,"Uint8Array","JSON Web Key"))}(e,t,"sign");((e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}})(e,n);const o=await ve.subtle.sign(function(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new Ie(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e,n.algorithm),n,r);return new Uint8Array(o)};class it{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new Se("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!((...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let r;for(const e of t){const t=Object.keys(e);if(r&&0!==r.size)for(const e of t){if(r.has(e))return!1;r.add(e)}else r=new Set(t)}return!0})(this._protectedHeader,this._unprotectedHeader))throw new Se("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader},n=function(e,t,r,n,o){if(void 0!==o.crit&&void 0===n?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;i=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of n.crit){if(!i.has(t))throw new Ie(`Extension Header Parameter "${t}" is not recognized`);if(void 0===o[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(i.get(t)&&void 0===n[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(n.crit)}(Se,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r);let o=!0;if(n.has("b64")&&(o=this._protectedHeader.b64,"boolean"!=typeof o))throw new Se('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:i}=r;if("string"!=typeof i||!i)throw new Se('JWS "alg" (Algorithm) Header Parameter missing or invalid');Ze(i,e,"sign");let s,a=this._payload;o&&(a=_e.encode(Re(a))),s=this._protectedHeader?_e.encode(Re(JSON.stringify(this._protectedHeader))):_e.encode("");const c=function(...e){const t=e.reduce((e,{length:t})=>e+t,0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}(s,_e.encode("."),a),l=await ot(i,e,c),u={signature:Re(l),payload:""};return o&&(u.payload=we.decode(a)),this._unprotectedHeader&&(u.header=this._unprotectedHeader),this._protectedHeader&&(u.protected=we.decode(s)),u}}class st{constructor(e){this._flattened=new it(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const r=await this._flattened.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}function at(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class ct{constructor(e={}){if(!$e(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:at("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:at("setNotBefore",et(e))}:this._payload={...this._payload,nbf:et(new Date)+nt(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:at("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:at("setExpirationTime",et(e))}:this._payload={...this._payload,exp:et(new Date)+nt(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:et(new Date)}:e instanceof Date?this._payload={...this._payload,iat:at("setIssuedAt",et(e))}:this._payload="string"==typeof e?{...this._payload,iat:at("setIssuedAt",et(new Date)+nt(e))}:{...this._payload,iat:at("setIssuedAt",e)},this}}class lt extends ct{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new st(_e.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new Te("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}function ut(e){const t={};if(!e)return{};if(function(e){if("object"==typeof e&&null!==e&&"entries"in Object(e)&&"function"==typeof Object(e).entries)return!0;return!1}(e)){for(const[r,n]of e.entries())t[r.toLowerCase()]=n;return t}for(const[r,n]of Object.entries(e))t[r.toLowerCase()]=n;return t}class ht{alg="RS256";grantType="client_credentials";clientAssertionType="urn:ietf:params:oauth:client-assertion-type:jwt-bearer";clientId;clientKey;keyId;scope;authServer;httpClient;maxRetries;clockSkewInSeconds=0;accessToken;tokenEmitter=new re;retryCount;pollerTimer;constructor(e){this.keyId=e.keyId,this.clientId=e.clientId,this.clientKey=e.clientKey,this.authServer=e.authServer??"https://oauth2.segment.io",this.scope=e.scope??"tracking_api:write",this.httpClient=e.httpClient,this.maxRetries=e.maxRetries,this.tokenEmitter.on("access_token",e=>{"token"in e&&(this.accessToken=e.token)}),this.retryCount=0}stopPoller(){clearTimeout(this.pollerTimer)}async pollerLoop(){let e,t=25;try{e=await this.requestAccessToken()}catch(e){return this.handleTransientError({error:e})}if(!(e=>"function"==typeof e.text)(e))return this.handleInvalidCustomResponse();const r=ut(e.headers);if(r.date&&this.updateClockSkew(Date.parse(r.date)),200!==e.status)return 429===e.status?await this.handleRateLimited(e,r,t):[400,401,415].includes(e.status)?this.handleUnrecoverableErrors(e):this.handleTransientError({error:new Error(`[${e.status}] ${e.statusText}`)});try{const r=await e.text(),o=JSON.parse(r);if(n=o,!Boolean(n&&"object"==typeof n&&"access_token"in n&&"expires_in"in n&&"string"==typeof n.access_token&&"number"==typeof n.expires_in))throw new Error("Response did not contain a valid access_token and expires_in");return o.expires_at=Math.round(Date.now()/1e3)+o.expires_in,this.tokenEmitter.emit("access_token",{token:o}),this.retryCount=0,t=o.expires_in/2*1e3,this.queueNextPoll(t)}catch(e){return this.handleTransientError({error:e,forceEmitError:!0})}var n}handleTransientError({error:e,forceEmitError:t}){this.incrementRetries({error:e,forceEmitError:t});const r=ne({attempt:this.retryCount,minTimeout:25,maxTimeout:1e3});this.queueNextPoll(r)}handleInvalidCustomResponse(){this.tokenEmitter.emit("access_token",{error:new Error("HTTPClient does not implement response.text method")})}async handleRateLimited(e,t,r){if(this.incrementRetries({error:new Error(`[${e.status}] ${e.statusText}`)}),t["x-ratelimit-reset"]){const e=parseInt(t["x-ratelimit-reset"],10);r=isFinite(e)?e-Date.now()+1e3*this.clockSkewInSeconds:5e3,await ee(r),r=0}this.queueNextPoll(r)}handleUnrecoverableErrors(e){this.retryCount=0,this.tokenEmitter.emit("access_token",{error:new Error(`[${e.status}] ${e.statusText}`)}),this.stopPoller()}updateClockSkew(e){this.clockSkewInSeconds=(Date.now()-e)/1e3}incrementRetries({error:e,forceEmitError:t}){this.retryCount++,(t||this.retryCount%this.maxRetries===0)&&(this.retryCount=0,this.tokenEmitter.emit("access_token",{error:e}))}queueNextPoll(e){this.pollerTimer=setTimeout(()=>this.pollerLoop(),e),this.pollerTimer.unref&&this.pollerTimer.unref()}async requestAccessToken(){const e=le(),t=Math.round(Date.now()/1e3)-this.clockSkewInSeconds,r={iss:this.clientId,sub:this.clientId,aud:this.authServer,iat:t-5,exp:t+55,jti:e},n=await async function(e,t){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Ge(e,t)}(this.clientKey,"RS256"),o=await new lt(r).setProtectedHeader({alg:this.alg,kid:this.keyId,typ:"JWT"}).sign(n),i=`grant_type=${this.grantType}&client_assertion_type=${this.clientAssertionType}&client_assertion=${o}&scope=${this.scope}`,s={method:"POST",url:`${this.authServer}/token`,body:i,headers:{"Content-Type":"application/x-www-form-urlencoded"},httpRequestTimeout:1e4};return this.httpClient.makeRequest(s)}async getAccessToken(){return this.isValidToken(this.accessToken)?this.accessToken:(this.stopPoller(),this.pollerLoop().catch(()=>{}),new Promise((e,t)=>{this.tokenEmitter.once("access_token",r=>{"token"in r?e(r.token):t(r.error)})}))}clearToken(){this.accessToken=void 0}isValidToken(e){return null!=e&&e.expires_in<Date.now()/1e3}}function dt(e){return new Promise(t=>setTimeout(t,e))}function pt(){}class ft{pendingFlushTimeout;_batch;_flushInterval;_flushAt;_maxRetries;_url;_flushPendingItemsCount;_httpRequestTimeout;_emitter;_disable;_httpClient;_writeKey;_tokenManager;constructor({host:e,path:t,maxRetries:r,flushAt:n,flushInterval:o,writeKey:i,httpRequestTimeout:s,httpClient:a,disable:c,oauthSettings:l},u){this._emitter=u,this._maxRetries=r,this._flushAt=Math.max(n,1),this._flushInterval=o,this._url=((e,t)=>new URL(t||"",e).href.replace(/\/$/,""))(e??"https://api.segment.io",t??"/v1/batch"),this._httpRequestTimeout=s??1e4,this._disable=Boolean(c),this._httpClient=a,this._writeKey=i,l&&(this._tokenManager=new ht({...l,httpClient:l.httpClient??a,maxRetries:l.maxRetries??r}))}createBatch(){this.pendingFlushTimeout&&clearTimeout(this.pendingFlushTimeout);const e=new be(this._flushAt);return this._batch=e,this.pendingFlushTimeout=setTimeout(()=>{e===this._batch&&(this._batch=void 0),this.pendingFlushTimeout=void 0,e.length&&this.send(e).catch(pt)},this._flushInterval),e}clearBatch(){this.pendingFlushTimeout&&clearTimeout(this.pendingFlushTimeout),this._batch=void 0}flush(e){if(!e)return void(this._tokenManager&&this._tokenManager.stopPoller());if(this._flushPendingItemsCount=e,!this._batch)return;this._batch.length===e&&(this.send(this._batch).catch(pt).finally(()=>{this._tokenManager&&this._tokenManager.stopPoller()}),this.clearBatch())}enqueue(e){const t=this._batch??this.createBatch(),{promise:r,resolve:n}=function(){var e,t,r=!1,n=new Promise(function(n,o){e=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];r=!0,n.apply(void 0,e)},t=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];r=!0,o.apply(void 0,e)}});return{resolve:e,reject:t,promise:n,isSettled:function(){return r}}}(),o={context:e,resolver:n};if(t.tryAdd(o).success){const e=t.length===this._flushPendingItemsCount;return(t.length===this._flushAt||e)&&(this.send(t).catch(pt),this.clearBatch()),r}t.length&&(this.send(t).catch(pt),this.clearBatch());const i=this.createBatch(),s=i.tryAdd(o);if(s.success){return i.length===this._flushPendingItemsCount&&(this.send(i).catch(pt),this.clearBatch()),r}return e.setFailedDelivery({reason:new Error(s.message)}),Promise.resolve(e)}async send(e){this._flushPendingItemsCount&&(this._flushPendingItemsCount-=e.length);const t=e.getEvents(),r=this._maxRetries+1;let n=0;for(;n<r;){let o,i;n++;try{if(this._disable)return e.resolveEvents();let r;if(this._tokenManager){const e=await this._tokenManager.getAccessToken();e&&e.access_token&&(r=`Bearer ${e.access_token}`)}const n={"Content-Type":"application/json","User-Agent":"analytics-node-next/latest",...r?{Authorization:r}:{}},s={url:this._url,method:"POST",headers:n,body:JSON.stringify({batch:t,writeKey:this._writeKey,sentAt:new Date}),httpRequestTimeout:this._httpRequestTimeout};this._emitter.emit("http_request",{body:s.body,method:s.method,url:s.url,headers:s.headers});const a=await this._httpClient.makeRequest(s);if(a.status>=200&&a.status<300)return void e.resolveEvents();if(!this._tokenManager||400!==a.status&&401!==a.status&&403!==a.status){if(400===a.status)return void gt(e,new Error(`[${a.status}] ${a.statusText}`));if(429===a.status){if(a.headers&&"x-ratelimit-reset"in a.headers){const e=parseInt(a.headers["x-ratelimit-reset"],10);isFinite(e)&&(o=e-Date.now())}i=new Error(`[${a.status}] ${a.statusText}`)}else i=new Error(`[${a.status}] ${a.statusText}`)}else this._tokenManager.clearToken(),i=new Error(`[${a.status}] ${a.statusText}`)}catch(e){i=e}if(n===r)return void gt(e,i);await dt(o||ne({attempt:n,minTimeout:25,maxTimeout:1e3}))}}}function gt(e,t){e.getContexts().forEach(e=>e.setFailedDelivery({reason:t})),e.resolveEvents()}const mt=()=>"object"==typeof process&&process&&"object"==typeof process.env&&process.env&&"string"==typeof process.version?"node":"object"==typeof window?"browser":"undefined"!=typeof WebSocketPair?"cloudflare-worker":"string"==typeof EdgeRuntime?"vercel-edge":"undefined"!=typeof WorkerGlobalScope&&"function"==typeof importScripts?"web-worker":"unknown";function yt(e){function t(t){return function(e){e.updateEvent("context.library.name","@segment/analytics-node"),e.updateEvent("context.library.version",ye);const t=mt();"node"===t&&e.updateEvent("_metadata.nodeVersion",process.version),e.updateEvent("_metadata.jsRuntime",t)}(t),e.enqueue(t)}return{name:"Segment.io",type:"destination",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),alias:t,group:t,identify:t,page:t,screen:t,track:t}}const bt=()=>`node-next-${Date.now()}-${le()}`;class vt extends X{constructor(){super({createMessageId:bt,onFinishedEvent:e=>{!function(e){var t=".userId/anonymousId/previousId/groupId",r=function(e){var t,r,n;return null!==(n=null!==(r=null!==(t=e.userId)&&void 0!==t?t:e.anonymousId)&&void 0!==r?r:e.groupId)&&void 0!==n?n:e.previousId}(e);if(!V(r))throw new q(t,z);if(!F(r))throw new q(t,J)}(e)}})}}class Et extends pe{static system(){return new this({type:"track",event:"system"})}}const _t=async(e,t,r,n)=>{try{const i=new Et(e),s=await function(e,t,r,n){return U(this,void 0,void 0,function(){var o,i;return L(this,function(s){switch(s.label){case 0:return r.emit("dispatch_start",e),o=Date.now(),t.isEmpty()?[4,t.dispatchSingle(e)]:[3,2];case 1:return i=s.sent(),[3,4];case 2:return[4,t.dispatch(e)];case 3:i=s.sent(),s.label=4;case 4:return(null==n?void 0:n.callback)?[4,te(i,n.callback,(a=o,c=n.timeout,l=Date.now()-a,Math.max((null!=c?c:300)-l,0)))]:[3,6];case 5:i=s.sent(),s.label=6;case 6:return(null==n?void 0:n.debug)&&i.flush(),[2,i]}var a,c,l})})}(i,t,r,{...n?{callback:(o=n,e=>{const t=e.failedDelivery();return o(t?t.reason:void 0,e)})}:{}}),a=s.failedDelivery();a?r.emit("error",{code:"delivery_failure",reason:a.reason,ctx:s}):r.emit(e.type,s)}catch(e){r.emit("error",{code:"unknown",reason:e})}var o};class wt extends re{}class Rt extends se{constructor(){super(1,[])}getAttempts(e){return e.attempts??0}updateAttempts(e){return e.attempts=this.getAttempts(e)+1,this.getAttempts(e)}}class Ot extends me{constructor(){super(new Rt)}}class Ct{onabort=null;aborted=!1;eventEmitter=new re;toString(){return"[object AbortSignal]"}get[Symbol.toStringTag](){return"AbortSignal"}removeEventListener(...e){this.eventEmitter.off(...e)}addEventListener(...e){this.eventEmitter.on(...e)}dispatchEvent(e){const t={type:e,target:this},r=`on${e}`;"function"==typeof this[r]&&this[r](t),this.eventEmitter.emit(e,t)}}let It=class{signal=new Ct;abort(){this.signal.aborted||(this.signal.aborted=!0,this.signal.dispatchEvent("abort"))}toString(){return"[object AbortController]"}get[Symbol.toStringTag](){return"AbortController"}};const St=async(...e)=>{if(globalThis.fetch)return globalThis.fetch(...e);if("string"!=typeof EdgeRuntime)return(await Promise.resolve().then(function(){return lr})).default(...e);throw new Error("Invariant: an edge runtime that does not support fetch should not exist")};class Tt{_fetch;constructor(e){this._fetch=e??St}async makeRequest(e){const[t,r]=(e=>{if("cloudflare-worker"===mt())return[];const t=new(globalThis.AbortController||It),r=setTimeout(()=>{t.abort()},e);return r?.unref?.(),[t.signal,r]})(e.httpRequestTimeout),n={url:e.url,method:e.method,headers:e.headers,body:e.body,signal:t};return this._fetch(e.url,n).finally(()=>clearTimeout(r))}}class At extends wt{_eventFactory;_isClosed=!1;_pendingEvents=0;_closeAndFlushDefaultTimeout;_publisher;_isFlushing=!1;_queue;ready;constructor(e){super(),(e=>{if(!e.writeKey)throw new q("writeKey","writeKey is missing.")})(e),this._eventFactory=new vt,this._queue=new Ot;const t=e.flushInterval??1e4;this._closeAndFlushDefaultTimeout=1.25*t;const{plugin:r,publisher:n}=((e,t)=>{const r=new ft(e,t);return{publisher:r,plugin:yt(r)}})({writeKey:e.writeKey,host:e.host,path:e.path,maxRetries:e.maxRetries??3,flushAt:e.flushAt??e.maxEventsInBatch??15,httpRequestTimeout:e.httpRequestTimeout,disable:e.disable,flushInterval:t,httpClient:"function"==typeof e.httpClient?new Tt(e.httpClient):e.httpClient??new Tt,oauthSettings:e.oauthSettings},this);this._publisher=n,this.ready=this.register(r).then(()=>{}),this.emit("initialize",e),function(e){for(var t=e.constructor.prototype,r=0,n=Object.getOwnPropertyNames(t);r<n.length;r++){var o=n[r];if("constructor"!==o){var i=Object.getOwnPropertyDescriptor(e.constructor.prototype,o);i&&"function"==typeof i.value&&(e[o]=e[o].bind(e))}}}(this)}get VERSION(){return ye}closeAndFlush({timeout:e=this._closeAndFlushDefaultTimeout}={}){return this.flush({timeout:e,close:!0})}async flush({timeout:e,close:t=!1}={}){if(this._isFlushing)return void console.warn("Overlapping flush calls detected. Please wait for the previous flush to finish before calling .flush again");this._isFlushing=!0,t&&(this._isClosed=!0),this._publisher.flush(this._pendingEvents);const r=new Promise(e=>{this._pendingEvents?this.once("drained",()=>{e()}):e()}).finally(()=>{this._isFlushing=!1});return e?Z(r,e).catch(()=>{}):r}_dispatch(e,t){this._isClosed?this.emit("call_after_close",e):(this._pendingEvents++,_t(e,this._queue,this,t).catch(e=>e).finally(()=>{this._pendingEvents--,this._pendingEvents||this.emit("drained")}))}alias({userId:e,previousId:t,context:r,timestamp:n,integrations:o,messageId:i},s){const a=this._eventFactory.alias(e,t,{context:r,integrations:o,timestamp:n,messageId:i});this._dispatch(a,s)}group({timestamp:e,groupId:t,userId:r,anonymousId:n,traits:o={},context:i,integrations:s,messageId:a},c){const l=this._eventFactory.group(t,o,{context:i,anonymousId:n,userId:r,timestamp:e,integrations:s,messageId:a});this._dispatch(l,c)}identify({userId:e,anonymousId:t,traits:r={},context:n,timestamp:o,integrations:i,messageId:s},a){const c=this._eventFactory.identify(e,r,{context:n,anonymousId:t,userId:e,timestamp:o,integrations:i,messageId:s});this._dispatch(c,a)}page({userId:e,anonymousId:t,category:r,name:n,properties:o,context:i,timestamp:s,integrations:a,messageId:c},l){const u=this._eventFactory.page(r??null,n??null,o,{context:i,anonymousId:t,userId:e,timestamp:s,integrations:a,messageId:c});this._dispatch(u,l)}screen({userId:e,anonymousId:t,category:r,name:n,properties:o,context:i,timestamp:s,integrations:a,messageId:c},l){const u=this._eventFactory.screen(r??null,n??null,o,{context:i,anonymousId:t,userId:e,timestamp:s,integrations:a,messageId:c});this._dispatch(u,l)}track({userId:e,anonymousId:t,event:r,properties:n,context:o,timestamp:i,integrations:s,messageId:a},c){const l=this._eventFactory.track(r,n,{context:o,userId:e,anonymousId:t,timestamp:i,integrations:s,messageId:a});this._dispatch(l,c)}register(...e){return this._queue.criticalTasks.run(async()=>{const t=Et.system(),r=e.map(e=>this._queue.register(t,e,this));await Promise.all(r),this.emit("register",e.map(e=>e.name))})}async deregister(...e){const t=Et.system(),r=e.map(e=>{const r=this._queue.plugins.find(t=>t.name===e);if(r)return this._queue.deregister(t,r,this);t.log("warn",`plugin ${e} not found`)});await Promise.all(r),this.emit("deregister",e)}}var kt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Pt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Nt,xt,Dt,Kt,Mt,jt,$t,Ut,Lt,Ht,Wt,qt,Ft,Vt,Bt,Jt,Gt,zt={exports:{}};function Yt(){if(Kt)return Dt;Kt=1;const e=xt?Nt:(xt=1,Nt={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}),t={};for(const r of Object.keys(e))t[e[r]]=r;const r={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};Dt=r;for(const e of Object.keys(r)){if(!("channels"in r[e]))throw new Error("missing channels property: "+e);if(!("labels"in r[e]))throw new Error("missing channel labels property: "+e);if(r[e].labels.length!==r[e].channels)throw new Error("channel and label counts mismatch: "+e);const{channels:t,labels:n}=r[e];delete r[e].channels,delete r[e].labels,Object.defineProperty(r[e],"channels",{value:t}),Object.defineProperty(r[e],"labels",{value:n})}function n(e,t){return(e[0]-t[0])**2+(e[1]-t[1])**2+(e[2]-t[2])**2}return r.rgb.hsl=function(e){const t=e[0]/255,r=e[1]/255,n=e[2]/255,o=Math.min(t,r,n),i=Math.max(t,r,n),s=i-o;let a,c;i===o?a=0:t===i?a=(r-n)/s:r===i?a=2+(n-t)/s:n===i&&(a=4+(t-r)/s),a=Math.min(60*a,360),a<0&&(a+=360);const l=(o+i)/2;return c=i===o?0:l<=.5?s/(i+o):s/(2-i-o),[a,100*c,100*l]},r.rgb.hsv=function(e){let t,r,n,o,i;const s=e[0]/255,a=e[1]/255,c=e[2]/255,l=Math.max(s,a,c),u=l-Math.min(s,a,c),h=function(e){return(l-e)/6/u+.5};return 0===u?(o=0,i=0):(i=u/l,t=h(s),r=h(a),n=h(c),s===l?o=n-r:a===l?o=1/3+t-n:c===l&&(o=2/3+r-t),o<0?o+=1:o>1&&(o-=1)),[360*o,100*i,100*l]},r.rgb.hwb=function(e){const t=e[0],n=e[1];let o=e[2];const i=r.rgb.hsl(e)[0],s=1/255*Math.min(t,Math.min(n,o));return o=1-1/255*Math.max(t,Math.max(n,o)),[i,100*s,100*o]},r.rgb.cmyk=function(e){const t=e[0]/255,r=e[1]/255,n=e[2]/255,o=Math.min(1-t,1-r,1-n);return[100*((1-t-o)/(1-o)||0),100*((1-r-o)/(1-o)||0),100*((1-n-o)/(1-o)||0),100*o]},r.rgb.keyword=function(r){const o=t[r];if(o)return o;let i,s=1/0;for(const t of Object.keys(e)){const o=n(r,e[t]);o<s&&(s=o,i=t)}return i},r.keyword.rgb=function(t){return e[t]},r.rgb.xyz=function(e){let t=e[0]/255,r=e[1]/255,n=e[2]/255;t=t>.04045?((t+.055)/1.055)**2.4:t/12.92,r=r>.04045?((r+.055)/1.055)**2.4:r/12.92,n=n>.04045?((n+.055)/1.055)**2.4:n/12.92;return[100*(.4124*t+.3576*r+.1805*n),100*(.2126*t+.7152*r+.0722*n),100*(.0193*t+.1192*r+.9505*n)]},r.rgb.lab=function(e){const t=r.rgb.xyz(e);let n=t[0],o=t[1],i=t[2];n/=95.047,o/=100,i/=108.883,n=n>.008856?n**(1/3):7.787*n+16/116,o=o>.008856?o**(1/3):7.787*o+16/116,i=i>.008856?i**(1/3):7.787*i+16/116;return[116*o-16,500*(n-o),200*(o-i)]},r.hsl.rgb=function(e){const t=e[0]/360,r=e[1]/100,n=e[2]/100;let o,i,s;if(0===r)return s=255*n,[s,s,s];o=n<.5?n*(1+r):n+r-n*r;const a=2*n-o,c=[0,0,0];for(let e=0;e<3;e++)i=t+1/3*-(e-1),i<0&&i++,i>1&&i--,s=6*i<1?a+6*(o-a)*i:2*i<1?o:3*i<2?a+(o-a)*(2/3-i)*6:a,c[e]=255*s;return c},r.hsl.hsv=function(e){const t=e[0];let r=e[1]/100,n=e[2]/100,o=r;const i=Math.max(n,.01);n*=2,r*=n<=1?n:2-n,o*=i<=1?i:2-i;return[t,100*(0===n?2*o/(i+o):2*r/(n+r)),100*((n+r)/2)]},r.hsv.rgb=function(e){const t=e[0]/60,r=e[1]/100;let n=e[2]/100;const o=Math.floor(t)%6,i=t-Math.floor(t),s=255*n*(1-r),a=255*n*(1-r*i),c=255*n*(1-r*(1-i));switch(n*=255,o){case 0:return[n,c,s];case 1:return[a,n,s];case 2:return[s,n,c];case 3:return[s,a,n];case 4:return[c,s,n];case 5:return[n,s,a]}},r.hsv.hsl=function(e){const t=e[0],r=e[1]/100,n=e[2]/100,o=Math.max(n,.01);let i,s;s=(2-r)*n;const a=(2-r)*o;return i=r*o,i/=a<=1?a:2-a,i=i||0,s/=2,[t,100*i,100*s]},r.hwb.rgb=function(e){const t=e[0]/360;let r=e[1]/100,n=e[2]/100;const o=r+n;let i;o>1&&(r/=o,n/=o);const s=Math.floor(6*t),a=1-n;i=6*t-s,1&s&&(i=1-i);const c=r+i*(a-r);let l,u,h;switch(s){default:case 6:case 0:l=a,u=c,h=r;break;case 1:l=c,u=a,h=r;break;case 2:l=r,u=a,h=c;break;case 3:l=r,u=c,h=a;break;case 4:l=c,u=r,h=a;break;case 5:l=a,u=r,h=c}return[255*l,255*u,255*h]},r.cmyk.rgb=function(e){const t=e[0]/100,r=e[1]/100,n=e[2]/100,o=e[3]/100;return[255*(1-Math.min(1,t*(1-o)+o)),255*(1-Math.min(1,r*(1-o)+o)),255*(1-Math.min(1,n*(1-o)+o))]},r.xyz.rgb=function(e){const t=e[0]/100,r=e[1]/100,n=e[2]/100;let o,i,s;return o=3.2406*t+-1.5372*r+-.4986*n,i=-.9689*t+1.8758*r+.0415*n,s=.0557*t+-.204*r+1.057*n,o=o>.0031308?1.055*o**(1/2.4)-.055:12.92*o,i=i>.0031308?1.055*i**(1/2.4)-.055:12.92*i,s=s>.0031308?1.055*s**(1/2.4)-.055:12.92*s,o=Math.min(Math.max(0,o),1),i=Math.min(Math.max(0,i),1),s=Math.min(Math.max(0,s),1),[255*o,255*i,255*s]},r.xyz.lab=function(e){let t=e[0],r=e[1],n=e[2];t/=95.047,r/=100,n/=108.883,t=t>.008856?t**(1/3):7.787*t+16/116,r=r>.008856?r**(1/3):7.787*r+16/116,n=n>.008856?n**(1/3):7.787*n+16/116;return[116*r-16,500*(t-r),200*(r-n)]},r.lab.xyz=function(e){let t,r,n;r=(e[0]+16)/116,t=e[1]/500+r,n=r-e[2]/200;const o=r**3,i=t**3,s=n**3;return r=o>.008856?o:(r-16/116)/7.787,t=i>.008856?i:(t-16/116)/7.787,n=s>.008856?s:(n-16/116)/7.787,t*=95.047,r*=100,n*=108.883,[t,r,n]},r.lab.lch=function(e){const t=e[0],r=e[1],n=e[2];let o;o=360*Math.atan2(n,r)/2/Math.PI,o<0&&(o+=360);return[t,Math.sqrt(r*r+n*n),o]},r.lch.lab=function(e){const t=e[0],r=e[1],n=e[2]/360*2*Math.PI;return[t,r*Math.cos(n),r*Math.sin(n)]},r.rgb.ansi16=function(e,t=null){const[n,o,i]=e;let s=null===t?r.rgb.hsv(e)[2]:t;if(s=Math.round(s/50),0===s)return 30;let a=30+(Math.round(i/255)<<2|Math.round(o/255)<<1|Math.round(n/255));return 2===s&&(a+=60),a},r.hsv.ansi16=function(e){return r.rgb.ansi16(r.hsv.rgb(e),e[2])},r.rgb.ansi256=function(e){const t=e[0],r=e[1],n=e[2];if(t===r&&r===n)return t<8?16:t>248?231:Math.round((t-8)/247*24)+232;return 16+36*Math.round(t/255*5)+6*Math.round(r/255*5)+Math.round(n/255*5)},r.ansi16.rgb=function(e){let t=e%10;if(0===t||7===t)return e>50&&(t+=3.5),t=t/10.5*255,[t,t,t];const r=.5*(1+~~(e>50));return[(1&t)*r*255,(t>>1&1)*r*255,(t>>2&1)*r*255]},r.ansi256.rgb=function(e){if(e>=232){const t=10*(e-232)+8;return[t,t,t]}let t;e-=16;return[Math.floor(e/36)/5*255,Math.floor((t=e%36)/6)/5*255,t%6/5*255]},r.rgb.hex=function(e){const t=(((255&Math.round(e[0]))<<16)+((255&Math.round(e[1]))<<8)+(255&Math.round(e[2]))).toString(16).toUpperCase();return"000000".substring(t.length)+t},r.hex.rgb=function(e){const t=e.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!t)return[0,0,0];let r=t[0];3===t[0].length&&(r=r.split("").map(e=>e+e).join(""));const n=parseInt(r,16);return[n>>16&255,n>>8&255,255&n]},r.rgb.hcg=function(e){const t=e[0]/255,r=e[1]/255,n=e[2]/255,o=Math.max(Math.max(t,r),n),i=Math.min(Math.min(t,r),n),s=o-i;let a,c;return a=s<1?i/(1-s):0,c=s<=0?0:o===t?(r-n)/s%6:o===r?2+(n-t)/s:4+(t-r)/s,c/=6,c%=1,[360*c,100*s,100*a]},r.hsl.hcg=function(e){const t=e[1]/100,r=e[2]/100,n=r<.5?2*t*r:2*t*(1-r);let o=0;return n<1&&(o=(r-.5*n)/(1-n)),[e[0],100*n,100*o]},r.hsv.hcg=function(e){const t=e[1]/100,r=e[2]/100,n=t*r;let o=0;return n<1&&(o=(r-n)/(1-n)),[e[0],100*n,100*o]},r.hcg.rgb=function(e){const t=e[0]/360,r=e[1]/100,n=e[2]/100;if(0===r)return[255*n,255*n,255*n];const o=[0,0,0],i=t%1*6,s=i%1,a=1-s;let c=0;switch(Math.floor(i)){case 0:o[0]=1,o[1]=s,o[2]=0;break;case 1:o[0]=a,o[1]=1,o[2]=0;break;case 2:o[0]=0,o[1]=1,o[2]=s;break;case 3:o[0]=0,o[1]=a,o[2]=1;break;case 4:o[0]=s,o[1]=0,o[2]=1;break;default:o[0]=1,o[1]=0,o[2]=a}return c=(1-r)*n,[255*(r*o[0]+c),255*(r*o[1]+c),255*(r*o[2]+c)]},r.hcg.hsv=function(e){const t=e[1]/100,r=t+e[2]/100*(1-t);let n=0;return r>0&&(n=t/r),[e[0],100*n,100*r]},r.hcg.hsl=function(e){const t=e[1]/100,r=e[2]/100*(1-t)+.5*t;let n=0;return r>0&&r<.5?n=t/(2*r):r>=.5&&r<1&&(n=t/(2*(1-r))),[e[0],100*n,100*r]},r.hcg.hwb=function(e){const t=e[1]/100,r=t+e[2]/100*(1-t);return[e[0],100*(r-t),100*(1-r)]},r.hwb.hcg=function(e){const t=e[1]/100,r=1-e[2]/100,n=r-t;let o=0;return n<1&&(o=(r-n)/(1-n)),[e[0],100*n,100*o]},r.apple.rgb=function(e){return[e[0]/65535*255,e[1]/65535*255,e[2]/65535*255]},r.rgb.apple=function(e){return[e[0]/255*65535,e[1]/255*65535,e[2]/255*65535]},r.gray.rgb=function(e){return[e[0]/100*255,e[0]/100*255,e[0]/100*255]},r.gray.hsl=function(e){return[0,0,e[0]]},r.gray.hsv=r.gray.hsl,r.gray.hwb=function(e){return[0,100,e[0]]},r.gray.cmyk=function(e){return[0,0,0,e[0]]},r.gray.lab=function(e){return[e[0],0,0]},r.gray.hex=function(e){const t=255&Math.round(e[0]/100*255),r=((t<<16)+(t<<8)+t).toString(16).toUpperCase();return"000000".substring(r.length)+r},r.rgb.gray=function(e){return[(e[0]+e[1]+e[2])/3/255*100]},Dt}function Qt(){if(jt)return Mt;jt=1;const e=Yt();function t(t){const r=function(){const t={},r=Object.keys(e);for(let e=r.length,n=0;n<e;n++)t[r[n]]={distance:-1,parent:null};return t}(),n=[t];for(r[t].distance=0;n.length;){const t=n.pop(),o=Object.keys(e[t]);for(let e=o.length,i=0;i<e;i++){const e=o[i],s=r[e];-1===s.distance&&(s.distance=r[t].distance+1,s.parent=t,n.unshift(e))}}return r}function r(e,t){return function(r){return t(e(r))}}function n(t,n){const o=[n[t].parent,t];let i=e[n[t].parent][t],s=n[t].parent;for(;n[s].parent;)o.unshift(n[s].parent),i=r(e[n[s].parent][s],i),s=n[s].parent;return i.conversion=o,i}return Mt=function(e){const r=t(e),o={},i=Object.keys(r);for(let e=i.length,t=0;t<e;t++){const e=i[t];null!==r[e].parent&&(o[e]=n(e,r))}return o}}function Xt(){if(Ut)return $t;Ut=1;const e=Yt(),t=Qt(),r={};return Object.keys(e).forEach(n=>{r[n]={},Object.defineProperty(r[n],"channels",{value:e[n].channels}),Object.defineProperty(r[n],"labels",{value:e[n].labels});const o=t(n);Object.keys(o).forEach(e=>{const t=o[e];r[n][e]=function(e){const t=function(...t){const r=t[0];if(null==r)return r;r.length>1&&(t=r);const n=e(t);if("object"==typeof n)for(let e=n.length,t=0;t<e;t++)n[t]=Math.round(n[t]);return n};return"conversion"in e&&(t.conversion=e.conversion),t}(t),r[n][e].raw=function(e){const t=function(...t){const r=t[0];return null==r?r:(r.length>1&&(t=r),e(t))};return"conversion"in e&&(t.conversion=e.conversion),t}(t)})}),$t=r}function Zt(){return Lt||(Lt=1,function(e){const t=(e,t)=>(...r)=>`[${e(...r)+t}m`,r=(e,t)=>(...r)=>{const n=e(...r);return`[${38+t};5;${n}m`},n=(e,t)=>(...r)=>{const n=e(...r);return`[${38+t};2;${n[0]};${n[1]};${n[2]}m`},o=e=>e,i=(e,t,r)=>[e,t,r],s=(e,t,r)=>{Object.defineProperty(e,t,{get:()=>{const n=r();return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0}),n},enumerable:!0,configurable:!0})};let a;const c=(e,t,r,n)=>{void 0===a&&(a=Xt());const o=n?10:0,i={};for(const[n,s]of Object.entries(a)){const a="ansi16"===n?"ansi":n;n===t?i[a]=e(r,o):"object"==typeof s&&(i[a]=e(s[t],o))}return i};Object.defineProperty(e,"exports",{enumerable:!0,get:function(){const e=new Map,a={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};a.color.gray=a.color.blackBright,a.bgColor.bgGray=a.bgColor.bgBlackBright,a.color.grey=a.color.blackBright,a.bgColor.bgGrey=a.bgColor.bgBlackBright;for(const[t,r]of Object.entries(a)){for(const[t,n]of Object.entries(r))a[t]={open:`[${n[0]}m`,close:`[${n[1]}m`},r[t]=a[t],e.set(n[0],n[1]);Object.defineProperty(a,t,{value:r,enumerable:!1})}return Object.defineProperty(a,"codes",{value:e,enumerable:!1}),a.color.close="",a.bgColor.close="",s(a.color,"ansi",()=>c(t,"ansi16",o,!1)),s(a.color,"ansi256",()=>c(r,"ansi256",o,!1)),s(a.color,"ansi16m",()=>c(n,"rgb",i,!1)),s(a.bgColor,"ansi",()=>c(t,"ansi16",o,!0)),s(a.bgColor,"ansi256",()=>c(r,"ansi256",o,!0)),s(a.bgColor,"ansi16m",()=>c(n,"rgb",i,!0)),a}})}(zt)),zt.exports}function er(e,t="",r={}){for(let n in e){const o=t?`${t}.${n}`:n;"object"==typeof e[n]&&null!==e[n]?er(e[n],o,r):r[o]=e[n]}return r}!function(){if(Gt)return Jt;Gt=1;const e=Zt(),{stdout:t,stderr:r}=Wt?Ht:(Wt=1,Ht={stdout:!1,stderr:!1}),{stringReplaceAll:n,stringEncaseCRLFWithFirstIndex:o}=Ft?qt:(Ft=1,qt={stringReplaceAll:(e,t,r)=>{let n=e.indexOf(t);if(-1===n)return e;const o=t.length;let i=0,s="";do{s+=e.substr(i,n-i)+t+r,i=n+o,n=e.indexOf(t,i)}while(-1!==n);return s+=e.substr(i),s},stringEncaseCRLFWithFirstIndex:(e,t,r,n)=>{let o=0,i="";do{const s="\r"===e[n-1];i+=e.substr(o,(s?n-1:n)-o)+t+(s?"\r\n":"\n")+r,o=n+1,n=e.indexOf("\n",o)}while(-1!==n);return i+=e.substr(o),i}}),{isArray:i}=Array,s=["ansi","ansi","ansi256","ansi16m"],a=Object.create(null);class c{constructor(e){return l(e)}}const l=e=>{const r={};return((e,r={})=>{if(r.level&&!(Number.isInteger(r.level)&&r.level>=0&&r.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const n=t?t.level:0;e.level=void 0===r.level?n:r.level})(r,e),r.template=(...e)=>y(r.template,...e),Object.setPrototypeOf(r,u.prototype),Object.setPrototypeOf(r.template,r),r.template.constructor=()=>{throw new Error("`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.")},r.template.Instance=c,r.template};function u(e){return l(e)}for(const[t,r]of Object.entries(e))a[t]={get(){const e=f(this,p(r.open,r.close,this._styler),this._isEmpty);return Object.defineProperty(this,t,{value:e}),e}};a.visible={get(){const e=f(this,this._styler,!0);return Object.defineProperty(this,"visible",{value:e}),e}};const h=["rgb","hex","keyword","hsl","hsv","hwb","ansi","ansi256"];for(const t of h)a[t]={get(){const{level:r}=this;return function(...n){const o=p(e.color[s[r]][t](...n),e.color.close,this._styler);return f(this,o,this._isEmpty)}}};for(const t of h){a["bg"+t[0].toUpperCase()+t.slice(1)]={get(){const{level:r}=this;return function(...n){const o=p(e.bgColor[s[r]][t](...n),e.bgColor.close,this._styler);return f(this,o,this._isEmpty)}}}}const d=Object.defineProperties(()=>{},{...a,level:{enumerable:!0,get(){return this._generator.level},set(e){this._generator.level=e}}}),p=(e,t,r)=>{let n,o;return void 0===r?(n=e,o=t):(n=r.openAll+e,o=t+r.closeAll),{open:e,close:t,openAll:n,closeAll:o,parent:r}},f=(e,t,r)=>{const n=(...e)=>i(e[0])&&i(e[0].raw)?g(n,y(n,...e)):g(n,1===e.length?""+e[0]:e.join(" "));return Object.setPrototypeOf(n,d),n._generator=e,n._styler=t,n._isEmpty=r,n},g=(e,t)=>{if(e.level<=0||!t)return e._isEmpty?"":t;let r=e._styler;if(void 0===r)return t;const{openAll:i,closeAll:s}=r;if(-1!==t.indexOf(""))for(;void 0!==r;)t=n(t,r.close,r.open),r=r.parent;const a=t.indexOf("\n");return-1!==a&&(t=o(t,s,i,a)),i+t+s};let m;const y=(e,...t)=>{const[r]=t;if(!i(r)||!i(r.raw))return t.join(" ");const n=t.slice(1),o=[r.raw[0]];for(let e=1;e<r.length;e++)o.push(String(n[e-1]).replace(/[{}\\]/g,"\\$&"),String(r.raw[e]));return void 0===m&&(m=function(){if(Bt)return Vt;Bt=1;const e=/(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi,t=/(?:^|\.)(\w+)(?:\(([^)]*)\))?/g,r=/^(['"])((?:\\.|(?!\1)[^\\])*)\1$/,n=/\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi,o=new Map([["n","\n"],["r","\r"],["t","\t"],["b","\b"],["f","\f"],["v","\v"],["0","\0"],["\\","\\"],["e",""],["a",""]]);function i(e){const t="u"===e[0],r="{"===e[1];return t&&!r&&5===e.length||"x"===e[0]&&3===e.length?String.fromCharCode(parseInt(e.slice(1),16)):t&&r?String.fromCodePoint(parseInt(e.slice(2,-1),16)):o.get(e)||e}function s(e,t){const o=[],s=t.trim().split(/\s*,\s*/g);let a;for(const t of s){const s=Number(t);if(Number.isNaN(s)){if(!(a=t.match(r)))throw new Error(`Invalid Chalk template style argument: ${t} (in style '${e}')`);o.push(a[2].replace(n,(e,t,r)=>t?i(t):r))}else o.push(s)}return o}function a(e){t.lastIndex=0;const r=[];let n;for(;null!==(n=t.exec(e));){const e=n[1];if(n[2]){const t=s(e,n[2]);r.push([e].concat(t))}else r.push([e])}return r}function c(e,t){const r={};for(const e of t)for(const t of e.styles)r[t[0]]=e.inverse?null:t.slice(1);let n=e;for(const[e,t]of Object.entries(r))if(Array.isArray(t)){if(!(e in n))throw new Error(`Unknown Chalk style: ${e}`);n=t.length>0?n[e](...t):n[e]}return n}return Vt=(t,r)=>{const n=[],o=[];let s=[];if(r.replace(e,(e,r,l,u,h,d)=>{if(r)s.push(i(r));else if(u){const e=s.join("");s=[],o.push(0===n.length?e:c(t,n)(e)),n.push({inverse:l,styles:a(u)})}else if(h){if(0===n.length)throw new Error("Found extraneous } in Chalk template literal");o.push(c(t,n)(s.join(""))),s=[],n.pop()}else s.push(d)}),o.push(s.join("")),n.length>0){const e=`Chalk template literal is missing ${n.length} closing bracket${1===n.length?"":"s"} (\`}\`)`;throw new Error(e)}return o.join("")}}()),m(e,o.join(""))};Object.defineProperties(u.prototype,a);const b=u();b.supportsColor=t,b.stderr=u({level:r?r.level:0}),b.stderr.supportsColor=r,Jt=b}();var tr="1.51.4-next.0";const rr=`https://copilotkit.gateway.scarf.sh/${tr}`;var nr=new class{constructor(){}async logEvent(e){try{const t=new AbortController,r=setTimeout(()=>t.abort(),3e3),n=new URLSearchParams;Object.entries(e).forEach(([e,t])=>{null!=t&&n.append(e,String(t))});const o=`${rr}?${n.toString()}`,i=await fetch(o,{method:"GET",signal:t.signal});if(clearTimeout(r),!i.ok)throw new Error(`HTTP error! status: ${i.status}`)}catch(e){}}};function or(){return"true"===process.env.COPILOTKIT_TELEMETRY_DISABLED||"1"===process.env.COPILOTKIT_TELEMETRY_DISABLED||"true"===process.env.DO_NOT_TRACK||"1"===process.env.DO_NOT_TRACK}const ir=tr;var sr,ar={exports:{}};var cr=(sr||(sr=1,function(e,t){var r=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==kt)return kt;throw new Error("unable to locate global object")}();e.exports=t=r.fetch,r.fetch&&(t.default=r.fetch.bind(r)),t.Headers=r.Headers,t.Request=r.Request,t.Response=r.Response}(ar,ar.exports)),ar.exports),lr=o({__proto__:null,default:Pt(cr)},[cr]);e.BANNER_ERROR_NAMES=g,e.COPILOTKIT_VERSION=ir,e.COPILOT_CLOUD_API_URL=D,e.COPILOT_CLOUD_CHAT_URL=K,e.COPILOT_CLOUD_ERROR_NAMES=m,e.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER="X-CopilotCloud-Public-Api-Key",e.COPILOT_CLOUD_VERSION="v1",e.ConfigurationError=I,e.ConsoleColors=s,e.ConsoleStyles=a,e.CopilotKitAgentDiscoveryError=class extends _{constructor(t){const{agentName:r,availableAgents:n}=t,o=e.CopilotKitErrorCode.AGENT_NOT_FOUND,i=v(E[o].troubleshootingUrl);let s;if(n.length){const e=n.map(e=>e.name).join(", ");s=r?`Agent '${r}' was not found. Available agents are: ${e}. Please verify the agent name in your configuration and ensure it matches one of the available agents.\n\n${i}`:`The requested agent was not found. Available agents are: ${e}. Please verify the agent name in your configuration and ensure it matches one of the available agents.\n\n${i}`}else s=`${r?`Agent '${r}'`:"The requested agent"} was not found. Please set up at least one agent before proceeding. ${i}`;super({message:s,code:o}),this.name=f.COPILOT_KIT_AGENT_DISCOVERY_ERROR}},e.CopilotKitApiDiscoveryError=R,e.CopilotKitError=_,e.CopilotKitLowLevelError=C,e.CopilotKitMisuseError=class extends _{constructor({message:t,code:r=e.CopilotKitErrorCode.MISUSE}){const n="troubleshootingUrl"in E[r]&&E[r].troubleshootingUrl?v(E[r].troubleshootingUrl):null;super({message:n?`${t}.\n\n${n}`:t,code:r}),this.name=f.COPILOT_API_DISCOVERY_ERROR}},e.CopilotKitRemoteEndpointDiscoveryError=O,e.CopilotKitVersionMismatchError=class extends _{constructor({reactCoreVersion:t,runtimeVersion:r,runtimeClientGqlVersion:n}){const o=e.CopilotKitErrorCode.VERSION_MISMATCH;super({message:w({reactCoreVersion:t,runtimeVersion:r,runtimeClientGqlVersion:n}),code:o}),this.name=f.COPILOT_KIT_VERSION_MISMATCH_ERROR}},e.ERROR_CONFIG=E,e.ERROR_NAMES=f,e.MissingPublicApiKeyError=class extends I{constructor(t){super(t),this.name=f.MISSING_PUBLIC_API_KEY_ERROR,this.severity=e.Severity.CRITICAL}},e.ResolvedCopilotKitError=class extends _{constructor({status:t,message:r,code:n,isRemoteEndpoint:o,url:i}){let s=n;if(!s)switch(t){case 400:throw new R({message:r,url:i});case 404:throw o?new O({message:r,url:i}):new R({message:r,url:i});default:s=e.CopilotKitErrorCode.UNKNOWN}super({message:r,code:s}),this.name=f.RESOLVED_COPILOT_KIT_ERROR}},e.TelemetryClient=class{constructor({packageName:e,packageVersion:t,telemetryDisabled:n,telemetryBaseUrl:o,sampleRate:i}){if(this.globalProperties={},this.cloudConfiguration=null,this.telemetryDisabled=!1,this.sampleRate=.05,this.anonymousId=`anon_${r.v4()}`,this.packageName=e,this.packageVersion=t,this.telemetryDisabled=n||or(),this.telemetryDisabled)return;this.setSampleRate(i);const s=process.env.COPILOTKIT_SEGMENT_WRITE_KEY||"n7XAZtQCGS2v1vvBy3LgBCv2h3Y8whja";this.segment=new At({writeKey:s}),this.setGlobalProperties({"copilotkit.package.name":e,"copilotkit.package.version":t})}shouldSendEvent(){return Math.random()<this.sampleRate}async capture(e,t){if(!this.shouldSendEvent()||!this.segment)return;const r=er(t),n=Object.assign(Object.assign({},this.globalProperties),r),o=Object.keys(n).sort().reduce((e,t)=>(e[t]=n[t],e),{});this.segment.track({anonymousId:this.anonymousId,event:e,properties:Object.assign({},o)}),await nr.logEvent({event:e})}setGlobalProperties(e){const t=er(e);this.globalProperties=Object.assign(Object.assign({},this.globalProperties),t)}setCloudConfiguration(e){this.cloudConfiguration=e,this.setGlobalProperties({cloud:{publicApiKey:e.publicApiKey,baseUrl:e.baseUrl}})}setSampleRate(e){let t;if(t=null!=e?e:.05,process.env.COPILOTKIT_TELEMETRY_SAMPLE_RATE&&(t=parseFloat(process.env.COPILOTKIT_TELEMETRY_SAMPLE_RATE)),t<0||t>1)throw new Error("Sample rate must be between 0 and 1");this.sampleRate=t,this.setGlobalProperties({sampleRate:this.sampleRate,sampleRateAdjustmentFactor:1-this.sampleRate,sampleWeight:1/this.sampleRate})}},e.UpgradeRequiredError=class extends I{constructor(t){super(t),this.name=f.UPGRADE_REQUIRED_ERROR,this.severity=e.Severity.WARNING}},e.actionParametersToJsonSchema=A,e.convertJsonSchemaToZodSchema=N,e.dataToUUID=function(e,t){const n="e4b01160-ff74-4c6e-9b27-d53cd930fe8e",o=t?r.v5(t,n):n,i="string"==typeof e?e:JSON.stringify(x(e));return r.v5(i,o)},e.ensureStructuredError=function(e,t){return S(e)?e:t(e)},e.executeConditions=function({conditions:e,value:t}){return!(null==e?void 0:e.length)||e.every(e=>i(e,t))},e.getPossibleVersionMismatch=async function({runtimeVersion:e,runtimeClientGqlVersion:t}){if(e&&""!==e&&t)return ir!==e||ir!==t||e!==t?{runtimeVersion:e,runtimeClientGqlVersion:t,reactCoreVersion:ir,message:w({runtimeVersion:e,runtimeClientGqlVersion:t,reactCoreVersion:ir})}:void 0},e.getZodParameters=function(e){return e?N(A(e),!0):n.z.object({})},e.isMacOS=function(){return/Mac|iMac|Macintosh/i.test(navigator.userAgent)},e.isStructuredCopilotKitError=S,e.isTelemetryDisabled=or,e.isValidUUID=function(e){return r.validate(e)},e.jsonSchemaToActionParameters=function(e){if("object"!==e.type||!e.properties)return[];const t=[],r=e.required||[];for(const[n,o]of Object.entries(e.properties)){const e=k(n,o,r.includes(n));t.push(e)}return t},e.logCopilotKitPlatformMessage=c,e.logStyled=u,e.parseJson=function(e,t="unset"){try{return JSON.parse(e)}catch(e){return"unset"===t?null:t}},e.publicApiKeyRequired=l,e.randomId=function(){return"ck-"+r.v4()},e.randomUUID=function(){return r.v4()},e.readBody=async function(e){var t;const r="method"in e?e.method.toUpperCase():void 0;if("GET"!==r&&"HEAD"!==r&&"body"in e&&null!=e.body)try{return await e.clone().json()}catch(r){try{const t=await e.clone().text(),r=t.trim();if(0===r.length)return t;if(r.startsWith("{")||r.startsWith("["))try{return JSON.parse(r)}catch(e){return t}return t}catch(r){try{const r=null!==(t=e.clone().body)&&void 0!==t?t:null;if(!r)return;const n=r.getReader(),o=new TextDecoder;let i="";for(;;){const{done:e,value:t}=await n.read();if(e)break;i+="string"==typeof t?t:o.decode(t,{stream:!0})}i+=o.decode();const s=i.trim();if(0===s.length)return i;if(s.startsWith("{")||s.startsWith("["))try{return JSON.parse(s)}catch(e){return i}return i}catch(e){return}}}},e.styledConsole=h,e.tryMap=function(e,t){return e.reduce((e,r,n,o)=>{try{e.push(t(r,n,o))}catch(e){console.error(e)}return e},[])}});
2
2
  //# sourceMappingURL=index.umd.js.map