@bolttech/form-engine-core 1.1.0-beta.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 +36 -0
- package/credit-card.d.ts +743 -0
- package/credit-card.esm.js +1 -0
- package/currency.d.ts +131 -0
- package/currency.esm.js +1 -0
- package/date.d.ts +582 -0
- package/date.esm.js +1 -0
- package/document.d.ts +527 -0
- package/document.esm.js +1 -0
- package/index.d.ts +2393 -0
- package/index.esm.js +1 -4435
- package/lite.d.ts +2393 -0
- package/lite.esm.js +1 -0
- package/package.json +50 -10
- package/src/constants/constants.d.ts +2 -1
- package/src/helpers/SafeSubject.d.ts +12 -2
- package/src/helpers/helpers.d.ts +6 -6
- package/src/helpers/lodash-replacements.d.ts +41 -0
- package/src/helpers/validation.d.ts +2 -1
- package/src/index.d.ts +5 -0
- package/src/interfaces/schema.d.ts +28 -1
- package/src/lite.d.ts +30 -0
- package/src/managers/field.d.ts +20 -3
- package/src/managers/form.d.ts +8 -2
- package/src/masks/currency.d.ts +29 -0
- package/src/masks/handler.d.ts +1 -1
- package/src/masks/string.d.ts +0 -62
- package/src/plugins/credit-card.d.ts +4 -0
- package/src/plugins/currency.d.ts +2 -0
- package/src/plugins/date.d.ts +2 -0
- package/src/plugins/document.d.ts +2 -0
- package/src/registry.d.ts +20 -0
- package/src/types/schema.d.ts +42 -23
- package/src/types/utility.d.ts +7 -4
- package/src/validations/custom.d.ts +3 -1
- package/index.esm.d.ts +0 -1
package/lite.esm.js
ADDED
|
@@ -0,0 +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)}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,15 +1,55 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bolttech/form-engine-core",
|
|
3
|
-
"version": "1.1.
|
|
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
|
+
],
|
|
14
|
+
"exports": {
|
|
15
|
+
".": {
|
|
16
|
+
"types": "./index.d.ts",
|
|
17
|
+
"import": "./index.esm.js",
|
|
18
|
+
"default": "./index.esm.js"
|
|
19
|
+
},
|
|
20
|
+
"./lite": {
|
|
21
|
+
"types": "./lite.d.ts",
|
|
22
|
+
"import": "./lite.esm.js",
|
|
23
|
+
"default": "./lite.esm.js"
|
|
24
|
+
},
|
|
25
|
+
"./credit-card": {
|
|
26
|
+
"types": "./credit-card.d.ts",
|
|
27
|
+
"import": "./credit-card.esm.js",
|
|
28
|
+
"default": "./credit-card.esm.js"
|
|
29
|
+
},
|
|
30
|
+
"./document": {
|
|
31
|
+
"types": "./document.d.ts",
|
|
32
|
+
"import": "./document.esm.js",
|
|
33
|
+
"default": "./document.esm.js"
|
|
34
|
+
},
|
|
35
|
+
"./currency": {
|
|
36
|
+
"types": "./currency.d.ts",
|
|
37
|
+
"import": "./currency.esm.js",
|
|
38
|
+
"default": "./currency.esm.js"
|
|
39
|
+
},
|
|
40
|
+
"./date": {
|
|
41
|
+
"types": "./date.d.ts",
|
|
42
|
+
"import": "./date.esm.js",
|
|
43
|
+
"default": "./date.esm.js"
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
"dependencies": {
|
|
47
|
+
"@gaignoux/currency": "^1.1.0",
|
|
48
|
+
"credit-card-type": "^10.0.0",
|
|
49
|
+
"rxjs": "7.8.2"
|
|
50
|
+
},
|
|
4
51
|
"module": "./index.esm.js",
|
|
5
52
|
"type": "module",
|
|
6
53
|
"main": "./index.esm.js",
|
|
7
|
-
"
|
|
8
|
-
|
|
9
|
-
"credit-card-type": "10.0.1",
|
|
10
|
-
"lodash": "4.17.21",
|
|
11
|
-
"react": "18.2.0",
|
|
12
|
-
"rxjs": "7.8.1"
|
|
13
|
-
},
|
|
14
|
-
"peerDependencies": {}
|
|
15
|
-
}
|
|
54
|
+
"types": "./index.d.ts"
|
|
55
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { IFormField } from "../managers/field";
|
|
1
2
|
declare const DEFAULT_API_DEBOUNCE_TIME = 1000;
|
|
2
3
|
declare const DEFAULT_STATE_REFRESH_TIME = 100;
|
|
3
4
|
declare const TEMPLATE_REGEX_STRING_CONCATENATION_DETECTOR: RegExp;
|
|
@@ -5,6 +6,6 @@ declare const TEMPLATE_REGEX_DELIMITATOR: RegExp;
|
|
|
5
6
|
declare const TEMPLATE_REGEX_OPERATOR_SPLITTER: RegExp;
|
|
6
7
|
declare const TEMPLATE_REGEX_OPERATOR_MATCHER: RegExp;
|
|
7
8
|
declare const TEMPLATE_AVALIABLE_SCOPES: readonly ["fields", "iVars", "form"];
|
|
8
|
-
declare const ALLOWED_RESET_PROPS_MUTATIONS: ("api" | "apiSchema" | "props" | "validations" | "visibilityConditions" | "resetValues")[];
|
|
9
|
+
declare const ALLOWED_RESET_PROPS_MUTATIONS: (keyof Pick<IFormField, "api" | "apiSchema" | "props" | "validations" | "visibilityConditions" | "resetValues">)[];
|
|
9
10
|
declare const DEFAULT_LOG_VERBOSE = false;
|
|
10
11
|
export { DEFAULT_API_DEBOUNCE_TIME, DEFAULT_STATE_REFRESH_TIME, DEFAULT_LOG_VERBOSE, TEMPLATE_REGEX_STRING_CONCATENATION_DETECTOR, TEMPLATE_REGEX_DELIMITATOR, TEMPLATE_REGEX_OPERATOR_SPLITTER, TEMPLATE_REGEX_OPERATOR_MATCHER, TEMPLATE_AVALIABLE_SCOPES, ALLOWED_RESET_PROPS_MUTATIONS, };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Subject } from 'rxjs';
|
|
1
|
+
import { BehaviorSubject, Subject } from 'rxjs';
|
|
2
2
|
/**
|
|
3
3
|
* Custom RXJS Subject to gracefully handle errors on unsubscribed Subjects
|
|
4
4
|
* that were unmounted due to adapter external handling such as visibility
|
|
@@ -8,4 +8,14 @@ declare class SafeSubject<T> extends Subject<T> {
|
|
|
8
8
|
constructor(isMounted: () => boolean);
|
|
9
9
|
next(value: T): void;
|
|
10
10
|
}
|
|
11
|
-
|
|
11
|
+
/**
|
|
12
|
+
* Custom RXJS BehaviourSubject to gracefully handle errors on unsubscribed Subjects
|
|
13
|
+
* since its fire and forget, no mount status needed to check if its available or not
|
|
14
|
+
*/
|
|
15
|
+
declare class SafeBehaviourSubject<T> extends BehaviorSubject<T> {
|
|
16
|
+
defaultValue: T;
|
|
17
|
+
constructor(value: T);
|
|
18
|
+
next(value: T): void;
|
|
19
|
+
get value(): T;
|
|
20
|
+
}
|
|
21
|
+
export { SafeSubject, SafeBehaviourSubject };
|
package/src/helpers/helpers.d.ts
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
/// <reference types="node" />
|
|
2
1
|
import { TApiResponsePayload } from '../types/schema';
|
|
3
2
|
import { TSubscribedTemplates, TTemplateAvaliableScopes } from '../types/template';
|
|
4
|
-
import { OutgoingHttpHeaders } from 'http2';
|
|
5
3
|
/**
|
|
6
|
-
* Makes an HTTP request using
|
|
4
|
+
* Makes an HTTP request using the Fetch API.
|
|
5
|
+
* Works in both browser and server (Node 18+) environments.
|
|
7
6
|
*
|
|
8
7
|
* @param {string} method - The HTTP method (GET, POST, PUT, DELETE, etc.).
|
|
9
8
|
* @param {string} url - The URL to which the request is sent.
|
|
10
|
-
* @param {
|
|
9
|
+
* @param {Record<string, string>} [headers] - Optional request headers.
|
|
11
10
|
* @param {Record<string,unknown>} [body] - Optional object body.
|
|
12
|
-
* @
|
|
11
|
+
* @param {Record<string, string>} [queryParams] - Optional query parameters.
|
|
12
|
+
* @returns {Promise<TApiResponsePayload>} A promise that resolves with the response text and status.
|
|
13
13
|
*
|
|
14
14
|
* @example
|
|
15
15
|
* ```typescript
|
|
16
16
|
* const response = await makeRequest('GET', 'https://api.example.com/data');
|
|
17
17
|
* ```
|
|
18
18
|
*/
|
|
19
|
-
declare function makeRequest(method: string, url: string, headers?:
|
|
19
|
+
declare function makeRequest(method: string, url: string, headers?: Record<string, string>, body?: Record<string, unknown>, queryParams?: Record<string, string>): Promise<TApiResponsePayload>;
|
|
20
20
|
/**
|
|
21
21
|
* Extracts keys enclosed in `${}` from a given expression.
|
|
22
22
|
*
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lightweight replacements for lodash functions used in form-engine-core.
|
|
3
|
+
* These cover the specific usage patterns in this codebase.
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* Deep clones a value. Handles objects, arrays, dates, and primitives.
|
|
7
|
+
* Equivalent to lodash/cloneDeep for the patterns used in this codebase.
|
|
8
|
+
*/
|
|
9
|
+
export declare function cloneDeep<T>(value: T): T;
|
|
10
|
+
/**
|
|
11
|
+
* Gets the value at a path of an object. If the resolved value is undefined,
|
|
12
|
+
* the defaultValue is returned in its place.
|
|
13
|
+
* Equivalent to lodash/get.
|
|
14
|
+
*/
|
|
15
|
+
export declare function get(obj: any, path: string | (string | number)[], defaultValue?: any): any;
|
|
16
|
+
/**
|
|
17
|
+
* Sets the value at a path of an object. If a portion of the path doesn't exist,
|
|
18
|
+
* it's created. Arrays are created for numeric keys, objects otherwise.
|
|
19
|
+
* Equivalent to lodash/set.
|
|
20
|
+
*/
|
|
21
|
+
export declare function set(obj: any, path: string | (string | number)[], value: any): any;
|
|
22
|
+
/**
|
|
23
|
+
* Performs a deep comparison between two values to determine if they are equivalent.
|
|
24
|
+
* Equivalent to lodash/isEqual for the patterns used in this codebase.
|
|
25
|
+
*/
|
|
26
|
+
export declare function isEqual(a: any, b: any): boolean;
|
|
27
|
+
/**
|
|
28
|
+
* Checks if value is null or undefined.
|
|
29
|
+
* Equivalent to lodash/isNil.
|
|
30
|
+
*/
|
|
31
|
+
export declare function isNil(value: any): value is null | undefined;
|
|
32
|
+
/**
|
|
33
|
+
* Checks if value is classified as a Function object.
|
|
34
|
+
* Equivalent to lodash/isFunction.
|
|
35
|
+
*/
|
|
36
|
+
export declare function isFunction(value: any): value is (...args: any[]) => any;
|
|
37
|
+
/**
|
|
38
|
+
* Checks if value is classified as a Number primitive or object.
|
|
39
|
+
* Equivalent to lodash/isNumber.
|
|
40
|
+
*/
|
|
41
|
+
export declare function isNumber(value: any): value is number;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { TSchemaValidation, TValidationMethods } from '../types/schema';
|
|
2
2
|
import { TValidationHandler } from '../types/utility';
|
|
3
|
+
import { TFormValues } from '../types/form';
|
|
3
4
|
/**
|
|
4
5
|
* @internal
|
|
5
6
|
* Handles the validation of a given value based on specified validation methods and rules.
|
|
@@ -24,4 +25,4 @@ import { TValidationHandler } from '../types/utility';
|
|
|
24
25
|
* const isValid = handleValidation(value, validations, methods, key);
|
|
25
26
|
* console.log(isValid); // Output: true
|
|
26
27
|
*/
|
|
27
|
-
export default function handleValidation(value: string | number | boolean | unknown, validations: TSchemaValidation, methods: TValidationHandler, key: keyof TValidationMethods): boolean;
|
|
28
|
+
export default function handleValidation(value: string | number | boolean | unknown, validations: TSchemaValidation, methods: TValidationHandler, key: keyof TValidationMethods, formValues: TFormValues<unknown>): boolean;
|
package/src/index.d.ts
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
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';
|
|
4
7
|
export * from './types/template';
|
|
5
8
|
export * from './types/mapper';
|
|
9
|
+
export * from './types/utility';
|
|
6
10
|
export * from './interfaces/schema';
|
|
7
11
|
export * from './interfaces/state';
|
|
8
12
|
export * from './managers/form';
|
|
9
13
|
export * from './managers/formGroup';
|
|
10
14
|
export * from './managers/field';
|
|
15
|
+
export { registerValidations, registerFormatters, registerMasks, validationRegistry, formatterRegistry, maskRegistry } from './registry';
|
|
@@ -130,5 +130,32 @@ interface IFormSchema {
|
|
|
130
130
|
iVars?: Record<string, unknown>;
|
|
131
131
|
components?: IComponentSchema[];
|
|
132
132
|
stopEventsOnSubmit?: boolean;
|
|
133
|
+
/** Pre-fetched API response data for SSR. Keys are field names, values contain the API responses to hydrate. */
|
|
134
|
+
prefetchedData?: Record<string, TPrefetchedFieldData>;
|
|
133
135
|
}
|
|
134
|
-
|
|
136
|
+
/**
|
|
137
|
+
* Represents pre-fetched API data for a single field.
|
|
138
|
+
* Used to hydrate API response caches during SSR so templates referencing API data resolve correctly.
|
|
139
|
+
*
|
|
140
|
+
* @property {unknown} [defaultResponse] - The pre-fetched response for the field's default API config.
|
|
141
|
+
* @property {Record<string, unknown>} [namedResponses] - Pre-fetched responses for named API configs.
|
|
142
|
+
*
|
|
143
|
+
* @example
|
|
144
|
+
* ```typescript
|
|
145
|
+
* const prefetchedData = {
|
|
146
|
+
* countryField: {
|
|
147
|
+
* defaultResponse: [{ id: 'BR', label: 'Brazil' }, { id: 'US', label: 'United States' }],
|
|
148
|
+
* },
|
|
149
|
+
* stateField: {
|
|
150
|
+
* namedResponses: { statesByCountry: [{ id: 'SP', label: 'São Paulo' }] },
|
|
151
|
+
* },
|
|
152
|
+
* };
|
|
153
|
+
* ```
|
|
154
|
+
*/
|
|
155
|
+
interface TPrefetchedFieldData {
|
|
156
|
+
/** The pre-fetched response for the field's default API config. */
|
|
157
|
+
defaultResponse?: unknown;
|
|
158
|
+
/** Pre-fetched responses keyed by named API config name. */
|
|
159
|
+
namedResponses?: Record<string, unknown>;
|
|
160
|
+
}
|
|
161
|
+
export { IFormSchema, IComponentSchema, IComponentSchemaAsFormField, TPrefetchedFieldData };
|
package/src/lite.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lite entry point for form-engine-core.
|
|
3
|
+
*
|
|
4
|
+
* This entry point excludes credit-card and document validation modules,
|
|
5
|
+
* reducing bundle size for consumers who don't need them.
|
|
6
|
+
*
|
|
7
|
+
* To add credit card support:
|
|
8
|
+
* import '@bolttech/form-engine-core/credit-card';
|
|
9
|
+
*
|
|
10
|
+
* To add document validation support:
|
|
11
|
+
* import '@bolttech/form-engine-core/document';
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```typescript
|
|
15
|
+
* import { FormCore, FormGroup } from '@bolttech/form-engine-core/lite';
|
|
16
|
+
* import '@bolttech/form-engine-core/credit-card'; // optional
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
export * from './types/event';
|
|
20
|
+
export * from './types/form';
|
|
21
|
+
export * from './types/schema';
|
|
22
|
+
export * from './types/template';
|
|
23
|
+
export * from './types/mapper';
|
|
24
|
+
export * from './types/utility';
|
|
25
|
+
export * from './interfaces/schema';
|
|
26
|
+
export * from './interfaces/state';
|
|
27
|
+
export * from './managers/form';
|
|
28
|
+
export * from './managers/formGroup';
|
|
29
|
+
export * from './managers/field';
|
|
30
|
+
export { registerValidations, registerFormatters, registerMasks, validationRegistry, formatterRegistry, maskRegistry } from './registry';
|
package/src/managers/field.d.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
|
-
import { Subject, Subscription } from 'rxjs';
|
|
1
|
+
import { Subject, Subscription, BehaviorSubject } from 'rxjs';
|
|
2
2
|
import { TApiConfig, TApiEvent, TApiResponse, TErrorMessages, TFormatters, TMasks, TResetPathMethods, TResetValueMethods, TSchemaFormConfig, TValidations, TVisibility } from '../types/schema';
|
|
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';
|
|
@@ -30,6 +33,7 @@ declare class FormField {
|
|
|
30
33
|
errorsString: string;
|
|
31
34
|
errorsList: string[];
|
|
32
35
|
private _props;
|
|
36
|
+
private _adapterProps;
|
|
33
37
|
private _value;
|
|
34
38
|
private _stateValue;
|
|
35
39
|
private _metadata;
|
|
@@ -55,6 +59,7 @@ declare class FormField {
|
|
|
55
59
|
key: string;
|
|
56
60
|
status: boolean;
|
|
57
61
|
}>;
|
|
62
|
+
formValuesStateSubject$: BehaviorSubject<TFormValues<unknown>>;
|
|
58
63
|
validateVisibility: (payload: {
|
|
59
64
|
event: TEvents;
|
|
60
65
|
key: string;
|
|
@@ -89,7 +94,7 @@ declare class FormField {
|
|
|
89
94
|
* @param {TMapper<unknown>} options.mapper, - component generic mapper containing render parameters for adapters
|
|
90
95
|
* @param {() => TFormValues<unknown>} options.getFormValues, - form instance function that builds onData parameter payload from fields
|
|
91
96
|
*/
|
|
92
|
-
constructor({ formIndex, schemaComponent, config,
|
|
97
|
+
constructor({ formIndex, schemaComponent, config, children, validateVisibility, resetValue, resetProperty, templateSubject$, fieldEventSubject$, dataSubject$, fieldValidNotification$, mountSubject$, mapper, formValuesStateSubject$, submitEvent, visibility, persistValue, }: {
|
|
93
98
|
formIndex: string;
|
|
94
99
|
schemaComponent: IComponentSchema;
|
|
95
100
|
config?: TSchemaFormConfig;
|
|
@@ -116,8 +121,8 @@ declare class FormField {
|
|
|
116
121
|
key: string;
|
|
117
122
|
status: boolean;
|
|
118
123
|
}>;
|
|
124
|
+
formValuesStateSubject$: BehaviorSubject<TFormValues<unknown>>;
|
|
119
125
|
mapper: TMapper<unknown>;
|
|
120
|
-
getFormValues: () => TFormValues<unknown>;
|
|
121
126
|
visibility?: boolean;
|
|
122
127
|
persistValue?: boolean;
|
|
123
128
|
});
|
|
@@ -127,6 +132,18 @@ declare class FormField {
|
|
|
127
132
|
* emissions to unsubscribed fields
|
|
128
133
|
*/
|
|
129
134
|
initializeObservers(): void;
|
|
135
|
+
/**
|
|
136
|
+
* Retrieves the raw props sent from the adapter.
|
|
137
|
+
*
|
|
138
|
+
* @returns {string} - raw props from the adapter
|
|
139
|
+
*/
|
|
140
|
+
get adapterProps(): string;
|
|
141
|
+
/**
|
|
142
|
+
* compares adapter props changes and emits the change if they effectively changed
|
|
143
|
+
* preventing an emission from the adapter of the same props that can overwrite other prop
|
|
144
|
+
* changes via templating
|
|
145
|
+
*/
|
|
146
|
+
set adapterProps(props: Record<string, unknown>);
|
|
130
147
|
/**
|
|
131
148
|
* Retrieves the properties associated with the form field.
|
|
132
149
|
*
|
package/src/managers/form.d.ts
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { IFormField } from './field';
|
|
2
|
+
import '../validations/handler';
|
|
2
3
|
import { Subject, Subscription } from 'rxjs';
|
|
3
|
-
import { IComponentSchema, IComponentSchemaAsFormField, IFormSchema } from '../interfaces/schema';
|
|
4
|
+
import { IComponentSchema, IComponentSchemaAsFormField, IFormSchema, TPrefetchedFieldData } from '../interfaces/schema';
|
|
4
5
|
import { TSchemaFormConfig } from '../types/schema';
|
|
5
6
|
import { TSubscribedTemplates, TTemplateAvaliableScopes, TTemplateEvent } from '../types/template';
|
|
6
7
|
import { TEvents, TFieldEvent, TFieldValidationPayload, TFormDataPayload, TFormSubmitPayload, TFormValidationPayload, TMutationEvents } from '../types/event';
|
|
7
8
|
import { TFormEntry, TFormValues } from '../types/form';
|
|
8
9
|
import { TMapper } from '../types/mapper';
|
|
10
|
+
import { SafeBehaviourSubject } from '../helpers/SafeSubject';
|
|
9
11
|
/**
|
|
10
12
|
* Represents the core logic for managing a form, including field management, validation, and submission.
|
|
11
13
|
*/
|
|
@@ -25,6 +27,7 @@ declare class FormCore {
|
|
|
25
27
|
dataSubject$: Subject<TFormDataPayload>;
|
|
26
28
|
formValidSubject$: Subject<TFormValidationPayload>;
|
|
27
29
|
fieldValidNotification$: Subject<TFieldValidationPayload>;
|
|
30
|
+
formValuesStateSubject$: SafeBehaviourSubject<TFormValues<unknown>>;
|
|
28
31
|
subscribedTemplates: TSubscribedTemplates[];
|
|
29
32
|
action?: string;
|
|
30
33
|
method?: string;
|
|
@@ -43,9 +46,12 @@ declare class FormCore {
|
|
|
43
46
|
value: unknown;
|
|
44
47
|
}>;
|
|
45
48
|
queuedInitialValues: Map<string, unknown>;
|
|
49
|
+
prefetchedData?: Record<string, TPrefetchedFieldData>;
|
|
46
50
|
_valid: boolean;
|
|
47
51
|
stopEventsOnSubmit: boolean;
|
|
48
52
|
submitted: boolean;
|
|
53
|
+
getFormValues: () => TFormValues<unknown>;
|
|
54
|
+
isolatedFormInstance: boolean;
|
|
49
55
|
/**
|
|
50
56
|
* Creates an instance of FormCore.
|
|
51
57
|
*
|
|
@@ -302,7 +308,7 @@ declare class FormCore {
|
|
|
302
308
|
*
|
|
303
309
|
* @returns {TFormValues} The current form values.
|
|
304
310
|
*/
|
|
305
|
-
|
|
311
|
+
getFormState<T>(): TFormValues<T>;
|
|
306
312
|
/**
|
|
307
313
|
* function to be called to events sent from the adapter
|
|
308
314
|
*
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { TMasks } from '../types/schema';
|
|
2
|
+
/**
|
|
3
|
+
* Formats a numeric value as a currency string based on the provided mask configuration.
|
|
4
|
+
*
|
|
5
|
+
* @param value - The numeric value to be formatted.
|
|
6
|
+
* @param masks - An object containing the mask configuration.
|
|
7
|
+
* @returns The formatted currency string.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```typescript
|
|
11
|
+
* import { currency } from './path/to/maskFunctions';
|
|
12
|
+
*
|
|
13
|
+
* const masks = {
|
|
14
|
+
* currency: {
|
|
15
|
+
* align: 'right',
|
|
16
|
+
* decimal: ',',
|
|
17
|
+
* precision: 2,
|
|
18
|
+
* prefix: 'USD',
|
|
19
|
+
* thousands: '.'
|
|
20
|
+
* }
|
|
21
|
+
* };
|
|
22
|
+
*
|
|
23
|
+
* const formattedValue = currency(12345.67, masks);
|
|
24
|
+
* console.log(formattedValue); // Output: '12.345,67 $'
|
|
25
|
+
*
|
|
26
|
+
* PS: To unCurrency this value, usage onlyFloatNumber formatter
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
export declare const currency: (value: string | number, masks: TMasks) => unknown;
|
package/src/masks/handler.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { TMasks } from '../types/schema';
|
|
2
|
-
export declare const masks: Record<
|
|
2
|
+
export declare const masks: Record<string, (value: unknown, masks?: TMasks | null) => unknown>;
|
package/src/masks/string.d.ts
CHANGED
|
@@ -14,63 +14,9 @@ import { TMasks } from '../types/schema';
|
|
|
14
14
|
*
|
|
15
15
|
* const maskedValue = replaceAll('12345', masks);
|
|
16
16
|
* console.log(maskedValue); // Output: '*****'
|
|
17
|
-
*
|
|
18
|
-
* // Using from a JSON config
|
|
19
|
-
* const config = {
|
|
20
|
-
* value: 'hello',
|
|
21
|
-
* masks: { replaceAll: '*' }
|
|
22
|
-
* };
|
|
23
|
-
*
|
|
24
|
-
* const maskedValue = replaceAll(config.value, config.masks);
|
|
25
|
-
* console.log(maskedValue); // Output: '*****'
|
|
26
17
|
* ```
|
|
27
18
|
*/
|
|
28
19
|
export declare const replaceAll: (value: string | number, masks: TMasks) => unknown;
|
|
29
|
-
/**
|
|
30
|
-
* Formats a numeric value as a currency string based on the provided mask configuration.
|
|
31
|
-
*
|
|
32
|
-
* @param value - The numeric value to be formatted.
|
|
33
|
-
* @param masks - An object containing the mask configuration.
|
|
34
|
-
* @returns The formatted currency string.
|
|
35
|
-
*
|
|
36
|
-
* @example
|
|
37
|
-
* ```typescript
|
|
38
|
-
* import { currency } from './path/to/maskFunctions';
|
|
39
|
-
*
|
|
40
|
-
* const masks = {
|
|
41
|
-
* currency: {
|
|
42
|
-
* align: 'right',
|
|
43
|
-
* decimal: ',',
|
|
44
|
-
* precision: 2,
|
|
45
|
-
* prefix: 'USD',
|
|
46
|
-
* thousands: '.'
|
|
47
|
-
* }
|
|
48
|
-
* };
|
|
49
|
-
*
|
|
50
|
-
* const formattedValue = currency(12345.67, masks);
|
|
51
|
-
* console.log(formattedValue); // Output: '12.345,67 $'
|
|
52
|
-
*
|
|
53
|
-
* // Using from a JSON config
|
|
54
|
-
* const config = {
|
|
55
|
-
* value: 9876.54,
|
|
56
|
-
* masks: {
|
|
57
|
-
* currency: {
|
|
58
|
-
* align: 'right',
|
|
59
|
-
* decimal: ',',
|
|
60
|
-
* precision: 2,
|
|
61
|
-
* prefix: 'EUR',
|
|
62
|
-
* thousands: '.'
|
|
63
|
-
* }
|
|
64
|
-
* }
|
|
65
|
-
* };
|
|
66
|
-
*
|
|
67
|
-
* const formattedValue = currency(config.value, config.masks);
|
|
68
|
-
* console.log(formattedValue); // Output: '9.876,54 €'
|
|
69
|
-
*
|
|
70
|
-
* PS: To unCurrency this value, usage onlyFloatNumber formatter
|
|
71
|
-
* ```
|
|
72
|
-
*/
|
|
73
|
-
export declare const currency: (value: string | number, masks: TMasks) => unknown;
|
|
74
20
|
/**
|
|
75
21
|
* Applies a custom mask to a string based on the provided mask configuration.
|
|
76
22
|
*
|
|
@@ -86,14 +32,6 @@ export declare const currency: (value: string | number, masks: TMasks) => unknow
|
|
|
86
32
|
*
|
|
87
33
|
* const maskedValue = custom('123456', masks);
|
|
88
34
|
* console.log(maskedValue); // Output: '12-34'
|
|
89
|
-
*
|
|
90
|
-
* // Using from a JSON config
|
|
91
|
-
* const config = {
|
|
92
|
-
* masks: { custom: '###-###' }
|
|
93
|
-
* };
|
|
94
|
-
*
|
|
95
|
-
* const maskedValue = custom(config.value, config.masks);
|
|
96
|
-
* console.log(maskedValue); // Output: '987-654'
|
|
97
35
|
* ```
|
|
98
36
|
*/
|
|
99
37
|
export declare const custom: (value: string, masks: TMasks) => string;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { isCreditCard, isCreditCardAndLength, isCreditCodeMatch } from '../validations/creditCard';
|
|
2
|
+
import { gapsCreditCard } from '../formatters/creditCard';
|
|
3
|
+
import { secureCreditCard, card, cardDate, fein } from '../masks/creditCard';
|
|
4
|
+
export { isCreditCard, isCreditCardAndLength, isCreditCodeMatch, gapsCreditCard, secureCreditCard, card, cardDate, fein, };
|