@copilotkit/shared 1.51.5-next.0 → 1.51.5-next.2

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.
Files changed (254) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/_virtual/_rolldown/runtime.cjs +29 -0
  3. package/dist/constants/index.cjs +13 -0
  4. package/dist/constants/index.cjs.map +1 -0
  5. package/dist/constants/{index.d.ts → index.d.cts} +3 -1
  6. package/dist/constants/index.d.cts.map +1 -0
  7. package/dist/constants/index.d.mts +8 -0
  8. package/dist/constants/index.d.mts.map +1 -0
  9. package/dist/constants/index.mjs +8 -12
  10. package/dist/constants/index.mjs.map +1 -1
  11. package/dist/index.cjs +64 -0
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.d.cts +22 -0
  14. package/dist/index.d.cts.map +1 -0
  15. package/dist/index.d.mts +23 -0
  16. package/dist/index.d.mts.map +1 -0
  17. package/dist/index.mjs +16 -123
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/index.umd.js +1017 -2
  20. package/dist/index.umd.js.map +1 -1
  21. package/dist/package.cjs +12 -0
  22. package/dist/package.cjs.map +1 -0
  23. package/dist/package.mjs +6 -0
  24. package/dist/package.mjs.map +1 -0
  25. package/dist/telemetry/events.d.cts +47 -0
  26. package/dist/telemetry/events.d.cts.map +1 -0
  27. package/dist/telemetry/events.d.mts +47 -0
  28. package/dist/telemetry/events.d.mts.map +1 -0
  29. package/dist/telemetry/index.d.mts +1 -0
  30. package/dist/telemetry/scarf-client.cjs +29 -0
  31. package/dist/telemetry/scarf-client.cjs.map +1 -0
  32. package/dist/telemetry/scarf-client.mjs +27 -5
  33. package/dist/telemetry/scarf-client.mjs.map +1 -1
  34. package/dist/telemetry/telemetry-client.cjs +87 -0
  35. package/dist/telemetry/telemetry-client.cjs.map +1 -0
  36. package/dist/telemetry/telemetry-client.d.cts +48 -0
  37. package/dist/telemetry/telemetry-client.d.cts.map +1 -0
  38. package/dist/telemetry/telemetry-client.d.mts +48 -0
  39. package/dist/telemetry/telemetry-client.d.mts.map +1 -0
  40. package/dist/telemetry/telemetry-client.mjs +83 -9
  41. package/dist/telemetry/telemetry-client.mjs.map +1 -1
  42. package/dist/telemetry/utils.cjs +16 -0
  43. package/dist/telemetry/utils.cjs.map +1 -0
  44. package/dist/telemetry/utils.mjs +14 -8
  45. package/dist/telemetry/utils.mjs.map +1 -1
  46. package/dist/types/{action.d.ts → action.d.cts} +32 -32
  47. package/dist/types/action.d.cts.map +1 -0
  48. package/dist/types/action.d.mts +59 -0
  49. package/dist/types/action.d.mts.map +1 -0
  50. package/dist/types/copilot-cloud-config.d.cts +15 -0
  51. package/dist/types/copilot-cloud-config.d.cts.map +1 -0
  52. package/dist/types/copilot-cloud-config.d.mts +15 -0
  53. package/dist/types/copilot-cloud-config.d.mts.map +1 -0
  54. package/dist/types/error.d.cts +57 -0
  55. package/dist/types/error.d.cts.map +1 -0
  56. package/dist/types/error.d.mts +57 -0
  57. package/dist/types/error.d.mts.map +1 -0
  58. package/dist/types/{message.d.ts → message.d.cts} +14 -12
  59. package/dist/types/message.d.cts.map +1 -0
  60. package/dist/types/message.d.mts +31 -0
  61. package/dist/types/message.d.mts.map +1 -0
  62. package/dist/types/openai-assistant.d.cts +55 -0
  63. package/dist/types/openai-assistant.d.cts.map +1 -0
  64. package/dist/types/openai-assistant.d.mts +55 -0
  65. package/dist/types/openai-assistant.d.mts.map +1 -0
  66. package/dist/types/utility.d.cts +6 -0
  67. package/dist/types/utility.d.cts.map +1 -0
  68. package/dist/types/utility.d.mts +6 -0
  69. package/dist/types/utility.d.mts.map +1 -0
  70. package/dist/utils/conditions.cjs +32 -0
  71. package/dist/utils/conditions.cjs.map +1 -0
  72. package/dist/utils/{conditions.d.ts → conditions.d.cts} +16 -11
  73. package/dist/utils/conditions.d.cts.map +1 -0
  74. package/dist/utils/conditions.d.mts +31 -0
  75. package/dist/utils/conditions.d.mts.map +1 -0
  76. package/dist/utils/conditions.mjs +30 -6
  77. package/dist/utils/conditions.mjs.map +1 -1
  78. package/dist/utils/console-styling.cjs +91 -0
  79. package/dist/utils/console-styling.cjs.map +1 -0
  80. package/dist/utils/console-styling.d.cts +65 -0
  81. package/dist/utils/console-styling.d.cts.map +1 -0
  82. package/dist/utils/console-styling.d.mts +65 -0
  83. package/dist/utils/console-styling.d.mts.map +1 -0
  84. package/dist/utils/console-styling.mjs +83 -15
  85. package/dist/utils/console-styling.mjs.map +1 -1
  86. package/dist/utils/errors.cjs +439 -0
  87. package/dist/utils/errors.cjs.map +1 -0
  88. package/dist/utils/{errors.d.ts → errors.d.cts} +188 -156
  89. package/dist/utils/errors.d.cts.map +1 -0
  90. package/dist/utils/errors.d.mts +312 -0
  91. package/dist/utils/errors.d.mts.map +1 -0
  92. package/dist/utils/errors.mjs +416 -63
  93. package/dist/utils/errors.mjs.map +1 -1
  94. package/dist/utils/index.cjs +50 -0
  95. package/dist/utils/index.cjs.map +1 -0
  96. package/dist/utils/{index.d.ts → index.d.cts} +10 -11
  97. package/dist/utils/index.d.cts.map +1 -0
  98. package/dist/utils/index.d.mts +31 -0
  99. package/dist/utils/index.d.mts.map +1 -0
  100. package/dist/utils/index.mjs +47 -107
  101. package/dist/utils/index.mjs.map +1 -1
  102. package/dist/utils/json-schema.cjs +157 -0
  103. package/dist/utils/json-schema.cjs.map +1 -0
  104. package/dist/utils/{json-schema.d.ts → json-schema.d.cts} +19 -17
  105. package/dist/utils/json-schema.d.cts.map +1 -0
  106. package/dist/utils/json-schema.d.mts +36 -0
  107. package/dist/utils/json-schema.d.mts.map +1 -0
  108. package/dist/utils/json-schema.mjs +152 -12
  109. package/dist/utils/json-schema.mjs.map +1 -1
  110. package/dist/utils/random-id.cjs +38 -0
  111. package/dist/utils/random-id.cjs.map +1 -0
  112. package/dist/utils/{random-id.d.ts → random-id.d.cts} +3 -1
  113. package/dist/utils/random-id.d.cts.map +1 -0
  114. package/dist/utils/random-id.d.mts +8 -0
  115. package/dist/utils/random-id.d.mts.map +1 -0
  116. package/dist/utils/random-id.mjs +33 -12
  117. package/dist/utils/random-id.mjs.map +1 -1
  118. package/dist/utils/requests.cjs +58 -0
  119. package/dist/utils/requests.cjs.map +1 -0
  120. package/dist/utils/{requests.d.ts → requests.d.cts} +3 -1
  121. package/dist/utils/requests.d.cts.map +1 -0
  122. package/dist/utils/requests.d.mts +12 -0
  123. package/dist/utils/requests.d.mts.map +1 -0
  124. package/dist/utils/requests.mjs +56 -6
  125. package/dist/utils/requests.mjs.map +1 -1
  126. package/dist/utils/{types.d.ts → types.d.cts} +9 -7
  127. package/dist/utils/types.d.cts.map +1 -0
  128. package/dist/utils/types.d.mts +22 -0
  129. package/dist/utils/types.d.mts.map +1 -0
  130. package/package.json +16 -14
  131. package/tsdown.config.ts +36 -0
  132. package/vitest.config.mjs +11 -0
  133. package/dist/chunk-2OJ5OJ2D.mjs +0 -1
  134. package/dist/chunk-2OJ5OJ2D.mjs.map +0 -1
  135. package/dist/chunk-3DK3UMRW.mjs +0 -217
  136. package/dist/chunk-3DK3UMRW.mjs.map +0 -1
  137. package/dist/chunk-7KOT4KP4.mjs +0 -435
  138. package/dist/chunk-7KOT4KP4.mjs.map +0 -1
  139. package/dist/chunk-DE5XAMMI.mjs +0 -110
  140. package/dist/chunk-DE5XAMMI.mjs.map +0 -1
  141. package/dist/chunk-FCCOSO5L.mjs +0 -1
  142. package/dist/chunk-FCCOSO5L.mjs.map +0 -1
  143. package/dist/chunk-GS5BLXSZ.mjs +0 -41
  144. package/dist/chunk-GS5BLXSZ.mjs.map +0 -1
  145. package/dist/chunk-IAFBVORQ.mjs +0 -1
  146. package/dist/chunk-IAFBVORQ.mjs.map +0 -1
  147. package/dist/chunk-M2RJI5BZ.mjs +0 -94
  148. package/dist/chunk-M2RJI5BZ.mjs.map +0 -1
  149. package/dist/chunk-MSUB6DGR.mjs +0 -1
  150. package/dist/chunk-MSUB6DGR.mjs.map +0 -1
  151. package/dist/chunk-N5EP5OD5.mjs +0 -1
  152. package/dist/chunk-N5EP5OD5.mjs.map +0 -1
  153. package/dist/chunk-NAFEBKSO.mjs +0 -1
  154. package/dist/chunk-NAFEBKSO.mjs.map +0 -1
  155. package/dist/chunk-P7STFMPO.mjs +0 -1
  156. package/dist/chunk-P7STFMPO.mjs.map +0 -1
  157. package/dist/chunk-UYARLQNA.mjs +0 -1
  158. package/dist/chunk-UYARLQNA.mjs.map +0 -1
  159. package/dist/chunk-V7BSERGI.mjs +0 -62
  160. package/dist/chunk-V7BSERGI.mjs.map +0 -1
  161. package/dist/chunk-WAZHII6M.mjs +0 -67
  162. package/dist/chunk-WAZHII6M.mjs.map +0 -1
  163. package/dist/chunk-XTHC46M2.mjs +0 -1
  164. package/dist/chunk-XTHC46M2.mjs.map +0 -1
  165. package/dist/chunk-ZI7ZVRL3.mjs +0 -38
  166. package/dist/chunk-ZI7ZVRL3.mjs.map +0 -1
  167. package/dist/chunk-ZIC6V6S5.mjs +0 -13
  168. package/dist/chunk-ZIC6V6S5.mjs.map +0 -1
  169. package/dist/chunk-ZUE2VR7D.mjs +0 -38
  170. package/dist/chunk-ZUE2VR7D.mjs.map +0 -1
  171. package/dist/constants/index.js +0 -40
  172. package/dist/constants/index.js.map +0 -1
  173. package/dist/index.d.ts +0 -25
  174. package/dist/index.js +0 -1138
  175. package/dist/index.js.map +0 -1
  176. package/dist/telemetry/events.d.ts +0 -45
  177. package/dist/telemetry/events.js +0 -19
  178. package/dist/telemetry/events.js.map +0 -1
  179. package/dist/telemetry/events.mjs +0 -1
  180. package/dist/telemetry/events.mjs.map +0 -1
  181. package/dist/telemetry/index.d.ts +0 -3
  182. package/dist/telemetry/index.js +0 -191
  183. package/dist/telemetry/index.js.map +0 -1
  184. package/dist/telemetry/index.mjs +0 -12
  185. package/dist/telemetry/index.mjs.map +0 -1
  186. package/dist/telemetry/scarf-client.d.ts +0 -7
  187. package/dist/telemetry/scarf-client.js +0 -59
  188. package/dist/telemetry/scarf-client.js.map +0 -1
  189. package/dist/telemetry/security-check.d.ts +0 -2
  190. package/dist/telemetry/security-check.js +0 -2
  191. package/dist/telemetry/security-check.js.map +0 -1
  192. package/dist/telemetry/security-check.mjs +0 -1
  193. package/dist/telemetry/security-check.mjs.map +0 -1
  194. package/dist/telemetry/telemetry-client.d.ts +0 -40
  195. package/dist/telemetry/telemetry-client.js +0 -189
  196. package/dist/telemetry/telemetry-client.js.map +0 -1
  197. package/dist/telemetry/utils.d.ts +0 -8
  198. package/dist/telemetry/utils.js +0 -73
  199. package/dist/telemetry/utils.js.map +0 -1
  200. package/dist/types/action.js +0 -19
  201. package/dist/types/action.js.map +0 -1
  202. package/dist/types/action.mjs +0 -2
  203. package/dist/types/action.mjs.map +0 -1
  204. package/dist/types/copilot-cloud-config.d.ts +0 -13
  205. package/dist/types/copilot-cloud-config.js +0 -19
  206. package/dist/types/copilot-cloud-config.js.map +0 -1
  207. package/dist/types/copilot-cloud-config.mjs +0 -2
  208. package/dist/types/copilot-cloud-config.mjs.map +0 -1
  209. package/dist/types/error.d.ts +0 -55
  210. package/dist/types/error.js +0 -19
  211. package/dist/types/error.js.map +0 -1
  212. package/dist/types/error.mjs +0 -2
  213. package/dist/types/error.mjs.map +0 -1
  214. package/dist/types/index.d.ts +0 -7
  215. package/dist/types/index.js +0 -19
  216. package/dist/types/index.js.map +0 -1
  217. package/dist/types/index.mjs +0 -8
  218. package/dist/types/index.mjs.map +0 -1
  219. package/dist/types/message.js +0 -19
  220. package/dist/types/message.js.map +0 -1
  221. package/dist/types/message.mjs +0 -2
  222. package/dist/types/message.mjs.map +0 -1
  223. package/dist/types/openai-assistant.d.ts +0 -53
  224. package/dist/types/openai-assistant.js +0 -19
  225. package/dist/types/openai-assistant.js.map +0 -1
  226. package/dist/types/openai-assistant.mjs +0 -2
  227. package/dist/types/openai-assistant.mjs.map +0 -1
  228. package/dist/types/utility.d.ts +0 -6
  229. package/dist/types/utility.js +0 -19
  230. package/dist/types/utility.js.map +0 -1
  231. package/dist/types/utility.mjs +0 -2
  232. package/dist/types/utility.mjs.map +0 -1
  233. package/dist/utils/conditions.js +0 -86
  234. package/dist/utils/conditions.js.map +0 -1
  235. package/dist/utils/console-styling.d.ts +0 -84
  236. package/dist/utils/console-styling.js +0 -123
  237. package/dist/utils/console-styling.js.map +0 -1
  238. package/dist/utils/errors.js +0 -452
  239. package/dist/utils/errors.js.map +0 -1
  240. package/dist/utils/index.js +0 -964
  241. package/dist/utils/index.js.map +0 -1
  242. package/dist/utils/json-schema.js +0 -244
  243. package/dist/utils/json-schema.js.map +0 -1
  244. package/dist/utils/random-id.js +0 -68
  245. package/dist/utils/random-id.js.map +0 -1
  246. package/dist/utils/requests.js +0 -91
  247. package/dist/utils/requests.js.map +0 -1
  248. package/dist/utils/types.js +0 -19
  249. package/dist/utils/types.js.map +0 -1
  250. package/dist/utils/types.mjs +0 -2
  251. package/dist/utils/types.mjs.map +0 -1
  252. package/jest.config.js +0 -5
  253. package/rollup.config.mjs +0 -54
  254. package/tsup.config.ts +0 -15
