apacuana-sdk-core 1.0.0 → 1.2.0

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.
Files changed (92) hide show
  1. package/.eslintrc.cjs +22 -0
  2. package/CHANGELOG.md +1 -0
  3. package/README.md +794 -0
  4. package/babel.config.cjs +11 -0
  5. package/coverage/clover.xml +628 -0
  6. package/coverage/coverage-final.json +13 -0
  7. package/coverage/lcov-report/api/index.html +131 -0
  8. package/coverage/lcov-report/api/signatures.js.html +1093 -0
  9. package/coverage/lcov-report/api/users.js.html +292 -0
  10. package/coverage/lcov-report/base.css +224 -0
  11. package/coverage/lcov-report/block-navigation.js +87 -0
  12. package/coverage/lcov-report/certs.js.html +175 -0
  13. package/coverage/lcov-report/config/index.html +116 -0
  14. package/coverage/lcov-report/config/index.js.html +208 -0
  15. package/coverage/lcov-report/errors/index.html +116 -0
  16. package/coverage/lcov-report/errors/index.js.html +148 -0
  17. package/coverage/lcov-report/favicon.png +0 -0
  18. package/coverage/lcov-report/index.html +191 -0
  19. package/coverage/lcov-report/prettify.css +1 -0
  20. package/coverage/lcov-report/prettify.js +2 -0
  21. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  22. package/coverage/lcov-report/sorter.js +210 -0
  23. package/coverage/lcov-report/src/api/certs.js.html +856 -0
  24. package/coverage/lcov-report/src/api/faceLiveness.js.html +523 -0
  25. package/coverage/lcov-report/src/api/index.html +176 -0
  26. package/coverage/lcov-report/src/api/revocations.js.html +412 -0
  27. package/coverage/lcov-report/src/api/signatures.js.html +1420 -0
  28. package/coverage/lcov-report/src/api/users.js.html +466 -0
  29. package/coverage/lcov-report/src/config/index.html +116 -0
  30. package/coverage/lcov-report/src/config/index.js.html +256 -0
  31. package/coverage/lcov-report/src/errors/index.html +116 -0
  32. package/coverage/lcov-report/src/errors/index.js.html +148 -0
  33. package/coverage/lcov-report/src/index.html +116 -0
  34. package/coverage/lcov-report/src/index.js.html +592 -0
  35. package/coverage/lcov-report/src/success/index.html +116 -0
  36. package/coverage/lcov-report/src/success/index.js.html +106 -0
  37. package/coverage/lcov-report/src/utils/constant.js.html +256 -0
  38. package/coverage/lcov-report/src/utils/helpers.js.html +1195 -0
  39. package/coverage/lcov-report/src/utils/httpClient.js.html +622 -0
  40. package/coverage/lcov-report/src/utils/index.html +146 -0
  41. package/coverage/lcov-report/utils/constant.js.html +145 -0
  42. package/coverage/lcov-report/utils/httpClient.js.html +646 -0
  43. package/coverage/lcov-report/utils/index.html +131 -0
  44. package/coverage/lcov.info +1259 -0
  45. package/dist/api/certs.d.ts +15 -0
  46. package/dist/api/faceLiveness.d.ts +6 -0
  47. package/dist/api/revocations.d.ts +6 -0
  48. package/dist/api/signatures.d.ts +19 -0
  49. package/dist/api/users.d.ts +47 -0
  50. package/dist/config/index.d.ts +22 -0
  51. package/dist/errors/index.d.ts +10 -0
  52. package/dist/index.d.ts +25 -0
  53. package/dist/index.js +34493 -0
  54. package/dist/index.js.map +1 -0
  55. package/dist/index.mjs +34491 -0
  56. package/dist/index.mjs.map +1 -0
  57. package/dist/success/index.d.ts +7 -0
  58. package/dist/types/certs.d.ts +83 -0
  59. package/dist/types/faceLiveness.d.ts +11 -0
  60. package/dist/types/revocations.d.ts +51 -0
  61. package/dist/types/signatures.d.ts +162 -0
  62. package/dist/types/users.d.ts +260 -0
  63. package/dist/utils/constant.d.ts +49 -0
  64. package/dist/utils/helpers.d.ts +25 -0
  65. package/dist/utils/httpClient.d.ts +3 -0
  66. package/jest.config.cjs +12 -0
  67. package/package.json +51 -9
  68. package/rollup.config.js +32 -0
  69. package/src/api/certs.js +257 -0
  70. package/src/api/faceLiveness.js +146 -0
  71. package/src/api/revocations.js +109 -0
  72. package/src/api/signatures.js +445 -0
  73. package/src/api/users.js +127 -0
  74. package/src/config/index.js +57 -0
  75. package/src/errors/index.js +21 -0
  76. package/src/index.js +169 -0
  77. package/src/success/index.js +8 -0
  78. package/src/types/certs.js +67 -0
  79. package/src/types/faceLiveness.js +16 -0
  80. package/src/types/revocations.js +45 -0
  81. package/src/types/signatures.js +96 -0
  82. package/src/types/users.js +73 -0
  83. package/src/utils/constant.js +57 -0
  84. package/src/utils/helpers.js +370 -0
  85. package/src/utils/httpClient.js +179 -0
  86. package/tests/api/certs.test.js +311 -0
  87. package/tests/api/faceLiveness.test.js +170 -0
  88. package/tests/api/revocations.test.js +119 -0
  89. package/tests/api/signatures.test.js +530 -0
  90. package/tests/api/users.test.js +117 -0
  91. package/tests/index.test.js +131 -0
  92. package/tsconfig.json +16 -0
