@bolttech/form-engine-core 1.1.0 → 1.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/CHANGELOG.md +30 -10
- package/index.d.ts +349 -349
- package/index.esm.js +1 -1
- package/lite.esm.js +1 -1
- package/package.json +11 -2
- package/src/index.d.ts +3 -3
- package/src/managers/field.d.ts +3 -0
- package/src/managers/form.d.ts +1 -0
package/index.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BehaviorSubject as e,Subject as t,Subscription as i,groupBy as s,mergeMap as n,debounceTime as r,filter as a,combineLatest as l,startWith as o,map as u,distinctUntilKeyChanged as d}from"rxjs";import c from"credit-card-type";import{getCurrencySymbol as h}from"@gaignoux/currency";var v;function f(e,t,i,s){return new(i||(i=Promise))(function(n,r){function a(e){try{o(s.next(e))}catch(e){r(e)}}function l(e){try{o(s.throw(e))}catch(e){r(e)}}function o(e){e.done?n(e.value):function(e){return e instanceof i?e:new i(function(t){t(e)})}(e.value).then(a,l)}o((s=s.apply(e,t||[])).next())})}!function(e){e.ON_VALUE="value",e.ON_PROPS="props",e.ON_VISIBILITY="visibility",e.ON_API="api",e.ON_IVARS="iVars",e.ON_FIELDS="fields"}(v||(v={})),"function"==typeof SuppressedError&&SuppressedError;const p=1e3,m=/^\$\{(?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*\}$/,b=/\$\{((?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*)\}/g,g=/\s*(\|\||&&|!+)\s*/g,S=/^\|\||&&|!+$/,y=["fields","iVars","form"],$=["api","apiSchema","props","validations","visibilityConditions","resetValues"],V=!1;function j(e){const t=b,i=[];let s;for(;null!==(s=t.exec(e));)i.push(s[1]);const n=g,r=i.map(e=>e.split(n).filter(e=>!n.test(e))).flat().filter(e=>e.split(".").length>1);return{originScopeKeys:Array.from(new Set(r.map(e=>e.split(".")[0]))),originFieldKeys:Array.from(new Set(r.map(e=>e.split(".")[1]))),originPropertyKeys:Array.from(new Set(r.map(e=>e.split(".")[2])))}}function E(e,t){const i=[];if(Array.isArray(e))e.forEach((e,s)=>{i.push(...E(e,`${t?`${t}.`:""}${s}`))});else if("object"==typeof e)for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&i.push(...E(e[s],`${t?`${t}.`:""}${s}`));else if("string"==typeof e&&e.includes("${")){const s=(t||"").split(".");j(e).originScopeKeys.every(e=>y.includes(e))?i.push(Object.assign(Object.assign({originExpression:e},j(e)),{destinationKey:s[0],destinationProperty:s[1],destinationPath:s.slice(2)})):console.warn(`scope malformed on this expression: ${e}, ignoring..`)}return i}const N={},x={},O={};function I(e){Object.assign(N,e)}function F(e){Object.assign(x,e)}function k(e){Object.assign(O,e)}function w(e){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e))return e.map(e=>w(e));const t={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=w(e[i]));return t}function _(e,t,i){if(null==e)return i;const s=Array.isArray(t)?t:t.split(".");let n=e;for(let e=0;e<s.length;e++){if(null==n)return i;n=n[s[e]]}return void 0===n?i:n}function D(e,t,i){if(null==e||"object"!=typeof e)return e;const s=Array.isArray(t)?t:t.split(".");let n=e;for(let e=0;e<s.length-1;e++){const t=s[e],i=s[e+1];null!=n[t]&&"object"==typeof n[t]||(n[t]="number"==typeof i||/^\d+$/.test(String(i))?[]:{}),n=n[t]}return n[s[s.length-1]]=i,e}function A(e,t){if(e===t)return!0;if(null==e||null==t)return e===t;if(typeof e!=typeof t)return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if("object"!=typeof e)return!1;const i=Array.isArray(e);if(i!==Array.isArray(t))return!1;if(i){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!A(e[i],t[i]))return!1;return!0}const s=Object.keys(e),n=Object.keys(t);if(s.length!==n.length)return!1;for(const i of s){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!A(e[i],t[i]))return!1}return!0}function T(e){return null==e}function M(e){return"function"==typeof e}class P extends t{constructor(e){super(),this.isMounted=e}next(e){this.isMounted()&&super.next(e)}}class C extends e{constructor(e){super(e),this.defaultValue=e}next(e){this.closed||super.next(e)}get value(){return this.closed?this.defaultValue:super.value}}var R=(e,t,i)=>!!t&&function(e,t,i){const s=[];return Object.keys(t).forEach(n=>{s.push(i[n](e,{[n]:t[n]}))}),s}(e,t,i).some(e=>e);function L(e,t,i,s,n){return M(i[s])?i[s](e,t,n):R(e,t[s],i)}class Y{constructor({formIndex:e,schemaComponent:t,config:s,children:n,validateVisibility:r,resetValue:a,resetProperty:l,templateSubject$:o,fieldEventSubject$:u,dataSubject$:d,fieldValidNotification$:c,mountSubject$:h,mapper:v,formValuesStateSubject$:f,submitEvent:m,visibility:b,persistValue:g}){var S,y,$,j,E,N;this.valueSubscription$=new i,this.fieldStateSubscription$=new i,this.formIndex=e,this.originalSchema=w(t),this.config={defaultAPIdebounceTimeMS:Number(null==s?void 0:s.defaultAPIdebounceTimeMS)?Number(null==s?void 0:s.defaultAPIdebounceTimeMS):p,defaultStateRefreshTimeMS:Number(null==s?void 0:s.defaultStateRefreshTimeMS)?Number(null==s?void 0:s.defaultStateRefreshTimeMS):100,defaultLogVerbose:(null==s?void 0:s.defaultLogVerbose)?s.defaultLogVerbose:V},this.name=t.name,this.nameToSubmit=t.nameToSubmit,this.component=t.component,this.children=n,this.validations=w(t.validations),this.visibilityConditions=w(t.visibilityConditions),this.resetValues=w(t.resetValues),this.resetPropertyValues=w(t.resetPropertyValues),this.apiSchema=w(t.api),this.formatters=w(t.formatters),this.masks=w(t.masks),v.valueChangeEvent&&(this.valueChangeEvent=v.valueChangeEvent),(null===(S=v.events)||void 0===S?void 0:S.setValue)&&(this.valuePropName=v.events.setValue),this.mapper=v,this.validateVisibility=r,this.resetValue=a,this.resetProperty=l,this.submitEvent=m,this.templateSubject$=o,this.fieldEventSubject$=u,this.dataSubject$=d,this.fieldValidNotification$=c,this.mountSubject$=h,this.formValuesStateSubject$=f,this.getFormValues=()=>this.formValuesStateSubject$.value,this._props=Y.filterProps(w(t.props||{})),this._adapterProps=JSON.stringify(t.props||{}),this._metadata="",this.errorsString="",this.errorsList=[],this._visibility="boolean"!=typeof b||b,this._api={default:{response:(null===(j=null===($=null===(y=this.apiSchema)||void 0===y?void 0:y.defaultConfig)||void 0===$?void 0:$.config)||void 0===j?void 0:j.fallbackValue)||"",status:null},named:(null===(E=this.apiSchema)||void 0===E?void 0:E.configs)&&Object.keys(null===(N=this.apiSchema)||void 0===N?void 0:N.configs).reduce((e,t)=>{var i,s;return e[t]={response:(null===(s=null===(i=this.apiSchema)||void 0===i?void 0:i.configs)||void 0===s?void 0:s[t].config.fallbackValue)||"",status:null},e},{}),apiState:{loading:!1}},this._errors={},this._mounted=!1,this.valid=!0,this.persistValue=g,this.initializeObservers()}initializeObservers(){this.valueSubject$&&!this.valueSubject$.closed||(this.valueSubject$=new P(()=>this.mounted)),this.errorSubject$&&!this.errorSubject$.closed||(this.errorSubject$=new P(()=>this.mounted)),this.visibilitySubject$&&!this.visibilitySubject$.closed||(this.visibilitySubject$=new P(()=>this.mounted)),this.propsSubject$&&!this.propsSubject$.closed||(this.propsSubject$=new P(()=>this.mounted)),this.fieldStateSubscription$&&!this.fieldStateSubscription$.closed||(this.fieldStateSubscription$=new i),this.apiEventQueueSubject$&&!this.apiEventQueueSubject$.closed||(this.apiEventQueueSubject$=new P(()=>this.mounted)),this.apiEventQueueSubject$.observed||this.apiEventQueueSubject$.pipe(s(({event:e})=>e),n(e=>e.pipe(r(this.config.defaultAPIdebounceTimeMS))),a(()=>this.apiEventQueueSubject$&&!this.apiEventQueueSubject$.closed)).subscribe(e=>{this.apiRequest(e)})}get adapterProps(){return this._adapterProps}set adapterProps(e){const t=JSON.stringify(e||{});t!==this.adapterProps&&(this.props=Y.filterProps(e),this._adapterProps=t)}get props(){return this._props}set props(e){void 0===e||A(e,this.props)||(this._props=e,this.propsSubject$.next(this.props),this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_PROPS"}))}static filterProps(e){return Array.isArray(e)?e.filter(e=>"string"!=typeof e||!e.includes("${")).map(e=>Y.filterProps(e)):"object"==typeof e&&null!==e?e instanceof Date?e:Object.keys(e).reduce((t,i)=>{const s=e[i];return"string"==typeof s&&s.includes("${")||(t[i]=Y.filterProps(e[i])),t},{}):e}get stateValue(){return this._stateValue}get metadata(){return this._metadata}get value(){return this._value}set value(e){var t,i,s;let n;if(this.valueChangeEvent)try{n=this.valueChangeEvent(e,{props:this.props})}catch(t){n=e}else n=e;null!=n&&("object"==typeof n&&"_value"in n&&"_metadata"in n?(this._value=this.formatValue(n._value),this._stateValue=(null===(t=this.mapper.events)||void 0===t?void 0:t.setValue)?{[this.mapper.events.setValue]:this.maskValue(this.formatValue(n._value))}:{},this._metadata=n._metadata):(this._value=this.formatValue(n),this._stateValue=(null===(i=this.mapper.events)||void 0===i?void 0:i.setValue)?{[null===(s=this.mapper.events)||void 0===s?void 0:s.setValue]:this.maskValue(this.formatValue(n))}:{},this.maskValue(this.formatValue(n)),this._metadata=n),this.stateValue&&this.valueSubject$.next(this.stateValue),this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_VALUE"}))}get visibility(){return this._visibility}set visibility(e){void 0!==e&&e!==this.visibility&&(this._visibility=e,this.visibilitySubject$.next(this.visibility),this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_VISIBILITY"}))}set valid(e){"boolean"!=typeof e&&this.valid===e||(this._valid=e,this.triggerFieldValidNotification())}get valid(){return this._valid}triggerFieldValidNotification(){this.fieldValidNotification$.closed||this.fieldValidNotification$.next({fieldTrigger:this.name})}get errors(){return this._errors}set errors(e){var t;void 0===e||A(e,this.errors)||(this._errors=e,this.errorsList=Object.values(this.errors).filter(e=>null!=e),this.errorsString=this.errorsList.join(", "),(null===(t=this.mapper.events)||void 0===t?void 0:t.setErrorMessage)&&this.errorSubject$.next({[this.mapper.events.setErrorMessage]:this.errorsString}),this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_PROPS"}))}get api(){return this._api}set api(e){void 0!==e&&(this._api=e,this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_API_RESPONSE"}),this.emitEvents({event:"ON_API_FIELD_RESPONSE"}))}notifyApiRequest(){this._api.apiState.loading=!0,this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_API_REQUEST"}),this.emitEvents({event:"ON_API_FIELD_REQUEST"})}get mounted(){return this._mounted}set mounted(e){void 0!==e&&e!==this.mounted&&(this._mounted=e,this.initializeObservers(),this.mountSubject$.closed||this.mountSubject$.next({key:this.name,status:this.mounted}))}mountField({valueSubscription:e,propsSubscription:t}){this.mounted=!0,this.subscribeValue(e),this.subscribeState(t),this.valueSubject$.next(this.stateValue),this.propsSubject$.next(this.props),this.visibilitySubject$.next(this.visibility),this.fieldEventSubject$.next({event:"ON_FIELD_MOUNT",fieldName:this.name,fieldInstance:this})}emitValue(e){this.visibility&&this.mounted&&(this.value=e.value,this.dataSubject$.next({event:e.event,fieldIndex:this.name,formIndex:this.formIndex}),this.emitEvents({event:e.event}))}emitEvents({event:e}){if("ON_FORM_SUBMIT"===e)return this.submitEvent();this.validateVisibility({event:e,key:this.name}),this.setFieldValidity({event:e}),this.resetValue({event:e,key:this.name}),this.resetProperty({event:e,key:this.name}),this.apiEventQueueSubject$.next({event:e}),this.fieldEventSubject$.next({event:e,fieldName:this.name,fieldInstance:this})}setFieldValidity({event:e}){var t,i,s,n;if(!this.validations||!this.visibility)return this.errors={},void(this.valid=!0);let r=!0;const a={},l=null===(t=this.validations)||void 0===t?void 0:t.methods;if(l&&Object.keys(l).forEach(e=>{var t,i;const s=L(this.value,l,N,e,null===(t=this.formValuesStateSubject$)||void 0===t?void 0:t.value);r=!s&&r,s&&(null===(i=this.validations)||void 0===i?void 0:i.messages)?e in this.validations.messages?a[e]=this.validations.messages[e]:"default"in this.validations.messages&&(a[e]=this.validations.messages.default):delete a[e]}),this.valid=r,null===(s=null===(i=this.validations)||void 0===i?void 0:i.eventMessages)||void 0===s?void 0:s[e]){const t={};null===(n=this.validations.eventMessages[e])||void 0===n||n.forEach(e=>{e in a&&(t[e]=a[e])}),this.errors=t}else"ON_FIELD_VALIDATION"===e&&(this.errors=a)}formatValue(e){return this.formatters?Object.keys(this.formatters).reduce((e,t)=>{const i=x[t];return i?i(e,this.formatters):e},e):e}maskValue(e){return this.masks?Object.keys(this.masks).reduce((e,t)=>{const i=O[t];return i?i(e,this.masks):e},e):e}checkApiRequestValidations(e){let t=!0;const i=e.preConditions;return i&&Object.keys(i).forEach(e=>{var s;const n=L(this.value,i,N,e,null===(s=this.formValuesStateSubject$)||void 0===s?void 0:s.value);t=t&&!n}),e.blockRequestWhenInvalid&&(t=t&&this.valid),t}apiRequest(e){return f(this,arguments,void 0,function*({event:e}){var t,i,s,n,r,a,l,o,u;let d=!1;const c=e=>f(this,void 0,void 0,function*(){var t,i;try{const{status:s,response:n}=yield function(e,t,i,s,n){return f(this,void 0,void 0,function*(){if(n){const[e,i]=t.split("?"),s=new URLSearchParams(i);Object.keys(n).forEach(e=>{s.append(e,n[e])}),t=`${e}?${s.toString()}`}const r=yield fetch(t,{method:e,headers:i,body:s?JSON.stringify(s):void 0}),a=yield r.text();return{status:r.status,response:a}})}(e.method,e.url,e.headers,e.body,e.queryParams),r=null===(t=e.transform)||void 0===t?void 0:t.callback,a=r?r({payload:JSON.parse(String(n)),formValues:null===(i=this.formValuesStateSubject$)||void 0===i?void 0:i.value}):JSON.parse(String(n));return{response:e.resultPath?_(a,e.resultPath):a,status:s}}catch(t){return{response:T(null==e?void 0:e.fallbackValue)?"error":e.fallbackValue,status:500}}});if("ON_API_FIELD_RESPONSE"===this.api.apiState.lastEvent&&"ON_API_FIELD_RESPONSE"===e||!(null===(i=null===(t=this.apiSchema)||void 0===t?void 0:t.defaultConfig)||void 0===i?void 0:i.events.includes(e))&&(!(null===(s=this.apiSchema)||void 0===s?void 0:s.configs)||!Object.keys(null===(n=this.apiSchema)||void 0===n?void 0:n.configs).some(t=>{var i,s;return null===(s=null===(i=this.apiSchema)||void 0===i?void 0:i.configs)||void 0===s?void 0:s[t].events.includes(e)})))return;const h={default:Object.assign({},this.api.default),named:Object.assign({},this.api.named),apiState:Object.assign({},this.api.apiState)},v=null===(r=this.apiSchema.defaultConfig)||void 0===r?void 0:r.config;if(v&&(null===(l=null===(a=this.apiSchema)||void 0===a?void 0:a.defaultConfig)||void 0===l?void 0:l.events.includes(e))&&this.checkApiRequestValidations(v)){d||this.notifyApiRequest();const{response:e,status:t}=yield c(v);d=!0,h.default={response:e,status:t}}if((null===(o=this.apiSchema)||void 0===o?void 0:o.configs)&&Object.keys(null===(u=this.apiSchema)||void 0===u?void 0:u.configs).some(t=>{var i,s;return null===(s=null===(i=this.apiSchema)||void 0===i?void 0:i.configs)||void 0===s?void 0:s[t].events.includes(e)})&&this.apiSchema.configs){const t=yield Promise.all(Object.keys(this.apiSchema.configs).map(t=>f(this,void 0,void 0,function*(){var i,s,n,r;const a=null===(s=null===(i=this.apiSchema)||void 0===i?void 0:i.configs)||void 0===s?void 0:s[t].config;if(a&&(null===(r=null===(n=this.apiSchema)||void 0===n?void 0:n.configs)||void 0===r?void 0:r[t].events.includes(e))&&this.checkApiRequestValidations(a)){d||this.notifyApiRequest();const{response:e,status:i}=yield c(a);return d=!0,{name:t,result:{response:e,status:i}}}return null})));t.forEach(e=>{e&&h.named&&(h.named[e.name]=e.result)})}d&&(h.apiState.lastEvent=e,h.apiState.loading=!1,this.api=h)})}destroyField(){this.mounted=!1,this.valueSubscription$.unsubscribe(),this.visibilitySubject$.unsubscribe(),this.fieldStateSubscription$.unsubscribe(),this.propsSubject$.unsubscribe(),this.errorSubject$.unsubscribe(),this.apiEventQueueSubject$.unsubscribe(),this.dataSubject$.closed||this.dataSubject$.next({event:"ON_FIELD_UNMOUNT",fieldIndex:this.name,formIndex:this.formIndex}),this.fieldEventSubject$.closed||this.fieldEventSubject$.next({event:"ON_FIELD_UNMOUNT",fieldName:this.name,fieldInstance:this})}subscribeState(e){var t;this.fieldStateSubscription$=l({visibility:this.visibilitySubject$.pipe(o(this.visibility)),props:this.propsSubject$.pipe(o(this.props)),errors:this.errorSubject$.pipe(o(Object.assign({},(null===(t=this.mapper.events)||void 0===t?void 0:t.setErrorMessage)&&{[this.mapper.events.setErrorMessage]:this.errorsString})))}).pipe(r(this.config.defaultStateRefreshTimeMS)).subscribe({next:e})}subscribeValue(e){this.valueSubscription$=this.valueSubject$.subscribe({next:e})}}class q{constructor(e){var s,n,r,a,l,o,u,d,c,h,v;this.templateSubscription$=new i,this.mappers=new Map,this.queuedFieldVisibilityEvents=new Map,this.queuedFieldResetValuesEvents=new Map,this.queuedFieldResetPropertyEvents=new Map,this.queuedInitialValues=new Map,this._valid=!1,this.stopEventsOnSubmit=!1,this.submitted=!1,this.isolatedFormInstance=!1,this.index=e.index,this.schema=e.schema,this.fields=new Map,this.action=e.action||(null===(s=e.schema)||void 0===s?void 0:s.action),this.method=e.method||(null===(n=e.schema)||void 0===n?void 0:n.method),this.config={defaultAPIdebounceTimeMS:Number(null===(r=e.config)||void 0===r?void 0:r.defaultAPIdebounceTimeMS)?Number(null===(a=e.config)||void 0===a?void 0:a.defaultAPIdebounceTimeMS):p,defaultStateRefreshTimeMS:Number(null===(l=e.config)||void 0===l?void 0:l.defaultStateRefreshTimeMS)?Number(null===(o=e.config)||void 0===o?void 0:o.defaultStateRefreshTimeMS):100,defaultLogVerbose:(null===(u=e.config)||void 0===u?void 0:u.defaultLogVerbose)?e.config.defaultLogVerbose:V},null===(d=e.mappers)||void 0===d||d.map(e=>{this.mappers.set(e.componentName,e)}),e.submitSubject$&&e.dataSubject$&&e.formValidSubject$||(this.isolatedFormInstance=!0,this.config.defaultLogVerbose&&console.warn(`some formGroup events are not properly instanciated, any onData, onValid, onSubmit events managed by formGroup won't trigger on form: ${this.index}`)),this.schema&&q.checkIndexes(this.schema.components),this.templateSubject$=new t,this.fieldEventSubject$=new t,this.mountSubject$=new t,this.fieldValidNotification$=new t,this.submitSubject$=e.submitSubject$?e.submitSubject$:new t,this.dataSubject$=e.dataSubject$?e.dataSubject$:new t,this.formValidSubject$=e.formValidSubject$?e.formValidSubject$:new t,this.formValuesStateSubject$=new C({erroredFields:[],isValid:!0,metadata:[],values:[]}),this.getFormValues=()=>this.formValuesStateSubject$.value,this.subscribedTemplates=[],this.templateSubscription$=this.templateSubject$.subscribe(this.refreshTemplates.bind(this)),this.fieldValidNotification$.subscribe(()=>{this.validateForm()}),this.fieldEventSubject$.subscribe(()=>{this.formValuesStateSubject$.next(this.getFormState())}),this.dataSubject$.subscribe(()=>{this.formValuesStateSubject$.next(this.getFormState())}),this.mountSubject$.subscribe(this.mountActions.bind(this)),this.prefetchedData=null===(c=e.schema)||void 0===c?void 0:c.prefetchedData,this.initialValues=e.initialValues||(null===(h=e.schema)||void 0===h?void 0:h.initialValues),this.iVars=e.iVars||(null===(v=e.schema)||void 0===v?void 0:v.iVars)||{},this.stopEventsOnSubmit=(null==e?void 0:e.stopEventsOnSubmit)||!1,this.submitted=!1}generateFields(){this.schema&&this.serializeStructure(this.schema.components),this.fields.forEach(e=>{e.mountField({valueSubscription:()=>null,propsSubscription:()=>null})})}submitChecker(){return!(this.stopEventsOnSubmit&&this.submitted)}mountActions({key:e,status:t}){if(t){const t=this.fields.get(e);if(!t)return void(this.config.defaultLogVerbose&&console.warn(`field ${e} was mounted but since it's parent has some visibility condition the field was already removed`));this.subscribeTemplates(),this.refreshTemplates({scope:"fields",event:"ON_FIELDS"}),this.templateSubject$.next({scope:"iVars",event:"ON_IVARS"}),this.queuedInitialValues.has(e)||(t.valuePropName&&!t.value?t.emitValue({event:"ON_FIELD_MOUNT",value:""}):t.emitEvents({event:"ON_FIELD_MOUNT"})),this.checkFieldEventQueues(e)}}set initialValues(e){e&&Object.keys(e).forEach(t=>{const i=this.fields.get(t);i&&(null==i?void 0:i.visibility)&&(null==i?void 0:i.mounted)?i.emitValue({value:null==e?void 0:e[t],event:"ON_FIELD_MOUNT"}):this.queuedInitialValues.set(t,null==e?void 0:e[t])})}get iVars(){return this._iVars}set iVars(e){this._iVars=e,this.templateSubject$.next({scope:"iVars",event:"ON_IVARS"})}validateForm(){if(0===this.fields.size)return this.valid=!1;for(const[,e]of this.fields)if(!e.valid)return this.valid=!1;return this.valid=!0}get valid(){return this._valid}set valid(e){this._valid!==e&&(this._valid=e,this.templateSubject$.next({event:"ON_FORM",scope:"form"}),this.formValidSubject$.next({formIndex:this.index,valid:this.valid}))}subscribeTemplates(){this.subscribedTemplates=[],this.fields.forEach(({originalSchema:{component:e,props:t,name:i,validations:s,visibilityConditions:n,resetValues:r,resetPropertyValues:a,api:l}},o)=>{E({component:e,props:t,name:i,validations:s,visibilityConditions:n,resetValues:r,resetPropertyValues:a,apiSchema:l},o).forEach(e=>this.subscribedTemplates.push(e))})}getValue({scope:e,key:t,property:i,path:s}){switch(e){case"iVars":return _(this.iVars,[t,...i?[i]:[],...s]);case"form":return _(this,[t,...i?[i]:[],...s]);case"fields":{const e=this.fields.get(t);return e?"props"===i&&s[0]===e.valuePropName?e.value:s.length>0?_(e[i],s):e[i]:this.config.defaultLogVerbose&&console.warn(`failed to get value from ${t}`)}}}setValue({key:e,property:t,path:i,originKey:s,value:n}){const r=this.fields.get(e);if(r){if(i.length>0){if("props"===t&&i[0]===r.valuePropName&&e!==s)return void r.emitValue({event:"ON_FIELD_CHANGE",value:n});const a=r[t];let l;return Array.isArray(a)||"object"==typeof a&&!T(a)?(l=w(a),D(l,i,n),void(r[t]=l)):void(this.config.defaultLogVerbose&&console.warn(`invalid template property, skipping evaluation of ${r.name} with ${a}`))}r[t]=n}else this.config.defaultLogVerbose&&console.warn(`failed to update field ${e}`)}extractParams(e){const t=function(e){const t=e.split(".");return t.length>1?this.getValue({scope:t[0],key:t[1],property:t[2],path:t.slice(3)}):t[0]}.bind(this),i=[];let s;for(;!T(s=b.exec(e));)i.push(s[1]);const n=i.map(e=>e.split(g)).map(e=>e.length<=1?{parse:!1,value:t(e[0])}:{parse:!0,value:e.filter(Boolean).reduce((e,i)=>{if(i.match(S))return`${e}${i}`;let s;const n=t(i);let r;try{r=JSON.parse(n)}catch(e){r=n}switch(typeof r){case"string":s=`\`${r}\``;break;case"boolean":case"undefined":case"number":default:s=r;break;case"object":if(null===r){s=null;break}if(r instanceof Date){s=`new Date(\`${r}\`)`;break}s=JSON.stringify(r)}return`${e}${s}`},"")});return n.map(({parse:t,value:i})=>{try{return t?new Function(`return ${i}`)():i}catch(t){return this.config.defaultLogVerbose&&(console.warn(`unhandled parsing on ${e} returning`),console.warn(i)),i}})}replaceExpression(e,t){return e.replace(b,()=>String(t.shift())||"")}hasStringConcatenation(e){return!m.test(e)}refreshTemplates({key:e,event:t}){this.subscribedTemplates.forEach(({destinationKey:i,destinationPath:s,destinationProperty:n,originExpression:r,originFieldKeys:a})=>{if(!e||a.includes(e)){const a=this.extractParams(r);let l;l=this.hasStringConcatenation(r)?this.replaceExpression(r,[...a]):null==a?void 0:a[0],A(this.getValue({scope:"fields",key:i,property:n,path:s}),l)||this.setValue({key:i,property:n,path:s,originKey:e,value:l,event:t})}})}checkFieldEventQueues(e){var t;if(null===(t=this.fields.get(e))||void 0===t?void 0:t.mounted){if(this.queuedFieldVisibilityEvents.has(e)&&(this.setFieldVisibility(Object.assign({field:e},this.queuedFieldVisibilityEvents.get(e))),this.queuedFieldVisibilityEvents.delete(e)),this.queuedInitialValues.has(e)){const t=this.queuedInitialValues.get(e);this.queuedInitialValues.delete(e),this.initialValues={[e]:t}}this.queuedFieldResetValuesEvents.has(e)&&(this.setResetFieldValue(Object.assign({key:e},this.queuedFieldResetValuesEvents.get(e))),this.queuedFieldResetValuesEvents.delete(e)),this.queuedFieldResetPropertyEvents.has(e)&&(this.setResetPathValue(Object.assign({key:e},this.queuedFieldResetPropertyEvents.get(e))),this.queuedFieldResetPropertyEvents.delete(e))}}setFieldVisibility({field:e,hasError:t,showOnlyIfTrue:i}){const s=this.fields.get(e);if(s&&s.mounted){const n=s.visibility,r=i?t:!t;if(s.visibility=r,n===r)return;s.visibility?this.queuedInitialValues.has(e)?(null==s||s.emitValue({value:this.queuedInitialValues.get(e)||"",event:"ON_FIELD_MOUNT"}),this.queuedInitialValues.delete(e)):s.emitEvents({event:"ON_FIELD_MOUNT"}):(s.emitEvents({event:"ON_FIELD_UNMOUNT"}),s.persistValue&&this.queuedInitialValues.set(s.name,s.value),s.value="",s.valid=!0)}else this.queuedFieldVisibilityEvents.set(e,{hasError:t,showOnlyIfTrue:i})}validateVisibility({event:e,key:t}){const i=this.fields.get(t),s=null==i?void 0:i.visibilityConditions;s&&(null==s?void 0:s.some(t=>t.events.includes(e)))&&s.forEach(t=>{t.events.includes(e)&&Object.keys(t.validations).forEach(e=>{const s=L(i.value,t.validations,N,e,this.formValuesStateSubject$.value);Array.isArray(t.fields)?t.fields.forEach(e=>{this.setFieldVisibility({field:e,hasError:s,showOnlyIfTrue:!(!i.value||!t.showOnlyIfTrue)})}):t.fields&&this.setFieldVisibility({field:t.fields,hasError:s,showOnlyIfTrue:!(!i.value||!t.showOnlyIfTrue)})})})}setResetFieldValue({key:e,value:t}){const i=this.fields.get(e);i&&(null==i?void 0:i.mounted)?i.emitValue({value:t,event:"ON_FIELD_CLEARED"}):this.queuedFieldResetValuesEvents.set(e,{value:t})}resetValue({event:e,key:t}){const i=this.fields.get(t),s=null==i?void 0:i.resetValues;s&&(null==s?void 0:s.some(t=>t.events.includes(e)))&&s.forEach(t=>{if(!t.events.includes(e))return;const s=()=>{Array.isArray(t.fields)?t.fields.forEach((e,i)=>{const s=Array.isArray(t.resettledValue)?t.resettledValue[i]:t.resettledValue;this.setResetFieldValue({key:e,value:s})}):t.fields&&this.setResetFieldValue({key:t.fields,value:t.resettledValue})};if(!t.validations)return s();Object.keys(t.validations).forEach(e=>{L(i.value,t.validations,N,e,this.formValuesStateSubject$.value)||s()})})}setResetPathValue({key:e,property:t,path:i,value:s}){this.fields.get(e)?this.setValue({key:e,property:t,path:i.split("."),value:s,event:"ON_RESET"}):this.queuedFieldResetPropertyEvents.set(e,{property:t,path:i,value:s})}resetProperty({event:e,key:t}){const i=this.fields.get(t),s=null==i?void 0:i.resetPropertyValues;s&&(null==s?void 0:s.some(t=>t.events.includes(e)))&&s.forEach(t=>{if(t.events.includes(e)&&$.includes(t.property))return t.validations?void Object.keys(t.validations).forEach(e=>{L(i.value,t.validations,N,e,this.formValuesStateSubject$.value)||this.setResetPathValue({key:t.field,path:t.path,property:t.property,value:t.resettledValue})}):this.setResetPathValue({key:t.field,path:t.path,property:t.property,value:t.resettledValue})})}addField({fieldSchema:e,mapperElement:t,path:i}){var s,n,r,a,l;if(this.fields.has(e.name))throw new Error(`field name ${e.name} already defined`);const o=t||(null===(s=this.mappers)||void 0===s?void 0:s.get(e.component));if(!o)throw new Error(`mapper not found for ${e.component}, add it to the mappers configuration`);if(null===(n=o.events)||void 0===n?void 0:n.setValue){const t=null===(r=null==e?void 0:e.props)||void 0===r?void 0:r[null===(a=null==o?void 0:o.events)||void 0===a?void 0:a.setValue];void 0===t||this.queuedInitialValues.has(e.name)||"string"==typeof t&&t.includes("${")||this.queuedInitialValues.set(e.name,w(t))}if(this.fields.set(e.name,new Y({formIndex:this.index,schemaComponent:e,mapper:o,children:e.children?e.children.map(e=>e.name):[],validateVisibility:this.validateVisibility.bind(this),resetValue:this.resetValue.bind(this),resetProperty:this.resetProperty.bind(this),formValuesStateSubject$:this.formValuesStateSubject$,templateSubject$:this.templateSubject$,fieldEventSubject$:this.fieldEventSubject$,dataSubject$:this.dataSubject$,fieldValidNotification$:this.fieldValidNotification$,mountSubject$:this.mountSubject$,config:this.config,submitEvent:this.submit.bind(this),visibility:e.visibility,persistValue:e.persistValue,path:i})),null===(l=this.prefetchedData)||void 0===l?void 0:l[e.name]){const t=this.fields.get(e.name);if(t){const i=this.prefetchedData[e.name],s=Object.assign({},t.api);void 0!==i.defaultResponse&&(s.default={response:i.defaultResponse,status:200}),i.namedResponses&&(s.named=s.named||{},Object.keys(i.namedResponses).forEach(e=>{s.named[e]={response:i.namedResponses[e],status:200}})),t._api=s}}}removeField({key:e}){var t;null===(t=this.fields.get(e))||void 0===t||t.destroyField(),this.fields.delete(e),this.subscribeTemplates(),this.templateSubject$.next({scope:"fields",key:e,event:"ON_FIELDS"}),this.validateForm()}serializeStructure(e,t){e&&e.forEach(e=>{var i;const s=this.fields.get(e.name);s?(s.children=(null===(i=null==e?void 0:e.children)||void 0===i?void 0:i.map(e=>e.name))||(null==s?void 0:s.children)||[],s.originalSchema=e,s.templateSubject$=this.templateSubject$):this.addField({fieldSchema:e,mapperElement:e.mapper,path:t}),e.children&&this.serializeStructure(e.children,`${t?`${t}.`:""}${e.name}`)})}refreshFields(e){const t=Array.from(this.fields.keys());this.serializeStructure(e);const i=q.checkIndexes(e);this.fields.forEach((e,t)=>{var s;i.includes(t)||(null===(s=this.fields.get(t))||void 0===s||s.destroyField(),this.fields.delete(t))}),this.subscribeTemplates(),this.fields.forEach((e,i)=>{var s;t.includes(i)||(null===(s=this.fields.get(i))||void 0===s||s.emitEvents({event:"ON_FIELD_MOUNT"}),this.checkFieldEventQueues(i))}),this.subscribedTemplates.forEach(e=>{e.originFieldKeys.forEach(e=>{this.templateSubject$.next({scope:"fields",key:e,event:"ON_FIELDS"})})})}getField({key:e}){return this.fields.get(e)}printValues(){console.table(this.formValuesStateSubject$.value.values)}getFormState(){const e={},t={},i=[];return this.fields.forEach((s,n)=>{"string"==typeof s.value&&0===s.value.length||null==s.value||(D(e,s.nameToSubmit||n,s.value),t[n]=s.metadata),s.valid||i.push(n)}),{values:e,metadata:t,erroredFields:i,isValid:this.valid}}subscribeFieldEvent({callback:e}){return this.fieldEventSubject$.pipe(a(()=>this.submitChecker()),s(e=>`${e.event}|${e.fieldName}`),n(e=>e.pipe(r(this.config.defaultStateRefreshTimeMS)))).subscribe({next:e})}subscribeOnMount(e){return this.mountSubject$.pipe(u(()=>this.formValuesStateSubject$.value)).subscribe({next:e})}subscribeData(e){return this.dataSubject$.pipe(a(({formIndex:e})=>this.index===e&&this.submitChecker()),s(e=>e.event),n(e=>e.pipe(r(this.config.defaultStateRefreshTimeMS))),u(({fieldIndex:e})=>({field:e,data:this.formValuesStateSubject$.value}))).subscribe({next:e})}subscribeOnSubmit(e){return this.submitSubject$.pipe(a(({formIndex:e})=>e===this.index&&this.submitChecker()),u(({values:e})=>e)).subscribe({next:e})}subscribeFormValidation(e){return this.formValidSubject$.pipe(a(({formIndex:e})=>this.index===e),u(()=>({formIndex:this.index,valid:this.valid})),d("valid"),o({formIndex:this.index,valid:this.valid})).subscribe({next:e})}submit(){this.fields.forEach(e=>{e.emitEvents({event:"ON_FIELD_VALIDATION"})}),this.valid&&(this.submitSubject$.next({formIndex:this.index,values:this.formValuesStateSubject$.value}),this.submitted=!0)}destroy(){this.templateSubject$.unsubscribe(),this.templateSubscription$.unsubscribe(),this.mountSubject$.unsubscribe(),this.fieldEventSubject$.unsubscribe(),this.fieldValidNotification$.unsubscribe(),this.formValuesStateSubject$.unsubscribe(),this.isolatedFormInstance&&(this.submitSubject$.unsubscribe(),this.dataSubject$.unsubscribe(),this.formValidSubject$.unsubscribe()),this.fields.forEach(e=>e.destroyField())}}q.checkIndexes=(e,t=[])=>{if(!e)return t;const i=(e,t)=>{for(let s=0;s<e.length;s++){const n=e[s];t.push(n.name),n.children&&i(n.children,t)}};i(e,t);const s=t.filter((e,i)=>t.indexOf(e)!==i);if(s.length>0)throw new Error(`duplicated indexes found on schema: ${JSON.stringify(s)}`);return t};class U{constructor(e){var i,s,n,r,a;this.destroy=()=>{this.forms.forEach(e=>e.destroy()),this.dataSubject$.unsubscribe(),this.formValidSubject$.unsubscribe(),this.submitSubject$.unsubscribe()},this.forms=new Map,this.config={defaultAPIdebounceTimeMS:Number(null===(i=null==e?void 0:e.config)||void 0===i?void 0:i.defaultAPIdebounceTimeMS)?Number(null===(s=null==e?void 0:e.config)||void 0===s?void 0:s.defaultAPIdebounceTimeMS):p,defaultStateRefreshTimeMS:Number(null===(n=null==e?void 0:e.config)||void 0===n?void 0:n.defaultStateRefreshTimeMS)?Number(null===(r=null==e?void 0:e.config)||void 0===r?void 0:r.defaultStateRefreshTimeMS):100,defaultLogVerbose:(null===(a=null==e?void 0:e.config)||void 0===a?void 0:a.defaultLogVerbose)?e.config.defaultLogVerbose:V},this.dataSubject$=new t,this.formValidSubject$=new t,this.submitSubject$=new t,this.mappers=null==e?void 0:e.mappers}createFormWithIndex({index:e,mappers:t}){this.addForm({key:e,params:{index:e,mappers:t,config:this.config}})}addForm({key:e,params:t}){this.checkIndexes({key:e});const i=new q(Object.assign(Object.assign({},t),{dataSubject$:this.dataSubject$,formValidSubject$:this.formValidSubject$,submitSubject$:this.submitSubject$}));i.config||(i.config=this.config),this.forms.set(e,i)}getForm({key:e}){return this.forms.get(e)}removeForm({key:e}){var t;null===(t=this.forms.get(e))||void 0===t||t.destroy(),this.forms.delete(e)}removeField({formIndex:e,fieldIndex:t}){const i=this.forms.get(e);null==i||i.removeField({key:t}),0===(null==i?void 0:i.fields.size)&&this.removeForm({key:e})}checkIndexes({key:e}){if(this.forms.has(e))throw new Error(`duplicate index ${e} on form group`)}printFormGroupInstance(){console.table(this.forms)}submitMultipleFormsByIndex(e,t){let i=!0,s={},n={},r=[];e.forEach(e=>{var t,a;null===(t=this.forms.get(e))||void 0===t||t.submit();const l=null===(a=this.forms.get(e))||void 0===a?void 0:a.formValuesStateSubject$.value,o="object"==typeof(null==l?void 0:l.metadata)&&null!==l.metadata?l.metadata:{};i=i&&((null==l?void 0:l.isValid)||!1),s=Object.assign(Object.assign({},s),(null==l?void 0:l.values)||{}),n=Object.assign(Object.assign({},n),o),r=[...r,...(null==l?void 0:l.erroredFields)||[]]}),i&&t&&t({erroredFields:r,isValid:i,values:s,metadata:n})}onDataSubscription({ids:e,callback:t}){return this.dataSubject$.pipe(a(({formIndex:t})=>e.includes(t)),s(({event:e,formIndex:t})=>`${e}.${t}`),n(e=>e.pipe(r(this.config.defaultStateRefreshTimeMS))),u(({fieldIndex:t,formIndex:i})=>e.reduce((e,s)=>{const n=this.forms.get(s);return n&&(e[s]={formId:i,formField:t,values:n.formValuesStateSubject$.value}),e},{}))).subscribe(t)}onValidSubscription({ids:e,callback:t}){return this.formValidSubject$.pipe(a(({formIndex:t})=>e.includes(t)),s(({formIndex:e})=>e),n(e=>e.pipe(r(0))),o({fieldTrigger:null}),u(()=>({groupValid:e.every(e=>{var t;return!this.forms.get(e)||(null===(t=this.forms.get(e))||void 0===t?void 0:t.valid)}),forms:e.reduce((e,t)=>{const i=this.forms.get(t);return i&&(e[t]=i.valid),e},{})}))).subscribe(t)}onSubmitSubscription({ids:e,callback:t}){return this.submitSubject$.pipe(a(({formIndex:t})=>e.includes(t)),u(()=>e.reduce((e,t)=>{const i=this.forms.get(t);return i&&(e[t]=i.formValuesStateSubject$.value),e},{}))).subscribe(t)}}var z=(e,t)=>{if(!t.length||!e)return!1;let i=e;return"string"!=typeof i&&(i=(null==e?void 0:e.toString())||i),{equal:i.length!==t.length.target,notEqual:i.length===t.length.target,less:i.length>=t.length.target,lessOrEqual:i.length>t.length.target,greater:i.length<=t.length.target,greaterOrEqual:i.length<t.length.target}[t.length.rule]};const Z=e=>{if(9!==e.length)return!0;if(!/^\d{8}$/.test(e.slice(0,8)))return!0;const t="TRWAGMYFPDXBNJZSQVHLCKE"[parseInt(e.slice(0,8),10)%23];return!(e[8].toUpperCase()===t)};var Q=(e,t)=>{if(!e||!t.document)return!0;const i={NIF:(e,t)=>((e,t)=>{switch(t){case"pt-PT":return(e=>{if(!/^\d{9}$/.test(e))return!1;const t=parseInt(e[8],10),i=11-Array.from(e.substring(0,8)).reduce((e,t,i)=>e+parseInt(t,10)*(9-i),0)%11;return 10===i||11===i?0===t:i===t})(e);case"es-ES":return Z(e);case"it-IT":return(e=>/^[A-Z]{6}\d{2}[A-Z]\d{2}[A-Z]\d{3}[A-Z]$/.test(e))(e);case"de-DE":return(e=>/^\d{11}$/.test(e))(e);case"fr-FR":return(e=>/^\d{2} \d{3} \d{3} \d{3} \d{3}$/.test(e))(e);case"en-GB":return(e=>/^GB\d{9}|\d{12}|\d{3}[A-Z]{5}$/.test(e))(e);case"nl-BE":case"fr-BE":return(e=>!!/^\d{11}$/.test(e)&&97-parseInt(e.substring(0,9),10)%97===parseInt(e.substring(9),10))(e);case"nl-NL":return(e=>!!/^\d{9}$/.test(e)&&e.split("").map((e,t)=>parseInt(e,10)*(9-t)).reduce((e,t)=>e+t,0)%11==0)(e);case"sv-SE":return(e=>!!/^\d{10,12}$/.test(e)&&(12===e.length?e.substring(2):e).split("").map((e,t)=>{let i=parseInt(e,10)*(t%2==0?2:1);return i>9&&(i-=9),i}).reduce((e,t)=>e+t,0)%10==0)(e);default:throw new Error(`NIF validation not supported for locale: ${t}`)}})(e,t),NIE:e=>(e=>{if(9!==e.length)return!0;if(!/^[XYZ]\d{7}[TRWAGMYFPDXBNJZSQVHLCKE]$/.test(e))return!0;let t=e.toUpperCase().padStart(9,"0");return t=t[0].replace(/[XYZ]/g,e=>({X:"0",Y:"1",Z:"2"}[e]||e))+t.slice(1),Z(t)})(e),CIF:e=>(e=>!/^[A-Z][0-9]{7}[A-J0-9]$/.test(e))(e),IBAN:e=>(e=>{const t=e.replace(/\s/g,"");return 24!==t.length||!/^(ES)[0-9]{22}$/.test(t)||1!==(e=>{for(;e.length>2;){const t=e.slice(0,6),i=parseInt(t,10);if(isNaN(i))return NaN;e=i%97+e.slice(t.length)}return parseInt(e,10)%97})(t.substring(4)+1428+t.substring(2,4))})(e)};return i[t.document.type](e,t.document.locale)};const B=(e,t)=>{const i=Number(e);return!(!t.max||Number.isNaN(i))&&i>Number(t.max)},J=(e,t)=>{const i=Number(e);return!(!t.min||Number.isNaN(i))&&i<Number(t.min)},K=(e,t)=>{if(!t.between||!e)return!1;const i=Number(e);return!(Number.isNaN(i)||+i>=t.between.start&&+i<=t.between.end)},G=(e,t)=>{const i=Number(e);return!(!t.lessThan||Number.isNaN(i))&&i>=t.lessThan},W=(e,t)=>{const i=Number(e);return!(!t.greaterThan||Number.isNaN(i))&&i<=t.greaterThan},X=(e,t)=>{if(!t.sequential)return!1;const i=String(e).replace(/[^0-9]/g,"");return!(-1==="0123456789".indexOf(i)&&-1==="9876543210".indexOf(i))},H=(e,t)=>!(!t.regex||!e)&&!new RegExp(t.regex).test(e),ee=(e,t)=>!(!t.email||!e)&&!/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(e),te=(e,t)=>!(!t.url||!e)&&!/[(http(s)?)://(www.)?a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)/gi.test(e),ie=(e,t)=>!!t.onlyLetters&&!/^[\p{L}\s]*$/u.test(e),se=(e,t)=>!!t.notAllowSpaces&&/\s/.test(e),ne=(e,t)=>!!t.isNumber&&!!e&&!/^[0-9\s]*$/.test(e),re=(e,t)=>!(!t.hasNoExtraSpaces||!e)&&H(e,{regex:"^[A-Za-zÀ-ÖØ-öø-ÿäöüÄÖÜß0-9]+$"}),ae=(e,t)=>{if(!t.repeated)return!1;const i={};for(const t of String(e))if(/\d/.test(t)){if(i[t])return!0;i[t]=1}return!1},le=(e,t,{values:i=[],metadata:s=[]}={values:[],metadata:[],erroredFields:[],isValid:!0})=>!!(t.callback&&(null==t?void 0:t.callback)instanceof Function)&&t.callback(e,{values:i,metadata:s}),oe=(e,t)=>!(!e||!Array.isArray(null==t?void 0:t.includes)||(null==t?void 0:t.includes.some(t=>t===e||JSON.stringify(t)===e))),ue=(e,t)=>{const i=de(null==e?void 0:e.toString()),s=c(i);return["object"==typeof t&&t.length?null==s?void 0:s.filter(({type:e})=>t.some(t=>t===e))[0]:s[0],i]},de=e=>null==e?void 0:e.replace(/ /g,""),ce=(e,t=4,i="/")=>{const s=e.replace(/\D/g,""),n=s.slice(0,2);return s.length>=5?`${n}${i}${s.slice(2,t)}`:s.length>=3?`${n}${i}${s.slice(2)}`:s},he=(e,t)=>{if(!e)return!0;const[i]=ue(String(e),t.isCreditCard);return!i},ve=(e,t)=>{var i;if(!e||!t.isCreditCodeMatch)return!1;const[s]=ue(t.isCreditCodeMatch.numberCard,t.isCreditCodeMatch.availableOptions);return(null===(i=null==s?void 0:s.code)||void 0===i?void 0:i.size)!==e.length},fe=(e,t)=>{if(!e||!t.isCreditCardAndLength)return!1;const[i,s]=ue(e,t.isCreditCardAndLength);return i&&!i.lengths.includes(s.length)},pe=(e,t)=>{var i;return!(!(null==t?void 0:t.notEmpty)||void 0===e||null!==e&&""!==e&&0!==e&&(null===(i=String(e))||void 0===i?void 0:i.trim().length))},me=(e,t)=>null!=(null==t?void 0:t.value)&&null!=e&&e!=t.value,be=(e,t)=>!(!t.required||e&&("string"!=typeof e||0!==e.trim().length)),ge=(e,t)=>{if(!(null==t?void 0:t.bool))return!1;let i=!1;return"boolean"==typeof t.bool&&(i=t.bool),i},Se=(e,t)=>{if(!t.exists)return!1;let i=!t.exists;return i||(i=!e),i},ye=(e,t)=>{if(t.forceDefinedOrigin&&void 0===t.origin||t.forceDefinedTarget&&void 0===t.target)return!1;const i=void 0===t.origin?e:t.origin,s=void 0===t.target?e:t.target;return{"!==":(i||e)!==(s||e),"===":(i||e)===(s||e),"<":(i||e)<(s||e),">":(i||e)>(s||e),"<=":(i||e)<=(s||e),">=":(i||e)>=(s||e),"!!origin":!!String(i||e).trim().length}[t.condition]},$e=(e,t)=>{if(!t.conditions)return!1;let i={and:()=>{var i;return!!(null===(i=t.conditions)||void 0===i?void 0:i.set.every(t=>ye(e,t)))},or:()=>{var i;return!!(null===(i=t.conditions)||void 0===i?void 0:i.set.some(t=>ye(e,t)))}}[t.conditions.rule]();return t.conditions.conditions&&(i="and"===t.conditions.rule?i&&$e(e,{conditions:t.conditions.conditions}):i||$e(e,{conditions:t.conditions.conditions})),!i},Ve={DDMMYYYY:e=>{if(!e)return"";const t=e.split(e.includes("/")?"/":"-");return`${t[1]}/${t[0]}/${t[2]}`},YYYYMMDD:e=>{if(!e)return"";const t=e.split(e.includes("/")?"/":"-");return`${t[1]}/${t[2]}/${t[0]}`},YYYYDDMM:e=>{if(!e)return"";const t=e.split(e.includes("/")?"/":"-");return`${t[2]}/${t[1]}/${t[0]}`},MMDDYYYY:e=>e,timestamp:e=>new Date(e).toString()},je=(e,t)=>{var i;let s=!1;if(2!=(null===(i=t.betweenDates)||void 0===i?void 0:i.length))return!1;for(const i of t.betweenDates)if(Ee(e,{date:i})){s=!0;break}return s},Ee=(e,t)=>{var i,s,n,r,a,l,o,u,d,c,h,v;if(!(null===(s=null===(i=t.date)||void 0===i?void 0:i.target)||void 0===s?void 0:s.value)&&!(null===(r=null===(n=t.date)||void 0===n?void 0:n.origin)||void 0===r?void 0:r.intervals))return!1;const f=t.date.origin.value||e,p=Ve[null===(a=t.date)||void 0===a?void 0:a.origin.format](f).toString();let m=new Date(p),b=new Date,g=new Date;if((null===(o=null===(l=t.date)||void 0===l?void 0:l.target)||void 0===o?void 0:o.format)&&(g=new Date(Ve[null===(d=null===(u=t.date)||void 0===u?void 0:u.target)||void 0===d?void 0:d.format](t.date.target.value).toString()),b=g),t.date.origin.intervals){b=((e,t)=>{const i={years:(e,t)=>new Date(e.setUTCFullYear(e.getUTCFullYear()+t)),months:(e,t)=>new Date(e.setUTCMonth(e.getUTCMonth()+t)),days:(e,t)=>new Date(e.setDate(e.getUTCDate()+t))};return Object.keys(t).reduce((e,s)=>i[s](e,t[s]),new Date(e))})(m,t.date.origin.intervals);const e=new Date;(null===(c=t.date.target)||void 0===c?void 0:c.value)&&g&&(e.setDate(g.getDate()),e.setMonth(g.getMonth())),m=new Date(`${e.getUTCMonth()+1}/${e.getUTCDate()}/${e.getUTCFullYear()}`)}if(t.date.onlyValidDate&&(!(b instanceof Date&&isFinite(b))||!(b instanceof Date&&isFinite(m))||f.length<8))return!0;if(((e,t)=>{if(!e.includes("/")&&!e.includes("-")||!t)return!0;const i=e.replace(/[-/]/g,"");return!{DDMMYYYY:/^(\d{2})(\d{2})(\d{4})$/,YYYYMMDD:/^(\d{4})(\d{2})(\d{2})$/,YYYYDDMM:/^(\d{4})(\d{2})(\d{2})$/,MMDDYYYY:/^(\d{2})(\d{2})(\d{4})$/,DMYYYY:/^(\d{1,2})(\d{1,2})(\d{4})$/,YYYYMD:/^(\d{4})(\d{1,2})(\d{1,2})$/,YYYYDM:/^(\d{4})(\d{1,2})(\d{1,2})$/,MDYYYY:/^(\d{1,2})(\d{1,2})(\d{4})$/}[t].test(i)})(p,null===(h=t.date)||void 0===h?void 0:h.origin.format))return!1;const S=m.getTime(),y=b.getTime();return{">":S>y,">=":S>=y,"<":S<y,"<=":S<=y,"===":S===y,"!==":S!==y}[null===(v=t.date)||void 0===v?void 0:v.operator]},Ne=(e,t)=>{if(!t.validDate||!e)return!1;if(/[^a-zA-Z0-9\s-]/.test(e))return!0;const i=Ve[t.validDate](e).toString().split(/[/-]/),s=parseInt(i[2],10),n=parseInt(i[0],10)-1,r=parseInt(i[1],10),a=new Date(s,n,r),l=new Date;return l.setFullYear(l.getFullYear()-150),a.getFullYear()<l.getFullYear()||!(a.getFullYear()===s&&a.getMonth()===n&&a.getDate()===r)},xe={max:B,min:J,lessThan:G,greaterThan:W,length:z,regex:H,url:te,email:ee,onlyLetters:ie,notAllowSpaces:se,callback:le,hasNoExtraSpaces:re,between:K,sequential:X,includes:oe,repeated:ae,document:Q,isCreditCard:he,isCreditCodeMatch:ve,isCreditCardAndLength:fe,required:be,value:me,notEmpty:pe,bool:ge,exists:Se,isNumber:ne,conditions:$e,validDate:Ne,date:Ee,betweenDates:je},Oe={max:B,min:J,lessThan:G,greaterThan:W,length:z,regex:H,url:te,email:ee,onlyLetters:ie,notAllowSpaces:se,callback:le,hasNoExtraSpaces:re,between:K,sequential:X,includes:oe,repeated:ae,document:Q,isCreditCard:he,isCreditCodeMatch:ve,isCreditCardAndLength:fe,required:be,value:me,notEmpty:pe,bool:ge,exists:Se,isNumber:ne,conditions:$e,multipleValidations:(e,t)=>{if(!t.multipleValidations)return!1;const i=function(e,t){const i=[];return Object.keys(t).forEach(s=>{let n;n=M(xe[s])?xe[s](e,{[s]:t[s]}):R(e,t[s],xe),i.push(n)}),i}(e,t.multipleValidations.validations);return{AND:()=>i.every(e=>e),OR:()=>i.some(e=>e),NOT:()=>!i.every(e=>e)}[t.multipleValidations.rule]()},date:Ee,betweenDates:je,validDate:Ne};I(Oe);const Ie={capitalize:e=>String(e).charAt(0).toUpperCase()+String(e).slice(1),uppercase:e=>String(e).toUpperCase(),onlyNumbers:e=>String(e).replace(/(\D)+/gim,""),onlyLetters:e=>String(e).replace(/[^\p{L}\s]/gu,""),regex:(e,t)=>t.regex?String(e).replace(new RegExp(t.regex,"g"),""):e,splitter:(e,t)=>{if(!e||!t.splitter||"string"!=typeof e)return e;t.splitter.sort((e,t)=>e.position-t.position);let i=e,s=0;for(const e of t.splitter){const{position:t,value:n}=e,r=t+s;r>=0&&r<=i.length&&(i=i.slice(0,r)+n+i.slice(r),s+=n.length)}return i},maxLength:(e,t)=>{if(!e||!t.maxLength)return e;const i=String(e);return i.length>t.maxLength?i.substring(0,t.maxLength):e},onlyFloatNumber:(e,t)=>{const{onlyFloatNumber:i}=t;if(!i||"string"!=typeof e||!e)return e;const{precision:s=2,decimal:n="."}=i;if(!e.includes(n))return e;const r=e.replace(/[^0-9]/g,""),a=r.slice(0,r.length-s),l=r.slice(r.length-s);return parseFloat(`${a}.${l}`).toFixed(s)},trim:(e,t)=>!e||(null==t?void 0:t.trim)?e:String(e).trim(),gapsCreditCard:(e,t)=>{if(!t.gapsCreditCard)return e;const[i,s]=ue(e,null==t?void 0:t.gapsCreditCard);return((e,t)=>t?((e,t=[])=>{const[i,s]=t.reduce(([e,i],s,n)=>[`${e}([0-9]{0,${s-(t[n-1]||0)}})`,`${i}$${n+1} `],["",""]);return e.replace(new RegExp(i),s).trim()})(e.slice(0,null==t?void 0:t.lengths[0]),t.gaps):null==e?void 0:e.slice(0,19))(s,i)},callback:(e,t)=>(null==t?void 0:t.callback)?t.callback(e):e,dotEvery3chars:e=>{const t=String(e).replace(/\./g,"").replace(/(.{3})/g,"$1.");return t.endsWith(".")?t.slice(0,-1):t}};F(Ie);var Fe=(e,t)=>{if(!(null==t?void 0:t.generic))return e;let i=e;return t.generic.forEach(t=>{const{to:s=i.length,mask:n}=t;let{from:r}=t;if(s>e.length-1)return;0===r&&(r=1);const a=new Array(s-r+2).join(n);i=i.slice(0,r-1)+a+i.slice(s)}),i};const ke={currency:(e,t)=>{if(!(null==t?void 0:t.currency))return e;const{align:i="",decimal:s=".",precision:n=2,prefix:r="BBD",thousands:a=","}=t.currency;let l=(function(e){return"number"==typeof e||"object"==typeof e&&null!==e&&"[object Number]"===Object.prototype.toString.call(e)}(e)?Number(e).toFixed(n):e).replace(/[^0-9]/g,"");if(!l)return"";let o=l.slice(0,l.length-n).replace(/^0*/g,"").replace(/\B(?=(\d{3})+(?!\d))/g,a);""===o&&(o="0"),"right"===i&&String(e).endsWith(" ")&&(l=l.slice(0,-1));let u=o,d=l.slice(l.length-n);if(n>0&&(d="0".repeat(n-d.length)+d,u+=s+d),!i)return u;const c=h(r);return"left"===i?`${c} ${u}`:`${u} ${c}`},custom:(e,t)=>{if(!t.custom||!e)return e;let i="",s=0;const n=e.replace(/[^\w\s]/gi,"");for(const e of t.custom)if("#"===e){if(!(s<n.length))break;i+=n[s],s++}else s<=n.length&&(i+=e);return e.length<i.length&&(i=i.replace(/[^\w]+$/,"")),i},callback:(e,t)=>(null==t?void 0:t.callback)&&t.callback(e),generic:Fe,secureCreditCard:e=>Fe(e,{generic:[{from:1,to:4,mask:"x"},{from:6,to:9,mask:"x"},{from:11,to:14,mask:"x"},{from:16,to:19,mask:"x"}]}),card:e=>e.replace(/[^\dA-Z]/g,"").replace(/(.{4})/g,"$1 ").trim(),cardDate:e=>ce(e),fein:e=>ce(e,9,"-"),replaceAll:(e,t)=>{let i=t.replaceAll;return i?("number"==typeof i&&(i=null==i?void 0:i.toString()),new Array(String(e).length+1).join(i)):e}};k(ke);export{q as FormCore,Y as FormField,U as FormGroup,v as TMutationEnum,x as formatterRegistry,O as maskRegistry,F as registerFormatters,k as registerMasks,I as registerValidations,N as validationRegistry};
|
|
1
|
+
import e from"credit-card-type";import{getCurrencySymbol as t}from"@gaignoux/currency";import{BehaviorSubject as i,Subject as s,Subscription as n,groupBy as r,mergeMap as a,debounceTime as l,filter as o,combineLatest as u,startWith as d,map as c,distinctUntilKeyChanged as h}from"rxjs";var v=(e,t)=>{if(!t.length||!e)return!1;let i=e;return"string"!=typeof i&&(i=(null==e?void 0:e.toString())||i),{equal:i.length!==t.length.target,notEqual:i.length===t.length.target,less:i.length>=t.length.target,lessOrEqual:i.length>t.length.target,greater:i.length<=t.length.target,greaterOrEqual:i.length<t.length.target}[t.length.rule]};const f=e=>{if(9!==e.length)return!0;if(!/^\d{8}$/.test(e.slice(0,8)))return!0;const t="TRWAGMYFPDXBNJZSQVHLCKE"[parseInt(e.slice(0,8),10)%23];return!(e[8].toUpperCase()===t)};var p=(e,t)=>{if(!e||!t.document)return!0;const i={NIF:(e,t)=>((e,t)=>{switch(t){case"pt-PT":return(e=>{if(!/^\d{9}$/.test(e))return!1;const t=parseInt(e[8],10),i=11-Array.from(e.substring(0,8)).reduce((e,t,i)=>e+parseInt(t,10)*(9-i),0)%11;return 10===i||11===i?0===t:i===t})(e);case"es-ES":return f(e);case"it-IT":return(e=>/^[A-Z]{6}\d{2}[A-Z]\d{2}[A-Z]\d{3}[A-Z]$/.test(e))(e);case"de-DE":return(e=>/^\d{11}$/.test(e))(e);case"fr-FR":return(e=>/^\d{2} \d{3} \d{3} \d{3} \d{3}$/.test(e))(e);case"en-GB":return(e=>/^GB\d{9}|\d{12}|\d{3}[A-Z]{5}$/.test(e))(e);case"nl-BE":case"fr-BE":return(e=>!!/^\d{11}$/.test(e)&&97-parseInt(e.substring(0,9),10)%97===parseInt(e.substring(9),10))(e);case"nl-NL":return(e=>!!/^\d{9}$/.test(e)&&e.split("").map((e,t)=>parseInt(e,10)*(9-t)).reduce((e,t)=>e+t,0)%11==0)(e);case"sv-SE":return(e=>!!/^\d{10,12}$/.test(e)&&(12===e.length?e.substring(2):e).split("").map((e,t)=>{let i=parseInt(e,10)*(t%2==0?2:1);return i>9&&(i-=9),i}).reduce((e,t)=>e+t,0)%10==0)(e);default:throw new Error(`NIF validation not supported for locale: ${t}`)}})(e,t),NIE:e=>(e=>{if(9!==e.length)return!0;if(!/^[XYZ]\d{7}[TRWAGMYFPDXBNJZSQVHLCKE]$/.test(e))return!0;let t=e.toUpperCase().padStart(9,"0");return t=t[0].replace(/[XYZ]/g,e=>({X:"0",Y:"1",Z:"2"}[e]||e))+t.slice(1),f(t)})(e),CIF:e=>(e=>!/^[A-Z][0-9]{7}[A-J0-9]$/.test(e))(e),IBAN:e=>(e=>{const t=e.replace(/\s/g,"");return 24!==t.length||!/^(ES)[0-9]{22}$/.test(t)||1!==(e=>{for(;e.length>2;){const t=e.slice(0,6),i=parseInt(t,10);if(isNaN(i))return NaN;e=i%97+e.slice(t.length)}return parseInt(e,10)%97})(t.substring(4)+1428+t.substring(2,4))})(e)};return i[t.document.type](e,t.document.locale)};const m=(e,t)=>{const i=Number(e);return!(!t.max||Number.isNaN(i))&&i>Number(t.max)},b=(e,t)=>{const i=Number(e);return!(!t.min||Number.isNaN(i))&&i<Number(t.min)},g=(e,t)=>{if(!t.between||!e)return!1;const i=Number(e);return!(Number.isNaN(i)||+i>=t.between.start&&+i<=t.between.end)},S=(e,t)=>{const i=Number(e);return!(!t.lessThan||Number.isNaN(i))&&i>=t.lessThan},y=(e,t)=>{const i=Number(e);return!(!t.greaterThan||Number.isNaN(i))&&i<=t.greaterThan},$=(e,t)=>{if(!t.sequential)return!1;const i=String(e).replace(/[^0-9]/g,"");return!(-1==="0123456789".indexOf(i)&&-1==="9876543210".indexOf(i))},V=(e,t)=>!(!t.regex||!e)&&!new RegExp(t.regex).test(e),j=(e,t)=>!(!t.email||!e)&&!/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(e),E=(e,t)=>!(!t.url||!e)&&!/[(http(s)?)://(www.)?a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)/gi.test(e),N=(e,t)=>!!t.onlyLetters&&!/^[\p{L}\s]*$/u.test(e),x=(e,t)=>!!t.notAllowSpaces&&/\s/.test(e),O=(e,t)=>!!t.isNumber&&!!e&&!/^[0-9\s]*$/.test(e),I=(e,t)=>!(!t.hasNoExtraSpaces||!e)&&V(e,{regex:"^[A-Za-zÀ-ÖØ-öø-ÿäöüÄÖÜß0-9]+$"}),F=(e,t)=>{if(!t.repeated)return!1;const i={};for(const t of String(e))if(/\d/.test(t)){if(i[t])return!0;i[t]=1}return!1},k=(e,t,{values:i=[],metadata:s=[]}={values:[],metadata:[],erroredFields:[],isValid:!0})=>!!(t.callback&&(null==t?void 0:t.callback)instanceof Function)&&t.callback(e,{values:i,metadata:s}),w=(e,t)=>!(!e||!Array.isArray(null==t?void 0:t.includes)||(null==t?void 0:t.includes.some(t=>t===e||JSON.stringify(t)===e))),_=(t,i)=>{const s=D(null==t?void 0:t.toString()),n=e(s);return["object"==typeof i&&i.length?null==n?void 0:n.filter(({type:e})=>i.some(t=>t===e))[0]:n[0],s]},D=e=>null==e?void 0:e.replace(/ /g,""),A=(e,t=4,i="/")=>{const s=e.replace(/\D/g,""),n=s.slice(0,2);return s.length>=5?`${n}${i}${s.slice(2,t)}`:s.length>=3?`${n}${i}${s.slice(2)}`:s},T=(e,t)=>{if(!e)return!0;const[i]=_(String(e),t.isCreditCard);return!i},M=(e,t)=>{var i;if(!e||!t.isCreditCodeMatch)return!1;const[s]=_(t.isCreditCodeMatch.numberCard,t.isCreditCodeMatch.availableOptions);return(null===(i=null==s?void 0:s.code)||void 0===i?void 0:i.size)!==e.length},P=(e,t)=>{if(!e||!t.isCreditCardAndLength)return!1;const[i,s]=_(e,t.isCreditCardAndLength);return i&&!i.lengths.includes(s.length)},C=(e,t)=>{var i;return!(!(null==t?void 0:t.notEmpty)||void 0===e||null!==e&&""!==e&&0!==e&&(null===(i=String(e))||void 0===i?void 0:i.trim().length))},R=(e,t)=>null!=(null==t?void 0:t.value)&&null!=e&&e!=t.value,L=(e,t)=>!(!t.required||e&&("string"!=typeof e||0!==e.trim().length)),Y=(e,t)=>{if(!(null==t?void 0:t.bool))return!1;let i=!1;return"boolean"==typeof t.bool&&(i=t.bool),i},q=(e,t)=>{if(!t.exists)return!1;let i=!t.exists;return i||(i=!e),i},U=(e,t)=>{if(t.forceDefinedOrigin&&void 0===t.origin||t.forceDefinedTarget&&void 0===t.target)return!1;const i=void 0===t.origin?e:t.origin,s=void 0===t.target?e:t.target;return{"!==":(i||e)!==(s||e),"===":(i||e)===(s||e),"<":(i||e)<(s||e),">":(i||e)>(s||e),"<=":(i||e)<=(s||e),">=":(i||e)>=(s||e),"!!origin":!!String(i||e).trim().length}[t.condition]},z=(e,t)=>{if(!t.conditions)return!1;let i={and:()=>{var i;return!!(null===(i=t.conditions)||void 0===i?void 0:i.set.every(t=>U(e,t)))},or:()=>{var i;return!!(null===(i=t.conditions)||void 0===i?void 0:i.set.some(t=>U(e,t)))}}[t.conditions.rule]();return t.conditions.conditions&&(i="and"===t.conditions.rule?i&&z(e,{conditions:t.conditions.conditions}):i||z(e,{conditions:t.conditions.conditions})),!i},Z={DDMMYYYY:e=>{if(!e)return"";const t=e.split(e.includes("/")?"/":"-");return`${t[1]}/${t[0]}/${t[2]}`},YYYYMMDD:e=>{if(!e)return"";const t=e.split(e.includes("/")?"/":"-");return`${t[1]}/${t[2]}/${t[0]}`},YYYYDDMM:e=>{if(!e)return"";const t=e.split(e.includes("/")?"/":"-");return`${t[2]}/${t[1]}/${t[0]}`},MMDDYYYY:e=>e,timestamp:e=>new Date(e).toString()},Q=(e,t)=>{var i;let s=!1;if(2!=(null===(i=t.betweenDates)||void 0===i?void 0:i.length))return!1;for(const i of t.betweenDates)if(B(e,{date:i})){s=!0;break}return s},B=(e,t)=>{var i,s,n,r,a,l,o,u,d,c,h,v;if(!(null===(s=null===(i=t.date)||void 0===i?void 0:i.target)||void 0===s?void 0:s.value)&&!(null===(r=null===(n=t.date)||void 0===n?void 0:n.origin)||void 0===r?void 0:r.intervals))return!1;const f=t.date.origin.value||e,p=Z[null===(a=t.date)||void 0===a?void 0:a.origin.format](f).toString();let m=new Date(p),b=new Date,g=new Date;if((null===(o=null===(l=t.date)||void 0===l?void 0:l.target)||void 0===o?void 0:o.format)&&(g=new Date(Z[null===(d=null===(u=t.date)||void 0===u?void 0:u.target)||void 0===d?void 0:d.format](t.date.target.value).toString()),b=g),t.date.origin.intervals){b=((e,t)=>{const i={years:(e,t)=>new Date(e.setUTCFullYear(e.getUTCFullYear()+t)),months:(e,t)=>new Date(e.setUTCMonth(e.getUTCMonth()+t)),days:(e,t)=>new Date(e.setDate(e.getUTCDate()+t))};return Object.keys(t).reduce((e,s)=>i[s](e,t[s]),new Date(e))})(m,t.date.origin.intervals);const e=new Date;(null===(c=t.date.target)||void 0===c?void 0:c.value)&&g&&(e.setDate(g.getDate()),e.setMonth(g.getMonth())),m=new Date(`${e.getUTCMonth()+1}/${e.getUTCDate()}/${e.getUTCFullYear()}`)}if(t.date.onlyValidDate&&(!(b instanceof Date&&isFinite(b))||!(b instanceof Date&&isFinite(m))||f.length<8))return!0;if(((e,t)=>{if(!e.includes("/")&&!e.includes("-")||!t)return!0;const i=e.replace(/[-/]/g,"");return!{DDMMYYYY:/^(\d{2})(\d{2})(\d{4})$/,YYYYMMDD:/^(\d{4})(\d{2})(\d{2})$/,YYYYDDMM:/^(\d{4})(\d{2})(\d{2})$/,MMDDYYYY:/^(\d{2})(\d{2})(\d{4})$/,DMYYYY:/^(\d{1,2})(\d{1,2})(\d{4})$/,YYYYMD:/^(\d{4})(\d{1,2})(\d{1,2})$/,YYYYDM:/^(\d{4})(\d{1,2})(\d{1,2})$/,MDYYYY:/^(\d{1,2})(\d{1,2})(\d{4})$/}[t].test(i)})(p,null===(h=t.date)||void 0===h?void 0:h.origin.format))return!1;const S=m.getTime(),y=b.getTime();return{">":S>y,">=":S>=y,"<":S<y,"<=":S<=y,"===":S===y,"!==":S!==y}[null===(v=t.date)||void 0===v?void 0:v.operator]},J=(e,t)=>{if(!t.validDate||!e)return!1;if(/[^a-zA-Z0-9\s-]/.test(e))return!0;const i=Z[t.validDate](e).toString().split(/[/-]/),s=parseInt(i[2],10),n=parseInt(i[0],10)-1,r=parseInt(i[1],10),a=new Date(s,n,r),l=new Date;return l.setFullYear(l.getFullYear()-150),a.getFullYear()<l.getFullYear()||!(a.getFullYear()===s&&a.getMonth()===n&&a.getDate()===r)};function K(e){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e))return e.map(e=>K(e));const t={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=K(e[i]));return t}function G(e,t,i){if(null==e)return i;const s=Array.isArray(t)?t:t.split(".");let n=e;for(let e=0;e<s.length;e++){if(null==n)return i;n=n[s[e]]}return void 0===n?i:n}function W(e,t,i){if(null==e||"object"!=typeof e)return e;const s=Array.isArray(t)?t:t.split(".");let n=e;for(let e=0;e<s.length-1;e++){const t=s[e],i=s[e+1];null!=n[t]&&"object"==typeof n[t]||(n[t]="number"==typeof i||/^\d+$/.test(String(i))?[]:{}),n=n[t]}return n[s[s.length-1]]=i,e}function X(e,t){if(e===t)return!0;if(null==e||null==t)return e===t;if(typeof e!=typeof t)return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if("object"!=typeof e)return!1;const i=Array.isArray(e);if(i!==Array.isArray(t))return!1;if(i){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!X(e[i],t[i]))return!1;return!0}const s=Object.keys(e),n=Object.keys(t);if(s.length!==n.length)return!1;for(const i of s){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!X(e[i],t[i]))return!1}return!0}function H(e){return null==e}function ee(e){return"function"==typeof e}var te=(e,t,i)=>!!t&&function(e,t,i){const s=[];return Object.keys(t).forEach(n=>{s.push(i[n](e,{[n]:t[n]}))}),s}(e,t,i).some(e=>e);const ie={max:m,min:b,lessThan:S,greaterThan:y,length:v,regex:V,url:E,email:j,onlyLetters:N,notAllowSpaces:x,callback:k,hasNoExtraSpaces:I,between:g,sequential:$,includes:w,repeated:F,document:p,isCreditCard:T,isCreditCodeMatch:M,isCreditCardAndLength:P,required:L,value:R,notEmpty:C,bool:Y,exists:q,isNumber:O,conditions:z,validDate:J,date:B,betweenDates:Q},se={},ne={},re={};function ae(e){Object.assign(se,e)}function le(e){Object.assign(ne,e)}function oe(e){Object.assign(re,e)}const ue={max:m,min:b,lessThan:S,greaterThan:y,length:v,regex:V,url:E,email:j,onlyLetters:N,notAllowSpaces:x,callback:k,hasNoExtraSpaces:I,between:g,sequential:$,includes:w,repeated:F,document:p,isCreditCard:T,isCreditCodeMatch:M,isCreditCardAndLength:P,required:L,value:R,notEmpty:C,bool:Y,exists:q,isNumber:O,conditions:z,multipleValidations:(e,t)=>{if(!t.multipleValidations)return!1;const i=function(e,t){const i=[];return Object.keys(t).forEach(s=>{let n;n=ee(ie[s])?ie[s](e,{[s]:t[s]}):te(e,t[s],ie),i.push(n)}),i}(e,t.multipleValidations.validations);return{AND:()=>i.every(e=>e),OR:()=>i.some(e=>e),NOT:()=>!i.every(e=>e)}[t.multipleValidations.rule]()},date:B,betweenDates:Q,validDate:J};ae(ue);const de={capitalize:e=>String(e).charAt(0).toUpperCase()+String(e).slice(1),uppercase:e=>String(e).toUpperCase(),onlyNumbers:e=>String(e).replace(/(\D)+/gim,""),onlyLetters:e=>String(e).replace(/[^\p{L}\s]/gu,""),regex:(e,t)=>t.regex?String(e).replace(new RegExp(t.regex,"g"),""):e,splitter:(e,t)=>{if(!e||!t.splitter||"string"!=typeof e)return e;t.splitter.sort((e,t)=>e.position-t.position);let i=e,s=0;for(const e of t.splitter){const{position:t,value:n}=e,r=t+s;r>=0&&r<=i.length&&(i=i.slice(0,r)+n+i.slice(r),s+=n.length)}return i},maxLength:(e,t)=>{if(!e||!t.maxLength)return e;const i=String(e);return i.length>t.maxLength?i.substring(0,t.maxLength):e},onlyFloatNumber:(e,t)=>{const{onlyFloatNumber:i}=t;if(!i||"string"!=typeof e||!e)return e;const{precision:s=2,decimal:n="."}=i;if(!e.includes(n))return e;const r=e.replace(/[^0-9]/g,""),a=r.slice(0,r.length-s),l=r.slice(r.length-s);return parseFloat(`${a}.${l}`).toFixed(s)},trim:(e,t)=>!e||(null==t?void 0:t.trim)?e:String(e).trim(),gapsCreditCard:(e,t)=>{if(!t.gapsCreditCard)return e;const[i,s]=_(e,null==t?void 0:t.gapsCreditCard);return((e,t)=>t?((e,t=[])=>{const[i,s]=t.reduce(([e,i],s,n)=>[`${e}([0-9]{0,${s-(t[n-1]||0)}})`,`${i}$${n+1} `],["",""]);return e.replace(new RegExp(i),s).trim()})(e.slice(0,null==t?void 0:t.lengths[0]),t.gaps):null==e?void 0:e.slice(0,19))(s,i)},callback:(e,t)=>(null==t?void 0:t.callback)?t.callback(e):e,dotEvery3chars:e=>{const t=String(e).replace(/\./g,"").replace(/(.{3})/g,"$1.");return t.endsWith(".")?t.slice(0,-1):t}};le(de);var ce=(e,t)=>{if(!(null==t?void 0:t.generic))return e;let i=e;return t.generic.forEach(t=>{const{to:s=i.length,mask:n}=t;let{from:r}=t;if(s>e.length-1)return;0===r&&(r=1);const a=new Array(s-r+2).join(n);i=i.slice(0,r-1)+a+i.slice(s)}),i};const he={currency:(e,i)=>{if(!(null==i?void 0:i.currency))return e;const{align:s="",decimal:n=".",precision:r=2,prefix:a="BBD",thousands:l=","}=i.currency;let o=(function(e){return"number"==typeof e||"object"==typeof e&&null!==e&&"[object Number]"===Object.prototype.toString.call(e)}(e)?Number(e).toFixed(r):e).replace(/[^0-9]/g,"");if(!o)return"";let u=o.slice(0,o.length-r).replace(/^0*/g,"").replace(/\B(?=(\d{3})+(?!\d))/g,l);""===u&&(u="0"),"right"===s&&String(e).endsWith(" ")&&(o=o.slice(0,-1));let d=u,c=o.slice(o.length-r);if(r>0&&(c="0".repeat(r-c.length)+c,d+=n+c),!s)return d;const h=t(a);return"left"===s?`${h} ${d}`:`${d} ${h}`},custom:(e,t)=>{if(!t.custom||!e)return e;let i="",s=0;const n=e.replace(/[^\w\s]/gi,"");for(const e of t.custom)if("#"===e){if(!(s<n.length))break;i+=n[s],s++}else s<=n.length&&(i+=e);return e.length<i.length&&(i=i.replace(/[^\w]+$/,"")),i},callback:(e,t)=>(null==t?void 0:t.callback)&&t.callback(e),generic:ce,secureCreditCard:e=>ce(e,{generic:[{from:1,to:4,mask:"x"},{from:6,to:9,mask:"x"},{from:11,to:14,mask:"x"},{from:16,to:19,mask:"x"}]}),card:e=>e.replace(/[^\dA-Z]/g,"").replace(/(.{4})/g,"$1 ").trim(),cardDate:e=>A(e),fein:e=>A(e,9,"-"),replaceAll:(e,t)=>{let i=t.replaceAll;return i?("number"==typeof i&&(i=null==i?void 0:i.toString()),new Array(String(e).length+1).join(i)):e}};var ve;function fe(e,t,i,s){return new(i||(i=Promise))(function(n,r){function a(e){try{o(s.next(e))}catch(e){r(e)}}function l(e){try{o(s.throw(e))}catch(e){r(e)}}function o(e){e.done?n(e.value):function(e){return e instanceof i?e:new i(function(t){t(e)})}(e.value).then(a,l)}o((s=s.apply(e,t||[])).next())})}oe(he),function(e){e.ON_VALUE="value",e.ON_PROPS="props",e.ON_VISIBILITY="visibility",e.ON_API="api",e.ON_IVARS="iVars",e.ON_FIELDS="fields"}(ve||(ve={})),"function"==typeof SuppressedError&&SuppressedError;const pe=1e3,me=/^\$\{(?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*\}$/,be=/\$\{((?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*)\}/g,ge=/\s*(\|\||&&|!+)\s*/g,Se=/^\|\||&&|!+$/,ye=["fields","iVars","form"],$e=["api","apiSchema","props","validations","visibilityConditions","resetValues"],Ve=!1;function je(e){const t=be,i=[];let s;for(;null!==(s=t.exec(e));)i.push(s[1]);const n=ge,r=i.map(e=>e.split(n).filter(e=>!n.test(e))).flat().filter(e=>e.split(".").length>1);return{originScopeKeys:Array.from(new Set(r.map(e=>e.split(".")[0]))),originFieldKeys:Array.from(new Set(r.map(e=>e.split(".")[1]))),originPropertyKeys:Array.from(new Set(r.map(e=>e.split(".")[2])))}}function Ee(e,t){const i=[];if(Array.isArray(e))e.forEach((e,s)=>{i.push(...Ee(e,`${t?`${t}.`:""}${s}`))});else if("object"==typeof e)for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&i.push(...Ee(e[s],`${t?`${t}.`:""}${s}`));else if("string"==typeof e&&e.includes("${")){const s=(t||"").split(".");je(e).originScopeKeys.every(e=>ye.includes(e))?i.push(Object.assign(Object.assign({originExpression:e},je(e)),{destinationKey:s[0],destinationProperty:s[1],destinationPath:s.slice(2)})):console.warn(`scope malformed on this expression: ${e}, ignoring..`)}return i}class Ne extends s{constructor(e){super(),this.isMounted=e}next(e){this.isMounted()&&super.next(e)}}class xe extends i{constructor(e){super(e),this.defaultValue=e}next(e){this.closed||super.next(e)}get value(){return this.closed?this.defaultValue:super.value}}function Oe(e,t,i,s,n){return ee(i[s])?i[s](e,t,n):te(e,t[s],i)}class Ie{constructor({formIndex:e,schemaComponent:t,config:i,children:s,validateVisibility:r,resetValue:a,resetProperty:l,templateSubject$:o,fieldEventSubject$:u,dataSubject$:d,fieldValidNotification$:c,mountSubject$:h,mapper:v,formValuesStateSubject$:f,submitEvent:p,visibility:m,persistValue:b}){var g,S,y,$,V,j;this.valueSubscription$=new n,this.fieldStateSubscription$=new n,this.formIndex=e,this.originalSchema=K(t),this.config={defaultAPIdebounceTimeMS:Number(null==i?void 0:i.defaultAPIdebounceTimeMS)?Number(null==i?void 0:i.defaultAPIdebounceTimeMS):pe,defaultStateRefreshTimeMS:Number(null==i?void 0:i.defaultStateRefreshTimeMS)?Number(null==i?void 0:i.defaultStateRefreshTimeMS):100,defaultLogVerbose:(null==i?void 0:i.defaultLogVerbose)?i.defaultLogVerbose:Ve},this.name=t.name,this.nameToSubmit=t.nameToSubmit,this.component=t.component,this.children=s,this.validations=K(t.validations),this.visibilityConditions=K(t.visibilityConditions),this.resetValues=K(t.resetValues),this.resetPropertyValues=K(t.resetPropertyValues),this.apiSchema=K(t.api),this.formatters=K(t.formatters),this.masks=K(t.masks),v.valueChangeEvent&&(this.valueChangeEvent=v.valueChangeEvent),(null===(g=v.events)||void 0===g?void 0:g.setValue)&&(this.valuePropName=v.events.setValue),this.mapper=v,this.validateVisibility=r,this.resetValue=a,this.resetProperty=l,this.submitEvent=p,this.templateSubject$=o,this.fieldEventSubject$=u,this.dataSubject$=d,this.fieldValidNotification$=c,this.mountSubject$=h,this.formValuesStateSubject$=f,this.getFormValues=()=>this.formValuesStateSubject$.value,this._props=Ie.filterProps(K(t.props||{})),this._adapterProps=JSON.stringify(t.props||{}),this._metadata="",this.errorsString="",this.errorsList=[],this._visibility="boolean"!=typeof m||m,this._api={default:{response:(null===($=null===(y=null===(S=this.apiSchema)||void 0===S?void 0:S.defaultConfig)||void 0===y?void 0:y.config)||void 0===$?void 0:$.fallbackValue)||"",status:null},named:(null===(V=this.apiSchema)||void 0===V?void 0:V.configs)&&Object.keys(null===(j=this.apiSchema)||void 0===j?void 0:j.configs).reduce((e,t)=>{var i,s;return e[t]={response:(null===(s=null===(i=this.apiSchema)||void 0===i?void 0:i.configs)||void 0===s?void 0:s[t].config.fallbackValue)||"",status:null},e},{}),apiState:{loading:!1}},this._errors={},this._mounted=!1,this.valid=!0,this.persistValue=b,this.initializeObservers()}initializeObservers(){this.valueSubject$&&!this.valueSubject$.closed||(this.valueSubject$=new Ne(()=>this.mounted)),this.errorSubject$&&!this.errorSubject$.closed||(this.errorSubject$=new Ne(()=>this.mounted)),this.visibilitySubject$&&!this.visibilitySubject$.closed||(this.visibilitySubject$=new Ne(()=>this.mounted)),this.propsSubject$&&!this.propsSubject$.closed||(this.propsSubject$=new Ne(()=>this.mounted)),this.fieldStateSubscription$&&!this.fieldStateSubscription$.closed||(this.fieldStateSubscription$=new n),this.apiEventQueueSubject$&&!this.apiEventQueueSubject$.closed||(this.apiEventQueueSubject$=new Ne(()=>this.mounted)),this.apiEventQueueSubject$.observed||this.apiEventQueueSubject$.pipe(r(({event:e})=>e),a(e=>e.pipe(l(this.config.defaultAPIdebounceTimeMS))),o(()=>this.apiEventQueueSubject$&&!this.apiEventQueueSubject$.closed)).subscribe(e=>{this.apiRequest(e)})}get adapterProps(){return this._adapterProps}set adapterProps(e){const t=JSON.stringify(e||{});t!==this.adapterProps&&(this.props=Ie.filterProps(e),this._adapterProps=t)}get props(){return this._props}set props(e){void 0===e||X(e,this.props)||(this._props=e,this.propsSubject$.next(this.props),this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_PROPS"}))}static filterProps(e){return Array.isArray(e)?e.filter(e=>"string"!=typeof e||!e.includes("${")).map(e=>Ie.filterProps(e)):"object"==typeof e&&null!==e?e instanceof Date?e:Object.keys(e).reduce((t,i)=>{const s=e[i];return"string"==typeof s&&s.includes("${")||(t[i]=Ie.filterProps(e[i])),t},{}):e}get stateValue(){return this._stateValue}get metadata(){return this._metadata}get value(){return this._value}set value(e){var t,i,s;let n;if(this.valueChangeEvent)try{n=this.valueChangeEvent(e,{props:this.props})}catch(t){n=e}else n=e;null!=n&&("object"==typeof n&&"_value"in n&&"_metadata"in n?(this._value=this.formatValue(n._value),this._stateValue=(null===(t=this.mapper.events)||void 0===t?void 0:t.setValue)?{[this.mapper.events.setValue]:this.maskValue(this.formatValue(n._value))}:{},this._metadata=n._metadata):(this._value=this.formatValue(n),this._stateValue=(null===(i=this.mapper.events)||void 0===i?void 0:i.setValue)?{[null===(s=this.mapper.events)||void 0===s?void 0:s.setValue]:this.maskValue(this.formatValue(n))}:{},this.maskValue(this.formatValue(n)),this._metadata=n),this.stateValue&&this.valueSubject$.next(this.stateValue),this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_VALUE"}))}get visibility(){return this._visibility}set visibility(e){void 0!==e&&e!==this.visibility&&(this._visibility=e,this.visibilitySubject$.next(this.visibility),this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_VISIBILITY"}))}set valid(e){"boolean"!=typeof e&&this.valid===e||(this._valid=e,this.triggerFieldValidNotification())}get valid(){return this._valid}triggerFieldValidNotification(){this.fieldValidNotification$.closed||this.fieldValidNotification$.next({fieldTrigger:this.name})}get errors(){return this._errors}set errors(e){var t;void 0===e||X(e,this.errors)||(this._errors=e,this.errorsList=Object.values(this.errors).filter(e=>null!=e),this.errorsString=this.errorsList.join(", "),(null===(t=this.mapper.events)||void 0===t?void 0:t.setErrorMessage)&&this.errorSubject$.next({[this.mapper.events.setErrorMessage]:this.errorsString}),this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_PROPS"}))}get api(){return this._api}set api(e){void 0!==e&&(this._api=e,this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_API_RESPONSE"}),this.emitEvents({event:"ON_API_FIELD_RESPONSE"}))}notifyApiRequest(){this._api.apiState.loading=!0,this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_API_REQUEST"}),this.emitEvents({event:"ON_API_FIELD_REQUEST"})}get mounted(){return this._mounted}set mounted(e){void 0!==e&&e!==this.mounted&&(this._mounted=e,this.initializeObservers(),this.mountSubject$.closed||this.mountSubject$.next({key:this.name,status:this.mounted}))}mountField({valueSubscription:e,propsSubscription:t}){this.mounted=!0,this.subscribeValue(e),this.subscribeState(t),this.valueSubject$.next(this.stateValue),this.propsSubject$.next(this.props),this.visibilitySubject$.next(this.visibility),this.fieldEventSubject$.next({event:"ON_FIELD_MOUNT",fieldName:this.name,fieldInstance:this})}emitValue(e){this.visibility&&this.mounted&&(this.value=e.value,this.dataSubject$.next({event:e.event,fieldIndex:this.name,formIndex:this.formIndex}),this.emitEvents({event:e.event}))}emitEvents({event:e}){if("ON_FORM_SUBMIT"===e)return this.submitEvent();this.validateVisibility({event:e,key:this.name}),this.setFieldValidity({event:e}),this.resetValue({event:e,key:this.name}),this.resetProperty({event:e,key:this.name}),this.apiEventQueueSubject$.next({event:e}),this.fieldEventSubject$.next({event:e,fieldName:this.name,fieldInstance:this})}setFieldValidity({event:e}){var t,i,s,n;if(!this.validations||!this.visibility)return this.errors={},void(this.valid=!0);let r=!0;const a={},l=null===(t=this.validations)||void 0===t?void 0:t.methods;if(l&&Object.keys(l).forEach(e=>{var t,i;const s=Oe(this.value,l,se,e,null===(t=this.formValuesStateSubject$)||void 0===t?void 0:t.value);r=!s&&r,s&&(null===(i=this.validations)||void 0===i?void 0:i.messages)?e in this.validations.messages?a[e]=this.validations.messages[e]:"default"in this.validations.messages&&(a[e]=this.validations.messages.default):delete a[e]}),this.valid=r,null===(s=null===(i=this.validations)||void 0===i?void 0:i.eventMessages)||void 0===s?void 0:s[e]){const t={};null===(n=this.validations.eventMessages[e])||void 0===n||n.forEach(e=>{e in a&&(t[e]=a[e])}),this.errors=t}else"ON_FIELD_VALIDATION"===e&&(this.errors=a)}formatValue(e){return this.formatters?Object.keys(this.formatters).reduce((e,t)=>{const i=ne[t];return i?i(e,this.formatters):e},e):e}maskValue(e){return this.masks?Object.keys(this.masks).reduce((e,t)=>{const i=re[t];return i?i(e,this.masks):e},e):e}checkApiRequestValidations(e){let t=!0;const i=e.preConditions;return i&&Object.keys(i).forEach(e=>{var s;const n=Oe(this.value,i,se,e,null===(s=this.formValuesStateSubject$)||void 0===s?void 0:s.value);t=t&&!n}),e.blockRequestWhenInvalid&&(t=t&&this.valid),t}apiRequest(e){return fe(this,arguments,void 0,function*({event:e}){var t,i,s,n,r,a,l,o,u;let d=!1;const c=e=>fe(this,void 0,void 0,function*(){var t,i;try{const{status:s,response:n}=yield function(e,t,i,s,n){return fe(this,void 0,void 0,function*(){if(n){const[e,i]=t.split("?"),s=new URLSearchParams(i);Object.keys(n).forEach(e=>{s.append(e,n[e])}),t=`${e}?${s.toString()}`}const r=yield fetch(t,{method:e,headers:i,body:s?JSON.stringify(s):void 0}),a=yield r.text();return{status:r.status,response:a}})}(e.method,e.url,e.headers,e.body,e.queryParams),r=null===(t=e.transform)||void 0===t?void 0:t.callback,a=r?r({payload:JSON.parse(String(n)),formValues:null===(i=this.formValuesStateSubject$)||void 0===i?void 0:i.value}):JSON.parse(String(n));return{response:e.resultPath?G(a,e.resultPath):a,status:s}}catch(t){return{response:H(null==e?void 0:e.fallbackValue)?"error":e.fallbackValue,status:500}}});if("ON_API_FIELD_RESPONSE"===this.api.apiState.lastEvent&&"ON_API_FIELD_RESPONSE"===e||!(null===(i=null===(t=this.apiSchema)||void 0===t?void 0:t.defaultConfig)||void 0===i?void 0:i.events.includes(e))&&(!(null===(s=this.apiSchema)||void 0===s?void 0:s.configs)||!Object.keys(null===(n=this.apiSchema)||void 0===n?void 0:n.configs).some(t=>{var i,s;return null===(s=null===(i=this.apiSchema)||void 0===i?void 0:i.configs)||void 0===s?void 0:s[t].events.includes(e)})))return;const h={default:Object.assign({},this.api.default),named:Object.assign({},this.api.named),apiState:Object.assign({},this.api.apiState)},v=null===(r=this.apiSchema.defaultConfig)||void 0===r?void 0:r.config;if(v&&(null===(l=null===(a=this.apiSchema)||void 0===a?void 0:a.defaultConfig)||void 0===l?void 0:l.events.includes(e))&&this.checkApiRequestValidations(v)){d||this.notifyApiRequest();const{response:e,status:t}=yield c(v);d=!0,h.default={response:e,status:t}}if((null===(o=this.apiSchema)||void 0===o?void 0:o.configs)&&Object.keys(null===(u=this.apiSchema)||void 0===u?void 0:u.configs).some(t=>{var i,s;return null===(s=null===(i=this.apiSchema)||void 0===i?void 0:i.configs)||void 0===s?void 0:s[t].events.includes(e)})&&this.apiSchema.configs){const t=yield Promise.all(Object.keys(this.apiSchema.configs).map(t=>fe(this,void 0,void 0,function*(){var i,s,n,r;const a=null===(s=null===(i=this.apiSchema)||void 0===i?void 0:i.configs)||void 0===s?void 0:s[t].config;if(a&&(null===(r=null===(n=this.apiSchema)||void 0===n?void 0:n.configs)||void 0===r?void 0:r[t].events.includes(e))&&this.checkApiRequestValidations(a)){d||this.notifyApiRequest();const{response:e,status:i}=yield c(a);return d=!0,{name:t,result:{response:e,status:i}}}return null})));t.forEach(e=>{e&&h.named&&(h.named[e.name]=e.result)})}d&&(h.apiState.lastEvent=e,h.apiState.loading=!1,this.api=h)})}destroyField(){this.mounted=!1,this.valueSubscription$.unsubscribe(),this.visibilitySubject$.unsubscribe(),this.fieldStateSubscription$.unsubscribe(),this.propsSubject$.unsubscribe(),this.errorSubject$.unsubscribe(),this.apiEventQueueSubject$.unsubscribe(),this.dataSubject$.closed||this.dataSubject$.next({event:"ON_FIELD_UNMOUNT",fieldIndex:this.name,formIndex:this.formIndex}),this.fieldEventSubject$.closed||this.fieldEventSubject$.next({event:"ON_FIELD_UNMOUNT",fieldName:this.name,fieldInstance:this})}subscribeState(e){var t;this.fieldStateSubscription$=u({visibility:this.visibilitySubject$.pipe(d(this.visibility)),props:this.propsSubject$.pipe(d(this.props)),errors:this.errorSubject$.pipe(d(Object.assign({},(null===(t=this.mapper.events)||void 0===t?void 0:t.setErrorMessage)&&{[this.mapper.events.setErrorMessage]:this.errorsString})))}).pipe(l(this.config.defaultStateRefreshTimeMS)).subscribe({next:e})}subscribeValue(e){this.valueSubscription$=this.valueSubject$.subscribe({next:e})}}class Fe{constructor(e){var t,i,r,a,l,o,u,d,c,h,v;this.templateSubscription$=new n,this.mappers=new Map,this.queuedFieldVisibilityEvents=new Map,this.queuedFieldResetValuesEvents=new Map,this.queuedFieldResetPropertyEvents=new Map,this.queuedInitialValues=new Map,this._valid=!1,this.stopEventsOnSubmit=!1,this.submitted=!1,this.isolatedFormInstance=!1,this.index=e.index,this.schema=e.schema,this.fields=new Map,this.action=e.action||(null===(t=e.schema)||void 0===t?void 0:t.action),this.method=e.method||(null===(i=e.schema)||void 0===i?void 0:i.method),this.config={defaultAPIdebounceTimeMS:Number(null===(r=e.config)||void 0===r?void 0:r.defaultAPIdebounceTimeMS)?Number(null===(a=e.config)||void 0===a?void 0:a.defaultAPIdebounceTimeMS):pe,defaultStateRefreshTimeMS:Number(null===(l=e.config)||void 0===l?void 0:l.defaultStateRefreshTimeMS)?Number(null===(o=e.config)||void 0===o?void 0:o.defaultStateRefreshTimeMS):100,defaultLogVerbose:(null===(u=e.config)||void 0===u?void 0:u.defaultLogVerbose)?e.config.defaultLogVerbose:Ve},null===(d=e.mappers)||void 0===d||d.map(e=>{this.mappers.set(e.componentName,e)}),e.submitSubject$&&e.dataSubject$&&e.formValidSubject$||(this.isolatedFormInstance=!0,this.config.defaultLogVerbose&&console.warn(`some formGroup events are not properly instanciated, any onData, onValid, onSubmit events managed by formGroup won't trigger on form: ${this.index}`)),this.schema&&Fe.checkIndexes(this.schema.components),this.templateSubject$=new s,this.fieldEventSubject$=new s,this.mountSubject$=new s,this.fieldValidNotification$=new s,this.submitSubject$=e.submitSubject$?e.submitSubject$:new s,this.dataSubject$=e.dataSubject$?e.dataSubject$:new s,this.formValidSubject$=e.formValidSubject$?e.formValidSubject$:new s,this.formValuesStateSubject$=new xe({erroredFields:[],isValid:!0,metadata:[],values:[]}),this.getFormValues=()=>this.formValuesStateSubject$.value,this.subscribedTemplates=[],this.templateSubscription$=this.templateSubject$.subscribe(this.refreshTemplates.bind(this)),this.fieldValidNotification$.subscribe(()=>{this.validateForm()}),this.fieldEventSubject$.subscribe(()=>{this.formValuesStateSubject$.next(this.getFormState())}),this.dataSubject$.subscribe(()=>{this.formValuesStateSubject$.next(this.getFormState())}),this.mountSubject$.subscribe(this.mountActions.bind(this)),this.prefetchedData=null===(c=e.schema)||void 0===c?void 0:c.prefetchedData,this.initialValues=e.initialValues||(null===(h=e.schema)||void 0===h?void 0:h.initialValues),this.iVars=e.iVars||(null===(v=e.schema)||void 0===v?void 0:v.iVars)||{},this.stopEventsOnSubmit=(null==e?void 0:e.stopEventsOnSubmit)||!1,this.submitted=!1}generateFields(){this.schema&&this.serializeStructure(this.schema.components),this.fields.forEach(e=>{e.mountField({valueSubscription:()=>null,propsSubscription:()=>null})})}submitChecker(){return!(this.stopEventsOnSubmit&&this.submitted)}mountActions({key:e,status:t}){if(t){const t=this.fields.get(e);if(!t)return void(this.config.defaultLogVerbose&&console.warn(`field ${e} was mounted but since it's parent has some visibility condition the field was already removed`));this.subscribeTemplates(),this.refreshTemplates({scope:"fields",event:"ON_FIELDS"}),this.templateSubject$.next({scope:"iVars",event:"ON_IVARS"}),this.queuedInitialValues.has(e)||(t.valuePropName&&!t.value?t.emitValue({event:"ON_FIELD_MOUNT",value:""}):t.emitEvents({event:"ON_FIELD_MOUNT"})),this.checkFieldEventQueues(e)}}set initialValues(e){e&&Object.keys(e).forEach(t=>{const i=this.fields.get(t);i&&(null==i?void 0:i.visibility)&&(null==i?void 0:i.mounted)?i.emitValue({value:null==e?void 0:e[t],event:"ON_FIELD_MOUNT"}):this.queuedInitialValues.set(t,null==e?void 0:e[t])})}get iVars(){return this._iVars}set iVars(e){this._iVars=e,this.templateSubject$.next({scope:"iVars",event:"ON_IVARS"})}validateForm(){if(0===this.fields.size)return this.valid=!1;for(const[,e]of this.fields)if(!e.valid)return this.valid=!1;return this.valid=!0}get valid(){return this._valid}set valid(e){this._valid!==e&&(this._valid=e,this.templateSubject$.next({event:"ON_FORM",scope:"form"}),this.formValidSubject$.next({formIndex:this.index,valid:this.valid}))}subscribeTemplates(){this.subscribedTemplates=[],this.fields.forEach(({originalSchema:{component:e,props:t,name:i,validations:s,visibilityConditions:n,resetValues:r,resetPropertyValues:a,api:l}},o)=>{Ee({component:e,props:t,name:i,validations:s,visibilityConditions:n,resetValues:r,resetPropertyValues:a,apiSchema:l},o).forEach(e=>this.subscribedTemplates.push(e))})}getValue({scope:e,key:t,property:i,path:s}){switch(e){case"iVars":return G(this.iVars,[t,...i?[i]:[],...s]);case"form":return G(this,[t,...i?[i]:[],...s]);case"fields":{const e=this.fields.get(t);return e?"props"===i&&s[0]===e.valuePropName?e.value:s.length>0?G(e[i],s):e[i]:this.config.defaultLogVerbose&&console.warn(`failed to get value from ${t}`)}}}setValue({key:e,property:t,path:i,originKey:s,value:n}){const r=this.fields.get(e);if(r){if(i.length>0){if("props"===t&&i[0]===r.valuePropName&&e!==s)return void r.emitValue({event:"ON_FIELD_CHANGE",value:n});const a=r[t];let l;return Array.isArray(a)||"object"==typeof a&&!H(a)?(l=K(a),W(l,i,n),void(r[t]=l)):void(this.config.defaultLogVerbose&&console.warn(`invalid template property, skipping evaluation of ${r.name} with ${a}`))}r[t]=n}else this.config.defaultLogVerbose&&console.warn(`failed to update field ${e}`)}extractParams(e){const t=function(e){const t=e.split(".");return t.length>1?this.getValue({scope:t[0],key:t[1],property:t[2],path:t.slice(3)}):t[0]}.bind(this),i=[];let s;for(;!H(s=be.exec(e));)i.push(s[1]);const n=i.map(e=>e.split(ge)).map(e=>e.length<=1?{parse:!1,value:t(e[0])}:{parse:!0,value:e.filter(Boolean).reduce((e,i)=>{if(i.match(Se))return`${e}${i}`;let s;const n=t(i);let r;try{r=JSON.parse(n)}catch(e){r=n}switch(typeof r){case"string":s=`\`${r}\``;break;case"boolean":case"undefined":case"number":default:s=r;break;case"object":if(null===r){s=null;break}if(r instanceof Date){s=`new Date(\`${r}\`)`;break}s=JSON.stringify(r)}return`${e}${s}`},"")});return n.map(({parse:t,value:i})=>{try{return t?new Function(`return ${i}`)():i}catch(t){return this.config.defaultLogVerbose&&(console.warn(`unhandled parsing on ${e} returning`),console.warn(i)),i}})}replaceExpression(e,t){return e.replace(be,()=>String(t.shift())||"")}hasStringConcatenation(e){return!me.test(e)}refreshTemplates({key:e,event:t}){this.subscribedTemplates.forEach(({destinationKey:i,destinationPath:s,destinationProperty:n,originExpression:r,originFieldKeys:a})=>{if(!e||a.includes(e)){const a=this.extractParams(r);let l;l=this.hasStringConcatenation(r)?this.replaceExpression(r,[...a]):null==a?void 0:a[0],X(this.getValue({scope:"fields",key:i,property:n,path:s}),l)||this.setValue({key:i,property:n,path:s,originKey:e,value:l,event:t})}})}checkFieldEventQueues(e){var t;if(null===(t=this.fields.get(e))||void 0===t?void 0:t.mounted){if(this.queuedFieldVisibilityEvents.has(e)&&(this.setFieldVisibility(Object.assign({field:e},this.queuedFieldVisibilityEvents.get(e))),this.queuedFieldVisibilityEvents.delete(e)),this.queuedInitialValues.has(e)){const t=this.queuedInitialValues.get(e);this.queuedInitialValues.delete(e),this.initialValues={[e]:t}}this.queuedFieldResetValuesEvents.has(e)&&(this.setResetFieldValue(Object.assign({key:e},this.queuedFieldResetValuesEvents.get(e))),this.queuedFieldResetValuesEvents.delete(e)),this.queuedFieldResetPropertyEvents.has(e)&&(this.setResetPathValue(Object.assign({key:e},this.queuedFieldResetPropertyEvents.get(e))),this.queuedFieldResetPropertyEvents.delete(e))}}setFieldVisibility({field:e,hasError:t,showOnlyIfTrue:i}){const s=this.fields.get(e);if(s&&s.mounted){const n=s.visibility,r=i?t:!t;if(s.visibility=r,n===r)return;s.visibility?this.queuedInitialValues.has(e)?(null==s||s.emitValue({value:this.queuedInitialValues.get(e)||"",event:"ON_FIELD_MOUNT"}),this.queuedInitialValues.delete(e)):s.emitEvents({event:"ON_FIELD_MOUNT"}):(s.emitEvents({event:"ON_FIELD_UNMOUNT"}),s.persistValue&&this.queuedInitialValues.set(s.name,s.value),s.value="",s.valid=!0)}else this.queuedFieldVisibilityEvents.set(e,{hasError:t,showOnlyIfTrue:i})}validateVisibility({event:e,key:t}){const i=this.fields.get(t),s=null==i?void 0:i.visibilityConditions;s&&(null==s?void 0:s.some(t=>t.events.includes(e)))&&s.forEach(t=>{t.events.includes(e)&&Object.keys(t.validations).forEach(e=>{const s=Oe(i.value,t.validations,se,e,this.formValuesStateSubject$.value);Array.isArray(t.fields)?t.fields.forEach(e=>{this.setFieldVisibility({field:e,hasError:s,showOnlyIfTrue:!(!i.value||!t.showOnlyIfTrue)})}):t.fields&&this.setFieldVisibility({field:t.fields,hasError:s,showOnlyIfTrue:!(!i.value||!t.showOnlyIfTrue)})})})}setResetFieldValue({key:e,value:t}){const i=this.fields.get(e);i&&(null==i?void 0:i.mounted)?i.emitValue({value:t,event:"ON_FIELD_CLEARED"}):this.queuedFieldResetValuesEvents.set(e,{value:t})}resetValue({event:e,key:t}){const i=this.fields.get(t),s=null==i?void 0:i.resetValues;s&&(null==s?void 0:s.some(t=>t.events.includes(e)))&&s.forEach(t=>{if(!t.events.includes(e))return;const s=()=>{Array.isArray(t.fields)?t.fields.forEach((e,i)=>{const s=Array.isArray(t.resettledValue)?t.resettledValue[i]:t.resettledValue;this.setResetFieldValue({key:e,value:s})}):t.fields&&this.setResetFieldValue({key:t.fields,value:t.resettledValue})};if(!t.validations)return s();Object.keys(t.validations).forEach(e=>{Oe(i.value,t.validations,se,e,this.formValuesStateSubject$.value)||s()})})}setResetPathValue({key:e,property:t,path:i,value:s}){this.fields.get(e)?this.setValue({key:e,property:t,path:i.split("."),value:s,event:"ON_RESET"}):this.queuedFieldResetPropertyEvents.set(e,{property:t,path:i,value:s})}resetProperty({event:e,key:t}){const i=this.fields.get(t),s=null==i?void 0:i.resetPropertyValues;s&&(null==s?void 0:s.some(t=>t.events.includes(e)))&&s.forEach(t=>{if(t.events.includes(e)&&$e.includes(t.property))return t.validations?void Object.keys(t.validations).forEach(e=>{Oe(i.value,t.validations,se,e,this.formValuesStateSubject$.value)||this.setResetPathValue({key:t.field,path:t.path,property:t.property,value:t.resettledValue})}):this.setResetPathValue({key:t.field,path:t.path,property:t.property,value:t.resettledValue})})}addField({fieldSchema:e,mapperElement:t,path:i}){var s,n,r,a,l;if(this.fields.has(e.name))throw new Error(`field name ${e.name} already defined`);const o=t||(null===(s=this.mappers)||void 0===s?void 0:s.get(e.component));if(!o)throw new Error(`mapper not found for ${e.component}, add it to the mappers configuration`);if(null===(n=o.events)||void 0===n?void 0:n.setValue){const t=null===(r=null==e?void 0:e.props)||void 0===r?void 0:r[null===(a=null==o?void 0:o.events)||void 0===a?void 0:a.setValue];void 0===t||this.queuedInitialValues.has(e.name)||"string"==typeof t&&t.includes("${")||this.queuedInitialValues.set(e.name,K(t))}if(this.fields.set(e.name,new Ie({formIndex:this.index,schemaComponent:e,mapper:o,children:e.children?e.children.map(e=>e.name):[],validateVisibility:this.validateVisibility.bind(this),resetValue:this.resetValue.bind(this),resetProperty:this.resetProperty.bind(this),formValuesStateSubject$:this.formValuesStateSubject$,templateSubject$:this.templateSubject$,fieldEventSubject$:this.fieldEventSubject$,dataSubject$:this.dataSubject$,fieldValidNotification$:this.fieldValidNotification$,mountSubject$:this.mountSubject$,config:this.config,submitEvent:this.submit.bind(this),visibility:e.visibility,persistValue:e.persistValue,path:i})),null===(l=this.prefetchedData)||void 0===l?void 0:l[e.name]){const t=this.fields.get(e.name);if(t){const i=this.prefetchedData[e.name],s=Object.assign({},t.api);void 0!==i.defaultResponse&&(s.default={response:i.defaultResponse,status:200}),i.namedResponses&&(s.named=s.named||{},Object.keys(i.namedResponses).forEach(e=>{s.named[e]={response:i.namedResponses[e],status:200}})),t._api=s}}}removeField({key:e}){var t;null===(t=this.fields.get(e))||void 0===t||t.destroyField(),this.fields.delete(e),this.subscribeTemplates(),this.templateSubject$.next({scope:"fields",key:e,event:"ON_FIELDS"}),this.validateForm()}serializeStructure(e,t){e&&e.forEach(e=>{var i;const s=this.fields.get(e.name);s?(s.children=(null===(i=null==e?void 0:e.children)||void 0===i?void 0:i.map(e=>e.name))||(null==s?void 0:s.children)||[],s.originalSchema=e,s.templateSubject$=this.templateSubject$):this.addField({fieldSchema:e,mapperElement:e.mapper,path:t}),e.children&&this.serializeStructure(e.children,`${t?`${t}.`:""}${e.name}`)})}refreshFields(e){const t=Array.from(this.fields.keys());this.serializeStructure(e);const i=Fe.checkIndexes(e);this.fields.forEach((e,t)=>{var s;i.includes(t)||(null===(s=this.fields.get(t))||void 0===s||s.destroyField(),this.fields.delete(t))}),this.subscribeTemplates(),this.fields.forEach((e,i)=>{var s;t.includes(i)||(null===(s=this.fields.get(i))||void 0===s||s.emitEvents({event:"ON_FIELD_MOUNT"}),this.checkFieldEventQueues(i))}),this.subscribedTemplates.forEach(e=>{e.originFieldKeys.forEach(e=>{this.templateSubject$.next({scope:"fields",key:e,event:"ON_FIELDS"})})})}getField({key:e}){return this.fields.get(e)}printValues(){console.table(this.formValuesStateSubject$.value.values)}getFormState(){const e={},t={},i=[];return this.fields.forEach((s,n)=>{"string"==typeof s.value&&0===s.value.length||null==s.value||(W(e,s.nameToSubmit||n,s.value),t[n]=s.metadata),s.valid||i.push(n)}),{values:e,metadata:t,erroredFields:i,isValid:this.valid}}subscribeFieldEvent({callback:e}){return this.fieldEventSubject$.pipe(o(()=>this.submitChecker()),r(e=>`${e.event}|${e.fieldName}`),a(e=>e.pipe(l(this.config.defaultStateRefreshTimeMS)))).subscribe({next:e})}subscribeOnMount(e){return this.mountSubject$.pipe(c(()=>this.formValuesStateSubject$.value)).subscribe({next:e})}subscribeData(e){return this.dataSubject$.pipe(o(({formIndex:e})=>this.index===e&&this.submitChecker()),r(e=>e.event),a(e=>e.pipe(l(this.config.defaultStateRefreshTimeMS))),c(({fieldIndex:e})=>({field:e,data:this.formValuesStateSubject$.value}))).subscribe({next:e})}subscribeOnSubmit(e){return this.submitSubject$.pipe(o(({formIndex:e})=>e===this.index&&this.submitChecker()),c(({values:e})=>e)).subscribe({next:e})}subscribeFormValidation(e){return this.formValidSubject$.pipe(o(({formIndex:e})=>this.index===e),c(()=>({formIndex:this.index,valid:this.valid})),h("valid"),d({formIndex:this.index,valid:this.valid})).subscribe({next:e})}submit(){this.fields.forEach(e=>{e.emitEvents({event:"ON_FIELD_VALIDATION"})}),this.valid&&(this.submitSubject$.next({formIndex:this.index,values:this.formValuesStateSubject$.value}),this.submitted=!0)}destroy(){this.templateSubject$.unsubscribe(),this.templateSubscription$.unsubscribe(),this.mountSubject$.unsubscribe(),this.fieldEventSubject$.unsubscribe(),this.fieldValidNotification$.unsubscribe(),this.formValuesStateSubject$.unsubscribe(),this.isolatedFormInstance&&(this.submitSubject$.unsubscribe(),this.dataSubject$.unsubscribe(),this.formValidSubject$.unsubscribe()),this.fields.forEach(e=>e.destroyField())}}Fe.checkIndexes=(e,t=[])=>{if(!e)return t;const i=(e,t)=>{for(let s=0;s<e.length;s++){const n=e[s];t.push(n.name),n.children&&i(n.children,t)}};i(e,t);const s=t.filter((e,i)=>t.indexOf(e)!==i);if(s.length>0)throw new Error(`duplicated indexes found on schema: ${JSON.stringify(s)}`);return t};class ke{constructor(e){var t,i,n,r,a;this.destroy=()=>{this.forms.forEach(e=>e.destroy()),this.dataSubject$.unsubscribe(),this.formValidSubject$.unsubscribe(),this.submitSubject$.unsubscribe()},this.forms=new Map,this.config={defaultAPIdebounceTimeMS:Number(null===(t=null==e?void 0:e.config)||void 0===t?void 0:t.defaultAPIdebounceTimeMS)?Number(null===(i=null==e?void 0:e.config)||void 0===i?void 0:i.defaultAPIdebounceTimeMS):pe,defaultStateRefreshTimeMS:Number(null===(n=null==e?void 0:e.config)||void 0===n?void 0:n.defaultStateRefreshTimeMS)?Number(null===(r=null==e?void 0:e.config)||void 0===r?void 0:r.defaultStateRefreshTimeMS):100,defaultLogVerbose:(null===(a=null==e?void 0:e.config)||void 0===a?void 0:a.defaultLogVerbose)?e.config.defaultLogVerbose:Ve},this.dataSubject$=new s,this.formValidSubject$=new s,this.submitSubject$=new s,this.mappers=null==e?void 0:e.mappers}createFormWithIndex({index:e,mappers:t}){this.addForm({key:e,params:{index:e,mappers:t,config:this.config}})}addForm({key:e,params:t}){this.checkIndexes({key:e});const i=new Fe(Object.assign(Object.assign({},t),{dataSubject$:this.dataSubject$,formValidSubject$:this.formValidSubject$,submitSubject$:this.submitSubject$}));i.config||(i.config=this.config),this.forms.set(e,i)}getForm({key:e}){return this.forms.get(e)}removeForm({key:e}){var t;null===(t=this.forms.get(e))||void 0===t||t.destroy(),this.forms.delete(e)}removeField({formIndex:e,fieldIndex:t}){const i=this.forms.get(e);null==i||i.removeField({key:t}),0===(null==i?void 0:i.fields.size)&&this.removeForm({key:e})}checkIndexes({key:e}){if(this.forms.has(e))throw new Error(`duplicate index ${e} on form group`)}printFormGroupInstance(){console.table(this.forms)}submitMultipleFormsByIndex(e,t){let i=!0,s={},n={},r=[];e.forEach(e=>{var t,a;null===(t=this.forms.get(e))||void 0===t||t.submit();const l=null===(a=this.forms.get(e))||void 0===a?void 0:a.formValuesStateSubject$.value,o="object"==typeof(null==l?void 0:l.metadata)&&null!==l.metadata?l.metadata:{};i=i&&((null==l?void 0:l.isValid)||!1),s=Object.assign(Object.assign({},s),(null==l?void 0:l.values)||{}),n=Object.assign(Object.assign({},n),o),r=[...r,...(null==l?void 0:l.erroredFields)||[]]}),i&&t&&t({erroredFields:r,isValid:i,values:s,metadata:n})}onDataSubscription({ids:e,callback:t}){return this.dataSubject$.pipe(o(({formIndex:t})=>e.includes(t)),r(({event:e,formIndex:t})=>`${e}.${t}`),a(e=>e.pipe(l(this.config.defaultStateRefreshTimeMS))),c(({fieldIndex:t,formIndex:i})=>e.reduce((e,s)=>{const n=this.forms.get(s);return n&&(e[s]={formId:i,formField:t,values:n.formValuesStateSubject$.value}),e},{}))).subscribe(t)}onValidSubscription({ids:e,callback:t}){return this.formValidSubject$.pipe(o(({formIndex:t})=>e.includes(t)),r(({formIndex:e})=>e),a(e=>e.pipe(l(0))),d({fieldTrigger:null}),c(()=>({groupValid:e.every(e=>{var t;return!this.forms.get(e)||(null===(t=this.forms.get(e))||void 0===t?void 0:t.valid)}),forms:e.reduce((e,t)=>{const i=this.forms.get(t);return i&&(e[t]=i.valid),e},{})}))).subscribe(t)}onSubmitSubscription({ids:e,callback:t}){return this.submitSubject$.pipe(o(({formIndex:t})=>e.includes(t)),c(()=>e.reduce((e,t)=>{const i=this.forms.get(t);return i&&(e[t]=i.formValuesStateSubject$.value),e},{}))).subscribe(t)}}export{Fe as FormCore,Ie as FormField,ke as FormGroup,ve as TMutationEnum,ne as formatterRegistry,re as maskRegistry,le as registerFormatters,oe as registerMasks,ae as registerValidations,se as validationRegistry};
|
package/lite.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BehaviorSubject as e,Subject as t,Subscription as i,groupBy as s,mergeMap as a,debounceTime as n,filter as r,combineLatest as l,startWith as o,map as u,distinctUntilKeyChanged as d}from"rxjs";var h;function c(e,t,i,s){return new(i||(i=Promise))(function(a,n){function r(e){try{o(s.next(e))}catch(e){n(e)}}function l(e){try{o(s.throw(e))}catch(e){n(e)}}function o(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(r,l)}o((s=s.apply(e,t||[])).next())})}!function(e){e.ON_VALUE="value",e.ON_PROPS="props",e.ON_VISIBILITY="visibility",e.ON_API="api",e.ON_IVARS="iVars",e.ON_FIELDS="fields"}(h||(h={})),"function"==typeof SuppressedError&&SuppressedError;const v=1e3,f=/^\$\{(?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*\}$/,p=/\$\{((?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*)\}/g,m=/\s*(\|\||&&|!+)\s*/g,b=/^\|\||&&|!+$/,S=["fields","iVars","form"],y=["api","apiSchema","props","validations","visibilityConditions","resetValues"],g=!1;function V(e){const t=p,i=[];let s;for(;null!==(s=t.exec(e));)i.push(s[1]);const a=m,n=i.map(e=>e.split(a).filter(e=>!a.test(e))).flat().filter(e=>e.split(".").length>1);return{originScopeKeys:Array.from(new Set(n.map(e=>e.split(".")[0]))),originFieldKeys:Array.from(new Set(n.map(e=>e.split(".")[1]))),originPropertyKeys:Array.from(new Set(n.map(e=>e.split(".")[2])))}}function $(e,t){const i=[];if(Array.isArray(e))e.forEach((e,s)=>{i.push(...$(e,`${t?`${t}.`:""}${s}`))});else if("object"==typeof e)for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&i.push(...$(e[s],`${t?`${t}.`:""}${s}`));else if("string"==typeof e&&e.includes("${")){const s=(t||"").split(".");V(e).originScopeKeys.every(e=>S.includes(e))?i.push(Object.assign(Object.assign({originExpression:e},V(e)),{destinationKey:s[0],destinationProperty:s[1],destinationPath:s.slice(2)})):console.warn(`scope malformed on this expression: ${e}, ignoring..`)}return i}const j={},E={},O={};function I(e){Object.assign(j,e)}function x(e){Object.assign(E,e)}function _(e){Object.assign(O,e)}function k(e){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e))return e.map(e=>k(e));const t={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=k(e[i]));return t}function F(e,t,i){if(null==e)return i;const s=Array.isArray(t)?t:t.split(".");let a=e;for(let e=0;e<s.length;e++){if(null==a)return i;a=a[s[e]]}return void 0===a?i:a}function N(e,t,i){if(null==e||"object"!=typeof e)return e;const s=Array.isArray(t)?t:t.split(".");let a=e;for(let e=0;e<s.length-1;e++){const t=s[e],i=s[e+1];null!=a[t]&&"object"==typeof a[t]||(a[t]="number"==typeof i||/^\d+$/.test(String(i))?[]:{}),a=a[t]}return a[s[s.length-1]]=i,e}function P(e,t){if(e===t)return!0;if(null==e||null==t)return e===t;if(typeof e!=typeof t)return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if("object"!=typeof e)return!1;const i=Array.isArray(e);if(i!==Array.isArray(t))return!1;if(i){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!P(e[i],t[i]))return!1;return!0}const s=Object.keys(e),a=Object.keys(t);if(s.length!==a.length)return!1;for(const i of s){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!P(e[i],t[i]))return!1}return!0}function w(e){return null==e}class T extends t{constructor(e){super(),this.isMounted=e}next(e){this.isMounted()&&super.next(e)}}class A extends e{constructor(e){super(e),this.defaultValue=e}next(e){this.closed||super.next(e)}get value(){return this.closed?this.defaultValue:super.value}}function R(e,t,i,s,a){return function(e){return"function"==typeof e}(i[s])?i[s](e,t,a):((e,t,i)=>!!t&&function(e,t,i){const s=[];return Object.keys(t).forEach(a=>{s.push(i[a](e,{[a]:t[a]}))}),s}(e,t,i).some(e=>e))(e,t[s],i)}class M{constructor({formIndex:e,schemaComponent:t,config:s,children:a,validateVisibility:n,resetValue:r,resetProperty:l,templateSubject$:o,fieldEventSubject$:u,dataSubject$:d,fieldValidNotification$:h,mountSubject$:c,mapper:f,formValuesStateSubject$:p,submitEvent:m,visibility:b,persistValue:S}){var y,V,$,j,E,O;this.valueSubscription$=new i,this.fieldStateSubscription$=new i,this.formIndex=e,this.originalSchema=k(t),this.config={defaultAPIdebounceTimeMS:Number(null==s?void 0:s.defaultAPIdebounceTimeMS)?Number(null==s?void 0:s.defaultAPIdebounceTimeMS):v,defaultStateRefreshTimeMS:Number(null==s?void 0:s.defaultStateRefreshTimeMS)?Number(null==s?void 0:s.defaultStateRefreshTimeMS):100,defaultLogVerbose:(null==s?void 0:s.defaultLogVerbose)?s.defaultLogVerbose:g},this.name=t.name,this.nameToSubmit=t.nameToSubmit,this.component=t.component,this.children=a,this.validations=k(t.validations),this.visibilityConditions=k(t.visibilityConditions),this.resetValues=k(t.resetValues),this.resetPropertyValues=k(t.resetPropertyValues),this.apiSchema=k(t.api),this.formatters=k(t.formatters),this.masks=k(t.masks),f.valueChangeEvent&&(this.valueChangeEvent=f.valueChangeEvent),(null===(y=f.events)||void 0===y?void 0:y.setValue)&&(this.valuePropName=f.events.setValue),this.mapper=f,this.validateVisibility=n,this.resetValue=r,this.resetProperty=l,this.submitEvent=m,this.templateSubject$=o,this.fieldEventSubject$=u,this.dataSubject$=d,this.fieldValidNotification$=h,this.mountSubject$=c,this.formValuesStateSubject$=p,this.getFormValues=()=>this.formValuesStateSubject$.value,this._props=M.filterProps(k(t.props||{})),this._adapterProps=JSON.stringify(t.props||{}),this._metadata="",this.errorsString="",this.errorsList=[],this._visibility="boolean"!=typeof b||b,this._api={default:{response:(null===(j=null===($=null===(V=this.apiSchema)||void 0===V?void 0:V.defaultConfig)||void 0===$?void 0:$.config)||void 0===j?void 0:j.fallbackValue)||"",status:null},named:(null===(E=this.apiSchema)||void 0===E?void 0:E.configs)&&Object.keys(null===(O=this.apiSchema)||void 0===O?void 0:O.configs).reduce((e,t)=>{var i,s;return e[t]={response:(null===(s=null===(i=this.apiSchema)||void 0===i?void 0:i.configs)||void 0===s?void 0:s[t].config.fallbackValue)||"",status:null},e},{}),apiState:{loading:!1}},this._errors={},this._mounted=!1,this.valid=!0,this.persistValue=S,this.initializeObservers()}initializeObservers(){this.valueSubject$&&!this.valueSubject$.closed||(this.valueSubject$=new T(()=>this.mounted)),this.errorSubject$&&!this.errorSubject$.closed||(this.errorSubject$=new T(()=>this.mounted)),this.visibilitySubject$&&!this.visibilitySubject$.closed||(this.visibilitySubject$=new T(()=>this.mounted)),this.propsSubject$&&!this.propsSubject$.closed||(this.propsSubject$=new T(()=>this.mounted)),this.fieldStateSubscription$&&!this.fieldStateSubscription$.closed||(this.fieldStateSubscription$=new i),this.apiEventQueueSubject$&&!this.apiEventQueueSubject$.closed||(this.apiEventQueueSubject$=new T(()=>this.mounted)),this.apiEventQueueSubject$.observed||this.apiEventQueueSubject$.pipe(s(({event:e})=>e),a(e=>e.pipe(n(this.config.defaultAPIdebounceTimeMS))),r(()=>this.apiEventQueueSubject$&&!this.apiEventQueueSubject$.closed)).subscribe(e=>{this.apiRequest(e)})}get adapterProps(){return this._adapterProps}set adapterProps(e){const t=JSON.stringify(e||{});t!==this.adapterProps&&(this.props=M.filterProps(e),this._adapterProps=t)}get props(){return this._props}set props(e){void 0===e||P(e,this.props)||(this._props=e,this.propsSubject$.next(this.props),this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_PROPS"}))}static filterProps(e){return Array.isArray(e)?e.filter(e=>"string"!=typeof e||!e.includes("${")).map(e=>M.filterProps(e)):"object"==typeof e&&null!==e?e instanceof Date?e:Object.keys(e).reduce((t,i)=>{const s=e[i];return"string"==typeof s&&s.includes("${")||(t[i]=M.filterProps(e[i])),t},{}):e}get stateValue(){return this._stateValue}get metadata(){return this._metadata}get value(){return this._value}set value(e){var t,i,s;let a;if(this.valueChangeEvent)try{a=this.valueChangeEvent(e,{props:this.props})}catch(t){a=e}else a=e;null!=a&&("object"==typeof a&&"_value"in a&&"_metadata"in a?(this._value=this.formatValue(a._value),this._stateValue=(null===(t=this.mapper.events)||void 0===t?void 0:t.setValue)?{[this.mapper.events.setValue]:this.maskValue(this.formatValue(a._value))}:{},this._metadata=a._metadata):(this._value=this.formatValue(a),this._stateValue=(null===(i=this.mapper.events)||void 0===i?void 0:i.setValue)?{[null===(s=this.mapper.events)||void 0===s?void 0:s.setValue]:this.maskValue(this.formatValue(a))}:{},this.maskValue(this.formatValue(a)),this._metadata=a),this.stateValue&&this.valueSubject$.next(this.stateValue),this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_VALUE"}))}get visibility(){return this._visibility}set visibility(e){void 0!==e&&e!==this.visibility&&(this._visibility=e,this.visibilitySubject$.next(this.visibility),this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_VISIBILITY"}))}set valid(e){"boolean"!=typeof e&&this.valid===e||(this._valid=e,this.triggerFieldValidNotification())}get valid(){return this._valid}triggerFieldValidNotification(){this.fieldValidNotification$.closed||this.fieldValidNotification$.next({fieldTrigger:this.name})}get errors(){return this._errors}set errors(e){var t;void 0===e||P(e,this.errors)||(this._errors=e,this.errorsList=Object.values(this.errors).filter(e=>null!=e),this.errorsString=this.errorsList.join(", "),(null===(t=this.mapper.events)||void 0===t?void 0:t.setErrorMessage)&&this.errorSubject$.next({[this.mapper.events.setErrorMessage]:this.errorsString}),this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_PROPS"}))}get api(){return this._api}set api(e){void 0!==e&&(this._api=e,this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_API_RESPONSE"}),this.emitEvents({event:"ON_API_FIELD_RESPONSE"}))}notifyApiRequest(){this._api.apiState.loading=!0,this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_API_REQUEST"}),this.emitEvents({event:"ON_API_FIELD_REQUEST"})}get mounted(){return this._mounted}set mounted(e){void 0!==e&&e!==this.mounted&&(this._mounted=e,this.initializeObservers(),this.mountSubject$.closed||this.mountSubject$.next({key:this.name,status:this.mounted}))}mountField({valueSubscription:e,propsSubscription:t}){this.mounted=!0,this.subscribeValue(e),this.subscribeState(t),this.valueSubject$.next(this.stateValue),this.propsSubject$.next(this.props),this.visibilitySubject$.next(this.visibility),this.fieldEventSubject$.next({event:"ON_FIELD_MOUNT",fieldName:this.name,fieldInstance:this})}emitValue(e){this.visibility&&this.mounted&&(this.value=e.value,this.dataSubject$.next({event:e.event,fieldIndex:this.name,formIndex:this.formIndex}),this.emitEvents({event:e.event}))}emitEvents({event:e}){if("ON_FORM_SUBMIT"===e)return this.submitEvent();this.validateVisibility({event:e,key:this.name}),this.setFieldValidity({event:e}),this.resetValue({event:e,key:this.name}),this.resetProperty({event:e,key:this.name}),this.apiEventQueueSubject$.next({event:e}),this.fieldEventSubject$.next({event:e,fieldName:this.name,fieldInstance:this})}setFieldValidity({event:e}){var t,i,s,a;if(!this.validations||!this.visibility)return this.errors={},void(this.valid=!0);let n=!0;const r={},l=null===(t=this.validations)||void 0===t?void 0:t.methods;if(l&&Object.keys(l).forEach(e=>{var t,i;const s=R(this.value,l,j,e,null===(t=this.formValuesStateSubject$)||void 0===t?void 0:t.value);n=!s&&n,s&&(null===(i=this.validations)||void 0===i?void 0:i.messages)?e in this.validations.messages?r[e]=this.validations.messages[e]:"default"in this.validations.messages&&(r[e]=this.validations.messages.default):delete r[e]}),this.valid=n,null===(s=null===(i=this.validations)||void 0===i?void 0:i.eventMessages)||void 0===s?void 0:s[e]){const t={};null===(a=this.validations.eventMessages[e])||void 0===a||a.forEach(e=>{e in r&&(t[e]=r[e])}),this.errors=t}else"ON_FIELD_VALIDATION"===e&&(this.errors=r)}formatValue(e){return this.formatters?Object.keys(this.formatters).reduce((e,t)=>{const i=E[t];return i?i(e,this.formatters):e},e):e}maskValue(e){return this.masks?Object.keys(this.masks).reduce((e,t)=>{const i=O[t];return i?i(e,this.masks):e},e):e}checkApiRequestValidations(e){let t=!0;const i=e.preConditions;return i&&Object.keys(i).forEach(e=>{var s;const a=R(this.value,i,j,e,null===(s=this.formValuesStateSubject$)||void 0===s?void 0:s.value);t=t&&!a}),e.blockRequestWhenInvalid&&(t=t&&this.valid),t}apiRequest(e){return c(this,arguments,void 0,function*({event:e}){var t,i,s,a,n,r,l,o,u;let d=!1;const h=e=>c(this,void 0,void 0,function*(){var t,i;try{const{status:s,response:a}=yield function(e,t,i,s,a){return c(this,void 0,void 0,function*(){if(a){const[e,i]=t.split("?"),s=new URLSearchParams(i);Object.keys(a).forEach(e=>{s.append(e,a[e])}),t=`${e}?${s.toString()}`}const n=yield fetch(t,{method:e,headers:i,body:s?JSON.stringify(s):void 0}),r=yield n.text();return{status:n.status,response:r}})}(e.method,e.url,e.headers,e.body,e.queryParams),n=null===(t=e.transform)||void 0===t?void 0:t.callback,r=n?n({payload:JSON.parse(String(a)),formValues:null===(i=this.formValuesStateSubject$)||void 0===i?void 0:i.value}):JSON.parse(String(a));return{response:e.resultPath?F(r,e.resultPath):r,status:s}}catch(t){return{response:w(null==e?void 0:e.fallbackValue)?"error":e.fallbackValue,status:500}}});if("ON_API_FIELD_RESPONSE"===this.api.apiState.lastEvent&&"ON_API_FIELD_RESPONSE"===e||!(null===(i=null===(t=this.apiSchema)||void 0===t?void 0:t.defaultConfig)||void 0===i?void 0:i.events.includes(e))&&(!(null===(s=this.apiSchema)||void 0===s?void 0:s.configs)||!Object.keys(null===(a=this.apiSchema)||void 0===a?void 0:a.configs).some(t=>{var i,s;return null===(s=null===(i=this.apiSchema)||void 0===i?void 0:i.configs)||void 0===s?void 0:s[t].events.includes(e)})))return;const v={default:Object.assign({},this.api.default),named:Object.assign({},this.api.named),apiState:Object.assign({},this.api.apiState)},f=null===(n=this.apiSchema.defaultConfig)||void 0===n?void 0:n.config;if(f&&(null===(l=null===(r=this.apiSchema)||void 0===r?void 0:r.defaultConfig)||void 0===l?void 0:l.events.includes(e))&&this.checkApiRequestValidations(f)){d||this.notifyApiRequest();const{response:e,status:t}=yield h(f);d=!0,v.default={response:e,status:t}}if((null===(o=this.apiSchema)||void 0===o?void 0:o.configs)&&Object.keys(null===(u=this.apiSchema)||void 0===u?void 0:u.configs).some(t=>{var i,s;return null===(s=null===(i=this.apiSchema)||void 0===i?void 0:i.configs)||void 0===s?void 0:s[t].events.includes(e)})&&this.apiSchema.configs){const t=yield Promise.all(Object.keys(this.apiSchema.configs).map(t=>c(this,void 0,void 0,function*(){var i,s,a,n;const r=null===(s=null===(i=this.apiSchema)||void 0===i?void 0:i.configs)||void 0===s?void 0:s[t].config;if(r&&(null===(n=null===(a=this.apiSchema)||void 0===a?void 0:a.configs)||void 0===n?void 0:n[t].events.includes(e))&&this.checkApiRequestValidations(r)){d||this.notifyApiRequest();const{response:e,status:i}=yield h(r);return d=!0,{name:t,result:{response:e,status:i}}}return null})));t.forEach(e=>{e&&v.named&&(v.named[e.name]=e.result)})}d&&(v.apiState.lastEvent=e,v.apiState.loading=!1,this.api=v)})}destroyField(){this.mounted=!1,this.valueSubscription$.unsubscribe(),this.visibilitySubject$.unsubscribe(),this.fieldStateSubscription$.unsubscribe(),this.propsSubject$.unsubscribe(),this.errorSubject$.unsubscribe(),this.apiEventQueueSubject$.unsubscribe(),this.dataSubject$.closed||this.dataSubject$.next({event:"ON_FIELD_UNMOUNT",fieldIndex:this.name,formIndex:this.formIndex}),this.fieldEventSubject$.closed||this.fieldEventSubject$.next({event:"ON_FIELD_UNMOUNT",fieldName:this.name,fieldInstance:this})}subscribeState(e){var t;this.fieldStateSubscription$=l({visibility:this.visibilitySubject$.pipe(o(this.visibility)),props:this.propsSubject$.pipe(o(this.props)),errors:this.errorSubject$.pipe(o(Object.assign({},(null===(t=this.mapper.events)||void 0===t?void 0:t.setErrorMessage)&&{[this.mapper.events.setErrorMessage]:this.errorsString})))}).pipe(n(this.config.defaultStateRefreshTimeMS)).subscribe({next:e})}subscribeValue(e){this.valueSubscription$=this.valueSubject$.subscribe({next:e})}}class L{constructor(e){var s,a,n,r,l,o,u,d,h,c,f;this.templateSubscription$=new i,this.mappers=new Map,this.queuedFieldVisibilityEvents=new Map,this.queuedFieldResetValuesEvents=new Map,this.queuedFieldResetPropertyEvents=new Map,this.queuedInitialValues=new Map,this._valid=!1,this.stopEventsOnSubmit=!1,this.submitted=!1,this.isolatedFormInstance=!1,this.index=e.index,this.schema=e.schema,this.fields=new Map,this.action=e.action||(null===(s=e.schema)||void 0===s?void 0:s.action),this.method=e.method||(null===(a=e.schema)||void 0===a?void 0:a.method),this.config={defaultAPIdebounceTimeMS:Number(null===(n=e.config)||void 0===n?void 0:n.defaultAPIdebounceTimeMS)?Number(null===(r=e.config)||void 0===r?void 0:r.defaultAPIdebounceTimeMS):v,defaultStateRefreshTimeMS:Number(null===(l=e.config)||void 0===l?void 0:l.defaultStateRefreshTimeMS)?Number(null===(o=e.config)||void 0===o?void 0:o.defaultStateRefreshTimeMS):100,defaultLogVerbose:(null===(u=e.config)||void 0===u?void 0:u.defaultLogVerbose)?e.config.defaultLogVerbose:g},null===(d=e.mappers)||void 0===d||d.map(e=>{this.mappers.set(e.componentName,e)}),e.submitSubject$&&e.dataSubject$&&e.formValidSubject$||(this.isolatedFormInstance=!0,this.config.defaultLogVerbose&&console.warn(`some formGroup events are not properly instanciated, any onData, onValid, onSubmit events managed by formGroup won't trigger on form: ${this.index}`)),this.schema&&L.checkIndexes(this.schema.components),this.templateSubject$=new t,this.fieldEventSubject$=new t,this.mountSubject$=new t,this.fieldValidNotification$=new t,this.submitSubject$=e.submitSubject$?e.submitSubject$:new t,this.dataSubject$=e.dataSubject$?e.dataSubject$:new t,this.formValidSubject$=e.formValidSubject$?e.formValidSubject$:new t,this.formValuesStateSubject$=new A({erroredFields:[],isValid:!0,metadata:[],values:[]}),this.getFormValues=()=>this.formValuesStateSubject$.value,this.subscribedTemplates=[],this.templateSubscription$=this.templateSubject$.subscribe(this.refreshTemplates.bind(this)),this.fieldValidNotification$.subscribe(()=>{this.validateForm()}),this.fieldEventSubject$.subscribe(()=>{this.formValuesStateSubject$.next(this.getFormState())}),this.dataSubject$.subscribe(()=>{this.formValuesStateSubject$.next(this.getFormState())}),this.mountSubject$.subscribe(this.mountActions.bind(this)),this.prefetchedData=null===(h=e.schema)||void 0===h?void 0:h.prefetchedData,this.initialValues=e.initialValues||(null===(c=e.schema)||void 0===c?void 0:c.initialValues),this.iVars=e.iVars||(null===(f=e.schema)||void 0===f?void 0:f.iVars)||{},this.stopEventsOnSubmit=(null==e?void 0:e.stopEventsOnSubmit)||!1,this.submitted=!1}generateFields(){this.schema&&this.serializeStructure(this.schema.components),this.fields.forEach(e=>{e.mountField({valueSubscription:()=>null,propsSubscription:()=>null})})}submitChecker(){return!(this.stopEventsOnSubmit&&this.submitted)}mountActions({key:e,status:t}){if(t){const t=this.fields.get(e);if(!t)return void(this.config.defaultLogVerbose&&console.warn(`field ${e} was mounted but since it's parent has some visibility condition the field was already removed`));this.subscribeTemplates(),this.refreshTemplates({scope:"fields",event:"ON_FIELDS"}),this.templateSubject$.next({scope:"iVars",event:"ON_IVARS"}),this.queuedInitialValues.has(e)||(t.valuePropName&&!t.value?t.emitValue({event:"ON_FIELD_MOUNT",value:""}):t.emitEvents({event:"ON_FIELD_MOUNT"})),this.checkFieldEventQueues(e)}}set initialValues(e){e&&Object.keys(e).forEach(t=>{const i=this.fields.get(t);i&&(null==i?void 0:i.visibility)&&(null==i?void 0:i.mounted)?i.emitValue({value:null==e?void 0:e[t],event:"ON_FIELD_MOUNT"}):this.queuedInitialValues.set(t,null==e?void 0:e[t])})}get iVars(){return this._iVars}set iVars(e){this._iVars=e,this.templateSubject$.next({scope:"iVars",event:"ON_IVARS"})}validateForm(){if(0===this.fields.size)return this.valid=!1;for(const[,e]of this.fields)if(!e.valid)return this.valid=!1;return this.valid=!0}get valid(){return this._valid}set valid(e){this._valid!==e&&(this._valid=e,this.templateSubject$.next({event:"ON_FORM",scope:"form"}),this.formValidSubject$.next({formIndex:this.index,valid:this.valid}))}subscribeTemplates(){this.subscribedTemplates=[],this.fields.forEach(({originalSchema:{component:e,props:t,name:i,validations:s,visibilityConditions:a,resetValues:n,resetPropertyValues:r,api:l}},o)=>{$({component:e,props:t,name:i,validations:s,visibilityConditions:a,resetValues:n,resetPropertyValues:r,apiSchema:l},o).forEach(e=>this.subscribedTemplates.push(e))})}getValue({scope:e,key:t,property:i,path:s}){switch(e){case"iVars":return F(this.iVars,[t,...i?[i]:[],...s]);case"form":return F(this,[t,...i?[i]:[],...s]);case"fields":{const e=this.fields.get(t);return e?"props"===i&&s[0]===e.valuePropName?e.value:s.length>0?F(e[i],s):e[i]:this.config.defaultLogVerbose&&console.warn(`failed to get value from ${t}`)}}}setValue({key:e,property:t,path:i,originKey:s,value:a}){const n=this.fields.get(e);if(n){if(i.length>0){if("props"===t&&i[0]===n.valuePropName&&e!==s)return void n.emitValue({event:"ON_FIELD_CHANGE",value:a});const r=n[t];let l;return Array.isArray(r)||"object"==typeof r&&!w(r)?(l=k(r),N(l,i,a),void(n[t]=l)):void(this.config.defaultLogVerbose&&console.warn(`invalid template property, skipping evaluation of ${n.name} with ${r}`))}n[t]=a}else this.config.defaultLogVerbose&&console.warn(`failed to update field ${e}`)}extractParams(e){const t=function(e){const t=e.split(".");return t.length>1?this.getValue({scope:t[0],key:t[1],property:t[2],path:t.slice(3)}):t[0]}.bind(this),i=[];let s;for(;!w(s=p.exec(e));)i.push(s[1]);return i.map(e=>e.split(m)).map(e=>e.length<=1?{parse:!1,value:t(e[0])}:{parse:!0,value:e.filter(Boolean).reduce((e,i)=>{if(i.match(b))return`${e}${i}`;let s;const a=t(i);let n;try{n=JSON.parse(a)}catch(e){n=a}switch(typeof n){case"string":s=`\`${n}\``;break;case"boolean":case"undefined":case"number":default:s=n;break;case"object":if(null===n){s=null;break}if(n instanceof Date){s=`new Date(\`${n}\`)`;break}s=JSON.stringify(n)}return`${e}${s}`},"")}).map(({parse:t,value:i})=>{try{return t?new Function(`return ${i}`)():i}catch(t){return this.config.defaultLogVerbose&&(console.warn(`unhandled parsing on ${e} returning`),console.warn(i)),i}})}replaceExpression(e,t){return e.replace(p,()=>String(t.shift())||"")}hasStringConcatenation(e){return!f.test(e)}refreshTemplates({key:e,event:t}){this.subscribedTemplates.forEach(({destinationKey:i,destinationPath:s,destinationProperty:a,originExpression:n,originFieldKeys:r})=>{if(!e||r.includes(e)){const r=this.extractParams(n);let l;l=this.hasStringConcatenation(n)?this.replaceExpression(n,[...r]):null==r?void 0:r[0],P(this.getValue({scope:"fields",key:i,property:a,path:s}),l)||this.setValue({key:i,property:a,path:s,originKey:e,value:l,event:t})}})}checkFieldEventQueues(e){var t;if(null===(t=this.fields.get(e))||void 0===t?void 0:t.mounted){if(this.queuedFieldVisibilityEvents.has(e)&&(this.setFieldVisibility(Object.assign({field:e},this.queuedFieldVisibilityEvents.get(e))),this.queuedFieldVisibilityEvents.delete(e)),this.queuedInitialValues.has(e)){const t=this.queuedInitialValues.get(e);this.queuedInitialValues.delete(e),this.initialValues={[e]:t}}this.queuedFieldResetValuesEvents.has(e)&&(this.setResetFieldValue(Object.assign({key:e},this.queuedFieldResetValuesEvents.get(e))),this.queuedFieldResetValuesEvents.delete(e)),this.queuedFieldResetPropertyEvents.has(e)&&(this.setResetPathValue(Object.assign({key:e},this.queuedFieldResetPropertyEvents.get(e))),this.queuedFieldResetPropertyEvents.delete(e))}}setFieldVisibility({field:e,hasError:t,showOnlyIfTrue:i}){const s=this.fields.get(e);if(s&&s.mounted){const a=s.visibility,n=i?t:!t;if(s.visibility=n,a===n)return;s.visibility?this.queuedInitialValues.has(e)?(null==s||s.emitValue({value:this.queuedInitialValues.get(e)||"",event:"ON_FIELD_MOUNT"}),this.queuedInitialValues.delete(e)):s.emitEvents({event:"ON_FIELD_MOUNT"}):(s.emitEvents({event:"ON_FIELD_UNMOUNT"}),s.persistValue&&this.queuedInitialValues.set(s.name,s.value),s.value="",s.valid=!0)}else this.queuedFieldVisibilityEvents.set(e,{hasError:t,showOnlyIfTrue:i})}validateVisibility({event:e,key:t}){const i=this.fields.get(t),s=null==i?void 0:i.visibilityConditions;s&&(null==s?void 0:s.some(t=>t.events.includes(e)))&&s.forEach(t=>{t.events.includes(e)&&Object.keys(t.validations).forEach(e=>{const s=R(i.value,t.validations,j,e,this.formValuesStateSubject$.value);Array.isArray(t.fields)?t.fields.forEach(e=>{this.setFieldVisibility({field:e,hasError:s,showOnlyIfTrue:!(!i.value||!t.showOnlyIfTrue)})}):t.fields&&this.setFieldVisibility({field:t.fields,hasError:s,showOnlyIfTrue:!(!i.value||!t.showOnlyIfTrue)})})})}setResetFieldValue({key:e,value:t}){const i=this.fields.get(e);i&&(null==i?void 0:i.mounted)?i.emitValue({value:t,event:"ON_FIELD_CLEARED"}):this.queuedFieldResetValuesEvents.set(e,{value:t})}resetValue({event:e,key:t}){const i=this.fields.get(t),s=null==i?void 0:i.resetValues;s&&(null==s?void 0:s.some(t=>t.events.includes(e)))&&s.forEach(t=>{if(!t.events.includes(e))return;const s=()=>{Array.isArray(t.fields)?t.fields.forEach((e,i)=>{const s=Array.isArray(t.resettledValue)?t.resettledValue[i]:t.resettledValue;this.setResetFieldValue({key:e,value:s})}):t.fields&&this.setResetFieldValue({key:t.fields,value:t.resettledValue})};if(!t.validations)return s();Object.keys(t.validations).forEach(e=>{R(i.value,t.validations,j,e,this.formValuesStateSubject$.value)||s()})})}setResetPathValue({key:e,property:t,path:i,value:s}){this.fields.get(e)?this.setValue({key:e,property:t,path:i.split("."),value:s,event:"ON_RESET"}):this.queuedFieldResetPropertyEvents.set(e,{property:t,path:i,value:s})}resetProperty({event:e,key:t}){const i=this.fields.get(t),s=null==i?void 0:i.resetPropertyValues;s&&(null==s?void 0:s.some(t=>t.events.includes(e)))&&s.forEach(t=>{if(t.events.includes(e)&&y.includes(t.property))return t.validations?void Object.keys(t.validations).forEach(e=>{R(i.value,t.validations,j,e,this.formValuesStateSubject$.value)||this.setResetPathValue({key:t.field,path:t.path,property:t.property,value:t.resettledValue})}):this.setResetPathValue({key:t.field,path:t.path,property:t.property,value:t.resettledValue})})}addField({fieldSchema:e,mapperElement:t,path:i}){var s,a,n,r,l;if(this.fields.has(e.name))throw new Error(`field name ${e.name} already defined`);const o=t||(null===(s=this.mappers)||void 0===s?void 0:s.get(e.component));if(!o)throw new Error(`mapper not found for ${e.component}, add it to the mappers configuration`);if(null===(a=o.events)||void 0===a?void 0:a.setValue){const t=null===(n=null==e?void 0:e.props)||void 0===n?void 0:n[null===(r=null==o?void 0:o.events)||void 0===r?void 0:r.setValue];void 0===t||this.queuedInitialValues.has(e.name)||"string"==typeof t&&t.includes("${")||this.queuedInitialValues.set(e.name,k(t))}if(this.fields.set(e.name,new M({formIndex:this.index,schemaComponent:e,mapper:o,children:e.children?e.children.map(e=>e.name):[],validateVisibility:this.validateVisibility.bind(this),resetValue:this.resetValue.bind(this),resetProperty:this.resetProperty.bind(this),formValuesStateSubject$:this.formValuesStateSubject$,templateSubject$:this.templateSubject$,fieldEventSubject$:this.fieldEventSubject$,dataSubject$:this.dataSubject$,fieldValidNotification$:this.fieldValidNotification$,mountSubject$:this.mountSubject$,config:this.config,submitEvent:this.submit.bind(this),visibility:e.visibility,persistValue:e.persistValue,path:i})),null===(l=this.prefetchedData)||void 0===l?void 0:l[e.name]){const t=this.fields.get(e.name);if(t){const i=this.prefetchedData[e.name],s=Object.assign({},t.api);void 0!==i.defaultResponse&&(s.default={response:i.defaultResponse,status:200}),i.namedResponses&&(s.named=s.named||{},Object.keys(i.namedResponses).forEach(e=>{s.named[e]={response:i.namedResponses[e],status:200}})),t._api=s}}}removeField({key:e}){var t;null===(t=this.fields.get(e))||void 0===t||t.destroyField(),this.fields.delete(e),this.subscribeTemplates(),this.templateSubject$.next({scope:"fields",key:e,event:"ON_FIELDS"}),this.validateForm()}serializeStructure(e,t){e&&e.forEach(e=>{var i;const s=this.fields.get(e.name);s?(s.children=(null===(i=null==e?void 0:e.children)||void 0===i?void 0:i.map(e=>e.name))||(null==s?void 0:s.children)||[],s.originalSchema=e,s.templateSubject$=this.templateSubject$):this.addField({fieldSchema:e,mapperElement:e.mapper,path:t}),e.children&&this.serializeStructure(e.children,`${t?`${t}.`:""}${e.name}`)})}refreshFields(e){const t=Array.from(this.fields.keys());this.serializeStructure(e);const i=L.checkIndexes(e);this.fields.forEach((e,t)=>{var s;i.includes(t)||(null===(s=this.fields.get(t))||void 0===s||s.destroyField(),this.fields.delete(t))}),this.subscribeTemplates(),this.fields.forEach((e,i)=>{var s;t.includes(i)||(null===(s=this.fields.get(i))||void 0===s||s.emitEvents({event:"ON_FIELD_MOUNT"}),this.checkFieldEventQueues(i))}),this.subscribedTemplates.forEach(e=>{e.originFieldKeys.forEach(e=>{this.templateSubject$.next({scope:"fields",key:e,event:"ON_FIELDS"})})})}getField({key:e}){return this.fields.get(e)}printValues(){console.table(this.formValuesStateSubject$.value.values)}getFormState(){const e={},t={},i=[];return this.fields.forEach((s,a)=>{"string"==typeof s.value&&0===s.value.length||null==s.value||(N(e,s.nameToSubmit||a,s.value),t[a]=s.metadata),s.valid||i.push(a)}),{values:e,metadata:t,erroredFields:i,isValid:this.valid}}subscribeFieldEvent({callback:e}){return this.fieldEventSubject$.pipe(r(()=>this.submitChecker()),s(e=>`${e.event}|${e.fieldName}`),a(e=>e.pipe(n(this.config.defaultStateRefreshTimeMS)))).subscribe({next:e})}subscribeOnMount(e){return this.mountSubject$.pipe(u(()=>this.formValuesStateSubject$.value)).subscribe({next:e})}subscribeData(e){return this.dataSubject$.pipe(r(({formIndex:e})=>this.index===e&&this.submitChecker()),s(e=>e.event),a(e=>e.pipe(n(this.config.defaultStateRefreshTimeMS))),u(({fieldIndex:e})=>({field:e,data:this.formValuesStateSubject$.value}))).subscribe({next:e})}subscribeOnSubmit(e){return this.submitSubject$.pipe(r(({formIndex:e})=>e===this.index&&this.submitChecker()),u(({values:e})=>e)).subscribe({next:e})}subscribeFormValidation(e){return this.formValidSubject$.pipe(r(({formIndex:e})=>this.index===e),u(()=>({formIndex:this.index,valid:this.valid})),d("valid"),o({formIndex:this.index,valid:this.valid})).subscribe({next:e})}submit(){this.fields.forEach(e=>{e.emitEvents({event:"ON_FIELD_VALIDATION"})}),this.valid&&(this.submitSubject$.next({formIndex:this.index,values:this.formValuesStateSubject$.value}),this.submitted=!0)}destroy(){this.templateSubject$.unsubscribe(),this.templateSubscription$.unsubscribe(),this.mountSubject$.unsubscribe(),this.fieldEventSubject$.unsubscribe(),this.fieldValidNotification$.unsubscribe(),this.formValuesStateSubject$.unsubscribe(),this.isolatedFormInstance&&(this.submitSubject$.unsubscribe(),this.dataSubject$.unsubscribe(),this.formValidSubject$.unsubscribe()),this.fields.forEach(e=>e.destroyField())}}L.checkIndexes=(e,t=[])=>{if(!e)return t;const i=(e,t)=>{for(let s=0;s<e.length;s++){const a=e[s];t.push(a.name),a.children&&i(a.children,t)}};i(e,t);const s=t.filter((e,i)=>t.indexOf(e)!==i);if(s.length>0)throw new Error(`duplicated indexes found on schema: ${JSON.stringify(s)}`);return t};class D{constructor(e){var i,s,a,n,r;this.destroy=()=>{this.forms.forEach(e=>e.destroy()),this.dataSubject$.unsubscribe(),this.formValidSubject$.unsubscribe(),this.submitSubject$.unsubscribe()},this.forms=new Map,this.config={defaultAPIdebounceTimeMS:Number(null===(i=null==e?void 0:e.config)||void 0===i?void 0:i.defaultAPIdebounceTimeMS)?Number(null===(s=null==e?void 0:e.config)||void 0===s?void 0:s.defaultAPIdebounceTimeMS):v,defaultStateRefreshTimeMS:Number(null===(a=null==e?void 0:e.config)||void 0===a?void 0:a.defaultStateRefreshTimeMS)?Number(null===(n=null==e?void 0:e.config)||void 0===n?void 0:n.defaultStateRefreshTimeMS):100,defaultLogVerbose:(null===(r=null==e?void 0:e.config)||void 0===r?void 0:r.defaultLogVerbose)?e.config.defaultLogVerbose:g},this.dataSubject$=new t,this.formValidSubject$=new t,this.submitSubject$=new t,this.mappers=null==e?void 0:e.mappers}createFormWithIndex({index:e,mappers:t}){this.addForm({key:e,params:{index:e,mappers:t,config:this.config}})}addForm({key:e,params:t}){this.checkIndexes({key:e});const i=new L(Object.assign(Object.assign({},t),{dataSubject$:this.dataSubject$,formValidSubject$:this.formValidSubject$,submitSubject$:this.submitSubject$}));i.config||(i.config=this.config),this.forms.set(e,i)}getForm({key:e}){return this.forms.get(e)}removeForm({key:e}){var t;null===(t=this.forms.get(e))||void 0===t||t.destroy(),this.forms.delete(e)}removeField({formIndex:e,fieldIndex:t}){const i=this.forms.get(e);null==i||i.removeField({key:t}),0===(null==i?void 0:i.fields.size)&&this.removeForm({key:e})}checkIndexes({key:e}){if(this.forms.has(e))throw new Error(`duplicate index ${e} on form group`)}printFormGroupInstance(){console.table(this.forms)}submitMultipleFormsByIndex(e,t){let i=!0,s={},a={},n=[];e.forEach(e=>{var t,r;null===(t=this.forms.get(e))||void 0===t||t.submit();const l=null===(r=this.forms.get(e))||void 0===r?void 0:r.formValuesStateSubject$.value,o="object"==typeof(null==l?void 0:l.metadata)&&null!==l.metadata?l.metadata:{};i=i&&((null==l?void 0:l.isValid)||!1),s=Object.assign(Object.assign({},s),(null==l?void 0:l.values)||{}),a=Object.assign(Object.assign({},a),o),n=[...n,...(null==l?void 0:l.erroredFields)||[]]}),i&&t&&t({erroredFields:n,isValid:i,values:s,metadata:a})}onDataSubscription({ids:e,callback:t}){return this.dataSubject$.pipe(r(({formIndex:t})=>e.includes(t)),s(({event:e,formIndex:t})=>`${e}.${t}`),a(e=>e.pipe(n(this.config.defaultStateRefreshTimeMS))),u(({fieldIndex:t,formIndex:i})=>e.reduce((e,s)=>{const a=this.forms.get(s);return a&&(e[s]={formId:i,formField:t,values:a.formValuesStateSubject$.value}),e},{}))).subscribe(t)}onValidSubscription({ids:e,callback:t}){return this.formValidSubject$.pipe(r(({formIndex:t})=>e.includes(t)),s(({formIndex:e})=>e),a(e=>e.pipe(n(0))),o({fieldTrigger:null}),u(()=>({groupValid:e.every(e=>{var t;return!this.forms.get(e)||(null===(t=this.forms.get(e))||void 0===t?void 0:t.valid)}),forms:e.reduce((e,t)=>{const i=this.forms.get(t);return i&&(e[t]=i.valid),e},{})}))).subscribe(t)}onSubmitSubscription({ids:e,callback:t}){return this.submitSubject$.pipe(r(({formIndex:t})=>e.includes(t)),u(()=>e.reduce((e,t)=>{const i=this.forms.get(t);return i&&(e[t]=i.formValuesStateSubject$.value),e},{}))).subscribe(t)}}export{L as FormCore,M as FormField,D as FormGroup,h as TMutationEnum,E as formatterRegistry,O as maskRegistry,x as registerFormatters,_ as registerMasks,I as registerValidations,j as validationRegistry};
|
|
1
|
+
import{BehaviorSubject as e,Subject as t,Subscription as i,groupBy as s,mergeMap as n,debounceTime as r,filter as a,combineLatest as l,startWith as o,map as u,distinctUntilKeyChanged as d}from"rxjs";import c from"credit-card-type";import{getCurrencySymbol as h}from"@gaignoux/currency";var v;function f(e,t,i,s){return new(i||(i=Promise))(function(n,r){function a(e){try{o(s.next(e))}catch(e){r(e)}}function l(e){try{o(s.throw(e))}catch(e){r(e)}}function o(e){e.done?n(e.value):function(e){return e instanceof i?e:new i(function(t){t(e)})}(e.value).then(a,l)}o((s=s.apply(e,t||[])).next())})}!function(e){e.ON_VALUE="value",e.ON_PROPS="props",e.ON_VISIBILITY="visibility",e.ON_API="api",e.ON_IVARS="iVars",e.ON_FIELDS="fields"}(v||(v={})),"function"==typeof SuppressedError&&SuppressedError;const p=1e3,m=/^\$\{(?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*\}$/,b=/\$\{((?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*)\}/g,g=/\s*(\|\||&&|!+)\s*/g,S=/^\|\||&&|!+$/,y=["fields","iVars","form"],$=["api","apiSchema","props","validations","visibilityConditions","resetValues"],V=!1;function j(e){const t=b,i=[];let s;for(;null!==(s=t.exec(e));)i.push(s[1]);const n=g,r=i.map(e=>e.split(n).filter(e=>!n.test(e))).flat().filter(e=>e.split(".").length>1);return{originScopeKeys:Array.from(new Set(r.map(e=>e.split(".")[0]))),originFieldKeys:Array.from(new Set(r.map(e=>e.split(".")[1]))),originPropertyKeys:Array.from(new Set(r.map(e=>e.split(".")[2])))}}function E(e,t){const i=[];if(Array.isArray(e))e.forEach((e,s)=>{i.push(...E(e,`${t?`${t}.`:""}${s}`))});else if("object"==typeof e)for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&i.push(...E(e[s],`${t?`${t}.`:""}${s}`));else if("string"==typeof e&&e.includes("${")){const s=(t||"").split(".");j(e).originScopeKeys.every(e=>y.includes(e))?i.push(Object.assign(Object.assign({originExpression:e},j(e)),{destinationKey:s[0],destinationProperty:s[1],destinationPath:s.slice(2)})):console.warn(`scope malformed on this expression: ${e}, ignoring..`)}return i}const N={},x={},O={};function I(e){Object.assign(N,e)}function F(e){Object.assign(x,e)}function k(e){Object.assign(O,e)}var w=(e,t)=>{if(!t.length||!e)return!1;let i=e;return"string"!=typeof i&&(i=(null==e?void 0:e.toString())||i),{equal:i.length!==t.length.target,notEqual:i.length===t.length.target,less:i.length>=t.length.target,lessOrEqual:i.length>t.length.target,greater:i.length<=t.length.target,greaterOrEqual:i.length<t.length.target}[t.length.rule]};const _=e=>{if(9!==e.length)return!0;if(!/^\d{8}$/.test(e.slice(0,8)))return!0;const t="TRWAGMYFPDXBNJZSQVHLCKE"[parseInt(e.slice(0,8),10)%23];return!(e[8].toUpperCase()===t)};var D=(e,t)=>{if(!e||!t.document)return!0;const i={NIF:(e,t)=>((e,t)=>{switch(t){case"pt-PT":return(e=>{if(!/^\d{9}$/.test(e))return!1;const t=parseInt(e[8],10),i=11-Array.from(e.substring(0,8)).reduce((e,t,i)=>e+parseInt(t,10)*(9-i),0)%11;return 10===i||11===i?0===t:i===t})(e);case"es-ES":return _(e);case"it-IT":return(e=>/^[A-Z]{6}\d{2}[A-Z]\d{2}[A-Z]\d{3}[A-Z]$/.test(e))(e);case"de-DE":return(e=>/^\d{11}$/.test(e))(e);case"fr-FR":return(e=>/^\d{2} \d{3} \d{3} \d{3} \d{3}$/.test(e))(e);case"en-GB":return(e=>/^GB\d{9}|\d{12}|\d{3}[A-Z]{5}$/.test(e))(e);case"nl-BE":case"fr-BE":return(e=>!!/^\d{11}$/.test(e)&&97-parseInt(e.substring(0,9),10)%97===parseInt(e.substring(9),10))(e);case"nl-NL":return(e=>!!/^\d{9}$/.test(e)&&e.split("").map((e,t)=>parseInt(e,10)*(9-t)).reduce((e,t)=>e+t,0)%11==0)(e);case"sv-SE":return(e=>!!/^\d{10,12}$/.test(e)&&(12===e.length?e.substring(2):e).split("").map((e,t)=>{let i=parseInt(e,10)*(t%2==0?2:1);return i>9&&(i-=9),i}).reduce((e,t)=>e+t,0)%10==0)(e);default:throw new Error(`NIF validation not supported for locale: ${t}`)}})(e,t),NIE:e=>(e=>{if(9!==e.length)return!0;if(!/^[XYZ]\d{7}[TRWAGMYFPDXBNJZSQVHLCKE]$/.test(e))return!0;let t=e.toUpperCase().padStart(9,"0");return t=t[0].replace(/[XYZ]/g,e=>({X:"0",Y:"1",Z:"2"}[e]||e))+t.slice(1),_(t)})(e),CIF:e=>(e=>!/^[A-Z][0-9]{7}[A-J0-9]$/.test(e))(e),IBAN:e=>(e=>{const t=e.replace(/\s/g,"");return 24!==t.length||!/^(ES)[0-9]{22}$/.test(t)||1!==(e=>{for(;e.length>2;){const t=e.slice(0,6),i=parseInt(t,10);if(isNaN(i))return NaN;e=i%97+e.slice(t.length)}return parseInt(e,10)%97})(t.substring(4)+1428+t.substring(2,4))})(e)};return i[t.document.type](e,t.document.locale)};const A=(e,t)=>{const i=Number(e);return!(!t.max||Number.isNaN(i))&&i>Number(t.max)},T=(e,t)=>{const i=Number(e);return!(!t.min||Number.isNaN(i))&&i<Number(t.min)},M=(e,t)=>{if(!t.between||!e)return!1;const i=Number(e);return!(Number.isNaN(i)||+i>=t.between.start&&+i<=t.between.end)},P=(e,t)=>{const i=Number(e);return!(!t.lessThan||Number.isNaN(i))&&i>=t.lessThan},C=(e,t)=>{const i=Number(e);return!(!t.greaterThan||Number.isNaN(i))&&i<=t.greaterThan},R=(e,t)=>{if(!t.sequential)return!1;const i=String(e).replace(/[^0-9]/g,"");return!(-1==="0123456789".indexOf(i)&&-1==="9876543210".indexOf(i))},L=(e,t)=>!(!t.regex||!e)&&!new RegExp(t.regex).test(e),Y=(e,t)=>!(!t.email||!e)&&!/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(e),q=(e,t)=>!(!t.url||!e)&&!/[(http(s)?)://(www.)?a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)/gi.test(e),U=(e,t)=>!!t.onlyLetters&&!/^[\p{L}\s]*$/u.test(e),z=(e,t)=>!!t.notAllowSpaces&&/\s/.test(e),Z=(e,t)=>!!t.isNumber&&!!e&&!/^[0-9\s]*$/.test(e),Q=(e,t)=>!(!t.hasNoExtraSpaces||!e)&&L(e,{regex:"^[A-Za-zÀ-ÖØ-öø-ÿäöüÄÖÜß0-9]+$"}),B=(e,t)=>{if(!t.repeated)return!1;const i={};for(const t of String(e))if(/\d/.test(t)){if(i[t])return!0;i[t]=1}return!1},J=(e,t,{values:i=[],metadata:s=[]}={values:[],metadata:[],erroredFields:[],isValid:!0})=>!!(t.callback&&(null==t?void 0:t.callback)instanceof Function)&&t.callback(e,{values:i,metadata:s}),K=(e,t)=>!(!e||!Array.isArray(null==t?void 0:t.includes)||(null==t?void 0:t.includes.some(t=>t===e||JSON.stringify(t)===e))),G=(e,t)=>{const i=W(null==e?void 0:e.toString()),s=c(i);return["object"==typeof t&&t.length?null==s?void 0:s.filter(({type:e})=>t.some(t=>t===e))[0]:s[0],i]},W=e=>null==e?void 0:e.replace(/ /g,""),X=(e,t=4,i="/")=>{const s=e.replace(/\D/g,""),n=s.slice(0,2);return s.length>=5?`${n}${i}${s.slice(2,t)}`:s.length>=3?`${n}${i}${s.slice(2)}`:s},H=(e,t)=>{if(!e)return!0;const[i]=G(String(e),t.isCreditCard);return!i},ee=(e,t)=>{var i;if(!e||!t.isCreditCodeMatch)return!1;const[s]=G(t.isCreditCodeMatch.numberCard,t.isCreditCodeMatch.availableOptions);return(null===(i=null==s?void 0:s.code)||void 0===i?void 0:i.size)!==e.length},te=(e,t)=>{if(!e||!t.isCreditCardAndLength)return!1;const[i,s]=G(e,t.isCreditCardAndLength);return i&&!i.lengths.includes(s.length)},ie=(e,t)=>{var i;return!(!(null==t?void 0:t.notEmpty)||void 0===e||null!==e&&""!==e&&0!==e&&(null===(i=String(e))||void 0===i?void 0:i.trim().length))},se=(e,t)=>null!=(null==t?void 0:t.value)&&null!=e&&e!=t.value,ne=(e,t)=>!(!t.required||e&&("string"!=typeof e||0!==e.trim().length)),re=(e,t)=>{if(!(null==t?void 0:t.bool))return!1;let i=!1;return"boolean"==typeof t.bool&&(i=t.bool),i},ae=(e,t)=>{if(!t.exists)return!1;let i=!t.exists;return i||(i=!e),i},le=(e,t)=>{if(t.forceDefinedOrigin&&void 0===t.origin||t.forceDefinedTarget&&void 0===t.target)return!1;const i=void 0===t.origin?e:t.origin,s=void 0===t.target?e:t.target;return{"!==":(i||e)!==(s||e),"===":(i||e)===(s||e),"<":(i||e)<(s||e),">":(i||e)>(s||e),"<=":(i||e)<=(s||e),">=":(i||e)>=(s||e),"!!origin":!!String(i||e).trim().length}[t.condition]},oe=(e,t)=>{if(!t.conditions)return!1;let i={and:()=>{var i;return!!(null===(i=t.conditions)||void 0===i?void 0:i.set.every(t=>le(e,t)))},or:()=>{var i;return!!(null===(i=t.conditions)||void 0===i?void 0:i.set.some(t=>le(e,t)))}}[t.conditions.rule]();return t.conditions.conditions&&(i="and"===t.conditions.rule?i&&oe(e,{conditions:t.conditions.conditions}):i||oe(e,{conditions:t.conditions.conditions})),!i},ue={DDMMYYYY:e=>{if(!e)return"";const t=e.split(e.includes("/")?"/":"-");return`${t[1]}/${t[0]}/${t[2]}`},YYYYMMDD:e=>{if(!e)return"";const t=e.split(e.includes("/")?"/":"-");return`${t[1]}/${t[2]}/${t[0]}`},YYYYDDMM:e=>{if(!e)return"";const t=e.split(e.includes("/")?"/":"-");return`${t[2]}/${t[1]}/${t[0]}`},MMDDYYYY:e=>e,timestamp:e=>new Date(e).toString()},de=(e,t)=>{var i;let s=!1;if(2!=(null===(i=t.betweenDates)||void 0===i?void 0:i.length))return!1;for(const i of t.betweenDates)if(ce(e,{date:i})){s=!0;break}return s},ce=(e,t)=>{var i,s,n,r,a,l,o,u,d,c,h,v;if(!(null===(s=null===(i=t.date)||void 0===i?void 0:i.target)||void 0===s?void 0:s.value)&&!(null===(r=null===(n=t.date)||void 0===n?void 0:n.origin)||void 0===r?void 0:r.intervals))return!1;const f=t.date.origin.value||e,p=ue[null===(a=t.date)||void 0===a?void 0:a.origin.format](f).toString();let m=new Date(p),b=new Date,g=new Date;if((null===(o=null===(l=t.date)||void 0===l?void 0:l.target)||void 0===o?void 0:o.format)&&(g=new Date(ue[null===(d=null===(u=t.date)||void 0===u?void 0:u.target)||void 0===d?void 0:d.format](t.date.target.value).toString()),b=g),t.date.origin.intervals){b=((e,t)=>{const i={years:(e,t)=>new Date(e.setUTCFullYear(e.getUTCFullYear()+t)),months:(e,t)=>new Date(e.setUTCMonth(e.getUTCMonth()+t)),days:(e,t)=>new Date(e.setDate(e.getUTCDate()+t))};return Object.keys(t).reduce((e,s)=>i[s](e,t[s]),new Date(e))})(m,t.date.origin.intervals);const e=new Date;(null===(c=t.date.target)||void 0===c?void 0:c.value)&&g&&(e.setDate(g.getDate()),e.setMonth(g.getMonth())),m=new Date(`${e.getUTCMonth()+1}/${e.getUTCDate()}/${e.getUTCFullYear()}`)}if(t.date.onlyValidDate&&(!(b instanceof Date&&isFinite(b))||!(b instanceof Date&&isFinite(m))||f.length<8))return!0;if(((e,t)=>{if(!e.includes("/")&&!e.includes("-")||!t)return!0;const i=e.replace(/[-/]/g,"");return!{DDMMYYYY:/^(\d{2})(\d{2})(\d{4})$/,YYYYMMDD:/^(\d{4})(\d{2})(\d{2})$/,YYYYDDMM:/^(\d{4})(\d{2})(\d{2})$/,MMDDYYYY:/^(\d{2})(\d{2})(\d{4})$/,DMYYYY:/^(\d{1,2})(\d{1,2})(\d{4})$/,YYYYMD:/^(\d{4})(\d{1,2})(\d{1,2})$/,YYYYDM:/^(\d{4})(\d{1,2})(\d{1,2})$/,MDYYYY:/^(\d{1,2})(\d{1,2})(\d{4})$/}[t].test(i)})(p,null===(h=t.date)||void 0===h?void 0:h.origin.format))return!1;const S=m.getTime(),y=b.getTime();return{">":S>y,">=":S>=y,"<":S<y,"<=":S<=y,"===":S===y,"!==":S!==y}[null===(v=t.date)||void 0===v?void 0:v.operator]},he=(e,t)=>{if(!t.validDate||!e)return!1;if(/[^a-zA-Z0-9\s-]/.test(e))return!0;const i=ue[t.validDate](e).toString().split(/[/-]/),s=parseInt(i[2],10),n=parseInt(i[0],10)-1,r=parseInt(i[1],10),a=new Date(s,n,r),l=new Date;return l.setFullYear(l.getFullYear()-150),a.getFullYear()<l.getFullYear()||!(a.getFullYear()===s&&a.getMonth()===n&&a.getDate()===r)};function ve(e){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e))return e.map(e=>ve(e));const t={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=ve(e[i]));return t}function fe(e,t,i){if(null==e)return i;const s=Array.isArray(t)?t:t.split(".");let n=e;for(let e=0;e<s.length;e++){if(null==n)return i;n=n[s[e]]}return void 0===n?i:n}function pe(e,t,i){if(null==e||"object"!=typeof e)return e;const s=Array.isArray(t)?t:t.split(".");let n=e;for(let e=0;e<s.length-1;e++){const t=s[e],i=s[e+1];null!=n[t]&&"object"==typeof n[t]||(n[t]="number"==typeof i||/^\d+$/.test(String(i))?[]:{}),n=n[t]}return n[s[s.length-1]]=i,e}function me(e,t){if(e===t)return!0;if(null==e||null==t)return e===t;if(typeof e!=typeof t)return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if("object"!=typeof e)return!1;const i=Array.isArray(e);if(i!==Array.isArray(t))return!1;if(i){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!me(e[i],t[i]))return!1;return!0}const s=Object.keys(e),n=Object.keys(t);if(s.length!==n.length)return!1;for(const i of s){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!me(e[i],t[i]))return!1}return!0}function be(e){return null==e}function ge(e){return"function"==typeof e}var Se=(e,t,i)=>!!t&&function(e,t,i){const s=[];return Object.keys(t).forEach(n=>{s.push(i[n](e,{[n]:t[n]}))}),s}(e,t,i).some(e=>e);const ye={max:A,min:T,lessThan:P,greaterThan:C,length:w,regex:L,url:q,email:Y,onlyLetters:U,notAllowSpaces:z,callback:J,hasNoExtraSpaces:Q,between:M,sequential:R,includes:K,repeated:B,document:D,isCreditCard:H,isCreditCodeMatch:ee,isCreditCardAndLength:te,required:ne,value:se,notEmpty:ie,bool:re,exists:ae,isNumber:Z,conditions:oe,validDate:he,date:ce,betweenDates:de},$e={max:A,min:T,lessThan:P,greaterThan:C,length:w,regex:L,url:q,email:Y,onlyLetters:U,notAllowSpaces:z,callback:J,hasNoExtraSpaces:Q,between:M,sequential:R,includes:K,repeated:B,document:D,isCreditCard:H,isCreditCodeMatch:ee,isCreditCardAndLength:te,required:ne,value:se,notEmpty:ie,bool:re,exists:ae,isNumber:Z,conditions:oe,multipleValidations:(e,t)=>{if(!t.multipleValidations)return!1;const i=function(e,t){const i=[];return Object.keys(t).forEach(s=>{let n;n=ge(ye[s])?ye[s](e,{[s]:t[s]}):Se(e,t[s],ye),i.push(n)}),i}(e,t.multipleValidations.validations);return{AND:()=>i.every(e=>e),OR:()=>i.some(e=>e),NOT:()=>!i.every(e=>e)}[t.multipleValidations.rule]()},date:ce,betweenDates:de,validDate:he};I($e);const Ve={capitalize:e=>String(e).charAt(0).toUpperCase()+String(e).slice(1),uppercase:e=>String(e).toUpperCase(),onlyNumbers:e=>String(e).replace(/(\D)+/gim,""),onlyLetters:e=>String(e).replace(/[^\p{L}\s]/gu,""),regex:(e,t)=>t.regex?String(e).replace(new RegExp(t.regex,"g"),""):e,splitter:(e,t)=>{if(!e||!t.splitter||"string"!=typeof e)return e;t.splitter.sort((e,t)=>e.position-t.position);let i=e,s=0;for(const e of t.splitter){const{position:t,value:n}=e,r=t+s;r>=0&&r<=i.length&&(i=i.slice(0,r)+n+i.slice(r),s+=n.length)}return i},maxLength:(e,t)=>{if(!e||!t.maxLength)return e;const i=String(e);return i.length>t.maxLength?i.substring(0,t.maxLength):e},onlyFloatNumber:(e,t)=>{const{onlyFloatNumber:i}=t;if(!i||"string"!=typeof e||!e)return e;const{precision:s=2,decimal:n="."}=i;if(!e.includes(n))return e;const r=e.replace(/[^0-9]/g,""),a=r.slice(0,r.length-s),l=r.slice(r.length-s);return parseFloat(`${a}.${l}`).toFixed(s)},trim:(e,t)=>!e||(null==t?void 0:t.trim)?e:String(e).trim(),gapsCreditCard:(e,t)=>{if(!t.gapsCreditCard)return e;const[i,s]=G(e,null==t?void 0:t.gapsCreditCard);return((e,t)=>t?((e,t=[])=>{const[i,s]=t.reduce(([e,i],s,n)=>[`${e}([0-9]{0,${s-(t[n-1]||0)}})`,`${i}$${n+1} `],["",""]);return e.replace(new RegExp(i),s).trim()})(e.slice(0,null==t?void 0:t.lengths[0]),t.gaps):null==e?void 0:e.slice(0,19))(s,i)},callback:(e,t)=>(null==t?void 0:t.callback)?t.callback(e):e,dotEvery3chars:e=>{const t=String(e).replace(/\./g,"").replace(/(.{3})/g,"$1.");return t.endsWith(".")?t.slice(0,-1):t}};F(Ve);var je=(e,t)=>{if(!(null==t?void 0:t.generic))return e;let i=e;return t.generic.forEach(t=>{const{to:s=i.length,mask:n}=t;let{from:r}=t;if(s>e.length-1)return;0===r&&(r=1);const a=new Array(s-r+2).join(n);i=i.slice(0,r-1)+a+i.slice(s)}),i};const Ee={currency:(e,t)=>{if(!(null==t?void 0:t.currency))return e;const{align:i="",decimal:s=".",precision:n=2,prefix:r="BBD",thousands:a=","}=t.currency;let l=(function(e){return"number"==typeof e||"object"==typeof e&&null!==e&&"[object Number]"===Object.prototype.toString.call(e)}(e)?Number(e).toFixed(n):e).replace(/[^0-9]/g,"");if(!l)return"";let o=l.slice(0,l.length-n).replace(/^0*/g,"").replace(/\B(?=(\d{3})+(?!\d))/g,a);""===o&&(o="0"),"right"===i&&String(e).endsWith(" ")&&(l=l.slice(0,-1));let u=o,d=l.slice(l.length-n);if(n>0&&(d="0".repeat(n-d.length)+d,u+=s+d),!i)return u;const c=h(r);return"left"===i?`${c} ${u}`:`${u} ${c}`},custom:(e,t)=>{if(!t.custom||!e)return e;let i="",s=0;const n=e.replace(/[^\w\s]/gi,"");for(const e of t.custom)if("#"===e){if(!(s<n.length))break;i+=n[s],s++}else s<=n.length&&(i+=e);return e.length<i.length&&(i=i.replace(/[^\w]+$/,"")),i},callback:(e,t)=>(null==t?void 0:t.callback)&&t.callback(e),generic:je,secureCreditCard:e=>je(e,{generic:[{from:1,to:4,mask:"x"},{from:6,to:9,mask:"x"},{from:11,to:14,mask:"x"},{from:16,to:19,mask:"x"}]}),card:e=>e.replace(/[^\dA-Z]/g,"").replace(/(.{4})/g,"$1 ").trim(),cardDate:e=>X(e),fein:e=>X(e,9,"-"),replaceAll:(e,t)=>{let i=t.replaceAll;return i?("number"==typeof i&&(i=null==i?void 0:i.toString()),new Array(String(e).length+1).join(i)):e}};k(Ee);class Ne extends t{constructor(e){super(),this.isMounted=e}next(e){this.isMounted()&&super.next(e)}}class xe extends e{constructor(e){super(e),this.defaultValue=e}next(e){this.closed||super.next(e)}get value(){return this.closed?this.defaultValue:super.value}}function Oe(e,t,i,s,n){return ge(i[s])?i[s](e,t,n):Se(e,t[s],i)}class Ie{constructor({formIndex:e,schemaComponent:t,config:s,children:n,validateVisibility:r,resetValue:a,resetProperty:l,templateSubject$:o,fieldEventSubject$:u,dataSubject$:d,fieldValidNotification$:c,mountSubject$:h,mapper:v,formValuesStateSubject$:f,submitEvent:m,visibility:b,persistValue:g}){var S,y,$,j,E,N;this.valueSubscription$=new i,this.fieldStateSubscription$=new i,this.formIndex=e,this.originalSchema=ve(t),this.config={defaultAPIdebounceTimeMS:Number(null==s?void 0:s.defaultAPIdebounceTimeMS)?Number(null==s?void 0:s.defaultAPIdebounceTimeMS):p,defaultStateRefreshTimeMS:Number(null==s?void 0:s.defaultStateRefreshTimeMS)?Number(null==s?void 0:s.defaultStateRefreshTimeMS):100,defaultLogVerbose:(null==s?void 0:s.defaultLogVerbose)?s.defaultLogVerbose:V},this.name=t.name,this.nameToSubmit=t.nameToSubmit,this.component=t.component,this.children=n,this.validations=ve(t.validations),this.visibilityConditions=ve(t.visibilityConditions),this.resetValues=ve(t.resetValues),this.resetPropertyValues=ve(t.resetPropertyValues),this.apiSchema=ve(t.api),this.formatters=ve(t.formatters),this.masks=ve(t.masks),v.valueChangeEvent&&(this.valueChangeEvent=v.valueChangeEvent),(null===(S=v.events)||void 0===S?void 0:S.setValue)&&(this.valuePropName=v.events.setValue),this.mapper=v,this.validateVisibility=r,this.resetValue=a,this.resetProperty=l,this.submitEvent=m,this.templateSubject$=o,this.fieldEventSubject$=u,this.dataSubject$=d,this.fieldValidNotification$=c,this.mountSubject$=h,this.formValuesStateSubject$=f,this.getFormValues=()=>this.formValuesStateSubject$.value,this._props=Ie.filterProps(ve(t.props||{})),this._adapterProps=JSON.stringify(t.props||{}),this._metadata="",this.errorsString="",this.errorsList=[],this._visibility="boolean"!=typeof b||b,this._api={default:{response:(null===(j=null===($=null===(y=this.apiSchema)||void 0===y?void 0:y.defaultConfig)||void 0===$?void 0:$.config)||void 0===j?void 0:j.fallbackValue)||"",status:null},named:(null===(E=this.apiSchema)||void 0===E?void 0:E.configs)&&Object.keys(null===(N=this.apiSchema)||void 0===N?void 0:N.configs).reduce((e,t)=>{var i,s;return e[t]={response:(null===(s=null===(i=this.apiSchema)||void 0===i?void 0:i.configs)||void 0===s?void 0:s[t].config.fallbackValue)||"",status:null},e},{}),apiState:{loading:!1}},this._errors={},this._mounted=!1,this.valid=!0,this.persistValue=g,this.initializeObservers()}initializeObservers(){this.valueSubject$&&!this.valueSubject$.closed||(this.valueSubject$=new Ne(()=>this.mounted)),this.errorSubject$&&!this.errorSubject$.closed||(this.errorSubject$=new Ne(()=>this.mounted)),this.visibilitySubject$&&!this.visibilitySubject$.closed||(this.visibilitySubject$=new Ne(()=>this.mounted)),this.propsSubject$&&!this.propsSubject$.closed||(this.propsSubject$=new Ne(()=>this.mounted)),this.fieldStateSubscription$&&!this.fieldStateSubscription$.closed||(this.fieldStateSubscription$=new i),this.apiEventQueueSubject$&&!this.apiEventQueueSubject$.closed||(this.apiEventQueueSubject$=new Ne(()=>this.mounted)),this.apiEventQueueSubject$.observed||this.apiEventQueueSubject$.pipe(s(({event:e})=>e),n(e=>e.pipe(r(this.config.defaultAPIdebounceTimeMS))),a(()=>this.apiEventQueueSubject$&&!this.apiEventQueueSubject$.closed)).subscribe(e=>{this.apiRequest(e)})}get adapterProps(){return this._adapterProps}set adapterProps(e){const t=JSON.stringify(e||{});t!==this.adapterProps&&(this.props=Ie.filterProps(e),this._adapterProps=t)}get props(){return this._props}set props(e){void 0===e||me(e,this.props)||(this._props=e,this.propsSubject$.next(this.props),this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_PROPS"}))}static filterProps(e){return Array.isArray(e)?e.filter(e=>"string"!=typeof e||!e.includes("${")).map(e=>Ie.filterProps(e)):"object"==typeof e&&null!==e?e instanceof Date?e:Object.keys(e).reduce((t,i)=>{const s=e[i];return"string"==typeof s&&s.includes("${")||(t[i]=Ie.filterProps(e[i])),t},{}):e}get stateValue(){return this._stateValue}get metadata(){return this._metadata}get value(){return this._value}set value(e){var t,i,s;let n;if(this.valueChangeEvent)try{n=this.valueChangeEvent(e,{props:this.props})}catch(t){n=e}else n=e;null!=n&&("object"==typeof n&&"_value"in n&&"_metadata"in n?(this._value=this.formatValue(n._value),this._stateValue=(null===(t=this.mapper.events)||void 0===t?void 0:t.setValue)?{[this.mapper.events.setValue]:this.maskValue(this.formatValue(n._value))}:{},this._metadata=n._metadata):(this._value=this.formatValue(n),this._stateValue=(null===(i=this.mapper.events)||void 0===i?void 0:i.setValue)?{[null===(s=this.mapper.events)||void 0===s?void 0:s.setValue]:this.maskValue(this.formatValue(n))}:{},this.maskValue(this.formatValue(n)),this._metadata=n),this.stateValue&&this.valueSubject$.next(this.stateValue),this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_VALUE"}))}get visibility(){return this._visibility}set visibility(e){void 0!==e&&e!==this.visibility&&(this._visibility=e,this.visibilitySubject$.next(this.visibility),this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_VISIBILITY"}))}set valid(e){"boolean"!=typeof e&&this.valid===e||(this._valid=e,this.triggerFieldValidNotification())}get valid(){return this._valid}triggerFieldValidNotification(){this.fieldValidNotification$.closed||this.fieldValidNotification$.next({fieldTrigger:this.name})}get errors(){return this._errors}set errors(e){var t;void 0===e||me(e,this.errors)||(this._errors=e,this.errorsList=Object.values(this.errors).filter(e=>null!=e),this.errorsString=this.errorsList.join(", "),(null===(t=this.mapper.events)||void 0===t?void 0:t.setErrorMessage)&&this.errorSubject$.next({[this.mapper.events.setErrorMessage]:this.errorsString}),this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_PROPS"}))}get api(){return this._api}set api(e){void 0!==e&&(this._api=e,this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_API_RESPONSE"}),this.emitEvents({event:"ON_API_FIELD_RESPONSE"}))}notifyApiRequest(){this._api.apiState.loading=!0,this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_API_REQUEST"}),this.emitEvents({event:"ON_API_FIELD_REQUEST"})}get mounted(){return this._mounted}set mounted(e){void 0!==e&&e!==this.mounted&&(this._mounted=e,this.initializeObservers(),this.mountSubject$.closed||this.mountSubject$.next({key:this.name,status:this.mounted}))}mountField({valueSubscription:e,propsSubscription:t}){this.mounted=!0,this.subscribeValue(e),this.subscribeState(t),this.valueSubject$.next(this.stateValue),this.propsSubject$.next(this.props),this.visibilitySubject$.next(this.visibility),this.fieldEventSubject$.next({event:"ON_FIELD_MOUNT",fieldName:this.name,fieldInstance:this})}emitValue(e){this.visibility&&this.mounted&&(this.value=e.value,this.dataSubject$.next({event:e.event,fieldIndex:this.name,formIndex:this.formIndex}),this.emitEvents({event:e.event}))}emitEvents({event:e}){if("ON_FORM_SUBMIT"===e)return this.submitEvent();this.validateVisibility({event:e,key:this.name}),this.setFieldValidity({event:e}),this.resetValue({event:e,key:this.name}),this.resetProperty({event:e,key:this.name}),this.apiEventQueueSubject$.next({event:e}),this.fieldEventSubject$.next({event:e,fieldName:this.name,fieldInstance:this})}setFieldValidity({event:e}){var t,i,s,n;if(!this.validations||!this.visibility)return this.errors={},void(this.valid=!0);let r=!0;const a={},l=null===(t=this.validations)||void 0===t?void 0:t.methods;if(l&&Object.keys(l).forEach(e=>{var t,i;const s=Oe(this.value,l,N,e,null===(t=this.formValuesStateSubject$)||void 0===t?void 0:t.value);r=!s&&r,s&&(null===(i=this.validations)||void 0===i?void 0:i.messages)?e in this.validations.messages?a[e]=this.validations.messages[e]:"default"in this.validations.messages&&(a[e]=this.validations.messages.default):delete a[e]}),this.valid=r,null===(s=null===(i=this.validations)||void 0===i?void 0:i.eventMessages)||void 0===s?void 0:s[e]){const t={};null===(n=this.validations.eventMessages[e])||void 0===n||n.forEach(e=>{e in a&&(t[e]=a[e])}),this.errors=t}else"ON_FIELD_VALIDATION"===e&&(this.errors=a)}formatValue(e){return this.formatters?Object.keys(this.formatters).reduce((e,t)=>{const i=x[t];return i?i(e,this.formatters):e},e):e}maskValue(e){return this.masks?Object.keys(this.masks).reduce((e,t)=>{const i=O[t];return i?i(e,this.masks):e},e):e}checkApiRequestValidations(e){let t=!0;const i=e.preConditions;return i&&Object.keys(i).forEach(e=>{var s;const n=Oe(this.value,i,N,e,null===(s=this.formValuesStateSubject$)||void 0===s?void 0:s.value);t=t&&!n}),e.blockRequestWhenInvalid&&(t=t&&this.valid),t}apiRequest(e){return f(this,arguments,void 0,function*({event:e}){var t,i,s,n,r,a,l,o,u;let d=!1;const c=e=>f(this,void 0,void 0,function*(){var t,i;try{const{status:s,response:n}=yield function(e,t,i,s,n){return f(this,void 0,void 0,function*(){if(n){const[e,i]=t.split("?"),s=new URLSearchParams(i);Object.keys(n).forEach(e=>{s.append(e,n[e])}),t=`${e}?${s.toString()}`}const r=yield fetch(t,{method:e,headers:i,body:s?JSON.stringify(s):void 0}),a=yield r.text();return{status:r.status,response:a}})}(e.method,e.url,e.headers,e.body,e.queryParams),r=null===(t=e.transform)||void 0===t?void 0:t.callback,a=r?r({payload:JSON.parse(String(n)),formValues:null===(i=this.formValuesStateSubject$)||void 0===i?void 0:i.value}):JSON.parse(String(n));return{response:e.resultPath?fe(a,e.resultPath):a,status:s}}catch(t){return{response:be(null==e?void 0:e.fallbackValue)?"error":e.fallbackValue,status:500}}});if("ON_API_FIELD_RESPONSE"===this.api.apiState.lastEvent&&"ON_API_FIELD_RESPONSE"===e||!(null===(i=null===(t=this.apiSchema)||void 0===t?void 0:t.defaultConfig)||void 0===i?void 0:i.events.includes(e))&&(!(null===(s=this.apiSchema)||void 0===s?void 0:s.configs)||!Object.keys(null===(n=this.apiSchema)||void 0===n?void 0:n.configs).some(t=>{var i,s;return null===(s=null===(i=this.apiSchema)||void 0===i?void 0:i.configs)||void 0===s?void 0:s[t].events.includes(e)})))return;const h={default:Object.assign({},this.api.default),named:Object.assign({},this.api.named),apiState:Object.assign({},this.api.apiState)},v=null===(r=this.apiSchema.defaultConfig)||void 0===r?void 0:r.config;if(v&&(null===(l=null===(a=this.apiSchema)||void 0===a?void 0:a.defaultConfig)||void 0===l?void 0:l.events.includes(e))&&this.checkApiRequestValidations(v)){d||this.notifyApiRequest();const{response:e,status:t}=yield c(v);d=!0,h.default={response:e,status:t}}if((null===(o=this.apiSchema)||void 0===o?void 0:o.configs)&&Object.keys(null===(u=this.apiSchema)||void 0===u?void 0:u.configs).some(t=>{var i,s;return null===(s=null===(i=this.apiSchema)||void 0===i?void 0:i.configs)||void 0===s?void 0:s[t].events.includes(e)})&&this.apiSchema.configs){const t=yield Promise.all(Object.keys(this.apiSchema.configs).map(t=>f(this,void 0,void 0,function*(){var i,s,n,r;const a=null===(s=null===(i=this.apiSchema)||void 0===i?void 0:i.configs)||void 0===s?void 0:s[t].config;if(a&&(null===(r=null===(n=this.apiSchema)||void 0===n?void 0:n.configs)||void 0===r?void 0:r[t].events.includes(e))&&this.checkApiRequestValidations(a)){d||this.notifyApiRequest();const{response:e,status:i}=yield c(a);return d=!0,{name:t,result:{response:e,status:i}}}return null})));t.forEach(e=>{e&&h.named&&(h.named[e.name]=e.result)})}d&&(h.apiState.lastEvent=e,h.apiState.loading=!1,this.api=h)})}destroyField(){this.mounted=!1,this.valueSubscription$.unsubscribe(),this.visibilitySubject$.unsubscribe(),this.fieldStateSubscription$.unsubscribe(),this.propsSubject$.unsubscribe(),this.errorSubject$.unsubscribe(),this.apiEventQueueSubject$.unsubscribe(),this.dataSubject$.closed||this.dataSubject$.next({event:"ON_FIELD_UNMOUNT",fieldIndex:this.name,formIndex:this.formIndex}),this.fieldEventSubject$.closed||this.fieldEventSubject$.next({event:"ON_FIELD_UNMOUNT",fieldName:this.name,fieldInstance:this})}subscribeState(e){var t;this.fieldStateSubscription$=l({visibility:this.visibilitySubject$.pipe(o(this.visibility)),props:this.propsSubject$.pipe(o(this.props)),errors:this.errorSubject$.pipe(o(Object.assign({},(null===(t=this.mapper.events)||void 0===t?void 0:t.setErrorMessage)&&{[this.mapper.events.setErrorMessage]:this.errorsString})))}).pipe(r(this.config.defaultStateRefreshTimeMS)).subscribe({next:e})}subscribeValue(e){this.valueSubscription$=this.valueSubject$.subscribe({next:e})}}class Fe{constructor(e){var s,n,r,a,l,o,u,d,c,h,v;this.templateSubscription$=new i,this.mappers=new Map,this.queuedFieldVisibilityEvents=new Map,this.queuedFieldResetValuesEvents=new Map,this.queuedFieldResetPropertyEvents=new Map,this.queuedInitialValues=new Map,this._valid=!1,this.stopEventsOnSubmit=!1,this.submitted=!1,this.isolatedFormInstance=!1,this.index=e.index,this.schema=e.schema,this.fields=new Map,this.action=e.action||(null===(s=e.schema)||void 0===s?void 0:s.action),this.method=e.method||(null===(n=e.schema)||void 0===n?void 0:n.method),this.config={defaultAPIdebounceTimeMS:Number(null===(r=e.config)||void 0===r?void 0:r.defaultAPIdebounceTimeMS)?Number(null===(a=e.config)||void 0===a?void 0:a.defaultAPIdebounceTimeMS):p,defaultStateRefreshTimeMS:Number(null===(l=e.config)||void 0===l?void 0:l.defaultStateRefreshTimeMS)?Number(null===(o=e.config)||void 0===o?void 0:o.defaultStateRefreshTimeMS):100,defaultLogVerbose:(null===(u=e.config)||void 0===u?void 0:u.defaultLogVerbose)?e.config.defaultLogVerbose:V},null===(d=e.mappers)||void 0===d||d.map(e=>{this.mappers.set(e.componentName,e)}),e.submitSubject$&&e.dataSubject$&&e.formValidSubject$||(this.isolatedFormInstance=!0,this.config.defaultLogVerbose&&console.warn(`some formGroup events are not properly instanciated, any onData, onValid, onSubmit events managed by formGroup won't trigger on form: ${this.index}`)),this.schema&&Fe.checkIndexes(this.schema.components),this.templateSubject$=new t,this.fieldEventSubject$=new t,this.mountSubject$=new t,this.fieldValidNotification$=new t,this.submitSubject$=e.submitSubject$?e.submitSubject$:new t,this.dataSubject$=e.dataSubject$?e.dataSubject$:new t,this.formValidSubject$=e.formValidSubject$?e.formValidSubject$:new t,this.formValuesStateSubject$=new xe({erroredFields:[],isValid:!0,metadata:[],values:[]}),this.getFormValues=()=>this.formValuesStateSubject$.value,this.subscribedTemplates=[],this.templateSubscription$=this.templateSubject$.subscribe(this.refreshTemplates.bind(this)),this.fieldValidNotification$.subscribe(()=>{this.validateForm()}),this.fieldEventSubject$.subscribe(()=>{this.formValuesStateSubject$.next(this.getFormState())}),this.dataSubject$.subscribe(()=>{this.formValuesStateSubject$.next(this.getFormState())}),this.mountSubject$.subscribe(this.mountActions.bind(this)),this.prefetchedData=null===(c=e.schema)||void 0===c?void 0:c.prefetchedData,this.initialValues=e.initialValues||(null===(h=e.schema)||void 0===h?void 0:h.initialValues),this.iVars=e.iVars||(null===(v=e.schema)||void 0===v?void 0:v.iVars)||{},this.stopEventsOnSubmit=(null==e?void 0:e.stopEventsOnSubmit)||!1,this.submitted=!1}generateFields(){this.schema&&this.serializeStructure(this.schema.components),this.fields.forEach(e=>{e.mountField({valueSubscription:()=>null,propsSubscription:()=>null})})}submitChecker(){return!(this.stopEventsOnSubmit&&this.submitted)}mountActions({key:e,status:t}){if(t){const t=this.fields.get(e);if(!t)return void(this.config.defaultLogVerbose&&console.warn(`field ${e} was mounted but since it's parent has some visibility condition the field was already removed`));this.subscribeTemplates(),this.refreshTemplates({scope:"fields",event:"ON_FIELDS"}),this.templateSubject$.next({scope:"iVars",event:"ON_IVARS"}),this.queuedInitialValues.has(e)||(t.valuePropName&&!t.value?t.emitValue({event:"ON_FIELD_MOUNT",value:""}):t.emitEvents({event:"ON_FIELD_MOUNT"})),this.checkFieldEventQueues(e)}}set initialValues(e){e&&Object.keys(e).forEach(t=>{const i=this.fields.get(t);i&&(null==i?void 0:i.visibility)&&(null==i?void 0:i.mounted)?i.emitValue({value:null==e?void 0:e[t],event:"ON_FIELD_MOUNT"}):this.queuedInitialValues.set(t,null==e?void 0:e[t])})}get iVars(){return this._iVars}set iVars(e){this._iVars=e,this.templateSubject$.next({scope:"iVars",event:"ON_IVARS"})}validateForm(){if(0===this.fields.size)return this.valid=!1;for(const[,e]of this.fields)if(!e.valid)return this.valid=!1;return this.valid=!0}get valid(){return this._valid}set valid(e){this._valid!==e&&(this._valid=e,this.templateSubject$.next({event:"ON_FORM",scope:"form"}),this.formValidSubject$.next({formIndex:this.index,valid:this.valid}))}subscribeTemplates(){this.subscribedTemplates=[],this.fields.forEach(({originalSchema:{component:e,props:t,name:i,validations:s,visibilityConditions:n,resetValues:r,resetPropertyValues:a,api:l}},o)=>{E({component:e,props:t,name:i,validations:s,visibilityConditions:n,resetValues:r,resetPropertyValues:a,apiSchema:l},o).forEach(e=>this.subscribedTemplates.push(e))})}getValue({scope:e,key:t,property:i,path:s}){switch(e){case"iVars":return fe(this.iVars,[t,...i?[i]:[],...s]);case"form":return fe(this,[t,...i?[i]:[],...s]);case"fields":{const e=this.fields.get(t);return e?"props"===i&&s[0]===e.valuePropName?e.value:s.length>0?fe(e[i],s):e[i]:this.config.defaultLogVerbose&&console.warn(`failed to get value from ${t}`)}}}setValue({key:e,property:t,path:i,originKey:s,value:n}){const r=this.fields.get(e);if(r){if(i.length>0){if("props"===t&&i[0]===r.valuePropName&&e!==s)return void r.emitValue({event:"ON_FIELD_CHANGE",value:n});const a=r[t];let l;return Array.isArray(a)||"object"==typeof a&&!be(a)?(l=ve(a),pe(l,i,n),void(r[t]=l)):void(this.config.defaultLogVerbose&&console.warn(`invalid template property, skipping evaluation of ${r.name} with ${a}`))}r[t]=n}else this.config.defaultLogVerbose&&console.warn(`failed to update field ${e}`)}extractParams(e){const t=function(e){const t=e.split(".");return t.length>1?this.getValue({scope:t[0],key:t[1],property:t[2],path:t.slice(3)}):t[0]}.bind(this),i=[];let s;for(;!be(s=b.exec(e));)i.push(s[1]);const n=i.map(e=>e.split(g)).map(e=>e.length<=1?{parse:!1,value:t(e[0])}:{parse:!0,value:e.filter(Boolean).reduce((e,i)=>{if(i.match(S))return`${e}${i}`;let s;const n=t(i);let r;try{r=JSON.parse(n)}catch(e){r=n}switch(typeof r){case"string":s=`\`${r}\``;break;case"boolean":case"undefined":case"number":default:s=r;break;case"object":if(null===r){s=null;break}if(r instanceof Date){s=`new Date(\`${r}\`)`;break}s=JSON.stringify(r)}return`${e}${s}`},"")});return n.map(({parse:t,value:i})=>{try{return t?new Function(`return ${i}`)():i}catch(t){return this.config.defaultLogVerbose&&(console.warn(`unhandled parsing on ${e} returning`),console.warn(i)),i}})}replaceExpression(e,t){return e.replace(b,()=>String(t.shift())||"")}hasStringConcatenation(e){return!m.test(e)}refreshTemplates({key:e,event:t}){this.subscribedTemplates.forEach(({destinationKey:i,destinationPath:s,destinationProperty:n,originExpression:r,originFieldKeys:a})=>{if(!e||a.includes(e)){const a=this.extractParams(r);let l;l=this.hasStringConcatenation(r)?this.replaceExpression(r,[...a]):null==a?void 0:a[0],me(this.getValue({scope:"fields",key:i,property:n,path:s}),l)||this.setValue({key:i,property:n,path:s,originKey:e,value:l,event:t})}})}checkFieldEventQueues(e){var t;if(null===(t=this.fields.get(e))||void 0===t?void 0:t.mounted){if(this.queuedFieldVisibilityEvents.has(e)&&(this.setFieldVisibility(Object.assign({field:e},this.queuedFieldVisibilityEvents.get(e))),this.queuedFieldVisibilityEvents.delete(e)),this.queuedInitialValues.has(e)){const t=this.queuedInitialValues.get(e);this.queuedInitialValues.delete(e),this.initialValues={[e]:t}}this.queuedFieldResetValuesEvents.has(e)&&(this.setResetFieldValue(Object.assign({key:e},this.queuedFieldResetValuesEvents.get(e))),this.queuedFieldResetValuesEvents.delete(e)),this.queuedFieldResetPropertyEvents.has(e)&&(this.setResetPathValue(Object.assign({key:e},this.queuedFieldResetPropertyEvents.get(e))),this.queuedFieldResetPropertyEvents.delete(e))}}setFieldVisibility({field:e,hasError:t,showOnlyIfTrue:i}){const s=this.fields.get(e);if(s&&s.mounted){const n=s.visibility,r=i?t:!t;if(s.visibility=r,n===r)return;s.visibility?this.queuedInitialValues.has(e)?(null==s||s.emitValue({value:this.queuedInitialValues.get(e)||"",event:"ON_FIELD_MOUNT"}),this.queuedInitialValues.delete(e)):s.emitEvents({event:"ON_FIELD_MOUNT"}):(s.emitEvents({event:"ON_FIELD_UNMOUNT"}),s.persistValue&&this.queuedInitialValues.set(s.name,s.value),s.value="",s.valid=!0)}else this.queuedFieldVisibilityEvents.set(e,{hasError:t,showOnlyIfTrue:i})}validateVisibility({event:e,key:t}){const i=this.fields.get(t),s=null==i?void 0:i.visibilityConditions;s&&(null==s?void 0:s.some(t=>t.events.includes(e)))&&s.forEach(t=>{t.events.includes(e)&&Object.keys(t.validations).forEach(e=>{const s=Oe(i.value,t.validations,N,e,this.formValuesStateSubject$.value);Array.isArray(t.fields)?t.fields.forEach(e=>{this.setFieldVisibility({field:e,hasError:s,showOnlyIfTrue:!(!i.value||!t.showOnlyIfTrue)})}):t.fields&&this.setFieldVisibility({field:t.fields,hasError:s,showOnlyIfTrue:!(!i.value||!t.showOnlyIfTrue)})})})}setResetFieldValue({key:e,value:t}){const i=this.fields.get(e);i&&(null==i?void 0:i.mounted)?i.emitValue({value:t,event:"ON_FIELD_CLEARED"}):this.queuedFieldResetValuesEvents.set(e,{value:t})}resetValue({event:e,key:t}){const i=this.fields.get(t),s=null==i?void 0:i.resetValues;s&&(null==s?void 0:s.some(t=>t.events.includes(e)))&&s.forEach(t=>{if(!t.events.includes(e))return;const s=()=>{Array.isArray(t.fields)?t.fields.forEach((e,i)=>{const s=Array.isArray(t.resettledValue)?t.resettledValue[i]:t.resettledValue;this.setResetFieldValue({key:e,value:s})}):t.fields&&this.setResetFieldValue({key:t.fields,value:t.resettledValue})};if(!t.validations)return s();Object.keys(t.validations).forEach(e=>{Oe(i.value,t.validations,N,e,this.formValuesStateSubject$.value)||s()})})}setResetPathValue({key:e,property:t,path:i,value:s}){this.fields.get(e)?this.setValue({key:e,property:t,path:i.split("."),value:s,event:"ON_RESET"}):this.queuedFieldResetPropertyEvents.set(e,{property:t,path:i,value:s})}resetProperty({event:e,key:t}){const i=this.fields.get(t),s=null==i?void 0:i.resetPropertyValues;s&&(null==s?void 0:s.some(t=>t.events.includes(e)))&&s.forEach(t=>{if(t.events.includes(e)&&$.includes(t.property))return t.validations?void Object.keys(t.validations).forEach(e=>{Oe(i.value,t.validations,N,e,this.formValuesStateSubject$.value)||this.setResetPathValue({key:t.field,path:t.path,property:t.property,value:t.resettledValue})}):this.setResetPathValue({key:t.field,path:t.path,property:t.property,value:t.resettledValue})})}addField({fieldSchema:e,mapperElement:t,path:i}){var s,n,r,a,l;if(this.fields.has(e.name))throw new Error(`field name ${e.name} already defined`);const o=t||(null===(s=this.mappers)||void 0===s?void 0:s.get(e.component));if(!o)throw new Error(`mapper not found for ${e.component}, add it to the mappers configuration`);if(null===(n=o.events)||void 0===n?void 0:n.setValue){const t=null===(r=null==e?void 0:e.props)||void 0===r?void 0:r[null===(a=null==o?void 0:o.events)||void 0===a?void 0:a.setValue];void 0===t||this.queuedInitialValues.has(e.name)||"string"==typeof t&&t.includes("${")||this.queuedInitialValues.set(e.name,ve(t))}if(this.fields.set(e.name,new Ie({formIndex:this.index,schemaComponent:e,mapper:o,children:e.children?e.children.map(e=>e.name):[],validateVisibility:this.validateVisibility.bind(this),resetValue:this.resetValue.bind(this),resetProperty:this.resetProperty.bind(this),formValuesStateSubject$:this.formValuesStateSubject$,templateSubject$:this.templateSubject$,fieldEventSubject$:this.fieldEventSubject$,dataSubject$:this.dataSubject$,fieldValidNotification$:this.fieldValidNotification$,mountSubject$:this.mountSubject$,config:this.config,submitEvent:this.submit.bind(this),visibility:e.visibility,persistValue:e.persistValue,path:i})),null===(l=this.prefetchedData)||void 0===l?void 0:l[e.name]){const t=this.fields.get(e.name);if(t){const i=this.prefetchedData[e.name],s=Object.assign({},t.api);void 0!==i.defaultResponse&&(s.default={response:i.defaultResponse,status:200}),i.namedResponses&&(s.named=s.named||{},Object.keys(i.namedResponses).forEach(e=>{s.named[e]={response:i.namedResponses[e],status:200}})),t._api=s}}}removeField({key:e}){var t;null===(t=this.fields.get(e))||void 0===t||t.destroyField(),this.fields.delete(e),this.subscribeTemplates(),this.templateSubject$.next({scope:"fields",key:e,event:"ON_FIELDS"}),this.validateForm()}serializeStructure(e,t){e&&e.forEach(e=>{var i;const s=this.fields.get(e.name);s?(s.children=(null===(i=null==e?void 0:e.children)||void 0===i?void 0:i.map(e=>e.name))||(null==s?void 0:s.children)||[],s.originalSchema=e,s.templateSubject$=this.templateSubject$):this.addField({fieldSchema:e,mapperElement:e.mapper,path:t}),e.children&&this.serializeStructure(e.children,`${t?`${t}.`:""}${e.name}`)})}refreshFields(e){const t=Array.from(this.fields.keys());this.serializeStructure(e);const i=Fe.checkIndexes(e);this.fields.forEach((e,t)=>{var s;i.includes(t)||(null===(s=this.fields.get(t))||void 0===s||s.destroyField(),this.fields.delete(t))}),this.subscribeTemplates(),this.fields.forEach((e,i)=>{var s;t.includes(i)||(null===(s=this.fields.get(i))||void 0===s||s.emitEvents({event:"ON_FIELD_MOUNT"}),this.checkFieldEventQueues(i))}),this.subscribedTemplates.forEach(e=>{e.originFieldKeys.forEach(e=>{this.templateSubject$.next({scope:"fields",key:e,event:"ON_FIELDS"})})})}getField({key:e}){return this.fields.get(e)}printValues(){console.table(this.formValuesStateSubject$.value.values)}getFormState(){const e={},t={},i=[];return this.fields.forEach((s,n)=>{"string"==typeof s.value&&0===s.value.length||null==s.value||(pe(e,s.nameToSubmit||n,s.value),t[n]=s.metadata),s.valid||i.push(n)}),{values:e,metadata:t,erroredFields:i,isValid:this.valid}}subscribeFieldEvent({callback:e}){return this.fieldEventSubject$.pipe(a(()=>this.submitChecker()),s(e=>`${e.event}|${e.fieldName}`),n(e=>e.pipe(r(this.config.defaultStateRefreshTimeMS)))).subscribe({next:e})}subscribeOnMount(e){return this.mountSubject$.pipe(u(()=>this.formValuesStateSubject$.value)).subscribe({next:e})}subscribeData(e){return this.dataSubject$.pipe(a(({formIndex:e})=>this.index===e&&this.submitChecker()),s(e=>e.event),n(e=>e.pipe(r(this.config.defaultStateRefreshTimeMS))),u(({fieldIndex:e})=>({field:e,data:this.formValuesStateSubject$.value}))).subscribe({next:e})}subscribeOnSubmit(e){return this.submitSubject$.pipe(a(({formIndex:e})=>e===this.index&&this.submitChecker()),u(({values:e})=>e)).subscribe({next:e})}subscribeFormValidation(e){return this.formValidSubject$.pipe(a(({formIndex:e})=>this.index===e),u(()=>({formIndex:this.index,valid:this.valid})),d("valid"),o({formIndex:this.index,valid:this.valid})).subscribe({next:e})}submit(){this.fields.forEach(e=>{e.emitEvents({event:"ON_FIELD_VALIDATION"})}),this.valid&&(this.submitSubject$.next({formIndex:this.index,values:this.formValuesStateSubject$.value}),this.submitted=!0)}destroy(){this.templateSubject$.unsubscribe(),this.templateSubscription$.unsubscribe(),this.mountSubject$.unsubscribe(),this.fieldEventSubject$.unsubscribe(),this.fieldValidNotification$.unsubscribe(),this.formValuesStateSubject$.unsubscribe(),this.isolatedFormInstance&&(this.submitSubject$.unsubscribe(),this.dataSubject$.unsubscribe(),this.formValidSubject$.unsubscribe()),this.fields.forEach(e=>e.destroyField())}}Fe.checkIndexes=(e,t=[])=>{if(!e)return t;const i=(e,t)=>{for(let s=0;s<e.length;s++){const n=e[s];t.push(n.name),n.children&&i(n.children,t)}};i(e,t);const s=t.filter((e,i)=>t.indexOf(e)!==i);if(s.length>0)throw new Error(`duplicated indexes found on schema: ${JSON.stringify(s)}`);return t};class ke{constructor(e){var i,s,n,r,a;this.destroy=()=>{this.forms.forEach(e=>e.destroy()),this.dataSubject$.unsubscribe(),this.formValidSubject$.unsubscribe(),this.submitSubject$.unsubscribe()},this.forms=new Map,this.config={defaultAPIdebounceTimeMS:Number(null===(i=null==e?void 0:e.config)||void 0===i?void 0:i.defaultAPIdebounceTimeMS)?Number(null===(s=null==e?void 0:e.config)||void 0===s?void 0:s.defaultAPIdebounceTimeMS):p,defaultStateRefreshTimeMS:Number(null===(n=null==e?void 0:e.config)||void 0===n?void 0:n.defaultStateRefreshTimeMS)?Number(null===(r=null==e?void 0:e.config)||void 0===r?void 0:r.defaultStateRefreshTimeMS):100,defaultLogVerbose:(null===(a=null==e?void 0:e.config)||void 0===a?void 0:a.defaultLogVerbose)?e.config.defaultLogVerbose:V},this.dataSubject$=new t,this.formValidSubject$=new t,this.submitSubject$=new t,this.mappers=null==e?void 0:e.mappers}createFormWithIndex({index:e,mappers:t}){this.addForm({key:e,params:{index:e,mappers:t,config:this.config}})}addForm({key:e,params:t}){this.checkIndexes({key:e});const i=new Fe(Object.assign(Object.assign({},t),{dataSubject$:this.dataSubject$,formValidSubject$:this.formValidSubject$,submitSubject$:this.submitSubject$}));i.config||(i.config=this.config),this.forms.set(e,i)}getForm({key:e}){return this.forms.get(e)}removeForm({key:e}){var t;null===(t=this.forms.get(e))||void 0===t||t.destroy(),this.forms.delete(e)}removeField({formIndex:e,fieldIndex:t}){const i=this.forms.get(e);null==i||i.removeField({key:t}),0===(null==i?void 0:i.fields.size)&&this.removeForm({key:e})}checkIndexes({key:e}){if(this.forms.has(e))throw new Error(`duplicate index ${e} on form group`)}printFormGroupInstance(){console.table(this.forms)}submitMultipleFormsByIndex(e,t){let i=!0,s={},n={},r=[];e.forEach(e=>{var t,a;null===(t=this.forms.get(e))||void 0===t||t.submit();const l=null===(a=this.forms.get(e))||void 0===a?void 0:a.formValuesStateSubject$.value,o="object"==typeof(null==l?void 0:l.metadata)&&null!==l.metadata?l.metadata:{};i=i&&((null==l?void 0:l.isValid)||!1),s=Object.assign(Object.assign({},s),(null==l?void 0:l.values)||{}),n=Object.assign(Object.assign({},n),o),r=[...r,...(null==l?void 0:l.erroredFields)||[]]}),i&&t&&t({erroredFields:r,isValid:i,values:s,metadata:n})}onDataSubscription({ids:e,callback:t}){return this.dataSubject$.pipe(a(({formIndex:t})=>e.includes(t)),s(({event:e,formIndex:t})=>`${e}.${t}`),n(e=>e.pipe(r(this.config.defaultStateRefreshTimeMS))),u(({fieldIndex:t,formIndex:i})=>e.reduce((e,s)=>{const n=this.forms.get(s);return n&&(e[s]={formId:i,formField:t,values:n.formValuesStateSubject$.value}),e},{}))).subscribe(t)}onValidSubscription({ids:e,callback:t}){return this.formValidSubject$.pipe(a(({formIndex:t})=>e.includes(t)),s(({formIndex:e})=>e),n(e=>e.pipe(r(0))),o({fieldTrigger:null}),u(()=>({groupValid:e.every(e=>{var t;return!this.forms.get(e)||(null===(t=this.forms.get(e))||void 0===t?void 0:t.valid)}),forms:e.reduce((e,t)=>{const i=this.forms.get(t);return i&&(e[t]=i.valid),e},{})}))).subscribe(t)}onSubmitSubscription({ids:e,callback:t}){return this.submitSubject$.pipe(a(({formIndex:t})=>e.includes(t)),u(()=>e.reduce((e,t)=>{const i=this.forms.get(t);return i&&(e[t]=i.formValuesStateSubject$.value),e},{}))).subscribe(t)}}export{Fe as FormCore,Ie as FormField,ke as FormGroup,v as TMutationEnum,x as formatterRegistry,O as maskRegistry,F as registerFormatters,k as registerMasks,I as registerValidations,N as validationRegistry};
|
package/package.json
CHANGED
|
@@ -1,7 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bolttech/form-engine-core",
|
|
3
|
-
"version": "1.1.
|
|
4
|
-
"sideEffects":
|
|
3
|
+
"version": "1.1.1",
|
|
4
|
+
"sideEffects": [
|
|
5
|
+
"./src/validations/handler.ts",
|
|
6
|
+
"./src/formatters/handler.ts",
|
|
7
|
+
"./src/masks/handler.ts",
|
|
8
|
+
"./src/index.ts",
|
|
9
|
+
"**/validations/handler*",
|
|
10
|
+
"**/formatters/handler*",
|
|
11
|
+
"**/masks/handler*",
|
|
12
|
+
"./index.esm.js"
|
|
13
|
+
],
|
|
5
14
|
"exports": {
|
|
6
15
|
".": {
|
|
7
16
|
"types": "./index.d.ts",
|
package/src/index.d.ts
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import './validations/handler';
|
|
2
|
+
import './formatters/handler';
|
|
3
|
+
import './masks/handler';
|
|
1
4
|
export * from './types/event';
|
|
2
5
|
export * from './types/form';
|
|
3
6
|
export * from './types/schema';
|
|
@@ -10,6 +13,3 @@ export * from './managers/form';
|
|
|
10
13
|
export * from './managers/formGroup';
|
|
11
14
|
export * from './managers/field';
|
|
12
15
|
export { registerValidations, registerFormatters, registerMasks, validationRegistry, formatterRegistry, maskRegistry } from './registry';
|
|
13
|
-
import './validations/handler';
|
|
14
|
-
import './formatters/handler';
|
|
15
|
-
import './masks/handler';
|
package/src/managers/field.d.ts
CHANGED
|
@@ -3,6 +3,9 @@ import { TApiConfig, TApiEvent, TApiResponse, TErrorMessages, TFormatters, TMask
|
|
|
3
3
|
import { IComponentSchema, IComponentSchemaAsFormField } from '../interfaces/schema';
|
|
4
4
|
import { IState } from '../interfaces/state';
|
|
5
5
|
import { TEvents, TFieldEvent, TFieldValidationPayload, TFormDataPayload, TValueChangeEvent } from '../types/event';
|
|
6
|
+
import '../validations/handler';
|
|
7
|
+
import '../formatters/handler';
|
|
8
|
+
import '../masks/handler';
|
|
6
9
|
import { TMapper } from '../types/mapper';
|
|
7
10
|
import { SafeSubject } from '../helpers/SafeSubject';
|
|
8
11
|
import { TTemplateEvent } from '../types/template';
|
package/src/managers/form.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { IFormField } from './field';
|
|
2
|
+
import '../validations/handler';
|
|
2
3
|
import { Subject, Subscription } from 'rxjs';
|
|
3
4
|
import { IComponentSchema, IComponentSchemaAsFormField, IFormSchema, TPrefetchedFieldData } from '../interfaces/schema';
|
|
4
5
|
import { TSchemaFormConfig } from '../types/schema';
|