@ekyc_qoobiss/qbs-ect-cmp 1.2.8 → 1.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,495 @@
1
- import { r as registerInstance, c as createEvent, h, g as getElement } from './index-5d6f9123.js';
2
- import { A as ApiCall, a as AgreementCheckValues, b as AgreementInfoValues, s as state, F as FlowStatus, c as createCommonjsModule, g as getDefaultExportFromCjs, G as GlobalValues, I as IdCaptureValues, S as SelfieCaptureValues, C as CompleteValues, H as HowToValues, d as SessionKeys, L as LandingValues, P as PhoneValidationValues, e as CodeValidationValues } from './_commonjsHelpers-d06997a2.js';
1
+ import { g as getRenderingRef, f as forceUpdate, r as registerInstance, c as createEvent, h, a as getElement } from './index-9d69e511.js';
2
+
3
+ var OrderStatuses;
4
+ (function (OrderStatuses) {
5
+ OrderStatuses[OrderStatuses["Capturing"] = 0] = "Capturing";
6
+ OrderStatuses[OrderStatuses["FinishedCapturing"] = 1] = "FinishedCapturing";
7
+ OrderStatuses[OrderStatuses["Waiting"] = 2] = "Waiting";
8
+ OrderStatuses[OrderStatuses["NotFound"] = 3] = "NotFound";
9
+ })(OrderStatuses || (OrderStatuses = {}));
10
+
11
+ const appendToMap = (map, propName, value) => {
12
+ const items = map.get(propName);
13
+ if (!items) {
14
+ map.set(propName, [value]);
15
+ }
16
+ else if (!items.includes(value)) {
17
+ items.push(value);
18
+ }
19
+ };
20
+ const debounce = (fn, ms) => {
21
+ let timeoutId;
22
+ return (...args) => {
23
+ if (timeoutId) {
24
+ clearTimeout(timeoutId);
25
+ }
26
+ timeoutId = setTimeout(() => {
27
+ timeoutId = 0;
28
+ fn(...args);
29
+ }, ms);
30
+ };
31
+ };
32
+
33
+ /**
34
+ * Check if a possible element isConnected.
35
+ * The property might not be there, so we check for it.
36
+ *
37
+ * We want it to return true if isConnected is not a property,
38
+ * otherwise we would remove these elements and would not update.
39
+ *
40
+ * Better leak in Edge than to be useless.
41
+ */
42
+ const isConnected = (maybeElement) => !('isConnected' in maybeElement) || maybeElement.isConnected;
43
+ const cleanupElements = debounce((map) => {
44
+ for (let key of map.keys()) {
45
+ map.set(key, map.get(key).filter(isConnected));
46
+ }
47
+ }, 2000);
48
+ const stencilSubscription = () => {
49
+ if (typeof getRenderingRef !== 'function') {
50
+ // If we are not in a stencil project, we do nothing.
51
+ // This function is not really exported by @stencil/core.
52
+ return {};
53
+ }
54
+ const elmsToUpdate = new Map();
55
+ return {
56
+ dispose: () => elmsToUpdate.clear(),
57
+ get: (propName) => {
58
+ const elm = getRenderingRef();
59
+ if (elm) {
60
+ appendToMap(elmsToUpdate, propName, elm);
61
+ }
62
+ },
63
+ set: (propName) => {
64
+ const elements = elmsToUpdate.get(propName);
65
+ if (elements) {
66
+ elmsToUpdate.set(propName, elements.filter(forceUpdate));
67
+ }
68
+ cleanupElements(elmsToUpdate);
69
+ },
70
+ reset: () => {
71
+ elmsToUpdate.forEach((elms) => elms.forEach(forceUpdate));
72
+ cleanupElements(elmsToUpdate);
73
+ },
74
+ };
75
+ };
76
+
77
+ const unwrap = (val) => (typeof val === 'function' ? val() : val);
78
+ const createObservableMap = (defaultState, shouldUpdate = (a, b) => a !== b) => {
79
+ const unwrappedState = unwrap(defaultState);
80
+ let states = new Map(Object.entries(unwrappedState !== null && unwrappedState !== void 0 ? unwrappedState : {}));
81
+ const handlers = {
82
+ dispose: [],
83
+ get: [],
84
+ set: [],
85
+ reset: [],
86
+ };
87
+ const reset = () => {
88
+ var _a;
89
+ // When resetting the state, the default state may be a function - unwrap it to invoke it.
90
+ // otherwise, the state won't be properly reset
91
+ states = new Map(Object.entries((_a = unwrap(defaultState)) !== null && _a !== void 0 ? _a : {}));
92
+ handlers.reset.forEach((cb) => cb());
93
+ };
94
+ const dispose = () => {
95
+ // Call first dispose as resetting the state would
96
+ // cause less updates ;)
97
+ handlers.dispose.forEach((cb) => cb());
98
+ reset();
99
+ };
100
+ const get = (propName) => {
101
+ handlers.get.forEach((cb) => cb(propName));
102
+ return states.get(propName);
103
+ };
104
+ const set = (propName, value) => {
105
+ const oldValue = states.get(propName);
106
+ if (shouldUpdate(value, oldValue, propName)) {
107
+ states.set(propName, value);
108
+ handlers.set.forEach((cb) => cb(propName, value, oldValue));
109
+ }
110
+ };
111
+ const state = (typeof Proxy === 'undefined'
112
+ ? {}
113
+ : new Proxy(unwrappedState, {
114
+ get(_, propName) {
115
+ return get(propName);
116
+ },
117
+ ownKeys(_) {
118
+ return Array.from(states.keys());
119
+ },
120
+ getOwnPropertyDescriptor() {
121
+ return {
122
+ enumerable: true,
123
+ configurable: true,
124
+ };
125
+ },
126
+ has(_, propName) {
127
+ return states.has(propName);
128
+ },
129
+ set(_, propName, value) {
130
+ set(propName, value);
131
+ return true;
132
+ },
133
+ }));
134
+ const on = (eventName, callback) => {
135
+ handlers[eventName].push(callback);
136
+ return () => {
137
+ removeFromArray(handlers[eventName], callback);
138
+ };
139
+ };
140
+ const onChange = (propName, cb) => {
141
+ const unSet = on('set', (key, newValue) => {
142
+ if (key === propName) {
143
+ cb(newValue);
144
+ }
145
+ });
146
+ // We need to unwrap the defaultState because it might be a function.
147
+ // Otherwise we might not be sending the right reset value.
148
+ const unReset = on('reset', () => cb(unwrap(defaultState)[propName]));
149
+ return () => {
150
+ unSet();
151
+ unReset();
152
+ };
153
+ };
154
+ const use = (...subscriptions) => {
155
+ const unsubs = subscriptions.reduce((unsubs, subscription) => {
156
+ if (subscription.set) {
157
+ unsubs.push(on('set', subscription.set));
158
+ }
159
+ if (subscription.get) {
160
+ unsubs.push(on('get', subscription.get));
161
+ }
162
+ if (subscription.reset) {
163
+ unsubs.push(on('reset', subscription.reset));
164
+ }
165
+ if (subscription.dispose) {
166
+ unsubs.push(on('dispose', subscription.dispose));
167
+ }
168
+ return unsubs;
169
+ }, []);
170
+ return () => unsubs.forEach((unsub) => unsub());
171
+ };
172
+ const forceUpdate = (key) => {
173
+ const oldValue = states.get(key);
174
+ handlers.set.forEach((cb) => cb(key, oldValue, oldValue));
175
+ };
176
+ return {
177
+ state,
178
+ get,
179
+ set,
180
+ on,
181
+ onChange,
182
+ use,
183
+ dispose,
184
+ reset,
185
+ forceUpdate,
186
+ };
187
+ };
188
+ const removeFromArray = (array, item) => {
189
+ const index = array.indexOf(item);
190
+ if (index >= 0) {
191
+ array[index] = array[array.length - 1];
192
+ array.length--;
193
+ }
194
+ };
195
+
196
+ const createStore = (defaultState, shouldUpdate) => {
197
+ const map = createObservableMap(defaultState, shouldUpdate);
198
+ map.use(stencilSubscription());
199
+ return map;
200
+ };
201
+
202
+ var FlowStatus;
203
+ (function (FlowStatus) {
204
+ FlowStatus[FlowStatus["LANDING"] = 0] = "LANDING";
205
+ FlowStatus[FlowStatus["AGREEMENT"] = 1] = "AGREEMENT";
206
+ FlowStatus[FlowStatus["PHONE"] = 2] = "PHONE";
207
+ FlowStatus[FlowStatus["CODE"] = 3] = "CODE";
208
+ FlowStatus[FlowStatus["CODEERROR"] = 4] = "CODEERROR";
209
+ FlowStatus[FlowStatus["ID"] = 5] = "ID";
210
+ FlowStatus[FlowStatus["LIVENESS"] = 6] = "LIVENESS";
211
+ FlowStatus[FlowStatus["COMPLETE"] = 7] = "COMPLETE";
212
+ FlowStatus[FlowStatus["ERROREND"] = 8] = "ERROREND";
213
+ })(FlowStatus || (FlowStatus = {}));
214
+
215
+ class GlobalValues {
216
+ }
217
+ GlobalValues.FooterText = 'Qoobiss eKYC';
218
+ GlobalValues.VideoLenght = 3100;
219
+ class HowToValues extends GlobalValues {
220
+ }
221
+ HowToValues.IdTitile = 'Prezintă actul tău de identitate';
222
+ HowToValues.IdSubTitileFace = 'Este necesară captarea actului de identitate. Urmează intrucțiunile ce vor fi afișate pe ecran.';
223
+ HowToValues.IdSubTitileBack = 'Este necesară captarea actului de identitate. Urmează intrucțiunile ce vor fi afișate pe ecran.';
224
+ HowToValues.IdButton = 'Sunt gata!';
225
+ HowToValues.SelfieTitile = 'Validare video';
226
+ HowToValues.SelfieSubTitile = 'Este necesară realizarea unei înregistrări video. Respectă intrucțiunile ce vor fi afișate pe ecran.';
227
+ HowToValues.SelfieButton = 'Sunt gata!';
228
+ class LandingValues extends GlobalValues {
229
+ }
230
+ LandingValues.Title = 'Validarea identității la distanță este o procedură simplă și rapidă';
231
+ LandingValues.Description = 'Asigură-te că ai:';
232
+ LandingValues.IdInfo = 'Actul de identitate, în original';
233
+ LandingValues.DeviceInfo = 'Un telefon mobil sau un calculator cu camera web';
234
+ LandingValues.SmsInfo = 'Acces la un telefon mobil ce permite primirea de mesaje SMS';
235
+ LandingValues.Warning = 'ATENȚIE! În cadrul acestui proces se poate utiliza doar cartea de identitate Românească.';
236
+ LandingValues.WarningMd = 'ATENȚIE! In cadrul acestui proces se pot utiliza doar buletinele de identitate din Republica Moldova.';
237
+ LandingValues.Terms = 'Prin continuarea procesului, confirmi că ai citit termenii de utilizare și ești de acord cu aceștia.';
238
+ LandingValues.Button = 'Am înțeles';
239
+ LandingValues.ButtonLeave = 'Nu sunt pregătit';
240
+ class PhoneValidationValues extends GlobalValues {
241
+ }
242
+ PhoneValidationValues.Title = 'Este necesar să validăm numărul tău de telefon';
243
+ PhoneValidationValues.Description = 'Introdu mai jos numarul tau de telefon:';
244
+ PhoneValidationValues.Button = 'Trimite SMS de verificare';
245
+ PhoneValidationValues.Label = 'Numarul tau de telefon';
246
+ class CodeValidationValues extends GlobalValues {
247
+ }
248
+ CodeValidationValues.Title = 'Introdu codul de validare primit prin sms:';
249
+ CodeValidationValues.Description = ' ';
250
+ CodeValidationValues.Button = 'Validează';
251
+ CodeValidationValues.Error = 'Codul introdus nu este valid. Asigură-te că îl introduci corect';
252
+ class CompleteValues extends GlobalValues {
253
+ }
254
+ CompleteValues.Title = 'Procesul a fost finalizat.';
255
+ CompleteValues.Description = 'Vei fi redirecționat în câteva momente.';
256
+ CompleteValues.Message = 'Îți mulțumim!';
257
+ class SessionKeys {
258
+ }
259
+ SessionKeys.FlowStatusKey = 'qbs-ect-flowstatus';
260
+ SessionKeys.RequestIdKey = 'qbs-ect-requestid';
261
+ SessionKeys.TokenKey = 'qbs-ect-token';
262
+ SessionKeys.InitialisedKey = 'qbs-ect-initialised';
263
+ SessionKeys.HasIdBackKey = 'qbs-ect-has-id-back';
264
+ SessionKeys.AgreementValidationKey = 'qbs-ect-agreement-validation';
265
+ SessionKeys.PhoneValidationKey = 'qbs-ect-phone-validation';
266
+ class IdCaptureValues extends GlobalValues {
267
+ }
268
+ IdCaptureValues.Button = 'Încerc din nou';
269
+ IdCaptureValues.Title = 'Încadrează actul de identitate în chenarul de pe ecran.';
270
+ IdCaptureValues.TitleBack = 'Încadrează spatele actului de identitate în chenarul de pe ecran.';
271
+ IdCaptureValues.TtileRotate = 'Întoarce actul de identitate.';
272
+ IdCaptureValues.Error = 'Procesul a eșuat. Te rugăm să respecți întocmai instrucțiunile de pe ecran. Ai grijă să încadrezi integral actul în chenraul de pe ecran și să nu apară reflexii de lumină pe suprafața acestuia.';
273
+ IdCaptureValues.IDPoseMapping = {
274
+ 0: '',
275
+ 1: 'Înclină actul de identitate spre spate.',
276
+ 2: '',
277
+ 3: '',
278
+ 4: '',
279
+ };
280
+ IdCaptureValues.IDPoseDemoMapping = {
281
+ 0: 'https://ekyc.blob.core.windows.net/$web/animations/id/id_front.mp4',
282
+ 1: 'https://ekyc.blob.core.windows.net/$web/animations/id/id_front_tilt.mp4',
283
+ 2: 'https://ekyc.blob.core.windows.net/$web/animations/id/id_rotate.mp4',
284
+ 3: 'https://ekyc.blob.core.windows.net/$web/animations/id/id_back.mp4',
285
+ 4: 'https://ekyc.blob.core.windows.net/$web/animations/id/id_back_tilt.mp4',
286
+ };
287
+ IdCaptureValues.Loading = 'Transferăm datele. Asteptați...';
288
+ class SelfieCaptureValues extends GlobalValues {
289
+ }
290
+ SelfieCaptureValues.Title = 'Încadrează fața în chenarul de pe ecran.';
291
+ SelfieCaptureValues.FinalTitle = 'Îndreaptă capul și încadrează fața în chenarul de pe ecran.';
292
+ SelfieCaptureValues.Error = 'Procesul a eșuat. Te rugăm să respecți întocmai instrucțiunile de pe ecran.';
293
+ SelfieCaptureValues.Loading = 'Transferăm datele. Asteptați...';
294
+ SelfieCaptureValues.FacePoseMapping = {
295
+ 0: 'Întoarce capul spre stânga.',
296
+ 1: 'Întoarce capul spre dreapta.',
297
+ 2: 'Înclină capul spre spate.',
298
+ 3: 'Înclină capul în față.',
299
+ // 4: 'Înclină capul spre stânga.',
300
+ // 5: 'Înclină capul spre dreapta.',
301
+ 4: '',
302
+ };
303
+ SelfieCaptureValues.FacePoseDemoMapping = {
304
+ 0: 'https://ekyc.blob.core.windows.net/$web/animations/selfie/selfie_rotate_left.mp4',
305
+ 1: 'https://ekyc.blob.core.windows.net/$web/animations/selfie/selfie_rotate_right.mp4',
306
+ 2: 'https://ekyc.blob.core.windows.net/$web/animations/selfie/selfie_tilt_back.mp4',
307
+ 3: 'https://ekyc.blob.core.windows.net/$web/animations/selfie/selfie_tilt_front.mp4',
308
+ // 4: 'https://ekyc.blob.core.windows.net/$web/animations/selfie/selfie_tilt_left.mp4',
309
+ // 5: 'https://ekyc.blob.core.windows.net/$web/animations/selfie/selfie_tilt_right.mp4',
310
+ 4: 'https://ekyc.blob.core.windows.net/$web/animations/selfie/selfie_main.mp4',
311
+ };
312
+ class AgreementInfoValues extends GlobalValues {
313
+ }
314
+ AgreementInfoValues.Title = 'Pentru începerea identificării avem nevoie de acordurile tale:';
315
+ AgreementInfoValues.Button = 'Încep identificarea';
316
+ AgreementInfoValues.Terms = 'Am luat la cunoștință și sunt de acord cu Termenii și condițiile generale de utilizare';
317
+ AgreementInfoValues.Agreement = 'Îmi exprim acordul pentru prelucrarea datelor cu caracter personal';
318
+ class AgreementCheckValues extends GlobalValues {
319
+ }
320
+ AgreementCheckValues.ButtonYes = 'Sunt de acord';
321
+ AgreementCheckValues.ButtonNo = 'Nu sunt de acord';
322
+ class ApiUrls {
323
+ constructor() {
324
+ this.uriEnv = '/';
325
+ this.uriEnv = state.environment == 'QA' ? '/dev_' : '/';
326
+ this.OtpSend = this.uriEnv + 'validation/otp/send';
327
+ this.OtpCheck = this.uriEnv + 'validation/otp/check';
328
+ this.IdentityInsert = this.uriEnv + 'validation/identity/insert';
329
+ this.UploadCapture = this.uriEnv + 'validation/upload/capture';
330
+ this.GetAgreement = this.uriEnv + 'validation/agreement/content';
331
+ this.GenerateAgreement = this.uriEnv + 'validation/agreement/generate';
332
+ this.SendLink = this.uriEnv + 'validation/otp/sendlink';
333
+ this.GetStatus = this.uriEnv + 'validation/identity/status';
334
+ this.AddLog = this.uriEnv + 'validation/logs/add';
335
+ }
336
+ }
337
+ class MobileRedirectValues extends GlobalValues {
338
+ }
339
+ MobileRedirectValues.InfoTop = 'Pentru a continua scanați codul de mai jos cu un smartphone.';
340
+ MobileRedirectValues.InfoBottom = 'Sau introduceți un număr de telefon pentru a primi link-ul pe smartphone.';
341
+ MobileRedirectValues.Validation = 'Număr de telefon invalid!';
342
+ MobileRedirectValues.InfoWaiting = 'Așteptăm finalizarea procesului pe smartphone.';
343
+
344
+ const { state, onChange } = createStore({
345
+ flowStatus: FlowStatus.LANDING,
346
+ environment: 'PROD',
347
+ requestId: '',
348
+ redirectId: '',
349
+ initialised: false,
350
+ token: '',
351
+ cameraIds: [],
352
+ cameraId: '',
353
+ hasIdBack: false,
354
+ agreementsValidation: true,
355
+ phoneValidation: true,
356
+ phoneNumber: '',
357
+ apiBaseUrl: 'https://apiro.id-kyc.com',
358
+ });
359
+ onChange('flowStatus', value => {
360
+ sessionStorage.setItem(SessionKeys.FlowStatusKey, FlowStatus[value]);
361
+ });
362
+ onChange('token', value => {
363
+ sessionStorage.setItem(SessionKeys.TokenKey, value);
364
+ });
365
+ onChange('requestId', value => {
366
+ console.log('Store requestId changed to ' + value);
367
+ sessionStorage.setItem(SessionKeys.RequestIdKey, value);
368
+ });
369
+ onChange('initialised', value => {
370
+ sessionStorage.setItem(SessionKeys.InitialisedKey, String(value));
371
+ });
372
+ onChange('hasIdBack', value => {
373
+ sessionStorage.setItem(SessionKeys.HasIdBackKey, String(value));
374
+ });
375
+ onChange('agreementsValidation', value => {
376
+ sessionStorage.setItem(SessionKeys.AgreementValidationKey, String(value));
377
+ });
378
+ onChange('phoneValidation', value => {
379
+ sessionStorage.setItem(SessionKeys.PhoneValidationKey, String(value));
380
+ });
381
+
382
+ class ApiCall {
383
+ constructor() {
384
+ this.toBase64 = (file) => new Promise((resolve, reject) => {
385
+ const reader = new FileReader();
386
+ reader.readAsDataURL(file);
387
+ reader.onload = () => resolve(reader.result);
388
+ reader.onerror = error => reject(error);
389
+ });
390
+ this.urls = new ApiUrls();
391
+ }
392
+ async http(request) {
393
+ const response = await fetch(request);
394
+ if (!response.ok) {
395
+ throw new Error(response.statusText);
396
+ }
397
+ try {
398
+ // may error if there is no body
399
+ return await response.json();
400
+ }
401
+ catch (ex) {
402
+ throw new Error('No json found in response ' + ex);
403
+ }
404
+ }
405
+ async post(url, data) {
406
+ return await this.http(new Request(state.apiBaseUrl + url, {
407
+ method: 'POST',
408
+ body: data,
409
+ headers: {
410
+ 'Content-Type': 'application/json',
411
+ 'Authorization': 'IDKYC-TOKEN ' + state.token,
412
+ },
413
+ }));
414
+ }
415
+ async get(url) {
416
+ return await this.http(new Request(state.apiBaseUrl + url, {
417
+ method: 'GET',
418
+ headers: {
419
+ 'Content-Type': 'application/json',
420
+ 'Authorization': 'IDKYC-TOKEN ' + state.token,
421
+ },
422
+ }));
423
+ }
424
+ async SendOTPCode(requestId, phoneNumber) {
425
+ let data = { requestId: requestId, phone: phoneNumber };
426
+ let jsonResp = await this.post(this.urls.OtpSend, JSON.stringify(data));
427
+ return jsonResp.sent;
428
+ }
429
+ async CheckOTPCode(requestId, otpCode) {
430
+ let data = { requestId: requestId, otp: otpCode };
431
+ let jsonResp = await this.post(this.urls.OtpCheck, JSON.stringify(data));
432
+ return jsonResp.valid;
433
+ }
434
+ async AddIdentificationRequest(deviceInfo) {
435
+ let data = {
436
+ requestId: state.requestId,
437
+ clientDeviceInfo: JSON.stringify(deviceInfo),
438
+ redirectId: state.redirectId,
439
+ phoneNumber: state.phoneNumber,
440
+ };
441
+ let jsonResp = await this.post(this.urls.IdentityInsert, JSON.stringify(data));
442
+ if (state.requestId == '') {
443
+ state.requestId = jsonResp.requestId;
444
+ }
445
+ state.hasIdBack = jsonResp.hasIdBack;
446
+ state.agreementsValidation = jsonResp.agreementsValidation;
447
+ state.phoneValidation = jsonResp.phoneValidation;
448
+ state.phoneNumber = jsonResp.phoneNumber;
449
+ return true;
450
+ }
451
+ async UploadFileForRequestB64(requestId, type, file) {
452
+ let data = {
453
+ requestId: requestId,
454
+ type: type,
455
+ data: await this.toBase64(file),
456
+ };
457
+ let respJson = await this.post(this.urls.UploadCapture, JSON.stringify(data));
458
+ if (!state.hasIdBack && type == 'IdFront') {
459
+ return respJson.isValid;
460
+ }
461
+ if (state.hasIdBack && type == 'IdBack') {
462
+ return respJson.isValid;
463
+ }
464
+ return true;
465
+ }
466
+ async GetAgreement(agreementType) {
467
+ let resp = await this.get(this.urls.GetAgreement + '?type=' + agreementType + '&requestId=' + state.requestId);
468
+ return resp.htmlText;
469
+ }
470
+ async GenerateAgreement(agreementType) {
471
+ let data = { requestId: state.requestId, documentType: agreementType };
472
+ let resp = await this.post(this.urls.GenerateAgreement, JSON.stringify(data));
473
+ return resp.generation;
474
+ }
475
+ async GetStatus(requestId) {
476
+ let resp = await this.get(this.urls.GetStatus + '?orderId=' + requestId);
477
+ return OrderStatuses[resp.status];
478
+ }
479
+ async SendLink(link, phoneNumber) {
480
+ let data = { requestId: state.requestId, link: link, phoneNumber: phoneNumber };
481
+ let resp = await this.post(this.urls.SendLink, JSON.stringify(data));
482
+ return resp.sent;
483
+ }
484
+ async AddLog(error) {
485
+ try {
486
+ let data = { requestId: state.requestId, action: FlowStatus[state.flowStatus], message: JSON.stringify(error !== null && error !== void 0 ? error : 'no error data') };
487
+ let result = await this.post(this.urls.AddLog, JSON.stringify(data));
488
+ return result.saved;
489
+ }
490
+ catch (_a) { }
491
+ }
492
+ }
3
493
 
