@authme/engine 2.2.0-rc.9 → 2.2.1-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,8 +3,6 @@
3
3
  let wasm_loaded = false;
4
4
  let wasm_loading = false;
5
5
 
6
- let modelSession = {};
7
-
8
6
  function importScriptsViaJsContent(jsContent) {
9
7
  const objectUrl = URL.createObjectURL(
10
8
  new Blob([jsContent], { type: 'text/javascript' })
@@ -13,40 +11,8 @@
13
11
  URL.revokeObjectURL(objectUrl);
14
12
  }
15
13
 
16
- function base64toBlob(data) {
17
- const byteChars = self.atob(data);
18
- const byteNumbers = new Array(byteChars.length);
19
- for (let i = 0; i < byteChars.length; i++) {
20
- byteNumbers[i] = byteChars.charCodeAt(i);
21
- }
22
- const byteArray = new Uint8Array(byteNumbers);
23
- return new Blob([byteArray], { type: 'application/octet-stream' });
24
- }
25
-
26
- async function fetchModel(code) {
27
- const method = self.config.dataTransferMethod || 'binary';
28
-
29
- const resp = await fetch(
30
- `${self.config.apiBaseUrl}/api/model-management/v1/model/${code}${
31
- method === 'binary' ? '/file' : ''
32
- }`,
33
- {
34
- headers: {
35
- Authorization: 'Bearer ' + self.config.token,
36
- },
37
- }
38
- );
39
-
40
- if (method === 'binary') {
41
- return resp.blob();
42
- } else {
43
- const data = await resp.json();
44
- return base64toBlob(data.data);
45
- }
46
- }
47
-
48
14
  async function loadWasm({ engineJsContent, engineWasmContent }) {
49
- return new Promise((res, rej) => {
15
+ return new Promise(function loadWasmExecutor(res, rej) {
50
16
  // console.log('load wasm');
51
17
  if (wasm_loaded || wasm_loading) {
52
18
  res(true);
@@ -65,7 +31,7 @@
65
31
  },
66
32
  };
67
33
  importScriptsViaJsContent(engineJsContent);
68
- let tryInitEngineLib = async () => {
34
+ async function tryInitEngineLib() {
69
35
  try {
70
36
  const module = await AuthmeMLEngineLib({
71
37
  wasmBinary: engineWasmContent,
@@ -89,64 +55,231 @@
89
55
  console.warn(
90
56
  'init Authme EngineLib error:',
91
57
  error,
92
- ' Try after 1 second.'
58
+ ' Try after 3 second.'
93
59
  );
94
- await waitTime(500);
60
+ await waitTime(3000);
95
61
  await tryInitEngineLib();
96
62
  }
97
- };
63
+ }
98
64
  tryInitEngineLib();
99
65
  }
100
66
  });
101
67
  }
102
68
 
103
- // PassportService
104
- self.PassportService = {
105
- instance: null,
106
- init: async function () {
107
- return await self.Base.init(self.PassportService, 'PassportService');
69
+ // Base
70
+ const baseFunctions = {
71
+ // 由於不同 service 間的 _loadedSessions instance 是隔離開來的,
72
+ // 所以不能將 _loadedSessions: {} 直接放到這裡,
73
+ // 否則會造成 destroy 異常。
74
+ // 更好的做法會是用 class 替代現在的做法,只是改的幅度偏大,
75
+ // 所以暫時保留現有的做法。
76
+ _getLoadedModelKey({ modelVersion: { name, version } }) {
77
+ return `${name}#${version}`;
78
+ },
79
+ _getModelVersions(constructorName) {
80
+ const versionVector =
81
+ self.EngineLib[constructorName]['getModelVersion']();
82
+ const models = [];
83
+ for (let i = 0; i < versionVector.size(); i++) {
84
+ let item = versionVector.get(i);
85
+ models.push({
86
+ name: `${item.szName}`,
87
+ version: `${item.szVersion}`,
88
+ });
89
+ }
90
+ return models;
108
91
  },
109
- start: function () {
110
- return self.Base.start(self.PassportService);
92
+ _getNoLoadedModelVersions(constructorName) {
93
+ const modelVersions = this._getModelVersions(constructorName);
94
+ return modelVersions.filter(
95
+ (modelVersion) =>
96
+ !this._loadedSessions[this._getLoadedModelKey({ modelVersion })]
97
+ );
111
98
  },
112
- stop: function () {
113
- return self.Base.stop(self.PassportService);
99
+
100
+ // worker 專心處理 cpu 密集 (model 載入) 的工作,
101
+ // 至於純 IO 下載的任務就交給 main thread 處理就好。
102
+ loadSession({ modelVersion: { name, version }, modelArrayBuffer }) {
103
+ let fileMounted = false;
104
+ try {
105
+ const FS = self.EngineLib.FS;
106
+ FS.mkdir(`/${name}-${version}/`);
107
+ FS.mount(
108
+ FS.filesystems.WORKERFS,
109
+ {
110
+ blobs: [
111
+ {
112
+ name: `${name}-${version}`,
113
+ data: new Blob([modelArrayBuffer], {
114
+ type: 'application/octet-stream',
115
+ }),
116
+ },
117
+ ],
118
+ },
119
+ `/${name}-${version}/`
120
+ );
121
+ fileMounted = true;
122
+ } catch (error) {
123
+ if (error?.errno === 20) {
124
+ // File Exist
125
+ fileMounted = true;
126
+ } else {
127
+ throw error;
128
+ }
129
+ }
130
+
131
+ if (fileMounted) {
132
+ const sessionKey = this._getLoadedModelKey({
133
+ modelVersion: { name, version },
134
+ });
135
+ if (this._loadedSessions[sessionKey]) {
136
+ throw new Error('should be undefined here.');
137
+ }
138
+ this._loadedSessions[sessionKey] =
139
+ self.EngineLib.createInferenceSession(
140
+ name,
141
+ `/${name}-${version}/${name}-${version}`
142
+ );
143
+ }
114
144
  },
115
- getJsonReport: function () {
116
- return self.Base.getJsonReport(self.PassportService);
145
+ async _init(constructorName) {
146
+ // 暫時將縮排透過遺留下來,減少 review 無變動的資訊。
147
+ {
148
+ {
149
+ {
150
+ const instance = new self.EngineLib[constructorName]();
151
+ instance.initial(
152
+ ...this._getModelVersions(constructorName).map(
153
+ (modelVersion) =>
154
+ this._loadedSessions[
155
+ this._getLoadedModelKey({ modelVersion })
156
+ ]
157
+ )
158
+ );
159
+ const engine = instance;
160
+ const uiParams = engine.getUIParams();
161
+ uiParams.previewPosition.fLeft = 0;
162
+ uiParams.previewPosition.fTop = 0;
163
+ uiParams.previewPosition.fRight = 1;
164
+ uiParams.previewPosition.fBottom = 1;
165
+ engine.setUIParams(uiParams);
166
+ this.instance = instance;
167
+ return true;
168
+ }
169
+ }
170
+ }
117
171
  },
118
- setFrameSize: function (params) {
119
- return self.Base.setFrameSize(self.PassportService, params);
172
+ start() {
173
+ return this.instance?.start();
120
174
  },
121
- getFinalResult: function (params) {
122
- return self.PassportService.instance.getFinalResult();
175
+ stop() {
176
+ return this.instance?.stop();
123
177
  },
124
- toJson: function (params) {
125
- return Object.getPrototypeOf(
126
- self.PassportService.instance
127
- ).constructor.toJson(params);
178
+ _setFrameSize(params) {
179
+ config.frame.width = Math.floor(params.width);
180
+ config.frame.height = Math.floor(params.height);
181
+ if (this.instance) {
182
+ const engine = this.instance;
183
+ const uiParams = engine.getUIParams();
184
+ uiParams.analyzeSize.iHeight = config.frame.height;
185
+ uiParams.analyzeSize.iWidth = config.frame.width;
186
+ engine.setUIParams(uiParams);
187
+ return true;
188
+ }
128
189
  },
129
- recognition: function (params) {
130
- const result = self.Base.recognition(self.PassportService, params);
131
- if (result) {
132
- result.eStatus = result.eStatus.constructor.name;
133
- result.tField = JSON.parse(self.PassportService.toJson(result.tField));
190
+ setFrameSize(params) {
191
+ return this._setFrameSize(params);
192
+ },
193
+ _recognition(params) {
194
+ const engine = this.instance;
195
+ if (engine) {
196
+ try {
197
+ const data = params.data;
198
+ const heapInfo = putOnHeap(data);
199
+ const result = engine.run(
200
+ heapInfo.byteOffset,
201
+ heapInfo.length,
202
+ config.frame.width,
203
+ config.frame.height
204
+ );
205
+ self.EngineLib._free(heapInfo.dataPtr);
206
+ return result;
207
+ } catch (error) {
208
+ // console.warn(error);
209
+ // console.warn('[Recognition Error]: ' + error?.message);
210
+ return null;
211
+ }
134
212
  }
135
- return result;
213
+ console.warn('engine not initialized');
136
214
  },
137
- getParams: function () {
138
- return self.Base.getParams(self.PassportService);
215
+ recognition(params) {
216
+ return this._recognition(params);
139
217
  },
140
- setParams: function (params) {
141
- return self.Base.setParams(self.PassportService, params);
218
+ getParams() {
219
+ return this.instance.getParams();
142
220
  },
143
- getDebugImage: function (params) {
144
- return self.Base.getDebugImage(self.PassportService, params);
221
+ setParams(params) {
222
+ return this.instance.setParams(params.params);
145
223
  },
146
- destroy: function () {
147
- return self.Base.destroy(self.PassportService);
224
+ getDebugImage(params) {
225
+ const data = params.data;
226
+ const heapInfo = putOnHeap(data);
227
+ let imageData;
228
+ const pointer = this.instance.getDebugImage(
229
+ heapInfo.byteOffset,
230
+ heapInfo.length,
231
+ config.frame.width,
232
+ config.frame.height
233
+ );
234
+ self.EngineLib._free(heapInfo.dataPtr);
235
+ if (pointer) {
236
+ imageData = self.EngineLib.HEAPU8.slice(
237
+ pointer,
238
+ pointer + config.frame.width * config.frame.height * 4
239
+ );
240
+ self.EngineLib._free(pointer);
241
+ }
242
+ return imageData;
243
+ },
244
+ destroy() {
245
+ if (this.instance) {
246
+ this.instance.delete();
247
+ this.instance = null;
248
+ }
249
+ for (const session of Object.values(this._loadedSessions)) {
250
+ self.EngineLib.deleteSession(session);
251
+ }
252
+ this._loadedSessions = {};
253
+ },
254
+ getJsonReport() {
255
+ return this.instance?.getJsonReport();
256
+ },
257
+ };
258
+
259
+ // PassportService
260
+ self.PassportService = {
261
+ instance: null,
262
+ _loadedSessions: {},
263
+ ...baseFunctions,
264
+
265
+ getNoLoadedModelVersions() {
266
+ return this._getNoLoadedModelVersions('PassportService');
267
+ },
268
+ init() {
269
+ return this._init('PassportService');
148
270
  },
149
- setMaskPosition: function (params) {
271
+ toJson(params) {
272
+ return Object.getPrototypeOf(this.instance).constructor.toJson(params);
273
+ },
274
+ recognition(params) {
275
+ const result = this._recognition(params);
276
+ if (result) {
277
+ result.eStatus = result.eStatus.constructor.name;
278
+ result.tField = JSON.parse(self.PassportService.toJson(result.tField));
279
+ }
280
+ return result;
281
+ },
282
+ setMaskPosition(params) {
150
283
  const positions = params.positions;
151
284
  return self.PassportService.instance?.setMatchROI(
152
285
  positions[0][0],
@@ -164,24 +297,17 @@
164
297
  // Card OCR
165
298
  self.CardOCR = {
166
299
  instance: null,
167
- init: async function () {
168
- let result = await self.Base.init(self.CardOCR, 'CardOCR');
169
- return result;
170
- },
171
- start: function () {
172
- return self.Base.start(self.CardOCR);
173
- },
174
- stop: function () {
175
- return self.Base.stop(self.CardOCR);
176
- },
177
- getJsonReport: function () {
178
- return self.Base.getJsonReport(self.CardOCR);
300
+ _loadedSessions: {},
301
+ ...baseFunctions,
302
+
303
+ getNoLoadedModelVersions() {
304
+ return this._getNoLoadedModelVersions('CardOCR');
179
305
  },
180
- setFrameSize: function (params) {
181
- return self.Base.setFrameSize(self.CardOCR, params);
306
+ init() {
307
+ return this._init('CardOCR');
182
308
  },
183
- recognition: function (params) {
184
- const result = self.Base.recognition(self.CardOCR, params);
309
+ recognition(params) {
310
+ const result = this._recognition(params);
185
311
  if (result) {
186
312
  if (result.pointer > 0) {
187
313
  result.imageData = self.EngineLib.HEAPU8.slice(
@@ -196,24 +322,23 @@
196
322
  }
197
323
  return result;
198
324
  },
199
- getDebugImage: function (params) {
200
- return self.Base.getDebugImage(self.CardOCR, params);
201
- },
202
- setType: function (params) {
203
- const engine = self.CardOCR.instance;
325
+ setType({ type }) {
326
+ const engine = this.instance;
204
327
  if (engine) {
205
328
  const engineParams = engine.getParams();
206
329
  engineParams.eTargetCardType =
207
- self.EngineLib.EAuthMeCardClass.values[params.type];
330
+ self.EngineLib.EAuthMeCardClass[
331
+ type.replace(/^EAuthMeCardClass_/, '')
332
+ ];
208
333
  engineParams.fImageBlurTh = 750;
209
334
  engine.setParams(engineParams);
210
335
  return true;
211
336
  }
212
337
  return false;
213
338
  },
214
- setMaskPosition: function (params) {
339
+ setMaskPosition(params) {
215
340
  const positions = params.positions;
216
- return self.CardOCR.instance?.setCardMatchROI(
341
+ return this.instance?.setCardMatchROI(
217
342
  positions[0][0],
218
343
  positions[0][1],
219
344
  positions[1][0],
@@ -224,44 +349,29 @@
224
349
  positions[3][1]
225
350
  );
226
351
  },
227
- getParams: function () {
228
- return self.Base.getParams(self.CardOCR);
229
- },
230
- setParams: function (params) {
231
- return self.Base.setParams(self.CardOCR, params);
232
- },
233
- destroy: function () {
234
- return self.Base.destroy(self.CardOCR);
235
- },
236
352
  };
237
353
 
238
354
  // Id Card Anti Fraud
239
355
  self.IdCardAntiFraud = {
240
356
  instance: null,
241
- init: async function () {
242
- await self.Base.init(self.IdCardAntiFraud, 'IdCardAntiFraudService');
243
- if (self.IdCardAntiFraud.instance) {
244
- const engine = self.IdCardAntiFraud.instance;
357
+ _loadedSessions: {},
358
+ ...baseFunctions,
359
+
360
+ getNoLoadedModelVersions() {
361
+ return this._getNoLoadedModelVersions('IdCardAntiFraudService');
362
+ },
363
+ async init() {
364
+ await this._init('IdCardAntiFraudService');
365
+ if (this.instance) {
366
+ const engine = this.instance;
245
367
  const engineParams = engine.getParams();
246
368
  engineParams.timeoutSec = 52;
247
369
  engine.setParams(engineParams);
248
370
  return true;
249
371
  }
250
372
  },
251
- start: function () {
252
- return self.Base.start(self.IdCardAntiFraud);
253
- },
254
- stop: function () {
255
- return self.Base.stop(self.IdCardAntiFraud);
256
- },
257
- getJsonReport: function () {
258
- return self.Base.getJsonReport(self.IdCardAntiFraud);
259
- },
260
- setFrameSize: function (params) {
261
- return self.Base.setFrameSize(self.IdCardAntiFraud, params);
262
- },
263
- recognition: function (params) {
264
- const result = self.Base.recognition(self.IdCardAntiFraud, params);
373
+ recognition(params) {
374
+ const result = this._recognition(params);
265
375
  if (result) {
266
376
  result.eStatus = result.eStatus.constructor.name;
267
377
  result.eStage = result.eStage.constructor.name;
@@ -275,9 +385,9 @@
275
385
  }
276
386
  return result;
277
387
  },
278
- setMaskPosition: function (params) {
388
+ setMaskPosition(params) {
279
389
  const positions = params.positions;
280
- return self.IdCardAntiFraud.instance?.setFrontalCardVertices(
390
+ return this.instance?.setFrontalCardVertices(
281
391
  positions[0][0],
282
392
  positions[0][1],
283
393
  positions[1][0],
@@ -288,68 +398,55 @@
288
398
  positions[3][1]
289
399
  );
290
400
  },
291
- setStage: function (params) {
292
- if (self.IdCardAntiFraud.instance) {
401
+ setStage(params) {
402
+ if (this.instance) {
293
403
  const stageList = new self.EngineLib.FraudStageList();
294
- params.forEach((x) => {
295
- stageList.push_back(self.EngineLib.EAuthMeIDCardAntiFraudStage[x]);
296
- });
297
- self.IdCardAntiFraud.instance.setStage(stageList);
404
+ for (const stage of params) {
405
+ stageList.push_back(
406
+ self.EngineLib.EAuthMeIDCardAntiFraudStage[stage]
407
+ );
408
+ }
409
+ this.instance.setStage(stageList);
298
410
  }
299
411
  },
300
- getParams: function () {
301
- return self.Base.getParams(self.IdCardAntiFraud);
302
- },
303
- setParams: function (params) {
304
- return self.Base.setParams(self.IdCardAntiFraud, params);
305
- },
306
- getDebugImage: function (params) {
307
- return self.Base.getDebugImage(self.IdCardAntiFraud, params);
308
- },
309
- destroy: function () {
310
- return self.Base.destroy(self.IdCardAntiFraud);
311
- },
312
412
  };
313
413
 
314
414
  self.Fas = {
315
415
  instance: null,
316
- init: async function () {
317
- await self.Base.init(self.Fas, 'CFASService');
318
- },
319
- start: function () {
320
- return self.Base.start(self.Fas);
321
- },
322
- stop: function () {
323
- return self.Base.stop(self.Fas);
416
+ _loadedSessions: {},
417
+ ...baseFunctions,
418
+
419
+ getNoLoadedModelVersions() {
420
+ return this._getNoLoadedModelVersions('CFASService');
324
421
  },
325
- getJsonReport: function () {
326
- return self.Base.getJsonReport(self.Fas);
422
+ init() {
423
+ return this._init('CFASService');
327
424
  },
328
- setFrameSize: function (params) {
329
- self.Base.setFrameSize(self.Fas, params);
425
+ setFrameSize(params) {
426
+ this._setFrameSize(params);
330
427
  if (config.frame.width / config.frame.height >= 1) {
331
- const params = self.Fas.instance.getParams();
428
+ const params = this.instance.getParams();
332
429
  params.fFaceRoiPreviewRatioW = 0.3;
333
- self.Fas.instance.setParams(params);
430
+ this.instance.setParams(params);
334
431
  }
335
432
  },
336
- setStage: function (params) {
337
- if (self.Fas.instance) {
433
+ setStage(params) {
434
+ if (this.instance) {
338
435
  const stageList = new self.EngineLib.FASStageList();
339
- params.stageList.forEach((x) => {
340
- stageList.push_back(self.EngineLib.EAuthMeFASServiceStage[x]);
341
- });
342
- self.Fas.instance.setStage(stageList);
436
+ for (const stage of params.stageList) {
437
+ stageList.push_back(self.EngineLib.EAuthMeFASServiceStage[stage]);
438
+ }
439
+ this.instance.setStage(stageList);
343
440
  }
344
441
  },
345
442
  getStageParams({ stageIndex }) {
346
- return self.Fas.instance.getStageParams(stageIndex);
443
+ return this.instance.getStageParams(stageIndex);
347
444
  },
348
445
  setStageParams({ stageIndex, value }) {
349
- self.Fas.instance.setStageParams(value, stageIndex);
446
+ this.instance.setStageParams(value, stageIndex);
350
447
  },
351
- recognition: function (params) {
352
- const result = self.Base.recognition(self.Fas, params);
448
+ recognition(params) {
449
+ const result = this._recognition(params);
353
450
  if (result) {
354
451
  result.eStatus = result.eStatus.constructor.name;
355
452
  result.eStage = result.eStage.constructor.name;
@@ -361,188 +458,59 @@
361
458
  }
362
459
  return result;
363
460
  },
364
- getParams: function () {
365
- return self.Base.getParams(self.Fas);
366
- },
367
- setParams: function (params) {
368
- return self.Base.setParams(self.Fas, params);
369
- },
370
- getDebugImage: function (params) {
371
- return self.Base.getDebugImage(self.Fas, params);
372
- },
373
- destroy: function () {
374
- return self.Base.destroy(self.Fas);
375
- },
376
- };
377
-
378
- // Base
379
- self.Base = {
380
- init: async function (target, constructorName) {
381
- return new Promise((res, rej) => {
382
- try {
383
- setTimeout(async () => {
384
- const models = [];
385
- const versionVector =
386
- self.EngineLib[constructorName]['getModelVersion']();
387
- target.sessionUsed = [];
388
- for (let i = 0; i < versionVector.size(); i++) {
389
- let item = versionVector.get(i);
390
- target.sessionUsed.push(item.szName);
391
- models.push({
392
- name: item.szName,
393
- version: item.szVersion,
394
- });
395
- }
396
-
397
- let queryModelString = models
398
- .map((x) => 'models=' + x.name + '[' + x.version + ']')
399
- .join('&');
400
- let modelPath = await loadModels(queryModelString);
401
- let modelPointer = models.map(({ name }, index) => {
402
- if (modelSession[name]) {
403
- return modelSession[name];
404
- } else {
405
- modelSession[name] = self.EngineLib.createInferenceSession(
406
- name,
407
- modelPath[index]
408
- );
409
- return modelSession[name];
410
- }
411
- });
412
- const instance = new self.EngineLib[constructorName]();
413
- instance.initial(...modelPointer);
414
- const engine = instance;
415
- const uiParams = engine.getUIParams();
416
- uiParams.previewPosition.fLeft = 0;
417
- uiParams.previewPosition.fTop = 0;
418
- uiParams.previewPosition.fRight = 1;
419
- uiParams.previewPosition.fBottom = 1;
420
- engine.setUIParams(uiParams);
421
- target.instance = instance;
422
- res(true);
423
- }, 10);
424
- } catch (error) {
425
- rej(error.message);
426
- }
427
- });
428
- },
429
- start: function (target) {
430
- return target?.instance?.start();
431
- },
432
- stop: function (target) {
433
- return target?.instance?.stop();
434
- },
435
- setFrameSize: function (target, params) {
436
- config.frame.width = Math.floor(params.width);
437
- config.frame.height = Math.floor(params.height);
438
- if (target.instance) {
439
- const engine = target.instance;
440
- const uiParams = engine.getUIParams();
441
- uiParams.analyzeSize.iHeight = config.frame.height;
442
- uiParams.analyzeSize.iWidth = config.frame.width;
443
- engine.setUIParams(uiParams);
444
- return true;
445
- }
446
- },
447
- recognition: function (target, params) {
448
- const engine = target.instance;
449
- if (engine) {
450
- try {
451
- const data = params.data;
452
- const heapInfo = putOnHeap(data);
453
- const result = engine.run(
454
- heapInfo.byteOffset,
455
- heapInfo.length,
456
- config.frame.width,
457
- config.frame.height
458
- );
459
- self.EngineLib._free(heapInfo.dataPtr);
460
- return result;
461
- } catch (error) {
462
- // console.warn(error);
463
- // console.warn('[Recognition Error]: ' + error?.message);
464
- return null;
465
- }
466
- }
467
- console.warn('engine not initialized');
468
- },
469
- getParams: function (target) {
470
- return target.instance.getParams();
471
- },
472
- setParams: function (target, params) {
473
- return target.instance.setParams(params.params);
474
- },
475
- getDebugImage: function (target, params) {
476
- const data = params.data;
477
- const heapInfo = putOnHeap(data);
478
- let imageData;
479
- const pointer = target.instance.getDebugImage(
480
- heapInfo.byteOffset,
481
- heapInfo.length,
482
- config.frame.width,
483
- config.frame.height
484
- );
485
- self.EngineLib._free(heapInfo.dataPtr);
486
- if (pointer) {
487
- imageData = self.EngineLib.HEAPU8.slice(
488
- pointer,
489
- pointer + config.frame.width * config.frame.height * 4
490
- );
491
- self.EngineLib._free(pointer);
492
- }
493
- return imageData;
494
- },
495
- destroy: function (target) {
496
- if (target.instance) {
497
- target.instance.delete();
498
- target.instance = null;
499
- }
500
- if (target.sessionUsed) {
501
- target.sessionUsed.forEach((name) => {
502
- if (modelSession[name]) {
503
- self.EngineLib.deleteSession(modelSession[name]);
504
- modelSession[name] = null;
505
- }
506
- });
507
- target.sessionUsed = [];
508
- }
509
- },
510
- getJsonReport: function (target) {
511
- return target?.instance?.getJsonReport();
512
- },
513
461
  };
514
462
 
515
463
  self.Core = {
516
- setConfig: async function (config) {
464
+ async setConfig(config) {
517
465
  self.config = {
518
466
  ...self.config,
519
467
  ...config,
520
468
  };
521
469
  return true;
522
470
  },
523
- loadEngine: async function ({ engineJsContent, engineWasmContent }) {
471
+ async loadEngine({ engineJsContent, engineWasmContent }) {
524
472
  return await loadWasm({ engineJsContent, engineWasmContent });
525
473
  },
526
- verify: async function (params) {
474
+ async verify(params) {
527
475
  for (let index = 0; index < 20; index++) {
528
476
  if (self.EngineLib) {
529
477
  let result = self.EngineLib.verifySDK(params.cert, params.authToken);
530
478
  return result.constructor.name;
531
479
  }
532
- await waitTime(500);
533
480
  }
534
481
  return false;
535
482
  },
483
+ checkEnumConsistency(enums) {
484
+ const problem = [];
485
+ for (const [enumName, enumDef] of Object.entries(enums)) {
486
+ const actualEnumDef = self.EngineLib[enumName];
487
+ const actualEnumValues = actualEnumDef?.values ?? {};
488
+ const actualEnumMap = Object.fromEntries(
489
+ Object.values(actualEnumValues).map((enumValue) => [
490
+ enumValue.constructor.name,
491
+ enumValue.value,
492
+ ])
493
+ );
494
+
495
+ for (const [key, engineKey] of Object.entries(enumDef)) {
496
+ const actualValue = actualEnumMap[engineKey];
497
+ if (typeof actualValue === 'undefined') {
498
+ problem.push({ enumName, key, engineKey, actualEnumMap });
499
+ }
500
+ }
501
+ }
502
+ return problem;
503
+ },
536
504
  };
537
505
 
538
506
  addEventListener(
539
507
  'message',
540
- async function ({ data }) {
508
+ async function onWorkerMessage({ data }) {
541
509
  const { module, command, id, value } = data;
542
510
  const fn = self[module][command];
543
511
  if (fn) {
544
512
  // console.log(`call ${module}.${command} :`, value);
545
- const result = await fn(value);
513
+ const result = await fn.call(self[module], value);
546
514
  // console.log(`worker return value for ${command}:`, result);
547
515
  postMessage({
548
516
  module,
@@ -563,60 +531,6 @@
563
531
  },
564
532
  };
565
533
 
566
- async function loadModel(modelInfo) {
567
- const { name, code } = modelInfo;
568
- const modelData = await fetchModel(code);
569
- console.log(modelData);
570
- try {
571
- const FS = self.EngineLib.FS;
572
- FS.mkdir(name);
573
- FS.mount(
574
- FS.filesystems.WORKERFS,
575
- {
576
- blobs: [
577
- {
578
- name,
579
- data: modelData,
580
- },
581
- ],
582
- },
583
- '/' + name
584
- );
585
- } catch (error) {
586
- if (error?.errno === 20) {
587
- // File Exist
588
- return `/${name}/${name}`;
589
- } else {
590
- throw error;
591
- }
592
- }
593
-
594
- return `/${name}/${name}`;
595
- }
596
-
597
- async function loadModels(modelString) {
598
- const start = performance.now();
599
- const resp = await fetch(
600
- self.config.apiBaseUrl + '/api/model-management/v1/model?' + modelString,
601
- {
602
- headers: {
603
- Authorization: 'Bearer ' + self.config.token,
604
- },
605
- }
606
- );
607
- if (!resp.ok) {
608
- throw new Error('[HTTP Error] Status: ' + resp.status);
609
- }
610
- const result = await resp.json();
611
- const modelPath = [];
612
- for (let i = 0; i < result.models.length; i++) {
613
- modelPath.push(await loadModel(result.models[i]));
614
- }
615
- const end = performance.now();
616
- // console.log('Load Model Time: ', +end - start + ' ms');
617
- return modelPath;
618
- }
619
-
620
534
  function putOnHeap(data) {
621
535
  const Module = self.EngineLib;
622
536
  const uint8ArrData = new Uint8Array(data);
@@ -633,7 +547,7 @@
633
547
  };
634
548
  }
635
549
 
636
- async function waitTime(ms) {
550
+ function waitTime(ms) {
637
551
  return new Promise((res) => {
638
552
  setTimeout(() => {
639
553
  res(true);