@burdenoff/website-sdk 2026.1101.1 → 2026.1101.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 (276) hide show
  1. package/README.md +42 -8
  2. package/dist/analytics/index.js +19 -69
  3. package/dist/analytics/index.js.map +1 -1
  4. package/dist/analytics/index.mjs +3 -69
  5. package/dist/analytics/index.mjs.map +1 -1
  6. package/dist/avatar-live/index.js +1 -0
  7. package/dist/avatar-live/index.js.map +1 -1
  8. package/dist/avatar-live/index.mjs +1 -0
  9. package/dist/avatar-live/index.mjs.map +1 -1
  10. package/dist/avatar-live-view/index.js +10 -30
  11. package/dist/avatar-live-view/index.js.map +1 -1
  12. package/dist/avatar-live-view/index.mjs +4 -24
  13. package/dist/avatar-live-view/index.mjs.map +1 -1
  14. package/dist/chunk-23H4JUL4.js +41 -0
  15. package/dist/chunk-23H4JUL4.js.map +1 -0
  16. package/dist/chunk-34RX5P75.mjs +25 -0
  17. package/dist/chunk-34RX5P75.mjs.map +1 -0
  18. package/dist/chunk-3LFFY7AZ.js +184 -0
  19. package/dist/chunk-3LFFY7AZ.js.map +1 -0
  20. package/dist/chunk-3X26GE4S.js +2794 -0
  21. package/dist/chunk-3X26GE4S.js.map +1 -0
  22. package/dist/chunk-45GCA4GG.js +85 -0
  23. package/dist/chunk-45GCA4GG.js.map +1 -0
  24. package/dist/chunk-4SAGVLHN.js +876 -0
  25. package/dist/chunk-4SAGVLHN.js.map +1 -0
  26. package/dist/chunk-4U6YAII5.js +218 -0
  27. package/dist/chunk-4U6YAII5.js.map +1 -0
  28. package/dist/chunk-5GMTBOO6.js +21 -0
  29. package/dist/chunk-5GMTBOO6.js.map +1 -0
  30. package/dist/chunk-5JRJ57CL.mjs +329 -0
  31. package/dist/chunk-5JRJ57CL.mjs.map +1 -0
  32. package/dist/chunk-6C2DKIC7.js +4 -0
  33. package/dist/chunk-6C2DKIC7.js.map +1 -0
  34. package/dist/chunk-6IBFBWC5.mjs +17 -0
  35. package/dist/chunk-6IBFBWC5.mjs.map +1 -0
  36. package/dist/chunk-6KY2ZRVI.js +116 -0
  37. package/dist/chunk-6KY2ZRVI.js.map +1 -0
  38. package/dist/chunk-6VJT3SM4.mjs +182 -0
  39. package/dist/chunk-6VJT3SM4.mjs.map +1 -0
  40. package/dist/chunk-6YZUFMK2.mjs +40 -0
  41. package/dist/chunk-6YZUFMK2.mjs.map +1 -0
  42. package/dist/chunk-7A6R7CGG.js +47 -0
  43. package/dist/chunk-7A6R7CGG.js.map +1 -0
  44. package/dist/chunk-7PWL4V2R.js +4 -0
  45. package/dist/chunk-7PWL4V2R.js.map +1 -0
  46. package/dist/chunk-AA33WDYS.js +161 -0
  47. package/dist/chunk-AA33WDYS.js.map +1 -0
  48. package/dist/chunk-AHRGFXV2.js +525 -0
  49. package/dist/chunk-AHRGFXV2.js.map +1 -0
  50. package/dist/chunk-B63XLDZH.mjs +109 -0
  51. package/dist/chunk-B63XLDZH.mjs.map +1 -0
  52. package/dist/chunk-BX2USEWF.mjs +35 -0
  53. package/dist/chunk-BX2USEWF.mjs.map +1 -0
  54. package/dist/chunk-BYSZT35R.js +150 -0
  55. package/dist/chunk-BYSZT35R.js.map +1 -0
  56. package/dist/chunk-C6OJIHNO.js +12 -0
  57. package/dist/chunk-C6OJIHNO.js.map +1 -0
  58. package/dist/chunk-COOELBX7.mjs +63 -0
  59. package/dist/chunk-COOELBX7.mjs.map +1 -0
  60. package/dist/chunk-D2TW7MNC.mjs +2771 -0
  61. package/dist/chunk-D2TW7MNC.mjs.map +1 -0
  62. package/dist/chunk-D5KEZ6V6.mjs +3 -0
  63. package/dist/chunk-D5KEZ6V6.mjs.map +1 -0
  64. package/dist/chunk-E3GUGJMY.js +46 -0
  65. package/dist/chunk-E3GUGJMY.js.map +1 -0
  66. package/dist/chunk-EBZ2HGJ2.mjs +52 -0
  67. package/dist/chunk-EBZ2HGJ2.mjs.map +1 -0
  68. package/dist/chunk-EDLTUOIA.mjs +210 -0
  69. package/dist/chunk-EDLTUOIA.mjs.map +1 -0
  70. package/dist/chunk-EJQSOT4X.js +4 -0
  71. package/dist/chunk-EJQSOT4X.js.map +1 -0
  72. package/dist/chunk-EUPFS6MZ.mjs +2019 -0
  73. package/dist/chunk-EUPFS6MZ.mjs.map +1 -0
  74. package/dist/chunk-F3XWDC3B.js +77 -0
  75. package/dist/chunk-F3XWDC3B.js.map +1 -0
  76. package/dist/chunk-FFADMVIK.mjs +5127 -0
  77. package/dist/chunk-FFADMVIK.mjs.map +1 -0
  78. package/dist/chunk-FJWS7BKT.mjs +3 -0
  79. package/dist/chunk-FJWS7BKT.mjs.map +1 -0
  80. package/dist/chunk-FJZJDUOR.mjs +3 -0
  81. package/dist/chunk-FJZJDUOR.mjs.map +1 -0
  82. package/dist/chunk-GCFLCO2Z.mjs +145 -0
  83. package/dist/chunk-GCFLCO2Z.mjs.map +1 -0
  84. package/dist/chunk-GEXC4LRP.js +61 -0
  85. package/dist/chunk-GEXC4LRP.js.map +1 -0
  86. package/dist/chunk-GTRAXQGC.mjs +3 -0
  87. package/dist/chunk-GTRAXQGC.mjs.map +1 -0
  88. package/dist/chunk-IKOIRUKW.js +270 -0
  89. package/dist/chunk-IKOIRUKW.js.map +1 -0
  90. package/dist/chunk-IXTWOPRN.js +45 -0
  91. package/dist/chunk-IXTWOPRN.js.map +1 -0
  92. package/dist/chunk-JDXOXGOK.js +547 -0
  93. package/dist/chunk-JDXOXGOK.js.map +1 -0
  94. package/dist/chunk-JSLDWYV7.mjs +558 -0
  95. package/dist/chunk-JSLDWYV7.mjs.map +1 -0
  96. package/dist/chunk-JXLSTVBK.js +336 -0
  97. package/dist/chunk-JXLSTVBK.js.map +1 -0
  98. package/dist/chunk-KHYXK7FG.mjs +49 -0
  99. package/dist/chunk-KHYXK7FG.mjs.map +1 -0
  100. package/dist/chunk-KSMBOWQQ.js +2034 -0
  101. package/dist/chunk-KSMBOWQQ.js.map +1 -0
  102. package/dist/chunk-KU2PXHGB.mjs +83 -0
  103. package/dist/chunk-KU2PXHGB.mjs.map +1 -0
  104. package/dist/chunk-KZANIV3S.mjs +37 -0
  105. package/dist/chunk-KZANIV3S.mjs.map +1 -0
  106. package/dist/chunk-L4BP6YOB.js +20 -0
  107. package/dist/chunk-L4BP6YOB.js.map +1 -0
  108. package/dist/chunk-MRKA2OAF.mjs +75 -0
  109. package/dist/chunk-MRKA2OAF.mjs.map +1 -0
  110. package/dist/chunk-N5EC53MH.mjs +80 -0
  111. package/dist/chunk-N5EC53MH.mjs.map +1 -0
  112. package/dist/chunk-NZANQGDM.mjs +34 -0
  113. package/dist/chunk-NZANQGDM.mjs.map +1 -0
  114. package/dist/chunk-O4GS3XPZ.js +10 -0
  115. package/dist/chunk-O4GS3XPZ.js.map +1 -0
  116. package/dist/chunk-O76QDGRM.js +5154 -0
  117. package/dist/chunk-O76QDGRM.js.map +1 -0
  118. package/dist/chunk-OYEUNZJY.js +114 -0
  119. package/dist/chunk-OYEUNZJY.js.map +1 -0
  120. package/dist/chunk-PHXAGQNB.js +74 -0
  121. package/dist/chunk-PHXAGQNB.js.map +1 -0
  122. package/dist/chunk-PIHHPP7J.mjs +16 -0
  123. package/dist/chunk-PIHHPP7J.mjs.map +1 -0
  124. package/dist/chunk-PXRHVVOU.mjs +499 -0
  125. package/dist/chunk-PXRHVVOU.mjs.map +1 -0
  126. package/dist/chunk-QMA6U6AU.js +36 -0
  127. package/dist/chunk-QMA6U6AU.js.map +1 -0
  128. package/dist/chunk-R6J7IULF.js +44 -0
  129. package/dist/chunk-R6J7IULF.js.map +1 -0
  130. package/dist/chunk-R7G6TWIS.mjs +10 -0
  131. package/dist/chunk-R7G6TWIS.mjs.map +1 -0
  132. package/dist/chunk-RUMGFI6L.mjs +544 -0
  133. package/dist/chunk-RUMGFI6L.mjs.map +1 -0
  134. package/dist/chunk-S54JWSJF.js +565 -0
  135. package/dist/chunk-S54JWSJF.js.map +1 -0
  136. package/dist/chunk-SK5UGG6A.js +2041 -0
  137. package/dist/chunk-SK5UGG6A.js.map +1 -0
  138. package/dist/chunk-SKIYDKIS.mjs +70 -0
  139. package/dist/chunk-SKIYDKIS.mjs.map +1 -0
  140. package/dist/chunk-SZNS5IK6.mjs +322 -0
  141. package/dist/chunk-SZNS5IK6.mjs.map +1 -0
  142. package/dist/chunk-T7JIPZAC.js +66 -0
  143. package/dist/chunk-T7JIPZAC.js.map +1 -0
  144. package/dist/chunk-TGYQHO2E.mjs +864 -0
  145. package/dist/chunk-TGYQHO2E.mjs.map +1 -0
  146. package/dist/chunk-TT3MHN42.mjs +8 -0
  147. package/dist/chunk-TT3MHN42.mjs.map +1 -0
  148. package/dist/chunk-UM55U65W.mjs +268 -0
  149. package/dist/chunk-UM55U65W.mjs.map +1 -0
  150. package/dist/chunk-UQ2HALUD.js +72 -0
  151. package/dist/chunk-UQ2HALUD.js.map +1 -0
  152. package/dist/chunk-UXWT7G77.js +82 -0
  153. package/dist/chunk-UXWT7G77.js.map +1 -0
  154. package/dist/chunk-VNS5WDWO.mjs +7 -0
  155. package/dist/chunk-VNS5WDWO.mjs.map +1 -0
  156. package/dist/chunk-VRWZLGR7.js +4 -0
  157. package/dist/chunk-VRWZLGR7.js.map +1 -0
  158. package/dist/chunk-VZLDSNH4.mjs +22 -0
  159. package/dist/chunk-VZLDSNH4.mjs.map +1 -0
  160. package/dist/chunk-W6P3YETJ.js +92 -0
  161. package/dist/chunk-W6P3YETJ.js.map +1 -0
  162. package/dist/chunk-WPKFFQCR.mjs +90 -0
  163. package/dist/chunk-WPKFFQCR.mjs.map +1 -0
  164. package/dist/chunk-WTVTI5TO.mjs +22 -0
  165. package/dist/chunk-WTVTI5TO.mjs.map +1 -0
  166. package/dist/chunk-XJOBZ4RJ.js +44 -0
  167. package/dist/chunk-XJOBZ4RJ.js.map +1 -0
  168. package/dist/chunk-XP2JDNDU.js +325 -0
  169. package/dist/chunk-XP2JDNDU.js.map +1 -0
  170. package/dist/chunk-Y4V5CEWD.mjs +112 -0
  171. package/dist/chunk-Y4V5CEWD.mjs.map +1 -0
  172. package/dist/chunk-YERN2UWM.js +116 -0
  173. package/dist/chunk-YERN2UWM.js.map +1 -0
  174. package/dist/chunk-ZKJQWFAA.mjs +114 -0
  175. package/dist/chunk-ZKJQWFAA.mjs.map +1 -0
  176. package/dist/chunk-ZOON3S3Y.mjs +138 -0
  177. package/dist/chunk-ZOON3S3Y.mjs.map +1 -0
  178. package/dist/chunk-ZP6QRAYC.mjs +2024 -0
  179. package/dist/chunk-ZP6QRAYC.mjs.map +1 -0
  180. package/dist/chunk-ZSTFX7FV.js +9 -0
  181. package/dist/chunk-ZSTFX7FV.js.map +1 -0
  182. package/dist/client/index.js +23 -331
  183. package/dist/client/index.js.map +1 -1
  184. package/dist/client/index.mjs +3 -330
  185. package/dist/client/index.mjs.map +1 -1
  186. package/dist/comparison/index.js +28 -111
  187. package/dist/comparison/index.js.map +1 -1
  188. package/dist/comparison/index.mjs +2 -107
  189. package/dist/comparison/index.mjs.map +1 -1
  190. package/dist/components/contact.js +21 -931
  191. package/dist/components/contact.js.map +1 -1
  192. package/dist/components/contact.mjs +12 -909
  193. package/dist/components/contact.mjs.map +1 -1
  194. package/dist/components/electron-download.js +12 -124
  195. package/dist/components/electron-download.js.map +1 -1
  196. package/dist/components/electron-download.mjs +4 -106
  197. package/dist/components/electron-download.mjs.map +1 -1
  198. package/dist/components/explore-cta.js +8 -112
  199. package/dist/components/explore-cta.js.map +1 -1
  200. package/dist/components/explore-cta.mjs +3 -114
  201. package/dist/components/explore-cta.mjs.map +1 -1
  202. package/dist/components/explore.js +62 -7833
  203. package/dist/components/explore.js.map +1 -1
  204. package/dist/components/explore.mjs +13 -7800
  205. package/dist/components/explore.mjs.map +1 -1
  206. package/dist/components/launch-countdown.js +8 -83
  207. package/dist/components/launch-countdown.js.map +1 -1
  208. package/dist/components/launch-countdown.mjs +3 -85
  209. package/dist/components/launch-countdown.mjs.map +1 -1
  210. package/dist/components/newsletter.js +20 -993
  211. package/dist/components/newsletter.js.map +1 -1
  212. package/dist/components/newsletter.mjs +11 -971
  213. package/dist/components/newsletter.mjs.map +1 -1
  214. package/dist/components/partners.js +24 -1302
  215. package/dist/components/partners.js.map +1 -1
  216. package/dist/components/partners.mjs +15 -1276
  217. package/dist/components/partners.mjs.map +1 -1
  218. package/dist/components/pricing.js +49 -1249
  219. package/dist/components/pricing.js.map +1 -1
  220. package/dist/components/pricing.mjs +8 -1226
  221. package/dist/components/pricing.mjs.map +1 -1
  222. package/dist/components/problems-solved.js +8 -150
  223. package/dist/components/problems-solved.js.map +1 -1
  224. package/dist/components/problems-solved.mjs +4 -133
  225. package/dist/components/problems-solved.mjs.map +1 -1
  226. package/dist/components/resource-links.js +8 -304
  227. package/dist/components/resource-links.js.map +1 -1
  228. package/dist/components/resource-links.mjs +5 -308
  229. package/dist/components/resource-links.mjs.map +1 -1
  230. package/dist/components/social-links.js +8 -343
  231. package/dist/components/social-links.js.map +1 -1
  232. package/dist/components/social-links.mjs +5 -347
  233. package/dist/components/social-links.mjs.map +1 -1
  234. package/dist/components/unsubscribe.js +10 -627
  235. package/dist/components/unsubscribe.js.map +1 -1
  236. package/dist/components/unsubscribe.mjs +6 -611
  237. package/dist/components/unsubscribe.mjs.map +1 -1
  238. package/dist/components/waitlist.js +21 -1001
  239. package/dist/components/waitlist.js.map +1 -1
  240. package/dist/components/waitlist.mjs +12 -982
  241. package/dist/components/waitlist.mjs.map +1 -1
  242. package/dist/components/website-switcher.js +12 -175
  243. package/dist/components/website-switcher.js.map +1 -1
  244. package/dist/components/website-switcher.mjs +4 -157
  245. package/dist/components/website-switcher.mjs.map +1 -1
  246. package/dist/content/index.js +118 -3616
  247. package/dist/content/index.js.map +1 -1
  248. package/dist/content/index.mjs +12 -3567
  249. package/dist/content/index.mjs.map +1 -1
  250. package/dist/hooks/index.js +37 -2321
  251. package/dist/hooks/index.js.map +1 -1
  252. package/dist/hooks/index.mjs +6 -2318
  253. package/dist/hooks/index.mjs.map +1 -1
  254. package/dist/index.d.mts +1 -1
  255. package/dist/index.d.ts +1 -1
  256. package/dist/index.js +4145 -20599
  257. package/dist/index.js.map +1 -1
  258. package/dist/index.mjs +3766 -20567
  259. package/dist/index.mjs.map +1 -1
  260. package/dist/product/index.js +20 -393
  261. package/dist/product/index.js.map +1 -1
  262. package/dist/product/index.mjs +5 -394
  263. package/dist/product/index.mjs.map +1 -1
  264. package/dist/seo/index.js +8 -76
  265. package/dist/seo/index.js.map +1 -1
  266. package/dist/seo/index.mjs +3 -78
  267. package/dist/seo/index.mjs.map +1 -1
  268. package/dist/store/index.js +51 -2650
  269. package/dist/store/index.js.map +1 -1
  270. package/dist/store/index.mjs +13 -2619
  271. package/dist/store/index.mjs.map +1 -1
  272. package/dist/utils/index.js +69 -134
  273. package/dist/utils/index.js.map +1 -1
  274. package/dist/utils/index.mjs +5 -122
  275. package/dist/utils/index.mjs.map +1 -1
  276. package/package.json +2 -1
