testaugnitoambientsdk2 2.1.3 → 2.1.4

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.
@@ -1 +1 @@
1
- function e(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class t{constructor(e){Object.defineProperty(this,"_config",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"wssBaseURL",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onMetaEvent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.wssBaseURL=`wss://${e.server}/ambient/v1/stream-job`}prepareWSSURL(e,t,n,r){let i=this.wssBaseURL;return i+=`?filetype=${e}`,i+=`&noteparams=${t}`,i+=`&subscriptioncode=${this._config.subscriptionCode}`,i+=`&accesskey=${this._config.accessKey}`,i+=`&usertag=${this._config.userTag}`,n&&""!==n&&(i+=`&filename=${n}`),r&&""!==r&&(i+=`&jobid=${r}`),i}}class n{constructor(){}static get Against(){return n.instance||(n.instance=new n),n.instance}NullOrUndefined(e,t){if(null===e)throw new TypeError(`${t} is null`);if(void 0===e)throw new TypeError(`${t} is undefined`);return e}NullOrEmpty(e,t){if(!(e=n.Against.NullOrUndefined(e,t)))throw new TypeError(`${t} is empty`);return e}}var r,i,o,s,a;!function(e){e[e.SPECIALITY=1]="SPECIALITY",e[e.VISIT_TYPE=2]="VISIT_TYPE",e[e.NOTE_TYPE=3]="NOTE_TYPE",e[e.CLINICAL_CODE=4]="CLINICAL_CODE",e[e.LANGUAGE=5]="LANGUAGE"}(r||(r={})),function(e){e[e.SoapNote=1]="SoapNote",e[e.PatientNote=2]="PatientNote",e[e.ReferralNote=3]="ReferralNote",e[e.ConsultationSummary=4]="ConsultationSummary",e[e.CDISuggestions=102]="CDISuggestions"}(i||(i={})),function(e){e.AUTH01="AUTH01",e.AUTH02="AUTH02",e.WSAUTH01="WSAUTH01",e.WSAUTH02="WSAUTH02",e.WSAUTH03="WSAUTH03",e.WSAUTH04="WSAUTH04",e.WSJOB01="WSJOB01",e.WSJOB02="WSJOB02",e.WSJOB03="WSJOB03",e.WSJOB04="WSJOB04",e.WSJOB05="WSJOB05",e.WSACC01="WSACC01",e.WSAUD01="WSAUD01",e.SDK01="SDK01",e.SDK02="SDK02",e.SDK03="SDK03",e.SDK04="SDK04",e.SDK05="SDK05",e.SDK06="SDK06",e.SDK07="SDK07",e.SDK08="SDK08",e.SDK11="SDK11",e.ERRUNKNOWN="ERRUNKNOWN"}(o||(o={}));class u extends Error{constructor(e,t){super(e),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=t,this.name="HttpCodedError",Object.setPrototypeOf(this,u.prototype)}}!function(e){e.Detailed="Detailed",e.Consise="Consise"}(s||(s={})),function(e){e.DashFormat="Dash-format",e.Paragraph="Paragraph"}(a||(a={}));class c{makePostRequest(t,n){return e(this,void 0,void 0,(function*(){try{const r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const t=yield r.text();var e=JSON.parse(t);throw new u(e.message,e.code.toString())}return yield r.json()}catch(e){throw e}}))}makePatchRequest(t,n){return e(this,void 0,void 0,(function*(){try{const r=yield fetch(t,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const t=yield r.text();var e=JSON.parse(t);throw new u(e.message,r.status.toString())}return yield r.json()}catch(e){throw e instanceof u?e:new u("500",e.message||"Unexpected error")}}))}}class l extends c{constructor(e){super(),Object.defineProperty(this,"_config",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"_baseUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._baseUrl=`https://${e.server}/ambient/v1`}getURL(e){return`${this._baseUrl}${e}`}GetNoteParams(){return e(this,void 0,void 0,(function*(){const e=this.getURL("/note-params"),t={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag};return yield this.makePostRequest(e,t)}))}ListJobs(t,r){return e(this,void 0,void 0,(function*(){n.Against.NullOrEmpty(t,"Page Size");const e=this.getURL("/list-jobs"),i={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,PageSize:t,PageID:r};return yield this.makePostRequest(e,i)}))}FetchJob(t){return e(this,void 0,void 0,(function*(){n.Against.NullOrEmpty(t,"Job Id");const e=this.getURL("/fetch-job"),r={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t};return yield this.makePostRequest(e,r)}))}SendFinalNote(t,r){return e(this,void 0,void 0,(function*(){n.Against.NullOrEmpty(t,"Job Id"),n.Against.NullOrEmpty(r,"Note Data");const e=this.getURL("/send-final-note"),i={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t,SoapData:r};return yield this.makePostRequest(e,i)}))}DeleteNotes(t){return e(this,void 0,void 0,(function*(){n.Against.NullOrEmpty(t,"Job Id");const e=this.getURL("/delete-job"),r={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobIDs:t};return yield this.makePostRequest(e,r)}))}RenameNoteTitle(t,r){return e(this,void 0,void 0,(function*(){n.Against.NullOrEmpty(t,"Job Id"),n.Against.NullOrEmpty(r,"Job Name");const e=this.getURL("/rename-job"),i={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t,JobName:r};return yield this.makePostRequest(e,i)}))}DownloadNotePDF(t,r,i,o,s,a){return e(this,void 0,void 0,(function*(){n.Against.NullOrEmpty(t,"Job Id");const e=this.getURL("/download-pdf");var u=s;u&&""!=u||(u='{"PatientName":"","PatientID":"","Age":"","Gender":"","ReceivingDoctor":"","DoctorName":"","DoctorDesignation":"","DoctorEmail":""}');const c={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t,NoteType:r,Language:null!=o?o:"English",SpecialityID:i,Regenerate:null!=a&&a,PersonnelInfo:u};return yield this.makePostRequest(e,c)}))}EndJob(t){return e(this,void 0,void 0,(function*(){n.Against.NullOrEmpty(t,"Job Id");const e=this.getURL("/end-job"),r={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t};return yield this.makePostRequest(e,r)}))}UpdatePatientContext(t,r,i){return e(this,void 0,void 0,(function*(){n.Against.NullOrEmpty(t,"Job Id"),n.Against.NullOrEmpty(r,"Patient Context");const e=this.getURL("/patient-context"),o={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t,NewContext:r,Replace:i};return yield this.makePostRequest(e,o)}))}GenerateSuggestions(t,r,i,o,s){return e(this,void 0,void 0,(function*(){n.Against.NullOrEmpty(t,"Job Id");const e=this.getURL("/cdi"),a={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t,Regenerate:r,SoapData:i,PatientContext:o,Codes:s};return yield this.makePostRequest(e,a)}))}ModifyGeneratedNote(t,r,i){return e(this,void 0,void 0,(function*(){n.Against.NullOrEmpty(t,"Job Id");const e=this.getURL("/modify-note"),o={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t,NoteType:r,NewNote:null!=i?i:""};return yield this.makePostRequest(e,o)}))}FetchTranscription(t){return e(this,void 0,void 0,(function*(){n.Against.NullOrEmpty(t,"Job Id");const e=this.getURL("/fetch-transcript"),r={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t};return yield this.makePostRequest(e,r)}))}}class h{static log(e,t){const n=null!=t?t:this.defaultTag;console.log(`${n}:`,e)}static error(e,t){const n=null!=t?t:this.defaultTag;console.error(`${n}:`,e)}}function d(){d=function(){return t};var e,t={},n=Object.prototype,r=n.hasOwnProperty,i=Object.defineProperty||function(e,t,n){e[t]=n.value},o="function"==typeof Symbol?Symbol:{},s=o.iterator||"@@iterator",a=o.asyncIterator||"@@asyncIterator",u=o.toStringTag||"@@toStringTag";function c(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,n){return e[t]=n}}function l(e,t,n,r){var o=t&&t.prototype instanceof y?t:y,s=Object.create(o.prototype),a=new D(r||[]);return i(s,"_invoke",{value:R(e,n,a)}),s}function h(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var f="suspendedStart",g="suspendedYield",p="executing",v="completed",b={};function y(){}function m(){}function S(){}var E={};c(E,s,(function(){return this}));var k=Object.getPrototypeOf,C=k&&k(k(N([])));C&&C!==n&&r.call(C,s)&&(E=C);var A=S.prototype=y.prototype=Object.create(E);function I(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function w(e,t){function n(i,o,s,a){var u=h(e[i],e,o);if("throw"!==u.type){var c=u.arg,l=c.value;return l&&"object"==typeof l&&r.call(l,"__await")?t.resolve(l.__await).then((function(e){n("next",e,s,a)}),(function(e){n("throw",e,s,a)})):t.resolve(l).then((function(e){c.value=e,s(c)}),(function(e){return n("throw",e,s,a)}))}a(u.arg)}var o;i(this,"_invoke",{value:function(e,r){function i(){return new t((function(t,i){n(e,r,t,i)}))}return o=o?o.then(i,i):i()}})}function R(t,n,r){var i=f;return function(o,s){if(i===p)throw Error("Generator is already running");if(i===v){if("throw"===o)throw s;return{value:e,done:!0}}for(r.method=o,r.arg=s;;){var a=r.delegate;if(a){var u=P(a,r);if(u){if(u===b)continue;return u}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(i===f)throw i=v,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);i=p;var c=h(t,n,r);if("normal"===c.type){if(i=r.done?v:g,c.arg===b)continue;return{value:c.arg,done:r.done}}"throw"===c.type&&(i=v,r.method="throw",r.arg=c.arg)}}}function P(t,n){var r=n.method,i=t.iterator[r];if(i===e)return n.delegate=null,"throw"===r&&t.iterator.return&&(n.method="return",n.arg=e,P(t,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),b;var o=h(i,t.iterator,n.arg);if("throw"===o.type)return n.method="throw",n.arg=o.arg,n.delegate=null,b;var s=o.arg;return s?s.done?(n[t.resultName]=s.value,n.next=t.nextLoc,"return"!==n.method&&(n.method="next",n.arg=e),n.delegate=null,b):s:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,b)}function T(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function O(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function D(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(T,this),this.reset(!0)}function N(t){if(t||""===t){var n=t[s];if(n)return n.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var i=-1,o=function n(){for(;++i<t.length;)if(r.call(t,i))return n.value=t[i],n.done=!1,n;return n.value=e,n.done=!0,n};return o.next=o}}throw new TypeError(typeof t+" is not iterable")}return m.prototype=S,i(A,"constructor",{value:S,configurable:!0}),i(S,"constructor",{value:m,configurable:!0}),m.displayName=c(S,u,"GeneratorFunction"),t.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===m||"GeneratorFunction"===(t.displayName||t.name))},t.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,S):(e.__proto__=S,c(e,u,"GeneratorFunction")),e.prototype=Object.create(A),e},t.awrap=function(e){return{__await:e}},I(w.prototype),c(w.prototype,a,(function(){return this})),t.AsyncIterator=w,t.async=function(e,n,r,i,o){void 0===o&&(o=Promise);var s=new w(l(e,n,r,i),o);return t.isGeneratorFunction(n)?s:s.next().then((function(e){return e.done?e.value:s.next()}))},I(A),c(A,u,"Generator"),c(A,s,(function(){return this})),c(A,"toString",(function(){return"[object Generator]"})),t.keys=function(e){var t=Object(e),n=[];for(var r in t)n.push(r);return n.reverse(),function e(){for(;n.length;){var r=n.pop();if(r in t)return e.value=r,e.done=!1,e}return e.done=!0,e}},t.values=N,D.prototype={constructor:D,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=e,this.done=!1,this.delegate=null,this.method="next",this.arg=e,this.tryEntries.forEach(O),!t)for(var n in this)"t"===n.charAt(0)&&r.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=e)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var n=this;function i(r,i){return a.type="throw",a.arg=t,n.next=r,i&&(n.method="next",n.arg=e),!!i}for(var o=this.tryEntries.length-1;o>=0;--o){var s=this.tryEntries[o],a=s.completion;if("root"===s.tryLoc)return i("end");if(s.tryLoc<=this.prev){var u=r.call(s,"catchLoc"),c=r.call(s,"finallyLoc");if(u&&c){if(this.prev<s.catchLoc)return i(s.catchLoc,!0);if(this.prev<s.finallyLoc)return i(s.finallyLoc)}else if(u){if(this.prev<s.catchLoc)return i(s.catchLoc,!0)}else{if(!c)throw Error("try statement without catch or finally");if(this.prev<s.finallyLoc)return i(s.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var i=this.tryEntries[n];if(i.tryLoc<=this.prev&&r.call(i,"finallyLoc")&&this.prev<i.finallyLoc){var o=i;break}}o&&("break"===e||"continue"===e)&&o.tryLoc<=t&&t<=o.finallyLoc&&(o=null);var s=o?o.completion:{};return s.type=e,s.arg=t,o?(this.method="next",this.next=o.finallyLoc,b):this.complete(s)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),b},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),O(n),b}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var i=r.arg;O(n)}return i}}throw Error("illegal catch attempt")},delegateYield:function(t,n,r){return this.delegate={iterator:N(t),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=e),b}},t}function f(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function g(e,t,n,r,i,o,s){try{var a=e[o](s),u=a.value}catch(e){return void n(e)}a.done?t(u):Promise.resolve(u).then(r,i)}function p(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var o=e.apply(t,n);function s(e){g(o,r,i,s,a,"next",e)}function a(e){g(o,r,i,s,a,"throw",e)}s(void 0)}))}}function v(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function b(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,f(r.key),r)}}function y(e,t,n){return t&&b(e.prototype,t),n&&b(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function m(e,t,n){return(t=f(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(h,"defaultTag",{enumerable:!0,configurable:!0,writable:!0,value:"AugnitoAmbientSDK"});var S="DONE",E="PAUSESOCKET",k="RESUMESOCKET",C="CLOSE",A=12e4,I=y((function e(t,n,r,i,o,s,a,u,c,l,h,d){v(this,e),this.worker,this.onFinalResultCallback=o,this.onErrorCallback=a,this.onPartialResultCallback=s,this.onSessionEventCallback=u,this.onOtherResultsCallback=c,this.onSpeechResponseCallback=l,this.packetSeqId=0,this.audioDuration=0,this.shouldSendAudioDataSequence=i,this.heavyOp,this.idleLoop,this.lastSent,this.enableLogs=t,this.eosMessage=n||"EOS",this.socketTimeoutInterval=r||1e4,this.bufferSizeInterval=h,this.switchToRegularSpeech=d}),[{key:"Start",value:function(e,t){var n=this;this.audioDuration=e;var r="\n (() => {\n (".concat(w.toString(),")(").concat(JSON.stringify(S),", ").concat(JSON.stringify(this.eosMessage),", ").concat(JSON.stringify(C),", ").concat(JSON.stringify(1e4),", ").concat(JSON.stringify(this.socketTimeoutInterval),", ").concat(JSON.stringify(1e3),", ").concat(JSON.stringify(100),", ").concat(JSON.stringify(t),", ").concat(JSON.stringify(this.enableLogs),", ").concat(JSON.stringify(this.shouldSendAudioDataSequence),",").concat(JSON.stringify(E),", ").concat(JSON.stringify(k),", ").concat(JSON.stringify(this.switchToRegularSpeech),", ").concat(JSON.stringify(this.heavyOp),");\n })();\n");this.worker=new Worker(URL.createObjectURL(new Blob([r],{type:"application/javascript"}))),this.worker.onmessage=function(e){n.enableLogs&&console.log("Augnito [MAIN]: "+JSON.stringify(e.data));var t=e.data;"final"==t.type?n.onFinalResultCallback(t.data):"partial"==t.type?n.onPartialResultCallback(t.data):"meta"==t.type?n.onSessionEventCallback(t.data):"error"==t.type?n.onErrorCallback(t.data):"other"==t.type?n.onOtherResultsCallback(t.data):"speechResponse"==t.type&&n.onSpeechResponseCallback(t.data)},this.idleLoop=setInterval((function(){var e=+new Date;n.lastSent&&e-n.lastSent>A&&(n.Send(n.eosMessage),n.enableLogs&&console.warn("No data sent since more than ".concat(120," secs, closing time...")))}),1e4)}},{key:"createAudioPacketHeader",value:function(e){this.audioDuration>0&&(this.packetSeqId=Math.ceil(this.audioDuration/this.bufferSizeInterval)+2,this.audioDuration=0),this.packetSeqId++;for(var t=new ArrayBuffer(16),n=new DataView(t),r=0;r<4;r++)n.setUint8(r,"@BSR".charCodeAt(r));return n.setBigInt64(4,BigInt(this.packetSeqId),!1),n.setUint8(12,e?1:0),t}},{key:"appendAudioData",value:function(e,t){var n=e.byteLength+t.byteLength,r=new ArrayBuffer(n),i=new Uint8Array(r);return i.set(new Uint8Array(e),0),i.set(new Uint8Array(t),e.byteLength),r}},{key:"Send",value:function(e){var t;if(this.lastSent=+new Date,e===C)null===(t=this.worker)||void 0===t||t.postMessage(C),clearInterval(this.idleLoop);else if(e===S){if(this.shouldSendAudioDataSequence){var n,r=this.createAudioPacketHeader(!0);null===(n=this.worker)||void 0===n||n.postMessage(r)}else{var i;null===(i=this.worker)||void 0===i||i.postMessage(S)}clearInterval(this.idleLoop)}else if(e==E){var o;null===(o=this.worker)||void 0===o||o.postMessage(E)}else if(e==k){var s;null===(s=this.worker)||void 0===s||s.postMessage(k)}else if(e===this.eosMessage){var a;this.shouldSendAudioDataSequence||null===(a=this.worker)||void 0===a||a.postMessage(e)}else{var u,c=[];this.shouldSendAudioDataSequence?(r=this.createAudioPacketHeader(!1),c=this.appendAudioData(r,e)):c=e,void 0!==c&&(null===(u=this.worker)||void 0===u||u.postMessage(c,[c]))}}},{key:"HeavyOp",set:function(e){this.heavyOp=e}}]);function w(e,t,n,r,i,o,s,a,u,c,l,h,d,f){var g,p,v,b,y,m,S,E,k=[],C=[],A=!1,I=!1,w=!1,R="",P=!1;function T(){g=+new Date,(m=""!=R?new WebSocket(a+"&jobid="+R):new WebSocket(a)).onopen=function(e){u&&console.log("Augnito: WebSocket connection established - "+JSON.stringify(e)),C.length>0&&(I=!0)},m.onmessage=function(e){u&&console.log("Augnito: Message from server - "+JSON.stringify(e.data)),v=+new Date,function(e){try{if("PING"===e.data)b=+new Date,self.postMessage({type:"ping",data:e.data});else{var t=JSON.parse(e.data);if(u&&console.log("Augnito [WORKER]: "+JSON.stringify(t)),"meta"==t.Type){t.JobID&&(R=t.JobID,console.log("Augnito JobID:",R)),self.postMessage({type:"meta",data:e.data});var n=JSON.parse(e.data);w=!(!n.Event||"INVALID_AUTH_CREDENTIALS"!==n.Event.Type)}else if(t.Result&&t.Result.Final){var r=JSON.stringify(t.Result);f&&(r=f(JSON.stringify(t.Result)),console.log(r)),self.postMessage({type:"final",data:r})}else t.Result&&!t.Result.Final?self.postMessage({type:"partial",data:t.Result.Transcript}):"ACK"==t.Type?(C=C.filter((function(e){return e.packetNumber>t.Index})),self.postMessage({type:"other",data:e.data})):"ERROR"==t.Type?("Timeout exceeded"==t.Data&&(A=!0,N()),self.postMessage({type:"error",data:e.data})):self.postMessage({type:"speechResponse",data:e.data})}}catch(e){self.postMessage({type:"error",data:"invalid response"})}}(e)},m.onerror=function(e){console.error("WebSocket error: ",e),self.postMessage({type:"error",data:JSON.stringify(e)})},m.onclose=function(e){u&&console.log("Augnito: WebSocket connection closed - "+JSON.stringify(e)),N()},p=+new Date,v=p,b=+new Date}function O(e){if(m&&m.readyState===WebSocket.OPEN){m.send(e);var n=+new Date;return p<=v&&(v=n-1),p=n,!0}return e===t?(u&&console.warn("Gulping ".concat(t," as socket seems already closed...")),N(),!0):(+new Date-g>r&&!w&&T(),!1)}function D(e){k.push(e)}function N(){A&&(clearInterval(S),clearInterval(E),k=[],C=[],self.close())}T(),S=setInterval((function(){if(I){for(var e=0;e<C.length;e++){if(!O(C[e].packetData))break}I=!1}else for(;k.length>0;){var t=k.shift();if(!O(t)){k.unshift(t);break}if(c){var n=new DataView(t),r={packetNumber:Number(n.getBigInt64(4)),packetData:t};C.push(r)}}}),s),E=setInterval((function(){if(m&&m.readyState===WebSocket.OPEN){var e=+new Date;(d?p>v&&e-v>i:e-b>i)&&(u&&console.error("No data received since more than ".concat(i/1e3," secs, closing time...")),m.close())}}),o),self.onmessage=function(r){r.data===n?(R="",A=!0,w=!0,m.close()):r.data===e?(D(t),R="",u&&console.log("Augnito: Worker received DONE, time to terminate..."),A=!0):r.data===l?P=!0:r.data===h?(D(y),P=!1,y=[]):P?y=r.data:D(r.data)}}var R,P,T,O,D,N,_,x,U,L=y((function e(t,n,r,i,o,s,a,u,c,l,h,d,f,g,p,b,y,m,S){v(this,e),this.audioContext,this.audioStream,this.executor=new I(t,o,s,a,d,f,g,b,y,m,r,l),this.executor.HeavyOp=h,this.source,this.processorNode,this.isPaused=!1,this.isStreaming=!1,this.audioData=[],this.isDebug=n,this.enableLogs=t,this.onStateChanged=p,this.onIntensity=S,this.onError=g,this.bufferSizeInterval=r,this.pausedBufferInterval=null!=i?i:1,this.shouldReadIntensity=c,this.closeSocketWithoutEOS=!1,this.shouldPreIntialiseRecorder=null!=u&&u,this.shouldPreIntialiseRecorder&&this.EarlyInitialiseMediaStream()}),[{key:"EarlyInitialiseMediaStream",value:(U=p(d().mark((function e(){return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.createMediaStreamSourceNode();case 2:if(!this.audioContext||"running"!=this.audioContext.state){e.next=5;break}return e.next=5,this.audioContext.suspend();case 5:case"end":return e.stop()}}),e,this)}))),function(){return U.apply(this,arguments)})},{key:"StartStream",value:(x=p(d().mark((function e(t,n){return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.log("New stream started..."),this.shouldPreIntialiseRecorder&&this.source){e.next=9;break}return e.next=4,this.createMediaStreamSourceNode();case 4:if(this.source){e.next=7;break}return console.error("Error: unable to create source node"),e.abrupt("return",!1);case 7:e.next=12;break;case 9:if("suspended"!=this.audioContext.state){e.next=12;break}return e.next=12,this.audioContext.resume();case 12:return e.next=14,this.createProcessorNode();case 14:if(this.processorNode){e.next=17;break}return console.error("Error: unable to create processor node"),e.abrupt("return",!1);case 17:if(!this.IsMicrophoneMuted){e.next=23;break}if(!this.audioContext||"running"!=this.audioContext.state){e.next=21;break}return e.next=21,this.audioContext.suspend();case 21:return this.onError(JSON.stringify({Type:"ERROR",Data:"Microphone is muted."})),e.abrupt("return",!1);case 23:return""!==n&&this.executor.Start(t,n),this.onStateChanged(!0),this.source.connect(this.processorNode).connect(this.audioContext.destination),this.log("AudioContext Sample Rate: "+this.audioContext.sampleRate),this.isStreaming=!0,e.abrupt("return",!0);case 29:case"end":return e.stop()}}),e,this)}))),function(e,t){return x.apply(this,arguments)})},{key:"createBufferedSourceNode",value:(_=p(d().mark((function e(){var t;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.loadAudio();case 2:if(t=e.sent){e.next=6;break}return console.error("Error: unable to create audio buffer"),e.abrupt("return");case 6:this.source=this.audioContext.createBufferSource(),this.source.buffer=t,this.source.loop=!0,this.source.start();case 10:case"end":return e.stop()}}),e,this)}))),function(){return _.apply(this,arguments)})},{key:"createMediaStreamSourceNode",value:(N=p(d().mark((function e(){var t,n=this;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,navigator.mediaDevices.getUserMedia({audio:{channelCount:1,noiseSuppression:!1}});case 3:this.audioStream=e.sent,this.audioContext=new AudioContext,this.source=this.audioContext.createMediaStreamSource(this.audioStream),this.audioStream.getAudioTracks()[0].addEventListener("ended",(function(){n.onError(JSON.stringify({Type:"ERROR",Data:"Audio track ended. Possibly the mic was unplugged."}))})),e.next=14;break;case 9:e.prev=9,e.t0=e.catch(0),t="","NotAllowedError"==e.t0.name?t="Mic permission denied":"NotFoundError"===e.t0.name&&(t="No suitable media device found"),this.onError(JSON.stringify({Type:"ERROR",Data:t}));case 14:case"end":return e.stop()}}),e,this,[[0,9]])}))),function(){return N.apply(this,arguments)})},{key:"loadAudio",value:(D=p(d().mark((function e(){var t,n,r;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,fetch("./radiology_speed_test.wav");case 3:return t=e.sent,e.next=6,t.arrayBuffer();case 6:return n=e.sent,e.next=9,this.audioContext.decodeAudioData(n);case 9:return r=e.sent,e.abrupt("return",r);case 13:return e.prev=13,e.t0=e.catch(0),console.error("Unable to fetch the audio file. Error: ".concat(e.t0.message)),e.abrupt("return",null);case 17:case"end":return e.stop()}}),e,this,[[0,13]])}))),function(){return D.apply(this,arguments)})},{key:"createProcessorNode",value:(O=p(d().mark((function e(){var t,n=this;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.audioContext.audioWorklet.addModule("data:application/javascript,".concat(encodeURIComponent('class MyAudioWorkletProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.accumulator = [];\n this.pauseSocketStreaming = false;\n this.sampleVal = 0;\n this.sampleSize = 0;\n this.intensityFrameCount = 0;\n this.reset();\n this.isProcessing = true;\n // message received from main-thread\n this.port.onmessage = (e) => {\n console.log("Augnito: Worklet received event - ", e.data);\n if (this.sampleSize > 0) {\n this.accumulator.push(this.sampleVal / this.sampleSize);\n }\n \n if (e.data == "PAUSE" || e.data == "STOP" || e.data == "PAUSESOCKET") {\n // append silence to get last word ASR.\n const silenceSize = 16000 * 2;\n for (let i = 0; i < silenceSize; i++) {\n this.accumulator.push(0);\n }\n }\n this.send();\n this.reset();\n if (e.data == "STOP") {\n // message sent to main-thread\n this.port.postMessage({type:"DONE", value:"DONE"});\n this.isProcessing = false;\n \n }\n if(e.data == "PAUSESOCKET"){\n this.pauseSocketStreaming = true;\n this.port.postMessage("PAUSESOCKET");\n } else if(e.data == "RESUMESOCKET"){\n this.pauseSocketStreaming = false;\n } \n };\n }\n\n static get parameterDescriptors() {\n return [\n {\n name: "sampleRate",\n defaultValue: 16000,\n minValue: 16000,\n maxValue: 6 * 16000,\n },\n {\n name: "bufferSizeInterval",\n defaultValue: 1,\n minValue: 1,\n maxValue: 100,\n },\n {\n name: "pausedBufferInterval",\n defaultValue: 1,\n minValue: 0,\n maxValue: 100,\n },\n {\n name: "shouldReadIntensity",\n defaultValue: false,\n minValue: 0,\n maxValue: 1,\n },\n ];\n }\n\n // 128 frames\n process(inputList, outputList, params) {\n const input = inputList[0];\n if (input && input.length && input[0].length) {\n const channelData = input[0];\n const output = outputList[0];\n const inputSampleRate = params.sampleRate[0];\n const sampleRatio = inputSampleRate / 16000\n const bufferSizeInterval = params["bufferSizeInterval"][0];\n const pausedBufferInterval = params["pausedBufferInterval"][0];\n const shouldReadIntensity = params["shouldReadIntensity"][0];\n\n let sumSquares = 0; // For intensity\n let sampleCount = 0;\n\n // console.log("BufferSizeInterval", bufferSizeInterval);\n // Jackpot\n input[0].forEach((float32Element, index) => {\n const int16Element = Math.min(1, Math.max(-1, float32Element)) * 0x7fff;\n this.sampleVal += int16Element;\n this.sampleSize += 1;\n // Accumulate for intensity (RMS)\n sumSquares += float32Element * float32Element;\n sampleCount++;\n \n\n if (this.sampleSize >= sampleRatio) {\n const fraction = this.sampleSize - sampleRatio \n this.sampleVal -= fraction * int16Element;\n\n this.accumulator.push(this.sampleVal / sampleRatio);\n \n this.sampleVal = fraction * int16Element;\n this.sampleSize = fraction;\n }\n\n // Comment this when streaming microphone audio\n // output[0][index] = float32Element;\n });\n if(this.pauseSocketStreaming){\n if (this.accumulator.length >= 125 * 128 * pausedBufferInterval) {\n this.send();\n }\n } else{\n if (this.accumulator.length >= 125 * 128 * bufferSizeInterval) {\n this.send();\n }\n }\n if(shouldReadIntensity){\n \n // Throttled intensity post\n this.intensityFrameCount = (this.intensityFrameCount || 0) + 1;\n if (this.intensityFrameCount >= 15 && sampleCount > 0) {\n const rms = Math.sqrt(sumSquares / sampleCount);\n const normalized = Math.min(1, rms); // [0–1] scale\n this.port.postMessage({ type: \'intensity\', value: normalized });\n this.intensityFrameCount = 0;\n }\n }\n }\n return this.isProcessing;\n }\n\n send() {\n if (this.accumulator.length == 0) return;\n const audioData = new Int16Array(this.accumulator);\n // message sent to main-thread - transferrable\n this.port.postMessage({ type: \'audioData\', value: audioData.buffer }, [audioData.buffer]);\n this.accumulator = [];\n }\n\n reset() {\n this.sampleVal = 0;\n this.sampleSize = 0;\n }\n}\n\nregisterProcessor("worklet-processor", MyAudioWorkletProcessor);')));case 3:this.processorNode=new AudioWorkletNode(this.audioContext,"worklet-processor"),this.processorNode.parameters.get("sampleRate").setValueAtTime(this.audioContext.sampleRate,this.audioContext.currentTime),this.processorNode.parameters.get("bufferSizeInterval").setValueAtTime(this.bufferSizeInterval,this.audioContext.currentTime),this.processorNode.parameters.get("pausedBufferInterval").setValueAtTime(this.pausedBufferInterval,this.audioContext.currentTime),this.processorNode.parameters.get("shouldReadIntensity").setValueAtTime(null!==(t=this.shouldReadIntensity)&&void 0!==t&&t,this.audioContext.currentTime),this.processorNode.port.onmessage=function(e){var t=e.data,r=t.type,i=t.value;if(r==S)n.log("Worklet processing done, clearing resources..."),n.isDebug&&n.saveAudio(),n.cleanup();else if(e.data==E)n.executor.Send(E);else{var o;"intensity"===r?null===(o=n.onIntensity)||void 0===o||o.call(n,i):"audioData"===r&&n.isDebug&&new Int16Array(i).forEach((function(e){n.audioData.length<=288e5&&n.audioData.push(e)}))}n.executor&&(n.closeSocketWithoutEOS?(n.executor.Send(C),n.closeSocketWithoutEOS=!1):"intensity"!==r&&n.executor.Send(i))},e.next=18;break;case 15:e.prev=15,e.t0=e.catch(0),console.error("Error: Unable to create worklet node: ",e.t0);case 18:case"end":return e.stop()}}),e,this,[[0,15]])}))),function(){return O.apply(this,arguments)})},{key:"PauseStream",value:(T=p(d().mark((function e(){return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("running"!=this.audioContext.state){e.next=10;break}if(this.shouldPreIntialiseRecorder){e.next=9;break}return e.next=4,this.audioContext.suspend();case 4:this.onStateChanged(!1),this.log("Stream paused..."),this.processorNode.port.postMessage("PAUSE"),e.next=10;break;case 9:this.processorNode.port.postMessage(E);case 10:this.isPaused=!0,this.isStreaming=!1;case 12:case"end":return e.stop()}}),e,this)}))),function(){return T.apply(this,arguments)})},{key:"ResumeStream",value:(P=p(d().mark((function e(){return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.shouldPreIntialiseRecorder||"suspended"!=this.audioContext.state){e.next=9;break}if(!this.IsMicrophoneMuted){e.next=4;break}return this.onError(JSON.stringify({Type:"ERROR",Data:"Microphone is muted."})),e.abrupt("return");case 4:return e.next=6,this.audioContext.resume();case 6:this.log("Stream resumed..."),e.next=11;break;case 9:this.processorNode.port.postMessage(k),this.executor.Send(k);case 11:this.onStateChanged(!0),this.isPaused=!1,this.isStreaming=!0;case 14:case"end":return e.stop()}}),e,this)}))),function(){return P.apply(this,arguments)})},{key:"IsPaused",get:function(){return this.isPaused}},{key:"IsStreaming",get:function(){return this.isStreaming}},{key:"IsMicrophoneMuted",get:function(){return this.audioStream.getAudioTracks()[0].muted}},{key:"StopStream",value:(R=p(d().mark((function e(t){var n,r,i,o;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("suspended"===(null===(n=this.audioContext)||void 0===n?void 0:n.state)){e.next=4;break}return e.next=3,null===(o=this.audioContext)||void 0===o?void 0:o.suspend();case 3:this.onStateChanged(!1);case 4:this.log("Stream stopped..."),this.isStreaming=!1,this.closeSocketWithoutEOS=!t,null===(r=this.processorNode)||void 0===r||null===(r=r.port)||void 0===r||r.postMessage("STOP"),null===(i=this.audioStream)||void 0===i||i.getAudioTracks()[0].removeEventListener("ended",(function(){}));case 9:case"end":return e.stop()}}),e,this)}))),function(e){return R.apply(this,arguments)})},{key:"cleanup",value:function(){this.source.mediaStream.getAudioTracks()[0].stop(),this.source.disconnect(),this.processorNode.disconnect(),this.processorNode.port.close(),this.audioContext.close(),this.audioData=[]}},{key:"saveAudio",value:function(){var e=this.encodeWAV(),t=URL.createObjectURL(new Blob([e],{type:"audio/wav"}));this.log("Download Recording: ".concat(t))}},{key:"getBlob",value:function(){var e=this.encodeWAV();console.log(e);var t=new Blob([e],{type:"audio/wav"});return console.log(t),t}},{key:"encodeWAV",value:function(){var e=new DataView(new ArrayBuffer(2*this.audioData.length));this.audioData.forEach((function(t,n){e.setInt16(2*n,t,!0)}));var t=e.buffer.byteLength,n=44+t,r=new DataView(new ArrayBuffer(n));r.setUint32(0,1380533830,!1),r.setUint32(4,n-8,!0),r.setUint32(8,1463899717,!1),r.setUint32(12,1718449184,!1),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,1,!0),r.setUint32(24,16e3,!0),r.setUint32(28,32e3,!0),r.setUint16(32,2,!0),r.setUint16(34,16,!0),r.setUint32(36,1684108385,!1),r.setUint32(40,t,!0);for(var i=0;i<t;i++)r.setInt8(44+i,e.getInt8(i));return r}},{key:"log",value:function(e){if(this.enableLogs){var t="".concat((new Date).toLocaleTimeString()," Augnito: ").concat(e);console.log(t+"\n")}}}]),M=function(){function e(){v(this,e)}return y(e,null,[{key:"isBrowserOnline",value:function(){return"undefined"!=typeof navigator&&!0===navigator.onLine}},{key:"hasInternetConnection",value:(n=p(d().mark((function t(){var n,r,i,o,s,a=arguments;return d().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(r=(n=a.length>0&&void 0!==a[0]?a[0]:{}).url||e.DEFAULT_URL,i=n.timeoutMs||e.DEFAULT_TIMEOUT,e.isBrowserOnline()){t.next=5;break}return t.abrupt("return",!1);case 5:return o=new AbortController,s=setTimeout((function(){return o.abort()}),i),t.prev=7,t.next=10,fetch(r,{method:"HEAD",mode:"no-cors",cache:"no-cache",signal:o.signal});case 10:return t.abrupt("return",!0);case 13:return t.prev=13,t.t0=t.catch(7),t.abrupt("return",!1);case 16:return t.prev=16,clearTimeout(s),t.finish(16);case 19:case"end":return t.stop()}}),t,null,[[7,13,16,19]])}))),function(){return n.apply(this,arguments)})},{key:"isOnline",value:(t=p(d().mark((function t(n){return d().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.abrupt("return",e.hasInternetConnection(n));case 1:case"end":return t.stop()}}),t)}))),function(e){return t.apply(this,arguments)})}]);var t,n}();m(M,"DEFAULT_URL","https://www.google.com/favicon.ico"),m(M,"DEFAULT_TIMEOUT",5e3);var K=function(){function e(){var t,n,r,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{serverURL:"",enableLogs:!1,isDebug:!1,bufferInterval:1,pausedBufferInterval:1,EOS_Message:void 0,socketTimeoutInterval:void 0,shouldSendAudioDataSequence:!1,shouldPreIntialiseRecorder:!1,shouldReadIntensity:!1,debounceDelay:300,switchToRegularSpeechProfile:!1},o=arguments.length>1?arguments[1]:void 0;if(v(this,e),e.instance)return e.instance;this.WebsocketURL=null!==(t=i.serverURL)&&void 0!==t?t:"",this.enableLogs=i.enableLogs,this.isDebug=i.isDebug,this.streamer=null,this.streamerNotStarted=!1,this.isStreamerStarting=!1,this.heavyOp=o,this.bufferInterval=i.bufferInterval,this.pausedBufferInterval=i.pausedBufferInterval,this.eosMessage=i.EOS_Message,this.socketTimeoutInterval=i.socketTimeoutInterval,this.shouldSendAudioDataSequence=i.shouldSendAudioDataSequence,this.shouldPreIntialiseRecorder=i.shouldPreIntialiseRecorder,this.switchToRegularSpeechProfile=null!==(n=i.switchToRegularSpeechProfile)&&void 0!==n&&n,this.shouldPreIntialiseRecorder&&(this.initialiseStreamer(),this.streamerNotStarted=!0),this.shouldReadIntensity=i.shouldReadIntensity,this.delay=null!==(r=i.debounceDelay)&&void 0!==r?r:300,this.toggleStartStopAudioStream=J(this.toggleStartStopAudioStream.bind(this),this.delay),this.togglePauseResumeAudioStream=J(this.togglePauseResumeAudioStream.bind(this),this.delay),e.instance=this}return y(e,[{key:"initialiseStreamer",value:function(){this.streamer=new L(this.enableLogs,this.isDebug,this.bufferInterval,this.pausedBufferInterval,this.eosMessage,this.socketTimeoutInterval,this.shouldSendAudioDataSequence,this.shouldPreIntialiseRecorder,this.shouldReadIntensity,this.switchToRegularSpeechProfile,this.heavyOp,this.onFinalResultCallback.bind(this),this.onPartialResultCallback.bind(this),this.onErrorCallback.bind(this),this.onStateChangedCallback.bind(this),this.onSessionEventCallback.bind(this),this.onOtherResultCallback.bind(this),this.onSpeechResponseCallback.bind(this),this.onIntensityCallback.bind(this))}},{key:"togglePauseResumeAudioStream",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0;!this.streamer||this.streamerNotStarted?(t&&(this.WebsocketURL=t),this.startAudio(e)):this.streamer.IsPaused?this.resumeAudio():this.pauseAudio()}},{key:"toggleStartStopAudioStream",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0;!this.streamer||this.streamerNotStarted?(t&&(this.WebsocketURL=t),this.startAudio(e)):this.stopAudio()}},{key:"startAudio",value:(r=p(d().mark((function e(t){return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,M.isOnline();case 2:if(e.sent){e.next=6;break}return this.onErrorCallback(JSON.stringify({Type:"ERROR",Data:"Internet is not available. Try again later."})),e.abrupt("return");case 6:if(!this.isStreamerStarting){e.next=8;break}return e.abrupt("return");case 8:return this.isStreamerStarting=!0,this.shouldPreIntialiseRecorder&&this.streamer||this.initialiseStreamer(),e.prev=10,e.next=13,this.streamer.StartStream(t,this.WebsocketURL);case 13:e.sent?(this.streamerNotStarted=!1,this.log("Stream Started...")):this.streamer=null;case 15:return e.prev=15,this.isStreamerStarting=!1,e.finish(15);case 18:case"end":return e.stop()}}),e,this,[[10,,15,18]])}))),function(e){return r.apply(this,arguments)})},{key:"pauseAudio",value:function(){this.streamer.PauseStream(),this.log("Stream Paused...")}},{key:"resumeAudio",value:function(){this.streamer.ResumeStream(),this.enableLogs&&this.log("Stream Resumed...")}},{key:"stopAudio",value:(n=p(d().mark((function e(){var t,n,r,i,o=arguments;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=!(o.length>0&&void 0!==o[0])||o[0],r=o.length>1&&void 0!==o[1]&&o[1],!(null!==(t=this.streamer)&&void 0!==t&&t.IsStreaming||r)){e.next=13;break}return e.next=5,M.isOnline();case 5:if(e.sent){e.next=9;break}return this.onErrorCallback(JSON.stringify({Type:"ERROR",Data:"Internet is not available. Try again later."})),e.abrupt("return");case 9:null===(i=this.streamer)||void 0===i||i.StopStream(n),this.streamer=null,this.log("Stream Stopped..."),this.shouldPreIntialiseRecorder&&(this.initialiseStreamer(),this.streamerNotStarted=!0);case 13:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"isInternetAvailable",value:(t=p(d().mark((function e(){var t;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,M.isOnline();case 2:return t=e.sent,e.abrupt("return",t);case 4:case"end":return e.stop()}}),e)}))),function(){return t.apply(this,arguments)})},{key:"getBlob",value:function(){var e=this.streamer.getBlob();return this.log("Blob Sent..."),e}},{key:"log",value:function(e){if(this.enableLogs){var t="".concat((new Date).toLocaleTimeString()," Augnito: ").concat(e);this.showLogCallback(t+"\n")}}},{key:"dispose",value:function(){e.instance=null}},{key:"onSessionEventCallback",value:function(e){this.onSessionEvent&&this.onSessionEvent(e)}},{key:"onStateChangedCallback",value:function(e){this.onStateChanged&&this.onStateChanged(e)}},{key:"onIntensityCallback",value:function(e){this.onIntensity&&this.onIntensity(e)}},{key:"onErrorCallback",value:function(e){this.onError&&this.onError(e)}},{key:"onPartialResultCallback",value:function(e){this.onPartialResult&&this.onPartialResult(e)}},{key:"onFinalResultCallback",value:function(e){this.onFinalResult&&this.onFinalResult(e)}},{key:"onOtherResultCallback",value:function(e){this.onOtherResults&&this.onOtherResults(e)}},{key:"onSpeechResponseCallback",value:function(e){this.onSpeechResponse&&this.onSpeechResponse(e)}},{key:"showLogCallback",value:function(e){this.showLog&&this.showLog(e)}}]);var t,n,r}();function J(e,t){var n;return function(){for(var r=this,i=arguments.length,o=new Array(i),s=0;s<i;s++)o[s]=arguments[s];n&&clearTimeout(n),n=setTimeout((function(){return e.apply(r,o)}),t)}}class W extends c{constructor(e){super(),Object.defineProperty(this,"_config",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"_baseUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._baseUrl=`https://${e.server}/pace/v1/sdk`}getURL(e){return`${this._baseUrl}${e}`}getNoteParams(){return e(this,void 0,void 0,(function*(){const e=this.getURL("/noteparams"),t={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag};return yield this.makePostRequest(e,t)}))}getSettingsConfigMaster(t){return e(this,void 0,void 0,(function*(){const e=this.getURL("/configmaster"),n={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,ConfigTypeId:t};return yield this.makePostRequest(e,n)}))}getUserConfigSettings(t){return e(this,void 0,void 0,(function*(){const e=this.getURL("/userconfigmapping"),n={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,ConfigTypeId:t};return yield this.makePostRequest(e,n)}))}updateUserConfig(t){return e(this,void 0,void 0,(function*(){const e=this.getURL("/userconfigmapping"),n={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,UserConfigMapping:t};return yield this.makePatchRequest(e,n)}))}getUserPreferences(){return e(this,void 0,void 0,(function*(){const e=this.getURL("/getuserpreferences"),t={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag};return yield this.makePostRequest(e,t)}))}updateUserPreference(t,n,r,i,o,s){return e(this,void 0,void 0,(function*(){const e=this.getURL("/postuserpreferences"),a={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,UserPreferences:{AutomaticallyGenerateTranscript:t,PreferredTranscriptionLanguage:n,HighlightMedicalTerms:r,DisplayPatientContext:i,NoteOutputStyle:o,NoteOutputVerbosity:s}};return yield this.makePostRequest(e,a)}))}}const j="Invalid user details, please check again",B="Subscription is not valid.",z="invalid request. Please make sure AccessKey, SubscriptionCode and UserTag is sent along with the request",V="Active seat is not available for user",q="Unable to fetch account details, please try again.",F="Unable to fetch job details, please try again.",H="Job not reconnectable",G="Timeout exceeded",$="Rate Limit Exceeded, Please try again in sometime!",Y="Audio Signal is power very LOW, Mic might be muted",Q="Job Id is empty",X="Page Size is undefined",Z="Note Data is empty",ee="Job Name is empty",te="Patient Context is empty",ne="Mic permission denied",re="Microphone is muted",ie="Audio track ended. Possibly the mic was unplugged",oe="Internet is not available. Try again later.";class se{constructor(e){Object.defineProperty(this,"_logTag",{enumerable:!0,configurable:!0,writable:!0,value:"Augnito-Ambient"}),Object.defineProperty(this,"_ambientRestAPI",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_ambientPaceAPI",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"enableLog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shouldReadAudioIntensity",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"recorderIns",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"forceStopAudio",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_isRecording",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"onJobCreated",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onStateChanged",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onOtherResult",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onIntensityValue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onIdleMic",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._ambientRestAPI=new l(this.validateConfig(e)),this._ambientPaceAPI=new W(e),this.config=this.createSocketConfig(e),this.enableLog=e.enableLogs,this.shouldReadAudioIntensity=e.shouldReadAudioIntensity}initRecorder(e){var t,n;this.recorderIns=new K({serverURL:e,enableLogs:null!==(t=this.enableLog)&&void 0!==t&&t,isDebug:null!==(n=this.enableLog)&&void 0!==n&&n,bufferInterval:15,EOS_Message:'{"JobAction": "EOS","Status": 0,"Type": "meta"}',socketTimeoutInterval:2e4,shouldSendAudioDataSequence:!0,shouldReadIntensity:this.shouldReadAudioIntensity}),this.recorderIns.onError=this.onErrorCallback.bind(this),this.recorderIns.onStateChanged=this.onStateChangeCallback.bind(this),this.recorderIns.onSessionEvent=this.onSessionEventCallback.bind(this),this.recorderIns.onOtherResults=this.onOtherResultsCallback.bind(this),this.recorderIns.onIntensity=this.onIntensityCallback.bind(this)}getNoteParams(){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientPaceAPI.getNoteParams();if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}getAllNotes(t,n){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientRestAPI.ListJobs(t,n);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}getSummarizedNote(t){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientRestAPI.FetchJob(t);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}sendSummarizedNote(t,n){return e(this,void 0,void 0,(function*(){try{return this._ambientRestAPI?yield this._ambientRestAPI.SendFinalNote(t,n):void h.error("SDK not initialized",this._logTag)}catch(e){this.handleException(e)}}))}toggleListening(e,t,n,r,i){var o,s,a=(null===(o=this.config)||void 0===o?void 0:o.prepareWSSURL(e,t,n,r))||"";this.recorderIns||this.initRecorder(a),null===(s=this.recorderIns)||void 0===s||s.toggleStartStopAudioStream(i,a)}togglePauseResumeListening(e,t,n,r,i){var o,s,a=(null===(o=this.config)||void 0===o?void 0:o.prepareWSSURL(e,t,n,r))||"";this.recorderIns||this.initRecorder(a),null===(s=this.recorderIns)||void 0===s||s.togglePauseResumeAudioStream(i,a)}startListening(){var e;null===(e=this.recorderIns)||void 0===e||e.startAudio()}stopListening(){var e;null===(e=this.recorderIns)||void 0===e||e.stopAudio(!0,!0)}deleteNotes(t){var n;return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientRestAPI.DeleteNotes(t);if(e){if(200===e.Status)return null===(n=this.recorderIns)||void 0===n||n.stopAudio(!1,!0),e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}renameNoteTitle(t,n){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientRestAPI.RenameNoteTitle(t,n);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}getNotePDF(t,n,r,i,o,s){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientRestAPI.DownloadNotePDF(t,n,r,i,o,s);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}endPausedJob(t){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientRestAPI.EndJob(t);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}generateCDISuggestions(t,n,r,i,o){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientRestAPI.GenerateSuggestions(t,n,r,o,i);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}updatePatientContext(t,n,r){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientRestAPI.UpdatePatientContext(t,n,r);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}modifyGeneratedNote(t,n,r){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientRestAPI.ModifyGeneratedNote(t,n,r);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}fetchTranscriptionForNote(t){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void h.error("SDK not initialized",this._logTag);if((yield this._ambientPaceAPI.getUserPreferences()).Items[0].AutomaticTranscriptionEnabledForOrg){var e=yield this._ambientRestAPI.FetchTranscription(t);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}else this.onErrorCallback("Automatic Transcription is not enabled for the organisation")}catch(e){this.handleException(e)}}))}getUserConfiguration(t){return e(this,void 0,void 0,(function*(){try{if(!this._ambientPaceAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientPaceAPI.getUserConfigSettings(t);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}updateUserConfiguration(t){return e(this,void 0,void 0,(function*(){try{if(!this._ambientPaceAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientPaceAPI.updateUserConfig(t);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}getUserPreferenceSettings(){return e(this,void 0,void 0,(function*(){try{if(!this._ambientPaceAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientPaceAPI.getUserPreferences();if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}updateUserPreferenceSettings(t){var n,r,i,o,u,c;return e(this,void 0,void 0,(function*(){try{if(!this._ambientPaceAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientPaceAPI.updateUserPreference(null!==(n=t.AutomaticallyGenerateTranscript)&&void 0!==n&&n,null!==(r=t.PreferredTranscriptionLanguage)&&void 0!==r?r:"English",null!==(i=t.HighlightMedicalTerms)&&void 0!==i&&i,null!==(o=t.DisplayPatientContext)&&void 0!==o&&o,null!==(u=t.NoteOutputStyle)&&void 0!==u?u:a.DashFormat,null!==(c=t.NoteOutputVerbosity)&&void 0!==c?c:s.Detailed);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}onEventCallback(e){this.onJobCreated&&this.onJobCreated(e)}onStateChangeCallback(e){var t;if(this.forceStopAudio)return null===(t=this.recorderIns)||void 0===t||t.stopAudio(!1,!0),void(this.forceStopAudio=!1);this._isRecording=e,this.onStateChanged&&this.onStateChanged(e)}handleException(e){if(e instanceof TypeError)this.onErrorCallback(e.message);else{if(e instanceof u)throw e;h.error(e.message,this._logTag)}}onErrorCallback(e,t){var n,r,i,s,a,u,c,l,d,f,g,p,v,b,y={ErrorCode:null!=t?t:o.ERRUNKNOWN,ErrorMessage:e};try{var m=JSON.parse(e);y.ErrorMessage=m.Data,m.Data===G?(this.stopListening(),h.error("Recording time limit exceeded",this._logTag),y.ErrorCode=o.WSJOB05):m.Data===j?(this._isRecording?null===(n=this.recorderIns)||void 0===n||n.stopAudio(!1,!0):this.forceStopAudio=!0,y.ErrorCode=o.WSAUTH03):m.Data.includes(q)?y.ErrorCode=o.WSAUTH04:m.Data.includes(F)?y.ErrorCode=o.WSJOB01:m.Data.includes(H)?y.ErrorCode=o.WSJOB02:m.Data.includes($)?y.ErrorCode=o.WSACC01:m.Data.includes(Y)&&(y.ErrorCode=o.WSAUD01)}catch(e){}(null===(r=y.ErrorMessage)||void 0===r?void 0:r.includes(Q))?y.ErrorCode=o.SDK01:(null===(i=y.ErrorMessage)||void 0===i?void 0:i.includes(X))?y.ErrorCode=o.SDK02:(null===(s=y.ErrorMessage)||void 0===s?void 0:s.includes(Z))?y.ErrorCode=o.SDK03:(null===(a=y.ErrorMessage)||void 0===a?void 0:a.includes(ee))?y.ErrorCode=o.SDK04:(null===(u=y.ErrorMessage)||void 0===u?void 0:u.includes(te))?y.ErrorCode=o.SDK05:(null===(c=y.ErrorMessage)||void 0===c?void 0:c.includes(ne))?y.ErrorCode=o.SDK06:(null===(l=y.ErrorMessage)||void 0===l?void 0:l.includes(re))?(y.ErrorCode=o.SDK07,null===(d=this.recorderIns)||void 0===d||d.stopAudio(!1,!0)):(null===(f=y.ErrorMessage)||void 0===f?void 0:f.includes(ie))?y.ErrorCode=o.SDK08:(null===(g=y.ErrorMessage)||void 0===g?void 0:g.includes(B))||(null===(p=y.ErrorMessage)||void 0===p?void 0:p.includes(z))?y.ErrorCode=o.AUTH01:(null===(v=y.ErrorMessage)||void 0===v?void 0:v.includes(V))?y.ErrorCode=o.AUTH02:(null===(b=y.ErrorMessage)||void 0===b?void 0:b.includes(oe))&&(y.ErrorCode=o.SDK11),this.onError&&this.onError(y)}onOtherResultsCallback(e){this.onOtherResult&&this.onOtherResult(e)}onIntensityCallback(e){this.onIntensityValue&&this.onIntensityValue(e)}onIdleMicCallback(){this.onIdleMic&&this.onIdleMic()}onSessionEventCallback(e){var t;if(!e)return;let n;try{n="string"==typeof e?JSON.parse(e):e}catch(e){return void h.error(`Error parsing session event data: ${e}`,this._logTag)}if(!n||!("Type"in n))return;if("meta"===n.Type.toLowerCase()&&(null===(t=this.config)||void 0===t?void 0:t.onMetaEvent)){if(!n.JobID)return void h.error("JobID is missing in meta event",this._logTag);this.config.onMetaEvent(n.JobID)}else"error"===n.Type.toLowerCase()&&n.Data&&this.onErrorCallback(n.Data);if("object"!=typeof n.Event||null===n.Event)return;const{Type:r,Value:i}=n.Event;r&&("SESSION_CREATED"===r&&i?h.log(`session Token ${i}`,this._logTag):"SERVICE_DOWN"===r?h.error(r,this._logTag):"NO_DICTATION_STOP_MIC"===r?(h.log("NO_DICTATION_STOP_MIC",this._logTag),this.onIdleMicCallback()):"INVALID_AUTH_CREDENTIALS"===r?h.error("INVALID_AUTH_CREDENTIALS",this._logTag):"LOW_BANDWIDTH"===r&&h.log("LOW_BANDWIDTH: Check internet connection",this._logTag))}validateConfig(e){return n.Against.NullOrEmpty(e.server,"Server"),n.Against.NullOrEmpty(e.subscriptionCode,"SubscriptionCode"),n.Against.NullOrEmpty(e.accessKey,"AccessKey"),n.Against.NullOrEmpty(e.userTag,"UserTag"),e}createSocketConfig(e){const n=new t(e);return n.onError=this.onErrorCallback.bind(this),n.onMetaEvent=this.onEventCallback.bind(this),n}}export{se as AugnitoAmbient,o as ErrorCodes,u as HttpCodedError,a as NoteOutputStyleConfig,i as NoteTypeConfig,s as NoteVerbosityConfig,r as SettingsConfigType};
1
+ function e(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{u(n.next(e))}catch(e){o(e)}}function a(e){try{u(n.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}u((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class t{constructor(e){Object.defineProperty(this,"_config",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"wssBaseURL",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onMetaEvent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.wssBaseURL=`wss://${e.server}/ambient/v1/stream-job`}prepareWSSURL(e,t,r,n){let i=this.wssBaseURL;return i+=`?filetype=${e}`,i+=`&noteparams=${t}`,i+=`&subscriptioncode=${this._config.subscriptionCode}`,i+=`&accesskey=${this._config.accessKey}`,i+=`&usertag=${this._config.userTag}`,r&&""!==r&&(i+=`&filename=${r}`),n&&""!==n&&(i+=`&jobid=${n}`),i}}class r{constructor(){}static get Against(){return r.instance||(r.instance=new r),r.instance}NullOrUndefined(e,t){if(null===e)throw new TypeError(`${t} is null`);if(void 0===e)throw new TypeError(`${t} is undefined`);return e}NullOrEmpty(e,t){if(!(e=r.Against.NullOrUndefined(e,t)))throw new TypeError(`${t} is empty`);return e}}var n,i,o,s,a;!function(e){e[e.SPECIALITY=1]="SPECIALITY",e[e.VISIT_TYPE=2]="VISIT_TYPE",e[e.NOTE_TYPE=3]="NOTE_TYPE",e[e.CLINICAL_CODE=4]="CLINICAL_CODE",e[e.LANGUAGE=5]="LANGUAGE"}(n||(n={})),function(e){e[e.SoapNote=1]="SoapNote",e[e.PatientNote=2]="PatientNote",e[e.ReferralNote=3]="ReferralNote",e[e.ConsultationSummary=4]="ConsultationSummary",e[e.CDISuggestions=102]="CDISuggestions"}(i||(i={})),function(e){e.AUTH01="AUTH01",e.AUTH02="AUTH02",e.WSAUTH01="WSAUTH01",e.WSAUTH02="WSAUTH02",e.WSAUTH03="WSAUTH03",e.WSAUTH04="WSAUTH04",e.WSJOB01="WSJOB01",e.WSJOB02="WSJOB02",e.WSJOB03="WSJOB03",e.WSJOB04="WSJOB04",e.WSJOB05="WSJOB05",e.WSACC01="WSACC01",e.WSAUD01="WSAUD01",e.SDK01="SDK01",e.SDK02="SDK02",e.SDK03="SDK03",e.SDK04="SDK04",e.SDK05="SDK05",e.SDK06="SDK06",e.SDK07="SDK07",e.SDK08="SDK08",e.SDK11="SDK11",e.ERRUNKNOWN="ERRUNKNOWN"}(o||(o={}));class u extends Error{constructor(e,t){super(e),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=t,this.name="HttpCodedError",Object.setPrototypeOf(this,u.prototype)}}!function(e){e.Detailed="Detailed",e.Consise="Consise"}(s||(s={})),function(e){e.DashFormat="Dash-format",e.Paragraph="Paragraph"}(a||(a={}));class c{makePostRequest(t,r){return e(this,void 0,void 0,(function*(){try{const n=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok){const t=yield n.text();var e=JSON.parse(t);throw new u(e.message,e.code.toString())}return yield n.json()}catch(e){throw e}}))}makePatchRequest(t,r){return e(this,void 0,void 0,(function*(){try{const n=yield fetch(t,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok){const t=yield n.text();var e=JSON.parse(t);throw new u(e.message,n.status.toString())}return yield n.json()}catch(e){throw e instanceof u?e:new u("500",e.message||"Unexpected error")}}))}}class l extends c{constructor(e){super(),Object.defineProperty(this,"_config",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"_baseUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._baseUrl=`https://${e.server}/ambient/v1`}getURL(e){return`${this._baseUrl}${e}`}GetNoteParams(){return e(this,void 0,void 0,(function*(){const e=this.getURL("/note-params"),t={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag};return yield this.makePostRequest(e,t)}))}ListJobs(t,n){return e(this,void 0,void 0,(function*(){r.Against.NullOrEmpty(t,"Page Size");const e=this.getURL("/list-jobs"),i={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,PageSize:t,PageID:n};return yield this.makePostRequest(e,i)}))}FetchJob(t){return e(this,void 0,void 0,(function*(){r.Against.NullOrEmpty(t,"Job Id");const e=this.getURL("/fetch-job"),n={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t};return yield this.makePostRequest(e,n)}))}SendFinalNote(t,n){return e(this,void 0,void 0,(function*(){r.Against.NullOrEmpty(t,"Job Id"),r.Against.NullOrEmpty(n,"Note Data");const e=this.getURL("/send-final-note"),i={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t,SoapData:n};return yield this.makePostRequest(e,i)}))}DeleteNotes(t){return e(this,void 0,void 0,(function*(){r.Against.NullOrEmpty(t,"Job Id");const e=this.getURL("/delete-job"),n={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobIDs:t};return yield this.makePostRequest(e,n)}))}RenameNoteTitle(t,n){return e(this,void 0,void 0,(function*(){r.Against.NullOrEmpty(t,"Job Id"),r.Against.NullOrEmpty(n,"Job Name");const e=this.getURL("/rename-job"),i={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t,JobName:n};return yield this.makePostRequest(e,i)}))}DownloadNotePDF(t,n,i,o,s,a){return e(this,void 0,void 0,(function*(){r.Against.NullOrEmpty(t,"Job Id");const e=this.getURL("/download-pdf");var u=s;u&&""!=u||(u='{"PatientName":"","PatientID":"","Age":"","Gender":"","ReceivingDoctor":"","DoctorName":"","DoctorDesignation":"","DoctorEmail":""}');const c={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t,NoteType:n,Language:null!=o?o:"English",SpecialityID:i,Regenerate:null!=a&&a,PersonnelInfo:u};return yield this.makePostRequest(e,c)}))}EndJob(t){return e(this,void 0,void 0,(function*(){r.Against.NullOrEmpty(t,"Job Id");const e=this.getURL("/end-job"),n={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t};return yield this.makePostRequest(e,n)}))}UpdatePatientContext(t,n,i){return e(this,void 0,void 0,(function*(){r.Against.NullOrEmpty(t,"Job Id"),r.Against.NullOrEmpty(n,"Patient Context");const e=this.getURL("/patient-context"),o={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t,NewContext:n,Replace:i};return yield this.makePostRequest(e,o)}))}GenerateSuggestions(t,n,i,o,s){return e(this,void 0,void 0,(function*(){r.Against.NullOrEmpty(t,"Job Id");const e=this.getURL("/cdi"),a={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t,Regenerate:n,SoapData:i,PatientContext:o,Codes:s};return yield this.makePostRequest(e,a)}))}ModifyGeneratedNote(t,n,i){return e(this,void 0,void 0,(function*(){r.Against.NullOrEmpty(t,"Job Id");const e=this.getURL("/modify-note"),o={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t,NoteType:n,NewNote:null!=i?i:""};return yield this.makePostRequest(e,o)}))}FetchTranscription(t){return e(this,void 0,void 0,(function*(){r.Against.NullOrEmpty(t,"Job Id");const e=this.getURL("/fetch-transcript"),n={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t};return yield this.makePostRequest(e,n)}))}}class h{static log(e,t){const r=null!=t?t:this.defaultTag;console.log(`${r}:`,e)}static error(e,t){const r=null!=t?t:this.defaultTag;console.error(`${r}:`,e)}}function d(){d=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,i=Object.defineProperty||function(e,t,r){e[t]=r.value},o="function"==typeof Symbol?Symbol:{},s=o.iterator||"@@iterator",a=o.asyncIterator||"@@asyncIterator",u=o.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var o=t&&t.prototype instanceof y?t:y,s=Object.create(o.prototype),a=new D(n||[]);return i(s,"_invoke",{value:R(e,r,a)}),s}function h(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var f="suspendedStart",g="suspendedYield",p="executing",v="completed",b={};function y(){}function m(){}function S(){}var E={};c(E,s,(function(){return this}));var k=Object.getPrototypeOf,C=k&&k(k(N([])));C&&C!==r&&n.call(C,s)&&(E=C);var I=S.prototype=y.prototype=Object.create(E);function A(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function w(e,t){function r(i,o,s,a){var u=h(e[i],e,o);if("throw"!==u.type){var c=u.arg,l=c.value;return l&&"object"==typeof l&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,s,a)}),(function(e){r("throw",e,s,a)})):t.resolve(l).then((function(e){c.value=e,s(c)}),(function(e){return r("throw",e,s,a)}))}a(u.arg)}var o;i(this,"_invoke",{value:function(e,n){function i(){return new t((function(t,i){r(e,n,t,i)}))}return o=o?o.then(i,i):i()}})}function R(t,r,n){var i=f;return function(o,s){if(i===p)throw Error("Generator is already running");if(i===v){if("throw"===o)throw s;return{value:e,done:!0}}for(n.method=o,n.arg=s;;){var a=n.delegate;if(a){var u=P(a,n);if(u){if(u===b)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(i===f)throw i=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);i=p;var c=h(t,r,n);if("normal"===c.type){if(i=n.done?v:g,c.arg===b)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(i=v,n.method="throw",n.arg=c.arg)}}}function P(t,r){var n=r.method,i=t.iterator[n];if(i===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,P(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),b;var o=h(i,t.iterator,r.arg);if("throw"===o.type)return r.method="throw",r.arg=o.arg,r.delegate=null,b;var s=o.arg;return s?s.done?(r[t.resultName]=s.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,b):s:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,b)}function T(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function O(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function D(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(T,this),this.reset(!0)}function N(t){if(t||""===t){var r=t[s];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var i=-1,o=function r(){for(;++i<t.length;)if(n.call(t,i))return r.value=t[i],r.done=!1,r;return r.value=e,r.done=!0,r};return o.next=o}}throw new TypeError(typeof t+" is not iterable")}return m.prototype=S,i(I,"constructor",{value:S,configurable:!0}),i(S,"constructor",{value:m,configurable:!0}),m.displayName=c(S,u,"GeneratorFunction"),t.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===m||"GeneratorFunction"===(t.displayName||t.name))},t.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,S):(e.__proto__=S,c(e,u,"GeneratorFunction")),e.prototype=Object.create(I),e},t.awrap=function(e){return{__await:e}},A(w.prototype),c(w.prototype,a,(function(){return this})),t.AsyncIterator=w,t.async=function(e,r,n,i,o){void 0===o&&(o=Promise);var s=new w(l(e,r,n,i),o);return t.isGeneratorFunction(r)?s:s.next().then((function(e){return e.done?e.value:s.next()}))},A(I),c(I,u,"Generator"),c(I,s,(function(){return this})),c(I,"toString",(function(){return"[object Generator]"})),t.keys=function(e){var t=Object(e),r=[];for(var n in t)r.push(n);return r.reverse(),function e(){for(;r.length;){var n=r.pop();if(n in t)return e.value=n,e.done=!1,e}return e.done=!0,e}},t.values=N,D.prototype={constructor:D,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=e,this.done=!1,this.delegate=null,this.method="next",this.arg=e,this.tryEntries.forEach(O),!t)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=e)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var r=this;function i(n,i){return a.type="throw",a.arg=t,r.next=n,i&&(r.method="next",r.arg=e),!!i}for(var o=this.tryEntries.length-1;o>=0;--o){var s=this.tryEntries[o],a=s.completion;if("root"===s.tryLoc)return i("end");if(s.tryLoc<=this.prev){var u=n.call(s,"catchLoc"),c=n.call(s,"finallyLoc");if(u&&c){if(this.prev<s.catchLoc)return i(s.catchLoc,!0);if(this.prev<s.finallyLoc)return i(s.finallyLoc)}else if(u){if(this.prev<s.catchLoc)return i(s.catchLoc,!0)}else{if(!c)throw Error("try statement without catch or finally");if(this.prev<s.finallyLoc)return i(s.finallyLoc)}}}},abrupt:function(e,t){for(var r=this.tryEntries.length-1;r>=0;--r){var i=this.tryEntries[r];if(i.tryLoc<=this.prev&&n.call(i,"finallyLoc")&&this.prev<i.finallyLoc){var o=i;break}}o&&("break"===e||"continue"===e)&&o.tryLoc<=t&&t<=o.finallyLoc&&(o=null);var s=o?o.completion:{};return s.type=e,s.arg=t,o?(this.method="next",this.next=o.finallyLoc,b):this.complete(s)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),b},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),O(r),b}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var i=n.arg;O(r)}return i}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:N(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),b}},t}function f(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function g(e,t,r,n,i,o,s){try{var a=e[o](s),u=a.value}catch(e){return void r(e)}a.done?t(u):Promise.resolve(u).then(n,i)}function p(e){return function(){var t=this,r=arguments;return new Promise((function(n,i){var o=e.apply(t,r);function s(e){g(o,n,i,s,a,"next",e)}function a(e){g(o,n,i,s,a,"throw",e)}s(void 0)}))}}function v(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function b(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,f(n.key),n)}}function y(e,t,r){return t&&b(e.prototype,t),r&&b(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function m(e,t,r){return(t=f(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}Object.defineProperty(h,"defaultTag",{enumerable:!0,configurable:!0,writable:!0,value:"AugnitoAmbientSDK"});var S="DONE",E="PAUSESOCKET",k="RESUMESOCKET",C="CLOSE",I=12e4,A=y((function e(t,r,n,i,o,s,a,u,c,l,h,d){v(this,e),this.worker,this.onFinalResultCallback=o,this.onErrorCallback=a,this.onPartialResultCallback=s,this.onSessionEventCallback=u,this.onOtherResultsCallback=c,this.onSpeechResponseCallback=l,this.packetSeqId=0,this.audioDuration=0,this.shouldSendAudioDataSequence=i,this.heavyOp,this.idleLoop,this.lastSent,this.enableLogs=t,this.eosMessage=r||"EOS",this.socketTimeoutInterval=n||1e4,this.bufferSizeInterval=h,this.switchToRegularSpeech=d}),[{key:"Start",value:function(e,t){var r=this;this.audioDuration=e;var n="\n (() => {\n (".concat(w.toString(),")(").concat(JSON.stringify(S),", ").concat(JSON.stringify(this.eosMessage),", ").concat(JSON.stringify(C),", ").concat(JSON.stringify(1e4),", ").concat(JSON.stringify(this.socketTimeoutInterval),", ").concat(JSON.stringify(1e3),", ").concat(JSON.stringify(100),", ").concat(JSON.stringify(t),", ").concat(JSON.stringify(this.enableLogs),", ").concat(JSON.stringify(this.shouldSendAudioDataSequence),",").concat(JSON.stringify(E),", ").concat(JSON.stringify(k),", ").concat(JSON.stringify(this.switchToRegularSpeech),", ").concat(JSON.stringify(this.heavyOp),");\n })();\n");this.worker=new Worker(URL.createObjectURL(new Blob([n],{type:"application/javascript"}))),this.worker.onmessage=function(e){r.enableLogs&&console.log("Augnito [MAIN]: "+JSON.stringify(e.data));var t=e.data;"final"==t.type?r.onFinalResultCallback(t.data):"partial"==t.type?r.onPartialResultCallback(t.data):"meta"==t.type?r.onSessionEventCallback(t.data):"error"==t.type?r.onErrorCallback(t.data):"other"==t.type?r.onOtherResultsCallback(t.data):"speechResponse"==t.type&&r.onSpeechResponseCallback(t.data)},this.idleLoop=setInterval((function(){var e=+new Date;r.lastSent&&e-r.lastSent>I&&(r.Send(r.eosMessage),r.enableLogs&&console.warn("No data sent since more than ".concat(120," secs, closing time...")))}),1e4)}},{key:"createAudioPacketHeader",value:function(e){this.audioDuration>0&&(this.packetSeqId=Math.ceil(this.audioDuration/this.bufferSizeInterval)+2,this.audioDuration=0),this.packetSeqId++;for(var t=new ArrayBuffer(16),r=new DataView(t),n=0;n<4;n++)r.setUint8(n,"@BSR".charCodeAt(n));return r.setBigInt64(4,BigInt(this.packetSeqId),!1),r.setUint8(12,e?1:0),t}},{key:"appendAudioData",value:function(e,t){var r=e.byteLength+t.byteLength,n=new ArrayBuffer(r),i=new Uint8Array(n);return i.set(new Uint8Array(e),0),i.set(new Uint8Array(t),e.byteLength),n}},{key:"Send",value:function(e){var t;if(this.lastSent=+new Date,e===C)null===(t=this.worker)||void 0===t||t.postMessage(C),clearInterval(this.idleLoop);else if(e===S){if(this.shouldSendAudioDataSequence){var r,n=this.createAudioPacketHeader(!0);null===(r=this.worker)||void 0===r||r.postMessage(n)}else{var i;null===(i=this.worker)||void 0===i||i.postMessage(S)}clearInterval(this.idleLoop)}else if(e==E){var o;null===(o=this.worker)||void 0===o||o.postMessage(E)}else if(e==k){var s;null===(s=this.worker)||void 0===s||s.postMessage(k)}else if(e===this.eosMessage){var a;this.shouldSendAudioDataSequence||null===(a=this.worker)||void 0===a||a.postMessage(e)}else{var u,c=[];this.shouldSendAudioDataSequence?(n=this.createAudioPacketHeader(!1),c=this.appendAudioData(n,e)):c=e,void 0!==c&&(null===(u=this.worker)||void 0===u||u.postMessage(c,[c]))}}},{key:"HeavyOp",set:function(e){this.heavyOp=e}}]);function w(e,t,r,n,i,o,s,a,u,c,l,h,d,f){var g,p,v,b,y,m,S,E,k=[],C=[],I=!1,A=!1,w=!1,R="",P=!1;function T(){g=+new Date,(m=""!=R?new WebSocket(a+"&jobid="+R):new WebSocket(a)).onopen=function(e){u&&console.log("Augnito: WebSocket connection established - "+JSON.stringify(e)),C.length>0&&(A=!0)},m.onmessage=function(e){u&&console.log("Augnito: Message from server - "+JSON.stringify(e.data)),v=+new Date,function(e){try{if("PING"===e.data)b=+new Date,self.postMessage({type:"ping",data:e.data});else{var t=JSON.parse(e.data);if(u&&console.log("Augnito [WORKER]: "+JSON.stringify(t)),"meta"==t.Type){t.JobID&&(R=t.JobID,console.log("Augnito JobID:",R)),self.postMessage({type:"meta",data:e.data});var r=JSON.parse(e.data);w=!(!r.Event||"INVALID_AUTH_CREDENTIALS"!==r.Event.Type)}else if(t.Result&&t.Result.Final){var n=JSON.stringify(t.Result);f&&(n=f(JSON.stringify(t.Result)),console.log(n)),self.postMessage({type:"final",data:n})}else t.Result&&!t.Result.Final?self.postMessage({type:"partial",data:t.Result.Transcript}):"ACK"==t.Type?(C=C.filter((function(e){return e.packetNumber>t.Index})),self.postMessage({type:"other",data:e.data})):"ERROR"==t.Type?("Timeout exceeded"==t.Data&&(I=!0,N()),self.postMessage({type:"error",data:e.data})):self.postMessage({type:"speechResponse",data:e.data})}}catch(e){self.postMessage({type:"error",data:"invalid response"})}}(e)},m.onerror=function(e){console.error("WebSocket error: ",e),self.postMessage({type:"error",data:JSON.stringify(e)})},m.onclose=function(e){u&&console.log("Augnito: WebSocket connection closed - "+JSON.stringify(e)),N()},p=+new Date,v=p,b=+new Date}function O(e){if(m&&m.readyState===WebSocket.OPEN){m.send(e);var r=+new Date;return p<=v&&(v=r-1),p=r,!0}return e===t?(u&&console.warn("Gulping ".concat(t," as socket seems already closed...")),N(),!0):(+new Date-g>n&&!w&&T(),!1)}function D(e){k.push(e)}function N(){I&&(clearInterval(S),clearInterval(E),k=[],C=[],self.close())}T(),S=setInterval((function(){if(A){for(var e=0;e<C.length;e++){if(!O(C[e].packetData))break}A=!1}else for(;k.length>0;){var t=k.shift();if(!O(t)){k.unshift(t);break}if(c){var r=new DataView(t),n={packetNumber:Number(r.getBigInt64(4)),packetData:t};C.push(n)}}}),s),E=setInterval((function(){if(m&&m.readyState===WebSocket.OPEN){var e=+new Date;(d?p>v&&e-v>i:e-b>i)&&(u&&console.error("No data received since more than ".concat(i/1e3," secs, closing time...")),m.close())}}),o),self.onmessage=function(n){n.data===r?(R="",I=!0,w=!0,m.close()):n.data===e?(D(t),R="",u&&console.log("Augnito: Worker received DONE, time to terminate..."),I=!0):n.data===l?P=!0:n.data===h?(D(y),P=!1,y=[]):P?y=n.data:D(n.data)}}var R,P,T,O,D,N,_,x,U,L=y((function e(t,r,n,i,o,s,a,u,c,l,h,d,f,g,p,b,y,m,S){v(this,e),this.audioContext,this.audioStream,this.executor=new A(t,o,s,a,d,f,g,b,y,m,n,l),this.executor.HeavyOp=h,this.source,this.processorNode,this.isPaused=!1,this.isStreaming=!1,this.audioData=[],this.isDebug=r,this.enableLogs=t,this.onStateChanged=p,this.onIntensity=S,this.onError=g,this.bufferSizeInterval=n,this.pausedBufferInterval=null!=i?i:1,this.shouldReadIntensity=c,this.closeSocketWithoutEOS=!1,this.shouldPreIntialiseRecorder=null!=u&&u,this.shouldPreIntialiseRecorder&&this.EarlyInitialiseMediaStream()}),[{key:"EarlyInitialiseMediaStream",value:(U=p(d().mark((function e(){return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.createMediaStreamSourceNode();case 2:if(!this.audioContext||"running"!=this.audioContext.state){e.next=5;break}return e.next=5,this.audioContext.suspend();case 5:case"end":return e.stop()}}),e,this)}))),function(){return U.apply(this,arguments)})},{key:"StartStream",value:(x=p(d().mark((function e(t,r){return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.log("New stream started..."),this.shouldPreIntialiseRecorder&&this.source){e.next=9;break}return e.next=4,this.createMediaStreamSourceNode();case 4:if(this.source){e.next=7;break}return console.error("Error: unable to create source node"),e.abrupt("return",!1);case 7:e.next=12;break;case 9:if("suspended"!=this.audioContext.state){e.next=12;break}return e.next=12,this.audioContext.resume();case 12:return e.next=14,this.createProcessorNode();case 14:if(this.processorNode){e.next=17;break}return console.error("Error: unable to create processor node"),e.abrupt("return",!1);case 17:if(!this.IsMicrophoneMuted){e.next=23;break}if(!this.audioContext||"running"!=this.audioContext.state){e.next=21;break}return e.next=21,this.audioContext.suspend();case 21:return this.onError(JSON.stringify({Type:"ERROR",Data:"Microphone is muted."})),e.abrupt("return",!1);case 23:return""!==r&&this.executor.Start(t,r),this.onStateChanged(!0),this.source.connect(this.processorNode).connect(this.audioContext.destination),this.log("AudioContext Sample Rate: "+this.audioContext.sampleRate),this.isStreaming=!0,e.abrupt("return",!0);case 29:case"end":return e.stop()}}),e,this)}))),function(e,t){return x.apply(this,arguments)})},{key:"createBufferedSourceNode",value:(_=p(d().mark((function e(){var t;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.loadAudio();case 2:if(t=e.sent){e.next=6;break}return console.error("Error: unable to create audio buffer"),e.abrupt("return");case 6:this.source=this.audioContext.createBufferSource(),this.source.buffer=t,this.source.loop=!0,this.source.start();case 10:case"end":return e.stop()}}),e,this)}))),function(){return _.apply(this,arguments)})},{key:"createMediaStreamSourceNode",value:(N=p(d().mark((function e(){var t,r=this;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,navigator.mediaDevices.getUserMedia({audio:{channelCount:1,noiseSuppression:!1}});case 3:this.audioStream=e.sent,this.audioContext=new AudioContext,this.source=this.audioContext.createMediaStreamSource(this.audioStream),this.audioStream.getAudioTracks()[0].addEventListener("ended",(function(){r.onError(JSON.stringify({Type:"ERROR",Data:"Audio track ended. Possibly the mic was unplugged."}))})),e.next=14;break;case 9:e.prev=9,e.t0=e.catch(0),t="","NotAllowedError"==e.t0.name?t="Mic permission denied":"NotFoundError"===e.t0.name&&(t="No suitable media device found"),this.onError(JSON.stringify({Type:"ERROR",Data:t}));case 14:case"end":return e.stop()}}),e,this,[[0,9]])}))),function(){return N.apply(this,arguments)})},{key:"loadAudio",value:(D=p(d().mark((function e(){var t,r,n;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,fetch("./radiology_speed_test.wav");case 3:return t=e.sent,e.next=6,t.arrayBuffer();case 6:return r=e.sent,e.next=9,this.audioContext.decodeAudioData(r);case 9:return n=e.sent,e.abrupt("return",n);case 13:return e.prev=13,e.t0=e.catch(0),console.error("Unable to fetch the audio file. Error: ".concat(e.t0.message)),e.abrupt("return",null);case 17:case"end":return e.stop()}}),e,this,[[0,13]])}))),function(){return D.apply(this,arguments)})},{key:"createProcessorNode",value:(O=p(d().mark((function e(){var t,r=this;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.audioContext.audioWorklet.addModule("data:application/javascript,".concat(encodeURIComponent('class MyAudioWorkletProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.accumulator = [];\n this.pauseSocketStreaming = false;\n this.sampleVal = 0;\n this.sampleSize = 0;\n this.intensityFrameCount = 0;\n this.reset();\n this.isProcessing = true;\n // message received from main-thread\n this.port.onmessage = (e) => {\n console.log("Augnito: Worklet received event - ", e.data);\n if (this.sampleSize > 0) {\n this.accumulator.push(this.sampleVal / this.sampleSize);\n }\n \n if (e.data == "PAUSE" || e.data == "STOP" || e.data == "PAUSESOCKET") {\n // append silence to get last word ASR.\n const silenceSize = 16000 * 2;\n for (let i = 0; i < silenceSize; i++) {\n this.accumulator.push(0);\n }\n }\n this.send();\n this.reset();\n if (e.data == "STOP") {\n // message sent to main-thread\n this.port.postMessage({type:"DONE", value:"DONE"});\n this.isProcessing = false;\n \n }\n if(e.data == "PAUSESOCKET"){\n this.pauseSocketStreaming = true;\n this.port.postMessage("PAUSESOCKET");\n } else if(e.data == "RESUMESOCKET"){\n this.pauseSocketStreaming = false;\n } \n };\n }\n\n static get parameterDescriptors() {\n return [\n {\n name: "sampleRate",\n defaultValue: 16000,\n minValue: 16000,\n maxValue: 6 * 16000,\n },\n {\n name: "bufferSizeInterval",\n defaultValue: 1,\n minValue: 1,\n maxValue: 100,\n },\n {\n name: "pausedBufferInterval",\n defaultValue: 1,\n minValue: 0,\n maxValue: 100,\n },\n {\n name: "shouldReadIntensity",\n defaultValue: false,\n minValue: 0,\n maxValue: 1,\n },\n ];\n }\n\n // 128 frames\n process(inputList, outputList, params) {\n const input = inputList[0];\n if (input && input.length && input[0].length) {\n const channelData = input[0];\n const output = outputList[0];\n const inputSampleRate = params.sampleRate[0];\n const sampleRatio = inputSampleRate / 16000\n const bufferSizeInterval = params["bufferSizeInterval"][0];\n const pausedBufferInterval = params["pausedBufferInterval"][0];\n const shouldReadIntensity = params["shouldReadIntensity"][0];\n\n let sumSquares = 0; // For intensity\n let sampleCount = 0;\n\n // console.log("BufferSizeInterval", bufferSizeInterval);\n // Jackpot\n input[0].forEach((float32Element, index) => {\n const int16Element = Math.min(1, Math.max(-1, float32Element)) * 0x7fff;\n this.sampleVal += int16Element;\n this.sampleSize += 1;\n // Accumulate for intensity (RMS)\n sumSquares += float32Element * float32Element;\n sampleCount++;\n \n\n if (this.sampleSize >= sampleRatio) {\n const fraction = this.sampleSize - sampleRatio \n this.sampleVal -= fraction * int16Element;\n\n this.accumulator.push(this.sampleVal / sampleRatio);\n \n this.sampleVal = fraction * int16Element;\n this.sampleSize = fraction;\n }\n\n // Comment this when streaming microphone audio\n // output[0][index] = float32Element;\n });\n if(this.pauseSocketStreaming){\n if (this.accumulator.length >= 125 * 128 * pausedBufferInterval) {\n this.send();\n }\n } else{\n if (this.accumulator.length >= 125 * 128 * bufferSizeInterval) {\n this.send();\n }\n }\n if(shouldReadIntensity){\n \n // Throttled intensity post\n this.intensityFrameCount = (this.intensityFrameCount || 0) + 1;\n if (this.intensityFrameCount >= 15 && sampleCount > 0) {\n const rms = Math.sqrt(sumSquares / sampleCount);\n const normalized = Math.min(1, rms); // [0–1] scale\n this.port.postMessage({ type: \'intensity\', value: normalized });\n this.intensityFrameCount = 0;\n }\n }\n }\n return this.isProcessing;\n }\n\n send() {\n if (this.accumulator.length == 0) return;\n const audioData = new Int16Array(this.accumulator);\n // message sent to main-thread - transferrable\n this.port.postMessage({ type: \'audioData\', value: audioData.buffer }, [audioData.buffer]);\n this.accumulator = [];\n }\n\n reset() {\n this.sampleVal = 0;\n this.sampleSize = 0;\n }\n}\n\nregisterProcessor("worklet-processor", MyAudioWorkletProcessor);')));case 3:this.processorNode=new AudioWorkletNode(this.audioContext,"worklet-processor"),this.processorNode.parameters.get("sampleRate").setValueAtTime(this.audioContext.sampleRate,this.audioContext.currentTime),this.processorNode.parameters.get("bufferSizeInterval").setValueAtTime(this.bufferSizeInterval,this.audioContext.currentTime),this.processorNode.parameters.get("pausedBufferInterval").setValueAtTime(this.pausedBufferInterval,this.audioContext.currentTime),this.processorNode.parameters.get("shouldReadIntensity").setValueAtTime(null!==(t=this.shouldReadIntensity)&&void 0!==t&&t,this.audioContext.currentTime),this.processorNode.port.onmessage=function(e){var t=e.data,n=t.type,i=t.value;if(n==S)r.log("Worklet processing done, clearing resources..."),r.isDebug&&r.saveAudio(),r.cleanup();else if(e.data==E)r.executor.Send(E);else{var o;"intensity"===n?null===(o=r.onIntensity)||void 0===o||o.call(r,i):"audioData"===n&&r.isDebug&&new Int16Array(i).forEach((function(e){r.audioData.length<=288e5&&r.audioData.push(e)}))}r.executor&&(r.closeSocketWithoutEOS?(r.executor.Send(C),r.closeSocketWithoutEOS=!1):"intensity"!==n&&r.executor.Send(i))},e.next=18;break;case 15:e.prev=15,e.t0=e.catch(0),console.error("Error: Unable to create worklet node: ",e.t0);case 18:case"end":return e.stop()}}),e,this,[[0,15]])}))),function(){return O.apply(this,arguments)})},{key:"PauseStream",value:(T=p(d().mark((function e(){return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("running"!=this.audioContext.state){e.next=10;break}if(this.shouldPreIntialiseRecorder){e.next=9;break}return e.next=4,this.audioContext.suspend();case 4:this.onStateChanged(!1),this.log("Stream paused..."),this.processorNode.port.postMessage("PAUSE"),e.next=10;break;case 9:this.processorNode.port.postMessage(E);case 10:this.isPaused=!0,this.isStreaming=!1;case 12:case"end":return e.stop()}}),e,this)}))),function(){return T.apply(this,arguments)})},{key:"ResumeStream",value:(P=p(d().mark((function e(){return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.shouldPreIntialiseRecorder||"suspended"!=this.audioContext.state){e.next=9;break}if(!this.IsMicrophoneMuted){e.next=4;break}return this.onError(JSON.stringify({Type:"ERROR",Data:"Microphone is muted."})),e.abrupt("return");case 4:return e.next=6,this.audioContext.resume();case 6:this.log("Stream resumed..."),e.next=11;break;case 9:this.processorNode.port.postMessage(k),this.executor.Send(k);case 11:this.onStateChanged(!0),this.isPaused=!1,this.isStreaming=!0;case 14:case"end":return e.stop()}}),e,this)}))),function(){return P.apply(this,arguments)})},{key:"IsPaused",get:function(){return this.isPaused}},{key:"IsStreaming",get:function(){return this.isStreaming}},{key:"IsMicrophoneMuted",get:function(){return this.audioStream.getAudioTracks()[0].muted}},{key:"StopStream",value:(R=p(d().mark((function e(t){var r,n,i,o;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("suspended"===(null===(r=this.audioContext)||void 0===r?void 0:r.state)){e.next=4;break}return e.next=3,null===(o=this.audioContext)||void 0===o?void 0:o.suspend();case 3:this.onStateChanged(!1);case 4:this.log("Stream stopped..."),this.isStreaming=!1,this.closeSocketWithoutEOS=!t,null===(n=this.processorNode)||void 0===n||null===(n=n.port)||void 0===n||n.postMessage("STOP"),null===(i=this.audioStream)||void 0===i||i.getAudioTracks()[0].removeEventListener("ended",(function(){}));case 9:case"end":return e.stop()}}),e,this)}))),function(e){return R.apply(this,arguments)})},{key:"cleanup",value:function(){this.source.mediaStream.getAudioTracks()[0].stop(),this.source.disconnect(),this.processorNode.disconnect(),this.processorNode.port.close(),this.audioContext.close(),this.audioData=[]}},{key:"saveAudio",value:function(){var e=this.encodeWAV(),t=URL.createObjectURL(new Blob([e],{type:"audio/wav"}));this.log("Download Recording: ".concat(t))}},{key:"getBlob",value:function(){var e=this.encodeWAV();console.log(e);var t=new Blob([e],{type:"audio/wav"});return console.log(t),t}},{key:"encodeWAV",value:function(){var e=new DataView(new ArrayBuffer(2*this.audioData.length));this.audioData.forEach((function(t,r){e.setInt16(2*r,t,!0)}));var t=e.buffer.byteLength,r=44+t,n=new DataView(new ArrayBuffer(r));n.setUint32(0,1380533830,!1),n.setUint32(4,r-8,!0),n.setUint32(8,1463899717,!1),n.setUint32(12,1718449184,!1),n.setUint32(16,16,!0),n.setUint16(20,1,!0),n.setUint16(22,1,!0),n.setUint32(24,16e3,!0),n.setUint32(28,32e3,!0),n.setUint16(32,2,!0),n.setUint16(34,16,!0),n.setUint32(36,1684108385,!1),n.setUint32(40,t,!0);for(var i=0;i<t;i++)n.setInt8(44+i,e.getInt8(i));return n}},{key:"log",value:function(e){if(this.enableLogs){var t="".concat((new Date).toLocaleTimeString()," Augnito: ").concat(e);console.log(t+"\n")}}}]),M=function(){function e(){v(this,e)}return y(e,null,[{key:"isBrowserOnline",value:function(){return"undefined"!=typeof navigator&&!0===navigator.onLine}},{key:"hasInternetConnection",value:(r=p(d().mark((function t(){var r,n,i,o,s,a=arguments;return d().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=(r=a.length>0&&void 0!==a[0]?a[0]:{}).url||e.DEFAULT_URL,i=r.timeoutMs||e.DEFAULT_TIMEOUT,e.isBrowserOnline()){t.next=5;break}return t.abrupt("return",!1);case 5:return o=new AbortController,s=setTimeout((function(){return o.abort()}),i),t.prev=7,t.next=10,fetch(n,{method:"HEAD",mode:"no-cors",cache:"no-cache",signal:o.signal});case 10:return t.abrupt("return",!0);case 13:return t.prev=13,t.t0=t.catch(7),t.abrupt("return",!1);case 16:return t.prev=16,clearTimeout(s),t.finish(16);case 19:case"end":return t.stop()}}),t,null,[[7,13,16,19]])}))),function(){return r.apply(this,arguments)})},{key:"isOnline",value:(t=p(d().mark((function t(r){return d().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.abrupt("return",e.hasInternetConnection(r));case 1:case"end":return t.stop()}}),t)}))),function(e){return t.apply(this,arguments)})}]);var t,r}();m(M,"DEFAULT_URL","https://www.google.com/favicon.ico"),m(M,"DEFAULT_TIMEOUT",5e3);var K=function(){function e(){var t,r,n,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{serverURL:"",enableLogs:!1,isDebug:!1,bufferInterval:1,pausedBufferInterval:1,EOS_Message:void 0,socketTimeoutInterval:void 0,shouldSendAudioDataSequence:!1,shouldPreIntialiseRecorder:!1,shouldReadIntensity:!1,debounceDelay:300,switchToRegularSpeechProfile:!1},o=arguments.length>1?arguments[1]:void 0;if(v(this,e),e.instance)return e.instance;this.WebsocketURL=null!==(t=i.serverURL)&&void 0!==t?t:"",this.enableLogs=i.enableLogs,this.isDebug=i.isDebug,this.streamer=null,this.streamerNotStarted=!1,this.isStreamerStarting=!1,this.heavyOp=o,this.bufferInterval=i.bufferInterval,this.pausedBufferInterval=i.pausedBufferInterval,this.eosMessage=i.EOS_Message,this.socketTimeoutInterval=i.socketTimeoutInterval,this.shouldSendAudioDataSequence=i.shouldSendAudioDataSequence,this.shouldPreIntialiseRecorder=i.shouldPreIntialiseRecorder,this.switchToRegularSpeechProfile=null!==(r=i.switchToRegularSpeechProfile)&&void 0!==r&&r,this.shouldPreIntialiseRecorder&&(this.initialiseStreamer(),this.streamerNotStarted=!0),this.shouldReadIntensity=i.shouldReadIntensity,this.delay=null!==(n=i.debounceDelay)&&void 0!==n?n:300,this.toggleStartStopAudioStream=J(this.toggleStartStopAudioStream.bind(this),this.delay),this.togglePauseResumeAudioStream=J(this.togglePauseResumeAudioStream.bind(this),this.delay),e.instance=this}return y(e,[{key:"initialiseStreamer",value:function(){this.streamer=new L(this.enableLogs,this.isDebug,this.bufferInterval,this.pausedBufferInterval,this.eosMessage,this.socketTimeoutInterval,this.shouldSendAudioDataSequence,this.shouldPreIntialiseRecorder,this.shouldReadIntensity,this.switchToRegularSpeechProfile,this.heavyOp,this.onFinalResultCallback.bind(this),this.onPartialResultCallback.bind(this),this.onErrorCallback.bind(this),this.onStateChangedCallback.bind(this),this.onSessionEventCallback.bind(this),this.onOtherResultCallback.bind(this),this.onSpeechResponseCallback.bind(this),this.onIntensityCallback.bind(this))}},{key:"togglePauseResumeAudioStream",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0;!this.streamer||this.streamerNotStarted?(t&&(this.WebsocketURL=t),this.startAudio(e)):this.streamer.IsPaused?this.resumeAudio():this.pauseAudio()}},{key:"toggleStartStopAudioStream",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0;!this.streamer||this.streamerNotStarted?(t&&(this.WebsocketURL=t),this.startAudio(e)):this.stopAudio()}},{key:"startAudio",value:(n=p(d().mark((function e(t){return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,M.isOnline();case 2:if(e.sent){e.next=6;break}return this.onErrorCallback(JSON.stringify({Type:"ERROR",Data:"Internet is not available. Try again later."})),e.abrupt("return");case 6:if(!this.isStreamerStarting){e.next=8;break}return e.abrupt("return");case 8:return this.isStreamerStarting=!0,this.shouldPreIntialiseRecorder&&this.streamer||this.initialiseStreamer(),e.prev=10,e.next=13,this.streamer.StartStream(t,this.WebsocketURL);case 13:e.sent?(this.streamerNotStarted=!1,this.log("Stream Started...")):this.streamer=null;case 15:return e.prev=15,this.isStreamerStarting=!1,e.finish(15);case 18:case"end":return e.stop()}}),e,this,[[10,,15,18]])}))),function(e){return n.apply(this,arguments)})},{key:"pauseAudio",value:function(){this.streamer.PauseStream(),this.log("Stream Paused...")}},{key:"resumeAudio",value:function(){this.streamer.ResumeStream(),this.enableLogs&&this.log("Stream Resumed...")}},{key:"stopAudio",value:(r=p(d().mark((function e(){var t,r,n,i,o=arguments;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=!(o.length>0&&void 0!==o[0])||o[0],n=o.length>1&&void 0!==o[1]&&o[1],!(null!==(t=this.streamer)&&void 0!==t&&t.IsStreaming||n)){e.next=13;break}return e.next=5,M.isOnline();case 5:if(e.sent){e.next=9;break}return this.onErrorCallback(JSON.stringify({Type:"ERROR",Data:"Internet is not available. Try again later."})),e.abrupt("return");case 9:null===(i=this.streamer)||void 0===i||i.StopStream(r),this.streamer=null,this.log("Stream Stopped..."),this.shouldPreIntialiseRecorder&&(this.initialiseStreamer(),this.streamerNotStarted=!0);case 13:case"end":return e.stop()}}),e,this)}))),function(){return r.apply(this,arguments)})},{key:"isInternetAvailable",value:(t=p(d().mark((function e(){var t;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,M.isOnline();case 2:return t=e.sent,e.abrupt("return",t);case 4:case"end":return e.stop()}}),e)}))),function(){return t.apply(this,arguments)})},{key:"getBlob",value:function(){var e=this.streamer.getBlob();return this.log("Blob Sent..."),e}},{key:"log",value:function(e){if(this.enableLogs){var t="".concat((new Date).toLocaleTimeString()," Augnito: ").concat(e);this.showLogCallback(t+"\n")}}},{key:"dispose",value:function(){e.instance=null}},{key:"onSessionEventCallback",value:function(e){this.onSessionEvent&&this.onSessionEvent(e)}},{key:"onStateChangedCallback",value:function(e){this.onStateChanged&&this.onStateChanged(e)}},{key:"onIntensityCallback",value:function(e){this.onIntensity&&this.onIntensity(e)}},{key:"onErrorCallback",value:function(e){this.onError&&this.onError(e)}},{key:"onPartialResultCallback",value:function(e){this.onPartialResult&&this.onPartialResult(e)}},{key:"onFinalResultCallback",value:function(e){this.onFinalResult&&this.onFinalResult(e)}},{key:"onOtherResultCallback",value:function(e){this.onOtherResults&&this.onOtherResults(e)}},{key:"onSpeechResponseCallback",value:function(e){this.onSpeechResponse&&this.onSpeechResponse(e)}},{key:"showLogCallback",value:function(e){this.showLog&&this.showLog(e)}}]);var t,r,n}();function J(e,t){var r;return function(){for(var n=this,i=arguments.length,o=new Array(i),s=0;s<i;s++)o[s]=arguments[s];r&&clearTimeout(r),r=setTimeout((function(){return e.apply(n,o)}),t)}}class W extends c{constructor(e){super(),Object.defineProperty(this,"_config",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"_baseUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._baseUrl=`https://${e.server}/pace/v1/sdk`}getURL(e){return`${this._baseUrl}${e}`}getNoteParams(){return e(this,void 0,void 0,(function*(){const e=this.getURL("/noteparams"),t={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag};return yield this.makePostRequest(e,t)}))}getSettingsConfigMaster(t){return e(this,void 0,void 0,(function*(){const e=this.getURL("/configmaster"),r={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,ConfigTypeId:t};return yield this.makePostRequest(e,r)}))}getUserConfigSettings(t){return e(this,void 0,void 0,(function*(){const e=this.getURL("/userconfigmapping"),r={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,ConfigTypeId:t};return yield this.makePostRequest(e,r)}))}updateUserConfig(t){return e(this,void 0,void 0,(function*(){const e=this.getURL("/userconfigmapping"),r={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,UserConfigMapping:t};return yield this.makePatchRequest(e,r)}))}getUserPreferences(){return e(this,void 0,void 0,(function*(){const e=this.getURL("/getuserpreferences"),t={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag};return yield this.makePostRequest(e,t)}))}updateUserPreference(t,r,n,i,o,s){return e(this,void 0,void 0,(function*(){const e=this.getURL("/postuserpreferences"),a={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,UserPreferences:{AutomaticallyGenerateTranscript:t,PreferredTranscriptionLanguage:r,HighlightMedicalTerms:n,DisplayPatientContext:i,NoteOutputStyle:o,NoteOutputVerbosity:s}};return yield this.makePostRequest(e,a)}))}}const j="Invalid user details, please check again",B="Subscription is not valid.",z="invalid request. Please make sure AccessKey, SubscriptionCode and UserTag is sent along with the request",V="Active seat is not available for user",q="Unable to fetch account details, please try again.",F="Unable to fetch job details, please try again.",H="Job not reconnectable",G="Timeout exceeded",$="Rate Limit Exceeded, Please try again in sometime!",Y="Audio Signal is power very LOW, Mic might be muted",Q="Job Id is empty",X="Page Size is undefined",Z="Note Data is empty",ee="Job Name is empty",te="Patient Context is empty",re="Mic permission denied",ne="Microphone is muted",ie="Audio track ended. Possibly the mic was unplugged",oe="Internet is not available. Try again later.";class se{constructor(e){Object.defineProperty(this,"_logTag",{enumerable:!0,configurable:!0,writable:!0,value:"Augnito-Ambient"}),Object.defineProperty(this,"_ambientRestAPI",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_ambientPaceAPI",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"enableLog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shouldReadAudioIntensity",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"recorderIns",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"forceStopAudio",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_isRecording",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"onJobCreated",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onStateChanged",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onOtherResult",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onIntensityValue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onIdleMic",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._ambientRestAPI=new l(this.validateConfig(e)),this._ambientPaceAPI=new W(e),this.config=this.createSocketConfig(e),this.enableLog=e.enableLogs,this.shouldReadAudioIntensity=e.shouldReadAudioIntensity}initRecorder(e){var t,r;this.recorderIns=new K({serverURL:e,enableLogs:null!==(t=this.enableLog)&&void 0!==t&&t,isDebug:null!==(r=this.enableLog)&&void 0!==r&&r,bufferInterval:15,EOS_Message:'{"JobAction": "EOS","Status": 0,"Type": "meta"}',socketTimeoutInterval:2e4,shouldSendAudioDataSequence:!0,shouldReadIntensity:this.shouldReadAudioIntensity}),this.recorderIns.onError=this.onErrorCallback.bind(this),this.recorderIns.onStateChanged=this.onStateChangeCallback.bind(this),this.recorderIns.onSessionEvent=this.onSessionEventCallback.bind(this),this.recorderIns.onOtherResults=this.onOtherResultsCallback.bind(this),this.recorderIns.onIntensity=this.onIntensityCallback.bind(this)}getNoteParams(){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientPaceAPI.getNoteParams();if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}getAllNotes(t,r){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientRestAPI.ListJobs(t,r);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}getSummarizedNote(t){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientRestAPI.FetchJob(t);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}sendSummarizedNote(t,r){return e(this,void 0,void 0,(function*(){try{return this._ambientRestAPI?yield this._ambientRestAPI.SendFinalNote(t,r):void h.error("SDK not initialized",this._logTag)}catch(e){this.handleException(e)}}))}toggleListening(e,t,r,n,i){var o,s,a=(null===(o=this.config)||void 0===o?void 0:o.prepareWSSURL(e,t,r,n))||"";this.recorderIns||this.initRecorder(a),null===(s=this.recorderIns)||void 0===s||s.toggleStartStopAudioStream(i,a)}togglePauseResumeListening(e,t,r,n,i){var o,s,a=(null===(o=this.config)||void 0===o?void 0:o.prepareWSSURL(e,t,r,n))||"";this.recorderIns||this.initRecorder(a),null===(s=this.recorderIns)||void 0===s||s.togglePauseResumeAudioStream(i,a)}startListening(){var e;null===(e=this.recorderIns)||void 0===e||e.startAudio()}stopListening(){var e;null===(e=this.recorderIns)||void 0===e||e.stopAudio(!0,!0)}deleteNotes(t){var r,n;return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void h.error("SDK not initialized",this._logTag);if(!(yield null===(r=this.recorderIns)||void 0===r?void 0:r.isInternetAvailable()))return void this.onErrorCallback(oe);var e=yield this._ambientRestAPI.DeleteNotes(t);if(e){if(200===e.Status)return null===(n=this.recorderIns)||void 0===n||n.stopAudio(!1,!0),e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}renameNoteTitle(t,r){var n;return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void h.error("SDK not initialized",this._logTag);if(!(yield null===(n=this.recorderIns)||void 0===n?void 0:n.isInternetAvailable()))return void this.onErrorCallback(oe);var e=yield this._ambientRestAPI.RenameNoteTitle(t,r);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}getNotePDF(t,r,n,i,o,s){var a;return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void h.error("SDK not initialized",this._logTag);if(!(yield null===(a=this.recorderIns)||void 0===a?void 0:a.isInternetAvailable()))return void this.onErrorCallback(oe);var e=yield this._ambientRestAPI.DownloadNotePDF(t,r,n,i,o,s);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}endPausedJob(t){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientRestAPI.EndJob(t);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}generateCDISuggestions(t,r,n,i,o){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientRestAPI.GenerateSuggestions(t,r,n,o,i);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}updatePatientContext(t,r,n){var i;return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void h.error("SDK not initialized",this._logTag);if(!(yield null===(i=this.recorderIns)||void 0===i?void 0:i.isInternetAvailable()))return void this.onErrorCallback(oe);var e=yield this._ambientRestAPI.UpdatePatientContext(t,r,n);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}modifyGeneratedNote(t,r,n){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientRestAPI.ModifyGeneratedNote(t,r,n);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}fetchTranscriptionForNote(t){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void h.error("SDK not initialized",this._logTag);if((yield this._ambientPaceAPI.getUserPreferences()).Items[0].AutomaticTranscriptionEnabledForOrg){var e=yield this._ambientRestAPI.FetchTranscription(t);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}else this.onErrorCallback("Automatic Transcription is not enabled for the organisation")}catch(e){this.handleException(e)}}))}getUserConfiguration(t){return e(this,void 0,void 0,(function*(){try{if(!this._ambientPaceAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientPaceAPI.getUserConfigSettings(t);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}updateUserConfiguration(t){return e(this,void 0,void 0,(function*(){try{if(!this._ambientPaceAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientPaceAPI.updateUserConfig(t);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}getUserPreferenceSettings(){return e(this,void 0,void 0,(function*(){try{if(!this._ambientPaceAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientPaceAPI.getUserPreferences();if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}updateUserPreferenceSettings(t){var r,n,i,o,u,c;return e(this,void 0,void 0,(function*(){try{if(!this._ambientPaceAPI)return void h.error("SDK not initialized",this._logTag);var e=yield this._ambientPaceAPI.updateUserPreference(null!==(r=t.AutomaticallyGenerateTranscript)&&void 0!==r&&r,null!==(n=t.PreferredTranscriptionLanguage)&&void 0!==n?n:"English",null!==(i=t.HighlightMedicalTerms)&&void 0!==i&&i,null!==(o=t.DisplayPatientContext)&&void 0!==o&&o,null!==(u=t.NoteOutputStyle)&&void 0!==u?u:a.DashFormat,null!==(c=t.NoteOutputVerbosity)&&void 0!==c?c:s.Detailed);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}onEventCallback(e){this.onJobCreated&&this.onJobCreated(e)}onStateChangeCallback(e){var t;if(this.forceStopAudio)return null===(t=this.recorderIns)||void 0===t||t.stopAudio(!1,!0),void(this.forceStopAudio=!1);this._isRecording=e,this.onStateChanged&&this.onStateChanged(e)}handleException(e){if(e instanceof TypeError)this.onErrorCallback(e.message);else{if(e instanceof u)throw e;h.error(e.message,this._logTag)}}onErrorCallback(e,t){var r,n,i,s,a,u,c,l,d,f,g,p,v,b,y={ErrorCode:null!=t?t:o.ERRUNKNOWN,ErrorMessage:e};try{var m=JSON.parse(e);y.ErrorMessage=m.Data,m.Data===G?(this.stopListening(),h.error("Recording time limit exceeded",this._logTag),y.ErrorCode=o.WSJOB05):m.Data===j?(this._isRecording?null===(r=this.recorderIns)||void 0===r||r.stopAudio(!1,!0):this.forceStopAudio=!0,y.ErrorCode=o.WSAUTH03):m.Data.includes(q)?y.ErrorCode=o.WSAUTH04:m.Data.includes(F)?y.ErrorCode=o.WSJOB01:m.Data.includes(H)?y.ErrorCode=o.WSJOB02:m.Data.includes($)?y.ErrorCode=o.WSACC01:m.Data.includes(Y)&&(y.ErrorCode=o.WSAUD01)}catch(e){}(null===(n=y.ErrorMessage)||void 0===n?void 0:n.includes(Q))?y.ErrorCode=o.SDK01:(null===(i=y.ErrorMessage)||void 0===i?void 0:i.includes(X))?y.ErrorCode=o.SDK02:(null===(s=y.ErrorMessage)||void 0===s?void 0:s.includes(Z))?y.ErrorCode=o.SDK03:(null===(a=y.ErrorMessage)||void 0===a?void 0:a.includes(ee))?y.ErrorCode=o.SDK04:(null===(u=y.ErrorMessage)||void 0===u?void 0:u.includes(te))?y.ErrorCode=o.SDK05:(null===(c=y.ErrorMessage)||void 0===c?void 0:c.includes(re))?y.ErrorCode=o.SDK06:(null===(l=y.ErrorMessage)||void 0===l?void 0:l.includes(ne))?(y.ErrorCode=o.SDK07,null===(d=this.recorderIns)||void 0===d||d.stopAudio(!1,!0)):(null===(f=y.ErrorMessage)||void 0===f?void 0:f.includes(ie))?y.ErrorCode=o.SDK08:(null===(g=y.ErrorMessage)||void 0===g?void 0:g.includes(B))||(null===(p=y.ErrorMessage)||void 0===p?void 0:p.includes(z))?y.ErrorCode=o.AUTH01:(null===(v=y.ErrorMessage)||void 0===v?void 0:v.includes(V))?y.ErrorCode=o.AUTH02:(null===(b=y.ErrorMessage)||void 0===b?void 0:b.includes(oe))&&(y.ErrorCode=o.SDK11),this.onError&&this.onError(y)}onOtherResultsCallback(e){this.onOtherResult&&this.onOtherResult(e)}onIntensityCallback(e){this.onIntensityValue&&this.onIntensityValue(e)}onIdleMicCallback(){this.onIdleMic&&this.onIdleMic()}onSessionEventCallback(e){var t;if(!e)return;let r;try{r="string"==typeof e?JSON.parse(e):e}catch(e){return void h.error(`Error parsing session event data: ${e}`,this._logTag)}if(!r||!("Type"in r))return;if("meta"===r.Type.toLowerCase()&&(null===(t=this.config)||void 0===t?void 0:t.onMetaEvent)){if(!r.JobID)return void h.error("JobID is missing in meta event",this._logTag);this.config.onMetaEvent(r.JobID)}else"error"===r.Type.toLowerCase()&&r.Data&&this.onErrorCallback(r.Data);if("object"!=typeof r.Event||null===r.Event)return;const{Type:n,Value:i}=r.Event;n&&("SESSION_CREATED"===n&&i?h.log(`session Token ${i}`,this._logTag):"SERVICE_DOWN"===n?h.error(n,this._logTag):"NO_DICTATION_STOP_MIC"===n?(h.log("NO_DICTATION_STOP_MIC",this._logTag),this.onIdleMicCallback()):"INVALID_AUTH_CREDENTIALS"===n?h.error("INVALID_AUTH_CREDENTIALS",this._logTag):"LOW_BANDWIDTH"===n&&h.log("LOW_BANDWIDTH: Check internet connection",this._logTag))}validateConfig(e){return r.Against.NullOrEmpty(e.server,"Server"),r.Against.NullOrEmpty(e.subscriptionCode,"SubscriptionCode"),r.Against.NullOrEmpty(e.accessKey,"AccessKey"),r.Against.NullOrEmpty(e.userTag,"UserTag"),e}createSocketConfig(e){const r=new t(e);return r.onError=this.onErrorCallback.bind(this),r.onMetaEvent=this.onEventCallback.bind(this),r}}export{se as AugnitoAmbient,o as ErrorCodes,u as HttpCodedError,a as NoteOutputStyleConfig,i as NoteTypeConfig,s as NoteVerbosityConfig,n as SettingsConfigType};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "testaugnitoambientsdk2",
3
- "version": "2.1.3",
3
+ "version": "2.1.4",
4
4
  "description": "Use this typescript SDK to integrate Augnito’s Ambient Tech within your EMR. To get access credentials or know more about how Augnito Ambient can benefit you, please visit our website and connect with our sales team: https://augnito.ai/",
5
5
  "main": "dist/augnitoambientsdk.js",
6
6
  "types": "dist/index.d.ts",
@@ -237,6 +237,10 @@ export class AugnitoAmbient {
237
237
  Logger.error("SDK not initialized", this._logTag);
238
238
  return;
239
239
  }
240
+ if (!await this.recorderIns?.isInternetAvailable()) {
241
+ this.onErrorCallback(ErrorMessages.noInternetConnection);
242
+ return;
243
+ }
240
244
  var responseJson = await this._ambientRestAPI.DeleteNotes(JobIds);
241
245
  if (responseJson) {
242
246
  if (responseJson.Status === 200) {
@@ -267,6 +271,10 @@ export class AugnitoAmbient {
267
271
  Logger.error("SDK not initialized", this._logTag);
268
272
  return;
269
273
  }
274
+ if (!await this.recorderIns?.isInternetAvailable()) {
275
+ this.onErrorCallback(ErrorMessages.noInternetConnection);
276
+ return;
277
+ }
270
278
  var responseJson = await this._ambientRestAPI.RenameNoteTitle(
271
279
  JobId,
272
280
  NewJobName
@@ -300,6 +308,10 @@ export class AugnitoAmbient {
300
308
  Logger.error("SDK not initialized", this._logTag);
301
309
  return;
302
310
  }
311
+ if (!await this.recorderIns?.isInternetAvailable()) {
312
+ this.onErrorCallback(ErrorMessages.noInternetConnection);
313
+ return;
314
+ }
303
315
  var responseJson = await this._ambientRestAPI.DownloadNotePDF(JobId, NoteType, SpecialityId, Language, PersonnelInfo, RegenerateNote);
304
316
  if (responseJson) {
305
317
  if (responseJson.Status === 200) {
@@ -394,6 +406,10 @@ export class AugnitoAmbient {
394
406
  Logger.error("SDK not initialized", this._logTag);
395
407
  return;
396
408
  }
409
+ if (!await this.recorderIns?.isInternetAvailable()) {
410
+ this.onErrorCallback(ErrorMessages.noInternetConnection);
411
+ return;
412
+ }
397
413
  var responseJson = await this._ambientRestAPI.UpdatePatientContext(
398
414
  JobId,
399
415
  Context,