testaugnitoambientsdk2 2.1.15 → 2.1.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -80,7 +80,7 @@ For the provided subscription code, accesskey and usertag, any authentication fa
80
80
  try {
81
81
  //Get list of specialities enabled for organisation
82
82
  const specialities = await augnitoAmbient.getUserConfiguration(
83
- SettingsConfigType.SPECIALITY,
83
+ SettingsConfigType.SPECIALITY
84
84
  );
85
85
  } catch (err) {
86
86
  if (err instanceof HttpCodedError) {
@@ -97,7 +97,7 @@ For the provided subscription code, accesskey and usertag, any authentication fa
97
97
  try {
98
98
  //Get list of specialities enabled for organisation
99
99
  const specialities = await augnitoAmbient.getUserConfiguration(
100
- SettingsConfigType["SPECIALITY"],
100
+ SettingsConfigType["SPECIALITY"]
101
101
  );
102
102
  } catch (err) {
103
103
  if (err instanceof HttpCodedError) {
@@ -112,7 +112,7 @@ For the provided subscription code, accesskey and usertag, any authentication fa
112
112
  try {
113
113
  //Get list of visit types enabled for organisation
114
114
  const visitTypes = await augnitoAmbient.getUserConfiguration(
115
- SettingsConfigType.VISIT_TYPE,
115
+ SettingsConfigType.VISIT_TYPE
116
116
  );
117
117
  } catch (err) {
118
118
  if (err instanceof HttpCodedError) {
@@ -129,7 +129,7 @@ For the provided subscription code, accesskey and usertag, any authentication fa
129
129
  try {
130
130
  //Get list of visit types enabled for organisation
131
131
  const visitTypes = await augnitoAmbient.getUserConfiguration(
132
- SettingsConfigType["VISIT_TYPE"],
132
+ SettingsConfigType["VISIT_TYPE"]
133
133
  );
134
134
  } catch (err) {
135
135
  if (err instanceof HttpCodedError) {
@@ -613,22 +613,6 @@ Used to fetch Transcription for any note that is recorded. It is essential to en
613
613
  | 500 | Unable to extract transcript data. Please try again. | Failed to complete the operation. Please try again later. | Received when generated SOAP note can not be retrieved |
614
614
  | 500 | Internal Marshaling Error | Failed to complete the operation. Please try again later. | Received when generated transcript is not in expected readable format |
615
615
 
616
- ### 18-Check for Internet Connectivity
617
-
618
- Used to check if browser has access to internet connection or not
619
-
620
- ```js
621
- /**
622
- * @param options an object which is optional and takes custom url as string and timeout in milliseconds, default url - https://www.google.com/favicon.ico, default timeout - 5000
623
- * @returns true if connected else false and onError callback triggered with SDK12
624
- */
625
- public async isInternetAvailable(options?: { url: null; timeoutMs: null; })
626
-
627
- //Usage
628
- var isOnline = await augnitoAmbient.isInternetAvailable();
629
-
630
- ```
631
-
632
616
  ## Note
633
617
 
634
618
  General SDK errors returned in onError callback are as below
@@ -643,4 +627,3 @@ General SDK errors returned in onError callback are as below
643
627
  | SDK06 | Mic permission denied | Conversation cannot be started. Please contact IT support team to enable mic permission. | Received from SDK when the user has not provided mic-permission in browser or OS for recording |
644
628
  | SDK07 | Microphone is muted | Conversation cannot be started. Please ensure the following before starting: <br><br> _ The microphone is unmuted <br> _ The microphone is properly plugged in and not loose <br> _ System input volume is set to maximum <br> _ The correct microphone is selected in your audio settings | Received from SDK at the start of recording, if the microphone is muted |
645
629
  | SDK08 | Audio track ended. Possibly the mic was unplugged | The microphone is unplugged or not properly connected. Please replug the microphone to continue the conversation. | Received from SDK while recording is in-progress and the USB/Jack microphone is unplugged (even though this is not the suggested to mic to use for consultations, we've seen its usage by the doctors) |
646
- | SDK12 | Internet is not available. Try again later. | Action can not be performed. No internet connectivity. Reach out to your IT team. | Received from SDK when internet is not available at the time of specific recording related actions are triggered |
@@ -33,6 +33,9 @@ export declare class AugnitoAmbient {
33
33
  onOtherResult?: (text: string) => void;
34
34
  onIntensityValue?: (intensity: number) => void;
35
35
  onIdleMic?: () => void;
36
+ onSoapNoteGenerated?: (soapNote: string) => void;
37
+ onTranscriptGenerated?: (transcript: string) => void;
38
+ onCodesGenerated?: (codes: string) => void;
36
39
  private initRecorder;
37
40
  /**
38
41
  * Returns the Note parameters which need be use while doing toggle listeing
@@ -69,7 +72,6 @@ export declare class AugnitoAmbient {
69
72
  * @returns Callback triggers to reurn the Job id on meta message
70
73
  */
71
74
  togglePauseResumeListening(_filetype: string, _noteparams: string, jobName?: string, jobId?: string, recordedDuration?: number): void;
72
- uploadAudioFile(_filetype: string, _noteparams: string, fileContent: ArrayBuffer, jobName?: string): void;
73
75
  /**
74
76
  * Method called to start audio recording
75
77
  */
@@ -151,14 +153,6 @@ export declare class AugnitoAmbient {
151
153
  * @returns success response on successful update else fail response
152
154
  */
153
155
  updateUserPreferenceSettings(NewUserPreference: PreferenceConfig): Promise<any>;
154
- /**
155
- * @param options a list of preference of type PreferenceConfig to be updated
156
- * @returns true if connected else false and onError callback triggered with SDK12
157
- */
158
- isInternetAvailable(options?: {
159
- url: null;
160
- timeoutMs: null;
161
- } | undefined): Promise<boolean>;
162
156
  private onEventCallback;
163
157
  private onStateChangeCallback;
164
158
  private handleException;
@@ -166,6 +160,7 @@ export declare class AugnitoAmbient {
166
160
  private onOtherResultsCallback;
167
161
  private onIntensityCallback;
168
162
  private onIdleMicCallback;
163
+ private onSpeechResponseCallback;
169
164
  private onSessionEventCallback;
170
165
  /**
171
166
  * Validates the Ambient config has all the mandatory fields
@@ -1,4 +1,3 @@
1
- import { NoteOutputStyleConfig, NoteVerbosityConfig } from "../config";
2
1
  import AmbientConfig from "../config/AmbientConfig";
3
2
  import { SettingsConfigType, UserConfigMap } from "../config/SettingsConfig";
4
3
  import { BaseAPI } from "./BaseAPI";
@@ -12,5 +11,5 @@ export declare class AmbientPACEAPI extends BaseAPI {
12
11
  getUserConfigSettings(_configTypeId: SettingsConfigType): Promise<any>;
13
12
  updateUserConfig(_updateSettingRequest: UserConfigMap[]): Promise<any>;
14
13
  getUserPreferences(): Promise<any>;
15
- updateUserPreference(_automaticallyGenerateTranscript: boolean, _preferredTranscriptionLanguage: string, _highlightMedicalTerms: boolean, _displayPatientContext: boolean, _noteOutputStyle: NoteOutputStyleConfig, _noteOutputVerbosity: NoteVerbosityConfig): Promise<any>;
14
+ updateUserPreference(_automaticallyGenerateTranscript: boolean, _preferredTranscriptionLanguage: string, _highlightMedicalTerms: boolean, _displayPatientContext: boolean): Promise<any>;
16
15
  }
@@ -1 +1 @@
1
- function e(e,t,i,r){return new(i||(i=Promise))(function(n,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?n(e.value):(t=e.value,t instanceof i?t:new i(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,i,r){let n=this.wssBaseURL;return n+=`?filetype=${e}`,n+=`&noteparams=${t}`,n+=`&subscriptioncode=${this._config.subscriptionCode}`,n+=`&accesskey=${this._config.accessKey}`,n+=`&usertag=${this._config.userTag}`,i&&""!==i&&(n+=`&filename=${i}`),r&&""!==r&&(n+=`&jobid=${r}`),n}}class i{constructor(){}static get Against(){return i.instance||(i.instance=new i),i.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=i.Against.NullOrUndefined(e,t)))throw new TypeError(`${t} is empty`);return e}}var r,n,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"}(n||(n={})),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.SDK12="SDK12",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,i){return e(this,void 0,void 0,function*(){try{const r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});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,i){return e(this,void 0,void 0,function*(){try{const r=yield fetch(t,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});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*(){i.Against.NullOrEmpty(t,"Page Size");const e=this.getURL("/list-jobs"),n={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,PageSize:t,PageID:r};return yield this.makePostRequest(e,n)})}FetchJob(t){return e(this,void 0,void 0,function*(){i.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*(){i.Against.NullOrEmpty(t,"Job Id"),i.Against.NullOrEmpty(r,"Note Data");const e=this.getURL("/send-final-note"),n={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t,SoapData:r};return yield this.makePostRequest(e,n)})}DeleteNotes(t){return e(this,void 0,void 0,function*(){i.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*(){i.Against.NullOrEmpty(t,"Job Id"),i.Against.NullOrEmpty(r,"Job Name");const e=this.getURL("/rename-job"),n={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t,JobName:r};return yield this.makePostRequest(e,n)})}DownloadNotePDF(t,r,n,o,s,a){return e(this,void 0,void 0,function*(){i.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:n,Regenerate:null!=a&&a,PersonnelInfo:u};return yield this.makePostRequest(e,c)})}EndJob(t){return e(this,void 0,void 0,function*(){i.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,n){return e(this,void 0,void 0,function*(){i.Against.NullOrEmpty(t,"Job Id"),i.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:n};return yield this.makePostRequest(e,o)})}GenerateSuggestions(t,r,n,o,s){return e(this,void 0,void 0,function*(){i.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:n,PatientContext:o,Codes:s};return yield this.makePostRequest(e,a)})}ModifyGeneratedNote(t,r,n){return e(this,void 0,void 0,function*(){i.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!=n?n:""};return yield this.makePostRequest(e,o)})}FetchTranscription(t){return e(this,void 0,void 0,function*(){i.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 i=null!=t?t:this.defaultTag;console.log(`${i}:`,e)}static error(e,t){const i=null!=t?t:this.defaultTag;console.error(`${i}:`,e)}}function d(){d=function(){return t};var e,t={},i=Object.prototype,r=i.hasOwnProperty,n=Object.defineProperty||function(e,t,i){e[t]=i.value},o="function"==typeof Symbol?Symbol:{},s=o.iterator||"@@iterator",a=o.asyncIterator||"@@asyncIterator",u=o.toStringTag||"@@toStringTag";function c(e,t,i){return Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,i){return e[t]=i}}function l(e,t,i,r){var o=t&&t.prototype instanceof m?t:m,s=Object.create(o.prototype),a=new O(r||[]);return n(s,"_invoke",{value:w(e,i,a)}),s}function h(e,t,i){try{return{type:"normal",arg:e.call(t,i)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var f="suspendedStart",g="suspendedYield",p="executing",v="completed",b={};function m(){}function y(){}function S(){}var E={};c(E,s,function(){return this});var k=Object.getPrototypeOf,C=k&&k(k(N([])));C&&C!==i&&r.call(C,s)&&(E=C);var A=S.prototype=m.prototype=Object.create(E);function I(e){["next","throw","return"].forEach(function(t){c(e,t,function(e){return this._invoke(t,e)})})}function R(e,t){function i(n,o,s,a){var u=h(e[n],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){i("next",e,s,a)},function(e){i("throw",e,s,a)}):t.resolve(l).then(function(e){c.value=e,s(c)},function(e){return i("throw",e,s,a)})}a(u.arg)}var o;n(this,"_invoke",{value:function(e,r){function n(){return new t(function(t,n){i(e,r,t,n)})}return o=o?o.then(n,n):n()}})}function w(t,i,r){var n=f;return function(o,s){if(n===p)throw Error("Generator is already running");if(n===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(n===f)throw n=v,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n=p;var c=h(t,i,r);if("normal"===c.type){if(n=r.done?v:g,c.arg===b)continue;return{value:c.arg,done:r.done}}"throw"===c.type&&(n=v,r.method="throw",r.arg=c.arg)}}}function P(t,i){var r=i.method,n=t.iterator[r];if(n===e)return i.delegate=null,"throw"===r&&t.iterator.return&&(i.method="return",i.arg=e,P(t,i),"throw"===i.method)||"return"!==r&&(i.method="throw",i.arg=new TypeError("The iterator does not provide a '"+r+"' method")),b;var o=h(n,t.iterator,i.arg);if("throw"===o.type)return i.method="throw",i.arg=o.arg,i.delegate=null,b;var s=o.arg;return s?s.done?(i[t.resultName]=s.value,i.next=t.nextLoc,"return"!==i.method&&(i.method="next",i.arg=e),i.delegate=null,b):s:(i.method="throw",i.arg=new TypeError("iterator result is not an object"),i.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 D(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function O(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(T,this),this.reset(!0)}function N(t){if(t||""===t){var i=t[s];if(i)return i.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var n=-1,o=function i(){for(;++n<t.length;)if(r.call(t,n))return i.value=t[n],i.done=!1,i;return i.value=e,i.done=!0,i};return o.next=o}}throw new TypeError(typeof t+" is not iterable")}return y.prototype=S,n(A,"constructor",{value:S,configurable:!0}),n(S,"constructor",{value:y,configurable:!0}),y.displayName=c(S,u,"GeneratorFunction"),t.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===y||"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(R.prototype),c(R.prototype,a,function(){return this}),t.AsyncIterator=R,t.async=function(e,i,r,n,o){void 0===o&&(o=Promise);var s=new R(l(e,i,r,n),o);return t.isGeneratorFunction(i)?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),i=[];for(var r in t)i.push(r);return i.reverse(),function e(){for(;i.length;){var r=i.pop();if(r in t)return e.value=r,e.done=!1,e}return e.done=!0,e}},t.values=N,O.prototype={constructor:O,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(D),!t)for(var i in this)"t"===i.charAt(0)&&r.call(this,i)&&!isNaN(+i.slice(1))&&(this[i]=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 i=this;function n(r,n){return a.type="throw",a.arg=t,i.next=r,n&&(i.method="next",i.arg=e),!!n}for(var o=this.tryEntries.length-1;o>=0;--o){var s=this.tryEntries[o],a=s.completion;if("root"===s.tryLoc)return n("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 n(s.catchLoc,!0);if(this.prev<s.finallyLoc)return n(s.finallyLoc)}else if(u){if(this.prev<s.catchLoc)return n(s.catchLoc,!0)}else{if(!c)throw Error("try statement without catch or finally");if(this.prev<s.finallyLoc)return n(s.finallyLoc)}}}},abrupt:function(e,t){for(var i=this.tryEntries.length-1;i>=0;--i){var n=this.tryEntries[i];if(n.tryLoc<=this.prev&&r.call(n,"finallyLoc")&&this.prev<n.finallyLoc){var o=n;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 i=this.tryEntries[t];if(i.finallyLoc===e)return this.complete(i.completion,i.afterLoc),D(i),b}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.tryLoc===e){var r=i.completion;if("throw"===r.type){var n=r.arg;D(i)}return n}}throw Error("illegal catch attempt")},delegateYield:function(t,i,r){return this.delegate={iterator:N(t),resultName:i,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 i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.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,i,r,n,o,s){try{var a=e[o](s),u=a.value}catch(e){return void i(e)}a.done?t(u):Promise.resolve(u).then(r,n)}function p(e){return function(){var t=this,i=arguments;return new Promise(function(r,n){var o=e.apply(t,i);function s(e){g(o,r,n,s,a,"next",e)}function a(e){g(o,r,n,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 i=0;i<t.length;i++){var r=t[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,f(r.key),r)}}function m(e,t,i){return t&&b(e.prototype,t),i&&b(e,i),Object.defineProperty(e,"prototype",{writable:!1}),e}Object.defineProperty(h,"defaultTag",{enumerable:!0,configurable:!0,writable:!0,value:"AugnitoAmbientSDK"});var y="DONE",S="PAUSESOCKET",E="RESUMESOCKET",k="INTENT_START_STREAM",C="CLOSE",A=m(function e(t,i,r,n,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=n,this.heavyOp,this.idleLoop,this.lastSent,this.enableLogs=t,this.eosMessage=i||"EOS",this.socketTimeoutInterval=r||1e4,this.bufferSizeInterval=h,this.switchToRegularSpeech=d},[{key:"Start",value:function(e,t,i){var r=this;this.audioDuration=e;var n="\n (() => {\n (".concat(I.toString(),")(").concat(JSON.stringify(y),", ").concat(JSON.stringify(this.eosMessage),", ").concat(JSON.stringify(C),", ").concat(JSON.stringify(1e4),", ").concat(JSON.stringify(this.socketTimeoutInterval),", ").concat(JSON.stringify(12e4),", ").concat(JSON.stringify(1e3),", ").concat(JSON.stringify(100),", ").concat(JSON.stringify(1e4),", ").concat(JSON.stringify(t),", ").concat(JSON.stringify(this.enableLogs),", ").concat(JSON.stringify(this.shouldSendAudioDataSequence),",").concat(JSON.stringify(S),", ").concat(JSON.stringify(E),", ").concat(JSON.stringify(k),", ").concat(JSON.stringify(this.switchToRegularSpeech),", ").concat(JSON.stringify(i),", ").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)}}},{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),i=new DataView(t),r=0;r<4;r++)i.setUint8(r,"@BSR".charCodeAt(r));return i.setBigInt64(4,BigInt(this.packetSeqId),!1),i.setUint8(12,e?1:0),t}},{key:"appendAudioData",value:function(e,t){var i=e.byteLength+t.byteLength,r=new ArrayBuffer(i),n=new Uint8Array(r);return n.set(new Uint8Array(e),0),n.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);else if(e===y)if(this.shouldSendAudioDataSequence){var i,r=this.createAudioPacketHeader(!0);null===(i=this.worker)||void 0===i||i.postMessage(r)}else{var n;null===(n=this.worker)||void 0===n||n.postMessage(y)}else if(e==S){var o;null===(o=this.worker)||void 0===o||o.postMessage(S)}else if(e==E){var s;null===(s=this.worker)||void 0===s||s.postMessage(E)}else if(e==k){var a;null===(a=this.worker)||void 0===a||a.postMessage(k)}else if(e===this.eosMessage){var u;this.shouldSendAudioDataSequence||null===(u=this.worker)||void 0===u||u.postMessage(e)}else{var c,l=[];this.shouldSendAudioDataSequence?(r=this.createAudioPacketHeader(!1),l=this.appendAudioData(r,e)):l=e,void 0!==l&&(null===(c=this.worker)||void 0===c||c.postMessage(l,[l]))}}},{key:"HeavyOp",set:function(e){this.heavyOp=e}}]);function I(e,t,i,r,n,o,s,a,u,c,l,h,d,f,g,p,v,b){var m,y,S,E,k,C,A,I,R,w=[],P=[],T=!1,D=[],O=!1,N=!1,_=!1,U="",x=v;function L(){m=+new Date,(C=""!=U?new WebSocket(c+"&jobid="+U):new WebSocket(c)).onopen=function(e){l&&console.log("Augnito: WebSocket connection established - "+JSON.stringify(e)),D.length>0&&(N=!0)},C.onmessage=function(e){l&&console.log("Augnito: Message from server - "+JSON.stringify(e.data)),S=+new Date,function(e){try{if("PING"===e.data)E=+new Date,self.postMessage({type:"ping",data:e.data});else{var t=JSON.parse(e.data);if(l&&console.log("Augnito [WORKER]: "+JSON.stringify(t)),"meta"==t.Type){t.JobID&&(U=t.JobID,console.log("Augnito JobID:",U)),self.postMessage({type:"meta",data:e.data});var i=JSON.parse(e.data);_=!(!i.Event||"INVALID_AUTH_CREDENTIALS"!==i.Event.Type)}else if(t.Result&&t.Result.Final){var r=JSON.stringify(t.Result);b&&(r=b(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?(D=D.filter(function(e){return e.packetNumber>t.Index}),self.postMessage({type:"other",data:e.data})):"ERROR"==t.Type?("Timeout exceeded"==t.Data&&(O=!0,K()),self.postMessage({type:"error",data:e.data})):self.postMessage({type:"speechResponse",data:e.data})}}catch(e){self.postMessage({type:"error",data:"invalid response"})}}(e)},C.onerror=function(e){console.error("WebSocket error: ",e),self.postMessage({type:"error",data:JSON.stringify(e)})},C.onclose=function(e){l&&console.log("Augnito: WebSocket connection closed - "+JSON.stringify(e)),K()},y=+new Date,S=y,E=+new Date}function M(e){if(C&&C.readyState===WebSocket.OPEN){C.send(e);var i=+new Date;return y<=S&&(S=i-1),y=i,!0}return e===t?(l&&console.warn("Gulping ".concat(t," as socket seems already closed...")),K(),!0):(+new Date-m>r&&!_&&L(),!1)}function J(e){w.push(e)}function K(){O&&(clearInterval(A),clearInterval(I),clearInterval(R),w=[],D=[],self.close())}L(),A=setInterval(function(){if(N){for(var e=0;e<D.length;e++){if(!M(D[e].packetData))break}N=!1}else for(;w.length>0;){var t=w.shift();if(!M(t)){w.unshift(t);break}if(h){var i=new DataView(t),r={packetNumber:Number(i.getBigInt64(4)),packetData:t};D.push(r)}}},a),I=setInterval(function(){if(C&&C.readyState===WebSocket.OPEN){var e=+new Date;(p?y>S&&e-S>n:e-E>n)&&(l&&console.error("No data received since more than ".concat(n/1e3," secs, closing time...")),C.close())}},s),R=setInterval(function(){if(C&&C.readyState===WebSocket.OPEN){var e=+new Date;y&&e-y>o&&(l&&console.warn("No data sent since more than ".concat(o/1e3," secs, closing time...")),C.close())}},u),self.onmessage=function(r){if(r.data===i)U="",O=!0,_=!0,C.close();else if(r.data===e)J(t),U="",l&&console.log("Augnito: Worker received DONE, time to terminate..."),O=!0;else if(r.data===d)x=!0;else if(r.data===g)T=!0;else if(r.data===f){if(J(k),P.length>0)for(var n=0;n<P.length;n++)J(P[n]);P=[],T=!1,x=!1,k=[]}else x&&!T?k=r.data:x&&T?P.push(r.data):J(r.data)}}var R,w,P,T,D,O,N,_,U,x,L=m(function e(t,i,r,n,o,s,a,u,c,l,h,d,f,g,p,b,m,y,S,E,k){v(this,e),this.audioContext,this.audioStream,this.executor=new A(i,s,a,u,g,p,b,y,S,E,n,d),this.executor.HeavyOp=f,this.source,this.processorNode,this.isPaused=!1,this.isStreaming=!1,this.audioData=[],this.isDebug=r,this.enableLogs=i,this.onStateChanged=m,this.onIntensity=k,this.onError=b,this.bufferSizeInterval=n,this.pausedBufferInterval=null!=o?o:1,this.shouldReadIntensity=h,this.closeSocketWithoutEOS=!1,this.shouldPreIntialiseRecorder=null!=l&&l,this.shouldPreIntialiseRecorder&&this.InitialiseMediaStream(c,t)},[{key:"InitialiseMediaStream",value:(x=p(d().mark(function e(t,i){return d().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.createMediaStreamSourceNode();case 2:if(this.source){e.next=5;break}return console.error("Error: unable to create source node"),e.abrupt("return",!1);case 5:return e.next=7,this.createProcessorNode();case 7:if(this.processorNode){e.next=10;break}return console.error("Error: unable to create processor node"),e.abrupt("return",!1);case 10:this.source.connect(this.processorNode).connect(this.audioContext.destination),this.log("AudioContext Sample Rate: "+this.audioContext.sampleRate),""!==i&&this.executor.Start(t,i,this.shouldPreIntialiseRecorder);case 13:case"end":return e.stop()}},e,this)})),function(e,t){return x.apply(this,arguments)})},{key:"StartStream",value:(U=p(d().mark(function e(t,i){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=6;break}return e.next=4,this.InitialiseMediaStream(t,i,!1);case 4:e.next=7;break;case 6:this.shouldPreIntialiseRecorder&&this.executor.Send(E);case 7:if(!this.IsMicrophoneMuted){e.next=13;break}if(!this.audioContext||"running"!=this.audioContext.state){e.next=11;break}return e.next=11,this.audioContext.suspend();case 11:return this.onError(JSON.stringify({Type:"ERROR",Data:"Microphone is muted."})),e.abrupt("return",!1);case 13:return this.onStateChanged(!0),this.isStreaming=!0,e.abrupt("return",!0);case 16:case"end":return e.stop()}},e,this)})),function(e,t){return U.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,i=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(){i.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:(O=p(d().mark(function e(){var t,i,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 i=e.sent,e.next=9,this.audioContext.decodeAudioData(i);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 O.apply(this,arguments)})},{key:"createProcessorNode",value:(D=p(d().mark(function e(){var t,i=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,n=t.value;if(r==y)i.log("Worklet processing done, clearing resources..."),i.isDebug&&i.saveAudio(),i.cleanup();else if(e.data==S)i.executor.Send(S);else{var o;"intensity"===r?null===(o=i.onIntensity)||void 0===o||o.call(i,n):"audioData"===r&&i.isDebug&&new Int16Array(n).forEach(function(e){i.audioData.length<=288e5&&i.audioData.push(e)})}i.executor&&(i.closeSocketWithoutEOS?(i.executor.Send(C),i.closeSocketWithoutEOS=!1):"intensity"!==r&&i.executor.Send(n))},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 D.apply(this,arguments)})},{key:"UploadAudioFile",value:(T=p(d().mark(function e(t,i){var r,n,o,s,a;return d().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t){e.next=3;break}return this.onError(JSON.stringify({Type:"ERROR",Data:"No file provided for upload."})),e.abrupt("return");case 3:if(this.executor){e.next=8;break}return this.onError(JSON.stringify({Type:"ERROR",Data:"Executor not initialized."})),e.abrupt("return");case 8:i&&this.executor.Start(0,i,!1),this.onStateChanged(!0),this.isStreaming=!0,r=t,n=24e4,o=Math.ceil(r.byteLength/n),s=0;case 15:if(!(s<o)){e.next=23;break}return a=r.slice(s*n,(s+1)*n),this.executor.Send(a),e.next=20,this.delay(500);case 20:s++,e.next=15;break;case 23:this.executor.Send(y),this.onStateChanged(!1),this.isStreaming=!1;case 26:case"end":return e.stop()}},e,this)})),function(e,t){return T.apply(this,arguments)})},{key:"PauseStream",value:(P=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=9;break}if(this.shouldPreIntialiseRecorder){e.next=8;break}return e.next=4,this.audioContext.suspend();case 4:this.log("Stream paused..."),this.processorNode.port.postMessage("PAUSE"),e.next=9;break;case 8:this.processorNode.port.postMessage(S);case 9:this.onStateChanged(!1),this.isPaused=!0,this.isStreaming=!1;case 12:case"end":return e.stop()}},e,this)})),function(){return P.apply(this,arguments)})},{key:"ResumeStream",value:(w=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(E),this.executor.Send(E);case 11:this.onStateChanged(!0),this.isPaused=!1,this.isStreaming=!0;case 14:case"end":return e.stop()}},e,this)})),function(){return w.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 i,r,n,o;return d().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if("suspended"===(null===(i=this.audioContext)||void 0===i?void 0:i.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===(n=this.audioStream)||void 0===n||n.getAudioTracks()[0].removeEventListener("ended",function(){});case 9:case"end":return e.stop()}},e,this)})),function(e){return R.apply(this,arguments)})},{key:"IntentStartStream",value:function(){this.executor.Send("INTENT_START_STREAM")}},{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:"delay",value:function(e){return new Promise(function(t){return setTimeout(t,e)})}},{key:"encodeWAV",value:function(){var e=new DataView(new ArrayBuffer(2*this.audioData.length));this.audioData.forEach(function(t,i){e.setInt16(2*i,t,!0)});var t=e.buffer.byteLength,i=44+t,r=new DataView(new ArrayBuffer(i));r.setUint32(0,1380533830,!1),r.setUint32(4,i-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 n=0;n<t;n++)r.setInt8(44+n,e.getInt8(n));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(){var t,i,r,n,o=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,reconnectAudioDuration:0,shouldPreIntialiseRecorder:!1,shouldReadIntensity:!1,debounceDelay:300,switchToRegularSpeechProfile:!1},s=arguments.length>1?arguments[1]:void 0;if(v(this,e),e.instance)return e.instance;this.WebsocketURL=null!==(t=o.serverURL)&&void 0!==t?t:"",this.enableLogs=o.enableLogs,this.isDebug=o.isDebug,this.streamer=null,this.streamerNotStarted=!1,this.isStreamerStarting=!1,this.pendingStartStream=!1,this.heavyOp=s,this.bufferInterval=o.bufferInterval,this.pausedBufferInterval=o.pausedBufferInterval,this.eosMessage=o.EOS_Message,this.socketTimeoutInterval=o.socketTimeoutInterval,this.shouldSendAudioDataSequence=o.shouldSendAudioDataSequence,this.reconnectAudioDuration=null!==(i=o.reconnectAudioDuration)&&void 0!==i?i:0,this.shouldPreIntialiseRecorder=o.shouldPreIntialiseRecorder,this.switchToRegularSpeechProfile=null!==(r=o.switchToRegularSpeechProfile)&&void 0!==r&&r,this.shouldPreIntialiseRecorder&&(this.initialiseStreamer(),this.streamerNotStarted=!0),this.shouldReadIntensity=o.shouldReadIntensity,this.delay=null!==(n=o.debounceDelay)&&void 0!==n?n:300,this.toggleStartStopAudioStream=J(this.toggleStartStopAudioStream.bind(this),this.delay),this.togglePauseResumeAudioStream=J(this.togglePauseResumeAudioStream.bind(this),this.delay),this.needsDispose=!1,e.instance=this}return m(e,[{key:"initialiseStreamer",value:function(){this.streamer=new L(this.WebsocketURL,this.enableLogs,this.isDebug,this.bufferInterval,this.pausedBufferInterval,this.eosMessage,this.socketTimeoutInterval,this.shouldSendAudioDataSequence,this.reconnectAudioDuration,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:"updateIntentStartStream",value:function(){var e;this.pendingStartStream=!0,null===(e=this.streamer)||void 0===e||e.IntentStartStream()}},{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:(i=p(d().mark(function e(t){return d().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.isStreamerStarting){e.next=2;break}return e.abrupt("return");case 2:return this.isStreamerStarting=!0,this.shouldPreIntialiseRecorder&&this.streamer||this.initialiseStreamer(),e.prev=4,e.next=7,this.streamer.StartStream(t,this.WebsocketURL);case 7:e.sent?(this.streamerNotStarted=!1,this.log("Stream Started...")):this.streamer=null;case 9:return e.prev=9,this.isStreamerStarting=!1,e.finish(9);case 12:case"end":return e.stop()}},e,this,[[4,,9,12]])})),function(e){return i.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:function(){var e,t,i=this,r=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];(null!==(e=this.streamer)&&void 0!==e&&e.IsStreaming||n)&&(null===(t=this.streamer)||void 0===t||t.StopStream(r),this.streamer=null,this.log("Stream Stopped..."),this.shouldPreIntialiseRecorder&&setTimeout(function(){i.needsDispose?i.needsDispose=!1:(i.initialiseStreamer(),i.streamerNotStarted=!0)},500))}},{key:"uploadAudioFile",value:(t=p(d().mark(function e(t){var i,r=arguments;return d().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return i=r.length>1&&void 0!==r[1]?r[1]:void 0,this.streamer||this.initialiseStreamer(),e.next=4,this.streamer.UploadAudioFile(t,i);case 4:this.log("Audio File Uploaded..."),this.streamer=null;case 6:case"end":return e.stop()}},e,this)})),function(e){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(){var t;this.needsDispose=!0,null===(t=this.streamer)||void 0===t||t.StopStream(!1),this.streamer=null,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,i}();function J(e,t){var i;return function(){for(var r=this,n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];i&&clearTimeout(i),i=setTimeout(function(){return e.apply(r,o)},t)}}class K 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"),i={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,ConfigTypeId:t};return yield this.makePostRequest(e,i)})}getUserConfigSettings(t){return e(this,void 0,void 0,function*(){const e=this.getURL("/userconfigmapping"),i={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,ConfigTypeId:t};return yield this.makePostRequest(e,i)})}updateUserConfig(t){return e(this,void 0,void 0,function*(){const e=this.getURL("/userconfigmapping"),i={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,UserConfigMapping:t};return yield this.makePatchRequest(e,i)})}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,i,r,n,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:i,HighlightMedicalTerms:r,DisplayPatientContext:n,NoteOutputStyle:o,NoteOutputVerbosity:s}};return yield this.makePostRequest(e,a)})}}const W="Invalid user details, please check again",j="Subscription is not valid.",B="invalid request. Please make sure AccessKey, SubscriptionCode and UserTag is sent along with the request",z="Active seat is not available for user",F="Unable to fetch account details, please try again.",V="Unable to fetch job details, please try again.",q="Job not reconnectable",H="Timeout exceeded",G="Rate Limit Exceeded, Please try again in sometime!",$="Audio Signal is power very LOW, Mic might be muted",Y="Job Id is empty",Q="Page Size is undefined",X="Note Data is empty",Z="Job Name is empty",ee="Patient Context is empty",te="Mic permission denied",ie="Microphone is muted",re="Audio track ended. Possibly the mic was unplugged",ne="Internet is not available. Try again later.";class oe{static isBrowserOnline(){return"undefined"!=typeof navigator&&!0===navigator.onLine}static isValidHttpUrl(e){if("string"!=typeof e||e.length>2048)return!1;try{const t=new URL(e);return("http:"===t.protocol||"https:"===t.protocol)&&(!t.username&&!t.password)}catch(e){return!1}}static hasInternetConnection(){return e(this,arguments,void 0,function*(e={url:null,timeoutMs:null}){var t=e.url||oe.DEFAULT_URL;const i=e.timeoutMs||oe.DEFAULT_TIMEOUT;if(!oe.isBrowserOnline())return!1;oe.isValidHttpUrl(t)||(t=oe.DEFAULT_URL);const r=new AbortController,n=setTimeout(()=>r.abort(),i);try{return yield fetch(t,{method:"HEAD",mode:"no-cors",cache:"no-cache",signal:r.signal}),!0}catch(e){return!1}finally{clearTimeout(n)}})}static isOnline(t){return e(this,void 0,void 0,function*(){return oe.hasInternetConnection(t)})}}Object.defineProperty(oe,"DEFAULT_URL",{enumerable:!0,configurable:!0,writable:!0,value:"https://www.google.com/favicon.ico"}),Object.defineProperty(oe,"DEFAULT_TIMEOUT",{enumerable:!0,configurable:!0,writable:!0,value:5e3});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 K(e),this.config=this.createSocketConfig(e),this.enableLog=e.enableLogs,this.shouldReadAudioIntensity=e.shouldReadAudioIntensity}initRecorder(e){var t,i;this.recorderIns=new M({serverURL:e,enableLogs:null!==(t=this.enableLog)&&void 0!==t&&t,isDebug:null!==(i=this.enableLog)&&void 0!==i&&i,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,i){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,i);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,i){return e(this,void 0,void 0,function*(){try{return this._ambientRestAPI?yield this._ambientRestAPI.SendFinalNote(t,i):void h.error("SDK not initialized",this._logTag)}catch(e){this.handleException(e)}})}toggleListening(e,t,i,r,n){var o,s,a=(null===(o=this.config)||void 0===o?void 0:o.prepareWSSURL(e,t,i,r))||"";this.recorderIns||this.initRecorder(a),null===(s=this.recorderIns)||void 0===s||s.toggleStartStopAudioStream(n,a)}togglePauseResumeListening(e,t,i,r,n){var o,s,a=(null===(o=this.config)||void 0===o?void 0:o.prepareWSSURL(e,t,i,r))||"";this.recorderIns||this.initRecorder(a),null===(s=this.recorderIns)||void 0===s||s.togglePauseResumeAudioStream(n,a)}uploadAudioFile(e,t,i,r){var n,o,s=(null===(n=this.config)||void 0===n?void 0:n.prepareWSSURL(e,t,r))||"";this.recorderIns||this.initRecorder(s),null===(o=this.recorderIns)||void 0===o||o.uploadAudioFile(i,s)}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){return e(this,void 0,void 0,function*(){var e;try{if(!this._ambientRestAPI)return void h.error("SDK not initialized",this._logTag);var i=yield this._ambientRestAPI.DeleteNotes(t);if(i){if(200===i.Status)return null===(e=this.recorderIns)||void 0===e||e.stopAudio(!1,!0),i;this.onErrorCallback(i.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}})}renameNoteTitle(t,i){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,i);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}})}getNotePDF(t,i,r,n,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,i,r,n,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,i,r,n,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,i,r,o,n);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}})}updatePatientContext(t,i,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,i,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,i,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,i,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){return e(this,void 0,void 0,function*(){var e,i,r,n,o,u;try{if(!this._ambientPaceAPI)return void h.error("SDK not initialized",this._logTag);var c=yield this._ambientPaceAPI.updateUserPreference(null!==(e=t.AutomaticallyGenerateTranscript)&&void 0!==e&&e,null!==(i=t.PreferredTranscriptionLanguage)&&void 0!==i?i:"English",null!==(r=t.HighlightMedicalTerms)&&void 0!==r&&r,null!==(n=t.DisplayPatientContext)&&void 0!==n&&n,null!==(o=t.NoteOutputStyle)&&void 0!==o?o:a.DashFormat,null!==(u=t.NoteOutputVerbosity)&&void 0!==u?u:s.Detailed);if(c){if(200===c.Status)return c;this.onErrorCallback(c.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}})}isInternetAvailable(t){return e(this,void 0,void 0,function*(){const e=yield oe.isOnline(t);return e||this.onErrorCallback(ne),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 i,r,n,s,a,u,c,l,d,f,g,p,v,b,m={ErrorCode:null!=t?t:o.ERRUNKNOWN,ErrorMessage:e};try{var y=JSON.parse(e);m.ErrorMessage=y.Data,y.Data===H?(this.stopListening(),h.error("Recording time limit exceeded",this._logTag),m.ErrorCode=o.WSJOB05):y.Data===W?(this._isRecording?null===(i=this.recorderIns)||void 0===i||i.stopAudio(!1,!0):this.forceStopAudio=!0,m.ErrorCode=o.WSAUTH03):y.Data.includes(F)?m.ErrorCode=o.WSAUTH04:y.Data.includes(V)?m.ErrorCode=o.WSJOB01:y.Data.includes(q)?m.ErrorCode=o.WSJOB02:y.Data.includes(G)?m.ErrorCode=o.WSACC01:y.Data.includes($)&&(m.ErrorCode=o.WSAUD01)}catch(e){}(null===(r=m.ErrorMessage)||void 0===r?void 0:r.includes(Y))?m.ErrorCode=o.SDK01:(null===(n=m.ErrorMessage)||void 0===n?void 0:n.includes(Q))?m.ErrorCode=o.SDK02:(null===(s=m.ErrorMessage)||void 0===s?void 0:s.includes(X))?m.ErrorCode=o.SDK03:(null===(a=m.ErrorMessage)||void 0===a?void 0:a.includes(Z))?m.ErrorCode=o.SDK04:(null===(u=m.ErrorMessage)||void 0===u?void 0:u.includes(ee))?m.ErrorCode=o.SDK05:(null===(c=m.ErrorMessage)||void 0===c?void 0:c.includes(te))?m.ErrorCode=o.SDK06:(null===(l=m.ErrorMessage)||void 0===l?void 0:l.includes(ie))?(m.ErrorCode=o.SDK07,null===(d=this.recorderIns)||void 0===d||d.stopAudio(!1,!0)):(null===(f=m.ErrorMessage)||void 0===f?void 0:f.includes(re))?m.ErrorCode=o.SDK08:(null===(g=m.ErrorMessage)||void 0===g?void 0:g.includes(j))||(null===(p=m.ErrorMessage)||void 0===p?void 0:p.includes(B))?m.ErrorCode=o.AUTH01:(null===(v=m.ErrorMessage)||void 0===v?void 0:v.includes(z))?m.ErrorCode=o.AUTH02:(null===(b=m.ErrorMessage)||void 0===b?void 0:b.includes(ne))&&(m.ErrorCode=o.SDK12),this.onError&&this.onError(m)}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 i;try{i="string"==typeof e?JSON.parse(e):e}catch(e){return void h.error(`Error parsing session event data: ${e}`,this._logTag)}if(!i||!("Type"in i))return;if("meta"===i.Type.toLowerCase()&&(null===(t=this.config)||void 0===t?void 0:t.onMetaEvent)){if(!i.JobID)return void h.error("JobID is missing in meta event",this._logTag);this.config.onMetaEvent(i.JobID)}else"error"===i.Type.toLowerCase()&&i.Data&&this.onErrorCallback(i.Data);if("object"!=typeof i.Event||null===i.Event)return;const{Type:r,Value:n}=i.Event;r&&("SESSION_CREATED"===r&&n?h.log(`session Token ${n}`,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 i.Against.NullOrEmpty(e.server,"Server"),i.Against.NullOrEmpty(e.subscriptionCode,"SubscriptionCode"),i.Against.NullOrEmpty(e.accessKey,"AccessKey"),i.Against.NullOrEmpty(e.userTag,"UserTag"),e}createSocketConfig(e){const i=new t(e);return i.onError=this.onErrorCallback.bind(this),i.onMetaEvent=this.onEventCallback.bind(this),i}}export{se as AugnitoAmbient,o as ErrorCodes,u as HttpCodedError,a as NoteOutputStyleConfig,n as NoteTypeConfig,s as NoteVerbosityConfig,r as SettingsConfigType};
1
+ function e(e,t,i,n){return new(i||(i=Promise))((function(r,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?r(e.value):(t=e.value,t instanceof i?t:new i((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,i,n){let r=this.wssBaseURL;return r+=`?filetype=${e}`,r+=`&noteparams=${t}`,r+=`&subscriptioncode=${this._config.subscriptionCode}`,r+=`&accesskey=${this._config.accessKey}`,r+=`&usertag=${this._config.userTag}`,i&&""!==i&&(r+=`&filename=${i}`),n&&""!==n&&(r+=`&jobid=${n}`),r}}class i{constructor(){}static get Against(){return i.instance||(i.instance=new i),i.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=i.Against.NullOrUndefined(e,t)))throw new TypeError(`${t} is empty`);return e}}var n,r,o;!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"}(r||(r={})),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.ERRUNKNOWN="ERRUNKNOWN"}(o||(o={}));class s 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,s.prototype)}}class a{makePostRequest(t,i){return e(this,void 0,void 0,(function*(){try{const n=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!n.ok){const t=yield n.text();var e=JSON.parse(t);throw new s(e.message,e.code.toString())}return yield n.json()}catch(e){throw e}}))}makePatchRequest(t,i){return e(this,void 0,void 0,(function*(){try{const n=yield fetch(t,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!n.ok){const t=yield n.text();var e=JSON.parse(t);throw new s(e.message,n.status.toString())}return yield n.json()}catch(e){throw e instanceof s?e:new s("500",e.message||"Unexpected error")}}))}}class u extends a{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*(){i.Against.NullOrEmpty(t,"Page Size");const e=this.getURL("/list-jobs"),r={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,PageSize:t,PageID:n};return yield this.makePostRequest(e,r)}))}FetchJob(t){return e(this,void 0,void 0,(function*(){i.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*(){i.Against.NullOrEmpty(t,"Job Id"),i.Against.NullOrEmpty(n,"Note Data");const e=this.getURL("/send-final-note"),r={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t,SoapData:n};return yield this.makePostRequest(e,r)}))}DeleteNotes(t){return e(this,void 0,void 0,(function*(){i.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*(){i.Against.NullOrEmpty(t,"Job Id"),i.Against.NullOrEmpty(n,"Job Name");const e=this.getURL("/rename-job"),r={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t,JobName:n};return yield this.makePostRequest(e,r)}))}DownloadNotePDF(t,n,r,o,s,a){return e(this,void 0,void 0,(function*(){i.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:r,Regenerate:null!=a&&a,PersonnelInfo:u};return yield this.makePostRequest(e,c)}))}EndJob(t){return e(this,void 0,void 0,(function*(){i.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,r){return e(this,void 0,void 0,(function*(){i.Against.NullOrEmpty(t,"Job Id"),i.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:r};return yield this.makePostRequest(e,o)}))}GenerateSuggestions(t,n,r,o,s){return e(this,void 0,void 0,(function*(){i.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:r,PatientContext:o,Codes:s};return yield this.makePostRequest(e,a)}))}ModifyGeneratedNote(t,n,r){return e(this,void 0,void 0,(function*(){i.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!=r?r:""};return yield this.makePostRequest(e,o)}))}FetchTranscription(t){return e(this,void 0,void 0,(function*(){i.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 c{static log(e,t){const i=null!=t?t:this.defaultTag;console.log(`${i}:`,e)}static error(e,t){const i=null!=t?t:this.defaultTag;console.error(`${i}:`,e)}}function l(){l=function(){return t};var e,t={},i=Object.prototype,n=i.hasOwnProperty,r=Object.defineProperty||function(e,t,i){e[t]=i.value},o="function"==typeof Symbol?Symbol:{},s=o.iterator||"@@iterator",a=o.asyncIterator||"@@asyncIterator",u=o.toStringTag||"@@toStringTag";function c(e,t,i){return Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,i){return e[t]=i}}function h(e,t,i,n){var o=t&&t.prototype instanceof m?t:m,s=Object.create(o.prototype),a=new D(n||[]);return r(s,"_invoke",{value:w(e,i,a)}),s}function d(e,t,i){try{return{type:"normal",arg:e.call(t,i)}}catch(e){return{type:"throw",arg:e}}}t.wrap=h;var f="suspendedStart",g="suspendedYield",p="executing",v="completed",b={};function m(){}function y(){}function S(){}var E={};c(E,s,(function(){return this}));var k=Object.getPrototypeOf,C=k&&k(k(N([])));C&&C!==i&&n.call(C,s)&&(E=C);var A=S.prototype=m.prototype=Object.create(E);function I(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function R(e,t){function i(r,o,s,a){var u=d(e[r],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){i("next",e,s,a)}),(function(e){i("throw",e,s,a)})):t.resolve(l).then((function(e){c.value=e,s(c)}),(function(e){return i("throw",e,s,a)}))}a(u.arg)}var o;r(this,"_invoke",{value:function(e,n){function r(){return new t((function(t,r){i(e,n,t,r)}))}return o=o?o.then(r,r):r()}})}function w(t,i,n){var r=f;return function(o,s){if(r===p)throw Error("Generator is already running");if(r===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(r===f)throw r=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r=p;var c=d(t,i,n);if("normal"===c.type){if(r=n.done?v:g,c.arg===b)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(r=v,n.method="throw",n.arg=c.arg)}}}function P(t,i){var n=i.method,r=t.iterator[n];if(r===e)return i.delegate=null,"throw"===n&&t.iterator.return&&(i.method="return",i.arg=e,P(t,i),"throw"===i.method)||"return"!==n&&(i.method="throw",i.arg=new TypeError("The iterator does not provide a '"+n+"' method")),b;var o=d(r,t.iterator,i.arg);if("throw"===o.type)return i.method="throw",i.arg=o.arg,i.delegate=null,b;var s=o.arg;return s?s.done?(i[t.resultName]=s.value,i.next=t.nextLoc,"return"!==i.method&&(i.method="next",i.arg=e),i.delegate=null,b):s:(i.method="throw",i.arg=new TypeError("iterator result is not an object"),i.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 i=t[s];if(i)return i.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var r=-1,o=function i(){for(;++r<t.length;)if(n.call(t,r))return i.value=t[r],i.done=!1,i;return i.value=e,i.done=!0,i};return o.next=o}}throw new TypeError(typeof t+" is not iterable")}return y.prototype=S,r(A,"constructor",{value:S,configurable:!0}),r(S,"constructor",{value:y,configurable:!0}),y.displayName=c(S,u,"GeneratorFunction"),t.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===y||"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(R.prototype),c(R.prototype,a,(function(){return this})),t.AsyncIterator=R,t.async=function(e,i,n,r,o){void 0===o&&(o=Promise);var s=new R(h(e,i,n,r),o);return t.isGeneratorFunction(i)?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),i=[];for(var n in t)i.push(n);return i.reverse(),function e(){for(;i.length;){var n=i.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 i in this)"t"===i.charAt(0)&&n.call(this,i)&&!isNaN(+i.slice(1))&&(this[i]=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 i=this;function r(n,r){return a.type="throw",a.arg=t,i.next=n,r&&(i.method="next",i.arg=e),!!r}for(var o=this.tryEntries.length-1;o>=0;--o){var s=this.tryEntries[o],a=s.completion;if("root"===s.tryLoc)return r("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 r(s.catchLoc,!0);if(this.prev<s.finallyLoc)return r(s.finallyLoc)}else if(u){if(this.prev<s.catchLoc)return r(s.catchLoc,!0)}else{if(!c)throw Error("try statement without catch or finally");if(this.prev<s.finallyLoc)return r(s.finallyLoc)}}}},abrupt:function(e,t){for(var i=this.tryEntries.length-1;i>=0;--i){var r=this.tryEntries[i];if(r.tryLoc<=this.prev&&n.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var o=r;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 i=this.tryEntries[t];if(i.finallyLoc===e)return this.complete(i.completion,i.afterLoc),O(i),b}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.tryLoc===e){var n=i.completion;if("throw"===n.type){var r=n.arg;O(i)}return r}}throw Error("illegal catch attempt")},delegateYield:function(t,i,n){return this.delegate={iterator:N(t),resultName:i,nextLoc:n},"next"===this.method&&(this.arg=e),b}},t}function h(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.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 d(e,t,i,n,r,o,s){try{var a=e[o](s),u=a.value}catch(e){return void i(e)}a.done?t(u):Promise.resolve(u).then(n,r)}function f(e){return function(){var t=this,i=arguments;return new Promise((function(n,r){var o=e.apply(t,i);function s(e){d(o,n,r,s,a,"next",e)}function a(e){d(o,n,r,s,a,"throw",e)}s(void 0)}))}}function g(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function p(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,h(n.key),n)}}function v(e,t,i){return t&&p(e.prototype,t),i&&p(e,i),Object.defineProperty(e,"prototype",{writable:!1}),e}Object.defineProperty(c,"defaultTag",{enumerable:!0,configurable:!0,writable:!0,value:"AugnitoAmbientSDK"});var b="DONE",m="PAUSESOCKET",y="RESUMESOCKET",S="INTENT_START_STREAM",E="CLOSE",k=v((function e(t,i,n,r,o,s,a,u,c,l,h,d){g(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=r,this.heavyOp,this.idleLoop,this.lastSent,this.enableLogs=t,this.eosMessage=i||"EOS",this.socketTimeoutInterval=n||1e4,this.bufferSizeInterval=h,this.switchToRegularSpeech=d}),[{key:"Start",value:function(e,t,i){var n=this;this.audioDuration=e;var r="\n (() => {\n (".concat(C.toString(),")(").concat(JSON.stringify(b),", ").concat(JSON.stringify(this.eosMessage),", ").concat(JSON.stringify(E),", ").concat(JSON.stringify(1e4),", ").concat(JSON.stringify(this.socketTimeoutInterval),", ").concat(JSON.stringify(12e4),", ").concat(JSON.stringify(1e3),", ").concat(JSON.stringify(100),", ").concat(JSON.stringify(1e4),", ").concat(JSON.stringify(t),", ").concat(JSON.stringify(this.enableLogs),", ").concat(JSON.stringify(this.shouldSendAudioDataSequence),",").concat(JSON.stringify(m),", ").concat(JSON.stringify(y),", ").concat(JSON.stringify(S),", ").concat(JSON.stringify(this.switchToRegularSpeech),", ").concat(JSON.stringify(i),", ").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)}}},{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),i=new DataView(t),n=0;n<4;n++)i.setUint8(n,"@BSR".charCodeAt(n));return i.setBigInt64(4,BigInt(this.packetSeqId),!1),i.setUint8(12,e?1:0),t}},{key:"appendAudioData",value:function(e,t){var i=e.byteLength+t.byteLength,n=new ArrayBuffer(i),r=new Uint8Array(n);return r.set(new Uint8Array(e),0),r.set(new Uint8Array(t),e.byteLength),n}},{key:"Send",value:function(e){var t;if(this.lastSent=+new Date,e===E)null===(t=this.worker)||void 0===t||t.postMessage(E);else if(e===b)if(this.shouldSendAudioDataSequence){var i,n=this.createAudioPacketHeader(!0);null===(i=this.worker)||void 0===i||i.postMessage(n)}else{var r;null===(r=this.worker)||void 0===r||r.postMessage(b)}else if(e==m){var o;null===(o=this.worker)||void 0===o||o.postMessage(m)}else if(e==y){var s;null===(s=this.worker)||void 0===s||s.postMessage(y)}else if(e==S){var a;null===(a=this.worker)||void 0===a||a.postMessage(S)}else if(e===this.eosMessage){var u;this.shouldSendAudioDataSequence||null===(u=this.worker)||void 0===u||u.postMessage(e)}else{var c,l=[];this.shouldSendAudioDataSequence?(n=this.createAudioPacketHeader(!1),l=this.appendAudioData(n,e)):l=e,void 0!==l&&(null===(c=this.worker)||void 0===c||c.postMessage(l,[l]))}}},{key:"HeavyOp",set:function(e){this.heavyOp=e}}]);function C(e,t,i,n,r,o,s,a,u,c,l,h,d,f,g,p,v,b){var m,y,S,E,k,C,A,I,R,w=[],P=[],T=!1,O=[],D=!1,N=!1,_=!1,U="",x=v;function L(){m=+new Date,(C=""!=U?new WebSocket(c+"&jobid="+U):new WebSocket(c)).onopen=function(e){l&&console.log("Augnito: WebSocket connection established - "+JSON.stringify(e)),O.length>0&&(N=!0)},C.onmessage=function(e){l&&console.log("Augnito: Message from server - "+JSON.stringify(e.data)),S=+new Date,function(e){try{if("PING"===e.data)E=+new Date,self.postMessage({type:"ping",data:e.data});else{var t=JSON.parse(e.data);if(l&&console.log("Augnito [WORKER]: "+JSON.stringify(t)),"meta"==t.Type){t.JobID&&(U=t.JobID,console.log("Augnito JobID:",U)),self.postMessage({type:"meta",data:e.data});var i=JSON.parse(e.data);_=!(!i.Event||"INVALID_AUTH_CREDENTIALS"!==i.Event.Type)}else if(t.Result&&t.Result.Final){var n=JSON.stringify(t.Result);b&&(n=b(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?(O=O.filter((function(e){return e.packetNumber>t.Index})),self.postMessage({type:"other",data:e.data})):"ERROR"==t.Type?("Timeout exceeded"==t.Data&&(D=!0,K()),self.postMessage({type:"error",data:e.data})):self.postMessage({type:"speechResponse",data:e.data})}}catch(e){self.postMessage({type:"error",data:"invalid response"})}}(e)},C.onerror=function(e){console.error("WebSocket error: ",e),self.postMessage({type:"error",data:JSON.stringify(e)})},C.onclose=function(e){l&&console.log("Augnito: WebSocket connection closed - "+JSON.stringify(e)),K()},y=+new Date,S=y,E=+new Date}function M(e){if(C&&C.readyState===WebSocket.OPEN){C.send(e);var i=+new Date;return y<=S&&(S=i-1),y=i,!0}return e===t?(l&&console.warn("Gulping ".concat(t," as socket seems already closed...")),K(),!0):(+new Date-m>n&&!_&&L(),!1)}function J(e){w.push(e)}function K(){D&&(clearInterval(A),clearInterval(I),clearInterval(R),w=[],O=[],self.close())}L(),A=setInterval((function(){if(N){for(var e=0;e<O.length;e++){if(!M(O[e].packetData))break}N=!1}else for(;w.length>0;){var t=w.shift();if(!M(t)){w.unshift(t);break}if(h){var i=new DataView(t),n={packetNumber:Number(i.getBigInt64(4)),packetData:t};O.push(n)}}}),a),I=setInterval((function(){if(C&&C.readyState===WebSocket.OPEN){var e=+new Date;(p?y>S&&e-S>r:e-E>r)&&(l&&console.error("No data received since more than ".concat(r/1e3," secs, closing time...")),C.close())}}),s),R=setInterval((function(){if(C&&C.readyState===WebSocket.OPEN){var e=+new Date;y&&e-y>o&&(l&&console.warn("No data sent since more than ".concat(o/1e3," secs, closing time...")),C.close())}}),u),self.onmessage=function(n){if(n.data===i)U="",D=!0,_=!0,C.close();else if(n.data===e)J(t),U="",l&&console.log("Augnito: Worker received DONE, time to terminate..."),D=!0;else if(n.data===d)x=!0;else if(n.data===g)T=!0;else if(n.data===f){if(J(k),P.length>0)for(var r=0;r<P.length;r++)J(P[r]);P=[],T=!1,x=!1,k=[]}else x&&!T?k=n.data:x&&T?P.push(n.data):J(n.data)}}var A,I,R,w,P,T,O,D,N,_=v((function e(t,i,n,r,o,s,a,u,c,l,h,d,f,p,v,b,m,y,S,E,C){g(this,e),this.audioContext,this.audioStream,this.executor=new k(i,s,a,u,p,v,b,y,S,E,r,d),this.executor.HeavyOp=f,this.source,this.processorNode,this.isPaused=!1,this.isStreaming=!1,this.audioData=[],this.isDebug=n,this.enableLogs=i,this.onStateChanged=m,this.onIntensity=C,this.onError=b,this.bufferSizeInterval=r,this.pausedBufferInterval=null!=o?o:1,this.shouldReadIntensity=h,this.closeSocketWithoutEOS=!1,this.shouldPreIntialiseRecorder=null!=l&&l,this.shouldPreIntialiseRecorder&&this.InitialiseMediaStream(c,t)}),[{key:"InitialiseMediaStream",value:(N=f(l().mark((function e(t,i){return l().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.createMediaStreamSourceNode();case 2:if(this.source){e.next=5;break}return console.error("Error: unable to create source node"),e.abrupt("return",!1);case 5:return e.next=7,this.createProcessorNode();case 7:if(this.processorNode){e.next=10;break}return console.error("Error: unable to create processor node"),e.abrupt("return",!1);case 10:this.source.connect(this.processorNode).connect(this.audioContext.destination),this.log("AudioContext Sample Rate: "+this.audioContext.sampleRate),""!==i&&this.executor.Start(t,i,this.shouldPreIntialiseRecorder);case 13:case"end":return e.stop()}}),e,this)}))),function(e,t){return N.apply(this,arguments)})},{key:"StartStream",value:(D=f(l().mark((function e(t,i){return l().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.log("New stream started..."),this.shouldPreIntialiseRecorder&&this.source){e.next=6;break}return e.next=4,this.InitialiseMediaStream(t,i,!1);case 4:e.next=7;break;case 6:this.shouldPreIntialiseRecorder&&this.executor.Send(y);case 7:if(!this.IsMicrophoneMuted){e.next=13;break}if(!this.audioContext||"running"!=this.audioContext.state){e.next=11;break}return e.next=11,this.audioContext.suspend();case 11:return this.onError(JSON.stringify({Type:"ERROR",Data:"Microphone is muted."})),e.abrupt("return",!1);case 13:return this.onStateChanged(!0),this.isStreaming=!0,e.abrupt("return",!0);case 16:case"end":return e.stop()}}),e,this)}))),function(e,t){return D.apply(this,arguments)})},{key:"createBufferedSourceNode",value:(O=f(l().mark((function e(){var t;return l().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 O.apply(this,arguments)})},{key:"createMediaStreamSourceNode",value:(T=f(l().mark((function e(){var t,i=this;return l().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(){i.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 T.apply(this,arguments)})},{key:"loadAudio",value:(P=f(l().mark((function e(){var t,i,n;return l().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 i=e.sent,e.next=9,this.audioContext.decodeAudioData(i);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 P.apply(this,arguments)})},{key:"createProcessorNode",value:(w=f(l().mark((function e(){var t,i=this;return l().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,r=t.value;if(n==b)i.log("Worklet processing done, clearing resources..."),i.isDebug&&i.saveAudio(),i.cleanup();else if(e.data==m)i.executor.Send(m);else{var o;"intensity"===n?null===(o=i.onIntensity)||void 0===o||o.call(i,r):"audioData"===n&&i.isDebug&&new Int16Array(r).forEach((function(e){i.audioData.length<=288e5&&i.audioData.push(e)}))}i.executor&&(i.closeSocketWithoutEOS?(i.executor.Send(E),i.closeSocketWithoutEOS=!1):"intensity"!==n&&i.executor.Send(r))},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 w.apply(this,arguments)})},{key:"PauseStream",value:(R=f(l().mark((function e(){return l().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("running"!=this.audioContext.state){e.next=9;break}if(this.shouldPreIntialiseRecorder){e.next=8;break}return e.next=4,this.audioContext.suspend();case 4:this.log("Stream paused..."),this.processorNode.port.postMessage("PAUSE"),e.next=9;break;case 8:this.processorNode.port.postMessage(m);case 9:this.onStateChanged(!1),this.isPaused=!0,this.isStreaming=!1;case 12:case"end":return e.stop()}}),e,this)}))),function(){return R.apply(this,arguments)})},{key:"ResumeStream",value:(I=f(l().mark((function e(){return l().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(y),this.executor.Send(y);case 11:this.onStateChanged(!0),this.isPaused=!1,this.isStreaming=!0;case 14:case"end":return e.stop()}}),e,this)}))),function(){return I.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:(A=f(l().mark((function e(t){var i,n,r,o;return l().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("suspended"===(null===(i=this.audioContext)||void 0===i?void 0:i.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===(r=this.audioStream)||void 0===r||r.getAudioTracks()[0].removeEventListener("ended",(function(){}));case 9:case"end":return e.stop()}}),e,this)}))),function(e){return A.apply(this,arguments)})},{key:"IntentStartStream",value:function(){this.executor.Send("INTENT_START_STREAM")}},{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,i){e.setInt16(2*i,t,!0)}));var t=e.buffer.byteLength,i=44+t,n=new DataView(new ArrayBuffer(i));n.setUint32(0,1380533830,!1),n.setUint32(4,i-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 r=0;r<t;r++)n.setInt8(44+r,e.getInt8(r));return n}},{key:"log",value:function(e){if(this.enableLogs){var t="".concat((new Date).toLocaleTimeString()," Augnito: ").concat(e);console.log(t+"\n")}}}]),U=function(){function e(){var t,i,n,r,o=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,reconnectAudioDuration:0,shouldPreIntialiseRecorder:!1,shouldReadIntensity:!1,debounceDelay:300,switchToRegularSpeechProfile:!1},s=arguments.length>1?arguments[1]:void 0;if(g(this,e),e.instance)return e.instance;this.WebsocketURL=null!==(t=o.serverURL)&&void 0!==t?t:"",this.enableLogs=o.enableLogs,this.isDebug=o.isDebug,this.streamer=null,this.streamerNotStarted=!1,this.isStreamerStarting=!1,this.pendingStartStream=!1,this.heavyOp=s,this.bufferInterval=o.bufferInterval,this.pausedBufferInterval=o.pausedBufferInterval,this.eosMessage=o.EOS_Message,this.socketTimeoutInterval=o.socketTimeoutInterval,this.shouldSendAudioDataSequence=o.shouldSendAudioDataSequence,this.reconnectAudioDuration=null!==(i=o.reconnectAudioDuration)&&void 0!==i?i:0,this.shouldPreIntialiseRecorder=o.shouldPreIntialiseRecorder,this.switchToRegularSpeechProfile=null!==(n=o.switchToRegularSpeechProfile)&&void 0!==n&&n,this.shouldPreIntialiseRecorder&&(this.initialiseStreamer(),this.streamerNotStarted=!0),this.shouldReadIntensity=o.shouldReadIntensity,this.delay=null!==(r=o.debounceDelay)&&void 0!==r?r:300,this.toggleStartStopAudioStream=x(this.toggleStartStopAudioStream.bind(this),this.delay),this.togglePauseResumeAudioStream=x(this.togglePauseResumeAudioStream.bind(this),this.delay),this.needsDispose=!1,e.instance=this}return v(e,[{key:"initialiseStreamer",value:function(){this.streamer=new _(this.WebsocketURL,this.enableLogs,this.isDebug,this.bufferInterval,this.pausedBufferInterval,this.eosMessage,this.socketTimeoutInterval,this.shouldSendAudioDataSequence,this.reconnectAudioDuration,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:"updateIntentStartStream",value:function(){var e;this.pendingStartStream=!0,null===(e=this.streamer)||void 0===e||e.IntentStartStream()}},{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:(t=f(l().mark((function e(t){return l().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.isStreamerStarting){e.next=2;break}return e.abrupt("return");case 2:return this.isStreamerStarting=!0,this.shouldPreIntialiseRecorder&&this.streamer||this.initialiseStreamer(),e.prev=4,e.next=7,this.streamer.StartStream(t,this.WebsocketURL);case 7:e.sent?(this.streamerNotStarted=!1,this.log("Stream Started...")):this.streamer=null;case 9:return e.prev=9,this.isStreamerStarting=!1,e.finish(9);case 12:case"end":return e.stop()}}),e,this,[[4,,9,12]])}))),function(e){return t.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:function(){var e,t,i=this,n=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];(null!==(e=this.streamer)&&void 0!==e&&e.IsStreaming||r)&&(null===(t=this.streamer)||void 0===t||t.StopStream(n),this.streamer=null,this.log("Stream Stopped..."),this.shouldPreIntialiseRecorder&&setTimeout((function(){i.needsDispose?i.needsDispose=!1:(i.initialiseStreamer(),i.streamerNotStarted=!0)}),500))}},{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(){var t;this.needsDispose=!0,null===(t=this.streamer)||void 0===t||t.StopStream(!1),this.streamer=null,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}();function x(e,t){var i;return function(){for(var n=this,r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];i&&clearTimeout(i),i=setTimeout((function(){return e.apply(n,o)}),t)}}class L extends a{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"),i={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,ConfigTypeId:t};return yield this.makePostRequest(e,i)}))}getUserConfigSettings(t){return e(this,void 0,void 0,(function*(){const e=this.getURL("/userconfigmapping"),i={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,ConfigTypeId:t};return yield this.makePostRequest(e,i)}))}updateUserConfig(t){return e(this,void 0,void 0,(function*(){const e=this.getURL("/userconfigmapping"),i={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,UserConfigMapping:t};return yield this.makePatchRequest(e,i)}))}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,i,n,r){return e(this,void 0,void 0,(function*(){const e=this.getURL("/postuserpreferences"),o={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,UserPreferences:{AutomaticallyGenerateTranscript:t,PreferredTranscriptionLanguage:i,HighlightMedicalTerms:n,DisplayPatientContext:r}};return yield this.makePostRequest(e,o)}))}}const M="Invalid user details, please check again",J="Subscription is not valid.",K="invalid request. Please make sure AccessKey, SubscriptionCode and UserTag is sent along with the request",W="Active seat is not available for user",j="Unable to fetch account details, please try again.",B="Unable to fetch job details, please try again.",z="Job not reconnectable",q="Timeout exceeded",V="Rate Limit Exceeded, Please try again in sometime!",G="Audio Signal is power very LOW, Mic might be muted",F="Job Id is empty",H="Page Size is undefined",$="Note Data is empty",Y="Job Name is empty",Q="Patient Context is empty",X="Mic permission denied",Z="Microphone is muted",ee="Audio track ended. Possibly the mic was unplugged";class te{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}),Object.defineProperty(this,"onSoapNoteGenerated",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onTranscriptGenerated",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onCodesGenerated",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._ambientRestAPI=new u(this.validateConfig(e)),this._ambientPaceAPI=new L(e),this.config=this.createSocketConfig(e),this.enableLog=e.enableLogs,this.shouldReadAudioIntensity=e.shouldReadAudioIntensity}initRecorder(e){var t,i;this.recorderIns=new U({serverURL:e,enableLogs:null!==(t=this.enableLog)&&void 0!==t&&t,isDebug:null!==(i=this.enableLog)&&void 0!==i&&i,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),this.recorderIns.onSpeechResponse=this.onSpeechResponseCallback.bind(this)}getNoteParams(){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void c.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,i){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void c.error("SDK not initialized",this._logTag);var e=yield this._ambientRestAPI.ListJobs(t,i);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 c.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,i){return e(this,void 0,void 0,(function*(){try{return this._ambientRestAPI?yield this._ambientRestAPI.SendFinalNote(t,i):void c.error("SDK not initialized",this._logTag)}catch(e){this.handleException(e)}}))}toggleListening(e,t,i,n,r){var o,s,a=(null===(o=this.config)||void 0===o?void 0:o.prepareWSSURL(e,t,i,n))||"";this.recorderIns||this.initRecorder(a),null===(s=this.recorderIns)||void 0===s||s.toggleStartStopAudioStream(r,a)}togglePauseResumeListening(e,t,i,n,r){var o,s,a=(null===(o=this.config)||void 0===o?void 0:o.prepareWSSURL(e,t,i,n))||"";this.recorderIns||this.initRecorder(a),null===(s=this.recorderIns)||void 0===s||s.togglePauseResumeAudioStream(r,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 i;return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void c.error("SDK not initialized",this._logTag);var e=yield this._ambientRestAPI.DeleteNotes(t);if(e){if(200===e.Status)return null===(i=this.recorderIns)||void 0===i||i.stopAudio(!1,!0),e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}renameNoteTitle(t,i){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void c.error("SDK not initialized",this._logTag);var e=yield this._ambientRestAPI.RenameNoteTitle(t,i);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}getNotePDF(t,i,n,r,o,s){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void c.error("SDK not initialized",this._logTag);var e=yield this._ambientRestAPI.DownloadNotePDF(t,i,n,r,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 c.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,i,n,r,o){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void c.error("SDK not initialized",this._logTag);var e=yield this._ambientRestAPI.GenerateSuggestions(t,i,n,o,r);if(e){if(200===e.Status)return e;this.onErrorCallback(e.ServerMessage)}else this.onErrorCallback("Unknown Error!")}catch(e){this.handleException(e)}}))}updatePatientContext(t,i,n){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void c.error("SDK not initialized",this._logTag);var e=yield this._ambientRestAPI.UpdatePatientContext(t,i,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,i,n){return e(this,void 0,void 0,(function*(){try{if(!this._ambientRestAPI)return void c.error("SDK not initialized",this._logTag);var e=yield this._ambientRestAPI.ModifyGeneratedNote(t,i,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 c.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 c.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 c.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 c.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 i,n,r,o;return e(this,void 0,void 0,(function*(){try{if(!this._ambientPaceAPI)return void c.error("SDK not initialized",this._logTag);var e=yield this._ambientPaceAPI.updateUserPreference(null!==(i=t.AutomaticallyGenerateTranscript)&&void 0!==i&&i,null!==(n=t.PreferredTranscriptionLanguage)&&void 0!==n?n:"English",null!==(r=t.HighlightMedicalTerms)&&void 0!==r&&r,null!==(o=t.DisplayPatientContext)&&void 0!==o&&o);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 s)throw e;c.error(e.message,this._logTag)}}onErrorCallback(e,t){var i,n,r,s,a,u,l,h,d,f,g,p,v,b={ErrorCode:null!=t?t:o.ERRUNKNOWN,ErrorMessage:e};try{var m=JSON.parse(e);b.ErrorMessage=m.Data,m.Data===q?(this.stopListening(),c.error("Recording time limit exceeded",this._logTag),b.ErrorCode=o.WSJOB05):m.Data===M?(this._isRecording?null===(i=this.recorderIns)||void 0===i||i.stopAudio(!1,!0):this.forceStopAudio=!0,b.ErrorCode=o.WSAUTH03):m.Data.includes(j)?b.ErrorCode=o.WSAUTH04:m.Data.includes(B)?b.ErrorCode=o.WSJOB01:m.Data.includes(z)?b.ErrorCode=o.WSJOB02:m.Data.includes(V)?b.ErrorCode=o.WSACC01:m.Data.includes(G)&&(b.ErrorCode=o.WSAUD01)}catch(e){}(null===(n=b.ErrorMessage)||void 0===n?void 0:n.includes(F))?b.ErrorCode=o.SDK01:(null===(r=b.ErrorMessage)||void 0===r?void 0:r.includes(H))?b.ErrorCode=o.SDK02:(null===(s=b.ErrorMessage)||void 0===s?void 0:s.includes($))?b.ErrorCode=o.SDK03:(null===(a=b.ErrorMessage)||void 0===a?void 0:a.includes(Y))?b.ErrorCode=o.SDK04:(null===(u=b.ErrorMessage)||void 0===u?void 0:u.includes(Q))?b.ErrorCode=o.SDK05:(null===(l=b.ErrorMessage)||void 0===l?void 0:l.includes(X))?b.ErrorCode=o.SDK06:(null===(h=b.ErrorMessage)||void 0===h?void 0:h.includes(Z))?(b.ErrorCode=o.SDK07,null===(d=this.recorderIns)||void 0===d||d.stopAudio(!1,!0)):(null===(f=b.ErrorMessage)||void 0===f?void 0:f.includes(ee))?b.ErrorCode=o.SDK08:(null===(g=b.ErrorMessage)||void 0===g?void 0:g.includes(J))||(null===(p=b.ErrorMessage)||void 0===p?void 0:p.includes(K))?b.ErrorCode=o.AUTH01:(null===(v=b.ErrorMessage)||void 0===v?void 0:v.includes(W))&&(b.ErrorCode=o.AUTH02),this.onError&&this.onError(b)}onOtherResultsCallback(e){this.onOtherResult&&this.onOtherResult(e)}onIntensityCallback(e){this.onIntensityValue&&this.onIntensityValue(e)}onIdleMicCallback(){this.onIdleMic&&this.onIdleMic()}onSpeechResponseCallback(e){var t=JSON.parse(e);"note"===t.Type&&this.onSoapNoteGenerated?this.onSoapNoteGenerated(t.Data):"transcript"===t.Type&&this.onTranscriptGenerated?this.onTranscriptGenerated(t.Data):"codes"===t.Type&&this.onCodesGenerated&&this.onCodesGenerated(t.Data)}onSessionEventCallback(e){var t;if(!e)return;let i;try{i="string"==typeof e?JSON.parse(e):e}catch(e){return void c.error(`Error parsing session event data: ${e}`,this._logTag)}if(!i||!("Type"in i))return;if("meta"===i.Type.toLowerCase()&&(null===(t=this.config)||void 0===t?void 0:t.onMetaEvent)){if(!i.JobID)return void c.error("JobID is missing in meta event",this._logTag);this.config.onMetaEvent(i.JobID)}else"error"===i.Type.toLowerCase()&&i.Data&&this.onErrorCallback(i.Data);if("object"!=typeof i.Event||null===i.Event)return;const{Type:n,Value:r}=i.Event;n&&("SESSION_CREATED"===n&&r?c.log(`session Token ${r}`,this._logTag):"SERVICE_DOWN"===n?c.error(n,this._logTag):"NO_DICTATION_STOP_MIC"===n?(c.log("NO_DICTATION_STOP_MIC",this._logTag),this.onIdleMicCallback()):"INVALID_AUTH_CREDENTIALS"===n?c.error("INVALID_AUTH_CREDENTIALS",this._logTag):"LOW_BANDWIDTH"===n&&c.log("LOW_BANDWIDTH: Check internet connection",this._logTag))}validateConfig(e){return i.Against.NullOrEmpty(e.server,"Server"),i.Against.NullOrEmpty(e.subscriptionCode,"SubscriptionCode"),i.Against.NullOrEmpty(e.accessKey,"AccessKey"),i.Against.NullOrEmpty(e.userTag,"UserTag"),e}createSocketConfig(e){const i=new t(e);return i.onError=this.onErrorCallback.bind(this),i.onMetaEvent=this.onEventCallback.bind(this),i}}export{te as AugnitoAmbient,o as ErrorCodes,s as HttpCodedError,r as NoteTypeConfig,n as SettingsConfigType};
@@ -20,6 +20,5 @@ export declare enum ErrorCodes {
20
20
  SDK06 = "SDK06",
21
21
  SDK07 = "SDK07",
22
22
  SDK08 = "SDK08",
23
- SDK12 = "SDK12",
24
23
  ERRUNKNOWN = "ERRUNKNOWN"
25
24
  }
@@ -1,10 +1,6 @@
1
- import { NoteOutputStyleConfig } from "./NoteOutputStyleConfig";
2
- import { NoteVerbosityConfig } from "./NoteVerbosityConfig";
3
1
  export interface PreferenceConfig {
4
2
  AutomaticallyGenerateTranscript?: boolean;
5
3
  PreferredTranscriptionLanguage?: string;
6
4
  HighlightMedicalTerms?: boolean;
7
5
  DisplayPatientContext?: boolean;
8
- NoteOutputStyle?: NoteOutputStyleConfig;
9
- NoteOutputVerbosity?: NoteVerbosityConfig;
10
6
  }
@@ -5,5 +5,3 @@ export * from './PreferenceConfig';
5
5
  export * from "./ErrorCodes";
6
6
  export * from "./ErrorInfo";
7
7
  export * from './HttpCodedError';
8
- export * from './NoteVerbosityConfig';
9
- export * from './NoteOutputStyleConfig';
@@ -21,5 +21,4 @@ export declare const ErrorMessages: {
21
21
  audioUnplugged: string;
22
22
  unknownError: string;
23
23
  sdkUnintialised: string;
24
- noInternetConnection: string;
25
24
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "testaugnitoambientsdk2",
3
- "version": "2.1.15",
3
+ "version": "2.1.17",
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",
@@ -37,6 +37,6 @@
37
37
  "rollup-plugin-cleanup": "^3.2.1",
38
38
  "rollup-plugin-terser": "^7.0.2",
39
39
  "rollup-plugin-typescript2": "^0.36.0",
40
- "testaugnitorecorder4": "^1.0.82"
40
+ "testaugnitorecorder4": "^1.0.83"
41
41
  }
42
42
  }
@@ -8,11 +8,10 @@ import { AugnitoSocketResponse } from "./support/AugnitoSocketResponse";
8
8
  import { AmbientPACEAPI } from "./api/AmbientPACEAPI";
9
9
  import { SettingsConfigType, UserConfigMap } from "./config/SettingsConfig";
10
10
  import { NoteTypeConfig } from "./config/NoteTypeConfig";
11
- import { HttpCodedError, NoteOutputStyleConfig, NoteVerbosityConfig, PreferenceConfig } from "./config";
11
+ import { HttpCodedError, PreferenceConfig } from "./config";
12
12
  import { ErrorCodes } from "./config/ErrorCodes";
13
13
  import { ErrorMessages } from "./utils/Constants";
14
14
  import ErrorInfo from "./config/ErrorInfo";
15
- import NetworkMonitor from "./support/NetworkMonitor";
16
15
 
17
16
  /**
18
17
  * Augnito Ambient Manager
@@ -53,6 +52,9 @@ export class AugnitoAmbient {
53
52
  public onOtherResult?: (text: string) => void;
54
53
  public onIntensityValue?: (intensity: number) => void;
55
54
  public onIdleMic?: () => void;
55
+ public onSoapNoteGenerated?: (soapNote: string) => void;
56
+ public onTranscriptGenerated?: (transcript: string) => void;
57
+ public onCodesGenerated?: (codes: string) => void;
56
58
  private initRecorder(url: string) {
57
59
  // console.log(_filetype, _noteparams);
58
60
  this.recorderIns = new AugnitoRecorder({
@@ -71,6 +73,7 @@ export class AugnitoAmbient {
71
73
  this.recorderIns.onSessionEvent = this.onSessionEventCallback.bind(this);
72
74
  this.recorderIns.onOtherResults = this.onOtherResultsCallback.bind(this);
73
75
  this.recorderIns.onIntensity = this.onIntensityCallback.bind(this);
76
+ this.recorderIns.onSpeechResponse = this.onSpeechResponseCallback.bind(this);
74
77
  }
75
78
 
76
79
  // #region Public Methods
@@ -214,17 +217,6 @@ export class AugnitoAmbient {
214
217
  this.recorderIns?.togglePauseResumeAudioStream(recordedDuration, serverUrl);
215
218
  }
216
219
 
217
- public uploadAudioFile(_filetype: string,
218
- _noteparams: string,
219
- fileContent: ArrayBuffer, jobName?: string) {
220
- var serverUrl =
221
- this.config?.prepareWSSURL(_filetype, _noteparams, jobName) || "";
222
- if (!this.recorderIns) {
223
- this.initRecorder(serverUrl);
224
- }
225
- this.recorderIns?.uploadAudioFile(fileContent, serverUrl);
226
- }
227
-
228
220
  /**
229
221
  * Method called to start audio recording
230
222
  */
@@ -249,10 +241,6 @@ export class AugnitoAmbient {
249
241
  Logger.error("SDK not initialized", this._logTag);
250
242
  return;
251
243
  }
252
- // if (!await this.isInternetAvailable()) {
253
- // this.onErrorCallback(ErrorMessages.noInternetConnection);
254
- // return;
255
- // }
256
244
  var responseJson = await this._ambientRestAPI.DeleteNotes(JobIds);
257
245
  if (responseJson) {
258
246
  if (responseJson.Status === 200) {
@@ -283,10 +271,6 @@ export class AugnitoAmbient {
283
271
  Logger.error("SDK not initialized", this._logTag);
284
272
  return;
285
273
  }
286
- // if (!await this.isInternetAvailable()) {
287
- // this.onErrorCallback(ErrorMessages.noInternetConnection);
288
- // return;
289
- // }
290
274
  var responseJson = await this._ambientRestAPI.RenameNoteTitle(
291
275
  JobId,
292
276
  NewJobName
@@ -320,10 +304,6 @@ export class AugnitoAmbient {
320
304
  Logger.error("SDK not initialized", this._logTag);
321
305
  return;
322
306
  }
323
- // if (!await this.isInternetAvailable()) {
324
- // this.onErrorCallback(ErrorMessages.noInternetConnection);
325
- // return;
326
- // }
327
307
  var responseJson = await this._ambientRestAPI.DownloadNotePDF(JobId, NoteType, SpecialityId, Language, PersonnelInfo, RegenerateNote);
328
308
  if (responseJson) {
329
309
  if (responseJson.Status === 200) {
@@ -418,10 +398,6 @@ export class AugnitoAmbient {
418
398
  Logger.error("SDK not initialized", this._logTag);
419
399
  return;
420
400
  }
421
- // if (!await this.isInternetAvailable()) {
422
- // this.onErrorCallback(ErrorMessages.noInternetConnection);
423
- // return;
424
- // }
425
401
  var responseJson = await this._ambientRestAPI.UpdatePatientContext(
426
402
  JobId,
427
403
  Context,
@@ -627,7 +603,7 @@ export class AugnitoAmbient {
627
603
  Logger.error("SDK not initialized", this._logTag);
628
604
  return;
629
605
  }
630
- var responseJson = await this._ambientPaceAPI.updateUserPreference(NewUserPreference.AutomaticallyGenerateTranscript ?? false, NewUserPreference.PreferredTranscriptionLanguage ?? 'English', NewUserPreference.HighlightMedicalTerms ?? false, NewUserPreference.DisplayPatientContext ?? false, NewUserPreference.NoteOutputStyle ?? NoteOutputStyleConfig.DashFormat, NewUserPreference.NoteOutputVerbosity ?? NoteVerbosityConfig.Detailed);
606
+ var responseJson = await this._ambientPaceAPI.updateUserPreference(NewUserPreference.AutomaticallyGenerateTranscript ?? false, NewUserPreference.PreferredTranscriptionLanguage ?? 'English', NewUserPreference.HighlightMedicalTerms ?? false, NewUserPreference.DisplayPatientContext ?? false);
631
607
  if (responseJson) {
632
608
  if (responseJson.Status === 200) {
633
609
  return responseJson;
@@ -642,18 +618,6 @@ export class AugnitoAmbient {
642
618
  }
643
619
  }
644
620
 
645
- /**
646
- * @param options a list of preference of type PreferenceConfig to be updated
647
- * @returns true if connected else false and onError callback triggered with SDK12
648
- */
649
- public async isInternetAvailable(options?: { url: null; timeoutMs: null; } | undefined) {
650
- const online = await NetworkMonitor.isOnline(options);
651
- if (!online) {
652
- this.onErrorCallback(ErrorMessages.noInternetConnection);
653
- }
654
- return online;
655
- }
656
-
657
621
  // #endregion
658
622
 
659
623
  // #region client callbacks
@@ -738,10 +702,9 @@ export class AugnitoAmbient {
738
702
  errorInfo.ErrorCode = ErrorCodes.SDK08
739
703
  } else if (errorInfo.ErrorMessage?.includes(ErrorMessages.invalidSubscription) || errorInfo.ErrorMessage?.includes(ErrorMessages.invalidRequest)) {
740
704
  errorInfo.ErrorCode = ErrorCodes.AUTH01
741
- } else if (errorInfo.ErrorMessage?.includes(ErrorMessages.activeSeatNotAvailable)) {
705
+ }
706
+ else if (errorInfo.ErrorMessage?.includes(ErrorMessages.activeSeatNotAvailable)) {
742
707
  errorInfo.ErrorCode = ErrorCodes.AUTH02
743
- } else if (errorInfo.ErrorMessage?.includes(ErrorMessages.noInternetConnection)) {
744
- errorInfo.ErrorCode = ErrorCodes.SDK12
745
708
  }
746
709
  if (this.onError) {
747
710
  this.onError(errorInfo);
@@ -765,6 +728,19 @@ export class AugnitoAmbient {
765
728
  this.onIdleMic();
766
729
  }
767
730
  }
731
+
732
+ private onSpeechResponseCallback(data: string): void {
733
+ var json = JSON.parse(data);
734
+ if (json.Type === "note" && this.onSoapNoteGenerated) {
735
+ this.onSoapNoteGenerated(json.Data);
736
+ }
737
+ else if (json.Type === "transcript" && this.onTranscriptGenerated) {
738
+ this.onTranscriptGenerated(json.Data);
739
+ } else if (json.Type === "codes" && this.onCodesGenerated) {
740
+ this.onCodesGenerated(json.Data);
741
+ }
742
+ }
743
+
768
744
  private onSessionEventCallback(data: string | AugnitoSocketResponse): void {
769
745
  if (!data) {
770
746
  return;
@@ -1,4 +1,3 @@
1
- import { NoteOutputStyleConfig, NoteVerbosityConfig } from "../config";
2
1
  import AmbientConfig from "../config/AmbientConfig";
3
2
  import { SettingsConfigType, UserConfigMap } from "../config/SettingsConfig";
4
3
  import { BaseAPI } from "./BaseAPI";
@@ -69,7 +68,7 @@ export class AmbientPACEAPI extends BaseAPI {
69
68
  return await this.makePostRequest(url, requestData);
70
69
  }
71
70
 
72
- async updateUserPreference(_automaticallyGenerateTranscript: boolean, _preferredTranscriptionLanguage: string, _highlightMedicalTerms: boolean, _displayPatientContext: boolean, _noteOutputStyle: NoteOutputStyleConfig, _noteOutputVerbosity: NoteVerbosityConfig): Promise<any> {
71
+ async updateUserPreference(_automaticallyGenerateTranscript: boolean, _preferredTranscriptionLanguage: string, _highlightMedicalTerms: boolean, _displayPatientContext: boolean): Promise<any> {
73
72
  const url = this.getURL('/postuserpreferences');
74
73
  const requestData = {
75
74
  SubscriptionCode: this._config.subscriptionCode,
@@ -79,9 +78,7 @@ export class AmbientPACEAPI extends BaseAPI {
79
78
  AutomaticallyGenerateTranscript: _automaticallyGenerateTranscript,
80
79
  PreferredTranscriptionLanguage: _preferredTranscriptionLanguage,
81
80
  HighlightMedicalTerms: _highlightMedicalTerms,
82
- DisplayPatientContext: _displayPatientContext,
83
- NoteOutputStyle: _noteOutputStyle,
84
- NoteOutputVerbosity: _noteOutputVerbosity
81
+ DisplayPatientContext: _displayPatientContext
85
82
  }
86
83
  };
87
84
  return await this.makePostRequest(url, requestData);
@@ -20,7 +20,6 @@ export enum ErrorCodes {
20
20
  SDK06 = "SDK06",
21
21
  SDK07 = "SDK07",
22
22
  SDK08 = "SDK08",
23
- SDK12 = "SDK12",
24
23
  ERRUNKNOWN = "ERRUNKNOWN",
25
24
  }
26
25
 
@@ -1,11 +1,6 @@
1
- import { NoteOutputStyleConfig } from "./NoteOutputStyleConfig";
2
- import { NoteVerbosityConfig } from "./NoteVerbosityConfig";
3
-
4
1
  export interface PreferenceConfig {
5
2
  AutomaticallyGenerateTranscript?: boolean,
6
3
  PreferredTranscriptionLanguage?: string,
7
4
  HighlightMedicalTerms?: boolean,
8
- DisplayPatientContext?: boolean,
9
- NoteOutputStyle?: NoteOutputStyleConfig,
10
- NoteOutputVerbosity?: NoteVerbosityConfig
5
+ DisplayPatientContext?: boolean
11
6
  }
@@ -5,5 +5,3 @@ export * from './PreferenceConfig';
5
5
  export * from "./ErrorCodes";
6
6
  export * from "./ErrorInfo";
7
7
  export * from './HttpCodedError';
8
- export * from './NoteVerbosityConfig';
9
- export * from './NoteOutputStyleConfig';
@@ -21,5 +21,4 @@ export const ErrorMessages = {
21
21
  audioUnplugged: 'Audio track ended. Possibly the mic was unplugged',
22
22
  unknownError: 'Oops! Something went wrong',
23
23
  sdkUnintialised: 'SDK not initialized',
24
- noInternetConnection: 'Internet is not available. Try again later.',
25
24
  }
@@ -1,4 +0,0 @@
1
- export declare enum NoteOutputStyleConfig {
2
- DashFormat = "Dash-format",
3
- Paragraph = "Paragraph"
4
- }
@@ -1,4 +0,0 @@
1
- export declare enum NoteVerbosityConfig {
2
- Detailed = "Detailed",
3
- Consise = "Consise"
4
- }
@@ -1,33 +0,0 @@
1
- declare class NetworkMonitor {
2
- static DEFAULT_URL: string;
3
- static DEFAULT_TIMEOUT: number;
4
- /**
5
- * Fast browser-level connectivity signal
6
- * @returns {boolean}
7
- */
8
- static isBrowserOnline(): boolean;
9
- static isValidHttpUrl(url: string): boolean;
10
- /**
11
- * Real internet connectivity check using fetch
12
- *
13
- * @param {Object} [options]
14
- * @param {string} [options.url] - Endpoint to ping
15
- * @param {number} [options.timeoutMs] - Timeout in milliseconds
16
- * @returns {Promise<boolean>}
17
- */
18
- static hasInternetConnection(options?: {
19
- url?: string | null;
20
- timeoutMs?: number | null;
21
- }): Promise<boolean>;
22
- /**
23
- * Best possible signal for SDK consumers
24
- *
25
- * @param {Object} [options]
26
- * @returns {Promise<boolean>}
27
- */
28
- static isOnline(options?: {
29
- url?: string | null;
30
- timeoutMs?: number | null;
31
- } | undefined): Promise<boolean>;
32
- }
33
- export default NetworkMonitor;
@@ -1,4 +0,0 @@
1
- export enum NoteOutputStyleConfig {
2
- DashFormat = "Dash-format",
3
- Paragraph = "Paragraph"
4
- }
@@ -1,4 +0,0 @@
1
- export enum NoteVerbosityConfig {
2
- Detailed = "Detailed",
3
- Consise = "Consise"
4
- }
@@ -1,84 +0,0 @@
1
- class NetworkMonitor {
2
- static DEFAULT_URL = "https://www.google.com/favicon.ico";
3
- static DEFAULT_TIMEOUT = 5000;
4
-
5
- /**
6
- * Fast browser-level connectivity signal
7
- * @returns {boolean}
8
- */
9
- static isBrowserOnline() {
10
- return typeof navigator !== "undefined" && navigator.onLine === true;
11
- }
12
-
13
- static isValidHttpUrl(url: string) {
14
- if (typeof url !== 'string' || url.length > 2048) return false;
15
-
16
- try {
17
- const parsed = new URL(url);
18
-
19
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
20
- return false;
21
- }
22
-
23
- // Optional: disallow credentials in URL
24
- if (parsed.username || parsed.password) {
25
- return false;
26
- }
27
-
28
- return true;
29
- } catch {
30
- return false;
31
- }
32
- }
33
-
34
-
35
- /**
36
- * Real internet connectivity check using fetch
37
- *
38
- * @param {Object} [options]
39
- * @param {string} [options.url] - Endpoint to ping
40
- * @param {number} [options.timeoutMs] - Timeout in milliseconds
41
- * @returns {Promise<boolean>}
42
- */
43
- static async hasInternetConnection(options: { url?: string | null, timeoutMs?: number | null } = { url: null, timeoutMs: null }) {
44
- var url = options.url || NetworkMonitor.DEFAULT_URL;
45
- const timeoutMs = options.timeoutMs || NetworkMonitor.DEFAULT_TIMEOUT;
46
-
47
- if (!NetworkMonitor.isBrowserOnline()) {
48
- return false;
49
- }
50
-
51
- if (!NetworkMonitor.isValidHttpUrl(url)) {
52
- url = NetworkMonitor.DEFAULT_URL;
53
- }
54
-
55
- const controller = new AbortController();
56
- const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
57
-
58
- try {
59
- await fetch(url, {
60
- method: "HEAD",
61
- mode: "no-cors",
62
- cache: "no-cache",
63
- signal: controller.signal,
64
- });
65
- return true;
66
- } catch (e) {
67
- return false;
68
- } finally {
69
- clearTimeout(timeoutId);
70
- }
71
- }
72
-
73
- /**
74
- * Best possible signal for SDK consumers
75
- *
76
- * @param {Object} [options]
77
- * @returns {Promise<boolean>}
78
- */
79
- static async isOnline(options?: { url?: string | null; timeoutMs?: number | null; } | undefined) {
80
- return NetworkMonitor.hasInternetConnection(options);
81
- }
82
- }
83
-
84
- export default NetworkMonitor;