4
494
  const agreementCheckCss = "";
5
495
 
@@ -76,6 +566,24 @@ const AgreementInfo = class {
76
566
  };
77
567
  AgreementInfo.style = agreementInfoCss;
78
568
 
569
+ function getDefaultExportFromCjs (x) {
570
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
571
+ }
572
+
573
+ function createCommonjsModule(fn, basedir, module) {
574
+ return module = {
575
+ path: basedir,
576
+ exports: {},
577
+ require: function (path, base) {
578
+ return commonjsRequire();
579
+ }
580
+ }, fn(module, module.exports), module.exports;
581
+ }
582
+
583
+ function commonjsRequire () {
584
+ throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
585
+ }
586
+
79
587
  var ml5_min = createCommonjsModule(function (module, exports) {
80
588
  !function(t,e){module.exports=e();}(window,function(){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:r});},n.r=function(t){Object.defineProperty(t,"__esModule",{value:!0});},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="/",n(n.s=581)}([function(t,e,n){n.r(e),function(t,r,i,o){n.d(e,"AdadeltaOptimizer",function(){return Dh}),n.d(e,"AdagradOptimizer",function(){return Fh}),n.d(e,"AdamOptimizer",function(){return Th}),n.d(e,"AdamaxOptimizer",function(){return Nh}),n.d(e,"Add",function(){return Er}),n.d(e,"AddN",function(){return Cr}),n.d(e,"BroadcastTo",function(){return Tr}),n.d(e,"DataStorage",function(){return ho}),n.d(e,"Div",function(){return Ar}),n.d(e,"ENV",function(){return h}),n.d(e,"Environment",function(){return l}),n.d(e,"FromPixels",function(){return jr}),n.d(e,"FusedBatchNorm",function(){return Or}),n.d(e,"Identity",function(){return Ir}),n.d(e,"KernelBackend",function(){return po}),n.d(e,"MaxPoolWithArgmax",function(){return Br}),n.d(e,"MomentumOptimizer",function(){return Rh}),n.d(e,"NonMaxSuppressionV5",function(){return Fr}),n.d(e,"OneHot",function(){return Nr}),n.d(e,"Optimizer",function(){return Sh}),n.d(e,"PadV2",function(){return Mr}),n.d(e,"RMSPropOptimizer",function(){return Mh}),n.d(e,"Rank",function(){return Ot}),n.d(e,"Reduction",function(){return pl}),n.d(e,"SGDOptimizer",function(){return Ih}),n.d(e,"Square",function(){return Sr}),n.d(e,"SquaredDifference",function(){return _r}),n.d(e,"Tensor",function(){return At}),n.d(e,"TensorBuffer",function(){return wt}),n.d(e,"Tile",function(){return Rr}),n.d(e,"Transpose",function(){return Dr}),n.d(e,"Variable",function(){return Tt}),n.d(e,"abs",function(){return Wr}),n.d(e,"acos",function(){return Vr}),n.d(e,"acosh",function(){return qr}),n.d(e,"add",function(){return Pr}),n.d(e,"addN",function(){return Ps}),n.d(e,"addStrict",function(){return ki}),n.d(e,"all",function(){return Ic}),n.d(e,"any",function(){return Rc}),n.d(e,"argMax",function(){return Mc}),n.d(e,"argMin",function(){return jc}),n.d(e,"asin",function(){return $r}),n.d(e,"asinh",function(){return Hr}),n.d(e,"atan",function(){return Gr}),n.d(e,"atan2",function(){return Ei}),n.d(e,"atanh",function(){return Kr}),n.d(e,"avgPool",function(){return kc}),n.d(e,"avgPool3d",function(){return Ac}),n.d(e,"backend",function(){return mn}),n.d(e,"backend_util",function(){return To}),n.d(e,"basicLSTMCell",function(){return Qc}),n.d(e,"batchNorm",function(){return qs}),n.d(e,"batchNorm2d",function(){return Gs}),n.d(e,"batchNorm3d",function(){return Ys}),n.d(e,"batchNorm4d",function(){return Zs}),n.d(e,"batchNormalization",function(){return Vs}),n.d(e,"batchNormalization2d",function(){return Hs}),n.d(e,"batchNormalization3d",function(){return Xs}),n.d(e,"batchNormalization4d",function(){return Qs}),n.d(e,"batchToSpaceND",function(){return sr}),n.d(e,"booleanMaskAsync",function(){return Yu}),n.d(e,"broadcastTo",function(){return tu}),n.d(e,"browser",function(){return wh}),n.d(e,"buffer",function(){return or}),n.d(e,"cast",function(){return ur}),n.d(e,"ceil",function(){return Xr}),n.d(e,"clipByValue",function(){return Yr}),n.d(e,"clone",function(){return eu}),n.d(e,"complex",function(){return In}),n.d(e,"concat",function(){return Zn}),n.d(e,"concat1d",function(){return tr}),n.d(e,"concat2d",function(){return er}),n.d(e,"concat3d",function(){return nr}),n.d(e,"concat4d",function(){return rr}),n.d(e,"conv1d",function(){return tc}),n.d(e,"conv2d",function(){return ec}),n.d(e,"conv2dTranspose",function(){return cc}),n.d(e,"conv3d",function(){return nc}),n.d(e,"conv3dTranspose",function(){return lc}),n.d(e,"cos",function(){return Jr}),n.d(e,"cosh",function(){return Qr}),n.d(e,"cumsum",function(){return cr}),n.d(e,"customGrad",function(){return so}),n.d(e,"deprecationWarn",function(){return Qe}),n.d(e,"depthToSpace",function(){return lr}),n.d(e,"depthwiseConv2d",function(){return oc}),n.d(e,"diag",function(){return fl}),n.d(e,"disableDeprecationWarnings",function(){return Je}),n.d(e,"dispose",function(){return on}),n.d(e,"disposeVariables",function(){return Ze}),n.d(e,"div",function(){return Li}),n.d(e,"divNoNan",function(){return uu}),n.d(e,"divStrict",function(){return Ci}),n.d(e,"dot",function(){return hc}),n.d(e,"dropout",function(){return hl}),n.d(e,"elu",function(){return qc}),n.d(e,"enableDebugMode",function(){return Ye}),n.d(e,"enableProdMode",function(){return Xe}),n.d(e,"engine",function(){return tn}),n.d(e,"env",function(){return f}),n.d(e,"equal",function(){return Ru}),n.d(e,"equalStrict",function(){return Mu}),n.d(e,"erf",function(){return Zr}),n.d(e,"exp",function(){return ti}),n.d(e,"expandDims",function(){return fr}),n.d(e,"expm1",function(){return ei}),n.d(e,"eye",function(){return lu}),n.d(e,"fft",function(){return il}),n.d(e,"fill",function(){return Kn}),n.d(e,"findBackend",function(){return hn}),n.d(e,"findBackendFactory",function(){return dn}),n.d(e,"floor",function(){return ni}),n.d(e,"floorDiv",function(){return Ai}),n.d(e,"frame",function(){return vl}),n.d(e,"fused",function(){return Yl}),n.d(e,"gather",function(){return Ku}),n.d(e,"gatherND",function(){return ll}),n.d(e,"gather_util",function(){return Ui}),n.d(e,"getBackend",function(){return ln}),n.d(e,"getGradient",function(){return g}),n.d(e,"getKernel",function(){return m}),n.d(e,"getKernelsForBackend",function(){return v}),n.d(e,"grad",function(){return no}),n.d(e,"grads",function(){return ro}),n.d(e,"greater",function(){return ju}),n.d(e,"greaterEqual",function(){return Bu}),n.d(e,"greaterEqualStrict",function(){return Pu}),n.d(e,"greaterStrict",function(){return Lu}),n.d(e,"hammingWindow",function(){return gl}),n.d(e,"hannWindow",function(){return ml}),n.d(e,"ifft",function(){return ol}),n.d(e,"imag",function(){return Mn}),n.d(e,"image",function(){return Wl}),n.d(e,"inTopKAsync",function(){return xl}),n.d(e,"io",function(){return vh}),n.d(e,"irfft",function(){return sl}),n.d(e,"isFinite",function(){return pi}),n.d(e,"isInf",function(){return di}),n.d(e,"isNaN",function(){return hi}),n.d(e,"keep",function(){return an}),n.d(e,"leakyRelu",function(){return $c}),n.d(e,"less",function(){return zu}),n.d(e,"lessEqual",function(){return Uu}),n.d(e,"lessEqualStrict",function(){return Wu}),n.d(e,"lessStrict",function(){return Vu}),n.d(e,"linalg",function(){return Ml}),n.d(e,"linspace",function(){return Xn}),n.d(e,"localResponseNormalization",function(){return Yc}),n.d(e,"log",function(){return ri}),n.d(e,"log1p",function(){return ii}),n.d(e,"logSigmoid",function(){return oi}),n.d(e,"logSoftmax",function(){return lo}),n.d(e,"logSumExp",function(){return Bc}),n.d(e,"logicalAnd",function(){return nu}),n.d(e,"logicalNot",function(){return ru}),n.d(e,"logicalOr",function(){return iu}),n.d(e,"logicalXor",function(){return ou}),n.d(e,"losses",function(){return Fl}),n.d(e,"matMul",function(){return fc}),n.d(e,"math",function(){return bh}),n.d(e,"max",function(){return Pc}),n.d(e,"maxPool",function(){return wc}),n.d(e,"maxPool3d",function(){return Cc}),n.d(e,"maxPoolWithArgmax",function(){return Oc}),n.d(e,"maximum",function(){return Oi}),n.d(e,"maximumStrict",function(){return _i}),n.d(e,"mean",function(){return Lc}),n.d(e,"memory",function(){return en}),n.d(e,"min",function(){return zc}),n.d(e,"minimum",function(){return Si}),n.d(e,"minimumStrict",function(){return Di}),n.d(e,"mod",function(){return Fi}),n.d(e,"modStrict",function(){return Ti}),n.d(e,"moments",function(){return Uc}),n.d(e,"movingAverage",function(){return tl}),n.d(e,"mul",function(){return Ni}),n.d(e,"mulStrict",function(){return Ii}),n.d(e,"multiRNNCell",function(){return Zc}),n.d(e,"multinomial",function(){return fu}),n.d(e,"neg",function(){return ai}),n.d(e,"nextFrame",function(){return Lh}),n.d(e,"norm",function(){return Jc}),n.d(e,"notEqual",function(){return qu}),n.d(e,"notEqualStrict",function(){return $u}),n.d(e,"oneHot",function(){return hu}),n.d(e,"ones",function(){return Hn}),n.d(e,"onesLike",function(){return Jn}),n.d(e,"op",function(){return Nn}),n.d(e,"outerProduct",function(){return dc}),n.d(e,"pad",function(){return du}),n.d(e,"pad1d",function(){return pu}),n.d(e,"pad2d",function(){return mu}),n.d(e,"pad3d",function(){return gu}),n.d(e,"pad4d",function(){return vu}),n.d(e,"pool",function(){return Ec}),n.d(e,"pow",function(){return Ri}),n.d(e,"powStrict",function(){return Mi}),n.d(e,"prelu",function(){return Hc}),n.d(e,"print",function(){return ar}),n.d(e,"prod",function(){return Vc}),n.d(e,"profile",function(){return nn}),n.d(e,"rand",function(){return yu}),n.d(e,"randomGamma",function(){return Su}),n.d(e,"randomNormal",function(){return Du}),n.d(e,"randomUniform",function(){return Fu}),n.d(e,"range",function(){return Yn}),n.d(e,"ready",function(){return cn}),n.d(e,"real",function(){return Rn}),n.d(e,"reciprocal",function(){return si}),n.d(e,"registerBackend",function(){return pn}),n.d(e,"registerGradient",function(){return b}),n.d(e,"registerKernel",function(){return y}),n.d(e,"relu",function(){return Gc}),n.d(e,"relu6",function(){return Kc}),n.d(e,"removeBackend",function(){return fn}),n.d(e,"reshape",function(){return hr}),n.d(e,"reverse",function(){return pc}),n.d(e,"reverse1d",function(){return mc}),n.d(e,"reverse2d",function(){return gc}),n.d(e,"reverse3d",function(){return vc}),n.d(e,"reverse4d",function(){return yc}),n.d(e,"rfft",function(){return al}),n.d(e,"round",function(){return ui}),n.d(e,"rsqrt",function(){return ci}),n.d(e,"scalar",function(){return Pn}),n.d(e,"scatterND",function(){return rl}),n.d(e,"scatter_util",function(){return Gi}),n.d(e,"selu",function(){return Xc}),n.d(e,"separableConv2d",function(){return uc}),n.d(e,"serialization",function(){return Ah}),n.d(e,"setBackend",function(){return un}),n.d(e,"setPlatform",function(){return gn}),n.d(e,"setdiff1dAsync",function(){return vr}),n.d(e,"sigmoid",function(){return li}),n.d(e,"sign",function(){return fi}),n.d(e,"signal",function(){return bl}),n.d(e,"sin",function(){return mi}),n.d(e,"sinh",function(){return gi}),n.d(e,"slice",function(){return _c}),n.d(e,"slice1d",function(){return Sc}),n.d(e,"slice2d",function(){return Dc}),n.d(e,"slice3d",function(){return Fc}),n.d(e,"slice4d",function(){return Tc}),n.d(e,"slice_util",function(){return eo}),n.d(e,"softmax",function(){return co}),n.d(e,"softplus",function(){return vi}),n.d(e,"spaceToBatchND",function(){return dr}),n.d(e,"sparseToDense",function(){return cl}),n.d(e,"spectral",function(){return ul}),n.d(e,"split",function(){return ir}),n.d(e,"sqrt",function(){return yi}),n.d(e,"square",function(){return Tu}),n.d(e,"squaredDifference",function(){return Nu}),n.d(e,"squaredDifferenceStrict",function(){return ji}),n.d(e,"squeeze",function(){return pr}),n.d(e,"stack",function(){return mr}),n.d(e,"step",function(){return bi}),n.d(e,"stft",function(){return yl}),n.d(e,"stridedSlice",function(){return el}),n.d(e,"sub",function(){return Bi}),n.d(e,"subStrict",function(){return Pi}),n.d(e,"sum",function(){return Wc}),n.d(e,"sumOutType",function(){return Rt}),n.d(e,"tan",function(){return xi}),n.d(e,"tanh",function(){return wi}),n.d(e,"tensor",function(){return jn}),n.d(e,"tensor1d",function(){return Ln}),n.d(e,"tensor2d",function(){return zn}),n.d(e,"tensor3d",function(){return Un}),n.d(e,"tensor4d",function(){return Wn}),n.d(e,"tensor5d",function(){return Vn}),n.d(e,"tensor6d",function(){return qn}),n.d(e,"tensor_util",function(){return Lt}),n.d(e,"test_util",function(){return Cu}),n.d(e,"tidy",function(){return rn}),n.d(e,"tile",function(){return cu}),n.d(e,"time",function(){return sn}),n.d(e,"topk",function(){return nl}),n.d(e,"train",function(){return Bh}),n.d(e,"transpose",function(){return fo}),n.d(e,"truncatedNormal",function(){return Iu}),n.d(e,"unregisterGradient",function(){return w}),n.d(e,"unregisterKernel",function(){return x}),n.d(e,"unsortedSegmentSum",function(){return Xu}),n.d(e,"unstack",function(){return gr}),n.d(e,"util",function(){return ht}),n.d(e,"valueAndGrad",function(){return io}),n.d(e,"valueAndGrads",function(){return oo}),n.d(e,"variable",function(){return $n}),n.d(e,"variableGrads",function(){return ao}),n.d(e,"version_core",function(){return Oh}),n.d(e,"webgl",function(){return _h}),n.d(e,"where",function(){return au}),n.d(e,"whereAsync",function(){return su}),n.d(e,"zeros",function(){return Gn}),n.d(e,"zerosLike",function(){return Qn});
81
589
  /**
@@ -4634,6 +5142,7 @@ class Events {
4634
5142
  }));
4635
5143
  }
4636
5144
  static flowAborted() {
5145
+ sessionStorage.clear();
4637
5146
  this.callingModule.dispatchEvent(new CustomEvent('ect-aborted', {
4638
5147
  detail: {},
4639
5148
  bubbles: true,
@@ -4660,6 +5169,7 @@ class Events {
4660
5169
  }));
4661
5170
  }
4662
5171
  static tokenExpired() {
5172
+ sessionStorage.clear();
4663
5173
  this.callingModule.dispatchEvent(new CustomEvent('ect-session-expired', {
4664
5174
  detail: {},
4665
5175
  bubbles: true,
@@ -5497,10 +6007,9 @@ const IdentificationComponent = class {
5497
6007
  }
5498
6008
  }
5499
6009
  async onOrderIdChange(newValue, _oldValue) {
5500
- if (state.requestId !== newValue) {
6010
+ if (state.requestId !== newValue && newValue != '') {
5501
6011
  state.requestId = newValue;
5502
6012
  state.initialised = false;
5503
- sessionStorage.clear();
5504
6013
  if (state.flowStatus != FlowStatus.LANDING) {
5505
6014
  state.flowStatus = FlowStatus.LANDING;
5506
6015
  }
@@ -5666,11 +6175,14 @@ const IdentificationComponent = class {
5666
6175
  }
5667
6176
  render() {
5668
6177
  let currentBlock = h("div", null);
5669
- {
6178
+ if (this.device.isMobile) {
5670
6179
  if (state.flowStatus == FlowStatus.LANDING) {
5671
6180
  currentBlock = h("landing-validation", { device: this.device });
5672
6181
  }
5673
6182
  }
6183
+ else {
6184
+ currentBlock = h("mobile-redirect", null);
6185
+ }
5674
6186
  if (state.flowStatus == FlowStatus.AGREEMENT) {
5675
6187
  currentBlock = h("agreement-info", null);
5676
6188
  }
@@ -5766,6 +6278,2967 @@ const LandingValidation = class {
5766
6278
  };
5767
6279
  LandingValidation.style = landingValidationCss;
5768
6280
 
6281
+ // can-promise has a crash in some versions of react native that dont have
6282
+ // standard global objects
6283
+ // https://github.com/soldair/node-qrcode/issues/157
6284
+
6285
+ var canPromise = function () {
6286
+ return typeof Promise === 'function' && Promise.prototype && Promise.prototype.then
6287
+ };
6288
+
6289
+ let toSJISFunction;
6290
+ const CODEWORDS_COUNT = [
6291
+ 0, // Not used
6292
+ 26, 44, 70, 100, 134, 172, 196, 242, 292, 346,
6293
+ 404, 466, 532, 581, 655, 733, 815, 901, 991, 1085,
6294
+ 1156, 1258, 1364, 1474, 1588, 1706, 1828, 1921, 2051, 2185,
6295
+ 2323, 2465, 2611, 2761, 2876, 3034, 3196, 3362, 3532, 3706
6296
+ ];
6297
+
6298
+ /**
6299
+ * Returns the QR Code size for the specified version
6300
+ *
6301
+ * @param {Number} version QR Code version
6302
+ * @return {Number} size of QR code
6303
+ */
6304
+ var getSymbolSize$1 = function getSymbolSize (version) {
6305
+ if (!version) throw new Error('"version" cannot be null or undefined')
6306
+ if (version < 1 || version > 40) throw new Error('"version" should be in range from 1 to 40')
6307
+ return version * 4 + 17
6308
+ };
6309
+
6310
+ /**
6311
+ * Returns the total number of codewords used to store data and EC information.
6312
+ *
6313
+ * @param {Number} version QR Code version
6314
+ * @return {Number} Data length in bits
6315
+ */
6316
+ var getSymbolTotalCodewords = function getSymbolTotalCodewords (version) {
6317
+ return CODEWORDS_COUNT[version]
6318
+ };
6319
+
6320
+ /**
6321
+ * Encode data with Bose-Chaudhuri-Hocquenghem
6322
+ *
6323
+ * @param {Number} data Value to encode
6324
+ * @return {Number} Encoded value
6325
+ */
6326
+ var getBCHDigit = function (data) {
6327
+ let digit = 0;
6328
+
6329
+ while (data !== 0) {
6330
+ digit++;
6331
+ data >>>= 1;
6332
+ }
6333
+
6334
+ return digit
6335
+ };
6336
+
6337
+ var setToSJISFunction = function setToSJISFunction (f) {
6338
+ if (typeof f !== 'function') {
6339
+ throw new Error('"toSJISFunc" is not a valid function.')
6340
+ }
6341
+
6342
+ toSJISFunction = f;
6343
+ };
6344
+
6345
+ var isKanjiModeEnabled = function () {
6346
+ return typeof toSJISFunction !== 'undefined'
6347
+ };
6348
+
6349
+ var toSJIS = function toSJIS (kanji) {
6350
+ return toSJISFunction(kanji)
6351
+ };
6352
+
6353
+ var utils$1 = {
6354
+ getSymbolSize: getSymbolSize$1,
6355
+ getSymbolTotalCodewords: getSymbolTotalCodewords,
6356
+ getBCHDigit: getBCHDigit,
6357
+ setToSJISFunction: setToSJISFunction,
6358
+ isKanjiModeEnabled: isKanjiModeEnabled,
6359
+ toSJIS: toSJIS
6360
+ };
6361
+
6362
+ var errorCorrectionLevel = createCommonjsModule(function (module, exports) {
6363
+ exports.L = { bit: 1 };
6364
+ exports.M = { bit: 0 };
6365
+ exports.Q = { bit: 3 };
6366
+ exports.H = { bit: 2 };
6367
+
6368
+ function fromString (string) {
6369
+ if (typeof string !== 'string') {
6370
+ throw new Error('Param is not a string')
6371
+ }
6372
+
6373
+ const lcStr = string.toLowerCase();
6374
+
6375
+ switch (lcStr) {
6376
+ case 'l':
6377
+ case 'low':
6378
+ return exports.L
6379
+
6380
+ case 'm':
6381
+ case 'medium':
6382
+ return exports.M
6383
+
6384
+ case 'q':
6385
+ case 'quartile':
6386
+ return exports.Q
6387
+
6388
+ case 'h':
6389
+ case 'high':
6390
+ return exports.H
6391
+
6392
+ default:
6393
+ throw new Error('Unknown EC Level: ' + string)
6394
+ }
6395
+ }
6396
+
6397
+ exports.isValid = function isValid (level) {
6398
+ return level && typeof level.bit !== 'undefined' &&
6399
+ level.bit >= 0 && level.bit < 4
6400
+ };
6401
+
6402
+ exports.from = function from (value, defaultValue) {
6403
+ if (exports.isValid(value)) {
6404
+ return value
6405
+ }
6406
+
6407
+ try {
6408
+ return fromString(value)
6409
+ } catch (e) {
6410
+ return defaultValue
6411
+ }
6412
+ };
6413
+ });
6414
+
6415
+ function BitBuffer () {
6416
+ this.buffer = [];
6417
+ this.length = 0;
6418
+ }
6419
+
6420
+ BitBuffer.prototype = {
6421
+
6422
+ get: function (index) {
6423
+ const bufIndex = Math.floor(index / 8);
6424
+ return ((this.buffer[bufIndex] >>> (7 - index % 8)) & 1) === 1
6425
+ },
6426
+
6427
+ put: function (num, length) {
6428
+ for (let i = 0; i < length; i++) {
6429
+ this.putBit(((num >>> (length - i - 1)) & 1) === 1);
6430
+ }
6431
+ },
6432
+
6433
+ getLengthInBits: function () {
6434
+ return this.length
6435
+ },
6436
+
6437
+ putBit: function (bit) {
6438
+ const bufIndex = Math.floor(this.length / 8);
6439
+ if (this.buffer.length <= bufIndex) {
6440
+ this.buffer.push(0);
6441
+ }
6442
+
6443
+ if (bit) {
6444
+ this.buffer[bufIndex] |= (0x80 >>> (this.length % 8));
6445
+ }
6446
+
6447
+ this.length++;
6448
+ }
6449
+ };
6450
+
6451
+ var bitBuffer = BitBuffer;
6452
+
6453
+ /**
6454
+ * Helper class to handle QR Code symbol modules
6455
+ *
6456
+ * @param {Number} size Symbol size
6457
+ */
6458
+ function BitMatrix (size) {
6459
+ if (!size || size < 1) {
6460
+ throw new Error('BitMatrix size must be defined and greater than 0')
6461
+ }
6462
+
6463
+ this.size = size;
6464
+ this.data = new Uint8Array(size * size);
6465
+ this.reservedBit = new Uint8Array(size * size);
6466
+ }
6467
+
6468
+ /**
6469
+ * Set bit value at specified location
6470
+ * If reserved flag is set, this bit will be ignored during masking process
6471
+ *
6472
+ * @param {Number} row
6473
+ * @param {Number} col
6474
+ * @param {Boolean} value
6475
+ * @param {Boolean} reserved
6476
+ */
6477
+ BitMatrix.prototype.set = function (row, col, value, reserved) {
6478
+ const index = row * this.size + col;
6479
+ this.data[index] = value;
6480
+ if (reserved) this.reservedBit[index] = true;
6481
+ };
6482
+
6483
+ /**
6484
+ * Returns bit value at specified location
6485
+ *
6486
+ * @param {Number} row
6487
+ * @param {Number} col
6488
+ * @return {Boolean}
6489
+ */
6490
+ BitMatrix.prototype.get = function (row, col) {
6491
+ return this.data[row * this.size + col]
6492
+ };
6493
+
6494
+ /**
6495
+ * Applies xor operator at specified location
6496
+ * (used during masking process)
6497
+ *
6498
+ * @param {Number} row
6499
+ * @param {Number} col
6500
+ * @param {Boolean} value
6501
+ */
6502
+ BitMatrix.prototype.xor = function (row, col, value) {
6503
+ this.data[row * this.size + col] ^= value;
6504
+ };
6505
+
6506
+ /**
6507
+ * Check if bit at specified location is reserved
6508
+ *
6509
+ * @param {Number} row
6510
+ * @param {Number} col
6511
+ * @return {Boolean}
6512
+ */
6513
+ BitMatrix.prototype.isReserved = function (row, col) {
6514
+ return this.reservedBit[row * this.size + col]
6515
+ };
6516
+
6517
+ var bitMatrix = BitMatrix;
6518
+
6519
+ var alignmentPattern = createCommonjsModule(function (module, exports) {
6520
+ /**
6521
+ * Alignment pattern are fixed reference pattern in defined positions
6522
+ * in a matrix symbology, which enables the decode software to re-synchronise
6523
+ * the coordinate mapping of the image modules in the event of moderate amounts
6524
+ * of distortion of the image.
6525
+ *
6526
+ * Alignment patterns are present only in QR Code symbols of version 2 or larger
6527
+ * and their number depends on the symbol version.
6528
+ */
6529
+
6530
+ const getSymbolSize = utils$1.getSymbolSize;
6531
+
6532
+ /**
6533
+ * Calculate the row/column coordinates of the center module of each alignment pattern
6534
+ * for the specified QR Code version.
6535
+ *
6536
+ * The alignment patterns are positioned symmetrically on either side of the diagonal
6537
+ * running from the top left corner of the symbol to the bottom right corner.
6538
+ *
6539
+ * Since positions are simmetrical only half of the coordinates are returned.
6540
+ * Each item of the array will represent in turn the x and y coordinate.
6541
+ * @see {@link getPositions}
6542
+ *
6543
+ * @param {Number} version QR Code version
6544
+ * @return {Array} Array of coordinate
6545
+ */
6546
+ exports.getRowColCoords = function getRowColCoords (version) {
6547
+ if (version === 1) return []
6548
+
6549
+ const posCount = Math.floor(version / 7) + 2;
6550
+ const size = getSymbolSize(version);
6551
+ const intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2;
6552
+ const positions = [size - 7]; // Last coord is always (size - 7)
6553
+
6554
+ for (let i = 1; i < posCount - 1; i++) {
6555
+ positions[i] = positions[i - 1] - intervals;
6556
+ }
6557
+
6558
+ positions.push(6); // First coord is always 6
6559
+
6560
+ return positions.reverse()
6561
+ };
6562
+
6563
+ /**
6564
+ * Returns an array containing the positions of each alignment pattern.
6565
+ * Each array's element represent the center point of the pattern as (x, y) coordinates
6566
+ *
6567
+ * Coordinates are calculated expanding the row/column coordinates returned by {@link getRowColCoords}
6568
+ * and filtering out the items that overlaps with finder pattern
6569
+ *
6570
+ * @example
6571
+ * For a Version 7 symbol {@link getRowColCoords} returns values 6, 22 and 38.
6572
+ * The alignment patterns, therefore, are to be centered on (row, column)
6573
+ * positions (6,22), (22,6), (22,22), (22,38), (38,22), (38,38).
6574
+ * Note that the coordinates (6,6), (6,38), (38,6) are occupied by finder patterns
6575
+ * and are not therefore used for alignment patterns.
6576
+ *
6577
+ * let pos = getPositions(7)
6578
+ * // [[6,22], [22,6], [22,22], [22,38], [38,22], [38,38]]
6579
+ *
6580
+ * @param {Number} version QR Code version
6581
+ * @return {Array} Array of coordinates
6582
+ */
6583
+ exports.getPositions = function getPositions (version) {
6584
+ const coords = [];
6585
+ const pos = exports.getRowColCoords(version);
6586
+ const posLength = pos.length;
6587
+
6588
+ for (let i = 0; i < posLength; i++) {
6589
+ for (let j = 0; j < posLength; j++) {
6590
+ // Skip if position is occupied by finder patterns
6591
+ if ((i === 0 && j === 0) || // top-left
6592
+ (i === 0 && j === posLength - 1) || // bottom-left
6593
+ (i === posLength - 1 && j === 0)) { // top-right
6594
+ continue
6595
+ }
6596
+
6597
+ coords.push([pos[i], pos[j]]);
6598
+ }
6599
+ }
6600
+
6601
+ return coords
6602
+ };
6603
+ });
6604
+
6605
+ const getSymbolSize = utils$1.getSymbolSize;
6606
+ const FINDER_PATTERN_SIZE = 7;
6607
+
6608
+ /**
6609
+ * Returns an array containing the positions of each finder pattern.
6610
+ * Each array's element represent the top-left point of the pattern as (x, y) coordinates
6611
+ *
6612
+ * @param {Number} version QR Code version
6613
+ * @return {Array} Array of coordinates
6614
+ */
6615
+ var getPositions = function getPositions (version) {
6616
+ const size = getSymbolSize(version);
6617
+
6618
+ return [
6619
+ // top-left
6620
+ [0, 0],
6621
+ // top-right
6622
+ [size - FINDER_PATTERN_SIZE, 0],
6623
+ // bottom-left
6624
+ [0, size - FINDER_PATTERN_SIZE]
6625
+ ]
6626
+ };
6627
+
6628
+ var finderPattern = {
6629
+ getPositions: getPositions
6630
+ };
6631
+
6632
+ var maskPattern = createCommonjsModule(function (module, exports) {
6633
+ /**
6634
+ * Data mask pattern reference
6635
+ * @type {Object}
6636
+ */
6637
+ exports.Patterns = {
6638
+ PATTERN000: 0,
6639
+ PATTERN001: 1,
6640
+ PATTERN010: 2,
6641
+ PATTERN011: 3,
6642
+ PATTERN100: 4,
6643
+ PATTERN101: 5,
6644
+ PATTERN110: 6,
6645
+ PATTERN111: 7
6646
+ };
6647
+
6648
+ /**
6649
+ * Weighted penalty scores for the undesirable features
6650
+ * @type {Object}
6651
+ */
6652
+ const PenaltyScores = {
6653
+ N1: 3,
6654
+ N2: 3,
6655
+ N3: 40,
6656
+ N4: 10
6657
+ };
6658
+
6659
+ /**
6660
+ * Check if mask pattern value is valid
6661
+ *
6662
+ * @param {Number} mask Mask pattern
6663
+ * @return {Boolean} true if valid, false otherwise
6664
+ */
6665
+ exports.isValid = function isValid (mask) {
6666
+ return mask != null && mask !== '' && !isNaN(mask) && mask >= 0 && mask <= 7
6667
+ };
6668
+
6669
+ /**
6670
+ * Returns mask pattern from a value.
6671
+ * If value is not valid, returns undefined
6672
+ *
6673
+ * @param {Number|String} value Mask pattern value
6674
+ * @return {Number} Valid mask pattern or undefined
6675
+ */
6676
+ exports.from = function from (value) {
6677
+ return exports.isValid(value) ? parseInt(value, 10) : undefined
6678
+ };
6679
+
6680
+ /**
6681
+ * Find adjacent modules in row/column with the same color
6682
+ * and assign a penalty value.
6683
+ *
6684
+ * Points: N1 + i
6685
+ * i is the amount by which the number of adjacent modules of the same color exceeds 5
6686
+ */
6687
+ exports.getPenaltyN1 = function getPenaltyN1 (data) {
6688
+ const size = data.size;
6689
+ let points = 0;
6690
+ let sameCountCol = 0;
6691
+ let sameCountRow = 0;
6692
+ let lastCol = null;
6693
+ let lastRow = null;
6694
+
6695
+ for (let row = 0; row < size; row++) {
6696
+ sameCountCol = sameCountRow = 0;
6697
+ lastCol = lastRow = null;
6698
+
6699
+ for (let col = 0; col < size; col++) {
6700
+ let module = data.get(row, col);
6701
+ if (module === lastCol) {
6702
+ sameCountCol++;
6703
+ } else {
6704
+ if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5);
6705
+ lastCol = module;
6706
+ sameCountCol = 1;
6707
+ }
6708
+
6709
+ module = data.get(col, row);
6710
+ if (module === lastRow) {
6711
+ sameCountRow++;
6712
+ } else {
6713
+ if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5);
6714
+ lastRow = module;
6715
+ sameCountRow = 1;
6716
+ }
6717
+ }
6718
+
6719
+ if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5);
6720
+ if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5);
6721
+ }
6722
+
6723
+ return points
6724
+ };
6725
+
6726
+ /**
6727
+ * Find 2x2 blocks with the same color and assign a penalty value
6728
+ *
6729
+ * Points: N2 * (m - 1) * (n - 1)
6730
+ */
6731
+ exports.getPenaltyN2 = function getPenaltyN2 (data) {
6732
+ const size = data.size;
6733
+ let points = 0;
6734
+
6735
+ for (let row = 0; row < size - 1; row++) {
6736
+ for (let col = 0; col < size - 1; col++) {
6737
+ const last = data.get(row, col) +
6738
+ data.get(row, col + 1) +
6739
+ data.get(row + 1, col) +
6740
+ data.get(row + 1, col + 1);
6741
+
6742
+ if (last === 4 || last === 0) points++;
6743
+ }
6744
+ }
6745
+
6746
+ return points * PenaltyScores.N2
6747
+ };
6748
+
6749
+ /**
6750
+ * Find 1:1:3:1:1 ratio (dark:light:dark:light:dark) pattern in row/column,
6751
+ * preceded or followed by light area 4 modules wide
6752
+ *
6753
+ * Points: N3 * number of pattern found
6754
+ */
6755
+ exports.getPenaltyN3 = function getPenaltyN3 (data) {
6756
+ const size = data.size;
6757
+ let points = 0;
6758
+ let bitsCol = 0;
6759
+ let bitsRow = 0;
6760
+
6761
+ for (let row = 0; row < size; row++) {
6762
+ bitsCol = bitsRow = 0;
6763
+ for (let col = 0; col < size; col++) {
6764
+ bitsCol = ((bitsCol << 1) & 0x7FF) | data.get(row, col);
6765
+ if (col >= 10 && (bitsCol === 0x5D0 || bitsCol === 0x05D)) points++;
6766
+
6767
+ bitsRow = ((bitsRow << 1) & 0x7FF) | data.get(col, row);
6768
+ if (col >= 10 && (bitsRow === 0x5D0 || bitsRow === 0x05D)) points++;
6769
+ }
6770
+ }
6771
+
6772
+ return points * PenaltyScores.N3
6773
+ };
6774
+
6775
+ /**
6776
+ * Calculate proportion of dark modules in entire symbol
6777
+ *
6778
+ * Points: N4 * k
6779
+ *
6780
+ * k is the rating of the deviation of the proportion of dark modules
6781
+ * in the symbol from 50% in steps of 5%
6782
+ */
6783
+ exports.getPenaltyN4 = function getPenaltyN4 (data) {
6784
+ let darkCount = 0;
6785
+ const modulesCount = data.data.length;
6786
+
6787
+ for (let i = 0; i < modulesCount; i++) darkCount += data.data[i];
6788
+
6789
+ const k = Math.abs(Math.ceil((darkCount * 100 / modulesCount) / 5) - 10);
6790
+
6791
+ return k * PenaltyScores.N4
6792
+ };
6793
+
6794
+ /**
6795
+ * Return mask value at given position
6796
+ *
6797
+ * @param {Number} maskPattern Pattern reference value
6798
+ * @param {Number} i Row
6799
+ * @param {Number} j Column
6800
+ * @return {Boolean} Mask value
6801
+ */
6802
+ function getMaskAt (maskPattern, i, j) {
6803
+ switch (maskPattern) {
6804
+ case exports.Patterns.PATTERN000: return (i + j) % 2 === 0
6805
+ case exports.Patterns.PATTERN001: return i % 2 === 0
6806
+ case exports.Patterns.PATTERN010: return j % 3 === 0
6807
+ case exports.Patterns.PATTERN011: return (i + j) % 3 === 0
6808
+ case exports.Patterns.PATTERN100: return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 === 0
6809
+ case exports.Patterns.PATTERN101: return (i * j) % 2 + (i * j) % 3 === 0
6810
+ case exports.Patterns.PATTERN110: return ((i * j) % 2 + (i * j) % 3) % 2 === 0
6811
+ case exports.Patterns.PATTERN111: return ((i * j) % 3 + (i + j) % 2) % 2 === 0
6812
+
6813
+ default: throw new Error('bad maskPattern:' + maskPattern)
6814
+ }
6815
+ }
6816
+
6817
+ /**
6818
+ * Apply a mask pattern to a BitMatrix
6819
+ *
6820
+ * @param {Number} pattern Pattern reference number
6821
+ * @param {BitMatrix} data BitMatrix data
6822
+ */
6823
+ exports.applyMask = function applyMask (pattern, data) {
6824
+ const size = data.size;
6825
+
6826
+ for (let col = 0; col < size; col++) {
6827
+ for (let row = 0; row < size; row++) {
6828
+ if (data.isReserved(row, col)) continue
6829
+ data.xor(row, col, getMaskAt(pattern, row, col));
6830
+ }
6831
+ }
6832
+ };
6833
+
6834
+ /**
6835
+ * Returns the best mask pattern for data
6836
+ *
6837
+ * @param {BitMatrix} data
6838
+ * @return {Number} Mask pattern reference number
6839
+ */
6840
+ exports.getBestMask = function getBestMask (data, setupFormatFunc) {
6841
+ const numPatterns = Object.keys(exports.Patterns).length;
6842
+ let bestPattern = 0;
6843
+ let lowerPenalty = Infinity;
6844
+
6845
+ for (let p = 0; p < numPatterns; p++) {
6846
+ setupFormatFunc(p);
6847
+ exports.applyMask(p, data);
6848
+
6849
+ // Calculate penalty
6850
+ const penalty =
6851
+ exports.getPenaltyN1(data) +
6852
+ exports.getPenaltyN2(data) +
6853
+ exports.getPenaltyN3(data) +
6854
+ exports.getPenaltyN4(data);
6855
+
6856
+ // Undo previously applied mask
6857
+ exports.applyMask(p, data);
6858
+
6859
+ if (penalty < lowerPenalty) {
6860
+ lowerPenalty = penalty;
6861
+ bestPattern = p;
6862
+ }
6863
+ }
6864
+
6865
+ return bestPattern
6866
+ };
6867
+ });
6868
+
6869
+ const EC_BLOCKS_TABLE = [
6870
+ // L M Q H
6871
+ 1, 1, 1, 1,
6872
+ 1, 1, 1, 1,
6873
+ 1, 1, 2, 2,
6874
+ 1, 2, 2, 4,
6875
+ 1, 2, 4, 4,
6876
+ 2, 4, 4, 4,
6877
+ 2, 4, 6, 5,
6878
+ 2, 4, 6, 6,
6879
+ 2, 5, 8, 8,
6880
+ 4, 5, 8, 8,
6881
+ 4, 5, 8, 11,
6882
+ 4, 8, 10, 11,
6883
+ 4, 9, 12, 16,
6884
+ 4, 9, 16, 16,
6885
+ 6, 10, 12, 18,
6886
+ 6, 10, 17, 16,
6887
+ 6, 11, 16, 19,
6888
+ 6, 13, 18, 21,
6889
+ 7, 14, 21, 25,
6890
+ 8, 16, 20, 25,
6891
+ 8, 17, 23, 25,
6892
+ 9, 17, 23, 34,
6893
+ 9, 18, 25, 30,
6894
+ 10, 20, 27, 32,
6895
+ 12, 21, 29, 35,
6896
+ 12, 23, 34, 37,
6897
+ 12, 25, 34, 40,
6898
+ 13, 26, 35, 42,
6899
+ 14, 28, 38, 45,
6900
+ 15, 29, 40, 48,
6901
+ 16, 31, 43, 51,
6902
+ 17, 33, 45, 54,
6903
+ 18, 35, 48, 57,
6904
+ 19, 37, 51, 60,
6905
+ 19, 38, 53, 63,
6906
+ 20, 40, 56, 66,
6907
+ 21, 43, 59, 70,
6908
+ 22, 45, 62, 74,
6909
+ 24, 47, 65, 77,
6910
+ 25, 49, 68, 81
6911
+ ];
6912
+
6913
+ const EC_CODEWORDS_TABLE = [
6914
+ // L M Q H
6915
+ 7, 10, 13, 17,
6916
+ 10, 16, 22, 28,
6917
+ 15, 26, 36, 44,
6918
+ 20, 36, 52, 64,
6919
+ 26, 48, 72, 88,
6920
+ 36, 64, 96, 112,
6921
+ 40, 72, 108, 130,
6922
+ 48, 88, 132, 156,
6923
+ 60, 110, 160, 192,
6924
+ 72, 130, 192, 224,
6925
+ 80, 150, 224, 264,
6926
+ 96, 176, 260, 308,
6927
+ 104, 198, 288, 352,
6928
+ 120, 216, 320, 384,
6929
+ 132, 240, 360, 432,
6930
+ 144, 280, 408, 480,
6931
+ 168, 308, 448, 532,
6932
+ 180, 338, 504, 588,
6933
+ 196, 364, 546, 650,
6934
+ 224, 416, 600, 700,
6935
+ 224, 442, 644, 750,
6936
+ 252, 476, 690, 816,
6937
+ 270, 504, 750, 900,
6938
+ 300, 560, 810, 960,
6939
+ 312, 588, 870, 1050,
6940
+ 336, 644, 952, 1110,
6941
+ 360, 700, 1020, 1200,
6942
+ 390, 728, 1050, 1260,
6943
+ 420, 784, 1140, 1350,
6944
+ 450, 812, 1200, 1440,
6945
+ 480, 868, 1290, 1530,
6946
+ 510, 924, 1350, 1620,
6947
+ 540, 980, 1440, 1710,
6948
+ 570, 1036, 1530, 1800,
6949
+ 570, 1064, 1590, 1890,
6950
+ 600, 1120, 1680, 1980,
6951
+ 630, 1204, 1770, 2100,
6952
+ 660, 1260, 1860, 2220,
6953
+ 720, 1316, 1950, 2310,
6954
+ 750, 1372, 2040, 2430
6955
+ ];
6956
+
6957
+ /**
6958
+ * Returns the number of error correction block that the QR Code should contain
6959
+ * for the specified version and error correction level.
6960
+ *
6961
+ * @param {Number} version QR Code version
6962
+ * @param {Number} errorCorrectionLevel Error correction level
6963
+ * @return {Number} Number of error correction blocks
6964
+ */
6965
+ var getBlocksCount = function getBlocksCount (version, errorCorrectionLevel$1) {
6966
+ switch (errorCorrectionLevel$1) {
6967
+ case errorCorrectionLevel.L:
6968
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 0]
6969
+ case errorCorrectionLevel.M:
6970
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 1]
6971
+ case errorCorrectionLevel.Q:
6972
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 2]
6973
+ case errorCorrectionLevel.H:
6974
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 3]
6975
+ default:
6976
+ return undefined
6977
+ }
6978
+ };
6979
+
6980
+ /**
6981
+ * Returns the number of error correction codewords to use for the specified
6982
+ * version and error correction level.
6983
+ *
6984
+ * @param {Number} version QR Code version
6985
+ * @param {Number} errorCorrectionLevel Error correction level
6986
+ * @return {Number} Number of error correction codewords
6987
+ */
6988
+ var getTotalCodewordsCount = function getTotalCodewordsCount (version, errorCorrectionLevel$1) {
6989
+ switch (errorCorrectionLevel$1) {
6990
+ case errorCorrectionLevel.L:
6991
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 0]
6992
+ case errorCorrectionLevel.M:
6993
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 1]
6994
+ case errorCorrectionLevel.Q:
6995
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 2]
6996
+ case errorCorrectionLevel.H:
6997
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 3]
6998
+ default:
6999
+ return undefined
7000
+ }
7001
+ };
7002
+
7003
+ var errorCorrectionCode = {
7004
+ getBlocksCount: getBlocksCount,
7005
+ getTotalCodewordsCount: getTotalCodewordsCount
7006
+ };
7007
+
7008
+ const EXP_TABLE = new Uint8Array(512);
7009
+ const LOG_TABLE = new Uint8Array(256)
7010
+ /**
7011
+ * Precompute the log and anti-log tables for faster computation later
7012
+ *
7013
+ * For each possible value in the galois field 2^8, we will pre-compute
7014
+ * the logarithm and anti-logarithm (exponential) of this value
7015
+ *
7016
+ * ref {@link https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Introduction_to_mathematical_fields}
7017
+ */
7018
+ ;(function initTables () {
7019
+ let x = 1;
7020
+ for (let i = 0; i < 255; i++) {
7021
+ EXP_TABLE[i] = x;
7022
+ LOG_TABLE[x] = i;
7023
+
7024
+ x <<= 1; // multiply by 2
7025
+
7026
+ // The QR code specification says to use byte-wise modulo 100011101 arithmetic.
7027
+ // This means that when a number is 256 or larger, it should be XORed with 0x11D.
7028
+ if (x & 0x100) { // similar to x >= 256, but a lot faster (because 0x100 == 256)
7029
+ x ^= 0x11D;
7030
+ }
7031
+ }
7032
+
7033
+ // Optimization: double the size of the anti-log table so that we don't need to mod 255 to
7034
+ // stay inside the bounds (because we will mainly use this table for the multiplication of
7035
+ // two GF numbers, no more).
7036
+ // @see {@link mul}
7037
+ for (let i = 255; i < 512; i++) {
7038
+ EXP_TABLE[i] = EXP_TABLE[i - 255];
7039
+ }
7040
+ }());
7041
+
7042
+ /**
7043
+ * Returns log value of n inside Galois Field
7044
+ *
7045
+ * @param {Number} n
7046
+ * @return {Number}
7047
+ */
7048
+ var log = function log (n) {
7049
+ if (n < 1) throw new Error('log(' + n + ')')
7050
+ return LOG_TABLE[n]
7051
+ };
7052
+
7053
+ /**
7054
+ * Returns anti-log value of n inside Galois Field
7055
+ *
7056
+ * @param {Number} n
7057
+ * @return {Number}
7058
+ */
7059
+ var exp = function exp (n) {
7060
+ return EXP_TABLE[n]
7061
+ };
7062
+
7063
+ /**
7064
+ * Multiplies two number inside Galois Field
7065
+ *
7066
+ * @param {Number} x
7067
+ * @param {Number} y
7068
+ * @return {Number}
7069
+ */
7070
+ var mul = function mul (x, y) {
7071
+ if (x === 0 || y === 0) return 0
7072
+
7073
+ // should be EXP_TABLE[(LOG_TABLE[x] + LOG_TABLE[y]) % 255] if EXP_TABLE wasn't oversized
7074
+ // @see {@link initTables}
7075
+ return EXP_TABLE[LOG_TABLE[x] + LOG_TABLE[y]]
7076
+ };
7077
+
7078
+ var galoisField = {
7079
+ log: log,
7080
+ exp: exp,
7081
+ mul: mul
7082
+ };
7083
+
7084
+ var polynomial = createCommonjsModule(function (module, exports) {
7085
+ /**
7086
+ * Multiplies two polynomials inside Galois Field
7087
+ *
7088
+ * @param {Uint8Array} p1 Polynomial
7089
+ * @param {Uint8Array} p2 Polynomial
7090
+ * @return {Uint8Array} Product of p1 and p2
7091
+ */
7092
+ exports.mul = function mul (p1, p2) {
7093
+ const coeff = new Uint8Array(p1.length + p2.length - 1);
7094
+
7095
+ for (let i = 0; i < p1.length; i++) {
7096
+ for (let j = 0; j < p2.length; j++) {
7097
+ coeff[i + j] ^= galoisField.mul(p1[i], p2[j]);
7098
+ }
7099
+ }
7100
+
7101
+ return coeff
7102
+ };
7103
+
7104
+ /**
7105
+ * Calculate the remainder of polynomials division
7106
+ *
7107
+ * @param {Uint8Array} divident Polynomial
7108
+ * @param {Uint8Array} divisor Polynomial
7109
+ * @return {Uint8Array} Remainder
7110
+ */
7111
+ exports.mod = function mod (divident, divisor) {
7112
+ let result = new Uint8Array(divident);
7113
+
7114
+ while ((result.length - divisor.length) >= 0) {
7115
+ const coeff = result[0];
7116
+
7117
+ for (let i = 0; i < divisor.length; i++) {
7118
+ result[i] ^= galoisField.mul(divisor[i], coeff);
7119
+ }
7120
+
7121
+ // remove all zeros from buffer head
7122
+ let offset = 0;
7123
+ while (offset < result.length && result[offset] === 0) offset++;
7124
+ result = result.slice(offset);
7125
+ }
7126
+
7127
+ return result
7128
+ };
7129
+
7130
+ /**
7131
+ * Generate an irreducible generator polynomial of specified degree
7132
+ * (used by Reed-Solomon encoder)
7133
+ *
7134
+ * @param {Number} degree Degree of the generator polynomial
7135
+ * @return {Uint8Array} Buffer containing polynomial coefficients
7136
+ */
7137
+ exports.generateECPolynomial = function generateECPolynomial (degree) {
7138
+ let poly = new Uint8Array([1]);
7139
+ for (let i = 0; i < degree; i++) {
7140
+ poly = exports.mul(poly, new Uint8Array([1, galoisField.exp(i)]));
7141
+ }
7142
+
7143
+ return poly
7144
+ };
7145
+ });
7146
+
7147
+ function ReedSolomonEncoder (degree) {
7148
+ this.genPoly = undefined;
7149
+ this.degree = degree;
7150
+
7151
+ if (this.degree) this.initialize(this.degree);
7152
+ }
7153
+
7154
+ /**
7155
+ * Initialize the encoder.
7156
+ * The input param should correspond to the number of error correction codewords.
7157
+ *
7158
+ * @param {Number} degree
7159
+ */
7160
+ ReedSolomonEncoder.prototype.initialize = function initialize (degree) {
7161
+ // create an irreducible generator polynomial
7162
+ this.degree = degree;
7163
+ this.genPoly = polynomial.generateECPolynomial(this.degree);
7164
+ };
7165
+
7166
+ /**
7167
+ * Encodes a chunk of data
7168
+ *
7169
+ * @param {Uint8Array} data Buffer containing input data
7170
+ * @return {Uint8Array} Buffer containing encoded data
7171
+ */
7172
+ ReedSolomonEncoder.prototype.encode = function encode (data) {
7173
+ if (!this.genPoly) {
7174
+ throw new Error('Encoder not initialized')
7175
+ }
7176
+
7177
+ // Calculate EC for this data block
7178
+ // extends data size to data+genPoly size
7179
+ const paddedData = new Uint8Array(data.length + this.degree);
7180
+ paddedData.set(data);
7181
+
7182
+ // The error correction codewords are the remainder after dividing the data codewords
7183
+ // by a generator polynomial
7184
+ const remainder = polynomial.mod(paddedData, this.genPoly);
7185
+
7186
+ // return EC data blocks (last n byte, where n is the degree of genPoly)
7187
+ // If coefficients number in remainder are less than genPoly degree,
7188
+ // pad with 0s to the left to reach the needed number of coefficients
7189
+ const start = this.degree - remainder.length;
7190
+ if (start > 0) {
7191
+ const buff = new Uint8Array(this.degree);
7192
+ buff.set(remainder, start);
7193
+
7194
+ return buff
7195
+ }
7196
+
7197
+ return remainder
7198
+ };
7199
+
7200
+ var reedSolomonEncoder = ReedSolomonEncoder;
7201
+
7202
+ /**
7203
+ * Check if QR Code version is valid
7204
+ *
7205
+ * @param {Number} version QR Code version
7206
+ * @return {Boolean} true if valid version, false otherwise
7207
+ */
7208
+ var isValid = function isValid (version) {
7209
+ return !isNaN(version) && version >= 1 && version <= 40
7210
+ };
7211
+
7212
+ var versionCheck = {
7213
+ isValid: isValid
7214
+ };
7215
+
7216
+ const numeric = '[0-9]+';
7217
+ const alphanumeric = '[A-Z $%*+\\-./:]+';
7218
+ let kanji = '(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|' +
7219
+ '[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|' +
7220
+ '[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|' +
7221
+ '[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+';
7222
+ kanji = kanji.replace(/u/g, '\\u');
7223
+
7224
+ const byte = '(?:(?![A-Z0-9 $%*+\\-./:]|' + kanji + ')(?:.|[\r\n]))+';
7225
+
7226
+ var KANJI = new RegExp(kanji, 'g');
7227
+ var BYTE_KANJI = new RegExp('[^A-Z0-9 $%*+\\-./:]+', 'g');
7228
+ var BYTE = new RegExp(byte, 'g');
7229
+ var NUMERIC = new RegExp(numeric, 'g');
7230
+ var ALPHANUMERIC = new RegExp(alphanumeric, 'g');
7231
+
7232
+ const TEST_KANJI = new RegExp('^' + kanji + '$');
7233
+ const TEST_NUMERIC = new RegExp('^' + numeric + '$');
7234
+ const TEST_ALPHANUMERIC = new RegExp('^[A-Z0-9 $%*+\\-./:]+$');
7235
+
7236
+ var testKanji = function testKanji (str) {
7237
+ return TEST_KANJI.test(str)
7238
+ };
7239
+
7240
+ var testNumeric = function testNumeric (str) {
7241
+ return TEST_NUMERIC.test(str)
7242
+ };
7243
+
7244
+ var testAlphanumeric = function testAlphanumeric (str) {
7245
+ return TEST_ALPHANUMERIC.test(str)
7246
+ };
7247
+
7248
+ var regex = {
7249
+ KANJI: KANJI,
7250
+ BYTE_KANJI: BYTE_KANJI,
7251
+ BYTE: BYTE,
7252
+ NUMERIC: NUMERIC,
7253
+ ALPHANUMERIC: ALPHANUMERIC,
7254
+ testKanji: testKanji,
7255
+ testNumeric: testNumeric,
7256
+ testAlphanumeric: testAlphanumeric
7257
+ };
7258
+
7259
+ var mode = createCommonjsModule(function (module, exports) {
7260
+ /**
7261
+ * Numeric mode encodes data from the decimal digit set (0 - 9)
7262
+ * (byte values 30HEX to 39HEX).
7263
+ * Normally, 3 data characters are represented by 10 bits.
7264
+ *
7265
+ * @type {Object}
7266
+ */
7267
+ exports.NUMERIC = {
7268
+ id: 'Numeric',
7269
+ bit: 1 << 0,
7270
+ ccBits: [10, 12, 14]
7271
+ };
7272
+
7273
+ /**
7274
+ * Alphanumeric mode encodes data from a set of 45 characters,
7275
+ * i.e. 10 numeric digits (0 - 9),
7276
+ * 26 alphabetic characters (A - Z),
7277
+ * and 9 symbols (SP, $, %, *, +, -, ., /, :).
7278
+ * Normally, two input characters are represented by 11 bits.
7279
+ *
7280
+ * @type {Object}
7281
+ */
7282
+ exports.ALPHANUMERIC = {
7283
+ id: 'Alphanumeric',
7284
+ bit: 1 << 1,
7285
+ ccBits: [9, 11, 13]
7286
+ };
7287
+
7288
+ /**
7289
+ * In byte mode, data is encoded at 8 bits per character.
7290
+ *
7291
+ * @type {Object}
7292
+ */
7293
+ exports.BYTE = {
7294
+ id: 'Byte',
7295
+ bit: 1 << 2,
7296
+ ccBits: [8, 16, 16]
7297
+ };
7298
+
7299
+ /**
7300
+ * The Kanji mode efficiently encodes Kanji characters in accordance with
7301
+ * the Shift JIS system based on JIS X 0208.
7302
+ * The Shift JIS values are shifted from the JIS X 0208 values.
7303
+ * JIS X 0208 gives details of the shift coded representation.
7304
+ * Each two-byte character value is compacted to a 13-bit binary codeword.
7305
+ *
7306
+ * @type {Object}
7307
+ */
7308
+ exports.KANJI = {
7309
+ id: 'Kanji',
7310
+ bit: 1 << 3,
7311
+ ccBits: [8, 10, 12]
7312
+ };
7313
+
7314
+ /**
7315
+ * Mixed mode will contain a sequences of data in a combination of any of
7316
+ * the modes described above
7317
+ *
7318
+ * @type {Object}
7319
+ */
7320
+ exports.MIXED = {
7321
+ bit: -1
7322
+ };
7323
+
7324
+ /**
7325
+ * Returns the number of bits needed to store the data length
7326
+ * according to QR Code specifications.
7327
+ *
7328
+ * @param {Mode} mode Data mode
7329
+ * @param {Number} version QR Code version
7330
+ * @return {Number} Number of bits
7331
+ */
7332
+ exports.getCharCountIndicator = function getCharCountIndicator (mode, version) {
7333
+ if (!mode.ccBits) throw new Error('Invalid mode: ' + mode)
7334
+
7335
+ if (!versionCheck.isValid(version)) {
7336
+ throw new Error('Invalid version: ' + version)
7337
+ }
7338
+
7339
+ if (version >= 1 && version < 10) return mode.ccBits[0]
7340
+ else if (version < 27) return mode.ccBits[1]
7341
+ return mode.ccBits[2]
7342
+ };
7343
+
7344
+ /**
7345
+ * Returns the most efficient mode to store the specified data
7346
+ *
7347
+ * @param {String} dataStr Input data string
7348
+ * @return {Mode} Best mode
7349
+ */
7350
+ exports.getBestModeForData = function getBestModeForData (dataStr) {
7351
+ if (regex.testNumeric(dataStr)) return exports.NUMERIC
7352
+ else if (regex.testAlphanumeric(dataStr)) return exports.ALPHANUMERIC
7353
+ else if (regex.testKanji(dataStr)) return exports.KANJI
7354
+ else return exports.BYTE
7355
+ };
7356
+
7357
+ /**
7358
+ * Return mode name as string
7359
+ *
7360
+ * @param {Mode} mode Mode object
7361
+ * @returns {String} Mode name
7362
+ */
7363
+ exports.toString = function toString (mode) {
7364
+ if (mode && mode.id) return mode.id
7365
+ throw new Error('Invalid mode')
7366
+ };
7367
+
7368
+ /**
7369
+ * Check if input param is a valid mode object
7370
+ *
7371
+ * @param {Mode} mode Mode object
7372
+ * @returns {Boolean} True if valid mode, false otherwise
7373
+ */
7374
+ exports.isValid = function isValid (mode) {
7375
+ return mode && mode.bit && mode.ccBits
7376
+ };
7377
+
7378
+ /**
7379
+ * Get mode object from its name
7380
+ *
7381
+ * @param {String} string Mode name
7382
+ * @returns {Mode} Mode object
7383
+ */
7384
+ function fromString (string) {
7385
+ if (typeof string !== 'string') {
7386
+ throw new Error('Param is not a string')
7387
+ }
7388
+
7389
+ const lcStr = string.toLowerCase();
7390
+
7391
+ switch (lcStr) {
7392
+ case 'numeric':
7393
+ return exports.NUMERIC
7394
+ case 'alphanumeric':
7395
+ return exports.ALPHANUMERIC
7396
+ case 'kanji':
7397
+ return exports.KANJI
7398
+ case 'byte':
7399
+ return exports.BYTE
7400
+ default:
7401
+ throw new Error('Unknown mode: ' + string)
7402
+ }
7403
+ }
7404
+
7405
+ /**
7406
+ * Returns mode from a value.
7407
+ * If value is not a valid mode, returns defaultValue
7408
+ *
7409
+ * @param {Mode|String} value Encoding mode
7410
+ * @param {Mode} defaultValue Fallback value
7411
+ * @return {Mode} Encoding mode
7412
+ */
7413
+ exports.from = function from (value, defaultValue) {
7414
+ if (exports.isValid(value)) {
7415
+ return value
7416
+ }
7417
+
7418
+ try {
7419
+ return fromString(value)
7420
+ } catch (e) {
7421
+ return defaultValue
7422
+ }
7423
+ };
7424
+ });
7425
+
7426
+ var version = createCommonjsModule(function (module, exports) {
7427
+ // Generator polynomial used to encode version information
7428
+ const G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0);
7429
+ const G18_BCH = utils$1.getBCHDigit(G18);
7430
+
7431
+ function getBestVersionForDataLength (mode, length, errorCorrectionLevel) {
7432
+ for (let currentVersion = 1; currentVersion <= 40; currentVersion++) {
7433
+ if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, mode)) {
7434
+ return currentVersion
7435
+ }
7436
+ }
7437
+
7438
+ return undefined
7439
+ }
7440
+
7441
+ function getReservedBitsCount (mode$1, version) {
7442
+ // Character count indicator + mode indicator bits
7443
+ return mode.getCharCountIndicator(mode$1, version) + 4
7444
+ }
7445
+
7446
+ function getTotalBitsFromDataArray (segments, version) {
7447
+ let totalBits = 0;
7448
+
7449
+ segments.forEach(function (data) {
7450
+ const reservedBits = getReservedBitsCount(data.mode, version);
7451
+ totalBits += reservedBits + data.getBitsLength();
7452
+ });
7453
+
7454
+ return totalBits
7455
+ }
7456
+
7457
+ function getBestVersionForMixedData (segments, errorCorrectionLevel) {
7458
+ for (let currentVersion = 1; currentVersion <= 40; currentVersion++) {
7459
+ const length = getTotalBitsFromDataArray(segments, currentVersion);
7460
+ if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, mode.MIXED)) {
7461
+ return currentVersion
7462
+ }
7463
+ }
7464
+
7465
+ return undefined
7466
+ }
7467
+
7468
+ /**
7469
+ * Returns version number from a value.
7470
+ * If value is not a valid version, returns defaultValue
7471
+ *
7472
+ * @param {Number|String} value QR Code version
7473
+ * @param {Number} defaultValue Fallback value
7474
+ * @return {Number} QR Code version number
7475
+ */
7476
+ exports.from = function from (value, defaultValue) {
7477
+ if (versionCheck.isValid(value)) {
7478
+ return parseInt(value, 10)
7479
+ }
7480
+
7481
+ return defaultValue
7482
+ };
7483
+
7484
+ /**
7485
+ * Returns how much data can be stored with the specified QR code version
7486
+ * and error correction level
7487
+ *
7488
+ * @param {Number} version QR Code version (1-40)
7489
+ * @param {Number} errorCorrectionLevel Error correction level
7490
+ * @param {Mode} mode Data mode
7491
+ * @return {Number} Quantity of storable data
7492
+ */
7493
+ exports.getCapacity = function getCapacity (version, errorCorrectionLevel, mode$1) {
7494
+ if (!versionCheck.isValid(version)) {
7495
+ throw new Error('Invalid QR Code version')
7496
+ }
7497
+
7498
+ // Use Byte mode as default
7499
+ if (typeof mode$1 === 'undefined') mode$1 = mode.BYTE;
7500
+
7501
+ // Total codewords for this QR code version (Data + Error correction)
7502
+ const totalCodewords = utils$1.getSymbolTotalCodewords(version);
7503
+
7504
+ // Total number of error correction codewords
7505
+ const ecTotalCodewords = errorCorrectionCode.getTotalCodewordsCount(version, errorCorrectionLevel);
7506
+
7507
+ // Total number of data codewords
7508
+ const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8;
7509
+
7510
+ if (mode$1 === mode.MIXED) return dataTotalCodewordsBits
7511
+
7512
+ const usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode$1, version);
7513
+
7514
+ // Return max number of storable codewords
7515
+ switch (mode$1) {
7516
+ case mode.NUMERIC:
7517
+ return Math.floor((usableBits / 10) * 3)
7518
+
7519
+ case mode.ALPHANUMERIC:
7520
+ return Math.floor((usableBits / 11) * 2)
7521
+
7522
+ case mode.KANJI:
7523
+ return Math.floor(usableBits / 13)
7524
+
7525
+ case mode.BYTE:
7526
+ default:
7527
+ return Math.floor(usableBits / 8)
7528
+ }
7529
+ };
7530
+
7531
+ /**
7532
+ * Returns the minimum version needed to contain the amount of data
7533
+ *
7534
+ * @param {Segment} data Segment of data
7535
+ * @param {Number} [errorCorrectionLevel=H] Error correction level
7536
+ * @param {Mode} mode Data mode
7537
+ * @return {Number} QR Code version
7538
+ */
7539
+ exports.getBestVersionForData = function getBestVersionForData (data, errorCorrectionLevel$1) {
7540
+ let seg;
7541
+
7542
+ const ecl = errorCorrectionLevel.from(errorCorrectionLevel$1, errorCorrectionLevel.M);
7543
+
7544
+ if (Array.isArray(data)) {
7545
+ if (data.length > 1) {
7546
+ return getBestVersionForMixedData(data, ecl)
7547
+ }
7548
+
7549
+ if (data.length === 0) {
7550
+ return 1
7551
+ }
7552
+
7553
+ seg = data[0];
7554
+ } else {
7555
+ seg = data;
7556
+ }
7557
+
7558
+ return getBestVersionForDataLength(seg.mode, seg.getLength(), ecl)
7559
+ };
7560
+
7561
+ /**
7562
+ * Returns version information with relative error correction bits
7563
+ *
7564
+ * The version information is included in QR Code symbols of version 7 or larger.
7565
+ * It consists of an 18-bit sequence containing 6 data bits,
7566
+ * with 12 error correction bits calculated using the (18, 6) Golay code.
7567
+ *
7568
+ * @param {Number} version QR Code version
7569
+ * @return {Number} Encoded version info bits
7570
+ */
7571
+ exports.getEncodedBits = function getEncodedBits (version) {
7572
+ if (!versionCheck.isValid(version) || version < 7) {
7573
+ throw new Error('Invalid QR Code version')
7574
+ }
7575
+
7576
+ let d = version << 12;
7577
+
7578
+ while (utils$1.getBCHDigit(d) - G18_BCH >= 0) {
7579
+ d ^= (G18 << (utils$1.getBCHDigit(d) - G18_BCH));
7580
+ }
7581
+
7582
+ return (version << 12) | d
7583
+ };
7584
+ });
7585
+
7586
+ const G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0);
7587
+ const G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1);
7588
+ const G15_BCH = utils$1.getBCHDigit(G15);
7589
+
7590
+ /**
7591
+ * Returns format information with relative error correction bits
7592
+ *
7593
+ * The format information is a 15-bit sequence containing 5 data bits,
7594
+ * with 10 error correction bits calculated using the (15, 5) BCH code.
7595
+ *
7596
+ * @param {Number} errorCorrectionLevel Error correction level
7597
+ * @param {Number} mask Mask pattern
7598
+ * @return {Number} Encoded format information bits
7599
+ */
7600
+ var getEncodedBits = function getEncodedBits (errorCorrectionLevel, mask) {
7601
+ const data = ((errorCorrectionLevel.bit << 3) | mask);
7602
+ let d = data << 10;
7603
+
7604
+ while (utils$1.getBCHDigit(d) - G15_BCH >= 0) {
7605
+ d ^= (G15 << (utils$1.getBCHDigit(d) - G15_BCH));
7606
+ }
7607
+
7608
+ // xor final data with mask pattern in order to ensure that
7609
+ // no combination of Error Correction Level and data mask pattern
7610
+ // will result in an all-zero data string
7611
+ return ((data << 10) | d) ^ G15_MASK
7612
+ };
7613
+
7614
+ var formatInfo = {
7615
+ getEncodedBits: getEncodedBits
7616
+ };
7617
+
7618
+ function NumericData (data) {
7619
+ this.mode = mode.NUMERIC;
7620
+ this.data = data.toString();
7621
+ }
7622
+
7623
+ NumericData.getBitsLength = function getBitsLength (length) {
7624
+ return 10 * Math.floor(length / 3) + ((length % 3) ? ((length % 3) * 3 + 1) : 0)
7625
+ };
7626
+
7627
+ NumericData.prototype.getLength = function getLength () {
7628
+ return this.data.length
7629
+ };
7630
+
7631
+ NumericData.prototype.getBitsLength = function getBitsLength () {
7632
+ return NumericData.getBitsLength(this.data.length)
7633
+ };
7634
+
7635
+ NumericData.prototype.write = function write (bitBuffer) {
7636
+ let i, group, value;
7637
+
7638
+ // The input data string is divided into groups of three digits,
7639
+ // and each group is converted to its 10-bit binary equivalent.
7640
+ for (i = 0; i + 3 <= this.data.length; i += 3) {
7641
+ group = this.data.substr(i, 3);
7642
+ value = parseInt(group, 10);
7643
+
7644
+ bitBuffer.put(value, 10);
7645
+ }
7646
+
7647
+ // If the number of input digits is not an exact multiple of three,
7648
+ // the final one or two digits are converted to 4 or 7 bits respectively.
7649
+ const remainingNum = this.data.length - i;
7650
+ if (remainingNum > 0) {
7651
+ group = this.data.substr(i);
7652
+ value = parseInt(group, 10);
7653
+
7654
+ bitBuffer.put(value, remainingNum * 3 + 1);
7655
+ }
7656
+ };
7657
+
7658
+ var numericData = NumericData;
7659
+
7660
+ /**
7661
+ * Array of characters available in alphanumeric mode
7662
+ *
7663
+ * As per QR Code specification, to each character
7664
+ * is assigned a value from 0 to 44 which in this case coincides
7665
+ * with the array index
7666
+ *
7667
+ * @type {Array}
7668
+ */
7669
+ const ALPHA_NUM_CHARS = [
7670
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
7671
+ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
7672
+ 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
7673
+ ' ', '$', '%', '*', '+', '-', '.', '/', ':'
7674
+ ];
7675
+
7676
+ function AlphanumericData (data) {
7677
+ this.mode = mode.ALPHANUMERIC;
7678
+ this.data = data;
7679
+ }
7680
+
7681
+ AlphanumericData.getBitsLength = function getBitsLength (length) {
7682
+ return 11 * Math.floor(length / 2) + 6 * (length % 2)
7683
+ };
7684
+
7685
+ AlphanumericData.prototype.getLength = function getLength () {
7686
+ return this.data.length
7687
+ };
7688
+
7689
+ AlphanumericData.prototype.getBitsLength = function getBitsLength () {
7690
+ return AlphanumericData.getBitsLength(this.data.length)
7691
+ };
7692
+
7693
+ AlphanumericData.prototype.write = function write (bitBuffer) {
7694
+ let i;
7695
+
7696
+ // Input data characters are divided into groups of two characters
7697
+ // and encoded as 11-bit binary codes.
7698
+ for (i = 0; i + 2 <= this.data.length; i += 2) {
7699
+ // The character value of the first character is multiplied by 45
7700
+ let value = ALPHA_NUM_CHARS.indexOf(this.data[i]) * 45;
7701
+
7702
+ // The character value of the second digit is added to the product
7703
+ value += ALPHA_NUM_CHARS.indexOf(this.data[i + 1]);
7704
+
7705
+ // The sum is then stored as 11-bit binary number
7706
+ bitBuffer.put(value, 11);
7707
+ }
7708
+
7709
+ // If the number of input data characters is not a multiple of two,
7710
+ // the character value of the final character is encoded as a 6-bit binary number.
7711
+ if (this.data.length % 2) {
7712
+ bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i]), 6);
7713
+ }
7714
+ };
7715
+
7716
+ var alphanumericData = AlphanumericData;
7717
+
7718
+ var encodeUtf8 = function encodeUtf8 (input) {
7719
+ var result = [];
7720
+ var size = input.length;
7721
+
7722
+ for (var index = 0; index < size; index++) {
7723
+ var point = input.charCodeAt(index);
7724
+
7725
+ if (point >= 0xD800 && point <= 0xDBFF && size > index + 1) {
7726
+ var second = input.charCodeAt(index + 1);
7727
+
7728
+ if (second >= 0xDC00 && second <= 0xDFFF) {
7729
+ // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
7730
+ point = (point - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
7731
+ index += 1;
7732
+ }
7733
+ }
7734
+
7735
+ // US-ASCII
7736
+ if (point < 0x80) {
7737
+ result.push(point);
7738
+ continue
7739
+ }
7740
+
7741
+ // 2-byte UTF-8
7742
+ if (point < 0x800) {
7743
+ result.push((point >> 6) | 192);
7744
+ result.push((point & 63) | 128);
7745
+ continue
7746
+ }
7747
+
7748
+ // 3-byte UTF-8
7749
+ if (point < 0xD800 || (point >= 0xE000 && point < 0x10000)) {
7750
+ result.push((point >> 12) | 224);
7751
+ result.push(((point >> 6) & 63) | 128);
7752
+ result.push((point & 63) | 128);
7753
+ continue
7754
+ }
7755
+
7756
+ // 4-byte UTF-8
7757
+ if (point >= 0x10000 && point <= 0x10FFFF) {
7758
+ result.push((point >> 18) | 240);
7759
+ result.push(((point >> 12) & 63) | 128);
7760
+ result.push(((point >> 6) & 63) | 128);
7761
+ result.push((point & 63) | 128);
7762
+ continue
7763
+ }
7764
+
7765
+ // Invalid character
7766
+ result.push(0xEF, 0xBF, 0xBD);
7767
+ }
7768
+
7769
+ return new Uint8Array(result).buffer
7770
+ };
7771
+
7772
+ function ByteData (data) {
7773
+ this.mode = mode.BYTE;
7774
+ if (typeof (data) === 'string') {
7775
+ data = encodeUtf8(data);
7776
+ }
7777
+ this.data = new Uint8Array(data);
7778
+ }
7779
+
7780
+ ByteData.getBitsLength = function getBitsLength (length) {
7781
+ return length * 8
7782
+ };
7783
+
7784
+ ByteData.prototype.getLength = function getLength () {
7785
+ return this.data.length
7786
+ };
7787
+
7788
+ ByteData.prototype.getBitsLength = function getBitsLength () {
7789
+ return ByteData.getBitsLength(this.data.length)
7790
+ };
7791
+
7792
+ ByteData.prototype.write = function (bitBuffer) {
7793
+ for (let i = 0, l = this.data.length; i < l; i++) {
7794
+ bitBuffer.put(this.data[i], 8);
7795
+ }
7796
+ };
7797
+
7798
+ var byteData = ByteData;
7799
+
7800
+ function KanjiData (data) {
7801
+ this.mode = mode.KANJI;
7802
+ this.data = data;
7803
+ }
7804
+
7805
+ KanjiData.getBitsLength = function getBitsLength (length) {
7806
+ return length * 13
7807
+ };
7808
+
7809
+ KanjiData.prototype.getLength = function getLength () {
7810
+ return this.data.length
7811
+ };
7812
+
7813
+ KanjiData.prototype.getBitsLength = function getBitsLength () {
7814
+ return KanjiData.getBitsLength(this.data.length)
7815
+ };
7816
+
7817
+ KanjiData.prototype.write = function (bitBuffer) {
7818
+ let i;
7819
+
7820
+ // In the Shift JIS system, Kanji characters are represented by a two byte combination.
7821
+ // These byte values are shifted from the JIS X 0208 values.
7822
+ // JIS X 0208 gives details of the shift coded representation.
7823
+ for (i = 0; i < this.data.length; i++) {
7824
+ let value = utils$1.toSJIS(this.data[i]);
7825
+
7826
+ // For characters with Shift JIS values from 0x8140 to 0x9FFC:
7827
+ if (value >= 0x8140 && value <= 0x9FFC) {
7828
+ // Subtract 0x8140 from Shift JIS value
7829
+ value -= 0x8140;
7830
+
7831
+ // For characters with Shift JIS values from 0xE040 to 0xEBBF
7832
+ } else if (value >= 0xE040 && value <= 0xEBBF) {
7833
+ // Subtract 0xC140 from Shift JIS value
7834
+ value -= 0xC140;
7835
+ } else {
7836
+ throw new Error(
7837
+ 'Invalid SJIS character: ' + this.data[i] + '\n' +
7838
+ 'Make sure your charset is UTF-8')
7839
+ }
7840
+
7841
+ // Multiply most significant byte of result by 0xC0
7842
+ // and add least significant byte to product
7843
+ value = (((value >>> 8) & 0xff) * 0xC0) + (value & 0xff);
7844
+
7845
+ // Convert result to a 13-bit binary string
7846
+ bitBuffer.put(value, 13);
7847
+ }
7848
+ };
7849
+
7850
+ var kanjiData = KanjiData;
7851
+
7852
+ var dijkstra_1 = createCommonjsModule(function (module) {
7853
+
7854
+ /******************************************************************************
7855
+ * Created 2008-08-19.
7856
+ *
7857
+ * Dijkstra path-finding functions. Adapted from the Dijkstar Python project.
7858
+ *
7859
+ * Copyright (C) 2008
7860
+ * Wyatt Baldwin <self@wyattbaldwin.com>
7861
+ * All rights reserved
7862
+ *
7863
+ * Licensed under the MIT license.
7864
+ *
7865
+ * http://www.opensource.org/licenses/mit-license.php
7866
+ *
7867
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
7868
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
7869
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7870
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
7871
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
7872
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
7873
+ * THE SOFTWARE.
7874
+ *****************************************************************************/
7875
+ var dijkstra = {
7876
+ single_source_shortest_paths: function(graph, s, d) {
7877
+ // Predecessor map for each node that has been encountered.
7878
+ // node ID => predecessor node ID
7879
+ var predecessors = {};
7880
+
7881
+ // Costs of shortest paths from s to all nodes encountered.
7882
+ // node ID => cost
7883
+ var costs = {};
7884
+ costs[s] = 0;
7885
+
7886
+ // Costs of shortest paths from s to all nodes encountered; differs from
7887
+ // `costs` in that it provides easy access to the node that currently has
7888
+ // the known shortest path from s.
7889
+ // XXX: Do we actually need both `costs` and `open`?
7890
+ var open = dijkstra.PriorityQueue.make();
7891
+ open.push(s, 0);
7892
+
7893
+ var closest,
7894
+ u, v,
7895
+ cost_of_s_to_u,
7896
+ adjacent_nodes,
7897
+ cost_of_e,
7898
+ cost_of_s_to_u_plus_cost_of_e,
7899
+ cost_of_s_to_v,
7900
+ first_visit;
7901
+ while (!open.empty()) {
7902
+ // In the nodes remaining in graph that have a known cost from s,
7903
+ // find the node, u, that currently has the shortest path from s.
7904
+ closest = open.pop();
7905
+ u = closest.value;
7906
+ cost_of_s_to_u = closest.cost;
7907
+
7908
+ // Get nodes adjacent to u...
7909
+ adjacent_nodes = graph[u] || {};
7910
+
7911
+ // ...and explore the edges that connect u to those nodes, updating
7912
+ // the cost of the shortest paths to any or all of those nodes as
7913
+ // necessary. v is the node across the current edge from u.
7914
+ for (v in adjacent_nodes) {
7915
+ if (adjacent_nodes.hasOwnProperty(v)) {
7916
+ // Get the cost of the edge running from u to v.
7917
+ cost_of_e = adjacent_nodes[v];
7918
+
7919
+ // Cost of s to u plus the cost of u to v across e--this is *a*
7920
+ // cost from s to v that may or may not be less than the current
7921
+ // known cost to v.
7922
+ cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e;
7923
+
7924
+ // If we haven't visited v yet OR if the current known cost from s to
7925
+ // v is greater than the new cost we just found (cost of s to u plus
7926
+ // cost of u to v across e), update v's cost in the cost list and
7927
+ // update v's predecessor in the predecessor list (it's now u).
7928
+ cost_of_s_to_v = costs[v];
7929
+ first_visit = (typeof costs[v] === 'undefined');
7930
+ if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) {
7931
+ costs[v] = cost_of_s_to_u_plus_cost_of_e;
7932
+ open.push(v, cost_of_s_to_u_plus_cost_of_e);
7933
+ predecessors[v] = u;
7934
+ }
7935
+ }
7936
+ }
7937
+ }
7938
+
7939
+ if (typeof d !== 'undefined' && typeof costs[d] === 'undefined') {
7940
+ var msg = ['Could not find a path from ', s, ' to ', d, '.'].join('');
7941
+ throw new Error(msg);
7942
+ }
7943
+
7944
+ return predecessors;
7945
+ },
7946
+
7947
+ extract_shortest_path_from_predecessor_list: function(predecessors, d) {
7948
+ var nodes = [];
7949
+ var u = d;
7950
+ while (u) {
7951
+ nodes.push(u);
7952
+ u = predecessors[u];
7953
+ }
7954
+ nodes.reverse();
7955
+ return nodes;
7956
+ },
7957
+
7958
+ find_path: function(graph, s, d) {
7959
+ var predecessors = dijkstra.single_source_shortest_paths(graph, s, d);
7960
+ return dijkstra.extract_shortest_path_from_predecessor_list(
7961
+ predecessors, d);
7962
+ },
7963
+
7964
+ /**
7965
+ * A very naive priority queue implementation.
7966
+ */
7967
+ PriorityQueue: {
7968
+ make: function (opts) {
7969
+ var T = dijkstra.PriorityQueue,
7970
+ t = {},
7971
+ key;
7972
+ opts = opts || {};
7973
+ for (key in T) {
7974
+ if (T.hasOwnProperty(key)) {
7975
+ t[key] = T[key];
7976
+ }
7977
+ }
7978
+ t.queue = [];
7979
+ t.sorter = opts.sorter || T.default_sorter;
7980
+ return t;
7981
+ },
7982
+
7983
+ default_sorter: function (a, b) {
7984
+ return a.cost - b.cost;
7985
+ },
7986
+
7987
+ /**
7988
+ * Add a new item to the queue and ensure the highest priority element
7989
+ * is at the front of the queue.
7990
+ */
7991
+ push: function (value, cost) {
7992
+ var item = {value: value, cost: cost};
7993
+ this.queue.push(item);
7994
+ this.queue.sort(this.sorter);
7995
+ },
7996
+
7997
+ /**
7998
+ * Return the highest priority element in the queue.
7999
+ */
8000
+ pop: function () {
8001
+ return this.queue.shift();
8002
+ },
8003
+
8004
+ empty: function () {
8005
+ return this.queue.length === 0;
8006
+ }
8007
+ }
8008
+ };
8009
+
8010
+
8011
+ // node.js module exports
8012
+ {
8013
+ module.exports = dijkstra;
8014
+ }
8015
+ });
8016
+
8017
+ var segments = createCommonjsModule(function (module, exports) {
8018
+ /**
8019
+ * Returns UTF8 byte length
8020
+ *
8021
+ * @param {String} str Input string
8022
+ * @return {Number} Number of byte
8023
+ */
8024
+ function getStringByteLength (str) {
8025
+ return unescape(encodeURIComponent(str)).length
8026
+ }
8027
+
8028
+ /**
8029
+ * Get a list of segments of the specified mode
8030
+ * from a string
8031
+ *
8032
+ * @param {Mode} mode Segment mode
8033
+ * @param {String} str String to process
8034
+ * @return {Array} Array of object with segments data
8035
+ */
8036
+ function getSegments (regex, mode, str) {
8037
+ const segments = [];
8038
+ let result;
8039
+
8040
+ while ((result = regex.exec(str)) !== null) {
8041
+ segments.push({
8042
+ data: result[0],
8043
+ index: result.index,
8044
+ mode: mode,
8045
+ length: result[0].length
8046
+ });
8047
+ }
8048
+
8049
+ return segments
8050
+ }
8051
+
8052
+ /**
8053
+ * Extracts a series of segments with the appropriate
8054
+ * modes from a string
8055
+ *
8056
+ * @param {String} dataStr Input string
8057
+ * @return {Array} Array of object with segments data
8058
+ */
8059
+ function getSegmentsFromString (dataStr) {
8060
+ const numSegs = getSegments(regex.NUMERIC, mode.NUMERIC, dataStr);
8061
+ const alphaNumSegs = getSegments(regex.ALPHANUMERIC, mode.ALPHANUMERIC, dataStr);
8062
+ let byteSegs;
8063
+ let kanjiSegs;
8064
+
8065
+ if (utils$1.isKanjiModeEnabled()) {
8066
+ byteSegs = getSegments(regex.BYTE, mode.BYTE, dataStr);
8067
+ kanjiSegs = getSegments(regex.KANJI, mode.KANJI, dataStr);
8068
+ } else {
8069
+ byteSegs = getSegments(regex.BYTE_KANJI, mode.BYTE, dataStr);
8070
+ kanjiSegs = [];
8071
+ }
8072
+
8073
+ const segs = numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs);
8074
+
8075
+ return segs
8076
+ .sort(function (s1, s2) {
8077
+ return s1.index - s2.index
8078
+ })
8079
+ .map(function (obj) {
8080
+ return {
8081
+ data: obj.data,
8082
+ mode: obj.mode,
8083
+ length: obj.length
8084
+ }
8085
+ })
8086
+ }
8087
+
8088
+ /**
8089
+ * Returns how many bits are needed to encode a string of
8090
+ * specified length with the specified mode
8091
+ *
8092
+ * @param {Number} length String length
8093
+ * @param {Mode} mode Segment mode
8094
+ * @return {Number} Bit length
8095
+ */
8096
+ function getSegmentBitsLength (length, mode$1) {
8097
+ switch (mode$1) {
8098
+ case mode.NUMERIC:
8099
+ return numericData.getBitsLength(length)
8100
+ case mode.ALPHANUMERIC:
8101
+ return alphanumericData.getBitsLength(length)
8102
+ case mode.KANJI:
8103
+ return kanjiData.getBitsLength(length)
8104
+ case mode.BYTE:
8105
+ return byteData.getBitsLength(length)
8106
+ }
8107
+ }
8108
+
8109
+ /**
8110
+ * Merges adjacent segments which have the same mode
8111
+ *
8112
+ * @param {Array} segs Array of object with segments data
8113
+ * @return {Array} Array of object with segments data
8114
+ */
8115
+ function mergeSegments (segs) {
8116
+ return segs.reduce(function (acc, curr) {
8117
+ const prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null;
8118
+ if (prevSeg && prevSeg.mode === curr.mode) {
8119
+ acc[acc.length - 1].data += curr.data;
8120
+ return acc
8121
+ }
8122
+
8123
+ acc.push(curr);
8124
+ return acc
8125
+ }, [])
8126
+ }
8127
+
8128
+ /**
8129
+ * Generates a list of all possible nodes combination which
8130
+ * will be used to build a segments graph.
8131
+ *
8132
+ * Nodes are divided by groups. Each group will contain a list of all the modes
8133
+ * in which is possible to encode the given text.
8134
+ *
8135
+ * For example the text '12345' can be encoded as Numeric, Alphanumeric or Byte.
8136
+ * The group for '12345' will contain then 3 objects, one for each
8137
+ * possible encoding mode.
8138
+ *
8139
+ * Each node represents a possible segment.
8140
+ *
8141
+ * @param {Array} segs Array of object with segments data
8142
+ * @return {Array} Array of object with segments data
8143
+ */
8144
+ function buildNodes (segs) {
8145
+ const nodes = [];
8146
+ for (let i = 0; i < segs.length; i++) {
8147
+ const seg = segs[i];
8148
+
8149
+ switch (seg.mode) {
8150
+ case mode.NUMERIC:
8151
+ nodes.push([seg,
8152
+ { data: seg.data, mode: mode.ALPHANUMERIC, length: seg.length },
8153
+ { data: seg.data, mode: mode.BYTE, length: seg.length }
8154
+ ]);
8155
+ break
8156
+ case mode.ALPHANUMERIC:
8157
+ nodes.push([seg,
8158
+ { data: seg.data, mode: mode.BYTE, length: seg.length }
8159
+ ]);
8160
+ break
8161
+ case mode.KANJI:
8162
+ nodes.push([seg,
8163
+ { data: seg.data, mode: mode.BYTE, length: getStringByteLength(seg.data) }
8164
+ ]);
8165
+ break
8166
+ case mode.BYTE:
8167
+ nodes.push([
8168
+ { data: seg.data, mode: mode.BYTE, length: getStringByteLength(seg.data) }
8169
+ ]);
8170
+ }
8171
+ }
8172
+
8173
+ return nodes
8174
+ }
8175
+
8176
+ /**
8177
+ * Builds a graph from a list of nodes.
8178
+ * All segments in each node group will be connected with all the segments of
8179
+ * the next group and so on.
8180
+ *
8181
+ * At each connection will be assigned a weight depending on the
8182
+ * segment's byte length.
8183
+ *
8184
+ * @param {Array} nodes Array of object with segments data
8185
+ * @param {Number} version QR Code version
8186
+ * @return {Object} Graph of all possible segments
8187
+ */
8188
+ function buildGraph (nodes, version) {
8189
+ const table = {};
8190
+ const graph = { start: {} };
8191
+ let prevNodeIds = ['start'];
8192
+
8193
+ for (let i = 0; i < nodes.length; i++) {
8194
+ const nodeGroup = nodes[i];
8195
+ const currentNodeIds = [];
8196
+
8197
+ for (let j = 0; j < nodeGroup.length; j++) {
8198
+ const node = nodeGroup[j];
8199
+ const key = '' + i + j;
8200
+
8201
+ currentNodeIds.push(key);
8202
+ table[key] = { node: node, lastCount: 0 };
8203
+ graph[key] = {};
8204
+
8205
+ for (let n = 0; n < prevNodeIds.length; n++) {
8206
+ const prevNodeId = prevNodeIds[n];
8207
+
8208
+ if (table[prevNodeId] && table[prevNodeId].node.mode === node.mode) {
8209
+ graph[prevNodeId][key] =
8210
+ getSegmentBitsLength(table[prevNodeId].lastCount + node.length, node.mode) -
8211
+ getSegmentBitsLength(table[prevNodeId].lastCount, node.mode);
8212
+
8213
+ table[prevNodeId].lastCount += node.length;
8214
+ } else {
8215
+ if (table[prevNodeId]) table[prevNodeId].lastCount = node.length;
8216
+
8217
+ graph[prevNodeId][key] = getSegmentBitsLength(node.length, node.mode) +
8218
+ 4 + mode.getCharCountIndicator(node.mode, version); // switch cost
8219
+ }
8220
+ }
8221
+ }
8222
+
8223
+ prevNodeIds = currentNodeIds;
8224
+ }
8225
+
8226
+ for (let n = 0; n < prevNodeIds.length; n++) {
8227
+ graph[prevNodeIds[n]].end = 0;
8228
+ }
8229
+
8230
+ return { map: graph, table: table }
8231
+ }
8232
+
8233
+ /**
8234
+ * Builds a segment from a specified data and mode.
8235
+ * If a mode is not specified, the more suitable will be used.
8236
+ *
8237
+ * @param {String} data Input data
8238
+ * @param {Mode | String} modesHint Data mode
8239
+ * @return {Segment} Segment
8240
+ */
8241
+ function buildSingleSegment (data, modesHint) {
8242
+ let mode$1;
8243
+ const bestMode = mode.getBestModeForData(data);
8244
+
8245
+ mode$1 = mode.from(modesHint, bestMode);
8246
+
8247
+ // Make sure data can be encoded
8248
+ if (mode$1 !== mode.BYTE && mode$1.bit < bestMode.bit) {
8249
+ throw new Error('"' + data + '"' +
8250
+ ' cannot be encoded with mode ' + mode.toString(mode$1) +
8251
+ '.\n Suggested mode is: ' + mode.toString(bestMode))
8252
+ }
8253
+
8254
+ // Use Mode.BYTE if Kanji support is disabled
8255
+ if (mode$1 === mode.KANJI && !utils$1.isKanjiModeEnabled()) {
8256
+ mode$1 = mode.BYTE;
8257
+ }
8258
+
8259
+ switch (mode$1) {
8260
+ case mode.NUMERIC:
8261
+ return new numericData(data)
8262
+
8263
+ case mode.ALPHANUMERIC:
8264
+ return new alphanumericData(data)
8265
+
8266
+ case mode.KANJI:
8267
+ return new kanjiData(data)
8268
+
8269
+ case mode.BYTE:
8270
+ return new byteData(data)
8271
+ }
8272
+ }
8273
+
8274
+ /**
8275
+ * Builds a list of segments from an array.
8276
+ * Array can contain Strings or Objects with segment's info.
8277
+ *
8278
+ * For each item which is a string, will be generated a segment with the given
8279
+ * string and the more appropriate encoding mode.
8280
+ *
8281
+ * For each item which is an object, will be generated a segment with the given
8282
+ * data and mode.
8283
+ * Objects must contain at least the property "data".
8284
+ * If property "mode" is not present, the more suitable mode will be used.
8285
+ *
8286
+ * @param {Array} array Array of objects with segments data
8287
+ * @return {Array} Array of Segments
8288
+ */
8289
+ exports.fromArray = function fromArray (array) {
8290
+ return array.reduce(function (acc, seg) {
8291
+ if (typeof seg === 'string') {
8292
+ acc.push(buildSingleSegment(seg, null));
8293
+ } else if (seg.data) {
8294
+ acc.push(buildSingleSegment(seg.data, seg.mode));
8295
+ }
8296
+
8297
+ return acc
8298
+ }, [])
8299
+ };
8300
+
8301
+ /**
8302
+ * Builds an optimized sequence of segments from a string,
8303
+ * which will produce the shortest possible bitstream.
8304
+ *
8305
+ * @param {String} data Input string
8306
+ * @param {Number} version QR Code version
8307
+ * @return {Array} Array of segments
8308
+ */
8309
+ exports.fromString = function fromString (data, version) {
8310
+ const segs = getSegmentsFromString(data, utils$1.isKanjiModeEnabled());
8311
+
8312
+ const nodes = buildNodes(segs);
8313
+ const graph = buildGraph(nodes, version);
8314
+ const path = dijkstra_1.find_path(graph.map, 'start', 'end');
8315
+
8316
+ const optimizedSegs = [];
8317
+ for (let i = 1; i < path.length - 1; i++) {
8318
+ optimizedSegs.push(graph.table[path[i]].node);
8319
+ }
8320
+
8321
+ return exports.fromArray(mergeSegments(optimizedSegs))
8322
+ };
8323
+
8324
+ /**
8325
+ * Splits a string in various segments with the modes which
8326
+ * best represent their content.
8327
+ * The produced segments are far from being optimized.
8328
+ * The output of this function is only used to estimate a QR Code version
8329
+ * which may contain the data.
8330
+ *
8331
+ * @param {string} data Input string
8332
+ * @return {Array} Array of segments
8333
+ */
8334
+ exports.rawSplit = function rawSplit (data) {
8335
+ return exports.fromArray(
8336
+ getSegmentsFromString(data, utils$1.isKanjiModeEnabled())
8337
+ )
8338
+ };
8339
+ });
8340
+
8341
+ /**
8342
+ * QRCode for JavaScript
8343
+ *
8344
+ * modified by Ryan Day for nodejs support
8345
+ * Copyright (c) 2011 Ryan Day
8346
+ *
8347
+ * Licensed under the MIT license:
8348
+ * http://www.opensource.org/licenses/mit-license.php
8349
+ *
8350
+ //---------------------------------------------------------------------
8351
+ // QRCode for JavaScript
8352
+ //
8353
+ // Copyright (c) 2009 Kazuhiko Arase
8354
+ //
8355
+ // URL: http://www.d-project.com/
8356
+ //
8357
+ // Licensed under the MIT license:
8358
+ // http://www.opensource.org/licenses/mit-license.php
8359
+ //
8360
+ // The word "QR Code" is registered trademark of
8361
+ // DENSO WAVE INCORPORATED
8362
+ // http://www.denso-wave.com/qrcode/faqpatent-e.html
8363
+ //
8364
+ //---------------------------------------------------------------------
8365
+ */
8366
+
8367
+ /**
8368
+ * Add finder patterns bits to matrix
8369
+ *
8370
+ * @param {BitMatrix} matrix Modules matrix
8371
+ * @param {Number} version QR Code version
8372
+ */
8373
+ function setupFinderPattern (matrix, version) {
8374
+ const size = matrix.size;
8375
+ const pos = finderPattern.getPositions(version);
8376
+
8377
+ for (let i = 0; i < pos.length; i++) {
8378
+ const row = pos[i][0];
8379
+ const col = pos[i][1];
8380
+
8381
+ for (let r = -1; r <= 7; r++) {
8382
+ if (row + r <= -1 || size <= row + r) continue
8383
+
8384
+ for (let c = -1; c <= 7; c++) {
8385
+ if (col + c <= -1 || size <= col + c) continue
8386
+
8387
+ if ((r >= 0 && r <= 6 && (c === 0 || c === 6)) ||
8388
+ (c >= 0 && c <= 6 && (r === 0 || r === 6)) ||
8389
+ (r >= 2 && r <= 4 && c >= 2 && c <= 4)) {
8390
+ matrix.set(row + r, col + c, true, true);
8391
+ } else {
8392
+ matrix.set(row + r, col + c, false, true);
8393
+ }
8394
+ }
8395
+ }
8396
+ }
8397
+ }
8398
+
8399
+ /**
8400
+ * Add timing pattern bits to matrix
8401
+ *
8402
+ * Note: this function must be called before {@link setupAlignmentPattern}
8403
+ *
8404
+ * @param {BitMatrix} matrix Modules matrix
8405
+ */
8406
+ function setupTimingPattern (matrix) {
8407
+ const size = matrix.size;
8408
+
8409
+ for (let r = 8; r < size - 8; r++) {
8410
+ const value = r % 2 === 0;
8411
+ matrix.set(r, 6, value, true);
8412
+ matrix.set(6, r, value, true);
8413
+ }
8414
+ }
8415
+
8416
+ /**
8417
+ * Add alignment patterns bits to matrix
8418
+ *
8419
+ * Note: this function must be called after {@link setupTimingPattern}
8420
+ *
8421
+ * @param {BitMatrix} matrix Modules matrix
8422
+ * @param {Number} version QR Code version
8423
+ */
8424
+ function setupAlignmentPattern (matrix, version) {
8425
+ const pos = alignmentPattern.getPositions(version);
8426
+
8427
+ for (let i = 0; i < pos.length; i++) {
8428
+ const row = pos[i][0];
8429
+ const col = pos[i][1];
8430
+
8431
+ for (let r = -2; r <= 2; r++) {
8432
+ for (let c = -2; c <= 2; c++) {
8433
+ if (r === -2 || r === 2 || c === -2 || c === 2 ||
8434
+ (r === 0 && c === 0)) {
8435
+ matrix.set(row + r, col + c, true, true);
8436
+ } else {
8437
+ matrix.set(row + r, col + c, false, true);
8438
+ }
8439
+ }
8440
+ }
8441
+ }
8442
+ }
8443
+
8444
+ /**
8445
+ * Add version info bits to matrix
8446
+ *
8447
+ * @param {BitMatrix} matrix Modules matrix
8448
+ * @param {Number} version QR Code version
8449
+ */
8450
+ function setupVersionInfo (matrix, version$1) {
8451
+ const size = matrix.size;
8452
+ const bits = version.getEncodedBits(version$1);
8453
+ let row, col, mod;
8454
+
8455
+ for (let i = 0; i < 18; i++) {
8456
+ row = Math.floor(i / 3);
8457
+ col = i % 3 + size - 8 - 3;
8458
+ mod = ((bits >> i) & 1) === 1;
8459
+
8460
+ matrix.set(row, col, mod, true);
8461
+ matrix.set(col, row, mod, true);
8462
+ }
8463
+ }
8464
+
8465
+ /**
8466
+ * Add format info bits to matrix
8467
+ *
8468
+ * @param {BitMatrix} matrix Modules matrix
8469
+ * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
8470
+ * @param {Number} maskPattern Mask pattern reference value
8471
+ */
8472
+ function setupFormatInfo (matrix, errorCorrectionLevel, maskPattern) {
8473
+ const size = matrix.size;
8474
+ const bits = formatInfo.getEncodedBits(errorCorrectionLevel, maskPattern);
8475
+ let i, mod;
8476
+
8477
+ for (i = 0; i < 15; i++) {
8478
+ mod = ((bits >> i) & 1) === 1;
8479
+
8480
+ // vertical
8481
+ if (i < 6) {
8482
+ matrix.set(i, 8, mod, true);
8483
+ } else if (i < 8) {
8484
+ matrix.set(i + 1, 8, mod, true);
8485
+ } else {
8486
+ matrix.set(size - 15 + i, 8, mod, true);
8487
+ }
8488
+
8489
+ // horizontal
8490
+ if (i < 8) {
8491
+ matrix.set(8, size - i - 1, mod, true);
8492
+ } else if (i < 9) {
8493
+ matrix.set(8, 15 - i - 1 + 1, mod, true);
8494
+ } else {
8495
+ matrix.set(8, 15 - i - 1, mod, true);
8496
+ }
8497
+ }
8498
+
8499
+ // fixed module
8500
+ matrix.set(size - 8, 8, 1, true);
8501
+ }
8502
+
8503
+ /**
8504
+ * Add encoded data bits to matrix
8505
+ *
8506
+ * @param {BitMatrix} matrix Modules matrix
8507
+ * @param {Uint8Array} data Data codewords
8508
+ */
8509
+ function setupData (matrix, data) {
8510
+ const size = matrix.size;
8511
+ let inc = -1;
8512
+ let row = size - 1;
8513
+ let bitIndex = 7;
8514
+ let byteIndex = 0;
8515
+
8516
+ for (let col = size - 1; col > 0; col -= 2) {
8517
+ if (col === 6) col--;
8518
+
8519
+ while (true) {
8520
+ for (let c = 0; c < 2; c++) {
8521
+ if (!matrix.isReserved(row, col - c)) {
8522
+ let dark = false;
8523
+
8524
+ if (byteIndex < data.length) {
8525
+ dark = (((data[byteIndex] >>> bitIndex) & 1) === 1);
8526
+ }
8527
+
8528
+ matrix.set(row, col - c, dark);
8529
+ bitIndex--;
8530
+
8531
+ if (bitIndex === -1) {
8532
+ byteIndex++;
8533
+ bitIndex = 7;
8534
+ }
8535
+ }
8536
+ }
8537
+
8538
+ row += inc;
8539
+
8540
+ if (row < 0 || size <= row) {
8541
+ row -= inc;
8542
+ inc = -inc;
8543
+ break
8544
+ }
8545
+ }
8546
+ }
8547
+ }
8548
+
8549
+ /**
8550
+ * Create encoded codewords from data input
8551
+ *
8552
+ * @param {Number} version QR Code version
8553
+ * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
8554
+ * @param {ByteData} data Data input
8555
+ * @return {Uint8Array} Buffer containing encoded codewords
8556
+ */
8557
+ function createData (version, errorCorrectionLevel, segments) {
8558
+ // Prepare data buffer
8559
+ const buffer = new bitBuffer();
8560
+
8561
+ segments.forEach(function (data) {
8562
+ // prefix data with mode indicator (4 bits)
8563
+ buffer.put(data.mode.bit, 4);
8564
+
8565
+ // Prefix data with character count indicator.
8566
+ // The character count indicator is a string of bits that represents the
8567
+ // number of characters that are being encoded.
8568
+ // The character count indicator must be placed after the mode indicator
8569
+ // and must be a certain number of bits long, depending on the QR version
8570
+ // and data mode
8571
+ // @see {@link Mode.getCharCountIndicator}.
8572
+ buffer.put(data.getLength(), mode.getCharCountIndicator(data.mode, version));
8573
+
8574
+ // add binary data sequence to buffer
8575
+ data.write(buffer);
8576
+ });
8577
+
8578
+ // Calculate required number of bits
8579
+ const totalCodewords = utils$1.getSymbolTotalCodewords(version);
8580
+ const ecTotalCodewords = errorCorrectionCode.getTotalCodewordsCount(version, errorCorrectionLevel);
8581
+ const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8;
8582
+
8583
+ // Add a terminator.
8584
+ // If the bit string is shorter than the total number of required bits,
8585
+ // a terminator of up to four 0s must be added to the right side of the string.
8586
+ // If the bit string is more than four bits shorter than the required number of bits,
8587
+ // add four 0s to the end.
8588
+ if (buffer.getLengthInBits() + 4 <= dataTotalCodewordsBits) {
8589
+ buffer.put(0, 4);
8590
+ }
8591
+
8592
+ // If the bit string is fewer than four bits shorter, add only the number of 0s that
8593
+ // are needed to reach the required number of bits.
8594
+
8595
+ // After adding the terminator, if the number of bits in the string is not a multiple of 8,
8596
+ // pad the string on the right with 0s to make the string's length a multiple of 8.
8597
+ while (buffer.getLengthInBits() % 8 !== 0) {
8598
+ buffer.putBit(0);
8599
+ }
8600
+
8601
+ // Add pad bytes if the string is still shorter than the total number of required bits.
8602
+ // Extend the buffer to fill the data capacity of the symbol corresponding to
8603
+ // the Version and Error Correction Level by adding the Pad Codewords 11101100 (0xEC)
8604
+ // and 00010001 (0x11) alternately.
8605
+ const remainingByte = (dataTotalCodewordsBits - buffer.getLengthInBits()) / 8;
8606
+ for (let i = 0; i < remainingByte; i++) {
8607
+ buffer.put(i % 2 ? 0x11 : 0xEC, 8);
8608
+ }
8609
+
8610
+ return createCodewords(buffer, version, errorCorrectionLevel)
8611
+ }
8612
+
8613
+ /**
8614
+ * Encode input data with Reed-Solomon and return codewords with
8615
+ * relative error correction bits
8616
+ *
8617
+ * @param {BitBuffer} bitBuffer Data to encode
8618
+ * @param {Number} version QR Code version
8619
+ * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
8620
+ * @return {Uint8Array} Buffer containing encoded codewords
8621
+ */
8622
+ function createCodewords (bitBuffer, version, errorCorrectionLevel) {
8623
+ // Total codewords for this QR code version (Data + Error correction)
8624
+ const totalCodewords = utils$1.getSymbolTotalCodewords(version);
8625
+
8626
+ // Total number of error correction codewords
8627
+ const ecTotalCodewords = errorCorrectionCode.getTotalCodewordsCount(version, errorCorrectionLevel);
8628
+
8629
+ // Total number of data codewords
8630
+ const dataTotalCodewords = totalCodewords - ecTotalCodewords;
8631
+
8632
+ // Total number of blocks
8633
+ const ecTotalBlocks = errorCorrectionCode.getBlocksCount(version, errorCorrectionLevel);
8634
+
8635
+ // Calculate how many blocks each group should contain
8636
+ const blocksInGroup2 = totalCodewords % ecTotalBlocks;
8637
+ const blocksInGroup1 = ecTotalBlocks - blocksInGroup2;
8638
+
8639
+ const totalCodewordsInGroup1 = Math.floor(totalCodewords / ecTotalBlocks);
8640
+
8641
+ const dataCodewordsInGroup1 = Math.floor(dataTotalCodewords / ecTotalBlocks);
8642
+ const dataCodewordsInGroup2 = dataCodewordsInGroup1 + 1;
8643
+
8644
+ // Number of EC codewords is the same for both groups
8645
+ const ecCount = totalCodewordsInGroup1 - dataCodewordsInGroup1;
8646
+
8647
+ // Initialize a Reed-Solomon encoder with a generator polynomial of degree ecCount
8648
+ const rs = new reedSolomonEncoder(ecCount);
8649
+
8650
+ let offset = 0;
8651
+ const dcData = new Array(ecTotalBlocks);
8652
+ const ecData = new Array(ecTotalBlocks);
8653
+ let maxDataSize = 0;
8654
+ const buffer = new Uint8Array(bitBuffer.buffer);
8655
+
8656
+ // Divide the buffer into the required number of blocks
8657
+ for (let b = 0; b < ecTotalBlocks; b++) {
8658
+ const dataSize = b < blocksInGroup1 ? dataCodewordsInGroup1 : dataCodewordsInGroup2;
8659
+
8660
+ // extract a block of data from buffer
8661
+ dcData[b] = buffer.slice(offset, offset + dataSize);
8662
+
8663
+ // Calculate EC codewords for this data block
8664
+ ecData[b] = rs.encode(dcData[b]);
8665
+
8666
+ offset += dataSize;
8667
+ maxDataSize = Math.max(maxDataSize, dataSize);
8668
+ }
8669
+
8670
+ // Create final data
8671
+ // Interleave the data and error correction codewords from each block
8672
+ const data = new Uint8Array(totalCodewords);
8673
+ let index = 0;
8674
+ let i, r;
8675
+
8676
+ // Add data codewords
8677
+ for (i = 0; i < maxDataSize; i++) {
8678
+ for (r = 0; r < ecTotalBlocks; r++) {
8679
+ if (i < dcData[r].length) {
8680
+ data[index++] = dcData[r][i];
8681
+ }
8682
+ }
8683
+ }
8684
+
8685
+ // Apped EC codewords
8686
+ for (i = 0; i < ecCount; i++) {
8687
+ for (r = 0; r < ecTotalBlocks; r++) {
8688
+ data[index++] = ecData[r][i];
8689
+ }
8690
+ }
8691
+
8692
+ return data
8693
+ }
8694
+
8695
+ /**
8696
+ * Build QR Code symbol
8697
+ *
8698
+ * @param {String} data Input string
8699
+ * @param {Number} version QR Code version
8700
+ * @param {ErrorCorretionLevel} errorCorrectionLevel Error level
8701
+ * @param {MaskPattern} maskPattern Mask pattern
8702
+ * @return {Object} Object containing symbol data
8703
+ */
8704
+ function createSymbol (data, version$1, errorCorrectionLevel, maskPattern$1) {
8705
+ let segments$1;
8706
+
8707
+ if (Array.isArray(data)) {
8708
+ segments$1 = segments.fromArray(data);
8709
+ } else if (typeof data === 'string') {
8710
+ let estimatedVersion = version$1;
8711
+
8712
+ if (!estimatedVersion) {
8713
+ const rawSegments = segments.rawSplit(data);
8714
+
8715
+ // Estimate best version that can contain raw splitted segments
8716
+ estimatedVersion = version.getBestVersionForData(rawSegments, errorCorrectionLevel);
8717
+ }
8718
+
8719
+ // Build optimized segments
8720
+ // If estimated version is undefined, try with the highest version
8721
+ segments$1 = segments.fromString(data, estimatedVersion || 40);
8722
+ } else {
8723
+ throw new Error('Invalid data')
8724
+ }
8725
+
8726
+ // Get the min version that can contain data
8727
+ const bestVersion = version.getBestVersionForData(segments$1, errorCorrectionLevel);
8728
+
8729
+ // If no version is found, data cannot be stored
8730
+ if (!bestVersion) {
8731
+ throw new Error('The amount of data is too big to be stored in a QR Code')
8732
+ }
8733
+
8734
+ // If not specified, use min version as default
8735
+ if (!version$1) {
8736
+ version$1 = bestVersion;
8737
+
8738
+ // Check if the specified version can contain the data
8739
+ } else if (version$1 < bestVersion) {
8740
+ throw new Error('\n' +
8741
+ 'The chosen QR Code version cannot contain this amount of data.\n' +
8742
+ 'Minimum version required to store current data is: ' + bestVersion + '.\n'
8743
+ )
8744
+ }
8745
+
8746
+ const dataBits = createData(version$1, errorCorrectionLevel, segments$1);
8747
+
8748
+ // Allocate matrix buffer
8749
+ const moduleCount = utils$1.getSymbolSize(version$1);
8750
+ const modules = new bitMatrix(moduleCount);
8751
+
8752
+ // Add function modules
8753
+ setupFinderPattern(modules, version$1);
8754
+ setupTimingPattern(modules);
8755
+ setupAlignmentPattern(modules, version$1);
8756
+
8757
+ // Add temporary dummy bits for format info just to set them as reserved.
8758
+ // This is needed to prevent these bits from being masked by {@link MaskPattern.applyMask}
8759
+ // since the masking operation must be performed only on the encoding region.
8760
+ // These blocks will be replaced with correct values later in code.
8761
+ setupFormatInfo(modules, errorCorrectionLevel, 0);
8762
+
8763
+ if (version$1 >= 7) {
8764
+ setupVersionInfo(modules, version$1);
8765
+ }
8766
+
8767
+ // Add data codewords
8768
+ setupData(modules, dataBits);
8769
+
8770
+ if (isNaN(maskPattern$1)) {
8771
+ // Find best mask pattern
8772
+ maskPattern$1 = maskPattern.getBestMask(modules,
8773
+ setupFormatInfo.bind(null, modules, errorCorrectionLevel));
8774
+ }
8775
+
8776
+ // Apply mask pattern
8777
+ maskPattern.applyMask(maskPattern$1, modules);
8778
+
8779
+ // Replace format info bits with correct values
8780
+ setupFormatInfo(modules, errorCorrectionLevel, maskPattern$1);
8781
+
8782
+ return {
8783
+ modules: modules,
8784
+ version: version$1,
8785
+ errorCorrectionLevel: errorCorrectionLevel,
8786
+ maskPattern: maskPattern$1,
8787
+ segments: segments$1
8788
+ }
8789
+ }
8790
+
8791
+ /**
8792
+ * QR Code
8793
+ *
8794
+ * @param {String | Array} data Input data
8795
+ * @param {Object} options Optional configurations
8796
+ * @param {Number} options.version QR Code version
8797
+ * @param {String} options.errorCorrectionLevel Error correction level
8798
+ * @param {Function} options.toSJISFunc Helper func to convert utf8 to sjis
8799
+ */
8800
+ var create$1 = function create (data, options) {
8801
+ if (typeof data === 'undefined' || data === '') {
8802
+ throw new Error('No input text')
8803
+ }
8804
+
8805
+ let errorCorrectionLevel$1 = errorCorrectionLevel.M;
8806
+ let version$1;
8807
+ let mask;
8808
+
8809
+ if (typeof options !== 'undefined') {
8810
+ // Use higher error correction level as default
8811
+ errorCorrectionLevel$1 = errorCorrectionLevel.from(options.errorCorrectionLevel, errorCorrectionLevel.M);
8812
+ version$1 = version.from(options.version);
8813
+ mask = maskPattern.from(options.maskPattern);
8814
+
8815
+ if (options.toSJISFunc) {
8816
+ utils$1.setToSJISFunction(options.toSJISFunc);
8817
+ }
8818
+ }
8819
+
8820
+ return createSymbol(data, version$1, errorCorrectionLevel$1, mask)
8821
+ };
8822
+
8823
+ var qrcode = {
8824
+ create: create$1
8825
+ };
8826
+
8827
+ var utils = createCommonjsModule(function (module, exports) {
8828
+ function hex2rgba (hex) {
8829
+ if (typeof hex === 'number') {
8830
+ hex = hex.toString();
8831
+ }
8832
+
8833
+ if (typeof hex !== 'string') {
8834
+ throw new Error('Color should be defined as hex string')
8835
+ }
8836
+
8837
+ let hexCode = hex.slice().replace('#', '').split('');
8838
+ if (hexCode.length < 3 || hexCode.length === 5 || hexCode.length > 8) {
8839
+ throw new Error('Invalid hex color: ' + hex)
8840
+ }
8841
+
8842
+ // Convert from short to long form (fff -> ffffff)
8843
+ if (hexCode.length === 3 || hexCode.length === 4) {
8844
+ hexCode = Array.prototype.concat.apply([], hexCode.map(function (c) {
8845
+ return [c, c]
8846
+ }));
8847
+ }
8848
+
8849
+ // Add default alpha value
8850
+ if (hexCode.length === 6) hexCode.push('F', 'F');
8851
+
8852
+ const hexValue = parseInt(hexCode.join(''), 16);
8853
+
8854
+ return {
8855
+ r: (hexValue >> 24) & 255,
8856
+ g: (hexValue >> 16) & 255,
8857
+ b: (hexValue >> 8) & 255,
8858
+ a: hexValue & 255,
8859
+ hex: '#' + hexCode.slice(0, 6).join('')
8860
+ }
8861
+ }
8862
+
8863
+ exports.getOptions = function getOptions (options) {
8864
+ if (!options) options = {};
8865
+ if (!options.color) options.color = {};
8866
+
8867
+ const margin = typeof options.margin === 'undefined' ||
8868
+ options.margin === null ||
8869
+ options.margin < 0
8870
+ ? 4
8871
+ : options.margin;
8872
+
8873
+ const width = options.width && options.width >= 21 ? options.width : undefined;
8874
+ const scale = options.scale || 4;
8875
+
8876
+ return {
8877
+ width: width,
8878
+ scale: width ? 4 : scale,
8879
+ margin: margin,
8880
+ color: {
8881
+ dark: hex2rgba(options.color.dark || '#000000ff'),
8882
+ light: hex2rgba(options.color.light || '#ffffffff')
8883
+ },
8884
+ type: options.type,
8885
+ rendererOpts: options.rendererOpts || {}
8886
+ }
8887
+ };
8888
+
8889
+ exports.getScale = function getScale (qrSize, opts) {
8890
+ return opts.width && opts.width >= qrSize + opts.margin * 2
8891
+ ? opts.width / (qrSize + opts.margin * 2)
8892
+ : opts.scale
8893
+ };
8894
+
8895
+ exports.getImageWidth = function getImageWidth (qrSize, opts) {
8896
+ const scale = exports.getScale(qrSize, opts);
8897
+ return Math.floor((qrSize + opts.margin * 2) * scale)
8898
+ };
8899
+
8900
+ exports.qrToImageData = function qrToImageData (imgData, qr, opts) {
8901
+ const size = qr.modules.size;
8902
+ const data = qr.modules.data;
8903
+ const scale = exports.getScale(size, opts);
8904
+ const symbolSize = Math.floor((size + opts.margin * 2) * scale);
8905
+ const scaledMargin = opts.margin * scale;
8906
+ const palette = [opts.color.light, opts.color.dark];
8907
+
8908
+ for (let i = 0; i < symbolSize; i++) {
8909
+ for (let j = 0; j < symbolSize; j++) {
8910
+ let posDst = (i * symbolSize + j) * 4;
8911
+ let pxColor = opts.color.light;
8912
+
8913
+ if (i >= scaledMargin && j >= scaledMargin &&
8914
+ i < symbolSize - scaledMargin && j < symbolSize - scaledMargin) {
8915
+ const iSrc = Math.floor((i - scaledMargin) / scale);
8916
+ const jSrc = Math.floor((j - scaledMargin) / scale);
8917
+ pxColor = palette[data[iSrc * size + jSrc] ? 1 : 0];
8918
+ }
8919
+
8920
+ imgData[posDst++] = pxColor.r;
8921
+ imgData[posDst++] = pxColor.g;
8922
+ imgData[posDst++] = pxColor.b;
8923
+ imgData[posDst] = pxColor.a;
8924
+ }
8925
+ }
8926
+ };
8927
+ });
8928
+
8929
+ var canvas = createCommonjsModule(function (module, exports) {
8930
+ function clearCanvas (ctx, canvas, size) {
8931
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
8932
+
8933
+ if (!canvas.style) canvas.style = {};
8934
+ canvas.height = size;
8935
+ canvas.width = size;
8936
+ canvas.style.height = size + 'px';
8937
+ canvas.style.width = size + 'px';
8938
+ }
8939
+
8940
+ function getCanvasElement () {
8941
+ try {
8942
+ return document.createElement('canvas')
8943
+ } catch (e) {
8944
+ throw new Error('You need to specify a canvas element')
8945
+ }
8946
+ }
8947
+
8948
+ exports.render = function render (qrData, canvas, options) {
8949
+ let opts = options;
8950
+ let canvasEl = canvas;
8951
+
8952
+ if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {
8953
+ opts = canvas;
8954
+ canvas = undefined;
8955
+ }
8956
+
8957
+ if (!canvas) {
8958
+ canvasEl = getCanvasElement();
8959
+ }
8960
+
8961
+ opts = utils.getOptions(opts);
8962
+ const size = utils.getImageWidth(qrData.modules.size, opts);
8963
+
8964
+ const ctx = canvasEl.getContext('2d');
8965
+ const image = ctx.createImageData(size, size);
8966
+ utils.qrToImageData(image.data, qrData, opts);
8967
+
8968
+ clearCanvas(ctx, canvasEl, size);
8969
+ ctx.putImageData(image, 0, 0);
8970
+
8971
+ return canvasEl
8972
+ };
8973
+
8974
+ exports.renderToDataURL = function renderToDataURL (qrData, canvas, options) {
8975
+ let opts = options;
8976
+
8977
+ if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {
8978
+ opts = canvas;
8979
+ canvas = undefined;
8980
+ }
8981
+
8982
+ if (!opts) opts = {};
8983
+
8984
+ const canvasEl = exports.render(qrData, canvas, opts);
8985
+
8986
+ const type = opts.type || 'image/png';
8987
+ const rendererOpts = opts.rendererOpts || {};
8988
+
8989
+ return canvasEl.toDataURL(type, rendererOpts.quality)
8990
+ };
8991
+ });
8992
+
8993
+ function getColorAttrib (color, attrib) {
8994
+ const alpha = color.a / 255;
8995
+ const str = attrib + '="' + color.hex + '"';
8996
+
8997
+ return alpha < 1
8998
+ ? str + ' ' + attrib + '-opacity="' + alpha.toFixed(2).slice(1) + '"'
8999
+ : str
9000
+ }
9001
+
9002
+ function svgCmd (cmd, x, y) {
9003
+ let str = cmd + x;
9004
+ if (typeof y !== 'undefined') str += ' ' + y;
9005
+
9006
+ return str
9007
+ }
9008
+
9009
+ function qrToPath (data, size, margin) {
9010
+ let path = '';
9011
+ let moveBy = 0;
9012
+ let newRow = false;
9013
+ let lineLength = 0;
9014
+
9015
+ for (let i = 0; i < data.length; i++) {
9016
+ const col = Math.floor(i % size);
9017
+ const row = Math.floor(i / size);
9018
+
9019
+ if (!col && !newRow) newRow = true;
9020
+
9021
+ if (data[i]) {
9022
+ lineLength++;
9023
+
9024
+ if (!(i > 0 && col > 0 && data[i - 1])) {
9025
+ path += newRow
9026
+ ? svgCmd('M', col + margin, 0.5 + row + margin)
9027
+ : svgCmd('m', moveBy, 0);
9028
+
9029
+ moveBy = 0;
9030
+ newRow = false;
9031
+ }
9032
+
9033
+ if (!(col + 1 < size && data[i + 1])) {
9034
+ path += svgCmd('h', lineLength);
9035
+ lineLength = 0;
9036
+ }
9037
+ } else {
9038
+ moveBy++;
9039
+ }
9040
+ }
9041
+
9042
+ return path
9043
+ }
9044
+
9045
+ var render = function render (qrData, options, cb) {
9046
+ const opts = utils.getOptions(options);
9047
+ const size = qrData.modules.size;
9048
+ const data = qrData.modules.data;
9049
+ const qrcodesize = size + opts.margin * 2;
9050
+
9051
+ const bg = !opts.color.light.a
9052
+ ? ''
9053
+ : '<path ' + getColorAttrib(opts.color.light, 'fill') +
9054
+ ' d="M0 0h' + qrcodesize + 'v' + qrcodesize + 'H0z"/>';
9055
+
9056
+ const path =
9057
+ '<path ' + getColorAttrib(opts.color.dark, 'stroke') +
9058
+ ' d="' + qrToPath(data, size, opts.margin) + '"/>';
9059
+
9060
+ const viewBox = 'viewBox="' + '0 0 ' + qrcodesize + ' ' + qrcodesize + '"';
9061
+
9062
+ const width = !opts.width ? '' : 'width="' + opts.width + '" height="' + opts.width + '" ';
9063
+
9064
+ const svgTag = '<svg xmlns="http://www.w3.org/2000/svg" ' + width + viewBox + ' shape-rendering="crispEdges">' + bg + path + '</svg>\n';
9065
+
9066
+ if (typeof cb === 'function') {
9067
+ cb(null, svgTag);
9068
+ }
9069
+
9070
+ return svgTag
9071
+ };
9072
+
9073
+ var svgTag = {
9074
+ render: render
9075
+ };
9076
+
9077
+ function renderCanvas (renderFunc, canvas, text, opts, cb) {
9078
+ const args = [].slice.call(arguments, 1);
9079
+ const argsNum = args.length;
9080
+ const isLastArgCb = typeof args[argsNum - 1] === 'function';
9081
+
9082
+ if (!isLastArgCb && !canPromise()) {
9083
+ throw new Error('Callback required as last argument')
9084
+ }
9085
+
9086
+ if (isLastArgCb) {
9087
+ if (argsNum < 2) {
9088
+ throw new Error('Too few arguments provided')
9089
+ }
9090
+
9091
+ if (argsNum === 2) {
9092
+ cb = text;
9093
+ text = canvas;
9094
+ canvas = opts = undefined;
9095
+ } else if (argsNum === 3) {
9096
+ if (canvas.getContext && typeof cb === 'undefined') {
9097
+ cb = opts;
9098
+ opts = undefined;
9099
+ } else {
9100
+ cb = opts;
9101
+ opts = text;
9102
+ text = canvas;
9103
+ canvas = undefined;
9104
+ }
9105
+ }
9106
+ } else {
9107
+ if (argsNum < 1) {
9108
+ throw new Error('Too few arguments provided')
9109
+ }
9110
+
9111
+ if (argsNum === 1) {
9112
+ text = canvas;
9113
+ canvas = opts = undefined;
9114
+ } else if (argsNum === 2 && !canvas.getContext) {
9115
+ opts = text;
9116
+ text = canvas;
9117
+ canvas = undefined;
9118
+ }
9119
+
9120
+ return new Promise(function (resolve, reject) {
9121
+ try {
9122
+ const data = qrcode.create(text, opts);
9123
+ resolve(renderFunc(data, canvas, opts));
9124
+ } catch (e) {
9125
+ reject(e);
9126
+ }
9127
+ })
9128
+ }
9129
+
9130
+ try {
9131
+ const data = qrcode.create(text, opts);
9132
+ cb(null, renderFunc(data, canvas, opts));
9133
+ } catch (e) {
9134
+ cb(e);
9135
+ }
9136
+ }
9137
+
9138
+ var create = qrcode.create;
9139
+ var toCanvas = renderCanvas.bind(null, canvas.render);
9140
+ var toDataURL = renderCanvas.bind(null, canvas.renderToDataURL);
9141
+
9142
+ // only svg for now.
9143
+ var toString_1 = renderCanvas.bind(null, function (data, _, opts) {
9144
+ return svgTag.render(data, opts)
9145
+ });
9146
+
9147
+ var browser = {
9148
+ create: create,
9149
+ toCanvas: toCanvas,
9150
+ toDataURL: toDataURL,
9151
+ toString: toString_1
9152
+ };
9153
+
9154
+ const mobileRedirectCss = ".qr-canvas{max-height:60vh;max-width:80vw;text-align:center}.qr-canvas>canvas{width:100%;height:100%}";
9155
+
9156
+ const MobileRedirect = class {
9157
+ constructor(hostRef) {
9158
+ registerInstance(this, hostRef);
9159
+ this.apiErrorEvent = createEvent(this, "apiError", 7);
9160
+ this.delay = ms => new Promise(res => setTimeout(res, ms));
9161
+ this.infoTextTop = undefined;
9162
+ this.infoTextBottom = undefined;
9163
+ this.contact = undefined;
9164
+ this.invalidValue = undefined;
9165
+ this.waitingMobile = undefined;
9166
+ this.orderStatus = undefined;
9167
+ this.redirectLink = undefined;
9168
+ this.qrCode = undefined;
9169
+ this.prefilledPhone = false;
9170
+ this.apiCall = new ApiCall();
9171
+ this.invalidValue = false;
9172
+ this.waitingMobile = false;
9173
+ }
9174
+ async componentWillLoad() {
9175
+ this.infoTextTop = MobileRedirectValues.InfoTop;
9176
+ this.infoTextBottom = MobileRedirectValues.InfoBottom;
9177
+ let envUri = state.environment == 'PROD' ? 'ect' : 'test';
9178
+ let baseUri = state.hasIdBack ? 'https://onmd.id-kyc.com/' : 'https://onro.id-kyc.com/';
9179
+ this.redirectLink = baseUri + envUri + '/identification?redirectId=' + state.redirectId;
9180
+ if (state.phoneNumber != '') {
9181
+ this.contact = state.phoneNumber;
9182
+ this.prefilledPhone = true;
9183
+ }
9184
+ var self = this;
9185
+ browser.toDataURL(this.redirectLink, { type: 'image/png', errorCorrectionLevel: 'M', scale: 6 }, function (error, url) {
9186
+ if (error)
9187
+ console.error(error);
9188
+ self.qrCode = url;
9189
+ });
9190
+ }
9191
+ componentWillRender() { }
9192
+ async componentDidLoad() {
9193
+ await this.delay(5000);
9194
+ await this.checkStatus();
9195
+ while (this.orderStatus == OrderStatuses.Capturing || this.orderStatus == OrderStatuses.Waiting) {
9196
+ await this.checkStatus();
9197
+ await this.delay(5000);
9198
+ }
9199
+ }
9200
+ async checkStatus() {
9201
+ this.orderStatus = await this.apiCall.GetStatus(state.requestId);
9202
+ if (this.orderStatus == OrderStatuses.FinishedCapturing) {
9203
+ this.waitingMobile = false;
9204
+ state.flowStatus = FlowStatus.COMPLETE;
9205
+ }
9206
+ if (this.orderStatus == OrderStatuses.NotFound) {
9207
+ this.apiErrorEvent.emit({ message: 'No order was started for this process.' });
9208
+ }
9209
+ if (this.orderStatus == OrderStatuses.Capturing) {
9210
+ this.infoTextTop = MobileRedirectValues.InfoWaiting;
9211
+ this.waitingMobile = true;
9212
+ }
9213
+ }
9214
+ async buttonClick() {
9215
+ if (this.contact == '' || this.contact.length != 10) {
9216
+ return;
9217
+ }
9218
+ this.waitingMobile = true;
9219
+ this.infoTextTop = MobileRedirectValues.InfoWaiting;
9220
+ try {
9221
+ await this.apiCall.SendLink(this.redirectLink, this.contact);
9222
+ }
9223
+ catch (e) {
9224
+ this.apiErrorEvent.emit(e);
9225
+ }
9226
+ }
9227
+ handleChangeContact(ev) {
9228
+ let value = ev.target ? ev.target.value : '';
9229
+ this.contact = value.replace(/\D/g, '');
9230
+ if (this.contact.length > 10) {
9231
+ this.contact = this.contact.substring(0, 10);
9232
+ }
9233
+ this.invalidValue = this.contact.length != 10;
9234
+ ev.target.value = this.contact;
9235
+ }
9236
+ render() {
9237
+ return (h("div", { class: "container" }, h("div", { class: "row" }, h("div", { hidden: this.waitingMobile }, h("div", { class: "text-center" }, h("p", { class: "font-size-2" }, this.infoTextTop)), h("div", { class: "qr-canvas align-center" }, h("img", { src: this.qrCode })), h("div", { class: "text-center" }, h("p", { class: "font-size-2" }, this.infoTextBottom)), h("div", { class: "input-container mb-15" }, h("label", { class: "font-size-18 mb-1 color-red", hidden: this.invalidValue == false }, h("b", null, MobileRedirectValues.Validation)), h("input", { type: "text", id: "codeInput", class: "main-input", disabled: this.prefilledPhone, value: this.contact, onInput: ev => this.handleChangeContact(ev) })), h("div", { class: "pos-relative" }, h("div", { class: "btn-buletin" }, h("button", { class: "main-button", onClick: () => this.buttonClick() }, "Trimite"), h("p", { class: "main-text font-size-18 text-right mb-0" }, MobileRedirectValues.FooterText)))), h("div", { hidden: this.waitingMobile == false }, h("div", { class: "text-center" }, h("p", { class: "font-size-2" }, this.infoTextTop))))));
9238
+ }
9239
+ };
9240
+ MobileRedirect.style = mobileRedirectCss;
9241
+
5769
9242
  const selfieCaptureCss = "";
