@absolutejs/voice-deepgram 0.0.18 → 0.0.19

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 CHANGED
@@ -1,2216 +1,117 @@
1
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);
2
+ // src/deepgram.ts
3
+ var LISTEN_V1_URL = "wss://api.deepgram.com/v1/listen";
4
+ var LISTEN_V2_URL = "wss://api.deepgram.com/v2/listen";
5
+ var createListenerMap = () => ({
6
+ close: new Set,
7
+ endOfTurn: new Set,
8
+ error: new Set,
9
+ final: new Set,
10
+ partial: new Set
11
+ });
12
+ var DEDUPE_WINDOW_MS = 2500;
13
+ var createSignalDeduper = () => ({
14
+ endOfTurnSignals: new Map,
15
+ finalSignals: new Map
16
+ });
17
+ var normalizeTranscriptText = (text) => text.trim().toLowerCase().replace(/\s+/g, " ");
18
+ var isSignalDuplicate = (signals, key, now) => {
19
+ for (const [signature, seenAt] of signals) {
20
+ if (now - seenAt > DEDUPE_WINDOW_MS) {
21
+ signals.delete(signature);
1773
22
  }
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
23
  }
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
- });
24
+ const lastSeen = signals.get(key);
25
+ if (lastSeen !== undefined && now - lastSeen <= DEDUPE_WINDOW_MS) {
26
+ return true;
1879
27
  }
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
- });
28
+ signals.set(key, now);
29
+ return false;
1900
30
  };
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
- };
31
+ var buildTranscriptSignalKey = (transcript) => [
32
+ transcript.vendor ?? "unknown",
33
+ normalizeTranscriptText(transcript.text),
34
+ String(transcript.startedAtMs ?? ""),
35
+ String(transcript.endedAtMs ?? "")
36
+ ].join("|");
37
+ var toRecord = (value) => typeof value === "object" && value !== null ? value : null;
38
+ var readStringField = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
39
+ var readField = (record, keys) => {
40
+ for (const key of keys) {
41
+ const value = record[key];
42
+ const direct = readStringField(value);
43
+ if (direct) {
44
+ return direct;
1983
45
  }
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
- });
46
+ const nested = toRecord(value);
47
+ if (nested) {
48
+ const nestedMessage = readField(nested, keys);
49
+ if (nestedMessage) {
50
+ return nestedMessage;
2035
51
  }
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
52
  }
