@absolutejs/voice-deepgram 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2422 @@
1
+ // @bun
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ function __accessProp(key) {
8
+ return this[key];
9
+ }
10
+ var __toESMCache_node;
11
+ var __toESMCache_esm;
12
+ var __toESM = (mod, isNodeMode, target) => {
13
+ var canCache = mod != null && typeof mod === "object";
14
+ if (canCache) {
15
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
16
+ var cached = cache.get(mod);
17
+ if (cached)
18
+ return cached;
19
+ }
20
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
21
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
22
+ for (let key of __getOwnPropNames(mod))
23
+ if (!__hasOwnProp.call(to, key))
24
+ __defProp(to, key, {
25
+ get: __accessProp.bind(mod, key),
26
+ enumerable: true
27
+ });
28
+ if (canCache)
29
+ cache.set(mod, to);
30
+ return to;
31
+ };
32
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
33
+ var __require = import.meta.require;
34
+
35
+ // node_modules/cross-fetch/dist/node-ponyfill.js
36
+ var require_node_ponyfill = __commonJS((exports, module) => {
37
+ var nodeFetch = __require("node-fetch");
38
+ var realFetch = nodeFetch.default || nodeFetch;
39
+ var fetch2 = function(url, options) {
40
+ if (/^\/\//.test(url)) {
41
+ url = "https:" + url;
42
+ }
43
+ return realFetch.call(this, url, options);
44
+ };
45
+ fetch2.ponyfill = true;
46
+ module.exports = exports = fetch2;
47
+ exports.fetch = fetch2;
48
+ exports.Headers = nodeFetch.Headers;
49
+ exports.Request = nodeFetch.Request;
50
+ exports.Response = nodeFetch.Response;
51
+ exports.default = fetch2;
52
+ });
53
+
54
+ // node_modules/deepmerge/dist/cjs.js
55
+ var require_cjs = __commonJS((exports, module) => {
56
+ var isMergeableObject = function isMergeableObject2(value) {
57
+ return isNonNullObject(value) && !isSpecial(value);
58
+ };
59
+ function isNonNullObject(value) {
60
+ return !!value && typeof value === "object";
61
+ }
62
+ function isSpecial(value) {
63
+ var stringValue = Object.prototype.toString.call(value);
64
+ return stringValue === "[object RegExp]" || stringValue === "[object Date]" || isReactElement(value);
65
+ }
66
+ var canUseSymbol = typeof Symbol === "function" && Symbol.for;
67
+ var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for("react.element") : 60103;
68
+ function isReactElement(value) {
69
+ return value.$$typeof === REACT_ELEMENT_TYPE;
70
+ }
71
+ function emptyTarget(val) {
72
+ return Array.isArray(val) ? [] : {};
73
+ }
74
+ function cloneUnlessOtherwiseSpecified(value, options) {
75
+ return options.clone !== false && options.isMergeableObject(value) ? deepmerge(emptyTarget(value), value, options) : value;
76
+ }
77
+ function defaultArrayMerge(target, source, options) {
78
+ return target.concat(source).map(function(element) {
79
+ return cloneUnlessOtherwiseSpecified(element, options);
80
+ });
81
+ }
82
+ function getMergeFunction(key, options) {
83
+ if (!options.customMerge) {
84
+ return deepmerge;
85
+ }
86
+ var customMerge = options.customMerge(key);
87
+ return typeof customMerge === "function" ? customMerge : deepmerge;
88
+ }
89
+ function getEnumerableOwnPropertySymbols(target) {
90
+ return Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(target).filter(function(symbol) {
91
+ return Object.propertyIsEnumerable.call(target, symbol);
92
+ }) : [];
93
+ }
94
+ function getKeys(target) {
95
+ return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target));
96
+ }
97
+ function propertyIsOnObject(object, property) {
98
+ try {
99
+ return property in object;
100
+ } catch (_) {
101
+ return false;
102
+ }
103
+ }
104
+ function propertyIsUnsafe(target, key) {
105
+ return propertyIsOnObject(target, key) && !(Object.hasOwnProperty.call(target, key) && Object.propertyIsEnumerable.call(target, key));
106
+ }
107
+ function mergeObject(target, source, options) {
108
+ var destination = {};
109
+ if (options.isMergeableObject(target)) {
110
+ getKeys(target).forEach(function(key) {
111
+ destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
112
+ });
113
+ }
114
+ getKeys(source).forEach(function(key) {
115
+ if (propertyIsUnsafe(target, key)) {
116
+ return;
117
+ }
118
+ if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) {
119
+ destination[key] = getMergeFunction(key, options)(target[key], source[key], options);
120
+ } else {
121
+ destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
122
+ }
123
+ });
124
+ return destination;
125
+ }
126
+ function deepmerge(target, source, options) {
127
+ options = options || {};
128
+ options.arrayMerge = options.arrayMerge || defaultArrayMerge;
129
+ options.isMergeableObject = options.isMergeableObject || isMergeableObject;
130
+ options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;
131
+ var sourceIsArray = Array.isArray(source);
132
+ var targetIsArray = Array.isArray(target);
133
+ var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
134
+ if (!sourceAndTargetTypesMatch) {
135
+ return cloneUnlessOtherwiseSpecified(source, options);
136
+ } else if (sourceIsArray) {
137
+ return options.arrayMerge(target, source, options);
138
+ } else {
139
+ return mergeObject(target, source, options);
140
+ }
141
+ }
142
+ deepmerge.all = function deepmergeAll(array, options) {
143
+ if (!Array.isArray(array)) {
144
+ throw new Error("first argument should be an array");
145
+ }
146
+ return array.reduce(function(prev, next) {
147
+ return deepmerge(prev, next, options);
148
+ }, {});
149
+ };
150
+ var deepmerge_1 = deepmerge;
151
+ module.exports = deepmerge_1;
152
+ });
153
+
154
+ // node_modules/@deepgram/sdk/dist/module/lib/errors.js
155
+ class DeepgramError extends Error {
156
+ constructor(message) {
157
+ super(message);
158
+ this.__dgError = true;
159
+ this.name = "DeepgramError";
160
+ }
161
+ }
162
+ function isDeepgramError(error) {
163
+ return typeof error === "object" && error !== null && "__dgError" in error;
164
+ }
165
+
166
+ class DeepgramApiError extends DeepgramError {
167
+ constructor(message, status) {
168
+ super(message);
169
+ this.name = "DeepgramApiError";
170
+ this.status = status;
171
+ }
172
+ toJSON() {
173
+ return {
174
+ name: this.name,
175
+ message: this.message,
176
+ status: this.status
177
+ };
178
+ }
179
+ }
180
+
181
+ class DeepgramUnknownError extends DeepgramError {
182
+ constructor(message, originalError) {
183
+ super(message);
184
+ this.name = "DeepgramUnknownError";
185
+ this.originalError = originalError;
186
+ }
187
+ }
188
+
189
+ class DeepgramVersionError extends DeepgramError {
190
+ constructor() {
191
+ super(`You are attempting to use an old format for a newer SDK version. Read more here: https://dpgr.am/js-v3`);
192
+ this.name = "DeepgramVersionError";
193
+ }
194
+ }
195
+
196
+ class DeepgramWebSocketError extends DeepgramError {
197
+ constructor(message, options = {}) {
198
+ super(message);
199
+ this.name = "DeepgramWebSocketError";
200
+ this.originalEvent = options.originalEvent;
201
+ this.statusCode = options.statusCode;
202
+ this.requestId = options.requestId;
203
+ this.responseHeaders = options.responseHeaders;
204
+ this.url = options.url;
205
+ this.readyState = options.readyState;
206
+ }
207
+ toJSON() {
208
+ return {
209
+ name: this.name,
210
+ message: this.message,
211
+ statusCode: this.statusCode,
212
+ requestId: this.requestId,
213
+ responseHeaders: this.responseHeaders,
214
+ url: this.url,
215
+ readyState: this.readyState,
216
+ originalEvent: this.originalEvent ? {
217
+ type: this.originalEvent.type,
218
+ timeStamp: this.originalEvent.timeStamp
219
+ } : undefined
220
+ };
221
+ }
222
+ }
223
+
224
+ // node_modules/@deepgram/sdk/dist/module/packages/AbstractClient.js
225
+ import { EventEmitter } from "events";
226
+
227
+ // node_modules/@deepgram/sdk/dist/module/lib/helpers.js
228
+ var import_cross_fetch = __toESM(require_node_ponyfill(), 1);
229
+ var import_deepmerge = __toESM(require_cjs(), 1);
230
+
231
+ // node_modules/@deepgram/sdk/dist/module/lib/runtime.js
232
+ var NODE_VERSION = typeof process !== "undefined" && process.versions && process.versions.node ? process.versions.node : "unknown";
233
+ var BUN_VERSION = typeof process !== "undefined" && process.versions && process.versions.bun ? process.versions.bun : "unknown";
234
+ var BROWSER_AGENT = typeof window !== "undefined" && window.navigator && window.navigator.userAgent ? window.navigator.userAgent : "unknown";
235
+ var isBrowser = () => BROWSER_AGENT !== "unknown";
236
+ var isNode = () => NODE_VERSION !== "unknown";
237
+ var isBun = () => BUN_VERSION !== "unknown";
238
+
239
+ // node_modules/@deepgram/sdk/dist/module/lib/helpers.js
240
+ function applyDefaults(options = {}, subordinate = {}) {
241
+ return import_deepmerge.default(subordinate, options);
242
+ }
243
+ function appendSearchParams(searchParams, options) {
244
+ Object.keys(options).forEach((i) => {
245
+ if (Array.isArray(options[i])) {
246
+ const arrayParams = options[i];
247
+ arrayParams.forEach((param) => {
248
+ searchParams.append(i, String(param));
249
+ });
250
+ } else {
251
+ searchParams.append(i, String(options[i]));
252
+ }
253
+ });
254
+ }
255
+ var resolveHeadersConstructor = () => {
256
+ if (typeof Headers === "undefined") {
257
+ return import_cross_fetch.Headers;
258
+ }
259
+ return Headers;
260
+ };
261
+ var isUrlSource = (providedSource) => {
262
+ if (providedSource && providedSource.url)
263
+ return true;
264
+ return false;
265
+ };
266
+ var isTextSource = (providedSource) => {
267
+ if (providedSource && providedSource.text)
268
+ return true;
269
+ return false;
270
+ };
271
+ var isFileSource = (providedSource) => {
272
+ if (isReadStreamSource(providedSource) || isBufferSource(providedSource))
273
+ return true;
274
+ return false;
275
+ };
276
+ var isBufferSource = (providedSource) => {
277
+ return providedSource != null && Buffer.isBuffer(providedSource);
278
+ };
279
+ var isReadStreamSource = (providedSource) => {
280
+ if (providedSource == null)
281
+ return false;
282
+ if (isBrowser())
283
+ return false;
284
+ return typeof providedSource === "object" && typeof providedSource.pipe === "function" && typeof providedSource.read === "function" && typeof providedSource._readableState === "object";
285
+ };
286
+ var convertProtocolToWs = (url) => {
287
+ const convert = (string) => string.toLowerCase().replace(/^http/, "ws");
288
+ return convert(url);
289
+ };
290
+ var convertLegacyOptions = (optionsArg) => {
291
+ var _a, _b, _c, _d, _e, _f;
292
+ const newOptions = {};
293
+ if (optionsArg._experimentalCustomFetch) {
294
+ newOptions.global = {
295
+ fetch: {
296
+ client: optionsArg._experimentalCustomFetch
297
+ }
298
+ };
299
+ }
300
+ optionsArg = import_deepmerge.default(optionsArg, newOptions);
301
+ if ((_a = optionsArg.restProxy) === null || _a === undefined ? undefined : _a.url) {
302
+ newOptions.global = {
303
+ fetch: {
304
+ options: {
305
+ proxy: {
306
+ url: (_b = optionsArg.restProxy) === null || _b === undefined ? undefined : _b.url
307
+ }
308
+ }
309
+ }
310
+ };
311
+ }
312
+ optionsArg = import_deepmerge.default(optionsArg, newOptions);
313
+ if ((_c = optionsArg.global) === null || _c === undefined ? undefined : _c.url) {
314
+ newOptions.global = {
315
+ fetch: {
316
+ options: {
317
+ url: optionsArg.global.url
318
+ }
319
+ },
320
+ websocket: {
321
+ options: {
322
+ url: optionsArg.global.url
323
+ }
324
+ }
325
+ };
326
+ }
327
+ optionsArg = import_deepmerge.default(optionsArg, newOptions);
328
+ if ((_d = optionsArg.global) === null || _d === undefined ? undefined : _d.headers) {
329
+ newOptions.global = {
330
+ fetch: {
331
+ options: {
332
+ headers: (_e = optionsArg.global) === null || _e === undefined ? undefined : _e.headers
333
+ }
334
+ },
335
+ websocket: {
336
+ options: {
337
+ _nodeOnlyHeaders: (_f = optionsArg.global) === null || _f === undefined ? undefined : _f.headers
338
+ }
339
+ }
340
+ };
341
+ }
342
+ optionsArg = import_deepmerge.default(optionsArg, newOptions);
343
+ return optionsArg;
344
+ };
345
+
346
+ // node_modules/@deepgram/sdk/dist/module/lib/version.js
347
+ var version = "4.11.3";
348
+
349
+ // node_modules/@deepgram/sdk/dist/module/lib/constants.js
350
+ var getAgent = () => {
351
+ if (isNode()) {
352
+ return `node/${NODE_VERSION}`;
353
+ } else if (isBun()) {
354
+ return `bun/${BUN_VERSION}`;
355
+ } else if (isBrowser()) {
356
+ return `javascript ${BROWSER_AGENT}`;
357
+ } else {
358
+ return `unknown`;
359
+ }
360
+ };
361
+ var DEFAULT_HEADERS = {
362
+ "Content-Type": `application/json`,
363
+ "X-Client-Info": `@deepgram/sdk; ${isBrowser() ? "browser" : "server"}; v${version}`,
364
+ "User-Agent": `@deepgram/sdk/${version} ${getAgent()}`
365
+ };
366
+ var DEFAULT_URL = "https://api.deepgram.com";
367
+ var DEFAULT_AGENT_URL = "wss://agent.deepgram.com";
368
+ var DEFAULT_GLOBAL_OPTIONS = {
369
+ fetch: { options: { url: DEFAULT_URL, headers: DEFAULT_HEADERS } },
370
+ websocket: {
371
+ options: { url: convertProtocolToWs(DEFAULT_URL), _nodeOnlyHeaders: DEFAULT_HEADERS }
372
+ }
373
+ };
374
+ var DEFAULT_AGENT_OPTIONS = {
375
+ fetch: { options: { url: DEFAULT_URL, headers: DEFAULT_HEADERS } },
376
+ websocket: {
377
+ options: { url: DEFAULT_AGENT_URL, _nodeOnlyHeaders: DEFAULT_HEADERS }
378
+ }
379
+ };
380
+ var DEFAULT_OPTIONS = {
381
+ global: DEFAULT_GLOBAL_OPTIONS,
382
+ agent: DEFAULT_AGENT_OPTIONS
383
+ };
384
+ var SOCKET_STATES;
385
+ (function(SOCKET_STATES2) {
386
+ SOCKET_STATES2[SOCKET_STATES2["connecting"] = 0] = "connecting";
387
+ SOCKET_STATES2[SOCKET_STATES2["open"] = 1] = "open";
388
+ SOCKET_STATES2[SOCKET_STATES2["closing"] = 2] = "closing";
389
+ SOCKET_STATES2[SOCKET_STATES2["closed"] = 3] = "closed";
390
+ })(SOCKET_STATES || (SOCKET_STATES = {}));
391
+ var CONNECTION_STATE;
392
+ (function(CONNECTION_STATE2) {
393
+ CONNECTION_STATE2["Connecting"] = "connecting";
394
+ CONNECTION_STATE2["Open"] = "open";
395
+ CONNECTION_STATE2["Closing"] = "closing";
396
+ CONNECTION_STATE2["Closed"] = "closed";
397
+ })(CONNECTION_STATE || (CONNECTION_STATE = {}));
398
+
399
+ // node_modules/@deepgram/sdk/dist/module/packages/AbstractClient.js
400
+ var noop = () => {};
401
+
402
+ class AbstractClient extends EventEmitter {
403
+ constructor(options) {
404
+ super();
405
+ this.factory = undefined;
406
+ this.key = undefined;
407
+ this.accessToken = undefined;
408
+ this.namespace = "global";
409
+ this.version = "v1";
410
+ this.baseUrl = DEFAULT_URL;
411
+ this.logger = noop;
412
+ if (typeof options.accessToken === "function") {
413
+ this.factory = options.accessToken;
414
+ this.accessToken = this.factory();
415
+ } else {
416
+ this.accessToken = options.accessToken;
417
+ }
418
+ if (typeof options.key === "function") {
419
+ this.factory = options.key;
420
+ this.key = this.factory();
421
+ } else {
422
+ this.key = options.key;
423
+ }
424
+ if (!this.key && !this.accessToken) {
425
+ this.accessToken = process.env.DEEPGRAM_ACCESS_TOKEN;
426
+ if (!this.accessToken) {
427
+ this.key = process.env.DEEPGRAM_API_KEY;
428
+ }
429
+ }
430
+ if (!this.key && !this.accessToken) {
431
+ throw new DeepgramError("A deepgram API key or access token is required.");
432
+ }
433
+ options = convertLegacyOptions(options);
434
+ this.options = applyDefaults(options, DEFAULT_OPTIONS);
435
+ }
436
+ v(version2 = "v1") {
437
+ this.version = version2;
438
+ return this;
439
+ }
440
+ get namespaceOptions() {
441
+ const defaults = applyDefaults(this.options[this.namespace], this.options.global);
442
+ return Object.assign(Object.assign({}, defaults), { key: this.key });
443
+ }
444
+ getRequestUrl(endpoint, fields = { version: this.version }, transcriptionOptions) {
445
+ fields.version = this.version;
446
+ endpoint = endpoint.replace(/:(\w+)/g, function(_, key) {
447
+ return fields[key];
448
+ });
449
+ const url = new URL(endpoint, this.baseUrl);
450
+ if (transcriptionOptions) {
451
+ appendSearchParams(url.searchParams, transcriptionOptions);
452
+ }
453
+ return url;
454
+ }
455
+ log(kind, msg, data) {
456
+ this.logger(kind, msg, data);
457
+ }
458
+ }
459
+
460
+ // node_modules/@deepgram/sdk/dist/module/packages/AbstractLiveClient.js
461
+ var __awaiter = function(thisArg, _arguments, P, generator) {
462
+ function adopt(value) {
463
+ return value instanceof P ? value : new P(function(resolve) {
464
+ resolve(value);
465
+ });
466
+ }
467
+ return new (P || (P = Promise))(function(resolve, reject) {
468
+ function fulfilled(value) {
469
+ try {
470
+ step(generator.next(value));
471
+ } catch (e) {
472
+ reject(e);
473
+ }
474
+ }
475
+ function rejected(value) {
476
+ try {
477
+ step(generator["throw"](value));
478
+ } catch (e) {
479
+ reject(e);
480
+ }
481
+ }
482
+ function step(result) {
483
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
484
+ }
485
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
486
+ });
487
+ };
488
+ var NATIVE_WEBSOCKET_AVAILABLE = typeof WebSocket !== "undefined";
489
+
490
+ class AbstractLiveClient extends AbstractClient {
491
+ constructor(options) {
492
+ super(options);
493
+ this.conn = null;
494
+ this.sendBuffer = [];
495
+ this.reconnect = noop;
496
+ const { key, websocket: { options: websocketOptions, client } } = this.namespaceOptions;
497
+ if (this.proxy) {
498
+ this.baseUrl = websocketOptions.proxy.url;
499
+ } else {
500
+ this.baseUrl = websocketOptions.url;
501
+ }
502
+ if (client) {
503
+ this.transport = client;
504
+ } else {
505
+ this.transport = null;
506
+ }
507
+ if (websocketOptions._nodeOnlyHeaders) {
508
+ this.headers = websocketOptions._nodeOnlyHeaders;
509
+ } else {
510
+ this.headers = {};
511
+ }
512
+ if (!("Authorization" in this.headers)) {
513
+ if (this.accessToken) {
514
+ this.headers["Authorization"] = `Bearer ${this.accessToken}`;
515
+ } else {
516
+ this.headers["Authorization"] = `Token ${key}`;
517
+ }
518
+ }
519
+ }
520
+ connect(transcriptionOptions, endpoint) {
521
+ if (this.conn) {
522
+ return;
523
+ }
524
+ this.reconnect = (options = transcriptionOptions) => {
525
+ this.connect(options, endpoint);
526
+ };
527
+ const requestUrl = this.getRequestUrl(endpoint, {}, transcriptionOptions);
528
+ const accessToken = this.accessToken;
529
+ const apiKey = this.key;
530
+ if (!accessToken && !apiKey) {
531
+ throw new Error("No key or access token provided for WebSocket connection.");
532
+ }
533
+ if (this.transport) {
534
+ this.conn = new this.transport(requestUrl, undefined, {
535
+ headers: this.headers
536
+ });
537
+ this.setupConnection();
538
+ return;
539
+ }
540
+ if (isBun()) {
541
+ import("ws").then(({ default: WS }) => {
542
+ this.conn = new WS(requestUrl, {
543
+ headers: this.headers
544
+ });
545
+ console.log(`Using WS package`);
546
+ this.setupConnection();
547
+ });
548
+ return;
549
+ }
550
+ if (NATIVE_WEBSOCKET_AVAILABLE) {
551
+ this.conn = new WebSocket(requestUrl, accessToken ? ["bearer", accessToken] : ["token", apiKey]);
552
+ this.setupConnection();
553
+ return;
554
+ }
555
+ this.conn = new WSWebSocketDummy(requestUrl, undefined, {
556
+ close: () => {
557
+ this.conn = null;
558
+ }
559
+ });
560
+ import("ws").then(({ default: WS }) => {
561
+ this.conn = new WS(requestUrl, undefined, {
562
+ headers: this.headers
563
+ });
564
+ this.setupConnection();
565
+ });
566
+ }
567
+ disconnect(code, reason) {
568
+ if (this.conn) {
569
+ this.conn.onclose = function() {};
570
+ if (code) {
571
+ this.conn.close(code, reason !== null && reason !== undefined ? reason : "");
572
+ } else {
573
+ this.conn.close();
574
+ }
575
+ this.conn = null;
576
+ }
577
+ }
578
+ connectionState() {
579
+ switch (this.conn && this.conn.readyState) {
580
+ case SOCKET_STATES.connecting:
581
+ return CONNECTION_STATE.Connecting;
582
+ case SOCKET_STATES.open:
583
+ return CONNECTION_STATE.Open;
584
+ case SOCKET_STATES.closing:
585
+ return CONNECTION_STATE.Closing;
586
+ default:
587
+ return CONNECTION_STATE.Closed;
588
+ }
589
+ }
590
+ getReadyState() {
591
+ var _a, _b;
592
+ return (_b = (_a = this.conn) === null || _a === undefined ? undefined : _a.readyState) !== null && _b !== undefined ? _b : SOCKET_STATES.closed;
593
+ }
594
+ isConnected() {
595
+ return this.connectionState() === CONNECTION_STATE.Open;
596
+ }
597
+ send(data) {
598
+ const callback = () => __awaiter(this, undefined, undefined, function* () {
599
+ var _a;
600
+ if (data instanceof Blob) {
601
+ if (data.size === 0) {
602
+ this.log("warn", "skipping `send` for zero-byte blob", data);
603
+ return;
604
+ }
605
+ data = yield data.arrayBuffer();
606
+ }
607
+ if (typeof data !== "string") {
608
+ if (!(data === null || data === undefined ? undefined : data.byteLength)) {
609
+ this.log("warn", "skipping `send` for zero-byte payload", data);
610
+ return;
611
+ }
612
+ }
613
+ (_a = this.conn) === null || _a === undefined || _a.send(data);
614
+ });
615
+ if (this.isConnected()) {
616
+ callback();
617
+ } else {
618
+ this.sendBuffer.push(callback);
619
+ }
620
+ }
621
+ get proxy() {
622
+ var _a;
623
+ return this.key === "proxy" && !!((_a = this.namespaceOptions.websocket.options.proxy) === null || _a === undefined ? undefined : _a.url);
624
+ }
625
+ extractErrorInformation(event, conn) {
626
+ var _a;
627
+ const errorInfo = {};
628
+ if (conn) {
629
+ errorInfo.readyState = conn.readyState;
630
+ errorInfo.url = typeof conn.url === "string" ? conn.url : (_a = conn.url) === null || _a === undefined ? undefined : _a.toString();
631
+ }
632
+ if (conn && typeof conn === "object") {
633
+ const wsConn = conn;
634
+ if (wsConn._req && wsConn._req.res) {
635
+ errorInfo.statusCode = wsConn._req.res.statusCode;
636
+ if (wsConn._req.res.headers) {
637
+ errorInfo.responseHeaders = Object.assign({}, wsConn._req.res.headers);
638
+ const requestId = wsConn._req.res.headers["dg-request-id"] || wsConn._req.res.headers["x-dg-request-id"];
639
+ if (requestId) {
640
+ errorInfo.requestId = requestId;
641
+ }
642
+ }
643
+ }
644
+ if (event && "target" in event && event.target) {
645
+ const target = event.target;
646
+ if (target.url) {
647
+ errorInfo.url = target.url;
648
+ }
649
+ if (target.readyState !== undefined) {
650
+ errorInfo.readyState = target.readyState;
651
+ }
652
+ }
653
+ }
654
+ return errorInfo;
655
+ }
656
+ createEnhancedError(event, enhancedInfo) {
657
+ const enhancedError = new DeepgramWebSocketError(event.message || "WebSocket connection error", Object.assign({ originalEvent: event }, enhancedInfo));
658
+ return Object.assign(Object.assign({}, event), {
659
+ error: enhancedError,
660
+ statusCode: enhancedInfo.statusCode,
661
+ requestId: enhancedInfo.requestId,
662
+ responseHeaders: enhancedInfo.responseHeaders,
663
+ url: enhancedInfo.url,
664
+ readyState: enhancedInfo.readyState,
665
+ message: this.buildEnhancedErrorMessage(event, enhancedInfo)
666
+ });
667
+ }
668
+ buildEnhancedErrorMessage(event, enhancedInfo) {
669
+ let message = event.message || "WebSocket connection error";
670
+ const details = [];
671
+ if (enhancedInfo.statusCode) {
672
+ details.push(`Status: ${enhancedInfo.statusCode}`);
673
+ }
674
+ if (enhancedInfo.requestId) {
675
+ details.push(`Request ID: ${enhancedInfo.requestId}`);
676
+ }
677
+ if (enhancedInfo.readyState !== undefined) {
678
+ const stateNames = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
679
+ const stateName = stateNames[enhancedInfo.readyState] || `Unknown(${enhancedInfo.readyState})`;
680
+ details.push(`Ready State: ${stateName}`);
681
+ }
682
+ if (enhancedInfo.url) {
683
+ details.push(`URL: ${enhancedInfo.url}`);
684
+ }
685
+ if (details.length > 0) {
686
+ message += ` (${details.join(", ")})`;
687
+ }
688
+ return message;
689
+ }
690
+ setupConnectionEvents(events) {
691
+ if (this.conn) {
692
+ this.conn.onopen = () => {
693
+ this.emit(events.Open, this);
694
+ };
695
+ this.conn.onclose = (event) => {
696
+ this.emit(events.Close, event);
697
+ };
698
+ this.conn.onerror = (event) => {
699
+ const enhancedInfo = this.extractErrorInformation(event, this.conn || undefined);
700
+ const enhancedError = this.createEnhancedError(event, enhancedInfo);
701
+ this.emit(events.Error, enhancedError);
702
+ };
703
+ }
704
+ }
705
+ }
706
+
707
+ class WSWebSocketDummy {
708
+ constructor(address, _protocols, options) {
709
+ this.binaryType = "arraybuffer";
710
+ this.onclose = () => {};
711
+ this.onerror = () => {};
712
+ this.onmessage = () => {};
713
+ this.onopen = () => {};
714
+ this.readyState = SOCKET_STATES.connecting;
715
+ this.send = () => {};
716
+ this.url = null;
717
+ this.url = address.toString();
718
+ this.close = options.close;
719
+ }
720
+ }
721
+
722
+ // node_modules/@deepgram/sdk/dist/module/lib/fetch.js
723
+ var import_cross_fetch2 = __toESM(require_node_ponyfill(), 1);
724
+ var __awaiter2 = function(thisArg, _arguments, P, generator) {
725
+ function adopt(value) {
726
+ return value instanceof P ? value : new P(function(resolve) {
727
+ resolve(value);
728
+ });
729
+ }
730
+ return new (P || (P = Promise))(function(resolve, reject) {
731
+ function fulfilled(value) {
732
+ try {
733
+ step(generator.next(value));
734
+ } catch (e) {
735
+ reject(e);
736
+ }
737
+ }
738
+ function rejected(value) {
739
+ try {
740
+ step(generator["throw"](value));
741
+ } catch (e) {
742
+ reject(e);
743
+ }
744
+ }
745
+ function step(result) {
746
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
747
+ }
748
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
749
+ });
750
+ };
751
+ var resolveFetch = (customFetch) => {
752
+ let _fetch;
753
+ if (customFetch) {
754
+ _fetch = customFetch;
755
+ } else if (typeof fetch === "undefined") {
756
+ _fetch = import_cross_fetch2.default;
757
+ } else {
758
+ _fetch = fetch;
759
+ }
760
+ return (...args) => _fetch(...args);
761
+ };
762
+ var fetchWithAuth = ({ apiKey, customFetch, accessToken }) => {
763
+ const fetch2 = resolveFetch(customFetch);
764
+ const HeadersConstructor = resolveHeadersConstructor();
765
+ return (input, init) => __awaiter2(undefined, undefined, undefined, function* () {
766
+ const headers = new HeadersConstructor(init === null || init === undefined ? undefined : init.headers);
767
+ if (!headers.has("Authorization")) {
768
+ headers.set("Authorization", accessToken ? `Bearer ${accessToken}` : `Token ${apiKey}`);
769
+ }
770
+ return fetch2(input, Object.assign(Object.assign({}, init), { headers }));
771
+ });
772
+ };
773
+ var resolveResponse = () => __awaiter2(undefined, undefined, undefined, function* () {
774
+ if (typeof Response === "undefined") {
775
+ return (yield Promise.resolve().then(() => __toESM(require_node_ponyfill(), 1))).Response;
776
+ }
777
+ return Response;
778
+ });
779
+
780
+ // node_modules/@deepgram/sdk/dist/module/packages/AbstractRestClient.js
781
+ var import_deepmerge2 = __toESM(require_cjs(), 1);
782
+ var __awaiter3 = function(thisArg, _arguments, P, generator) {
783
+ function adopt(value) {
784
+ return value instanceof P ? value : new P(function(resolve) {
785
+ resolve(value);
786
+ });
787
+ }
788
+ return new (P || (P = Promise))(function(resolve, reject) {
789
+ function fulfilled(value) {
790
+ try {
791
+ step(generator.next(value));
792
+ } catch (e) {
793
+ reject(e);
794
+ }
795
+ }
796
+ function rejected(value) {
797
+ try {
798
+ step(generator["throw"](value));
799
+ } catch (e) {
800
+ reject(e);
801
+ }
802
+ }
803
+ function step(result) {
804
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
805
+ }
806
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
807
+ });
808
+ };
809
+
810
+ class AbstractRestClient extends AbstractClient {
811
+ constructor(options) {
812
+ super(options);
813
+ if (isBrowser() && !this.proxy) {
814
+ throw new DeepgramError("Due to CORS we are unable to support REST-based API calls to our API from the browser. Please consider using a proxy: https://dpgr.am/js-proxy for more information.");
815
+ }
816
+ const { accessToken, key: apiKey, fetch: customFetch } = this;
817
+ this.fetch = fetchWithAuth({ accessToken, apiKey, customFetch });
818
+ if (this.proxy) {
819
+ this.baseUrl = this.namespaceOptions.fetch.options.proxy.url;
820
+ } else {
821
+ this.baseUrl = this.namespaceOptions.fetch.options.url;
822
+ }
823
+ }
824
+ _getErrorMessage(err) {
825
+ return err.msg || err.message || err.error_description || err.error || JSON.stringify(err);
826
+ }
827
+ _handleError(error, reject) {
828
+ return __awaiter3(this, undefined, undefined, function* () {
829
+ const Res = yield resolveResponse();
830
+ if (error instanceof Res) {
831
+ error.json().then((err) => {
832
+ reject(new DeepgramApiError(this._getErrorMessage(err), error.status || 500));
833
+ }).catch((err) => {
834
+ reject(new DeepgramUnknownError(this._getErrorMessage(err), err));
835
+ });
836
+ } else {
837
+ reject(new DeepgramUnknownError(this._getErrorMessage(error), error));
838
+ }
839
+ });
840
+ }
841
+ _getRequestOptions(method, bodyOrOptions, options) {
842
+ let reqOptions = { method };
843
+ if (method === "GET" || method === "DELETE") {
844
+ reqOptions = Object.assign(Object.assign({}, reqOptions), bodyOrOptions);
845
+ } else {
846
+ reqOptions = Object.assign(Object.assign({ duplex: "half", body: bodyOrOptions }, reqOptions), options);
847
+ }
848
+ return import_deepmerge2.default(this.namespaceOptions.fetch.options, reqOptions, { clone: false });
849
+ }
850
+ _handleRequest(method, url, bodyOrOptions, options) {
851
+ return __awaiter3(this, undefined, undefined, function* () {
852
+ return new Promise((resolve, reject) => {
853
+ const fetcher = this.fetch;
854
+ fetcher(url, this._getRequestOptions(method, bodyOrOptions, options)).then((result) => {
855
+ if (!result.ok)
856
+ throw result;
857
+ resolve(result);
858
+ }).catch((error) => this._handleError(error, reject));
859
+ });
860
+ });
861
+ }
862
+ get(url, options) {
863
+ return __awaiter3(this, undefined, undefined, function* () {
864
+ return this._handleRequest("GET", url, options);
865
+ });
866
+ }
867
+ post(url, body, options) {
868
+ return __awaiter3(this, undefined, undefined, function* () {
869
+ return this._handleRequest("POST", url, body, options);
870
+ });
871
+ }
872
+ put(url, body, options) {
873
+ return __awaiter3(this, undefined, undefined, function* () {
874
+ return this._handleRequest("PUT", url, body, options);
875
+ });
876
+ }
877
+ patch(url, body, options) {
878
+ return __awaiter3(this, undefined, undefined, function* () {
879
+ return this._handleRequest("PATCH", url, body, options);
880
+ });
881
+ }
882
+ delete(url, options) {
883
+ return __awaiter3(this, undefined, undefined, function* () {
884
+ return this._handleRequest("DELETE", url, options);
885
+ });
886
+ }
887
+ get proxy() {
888
+ var _a;
889
+ return this.key === "proxy" && !!((_a = this.namespaceOptions.fetch.options.proxy) === null || _a === undefined ? undefined : _a.url);
890
+ }
891
+ }
892
+
893
+ // node_modules/@deepgram/sdk/dist/module/lib/enums/AgentEvents.js
894
+ var AgentEvents;
895
+ (function(AgentEvents2) {
896
+ AgentEvents2["Open"] = "Open";
897
+ AgentEvents2["Close"] = "Close";
898
+ AgentEvents2["Error"] = "Error";
899
+ AgentEvents2["Audio"] = "Audio";
900
+ AgentEvents2["Welcome"] = "Welcome";
901
+ AgentEvents2["SettingsApplied"] = "SettingsApplied";
902
+ AgentEvents2["ConversationText"] = "ConversationText";
903
+ AgentEvents2["UserStartedSpeaking"] = "UserStartedSpeaking";
904
+ AgentEvents2["AgentThinking"] = "AgentThinking";
905
+ AgentEvents2["FunctionCallRequest"] = "FunctionCallRequest";
906
+ AgentEvents2["AgentStartedSpeaking"] = "AgentStartedSpeaking";
907
+ AgentEvents2["AgentAudioDone"] = "AgentAudioDone";
908
+ AgentEvents2["InjectionRefused"] = "InjectionRefused";
909
+ AgentEvents2["PromptUpdated"] = "PromptUpdated";
910
+ AgentEvents2["SpeakUpdated"] = "SpeakUpdated";
911
+ AgentEvents2["Unhandled"] = "Unhandled";
912
+ })(AgentEvents || (AgentEvents = {}));
913
+
914
+ // node_modules/@deepgram/sdk/dist/module/packages/AgentLiveClient.js
915
+ class AgentLiveClient extends AbstractLiveClient {
916
+ constructor(options, endpoint = "/:version/agent/converse") {
917
+ var _a, _b, _c, _d;
918
+ super(options);
919
+ this.namespace = "agent";
920
+ this.baseUrl = (_d = (_c = (_b = (_a = options.agent) === null || _a === undefined ? undefined : _a.websocket) === null || _b === undefined ? undefined : _b.options) === null || _c === undefined ? undefined : _c.url) !== null && _d !== undefined ? _d : DEFAULT_AGENT_URL;
921
+ this.connect({}, endpoint);
922
+ }
923
+ setupConnection() {
924
+ this.setupConnectionEvents({
925
+ Open: AgentEvents.Open,
926
+ Close: AgentEvents.Close,
927
+ Error: AgentEvents.Error
928
+ });
929
+ if (this.conn) {
930
+ this.conn.onmessage = (event) => {
931
+ this.handleMessage(event);
932
+ };
933
+ }
934
+ }
935
+ handleMessage(event) {
936
+ var _a, _b, _c, _d, _e, _f;
937
+ if (typeof event.data === "string") {
938
+ try {
939
+ const data = JSON.parse(event.data);
940
+ this.handleTextMessage(data);
941
+ } catch (error) {
942
+ this.emit(AgentEvents.Error, {
943
+ event,
944
+ data: ((_a = event.data) === null || _a === undefined ? undefined : _a.toString().substring(0, 200)) + (((_b = event.data) === null || _b === undefined ? undefined : _b.toString().length) > 200 ? "..." : ""),
945
+ message: "Unable to parse `data` as JSON.",
946
+ error,
947
+ url: (_c = this.conn) === null || _c === undefined ? undefined : _c.url,
948
+ readyState: (_d = this.conn) === null || _d === undefined ? undefined : _d.readyState
949
+ });
950
+ }
951
+ } else if (event.data instanceof Blob) {
952
+ event.data.arrayBuffer().then((buffer) => {
953
+ this.handleBinaryMessage(Buffer.from(buffer));
954
+ });
955
+ } else if (event.data instanceof ArrayBuffer) {
956
+ this.handleBinaryMessage(Buffer.from(event.data));
957
+ } else if (Buffer.isBuffer(event.data)) {
958
+ this.handleBinaryMessage(event.data);
959
+ } else {
960
+ console.log("Received unknown data type", event.data);
961
+ this.emit(AgentEvents.Error, {
962
+ event,
963
+ message: "Received unknown data type.",
964
+ url: (_e = this.conn) === null || _e === undefined ? undefined : _e.url,
965
+ readyState: (_f = this.conn) === null || _f === undefined ? undefined : _f.readyState,
966
+ dataType: typeof event.data
967
+ });
968
+ }
969
+ }
970
+ handleBinaryMessage(data) {
971
+ this.emit(AgentEvents.Audio, data);
972
+ }
973
+ handleTextMessage(data) {
974
+ if (data.type in AgentEvents) {
975
+ this.emit(data.type, data);
976
+ } else {
977
+ this.emit(AgentEvents.Unhandled, data);
978
+ }
979
+ }
980
+ configure(options) {
981
+ const string = JSON.stringify(Object.assign({ type: "Settings" }, options));
982
+ this.send(string);
983
+ }
984
+ updatePrompt(prompt) {
985
+ this.send(JSON.stringify({ type: "UpdatePrompt", prompt }));
986
+ }
987
+ updateSpeak(speakConfig) {
988
+ this.send(JSON.stringify({ type: "UpdateSpeak", speak: speakConfig }));
989
+ }
990
+ injectAgentMessage(content) {
991
+ this.send(JSON.stringify({ type: "InjectAgentMessage", content }));
992
+ }
993
+ injectUserMessage(content) {
994
+ this.send(JSON.stringify({ type: "InjectUserMessage", content }));
995
+ }
996
+ functionCallResponse(response) {
997
+ this.send(JSON.stringify(Object.assign({ type: "FunctionCallResponse" }, response)));
998
+ }
999
+ keepAlive() {
1000
+ this.send(JSON.stringify({ type: "KeepAlive" }));
1001
+ }
1002
+ }
1003
+
1004
+ // node_modules/@deepgram/sdk/dist/module/packages/AuthRestClient.js
1005
+ var __awaiter4 = function(thisArg, _arguments, P, generator) {
1006
+ function adopt(value) {
1007
+ return value instanceof P ? value : new P(function(resolve) {
1008
+ resolve(value);
1009
+ });
1010
+ }
1011
+ return new (P || (P = Promise))(function(resolve, reject) {
1012
+ function fulfilled(value) {
1013
+ try {
1014
+ step(generator.next(value));
1015
+ } catch (e) {
1016
+ reject(e);
1017
+ }
1018
+ }
1019
+ function rejected(value) {
1020
+ try {
1021
+ step(generator["throw"](value));
1022
+ } catch (e) {
1023
+ reject(e);
1024
+ }
1025
+ }
1026
+ function step(result) {
1027
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
1028
+ }
1029
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
1030
+ });
1031
+ };
1032
+
1033
+ class AuthRestClient extends AbstractRestClient {
1034
+ constructor() {
1035
+ super(...arguments);
1036
+ this.namespace = "auth";
1037
+ }
1038
+ grantToken(options = {}, endpoint = ":version/auth/grant") {
1039
+ return __awaiter4(this, undefined, undefined, function* () {
1040
+ try {
1041
+ const requestUrl = this.getRequestUrl(endpoint);
1042
+ const body = JSON.stringify(options);
1043
+ const result = yield this.post(requestUrl, body, {
1044
+ headers: { "Content-Type": "application/json" }
1045
+ }).then((result2) => result2.json());
1046
+ return { result, error: null };
1047
+ } catch (error) {
1048
+ if (isDeepgramError(error)) {
1049
+ return { result: null, error };
1050
+ }
1051
+ throw error;
1052
+ }
1053
+ });
1054
+ }
1055
+ }
1056
+
1057
+ // node_modules/@deepgram/sdk/dist/module/lib/enums/LiveTranscriptionEvents.js
1058
+ var LiveTranscriptionEvents;
1059
+ (function(LiveTranscriptionEvents2) {
1060
+ LiveTranscriptionEvents2["Open"] = "open";
1061
+ LiveTranscriptionEvents2["Close"] = "close";
1062
+ LiveTranscriptionEvents2["Error"] = "error";
1063
+ LiveTranscriptionEvents2["Transcript"] = "Results";
1064
+ LiveTranscriptionEvents2["Metadata"] = "Metadata";
1065
+ LiveTranscriptionEvents2["UtteranceEnd"] = "UtteranceEnd";
1066
+ LiveTranscriptionEvents2["SpeechStarted"] = "SpeechStarted";
1067
+ LiveTranscriptionEvents2["Unhandled"] = "Unhandled";
1068
+ })(LiveTranscriptionEvents || (LiveTranscriptionEvents = {}));
1069
+
1070
+ // node_modules/@deepgram/sdk/dist/module/lib/enums/LiveTTSEvents.js
1071
+ var LiveTTSEvents;
1072
+ (function(LiveTTSEvents2) {
1073
+ LiveTTSEvents2["Open"] = "Open";
1074
+ LiveTTSEvents2["Close"] = "Close";
1075
+ LiveTTSEvents2["Error"] = "Error";
1076
+ LiveTTSEvents2["Metadata"] = "Metadata";
1077
+ LiveTTSEvents2["Flushed"] = "Flushed";
1078
+ LiveTTSEvents2["Warning"] = "Warning";
1079
+ LiveTTSEvents2["Audio"] = "Audio";
1080
+ LiveTTSEvents2["Unhandled"] = "Unhandled";
1081
+ })(LiveTTSEvents || (LiveTTSEvents = {}));
1082
+
1083
+ // node_modules/@deepgram/sdk/dist/module/packages/ListenLiveClient.js
1084
+ class ListenLiveClient extends AbstractLiveClient {
1085
+ constructor(options, transcriptionOptions = {}, endpoint = ":version/listen") {
1086
+ super(options);
1087
+ this.namespace = "listen";
1088
+ this.connect(transcriptionOptions, endpoint);
1089
+ }
1090
+ setupConnection() {
1091
+ this.setupConnectionEvents({
1092
+ Open: LiveTranscriptionEvents.Open,
1093
+ Close: LiveTranscriptionEvents.Close,
1094
+ Error: LiveTranscriptionEvents.Error
1095
+ });
1096
+ if (this.conn) {
1097
+ this.conn.onmessage = (event) => {
1098
+ var _a, _b, _c, _d;
1099
+ try {
1100
+ const data = JSON.parse(event.data.toString());
1101
+ if (data.type === LiveTranscriptionEvents.Metadata) {
1102
+ this.emit(LiveTranscriptionEvents.Metadata, data);
1103
+ } else if (data.type === LiveTranscriptionEvents.Transcript) {
1104
+ this.emit(LiveTranscriptionEvents.Transcript, data);
1105
+ } else if (data.type === LiveTranscriptionEvents.UtteranceEnd) {
1106
+ this.emit(LiveTranscriptionEvents.UtteranceEnd, data);
1107
+ } else if (data.type === LiveTranscriptionEvents.SpeechStarted) {
1108
+ this.emit(LiveTranscriptionEvents.SpeechStarted, data);
1109
+ } else {
1110
+ this.emit(LiveTranscriptionEvents.Unhandled, data);
1111
+ }
1112
+ } catch (error) {
1113
+ this.emit(LiveTranscriptionEvents.Error, {
1114
+ event,
1115
+ message: "Unable to parse `data` as JSON.",
1116
+ error,
1117
+ url: (_a = this.conn) === null || _a === undefined ? undefined : _a.url,
1118
+ readyState: (_b = this.conn) === null || _b === undefined ? undefined : _b.readyState,
1119
+ data: ((_c = event.data) === null || _c === undefined ? undefined : _c.toString().substring(0, 200)) + (((_d = event.data) === null || _d === undefined ? undefined : _d.toString().length) > 200 ? "..." : "")
1120
+ });
1121
+ }
1122
+ };
1123
+ }
1124
+ }
1125
+ configure(config) {
1126
+ this.send(JSON.stringify({
1127
+ type: "Configure",
1128
+ processors: config
1129
+ }));
1130
+ }
1131
+ keepAlive() {
1132
+ this.send(JSON.stringify({
1133
+ type: "KeepAlive"
1134
+ }));
1135
+ }
1136
+ finalize() {
1137
+ this.send(JSON.stringify({
1138
+ type: "Finalize"
1139
+ }));
1140
+ }
1141
+ finish() {
1142
+ this.requestClose();
1143
+ }
1144
+ requestClose() {
1145
+ this.send(JSON.stringify({
1146
+ type: "CloseStream"
1147
+ }));
1148
+ }
1149
+ }
1150
+
1151
+ // node_modules/@deepgram/sdk/dist/module/packages/ListenRestClient.js
1152
+ var __awaiter5 = function(thisArg, _arguments, P, generator) {
1153
+ function adopt(value) {
1154
+ return value instanceof P ? value : new P(function(resolve) {
1155
+ resolve(value);
1156
+ });
1157
+ }
1158
+ return new (P || (P = Promise))(function(resolve, reject) {
1159
+ function fulfilled(value) {
1160
+ try {
1161
+ step(generator.next(value));
1162
+ } catch (e) {
1163
+ reject(e);
1164
+ }
1165
+ }
1166
+ function rejected(value) {
1167
+ try {
1168
+ step(generator["throw"](value));
1169
+ } catch (e) {
1170
+ reject(e);
1171
+ }
1172
+ }
1173
+ function step(result) {
1174
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
1175
+ }
1176
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
1177
+ });
1178
+ };
1179
+
1180
+ class ListenRestClient extends AbstractRestClient {
1181
+ constructor() {
1182
+ super(...arguments);
1183
+ this.namespace = "listen";
1184
+ }
1185
+ transcribeUrl(source, options, endpoint = ":version/listen") {
1186
+ var _a, _b;
1187
+ return __awaiter5(this, undefined, undefined, function* () {
1188
+ try {
1189
+ let body;
1190
+ if (isUrlSource(source)) {
1191
+ body = JSON.stringify(source);
1192
+ } else {
1193
+ throw new DeepgramError("Unknown transcription source type");
1194
+ }
1195
+ if (options !== undefined && "callback" in options) {
1196
+ throw new DeepgramError("Callback cannot be provided as an option to a synchronous transcription. Use `transcribeUrlCallback` or `transcribeFileCallback` instead.");
1197
+ }
1198
+ if (((_a = options === null || options === undefined ? undefined : options.keyterm) === null || _a === undefined ? undefined : _a.length) && !((_b = options.model) === null || _b === undefined ? undefined : _b.startsWith("nova-3"))) {
1199
+ throw new DeepgramError("Keyterms are only supported with the Nova 3 models.");
1200
+ }
1201
+ const requestUrl = this.getRequestUrl(endpoint, {}, Object.assign({}, options));
1202
+ const result = yield this.post(requestUrl, body).then((result2) => result2.json());
1203
+ return { result, error: null };
1204
+ } catch (error) {
1205
+ if (isDeepgramError(error)) {
1206
+ return { result: null, error };
1207
+ }
1208
+ throw error;
1209
+ }
1210
+ });
1211
+ }
1212
+ transcribeFile(source, options, endpoint = ":version/listen") {
1213
+ return __awaiter5(this, undefined, undefined, function* () {
1214
+ try {
1215
+ let body;
1216
+ if (isFileSource(source)) {
1217
+ body = source;
1218
+ } else {
1219
+ throw new DeepgramError("Unknown transcription source type");
1220
+ }
1221
+ if (options !== undefined && "callback" in options) {
1222
+ throw new DeepgramError("Callback cannot be provided as an option to a synchronous transcription. Use `transcribeUrlCallback` or `transcribeFileCallback` instead.");
1223
+ }
1224
+ const requestUrl = this.getRequestUrl(endpoint, {}, Object.assign({}, options));
1225
+ const result = yield this.post(requestUrl, body, {
1226
+ headers: { "Content-Type": "deepgram/audio+video" }
1227
+ }).then((result2) => result2.json());
1228
+ return { result, error: null };
1229
+ } catch (error) {
1230
+ if (isDeepgramError(error)) {
1231
+ return { result: null, error };
1232
+ }
1233
+ throw error;
1234
+ }
1235
+ });
1236
+ }
1237
+ transcribeUrlCallback(source, callback, options, endpoint = ":version/listen") {
1238
+ return __awaiter5(this, undefined, undefined, function* () {
1239
+ try {
1240
+ let body;
1241
+ if (isUrlSource(source)) {
1242
+ body = JSON.stringify(source);
1243
+ } else {
1244
+ throw new DeepgramError("Unknown transcription source type");
1245
+ }
1246
+ const requestUrl = this.getRequestUrl(endpoint, {}, Object.assign(Object.assign({}, options), { callback: callback.toString() }));
1247
+ const result = yield this.post(requestUrl, body).then((result2) => result2.json());
1248
+ return { result, error: null };
1249
+ } catch (error) {
1250
+ if (isDeepgramError(error)) {
1251
+ return { result: null, error };
1252
+ }
1253
+ throw error;
1254
+ }
1255
+ });
1256
+ }
1257
+ transcribeFileCallback(source, callback, options, endpoint = ":version/listen") {
1258
+ return __awaiter5(this, undefined, undefined, function* () {
1259
+ try {
1260
+ let body;
1261
+ if (isFileSource(source)) {
1262
+ body = source;
1263
+ } else {
1264
+ throw new DeepgramError("Unknown transcription source type");
1265
+ }
1266
+ const requestUrl = this.getRequestUrl(endpoint, {}, Object.assign(Object.assign({}, options), { callback: callback.toString() }));
1267
+ const result = yield this.post(requestUrl, body, {
1268
+ headers: { "Content-Type": "deepgram/audio+video" }
1269
+ }).then((result2) => result2.json());
1270
+ return { result, error: null };
1271
+ } catch (error) {
1272
+ if (isDeepgramError(error)) {
1273
+ return { result: null, error };
1274
+ }
1275
+ throw error;
1276
+ }
1277
+ });
1278
+ }
1279
+ }
1280
+
1281
+ // node_modules/@deepgram/sdk/dist/module/packages/ListenClient.js
1282
+ class ListenClient extends AbstractClient {
1283
+ constructor() {
1284
+ super(...arguments);
1285
+ this.namespace = "listen";
1286
+ }
1287
+ get prerecorded() {
1288
+ return new ListenRestClient(this.options);
1289
+ }
1290
+ live(transcriptionOptions = {}, endpoint = ":version/listen") {
1291
+ return new ListenLiveClient(this.options, transcriptionOptions, endpoint);
1292
+ }
1293
+ }
1294
+
1295
+ // node_modules/@deepgram/sdk/dist/module/packages/ManageRestClient.js
1296
+ var __awaiter6 = function(thisArg, _arguments, P, generator) {
1297
+ function adopt(value) {
1298
+ return value instanceof P ? value : new P(function(resolve) {
1299
+ resolve(value);
1300
+ });
1301
+ }
1302
+ return new (P || (P = Promise))(function(resolve, reject) {
1303
+ function fulfilled(value) {
1304
+ try {
1305
+ step(generator.next(value));
1306
+ } catch (e) {
1307
+ reject(e);
1308
+ }
1309
+ }
1310
+ function rejected(value) {
1311
+ try {
1312
+ step(generator["throw"](value));
1313
+ } catch (e) {
1314
+ reject(e);
1315
+ }
1316
+ }
1317
+ function step(result) {
1318
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
1319
+ }
1320
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
1321
+ });
1322
+ };
1323
+
1324
+ class ManageRestClient extends AbstractRestClient {
1325
+ constructor() {
1326
+ super(...arguments);
1327
+ this.namespace = "manage";
1328
+ }
1329
+ getTokenDetails(endpoint = ":version/auth/token") {
1330
+ return __awaiter6(this, undefined, undefined, function* () {
1331
+ try {
1332
+ const requestUrl = this.getRequestUrl(endpoint);
1333
+ const result = yield this.get(requestUrl).then((result2) => result2.json());
1334
+ return { result, error: null };
1335
+ } catch (error) {
1336
+ if (isDeepgramError(error)) {
1337
+ return { result: null, error };
1338
+ }
1339
+ throw error;
1340
+ }
1341
+ });
1342
+ }
1343
+ getProjects(endpoint = ":version/projects") {
1344
+ return __awaiter6(this, undefined, undefined, function* () {
1345
+ try {
1346
+ const requestUrl = this.getRequestUrl(endpoint);
1347
+ const result = yield this.get(requestUrl).then((result2) => result2.json());
1348
+ return { result, error: null };
1349
+ } catch (error) {
1350
+ if (isDeepgramError(error)) {
1351
+ return { result: null, error };
1352
+ }
1353
+ throw error;
1354
+ }
1355
+ });
1356
+ }
1357
+ getProject(projectId, endpoint = ":version/projects/:projectId") {
1358
+ return __awaiter6(this, undefined, undefined, function* () {
1359
+ try {
1360
+ const requestUrl = this.getRequestUrl(endpoint, { projectId });
1361
+ const result = yield this.get(requestUrl).then((result2) => result2.json());
1362
+ return { result, error: null };
1363
+ } catch (error) {
1364
+ if (isDeepgramError(error)) {
1365
+ return { result: null, error };
1366
+ }
1367
+ throw error;
1368
+ }
1369
+ });
1370
+ }
1371
+ updateProject(projectId, options, endpoint = ":version/projects/:projectId") {
1372
+ return __awaiter6(this, undefined, undefined, function* () {
1373
+ try {
1374
+ const requestUrl = this.getRequestUrl(endpoint, { projectId }, options);
1375
+ const body = JSON.stringify(options);
1376
+ const result = yield this.patch(requestUrl, body).then((result2) => result2.json());
1377
+ return { result, error: null };
1378
+ } catch (error) {
1379
+ if (isDeepgramError(error)) {
1380
+ return { result: null, error };
1381
+ }
1382
+ throw error;
1383
+ }
1384
+ });
1385
+ }
1386
+ deleteProject(projectId, endpoint = ":version/projects/:projectId") {
1387
+ return __awaiter6(this, undefined, undefined, function* () {
1388
+ try {
1389
+ const requestUrl = this.getRequestUrl(endpoint, { projectId });
1390
+ yield this.delete(requestUrl);
1391
+ return { error: null };
1392
+ } catch (error) {
1393
+ if (isDeepgramError(error)) {
1394
+ return { error };
1395
+ }
1396
+ throw error;
1397
+ }
1398
+ });
1399
+ }
1400
+ getProjectKeys(projectId, endpoint = ":version/projects/:projectId/keys") {
1401
+ return __awaiter6(this, undefined, undefined, function* () {
1402
+ try {
1403
+ const requestUrl = this.getRequestUrl(endpoint, { projectId });
1404
+ const result = yield this.get(requestUrl).then((result2) => result2.json());
1405
+ return { result, error: null };
1406
+ } catch (error) {
1407
+ if (isDeepgramError(error)) {
1408
+ return { result: null, error };
1409
+ }
1410
+ throw error;
1411
+ }
1412
+ });
1413
+ }
1414
+ getProjectKey(projectId, keyId, endpoint = ":version/projects/:projectId/keys/:keyId") {
1415
+ return __awaiter6(this, undefined, undefined, function* () {
1416
+ try {
1417
+ const requestUrl = this.getRequestUrl(endpoint, { projectId, keyId });
1418
+ const result = yield this.get(requestUrl).then((result2) => result2.json());
1419
+ return { result, error: null };
1420
+ } catch (error) {
1421
+ if (isDeepgramError(error)) {
1422
+ return { result: null, error };
1423
+ }
1424
+ throw error;
1425
+ }
1426
+ });
1427
+ }
1428
+ createProjectKey(projectId, options, endpoint = ":version/projects/:projectId/keys") {
1429
+ return __awaiter6(this, undefined, undefined, function* () {
1430
+ try {
1431
+ const requestUrl = this.getRequestUrl(endpoint, { projectId }, options);
1432
+ const body = JSON.stringify(options);
1433
+ const result = yield this.post(requestUrl, body).then((result2) => result2.json());
1434
+ return { result, error: null };
1435
+ } catch (error) {
1436
+ if (isDeepgramError(error)) {
1437
+ return { result: null, error };
1438
+ }
1439
+ throw error;
1440
+ }
1441
+ });
1442
+ }
1443
+ deleteProjectKey(projectId, keyId, endpoint = ":version/projects/:projectId/keys/:keyId") {
1444
+ return __awaiter6(this, undefined, undefined, function* () {
1445
+ try {
1446
+ const requestUrl = this.getRequestUrl(endpoint, { projectId, keyId });
1447
+ yield this.delete(requestUrl);
1448
+ return { error: null };
1449
+ } catch (error) {
1450
+ if (isDeepgramError(error)) {
1451
+ return { error };
1452
+ }
1453
+ throw error;
1454
+ }
1455
+ });
1456
+ }
1457
+ getProjectMembers(projectId, endpoint = ":version/projects/:projectId/members") {
1458
+ return __awaiter6(this, undefined, undefined, function* () {
1459
+ try {
1460
+ const requestUrl = this.getRequestUrl(endpoint, { projectId });
1461
+ const result = yield this.get(requestUrl).then((result2) => result2.json());
1462
+ return { result, error: null };
1463
+ } catch (error) {
1464
+ if (isDeepgramError(error)) {
1465
+ return { result: null, error };
1466
+ }
1467
+ throw error;
1468
+ }
1469
+ });
1470
+ }
1471
+ removeProjectMember(projectId, memberId, endpoint = ":version/projects/:projectId/members/:memberId") {
1472
+ return __awaiter6(this, undefined, undefined, function* () {
1473
+ try {
1474
+ const requestUrl = this.getRequestUrl(endpoint, { projectId, memberId });
1475
+ yield this.delete(requestUrl);
1476
+ return { error: null };
1477
+ } catch (error) {
1478
+ if (isDeepgramError(error)) {
1479
+ return { error };
1480
+ }
1481
+ throw error;
1482
+ }
1483
+ });
1484
+ }
1485
+ getProjectMemberScopes(projectId, memberId, endpoint = ":version/projects/:projectId/members/:memberId/scopes") {
1486
+ return __awaiter6(this, undefined, undefined, function* () {
1487
+ try {
1488
+ const requestUrl = this.getRequestUrl(endpoint, { projectId, memberId });
1489
+ const result = yield this.get(requestUrl).then((result2) => result2.json());
1490
+ return { result, error: null };
1491
+ } catch (error) {
1492
+ if (isDeepgramError(error)) {
1493
+ return { result: null, error };
1494
+ }
1495
+ throw error;
1496
+ }
1497
+ });
1498
+ }
1499
+ updateProjectMemberScope(projectId, memberId, options, endpoint = ":version/projects/:projectId/members/:memberId/scopes") {
1500
+ return __awaiter6(this, undefined, undefined, function* () {
1501
+ try {
1502
+ const requestUrl = this.getRequestUrl(endpoint, { projectId, memberId }, options);
1503
+ const body = JSON.stringify(options);
1504
+ const result = yield this.put(requestUrl, body).then((result2) => result2.json());
1505
+ return { result, error: null };
1506
+ } catch (error) {
1507
+ if (isDeepgramError(error)) {
1508
+ return { result: null, error };
1509
+ }
1510
+ throw error;
1511
+ }
1512
+ });
1513
+ }
1514
+ getProjectInvites(projectId, endpoint = ":version/projects/:projectId/invites") {
1515
+ return __awaiter6(this, undefined, undefined, function* () {
1516
+ try {
1517
+ const requestUrl = this.getRequestUrl(endpoint, { projectId });
1518
+ const result = yield this.get(requestUrl).then((result2) => result2.json());
1519
+ return { result, error: null };
1520
+ } catch (error) {
1521
+ if (isDeepgramError(error)) {
1522
+ return { result: null, error };
1523
+ }
1524
+ throw error;
1525
+ }
1526
+ });
1527
+ }
1528
+ sendProjectInvite(projectId, options, endpoint = ":version/projects/:projectId/invites") {
1529
+ return __awaiter6(this, undefined, undefined, function* () {
1530
+ try {
1531
+ const requestUrl = this.getRequestUrl(endpoint, { projectId }, options);
1532
+ const body = JSON.stringify(options);
1533
+ const result = yield this.post(requestUrl, body).then((result2) => result2.json());
1534
+ return { result, error: null };
1535
+ } catch (error) {
1536
+ if (isDeepgramError(error)) {
1537
+ return { result: null, error };
1538
+ }
1539
+ throw error;
1540
+ }
1541
+ });
1542
+ }
1543
+ deleteProjectInvite(projectId, email, endpoint = ":version/projects/:projectId/invites/:email") {
1544
+ return __awaiter6(this, undefined, undefined, function* () {
1545
+ try {
1546
+ const requestUrl = this.getRequestUrl(endpoint, { projectId, email });
1547
+ yield this.delete(requestUrl);
1548
+ return { error: null };
1549
+ } catch (error) {
1550
+ if (isDeepgramError(error)) {
1551
+ return { error };
1552
+ }
1553
+ throw error;
1554
+ }
1555
+ });
1556
+ }
1557
+ leaveProject(projectId, endpoint = ":version/projects/:projectId/leave") {
1558
+ return __awaiter6(this, undefined, undefined, function* () {
1559
+ try {
1560
+ const requestUrl = this.getRequestUrl(endpoint, { projectId });
1561
+ const result = yield this.delete(requestUrl).then((result2) => result2.json());
1562
+ return { result, error: null };
1563
+ } catch (error) {
1564
+ if (isDeepgramError(error)) {
1565
+ return { result: null, error };
1566
+ }
1567
+ throw error;
1568
+ }
1569
+ });
1570
+ }
1571
+ getProjectUsageRequests(projectId, options, endpoint = ":version/projects/:projectId/requests") {
1572
+ return __awaiter6(this, undefined, undefined, function* () {
1573
+ try {
1574
+ const requestUrl = this.getRequestUrl(endpoint, { projectId }, options);
1575
+ const result = yield this.get(requestUrl).then((result2) => result2.json());
1576
+ return { result, error: null };
1577
+ } catch (error) {
1578
+ if (isDeepgramError(error)) {
1579
+ return { result: null, error };
1580
+ }
1581
+ throw error;
1582
+ }
1583
+ });
1584
+ }
1585
+ getProjectUsageRequest(projectId, requestId, endpoint = ":version/projects/:projectId/requests/:requestId") {
1586
+ return __awaiter6(this, undefined, undefined, function* () {
1587
+ try {
1588
+ const requestUrl = this.getRequestUrl(endpoint, { projectId, requestId });
1589
+ const result = yield this.get(requestUrl).then((result2) => result2.json());
1590
+ return { result, error: null };
1591
+ } catch (error) {
1592
+ if (isDeepgramError(error)) {
1593
+ return { result: null, error };
1594
+ }
1595
+ throw error;
1596
+ }
1597
+ });
1598
+ }
1599
+ getProjectUsageSummary(projectId, options, endpoint = ":version/projects/:projectId/usage") {
1600
+ return __awaiter6(this, undefined, undefined, function* () {
1601
+ try {
1602
+ const requestUrl = this.getRequestUrl(endpoint, { projectId }, options);
1603
+ const result = yield this.get(requestUrl).then((result2) => result2.json());
1604
+ return { result, error: null };
1605
+ } catch (error) {
1606
+ if (isDeepgramError(error)) {
1607
+ return { result: null, error };
1608
+ }
1609
+ throw error;
1610
+ }
1611
+ });
1612
+ }
1613
+ getProjectUsageFields(projectId, options, endpoint = ":version/projects/:projectId/usage/fields") {
1614
+ return __awaiter6(this, undefined, undefined, function* () {
1615
+ try {
1616
+ const requestUrl = this.getRequestUrl(endpoint, { projectId }, options);
1617
+ const result = yield this.get(requestUrl).then((result2) => result2.json());
1618
+ return { result, error: null };
1619
+ } catch (error) {
1620
+ if (isDeepgramError(error)) {
1621
+ return { result: null, error };
1622
+ }
1623
+ throw error;
1624
+ }
1625
+ });
1626
+ }
1627
+ getProjectBalances(projectId, endpoint = ":version/projects/:projectId/balances") {
1628
+ return __awaiter6(this, undefined, undefined, function* () {
1629
+ try {
1630
+ const requestUrl = this.getRequestUrl(endpoint, { projectId });
1631
+ const result = yield this.get(requestUrl).then((result2) => result2.json());
1632
+ return { result, error: null };
1633
+ } catch (error) {
1634
+ if (isDeepgramError(error)) {
1635
+ return { result: null, error };
1636
+ }
1637
+ throw error;
1638
+ }
1639
+ });
1640
+ }
1641
+ getProjectBalance(projectId, balanceId, endpoint = ":version/projects/:projectId/balances/:balanceId") {
1642
+ return __awaiter6(this, undefined, undefined, function* () {
1643
+ try {
1644
+ const requestUrl = this.getRequestUrl(endpoint, { projectId, balanceId });
1645
+ const result = yield this.get(requestUrl).then((result2) => result2.json());
1646
+ return { result, error: null };
1647
+ } catch (error) {
1648
+ if (isDeepgramError(error)) {
1649
+ return { result: null, error };
1650
+ }
1651
+ throw error;
1652
+ }
1653
+ });
1654
+ }
1655
+ getAllModels(projectId, options = {}, endpoint = ":version/projects/:projectId/models") {
1656
+ return __awaiter6(this, undefined, undefined, function* () {
1657
+ try {
1658
+ const requestUrl = this.getRequestUrl(endpoint, { projectId }, options);
1659
+ const result = yield this.get(requestUrl).then((result2) => result2.json());
1660
+ return { result, error: null };
1661
+ } catch (error) {
1662
+ if (isDeepgramError(error)) {
1663
+ return { result: null, error };
1664
+ }
1665
+ throw error;
1666
+ }
1667
+ });
1668
+ }
1669
+ getModel(projectId, modelId, endpoint = ":version/projects/:projectId/models/:modelId") {
1670
+ return __awaiter6(this, undefined, undefined, function* () {
1671
+ try {
1672
+ const requestUrl = this.getRequestUrl(endpoint, { projectId, modelId });
1673
+ const result = yield this.get(requestUrl).then((result2) => result2.json());
1674
+ return { result, error: null };
1675
+ } catch (error) {
1676
+ if (isDeepgramError(error)) {
1677
+ return { result: null, error };
1678
+ }
1679
+ throw error;
1680
+ }
1681
+ });
1682
+ }
1683
+ }
1684
+
1685
+ // node_modules/@deepgram/sdk/dist/module/packages/ModelsRestClient.js
1686
+ var __awaiter7 = function(thisArg, _arguments, P, generator) {
1687
+ function adopt(value) {
1688
+ return value instanceof P ? value : new P(function(resolve) {
1689
+ resolve(value);
1690
+ });
1691
+ }
1692
+ return new (P || (P = Promise))(function(resolve, reject) {
1693
+ function fulfilled(value) {
1694
+ try {
1695
+ step(generator.next(value));
1696
+ } catch (e) {
1697
+ reject(e);
1698
+ }
1699
+ }
1700
+ function rejected(value) {
1701
+ try {
1702
+ step(generator["throw"](value));
1703
+ } catch (e) {
1704
+ reject(e);
1705
+ }
1706
+ }
1707
+ function step(result) {
1708
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
1709
+ }
1710
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
1711
+ });
1712
+ };
1713
+
1714
+ class ModelsRestClient extends AbstractRestClient {
1715
+ constructor() {
1716
+ super(...arguments);
1717
+ this.namespace = "models";
1718
+ }
1719
+ getAll(endpoint = ":version/models", options = {}) {
1720
+ return __awaiter7(this, undefined, undefined, function* () {
1721
+ try {
1722
+ const requestUrl = this.getRequestUrl(endpoint, {}, options);
1723
+ const result = yield this.get(requestUrl).then((result2) => result2.json());
1724
+ return { result, error: null };
1725
+ } catch (error) {
1726
+ if (isDeepgramError(error)) {
1727
+ return { result: null, error };
1728
+ }
1729
+ throw error;
1730
+ }
1731
+ });
1732
+ }
1733
+ getModel(modelId, endpoint = ":version/models/:modelId") {
1734
+ return __awaiter7(this, undefined, undefined, function* () {
1735
+ try {
1736
+ const requestUrl = this.getRequestUrl(endpoint, { modelId });
1737
+ const result = yield this.get(requestUrl).then((result2) => result2.json());
1738
+ return { result, error: null };
1739
+ } catch (error) {
1740
+ if (isDeepgramError(error)) {
1741
+ return { result: null, error };
1742
+ }
1743
+ throw error;
1744
+ }
1745
+ });
1746
+ }
1747
+ }
1748
+
1749
+ // node_modules/@deepgram/sdk/dist/module/packages/ReadRestClient.js
1750
+ var __awaiter8 = function(thisArg, _arguments, P, generator) {
1751
+ function adopt(value) {
1752
+ return value instanceof P ? value : new P(function(resolve) {
1753
+ resolve(value);
1754
+ });
1755
+ }
1756
+ return new (P || (P = Promise))(function(resolve, reject) {
1757
+ function fulfilled(value) {
1758
+ try {
1759
+ step(generator.next(value));
1760
+ } catch (e) {
1761
+ reject(e);
1762
+ }
1763
+ }
1764
+ function rejected(value) {
1765
+ try {
1766
+ step(generator["throw"](value));
1767
+ } catch (e) {
1768
+ reject(e);
1769
+ }
1770
+ }
1771
+ function step(result) {
1772
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
1773
+ }
1774
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
1775
+ });
1776
+ };
1777
+
1778
+ class ReadRestClient extends AbstractRestClient {
1779
+ constructor() {
1780
+ super(...arguments);
1781
+ this.namespace = "read";
1782
+ }
1783
+ analyzeUrl(source, options, endpoint = ":version/read") {
1784
+ return __awaiter8(this, undefined, undefined, function* () {
1785
+ try {
1786
+ let body;
1787
+ if (isUrlSource(source)) {
1788
+ body = JSON.stringify(source);
1789
+ } else {
1790
+ throw new DeepgramError("Unknown source type");
1791
+ }
1792
+ if (options !== undefined && "callback" in options) {
1793
+ throw new DeepgramError("Callback cannot be provided as an option to a synchronous transcription. Use `analyzeUrlCallback` or `analyzeTextCallback` instead.");
1794
+ }
1795
+ const requestUrl = this.getRequestUrl(endpoint, {}, Object.assign({}, options));
1796
+ const result = yield this.post(requestUrl, body).then((result2) => result2.json());
1797
+ return { result, error: null };
1798
+ } catch (error) {
1799
+ if (isDeepgramError(error)) {
1800
+ return { result: null, error };
1801
+ }
1802
+ throw error;
1803
+ }
1804
+ });
1805
+ }
1806
+ analyzeText(source, options, endpoint = ":version/read") {
1807
+ return __awaiter8(this, undefined, undefined, function* () {
1808
+ try {
1809
+ let body;
1810
+ if (isTextSource(source)) {
1811
+ body = JSON.stringify(source);
1812
+ } else {
1813
+ throw new DeepgramError("Unknown source type");
1814
+ }
1815
+ if (options !== undefined && "callback" in options) {
1816
+ throw new DeepgramError("Callback cannot be provided as an option to a synchronous requests. Use `analyzeUrlCallback` or `analyzeTextCallback` instead.");
1817
+ }
1818
+ const requestUrl = this.getRequestUrl(endpoint, {}, Object.assign({}, options));
1819
+ const result = yield this.post(requestUrl, body).then((result2) => result2.json());
1820
+ return { result, error: null };
1821
+ } catch (error) {
1822
+ if (isDeepgramError(error)) {
1823
+ return { result: null, error };
1824
+ }
1825
+ throw error;
1826
+ }
1827
+ });
1828
+ }
1829
+ analyzeUrlCallback(source, callback, options, endpoint = ":version/read") {
1830
+ return __awaiter8(this, undefined, undefined, function* () {
1831
+ try {
1832
+ let body;
1833
+ if (isUrlSource(source)) {
1834
+ body = JSON.stringify(source);
1835
+ } else {
1836
+ throw new DeepgramError("Unknown source type");
1837
+ }
1838
+ const requestUrl = this.getRequestUrl(endpoint, {}, Object.assign(Object.assign({}, options), { callback: callback.toString() }));
1839
+ const result = yield this.post(requestUrl, body).then((result2) => result2.json());
1840
+ return { result, error: null };
1841
+ } catch (error) {
1842
+ if (isDeepgramError(error)) {
1843
+ return { result: null, error };
1844
+ }
1845
+ throw error;
1846
+ }
1847
+ });
1848
+ }
1849
+ analyzeTextCallback(source, callback, options, endpoint = ":version/read") {
1850
+ return __awaiter8(this, undefined, undefined, function* () {
1851
+ try {
1852
+ let body;
1853
+ if (isTextSource(source)) {
1854
+ body = JSON.stringify(source);
1855
+ } else {
1856
+ throw new DeepgramError("Unknown source type");
1857
+ }
1858
+ const requestUrl = this.getRequestUrl(endpoint, {}, Object.assign(Object.assign({}, options), { callback: callback.toString() }));
1859
+ const result = yield this.post(requestUrl, body, {
1860
+ headers: { "Content-Type": "deepgram/audio+video" }
1861
+ }).then((result2) => result2.json());
1862
+ return { result, error: null };
1863
+ } catch (error) {
1864
+ if (isDeepgramError(error)) {
1865
+ return { result: null, error };
1866
+ }
1867
+ throw error;
1868
+ }
1869
+ });
1870
+ }
1871
+ }
1872
+
1873
+ // node_modules/@deepgram/sdk/dist/module/packages/SelfHostedRestClient.js
1874
+ var __awaiter9 = function(thisArg, _arguments, P, generator) {
1875
+ function adopt(value) {
1876
+ return value instanceof P ? value : new P(function(resolve) {
1877
+ resolve(value);
1878
+ });
1879
+ }
1880
+ return new (P || (P = Promise))(function(resolve, reject) {
1881
+ function fulfilled(value) {
1882
+ try {
1883
+ step(generator.next(value));
1884
+ } catch (e) {
1885
+ reject(e);
1886
+ }
1887
+ }
1888
+ function rejected(value) {
1889
+ try {
1890
+ step(generator["throw"](value));
1891
+ } catch (e) {
1892
+ reject(e);
1893
+ }
1894
+ }
1895
+ function step(result) {
1896
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
1897
+ }
1898
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
1899
+ });
1900
+ };
1901
+
1902
+ class SelfHostedRestClient extends AbstractRestClient {
1903
+ constructor() {
1904
+ super(...arguments);
1905
+ this.namespace = "selfhosted";
1906
+ }
1907
+ listCredentials(projectId, endpoint = ":version/projects/:projectId/onprem/distribution/credentials") {
1908
+ return __awaiter9(this, undefined, undefined, function* () {
1909
+ try {
1910
+ const requestUrl = this.getRequestUrl(endpoint, { projectId });
1911
+ const result = yield this.get(requestUrl).then((result2) => result2.json());
1912
+ return { result, error: null };
1913
+ } catch (error) {
1914
+ if (isDeepgramError(error)) {
1915
+ return { result: null, error };
1916
+ }
1917
+ throw error;
1918
+ }
1919
+ });
1920
+ }
1921
+ getCredentials(projectId, credentialsId, endpoint = ":version/projects/:projectId/onprem/distribution/credentials/:credentialsId") {
1922
+ return __awaiter9(this, undefined, undefined, function* () {
1923
+ try {
1924
+ const requestUrl = this.getRequestUrl(endpoint, { projectId, credentialsId });
1925
+ const result = yield this.get(requestUrl).then((result2) => result2.json());
1926
+ return { result, error: null };
1927
+ } catch (error) {
1928
+ if (isDeepgramError(error)) {
1929
+ return { result: null, error };
1930
+ }
1931
+ throw error;
1932
+ }
1933
+ });
1934
+ }
1935
+ createCredentials(projectId, options, endpoint = ":version/projects/:projectId/onprem/distribution/credentials") {
1936
+ return __awaiter9(this, undefined, undefined, function* () {
1937
+ try {
1938
+ const requestUrl = this.getRequestUrl(endpoint, { projectId });
1939
+ const body = JSON.stringify(options);
1940
+ const result = yield this.post(requestUrl, body).then((result2) => result2.json());
1941
+ return { result, error: null };
1942
+ } catch (error) {
1943
+ if (isDeepgramError(error)) {
1944
+ return { result: null, error };
1945
+ }
1946
+ throw error;
1947
+ }
1948
+ });
1949
+ }
1950
+ deleteCredentials(projectId, credentialsId, endpoint = ":version/projects/:projectId/onprem/distribution/credentials/:credentialsId") {
1951
+ return __awaiter9(this, undefined, undefined, function* () {
1952
+ try {
1953
+ const requestUrl = this.getRequestUrl(endpoint, { projectId, credentialsId });
1954
+ const result = yield this.delete(requestUrl).then((result2) => result2.json());
1955
+ return { result, error: null };
1956
+ } catch (error) {
1957
+ if (isDeepgramError(error)) {
1958
+ return { result: null, error };
1959
+ }
1960
+ throw error;
1961
+ }
1962
+ });
1963
+ }
1964
+ }
1965
+
1966
+ // node_modules/@deepgram/sdk/dist/module/packages/SpeakLiveClient.js
1967
+ class SpeakLiveClient extends AbstractLiveClient {
1968
+ constructor(options, speakOptions = {}, endpoint = ":version/speak") {
1969
+ super(options);
1970
+ this.namespace = "speak";
1971
+ this.connect(speakOptions, endpoint);
1972
+ }
1973
+ setupConnection() {
1974
+ this.setupConnectionEvents({
1975
+ Open: LiveTTSEvents.Open,
1976
+ Close: LiveTTSEvents.Close,
1977
+ Error: LiveTTSEvents.Error
1978
+ });
1979
+ if (this.conn) {
1980
+ this.conn.onmessage = (event) => {
1981
+ this.handleMessage(event);
1982
+ };
1983
+ }
1984
+ }
1985
+ handleTextMessage(data) {
1986
+ if (data.type === LiveTTSEvents.Metadata) {
1987
+ this.emit(LiveTTSEvents.Metadata, data);
1988
+ } else if (data.type === LiveTTSEvents.Flushed) {
1989
+ this.emit(LiveTTSEvents.Flushed, data);
1990
+ } else if (data.type === LiveTTSEvents.Warning) {
1991
+ this.emit(LiveTTSEvents.Warning, data);
1992
+ } else {
1993
+ this.emit(LiveTTSEvents.Unhandled, data);
1994
+ }
1995
+ }
1996
+ handleBinaryMessage(data) {
1997
+ this.emit(LiveTTSEvents.Audio, data);
1998
+ }
1999
+ sendText(text) {
2000
+ this.send(JSON.stringify({
2001
+ type: "Speak",
2002
+ text
2003
+ }));
2004
+ }
2005
+ flush() {
2006
+ this.send(JSON.stringify({
2007
+ type: "Flush"
2008
+ }));
2009
+ }
2010
+ clear() {
2011
+ this.send(JSON.stringify({
2012
+ type: "Clear"
2013
+ }));
2014
+ }
2015
+ requestClose() {
2016
+ this.send(JSON.stringify({
2017
+ type: "Close"
2018
+ }));
2019
+ }
2020
+ handleMessage(event) {
2021
+ var _a, _b, _c, _d, _e, _f;
2022
+ if (typeof event.data === "string") {
2023
+ try {
2024
+ const data = JSON.parse(event.data);
2025
+ this.handleTextMessage(data);
2026
+ } catch (error) {
2027
+ this.emit(LiveTTSEvents.Error, {
2028
+ event,
2029
+ message: "Unable to parse `data` as JSON.",
2030
+ error,
2031
+ url: (_a = this.conn) === null || _a === undefined ? undefined : _a.url,
2032
+ readyState: (_b = this.conn) === null || _b === undefined ? undefined : _b.readyState,
2033
+ data: ((_c = event.data) === null || _c === undefined ? undefined : _c.toString().substring(0, 200)) + (((_d = event.data) === null || _d === undefined ? undefined : _d.toString().length) > 200 ? "..." : "")
2034
+ });
2035
+ }
2036
+ } else if (event.data instanceof Blob) {
2037
+ event.data.arrayBuffer().then((buffer) => {
2038
+ this.handleBinaryMessage(Buffer.from(buffer));
2039
+ });
2040
+ } else if (event.data instanceof ArrayBuffer) {
2041
+ this.handleBinaryMessage(Buffer.from(event.data));
2042
+ } else if (Buffer.isBuffer(event.data)) {
2043
+ this.handleBinaryMessage(event.data);
2044
+ } else {
2045
+ console.log("Received unknown data type", event.data);
2046
+ this.emit(LiveTTSEvents.Error, {
2047
+ event,
2048
+ message: "Received unknown data type.",
2049
+ url: (_e = this.conn) === null || _e === undefined ? undefined : _e.url,
2050
+ readyState: (_f = this.conn) === null || _f === undefined ? undefined : _f.readyState,
2051
+ dataType: typeof event.data
2052
+ });
2053
+ }
2054
+ }
2055
+ }
2056
+
2057
+ // node_modules/@deepgram/sdk/dist/module/packages/SpeakRestClient.js
2058
+ var __awaiter10 = function(thisArg, _arguments, P, generator) {
2059
+ function adopt(value) {
2060
+ return value instanceof P ? value : new P(function(resolve) {
2061
+ resolve(value);
2062
+ });
2063
+ }
2064
+ return new (P || (P = Promise))(function(resolve, reject) {
2065
+ function fulfilled(value) {
2066
+ try {
2067
+ step(generator.next(value));
2068
+ } catch (e) {
2069
+ reject(e);
2070
+ }
2071
+ }
2072
+ function rejected(value) {
2073
+ try {
2074
+ step(generator["throw"](value));
2075
+ } catch (e) {
2076
+ reject(e);
2077
+ }
2078
+ }
2079
+ function step(result) {
2080
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
2081
+ }
2082
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
2083
+ });
2084
+ };
2085
+
2086
+ class SpeakRestClient extends AbstractRestClient {
2087
+ constructor() {
2088
+ super(...arguments);
2089
+ this.namespace = "speak";
2090
+ }
2091
+ request(source, options, endpoint = ":version/speak") {
2092
+ return __awaiter10(this, undefined, undefined, function* () {
2093
+ let body;
2094
+ if (isTextSource(source)) {
2095
+ body = JSON.stringify(source);
2096
+ } else {
2097
+ throw new DeepgramError("Unknown transcription source type");
2098
+ }
2099
+ const requestUrl = this.getRequestUrl(endpoint, {}, Object.assign({ model: "aura-2-thalia-en" }, options));
2100
+ this.result = yield this.post(requestUrl, body, {
2101
+ headers: { Accept: "audio/*", "Content-Type": "application/json" }
2102
+ });
2103
+ return this;
2104
+ });
2105
+ }
2106
+ getStream() {
2107
+ return __awaiter10(this, undefined, undefined, function* () {
2108
+ if (!this.result)
2109
+ throw new DeepgramUnknownError("Tried to get stream before making request", "");
2110
+ return this.result.body;
2111
+ });
2112
+ }
2113
+ getHeaders() {
2114
+ return __awaiter10(this, undefined, undefined, function* () {
2115
+ if (!this.result)
2116
+ throw new DeepgramUnknownError("Tried to get headers before making request", "");
2117
+ return this.result.headers;
2118
+ });
2119
+ }
2120
+ }
2121
+
2122
+ // node_modules/@deepgram/sdk/dist/module/packages/SpeakClient.js
2123
+ class SpeakClient extends AbstractClient {
2124
+ constructor() {
2125
+ super(...arguments);
2126
+ this.namespace = "speak";
2127
+ }
2128
+ request(source, options, endpoint = ":version/speak") {
2129
+ const client = new SpeakRestClient(this.options);
2130
+ return client.request(source, options, endpoint);
2131
+ }
2132
+ live(ttsOptions = {}, endpoint = ":version/speak") {
2133
+ return new SpeakLiveClient(this.options, ttsOptions, endpoint);
2134
+ }
2135
+ }
2136
+
2137
+ // node_modules/@deepgram/sdk/dist/module/DeepgramClient.js
2138
+ class DeepgramClient extends AbstractClient {
2139
+ get auth() {
2140
+ return new AuthRestClient(this.options);
2141
+ }
2142
+ get listen() {
2143
+ return new ListenClient(this.options);
2144
+ }
2145
+ get manage() {
2146
+ return new ManageRestClient(this.options);
2147
+ }
2148
+ get models() {
2149
+ return new ModelsRestClient(this.options);
2150
+ }
2151
+ get onprem() {
2152
+ return this.selfhosted;
2153
+ }
2154
+ get selfhosted() {
2155
+ return new SelfHostedRestClient(this.options);
2156
+ }
2157
+ get read() {
2158
+ return new ReadRestClient(this.options);
2159
+ }
2160
+ get speak() {
2161
+ return new SpeakClient(this.options);
2162
+ }
2163
+ agent(endpoint = "/:version/agent/converse") {
2164
+ return new AgentLiveClient(this.options, endpoint);
2165
+ }
2166
+ get transcription() {
2167
+ throw new DeepgramVersionError;
2168
+ }
2169
+ get projects() {
2170
+ throw new DeepgramVersionError;
2171
+ }
2172
+ get keys() {
2173
+ throw new DeepgramVersionError;
2174
+ }
2175
+ get members() {
2176
+ throw new DeepgramVersionError;
2177
+ }
2178
+ get scopes() {
2179
+ throw new DeepgramVersionError;
2180
+ }
2181
+ get invitation() {
2182
+ throw new DeepgramVersionError;
2183
+ }
2184
+ get usage() {
2185
+ throw new DeepgramVersionError;
2186
+ }
2187
+ get billing() {
2188
+ throw new DeepgramVersionError;
2189
+ }
2190
+ }
2191
+ // node_modules/@deepgram/sdk/dist/module/index.js
2192
+ function createClient(keyOrOptions, options) {
2193
+ let resolvedOptions = {};
2194
+ if (typeof keyOrOptions === "string" || typeof keyOrOptions === "function") {
2195
+ if (typeof options === "object") {
2196
+ resolvedOptions = options;
2197
+ }
2198
+ resolvedOptions.key = keyOrOptions;
2199
+ } else if (typeof keyOrOptions === "object") {
2200
+ resolvedOptions = keyOrOptions;
2201
+ }
2202
+ return new DeepgramClient(resolvedOptions);
2203
+ }
2204
+
2205
+ // src/deepgram.ts
2206
+ var createListenerMap = () => ({
2207
+ close: new Set,
2208
+ endOfTurn: new Set,
2209
+ error: new Set,
2210
+ final: new Set,
2211
+ partial: new Set
2212
+ });
2213
+ var emit = async (listeners, event, payload) => {
2214
+ for (const listener of listeners[event]) {
2215
+ await listener(payload);
2216
+ }
2217
+ };
2218
+ var normalizeWords = (words) => {
2219
+ if (!Array.isArray(words) || words.length === 0) {
2220
+ return {};
2221
+ }
2222
+ const first = words[0];
2223
+ const last = words.at(-1);
2224
+ return {
2225
+ endedAtMs: typeof last?.end === "number" ? Math.round(last.end * 1000) : undefined,
2226
+ startedAtMs: typeof first?.start === "number" ? Math.round(first.start * 1000) : undefined
2227
+ };
2228
+ };
2229
+ var buildTranscript = (payload, vendor) => {
2230
+ const channel = payload.channel && typeof payload.channel === "object" ? payload.channel : null;
2231
+ const alternatives = Array.isArray(channel?.alternatives) ? channel?.alternatives : [];
2232
+ const alternative = alternatives[0];
2233
+ if (!alternative || typeof alternative.transcript !== "string") {
2234
+ return null;
2235
+ }
2236
+ return {
2237
+ ...normalizeWords(Array.isArray(alternative.words) ? alternative.words : undefined),
2238
+ confidence: typeof alternative.confidence === "number" ? alternative.confidence : undefined,
2239
+ id: crypto.randomUUID(),
2240
+ isFinal: payload.is_final === true,
2241
+ language: typeof payload.language === "string" ? payload.language : undefined,
2242
+ text: alternative.transcript,
2243
+ vendor
2244
+ };
2245
+ };
2246
+ var buildLiveOptions = (config, format) => {
2247
+ const options = {
2248
+ channels: format.channels,
2249
+ encoding: "linear16",
2250
+ interim_results: config.interimResults ?? true,
2251
+ model: config.model,
2252
+ punctuate: config.punctuate,
2253
+ sample_rate: format.sampleRateHz,
2254
+ smart_format: config.smartFormat
2255
+ };
2256
+ if (!String(config.model).startsWith("flux")) {
2257
+ options.endpointing = config.endpointing ?? 300;
2258
+ options.language = config.language;
2259
+ options.utterance_end_ms = config.utteranceEndMs;
2260
+ options.vad_events = config.vadEvents;
2261
+ } else {
2262
+ options.eager_eot_threshold = config.eagerEotThreshold;
2263
+ options.eot_threshold = config.eotThreshold;
2264
+ options.eot_timeout_ms = config.eotTimeoutMs;
2265
+ }
2266
+ if (config.diarize !== undefined) {
2267
+ options.diarize = config.diarize;
2268
+ }
2269
+ if (config.numerals !== undefined) {
2270
+ options.numerals = config.numerals;
2271
+ }
2272
+ if (config.profanityFilter !== undefined) {
2273
+ options.profanity_filter = config.profanityFilter;
2274
+ }
2275
+ if (config.redact !== undefined) {
2276
+ options.redact = config.redact;
2277
+ }
2278
+ if (config.tag !== undefined) {
2279
+ options.tag = config.tag;
2280
+ }
2281
+ if (config.extra) {
2282
+ options.extra = config.extra;
2283
+ }
2284
+ const keyterm = config.keyterms ?? config.keyterm;
2285
+ if (keyterm !== undefined) {
2286
+ options.keyterm = keyterm;
2287
+ }
2288
+ return options;
2289
+ };
2290
+ var openConnection = (client, config, liveOptions) => {
2291
+ const listen = client.listen;
2292
+ if (String(config.model).startsWith("flux") && listen && "v2" in listen && listen.v2 && typeof listen.v2.connect === "function") {
2293
+ return listen.v2.connect(liveOptions);
2294
+ }
2295
+ if (listen && typeof listen.live === "function") {
2296
+ return listen.live(liveOptions);
2297
+ }
2298
+ if (listen && "v1" in listen && listen.v1 && typeof listen.v1.connect === "function") {
2299
+ return listen.v1.connect(liveOptions);
2300
+ }
2301
+ throw new Error("Unsupported Deepgram SDK live transcription surface");
2302
+ };
2303
+ var deepgram = (config) => ({
2304
+ kind: "stt",
2305
+ open: (options) => {
2306
+ const client = createClient(config.apiKey);
2307
+ const listeners = createListenerMap();
2308
+ const liveOptions = buildLiveOptions(config, {
2309
+ channels: options.format.channels,
2310
+ sampleRateHz: options.format.sampleRateHz
2311
+ });
2312
+ const connection = openConnection(client, config, liveOptions);
2313
+ const keepAliveMs = config.keepAliveMs ?? 4000;
2314
+ let keepAliveTimer = null;
2315
+ const clearKeepAlive = () => {
2316
+ if (!keepAliveTimer) {
2317
+ return;
2318
+ }
2319
+ clearInterval(keepAliveTimer);
2320
+ keepAliveTimer = null;
2321
+ };
2322
+ connection.on(LiveTranscriptionEvents.Open, () => {
2323
+ clearKeepAlive();
2324
+ keepAliveTimer = setInterval(() => {
2325
+ try {
2326
+ connection.send(JSON.stringify({ type: "KeepAlive" }));
2327
+ } catch {
2328
+ clearKeepAlive();
2329
+ }
2330
+ }, keepAliveMs);
2331
+ });
2332
+ connection.on(LiveTranscriptionEvents.Transcript, (payload) => {
2333
+ const type = typeof payload.type === "string" ? payload.type : "Results";
2334
+ if (type === "UtteranceEnd" || type === "EndOfTurn" || type === "EagerEndOfTurn") {
2335
+ emit(listeners, "endOfTurn", {
2336
+ receivedAt: Date.now(),
2337
+ reason: "vendor",
2338
+ type: "endOfTurn"
2339
+ });
2340
+ return;
2341
+ }
2342
+ if (type === "TurnResumed") {
2343
+ return;
2344
+ }
2345
+ const transcript = buildTranscript(payload, "deepgram");
2346
+ if (!transcript || !transcript.text.trim()) {
2347
+ return;
2348
+ }
2349
+ if (payload.is_final === true) {
2350
+ emit(listeners, "final", {
2351
+ receivedAt: Date.now(),
2352
+ transcript: {
2353
+ ...transcript,
2354
+ isFinal: true
2355
+ },
2356
+ type: "final"
2357
+ });
2358
+ } else {
2359
+ emit(listeners, "partial", {
2360
+ receivedAt: Date.now(),
2361
+ transcript: {
2362
+ ...transcript,
2363
+ isFinal: false
2364
+ },
2365
+ type: "partial"
2366
+ });
2367
+ }
2368
+ if (payload.speech_final === true) {
2369
+ emit(listeners, "endOfTurn", {
2370
+ receivedAt: Date.now(),
2371
+ reason: "vendor",
2372
+ type: "endOfTurn"
2373
+ });
2374
+ }
2375
+ });
2376
+ connection.on(LiveTranscriptionEvents.Error, (error) => {
2377
+ clearKeepAlive();
2378
+ const resolvedError = error instanceof Error ? error : new Error(typeof error.toString === "function" ? String(error) : "Deepgram stream error");
2379
+ emit(listeners, "error", {
2380
+ error: resolvedError,
2381
+ recoverable: false,
2382
+ type: "error"
2383
+ });
2384
+ });
2385
+ connection.on(LiveTranscriptionEvents.Close, (event) => {
2386
+ clearKeepAlive();
2387
+ emit(listeners, "close", {
2388
+ code: event?.code,
2389
+ reason: event?.reason,
2390
+ recoverable: true,
2391
+ type: "close"
2392
+ });
2393
+ });
2394
+ return {
2395
+ close: async (reason) => {
2396
+ clearKeepAlive();
2397
+ try {
2398
+ connection.send(JSON.stringify({ type: "CloseStream" }));
2399
+ } catch {}
2400
+ if (typeof connection.finish === "function") {
2401
+ await connection.finish();
2402
+ } else if (typeof connection.requestClose === "function") {
2403
+ connection.requestClose();
2404
+ } else if (typeof connection.close === "function") {
2405
+ connection.close(1000, reason);
2406
+ }
2407
+ },
2408
+ on: (event, handler) => {
2409
+ listeners[event].add(handler);
2410
+ return () => {
2411
+ listeners[event].delete(handler);
2412
+ };
2413
+ },
2414
+ send: async (audio) => {
2415
+ connection.send(audio);
2416
+ }
2417
+ };
2418
+ }
2419
+ });
2420
+ export {
2421
+ deepgram
2422
+ };