@apia/api 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,1557 +1,2 @@
1
- import { jsx, jsxs } from 'react/jsx-runtime';
2
- import * as React from 'react';
3
- import React__default, { createContext, useMemo } from 'react';
4
- import { Box } from 'theme-ui';
5
- import { debugDispatcher, EventEmitter, parseXmlAsync, arrayOrArray, useMount, encrypt, WithEventsValue, focus, focusSelector, useStateRef, useUnmount } from '@apia/util';
6
- import { notify, getNotificationMessageObj, dispatchNotifications } from '@apia/notifications';
7
- import { classToValidate, Checkbox, FileInput, classToValidationFunction, Input, Radio, Select, useFormContext, validationsStore, hasSucceedFormValidation, Form } from '@apia/validations';
8
- import { SimpleButton, useModal, Modal, ProgressBar } from '@apia/components';
9
- import { getVariant } from '@apia/theme';
10
- import axios from 'axios';
11
- import { merge, uniqueId } from 'lodash';
12
- import QueryString from 'qs';
13
- import { session } from '@apia/session';
14
-
15
- const ApiaApiId = createContext("apiaApi");
16
- const ApiaApiContext = ({
17
- children,
18
- id
19
- }) => {
20
- return /* @__PURE__ */ jsx(ApiaApiId.Provider, { value: id, children });
21
- };
22
- var ApiaApiContext$1 = React.memo(ApiaApiContext);
23
-
24
- var __defProp$8 = Object.defineProperty;
25
- var __defProps$4 = Object.defineProperties;
26
- var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
27
- var __getOwnPropSymbols$8 = Object.getOwnPropertySymbols;
28
- var __hasOwnProp$8 = Object.prototype.hasOwnProperty;
29
- var __propIsEnum$8 = Object.prototype.propertyIsEnumerable;
30
- var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
31
- var __spreadValues$8 = (a, b) => {
32
- for (var prop in b || (b = {}))
33
- if (__hasOwnProp$8.call(b, prop))
34
- __defNormalProp$8(a, prop, b[prop]);
35
- if (__getOwnPropSymbols$8)
36
- for (var prop of __getOwnPropSymbols$8(b)) {
37
- if (__propIsEnum$8.call(b, prop))
38
- __defNormalProp$8(a, prop, b[prop]);
39
- }
40
- return a;
41
- };
42
- var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
43
- var __objRest$1 = (source, exclude) => {
44
- var target = {};
45
- for (var prop in source)
46
- if (__hasOwnProp$8.call(source, prop) && exclude.indexOf(prop) < 0)
47
- target[prop] = source[prop];
48
- if (source != null && __getOwnPropSymbols$8)
49
- for (var prop of __getOwnPropSymbols$8(source)) {
50
- if (exclude.indexOf(prop) < 0 && __propIsEnum$8.call(source, prop))
51
- target[prop] = source[prop];
52
- }
53
- return target;
54
- };
55
- var __async$2 = (__this, __arguments, generator) => {
56
- return new Promise((resolve, reject) => {
57
- var fulfilled = (value) => {
58
- try {
59
- step(generator.next(value));
60
- } catch (e) {
61
- reject(e);
62
- }
63
- };
64
- var rejected = (value) => {
65
- try {
66
- step(generator.throw(value));
67
- } catch (e) {
68
- reject(e);
69
- }
70
- };
71
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
72
- step((generator = generator.apply(__this, __arguments)).next());
73
- });
74
- };
75
- debugDispatcher.on(
76
- "parseXml",
77
- (_0) => __async$2(void 0, [_0], function* ([text]) {
78
- const result = yield parseXmlAsync(text);
79
- console.info(result);
80
- }),
81
- "Acepta un par\xE1metro de tipo string y realiza un parseo como si fuera xml, convirti\xE9ndolo a objeto javascript."
82
- );
83
- const defaultConfig = {
84
- debug: true,
85
- colors: {
86
- exception: "red",
87
- alert: "yellow",
88
- message: "lightgreen"
89
- },
90
- handleLoad: false
91
- };
92
- const STORED_CONFIG = "ApiaApiConfig";
93
- let forcedConfig = {};
94
- const storedConfig = localStorage.getItem(STORED_CONFIG);
95
- if (storedConfig)
96
- forcedConfig = JSON.parse(storedConfig);
97
- function getConfig(outerBehaveConfig) {
98
- return merge({}, defaultConfig, outerBehaveConfig, forcedConfig);
99
- }
100
- function makeUrl(url, queryData, stringifyOptions) {
101
- let finalUrl = url;
102
- const questionMarkIndex = finalUrl.indexOf("?");
103
- if (questionMarkIndex === -1)
104
- finalUrl += "?";
105
- else if (questionMarkIndex !== finalUrl.length - 1 && !finalUrl.endsWith("&"))
106
- finalUrl += "&";
107
- let parsedUrl = `${finalUrl}${queryData ? QueryString.stringify(queryData, stringifyOptions) : ""}`;
108
- if (parsedUrl.endsWith("&") || parsedUrl.endsWith("?")) {
109
- parsedUrl = parsedUrl.slice(0, parsedUrl.length - 1);
110
- }
111
- return parsedUrl;
112
- }
113
- const getURLActionName = (url) => {
114
- var _a;
115
- const actionIdx = (_a = url.match(/action=(\w+)/)) == null ? void 0 : _a[1];
116
- return actionIdx != null ? actionIdx : "noAction";
117
- };
118
- const ApiaActions = new class ApiaActions2 extends EventEmitter {
119
- }();
120
- function getColor(color, colors = ((_a) => (_a = defaultConfig.colors) != null ? _a : {
121
- exception: "red",
122
- alert: "yellow",
123
- message: "green"
124
- })()) {
125
- return colors[color];
126
- }
127
- const handleWrongResponse = (error) => {
128
- let errorMessage;
129
- if (typeof error !== "string") {
130
- if (error.message)
131
- errorMessage = error.message;
132
- else
133
- errorMessage = error.toString();
134
- } else
135
- errorMessage = error;
136
- notify({
137
- type: "danger",
138
- message: error.message.replaceAll("AxiosError", "Error")
139
- });
140
- console.log("%c ", "font-size:10vh");
141
- console.log("%cError in ApiaApi", "color:red;font-size:2em;font-weight:bold");
142
- console.log(`red/${errorMessage}`, { error });
143
- console.log("%c ", "font-size:10vh");
144
- };
145
- function isJsonResponse(response) {
146
- return response.headers["content-type"].match("application/json");
147
- }
148
- function isXmlResponse(response) {
149
- return response.headers["content-type"].match(
150
- /(?:application|text)?\/xml/
151
- );
152
- }
153
- function isHtmlResponse(response) {
154
- return response.headers["content-type"].match(
155
- /(?:application|text)?\/html/
156
- );
157
- }
158
- function handleActions(actions) {
159
- var _a, _b;
160
- if (actions) {
161
- if (getConfig().debug)
162
- console.log(
163
- "%cHandled actions: ",
164
- `color: ${(_b = (_a = getConfig().colors) == null ? void 0 : _a.message) != null ? _b : "green"}`,
165
- { actions }
166
- );
167
- const actionsArray = arrayOrArray(actions.action);
168
- actionsArray.forEach((action) => {
169
- ApiaActions.emit("action", __spreadProps$4(__spreadValues$8({}, action), {
170
- param: arrayOrArray(action.param)
171
- }));
172
- });
173
- }
174
- }
175
- function handleOnClose({
176
- exceptions,
177
- onClose,
178
- sysExceptions,
179
- sysMessages
180
- }) {
181
- try {
182
- import(
183
- /* webpackChunkName: "api-[request]" */
184
- `/api/onClose/${onClose}.ts`
185
- ).then(
186
- (func) => {
187
- if (exceptions || sysExceptions || sysMessages) {
188
- const notificationsObject = getNotificationMessageObj({
189
- exceptions,
190
- onClose,
191
- sysExceptions,
192
- sysMessages
193
- });
194
- if (notificationsObject)
195
- notificationsObject.forEach((notification) => {
196
- notify(__spreadProps$4(__spreadValues$8({}, notification), {
197
- onClose: func.default
198
- }));
199
- });
200
- else
201
- func.default();
202
- } else
203
- func.default();
204
- },
205
- (e) => {
206
- notify({
207
- message: `onClose action not found: ${String(e)}`,
208
- type: "danger"
209
- });
210
- }
211
- );
212
- } catch (e) {
213
- parseMessages({ exceptions, sysExceptions, sysMessages });
214
- console.error("Error while handling onClose");
215
- console.error(e);
216
- }
217
- }
218
- function parseMessages(response) {
219
- if (!response)
220
- return;
221
- const { exceptions, sysMessages, sysExceptions } = response;
222
- if (exceptions || sysExceptions || sysMessages) {
223
- try {
224
- dispatchNotifications({
225
- exceptions,
226
- sysExceptions,
227
- sysMessages
228
- });
229
- } catch (e) {
230
- handleWrongResponse(new Error(e));
231
- }
232
- }
233
- }
234
- const parseSuccessfulResponse = (_0, _1, ..._2) => __async$2(void 0, [_0, _1, ..._2], function* (response, currentUrl, outerBehaveConfig = defaultConfig) {
235
- var _a;
236
- const behaveConfig = getConfig(outerBehaveConfig);
237
- let parsedObj;
238
- if (isJsonResponse(response)) {
239
- if (typeof response.data === "string")
240
- parsedObj = JSON.parse(
241
- response.data.trim()
242
- );
243
- else if (typeof response.data === "object" && response.data)
244
- parsedObj = response.data;
245
- } else if (isXmlResponse(response)) {
246
- parsedObj = yield parseXmlAsync(response.data).catch(
247
- (e) => {
248
- handleWrongResponse(new Error(e));
249
- }
250
- );
251
- } else if (isHtmlResponse(response)) {
252
- console.error(
253
- "El contenido devuelto es Html, no se esperaba esa respuesta"
254
- );
255
- return null;
256
- }
257
- if (behaveConfig.validateResponse) {
258
- const validateResult = yield behaveConfig.validateResponse(__spreadProps$4(__spreadValues$8({}, response), {
259
- data: (_a = parsedObj == null ? void 0 : parsedObj.load) != null ? _a : parsedObj
260
- }));
261
- if (typeof validateResult === "string")
262
- throw new Error(`Validation error: ${validateResult}`);
263
- else if (!validateResult) {
264
- throw new Error("Error");
265
- }
266
- }
267
- if (parsedObj) {
268
- const _b = parsedObj, {
269
- actions,
270
- onClose,
271
- exceptions,
272
- sysExceptions,
273
- sysMessages,
274
- load
275
- } = _b, rest = __objRest$1(_b, [
276
- "actions",
277
- "onClose",
278
- "exceptions",
279
- "sysExceptions",
280
- "sysMessages",
281
- "load"
282
- ]);
283
- if (rest.code === "-1" && exceptions) {
284
- session.invalidate();
285
- return null;
286
- }
287
- if (exceptions && behaveConfig.debug) {
288
- console.log(
289
- `%cparseSuccessfulResponse`,
290
- `color: ${getColor("exception", behaveConfig.colors)}`,
291
- {
292
- exceptions
293
- }
294
- );
295
- }
296
- if (sysExceptions && behaveConfig.debug) {
297
- console.log(
298
- `%cparseSuccessfulResponse`,
299
- `color: ${getColor("exception", behaveConfig.colors)}`,
300
- {
301
- sysExceptions
302
- }
303
- );
304
- }
305
- if (sysMessages && behaveConfig.debug) {
306
- console.log(
307
- `%cparseSuccessfulResponse`,
308
- `color: ${getColor("alert", behaveConfig.colors)}`,
309
- {
310
- sysMessages
311
- }
312
- );
313
- }
314
- handleActions(actions);
315
- if (behaveConfig.handleLoad && onClose)
316
- handleOnClose({
317
- exceptions,
318
- onClose,
319
- sysExceptions,
320
- sysMessages
321
- });
322
- else
323
- parseMessages({ exceptions, sysExceptions, sysMessages });
324
- if (load) {
325
- if (behaveConfig.handleLoad) {
326
- console.log(
327
- `%chandleLoad`,
328
- `color: ${getColor("message", behaveConfig.colors)}`,
329
- {
330
- load
331
- }
332
- );
333
- if (!handle(load, currentUrl, {
334
- methodsPath: outerBehaveConfig.methodsPath,
335
- modalConfiguration: __spreadProps$4(__spreadValues$8({}, behaveConfig.modalConfiguration), {
336
- onClose: () => {
337
- var _a2, _b2;
338
- if (onClose)
339
- handleOnClose({
340
- exceptions,
341
- onClose,
342
- sysExceptions,
343
- sysMessages
344
- });
345
- if ((_a2 = behaveConfig.modalConfiguration) == null ? void 0 : _a2.onClose)
346
- (_b2 = behaveConfig.modalConfiguration) == null ? void 0 : _b2.onClose();
347
- }
348
- })
349
- })) {
350
- console.log(
351
- `%cunhandledLoad -> There is no handler defined`,
352
- `color: ${getColor("exception", behaveConfig.colors)}`,
353
- {
354
- load
355
- }
356
- );
357
- }
358
- }
359
- return __spreadProps$4(__spreadValues$8({}, load), { sysMessages, exceptions, sysExceptions });
360
- }
361
- return __spreadProps$4(__spreadValues$8({}, rest), { sysMessages, exceptions, sysExceptions });
362
- }
363
- return null;
364
- });
365
- function handleResponse(_0, _1) {
366
- return __async$2(this, arguments, function* (result, currentUrl, outerBehaveConfig = defaultConfig) {
367
- var _a;
368
- const behaveConfig = getConfig(outerBehaveConfig);
369
- try {
370
- if (!result || result.data === void 0) {
371
- if (behaveConfig.debug)
372
- console.log(
373
- `%cApiaApi wrong response`,
374
- `color: ${getColor("alert", behaveConfig.colors)}`
375
- );
376
- } else {
377
- const parsedResponse = yield parseSuccessfulResponse(
378
- result,
379
- currentUrl,
380
- behaveConfig
381
- );
382
- const action = getURLActionName(currentUrl);
383
- if (behaveConfig.debug)
384
- console.log(
385
- `%c <- ApiaApi.${(_a = result.config.method) != null ? _a : ""} ${action} `,
386
- `color: ${getColor("message", behaveConfig.colors)}`,
387
- {
388
- data: parsedResponse
389
- }
390
- );
391
- return __spreadProps$4(__spreadValues$8({}, result), {
392
- data: parsedResponse,
393
- hasError: !!(parsedResponse == null ? void 0 : parsedResponse.exceptions) || !!(parsedResponse == null ? void 0 : parsedResponse.sysExceptions),
394
- hasMessages: !!(parsedResponse == null ? void 0 : parsedResponse.sysMessages)
395
- });
396
- }
397
- } catch (e) {
398
- handleWrongResponse(new Error(e));
399
- return null;
400
- }
401
- return null;
402
- });
403
- }
404
- function post(par1, par2) {
405
- return __async$2(this, null, function* () {
406
- const actualUrl = typeof par1 !== "string" ? makeApiaUrl() : par1;
407
- const configParameter = typeof par1 === "string" ? par2 != null ? par2 : defaultConfig : par1;
408
- const behaveConfig = __spreadProps$4(__spreadValues$8({}, getConfig(configParameter)), {
409
- postData: configParameter.postDataTreatement === "stringify" ? QueryString.stringify(
410
- configParameter.postData,
411
- configParameter.stringifyOptions
412
- ) : configParameter.postData
413
- });
414
- const parsedUrl = makeUrl(
415
- actualUrl,
416
- behaveConfig.queryData,
417
- behaveConfig.stringifyOptions
418
- );
419
- if (behaveConfig.debug) {
420
- const queryString = actualUrl.split("&");
421
- const action = getURLActionName(actualUrl);
422
- console.log(
423
- `%cApiaApi.post ${action}`,
424
- `color: ${getColor("message", behaveConfig.colors)}`,
425
- {
426
- url: parsedUrl,
427
- queryDataInURL: [...queryString],
428
- queryData: behaveConfig.queryData,
429
- formData: behaveConfig.postData,
430
- stringifyOptiopns: behaveConfig.stringifyOptions
431
- }
432
- );
433
- }
434
- const response = yield axios.post(
435
- parsedUrl,
436
- behaveConfig.postData,
437
- behaveConfig.axiosConfig
438
- ).catch((e) => {
439
- handleWrongResponse(new Error(e));
440
- });
441
- if (response) {
442
- const result = handleResponse(response, actualUrl, behaveConfig);
443
- return result;
444
- }
445
- return null;
446
- });
447
- }
448
- function get(par1, par2) {
449
- return __async$2(this, null, function* () {
450
- const actualUrl = typeof par1 !== "string" ? makeApiaUrl() : par1;
451
- const behaveConfig = getConfig(
452
- typeof par1 === "string" ? par2 != null ? par2 : defaultConfig : par1
453
- );
454
- const parsedUrl = makeUrl(
455
- actualUrl,
456
- behaveConfig.queryData,
457
- behaveConfig.stringifyOptions
458
- );
459
- if (behaveConfig.debug)
460
- console.log(
461
- `%cApiaApi.get`,
462
- `color: ${getColor("message", behaveConfig.colors)}`,
463
- {
464
- url: parsedUrl
465
- }
466
- );
467
- const response = yield axios.get(parsedUrl, behaveConfig.axiosConfig).catch((e) => {
468
- handleWrongResponse(new Error(e));
469
- });
470
- if (response) {
471
- const result = yield handleResponse(
472
- response,
473
- actualUrl,
474
- behaveConfig
475
- );
476
- return result;
477
- }
478
- return null;
479
- });
480
- }
481
- const ApiaApi = {
482
- get,
483
- getConfig,
484
- post
485
- };
486
- function makeApiaUrl(props) {
487
- var _b, _c;
488
- let actualQueryData = {};
489
- if (props) {
490
- const _a = props, rest = __objRest$1(_a, [
491
- "ajaxUrl",
492
- "queryString",
493
- "stringifyOptions",
494
- "shouldAvoidTabId",
495
- "preventAsXmlParameter",
496
- "avoidTabId"
497
- ]);
498
- actualQueryData = __spreadValues$8({}, rest);
499
- }
500
- const queryString = QueryString.stringify(
501
- actualQueryData,
502
- (_b = props == null ? void 0 : props.stringifyOptions) != null ? _b : {
503
- arrayFormat: "repeat",
504
- encodeValuesOnly: false
505
- }
506
- );
507
- let actualAjaxUrl = (_c = props == null ? void 0 : props.ajaxUrl) != null ? _c : window.URL_REQUEST_AJAX;
508
- if (actualAjaxUrl.indexOf("?") === actualAjaxUrl.length - 1)
509
- actualAjaxUrl = actualAjaxUrl.slice(0, actualAjaxUrl.length - 1);
510
- if (!actualAjaxUrl.startsWith("/"))
511
- actualAjaxUrl = `/${actualAjaxUrl}`;
512
- const match = window.TAB_ID_REQUEST.match(/tokenId=(\w+)/);
513
- const currentTokenId = (match != null ? match : [])[1];
514
- let tabId = ((props == null ? void 0 : props.tabId) ? `&tabId=${props.tabId}&tokenId=${currentTokenId}` : window.TAB_ID_REQUEST).slice(1);
515
- if (props == null ? void 0 : props.avoidTabId)
516
- tabId = "";
517
- let { CONTEXT } = window;
518
- if (CONTEXT == null ? void 0 : CONTEXT.endsWith("/"))
519
- CONTEXT += CONTEXT.slice(0, CONTEXT.length - 1);
520
- return `${CONTEXT}${actualAjaxUrl}?${!(props == null ? void 0 : props.preventAsXmlParameter) ? "asXml=true&" : ""}${(props == null ? void 0 : props.queryString) ? `${props.queryString}&` : ""}${queryString ? `${queryString}&` : ""}${tabId}`;
521
- }
522
-
523
- var __defProp$7 = Object.defineProperty;
524
- var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
525
- var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
526
- var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
527
- var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
528
- var __spreadValues$7 = (a, b) => {
529
- for (var prop in b || (b = {}))
530
- if (__hasOwnProp$7.call(b, prop))
531
- __defNormalProp$7(a, prop, b[prop]);
532
- if (__getOwnPropSymbols$7)
533
- for (var prop of __getOwnPropSymbols$7(b)) {
534
- if (__propIsEnum$7.call(b, prop))
535
- __defNormalProp$7(a, prop, b[prop]);
536
- }
537
- return a;
538
- };
539
- const ApiaApiCheckbox = (props) => {
540
- const element = React__default.useMemo(() => props.element, [props.element]);
541
- const className = React__default.useMemo(
542
- () => element.class ? `handler__checkbox ${element.class}` : "handler__checkbox",
543
- [element.class]
544
- );
545
- const validationRules = React__default.useMemo(
546
- () => __spreadValues$7({
547
- required: element.mandatory
548
- }, classToValidate(element.class)),
549
- [element.class, element.mandatory]
550
- );
551
- const submitValueParser = React__default.useCallback(
552
- (value) => value === "on" || value === true,
553
- []
554
- );
555
- return /* @__PURE__ */ jsx(
556
- Checkbox,
557
- {
558
- className,
559
- name: element.id || element.name,
560
- label: element.text,
561
- title: element.title || element.text,
562
- initialValue: String(element.selected) === "true",
563
- disabled: element.readonly || element.disabled,
564
- validationRules,
565
- onChange: element.onChange,
566
- submitValueParser
567
- }
568
- );
569
- };
570
-
571
- var __defProp$6 = Object.defineProperty;
572
- var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
573
- var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
574
- var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
575
- var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
576
- var __spreadValues$6 = (a, b) => {
577
- for (var prop in b || (b = {}))
578
- if (__hasOwnProp$6.call(b, prop))
579
- __defNormalProp$6(a, prop, b[prop]);
580
- if (__getOwnPropSymbols$6)
581
- for (var prop of __getOwnPropSymbols$6(b)) {
582
- if (__propIsEnum$6.call(b, prop))
583
- __defNormalProp$6(a, prop, b[prop]);
584
- }
585
- return a;
586
- };
587
- const ApiaApiFileInput = (props) => {
588
- const element = React__default.useMemo(() => props.element, [props.element]);
589
- const className = React__default.useMemo(
590
- () => element.class ? `handler__file ${element.class}` : "handler__file",
591
- [element.class]
592
- );
593
- const validationRules = React__default.useMemo(
594
- () => __spreadValues$6({
595
- required: element.mandatory
596
- }, classToValidate(element.class)),
597
- [element.class, element.mandatory]
598
- );
599
- return /* @__PURE__ */ jsx(
600
- FileInput,
601
- {
602
- className,
603
- name: element.id || element.name,
604
- label: element.text,
605
- title: element.title || element.text,
606
- readOnly: element.readonly,
607
- disabled: element.disabled,
608
- validationRules
609
- }
610
- );
611
- };
612
- ApiaApiFileInput.displayName = "ApiaApiFileInput";
613
-
614
- var __defProp$5 = Object.defineProperty;
615
- var __defProps$3 = Object.defineProperties;
616
- var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
617
- var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
618
- var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
619
- var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
620
- var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
621
- var __spreadValues$5 = (a, b) => {
622
- for (var prop in b || (b = {}))
623
- if (__hasOwnProp$5.call(b, prop))
624
- __defNormalProp$5(a, prop, b[prop]);
625
- if (__getOwnPropSymbols$5)
626
- for (var prop of __getOwnPropSymbols$5(b)) {
627
- if (__propIsEnum$5.call(b, prop))
628
- __defNormalProp$5(a, prop, b[prop]);
629
- }
630
- return a;
631
- };
632
- var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
633
- const ApiaApiInput = (props) => {
634
- const element = React__default.useMemo(() => props.element, [props.element]);
635
- const getModal = React__default.useCallback((path) => {
636
- return React__default.lazy(() => {
637
- return new Promise((resolve) => {
638
- import(
639
- /* webpackChunkName: "handlerModal" */
640
- /* webpackInclude: /\.tsx?$/ */
641
- `/api/modals/${path}`
642
- ).then((result) => {
643
- resolve(
644
- result
645
- );
646
- }).catch((error) => {
647
- resolve({
648
- default: () => {
649
- console.error(error);
650
- throw new Error(
651
- `The above error ocurred at component ApiaApiHandler/${path}, does it exist?`
652
- );
653
- }
654
- });
655
- });
656
- });
657
- });
658
- }, []);
659
- const [Submodal, setSubmodal] = React__default.useState(null);
660
- useMount(() => {
661
- if (element.modalFunction) {
662
- const found = element.modalFunction.match(/(?:fnc)?(\w+)\(?\)?$/);
663
- if (found) {
664
- const modalName = found[found.length - 1];
665
- setSubmodal(getModal(modalName));
666
- }
667
- }
668
- });
669
- const className = React__default.useMemo(
670
- () => element.class ? `handler__${element.type} ${element.class}` : `handler__${element.type}`,
671
- [element.class, element.type]
672
- );
673
- const validationRules = React__default.useMemo(
674
- () => __spreadValues$5({
675
- required: element.mandatory,
676
- maxLength: element.maxlength ? Number(element.maxlength) : void 0,
677
- pattern: element.regExp,
678
- patternMessage: element.regExpMessage
679
- }, classToValidate(element.class)),
680
- [
681
- element.class,
682
- element.mandatory,
683
- element.maxlength,
684
- element.regExp,
685
- element.regExpMessage
686
- ]
687
- );
688
- const validationFunction = React__default.useMemo(
689
- () => classToValidationFunction(element.class),
690
- [element.class]
691
- );
692
- const submitValueParser = React__default.useCallback(
693
- (value) => {
694
- if (element.type === "password") {
695
- return encrypt(
696
- window.SALT,
697
- window.IV,
698
- window.PASSPHRASE,
699
- value,
700
- Number(window.KEY_SIZE),
701
- Number(window.ITERATION_COUNT)
702
- );
703
- }
704
- return value;
705
- },
706
- [element.type]
707
- );
708
- if (element.modalFunction) {
709
- if (Submodal) {
710
- return /* @__PURE__ */ jsx(React__default.Suspense, { children: /* @__PURE__ */ jsx(Submodal, __spreadProps$3(__spreadValues$5({}, props), { element })) });
711
- }
712
- return null;
713
- }
714
- return /* @__PURE__ */ jsx(
715
- Input,
716
- {
717
- type: element.type,
718
- className,
719
- name: element.id || element.name,
720
- label: element.text,
721
- title: element.title || element.text,
722
- value: element.value,
723
- readOnly: element.readonly,
724
- disabled: element.disabled,
725
- validationFunction,
726
- validationRules,
727
- submitValueParser,
728
- onChange: element.onChange,
729
- autoComplete: element.type === "password" ? "new-password" : void 0
730
- }
731
- );
732
- };
733
- ApiaApiInput.displayName = "ApiaApiInput";
734
-
735
- var __defProp$4 = Object.defineProperty;
736
- var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
737
- var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
738
- var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
739
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
740
- var __spreadValues$4 = (a, b) => {
741
- for (var prop in b || (b = {}))
742
- if (__hasOwnProp$4.call(b, prop))
743
- __defNormalProp$4(a, prop, b[prop]);
744
- if (__getOwnPropSymbols$4)
745
- for (var prop of __getOwnPropSymbols$4(b)) {
746
- if (__propIsEnum$4.call(b, prop))
747
- __defNormalProp$4(a, prop, b[prop]);
748
- }
749
- return a;
750
- };
751
- const ApiaApiRadio = (props) => {
752
- var _a;
753
- const element = React__default.useMemo(() => props.element, [props.element]);
754
- const className = React__default.useMemo(
755
- () => element.class ? `handler__radio ${element.class}` : "handler__radio",
756
- [element.class]
757
- );
758
- const options = React__default.useMemo(
759
- () => {
760
- var _a2;
761
- return arrayOrArray((_a2 = element.options) == null ? void 0 : _a2.option).map((currOption) => {
762
- return { value: currOption.value, label: currOption.content };
763
- });
764
- },
765
- [(_a = element.options) == null ? void 0 : _a.option]
766
- );
767
- const validationRules = React__default.useMemo(
768
- () => __spreadValues$4({
769
- required: element.mandatory
770
- }, classToValidate(element.class)),
771
- [element.class, element.mandatory]
772
- );
773
- return /* @__PURE__ */ jsx(
774
- Radio,
775
- {
776
- className,
777
- name: element.id || element.name,
778
- label: element.text,
779
- title: element.title || element.text,
780
- value: element.value,
781
- disabled: element.readonly || element.disabled,
782
- validationRules,
783
- options,
784
- onChange: element.onChange
785
- }
786
- );
787
- };
788
- ApiaApiRadio.displayName = "ApiaApiRadio";
789
-
790
- var __defProp$3 = Object.defineProperty;
791
- var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
792
- var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
793
- var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
794
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
795
- var __spreadValues$3 = (a, b) => {
796
- for (var prop in b || (b = {}))
797
- if (__hasOwnProp$3.call(b, prop))
798
- __defNormalProp$3(a, prop, b[prop]);
799
- if (__getOwnPropSymbols$3)
800
- for (var prop of __getOwnPropSymbols$3(b)) {
801
- if (__propIsEnum$3.call(b, prop))
802
- __defNormalProp$3(a, prop, b[prop]);
803
- }
804
- return a;
805
- };
806
- const ApiaApiSelect = (props) => {
807
- var _a;
808
- const element = React__default.useMemo(() => props.element, [props.element]);
809
- const className = React__default.useMemo(
810
- () => element.class ? `handler__select ${element.class}` : "handler__select",
811
- [element.class]
812
- );
813
- const options = React__default.useMemo(
814
- () => {
815
- var _a2;
816
- return arrayOrArray((_a2 = element.options) == null ? void 0 : _a2.option).map((currOption) => {
817
- return { value: currOption.value, label: currOption.content };
818
- });
819
- },
820
- [(_a = element.options) == null ? void 0 : _a.option]
821
- );
822
- const validationRules = React__default.useMemo(
823
- () => __spreadValues$3({
824
- required: element.mandatory
825
- }, classToValidate(element.class)),
826
- [element.class, element.mandatory]
827
- );
828
- const initialValue = useMemo(
829
- () => {
830
- var _a2, _b, _c, _d;
831
- return (_d = (_c = (_a2 = options.find((current) => current.value === props.element.value)) == null ? void 0 : _a2.value) != null ? _c : (_b = options[0]) == null ? void 0 : _b.value) != null ? _d : "";
832
- },
833
- // eslint-disable-next-line react-hooks/exhaustive-deps
834
- []
835
- );
836
- return /* @__PURE__ */ jsx(
837
- Select,
838
- {
839
- className,
840
- name: element.id || element.name,
841
- label: element.text,
842
- title: element.title || element.text,
843
- value: element.value,
844
- disabled: element.readonly || element.disabled,
845
- validationRules,
846
- options,
847
- onChange: element.onChange,
848
- initialValue
849
- }
850
- );
851
- };
852
- ApiaApiSelect.displayName = "ApiaApiSelect";
853
-
854
- var __defProp$2 = Object.defineProperty;
855
- var __defProps$2 = Object.defineProperties;
856
- var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
857
- var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
858
- var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
859
- var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
860
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
861
- var __spreadValues$2 = (a, b) => {
862
- for (var prop in b || (b = {}))
863
- if (__hasOwnProp$2.call(b, prop))
864
- __defNormalProp$2(a, prop, b[prop]);
865
- if (__getOwnPropSymbols$2)
866
- for (var prop of __getOwnPropSymbols$2(b)) {
867
- if (__propIsEnum$2.call(b, prop))
868
- __defNormalProp$2(a, prop, b[prop]);
869
- }
870
- return a;
871
- };
872
- var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
873
- const ApiaApiFieldsContainer = (props) => {
874
- var _a, _b;
875
- const elements = React__default.useMemo(
876
- () => {
877
- var _a2, _b2, _c;
878
- return arrayOrArray((_c = (_b2 = (_a2 = props == null ? void 0 : props.definition) == null ? void 0 : _a2.form.elements) == null ? void 0 : _b2.element) != null ? _c : []);
879
- },
880
- [(_b = (_a = props == null ? void 0 : props.definition) == null ? void 0 : _a.form.elements) == null ? void 0 : _b.element]
881
- );
882
- const getSections = React__default.useCallback(() => {
883
- var _a2;
884
- const removeEndingSpacers = (sectionElements) => {
885
- if (sectionElements.length > 1) {
886
- for (let i = sectionElements.length - 1; i >= 0; i--) {
887
- if (sectionElements[i].type === "empty") {
888
- sectionElements.pop();
889
- } else {
890
- return sectionElements;
891
- }
892
- }
893
- }
894
- return sectionElements;
895
- };
896
- const sectionIndexes = [];
897
- if (((_a2 = elements[0]) == null ? void 0 : _a2.type) !== "2columnTitle") {
898
- sectionIndexes.push(-1);
899
- }
900
- elements.forEach((element, index) => {
901
- if (element.type === "2columnTitle") {
902
- sectionIndexes.push(index);
903
- }
904
- });
905
- const sections2 = [];
906
- sectionIndexes.forEach((sectionIndex, arrayIndex) => {
907
- const start = sectionIndex + 1 < elements.length ? sectionIndex + 1 : elements.length - 1;
908
- const end = arrayIndex + 1 < sectionIndexes.length ? sectionIndexes[arrayIndex + 1] : void 0;
909
- sections2.push({
910
- sectionHeader: sectionIndex !== -1 ? elements[sectionIndex] : void 0,
911
- sectionElements: removeEndingSpacers(elements.slice(start, end))
912
- });
913
- });
914
- return sections2;
915
- }, [elements]);
916
- const sections = getSections();
917
- const renderSectionContent = React__default.useCallback(
918
- (sectionElements) => {
919
- const isVisible = sectionElements.findIndex((element) => element.type !== "hidden") !== -1;
920
- return /* @__PURE__ */ jsx(
921
- Box,
922
- {
923
- className: isVisible ? "handler__form__elements__section__content" : `handler__form__elements__section__content handler__hidden`,
924
- children: sectionElements.map((current) => {
925
- const element = __spreadProps$2(__spreadValues$2({}, current), {
926
- onChange() {
927
- getFunction(current.onChange, props).then((onChangeMethod) => {
928
- if (onChangeMethod) {
929
- onChangeMethod();
930
- }
931
- }).catch(console.error);
932
- }
933
- });
934
- const elementKey = element.id || element.name || uniqueId();
935
- switch (element.type) {
936
- case "table": {
937
- const data = JSON.parse(element.text);
938
- return /* @__PURE__ */ jsx(
939
- Box,
940
- __spreadProps$2(__spreadValues$2({}, getVariant("layout.common.tables.information")), {
941
- children: /* @__PURE__ */ jsxs("table", { sx: { width: "100%" }, children: [
942
- /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsx("tr", { children: data.columns.map((column) => {
943
- return /* @__PURE__ */ jsx("th", { children: column }, column);
944
- }) }) }),
945
- /* @__PURE__ */ jsx("tbody", { children: data.rows.map((row) => {
946
- return /* @__PURE__ */ jsx("tr", { children: row.cells.map((cell, i) => {
947
- return /* @__PURE__ */ jsx("td", { children: cell }, `${cell}_${data.columns[i]}`);
948
- }) }, row.cells.join("-"));
949
- }) })
950
- ] })
951
- }),
952
- elementKey
953
- );
954
- }
955
- case "2columnSubTitle":
956
- return /* @__PURE__ */ jsx(Box, { className: element.class, as: "h6", children: element.value || element.text }, elementKey);
957
- case "2column":
958
- return /* @__PURE__ */ jsx(
959
- Box,
960
- {
961
- dangerouslySetInnerHTML: {
962
- __html: element.value || element.text
963
- },
964
- className: element.class
965
- },
966
- elementKey
967
- );
968
- case "checkbox":
969
- return /* @__PURE__ */ jsx(
970
- ApiaApiCheckbox,
971
- __spreadProps$2(__spreadValues$2({}, props), {
972
- element
973
- }),
974
- elementKey
975
- );
976
- case "file":
977
- return /* @__PURE__ */ jsx(
978
- ApiaApiFileInput,
979
- __spreadProps$2(__spreadValues$2({}, props), {
980
- element
981
- }),
982
- elementKey
983
- );
984
- case "hidden":
985
- case "password":
986
- case "text":
987
- return /* @__PURE__ */ jsx(ApiaApiInput, __spreadProps$2(__spreadValues$2({}, props), { element }), elementKey);
988
- case "select":
989
- return /* @__PURE__ */ jsx(
990
- ApiaApiSelect,
991
- __spreadProps$2(__spreadValues$2({}, props), {
992
- element
993
- }),
994
- elementKey
995
- );
996
- case "radio":
997
- return /* @__PURE__ */ jsx(ApiaApiRadio, __spreadProps$2(__spreadValues$2({}, props), { element }), elementKey);
998
- case "empty":
999
- return /* @__PURE__ */ jsx(Box, { className: "spacer" }, elementKey);
1000
- default:
1001
- console.warn(
1002
- `Unhandled element type: ${element.type}`,
1003
- element
1004
- );
1005
- return null;
1006
- }
1007
- })
1008
- },
1009
- uniqueId()
1010
- );
1011
- },
1012
- [props]
1013
- );
1014
- return /* @__PURE__ */ jsx(Box, { className: "handler__form__elements", children: sections.map((section) => {
1015
- if (section.sectionHeader) {
1016
- return renderSectionContent(section.sectionElements);
1017
- }
1018
- return renderSectionContent(section.sectionElements);
1019
- }) });
1020
- };
1021
- ApiaApiFieldsContainer.displayName = "ApiaApiFieldsContainer";
1022
-
1023
- var __defProp$1 = Object.defineProperty;
1024
- var __defProps$1 = Object.defineProperties;
1025
- var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
1026
- var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
1027
- var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
1028
- var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
1029
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1030
- var __spreadValues$1 = (a, b) => {
1031
- for (var prop in b || (b = {}))
1032
- if (__hasOwnProp$1.call(b, prop))
1033
- __defNormalProp$1(a, prop, b[prop]);
1034
- if (__getOwnPropSymbols$1)
1035
- for (var prop of __getOwnPropSymbols$1(b)) {
1036
- if (__propIsEnum$1.call(b, prop))
1037
- __defNormalProp$1(a, prop, b[prop]);
1038
- }
1039
- return a;
1040
- };
1041
- var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
1042
- var __async$1 = (__this, __arguments, generator) => {
1043
- return new Promise((resolve, reject) => {
1044
- var fulfilled = (value) => {
1045
- try {
1046
- step(generator.next(value));
1047
- } catch (e) {
1048
- reject(e);
1049
- }
1050
- };
1051
- var rejected = (value) => {
1052
- try {
1053
- step(generator.throw(value));
1054
- } catch (e) {
1055
- reject(e);
1056
- }
1057
- };
1058
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
1059
- step((generator = generator.apply(__this, __arguments)).next());
1060
- });
1061
- };
1062
- var __forAwait = (obj, it, method) => {
1063
- it = obj[Symbol.asyncIterator];
1064
- method = (key, fn) => (fn = obj[key]) && (it[key] = (arg) => new Promise((resolve, reject, done) => {
1065
- arg = fn.call(obj, arg);
1066
- done = arg.done;
1067
- return Promise.resolve(arg.value).then((value) => resolve({ value, done }), reject);
1068
- }));
1069
- return it ? it.call(obj) : (obj = obj[Symbol.iterator](), it = {}, method("next"), method("return"), it);
1070
- };
1071
- const NonMemoizedApiaApiButtonsContainer = (props) => {
1072
- var _a, _b, _c, _d, _e;
1073
- const buttons = arrayOrArray((_c = (_b = (_a = props.definition) == null ? void 0 : _a.form.buttons) == null ? void 0 : _b.button) != null ? _c : []);
1074
- const modalConfiguration = (_d = props.configuration) == null ? void 0 : _d.modalConfiguration;
1075
- const methodsPath = (_e = props.configuration) == null ? void 0 : _e.methodsPath;
1076
- const { name: apiaApiForm } = useFormContext();
1077
- const renderButton = React__default.useCallback(
1078
- (button) => {
1079
- const key = uniqueId();
1080
- const buttonType = ["submitAjax", "submit"].includes(button.type) && !button.onclick ? "submit" : "button";
1081
- const className = `handler__${buttonType}`;
1082
- const onClick = () => {
1083
- void function submitForm() {
1084
- return __async$1(this, null, function* () {
1085
- const validationResult = yield validationsStore.validateForm(
1086
- apiaApiForm
1087
- );
1088
- if (!hasSucceedFormValidation(validationResult)) {
1089
- return;
1090
- }
1091
- const { submitValues } = validationResult;
1092
- if ((props == null ? void 0 : props.definition) && ["submitAjax", "submit"].includes(button.type)) {
1093
- const formData = new FormData();
1094
- Object.entries(submitValues).forEach(([name, value]) => {
1095
- formData.append(name, value != null ? value : "");
1096
- });
1097
- const hasContext = props == null ? void 0 : props.definition.form.action.match(
1098
- new RegExp(`^${window.CONTEXT}/`)
1099
- );
1100
- const url = `${hasContext ? "" : window.CONTEXT}${!(props == null ? void 0 : props.definition.form.action.startsWith("/")) ? "/" : ""}${props == null ? void 0 : props.definition.form.action}`;
1101
- props.setState((current) => __spreadProps$1(__spreadValues$1({}, current), {
1102
- isLoading: true
1103
- }));
1104
- void ApiaApi.post(url, {
1105
- postData: props.state.isMultipart ? formData : QueryString.stringify(
1106
- [...formData.entries(), ["isAjax", true]].reduce((accumulated, [name, value]) => {
1107
- const retValue = __spreadValues$1({}, accumulated);
1108
- retValue[name.toString()] = value.toString();
1109
- return retValue;
1110
- }, {})
1111
- ),
1112
- handleLoad: true,
1113
- notificationsCategory: "apiaApiHandler",
1114
- modalConfiguration,
1115
- methodsPath
1116
- }).finally(() => {
1117
- void (() => __async$1(this, null, function* () {
1118
- var _a2, _b2, _c2, _d2;
1119
- if (button.onclick) {
1120
- const actions = button.onclick.split(";");
1121
- try {
1122
- for (var iter = __forAwait(actions), more, temp, error; more = !(temp = yield iter.next()).done; more = false) {
1123
- const action = temp.value;
1124
- const method = yield getFunction(action, __spreadValues$1({}, props));
1125
- if (method)
1126
- method({
1127
- currentUrl: (_b2 = (_a2 = props.definition) == null ? void 0 : _a2.form.action) != null ? _b2 : "noUrl"
1128
- });
1129
- else {
1130
- throw new Error(
1131
- `The requested action is not defined: "${(_d2 = (_c2 = props.definition) == null ? void 0 : _c2.form.action) != null ? _d2 : ""}"`
1132
- );
1133
- }
1134
- }
1135
- } catch (temp) {
1136
- error = [temp];
1137
- } finally {
1138
- try {
1139
- more && (temp = iter.return) && (yield temp.call(iter));
1140
- } finally {
1141
- if (error)
1142
- throw error[0];
1143
- }
1144
- }
1145
- }
1146
- }))();
1147
- });
1148
- }
1149
- });
1150
- }();
1151
- };
1152
- return /* @__PURE__ */ jsx(
1153
- SimpleButton,
1154
- {
1155
- className,
1156
- disabled: props.state.disabled,
1157
- id: button.id || button.text,
1158
- isLoading: props.state.isLoading,
1159
- title: button.text,
1160
- type: buttonType,
1161
- onClick,
1162
- children: button.text
1163
- },
1164
- key
1165
- );
1166
- },
1167
- [apiaApiForm, methodsPath, modalConfiguration, props]
1168
- );
1169
- return /* @__PURE__ */ jsx(Box, { className: "handler__form__buttons", children: buttons.map((currentButton) => renderButton(currentButton)) });
1170
- };
1171
- const ApiaApiButtonsContainer = React__default.memo(
1172
- NonMemoizedApiaApiButtonsContainer
1173
- );
1174
-
1175
- var __defProp = Object.defineProperty;
1176
- var __defProps = Object.defineProperties;
1177
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
1178
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
1179
- var __hasOwnProp = Object.prototype.hasOwnProperty;
1180
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
1181
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1182
- var __spreadValues = (a, b) => {
1183
- for (var prop in b || (b = {}))
1184
- if (__hasOwnProp.call(b, prop))
1185
- __defNormalProp(a, prop, b[prop]);
1186
- if (__getOwnPropSymbols)
1187
- for (var prop of __getOwnPropSymbols(b)) {
1188
- if (__propIsEnum.call(b, prop))
1189
- __defNormalProp(a, prop, b[prop]);
1190
- }
1191
- return a;
1192
- };
1193
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1194
- var __objRest = (source, exclude) => {
1195
- var target = {};
1196
- for (var prop in source)
1197
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
1198
- target[prop] = source[prop];
1199
- if (source != null && __getOwnPropSymbols)
1200
- for (var prop of __getOwnPropSymbols(source)) {
1201
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
1202
- target[prop] = source[prop];
1203
- }
1204
- return target;
1205
- };
1206
- var __async = (__this, __arguments, generator) => {
1207
- return new Promise((resolve, reject) => {
1208
- var fulfilled = (value) => {
1209
- try {
1210
- step(generator.next(value));
1211
- } catch (e) {
1212
- reject(e);
1213
- }
1214
- };
1215
- var rejected = (value) => {
1216
- try {
1217
- step(generator.throw(value));
1218
- } catch (e) {
1219
- reject(e);
1220
- }
1221
- };
1222
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
1223
- step((generator = generator.apply(__this, __arguments)).next());
1224
- });
1225
- };
1226
- const ApiaApiMessenger = new class extends EventEmitter {
1227
- }();
1228
- const FunctionsDispatcher = new class extends EventEmitter {
1229
- }();
1230
- const apiaApiForm = "ApiaApiForm";
1231
- const methods = {};
1232
- function getFunction(name, handler) {
1233
- return __async(this, null, function* () {
1234
- return new Promise((resolve) => {
1235
- var _a, _b, _c;
1236
- try {
1237
- const separateNameFromParametersRegex = /^\/?([\w\d_-]+)\/?(?:\(([^)]*)\))?$/;
1238
- const match = name.match(separateNameFromParametersRegex);
1239
- if (match) {
1240
- const functionName = match[1];
1241
- const parameters = match[2];
1242
- const path = [
1243
- ...(_c = (_b = (_a = handler.configuration) == null ? void 0 : _a.methodsPath) == null ? void 0 : _b.split("/").filter((current) => {
1244
- return !!current;
1245
- })) != null ? _c : [],
1246
- functionName
1247
- ].join("/");
1248
- const storeMethodAndResolve = (result) => {
1249
- if (typeof result.default !== "function")
1250
- notFound();
1251
- const method = result.default;
1252
- methods[functionName] = (props) => {
1253
- var _a2;
1254
- return method(handler, __spreadProps(__spreadValues({}, props), {
1255
- inlineArguments: (_a2 = parameters == null ? void 0 : parameters.split(",").map((argument) => {
1256
- if (argument.startsWith("'") || argument.startsWith('"'))
1257
- return argument.slice(1, argument.length - 1);
1258
- return argument;
1259
- })) != null ? _a2 : []
1260
- }));
1261
- };
1262
- resolve(methods[functionName]);
1263
- };
1264
- const notFound = () => {
1265
- throw new Error(
1266
- `${functionName}.ts not found at ${path}.ts nor ./${functionName}.ts`
1267
- );
1268
- };
1269
- import(
1270
- /* webpackChunkName: "api-methods-[request]" */
1271
- `/api/methods/${path}.ts`
1272
- ).then(storeMethodAndResolve).catch(() => {
1273
- var _a2;
1274
- if (((_a2 = handler.configuration) == null ? void 0 : _a2.methodsPath) !== void 0)
1275
- import(
1276
- /* webpackChunkName: "api-methods-[request]" */
1277
- `/api/methods/${functionName}.ts`
1278
- ).then(storeMethodAndResolve).catch(notFound);
1279
- else
1280
- notFound();
1281
- });
1282
- }
1283
- } catch (e) {
1284
- console.error(e);
1285
- handler.reset();
1286
- handler.setError({
1287
- type: "danger",
1288
- message: "Error while loading current method."
1289
- });
1290
- }
1291
- });
1292
- });
1293
- }
1294
- function isForm(responseObject) {
1295
- return typeof responseObject.canClose === "boolean" && typeof responseObject.type === "string" && !!responseObject.form;
1296
- }
1297
- function isFunction(responseObject) {
1298
- return typeof responseObject.canClose === "boolean" && typeof responseObject.type === "string" && !!responseObject.function;
1299
- }
1300
- function isMessage(responseObject) {
1301
- if (typeof responseObject.canClose === "boolean" && typeof responseObject.type === "string" && typeof responseObject.text === "object" && responseObject.text && typeof responseObject.text.label === "string") {
1302
- return true;
1303
- }
1304
- return false;
1305
- }
1306
- const modalConfigurationHandler = new WithEventsValue();
1307
- function useModalConfiguration() {
1308
- const [, setValue, value] = useStateRef(
1309
- void 0
1310
- );
1311
- const handleChange = React.useCallback(
1312
- (newEventsHandler) => {
1313
- setValue(newEventsHandler);
1314
- },
1315
- [setValue]
1316
- );
1317
- useMount(() => {
1318
- modalConfigurationHandler.on("update", handleChange);
1319
- });
1320
- useUnmount(() => {
1321
- return modalConfigurationHandler.off("update", handleChange);
1322
- });
1323
- return value;
1324
- }
1325
- const currentFormDispatcher = new class currentFormDispatcher2 extends EventEmitter {
1326
- emit(eventName, params) {
1327
- super.emit(eventName, params);
1328
- }
1329
- }();
1330
- function handle(responseObject, currentUrl, configuration) {
1331
- modalConfigurationHandler.value = configuration;
1332
- if (isForm(responseObject)) {
1333
- currentFormDispatcher.emit("form", responseObject);
1334
- return true;
1335
- }
1336
- if (isFunction(responseObject)) {
1337
- FunctionsDispatcher.emit("method", {
1338
- name: responseObject.function.name,
1339
- props: {
1340
- messages: responseObject.function.messages,
1341
- attributes: responseObject.function,
1342
- currentUrl
1343
- }
1344
- });
1345
- return true;
1346
- }
1347
- if (isMessage(responseObject)) {
1348
- ApiaApiMessenger.emit("message", {
1349
- predicate: responseObject.text.content,
1350
- title: responseObject.text.title
1351
- });
1352
- return true;
1353
- }
1354
- return false;
1355
- }
1356
- const initialState = {
1357
- disabled: false,
1358
- isLoading: false,
1359
- isMultipart: false,
1360
- progress: 0,
1361
- errors: {}
1362
- };
1363
- const ApiaApiHandlerNonMemoized = () => {
1364
- var _b, _c, _d;
1365
- const configuration = useModalConfiguration();
1366
- const [state, setState] = React.useState(__spreadProps(__spreadValues({}, initialState), {
1367
- windowIndex: -1
1368
- }));
1369
- const [currentForm2, setCurrentForm] = React.useState(
1370
- void 0
1371
- );
1372
- React.useEffect(() => {
1373
- return currentFormDispatcher.on("form", setCurrentForm);
1374
- }, []);
1375
- const setValue = React.useCallback((name, value) => {
1376
- return validationsStore.setFieldValue(apiaApiForm, name, value);
1377
- }, []);
1378
- React.useEffect(() => {
1379
- var _a2, _b2, _c2;
1380
- if (!currentForm2)
1381
- return;
1382
- const elements = arrayOrArray((_c2 = (_b2 = (_a2 = currentForm2 == null ? void 0 : currentForm2.form) == null ? void 0 : _a2.elements) == null ? void 0 : _b2.element) != null ? _c2 : []);
1383
- let isMultipart = false;
1384
- const elementsValues = Object.values(elements);
1385
- let i = 0;
1386
- while (i < elementsValues.length && !isMultipart) {
1387
- if (elementsValues[i++].type === "file") {
1388
- isMultipart = true;
1389
- }
1390
- }
1391
- setState((currentState) => {
1392
- return __spreadProps(__spreadValues(__spreadValues({}, currentState), initialState), {
1393
- isMultipart
1394
- });
1395
- });
1396
- }, [currentForm2]);
1397
- const _a = useModal(), { show, onClose } = _a, modalProps = __objRest(_a, ["show", "onClose"]);
1398
- const close = React.useCallback(() => {
1399
- var _a2, _b2;
1400
- onClose();
1401
- currentFormDispatcher.emit("form", void 0);
1402
- setState((currentState) => {
1403
- return __spreadValues(__spreadValues({}, currentState), initialState);
1404
- });
1405
- if ((_b2 = (_a2 = configuration.current) == null ? void 0 : _a2.modalConfiguration) == null ? void 0 : _b2.onClose)
1406
- configuration.current.modalConfiguration.onClose();
1407
- validationsStore.unregisterForm(apiaApiForm);
1408
- }, [onClose, configuration]);
1409
- const modalRef = React.useRef(null);
1410
- React.useEffect(() => {
1411
- var _a2;
1412
- const elements = (_a2 = modalRef.current) == null ? void 0 : _a2.querySelectorAll(
1413
- "a,input,textarea,button"
1414
- );
1415
- if ((elements == null ? void 0 : elements.length) === 1)
1416
- void focus.on([...elements][0]);
1417
- });
1418
- const setError = React.useCallback(
1419
- (notification) => {
1420
- notify(__spreadValues({}, notification));
1421
- },
1422
- []
1423
- );
1424
- const getHandler = React.useCallback(() => {
1425
- const newHandler = {
1426
- alert,
1427
- close,
1428
- configuration: configuration.current,
1429
- formDefinition: currentForm2,
1430
- reset: () => {
1431
- return setState((currentState) => {
1432
- return __spreadValues(__spreadValues({}, currentState), initialState);
1433
- });
1434
- },
1435
- setError,
1436
- setMessage: (message) => {
1437
- var _a2, _b2;
1438
- if ((_b2 = (_a2 = configuration.current) == null ? void 0 : _a2.modalConfiguration) == null ? void 0 : _b2.onMessage)
1439
- configuration.current.modalConfiguration.onMessage(message);
1440
- },
1441
- setState,
1442
- state,
1443
- setValue
1444
- };
1445
- return newHandler;
1446
- }, [close, configuration, currentForm2, setError, state, setValue]);
1447
- React.useEffect(() => {
1448
- const handleFunction = (_0) => __async(void 0, [_0], function* ({
1449
- name,
1450
- props: { messages, attributes, currentUrl }
1451
- }) {
1452
- const method = yield getFunction(`${name}`, getHandler());
1453
- if (method) {
1454
- method({ messages, attributes, currentUrl });
1455
- }
1456
- });
1457
- const handleMessage = (ev) => {
1458
- var _a2, _b2, _c2, _d2;
1459
- const handler2 = getHandler();
1460
- notify({
1461
- message: ev.predicate,
1462
- type: "warning",
1463
- onClose: (_b2 = (_a2 = handler2.configuration) == null ? void 0 : _a2.modalConfiguration) == null ? void 0 : _b2.onMessageClose
1464
- });
1465
- const onMessage = (_d2 = (_c2 = handler2.configuration) == null ? void 0 : _c2.modalConfiguration) == null ? void 0 : _d2.onMessage;
1466
- if (onMessage)
1467
- onMessage(ev);
1468
- };
1469
- const handleAction = (action) => __async(void 0, null, function* () {
1470
- if (action.toDo === "ajaxHiddeAll") {
1471
- close();
1472
- }
1473
- if (action.toDo === "functionTimedCall") {
1474
- const method = yield getFunction(
1475
- arrayOrArray(action.param)[1],
1476
- getHandler()
1477
- );
1478
- if (method)
1479
- setTimeout(() => {
1480
- var _a2;
1481
- return method({
1482
- currentUrl: (_a2 = currentForm2 == null ? void 0 : currentForm2.form.action) != null ? _a2 : "noUrl"
1483
- });
1484
- }, Number(action.param[0]));
1485
- }
1486
- });
1487
- ApiaApiMessenger.on("message", handleMessage);
1488
- FunctionsDispatcher.on("method", handleFunction);
1489
- ApiaActions.on("action", handleAction);
1490
- return () => {
1491
- ApiaApiMessenger.off("message", handleMessage);
1492
- FunctionsDispatcher.off("method", handleFunction);
1493
- ApiaActions.off("action", handleAction);
1494
- };
1495
- }, [state.windowIndex, onClose, close]);
1496
- React.useEffect(() => {
1497
- if (currentForm2) {
1498
- show();
1499
- }
1500
- }, [currentForm2]);
1501
- const handler = getHandler();
1502
- const formRef = React.useCallback(
1503
- (el) => __async(void 0, null, function* () {
1504
- if (el && (currentForm2 == null ? void 0 : currentForm2.form.onLoad)) {
1505
- const method = yield getFunction(
1506
- `${currentForm2 == null ? void 0 : currentForm2.form.onLoad}`,
1507
- getHandler()
1508
- );
1509
- if (method) {
1510
- method();
1511
- }
1512
- }
1513
- }),
1514
- [currentForm2 == null ? void 0 : currentForm2.form.onLoad, getHandler]
1515
- );
1516
- return /* @__PURE__ */ jsx(ApiaApiContext$1, { id: apiaApiForm, children: /* @__PURE__ */ jsx(
1517
- Modal,
1518
- __spreadProps(__spreadValues({
1519
- ref: modalRef,
1520
- onClose: close,
1521
- id: apiaApiForm,
1522
- title: (_d = (_c = (_b = configuration.current) == null ? void 0 : _b.modalConfiguration) == null ? void 0 : _c.modalTitle) != null ? _d : currentForm2 == null ? void 0 : currentForm2.form.title,
1523
- size: "md-fixed",
1524
- shouldCloseOnEsc: !state.disabled,
1525
- shouldCloseOnOverlayClick: !state.disabled,
1526
- initialFocusGetter: React.useCallback((ref) => {
1527
- return ref == null ? void 0 : ref.querySelector(focusSelector);
1528
- }, [])
1529
- }, modalProps), {
1530
- children: currentForm2 && /* @__PURE__ */ jsx(Box, __spreadProps(__spreadValues({}, getVariant("layout.common.modals.apiaApi")), { children: /* @__PURE__ */ jsxs(
1531
- Form,
1532
- {
1533
- name: apiaApiForm,
1534
- avoidFieldsOverride: true,
1535
- className: "handler__form",
1536
- children: [
1537
- /* @__PURE__ */ jsx(ApiaApiFieldsContainer, __spreadValues({ definition: currentForm2 }, handler)),
1538
- state.isMultipart && state.progress > 0 && /* @__PURE__ */ jsx(Box, { className: "progressBox", children: /* @__PURE__ */ jsx(
1539
- ProgressBar,
1540
- {
1541
- id: "ApiaApiHandler progress",
1542
- progress: state.progress,
1543
- loading: true
1544
- }
1545
- ) }),
1546
- /* @__PURE__ */ jsx(Box, { ref: formRef }),
1547
- /* @__PURE__ */ jsx(ApiaApiButtonsContainer, __spreadValues({ definition: currentForm2 }, handler))
1548
- ]
1549
- }
1550
- ) }))
1551
- })
1552
- ) });
1553
- };
1554
- const ApiaApiHandler = React.memo(ApiaApiHandlerNonMemoized);
1555
-
1556
- export { ApiaApi, ApiaApiHandler, makeApiaUrl };
1
+ import{jsx as p,jsxs as pe}from"react/jsx-runtime";import*as x from"react";import y,{createContext as et,useMemo as tt}from"react";import{Box as M}from"theme-ui";import{debugDispatcher as ot,EventEmitter as Q,parseXmlAsync as me,arrayOrArray as k,useMount as fe,encrypt as nt,WithEventsValue as rt,focus as at,focusSelector as lt,useStateRef as st,useUnmount as it}from"@apia/util";import{notify as U,getNotificationMessageObj as ct,dispatchNotifications as ut}from"@apia/notifications";import{classToValidate as V,Checkbox as dt,FileInput as pt,classToValidationFunction as mt,Input as ft,Radio as yt,Select as vt,useFormContext as gt,validationsStore as oe,hasSucceedFormValidation as ht,Form as bt}from"@apia/validations";import{SimpleButton as xt,useModal as wt,Modal as $t,ProgressBar as Ot}from"@apia/components";import{getVariant as ye}from"@apia/theme";import ve from"axios";import{merge as Ct,uniqueId as ne}from"lodash";import K from"qs";import{session as At}from"@apia/session";const Et=et("apiaApi"),_t=({children:t,id:e})=>p(Et.Provider,{value:e,children:t});var jt=x.memo(_t),Pt=Object.defineProperty,Mt=Object.defineProperties,St=Object.getOwnPropertyDescriptors,Z=Object.getOwnPropertySymbols,ge=Object.prototype.hasOwnProperty,he=Object.prototype.propertyIsEnumerable,be=(t,e,o)=>e in t?Pt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o,I=(t,e)=>{for(var o in e||(e={}))ge.call(e,o)&&be(t,o,e[o]);if(Z)for(var o of Z(e))he.call(e,o)&&be(t,o,e[o]);return t},R=(t,e)=>Mt(t,St(e)),xe=(t,e)=>{var o={};for(var n in t)ge.call(t,n)&&e.indexOf(n)<0&&(o[n]=t[n]);if(t!=null&&Z)for(var n of Z(t))e.indexOf(n)<0&&he.call(t,n)&&(o[n]=t[n]);return o},H=(t,e,o)=>new Promise((n,s)=>{var c=r=>{try{l(o.next(r))}catch(i){s(i)}},a=r=>{try{l(o.throw(r))}catch(i){s(i)}},l=r=>r.done?n(r.value):Promise.resolve(r.value).then(c,a);l((o=o.apply(t,e)).next())});ot.on("parseXml",t=>H(void 0,[t],function*([e]){const o=yield me(e);console.info(o)}),"Acepta un par\xE1metro de tipo string y realiza un parseo como si fuera xml, convirti\xE9ndolo a objeto javascript.");const q={debug:!0,colors:{exception:"red",alert:"yellow",message:"lightgreen"},handleLoad:!1},It="ApiaApiConfig";let we={};const $e=localStorage.getItem(It);$e&&(we=JSON.parse($e));function D(t){return Ct({},q,t,we)}function Oe(t,e,o){let n=t;const s=n.indexOf("?");s===-1?n+="?":s!==n.length-1&&!n.endsWith("&")&&(n+="&");let c=`${n}${e?K.stringify(e,o):""}`;return(c.endsWith("&")||c.endsWith("?"))&&(c=c.slice(0,c.length-1)),c}const Ce=t=>{var e;const o=(e=t.match(/action=(\w+)/))==null?void 0:e[1];return o??"noAction"},re=new class extends Q{};function N(t,e=(o=>(o=q.colors)!=null?o:{exception:"red",alert:"yellow",message:"green"})()){return e[t]}const W=t=>{let e;typeof t!="string"?t.message?e=t.message:e=t.toString():e=t,U({type:"danger",message:t.message.replaceAll("AxiosError","Error")}),console.log("%c ","font-size:10vh"),console.log("%cError in ApiaApi","color:red;font-size:2em;font-weight:bold"),console.log(`red/${e}`,{error:t}),console.log("%c ","font-size:10vh")};function Nt(t){return t.headers["content-type"].match("application/json")}function Tt(t){return t.headers["content-type"].match(/(?:application|text)?\/xml/)}function kt(t){return t.headers["content-type"].match(/(?:application|text)?\/html/)}function Rt(t){var e,o;t&&(D().debug&&console.log("%cHandled actions: ",`color: ${(o=(e=D().colors)==null?void 0:e.message)!=null?o:"green"}`,{actions:t}),k(t.action).forEach(n=>{re.emit("action",R(I({},n),{param:k(n.param)}))}))}function Ae({exceptions:t,onClose:e,sysExceptions:o,sysMessages:n}){try{import(`/api/onClose/${e}.ts`).then(s=>{if(t||o||n){const c=ct({exceptions:t,onClose:e,sysExceptions:o,sysMessages:n});c?c.forEach(a=>{U(R(I({},a),{onClose:s.default}))}):s.default()}else s.default()},s=>{U({message:`onClose action not found: ${String(s)}`,type:"danger"})})}catch(s){Ee({exceptions:t,sysExceptions:o,sysMessages:n}),console.error("Error while handling onClose"),console.error(s)}}function Ee(t){if(!t)return;const{exceptions:e,sysMessages:o,sysExceptions:n}=t;if(e||n||o)try{ut({exceptions:e,sysExceptions:n,sysMessages:o})}catch(s){W(new Error(s))}}const Dt=(t,e,...o)=>H(void 0,[t,e,...o],function*(n,s,c=q){var a;const l=D(c);let r;if(Nt(n))typeof n.data=="string"?r=JSON.parse(n.data.trim()):typeof n.data=="object"&&n.data&&(r=n.data);else if(Tt(n))r=yield me(n.data).catch(i=>{W(new Error(i))});else if(kt(n))return console.error("El contenido devuelto es Html, no se esperaba esa respuesta"),null;if(l.validateResponse){const i=yield l.validateResponse(R(I({},n),{data:(a=r?.load)!=null?a:r}));if(typeof i=="string")throw new Error(`Validation error: ${i}`);if(!i)throw new Error("Error")}if(r){const i=r,{actions:d,onClose:u,exceptions:g,sysExceptions:m,sysMessages:w,load:_}=i,O=xe(i,["actions","onClose","exceptions","sysExceptions","sysMessages","load"]);return O.code==="-1"&&g?(At.invalidate(),null):(g&&l.debug&&console.log("%cparseSuccessfulResponse",`color: ${N("exception",l.colors)}`,{exceptions:g}),m&&l.debug&&console.log("%cparseSuccessfulResponse",`color: ${N("exception",l.colors)}`,{sysExceptions:m}),w&&l.debug&&console.log("%cparseSuccessfulResponse",`color: ${N("alert",l.colors)}`,{sysMessages:w}),Rt(d),l.handleLoad&&u?Ae({exceptions:g,onClose:u,sysExceptions:m,sysMessages:w}):Ee({exceptions:g,sysExceptions:m,sysMessages:w}),_?(l.handleLoad&&(console.log("%chandleLoad",`color: ${N("message",l.colors)}`,{load:_}),Io(_,s,{methodsPath:c.methodsPath,modalConfiguration:R(I({},l.modalConfiguration),{onClose:()=>{var A,T;u&&Ae({exceptions:g,onClose:u,sysExceptions:m,sysMessages:w}),(A=l.modalConfiguration)!=null&&A.onClose&&((T=l.modalConfiguration)==null||T.onClose())}})})||console.log("%cunhandledLoad -> There is no handler defined",`color: ${N("exception",l.colors)}`,{load:_})),R(I({},_),{sysMessages:w,exceptions:g,sysExceptions:m})):R(I({},O),{sysMessages:w,exceptions:g,sysExceptions:m}))}return null});function _e(t,e){return H(this,arguments,function*(o,n,s=q){var c;const a=D(s);try{if(!o||o.data===void 0)a.debug&&console.log("%cApiaApi wrong response",`color: ${N("alert",a.colors)}`);else{const l=yield Dt(o,n,a),r=Ce(n);return a.debug&&console.log(`%c <- ApiaApi.${(c=o.config.method)!=null?c:""} ${r} `,`color: ${N("message",a.colors)}`,{data:l}),R(I({},o),{data:l,hasError:!!(l!=null&&l.exceptions)||!!(l!=null&&l.sysExceptions),hasMessages:!!(l!=null&&l.sysMessages)})}}catch(l){return W(new Error(l)),null}return null})}function Ft(t,e){return H(this,null,function*(){const o=typeof t!="string"?ae():t,n=typeof t=="string"?e??q:t,s=R(I({},D(n)),{postData:n.postDataTreatement==="stringify"?K.stringify(n.postData,n.stringifyOptions):n.postData}),c=Oe(o,s.queryData,s.stringifyOptions);if(s.debug){const l=o.split("&"),r=Ce(o);console.log(`%cApiaApi.post ${r}`,`color: ${N("message",s.colors)}`,{url:c,queryDataInURL:[...l],queryData:s.queryData,formData:s.postData,stringifyOptiopns:s.stringifyOptions})}const a=yield ve.post(c,s.postData,s.axiosConfig).catch(l=>{W(new Error(l))});return a?_e(a,o,s):null})}function Lt(t,e){return H(this,null,function*(){const o=typeof t!="string"?ae():t,n=D(typeof t=="string"?e??q:t),s=Oe(o,n.queryData,n.stringifyOptions);n.debug&&console.log("%cApiaApi.get",`color: ${N("message",n.colors)}`,{url:s});const c=yield ve.get(s,n.axiosConfig).catch(a=>{W(new Error(a))});return c?yield _e(c,o,n):null})}const je={get:Lt,getConfig:D,post:Ft};function ae(t){var e,o;let n={};if(t){const d=t,u=xe(d,["ajaxUrl","queryString","stringifyOptions","shouldAvoidTabId","preventAsXmlParameter","avoidTabId"]);n=I({},u)}const s=K.stringify(n,(e=t?.stringifyOptions)!=null?e:{arrayFormat:"repeat",encodeValuesOnly:!1});let c=(o=t?.ajaxUrl)!=null?o:window.URL_REQUEST_AJAX;c.indexOf("?")===c.length-1&&(c=c.slice(0,c.length-1)),c.startsWith("/")||(c=`/${c}`);const a=window.TAB_ID_REQUEST.match(/tokenId=(\w+)/),l=(a??[])[1];let r=(t!=null&&t.tabId?`&tabId=${t.tabId}&tokenId=${l}`:window.TAB_ID_REQUEST).slice(1);t!=null&&t.avoidTabId&&(r="");let{CONTEXT:i}=window;return i!=null&&i.endsWith("/")&&(i+=i.slice(0,i.length-1)),`${i}${c}?${t!=null&&t.preventAsXmlParameter?"":"asXml=true&"}${t!=null&&t.queryString?`${t.queryString}&`:""}${s?`${s}&`:""}${r}`}var qt=Object.defineProperty,Pe=Object.getOwnPropertySymbols,Ut=Object.prototype.hasOwnProperty,Vt=Object.prototype.propertyIsEnumerable,Me=(t,e,o)=>e in t?qt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o,Ht=(t,e)=>{for(var o in e||(e={}))Ut.call(e,o)&&Me(t,o,e[o]);if(Pe)for(var o of Pe(e))Vt.call(e,o)&&Me(t,o,e[o]);return t};const Wt=t=>{const e=y.useMemo(()=>t.element,[t.element]),o=y.useMemo(()=>e.class?`handler__checkbox ${e.class}`:"handler__checkbox",[e.class]),n=y.useMemo(()=>Ht({required:e.mandatory},V(e.class)),[e.class,e.mandatory]),s=y.useCallback(c=>c==="on"||c===!0,[]);return p(dt,{className:o,name:e.id||e.name,label:e.text,title:e.title||e.text,initialValue:String(e.selected)==="true",disabled:e.readonly||e.disabled,validationRules:n,onChange:e.onChange,submitValueParser:s})};var Xt=Object.defineProperty,Se=Object.getOwnPropertySymbols,Bt=Object.prototype.hasOwnProperty,zt=Object.prototype.propertyIsEnumerable,Ie=(t,e,o)=>e in t?Xt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o,Jt=(t,e)=>{for(var o in e||(e={}))Bt.call(e,o)&&Ie(t,o,e[o]);if(Se)for(var o of Se(e))zt.call(e,o)&&Ie(t,o,e[o]);return t};const Ne=t=>{const e=y.useMemo(()=>t.element,[t.element]),o=y.useMemo(()=>e.class?`handler__file ${e.class}`:"handler__file",[e.class]),n=y.useMemo(()=>Jt({required:e.mandatory},V(e.class)),[e.class,e.mandatory]);return p(pt,{className:o,name:e.id||e.name,label:e.text,title:e.title||e.text,readOnly:e.readonly,disabled:e.disabled,validationRules:n})};Ne.displayName="ApiaApiFileInput";var Qt=Object.defineProperty,Kt=Object.defineProperties,Zt=Object.getOwnPropertyDescriptors,Te=Object.getOwnPropertySymbols,Yt=Object.prototype.hasOwnProperty,Gt=Object.prototype.propertyIsEnumerable,ke=(t,e,o)=>e in t?Qt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o,Re=(t,e)=>{for(var o in e||(e={}))Yt.call(e,o)&&ke(t,o,e[o]);if(Te)for(var o of Te(e))Gt.call(e,o)&&ke(t,o,e[o]);return t},eo=(t,e)=>Kt(t,Zt(e));const De=t=>{const e=y.useMemo(()=>t.element,[t.element]),o=y.useCallback(i=>y.lazy(()=>new Promise(d=>{import(`/api/modals/${i}`).then(u=>{d(u)}).catch(u=>{d({default:()=>{throw console.error(u),new Error(`The above error ocurred at component ApiaApiHandler/${i}, does it exist?`)}})})})),[]),[n,s]=y.useState(null);fe(()=>{if(e.modalFunction){const i=e.modalFunction.match(/(?:fnc)?(\w+)\(?\)?$/);if(i){const d=i[i.length-1];s(o(d))}}});const c=y.useMemo(()=>e.class?`handler__${e.type} ${e.class}`:`handler__${e.type}`,[e.class,e.type]),a=y.useMemo(()=>Re({required:e.mandatory,maxLength:e.maxlength?Number(e.maxlength):void 0,pattern:e.regExp,patternMessage:e.regExpMessage},V(e.class)),[e.class,e.mandatory,e.maxlength,e.regExp,e.regExpMessage]),l=y.useMemo(()=>mt(e.class),[e.class]),r=y.useCallback(i=>e.type==="password"?nt(window.SALT,window.IV,window.PASSPHRASE,i,Number(window.KEY_SIZE),Number(window.ITERATION_COUNT)):i,[e.type]);return e.modalFunction?n?p(y.Suspense,{children:p(n,eo(Re({},t),{element:e}))}):null:p(ft,{type:e.type,className:c,name:e.id||e.name,label:e.text,title:e.title||e.text,value:e.value,readOnly:e.readonly,disabled:e.disabled,validationFunction:l,validationRules:a,submitValueParser:r,onChange:e.onChange,autoComplete:e.type==="password"?"new-password":void 0})};De.displayName="ApiaApiInput";var to=Object.defineProperty,Fe=Object.getOwnPropertySymbols,oo=Object.prototype.hasOwnProperty,no=Object.prototype.propertyIsEnumerable,Le=(t,e,o)=>e in t?to(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o,ro=(t,e)=>{for(var o in e||(e={}))oo.call(e,o)&&Le(t,o,e[o]);if(Fe)for(var o of Fe(e))no.call(e,o)&&Le(t,o,e[o]);return t};const qe=t=>{var e;const o=y.useMemo(()=>t.element,[t.element]),n=y.useMemo(()=>o.class?`handler__radio ${o.class}`:"handler__radio",[o.class]),s=y.useMemo(()=>{var a;return k((a=o.options)==null?void 0:a.option).map(l=>({value:l.value,label:l.content}))},[(e=o.options)==null?void 0:e.option]),c=y.useMemo(()=>ro({required:o.mandatory},V(o.class)),[o.class,o.mandatory]);return p(yt,{className:n,name:o.id||o.name,label:o.text,title:o.title||o.text,value:o.value,disabled:o.readonly||o.disabled,validationRules:c,options:s,onChange:o.onChange})};qe.displayName="ApiaApiRadio";var ao=Object.defineProperty,Ue=Object.getOwnPropertySymbols,lo=Object.prototype.hasOwnProperty,so=Object.prototype.propertyIsEnumerable,Ve=(t,e,o)=>e in t?ao(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o,io=(t,e)=>{for(var o in e||(e={}))lo.call(e,o)&&Ve(t,o,e[o]);if(Ue)for(var o of Ue(e))so.call(e,o)&&Ve(t,o,e[o]);return t};const He=t=>{var e;const o=y.useMemo(()=>t.element,[t.element]),n=y.useMemo(()=>o.class?`handler__select ${o.class}`:"handler__select",[o.class]),s=y.useMemo(()=>{var l;return k((l=o.options)==null?void 0:l.option).map(r=>({value:r.value,label:r.content}))},[(e=o.options)==null?void 0:e.option]),c=y.useMemo(()=>io({required:o.mandatory},V(o.class)),[o.class,o.mandatory]),a=tt(()=>{var l,r,i,d;return(d=(i=(l=s.find(u=>u.value===t.element.value))==null?void 0:l.value)!=null?i:(r=s[0])==null?void 0:r.value)!=null?d:""},[]);return p(vt,{className:n,name:o.id||o.name,label:o.text,title:o.title||o.text,value:o.value,disabled:o.readonly||o.disabled,validationRules:c,options:s,onChange:o.onChange,initialValue:a})};He.displayName="ApiaApiSelect";var co=Object.defineProperty,uo=Object.defineProperties,po=Object.getOwnPropertyDescriptors,We=Object.getOwnPropertySymbols,mo=Object.prototype.hasOwnProperty,fo=Object.prototype.propertyIsEnumerable,Xe=(t,e,o)=>e in t?co(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o,F=(t,e)=>{for(var o in e||(e={}))mo.call(e,o)&&Xe(t,o,e[o]);if(We)for(var o of We(e))fo.call(e,o)&&Xe(t,o,e[o]);return t},L=(t,e)=>uo(t,po(e));const Be=t=>{var e,o;const n=y.useMemo(()=>{var a,l,r;return k((r=(l=(a=t?.definition)==null?void 0:a.form.elements)==null?void 0:l.element)!=null?r:[])},[(o=(e=t?.definition)==null?void 0:e.form.elements)==null?void 0:o.element]),s=y.useCallback(()=>{var a;const l=d=>{if(d.length>1)for(let u=d.length-1;u>=0;u--)if(d[u].type==="empty")d.pop();else return d;return d},r=[];((a=n[0])==null?void 0:a.type)!=="2columnTitle"&&r.push(-1),n.forEach((d,u)=>{d.type==="2columnTitle"&&r.push(u)});const i=[];return r.forEach((d,u)=>{const g=d+1<n.length?d+1:n.length-1,m=u+1<r.length?r[u+1]:void 0;i.push({sectionHeader:d!==-1?n[d]:void 0,sectionElements:l(n.slice(g,m))})}),i},[n])(),c=y.useCallback(a=>{const l=a.findIndex(r=>r.type!=="hidden")!==-1;return p(M,{className:l?"handler__form__elements__section__content":"handler__form__elements__section__content handler__hidden",children:a.map(r=>{const i=L(F({},r),{onChange(){z(r.onChange,t).then(u=>{u&&u()}).catch(console.error)}}),d=i.id||i.name||ne();switch(i.type){case"table":{const u=JSON.parse(i.text);return p(M,L(F({},ye("layout.common.tables.information")),{children:pe("table",{sx:{width:"100%"},children:[p("thead",{children:p("tr",{children:u.columns.map(g=>p("th",{children:g},g))})}),p("tbody",{children:u.rows.map(g=>p("tr",{children:g.cells.map((m,w)=>p("td",{children:m},`${m}_${u.columns[w]}`))},g.cells.join("-")))})]})}),d)}case"2columnSubTitle":return p(M,{className:i.class,as:"h6",children:i.value||i.text},d);case"2column":return p(M,{dangerouslySetInnerHTML:{__html:i.value||i.text},className:i.class},d);case"checkbox":return p(Wt,L(F({},t),{element:i}),d);case"file":return p(Ne,L(F({},t),{element:i}),d);case"hidden":case"password":case"text":return p(De,L(F({},t),{element:i}),d);case"select":return p(He,L(F({},t),{element:i}),d);case"radio":return p(qe,L(F({},t),{element:i}),d);case"empty":return p(M,{className:"spacer"},d);default:return console.warn(`Unhandled element type: ${i.type}`,i),null}})},ne())},[t]);return p(M,{className:"handler__form__elements",children:s.map(a=>(a.sectionHeader,c(a.sectionElements)))})};Be.displayName="ApiaApiFieldsContainer";var yo=Object.defineProperty,vo=Object.defineProperties,go=Object.getOwnPropertyDescriptors,ze=Object.getOwnPropertySymbols,ho=Object.prototype.hasOwnProperty,bo=Object.prototype.propertyIsEnumerable,Je=(t,e,o)=>e in t?yo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o,le=(t,e)=>{for(var o in e||(e={}))ho.call(e,o)&&Je(t,o,e[o]);if(ze)for(var o of ze(e))bo.call(e,o)&&Je(t,o,e[o]);return t},xo=(t,e)=>vo(t,go(e)),Qe=(t,e,o)=>new Promise((n,s)=>{var c=r=>{try{l(o.next(r))}catch(i){s(i)}},a=r=>{try{l(o.throw(r))}catch(i){s(i)}},l=r=>r.done?n(r.value):Promise.resolve(r.value).then(c,a);l((o=o.apply(t,e)).next())}),wo=(t,e,o)=>(e=t[Symbol.asyncIterator],o=(n,s)=>(s=t[n])&&(e[n]=c=>new Promise((a,l,r)=>(c=s.call(t,c),r=c.done,Promise.resolve(c.value).then(i=>a({value:i,done:r}),l)))),e?e.call(t):(t=t[Symbol.iterator](),e={},o("next"),o("return"),e));const $o=t=>{var e,o,n,s,c;const a=k((n=(o=(e=t.definition)==null?void 0:e.form.buttons)==null?void 0:o.button)!=null?n:[]),l=(s=t.configuration)==null?void 0:s.modalConfiguration,r=(c=t.configuration)==null?void 0:c.methodsPath,{name:i}=gt(),d=y.useCallback(u=>{const g=ne(),m=["submitAjax","submit"].includes(u.type)&&!u.onclick?"submit":"button",w=`handler__${m}`,_=()=>{(function(){return Qe(this,null,function*(){const O=yield oe.validateForm(i);if(!ht(O))return;const{submitValues:A}=O;if(t!=null&&t.definition&&["submitAjax","submit"].includes(u.type)){const T=new FormData;Object.entries(A).forEach(([f,h])=>{T.append(f,h??"")});const v=`${t?.definition.form.action.match(new RegExp(`^${window.CONTEXT}/`))?"":window.CONTEXT}${t!=null&&t.definition.form.action.startsWith("/")?"":"/"}${t?.definition.form.action}`;t.setState(f=>xo(le({},f),{isLoading:!0})),je.post(v,{postData:t.state.isMultipart?T:K.stringify([...T.entries(),["isAjax",!0]].reduce((f,[h,$])=>{const b=le({},f);return b[h.toString()]=$.toString(),b},{})),handleLoad:!0,notificationsCategory:"apiaApiHandler",modalConfiguration:l,methodsPath:r}).finally(()=>{Qe(this,null,function*(){var f,h,$,b;if(u.onclick){const J=u.onclick.split(";");try{for(var C=wo(J),j,P,S;j=!(P=yield C.next()).done;j=!1){const te=P.value,de=yield z(te,le({},t));if(de)de({currentUrl:(h=(f=t.definition)==null?void 0:f.form.action)!=null?h:"noUrl"});else throw new Error(`The requested action is not defined: "${(b=($=t.definition)==null?void 0:$.form.action)!=null?b:""}"`)}}catch(te){S=[te]}finally{try{j&&(P=C.return)&&(yield P.call(C))}finally{if(S)throw S[0]}}}})})}})})()};return p(xt,{className:w,disabled:t.state.disabled,id:u.id||u.text,isLoading:t.state.isLoading,title:u.text,type:m,onClick:_,children:u.text},g)},[i,r,l,t]);return p(M,{className:"handler__form__buttons",children:a.map(u=>d(u))})},Oo=y.memo($o);var Co=Object.defineProperty,Ao=Object.defineProperties,Eo=Object.getOwnPropertyDescriptors,Y=Object.getOwnPropertySymbols,Ke=Object.prototype.hasOwnProperty,Ze=Object.prototype.propertyIsEnumerable,Ye=(t,e,o)=>e in t?Co(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o,E=(t,e)=>{for(var o in e||(e={}))Ke.call(e,o)&&Ye(t,o,e[o]);if(Y)for(var o of Y(e))Ze.call(e,o)&&Ye(t,o,e[o]);return t},X=(t,e)=>Ao(t,Eo(e)),_o=(t,e)=>{var o={};for(var n in t)Ke.call(t,n)&&e.indexOf(n)<0&&(o[n]=t[n]);if(t!=null&&Y)for(var n of Y(t))e.indexOf(n)<0&&Ze.call(t,n)&&(o[n]=t[n]);return o},G=(t,e,o)=>new Promise((n,s)=>{var c=r=>{try{l(o.next(r))}catch(i){s(i)}},a=r=>{try{l(o.throw(r))}catch(i){s(i)}},l=r=>r.done?n(r.value):Promise.resolve(r.value).then(c,a);l((o=o.apply(t,e)).next())});const se=new class extends Q{},ie=new class extends Q{},B="ApiaApiForm",Ge={};function z(t,e){return G(this,null,function*(){return new Promise(o=>{var n,s,c;try{const a=/^\/?([\w\d_-]+)\/?(?:\(([^)]*)\))?$/,l=t.match(a);if(l){const r=l[1],i=l[2],d=[...(c=(s=(n=e.configuration)==null?void 0:n.methodsPath)==null?void 0:s.split("/").filter(m=>!!m))!=null?c:[],r].join("/"),u=m=>{typeof m.default!="function"&&g();const w=m.default;Ge[r]=_=>{var O;return w(e,X(E({},_),{inlineArguments:(O=i?.split(",").map(A=>A.startsWith("'")||A.startsWith('"')?A.slice(1,A.length-1):A))!=null?O:[]}))},o(Ge[r])},g=()=>{throw new Error(`${r}.ts not found at ${d}.ts nor ./${r}.ts`)};import(`/api/methods/${d}.ts`).then(u).catch(()=>{var m;((m=e.configuration)==null?void 0:m.methodsPath)!==void 0?import(`/api/methods/${r}.ts`).then(u).catch(g):g()})}}catch(a){console.error(a),e.reset(),e.setError({type:"danger",message:"Error while loading current method."})}})})}function jo(t){return typeof t.canClose=="boolean"&&typeof t.type=="string"&&!!t.form}function Po(t){return typeof t.canClose=="boolean"&&typeof t.type=="string"&&!!t.function}function Mo(t){return!!(typeof t.canClose=="boolean"&&typeof t.type=="string"&&typeof t.text=="object"&&t.text&&typeof t.text.label=="string")}const ce=new rt;function So(){const[,t,e]=st(void 0),o=x.useCallback(n=>{t(n)},[t]);return fe(()=>{ce.on("update",o)}),it(()=>ce.off("update",o)),e}const ue=new class extends Q{emit(t,e){super.emit(t,e)}};function Io(t,e,o){return ce.value=o,jo(t)?(ue.emit("form",t),!0):Po(t)?(ie.emit("method",{name:t.function.name,props:{messages:t.function.messages,attributes:t.function,currentUrl:e}}),!0):Mo(t)?(se.emit("message",{predicate:t.text.content,title:t.text.title}),!0):!1}const ee={disabled:!1,isLoading:!1,isMultipart:!1,progress:0,errors:{}},No=()=>{var t,e,o;const n=So(),[s,c]=x.useState(X(E({},ee),{windowIndex:-1})),[a,l]=x.useState(void 0);x.useEffect(()=>ue.on("form",l),[]);const r=x.useCallback((v,f)=>oe.setFieldValue(B,v,f),[]);x.useEffect(()=>{var v,f,h;if(!a)return;const $=k((h=(f=(v=a?.form)==null?void 0:v.elements)==null?void 0:f.element)!=null?h:[]);let b=!1;const C=Object.values($);let j=0;for(;j<C.length&&!b;)C[j++].type==="file"&&(b=!0);c(P=>X(E(E({},P),ee),{isMultipart:b}))},[a]);const i=wt(),{show:d,onClose:u}=i,g=_o(i,["show","onClose"]),m=x.useCallback(()=>{var v,f;u(),ue.emit("form",void 0),c(h=>E(E({},h),ee)),(f=(v=n.current)==null?void 0:v.modalConfiguration)!=null&&f.onClose&&n.current.modalConfiguration.onClose(),oe.unregisterForm(B)},[u,n]),w=x.useRef(null);x.useEffect(()=>{var v;const f=(v=w.current)==null?void 0:v.querySelectorAll("a,input,textarea,button");f?.length===1&&at.on([...f][0])});const _=x.useCallback(v=>{U(E({},v))},[]),O=x.useCallback(()=>({alert,close:m,configuration:n.current,formDefinition:a,reset:()=>c(v=>E(E({},v),ee)),setError:_,setMessage:v=>{var f,h;(h=(f=n.current)==null?void 0:f.modalConfiguration)!=null&&h.onMessage&&n.current.modalConfiguration.onMessage(v)},setState:c,state:s,setValue:r}),[m,n,a,_,s,r]);x.useEffect(()=>{const v=$=>G(void 0,[$],function*({name:b,props:{messages:C,attributes:j,currentUrl:P}}){const S=yield z(`${b}`,O());S&&S({messages:C,attributes:j,currentUrl:P})}),f=$=>{var b,C,j,P;const S=O();U({message:$.predicate,type:"warning",onClose:(C=(b=S.configuration)==null?void 0:b.modalConfiguration)==null?void 0:C.onMessageClose});const J=(P=(j=S.configuration)==null?void 0:j.modalConfiguration)==null?void 0:P.onMessage;J&&J($)},h=$=>G(void 0,null,function*(){if($.toDo==="ajaxHiddeAll"&&m(),$.toDo==="functionTimedCall"){const b=yield z(k($.param)[1],O());b&&setTimeout(()=>{var C;return b({currentUrl:(C=a?.form.action)!=null?C:"noUrl"})},Number($.param[0]))}});return se.on("message",f),ie.on("method",v),re.on("action",h),()=>{se.off("message",f),ie.off("method",v),re.off("action",h)}},[s.windowIndex,u,m]),x.useEffect(()=>{a&&d()},[a]);const A=O(),T=x.useCallback(v=>G(void 0,null,function*(){if(v&&a!=null&&a.form.onLoad){const f=yield z(`${a?.form.onLoad}`,O());f&&f()}}),[a?.form.onLoad,O]);return p(jt,{id:B,children:p($t,X(E({ref:w,onClose:m,id:B,title:(o=(e=(t=n.current)==null?void 0:t.modalConfiguration)==null?void 0:e.modalTitle)!=null?o:a?.form.title,size:"md-fixed",shouldCloseOnEsc:!s.disabled,shouldCloseOnOverlayClick:!s.disabled,initialFocusGetter:x.useCallback(v=>v?.querySelector(lt),[])},g),{children:a&&p(M,X(E({},ye("layout.common.modals.apiaApi")),{children:pe(bt,{name:B,avoidFieldsOverride:!0,className:"handler__form",children:[p(Be,E({definition:a},A)),s.isMultipart&&s.progress>0&&p(M,{className:"progressBox",children:p(Ot,{id:"ApiaApiHandler progress",progress:s.progress,loading:!0})}),p(M,{ref:T}),p(Oo,E({definition:a},A))]})}))}))})},To=x.memo(No);export{je as ApiaApi,To as ApiaApiHandler,ae as makeApiaUrl};
1557
2
  //# sourceMappingURL=index.js.map