assemblyai 4.0.0-beta.1 → 4.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -621,13 +621,12 @@
621
621
  }
622
622
  }
623
623
 
624
- function throwError() {
625
- throw new Error("'fs' is not supported in this environment.");
626
- }
627
-
628
- const createReadStream = throwError;
629
- var fs = {
630
- createReadStream,
624
+ const readFile = function (
625
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
626
+ path) {
627
+ return __awaiter(this, void 0, void 0, function* () {
628
+ throw new Error("Interacting with the file system is not supported in this environment.");
629
+ });
631
630
  };
632
631
 
633
632
  class FileService extends BaseService {
@@ -640,7 +639,7 @@
640
639
  return __awaiter(this, void 0, void 0, function* () {
641
640
  let fileData;
642
641
  if (typeof input === "string")
643
- fileData = fs.createReadStream(input);
642
+ fileData = yield readFile();
644
643
  else
645
644
  fileData = input;
646
645
  const data = yield this.fetchJson("/v2/upload", {
@@ -1 +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}));
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(i,r){function n(e){try{l(s.next(e))}catch(e){r(e)}}function a(e){try{l(s.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?i(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:i,ReadableStreamDefaultReader:r,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}}(i);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,i;e.error?null===(o=(t=this.listeners).error)||void 0===o||o.call(t,e.error):null===(i=(s=this.listeners).error)||void 0===i||i.call(s,new Error(e.message))},this.socket.onmessage=({data:t})=>{var o,s,i,r,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===(r=(i=this.listeners).open)||void 0===r||r.call(i,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 i=0;for(s=Object.getOwnPropertySymbols(e);i<s.length;i++)t.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(e,s[i])&&(o[s[i]]=e[s[i]])}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 i=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(i.id,o):i}))}waitUntilReady(e,o){var s,i;return t(this,void 0,void 0,(function*(){const t=null!==(s=null==o?void 0:o.pollingInterval)&&void 0!==s?s:3e3,r=null!==(i=null==o?void 0:o.pollingTimeout)&&void 0!==i?i:-1,n=Date.now();for(;;){const o=yield this.get(e);if("completed"===o.status||"error"===o.status)return o;if(r>0&&Date.now()-n>r)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 i=yield this.fetch(t);return yield i.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}}class A extends o{upload(e){return t(this,void 0,void 0,(function*(){let o;o="string"==typeof e?yield function(e){return t(this,void 0,void 0,(function*(){throw new Error("Interacting with the file system is not supported in this environment.")}))}():e;return(yield this.fetchJson("/v2/upload",{method:"POST",body:o,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 A(e),this.transcripts=new x(e,this.files),this.lemur=new s(e),this.realtime=new O(e)}},e.FileService=A,e.LemurService=s,e.RealtimeService=R,e.RealtimeServiceFactory=O,e.TranscriptService=x}));
@@ -1,50 +1,5 @@
1
1
  import { WritableStream } from '@swimburger/isomorphic-streams';
2
2
  import WebSocket from 'isomorphic-ws';
3
- import fs from 'fs';
4
-
5
- /******************************************************************************
6
- Copyright (c) Microsoft Corporation.
7
-
8
- Permission to use, copy, modify, and/or distribute this software for any
9
- purpose with or without fee is hereby granted.
10
-
11
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
12
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
14
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
16
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17
- PERFORMANCE OF THIS SOFTWARE.
18
- ***************************************************************************** */
19
- /* global Reflect, Promise, SuppressedError, Symbol */
20
-
21
-
22
- function __rest(s, e) {
23
- var t = {};
24
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
25
- t[p] = s[p];
26
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
27
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
28
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
29
- t[p[i]] = s[p[i]];
30
- }
31
- return t;
32
- }
33
-
34
- function __awaiter(thisArg, _arguments, P, generator) {
35
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
36
- return new (P || (P = Promise))(function (resolve, reject) {
37
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
38
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
39
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
40
- step((generator = generator.apply(thisArg, _arguments || [])).next());
41
- });
42
- }
43
-
44
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
45
- var e = new Error(message);
46
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
47
- };
48
3
 
49
4
  /**
50
5
  * Base class for services that communicate with the API.
@@ -57,39 +12,38 @@ class BaseService {
57
12
  constructor(params) {
58
13
  this.params = params;
59
14
  }
60
- fetch(input, init) {
61
- var _a;
62
- return __awaiter(this, void 0, void 0, function* () {
63
- init = init !== null && init !== void 0 ? init : {};
64
- init.headers = (_a = init.headers) !== null && _a !== void 0 ? _a : {};
65
- init.headers = Object.assign({ Authorization: this.params.apiKey, "Content-Type": "application/json" }, init.headers);
66
- if (!input.startsWith("http"))
67
- input = this.params.baseUrl + input;
68
- const response = yield fetch(input, init);
69
- if (response.status >= 400) {
70
- let json;
71
- const text = yield response.text();
72
- if (text) {
73
- try {
74
- json = JSON.parse(text);
75
- }
76
- catch (_b) {
77
- /* empty */
78
- }
79
- if (json === null || json === void 0 ? void 0 : json.error)
80
- throw new Error(json.error);
81
- throw new Error(text);
15
+ async fetch(input, init) {
16
+ init = init ?? {};
17
+ init.headers = init.headers ?? {};
18
+ init.headers = {
19
+ Authorization: this.params.apiKey,
20
+ "Content-Type": "application/json",
21
+ ...init.headers,
22
+ };
23
+ if (!input.startsWith("http"))
24
+ input = this.params.baseUrl + input;
25
+ const response = await fetch(input, init);
26
+ if (response.status >= 400) {
27
+ let json;
28
+ const text = await response.text();
29
+ if (text) {
30
+ try {
31
+ json = JSON.parse(text);
32
+ }
33
+ catch {
34
+ /* empty */
82
35
  }
83
- throw new Error(`HTTP Error: ${response.status} ${response.statusText}`);
36
+ if (json?.error)
37
+ throw new Error(json.error);
38
+ throw new Error(text);
84
39
  }
85
- return response;
86
- });
40
+ throw new Error(`HTTP Error: ${response.status} ${response.statusText}`);
41
+ }
42
+ return response;
87
43
  }
88
- fetchJson(input, init) {
89
- return __awaiter(this, void 0, void 0, function* () {
90
- const response = yield this.fetch(input, init);
91
- return response.json();
92
- });
44
+ async fetchJson(input, init) {
45
+ const response = await this.fetch(input, init);
46
+ return response.json();
93
47
  }
94
48
  }
95
49
 
@@ -173,10 +127,9 @@ class RealtimeError extends Error {
173
127
  const defaultRealtimeUrl = "wss://api.assemblyai.com/v2/realtime/ws";
174
128
  class RealtimeService {
175
129
  constructor(params) {
176
- var _a, _b;
177
130
  this.listeners = {};
178
- this.realtimeUrl = (_a = params.realtimeUrl) !== null && _a !== void 0 ? _a : defaultRealtimeUrl;
179
- this.sampleRate = (_b = params.sampleRate) !== null && _b !== void 0 ? _b : 16000;
131
+ this.realtimeUrl = params.realtimeUrl ?? defaultRealtimeUrl;
132
+ this.sampleRate = params.sampleRate ?? 16000;
180
133
  this.wordBoost = params.wordBoost;
181
134
  if ("apiKey" in params && params.apiKey)
182
135
  this.apiKey = params.apiKey;
@@ -221,26 +174,23 @@ class RealtimeService {
221
174
  });
222
175
  }
223
176
  this.socket.onclose = ({ code, reason }) => {
224
- var _a, _b;
225
177
  if (!reason) {
226
178
  if (code in RealtimeErrorType) {
227
179
  reason = RealtimeErrorMessages[code];
228
180
  }
229
181
  }
230
- (_b = (_a = this.listeners).close) === null || _b === void 0 ? void 0 : _b.call(_a, code, reason);
182
+ this.listeners.close?.(code, reason);
231
183
  };
232
184
  this.socket.onerror = (event) => {
233
- var _a, _b, _c, _d;
234
185
  if (event.error)
235
- (_b = (_a = this.listeners).error) === null || _b === void 0 ? void 0 : _b.call(_a, event.error);
186
+ this.listeners.error?.(event.error);
236
187
  else
237
- (_d = (_c = this.listeners).error) === null || _d === void 0 ? void 0 : _d.call(_c, new Error(event.message));
188
+ this.listeners.error?.(new Error(event.message));
238
189
  };
239
190
  this.socket.onmessage = ({ data }) => {
240
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
241
191
  const message = JSON.parse(data.toString());
242
192
  if ("error" in message) {
243
- (_b = (_a = this.listeners).error) === null || _b === void 0 ? void 0 : _b.call(_a, new RealtimeError(message.error));
193
+ this.listeners.error?.(new RealtimeError(message.error));
244
194
  return;
245
195
  }
246
196
  switch (message.message_type) {
@@ -250,25 +200,25 @@ class RealtimeService {
250
200
  expiresAt: new Date(message.expires_at),
251
201
  };
252
202
  resolve(openObject);
253
- (_d = (_c = this.listeners).open) === null || _d === void 0 ? void 0 : _d.call(_c, openObject);
203
+ this.listeners.open?.(openObject);
254
204
  break;
255
205
  }
256
206
  case "PartialTranscript": {
257
207
  // message.created is actually a string when coming from the socket
258
208
  message.created = new Date(message.created);
259
- (_f = (_e = this.listeners).transcript) === null || _f === void 0 ? void 0 : _f.call(_e, message);
260
- (_h = (_g = this.listeners)["transcript.partial"]) === null || _h === void 0 ? void 0 : _h.call(_g, message);
209
+ this.listeners.transcript?.(message);
210
+ this.listeners["transcript.partial"]?.(message);
261
211
  break;
262
212
  }
263
213
  case "FinalTranscript": {
264
214
  // message.created is actually a string when coming from the socket
265
215
  message.created = new Date(message.created);
266
- (_k = (_j = this.listeners).transcript) === null || _k === void 0 ? void 0 : _k.call(_j, message);
267
- (_m = (_l = this.listeners)["transcript.final"]) === null || _m === void 0 ? void 0 : _m.call(_l, message);
216
+ this.listeners.transcript?.(message);
217
+ this.listeners["transcript.final"]?.(message);
268
218
  break;
269
219
  }
270
220
  case "SessionTerminated": {
271
- (_o = this.sessionTerminatedResolve) === null || _o === void 0 ? void 0 : _o.call(this);
221
+ this.sessionTerminatedResolve?.();
272
222
  break;
273
223
  }
274
224
  }
@@ -300,29 +250,27 @@ class RealtimeService {
300
250
  },
301
251
  });
302
252
  }
303
- close(waitForSessionTermination = true) {
304
- return __awaiter(this, void 0, void 0, function* () {
305
- if (this.socket) {
306
- if (this.socket.readyState === WebSocket.OPEN) {
307
- const terminateSessionMessage = `{"terminate_session": true}`;
308
- if (waitForSessionTermination) {
309
- const sessionTerminatedPromise = new Promise((resolve) => {
310
- this.sessionTerminatedResolve = resolve;
311
- });
312
- this.socket.send(terminateSessionMessage);
313
- yield sessionTerminatedPromise;
314
- }
315
- else {
316
- this.socket.send(terminateSessionMessage);
317
- }
253
+ async close(waitForSessionTermination = true) {
254
+ if (this.socket) {
255
+ if (this.socket.readyState === WebSocket.OPEN) {
256
+ const terminateSessionMessage = `{"terminate_session": true}`;
257
+ if (waitForSessionTermination) {
258
+ const sessionTerminatedPromise = new Promise((resolve) => {
259
+ this.sessionTerminatedResolve = resolve;
260
+ });
261
+ this.socket.send(terminateSessionMessage);
262
+ await sessionTerminatedPromise;
263
+ }
264
+ else {
265
+ this.socket.send(terminateSessionMessage);
318
266
  }
319
- if ("removeAllListeners" in this.socket)
320
- this.socket.removeAllListeners();
321
- this.socket.close();
322
267
  }
323
- this.listeners = {};
324
- this.socket = undefined;
325
- });
268
+ if ("removeAllListeners" in this.socket)
269
+ this.socket.removeAllListeners();
270
+ this.socket.close();
271
+ }
272
+ this.listeners = {};
273
+ this.socket = undefined;
326
274
  }
327
275
  }
328
276
 
@@ -339,14 +287,12 @@ class RealtimeServiceFactory extends BaseService {
339
287
  }
340
288
  return new RealtimeService(params);
341
289
  }
342
- createTemporaryToken(params) {
343
- return __awaiter(this, void 0, void 0, function* () {
344
- const data = yield this.fetchJson("/v2/realtime/token", {
345
- method: "POST",
346
- body: JSON.stringify(params),
347
- });
348
- return data.token;
290
+ async createTemporaryToken(params) {
291
+ const data = await this.fetchJson("/v2/realtime/token", {
292
+ method: "POST",
293
+ body: JSON.stringify(params),
349
294
  });
295
+ return data.token;
350
296
  }
351
297
  }
352
298
 
@@ -361,42 +307,38 @@ class TranscriptService extends BaseService {
361
307
  * @param options The options to transcribe an audio file.
362
308
  * @returns A promise that resolves to the transcript. The transcript status is "completed" or "error".
363
309
  */
364
- transcribe(params, options) {
365
- return __awaiter(this, void 0, void 0, function* () {
366
- const transcript = yield this.submit(params);
367
- return yield this.waitUntilReady(transcript.id, options);
368
- });
310
+ async transcribe(params, options) {
311
+ const transcript = await this.submit(params);
312
+ return await this.waitUntilReady(transcript.id, options);
369
313
  }
370
314
  /**
371
315
  * Submits a transcription job for an audio file. This will not wait until the transcript status is "completed" or "error".
372
316
  * @param params The parameters to start the transcription of an audio file.
373
317
  * @returns A promise that resolves to the queued transcript.
374
318
  */
375
- submit(params) {
376
- return __awaiter(this, void 0, void 0, function* () {
377
- const { audio } = params, createParams = __rest(params, ["audio"]);
378
- let audioUrl;
379
- if (typeof audio === "string") {
380
- const path = getPath(audio);
381
- if (path !== null) {
382
- // audio is local path, upload local file
383
- audioUrl = yield this.files.upload(path);
384
- }
385
- else {
386
- // audio is not a local path, assume it's a URL
387
- audioUrl = audio;
388
- }
319
+ async submit(params) {
320
+ const { audio, ...createParams } = params;
321
+ let audioUrl;
322
+ if (typeof audio === "string") {
323
+ const path = getPath(audio);
324
+ if (path !== null) {
325
+ // audio is local path, upload local file
326
+ audioUrl = await this.files.upload(path);
389
327
  }
390
328
  else {
391
- // audio is of uploadable type
392
- audioUrl = yield this.files.upload(audio);
329
+ // audio is not a local path, assume it's a URL
330
+ audioUrl = audio;
393
331
  }
394
- const data = yield this.fetchJson("/v2/transcript", {
395
- method: "POST",
396
- body: JSON.stringify(Object.assign(Object.assign({}, createParams), { audio_url: audioUrl })),
397
- });
398
- return data;
332
+ }
333
+ else {
334
+ // audio is of uploadable type
335
+ audioUrl = await this.files.upload(audio);
336
+ }
337
+ const data = await this.fetchJson("/v2/transcript", {
338
+ method: "POST",
339
+ body: JSON.stringify({ ...createParams, audio_url: audioUrl }),
399
340
  });
341
+ return data;
400
342
  }
401
343
  /**
402
344
  * Create a transcript.
@@ -405,23 +347,20 @@ class TranscriptService extends BaseService {
405
347
  * @returns A promise that resolves to the transcript.
406
348
  * @deprecated Use `transcribe` instead to transcribe a audio file that includes polling, or `submit` to transcribe a audio file without polling.
407
349
  */
408
- create(params, options) {
409
- var _a;
410
- return __awaiter(this, void 0, void 0, function* () {
411
- const path = getPath(params.audio_url);
412
- if (path !== null) {
413
- const uploadUrl = yield this.files.upload(path);
414
- params.audio_url = uploadUrl;
415
- }
416
- const data = yield this.fetchJson("/v2/transcript", {
417
- method: "POST",
418
- body: JSON.stringify(params),
419
- });
420
- if ((_a = options === null || options === void 0 ? void 0 : options.poll) !== null && _a !== void 0 ? _a : true) {
421
- return yield this.waitUntilReady(data.id, options);
422
- }
423
- return data;
350
+ async create(params, options) {
351
+ const path = getPath(params.audio_url);
352
+ if (path !== null) {
353
+ const uploadUrl = await this.files.upload(path);
354
+ params.audio_url = uploadUrl;
355
+ }
356
+ const data = await this.fetchJson("/v2/transcript", {
357
+ method: "POST",
358
+ body: JSON.stringify(params),
424
359
  });
360
+ if (options?.poll ?? true) {
361
+ return await this.waitUntilReady(data.id, options);
362
+ }
363
+ return data;
425
364
  }
426
365
  /**
427
366
  * Wait until the transcript ready, either the status is "completed" or "error".
@@ -429,27 +368,24 @@ class TranscriptService extends BaseService {
429
368
  * @param options The options to wait until the transcript is ready.
430
369
  * @returns A promise that resolves to the transcript. The transcript status is "completed" or "error".
431
370
  */
432
- waitUntilReady(transcriptId, options) {
433
- var _a, _b;
434
- return __awaiter(this, void 0, void 0, function* () {
435
- const pollingInterval = (_a = options === null || options === void 0 ? void 0 : options.pollingInterval) !== null && _a !== void 0 ? _a : 3000;
436
- const pollingTimeout = (_b = options === null || options === void 0 ? void 0 : options.pollingTimeout) !== null && _b !== void 0 ? _b : -1;
437
- const startTime = Date.now();
438
- // eslint-disable-next-line no-constant-condition
439
- while (true) {
440
- const transcript = yield this.get(transcriptId);
441
- if (transcript.status === "completed" || transcript.status === "error") {
442
- return transcript;
443
- }
444
- else if (pollingTimeout > 0 &&
445
- Date.now() - startTime > pollingTimeout) {
446
- throw new Error("Polling timeout");
447
- }
448
- else {
449
- yield new Promise((resolve) => setTimeout(resolve, pollingInterval));
450
- }
371
+ async waitUntilReady(transcriptId, options) {
372
+ const pollingInterval = options?.pollingInterval ?? 3000;
373
+ const pollingTimeout = options?.pollingTimeout ?? -1;
374
+ const startTime = Date.now();
375
+ // eslint-disable-next-line no-constant-condition
376
+ while (true) {
377
+ const transcript = await this.get(transcriptId);
378
+ if (transcript.status === "completed" || transcript.status === "error") {
379
+ return transcript;
451
380
  }
452
- });
381
+ else if (pollingTimeout > 0 &&
382
+ Date.now() - startTime > pollingTimeout) {
383
+ throw new Error("Polling timeout");
384
+ }
385
+ else {
386
+ await new Promise((resolve) => setTimeout(resolve, pollingInterval));
387
+ }
388
+ }
453
389
  }
454
390
  /**
455
391
  * Retrieve a transcript.
@@ -463,30 +399,25 @@ class TranscriptService extends BaseService {
463
399
  * Retrieves a page of transcript listings.
464
400
  * @param parameters The parameters to filter the transcript list by, or the URL to retrieve the transcript list from.
465
401
  */
466
- list(parameters) {
467
- return __awaiter(this, void 0, void 0, function* () {
468
- let url = "/v2/transcript";
469
- if (typeof parameters === "string") {
470
- url = parameters;
471
- }
472
- else if (parameters) {
473
- url = `${url}?${new URLSearchParams(Object.keys(parameters).map((key) => {
474
- var _a;
475
- return [
476
- key,
477
- ((_a = parameters[key]) === null || _a === void 0 ? void 0 : _a.toString()) || "",
478
- ];
479
- }))}`;
480
- }
481
- const data = yield this.fetchJson(url);
482
- for (const transcriptListItem of data.transcripts) {
483
- transcriptListItem.created = new Date(transcriptListItem.created);
484
- if (transcriptListItem.completed) {
485
- transcriptListItem.completed = new Date(transcriptListItem.completed);
486
- }
402
+ async list(parameters) {
403
+ let url = "/v2/transcript";
404
+ if (typeof parameters === "string") {
405
+ url = parameters;
406
+ }
407
+ else if (parameters) {
408
+ url = `${url}?${new URLSearchParams(Object.keys(parameters).map((key) => [
409
+ key,
410
+ parameters[key]?.toString() || "",
411
+ ]))}`;
412
+ }
413
+ const data = await this.fetchJson(url);
414
+ for (const transcriptListItem of data.transcripts) {
415
+ transcriptListItem.created = new Date(transcriptListItem.created);
416
+ if (transcriptListItem.completed) {
417
+ transcriptListItem.completed = new Date(transcriptListItem.completed);
487
418
  }
488
- return data;
489
- });
419
+ }
420
+ return data;
490
421
  }
491
422
  /**
492
423
  * Delete a transcript
@@ -530,17 +461,15 @@ class TranscriptService extends BaseService {
530
461
  * @param chars_per_caption The maximum number of characters per caption.
531
462
  * @return A promise that resolves to the subtitles text.
532
463
  */
533
- subtitles(id, format = "srt", chars_per_caption) {
534
- return __awaiter(this, void 0, void 0, function* () {
535
- let url = `/v2/transcript/${id}/${format}`;
536
- if (chars_per_caption) {
537
- const params = new URLSearchParams();
538
- params.set("chars_per_caption", chars_per_caption.toString());
539
- url += `?${params.toString()}`;
540
- }
541
- const response = yield this.fetch(url);
542
- return yield response.text();
543
- });
464
+ async subtitles(id, format = "srt", chars_per_caption) {
465
+ let url = `/v2/transcript/${id}/${format}`;
466
+ if (chars_per_caption) {
467
+ const params = new URLSearchParams();
468
+ params.set("chars_per_caption", chars_per_caption.toString());
469
+ url += `?${params.toString()}`;
470
+ }
471
+ const response = await this.fetch(url);
472
+ return await response.text();
544
473
  }
545
474
  /**
546
475
  * Retrieve redactions of a transcript.
@@ -560,34 +489,34 @@ function getPath(path) {
560
489
  else
561
490
  return null;
562
491
  }
563
- catch (_a) {
492
+ catch {
564
493
  return path;
565
494
  }
566
495
  }
567
496
 
497
+ const readFile = async (path) => Bun.file(path).stream();
498
+
568
499
  class FileService extends BaseService {
569
500
  /**
570
501
  * Upload a local file to AssemblyAI.
571
502
  * @param input The local file path to upload, or a stream or buffer of the file to upload.
572
503
  * @return A promise that resolves to the uploaded file URL.
573
504
  */
574
- upload(input) {
575
- return __awaiter(this, void 0, void 0, function* () {
576
- let fileData;
577
- if (typeof input === "string")
578
- fileData = fs.createReadStream(input);
579
- else
580
- fileData = input;
581
- const data = yield this.fetchJson("/v2/upload", {
582
- method: "POST",
583
- body: fileData,
584
- headers: {
585
- "Content-Type": "application/octet-stream",
586
- },
587
- duplex: "half",
588
- });
589
- return data.upload_url;
505
+ async upload(input) {
506
+ let fileData;
507
+ if (typeof input === "string")
508
+ fileData = await readFile(input);
509
+ else
510
+ fileData = input;
511
+ const data = await this.fetchJson("/v2/upload", {
512
+ method: "POST",
513
+ body: fileData,
514
+ headers: {
515
+ "Content-Type": "application/octet-stream",
516
+ },
517
+ duplex: "half",
590
518
  });
519
+ return data.upload_url;
591
520
  }
592
521
  }
593
522