@nuralogix.ai/web-measurement-embedded-app 0.1.0-beta.1 → 0.1.0-beta.3

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.
@@ -22,4 +22,4 @@
22
22
  "TURN_LEFT": "Drehen Sie den Kopf nach links",
23
23
  "TURN_RIGHT": "Drehen Sie den Kopf nach rechts",
24
24
  "WAITING_FOR_RESULTS": "Warten auf Ergebnisse"
25
- }
25
+ }
@@ -22,4 +22,4 @@
22
22
  "TURN_LEFT": "Turn left",
23
23
  "TURN_RIGHT": "Turn right",
24
24
  "WAITING_FOR_RESULTS": "Waiting for results"
25
- }
25
+ }
@@ -22,4 +22,4 @@
22
22
  "TURN_LEFT": "Gire a la izquierda",
23
23
  "TURN_RIGHT": "Gire a la derecha",
24
24
  "WAITING_FOR_RESULTS": "Esperando resultados."
25
- }
25
+ }
@@ -22,4 +22,4 @@
22
22
  "TURN_LEFT": "Tournez la tête à gauche",
23
23
  "TURN_RIGHT": "Tournez la tête à droite",
24
24
  "WAITING_FOR_RESULTS": "Dans l'attente des résultats"
25
- }
25
+ }
@@ -22,4 +22,4 @@
22
22
  "TURN_LEFT": "Gira a sinistra",
23
23
  "TURN_RIGHT": "Gira a destra",
24
24
  "WAITING_FOR_RESULTS": "In attesa dei risultati"
25
- }
25
+ }
@@ -22,4 +22,4 @@
22
22
  "TURN_LEFT": "左を向いてください",
23
23
  "TURN_RIGHT": "右を向いてください",
24
24
  "WAITING_FOR_RESULTS": "結果が出るまで待機しています"
25
- }
25
+ }
@@ -22,4 +22,4 @@
22
22
  "TURN_LEFT": "Vire à esquerda",
23
23
  "TURN_RIGHT": "Vire à direita",
24
24
  "WAITING_FOR_RESULTS": "Aguardando resultados"
25
- }
25
+ }
@@ -22,4 +22,4 @@
22
22
  "TURN_LEFT": "Vire à esquerda",
23
23
  "TURN_RIGHT": "Vire à direita",
24
24
  "WAITING_FOR_RESULTS": "À espera de resultados"
25
- }
25
+ }
@@ -22,4 +22,4 @@
22
22
  "TURN_LEFT": "向左转头",
23
23
  "TURN_RIGHT": "向右转头",
24
24
  "WAITING_FOR_RESULTS": "等待结果"
25
- }
25
+ }
package/lib/index.d.ts CHANGED
@@ -914,38 +914,48 @@ interface Results {
914
914
  statusId: string;
915
915
  }
916
916
 
917
- declare const measurementEmbeddedAppEvents: {
918
- readonly RESULTS: "results";
919
- readonly ERROR: "error";
920
- readonly APPEVENT: "appEvent";
921
- readonly CANCELLED: "cancelled";
922
- readonly LOGS: "logs";
923
- };
924
917
  interface AppSettings {
925
918
  token: string;
926
919
  refreshToken: string;
927
920
  studyId: string;
928
921
  }
929
- type SupportedLanguage = 'en' | 'ja' | 'cn' | 'es' | 'pt' | 'it' | 'fr' | 'de' | 'br';
922
+ type SupportedLanguage = 'en' | 'ja' | 'zh' | 'es' | 'pt' | 'pt-BR' | 'it' | 'fr' | 'de';
930
923
  interface Config {
924
+ /** Enables all distance, direction, and movement validations */
931
925
  checkConstraints?: boolean;
926
+ /** Camera facing mode: 'user' for front camera, 'environment' for back camera */
932
927
  cameraFacingMode?: 'user' | 'environment';
928
+ /** If true, camera starts automatically without user interaction */
933
929
  cameraAutoStart?: boolean;
930
+ /** If true, measurement begins automatically after camera starts */
934
931
  measurementAutoStart?: boolean;
932
+ /** If true, measurement will be canceled when low SNR is detected */
935
933
  cancelWhenLowSNR?: boolean;
936
934
  }
937
935
  interface Profile extends Demographics {
936
+ /** When set to true you are explicitly indicating that you do not want to
937
+ * provide any demographic information (age, sex, height, weight, smoking,
938
+ * diabetes, blood pressure medication).
939
+ * In this mode WMEA will skip validation of those attributes and proceed
940
+ * with a "profile-less" measurement. */
938
941
  bypassProfile: boolean;
939
942
  }
940
943
  interface MeasurementEmbeddedAppOptions {
944
+ /** The HTML container element where the app will be mounted */
941
945
  container: HTMLDivElement;
942
- top?: string;
946
+ /** Path to WMEA static assets */
943
947
  appPath: string;
948
+ /** Application settings including token, refreshToken, and studyId */
944
949
  settings: AppSettings;
950
+ /** User profile information */
945
951
  profile: Profile;
952
+ /** Selected language for the app */
946
953
  language?: SupportedLanguage;
954
+ /** Configuration options for the app */
947
955
  config?: Config;
956
+ /** API URL for region-specific data processing */
948
957
  apiUrl?: string;
958
+ /** Callback function to handle load errors */
949
959
  loadError?: (error: string) => void;
950
960
  }
