@burdenoff/website-sdk 2026.824.2 → 2026.828.1

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 (124) hide show
  1. package/README.md +88 -0
  2. package/dist/client/index.d.mts +2 -3
  3. package/dist/client/index.d.ts +2 -3
  4. package/dist/client/index.js +13 -7
  5. package/dist/client/index.js.map +1 -1
  6. package/dist/client/index.mjs +13 -7
  7. package/dist/client/index.mjs.map +1 -1
  8. package/dist/components/contact.d.mts +2 -2
  9. package/dist/components/contact.d.ts +2 -2
  10. package/dist/components/contact.js +13 -7
  11. package/dist/components/contact.js.map +1 -1
  12. package/dist/components/contact.mjs +13 -7
  13. package/dist/components/contact.mjs.map +1 -1
  14. package/dist/components/electron-download.d.mts +2 -2
  15. package/dist/components/electron-download.d.ts +2 -2
  16. package/dist/components/explore-cta.d.mts +26 -0
  17. package/dist/components/explore-cta.d.ts +26 -0
  18. package/dist/components/explore-cta.js +95 -0
  19. package/dist/components/explore-cta.js.map +1 -0
  20. package/dist/components/explore-cta.mjs +93 -0
  21. package/dist/components/explore-cta.mjs.map +1 -0
  22. package/dist/components/explore.d.mts +43 -0
  23. package/dist/components/explore.d.ts +43 -0
  24. package/dist/components/explore.js +2219 -0
  25. package/dist/components/explore.js.map +1 -0
  26. package/dist/components/explore.mjs +2193 -0
  27. package/dist/components/explore.mjs.map +1 -0
  28. package/dist/components/launch-countdown.d.mts +2 -2
  29. package/dist/components/launch-countdown.d.ts +2 -2
  30. package/dist/components/newsletter.d.mts +3 -3
  31. package/dist/components/newsletter.d.ts +3 -3
  32. package/dist/components/newsletter.js +13 -7
  33. package/dist/components/newsletter.js.map +1 -1
  34. package/dist/components/newsletter.mjs +13 -7
  35. package/dist/components/newsletter.mjs.map +1 -1
  36. package/dist/components/partners.d.mts +2 -2
  37. package/dist/components/partners.d.ts +2 -2
  38. package/dist/components/partners.js +13 -7
  39. package/dist/components/partners.js.map +1 -1
  40. package/dist/components/partners.mjs +13 -7
  41. package/dist/components/partners.mjs.map +1 -1
  42. package/dist/components/pricing.d.mts +3 -3
  43. package/dist/components/pricing.d.ts +3 -3
  44. package/dist/components/pricing.js +13 -7
  45. package/dist/components/pricing.js.map +1 -1
  46. package/dist/components/pricing.mjs +13 -7
  47. package/dist/components/pricing.mjs.map +1 -1
  48. package/dist/components/problems-solved.d.mts +2 -2
  49. package/dist/components/problems-solved.d.ts +2 -2
  50. package/dist/components/resource-links.d.mts +2 -2
  51. package/dist/components/resource-links.d.ts +2 -2
  52. package/dist/components/resource-links.js +13 -7
  53. package/dist/components/resource-links.js.map +1 -1
  54. package/dist/components/resource-links.mjs +13 -7
  55. package/dist/components/resource-links.mjs.map +1 -1
  56. package/dist/components/social-links.d.mts +2 -2
  57. package/dist/components/social-links.d.ts +2 -2
  58. package/dist/components/social-links.js +13 -7
  59. package/dist/components/social-links.js.map +1 -1
  60. package/dist/components/social-links.mjs +13 -7
  61. package/dist/components/social-links.mjs.map +1 -1
  62. package/dist/components/unsubscribe.d.mts +2 -2
  63. package/dist/components/unsubscribe.d.ts +2 -2
  64. package/dist/components/unsubscribe.js +13 -7
  65. package/dist/components/unsubscribe.js.map +1 -1
  66. package/dist/components/unsubscribe.mjs +13 -7
  67. package/dist/components/unsubscribe.mjs.map +1 -1
  68. package/dist/components/waitlist.d.mts +3 -3
  69. package/dist/components/waitlist.d.ts +3 -3
  70. package/dist/components/waitlist.js +13 -7
  71. package/dist/components/waitlist.js.map +1 -1
  72. package/dist/components/waitlist.mjs +13 -7
  73. package/dist/components/waitlist.mjs.map +1 -1
  74. package/dist/components/website-switcher.d.mts +2 -2
  75. package/dist/components/website-switcher.d.ts +2 -2
  76. package/dist/content/index.d.mts +2 -3
  77. package/dist/content/index.d.ts +2 -3
  78. package/dist/content/index.js +13 -7
  79. package/dist/content/index.js.map +1 -1
  80. package/dist/content/index.mjs +13 -7
  81. package/dist/content/index.mjs.map +1 -1
  82. package/dist/{graphql-client-Cv6TO6hn.d.mts → graphql-client-BXn6RYV0.d.mts} +31 -4
  83. package/dist/{graphql-client-Cv6TO6hn.d.ts → graphql-client-BXn6RYV0.d.ts} +31 -4
  84. package/dist/hooks/index.d.mts +1 -0
  85. package/dist/hooks/index.d.ts +1 -0
  86. package/dist/hooks/index.js +1145 -0
  87. package/dist/hooks/index.js.map +1 -0
  88. package/dist/hooks/index.mjs +1140 -0
  89. package/dist/hooks/index.mjs.map +1 -0
  90. package/dist/{index-CFsUFxYo.d.ts → index-BXg7cQLm.d.ts} +11 -11
  91. package/dist/index-CUJTTlYx.d.mts +244 -0
  92. package/dist/index-CUJTTlYx.d.ts +244 -0
  93. package/dist/{index-CuMRiKGB.d.mts → index-DYxQiEm5.d.mts} +11 -11
  94. package/dist/index.d.mts +17 -15
  95. package/dist/index.d.ts +17 -15
  96. package/dist/index.js +1987 -426
  97. package/dist/index.js.map +1 -1
  98. package/dist/index.mjs +1977 -428
  99. package/dist/index.mjs.map +1 -1
  100. package/dist/product/index.d.mts +2 -2
  101. package/dist/product/index.d.ts +2 -2
  102. package/dist/product/index.js +13 -7
  103. package/dist/product/index.js.map +1 -1
  104. package/dist/product/index.mjs +13 -7
  105. package/dist/product/index.mjs.map +1 -1
  106. package/dist/{product-card-DL9O3Ez9.d.mts → product-card-CGxETsFa.d.mts} +7 -7
  107. package/dist/{product-card-DL9O3Ez9.d.ts → product-card-CGxETsFa.d.ts} +7 -7
  108. package/dist/{provider-D-Do5PmD.d.ts → provider-CUfI8meE.d.mts} +3 -3
  109. package/dist/{provider-BhsbxVPo.d.mts → provider-D_uUM7_e.d.ts} +3 -3
  110. package/dist/seo/index.d.mts +2 -2
  111. package/dist/seo/index.d.ts +2 -2
  112. package/dist/store/index.d.mts +3 -3
  113. package/dist/store/index.d.ts +3 -3
  114. package/dist/store/index.js +13 -7
  115. package/dist/store/index.js.map +1 -1
  116. package/dist/store/index.mjs +13 -7
  117. package/dist/store/index.mjs.map +1 -1
  118. package/dist/utils/index.d.mts +49 -1
  119. package/dist/utils/index.d.ts +49 -1
  120. package/dist/utils/index.js +70 -0
  121. package/dist/utils/index.js.map +1 -1
  122. package/dist/utils/index.mjs +68 -1
  123. package/dist/utils/index.mjs.map +1 -1
  124. package/package.json +40 -30