5770
9243
 
5771
9244
  const SelfieCapture = class {
@@ -6097,4 +9570,4 @@ const UserLiveness = class {
6097
9570
  };
6098
9571
  UserLiveness.style = userLivenessCss;
6099
9572
 
6100
- export { AgreementCheck as agreement_check, AgreementInfo as agreement_info, Camera as camera_comp, CaptureError as capture_error, EndRedirect as end_redirect, ErrorEnd as error_end, HowToInfo as how_to_info, IdBackCapture as id_back_capture, IdCapture as id_capture, IdDoubleSide as id_double_side, IdSingleSide as id_single_side, IdentificationComponent as identification_component, LandingValidation as landing_validation, SelfieCapture as selfie_capture, SmsCodeValidation as sms_code_validation, UserLiveness as user_liveness };
9573
+ export { AgreementCheck as agreement_check, AgreementInfo as agreement_info, Camera as camera_comp, CaptureError as capture_error, EndRedirect as end_redirect, ErrorEnd as error_end, HowToInfo as how_to_info, IdBackCapture as id_back_capture, IdCapture as id_capture, IdDoubleSide as id_double_side, IdSingleSide as id_single_side, IdentificationComponent as identification_component, LandingValidation as landing_validation, MobileRedirect as mobile_redirect, SelfieCapture as selfie_capture, SmsCodeValidation as sms_code_validation, UserLiveness as user_liveness };