@cimulate/copilot-sdk 3.14.0 → 3.15.0

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 (33) hide show
  1. package/dist/bundle.cimulate.copilot-sdk.2fcdd90b.esm.js +2 -0
  2. package/dist/bundle.cimulate.copilot-sdk.2fcdd90b.esm.js.map +1 -0
  3. package/dist/bundle.cimulate.copilot-sdk.6effe8df.cjs.js +2 -0
  4. package/dist/bundle.cimulate.copilot-sdk.6effe8df.cjs.js.map +1 -0
  5. package/dist/bundle.cimulate.copilot-sdk.fe5dd664.umd.js +2 -0
  6. package/dist/bundle.cimulate.copilot-sdk.fe5dd664.umd.js.map +1 -0
  7. package/dist/index.cjs.js +1 -1
  8. package/dist/index.cjs.js.map +1 -1
  9. package/dist/index.esm.js +1 -1
  10. package/dist/index.esm.js.map +1 -1
  11. package/dist/index.umd.js +1 -1
  12. package/dist/index.umd.js.map +1 -1
  13. package/dist/types/copilot.d.ts +9 -1
  14. package/dist/types/model/AskCimSuggestionsAck.d.ts +10 -0
  15. package/dist/types/model/CopilotApiAck.d.ts +5 -1
  16. package/dist/types/model/CopilotBrowseSuggestionsAck.d.ts +10 -0
  17. package/dist/types/model/CopilotSearchSuggestionsAck.d.ts +10 -0
  18. package/dist/types/model/ProductViewSuggestionsAck.d.ts +10 -0
  19. package/dist/types/model/index.d.ts +4 -0
  20. package/package.json +1 -1
  21. package/src/copilot.ts +161 -77
  22. package/src/model/AskCimSuggestionsAck.ts +10 -0
  23. package/src/model/CopilotApiAck.ts +8 -0
  24. package/src/model/CopilotBrowseSuggestionsAck.ts +10 -0
  25. package/src/model/CopilotSearchSuggestionsAck.ts +10 -0
  26. package/src/model/ProductViewSuggestionsAck.ts +10 -0
  27. package/src/model/index.ts +4 -0
  28. package/dist/bundle.cimulate.copilot-sdk.7dbeb4d0.umd.js +0 -2
  29. package/dist/bundle.cimulate.copilot-sdk.7dbeb4d0.umd.js.map +0 -1
  30. package/dist/bundle.cimulate.copilot-sdk.a60898e7.esm.js +0 -2
  31. package/dist/bundle.cimulate.copilot-sdk.a60898e7.esm.js.map +0 -1
  32. package/dist/bundle.cimulate.copilot-sdk.ff5873e3.cjs.js +0 -2
  33. package/dist/bundle.cimulate.copilot-sdk.ff5873e3.cjs.js.map +0 -1
package/src/copilot.ts CHANGED
@@ -4,12 +4,16 @@ import deepmerge from "deepmerge";
4
4
  import type {
5
5
  AskCim,
6
6
  AskCimAck,
7
+ AskCimSuggestions,
8
+ AskCimSuggestionsAck,
7
9
  Cancel,
8
10
  CancelAck,
9
11
  CopilotAPIAck,
10
12
  ConnectAck,
11
13
  CopilotBrowse,
12
14
  CopilotBrowseAck,
15
+ CopilotBrowseSuggestions,
16
+ CopilotBrowseSuggestionsAck,
13
17
  ConnectError,
14
18
  ConversationEvents,
15
19
  CopilotAPIEvent,
@@ -17,10 +21,14 @@ import type {
17
21
  CopilotEventName,
18
22
  CopilotSearch,
19
23
  CopilotSearchAck,
24
+ CopilotSearchSuggestions,
25
+ CopilotSearchSuggestionsAck,
20
26
  FacetedNavigation,
21
27
  FacetedNavigationAck,
22
28
  ProductView,
23
29
  ProductViewAck,
30
+ ProductViewSuggestions,
31
+ ProductViewSuggestionsAck,
24
32
  ReturnedFields,
25
33
  SessionInformation,
26
34
  ConversationReset,
@@ -42,7 +50,7 @@ interface CommonOptions {
42
50
  }
43
51
 
44
52
  type CimulateCopilotOptions = (ApiKeyAuth | ApiTokenAuth) & CommonOptions;
45
- type CopilotEvents = CopilotEvent[]
53
+ type CopilotEvents = CopilotEvent[];
46
54
 
47
55
  const socketDefaults: SocketIOOptions = {
48
56
  path: "/api/v1/socket.io",
@@ -58,7 +66,7 @@ interface CopilotResult<T extends ReturnedFields, R> {
58
66
  }
59
67
 
60
68
  export default class CimulateCopilot<
61
- T extends ReturnedFields = ReturnedFields
69
+ T extends ReturnedFields = ReturnedFields,
62
70
  > {
63
71
  private socket: Socket;
64
72
  private sessionIdKey: string = "x-cimulate-copilot-session-id";
@@ -74,9 +82,10 @@ export default class CimulateCopilot<
74
82
  namespace = "/copilot",
75
83
  socketOptions = {},
76
84
  }: CimulateCopilotOptions) {
77
-
78
85
  if ((apiKey && apiToken) || (!apiKey && !apiToken)) {
79
- throw new Error("Provide exactly one authentication method: either 'apiKey' or 'apiToken', but not both.");
86
+ throw new Error(
87
+ "Provide exactly one authentication method: either 'apiKey' or 'apiToken', but not both.",
88
+ );
80
89
  }
81
90
 
82
91
  const socketioEndpoint = `${baseUrl}${namespace}`;
@@ -110,18 +119,20 @@ export default class CimulateCopilot<
110
119
  [this.sessionIdKey]: event.sessionId,
111
120
  };
112
121
  };
113
-
122
+
114
123
  private readonly handleDisconnect = (reason: Socket.DisconnectReason) => {
115
124
  console.warn(`[Copilot SDK] Disconnected: ${reason}`);
116
125
  if (reason !== "io client disconnect") {
117
- console.log(`[Copilot SDK] Disconnected due to ${reason}. Attempting reconnect...`);
126
+ console.log(
127
+ `[Copilot SDK] Disconnected due to ${reason}. Attempting reconnect...`,
128
+ );
118
129
  this.retryConnect();
119
130
  }
120
131
  };
121
-
132
+
122
133
  private readonly handleConnectError = (err: ConnectError) => {
123
134
  console.error(`[Copilot SDK] Connect error: ${err.message}`);
124
-
135
+
125
136
  const authErrors = ["InvalidApiKey", "InvalidToken", "BadRequest"];
126
137
 
127
138
  // Use regex to extract error type
@@ -142,10 +153,9 @@ export default class CimulateCopilot<
142
153
  this.socket.off("connect_ack", this.handleConnectAck);
143
154
  this.socket.off("disconnect", this.handleDisconnect);
144
155
  this.off("connect_error", this.handleConnectError);
145
- }
156
+ };
146
157
 