951
961
  declare enum logCategory {
@@ -962,7 +972,7 @@ interface Log {
962
972
  }
963
973
  interface MeasurementEmbedded {
964
974
  init(options: MeasurementEmbeddedAppOptions): void;
965
- destroy(): void;
975
+ destroy(): Promise<void>;
966
976
  /**
967
977
  * Cancel the measurement
968
978
  * @param {boolean} reset - whether to reset the Web SDK or just close the camera and hide the mask
@@ -1001,15 +1011,28 @@ declare const appEventSeverity: {
1001
1011
  };
1002
1012
  declare const appEvent: {
1003
1013
  readonly CAMERA_STARTED: "CAMERA_STARTED";
1014
+ /** WMEA component has been loaded */
1004
1015
  readonly APP_LOADED: "APP_LOADED";
1016
+ /** Measurement has been prepared */
1017
+ readonly MEASUREMENT_PREPARED: "MEASUREMENT_PREPARED";
1018
+ /** Assets have been downloaded */
1019
+ readonly ASSETS_DOWNLOADED: "ASSETS_DOWNLOADED";
1020
+ /** Measurement has started */
1005
1021
  readonly MEASUREMENT_STARTED: "MEASUREMENT_STARTED";
1022
+ /** Measurement has completed */
1006
1023
  readonly MEASUREMENT_COMPLETED: "MEASUREMENT_COMPLETED";
1007
1024
  readonly CAMERA_PERMISSION_GRANTED: "CAMERA_PERMISSION_GRANTED";
1025
+ /** Intermediate measurement data received */
1008
1026
  readonly INTERMEDIATE_RESULTS: "INTERMEDIATE_RESULTS";
1027
+ /** Final measurement results received */
1009
1028
  readonly RESULTS_RECEIVED: "RESULTS_RECEIVED";
1029
+ /** User cancelled the measurement */
1010
1030
  readonly MEASUREMENT_CANCELED: "MEASUREMENT_CANCELED";
1031
+ /** Constraint violated */
1011
1032
  readonly CONSTRAINT_VIOLATION: "CONSTRAINT_VIOLATION";
1033
+ /** Page was unloaded */
1012
1034
  readonly PAGE_UNLOADED: "PAGE_UNLOADED";
1035
+ /** Browser tab focus changed */
1013
1036
  readonly PAGE_VISIBILITY_CHANGE: "PAGE_VISIBILITY_CHANGE";
1014
1037
  };
1015
1038
  declare const appEvents: {
@@ -1021,6 +1044,14 @@ declare const appEvents: {
1021
1044
  readonly event: "APP_LOADED";
1022
1045
  readonly level: "INFO";
1023
1046
  };
1047
+ readonly MEASUREMENT_PREPARED: {
1048
+ readonly event: "MEASUREMENT_PREPARED";
1049
+ readonly level: "INFO";
1050
+ };
1051
+ readonly ASSETS_DOWNLOADED: {
1052
+ readonly event: "ASSETS_DOWNLOADED";
1053
+ readonly level: "INFO";
1054
+ };
1024
1055
  readonly MEASUREMENT_STARTED: {
1025
1056
  readonly event: "MEASUREMENT_STARTED";
1026
1057
  readonly level: "INFO";
@@ -1063,20 +1094,35 @@ interface AppEvent {
1063
1094
  level: keyof typeof appEventSeverity;
1064
1095
  }
1065
1096
  declare enum ErrorCodes {
1097
+ /** Camera access was denied */
1066
1098
  CAMERA_PERMISSION_DENIED = "CAMERA_PERMISSION_DENIED",
1099
+ /** DeepAffex Cloud processing error */
1067
1100
  WORKER_ERROR = "WORKER_ERROR",
1101
+ /** User profile information is not set */
1068
1102
  PROFILE_INFO_NOT_SET = "PROFILE_INFO_NOT_SET",
1103
+ /** No camera devices found */
1069
1104
  NO_DEVICES_FOUND = "NO_DEVICES_FOUND",
1105
+ /** Page is not visible */
1070
1106
  PAGE_NOT_VISIBLE = "PAGE_NOT_VISIBLE",
1107
+ /** Camera failed to start */
1071
1108
  CAMERA_START_FAILED = "CAMERA_START_FAILED",
1109
+ /** Measurement failed due to low signal-to-noise ratio */
1072
1110
  MEASUREMENT_LOW_SNR = "MEASUREMENT_LOW_SNR",
1111
+ /** Extraction library error */
1073
1112
  COLLECTOR = "COLLECTOR",
1074
- WEBSOCKET_DISCONNECTED = "WEBSOCKET_DISCONNECTED"
1113
+ /** WebSocket disconnected */
1114
+ WEBSOCKET_DISCONNECTED = "WEBSOCKET_DISCONNECTED",
1115
+ /** Measurement preparation failed - invalid or missing credentials */
1116
+ MEASUREMENT_PREPARE_FAILED = "MEASUREMENT_PREPARE_FAILED"
1075
1117
  }
1076
1118
  type MeasurementErrorCodes = ErrorCodes.WORKER_ERROR | ErrorCodes.PROFILE_INFO_NOT_SET;
1077
1119
 
1078
1120
  declare class MeasurementEmbeddedApp implements MeasurementEmbedded {
1079
1121
  #private;
1122
+ static VERSION: string;
1123
+ /**
1124
+ * The `on` object holds the event handlers
1125
+ */
1080
1126
  readonly on: {
1081
1127
  /**
1082
1128
  * when measurement results are received
@@ -1094,14 +1140,15 @@ declare class MeasurementEmbeddedApp implements MeasurementEmbedded {
1094
1140
  */
1095
1141
  event: ((appEvent: AppEvent) => void) | null;
1096
1142
  };
1143
+ /** @hideconstructor */
1097
1144
  constructor();
1098
1145
  init(options: MeasurementEmbeddedAppOptions): void;
1099
- destroy(): void;
1146
+ destroy(): Promise<void>;
1100
1147
  setTheme(theme: 'light' | 'dark'): void;
1101
1148
  setLanguage(language: SupportedLanguage): void;
1102
1149
  cancel(reset: boolean): Promise<boolean>;
1103
1150
  getLogs(): Promise<Log[]>;
1104
1151
  }
1105
1152
 
1106
- export { ErrorCodes, appEvents, MeasurementEmbeddedApp as default, faceAttributeValue, measurementEmbeddedAppEvents };
1107
- export type { AppSettings, DfxPointId, DialSection, IMeta, MeasurementEmbeddedAppError, MeasurementEmbeddedAppOptions, MeasurementErrorCodes, Point, PointGroupType, Profile, Results };
1153
+ export { ErrorCodes, appEvents, MeasurementEmbeddedApp as default, faceAttributeValue, logCategory };
1154
+ export type { AppSettings, Config, DfxPointId, DialSection, IMeta, Log, MeasurementEmbeddedAppError, MeasurementEmbeddedAppOptions, MeasurementErrorCodes, Point, PointGroupType, Points, Profile, RealtimeResultNotes, Results, ResultsError, SupportedLanguage };
package/lib/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- const U={RESULTS:"results",ERROR:"error",APPEVENT:"appEvent",CANCELLED:"cancelled",LOGS:"logs"};var Nt=(t=>(t.measurement="Measurement",t.collector="Collector",t.camera="Camera",t.app="App",t))(Nt||{});const D={INFO:"INFO",WARN:"WARN",ERROR:"ERROR"},I={CAMERA_STARTED:"CAMERA_STARTED",APP_LOADED:"APP_LOADED",MEASUREMENT_STARTED:"MEASUREMENT_STARTED",MEASUREMENT_COMPLETED:"MEASUREMENT_COMPLETED",CAMERA_PERMISSION_GRANTED:"CAMERA_PERMISSION_GRANTED",INTERMEDIATE_RESULTS:"INTERMEDIATE_RESULTS",RESULTS_RECEIVED:"RESULTS_RECEIVED",MEASUREMENT_CANCELED:"MEASUREMENT_CANCELED",CONSTRAINT_VIOLATION:"CONSTRAINT_VIOLATION",PAGE_UNLOADED:"PAGE_UNLOADED",PAGE_VISIBILITY_CHANGE:"PAGE_VISIBILITY_CHANGE"},Lt={CAMERA_STARTED:{event:I.CAMERA_STARTED,level:D.INFO},APP_LOADED:{event:I.APP_LOADED,level:D.INFO},MEASUREMENT_STARTED:{event:I.MEASUREMENT_STARTED,level:D.INFO},MEASUREMENT_COMPLETED:{event:I.MEASUREMENT_COMPLETED,level:D.INFO},CAMERA_PERMISSION_GRANTED:{event:I.CAMERA_PERMISSION_GRANTED,level:D.INFO},INTERMEDIATE_RESULTS:{event:I.INTERMEDIATE_RESULTS,level:D.INFO},RESULTS_RECEIVED:{event:I.RESULTS_RECEIVED,level:D.INFO},MEASUREMENT_CANCELED:{event:I.MEASUREMENT_CANCELED,level:D.WARN},CONSTRAINT_VIOLATION:{event:I.CONSTRAINT_VIOLATION,level:D.ERROR},PAGE_UNLOADED:{event:I.PAGE_UNLOADED,level:D.INFO},PAGE_VISIBILITY_CHANGE:{event:I.PAGE_VISIBILITY_CHANGE,level:D.INFO}},ne={DESTROY:"destroy",CANCEL:"cancel",SET_THEME:"setTheme",SET_LANGUAGE:"setLanguage",GET_LOGS:"getLogs"};var Ye=(t=>(t.CAMERA_PERMISSION_DENIED="CAMERA_PERMISSION_DENIED",t.WORKER_ERROR="WORKER_ERROR",t.PROFILE_INFO_NOT_SET="PROFILE_INFO_NOT_SET",t.NO_DEVICES_FOUND="NO_DEVICES_FOUND",t.PAGE_NOT_VISIBLE="PAGE_NOT_VISIBLE",t.CAMERA_START_FAILED="CAMERA_START_FAILED",t.MEASUREMENT_LOW_SNR="MEASUREMENT_LOW_SNR",t.COLLECTOR="COLLECTOR",t.WEBSOCKET_DISCONNECTED="WEBSOCKET_DISCONNECTED",t))(Ye||{}),Je="0.1.0-alpha.36",J=(t=>(t.DELETE="DELETE",t.GET="GET",t.PATCH="PATCH",t.POST="POST",t.PUT="PUT",t.CONNECT="CONNECT",t))(J||{}),H=(t=>(t.ON_BEFORE_REST_CALL_ERROR="ON_BEFORE_REST_CALL_ERROR",t))(H||{});const Xe=typeof DedicatedWorkerGlobalScope<"u",_e=async({baseUrl:t,urlFragment:e,method:i,headers:r,data:c},d)=>{const n=`${t}/${e}`;let a={Code:"",Message:""};try{const m=await fetch(n,{method:i,cache:"no-store",credentials:"include",headers:r,...c!=null&&{body:JSON.stringify(c)}}),h=m.headers.get("content-type"),E=m.status.toString();a={Code:"UNSUPPORTED_RESPONSE_CONTENT_TYPE",Message:"UNSUPPORTED_RESPONSE_CONTENT_TYPE"},E==="503"&&(a={Code:"SERVICE_UNAVAILABLE",Message:"Service unavailable"}),E==="429"&&(a={Code:"TOO_MANY_REQUESTS",Message:"Too many requests"}),h!=null&&(h.startsWith("application/json;")&&(a=await m.json()),h.startsWith("text/plain;")&&(a={data:await m.text()}));let S=m.headers;if(Xe){const R={};m.headers.forEach((k,O)=>{R[O]=k}),S=R}try{d(E,E==="200"?void 0:a)}catch(R){console.error("Error running onAfterRESTCall callback",R)}return{status:E,headers:S,body:a}}catch(m){return m instanceof SyntaxError?a={Code:"SYNTAX_ERROR",Message:"SYNTAX_ERROR"}:a={Code:"UNEXPECTED_ERROR",Message:"UNEXPECTED_ERROR"},{status:"UNKNOWN",headers:Xe?{}:new Headers,body:a}}},ge=()=>new Headers({"Content-Type":"application/json"});var Dt=Object.defineProperty,It=(t,e,i)=>e in t?Dt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,xt=(t,e,i)=>It(t,e+"",i);class Me{constructor(e){xt(this,"parent"),this.parent=e}async onBeforeRESTCall(){try{return this.parent.onBeforeRESTCall(),{Code:"SUCCESS",Message:"SUCCESS"}}catch{return{Code:H.ON_BEFORE_REST_CALL_ERROR,Message:H.ON_BEFORE_REST_CALL_ERROR}}}getDefaults(e){return{baseUrl:JSON.parse(this.parent.getUrl()).http.slice(0,-1),method:J[e],headers:ge()}}getHeaderWithDeviceToken(){const e=ge();return e.set("Authorization",`Bearer ${this.parent.getSession().deviceToken}`),e}getHeaderWithUserToken(){const e=ge();return e.set("Authorization",`Bearer ${this.parent.getSession().userToken}`),e}getHeaderWithSessionEnabled(){const e=ge();return e.set("x-nura-session","true"),e}}class Ft extends Me{async create(e,i){const{Code:r,Message:c}=await this.onBeforeRESTCall();if(r===H.ON_BEFORE_REST_CALL_ERROR)return{status:r,body:{Code:r,Message:c},headers:new Headers};const{status:d,body:n,headers:a}=await _e({...this.getDefaults(J.POST),headers:i==="device"?this.getHeaderWithDeviceToken():this.getHeaderWithUserToken(),urlFragment:"measurements",data:e},this.parent.onAfterRESTCall);return d==="200"&&this.parent.setSession({lastMeasurementId:n.ID}),{status:d,body:n,headers:a}}}class Mt extends Me{async retrieveSdkConfigData(e,i){const{Code:r,Message:c}=await this.onBeforeRESTCall();if(r===H.ON_BEFORE_REST_CALL_ERROR)return{status:r,body:{Code:r,Message:c},headers:new Headers};const{status:d,body:n,headers:a}=await _e({...this.getDefaults(J.POST),headers:i==="device"?this.getHeaderWithDeviceToken():this.getHeaderWithUserToken(),urlFragment:"studies/sdkconfig",data:e},this.parent.onAfterRESTCall);return d==="200"&&this.parent.setSession({studyCfgData:n.ConfigFile,studyCfgHash:n.MD5Hash}),{status:d,body:n,headers:a}}}class Pt extends Me{async renew(e,i){const{Code:r,Message:c}=await this.onBeforeRESTCall();if(r===H.ON_BEFORE_REST_CALL_ERROR)return{status:r,body:{Code:r,Message:c},headers:new Headers};const{status:d,body:n,headers:a}=await _e({...this.getDefaults(J.POST),headers:i==="device"?this.getHeaderWithDeviceToken():this.getHeaderWithUserToken(),urlFragment:"auths/renew",data:e},this.parent.onAfterRESTCall);if(d==="200"){const m=n.Token,h=n.RefreshToken,E={...i==="user"&&{userToken:m,userRefreshToken:h},...i==="device"&&{deviceToken:m,deviceRefreshToken:h}};this.parent.setSession(E)}return{status:d,body:n,headers:a}}async validate(e){const{Code:i,Message:r}=await this.onBeforeRESTCall();return i===H.ON_BEFORE_REST_CALL_ERROR?{status:i,body:{Code:i,Message:r},headers:new Headers}:await _e({...this.getDefaults(J.GET),headers:e==="device"?this.getHeaderWithDeviceToken():this.getHeaderWithUserToken(),urlFragment:"auth/v1/validate"},this.parent.onAfterRESTCall)}}var Wt=Object.defineProperty,ze=t=>{throw TypeError(t)},Ut=(t,e,i)=>e in t?Wt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Pe=(t,e,i)=>Ut(t,typeof e!="symbol"?e+"":e,i),qe=(t,e,i)=>e.has(t)||ze("Cannot "+i),We=(t,e,i)=>(qe(t,e,"read from private field"),i?i.call(t):e.get(t)),Ze=(t,e,i)=>e.has(t)?ze("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),we=(t,e,i,r)=>(qe(t,e,"write to private field"),e.set(t,i),i),oe,X;class $t{constructor(e){Ze(this,oe,{http:new URL("https://api.deepaffex.ai")}),Ze(this,X),Pe(this,"onBeforeRESTCall"),Pe(this,"onAfterRESTCall"),Pe(this,"http"),we(this,X,{deviceToken:"",deviceRefreshToken:"",userToken:"",userRefreshToken:"",deviceId:"",roleId:"",userId:"",selectedStudy:"",lastMeasurementId:"",studyCfgHash:"",studyCfgData:""}),this.http={measurements:new Ft(this),studies:new Mt(this),auths:new Pt(this)},this.onBeforeRESTCall=e?.onBeforeRESTCall?e.onBeforeRESTCall:()=>{},this.onAfterRESTCall=e?.onAfterRESTCall?e.onAfterRESTCall:()=>{},e?.url!=null&&we(this,oe,e.url)}static new(e){return new this(e??void 0)}getUrl(){return JSON.stringify(We(this,oe))}setUrl(e){we(this,oe,{http:new URL(e)})}getSession(){return We(this,X)}setSession(e){const i=["deviceToken","deviceRefreshToken","userToken","userRefreshToken","deviceId","userId","roleId","selectedStudy","lastMeasurementId","studyCfgHash","studyCfgData"];Object.keys(e).every(d=>i.includes(d)&&typeof e[d]=="string")&&we(this,X,{...We(this,X),...e})}}oe=new WeakMap,X=new WeakMap;const Bt=t=>$t.new(t);var Gt=Object.defineProperty,Qe=t=>{throw TypeError(t)},Ht=(t,e,i)=>e in t?Gt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Vt=(t,e,i)=>Ht(t,e+"",i),Kt=(t,e,i)=>e.has(t)||Qe("Cannot "+i),jt=(t,e,i)=>e.has(t)?Qe("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),Ue=(t,e,i)=>(Kt(t,e,"access private method"),i),le,$e,et;let tt=t=>new Int8Array(t);class Yt extends EventTarget{constructor(){super(...arguments),jt(this,le),Vt(this,"canDecompress",!1)}static init(){return new this}dispatch(e,i){this.dispatchEvent(new CustomEvent(e,{detail:i}))}getBytesDownloadedEvent(e,i,r,c){return new CustomEvent("bytesDownloaded",{detail:{bytes:e,uncompressedSize:i,url:r,done:c}})}getBytesDownloadErrorEvent(e,i){return new CustomEvent("downloadedError",{detail:{url:e,error:i}})}decompressBrotli(e){const i=atob(e),r=new Uint8Array(i.length);for(let n=0;n<i.length;n++)r[n]=i.charCodeAt(n);const c=new Int8Array(r.length);for(let n=0;n<r.length;n++)c[n]=r[n]>=128?r[n]-256:r[n];return tt(c).buffer}async fetchAsset(e,i,r,c,d){const n=i+r,a=e.find(h=>h.file===r).uncompressedSize,m=(h,E,S,R)=>Ue(this,le,$e).call(this,this.getBytesDownloadedEvent(h,E,S,R));try{const E=(await fetch(n)).body?.getReader();if(!E)throw new Error("Failed to get reader from response body.");let S=0;const R=new ReadableStream({async start(O){await P();async function P(){const{done:B,value:re}=await E.read();if(B){O.close(),m(S,a,n,!0);return}re&&(O.enqueue(re),S+=re.length,m(S,a,n,!1)),await P()}}}),k=new Response(R);if(c){const O=await k.json(),{base64EncodedValue:P}=O;if(d==="gzip"){await Ue(this,le,et).call(this,P);return}return this.decompressBrotli(P)}else return await k.arrayBuffer()}catch(h){Ue(this,le,$e).call(this,this.getBytesDownloadErrorEvent(n,h))}}}le=new WeakSet,$e=function(t){this.dispatchEvent(t)},et=async function(t){const e=Uint8Array.from(atob(t),h=>h.charCodeAt(0)),r=new Blob([e]).stream().pipeThrough(new DecompressionStream("gzip")),c=await new Response(r).arrayBuffer(),d=new TextDecoder().decode(new Uint8Array(c)),n=new Blob([d],{type:"application/javascript"}),a=URL.createObjectURL(n);tt=(await import(a)).BrotliDecode,this.canDecompress=!0,URL.revokeObjectURL(a)};var Jt=Object.defineProperty,Xt=(t,e,i)=>e in t?Jt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,it=(t,e,i)=>Xt(t,typeof e!="symbol"?e+"":e,i);class zt{constructor(){it(this,"version",{webSDK:"",extractionLib:{version:"",sdkId:""},faceTracker:""}),it(this,"debugLogs",[])}appendLog(e){this.debugLogs.push(e)}transferLogs(){}generateHTMLTable(){return`
1
+ var Nt="0.1.0-beta.3";const U={RESULTS:"results",ERROR:"error",APPEVENT:"appEvent",CANCELLED:"cancelled",DESTROYED:"destroyed",LOGS:"logs"};var je=(t=>(t.measurement="Measurement",t.collector="Collector",t.camera="Camera",t.app="App",t))(je||{});const O={INFO:"INFO",WARN:"WARN",ERROR:"ERROR"},N={CAMERA_STARTED:"CAMERA_STARTED",APP_LOADED:"APP_LOADED",MEASUREMENT_PREPARED:"MEASUREMENT_PREPARED",ASSETS_DOWNLOADED:"ASSETS_DOWNLOADED",MEASUREMENT_STARTED:"MEASUREMENT_STARTED",MEASUREMENT_COMPLETED:"MEASUREMENT_COMPLETED",CAMERA_PERMISSION_GRANTED:"CAMERA_PERMISSION_GRANTED",INTERMEDIATE_RESULTS:"INTERMEDIATE_RESULTS",RESULTS_RECEIVED:"RESULTS_RECEIVED",MEASUREMENT_CANCELED:"MEASUREMENT_CANCELED",CONSTRAINT_VIOLATION:"CONSTRAINT_VIOLATION",PAGE_UNLOADED:"PAGE_UNLOADED",PAGE_VISIBILITY_CHANGE:"PAGE_VISIBILITY_CHANGE"},Lt={CAMERA_STARTED:{event:N.CAMERA_STARTED,level:O.INFO},APP_LOADED:{event:N.APP_LOADED,level:O.INFO},MEASUREMENT_PREPARED:{event:N.MEASUREMENT_PREPARED,level:O.INFO},ASSETS_DOWNLOADED:{event:N.ASSETS_DOWNLOADED,level:O.INFO},MEASUREMENT_STARTED:{event:N.MEASUREMENT_STARTED,level:O.INFO},MEASUREMENT_COMPLETED:{event:N.MEASUREMENT_COMPLETED,level:O.INFO},CAMERA_PERMISSION_GRANTED:{event:N.CAMERA_PERMISSION_GRANTED,level:O.INFO},INTERMEDIATE_RESULTS:{event:N.INTERMEDIATE_RESULTS,level:O.INFO},RESULTS_RECEIVED:{event:N.RESULTS_RECEIVED,level:O.INFO},MEASUREMENT_CANCELED:{event:N.MEASUREMENT_CANCELED,level:O.WARN},CONSTRAINT_VIOLATION:{event:N.CONSTRAINT_VIOLATION,level:O.ERROR},PAGE_UNLOADED:{event:N.PAGE_UNLOADED,level:O.INFO},PAGE_VISIBILITY_CHANGE:{event:N.PAGE_VISIBILITY_CHANGE,level:O.INFO}},re={DESTROY:"destroy",CANCEL:"cancel",SET_THEME:"setTheme",SET_LANGUAGE:"setLanguage",GET_LOGS:"getLogs"};var Ye=(t=>(t.CAMERA_PERMISSION_DENIED="CAMERA_PERMISSION_DENIED",t.WORKER_ERROR="WORKER_ERROR",t.PROFILE_INFO_NOT_SET="PROFILE_INFO_NOT_SET",t.NO_DEVICES_FOUND="NO_DEVICES_FOUND",t.PAGE_NOT_VISIBLE="PAGE_NOT_VISIBLE",t.CAMERA_START_FAILED="CAMERA_START_FAILED",t.MEASUREMENT_LOW_SNR="MEASUREMENT_LOW_SNR",t.COLLECTOR="COLLECTOR",t.WEBSOCKET_DISCONNECTED="WEBSOCKET_DISCONNECTED",t.MEASUREMENT_PREPARE_FAILED="MEASUREMENT_PREPARE_FAILED",t))(Ye||{}),Je="0.1.0-beta.2",J=(t=>(t.DELETE="DELETE",t.GET="GET",t.PATCH="PATCH",t.POST="POST",t.PUT="PUT",t.CONNECT="CONNECT",t))(J||{}),V=(t=>(t.ON_BEFORE_REST_CALL_ERROR="ON_BEFORE_REST_CALL_ERROR",t))(V||{});const Xe=typeof DedicatedWorkerGlobalScope<"u",be=async({baseUrl:t,urlFragment:e,method:i,headers:r,data:c},d)=>{const n=`${t}/${e}`;let a={Code:"",Message:""};try{const u=await fetch(n,{method:i,cache:"no-store",credentials:"include",headers:r,...c!=null&&{body:JSON.stringify(c)}}),h=u.headers.get("content-type"),E=u.status.toString();a={Code:"UNSUPPORTED_RESPONSE_CONTENT_TYPE",Message:"UNSUPPORTED_RESPONSE_CONTENT_TYPE"},E==="503"&&(a={Code:"SERVICE_UNAVAILABLE",Message:"Service unavailable"}),E==="429"&&(a={Code:"TOO_MANY_REQUESTS",Message:"Too many requests"}),h!=null&&(h.startsWith("application/json;")&&(a=await u.json()),h.startsWith("text/plain;")&&(a={data:await u.text()}));let _=u.headers;if(Xe){const C={};u.headers.forEach((k,I)=>{C[I]=k}),_=C}try{d(E,E==="200"?void 0:a)}catch(C){console.error("Error running onAfterRESTCall callback",C)}return{status:E,headers:_,body:a}}catch(u){return u instanceof SyntaxError?a={Code:"SYNTAX_ERROR",Message:"SYNTAX_ERROR"}:a={Code:"UNEXPECTED_ERROR",Message:"UNEXPECTED_ERROR"},{status:"UNKNOWN",headers:Xe?{}:new Headers,body:a}}},_e=()=>new Headers({"Content-Type":"application/json"});var Dt=Object.defineProperty,It=(t,e,i)=>e in t?Dt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,xt=(t,e,i)=>It(t,e+"",i);class Fe{constructor(e){xt(this,"parent"),this.parent=e}async onBeforeRESTCall(){try{return this.parent.onBeforeRESTCall(),{Code:"SUCCESS",Message:"SUCCESS"}}catch{return{Code:V.ON_BEFORE_REST_CALL_ERROR,Message:V.ON_BEFORE_REST_CALL_ERROR}}}getDefaults(e){return{baseUrl:JSON.parse(this.parent.getUrl()).http.slice(0,-1),method:J[e],headers:_e()}}getHeaderWithDeviceToken(){const e=_e();return e.set("Authorization",`Bearer ${this.parent.getSession().deviceToken}`),e}getHeaderWithUserToken(){const e=_e();return e.set("Authorization",`Bearer ${this.parent.getSession().userToken}`),e}getHeaderWithSessionEnabled(){const e=_e();return e.set("x-nura-session","true"),e}}class Ft extends Fe{async create(e,i){const{Code:r,Message:c}=await this.onBeforeRESTCall();if(r===V.ON_BEFORE_REST_CALL_ERROR)return{status:r,body:{Code:r,Message:c},headers:new Headers};const{status:d,body:n,headers:a}=await be({...this.getDefaults(J.POST),headers:i==="device"?this.getHeaderWithDeviceToken():this.getHeaderWithUserToken(),urlFragment:"measurements",data:e},this.parent.onAfterRESTCall);return d==="200"&&this.parent.setSession({lastMeasurementId:n.ID}),{status:d,body:n,headers:a}}}class Mt extends Fe{async retrieveSdkConfigData(e,i){const{Code:r,Message:c}=await this.onBeforeRESTCall();if(r===V.ON_BEFORE_REST_CALL_ERROR)return{status:r,body:{Code:r,Message:c},headers:new Headers};const{status:d,body:n,headers:a}=await be({...this.getDefaults(J.POST),headers:i==="device"?this.getHeaderWithDeviceToken():this.getHeaderWithUserToken(),urlFragment:"studies/sdkconfig",data:e},this.parent.onAfterRESTCall);return d==="200"&&this.parent.setSession({studyCfgData:n.ConfigFile,studyCfgHash:n.MD5Hash}),{status:d,body:n,headers:a}}}class Pt extends Fe{async renew(e,i){const{Code:r,Message:c}=await this.onBeforeRESTCall();if(r===V.ON_BEFORE_REST_CALL_ERROR)return{status:r,body:{Code:r,Message:c},headers:new Headers};const{status:d,body:n,headers:a}=await be({...this.getDefaults(J.POST),headers:i==="device"?this.getHeaderWithDeviceToken():this.getHeaderWithUserToken(),urlFragment:"auths/renew",data:e},this.parent.onAfterRESTCall);if(d==="200"){const u=n.Token,h=n.RefreshToken,E={...i==="user"&&{userToken:u,userRefreshToken:h},...i==="device"&&{deviceToken:u,deviceRefreshToken:h}};this.parent.setSession(E)}return{status:d,body:n,headers:a}}async validate(e){const{Code:i,Message:r}=await this.onBeforeRESTCall();return i===V.ON_BEFORE_REST_CALL_ERROR?{status:i,body:{Code:i,Message:r},headers:new Headers}:await be({...this.getDefaults(J.GET),headers:e==="device"?this.getHeaderWithDeviceToken():this.getHeaderWithUserToken(),urlFragment:"auth/v1/validate"},this.parent.onAfterRESTCall)}}var Wt=Object.defineProperty,ze=t=>{throw TypeError(t)},Ut=(t,e,i)=>e in t?Wt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Me=(t,e,i)=>Ut(t,typeof e!="symbol"?e+"":e,i),qe=(t,e,i)=>e.has(t)||ze("Cannot "+i),Pe=(t,e,i)=>(qe(t,e,"read from private field"),i?i.call(t):e.get(t)),Ze=(t,e,i)=>e.has(t)?ze("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),ge=(t,e,i,r)=>(qe(t,e,"write to private field"),e.set(t,i),i),ne,X;class $t{constructor(e){Ze(this,ne,{http:new URL("https://api.deepaffex.ai")}),Ze(this,X),Me(this,"onBeforeRESTCall"),Me(this,"onAfterRESTCall"),Me(this,"http"),ge(this,X,{deviceToken:"",deviceRefreshToken:"",userToken:"",userRefreshToken:"",deviceId:"",roleId:"",userId:"",selectedStudy:"",lastMeasurementId:"",studyCfgHash:"",studyCfgData:""}),this.http={measurements:new Ft(this),studies:new Mt(this),auths:new Pt(this)},this.onBeforeRESTCall=e?.onBeforeRESTCall?e.onBeforeRESTCall:()=>{},this.onAfterRESTCall=e?.onAfterRESTCall?e.onAfterRESTCall:()=>{},e?.url!=null&&ge(this,ne,e.url)}static new(e){return new this(e??void 0)}getUrl(){return JSON.stringify(Pe(this,ne))}setUrl(e){ge(this,ne,{http:new URL(e)})}getSession(){return Pe(this,X)}setSession(e){const i=["deviceToken","deviceRefreshToken","userToken","userRefreshToken","deviceId","userId","roleId","selectedStudy","lastMeasurementId","studyCfgHash","studyCfgData"];Object.keys(e).every(d=>i.includes(d)&&typeof e[d]=="string")&&ge(this,X,{...Pe(this,X),...e})}}ne=new WeakMap,X=new WeakMap;const Bt=t=>$t.new(t);var Gt=Object.defineProperty,Qe=t=>{throw TypeError(t)},Ht=(t,e,i)=>e in t?Gt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Vt=(t,e,i)=>Ht(t,e+"",i),Kt=(t,e,i)=>e.has(t)||Qe("Cannot "+i),jt=(t,e,i)=>e.has(t)?Qe("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),We=(t,e,i)=>(Kt(t,e,"access private method"),i),oe,Ue,et;let tt=t=>new Int8Array(t);class Yt extends EventTarget{constructor(){super(...arguments),jt(this,oe),Vt(this,"canDecompress",!1)}static init(){return new this}dispatch(e,i){this.dispatchEvent(new CustomEvent(e,{detail:i}))}getBytesDownloadedEvent(e,i,r,c){return new CustomEvent("bytesDownloaded",{detail:{bytes:e,uncompressedSize:i,url:r,done:c}})}getBytesDownloadErrorEvent(e,i){return new CustomEvent("downloadedError",{detail:{url:e,error:i}})}decompressBrotli(e){const i=atob(e),r=new Uint8Array(i.length);for(let n=0;n<i.length;n++)r[n]=i.charCodeAt(n);const c=new Int8Array(r.length);for(let n=0;n<r.length;n++)c[n]=r[n]>=128?r[n]-256:r[n];return tt(c).buffer}async fetchAsset(e,i,r,c,d){const n=i+r,a=e.find(h=>h.file===r).uncompressedSize,u=(h,E,_,C)=>We(this,oe,Ue).call(this,this.getBytesDownloadedEvent(h,E,_,C));try{const E=(await fetch(n)).body?.getReader();if(!E)throw new Error("Failed to get reader from response body.");let _=0;const C=new ReadableStream({async start(I){await W();async function W(){const{done:G,value:M}=await E.read();if(G){I.close(),u(_,a,n,!0);return}M&&(I.enqueue(M),_+=M.length,u(_,a,n,!1)),await W()}}}),k=new Response(C);if(c){const I=await k.json(),{base64EncodedValue:W}=I;if(d==="gzip"){await We(this,oe,et).call(this,W);return}return this.decompressBrotli(W)}else return await k.arrayBuffer()}catch(h){We(this,oe,Ue).call(this,this.getBytesDownloadErrorEvent(n,h))}}}oe=new WeakSet,Ue=function(t){this.dispatchEvent(t)},et=async function(t){const e=Uint8Array.from(atob(t),h=>h.charCodeAt(0)),r=new Blob([e]).stream().pipeThrough(new DecompressionStream("gzip")),c=await new Response(r).arrayBuffer(),d=new TextDecoder().decode(new Uint8Array(c)),n=new Blob([d],{type:"application/javascript"}),a=URL.createObjectURL(n);tt=(await import(a)).BrotliDecode,this.canDecompress=!0,URL.revokeObjectURL(a)};var Jt=Object.defineProperty,Xt=(t,e,i)=>e in t?Jt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,it=(t,e,i)=>Xt(t,typeof e!="symbol"?e+"":e,i);class zt{constructor(){it(this,"version",{webSDK:"",extractionLib:{version:"",sdkId:""},faceTracker:""}),it(this,"debugLogs",[])}appendLog(e){this.debugLogs.push(e)}transferLogs(){}generateHTMLTable(){return`
2
2
  <html lang="en">
3
3
  <head>
4
4
  <meta charset="UTF-8">
@@ -736,4 +736,4 @@ const U={RESULTS:"results",ERROR:"error",APPEVENT:"appEvent",CANCELLED:"cancelle
736
736
  <\/script>
737
737
  </body>
738
738
  </html>
739
- `}openLogInNewWindow(){const e=this.generateHTMLTable(),i=new Blob([e],{type:"text/html"}),r=URL.createObjectURL(i);window.open(r,"_blank")}}var qt=Object.defineProperty,Zt=(t,e,i)=>e in t?qt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Ce=(t,e,i)=>Zt(t,typeof e!="symbol"?e+"":e,i);class Fe{constructor(e,i){Ce(this,"workerUrl"),Ce(this,"worker"),this.worker=e,this.workerUrl=i}static init(e,i,r){const c=new Blob([e],{type:"application/javascript"}),d=URL.createObjectURL(c),n=r||`WORKER${String(new Date().getTime())}`,a=new Worker(new URL(d,import.meta.url),{name:n,type:i});return new Fe(a,d)}destroy(){this.worker&&(this.worker.terminate(),URL.revokeObjectURL(this.worker))}}const Qt=(t,e,i,r)=>{const c=t/e,d=i/r;let n=0,a=0;c>d?(n=t,a=t/d):(a=e,n=e*d);const m=(t-n)/2,h=(e-a)/2;return{width:n||0,height:a||0,offsetX:m||0,offsetY:h||0}},ei=(t,e,i,r)=>{const c=(t-i)/2,d=(e-r)/2;return{width:i||0,height:r||0,offsetX:c||0,offsetY:d||0}},ti=(t,e,i,r)=>{const c=t/e,d=i/r;let n=0,a=0;c>d?(a=e,n=e*d):(n=t,a=t/d);const m=(t-n)/2,h=(e-a)/2;return{width:n||0,height:a||0,offsetX:m||0,offsetY:h||0}},ii=(t,e)=>{switch(t){case"none":return ei(...e);case"cover":return Qt(...e);case"contain":default:return ti(...e)}},st=t=>/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(t),si=t=>t===void 0?!0:!(typeof t.mediaPipe<"u"&&typeof t.mediaPipe!="boolean"||typeof t.beforeRESTCall<"u"&&typeof t.beforeRESTCall!="boolean"||typeof t.afterRESTCall<"u"&&typeof t.afterRESTCall!="boolean"||typeof t.extractionLibWasm<"u"&&typeof t.extractionLibWasm!="boolean"||typeof t.apiClient<"u"&&typeof t.apiClient!="boolean"||typeof t.extractionWorker<"u"&&typeof t.extractionWorker!="boolean"||typeof t.faceTrackerWorkers<"u"&&typeof t.faceTrackerWorkers!="boolean"||typeof t.sdk<"u"&&typeof t.sdk!="boolean"),ai=(t,e)=>{const i={...t};if(e.logger)if(si(e.logger))i.logger={...i.logger,...e.logger};else return{results:"invalid"};if(e.apiUrl!==void 0)if(typeof e.apiUrl=="string")i.apiUrl=e.apiUrl;else return{results:"invalid"};if(e.metrics!==void 0)if(typeof e.metrics=="boolean")i.metrics=e.metrics;else return{results:"invalid"};if(e.mirrorVideo!==void 0)if(typeof e.mirrorVideo=="boolean")i.mirrorVideo=e.mirrorVideo;else return{results:"invalid"};if(e.displayMediaStream!==void 0)if(typeof e.displayMediaStream=="boolean")i.displayMediaStream=e.displayMediaStream;else return{results:"invalid"};if(e.assetFolder!==void 0)if(typeof e.assetFolder=="string")i.assetFolder=e.assetFolder;else return{results:"invalid"};if(e.mediaElement!==void 0)if(e.mediaElement instanceof HTMLDivElement)i.mediaElement=e.mediaElement;else return{results:"invalid"};if(e.constraintOverrides!==void 0){let r=function(n,a){if(!(n in d))return!1;const m=d[n];return typeof a===m};const d=Object.fromEntries(Object.entries({backLightMaxPixels_pct:30,backLightSearchMult:1.5,backLightThresh:240,boxCenterX_pct:50,boxCenterY_pct:50,boxHeight_pct:99,boxWidth_pct:50,cameraRot_chunkThresh:.7853981633974483,cameraRot_windowThresh:.2617993877991494,checkBackLight:!1,checkCameraMovement:!1,checkCentered:!1,checkDistance:!1,checkEyebrowMovement:!1,checkFaceDirection:!1,checkLighting:!1,checkMaxDistance:!1,checkMinFps:!1,checkMovement:!1,chunkMovementThresh_pct:60,enableDebugLog:!1,enableFigures:!1,faceRotLR_thresh:.33,faceRotUD_lowerthresh:.25,faceRotUD_upperThresh:5,hy_faceRotLR_thresh:.05,hy_maxFaceRotLR_deg:2,hy_maxFaceRotUD_deg:2,hy_minInterPupilDist_px:5,hy_minimumFps:1,maxEyebrowMovement_mm:3,maxFaceRotLR_deg:12.5,maxFaceRotUD_deg:25,maxMovement_mm:10,minInterPupilDist_px:100,minimumFps:26,movementWindow_ms:2e3,threshBright:225,threshDark:48}).map(([n,a])=>[n,typeof a]));for(const n in e.constraintOverrides){const a=e.constraintOverrides[n];if(!r(n,a))return{results:"invalid"}}i.constraintOverrides=e.constraintOverrides}return{results:"valid",settings:i}},ri=t=>typeof t.age!="number"||t.age<13||t.age>120?(console.error("Invalid age. It should be a number between 13 and 120."),!1):typeof t.height!="number"||t.height<120||t.height>220?(console.error("Invalid height. It should be a number between 120 and 220."),!1):typeof t.weight!="number"||t.weight<30||t.weight>300?(console.error("Invalid weight. It should be a number between 30 and 300."),!1):typeof t.sex!="number"||t.sex<1||t.sex>3?(console.error("Invalid sex. It should be a number between 1 and 3."),!1):typeof t.diabetes!="number"||t.diabetes<4||t.diabetes>6?(console.error("Invalid diabetes. It should be a number between 4 and 6."),!1):typeof t.bloodPressureMedication!="number"||t.bloodPressureMedication!==0&&t.bloodPressureMedication!==1?(console.error("Invalid bloodPressureMedication. It should be either 0 or 1."),!1):typeof t.smoking!="number"||t.smoking!==0&&t.smoking!==1?(console.error("Invalid smoking. It should be either 0 or 1."),!1):!0;var u=(t=>(t.beforeRESTCall="Before REST call event",t.afterRESTCall="After REST call event",t.mediaPipe="MediaPipe",t.extractionLibWasm="DFX Extraction lib WASM",t.apiClient="DFX API client",t.webSocket="WebSocket",t.sdk="SDK",t.dfxWorker="DFX Worker",t))(u||{});const ni=t=>{switch(t){case"Before REST call event":return"red";case"After REST call event":return"orange";case"MediaPipe":return"green";case"DFX Extraction lib WASM":return"violet";case"DFX API client":return"#d34110";case"WebSocket":return"#d34110";case"SDK":return"#d34110";case"DFX Worker":return"#ad4393";default:return"black"}};class at{constructor(e=1e3){Ce(this,"timestamps",[]),Ce(this,"windowMs"),this.windowMs=e}tick(e=performance.now()){for(this.timestamps.push(e);this.timestamps.length>0&&e-this.timestamps[0]>this.windowMs;)this.timestamps.shift()}get fps(){const e=this.timestamps.length,i=this.timestamps.at(-1)-this.timestamps[0]||1;return e/i*1e3}get frameCount(){return this.timestamps.length}reset(){this.timestamps=[]}}var oi=Object.defineProperty,li=(t,e,i)=>e in t?oi(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,rt=(t,e,i)=>li(t,typeof e!="symbol"?e+"":e,i);const ci=()=>{const t=new Date,e=(t.getMonth()+1).toString().padStart(2,"0"),i=t.getDate().toString().padStart(2,"0"),r=t.getFullYear();let c=t.getHours();const d=t.getMinutes().toString().padStart(2,"0"),n=t.getSeconds().toString().padStart(2,"0"),a=t.getMilliseconds().toString().padStart(3,"0"),m=c>=12?"PM":"AM";return c=c%12||12,`[${e}/${i}/${r}, ${c}:${d}:${n}.${a} ${m}]`};class nt{constructor(){rt(this,"mertics",new zt),rt(this,"version",{webSDK:"",extractionLib:{version:"",sdkId:""},faceTracker:""})}retrieveLogs(){this.mertics.transferLogs(),this.mertics.openLogInNewWindow(),this.mertics.debugLogs=[]}setVersion(e){this.version=e,this.mertics.version=e}log(e,i,r,c=!1,d={}){const n=ci();if(c)this.mertics.appendLog({thread:"Main",timestamp:n,category:i,message:e,meta:d});else{const a=`[${i}]`,m=" ",h=e,E=`color:${r}; font-weight:800;`,S=`color:${ni(i)}; font-weight:700;`;console.log("%c%s%c%s%c%s%c%s",E,n,S,a,"background:inherit;",m,"font-style: italic;",h)}}info(e,i){this.log(e,i,"blue")}warn(e,i){this.log(e,i,"orange")}error(e,i){this.log(e,i,"red")}debug(e,i){this.log(e,i,"green")}start(){console.log("%c%s","color: #5e5e5e; background-color: #2d2d2d; letter-spacing: 0.1em; text-shadow: -1px -1px 1px #111, 2px 2px 1px #363636; font-size: 36px; padding: 20px 40px; text-align: center; text-transform: uppercase; text-rendering: optimizeLegibility;","Anura Web Core SDK"),console.log(`Version: ${this.version.webSDK}`),console.log("https://www.deepaffex.ai")}}const di={SEX_NOT_PROVIDED:1,SEX_ASSIGNED_MALE_AT_BIRTH:2,SEX_ASSIGNED_FEMALE_AT_BIRTH:3,DIABETES_NONE:4,DIABETES_TYPE1:5,DIABETES_TYPE2:6,SMOKER_TRUE:0,SMOKER_FALSE:1,BLOOD_PRESSURE_MEDICATION_TRUE:1,BLOOD_PRESSURE_MEDICATION_FALSE:0},V={SEX_ASSIGNED_AT_BIRTH:1,AGE_YEARS:2,HEIGHT_CM:3,WEIGHT_KG:4,SMOKER:5,BLOOD_PRESSURE_MEDICATION:7,DIABETES:8};var ot=(t=>(t[t.BGR=1]="BGR",t[t.RGB=2]="RGB",t[t.BGRA=3]="BGRA",t[t.RGBA=4]="RGBA",t[t.Infrared=5]="Infrared",t[t.Infrared888=6]="Infrared888",t[t.BGR_Infrared=7]="BGR_Infrared",t[t.RGB_Infrared=8]="RGB_Infrared",t[t.Gray=9]="Gray",t))(ot||{});const K={ASSETS_NOT_DOWNLOADED:"ASSETS_NOT_DOWNLOADED",NOT_LOADED:"NOT_LOADED",LOADING:"LOADING",LOADED:"LOADED",READY:"READY"},Re={COLLECTOR:"COLLECTOR",ASSET_DOWNLOAD:"ASSET_DOWNLOAD",WEB_SOCKET:"WEB_SOCKET"},ke={CONTAIN:"contain",COVER:"cover",NONE:"none"};var W=(t=>(t.INIT="INIT",t.READY="READY",t.INIT_TFJS="INIT_TFJS",t.SET_PORT="SET_PORT",t.TRACK="TRACK",t.RESULTS_READY="RESULTS_READY",t.WARM_UP="WARM_UP",t.DESTROY="DESTROY",t.LANDMARKS="LANDMARKS",t.VIDEO_FRAME="VIDEO_FRAME",t.SCALE_FACTOR_CHANGED="SCALE_FACTOR_CHANGED",t))(W||{}),hi=Object.defineProperty,lt=t=>{throw TypeError(t)},mi=(t,e,i)=>e in t?hi(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,w=(t,e,i)=>mi(t,typeof e!="symbol"?e+"":e,i),Be=(t,e,i)=>e.has(t)||lt("Cannot "+i),ct=(t,e,i)=>(Be(t,e,"read from private field"),i?i.call(t):e.get(t)),dt=(t,e,i)=>e.has(t)?lt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),ui=(t,e,i,r)=>(Be(t,e,"write to private field"),e.set(t,i),i),fi=(t,e,i)=>(Be(t,e,"access private method"),i),ce,Ge,ht;const pi=class yt{constructor(e,i,r){dt(this,Ge),dt(this,ce),w(this,"mediaElement"),w(this,"numOfFramesPresented",0),w(this,"workers",[]),w(this,"numOftrackedVideoFrames",0),w(this,"warmupFrameNumber",0),w(this,"videoCallbackId",0),w(this,"numOfWorkers",4),w(this,"isLoggingFaceTrackerWorkers",!1),w(this,"isLoggingSdk",!1),w(this,"workerIndex",0),w(this,"metrics",!1),w(this,"videoFpsTracker",new at(1e3)),w(this,"faceTrackerFpsTracker",new at(1e3)),w(this,"videoElementSize",{width:0,height:0,offsetX:0,offsetY:0}),w(this,"videoElement",document.createElement("video")),w(this,"frameWidth",0),w(this,"frameHeight",0),w(this,"mirrorVideo",!0),w(this,"settings",{faceTrackerWidth:0,faceTrackerHeight:0,displayMediaStream:!0,objectFit:ke.COVER}),w(this,"isExtracting",!1),w(this,"starRating",0),w(this,"scaleFactor",1),w(this,"warmupIndex",0),w(this,"warmingUp",!0),w(this,"ftWorkerIndex",0),w(this,"lastFrameNumber",-1),w(this,"on",{faceTrackersReady:null,frameAvailable:null,landmarksAvailable:null,scaleFactorChanged:null});const{mediaElement:c,mirrorVideo:d,numOfWorkers:n,isLoggingFaceTrackerWorkers:a,isLoggingSdk:m,metrics:h,displayMediaStream:E}=i;this.numOfWorkers=n,this.isLoggingFaceTrackerWorkers=a,this.isLoggingSdk=m,this.metrics=h,ui(this,ce,r),this.settings.displayMediaStream=E,this.mirrorVideo=d,this.mediaElement=c,this.videoFrameCallback=this.videoFrameCallback.bind(this),this.workers=e,this.scaleFactor=i.scaleFactor,this.initWorkerOnMessage(i.models),this.videoElement.muted=!0,this.videoElement.playsInline=!0,this.videoElement.preload="auto"}static async init(e,i){const{numOfWorkers:r,faceTrackerCode:c}=e,d=[],n=new TextDecoder().decode(new Uint8Array(c));if(r>0)for(let a=1;a<=r;a+=1){const m=Fe.init(n,"module",`FACE_TRACKER_WORKER_${a-1}`);d.push({ft:m,channel:new MessageChannel,isBusy:!1})}return new yt(d,e,i)}initWorkerOnMessage(e){const i=window.matchMedia("(orientation: portrait)").matches,r=i?360:640,c=i?640:360;this.workers.forEach(d=>{d.ft.worker.postMessage({action:W.INIT_TFJS,payload:{width:r,height:c,models:e,scaleFactor:this.scaleFactor}}),d.ft.worker.postMessage({action:W.SET_PORT,payload:{port:d.channel.port2}},[d.channel.port2]),d.ft.worker.onmessage=n=>{const{action:a,payload:m}=n.data;switch(a){case W.INIT_TFJS:break;case W.READY:{const{workerName:h,version:E,workerId:S,backend:R}=m;this.on.faceTrackersReady&&this.on.faceTrackersReady(h,E,S,R);break}case W.LANDMARKS:{this.faceTrackerFpsTracker.tick(),d.isBusy=!1,this.warmingUp&&this.warmupIndex++;const{face:h,annotations:E,frameTimestamp:S}=m;this.on.landmarksAvailable&&this.on.landmarksAvailable(h,E,S);break}case W.DESTROY:{const{workerId:h}=m;this.workers[h].ft.destroy();break}}}})}getMediaElement(){return this.mediaElement}setIsExtracting(e){this.isExtracting=e}destroyWorkers(){setTimeout(async()=>{this.videoCallbackId&&this.videoElement.cancelVideoFrameCallback(this.videoCallbackId),this.workers.forEach(e=>e.ft.worker.postMessage({action:W.DESTROY}))},200)}createMediaElements(){this.videoElement.addEventListener("ended",async()=>{this.destroyWorkers()});const e=document.createElement("div"),i=this.settings.displayMediaStream?this.videoElement:e,r="white";this.mediaElement.appendChild(i),i.style.width="100%",i.style.height="100%",i.style.boxSizing="border-box",this.settings.displayMediaStream&&(i.style.border=`1px solid ${r}`),i.style.objectFit=this.settings.objectFit,i.style.transform=`scale(${this.mirrorVideo?"-1":"1"},1)`,this.settings.displayMediaStream||(i.style.height=`${this.frameHeight}px`,i.style.width=`${this.frameWidth}px`),new ResizeObserver(d=>{const{contentRect:n,target:a}=d[0],{width:m,height:h}=n,{x:E,y:S}=a.getBoundingClientRect(),{faceTrackerWidth:R,faceTrackerHeight:k}=this.settings;this.videoElementSize=ii(this.settings.objectFit,[m,h,this.frameWidth,this.frameHeight]);const{width:O,height:P}=this.videoElementSize;if(!this.settings.displayMediaStream){const B=this.settings.objectFit===ke.NONE;i.style.height=`${Math.trunc(B?P:h)}px`,i.style.width=`${Math.trunc(B?O:m)}px`}this.mediaElement.dispatchEvent(new CustomEvent("mediaElementSizeChanged",{detail:{mediaElementSize:{width:m,height:h,x:E,y:S},videoElementSize:this.videoElementSize,frameInfo:{mediaStreamWidth:this.frameWidth,mediaStreamHeight:this.frameHeight,faceTrackerWidth:R,faceTrackerHeight:k},isPortrait:h>m,aspectRatio:m/h}}))}).observe(this.mediaElement)}log(e,i,r){this.isLoggingSdk&&ct(this,ce).info(e,i),this.metrics&&ct(this,ce).log(e,i,"",!0,r)}videoFrameCallback(e,i){const{presentedFrames:r,captureTime:c,expectedDisplayTime:d,mediaTime:n}=i;this.videoFpsTracker.tick();const a=c===void 0?d:c;this.numOfFramesPresented=r;const m=`Number of frames presented: ${this.numOfFramesPresented} - time: ${a}`;let h=0;if(n&&n>0?h=n*1e3:c&&c>0?h=c>1e6?c-performance.timeOrigin:c:h=e,this.log(m,u.sdk,{captureTime:a,presentedFrames:r}),this.warmingUp)if(this.warmupIndex>=this.numOfWorkers)this.warmingUp=!1;else{const E=this.workers[this.warmupIndex];if(!E.isBusy){E.isBusy=!0;const S=new VideoFrame(this.videoElement,{timestamp:h});E.ft.worker.postMessage({action:"TRACK",payload:{frame:S,frameTimestamp:h,frameNumber:this.numOfFramesPresented}},[S])}}if(!this.warmingUp){const E=new VideoFrame(this.videoElement,{timestamp:h});let S=!1;for(let R=0;R<this.numOfWorkers;R++){this.ftWorkerIndex=(this.ftWorkerIndex+1)%this.numOfWorkers;const k=this.workers[this.ftWorkerIndex];if(k&&!k.isBusy){k.isBusy=!0,this.on.frameAvailable(h,this.numOfFramesPresented,this.lastFrameNumber,!0),k.ft.worker.postMessage({action:"TRACK",payload:{frame:E,frameTimestamp:h,frameNumber:this.numOfFramesPresented}},[E]),S=!0;break}}S||this.on.frameAvailable(h,this.numOfFramesPresented,this.lastFrameNumber,!1,E)}this.lastFrameNumber=this.numOfFramesPresented,this.videoCallbackId=this.videoElement.requestVideoFrameCallback(this.videoFrameCallback)}setFaceTrackerMediaStreamResolution(e,i){(e<=360||i<=360)&&(this.scaleFactor=1),this.settings.faceTrackerWidth=e*this.scaleFactor,this.settings.faceTrackerHeight=i*this.scaleFactor,this.workers.forEach(r=>r.ft.worker.postMessage({action:W.SCALE_FACTOR_CHANGED,payload:{scaleFactor:this.scaleFactor}})),this.on.scaleFactorChanged&&this.on.scaleFactorChanged(this.scaleFactor)}async setMediaStream(e){if(e instanceof MediaStream)try{const{settings:i,constraints:r}=await fi(this,Ge,ht).call(this,e,this.videoElement);await this.videoElement.play(),this.settings.displayMediaStream||(this.videoElement.style.visibility="none");const{width:c,height:d}=i;return this.setFaceTrackerMediaStreamResolution(c??0,d??0),this.frameWidth=c||1,this.frameHeight=d||1,this.log(`Face tracker resolution: ${c} x ${d} pixels. Video resolution: ${this.frameWidth} x ${this.frameHeight} pixels`,u.sdk,{ftWidth:c,ftHeight:d,frameWidth:this.frameWidth,frameHeight:this.frameHeight}),this.createMediaElements(),this.videoCallbackId=this.videoElement.requestVideoFrameCallback(this.videoFrameCallback),!0}catch(i){return console.log("Error applying face tracker video track constraints",i),!1}return!1}stopTracking(){this.videoCallbackId&&this.videoElement.cancelVideoFrameCallback(this.videoCallbackId),this.videoElement.pause(),this.videoElement.srcObject=null}};ce=new WeakMap,Ge=new WeakSet,ht=async function(t,e){e.srcObject=t,await new Promise(r=>e.onloadedmetadata=r);const[i]=t.getVideoTracks();return{constraints:i.getConstraints(),settings:i.getSettings()}};let Ei=pi;var T=(t=>(t.INIT="INIT",t.READY="READY",t.SET_MODE="SET_MODE",t.SET_NUMBER_OF_CHUNKS="SET_NUMBER_OF_CHUNKS",t.SET_TARGET_FPS="SET_TARGET_FPS",t.SET_CHUNK_DURATION_SECONDS="SET_CHUNK_DURATION_SECONDS",t.SET_FRAME_ORDER="SET_FRAME_ORDER",t.GET_CONSTRAINTS_CONFIG="GET_CONSTRAINTS_CONFIG",t.SET_CONSTRAINTS_CONFIG="SET_CONSTRAINTS_CONFIG",t.SET_FACE_ATTRIBUTE="SET_FACE_ATTRIBUTE",t.RESET_COLLECTION="RESET_COLLECTION",t.CANCEL_COLLECTION="CANCEL_COLLECTION",t.START_COLLECTION="START_COLLECTION",t.SET_PORTS="SET_PORTS",t.COLLECTOR_ERROR="COLLECTOR_ERROR",t.STAR_RATING="STAR_RATING",t.ALL_FACE_TRACKERS_WARMED_UP="ALL_FACE_TRACKERS_WARMED_UP",t.CONSTRAINTS_UPDATED="CONSTRAINTS_UPDATED",t.SHOULD_END_MEASUREMENT_EARLY="SHOULD_END_MEASUREMENT_EARLY",t.GET_LOGS="GET_LOGS",t.NEW_FRAME="NEW_FRAME",t.TRACKING_STATUS="TRACKING_STATUS",t.SCALE_FACTOR_CHANGED="SCALE_FACTOR_CHANGED",t))(T||{}),y=(t=>(t.CONNECT="CONNECT",t.DISCONNECT="DISCONNECT",t.DISCONNECTED="DISCONNECTED",t.LOGIN_WITH_TOKEN_SUCCESS="LOGIN_WITH_TOKEN_SUCCESS",t.SUBSCRIBED_TO_RESULTS="SUBSCRIBED_TO_RESULTS",t.CHUNK_SENT="CHUNK_SENT",t.RESULTS_RECEIVED="RESULTS_RECEIVED",t.CHUNK_ACKNOWLEDGED="CHUNK_ACKNOWLEDGED",t.ERROR="ERROR",t.NETWORK_DELAY="NETWORK_DELAY",t))(y||{}),Ti=Object.defineProperty,mt=t=>{throw TypeError(t)},Si=(t,e,i)=>e in t?Ti(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ut=(t,e,i)=>Si(t,typeof e!="symbol"?e+"":e,i),He=(t,e,i)=>e.has(t)||mt("Cannot "+i),s=(t,e,i)=>(He(t,e,"read from private field"),i?i.call(t):e.get(t)),b=(t,e,i)=>e.has(t)?mt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),f=(t,e,i,r)=>(He(t,e,"write to private field"),e.set(t,i),i),l=(t,e,i)=>(He(t,e,"access private method"),i),bi=(t,e,i,r)=>({set _(c){f(t,e,c)},get _(){return s(t,e,r)}}),x,g,M,v,N,ve,Ae,ye,Oe,de,z,Ne,he,me,_,q,L,ue,F,Le,Z,Q,ee,te,fe,pe,j,Ee,De,ie,Ie,se,Te,A,Se,$,be,o,ft,pt,Et,Ve,Ke,Tt,St,bt,_t,gt,wt,xe,je,p,Ct,Rt,kt,vt,ae,C;const At=Symbol("instance_creation_key"),_i=class Ot{constructor(e){if(b(this,o),b(this,x),b(this,g,{mediaElement:document.createElement("div"),assetFolder:"",apiUrl:"",metrics:!1,logger:{sdk:!1,mediaPipe:!1,beforeRESTCall:!1,afterRESTCall:!1,extractionLibWasm:!1,apiClient:!1,extractionWorker:!1,faceTrackerWorkers:!1},mirrorVideo:!0,displayMediaStream:!0,constraintOverrides:{}}),b(this,M,[{file:"decompress.json",uncompressedSize:89469},{file:"extraction_worker_0.1.0-alpha.36_js.json",uncompressedSize:59626},{file:"facetracker_worker_0.1.0-alpha.36_js.json",uncompressedSize:306555},{file:"extraction_wasm_0.1.0-alpha.36.json",uncompressedSize:1926128},{file:"detectorModel_json.json",uncompressedSize:4640},{file:"detectorModel_bin.json",uncompressedSize:242046},{file:"landmarkModel_json.json",uncompressedSize:5036},{file:"landmarkModel_bin.json",uncompressedSize:1704814}]),b(this,v,new nt),b(this,N,Yt.init()),b(this,ve),b(this,Ae),b(this,ye),b(this,Oe),b(this,de),b(this,z),b(this,Ne),b(this,he,{version:"",sdkId:""}),b(this,me,""),b(this,_),b(this,q,0),b(this,L),b(this,ue,K.ASSETS_NOT_DOWNLOADED),b(this,F,""),b(this,Le,""),b(this,Z,!1),b(this,Q,5),b(this,ee,30),b(this,te,5),b(this,fe,!1),b(this,pe,4),b(this,j),b(this,Ee),b(this,De),b(this,ie,1e7),b(this,Ie,0),b(this,se,new Map),b(this,Te,Promise.resolve()),b(this,A,0),b(this,Se,-1),b(this,$,-1),b(this,be,.5),ut(this,"on",{beforeRESTCall:null,afterRESTCall:null,bytesDownloaded:null,faceTrackerStateChanged:null,resultsReceived:null,constraintsUpdated:null,mediaElementResize:null,facialLandmarksUpdated:null,chunkSent:null,error:null}),e!==At)throw new Error("Use await Measurement.init() to create an instance of Measurement class.")}static async init(e){if(!e)throw new Error("Missing `settings` object");const i=new Ot(At);if(!i.setSettings(e))throw new Error("Invalid settings object");f(i,x,Bt({url:{http:new URL("https://api.deepaffex.ai")},onBeforeRESTCall:()=>{var n,a;l(n=i,o,St).call(n),l(a=i,o,bt).call(a)},onAfterRESTCall:(n,a)=>{var m,h;l(m=i,o,_t).call(m,n,a),l(h=i,o,gt).call(h,n,a)}}));const c=n=>{var a;const{bytes:m,url:h,uncompressedSize:E,done:S}=n.detail;l(a=i,o,p).call(a,`bytesDownloaded event, ${m}, ${E}, ${h}, ${S}`,u.mediaPipe),i.on.bytesDownloaded&&i.on.bytesDownloaded(m,E,h,S)},d=n=>{var a;const{error:m,url:h}=n.detail;l(a=i,o,p).call(a,`downloadError event, ${h}, ${m}`,u.mediaPipe),i.on.error&&i.on.error(Re.ASSET_DOWNLOAD,{url:h,error:m})};return s(i,N).addEventListener("downloadedError",d),s(i,N).addEventListener("bytesDownloaded",c),s(i,v).setVersion(i.getVersion()),s(i,g).logger&&Object.values(s(i,g).logger).some(n=>n===!0)&&s(i,v).start(),setTimeout(()=>{var n;l(n=i,o,ae).call(n,K.ASSETS_NOT_DOWNLOADED)},500),new Proxy(i,{get(n,a,m){const h=a;return typeof n[h]=="function"?n[h].bind(n):Reflect.get(n,h,m)},set(n,a,m){return console.log(`Setting property "${String(a)}" to "${m}" is not allowed`),!0}})}loadMask(e){if(s(this,_)){let i=!1;const r=s(this,_).mediaElement.querySelector("svg");r&&(i=!0,s(this,_).mediaElement.removeChild(r)),s(this,_).mediaElement.appendChild(e),i&&(s(this,_).mediaElement.style.setProperty("border","1px solid transparent"),setTimeout(()=>{s(this,_).mediaElement.removeAttribute("style")},100))}}setSettings(e){const i=ai(s(this,g),e);return i.results==="valid"?(f(this,g,i.settings),!0):!1}getVersion(){return{webSDK:Je,extractionLib:s(this,he),faceTracker:s(this,me)}}async downloadAssets(){const{assetFolder:e}=s(this,g);try{if(l(this,o,p).call(this,`Asset base URL ${e}`,u.sdk),l(this,o,p).call(this,"Start downloading decompressor...",u.sdk),await s(this,N).fetchAsset(s(this,M),`${e}/`,"decompress.json",!0,"gzip"),s(this,N).canDecompress){await l(this,o,pt).call(this,e),s(this,z)&&await l(this,o,Ke).call(this),l(this,o,p).call(this,"Start downloading TFJS worker...",u.mediaPipe);const i=await s(this,N).fetchAsset(s(this,M),`${e}/`,`facetracker_worker_${this.getVersion().webSDK}_js.json`,!0,"brotli");return i&&(f(this,Ne,i),await l(this,o,ft).call(this,e),await l(this,o,Ve).call(this)),l(this,o,Et).call(this),!0}}catch{return l(this,o,p).call(this,"Failed to download TFJS face tracker or DFX extraction worker WASM assets",u.mediaPipe),!1}}setExtractionLibSettings(e=6,i=30,r=5){f(this,Q,e-1),f(this,ee,i),f(this,te,r)}async setNextChunkAsFinal(){f(this,fe,!0),await l(this,o,C).call(this,T.SHOULD_END_MEASUREMENT_EARLY,{},!0),l(this,o,p).call(this,"Set the action for the next chunk to LAST::PROCESS",u.extractionLibWasm)}async startTracking(){s(this,_)&&(s(this,_).isExtracting||(s(this,_).setIsExtracting(!0),l(this,o,p).call(this,"Start tracking frames",u.mediaPipe),await l(this,o,C).call(this,T.SET_NUMBER_OF_CHUNKS,{value:s(this,ie)},!0),await l(this,o,xe).call(this)))}async stopTracking(){if(s(this,_)){s(this,_).stopTracking(),await l(this,o,wt).call(this),s(this,_).setIsExtracting(!1),l(this,o,p).call(this,"Stop extracting frames",u.mediaPipe);const{numOfFramesPresented:e,warmupFrameNumber:i,numOftrackedVideoFrames:r}=s(this,_);l(this,o,p).call(this,"Tracking metrics",u.sdk,{numOfFramesPresented:e,warmupFrameNumber:i,numOftrackedVideoFrames:r}),f(this,F,"")}}async disconnect(){s(this,Z)&&await l(this,o,C).call(this,y.DISCONNECT,{},!0),s(this,g).metrics&&(await l(this,o,C).call(this,T.GET_LOGS,{},!0),s(this,v).retrieveLogs())}async destroy(){s(this,L)&&(s(this,L).destroy(),l(this,o,p).call(this,"Destroyed",u.extractionLibWasm)),s(this,_)&&(s(this,_).destroyWorkers(),l(this,o,p).call(this,"Destroyed",u.mediaPipe))}async reset(){return s(this,ue)===K.READY?(await this.stopTracking(),await this.destroy(),f(this,v,new nt),f(this,he,{version:"",sdkId:""}),f(this,me,""),f(this,q,0),f(this,F,""),f(this,Z,!1),f(this,Q,5),f(this,ee,30),f(this,te,5),f(this,fe,!1),f(this,j,void 0),f(this,ie,1e7),f(this,Ie,0),f(this,se,new Map),f(this,Te,Promise.resolve()),f(this,A,0),f(this,Se,-1),f(this,$,-1),s(this,g).mediaElement.innerHTML="",await l(this,o,Ke).call(this),await l(this,o,Ve).call(this),!0):!1}async setMediaStream(e){if(s(this,_)&&!s(this,_).isExtracting&&s(this,L)){await s(this,_).setMediaStream(e);const i=Object.fromEntries(s(this,_).workers.map((r,c)=>[`port${c+1}`,r.channel.port1]));s(this,L).worker.postMessage({action:T.SET_PORTS,payload:{numOfWorkers:s(this,pe),workerPorts:i}},[...s(this,_).workers.map(r=>r.channel.port1)])}}async prepare(e,i,r,c){s(this,x).setSession({userToken:e,userRefreshToken:i});const{region:d,status:n}=await l(this,o,Ct).call(this,"user");let a=`api.${d}.deepaffex.ai`;s(this,g).apiUrl?a=s(this,g).apiUrl:s(this,g).apiUrl=a,s(this,x).setUrl(`https://${a}`);const m=await l(this,o,Rt).call(this,e,i,"user"),h=await l(this,o,kt).call(this,r,c);return m&&h&&n==="200"}async setConstraintsConfig(e){await l(this,o,C).call(this,T.SET_CONSTRAINTS_CONFIG,{...s(this,De),...e&&{...s(this,g).constraintOverrides}},!0)}async startMeasurement(e=!1,i={}){if(f(this,fe,!1),f(this,F,""),await l(this,o,vt).call(this,i),s(this,L)&&s(this,F)!==""){await l(this,o,je).call(this),await l(this,o,C).call(this,T.SET_NUMBER_OF_CHUNKS,{value:s(this,Q)+1},!0),await this.setConstraintsConfig(e),await l(this,o,Tt).call(this),await l(this,o,xe).call(this);const{userToken:r}=s(this,x).getSession();r?await l(this,o,C).call(this,y.CONNECT,{token:r,measurementId:s(this,F)},!0):l(this,o,p).call(this,"User token is missing. Unable to connect.",u.webSocket)}}setDemographics(e){ri(e)?(f(this,j,e),l(this,o,p).call(this,`Demographics updated ${JSON.stringify(e)}`,u.extractionLibWasm)):l(this,o,p).call(this,`Error updating Demographics ${JSON.stringify(e)}`,u.extractionLibWasm)}setObjectFit(e){return s(this,_)&&ke!==void 0&&Object.values(ke).includes(e)?(s(this,_).settings.objectFit=e,!0):!1}};x=new WeakMap,g=new WeakMap,M=new WeakMap,v=new WeakMap,N=new WeakMap,ve=new WeakMap,Ae=new WeakMap,ye=new WeakMap,Oe=new WeakMap,de=new WeakMap,z=new WeakMap,Ne=new WeakMap,he=new WeakMap,me=new WeakMap,_=new WeakMap,q=new WeakMap,L=new WeakMap,ue=new WeakMap,F=new WeakMap,Le=new WeakMap,Z=new WeakMap,Q=new WeakMap,ee=new WeakMap,te=new WeakMap,fe=new WeakMap,pe=new WeakMap,j=new WeakMap,Ee=new WeakMap,De=new WeakMap,ie=new WeakMap,Ie=new WeakMap,se=new WeakMap,Te=new WeakMap,A=new WeakMap,Se=new WeakMap,$=new WeakMap,be=new WeakMap,o=new WeakSet,ft=async function(t){l(this,o,p).call(this,"Start downloading TFJS face tracker assets...",u.mediaPipe);const e=`${t}/models/`,[i,r,c,d]=await Promise.all([s(this,N).fetchAsset(s(this,M),e,"detectorModel_json.json",!0,"brotli"),s(this,N).fetchAsset(s(this,M),e,"detectorModel_bin.json",!0,"brotli"),s(this,N).fetchAsset(s(this,M),e,"landmarkModel_json.json",!0,"brotli"),s(this,N).fetchAsset(s(this,M),e,"landmarkModel_bin.json",!0,"brotli")]);l(this,o,p).call(this,"TFJS face tracker assets successfully downloaded",u.mediaPipe),f(this,ve,i),f(this,Ae,r),f(this,ye,c),f(this,Oe,d)},pt=async function(t){l(this,o,p).call(this,"Start downloading DFX extraction worker assets...",u.extractionLibWasm);const[e,i]=await Promise.all([s(this,N).fetchAsset(s(this,M),`${t}/extraction/`,`extraction_wasm_${this.getVersion().webSDK}.json`,!0,"brotli"),s(this,N).fetchAsset(s(this,M),`${t}/`,`extraction_worker_${this.getVersion().webSDK}_js.json`,!0,"brotli")]);l(this,o,p).call(this,"DFX extraction worker assets successfully downloaded",u.extractionLibWasm),f(this,de,e),f(this,z,i)},Et=function(){if(s(this,_)){const t=e=>{this.on.mediaElementResize&&this.on.mediaElementResize(e)};s(this,g).mediaElement.addEventListener("mediaElementSizeChanged",t)}},Ve=async function(){s(this,g),l(this,o,ae).call(this,K.NOT_LOADED);const t={faceTrackerCode:s(this,Ne),numOfWorkers:s(this,pe),mediaElement:s(this,g).mediaElement,mirrorVideo:s(this,g).mirrorVideo,metrics:s(this,g).metrics,displayMediaStream:s(this,g).displayMediaStream,isLoggingFaceTrackerWorkers:s(this,g).logger?.faceTrackerWorkers??!1,isLoggingSdk:s(this,g).logger?.sdk??!1,scaleFactor:s(this,be),models:{detectorJson:s(this,ve),detectorBin:s(this,Ae),landmarkJson:s(this,ye),landmarkBin:s(this,Oe)}};l(this,o,ae).call(this,K.LOADING),f(this,_,await Ei.init(t,s(this,v))),s(this,_).on.faceTrackersReady=(e,i,r,c)=>{l(this,o,p).call(this,`TFJS face tracker version ${i} loaded. Worker name: ${e} - workerId: ${r} - backend: ${c}`,u.mediaPipe),f(this,me,`${i}-${c}`),f(this,q,s(this,q)+1),s(this,v).setVersion(this.getVersion()),s(this,q)===s(this,pe)&&l(this,o,ae).call(this,K.LOADED)},s(this,_).on.frameAvailable=(e,i,r,c,d)=>{!c&&d?s(this,L).worker.postMessage({action:T.NEW_FRAME,payload:{frameNumber:i,frameTimestamp:e,frame:d,lastFrameNumber:r,tracked:c}},[d]):s(this,L).worker.postMessage({action:T.TRACKING_STATUS,payload:{frameNumber:i,frameTimestamp:e,lastFrameNumber:r,tracked:c}})},s(this,_).on.landmarksAvailable=(e,i,r)=>{const c=r/1e3;s(this,$)===0&&f(this,$,c),f(this,Se,c),s(this,_).numOftrackedVideoFrames+=1;const{starRating:d}=s(this,_),n=30,a=Math.min(s(this,Se)-s(this,$),n),m=s(this,$)>0?a/n*100:0,h={video:s(this,_).videoFpsTracker.fps.toFixed(1),faceTracker:s(this,_).faceTrackerFpsTracker.fps.toFixed(1)},E={face:e,annotations:i,starRating:d,percentCompleted:m,fps:h};this.on.facialLandmarksUpdated&&this.on.facialLandmarksUpdated(E)},s(this,_).on.scaleFactorChanged=e=>{f(this,be,e),s(this,_).scaleFactor=e,s(this,L).worker.postMessage({action:T.SCALE_FACTOR_CHANGED,payload:{scaleFactor:e}})}},Ke=async function(){const t=new TextDecoder().decode(new Uint8Array(s(this,z)));f(this,L,Fe.init(t,"module","EXTRACTION_WORKER"));const{studyCfgData:e}=s(this,x).getSession();e&&s(this,de)&&s(this,z)&&(s(this,L).worker.onmessage=async i=>{const{data:r}=i,{id:c,result:d}=r,{action:n,payload:a}=d,m=s(this,se).get(c);if(m||c===-1){switch(n){case T.READY:{const{sdkId:h,version:E,workerName:S}=a;f(this,he,{version:E,sdkId:h}),l(this,o,p).call(this,`DFX extraction worker WASM loaded. SDK ID: ${h} - Version: ${E} - Worker Name: ${S}`,u.extractionLibWasm),await l(this,o,C).call(this,T.SET_MODE,{value:"discrete"},!0),await l(this,o,C).call(this,T.SET_NUMBER_OF_CHUNKS,{value:s(this,ie)},!0),await l(this,o,C).call(this,T.SET_TARGET_FPS,{value:s(this,ee)},!0),await l(this,o,C).call(this,T.SET_CHUNK_DURATION_SECONDS,{value:s(this,te)},!0),await l(this,o,C).call(this,T.SET_FRAME_ORDER,{value:ot.RGBA},!0),await l(this,o,C).call(this,T.GET_CONSTRAINTS_CONFIG,{},!0),f(this,De,s(this,Ee));break}case T.SET_MODE:{a&&l(this,o,p).call(this,`Set mode to ${a.mode}`,u.extractionLibWasm);break}case T.SET_NUMBER_OF_CHUNKS:{a&&l(this,o,p).call(this,`Set number of chunks to ${d.number}`,u.extractionLibWasm);break}case T.SET_TARGET_FPS:{a&&l(this,o,p).call(this,`Set target FPS to ${s(this,ee)}`,u.extractionLibWasm);break}case T.SET_CHUNK_DURATION_SECONDS:{a&&l(this,o,p).call(this,`Set chunk duration to ${s(this,te)} Seconds`,u.extractionLibWasm);break}case T.SET_FRAME_ORDER:{a&&l(this,o,p).call(this,"Set channel order RGBA",u.extractionLibWasm);break}case T.GET_CONSTRAINTS_CONFIG:{a&&(f(this,Ee,a),l(this,o,p).call(this,`Get constraints ${JSON.stringify(a)}`,u.extractionLibWasm));break}case T.SET_CONSTRAINTS_CONFIG:{a&&(f(this,Ee,a),l(this,o,p).call(this,`Set constraints ${JSON.stringify(a)}`,u.extractionLibWasm));break}case T.SET_FACE_ATTRIBUTE:{const{success:h,faceId:E,attribute:S,value:R}=a;h&&l(this,o,p).call(this,`Set face attribute: faceId: ${E}, attribute: ${S}, value: ${R}`,u.extractionLibWasm);break}case T.RESET_COLLECTION:{a&&l(this,o,p).call(this,"Reset collection",u.extractionLibWasm);break}case T.CANCEL_COLLECTION:{a&&l(this,o,p).call(this,"Collecttion cancelled",u.extractionLibWasm);break}case T.START_COLLECTION:{a&&l(this,o,p).call(this,`Collector started - state: ${a}`,u.extractionLibWasm);break}case T.SET_PORTS:{a&&l(this,o,p).call(this,"Ports set",u.extractionLibWasm);break}case T.COLLECTOR_ERROR:{if(a){const{error:h,frameNumber:E}=a;l(this,o,p).call(this,`Collector error on frame ${E}: ${h}`,u.extractionLibWasm),this.on.error&&this.on.error(Re.COLLECTOR,a),await this.stopTracking()}break}case T.STAR_RATING:{s(this,_).starRating=a.rating;break}case T.ALL_FACE_TRACKERS_WARMED_UP:{const{frameNumber:h}=d;s(this,_).warmupFrameNumber=h,l(this,o,p).call(this,"All face tracker workers are warmed up.",u.mediaPipe),l(this,o,ae).call(this,K.READY);break}case T.CONSTRAINTS_UPDATED:{const{feedback:h,status:E}=a;this.on.constraintsUpdated&&this.on.constraintsUpdated(h,E);break}case T.SHOULD_END_MEASUREMENT_EARLY:{const{currentFinalChunkNumber:h,currentResultsOrder:E,newFinalChunkNumber:S}=d;l(this,o,p).call(this,`Request the end measurement early. Current final chunk number: ${h}, Current results order: ${E}, New final chunk number: ${S}`,u.extractionLibWasm);break}case T.GET_LOGS:{console.log(`DFX Log: ${a}`);break}case y.CONNECT:{f(this,Z,!0),f(this,$,0),l(this,o,p).call(this,a?"Connected":"Connection error",u.webSocket);break}case y.LOGIN_WITH_TOKEN_SUCCESS:{l(this,o,p).call(this,"Successfully logged in with token",u.webSocket);break}case y.SUBSCRIBED_TO_RESULTS:{l(this,o,p).call(this,"Subscribed to the results",u.webSocket);break}case y.CHUNK_SENT:{l(this,o,p).call(this,`Chunk sent ${JSON.stringify(a)}`,u.webSocket),this.on.chunkSent&&this.on.chunkSent(a);break}case y.DISCONNECT:{f(this,Z,!1),l(this,o,p).call(this,"Disconnect",u.webSocket);break}case y.DISCONNECTED:{l(this,o,p).call(this,`Disconnected! - code: ${a.code}, reason: ${a.reason}, wasClean: ${a.wasClean}`,u.webSocket),this.on.error&&this.on.error(Re.WEB_SOCKET,a);break}case y.CHUNK_ACKNOWLEDGED:{l(this,o,p).call(this,`Chunk number ${a.chunkOrder} received by the server!`,u.webSocket),s(this,Q)===a.chunkOrder&&await this.stopTracking();break}case y.RESULTS_RECEIVED:{const{resultsOrder:h,finalChunkNumber:E}=a;this.on.resultsReceived&&this.on.resultsReceived(a),l(this,o,p).call(this,`Results received: ${JSON.stringify(a)}`,u.webSocket),h===E&&(await l(this,o,C).call(this,y.DISCONNECT,{},!0),await l(this,o,je).call(this),await l(this,o,xe).call(this));break}case y.NETWORK_DELAY:{const{delay:h,description:E,actionId:S}=a;l(this,o,p).call(this,`Round-trip delay for ${E} call with Action ID ${S} was ${h.toFixed(2)} ms`,u.webSocket,{delay:h,actionId:S,description:E});break}case y.ERROR:{l(this,o,p).call(this,"Error",u.webSocket),this.on.error&&this.on.error(Re.WEB_SOCKET,a);break}}m&&(m.resolve(d),s(this,se).delete(c))}},await l(this,o,C).call(this,T.INIT,{wasm:s(this,de),studyConfigData:e,isLogging:s(this,g).logger?.extractionWorker||!1,metrics:s(this,g).metrics||!1,apiUrl:s(this,g).apiUrl,scaleFactor:s(this,be)},!0))},Tt=async function(){if(s(this,_)&&s(this,j)){const{age:e,height:i,weight:r,sex:c,smoking:d,bloodPressureMedication:n,diabetes:a}=s(this,j);await l(this,o,C).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:V.SEX_ASSIGNED_AT_BIRTH,value:c},!0),await l(this,o,C).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:V.AGE_YEARS,value:e},!0),await l(this,o,C).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:V.HEIGHT_CM,value:i},!0),await l(this,o,C).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:V.WEIGHT_KG,value:r},!0),await l(this,o,C).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:V.SMOKER,value:d},!0),await l(this,o,C).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:V.BLOOD_PRESSURE_MEDICATION,value:n},!0),await l(this,o,C).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:V.DIABETES,value:a},!0),l(this,o,p).call(this,`Set demographics for Face ID 1, ${JSON.stringify(s(this,j))}`,u.extractionLibWasm)}},St=function(){},bt=function(){const t=new Date().toISOString();st(t)&&(l(this,o,p).call(this,`Action ID: ${s(this,A)}`,u.beforeRESTCall),this.on.beforeRESTCall&&this.on.beforeRESTCall(t,s(this,A)))},_t=function(t,e){},gt=function(t,e){const i=new Date().toISOString();st(i)&&(l(this,o,p).call(this,`Action ID: ${s(this,A)}, HTTP status code: ${t}, error: ${JSON.stringify(e)}`,u.afterRESTCall),this.on.afterRESTCall&&this.on.afterRESTCall(i,s(this,A),t,e))},wt=async function(){await l(this,o,C).call(this,T.CANCEL_COLLECTION,{},!0)},xe=async function(){await l(this,o,C).call(this,T.START_COLLECTION,{},!0)},je=async function(){await l(this,o,C).call(this,T.RESET_COLLECTION,{},!0),await l(this,o,C).call(this,T.SET_NUMBER_OF_CHUNKS,{value:s(this,ie)},!0)},p=function(t,e,i){s(this,g).metrics&&s(this,v).log(t,e,"",!0,i),s(this,g).logger?.mediaPipe&&e===u.mediaPipe&&s(this,v).info(t,e),s(this,g).logger?.beforeRESTCall&&e===u.beforeRESTCall&&s(this,v).info(t,e),s(this,g).logger?.afterRESTCall&&e===u.afterRESTCall&&s(this,v).info(t,e),s(this,g).logger?.extractionLibWasm&&e===u.extractionLibWasm&&s(this,v).info(t,e),s(this,g).logger?.apiClient&&e===u.apiClient&&s(this,v).info(t,e),s(this,g).logger?.webSocket&&e===u.webSocket&&s(this,v).info(t,e),s(this,g).logger?.sdk&&e===u.sdk&&s(this,v).info(t,e)},Ct=async function(t){f(this,A,0);const e=performance.now(),i=await s(this,x).http.auths.validate(t),r=performance.now()-e,{status:c,body:d}=i;if(l(this,o,p).call(this,c==="200"?"Successfully validated the Token":`Failed to validate token. Status: ${c}`,u.apiClient,{delay:r,actionId:s(this,A),description:"Validate Token"}),c==="200"){const{Region:n}=d;return{region:n,status:c}}else return{status:c,region:""}},Rt=async function(t,e,i){f(this,A,2304);const r=performance.now(),c=await s(this,x).http.auths.renew({Token:t,RefreshToken:e},i),d=performance.now()-r,{status:n}=c;return l(this,o,p).call(this,n==="200"?"Successfully refreshed the Token":`Failed to refresh token. Status: ${n}`,u.apiClient,{delay:d,actionId:s(this,A),description:"Refresh Token"}),n==="200"},kt=async function(t,e){f(this,A,806);const i=performance.now();f(this,Le,t);const r=await s(this,x).http.studies.retrieveSdkConfigData({StudyID:t,...e&&{sdkId:e}},"user"),c=performance.now()-i,{status:d}=r;return l(this,o,p).call(this,d==="200"?"Retrieve SDK Config Data - success":"Retrieve SDK Config Data - failure",u.apiClient,{delay:c,actionId:s(this,A),description:"Retrieve SDK Config Data"}),d==="200"},vt=async function(t){l(this,o,p).call(this,"Get Measurement ID",u.apiClient),f(this,A,504);const e=performance.now(),i={StudyID:s(this,Le),Resolution:100};t.partnerId&&(i.PartnerID=t.partnerId),t.userProfileId&&(i.UserProfileID=t.userProfileId);const r=await s(this,x).http.measurements.create(i,"user"),c=performance.now()-e,{status:d,body:n}=r;let a="";d==="200"?(f(this,F,n.ID),a=`Successfully obtained measurement ID: ${s(this,F)}`):(f(this,F,""),a=`Failed to obtain measurement ID. Status: ${d}`),l(this,o,p).call(this,a,u.apiClient,{delay:c,actionId:s(this,A),measurementId:s(this,F),description:"Get Measurement ID"})},ae=function(t){f(this,ue,t),l(this,o,p).call(this,`Face tracker state changed: ${t}`,u.mediaPipe),this.on.faceTrackerStateChanged&&this.on.faceTrackerStateChanged(s(this,ue))},C=function(t,e,i=!1){return new Promise(r=>{const c=bi(this,Ie)._++;s(this,se).set(c,{resolve:r,action:t});const d=()=>s(this,L).worker.postMessage({id:c,action:t,payload:e});i?f(this,Te,s(this,Te).then(d).catch(n=>console.error(n))):d()})},ut(_i,"VERSION",Je);const gi=document.documentElement.style.overflow;class wi{#e=document.createElement("div");#t=document.createElement("div");on={results:null,error:null,event:null};constructor(){this.#e.style.height="100%"}init(e){const{container:i,appPath:r,settings:c,profile:d,config:n,loadError:a,top:m=0,language:h,apiUrl:E}=e;this.#t=i,Object.assign(i.style,{position:"fixed",top:m,left:"0",width:"100vw",height:`calc(100vh - ${m})`}),document.body.appendChild(i);const S=i.attachShadow({mode:"open"});document.documentElement.style.overflow="hidden";const R="app",k=document.createElement("link");k.rel="stylesheet",k.href=`${r}/stylex.css`,S.appendChild(k);const O=document.createElement("link");O.rel="stylesheet",O.href=`${r}/${R}.css`,S.appendChild(O);const P=G=>{this.on.results&&this.on.results({...G.detail})},B=G=>{this.on.error&&this.on.error({...G.detail})},re=G=>{this.on.event&&this.on.event({...G.detail})};this.#e.addEventListener(U.RESULTS,P),this.#e.addEventListener(U.ERROR,B),this.#e.addEventListener(U.APPEVENT,re),S.appendChild(this.#e);const Y=document.createElement("script");Y.type="module",Y.src=`${r}/${R}.mjs`,Y.onload=()=>{import(Y.src).then(G=>{G.app.init(this.#e,r,c,d,E,n,h)}).catch(()=>{a&&a("Failed to initialize Measurement Embedded React app")})},Y.onerror=()=>{a&&a("Failed to load the measurement embedded app script")},S.appendChild(Y)}destroy(){const e=new CustomEvent("measurement-embedded-app-action",{detail:{action:ne.DESTROY,data:{}}});this.#e.dispatchEvent(e),document.documentElement.style.overflow=gi,this.#t&&document.body.contains(this.#t)&&document.body.removeChild(this.#t)}setTheme(e){const i=new CustomEvent("measurement-embedded-app-action",{detail:{action:ne.SET_THEME,data:{theme:e}}});this.#e.dispatchEvent(i)}setLanguage(e){const i=new CustomEvent("measurement-embedded-app-action",{detail:{action:ne.SET_LANGUAGE,data:{language:e}}});this.#e.dispatchEvent(i)}async cancel(e){return new Promise(i=>{const r=d=>{this.#e.removeEventListener(U.CANCELLED,r),i(d.detail.reset)};this.#e.addEventListener(U.CANCELLED,r);const c=new CustomEvent("measurement-embedded-app-action",{detail:{action:ne.CANCEL,data:{reset:e}}});this.#e.dispatchEvent(c)})}getLogs(){return new Promise(e=>{const i=c=>{this.#e.removeEventListener(U.LOGS,i),e(c.detail.logs)};this.#e.addEventListener(U.LOGS,i);const r=new CustomEvent("measurement-embedded-app-action",{detail:{action:ne.GET_LOGS,data:{}}});this.#e.dispatchEvent(r)})}}export{Ye as ErrorCodes,Lt as appEvents,wi as default,di as faceAttributeValue,U as measurementEmbeddedAppEvents};
739
+ `}openLogInNewWindow(){const e=this.generateHTMLTable(),i=new Blob([e],{type:"text/html"}),r=URL.createObjectURL(i);window.open(r,"_blank")}}var qt=Object.defineProperty,Zt=(t,e,i)=>e in t?qt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,we=(t,e,i)=>Zt(t,typeof e!="symbol"?e+"":e,i);class xe{constructor(e,i){we(this,"workerUrl"),we(this,"worker"),this.worker=e,this.workerUrl=i}static init(e,i,r){const c=new Blob([e],{type:"application/javascript"}),d=URL.createObjectURL(c),n=r||`WORKER${String(new Date().getTime())}`,a=new Worker(new URL(d,import.meta.url),{name:n,type:i});return new xe(a,d)}destroy(){this.worker&&(this.worker.terminate(),URL.revokeObjectURL(this.worker))}}const Qt=(t,e,i,r)=>{const c=t/e,d=i/r;let n=0,a=0;c>d?(n=t,a=t/d):(a=e,n=e*d);const u=(t-n)/2,h=(e-a)/2;return{width:n||0,height:a||0,offsetX:u||0,offsetY:h||0}},ei=(t,e,i,r)=>{const c=(t-i)/2,d=(e-r)/2;return{width:i||0,height:r||0,offsetX:c||0,offsetY:d||0}},ti=(t,e,i,r)=>{const c=t/e,d=i/r;let n=0,a=0;c>d?(a=e,n=e*d):(n=t,a=t/d);const u=(t-n)/2,h=(e-a)/2;return{width:n||0,height:a||0,offsetX:u||0,offsetY:h||0}},ii=(t,e)=>{switch(t){case"none":return ei(...e);case"cover":return Qt(...e);case"contain":default:return ti(...e)}},st=t=>/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(t),si=t=>t===void 0?!0:!(typeof t.mediaPipe<"u"&&typeof t.mediaPipe!="boolean"||typeof t.beforeRESTCall<"u"&&typeof t.beforeRESTCall!="boolean"||typeof t.afterRESTCall<"u"&&typeof t.afterRESTCall!="boolean"||typeof t.extractionLibWasm<"u"&&typeof t.extractionLibWasm!="boolean"||typeof t.apiClient<"u"&&typeof t.apiClient!="boolean"||typeof t.extractionWorker<"u"&&typeof t.extractionWorker!="boolean"||typeof t.faceTrackerWorkers<"u"&&typeof t.faceTrackerWorkers!="boolean"||typeof t.sdk<"u"&&typeof t.sdk!="boolean"),ai=(t,e)=>{const i={...t};if(e.logger)if(si(e.logger))i.logger={...i.logger,...e.logger};else return{results:"invalid"};if(e.apiUrl!==void 0)if(typeof e.apiUrl=="string")i.apiUrl=e.apiUrl;else return{results:"invalid"};if(e.metrics!==void 0)if(typeof e.metrics=="boolean")i.metrics=e.metrics;else return{results:"invalid"};if(e.mirrorVideo!==void 0)if(typeof e.mirrorVideo=="boolean")i.mirrorVideo=e.mirrorVideo;else return{results:"invalid"};if(e.displayMediaStream!==void 0)if(typeof e.displayMediaStream=="boolean")i.displayMediaStream=e.displayMediaStream;else return{results:"invalid"};if(e.assetFolder!==void 0)if(typeof e.assetFolder=="string")i.assetFolder=e.assetFolder;else return{results:"invalid"};if(e.mediaElement!==void 0)if(e.mediaElement instanceof HTMLDivElement)i.mediaElement=e.mediaElement;else return{results:"invalid"};if(e.constraintOverrides!==void 0){let r=function(n,a){if(!(n in d))return!1;const u=d[n];return typeof a===u};const d=Object.fromEntries(Object.entries({backLightMaxPixels_pct:30,backLightSearchMult:1.5,backLightThresh:240,boxCenterX_pct:50,boxCenterY_pct:50,boxHeight_pct:99,boxWidth_pct:50,cameraRot_chunkThresh:.7853981633974483,cameraRot_windowThresh:.2617993877991494,checkBackLight:!1,checkCameraMovement:!1,checkCentered:!1,checkDistance:!1,checkEyebrowMovement:!1,checkFaceDirection:!1,checkLighting:!1,checkMaxDistance:!1,checkMinFps:!1,checkMovement:!1,chunkMovementThresh_pct:60,enableDebugLog:!1,enableFigures:!1,faceRotLR_thresh:.33,faceRotUD_lowerthresh:.25,faceRotUD_upperThresh:5,hy_faceRotLR_thresh:.05,hy_maxFaceRotLR_deg:2,hy_maxFaceRotUD_deg:2,hy_minInterPupilDist_px:5,hy_minimumFps:1,maxEyebrowMovement_mm:3,maxFaceRotLR_deg:12.5,maxFaceRotUD_deg:25,maxMovement_mm:10,minInterPupilDist_px:100,minimumFps:26,movementWindow_ms:2e3,threshBright:225,threshDark:48}).map(([n,a])=>[n,typeof a]));for(const n in e.constraintOverrides){const a=e.constraintOverrides[n];if(!r(n,a))return{results:"invalid"}}i.constraintOverrides=e.constraintOverrides}return{results:"valid",settings:i}},ri=t=>typeof t.age!="number"||t.age<13||t.age>120?(console.error("Invalid age. It should be a number between 13 and 120."),!1):typeof t.height!="number"||t.height<120||t.height>220?(console.error("Invalid height. It should be a number between 120 and 220."),!1):typeof t.weight!="number"||t.weight<30||t.weight>300?(console.error("Invalid weight. It should be a number between 30 and 300."),!1):typeof t.sex!="number"||t.sex<1||t.sex>3?(console.error("Invalid sex. It should be a number between 1 and 3."),!1):typeof t.diabetes!="number"||t.diabetes<4||t.diabetes>6?(console.error("Invalid diabetes. It should be a number between 4 and 6."),!1):typeof t.bloodPressureMedication!="number"||t.bloodPressureMedication!==0&&t.bloodPressureMedication!==1?(console.error("Invalid bloodPressureMedication. It should be either 0 or 1."),!1):typeof t.smoking!="number"||t.smoking!==0&&t.smoking!==1?(console.error("Invalid smoking. It should be either 0 or 1."),!1):!0;var m=(t=>(t.beforeRESTCall="Before REST call event",t.afterRESTCall="After REST call event",t.mediaPipe="MediaPipe",t.extractionLibWasm="DFX Extraction lib WASM",t.apiClient="DFX API client",t.webSocket="WebSocket",t.sdk="SDK",t.dfxWorker="DFX Worker",t))(m||{});const ni=t=>{switch(t){case"Before REST call event":return"red";case"After REST call event":return"orange";case"MediaPipe":return"green";case"DFX Extraction lib WASM":return"violet";case"DFX API client":return"#d34110";case"WebSocket":return"#d34110";case"SDK":return"#d34110";case"DFX Worker":return"#ad4393";default:return"black"}};class at{constructor(e=1e3){we(this,"timestamps",[]),we(this,"windowMs"),this.windowMs=e}tick(e=performance.now()){for(this.timestamps.push(e);this.timestamps.length>0&&e-this.timestamps[0]>this.windowMs;)this.timestamps.shift()}get fps(){const e=this.timestamps.length,i=this.timestamps.at(-1)-this.timestamps[0]||1;return e/i*1e3}get frameCount(){return this.timestamps.length}reset(){this.timestamps=[]}}var oi=Object.defineProperty,li=(t,e,i)=>e in t?oi(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,rt=(t,e,i)=>li(t,typeof e!="symbol"?e+"":e,i);const ci=()=>{const t=new Date,e=(t.getMonth()+1).toString().padStart(2,"0"),i=t.getDate().toString().padStart(2,"0"),r=t.getFullYear();let c=t.getHours();const d=t.getMinutes().toString().padStart(2,"0"),n=t.getSeconds().toString().padStart(2,"0"),a=t.getMilliseconds().toString().padStart(3,"0"),u=c>=12?"PM":"AM";return c=c%12||12,`[${e}/${i}/${r}, ${c}:${d}:${n}.${a} ${u}]`};class nt{constructor(){rt(this,"mertics",new zt),rt(this,"version",{webSDK:"",extractionLib:{version:"",sdkId:""},faceTracker:""})}retrieveLogs(){this.mertics.transferLogs(),this.mertics.openLogInNewWindow(),this.mertics.debugLogs=[]}setVersion(e){this.version=e,this.mertics.version=e}log(e,i,r,c=!1,d={}){const n=ci();if(c)this.mertics.appendLog({thread:"Main",timestamp:n,category:i,message:e,meta:d});else{const a=`[${i}]`,u=" ",h=e,E=`color:${r}; font-weight:800;`,_=`color:${ni(i)}; font-weight:700;`;console.log("%c%s%c%s%c%s%c%s",E,n,_,a,"background:inherit;",u,"font-style: italic;",h)}}info(e,i){this.log(e,i,"blue")}warn(e,i){this.log(e,i,"orange")}error(e,i){this.log(e,i,"red")}debug(e,i){this.log(e,i,"green")}start(){console.log("%c%s","color: #5e5e5e; background-color: #2d2d2d; letter-spacing: 0.1em; text-shadow: -1px -1px 1px #111, 2px 2px 1px #363636; font-size: 36px; padding: 20px 40px; text-align: center; text-transform: uppercase; text-rendering: optimizeLegibility;","Anura Web Core SDK"),console.log(`Version: ${this.version.webSDK}`),console.log("https://www.deepaffex.ai")}}const di={SEX_NOT_PROVIDED:1,SEX_ASSIGNED_MALE_AT_BIRTH:2,SEX_ASSIGNED_FEMALE_AT_BIRTH:3,DIABETES_NONE:4,DIABETES_TYPE1:5,DIABETES_TYPE2:6,SMOKER_TRUE:0,SMOKER_FALSE:1,BLOOD_PRESSURE_MEDICATION_TRUE:1,BLOOD_PRESSURE_MEDICATION_FALSE:0},K={SEX_ASSIGNED_AT_BIRTH:1,AGE_YEARS:2,HEIGHT_CM:3,WEIGHT_KG:4,SMOKER:5,BLOOD_PRESSURE_MEDICATION:7,DIABETES:8};var ot=(t=>(t[t.BGR=1]="BGR",t[t.RGB=2]="RGB",t[t.BGRA=3]="BGRA",t[t.RGBA=4]="RGBA",t[t.Infrared=5]="Infrared",t[t.Infrared888=6]="Infrared888",t[t.BGR_Infrared=7]="BGR_Infrared",t[t.RGB_Infrared=8]="RGB_Infrared",t[t.Gray=9]="Gray",t))(ot||{});const j={ASSETS_NOT_DOWNLOADED:"ASSETS_NOT_DOWNLOADED",NOT_LOADED:"NOT_LOADED",LOADING:"LOADING",LOADED:"LOADED",READY:"READY"},Re={COLLECTOR:"COLLECTOR",ASSET_DOWNLOAD:"ASSET_DOWNLOAD",WEB_SOCKET:"WEB_SOCKET"},Ce={CONTAIN:"contain",COVER:"cover",NONE:"none"};var $=(t=>(t.INIT="INIT",t.READY="READY",t.INIT_TFJS="INIT_TFJS",t.SET_PORT="SET_PORT",t.TRACK="TRACK",t.RESULTS_READY="RESULTS_READY",t.WARM_UP="WARM_UP",t.DESTROY="DESTROY",t.LANDMARKS="LANDMARKS",t.VIDEO_FRAME="VIDEO_FRAME",t.SCALE_FACTOR_CHANGED="SCALE_FACTOR_CHANGED",t))($||{}),hi=Object.defineProperty,lt=t=>{throw TypeError(t)},mi=(t,e,i)=>e in t?hi(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,w=(t,e,i)=>mi(t,typeof e!="symbol"?e+"":e,i),$e=(t,e,i)=>e.has(t)||lt("Cannot "+i),ct=(t,e,i)=>($e(t,e,"read from private field"),i?i.call(t):e.get(t)),dt=(t,e,i)=>e.has(t)?lt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),ui=(t,e,i,r)=>($e(t,e,"write to private field"),e.set(t,i),i),fi=(t,e,i)=>($e(t,e,"access private method"),i),le,Be,ht;const Ei=class yt{constructor(e,i,r){dt(this,Be),dt(this,le),w(this,"mediaElement"),w(this,"numOfFramesPresented",0),w(this,"workers",[]),w(this,"numOftrackedVideoFrames",0),w(this,"warmupFrameNumber",0),w(this,"videoCallbackId",0),w(this,"numOfWorkers",4),w(this,"isLoggingFaceTrackerWorkers",!1),w(this,"isLoggingSdk",!1),w(this,"workerIndex",0),w(this,"metrics",!1),w(this,"videoFpsTracker",new at(1e3)),w(this,"faceTrackerFpsTracker",new at(1e3)),w(this,"videoElementSize",{width:0,height:0,offsetX:0,offsetY:0}),w(this,"videoElement",document.createElement("video")),w(this,"frameWidth",0),w(this,"frameHeight",0),w(this,"mirrorVideo",!0),w(this,"settings",{faceTrackerWidth:0,faceTrackerHeight:0,displayMediaStream:!0,objectFit:Ce.COVER}),w(this,"isExtracting",!1),w(this,"starRating",0),w(this,"scaleFactor",1),w(this,"warmupIndex",0),w(this,"warmingUp",!0),w(this,"ftWorkerIndex",0),w(this,"lastFrameNumber",-1),w(this,"on",{faceTrackersReady:null,frameAvailable:null,landmarksAvailable:null,scaleFactorChanged:null});const{mediaElement:c,mirrorVideo:d,numOfWorkers:n,isLoggingFaceTrackerWorkers:a,isLoggingSdk:u,metrics:h,displayMediaStream:E}=i;this.numOfWorkers=n,this.isLoggingFaceTrackerWorkers=a,this.isLoggingSdk=u,this.metrics=h,ui(this,le,r),this.settings.displayMediaStream=E,this.mirrorVideo=d,this.mediaElement=c,this.videoFrameCallback=this.videoFrameCallback.bind(this),this.workers=e,this.scaleFactor=i.scaleFactor,this.initWorkerOnMessage(i.models),this.videoElement.muted=!0,this.videoElement.playsInline=!0,this.videoElement.preload="auto"}static async init(e,i){const{numOfWorkers:r,faceTrackerCode:c}=e,d=[],n=new TextDecoder().decode(new Uint8Array(c));if(r>0)for(let a=1;a<=r;a+=1){const u=xe.init(n,"module",`FACE_TRACKER_WORKER_${a-1}`);d.push({ft:u,channel:new MessageChannel,isBusy:!1})}return new yt(d,e,i)}initWorkerOnMessage(e){const i=window.matchMedia("(orientation: portrait)").matches,r=i?360:640,c=i?640:360;this.workers.forEach(d=>{d.ft.worker.postMessage({action:$.INIT_TFJS,payload:{width:r,height:c,models:e,scaleFactor:this.scaleFactor}}),d.ft.worker.postMessage({action:$.SET_PORT,payload:{port:d.channel.port2}},[d.channel.port2]),d.ft.worker.onmessage=n=>{const{action:a,payload:u}=n.data;switch(a){case $.INIT_TFJS:break;case $.READY:{const{workerName:h,version:E,workerId:_,backend:C}=u;this.on.faceTrackersReady&&this.on.faceTrackersReady(h,E,_,C);break}case $.LANDMARKS:{this.faceTrackerFpsTracker.tick(),d.isBusy=!1,this.warmingUp&&this.warmupIndex++;const{face:h,annotations:E,frameTimestamp:_}=u;this.on.landmarksAvailable&&this.on.landmarksAvailable(h,E,_);break}case $.DESTROY:{const{workerId:h}=u;this.workers[h].ft.destroy();break}}}})}getMediaElement(){return this.mediaElement}setIsExtracting(e){this.isExtracting=e}destroyWorkers(){setTimeout(async()=>{this.videoCallbackId&&this.videoElement.cancelVideoFrameCallback(this.videoCallbackId),this.workers.forEach(e=>e.ft.worker.postMessage({action:$.DESTROY}))},200)}createMediaElements(){this.videoElement.addEventListener("ended",async()=>{this.destroyWorkers()});const e=document.createElement("div"),i=this.settings.displayMediaStream?this.videoElement:e,r="white";this.mediaElement.appendChild(i),i.style.width="100%",i.style.height="100%",i.style.boxSizing="border-box",this.settings.displayMediaStream&&(i.style.border=`1px solid ${r}`),i.style.objectFit=this.settings.objectFit,i.style.transform=`scale(${this.mirrorVideo?"-1":"1"},1)`,this.settings.displayMediaStream||(i.style.height=`${this.frameHeight}px`,i.style.width=`${this.frameWidth}px`),new ResizeObserver(d=>{const{contentRect:n,target:a}=d[0],{width:u,height:h}=n,{x:E,y:_}=a.getBoundingClientRect(),{faceTrackerWidth:C,faceTrackerHeight:k}=this.settings;this.videoElementSize=ii(this.settings.objectFit,[u,h,this.frameWidth,this.frameHeight]);const{width:I,height:W}=this.videoElementSize;if(!this.settings.displayMediaStream){const G=this.settings.objectFit===Ce.NONE;i.style.height=`${Math.trunc(G?W:h)}px`,i.style.width=`${Math.trunc(G?I:u)}px`}this.mediaElement.dispatchEvent(new CustomEvent("mediaElementSizeChanged",{detail:{mediaElementSize:{width:u,height:h,x:E,y:_},videoElementSize:this.videoElementSize,frameInfo:{mediaStreamWidth:this.frameWidth,mediaStreamHeight:this.frameHeight,faceTrackerWidth:C,faceTrackerHeight:k},isPortrait:h>u,aspectRatio:u/h}}))}).observe(this.mediaElement)}log(e,i,r){this.isLoggingSdk&&ct(this,le).info(e,i),this.metrics&&ct(this,le).log(e,i,"",!0,r)}videoFrameCallback(e,i){const{presentedFrames:r,captureTime:c,expectedDisplayTime:d,mediaTime:n}=i;this.videoFpsTracker.tick();const a=c===void 0?d:c;this.numOfFramesPresented=r;const u=`Number of frames presented: ${this.numOfFramesPresented} - time: ${a}`;let h=0;if(n&&n>0?h=n*1e3:c&&c>0?h=c>1e6?c-performance.timeOrigin:c:h=e,this.log(u,m.sdk,{captureTime:a,presentedFrames:r}),this.warmingUp)if(this.warmupIndex>=this.numOfWorkers)this.warmingUp=!1;else{const E=this.workers[this.warmupIndex];if(!E.isBusy){E.isBusy=!0;const _=new VideoFrame(this.videoElement,{timestamp:h});E.ft.worker.postMessage({action:"TRACK",payload:{frame:_,frameTimestamp:h,frameNumber:this.numOfFramesPresented}},[_])}}if(!this.warmingUp){const E=new VideoFrame(this.videoElement,{timestamp:h});let _=!1;for(let C=0;C<this.numOfWorkers;C++){this.ftWorkerIndex=(this.ftWorkerIndex+1)%this.numOfWorkers;const k=this.workers[this.ftWorkerIndex];if(k&&!k.isBusy){k.isBusy=!0,this.on.frameAvailable(h,this.numOfFramesPresented,this.lastFrameNumber,!0),k.ft.worker.postMessage({action:"TRACK",payload:{frame:E,frameTimestamp:h,frameNumber:this.numOfFramesPresented}},[E]),_=!0;break}}_||this.on.frameAvailable(h,this.numOfFramesPresented,this.lastFrameNumber,!1,E)}this.lastFrameNumber=this.numOfFramesPresented,this.videoCallbackId=this.videoElement.requestVideoFrameCallback(this.videoFrameCallback)}setFaceTrackerMediaStreamResolution(e,i){(e<=360||i<=360)&&(this.scaleFactor=1),this.settings.faceTrackerWidth=e*this.scaleFactor,this.settings.faceTrackerHeight=i*this.scaleFactor,this.workers.forEach(r=>r.ft.worker.postMessage({action:$.SCALE_FACTOR_CHANGED,payload:{scaleFactor:this.scaleFactor}})),this.on.scaleFactorChanged&&this.on.scaleFactorChanged(this.scaleFactor)}async setMediaStream(e){if(e instanceof MediaStream)try{const{settings:i,constraints:r}=await fi(this,Be,ht).call(this,e,this.videoElement);await this.videoElement.play(),this.settings.displayMediaStream||(this.videoElement.style.visibility="none");const{width:c,height:d}=i;return this.setFaceTrackerMediaStreamResolution(c??0,d??0),this.frameWidth=c||1,this.frameHeight=d||1,this.log(`Face tracker resolution: ${c} x ${d} pixels. Video resolution: ${this.frameWidth} x ${this.frameHeight} pixels`,m.sdk,{ftWidth:c,ftHeight:d,frameWidth:this.frameWidth,frameHeight:this.frameHeight}),this.createMediaElements(),this.videoCallbackId=this.videoElement.requestVideoFrameCallback(this.videoFrameCallback),!0}catch(i){return console.log("Error applying face tracker video track constraints",i),!1}return!1}stopTracking(){this.videoCallbackId&&this.videoElement.cancelVideoFrameCallback(this.videoCallbackId),this.videoElement.pause(),this.videoElement.srcObject=null}};le=new WeakMap,Be=new WeakSet,ht=async function(t,e){e.srcObject=t,await new Promise(r=>e.onloadedmetadata=r);const[i]=t.getVideoTracks();return{constraints:i.getConstraints(),settings:i.getSettings()}};let pi=Ei;var T=(t=>(t.INIT="INIT",t.READY="READY",t.SET_MODE="SET_MODE",t.SET_NUMBER_OF_CHUNKS="SET_NUMBER_OF_CHUNKS",t.SET_TARGET_FPS="SET_TARGET_FPS",t.SET_CHUNK_DURATION_SECONDS="SET_CHUNK_DURATION_SECONDS",t.SET_FRAME_ORDER="SET_FRAME_ORDER",t.GET_CONSTRAINTS_CONFIG="GET_CONSTRAINTS_CONFIG",t.SET_CONSTRAINTS_CONFIG="SET_CONSTRAINTS_CONFIG",t.SET_FACE_ATTRIBUTE="SET_FACE_ATTRIBUTE",t.RESET_COLLECTION="RESET_COLLECTION",t.CANCEL_COLLECTION="CANCEL_COLLECTION",t.START_COLLECTION="START_COLLECTION",t.SET_PORTS="SET_PORTS",t.COLLECTOR_ERROR="COLLECTOR_ERROR",t.STAR_RATING="STAR_RATING",t.ALL_FACE_TRACKERS_WARMED_UP="ALL_FACE_TRACKERS_WARMED_UP",t.CONSTRAINTS_UPDATED="CONSTRAINTS_UPDATED",t.SHOULD_END_MEASUREMENT_EARLY="SHOULD_END_MEASUREMENT_EARLY",t.GET_LOGS="GET_LOGS",t.NEW_FRAME="NEW_FRAME",t.TRACKING_STATUS="TRACKING_STATUS",t.SCALE_FACTOR_CHANGED="SCALE_FACTOR_CHANGED",t))(T||{}),y=(t=>(t.CONNECT="CONNECT",t.DISCONNECT="DISCONNECT",t.DISCONNECTED="DISCONNECTED",t.LOGIN_WITH_TOKEN_SUCCESS="LOGIN_WITH_TOKEN_SUCCESS",t.SUBSCRIBED_TO_RESULTS="SUBSCRIBED_TO_RESULTS",t.CHUNK_SENT="CHUNK_SENT",t.RESULTS_RECEIVED="RESULTS_RECEIVED",t.CHUNK_ACKNOWLEDGED="CHUNK_ACKNOWLEDGED",t.ERROR="ERROR",t.NETWORK_DELAY="NETWORK_DELAY",t))(y||{}),Ti=Object.defineProperty,mt=t=>{throw TypeError(t)},Si=(t,e,i)=>e in t?Ti(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ut=(t,e,i)=>Si(t,typeof e!="symbol"?e+"":e,i),Ge=(t,e,i)=>e.has(t)||mt("Cannot "+i),s=(t,e,i)=>(Ge(t,e,"read from private field"),i?i.call(t):e.get(t)),S=(t,e,i)=>e.has(t)?mt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),f=(t,e,i,r)=>(Ge(t,e,"write to private field"),e.set(t,i),i),l=(t,e,i)=>(Ge(t,e,"access private method"),i),bi=(t,e,i,r)=>({set _(c){f(t,e,c)},get _(){return s(t,e,r)}}),x,g,P,v,L,ke,ve,Ae,ye,ce,z,Oe,de,he,b,q,D,me,F,Ne,Z,Q,ee,te,ue,fe,Y,Ee,Le,ie,De,se,pe,A,Te,B,Se,o,ft,Et,pt,He,Ve,Tt,St,bt,_t,gt,wt,Ie,Ke,p,Rt,Ct,kt,vt,ae,R;const At=Symbol("instance_creation_key"),_i=class Ot{constructor(e){if(S(this,o),S(this,x),S(this,g,{mediaElement:document.createElement("div"),assetFolder:"",apiUrl:"",metrics:!1,logger:{sdk:!1,mediaPipe:!1,beforeRESTCall:!1,afterRESTCall:!1,extractionLibWasm:!1,apiClient:!1,extractionWorker:!1,faceTrackerWorkers:!1},mirrorVideo:!0,displayMediaStream:!0,constraintOverrides:{}}),S(this,P,[{file:"decompress.json",uncompressedSize:89469},{file:"extraction_worker_0.1.0-beta.2_js.json",uncompressedSize:59696},{file:"facetracker_worker_0.1.0-beta.2_js.json",uncompressedSize:306553},{file:"extraction_wasm_0.1.0-beta.2.json",uncompressedSize:1926126},{file:"detectorModel_json.json",uncompressedSize:4640},{file:"detectorModel_bin.json",uncompressedSize:242046},{file:"landmarkModel_json.json",uncompressedSize:5036},{file:"landmarkModel_bin.json",uncompressedSize:1704814}]),S(this,v,new nt),S(this,L,Yt.init()),S(this,ke),S(this,ve),S(this,Ae),S(this,ye),S(this,ce),S(this,z),S(this,Oe),S(this,de,{version:"",sdkId:""}),S(this,he,""),S(this,b),S(this,q,0),S(this,D),S(this,me,j.ASSETS_NOT_DOWNLOADED),S(this,F,""),S(this,Ne,""),S(this,Z,!1),S(this,Q,5),S(this,ee,30),S(this,te,5),S(this,ue,!1),S(this,fe,4),S(this,Y),S(this,Ee),S(this,Le),S(this,ie,1e7),S(this,De,0),S(this,se,new Map),S(this,pe,Promise.resolve()),S(this,A,0),S(this,Te,-1),S(this,B,-1),S(this,Se,.5),ut(this,"on",{beforeRESTCall:null,afterRESTCall:null,bytesDownloaded:null,faceTrackerStateChanged:null,resultsReceived:null,constraintsUpdated:null,mediaElementResize:null,facialLandmarksUpdated:null,chunkSent:null,error:null}),e!==At)throw new Error("Use await Measurement.init() to create an instance of Measurement class.")}static async init(e){if(!e)throw new Error("Missing `settings` object");const i=new Ot(At);if(!i.setSettings(e))throw new Error("Invalid settings object");f(i,x,Bt({url:{http:new URL("https://api.deepaffex.ai")},onBeforeRESTCall:()=>{var n,a;l(n=i,o,St).call(n),l(a=i,o,bt).call(a)},onAfterRESTCall:(n,a)=>{var u,h;l(u=i,o,_t).call(u,n,a),l(h=i,o,gt).call(h,n,a)}}));const c=n=>{var a;const{bytes:u,url:h,uncompressedSize:E,done:_}=n.detail;l(a=i,o,p).call(a,`bytesDownloaded event, ${u}, ${E}, ${h}, ${_}`,m.mediaPipe),i.on.bytesDownloaded&&i.on.bytesDownloaded(u,E,h,_)},d=n=>{var a;const{error:u,url:h}=n.detail;l(a=i,o,p).call(a,`downloadError event, ${h}, ${u}`,m.mediaPipe),i.on.error&&i.on.error(Re.ASSET_DOWNLOAD,{url:h,error:u})};return s(i,L).addEventListener("downloadedError",d),s(i,L).addEventListener("bytesDownloaded",c),s(i,v).setVersion(i.getVersion()),s(i,g).logger&&Object.values(s(i,g).logger).some(n=>n===!0)&&s(i,v).start(),setTimeout(()=>{var n;l(n=i,o,ae).call(n,j.ASSETS_NOT_DOWNLOADED)},500),new Proxy(i,{get(n,a,u){const h=a;return typeof n[h]=="function"?n[h].bind(n):Reflect.get(n,h,u)},set(n,a,u){return console.log(`Setting property "${String(a)}" to "${u}" is not allowed`),!0}})}loadMask(e){if(s(this,b)){let i=!1;const r=s(this,b).mediaElement.querySelector("svg");r&&(i=!0,s(this,b).mediaElement.removeChild(r)),s(this,b).mediaElement.appendChild(e),i&&(s(this,b).mediaElement.style.setProperty("border","1px solid transparent"),setTimeout(()=>{s(this,b).mediaElement.removeAttribute("style")},100))}}setSettings(e){const i=ai(s(this,g),e);return i.results==="valid"?(f(this,g,i.settings),!0):!1}getVersion(){return{webSDK:Je,extractionLib:s(this,de),faceTracker:s(this,he)}}async downloadAssets(){const{assetFolder:e}=s(this,g);try{if(l(this,o,p).call(this,`Asset base URL ${e}`,m.sdk),l(this,o,p).call(this,"Start downloading decompressor...",m.sdk),await s(this,L).fetchAsset(s(this,P),`${e}/`,"decompress.json",!0,"gzip"),s(this,L).canDecompress){await l(this,o,Et).call(this,e),s(this,z)&&await l(this,o,Ve).call(this),l(this,o,p).call(this,"Start downloading TFJS worker...",m.mediaPipe);const i=await s(this,L).fetchAsset(s(this,P),`${e}/`,`facetracker_worker_${this.getVersion().webSDK}_js.json`,!0,"brotli");return i&&(f(this,Oe,i),await l(this,o,ft).call(this,e),await l(this,o,He).call(this)),l(this,o,pt).call(this),!0}}catch{return l(this,o,p).call(this,"Failed to download TFJS face tracker or DFX extraction worker WASM assets",m.mediaPipe),!1}}setExtractionLibSettings(e=6,i=30,r=5){f(this,Q,e-1),f(this,ee,i),f(this,te,r)}async setNextChunkAsFinal(){f(this,ue,!0),await l(this,o,R).call(this,T.SHOULD_END_MEASUREMENT_EARLY,{},!0),l(this,o,p).call(this,"Set the action for the next chunk to LAST::PROCESS",m.extractionLibWasm)}async startTracking(){s(this,b)&&(s(this,b).isExtracting||(s(this,b).setIsExtracting(!0),l(this,o,p).call(this,"Start tracking frames",m.mediaPipe),await l(this,o,R).call(this,T.SET_NUMBER_OF_CHUNKS,{value:s(this,ie)},!0),await l(this,o,Ie).call(this)))}async stopTracking(){if(s(this,b)){s(this,b).stopTracking(),await l(this,o,wt).call(this),s(this,b).setIsExtracting(!1),l(this,o,p).call(this,"Stop extracting frames",m.mediaPipe);const{numOfFramesPresented:e,warmupFrameNumber:i,numOftrackedVideoFrames:r}=s(this,b);l(this,o,p).call(this,"Tracking metrics",m.sdk,{numOfFramesPresented:e,warmupFrameNumber:i,numOftrackedVideoFrames:r}),f(this,F,"")}}async disconnect(){s(this,Z)&&await l(this,o,R).call(this,y.DISCONNECT,{},!0),s(this,g).metrics&&(await l(this,o,R).call(this,T.GET_LOGS,{},!0),s(this,v).retrieveLogs())}async destroy(){s(this,D)&&(s(this,D).destroy(),l(this,o,p).call(this,"Destroyed",m.extractionLibWasm)),s(this,b)&&(s(this,b).destroyWorkers(),l(this,o,p).call(this,"Destroyed",m.mediaPipe))}async reset(){return s(this,me)===j.READY?(await this.stopTracking(),await this.destroy(),f(this,v,new nt),f(this,de,{version:"",sdkId:""}),f(this,he,""),f(this,q,0),f(this,F,""),f(this,Z,!1),f(this,Q,5),f(this,ee,30),f(this,te,5),f(this,ue,!1),f(this,Y,void 0),f(this,ie,1e7),f(this,De,0),f(this,se,new Map),f(this,pe,Promise.resolve()),f(this,A,0),f(this,Te,-1),f(this,B,-1),s(this,g).mediaElement.innerHTML="",await l(this,o,Ve).call(this),await l(this,o,He).call(this),!0):!1}async setMediaStream(e){if(s(this,b)&&!s(this,b).isExtracting&&s(this,D)){await s(this,b).setMediaStream(e);const i=Object.fromEntries(s(this,b).workers.map((r,c)=>[`port${c+1}`,r.channel.port1]));s(this,D).worker.postMessage({action:T.SET_PORTS,payload:{numOfWorkers:s(this,fe),workerPorts:i}},[...s(this,b).workers.map(r=>r.channel.port1)])}}async prepare(e,i,r,c){s(this,x).setSession({userToken:e,userRefreshToken:i});const{region:d,status:n}=await l(this,o,Rt).call(this,"user");let a=`api.${d}.deepaffex.ai`;s(this,g).apiUrl?a=s(this,g).apiUrl:s(this,g).apiUrl=a,s(this,x).setUrl(`https://${a}`);const u=await l(this,o,Ct).call(this,e,i,"user"),h=await l(this,o,kt).call(this,r,c);return u&&h&&n==="200"}async setConstraintsConfig(e){await l(this,o,R).call(this,T.SET_CONSTRAINTS_CONFIG,{...s(this,Le),...e&&{...s(this,g).constraintOverrides}},!0)}async startMeasurement(e=!1,i={}){if(f(this,ue,!1),f(this,F,""),await l(this,o,vt).call(this,i),s(this,D)&&s(this,F)!==""){await l(this,o,Ke).call(this),await l(this,o,R).call(this,T.SET_NUMBER_OF_CHUNKS,{value:s(this,Q)+1},!0),await this.setConstraintsConfig(e),await l(this,o,Tt).call(this),await l(this,o,Ie).call(this);const{userToken:r}=s(this,x).getSession();r?await l(this,o,R).call(this,y.CONNECT,{token:r,measurementId:s(this,F)},!0):l(this,o,p).call(this,"User token is missing. Unable to connect.",m.webSocket)}}setDemographics(e){ri(e)?(f(this,Y,e),l(this,o,p).call(this,`Demographics updated ${JSON.stringify(e)}`,m.extractionLibWasm)):l(this,o,p).call(this,`Error updating Demographics ${JSON.stringify(e)}`,m.extractionLibWasm)}setObjectFit(e){return s(this,b)&&Ce!==void 0&&Object.values(Ce).includes(e)?(s(this,b).settings.objectFit=e,!0):!1}};x=new WeakMap,g=new WeakMap,P=new WeakMap,v=new WeakMap,L=new WeakMap,ke=new WeakMap,ve=new WeakMap,Ae=new WeakMap,ye=new WeakMap,ce=new WeakMap,z=new WeakMap,Oe=new WeakMap,de=new WeakMap,he=new WeakMap,b=new WeakMap,q=new WeakMap,D=new WeakMap,me=new WeakMap,F=new WeakMap,Ne=new WeakMap,Z=new WeakMap,Q=new WeakMap,ee=new WeakMap,te=new WeakMap,ue=new WeakMap,fe=new WeakMap,Y=new WeakMap,Ee=new WeakMap,Le=new WeakMap,ie=new WeakMap,De=new WeakMap,se=new WeakMap,pe=new WeakMap,A=new WeakMap,Te=new WeakMap,B=new WeakMap,Se=new WeakMap,o=new WeakSet,ft=async function(t){l(this,o,p).call(this,"Start downloading TFJS face tracker assets...",m.mediaPipe);const e=`${t}/models/`,[i,r,c,d]=await Promise.all([s(this,L).fetchAsset(s(this,P),e,"detectorModel_json.json",!0,"brotli"),s(this,L).fetchAsset(s(this,P),e,"detectorModel_bin.json",!0,"brotli"),s(this,L).fetchAsset(s(this,P),e,"landmarkModel_json.json",!0,"brotli"),s(this,L).fetchAsset(s(this,P),e,"landmarkModel_bin.json",!0,"brotli")]);l(this,o,p).call(this,"TFJS face tracker assets successfully downloaded",m.mediaPipe),f(this,ke,i),f(this,ve,r),f(this,Ae,c),f(this,ye,d)},Et=async function(t){l(this,o,p).call(this,"Start downloading DFX extraction worker assets...",m.extractionLibWasm);const[e,i]=await Promise.all([s(this,L).fetchAsset(s(this,P),`${t}/extraction/`,`extraction_wasm_${this.getVersion().webSDK}.json`,!0,"brotli"),s(this,L).fetchAsset(s(this,P),`${t}/`,`extraction_worker_${this.getVersion().webSDK}_js.json`,!0,"brotli")]);l(this,o,p).call(this,"DFX extraction worker assets successfully downloaded",m.extractionLibWasm),f(this,ce,e),f(this,z,i)},pt=function(){if(s(this,b)){const t=e=>{this.on.mediaElementResize&&this.on.mediaElementResize(e)};s(this,g).mediaElement.addEventListener("mediaElementSizeChanged",t)}},He=async function(){s(this,g),l(this,o,ae).call(this,j.NOT_LOADED);const t={faceTrackerCode:s(this,Oe),numOfWorkers:s(this,fe),mediaElement:s(this,g).mediaElement,mirrorVideo:s(this,g).mirrorVideo,metrics:s(this,g).metrics,displayMediaStream:s(this,g).displayMediaStream,isLoggingFaceTrackerWorkers:s(this,g).logger?.faceTrackerWorkers??!1,isLoggingSdk:s(this,g).logger?.sdk??!1,scaleFactor:s(this,Se),models:{detectorJson:s(this,ke),detectorBin:s(this,ve),landmarkJson:s(this,Ae),landmarkBin:s(this,ye)}};l(this,o,ae).call(this,j.LOADING),f(this,b,await pi.init(t,s(this,v))),s(this,b).on.faceTrackersReady=(e,i,r,c)=>{l(this,o,p).call(this,`TFJS face tracker version ${i} loaded. Worker name: ${e} - workerId: ${r} - backend: ${c}`,m.mediaPipe),f(this,he,`${i}-${c}`),f(this,q,s(this,q)+1),s(this,v).setVersion(this.getVersion()),s(this,q)===s(this,fe)&&l(this,o,ae).call(this,j.LOADED)},s(this,b).on.frameAvailable=(e,i,r,c,d)=>{!c&&d?s(this,D).worker.postMessage({action:T.NEW_FRAME,payload:{frameNumber:i,frameTimestamp:e,frame:d,lastFrameNumber:r,tracked:c}},[d]):s(this,D).worker.postMessage({action:T.TRACKING_STATUS,payload:{frameNumber:i,frameTimestamp:e,lastFrameNumber:r,tracked:c}})},s(this,b).on.landmarksAvailable=(e,i,r)=>{const c=r/1e3;s(this,B)===0&&f(this,B,c),f(this,Te,c),s(this,b).numOftrackedVideoFrames+=1;const{starRating:d}=s(this,b),n=30,a=Math.min(s(this,Te)-s(this,B),n),u=s(this,B)>0?a/n*100:0,h={video:s(this,b).videoFpsTracker.fps.toFixed(1),faceTracker:s(this,b).faceTrackerFpsTracker.fps.toFixed(1)},E={face:e,annotations:i,starRating:d,percentCompleted:u,fps:h};this.on.facialLandmarksUpdated&&this.on.facialLandmarksUpdated(E)},s(this,b).on.scaleFactorChanged=e=>{f(this,Se,e),s(this,b).scaleFactor=e,s(this,D).worker.postMessage({action:T.SCALE_FACTOR_CHANGED,payload:{scaleFactor:e}})}},Ve=async function(){const t=new TextDecoder().decode(new Uint8Array(s(this,z)));f(this,D,xe.init(t,"module","EXTRACTION_WORKER"));const{studyCfgData:e}=s(this,x).getSession();e&&s(this,ce)&&s(this,z)&&(s(this,D).worker.onmessage=async i=>{const{data:r}=i,{id:c,result:d}=r,{action:n,payload:a}=d,u=s(this,se).get(c);if(u||c===-1){switch(n){case T.READY:{const{sdkId:h,version:E,workerName:_}=a;f(this,de,{version:E,sdkId:h}),l(this,o,p).call(this,`DFX extraction worker WASM loaded. SDK ID: ${h} - Version: ${E} - Worker Name: ${_}`,m.extractionLibWasm),await l(this,o,R).call(this,T.SET_MODE,{value:"discrete"},!0),await l(this,o,R).call(this,T.SET_NUMBER_OF_CHUNKS,{value:s(this,ie)},!0),await l(this,o,R).call(this,T.SET_TARGET_FPS,{value:s(this,ee)},!0),await l(this,o,R).call(this,T.SET_CHUNK_DURATION_SECONDS,{value:s(this,te)},!0),await l(this,o,R).call(this,T.SET_FRAME_ORDER,{value:ot.RGBA},!0),await l(this,o,R).call(this,T.GET_CONSTRAINTS_CONFIG,{},!0),f(this,Le,s(this,Ee));break}case T.SET_MODE:{a&&l(this,o,p).call(this,`Set mode to ${a.mode}`,m.extractionLibWasm);break}case T.SET_NUMBER_OF_CHUNKS:{a&&l(this,o,p).call(this,`Set number of chunks to ${d.number}`,m.extractionLibWasm);break}case T.SET_TARGET_FPS:{a&&l(this,o,p).call(this,`Set target FPS to ${s(this,ee)}`,m.extractionLibWasm);break}case T.SET_CHUNK_DURATION_SECONDS:{a&&l(this,o,p).call(this,`Set chunk duration to ${s(this,te)} Seconds`,m.extractionLibWasm);break}case T.SET_FRAME_ORDER:{a&&l(this,o,p).call(this,"Set channel order RGBA",m.extractionLibWasm);break}case T.GET_CONSTRAINTS_CONFIG:{a&&(f(this,Ee,a),l(this,o,p).call(this,`Get constraints ${JSON.stringify(a)}`,m.extractionLibWasm));break}case T.SET_CONSTRAINTS_CONFIG:{a&&(f(this,Ee,a),l(this,o,p).call(this,`Set constraints ${JSON.stringify(a)}`,m.extractionLibWasm));break}case T.SET_FACE_ATTRIBUTE:{const{success:h,faceId:E,attribute:_,value:C}=a;h&&l(this,o,p).call(this,`Set face attribute: faceId: ${E}, attribute: ${_}, value: ${C}`,m.extractionLibWasm);break}case T.RESET_COLLECTION:{a&&l(this,o,p).call(this,"Reset collection",m.extractionLibWasm);break}case T.CANCEL_COLLECTION:{a&&l(this,o,p).call(this,"Collecttion cancelled",m.extractionLibWasm);break}case T.START_COLLECTION:{a&&l(this,o,p).call(this,`Collector started - state: ${a}`,m.extractionLibWasm);break}case T.SET_PORTS:{a&&l(this,o,p).call(this,"Ports set",m.extractionLibWasm);break}case T.COLLECTOR_ERROR:{if(a){const{error:h,frameNumber:E}=a;l(this,o,p).call(this,`Collector error on frame ${E}: ${h}`,m.extractionLibWasm),this.on.error&&this.on.error(Re.COLLECTOR,a),await this.stopTracking()}break}case T.STAR_RATING:{s(this,b).starRating=a.rating;break}case T.ALL_FACE_TRACKERS_WARMED_UP:{const{frameNumber:h}=d;s(this,b).warmupFrameNumber=h,l(this,o,p).call(this,"All face tracker workers are warmed up.",m.mediaPipe),l(this,o,ae).call(this,j.READY);break}case T.CONSTRAINTS_UPDATED:{const{feedback:h,status:E}=a;this.on.constraintsUpdated&&this.on.constraintsUpdated(h,E);break}case T.SHOULD_END_MEASUREMENT_EARLY:{const{currentFinalChunkNumber:h,currentResultsOrder:E,newFinalChunkNumber:_}=d;l(this,o,p).call(this,`Request the end measurement early. Current final chunk number: ${h}, Current results order: ${E}, New final chunk number: ${_}`,m.extractionLibWasm);break}case T.GET_LOGS:{console.log(`DFX Log: ${a}`);break}case y.CONNECT:{f(this,Z,!0),f(this,B,0),l(this,o,p).call(this,a?"Connected":"Connection error",m.webSocket);break}case y.LOGIN_WITH_TOKEN_SUCCESS:{l(this,o,p).call(this,"Successfully logged in with token",m.webSocket);break}case y.SUBSCRIBED_TO_RESULTS:{l(this,o,p).call(this,"Subscribed to the results",m.webSocket);break}case y.CHUNK_SENT:{l(this,o,p).call(this,`Chunk sent ${JSON.stringify(a)}`,m.webSocket),this.on.chunkSent&&this.on.chunkSent(a);break}case y.DISCONNECT:{f(this,Z,!1),l(this,o,p).call(this,"Disconnect",m.webSocket);break}case y.DISCONNECTED:{l(this,o,p).call(this,`Disconnected! - code: ${a.code}, reason: ${a.reason}, wasClean: ${a.wasClean}`,m.webSocket),this.on.error&&this.on.error(Re.WEB_SOCKET,a);break}case y.CHUNK_ACKNOWLEDGED:{l(this,o,p).call(this,`Chunk number ${a.chunkOrder} received by the server!`,m.webSocket),s(this,Q)===a.chunkOrder&&await this.stopTracking();break}case y.RESULTS_RECEIVED:{const{resultsOrder:h,finalChunkNumber:E}=a;this.on.resultsReceived&&this.on.resultsReceived(a),l(this,o,p).call(this,`Results received: ${JSON.stringify(a)}`,m.webSocket),h===E&&(await l(this,o,R).call(this,y.DISCONNECT,{},!0),await l(this,o,Ke).call(this),await l(this,o,Ie).call(this));break}case y.NETWORK_DELAY:{const{delay:h,description:E,actionId:_}=a;l(this,o,p).call(this,`Round-trip delay for ${E} call with Action ID ${_} was ${h.toFixed(2)} ms`,m.webSocket,{delay:h,actionId:_,description:E});break}case y.ERROR:{l(this,o,p).call(this,"Error",m.webSocket),this.on.error&&this.on.error(Re.WEB_SOCKET,a);break}}u&&(u.resolve(d),s(this,se).delete(c))}},await l(this,o,R).call(this,T.INIT,{wasm:s(this,ce),studyConfigData:e,isLogging:s(this,g).logger?.extractionWorker||!1,metrics:s(this,g).metrics||!1,apiUrl:s(this,g).apiUrl,scaleFactor:s(this,Se)},!0))},Tt=async function(){if(s(this,b)&&s(this,Y)){const{age:e,height:i,weight:r,sex:c,smoking:d,bloodPressureMedication:n,diabetes:a}=s(this,Y);await l(this,o,R).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:K.SEX_ASSIGNED_AT_BIRTH,value:c},!0),await l(this,o,R).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:K.AGE_YEARS,value:e},!0),await l(this,o,R).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:K.HEIGHT_CM,value:i},!0),await l(this,o,R).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:K.WEIGHT_KG,value:r},!0),await l(this,o,R).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:K.SMOKER,value:d},!0),await l(this,o,R).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:K.BLOOD_PRESSURE_MEDICATION,value:n},!0),await l(this,o,R).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:K.DIABETES,value:a},!0),l(this,o,p).call(this,`Set demographics for Face ID 1, ${JSON.stringify(s(this,Y))}`,m.extractionLibWasm)}},St=function(){},bt=function(){const t=new Date().toISOString();st(t)&&(l(this,o,p).call(this,`Action ID: ${s(this,A)}`,m.beforeRESTCall),this.on.beforeRESTCall&&this.on.beforeRESTCall(t,s(this,A)))},_t=function(t,e){},gt=function(t,e){const i=new Date().toISOString();st(i)&&(l(this,o,p).call(this,`Action ID: ${s(this,A)}, HTTP status code: ${t}, error: ${JSON.stringify(e)}`,m.afterRESTCall),this.on.afterRESTCall&&this.on.afterRESTCall(i,s(this,A),t,e))},wt=async function(){await l(this,o,R).call(this,T.CANCEL_COLLECTION,{},!0)},Ie=async function(){await l(this,o,R).call(this,T.START_COLLECTION,{},!0)},Ke=async function(){await l(this,o,R).call(this,T.RESET_COLLECTION,{},!0),await l(this,o,R).call(this,T.SET_NUMBER_OF_CHUNKS,{value:s(this,ie)},!0)},p=function(t,e,i){s(this,g).metrics&&s(this,v).log(t,e,"",!0,i),s(this,g).logger?.mediaPipe&&e===m.mediaPipe&&s(this,v).info(t,e),s(this,g).logger?.beforeRESTCall&&e===m.beforeRESTCall&&s(this,v).info(t,e),s(this,g).logger?.afterRESTCall&&e===m.afterRESTCall&&s(this,v).info(t,e),s(this,g).logger?.extractionLibWasm&&e===m.extractionLibWasm&&s(this,v).info(t,e),s(this,g).logger?.apiClient&&e===m.apiClient&&s(this,v).info(t,e),s(this,g).logger?.webSocket&&e===m.webSocket&&s(this,v).info(t,e),s(this,g).logger?.sdk&&e===m.sdk&&s(this,v).info(t,e)},Rt=async function(t){f(this,A,0);const e=performance.now(),i=await s(this,x).http.auths.validate(t),r=performance.now()-e,{status:c,body:d}=i;if(l(this,o,p).call(this,c==="200"?"Successfully validated the Token":`Failed to validate token. Status: ${c}`,m.apiClient,{delay:r,actionId:s(this,A),description:"Validate Token"}),c==="200"){const{Region:n}=d;return{region:n,status:c}}else return{status:c,region:""}},Ct=async function(t,e,i){f(this,A,2304);const r=performance.now(),c=await s(this,x).http.auths.renew({Token:t,RefreshToken:e},i),d=performance.now()-r,{status:n}=c;return l(this,o,p).call(this,n==="200"?"Successfully refreshed the Token":`Failed to refresh token. Status: ${n}`,m.apiClient,{delay:d,actionId:s(this,A),description:"Refresh Token"}),n==="200"},kt=async function(t,e){f(this,A,806);const i=performance.now();f(this,Ne,t);const r=await s(this,x).http.studies.retrieveSdkConfigData({StudyID:t,...e&&{sdkId:e}},"user"),c=performance.now()-i,{status:d}=r;return l(this,o,p).call(this,d==="200"?"Retrieve SDK Config Data - success":"Retrieve SDK Config Data - failure",m.apiClient,{delay:c,actionId:s(this,A),description:"Retrieve SDK Config Data"}),d==="200"},vt=async function(t){l(this,o,p).call(this,"Get Measurement ID",m.apiClient),f(this,A,504);const e=performance.now(),i={StudyID:s(this,Ne),Resolution:100};t.partnerId&&(i.PartnerID=t.partnerId),t.userProfileId&&(i.UserProfileID=t.userProfileId);const r=await s(this,x).http.measurements.create(i,"user"),c=performance.now()-e,{status:d,body:n}=r;let a="";d==="200"?(f(this,F,n.ID),a=`Successfully obtained measurement ID: ${s(this,F)}`):(f(this,F,""),a=`Failed to obtain measurement ID. Status: ${d}`),l(this,o,p).call(this,a,m.apiClient,{delay:c,actionId:s(this,A),measurementId:s(this,F),description:"Get Measurement ID"})},ae=function(t){f(this,me,t),l(this,o,p).call(this,`Face tracker state changed: ${t}`,m.mediaPipe),this.on.faceTrackerStateChanged&&this.on.faceTrackerStateChanged(s(this,me))},R=function(t,e,i=!1){return new Promise(r=>{const c=bi(this,De)._++;s(this,se).set(c,{resolve:r,action:t});const d=()=>s(this,D).worker.postMessage({id:c,action:t,payload:e});i?f(this,pe,s(this,pe).then(d).catch(n=>console.error(n))):d()})},ut(_i,"VERSION",Je);class gi{static VERSION=Nt;#e=document.createElement("div");#i=document.createElement("div");#s=!1;on={results:null,error:null,event:null};constructor(){this.#e.style.height="100%"}init(e){const{container:i,appPath:r,settings:c,profile:d,config:n,loadError:a,language:u,apiUrl:h}=e;this.#i=i;const E=i.attachShadow({mode:"open"}),_="app",C=document.createElement("link");C.rel="stylesheet",C.href=`${r}/stylex.css`,E.appendChild(C);const k=document.createElement("link");k.rel="stylesheet",k.href=`${r}/${_}.css`,E.appendChild(k);const I=H=>{this.on.results&&this.on.results({...H.detail})},W=H=>{this.on.error&&this.on.error({...H.detail})},G=H=>{this.on.event&&this.on.event({...H.detail})};this.#e.addEventListener(U.RESULTS,I),this.#e.addEventListener(U.ERROR,W),this.#e.addEventListener(U.APPEVENT,G),E.appendChild(this.#e);const M=document.createElement("script");M.type="module",M.src=`${r}/${_}.mjs`,M.onload=()=>{import(M.src).then(H=>{H.app.init(this.#e,r,c,d,h,n,u),this.#s=!0}).catch(()=>{a&&a("Failed to initialize Measurement Embedded React app")})},M.onerror=()=>{a&&a("Failed to load the measurement embedded app script")},E.appendChild(M)}#t(){if(!this.#s)throw new Error("MeasurementEmbeddedApp is not initialized. Call init() before using this method.")}async destroy(){return this.#t(),new Promise(e=>{const i=c=>{if(this.#e.removeEventListener(U.DESTROYED,i),this.#i){const d=this.#i.cloneNode(!1);this.#i.replaceWith(d)}e()};this.#e.addEventListener(U.DESTROYED,i);const r=new CustomEvent("measurement-embedded-app-action",{detail:{action:re.DESTROY,data:{}}});this.#e.dispatchEvent(r)})}setTheme(e){this.#t();const i=new CustomEvent("measurement-embedded-app-action",{detail:{action:re.SET_THEME,data:{theme:e}}});this.#e.dispatchEvent(i)}setLanguage(e){this.#t();const i=new CustomEvent("measurement-embedded-app-action",{detail:{action:re.SET_LANGUAGE,data:{language:e}}});this.#e.dispatchEvent(i)}async cancel(e){return this.#t(),new Promise(i=>{const r=d=>{this.#e.removeEventListener(U.CANCELLED,r),i(d.detail.reset)};this.#e.addEventListener(U.CANCELLED,r);const c=new CustomEvent("measurement-embedded-app-action",{detail:{action:re.CANCEL,data:{reset:e}}});this.#e.dispatchEvent(c)})}getLogs(){return this.#t(),new Promise(e=>{const i=c=>{this.#e.removeEventListener(U.LOGS,i),e(c.detail.logs)};this.#e.addEventListener(U.LOGS,i);const r=new CustomEvent("measurement-embedded-app-action",{detail:{action:re.GET_LOGS,data:{}}});this.#e.dispatchEvent(r)})}}export{Ye as ErrorCodes,Lt as appEvents,gi as default,di as faceAttributeValue,je as logCategory};
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@nuralogix.ai/web-measurement-embedded-app",
3
- "version": "0.1.0-beta.1",
3
+ "version": "0.1.0-beta.3",
4
4
  "description": "Web Measurement Embedded App",
5
5
  "homepage": "https://docs.deepaffex.ai/wmea/",
6
6
  "contributors": [
7
7
  "Hamed Hassanzadeh Amin",
8
8
  "Will Morgan"
9
9
  ],
10
+ "type": "module",
10
11
  "main": "./lib/index.mjs",
11
12
  "types": "./lib/index.d.ts",
12
13
  "exports": {