@@ -0,0 +1,445 @@
1
+ // src/api/signatures.js
2
+ import { getConfig } from "../config/index";
3
+ import { httpRequest } from "../utils/httpClient";
4
+ import { ApacuanaAPIError } from "../errors";
5
+ import ApacuanaSuccess from "../success";
6
+ import helpers from "../utils/helpers";
7
+ import { INTEGRATION_TYPE } from "../utils/constant";
8
+
9
+ /** @typedef {import("../types/signatures").Signer} Signer */
10
+ /** @typedef {import("../types/signatures").SignerData} SignerData */
11
+ /** @typedef {import("../types/signatures").AddSignerResponse} AddSignerResponse */
12
+ /** @typedef {import("../types/signatures").GetDigestData} GetDigestData */
13
+ /** @typedef {import("../types/signatures").GetDigestResponse} GetDigestResponse */
14
+ /** @typedef {import("../types/signatures").GetDocsParams} GetDocsParams */
15
+ /** @typedef {import("../types/signatures").GetDocsResponse} GetDocsResponse */
16
+ /** @typedef {import("../types/signatures").SignDocumentData} SignDocumentData */
17
+ /** @typedef {import("../types/signatures").SignaturePosition} SignaturePosition */
18
+ /** @typedef {import("../types/signatures").OnboardingSignerData} OnboardingSignerData */
19
+
20
+ // =================================================================
21
+ // Internal Functions
22
+ // =================================================================
23
+
24
+ const signDocumentOnBoarding = async (signData) => {
25
+ const payload = helpers.validateOnBoardingSignDocumentData(signData);
26
+
27
+ const { signature } = signData;
28
+ try {
29
+ const response = await httpRequest(
30
+ `services/api/documents/sign/${signature.id}`,
31
+ payload,
32
+ "PUT"
33
+ );
34
+ return new ApacuanaSuccess(response);
35
+ } catch (error) {
36
+ if (error instanceof ApacuanaAPIError) {
37
+ throw error;
38
+ }
39
+ throw new ApacuanaAPIError(
40
+ `Failed to sign document: ${error.message || "Unknown error"}`
41
+ );
42
+ }
43
+ };
44
+
45
+ const signDocumentOnPremise = async () => {
46
+ throw new ApacuanaAPIError(
47
+ "Document signing is not supported for integration type: ONPREMISE",
48
+ 501,
49
+ "NOT_IMPLEMENTED"
50
+ );
51
+ };
52
+
53
+ const getDigestToSignOnBoarding = async (signData) => {
54
+ try {
55
+ const formData = helpers.createPayloadGetDigest(signData);
56
+ const response = await httpRequest(
57
+ `services/api/documents/getdigest/${signData.signatureId}`,
58
+ formData,
59
+ "POST"
60
+ );
61
+ const digest = response.data?.digest || response.digest;
62
+ if (!digest) {
63
+ throw new ApacuanaAPIError(
64
+ "Signature generation failed: digest not found in the response.",
65
+ 500,
66
+ "API_RESPONSE_ERROR"
67
+ );
68
+ }
69
+
70
+ return new ApacuanaSuccess({ digest });
71
+ } catch (error) {
72
+ if (error.name === "ApacuanaAPIError") {
73
+ throw error;
74
+ }
75
+ throw new ApacuanaAPIError(
76
+ `Failed to sign document (on-boarding): ${error.message}`
77
+ );
78
+ }
79
+ };
80
+
81
+ const getDigestToSignOnPremise = async () => {
82
+ throw new ApacuanaAPIError(
83
+ "Digest retrieval is not supported for integration type: ONPREMISE",
84
+ 501,
85
+ "NOT_IMPLEMENTED"
86
+ );
87
+ };
88
+
89
+ const addSignerOnBoarding = async (signerData) => {
90
+ const payload = helpers.validateOnBoardingSignerData(signerData);
91
+ try {
92
+ await httpRequest("services/api/documents/signingsdk", payload, "POST");
93
+ return new ApacuanaSuccess({
94
+ signer: signerData.typedoc + signerData.doc,
95
+ });
96
+ } catch (error) {
97
+ if (error instanceof ApacuanaAPIError) {
98
+ throw error;
99
+ }
100
+ throw new Error(`Failed to add signer in On-Boarding: ${error.message}`);
101
+ }
102
+ };
103
+
104
+ const addSignerOnPremise = async () => {
105
+ throw new ApacuanaAPIError(
106
+ "Adding signers is not supported for integration type: ONPREMISE",
107
+ 501,
108
+ "NOT_IMPLEMENTED"
109
+ );
110
+ };
111
+
112
+ const getDocsOnPremise = async () => {
113
+ throw new ApacuanaAPIError(
114
+ "Document retrieval is not supported for integration type: ONPREMISE",
115
+ 501,
116
+ "NOT_IMPLEMENTED"
117
+ );
118
+ };
119
+
120
+ const getDocsOnBoarding = async (data) => {
121
+ const { customerId } = getConfig();
122
+ if (!customerId) {
123
+ throw new ApacuanaAPIError(
124
+ "'customerId' is not configured. Please configure the SDK.",
125
+ 400,
126
+ "CONFIGURATION_ERROR"
127
+ );
128
+ }
129
+
130
+ try {
131
+ const params = new URLSearchParams({
132
+ page: data.page,
133
+ customerid: customerId,
134
+ size: data.size,
135
+ });
136
+
137
+ if (typeof data.status !== "undefined") {
138
+ params.append("status", data.status);
139
+ }
140
+
141
+ const apiUrl = `services/api/documents/listcustomer?${params.toString()}`;
142
+ const response = await httpRequest(apiUrl, {}, "GET");
143
+ return new ApacuanaSuccess({
144
+ totalRecords: response.numofrecords,
145
+ records: response.records,
146
+ });
147
+ } catch (error) {
148
+ if (error.name === "ApacuanaAPIError") {
149
+ throw error;
150
+ }
151
+ throw new ApacuanaAPIError(
152
+ `Failed to get document list (on-boarding): ${error.message}`
153
+ );
154
+ }
155
+ };
156
+
157
+ const uploadSignatureVariantOnBoarding = async ({ file }) => {
158
+ try {
159
+ const response = await httpRequest(
160
+ "services/api/customer/signaturephoto",
161
+ { file },
162
+ "POST"
163
+ );
164
+ return new ApacuanaSuccess(response);
165
+ } catch (error) {
166
+ if (error instanceof ApacuanaAPIError) {
167
+ throw error;
168
+ }
169
+ throw new ApacuanaAPIError(
170
+ `Failed to upload signature variant: ${error.message || "Unknown error"}`
171
+ );
172
+ }
173
+ };
174
+
175
+ const uploadSignatureVariantOnPremise = async () => {
176
+ throw new ApacuanaAPIError(
177
+ "Uploading signature variants is not supported for integration type: ONPREMISE",
178
+ 501,
179
+ "NOT_IMPLEMENTED"
180
+ );
181
+ };
182
+
183
+ const getSignatureVariantOnBoarding = async () => {
184
+ const { customerId } = getConfig();
185
+ try {
186
+ const response = await httpRequest(
187
+ `services/api/customer/getsignaturephotosdk/${customerId}`,
188
+ {},
189
+ "GET"
190
+ );
191
+ return new ApacuanaSuccess(response);
192
+ } catch (error) {
193
+ if (error instanceof ApacuanaAPIError) {
194
+ throw error;
195
+ }
196
+ throw new ApacuanaAPIError(
197
+ `Failed to get signature variant: ${error.message || "Unknown error"}`
198
+ );
199
+ }
200
+ };
201
+
202
+ const getSignatureVariantOnPremise = async () => {
203
+ throw new ApacuanaAPIError(
204
+ "Getting signature variants is not supported for integration type: ONPREMISE",
205
+ 501,
206
+ "NOT_IMPLEMENTED"
207
+ );
208
+ };
209
+
210
+ const deleteSignatureVariantOnBoarding = async () => {
211
+ try {
212
+ const response = await httpRequest(
213
+ "services/api/customer/cleansignaturephoto",
214
+ {},
215
+ "DELETE"
216
+ );
217
+ return new ApacuanaSuccess(response);
218
+ } catch (error) {
219
+ if (error instanceof ApacuanaAPIError) {
220
+ throw error;
221
+ }
222
+ throw new ApacuanaAPIError(
223
+ `Failed to delete signature variant: ${error.message || "Unknown error"}`
224
+ );
225
+ }
226
+ };
227
+
228
+ const deleteSignatureVariantOnPremise = async () => {
229
+ throw new ApacuanaAPIError(
230
+ "Deleting signature variants is not supported for integration type: ONPREMISE",
231
+ 501,
232
+ "NOT_IMPLEMENTED"
233
+ );
234
+ };
235
+
236
+ // =================================================================
237
+ // Exported Functions
238
+ // =================================================================
239
+
240
+ /**
241
+ * Firma un documento PDF con un certificado digital.
242
+ * NOTA: Esta función no está implementada actualmente para ningún tipo de integración.
243
+ * @param {SignDocumentData} signData - Datos necesarios para la firma.
244
+ * @returns {Promise<object>}
245
+ * @throws {ApacuanaAPIError} Arroja un error 'NOT_IMPLEMENTED' para cualquier tipo de integración.
246
+ */
247
+ export const signDocument = async (signData) => {
248
+ const { integrationType } = getConfig();
249
+
250
+ if (integrationType === INTEGRATION_TYPE.ONBOARDING) {
251
+ return signDocumentOnBoarding(signData);
252
+ }
253
+
254
+ if (integrationType === INTEGRATION_TYPE.ONPREMISE) {
255
+ return signDocumentOnPremise();
256
+ }
257
+
258
+ throw new ApacuanaAPIError(
259
+ `Unsupported integration type: ${integrationType}`,
260
+ 400,
261
+ "UNSUPPORTED_INTEGRATION_TYPE"
262
+ );
263
+ };
264
+
265
+ /**
266
+ * Obtiene el digest de un documento para ser firmado.
267
+ * @param {GetDigestData} signData - Datos requeridos para obtener el digest.
268
+ * @returns {Promise<GetDigestResponse>} Una promesa que resuelve a un objeto con el digest del documento.
269
+ * @throws {ApacuanaAPIError} Si los datos de entrada son inválidos, la llamada a la API falla, o el tipo de integración no es soportado.
270
+ */
271
+ export const getDigest = async (signData) => {
272
+ helpers.validateGetDigestData(signData);
273
+
274
+ const { integrationType } = getConfig();
275
+
276
+ if (integrationType === INTEGRATION_TYPE.ONBOARDING) {
277
+ return getDigestToSignOnBoarding(signData);
278
+ }
279
+
280
+ if (integrationType === INTEGRATION_TYPE.ONPREMISE) {
281
+ return getDigestToSignOnPremise();
282
+ }
283
+
284
+ throw new ApacuanaAPIError(
285
+ `Document retrieval is not supported for an unknown integration type: ${integrationType}`,
286
+ 501,
287
+ "NOT_IMPLEMENTED"
288
+ );
289
+ };
290
+
291
+ /**
292
+ * Añade un firmante a un documento.
293
+ * @param {SignerData} signerData - Los datos del firmante que se va a añadir.
294
+ * @returns {Promise<AddSignerResponse>} Una promesa que resuelve a un objeto con el resultado de la operación.
295
+ * @throws {ApacuanaAPIError} Si los datos del firmante son inválidos, la llamada a la API falla, o el tipo de integración no es soportado.
296
+ */
297
+ export const addSigner = async (signerData) => {
298
+ if (
299
+ !signerData ||
300
+ typeof signerData !== "object" ||
301
+ Object.keys(signerData).length === 0
302
+ ) {
303
+ throw new ApacuanaAPIError(
304
+ "Signer data (signerData) is required and must be a non-empty object.",
305
+ 400,
306
+ "INVALID_PARAMETER"
307
+ );
308
+ }
309
+ const { integrationType } = getConfig();
310
+
311
+ if (integrationType === INTEGRATION_TYPE.ONBOARDING) {
312
+ return addSignerOnBoarding(signerData);
313
+ }
314
+
315
+ if (integrationType === INTEGRATION_TYPE.ONPREMISE) {
316
+ return addSignerOnPremise();
317
+ }
318
+
319
+ throw new ApacuanaAPIError(
320
+ `Unsupported integration type: ${integrationType}`,
321
+ 400,
322
+ "UNSUPPORTED_INTEGRATION_TYPE"
323
+ );
324
+ };
325
+
326
+ /**
327
+ * Obtiene una lista de documentos basada en los filtros especificados.
328
+ * @param {GetDocsParams} data - Objeto con parámetros de paginación y filtros.
329
+ * @returns {Promise<GetDocsResponse>} Una promesa que resuelve a un objeto con la lista de documentos.
330
+ * @throws {ApacuanaAPIError} Si los parámetros de paginación son inválidos, 'customerId' no está configurado, la llamada a la API falla, o el tipo de integración no es soportado.
331
+ */
332
+ export const getDocs = async (data) => {
333
+ helpers.validateGetDocsData(data);
334
+
335
+ const { integrationType } = getConfig();
336
+
337
+ if (integrationType === INTEGRATION_TYPE.ONBOARDING) {
338
+ return getDocsOnBoarding(data);
339
+ }
340
+
341
+ if (integrationType === INTEGRATION_TYPE.ONPREMISE) {
342
+ return getDocsOnPremise();
343
+ }
344
+
345
+ throw new ApacuanaAPIError(
346
+ `Document retrieval is not supported for an unknown integration type: ${integrationType}`,
347
+ 501,
348
+ "NOT_IMPLEMENTED"
349
+ );
350
+ };
351
+
352
+ /**
353
+ * Sube una variante de firma para un firmante.
354
+ * @param {object} data - Datos para la subida.
355
+ * @param {File} data.file - El archivo de la variante de firma (debe ser PNG).
356
+ * @returns {Promise<object>} Una promesa que resuelve a un objeto con el resultado de la operación.
357
+ * @throws {ApacuanaAPIError} Si los datos son inválidos o la llamada a la API falla.
358
+ */
359
+ export const uploadSignatureVariant = async (data) => {
360
+ if (!data || !data.file) {
361
+ throw new ApacuanaAPIError(
362
+ "El parámetro 'file' es requerido.",
363
+ 400,
364
+ "INVALID_PARAMETER"
365
+ );
366
+ }
367
+
368
+ if (typeof File === "undefined" || !(data.file instanceof File)) {
369
+ throw new ApacuanaAPIError(
370
+ "El parámetro 'file' debe ser una instancia de 'File'.",
371
+ 400,
372
+ "INVALID_PARAMETER"
373
+ );
374
+ }
375
+
376
+ if (data.file.type !== "image/png") {
377
+ throw new ApacuanaAPIError(
378
+ "El archivo debe ser de tipo PNG (image/png).",
379
+ 400,
380
+ "INVALID_PARAMETER"
381
+ );
382
+ }
383
+
384
+ const { integrationType } = getConfig();
385
+
386
+ if (integrationType === INTEGRATION_TYPE.ONBOARDING) {
387
+ return uploadSignatureVariantOnBoarding(data);
388
+ }
389
+
390
+ if (integrationType === INTEGRATION_TYPE.ONPREMISE) {
391
+ return uploadSignatureVariantOnPremise();
392
+ }
393
+
394
+ throw new ApacuanaAPIError(
395
+ `Unsupported integration type: ${integrationType}`,
396
+ 400,
397
+ "UNSUPPORTED_INTEGRATION_TYPE"
398
+ );
399
+ };
400
+
401
+ /**
402
+ * Obtiene la variante de firma del firmante.
403
+ * @returns {Promise<object>} Una promesa que resuelve a un objeto con los datos de la variante de firma.
404
+ * @throws {ApacuanaAPIError} Si la llamada a la API falla o el tipo de integración no es soportado.
405
+ */
406
+ export const getSignatureVariant = async () => {
407
+ const { integrationType } = getConfig();
408
+
409
+ if (integrationType === INTEGRATION_TYPE.ONBOARDING) {
410
+ return getSignatureVariantOnBoarding();
411
+ }
412
+
413
+ if (integrationType === INTEGRATION_TYPE.ONPREMISE) {
414
+ return getSignatureVariantOnPremise();
415
+ }
416
+
417
+ throw new ApacuanaAPIError(
418
+ `Unsupported integration type: ${integrationType}`,
419
+ 400,
420
+ "UNSUPPORTED_INTEGRATION_TYPE"
421
+ );
422
+ };
423
+
424
+ /**
425
+ * Elimina la variante de firma del firmante.
426
+ * @returns {Promise<object>} Una promesa que resuelve a un objeto con el resultado de la operación.
427
+ * @throws {ApacuanaAPIError} Si la llamada a la API falla o el tipo de integración no es soportado.
428
+ */
429
+ export const deleteSignatureVariant = async () => {
430
+ const { integrationType } = getConfig();
431
+
432
+ if (integrationType === INTEGRATION_TYPE.ONBOARDING) {
433
+ return deleteSignatureVariantOnBoarding();
434
+ }
435
+
436
+ if (integrationType === INTEGRATION_TYPE.ONPREMISE) {
437
+ return deleteSignatureVariantOnPremise();
438
+ }
439
+
440
+ throw new ApacuanaAPIError(
441
+ `Unsupported integration type: ${integrationType}`,
442
+ 400,
443
+ "UNSUPPORTED_INTEGRATION_TYPE"
444
+ );
445
+ };
@@ -0,0 +1,127 @@
1
+ import { httpRequest } from "../utils/httpClient";
2
+ import { ApacuanaAPIError } from "../errors/index";
3
+ import { getConfig } from "../config/index";
4
+ import ApacuanaSuccess from "../success";
5
+
6
+ /**
7
+ * @typedef {object} GetCustomerData
8
+ * @property {string} token - El token de sesión del usuario.
9
+ * @property {object} userData - Los datos del usuario obtenidos.
10
+ */
11
+
12
+ /**
13
+ * @typedef {object} GetCustomerResponse
14
+ * @property {true} success - Indica que la operación fue exitosa.
15
+ * @property {GetCustomerData} data - El payload de la respuesta.
16
+ */
17
+
18
+ /**
19
+ * Obtiene el token de un usuario a través de una petición POST.
20
+ * Este método es útil para endpoints que requieren datos en el cuerpo de la petición
21
+ * para buscar un usuario, como un ID de sesión o un token de acceso.
22
+ *
23
+ * @returns {Promise<GetCustomerResponse>} Una promesa que resuelve a un objeto con la respuesta exitosa.
24
+ * @throws {Error} Si los parámetros de entrada son inválidos.
25
+ * @throws {ApacuanaAPIError} Si ocurre un error en la API de Apacuana.
26
+ */
27
+ export const getCustomer = async () => {
28
+ const { verificationId, customerId } = getConfig();
29
+
30
+ if (!verificationId || !customerId) {
31
+ throw new ApacuanaAPIError(
32
+ "Both 'verificationId' and 'customerId' must be configured.",
33
+ 400,
34
+ "CONFIGURATION_ERROR"
35
+ );
36
+ }
37
+
38
+ const body = {
39
+ verificationid: verificationId,
40
+ customerid: customerId,
41
+ };
42
+
43
+ try {
44
+ const response = await httpRequest(
45
+ "services/api/register/init",
46
+ body,
47
+ "POST"
48
+ );
49
+
50
+ if (!response.sessionid || !response.entry) {
51
+ throw new ApacuanaAPIError(
52
+ "The API response does not contain the user.",
53
+ 200,
54
+ "INVALID_API_RESPONSE"
55
+ );
56
+ }
57
+
58
+ return new ApacuanaSuccess({
59
+ token: response.sessionid,
60
+ userData: response.entry,
61
+ });
62
+ } catch (error) {
63
+ if (error instanceof ApacuanaAPIError) {
64
+ throw error;
65
+ }
66
+ throw new ApacuanaAPIError(
67
+ `Unexpected failure getting token: ${error.message || "Unknown error"}`
68
+ );
69
+ }
70
+ };
71
+
72
+ /**
73
+ * @typedef {object} CreateUserPayload
74
+ * @property {string} usr - Correo electrónico del usuario.
75
+ * @property {string} pwd - Contraseña del usuario.
76
+ * @property {string} kinddoc - Tipo de documento de identidad (ej. 'V', 'P', 'E').
77
+ * @property {string} doc - Número de documento de identidad.
78
+ */
79
+
80
+ /**
81
+ * @typedef {object} CreateUserResponse
82
+ * @property {string} message - Mensaje de confirmación de la creación del usuario.
83
+ */
84
+
85
+ /**
86
+ * Crea un nuevo usuario en la plataforma de Apacuana.
87
+ * @param {CreateUserPayload} userData - Objeto con los datos del usuario a crear.
88
+ * @returns {Promise<ApacuanaSuccess>} Una promesa que resuelve a un objeto con la respuesta exitosa.
89
+ * @throws {ApacuanaAPIError} Si los datos de entrada son inválidos o si ocurre un error en la API.
90
+ */
91
+
92
+ export const createApacuanaUser = async (userData) => {
93
+ try {
94
+ const formData = new FormData();
95
+ Object.keys(userData).forEach((key) => {
96
+ const value = userData[key];
97
+ const isRNFile =
98
+ value &&
99
+ typeof value === "object" &&
100
+ value.uri &&
101
+ value.name &&
102
+ value.type;
103
+ if (value instanceof File || isRNFile) {
104
+ formData.append(key, value);
105
+ } else if (value !== null && value !== undefined) {
106
+ formData.append(key, String(value));
107
+ }
108
+ });
109
+
110
+ const response = await httpRequest(
111
+ "services/api/register/initial",
112
+ formData,
113
+ "POST"
114
+ );
115
+
116
+ return new ApacuanaSuccess({
117
+ ...response,
118
+ });
119
+ } catch (error) {
120
+ if (error instanceof ApacuanaAPIError) {
121
+ throw error;
122
+ }
123
+ throw new ApacuanaAPIError(
124
+ `Unexpected failure creating user: ${error.message || "Unknown error"}`
125
+ );
126
+ }
127
+ };
@@ -0,0 +1,57 @@
1
+ // src/config/index.js
2
+ import { INTEGRATION_TYPE } from "../utils/constant";
3
+
4
+ /**
5
+ * @typedef {object} SDKConfig
6
+ * @property {string} apiUrl
7
+ * @property {string} secretKey
8
+ * @property {string} apiKey
9
+ * @property {string} verificationId
10
+ * @property {string} customerId
11
+ * @property {string} integrationType
12
+ * @property {object} [userData]
13
+ * @property {string} [token]
14
+ */
15
+
16
+ const defaultConfig = {
17
+ apiUrl: "",
18
+ secretKey: "",
19
+ apiKey: "",
20
+ verificationId: "",
21
+ customerId: "",
22
+ integrationType: "",
23
+ userData: undefined,
24
+ token: undefined,
25
+ };
26
+
27
+ /** @type {SDKConfig} */
28
+ let config = { ...defaultConfig };
29
+
30
+ export const setConfig = (newConfig) => {
31
+ const { apiUrl, secretKey, apiKey, verificationId, integrationType } =
32
+ newConfig;
33
+
34
+ if (!apiUrl || !secretKey || !apiKey || !verificationId || !integrationType) {
35
+ throw new Error(
36
+ "Apacuana SDK: La configuración inicial debe incluir apiUrl, " +
37
+ "secretKey, apiKey, verificationId e integrationType."
38
+ );
39
+ }
40
+
41
+ // Nueva validación para el valor de integrationType
42
+ if (!Object.values(INTEGRATION_TYPE).includes(integrationType)) {
43
+ throw new Error(
44
+ `Apacuana SDK: El valor de integrationType ('${integrationType}') no es válido. ` +
45
+ `Valores permitidos: ${Object.values(INTEGRATION_TYPE).join(", ")}`
46
+ );
47
+ }
48
+
49
+ config = { ...config, ...newConfig };
50
+ // eslint-disable-next-line no-console
51
+ };
52
+
53
+ export const getConfig = () => ({ ...config });
54
+
55
+ export const close = () => {
56
+ config = { ...defaultConfig };
57
+ };
@@ -0,0 +1,21 @@
1
+ // src/errors/index.js
2
+
3
+ /**
4
+ * Clase de error personalizada para errores de la API de Apacuana.
5
+ */
6
+ export class ApacuanaAPIError extends Error {
7
+ constructor(message, statusCode = 500, errorCode = null) {
8
+ super(message);
9
+ this.name = "ApacuanaAPIError";
10
+ this.statusCode = statusCode;
11
+ this.errorCode = errorCode;
12
+ this.success = false; // Añadir el atributo success con valor false
13
+
14
+ // Mantener el stack trace correcto
15
+ if (Error.captureStackTrace) {
16
+ Error.captureStackTrace(this, ApacuanaAPIError);
17
+ }
18
+ }
19
+ }
20
+
21
+ export default ApacuanaAPIError;