147
158
  connect() {
148
-
149
159
  if (this.reconnectTimeout) {
150
160
  clearTimeout(this.reconnectTimeout);
151
161
  this.reconnectTimeout = undefined;
@@ -154,35 +164,44 @@ export default class CimulateCopilot<
154
164
 
155
165
  // Clear old handlers to avoid duplicates
156
166
  this.offInternalHandlers();
157
-
167
+
158
168
  // Add fresh handlers
159
169
  this.on("connect_ack", this.handleConnectAck);
160
170
  this.socket.on("disconnect", this.handleDisconnect);
161
171
  this.on("connect_error", this.handleConnectError);
162
-
172
+
163
173
  // Clear old auth state
164
174
  if (this.socket.auth && this.sessionIdKey in this.socket.auth) {
165
175
  this.socket.auth = {};
166
176
  }
167
-
177
+
168
178
  this.socket.connect();
169
- }
179
+ }
170
180
 
171
181
  private retryConnect() {
172
182
  // Don't retry connect if connected or currently trying to connect
173
- if (this.socket.connected || this.socket.active || this.reconnectAttempts >= this.maxReconnectAttempts) {
183
+ if (
184
+ this.socket.connected ||
185
+ this.socket.active ||
186
+ this.reconnectAttempts >= this.maxReconnectAttempts
187
+ ) {
174
188
  return;
175
189
  }
176
-
190
+
177
191
  if (this.reconnectTimeout) {
178
192
  clearTimeout(this.reconnectTimeout);
179
193
  this.reconnectTimeout = undefined;
180
194
  }
181
195
 
182
196
  if (this.reconnectAttempts < this.maxReconnectAttempts) {
183
- const delay = Math.min(1000 * 2 ** this.reconnectAttempts, this.maxReconnectDelay);
184
- console.info(`[Copilot SDK] Retry #${this.reconnectAttempts + 1} in ${delay}ms...`);
185
-
197
+ const delay = Math.min(
198
+ 1000 * 2 ** this.reconnectAttempts,
199
+ this.maxReconnectDelay,
200
+ );
201
+ console.info(
202
+ `[Copilot SDK] Retry #${this.reconnectAttempts + 1} in ${delay}ms...`,
203
+ );
204
+
186
205
  this.reconnectTimeout = setTimeout(() => {
187
206
  if (!this.socket.connected && !this.socket.active) {
188
207
  this.reconnectAttempts++;
@@ -196,140 +215,204 @@ export default class CimulateCopilot<
196
215
 
197
216
  reconnect() {
198
217
  // Don't reconnect if connected or currently trying to connect
199
- if (this.socket.connected || this.socket.active || this.reconnectAttempts >= this.maxReconnectAttempts) {
218
+ if (
219
+ this.socket.connected ||
220
+ this.socket.active ||
221
+ this.reconnectAttempts >= this.maxReconnectAttempts
222
+ ) {
200
223
  return;
201
224
  }
202
-
225
+
203
226
  // Clear any existing scheduled reconnect to debounce
204
227
  if (this.reconnectTimeout) {
205
228
  clearTimeout(this.reconnectTimeout);
206
229
  this.reconnectTimeout = undefined;
207
230
  this.reconnectAttempts = 0;
208
231
  }
209
-
232
+
210
233
  this.socket.connect();
211
234
  }
212
235
 
213
236
  async browse(
214
- args: CopilotBrowse
237
+ args: CopilotBrowse,
215
238
  ): Promise<CopilotResult<T, CopilotBrowseAck>>;
216
239
  async browse(
217
240
  args: CopilotBrowse,
218
- callback?: (event: CopilotBrowseAck) => void
241
+ callback?: (event: CopilotBrowseAck) => void,
219
242
  ): Promise<void>;
220
243
  async browse(
221
244
  args: CopilotBrowse,
222
- callback?: (event: CopilotBrowseAck) => void
245
+ callback?: (event: CopilotBrowseAck) => void,
223
246
  ): Promise<CopilotResult<T, CopilotBrowseAck> | void> {
224
247
  return this.asyncResponse<CopilotBrowse, CopilotBrowseAck>(
225
248
  "copilot_browse",
226
249
  args,
227
- callback
250
+ callback,
228
251
  );
229
252
  }
230
253
 
254
+ async browseSuggestions(
255
+ args: CopilotBrowseSuggestions,
256
+ ): Promise<CopilotResult<T, CopilotBrowseSuggestionsAck>>;
257
+ async browseSuggestions(
258
+ args: CopilotBrowseSuggestions,
259
+ callback?: (event: CopilotBrowseSuggestionsAck) => void,
260
+ ): Promise<void>;
261
+ async browseSuggestions(
262
+ args: CopilotBrowseSuggestions,
263
+ callback?: (event: CopilotBrowseSuggestionsAck) => void,
264
+ ): Promise<CopilotResult<T, CopilotBrowseSuggestionsAck> | void> {
265
+ return this.asyncResponse<
266
+ CopilotBrowseSuggestions,
267
+ CopilotBrowseSuggestionsAck
268
+ >("copilot_browse_suggestions", args, callback);
269
+ }
231
270
 
232
271
  async search(
233
- args: CopilotSearch
272
+ args: CopilotSearch,
234
273
  ): Promise<CopilotResult<T, CopilotSearchAck>>;
235
274
  async search(
236
275
  args: CopilotSearch,
237
- callback?: (event: CopilotSearchAck) => void
276
+ callback?: (event: CopilotSearchAck) => void,
238
277
  ): Promise<void>;
239
278
  async search(
240
279
  args: CopilotSearch,
241
- callback?: (event: CopilotSearchAck) => void
280
+ callback?: (event: CopilotSearchAck) => void,
242
281
  ): Promise<CopilotResult<T, CopilotSearchAck> | void> {
243
282
  return this.asyncResponse<CopilotSearch, CopilotSearchAck>(
244
283
  "copilot_search",
245
284
  args,
246
- callback
285
+ callback,
247
286
  );
248
287
  }
249
288
 
289
+ async searchSuggestions(
290
+ args: CopilotSearchSuggestions,
291
+ ): Promise<CopilotResult<T, CopilotSearchSuggestionsAck>>;
292
+ async searchSuggestions(
293
+ args: CopilotSearchSuggestions,
294
+ callback?: (event: CopilotSearchSuggestionsAck) => void,
295
+ ): Promise<void>;
296
+ async searchSuggestions(
297
+ args: CopilotSearchSuggestions,
298
+ callback?: (event: CopilotSearchSuggestionsAck) => void,
299
+ ): Promise<CopilotResult<T, CopilotSearchSuggestionsAck> | void> {
300
+ return this.asyncResponse<
301
+ CopilotSearchSuggestions,
302
+ CopilotSearchSuggestionsAck
303
+ >("copilot_search_suggestions", args, callback);
304
+ }
305
+
250
306
  async facetedNavigation(
251
- args: FacetedNavigation
307
+ args: FacetedNavigation,
252
308
  ): Promise<CopilotResult<T, FacetedNavigationAck>>;
253
309
  async facetedNavigation(
254
310
  args: FacetedNavigation,
255
- callback?: (event: FacetedNavigationAck) => void
311
+ callback?: (event: FacetedNavigationAck) => void,
256
312
  ): Promise<void>;
257
313
  async facetedNavigation(
258
314
  args: FacetedNavigation,
259
- callback?: (event: FacetedNavigationAck) => void
315
+ callback?: (event: FacetedNavigationAck) => void,
260
316
  ): Promise<CopilotResult<T, FacetedNavigationAck> | void> {
261
317
  return this.asyncResponse<FacetedNavigation, FacetedNavigationAck>(
262
318
  "faceted_navigation",
263
319
  args,
264
- callback
320
+ callback,
265
321
  );
266
322
  }
267
323
 
268
324
  async cancelRequest(args: Cancel): Promise<CopilotResult<T, CancelAck>>;
269
325
  async cancelRequest(
270
326
  args: Cancel,
271
- callback?: (event: CancelAck) => void
327
+ callback?: (event: CancelAck) => void,
272
328
  ): Promise<void>;
273
329
  cancelRequest(
274
330
  args: Cancel,
275
- callback?: (event: CancelAck) => void
331
+ callback?: (event: CancelAck) => void,
276
332
  ): Promise<CopilotResult<T, CancelAck> | void> {
277
- return this.asyncResponse<Cancel, CancelAck>(
278
- "cancel",
279
- args,
280
- callback
281
- );
333
+ return this.asyncResponse<Cancel, CancelAck>("cancel", args, callback);
282
334
  }
283
335
 
284
- async conversationReset(args: ConversationReset): Promise<CopilotResult<T, ConversationResetAck>>;
285
336
  async conversationReset(
286
337
  args: ConversationReset,
287
- callback?: (event: ConversationResetAck) => void
338
+ ): Promise<CopilotResult<T, ConversationResetAck>>;
339
+ async conversationReset(
340
+ args: ConversationReset,
341
+ callback?: (event: ConversationResetAck) => void,
288
342
  ): Promise<void>;
289
343
  conversationReset(
290
344
  args: ConversationReset,
291
- callback?: (event: ConversationResetAck) => void
345
+ callback?: (event: ConversationResetAck) => void,
292
346
  ): Promise<CopilotResult<T, ConversationResetAck> | void> {
293
347
  return this.asyncResponse<ConversationReset, ConversationResetAck>(
294
348
  "conversation_reset",
295
349
  args,
296
- callback
350
+ callback,
297
351
  );
298
352
  }
299
353
 
300
354
  async productView(
301
- args: ProductView
355
+ args: ProductView,
302
356
  ): Promise<CopilotResult<T, ProductViewAck>>;
303
357
  async productView(
304
358
  args: ProductView,
305
- callback?: (event: ProductViewAck) => void
359
+ callback?: (event: ProductViewAck) => void,
306
360
  ): Promise<void>;
307
361
  async productView(
308
362
  args: ProductView,
309
- callback?: (event: ProductViewAck) => void
363
+ callback?: (event: ProductViewAck) => void,
310
364
  ): Promise<CopilotResult<T, ProductViewAck> | void> {
311
365
  return this.asyncResponse<ProductView, ProductViewAck>(
312
366
  "product_view",
313
367
  args,
314
- callback
368
+ callback,
315
369
  );
316
370
  }
317
371
 
318
- async askCim(
319
- args: AskCim
320
- ): Promise<CopilotResult<T, AskCimAck>>;
372
+ async productViewSuggestions(
373
+ args: ProductViewSuggestions,
374
+ ): Promise<CopilotResult<T, ProductViewSuggestionsAck>>;
375
+ async productViewSuggestions(
376
+ args: ProductViewSuggestions,
377
+ callback?: (event: ProductViewSuggestionsAck) => void,
378
+ ): Promise<void>;
379
+ async productViewSuggestions(
380
+ args: ProductViewSuggestions,
381
+ callback?: (event: ProductViewSuggestionsAck) => void,
382
+ ): Promise<CopilotResult<T, ProductViewSuggestionsAck> | void> {
383
+ return this.asyncResponse<
384
+ ProductViewSuggestions,
385
+ ProductViewSuggestionsAck
386
+ >("product_view_suggestions", args, callback);
387
+ }
388
+
389
+ async askCim(args: AskCim): Promise<CopilotResult<T, AskCimAck>>;
321
390
  async askCim(
322
391
  args: AskCim,
323
- callback?: (event: AskCimAck) => void
392
+ callback?: (event: AskCimAck) => void,
324
393
  ): Promise<void>;
325
394
  async askCim(
326
395
  args: AskCim,
327
- callback?: (event: AskCimAck) => void
396
+ callback?: (event: AskCimAck) => void,
328
397
  ): Promise<CopilotResult<T, AskCimAck> | void> {
329
- return this.asyncResponse<AskCim, AskCimAck>(
330
- "ask_cim",
398
+ return this.asyncResponse<AskCim, AskCimAck>("ask_cim", args, callback);
399
+ }
400
+
401
+ async askCimSuggestions(
402
+ args: AskCimSuggestions,
403
+ ): Promise<CopilotResult<T, AskCimSuggestionsAck>>;
404
+ async askCimSuggestions(
405
+ args: AskCimSuggestions,
406
+ callback?: (event: AskCimSuggestionsAck) => void,
407
+ ): Promise<void>;
408
+ async askCimSuggestions(
409
+ args: AskCimSuggestions,
410
+ callback?: (event: AskCimSuggestionsAck) => void,
411
+ ): Promise<CopilotResult<T, AskCimSuggestionsAck> | void> {
412
+ return this.asyncResponse<AskCimSuggestions, AskCimSuggestionsAck>(
413
+ "ask_cim_suggestions",
331
414
  args,
332
- callback
415
+ callback,
333
416
  );
334
417
  }
335
418
 
@@ -337,10 +420,10 @@ export default class CimulateCopilot<
337
420
  CopilotResult<T, SessionInformation>
338
421
  >;
339
422
  async requestSessionInformation(
340
- callback?: (sessionInformation: SessionInformation) => void
423
+ callback?: (sessionInformation: SessionInformation) => void,
341
424
  ): Promise<void>;
342
425
  async requestSessionInformation(
343
- callback?: (sessionInformation: SessionInformation) => void
426
+ callback?: (sessionInformation: SessionInformation) => void,
344
427
  ): Promise<CopilotResult<T, SessionInformation> | void> {
345
428
  return new Promise((resolve) => {
346
429
  this.socket.emit("session_info", (response: SessionInformation) => {
@@ -351,29 +434,31 @@ export default class CimulateCopilot<
351
434
  });
352
435
  }
353
436
 
354
- async getConversationEvents(
355
- args: ConversationEvents
356
- ): Promise<CopilotEvents>;
437
+ async getConversationEvents(args: ConversationEvents): Promise<CopilotEvents>;
357
438
  async getConversationEvents(
358
439
  args: ConversationEvents,
359
- callback?: (events: CopilotEvents) => void
440
+ callback?: (events: CopilotEvents) => void,
360
441
  ): Promise<void>;
361
442
  async getConversationEvents(
362
443
  args: ConversationEvents,
363
- callback?: (events: CopilotEvents) => void
444
+ callback?: (events: CopilotEvents) => void,
364
445
  ): Promise<CopilotEvents | void> {
365
446
  return new Promise((resolve) => {
366
- this.socket.emit("conversation_events", args, (response: CopilotEvents) => {
367
- if (callback) callback(response);
368
- // TODO - error handling
369
- resolve(response as CopilotEvents);
370
- });
447
+ this.socket.emit(
448
+ "conversation_events",
449
+ args,
450
+ (response: CopilotEvents) => {
451
+ if (callback) callback(response);
452
+ // TODO - error handling
453
+ resolve(response as CopilotEvents);
454
+ },
455
+ );
371
456
  });
372
457
  }
373
458
 
374
459
  on<E extends CopilotEventName>(
375
460
  name: E,
376
- handler: (event: Extract<CopilotAPIEvent<T>, { name: E }>) => void
461
+ handler: (event: Extract<CopilotAPIEvent<T>, { name: E }>) => void,
377
462
  ) {
378
463
  this.socket.on<CopilotEventName>(name, handler);
379
464
  return handler;
@@ -381,20 +466,19 @@ export default class CimulateCopilot<
381
466
 
382
467
  once<E extends CopilotEventName>(
383
468
  name: E,
384
- handler: (event: Extract<CopilotAPIEvent<T>, { name: E }>) => void
469
+ handler: (event: Extract<CopilotAPIEvent<T>, { name: E }>) => void,
385
470
  ) {
386
471
  this.socket.once<CopilotEventName>(name, handler);
387
472
  }
388
473
 
389
474
  off<E extends CopilotEventName>(
390
475
  name?: E,
391
- handler?: (event: Extract<CopilotAPIEvent<T>, { name: E }>) => void
476
+ handler?: (event: Extract<CopilotAPIEvent<T>, { name: E }>) => void,
392
477
  ) {
393
478
  this.socket.off(name, handler as any);
394
479
  }
395
480
 
396
481
  disconnect() {
397
-
398
482
  if (this.reconnectTimeout) {
399
483
  clearTimeout(this.reconnectTimeout);
400
484
  this.reconnectTimeout = undefined;
@@ -402,7 +486,7 @@ export default class CimulateCopilot<
402
486
 
403
487
  this.offInternalHandlers();
404
488
  this.socket.disconnect();
405
- }
489
+ }
406
490
 
407
491
  onDisconnect(handler: (reason: string) => void) {
408
492
  this.socket.on("disconnect", handler);
@@ -411,7 +495,7 @@ export default class CimulateCopilot<
411
495
  private async asyncResponse<P, A extends CopilotAPIAck>(
412
496
  operation: string,
413
497
  payload: P,
414
- handler?: (event: A) => void
498
+ handler?: (event: A) => void,
415
499
  ): Promise<CopilotResult<T, A> | void> {
416
500
  if (handler) {
417
501
  this.socket.emit(operation, payload, handler);
@@ -423,7 +507,7 @@ export default class CimulateCopilot<
423
507
  const events = asyncGenerator<CopilotAPIEvent<T>>(({ emit, cancel }) => {
424
508
  const handler = (
425
509
  event: string,
426
- payload: Exclude<CopilotAPIEvent<T>, ConnectAck | ConnectError>
510
+ payload: Exclude<CopilotAPIEvent<T>, ConnectAck | ConnectError>,
427
511
  ) => {
428
512
  if (["done", "error"].includes(payload.name)) {
429
513
  cancel();
@@ -446,7 +530,7 @@ export default class CimulateCopilot<
446
530
  eventSourceId = ack?.id;
447
531
  resolve(ack);
448
532
  }
449
- })
533
+ }),
450
534
  );
451
535
 
452
536
  return { result, events };
@@ -0,0 +1,10 @@
1
+ import { AskCimSuggestions } from './AskCimSuggestions';
2
+ interface AskCimSuggestionsAck {
3
+ name: 'ask_cim_suggestions';
4
+ request: AskCimSuggestions;
5
+ sessionId: string;
6
+ id: string;
7
+ createdAt: string;
8
+ status: number;
9
+ }
10
+ export { AskCimSuggestionsAck };
@@ -3,20 +3,28 @@
3
3
  For any new event, manually create an entry here.
4
4
  */
5
5
  import { AskCimAck } from "./AskCimAck";
6
+ import { AskCimSuggestionsAck } from "./AskCimSuggestionsAck";
6
7
  import { CancelAck } from "./CancelAck";
7
8
  import { ConversationResetAck } from "./ConversationResetAck";
8
9
  import { CopilotBrowseAck } from "./CopilotBrowseAck";
10
+ import { CopilotBrowseSuggestionsAck } from "./CopilotBrowseSuggestionsAck";
9
11
  import { CopilotError } from "./CopilotError";
10
12
  import { CopilotSearchAck } from "./CopilotSearchAck";
13
+ import { CopilotSearchSuggestionsAck } from "./CopilotSearchSuggestionsAck";
11
14
  import { FacetedNavigationAck } from "./FacetedNavigationAck";
12
15
  import { ProductViewAck } from "./ProductViewAck";
16
+ import { ProductViewSuggestionsAck } from "./ProductViewSuggestionsAck";
13
17
 
14
18
  export type CopilotAPIAck =
15
19
  | AskCimAck
20
+ | AskCimSuggestionsAck
16
21
  | CancelAck
17
22
  | CopilotBrowseAck
23
+ | CopilotBrowseSuggestionsAck
18
24
  | CopilotSearchAck
25
+ | CopilotSearchSuggestionsAck
19
26
  | ConversationResetAck
20
27
  | FacetedNavigationAck
21
28
  | ProductViewAck
29
+ | ProductViewSuggestionsAck
22
30
  | CopilotError;
@@ -0,0 +1,10 @@
1
+ import { CopilotBrowseSuggestions } from './CopilotBrowseSuggestions';
2
+ interface CopilotBrowseSuggestionsAck {
3
+ name: 'copilot_browse_suggestions';
4
+ request: CopilotBrowseSuggestions;
5
+ sessionId: string;
6
+ id: string;
7
+ createdAt: string;
8
+ status: number;
9
+ }
10
+ export { CopilotBrowseSuggestionsAck };
@@ -0,0 +1,10 @@
1
+ import { CopilotSearchSuggestions } from './CopilotSearchSuggestions';
2
+ interface CopilotSearchSuggestionsAck {
3
+ name: 'copilot_search_suggestions';
4
+ request: CopilotSearchSuggestions;
5
+ sessionId: string;
6
+ id: string;
7
+ createdAt: string;
8
+ status: number;
9
+ }
10
+ export { CopilotSearchSuggestionsAck };
@@ -0,0 +1,10 @@
1
+ import { ProductViewSuggestions } from './ProductViewSuggestions';
2
+ interface ProductViewSuggestionsAck {
3
+ name: 'product_view_suggestions';
4
+ request: ProductViewSuggestions;
5
+ sessionId: string;
6
+ id: string;
7
+ createdAt: string;
8
+ status: number;
9
+ }
10
+ export { ProductViewSuggestionsAck };
@@ -1,6 +1,7 @@
1
1
  export * from './AskCim';
2
2
  export * from './AskCimAck';
3
3
  export * from './AskCimSuggestions';
4
+ export * from './AskCimSuggestionsAck';
4
5
  export * from './Attachments';
5
6
  export * from './BrowseParams';
6
7
  export * from './Cancel';
@@ -20,12 +21,14 @@ export * from './CopilotBrowse';
20
21
  export * from './CopilotBrowseAck';
21
22
  export * from './CopilotBrowseSuggestion';
22
23
  export * from './CopilotBrowseSuggestions';
24
+ export * from './CopilotBrowseSuggestionsAck';
23
25
  export * from './CopilotError';
24
26
  export * from './CopilotEvent';
25
27
  export * from './CopilotSearch';
26
28
  export * from './CopilotSearchAck';
27
29
  export * from './CopilotSearchSuggestion';
28
30
  export * from './CopilotSearchSuggestions';
31
+ export * from './CopilotSearchSuggestionsAck';
29
32
  export * from './customization';
30
33
  export * from './DisplayProducts';
31
34
  export * from './Done';
@@ -42,6 +45,7 @@ export * from './ProductView';
42
45
  export * from './ProductViewAck';
43
46
  export * from './ProductViewSuggestion';
44
47
  export * from './ProductViewSuggestions';
48
+ export * from './ProductViewSuggestionsAck';
45
49
  export * from './Progress';
46
50
  export * from './ProgressToolKwargs';
47
51
  export * from './RefinedBrowse';
@@ -1,2 +0,0 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("socket.io-client")):"function"==typeof define&&define.amd?define(["exports","socket.io-client"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).CimulateCopilot={},t.io)}(this,(function(t,e){"use strict";function n(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var r=n(e),o=function(t){return function(t){return!!t&&"object"==typeof t}(t)&&!function(t){var e=Object.prototype.toString.call(t);return"[object RegExp]"===e||"[object Date]"===e||function(t){return t.$$typeof===s}(t)}(t)};var s="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function c(t,e){return!1!==e.clone&&e.isMergeableObject(t)?h((n=t,Array.isArray(n)?[]:{}),t,e):t;var n}function i(t,e,n){return t.concat(e).map((function(t){return c(t,n)}))}function a(t){return Object.keys(t).concat(function(t){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(t).filter((function(e){return Object.propertyIsEnumerable.call(t,e)})):[]}(t))}function l(t,e){try{return e in t}catch(t){return!1}}function u(t,e,n){var r={};return n.isMergeableObject(t)&&a(t).forEach((function(e){r[e]=c(t[e],n)})),a(e).forEach((function(o){(function(t,e){return l(t,e)&&!(Object.hasOwnProperty.call(t,e)&&Object.propertyIsEnumerable.call(t,e))})(t,o)||(l(t,o)&&n.isMergeableObject(e[o])?r[o]=function(t,e){if(!e.customMerge)return h;var n=e.customMerge(t);return"function"==typeof n?n:h}(o,n)(t[o],e[o],n):r[o]=c(e[o],n))})),r}function h(t,e,n){(n=n||{}).arrayMerge=n.arrayMerge||i,n.isMergeableObject=n.isMergeableObject||o,n.cloneUnlessOtherwiseSpecified=c;var r=Array.isArray(e);return r===Array.isArray(t)?r?n.arrayMerge(t,e,n):u(t,e,n):c(e,n)}h.all=function(t,e){if(!Array.isArray(t))throw new Error("first argument should be an array");return t.reduce((function(t,n){return h(t,n,e)}),{})};var f=h;class p{constructor(t){Object.assign(this,t)}}function y(t){if(t)return function(t){for(var e in y.prototype)t[e]=y.prototype[e];return t}(t)}y.prototype.on=y.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},y.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},y.prototype.off=y.prototype.removeListener=y.prototype.removeAllListeners=y.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var o=0;o<r.length;o++)if((n=r[o])===e||n.fn===e){r.splice(o,1);break}return 0===r.length&&delete this._callbacks["$"+t],this},y.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),n=this._callbacks["$"+t],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(n){r=0;for(var o=(n=n.slice(0)).length;r<o;++r)n[r].apply(this,e)}return this},y.prototype.emitReserved=y.prototype.emit,y.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},y.prototype.hasListeners=function(t){return!!this.listeners(t).length};const d="function"==typeof ArrayBuffer,m=Object.prototype.toString,b="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===m.call(Blob),A="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===m.call(File);function k(t){return d&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||b&&t instanceof Blob||A&&t instanceof File}function g(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,n=t.length;e<n;e++)if(g(t[e]))return!0;return!1}if(k(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return g(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&g(t[e]))return!0;return!1}function E(t){const e=[],n=t.data,r=t;return r.data=C(n,e),r.attachments=e.length,{packet:r,buffers:e}}function C(t,e){if(!t)return t;if(k(t)){const n={_placeholder:!0,num:e.length};return e.push(t),n}if(Array.isArray(t)){const n=new Array(t.length);for(let r=0;r<t.length;r++)n[r]=C(t[r],e);return n}if("object"==typeof t&&!(t instanceof Date)){const n={};for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=C(t[r],e));return n}return t}function v(t,e){return t.data=N(t.data,e),delete t.attachments,t}function N(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let n=0;n<t.length;n++)t[n]=N(t[n],e);else if("object"==typeof t)for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(t[n]=N(t[n],e));return t}const w=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var _;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(_||(_={}));class O{constructor(t){this.replacer=t}encode(t){return t.type!==_.EVENT&&t.type!==_.ACK||!g(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===_.EVENT?_.BINARY_EVENT:_.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==_.BINARY_EVENT&&t.type!==_.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=E(t),n=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(n),r}}function R(t){return"[object Object]"===Object.prototype.toString.call(t)}class T extends y{constructor(t){super(),this.reviver=t}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const n=e.type===_.BINARY_EVENT;n||e.type===_.BINARY_ACK?(e.type=n?_.EVENT:_.ACK,this.reconstructor=new j(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!k(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const n={type:Number(t.charAt(0))};if(void 0===_[n.type])throw new Error("unknown packet type "+n.type);if(n.type===_.BINARY_EVENT||n.type===_.BINARY_ACK){const r=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const o=t.substring(r,e);if(o!=Number(o)||"-"!==t.charAt(e))throw new Error("Illegal attachments");n.attachments=Number(o)}if("/"===t.charAt(e+1)){const r=e+1;for(;++e;){if(","===t.charAt(e))break;if(e===t.length)break}n.nsp=t.substring(r,e)}else n.nsp="/";const r=t.charAt(e+1);if(""!==r&&Number(r)==r){const r=e+1;for(;++e;){const n=t.charAt(e);if(null==n||Number(n)!=n){--e;break}if(e===t.length)break}n.id=Number(t.substring(r,e+1))}if(t.charAt(++e)){const r=this.tryParse(t.substr(e));if(!T.isPayloadValid(n.type,r))throw new Error("invalid payload");n.data=r}return n}tryParse(t){try{return JSON.parse(t,this.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case _.CONNECT:return R(e);case _.DISCONNECT:return void 0===e;case _.CONNECT_ERROR:return"string"==typeof e||R(e);case _.EVENT:case _.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===w.indexOf(e[0]));case _.ACK:case _.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class j{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=v(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const S=["searchParams.facetFilters","browseParams.facetFilters","hits","products"];const I=(t,e,n)=>function r(o,s=[]){const c=Object.entries(o).map((([o,c])=>{const i=[...s,e(o)];return[t(o),c instanceof Object&&!n?.includes(i.join("."))?r(c,i):c]}));return Array.isArray(o)?c.map((t=>t[1])):Object.fromEntries(c)},B=t=>t.replace(/_([a-z])/g,((t,e)=>e.toUpperCase())),K=I((t=>t.replace(/([A-Z])/g,"_$1").toLowerCase()),(t=>t),S),P=I(B,B,S),D={Encoder:class extends O{encode(t){return super.encode({...t,data:2==t.data?.length?[t.data[0],K(t.data[1])]:1==t.data?.length?[t.data[0]]:"object"==typeof t.data&&null!=t.data?t.data:void 0})}},Decoder:class extends T{constructor(){super(((t,e)=>""==t&&Array.isArray(e)?e.map((t=>Array.isArray(t)?t.map((t=>t instanceof Object?P(t):t)):t instanceof Object?P(t):t)):e))}}};const x={path:"/api/v1/socket.io",autoConnect:!1,transports:["polling","websocket"],upgrade:!0,timeout:1e4};t.CimulateCopilot=class{constructor({apiKey:t,apiToken:e,baseUrl:n,namespace:o="/copilot",socketOptions:s={}}){if(this.sessionIdKey="x-cimulate-copilot-session-id",this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.maxReconnectDelay=3e4,this.handleConnectAck=t=>{console.log("[Copilot SDK] Connect Ack:",t),this.socket.auth={[this.sessionIdKey]:t.sessionId}},this.handleDisconnect=t=>{console.warn(`[Copilot SDK] Disconnected: ${t}`),"io client disconnect"!==t&&(console.log(`[Copilot SDK] Disconnected due to ${t}. Attempting reconnect...`),this.retryConnect())},this.handleConnectError=t=>{console.error(`[Copilot SDK] Connect error: ${t.message}`);const e=t.message.match(/['"]error['"]:\s*['"](\w+)['"]/),n=e?.[1];n&&["InvalidApiKey","InvalidToken","BadRequest"].includes(n)?this.disconnect():this.socket.connected||this.socket.active||(console.log("[Copilot SDK] Retrying connect attempt..."),this.retryConnect())},this.offInternalHandlers=()=>{this.socket.off("connect_ack",this.handleConnectAck),this.socket.off("disconnect",this.handleDisconnect),this.off("connect_error",this.handleConnectError)},t&&e||!t&&!e)throw new Error("Provide exactly one authentication method: either 'apiKey' or 'apiToken', but not both.");const c=`${n}${o}`,i={};t?i["x-cimulate-api-key"]=t:e&&(i.Authorization=`Bearer ${e}`);const a=[x,s,{parser:D,withCredentials:!0,transportOptions:{polling:{extraHeaders:i}}}];this.socket=r.default(c,f.all(a))}connect(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectAttempts=0),this.offInternalHandlers(),this.on("connect_ack",this.handleConnectAck),this.socket.on("disconnect",this.handleDisconnect),this.on("connect_error",this.handleConnectError),this.socket.auth&&this.sessionIdKey in this.socket.auth&&(this.socket.auth={}),this.socket.connect()}retryConnect(){if(!(this.socket.connected||this.socket.active||this.reconnectAttempts>=this.maxReconnectAttempts))if(this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0),this.reconnectAttempts<this.maxReconnectAttempts){const t=Math.min(1e3*2**this.reconnectAttempts,this.maxReconnectDelay);console.info(`[Copilot SDK] Retry #${this.reconnectAttempts+1} in ${t}ms...`),this.reconnectTimeout=setTimeout((()=>{this.socket.connected||this.socket.active||(this.reconnectAttempts++,this.reconnect())}),t)}else console.error("[Copilot SDK] Max reconnect attempts reached.")}reconnect(){this.socket.connected||this.socket.active||this.reconnectAttempts>=this.maxReconnectAttempts||(this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectAttempts=0),this.socket.connect())}async browse(t,e){return this.asyncResponse("copilot_browse",t,e)}async search(t,e){return this.asyncResponse("copilot_search",t,e)}async facetedNavigation(t,e){return this.asyncResponse("faceted_navigation",t,e)}cancelRequest(t,e){return this.asyncResponse("cancel",t,e)}conversationReset(t,e){return this.asyncResponse("conversation_reset",t,e)}async productView(t,e){return this.asyncResponse("product_view",t,e)}async askCim(t,e){return this.asyncResponse("ask_cim",t,e)}async requestSessionInformation(t){return new Promise((e=>{this.socket.emit("session_info",(n=>{t&&t(n),e(n)}))}))}async getConversationEvents(t,e){return new Promise((n=>{this.socket.emit("conversation_events",t,(t=>{e&&e(t),n(t)}))}))}on(t,e){return this.socket.on(t,e),e}once(t,e){this.socket.once(t,e)}off(t,e){this.socket.off(t,e)}disconnect(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0),this.offInternalHandlers(),this.socket.disconnect()}onDisconnect(t){this.socket.on("disconnect",t)}async asyncResponse(t,e,n){if(n)return void this.socket.emit(t,e,n);let r="";const o=async function*(t){const e=[];let n=!1,r=null;const o=await t({emit:t=>{e.push(t),r&&(r(),r=null)},cancel:()=>{n=!0}});try{for(;!n;)e.length>0?yield e.shift():await new Promise((t=>{r=t}));for(;e.length>0;)yield e.shift()}finally{await(o?.())}}((({emit:t,cancel:e})=>{const n=(n,o)=>{["done","error"].includes(o.name)&&e(),o.eventSourceId==r&&t(o)};return this.socket.onAny(n),async()=>{this.socket.offAny(n)}}));return{result:await new Promise(((n,o)=>this.socket.emit(t,e,(t=>{"error"===t.name?o(new p(t)):(r=t?.id,n(t))})))),events:o}}},t.CimulateCopilotException=p,t.RAW_PROPERTY_VALUES=S,Object.defineProperty(t,"__esModule",{value:!0})}));
2
- //# sourceMappingURL=bundle.cimulate.copilot-sdk.7dbeb4d0.umd.js.map