package/dist/index.umd.js CHANGED
@@ -1,2 +1,1017 @@
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.5-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
- //# sourceMappingURL=index.umd.js.map
1
+ (function(global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('graphql'), require('zod'), require('uuid'), require('@segment/analytics-node'), require('chalk')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'graphql', 'zod', 'uuid', '@segment/analytics-node', 'chalk'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.CopilotKitShared = {}), global.GraphQL,global.Zod,global.UUID,global.SegmentAnalyticsNode,global.chalk));
5
+ })(this, function(exports, graphql, zod, uuid, _segment_analytics_node, chalk) {
6
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7
+ //#region \0rolldown/runtime.js
8
+ var __create = Object.create;
9
+ var __defProp = Object.defineProperty;
10
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11
+ var __getOwnPropNames = Object.getOwnPropertyNames;
12
+ var __getProtoOf = Object.getPrototypeOf;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __copyProps = (to, from, except, desc) => {
15
+ if (from && typeof from === "object" || typeof from === "function") {
16
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
17
+ key = keys[i];
18
+ if (!__hasOwnProp.call(to, key) && key !== except) {
19
+ __defProp(to, key, {
20
+ get: ((k) => from[k]).bind(null, key),
21
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
22
+ });
23
+ }
24
+ }
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
29
+ value: mod,
30
+ enumerable: true
31
+ }) : target, mod));
32
+
33
+ //#endregion
34
+
35
+ //#region src/utils/conditions.ts
36
+ function executeConditions({ conditions, value }) {
37
+ if (!(conditions === null || conditions === void 0 ? void 0 : conditions.length)) return true;
38
+ return conditions.every((condition) => executeCondition(condition, value));
39
+ }
40
+ function executeCondition(condition, value) {
41
+ const targetValue = condition.path ? getValueFromPath(value, condition.path) : value;
42
+ switch (condition.rule) {
43
+ case "AND": return condition.conditions.every((c) => executeCondition(c, value));
44
+ case "OR": return condition.conditions.some((c) => executeCondition(c, value));
45
+ case "NOT": return !condition.conditions.every((c) => executeCondition(c, value));
46
+ case "EQUALS": return targetValue === condition.value;
47
+ case "NOT_EQUALS": return targetValue !== condition.value;
48
+ case "GREATER_THAN": return targetValue > condition.value;
49
+ case "LESS_THAN": return targetValue < condition.value;
50
+ case "CONTAINS": return Array.isArray(targetValue) && targetValue.includes(condition.value);
51
+ case "NOT_CONTAINS": return Array.isArray(targetValue) && !targetValue.includes(condition.value);
52
+ case "MATCHES": return new RegExp(condition.value).test(String(targetValue));
53
+ case "STARTS_WITH": return String(targetValue).startsWith(condition.value);
54
+ case "ENDS_WITH": return String(targetValue).endsWith(condition.value);
55
+ case "EXISTS": return targetValue !== void 0 && targetValue !== null;
56
+ case "NOT_EXISTS": return targetValue === void 0 || targetValue === null;
57
+ }
58
+ }
59
+ function getValueFromPath(obj, path) {
60
+ return path.split(".").reduce((acc, part) => acc === null || acc === void 0 ? void 0 : acc[part], obj);
61
+ }
62
+
63
+ //#endregion
64
+ //#region src/utils/console-styling.ts
65
+ /**
66
+ * Console styling utilities for CopilotKit branded messages
67
+ * Provides consistent, readable colors across light and dark console themes
68
+ */
69
+ /**
70
+ * Color palette optimized for console readability
71
+ */
72
+ const ConsoleColors = {
73
+ primary: "#007acc",
74
+ success: "#22c55e",
75
+ feature: "#a855f7",
76
+ cta: "#ef4444",
77
+ info: "#06b6d4",
78
+ inherit: "inherit",
79
+ warning: "#f59e0b"
80
+ };
81
+ /**
82
+ * Console style templates for common patterns
83
+ */
84
+ const ConsoleStyles = {
85
+ header: `color: ${ConsoleColors.warning}; font-weight: bold; font-size: 16px;`,
86
+ section: `color: ${ConsoleColors.success}; font-weight: bold;`,
87
+ highlight: `color: ${ConsoleColors.feature}; font-weight: bold;`,
88
+ cta: `color: ${ConsoleColors.success}; font-weight: bold;`,
89
+ info: `color: ${ConsoleColors.info}; font-weight: bold;`,
90
+ link: `color: ${ConsoleColors.primary}; text-decoration: underline;`,
91
+ body: `color: ${ConsoleColors.inherit};`,
92
+ warning: `color: ${ConsoleColors.cta}; font-weight: bold;`
93
+ };
94
+ /**
95
+ * Styled console message for CopilotKit Platform promotion
96
+ * Displays a beautiful, branded advertisement in the console
97
+ */
98
+ function logCopilotKitPlatformMessage() {
99
+ console.log(`%cCopilotKit Warning%c
100
+
101
+ useCopilotChatHeadless_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:
102
+
103
+ %chttps://cloud.copilotkit.ai%c
104
+
105
+ Alternatively, useCopilotChat is available for basic programmatic control, and does not require an API key.
106
+
107
+ To learn more about premium features, read the documentation here:
108
+
109
+ %chttps://docs.copilotkit.ai/premium%c`, ConsoleStyles.header, ConsoleStyles.body, ConsoleStyles.cta, ConsoleStyles.body, ConsoleStyles.link, ConsoleStyles.body);
110
+ }
111
+ function publicApiKeyRequired(feature) {
112
+ console.log(`
113
+ %cCopilotKit Warning%c \n
114
+ In order to use ${feature}, you need to add your CopilotKit API key, available for free at https://cloud.copilotkit.ai.
115
+ `.trim(), ConsoleStyles.header, ConsoleStyles.body);
116
+ }
117
+ /**
118
+ * Create a styled console message with custom content
119
+ *
120
+ * @param template - Template string with %c placeholders
121
+ * @param styles - Array of style strings matching the %c placeholders
122
+ *
123
+ * @example
124
+ * ```typescript
125
+ * logStyled(
126
+ * '%cCopilotKit%c Welcome to the platform!',
127
+ * [ConsoleStyles.header, ConsoleStyles.body]
128
+ * );
129
+ * ```
130
+ */
131
+ function logStyled(template, styles) {
132
+ console.log(template, ...styles);
133
+ }
134
+ /**
135
+ * Quick styled console methods for common use cases
136
+ */
137
+ const styledConsole = {
138
+ success: (message) => logStyled(`%c✅ ${message}`, [ConsoleStyles.section]),
139
+ info: (message) => logStyled(`%cℹ️ ${message}`, [ConsoleStyles.info]),
140
+ feature: (message) => logStyled(`%c✨ ${message}`, [ConsoleStyles.highlight]),
141
+ cta: (message) => logStyled(`%c🚀 ${message}`, [ConsoleStyles.cta]),
142
+ logCopilotKitPlatformMessage,
143
+ publicApiKeyRequired
144
+ };
145
+
146
+ //#endregion
147
+ //#region src/utils/errors.ts
148
+ let Severity = /* @__PURE__ */ function(Severity) {
149
+ Severity["CRITICAL"] = "critical";
150
+ Severity["WARNING"] = "warning";
151
+ Severity["INFO"] = "info";
152
+ return Severity;
153
+ }({});
154
+ let ErrorVisibility = /* @__PURE__ */ function(ErrorVisibility) {
155
+ ErrorVisibility["BANNER"] = "banner";
156
+ ErrorVisibility["TOAST"] = "toast";
157
+ ErrorVisibility["SILENT"] = "silent";
158
+ ErrorVisibility["DEV_ONLY"] = "dev_only";
159
+ return ErrorVisibility;
160
+ }({});
161
+ const ERROR_NAMES = {
162
+ COPILOT_ERROR: "CopilotError",
163
+ COPILOT_API_DISCOVERY_ERROR: "CopilotApiDiscoveryError",
164
+ COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR: "CopilotKitRemoteEndpointDiscoveryError",
165
+ COPILOT_KIT_AGENT_DISCOVERY_ERROR: "CopilotKitAgentDiscoveryError",
166
+ COPILOT_KIT_LOW_LEVEL_ERROR: "CopilotKitLowLevelError",
167
+ COPILOT_KIT_VERSION_MISMATCH_ERROR: "CopilotKitVersionMismatchError",
168
+ RESOLVED_COPILOT_KIT_ERROR: "ResolvedCopilotKitError",
169
+ CONFIGURATION_ERROR: "ConfigurationError",
170
+ MISSING_PUBLIC_API_KEY_ERROR: "MissingPublicApiKeyError",
171
+ UPGRADE_REQUIRED_ERROR: "UpgradeRequiredError"
172
+ };
173
+ const BANNER_ERROR_NAMES = [
174
+ ERROR_NAMES.CONFIGURATION_ERROR,
175
+ ERROR_NAMES.MISSING_PUBLIC_API_KEY_ERROR,
176
+ ERROR_NAMES.UPGRADE_REQUIRED_ERROR,
177
+ ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR,
178
+ ERROR_NAMES.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR,
179
+ ERROR_NAMES.COPILOT_KIT_AGENT_DISCOVERY_ERROR
180
+ ];
181
+ const COPILOT_CLOUD_ERROR_NAMES = BANNER_ERROR_NAMES;
182
+ let CopilotKitErrorCode = /* @__PURE__ */ function(CopilotKitErrorCode) {
183
+ CopilotKitErrorCode["NETWORK_ERROR"] = "NETWORK_ERROR";
184
+ CopilotKitErrorCode["NOT_FOUND"] = "NOT_FOUND";
185
+ CopilotKitErrorCode["AGENT_NOT_FOUND"] = "AGENT_NOT_FOUND";
186
+ CopilotKitErrorCode["API_NOT_FOUND"] = "API_NOT_FOUND";
187
+ CopilotKitErrorCode["REMOTE_ENDPOINT_NOT_FOUND"] = "REMOTE_ENDPOINT_NOT_FOUND";
188
+ CopilotKitErrorCode["AUTHENTICATION_ERROR"] = "AUTHENTICATION_ERROR";
189
+ CopilotKitErrorCode["MISUSE"] = "MISUSE";
190
+ CopilotKitErrorCode["UNKNOWN"] = "UNKNOWN";
191
+ CopilotKitErrorCode["VERSION_MISMATCH"] = "VERSION_MISMATCH";
192
+ CopilotKitErrorCode["CONFIGURATION_ERROR"] = "CONFIGURATION_ERROR";
193
+ CopilotKitErrorCode["MISSING_PUBLIC_API_KEY_ERROR"] = "MISSING_PUBLIC_API_KEY_ERROR";
194
+ CopilotKitErrorCode["UPGRADE_REQUIRED_ERROR"] = "UPGRADE_REQUIRED_ERROR";
195
+ return CopilotKitErrorCode;
196
+ }({});
197
+ const BASE_URL = "https://docs.copilotkit.ai";
198
+ const getSeeMoreMarkdown = (link) => `See more: [${link}](${link})`;
199
+ const ERROR_CONFIG = {
200
+ [CopilotKitErrorCode.NETWORK_ERROR]: {
201
+ statusCode: 503,
202
+ troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#i-am-getting-a-network-errors--api-not-found`,
203
+ visibility: ErrorVisibility.BANNER,
204
+ severity: Severity.CRITICAL
205
+ },
206
+ [CopilotKitErrorCode.NOT_FOUND]: {
207
+ statusCode: 404,
208
+ troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#i-am-getting-a-network-errors--api-not-found`,
209
+ visibility: ErrorVisibility.BANNER,
210
+ severity: Severity.CRITICAL
211
+ },
212
+ [CopilotKitErrorCode.AGENT_NOT_FOUND]: {
213
+ statusCode: 500,
214
+ troubleshootingUrl: `${BASE_URL}/coagents/troubleshooting/common-issues#i-am-getting-agent-not-found-error`,
215
+ visibility: ErrorVisibility.BANNER,
216
+ severity: Severity.CRITICAL
217
+ },
218
+ [CopilotKitErrorCode.API_NOT_FOUND]: {
219
+ statusCode: 404,
220
+ troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#i-am-getting-a-network-errors--api-not-found`,
221
+ visibility: ErrorVisibility.BANNER,
222
+ severity: Severity.CRITICAL
223
+ },
224
+ [CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND]: {
225
+ statusCode: 404,
226
+ troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#i-am-getting-copilotkits-remote-endpoint-not-found-error`,
227
+ visibility: ErrorVisibility.BANNER,
228
+ severity: Severity.CRITICAL
229
+ },
230
+ [CopilotKitErrorCode.AUTHENTICATION_ERROR]: {
231
+ statusCode: 401,
232
+ troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#authentication-errors`,
233
+ visibility: ErrorVisibility.BANNER,
234
+ severity: Severity.CRITICAL
235
+ },
236
+ [CopilotKitErrorCode.MISUSE]: {
237
+ statusCode: 400,
238
+ troubleshootingUrl: null,
239
+ visibility: ErrorVisibility.DEV_ONLY,
240
+ severity: Severity.WARNING
241
+ },
242
+ [CopilotKitErrorCode.UNKNOWN]: {
243
+ statusCode: 500,
244
+ visibility: ErrorVisibility.TOAST,
245
+ severity: Severity.CRITICAL
246
+ },
247
+ [CopilotKitErrorCode.CONFIGURATION_ERROR]: {
248
+ statusCode: 400,
249
+ troubleshootingUrl: null,
250
+ severity: Severity.WARNING,
251
+ visibility: ErrorVisibility.BANNER
252
+ },
253
+ [CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR]: {
254
+ statusCode: 400,
255
+ troubleshootingUrl: null,
256
+ severity: Severity.CRITICAL,
257
+ visibility: ErrorVisibility.BANNER
258
+ },
259
+ [CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR]: {
260
+ statusCode: 402,
261
+ troubleshootingUrl: null,
262
+ severity: Severity.WARNING,
263
+ visibility: ErrorVisibility.BANNER
264
+ },
265
+ [CopilotKitErrorCode.VERSION_MISMATCH]: {
266
+ statusCode: 400,
267
+ troubleshootingUrl: null,
268
+ visibility: ErrorVisibility.DEV_ONLY,
269
+ severity: Severity.INFO
270
+ }
271
+ };
272
+ var CopilotKitError = class extends graphql.GraphQLError {
273
+ constructor({ message = "Unknown error occurred", code, severity, visibility }) {
274
+ var _ref;
275
+ const name = ERROR_NAMES.COPILOT_ERROR;
276
+ const config = ERROR_CONFIG[code];
277
+ const { statusCode } = config;
278
+ const resolvedVisibility = (_ref = visibility !== null && visibility !== void 0 ? visibility : config.visibility) !== null && _ref !== void 0 ? _ref : ErrorVisibility.TOAST;
279
+ const resolvedSeverity = severity !== null && severity !== void 0 ? severity : "severity" in config ? config.severity : void 0;
280
+ super(message, { extensions: {
281
+ name,
282
+ statusCode,
283
+ code,
284
+ visibility: resolvedVisibility,
285
+ severity: resolvedSeverity,
286
+ troubleshootingUrl: "troubleshootingUrl" in config ? config.troubleshootingUrl : null,
287
+ originalError: {
288
+ message,
289
+ stack: (/* @__PURE__ */ new Error()).stack
290
+ }
291
+ } });
292
+ this.code = code;
293
+ this.name = name;
294
+ this.statusCode = statusCode;
295
+ this.severity = resolvedSeverity;
296
+ this.visibility = resolvedVisibility;
297
+ }
298
+ };
299
+ /**
300
+ * Error thrown when we can identify wrong usage of our components.
301
+ * This helps us notify the developer before real errors can happen
302
+ *
303
+ * @extends CopilotKitError
304
+ */
305
+ var CopilotKitMisuseError = class extends CopilotKitError {
306
+ constructor({ message, code = CopilotKitErrorCode.MISUSE }) {
307
+ const docsLink = "troubleshootingUrl" in ERROR_CONFIG[code] && ERROR_CONFIG[code].troubleshootingUrl ? getSeeMoreMarkdown(ERROR_CONFIG[code].troubleshootingUrl) : null;
308
+ const finalMessage = docsLink ? `${message}.\n\n${docsLink}` : message;
309
+ super({
310
+ message: finalMessage,
311
+ code
312
+ });
313
+ this.name = ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR;
314
+ }
315
+ };
316
+ const getVersionMismatchErrorMessage = ({ reactCoreVersion, runtimeVersion, runtimeClientGqlVersion }) => `Version mismatch detected: @copilotkit/runtime@${runtimeVersion !== null && runtimeVersion !== void 0 ? runtimeVersion : ""} is not compatible with @copilotkit/react-core@${reactCoreVersion} and @copilotkit/runtime-client-gql@${runtimeClientGqlVersion}. Please ensure all installed copilotkit packages are on the same version.`;
317
+ /**
318
+ * Error thrown when CPK versions does not match
319
+ *
320
+ * @extends CopilotKitError
321
+ */
322
+ var CopilotKitVersionMismatchError = class extends CopilotKitError {
323
+ constructor({ reactCoreVersion, runtimeVersion, runtimeClientGqlVersion }) {
324
+ const code = CopilotKitErrorCode.VERSION_MISMATCH;
325
+ super({
326
+ message: getVersionMismatchErrorMessage({
327
+ reactCoreVersion,
328
+ runtimeVersion,
329
+ runtimeClientGqlVersion
330
+ }),
331
+ code
332
+ });
333
+ this.name = ERROR_NAMES.COPILOT_KIT_VERSION_MISMATCH_ERROR;
334
+ }
335
+ };
336
+ /**
337
+ * Error thrown when the CopilotKit API endpoint cannot be discovered or accessed.
338
+ * This typically occurs when:
339
+ * - The API endpoint URL is invalid or misconfigured
340
+ * - The API service is not running at the expected location
341
+ * - There are network/firewall issues preventing access
342
+ *
343
+ * @extends CopilotKitError
344
+ */
345
+ var CopilotKitApiDiscoveryError = class extends CopilotKitError {
346
+ constructor(params = {}) {
347
+ var _params$url, _params$message, _params$code;
348
+ const url = (_params$url = params.url) !== null && _params$url !== void 0 ? _params$url : "";
349
+ let operationSuffix = "";
350
+ if (url === null || url === void 0 ? void 0 : url.includes("/info")) operationSuffix = `when fetching CopilotKit info`;
351
+ else if (url.includes("/actions/execute")) operationSuffix = `when attempting to execute actions.`;
352
+ else if (url.includes("/agents/state")) operationSuffix = `when attempting to get agent state.`;
353
+ else if (url.includes("/agents/execute")) operationSuffix = `when attempting to execute agent(s).`;
354
+ const message = (_params$message = params.message) !== null && _params$message !== void 0 ? _params$message : params.url ? `Failed to find CopilotKit API endpoint at url ${params.url} ${operationSuffix}` : `Failed to find CopilotKit API endpoint.`;
355
+ const code = (_params$code = params.code) !== null && _params$code !== void 0 ? _params$code : CopilotKitErrorCode.API_NOT_FOUND;
356
+ const errorMessage = `${message}.\n\n${getSeeMoreMarkdown(ERROR_CONFIG[code].troubleshootingUrl)}`;
357
+ super({
358
+ message: errorMessage,
359
+ code
360
+ });
361
+ this.name = ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR;
362
+ }
363
+ };
364
+ /**
365
+ * This error is used for endpoints specified in runtime's remote endpoints. If they cannot be contacted
366
+ * This typically occurs when:
367
+ * - The API endpoint URL is invalid or misconfigured
368
+ * - The API service is not running at the expected location
369
+ *
370
+ * @extends CopilotKitApiDiscoveryError
371
+ */
372
+ var CopilotKitRemoteEndpointDiscoveryError = class extends CopilotKitApiDiscoveryError {
373
+ constructor(params) {
374
+ var _params$message2;
375
+ const message = (_params$message2 = params === null || params === void 0 ? void 0 : params.message) !== null && _params$message2 !== void 0 ? _params$message2 : (params === null || params === void 0 ? void 0 : params.url) ? `Failed to find or contact remote endpoint at url ${params.url}` : "Failed to find or contact remote endpoint";
376
+ const code = CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND;
377
+ super({
378
+ message,
379
+ code
380
+ });
381
+ this.name = ERROR_NAMES.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR;
382
+ }
383
+ };
384
+ /**
385
+ * Error thrown when a LangGraph agent cannot be found or accessed.
386
+ * This typically occurs when:
387
+ * - The specified agent name does not exist in the deployment
388
+ * - The agent configuration is invalid or missing
389
+ * - The agent service is not properly deployed or initialized
390
+ *
391
+ * @extends CopilotKitError
392
+ */
393
+ var CopilotKitAgentDiscoveryError = class extends CopilotKitError {
394
+ constructor(params) {
395
+ const { agentName, availableAgents } = params;
396
+ const code = CopilotKitErrorCode.AGENT_NOT_FOUND;
397
+ const seeMore = getSeeMoreMarkdown(ERROR_CONFIG[code].troubleshootingUrl);
398
+ let message;
399
+ if (availableAgents.length) {
400
+ const agentList = availableAgents.map((agent) => agent.name).join(", ");
401
+ if (agentName) message = `Agent '${agentName}' was not found. Available agents are: ${agentList}. Please verify the agent name in your configuration and ensure it matches one of the available agents.\n\n${seeMore}`;
402
+ else message = `The requested agent was not found. Available agents are: ${agentList}. Please verify the agent name in your configuration and ensure it matches one of the available agents.\n\n${seeMore}`;
403
+ } else message = `${agentName ? `Agent '${agentName}'` : "The requested agent"} was not found. Please set up at least one agent before proceeding. ${seeMore}`;
404
+ super({
405
+ message,
406
+ code
407
+ });
408
+ this.name = ERROR_NAMES.COPILOT_KIT_AGENT_DISCOVERY_ERROR;
409
+ }
410
+ };
411
+ /**
412
+ * Handles low-level networking errors that occur before a request reaches the server.
413
+ * These errors arise from issues in the underlying communication infrastructure rather than
414
+ * application-level logic or server responses. Typically used to handle "fetch failed" errors
415
+ * where no HTTP status code is available.
416
+ *
417
+ * Common scenarios include:
418
+ * - Connection failures (ECONNREFUSED) when server is down/unreachable
419
+ * - DNS resolution failures (ENOTFOUND) when domain can't be resolved
420
+ * - Timeouts (ETIMEDOUT) when request takes too long
421
+ * - Protocol/transport layer errors like SSL/TLS issues
422
+ */
423
+ var CopilotKitLowLevelError = class extends CopilotKitError {
424
+ constructor({ error, url, message }) {
425
+ let code = CopilotKitErrorCode.NETWORK_ERROR;
426
+ const errorCode = error.code;
427
+ const errorMessage = message !== null && message !== void 0 ? message : resolveLowLevelErrorMessage({
428
+ errorCode,
429
+ url
430
+ });
431
+ super({
432
+ message: errorMessage,
433
+ code
434
+ });
435
+ this.name = ERROR_NAMES.COPILOT_KIT_LOW_LEVEL_ERROR;
436
+ }
437
+ };
438
+ /**
439
+ * Generic catch-all error handler for HTTP responses from the CopilotKit API where a status code is available.
440
+ * Used when we receive an HTTP error status and wish to handle broad range of them
441
+ *
442
+ * This differs from CopilotKitLowLevelError in that:
443
+ * - ResolvedCopilotKitError: Server was reached and returned an HTTP status
444
+ * - CopilotKitLowLevelError: Error occurred before reaching server (e.g. network failure)
445
+ *
446
+ * @param status - The HTTP status code received from the API response
447
+ * @param message - Optional error message to include
448
+ * @param code - Optional specific CopilotKitErrorCode to override default behavior
449
+ *
450
+ * Default behavior:
451
+ * - 400 Bad Request: Maps to CopilotKitApiDiscoveryError
452
+ * - All other status codes: Maps to UNKNOWN error code if no specific code provided
453
+ */
454
+ var ResolvedCopilotKitError = class extends CopilotKitError {
455
+ constructor({ status, message, code, isRemoteEndpoint, url }) {
456
+ let resolvedCode = code;
457
+ if (!resolvedCode) switch (status) {
458
+ case 400: throw new CopilotKitApiDiscoveryError({
459
+ message,
460
+ url
461
+ });
462
+ case 404: throw isRemoteEndpoint ? new CopilotKitRemoteEndpointDiscoveryError({
463
+ message,
464
+ url
465
+ }) : new CopilotKitApiDiscoveryError({
466
+ message,
467
+ url
468
+ });
469
+ default:
470
+ resolvedCode = CopilotKitErrorCode.UNKNOWN;
471
+ break;
472
+ }
473
+ super({
474
+ message,
475
+ code: resolvedCode
476
+ });
477
+ this.name = ERROR_NAMES.RESOLVED_COPILOT_KIT_ERROR;
478
+ }
479
+ };
480
+ var ConfigurationError = class extends CopilotKitError {
481
+ constructor(message) {
482
+ super({
483
+ message,
484
+ code: CopilotKitErrorCode.CONFIGURATION_ERROR
485
+ });
486
+ this.name = ERROR_NAMES.CONFIGURATION_ERROR;
487
+ this.severity = Severity.WARNING;
488
+ }
489
+ };
490
+ var MissingPublicApiKeyError = class extends ConfigurationError {
491
+ constructor(message) {
492
+ super(message);
493
+ this.name = ERROR_NAMES.MISSING_PUBLIC_API_KEY_ERROR;
494
+ this.severity = Severity.CRITICAL;
495
+ }
496
+ };
497
+ var UpgradeRequiredError = class extends ConfigurationError {
498
+ constructor(message) {
499
+ super(message);
500
+ this.name = ERROR_NAMES.UPGRADE_REQUIRED_ERROR;
501
+ this.severity = Severity.WARNING;
502
+ }
503
+ };
504
+ /**
505
+ * Checks if an error is already a structured CopilotKit error.
506
+ * This utility centralizes the logic for detecting structured errors across the codebase.
507
+ *
508
+ * @param error - The error to check
509
+ * @returns true if the error is already structured, false otherwise
510
+ */
511
+ function isStructuredCopilotKitError(error) {
512
+ var _error$extensions;
513
+ return error instanceof CopilotKitError || error instanceof CopilotKitLowLevelError || (error === null || error === void 0 ? void 0 : error.name) && error.name.includes("CopilotKit") || (error === null || error === void 0 || (_error$extensions = error.extensions) === null || _error$extensions === void 0 ? void 0 : _error$extensions.code) !== void 0;
514
+ }
515
+ /**
516
+ * Returns the error as-is if it's already structured, otherwise converts it using the provided converter function.
517
+ * This utility centralizes the pattern of preserving structured errors while converting unstructured ones.
518
+ *
519
+ * @param error - The error to process
520
+ * @param converter - Function to convert unstructured errors to structured ones
521
+ * @returns The structured error
522
+ */
523
+ function ensureStructuredError(error, converter) {
524
+ return isStructuredCopilotKitError(error) ? error : converter(error);
525
+ }
526
+ async function getPossibleVersionMismatch({ runtimeVersion, runtimeClientGqlVersion }) {
527
+ if (!runtimeVersion || runtimeVersion === "" || !runtimeClientGqlVersion) return;
528
+ if (COPILOTKIT_VERSION !== runtimeVersion || COPILOTKIT_VERSION !== runtimeClientGqlVersion || runtimeVersion !== runtimeClientGqlVersion) return {
529
+ runtimeVersion,
530
+ runtimeClientGqlVersion,
531
+ reactCoreVersion: COPILOTKIT_VERSION,
532
+ message: getVersionMismatchErrorMessage({
533
+ runtimeVersion,
534
+ runtimeClientGqlVersion,
535
+ reactCoreVersion: COPILOTKIT_VERSION
536
+ })
537
+ };
538
+ }
539
+ const resolveLowLevelErrorMessage = ({ errorCode, url }) => {
540
+ const troubleshootingLink = ERROR_CONFIG[CopilotKitErrorCode.NETWORK_ERROR].troubleshootingUrl;
541
+ const genericMessage = (description = `Failed to fetch from url ${url}.`) => `${description}.
542
+
543
+ Possible reasons:
544
+ - -The server may have an error preventing it from returning a response (Check the server logs for more info).
545
+ - -The server might be down or unreachable
546
+ - -There might be a network issue (e.g., DNS failure, connection timeout)
547
+ - -The URL might be incorrect
548
+ - -The server is not running on the specified port
549
+
550
+ ${getSeeMoreMarkdown(troubleshootingLink)}`;
551
+ if (url.includes("/info")) return genericMessage(`Failed to fetch CopilotKit agents/action information from url ${url}.`);
552
+ if (url.includes("/actions/execute")) return genericMessage(`Fetch call to ${url} to execute actions failed.`);
553
+ if (url.includes("/agents/state")) return genericMessage(`Fetch call to ${url} to get agent state failed.`);
554
+ if (url.includes("/agents/execute")) return genericMessage(`Fetch call to ${url} to execute agent(s) failed.`);
555
+ switch (errorCode) {
556
+ case "ECONNREFUSED": return `Connection to ${url} was refused. Ensure the server is running and accessible.\n\n${getSeeMoreMarkdown(troubleshootingLink)}`;
557
+ case "ENOTFOUND": return `The server on ${url} could not be found. Check the URL or your network configuration.\n\n${getSeeMoreMarkdown(ERROR_CONFIG[CopilotKitErrorCode.NOT_FOUND].troubleshootingUrl)}`;
558
+ case "ETIMEDOUT": return `The connection to ${url} timed out. The server might be overloaded or taking too long to respond.\n\n${getSeeMoreMarkdown(troubleshootingLink)}`;
559
+ default: return;
560
+ }
561
+ };
562
+
563
+ //#endregion
564
+ //#region src/utils/json-schema.ts
565
+ function actionParametersToJsonSchema(actionParameters) {
566
+ let parameters = {};
567
+ for (let parameter of actionParameters || []) parameters[parameter.name] = convertAttribute(parameter);
568
+ let requiredParameterNames = [];
569
+ for (let arg of actionParameters || []) if (arg.required !== false) requiredParameterNames.push(arg.name);
570
+ return {
571
+ type: "object",
572
+ properties: parameters,
573
+ required: requiredParameterNames
574
+ };
575
+ }
576
+ function jsonSchemaToActionParameters(jsonSchema) {
577
+ if (jsonSchema.type !== "object" || !jsonSchema.properties) return [];
578
+ const parameters = [];
579
+ const requiredFields = jsonSchema.required || [];
580
+ for (const [name, schema] of Object.entries(jsonSchema.properties)) {
581
+ const parameter = convertJsonSchemaToParameter(name, schema, requiredFields.includes(name));
582
+ parameters.push(parameter);
583
+ }
584
+ return parameters;
585
+ }
586
+ function convertJsonSchemaToParameter(name, schema, isRequired) {
587
+ const baseParameter = {
588
+ name,
589
+ description: schema.description
590
+ };
591
+ if (!isRequired) baseParameter.required = false;
592
+ switch (schema.type) {
593
+ case "string": return {
594
+ ...baseParameter,
595
+ type: "string",
596
+ ...schema.enum && { enum: schema.enum }
597
+ };
598
+ case "number":
599
+ case "boolean": return {
600
+ ...baseParameter,
601
+ type: schema.type
602
+ };
603
+ case "object":
604
+ if (schema.properties) {
605
+ const attributes = [];
606
+ const requiredFields = schema.required || [];
607
+ for (const [propName, propSchema] of Object.entries(schema.properties)) attributes.push(convertJsonSchemaToParameter(propName, propSchema, requiredFields.includes(propName)));
608
+ return {
609
+ ...baseParameter,
610
+ type: "object",
611
+ attributes
612
+ };
613
+ }
614
+ return {
615
+ ...baseParameter,
616
+ type: "object"
617
+ };
618
+ case "array": if (schema.items.type === "object" && "properties" in schema.items) {
619
+ const attributes = [];
620
+ const requiredFields = schema.items.required || [];
621
+ for (const [propName, propSchema] of Object.entries(schema.items.properties || {})) attributes.push(convertJsonSchemaToParameter(propName, propSchema, requiredFields.includes(propName)));
622
+ return {
623
+ ...baseParameter,
624
+ type: "object[]",
625
+ attributes
626
+ };
627
+ } else if (schema.items.type === "array") throw new Error("Nested arrays are not supported");
628
+ else return {
629
+ ...baseParameter,
630
+ type: `${schema.items.type}[]`
631
+ };
632
+ default: return {
633
+ ...baseParameter,
634
+ type: "string"
635
+ };
636
+ }
637
+ }
638
+ function convertAttribute(attribute) {
639
+ switch (attribute.type) {
640
+ case "string": return {
641
+ type: "string",
642
+ description: attribute.description,
643
+ ...attribute.enum && { enum: attribute.enum }
644
+ };
645
+ case "number":
646
+ case "boolean": return {
647
+ type: attribute.type,
648
+ description: attribute.description
649
+ };
650
+ case "object":
651
+ case "object[]":
652
+ var _attribute$attributes, _attribute$attributes2;
653
+ const properties = (_attribute$attributes = attribute.attributes) === null || _attribute$attributes === void 0 ? void 0 : _attribute$attributes.reduce((acc, attr) => {
654
+ acc[attr.name] = convertAttribute(attr);
655
+ return acc;
656
+ }, {});
657
+ const required = (_attribute$attributes2 = attribute.attributes) === null || _attribute$attributes2 === void 0 ? void 0 : _attribute$attributes2.filter((attr) => attr.required !== false).map((attr) => attr.name);
658
+ if (attribute.type === "object[]") return {
659
+ type: "array",
660
+ items: {
661
+ type: "object",
662
+ ...properties && { properties },
663
+ ...required && required.length > 0 && { required }
664
+ },
665
+ description: attribute.description
666
+ };
667
+ return {
668
+ type: "object",
669
+ description: attribute.description,
670
+ ...properties && { properties },
671
+ ...required && required.length > 0 && { required }
672
+ };
673
+ default:
674
+ var _attribute$type;
675
+ if ((_attribute$type = attribute.type) === null || _attribute$type === void 0 ? void 0 : _attribute$type.endsWith("[]")) return {
676
+ type: "array",
677
+ items: { type: attribute.type.slice(0, -2) },
678
+ description: attribute.description
679
+ };
680
+ return {
681
+ type: "string",
682
+ description: attribute.description
683
+ };
684
+ }
685
+ }
686
+ function convertJsonSchemaToZodSchema(jsonSchema, required) {
687
+ if (jsonSchema.type === "object") {
688
+ const spec = {};
689
+ if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) return !required ? zod.z.object(spec).optional() : zod.z.object(spec);
690
+ for (const [key, value] of Object.entries(jsonSchema.properties)) spec[key] = convertJsonSchemaToZodSchema(value, jsonSchema.required ? jsonSchema.required.includes(key) : false);
691
+ let schema = zod.z.object(spec).describe(jsonSchema.description);
692
+ return required ? schema : schema.optional();
693
+ } else if (jsonSchema.type === "string") {
694
+ let schema = zod.z.string().describe(jsonSchema.description);
695
+ return required ? schema : schema.optional();
696
+ } else if (jsonSchema.type === "number") {
697
+ let schema = zod.z.number().describe(jsonSchema.description);
698
+ return required ? schema : schema.optional();
699
+ } else if (jsonSchema.type === "boolean") {
700
+ let schema = zod.z.boolean().describe(jsonSchema.description);
701
+ return required ? schema : schema.optional();
702
+ } else if (jsonSchema.type === "array") {
703
+ let itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true);
704
+ let schema = zod.z.array(itemSchema).describe(jsonSchema.description);
705
+ return required ? schema : schema.optional();
706
+ }
707
+ throw new Error("Invalid JSON schema");
708
+ }
709
+ function getZodParameters(parameters) {
710
+ if (!parameters) return zod.z.object({});
711
+ return convertJsonSchemaToZodSchema(actionParametersToJsonSchema(parameters), true);
712
+ }
713
+
714
+ //#endregion
715
+ //#region src/utils/random-id.ts
716
+ function randomId() {
717
+ return "ck-" + (0, uuid.v4)();
718
+ }
719
+ function randomUUID() {
720
+ return (0, uuid.v4)();
721
+ }
722
+ /**
723
+ * Recursively converts an object to a serializable form by converting functions to their string representation.
724
+ */
725
+ function toSerializable(value) {
726
+ if (typeof value === "function") return value.toString();
727
+ if (Array.isArray(value)) return value.map(toSerializable);
728
+ if (value !== null && typeof value === "object") {
729
+ const result = {};
730
+ for (const key of Object.keys(value)) result[key] = toSerializable(value[key]);
731
+ return result;
732
+ }
733
+ return value;
734
+ }
735
+ function dataToUUID(input, namespace) {
736
+ const BASE_NAMESPACE = "e4b01160-ff74-4c6e-9b27-d53cd930fe8e";
737
+ const boundNamespace = namespace ? (0, uuid.v5)(namespace, BASE_NAMESPACE) : BASE_NAMESPACE;
738
+ return (0, uuid.v5)(typeof input === "string" ? input : JSON.stringify(toSerializable(input)), boundNamespace);
739
+ }
740
+ function isValidUUID(uuid$1) {
741
+ return (0, uuid.validate)(uuid$1);
742
+ }
743
+
744
+ //#endregion
745
+ //#region src/utils/requests.ts
746
+ /**
747
+ * Safely read a Response/Request body with sensible defaults:
748
+ * - clones the response/request to avoid consuming the original response/request
749
+ * - Skips GET/HEAD
750
+ * - Tries JSON first regardless of content-type
751
+ * - Falls back to text and optionally parses when it "looks" like JSON
752
+ */
753
+ async function readBody(r) {
754
+ const method = "method" in r ? r.method.toUpperCase() : void 0;
755
+ if (method === "GET" || method === "HEAD") return;
756
+ if (!("body" in r) || r.body == null) return;
757
+ try {
758
+ return await r.clone().json();
759
+ } catch (_unused) {
760
+ try {
761
+ const text = await r.clone().text();
762
+ const trimmed = text.trim();
763
+ if (trimmed.length === 0) return text;
764
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) try {
765
+ return JSON.parse(trimmed);
766
+ } catch (_unused2) {
767
+ return text;
768
+ }
769
+ return text;
770
+ } catch (_unused3) {
771
+ try {
772
+ var _c$body;
773
+ const stream = (_c$body = r.clone().body) !== null && _c$body !== void 0 ? _c$body : null;
774
+ if (!stream) return void 0;
775
+ const reader = stream.getReader();
776
+ const decoder = new TextDecoder();
777
+ let out = "";
778
+ while (true) {
779
+ const { done, value } = await reader.read();
780
+ if (done) break;
781
+ if (typeof value === "string") out += value;
782
+ else out += decoder.decode(value, { stream: true });
783
+ }
784
+ out += decoder.decode();
785
+ const trimmed = out.trim();
786
+ if (trimmed.length === 0) return out;
787
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) try {
788
+ return JSON.parse(trimmed);
789
+ } catch (_unused4) {
790
+ return out;
791
+ }
792
+ return out;
793
+ } catch (_unused5) {
794
+ return;
795
+ }
796
+ }
797
+ }
798
+ }
799
+
800
+ //#endregion
801
+ //#region src/utils/index.ts
802
+ /**
803
+ * Safely parses a JSON string into an object
804
+ * @param json The JSON string to parse
805
+ * @param fallback Optional fallback value to return if parsing fails. If not provided or set to "unset", returns null
806
+ * @returns The parsed JSON object, or the fallback value (or null) if parsing fails
807
+ */
808
+ function parseJson(json, fallback = "unset") {
809
+ try {
810
+ return JSON.parse(json);
811
+ } catch (e) {
812
+ return fallback === "unset" ? null : fallback;
813
+ }
814
+ }
815
+ /**
816
+ * Maps an array of items to a new array, skipping items that throw errors during mapping
817
+ * @param items The array to map
818
+ * @param callback The mapping function to apply to each item
819
+ * @returns A new array containing only the successfully mapped items
820
+ */
821
+ function tryMap(items, callback) {
822
+ return items.reduce((acc, item, index, array) => {
823
+ try {
824
+ acc.push(callback(item, index, array));
825
+ } catch (error) {
826
+ console.error(error);
827
+ }
828
+ return acc;
829
+ }, []);
830
+ }
831
+ /**
832
+ * Checks if the current environment is macOS
833
+ * @returns {boolean} True if running on macOS, false otherwise
834
+ */
835
+ function isMacOS() {
836
+ return /Mac|iMac|Macintosh/i.test(navigator.userAgent);
837
+ }
838
+
839
+ //#endregion
840
+ //#region src/constants/index.ts
841
+ const COPILOT_CLOUD_API_URL = "https://api.cloud.copilotkit.ai";
842
+ const COPILOT_CLOUD_VERSION = "v1";
843
+ const COPILOT_CLOUD_CHAT_URL = `${COPILOT_CLOUD_API_URL}/copilotkit/${COPILOT_CLOUD_VERSION}`;
844
+ const COPILOT_CLOUD_PUBLIC_API_KEY_HEADER = "X-CopilotCloud-Public-Api-Key";
845
+
846
+ //#endregion
847
+ //#region src/telemetry/utils.ts
848
+ function flattenObject(obj, parentKey = "", res = {}) {
849
+ for (let key in obj) {
850
+ const propName = parentKey ? `${parentKey}.${key}` : key;
851
+ if (typeof obj[key] === "object" && obj[key] !== null) flattenObject(obj[key], propName, res);
852
+ else res[propName] = obj[key];
853
+ }
854
+ return res;
855
+ }
856
+
857
+ //#endregion
858
+ //#region package.json
859
+ var version = "1.51.5-next.2";
860
+
861
+ //#endregion
862
+ //#region src/telemetry/scarf-client.ts
863
+ const SCARF_BASE_URL = `https://copilotkit.gateway.scarf.sh/${version}`;
864
+ var ScarfClient = class {
865
+ constructor() {}
866
+ async logEvent(properties) {
867
+ try {
868
+ const controller = new AbortController();
869
+ const timeoutId = setTimeout(() => controller.abort(), 3e3);
870
+ const queryParams = new URLSearchParams();
871
+ Object.entries(properties).forEach(([key, value]) => {
872
+ if (value !== null && value !== void 0) queryParams.append(key, String(value));
873
+ });
874
+ const url = `${SCARF_BASE_URL}?${queryParams.toString()}`;
875
+ const response = await fetch(url, {
876
+ method: "GET",
877
+ signal: controller.signal
878
+ });
879
+ clearTimeout(timeoutId);
880
+ if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
881
+ } catch (_unused) {}
882
+ }
883
+ };
884
+ var scarf_client_default = new ScarfClient();
885
+
886
+ //#endregion
887
+ //#region src/telemetry/telemetry-client.ts
888
+ /**
889
+ * Checks if telemetry is disabled via environment variables.
890
+ * Users can opt out by setting:
891
+ * - COPILOTKIT_TELEMETRY_DISABLED=true or COPILOTKIT_TELEMETRY_DISABLED=1
892
+ * - DO_NOT_TRACK=true or DO_NOT_TRACK=1
893
+ */
894
+ function isTelemetryDisabled() {
895
+ return process.env.COPILOTKIT_TELEMETRY_DISABLED === "true" || process.env.COPILOTKIT_TELEMETRY_DISABLED === "1" || process.env.DO_NOT_TRACK === "true" || process.env.DO_NOT_TRACK === "1";
896
+ }
897
+ var TelemetryClient = class {
898
+ constructor({ packageName, packageVersion, telemetryDisabled, telemetryBaseUrl, sampleRate }) {
899
+ this.globalProperties = {};
900
+ this.cloudConfiguration = null;
901
+ this.telemetryDisabled = false;
902
+ this.sampleRate = .05;
903
+ this.anonymousId = `anon_${(0, uuid.v4)()}`;
904
+ this.packageName = packageName;
905
+ this.packageVersion = packageVersion;
906
+ this.telemetryDisabled = telemetryDisabled || isTelemetryDisabled();
907
+ if (this.telemetryDisabled) return;
908
+ this.setSampleRate(sampleRate);
909
+ this.segment = new _segment_analytics_node.Analytics({ writeKey: process.env.COPILOTKIT_SEGMENT_WRITE_KEY || "n7XAZtQCGS2v1vvBy3LgBCv2h3Y8whja" });
910
+ this.setGlobalProperties({
911
+ "copilotkit.package.name": packageName,
912
+ "copilotkit.package.version": packageVersion
913
+ });
914
+ }
915
+ shouldSendEvent() {
916
+ return Math.random() < this.sampleRate;
917
+ }
918
+ async capture(event, properties) {
919
+ if (!this.shouldSendEvent() || !this.segment) return;
920
+ const flattenedProperties = flattenObject(properties);
921
+ const propertiesWithGlobal = {
922
+ ...this.globalProperties,
923
+ ...flattenedProperties
924
+ };
925
+ const orderedPropertiesWithGlobal = Object.keys(propertiesWithGlobal).sort().reduce((obj, key) => {
926
+ obj[key] = propertiesWithGlobal[key];
927
+ return obj;
928
+ }, {});
929
+ this.segment.track({
930
+ anonymousId: this.anonymousId,
931
+ event,
932
+ properties: { ...orderedPropertiesWithGlobal }
933
+ });
934
+ await scarf_client_default.logEvent({ event });
935
+ }
936
+ setGlobalProperties(properties) {
937
+ const flattenedProperties = flattenObject(properties);
938
+ this.globalProperties = {
939
+ ...this.globalProperties,
940
+ ...flattenedProperties
941
+ };
942
+ }
943
+ setCloudConfiguration(properties) {
944
+ this.cloudConfiguration = properties;
945
+ this.setGlobalProperties({ cloud: {
946
+ publicApiKey: properties.publicApiKey,
947
+ baseUrl: properties.baseUrl
948
+ } });
949
+ }
950
+ setSampleRate(sampleRate) {
951
+ let _sampleRate;
952
+ _sampleRate = sampleRate !== null && sampleRate !== void 0 ? sampleRate : .05;
953
+ if (process.env.COPILOTKIT_TELEMETRY_SAMPLE_RATE) _sampleRate = parseFloat(process.env.COPILOTKIT_TELEMETRY_SAMPLE_RATE);
954
+ if (_sampleRate < 0 || _sampleRate > 1) throw new Error("Sample rate must be between 0 and 1");
955
+ this.sampleRate = _sampleRate;
956
+ this.setGlobalProperties({
957
+ sampleRate: this.sampleRate,
958
+ sampleRateAdjustmentFactor: 1 - this.sampleRate,
959
+ sampleWeight: 1 / this.sampleRate
960
+ });
961
+ }
962
+ };
963
+
964
+ //#endregion
965
+ //#region src/index.ts
966
+ const COPILOTKIT_VERSION = version;
967
+
968
+ //#endregion
969
+ exports.BANNER_ERROR_NAMES = BANNER_ERROR_NAMES;
970
+ exports.COPILOTKIT_VERSION = COPILOTKIT_VERSION;
971
+ exports.COPILOT_CLOUD_API_URL = COPILOT_CLOUD_API_URL;
972
+ exports.COPILOT_CLOUD_CHAT_URL = COPILOT_CLOUD_CHAT_URL;
973
+ exports.COPILOT_CLOUD_ERROR_NAMES = COPILOT_CLOUD_ERROR_NAMES;
974
+ exports.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER = COPILOT_CLOUD_PUBLIC_API_KEY_HEADER;
975
+ exports.COPILOT_CLOUD_VERSION = COPILOT_CLOUD_VERSION;
976
+ exports.ConfigurationError = ConfigurationError;
977
+ exports.ConsoleColors = ConsoleColors;
978
+ exports.ConsoleStyles = ConsoleStyles;
979
+ exports.CopilotKitAgentDiscoveryError = CopilotKitAgentDiscoveryError;
980
+ exports.CopilotKitApiDiscoveryError = CopilotKitApiDiscoveryError;
981
+ exports.CopilotKitError = CopilotKitError;
982
+ exports.CopilotKitErrorCode = CopilotKitErrorCode;
983
+ exports.CopilotKitLowLevelError = CopilotKitLowLevelError;
984
+ exports.CopilotKitMisuseError = CopilotKitMisuseError;
985
+ exports.CopilotKitRemoteEndpointDiscoveryError = CopilotKitRemoteEndpointDiscoveryError;
986
+ exports.CopilotKitVersionMismatchError = CopilotKitVersionMismatchError;
987
+ exports.ERROR_CONFIG = ERROR_CONFIG;
988
+ exports.ERROR_NAMES = ERROR_NAMES;
989
+ exports.ErrorVisibility = ErrorVisibility;
990
+ exports.MissingPublicApiKeyError = MissingPublicApiKeyError;
991
+ exports.ResolvedCopilotKitError = ResolvedCopilotKitError;
992
+ exports.Severity = Severity;
993
+ exports.TelemetryClient = TelemetryClient;
994
+ exports.UpgradeRequiredError = UpgradeRequiredError;
995
+ exports.actionParametersToJsonSchema = actionParametersToJsonSchema;
996
+ exports.convertJsonSchemaToZodSchema = convertJsonSchemaToZodSchema;
997
+ exports.dataToUUID = dataToUUID;
998
+ exports.ensureStructuredError = ensureStructuredError;
999
+ exports.executeConditions = executeConditions;
1000
+ exports.getPossibleVersionMismatch = getPossibleVersionMismatch;
1001
+ exports.getZodParameters = getZodParameters;
1002
+ exports.isMacOS = isMacOS;
1003
+ exports.isStructuredCopilotKitError = isStructuredCopilotKitError;
1004
+ exports.isTelemetryDisabled = isTelemetryDisabled;
1005
+ exports.isValidUUID = isValidUUID;
1006
+ exports.jsonSchemaToActionParameters = jsonSchemaToActionParameters;
1007
+ exports.logCopilotKitPlatformMessage = logCopilotKitPlatformMessage;
1008
+ exports.logStyled = logStyled;
1009
+ exports.parseJson = parseJson;
1010
+ exports.publicApiKeyRequired = publicApiKeyRequired;
1011
+ exports.randomId = randomId;
1012
+ exports.randomUUID = randomUUID;
1013
+ exports.readBody = readBody;
1014
+ exports.styledConsole = styledConsole;
1015
+ exports.tryMap = tryMap;
1016
+ });
1017
+ //# sourceMappingURL=index.umd.js.map