@inkeep/agents-ui 0.15.19 → 0.15.21

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.
@@ -1,108 +1,118 @@
1
1
  "use client";
2
- import { useChat as Pe } from "@ai-sdk/react";
3
- import { DefaultChatTransport as He } from "ai";
4
- import { useRef as l, useEffect as q, useState as C, useMemo as pe, useCallback as E, useImperativeHandle as Le } from "react";
5
- import { useModal as Ue } from "../modal/modal-provider.js";
6
- import { useOptionalChatBubble as $e } from "../../providers/chat-bubble-provider.js";
7
- import { useOptionalSidebarChat as ze } from "../../providers/sidebar-chat-provider.js";
8
- import { useInkeepConfig as We } from "../../providers/config-provider.js";
9
- import { useCaptcha as qe } from "./use-captcha.js";
10
- import { useMediaQuery as Ke } from "../../hooks/use-media-query.js";
11
- import { useAnonymousSession as Je } from "../../hooks/use-anonymous-session.js";
12
- import { useConversationLoader as je } from "../../hooks/use-conversation-loader.js";
13
- import { generateUid as k } from "../../utils/generate-uid.js";
14
- import { useBaseEvents as Ge } from "../../providers/base-events-provider.js";
15
- import { useChatForm as Qe } from "../../providers/chat-form-provider.js";
16
- import { useWidget as Ve } from "../../providers/widget-provider.js";
17
- import { useControllableState as Ze } from "@radix-ui/react-use-controllable-state";
18
- import { useStreamingEvents as Xe } from "../../hooks/use-streaming-events.js";
19
- import { parseAuthError as Ye } from "../../hooks/use-inkeep-api-client.js";
20
- function et(f) {
21
- const u = f.message ?? "";
22
- let t = Number(f.code) || Number(f.statusCode);
2
+ import { useChat as Je } from "@ai-sdk/react";
3
+ import { DefaultChatTransport as Ke } from "ai";
4
+ import { useRef as c, useEffect as O, useState as A, useMemo as Ce, useCallback as _, useImperativeHandle as je } from "react";
5
+ import { useModal as Ge } from "../modal/modal-provider.js";
6
+ import { useOptionalChatBubble as Qe } from "../../providers/chat-bubble-provider.js";
7
+ import { useOptionalSidebarChat as Ve } from "../../providers/sidebar-chat-provider.js";
8
+ import { useInkeepConfig as Ze } from "../../providers/config-provider.js";
9
+ import { useCaptcha as Xe } from "./use-captcha.js";
10
+ import { useMediaQuery as Ye } from "../../hooks/use-media-query.js";
11
+ import { useAnonymousSession as et } from "../../hooks/use-anonymous-session.js";
12
+ import { useAuthToken as tt } from "../../hooks/use-auth-token.js";
13
+ import { useConversationLoader as st } from "../../hooks/use-conversation-loader.js";
14
+ import { generateUid as F } from "../../utils/generate-uid.js";
15
+ import { useBaseEvents as rt } from "../../providers/base-events-provider.js";
16
+ import { useChatForm as nt } from "../../providers/chat-form-provider.js";
17
+ import { useWidget as ot } from "../../providers/widget-provider.js";
18
+ import { useControllableState as at } from "@radix-ui/react-use-controllable-state";
19
+ import { useStreamingEvents as it } from "../../hooks/use-streaming-events.js";
20
+ import { parseAuthError as ct } from "../../hooks/use-inkeep-api-client.js";
21
+ function ut(m) {
22
+ const f = m.message ?? "";
23
+ let t = Number(m.code) || Number(m.statusCode);
23
24
  if (Number.isNaN(t))
24
25
  try {
25
- t = Number(JSON.parse(u).status);
26
+ t = Number(JSON.parse(f).status);
26
27
  } catch {
27
28
  }
28
- const p = Ye(t, { detail: u });
29
- return p !== null ? p : t === 401 ? "session" : null;
29
+ const l = ct(t, { detail: f });
30
+ return l !== null ? l : t === 401 ? "session" : null;
30
31
  }
31
- const me = `Hmm..
32
+ const Z = `Hmm..
32
33
 
33
- It seems I might be having some issues right now. Please clear the chat and try again.`, bt = () => {
34
- const { baseSettings: f, aiChatSettings: u } = We(), [t = "", p] = Ze({
35
- prop: u.conversationId,
36
- defaultProp: u.conversationId ?? ""
37
- }), de = Ue(), fe = $e(), ge = ze(), { logEvent: m } = Ge(), { setConversationId: he, emitToParent: S } = Xe(), K = l(t);
38
- q(() => {
39
- const e = K.current;
40
- K.current = t, e !== t && m({
34
+ It seems I might be having some issues right now. Please clear the chat and try again.`, xt = () => {
35
+ const { baseSettings: m, aiChatSettings: f } = Ze(), [t = "", l] = at({
36
+ prop: f.conversationId,
37
+ defaultProp: f.conversationId ?? ""
38
+ }), Se = Ge(), ke = Qe(), Ae = Ve(), { logEvent: h } = rt(), { setConversationId: Ie, emitToParent: I } = it(), X = c(t);
39
+ O(() => {
40
+ const e = X.current;
41
+ X.current = t, e !== t && h({
41
42
  eventName: "chat_conversation_changed",
42
43
  properties: {
43
44
  conversationId: t,
44
45
  previousConversationId: e
45
46
  }
46
47
  });
47
- }, [t, m]);
48
- const [v, N] = C(""), ve = (e) => N(e.target.value), { shouldBypassCaptcha: J, filters: j, privacyPreferences: ye } = f, {
49
- onInputMessageChange: be,
50
- filters: G,
51
- baseUrl: I,
52
- agentUrl: Ce,
53
- context: Q,
54
- headers: V,
55
- appId: y,
56
- apiKey: d
57
- } = u, Se = de?.isOpen ?? fe?.isOpen ?? ge?.isOpen ?? !0, { getCaptchaHeader: b, invalidate: c } = qe({
58
- baseUrl: I,
59
- shouldBypassCaptcha: J || !!d,
60
- shouldMakeInitialRequest: Se
61
- }), Z = l(b);
62
- Z.current = b;
63
- const X = Ce || `${I}/run/api/chat`, { sessionToken: T, refreshSession: _ } = Je({
64
- baseUrl: I,
65
- appId: y,
66
- getCaptchaHeader: b,
67
- invalidateCaptcha: c,
68
- optOutAllAnalytics: ye?.optOutAllAnalytics
69
- }), { loadConversation: Y } = je({
70
- baseUrl: I,
71
- appId: y,
72
- authToken: d ?? T,
73
- getCaptchaHeader: b,
74
- invalidateCaptcha: c,
75
- // Only pass refreshSession for anonymous-session flows; API key auth has no token to refresh.
76
- refreshSession: d ? void 0 : _
77
- }), [Ie, ee] = C(!1), w = l(null);
78
- w.current = T;
79
- const g = l(0), te = l(null), O = l(null), se = l(V);
80
- se.current = V;
81
- const F = l(void 0);
82
- F.current = j || G ? JSON.stringify({ ...j, ...G }) : void 0;
83
- const we = (e) => {
48
+ }, [t, h]);
49
+ const [y, w] = A(""), we = (e) => w(e.target.value), { shouldBypassCaptcha: Y, filters: ee, privacyPreferences: Re, userProperties: P } = m, { authToken: R, refreshToken: te } = tt(), se = !!m.getAuthToken, p = !!R, {
50
+ onInputMessageChange: Te,
51
+ filters: re,
52
+ baseUrl: T,
53
+ agentUrl: Me,
54
+ context: ne,
55
+ headers: oe,
56
+ appId: b,
57
+ apiKey: g
58
+ } = f, xe = Se?.isOpen ?? ke?.isOpen ?? Ae?.isOpen ?? !0, { getCaptchaHeader: C, invalidate: u } = Xe({
59
+ baseUrl: T,
60
+ shouldBypassCaptcha: Y || !!g,
61
+ shouldMakeInitialRequest: xe
62
+ }), ae = c(C);
63
+ ae.current = C;
64
+ const ie = Me || `${T}/run/api/chat`, { sessionToken: D, refreshSession: B } = et({
65
+ baseUrl: T,
66
+ appId: b,
67
+ getCaptchaHeader: C,
68
+ invalidateCaptcha: u,
69
+ optOutAllAnalytics: Re?.optOutAllAnalytics,
70
+ enabled: !p
71
+ }), { loadConversation: ce } = st({
72
+ baseUrl: T,
73
+ appId: b,
74
+ authToken: g ?? (p ? R : D),
75
+ getCaptchaHeader: C,
76
+ invalidateCaptcha: u,
77
+ refreshSession: g || p ? void 0 : B
78
+ }), [Ee, ue] = A(!1), H = c(null);
79
+ H.current = D;
80
+ const L = c(null);
81
+ L.current = R;
82
+ const U = c(void 0);
83
+ U.current = P && Object.keys(P).length > 0 ? JSON.stringify(P) : void 0;
84
+ const v = c(0), le = c(null), W = c(null), pe = c(oe);
85
+ pe.current = oe;
86
+ const $ = c(void 0);
87
+ $.current = ee || re ? JSON.stringify({ ...ee, ...re }) : void 0;
88
+ const Ne = (e) => {
84
89
  switch (e.code) {
85
90
  case 400:
86
91
  return e.message;
92
+ case 401:
93
+ return se ? "Authentication failed. Please try again." : Z;
87
94
  case 403:
88
- return `There seems to be a configuration error. Please contact ${f.organizationDisplayName ?? "Administrator"}`;
95
+ return `There seems to be a configuration error. Please contact ${m.organizationDisplayName ?? "Administrator"}`;
89
96
  default:
90
- return me;
97
+ return Z;
91
98
  }
92
- }, [Ae, A] = C([]), [Re, B] = C(null), Me = pe(
93
- () => new He({
94
- api: X,
95
- headers: () => ({
96
- "x-inkeep-client-timezone": Intl.DateTimeFormat().resolvedOptions().timeZone,
97
- "x-inkeep-client-timestamp": (/* @__PURE__ */ new Date()).toISOString(),
98
- ...y ? { "x-inkeep-app-id": y } : {},
99
- ...w.current ? { Authorization: `Bearer ${w.current}` } : {},
100
- ...d ? { Authorization: `Bearer ${d}` } : {},
101
- ...F.current ? { "inkeep-filters": F.current } : {},
102
- ...se.current
103
- }),
99
+ }, [Oe, S] = A([]), [_e, M] = A(null), Fe = Ce(
100
+ () => new Ke({
101
+ api: ie,
102
+ headers: () => {
103
+ const e = g ?? L.current ?? H.current;
104
+ return {
105
+ "x-inkeep-client-timezone": Intl.DateTimeFormat().resolvedOptions().timeZone,
106
+ "x-inkeep-client-timestamp": (/* @__PURE__ */ new Date()).toISOString(),
107
+ ...b ? { "x-inkeep-app-id": b } : {},
108
+ ...e ? { Authorization: `Bearer ${e}` } : {},
109
+ ...$.current ? { "inkeep-filters": $.current } : {},
110
+ ...U.current ? { "x-inkeep-user-properties": U.current } : {},
111
+ ...pe.current
112
+ };
113
+ },
104
114
  prepareSendMessagesRequest: async (e) => {
105
- const s = await Z.current();
115
+ const s = await ae.current();
106
116
  return {
107
117
  body: {
108
118
  ...e.body,
@@ -118,30 +128,30 @@ It seems I might be having some issues right now. Please clear the chat and try
118
128
  };
119
129
  },
120
130
  body: {
121
- requestContext: Q
131
+ requestContext: ne
122
132
  }
123
133
  }),
124
- [X, Q, y, d]
134
+ [ie, ne, b, g]
125
135
  ), {
126
- messages: R,
127
- sendMessage: D,
128
- addToolApprovalResponse: P,
129
- status: re,
130
- setMessages: h,
131
- stop: ne,
132
- error: H
133
- } = Pe({
134
- transport: Me,
136
+ messages: x,
137
+ sendMessage: q,
138
+ addToolApprovalResponse: z,
139
+ status: de,
140
+ setMessages: d,
141
+ stop: E,
142
+ error: J
143
+ } = Je({
144
+ transport: Fe,
135
145
  onData(e) {
136
- S(e.type, e.data);
146
+ I(e.type, e.data);
137
147
  },
138
148
  async onFinish() {
139
- S("completion", { conversationId: t }), await m({
149
+ I("completion", { conversationId: t }), await h({
140
150
  eventName: "assistant_message_received",
141
151
  properties: {
142
152
  conversationId: t
143
153
  }
144
- }), m({
154
+ }), h({
145
155
  eventName: "assistant_answer_displayed",
146
156
  properties: {
147
157
  conversationId: t
@@ -150,178 +160,187 @@ It seems I might be having some issues right now. Please clear the chat and try
150
160
  },
151
161
  onError(e) {
152
162
  console.error("onError", { code: e.code, message: e.message });
153
- const s = J || d ? null : et(e);
154
- if (s !== null && g.current < 1) {
155
- g.current++;
156
- const n = O.current, r = te.current;
163
+ const s = Y || g ? null : ut(e);
164
+ if (s !== null && v.current < 1) {
165
+ v.current++;
166
+ const o = W.current, n = le.current;
157
167
  (async () => {
158
- if (s === "session") {
159
- const i = await _();
160
- i && (w.current = i);
168
+ if (s === "session" && se) {
169
+ const r = await te();
170
+ if (!r) throw new Error("Auth token refresh failed");
171
+ L.current = r;
172
+ } else if (s === "session") {
173
+ const r = await B();
174
+ r && (H.current = r);
161
175
  } else
162
- c();
163
- if (n) {
164
- P(n);
176
+ u();
177
+ if (o) {
178
+ z(o);
165
179
  return;
166
180
  }
167
- r && (h((i) => {
168
- let a = [...i];
169
- return a.at(-1)?.role === "assistant" && (a = a.slice(0, -1)), a.at(-1)?.role === "user" && (a = a.slice(0, -1)), a;
170
- }), D({ text: r.content }, { body: r.body }));
181
+ n && (d((r) => {
182
+ let i = [...r];
183
+ return i.at(-1)?.role === "assistant" && (i = i.slice(0, -1)), i.at(-1)?.role === "user" && (i = i.slice(0, -1)), i;
184
+ }), q({ text: n.content }, { body: n.body }));
171
185
  })().catch(() => {
172
- g.current = 0, c(), h((i) => {
173
- const a = [...i], W = a[a.length - 1];
174
- if (!W) return a;
175
- const ue = me;
176
- return W.role === "user" ? a.push({
177
- id: k(16),
186
+ v.current = 0, u(), d((r) => {
187
+ const i = [...r], V = i[i.length - 1];
188
+ if (!V) return i;
189
+ const be = Z;
190
+ return V.role === "user" ? i.push({
191
+ id: F(16),
178
192
  role: "assistant",
179
- parts: [{ type: "text", text: ue }]
180
- }) : W.parts = [{ type: "text", text: ue }], a;
193
+ parts: [{ type: "text", text: be }]
194
+ }) : V.parts = [{ type: "text", text: be }], i;
181
195
  });
182
196
  });
183
197
  return;
184
198
  }
185
- g.current = 0, s !== null && c(), m({
199
+ v.current = 0, s !== null && u(), h({
186
200
  eventName: "chat_error",
187
201
  properties: {
188
202
  conversationId: t,
189
203
  error: e.message
190
204
  }
191
- }), h((n) => {
192
- const r = [...n], o = r[r.length - 1];
193
- if (o) {
194
- const i = we(e);
195
- o.role === "user" ? r.push({
196
- id: k(16),
205
+ }), d((o) => {
206
+ const n = [...o], a = n[n.length - 1];
207
+ if (a) {
208
+ const r = Ne(e);
209
+ a.role === "user" ? n.push({
210
+ id: F(16),
197
211
  role: "assistant",
198
- parts: [{ type: "text", text: i }]
199
- }) : o.parts = [{ type: "text", text: i }];
212
+ parts: [{ type: "text", text: r }]
213
+ }) : a.parts = [{ type: "text", text: r }];
200
214
  }
201
- return r;
215
+ return n;
202
216
  });
203
217
  }
204
- }), oe = re === "submitted", L = re === "streaming", xe = pe(() => {
205
- const e = (o) => {
206
- if (!o || typeof o != "object") return !1;
207
- const i = o;
208
- return typeof i.type == "string" && i.type.startsWith("tool-");
209
- }, n = [...R ?? []].reverse().find((o) => o.role === "assistant");
210
- if (!n) return !1;
211
- const r = n.parts?.at(-1);
212
- return !(!e(r) || r.state !== "output-available" || !r.approval?.id || L);
213
- }, [R, L]), ae = L || xe, ie = oe || ae, Ee = R.length === 0, U = !v.trim() || ie, ke = Ke("(max-width: 768px)"), [Ne, M] = C(null);
214
- q(() => {
215
- H && M(H);
216
- }, [H]);
217
- const Te = () => M(null), ce = l(null);
218
- q(() => {
219
- be?.(v);
220
- }, [v]);
221
- const _e = (e) => {
222
- e.key === "Enter" && !e.shiftKey && !U && !e.nativeEvent.isComposing && (e.preventDefault(), $());
223
- }, $ = async (e = v) => {
224
- if (U && (!e || e.trim().length === 0)) return;
225
- A([]), N(""), g.current = 0, O.current = null, await m({
218
+ }), me = c(p);
219
+ O(() => {
220
+ const e = me.current;
221
+ me.current = p, e !== p && (E(), k(null), d([]), l(""), w(""), S([]), M(null), u());
222
+ }, [p, E, d, l, u]);
223
+ const fe = de === "submitted", K = de === "streaming", Pe = Ce(() => {
224
+ const e = (a) => {
225
+ if (!a || typeof a != "object") return !1;
226
+ const r = a;
227
+ return typeof r.type == "string" && r.type.startsWith("tool-");
228
+ }, o = [...x ?? []].reverse().find((a) => a.role === "assistant");
229
+ if (!o) return !1;
230
+ const n = o.parts?.at(-1);
231
+ return !(!e(n) || n.state !== "output-available" || !n.approval?.id || K);
232
+ }, [x, K]), he = K || Pe, ge = fe || he, De = x.length === 0, j = !y.trim() || ge, Be = Ye("(max-width: 768px)"), [He, k] = A(null);
233
+ O(() => {
234
+ J && k(J);
235
+ }, [J]);
236
+ const Le = () => k(null), ve = c(null);
237
+ O(() => {
238
+ Te?.(y);
239
+ }, [y]);
240
+ const Ue = (e) => {
241
+ e.key === "Enter" && !e.shiftKey && !j && !e.nativeEvent.isComposing && (e.preventDefault(), G());
242
+ }, G = async (e = y) => {
243
+ if (j && (!e || e.trim().length === 0)) return;
244
+ S([]), w(""), v.current = 0, W.current = null, await h({
226
245
  eventName: "user_message_submitted",
227
246
  properties: {
228
247
  conversationId: t
229
248
  }
230
249
  });
231
250
  let s = t;
232
- s || (s = `conv_${k(16)}`, p(s)), he(s), te.current = {
251
+ s || (s = `conv_${F(16)}`, l(s)), Ie(s), le.current = {
233
252
  content: e,
234
253
  body: { conversationId: s }
235
- }, D(
254
+ }, q(
236
255
  { text: e },
237
256
  {
238
257
  body: { conversationId: s }
239
258
  }
240
259
  );
241
- }, Oe = E(
260
+ }, We = _(
242
261
  (e) => {
243
- g.current = 0, O.current = e, P(e);
262
+ v.current = 0, W.current = e, z(e);
244
263
  },
245
- [P]
246
- ), z = E(() => {
247
- ne().then(() => {
248
- S("aborted", { conversationId: t });
264
+ [z]
265
+ ), Q = _(() => {
266
+ E().then(() => {
267
+ I("aborted", { conversationId: t });
249
268
  });
250
- }, [ne, t, S]), le = () => {
251
- Te(), h([]), p(""), A([]), B(null), c(), m({
269
+ }, [E, t, I]), ye = () => {
270
+ Le(), d([]), l(""), S([]), M(null), u(), h({
252
271
  eventName: "chat_clear_button_clicked",
253
272
  properties: {
254
273
  conversationId: t
255
274
  }
256
275
  });
257
- }, x = E(
276
+ }, N = _(
258
277
  (e, s) => {
259
- M(null), h(s), p(e), A([]), B(null), c();
278
+ k(null), d(s), l(e), S([]), M(null), u();
260
279
  },
261
- [h, p, c]
262
- ), Fe = E(
280
+ [d, l, u]
281
+ ), $e = _(
263
282
  async (e, s) => {
264
- z(), x(e, []), ee(!0);
283
+ Q(), N(e, []), ue(!0);
265
284
  try {
266
- const n = await Y(e, s), r = n?.[n.length - 1], o = n !== null && r?.role === "user" ? [...n, {
267
- id: k(16),
285
+ const o = await ce(e, s), n = o?.[o.length - 1], a = o !== null && n?.role === "user" ? [...o, {
286
+ id: F(16),
268
287
  role: "assistant",
269
288
  parts: [{ type: "text", text: "This session was interrupted. Please check back in a few minutes or start a new conversation." }]
270
- }] : n;
271
- o !== null && x(e, o);
289
+ }] : o;
290
+ a !== null && N(e, a);
272
291
  } finally {
273
- s?.aborted || ee(!1);
292
+ s?.aborted || ue(!1);
274
293
  }
275
294
  },
276
- [x, Y, z]
277
- ), { openForm: Be } = Qe(), De = Ve();
278
- return Le(u.chatFunctionsRef, () => ({
279
- submitMessage: $,
295
+ [N, ce, Q]
296
+ ), { openForm: qe } = nt(), ze = ot();
297
+ return je(f.chatFunctionsRef, () => ({
298
+ submitMessage: G,
280
299
  updateInputMessage(e) {
281
- N(e);
300
+ w(e);
282
301
  },
283
- clearChat: le,
302
+ clearChat: ye,
284
303
  openForm: (e) => {
285
- De?.setView("chat"), Be(e, void 0);
304
+ ze?.setView("chat"), qe(e, void 0);
286
305
  },
287
306
  focusInput: () => {
288
- ce.current?.focus();
307
+ ve.current?.focus();
289
308
  }
290
309
  })), {
291
- messages: R,
292
- sendMessage: D,
293
- addToolApprovalResponse: Oe,
294
- isLoading: oe,
295
- isStreaming: ae,
296
- isBusy: ie,
297
- error: Ne,
298
- setError: M,
299
- isSubmitDisabled: U,
300
- input: v,
301
- handleInputChange: ve,
302
- handleInputKeyDown: _e,
303
- handleSubmit: $,
304
- stop: z,
305
- clear: le,
306
- inputRef: ce,
307
- isMobile: ke,
310
+ messages: x,
311
+ sendMessage: q,
312
+ addToolApprovalResponse: We,
313
+ isLoading: fe,
314
+ isStreaming: he,
315
+ isBusy: ge,
316
+ error: He,
317
+ setError: k,
318
+ isSubmitDisabled: j,
319
+ input: y,
320
+ handleInputChange: we,
321
+ handleInputKeyDown: Ue,
322
+ handleSubmit: G,
323
+ stop: Q,
324
+ clear: ye,
325
+ inputRef: ve,
326
+ isMobile: Be,
308
327
  // Additional state for attachments and workflow
309
- messageAttachments: Ae,
310
- setMessageAttachments: A,
311
- selectedWorkflow: Re,
312
- setSelectedWorkflow: B,
313
- isNewChat: Ee,
328
+ messageAttachments: Oe,
329
+ setMessageAttachments: S,
330
+ selectedWorkflow: _e,
331
+ setSelectedWorkflow: M,
332
+ isNewChat: De,
314
333
  conversationId: t,
315
- restoreSession: x,
316
- loadAndRestoreSession: Fe,
317
- isSessionLoading: Ie,
318
- sessionToken: T,
319
- refreshSession: _,
320
- getCaptchaHeader: b,
321
- invalidateCaptcha: c
334
+ restoreSession: N,
335
+ loadAndRestoreSession: $e,
336
+ isSessionLoading: Ee,
337
+ sessionToken: p ? R : D,
338
+ refreshSession: p ? te : B,
339
+ getCaptchaHeader: C,
340
+ invalidateCaptcha: u
322
341
  };
323
342
  };
324
343
  export {
325
- me as DEFAULT_ERROR_MESSAGE,
326
- bt as useInkeepChat
344
+ Z as DEFAULT_ERROR_MESSAGE,
345
+ xt as useInkeepChat
327
346
  };
@@ -1 +1 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react"),b=require("./use-local-storage.cjs"),_=require("./use-inkeep-api-client.cjs"),M=30*1e3,$=2147483647,D=()=>{},F=async()=>({});function C(n){return new Date(n.expiresAt).getTime()-M<=Date.now()}const L=({baseUrl:n,appId:t,getCaptchaHeader:d,invalidateCaptcha:g,optOutAllAnalytics:p})=>{const w=t&&!p?`inkeep_session_${t}`:null,[u,R]=b.useLocalStorage(w),{fetchWithAuth:k}=_.useInkeepApiClient({appId:t,authToken:void 0,getCaptchaHeader:d??F,invalidateCaptcha:g??D}),l=e.useRef(n);l.current=n;const h=e.useRef(t);h.current=t;const c=e.useRef(u);c.current=u;const S=e.useRef(R);S.current=R;const T=e.useRef(k);T.current=k;const f=e.useRef(null),s=e.useCallback(async r=>{if(!l.current||!h.current)return null;if(!r&&f.current)return f.current;const o=`${l.current}/run/auth/apps/${h.current}/anonymous-session`,a=(async()=>{try{const i={"Content-Type":"application/json"},v=c.current?.token;v&&(i.Authorization=`Bearer ${v}`);const A=await T.current(o,{method:"POST",headers:i,signal:r});if(!A.ok)throw new Error(`Failed to fetch anonymous session: ${A.status}`);const y=await A.json();return S.current({token:y.token,expiresAt:y.expiresAt}),y.token}catch(i){return i instanceof Error&&i.name==="AbortError"||console.error("[anonymous-session] fetch failed",i),null}finally{r||(f.current=null)}})();return r||(f.current=a),a},[]),E=e.useRef(!1);e.useEffect(()=>{if(!n||!t)return;const r=!E.current;if(E.current=!0,!r&&c.current&&!C(c.current)||f.current)return;const o=new AbortController;return s(o.signal),()=>o.abort()},[n,t,s]),e.useEffect(()=>{if(!n||!t||!u?.expiresAt)return;const m=new Date(u.expiresAt).getTime()-M-Date.now();if(m<=0)return;const a=setTimeout(()=>s(),Math.min(m,$));return()=>clearTimeout(a)},[n,t,u?.expiresAt,s]),e.useEffect(()=>{if(!n||!t)return;const r=()=>{if(document.visibilityState!=="visible")return;const o=c.current;(!o||C(o))&&s()};return document.addEventListener("visibilitychange",r),()=>document.removeEventListener("visibilitychange",r)},[n,t,s]);const x=e.useCallback(()=>s(),[s]);return{sessionToken:u?.token??null,refreshSession:x}};exports.useAnonymousSession=L;
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react"),j=require("./use-local-storage.cjs"),p=require("./use-inkeep-api-client.cjs"),_=30*1e3,q=2147483647,P=()=>{},B=async()=>({});function x(s){return new Date(s.expiresAt).getTime()-_<=Date.now()}const W=({baseUrl:s,appId:t,getCaptchaHeader:$,invalidateCaptcha:D,optOutAllAnalytics:m,enabled:n=!0})=>{const F=n&&t&&!m?`inkeep_session_${t}`:null,[c,h]=j.useLocalStorage(F),E=e.useRef(n);e.useEffect(()=>{const r=E.current;if(E.current=n,r&&!n&&t&&!m){try{localStorage.removeItem(`inkeep_session_${t}`)}catch{}h(null)}},[n,t,m,h]);const{fetchWithAuth:v}=p.useInkeepApiClient({appId:t,authToken:void 0,getCaptchaHeader:$??B,invalidateCaptcha:D??P}),R=e.useRef(s);R.current=s;const y=e.useRef(t);y.current=t;const f=e.useRef(c);f.current=c;const T=e.useRef(h);T.current=h;const g=e.useRef(v);g.current=v;const a=e.useRef(null),w=e.useRef(n);w.current=n;const o=e.useCallback(async r=>{if(!w.current||!R.current||!y.current)return null;if(!r&&a.current)return a.current;const u=`${R.current}/run/auth/apps/${y.current}/anonymous-session`,l=(async()=>{try{const i={"Content-Type":"application/json"},M=f.current?.token;M&&(i.Authorization=`Bearer ${M}`);const A=await g.current(u,{method:"POST",headers:i,signal:r});if(!A.ok)throw new Error(`Failed to fetch anonymous session: ${A.status}`);const S=await A.json();return T.current({token:S.token,expiresAt:S.expiresAt}),S.token}catch(i){return i instanceof Error&&i.name==="AbortError"||console.error("[anonymous-session] fetch failed",i),null}finally{r||(a.current=null)}})();return r||(a.current=l),l},[]),C=e.useRef(!1);e.useEffect(()=>{if(!n||!s||!t)return;const r=!C.current;if(C.current=!0,!r&&f.current&&!x(f.current)||a.current)return;const u=new AbortController;return o(u.signal),()=>u.abort()},[s,t,n,o]),e.useEffect(()=>{if(!n||!s||!t||!c?.expiresAt)return;const k=new Date(c.expiresAt).getTime()-_-Date.now();if(k<=0)return;const l=setTimeout(()=>o(),Math.min(k,q));return()=>clearTimeout(l)},[s,t,n,c?.expiresAt,o]),e.useEffect(()=>{if(!n||!s||!t)return;const r=()=>{if(document.visibilityState!=="visible")return;const u=f.current;(!u||x(u))&&o()};return document.addEventListener("visibilitychange",r),()=>document.removeEventListener("visibilitychange",r)},[s,t,n,o]);const L=e.useCallback(()=>o(),[o]);return{sessionToken:c?.token??null,refreshSession:L}};exports.useAnonymousSession=W;
@@ -4,8 +4,9 @@ interface UseAnonymousSessionOptions {
4
4
  getCaptchaHeader?: () => Promise<Record<string, string>>;
5
5
  invalidateCaptcha?: () => void;
6
6
  optOutAllAnalytics?: boolean;
7
+ enabled?: boolean;
7
8
  }
8
- export declare const useAnonymousSession: ({ baseUrl, appId, getCaptchaHeader, invalidateCaptcha, optOutAllAnalytics, }: UseAnonymousSessionOptions) => {
9
+ export declare const useAnonymousSession: ({ baseUrl, appId, getCaptchaHeader, invalidateCaptcha, optOutAllAnalytics, enabled, }: UseAnonymousSessionOptions) => {
9
10
  sessionToken: string | null;
10
11
  refreshSession: () => Promise<string | null>;
11
12
  };