2054
53
  }
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
- });
54
+ return;
2084
55
  };
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;
56
+ var resolveErrorDetails = (error) => {
57
+ if (typeof error === "string" && error.trim()) {
58
+ return {
59
+ message: error.trim()
60
+ };
2174
61
  }
2175
- get members() {
2176
- throw new DeepgramVersionError;
62
+ if (error instanceof Error && error.message.trim()) {
63
+ return {
64
+ message: error.message
65
+ };
2177
66
  }
2178
- get scopes() {
2179
- throw new DeepgramVersionError;
67
+ const record = toRecord(error);
68
+ if (!record) {
69
+ return {
70
+ message: "Deepgram stream error"
71
+ };
2180
72
  }
2181
- get invitation() {
2182
- throw new DeepgramVersionError;
73
+ const message = readField(record, ["message", "reason", "description"]) ?? "Deepgram stream error";
74
+ const code = readField(record, ["code", "error_code", "status_code"]);
75
+ const requestId = readField(record, [
76
+ "request_id",
77
+ "requestId",
78
+ "request-id"
79
+ ]);
80
+ return {
81
+ code,
82
+ message,
83
+ requestId
84
+ };
85
+ };
86
+ var isNil = (value) => value == null;
87
+ var collectPhraseHintTerms = (options) => (options.phraseHints ?? []).flatMap((hint) => [
88
+ hint.text,
89
+ ...hint.aliases ?? []
90
+ ]);
91
+ var normalizeKeyterms = (value) => value === undefined ? [] : Array.isArray(value) ? value : [value];
92
+ var formatErrorMessage = (details) => {
93
+ const parts = [
94
+ details.code ? `code=${details.code}` : undefined,
95
+ details.requestId ? `requestId=${details.requestId}` : undefined
96
+ ].filter((value) => typeof value === "string");
97
+ if (parts.length === 0) {
98
+ return details.message;
2183
99
  }
2184
- get usage() {
2185
- throw new DeepgramVersionError;
100
+ return `${details.message} (${parts.join(", ")})`;
101
+ };
102
+ var resolveCloseReason = (code, reason) => {
103
+ const normalized = reason?.trim();
104
+ if (normalized) {
105
+ return normalized;
2186
106
  }
2187
- get billing() {
2188
- throw new DeepgramVersionError;
107
+ if (code === 1006) {
108
+ return "transport closed before handshake";
2189
109
  }
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;
110
+ if (code === 1000) {
111
+ return;
2201
112
  }
2202
- return new DeepgramClient(resolvedOptions);
2203
- }
2204
-
2205
- // src/deepgram.ts
2206
- import WS from "ws";
2207
- var createListenerMap = () => ({
2208
- close: new Set,
2209
- endOfTurn: new Set,
2210
- error: new Set,
2211
- final: new Set,
2212
- partial: new Set
2213
- });
113
+ return `websocket closed with code ${code}`;
114
+ };
2214
115
  var emit = async (listeners, event, payload) => {
2215
116
  for (const listener of listeners[event]) {
2216
117
  await listener(payload);
@@ -2227,81 +128,84 @@ var normalizeWords = (words) => {
2227
128
  startedAtMs: typeof first?.start === "number" ? Math.round(first.start * 1000) : undefined
2228
129
  };
2229
130
  };
2230
- var buildTranscript = (payload, vendor) => {
2231
- const channel = payload.channel && typeof payload.channel === "object" ? payload.channel : null;
2232
- const alternatives = Array.isArray(channel?.alternatives) ? channel?.alternatives : [];
2233
- const alternative = alternatives[0];
131
+ var buildTranscript = (payload) => {
132
+ const alternative = payload.channel?.alternatives?.[0];
2234
133
  if (!alternative || typeof alternative.transcript !== "string") {
2235
134
  return null;
2236
135
  }
2237
136
  return {
2238
- ...normalizeWords(Array.isArray(alternative.words) ? alternative.words : undefined),
137
+ ...normalizeWords(alternative.words),
2239
138
  confidence: typeof alternative.confidence === "number" ? alternative.confidence : undefined,
2240
139
  id: crypto.randomUUID(),
2241
140
  isFinal: payload.is_final === true,
2242
- language: typeof payload.language === "string" ? payload.language : undefined,
141
+ language: payload.language,
2243
142
  text: alternative.transcript,
2244
- vendor
143
+ vendor: "deepgram"
2245
144
  };
2246
145
  };
2247
- var resolveErrorMessage = (error) => {
2248
- if (typeof error === "string" && error.trim()) {
2249
- return error;
2250
- }
2251
- if (error instanceof Error && error.message.trim()) {
2252
- return error.message;
2253
- }
2254
- if (error && typeof error === "object") {
2255
- const record = error;
2256
- for (const key of ["message", "reason", "description"]) {
2257
- const candidate = record[key];
2258
- if (typeof candidate === "string" && candidate.trim()) {
2259
- return candidate;
2260
- }
2261
- }
2262
- if ("error" in record) {
2263
- return resolveErrorMessage(record.error);
2264
- }
2265
- if ("cause" in record) {
2266
- return resolveErrorMessage(record.cause);
2267
- }
2268
- try {
2269
- return JSON.stringify(error);
2270
- } catch {}
146
+ var buildFluxTranscript = (payload) => {
147
+ if (typeof payload.transcript !== "string" || !payload.transcript.trim()) {
148
+ return null;
2271
149
  }
2272
- return "Deepgram stream error";
150
+ const confidences = (payload.words ?? []).map((word) => typeof word.confidence === "number" ? word.confidence : undefined).filter((value) => value !== undefined);
151
+ const confidence = confidences.length > 0 ? confidences.reduce((sum, value) => sum + value, 0) / confidences.length : payload.end_of_turn_confidence;
152
+ return {
153
+ confidence,
154
+ endedAtMs: typeof payload.audio_window_end === "number" ? Math.round(payload.audio_window_end * 1000) : undefined,
155
+ id: typeof payload.sequence_id === "number" ? `flux-${payload.sequence_id}` : crypto.randomUUID(),
156
+ isFinal: payload.event === "EndOfTurn",
157
+ startedAtMs: typeof payload.audio_window_start === "number" ? Math.round(payload.audio_window_start * 1000) : undefined,
158
+ text: payload.transcript,
159
+ vendor: "deepgram"
160
+ };
2273
161
  };
2274
162
  var omitUndefined = (value) => Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));
2275
163
  var buildLiveOptions = (config, format) => {
164
+ const isFlux = String(config.model).startsWith("flux");
165
+ const language = typeof config.language === "string" && config.language.trim().length > 0 ? config.language.trim() : undefined;
2276
166
  const options = {
2277
- channels: format.channels,
2278
167
  encoding: "linear16",
2279
- interim_results: config.interimResults ?? true,
2280
168
  model: config.model,
2281
- punctuate: config.punctuate,
2282
- sample_rate: format.sampleRateHz,
2283
- smart_format: config.smartFormat
169
+ sample_rate: format.sampleRateHz
2284
170
  };
2285
- if (!String(config.model).startsWith("flux")) {
2286
- options.endpointing = config.endpointing ?? 300;
2287
- options.language = config.language;
2288
- options.utterance_end_ms = config.utteranceEndMs;
2289
- options.vad_events = config.vadEvents;
171
+ if (!isFlux) {
172
+ options.channels = format.channels;
173
+ if (config.punctuate !== undefined) {
174
+ options.punctuate = config.punctuate;
175
+ }
176
+ if (config.smartFormat !== undefined) {
177
+ options.smart_format = config.smartFormat;
178
+ }
179
+ if (config.interimResults !== undefined) {
180
+ options.interim_results = config.interimResults;
181
+ }
182
+ if (config.endpointing !== undefined) {
183
+ options.endpointing = config.endpointing;
184
+ }
185
+ if (language) {
186
+ options.language = language;
187
+ }
188
+ if (config.utteranceEndMs !== undefined) {
189
+ options.utterance_end_ms = config.utteranceEndMs;
190
+ }
191
+ if (config.vadEvents !== undefined) {
192
+ options.vad_events = config.vadEvents;
193
+ }
2290
194
  } else {
2291
- options.eager_eot_threshold = config.eagerEotThreshold;
2292
- options.eot_threshold = config.eotThreshold;
2293
- options.eot_timeout_ms = config.eotTimeoutMs;
195
+ options.eager_eot_threshold = config.eagerEotThreshold ?? 0.8;
196
+ options.eot_threshold = config.eotThreshold ?? 0.82;
197
+ options.eot_timeout_ms = config.eotTimeoutMs ?? 1200;
2294
198
  }
2295
- if (config.diarize !== undefined) {
199
+ if (!isFlux && config.diarize !== undefined) {
2296
200
  options.diarize = config.diarize;
2297
201
  }
2298
- if (config.numerals !== undefined) {
202
+ if (!isFlux && config.numerals !== undefined) {
2299
203
  options.numerals = config.numerals;
2300
204
  }
2301
- if (config.profanityFilter !== undefined) {
205
+ if (!isFlux && config.profanityFilter !== undefined) {
2302
206
  options.profanity_filter = config.profanityFilter;
2303
207
  }
2304
- if (config.redact !== undefined) {
208
+ if (!isFlux && config.redact !== undefined) {
2305
209
  options.redact = config.redact;
2306
210
  }
2307
211
  if (config.tag !== undefined) {
@@ -2316,38 +220,78 @@ var buildLiveOptions = (config, format) => {
2316
220
  }
2317
221
  return omitUndefined(options);
2318
222
  };
2319
- var openConnection = (client, config, liveOptions) => {
2320
- const listen = client.listen;
2321
- if (String(config.model).startsWith("flux") && listen && "v2" in listen && listen.v2 && typeof listen.v2.connect === "function") {
2322
- return listen.v2.connect(liveOptions);
2323
- }
2324
- if (listen && typeof listen.live === "function") {
2325
- return listen.live(liveOptions);
223
+ var buildUrl = (config, input) => {
224
+ const url = new URL(String(config.model).startsWith("flux") ? LISTEN_V2_URL : LISTEN_V1_URL);
225
+ const keytermTerms = [
226
+ ...normalizeKeyterms(config.keyterms ?? config.keyterm),
227
+ ...input.phraseHintTerms ?? []
228
+ ].filter((value, index, list) => list.indexOf(value) === index);
229
+ const options = buildLiveOptions({
230
+ ...config,
231
+ keyterms: keytermTerms.length > 0 ? keytermTerms : config.keyterms
232
+ }, {
233
+ channels: input.channels,
234
+ sampleRateHz: input.sampleRateHz
235
+ });
236
+ for (const [key, value] of Object.entries(options)) {
237
+ if (isNil(value)) {
238
+ continue;
239
+ }
240
+ if (Array.isArray(value)) {
241
+ for (const entry of value) {
242
+ url.searchParams.append(key, String(entry));
243
+ }
244
+ continue;
245
+ }
246
+ if (value && typeof value === "object") {
247
+ url.searchParams.set(key, JSON.stringify(value));
248
+ continue;
249
+ }
250
+ url.searchParams.set(key, String(value));
2326
251
  }
2327
- if (listen && "v1" in listen && listen.v1 && typeof listen.v1.connect === "function") {
2328
- return listen.v1.connect(liveOptions);
252
+ return url.toString();
253
+ };
254
+ var createTransport = async (url, apiKey, authMode = "header") => {
255
+ const globalWebSocket = globalThis.WebSocket;
256
+ if (typeof globalWebSocket === "function") {
257
+ if (authMode === "protocol") {
258
+ return new globalWebSocket(url, ["token", apiKey]);
259
+ }
260
+ return new globalWebSocket(url, {
261
+ headers: {
262
+ Authorization: `Token ${apiKey}`
263
+ }
264
+ });
2329
265
  }
2330
- throw new Error("Unsupported Deepgram SDK live transcription surface");
266
+ const headers = {
267
+ Authorization: `Token ${apiKey}`
268
+ };
269
+ return new WebSocket(url, { headers });
270
+ };
271
+ var resolveOpenFailure = (error, url, timeoutMs) => {
272
+ const details = resolveErrorDetails(error);
273
+ return new Error(`${formatErrorMessage(details)} (url=${url}, timeoutMs=${timeoutMs})`);
2331
274
  };
2332
275
  var deepgram = (config) => ({
2333
276
  kind: "stt",
2334
- open: (options) => {
277
+ open: async (options) => {
2335
278
  const emitsNativeEndOfTurn = String(config.model).startsWith("flux");
2336
- const client = createClient(config.apiKey, {
2337
- global: {
2338
- websocket: {
2339
- client: WS
2340
- }
2341
- }
2342
- });
2343
279
  const listeners = createListenerMap();
2344
- const liveOptions = buildLiveOptions(config, {
280
+ const url = buildUrl(config, {
2345
281
  channels: options.format.channels,
282
+ phraseHintTerms: collectPhraseHintTerms(options),
2346
283
  sampleRateHz: options.format.sampleRateHz
2347
284
  });
2348
- const connection = openConnection(client, config, liveOptions);
285
+ const connection = await createTransport(url, config.apiKey, config.authMode);
286
+ const connectTimeoutMs = config.connectTimeoutMs ?? 8000;
2349
287
  const keepAliveMs = config.keepAliveMs ?? 4000;
288
+ const pendingAudio = [];
289
+ const deduper = createSignalDeduper();
2350
290
  let keepAliveTimer = null;
291
+ let openTimeout = null;
292
+ let opened = false;
293
+ let closed = false;
294
+ let openError = false;
2351
295
  const clearKeepAlive = () => {
2352
296
  if (!keepAliveTimer) {
2353
297
  return;
@@ -2355,90 +299,216 @@ var deepgram = (config) => ({
2355
299
  clearInterval(keepAliveTimer);
2356
300
  keepAliveTimer = null;
2357
301
  };
2358
- connection.on(LiveTranscriptionEvents.Open, () => {
2359
- clearKeepAlive();
2360
- keepAliveTimer = setInterval(() => {
2361
- try {
2362
- connection.send(JSON.stringify({ type: "KeepAlive" }));
2363
- } catch {
2364
- clearKeepAlive();
2365
- }
2366
- }, keepAliveMs);
2367
- });
2368
- connection.on(LiveTranscriptionEvents.Transcript, (payload) => {
2369
- const type = typeof payload.type === "string" ? payload.type : "Results";
2370
- if (emitsNativeEndOfTurn && (type === "UtteranceEnd" || type === "EndOfTurn" || type === "EagerEndOfTurn")) {
2371
- emit(listeners, "endOfTurn", {
2372
- receivedAt: Date.now(),
2373
- reason: "vendor",
2374
- type: "endOfTurn"
2375
- });
302
+ const clearOpenTimeout = () => {
303
+ if (!openTimeout) {
2376
304
  return;
2377
305
  }
2378
- if (type === "TurnResumed") {
2379
- return;
306
+ clearTimeout(openTimeout);
307
+ openTimeout = null;
308
+ };
309
+ const failOpen = (error) => {
310
+ if (openError || opened || closed) {
311
+ return new Error("Deepgram websocket failed to open");
2380
312
  }
2381
- const transcript = buildTranscript(payload, "deepgram");
2382
- if (!transcript || !transcript.text.trim()) {
313
+ openError = true;
314
+ clearOpenTimeout();
315
+ return resolveOpenFailure(error, url, connectTimeoutMs);
316
+ };
317
+ const openReadyState = typeof WebSocket.OPEN === "number" ? WebSocket.OPEN : 1;
318
+ const waitForOpen = new Promise((resolve, reject) => {
319
+ openTimeout = setTimeout(() => {
320
+ const message = `Deepgram websocket open timeout after ${connectTimeoutMs}ms`;
321
+ clearOpenTimeout();
322
+ const error = failOpen(new Error(message));
323
+ reject(error);
324
+ connection.close(1013, message);
325
+ }, connectTimeoutMs);
326
+ const handleOpen = () => {
327
+ if (opened || closed) {
328
+ return;
329
+ }
330
+ opened = true;
331
+ clearOpenTimeout();
332
+ const keepAliveEnabled = !String(config.model).startsWith("flux");
333
+ while (pendingAudio.length > 0) {
334
+ const next = pendingAudio.shift();
335
+ if (next) {
336
+ connection.send(next);
337
+ }
338
+ }
339
+ clearKeepAlive();
340
+ if (!keepAliveEnabled) {
341
+ resolve();
342
+ return;
343
+ }
344
+ keepAliveTimer = setInterval(() => {
345
+ if (connection.readyState !== openReadyState) {
346
+ clearKeepAlive();
347
+ return;
348
+ }
349
+ connection.send(JSON.stringify({ type: "KeepAlive" }));
350
+ }, keepAliveMs);
351
+ resolve();
352
+ };
353
+ connection.addEventListener("open", handleOpen, { once: true });
354
+ if (connection.readyState === openReadyState) {
355
+ handleOpen();
356
+ }
357
+ connection.addEventListener("error", (rawEvent) => {
358
+ const event = rawEvent;
359
+ const error = resolveErrorDetails(event.error ?? new Error("Deepgram websocket failed to open"));
360
+ const openFailure = failOpen(error);
361
+ reject(openFailure);
362
+ }, { once: true });
363
+ });
364
+ connection.addEventListener("message", (event) => {
365
+ if (typeof event.data !== "string") {
2383
366
  return;
2384
367
  }
2385
- if (payload.is_final === true) {
2386
- emit(listeners, "final", {
2387
- receivedAt: Date.now(),
2388
- transcript: {
2389
- ...transcript,
2390
- isFinal: true
2391
- },
2392
- type: "final"
2393
- });
2394
- } else {
2395
- emit(listeners, "partial", {
2396
- receivedAt: Date.now(),
2397
- transcript: {
2398
- ...transcript,
2399
- isFinal: false
2400
- },
2401
- type: "partial"
2402
- });
2403
- }
2404
- if (emitsNativeEndOfTurn && payload.speech_final === true) {
2405
- emit(listeners, "endOfTurn", {
2406
- receivedAt: Date.now(),
2407
- reason: "vendor",
2408
- type: "endOfTurn"
368
+ try {
369
+ const payload = JSON.parse(event.data);
370
+ const type = typeof payload.type === "string" ? payload.type : "Results";
371
+ if (emitsNativeEndOfTurn && type === "TurnInfo") {
372
+ const turnInfo = payload;
373
+ const transcript2 = buildFluxTranscript(turnInfo);
374
+ if (!transcript2) {
375
+ return;
376
+ }
377
+ if (turnInfo.event === "EndOfTurn") {
378
+ const now = Date.now();
379
+ const signal = buildTranscriptSignalKey(transcript2);
380
+ if (!isSignalDuplicate(deduper.finalSignals, signal, now)) {
381
+ emit(listeners, "final", {
382
+ receivedAt: now,
383
+ transcript: {
384
+ ...transcript2,
385
+ isFinal: true
386
+ },
387
+ type: "final"
388
+ });
389
+ }
390
+ if (!isSignalDuplicate(deduper.endOfTurnSignals, `eot:${signal}`, now)) {
391
+ emit(listeners, "endOfTurn", {
392
+ receivedAt: now,
393
+ reason: "vendor",
394
+ type: "endOfTurn"
395
+ });
396
+ }
397
+ return;
398
+ }
399
+ if (turnInfo.event === "Update" || turnInfo.event === "EagerEndOfTurn" || turnInfo.event === "TurnResumed") {
400
+ emit(listeners, "partial", {
401
+ receivedAt: Date.now(),
402
+ transcript: {
403
+ ...transcript2,
404
+ isFinal: false
405
+ },
406
+ type: "partial"
407
+ });
408
+ }
409
+ return;
410
+ }
411
+ if (emitsNativeEndOfTurn && (type === "UtteranceEnd" || type === "EndOfTurn" || type === "EagerEndOfTurn")) {
412
+ const now = Date.now();
413
+ const signal = `${type}:${JSON.stringify(payload)}`;
414
+ if (isSignalDuplicate(deduper.endOfTurnSignals, signal, now)) {
415
+ return;
416
+ }
417
+ emit(listeners, "endOfTurn", {
418
+ receivedAt: now,
419
+ reason: "vendor",
420
+ type: "endOfTurn"
421
+ });
422
+ return;
423
+ }
424
+ if (type === "TurnResumed" || type === "Connected" || type === "ConfigureSuccess" || type === "Metadata" || type === "SpeechStarted") {
425
+ return;
426
+ }
427
+ if (type === "ConfigureFailure" || type === "FatalError" || type === "Error") {
428
+ const details = resolveErrorDetails(payload);
429
+ emit(listeners, "error", {
430
+ code: details.code,
431
+ error: new Error(formatErrorMessage(details)),
432
+ recoverable: false,
433
+ type: "error"
434
+ });
435
+ return;
436
+ }
437
+ const transcript = buildTranscript(payload);
438
+ if (!transcript || !transcript.text.trim()) {
439
+ return;
440
+ }
441
+ if (payload.is_final === true) {
442
+ const now = Date.now();
443
+ const signal = buildTranscriptSignalKey(transcript);
444
+ if (!isSignalDuplicate(deduper.finalSignals, `final:${signal}`, now)) {
445
+ emit(listeners, "final", {
446
+ receivedAt: now,
447
+ transcript: {
448
+ ...transcript,
449
+ isFinal: true
450
+ },
451
+ type: "final"
452
+ });
453
+ }
454
+ if (payload.speech_final === true && !isSignalDuplicate(deduper.endOfTurnSignals, `speech-final:${signal}`, now)) {
455
+ emit(listeners, "endOfTurn", {
456
+ receivedAt: now,
457
+ reason: "vendor",
458
+ type: "endOfTurn"
459
+ });
460
+ }
461
+ } else {
462
+ emit(listeners, "partial", {
463
+ receivedAt: Date.now(),
464
+ transcript: {
465
+ ...transcript,
466
+ isFinal: false
467
+ },
468
+ type: "partial"
469
+ });
470
+ }
471
+ } catch (error) {
472
+ const details = resolveErrorDetails(error);
473
+ emit(listeners, "error", {
474
+ code: details.code,
475
+ error: new Error(formatErrorMessage(details)),
476
+ recoverable: false,
477
+ type: "error"
2409
478
  });
2410
479
  }
2411
480
  });
2412
- connection.on(LiveTranscriptionEvents.Error, (error) => {
2413
- clearKeepAlive();
2414
- const resolvedError = error instanceof Error ? error : new Error(resolveErrorMessage(error));
481
+ connection.addEventListener("error", (rawEvent) => {
482
+ const event = rawEvent;
483
+ const details = resolveErrorDetails(event.error ?? event);
2415
484
  emit(listeners, "error", {
2416
- error: resolvedError,
485
+ code: details.code,
486
+ error: event.error instanceof Error ? event.error : new Error(formatErrorMessage(details)),
2417
487
  recoverable: false,
2418
488
  type: "error"
2419
489
  });
2420
490
  });
2421
- connection.on(LiveTranscriptionEvents.Close, (event) => {
491
+ connection.addEventListener("close", (event) => {
492
+ closed = true;
2422
493
  clearKeepAlive();
494
+ clearOpenTimeout();
2423
495
  emit(listeners, "close", {
2424
- code: event?.code,
2425
- reason: event?.reason,
2426
- recoverable: true,
496
+ code: event.code,
497
+ reason: resolveCloseReason(event.code, event.reason),
498
+ recoverable: event.code === 1006 || event.code === 1011 || event.code === 1012,
2427
499
  type: "close"
2428
500
  });
2429
501
  });
502
+ await waitForOpen;
2430
503
  return {
2431
- close: async (reason) => {
504
+ close: async () => {
505
+ if (closed) {
506
+ return;
507
+ }
2432
508
  clearKeepAlive();
2433
- try {
509
+ if (opened && connection.readyState === WebSocket.OPEN) {
2434
510
  connection.send(JSON.stringify({ type: "CloseStream" }));
2435
- } catch {}
2436
- if (typeof connection.finish === "function") {
2437
- await connection.finish();
2438
- } else if (typeof connection.requestClose === "function") {
2439
- connection.requestClose();
2440
- } else if (typeof connection.close === "function") {
2441
- connection.close(1000, reason);
511
+ connection.close(1000, "closed");
2442
512
  }
2443
513
  },
2444
514
  on: (event, handler) => {
@@ -2448,7 +518,15 @@ var deepgram = (config) => ({
2448
518
  };
2449
519
  },
2450
520
  send: async (audio) => {
2451
- connection.send(audio);
521
+ if (closed) {
522
+ return;
523
+ }
524
+ if (opened && connection.readyState === WebSocket.OPEN) {
525
+ connection.send(audio);
526
+ return;
527
+ }
528
+ pendingAudio.push(audio);
529
+ await waitForOpen;
2452
530
  }
2453
531
  };
2454
532
  }