@@ -0,0 +1,1140 @@
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
+
44
+ // src/client/graphql-client.ts
45
+ var _WebSDKClient = class _WebSDKClient {
46
+ constructor(config) {
47
+ __publicField(this, "config");
48
+ __publicField(this, "queryCache", /* @__PURE__ */ new Map());
49
+ __publicField(this, "inflight", /* @__PURE__ */ new Map());
50
+ this.config = {
51
+ ...config,
52
+ gatewayUrl: validateGatewayUrl(config.gatewayUrl),
53
+ headers: sanitizeHeaders(config.headers)
54
+ };
55
+ }
56
+ getConfig() {
57
+ return this.config;
58
+ }
59
+ /**
60
+ * Execute a GraphQL query (with deduplication and caching).
61
+ *
62
+ * Pass `{ cache: false }` to bypass the cache entirely — required for poll
63
+ * loops, where every tick must reach the network.
64
+ */
65
+ async query(query, variables, options) {
66
+ if (options?.cache === false) {
67
+ return this.request(query, variables, true, options.timeoutMs);
68
+ }
69
+ const cacheKey = JSON.stringify({ query, variables });
70
+ const cached = this.queryCache.get(cacheKey);
71
+ if (cached) {
72
+ if (Date.now() - cached.ts < _WebSDKClient.CACHE_TTL) {
73
+ return cached.data;
74
+ }
75
+ this.queryCache.delete(cacheKey);
76
+ }
77
+ const existing = this.inflight.get(cacheKey);
78
+ if (existing) {
79
+ return existing;
80
+ }
81
+ const promise = this.request(query, variables, true, options?.timeoutMs).then((result) => {
82
+ if (result.data && !result.errors?.length) {
83
+ if (this.queryCache.size >= _WebSDKClient.MAX_CACHE_ENTRIES) {
84
+ const oldestEntry = this.queryCache.keys().next().value;
85
+ if (oldestEntry) {
86
+ this.queryCache.delete(oldestEntry);
87
+ }
88
+ }
89
+ this.queryCache.set(cacheKey, { data: result, ts: Date.now() });
90
+ }
91
+ return result;
92
+ }).finally(() => {
93
+ this.inflight.delete(cacheKey);
94
+ });
95
+ this.inflight.set(cacheKey, promise);
96
+ return promise;
97
+ }
98
+ /**
99
+ * Execute a GraphQL mutation
100
+ */
101
+ async mutate(mutation, variables, options) {
102
+ return this.request(mutation, variables, false, options?.timeoutMs);
103
+ }
104
+ /** HTTP statuses worth another attempt — transient server/edge conditions. */
105
+ static isRetriableStatus(status) {
106
+ return status === 429 || status === 408 || status >= 500 && status < 600;
107
+ }
108
+ static sleep(ms) {
109
+ return new Promise((resolve) => setTimeout(resolve, ms));
110
+ }
111
+ /**
112
+ * Perform the HTTP call with a hard timeout. Every outcome resolves to a
113
+ * GraphQLResponse — callers never hang, so a UI's `loading` state always
114
+ * settles into data or a renderable error.
115
+ */
116
+ async attempt(query, variables, timeoutMs) {
117
+ const controller = new AbortController();
118
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
119
+ try {
120
+ const response = await fetch(this.config.gatewayUrl, {
121
+ method: "POST",
122
+ headers: {
123
+ "Content-Type": "application/json",
124
+ "x-product-id": this.config.productId,
125
+ ...this.config.headers
126
+ },
127
+ body: JSON.stringify({ query, variables }),
128
+ signal: controller.signal
129
+ });
130
+ if (!response.ok) {
131
+ console.error(
132
+ "[WebSDK] GraphQL request failed",
133
+ response.status,
134
+ response.statusText
135
+ );
136
+ return {
137
+ res: {
138
+ errors: [
139
+ {
140
+ message: `HTTP ${response.status}: ${response.statusText}`,
141
+ extensions: { code: `HTTP_${response.status}` }
142
+ }
143
+ ]
144
+ },
145
+ retriable: _WebSDKClient.isRetriableStatus(response.status)
146
+ };
147
+ }
148
+ return {
149
+ res: await response.json(),
150
+ retriable: false
151
+ };
152
+ } catch (error) {
153
+ const aborted = error instanceof Error && (error.name === "AbortError" || controller.signal.aborted);
154
+ const message = aborted ? `Request timed out after ${timeoutMs}ms` : error instanceof Error ? error.message : "Network error";
155
+ console.error("[WebSDK] Network error", message);
156
+ return {
157
+ res: {
158
+ errors: [
159
+ {
160
+ message,
161
+ extensions: { code: aborted ? "TIMEOUT" : "NETWORK_ERROR" }
162
+ }
163
+ ]
164
+ },
165
+ // Transport-level failures are worth one more try; a genuine outage
166
+ // just fails twice quickly and still renders an error state.
167
+ retriable: true
168
+ };
169
+ } finally {
170
+ clearTimeout(timer);
171
+ }
172
+ }
173
+ async request(query, variables, retry = true, timeoutOverrideMs) {
174
+ const timeoutMs = timeoutOverrideMs ?? this.config.timeoutMs ?? _WebSDKClient.DEFAULT_TIMEOUT_MS;
175
+ const maxRetries = retry ? this.config.maxRetries ?? _WebSDKClient.DEFAULT_MAX_RETRIES : 0;
176
+ let last;
177
+ for (let i = 0; i <= maxRetries; i++) {
178
+ const { res, retriable } = await this.attempt(
179
+ query,
180
+ variables,
181
+ timeoutMs
182
+ );
183
+ if (!retriable || i === maxRetries) return res;
184
+ last = res;
185
+ await _WebSDKClient.sleep(
186
+ _WebSDKClient.RETRY_BASE_DELAY_MS * (i + 1) + Math.random() * 200
187
+ );
188
+ }
189
+ return last;
190
+ }
191
+ };
192
+ __publicField(_WebSDKClient, "CACHE_TTL", 5 * 60 * 1e3);
193
+ // 5 minutes
194
+ __publicField(_WebSDKClient, "MAX_CACHE_ENTRIES", 100);
195
+ __publicField(_WebSDKClient, "DEFAULT_TIMEOUT_MS", 12e3);
196
+ __publicField(_WebSDKClient, "DEFAULT_MAX_RETRIES", 1);
197
+ __publicField(_WebSDKClient, "RETRY_BASE_DELAY_MS", 400);
198
+ var WebSDKContext = createContext(null);
199
+ function useWebSDK() {
200
+ const client = useContext(WebSDKContext);
201
+ if (!client) {
202
+ throw new Error("useWebSDK must be used within a WebSDKProvider");
203
+ }
204
+ return client;
205
+ }
206
+
207
+ // src/components/explore-types.ts
208
+ var EXPLORE_MESSAGE_FIELDS = (
209
+ /* GraphQL */
210
+ `
211
+ id
212
+ conversationId
213
+ role
214
+ status
215
+ content
216
+ partialContent
217
+ activity
218
+ references {
219
+ url
220
+ title
221
+ description
222
+ product
223
+ imageUrl
224
+ }
225
+ ctas {
226
+ kind
227
+ label
228
+ url
229
+ product
230
+ }
231
+ errorCode
232
+ createdAt
233
+ completedAt
234
+ `
235
+ );
236
+ var EXPLORE_CATALOG_QUERY = (
237
+ /* GraphQL */
238
+ `
239
+ query ExploreCatalog($productSlug: String) {
240
+ exploreCatalog(productSlug: $productSlug) {
241
+ enabled
242
+ products {
243
+ slug
244
+ name
245
+ tagline
246
+ website
247
+ }
248
+ examplePrompts
249
+ welcomeTitle
250
+ welcomeBody
251
+ limits {
252
+ maxMessageLength
253
+ maxTurnsPerConversation
254
+ messagesPerDay
255
+ historyTurns
256
+ }
257
+ captchaRequired
258
+ recaptchaSiteKey
259
+ }
260
+ }
261
+ `
262
+ );
263
+ var EXPLORE_MESSAGE_QUERY = (
264
+ /* GraphQL */
265
+ `
266
+ query ExploreMessage($conversationToken: String!, $id: ID!) {
267
+ exploreMessage(conversationToken: $conversationToken, id: $id) {
268
+ ${EXPLORE_MESSAGE_FIELDS}
269
+ }
270
+ }
271
+ `
272
+ );
273
+ var SEND_EXPLORE_MESSAGE_MUTATION = (
274
+ /* GraphQL */
275
+ `
276
+ mutation SendExploreMessage($input: SendExploreMessageInput!) {
277
+ sendExploreMessage(input: $input) {
278
+ conversation {
279
+ id
280
+ token
281
+ productSlug
282
+ turnCount
283
+ createdAt
284
+ }
285
+ userMessage {
286
+ ${EXPLORE_MESSAGE_FIELDS}
287
+ }
288
+ assistantMessage {
289
+ ${EXPLORE_MESSAGE_FIELDS}
290
+ }
291
+ remainingToday
292
+ }
293
+ }
294
+ `
295
+ );
296
+
297
+ // src/data/products.ts
298
+ var ECOSYSTEM_PRODUCTS = [
299
+ {
300
+ slug: "workspaces",
301
+ name: "Workspaces",
302
+ websiteUrl: "https://burdenoff.com"
303
+ },
304
+ {
305
+ slug: "vibecontrols",
306
+ name: "VibeControls",
307
+ websiteUrl: "https://vibecontrols.com"
308
+ },
309
+ {
310
+ slug: "fluidgrids",
311
+ name: "FluidGrids",
312
+ websiteUrl: "https://fluidgrids.com"
313
+ },
314
+ // Botlit ships on botlit.ai — botlit.com does not resolve.
315
+ { slug: "botlit", name: "Botlit", websiteUrl: "https://www.botlit.ai" },
316
+ {
317
+ slug: "bigconsole",
318
+ name: "BigConsole",
319
+ websiteUrl: "https://bigconsole.com"
320
+ },
321
+ {
322
+ slug: "semanticfed",
323
+ name: "SemanticFed",
324
+ websiteUrl: "https://semanticfed.com"
325
+ },
326
+ {
327
+ slug: "intelwatchtower",
328
+ name: "IntelWatchtower",
329
+ websiteUrl: "https://intelwatchtower.com"
330
+ },
331
+ { slug: "buildmyiq", name: "BuildMyIQ", websiteUrl: "https://buildmyiq.com" },
332
+ {
333
+ slug: "assethandler",
334
+ name: "AssetHandler",
335
+ websiteUrl: "https://assethandler.com"
336
+ },
337
+ {
338
+ slug: "crewfoundry",
339
+ name: "CrewFoundry",
340
+ websiteUrl: "https://crewfoundry.com"
341
+ },
342
+ {
343
+ slug: "planmagnet",
344
+ name: "PlanMagnet",
345
+ websiteUrl: "https://planmagnet.com"
346
+ },
347
+ {
348
+ slug: "eventfullymanaged",
349
+ name: "EventfullyManaged",
350
+ websiteUrl: "https://eventfullymanaged.com"
351
+ },
352
+ {
353
+ slug: "headshotmarketing",
354
+ name: "HeadshotMarketing",
355
+ websiteUrl: "https://headshotmarketing.com"
356
+ },
357
+ {
358
+ slug: "technospam",
359
+ name: "TechnoSpam",
360
+ websiteUrl: "https://technospam.com"
361
+ },
362
+ { slug: "kadaikodi", name: "Kadaikodi", websiteUrl: "https://kadaikodi.com" },
363
+ {
364
+ slug: "movethewheels",
365
+ name: "MoveTheWheels",
366
+ websiteUrl: "https://movethewheels.com"
367
+ },
368
+ {
369
+ slug: "healthybowl",
370
+ name: "Healthy Bowl",
371
+ websiteUrl: "https://gethealthybowl.com"
372
+ },
373
+ { slug: "ggnomad", name: "GGNomad", websiteUrl: "https://ggnomad.com" },
374
+ {
375
+ slug: "timecampus",
376
+ name: "TimeCampus",
377
+ websiteUrl: "https://timecampus.com"
378
+ },
379
+ {
380
+ slug: "manufacturedops",
381
+ name: "ManufacturedOps",
382
+ websiteUrl: "https://manufacturedops.com"
383
+ },
384
+ {
385
+ slug: "theglobalfuel",
386
+ name: "TheGlobalFuel",
387
+ websiteUrl: "https://theglobalfuel.com"
388
+ },
389
+ {
390
+ slug: "housingvista",
391
+ name: "HousingVista",
392
+ websiteUrl: "https://housingvista.com"
393
+ },
394
+ {
395
+ slug: "proserviceworld",
396
+ name: "ProServiceWorld",
397
+ websiteUrl: "https://proserviceworld.com"
398
+ },
399
+ {
400
+ slug: "mybodyshield",
401
+ name: "MyBodyShield",
402
+ websiteUrl: "https://mybodyshield.com"
403
+ },
404
+ {
405
+ slug: "artistrybase",
406
+ name: "ArtistryBase",
407
+ websiteUrl: "https://artistrybase.com"
408
+ },
409
+ {
410
+ slug: "theculturepost",
411
+ name: "TheCulturePost",
412
+ websiteUrl: "https://theculturepost.com"
413
+ },
414
+ { slug: "collabkin", name: "CollabKin", websiteUrl: "https://collabkin.com" },
415
+ {
416
+ slug: "comradecircle",
417
+ name: "ComradeCircle",
418
+ websiteUrl: "https://comradecircle.com"
419
+ },
420
+ {
421
+ slug: "brainyrich",
422
+ name: "BrainyRich",
423
+ websiteUrl: "https://brainyrich.com"
424
+ },
425
+ {
426
+ slug: "cosmicintersection",
427
+ name: "CosmicIntersection",
428
+ websiteUrl: "https://cosmicintersection.com"
429
+ },
430
+ {
431
+ slug: "govcitizenhub",
432
+ name: "GovCitizenHub",
433
+ websiteUrl: "https://govcitizenhub.com"
434
+ },
435
+ {
436
+ slug: "adaptercloud",
437
+ name: "AdapterCloud",
438
+ websiteUrl: "https://adaptercloud.com"
439
+ },
440
+ {
441
+ slug: "subscriberbot",
442
+ name: "Subscriber Bot",
443
+ websiteUrl: "https://subscriberbot.com"
444
+ },
445
+ {
446
+ slug: "hookmovies",
447
+ name: "HookMovies",
448
+ websiteUrl: "https://hookmovies.com"
449
+ },
450
+ {
451
+ slug: "coolandlovely",
452
+ name: "CoolAndLovely",
453
+ websiteUrl: "https://coolandlovely.com"
454
+ },
455
+ {
456
+ slug: "atheletebridge",
457
+ name: "AthleteBridge",
458
+ websiteUrl: "https://atheletebridge.com"
459
+ },
460
+ {
461
+ slug: "labsofscience",
462
+ name: "LabsOfScience",
463
+ websiteUrl: "https://labsofscience.com"
464
+ },
465
+ {
466
+ slug: "ecoimpacthub",
467
+ name: "EcoImpactHub",
468
+ websiteUrl: "https://ecoimpacthub.com"
469
+ }
470
+ ];
471
+
472
+ // src/utils/recaptcha-v3.ts
473
+ var SCRIPT_ID = "boff-recaptcha-v3";
474
+ var SCRIPT_SRC = "https://www.google.com/recaptcha/api.js?render=";
475
+ var EXPLORE_RECAPTCHA_ACTION = "explore_chat";
476
+ var loaders = /* @__PURE__ */ new Map();
477
+ function isBrowser() {
478
+ return typeof window !== "undefined" && typeof document !== "undefined";
479
+ }
480
+ function loadRecaptchaV3(siteKey) {
481
+ if (!siteKey) {
482
+ return Promise.reject(new Error("reCAPTCHA site key is required"));
483
+ }
484
+ if (!isBrowser()) {
485
+ return Promise.reject(
486
+ new Error("reCAPTCHA v3 can only be loaded in a browser")
487
+ );
488
+ }
489
+ const existing = loaders.get(siteKey);
490
+ if (existing) return existing;
491
+ const promise = new Promise((resolve, reject) => {
492
+ const ready = () => {
493
+ const api = window.grecaptcha;
494
+ if (!api) {
495
+ reject(new Error("reCAPTCHA loaded but grecaptcha is unavailable"));
496
+ return;
497
+ }
498
+ api.ready(() => resolve(api));
499
+ };
500
+ if (window.grecaptcha) {
501
+ ready();
502
+ return;
503
+ }
504
+ const scriptId = `${SCRIPT_ID}-${siteKey}`;
505
+ const found = document.getElementById(scriptId);
506
+ if (found) {
507
+ found.addEventListener("load", ready, { once: true });
508
+ found.addEventListener(
509
+ "error",
510
+ () => reject(new Error("Failed to load reCAPTCHA v3")),
511
+ { once: true }
512
+ );
513
+ return;
514
+ }
515
+ const script = document.createElement("script");
516
+ script.id = scriptId;
517
+ script.src = `${SCRIPT_SRC}${encodeURIComponent(siteKey)}`;
518
+ script.async = true;
519
+ script.defer = true;
520
+ script.addEventListener("load", ready, { once: true });
521
+ script.addEventListener(
522
+ "error",
523
+ () => {
524
+ loaders.delete(siteKey);
525
+ reject(new Error("Failed to load reCAPTCHA v3"));
526
+ },
527
+ { once: true }
528
+ );
529
+ document.head.appendChild(script);
530
+ });
531
+ loaders.set(siteKey, promise);
532
+ return promise;
533
+ }
534
+ async function getRecaptchaV3Token(siteKey, action = EXPLORE_RECAPTCHA_ACTION) {
535
+ const api = await loadRecaptchaV3(siteKey);
536
+ return api.execute(siteKey, { action });
537
+ }
538
+
539
+ // src/hooks/use-explore-chat.ts
540
+ var DEFAULT_STORAGE_KEY = "boff.explore.v1";
541
+ var DEFAULT_POLL_INTERVAL_MS = 1500;
542
+ var DEFAULT_POLL_TIMEOUT_MS = 9e4;
543
+ var POLL_REQUEST_TIMEOUT_MS = 1e4;
544
+ var SEND_REQUEST_TIMEOUT_MS = 18e3;
545
+ var MAX_CONSECUTIVE_POLL_FAILURES = 4;
546
+ var MAX_PERSISTED_MESSAGES = 40;
547
+ var FALLBACK_EXPLORE_LIMITS = {
548
+ maxMessageLength: 2e3,
549
+ maxTurnsPerConversation: 20,
550
+ messagesPerDay: 100,
551
+ historyTurns: 6
552
+ };
553
+ var DEFAULT_EXPLORE_EXAMPLE_PROMPTS = [
554
+ "What does this product actually do?",
555
+ "Which Burdenoff product fits my team?",
556
+ "How do I get started, step by step?",
557
+ "What does it integrate with?"
558
+ ];
559
+ var FALLBACK_WELCOME_TITLE = "Ask anything about our products";
560
+ var FALLBACK_WELCOME_BODY = "Get straight answers drawn from our product documentation and public pages \u2014 with links back to the exact page each answer came from.";
561
+ function buildFallbackCatalog(examplePrompts) {
562
+ return {
563
+ enabled: true,
564
+ products: ECOSYSTEM_PRODUCTS.map((p) => ({
565
+ slug: p.slug,
566
+ name: p.name,
567
+ tagline: null,
568
+ website: p.websiteUrl
569
+ })),
570
+ examplePrompts: examplePrompts?.length ? examplePrompts : DEFAULT_EXPLORE_EXAMPLE_PROMPTS,
571
+ welcomeTitle: FALLBACK_WELCOME_TITLE,
572
+ welcomeBody: FALLBACK_WELCOME_BODY,
573
+ limits: FALLBACK_EXPLORE_LIMITS,
574
+ captchaRequired: false,
575
+ recaptchaSiteKey: null
576
+ };
577
+ }
578
+ function normalizeCatalog(raw, fallback) {
579
+ return {
580
+ enabled: raw.enabled !== false,
581
+ products: raw.products?.length ? raw.products : fallback.products,
582
+ examplePrompts: raw.examplePrompts?.length ? raw.examplePrompts : fallback.examplePrompts,
583
+ welcomeTitle: raw.welcomeTitle || fallback.welcomeTitle,
584
+ welcomeBody: raw.welcomeBody || fallback.welcomeBody,
585
+ limits: {
586
+ maxMessageLength: raw.limits?.maxMessageLength || fallback.limits.maxMessageLength,
587
+ maxTurnsPerConversation: raw.limits?.maxTurnsPerConversation || fallback.limits.maxTurnsPerConversation,
588
+ messagesPerDay: raw.limits?.messagesPerDay || fallback.limits.messagesPerDay,
589
+ historyTurns: raw.limits?.historyTurns || fallback.limits.historyTurns
590
+ },
591
+ captchaRequired: raw.captchaRequired === true,
592
+ recaptchaSiteKey: raw.recaptchaSiteKey ?? null
593
+ };
594
+ }
595
+ var RATE_LIMIT_CODES = /* @__PURE__ */ new Set([
596
+ "RATE_LIMITED",
597
+ "HTTP_429",
598
+ "EXPLORE_GLOBAL_LIMIT"
599
+ ]);
600
+ var CAPTCHA_CODES = /* @__PURE__ */ new Set(["CAPTCHA_FAILED", "CAPTCHA_REQUIRED"]);
601
+ var NETWORK_CODES = /* @__PURE__ */ new Set([
602
+ "NETWORK_ERROR",
603
+ "UPSTREAM_UNAVAILABLE",
604
+ "CONVERSATION_BUSY",
605
+ "PROVIDER_ERROR",
606
+ "QUEUE_FULL"
607
+ ]);
608
+ var VALIDATION_CODES = /* @__PURE__ */ new Set([
609
+ "MESSAGE_TOO_LONG",
610
+ "MESSAGE_EMPTY",
611
+ "CONVERSATION_LIMIT",
612
+ "INVALID_INPUT"
613
+ ]);
614
+ function classifyExploreError(code, serverMessage) {
615
+ const c = code ?? "UNKNOWN";
616
+ if (RATE_LIMIT_CODES.has(c)) {
617
+ return {
618
+ kind: "rate-limit",
619
+ code: c,
620
+ message: "You've reached the message limit for now. Please try again later.",
621
+ retryable: false
622
+ };
623
+ }
624
+ if (CAPTCHA_CODES.has(c)) {
625
+ return {
626
+ kind: "captcha",
627
+ code: c,
628
+ message: "We couldn't verify that you're human. Please try sending that again.",
629
+ retryable: true
630
+ };
631
+ }
632
+ if (c === "TIMEOUT" || c === "TOOL_BUDGET") {
633
+ return {
634
+ kind: "timeout",
635
+ code: c,
636
+ message: "That answer took too long to come back. Try asking again.",
637
+ retryable: true
638
+ };
639
+ }
640
+ if (NETWORK_CODES.has(c)) {
641
+ return {
642
+ kind: "network",
643
+ code: c,
644
+ message: "We couldn't reach the assistant just now. Check your connection and try again.",
645
+ retryable: true
646
+ };
647
+ }
648
+ if (c === "EXPLORE_DISABLED") {
649
+ return {
650
+ kind: "disabled",
651
+ code: c,
652
+ message: "Explore is unavailable at the moment. Please check back soon.",
653
+ retryable: false
654
+ };
655
+ }
656
+ if (VALIDATION_CODES.has(c)) {
657
+ return {
658
+ kind: "validation",
659
+ code: c,
660
+ message: serverMessage || "That message couldn't be sent.",
661
+ retryable: false
662
+ };
663
+ }
664
+ if (c === "EMPTY_ANSWER") {
665
+ return {
666
+ kind: "unknown",
667
+ code: c,
668
+ message: "No answer came back for that one. Try rephrasing, or ask something more specific.",
669
+ retryable: true
670
+ };
671
+ }
672
+ return {
673
+ kind: "unknown",
674
+ code: c,
675
+ message: serverMessage || "Something went wrong. Please try again.",
676
+ retryable: true
677
+ };
678
+ }
679
+ function readPersisted(key) {
680
+ if (typeof window === "undefined") return null;
681
+ try {
682
+ const raw = window.sessionStorage.getItem(key);
683
+ if (!raw) return null;
684
+ const parsed = JSON.parse(raw);
685
+ if (!parsed || typeof parsed !== "object") return null;
686
+ const record = parsed;
687
+ return {
688
+ conversationToken: typeof record.conversationToken === "string" ? record.conversationToken : null,
689
+ messages: Array.isArray(record.messages) ? record.messages.slice(-MAX_PERSISTED_MESSAGES) : [],
690
+ focusProduct: typeof record.focusProduct === "string" ? record.focusProduct : null
691
+ };
692
+ } catch {
693
+ return null;
694
+ }
695
+ }
696
+ function visibleText(message) {
697
+ return message.content || message.partialContent || "";
698
+ }
699
+ function countUserTurns(messages) {
700
+ return messages.filter((m) => m.role === "USER").length;
701
+ }
702
+ function useExploreChat(options = {}) {
703
+ const {
704
+ productSlug,
705
+ pageUrl,
706
+ locale,
707
+ examplePrompts,
708
+ pollIntervalMs = DEFAULT_POLL_INTERVAL_MS,
709
+ pollTimeoutMs = DEFAULT_POLL_TIMEOUT_MS,
710
+ storageKey = DEFAULT_STORAGE_KEY,
711
+ persist = true,
712
+ onSend
713
+ } = options;
714
+ const client = useWebSDK();
715
+ const promptKey = JSON.stringify(examplePrompts ?? []);
716
+ const fallbackCatalog = useMemo(
717
+ () => buildFallbackCatalog(JSON.parse(promptKey)),
718
+ [promptKey]
719
+ );
720
+ const [catalog, setCatalog] = useState(fallbackCatalog);
721
+ const [messages, setMessages] = useState([]);
722
+ const [phase, setPhase] = useState("loading");
723
+ const [error, setError] = useState(null);
724
+ const [remainingToday, setRemainingToday] = useState(null);
725
+ const [focusProduct, setFocusProductState] = useState(null);
726
+ const [turnCount, setTurnCount] = useState(0);
727
+ const [hydrated, setHydrated] = useState(false);
728
+ const mountedRef = useRef(true);
729
+ const pollGenerationRef = useRef(0);
730
+ const pollTimerRef = useRef(null);
731
+ const conversationTokenRef = useRef(null);
732
+ const catalogRef = useRef(fallbackCatalog);
733
+ const turnCountRef = useRef(0);
734
+ const focusProductRef = useRef(null);
735
+ const lastSentTextRef = useRef(null);
736
+ const inFlightRef = useRef(false);
737
+ catalogRef.current = catalog;
738
+ const clearPollTimer = useCallback(() => {
739
+ if (pollTimerRef.current !== null) {
740
+ clearTimeout(pollTimerRef.current);
741
+ pollTimerRef.current = null;
742
+ }
743
+ }, []);
744
+ const cancelPolling = useCallback(() => {
745
+ pollGenerationRef.current += 1;
746
+ clearPollTimer();
747
+ }, [clearPollTimer]);
748
+ useEffect(() => {
749
+ mountedRef.current = true;
750
+ return () => {
751
+ mountedRef.current = false;
752
+ pollGenerationRef.current += 1;
753
+ if (pollTimerRef.current !== null) {
754
+ clearTimeout(pollTimerRef.current);
755
+ pollTimerRef.current = null;
756
+ }
757
+ };
758
+ }, []);
759
+ useEffect(() => {
760
+ if (!persist) {
761
+ setHydrated(true);
762
+ return;
763
+ }
764
+ const stored = readPersisted(storageKey);
765
+ if (stored) {
766
+ conversationTokenRef.current = stored.conversationToken;
767
+ focusProductRef.current = stored.focusProduct;
768
+ const settled = stored.messages.flatMap((m) => {
769
+ if (m.role !== "ASSISTANT") return [m];
770
+ if (m.status !== "PENDING" && m.status !== "RUNNING") return [m];
771
+ const text = visibleText(m);
772
+ if (!text) return [];
773
+ return [{ ...m, status: "COMPLETED", content: text }];
774
+ });
775
+ setMessages(settled);
776
+ setFocusProductState(stored.focusProduct);
777
+ const turns = countUserTurns(settled);
778
+ turnCountRef.current = turns;
779
+ setTurnCount(turns);
780
+ }
781
+ setHydrated(true);
782
+ }, [persist, storageKey]);
783
+ useEffect(() => {
784
+ if (!persist || !hydrated || typeof window === "undefined") return;
785
+ try {
786
+ const payload = {
787
+ conversationToken: conversationTokenRef.current,
788
+ messages: messages.slice(-MAX_PERSISTED_MESSAGES),
789
+ focusProduct
790
+ };
791
+ if (!payload.conversationToken && payload.messages.length === 0 && !payload.focusProduct) {
792
+ window.sessionStorage.removeItem(storageKey);
793
+ return;
794
+ }
795
+ window.sessionStorage.setItem(storageKey, JSON.stringify(payload));
796
+ } catch {
797
+ }
798
+ }, [persist, hydrated, storageKey, messages, focusProduct]);
799
+ useEffect(() => {
800
+ let cancelled = false;
801
+ const load = async () => {
802
+ const res = await client.query(
803
+ EXPLORE_CATALOG_QUERY,
804
+ { productSlug: productSlug ?? null }
805
+ );
806
+ if (cancelled || !mountedRef.current) return;
807
+ const raw = res.data?.exploreCatalog;
808
+ if (res.errors?.length || !raw) {
809
+ console.warn(
810
+ "[WebSDK] exploreCatalog unavailable \u2014 using the built-in fallback catalog",
811
+ res.errors?.[0]?.message
812
+ );
813
+ setPhase((prev) => prev === "loading" ? "ready" : prev);
814
+ return;
815
+ }
816
+ const next = normalizeCatalog(raw, fallbackCatalog);
817
+ setCatalog(next);
818
+ catalogRef.current = next;
819
+ setPhase((prev) => {
820
+ if (!next.enabled) return "disabled";
821
+ return prev === "loading" ? "ready" : prev;
822
+ });
823
+ };
824
+ void load();
825
+ return () => {
826
+ cancelled = true;
827
+ };
828
+ }, [client, productSlug, fallbackCatalog]);
829
+ const startPolling = useCallback(
830
+ (conversationToken, messageId) => {
831
+ pollGenerationRef.current += 1;
832
+ const generation = pollGenerationRef.current;
833
+ const startedAt = Date.now();
834
+ let consecutiveFailures = 0;
835
+ const isStale = () => !mountedRef.current || generation !== pollGenerationRef.current;
836
+ const finishWithError = (chatError) => {
837
+ inFlightRef.current = false;
838
+ setMessages(
839
+ (prev) => prev.flatMap((m) => {
840
+ if (m.id !== messageId) return [m];
841
+ const text = visibleText(m);
842
+ if (!text) return [];
843
+ return [{ ...m, status: "FAILED", content: text }];
844
+ })
845
+ );
846
+ setError(chatError);
847
+ setPhase(chatError.kind === "rate-limit" ? "limited" : "error");
848
+ };
849
+ const tick = async () => {
850
+ if (isStale()) return;
851
+ if (Date.now() - startedAt > pollTimeoutMs) {
852
+ finishWithError(classifyExploreError("TIMEOUT"));
853
+ return;
854
+ }
855
+ const res = await client.query(
856
+ EXPLORE_MESSAGE_QUERY,
857
+ { conversationToken, id: messageId },
858
+ { cache: false, timeoutMs: POLL_REQUEST_TIMEOUT_MS }
859
+ );
860
+ if (isStale()) return;
861
+ const first = res.errors?.[0];
862
+ if (first) {
863
+ const code = typeof first.extensions?.code === "string" ? first.extensions.code : void 0;
864
+ const classified = classifyExploreError(code, first.message);
865
+ if (!classified.retryable) {
866
+ finishWithError(classified);
867
+ return;
868
+ }
869
+ consecutiveFailures += 1;
870
+ if (consecutiveFailures >= MAX_CONSECUTIVE_POLL_FAILURES) {
871
+ finishWithError(classified);
872
+ return;
873
+ }
874
+ pollTimerRef.current = setTimeout(() => void tick(), pollIntervalMs);
875
+ return;
876
+ }
877
+ const message = res.data?.exploreMessage;
878
+ if (!message) {
879
+ consecutiveFailures += 1;
880
+ if (consecutiveFailures >= MAX_CONSECUTIVE_POLL_FAILURES) {
881
+ finishWithError(classifyExploreError("NOT_FOUND"));
882
+ return;
883
+ }
884
+ pollTimerRef.current = setTimeout(() => void tick(), pollIntervalMs);
885
+ return;
886
+ }
887
+ consecutiveFailures = 0;
888
+ setMessages(
889
+ (prev) => prev.map((m) => m.id === messageId ? message : m)
890
+ );
891
+ if (message.status === "COMPLETED") {
892
+ inFlightRef.current = false;
893
+ setError(null);
894
+ setPhase("ready");
895
+ return;
896
+ }
897
+ if (message.status === "FAILED") {
898
+ finishWithError(
899
+ classifyExploreError(message.errorCode ?? "UPSTREAM_UNAVAILABLE")
900
+ );
901
+ return;
902
+ }
903
+ setPhase("streaming");
904
+ pollTimerRef.current = setTimeout(() => void tick(), pollIntervalMs);
905
+ };
906
+ pollTimerRef.current = setTimeout(() => void tick(), pollIntervalMs);
907
+ },
908
+ [client, pollIntervalMs, pollTimeoutMs]
909
+ );
910
+ const submit = useCallback(
911
+ async (text, optimisticId, captchaAttempt) => {
912
+ const activeCatalog = catalogRef.current;
913
+ let recaptchaToken;
914
+ if (activeCatalog.captchaRequired && activeCatalog.recaptchaSiteKey) {
915
+ try {
916
+ recaptchaToken = await getRecaptchaV3Token(
917
+ activeCatalog.recaptchaSiteKey
918
+ );
919
+ } catch (err) {
920
+ console.warn("[WebSDK] reCAPTCHA v3 token could not be minted", err);
921
+ }
922
+ }
923
+ const input = {
924
+ message: text,
925
+ ...conversationTokenRef.current ? { conversationToken: conversationTokenRef.current } : {},
926
+ ...focusProductRef.current || productSlug ? { productSlug: focusProductRef.current ?? productSlug } : {},
927
+ ...recaptchaToken ? { recaptchaToken } : {},
928
+ ...locale ? { locale } : {},
929
+ ...pageUrl ? { pageUrl } : {}
930
+ };
931
+ const res = await client.mutate(
932
+ SEND_EXPLORE_MESSAGE_MUTATION,
933
+ { input },
934
+ { timeoutMs: SEND_REQUEST_TIMEOUT_MS }
935
+ );
936
+ if (!mountedRef.current) return;
937
+ const first = res.errors?.[0];
938
+ const result = res.data?.sendExploreMessage;
939
+ if (first || !result) {
940
+ const code = typeof first?.extensions?.code === "string" ? first.extensions.code : void 0;
941
+ const classified = classifyExploreError(code, first?.message);
942
+ if (classified.kind === "captcha" && captchaAttempt === 0) {
943
+ await submit(text, optimisticId, 1);
944
+ return;
945
+ }
946
+ inFlightRef.current = false;
947
+ setError(classified);
948
+ setPhase(classified.kind === "rate-limit" ? "limited" : "error");
949
+ return;
950
+ }
951
+ conversationTokenRef.current = result.conversation.token;
952
+ turnCountRef.current = result.conversation.turnCount;
953
+ setTurnCount(result.conversation.turnCount);
954
+ setRemainingToday(result.remainingToday ?? null);
955
+ const userMessage = result.userMessage;
956
+ const assistantMessage = result.assistantMessage;
957
+ setMessages((prev) => {
958
+ const replaced = prev.some((m) => m.id === optimisticId) ? prev.map((m) => m.id === optimisticId ? userMessage : m) : [...prev, userMessage];
959
+ return [...replaced, assistantMessage];
960
+ });
961
+ if (assistantMessage.status === "COMPLETED" || assistantMessage.status === "FAILED") {
962
+ inFlightRef.current = false;
963
+ if (assistantMessage.status === "FAILED") {
964
+ const classified = classifyExploreError(
965
+ assistantMessage.errorCode ?? "UPSTREAM_UNAVAILABLE"
966
+ );
967
+ setError(classified);
968
+ setPhase("error");
969
+ } else {
970
+ setPhase("ready");
971
+ }
972
+ return;
973
+ }
974
+ setPhase("streaming");
975
+ startPolling(result.conversation.token, assistantMessage.id);
976
+ },
977
+ [client, locale, pageUrl, productSlug, startPolling]
978
+ );
979
+ const send = useCallback(
980
+ async (message) => {
981
+ const text = message.trim();
982
+ if (!text) return;
983
+ if (inFlightRef.current) return;
984
+ const activeCatalog = catalogRef.current;
985
+ if (!activeCatalog.enabled) {
986
+ setError(classifyExploreError("EXPLORE_DISABLED"));
987
+ setPhase("disabled");
988
+ return;
989
+ }
990
+ if (text.length > activeCatalog.limits.maxMessageLength) {
991
+ setError({
992
+ kind: "validation",
993
+ code: "MESSAGE_TOO_LONG",
994
+ message: `That message is ${text.length} characters \u2014 the limit is ${activeCatalog.limits.maxMessageLength}.`,
995
+ retryable: false
996
+ });
997
+ return;
998
+ }
999
+ if (turnCountRef.current >= activeCatalog.limits.maxTurnsPerConversation) {
1000
+ setError({
1001
+ kind: "validation",
1002
+ code: "CONVERSATION_LIMIT",
1003
+ message: `This conversation has reached its ${activeCatalog.limits.maxTurnsPerConversation}-message limit. Start a new chat to keep going.`,
1004
+ retryable: false
1005
+ });
1006
+ return;
1007
+ }
1008
+ inFlightRef.current = true;
1009
+ lastSentTextRef.current = text;
1010
+ setError(null);
1011
+ setPhase("sending");
1012
+ cancelPolling();
1013
+ const optimistic = {
1014
+ id: makeOptimisticId(),
1015
+ conversationId: conversationTokenRef.current ?? "pending",
1016
+ role: "USER",
1017
+ status: "COMPLETED",
1018
+ content: text,
1019
+ partialContent: null,
1020
+ activity: [],
1021
+ references: [],
1022
+ ctas: [],
1023
+ errorCode: null,
1024
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1025
+ completedAt: (/* @__PURE__ */ new Date()).toISOString()
1026
+ };
1027
+ setMessages((prev) => [...prev, optimistic]);
1028
+ turnCountRef.current += 1;
1029
+ setTurnCount(turnCountRef.current);
1030
+ onSend?.(text);
1031
+ try {
1032
+ await submit(text, optimistic.id, 0);
1033
+ } catch (err) {
1034
+ if (!mountedRef.current) return;
1035
+ console.error("[WebSDK] Explore send failed", err);
1036
+ inFlightRef.current = false;
1037
+ setError(classifyExploreError("NETWORK_ERROR"));
1038
+ setPhase("error");
1039
+ }
1040
+ },
1041
+ [cancelPolling, onSend, submit]
1042
+ );
1043
+ const stop = useCallback(() => {
1044
+ cancelPolling();
1045
+ inFlightRef.current = false;
1046
+ setMessages(
1047
+ (prev) => prev.flatMap((m) => {
1048
+ if (m.role !== "ASSISTANT") return [m];
1049
+ if (m.status !== "PENDING" && m.status !== "RUNNING") return [m];
1050
+ const text = visibleText(m);
1051
+ if (!text) return [];
1052
+ return [
1053
+ {
1054
+ ...m,
1055
+ status: "COMPLETED",
1056
+ content: text,
1057
+ completedAt: (/* @__PURE__ */ new Date()).toISOString()
1058
+ }
1059
+ ];
1060
+ })
1061
+ );
1062
+ setPhase(
1063
+ (prev) => prev === "sending" || prev === "streaming" ? "ready" : prev
1064
+ );
1065
+ }, [cancelPolling]);
1066
+ const retry = useCallback(() => {
1067
+ const text = lastSentTextRef.current;
1068
+ if (!text) return;
1069
+ cancelPolling();
1070
+ inFlightRef.current = false;
1071
+ setMessages((prev) => {
1072
+ const next = [...prev];
1073
+ const last = next[next.length - 1];
1074
+ if (last?.role === "ASSISTANT" && last.status === "FAILED") next.pop();
1075
+ const prior = next[next.length - 1];
1076
+ if (prior?.role === "USER" && prior.content === text) next.pop();
1077
+ return next;
1078
+ });
1079
+ turnCountRef.current = Math.max(0, turnCountRef.current - 1);
1080
+ setTurnCount(turnCountRef.current);
1081
+ void send(text);
1082
+ }, [cancelPolling, send]);
1083
+ const reset = useCallback(() => {
1084
+ cancelPolling();
1085
+ inFlightRef.current = false;
1086
+ conversationTokenRef.current = null;
1087
+ lastSentTextRef.current = null;
1088
+ turnCountRef.current = 0;
1089
+ setTurnCount(0);
1090
+ setMessages([]);
1091
+ setError(null);
1092
+ setRemainingToday(null);
1093
+ setPhase(catalogRef.current.enabled ? "ready" : "disabled");
1094
+ if (typeof window !== "undefined") {
1095
+ try {
1096
+ window.sessionStorage.removeItem(storageKey);
1097
+ } catch {
1098
+ }
1099
+ }
1100
+ }, [cancelPolling, storageKey]);
1101
+ const setFocusProduct = useCallback((slug) => {
1102
+ focusProductRef.current = slug;
1103
+ setFocusProductState(slug);
1104
+ }, []);
1105
+ const activity = useMemo(() => {
1106
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
1107
+ const m = messages[i];
1108
+ if (!m || m.role !== "ASSISTANT") continue;
1109
+ if (m.status !== "PENDING" && m.status !== "RUNNING") return null;
1110
+ const lines = m.activity ?? [];
1111
+ return lines.length ? lines[lines.length - 1] ?? null : null;
1112
+ }
1113
+ return null;
1114
+ }, [messages]);
1115
+ const canSend = (phase === "ready" || phase === "error") && catalog.enabled && turnCount < catalog.limits.maxTurnsPerConversation;
1116
+ return {
1117
+ phase,
1118
+ catalog,
1119
+ messages,
1120
+ activity,
1121
+ remainingToday,
1122
+ error,
1123
+ focusProduct,
1124
+ setFocusProduct,
1125
+ send,
1126
+ stop,
1127
+ retry,
1128
+ reset,
1129
+ canSend
1130
+ };
1131
+ }
1132
+ var optimisticCounter = 0;
1133
+ function makeOptimisticId() {
1134
+ optimisticCounter += 1;
1135
+ return `boff-explore-local-${Date.now()}-${optimisticCounter}`;
1136
+ }
1137
+
1138
+ export { DEFAULT_EXPLORE_EXAMPLE_PROMPTS, FALLBACK_EXPLORE_LIMITS, classifyExploreError, useExploreChat };
1139
+ //# sourceMappingURL=index.mjs.map
1140
+ //# sourceMappingURL=index.mjs.map