@lpextend/node-sdk 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2162 @@
1
+ 'use strict';
2
+
3
+ // src/types/index.ts
4
+ var LPExtendSDKError = class extends Error {
5
+ constructor(message, code, status, details) {
6
+ super(message);
7
+ this.code = code;
8
+ this.status = status;
9
+ this.details = details;
10
+ this.name = "LPExtendSDKError";
11
+ }
12
+ };
13
+ var ErrorCodes = {
14
+ /** Not running inside shell iframe */
15
+ NOT_IN_SHELL: "NOT_IN_SHELL",
16
+ /** SDK initialization failed */
17
+ INIT_FAILED: "INIT_FAILED",
18
+ /** App not registered or disabled */
19
+ APP_NOT_REGISTERED: "APP_NOT_REGISTERED",
20
+ /** Authentication failed */
21
+ UNAUTHORIZED: "UNAUTHORIZED",
22
+ /** Scope not granted - update app registration */
23
+ SCOPE_DENIED: "SCOPE_DENIED",
24
+ /** Resource not found */
25
+ NOT_FOUND: "NOT_FOUND",
26
+ /** API call failed */
27
+ API_ERROR: "API_ERROR",
28
+ /** Request timeout */
29
+ TIMEOUT: "TIMEOUT",
30
+ /** Invalid configuration */
31
+ INVALID_CONFIG: "INVALID_CONFIG",
32
+ /** Revision conflict - resource was modified */
33
+ REVISION_CONFLICT: "REVISION_CONFLICT",
34
+ /** Rate limit exceeded */
35
+ RATE_LIMITED: "RATE_LIMITED"
36
+ };
37
+
38
+ // src/domains.ts
39
+ var ZONE_MAP = {
40
+ va: "z1",
41
+ // US
42
+ lo: "z2",
43
+ // EU
44
+ sy: "z3"
45
+ // AU/APAC
46
+ };
47
+ var GEO_MAP = {
48
+ z1: "p-us",
49
+ z2: "p-eu",
50
+ z3: "p-au"
51
+ };
52
+ var domainCache = /* @__PURE__ */ new Map();
53
+ var CACHE_TTL_MS = 60 * 60 * 1e3;
54
+ var DomainResolver = class {
55
+ constructor(accountId) {
56
+ this.region = null;
57
+ this.zone = null;
58
+ this.geo = null;
59
+ this.accountId = accountId;
60
+ }
61
+ /**
62
+ * Get domain for a specific LP service
63
+ */
64
+ async getDomain(service) {
65
+ const domains = await this.getDomains();
66
+ const domain = domains.find((d) => d.service === service);
67
+ return domain?.baseURI || null;
68
+ }
69
+ /**
70
+ * Get all domains for the account
71
+ */
72
+ async getDomains() {
73
+ const cached = domainCache.get(this.accountId);
74
+ if (cached && cached.expires > Date.now()) {
75
+ return cached.domains;
76
+ }
77
+ const response = await fetch(
78
+ `https://api.liveperson.net/api/account/${this.accountId}/service/baseURI.json?version=1.0`,
79
+ {
80
+ headers: {
81
+ "Content-Type": "application/json"
82
+ }
83
+ }
84
+ );
85
+ if (!response.ok) {
86
+ throw new Error(`Failed to fetch domains: ${response.status} ${response.statusText}`);
87
+ }
88
+ const data = await response.json();
89
+ const domains = data.baseURIs || [];
90
+ const asyncMessagingEnt = domains.find((d) => d.service === "asyncMessagingEnt");
91
+ if (asyncMessagingEnt) {
92
+ this.region = asyncMessagingEnt.baseURI.split(".")[0];
93
+ this.zone = ZONE_MAP[this.region] || null;
94
+ this.geo = this.zone ? GEO_MAP[this.zone] : null;
95
+ if (this.zone && this.region && this.geo) {
96
+ const additionalDomains = this.getAdditionalDomains();
97
+ for (const additional of additionalDomains) {
98
+ if (!domains.find((d) => d.service === additional.service)) {
99
+ domains.push(additional);
100
+ }
101
+ }
102
+ }
103
+ }
104
+ domainCache.set(this.accountId, {
105
+ domains,
106
+ expires: Date.now() + CACHE_TTL_MS
107
+ });
108
+ return domains;
109
+ }
110
+ /**
111
+ * Get additional domains not in CSDS
112
+ */
113
+ getAdditionalDomains() {
114
+ if (!this.zone || !this.region || !this.geo) {
115
+ return [];
116
+ }
117
+ return [
118
+ {
119
+ account: this.accountId,
120
+ service: "aiStudioPlatformService",
121
+ baseURI: `aistudio-${this.geo}.liveperson.net`
122
+ },
123
+ {
124
+ account: this.accountId,
125
+ service: "proactive",
126
+ baseURI: `proactive-messaging.${this.zone}.fs.liveperson.com`
127
+ },
128
+ {
129
+ account: this.accountId,
130
+ service: "botlogs",
131
+ baseURI: `${this.region}.bc-bot.liveperson.net`
132
+ },
133
+ {
134
+ account: this.accountId,
135
+ service: "bot",
136
+ baseURI: `${this.region}.bc-bot.liveperson.net`
137
+ },
138
+ {
139
+ account: this.accountId,
140
+ service: "botPlatform",
141
+ baseURI: `${this.region}.bc-platform.liveperson.net`
142
+ },
143
+ {
144
+ account: this.accountId,
145
+ service: "kb",
146
+ baseURI: `${this.region}.bc-kb.liveperson.net`
147
+ },
148
+ {
149
+ account: this.accountId,
150
+ service: "context",
151
+ baseURI: `${this.region}.context.liveperson.net`
152
+ },
153
+ {
154
+ account: this.accountId,
155
+ service: "recommendation",
156
+ baseURI: `${this.zone}.askmaven.liveperson.net`
157
+ },
158
+ {
159
+ account: this.accountId,
160
+ service: "proactiveHandoff",
161
+ baseURI: `${this.region}.handoff.liveperson.net`
162
+ },
163
+ {
164
+ account: this.accountId,
165
+ service: "convBuild",
166
+ baseURI: `${this.region}.bc-sso.liveperson.net`
167
+ },
168
+ {
169
+ account: this.accountId,
170
+ service: "bcmgmt",
171
+ baseURI: `${this.region}.bc-mgmt.liveperson.net`
172
+ },
173
+ {
174
+ account: this.accountId,
175
+ service: "bcintg",
176
+ baseURI: `${this.region}.bc-intg.liveperson.net`
177
+ },
178
+ {
179
+ account: this.accountId,
180
+ service: "bcnlu",
181
+ baseURI: `${this.region}.bc-nlu.liveperson.net`
182
+ },
183
+ {
184
+ account: this.accountId,
185
+ service: "promptlibrary",
186
+ baseURI: `${this.geo}.promptlibrary.liveperson.net`
187
+ }
188
+ ];
189
+ }
190
+ /**
191
+ * Clear cached domains for this account
192
+ */
193
+ clearCache() {
194
+ domainCache.delete(this.accountId);
195
+ }
196
+ };
197
+
198
+ // src/http.ts
199
+ var SCOPE_CONFIG = {
200
+ // Account Configuration APIs (Bearer auth)
201
+ skills: { service: "accountConfigReadOnly", pathPrefix: "/le-users/skills", urlPattern: "accountConfig" },
202
+ users: { service: "accountConfigReadOnly", pathPrefix: "/le-users/users", urlPattern: "accountConfig" },
203
+ agentGroups: { service: "accountConfigReadOnly", pathPrefix: "/le-users/agentGroups", urlPattern: "accountConfig" },
204
+ profiles: { service: "accountConfigReadOnly", pathPrefix: "/le-users/profiles", urlPattern: "accountConfig" },
205
+ lobs: { service: "accountConfigReadOnly", pathPrefix: "/le-users/lobs", urlPattern: "accountConfig" },
206
+ predefinedContent: { service: "accountConfigReadOnly", pathPrefix: "/le-predefined-content/predefinedContent", urlPattern: "accountConfig" },
207
+ automaticMessages: { service: "accountConfigReadOnly", pathPrefix: "/le-campaigns/automatic-messages", urlPattern: "accountConfig" },
208
+ workingHours: { service: "accountConfigReadOnly", pathPrefix: "/le-users/working-hours", urlPattern: "accountConfig" },
209
+ specialOccasions: { service: "accountConfigReadOnly", pathPrefix: "/le-users/special-occasions", urlPattern: "accountConfig" },
210
+ campaigns: { service: "accountConfigReadOnly", pathPrefix: "/le-campaigns/campaigns", urlPattern: "accountConfig" },
211
+ engagements: { service: "accountConfigReadOnly", pathPrefix: "/le-campaigns/campaigns", urlPattern: "accountConfig" },
212
+ // AI Studio APIs (CC-Bearer auth)
213
+ aiStudio: { service: "aiStudioPlatformService", pathPrefix: "", authType: "cc-bearer", urlPattern: "aiStudio" },
214
+ promptLibrary: { service: "aiStudioPlatformService", pathPrefix: "", authType: "cc-bearer", urlPattern: "aiStudio" },
215
+ // Messaging APIs
216
+ messagingHistory: { service: "msgHist", pathPrefix: "/messaging_history/api/account", urlPattern: "messaging" },
217
+ messagingOperations: { service: "asyncMessagingEnt", pathPrefix: "/api/account", urlPattern: "messaging" },
218
+ connectToMessaging: { service: "asyncMessagingEnt", pathPrefix: "/api/account", urlPattern: "messaging" },
219
+ agentMetrics: { service: "leDataReporting", pathPrefix: "/operations/api/account", urlPattern: "messaging" },
220
+ agentActivity: { service: "leDataReporting", pathPrefix: "/operations/api/account", urlPattern: "messaging" },
221
+ outboundReporting: { service: "leDataReporting", pathPrefix: "/operations/api/account", urlPattern: "messaging" },
222
+ // Other LP APIs
223
+ conversationOrchestrator: { service: "maven", pathPrefix: "/v1/account", urlPattern: "messaging" },
224
+ faas: { service: "faasUI", pathPrefix: "/api/account", urlPattern: "messaging" },
225
+ proactiveMessaging: { service: "proactive", pathPrefix: "/api", urlPattern: "custom" },
226
+ // LP Prompt Library (separate from AI Studio Prompt Library)
227
+ prompts: { service: "promptlibrary", pathPrefix: "/v2", urlPattern: "prompts" }
228
+ };
229
+ var WRITE_SERVICE = "accountConfigReadWrite";
230
+ var HTTPClient = class {
231
+ constructor(accountId, accessToken, defaultTimeout, debug) {
232
+ this.accountId = accountId;
233
+ this.accessToken = accessToken;
234
+ this.defaultTimeout = defaultTimeout;
235
+ this.debug = debug;
236
+ this.domainResolver = new DomainResolver(accountId);
237
+ }
238
+ /**
239
+ * Make a GET request
240
+ */
241
+ async get(path, options) {
242
+ return this.request("GET", path, options);
243
+ }
244
+ /**
245
+ * Make a POST request
246
+ */
247
+ async post(path, body, options) {
248
+ return this.request("POST", path, { ...options, body });
249
+ }
250
+ /**
251
+ * Make a PUT request
252
+ */
253
+ async put(path, body, options) {
254
+ return this.request("PUT", path, { ...options, body });
255
+ }
256
+ /**
257
+ * Make a DELETE request
258
+ */
259
+ async delete(path, options) {
260
+ return this.request("DELETE", path, options);
261
+ }
262
+ /**
263
+ * Make a PATCH request
264
+ */
265
+ async patch(path, body, options) {
266
+ return this.request("PATCH", path, { ...options, body });
267
+ }
268
+ /**
269
+ * Create a scoped client for a specific API domain
270
+ * This allows setting default options like authMode for all requests
271
+ */
272
+ withDefaults(defaults) {
273
+ return new ScopedHTTPClient(this, defaults);
274
+ }
275
+ /**
276
+ * Build the full URL for an LP API endpoint
277
+ */
278
+ async buildUrl(path, scopeConfig, isWrite) {
279
+ const serviceName = isWrite && scopeConfig.service.startsWith("accountConfig") ? WRITE_SERVICE : scopeConfig.service;
280
+ const domain = await this.domainResolver.getDomain(serviceName);
281
+ if (!domain) {
282
+ throw new LPExtendSDKError(
283
+ `Could not resolve domain for service: ${serviceName}`,
284
+ ErrorCodes.API_ERROR
285
+ );
286
+ }
287
+ let url;
288
+ switch (scopeConfig.urlPattern) {
289
+ case "accountConfig":
290
+ url = `https://${domain}/api/account/${this.accountId}/configuration${scopeConfig.pathPrefix}`;
291
+ break;
292
+ case "messaging":
293
+ url = `https://${domain}${scopeConfig.pathPrefix}/${this.accountId}`;
294
+ break;
295
+ case "aiStudio":
296
+ url = `https://${domain}/api/v2`;
297
+ break;
298
+ case "prompts":
299
+ url = `https://${domain}${scopeConfig.pathPrefix}`;
300
+ if (path.startsWith("/system")) {
301
+ url += `/system/prompts${path.substring("/system".length)}`;
302
+ return url;
303
+ } else if (path.startsWith("/account")) {
304
+ url += `/accounts/${this.accountId}/prompts${path.substring("/account".length)}`;
305
+ return url;
306
+ } else if (path.startsWith("/llm-providers")) {
307
+ url += `/accounts/${this.accountId}/configurations/llm-providers${path.substring("/llm-providers".length)}`;
308
+ return url;
309
+ }
310
+ break;
311
+ case "custom":
312
+ default:
313
+ url = `https://${domain}${scopeConfig.pathPrefix}`;
314
+ break;
315
+ }
316
+ if (path) {
317
+ url += path.startsWith("/") ? path : `/${path}`;
318
+ }
319
+ return url;
320
+ }
321
+ /**
322
+ * Determine scope from path
323
+ */
324
+ getScopeFromPath(path) {
325
+ const normalizedPath = path.startsWith("/") ? path.substring(1) : path;
326
+ const firstSegment = normalizedPath.split("/")[0];
327
+ if (firstSegment === "prompts") {
328
+ return "prompts";
329
+ }
330
+ if (firstSegment === "ai-studio" || normalizedPath.startsWith("ai-studio")) {
331
+ return "aiStudio";
332
+ }
333
+ if (firstSegment === "messaging") {
334
+ const secondSegment = normalizedPath.split("/")[1];
335
+ if (secondSegment === "history") return "messagingHistory";
336
+ if (secondSegment === "agent-metrics") return "agentMetrics";
337
+ if (secondSegment === "agent-activity") return "agentActivity";
338
+ if (secondSegment === "operations") return "messagingOperations";
339
+ if (secondSegment === "connect") return "connectToMessaging";
340
+ if (secondSegment === "outbound") return "outboundReporting";
341
+ return "messagingHistory";
342
+ }
343
+ const scopeMap = {
344
+ skills: "skills",
345
+ users: "users",
346
+ "agent-groups": "agentGroups",
347
+ profiles: "profiles",
348
+ lobs: "lobs",
349
+ campaigns: "campaigns",
350
+ engagements: "engagements",
351
+ "predefined-content": "predefinedContent",
352
+ "automatic-messages": "automaticMessages",
353
+ "working-hours": "workingHours",
354
+ "special-occasions": "specialOccasions"
355
+ };
356
+ return scopeMap[firstSegment] || firstSegment;
357
+ }
358
+ /**
359
+ * Make HTTP request to LP API
360
+ */
361
+ async request(method, path, options) {
362
+ const scope = this.getScopeFromPath(path);
363
+ const scopeConfig = SCOPE_CONFIG[scope];
364
+ if (!scopeConfig) {
365
+ throw new LPExtendSDKError(
366
+ `Unknown scope: ${scope}. Path: ${path}`,
367
+ ErrorCodes.SCOPE_DENIED
368
+ );
369
+ }
370
+ const isWrite = method !== "GET";
371
+ const pathWithoutScope = this.stripScopeFromPath(path, scope);
372
+ const url = await this.buildUrl(pathWithoutScope, scopeConfig, isWrite);
373
+ let fullUrl = url;
374
+ if (options?.params) {
375
+ const searchParams = new URLSearchParams();
376
+ Object.entries(options.params).forEach(([key, value]) => {
377
+ if (value !== void 0) {
378
+ searchParams.set(key, String(value));
379
+ }
380
+ });
381
+ const paramString = searchParams.toString();
382
+ if (paramString) {
383
+ fullUrl += (fullUrl.includes("?") ? "&" : "?") + paramString;
384
+ }
385
+ }
386
+ const authMode = options?.authMode || scopeConfig.authType || "bearer";
387
+ const authHeader = authMode === "cc-bearer" ? `CC-Bearer ${this.accessToken}` : `Bearer ${this.accessToken}`;
388
+ const headers = {
389
+ "Content-Type": "application/json",
390
+ Accept: "application/json",
391
+ Authorization: authHeader,
392
+ ...options?.headers
393
+ };
394
+ if (options?.revision) {
395
+ headers["If-Match"] = options.revision;
396
+ }
397
+ this.log(`${method} ${fullUrl}`, { scope, authMode });
398
+ const timeout = options?.timeout || this.defaultTimeout;
399
+ const controller = new AbortController();
400
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
401
+ try {
402
+ const response = await fetch(fullUrl, {
403
+ method,
404
+ headers,
405
+ body: options?.body ? JSON.stringify(options.body) : void 0,
406
+ signal: controller.signal
407
+ });
408
+ clearTimeout(timeoutId);
409
+ if (!response.ok) {
410
+ await this.handleError(response);
411
+ }
412
+ const contentType = response.headers.get("content-type");
413
+ const hasJsonBody = contentType?.includes("application/json");
414
+ let responseData;
415
+ if (hasJsonBody && response.status !== 204) {
416
+ responseData = await response.json();
417
+ }
418
+ const revision = response.headers.get("ac-revision") || response.headers.get("etag") || response.headers.get("x-revision") || void 0;
419
+ return {
420
+ data: responseData,
421
+ revision: revision || void 0
422
+ };
423
+ } catch (error) {
424
+ clearTimeout(timeoutId);
425
+ if (error.name === "AbortError") {
426
+ throw new LPExtendSDKError("Request timeout", ErrorCodes.TIMEOUT);
427
+ }
428
+ if (error instanceof LPExtendSDKError) {
429
+ throw error;
430
+ }
431
+ throw new LPExtendSDKError(error.message, ErrorCodes.API_ERROR);
432
+ }
433
+ }
434
+ /**
435
+ * Strip the scope prefix from the path
436
+ */
437
+ stripScopeFromPath(path, scope) {
438
+ const normalizedPath = path.startsWith("/") ? path.substring(1) : path;
439
+ const prefixMap = {
440
+ skills: ["skills"],
441
+ users: ["users"],
442
+ agentGroups: ["agent-groups"],
443
+ profiles: ["profiles"],
444
+ lobs: ["lobs"],
445
+ campaigns: ["campaigns"],
446
+ engagements: ["engagements"],
447
+ predefinedContent: ["predefined-content"],
448
+ automaticMessages: ["automatic-messages"],
449
+ workingHours: ["working-hours"],
450
+ specialOccasions: ["special-occasions"],
451
+ aiStudio: ["ai-studio"],
452
+ messagingHistory: ["messaging/history"],
453
+ agentMetrics: ["messaging/agent-metrics"],
454
+ agentActivity: ["messaging/agent-activity"],
455
+ messagingOperations: ["messaging/operations"],
456
+ connectToMessaging: ["messaging/connect"],
457
+ outboundReporting: ["messaging/outbound"],
458
+ prompts: ["prompts"]
459
+ };
460
+ const prefixes = prefixMap[scope] || [];
461
+ for (const prefix of prefixes) {
462
+ if (normalizedPath.startsWith(prefix)) {
463
+ const remaining = normalizedPath.substring(prefix.length);
464
+ return remaining.startsWith("/") ? remaining : `/${remaining}`;
465
+ }
466
+ }
467
+ return path;
468
+ }
469
+ /**
470
+ * Handle HTTP error responses
471
+ */
472
+ async handleError(response) {
473
+ const errorBody = await response.json().catch(() => ({ message: "Unknown error" }));
474
+ switch (response.status) {
475
+ case 401:
476
+ throw new LPExtendSDKError(
477
+ "Authentication failed",
478
+ ErrorCodes.UNAUTHORIZED,
479
+ response.status,
480
+ errorBody
481
+ );
482
+ case 403:
483
+ throw new LPExtendSDKError(
484
+ errorBody.message || "Access denied",
485
+ ErrorCodes.SCOPE_DENIED,
486
+ response.status,
487
+ errorBody
488
+ );
489
+ case 404:
490
+ throw new LPExtendSDKError(
491
+ errorBody.message || "Resource not found",
492
+ ErrorCodes.NOT_FOUND,
493
+ response.status,
494
+ errorBody
495
+ );
496
+ case 409:
497
+ throw new LPExtendSDKError(
498
+ errorBody.message || "Revision conflict - resource was modified",
499
+ ErrorCodes.REVISION_CONFLICT,
500
+ response.status,
501
+ errorBody
502
+ );
503
+ case 429:
504
+ throw new LPExtendSDKError(
505
+ errorBody.message || "Rate limit exceeded",
506
+ ErrorCodes.RATE_LIMITED,
507
+ response.status,
508
+ errorBody
509
+ );
510
+ default:
511
+ throw new LPExtendSDKError(
512
+ `API Error: ${response.status} - ${errorBody.message || response.statusText}`,
513
+ ErrorCodes.API_ERROR,
514
+ response.status,
515
+ errorBody
516
+ );
517
+ }
518
+ }
519
+ /**
520
+ * Debug logging
521
+ */
522
+ log(...args) {
523
+ if (this.debug) {
524
+ console.log("[LP-Extend-SDK]", ...args);
525
+ }
526
+ }
527
+ };
528
+ var ScopedHTTPClient = class {
529
+ constructor(client, defaults) {
530
+ this.client = client;
531
+ this.defaults = defaults;
532
+ }
533
+ async get(path, options) {
534
+ return this.client.get(path, this.mergeOptions(options));
535
+ }
536
+ async post(path, body, options) {
537
+ return this.client.post(path, body, this.mergeOptions(options));
538
+ }
539
+ async put(path, body, options) {
540
+ return this.client.put(path, body, this.mergeOptions(options));
541
+ }
542
+ async delete(path, options) {
543
+ return this.client.delete(path, this.mergeOptions(options));
544
+ }
545
+ async patch(path, body, options) {
546
+ return this.client.patch(path, body, this.mergeOptions(options));
547
+ }
548
+ mergeOptions(options) {
549
+ return {
550
+ ...this.defaults,
551
+ ...options,
552
+ headers: {
553
+ ...this.defaults.headers,
554
+ ...options?.headers
555
+ }
556
+ };
557
+ }
558
+ };
559
+
560
+ // src/api/account-config.api.ts
561
+ var SkillsAPI = class {
562
+ constructor(http) {
563
+ this.http = http;
564
+ }
565
+ /**
566
+ * Get all skills
567
+ */
568
+ async getAll() {
569
+ return this.http.get("/skills");
570
+ }
571
+ /**
572
+ * Get a skill by ID
573
+ */
574
+ async getById(skillId) {
575
+ return this.http.get(`/skills/${skillId}`);
576
+ }
577
+ /**
578
+ * Create a new skill
579
+ */
580
+ async create(skill) {
581
+ return this.http.post("/skills", skill);
582
+ }
583
+ /**
584
+ * Update a skill
585
+ * @param skillId - The skill ID
586
+ * @param skill - Updated skill data
587
+ * @param revision - Optional revision for optimistic locking (auto-fetched if not provided)
588
+ */
589
+ async update(skillId, skill, revision) {
590
+ const rev = revision || (await this.getAll()).revision;
591
+ return this.http.put(`/skills/${skillId}`, skill, { revision: rev });
592
+ }
593
+ /**
594
+ * Delete a skill
595
+ * @param skillId - The skill ID
596
+ * @param revision - Optional revision for optimistic locking (auto-fetched if not provided)
597
+ */
598
+ async delete(skillId, revision) {
599
+ const rev = revision || (await this.getAll()).revision;
600
+ return this.http.delete(`/skills/${skillId}`, { revision: rev });
601
+ }
602
+ };
603
+ var UsersAPI = class {
604
+ constructor(http) {
605
+ this.http = http;
606
+ }
607
+ /**
608
+ * Get all users
609
+ */
610
+ async getAll() {
611
+ return this.http.get("/users");
612
+ }
613
+ /**
614
+ * Get a user by ID
615
+ */
616
+ async getById(userId) {
617
+ return this.http.get(`/users/${userId}`);
618
+ }
619
+ /**
620
+ * Create a new user
621
+ */
622
+ async create(user) {
623
+ return this.http.post("/users", user);
624
+ }
625
+ /**
626
+ * Update a user
627
+ * @param userId - The user ID
628
+ * @param user - Updated user data
629
+ * @param revision - Optional revision for optimistic locking (auto-fetched if not provided)
630
+ */
631
+ async update(userId, user, revision) {
632
+ const rev = revision || (await this.getAll()).revision;
633
+ return this.http.put(`/users/${userId}`, user, { revision: rev });
634
+ }
635
+ /**
636
+ * Delete a user
637
+ * @param userId - The user ID
638
+ * @param revision - Optional revision for optimistic locking (auto-fetched if not provided)
639
+ */
640
+ async delete(userId, revision) {
641
+ const rev = revision || (await this.getAll()).revision;
642
+ return this.http.delete(`/users/${userId}`, { revision: rev });
643
+ }
644
+ /**
645
+ * Get the current authenticated user
646
+ */
647
+ async getSelf() {
648
+ return this.http.get("/users/self");
649
+ }
650
+ };
651
+ var AgentGroupsAPI = class {
652
+ constructor(http) {
653
+ this.http = http;
654
+ }
655
+ /**
656
+ * Get all agent groups
657
+ */
658
+ async getAll() {
659
+ return this.http.get("/agent-groups");
660
+ }
661
+ /**
662
+ * Get an agent group by ID
663
+ */
664
+ async getById(groupId) {
665
+ return this.http.get(`/agent-groups/${groupId}`);
666
+ }
667
+ /**
668
+ * Create a new agent group
669
+ */
670
+ async create(group) {
671
+ return this.http.post("/agent-groups", group);
672
+ }
673
+ /**
674
+ * Update an agent group
675
+ * @param revision - Optional revision for optimistic locking (auto-fetched if not provided)
676
+ */
677
+ async update(groupId, group, revision) {
678
+ const rev = revision || (await this.getAll()).revision;
679
+ return this.http.put(`/agent-groups/${groupId}`, group, { revision: rev });
680
+ }
681
+ /**
682
+ * Delete an agent group
683
+ * @param revision - Optional revision for optimistic locking (auto-fetched if not provided)
684
+ */
685
+ async delete(groupId, revision) {
686
+ const rev = revision || (await this.getAll()).revision;
687
+ return this.http.delete(`/agent-groups/${groupId}`, { revision: rev });
688
+ }
689
+ };
690
+ var ProfilesAPI = class {
691
+ constructor(http) {
692
+ this.http = http;
693
+ }
694
+ /**
695
+ * Get all profiles
696
+ */
697
+ async getAll() {
698
+ return this.http.get("/profiles");
699
+ }
700
+ /**
701
+ * Get a profile by ID
702
+ */
703
+ async getById(profileId) {
704
+ return this.http.get(`/profiles/${profileId}`);
705
+ }
706
+ /**
707
+ * Create a new profile
708
+ */
709
+ async create(profile) {
710
+ return this.http.post("/profiles", profile);
711
+ }
712
+ /**
713
+ * Update a profile
714
+ * @param revision - Optional revision for optimistic locking (auto-fetched if not provided)
715
+ */
716
+ async update(profileId, profile, revision) {
717
+ const rev = revision || (await this.getAll()).revision;
718
+ return this.http.put(`/profiles/${profileId}`, profile, { revision: rev });
719
+ }
720
+ /**
721
+ * Delete a profile
722
+ * @param revision - Optional revision for optimistic locking (auto-fetched if not provided)
723
+ */
724
+ async delete(profileId, revision) {
725
+ const rev = revision || (await this.getAll()).revision;
726
+ return this.http.delete(`/profiles/${profileId}`, { revision: rev });
727
+ }
728
+ };
729
+ var LOBsAPI = class {
730
+ constructor(http) {
731
+ this.http = http;
732
+ }
733
+ /**
734
+ * Get all LOBs
735
+ */
736
+ async getAll() {
737
+ return this.http.get("/lobs");
738
+ }
739
+ /**
740
+ * Get a LOB by ID
741
+ */
742
+ async getById(lobId) {
743
+ return this.http.get(`/lobs/${lobId}`);
744
+ }
745
+ /**
746
+ * Create a new LOB
747
+ */
748
+ async create(lob) {
749
+ return this.http.post("/lobs", lob);
750
+ }
751
+ /**
752
+ * Update a LOB
753
+ * @param revision - Optional revision for optimistic locking (auto-fetched if not provided)
754
+ */
755
+ async update(lobId, lob, revision) {
756
+ const rev = revision || (await this.getAll()).revision;
757
+ return this.http.put(`/lobs/${lobId}`, lob, { revision: rev });
758
+ }
759
+ /**
760
+ * Delete a LOB
761
+ * @param revision - Optional revision for optimistic locking (auto-fetched if not provided)
762
+ */
763
+ async delete(lobId, revision) {
764
+ const rev = revision || (await this.getAll()).revision;
765
+ return this.http.delete(`/lobs/${lobId}`, { revision: rev });
766
+ }
767
+ };
768
+ var CampaignsAPI = class {
769
+ constructor(http) {
770
+ this.http = http;
771
+ }
772
+ /**
773
+ * Get all campaigns
774
+ */
775
+ async getAll() {
776
+ return this.http.get("/campaigns");
777
+ }
778
+ /**
779
+ * Get a campaign by ID
780
+ */
781
+ async getById(campaignId) {
782
+ return this.http.get(`/campaigns/${campaignId}`);
783
+ }
784
+ /**
785
+ * Create a new campaign
786
+ */
787
+ async create(campaign) {
788
+ return this.http.post("/campaigns", campaign);
789
+ }
790
+ /**
791
+ * Update a campaign
792
+ * @param revision - Optional revision for optimistic locking (auto-fetched if not provided)
793
+ */
794
+ async update(campaignId, campaign, revision) {
795
+ const rev = revision || (await this.getAll()).revision;
796
+ return this.http.put(`/campaigns/${campaignId}`, campaign, { revision: rev });
797
+ }
798
+ /**
799
+ * Delete a campaign
800
+ * @param revision - Optional revision for optimistic locking (auto-fetched if not provided)
801
+ */
802
+ async delete(campaignId, revision) {
803
+ const rev = revision || (await this.getAll()).revision;
804
+ return this.http.delete(`/campaigns/${campaignId}`, { revision: rev });
805
+ }
806
+ };
807
+ var EngagementsAPI = class {
808
+ constructor(http) {
809
+ this.http = http;
810
+ }
811
+ /**
812
+ * Get all engagements for a campaign
813
+ */
814
+ async getByCampaign(campaignId) {
815
+ return this.http.get(`/campaigns/${campaignId}/engagements`);
816
+ }
817
+ /**
818
+ * Get an engagement by ID
819
+ */
820
+ async getById(campaignId, engagementId) {
821
+ return this.http.get(`/campaigns/${campaignId}/engagements/${engagementId}`);
822
+ }
823
+ /**
824
+ * Create a new engagement
825
+ */
826
+ async create(engagement) {
827
+ return this.http.post(`/campaigns/${engagement.campaignId}/engagements`, engagement);
828
+ }
829
+ /**
830
+ * Update an engagement
831
+ * @param revision - Optional revision for optimistic locking (auto-fetched if not provided)
832
+ */
833
+ async update(campaignId, engagementId, engagement, revision) {
834
+ const rev = revision || (await this.getByCampaign(campaignId)).revision;
835
+ return this.http.put(`/campaigns/${campaignId}/engagements/${engagementId}`, engagement, { revision: rev });
836
+ }
837
+ /**
838
+ * Delete an engagement
839
+ * @param revision - Optional revision for optimistic locking (auto-fetched if not provided)
840
+ */
841
+ async delete(campaignId, engagementId, revision) {
842
+ const rev = revision || (await this.getByCampaign(campaignId)).revision;
843
+ return this.http.delete(`/campaigns/${campaignId}/engagements/${engagementId}`, { revision: rev });
844
+ }
845
+ };
846
+ var PredefinedContentAPI = class {
847
+ constructor(http) {
848
+ this.http = http;
849
+ }
850
+ /**
851
+ * Get all predefined content
852
+ */
853
+ async getAll() {
854
+ return this.http.get("/predefined-content");
855
+ }
856
+ /**
857
+ * Get predefined content by ID
858
+ */
859
+ async getById(contentId) {
860
+ return this.http.get(`/predefined-content/${contentId}`);
861
+ }
862
+ /**
863
+ * Create new predefined content
864
+ */
865
+ async create(content) {
866
+ return this.http.post("/predefined-content", content);
867
+ }
868
+ /**
869
+ * Update predefined content
870
+ * @param revision - Optional revision for optimistic locking (auto-fetched if not provided)
871
+ */
872
+ async update(contentId, content, revision) {
873
+ const rev = revision || (await this.getAll()).revision;
874
+ return this.http.put(`/predefined-content/${contentId}`, content, { revision: rev });
875
+ }
876
+ /**
877
+ * Delete predefined content
878
+ * @param revision - Optional revision for optimistic locking (auto-fetched if not provided)
879
+ */
880
+ async delete(contentId, revision) {
881
+ const rev = revision || (await this.getAll()).revision;
882
+ return this.http.delete(`/predefined-content/${contentId}`, { revision: rev });
883
+ }
884
+ };
885
+ var AutomaticMessagesAPI = class {
886
+ constructor(http) {
887
+ this.http = http;
888
+ }
889
+ /**
890
+ * Get all automatic messages
891
+ */
892
+ async getAll() {
893
+ return this.http.get("/automatic-messages");
894
+ }
895
+ /**
896
+ * Get an automatic message by ID
897
+ */
898
+ async getById(messageId) {
899
+ return this.http.get(`/automatic-messages/${messageId}`);
900
+ }
901
+ /**
902
+ * Create a new automatic message
903
+ */
904
+ async create(message) {
905
+ return this.http.post("/automatic-messages", message);
906
+ }
907
+ /**
908
+ * Update an automatic message
909
+ * @param revision - Optional revision for optimistic locking (auto-fetched if not provided)
910
+ */
911
+ async update(messageId, message, revision) {
912
+ const rev = revision || (await this.getAll()).revision;
913
+ return this.http.put(`/automatic-messages/${messageId}`, message, { revision: rev });
914
+ }
915
+ /**
916
+ * Delete an automatic message
917
+ * @param revision - Optional revision for optimistic locking (auto-fetched if not provided)
918
+ */
919
+ async delete(messageId, revision) {
920
+ const rev = revision || (await this.getAll()).revision;
921
+ return this.http.delete(`/automatic-messages/${messageId}`, { revision: rev });
922
+ }
923
+ };
924
+ var WorkingHoursAPI = class {
925
+ constructor(http) {
926
+ this.http = http;
927
+ }
928
+ /**
929
+ * Get all working hours schedules
930
+ */
931
+ async getAll() {
932
+ return this.http.get("/working-hours");
933
+ }
934
+ /**
935
+ * Get working hours by ID
936
+ */
937
+ async getById(scheduleId) {
938
+ return this.http.get(`/working-hours/${scheduleId}`);
939
+ }
940
+ /**
941
+ * Create new working hours schedule
942
+ */
943
+ async create(schedule) {
944
+ return this.http.post("/working-hours", schedule);
945
+ }
946
+ /**
947
+ * Update working hours schedule
948
+ * @param revision - Optional revision for optimistic locking (auto-fetched if not provided)
949
+ */
950
+ async update(scheduleId, schedule, revision) {
951
+ const rev = revision || (await this.getAll()).revision;
952
+ return this.http.put(`/working-hours/${scheduleId}`, schedule, { revision: rev });
953
+ }
954
+ /**
955
+ * Delete working hours schedule
956
+ * @param revision - Optional revision for optimistic locking (auto-fetched if not provided)
957
+ */
958
+ async delete(scheduleId, revision) {
959
+ const rev = revision || (await this.getAll()).revision;
960
+ return this.http.delete(`/working-hours/${scheduleId}`, { revision: rev });
961
+ }
962
+ };
963
+ var SpecialOccasionsAPI = class {
964
+ constructor(http) {
965
+ this.http = http;
966
+ }
967
+ /**
968
+ * Get all special occasions
969
+ */
970
+ async getAll() {
971
+ return this.http.get("/special-occasions");
972
+ }
973
+ /**
974
+ * Get a special occasion by ID
975
+ */
976
+ async getById(occasionId) {
977
+ return this.http.get(`/special-occasions/${occasionId}`);
978
+ }
979
+ /**
980
+ * Create a new special occasion
981
+ */
982
+ async create(occasion) {
983
+ return this.http.post("/special-occasions", occasion);
984
+ }
985
+ /**
986
+ * Update a special occasion
987
+ * @param revision - Optional revision for optimistic locking (auto-fetched if not provided)
988
+ */
989
+ async update(occasionId, occasion, revision) {
990
+ const rev = revision || (await this.getAll()).revision;
991
+ return this.http.put(`/special-occasions/${occasionId}`, occasion, { revision: rev });
992
+ }
993
+ /**
994
+ * Delete a special occasion
995
+ * @param revision - Optional revision for optimistic locking (auto-fetched if not provided)
996
+ */
997
+ async delete(occasionId, revision) {
998
+ const rev = revision || (await this.getAll()).revision;
999
+ return this.http.delete(`/special-occasions/${occasionId}`, { revision: rev });
1000
+ }
1001
+ };
1002
+
1003
+ // src/api/ai-studio.api.ts
1004
+ var CategoriesAPI = class {
1005
+ constructor(http) {
1006
+ this.http = http;
1007
+ }
1008
+ async getAll() {
1009
+ return this.http.get("/ai-studio/categories");
1010
+ }
1011
+ async create(data) {
1012
+ return this.http.post("/ai-studio/categories", data);
1013
+ }
1014
+ async update(categoryId, data) {
1015
+ return this.http.put(`/ai-studio/categories/${categoryId}`, data);
1016
+ }
1017
+ async delete(categoryId) {
1018
+ return this.http.delete(`/ai-studio/categories/${categoryId}`);
1019
+ }
1020
+ };
1021
+ var ConversationsAPI = class {
1022
+ constructor(http) {
1023
+ this.http = http;
1024
+ }
1025
+ async getAll(params) {
1026
+ return this.http.get("/ai-studio/conversations", { params });
1027
+ }
1028
+ async getById(convId) {
1029
+ return this.http.get(`/ai-studio/conversations/${convId}`);
1030
+ }
1031
+ async create(data) {
1032
+ return this.http.post("/ai-studio/conversations", data);
1033
+ }
1034
+ async update(convId, data) {
1035
+ return this.http.put(`/ai-studio/conversations/${convId}`, data);
1036
+ }
1037
+ async delete(convId) {
1038
+ return this.http.delete(`/ai-studio/conversations/${convId}`);
1039
+ }
1040
+ async updateAttributes(convId, data) {
1041
+ return this.http.put(`/ai-studio/conversations/${convId}/attributes`, data);
1042
+ }
1043
+ async close(convId) {
1044
+ return this.http.patch(`/ai-studio/conversations/${convId}/close`);
1045
+ }
1046
+ async export(params) {
1047
+ return this.http.get("/ai-studio/conversations/export", { params });
1048
+ }
1049
+ async upload(conversations) {
1050
+ return this.http.post("/ai-studio/conversations/upload", { conversations });
1051
+ }
1052
+ };
1053
+ var SummaryAPI = class {
1054
+ constructor(http) {
1055
+ this.http = http;
1056
+ }
1057
+ async create(data) {
1058
+ return this.http.post("/ai-studio/summary", data);
1059
+ }
1060
+ async createBatch(data) {
1061
+ return this.http.post("/ai-studio/summary/batch", data);
1062
+ }
1063
+ async getBatch(offset, limit) {
1064
+ return this.http.get("/ai-studio/summary/batch", { params: { offset, limit } });
1065
+ }
1066
+ async getBatchById(summaryId) {
1067
+ return this.http.get(`/ai-studio/summary/batch/${summaryId}`);
1068
+ }
1069
+ async deleteBatch(summaryId) {
1070
+ return this.http.delete(`/ai-studio/summary/batch/${summaryId}`);
1071
+ }
1072
+ };
1073
+ var QueryAPI = class {
1074
+ constructor(http) {
1075
+ this.http = http;
1076
+ }
1077
+ async generate(data) {
1078
+ return this.http.post("/ai-studio/query", data);
1079
+ }
1080
+ };
1081
+ var SimulationsAPI = class {
1082
+ constructor(http) {
1083
+ this.http = http;
1084
+ }
1085
+ async getAll(params) {
1086
+ return this.http.get("/ai-studio/simulations", { params });
1087
+ }
1088
+ async getById(simulationId) {
1089
+ return this.http.get(`/ai-studio/simulations/${simulationId}`);
1090
+ }
1091
+ async create(data) {
1092
+ return this.http.post("/ai-studio/simulations", data);
1093
+ }
1094
+ async update(simulationId, data) {
1095
+ return this.http.put(`/ai-studio/simulations/${simulationId}`, data);
1096
+ }
1097
+ async delete(simulationId) {
1098
+ return this.http.delete(`/ai-studio/simulations/${simulationId}`);
1099
+ }
1100
+ async getStatus(simulationId) {
1101
+ return this.http.get(`/ai-studio/simulations/${simulationId}/status`);
1102
+ }
1103
+ async getJobResults(simulationId, jobId) {
1104
+ return this.http.get(`/ai-studio/simulations/${simulationId}/jobs/${jobId}`);
1105
+ }
1106
+ async cancel(simulationId) {
1107
+ return this.http.post(`/ai-studio/simulations/${simulationId}/cancel`);
1108
+ }
1109
+ };
1110
+ var TranscriptAnalysisAPI = class {
1111
+ constructor(http) {
1112
+ this.http = http;
1113
+ }
1114
+ async getAll(owner, limit, startAfterId) {
1115
+ return this.http.get("/ai-studio/transcript-analysis", {
1116
+ params: { owner, limit, start_after_id: startAfterId }
1117
+ });
1118
+ }
1119
+ async getById(analysisId, excludeConversations, excludeQuestions) {
1120
+ return this.http.get(`/ai-studio/transcript-analysis/${analysisId}`, {
1121
+ params: { exclude_conversations: excludeConversations, exclude_questions: excludeQuestions }
1122
+ });
1123
+ }
1124
+ async create(data) {
1125
+ return this.http.post("/ai-studio/transcript-analysis", data);
1126
+ }
1127
+ async update(analysisId, data) {
1128
+ return this.http.put(`/ai-studio/transcript-analysis/${analysisId}`, data);
1129
+ }
1130
+ async delete(analysisId) {
1131
+ return this.http.delete(`/ai-studio/transcript-analysis/${analysisId}`);
1132
+ }
1133
+ };
1134
+ var KnowledgebasesAPI = class {
1135
+ constructor(http) {
1136
+ this.http = http;
1137
+ }
1138
+ async getAll() {
1139
+ return this.http.get("/ai-studio/knowledgebases");
1140
+ }
1141
+ async getKai() {
1142
+ return this.http.get("/ai-studio/knowledgebases/kai");
1143
+ }
1144
+ async getById(kbId) {
1145
+ return this.http.get(`/ai-studio/knowledgebases/${kbId}`);
1146
+ }
1147
+ async delete(kbId) {
1148
+ return this.http.delete(`/ai-studio/knowledgebases/${kbId}`);
1149
+ }
1150
+ async getHealth(kbId) {
1151
+ return this.http.get(`/ai-studio/knowledgebases/${kbId}/health`);
1152
+ }
1153
+ async refresh(kbId) {
1154
+ return this.http.get(`/ai-studio/knowledgebases/${kbId}/refresh`);
1155
+ }
1156
+ async search(kbId, data) {
1157
+ return this.http.post(`/ai-studio/knowledgebases/${kbId}/search`, data);
1158
+ }
1159
+ async getItems(kbId) {
1160
+ return this.http.get(`/ai-studio/knowledgebases/${kbId}/items`);
1161
+ }
1162
+ async getItemsBySource(kbId, sourceId) {
1163
+ return this.http.get(`/ai-studio/knowledgebases/${kbId}/items/${sourceId}`);
1164
+ }
1165
+ async createItems(kbId, sourceId, items) {
1166
+ return this.http.post(`/ai-studio/knowledgebases/${kbId}/items/${sourceId}`, items);
1167
+ }
1168
+ async updateItems(kbId, sourceId, items) {
1169
+ return this.http.put(`/ai-studio/knowledgebases/${kbId}/items/${sourceId}`, items);
1170
+ }
1171
+ async deleteItems(kbId, sourceId, itemIds) {
1172
+ return this.http.delete(`/ai-studio/knowledgebases/${kbId}/items/${sourceId}`, { body: itemIds });
1173
+ }
1174
+ };
1175
+ var EvaluatorsAPI = class {
1176
+ constructor(http) {
1177
+ this.http = http;
1178
+ }
1179
+ async similarity(evaluationType, data) {
1180
+ return this.http.post("/ai-studio/evaluators/similarity", data, {
1181
+ params: { type: evaluationType }
1182
+ });
1183
+ }
1184
+ async resolution(data) {
1185
+ return this.http.post("/ai-studio/evaluators/resolution", data);
1186
+ }
1187
+ async guidedRouting(data) {
1188
+ return this.http.post("/ai-studio/evaluators/guided-routing", data);
1189
+ }
1190
+ };
1191
+ var GeneratorsAPI = class {
1192
+ constructor(http) {
1193
+ this.http = http;
1194
+ }
1195
+ async qaFromModel(modelId) {
1196
+ return this.http.get(`/ai-studio/generators/qa/model/${modelId}`);
1197
+ }
1198
+ async qaFromKnowledgebase(kbIds, generateAnswers, useRandomSections) {
1199
+ return this.http.get("/ai-studio/generators/qa/knowledgebase", {
1200
+ params: { kb_id: kbIds.join(","), generate_answers: generateAnswers, use_random_sections: useRandomSections }
1201
+ });
1202
+ }
1203
+ async qaFromConversationCloud(data) {
1204
+ return this.http.post("/ai-studio/generators/qa/conversation-cloud", data);
1205
+ }
1206
+ async kaiRoutesLlm(data) {
1207
+ return this.http.post("/ai-studio/generators/routes/kai-llm", data);
1208
+ }
1209
+ async kaiRoutes(data) {
1210
+ return this.http.post("/ai-studio/generators/routes/kai", data);
1211
+ }
1212
+ async kaiRoutesStatus(flowId) {
1213
+ return this.http.get("/ai-studio/generators/routes/kai/status", {
1214
+ params: { flow_id: flowId }
1215
+ });
1216
+ }
1217
+ };
1218
+ var PromptLibraryAPI = class {
1219
+ constructor(http) {
1220
+ this.http = http;
1221
+ }
1222
+ async getAll() {
1223
+ return this.http.get("/ai-studio/prompt-library");
1224
+ }
1225
+ async create(data) {
1226
+ return this.http.post("/ai-studio/prompt-library", data);
1227
+ }
1228
+ async update(promptId, data) {
1229
+ return this.http.put(`/ai-studio/prompt-library/${promptId}`, data);
1230
+ }
1231
+ async getProviders() {
1232
+ return this.http.get("/ai-studio/prompt-library/providers");
1233
+ }
1234
+ async getSystemPrompts() {
1235
+ return this.http.get("/ai-studio/prompt-library/system");
1236
+ }
1237
+ };
1238
+ var AIStudioUsersAPI = class {
1239
+ constructor(http) {
1240
+ this.http = http;
1241
+ }
1242
+ async getSelf() {
1243
+ return this.http.get("/ai-studio/users/self");
1244
+ }
1245
+ async getAll() {
1246
+ return this.http.get("/ai-studio/users");
1247
+ }
1248
+ async getDetails() {
1249
+ return this.http.get("/ai-studio/users/details");
1250
+ }
1251
+ async create(data) {
1252
+ return this.http.post("/ai-studio/users", data);
1253
+ }
1254
+ async update(userId, data) {
1255
+ return this.http.put(`/ai-studio/users/${userId}`, data);
1256
+ }
1257
+ async delete(userId) {
1258
+ return this.http.delete(`/ai-studio/users/${userId}`);
1259
+ }
1260
+ async updateModels(userId, data) {
1261
+ return this.http.put(`/ai-studio/users/${userId}/models`, data);
1262
+ }
1263
+ async agreeToTerms(userId) {
1264
+ return this.http.get(`/ai-studio/users/${userId}/terms`);
1265
+ }
1266
+ };
1267
+ var FlowsAPI = class {
1268
+ constructor(http, accountId) {
1269
+ this.http = http;
1270
+ this.accountId = accountId;
1271
+ }
1272
+ /**
1273
+ * List all flows for the account
1274
+ * GET /api/v2/flows?account_id={accountId}
1275
+ */
1276
+ async getAll() {
1277
+ return this.http.get("/ai-studio/flows", {
1278
+ params: { account_id: this.accountId }
1279
+ });
1280
+ }
1281
+ /**
1282
+ * Get a specific flow by ID
1283
+ * GET /api/v2/flows/{flowId}
1284
+ */
1285
+ async getById(flowId) {
1286
+ return this.http.get(`/ai-studio/flows/${flowId}`);
1287
+ }
1288
+ /**
1289
+ * Invoke a flow
1290
+ * POST /api/v2/flows/{flowId}
1291
+ */
1292
+ async invoke(flowId, data) {
1293
+ return this.http.post(`/ai-studio/flows/${flowId}`, data);
1294
+ }
1295
+ /**
1296
+ * Invoke a promptless flow (quick response)
1297
+ * POST /api/v2/flows/response
1298
+ */
1299
+ async invokeWithResponse(prompt, messages, text) {
1300
+ const body = { prompt };
1301
+ if (messages) body.messages = messages;
1302
+ if (text) body.text = text;
1303
+ return this.http.post("/ai-studio/flows/response", body);
1304
+ }
1305
+ };
1306
+ var AIStudioAPI = class {
1307
+ constructor(http, accountId) {
1308
+ const scopedHttp = http.withDefaults({ authMode: "cc-bearer" });
1309
+ this.categories = new CategoriesAPI(scopedHttp);
1310
+ this.conversations = new ConversationsAPI(scopedHttp);
1311
+ this.summary = new SummaryAPI(scopedHttp);
1312
+ this.query = new QueryAPI(scopedHttp);
1313
+ this.simulations = new SimulationsAPI(scopedHttp);
1314
+ this.transcriptAnalysis = new TranscriptAnalysisAPI(scopedHttp);
1315
+ this.knowledgebases = new KnowledgebasesAPI(scopedHttp);
1316
+ this.evaluators = new EvaluatorsAPI(scopedHttp);
1317
+ this.generators = new GeneratorsAPI(scopedHttp);
1318
+ this.promptLibrary = new PromptLibraryAPI(scopedHttp);
1319
+ this.users = new AIStudioUsersAPI(scopedHttp);
1320
+ this.flows = new FlowsAPI(scopedHttp, accountId);
1321
+ }
1322
+ };
1323
+
1324
+ // src/api/messaging.api.ts
1325
+ var MessagingHistoryAPI = class {
1326
+ constructor(http) {
1327
+ this.http = http;
1328
+ }
1329
+ /**
1330
+ * Query messaging conversations
1331
+ */
1332
+ async query(params) {
1333
+ return this.http.post("/messaging/history", params);
1334
+ }
1335
+ /**
1336
+ * Get a single conversation by ID
1337
+ */
1338
+ async getConversation(conversationId) {
1339
+ return this.http.get(`/messaging/history/${conversationId}`);
1340
+ }
1341
+ /**
1342
+ * Get conversations by IDs (batch)
1343
+ */
1344
+ async getConversations(conversationIds) {
1345
+ return this.http.post("/messaging/history/batch", { conversationIds });
1346
+ }
1347
+ /**
1348
+ * Export conversations matching criteria
1349
+ */
1350
+ async export(params) {
1351
+ return this.http.post("/messaging/history/export", params);
1352
+ }
1353
+ };
1354
+ var AgentMetricsAPI = class {
1355
+ constructor(http) {
1356
+ this.http = http;
1357
+ }
1358
+ /**
1359
+ * Get current metrics for agents
1360
+ */
1361
+ async getMetrics(params) {
1362
+ return this.http.post("/messaging/agent-metrics", params || {});
1363
+ }
1364
+ /**
1365
+ * Get metrics for a specific agent
1366
+ */
1367
+ async getAgentMetrics(agentId) {
1368
+ return this.http.get(`/messaging/agent-metrics/${agentId}`);
1369
+ }
1370
+ /**
1371
+ * Get metrics summary by skill
1372
+ */
1373
+ async getBySkill(skillId) {
1374
+ return this.http.get(`/messaging/agent-metrics/skill/${skillId}`);
1375
+ }
1376
+ /**
1377
+ * Get metrics summary by agent group
1378
+ */
1379
+ async getByAgentGroup(groupId) {
1380
+ return this.http.get(`/messaging/agent-metrics/group/${groupId}`);
1381
+ }
1382
+ };
1383
+ var AgentActivityAPI = class {
1384
+ constructor(http) {
1385
+ this.http = http;
1386
+ }
1387
+ /**
1388
+ * Query agent activity
1389
+ */
1390
+ async query(params) {
1391
+ return this.http.post("/messaging/agent-activity", params);
1392
+ }
1393
+ /**
1394
+ * Get activity for a specific agent
1395
+ */
1396
+ async getAgentActivity(agentId, from, to) {
1397
+ return this.http.get(`/messaging/agent-activity/${agentId}`, {
1398
+ params: { from, to }
1399
+ });
1400
+ }
1401
+ };
1402
+ var MessagingOperationsAPI = class {
1403
+ constructor(http) {
1404
+ this.http = http;
1405
+ }
1406
+ /**
1407
+ * Transfer a conversation to another skill or agent
1408
+ */
1409
+ async transfer(request) {
1410
+ return this.http.post(`/messaging/operations/${request.conversationId}/transfer`, {
1411
+ targetSkillId: request.targetSkillId,
1412
+ targetAgentId: request.targetAgentId,
1413
+ reason: request.reason
1414
+ });
1415
+ }
1416
+ /**
1417
+ * Close a conversation
1418
+ */
1419
+ async close(request) {
1420
+ return this.http.post(`/messaging/operations/${request.conversationId}/close`, {
1421
+ closeReason: request.closeReason
1422
+ });
1423
+ }
1424
+ /**
1425
+ * Send a message to a conversation
1426
+ */
1427
+ async sendMessage(request) {
1428
+ return this.http.post(`/messaging/operations/${request.conversationId}/message`, {
1429
+ message: request.message,
1430
+ contentType: request.contentType,
1431
+ richContent: request.richContent
1432
+ });
1433
+ }
1434
+ /**
1435
+ * Set conversation priority
1436
+ */
1437
+ async setPriority(conversationId, priority) {
1438
+ return this.http.post(`/messaging/operations/${conversationId}/priority`, { priority });
1439
+ }
1440
+ /**
1441
+ * Set conversation TTR (Time To Respond)
1442
+ */
1443
+ async setTTR(conversationId, ttrType, value) {
1444
+ return this.http.post(`/messaging/operations/${conversationId}/ttr`, { ttrType, value });
1445
+ }
1446
+ };
1447
+ var ConnectToMessagingAPI = class {
1448
+ constructor(http) {
1449
+ this.http = http;
1450
+ }
1451
+ /**
1452
+ * Create a new conversation
1453
+ */
1454
+ async createConversation(request) {
1455
+ return this.http.post("/messaging/connect", request);
1456
+ }
1457
+ /**
1458
+ * Get available campaigns and engagements for creating conversations
1459
+ */
1460
+ async getAvailableEngagements() {
1461
+ return this.http.get("/messaging/connect/engagements");
1462
+ }
1463
+ };
1464
+ var OutboundReportingAPI = class {
1465
+ constructor(http) {
1466
+ this.http = http;
1467
+ }
1468
+ /**
1469
+ * Query outbound campaign reports
1470
+ */
1471
+ async query(params) {
1472
+ return this.http.post("/messaging/outbound/reports", params);
1473
+ }
1474
+ /**
1475
+ * Get report for a specific campaign
1476
+ */
1477
+ async getCampaignReport(campaignId, from, to) {
1478
+ return this.http.get(`/messaging/outbound/reports/${campaignId}`, {
1479
+ params: { from, to }
1480
+ });
1481
+ }
1482
+ /**
1483
+ * Get aggregate outbound stats
1484
+ */
1485
+ async getAggregateStats(from, to) {
1486
+ return this.http.get("/messaging/outbound/reports/aggregate", {
1487
+ params: { from, to }
1488
+ });
1489
+ }
1490
+ };
1491
+ var MessagingAPI = class {
1492
+ constructor(http) {
1493
+ this.history = new MessagingHistoryAPI(http);
1494
+ this.agentMetrics = new AgentMetricsAPI(http);
1495
+ this.agentActivity = new AgentActivityAPI(http);
1496
+ this.operations = new MessagingOperationsAPI(http);
1497
+ this.connect = new ConnectToMessagingAPI(http);
1498
+ this.outbound = new OutboundReportingAPI(http);
1499
+ }
1500
+ };
1501
+
1502
+ // src/api/sentinel.api.ts
1503
+ var SentinelAPI = class {
1504
+ constructor(http) {
1505
+ this.http = http;
1506
+ }
1507
+ /**
1508
+ * Get login URL for OAuth redirect
1509
+ *
1510
+ * Returns a URL to redirect the user to for LivePerson authentication.
1511
+ * After successful auth, user is redirected back with an authorization code.
1512
+ *
1513
+ * @returns Login URL for OAuth redirect
1514
+ *
1515
+ * @example
1516
+ * ```typescript
1517
+ * const { url } = await sdk.sentinel.getLoginUrl();
1518
+ * // Redirect user to LP login
1519
+ * window.location.href = url;
1520
+ * ```
1521
+ */
1522
+ async getLoginUrl() {
1523
+ const response = await this.http.get("/idp/login-url");
1524
+ return response.data;
1525
+ }
1526
+ /**
1527
+ * Exchange OAuth authorization code for access token
1528
+ *
1529
+ * After the user completes LP authentication and is redirected back,
1530
+ * use this method to exchange the authorization code for tokens.
1531
+ *
1532
+ * @param request - Token exchange request with code and redirect URI
1533
+ * @returns Token object with access token, refresh token, and user info
1534
+ *
1535
+ * @example
1536
+ * ```typescript
1537
+ * // Get code from URL params after redirect
1538
+ * const urlParams = new URLSearchParams(window.location.search);
1539
+ * const code = urlParams.get('code');
1540
+ *
1541
+ * const token = await sdk.sentinel.exchangeToken({
1542
+ * code,
1543
+ * redirect: window.location.origin + '/callback',
1544
+ * appname: 'my-app',
1545
+ * });
1546
+ *
1547
+ * // Store token for API calls
1548
+ * localStorage.setItem('lpToken', token.accessToken);
1549
+ * ```
1550
+ */
1551
+ async exchangeToken(request) {
1552
+ const response = await this.http.post("/idp/token", request);
1553
+ return response.data;
1554
+ }
1555
+ /**
1556
+ * Logout and revoke token
1557
+ *
1558
+ * Revokes the current access token, ending the user's session.
1559
+ *
1560
+ * @example
1561
+ * ```typescript
1562
+ * await sdk.sentinel.logout();
1563
+ * // Clear local storage and redirect to login
1564
+ * localStorage.removeItem('lpToken');
1565
+ * window.location.href = '/login';
1566
+ * ```
1567
+ */
1568
+ async logout() {
1569
+ await this.http.post("/idp/logout", {});
1570
+ }
1571
+ /**
1572
+ * Get LivePerson domains for the account
1573
+ *
1574
+ * Returns the domain URLs for various LP services.
1575
+ * Useful for making direct API calls to specific LP services.
1576
+ *
1577
+ * @returns Map of service names to domain URLs
1578
+ *
1579
+ * @example
1580
+ * ```typescript
1581
+ * const domains = await sdk.sentinel.getDomains();
1582
+ * console.log('Sentinel domain:', domains.sentinel);
1583
+ * console.log('Account Config domain:', domains.accountConfigReadOnly);
1584
+ * ```
1585
+ */
1586
+ async getDomains() {
1587
+ const response = await this.http.get("/idp/domains");
1588
+ return response.data;
1589
+ }
1590
+ /**
1591
+ * Authenticate with Conversation Builder
1592
+ *
1593
+ * Exchanges the LP access token for a CB-specific token.
1594
+ * Required for making Conversation Builder API calls.
1595
+ *
1596
+ * @returns CB authentication info with token and organization ID
1597
+ *
1598
+ * @example
1599
+ * ```typescript
1600
+ * const cbAuth = await sdk.sentinel.authenticateCB();
1601
+ * if (cbAuth.success) {
1602
+ * const cbToken = cbAuth.successResult.apiAccessToken;
1603
+ * const cbOrg = cbAuth.successResult.sessionOrganizationId;
1604
+ * // Use cbToken for CB API calls
1605
+ * }
1606
+ * ```
1607
+ */
1608
+ async authenticateCB() {
1609
+ const response = await this.http.get("/idp/authenticate-cb");
1610
+ return response.data;
1611
+ }
1612
+ };
1613
+
1614
+ // src/api/prompts.api.ts
1615
+ var LPPromptsAPI = class {
1616
+ constructor(http) {
1617
+ this.scopedHttp = http.withDefaults({
1618
+ params: { source: "ccui" }
1619
+ });
1620
+ }
1621
+ /**
1622
+ * Get all system prompts (read-only, provided by LivePerson)
1623
+ */
1624
+ async getSystemPrompts(params) {
1625
+ const response = await this.scopedHttp.get(
1626
+ "/prompts/system",
1627
+ { params }
1628
+ );
1629
+ const prompts = response.data?.successResult?.prompts || [];
1630
+ return {
1631
+ data: prompts,
1632
+ revision: response.revision
1633
+ };
1634
+ }
1635
+ /**
1636
+ * Get all account prompts
1637
+ */
1638
+ async getAccountPrompts(params) {
1639
+ const response = await this.scopedHttp.get(
1640
+ "/prompts/account",
1641
+ { params }
1642
+ );
1643
+ const prompts = response.data?.successResult?.prompts || [];
1644
+ return {
1645
+ data: prompts,
1646
+ revision: response.revision
1647
+ };
1648
+ }
1649
+ /**
1650
+ * Get a single account prompt by ID
1651
+ */
1652
+ async getById(promptId) {
1653
+ return this.scopedHttp.get(`/prompts/account/${promptId}`);
1654
+ }
1655
+ /**
1656
+ * Create a new account prompt
1657
+ */
1658
+ async create(prompt) {
1659
+ return this.scopedHttp.post("/prompts/account", prompt);
1660
+ }
1661
+ /**
1662
+ * Update an account prompt
1663
+ * @param promptId - The prompt ID
1664
+ * @param prompt - Updated prompt data
1665
+ */
1666
+ async update(promptId, prompt) {
1667
+ return this.scopedHttp.put(`/prompts/account/${promptId}`, prompt);
1668
+ }
1669
+ /**
1670
+ * Delete an account prompt
1671
+ * @param promptId - The prompt ID
1672
+ */
1673
+ async delete(promptId) {
1674
+ return this.scopedHttp.delete(`/prompts/account/${promptId}`);
1675
+ }
1676
+ /**
1677
+ * Get LLM provider subscriptions for the account
1678
+ */
1679
+ async getLLMProviders() {
1680
+ const response = await this.scopedHttp.get(
1681
+ "/prompts/llm-providers"
1682
+ );
1683
+ const providers = response.data?.successResult?.provider_subscriptions || [];
1684
+ return {
1685
+ data: providers,
1686
+ revision: response.revision
1687
+ };
1688
+ }
1689
+ };
1690
+
1691
+ // src/sdk.ts
1692
+ var LPExtendSDK = class {
1693
+ /**
1694
+ * Create SDK instance (use initializeSDK() instead for async init)
1695
+ */
1696
+ constructor(config, initResult) {
1697
+ this.config = config;
1698
+ this.debug = config.debug ?? false;
1699
+ this.grantedScopes = initResult.grantedScopes;
1700
+ this.appName = initResult.appName;
1701
+ const timeout = config.timeout ?? 3e4;
1702
+ this.http = new HTTPClient(
1703
+ config.accountId,
1704
+ config.accessToken,
1705
+ timeout,
1706
+ this.debug
1707
+ );
1708
+ this.skills = new SkillsAPI(this.http);
1709
+ this.users = new UsersAPI(this.http);
1710
+ this.agentGroups = new AgentGroupsAPI(this.http);
1711
+ this.profiles = new ProfilesAPI(this.http);
1712
+ this.lobs = new LOBsAPI(this.http);
1713
+ this.campaigns = new CampaignsAPI(this.http);
1714
+ this.engagements = new EngagementsAPI(this.http);
1715
+ this.predefinedContent = new PredefinedContentAPI(this.http);
1716
+ this.automaticMessages = new AutomaticMessagesAPI(this.http);
1717
+ this.workingHours = new WorkingHoursAPI(this.http);
1718
+ this.specialOccasions = new SpecialOccasionsAPI(this.http);
1719
+ this.aiStudio = new AIStudioAPI(this.http, this.config.accountId);
1720
+ this.messaging = new MessagingAPI(this.http);
1721
+ this.sentinel = new SentinelAPI(this.http);
1722
+ this.prompts = new LPPromptsAPI(this.http);
1723
+ this.log("SDK initialized with scopes:", this.grantedScopes);
1724
+ }
1725
+ /**
1726
+ * Get the current account ID
1727
+ */
1728
+ get accountId() {
1729
+ return this.config.accountId;
1730
+ }
1731
+ /**
1732
+ * Get the app ID
1733
+ */
1734
+ get appId() {
1735
+ return this.config.appId;
1736
+ }
1737
+ /**
1738
+ * Check if a scope was granted
1739
+ */
1740
+ hasScope(scope) {
1741
+ return this.grantedScopes.includes(scope);
1742
+ }
1743
+ /**
1744
+ * Check if multiple scopes were granted
1745
+ */
1746
+ hasScopes(scopes) {
1747
+ return scopes.every((scope) => this.grantedScopes.includes(scope));
1748
+ }
1749
+ /**
1750
+ * Check if any of the specified scopes were granted
1751
+ */
1752
+ hasAnyScope(scopes) {
1753
+ return scopes.some((scope) => this.grantedScopes.includes(scope));
1754
+ }
1755
+ /**
1756
+ * Debug logging
1757
+ */
1758
+ log(...args) {
1759
+ if (this.debug) {
1760
+ console.log("[LP-Extend-SDK]", ...args);
1761
+ }
1762
+ }
1763
+ };
1764
+ async function createSDK(config) {
1765
+ if (!config.appId) {
1766
+ throw new LPExtendSDKError("appId is required", ErrorCodes.INVALID_CONFIG);
1767
+ }
1768
+ if (!config.accountId) {
1769
+ throw new LPExtendSDKError("accountId is required", ErrorCodes.INVALID_CONFIG);
1770
+ }
1771
+ if (!config.accessToken && !config.extendToken && !config.shellToken) {
1772
+ throw new LPExtendSDKError(
1773
+ "Either accessToken, extendToken, or shellToken is required",
1774
+ ErrorCodes.INVALID_CONFIG
1775
+ );
1776
+ }
1777
+ const debug = config.debug ?? false;
1778
+ const timeout = config.timeout ?? 3e4;
1779
+ let shellBaseUrl = config.shellBaseUrl;
1780
+ if (!shellBaseUrl) {
1781
+ if (typeof window !== "undefined") {
1782
+ try {
1783
+ if (window.self !== window.top && document.referrer) {
1784
+ const url = new URL(document.referrer);
1785
+ shellBaseUrl = url.origin;
1786
+ }
1787
+ } catch {
1788
+ }
1789
+ shellBaseUrl = shellBaseUrl || window.location.origin;
1790
+ } else {
1791
+ throw new LPExtendSDKError(
1792
+ "shellBaseUrl is required in non-browser environments",
1793
+ ErrorCodes.INVALID_CONFIG
1794
+ );
1795
+ }
1796
+ }
1797
+ let accessToken = config.accessToken;
1798
+ if (!accessToken && config.extendToken) {
1799
+ if (debug) {
1800
+ console.log("[LP-Extend-SDK] Verifying ExtendJWT with shell");
1801
+ }
1802
+ const verifyUrl = `${shellBaseUrl}/api/v2/auth/verify-child`;
1803
+ const extendController = new AbortController();
1804
+ const extendTimeoutId = setTimeout(() => extendController.abort(), timeout);
1805
+ try {
1806
+ const verifyResponse = await fetch(verifyUrl, {
1807
+ method: "POST",
1808
+ headers: {
1809
+ "Content-Type": "application/json"
1810
+ },
1811
+ body: JSON.stringify({
1812
+ extendToken: config.extendToken,
1813
+ appId: config.appId
1814
+ }),
1815
+ signal: extendController.signal
1816
+ });
1817
+ clearTimeout(extendTimeoutId);
1818
+ if (!verifyResponse.ok) {
1819
+ const errorData = await verifyResponse.json().catch(() => ({}));
1820
+ if (verifyResponse.status === 401) {
1821
+ throw new LPExtendSDKError(
1822
+ errorData.message || "ExtendJWT invalid or expired",
1823
+ ErrorCodes.UNAUTHORIZED,
1824
+ verifyResponse.status,
1825
+ errorData
1826
+ );
1827
+ }
1828
+ throw new LPExtendSDKError(
1829
+ errorData.message || `ExtendJWT verification failed: ${verifyResponse.status}`,
1830
+ ErrorCodes.API_ERROR,
1831
+ verifyResponse.status,
1832
+ errorData
1833
+ );
1834
+ }
1835
+ const authData = await verifyResponse.json();
1836
+ accessToken = authData.lpAccessToken;
1837
+ if (debug) {
1838
+ console.log("[LP-Extend-SDK] ExtendJWT verified, got LP access token");
1839
+ console.log("[LP-Extend-SDK] User:", authData.lpUserId, "Account:", authData.lpAccountId);
1840
+ }
1841
+ } catch (error) {
1842
+ clearTimeout(extendTimeoutId);
1843
+ if (error instanceof LPExtendSDKError) {
1844
+ throw error;
1845
+ }
1846
+ if (error.name === "AbortError") {
1847
+ throw new LPExtendSDKError("ExtendJWT verification timeout", ErrorCodes.TIMEOUT);
1848
+ }
1849
+ throw new LPExtendSDKError(
1850
+ `ExtendJWT verification failed: ${error.message}`,
1851
+ ErrorCodes.INIT_FAILED
1852
+ );
1853
+ }
1854
+ }
1855
+ if (!accessToken && config.shellToken) {
1856
+ if (debug) {
1857
+ console.log("[LP-Extend-SDK] Fetching LP token from shell using shellToken (legacy)");
1858
+ }
1859
+ const tokenUrl = `${shellBaseUrl}/api/v1/shell/token/${config.accountId}/lp-token`;
1860
+ const tokenController = new AbortController();
1861
+ const tokenTimeoutId = setTimeout(() => tokenController.abort(), timeout);
1862
+ try {
1863
+ const tokenResponse = await fetch(tokenUrl, {
1864
+ method: "POST",
1865
+ headers: {
1866
+ "Content-Type": "application/json",
1867
+ "X-Shell-Token": config.shellToken
1868
+ },
1869
+ body: JSON.stringify({
1870
+ appId: config.appId,
1871
+ scopes: config.scopes
1872
+ }),
1873
+ signal: tokenController.signal
1874
+ });
1875
+ clearTimeout(tokenTimeoutId);
1876
+ if (!tokenResponse.ok) {
1877
+ const errorData = await tokenResponse.json().catch(() => ({}));
1878
+ if (tokenResponse.status === 401) {
1879
+ throw new LPExtendSDKError(
1880
+ errorData.message || "Shell token invalid or expired",
1881
+ ErrorCodes.UNAUTHORIZED,
1882
+ tokenResponse.status,
1883
+ errorData
1884
+ );
1885
+ }
1886
+ if (tokenResponse.status === 403) {
1887
+ throw new LPExtendSDKError(
1888
+ errorData.message || "App not installed or disabled",
1889
+ ErrorCodes.APP_NOT_REGISTERED,
1890
+ tokenResponse.status,
1891
+ errorData
1892
+ );
1893
+ }
1894
+ if (tokenResponse.status === 404) {
1895
+ throw new LPExtendSDKError(
1896
+ errorData.message || "No LP token found - user may need to re-authenticate",
1897
+ ErrorCodes.NOT_FOUND,
1898
+ tokenResponse.status,
1899
+ errorData
1900
+ );
1901
+ }
1902
+ throw new LPExtendSDKError(
1903
+ errorData.message || `Failed to retrieve LP token: ${tokenResponse.status}`,
1904
+ ErrorCodes.API_ERROR,
1905
+ tokenResponse.status,
1906
+ errorData
1907
+ );
1908
+ }
1909
+ const tokenData = await tokenResponse.json();
1910
+ accessToken = tokenData.accessToken;
1911
+ if (debug) {
1912
+ console.log("[LP-Extend-SDK] LP token retrieved successfully");
1913
+ }
1914
+ } catch (error) {
1915
+ clearTimeout(tokenTimeoutId);
1916
+ if (error instanceof LPExtendSDKError) {
1917
+ throw error;
1918
+ }
1919
+ if (error.name === "AbortError") {
1920
+ throw new LPExtendSDKError("LP token retrieval timeout", ErrorCodes.TIMEOUT);
1921
+ }
1922
+ throw new LPExtendSDKError(
1923
+ `Failed to retrieve LP token: ${error.message}`,
1924
+ ErrorCodes.INIT_FAILED
1925
+ );
1926
+ }
1927
+ }
1928
+ if (debug) {
1929
+ console.log("[LP-Extend-SDK] Verifying scopes with shell:", shellBaseUrl);
1930
+ }
1931
+ const initUrl = `${shellBaseUrl}/api/v1/lp/${config.accountId}/sdk/init`;
1932
+ const controller = new AbortController();
1933
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
1934
+ try {
1935
+ const response = await fetch(initUrl, {
1936
+ method: "POST",
1937
+ headers: {
1938
+ "Content-Type": "application/json",
1939
+ Authorization: `Bearer ${accessToken}`,
1940
+ "X-App-Id": config.appId
1941
+ },
1942
+ body: JSON.stringify({ scopes: config.scopes || [] }),
1943
+ signal: controller.signal
1944
+ });
1945
+ clearTimeout(timeoutId);
1946
+ if (!response.ok) {
1947
+ const errorBody = await response.json().catch(() => ({ message: "Unknown error" }));
1948
+ if (response.status === 404) {
1949
+ throw new LPExtendSDKError(
1950
+ `App "${config.appId}" is not registered for account ${config.accountId}`,
1951
+ ErrorCodes.APP_NOT_REGISTERED,
1952
+ response.status,
1953
+ errorBody
1954
+ );
1955
+ }
1956
+ if (response.status === 403) {
1957
+ throw new LPExtendSDKError(
1958
+ errorBody.message || "App is disabled or not authorized",
1959
+ ErrorCodes.APP_NOT_REGISTERED,
1960
+ response.status,
1961
+ errorBody
1962
+ );
1963
+ }
1964
+ if (response.status === 401) {
1965
+ throw new LPExtendSDKError(
1966
+ "Authentication failed - invalid access token",
1967
+ ErrorCodes.UNAUTHORIZED,
1968
+ response.status,
1969
+ errorBody
1970
+ );
1971
+ }
1972
+ throw new LPExtendSDKError(
1973
+ `SDK initialization failed: ${errorBody.message || response.statusText}`,
1974
+ ErrorCodes.INIT_FAILED,
1975
+ response.status,
1976
+ errorBody
1977
+ );
1978
+ }
1979
+ const initResult = await response.json();
1980
+ if (debug) {
1981
+ console.log("[LP-Extend-SDK] Scopes verified:", initResult.grantedScopes);
1982
+ console.log("[LP-Extend-SDK] SDK will call LP APIs directly");
1983
+ }
1984
+ const resolvedConfig = { ...config, accessToken };
1985
+ return new LPExtendSDK(resolvedConfig, initResult);
1986
+ } catch (error) {
1987
+ clearTimeout(timeoutId);
1988
+ if (error.name === "AbortError") {
1989
+ throw new LPExtendSDKError("SDK initialization timeout", ErrorCodes.TIMEOUT);
1990
+ }
1991
+ if (error instanceof LPExtendSDKError) {
1992
+ throw error;
1993
+ }
1994
+ throw new LPExtendSDKError(
1995
+ `SDK initialization failed: ${error.message}`,
1996
+ ErrorCodes.INIT_FAILED
1997
+ );
1998
+ }
1999
+ }
2000
+
2001
+ // src/index.ts
2002
+ async function initializeSDK(config) {
2003
+ return createSDK(config);
2004
+ }
2005
+ var VERSION = "1.0.0";
2006
+ var Scopes = {
2007
+ // Account Configuration
2008
+ SKILLS: "skills",
2009
+ USERS: "users",
2010
+ AGENT_GROUPS: "agentGroups",
2011
+ PROFILES: "profiles",
2012
+ LOBS: "lobs",
2013
+ PREDEFINED_CONTENT: "predefinedContent",
2014
+ AUTOMATIC_MESSAGES: "automaticMessages",
2015
+ WORKING_HOURS: "workingHours",
2016
+ SPECIAL_OCCASIONS: "specialOccasions",
2017
+ CAMPAIGNS: "campaigns",
2018
+ ENGAGEMENTS: "engagements",
2019
+ // Messaging & Conversations
2020
+ MESSAGING_HISTORY: "messagingHistory",
2021
+ MESSAGING_OPERATIONS: "messagingOperations",
2022
+ CONNECT_TO_MESSAGING: "connectToMessaging",
2023
+ // Agent & Reporting
2024
+ AGENT_METRICS: "agentMetrics",
2025
+ AGENT_ACTIVITY: "agentActivity",
2026
+ OUTBOUND_REPORTING: "outboundReporting",
2027
+ // AI & Automation
2028
+ AI_STUDIO: "aiStudio",
2029
+ CONVERSATION_BUILDER: "conversationBuilder",
2030
+ CONVERSATION_ORCHESTRATOR: "conversationOrchestrator",
2031
+ /** AI Studio Prompt Library (different from LP Prompts) */
2032
+ PROMPT_LIBRARY: "promptLibrary",
2033
+ /** LP Prompts API (Prompt Library) */
2034
+ LP_PROMPTS: "prompts",
2035
+ FAAS: "faas",
2036
+ // Proactive
2037
+ PROACTIVE_MESSAGING: "proactiveMessaging"
2038
+ };
2039
+ async function getShellToken(config) {
2040
+ const { shellBaseUrl, accountId, shellToken, appId, scopes, timeout = 1e4 } = config;
2041
+ if (!shellBaseUrl) {
2042
+ throw new LPExtendSDKError("shellBaseUrl is required", ErrorCodes.INVALID_CONFIG);
2043
+ }
2044
+ if (!accountId) {
2045
+ throw new LPExtendSDKError("accountId is required", ErrorCodes.INVALID_CONFIG);
2046
+ }
2047
+ if (!shellToken) {
2048
+ throw new LPExtendSDKError("shellToken is required", ErrorCodes.INVALID_CONFIG);
2049
+ }
2050
+ if (!appId) {
2051
+ throw new LPExtendSDKError("appId is required", ErrorCodes.INVALID_CONFIG);
2052
+ }
2053
+ const url = `${shellBaseUrl.replace(/\/$/, "")}/api/v1/shell/token/${accountId}/lp-token`;
2054
+ const controller = new AbortController();
2055
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
2056
+ try {
2057
+ const response = await fetch(url, {
2058
+ method: "POST",
2059
+ headers: {
2060
+ "Content-Type": "application/json",
2061
+ "X-Shell-Token": shellToken
2062
+ },
2063
+ body: JSON.stringify({
2064
+ appId,
2065
+ scopes
2066
+ }),
2067
+ signal: controller.signal
2068
+ });
2069
+ clearTimeout(timeoutId);
2070
+ if (!response.ok) {
2071
+ const errorData = await response.json().catch(() => ({}));
2072
+ if (response.status === 401) {
2073
+ throw new LPExtendSDKError(
2074
+ errorData.message || "Shell token invalid or expired",
2075
+ ErrorCodes.UNAUTHORIZED,
2076
+ response.status,
2077
+ errorData
2078
+ );
2079
+ }
2080
+ if (response.status === 403) {
2081
+ throw new LPExtendSDKError(
2082
+ errorData.message || "App not installed or disabled",
2083
+ ErrorCodes.APP_NOT_REGISTERED,
2084
+ response.status,
2085
+ errorData
2086
+ );
2087
+ }
2088
+ if (response.status === 404) {
2089
+ throw new LPExtendSDKError(
2090
+ errorData.message || "No LP token found for user",
2091
+ ErrorCodes.NOT_FOUND,
2092
+ response.status,
2093
+ errorData
2094
+ );
2095
+ }
2096
+ throw new LPExtendSDKError(
2097
+ errorData.message || `Shell token request failed: ${response.status}`,
2098
+ ErrorCodes.API_ERROR,
2099
+ response.status,
2100
+ errorData
2101
+ );
2102
+ }
2103
+ const data = await response.json();
2104
+ return data;
2105
+ } catch (error) {
2106
+ clearTimeout(timeoutId);
2107
+ if (error instanceof LPExtendSDKError) {
2108
+ throw error;
2109
+ }
2110
+ if (error instanceof Error && error.name === "AbortError") {
2111
+ throw new LPExtendSDKError("Shell token request timed out", ErrorCodes.TIMEOUT);
2112
+ }
2113
+ throw new LPExtendSDKError(
2114
+ `Failed to retrieve shell token: ${error instanceof Error ? error.message : "Unknown error"}`,
2115
+ ErrorCodes.API_ERROR
2116
+ );
2117
+ }
2118
+ }
2119
+
2120
+ exports.AIStudioAPI = AIStudioAPI;
2121
+ exports.AIStudioUsersAPI = AIStudioUsersAPI;
2122
+ exports.AgentActivityAPI = AgentActivityAPI;
2123
+ exports.AgentGroupsAPI = AgentGroupsAPI;
2124
+ exports.AgentMetricsAPI = AgentMetricsAPI;
2125
+ exports.AutomaticMessagesAPI = AutomaticMessagesAPI;
2126
+ exports.CampaignsAPI = CampaignsAPI;
2127
+ exports.CategoriesAPI = CategoriesAPI;
2128
+ exports.ConnectToMessagingAPI = ConnectToMessagingAPI;
2129
+ exports.ConversationsAPI = ConversationsAPI;
2130
+ exports.EngagementsAPI = EngagementsAPI;
2131
+ exports.ErrorCodes = ErrorCodes;
2132
+ exports.EvaluatorsAPI = EvaluatorsAPI;
2133
+ exports.FlowsAPI = FlowsAPI;
2134
+ exports.GeneratorsAPI = GeneratorsAPI;
2135
+ exports.KnowledgebasesAPI = KnowledgebasesAPI;
2136
+ exports.LOBsAPI = LOBsAPI;
2137
+ exports.LPExtendSDK = LPExtendSDK;
2138
+ exports.LPExtendSDKError = LPExtendSDKError;
2139
+ exports.LPPromptsAPI = LPPromptsAPI;
2140
+ exports.MessagingAPI = MessagingAPI;
2141
+ exports.MessagingHistoryAPI = MessagingHistoryAPI;
2142
+ exports.MessagingOperationsAPI = MessagingOperationsAPI;
2143
+ exports.OutboundReportingAPI = OutboundReportingAPI;
2144
+ exports.PredefinedContentAPI = PredefinedContentAPI;
2145
+ exports.ProfilesAPI = ProfilesAPI;
2146
+ exports.PromptLibraryAPI = PromptLibraryAPI;
2147
+ exports.QueryAPI = QueryAPI;
2148
+ exports.Scopes = Scopes;
2149
+ exports.SentinelAPI = SentinelAPI;
2150
+ exports.SimulationsAPI = SimulationsAPI;
2151
+ exports.SkillsAPI = SkillsAPI;
2152
+ exports.SpecialOccasionsAPI = SpecialOccasionsAPI;
2153
+ exports.SummaryAPI = SummaryAPI;
2154
+ exports.TranscriptAnalysisAPI = TranscriptAnalysisAPI;
2155
+ exports.UsersAPI = UsersAPI;
2156
+ exports.VERSION = VERSION;
2157
+ exports.WorkingHoursAPI = WorkingHoursAPI;
2158
+ exports.createSDK = createSDK;
2159
+ exports.getShellToken = getShellToken;
2160
+ exports.initializeSDK = initializeSDK;
2161
+ //# sourceMappingURL=index.js.map
2162
+ //# sourceMappingURL=index.js.map