@sippulse/niva-sdk 0.1.0-rc.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.
package/index.deno.js ADDED
@@ -0,0 +1,2831 @@
1
+ // src/errors.ts
2
+ class NivaError extends Error {
3
+ constructor(message, options) {
4
+ super(message, options);
5
+ }
6
+ name = "NivaError";
7
+ }
8
+
9
+ class NivaApiError extends NivaError {
10
+ name = "NivaApiError";
11
+ status;
12
+ code;
13
+ data;
14
+ requestId;
15
+ operation;
16
+ constructor(details) {
17
+ super(details.message);
18
+ this.status = details.status;
19
+ this.code = details.code;
20
+ this.data = details.data;
21
+ this.requestId = details.requestId;
22
+ this.operation = details.operation;
23
+ }
24
+ }
25
+
26
+ class NivaConnectionError extends NivaError {
27
+ name = "NivaConnectionError";
28
+ reason;
29
+ constructor(message, options) {
30
+ super(message, options);
31
+ this.reason = options.reason;
32
+ }
33
+ }
34
+
35
+ class NivaConfigurationError extends NivaError {
36
+ name = "NivaConfigurationError";
37
+ }
38
+
39
+ class NivaIncompatibleServerError extends NivaError {
40
+ name = "NivaIncompatibleServerError";
41
+ serverVersion;
42
+ supported;
43
+ installCommand;
44
+ constructor(message, details) {
45
+ super(message);
46
+ this.serverVersion = details.serverVersion;
47
+ this.supported = details.supported;
48
+ this.installCommand = details.installCommand;
49
+ }
50
+ }
51
+
52
+ class NivaUnavailableError extends NivaError {
53
+ name = "NivaUnavailableError";
54
+ operation;
55
+ reason;
56
+ module;
57
+ constructor(operation, options) {
58
+ super(options.reason === "operation" ? `Operation ${operation} is not served by this NIVA installation` : `Operation ${operation} needs module ${options.module ?? "unknown"}, which is disabled on this installation`);
59
+ this.operation = operation;
60
+ this.reason = options.reason;
61
+ this.module = options.module;
62
+ }
63
+ }
64
+
65
+ class NivaWebhookError extends NivaError {
66
+ name = "NivaWebhookError";
67
+ kind;
68
+ code;
69
+ constructor(kind, code, message) {
70
+ super(message);
71
+ this.kind = kind;
72
+ this.code = code;
73
+ }
74
+ }
75
+ function isNivaApiError(err, code) {
76
+ return err instanceof NivaApiError && (code === undefined || err.code === code);
77
+ }
78
+
79
+ // src/sse.ts
80
+ function parseFrame(block) {
81
+ let event;
82
+ const dataLines = [];
83
+ for (const line of block.split(`
84
+ `)) {
85
+ if (line === "")
86
+ continue;
87
+ if (line.startsWith(":"))
88
+ continue;
89
+ const colon = line.indexOf(":");
90
+ if (colon === -1)
91
+ continue;
92
+ const field = line.slice(0, colon);
93
+ const value = line.slice(colon + 1).startsWith(" ") ? line.slice(colon + 2) : line.slice(colon + 1);
94
+ if (field === "event")
95
+ event = value;
96
+ else if (field === "data")
97
+ dataLines.push(value);
98
+ }
99
+ if (event === undefined)
100
+ return;
101
+ return { event, dataLines };
102
+ }
103
+ function frameData(frame) {
104
+ const text = frame.dataLines.join(`
105
+ `);
106
+ if (text === "")
107
+ return;
108
+ const parsed = JSON.parse(text);
109
+ return parsed;
110
+ }
111
+ function isRecord(value) {
112
+ return value !== null && typeof value === "object" && !Array.isArray(value);
113
+ }
114
+ function errorFromFrame(frame, data, operation) {
115
+ if (isRecord(data) && data["defined"] === true && typeof data["code"] === "string") {
116
+ return new NivaApiError({
117
+ status: typeof data["status"] === "number" ? data["status"] : 500,
118
+ code: data["code"],
119
+ message: typeof data["message"] === "string" ? data["message"] : "stream error",
120
+ data: data["data"],
121
+ operation
122
+ });
123
+ }
124
+ return new NivaApiError({
125
+ status: 500,
126
+ code: "UNEXPECTED_RESPONSE",
127
+ message: `unexpected stream event ${frame.event}`,
128
+ operation
129
+ });
130
+ }
131
+ function messageValue(frame) {
132
+ return frameData(frame);
133
+ }
134
+ async function* emptyGenerator() {}
135
+ async function* readFrames(reader, decoder, isClosed) {
136
+ let buffer = "";
137
+ const carry = { current: "" };
138
+ for (;; ) {
139
+ if (isClosed())
140
+ return;
141
+ const chunk = await reader.read();
142
+ buffer += normalizeChunk(decoder, chunk.done ? undefined : chunk.value, carry);
143
+ const holder = { text: buffer };
144
+ for (const frame of takeFrames(holder)) {
145
+ yield frame;
146
+ if (isClosed())
147
+ return;
148
+ }
149
+ buffer = holder.text;
150
+ if (chunk.done)
151
+ return;
152
+ }
153
+ }
154
+ function normalizeChunk(decoder, raw, carry) {
155
+ if (raw === undefined) {
156
+ const flushed = carry.current === "\r" ? `
157
+ ` : carry.current;
158
+ carry.current = "";
159
+ return flushed;
160
+ }
161
+ let text = carry.current + decoder.decode(raw, { stream: true });
162
+ carry.current = "";
163
+ if (text.endsWith("\r")) {
164
+ carry.current = "\r";
165
+ text = text.slice(0, -1);
166
+ }
167
+ return text.replaceAll(`\r
168
+ `, `
169
+ `).replaceAll("\r", `
170
+ `);
171
+ }
172
+ function takeFrames(buffer) {
173
+ const frames = [];
174
+ let boundary = buffer.text.indexOf(`
175
+
176
+ `);
177
+ while (boundary !== -1) {
178
+ const block = buffer.text.slice(0, boundary);
179
+ buffer.text = buffer.text.slice(boundary + 2);
180
+ const frame = parseFrame(block);
181
+ if (frame !== undefined)
182
+ frames.push(frame);
183
+ boundary = buffer.text.indexOf(`
184
+
185
+ `);
186
+ }
187
+ return frames;
188
+ }
189
+ function createSseStream(response, options) {
190
+ const operation = options?.operation ?? "unknown";
191
+ const callerSignal = options?.signal;
192
+ const reader = response.body?.getReader();
193
+ const decoder = new TextDecoder;
194
+ let closed = false;
195
+ async function cancelBody() {
196
+ closed = true;
197
+ try {
198
+ await reader?.cancel();
199
+ } catch {}
200
+ }
201
+ if (callerSignal !== undefined) {
202
+ if (callerSignal.aborted)
203
+ cancelBody();
204
+ else
205
+ callerSignal.addEventListener("abort", () => void cancelBody(), { once: true });
206
+ }
207
+ async function* iterate() {
208
+ if (reader === undefined)
209
+ return;
210
+ try {
211
+ for await (const frame of readFrames(reader, decoder, () => closed)) {
212
+ if (frame.event === "message") {
213
+ yield messageValue(frame);
214
+ } else if (frame.event === "done") {
215
+ await cancelBody();
216
+ return;
217
+ } else if (frame.event === "error") {
218
+ throw errorFromFrame(frame, frameData(frame), operation);
219
+ } else {
220
+ throw new NivaApiError({
221
+ status: 500,
222
+ code: "UNEXPECTED_RESPONSE",
223
+ message: `unexpected stream event ${frame.event}`,
224
+ operation
225
+ });
226
+ }
227
+ }
228
+ } finally {
229
+ if (!closed)
230
+ await cancelBody();
231
+ }
232
+ }
233
+ const iterator = iterate();
234
+ return {
235
+ [Symbol.asyncIterator]() {
236
+ return iterator;
237
+ },
238
+ close: async () => {
239
+ await cancelBody();
240
+ }
241
+ };
242
+ }
243
+ async function cancelQuietly(response) {
244
+ try {
245
+ await response.body?.cancel();
246
+ } catch {}
247
+ }
248
+ function streamFromResponse(responsePromise, options) {
249
+ let inner;
250
+ let closed = false;
251
+ let arrived;
252
+ responsePromise.then((response) => {
253
+ arrived = response;
254
+ if (closed)
255
+ cancelQuietly(response);
256
+ }, () => {
257
+ return;
258
+ });
259
+ const empty = {
260
+ [Symbol.asyncIterator]() {
261
+ return emptyGenerator();
262
+ },
263
+ close: async () => {}
264
+ };
265
+ async function* iterate() {
266
+ const response = await responsePromise;
267
+ if (closed) {
268
+ await cancelQuietly(response);
269
+ yield* empty;
270
+ return;
271
+ }
272
+ inner = createSseStream(response, options);
273
+ yield* inner;
274
+ }
275
+ return {
276
+ [Symbol.asyncIterator]() {
277
+ return iterate();
278
+ },
279
+ close: async () => {
280
+ closed = true;
281
+ try {
282
+ await arrived?.body?.cancel();
283
+ } catch {}
284
+ await inner?.close();
285
+ }
286
+ };
287
+ }
288
+
289
+ // src/generated/client-impl.ts
290
+ function buildNivaClient(call) {
291
+ return {
292
+ ai: {
293
+ getBudget: async (options) => call("ai.getBudget", undefined, options),
294
+ getBudgetOverview: async (options) => call("ai.getBudgetOverview", undefined, options),
295
+ getCallAnalyses: async (input, options) => call("ai.getCallAnalyses", input, options),
296
+ getTranscription: async (input, options) => call("ai.getTranscription", input, options),
297
+ getUsage: async (options) => call("ai.getUsage", undefined, options),
298
+ listAgents: async (options) => call("ai.listAgents", undefined, options),
299
+ listStructuredAnalyses: async (input, options) => call("ai.listStructuredAnalyses", input, options),
300
+ runAnalysis: async (input, options) => call("ai.runAnalysis", input, options),
301
+ runConfiguredAnalyses: async (input, options) => call("ai.runConfiguredAnalyses", input, options),
302
+ runSpeechAnalytics: async (input, options) => call("ai.runSpeechAnalytics", input, options),
303
+ searchTranscriptions: async (input, options) => call("ai.searchTranscriptions", input, options),
304
+ transcribeNow: async (input, options) => call("ai.transcribeNow", input, options)
305
+ },
306
+ apiKeys: {
307
+ create: async (input, options) => call("apiKeys.create", input, options),
308
+ finishRotation: async (input, options) => call("apiKeys.finishRotation", input, options),
309
+ get: async (input, options) => call("apiKeys.get", input, options),
310
+ list: async (input, options) => call("apiKeys.list", input, options),
311
+ revoke: async (input, options) => call("apiKeys.revoke", input, options),
312
+ rotate: async (input, options) => call("apiKeys.rotate", input, options),
313
+ update: async (input, options) => call("apiKeys.update", input, options),
314
+ usage: async (input, options) => call("apiKeys.usage", input, options)
315
+ },
316
+ archive: {
317
+ listDeleted: async (input, options) => call("archive.listDeleted", input, options),
318
+ purge: async (input, options) => call("archive.purge", input, options),
319
+ restore: async (input, options) => call("archive.restore", input, options),
320
+ summary: async (options) => call("archive.summary", undefined, options)
321
+ },
322
+ audioFiles: {
323
+ content: async (input, options) => call("audioFiles.content", input, options),
324
+ delete: async (input, options) => call("audioFiles.delete", input, options),
325
+ generateTts: async (input, options) => call("audioFiles.generateTts", input, options),
326
+ getById: async (input, options) => call("audioFiles.getById", input, options),
327
+ list: async (input, options) => call("audioFiles.list", input, options),
328
+ previewUrl: async (input, options) => call("audioFiles.previewUrl", input, options),
329
+ regenerateTts: async (input, options) => call("audioFiles.regenerateTts", input, options),
330
+ update: async (input, options) => call("audioFiles.update", input, options),
331
+ upload: async (input, options) => call("audioFiles.upload", input, options)
332
+ },
333
+ audit: {
334
+ count: async (input, options) => call("audit.count", input, options),
335
+ exportCsv: (input, options) => streamFromResponse(call("audit.exportCsv", input, options), {
336
+ signal: options?.signal,
337
+ operation: "audit.exportCsv"
338
+ }),
339
+ list: async (input, options) => call("audit.list", input, options)
340
+ },
341
+ callRecords: {
342
+ count: async (input, options) => call("callRecords.count", input, options),
343
+ exportCsv: (input, options) => streamFromResponse(call("callRecords.exportCsv", input, options), {
344
+ signal: options?.signal,
345
+ operation: "callRecords.exportCsv"
346
+ }),
347
+ getById: async (input, options) => call("callRecords.getById", input, options),
348
+ getEvents: async (input, options) => call("callRecords.getEvents", input, options),
349
+ getRecordingUrl: async (input, options) => call("callRecords.getRecordingUrl", input, options),
350
+ list: async (input, options) => call("callRecords.list", input, options),
351
+ purgeVoiceContent: async (input, options) => call("callRecords.purgeVoiceContent", input, options),
352
+ recordingContent: async (input, options) => call("callRecords.recordingContent", input, options),
353
+ retryRecording: async (input, options) => call("callRecords.retryRecording", input, options)
354
+ },
355
+ calls: {
356
+ hangupCall: async (input, options) => call("calls.hangupCall", input, options),
357
+ originate: async (input, options) => call("calls.originate", input, options)
358
+ },
359
+ capabilities: {
360
+ get: async (options) => call("capabilities.get", undefined, options)
361
+ },
362
+ channels: {
363
+ create: async (input, options) => call("channels.create", input, options),
364
+ delete: async (input, options) => call("channels.delete", input, options),
365
+ getById: async (input, options) => call("channels.getById", input, options),
366
+ list: async (input, options) => call("channels.list", input, options),
367
+ testConnection: async (input, options) => call("channels.testConnection", input, options),
368
+ toggle: async (input, options) => call("channels.toggle", input, options),
369
+ update: async (input, options) => call("channels.update", input, options)
370
+ },
371
+ contacts: {
372
+ getById: async (input, options) => call("contacts.getById", input, options),
373
+ list: async (input, options) => call("contacts.list", input, options),
374
+ update: async (input, options) => call("contacts.update", input, options)
375
+ },
376
+ dashboard: {
377
+ capacityStatus: async (options) => call("dashboard.capacityStatus", undefined, options),
378
+ watchDashboardMetrics: (options) => streamFromResponse(call("dashboard.watchDashboardMetrics", undefined, options), {
379
+ signal: options?.signal,
380
+ operation: "dashboard.watchDashboardMetrics"
381
+ })
382
+ },
383
+ destinations: {
384
+ create: async (input, options) => call("destinations.create", input, options),
385
+ delete: async (input, options) => call("destinations.delete", input, options),
386
+ getById: async (input, options) => call("destinations.getById", input, options),
387
+ list: async (input, options) => call("destinations.list", input, options),
388
+ update: async (input, options) => call("destinations.update", input, options)
389
+ },
390
+ dialerAttempts: {
391
+ list: async (input, options) => call("dialerAttempts.list", input, options)
392
+ },
393
+ dialerCampaigns: {
394
+ control: async (input, options) => call("dialerCampaigns.control", input, options),
395
+ create: async (input, options) => call("dialerCampaigns.create", input, options),
396
+ delete: async (input, options) => call("dialerCampaigns.delete", input, options),
397
+ get: async (input, options) => call("dialerCampaigns.get", input, options),
398
+ list: async (input, options) => call("dialerCampaigns.list", input, options),
399
+ liveStats: (input, options) => streamFromResponse(call("dialerCampaigns.liveStats", input, options), {
400
+ signal: options?.signal,
401
+ operation: "dialerCampaigns.liveStats"
402
+ }),
403
+ orgLiveStats: (options) => streamFromResponse(call("dialerCampaigns.orgLiveStats", undefined, options), {
404
+ signal: options?.signal,
405
+ operation: "dialerCampaigns.orgLiveStats"
406
+ }),
407
+ stats: async (input, options) => call("dialerCampaigns.stats", input, options),
408
+ summary: async (options) => call("dialerCampaigns.summary", undefined, options),
409
+ update: async (input, options) => call("dialerCampaigns.update", input, options)
410
+ },
411
+ dialerContacts: {
412
+ add: async (input, options) => call("dialerContacts.add", input, options),
413
+ bulkCancel: async (input, options) => call("dialerContacts.bulkCancel", input, options),
414
+ bulkRequeue: async (input, options) => call("dialerContacts.bulkRequeue", input, options),
415
+ cancel: async (input, options) => call("dialerContacts.cancel", input, options),
416
+ exportCsv: (input, options) => streamFromResponse(call("dialerContacts.exportCsv", input, options), {
417
+ signal: options?.signal,
418
+ operation: "dialerContacts.exportCsv"
419
+ }),
420
+ get: async (input, options) => call("dialerContacts.get", input, options),
421
+ list: async (input, options) => call("dialerContacts.list", input, options),
422
+ remove: async (input, options) => call("dialerContacts.remove", input, options),
423
+ requeue: async (input, options) => call("dialerContacts.requeue", input, options),
424
+ requeueAll: async (input, options) => call("dialerContacts.requeueAll", input, options),
425
+ update: async (input, options) => call("dialerContacts.update", input, options)
426
+ },
427
+ dialerDnc: {
428
+ add: async (input, options) => call("dialerDnc.add", input, options),
429
+ bulkImport: async (input, options) => call("dialerDnc.bulkImport", input, options),
430
+ bulkRemove: async (input, options) => call("dialerDnc.bulkRemove", input, options),
431
+ list: async (input, options) => call("dialerDnc.list", input, options),
432
+ remove: async (input, options) => call("dialerDnc.remove", input, options)
433
+ },
434
+ dialerImports: {
435
+ create: async (input, options) => call("dialerImports.create", input, options),
436
+ get: async (input, options) => call("dialerImports.get", input, options),
437
+ invalidRows: async (input, options) => call("dialerImports.invalidRows", input, options),
438
+ progress: (input, options) => streamFromResponse(call("dialerImports.progress", input, options), {
439
+ signal: options?.signal,
440
+ operation: "dialerImports.progress"
441
+ })
442
+ },
443
+ holidays: {
444
+ countries: async (options) => call("holidays.countries", undefined, options),
445
+ create: async (input, options) => call("holidays.create", input, options),
446
+ delete: async (input, options) => call("holidays.delete", input, options),
447
+ import: async (input, options) => call("holidays.import", input, options),
448
+ list: async (input, options) => call("holidays.list", input, options),
449
+ previewImport: async (input, options) => call("holidays.previewImport", input, options),
450
+ update: async (input, options) => call("holidays.update", input, options),
451
+ groups: {
452
+ create: async (input, options) => call("holidays.groups.create", input, options),
453
+ delete: async (input, options) => call("holidays.groups.delete", input, options),
454
+ getById: async (input, options) => call("holidays.groups.getById", input, options),
455
+ list: async (input, options) => call("holidays.groups.list", input, options),
456
+ update: async (input, options) => call("holidays.groups.update", input, options)
457
+ }
458
+ },
459
+ license: {
460
+ status: async (options) => call("license.status", undefined, options)
461
+ },
462
+ oauthGrants: {
463
+ list: async (input, options) => call("oauthGrants.list", input, options),
464
+ revoke: async (input, options) => call("oauthGrants.revoke", input, options),
465
+ usage: async (input, options) => call("oauthGrants.usage", input, options)
466
+ },
467
+ orgSettings: {
468
+ getDialer: async (options) => call("orgSettings.getDialer", undefined, options),
469
+ upsertDialer: async (input, options) => call("orgSettings.upsertDialer", input, options)
470
+ },
471
+ schedules: {
472
+ create: async (input, options) => call("schedules.create", input, options),
473
+ delete: async (input, options) => call("schedules.delete", input, options),
474
+ getById: async (input, options) => call("schedules.getById", input, options),
475
+ list: async (input, options) => call("schedules.list", input, options),
476
+ update: async (input, options) => call("schedules.update", input, options)
477
+ },
478
+ secrets: {
479
+ list: async (input, options) => call("secrets.list", input, options),
480
+ listNames: async (options) => call("secrets.listNames", undefined, options)
481
+ },
482
+ tts: {
483
+ listModels: async (options) => call("tts.listModels", undefined, options),
484
+ listVoices: async (input, options) => call("tts.listVoices", input, options),
485
+ preview: async (input, options) => call("tts.preview", input, options)
486
+ },
487
+ users: {
488
+ activateMember: async (input, options) => call("users.activateMember", input, options),
489
+ createMember: async (input, options) => call("users.createMember", input, options),
490
+ listMembers: async (input, options) => call("users.listMembers", input, options),
491
+ me: async (options) => call("users.me", undefined, options),
492
+ removeMember: async (input, options) => call("users.removeMember", input, options),
493
+ suspendMember: async (input, options) => call("users.suspendMember", input, options),
494
+ updateRole: async (input, options) => call("users.updateRole", input, options)
495
+ },
496
+ visualPlans: {
497
+ clone: async (input, options) => call("visualPlans.clone", input, options),
498
+ create: async (input, options) => call("visualPlans.create", input, options),
499
+ delete: async (input, options) => call("visualPlans.delete", input, options),
500
+ getById: async (input, options) => call("visualPlans.getById", input, options),
501
+ importDraft: async (input, options) => call("visualPlans.importDraft", input, options),
502
+ list: async (input, options) => call("visualPlans.list", input, options),
503
+ listVersions: async (input, options) => call("visualPlans.listVersions", input, options),
504
+ publish: async (input, options) => call("visualPlans.publish", input, options),
505
+ update: async (input, options) => call("visualPlans.update", input, options),
506
+ validate: async (input, options) => call("visualPlans.validate", input, options)
507
+ },
508
+ webhooks: {
509
+ deliveries: {
510
+ count: async (input, options) => call("webhooks.deliveries.count", input, options),
511
+ getById: async (input, options) => call("webhooks.deliveries.getById", input, options),
512
+ list: async (input, options) => call("webhooks.deliveries.list", input, options),
513
+ retention: async (options) => call("webhooks.deliveries.retention", undefined, options),
514
+ retry: async (input, options) => call("webhooks.deliveries.retry", input, options),
515
+ aggregates: {
516
+ get: async (input, options) => call("webhooks.deliveries.aggregates.get", input, options),
517
+ list: async (input, options) => call("webhooks.deliveries.aggregates.list", input, options)
518
+ }
519
+ },
520
+ endpoints: {
521
+ create: async (input, options) => call("webhooks.endpoints.create", input, options),
522
+ delete: async (input, options) => call("webhooks.endpoints.delete", input, options),
523
+ getById: async (input, options) => call("webhooks.endpoints.getById", input, options),
524
+ list: async (input, options) => call("webhooks.endpoints.list", input, options),
525
+ rotateSecret: async (input, options) => call("webhooks.endpoints.rotateSecret", input, options),
526
+ update: async (input, options) => call("webhooks.endpoints.update", input, options)
527
+ },
528
+ events: {
529
+ list: async (options) => call("webhooks.events.list", undefined, options)
530
+ }
531
+ }
532
+ };
533
+ }
534
+
535
+ // src/generated/meta.ts
536
+ var SDK_VERSION = "0.1.0-rc.0";
537
+ var SUPPORTED_NIVA = { min: "2.0.0", max: null };
538
+ var PROTOCOL_VERSION = 1;
539
+ var COMPAT_TABLE = [
540
+ { nivaMin: "2.0.0", nivaMax: null, distTag: "niva-2.0" }
541
+ ];
542
+
543
+ // src/generated/operations.ts
544
+ var OPERATIONS = {
545
+ "ai.getBudget": {
546
+ method: "GET",
547
+ path: "/ai/budget",
548
+ pathParams: [],
549
+ queryParams: [],
550
+ bodyKind: "none",
551
+ responseKind: "json"
552
+ },
553
+ "ai.getBudgetOverview": {
554
+ method: "GET",
555
+ path: "/ai/budget/overview",
556
+ pathParams: [],
557
+ queryParams: [],
558
+ bodyKind: "none",
559
+ responseKind: "json"
560
+ },
561
+ "ai.getCallAnalyses": {
562
+ method: "GET",
563
+ path: "/call-records/{call_record_id}/analyses",
564
+ pathParams: ["call_record_id"],
565
+ queryParams: [],
566
+ bodyKind: "none",
567
+ responseKind: "json"
568
+ },
569
+ "ai.getTranscription": {
570
+ method: "GET",
571
+ path: "/call-records/{call_record_id}/transcription",
572
+ pathParams: ["call_record_id"],
573
+ queryParams: [],
574
+ bodyKind: "none",
575
+ responseKind: "json"
576
+ },
577
+ "ai.getUsage": {
578
+ method: "GET",
579
+ path: "/ai/usage",
580
+ pathParams: [],
581
+ queryParams: [],
582
+ bodyKind: "none",
583
+ responseKind: "json"
584
+ },
585
+ "ai.listAgents": {
586
+ method: "GET",
587
+ path: "/ai/agents",
588
+ pathParams: [],
589
+ queryParams: [],
590
+ bodyKind: "none",
591
+ responseKind: "json"
592
+ },
593
+ "ai.listStructuredAnalyses": {
594
+ method: "GET",
595
+ path: "/ai/structured-analyses",
596
+ pathParams: [],
597
+ queryParams: ["refresh"],
598
+ bodyKind: "none",
599
+ responseKind: "json"
600
+ },
601
+ "ai.runAnalysis": {
602
+ method: "POST",
603
+ path: "/call-records/{call_record_id}/analyses",
604
+ pathParams: ["call_record_id"],
605
+ queryParams: [],
606
+ bodyKind: "json",
607
+ responseKind: "json"
608
+ },
609
+ "ai.runConfiguredAnalyses": {
610
+ method: "POST",
611
+ path: "/call-records/{call_record_id}/configured-analyses",
612
+ pathParams: ["call_record_id"],
613
+ queryParams: [],
614
+ bodyKind: "json",
615
+ responseKind: "json"
616
+ },
617
+ "ai.runSpeechAnalytics": {
618
+ method: "POST",
619
+ path: "/call-records/{call_record_id}/speech-analytics",
620
+ pathParams: ["call_record_id"],
621
+ queryParams: [],
622
+ bodyKind: "json",
623
+ responseKind: "json"
624
+ },
625
+ "ai.searchTranscriptions": {
626
+ method: "GET",
627
+ path: "/transcriptions/search",
628
+ pathParams: [],
629
+ queryParams: ["query", "limit", "threshold", "date_from", "date_to", "visual_plan_id"],
630
+ bodyKind: "none",
631
+ responseKind: "json"
632
+ },
633
+ "ai.transcribeNow": {
634
+ method: "POST",
635
+ path: "/call-records/{call_record_id}/transcription",
636
+ pathParams: ["call_record_id"],
637
+ queryParams: [],
638
+ bodyKind: "json",
639
+ responseKind: "json"
640
+ },
641
+ "apiKeys.create": {
642
+ method: "POST",
643
+ path: "/api-keys",
644
+ pathParams: [],
645
+ queryParams: [],
646
+ bodyKind: "json",
647
+ responseKind: "json"
648
+ },
649
+ "apiKeys.finishRotation": {
650
+ method: "POST",
651
+ path: "/api-keys/{api_key_id}/finish-rotation",
652
+ pathParams: ["api_key_id"],
653
+ queryParams: [],
654
+ bodyKind: "none",
655
+ responseKind: "json"
656
+ },
657
+ "apiKeys.get": {
658
+ method: "GET",
659
+ path: "/api-keys/{api_key_id}",
660
+ pathParams: ["api_key_id"],
661
+ queryParams: [],
662
+ bodyKind: "none",
663
+ responseKind: "json"
664
+ },
665
+ "apiKeys.list": {
666
+ method: "GET",
667
+ path: "/api-keys",
668
+ pathParams: [],
669
+ queryParams: ["search", "page", "limit", "sort_by", "sort_order"],
670
+ bodyKind: "none",
671
+ responseKind: "json"
672
+ },
673
+ "apiKeys.revoke": {
674
+ method: "DELETE",
675
+ path: "/api-keys/{api_key_id}",
676
+ pathParams: ["api_key_id"],
677
+ queryParams: [],
678
+ bodyKind: "none",
679
+ responseKind: "json"
680
+ },
681
+ "apiKeys.rotate": {
682
+ method: "POST",
683
+ path: "/api-keys/{api_key_id}/rotate",
684
+ pathParams: ["api_key_id"],
685
+ queryParams: [],
686
+ bodyKind: "json",
687
+ responseKind: "json"
688
+ },
689
+ "apiKeys.update": {
690
+ method: "PATCH",
691
+ path: "/api-keys/{api_key_id}",
692
+ pathParams: ["api_key_id"],
693
+ queryParams: [],
694
+ bodyKind: "json",
695
+ responseKind: "json"
696
+ },
697
+ "apiKeys.usage": {
698
+ method: "GET",
699
+ path: "/api-keys/{api_key_id}/usage",
700
+ pathParams: ["api_key_id"],
701
+ queryParams: ["days"],
702
+ bodyKind: "none",
703
+ responseKind: "json"
704
+ },
705
+ "archive.listDeleted": {
706
+ method: "GET",
707
+ path: "/archive",
708
+ pathParams: [],
709
+ queryParams: ["search", "page", "limit", "sort_by", "sort_order", "entity_type"],
710
+ bodyKind: "none",
711
+ responseKind: "json"
712
+ },
713
+ "archive.purge": {
714
+ method: "DELETE",
715
+ path: "/archive/{entity_type}/{id}",
716
+ pathParams: ["entity_type", "id"],
717
+ queryParams: [],
718
+ bodyKind: "none",
719
+ responseKind: "json"
720
+ },
721
+ "archive.restore": {
722
+ method: "POST",
723
+ path: "/archive/{entity_type}/{id}/restore",
724
+ pathParams: ["entity_type", "id"],
725
+ queryParams: [],
726
+ bodyKind: "none",
727
+ responseKind: "json"
728
+ },
729
+ "archive.summary": {
730
+ method: "GET",
731
+ path: "/archive/summary",
732
+ pathParams: [],
733
+ queryParams: [],
734
+ bodyKind: "none",
735
+ responseKind: "json"
736
+ },
737
+ "audioFiles.content": {
738
+ method: "GET",
739
+ path: "/audio-files/{audio_file_id}/content",
740
+ pathParams: ["audio_file_id"],
741
+ queryParams: [],
742
+ bodyKind: "none",
743
+ responseKind: "binary"
744
+ },
745
+ "audioFiles.delete": {
746
+ method: "DELETE",
747
+ path: "/audio-files/{audio_file_id}",
748
+ pathParams: ["audio_file_id"],
749
+ queryParams: [],
750
+ bodyKind: "none",
751
+ responseKind: "json"
752
+ },
753
+ "audioFiles.generateTts": {
754
+ method: "POST",
755
+ path: "/audio-files/generate-tts",
756
+ pathParams: [],
757
+ queryParams: [],
758
+ bodyKind: "json",
759
+ responseKind: "json"
760
+ },
761
+ "audioFiles.getById": {
762
+ method: "GET",
763
+ path: "/audio-files/{audio_file_id}",
764
+ pathParams: ["audio_file_id"],
765
+ queryParams: [],
766
+ bodyKind: "none",
767
+ responseKind: "json"
768
+ },
769
+ "audioFiles.list": {
770
+ method: "GET",
771
+ path: "/audio-files",
772
+ pathParams: [],
773
+ queryParams: ["search", "page", "limit", "sort_by", "sort_order"],
774
+ bodyKind: "none",
775
+ responseKind: "json"
776
+ },
777
+ "audioFiles.previewUrl": {
778
+ method: "POST",
779
+ path: "/audio-files/preview-url",
780
+ pathParams: [],
781
+ queryParams: [],
782
+ bodyKind: "json",
783
+ responseKind: "binary"
784
+ },
785
+ "audioFiles.regenerateTts": {
786
+ method: "POST",
787
+ path: "/audio-files/{audio_file_id}/regenerate-tts",
788
+ pathParams: ["audio_file_id"],
789
+ queryParams: [],
790
+ bodyKind: "json",
791
+ responseKind: "json"
792
+ },
793
+ "audioFiles.update": {
794
+ method: "PATCH",
795
+ path: "/audio-files/{audio_file_id}",
796
+ pathParams: ["audio_file_id"],
797
+ queryParams: [],
798
+ bodyKind: "json",
799
+ responseKind: "json"
800
+ },
801
+ "audioFiles.upload": {
802
+ method: "POST",
803
+ path: "/audio-files/upload",
804
+ pathParams: [],
805
+ queryParams: [],
806
+ bodyKind: "multipart",
807
+ responseKind: "json"
808
+ },
809
+ "audit.count": {
810
+ method: "GET",
811
+ path: "/audit-logs/count",
812
+ pathParams: [],
813
+ queryParams: [
814
+ "search",
815
+ "action",
816
+ "actions",
817
+ "resource_type",
818
+ "resource_types",
819
+ "auth_kind",
820
+ "credential_id",
821
+ "retention_class",
822
+ "date_from",
823
+ "date_to"
824
+ ],
825
+ bodyKind: "none",
826
+ responseKind: "json"
827
+ },
828
+ "audit.exportCsv": {
829
+ method: "GET",
830
+ path: "/audit-logs/export",
831
+ pathParams: [],
832
+ queryParams: [
833
+ "search",
834
+ "action",
835
+ "actions",
836
+ "resource_type",
837
+ "resource_types",
838
+ "auth_kind",
839
+ "credential_id",
840
+ "retention_class",
841
+ "date_from",
842
+ "date_to"
843
+ ],
844
+ bodyKind: "none",
845
+ responseKind: "sse"
846
+ },
847
+ "audit.list": {
848
+ method: "GET",
849
+ path: "/audit-logs",
850
+ pathParams: [],
851
+ queryParams: [
852
+ "search",
853
+ "page",
854
+ "limit",
855
+ "sort_by",
856
+ "sort_order",
857
+ "action",
858
+ "actions",
859
+ "resource_type",
860
+ "resource_types",
861
+ "auth_kind",
862
+ "credential_id",
863
+ "retention_class",
864
+ "date_from",
865
+ "date_to",
866
+ "cursor"
867
+ ],
868
+ bodyKind: "none",
869
+ responseKind: "json"
870
+ },
871
+ "callRecords.count": {
872
+ method: "GET",
873
+ path: "/call-records/count",
874
+ pathParams: [],
875
+ queryParams: [
876
+ "search",
877
+ "call_record_id",
878
+ "uuid",
879
+ "sip_call_id",
880
+ "date_from",
881
+ "date_to",
882
+ "visual_plan_id",
883
+ "channel_id",
884
+ "status",
885
+ "caller_search",
886
+ "min_duration",
887
+ "max_duration",
888
+ "has_recording",
889
+ "has_transcription",
890
+ "recording_states",
891
+ "transcription_states",
892
+ "analysis_states",
893
+ "has_error",
894
+ "has_structured_analysis",
895
+ "has_structured_analysis_error",
896
+ "channel_type",
897
+ "origin",
898
+ "metadata"
899
+ ],
900
+ bodyKind: "none",
901
+ responseKind: "json"
902
+ },
903
+ "callRecords.exportCsv": {
904
+ method: "GET",
905
+ path: "/call-records/export",
906
+ pathParams: [],
907
+ queryParams: [
908
+ "date_from",
909
+ "date_to",
910
+ "visual_plan_id",
911
+ "channel_id",
912
+ "status",
913
+ "search",
914
+ "min_duration",
915
+ "max_duration",
916
+ "channel_type",
917
+ "origin",
918
+ "has_structured_analysis",
919
+ "has_structured_analysis_error",
920
+ "metadata",
921
+ "apply_table_filters",
922
+ "separator",
923
+ "columns",
924
+ "include_events"
925
+ ],
926
+ bodyKind: "none",
927
+ responseKind: "sse"
928
+ },
929
+ "callRecords.getById": {
930
+ method: "GET",
931
+ path: "/call-records/{call_record_id}",
932
+ pathParams: ["call_record_id"],
933
+ queryParams: [],
934
+ bodyKind: "none",
935
+ responseKind: "json"
936
+ },
937
+ "callRecords.getEvents": {
938
+ method: "GET",
939
+ path: "/call-records/{call_record_id}/events",
940
+ pathParams: ["call_record_id"],
941
+ queryParams: [],
942
+ bodyKind: "none",
943
+ responseKind: "json"
944
+ },
945
+ "callRecords.getRecordingUrl": {
946
+ method: "GET",
947
+ path: "/call-records/{call_record_id}/recording-url",
948
+ pathParams: ["call_record_id"],
949
+ queryParams: ["ttl_seconds"],
950
+ bodyKind: "none",
951
+ responseKind: "json"
952
+ },
953
+ "callRecords.list": {
954
+ method: "GET",
955
+ path: "/call-records",
956
+ pathParams: [],
957
+ queryParams: [
958
+ "search",
959
+ "page",
960
+ "limit",
961
+ "sort_by",
962
+ "sort_order",
963
+ "call_record_id",
964
+ "uuid",
965
+ "sip_call_id",
966
+ "date_from",
967
+ "date_to",
968
+ "visual_plan_id",
969
+ "channel_id",
970
+ "status",
971
+ "caller_search",
972
+ "min_duration",
973
+ "max_duration",
974
+ "has_recording",
975
+ "has_transcription",
976
+ "recording_states",
977
+ "transcription_states",
978
+ "analysis_states",
979
+ "has_error",
980
+ "has_structured_analysis",
981
+ "has_structured_analysis_error",
982
+ "channel_type",
983
+ "origin",
984
+ "metadata",
985
+ "cursor"
986
+ ],
987
+ bodyKind: "none",
988
+ responseKind: "json"
989
+ },
990
+ "callRecords.purgeVoiceContent": {
991
+ method: "POST",
992
+ path: "/call-records/{call_record_id}/purge-voice",
993
+ pathParams: ["call_record_id"],
994
+ queryParams: [],
995
+ bodyKind: "none",
996
+ responseKind: "json"
997
+ },
998
+ "callRecords.recordingContent": {
999
+ method: "GET",
1000
+ path: "/call-records/{call_record_id}/recording",
1001
+ pathParams: ["call_record_id"],
1002
+ queryParams: [],
1003
+ bodyKind: "none",
1004
+ responseKind: "binary"
1005
+ },
1006
+ "callRecords.retryRecording": {
1007
+ method: "POST",
1008
+ path: "/call-records/{call_record_id}/recording/retry",
1009
+ pathParams: ["call_record_id"],
1010
+ queryParams: [],
1011
+ bodyKind: "none",
1012
+ responseKind: "json"
1013
+ },
1014
+ "calls.hangupCall": {
1015
+ method: "POST",
1016
+ path: "/calls/{call_id}/hangup",
1017
+ pathParams: ["call_id"],
1018
+ queryParams: [],
1019
+ bodyKind: "none",
1020
+ responseKind: "json"
1021
+ },
1022
+ "calls.originate": {
1023
+ method: "POST",
1024
+ path: "/calls",
1025
+ pathParams: [],
1026
+ queryParams: [],
1027
+ bodyKind: "json",
1028
+ responseKind: "json"
1029
+ },
1030
+ "capabilities.get": {
1031
+ method: "GET",
1032
+ path: "/capabilities",
1033
+ pathParams: [],
1034
+ queryParams: [],
1035
+ bodyKind: "none",
1036
+ responseKind: "json"
1037
+ },
1038
+ "channels.create": {
1039
+ method: "POST",
1040
+ path: "/channels",
1041
+ pathParams: [],
1042
+ queryParams: [],
1043
+ bodyKind: "json",
1044
+ responseKind: "json"
1045
+ },
1046
+ "channels.delete": {
1047
+ method: "DELETE",
1048
+ path: "/channels/{channel_id}",
1049
+ pathParams: ["channel_id"],
1050
+ queryParams: [],
1051
+ bodyKind: "none",
1052
+ responseKind: "json"
1053
+ },
1054
+ "channels.getById": {
1055
+ method: "GET",
1056
+ path: "/channels/{channel_id}",
1057
+ pathParams: ["channel_id"],
1058
+ queryParams: [],
1059
+ bodyKind: "none",
1060
+ responseKind: "json"
1061
+ },
1062
+ "channels.list": {
1063
+ method: "GET",
1064
+ path: "/channels",
1065
+ pathParams: [],
1066
+ queryParams: ["search", "page", "limit", "sort_by", "sort_order", "channel_type", "is_active"],
1067
+ bodyKind: "none",
1068
+ responseKind: "json"
1069
+ },
1070
+ "channels.testConnection": {
1071
+ method: "POST",
1072
+ path: "/channels/test-connection",
1073
+ pathParams: [],
1074
+ queryParams: [],
1075
+ bodyKind: "json",
1076
+ responseKind: "json"
1077
+ },
1078
+ "channels.toggle": {
1079
+ method: "POST",
1080
+ path: "/channels/{channel_id}/toggle-active",
1081
+ pathParams: ["channel_id"],
1082
+ queryParams: [],
1083
+ bodyKind: "json",
1084
+ responseKind: "json"
1085
+ },
1086
+ "channels.update": {
1087
+ method: "PATCH",
1088
+ path: "/channels/{channel_id}",
1089
+ pathParams: ["channel_id"],
1090
+ queryParams: [],
1091
+ bodyKind: "json",
1092
+ responseKind: "json"
1093
+ },
1094
+ "contacts.getById": {
1095
+ method: "GET",
1096
+ path: "/contacts/{contact_id}",
1097
+ pathParams: ["contact_id"],
1098
+ queryParams: [],
1099
+ bodyKind: "none",
1100
+ responseKind: "json"
1101
+ },
1102
+ "contacts.list": {
1103
+ method: "GET",
1104
+ path: "/contacts",
1105
+ pathParams: [],
1106
+ queryParams: ["search", "page", "limit", "sort_by", "sort_order"],
1107
+ bodyKind: "none",
1108
+ responseKind: "json"
1109
+ },
1110
+ "contacts.update": {
1111
+ method: "PATCH",
1112
+ path: "/contacts/{contact_id}",
1113
+ pathParams: ["contact_id"],
1114
+ queryParams: [],
1115
+ bodyKind: "json",
1116
+ responseKind: "json"
1117
+ },
1118
+ "dashboard.capacityStatus": {
1119
+ method: "GET",
1120
+ path: "/capacity",
1121
+ pathParams: [],
1122
+ queryParams: [],
1123
+ bodyKind: "none",
1124
+ responseKind: "json"
1125
+ },
1126
+ "dashboard.watchDashboardMetrics": {
1127
+ method: "GET",
1128
+ path: "/capacity/stream",
1129
+ pathParams: [],
1130
+ queryParams: [],
1131
+ bodyKind: "none",
1132
+ responseKind: "sse"
1133
+ },
1134
+ "destinations.create": {
1135
+ method: "POST",
1136
+ path: "/destinations",
1137
+ pathParams: [],
1138
+ queryParams: [],
1139
+ bodyKind: "json",
1140
+ responseKind: "json"
1141
+ },
1142
+ "destinations.delete": {
1143
+ method: "DELETE",
1144
+ path: "/destinations/{destination_id}",
1145
+ pathParams: ["destination_id"],
1146
+ queryParams: [],
1147
+ bodyKind: "none",
1148
+ responseKind: "json"
1149
+ },
1150
+ "destinations.getById": {
1151
+ method: "GET",
1152
+ path: "/destinations/{destination_id}",
1153
+ pathParams: ["destination_id"],
1154
+ queryParams: [],
1155
+ bodyKind: "none",
1156
+ responseKind: "json"
1157
+ },
1158
+ "destinations.list": {
1159
+ method: "GET",
1160
+ path: "/destinations",
1161
+ pathParams: [],
1162
+ queryParams: ["search", "page", "limit", "sort_by", "sort_order"],
1163
+ bodyKind: "none",
1164
+ responseKind: "json"
1165
+ },
1166
+ "destinations.update": {
1167
+ method: "PATCH",
1168
+ path: "/destinations/{destination_id}",
1169
+ pathParams: ["destination_id"],
1170
+ queryParams: [],
1171
+ bodyKind: "json",
1172
+ responseKind: "json"
1173
+ },
1174
+ "dialerAttempts.list": {
1175
+ method: "GET",
1176
+ path: "/dialer/campaigns/{campaign_id}/attempts",
1177
+ pathParams: ["campaign_id"],
1178
+ queryParams: ["search", "page", "limit", "sort_by", "sort_order", "date_from", "date_to", "status", "contact_id"],
1179
+ bodyKind: "none",
1180
+ responseKind: "json"
1181
+ },
1182
+ "dialerCampaigns.control": {
1183
+ method: "POST",
1184
+ path: "/dialer/campaigns/{campaign_id}/control",
1185
+ pathParams: ["campaign_id"],
1186
+ queryParams: [],
1187
+ bodyKind: "json",
1188
+ responseKind: "json"
1189
+ },
1190
+ "dialerCampaigns.create": {
1191
+ method: "POST",
1192
+ path: "/dialer/campaigns",
1193
+ pathParams: [],
1194
+ queryParams: [],
1195
+ bodyKind: "json",
1196
+ responseKind: "json"
1197
+ },
1198
+ "dialerCampaigns.delete": {
1199
+ method: "DELETE",
1200
+ path: "/dialer/campaigns/{campaign_id}",
1201
+ pathParams: ["campaign_id"],
1202
+ queryParams: [],
1203
+ bodyKind: "none",
1204
+ responseKind: "json"
1205
+ },
1206
+ "dialerCampaigns.get": {
1207
+ method: "GET",
1208
+ path: "/dialer/campaigns/{campaign_id}",
1209
+ pathParams: ["campaign_id"],
1210
+ queryParams: [],
1211
+ bodyKind: "none",
1212
+ responseKind: "json"
1213
+ },
1214
+ "dialerCampaigns.list": {
1215
+ method: "GET",
1216
+ path: "/dialer/campaigns",
1217
+ pathParams: [],
1218
+ queryParams: ["search", "page", "limit", "sort_by", "sort_order", "status"],
1219
+ bodyKind: "none",
1220
+ responseKind: "json"
1221
+ },
1222
+ "dialerCampaigns.liveStats": {
1223
+ method: "GET",
1224
+ path: "/dialer/campaigns/{campaign_id}/stats/stream",
1225
+ pathParams: ["campaign_id"],
1226
+ queryParams: [],
1227
+ bodyKind: "none",
1228
+ responseKind: "sse"
1229
+ },
1230
+ "dialerCampaigns.orgLiveStats": {
1231
+ method: "GET",
1232
+ path: "/dialer/campaigns/stats/stream",
1233
+ pathParams: [],
1234
+ queryParams: [],
1235
+ bodyKind: "none",
1236
+ responseKind: "sse"
1237
+ },
1238
+ "dialerCampaigns.stats": {
1239
+ method: "GET",
1240
+ path: "/dialer/campaigns/{campaign_id}/stats",
1241
+ pathParams: ["campaign_id"],
1242
+ queryParams: [],
1243
+ bodyKind: "none",
1244
+ responseKind: "json"
1245
+ },
1246
+ "dialerCampaigns.summary": {
1247
+ method: "GET",
1248
+ path: "/dialer/campaigns/summary",
1249
+ pathParams: [],
1250
+ queryParams: [],
1251
+ bodyKind: "none",
1252
+ responseKind: "json"
1253
+ },
1254
+ "dialerCampaigns.update": {
1255
+ method: "PATCH",
1256
+ path: "/dialer/campaigns/{campaign_id}",
1257
+ pathParams: ["campaign_id"],
1258
+ queryParams: [],
1259
+ bodyKind: "json",
1260
+ responseKind: "json"
1261
+ },
1262
+ "dialerContacts.add": {
1263
+ method: "POST",
1264
+ path: "/dialer/campaigns/{campaign_id}/contacts",
1265
+ pathParams: ["campaign_id"],
1266
+ queryParams: [],
1267
+ bodyKind: "json",
1268
+ responseKind: "json"
1269
+ },
1270
+ "dialerContacts.bulkCancel": {
1271
+ method: "POST",
1272
+ path: "/dialer/campaigns/{campaign_id}/contacts/bulk-cancel",
1273
+ pathParams: ["campaign_id"],
1274
+ queryParams: [],
1275
+ bodyKind: "json",
1276
+ responseKind: "json"
1277
+ },
1278
+ "dialerContacts.bulkRequeue": {
1279
+ method: "POST",
1280
+ path: "/dialer/campaigns/{campaign_id}/contacts/bulk-requeue",
1281
+ pathParams: ["campaign_id"],
1282
+ queryParams: [],
1283
+ bodyKind: "json",
1284
+ responseKind: "json"
1285
+ },
1286
+ "dialerContacts.cancel": {
1287
+ method: "POST",
1288
+ path: "/dialer/campaigns/{campaign_id}/contacts/{contact_id}/cancel",
1289
+ pathParams: ["campaign_id", "contact_id"],
1290
+ queryParams: [],
1291
+ bodyKind: "none",
1292
+ responseKind: "json"
1293
+ },
1294
+ "dialerContacts.exportCsv": {
1295
+ method: "GET",
1296
+ path: "/dialer/campaigns/{campaign_id}/contacts/export",
1297
+ pathParams: ["campaign_id"],
1298
+ queryParams: ["date_from", "date_to", "status", "search"],
1299
+ bodyKind: "none",
1300
+ responseKind: "sse"
1301
+ },
1302
+ "dialerContacts.get": {
1303
+ method: "GET",
1304
+ path: "/dialer/campaigns/{campaign_id}/contacts/{contact_id}",
1305
+ pathParams: ["campaign_id", "contact_id"],
1306
+ queryParams: [],
1307
+ bodyKind: "none",
1308
+ responseKind: "json"
1309
+ },
1310
+ "dialerContacts.list": {
1311
+ method: "GET",
1312
+ path: "/dialer/campaigns/{campaign_id}/contacts",
1313
+ pathParams: ["campaign_id"],
1314
+ queryParams: ["search", "page", "limit", "sort_by", "sort_order", "date_from", "date_to", "status"],
1315
+ bodyKind: "none",
1316
+ responseKind: "json"
1317
+ },
1318
+ "dialerContacts.remove": {
1319
+ method: "POST",
1320
+ path: "/dialer/campaigns/{campaign_id}/contacts/bulk-remove",
1321
+ pathParams: ["campaign_id"],
1322
+ queryParams: [],
1323
+ bodyKind: "json",
1324
+ responseKind: "json"
1325
+ },
1326
+ "dialerContacts.requeue": {
1327
+ method: "POST",
1328
+ path: "/dialer/campaigns/{campaign_id}/contacts/{contact_id}/requeue",
1329
+ pathParams: ["campaign_id", "contact_id"],
1330
+ queryParams: [],
1331
+ bodyKind: "none",
1332
+ responseKind: "json"
1333
+ },
1334
+ "dialerContacts.requeueAll": {
1335
+ method: "POST",
1336
+ path: "/dialer/campaigns/{campaign_id}/contacts/requeue-all",
1337
+ pathParams: ["campaign_id"],
1338
+ queryParams: [],
1339
+ bodyKind: "json",
1340
+ responseKind: "json"
1341
+ },
1342
+ "dialerContacts.update": {
1343
+ method: "PATCH",
1344
+ path: "/dialer/campaigns/{campaign_id}/contacts/{contact_id}",
1345
+ pathParams: ["campaign_id", "contact_id"],
1346
+ queryParams: [],
1347
+ bodyKind: "json",
1348
+ responseKind: "json"
1349
+ },
1350
+ "dialerDnc.add": {
1351
+ method: "POST",
1352
+ path: "/dialer/dnc",
1353
+ pathParams: [],
1354
+ queryParams: [],
1355
+ bodyKind: "json",
1356
+ responseKind: "json"
1357
+ },
1358
+ "dialerDnc.bulkImport": {
1359
+ method: "POST",
1360
+ path: "/dialer/dnc/bulk-import",
1361
+ pathParams: [],
1362
+ queryParams: [],
1363
+ bodyKind: "json",
1364
+ responseKind: "json"
1365
+ },
1366
+ "dialerDnc.bulkRemove": {
1367
+ method: "POST",
1368
+ path: "/dialer/dnc/bulk-remove",
1369
+ pathParams: [],
1370
+ queryParams: [],
1371
+ bodyKind: "json",
1372
+ responseKind: "json"
1373
+ },
1374
+ "dialerDnc.list": {
1375
+ method: "GET",
1376
+ path: "/dialer/dnc",
1377
+ pathParams: [],
1378
+ queryParams: ["search", "page", "limit", "sort_by", "sort_order"],
1379
+ bodyKind: "none",
1380
+ responseKind: "json"
1381
+ },
1382
+ "dialerDnc.remove": {
1383
+ method: "DELETE",
1384
+ path: "/dialer/dnc/{dnc_id}",
1385
+ pathParams: ["dnc_id"],
1386
+ queryParams: [],
1387
+ bodyKind: "none",
1388
+ responseKind: "json"
1389
+ },
1390
+ "dialerImports.create": {
1391
+ method: "POST",
1392
+ path: "/dialer/campaigns/{campaign_id}/imports",
1393
+ pathParams: ["campaign_id"],
1394
+ queryParams: [],
1395
+ bodyKind: "json",
1396
+ responseKind: "json"
1397
+ },
1398
+ "dialerImports.get": {
1399
+ method: "GET",
1400
+ path: "/dialer/imports/{import_job_id}",
1401
+ pathParams: ["import_job_id"],
1402
+ queryParams: [],
1403
+ bodyKind: "none",
1404
+ responseKind: "json"
1405
+ },
1406
+ "dialerImports.invalidRows": {
1407
+ method: "GET",
1408
+ path: "/dialer/imports/{import_job_id}/invalid-rows",
1409
+ pathParams: ["import_job_id"],
1410
+ queryParams: [],
1411
+ bodyKind: "none",
1412
+ responseKind: "json"
1413
+ },
1414
+ "dialerImports.progress": {
1415
+ method: "GET",
1416
+ path: "/dialer/imports/{import_job_id}/progress",
1417
+ pathParams: ["import_job_id"],
1418
+ queryParams: [],
1419
+ bodyKind: "none",
1420
+ responseKind: "sse"
1421
+ },
1422
+ "holidays.countries": {
1423
+ method: "GET",
1424
+ path: "/holidays/countries",
1425
+ pathParams: [],
1426
+ queryParams: [],
1427
+ bodyKind: "none",
1428
+ responseKind: "json"
1429
+ },
1430
+ "holidays.create": {
1431
+ method: "POST",
1432
+ path: "/holidays/groups/{holiday_group_id}/holidays",
1433
+ pathParams: ["holiday_group_id"],
1434
+ queryParams: [],
1435
+ bodyKind: "json",
1436
+ responseKind: "json"
1437
+ },
1438
+ "holidays.delete": {
1439
+ method: "DELETE",
1440
+ path: "/holidays/{holiday_id}",
1441
+ pathParams: ["holiday_id"],
1442
+ queryParams: [],
1443
+ bodyKind: "none",
1444
+ responseKind: "json"
1445
+ },
1446
+ "holidays.groups.create": {
1447
+ method: "POST",
1448
+ path: "/holidays/groups",
1449
+ pathParams: [],
1450
+ queryParams: [],
1451
+ bodyKind: "json",
1452
+ responseKind: "json"
1453
+ },
1454
+ "holidays.groups.delete": {
1455
+ method: "DELETE",
1456
+ path: "/holidays/groups/{holiday_group_id}",
1457
+ pathParams: ["holiday_group_id"],
1458
+ queryParams: [],
1459
+ bodyKind: "none",
1460
+ responseKind: "json"
1461
+ },
1462
+ "holidays.groups.getById": {
1463
+ method: "GET",
1464
+ path: "/holidays/groups/{holiday_group_id}",
1465
+ pathParams: ["holiday_group_id"],
1466
+ queryParams: [],
1467
+ bodyKind: "none",
1468
+ responseKind: "json"
1469
+ },
1470
+ "holidays.groups.list": {
1471
+ method: "GET",
1472
+ path: "/holidays/groups",
1473
+ pathParams: [],
1474
+ queryParams: ["search", "page", "limit", "sort_by", "sort_order"],
1475
+ bodyKind: "none",
1476
+ responseKind: "json"
1477
+ },
1478
+ "holidays.groups.update": {
1479
+ method: "PATCH",
1480
+ path: "/holidays/groups/{holiday_group_id}",
1481
+ pathParams: ["holiday_group_id"],
1482
+ queryParams: [],
1483
+ bodyKind: "json",
1484
+ responseKind: "json"
1485
+ },
1486
+ "holidays.import": {
1487
+ method: "POST",
1488
+ path: "/holidays/groups/{holiday_group_id}/import",
1489
+ pathParams: ["holiday_group_id"],
1490
+ queryParams: [],
1491
+ bodyKind: "json",
1492
+ responseKind: "json"
1493
+ },
1494
+ "holidays.list": {
1495
+ method: "GET",
1496
+ path: "/holidays/groups/{holiday_group_id}/holidays",
1497
+ pathParams: ["holiday_group_id"],
1498
+ queryParams: ["page", "limit"],
1499
+ bodyKind: "none",
1500
+ responseKind: "json"
1501
+ },
1502
+ "holidays.previewImport": {
1503
+ method: "GET",
1504
+ path: "/holidays/preview",
1505
+ pathParams: [],
1506
+ queryParams: ["country_code", "year"],
1507
+ bodyKind: "none",
1508
+ responseKind: "json"
1509
+ },
1510
+ "holidays.update": {
1511
+ method: "PATCH",
1512
+ path: "/holidays/{holiday_id}",
1513
+ pathParams: ["holiday_id"],
1514
+ queryParams: [],
1515
+ bodyKind: "json",
1516
+ responseKind: "json"
1517
+ },
1518
+ "license.status": {
1519
+ method: "GET",
1520
+ path: "/license/status",
1521
+ pathParams: [],
1522
+ queryParams: [],
1523
+ bodyKind: "none",
1524
+ responseKind: "json"
1525
+ },
1526
+ "oauthGrants.list": {
1527
+ method: "GET",
1528
+ path: "/oauth-grants",
1529
+ pathParams: [],
1530
+ queryParams: ["search", "page", "limit", "sort_by", "sort_order"],
1531
+ bodyKind: "none",
1532
+ responseKind: "json"
1533
+ },
1534
+ "oauthGrants.revoke": {
1535
+ method: "DELETE",
1536
+ path: "/oauth-grants/{oauth_grant_id}",
1537
+ pathParams: ["oauth_grant_id"],
1538
+ queryParams: [],
1539
+ bodyKind: "none",
1540
+ responseKind: "json"
1541
+ },
1542
+ "oauthGrants.usage": {
1543
+ method: "GET",
1544
+ path: "/oauth-grants/{oauth_grant_id}/usage",
1545
+ pathParams: ["oauth_grant_id"],
1546
+ queryParams: ["days"],
1547
+ bodyKind: "none",
1548
+ responseKind: "json"
1549
+ },
1550
+ "orgSettings.getDialer": {
1551
+ method: "GET",
1552
+ path: "/organization/dialer-settings",
1553
+ pathParams: [],
1554
+ queryParams: [],
1555
+ bodyKind: "none",
1556
+ responseKind: "json"
1557
+ },
1558
+ "orgSettings.upsertDialer": {
1559
+ method: "PATCH",
1560
+ path: "/organization/dialer-settings",
1561
+ pathParams: [],
1562
+ queryParams: [],
1563
+ bodyKind: "json",
1564
+ responseKind: "json"
1565
+ },
1566
+ "schedules.create": {
1567
+ method: "POST",
1568
+ path: "/schedules",
1569
+ pathParams: [],
1570
+ queryParams: [],
1571
+ bodyKind: "json",
1572
+ responseKind: "json"
1573
+ },
1574
+ "schedules.delete": {
1575
+ method: "DELETE",
1576
+ path: "/schedules/{schedule_id}",
1577
+ pathParams: ["schedule_id"],
1578
+ queryParams: [],
1579
+ bodyKind: "none",
1580
+ responseKind: "json"
1581
+ },
1582
+ "schedules.getById": {
1583
+ method: "GET",
1584
+ path: "/schedules/{schedule_id}",
1585
+ pathParams: ["schedule_id"],
1586
+ queryParams: [],
1587
+ bodyKind: "none",
1588
+ responseKind: "json"
1589
+ },
1590
+ "schedules.list": {
1591
+ method: "GET",
1592
+ path: "/schedules",
1593
+ pathParams: [],
1594
+ queryParams: ["search", "page", "limit", "sort_by", "sort_order"],
1595
+ bodyKind: "none",
1596
+ responseKind: "json"
1597
+ },
1598
+ "schedules.update": {
1599
+ method: "PATCH",
1600
+ path: "/schedules/{schedule_id}",
1601
+ pathParams: ["schedule_id"],
1602
+ queryParams: [],
1603
+ bodyKind: "json",
1604
+ responseKind: "json"
1605
+ },
1606
+ "secrets.list": {
1607
+ method: "GET",
1608
+ path: "/secrets",
1609
+ pathParams: [],
1610
+ queryParams: ["search", "page", "limit", "sort_by", "sort_order"],
1611
+ bodyKind: "none",
1612
+ responseKind: "json"
1613
+ },
1614
+ "secrets.listNames": {
1615
+ method: "GET",
1616
+ path: "/secrets/names",
1617
+ pathParams: [],
1618
+ queryParams: [],
1619
+ bodyKind: "none",
1620
+ responseKind: "json"
1621
+ },
1622
+ "tts.listModels": {
1623
+ method: "GET",
1624
+ path: "/tts/models",
1625
+ pathParams: [],
1626
+ queryParams: [],
1627
+ bodyKind: "none",
1628
+ responseKind: "json"
1629
+ },
1630
+ "tts.listVoices": {
1631
+ method: "GET",
1632
+ path: "/tts/voices",
1633
+ pathParams: [],
1634
+ queryParams: ["language", "model"],
1635
+ bodyKind: "none",
1636
+ responseKind: "json"
1637
+ },
1638
+ "tts.preview": {
1639
+ method: "POST",
1640
+ path: "/tts/preview",
1641
+ pathParams: [],
1642
+ queryParams: [],
1643
+ bodyKind: "json",
1644
+ responseKind: "binary"
1645
+ },
1646
+ "users.activateMember": {
1647
+ method: "POST",
1648
+ path: "/members/{user_id}/activate",
1649
+ pathParams: ["user_id"],
1650
+ queryParams: [],
1651
+ bodyKind: "none",
1652
+ responseKind: "json"
1653
+ },
1654
+ "users.createMember": {
1655
+ method: "POST",
1656
+ path: "/members",
1657
+ pathParams: [],
1658
+ queryParams: [],
1659
+ bodyKind: "json",
1660
+ responseKind: "json"
1661
+ },
1662
+ "users.listMembers": {
1663
+ method: "GET",
1664
+ path: "/members",
1665
+ pathParams: [],
1666
+ queryParams: ["search", "page", "limit", "sort_by", "sort_order", "status"],
1667
+ bodyKind: "none",
1668
+ responseKind: "json"
1669
+ },
1670
+ "users.me": {
1671
+ method: "GET",
1672
+ path: "/users/me",
1673
+ pathParams: [],
1674
+ queryParams: [],
1675
+ bodyKind: "none",
1676
+ responseKind: "json"
1677
+ },
1678
+ "users.removeMember": {
1679
+ method: "DELETE",
1680
+ path: "/members/{user_id}",
1681
+ pathParams: ["user_id"],
1682
+ queryParams: [],
1683
+ bodyKind: "none",
1684
+ responseKind: "json"
1685
+ },
1686
+ "users.suspendMember": {
1687
+ method: "POST",
1688
+ path: "/members/{user_id}/suspend",
1689
+ pathParams: ["user_id"],
1690
+ queryParams: [],
1691
+ bodyKind: "none",
1692
+ responseKind: "json"
1693
+ },
1694
+ "users.updateRole": {
1695
+ method: "PATCH",
1696
+ path: "/members/{user_id}/role",
1697
+ pathParams: ["user_id"],
1698
+ queryParams: [],
1699
+ bodyKind: "json",
1700
+ responseKind: "json"
1701
+ },
1702
+ "visualPlans.clone": {
1703
+ method: "POST",
1704
+ path: "/visual-plans/{plan_id}/clone",
1705
+ pathParams: ["plan_id"],
1706
+ queryParams: [],
1707
+ bodyKind: "json",
1708
+ responseKind: "json"
1709
+ },
1710
+ "visualPlans.create": {
1711
+ method: "POST",
1712
+ path: "/visual-plans",
1713
+ pathParams: [],
1714
+ queryParams: [],
1715
+ bodyKind: "json",
1716
+ responseKind: "json"
1717
+ },
1718
+ "visualPlans.delete": {
1719
+ method: "DELETE",
1720
+ path: "/visual-plans/{plan_id}",
1721
+ pathParams: ["plan_id"],
1722
+ queryParams: [],
1723
+ bodyKind: "none",
1724
+ responseKind: "json"
1725
+ },
1726
+ "visualPlans.getById": {
1727
+ method: "GET",
1728
+ path: "/visual-plans/{plan_id}",
1729
+ pathParams: ["plan_id"],
1730
+ queryParams: [],
1731
+ bodyKind: "none",
1732
+ responseKind: "json"
1733
+ },
1734
+ "visualPlans.importDraft": {
1735
+ method: "POST",
1736
+ path: "/visual-plans/{plan_id}/import",
1737
+ pathParams: ["plan_id"],
1738
+ queryParams: [],
1739
+ bodyKind: "json",
1740
+ responseKind: "json"
1741
+ },
1742
+ "visualPlans.list": {
1743
+ method: "GET",
1744
+ path: "/visual-plans",
1745
+ pathParams: [],
1746
+ queryParams: ["search", "page", "limit", "sort_by", "sort_order"],
1747
+ bodyKind: "none",
1748
+ responseKind: "json"
1749
+ },
1750
+ "visualPlans.listVersions": {
1751
+ method: "GET",
1752
+ path: "/visual-plans/{plan_id}/versions",
1753
+ pathParams: ["plan_id"],
1754
+ queryParams: [],
1755
+ bodyKind: "none",
1756
+ responseKind: "json"
1757
+ },
1758
+ "visualPlans.publish": {
1759
+ method: "POST",
1760
+ path: "/visual-plans/{plan_id}/publish",
1761
+ pathParams: ["plan_id"],
1762
+ queryParams: [],
1763
+ bodyKind: "json",
1764
+ responseKind: "json"
1765
+ },
1766
+ "visualPlans.update": {
1767
+ method: "PATCH",
1768
+ path: "/visual-plans/{plan_id}",
1769
+ pathParams: ["plan_id"],
1770
+ queryParams: [],
1771
+ bodyKind: "json",
1772
+ responseKind: "json"
1773
+ },
1774
+ "visualPlans.validate": {
1775
+ method: "POST",
1776
+ path: "/visual-plans/validate",
1777
+ pathParams: [],
1778
+ queryParams: [],
1779
+ bodyKind: "json",
1780
+ responseKind: "json"
1781
+ },
1782
+ "webhooks.deliveries.aggregates.get": {
1783
+ method: "GET",
1784
+ path: "/webhooks/deliveries/aggregates/{day}",
1785
+ pathParams: ["day"],
1786
+ queryParams: ["webhook_endpoint_id"],
1787
+ bodyKind: "none",
1788
+ responseKind: "json"
1789
+ },
1790
+ "webhooks.deliveries.aggregates.list": {
1791
+ method: "GET",
1792
+ path: "/webhooks/deliveries/aggregates",
1793
+ pathParams: [],
1794
+ queryParams: [
1795
+ "limit",
1796
+ "cursor",
1797
+ "sort_order",
1798
+ "webhook_endpoint_id",
1799
+ "event_type",
1800
+ "outcome",
1801
+ "http_class",
1802
+ "date_from",
1803
+ "date_to"
1804
+ ],
1805
+ bodyKind: "none",
1806
+ responseKind: "json"
1807
+ },
1808
+ "webhooks.deliveries.count": {
1809
+ method: "GET",
1810
+ path: "/webhooks/deliveries/count",
1811
+ pathParams: [],
1812
+ queryParams: ["webhook_endpoint_id", "event_type", "status", "date_from", "date_to"],
1813
+ bodyKind: "none",
1814
+ responseKind: "json"
1815
+ },
1816
+ "webhooks.deliveries.getById": {
1817
+ method: "GET",
1818
+ path: "/webhooks/deliveries/{delivery_log_id}",
1819
+ pathParams: ["delivery_log_id"],
1820
+ queryParams: [],
1821
+ bodyKind: "none",
1822
+ responseKind: "json"
1823
+ },
1824
+ "webhooks.deliveries.list": {
1825
+ method: "GET",
1826
+ path: "/webhooks/deliveries",
1827
+ pathParams: [],
1828
+ queryParams: [
1829
+ "limit",
1830
+ "cursor",
1831
+ "sort_order",
1832
+ "webhook_endpoint_id",
1833
+ "event_type",
1834
+ "status",
1835
+ "date_from",
1836
+ "date_to"
1837
+ ],
1838
+ bodyKind: "none",
1839
+ responseKind: "json"
1840
+ },
1841
+ "webhooks.deliveries.retention": {
1842
+ method: "GET",
1843
+ path: "/webhooks/deliveries/retention",
1844
+ pathParams: [],
1845
+ queryParams: [],
1846
+ bodyKind: "none",
1847
+ responseKind: "json"
1848
+ },
1849
+ "webhooks.deliveries.retry": {
1850
+ method: "POST",
1851
+ path: "/webhooks/deliveries/{delivery_log_id}/retry",
1852
+ pathParams: ["delivery_log_id"],
1853
+ queryParams: [],
1854
+ bodyKind: "none",
1855
+ responseKind: "json"
1856
+ },
1857
+ "webhooks.endpoints.create": {
1858
+ method: "POST",
1859
+ path: "/webhooks",
1860
+ pathParams: [],
1861
+ queryParams: [],
1862
+ bodyKind: "json",
1863
+ responseKind: "json"
1864
+ },
1865
+ "webhooks.endpoints.delete": {
1866
+ method: "DELETE",
1867
+ path: "/webhooks/{webhook_endpoint_id}",
1868
+ pathParams: ["webhook_endpoint_id"],
1869
+ queryParams: [],
1870
+ bodyKind: "none",
1871
+ responseKind: "json"
1872
+ },
1873
+ "webhooks.endpoints.getById": {
1874
+ method: "GET",
1875
+ path: "/webhooks/{webhook_endpoint_id}",
1876
+ pathParams: ["webhook_endpoint_id"],
1877
+ queryParams: [],
1878
+ bodyKind: "none",
1879
+ responseKind: "json"
1880
+ },
1881
+ "webhooks.endpoints.list": {
1882
+ method: "GET",
1883
+ path: "/webhooks",
1884
+ pathParams: [],
1885
+ queryParams: ["search", "page", "limit", "sort_by", "sort_order"],
1886
+ bodyKind: "none",
1887
+ responseKind: "json"
1888
+ },
1889
+ "webhooks.endpoints.rotateSecret": {
1890
+ method: "POST",
1891
+ path: "/webhooks/{webhook_endpoint_id}/rotate-secret",
1892
+ pathParams: ["webhook_endpoint_id"],
1893
+ queryParams: [],
1894
+ bodyKind: "none",
1895
+ responseKind: "json"
1896
+ },
1897
+ "webhooks.endpoints.update": {
1898
+ method: "PATCH",
1899
+ path: "/webhooks/{webhook_endpoint_id}",
1900
+ pathParams: ["webhook_endpoint_id"],
1901
+ queryParams: [],
1902
+ bodyKind: "json",
1903
+ responseKind: "json"
1904
+ },
1905
+ "webhooks.events.list": {
1906
+ method: "GET",
1907
+ path: "/webhooks/events",
1908
+ pathParams: [],
1909
+ queryParams: [],
1910
+ bodyKind: "none",
1911
+ responseKind: "json"
1912
+ }
1913
+ };
1914
+
1915
+ // src/transport.ts
1916
+ function splitOperationInput(op, input) {
1917
+ const record = isPlainObject(input) ? input : {};
1918
+ const path = {};
1919
+ const query = {};
1920
+ const body = {};
1921
+ const pathSet = new Set(op.pathParams);
1922
+ const querySet = new Set(op.queryParams);
1923
+ for (const [key, value] of Object.entries(record)) {
1924
+ if (pathSet.has(key)) {
1925
+ path[key] = encodeURIComponent(String(value));
1926
+ } else if (querySet.has(key)) {
1927
+ query[key] = value;
1928
+ } else if (op.bodyKind !== "none") {
1929
+ body[key] = value;
1930
+ }
1931
+ }
1932
+ return { path, query, body };
1933
+ }
1934
+ function isRecord2(value) {
1935
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1936
+ }
1937
+ function isPlainObject(value) {
1938
+ if (!isRecord2(value))
1939
+ return false;
1940
+ const proto = Object.getPrototypeOf(value);
1941
+ return proto === Object.prototype || proto === null;
1942
+ }
1943
+ var SAFE_ERROR_NAMES = new Set([
1944
+ "TypeError",
1945
+ "AbortError",
1946
+ "TimeoutError",
1947
+ "DOMException",
1948
+ "Error",
1949
+ "SyntaxError"
1950
+ ]);
1951
+ var SAFE_ERROR_CODES = new Set([
1952
+ "ECONNREFUSED",
1953
+ "ECONNRESET",
1954
+ "ENOTFOUND",
1955
+ "EAI_AGAIN",
1956
+ "ETIMEDOUT",
1957
+ "EHOSTUNREACH",
1958
+ "ENETUNREACH",
1959
+ "EPIPE",
1960
+ "CERT_HAS_EXPIRED",
1961
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
1962
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
1963
+ "UND_ERR_CONNECT_TIMEOUT",
1964
+ "UND_ERR_HEADERS_TIMEOUT",
1965
+ "UND_ERR_BODY_TIMEOUT",
1966
+ "UND_ERR_SOCKET",
1967
+ "UND_ERR_ABORT",
1968
+ "UND_ERR_INFO",
1969
+ "UND_ERR_CLOSED",
1970
+ "UND_ERR_DESTROYED",
1971
+ "UND_ERR_REQ_CONTENT_LENGTH_MISMATCH",
1972
+ "UND_ERR_RES_CONTENT_LENGTH_MISMATCH",
1973
+ "UND_ERR_CONTINUE_100",
1974
+ "UND_ERR_HEADERS_OVERFLOW",
1975
+ "UND_ERR_BODY_TOO_LARGE",
1976
+ "UND_ERR_RESPONSE_STATUS_CODE",
1977
+ "UND_ERR_INVALID_ARG",
1978
+ "UND_ERR_NOT_SUPPORTED"
1979
+ ]);
1980
+ function sanitizeCause(error) {
1981
+ if (!(error instanceof Error))
1982
+ return;
1983
+ const cause = {
1984
+ name: SAFE_ERROR_NAMES.has(error.name) ? error.name : "Error"
1985
+ };
1986
+ if (isRecord2(error)) {
1987
+ const code = error["code"];
1988
+ if (typeof code === "string" && SAFE_ERROR_CODES.has(code))
1989
+ cause.code = code;
1990
+ }
1991
+ return cause;
1992
+ }
1993
+ function jsonScalar(value) {
1994
+ if (value instanceof Date)
1995
+ return Number.isNaN(value.getTime()) ? null : value.toISOString();
1996
+ if (typeof value === "bigint" || value instanceof RegExp || value instanceof URL)
1997
+ return value.toString();
1998
+ if (typeof value === "number" && Number.isNaN(value))
1999
+ return null;
2000
+ return value;
2001
+ }
2002
+ function escapeSegment(segment) {
2003
+ const bs = String.fromCharCode(92);
2004
+ return segment.split(bs).join(bs + bs).split("[").join(bs + "[").split("]").join(bs + "]");
2005
+ }
2006
+ function bracketPath(segments) {
2007
+ return segments.map((segment) => typeof segment === "number" ? String(segment) : escapeSegment(segment)).reduce((head, segment, index) => index === 0 ? head + segment : `${head}[${segment}]`);
2008
+ }
2009
+ function flattenBracket(value, segments, out) {
2010
+ if (Array.isArray(value)) {
2011
+ value.forEach((item, index) => flattenBracket(item, [...segments, index], out));
2012
+ } else if (isPlainObject(value)) {
2013
+ for (const [key, entry] of Object.entries(value))
2014
+ flattenBracket(entry, [...segments, key], out);
2015
+ } else {
2016
+ out.push([bracketPath(segments), value]);
2017
+ }
2018
+ }
2019
+ function appendQueryValue(params, path, value) {
2020
+ const scalar = jsonScalar(value);
2021
+ if (typeof scalar === "string" || typeof scalar === "number" || typeof scalar === "boolean") {
2022
+ params.append(path, String(scalar));
2023
+ }
2024
+ }
2025
+ function encodeQueryParams(query) {
2026
+ const params = new URLSearchParams;
2027
+ const flat = [];
2028
+ flattenBracket(query, [], flat);
2029
+ for (const [path, value] of flat)
2030
+ appendQueryValue(params, path, value);
2031
+ return params.toString();
2032
+ }
2033
+ function encodeMultipartForm(body) {
2034
+ const form = new FormData;
2035
+ const flat = [];
2036
+ flattenBracket(body, [], flat);
2037
+ for (const [path, value] of flat) {
2038
+ const scalar = jsonScalar(value);
2039
+ if (typeof scalar === "string" || typeof scalar === "number" || typeof scalar === "boolean") {
2040
+ form.append(path, String(scalar));
2041
+ } else if (scalar instanceof Blob) {
2042
+ form.append(path, scalar);
2043
+ }
2044
+ }
2045
+ return form;
2046
+ }
2047
+ function encodeBody(bodyKind, body) {
2048
+ if (bodyKind === "multipart")
2049
+ return { contentType: undefined, body: encodeMultipartForm(body) };
2050
+ return { contentType: "application/json", body: JSON.stringify(body) };
2051
+ }
2052
+ function mergeRequestHeaders(base, extra) {
2053
+ const merged = new Headers(base);
2054
+ if (extra !== undefined)
2055
+ new Headers(extra).forEach((value, key) => merged.set(key, value));
2056
+ return merged;
2057
+ }
2058
+ function abortError(signal, timeoutMs) {
2059
+ if (signal?.aborted === true) {
2060
+ return new NivaConnectionError("request aborted by the caller", { reason: "aborted" });
2061
+ }
2062
+ return new NivaConnectionError(`request timed out after ${timeoutMs}ms`, { reason: "timeout" });
2063
+ }
2064
+ async function fetchWithTimeout(fetchImpl, url, init, timeoutMs) {
2065
+ const callerSignal = init.signal instanceof AbortSignal ? init.signal : undefined;
2066
+ if (callerSignal?.aborted === true)
2067
+ throw abortError(callerSignal, timeoutMs);
2068
+ const controller = new AbortController;
2069
+ const onCallerAbort = () => controller.abort();
2070
+ callerSignal?.addEventListener("abort", onCallerAbort, { once: true });
2071
+ const timer = setTimeout(() => {
2072
+ callerSignal?.removeEventListener("abort", onCallerAbort);
2073
+ controller.abort();
2074
+ }, timeoutMs);
2075
+ try {
2076
+ return await fetchImpl(url, { ...init, signal: controller.signal });
2077
+ } catch (error) {
2078
+ if (error instanceof Error && error.name === "AbortError")
2079
+ throw abortError(callerSignal, timeoutMs);
2080
+ throw new NivaConnectionError("request failed", { reason: "network", cause: sanitizeCause(error) });
2081
+ } finally {
2082
+ clearTimeout(timer);
2083
+ }
2084
+ }
2085
+ function isDefinedErrorBody(body) {
2086
+ if (!isPlainObject(body))
2087
+ return false;
2088
+ return body["defined"] === true && typeof body["code"] === "string" && typeof body["status"] === "number" && typeof body["message"] === "string";
2089
+ }
2090
+ async function parseApiError(response, operation) {
2091
+ const requestId = response.headers.get("x-request-id") ?? undefined;
2092
+ let body;
2093
+ try {
2094
+ body = await response.json();
2095
+ } catch {
2096
+ body = undefined;
2097
+ }
2098
+ if (isDefinedErrorBody(body)) {
2099
+ return new NivaApiError({
2100
+ status: body.status,
2101
+ code: body.code,
2102
+ message: body.message,
2103
+ data: body.data,
2104
+ requestId,
2105
+ operation
2106
+ });
2107
+ }
2108
+ return new NivaApiError({
2109
+ status: response.status,
2110
+ code: "UNEXPECTED_RESPONSE",
2111
+ message: `request failed with status ${response.status}`,
2112
+ requestId,
2113
+ operation
2114
+ });
2115
+ }
2116
+ async function readJsonResponse(response) {
2117
+ if (response.status === 204)
2118
+ return;
2119
+ return await response.json();
2120
+ }
2121
+
2122
+ // src/handshake.ts
2123
+ var PUBLISHED_PACKAGE = "@sippulse/niva-sdk";
2124
+ function isRecord3(value) {
2125
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2126
+ }
2127
+ function parseVersion(value) {
2128
+ if (typeof value !== "string")
2129
+ return;
2130
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-([\w.-]+))?$/.exec(value);
2131
+ if (match === null)
2132
+ return;
2133
+ const [, major, minor, patch, pre] = match;
2134
+ return { major: Number(major), minor: Number(minor), patch: Number(patch), pre };
2135
+ }
2136
+ function isBelowFloor(version, floor) {
2137
+ if (version.major !== floor.major)
2138
+ return version.major < floor.major;
2139
+ if (version.minor !== floor.minor)
2140
+ return version.minor < floor.minor;
2141
+ if (version.patch !== floor.patch)
2142
+ return version.patch < floor.patch;
2143
+ if (version.pre === floor.pre)
2144
+ return false;
2145
+ if (version.pre === undefined)
2146
+ return false;
2147
+ return true;
2148
+ }
2149
+ function rowForServer(serverVersion) {
2150
+ for (const row of COMPAT_TABLE) {
2151
+ const min = parseVersion(row.nivaMin);
2152
+ if (min === undefined)
2153
+ continue;
2154
+ if (isBelowFloor(serverVersion, min))
2155
+ continue;
2156
+ if (row.nivaMax !== null) {
2157
+ const max = parseVersion(row.nivaMax);
2158
+ if (max === undefined || isBelowFloor(max, serverVersion))
2159
+ continue;
2160
+ }
2161
+ return { distTag: row.distTag };
2162
+ }
2163
+ return;
2164
+ }
2165
+ function incompatibleError(baseUrl, serverVersion, serverProtocol) {
2166
+ const range = SUPPORTED_NIVA.max === null ? `>= ${SUPPORTED_NIVA.min}` : `>= ${SUPPORTED_NIVA.min} <${SUPPORTED_NIVA.max}`;
2167
+ const lines = [
2168
+ `${PUBLISHED_PACKAGE}@${SDK_VERSION} requires NIVA ${range} (protocol ${PROTOCOL_VERSION}).`,
2169
+ `The server ${baseUrl} reports NIVA ${serverVersion} (protocol ${String(serverProtocol)}).`
2170
+ ];
2171
+ let installCommand;
2172
+ const parsed = parseVersion(serverVersion);
2173
+ const row = parsed === undefined ? undefined : rowForServer(parsed);
2174
+ if (row !== undefined) {
2175
+ installCommand = `npm i ${PUBLISHED_PACKAGE}@${row.distTag}`;
2176
+ lines.push(`Install the matching version: ${installCommand}`);
2177
+ }
2178
+ return new NivaIncompatibleServerError(lines.join(`
2179
+ `), {
2180
+ serverVersion,
2181
+ supported: range,
2182
+ installCommand
2183
+ });
2184
+ }
2185
+ async function resolveHandshakeHeaders(input) {
2186
+ const base = typeof input.headers === "function" ? await input.headers() : input.headers;
2187
+ const headers = new Headers(base);
2188
+ if (!headers.has("accept"))
2189
+ headers.set("accept", "application/json");
2190
+ return headers;
2191
+ }
2192
+ async function readJson(response) {
2193
+ try {
2194
+ const parsed = await response.json();
2195
+ return parsed;
2196
+ } catch {
2197
+ return;
2198
+ }
2199
+ }
2200
+ async function fetchVersion(input) {
2201
+ const timeout = input.timeout ?? 30000;
2202
+ let response;
2203
+ try {
2204
+ response = await fetchWithTimeout(input.fetchImpl, `${input.baseUrl}/api/version`, { headers: { accept: "application/json" } }, timeout);
2205
+ } catch (error) {
2206
+ if (error instanceof NivaConnectionError)
2207
+ throw error;
2208
+ throw new NivaConnectionError("version check failed", {
2209
+ reason: "network",
2210
+ cause: error instanceof Error ? error : undefined
2211
+ });
2212
+ }
2213
+ const body = await readJson(response);
2214
+ if (!isRecord3(body)) {
2215
+ throw new NivaConnectionError("unexpected version response: not JSON", { reason: "network" });
2216
+ }
2217
+ const record = body;
2218
+ const nivaVersion = record["niva_version"];
2219
+ if (typeof nivaVersion !== "string" || parseVersion(nivaVersion) === undefined) {
2220
+ throw new NivaConnectionError("unexpected version response: bad niva_version", { reason: "network" });
2221
+ }
2222
+ return { nivaVersion, protocol: record["protocol_version"] };
2223
+ }
2224
+ var EMPTY_SNAPSHOT = { operations: undefined, modules: {}, requiredModules: {} };
2225
+ async function fetchCapabilities(input) {
2226
+ const timeout = input.timeout ?? 30000;
2227
+ const response = await fetchWithTimeout(input.fetchImpl, `${input.baseUrl}/api/v1/capabilities`, { headers: await resolveHandshakeHeaders(input) }, timeout);
2228
+ if (response.status === 404 || response.status === 403)
2229
+ return { ...EMPTY_SNAPSHOT };
2230
+ if (response.status < 200 || response.status >= 300)
2231
+ throw await parseApiError(response, "capabilities.get");
2232
+ const raw = await readJson(response);
2233
+ if (!isRecord3(raw))
2234
+ return { ...EMPTY_SNAPSHOT };
2235
+ return parseSnapshot(raw);
2236
+ }
2237
+ function parseSnapshot(body) {
2238
+ const modules = {};
2239
+ const modulesValue = body["modules"];
2240
+ if (isRecord3(modulesValue)) {
2241
+ for (const [key, value] of Object.entries(modulesValue)) {
2242
+ if (typeof value === "boolean")
2243
+ modules[key] = value;
2244
+ }
2245
+ }
2246
+ const requiredModules = {};
2247
+ const requiredValue = body["required_modules"];
2248
+ if (isRecord3(requiredValue)) {
2249
+ for (const [key, value] of Object.entries(requiredValue)) {
2250
+ if (Array.isArray(value)) {
2251
+ requiredModules[key] = value.filter((entry) => typeof entry === "string");
2252
+ }
2253
+ }
2254
+ }
2255
+ const operations = body["operations"];
2256
+ return {
2257
+ operations: Array.isArray(operations) ? operations.filter((op) => typeof op === "string") : [],
2258
+ modules,
2259
+ requiredModules
2260
+ };
2261
+ }
2262
+ function createHandshake(input) {
2263
+ let memo;
2264
+ return {
2265
+ async ensure() {
2266
+ memo ??= run().catch((error) => {
2267
+ if (error instanceof NivaConnectionError)
2268
+ memo = undefined;
2269
+ throw error;
2270
+ });
2271
+ return memo;
2272
+ }
2273
+ };
2274
+ async function run() {
2275
+ const { nivaVersion, protocol } = await fetchVersion(input);
2276
+ const floor = parseVersion(SUPPORTED_NIVA.min);
2277
+ const parsed = parseVersion(nivaVersion);
2278
+ if (floor === undefined || parsed === undefined || isBelowFloor(parsed, floor) || protocol !== PROTOCOL_VERSION) {
2279
+ throw incompatibleError(input.baseUrl, nivaVersion, protocol);
2280
+ }
2281
+ return fetchCapabilities(input);
2282
+ }
2283
+ }
2284
+ function assertOperationAvailable(snapshot, opId) {
2285
+ if (snapshot.operations === undefined)
2286
+ return;
2287
+ if (!snapshot.operations.includes(opId))
2288
+ throw new NivaUnavailableError(opId, { reason: "operation" });
2289
+ const required = snapshot.requiredModules[opId];
2290
+ if (required === undefined)
2291
+ return;
2292
+ const disabled = required.find((module) => snapshot.modules[module] !== true);
2293
+ if (disabled !== undefined)
2294
+ throw new NivaUnavailableError(opId, { reason: "module", module: disabled });
2295
+ }
2296
+
2297
+ // src/client.ts
2298
+ var DEFAULT_TIMEOUT_MS = 30000;
2299
+ function normalizeBaseUrl(baseUrl) {
2300
+ let url;
2301
+ try {
2302
+ url = new URL(baseUrl);
2303
+ } catch {
2304
+ throw new NivaConfigurationError(`baseUrl is not a URL: ${baseUrl}`);
2305
+ }
2306
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
2307
+ throw new NivaConfigurationError(`baseUrl must be http(s): ${baseUrl}`);
2308
+ }
2309
+ return url.toString().replace(/\/$/, "");
2310
+ }
2311
+ async function resolveHeaders(headers) {
2312
+ if (headers === undefined)
2313
+ return;
2314
+ return typeof headers === "function" ? headers() : headers;
2315
+ }
2316
+ function lookupOperation(opId) {
2317
+ for (const [id, entry] of Object.entries(OPERATIONS)) {
2318
+ if (id === opId)
2319
+ return entry;
2320
+ }
2321
+ throw new NivaUnavailableError(opId, { reason: "operation" });
2322
+ }
2323
+ async function resolveApiKey(apiKey) {
2324
+ const key = typeof apiKey === "function" ? await apiKey() : apiKey;
2325
+ if (key.length === 0)
2326
+ throw new NivaConfigurationError("apiKey provider resolved an empty key");
2327
+ return key;
2328
+ }
2329
+ function buildUrl(baseUrl, entry, input) {
2330
+ const split = splitOperationInput(entry, input);
2331
+ let url = `${baseUrl}/api/v1${entry.path}`;
2332
+ for (const [name, encoded] of Object.entries(split.path)) {
2333
+ url = url.replace(`{${name}}`, encoded);
2334
+ }
2335
+ const query = encodeQueryParams(split.query);
2336
+ if (query.length > 0)
2337
+ url += `?${query}`;
2338
+ return url;
2339
+ }
2340
+ async function buildHeaders(deps, apiKey, callOptions, entry) {
2341
+ const headers = mergeRequestHeaders(await resolveHeaders(deps.clientHeaders), callOptions.headers);
2342
+ headers.set("x-api-key", apiKey);
2343
+ headers.set("x-niva-sdk-version", SDK_VERSION);
2344
+ if (!headers.has("accept"))
2345
+ headers.set("accept", "application/json");
2346
+ if (callOptions.range !== undefined && entry.responseKind === "binary")
2347
+ headers.set("range", callOptions.range);
2348
+ return headers;
2349
+ }
2350
+ function buildBody(entry, input) {
2351
+ const split = splitOperationInput(entry, input);
2352
+ if (entry.bodyKind === "none" || Object.keys(split.body).length === 0) {
2353
+ return { contentType: undefined, body: undefined };
2354
+ }
2355
+ const encoded = encodeBody(entry.bodyKind, split.body);
2356
+ return { contentType: encoded.contentType, body: encoded.body ?? undefined };
2357
+ }
2358
+ async function performRequest(deps, opId, entry, input, callOptions, apiKey) {
2359
+ const url = buildUrl(deps.baseUrl, entry, input);
2360
+ const headers = await buildHeaders(deps, apiKey, callOptions, entry);
2361
+ const { contentType, body } = buildBody(entry, input);
2362
+ if (contentType !== undefined)
2363
+ headers.set("content-type", contentType);
2364
+ const init = { method: entry.method, headers };
2365
+ if (body !== undefined)
2366
+ init.body = body;
2367
+ if (callOptions.signal !== undefined)
2368
+ init.signal = callOptions.signal;
2369
+ const timeout = callOptions.timeout ?? deps.defaultTimeout;
2370
+ const response = await fetchWithTimeout(deps.fetchImpl, url, init, timeout);
2371
+ if (response.status < 200 || response.status >= 300)
2372
+ throw await parseApiError(response, opId);
2373
+ if (entry.responseKind === "binary" || entry.responseKind === "sse")
2374
+ return response;
2375
+ if (entry.responseKind === "empty")
2376
+ return;
2377
+ return readJsonResponse(response);
2378
+ }
2379
+ function createNivaClient(options) {
2380
+ const baseUrl = normalizeBaseUrl(options.baseUrl);
2381
+ if (typeof options.apiKey === "string" && options.apiKey.length === 0) {
2382
+ throw new NivaConfigurationError("apiKey must not be empty");
2383
+ }
2384
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2385
+ if (typeof fetchImpl !== "function")
2386
+ throw new NivaConfigurationError("no fetch implementation available");
2387
+ const defaultTimeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
2388
+ const deps = {
2389
+ fetchImpl,
2390
+ baseUrl,
2391
+ defaultTimeout,
2392
+ handshake: createHandshake({
2393
+ fetchImpl,
2394
+ baseUrl,
2395
+ headers: async () => {
2396
+ const apiKey = typeof options.apiKey === "function" ? await options.apiKey() : options.apiKey;
2397
+ const headers = mergeRequestHeaders(await resolveHeaders(options.headers));
2398
+ if (apiKey.length > 0)
2399
+ headers.set("x-api-key", apiKey);
2400
+ headers.set("x-niva-sdk-version", SDK_VERSION);
2401
+ return headers;
2402
+ },
2403
+ timeout: defaultTimeout
2404
+ }),
2405
+ apiKey: options.apiKey,
2406
+ clientHeaders: options.headers
2407
+ };
2408
+ const call = async (opId, input, callOptions) => {
2409
+ const snapshot = await deps.handshake.ensure();
2410
+ assertOperationAvailable(snapshot, opId);
2411
+ const entry = lookupOperation(opId);
2412
+ const apiKey = await resolveApiKey(deps.apiKey);
2413
+ return performRequest(deps, opId, entry, input, callOptions ?? {}, apiKey);
2414
+ };
2415
+ return buildNivaClient(call);
2416
+ }
2417
+ // src/generated/webhooks.ts
2418
+ var NIVA_WEBHOOK_EVENT_TYPES = [
2419
+ "alert.fired",
2420
+ "alert.resolved",
2421
+ "call.amd_completed",
2422
+ "call.analysis_completed",
2423
+ "call.answered",
2424
+ "call.hangup",
2425
+ "call.intent_matched",
2426
+ "call.node_entered",
2427
+ "call.node_error",
2428
+ "call.node_warning",
2429
+ "call.recording_available",
2430
+ "call.rejected",
2431
+ "call.started",
2432
+ "call.transcribed",
2433
+ "call.transferred",
2434
+ "dialer.attempt.finished",
2435
+ "message.sent",
2436
+ "plan.published",
2437
+ "service.down",
2438
+ "service.up"
2439
+ ];
2440
+ // src/webhook/verify.ts
2441
+ var SIGNATURE_RE = /^sha256=([0-9a-f]{64})$/;
2442
+ var TIMESTAMP_RE = /^(0|[1-9]\d{0,15})$/;
2443
+ var ISO_DATETIME_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;
2444
+ var DEFAULT_TOLERANCE_SECONDS = 300;
2445
+ function readHeader(headers, name) {
2446
+ if (headers instanceof Headers) {
2447
+ const value2 = headers.get(name);
2448
+ return value2 !== null && value2.length > 0 ? value2 : undefined;
2449
+ }
2450
+ const matches = Object.entries(headers).filter(([key]) => key.toLowerCase() === name);
2451
+ if (matches.length > 1)
2452
+ throw verification("duplicate_header", `duplicate ${name}`);
2453
+ const value = matches[0]?.[1];
2454
+ return typeof value === "string" && value.length > 0 ? value : undefined;
2455
+ }
2456
+ var verification = (code, message) => new NivaWebhookError("verification", code, message);
2457
+ var payload = (code, message) => new NivaWebhookError("payload", code, message);
2458
+ function isJsonObject(value) {
2459
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2460
+ }
2461
+ function hasControlChars(value) {
2462
+ for (let i = 0;i < value.length; i++) {
2463
+ const code = value.charCodeAt(i);
2464
+ if (code <= 31 || code === 127)
2465
+ return true;
2466
+ }
2467
+ return false;
2468
+ }
2469
+ function readDeliveryHeaders(headers) {
2470
+ const id = readHeader(headers, "x-webhook-id");
2471
+ const timestampText = readHeader(headers, "x-webhook-timestamp");
2472
+ const signature = readHeader(headers, "x-webhook-signature");
2473
+ if (id === undefined)
2474
+ throw verification("missing_header", "missing x-webhook-id");
2475
+ if (timestampText === undefined)
2476
+ throw verification("missing_header", "missing x-webhook-timestamp");
2477
+ if (signature === undefined)
2478
+ throw verification("missing_header", "missing x-webhook-signature");
2479
+ return { id, timestampText, signature };
2480
+ }
2481
+ function checkTimestamp(timestampText, toleranceSeconds, nowSeconds) {
2482
+ if (!TIMESTAMP_RE.test(timestampText))
2483
+ throw verification("bad_timestamp", "malformed x-webhook-timestamp");
2484
+ const timestamp = Number(timestampText);
2485
+ if (!Number.isSafeInteger(timestamp) || Math.abs(nowSeconds - timestamp) > toleranceSeconds) {
2486
+ throw verification("timestamp_out_of_tolerance", "webhook timestamp outside the allowed window");
2487
+ }
2488
+ }
2489
+ function freshBytes(length) {
2490
+ return new Uint8Array(new ArrayBuffer(length));
2491
+ }
2492
+ function hexToBytes(hex) {
2493
+ const out = freshBytes(hex.length / 2);
2494
+ for (let i = 0;i < out.length; i++)
2495
+ out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
2496
+ return out;
2497
+ }
2498
+ function bodyBytes(body) {
2499
+ if (typeof body === "string")
2500
+ return new TextEncoder().encode(body);
2501
+ if (body instanceof Uint8Array)
2502
+ return body;
2503
+ return new Uint8Array(body);
2504
+ }
2505
+ async function verifySignature(secret, id, timestampText, raw, signature) {
2506
+ const signatureMatch = SIGNATURE_RE.exec(signature);
2507
+ if (signatureMatch === null)
2508
+ throw verification("bad_signature", "malformed x-webhook-signature");
2509
+ const encoder = new TextEncoder;
2510
+ const secretBytes = encoder.encode(secret);
2511
+ const keyMaterial = freshBytes(secretBytes.length);
2512
+ keyMaterial.set(secretBytes);
2513
+ const key = await crypto.subtle.importKey("raw", keyMaterial, { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
2514
+ const prefix = encoder.encode(`${id}.${timestampText}.`);
2515
+ const signed = freshBytes(prefix.length + raw.length);
2516
+ signed.set(prefix, 0);
2517
+ signed.set(raw, prefix.length);
2518
+ let valid = false;
2519
+ try {
2520
+ valid = await crypto.subtle.verify("HMAC", key, hexToBytes(signatureMatch[1]), signed);
2521
+ } catch {
2522
+ valid = false;
2523
+ }
2524
+ if (!valid)
2525
+ throw verification("bad_signature", "webhook signature mismatch");
2526
+ }
2527
+ function parseEnvelope(raw, headerId) {
2528
+ let parsed;
2529
+ try {
2530
+ parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(raw));
2531
+ } catch {
2532
+ throw payload("invalid_json", "webhook body is not valid JSON");
2533
+ }
2534
+ if (!isJsonObject(parsed)) {
2535
+ throw payload("invalid_envelope", "webhook body is not an envelope object");
2536
+ }
2537
+ const body = parsed;
2538
+ if ("org_id" in body)
2539
+ throw payload("invalid_envelope", "webhook envelope carries org_id");
2540
+ if (typeof body["event"] !== "string")
2541
+ throw payload("invalid_envelope", "webhook envelope has no event");
2542
+ const event = NIVA_WEBHOOK_EVENT_TYPES.find((candidate) => candidate === body["event"]);
2543
+ if (event === undefined)
2544
+ throw payload("unknown_event", "unknown webhook event");
2545
+ if (typeof body["event_id"] !== "string" || body["event_id"].length === 0) {
2546
+ throw payload("invalid_envelope", "webhook envelope has no event_id");
2547
+ }
2548
+ if (typeof body["timestamp"] !== "string" || !isDispatcherTimestamp(body["timestamp"])) {
2549
+ throw payload("invalid_envelope", "webhook envelope timestamp is not an ISO 8601 date-time");
2550
+ }
2551
+ if (typeof body["data"] !== "object" || body["data"] === null || Array.isArray(body["data"])) {
2552
+ throw payload("invalid_envelope", "webhook envelope has no data object");
2553
+ }
2554
+ if (body["event_id"] !== headerId)
2555
+ throw payload("invalid_envelope", "webhook id does not match the envelope");
2556
+ return { event, event_id: body["event_id"], timestamp: body["timestamp"], data: body["data"] };
2557
+ }
2558
+ async function verifyNivaWebhook(options) {
2559
+ const { secret, toleranceSeconds = DEFAULT_TOLERANCE_SECONDS } = options;
2560
+ if (secret.length === 0)
2561
+ throw verification("bad_signature", "a non-empty webhook secret is required");
2562
+ const { id, timestampText, signature } = readDeliveryHeaders(options.headers);
2563
+ if (id.length > 256 || hasControlChars(id))
2564
+ throw verification("bad_signature", "malformed x-webhook-id");
2565
+ checkTimestamp(timestampText, toleranceSeconds, options.now ?? Math.floor(Date.now() / 1000));
2566
+ const raw = bodyBytes(options.body);
2567
+ await verifySignature(secret, id, timestampText, raw, signature);
2568
+ return envelopeToEvent(parseEnvelope(raw, id));
2569
+ }
2570
+ function isDispatcherTimestamp(value) {
2571
+ return ISO_DATETIME_RE.test(value) && Number.isFinite(Date.parse(value));
2572
+ }
2573
+ function envelopeToEvent(envelope) {
2574
+ return envelope;
2575
+ }
2576
+ // src/webhook/handler.ts
2577
+ var DEFAULT_MAX_BODY_BYTES = 1024 * 1024;
2578
+ var DRAIN_CAP_BYTES = 1024 * 1024;
2579
+ var DRAIN_TIMEOUT_MS = 1000;
2580
+ function concatChunks(chunks, total) {
2581
+ const out = new Uint8Array(total);
2582
+ let offset = 0;
2583
+ for (const chunk of chunks) {
2584
+ out.set(chunk, offset);
2585
+ offset += chunk.byteLength;
2586
+ }
2587
+ return out;
2588
+ }
2589
+ async function drainOverLimit(reader) {
2590
+ const deadline = Date.now() + DRAIN_TIMEOUT_MS;
2591
+ let discarded = 0;
2592
+ for (;; ) {
2593
+ const remaining = deadline - Date.now();
2594
+ if (remaining <= 0)
2595
+ return;
2596
+ let timer;
2597
+ try {
2598
+ const next = await Promise.race([
2599
+ reader.read(),
2600
+ new Promise((resolve) => {
2601
+ timer = setTimeout(() => resolve(undefined), remaining);
2602
+ })
2603
+ ]);
2604
+ if (next === undefined || next.done)
2605
+ return;
2606
+ discarded += next.value.byteLength;
2607
+ if (discarded > DRAIN_CAP_BYTES)
2608
+ return;
2609
+ } finally {
2610
+ if (timer !== undefined)
2611
+ clearTimeout(timer);
2612
+ }
2613
+ }
2614
+ }
2615
+
2616
+ class BodyTooLargeError extends Error {
2617
+ constructor() {
2618
+ super("webhook body exceeds maxBodyBytes");
2619
+ this.name = "BodyTooLargeError";
2620
+ }
2621
+ }
2622
+ async function readBodyWithLimit(request, maxBodyBytes) {
2623
+ if (request.body === null)
2624
+ return new Uint8Array(0);
2625
+ const reader = request.body.getReader();
2626
+ const chunks = [];
2627
+ let total = 0;
2628
+ try {
2629
+ for (;; ) {
2630
+ const { done, value } = await reader.read();
2631
+ if (done)
2632
+ return concatChunks(chunks, total);
2633
+ total += value.byteLength;
2634
+ if (total <= maxBodyBytes) {
2635
+ chunks.push(value);
2636
+ continue;
2637
+ }
2638
+ chunks.length = 0;
2639
+ await drainOverLimit(reader);
2640
+ try {
2641
+ await reader.cancel();
2642
+ } catch {}
2643
+ throw new BodyTooLargeError;
2644
+ }
2645
+ } finally {
2646
+ reader.releaseLock();
2647
+ }
2648
+ }
2649
+ var empty = (status, headers) => new Response(null, headers === undefined ? { status } : { status, headers });
2650
+ function createNivaWebhookHandler(options) {
2651
+ const path = options.path ?? "/";
2652
+ const maxBodyBytes = options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
2653
+ const handlers = new Map;
2654
+ return {
2655
+ on(event, handler) {
2656
+ if (handlers.has(event))
2657
+ throw new Error(`a handler is already registered for event ${JSON.stringify(event)}`);
2658
+ handlers.set(event, async (incoming, context) => {
2659
+ if (incoming.event !== event)
2660
+ throw new Error("webhook dispatcher delivered the wrong event");
2661
+ await handler(incoming, context);
2662
+ });
2663
+ },
2664
+ off(event) {
2665
+ handlers.delete(event);
2666
+ },
2667
+ async fetch(request) {
2668
+ let pathname;
2669
+ try {
2670
+ pathname = new URL(request.url).pathname;
2671
+ } catch {
2672
+ return empty(400);
2673
+ }
2674
+ if (pathname !== path)
2675
+ return empty(404);
2676
+ if (request.method !== "POST")
2677
+ return empty(405);
2678
+ let raw;
2679
+ try {
2680
+ raw = await readBodyWithLimit(request, maxBodyBytes);
2681
+ } catch (error) {
2682
+ if (error instanceof BodyTooLargeError)
2683
+ return empty(413, { Connection: "close" });
2684
+ return empty(500);
2685
+ }
2686
+ let event;
2687
+ try {
2688
+ event = await verifyNivaWebhook({
2689
+ secret: options.secret,
2690
+ headers: request.headers,
2691
+ body: raw,
2692
+ ...options.toleranceSeconds === undefined ? {} : { toleranceSeconds: options.toleranceSeconds }
2693
+ });
2694
+ } catch (error) {
2695
+ if (error instanceof NivaWebhookError)
2696
+ return empty(error.kind === "verification" ? 401 : 400);
2697
+ return empty(500);
2698
+ }
2699
+ const handler = handlers.get(event.event);
2700
+ if (handler === undefined)
2701
+ return empty(422);
2702
+ try {
2703
+ await handler(event, { signal: request.signal });
2704
+ } catch {
2705
+ return empty(500);
2706
+ }
2707
+ return empty(204);
2708
+ }
2709
+ };
2710
+ }
2711
+ // src/webhook/server.ts
2712
+ var SHUTDOWN_GRACE_MS = 5000;
2713
+ var SHUTDOWN_SETTLE_MS = 200;
2714
+ async function delayMs(ms) {
2715
+ await new Promise((resolve) => setTimeout(resolve, ms));
2716
+ }
2717
+ function createShutdownTracker() {
2718
+ let shuttingDown = false;
2719
+ const active = new Set;
2720
+ return {
2721
+ get shuttingDown() {
2722
+ return shuttingDown;
2723
+ },
2724
+ get inFlight() {
2725
+ return active.size;
2726
+ },
2727
+ beginShutdown() {
2728
+ shuttingDown = true;
2729
+ },
2730
+ admit() {
2731
+ if (shuttingDown)
2732
+ return;
2733
+ const controller = new AbortController;
2734
+ active.add(controller);
2735
+ return controller;
2736
+ },
2737
+ release(controller) {
2738
+ active.delete(controller);
2739
+ },
2740
+ abortInFlight() {
2741
+ for (const controller of active)
2742
+ controller.abort();
2743
+ active.clear();
2744
+ }
2745
+ };
2746
+ }
2747
+ function withShutdownSignal(request, signal) {
2748
+ return new Request(request, { signal: AbortSignal.any([request.signal, signal]) });
2749
+ }
2750
+ function defineNivaWebhookServer(options, adapter) {
2751
+ const handler = createNivaWebhookHandler(options);
2752
+ return {
2753
+ on: (event, fn) => handler.on(event, fn),
2754
+ off: (event) => handler.off(event),
2755
+ fetch: async (request) => handler.fetch(request),
2756
+ async serve(serveOptions = {}) {
2757
+ const shutdownGraceMs = serveOptions.shutdownGraceMs !== undefined && Number.isFinite(serveOptions.shutdownGraceMs) && serveOptions.shutdownGraceMs >= 0 ? serveOptions.shutdownGraceMs : SHUTDOWN_GRACE_MS;
2758
+ return adapter(async (request) => handler.fetch(request), {
2759
+ port: serveOptions.port ?? 0,
2760
+ hostname: serveOptions.hostname ?? "127.0.0.1",
2761
+ shutdownGraceMs
2762
+ });
2763
+ }
2764
+ };
2765
+ }
2766
+
2767
+ // src/webhook/serve-deno.ts
2768
+ async function denoAdapter(fetch, opts) {
2769
+ const tracker = createShutdownTracker();
2770
+ const server = Deno.serve({ port: opts.port, hostname: opts.hostname, onListen: () => {} }, async (request) => {
2771
+ const controller = tracker.admit();
2772
+ if (controller === undefined)
2773
+ return new Response(null, { status: 503 });
2774
+ try {
2775
+ return await fetch(withShutdownSignal(request, controller.signal));
2776
+ } finally {
2777
+ tracker.release(controller);
2778
+ }
2779
+ });
2780
+ let shutdownPromise;
2781
+ return {
2782
+ url: `http://${server.addr.hostname}:${server.addr.port}`,
2783
+ port: server.addr.port,
2784
+ close() {
2785
+ return shutdownPromise ??= (async () => {
2786
+ tracker.beginShutdown();
2787
+ const exiting = server.shutdown();
2788
+ exiting.then(() => {
2789
+ return;
2790
+ }, () => {
2791
+ return;
2792
+ });
2793
+ const finished = server.finished;
2794
+ finished.then(() => {
2795
+ return;
2796
+ }, () => {
2797
+ return;
2798
+ });
2799
+ const deadline = Date.now() + opts.shutdownGraceMs;
2800
+ while (tracker.inFlight > 0 && Date.now() < deadline)
2801
+ await delayMs(10);
2802
+ tracker.abortInFlight();
2803
+ await Promise.race([Promise.all([exiting, finished]), delayMs(SHUTDOWN_SETTLE_MS)]);
2804
+ })();
2805
+ }
2806
+ };
2807
+ }
2808
+ function createNivaWebhookServer(options) {
2809
+ return defineNivaWebhookServer(options, denoAdapter);
2810
+ }
2811
+ var WEBHOOK_RUNTIME = "deno";
2812
+ export {
2813
+ verifyNivaWebhook,
2814
+ isNivaApiError,
2815
+ createNivaWebhookServer,
2816
+ createNivaWebhookHandler,
2817
+ createNivaClient,
2818
+ buildNivaClient,
2819
+ WEBHOOK_RUNTIME,
2820
+ OPERATIONS,
2821
+ NivaWebhookError,
2822
+ NivaUnavailableError,
2823
+ NivaIncompatibleServerError,
2824
+ NivaError,
2825
+ NivaConnectionError,
2826
+ NivaConfigurationError,
2827
+ NivaApiError,
2828
+ NIVA_WEBHOOK_EVENT_TYPES,
2829
+ DEFAULT_TOLERANCE_SECONDS,
2830
+ DEFAULT_MAX_BODY_BYTES
2831
+ };