@cstar.help/js 0.1.0 → 0.1.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.
@@ -40,6 +40,14 @@ interface IdentifyResult {
40
40
  };
41
41
  sessionToken: string;
42
42
  expiresAt: string;
43
+ /** Team UUID — used for realtime token requests. */
44
+ teamId: string;
45
+ }
46
+ /** Response from the realtime-token endpoint. */
47
+ interface RealtimeTokenResponse {
48
+ token: string;
49
+ expiresAt: string;
50
+ refreshAt: string;
43
51
  }
44
52
  /** A customer conversation (maps to a ticket). */
45
53
  interface Conversation {
@@ -92,22 +100,38 @@ type TypingCallback = (payload: TypingPayload) => void;
92
100
  /**
93
101
  * Customer-facing chat client for the cStar widget API.
94
102
  *
103
+ * Supports real-time messages and typing indicators when `supabaseUrl`
104
+ * and `supabaseAnonKey` are provided and `@supabase/supabase-js` is installed.
105
+ * Falls back to polling otherwise.
106
+ *
95
107
  * ```typescript
96
- * const chat = new ChatClient({ teamSlug: 'acme' });
108
+ * const chat = new ChatClient({
109
+ * teamSlug: 'acme',
110
+ * supabaseUrl: 'https://xxx.supabase.co',
111
+ * supabaseAnonKey: 'eyJ...',
112
+ * });
97
113
  * await chat.identify(
98
114
  * { externalId: 'usr_123', email: 'jane@co.com', name: 'Jane', timestamp: Date.now() / 1000 },
99
115
  * 'hmac_signature_hex'
100
116
  * );
101
- * const { conversations } = await chat.conversations.list();
117
+ * chat.onMessage('tkt_abc', (msg) => console.log(msg));
118
+ * chat.onTyping('tkt_abc', ({ agent_name }) => console.log(agent_name, 'is typing'));
102
119
  * ```
103
120
  */
104
121
  declare class ChatClient {
105
122
  private readonly baseUrl;
106
123
  private readonly teamSlug;
107
124
  private readonly pollingInterval;
125
+ private readonly supabaseUrl?;
126
+ private readonly supabaseAnonKey?;
108
127
  private sessionToken;
109
128
  private teamId;
129
+ private customerId;
110
130
  private pollingTimers;
131
+ private realtimeManager;
132
+ private presenceManager;
133
+ private realtimeReady;
134
+ private realtimeInitPromise;
111
135
  /** Sub-resource for managing conversations. */
112
136
  readonly conversations: ConversationsApi;
113
137
  /** Sub-resource for managing messages. */
@@ -117,6 +141,9 @@ declare class ChatClient {
117
141
  * Identify a customer using HMAC signature verification.
118
142
  * Must be called before accessing conversations or messages.
119
143
  *
144
+ * If `supabaseUrl` and `supabaseAnonKey` were provided in the config,
145
+ * this will also initialize real-time subscriptions (non-blocking).
146
+ *
120
147
  * @param customer - Customer identity fields
121
148
  * @param signature - HMAC-SHA256 hex signature of the signed fields
122
149
  * @param testMode - Whether to use test mode (relaxed timestamp validation)
@@ -124,7 +151,7 @@ declare class ChatClient {
124
151
  identify(customer: IdentifyParams, signature: string, testMode?: boolean): Promise<IdentifyResult>;
125
152
  /**
126
153
  * Subscribe to new messages on a conversation.
127
- * Falls back to polling when Supabase Realtime is not available.
154
+ * Uses Supabase Realtime (Postgres Changes) when available, falls back to polling.
128
155
  *
129
156
  * @returns Unsubscribe function
130
157
  */
@@ -135,7 +162,12 @@ declare class ChatClient {
135
162
  *
136
163
  * @returns Unsubscribe function
137
164
  */
138
- onTyping(_ticketId: string, _callback: TypingCallback): () => void;
165
+ onTyping(ticketId: string, callback: TypingCallback): () => void;
166
+ /**
167
+ * Send a customer typing indicator (requires realtime).
168
+ * No-op if realtime is not available.
169
+ */
170
+ sendTyping(ticketId: string, isTyping: boolean): Promise<void>;
139
171
  /** Disconnect all subscriptions and clean up. */
140
172
  disconnect(): void;
141
173
  /** @internal Make an authenticated request to the widget API. */
@@ -148,6 +180,11 @@ declare class ChatClient {
148
180
  getTeamId(): string | null;
149
181
  /** @internal Set team ID from identify response or other source. */
150
182
  setTeamId(teamId: string): void;
183
+ /** @internal Wait for realtime to be initialized (for testing). */
184
+ waitForRealtime(): Promise<void>;
185
+ private initRealtime;
186
+ private fetchRealtimeToken;
187
+ private pollMessages;
151
188
  private buildUrl;
152
189
  }
153
190
  /** Conversations sub-resource on ChatClient. */
@@ -169,4 +206,4 @@ declare class MessagesApi {
169
206
  send(ticketId: string, content: string): Promise<WidgetMessage>;
170
207
  }
171
208
 
172
- export { ChatClient, type ChatConfig, type Conversation, type ConversationCreateParams, type ConversationListParams, type ConversationListResponse, type IdentifyParams, type IdentifyResult, type MessageCallback, type TypingCallback, type WidgetMessage };
209
+ export { ChatClient, type ChatConfig, type Conversation, type ConversationCreateParams, type ConversationListParams, type ConversationListResponse, type IdentifyParams, type IdentifyResult, type MessageCallback, type RealtimeTokenResponse, type TypingCallback, type TypingPayload, type WidgetMessage };
@@ -40,6 +40,14 @@ interface IdentifyResult {
40
40
  };
41
41
  sessionToken: string;
42
42
  expiresAt: string;
43
+ /** Team UUID — used for realtime token requests. */
44
+ teamId: string;
45
+ }
46
+ /** Response from the realtime-token endpoint. */
47
+ interface RealtimeTokenResponse {
48
+ token: string;
49
+ expiresAt: string;
50
+ refreshAt: string;
43
51
  }
44
52
  /** A customer conversation (maps to a ticket). */
45
53
  interface Conversation {
@@ -92,22 +100,38 @@ type TypingCallback = (payload: TypingPayload) => void;
92
100
  /**
93
101
  * Customer-facing chat client for the cStar widget API.
94
102
  *
103
+ * Supports real-time messages and typing indicators when `supabaseUrl`
104
+ * and `supabaseAnonKey` are provided and `@supabase/supabase-js` is installed.
105
+ * Falls back to polling otherwise.
106
+ *
95
107
  * ```typescript
96
- * const chat = new ChatClient({ teamSlug: 'acme' });
108
+ * const chat = new ChatClient({
109
+ * teamSlug: 'acme',
110
+ * supabaseUrl: 'https://xxx.supabase.co',
111
+ * supabaseAnonKey: 'eyJ...',
112
+ * });
97
113
  * await chat.identify(
98
114
  * { externalId: 'usr_123', email: 'jane@co.com', name: 'Jane', timestamp: Date.now() / 1000 },
99
115
  * 'hmac_signature_hex'
100
116
  * );
101
- * const { conversations } = await chat.conversations.list();
117
+ * chat.onMessage('tkt_abc', (msg) => console.log(msg));
118
+ * chat.onTyping('tkt_abc', ({ agent_name }) => console.log(agent_name, 'is typing'));
102
119
  * ```
103
120
  */
104
121
  declare class ChatClient {
105
122
  private readonly baseUrl;
106
123
  private readonly teamSlug;
107
124
  private readonly pollingInterval;
125
+ private readonly supabaseUrl?;
126
+ private readonly supabaseAnonKey?;
108
127
  private sessionToken;
109
128
  private teamId;
129
+ private customerId;
110
130
  private pollingTimers;
131
+ private realtimeManager;
132
+ private presenceManager;
133
+ private realtimeReady;
134
+ private realtimeInitPromise;
111
135
  /** Sub-resource for managing conversations. */
112
136
  readonly conversations: ConversationsApi;
113
137
  /** Sub-resource for managing messages. */
@@ -117,6 +141,9 @@ declare class ChatClient {
117
141
  * Identify a customer using HMAC signature verification.
118
142
  * Must be called before accessing conversations or messages.
119
143
  *
144
+ * If `supabaseUrl` and `supabaseAnonKey` were provided in the config,
145
+ * this will also initialize real-time subscriptions (non-blocking).
146
+ *
120
147
  * @param customer - Customer identity fields
121
148
  * @param signature - HMAC-SHA256 hex signature of the signed fields
122
149
  * @param testMode - Whether to use test mode (relaxed timestamp validation)
@@ -124,7 +151,7 @@ declare class ChatClient {
124
151
  identify(customer: IdentifyParams, signature: string, testMode?: boolean): Promise<IdentifyResult>;
125
152
  /**
126
153
  * Subscribe to new messages on a conversation.
127
- * Falls back to polling when Supabase Realtime is not available.
154
+ * Uses Supabase Realtime (Postgres Changes) when available, falls back to polling.
128
155
  *
129
156
  * @returns Unsubscribe function
130
157
  */
@@ -135,7 +162,12 @@ declare class ChatClient {
135
162
  *
136
163
  * @returns Unsubscribe function
137
164
  */
138
- onTyping(_ticketId: string, _callback: TypingCallback): () => void;
165
+ onTyping(ticketId: string, callback: TypingCallback): () => void;
166
+ /**
167
+ * Send a customer typing indicator (requires realtime).
168
+ * No-op if realtime is not available.
169
+ */
170
+ sendTyping(ticketId: string, isTyping: boolean): Promise<void>;
139
171
  /** Disconnect all subscriptions and clean up. */
140
172
  disconnect(): void;
141
173
  /** @internal Make an authenticated request to the widget API. */
@@ -148,6 +180,11 @@ declare class ChatClient {
148
180
  getTeamId(): string | null;
149
181
  /** @internal Set team ID from identify response or other source. */
150
182
  setTeamId(teamId: string): void;
183
+ /** @internal Wait for realtime to be initialized (for testing). */
184
+ waitForRealtime(): Promise<void>;
185
+ private initRealtime;
186
+ private fetchRealtimeToken;
187
+ private pollMessages;
151
188
  private buildUrl;
152
189
  }
153
190
  /** Conversations sub-resource on ChatClient. */
@@ -169,4 +206,4 @@ declare class MessagesApi {
169
206
  send(ticketId: string, content: string): Promise<WidgetMessage>;
170
207
  }
171
208
 
172
- export { ChatClient, type ChatConfig, type Conversation, type ConversationCreateParams, type ConversationListParams, type ConversationListResponse, type IdentifyParams, type IdentifyResult, type MessageCallback, type TypingCallback, type WidgetMessage };
209
+ export { ChatClient, type ChatConfig, type Conversation, type ConversationCreateParams, type ConversationListParams, type ConversationListResponse, type IdentifyParams, type IdentifyResult, type MessageCallback, type RealtimeTokenResponse, type TypingCallback, type TypingPayload, type WidgetMessage };
@@ -1,3 +1,243 @@
1
+ // src/chat/realtime.ts
2
+ var RealtimeManager = class {
3
+ constructor(options) {
4
+ this.client = null;
5
+ this.initPromise = null;
6
+ this.channels = /* @__PURE__ */ new Map();
7
+ this.refreshTimer = null;
8
+ this.currentToken = null;
9
+ this.options = options;
10
+ }
11
+ /**
12
+ * Initialize the Supabase client and authenticate with a realtime token.
13
+ * Returns true if successful, false if @supabase/supabase-js is unavailable.
14
+ */
15
+ init() {
16
+ if (this.initPromise) return this.initPromise;
17
+ this.initPromise = this.doInit();
18
+ return this.initPromise;
19
+ }
20
+ async doInit() {
21
+ try {
22
+ const { createClient } = await import(
23
+ /* webpackIgnore: true */
24
+ "@supabase/supabase-js"
25
+ );
26
+ this.client = createClient(this.options.supabaseUrl, this.options.supabaseAnonKey, {
27
+ auth: { persistSession: false, autoRefreshToken: false },
28
+ realtime: { params: { eventsPerSecond: 10 } }
29
+ });
30
+ const tokenData = await this.options.fetchToken();
31
+ this.setToken(tokenData);
32
+ return true;
33
+ } catch {
34
+ this.initPromise = null;
35
+ return false;
36
+ }
37
+ }
38
+ setToken(tokenData) {
39
+ this.currentToken = tokenData.token;
40
+ if (this.client) {
41
+ this.client.realtime.setAuth(tokenData.token);
42
+ }
43
+ this.scheduleRefresh(tokenData.refreshAt);
44
+ }
45
+ scheduleRefresh(refreshAt) {
46
+ if (this.refreshTimer) {
47
+ clearTimeout(this.refreshTimer);
48
+ }
49
+ const msUntilRefresh = new Date(refreshAt).getTime() - Date.now();
50
+ const delay = Math.max(msUntilRefresh, 1e4);
51
+ this.refreshTimer = setTimeout(() => this.doRefresh(), delay);
52
+ }
53
+ async doRefresh() {
54
+ try {
55
+ const tokenData = await this.options.fetchToken();
56
+ this.setToken(tokenData);
57
+ } catch {
58
+ this.refreshTimer = setTimeout(() => this.doRefresh(), 3e4);
59
+ }
60
+ }
61
+ /**
62
+ * Subscribe to new messages on a ticket via Postgres Changes.
63
+ * Returns an unsubscribe function.
64
+ */
65
+ subscribeToMessages(ticketId, callback) {
66
+ if (!this.client) return () => {
67
+ };
68
+ const channelName = `messages:${ticketId}`;
69
+ this.removeChannel(channelName);
70
+ const channel = this.client.channel(channelName).on(
71
+ "postgres_changes",
72
+ {
73
+ event: "INSERT",
74
+ schema: "public",
75
+ table: "messages",
76
+ filter: `ticket_id=eq.${ticketId}`
77
+ },
78
+ (payload) => {
79
+ const row = payload.new;
80
+ if (!row) return;
81
+ const message = {
82
+ id: row.id,
83
+ content: row.content,
84
+ sender: row.sender,
85
+ sender_name: row.sender_name ?? "",
86
+ created_at: row.created_at,
87
+ read_at: row.read_at ?? null,
88
+ attachments: row.attachments ?? []
89
+ };
90
+ callback(message);
91
+ }
92
+ ).subscribe();
93
+ this.channels.set(channelName, channel);
94
+ return () => this.removeChannel(channelName);
95
+ }
96
+ /** Get the underlying Supabase client (for sharing with PresenceManager). */
97
+ getClient() {
98
+ return this.client;
99
+ }
100
+ /** Whether the realtime manager is initialized and has a token. */
101
+ get isReady() {
102
+ return this.client !== null && this.currentToken !== null;
103
+ }
104
+ removeChannel(name) {
105
+ const existing = this.channels.get(name);
106
+ if (existing && this.client) {
107
+ this.client.removeChannel(existing);
108
+ this.channels.delete(name);
109
+ }
110
+ }
111
+ /** Clean up all channels, timers, and the client. */
112
+ destroy() {
113
+ if (this.refreshTimer) {
114
+ clearTimeout(this.refreshTimer);
115
+ this.refreshTimer = null;
116
+ }
117
+ for (const [name] of this.channels) {
118
+ this.removeChannel(name);
119
+ }
120
+ this.channels.clear();
121
+ this.client = null;
122
+ this.initPromise = null;
123
+ this.currentToken = null;
124
+ }
125
+ };
126
+
127
+ // src/chat/presence.ts
128
+ var TYPING_THROTTLE_MS = 2e3;
129
+ var TYPING_CLEAR_DELAY_MS = 3e3;
130
+ var PresenceManager = class {
131
+ constructor(options) {
132
+ this.client = null;
133
+ this.channels = /* @__PURE__ */ new Map();
134
+ this.lastTypingSentAt = /* @__PURE__ */ new Map();
135
+ this.typingClearTimers = /* @__PURE__ */ new Map();
136
+ this.options = options;
137
+ }
138
+ /** Set the Supabase client (shared from RealtimeManager). */
139
+ setClient(client) {
140
+ this.client = client;
141
+ }
142
+ /**
143
+ * Subscribe to agent typing events on a ticket.
144
+ * Only fires callback for agent typing (has `agent_id`), not customer typing echoes.
145
+ *
146
+ * @returns Unsubscribe function
147
+ */
148
+ subscribeToTyping(ticketId, callback) {
149
+ if (!this.client) return () => {
150
+ };
151
+ const channelName = `typing:${ticketId}`;
152
+ this.removeChannel(channelName);
153
+ const channel = this.client.channel(`ticket:${ticketId}`).on("broadcast", { event: "typing" }, (data) => {
154
+ const payload = data?.payload;
155
+ if (!payload) return;
156
+ if (payload.agent_id) {
157
+ const typingPayload = {
158
+ agent_id: payload.agent_id,
159
+ agent_name: payload.agent_name || "Agent",
160
+ is_typing: !!payload.is_typing
161
+ };
162
+ callback(typingPayload);
163
+ }
164
+ }).subscribe();
165
+ this.channels.set(channelName, channel);
166
+ return () => this.removeChannel(channelName);
167
+ }
168
+ /**
169
+ * Send a customer typing indicator.
170
+ * Throttled: max 1 typing=true per 2s, auto-clears after 3s.
171
+ */
172
+ async sendTyping(ticketId, isTyping) {
173
+ if (!this.client) return;
174
+ const existingTimer = this.typingClearTimers.get(ticketId);
175
+ if (existingTimer) {
176
+ clearTimeout(existingTimer);
177
+ this.typingClearTimers.delete(ticketId);
178
+ }
179
+ if (isTyping) {
180
+ const lastSent = this.lastTypingSentAt.get(ticketId) || 0;
181
+ const now = Date.now();
182
+ if (now - lastSent < TYPING_THROTTLE_MS) {
183
+ const timer2 = setTimeout(() => {
184
+ this.doSendTyping(ticketId, false);
185
+ }, TYPING_CLEAR_DELAY_MS);
186
+ this.typingClearTimers.set(ticketId, timer2);
187
+ return;
188
+ }
189
+ this.lastTypingSentAt.set(ticketId, now);
190
+ const timer = setTimeout(() => {
191
+ this.doSendTyping(ticketId, false);
192
+ }, TYPING_CLEAR_DELAY_MS);
193
+ this.typingClearTimers.set(ticketId, timer);
194
+ }
195
+ await this.doSendTyping(ticketId, isTyping);
196
+ }
197
+ async doSendTyping(ticketId, isTyping) {
198
+ if (!this.client) return;
199
+ try {
200
+ const sendChannelName = `typing-send:${ticketId}`;
201
+ let channel = this.channels.get(sendChannelName);
202
+ if (!channel) {
203
+ channel = this.client.channel(`ticket:${ticketId}`);
204
+ channel.subscribe();
205
+ this.channels.set(sendChannelName, channel);
206
+ }
207
+ await channel.send({
208
+ type: "broadcast",
209
+ event: "typing",
210
+ payload: {
211
+ customer_id: this.options.customerId,
212
+ customer_name: this.options.customerName,
213
+ is_typing: isTyping
214
+ }
215
+ });
216
+ } catch {
217
+ }
218
+ }
219
+ removeChannel(name) {
220
+ const existing = this.channels.get(name);
221
+ if (existing && this.client) {
222
+ this.client.removeChannel(existing);
223
+ this.channels.delete(name);
224
+ }
225
+ }
226
+ /** Clean up all channels and timers. */
227
+ destroy() {
228
+ for (const timer of this.typingClearTimers.values()) {
229
+ clearTimeout(timer);
230
+ }
231
+ this.typingClearTimers.clear();
232
+ this.lastTypingSentAt.clear();
233
+ for (const [name] of this.channels) {
234
+ this.removeChannel(name);
235
+ }
236
+ this.channels.clear();
237
+ this.client = null;
238
+ }
239
+ };
240
+
1
241
  // src/chat/index.ts
2
242
  var DEFAULT_BASE_URL = "https://app.cstar.help";
3
243
  var DEFAULT_POLLING_INTERVAL = 3e3;
@@ -5,10 +245,17 @@ var ChatClient = class {
5
245
  constructor(config) {
6
246
  this.sessionToken = null;
7
247
  this.teamId = null;
248
+ this.customerId = null;
8
249
  this.pollingTimers = /* @__PURE__ */ new Map();
250
+ this.realtimeManager = null;
251
+ this.presenceManager = null;
252
+ this.realtimeReady = false;
253
+ this.realtimeInitPromise = null;
9
254
  this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
10
255
  this.teamSlug = config.teamSlug;
11
256
  this.pollingInterval = config.pollingInterval ?? DEFAULT_POLLING_INTERVAL;
257
+ this.supabaseUrl = config.supabaseUrl;
258
+ this.supabaseAnonKey = config.supabaseAnonKey;
12
259
  this.conversations = new ConversationsApi(this);
13
260
  this.messages = new MessagesApi(this);
14
261
  }
@@ -16,6 +263,9 @@ var ChatClient = class {
16
263
  * Identify a customer using HMAC signature verification.
17
264
  * Must be called before accessing conversations or messages.
18
265
  *
266
+ * If `supabaseUrl` and `supabaseAnonKey` were provided in the config,
267
+ * this will also initialize real-time subscriptions (non-blocking).
268
+ *
19
269
  * @param customer - Customer identity fields
20
270
  * @param signature - HMAC-SHA256 hex signature of the signed fields
21
271
  * @param testMode - Whether to use test mode (relaxed timestamp validation)
@@ -34,40 +284,27 @@ var ChatClient = class {
34
284
  }
35
285
  );
36
286
  this.sessionToken = response.data.sessionToken;
287
+ this.teamId = response.data.teamId;
288
+ this.customerId = response.data.customer.id;
289
+ if (this.supabaseUrl && this.supabaseAnonKey) {
290
+ this.realtimeInitPromise = this.initRealtime(
291
+ response.data.customer.id,
292
+ response.data.customer.name || customer.name || customer.email
293
+ );
294
+ }
37
295
  return response.data;
38
296
  }
39
297
  /**
40
298
  * Subscribe to new messages on a conversation.
41
- * Falls back to polling when Supabase Realtime is not available.
299
+ * Uses Supabase Realtime (Postgres Changes) when available, falls back to polling.
42
300
  *
43
301
  * @returns Unsubscribe function
44
302
  */
45
303
  onMessage(ticketId, callback) {
46
- let lastMessageId = null;
47
- const poll = async () => {
48
- try {
49
- const messages = await this.messages.list(ticketId);
50
- if (messages.length > 0) {
51
- const latest = messages[messages.length - 1];
52
- if (lastMessageId && latest.id !== lastMessageId) {
53
- const lastIdx = messages.findIndex((m) => m.id === lastMessageId);
54
- const newMessages = lastIdx >= 0 ? messages.slice(lastIdx + 1) : [latest];
55
- for (const msg of newMessages) {
56
- callback(msg);
57
- }
58
- }
59
- lastMessageId = latest.id;
60
- }
61
- } catch {
62
- }
63
- };
64
- poll();
65
- const timer = setInterval(poll, this.pollingInterval);
66
- this.pollingTimers.set(ticketId, timer);
67
- return () => {
68
- clearInterval(timer);
69
- this.pollingTimers.delete(ticketId);
70
- };
304
+ if (this.realtimeReady && this.realtimeManager) {
305
+ return this.realtimeManager.subscribeToMessages(ticketId, callback);
306
+ }
307
+ return this.pollMessages(ticketId, callback);
71
308
  }
72
309
  /**
73
310
  * Subscribe to typing indicator events.
@@ -75,17 +312,41 @@ var ChatClient = class {
75
312
  *
76
313
  * @returns Unsubscribe function
77
314
  */
78
- onTyping(_ticketId, _callback) {
315
+ onTyping(ticketId, callback) {
316
+ if (this.realtimeReady && this.presenceManager) {
317
+ return this.presenceManager.subscribeToTyping(ticketId, callback);
318
+ }
79
319
  return () => {
80
320
  };
81
321
  }
322
+ /**
323
+ * Send a customer typing indicator (requires realtime).
324
+ * No-op if realtime is not available.
325
+ */
326
+ async sendTyping(ticketId, isTyping) {
327
+ if (this.presenceManager) {
328
+ await this.presenceManager.sendTyping(ticketId, isTyping);
329
+ }
330
+ }
82
331
  /** Disconnect all subscriptions and clean up. */
83
332
  disconnect() {
333
+ if (this.realtimeManager) {
334
+ this.realtimeManager.destroy();
335
+ this.realtimeManager = null;
336
+ }
337
+ if (this.presenceManager) {
338
+ this.presenceManager.destroy();
339
+ this.presenceManager = null;
340
+ }
341
+ this.realtimeReady = false;
342
+ this.realtimeInitPromise = null;
84
343
  for (const timer of this.pollingTimers.values()) {
85
344
  clearInterval(timer);
86
345
  }
87
346
  this.pollingTimers.clear();
88
347
  this.sessionToken = null;
348
+ this.teamId = null;
349
+ this.customerId = null;
89
350
  }
90
351
  /** @internal Make an authenticated request to the widget API. */
91
352
  async fetch(path, options) {
@@ -115,6 +376,72 @@ var ChatClient = class {
115
376
  setTeamId(teamId) {
116
377
  this.teamId = teamId;
117
378
  }
379
+ /** @internal Wait for realtime to be initialized (for testing). */
380
+ async waitForRealtime() {
381
+ if (this.realtimeInitPromise) {
382
+ await this.realtimeInitPromise;
383
+ }
384
+ }
385
+ async initRealtime(customerId, customerName) {
386
+ try {
387
+ this.realtimeManager = new RealtimeManager({
388
+ supabaseUrl: this.supabaseUrl,
389
+ supabaseAnonKey: this.supabaseAnonKey,
390
+ fetchToken: () => this.fetchRealtimeToken()
391
+ });
392
+ const ready = await this.realtimeManager.init();
393
+ if (ready) {
394
+ this.realtimeReady = true;
395
+ this.presenceManager = new PresenceManager({
396
+ customerId,
397
+ customerName
398
+ });
399
+ const client = this.realtimeManager.getClient();
400
+ if (client) {
401
+ this.presenceManager.setClient(client);
402
+ }
403
+ }
404
+ } catch {
405
+ this.realtimeReady = false;
406
+ }
407
+ }
408
+ async fetchRealtimeToken() {
409
+ const response = await this.fetch(
410
+ "/api/widget/realtime-token",
411
+ {
412
+ method: "POST",
413
+ body: { teamId: this.teamId }
414
+ }
415
+ );
416
+ return response.data;
417
+ }
418
+ pollMessages(ticketId, callback) {
419
+ let lastMessageId = null;
420
+ const poll = async () => {
421
+ try {
422
+ const messages = await this.messages.list(ticketId);
423
+ if (messages.length > 0) {
424
+ const latest = messages[messages.length - 1];
425
+ if (lastMessageId && latest.id !== lastMessageId) {
426
+ const lastIdx = messages.findIndex((m) => m.id === lastMessageId);
427
+ const newMessages = lastIdx >= 0 ? messages.slice(lastIdx + 1) : [latest];
428
+ for (const msg of newMessages) {
429
+ callback(msg);
430
+ }
431
+ }
432
+ lastMessageId = latest.id;
433
+ }
434
+ } catch {
435
+ }
436
+ };
437
+ poll();
438
+ const timer = setInterval(poll, this.pollingInterval);
439
+ this.pollingTimers.set(ticketId, timer);
440
+ return () => {
441
+ clearInterval(timer);
442
+ this.pollingTimers.delete(ticketId);
443
+ };
444
+ }
118
445
  buildUrl(path, query) {
119
446
  const base = `${this.baseUrl}${path}`;
120
447
  if (!query) return base;