@dynamicore/jumio-sdk 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,86 +1,81 @@
1
1
  import axios from 'axios';
2
2
  import { useMemo, useState, useRef, useEffect, useCallback } from 'react';
3
3
 
4
- // src/core/errors.ts
5
- var JumioError = class extends Error {
6
- isJumioError = true;
7
- statusCode;
8
- rawData;
9
- code;
10
- constructor(message, options) {
11
- super(message);
12
- this.name = "JumioError";
13
- this.statusCode = options?.statusCode;
14
- this.rawData = options?.rawData;
15
- this.code = options?.code;
16
- if (options?.cause) {
17
- this.cause = options.cause;
18
- }
19
- }
20
- };
21
- var JumioTimeoutError = class extends JumioError {
22
- constructor(message = "El servicio de verificaci\xF3n de Jumio excedi\xF3 el tiempo l\xEDmite de espera.", rawData) {
23
- super(message, { code: "TIMEOUT", rawData });
24
- this.name = "JumioTimeoutError";
25
- }
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __esm = (fn, res) => function __init() {
7
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
26
8
  };
27
- var JumioNetworkError = class extends JumioError {
28
- constructor(message = "No fue posible comunicarse con los servidores de validaci\xF3n de identidad.", cause) {
29
- super(message, { code: "NETWORK_ERROR", cause });
30
- this.name = "JumioNetworkError";
31
- }
32
- };
33
- var JumioValidationError = class extends JumioError {
34
- constructor(message = "El documento no pudo ser validado o fue rechazado por Jumio.", rawData) {
35
- super(message, { code: "VALIDATION_FAILED", rawData });
36
- this.name = "JumioValidationError";
37
- }
38
- };
39
- var JumioImageProcessingError = class extends JumioError {
40
- constructor(message, cause) {
41
- super(message, { code: "IMAGE_PROCESSING_ERROR", cause });
42
- this.name = "JumioImageProcessingError";
43
- }
44
- };
45
- var JumioPollingTimeoutError = class extends JumioError {
46
- attempts;
47
- constructor(attempts, message = "La validaci\xF3n sigue en proceso. Por favor verifica nuevamente m\xE1s tarde.", rawData) {
48
- super(message, { code: "POLLING_TIMEOUT", rawData });
49
- this.name = "JumioPollingTimeoutError";
50
- this.attempts = attempts;
51
- }
52
- };
53
- var JumioAbortError = class extends JumioError {
54
- constructor(message = "La operaci\xF3n de validaci\xF3n de Jumio fue cancelada.") {
55
- super(message, { code: "ABORTED" });
56
- this.name = "JumioAbortError";
57
- }
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
58
12
  };
13
+
14
+ // src/core/errors.ts
59
15
  function isJumioError(error) {
60
16
  return error instanceof JumioError || typeof error === "object" && error !== null && "isJumioError" in error && error.isJumioError === true;
61
17
  }
18
+ var JumioError, JumioTimeoutError, JumioNetworkError, JumioValidationError, JumioImageProcessingError, JumioPollingTimeoutError, JumioAbortError;
19
+ var init_errors = __esm({
20
+ "src/core/errors.ts"() {
21
+ JumioError = class extends Error {
22
+ isJumioError = true;
23
+ statusCode;
24
+ rawData;
25
+ code;
26
+ constructor(message, options) {
27
+ super(message);
28
+ this.name = "JumioError";
29
+ this.statusCode = options?.statusCode;
30
+ this.rawData = options?.rawData;
31
+ this.code = options?.code;
32
+ if (options?.cause) {
33
+ this.cause = options.cause;
34
+ }
35
+ }
36
+ };
37
+ JumioTimeoutError = class extends JumioError {
38
+ constructor(message = "El servicio de verificaci\xF3n de Jumio excedi\xF3 el tiempo l\xEDmite de espera.", rawData) {
39
+ super(message, { code: "TIMEOUT", rawData });
40
+ this.name = "JumioTimeoutError";
41
+ }
42
+ };
43
+ JumioNetworkError = class extends JumioError {
44
+ constructor(message = "No fue posible comunicarse con los servidores de validaci\xF3n de identidad.", cause) {
45
+ super(message, { code: "NETWORK_ERROR", cause });
46
+ this.name = "JumioNetworkError";
47
+ }
48
+ };
49
+ JumioValidationError = class extends JumioError {
50
+ constructor(message = "El documento no pudo ser validado o fue rechazado por Jumio.", rawData) {
51
+ super(message, { code: "VALIDATION_FAILED", rawData });
52
+ this.name = "JumioValidationError";
53
+ }
54
+ };
55
+ JumioImageProcessingError = class extends JumioError {
56
+ constructor(message, cause) {
57
+ super(message, { code: "IMAGE_PROCESSING_ERROR", cause });
58
+ this.name = "JumioImageProcessingError";
59
+ }
60
+ };
61
+ JumioPollingTimeoutError = class extends JumioError {
62
+ attempts;
63
+ constructor(attempts, message = "La validaci\xF3n sigue en proceso. Por favor verifica nuevamente m\xE1s tarde.", rawData) {
64
+ super(message, { code: "POLLING_TIMEOUT", rawData });
65
+ this.name = "JumioPollingTimeoutError";
66
+ this.attempts = attempts;
67
+ }
68
+ };
69
+ JumioAbortError = class extends JumioError {
70
+ constructor(message = "La operaci\xF3n de validaci\xF3n de Jumio fue cancelada.") {
71
+ super(message, { code: "ABORTED" });
72
+ this.name = "JumioAbortError";
73
+ }
74
+ };
75
+ }
76
+ });
62
77
 
63
78
  // src/core/envelope.ts
64
- var FINAL_JUMIO_STATUSES = [
65
- "PROCESSED",
66
- "APPROVED_VERIFIED",
67
- "REJECTED",
68
- "FAILED",
69
- "ERROR",
70
- "DENIED",
71
- "EXPIRED",
72
- "ABANDONED",
73
- "DONE",
74
- "COMPLETED",
75
- "NOT_READABLE",
76
- "FRAUD",
77
- "UNSUPPORTED_ID_TYPE"
78
- ];
79
- var APPROVED_JUMIO_STATUSES = [
80
- "APPROVED_VERIFIED",
81
- "DONE",
82
- "COMPLETED"
83
- ];
84
79
  function toLowerText(value) {
85
80
  return String(value ?? "").trim().toLowerCase();
86
81
  }
@@ -88,10 +83,13 @@ function toUpperText(value) {
88
83
  return String(value ?? "").trim().toUpperCase();
89
84
  }
90
85
  function extractEnvelopeData(responseData) {
91
- if (responseData && typeof responseData === "object" && "data" in responseData) {
92
- const candidate = responseData.data;
93
- if (candidate !== void 0) {
94
- return candidate;
86
+ if (responseData && typeof responseData === "object") {
87
+ const obj = responseData;
88
+ if ("data" in obj && obj.data !== void 0) {
89
+ return obj.data;
90
+ }
91
+ if ("values" in obj && obj.values !== void 0) {
92
+ return obj.values;
95
93
  }
96
94
  }
97
95
  return responseData;
@@ -162,6 +160,48 @@ function resolveVerificationValidity(data, fallbackStatus) {
162
160
  }
163
161
  return isApprovedJumioStatus(fallbackStatus);
164
162
  }
163
+ function encodeUrlToBase64UrlSafe(url) {
164
+ try {
165
+ let base64;
166
+ if (typeof Buffer !== "undefined") {
167
+ base64 = Buffer.from(url, "utf-8").toString("base64");
168
+ } else if (typeof TextEncoder !== "undefined") {
169
+ const encoder = new TextEncoder();
170
+ const data = encoder.encode(url);
171
+ base64 = btoa(String.fromCharCode(...new Uint8Array(data)));
172
+ } else {
173
+ base64 = btoa(url);
174
+ }
175
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
176
+ } catch {
177
+ return null;
178
+ }
179
+ }
180
+ var FINAL_JUMIO_STATUSES, APPROVED_JUMIO_STATUSES;
181
+ var init_envelope = __esm({
182
+ "src/core/envelope.ts"() {
183
+ FINAL_JUMIO_STATUSES = [
184
+ "PROCESSED",
185
+ "APPROVED_VERIFIED",
186
+ "REJECTED",
187
+ "FAILED",
188
+ "ERROR",
189
+ "DENIED",
190
+ "EXPIRED",
191
+ "ABANDONED",
192
+ "DONE",
193
+ "COMPLETED",
194
+ "NOT_READABLE",
195
+ "FRAUD",
196
+ "UNSUPPORTED_ID_TYPE"
197
+ ];
198
+ APPROVED_JUMIO_STATUSES = [
199
+ "APPROVED_VERIFIED",
200
+ "DONE",
201
+ "COMPLETED"
202
+ ];
203
+ }
204
+ });
165
205
 
166
206
  // src/core/retry.ts
167
207
  function delay(ms, signal) {
@@ -233,8 +273,268 @@ async function withRetry(operation, options = {}) {
233
273
  }
234
274
  throw lastError;
235
275
  }
276
+ var init_retry = __esm({
277
+ "src/core/retry.ts"() {
278
+ init_envelope();
279
+ init_errors();
280
+ }
281
+ });
282
+
283
+ // src/core/webflow.ts
284
+ var webflow_exports = {};
285
+ __export(webflow_exports, {
286
+ buildRedirectUrl: () => buildRedirectUrl,
287
+ parseWebflowReturnParams: () => parseWebflowReturnParams,
288
+ pollWebflowStatus: () => pollWebflowStatus,
289
+ resolveWebflowResult: () => resolveWebflowResult,
290
+ startWebflowSession: () => startWebflowSession
291
+ });
292
+ function buildRedirectUrl(returnUrl, proxyUrl) {
293
+ if (!proxyUrl) {
294
+ return returnUrl;
295
+ }
296
+ const encoded = encodeUrlToBase64UrlSafe(returnUrl);
297
+ if (!encoded) {
298
+ throw new JumioValidationError(
299
+ `No fue posible codificar la URL de retorno: "${returnUrl}"`
300
+ );
301
+ }
302
+ const normalizedProxy = proxyUrl.endsWith("/") ? proxyUrl : `${proxyUrl}/`;
303
+ return `${normalizedProxy}${encoded}`;
304
+ }
305
+ function parseWebflowReturnParams(source) {
306
+ let searchString;
307
+ if (!source) {
308
+ if (typeof window !== "undefined" && window.location) {
309
+ searchString = window.location.search;
310
+ } else {
311
+ return { allParams: {} };
312
+ }
313
+ } else if (typeof source === "string") {
314
+ const questionIdx = source.indexOf("?");
315
+ searchString = questionIdx >= 0 ? source.slice(questionIdx) : "";
316
+ } else if (source instanceof URLSearchParams) {
317
+ searchString = `?${source.toString()}`;
318
+ } else {
319
+ const hrefSearch = source.href ? (() => {
320
+ try {
321
+ return new URL(source.href).search;
322
+ } catch {
323
+ return "";
324
+ }
325
+ })() : "";
326
+ searchString = source.search ?? hrefSearch;
327
+ }
328
+ const params = new URLSearchParams(searchString);
329
+ const allParams = {};
330
+ params.forEach((value, key) => {
331
+ allParams[key] = value;
332
+ });
333
+ const accountId = params.get("accountId") ?? void 0;
334
+ let workflowId = params.get("workflowExecutionId") ?? params.get("workflowId") ?? void 0;
335
+ const rawStatus = params.get("status") ?? void 0;
336
+ if (rawStatus && (!accountId || !workflowId)) {
337
+ const statusParts = rawStatus.split("?");
338
+ const nestedSearch = statusParts.length > 1 ? `?${statusParts.slice(1).join("?")}` : "";
339
+ if (nestedSearch && nestedSearch !== "?") {
340
+ const nestedParams = new URLSearchParams(nestedSearch);
341
+ nestedParams.forEach((value, key) => {
342
+ if (!allParams[key]) allParams[key] = value;
343
+ });
344
+ if (!workflowId) {
345
+ workflowId = nestedParams.get("workflowExecutionId") ?? nestedParams.get("workflowId") ?? workflowId;
346
+ }
347
+ }
348
+ }
349
+ return {
350
+ accountId: accountId || void 0,
351
+ workflowId: workflowId || void 0,
352
+ rawStatus,
353
+ allParams
354
+ };
355
+ }
356
+ function resolveWebflowResult(rawData, accountId, workflowId) {
357
+ if (!rawData || typeof rawData !== "object") return null;
358
+ const data = rawData;
359
+ if (data.valid === true) {
360
+ return {
361
+ valid: true,
362
+ status: String(data.workflowStatus ?? data.status ?? "APPROVED_VERIFIED"),
363
+ decision: data.decision,
364
+ extraction: data.extraction,
365
+ accountId,
366
+ workflowId,
367
+ data: rawData
368
+ };
369
+ }
370
+ if (data.valid === false) {
371
+ return {
372
+ valid: false,
373
+ status: String(data.workflowStatus ?? data.status ?? "REJECTED"),
374
+ decision: data.decision,
375
+ accountId,
376
+ workflowId,
377
+ data: rawData,
378
+ errorMessage: extractJumioMessage(rawData) || "El documento fue rechazado durante la verificacion."
379
+ };
380
+ }
381
+ const capData = data;
382
+ const decisionType = capData?.decision?.type;
383
+ const extractionArr = capData?.capabilities?.extraction ?? [];
384
+ const extraction = extractionArr[0];
385
+ const isExtractionEmpty = extraction !== void 0 && Object.keys(extraction).length === 0;
386
+ if (decisionType === "REJECTED") {
387
+ return {
388
+ valid: false,
389
+ status: "REJECTED",
390
+ decision: decisionType,
391
+ accountId,
392
+ workflowId,
393
+ data: rawData,
394
+ errorMessage: extractJumioMessage(rawData) || "El documento fue rechazado por Jumio."
395
+ };
396
+ }
397
+ if (extraction && !isExtractionEmpty) {
398
+ const isApproved = decisionType === "PASSED" || decisionType === "WARNING";
399
+ return {
400
+ valid: isApproved,
401
+ status: isApproved ? decisionType ?? "PASSED" : decisionType ?? "REJECTED",
402
+ decision: decisionType,
403
+ extraction,
404
+ accountId,
405
+ workflowId,
406
+ data: rawData,
407
+ ...!isApproved ? {
408
+ errorMessage: extractJumioMessage(rawData) || "La verificacion no fue aprobada."
409
+ } : {}
410
+ };
411
+ }
412
+ return null;
413
+ }
414
+ async function pollWebflowStatus(http, params, options = {}) {
415
+ const config = http.getConfig();
416
+ const maxAttempts = options.maxAttempts ?? config.maxPollingAttempts ?? 20;
417
+ const intervalMs = options.pollingIntervalMs ?? config.pollingIntervalMs ?? 1e4;
418
+ const signal = options.signal;
419
+ let lastRawData = {};
420
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
421
+ if (signal?.aborted) {
422
+ throw new JumioAbortError();
423
+ }
424
+ const responseData = await withRetry(
425
+ () => http.getVerificationStatus(params.accountId, params.workflowId, {
426
+ signal,
427
+ timeout: config.statusTimeout,
428
+ clientId: params.clientId
429
+ }),
430
+ {
431
+ maxRetries: config.maxRetries ?? 3,
432
+ initialDelayMs: config.retryDelayMs ?? 800,
433
+ signal
434
+ }
435
+ );
436
+ const firstLevel = extractEnvelopeData(responseData);
437
+ const statusData = extractNestedData(firstLevel) ?? {};
438
+ lastRawData = statusData;
439
+ options.onAttempt?.(attempt, maxAttempts, statusData);
440
+ const result = resolveWebflowResult(
441
+ statusData,
442
+ params.accountId,
443
+ params.workflowId
444
+ );
445
+ if (result !== null) {
446
+ return result;
447
+ }
448
+ if (attempt < maxAttempts) {
449
+ await delay(intervalMs, signal);
450
+ }
451
+ }
452
+ const lastMessage = extractJumioMessage(lastRawData) || "La verificacion Jumio sigue en proceso. Intenta nuevamente en unos momentos.";
453
+ throw new JumioPollingTimeoutError(maxAttempts, lastMessage, lastRawData);
454
+ }
455
+ async function startWebflowSession(http, config, input) {
456
+ const {
457
+ clientId,
458
+ successUrl,
459
+ errorUrl,
460
+ useRedirectProxy = false,
461
+ autoRedirect = false,
462
+ openInNewTab = false,
463
+ signal
464
+ } = input;
465
+ if (!clientId?.trim()) {
466
+ throw new JumioValidationError(
467
+ "Se requiere un identificador de cliente valido (clientId)."
468
+ );
469
+ }
470
+ if (!successUrl?.trim()) {
471
+ throw new JumioValidationError("Se requiere la URL de exito (successUrl).");
472
+ }
473
+ if (!errorUrl?.trim()) {
474
+ throw new JumioValidationError("Se requiere la URL de error (errorUrl).");
475
+ }
476
+ if (signal?.aborted) {
477
+ throw new JumioAbortError();
478
+ }
479
+ const proxyUrl = useRedirectProxy ? config.redirectProxyUrl ?? void 0 : void 0;
480
+ const finalSuccessUrl = buildRedirectUrl(successUrl, proxyUrl);
481
+ const finalErrorUrl = buildRedirectUrl(errorUrl, proxyUrl);
482
+ try {
483
+ const responseData = await withRetry(
484
+ () => http.postVerification(
485
+ {
486
+ client: clientId.trim(),
487
+ successUrl: finalSuccessUrl,
488
+ errorUrl: finalErrorUrl
489
+ },
490
+ { signal, timeout: config.requestTimeout }
491
+ ),
492
+ {
493
+ maxRetries: config.maxRetries ?? 3,
494
+ initialDelayMs: config.retryDelayMs ?? 800,
495
+ signal
496
+ }
497
+ );
498
+ const firstLevel = extractEnvelopeData(responseData);
499
+ const payload = extractNestedData(firstLevel) ?? {};
500
+ const href = payload?.href;
501
+ if (!href) {
502
+ throw new JumioError(
503
+ extractJumioMessage(payload) || "El backend no devolvio la URL de verificacion de Jumio (href).",
504
+ { rawData: payload }
505
+ );
506
+ }
507
+ const result = {
508
+ href,
509
+ accountId: payload?.accountId,
510
+ workflowId: payload?.workflowId,
511
+ data: payload
512
+ };
513
+ if (typeof window !== "undefined") {
514
+ if (openInNewTab) {
515
+ const win = window.open(href, "_blank");
516
+ if (!win || win.closed || typeof win.closed === "undefined") {
517
+ window.location.href = href;
518
+ }
519
+ } else if (autoRedirect) {
520
+ window.location.href = href;
521
+ }
522
+ }
523
+ return result;
524
+ } catch (err) {
525
+ throw err;
526
+ }
527
+ }
528
+ var init_webflow = __esm({
529
+ "src/core/webflow.ts"() {
530
+ init_envelope();
531
+ init_errors();
532
+ init_retry();
533
+ }
534
+ });
236
535
 
237
536
  // src/core/image.ts
537
+ init_errors();
238
538
  function stripDataUrlPrefix(dataUrl) {
239
539
  if (!dataUrl) return "";
240
540
  const commaIndex = dataUrl.indexOf(",");
@@ -390,6 +690,10 @@ async function resolveImageSourceToBase64(source, s3Signer, signal) {
390
690
  }
391
691
  throw new JumioImageProcessingError("Tipo de dato de imagen no soportado.");
392
692
  }
693
+
694
+ // src/core/http.ts
695
+ init_errors();
696
+ init_envelope();
393
697
  var JumioHttpClient = class {
394
698
  client;
395
699
  config;
@@ -505,6 +809,7 @@ var JumioHttpClient = class {
505
809
  }
506
810
  /**
507
811
  * Ejecuta una petición GET para consultar el estado actual de una verificación de INE.
812
+ * Soporta un `clientId` opcional requerido por algunos endpoints de DynamiCore (p. ej. Hosted Webflow).
508
813
  */
509
814
  async getVerificationStatus(accountId, workflowId, options) {
510
815
  if (options?.signal?.aborted) {
@@ -514,12 +819,16 @@ var JumioHttpClient = class {
514
819
  const dynamicHeaders = await this.resolveHeaders();
515
820
  const endpoint = this.config.endpoint || "/marketplace/apps/jumio";
516
821
  const timeout = options?.timeout ?? this.config.statusTimeout ?? 12e4;
822
+ const queryParams = {
823
+ type: "ine",
824
+ accountId,
825
+ workflowId
826
+ };
827
+ if (options?.clientId) {
828
+ queryParams.clientId = options.clientId;
829
+ }
517
830
  const response = await this.client.get(endpoint, {
518
- params: {
519
- type: "ine",
520
- accountId,
521
- workflowId
522
- },
831
+ params: queryParams,
523
832
  headers: dynamicHeaders,
524
833
  timeout,
525
834
  signal: options?.signal
@@ -535,6 +844,9 @@ var JumioHttpClient = class {
535
844
  };
536
845
 
537
846
  // src/core/polling.ts
847
+ init_envelope();
848
+ init_errors();
849
+ init_retry();
538
850
  async function pollJumioStatus(http, accountId, workflowId, options = {}) {
539
851
  const config = http.getConfig();
540
852
  const maxAttempts = options.maxAttempts ?? config.maxPollingAttempts ?? 20;
@@ -591,6 +903,10 @@ async function pollJumioStatus(http, accountId, workflowId, options = {}) {
591
903
  }
592
904
 
593
905
  // src/core/client.ts
906
+ init_envelope();
907
+ init_errors();
908
+ init_retry();
909
+ init_webflow();
594
910
  var JumioClient = class {
595
911
  http;
596
912
  config;
@@ -730,10 +1046,110 @@ var JumioClient = class {
730
1046
  onStatusResolved?.(finalResult);
731
1047
  return finalResult;
732
1048
  }
1049
+ // ─────────────────────────────────────────────────────────────────────────
1050
+ // Hosted Webflow (Redirección)
1051
+ // ─────────────────────────────────────────────────────────────────────────
1052
+ /**
1053
+ * Construye la URL de redirección de retorno para el flujo Hosted Webflow.
1054
+ *
1055
+ * Si el cliente está configurado con un `redirectProxyUrl` y `useProxy` es `true`,
1056
+ * la URL de retorno se codifica en Base64 URL-safe y se adjunta al proxy.
1057
+ *
1058
+ * @param returnUrl URL de la aplicación a la que Jumio redirigirá tras la verificación.
1059
+ * @param useProxy Si es `true` y hay `redirectProxyUrl` configurado, usa el proxy.
1060
+ * @returns URL de redirección construida.
1061
+ */
1062
+ buildRedirectUrl(returnUrl, useProxy = false) {
1063
+ const proxyUrl = useProxy ? this.config.redirectProxyUrl ?? void 0 : void 0;
1064
+ return buildRedirectUrl(returnUrl, proxyUrl);
1065
+ }
1066
+ /**
1067
+ * Inicia el flujo Hosted Webflow solicitando al backend de DynamiCore la URL
1068
+ * de verificación de Jumio (`href`).
1069
+ *
1070
+ * El usuario debe ser redirigido a esa URL para completar la verificación en la
1071
+ * página oficial de Jumio. Al terminar, Jumio redirige de vuelta a la aplicación
1072
+ * con `accountId` y `workflowExecutionId` como query params.
1073
+ *
1074
+ * @param input Parámetros del flujo: `clientId`, `successUrl`, `errorUrl`, opciones de proxy y redirección.
1075
+ * @returns `StartWebflowResult` con la URL de Jumio (`href`) y datos adicionales.
1076
+ *
1077
+ * @example
1078
+ * ```ts
1079
+ * const { href } = await client.startWebflow({
1080
+ * clientId: "usr_123",
1081
+ * successUrl: "https://app.example.com/verify/success",
1082
+ * errorUrl: "https://app.example.com/verify/error",
1083
+ * });
1084
+ * window.location.href = href;
1085
+ * ```
1086
+ */
1087
+ async startWebflow(input) {
1088
+ return startWebflowSession(this.http, this.config, input);
1089
+ }
1090
+ /**
1091
+ * Extrae los parámetros de seguimiento de Jumio de la URL de retorno.
1092
+ *
1093
+ * Jumio añade `accountId` y `workflowExecutionId` (o `workflowId`) como query
1094
+ * params al redirigir de vuelta a la aplicación tras la verificación.
1095
+ *
1096
+ * @param source URL completa, `URLSearchParams`, objeto con `search`/`href`, o nada para leer `window.location`.
1097
+ * @returns `WebflowReturnParams` con `accountId`, `workflowId`, `rawStatus` y todos los params.
1098
+ *
1099
+ * @example En React, en el componente de retorno:
1100
+ * ```ts
1101
+ * const { accountId, workflowId } = client.parseWebflowReturnParams(window.location.href);
1102
+ * ```
1103
+ */
1104
+ parseWebflowReturnParams(source) {
1105
+ return parseWebflowReturnParams(source);
1106
+ }
1107
+ /**
1108
+ * Consulta una única vez el estado actual de la verificación del flujo Hosted Webflow.
1109
+ *
1110
+ * @param input Parámetros de consulta: `accountId`, `workflowId`, y `clientId` opcional.
1111
+ * @returns `WebflowResult | null` — `null` si la verificación aún está pendiente.
1112
+ */
1113
+ async getWebflowStatus(input) {
1114
+ const { accountId, workflowId, clientId, signal } = input;
1115
+ const responseData = await this.http.getVerificationStatus(accountId, workflowId, {
1116
+ signal,
1117
+ timeout: this.config.statusTimeout,
1118
+ clientId
1119
+ });
1120
+ const firstLevel = extractEnvelopeData(responseData);
1121
+ const statusData = extractNestedData(firstLevel) ?? {};
1122
+ const { resolveWebflowResult: resolveWebflowResult2 } = await Promise.resolve().then(() => (init_webflow(), webflow_exports));
1123
+ return resolveWebflowResult2(statusData, accountId, workflowId);
1124
+ }
1125
+ /**
1126
+ * Sondea periódicamente el estado de verificación de un flujo Hosted Webflow de Jumio.
1127
+ *
1128
+ * Continúa consultando hasta obtener un resultado definitivo o agotar los intentos.
1129
+ *
1130
+ * @param params `accountId`, `workflowId` y `clientId` opcional.
1131
+ * @param options Opciones de sondeo (`maxAttempts`, `pollingIntervalMs`, `signal`, `onAttempt`).
1132
+ * @returns `WebflowResult` con el resultado definitivo.
1133
+ *
1134
+ * @example
1135
+ * ```ts
1136
+ * // En el componente de retorno, tras leer los params de la URL:
1137
+ * const result = await client.pollWebflowStatus({ accountId, workflowId, clientId });
1138
+ * if (result.valid) {
1139
+ * console.log("Verificación aprobada:", result.extraction);
1140
+ * } else {
1141
+ * console.warn("Rechazado:", result.errorMessage);
1142
+ * }
1143
+ * ```
1144
+ */
1145
+ async pollWebflowStatus(params, options) {
1146
+ return pollWebflowStatus(this.http, params, options);
1147
+ }
733
1148
  };
734
1149
  function createJumioClient(config) {
735
1150
  return new JumioClient(config);
736
1151
  }
1152
+ init_errors();
737
1153
  var INITIAL_STATE = {
738
1154
  isSubmitting: false,
739
1155
  isPolling: false,
@@ -885,6 +1301,13 @@ function useJumioVerification(options = {}) {
885
1301
  };
886
1302
  const handleError = (err) => {
887
1303
  if (err instanceof JumioAbortError) {
1304
+ setState((prev) => ({
1305
+ ...prev,
1306
+ isSubmitting: false,
1307
+ isPolling: false,
1308
+ isLoading: false,
1309
+ stage: "CANCELLED"
1310
+ }));
888
1311
  return;
889
1312
  }
890
1313
  setState((prev) => ({
@@ -948,7 +1371,207 @@ function useJumioVerification(options = {}) {
948
1371
  client
949
1372
  };
950
1373
  }
1374
+ init_errors();
1375
+ var INITIAL_STATE2 = {
1376
+ isStarting: false,
1377
+ isChecking: false,
1378
+ isLoading: false,
1379
+ result: null,
1380
+ error: null,
1381
+ isValid: false,
1382
+ isRejected: false
1383
+ };
1384
+ function useJumioWebflow(options = {}) {
1385
+ const {
1386
+ client: customClient,
1387
+ baseUrl,
1388
+ endpoint,
1389
+ context,
1390
+ authToken,
1391
+ authTokenPrefix,
1392
+ requestTimeout,
1393
+ statusTimeout,
1394
+ maxRetries,
1395
+ retryDelayMs,
1396
+ pollingIntervalMs,
1397
+ maxPollingAttempts,
1398
+ redirectProxyUrl,
1399
+ s3Signer,
1400
+ customHeaders,
1401
+ axiosInstance,
1402
+ onResult: globalOnResult,
1403
+ onError: globalOnError
1404
+ } = options;
1405
+ const client = useMemo(() => {
1406
+ if (customClient) return customClient;
1407
+ return new JumioClient({
1408
+ baseUrl,
1409
+ endpoint,
1410
+ context,
1411
+ authToken,
1412
+ authTokenPrefix,
1413
+ requestTimeout,
1414
+ statusTimeout,
1415
+ maxRetries,
1416
+ retryDelayMs,
1417
+ pollingIntervalMs,
1418
+ maxPollingAttempts,
1419
+ redirectProxyUrl,
1420
+ s3Signer,
1421
+ customHeaders,
1422
+ axiosInstance
1423
+ });
1424
+ }, [
1425
+ customClient,
1426
+ baseUrl,
1427
+ endpoint,
1428
+ context,
1429
+ authToken,
1430
+ authTokenPrefix,
1431
+ requestTimeout,
1432
+ statusTimeout,
1433
+ maxRetries,
1434
+ retryDelayMs,
1435
+ pollingIntervalMs,
1436
+ maxPollingAttempts,
1437
+ redirectProxyUrl,
1438
+ s3Signer,
1439
+ customHeaders,
1440
+ axiosInstance
1441
+ ]);
1442
+ const [state, setState] = useState(INITIAL_STATE2);
1443
+ const abortControllerRef = useRef(null);
1444
+ const callbacksRef = useRef({ onResult: globalOnResult, onError: globalOnError });
1445
+ useEffect(() => {
1446
+ callbacksRef.current = { onResult: globalOnResult, onError: globalOnError };
1447
+ }, [globalOnResult, globalOnError]);
1448
+ useEffect(() => {
1449
+ return () => {
1450
+ abortControllerRef.current?.abort();
1451
+ };
1452
+ }, []);
1453
+ const cancel = useCallback(() => {
1454
+ abortControllerRef.current?.abort();
1455
+ abortControllerRef.current = null;
1456
+ setState((prev) => ({
1457
+ ...prev,
1458
+ isStarting: false,
1459
+ isChecking: false,
1460
+ isLoading: false
1461
+ }));
1462
+ }, []);
1463
+ const reset = useCallback(() => {
1464
+ cancel();
1465
+ setState(INITIAL_STATE2);
1466
+ }, [cancel]);
1467
+ const handleError = useCallback((err) => {
1468
+ if (err instanceof JumioAbortError) {
1469
+ setState((prev) => ({
1470
+ ...prev,
1471
+ isStarting: false,
1472
+ isChecking: false,
1473
+ isLoading: false
1474
+ }));
1475
+ return;
1476
+ }
1477
+ setState((prev) => ({
1478
+ ...prev,
1479
+ isStarting: false,
1480
+ isChecking: false,
1481
+ isLoading: false,
1482
+ error: err,
1483
+ isRejected: true
1484
+ }));
1485
+ callbacksRef.current.onError?.(err);
1486
+ }, []);
1487
+ const handleResult = useCallback((result) => {
1488
+ setState((prev) => ({
1489
+ ...prev,
1490
+ isChecking: false,
1491
+ isLoading: false,
1492
+ result,
1493
+ isValid: result.valid,
1494
+ isRejected: !result.valid,
1495
+ error: result.valid ? null : new Error(result.errorMessage ?? "Verificacion de identidad rechazada")
1496
+ }));
1497
+ callbacksRef.current.onResult?.(result);
1498
+ }, []);
1499
+ const startWebflow = useCallback(
1500
+ async (input) => {
1501
+ if (abortControllerRef.current) {
1502
+ abortControllerRef.current.abort();
1503
+ }
1504
+ const controller = new AbortController();
1505
+ abortControllerRef.current = controller;
1506
+ setState({
1507
+ ...INITIAL_STATE2,
1508
+ isStarting: true,
1509
+ isLoading: true
1510
+ });
1511
+ try {
1512
+ const result = await client.startWebflow({
1513
+ ...input,
1514
+ signal: input.signal ?? controller.signal
1515
+ });
1516
+ setState((prev) => ({
1517
+ ...prev,
1518
+ isStarting: false,
1519
+ isLoading: false
1520
+ }));
1521
+ return result;
1522
+ } catch (err) {
1523
+ const normalizedError = err instanceof Error ? err : new Error(String(err));
1524
+ handleError(normalizedError);
1525
+ throw normalizedError;
1526
+ }
1527
+ },
1528
+ [client, handleError]
1529
+ );
1530
+ const checkResult = useCallback(
1531
+ async (params, pollOptions) => {
1532
+ if (abortControllerRef.current) {
1533
+ abortControllerRef.current.abort();
1534
+ }
1535
+ const controller = new AbortController();
1536
+ abortControllerRef.current = controller;
1537
+ setState((prev) => ({
1538
+ ...prev,
1539
+ isChecking: true,
1540
+ isLoading: true,
1541
+ error: null
1542
+ }));
1543
+ try {
1544
+ const result = await client.pollWebflowStatus(params, {
1545
+ ...pollOptions,
1546
+ signal: pollOptions?.signal ?? controller.signal
1547
+ });
1548
+ handleResult(result);
1549
+ return result;
1550
+ } catch (err) {
1551
+ const normalizedError = err instanceof Error ? err : new Error(String(err));
1552
+ handleError(normalizedError);
1553
+ throw normalizedError;
1554
+ }
1555
+ },
1556
+ [client, handleResult, handleError]
1557
+ );
1558
+ const parseReturnParams = useCallback(
1559
+ (source) => {
1560
+ return client.parseWebflowReturnParams(source);
1561
+ },
1562
+ [client]
1563
+ );
1564
+ return {
1565
+ ...state,
1566
+ startWebflow,
1567
+ checkResult,
1568
+ parseReturnParams,
1569
+ cancel,
1570
+ reset,
1571
+ client
1572
+ };
1573
+ }
951
1574
 
952
- export { APPROVED_JUMIO_STATUSES, FINAL_JUMIO_STATUSES, JumioAbortError, JumioClient, JumioError, JumioHttpClient, JumioImageProcessingError, JumioNetworkError, JumioPollingTimeoutError, JumioTimeoutError, JumioValidationError, arrayBufferToBase64, blobToBase64, createJumioClient, delay, extractEnvelopeData, extractJumioMessage, extractNestedData, fetchUrlAsBase64, isApprovedJumioStatus, isBase64String, isFinalJumioStatus, isJumioError, isPassedJumioDecision, normalizeSignedUrl, pollJumioStatus, resolveImageSourceToBase64, resolveVerificationValidity, shouldRetryJumio, stripDataUrlPrefix, toLowerText, toUpperText, useJumioVerification, withRetry };
1575
+ export { APPROVED_JUMIO_STATUSES, FINAL_JUMIO_STATUSES, JumioAbortError, JumioClient, JumioError, JumioHttpClient, JumioImageProcessingError, JumioNetworkError, JumioPollingTimeoutError, JumioTimeoutError, JumioValidationError, arrayBufferToBase64, blobToBase64, buildRedirectUrl, createJumioClient, delay, encodeUrlToBase64UrlSafe, extractEnvelopeData, extractJumioMessage, extractNestedData, fetchUrlAsBase64, isApprovedJumioStatus, isBase64String, isFinalJumioStatus, isJumioError, isPassedJumioDecision, normalizeSignedUrl, parseWebflowReturnParams, pollJumioStatus, pollWebflowStatus, resolveImageSourceToBase64, resolveVerificationValidity, resolveWebflowResult, shouldRetryJumio, startWebflowSession, stripDataUrlPrefix, toLowerText, toUpperText, useJumioVerification, useJumioWebflow, withRetry };
953
1576
  //# sourceMappingURL=index.mjs.map
954
1577
  //# sourceMappingURL=index.mjs.map