assemblyai 3.1.3 → 4.0.0-beta.1
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/CHANGELOG.md +92 -0
- package/README.md +6 -5
- package/dist/assemblyai.umd.js +683 -0
- package/dist/assemblyai.umd.min.js +1 -0
- package/dist/index.cjs +36 -20
- package/dist/index.mjs +36 -20
- package/dist/index.node.cjs +618 -0
- package/dist/index.node.mjs +611 -0
- package/dist/polyfills/no-fs.d.ts +6 -0
- package/dist/services/realtime/service.d.ts +3 -2
- package/docs/compat.md +59 -0
- package/package.json +37 -10
- package/src/polyfills/no-fs.ts +8 -0
- package/src/services/files/index.ts +0 -2
- package/src/services/realtime/service.ts +34 -24
|
@@ -0,0 +1 @@
|
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).assemblyai={})}(this,(function(e){"use strict";function t(e,t,o,s){return new(o||(o=Promise))((function(r,i){function n(e){try{l(s.next(e))}catch(e){i(e)}}function a(e){try{l(s.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof o?t:new o((function(e){e(t)}))).then(n,a)}l((s=s.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class o{constructor(e){this.params=e}fetch(e,o){var s;return t(this,void 0,void 0,(function*(){(o=null!=o?o:{}).headers=null!==(s=o.headers)&&void 0!==s?s:{},o.headers=Object.assign({Authorization:this.params.apiKey,"Content-Type":"application/json"},o.headers),e.startsWith("http")||(e=this.params.baseUrl+e);const t=yield fetch(e,o);if(t.status>=400){let e;const o=yield t.text();if(o){try{e=JSON.parse(o)}catch(e){}if(null==e?void 0:e.error)throw new Error(e.error);throw new Error(o)}throw new Error(`HTTP Error: ${t.status} ${t.statusText}`)}return t}))}fetchJson(e,o){return t(this,void 0,void 0,(function*(){return(yield this.fetch(e,o)).json()}))}}class s extends o{summary(e){return this.fetchJson("/lemur/v3/generate/summary",{method:"POST",body:JSON.stringify(e)})}questionAnswer(e){return this.fetchJson("/lemur/v3/generate/question-answer",{method:"POST",body:JSON.stringify(e)})}actionItems(e){return this.fetchJson("/lemur/v3/generate/action-items",{method:"POST",body:JSON.stringify(e)})}task(e){return this.fetchJson("/lemur/v3/generate/task",{method:"POST",body:JSON.stringify(e)})}purgeRequestData(e){return this.fetchJson(`/lemur/v3/${e}`,{method:"DELETE"})}}const{ReadableStream:r,ReadableStreamDefaultReader:i,ReadableStreamBYOBReader:n,ReadableStreamBYOBRequest:a,ReadableByteStreamController:l,ReadableStreamDefaultController:c,TransformStream:d,TransformStreamDefaultController:u,WritableStream:h,WritableStreamDefaultWriter:f,WritableStreamDefaultController:p,ByteLengthQueuingStrategy:m,CountQueuingStrategy:y,TextEncoderStream:S,TextDecoderStream:v}="undefined"!=typeof window?window:"undefined"!=typeof global?global:globalThis;!function(e){if(!e.prototype[Symbol.asyncIterator]){async function*t(){const e=this.getReader();try{for(;;){const{done:t,value:o}=await e.read();if(t)return;yield o}}finally{e.releaseLock()}}e.prototype[Symbol.asyncIterator]=t}}(r);var w=null;"undefined"!=typeof WebSocket?w=WebSocket:"undefined"!=typeof MozWebSocket?w=MozWebSocket:"undefined"!=typeof global?w=global.WebSocket||global.MozWebSocket:"undefined"!=typeof window?w=window.WebSocket||window.MozWebSocket:"undefined"!=typeof self&&(w=self.WebSocket||self.MozWebSocket);var b,g=w;!function(e){e[e.BadSampleRate=4e3]="BadSampleRate",e[e.AuthFailed=4001]="AuthFailed",e[e.InsufficientFundsOrFreeAccount=4002]="InsufficientFundsOrFreeAccount",e[e.NonexistentSessionId=4004]="NonexistentSessionId",e[e.SessionExpired=4008]="SessionExpired",e[e.ClosedSession=4010]="ClosedSession",e[e.RateLimited=4029]="RateLimited",e[e.UniqueSessionViolation=4030]="UniqueSessionViolation",e[e.SessionTimeout=4031]="SessionTimeout",e[e.AudioTooShort=4032]="AudioTooShort",e[e.AudioTooLong=4033]="AudioTooLong",e[e.BadJson=4100]="BadJson",e[e.BadSchema=4101]="BadSchema",e[e.TooManyStreams=4102]="TooManyStreams",e[e.Reconnected=4103]="Reconnected",e[e.ReconnectAttemptsExhausted=1013]="ReconnectAttemptsExhausted"}(b||(b={}));const k={[b.BadSampleRate]:"Sample rate must be a positive integer",[b.AuthFailed]:"Not Authorized",[b.InsufficientFundsOrFreeAccount]:"Insufficient funds or you are using a free account. This feature is paid-only and requires you to add a credit card. Please visit https://assemblyai.com/dashboard/ to add a credit card to your account.",[b.NonexistentSessionId]:"Session ID does not exist",[b.SessionExpired]:"Session has expired",[b.ClosedSession]:"Session is closed",[b.RateLimited]:"Rate limited",[b.UniqueSessionViolation]:"Unique session violation",[b.SessionTimeout]:"Session Timeout",[b.AudioTooShort]:"Audio too short",[b.AudioTooLong]:"Audio too long",[b.BadJson]:"Bad JSON",[b.BadSchema]:"Bad schema",[b.TooManyStreams]:"Too many streams",[b.Reconnected]:"Reconnected",[b.ReconnectAttemptsExhausted]:"Reconnect attempts exhausted"};class T extends Error{}class R{constructor(e){var t,o;if(this.listeners={},this.realtimeUrl=null!==(t=e.realtimeUrl)&&void 0!==t?t:"wss://api.assemblyai.com/v2/realtime/ws",this.sampleRate=null!==(o=e.sampleRate)&&void 0!==o?o:16e3,this.wordBoost=e.wordBoost,"apiKey"in e&&e.apiKey&&(this.apiKey=e.apiKey),"token"in e&&e.token&&(this.token=e.token),!this.apiKey&&!this.token)throw new Error("API key or temporary token is required.")}connectionUrl(){const e=new URL(this.realtimeUrl);if("wss:"!==e.protocol)throw new Error("Invalid protocol, must be wss");const t=new URLSearchParams;return this.token&&t.set("token",this.token),t.set("sample_rate",this.sampleRate.toString()),this.wordBoost&&this.wordBoost.length>0&&t.set("word_boost",JSON.stringify(this.wordBoost)),e.search=t.toString(),e}on(e,t){this.listeners[e]=t}connect(){return new Promise((e=>{if(this.socket)throw new Error("Already connected");const t=this.connectionUrl();this.token?this.socket=new g(t.toString()):this.socket=new g(t.toString(),{headers:{Authorization:this.apiKey}}),this.socket.onclose=({code:e,reason:t})=>{var o,s;t||e in b&&(t=k[e]),null===(s=(o=this.listeners).close)||void 0===s||s.call(o,e,t)},this.socket.onerror=e=>{var t,o,s,r;e.error?null===(o=(t=this.listeners).error)||void 0===o||o.call(t,e.error):null===(r=(s=this.listeners).error)||void 0===r||r.call(s,new Error(e.message))},this.socket.onmessage=({data:t})=>{var o,s,r,i,n,a,l,c,d,u,h,f,p;const m=JSON.parse(t.toString());if("error"in m)null===(s=(o=this.listeners).error)||void 0===s||s.call(o,new T(m.error));else switch(m.message_type){case"SessionBegins":{const t={sessionId:m.session_id,expiresAt:new Date(m.expires_at)};e(t),null===(i=(r=this.listeners).open)||void 0===i||i.call(r,t);break}case"PartialTranscript":m.created=new Date(m.created),null===(a=(n=this.listeners).transcript)||void 0===a||a.call(n,m),null===(c=(l=this.listeners)["transcript.partial"])||void 0===c||c.call(l,m);break;case"FinalTranscript":m.created=new Date(m.created),null===(u=(d=this.listeners).transcript)||void 0===u||u.call(d,m),null===(f=(h=this.listeners)["transcript.final"])||void 0===f||f.call(h,m);break;case"SessionTerminated":null===(p=this.sessionTerminatedResolve)||void 0===p||p.call(this)}}}))}sendAudio(e){if(!this.socket||this.socket.readyState!==g.OPEN)throw new Error("Socket is not open for communication");let t;t="undefined"!=typeof Buffer?Buffer.from(e).toString("base64"):btoa(new Uint8Array(e).reduce(((e,t)=>e+String.fromCharCode(t)),""));const o={audio_data:t};this.socket.send(JSON.stringify(o))}stream(){return new h({write:e=>{this.sendAudio(e)}})}close(e=!0){return t(this,void 0,void 0,(function*(){if(this.socket){if(this.socket.readyState===g.OPEN){const t='{"terminate_session": true}';if(e){const e=new Promise((e=>{this.sessionTerminatedResolve=e}));this.socket.send(t),yield e}else this.socket.send(t)}"removeAllListeners"in this.socket&&this.socket.removeAllListeners(),this.socket.close()}this.listeners={},this.socket=void 0}))}}class O extends o{constructor(e){super(e),this.rtFactoryParams=e}createService(e){return e?"token"in e||e.apiKey||(e.apiKey=this.rtFactoryParams.apiKey):e={apiKey:this.rtFactoryParams.apiKey},new R(e)}createTemporaryToken(e){return t(this,void 0,void 0,(function*(){return(yield this.fetchJson("/v2/realtime/token",{method:"POST",body:JSON.stringify(e)})).token}))}}class x extends o{constructor(e,t){super(e),this.files=t}transcribe(e,o){return t(this,void 0,void 0,(function*(){const t=yield this.submit(e);return yield this.waitUntilReady(t.id,o)}))}submit(e){return t(this,void 0,void 0,(function*(){const{audio:t}=e,o=function(e,t){var o={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(o[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(s=Object.getOwnPropertySymbols(e);r<s.length;r++)t.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(e,s[r])&&(o[s[r]]=e[s[r]])}return o}(e,["audio"]);let s;if("string"==typeof t){const e=J(t);s=null!==e?yield this.files.upload(e):t}else s=yield this.files.upload(t);return yield this.fetchJson("/v2/transcript",{method:"POST",body:JSON.stringify(Object.assign(Object.assign({},o),{audio_url:s}))})}))}create(e,o){var s;return t(this,void 0,void 0,(function*(){const t=J(e.audio_url);if(null!==t){const o=yield this.files.upload(t);e.audio_url=o}const r=yield this.fetchJson("/v2/transcript",{method:"POST",body:JSON.stringify(e)});return null===(s=null==o?void 0:o.poll)||void 0===s||s?yield this.waitUntilReady(r.id,o):r}))}waitUntilReady(e,o){var s,r;return t(this,void 0,void 0,(function*(){const t=null!==(s=null==o?void 0:o.pollingInterval)&&void 0!==s?s:3e3,i=null!==(r=null==o?void 0:o.pollingTimeout)&&void 0!==r?r:-1,n=Date.now();for(;;){const o=yield this.get(e);if("completed"===o.status||"error"===o.status)return o;if(i>0&&Date.now()-n>i)throw new Error("Polling timeout");yield new Promise((e=>setTimeout(e,t)))}}))}get(e){return this.fetchJson(`/v2/transcript/${e}`)}list(e){return t(this,void 0,void 0,(function*(){let t="/v2/transcript";"string"==typeof e?t=e:e&&(t=`${t}?${new URLSearchParams(Object.keys(e).map((t=>{var o;return[t,(null===(o=e[t])||void 0===o?void 0:o.toString())||""]})))}`);const o=yield this.fetchJson(t);for(const e of o.transcripts)e.created=new Date(e.created),e.completed&&(e.completed=new Date(e.completed));return o}))}delete(e){return this.fetchJson(`/v2/transcript/${e}`,{method:"DELETE"})}wordSearch(e,t){const o=new URLSearchParams({words:t.join(",")});return this.fetchJson(`/v2/transcript/${e}/word-search?${o.toString()}`)}sentences(e){return this.fetchJson(`/v2/transcript/${e}/sentences`)}paragraphs(e){return this.fetchJson(`/v2/transcript/${e}/paragraphs`)}subtitles(e,o="srt",s){return t(this,void 0,void 0,(function*(){let t=`/v2/transcript/${e}/${o}`;if(s){const e=new URLSearchParams;e.set("chars_per_caption",s.toString()),t+=`?${e.toString()}`}const r=yield this.fetch(t);return yield r.text()}))}redactions(e){return this.fetchJson(`/v2/transcript/${e}/redacted-audio`)}}function J(e){let t;try{return t=new URL(e),"file:"===t.protocol?t.pathname:null}catch(t){return e}}var A={createReadStream:function(){throw new Error("'fs' is not supported in this environment.")}};class E extends o{upload(e){return t(this,void 0,void 0,(function*(){let t;t="string"==typeof e?A.createReadStream(e):e;return(yield this.fetchJson("/v2/upload",{method:"POST",body:t,headers:{"Content-Type":"application/octet-stream"},duplex:"half"})).upload_url}))}}e.AssemblyAI=class{constructor(e){e.baseUrl=e.baseUrl||"https://api.assemblyai.com",e.baseUrl&&e.baseUrl.endsWith("/")&&(e.baseUrl=e.baseUrl.slice(0,-1)),this.files=new E(e),this.transcripts=new x(e,this.files),this.lemur=new s(e),this.realtime=new O(e)}},e.FileService=E,e.LemurService=s,e.RealtimeService=R,e.RealtimeServiceFactory=O,e.TranscriptService=x}));
|
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
var
|
|
5
|
-
var fs = require('fs');
|
|
3
|
+
var isomorphicStreams = require('@swimburger/isomorphic-streams');
|
|
4
|
+
var WebSocket = require('isomorphic-ws');
|
|
6
5
|
|
|
7
6
|
/******************************************************************************
|
|
8
7
|
Copyright (c) Microsoft Corporation.
|
|
@@ -180,9 +179,9 @@ class RealtimeService {
|
|
|
180
179
|
this.realtimeUrl = (_a = params.realtimeUrl) !== null && _a !== void 0 ? _a : defaultRealtimeUrl;
|
|
181
180
|
this.sampleRate = (_b = params.sampleRate) !== null && _b !== void 0 ? _b : 16000;
|
|
182
181
|
this.wordBoost = params.wordBoost;
|
|
183
|
-
if ("apiKey" in params)
|
|
182
|
+
if ("apiKey" in params && params.apiKey)
|
|
184
183
|
this.apiKey = params.apiKey;
|
|
185
|
-
if ("token" in params)
|
|
184
|
+
if ("token" in params && params.token)
|
|
186
185
|
this.token = params.token;
|
|
187
186
|
if (!(this.apiKey || this.token)) {
|
|
188
187
|
throw new Error("API key or temporary token is required.");
|
|
@@ -214,14 +213,14 @@ class RealtimeService {
|
|
|
214
213
|
throw new Error("Already connected");
|
|
215
214
|
}
|
|
216
215
|
const url = this.connectionUrl();
|
|
217
|
-
let headers;
|
|
218
216
|
if (this.token) {
|
|
219
|
-
|
|
217
|
+
this.socket = new WebSocket(url.toString());
|
|
220
218
|
}
|
|
221
|
-
else
|
|
222
|
-
|
|
219
|
+
else {
|
|
220
|
+
this.socket = new WebSocket(url.toString(), {
|
|
221
|
+
headers: { Authorization: this.apiKey },
|
|
222
|
+
});
|
|
223
223
|
}
|
|
224
|
-
this.socket = new WebSocket(url.toString(), { headers });
|
|
225
224
|
this.socket.onclose = ({ code, reason }) => {
|
|
226
225
|
var _a, _b;
|
|
227
226
|
if (!reason) {
|
|
@@ -231,12 +230,12 @@ class RealtimeService {
|
|
|
231
230
|
}
|
|
232
231
|
(_b = (_a = this.listeners).close) === null || _b === void 0 ? void 0 : _b.call(_a, code, reason);
|
|
233
232
|
};
|
|
234
|
-
this.socket.onerror = (
|
|
233
|
+
this.socket.onerror = (event) => {
|
|
235
234
|
var _a, _b, _c, _d;
|
|
236
|
-
if (
|
|
237
|
-
(_b = (_a = this.listeners).error) === null || _b === void 0 ? void 0 : _b.call(_a,
|
|
235
|
+
if (event.error)
|
|
236
|
+
(_b = (_a = this.listeners).error) === null || _b === void 0 ? void 0 : _b.call(_a, event.error);
|
|
238
237
|
else
|
|
239
|
-
(_d = (_c = this.listeners).error) === null || _d === void 0 ? void 0 : _d.call(_c, new Error(
|
|
238
|
+
(_d = (_c = this.listeners).error) === null || _d === void 0 ? void 0 : _d.call(_c, new Error(event.message));
|
|
240
239
|
};
|
|
241
240
|
this.socket.onmessage = ({ data }) => {
|
|
242
241
|
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
|
|
@@ -281,19 +280,26 @@ class RealtimeService {
|
|
|
281
280
|
if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
|
|
282
281
|
throw new Error("Socket is not open for communication");
|
|
283
282
|
}
|
|
283
|
+
let audioData;
|
|
284
|
+
if (typeof Buffer !== "undefined") {
|
|
285
|
+
audioData = Buffer.from(audio).toString("base64");
|
|
286
|
+
}
|
|
287
|
+
else {
|
|
288
|
+
// Buffer is not available in the browser by default
|
|
289
|
+
// https://stackoverflow.com/a/42334410/2919731
|
|
290
|
+
audioData = btoa(new Uint8Array(audio).reduce((data, byte) => data + String.fromCharCode(byte), ""));
|
|
291
|
+
}
|
|
284
292
|
const payload = {
|
|
285
|
-
audio_data:
|
|
293
|
+
audio_data: audioData,
|
|
286
294
|
};
|
|
287
295
|
this.socket.send(JSON.stringify(payload));
|
|
288
296
|
}
|
|
289
297
|
stream() {
|
|
290
|
-
|
|
291
|
-
write: (chunk
|
|
298
|
+
return new isomorphicStreams.WritableStream({
|
|
299
|
+
write: (chunk) => {
|
|
292
300
|
this.sendAudio(chunk);
|
|
293
|
-
next();
|
|
294
301
|
},
|
|
295
302
|
});
|
|
296
|
-
return stream;
|
|
297
303
|
}
|
|
298
304
|
close(waitForSessionTermination = true) {
|
|
299
305
|
return __awaiter(this, void 0, void 0, function* () {
|
|
@@ -311,7 +317,8 @@ class RealtimeService {
|
|
|
311
317
|
this.socket.send(terminateSessionMessage);
|
|
312
318
|
}
|
|
313
319
|
}
|
|
314
|
-
this.socket
|
|
320
|
+
if ("removeAllListeners" in this.socket)
|
|
321
|
+
this.socket.removeAllListeners();
|
|
315
322
|
this.socket.close();
|
|
316
323
|
}
|
|
317
324
|
this.listeners = {};
|
|
@@ -559,6 +566,15 @@ function getPath(path) {
|
|
|
559
566
|
}
|
|
560
567
|
}
|
|
561
568
|
|
|
569
|
+
function throwError() {
|
|
570
|
+
throw new Error("'fs' is not supported in this environment.");
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
const createReadStream = throwError;
|
|
574
|
+
var fs = {
|
|
575
|
+
createReadStream,
|
|
576
|
+
};
|
|
577
|
+
|
|
562
578
|
class FileService extends BaseService {
|
|
563
579
|
/**
|
|
564
580
|
* Upload a local file to AssemblyAI.
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
import fs from 'fs';
|
|
1
|
+
import { WritableStream } from '@swimburger/isomorphic-streams';
|
|
2
|
+
import WebSocket from 'isomorphic-ws';
|
|
4
3
|
|
|
5
4
|
/******************************************************************************
|
|
6
5
|
Copyright (c) Microsoft Corporation.
|
|
@@ -178,9 +177,9 @@ class RealtimeService {
|
|
|
178
177
|
this.realtimeUrl = (_a = params.realtimeUrl) !== null && _a !== void 0 ? _a : defaultRealtimeUrl;
|
|
179
178
|
this.sampleRate = (_b = params.sampleRate) !== null && _b !== void 0 ? _b : 16000;
|
|
180
179
|
this.wordBoost = params.wordBoost;
|
|
181
|
-
if ("apiKey" in params)
|
|
180
|
+
if ("apiKey" in params && params.apiKey)
|
|
182
181
|
this.apiKey = params.apiKey;
|
|
183
|
-
if ("token" in params)
|
|
182
|
+
if ("token" in params && params.token)
|
|
184
183
|
this.token = params.token;
|
|
185
184
|
if (!(this.apiKey || this.token)) {
|
|
186
185
|
throw new Error("API key or temporary token is required.");
|
|
@@ -212,14 +211,14 @@ class RealtimeService {
|
|
|
212
211
|
throw new Error("Already connected");
|
|
213
212
|
}
|
|
214
213
|
const url = this.connectionUrl();
|
|
215
|
-
let headers;
|
|
216
214
|
if (this.token) {
|
|
217
|
-
|
|
215
|
+
this.socket = new WebSocket(url.toString());
|
|
218
216
|
}
|
|
219
|
-
else
|
|
220
|
-
|
|
217
|
+
else {
|
|
218
|
+
this.socket = new WebSocket(url.toString(), {
|
|
219
|
+
headers: { Authorization: this.apiKey },
|
|
220
|
+
});
|
|
221
221
|
}
|
|
222
|
-
this.socket = new WebSocket(url.toString(), { headers });
|
|
223
222
|
this.socket.onclose = ({ code, reason }) => {
|
|
224
223
|
var _a, _b;
|
|
225
224
|
if (!reason) {
|
|
@@ -229,12 +228,12 @@ class RealtimeService {
|
|
|
229
228
|
}
|
|
230
229
|
(_b = (_a = this.listeners).close) === null || _b === void 0 ? void 0 : _b.call(_a, code, reason);
|
|
231
230
|
};
|
|
232
|
-
this.socket.onerror = (
|
|
231
|
+
this.socket.onerror = (event) => {
|
|
233
232
|
var _a, _b, _c, _d;
|
|
234
|
-
if (
|
|
235
|
-
(_b = (_a = this.listeners).error) === null || _b === void 0 ? void 0 : _b.call(_a,
|
|
233
|
+
if (event.error)
|
|
234
|
+
(_b = (_a = this.listeners).error) === null || _b === void 0 ? void 0 : _b.call(_a, event.error);
|
|
236
235
|
else
|
|
237
|
-
(_d = (_c = this.listeners).error) === null || _d === void 0 ? void 0 : _d.call(_c, new Error(
|
|
236
|
+
(_d = (_c = this.listeners).error) === null || _d === void 0 ? void 0 : _d.call(_c, new Error(event.message));
|
|
238
237
|
};
|
|
239
238
|
this.socket.onmessage = ({ data }) => {
|
|
240
239
|
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
|
|
@@ -279,19 +278,26 @@ class RealtimeService {
|
|
|
279
278
|
if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
|
|
280
279
|
throw new Error("Socket is not open for communication");
|
|
281
280
|
}
|
|
281
|
+
let audioData;
|
|
282
|
+
if (typeof Buffer !== "undefined") {
|
|
283
|
+
audioData = Buffer.from(audio).toString("base64");
|
|
284
|
+
}
|
|
285
|
+
else {
|
|
286
|
+
// Buffer is not available in the browser by default
|
|
287
|
+
// https://stackoverflow.com/a/42334410/2919731
|
|
288
|
+
audioData = btoa(new Uint8Array(audio).reduce((data, byte) => data + String.fromCharCode(byte), ""));
|
|
289
|
+
}
|
|
282
290
|
const payload = {
|
|
283
|
-
audio_data:
|
|
291
|
+
audio_data: audioData,
|
|
284
292
|
};
|
|
285
293
|
this.socket.send(JSON.stringify(payload));
|
|
286
294
|
}
|
|
287
295
|
stream() {
|
|
288
|
-
|
|
289
|
-
write: (chunk
|
|
296
|
+
return new WritableStream({
|
|
297
|
+
write: (chunk) => {
|
|
290
298
|
this.sendAudio(chunk);
|
|
291
|
-
next();
|
|
292
299
|
},
|
|
293
300
|
});
|
|
294
|
-
return stream;
|
|
295
301
|
}
|
|
296
302
|
close(waitForSessionTermination = true) {
|
|
297
303
|
return __awaiter(this, void 0, void 0, function* () {
|
|
@@ -309,7 +315,8 @@ class RealtimeService {
|
|
|
309
315
|
this.socket.send(terminateSessionMessage);
|
|
310
316
|
}
|
|
311
317
|
}
|
|
312
|
-
this.socket
|
|
318
|
+
if ("removeAllListeners" in this.socket)
|
|
319
|
+
this.socket.removeAllListeners();
|
|
313
320
|
this.socket.close();
|
|
314
321
|
}
|
|
315
322
|
this.listeners = {};
|
|
@@ -557,6 +564,15 @@ function getPath(path) {
|
|
|
557
564
|
}
|
|
558
565
|
}
|
|
559
566
|
|
|
567
|
+
function throwError() {
|
|
568
|
+
throw new Error("'fs' is not supported in this environment.");
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
const createReadStream = throwError;
|
|
572
|
+
var fs = {
|
|
573
|
+
createReadStream,
|
|
574
|
+
};
|
|
575
|
+
|
|
560
576
|
class FileService extends BaseService {
|
|
561
577
|
/**
|
|
562
578
|
* Upload a local file to AssemblyAI.
|