@@ -1,2320 +1,8 @@
1
- import { createContext, useMemo, useState, useRef, useCallback, useEffect, useContext } from 'react';
2
- import 'react/jsx-runtime';
3
-
4
- var __defProp = Object.defineProperty;
5
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7
-
8
- // src/client/security.ts
9
- var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1"]);
10
- var RESERVED_HEADERS = /* @__PURE__ */ new Set([
11
- "authorization",
12
- "cookie",
13
- "x-actor-id",
14
- "x-actor-type",
15
- "x-consent-granted-by",
16
- "x-consent-scope",
17
- "x-consent-granted-at",
18
- "x-consent-expires-at"
19
- ]);
20
- function validateGatewayUrl(value) {
21
- let url;
22
- try {
23
- url = new URL(value);
24
- } catch {
25
- throw new Error("Gateway URL must be a valid absolute URL");
26
- }
27
- if (url.protocol === "https:") {
28
- return url.toString();
29
- }
30
- if (url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname.toLowerCase())) {
31
- return url.toString();
32
- }
33
- throw new Error("Gateway URL must use HTTPS unless it targets localhost");
34
- }
35
- function sanitizeHeaders(headers) {
36
- if (!headers) return void 0;
37
- return Object.fromEntries(
38
- Object.entries(headers).filter(
39
- ([key]) => !RESERVED_HEADERS.has(key.toLowerCase())
40
- )
41
- );
42
- }
43
- var CF_ACCESS_GATED_HOSTS = /* @__PURE__ */ new Set([
44
- "alphagraphql.burdenoff.com",
45
- "alphagraphqlworkspaces.burdenoff.com"
46
- ]);
47
- function cfAccessHeaders(gatewayUrl, cfAccess) {
48
- const clientId = cfAccess?.clientId?.trim();
49
- const clientSecret = cfAccess?.clientSecret?.trim();
50
- if (!clientId || !clientSecret) return {};
51
- let host;
52
- try {
53
- host = new URL(gatewayUrl).hostname.toLowerCase();
54
- } catch {
55
- return {};
56
- }
57
- if (!CF_ACCESS_GATED_HOSTS.has(host)) return {};
58
- return {
59
- "CF-Access-Client-Id": clientId,
60
- "CF-Access-Client-Secret": clientSecret
61
- };
62
- }
63
-
64
- // src/client/graphql-client.ts
65
- var _WebSDKClient = class _WebSDKClient {
66
- constructor(config) {
67
- __publicField(this, "config");
68
- __publicField(this, "queryCache", /* @__PURE__ */ new Map());
69
- __publicField(this, "inflight", /* @__PURE__ */ new Map());
70
- this.config = {
71
- ...config,
72
- gatewayUrl: validateGatewayUrl(config.gatewayUrl),
73
- headers: sanitizeHeaders(config.headers)
74
- };
75
- }
76
- getConfig() {
77
- return this.config;
78
- }
79
- /**
80
- * Execute a GraphQL query (with deduplication and caching).
81
- *
82
- * Pass `{ cache: false }` to bypass the cache entirely — required for poll
83
- * loops, where every tick must reach the network.
84
- */
85
- async query(query, variables, options) {
86
- if (options?.cache === false) {
87
- return this.request(query, variables, true, options.timeoutMs);
88
- }
89
- const cacheKey = JSON.stringify({ query, variables });
90
- const cached = this.queryCache.get(cacheKey);
91
- if (cached) {
92
- if (Date.now() - cached.ts < _WebSDKClient.CACHE_TTL) {
93
- return cached.data;
94
- }
95
- this.queryCache.delete(cacheKey);
96
- }
97
- const existing = this.inflight.get(cacheKey);
98
- if (existing) {
99
- return existing;
100
- }
101
- const promise = this.request(query, variables, true, options?.timeoutMs).then((result) => {
102
- if (result.data && !result.errors?.length) {
103
- if (this.queryCache.size >= _WebSDKClient.MAX_CACHE_ENTRIES) {
104
- const oldestEntry = this.queryCache.keys().next().value;
105
- if (oldestEntry) {
106
- this.queryCache.delete(oldestEntry);
107
- }
108
- }
109
- this.queryCache.set(cacheKey, { data: result, ts: Date.now() });
110
- }
111
- return result;
112
- }).finally(() => {
113
- this.inflight.delete(cacheKey);
114
- });
115
- this.inflight.set(cacheKey, promise);
116
- return promise;
117
- }
118
- /**
119
- * Execute a GraphQL mutation
120
- */
121
- async mutate(mutation, variables, options) {
122
- return this.request(mutation, variables, false, options?.timeoutMs);
123
- }
124
- /** HTTP statuses worth another attempt — transient server/edge conditions. */
125
- static isRetriableStatus(status) {
126
- return status === 429 || status === 408 || status >= 500 && status < 600;
127
- }
128
- static sleep(ms) {
129
- return new Promise((resolve) => setTimeout(resolve, ms));
130
- }
131
- /**
132
- * Perform the HTTP call with a hard timeout. Every outcome resolves to a
133
- * GraphQLResponse — callers never hang, so a UI's `loading` state always
134
- * settles into data or a renderable error.
135
- */
136
- async attempt(query, variables, timeoutMs) {
137
- const controller = new AbortController();
138
- const timer = setTimeout(() => controller.abort(), timeoutMs);
139
- try {
140
- const response = await fetch(this.config.gatewayUrl, {
141
- method: "POST",
142
- headers: {
143
- "Content-Type": "application/json",
144
- "x-product-id": this.config.productId,
145
- ...this.config.headers,
146
- ...cfAccessHeaders(this.config.gatewayUrl, this.config.cfAccess)
147
- },
148
- body: JSON.stringify({ query, variables }),
149
- signal: controller.signal
150
- });
151
- if (!response.ok) {
152
- console.error(
153
- "[WebSDK] GraphQL request failed",
154
- response.status,
155
- response.statusText
156
- );
157
- return {
158
- res: {
159
- errors: [
160
- {
161
- message: `HTTP ${response.status}: ${response.statusText}`,
162
- extensions: { code: `HTTP_${response.status}` }
163
- }
164
- ]
165
- },
166
- retriable: _WebSDKClient.isRetriableStatus(response.status)
167
- };
168
- }
169
- return {
170
- res: await response.json(),
171
- retriable: false
172
- };
173
- } catch (error) {
174
- const aborted = error instanceof Error && (error.name === "AbortError" || controller.signal.aborted);
175
- const message = aborted ? `Request timed out after ${timeoutMs}ms` : error instanceof Error ? error.message : "Network error";
176
- console.error("[WebSDK] Network error", message);
177
- return {
178
- res: {
179
- errors: [
180
- {
181
- message,
182
- extensions: { code: aborted ? "TIMEOUT" : "NETWORK_ERROR" }
183
- }
184
- ]
185
- },
186
- // Transport-level failures are worth one more try; a genuine outage
187
- // just fails twice quickly and still renders an error state.
188
- retriable: true
189
- };
190
- } finally {
191
- clearTimeout(timer);
192
- }
193
- }
194
- async request(query, variables, retry = true, timeoutOverrideMs) {
195
- const timeoutMs = timeoutOverrideMs ?? this.config.timeoutMs ?? _WebSDKClient.DEFAULT_TIMEOUT_MS;
196
- const maxRetries = retry ? this.config.maxRetries ?? _WebSDKClient.DEFAULT_MAX_RETRIES : 0;
197
- let last;
198
- for (let i = 0; i <= maxRetries; i++) {
199
- const { res, retriable } = await this.attempt(
200
- query,
201
- variables,
202
- timeoutMs
203
- );
204
- if (!retriable || i === maxRetries) return res;
205
- last = res;
206
- await _WebSDKClient.sleep(
207
- _WebSDKClient.RETRY_BASE_DELAY_MS * (i + 1) + Math.random() * 200
208
- );
209
- }
210
- return last;
211
- }
212
- };
213
- __publicField(_WebSDKClient, "CACHE_TTL", 5 * 60 * 1e3);
214
- // 5 minutes
215
- __publicField(_WebSDKClient, "MAX_CACHE_ENTRIES", 100);
216
- __publicField(_WebSDKClient, "DEFAULT_TIMEOUT_MS", 12e3);
217
- __publicField(_WebSDKClient, "DEFAULT_MAX_RETRIES", 1);
218
- __publicField(_WebSDKClient, "RETRY_BASE_DELAY_MS", 400);
219
- var WebSDKContext = createContext(null);
220
- function useWebSDK() {
221
- const client = useContext(WebSDKContext);
222
- if (!client) {
223
- throw new Error("useWebSDK must be used within a WebSDKProvider");
224
- }
225
- return client;
226
- }
227
- function useWebSDKConfig() {
228
- const client = useWebSDK();
229
- return client.getConfig();
230
- }
231
-
232
- // src/components/explore-types.ts
233
- var EXPLORE_MESSAGE_FIELDS = (
234
- /* GraphQL */
235
- `
236
- id
237
- conversationId
238
- role
239
- status
240
- content
241
- partialContent
242
- activity
243
- references {
244
- url
245
- title
246
- description
247
- product
248
- imageUrl
249
- index
250
- }
251
- ctas {
252
- kind
253
- label
254
- url
255
- product
256
- }
257
- followUps
258
- answered
259
- attachments {
260
- name
261
- mimeType
262
- size
263
- textExtracted
264
- }
265
- errorCode
266
- createdAt
267
- completedAt
268
- `
269
- );
270
- var EXPLORE_OWN_MESSAGE_FIELDS = (
271
- /* GraphQL */
272
- `
273
- ${EXPLORE_MESSAGE_FIELDS}
274
- feedback {
275
- rating
276
- reason
277
- comment
278
- createdAt
279
- }
280
- `
281
- );
282
- var EXPLORE_CATALOG_ESTABLISHED_FIELDS = (
283
- /* GraphQL */
284
- `
285
- enabled
286
- products {
287
- slug
288
- name
289
- tagline
290
- website
291
- }
292
- examplePrompts
293
- welcomeTitle
294
- welcomeBody
295
- limits {
296
- maxMessageLength
297
- maxTurnsPerConversation
298
- messagesPerDay
299
- historyTurns
300
- }
301
- captchaRequired
302
- recaptchaSiteKey`
303
- );
304
- var EXPLORE_CATALOG_HIGHLIGHT_FIELD = (
305
- /* GraphQL */
306
- `
307
- conceptHighlights {
308
- product
309
- productName
310
- title
311
- url
312
- imageUrl
313
- alt
314
- }`
315
- );
316
- function exploreCatalogDocument(extraFields) {
317
- return (
318
- /* GraphQL */
319
- `
320
- query ExploreCatalog($productSlug: String) {
321
- exploreCatalog(productSlug: $productSlug) {${EXPLORE_CATALOG_ESTABLISHED_FIELDS}${extraFields}
322
- }
323
- }
324
- `
325
- );
326
- }
327
- var EXPLORE_CATALOG_QUERY = exploreCatalogDocument(
328
- EXPLORE_CATALOG_HIGHLIGHT_FIELD
329
- );
330
- var EXPLORE_CATALOG_QUERY_WITHOUT_HIGHLIGHTS = exploreCatalogDocument("");
331
- var EXPLORE_MESSAGE_QUERY = (
332
- /* GraphQL */
333
- `
334
- query ExploreMessage($conversationToken: String!, $id: ID!) {
335
- exploreMessage(conversationToken: $conversationToken, id: $id) {
336
- ${EXPLORE_OWN_MESSAGE_FIELDS}
337
- }
338
- }
339
- `
340
- );
341
- var SEND_EXPLORE_MESSAGE_MUTATION = (
342
- /* GraphQL */
343
- `
344
- mutation SendExploreMessage($input: SendExploreMessageInput!) {
345
- sendExploreMessage(input: $input) {
346
- conversation {
347
- id
348
- token
349
- productSlug
350
- turnCount
351
- createdAt
352
- }
353
- userMessage {
354
- ${EXPLORE_OWN_MESSAGE_FIELDS}
355
- }
356
- assistantMessage {
357
- ${EXPLORE_OWN_MESSAGE_FIELDS}
358
- }
359
- remainingToday
360
- }
361
- }
362
- `
363
- );
364
- var RECORD_EXPLORE_CLICK_MUTATION = (
365
- /* GraphQL */
366
- `
367
- mutation RecordExploreClick($input: RecordExploreClickInput!) {
368
- recordExploreClick(input: $input) {
369
- recorded
370
- }
371
- }
372
- `
373
- );
374
- var SUBMIT_EXPLORE_FEEDBACK_MUTATION = (
375
- /* GraphQL */
376
- `
377
- mutation SubmitExploreFeedback($input: SubmitExploreFeedbackInput!) {
378
- submitExploreFeedback(input: $input) {
379
- recorded
380
- feedback {
381
- rating
382
- reason
383
- comment
384
- createdAt
385
- }
386
- }
387
- }
388
- `
389
- );
390
- var ESCALATE_EXPLORE_CONVERSATION_MUTATION = (
391
- /* GraphQL */
392
- `
393
- mutation EscalateExploreConversation(
394
- $input: EscalateExploreConversationInput!
395
- ) {
396
- escalateExploreConversation(input: $input) {
397
- created
398
- escalation {
399
- email
400
- createdAt
401
- }
402
- }
403
- }
404
- `
405
- );
406
- var CREATE_EXPLORE_SHARE_LINK_MUTATION = (
407
- /* GraphQL */
408
- `
409
- mutation CreateExploreShareLink($conversationToken: String!) {
410
- createExploreShareLink(conversationToken: $conversationToken) {
411
- shareToken
412
- }
413
- }
414
- `
415
- );
416
- var EXPLORE_SHARED_CONVERSATION_QUERY = (
417
- /* GraphQL */
418
- `
419
- query ExploreSharedConversation($shareToken: String!) {
420
- exploreSharedConversation(shareToken: $shareToken) {
421
- ${EXPLORE_MESSAGE_FIELDS}
422
- }
423
- }
424
- `
425
- );
426
-
427
- // src/utils/product-slug.ts
428
- var PRODUCT_SLUG_RENAMES = Object.freeze(
429
- [Object.freeze({ legacy: "botlit", current: "botmanor" })]
430
- );
431
- Object.freeze(
432
- Object.fromEntries(PRODUCT_SLUG_RENAMES.map((r) => [r.legacy, r.current]))
433
- );
434
- var PRODUCT_SLUG_EMIT = Object.freeze({ productSlug: "current" });
435
- function findRename(slug) {
436
- const wanted = slug.toLowerCase();
437
- return PRODUCT_SLUG_RENAMES.find(
438
- (r) => r.legacy === wanted || r.current === wanted
439
- );
440
- }
441
- function normalizeProductSlug(slug) {
442
- return findRename(slug)?.current ?? slug;
443
- }
444
- function legacyProductSlug(slug) {
445
- return findRename(slug)?.legacy ?? slug;
446
- }
447
- function emitProductSlug(slug) {
448
- return PRODUCT_SLUG_EMIT.productSlug === "current" ? normalizeProductSlug(slug) : legacyProductSlug(slug);
449
- }
450
-
451
- // src/data/products.ts
452
- var ECOSYSTEM_PRODUCTS = [
453
- {
454
- slug: "workspaces",
455
- name: "Workspaces",
456
- websiteUrl: "https://burdenoff.com"
457
- },
458
- {
459
- slug: "vibecontrols",
460
- name: "VibeControls",
461
- websiteUrl: "https://vibecontrols.com"
462
- },
463
- // FluidGrids ships on www.fluidgrids.ai — fluidgrids.com only redirects there. The explore
464
- // catalog and the site's own sitemap use this origin, and so must the fallback catalog
465
- // built from this list, or /explore rejects FluidGrids concept images until it loads.
466
- {
467
- slug: "fluidgrids",
468
- name: "FluidGrids",
469
- websiteUrl: "https://www.fluidgrids.ai"
470
- },
471
- // BotManor ships on www.botmanor.com (the apex redirects there; the old botlit.ai domain
472
- // still serves the same site but is no longer the name we link to).
473
- // The slug follows the botlit → botmanor rename switch (utils/product-slug.ts).
474
- {
475
- slug: emitProductSlug("botmanor"),
476
- name: "BotManor",
477
- websiteUrl: "https://www.botmanor.com"
478
- },
479
- {
480
- slug: "bigconsole",
481
- name: "BigConsole",
482
- websiteUrl: "https://bigconsole.com"
483
- },
484
- {
485
- slug: "semanticfed",
486
- name: "SemanticFed",
487
- websiteUrl: "https://semanticfed.com"
488
- },
489
- {
490
- slug: "intelwatchtower",
491
- name: "IntelWatchtower",
492
- websiteUrl: "https://intelwatchtower.com"
493
- },
494
- { slug: "buildmyiq", name: "BuildMyIQ", websiteUrl: "https://buildmyiq.com" },
495
- {
496
- slug: "assethandler",
497
- name: "AssetHandler",
498
- websiteUrl: "https://assethandler.com"
499
- },
500
- {
501
- slug: "crewfoundry",
502
- name: "CrewFoundry",
503
- websiteUrl: "https://crewfoundry.com"
504
- },
505
- {
506
- slug: "planmagnet",
507
- name: "PlanMagnet",
508
- websiteUrl: "https://planmagnet.com"
509
- },
510
- {
511
- slug: "eventfullymanaged",
512
- name: "EventfullyManaged",
513
- websiteUrl: "https://eventfullymanaged.com"
514
- },
515
- {
516
- slug: "headshotmarketing",
517
- name: "HeadshotMarketing",
518
- websiteUrl: "https://headshotmarketing.com"
519
- },
520
- {
521
- slug: "technospam",
522
- name: "TechnoSpam",
523
- websiteUrl: "https://technospam.com"
524
- },
525
- { slug: "kadaikodi", name: "Kadaikodi", websiteUrl: "https://kadaikodi.com" },
526
- {
527
- slug: "movethewheels",
528
- name: "MoveTheWheels",
529
- websiteUrl: "https://movethewheels.com"
530
- },
531
- {
532
- slug: "healthybowl",
533
- name: "Healthy Bowl",
534
- websiteUrl: "https://gethealthybowl.com"
535
- },
536
- { slug: "ggnomad", name: "GGNomad", websiteUrl: "https://ggnomad.com" },
537
- {
538
- slug: "timecampus",
539
- name: "TimeCampus",
540
- websiteUrl: "https://timecampus.com"
541
- },
542
- {
543
- slug: "manufacturedops",
544
- name: "ManufacturedOps",
545
- websiteUrl: "https://manufacturedops.com"
546
- },
547
- {
548
- slug: "theglobalfuel",
549
- name: "TheGlobalFuel",
550
- websiteUrl: "https://theglobalfuel.com"
551
- },
552
- {
553
- slug: "housingvista",
554
- name: "HousingVista",
555
- websiteUrl: "https://housingvista.com"
556
- },
557
- {
558
- slug: "proserviceworld",
559
- name: "ProServiceWorld",
560
- websiteUrl: "https://proserviceworld.com"
561
- },
562
- {
563
- slug: "mybodyshield",
564
- name: "MyBodyShield",
565
- websiteUrl: "https://mybodyshield.com"
566
- },
567
- {
568
- slug: "artistrybase",
569
- name: "ArtistryBase",
570
- websiteUrl: "https://artistrybase.com"
571
- },
572
- {
573
- slug: "theculturepost",
574
- name: "TheCulturePost",
575
- websiteUrl: "https://theculturepost.com"
576
- },
577
- { slug: "collabkin", name: "CollabKin", websiteUrl: "https://collabkin.com" },
578
- {
579
- slug: "comradecircle",
580
- name: "ComradeCircle",
581
- websiteUrl: "https://comradecircle.com"
582
- },
583
- {
584
- slug: "brainyrich",
585
- name: "BrainyRich",
586
- websiteUrl: "https://brainyrich.com"
587
- },
588
- {
589
- slug: "cosmicintersection",
590
- name: "CosmicIntersection",
591
- websiteUrl: "https://cosmicintersection.com"
592
- },
593
- {
594
- slug: "govcitizenhub",
595
- name: "GovCitizenHub",
596
- websiteUrl: "https://govcitizenhub.com"
597
- },
598
- {
599
- slug: "adaptercloud",
600
- name: "AdapterCloud",
601
- websiteUrl: "https://adaptercloud.com"
602
- },
603
- {
604
- slug: "subscriberbot",
605
- name: "Subscriber Bot",
606
- websiteUrl: "https://subscriberbot.com"
607
- },
608
- {
609
- slug: "hookmovies",
610
- name: "HookMovies",
611
- websiteUrl: "https://hookmovies.com"
612
- },
613
- {
614
- slug: "coolandlovely",
615
- name: "CoolAndLovely",
616
- websiteUrl: "https://coolandlovely.com"
617
- },
618
- {
619
- slug: "atheletebridge",
620
- name: "AthleteBridge",
621
- websiteUrl: "https://atheletebridge.com"
622
- },
623
- {
624
- slug: "labsofscience",
625
- name: "LabsOfScience",
626
- websiteUrl: "https://labsofscience.com"
627
- },
628
- {
629
- slug: "ecoimpacthub",
630
- name: "EcoImpactHub",
631
- websiteUrl: "https://ecoimpacthub.com"
632
- }
633
- ];
634
-
635
- // src/utils/recaptcha-v3.ts
636
- var SCRIPT_ID = "boff-recaptcha-v3";
637
- var SCRIPT_SRC = "https://www.google.com/recaptcha/api.js?render=";
638
- var EXPLORE_RECAPTCHA_ACTION = "explore_chat";
639
- var loaders = /* @__PURE__ */ new Map();
640
- function isBrowser() {
641
- return typeof window !== "undefined" && typeof document !== "undefined";
642
- }
643
- function loadRecaptchaV3(siteKey) {
644
- if (!siteKey) {
645
- return Promise.reject(new Error("reCAPTCHA site key is required"));
646
- }
647
- if (!isBrowser()) {
648
- return Promise.reject(
649
- new Error("reCAPTCHA v3 can only be loaded in a browser")
650
- );
651
- }
652
- const existing = loaders.get(siteKey);
653
- if (existing) return existing;
654
- const promise = new Promise((resolve, reject) => {
655
- const ready = () => {
656
- const api = window.grecaptcha;
657
- if (!api) {
658
- reject(new Error("reCAPTCHA loaded but grecaptcha is unavailable"));
659
- return;
660
- }
661
- api.ready(() => resolve(api));
662
- };
663
- if (window.grecaptcha) {
664
- ready();
665
- return;
666
- }
667
- const scriptId = `${SCRIPT_ID}-${siteKey}`;
668
- const found = document.getElementById(scriptId);
669
- if (found) {
670
- found.addEventListener("load", ready, { once: true });
671
- found.addEventListener(
672
- "error",
673
- () => reject(new Error("Failed to load reCAPTCHA v3")),
674
- { once: true }
675
- );
676
- return;
677
- }
678
- const script = document.createElement("script");
679
- script.id = scriptId;
680
- script.src = `${SCRIPT_SRC}${encodeURIComponent(siteKey)}`;
681
- script.async = true;
682
- script.defer = true;
683
- script.addEventListener("load", ready, { once: true });
684
- script.addEventListener(
685
- "error",
686
- () => {
687
- loaders.delete(siteKey);
688
- reject(new Error("Failed to load reCAPTCHA v3"));
689
- },
690
- { once: true }
691
- );
692
- document.head.appendChild(script);
693
- });
694
- loaders.set(siteKey, promise);
695
- return promise;
696
- }
697
- async function getRecaptchaV3Token(siteKey, action = EXPLORE_RECAPTCHA_ACTION) {
698
- const api = await loadRecaptchaV3(siteKey);
699
- return api.execute(siteKey, { action });
700
- }
701
-
702
- // src/hooks/use-explore-chat.ts
703
- var DEFAULT_STORAGE_KEY = "boff.explore.v1";
704
- var HISTORY_SUFFIX = ".history";
705
- var MAX_ARCHIVED_CONVERSATIONS = 15;
706
- var DEFAULT_POLL_INTERVAL_MS = 1500;
707
- var DEFAULT_POLL_TIMEOUT_MS = 9e4;
708
- var POLL_REQUEST_TIMEOUT_MS = 1e4;
709
- var SEND_REQUEST_TIMEOUT_MS = 18e3;
710
- var MAX_CONSECUTIVE_POLL_FAILURES = 4;
711
- var MAX_PERSISTED_MESSAGES = 40;
712
- var FALLBACK_EXPLORE_LIMITS = {
713
- maxMessageLength: 2e3,
714
- maxTurnsPerConversation: 20,
715
- messagesPerDay: 100,
716
- historyTurns: 6
717
- };
718
- var DEFAULT_EXPLORE_EXAMPLE_PROMPTS = [
719
- "Every course we run lives in a different spreadsheet.",
720
- "We only hear a machine is down after the line has stopped.",
721
- "Members quietly stop showing up and we never know why.",
722
- "Which of your products fits a problem like mine?"
723
- ];
724
- var FALLBACK_WELCOME_TITLE = "What problem are you trying to solve?";
725
- var FALLBACK_WELCOME_BODY = "Describe the problem, in your own words. You can also ask about a specific product or compare a few. Every answer comes straight from our documentation.";
726
- function buildFallbackCatalog(examplePrompts, welcome) {
727
- return {
728
- enabled: true,
729
- products: ECOSYSTEM_PRODUCTS.map((p) => ({
730
- slug: p.slug,
731
- name: p.name,
732
- tagline: null,
733
- website: p.websiteUrl
734
- })),
735
- examplePrompts: examplePrompts?.length ? examplePrompts : DEFAULT_EXPLORE_EXAMPLE_PROMPTS,
736
- welcomeTitle: welcome?.title ?? FALLBACK_WELCOME_TITLE,
737
- welcomeBody: welcome?.body ?? FALLBACK_WELCOME_BODY,
738
- limits: FALLBACK_EXPLORE_LIMITS,
739
- captchaRequired: false,
740
- recaptchaSiteKey: null,
741
- // Empty, and deliberately not synthesised from `ECOSYSTEM_PRODUCTS`: a concept highlight
742
- // needs a real published illustration URL, and this SDK has no registry of them. An
743
- // invented path would render 38 broken frames on the one screen every prerender captures.
744
- // The strip renders nothing at all when the list is empty, which is the honest fallback.
745
- conceptHighlights: []
746
- };
747
- }
748
- var BAKED_CATALOG_ELEMENT_ID = "boff-explore-catalog";
749
- function bakedCatalogLocale() {
750
- if (typeof navigator === "undefined") return "";
751
- return (navigator.language || "").toLowerCase().split("-")[0] ?? "";
752
- }
753
- function snapshotBakedElement() {
754
- if (typeof document === "undefined") return null;
755
- const el = document.getElementById(BAKED_CATALOG_ELEMENT_ID);
756
- if (!el || el.tagName !== "SCRIPT" || el.getAttribute("type") !== "application/json")
757
- return null;
758
- return {
759
- product: el.getAttribute("data-product") ?? "",
760
- locale: el.getAttribute("data-locale") ?? "",
761
- text: el.textContent ?? ""
762
- };
763
- }
764
- var BAKED_AT_LOAD = snapshotBakedElement();
765
- function isCatalogShape(value) {
766
- if (!value || typeof value !== "object") return false;
767
- const c = value;
768
- const listOrAbsent = (v) => v === void 0 || v === null || Array.isArray(v);
769
- const textOrAbsent = (v) => v === void 0 || v === null || typeof v === "string";
770
- return (c["enabled"] === void 0 || typeof c["enabled"] === "boolean") && listOrAbsent(c["products"]) && listOrAbsent(c["examplePrompts"]) && listOrAbsent(c["conceptHighlights"]) && textOrAbsent(c["welcomeTitle"]) && textOrAbsent(c["welcomeBody"]);
771
- }
772
- function readBakedCatalog(productSlug) {
773
- const baked = snapshotBakedElement() ?? BAKED_AT_LOAD;
774
- if (!baked) return null;
775
- if (baked.product !== (productSlug ?? "")) return null;
776
- if (baked.locale && baked.locale !== bakedCatalogLocale()) return null;
777
- try {
778
- const parsed = JSON.parse(baked.text);
779
- return isCatalogShape(parsed) ? parsed : null;
780
- } catch {
781
- return null;
782
- }
783
- }
784
- function normalizeCatalog(raw, fallback) {
785
- return {
786
- enabled: raw.enabled !== false,
787
- products: raw.products?.length ? raw.products : fallback.products,
788
- examplePrompts: raw.examplePrompts?.length ? raw.examplePrompts : fallback.examplePrompts,
789
- welcomeTitle: raw.welcomeTitle || fallback.welcomeTitle,
790
- welcomeBody: raw.welcomeBody || fallback.welcomeBody,
791
- limits: {
792
- maxMessageLength: raw.limits?.maxMessageLength || fallback.limits.maxMessageLength,
793
- maxTurnsPerConversation: raw.limits?.maxTurnsPerConversation || fallback.limits.maxTurnsPerConversation,
794
- messagesPerDay: raw.limits?.messagesPerDay || fallback.limits.messagesPerDay,
795
- historyTurns: raw.limits?.historyTurns || fallback.limits.historyTurns
796
- },
797
- captchaRequired: raw.captchaRequired === true,
798
- recaptchaSiteKey: raw.recaptchaSiteKey ?? null,
799
- // `[ExploreConceptHighlight!]!` on the wire, so a gateway that KNOWS the field always
800
- // sends an array. The one response that arrives without it is the retry against an older
801
- // supergraph (`EXPLORE_CATALOG_QUERY_WITHOUT_HIGHLIGHTS`) — that gateway does not answer
802
- // the full document at all, it refuses it. Either way
803
- // `catalog.conceptHighlights.filter(...)` on `undefined` would throw inside render,
804
- // blanking the welcome screen over a decorative strip.
805
- conceptHighlights: raw.conceptHighlights?.length ? raw.conceptHighlights : fallback.conceptHighlights
806
- };
807
- }
808
- var CATALOG_DOCUMENT_REJECTED_CODES = /* @__PURE__ */ new Set([
809
- "GRAPHQL_VALIDATION_FAILED",
810
- "HTTP_400"
811
- ]);
812
- function catalogRejectedTheHighlightField(res) {
813
- if (res.data?.exploreCatalog) return false;
814
- return (res.errors ?? []).some((error) => {
815
- const code = error.extensions?.code;
816
- return typeof code === "string" && CATALOG_DOCUMENT_REJECTED_CODES.has(code) || error.message.includes("conceptHighlights");
817
- });
818
- }
819
- var RATE_LIMIT_CODES = /* @__PURE__ */ new Set([
820
- "RATE_LIMITED",
821
- "HTTP_429",
822
- "EXPLORE_GLOBAL_LIMIT"
823
- ]);
824
- var CAPTCHA_CODES = /* @__PURE__ */ new Set(["CAPTCHA_FAILED", "CAPTCHA_REQUIRED"]);
825
- var NETWORK_CODES = /* @__PURE__ */ new Set([
826
- "NETWORK_ERROR",
827
- "UPSTREAM_UNAVAILABLE",
828
- "CONVERSATION_BUSY",
829
- "PROVIDER_ERROR",
830
- "QUEUE_FULL"
831
- ]);
832
- var VALIDATION_CODES = /* @__PURE__ */ new Set([
833
- "MESSAGE_TOO_LONG",
834
- "MESSAGE_EMPTY",
835
- "CONVERSATION_LIMIT",
836
- "INVALID_INPUT"
837
- ]);
838
- function escalateOutcomeForCode(code) {
839
- switch (code) {
840
- case "INVALID_EMAIL":
841
- return "invalid-email";
842
- case "RATE_LIMITED":
843
- case "HTTP_429":
844
- return "rate-limited";
845
- case "CAPTCHA_REQUIRED":
846
- case "CAPTCHA_FAILED":
847
- return "captcha";
848
- // The token owns nothing, or owns a different conversation. The server answers NOT_FOUND
849
- // rather than FORBIDDEN so the endpoint is not an oracle for whether a thread exists;
850
- // either way there is nothing this visitor can do about it, so it reads as a failure.
851
- case "NOT_FOUND":
852
- return "failed";
853
- default:
854
- return "failed";
855
- }
856
- }
857
- function classifyExploreError(code, serverMessage) {
858
- const c = code ?? "UNKNOWN";
859
- if (RATE_LIMIT_CODES.has(c)) {
860
- return {
861
- kind: "rate-limit",
862
- code: c,
863
- message: "You've reached the message limit for now. Please try again later.",
864
- retryable: false
865
- };
866
- }
867
- if (CAPTCHA_CODES.has(c)) {
868
- return {
869
- kind: "captcha",
870
- code: c,
871
- message: "We couldn't verify that you're human. Please try sending that again.",
872
- retryable: true
873
- };
874
- }
875
- if (c === "TOOL_BUDGET") {
876
- return {
877
- kind: "scope",
878
- code: c,
879
- message: "That question spans more of our products than I can look through in one go. Try asking about two or three specific products.",
880
- retryable: false
881
- };
882
- }
883
- if (c === "TIMEOUT") {
884
- return {
885
- kind: "timeout",
886
- code: c,
887
- message: "That answer took too long to come back. Try asking again.",
888
- retryable: true
889
- };
890
- }
891
- if (NETWORK_CODES.has(c)) {
892
- return {
893
- kind: "network",
894
- code: c,
895
- message: "We couldn't reach the assistant just now. Check your connection and try again.",
896
- retryable: true
897
- };
898
- }
899
- if (c === "EXPLORE_DISABLED") {
900
- return {
901
- kind: "disabled",
902
- code: c,
903
- message: "Explore is unavailable at the moment. Please check back soon.",
904
- retryable: false
905
- };
906
- }
907
- if (VALIDATION_CODES.has(c)) {
908
- return {
909
- kind: "validation",
910
- code: c,
911
- message: serverMessage || "That message couldn't be sent.",
912
- retryable: false
913
- };
914
- }
915
- if (c === "EMPTY_ANSWER") {
916
- return {
917
- kind: "unknown",
918
- code: c,
919
- message: "No answer came back for that one. Try rephrasing, or ask something more specific.",
920
- retryable: true
921
- };
922
- }
923
- return {
924
- kind: "unknown",
925
- code: c,
926
- message: serverMessage || "Something went wrong. Please try again.",
927
- retryable: true
928
- };
929
- }
930
- function historyKey(key) {
931
- return `${key}${HISTORY_SUFFIX}`;
932
- }
933
- function readArchive(key) {
934
- if (typeof window === "undefined") return [];
935
- try {
936
- const raw = window.localStorage.getItem(historyKey(key));
937
- if (!raw) return [];
938
- const parsed = JSON.parse(raw);
939
- if (!Array.isArray(parsed)) return [];
940
- return parsed.filter(
941
- (entry) => typeof entry === "object" && entry !== null && typeof entry.token === "string" && Array.isArray(entry.messages)
942
- );
943
- } catch {
944
- return [];
945
- }
946
- }
947
- function writeArchive(key, entries) {
948
- if (typeof window === "undefined") return;
949
- try {
950
- if (entries.length === 0) {
951
- window.localStorage.removeItem(historyKey(key));
952
- return;
953
- }
954
- window.localStorage.setItem(historyKey(key), JSON.stringify(entries));
955
- } catch {
956
- }
957
- }
958
- function upsertArchive(key, thread) {
959
- if (!thread.token) return readArchive(key);
960
- const real = thread.messages.filter(
961
- (m) => m.content.trim() !== "" || m.role === "USER"
962
- );
963
- if (real.length === 0) return readArchive(key);
964
- const firstUser = real.find((m) => m.role === "USER");
965
- const entry = {
966
- token: thread.token,
967
- title: (firstUser?.content ?? "Conversation").trim().slice(0, 80),
968
- updatedAt: real[real.length - 1]?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
969
- messageCount: real.length,
970
- focusProduct: thread.focusProduct,
971
- messages: real.slice(-20)
972
- };
973
- const rest = readArchive(key).filter((e) => e.token !== entry.token);
974
- const next = [entry, ...rest].slice(0, MAX_ARCHIVED_CONVERSATIONS);
975
- writeArchive(key, next);
976
- return next;
977
- }
978
- function readPersisted(key) {
979
- if (typeof window === "undefined") return null;
980
- try {
981
- const raw = window.localStorage.getItem(key);
982
- if (!raw) return null;
983
- const parsed = JSON.parse(raw);
984
- if (!parsed || typeof parsed !== "object") return null;
985
- const record = parsed;
986
- return {
987
- conversationToken: typeof record.conversationToken === "string" ? record.conversationToken : null,
988
- messages: Array.isArray(record.messages) ? record.messages.slice(-MAX_PERSISTED_MESSAGES) : [],
989
- focusProduct: typeof record.focusProduct === "string" ? record.focusProduct : null
990
- };
991
- } catch {
992
- return null;
993
- }
994
- }
995
- function readShareToken() {
996
- if (typeof window === "undefined") return null;
997
- try {
998
- return new URL(window.location.href).searchParams.get("c");
999
- } catch {
1000
- return null;
1001
- }
1002
- }
1003
- function visibleText(message) {
1004
- return message.content || message.partialContent || "";
1005
- }
1006
- function countUserTurns(messages) {
1007
- return messages.filter((m) => m.role === "USER").length;
1008
- }
1009
- function useExploreChat(options = {}) {
1010
- const {
1011
- productSlug,
1012
- pageUrl,
1013
- locale,
1014
- examplePrompts,
1015
- fallbackWelcome,
1016
- pollIntervalMs = DEFAULT_POLL_INTERVAL_MS,
1017
- pollTimeoutMs = DEFAULT_POLL_TIMEOUT_MS,
1018
- storageKey = DEFAULT_STORAGE_KEY,
1019
- persist = true,
1020
- onSend,
1021
- enabled = true,
1022
- shareToken: shareTokenOption
1023
- } = options;
1024
- const client = useWebSDK();
1025
- const { productId } = useWebSDKConfig();
1026
- const promptKey = JSON.stringify(examplePrompts ?? []);
1027
- const welcomeKey = JSON.stringify(fallbackWelcome ?? null);
1028
- const fallbackCatalog = useMemo(
1029
- () => buildFallbackCatalog(
1030
- JSON.parse(promptKey),
1031
- JSON.parse(welcomeKey) ?? void 0
1032
- ),
1033
- [promptKey, welcomeKey]
1034
- );
1035
- const [bakedRaw] = useState(
1036
- () => readBakedCatalog(productSlug)
1037
- );
1038
- const [catalog, setCatalog] = useState(
1039
- () => bakedRaw ? normalizeCatalog(bakedRaw, fallbackCatalog) : fallbackCatalog
1040
- );
1041
- const [serverCatalogRaw, setServerCatalogRaw] = useState(bakedRaw);
1042
- const [messages, setMessages] = useState([]);
1043
- const [phase, setPhase] = useState(
1044
- () => bakedRaw ? bakedRaw.enabled === false ? "disabled" : "ready" : "loading"
1045
- );
1046
- const [error, setError] = useState(null);
1047
- const [remainingToday, setRemainingToday] = useState(null);
1048
- const [focusProduct, setFocusProductState] = useState(null);
1049
- const [turnCount, setTurnCount] = useState(0);
1050
- const messagesRef = useRef([]);
1051
- const [archive, setArchive] = useState([]);
1052
- const [hydrated, setHydrated] = useState(false);
1053
- const mountedRef = useRef(true);
1054
- const pollGenerationRef = useRef(0);
1055
- const pollTimerRef = useRef(null);
1056
- const conversationTokenRef = useRef(null);
1057
- const [hasConversation, setHasConversation] = useState(false);
1058
- const shareTokenRef = useRef(void 0);
1059
- if (shareTokenRef.current === void 0) {
1060
- shareTokenRef.current = shareTokenOption === void 0 ? readShareToken() : shareTokenOption;
1061
- }
1062
- const isSharedView = shareTokenRef.current !== null;
1063
- const catalogRef = useRef(catalog);
1064
- const turnCountRef = useRef(0);
1065
- const focusProductRef = useRef(null);
1066
- const lastSentTextRef = useRef(null);
1067
- const lastSentAttachmentsRef = useRef(
1068
- []
1069
- );
1070
- const inFlightRef = useRef(false);
1071
- catalogRef.current = catalog;
1072
- const rememberConversationToken = useCallback((token) => {
1073
- conversationTokenRef.current = token;
1074
- setHasConversation(token !== null);
1075
- }, []);
1076
- const clearPollTimer = useCallback(() => {
1077
- if (pollTimerRef.current !== null) {
1078
- clearTimeout(pollTimerRef.current);
1079
- pollTimerRef.current = null;
1080
- }
1081
- }, []);
1082
- const cancelPolling = useCallback(() => {
1083
- pollGenerationRef.current += 1;
1084
- clearPollTimer();
1085
- }, [clearPollTimer]);
1086
- useEffect(() => {
1087
- mountedRef.current = true;
1088
- return () => {
1089
- mountedRef.current = false;
1090
- pollGenerationRef.current += 1;
1091
- if (pollTimerRef.current !== null) {
1092
- clearTimeout(pollTimerRef.current);
1093
- pollTimerRef.current = null;
1094
- }
1095
- };
1096
- }, []);
1097
- useEffect(() => {
1098
- if (!enabled) return;
1099
- const shareToken = shareTokenRef.current;
1100
- if (!shareToken) return;
1101
- let cancelled = false;
1102
- setHydrated(true);
1103
- void client.query(
1104
- EXPLORE_SHARED_CONVERSATION_QUERY,
1105
- { shareToken },
1106
- { cache: false }
1107
- ).then((res) => {
1108
- if (cancelled || !mountedRef.current) return;
1109
- const shared = res?.data?.exploreSharedConversation;
1110
- if (shared && shared.length > 0) {
1111
- setMessages(shared);
1112
- return;
1113
- }
1114
- setError({
1115
- kind: "unknown",
1116
- code: "SHARE_NOT_FOUND",
1117
- message: "That shared conversation could not be found. The link may have expired.",
1118
- // Nothing to retry: a bad token will stay bad.
1119
- retryable: false
1120
- });
1121
- }).catch(() => {
1122
- if (cancelled || !mountedRef.current) return;
1123
- setError({
1124
- kind: "unknown",
1125
- code: "SHARE_NOT_FOUND",
1126
- message: "That shared conversation could not be loaded.",
1127
- retryable: true
1128
- });
1129
- });
1130
- return () => {
1131
- cancelled = true;
1132
- };
1133
- }, [client, enabled]);
1134
- useEffect(() => {
1135
- if (!enabled) return;
1136
- if (shareTokenRef.current !== null) return;
1137
- if (!persist) {
1138
- setHydrated(true);
1139
- return;
1140
- }
1141
- setArchive(readArchive(storageKey));
1142
- const stored = readPersisted(storageKey);
1143
- if (stored) {
1144
- rememberConversationToken(stored.conversationToken);
1145
- focusProductRef.current = stored.focusProduct;
1146
- const settled = stored.messages.flatMap((m) => {
1147
- if (m.role !== "ASSISTANT") return [m];
1148
- if (m.status !== "PENDING" && m.status !== "RUNNING") return [m];
1149
- const text = visibleText(m);
1150
- if (!text) return [];
1151
- return [{ ...m, status: "COMPLETED", content: text }];
1152
- });
1153
- setMessages(settled);
1154
- setFocusProductState(stored.focusProduct);
1155
- const turns = countUserTurns(settled);
1156
- turnCountRef.current = turns;
1157
- setTurnCount(turns);
1158
- }
1159
- setHydrated(true);
1160
- }, [persist, rememberConversationToken, storageKey, enabled]);
1161
- useEffect(() => {
1162
- if (!persist || !hydrated || isSharedView || typeof window === "undefined")
1163
- return;
1164
- try {
1165
- const payload = {
1166
- conversationToken: conversationTokenRef.current,
1167
- messages: messages.slice(-MAX_PERSISTED_MESSAGES),
1168
- focusProduct
1169
- };
1170
- if (!payload.conversationToken && payload.messages.length === 0 && !payload.focusProduct) {
1171
- window.localStorage.removeItem(storageKey);
1172
- return;
1173
- }
1174
- window.localStorage.setItem(storageKey, JSON.stringify(payload));
1175
- } catch {
1176
- }
1177
- }, [persist, hydrated, isSharedView, storageKey, messages, focusProduct]);
1178
- useEffect(() => {
1179
- messagesRef.current = messages;
1180
- if (!persist || !hydrated || isSharedView) return;
1181
- const settled = messages.some(
1182
- (m) => m.role === "ASSISTANT" && (m.status === "COMPLETED" || m.status === "FAILED")
1183
- );
1184
- if (!settled) return;
1185
- setArchive(
1186
- upsertArchive(storageKey, {
1187
- token: conversationTokenRef.current,
1188
- messages,
1189
- focusProduct: focusProductRef.current
1190
- })
1191
- );
1192
- }, [messages, persist, hydrated, isSharedView, storageKey]);
1193
- useEffect(() => {
1194
- if (!enabled) return;
1195
- let cancelled = false;
1196
- const load = async () => {
1197
- const variables = { productSlug: productSlug ?? null };
1198
- let res = await client.query(
1199
- EXPLORE_CATALOG_QUERY,
1200
- variables
1201
- );
1202
- if (cancelled || !mountedRef.current) return;
1203
- if (catalogRejectedTheHighlightField(res)) {
1204
- res = await client.query(
1205
- EXPLORE_CATALOG_QUERY_WITHOUT_HIGHLIGHTS,
1206
- variables
1207
- );
1208
- if (cancelled || !mountedRef.current) return;
1209
- }
1210
- const raw = res.data?.exploreCatalog;
1211
- if (res.errors?.length || !raw) {
1212
- console.warn(
1213
- "[WebSDK] exploreCatalog unavailable \u2014 keeping the catalog the page started with",
1214
- res.errors?.[0]?.message
1215
- );
1216
- setPhase((prev) => prev === "loading" ? "ready" : prev);
1217
- return;
1218
- }
1219
- const next = normalizeCatalog(
1220
- raw,
1221
- bakedRaw ? normalizeCatalog(bakedRaw, fallbackCatalog) : fallbackCatalog
1222
- );
1223
- setCatalog(next);
1224
- setServerCatalogRaw(raw);
1225
- catalogRef.current = next;
1226
- setPhase((prev) => {
1227
- if (!next.enabled) return "disabled";
1228
- return prev === "loading" || prev === "disabled" ? "ready" : prev;
1229
- });
1230
- };
1231
- void load();
1232
- return () => {
1233
- cancelled = true;
1234
- };
1235
- }, [client, productSlug, fallbackCatalog, bakedRaw, enabled]);
1236
- const startPolling = useCallback(
1237
- (conversationToken, messageId) => {
1238
- pollGenerationRef.current += 1;
1239
- const generation = pollGenerationRef.current;
1240
- const startedAt = Date.now();
1241
- let consecutiveFailures = 0;
1242
- const isStale = () => !mountedRef.current || generation !== pollGenerationRef.current;
1243
- const finishWithError = (chatError) => {
1244
- inFlightRef.current = false;
1245
- setMessages(
1246
- (prev) => prev.flatMap((m) => {
1247
- if (m.id !== messageId) return [m];
1248
- const text = visibleText(m);
1249
- if (!text) return [];
1250
- return [{ ...m, status: "FAILED", content: text }];
1251
- })
1252
- );
1253
- setError(chatError);
1254
- setPhase(chatError.kind === "rate-limit" ? "limited" : "error");
1255
- };
1256
- const tick = async () => {
1257
- if (isStale()) return;
1258
- if (Date.now() - startedAt > pollTimeoutMs) {
1259
- finishWithError(classifyExploreError("TIMEOUT"));
1260
- return;
1261
- }
1262
- const res = await client.query(
1263
- EXPLORE_MESSAGE_QUERY,
1264
- { conversationToken, id: messageId },
1265
- { cache: false, timeoutMs: POLL_REQUEST_TIMEOUT_MS }
1266
- );
1267
- if (isStale()) return;
1268
- const first = res.errors?.[0];
1269
- if (first) {
1270
- const code = typeof first.extensions?.code === "string" ? first.extensions.code : void 0;
1271
- const classified = classifyExploreError(code, first.message);
1272
- if (!classified.retryable) {
1273
- finishWithError(classified);
1274
- return;
1275
- }
1276
- consecutiveFailures += 1;
1277
- if (consecutiveFailures >= MAX_CONSECUTIVE_POLL_FAILURES) {
1278
- finishWithError(classified);
1279
- return;
1280
- }
1281
- pollTimerRef.current = setTimeout(() => void tick(), pollIntervalMs);
1282
- return;
1283
- }
1284
- const message = res.data?.exploreMessage;
1285
- if (!message) {
1286
- consecutiveFailures += 1;
1287
- if (consecutiveFailures >= MAX_CONSECUTIVE_POLL_FAILURES) {
1288
- finishWithError(classifyExploreError("NOT_FOUND"));
1289
- return;
1290
- }
1291
- pollTimerRef.current = setTimeout(() => void tick(), pollIntervalMs);
1292
- return;
1293
- }
1294
- consecutiveFailures = 0;
1295
- setMessages(
1296
- (prev) => prev.map((m) => m.id === messageId ? message : m)
1297
- );
1298
- if (message.status === "COMPLETED") {
1299
- inFlightRef.current = false;
1300
- setError(null);
1301
- setPhase("ready");
1302
- return;
1303
- }
1304
- if (message.status === "FAILED") {
1305
- finishWithError(
1306
- classifyExploreError(message.errorCode ?? "UPSTREAM_UNAVAILABLE")
1307
- );
1308
- return;
1309
- }
1310
- setPhase("streaming");
1311
- pollTimerRef.current = setTimeout(() => void tick(), pollIntervalMs);
1312
- };
1313
- pollTimerRef.current = setTimeout(() => void tick(), pollIntervalMs);
1314
- },
1315
- [client, pollIntervalMs, pollTimeoutMs]
1316
- );
1317
- const submit = useCallback(
1318
- async (text, optimisticId, captchaAttempt, attachments) => {
1319
- const activeCatalog = catalogRef.current;
1320
- let recaptchaToken;
1321
- if (activeCatalog.captchaRequired && activeCatalog.recaptchaSiteKey) {
1322
- try {
1323
- recaptchaToken = await getRecaptchaV3Token(
1324
- activeCatalog.recaptchaSiteKey
1325
- );
1326
- } catch (err) {
1327
- console.warn("[WebSDK] reCAPTCHA v3 token could not be minted", err);
1328
- }
1329
- }
1330
- const input = {
1331
- message: text,
1332
- ...conversationTokenRef.current ? { conversationToken: conversationTokenRef.current } : {},
1333
- ...focusProductRef.current || productSlug ? { productSlug: focusProductRef.current ?? productSlug } : {},
1334
- ...recaptchaToken ? { recaptchaToken } : {},
1335
- ...locale ? { locale } : {},
1336
- ...pageUrl ? { pageUrl } : {},
1337
- ...attachments.length > 0 ? { attachments: [...attachments] } : {}
1338
- };
1339
- const res = await client.mutate(
1340
- SEND_EXPLORE_MESSAGE_MUTATION,
1341
- { input },
1342
- { timeoutMs: SEND_REQUEST_TIMEOUT_MS }
1343
- );
1344
- if (!mountedRef.current) return;
1345
- const first = res.errors?.[0];
1346
- const result = res.data?.sendExploreMessage;
1347
- if (first || !result) {
1348
- const code = typeof first?.extensions?.code === "string" ? first.extensions.code : void 0;
1349
- const classified = classifyExploreError(code, first?.message);
1350
- if (classified.kind === "captcha" && captchaAttempt === 0) {
1351
- await submit(text, optimisticId, 1, attachments);
1352
- return;
1353
- }
1354
- inFlightRef.current = false;
1355
- setError(classified);
1356
- setPhase(classified.kind === "rate-limit" ? "limited" : "error");
1357
- return;
1358
- }
1359
- rememberConversationToken(result.conversation.token);
1360
- turnCountRef.current = result.conversation.turnCount;
1361
- setTurnCount(result.conversation.turnCount);
1362
- setRemainingToday(result.remainingToday ?? null);
1363
- const userMessage = result.userMessage;
1364
- const assistantMessage = result.assistantMessage;
1365
- setMessages((prev) => {
1366
- const replaced = prev.some((m) => m.id === optimisticId) ? prev.map((m) => m.id === optimisticId ? userMessage : m) : [...prev, userMessage];
1367
- return [...replaced, assistantMessage];
1368
- });
1369
- if (assistantMessage.status === "COMPLETED" || assistantMessage.status === "FAILED") {
1370
- inFlightRef.current = false;
1371
- if (assistantMessage.status === "FAILED") {
1372
- const classified = classifyExploreError(
1373
- assistantMessage.errorCode ?? "UPSTREAM_UNAVAILABLE"
1374
- );
1375
- setError(classified);
1376
- setPhase("error");
1377
- } else {
1378
- setPhase("ready");
1379
- }
1380
- return;
1381
- }
1382
- setPhase("streaming");
1383
- startPolling(result.conversation.token, assistantMessage.id);
1384
- },
1385
- [
1386
- client,
1387
- locale,
1388
- pageUrl,
1389
- productSlug,
1390
- rememberConversationToken,
1391
- startPolling
1392
- ]
1393
- );
1394
- const send = useCallback(
1395
- async (message, attachments = []) => {
1396
- const text = message.trim();
1397
- if (!text) return;
1398
- if (inFlightRef.current) return;
1399
- const activeCatalog = catalogRef.current;
1400
- if (!activeCatalog.enabled) {
1401
- setError(classifyExploreError("EXPLORE_DISABLED"));
1402
- setPhase("disabled");
1403
- return;
1404
- }
1405
- if (text.length > activeCatalog.limits.maxMessageLength) {
1406
- setError({
1407
- kind: "validation",
1408
- code: "MESSAGE_TOO_LONG",
1409
- message: `That message is ${text.length} characters \u2014 the limit is ${activeCatalog.limits.maxMessageLength}.`,
1410
- retryable: false
1411
- });
1412
- return;
1413
- }
1414
- if (turnCountRef.current >= activeCatalog.limits.maxTurnsPerConversation) {
1415
- setError({
1416
- kind: "validation",
1417
- code: "CONVERSATION_LIMIT",
1418
- message: `This conversation has reached its ${activeCatalog.limits.maxTurnsPerConversation}-message limit. Start a new chat to keep going.`,
1419
- retryable: false
1420
- });
1421
- return;
1422
- }
1423
- inFlightRef.current = true;
1424
- lastSentTextRef.current = text;
1425
- lastSentAttachmentsRef.current = attachments;
1426
- setError(null);
1427
- setPhase("sending");
1428
- cancelPolling();
1429
- const optimistic = {
1430
- id: makeOptimisticId(),
1431
- conversationId: conversationTokenRef.current ?? "pending",
1432
- role: "USER",
1433
- status: "COMPLETED",
1434
- content: text,
1435
- partialContent: null,
1436
- activity: [],
1437
- references: [],
1438
- ctas: [],
1439
- errorCode: null,
1440
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1441
- completedAt: (/* @__PURE__ */ new Date()).toISOString()
1442
- };
1443
- setMessages((prev) => [...prev, optimistic]);
1444
- turnCountRef.current += 1;
1445
- setTurnCount(turnCountRef.current);
1446
- onSend?.(text);
1447
- try {
1448
- await submit(text, optimistic.id, 0, attachments);
1449
- } catch (err) {
1450
- if (!mountedRef.current) return;
1451
- console.error("[WebSDK] Explore send failed", err);
1452
- inFlightRef.current = false;
1453
- setError(classifyExploreError("NETWORK_ERROR"));
1454
- setPhase("error");
1455
- }
1456
- },
1457
- [cancelPolling, onSend, submit]
1458
- );
1459
- const stop = useCallback(() => {
1460
- cancelPolling();
1461
- inFlightRef.current = false;
1462
- setMessages(
1463
- (prev) => prev.flatMap((m) => {
1464
- if (m.role !== "ASSISTANT") return [m];
1465
- if (m.status !== "PENDING" && m.status !== "RUNNING") return [m];
1466
- const text = visibleText(m);
1467
- if (!text) return [];
1468
- return [
1469
- {
1470
- ...m,
1471
- status: "COMPLETED",
1472
- content: text,
1473
- completedAt: (/* @__PURE__ */ new Date()).toISOString()
1474
- }
1475
- ];
1476
- })
1477
- );
1478
- setPhase(
1479
- (prev) => prev === "sending" || prev === "streaming" ? "ready" : prev
1480
- );
1481
- }, [cancelPolling]);
1482
- const retry = useCallback(() => {
1483
- const text = lastSentTextRef.current;
1484
- if (!text) return;
1485
- cancelPolling();
1486
- inFlightRef.current = false;
1487
- setMessages((prev) => {
1488
- const next = [...prev];
1489
- const last = next[next.length - 1];
1490
- if (last?.role === "ASSISTANT" && last.status === "FAILED") next.pop();
1491
- const prior = next[next.length - 1];
1492
- if (prior?.role === "USER" && prior.content === text) next.pop();
1493
- return next;
1494
- });
1495
- turnCountRef.current = Math.max(0, turnCountRef.current - 1);
1496
- setTurnCount(turnCountRef.current);
1497
- void send(text, lastSentAttachmentsRef.current);
1498
- }, [cancelPolling, send]);
1499
- const reset = useCallback(() => {
1500
- setArchive(
1501
- upsertArchive(storageKey, {
1502
- token: conversationTokenRef.current,
1503
- messages: messagesRef.current,
1504
- focusProduct: focusProductRef.current
1505
- })
1506
- );
1507
- cancelPolling();
1508
- inFlightRef.current = false;
1509
- rememberConversationToken(null);
1510
- lastSentTextRef.current = null;
1511
- lastSentAttachmentsRef.current = [];
1512
- turnCountRef.current = 0;
1513
- setTurnCount(0);
1514
- setMessages([]);
1515
- setError(null);
1516
- setRemainingToday(null);
1517
- setPhase(catalogRef.current.enabled ? "ready" : "disabled");
1518
- if (typeof window !== "undefined") {
1519
- try {
1520
- window.localStorage.removeItem(storageKey);
1521
- } catch {
1522
- }
1523
- }
1524
- }, [cancelPolling, rememberConversationToken, storageKey]);
1525
- const openConversation = useCallback(
1526
- (token) => {
1527
- const entry = readArchive(storageKey).find((e) => e.token === token);
1528
- if (!entry) return;
1529
- upsertArchive(storageKey, {
1530
- token: conversationTokenRef.current,
1531
- messages: messagesRef.current,
1532
- focusProduct: focusProductRef.current
1533
- });
1534
- cancelPolling();
1535
- inFlightRef.current = false;
1536
- rememberConversationToken(entry.token);
1537
- turnCountRef.current = entry.messages.filter(
1538
- (m) => m.role === "USER"
1539
- ).length;
1540
- setTurnCount(turnCountRef.current);
1541
- setMessages(entry.messages);
1542
- focusProductRef.current = entry.focusProduct;
1543
- setFocusProductState(entry.focusProduct);
1544
- setError(null);
1545
- setPhase(catalogRef.current.enabled ? "ready" : "disabled");
1546
- setArchive(readArchive(storageKey));
1547
- },
1548
- [cancelPolling, rememberConversationToken, storageKey]
1549
- );
1550
- const deleteConversation = useCallback(
1551
- (token) => {
1552
- const next = readArchive(storageKey).filter((e) => e.token !== token);
1553
- writeArchive(storageKey, next);
1554
- setArchive(next);
1555
- },
1556
- [storageKey]
1557
- );
1558
- const clearHistory = useCallback(() => {
1559
- writeArchive(storageKey, []);
1560
- setArchive([]);
1561
- }, [storageKey]);
1562
- const setFocusProduct = useCallback((slug) => {
1563
- focusProductRef.current = slug;
1564
- setFocusProductState(slug);
1565
- }, []);
1566
- const activity = useMemo(() => {
1567
- for (let i = messages.length - 1; i >= 0; i -= 1) {
1568
- const m = messages[i];
1569
- if (!m || m.role !== "ASSISTANT") continue;
1570
- if (m.status !== "PENDING" && m.status !== "RUNNING") return null;
1571
- const lines = m.activity ?? [];
1572
- return lines.length ? lines[lines.length - 1] ?? null : null;
1573
- }
1574
- return null;
1575
- }, [messages]);
1576
- const canSend = (phase === "ready" || phase === "error") && catalog.enabled && turnCount < catalog.limits.maxTurnsPerConversation;
1577
- const createShareLink = useCallback(async () => {
1578
- const token = conversationTokenRef.current;
1579
- if (!token) return null;
1580
- try {
1581
- const result = await client.mutate(CREATE_EXPLORE_SHARE_LINK_MUTATION, { conversationToken: token });
1582
- return result?.data?.createExploreShareLink?.shareToken ?? null;
1583
- } catch {
1584
- return null;
1585
- }
1586
- }, [client]);
1587
- const recordClick = useCallback(
1588
- (messageId, kind, url) => {
1589
- const token = conversationTokenRef.current;
1590
- if (!token) return;
1591
- try {
1592
- void client.mutate(RECORD_EXPLORE_CLICK_MUTATION, {
1593
- input: { conversationToken: token, messageId, kind, url }
1594
- }).catch(() => {
1595
- });
1596
- } catch {
1597
- }
1598
- },
1599
- [client]
1600
- );
1601
- const submitFeedback = useCallback(
1602
- async (messageId, rating, detail) => {
1603
- const token = conversationTokenRef.current;
1604
- if (!token) return false;
1605
- const comment = detail?.comment?.trim();
1606
- const input = {
1607
- conversationToken: token,
1608
- messageId,
1609
- rating,
1610
- // Only meaningful with NOT_HELPFUL. The server stores null for HELPFUL either
1611
- // way; sending it would just be noise the backend has to defend against.
1612
- reason: rating === "NOT_HELPFUL" ? detail?.reason ?? null : null,
1613
- comment: comment ? comment : null
1614
- };
1615
- try {
1616
- const res = await client.mutate(
1617
- SUBMIT_EXPLORE_FEEDBACK_MUTATION,
1618
- { input }
1619
- );
1620
- const result = res?.data?.submitExploreFeedback;
1621
- if (!result?.recorded) return false;
1622
- const recorded = result.feedback;
1623
- if (recorded && mountedRef.current) {
1624
- setMessages(
1625
- (current) => current.map(
1626
- (message) => message.id === messageId ? { ...message, feedback: recorded } : message
1627
- )
1628
- );
1629
- }
1630
- return true;
1631
- } catch {
1632
- return false;
1633
- }
1634
- },
1635
- [client]
1636
- );
1637
- const escalate = useCallback(
1638
- async (email, note) => {
1639
- const token = conversationTokenRef.current;
1640
- if (!token) {
1641
- return { outcome: "no-conversation", email: null, createdAt: null };
1642
- }
1643
- const attempt = async (captchaAttempt) => {
1644
- const activeCatalog = catalogRef.current;
1645
- let recaptchaToken;
1646
- if (activeCatalog.captchaRequired && activeCatalog.recaptchaSiteKey) {
1647
- try {
1648
- recaptchaToken = await getRecaptchaV3Token(
1649
- activeCatalog.recaptchaSiteKey
1650
- );
1651
- } catch (err) {
1652
- console.warn(
1653
- "[WebSDK] reCAPTCHA v3 token could not be minted",
1654
- err
1655
- );
1656
- }
1657
- }
1658
- const input = {
1659
- conversationToken: token,
1660
- email: email.trim(),
1661
- note: note?.trim() ? note.trim() : null,
1662
- ...recaptchaToken ? { recaptchaToken } : {},
1663
- ...productId ? { productId } : {}
1664
- };
1665
- try {
1666
- const res = await client.mutate(
1667
- ESCALATE_EXPLORE_CONVERSATION_MUTATION,
1668
- { input }
1669
- );
1670
- const first = res?.errors?.[0];
1671
- const result = res?.data?.escalateExploreConversation;
1672
- if (first || !result) {
1673
- const code = typeof first?.extensions?.code === "string" ? first.extensions.code : "ESCALATION_FAILED";
1674
- if (code === "CAPTCHA_FAILED" && captchaAttempt === 0) {
1675
- return attempt(1);
1676
- }
1677
- return {
1678
- outcome: escalateOutcomeForCode(code),
1679
- email: null,
1680
- createdAt: null
1681
- };
1682
- }
1683
- return {
1684
- // `created: false` is the double-click, the retry, the reload. The handover
1685
- // exists, so this is a success — and the address comes from the SERVER, because
1686
- // on a repeat submit the reply goes to whatever the FIRST handover used.
1687
- outcome: result.created ? "sent" : "already-handed-over",
1688
- email: result.escalation?.email ?? null,
1689
- createdAt: result.escalation?.createdAt ?? null
1690
- };
1691
- } catch {
1692
- return { outcome: "failed", email: null, createdAt: null };
1693
- }
1694
- };
1695
- return attempt(0);
1696
- },
1697
- [client, productId]
1698
- );
1699
- const canEscalate = hasConversation && !isSharedView;
1700
- const getConversationToken = useCallback(
1701
- () => conversationTokenRef.current,
1702
- []
1703
- );
1704
- return {
1705
- phase,
1706
- catalog,
1707
- serverCatalogRaw,
1708
- messages,
1709
- activity,
1710
- remainingToday,
1711
- error,
1712
- focusProduct,
1713
- setFocusProduct,
1714
- send,
1715
- stop,
1716
- retry,
1717
- reset,
1718
- canSend,
1719
- history: archive,
1720
- openConversation,
1721
- deleteConversation,
1722
- clearHistory,
1723
- recordClick,
1724
- submitFeedback,
1725
- escalate,
1726
- canEscalate,
1727
- createShareLink,
1728
- isSharedView,
1729
- getConversationToken
1730
- };
1731
- }
1732
- var optimisticCounter = 0;
1733
- function makeOptimisticId() {
1734
- optimisticCounter += 1;
1735
- return `boff-explore-local-${Date.now()}-${optimisticCounter}`;
1736
- }
1737
- function getRecognitionCtor() {
1738
- if (typeof window === "undefined") return null;
1739
- const w = window;
1740
- return w.SpeechRecognition ?? w.webkitSpeechRecognition ?? null;
1741
- }
1742
- function isTouchDevice() {
1743
- if (typeof window === "undefined" || !window.matchMedia) return false;
1744
- try {
1745
- return window.matchMedia("(pointer: coarse)").matches;
1746
- } catch {
1747
- return false;
1748
- }
1749
- }
1750
- var MIC_DENIED_MESSAGE = "Microphone access was blocked. Allow it in your browser's site settings to dictate.";
1751
- var MIC_UNAVAILABLE_MESSAGE = "Dictation isn't available in this browser. You can type instead.";
1752
- var RELEASE_SETTLE_MS = 250;
1753
- var RETRY_DELAY_MS = 350;
1754
- var sleep = (ms) => new Promise((resolve) => {
1755
- setTimeout(resolve, ms);
1756
- });
1757
- async function ensureMicrophoneAccess() {
1758
- const media = typeof navigator === "undefined" ? void 0 : navigator.mediaDevices;
1759
- if (!media?.getUserMedia)
1760
- return { ok: true, confirmed: false, primed: false };
1761
- try {
1762
- const status = await navigator.permissions?.query({
1763
- name: "microphone"
1764
- });
1765
- if (status?.state === "granted")
1766
- return { ok: true, confirmed: true, primed: false };
1767
- } catch {
1768
- }
1769
- try {
1770
- const stream = await media.getUserMedia({ audio: true });
1771
- for (const track of stream.getTracks()) track.stop();
1772
- return { ok: true, confirmed: true, primed: true };
1773
- } catch (error) {
1774
- const name = typeof error === "object" && error !== null && "name" in error ? String(error.name) : "";
1775
- if (name === "NotAllowedError" || name === "SecurityError") {
1776
- return { ok: false, message: MIC_DENIED_MESSAGE };
1777
- }
1778
- if (name === "NotFoundError" || name === "DevicesNotFoundError") {
1779
- return { ok: false, message: "No microphone was found." };
1780
- }
1781
- return {
1782
- ok: false,
1783
- message: "Dictation could not start. You can type instead."
1784
- };
1785
- }
1786
- }
1787
- function describeError(code) {
1788
- switch (code) {
1789
- case "not-allowed":
1790
- case "service-not-allowed":
1791
- return MIC_DENIED_MESSAGE;
1792
- case "no-speech":
1793
- return "I didn't catch anything \u2014 try again a little closer to the mic.";
1794
- case "audio-capture":
1795
- return "No microphone was found.";
1796
- case "network":
1797
- return "Speech recognition needs a network connection.";
1798
- case "aborted":
1799
- return "";
1800
- default:
1801
- return "Dictation stopped unexpectedly. You can type instead.";
1802
- }
1803
- }
1804
- function useSpeechInput({
1805
- onFinalTranscript,
1806
- lang,
1807
- onError
1808
- }) {
1809
- const [supported] = useState(() => getRecognitionCtor() !== null);
1810
- const [listening, setListening] = useState(false);
1811
- const [interim, setInterim] = useState("");
1812
- const [error, setError] = useState(null);
1813
- const recognitionRef = useRef(null);
1814
- const startTokenRef = useRef(0);
1815
- const micConfirmedRef = useRef(false);
1816
- const wantsListeningRef = useRef(false);
1817
- const retriedRef = useRef(false);
1818
- const finalRef = useRef(onFinalTranscript);
1819
- const errorRef = useRef(onError);
1820
- finalRef.current = onFinalTranscript;
1821
- errorRef.current = onError;
1822
- const langRef = useRef(lang);
1823
- langRef.current = lang;
1824
- const stop = useCallback(() => {
1825
- startTokenRef.current += 1;
1826
- wantsListeningRef.current = false;
1827
- setListening(false);
1828
- setInterim("");
1829
- const recognition = recognitionRef.current;
1830
- if (!recognition) return;
1831
- try {
1832
- recognition.stop();
1833
- } catch {
1834
- }
1835
- }, []);
1836
- const openSession = useCallback((token) => {
1837
- const Ctor = getRecognitionCtor();
1838
- if (!Ctor || token !== startTokenRef.current) return;
1839
- const recognition = new Ctor();
1840
- recognition.lang = langRef.current ?? (typeof navigator === "undefined" ? "en-US" : navigator.language || "en-US");
1841
- recognition.continuous = !isTouchDevice();
1842
- recognition.interimResults = true;
1843
- recognition.maxAlternatives = 1;
1844
- recognition.onstart = () => {
1845
- if (token !== startTokenRef.current) return;
1846
- setError(null);
1847
- setListening(true);
1848
- };
1849
- recognition.onresult = (event) => {
1850
- if (token !== startTokenRef.current) return;
1851
- let settled = "";
1852
- let pending = "";
1853
- for (let i = event.resultIndex; i < event.results.length; i += 1) {
1854
- const result = event.results[i];
1855
- if (!result) continue;
1856
- const text = result[0]?.transcript ?? "";
1857
- if (result.isFinal) settled += text;
1858
- else pending += text;
1859
- }
1860
- setInterim(pending);
1861
- if (settled.trim() !== "") finalRef.current(settled);
1862
- };
1863
- recognition.onerror = (event) => {
1864
- if (token !== startTokenRef.current) return;
1865
- if ((event.error === "not-allowed" || event.error === "service-not-allowed") && micConfirmedRef.current && !retriedRef.current) {
1866
- retriedRef.current = true;
1867
- void sleep(RETRY_DELAY_MS).then(() => {
1868
- if (token !== startTokenRef.current || !wantsListeningRef.current)
1869
- return;
1870
- openSessionRef.current?.(token);
1871
- });
1872
- return;
1873
- }
1874
- const message = micConfirmedRef.current && (event.error === "not-allowed" || event.error === "service-not-allowed") ? MIC_UNAVAILABLE_MESSAGE : describeError(event.error);
1875
- wantsListeningRef.current = false;
1876
- setListening(false);
1877
- setInterim("");
1878
- if (message !== "") {
1879
- setError(message);
1880
- errorRef.current?.(message);
1881
- }
1882
- };
1883
- recognition.onend = () => {
1884
- if (token !== startTokenRef.current) return;
1885
- setInterim("");
1886
- if (wantsListeningRef.current && isTouchDevice()) {
1887
- void sleep(120).then(() => {
1888
- if (token !== startTokenRef.current || !wantsListeningRef.current)
1889
- return;
1890
- openSessionRef.current?.(token);
1891
- });
1892
- return;
1893
- }
1894
- setListening(false);
1895
- };
1896
- recognitionRef.current = recognition;
1897
- try {
1898
- recognition.start();
1899
- } catch {
1900
- wantsListeningRef.current = false;
1901
- setListening(false);
1902
- }
1903
- }, []);
1904
- const openSessionRef = useRef(null);
1905
- openSessionRef.current = openSession;
1906
- const start = useCallback(() => {
1907
- if (!getRecognitionCtor()) return;
1908
- startTokenRef.current += 1;
1909
- const token = startTokenRef.current;
1910
- wantsListeningRef.current = true;
1911
- retriedRef.current = false;
1912
- micConfirmedRef.current = false;
1913
- setError(null);
1914
- setListening(true);
1915
- void ensureMicrophoneAccess().then(async (access) => {
1916
- if (token !== startTokenRef.current) return;
1917
- if (!access.ok) {
1918
- wantsListeningRef.current = false;
1919
- setListening(false);
1920
- setError(access.message);
1921
- errorRef.current?.(access.message);
1922
- return;
1923
- }
1924
- micConfirmedRef.current = access.confirmed;
1925
- if (access.primed) {
1926
- await sleep(RELEASE_SETTLE_MS);
1927
- if (token !== startTokenRef.current) return;
1928
- }
1929
- openSessionRef.current?.(token);
1930
- });
1931
- }, []);
1932
- const toggle = useCallback(() => {
1933
- if (listening) stop();
1934
- else start();
1935
- }, [listening, start, stop]);
1936
- useEffect(
1937
- () => () => {
1938
- startTokenRef.current += 1;
1939
- wantsListeningRef.current = false;
1940
- const recognition = recognitionRef.current;
1941
- if (!recognition) return;
1942
- recognition.onresult = null;
1943
- recognition.onerror = null;
1944
- recognition.onend = null;
1945
- recognition.onstart = null;
1946
- try {
1947
- recognition.abort();
1948
- } catch {
1949
- }
1950
- },
1951
- []
1952
- );
1953
- return { supported, listening, interim, error, start, stop, toggle };
1954
- }
1955
- var SILENT_FAILURE_MS = 1500;
1956
- function speechPlatform() {
1957
- if (typeof window === "undefined") return null;
1958
- const scope = window;
1959
- const synth = scope.speechSynthesis;
1960
- const Utterance = scope.SpeechSynthesisUtterance;
1961
- if (!synth || typeof synth.speak !== "function") return null;
1962
- if (typeof Utterance !== "function") return null;
1963
- return { synth, Utterance };
1964
- }
1965
- function normaliseTag(tag) {
1966
- return tag.trim().toLowerCase().replace(/_/g, "-");
1967
- }
1968
- function primaryOf(tag) {
1969
- return normaliseTag(tag).split("-")[0] ?? "";
1970
- }
1971
- function pickVoice(voices, lang) {
1972
- const wanted = normaliseTag(lang);
1973
- if (wanted === "") return null;
1974
- const primary = primaryOf(wanted);
1975
- const exact = voices.filter((voice) => normaliseTag(voice.lang) === wanted);
1976
- const related = voices.filter((voice) => primaryOf(voice.lang) === primary);
1977
- return exact.find((voice) => voice.default) ?? exact[0] ?? related.find((voice) => voice.default) ?? related[0] ?? null;
1978
- }
1979
- var activeOwner = null;
1980
- var activeStop = null;
1981
- function stopSpeaking() {
1982
- activeStop?.();
1983
- }
1984
- function useSpeechOutput({
1985
- lang
1986
- } = {}) {
1987
- const [available, setAvailable] = useState(() => speechPlatform() !== null);
1988
- const [speaking, setSpeaking] = useState(false);
1989
- const utteranceRef = useRef(null);
1990
- const watchdogRef = useRef(null);
1991
- const ownerRef = useRef({});
1992
- const stopRef = useRef(() => void 0);
1993
- const langRef = useRef(lang);
1994
- langRef.current = lang;
1995
- const clearWatchdog = useCallback(() => {
1996
- if (watchdogRef.current === null) return;
1997
- clearTimeout(watchdogRef.current);
1998
- watchdogRef.current = null;
1999
- }, []);
2000
- const settle = useCallback(() => {
2001
- clearWatchdog();
2002
- utteranceRef.current = null;
2003
- if (activeOwner === ownerRef.current) {
2004
- activeOwner = null;
2005
- activeStop = null;
2006
- }
2007
- setSpeaking(false);
2008
- }, [clearWatchdog]);
2009
- const stop = useCallback(() => {
2010
- const owned = utteranceRef.current !== null;
2011
- settle();
2012
- if (owned) speechPlatform()?.synth.cancel();
2013
- }, [settle]);
2014
- stopRef.current = stop;
2015
- const speak = useCallback(
2016
- (text) => {
2017
- const platform = speechPlatform();
2018
- if (!platform) {
2019
- setAvailable(false);
2020
- return;
2021
- }
2022
- const spoken = text.trim();
2023
- if (spoken === "") return;
2024
- if (activeStop && activeOwner !== ownerRef.current) activeStop();
2025
- platform.synth.cancel();
2026
- const utterance = new platform.Utterance(spoken);
2027
- const wanted = langRef.current;
2028
- if (wanted !== void 0 && wanted !== "") {
2029
- const voice = pickVoice(platform.synth.getVoices(), wanted);
2030
- utterance.lang = voice?.lang ?? wanted;
2031
- if (voice) utterance.voice = voice;
2032
- }
2033
- const mine = () => utteranceRef.current === utterance;
2034
- utterance.onstart = () => {
2035
- if (!mine()) return;
2036
- clearWatchdog();
2037
- setSpeaking(true);
2038
- };
2039
- utterance.onend = () => {
2040
- if (!mine()) return;
2041
- settle();
2042
- };
2043
- utterance.onerror = (event) => {
2044
- if (!mine()) return;
2045
- const code = typeof event?.error === "string" ? event.error : "";
2046
- settle();
2047
- if (code !== "interrupted" && code !== "canceled") setAvailable(false);
2048
- };
2049
- utteranceRef.current = utterance;
2050
- activeOwner = ownerRef.current;
2051
- activeStop = () => {
2052
- stopRef.current();
2053
- };
2054
- setSpeaking(true);
2055
- platform.synth.speak(utterance);
2056
- clearWatchdog();
2057
- watchdogRef.current = setTimeout(() => {
2058
- watchdogRef.current = null;
2059
- if (!mine()) return;
2060
- if (platform.synth.speaking) return;
2061
- settle();
2062
- setAvailable(false);
2063
- }, SILENT_FAILURE_MS);
2064
- },
2065
- [clearWatchdog, settle]
2066
- );
2067
- const toggle = useCallback(
2068
- (text) => {
2069
- if (speaking) stop();
2070
- else speak(text);
2071
- },
2072
- [speak, speaking, stop]
2073
- );
2074
- useEffect(() => {
2075
- if (!speaking || typeof window === "undefined") return;
2076
- const onHide = () => {
2077
- stopRef.current();
2078
- };
2079
- window.addEventListener("pagehide", onHide);
2080
- return () => window.removeEventListener("pagehide", onHide);
2081
- }, [speaking]);
2082
- useEffect(
2083
- () => () => {
2084
- stopRef.current();
2085
- },
2086
- []
2087
- );
2088
- return { supported: available, speaking, speak, stop, toggle };
2089
- }
2090
- var DRAIN_TARGET_MS = 1200;
2091
- var MIN_CHARS_PER_SECOND = 90;
2092
- var MAX_CHARS_PER_SECOND = 2200;
2093
- var MAX_STEP_MS = 250;
2094
- var COMMIT_INTERVAL_MS = 45;
2095
- var FALLBACK_STEP_MS = 50;
2096
- var FENCE = /^ {0,3}(?:```|~~~)/;
2097
- var TABLE_ROW = /^ {0,3}\|/;
2098
- var EMPTY_BLOCK_MARKER = /^ {0,3}(?:[-+>]|#{1,6}|\d{1,9}[.)])\s*$/;
2099
- function isWordCharacter(char) {
2100
- return char !== void 0 && /[\p{L}\p{N}]/u.test(char);
2101
- }
2102
- function clamp(value, min, max) {
2103
- return Math.min(Math.max(value, min), max);
2104
- }
2105
- function now() {
2106
- return typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
2107
- }
2108
- function isHighSurrogate(code) {
2109
- return code >= 55296 && code <= 56319;
2110
- }
2111
- function safeInlineEnd(line) {
2112
- let codeSpan = null;
2113
- const links = [];
2114
- const emphasis = [];
2115
- let at = 0;
2116
- while (at < line.length) {
2117
- const char = line[at] ?? "";
2118
- if (char === "\\") {
2119
- at += 2;
2120
- continue;
2121
- }
2122
- const innermost = links[links.length - 1];
2123
- if (innermost !== void 0 && innermost.kind !== "label") {
2124
- if (char === "(") links.push({ kind: "paren", start: innermost.start });
2125
- else if (char === ")") links.pop();
2126
- at += 1;
2127
- continue;
2128
- }
2129
- if (char === "`") {
2130
- let run = 1;
2131
- while (line[at + run] === "`") run += 1;
2132
- codeSpan = codeSpan === null ? at : null;
2133
- at += run;
2134
- continue;
2135
- }
2136
- if (codeSpan !== null) {
2137
- at += 1;
2138
- continue;
2139
- }
2140
- if (char === "[") {
2141
- links.push({ kind: "label", start: line[at - 1] === "!" ? at - 1 : at });
2142
- at += 1;
2143
- continue;
2144
- }
2145
- if (char === "]" && innermost !== void 0) {
2146
- links.pop();
2147
- if (line[at + 1] === "(") {
2148
- links.push({ kind: "destination", start: innermost.start });
2149
- at += 2;
2150
- continue;
2151
- }
2152
- at += 1;
2153
- continue;
2154
- }
2155
- if (char === "*" || char === "_" || char === "~") {
2156
- let run = 1;
2157
- while (line[at + run] === char) run += 1;
2158
- const start = at;
2159
- at += run;
2160
- const before = line[start - 1];
2161
- const after = line[start + run];
2162
- if (run < 2) continue;
2163
- if (char === "_" && isWordCharacter(before) && isWordCharacter(after)) {
2164
- continue;
2165
- }
2166
- const marker = char.repeat(run);
2167
- const open2 = emphasis.findIndex((entry) => entry.marker === marker);
2168
- if (open2 !== -1) {
2169
- emphasis.splice(open2, 1);
2170
- continue;
2171
- }
2172
- if (after !== void 0 && /\s/.test(after)) continue;
2173
- emphasis.push({ marker, start });
2174
- continue;
2175
- }
2176
- at += 1;
2177
- }
2178
- const open = [
2179
- codeSpan,
2180
- links[0]?.start ?? null,
2181
- emphasis[0]?.start ?? null
2182
- ].filter((value) => value !== null);
2183
- return open.length === 0 ? line.length : Math.min(...open);
2184
- }
2185
- function revealBoundary(text, limit) {
2186
- if (limit <= 0) return 0;
2187
- const caughtUp = limit >= text.length;
2188
- const head = caughtUp ? text : text.slice(0, limit);
2189
- const lineStart = head.lastIndexOf("\n") + 1;
2190
- const line = head.slice(lineStart);
2191
- let fenceStart = null;
2192
- let tableStart = null;
2193
- let tableRows = 0;
2194
- let at = 0;
2195
- while (at < lineStart) {
2196
- const breakAt = head.indexOf("\n", at);
2197
- const end = breakAt === -1 ? lineStart : breakAt;
2198
- const row = head.slice(at, end);
2199
- if (fenceStart !== null) {
2200
- if (FENCE.test(row)) fenceStart = null;
2201
- } else if (FENCE.test(row)) {
2202
- fenceStart = at;
2203
- } else if (TABLE_ROW.test(row)) {
2204
- if (tableStart === null) {
2205
- tableStart = at;
2206
- tableRows = 0;
2207
- }
2208
- tableRows += 1;
2209
- } else if (tableStart !== null) {
2210
- tableStart = null;
2211
- tableRows = 0;
2212
- }
2213
- at = end + 1;
2214
- }
2215
- if (fenceStart === null) {
2216
- const lastIsRow = TABLE_ROW.test(line);
2217
- if (lastIsRow && tableStart === null) {
2218
- tableStart = lineStart;
2219
- tableRows = 0;
2220
- } else if (!lastIsRow && line !== "") {
2221
- tableStart = null;
2222
- tableRows = 0;
2223
- }
2224
- if (tableStart !== null && tableRows < 2) return tableStart;
2225
- }
2226
- if (caughtUp) return text.length;
2227
- if (fenceStart !== null) return fenceStart;
2228
- if (TABLE_ROW.test(line)) return lineStart;
2229
- if (EMPTY_BLOCK_MARKER.test(line)) return lineStart;
2230
- const cut = lineStart + safeInlineEnd(line);
2231
- return isHighSurrogate(text.charCodeAt(cut - 1)) ? cut - 1 : cut;
2232
- }
2233
- function prefersReducedMotion() {
2234
- if (typeof window === "undefined") return true;
2235
- try {
2236
- return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches === true;
2237
- } catch {
2238
- return false;
2239
- }
2240
- }
2241
- function useProgressiveReveal(text, settled) {
2242
- const [, setFrame] = useState(0);
2243
- const [reduced] = useState(prefersReducedMotion);
2244
- const immediate = settled || reduced;
2245
- const textRef = useRef(text);
2246
- const cursorRef = useRef(immediate ? text.length : 0);
2247
- const cutRef = useRef(immediate ? text.length : 0);
2248
- const committedRef = useRef(0);
2249
- if (text !== textRef.current) {
2250
- const revealed = textRef.current.slice(0, Math.floor(cursorRef.current));
2251
- if (revealed !== "" && !text.startsWith(revealed)) {
2252
- cursorRef.current = text.length;
2253
- }
2254
- cursorRef.current = Math.min(cursorRef.current, text.length);
2255
- cutRef.current = Math.min(cutRef.current, text.length);
2256
- textRef.current = text;
2257
- }
2258
- if (immediate) cursorRef.current = text.length;
2259
- const cut = immediate ? text.length : Math.max(
2260
- cutRef.current,
2261
- revealBoundary(text, Math.floor(cursorRef.current))
2262
- );
2263
- cutRef.current = cut;
2264
- useEffect(() => {
2265
- if (immediate) return;
2266
- if (cursorRef.current >= text.length) return;
2267
- let cancelled = false;
2268
- let cancelStep = null;
2269
- let previous = now();
2270
- const commit = (at, force) => {
2271
- if (!force && at - committedRef.current < COMMIT_INTERVAL_MS) return;
2272
- committedRef.current = at;
2273
- setFrame((value) => value + 1);
2274
- };
2275
- const step = () => {
2276
- cancelStep = null;
2277
- if (cancelled) return;
2278
- const at = now();
2279
- const elapsed = clamp(at - previous, 0, MAX_STEP_MS);
2280
- previous = at;
2281
- const length = textRef.current.length;
2282
- const pending = length - cursorRef.current;
2283
- if (pending <= 0) {
2284
- commit(at, true);
2285
- return;
2286
- }
2287
- const perSecond = clamp(
2288
- pending / (DRAIN_TARGET_MS / 1e3),
2289
- MIN_CHARS_PER_SECOND,
2290
- MAX_CHARS_PER_SECOND
2291
- );
2292
- cursorRef.current = Math.min(
2293
- length,
2294
- cursorRef.current + perSecond * elapsed / 1e3
2295
- );
2296
- const done = cursorRef.current >= length;
2297
- commit(at, done);
2298
- if (!done) schedule();
2299
- };
2300
- const schedule = () => {
2301
- if (typeof window.requestAnimationFrame === "function") {
2302
- const id2 = window.requestAnimationFrame(step);
2303
- cancelStep = () => window.cancelAnimationFrame(id2);
2304
- return;
2305
- }
2306
- const id = setTimeout(step, FALLBACK_STEP_MS);
2307
- cancelStep = () => clearTimeout(id);
2308
- };
2309
- schedule();
2310
- return () => {
2311
- cancelled = true;
2312
- cancelStep?.();
2313
- };
2314
- }, [text, immediate]);
2315
- return text.slice(0, cut);
2316
- }
2317
-
2318
- export { DEFAULT_EXPLORE_EXAMPLE_PROMPTS, FALLBACK_EXPLORE_LIMITS, classifyExploreError, stopSpeaking, useExploreChat, useProgressiveReveal, useSpeechInput, useSpeechOutput };
1
+ import '../chunk-GTRAXQGC.mjs';
2
+ export { DEFAULT_EXPLORE_EXAMPLE_PROMPTS, FALLBACK_EXPLORE_LIMITS, classifyExploreError, stopSpeaking, useExploreChat, useProgressiveReveal, useSpeechInput, useSpeechOutput } from '../chunk-EUPFS6MZ.mjs';
3
+ import '../chunk-SKIYDKIS.mjs';
4
+ import '../chunk-KZANIV3S.mjs';
5
+ import '../chunk-5JRJ57CL.mjs';
6
+ import '../chunk-VNS5WDWO.mjs';
2319
7
  //# sourceMappingURL=index.mjs.map
2320
8
  //# sourceMappingURL=index.mjs.map