From 20b08fe6e86506ac4a3362f714930fa39c3173a2 Mon Sep 17 00:00:00 2001 From: 1on Date: Wed, 11 Nov 2020 11:56:00 +0300 Subject: [PATCH] 0.4.0 --- dist/formulario.esm.js | 1593 ++++++++++++++++++++++++++++++++++++++- dist/formulario.min.js | 11 +- dist/formulario.umd.js | 1600 +++++++++++++++++++++++++++++++++++++++- package.json | 2 +- 4 files changed, 3171 insertions(+), 35 deletions(-) diff --git a/dist/formulario.esm.js b/dist/formulario.esm.js index f7ee329..c672032 100644 --- a/dist/formulario.esm.js +++ b/dist/formulario.esm.js @@ -1,16 +1,1581 @@ -import e from"is-plain-object";import t from"is-url";import r from"vue";import{Model as i,Prop as o,Provide as s,Watch as a,Component as n,Inject as l}from"vue-property-decorator";function u(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function d(t,r,i=!0){const o={};for(const s in t)u(r,s)?e(r[s])&&e(t[s])?o[s]=d(t[s],r[s],i):i&&Array.isArray(t[s])&&Array.isArray(r[s])?o[s]=t[s].concat(r[s]):o[s]=r[s]:o[s]=t[s];for(const e in r)u(o,e)||(o[e]=r[e]);return o}function h(e){switch(typeof e){case"symbol":case"number":case"string":case"boolean":case"undefined":return!0;default:return null===e}}function c(e,t){if(e===t)return!0;if(!e||!t)return!1;const r=Object.keys(e);if(Object.keys(t).length!==r.length)return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(0===r.length)return e===t;for(let i=0;i0!==e.indexOf(t)&&"_"!==e[e.indexOf(t)-1]?t.toUpperCase().replace("_",""):t)}function p(e,t){const r=t.split(".");let i=e;for(const e in r){const t=r[e].match(/(.+)\[(\d+)\]$/);if(void 0===i)return null;if(t){if(i=i[t[1]],void 0===i)return null;i=i[t[2]]}else i=i[r[e]]}return i}var v={accepted:({value:e})=>Promise.resolve(["yes","on","1",1,!0,"true"].includes(e)),after({value:e},t=!1){const r=!1!==t?Date.parse(t):Date.now(),i=e instanceof Date?e.getTime():Date.parse(e);return Promise.resolve(!isNaN(i)&&i>r)},alpha({value:e},t="default"){const r={default:/^[a-zA-ZÀ-ÖØ-öø-ÿ]+$/,latin:/^[a-zA-Z]+$/},i=u(r,t)?t:"default";return Promise.resolve(r[i].test(e))},alphanumeric({value:e},t="default"){const r={default:/^[a-zA-Z0-9À-ÖØ-öø-ÿ]+$/,latin:/^[a-zA-Z0-9]+$/},i=u(r,t)?t:"default";return Promise.resolve(r[i].test(e))},before({value:e},t=!1){const r=!1!==t?Date.parse(t):Date.now(),i=e instanceof Date?e.getTime():Date.parse(e);return Promise.resolve(!isNaN(i)&&iPromise.resolve(null!==t&&null!==r&&!isNaN(t)&&!isNaN(r)&&(!isNaN(Number(e))&&"length"!==i||"value"===i?(e=Number(e),t=Number(t),r=Number(r),e>t&&et&&e.lengthPromise.resolve((()=>{let o=i;return o||(o=/_confirm$/.test(r)?r.substr(0,r.length-8):r+"_confirm"),t[o]===e})()),date:({value:e},t=!1)=>Promise.resolve(t?function(e){const t=`^${r=e,r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`;var r;const i={MM:"(0[1-9]|1[012])",M:"([1-9]|1[012])",DD:"([012][1-9]|3[01])",D:"([012]?[1-9]|3[01])",YYYY:"\\d{4}",YY:"\\d{2}"};return new RegExp(Object.keys(i).reduce((e,t)=>e.replace(t,i[t]),t))}(t).test(e):!isNaN(Date.parse(e))),email({value:e}){if(!e)return Promise.resolve(!0);return Promise.resolve(/^(([^<>()\[\].,;:\s@"]+(\.[^<>()\[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})$/i.test(e))},endsWith:({value:e},...t)=>e?"string"==typeof e?Promise.resolve(0===t.length||t.some(t=>e.endsWith(t))):Promise.resolve(!1):Promise.resolve(!0),in:({value:e},...t)=>Promise.resolve(t.some(t=>"object"==typeof t?c(t,e):t===e)),matches:({value:e},...t)=>Promise.resolve(!!t.find(t=>("string"==typeof t&&"/"===t.substr(0,1)&&"/"===t.substr(-1)&&(t=new RegExp(t.substr(1,t.length-2))),t instanceof RegExp?t.test(e):t===e))),max:({value:e},t=10,r)=>Promise.resolve(Array.isArray(e)?(t=isNaN(Number(t))?t:Number(t),e.length<=t):!isNaN(e)&&"length"!==r||"value"===r?(e=isNaN(e)?e:Number(e))<=t:("string"==typeof e||"length"===r)&&(e=isNaN(e)?e:e.toString()).length<=t),min:({value:e},t=1,r)=>Promise.resolve(Array.isArray(e)?(t=isNaN(t)?t:Number(t),e.length>=t):!isNaN(e)&&"length"!==r||"value"===r?(e=isNaN(e)?e:Number(e))>=t:("string"==typeof e||"length"===r)&&(e=isNaN(e)?e:e.toString()).length>=t),not:({value:e},...t)=>Promise.resolve(!t.some(t=>"object"==typeof t?c(t,e):t===e)),number:({value:e})=>Promise.resolve(String(e).length>0&&!isNaN(Number(e))),required:({value:e},t=!0)=>Promise.resolve(!(t&&!["no","false"].includes(t)&&(Array.isArray(e)?!e.length:"string"==typeof e?!e:!("object"!=typeof e||e&&Object.keys(e).length)))),startsWith:({value:e},...t)=>e?"string"==typeof e?Promise.resolve(0===t.length||t.some(t=>e.startsWith(t))):Promise.resolve(!1):Promise.resolve(!0),url:({value:e})=>Promise.resolve(t(e)),bail:()=>Promise.resolve(!0)},m={default:(e,t)=>e.$t("validation.default",t),accepted:(e,t)=>e.$t("validation.accepted",t),after:(e,t,r=!1)=>"string"==typeof r&&r.length?e.$t("validation.after.compare",t):e.$t("validation.after.default",t),alpha:(e,t)=>e.$t("validation.alpha",t),alphanumeric:(e,t)=>e.$t("validation.alphanumeric",t),before:(e,t,r=!1)=>"string"==typeof r&&r.length?e.$t("validation.before.compare",t):e.$t("validation.before.default",t),between(e,t,r=0,i=10,o){const s=Object.assign(Object.assign({},t),{from:r,to:i});return!isNaN(t.value)&&"length"!==o||"value"===o?e.$t("validation.between.force",s):e.$t("validation.between.default",s)},confirm:(e,t)=>e.$t("validation.confirm",t),date:(e,t,r=!1)=>"string"==typeof r&&r.length?e.$t("validation.date.format",t):e.$t("validation.date.default",t),email:(e,t)=>e.$t("validation.email.default",t),endsWith:(e,t)=>e.$t("validation.endsWith.default",t),in:function(e,t){return"string"==typeof t.value&&t.value?e.$t("validation.in.string",t):e.$t("validation.in.default",t)},matches:(e,t)=>e.$t("validation.matches.default",t),max:(e,t,r=10,i)=>Array.isArray(t.value)?e.$tc("validation.max.array",r,t):!isNaN(t.value)&&"length"!==i||"value"===i?e.$tc("validation.max.force",r,t):e.$tc("validation.max.default",r,t),min:(e,t,r=1,i)=>Array.isArray(t.value)?e.$tc("validation.min.array",r,t):!isNaN(t.value)&&"length"!==i||"value"===i?e.$tc("validation.min.force",r,t):e.$tc("validation.min.default",r,t),not:(e,t)=>e.$t("validation.not.default",t),number:(e,t)=>e.$t("validation.number.default",t),required:(e,t)=>e.$t("validation.required.default",t),startsWith:(e,t)=>e.$t("validation.startsWith.default",t),url:(e,t)=>e.$t("validation.url.default",t)}; -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. +import isPlainObject from 'is-plain-object'; +import isUrl from 'is-url'; +import Vue from 'vue'; +import { Model, Prop, Provide, Watch, Component, Inject } from 'vue-property-decorator'; -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. +/** + * Shorthand for Object.prototype.hasOwnProperty.call (space saving) + */ +function has(ctx, prop) { + return Object.prototype.hasOwnProperty.call(ctx, prop); +} -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -function g(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(i=Object.getOwnPropertySymbols(e);o=0;n--)(o=e[n])&&(a=(s<3?o(a):s>3?o(t,r,a):o(t,r))||a);return s>3&&a&&Object.defineProperty(t,r,a),a}class b{constructor(e){this.registry=new Map,this.ctx=e}add(e,t){this.registry.set(e,t)}remove(e){this.registry.delete(e);const t=this.ctx.proxy,r=e,i=(t[r],g(t,["symbol"==typeof r?r:r+""]));this.ctx.proxy=i}has(e){return this.registry.has(e)}hasNested(e){for(const t of this.registry.keys())if(t===e||t.includes(e+"."))return!0;return!1}get(e){return this.registry.get(e)}getNested(e){const t=new Map;for(const r of this.registry.keys()){const i=e+".",o=e+"[";r!==e&&r.substring(0,i.length)!==i&&r.substring(0,o.length)!==o||t.set(r,this.registry.get(r))}return t}forEach(e){this.registry.forEach((t,r)=>{e(t,r)})}keys(){return Array.from(this.registry.keys())}register(e,t){if(this.registry.has(e))return;this.registry.set(e,t);const r=u(t.$options.propsData||{},"value");!r&&this.ctx.hasInitialValue&&void 0!==p(this.ctx.initialValues,e)?t.context.model=p(this.ctx.initialValues,e):r&&!c(t.proxy,p(this.ctx.initialValues,e))&&this.ctx.setFieldValue(e,t.proxy)}reduce(e,t){return this.registry.forEach((r,i)=>{t=e(t,r,i)}),t}}class E{constructor(e=[]){this.observers=[],this.observers=e}add(e){this.observers.some(t=>t.callback===e.callback)||this.observers.push(e)}remove(e){this.observers=this.observers.filter(t=>t.callback!==e)}filter(e){return new E(this.observers.filter(e))}some(e){return this.observers.some(e)}observe(e){this.observers.forEach(t=>{"form"===t.type?t.callback(e):t.field&&!Array.isArray(e)&&u(e,t.field)&&t.callback(e[t.field])})}}let x=class extends r{constructor(){super(...arguments),this.path="",this.proxy={},this.registry=new b(this),this.errorObserverRegistry=new E,this.localFormErrors=[],this.localFieldErrors={}}get initialValues(){return this.hasModel&&"object"==typeof this.formularioValue?Object.assign({},this.formularioValue):{}}get mergedFormErrors(){return[...this.formErrors,...this.localFormErrors]}get mergedFieldErrors(){return d(this.errors||{},this.localFieldErrors)}get hasModel(){return u(this.$options.propsData||{},"formularioValue")}get hasInitialValue(){return this.formularioValue&&"object"==typeof this.formularioValue}onFormularioValueChanged(e){this.hasModel&&e&&"object"==typeof e&&this.setValues(e)}onMergedFormErrorsChanged(e){this.errorObserverRegistry.filter(e=>"form"===e.type).observe(e)}onMergedFieldErrorsChanged(e){this.errorObserverRegistry.filter(e=>"input"===e.type).observe(e)}created(){this.initProxy()}getFormValues(){return this.proxy}onFormSubmit(){return this.hasValidationErrors().then(e=>e?void 0:function e(t){if("object"!=typeof t)return t;const r=Array.isArray(t)?[]:{};for(const i in t)u(t,i)&&(r[i]=h(t[i])?t[i]:e(t[i]));return r}(this.proxy)).then(e=>{void 0!==e?this.$emit("submit",e):this.$emit("error")})}onFormularioFieldValidation(e){this.$emit("validation",e)}addErrorObserver(e){this.errorObserverRegistry.add(e),"form"===e.type?e.callback(this.mergedFormErrors):e.field&&u(this.mergedFieldErrors,e.field)&&e.callback(this.mergedFieldErrors[e.field])}removeErrorObserver(e){this.errorObserverRegistry.remove(e)}register(e,t){this.registry.register(e,t)}deregister(e){this.registry.remove(e)}initProxy(){this.hasInitialValue&&(this.proxy=this.initialValues)}setValues(e){const t=Array.from(new Set([...Object.keys(e),...Object.keys(this.proxy)]));let r=!1;t.forEach(t=>{this.registry.hasNested(t)&&this.registry.getNested(t).forEach((t,i)=>{const o=this.registry.get(i),s=p(this.proxy,i),a=p(e,i);c(a,s)||(this.setFieldValue(i,a,!1),r=!0),c(a,o.proxy)||(o.context.model=a)})}),this.initProxy(),r&&this.$emit("input",Object.assign({},this.proxy))}setFieldValue(e,t,r=!0){if(void 0===t){const t=this.proxy,r=e,i=(t[r],g(t,["symbol"==typeof r?r:r+""]));this.proxy=i}else!function(e,t,r){const i=t.split(".");let o=e;for(let e=0;e(e.push(t.runValidation()&&t.hasValidationErrors()),e),[])).then(e=>e.some(e=>e))}resetValidation(){this.localFormErrors=[],this.localFieldErrors={},this.registry.forEach(e=>{e.resetValidation()})}};function $(e,t,r,i,o,s,a,n,l,u){"boolean"!=typeof a&&(l=n,n=a,a=!1);const d="function"==typeof r?r.options:r;let h;if(e&&e.render&&(d.render=e.render,d.staticRenderFns=e.staticRenderFns,d._compiled=!0,o&&(d.functional=!0)),i&&(d._scopeId=i),s?(h=function(e){(e=e||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(e=__VUE_SSR_CONTEXT__),t&&t.call(this,l(e)),e&&e._registeredComponents&&e._registeredComponents.add(s)},d._ssrRegister=h):t&&(h=a?function(e){t.call(this,u(e,this.$root.$options.shadowRoot))}:function(e){t.call(this,n(e))}),h)if(d.functional){const e=d.render;d.render=function(t,r){return h.call(r),e(t,r)}}else{const e=d.beforeCreate;d.beforeCreate=e?[].concat(e,h):[h]}return r}y([i("input",{default:()=>({})})],x.prototype,"formularioValue",void 0),y([o({default:()=>({})})],x.prototype,"errors",void 0),y([o({default:()=>[]})],x.prototype,"formErrors",void 0),y([s()],x.prototype,"path",void 0),y([a("formularioValue",{deep:!0})],x.prototype,"onFormularioValueChanged",null),y([a("mergedFormErrors")],x.prototype,"onMergedFormErrorsChanged",null),y([a("mergedFieldErrors",{deep:!0,immediate:!0})],x.prototype,"onMergedFieldErrorsChanged",null),y([s()],x.prototype,"getFormValues",null),y([s()],x.prototype,"onFormularioFieldValidation",null),y([s()],x.prototype,"addErrorObserver",null),y([s()],x.prototype,"removeErrorObserver",null),y([s("formularioRegister")],x.prototype,"register",null),y([s("formularioDeregister")],x.prototype,"deregister",null),y([s("formularioSetter")],x.prototype,"setFieldValue",null),x=y([n({name:"FormularioForm"})],x);const N=x;var F=function(){var e=this,t=e.$createElement;return(e._self._c||t)("form",{on:{submit:function(t){return t.preventDefault(),e.onFormSubmit(t)}}},[e._t("default",null,{errors:e.mergedFormErrors})],2)};F._withStripped=!0;const V=$({render:F,staticRenderFns:[]},void 0,N,void 0,!1,void 0,!1,void 0,void 0,void 0);let O=class extends r{get groupPath(){return this.isArrayItem?`${this.path}[${this.name}]`:""===this.path?this.name:`${this.path}.${this.name}`}};y([l({default:""})],O.prototype,"path",void 0),y([o({required:!0})],O.prototype,"name",void 0),y([o({default:!1})],O.prototype,"isArrayItem",void 0),y([s("path")],O.prototype,"groupPath",null),O=y([n({name:"FormularioGrouping"})],O);const P=O;var R=function(){var e=this.$createElement;return(this._self._c||e)("div",[this._t("default")],2)};R._withStripped=!0;const j=$({render:R,staticRenderFns:[]},void 0,P,void 0,!1,void 0,!1,void 0,void 0,void 0);function w(e,t,r,i){return o=>Promise.resolve(e(o,...r)).then(e=>e?null:{rule:t,args:r,context:o,message:i(o,...r)})}function A(e){return/^[\^]/.test(e.charAt(0))?[f(e.substr(1)),e.charAt(0)]:[f(e),null]}function _(e,t,r){return"function"==typeof e?[e,null,null]:Array.isArray(e)&&e.length?function(e,t,r){const i=e.slice(),o=i.shift();if("function"==typeof o)return[o,null,null];if("string"!=typeof o)throw new Error("[Formulario]: For array constraint first element must be rule name or Validator function");const[s,a]=A(o);if(u(t,s))return[w(t[s],s,i,r[s]||r.default),s,a];throw new Error("[Formulario] Can't create validator for constraint: "+JSON.stringify(e))}(e,t,r):"string"==typeof e?function(e,t,r){const i=e.split(":"),[o,s]=A(i.shift()||"");if(u(t,o))return[w(t[o],o,i.length?i.join(":").split(","):[],r[o]||r.default),o,s];throw new Error("[Formulario] Can't create validator for constraint: "+e)}(e,t,r):[()=>Promise.resolve(null),null,null]}function D(e){const t=[];if(e.length){let r=e.shift();t.push(r),e.forEach(e=>{e.bail||e.bail!==r.bail?(r=Object.assign({},e),t.push(r)):r.validators.push(...e.validators)})}return t}function M(e,t){return new Promise(r=>{const i=(e,o=[])=>{if(e.length){const s=e.shift();(function(e,t){return Promise.all(e.validators.map(e=>e(t))).then(e=>e.filter(e=>null!==e))})(s,t).then(t=>0!==t.length&&s.bail||!e.length?r(o.concat(t)):i(e,o.concat(t)))}else r([])};i(function(e){const t=([e,,t])=>({validators:[e],bail:"^"===t}),r=[],i=e.findIndex(([,e])=>e&&"bail"===e.toLowerCase());return i>=0?(r.push(...D(e.splice(0,i+1).slice(0,-1).map(t))),r.push(...e.map(([e])=>({validators:[e],bail:!0})))):r.push(...D(e.map(t))),r}(e))})}const k={DEMAND:"demand",LIVE:"live",SUBMIT:"submit"};let C=class extends r{constructor(){super(...arguments),this.proxy=this.getInitialValue(),this.localErrors=[],this.violations=[],this.validationRun=Promise.resolve()}get fullQualifiedName(){return""!==this.path?`${this.path}.${this.name}`:this.name}get model(){const e=this.hasModel?"value":"proxy";return void 0===this[e]?"":this[e]}set model(e){c(e,this.proxy)||(this.proxy=e),this.$emit("input",e),"function"==typeof this.formularioSetter&&this.formularioSetter(this.context.name,e)}get context(){return Object.defineProperty({name:this.fullQualifiedName,runValidation:this.runValidation.bind(this),violations:this.violations,errors:this.localErrors,allErrors:[...this.localErrors,...this.violations.map(e=>e.message)]},"model",{get:()=>this.model,set:e=>{this.model=e}})}get normalizedValidationRules(){const e={};return Object.keys(this.validationRules).forEach(t=>{e[f(t)]=this.validationRules[t]}),e}get normalizedValidationMessages(){const e={};return Object.keys(this.validationMessages).forEach(t=>{e[f(t)]=this.validationMessages[t]}),e}get hasModel(){return u(this.$options.propsData||{},"value")}onProxyChanged(e,t){this.hasModel||c(e,t)||(this.context.model=e),this.validationBehavior===k.LIVE?this.runValidation():this.violations=[]}onValueChanged(e,t){this.hasModel&&!c(e,t)&&(this.context.model=e)}created(){this.initProxy(),"function"==typeof this.formularioRegister&&this.formularioRegister(this.fullQualifiedName,this),"function"!=typeof this.addErrorObserver||this.errorsDisabled||this.addErrorObserver({callback:this.setErrors,type:"input",field:this.fullQualifiedName}),this.validationBehavior===k.LIVE&&this.runValidation()}beforeDestroy(){this.errorsDisabled||"function"!=typeof this.removeErrorObserver||this.removeErrorObserver(this.setErrors),"function"==typeof this.formularioDeregister&&this.formularioDeregister(this.fullQualifiedName)}getInitialValue(){return u(this.$options.propsData||{},"value")?this.value:""}initProxy(){c(this.context.model,this.proxy)||(this.context.model=this.proxy)}runValidation(){return this.validationRun=this.validate().then(e=>{const t=!c(e,this.violations);if(this.violations=e,t){const e={name:this.context.name,violations:this.violations};this.$emit("validation",e),"function"==typeof this.onFormularioFieldValidation&&this.onFormularioFieldValidation(e)}return this.violations}),this.validationRun}validate(){return M(function e(t,r,i){return"string"==typeof t?e(t.split("|").filter(e=>e.length),r,i):Array.isArray(t)?t.map(e=>_(e,r,i)):[]}(this.validation,this.$formulario.getRules(this.normalizedValidationRules),this.$formulario.getMessages(this,this.normalizedValidationMessages)),{value:this.context.model,name:this.context.name,formValues:this.getFormValues()})}hasValidationErrors(){return new Promise(e=>{this.$nextTick(()=>{this.validationRun.then(()=>e(this.violations.length>0))})})}setErrors(e){var t;this.localErrors=(t=e)?"string"==typeof t?[t]:Array.isArray(t)?t:"object"==typeof t?Object.values(t):[]:[]}resetValidation(){this.localErrors=[],this.violations=[]}};y([l({default:void 0})],C.prototype,"formularioSetter",void 0),y([l({default:()=>()=>{}})],C.prototype,"onFormularioFieldValidation",void 0),y([l({default:void 0})],C.prototype,"formularioRegister",void 0),y([l({default:void 0})],C.prototype,"formularioDeregister",void 0),y([l({default:()=>()=>({})})],C.prototype,"getFormValues",void 0),y([l({default:void 0})],C.prototype,"addErrorObserver",void 0),y([l({default:void 0})],C.prototype,"removeErrorObserver",void 0),y([l({default:""})],C.prototype,"path",void 0),y([i("input",{default:""})],C.prototype,"value",void 0),y([o({required:!0,validator:e=>"string"==typeof e&&e.length>0})],C.prototype,"name",void 0),y([o({default:""})],C.prototype,"validation",void 0),y([o({default:()=>({})})],C.prototype,"validationRules",void 0),y([o({default:()=>({})})],C.prototype,"validationMessages",void 0),y([o({default:k.DEMAND,validator:e=>Object.values(k).includes(e)})],C.prototype,"validationBehavior",void 0),y([o({default:!1})],C.prototype,"errorsDisabled",void 0),y([a("proxy")],C.prototype,"onProxyChanged",null),y([a("value")],C.prototype,"onValueChanged",null),C=y([n({name:"FormularioInput",inheritAttrs:!1})],C);const S=C;var I=function(){var e=this.$createElement;return(this._self._c||e)("div",{staticClass:"formulario-input"},[this._t("default",null,{context:this.context})],2)};I._withStripped=!0;const T=$({render:I,staticRenderFns:[]},void 0,S,void 0,!1,void 0,!1,void 0,void 0,void 0);var z=new class{constructor(){this.validationRules={},this.validationMessages={},this.validationRules=v,this.validationMessages=m}install(e,t){e.prototype.$formulario=this,e.component("FormularioForm",V),e.component("FormularioGrouping",j),e.component("FormularioInput",T),this.extend(t||{})}extend(e){if("object"==typeof e)return this.validationRules=d(this.validationRules,e.validationRules||{}),this.validationMessages=d(this.validationMessages,e.validationMessages||{}),this;throw new Error(`[Formulario]: Formulario.extend() should be passed an object (was ${typeof e})`)}getRules(e={}){return d(this.validationRules,e)}getMessages(e,t){const r=d(this.validationMessages||{},t),i={};for(const t in r)i[t]=(i,...o)=>"string"==typeof r[t]?r[t]:r[t](e,i,...o);return i}};export default z; +/** + * Create a new object by copying properties of base and mergeWith. + * Note: arrays don't overwrite - they push + * + * @param {Object} a + * @param {Object} b + * @param {boolean} concatArrays + */ +function merge(a, b, concatArrays = true) { + const merged = {}; + for (const key in a) { + if (has(b, key)) { + if (isPlainObject(b[key]) && isPlainObject(a[key])) { + merged[key] = merge(a[key], b[key], concatArrays); + } + else if (concatArrays && Array.isArray(a[key]) && Array.isArray(b[key])) { + merged[key] = a[key].concat(b[key]); + } + else { + merged[key] = b[key]; + } + } + else { + merged[key] = a[key]; + } + } + for (const prop in b) { + if (!has(merged, prop)) { + merged[prop] = b[prop]; + } + } + return merged; +} + +/** + * Converts to array. + * If given parameter is not string, object ot array, result will be an empty array. + * @param {*} item + */ +function arrayify(item) { + if (!item) { + return []; + } + if (typeof item === 'string') { + return [item]; + } + if (Array.isArray(item)) { + return item; + } + if (typeof item === 'object') { + return Object.values(item); + } + return []; +} + +function isScalar(data) { + switch (typeof data) { + case 'symbol': + case 'number': + case 'string': + case 'boolean': + case 'undefined': + return true; + default: + return data === null; + } +} + +/** + * A simple (somewhat non-comprehensive) clone function, valid for our use + * case of needing to unbind reactive watchers. + */ +function clone(value) { + if (typeof value !== 'object') { + return value; + } + const copy = Array.isArray(value) ? [] : {}; + for (const key in value) { + if (has(value, key)) { + if (isScalar(value[key])) { + copy[key] = value[key]; + } + else if (value instanceof Date) { + copy[key] = new Date(copy[key]); + } + else { + copy[key] = clone(value[key]); + } + } + } + return copy; +} + +/** + * Escape a string for use in regular expressions. + */ +function escapeRegExp(string) { + return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string +} +/** + * Given a string format (date) return a regex to match against. + */ +function regexForFormat(format) { + const escaped = `^${escapeRegExp(format)}$`; + const formats = { + MM: '(0[1-9]|1[012])', + M: '([1-9]|1[012])', + DD: '([012][1-9]|3[01])', + D: '([012]?[1-9]|3[01])', + YYYY: '\\d{4}', + YY: '\\d{2}' + }; + return new RegExp(Object.keys(formats).reduce((regex, format) => { + return regex.replace(format, formats[format]); + }, escaped)); +} + +function shallowEqualObjects(objA, objB) { + if (objA === objB) { + return true; + } + if (!objA || !objB) { + return false; + } + const aKeys = Object.keys(objA); + const bKeys = Object.keys(objB); + if (bKeys.length !== aKeys.length) { + return false; + } + if (objA instanceof Date && objB instanceof Date) { + return objA.getTime() === objB.getTime(); + } + if (aKeys.length === 0) { + return objA === objB; + } + for (let i = 0; i < aKeys.length; i++) { + const key = aKeys[i]; + if (objA[key] !== objB[key]) { + return false; + } + } + return true; +} + +/** + * Given a string, convert snake_case to camelCase + */ +function snakeToCamel(string) { + return string.replace(/([_][a-z0-9])/ig, ($1) => { + if (string.indexOf($1) !== 0 && string[string.indexOf($1) - 1] !== '_') { + return $1.toUpperCase().replace('_', ''); + } + return $1; + }); +} + +function getNested(obj, field) { + const fieldParts = field.split('.'); + let result = obj; + for (const key in fieldParts) { + const matches = fieldParts[key].match(/(.+)\[(\d+)\]$/); + if (result === undefined) { + return null; + } + if (matches) { + result = result[matches[1]]; + if (result === undefined) { + return null; + } + result = result[matches[2]]; + } + else { + result = result[fieldParts[key]]; + } + } + return result; +} +function setNested(obj, field, value) { + const fieldParts = field.split('.'); + let subProxy = obj; + for (let i = 0; i < fieldParts.length; i++) { + const fieldPart = fieldParts[i]; + const matches = fieldPart.match(/(.+)\[(\d+)\]$/); + if (matches) { + if (subProxy[matches[1]] === undefined) { + subProxy[matches[1]] = []; + } + subProxy = subProxy[matches[1]]; + if (i === fieldParts.length - 1) { + subProxy[matches[2]] = value; + break; + } + else { + subProxy = subProxy[matches[2]]; + } + } + else { + if (subProxy === undefined) { + break; + } + if (i === fieldParts.length - 1) { + subProxy[fieldPart] = value; + break; + } + else { + // eslint-disable-next-line max-depth + if (subProxy[fieldPart] === undefined) { + subProxy[fieldPart] = {}; + } + subProxy = subProxy[fieldPart]; + } + } + } +} + +const rules = { + /** + * Rule: the value must be "yes", "on", "1", or true + */ + accepted({ value }) { + return ['yes', 'on', '1', 1, true, 'true'].includes(value); + }, + /** + * Rule: checks if a value is after a given date. Defaults to current time + */ + after({ value }, compare = false) { + const compareTimestamp = compare !== false ? Date.parse(compare) : Date.now(); + const valueTimestamp = value instanceof Date ? value.getTime() : Date.parse(value); + return isNaN(valueTimestamp) ? false : (valueTimestamp > compareTimestamp); + }, + /** + * Rule: checks if the value is only alpha + */ + alpha({ value }, set = 'default') { + const sets = { + default: /^[a-zA-ZÀ-ÖØ-öø-ÿ]+$/, + latin: /^[a-zA-Z]+$/, + }; + return typeof value === 'string' && sets[has(sets, set) ? set : 'default'].test(value); + }, + /** + * Rule: checks if the value is alpha numeric + */ + alphanumeric({ value }, set = 'default') { + const sets = { + default: /^[a-zA-Z0-9À-ÖØ-öø-ÿ]+$/, + latin: /^[a-zA-Z0-9]+$/ + }; + return typeof value === 'string' && sets[has(sets, set) ? set : 'default'].test(value); + }, + /** + * Rule: checks if a value is after a given date. Defaults to current time + */ + before({ value }, compare = false) { + const compareTimestamp = compare !== false ? Date.parse(compare) : Date.now(); + const valueTimestamp = value instanceof Date ? value.getTime() : Date.parse(value); + return isNaN(valueTimestamp) ? false : (valueTimestamp < compareTimestamp); + }, + /** + * Rule: checks if the value is between two other values + */ + between({ value }, from = 0, to = 10, force) { + if (from === null || to === null || isNaN(from) || isNaN(to)) { + return false; + } + if ((!isNaN(Number(value)) && force !== 'length') || force === 'value') { + value = Number(value); + return (value > Number(from) && value < Number(to)); + } + if (typeof value === 'string' || force === 'length') { + value = (!isNaN(Number(value)) ? value.toString() : value); + return value.length > from && value.length < to; + } + return false; + }, + /** + * Confirm that the value of one field is the same as another, mostly used + * for password confirmations. + */ + confirm({ value, formValues, name }, field) { + let confirmationFieldName = field; + if (!confirmationFieldName) { + confirmationFieldName = /_confirm$/.test(name) ? name.substr(0, name.length - 8) : `${name}_confirm`; + } + return formValues[confirmationFieldName] === value; + }, + /** + * Rule: ensures the value is a date according to Date.parse(), or a format + * regex. + */ + date({ value }, format = false) { + return format ? regexForFormat(format).test(value) : !isNaN(Date.parse(value)); + }, + /** + * Rule: tests + */ + email({ value }) { + if (!value) { + return true; + } + // eslint-disable-next-line + const isEmail = /^(([^<>()\[\].,;:\s@"]+(\.[^<>()\[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})$/i; + return isEmail.test(value); + }, + /** + * Rule: Value ends with one of the given Strings + */ + endsWith({ value }, ...stack) { + if (!value) { + return true; + } + if (typeof value === 'string') { + return stack.length === 0 || stack.some(str => value.endsWith(str)); + } + return false; + }, + /** + * Rule: Value is in an array (stack). + */ + in({ value }, ...stack) { + return stack.some(item => typeof item === 'object' ? shallowEqualObjects(item, value) : item === value); + }, + /** + * Rule: Match the value against a (stack) of patterns or strings + */ + matches({ value }, ...stack) { + return !!stack.find(pattern => { + if (typeof pattern === 'string' && pattern.substr(0, 1) === '/' && pattern.substr(-1) === '/') { + pattern = new RegExp(pattern.substr(1, pattern.length - 2)); + } + if (pattern instanceof RegExp) { + return pattern.test(value); + } + return pattern === value; + }); + }, + /** + * Check the maximum value of a particular. + */ + max({ value }, maximum = 10, force) { + if (Array.isArray(value)) { + maximum = !isNaN(Number(maximum)) ? Number(maximum) : maximum; + return value.length <= maximum; + } + if ((!isNaN(value) && force !== 'length') || force === 'value') { + value = !isNaN(value) ? Number(value) : value; + return value <= maximum; + } + if (typeof value === 'string' || (force === 'length')) { + value = !isNaN(value) ? value.toString() : value; + return value.length <= maximum; + } + return false; + }, + /** + * Check the minimum value of a particular. + */ + min({ value }, minimum = 1, force) { + if (Array.isArray(value)) { + minimum = !isNaN(minimum) ? Number(minimum) : minimum; + return value.length >= minimum; + } + if ((!isNaN(value) && force !== 'length') || force === 'value') { + value = !isNaN(value) ? Number(value) : value; + return value >= minimum; + } + if (typeof value === 'string' || (force === 'length')) { + value = !isNaN(value) ? value.toString() : value; + return value.length >= minimum; + } + return false; + }, + /** + * Rule: Value is not in stack. + */ + not({ value }, ...stack) { + return !stack.some(item => typeof item === 'object' ? shallowEqualObjects(item, value) : item === value); + }, + /** + * Rule: checks if the value is only alpha numeric + */ + number({ value }) { + return String(value).length > 0 && !isNaN(Number(value)); + }, + /** + * Rule: must be a value + */ + required({ value }, isRequired = true) { + if (!isRequired || ['no', 'false'].includes(isRequired)) { + return true; + } + if (Array.isArray(value)) { + return !!value.length; + } + if (typeof value === 'string') { + return !!value; + } + if (typeof value === 'object') { + return (!value) ? false : !!Object.keys(value).length; + } + return true; + }, + /** + * Rule: Value starts with one of the given Strings + */ + startsWith({ value }, ...stack) { + if (!value) { + return true; + } + if (typeof value === 'string') { + return stack.length === 0 || stack.some(str => value.startsWith(str)); + } + return false; + }, + /** + * Rule: checks if a string is a valid url + */ + url({ value }) { + return isUrl(value); + }, + /** + * Rule: not a true rule — more like a compiler flag. + */ + bail() { + return true; + }, +}; + +/** + * Message builders, names match rules names, see @/validation/rules + */ +const messages = { + /** + * Fallback for rules without message builder + * @param vm + * @param context + */ + default(vm, context) { + return vm.$t('validation.default', context); + }, + accepted(vm, context) { + return vm.$t('validation.accepted', context); + }, + after(vm, context, compare = false) { + if (typeof compare === 'string' && compare.length) { + return vm.$t('validation.after.compare', context); + } + return vm.$t('validation.after.default', context); + }, + alpha(vm, context) { + return vm.$t('validation.alpha', context); + }, + alphanumeric(vm, context) { + return vm.$t('validation.alphanumeric', context); + }, + before(vm, context, compare = false) { + if (typeof compare === 'string' && compare.length) { + return vm.$t('validation.before.compare', context); + } + return vm.$t('validation.before.default', context); + }, + between(vm, context, from = 0, to = 10, force) { + const data = Object.assign(Object.assign({}, context), { from, to }); + if ((!isNaN(context.value) && force !== 'length') || force === 'value') { + return vm.$t('validation.between.force', data); + } + return vm.$t('validation.between.default', data); + }, + confirm(vm, context) { + return vm.$t('validation.confirm', context); + }, + date(vm, context, format = false) { + if (typeof format === 'string' && format.length) { + return vm.$t('validation.date.format', context); + } + return vm.$t('validation.date.default', context); + }, + email(vm, context) { + return vm.$t('validation.email.default', context); + }, + endsWith(vm, context) { + return vm.$t('validation.endsWith.default', context); + }, + in(vm, context) { + if (typeof context.value === 'string' && context.value) { + return vm.$t('validation.in.string', context); + } + return vm.$t('validation.in.default', context); + }, + matches(vm, context) { + return vm.$t('validation.matches.default', context); + }, + max(vm, context, maximum = 10, force) { + if (Array.isArray(context.value)) { + return vm.$tc('validation.max.array', maximum, context); + } + if ((!isNaN(context.value) && force !== 'length') || force === 'value') { + return vm.$tc('validation.max.force', maximum, context); + } + return vm.$tc('validation.max.default', maximum, context); + }, + min(vm, context, minimum = 1, force) { + if (Array.isArray(context.value)) { + return vm.$tc('validation.min.array', minimum, context); + } + if ((!isNaN(context.value) && force !== 'length') || force === 'value') { + return vm.$tc('validation.min.force', minimum, context); + } + return vm.$tc('validation.min.default', minimum, context); + }, + not(vm, context) { + return vm.$t('validation.not.default', context); + }, + number(vm, context) { + return vm.$t('validation.number.default', context); + }, + required(vm, context) { + return vm.$t('validation.required.default', context); + }, + startsWith(vm, context) { + return vm.$t('validation.startsWith.default', context); + }, + url(vm, context) { + return vm.$t('validation.url.default', context); + } +}; + +/** + * The base formulario library. + */ +class Formulario { + constructor(options) { + this.validationRules = {}; + this.validationMessages = {}; + this.validationRules = rules; + this.validationMessages = messages; + this.extend(options || {}); + } + /** + * Given a set of options, apply them to the pre-existing options. + */ + extend(extendWith) { + if (typeof extendWith === 'object') { + this.validationRules = merge(this.validationRules, extendWith.validationRules || {}); + this.validationMessages = merge(this.validationMessages, extendWith.validationMessages || {}); + return this; + } + throw new Error(`[Formulario]: Formulario.extend() should be passed an object (was ${typeof extendWith})`); + } + /** + * Get validation rules by merging any passed in with global rules. + */ + getRules(extendWith = {}) { + return merge(this.validationRules, extendWith); + } + /** + * Get validation messages by merging any passed in with global messages. + */ + getMessages(vm, extendWith) { + const raw = merge(this.validationMessages || {}, extendWith); + const messages = {}; + for (const name in raw) { + messages[name] = (context, ...args) => { + return typeof raw[name] === 'string' ? raw[name] : raw[name](vm, context, ...args); + }; + } + return messages; + } +} + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ + +function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +} + +function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} + +/** + * Component registry with inherent depth to handle complex nesting. This is + * important for features such as grouped fields. + */ +class Registry { + /** + * Create a new registry of components. + * @param {FormularioForm} ctx The host vm context of the registry. + */ + constructor(ctx) { + this.registry = new Map(); + this.ctx = ctx; + } + /** + * Fully register a component. + * @param {string} field name of the field. + * @param {FormularioForm} component the actual component instance. + */ + add(field, component) { + if (this.registry.has(field)) { + return; + } + this.registry.set(field, component); + // @ts-ignore + const value = getNested(this.ctx.initialValues, field); + const hasModel = has(component.$options.propsData || {}, 'value'); + // @ts-ignore + if (!hasModel && this.ctx.hasInitialValue && value !== undefined) { + // In the case that the form is carrying an initial value and the + // element is not, set it directly. + // @ts-ignore + component.context.model = value; + // @ts-ignore + } + else if (hasModel && !shallowEqualObjects(component.proxy, value)) { + // In this case, the field is v-modeled or has an initial value and the + // form has no value or a different value, so use the field value + // @ts-ignore + this.ctx.setFieldValueAndEmit(field, component.proxy); + } + } + /** + * Remove an item from the registry. + */ + remove(name) { + this.registry.delete(name); + // @ts-ignore + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const _a = this.ctx.proxy, _b = name, value = _a[_b], newProxy = __rest(_a, [typeof _b === "symbol" ? _b : _b + ""]); + // @ts-ignore + this.ctx.proxy = newProxy; + } + /** + * Check if the registry has the given key. + */ + has(key) { + return this.registry.has(key); + } + /** + * Check if the registry has elements, that equals or nested given key + */ + hasNested(key) { + for (const i of this.registry.keys()) { + if (i === key || i.includes(key + '.')) { + return true; + } + } + return false; + } + /** + * Get a particular registry value. + */ + get(key) { + return this.registry.get(key); + } + /** + * Get registry value for key or nested to given key + */ + getNested(key) { + const result = new Map(); + for (const i of this.registry.keys()) { + const objectKey = key + '.'; + const arrayKey = key + '['; + if (i === key || + i.substring(0, objectKey.length) === objectKey || + i.substring(0, arrayKey.length) === arrayKey) { + result.set(i, this.registry.get(i)); + } + } + return result; + } + /** + * Map over the registry (recursively). + */ + forEach(callback) { + this.registry.forEach((component, field) => { + callback(component, field); + }); + } + /** + * Return the keys of the registry. + */ + keys() { + return Array.from(this.registry.keys()); + } + /** + * Reduce the registry. + * @param {function} callback + * @param accumulator + */ + reduce(callback, accumulator) { + this.registry.forEach((component, field) => { + accumulator = callback(accumulator, component, field); + }); + return accumulator; + } +} + +class ErrorObserverRegistry { + constructor(observers = []) { + this.observers = []; + this.observers = observers; + } + add(observer) { + if (!this.observers.some(o => o.callback === observer.callback)) { + this.observers.push(observer); + } + } + remove(handler) { + this.observers = this.observers.filter(o => o.callback !== handler); + } + filter(predicate) { + return new ErrorObserverRegistry(this.observers.filter(predicate)); + } + some(predicate) { + return this.observers.some(predicate); + } + observe(errors) { + this.observers.forEach(observer => { + if (observer.type === 'form') { + observer.callback(errors); + } + else if (observer.field && + !Array.isArray(errors) && + has(errors, observer.field)) { + observer.callback(errors[observer.field]); + } + }); + } +} + +let FormularioForm = class FormularioForm extends Vue { + constructor() { + super(...arguments); + this.path = ''; + this.proxy = {}; + this.registry = new Registry(this); + this.errorObserverRegistry = new ErrorObserverRegistry(); + // Local error messages are temporal, they wiped each resetValidation call + this.localFormErrors = []; + this.localFieldErrors = {}; + } + get initialValues() { + if (this.hasModel && typeof this.formularioValue === 'object') { + // If there is a v-model on the form/group, use those values as first priority + return Object.assign({}, this.formularioValue); // @todo - use a deep clone to detach reference types + } + return {}; + } + get mergedFormErrors() { + return [...this.formErrors, ...this.localFormErrors]; + } + get mergedFieldErrors() { + return merge(this.errors || {}, this.localFieldErrors); + } + get hasModel() { + return has(this.$options.propsData || {}, 'formularioValue'); + } + get hasInitialValue() { + return this.formularioValue && typeof this.formularioValue === 'object'; + } + onFormularioValueChanged(values) { + if (this.hasModel && values && typeof values === 'object') { + this.setValues(values); + } + } + onMergedFormErrorsChanged(errors) { + this.errorObserverRegistry.filter(o => o.type === 'form').observe(errors); + } + onMergedFieldErrorsChanged(errors) { + this.errorObserverRegistry.filter(o => o.type === 'input').observe(errors); + } + created() { + this.initProxy(); + } + getFormValues() { + return this.proxy; + } + onFormSubmit() { + return this.hasValidationErrors() + .then(hasErrors => hasErrors ? undefined : clone(this.proxy)) + .then(data => { + if (typeof data !== 'undefined') { + this.$emit('submit', data); + } + else { + this.$emit('error'); + } + }); + } + onFormularioFieldValidation(payload) { + this.$emit('validation', payload); + } + addErrorObserver(observer) { + this.errorObserverRegistry.add(observer); + if (observer.type === 'form') { + observer.callback(this.mergedFormErrors); + } + else if (observer.field && has(this.mergedFieldErrors, observer.field)) { + observer.callback(this.mergedFieldErrors[observer.field]); + } + } + removeErrorObserver(observer) { + this.errorObserverRegistry.remove(observer); + } + register(field, component) { + this.registry.add(field, component); + } + deregister(field) { + this.registry.remove(field); + } + initProxy() { + if (this.hasInitialValue) { + this.proxy = this.initialValues; + } + } + setValues(values) { + const keys = Array.from(new Set([...Object.keys(values), ...Object.keys(this.proxy)])); + let proxyHasChanges = false; + keys.forEach(field => { + if (!this.registry.hasNested(field)) { + return; + } + this.registry.getNested(field).forEach((registryField, registryKey) => { + const $input = this.registry.get(registryKey); + const oldValue = getNested(this.proxy, registryKey); + const newValue = getNested(values, registryKey); + if (!shallowEqualObjects(newValue, oldValue)) { + this.setFieldValue(registryKey, newValue); + proxyHasChanges = true; + } + if (!shallowEqualObjects(newValue, $input.proxy)) { + $input.context.model = newValue; + } + }); + }); + this.initProxy(); + if (proxyHasChanges) { + this.$emit('input', Object.assign({}, this.proxy)); + } + } + setFieldValue(field, value) { + if (value === undefined) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const _a = this.proxy, _b = field, value = _a[_b], proxy = __rest(_a, [typeof _b === "symbol" ? _b : _b + ""]); + this.proxy = proxy; + } + else { + setNested(this.proxy, field, value); + } + } + setFieldValueAndEmit(field, value) { + this.setFieldValue(field, value); + this.$emit('input', Object.assign({}, this.proxy)); + } + setErrors({ formErrors, inputErrors }) { + this.localFormErrors = formErrors || []; + this.localFieldErrors = inputErrors || {}; + } + hasValidationErrors() { + return Promise.all(this.registry.reduce((resolvers, input) => { + resolvers.push(input.runValidation() && input.hasValidationErrors()); + return resolvers; + }, [])).then(results => results.some(hasErrors => hasErrors)); + } + resetValidation() { + this.localFormErrors = []; + this.localFieldErrors = {}; + this.registry.forEach((input) => { + input.resetValidation(); + }); + } +}; +__decorate([ + Model('input', { default: () => ({}) }) +], FormularioForm.prototype, "formularioValue", void 0); +__decorate([ + Prop({ default: () => ({}) }) +], FormularioForm.prototype, "errors", void 0); +__decorate([ + Prop({ default: () => ([]) }) +], FormularioForm.prototype, "formErrors", void 0); +__decorate([ + Provide() +], FormularioForm.prototype, "path", void 0); +__decorate([ + Watch('formularioValue', { deep: true }) +], FormularioForm.prototype, "onFormularioValueChanged", null); +__decorate([ + Watch('mergedFormErrors') +], FormularioForm.prototype, "onMergedFormErrorsChanged", null); +__decorate([ + Watch('mergedFieldErrors', { deep: true, immediate: true }) +], FormularioForm.prototype, "onMergedFieldErrorsChanged", null); +__decorate([ + Provide() +], FormularioForm.prototype, "getFormValues", null); +__decorate([ + Provide() +], FormularioForm.prototype, "onFormularioFieldValidation", null); +__decorate([ + Provide() +], FormularioForm.prototype, "addErrorObserver", null); +__decorate([ + Provide() +], FormularioForm.prototype, "removeErrorObserver", null); +__decorate([ + Provide('formularioRegister') +], FormularioForm.prototype, "register", null); +__decorate([ + Provide('formularioDeregister') +], FormularioForm.prototype, "deregister", null); +__decorate([ + Provide('formularioSetter') +], FormularioForm.prototype, "setFieldValueAndEmit", null); +FormularioForm = __decorate([ + Component({ name: 'FormularioForm' }) +], FormularioForm); +var script = FormularioForm; + +function normalizeComponent(template, style, script, scopeId, isFunctionalTemplate, moduleIdentifier /* server only */, shadowMode, createInjector, createInjectorSSR, createInjectorShadow) { + if (typeof shadowMode !== 'boolean') { + createInjectorSSR = createInjector; + createInjector = shadowMode; + shadowMode = false; + } + // Vue.extend constructor export interop. + const options = typeof script === 'function' ? script.options : script; + // render functions + if (template && template.render) { + options.render = template.render; + options.staticRenderFns = template.staticRenderFns; + options._compiled = true; + // functional template + if (isFunctionalTemplate) { + options.functional = true; + } + } + // scopedId + if (scopeId) { + options._scopeId = scopeId; + } + let hook; + if (moduleIdentifier) { + // server build + hook = function (context) { + // 2.3 injection + context = + context || // cached call + (this.$vnode && this.$vnode.ssrContext) || // stateful + (this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext); // functional + // 2.2 with runInNewContext: true + if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') { + context = __VUE_SSR_CONTEXT__; + } + // inject component styles + if (style) { + style.call(this, createInjectorSSR(context)); + } + // register component module identifier for async chunk inference + if (context && context._registeredComponents) { + context._registeredComponents.add(moduleIdentifier); + } + }; + // used by ssr in case component is cached and beforeCreate + // never gets called + options._ssrRegister = hook; + } + else if (style) { + hook = shadowMode + ? function (context) { + style.call(this, createInjectorShadow(context, this.$root.$options.shadowRoot)); + } + : function (context) { + style.call(this, createInjector(context)); + }; + } + if (hook) { + if (options.functional) { + // register for functional component in vue file + const originalRender = options.render; + options.render = function renderWithStyleInjection(h, context) { + hook.call(context); + return originalRender(h, context); + }; + } + else { + // inject component registration as beforeCreate hook + const existing = options.beforeCreate; + options.beforeCreate = existing ? [].concat(existing, hook) : [hook]; + } + } + return script; +} + +/* script */ +const __vue_script__ = script; + +/* template */ +var __vue_render__ = function() { + var _vm = this; + var _h = _vm.$createElement; + var _c = _vm._self._c || _h; + return _c( + "form", + { + on: { + submit: function($event) { + $event.preventDefault(); + return _vm.onFormSubmit($event) + } + } + }, + [_vm._t("default", null, { errors: _vm.mergedFormErrors })], + 2 + ) +}; +var __vue_staticRenderFns__ = []; +__vue_render__._withStripped = true; + + /* style */ + const __vue_inject_styles__ = undefined; + /* scoped */ + const __vue_scope_id__ = undefined; + /* module identifier */ + const __vue_module_identifier__ = undefined; + /* functional template */ + const __vue_is_functional_template__ = false; + /* style inject */ + + /* style inject SSR */ + + /* style inject shadow dom */ + + + + const __vue_component__ = /*#__PURE__*/normalizeComponent( + { render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ }, + __vue_inject_styles__, + __vue_script__, + __vue_scope_id__, + __vue_is_functional_template__, + __vue_module_identifier__, + false, + undefined, + undefined, + undefined + ); + +let FormularioGrouping = class FormularioGrouping extends Vue { + get groupPath() { + if (this.isArrayItem) { + return `${this.path}[${this.name}]`; + } + if (this.path === '') { + return this.name; + } + return `${this.path}.${this.name}`; + } +}; +__decorate([ + Inject({ default: '' }) +], FormularioGrouping.prototype, "path", void 0); +__decorate([ + Prop({ required: true }) +], FormularioGrouping.prototype, "name", void 0); +__decorate([ + Prop({ default: false }) +], FormularioGrouping.prototype, "isArrayItem", void 0); +__decorate([ + Provide('path') +], FormularioGrouping.prototype, "groupPath", null); +FormularioGrouping = __decorate([ + Component({ name: 'FormularioGrouping' }) +], FormularioGrouping); +var script$1 = FormularioGrouping; + +/* script */ +const __vue_script__$1 = script$1; + +/* template */ +var __vue_render__$1 = function() { + var _vm = this; + var _h = _vm.$createElement; + var _c = _vm._self._c || _h; + return _c("div", [_vm._t("default")], 2) +}; +var __vue_staticRenderFns__$1 = []; +__vue_render__$1._withStripped = true; + + /* style */ + const __vue_inject_styles__$1 = undefined; + /* scoped */ + const __vue_scope_id__$1 = undefined; + /* module identifier */ + const __vue_module_identifier__$1 = undefined; + /* functional template */ + const __vue_is_functional_template__$1 = false; + /* style inject */ + + /* style inject SSR */ + + /* style inject shadow dom */ + + + + const __vue_component__$1 = /*#__PURE__*/normalizeComponent( + { render: __vue_render__$1, staticRenderFns: __vue_staticRenderFns__$1 }, + __vue_inject_styles__$1, + __vue_script__$1, + __vue_scope_id__$1, + __vue_is_functional_template__$1, + __vue_module_identifier__$1, + false, + undefined, + undefined, + undefined + ); + +function createValidator(ruleFn, ruleName, ruleArgs, messageFn) { + return (context) => { + return Promise.resolve(ruleFn(context, ...ruleArgs)).then(valid => { + return !valid ? { + rule: ruleName, + args: ruleArgs, + context, + message: messageFn(context, ...ruleArgs), + } : null; + }); + }; +} +function parseModifier(ruleName) { + if (/^[\^]/.test(ruleName.charAt(0))) { + return [snakeToCamel(ruleName.substr(1)), ruleName.charAt(0)]; + } + return [snakeToCamel(ruleName), null]; +} +function processSingleArrayConstraint(constraint, rules, messages) { + const args = constraint.slice(); + const first = args.shift(); + if (typeof first === 'function') { + return [first, null, null]; + } + if (typeof first !== 'string') { + throw new Error('[Formulario]: For array constraint first element must be rule name or Validator function'); + } + const [name, modifier] = parseModifier(first); + if (has(rules, name)) { + return [ + createValidator(rules[name], name, args, messages[name] || messages.default), + name, + modifier, + ]; + } + throw new Error(`[Formulario] Can't create validator for constraint: ${JSON.stringify(constraint)}`); +} +function processSingleStringConstraint(constraint, rules, messages) { + const args = constraint.split(':'); + const [name, modifier] = parseModifier(args.shift() || ''); + if (has(rules, name)) { + return [ + createValidator(rules[name], name, args.length ? args.join(':').split(',') : [], messages[name] || messages.default), + name, + modifier, + ]; + } + throw new Error(`[Formulario] Can't create validator for constraint: ${constraint}`); +} +function processSingleConstraint(constraint, rules, messages) { + if (typeof constraint === 'function') { + return [constraint, null, null]; + } + if (Array.isArray(constraint) && constraint.length) { + return processSingleArrayConstraint(constraint, rules, messages); + } + if (typeof constraint === 'string') { + return processSingleStringConstraint(constraint, rules, messages); + } + return [() => Promise.resolve(null), null, null]; +} +function processConstraints(constraints, rules, messages) { + if (typeof constraints === 'string') { + return processConstraints(constraints.split('|').filter(f => f.length), rules, messages); + } + if (!Array.isArray(constraints)) { + return []; + } + return constraints.map(constraint => processSingleConstraint(constraint, rules, messages)); +} +function enlarge(groups) { + const enlarged = []; + if (groups.length) { + let current = groups.shift(); + enlarged.push(current); + groups.forEach((group) => { + if (!group.bail && group.bail === current.bail) { + current.validators.push(...group.validators); + } + else { + current = Object.assign({}, group); + enlarged.push(current); + } + }); + } + return enlarged; +} +/** + * Given an array of rules, group them by bail signals. For example for this: + * bail|required|min:10|max:20 + * we would expect: + * [[required], [min], [max]] + * because any sub-array failure would cause a shutdown. While + * ^required|min:10|max:10 + * would return: + * [[required], [min, max]] + * and no bailing would produce: + * [[required, min, max]] + * @param {array} rules + */ +function createValidatorGroups(rules) { + const mapper = ([validator, /** name */ , modifier]) => ({ + validators: [validator], + bail: modifier === '^', + }); + const groups = []; + const bailIndex = rules.findIndex(([, name]) => name && name.toLowerCase() === 'bail'); + if (bailIndex >= 0) { + groups.push(...enlarge(rules.splice(0, bailIndex + 1).slice(0, -1).map(mapper))); + groups.push(...rules.map(([validator]) => ({ + validators: [validator], + bail: true, + }))); + } + else { + groups.push(...enlarge(rules.map(mapper))); + } + return groups; +} +function validateByGroup(group, context) { + return Promise.all(group.validators.map(validate => validate(context))) + .then(violations => violations.filter(v => v !== null)); +} +function validate(validators, context) { + return new Promise(resolve => { + const resolveGroups = (groups, all = []) => { + if (groups.length) { + const current = groups.shift(); + validateByGroup(current, context).then(violations => { + // The rule passed or its a non-bailing group, and there are additional groups to check, continue + if ((violations.length === 0 || !current.bail) && groups.length) { + return resolveGroups(groups, all.concat(violations)); + } + return resolve(all.concat(violations)); + }); + } + else { + resolve([]); + } + }; + resolveGroups(createValidatorGroups(validators)); + }); +} + +const VALIDATION_BEHAVIOR = { + DEMAND: 'demand', + LIVE: 'live', + SUBMIT: 'submit', +}; +let FormularioInput = class FormularioInput extends Vue { + constructor() { + super(...arguments); + this.proxy = this.getInitialValue(); + this.localErrors = []; + this.violations = []; + this.validationRun = Promise.resolve(); + } + get fullQualifiedName() { + return this.path !== '' ? `${this.path}.${this.name}` : this.name; + } + get model() { + const model = this.hasModel ? 'value' : 'proxy'; + return this[model] !== undefined ? this[model] : ''; + } + set model(value) { + if (!shallowEqualObjects(value, this.proxy)) { + this.proxy = value; + } + this.$emit('input', value); + if (typeof this.formularioSetter === 'function') { + this.formularioSetter(this.context.name, value); + } + } + get context() { + return Object.defineProperty({ + name: this.fullQualifiedName, + runValidation: this.runValidation.bind(this), + violations: this.violations, + errors: this.localErrors, + allErrors: [...this.localErrors, ...this.violations.map(v => v.message)], + }, 'model', { + get: () => this.model, + set: (value) => { + this.model = value; + }, + }); + } + get normalizedValidationRules() { + const rules = {}; + Object.keys(this.validationRules).forEach(key => { + rules[snakeToCamel(key)] = this.validationRules[key]; + }); + return rules; + } + get normalizedValidationMessages() { + const messages = {}; + Object.keys(this.validationMessages).forEach(key => { + messages[snakeToCamel(key)] = this.validationMessages[key]; + }); + return messages; + } + /** + * Determines if this formulario element is v-modeled or not. + */ + get hasModel() { + return has(this.$options.propsData || {}, 'value'); + } + onProxyChanged(newValue, oldValue) { + if (!this.hasModel && !shallowEqualObjects(newValue, oldValue)) { + this.context.model = newValue; + } + if (this.validationBehavior === VALIDATION_BEHAVIOR.LIVE) { + this.runValidation(); + } + else { + this.violations = []; + } + } + onValueChanged(newValue, oldValue) { + if (this.hasModel && !shallowEqualObjects(newValue, oldValue)) { + this.context.model = newValue; + } + } + created() { + this.initProxy(); + if (typeof this.formularioRegister === 'function') { + this.formularioRegister(this.fullQualifiedName, this); + } + if (typeof this.addErrorObserver === 'function' && !this.errorsDisabled) { + this.addErrorObserver({ callback: this.setErrors, type: 'input', field: this.fullQualifiedName }); + } + if (this.validationBehavior === VALIDATION_BEHAVIOR.LIVE) { + this.runValidation(); + } + } + // noinspection JSUnusedGlobalSymbols + beforeDestroy() { + if (!this.errorsDisabled && typeof this.removeErrorObserver === 'function') { + this.removeErrorObserver(this.setErrors); + } + if (typeof this.formularioDeregister === 'function') { + this.formularioDeregister(this.fullQualifiedName); + } + } + getInitialValue() { + return has(this.$options.propsData || {}, 'value') ? this.value : ''; + } + initProxy() { + // This should only be run immediately on created and ensures that the + // proxy and the model are both the same before any additional registration. + if (!shallowEqualObjects(this.context.model, this.proxy)) { + this.context.model = this.proxy; + } + } + runValidation() { + this.validationRun = this.validate().then(violations => { + const validationChanged = !shallowEqualObjects(violations, this.violations); + this.violations = violations; + if (validationChanged) { + const payload = { + name: this.context.name, + violations: this.violations, + }; + this.$emit('validation', payload); + if (typeof this.onFormularioFieldValidation === 'function') { + this.onFormularioFieldValidation(payload); + } + } + return this.violations; + }); + return this.validationRun; + } + validate() { + return validate(processConstraints(this.validation, this.$formulario.getRules(this.normalizedValidationRules), this.$formulario.getMessages(this, this.normalizedValidationMessages)), { + value: this.context.model, + name: this.context.name, + formValues: this.getFormValues(), + }); + } + hasValidationErrors() { + return new Promise(resolve => { + this.$nextTick(() => { + this.validationRun.then(() => resolve(this.violations.length > 0)); + }); + }); + } + setErrors(errors) { + this.localErrors = arrayify(errors); + } + resetValidation() { + this.localErrors = []; + this.violations = []; + } +}; +__decorate([ + Inject({ default: undefined }) +], FormularioInput.prototype, "formularioSetter", void 0); +__decorate([ + Inject({ default: () => () => { } }) +], FormularioInput.prototype, "onFormularioFieldValidation", void 0); +__decorate([ + Inject({ default: undefined }) +], FormularioInput.prototype, "formularioRegister", void 0); +__decorate([ + Inject({ default: undefined }) +], FormularioInput.prototype, "formularioDeregister", void 0); +__decorate([ + Inject({ default: () => () => ({}) }) +], FormularioInput.prototype, "getFormValues", void 0); +__decorate([ + Inject({ default: undefined }) +], FormularioInput.prototype, "addErrorObserver", void 0); +__decorate([ + Inject({ default: undefined }) +], FormularioInput.prototype, "removeErrorObserver", void 0); +__decorate([ + Inject({ default: '' }) +], FormularioInput.prototype, "path", void 0); +__decorate([ + Model('input', { default: '' }) +], FormularioInput.prototype, "value", void 0); +__decorate([ + Prop({ + required: true, + validator: (name) => typeof name === 'string' && name.length > 0, + }) +], FormularioInput.prototype, "name", void 0); +__decorate([ + Prop({ default: '' }) +], FormularioInput.prototype, "validation", void 0); +__decorate([ + Prop({ default: () => ({}) }) +], FormularioInput.prototype, "validationRules", void 0); +__decorate([ + Prop({ default: () => ({}) }) +], FormularioInput.prototype, "validationMessages", void 0); +__decorate([ + Prop({ + default: VALIDATION_BEHAVIOR.DEMAND, + validator: behavior => Object.values(VALIDATION_BEHAVIOR).includes(behavior) + }) +], FormularioInput.prototype, "validationBehavior", void 0); +__decorate([ + Prop({ default: false }) +], FormularioInput.prototype, "errorsDisabled", void 0); +__decorate([ + Watch('proxy') +], FormularioInput.prototype, "onProxyChanged", null); +__decorate([ + Watch('value') +], FormularioInput.prototype, "onValueChanged", null); +FormularioInput = __decorate([ + Component({ name: 'FormularioInput', inheritAttrs: false }) +], FormularioInput); +var script$2 = FormularioInput; + +/* script */ +const __vue_script__$2 = script$2; + +/* template */ +var __vue_render__$2 = function() { + var _vm = this; + var _h = _vm.$createElement; + var _c = _vm._self._c || _h; + return _c( + "div", + { staticClass: "formulario-input" }, + [_vm._t("default", null, { context: _vm.context })], + 2 + ) +}; +var __vue_staticRenderFns__$2 = []; +__vue_render__$2._withStripped = true; + + /* style */ + const __vue_inject_styles__$2 = undefined; + /* scoped */ + const __vue_scope_id__$2 = undefined; + /* module identifier */ + const __vue_module_identifier__$2 = undefined; + /* functional template */ + const __vue_is_functional_template__$2 = false; + /* style inject */ + + /* style inject SSR */ + + /* style inject shadow dom */ + + + + const __vue_component__$2 = /*#__PURE__*/normalizeComponent( + { render: __vue_render__$2, staticRenderFns: __vue_staticRenderFns__$2 }, + __vue_inject_styles__$2, + __vue_script__$2, + __vue_scope_id__$2, + __vue_is_functional_template__$2, + __vue_module_identifier__$2, + false, + undefined, + undefined, + undefined + ); + +var index = { + install(Vue, options) { + Vue.component('FormularioForm', __vue_component__); + Vue.component('FormularioGrouping', __vue_component__$1); + Vue.component('FormularioInput', __vue_component__$2); + Vue.mixin({ + beforeCreate() { + const o = this.$options; + if (typeof o.formulario === 'function') { + this.$formulario = o.formulario(); + } + else if (o.parent && o.parent.$formulario) { + this.$formulario = o.parent.$formulario; + } + else { + this.$formulario = new Formulario(options); + } + } + }); + }, +}; + +export default index; diff --git a/dist/formulario.min.js b/dist/formulario.min.js index 2fd351e..afae87c 100644 --- a/dist/formulario.min.js +++ b/dist/formulario.min.js @@ -1,18 +1,18 @@ -var VueFormulario=function(e){"use strict"; +var VueFormulario=function(t){"use strict"; /*! * is-plain-object * * Copyright (c) 2014-2017, Jon Schlinkert. * Released under the MIT License. */ -function t(e){return!0==(null!=(t=e)&&"object"==typeof t&&!1===Array.isArray(t))&&"[object Object]"===Object.prototype.toString.call(e); +function e(t){return!0==(null!=(e=t)&&"object"==typeof e&&!1===Array.isArray(e))&&"[object Object]"===Object.prototype.toString.call(t); /*! * isobject * * Copyright (c) 2014-2017, Jon Schlinkert. * Released under the MIT License. */ -var t}function r(e){var r,o;return!1!==t(e)&&("function"==typeof(r=e.constructor)&&(!1!==t(o=r.prototype)&&!1!==o.hasOwnProperty("isPrototypeOf")))}function o(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function i(e,t,n=!0){const a={};for(const s in e)o(t,s)?r(t[s])&&r(e[s])?a[s]=i(e[s],t[s],n):n&&Array.isArray(e[s])&&Array.isArray(t[s])?a[s]=e[s].concat(t[s]):a[s]=t[s]:a[s]=e[s];for(const e in t)o(a,e)||(a[e]=t[e]);return a}e=e&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e;var n=function(e){if("string"!=typeof e)return!1;var t=e.match(a);if(!t)return!1;var r=t[1];if(!r)return!1;if(s.test(r)||l.test(r))return!0;return!1},a=/^(?:\w+:)?\/\/(\S+)$/,s=/^localhost[\:?\d]*(?:[^\:?\d]\S*)?$/,l=/^[^\s\.]+\.\S{2,}$/;function u(e){switch(typeof e){case"symbol":case"number":case"string":case"boolean":case"undefined":return!0;default:return null===e}}function c(e,t){if(e===t)return!0;if(!e||!t)return!1;const r=Object.keys(e);if(Object.keys(t).length!==r.length)return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(0===r.length)return e===t;for(let o=0;o0!==e.indexOf(t)&&"_"!==e[e.indexOf(t)-1]?t.toUpperCase().replace("_",""):t)}function f(e,t){const r=t.split(".");let o=e;for(const e in r){const t=r[e].match(/(.+)\[(\d+)\]$/);if(void 0===o)return null;if(t){if(o=o[t[1]],void 0===o)return null;o=o[t[2]]}else o=o[r[e]]}return o}var h={accepted:({value:e})=>Promise.resolve(["yes","on","1",1,!0,"true"].includes(e)),after({value:e},t=!1){const r=!1!==t?Date.parse(t):Date.now(),o=e instanceof Date?e.getTime():Date.parse(e);return Promise.resolve(!isNaN(o)&&o>r)},alpha({value:e},t="default"){const r={default:/^[a-zA-ZÀ-ÖØ-öø-ÿ]+$/,latin:/^[a-zA-Z]+$/},i=o(r,t)?t:"default";return Promise.resolve(r[i].test(e))},alphanumeric({value:e},t="default"){const r={default:/^[a-zA-Z0-9À-ÖØ-öø-ÿ]+$/,latin:/^[a-zA-Z0-9]+$/},i=o(r,t)?t:"default";return Promise.resolve(r[i].test(e))},before({value:e},t=!1){const r=!1!==t?Date.parse(t):Date.now(),o=e instanceof Date?e.getTime():Date.parse(e);return Promise.resolve(!isNaN(o)&&oPromise.resolve(null!==t&&null!==r&&!isNaN(t)&&!isNaN(r)&&(!isNaN(Number(e))&&"length"!==o||"value"===o?(e=Number(e),t=Number(t),r=Number(r),e>t&&et&&e.lengthPromise.resolve((()=>{let i=o;return i||(i=/_confirm$/.test(r)?r.substr(0,r.length-8):r+"_confirm"),t[i]===e})()),date:({value:e},t=!1)=>Promise.resolve(t?function(e){const t=`^${r=e,r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`;var r;const o={MM:"(0[1-9]|1[012])",M:"([1-9]|1[012])",DD:"([012][1-9]|3[01])",D:"([012]?[1-9]|3[01])",YYYY:"\\d{4}",YY:"\\d{2}"};return new RegExp(Object.keys(o).reduce((e,t)=>e.replace(t,o[t]),t))}(t).test(e):!isNaN(Date.parse(e))),email({value:e}){if(!e)return Promise.resolve(!0);return Promise.resolve(/^(([^<>()\[\].,;:\s@"]+(\.[^<>()\[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})$/i.test(e))},endsWith:({value:e},...t)=>e?"string"==typeof e?Promise.resolve(0===t.length||t.some(t=>e.endsWith(t))):Promise.resolve(!1):Promise.resolve(!0),in:({value:e},...t)=>Promise.resolve(t.some(t=>"object"==typeof t?c(t,e):t===e)),matches:({value:e},...t)=>Promise.resolve(!!t.find(t=>("string"==typeof t&&"/"===t.substr(0,1)&&"/"===t.substr(-1)&&(t=new RegExp(t.substr(1,t.length-2))),t instanceof RegExp?t.test(e):t===e))),max:({value:e},t=10,r)=>Promise.resolve(Array.isArray(e)?(t=isNaN(Number(t))?t:Number(t),e.length<=t):!isNaN(e)&&"length"!==r||"value"===r?(e=isNaN(e)?e:Number(e))<=t:("string"==typeof e||"length"===r)&&(e=isNaN(e)?e:e.toString()).length<=t),min:({value:e},t=1,r)=>Promise.resolve(Array.isArray(e)?(t=isNaN(t)?t:Number(t),e.length>=t):!isNaN(e)&&"length"!==r||"value"===r?(e=isNaN(e)?e:Number(e))>=t:("string"==typeof e||"length"===r)&&(e=isNaN(e)?e:e.toString()).length>=t),not:({value:e},...t)=>Promise.resolve(!t.some(t=>"object"==typeof t?c(t,e):t===e)),number:({value:e})=>Promise.resolve(String(e).length>0&&!isNaN(Number(e))),required:({value:e},t=!0)=>Promise.resolve(!(t&&!["no","false"].includes(t)&&(Array.isArray(e)?!e.length:"string"==typeof e?!e:!("object"!=typeof e||e&&Object.keys(e).length)))),startsWith:({value:e},...t)=>e?"string"==typeof e?Promise.resolve(0===t.length||t.some(t=>e.startsWith(t))):Promise.resolve(!1):Promise.resolve(!0),url:({value:e})=>Promise.resolve(n(e)),bail:()=>Promise.resolve(!0)},p={default:(e,t)=>e.$t("validation.default",t),accepted:(e,t)=>e.$t("validation.accepted",t),after:(e,t,r=!1)=>"string"==typeof r&&r.length?e.$t("validation.after.compare",t):e.$t("validation.after.default",t),alpha:(e,t)=>e.$t("validation.alpha",t),alphanumeric:(e,t)=>e.$t("validation.alphanumeric",t),before:(e,t,r=!1)=>"string"==typeof r&&r.length?e.$t("validation.before.compare",t):e.$t("validation.before.default",t),between(e,t,r=0,o=10,i){const n=Object.assign(Object.assign({},t),{from:r,to:o});return!isNaN(t.value)&&"length"!==i||"value"===i?e.$t("validation.between.force",n):e.$t("validation.between.default",n)},confirm:(e,t)=>e.$t("validation.confirm",t),date:(e,t,r=!1)=>"string"==typeof r&&r.length?e.$t("validation.date.format",t):e.$t("validation.date.default",t),email:(e,t)=>e.$t("validation.email.default",t),endsWith:(e,t)=>e.$t("validation.endsWith.default",t),in:function(e,t){return"string"==typeof t.value&&t.value?e.$t("validation.in.string",t):e.$t("validation.in.default",t)},matches:(e,t)=>e.$t("validation.matches.default",t),max:(e,t,r=10,o)=>Array.isArray(t.value)?e.$tc("validation.max.array",r,t):!isNaN(t.value)&&"length"!==o||"value"===o?e.$tc("validation.max.force",r,t):e.$tc("validation.max.default",r,t),min:(e,t,r=1,o)=>Array.isArray(t.value)?e.$tc("validation.min.array",r,t):!isNaN(t.value)&&"length"!==o||"value"===o?e.$tc("validation.min.force",r,t):e.$tc("validation.min.default",r,t),not:(e,t)=>e.$t("validation.not.default",t),number:(e,t)=>e.$t("validation.number.default",t),required:(e,t)=>e.$t("validation.required.default",t),startsWith:(e,t)=>e.$t("validation.startsWith.default",t),url:(e,t)=>e.$t("validation.url.default",t)}; +var e}function r(t){var r,o;return!1!==e(t)&&("function"==typeof(r=t.constructor)&&(!1!==e(o=r.prototype)&&!1!==o.hasOwnProperty("isPrototypeOf")))}function o(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function i(t,e,n=!0){const a={};for(const s in t)o(e,s)?r(e[s])&&r(t[s])?a[s]=i(t[s],e[s],n):n&&Array.isArray(t[s])&&Array.isArray(e[s])?a[s]=t[s].concat(e[s]):a[s]=e[s]:a[s]=t[s];for(const t in e)o(a,t)||(a[t]=e[t]);return a}t=t&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t;var n=function(t){if("string"!=typeof t)return!1;var e=t.match(a);if(!e)return!1;var r=e[1];if(!r)return!1;if(s.test(r)||l.test(r))return!0;return!1},a=/^(?:\w+:)?\/\/(\S+)$/,s=/^localhost[\:?\d]*(?:[^\:?\d]\S*)?$/,l=/^[^\s\.]+\.\S{2,}$/;function u(t){switch(typeof t){case"symbol":case"number":case"string":case"boolean":case"undefined":return!0;default:return null===t}}function c(t,e){if(t===e)return!0;if(!t||!e)return!1;const r=Object.keys(t);if(Object.keys(e).length!==r.length)return!1;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(0===r.length)return t===e;for(let o=0;o0!==t.indexOf(e)&&"_"!==t[t.indexOf(e)-1]?e.toUpperCase().replace("_",""):e)}function f(t,e){const r=e.split(".");let o=t;for(const t in r){const e=r[t].match(/(.+)\[(\d+)\]$/);if(void 0===o)return null;if(e){if(o=o[e[1]],void 0===o)return null;o=o[e[2]]}else o=o[r[t]]}return o}const h={accepted:({value:t})=>["yes","on","1",1,!0,"true"].includes(t),after({value:t},e=!1){const r=!1!==e?Date.parse(e):Date.now(),o=t instanceof Date?t.getTime():Date.parse(t);return!isNaN(o)&&o>r},alpha({value:t},e="default"){const r={default:/^[a-zA-ZÀ-ÖØ-öø-ÿ]+$/,latin:/^[a-zA-Z]+$/};return"string"==typeof t&&r[o(r,e)?e:"default"].test(t)},alphanumeric({value:t},e="default"){const r={default:/^[a-zA-Z0-9À-ÖØ-öø-ÿ]+$/,latin:/^[a-zA-Z0-9]+$/};return"string"==typeof t&&r[o(r,e)?e:"default"].test(t)},before({value:t},e=!1){const r=!1!==e?Date.parse(e):Date.now(),o=t instanceof Date?t.getTime():Date.parse(t);return!isNaN(o)&&onull!==e&&null!==r&&!isNaN(e)&&!isNaN(r)&&(!isNaN(Number(t))&&"length"!==o||"value"===o?(t=Number(t))>Number(e)&&te&&t.lengthe?function(t){const e=`^${r=t,r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`;var r;const o={MM:"(0[1-9]|1[012])",M:"([1-9]|1[012])",DD:"([012][1-9]|3[01])",D:"([012]?[1-9]|3[01])",YYYY:"\\d{4}",YY:"\\d{2}"};return new RegExp(Object.keys(o).reduce((t,e)=>t.replace(e,o[e]),e))}(e).test(t):!isNaN(Date.parse(t)),email({value:t}){if(!t)return!0;return/^(([^<>()\[\].,;:\s@"]+(\.[^<>()\[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})$/i.test(t)},endsWith:({value:t},...e)=>!t||"string"==typeof t&&(0===e.length||e.some(e=>t.endsWith(e))),in:({value:t},...e)=>e.some(e=>"object"==typeof e?c(e,t):e===t),matches:({value:t},...e)=>!!e.find(e=>("string"==typeof e&&"/"===e.substr(0,1)&&"/"===e.substr(-1)&&(e=new RegExp(e.substr(1,e.length-2))),e instanceof RegExp?e.test(t):e===t)),max:({value:t},e=10,r)=>Array.isArray(t)?(e=isNaN(Number(e))?e:Number(e),t.length<=e):!isNaN(t)&&"length"!==r||"value"===r?(t=isNaN(t)?t:Number(t))<=e:("string"==typeof t||"length"===r)&&(t=isNaN(t)?t:t.toString()).length<=e,min:({value:t},e=1,r)=>Array.isArray(t)?(e=isNaN(e)?e:Number(e),t.length>=e):!isNaN(t)&&"length"!==r||"value"===r?(t=isNaN(t)?t:Number(t))>=e:("string"==typeof t||"length"===r)&&(t=isNaN(t)?t:t.toString()).length>=e,not:({value:t},...e)=>!e.some(e=>"object"==typeof e?c(e,t):e===t),number:({value:t})=>String(t).length>0&&!isNaN(Number(t)),required:({value:t},e=!0)=>!(e&&!["no","false"].includes(e))||(Array.isArray(t)?!!t.length:"string"==typeof t?!!t:"object"!=typeof t||!!t&&!!Object.keys(t).length),startsWith:({value:t},...e)=>!t||"string"==typeof t&&(0===e.length||e.some(e=>t.startsWith(e))),url:({value:t})=>n(t),bail:()=>!0},p={default:(t,e)=>t.$t("validation.default",e),accepted:(t,e)=>t.$t("validation.accepted",e),after:(t,e,r=!1)=>"string"==typeof r&&r.length?t.$t("validation.after.compare",e):t.$t("validation.after.default",e),alpha:(t,e)=>t.$t("validation.alpha",e),alphanumeric:(t,e)=>t.$t("validation.alphanumeric",e),before:(t,e,r=!1)=>"string"==typeof r&&r.length?t.$t("validation.before.compare",e):t.$t("validation.before.default",e),between(t,e,r=0,o=10,i){const n=Object.assign(Object.assign({},e),{from:r,to:o});return!isNaN(e.value)&&"length"!==i||"value"===i?t.$t("validation.between.force",n):t.$t("validation.between.default",n)},confirm:(t,e)=>t.$t("validation.confirm",e),date:(t,e,r=!1)=>"string"==typeof r&&r.length?t.$t("validation.date.format",e):t.$t("validation.date.default",e),email:(t,e)=>t.$t("validation.email.default",e),endsWith:(t,e)=>t.$t("validation.endsWith.default",e),in:(t,e)=>"string"==typeof e.value&&e.value?t.$t("validation.in.string",e):t.$t("validation.in.default",e),matches:(t,e)=>t.$t("validation.matches.default",e),max:(t,e,r=10,o)=>Array.isArray(e.value)?t.$tc("validation.max.array",r,e):!isNaN(e.value)&&"length"!==o||"value"===o?t.$tc("validation.max.force",r,e):t.$tc("validation.max.default",r,e),min:(t,e,r=1,o)=>Array.isArray(e.value)?t.$tc("validation.min.array",r,e):!isNaN(e.value)&&"length"!==o||"value"===o?t.$tc("validation.min.force",r,e):t.$tc("validation.min.default",r,e),not:(t,e)=>t.$t("validation.not.default",e),number:(t,e)=>t.$t("validation.number.default",e),required:(t,e)=>t.$t("validation.required.default",e),startsWith:(t,e)=>t.$t("validation.startsWith.default",e),url:(t,e)=>t.$t("validation.url.default",e)};class v{constructor(t){this.validationRules={},this.validationMessages={},this.validationRules=h,this.validationMessages=p,this.extend(t||{})}extend(t){if("object"==typeof t)return this.validationRules=i(this.validationRules,t.validationRules||{}),this.validationMessages=i(this.validationMessages,t.validationMessages||{}),this;throw new Error(`[Formulario]: Formulario.extend() should be passed an object (was ${typeof t})`)}getRules(t={}){return i(this.validationRules,t)}getMessages(t,e){const r=i(this.validationMessages||{},e),o={};for(const e in r)o[e]=(o,...i)=>"string"==typeof r[e]?r[e]:r[e](t,o,...i);return o}} /*! ***************************************************************************** Copyright (c) Microsoft Corporation. @@ -26,10 +26,9 @@ var t}function r(e){var r,o;return!1!==t(e)&&("function"==typeof(r=e.constructor LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ -function v(e,t){var r={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(r[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(o=Object.getOwnPropertySymbols(e);i=0;s--)(i=e[s])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a + ***************************************************************************** */function m(t,e){var r={};for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&e.indexOf(o)<0&&(r[o]=t[o]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(o=Object.getOwnPropertySymbols(t);i=0;s--)(i=t[s])&&(a=(n<3?i(a):n>3?i(e,r,a):i(e,r))||a);return n>3&&a&&Object.defineProperty(e,r,a),a /** * vue-class-component v7.2.3 * (c) 2015-present Evan You * @license MIT - */}function y(e){return(y="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function g(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function b(e){return function(e){if(Array.isArray(e)){for(var t=0,r=new Array(e.length);t0&&j("Component class must inherit Vue or its descendant class when class property is used."),n}var P=["data","beforeCreate","created","beforeMount","mounted","beforeDestroy","destroyed","beforeUpdate","updated","activated","deactivated","render","errorCaptured","serverPrefetch"];function V(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};r.name=r.name||t._componentTag||t.name;var o=t.prototype;Object.getOwnPropertyNames(o).forEach((function(e){if("constructor"!==e)if(P.indexOf(e)>-1)r[e]=o[e];else{var t=Object.getOwnPropertyDescriptor(o,e);void 0!==t.value?"function"==typeof t.value?(r.methods||(r.methods={}))[e]=t.value:(r.mixins||(r.mixins=[])).push({data:function(){return g({},e,t.value)}}):(t.get||t.set)&&((r.computed||(r.computed={}))[e]={get:t.get,set:t.set})}})),(r.mixins||(r.mixins=[])).push({data:function(){return N(this,t)}});var i=t.__decorators__;i&&(i.forEach((function(e){return e(r)})),delete t.__decorators__);var n=Object.getPrototypeOf(t.prototype),a=n instanceof e?n.constructor:e,s=a.extend(r);return R(s,t,a),O()&&E(s,t),s}var w=["cid","super","options","superOptions","extendOptions","sealedOptions","component","directive","filter"],F={prototype:!0,arguments:!0,callee:!0,caller:!0};function R(e,t,r){Object.getOwnPropertyNames(t).forEach((function(o){if(!F[o]){var i=Object.getOwnPropertyDescriptor(e,o);if(!i||i.configurable){var n,a,s=Object.getOwnPropertyDescriptor(t,o);if(!$){if("cid"===o)return;var l=Object.getOwnPropertyDescriptor(r,o);if(n=s.value,a=y(n),null!=n&&("object"===a||"function"===a)&&l&&l.value===s.value)return}"production"!==process.env.NODE_ENV&&w.indexOf(o)>=0&&j("Static property name '".concat(o,"' declared on class '").concat(t.name,"' ")+"conflicts with reserved property name of Vue internal. It may cause unexpected behavior of the component. Consider renaming the property."),Object.defineProperty(e,o,s)}}}))}function A(e){return"function"==typeof e?V(e):function(t){return V(t,e)}}A.registerHooks=function(e){P.push.apply(P,b(e))};function M(e){return _((function(t,r){void 0===t.inject&&(t.inject={}),Array.isArray(t.inject)||(t.inject[r]=e||r)}))}function D(e){return _((function(t,r){var o,i=t.provide;("function"!=typeof(o=i)||!o.managed&&!o.managedReactive)&&(i=t.provide=function(e){var t=function(){var r=this,o="function"==typeof e?e.call(this):e;for(var i in(o=Object.create(o||null)).__reactiveInject__=this.__reactiveInject__||{},t.managed)o[t.managed[i]]=this[i];var n=function(e){o[t.managedReactive[e]]=a[e],Object.defineProperty(o.__reactiveInject__,t.managedReactive[e],{enumerable:!0,get:function(){return r[e]}})},a=this;for(var i in t.managedReactive)n(i);return o};return t.managed={},t.managedReactive={},t}(i)),i.managed[r]=e||r}))}var S="undefined"!=typeof Reflect&&void 0!==Reflect.getMetadata;function k(e,t,r){if(S&&!Array.isArray(e)&&"function"!=typeof e&&void 0===e.type){var o=Reflect.getMetadata("design:type",t,r);o!==Object&&(e.type=o)}}function C(e,t){return void 0===t&&(t={}),function(r,o){k(t,r,o),_((function(r,o){(r.props||(r.props={}))[o]=t,r.model={prop:o,event:e||o}}))(r,o)}}function I(e){return void 0===e&&(e={}),function(t,r){k(e,t,r),_((function(t,r){(t.props||(t.props={}))[r]=e}))(t,r)}}function T(e,t){void 0===t&&(t={});var r=t.deep,o=void 0!==r&&r,i=t.immediate,n=void 0!==i&&i;return _((function(t,r){"object"!=typeof t.watch&&(t.watch=Object.create(null));var i=t.watch;"object"!=typeof i[e]||Array.isArray(i[e])?void 0===i[e]&&(i[e]=[]):i[e]=[i[e]],i[e].push({handler:r,deep:o,immediate:n})}))}class z{constructor(e){this.registry=new Map,this.ctx=e}add(e,t){this.registry.set(e,t)}remove(e){this.registry.delete(e);const t=this.ctx.proxy,r=e,o=(t[r],v(t,["symbol"==typeof r?r:r+""]));this.ctx.proxy=o}has(e){return this.registry.has(e)}hasNested(e){for(const t of this.registry.keys())if(t===e||t.includes(e+"."))return!0;return!1}get(e){return this.registry.get(e)}getNested(e){const t=new Map;for(const r of this.registry.keys()){const o=e+".",i=e+"[";r!==e&&r.substring(0,o.length)!==o&&r.substring(0,i.length)!==i||t.set(r,this.registry.get(r))}return t}forEach(e){this.registry.forEach((t,r)=>{e(t,r)})}keys(){return Array.from(this.registry.keys())}register(e,t){if(this.registry.has(e))return;this.registry.set(e,t);const r=o(t.$options.propsData||{},"value");!r&&this.ctx.hasInitialValue&&void 0!==f(this.ctx.initialValues,e)?t.context.model=f(this.ctx.initialValues,e):r&&!c(t.proxy,f(this.ctx.initialValues,e))&&this.ctx.setFieldValue(e,t.proxy)}reduce(e,t){return this.registry.forEach((r,o)=>{t=e(t,r,o)}),t}}class W{constructor(e=[]){this.observers=[],this.observers=e}add(e){this.observers.some(t=>t.callback===e.callback)||this.observers.push(e)}remove(e){this.observers=this.observers.filter(t=>t.callback!==e)}filter(e){return new W(this.observers.filter(e))}some(e){return this.observers.some(e)}observe(e){this.observers.forEach(t=>{"form"===t.type?t.callback(e):t.field&&!Array.isArray(e)&&o(e,t.field)&&t.callback(e[t.field])})}}let Y=class extends e{constructor(){super(...arguments),this.path="",this.proxy={},this.registry=new z(this),this.errorObserverRegistry=new W,this.localFormErrors=[],this.localFieldErrors={}}get initialValues(){return this.hasModel&&"object"==typeof this.formularioValue?Object.assign({},this.formularioValue):{}}get mergedFormErrors(){return[...this.formErrors,...this.localFormErrors]}get mergedFieldErrors(){return i(this.errors||{},this.localFieldErrors)}get hasModel(){return o(this.$options.propsData||{},"formularioValue")}get hasInitialValue(){return this.formularioValue&&"object"==typeof this.formularioValue}onFormularioValueChanged(e){this.hasModel&&e&&"object"==typeof e&&this.setValues(e)}onMergedFormErrorsChanged(e){this.errorObserverRegistry.filter(e=>"form"===e.type).observe(e)}onMergedFieldErrorsChanged(e){this.errorObserverRegistry.filter(e=>"input"===e.type).observe(e)}created(){this.initProxy()}getFormValues(){return this.proxy}onFormSubmit(){return this.hasValidationErrors().then(e=>e?void 0:function e(t){if("object"!=typeof t)return t;const r=Array.isArray(t)?[]:{};for(const i in t)o(t,i)&&(r[i]=u(t[i])?t[i]:e(t[i]));return r}(this.proxy)).then(e=>{void 0!==e?this.$emit("submit",e):this.$emit("error")})}onFormularioFieldValidation(e){this.$emit("validation",e)}addErrorObserver(e){this.errorObserverRegistry.add(e),"form"===e.type?e.callback(this.mergedFormErrors):e.field&&o(this.mergedFieldErrors,e.field)&&e.callback(this.mergedFieldErrors[e.field])}removeErrorObserver(e){this.errorObserverRegistry.remove(e)}register(e,t){this.registry.register(e,t)}deregister(e){this.registry.remove(e)}initProxy(){this.hasInitialValue&&(this.proxy=this.initialValues)}setValues(e){const t=Array.from(new Set([...Object.keys(e),...Object.keys(this.proxy)]));let r=!1;t.forEach(t=>{this.registry.hasNested(t)&&this.registry.getNested(t).forEach((t,o)=>{const i=this.registry.get(o),n=f(this.proxy,o),a=f(e,o);c(a,n)||(this.setFieldValue(o,a,!1),r=!0),c(a,i.proxy)||(i.context.model=a)})}),this.initProxy(),r&&this.$emit("input",Object.assign({},this.proxy))}setFieldValue(e,t,r=!0){if(void 0===t){const t=this.proxy,r=e,o=(t[r],v(t,["symbol"==typeof r?r:r+""]));this.proxy=o}else!function(e,t,r){const o=t.split(".");let i=e;for(let e=0;e(e.push(t.runValidation()&&t.hasValidationErrors()),e),[])).then(e=>e.some(e=>e))}resetValidation(){this.localFormErrors=[],this.localFieldErrors={},this.registry.forEach(e=>{e.resetValidation()})}};function q(e,t,r,o,i,n,a,s,l,u){"boolean"!=typeof a&&(l=s,s=a,a=!1);const c="function"==typeof r?r.options:r;let d;if(e&&e.render&&(c.render=e.render,c.staticRenderFns=e.staticRenderFns,c._compiled=!0,i&&(c.functional=!0)),o&&(c._scopeId=o),n?(d=function(e){(e=e||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(e=__VUE_SSR_CONTEXT__),t&&t.call(this,l(e)),e&&e._registeredComponents&&e._registeredComponents.add(n)},c._ssrRegister=d):t&&(d=a?function(e){t.call(this,u(e,this.$root.$options.shadowRoot))}:function(e){t.call(this,s(e))}),d)if(c.functional){const e=c.render;c.render=function(t,r){return d.call(r),e(t,r)}}else{const e=c.beforeCreate;c.beforeCreate=e?[].concat(e,d):[d]}return r}m([C("input",{default:()=>({})})],Y.prototype,"formularioValue",void 0),m([I({default:()=>({})})],Y.prototype,"errors",void 0),m([I({default:()=>[]})],Y.prototype,"formErrors",void 0),m([D()],Y.prototype,"path",void 0),m([T("formularioValue",{deep:!0})],Y.prototype,"onFormularioValueChanged",null),m([T("mergedFormErrors")],Y.prototype,"onMergedFormErrorsChanged",null),m([T("mergedFieldErrors",{deep:!0,immediate:!0})],Y.prototype,"onMergedFieldErrorsChanged",null),m([D()],Y.prototype,"getFormValues",null),m([D()],Y.prototype,"onFormularioFieldValidation",null),m([D()],Y.prototype,"addErrorObserver",null),m([D()],Y.prototype,"removeErrorObserver",null),m([D("formularioRegister")],Y.prototype,"register",null),m([D("formularioDeregister")],Y.prototype,"deregister",null),m([D("formularioSetter")],Y.prototype,"setFieldValue",null),Y=m([A({name:"FormularioForm"})],Y);const Q=Y;var U=function(){var e=this,t=e.$createElement;return(e._self._c||t)("form",{on:{submit:function(t){return t.preventDefault(),e.onFormSubmit(t)}}},[e._t("default",null,{errors:e.mergedFormErrors})],2)};U._withStripped=!0;const B=q({render:U,staticRenderFns:[]},void 0,Q,void 0,!1,void 0,!1,void 0,void 0,void 0);let L=class extends e{get groupPath(){return this.isArrayItem?`${this.path}[${this.name}]`:""===this.path?this.name:`${this.path}.${this.name}`}};m([M({default:""})],L.prototype,"path",void 0),m([I({required:!0})],L.prototype,"name",void 0),m([I({default:!1})],L.prototype,"isArrayItem",void 0),m([D("path")],L.prototype,"groupPath",null),L=m([A({name:"FormularioGrouping"})],L);const Z=L;var K=function(){var e=this.$createElement;return(this._self._c||e)("div",[this._t("default")],2)};K._withStripped=!0;const G=q({render:K,staticRenderFns:[]},void 0,Z,void 0,!1,void 0,!1,void 0,void 0,void 0);function X(e,t,r,o){return i=>Promise.resolve(e(i,...r)).then(e=>e?null:{rule:t,args:r,context:i,message:o(i,...r)})}function H(e){return/^[\^]/.test(e.charAt(0))?[d(e.substr(1)),e.charAt(0)]:[d(e),null]}function J(e,t,r){return"function"==typeof e?[e,null,null]:Array.isArray(e)&&e.length?function(e,t,r){const i=e.slice(),n=i.shift();if("function"==typeof n)return[n,null,null];if("string"!=typeof n)throw new Error("[Formulario]: For array constraint first element must be rule name or Validator function");const[a,s]=H(n);if(o(t,a))return[X(t[a],a,i,r[a]||r.default),a,s];throw new Error("[Formulario] Can't create validator for constraint: "+JSON.stringify(e))}(e,t,r):"string"==typeof e?function(e,t,r){const i=e.split(":"),[n,a]=H(i.shift()||"");if(o(t,n))return[X(t[n],n,i.length?i.join(":").split(","):[],r[n]||r.default),n,a];throw new Error("[Formulario] Can't create validator for constraint: "+e)}(e,t,r):[()=>Promise.resolve(null),null,null]}function ee(e){const t=[];if(e.length){let r=e.shift();t.push(r),e.forEach(e=>{e.bail||e.bail!==r.bail?(r=Object.assign({},e),t.push(r)):r.validators.push(...e.validators)})}return t}function te(e,t){return new Promise(r=>{const o=(e,i=[])=>{if(e.length){const n=e.shift();(function(e,t){return Promise.all(e.validators.map(e=>e(t))).then(e=>e.filter(e=>null!==e))})(n,t).then(t=>0!==t.length&&n.bail||!e.length?r(i.concat(t)):o(e,i.concat(t)))}else r([])};o(function(e){const t=([e,,t])=>({validators:[e],bail:"^"===t}),r=[],o=e.findIndex(([,e])=>e&&"bail"===e.toLowerCase());return o>=0?(r.push(...ee(e.splice(0,o+1).slice(0,-1).map(t))),r.push(...e.map(([e])=>({validators:[e],bail:!0})))):r.push(...ee(e.map(t))),r}(e))})}const re={DEMAND:"demand",LIVE:"live",SUBMIT:"submit"};let oe=class extends e{constructor(){super(...arguments),this.proxy=this.getInitialValue(),this.localErrors=[],this.violations=[],this.validationRun=Promise.resolve()}get fullQualifiedName(){return""!==this.path?`${this.path}.${this.name}`:this.name}get model(){const e=this.hasModel?"value":"proxy";return void 0===this[e]?"":this[e]}set model(e){c(e,this.proxy)||(this.proxy=e),this.$emit("input",e),"function"==typeof this.formularioSetter&&this.formularioSetter(this.context.name,e)}get context(){return Object.defineProperty({name:this.fullQualifiedName,runValidation:this.runValidation.bind(this),violations:this.violations,errors:this.localErrors,allErrors:[...this.localErrors,...this.violations.map(e=>e.message)]},"model",{get:()=>this.model,set:e=>{this.model=e}})}get normalizedValidationRules(){const e={};return Object.keys(this.validationRules).forEach(t=>{e[d(t)]=this.validationRules[t]}),e}get normalizedValidationMessages(){const e={};return Object.keys(this.validationMessages).forEach(t=>{e[d(t)]=this.validationMessages[t]}),e}get hasModel(){return o(this.$options.propsData||{},"value")}onProxyChanged(e,t){this.hasModel||c(e,t)||(this.context.model=e),this.validationBehavior===re.LIVE?this.runValidation():this.violations=[]}onValueChanged(e,t){this.hasModel&&!c(e,t)&&(this.context.model=e)}created(){this.initProxy(),"function"==typeof this.formularioRegister&&this.formularioRegister(this.fullQualifiedName,this),"function"!=typeof this.addErrorObserver||this.errorsDisabled||this.addErrorObserver({callback:this.setErrors,type:"input",field:this.fullQualifiedName}),this.validationBehavior===re.LIVE&&this.runValidation()}beforeDestroy(){this.errorsDisabled||"function"!=typeof this.removeErrorObserver||this.removeErrorObserver(this.setErrors),"function"==typeof this.formularioDeregister&&this.formularioDeregister(this.fullQualifiedName)}getInitialValue(){return o(this.$options.propsData||{},"value")?this.value:""}initProxy(){c(this.context.model,this.proxy)||(this.context.model=this.proxy)}runValidation(){return this.validationRun=this.validate().then(e=>{const t=!c(e,this.violations);if(this.violations=e,t){const e={name:this.context.name,violations:this.violations};this.$emit("validation",e),"function"==typeof this.onFormularioFieldValidation&&this.onFormularioFieldValidation(e)}return this.violations}),this.validationRun}validate(){return te(function e(t,r,o){return"string"==typeof t?e(t.split("|").filter(e=>e.length),r,o):Array.isArray(t)?t.map(e=>J(e,r,o)):[]}(this.validation,this.$formulario.getRules(this.normalizedValidationRules),this.$formulario.getMessages(this,this.normalizedValidationMessages)),{value:this.context.model,name:this.context.name,formValues:this.getFormValues()})}hasValidationErrors(){return new Promise(e=>{this.$nextTick(()=>{this.validationRun.then(()=>e(this.violations.length>0))})})}setErrors(e){var t;this.localErrors=(t=e)?"string"==typeof t?[t]:Array.isArray(t)?t:"object"==typeof t?Object.values(t):[]:[]}resetValidation(){this.localErrors=[],this.violations=[]}};m([M({default:void 0})],oe.prototype,"formularioSetter",void 0),m([M({default:()=>()=>{}})],oe.prototype,"onFormularioFieldValidation",void 0),m([M({default:void 0})],oe.prototype,"formularioRegister",void 0),m([M({default:void 0})],oe.prototype,"formularioDeregister",void 0),m([M({default:()=>()=>({})})],oe.prototype,"getFormValues",void 0),m([M({default:void 0})],oe.prototype,"addErrorObserver",void 0),m([M({default:void 0})],oe.prototype,"removeErrorObserver",void 0),m([M({default:""})],oe.prototype,"path",void 0),m([C("input",{default:""})],oe.prototype,"value",void 0),m([I({required:!0,validator:e=>"string"==typeof e&&e.length>0})],oe.prototype,"name",void 0),m([I({default:""})],oe.prototype,"validation",void 0),m([I({default:()=>({})})],oe.prototype,"validationRules",void 0),m([I({default:()=>({})})],oe.prototype,"validationMessages",void 0),m([I({default:re.DEMAND,validator:e=>Object.values(re).includes(e)})],oe.prototype,"validationBehavior",void 0),m([I({default:!1})],oe.prototype,"errorsDisabled",void 0),m([T("proxy")],oe.prototype,"onProxyChanged",null),m([T("value")],oe.prototype,"onValueChanged",null),oe=m([A({name:"FormularioInput",inheritAttrs:!1})],oe);const ie=oe;var ne=function(){var e=this.$createElement;return(this._self._c||e)("div",{staticClass:"formulario-input"},[this._t("default",null,{context:this.context})],2)};ne._withStripped=!0;const ae=q({render:ne,staticRenderFns:[]},void 0,ie,void 0,!1,void 0,!1,void 0,void 0,void 0);return new class{constructor(){this.validationRules={},this.validationMessages={},this.validationRules=h,this.validationMessages=p}install(e,t){e.prototype.$formulario=this,e.component("FormularioForm",B),e.component("FormularioGrouping",G),e.component("FormularioInput",ae),this.extend(t||{})}extend(e){if("object"==typeof e)return this.validationRules=i(this.validationRules,e.validationRules||{}),this.validationMessages=i(this.validationMessages,e.validationMessages||{}),this;throw new Error(`[Formulario]: Formulario.extend() should be passed an object (was ${typeof e})`)}getRules(e={}){return i(this.validationRules,e)}getMessages(e,t){const r=i(this.validationMessages||{},t),o={};for(const t in r)o[t]=(o,...i)=>"string"==typeof r[t]?r[t]:r[t](e,o,...i);return o}}}(Vue); + */}function g(t){return(g="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function b(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function O(t){return function(t){if(Array.isArray(t)){for(var e=0,r=new Array(t.length);e0&&N("Component class must inherit Vue or its descendant class when class property is used."),n}var V=["data","beforeCreate","created","beforeMount","mounted","beforeDestroy","destroyed","beforeUpdate","updated","activated","deactivated","render","errorCaptured","serverPrefetch"];function F(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};r.name=r.name||e._componentTag||e.name;var o=e.prototype;Object.getOwnPropertyNames(o).forEach((function(t){if("constructor"!==t)if(V.indexOf(t)>-1)r[t]=o[t];else{var e=Object.getOwnPropertyDescriptor(o,t);void 0!==e.value?"function"==typeof e.value?(r.methods||(r.methods={}))[t]=e.value:(r.mixins||(r.mixins=[])).push({data:function(){return b({},t,e.value)}}):(e.get||e.set)&&((r.computed||(r.computed={}))[t]={get:e.get,set:e.set})}})),(r.mixins||(r.mixins=[])).push({data:function(){return w(this,e)}});var i=e.__decorators__;i&&(i.forEach((function(t){return t(r)})),delete e.__decorators__);var n=Object.getPrototypeOf(e.prototype),a=n instanceof t?n.constructor:t,s=a.extend(r);return M(s,e,a),E()&&x(s,e),s}var R=["cid","super","options","superOptions","extendOptions","sealedOptions","component","directive","filter"],A={prototype:!0,arguments:!0,callee:!0,caller:!0};function M(t,e,r){Object.getOwnPropertyNames(e).forEach((function(o){if(!A[o]){var i=Object.getOwnPropertyDescriptor(t,o);if(!i||i.configurable){var n,a,s=Object.getOwnPropertyDescriptor(e,o);if(!_){if("cid"===o)return;var l=Object.getOwnPropertyDescriptor(r,o);if(n=s.value,a=g(n),null!=n&&("object"===a||"function"===a)&&l&&l.value===s.value)return}"production"!==process.env.NODE_ENV&&R.indexOf(o)>=0&&N("Static property name '".concat(o,"' declared on class '").concat(e.name,"' ")+"conflicts with reserved property name of Vue internal. It may cause unexpected behavior of the component. Consider renaming the property."),Object.defineProperty(t,o,s)}}}))}function P(t){return"function"==typeof t?F(t):function(e){return F(e,t)}}P.registerHooks=function(t){V.push.apply(V,O(t))};function D(t){return j((function(e,r){void 0===e.inject&&(e.inject={}),Array.isArray(e.inject)||(e.inject[r]=t||r)}))}function S(t){return j((function(e,r){var o,i=e.provide;("function"!=typeof(o=i)||!o.managed&&!o.managedReactive)&&(i=e.provide=function(t){var e=function(){var r=this,o="function"==typeof t?t.call(this):t;for(var i in(o=Object.create(o||null)).__reactiveInject__=this.__reactiveInject__||{},e.managed)o[e.managed[i]]=this[i];var n=function(t){o[e.managedReactive[t]]=a[t],Object.defineProperty(o.__reactiveInject__,e.managedReactive[t],{enumerable:!0,get:function(){return r[t]}})},a=this;for(var i in e.managedReactive)n(i);return o};return e.managed={},e.managedReactive={},e}(i)),i.managed[r]=t||r}))}var C="undefined"!=typeof Reflect&&void 0!==Reflect.getMetadata;function k(t,e,r){if(C&&!Array.isArray(t)&&"function"!=typeof t&&void 0===t.type){var o=Reflect.getMetadata("design:type",e,r);o!==Object&&(t.type=o)}}function I(t,e){return void 0===e&&(e={}),function(r,o){k(e,r,o),j((function(r,o){(r.props||(r.props={}))[o]=e,r.model={prop:o,event:t||o}}))(r,o)}}function T(t){return void 0===t&&(t={}),function(e,r){k(t,e,r),j((function(e,r){(e.props||(e.props={}))[r]=t}))(e,r)}}function z(t,e){void 0===e&&(e={});var r=e.deep,o=void 0!==r&&r,i=e.immediate,n=void 0!==i&&i;return j((function(e,r){"object"!=typeof e.watch&&(e.watch=Object.create(null));var i=e.watch;"object"!=typeof i[t]||Array.isArray(i[t])?void 0===i[t]&&(i[t]=[]):i[t]=[i[t]],i[t].push({handler:r,deep:o,immediate:n})}))}class W{constructor(t){this.registry=new Map,this.ctx=t}add(t,e){if(this.registry.has(t))return;this.registry.set(t,e);const r=f(this.ctx.initialValues,t),i=o(e.$options.propsData||{},"value");!i&&this.ctx.hasInitialValue&&void 0!==r?e.context.model=r:i&&!c(e.proxy,r)&&this.ctx.setFieldValueAndEmit(t,e.proxy)}remove(t){this.registry.delete(t);const e=this.ctx.proxy,r=t,o=(e[r],m(e,["symbol"==typeof r?r:r+""]));this.ctx.proxy=o}has(t){return this.registry.has(t)}hasNested(t){for(const e of this.registry.keys())if(e===t||e.includes(t+"."))return!0;return!1}get(t){return this.registry.get(t)}getNested(t){const e=new Map;for(const r of this.registry.keys()){const o=t+".",i=t+"[";r!==t&&r.substring(0,o.length)!==o&&r.substring(0,i.length)!==i||e.set(r,this.registry.get(r))}return e}forEach(t){this.registry.forEach((e,r)=>{t(e,r)})}keys(){return Array.from(this.registry.keys())}reduce(t,e){return this.registry.forEach((r,o)=>{e=t(e,r,o)}),e}}class Y{constructor(t=[]){this.observers=[],this.observers=t}add(t){this.observers.some(e=>e.callback===t.callback)||this.observers.push(t)}remove(t){this.observers=this.observers.filter(e=>e.callback!==t)}filter(t){return new Y(this.observers.filter(t))}some(t){return this.observers.some(t)}observe(t){this.observers.forEach(e=>{"form"===e.type?e.callback(t):e.field&&!Array.isArray(t)&&o(t,e.field)&&e.callback(t[e.field])})}}let q=class extends t{constructor(){super(...arguments),this.path="",this.proxy={},this.registry=new W(this),this.errorObserverRegistry=new Y,this.localFormErrors=[],this.localFieldErrors={}}get initialValues(){return this.hasModel&&"object"==typeof this.formularioValue?Object.assign({},this.formularioValue):{}}get mergedFormErrors(){return[...this.formErrors,...this.localFormErrors]}get mergedFieldErrors(){return i(this.errors||{},this.localFieldErrors)}get hasModel(){return o(this.$options.propsData||{},"formularioValue")}get hasInitialValue(){return this.formularioValue&&"object"==typeof this.formularioValue}onFormularioValueChanged(t){this.hasModel&&t&&"object"==typeof t&&this.setValues(t)}onMergedFormErrorsChanged(t){this.errorObserverRegistry.filter(t=>"form"===t.type).observe(t)}onMergedFieldErrorsChanged(t){this.errorObserverRegistry.filter(t=>"input"===t.type).observe(t)}created(){this.initProxy()}getFormValues(){return this.proxy}onFormSubmit(){return this.hasValidationErrors().then(t=>t?void 0:function t(e){if("object"!=typeof e)return e;const r=Array.isArray(e)?[]:{};for(const i in e)o(e,i)&&(u(e[i])?r[i]=e[i]:e instanceof Date?r[i]=new Date(r[i]):r[i]=t(e[i]));return r}(this.proxy)).then(t=>{void 0!==t?this.$emit("submit",t):this.$emit("error")})}onFormularioFieldValidation(t){this.$emit("validation",t)}addErrorObserver(t){this.errorObserverRegistry.add(t),"form"===t.type?t.callback(this.mergedFormErrors):t.field&&o(this.mergedFieldErrors,t.field)&&t.callback(this.mergedFieldErrors[t.field])}removeErrorObserver(t){this.errorObserverRegistry.remove(t)}register(t,e){this.registry.add(t,e)}deregister(t){this.registry.remove(t)}initProxy(){this.hasInitialValue&&(this.proxy=this.initialValues)}setValues(t){const e=Array.from(new Set([...Object.keys(t),...Object.keys(this.proxy)]));let r=!1;e.forEach(e=>{this.registry.hasNested(e)&&this.registry.getNested(e).forEach((e,o)=>{const i=this.registry.get(o),n=f(this.proxy,o),a=f(t,o);c(a,n)||(this.setFieldValue(o,a),r=!0),c(a,i.proxy)||(i.context.model=a)})}),this.initProxy(),r&&this.$emit("input",Object.assign({},this.proxy))}setFieldValue(t,e){if(void 0===e){const e=this.proxy,r=t,o=(e[r],m(e,["symbol"==typeof r?r:r+""]));this.proxy=o}else!function(t,e,r){const o=e.split(".");let i=t;for(let t=0;t(t.push(e.runValidation()&&e.hasValidationErrors()),t),[])).then(t=>t.some(t=>t))}resetValidation(){this.localFormErrors=[],this.localFieldErrors={},this.registry.forEach(t=>{t.resetValidation()})}};function Q(t,e,r,o,i,n,a,s,l,u){"boolean"!=typeof a&&(l=s,s=a,a=!1);const c="function"==typeof r?r.options:r;let d;if(t&&t.render&&(c.render=t.render,c.staticRenderFns=t.staticRenderFns,c._compiled=!0,i&&(c.functional=!0)),o&&(c._scopeId=o),n?(d=function(t){(t=t||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(t=__VUE_SSR_CONTEXT__),e&&e.call(this,l(t)),t&&t._registeredComponents&&t._registeredComponents.add(n)},c._ssrRegister=d):e&&(d=a?function(t){e.call(this,u(t,this.$root.$options.shadowRoot))}:function(t){e.call(this,s(t))}),d)if(c.functional){const t=c.render;c.render=function(e,r){return d.call(r),t(e,r)}}else{const t=c.beforeCreate;c.beforeCreate=t?[].concat(t,d):[d]}return r}y([I("input",{default:()=>({})})],q.prototype,"formularioValue",void 0),y([T({default:()=>({})})],q.prototype,"errors",void 0),y([T({default:()=>[]})],q.prototype,"formErrors",void 0),y([S()],q.prototype,"path",void 0),y([z("formularioValue",{deep:!0})],q.prototype,"onFormularioValueChanged",null),y([z("mergedFormErrors")],q.prototype,"onMergedFormErrorsChanged",null),y([z("mergedFieldErrors",{deep:!0,immediate:!0})],q.prototype,"onMergedFieldErrorsChanged",null),y([S()],q.prototype,"getFormValues",null),y([S()],q.prototype,"onFormularioFieldValidation",null),y([S()],q.prototype,"addErrorObserver",null),y([S()],q.prototype,"removeErrorObserver",null),y([S("formularioRegister")],q.prototype,"register",null),y([S("formularioDeregister")],q.prototype,"deregister",null),y([S("formularioSetter")],q.prototype,"setFieldValueAndEmit",null),q=y([P({name:"FormularioForm"})],q);const U=q;var B=function(){var t=this,e=t.$createElement;return(t._self._c||e)("form",{on:{submit:function(e){return e.preventDefault(),t.onFormSubmit(e)}}},[t._t("default",null,{errors:t.mergedFormErrors})],2)};B._withStripped=!0;const L=Q({render:B,staticRenderFns:[]},void 0,U,void 0,!1,void 0,!1,void 0,void 0,void 0);let Z=class extends t{get groupPath(){return this.isArrayItem?`${this.path}[${this.name}]`:""===this.path?this.name:`${this.path}.${this.name}`}};y([D({default:""})],Z.prototype,"path",void 0),y([T({required:!0})],Z.prototype,"name",void 0),y([T({default:!1})],Z.prototype,"isArrayItem",void 0),y([S("path")],Z.prototype,"groupPath",null),Z=y([P({name:"FormularioGrouping"})],Z);const K=Z;var G=function(){var t=this.$createElement;return(this._self._c||t)("div",[this._t("default")],2)};G._withStripped=!0;const X=Q({render:G,staticRenderFns:[]},void 0,K,void 0,!1,void 0,!1,void 0,void 0,void 0);function H(t,e,r,o){return i=>Promise.resolve(t(i,...r)).then(t=>t?null:{rule:e,args:r,context:i,message:o(i,...r)})}function J(t){return/^[\^]/.test(t.charAt(0))?[d(t.substr(1)),t.charAt(0)]:[d(t),null]}function tt(t,e,r){return"function"==typeof t?[t,null,null]:Array.isArray(t)&&t.length?function(t,e,r){const i=t.slice(),n=i.shift();if("function"==typeof n)return[n,null,null];if("string"!=typeof n)throw new Error("[Formulario]: For array constraint first element must be rule name or Validator function");const[a,s]=J(n);if(o(e,a))return[H(e[a],a,i,r[a]||r.default),a,s];throw new Error("[Formulario] Can't create validator for constraint: "+JSON.stringify(t))}(t,e,r):"string"==typeof t?function(t,e,r){const i=t.split(":"),[n,a]=J(i.shift()||"");if(o(e,n))return[H(e[n],n,i.length?i.join(":").split(","):[],r[n]||r.default),n,a];throw new Error("[Formulario] Can't create validator for constraint: "+t)}(t,e,r):[()=>Promise.resolve(null),null,null]}function et(t){const e=[];if(t.length){let r=t.shift();e.push(r),t.forEach(t=>{t.bail||t.bail!==r.bail?(r=Object.assign({},t),e.push(r)):r.validators.push(...t.validators)})}return e}function rt(t,e){return new Promise(r=>{const o=(t,i=[])=>{if(t.length){const n=t.shift();(function(t,e){return Promise.all(t.validators.map(t=>t(e))).then(t=>t.filter(t=>null!==t))})(n,e).then(e=>0!==e.length&&n.bail||!t.length?r(i.concat(e)):o(t,i.concat(e)))}else r([])};o(function(t){const e=([t,,e])=>({validators:[t],bail:"^"===e}),r=[],o=t.findIndex(([,t])=>t&&"bail"===t.toLowerCase());return o>=0?(r.push(...et(t.splice(0,o+1).slice(0,-1).map(e))),r.push(...t.map(([t])=>({validators:[t],bail:!0})))):r.push(...et(t.map(e))),r}(t))})}const ot={DEMAND:"demand",LIVE:"live",SUBMIT:"submit"};let it=class extends t{constructor(){super(...arguments),this.proxy=this.getInitialValue(),this.localErrors=[],this.violations=[],this.validationRun=Promise.resolve()}get fullQualifiedName(){return""!==this.path?`${this.path}.${this.name}`:this.name}get model(){const t=this.hasModel?"value":"proxy";return void 0!==this[t]?this[t]:""}set model(t){c(t,this.proxy)||(this.proxy=t),this.$emit("input",t),"function"==typeof this.formularioSetter&&this.formularioSetter(this.context.name,t)}get context(){return Object.defineProperty({name:this.fullQualifiedName,runValidation:this.runValidation.bind(this),violations:this.violations,errors:this.localErrors,allErrors:[...this.localErrors,...this.violations.map(t=>t.message)]},"model",{get:()=>this.model,set:t=>{this.model=t}})}get normalizedValidationRules(){const t={};return Object.keys(this.validationRules).forEach(e=>{t[d(e)]=this.validationRules[e]}),t}get normalizedValidationMessages(){const t={};return Object.keys(this.validationMessages).forEach(e=>{t[d(e)]=this.validationMessages[e]}),t}get hasModel(){return o(this.$options.propsData||{},"value")}onProxyChanged(t,e){this.hasModel||c(t,e)||(this.context.model=t),this.validationBehavior===ot.LIVE?this.runValidation():this.violations=[]}onValueChanged(t,e){this.hasModel&&!c(t,e)&&(this.context.model=t)}created(){this.initProxy(),"function"==typeof this.formularioRegister&&this.formularioRegister(this.fullQualifiedName,this),"function"!=typeof this.addErrorObserver||this.errorsDisabled||this.addErrorObserver({callback:this.setErrors,type:"input",field:this.fullQualifiedName}),this.validationBehavior===ot.LIVE&&this.runValidation()}beforeDestroy(){this.errorsDisabled||"function"!=typeof this.removeErrorObserver||this.removeErrorObserver(this.setErrors),"function"==typeof this.formularioDeregister&&this.formularioDeregister(this.fullQualifiedName)}getInitialValue(){return o(this.$options.propsData||{},"value")?this.value:""}initProxy(){c(this.context.model,this.proxy)||(this.context.model=this.proxy)}runValidation(){return this.validationRun=this.validate().then(t=>{const e=!c(t,this.violations);if(this.violations=t,e){const t={name:this.context.name,violations:this.violations};this.$emit("validation",t),"function"==typeof this.onFormularioFieldValidation&&this.onFormularioFieldValidation(t)}return this.violations}),this.validationRun}validate(){return rt(function t(e,r,o){return"string"==typeof e?t(e.split("|").filter(t=>t.length),r,o):Array.isArray(e)?e.map(t=>tt(t,r,o)):[]}(this.validation,this.$formulario.getRules(this.normalizedValidationRules),this.$formulario.getMessages(this,this.normalizedValidationMessages)),{value:this.context.model,name:this.context.name,formValues:this.getFormValues()})}hasValidationErrors(){return new Promise(t=>{this.$nextTick(()=>{this.validationRun.then(()=>t(this.violations.length>0))})})}setErrors(t){var e;this.localErrors=(e=t)?"string"==typeof e?[e]:Array.isArray(e)?e:"object"==typeof e?Object.values(e):[]:[]}resetValidation(){this.localErrors=[],this.violations=[]}};y([D({default:void 0})],it.prototype,"formularioSetter",void 0),y([D({default:()=>()=>{}})],it.prototype,"onFormularioFieldValidation",void 0),y([D({default:void 0})],it.prototype,"formularioRegister",void 0),y([D({default:void 0})],it.prototype,"formularioDeregister",void 0),y([D({default:()=>()=>({})})],it.prototype,"getFormValues",void 0),y([D({default:void 0})],it.prototype,"addErrorObserver",void 0),y([D({default:void 0})],it.prototype,"removeErrorObserver",void 0),y([D({default:""})],it.prototype,"path",void 0),y([I("input",{default:""})],it.prototype,"value",void 0),y([T({required:!0,validator:t=>"string"==typeof t&&t.length>0})],it.prototype,"name",void 0),y([T({default:""})],it.prototype,"validation",void 0),y([T({default:()=>({})})],it.prototype,"validationRules",void 0),y([T({default:()=>({})})],it.prototype,"validationMessages",void 0),y([T({default:ot.DEMAND,validator:t=>Object.values(ot).includes(t)})],it.prototype,"validationBehavior",void 0),y([T({default:!1})],it.prototype,"errorsDisabled",void 0),y([z("proxy")],it.prototype,"onProxyChanged",null),y([z("value")],it.prototype,"onValueChanged",null),it=y([P({name:"FormularioInput",inheritAttrs:!1})],it);const nt=it;var at=function(){var t=this.$createElement;return(this._self._c||t)("div",{staticClass:"formulario-input"},[this._t("default",null,{context:this.context})],2)};at._withStripped=!0;const st=Q({render:at,staticRenderFns:[]},void 0,nt,void 0,!1,void 0,!1,void 0,void 0,void 0);return{install(t,e){t.component("FormularioForm",L),t.component("FormularioGrouping",X),t.component("FormularioInput",st),t.mixin({beforeCreate(){const t=this.$options;"function"==typeof t.formulario?this.$formulario=t.formulario():t.parent&&t.parent.$formulario?this.$formulario=t.parent.$formulario:this.$formulario=new v(e)}})}}}(Vue); diff --git a/dist/formulario.umd.js b/dist/formulario.umd.js index 5c62dcc..95e8380 100644 --- a/dist/formulario.umd.js +++ b/dist/formulario.umd.js @@ -1,16 +1,1588 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("is-plain-object"),require("is-url"),require("vue"),require("vue-property-decorator")):"function"==typeof define&&define.amd?define(["is-plain-object","is-url","vue","vue-property-decorator"],t):(e=e||self).Formulario=t(e.isPlainObject,e.isUrl,e.Vue,e.vuePropertyDecorator)}(this,(function(e,t,r,i){"use strict";function o(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function s(t,r,i=!0){const a={};for(const n in t)o(r,n)?e(r[n])&&e(t[n])?a[n]=s(t[n],r[n],i):i&&Array.isArray(t[n])&&Array.isArray(r[n])?a[n]=t[n].concat(r[n]):a[n]=r[n]:a[n]=t[n];for(const e in r)o(a,e)||(a[e]=r[e]);return a}function a(e){switch(typeof e){case"symbol":case"number":case"string":case"boolean":case"undefined":return!0;default:return null===e}}function n(e,t){if(e===t)return!0;if(!e||!t)return!1;const r=Object.keys(e);if(Object.keys(t).length!==r.length)return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(0===r.length)return e===t;for(let i=0;i0!==e.indexOf(t)&&"_"!==e[e.indexOf(t)-1]?t.toUpperCase().replace("_",""):t)}function u(e,t){const r=t.split(".");let i=e;for(const e in r){const t=r[e].match(/(.+)\[(\d+)\]$/);if(void 0===i)return null;if(t){if(i=i[t[1]],void 0===i)return null;i=i[t[2]]}else i=i[r[e]]}return i}e=e&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e,t=t&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t,r=r&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r;var d={accepted:({value:e})=>Promise.resolve(["yes","on","1",1,!0,"true"].includes(e)),after({value:e},t=!1){const r=!1!==t?Date.parse(t):Date.now(),i=e instanceof Date?e.getTime():Date.parse(e);return Promise.resolve(!isNaN(i)&&i>r)},alpha({value:e},t="default"){const r={default:/^[a-zA-ZÀ-ÖØ-öø-ÿ]+$/,latin:/^[a-zA-Z]+$/},i=o(r,t)?t:"default";return Promise.resolve(r[i].test(e))},alphanumeric({value:e},t="default"){const r={default:/^[a-zA-Z0-9À-ÖØ-öø-ÿ]+$/,latin:/^[a-zA-Z0-9]+$/},i=o(r,t)?t:"default";return Promise.resolve(r[i].test(e))},before({value:e},t=!1){const r=!1!==t?Date.parse(t):Date.now(),i=e instanceof Date?e.getTime():Date.parse(e);return Promise.resolve(!isNaN(i)&&iPromise.resolve(null!==t&&null!==r&&!isNaN(t)&&!isNaN(r)&&(!isNaN(Number(e))&&"length"!==i||"value"===i?(e=Number(e),t=Number(t),r=Number(r),e>t&&et&&e.lengthPromise.resolve((()=>{let o=i;return o||(o=/_confirm$/.test(r)?r.substr(0,r.length-8):r+"_confirm"),t[o]===e})()),date:({value:e},t=!1)=>Promise.resolve(t?function(e){const t=`^${r=e,r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`;var r;const i={MM:"(0[1-9]|1[012])",M:"([1-9]|1[012])",DD:"([012][1-9]|3[01])",D:"([012]?[1-9]|3[01])",YYYY:"\\d{4}",YY:"\\d{2}"};return new RegExp(Object.keys(i).reduce((e,t)=>e.replace(t,i[t]),t))}(t).test(e):!isNaN(Date.parse(e))),email({value:e}){if(!e)return Promise.resolve(!0);return Promise.resolve(/^(([^<>()\[\].,;:\s@"]+(\.[^<>()\[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})$/i.test(e))},endsWith:({value:e},...t)=>e?"string"==typeof e?Promise.resolve(0===t.length||t.some(t=>e.endsWith(t))):Promise.resolve(!1):Promise.resolve(!0),in:({value:e},...t)=>Promise.resolve(t.some(t=>"object"==typeof t?n(t,e):t===e)),matches:({value:e},...t)=>Promise.resolve(!!t.find(t=>("string"==typeof t&&"/"===t.substr(0,1)&&"/"===t.substr(-1)&&(t=new RegExp(t.substr(1,t.length-2))),t instanceof RegExp?t.test(e):t===e))),max:({value:e},t=10,r)=>Promise.resolve(Array.isArray(e)?(t=isNaN(Number(t))?t:Number(t),e.length<=t):!isNaN(e)&&"length"!==r||"value"===r?(e=isNaN(e)?e:Number(e))<=t:("string"==typeof e||"length"===r)&&(e=isNaN(e)?e:e.toString()).length<=t),min:({value:e},t=1,r)=>Promise.resolve(Array.isArray(e)?(t=isNaN(t)?t:Number(t),e.length>=t):!isNaN(e)&&"length"!==r||"value"===r?(e=isNaN(e)?e:Number(e))>=t:("string"==typeof e||"length"===r)&&(e=isNaN(e)?e:e.toString()).length>=t),not:({value:e},...t)=>Promise.resolve(!t.some(t=>"object"==typeof t?n(t,e):t===e)),number:({value:e})=>Promise.resolve(String(e).length>0&&!isNaN(Number(e))),required:({value:e},t=!0)=>Promise.resolve(!(t&&!["no","false"].includes(t)&&(Array.isArray(e)?!e.length:"string"==typeof e?!e:!("object"!=typeof e||e&&Object.keys(e).length)))),startsWith:({value:e},...t)=>e?"string"==typeof e?Promise.resolve(0===t.length||t.some(t=>e.startsWith(t))):Promise.resolve(!1):Promise.resolve(!0),url:({value:e})=>Promise.resolve(t(e)),bail:()=>Promise.resolve(!0)},h={default:(e,t)=>e.$t("validation.default",t),accepted:(e,t)=>e.$t("validation.accepted",t),after:(e,t,r=!1)=>"string"==typeof r&&r.length?e.$t("validation.after.compare",t):e.$t("validation.after.default",t),alpha:(e,t)=>e.$t("validation.alpha",t),alphanumeric:(e,t)=>e.$t("validation.alphanumeric",t),before:(e,t,r=!1)=>"string"==typeof r&&r.length?e.$t("validation.before.compare",t):e.$t("validation.before.default",t),between(e,t,r=0,i=10,o){const s=Object.assign(Object.assign({},t),{from:r,to:i});return!isNaN(t.value)&&"length"!==o||"value"===o?e.$t("validation.between.force",s):e.$t("validation.between.default",s)},confirm:(e,t)=>e.$t("validation.confirm",t),date:(e,t,r=!1)=>"string"==typeof r&&r.length?e.$t("validation.date.format",t):e.$t("validation.date.default",t),email:(e,t)=>e.$t("validation.email.default",t),endsWith:(e,t)=>e.$t("validation.endsWith.default",t),in:function(e,t){return"string"==typeof t.value&&t.value?e.$t("validation.in.string",t):e.$t("validation.in.default",t)},matches:(e,t)=>e.$t("validation.matches.default",t),max:(e,t,r=10,i)=>Array.isArray(t.value)?e.$tc("validation.max.array",r,t):!isNaN(t.value)&&"length"!==i||"value"===i?e.$tc("validation.max.force",r,t):e.$tc("validation.max.default",r,t),min:(e,t,r=1,i)=>Array.isArray(t.value)?e.$tc("validation.min.array",r,t):!isNaN(t.value)&&"length"!==i||"value"===i?e.$tc("validation.min.force",r,t):e.$tc("validation.min.default",r,t),not:(e,t)=>e.$t("validation.not.default",t),number:(e,t)=>e.$t("validation.number.default",t),required:(e,t)=>e.$t("validation.required.default",t),startsWith:(e,t)=>e.$t("validation.startsWith.default",t),url:(e,t)=>e.$t("validation.url.default",t)}; -/*! ***************************************************************************** - Copyright (c) Microsoft Corporation. +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('is-plain-object'), require('is-url'), require('vue'), require('vue-property-decorator')) : + typeof define === 'function' && define.amd ? define(['is-plain-object', 'is-url', 'vue', 'vue-property-decorator'], factory) : + (global = global || self, global.Formulario = factory(global.isPlainObject, global.isUrl, global.Vue, global.vuePropertyDecorator)); +}(this, (function (isPlainObject, isUrl, Vue, vuePropertyDecorator) { 'use strict'; - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. + isPlainObject = isPlainObject && Object.prototype.hasOwnProperty.call(isPlainObject, 'default') ? isPlainObject['default'] : isPlainObject; + isUrl = isUrl && Object.prototype.hasOwnProperty.call(isUrl, 'default') ? isUrl['default'] : isUrl; + Vue = Vue && Object.prototype.hasOwnProperty.call(Vue, 'default') ? Vue['default'] : Vue; - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ -function c(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(i=Object.getOwnPropertySymbols(e);o=0;n--)(o=e[n])&&(a=(s<3?o(a):s>3?o(t,r,a):o(t,r))||a);return s>3&&a&&Object.defineProperty(t,r,a),a}class p{constructor(e){this.registry=new Map,this.ctx=e}add(e,t){this.registry.set(e,t)}remove(e){this.registry.delete(e);const t=this.ctx.proxy,r=e,i=(t[r],c(t,["symbol"==typeof r?r:r+""]));this.ctx.proxy=i}has(e){return this.registry.has(e)}hasNested(e){for(const t of this.registry.keys())if(t===e||t.includes(e+"."))return!0;return!1}get(e){return this.registry.get(e)}getNested(e){const t=new Map;for(const r of this.registry.keys()){const i=e+".",o=e+"[";r!==e&&r.substring(0,i.length)!==i&&r.substring(0,o.length)!==o||t.set(r,this.registry.get(r))}return t}forEach(e){this.registry.forEach((t,r)=>{e(t,r)})}keys(){return Array.from(this.registry.keys())}register(e,t){if(this.registry.has(e))return;this.registry.set(e,t);const r=o(t.$options.propsData||{},"value");!r&&this.ctx.hasInitialValue&&void 0!==u(this.ctx.initialValues,e)?t.context.model=u(this.ctx.initialValues,e):r&&!n(t.proxy,u(this.ctx.initialValues,e))&&this.ctx.setFieldValue(e,t.proxy)}reduce(e,t){return this.registry.forEach((r,i)=>{t=e(t,r,i)}),t}}class v{constructor(e=[]){this.observers=[],this.observers=e}add(e){this.observers.some(t=>t.callback===e.callback)||this.observers.push(e)}remove(e){this.observers=this.observers.filter(t=>t.callback!==e)}filter(e){return new v(this.observers.filter(e))}some(e){return this.observers.some(e)}observe(e){this.observers.forEach(t=>{"form"===t.type?t.callback(e):t.field&&!Array.isArray(e)&&o(e,t.field)&&t.callback(e[t.field])})}}let m=class extends r{constructor(){super(...arguments),this.path="",this.proxy={},this.registry=new p(this),this.errorObserverRegistry=new v,this.localFormErrors=[],this.localFieldErrors={}}get initialValues(){return this.hasModel&&"object"==typeof this.formularioValue?Object.assign({},this.formularioValue):{}}get mergedFormErrors(){return[...this.formErrors,...this.localFormErrors]}get mergedFieldErrors(){return s(this.errors||{},this.localFieldErrors)}get hasModel(){return o(this.$options.propsData||{},"formularioValue")}get hasInitialValue(){return this.formularioValue&&"object"==typeof this.formularioValue}onFormularioValueChanged(e){this.hasModel&&e&&"object"==typeof e&&this.setValues(e)}onMergedFormErrorsChanged(e){this.errorObserverRegistry.filter(e=>"form"===e.type).observe(e)}onMergedFieldErrorsChanged(e){this.errorObserverRegistry.filter(e=>"input"===e.type).observe(e)}created(){this.initProxy()}getFormValues(){return this.proxy}onFormSubmit(){return this.hasValidationErrors().then(e=>e?void 0:function e(t){if("object"!=typeof t)return t;const r=Array.isArray(t)?[]:{};for(const i in t)o(t,i)&&(r[i]=a(t[i])?t[i]:e(t[i]));return r}(this.proxy)).then(e=>{void 0!==e?this.$emit("submit",e):this.$emit("error")})}onFormularioFieldValidation(e){this.$emit("validation",e)}addErrorObserver(e){this.errorObserverRegistry.add(e),"form"===e.type?e.callback(this.mergedFormErrors):e.field&&o(this.mergedFieldErrors,e.field)&&e.callback(this.mergedFieldErrors[e.field])}removeErrorObserver(e){this.errorObserverRegistry.remove(e)}register(e,t){this.registry.register(e,t)}deregister(e){this.registry.remove(e)}initProxy(){this.hasInitialValue&&(this.proxy=this.initialValues)}setValues(e){const t=Array.from(new Set([...Object.keys(e),...Object.keys(this.proxy)]));let r=!1;t.forEach(t=>{this.registry.hasNested(t)&&this.registry.getNested(t).forEach((t,i)=>{const o=this.registry.get(i),s=u(this.proxy,i),a=u(e,i);n(a,s)||(this.setFieldValue(i,a,!1),r=!0),n(a,o.proxy)||(o.context.model=a)})}),this.initProxy(),r&&this.$emit("input",Object.assign({},this.proxy))}setFieldValue(e,t,r=!0){if(void 0===t){const t=this.proxy,r=e,i=(t[r],c(t,["symbol"==typeof r?r:r+""]));this.proxy=i}else!function(e,t,r){const i=t.split(".");let o=e;for(let e=0;e(e.push(t.runValidation()&&t.hasValidationErrors()),e),[])).then(e=>e.some(e=>e))}resetValidation(){this.localFormErrors=[],this.localFieldErrors={},this.registry.forEach(e=>{e.resetValidation()})}};function y(e,t,r,i,o,s,a,n,l,u){"boolean"!=typeof a&&(l=n,n=a,a=!1);const d="function"==typeof r?r.options:r;let h;if(e&&e.render&&(d.render=e.render,d.staticRenderFns=e.staticRenderFns,d._compiled=!0,o&&(d.functional=!0)),i&&(d._scopeId=i),s?(h=function(e){(e=e||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(e=__VUE_SSR_CONTEXT__),t&&t.call(this,l(e)),e&&e._registeredComponents&&e._registeredComponents.add(s)},d._ssrRegister=h):t&&(h=a?function(e){t.call(this,u(e,this.$root.$options.shadowRoot))}:function(e){t.call(this,n(e))}),h)if(d.functional){const e=d.render;d.render=function(t,r){return h.call(r),e(t,r)}}else{const e=d.beforeCreate;d.beforeCreate=e?[].concat(e,h):[h]}return r}f([i.Model("input",{default:()=>({})})],m.prototype,"formularioValue",void 0),f([i.Prop({default:()=>({})})],m.prototype,"errors",void 0),f([i.Prop({default:()=>[]})],m.prototype,"formErrors",void 0),f([i.Provide()],m.prototype,"path",void 0),f([i.Watch("formularioValue",{deep:!0})],m.prototype,"onFormularioValueChanged",null),f([i.Watch("mergedFormErrors")],m.prototype,"onMergedFormErrorsChanged",null),f([i.Watch("mergedFieldErrors",{deep:!0,immediate:!0})],m.prototype,"onMergedFieldErrorsChanged",null),f([i.Provide()],m.prototype,"getFormValues",null),f([i.Provide()],m.prototype,"onFormularioFieldValidation",null),f([i.Provide()],m.prototype,"addErrorObserver",null),f([i.Provide()],m.prototype,"removeErrorObserver",null),f([i.Provide("formularioRegister")],m.prototype,"register",null),f([i.Provide("formularioDeregister")],m.prototype,"deregister",null),f([i.Provide("formularioSetter")],m.prototype,"setFieldValue",null),m=f([i.Component({name:"FormularioForm"})],m);const g=m;var b=function(){var e=this,t=e.$createElement;return(e._self._c||t)("form",{on:{submit:function(t){return t.preventDefault(),e.onFormSubmit(t)}}},[e._t("default",null,{errors:e.mergedFormErrors})],2)};b._withStripped=!0;const E=y({render:b,staticRenderFns:[]},void 0,g,void 0,!1,void 0,!1,void 0,void 0,void 0);let x=class extends r{get groupPath(){return this.isArrayItem?`${this.path}[${this.name}]`:""===this.path?this.name:`${this.path}.${this.name}`}};f([i.Inject({default:""})],x.prototype,"path",void 0),f([i.Prop({required:!0})],x.prototype,"name",void 0),f([i.Prop({default:!1})],x.prototype,"isArrayItem",void 0),f([i.Provide("path")],x.prototype,"groupPath",null),x=f([i.Component({name:"FormularioGrouping"})],x);const P=x;var $=function(){var e=this.$createElement;return(this._self._c||e)("div",[this._t("default")],2)};$._withStripped=!0;const N=y({render:$,staticRenderFns:[]},void 0,P,void 0,!1,void 0,!1,void 0,void 0,void 0);function F(e,t,r,i){return o=>Promise.resolve(e(o,...r)).then(e=>e?null:{rule:t,args:r,context:o,message:i(o,...r)})}function V(e){return/^[\^]/.test(e.charAt(0))?[l(e.substr(1)),e.charAt(0)]:[l(e),null]}function O(e,t,r){return"function"==typeof e?[e,null,null]:Array.isArray(e)&&e.length?function(e,t,r){const i=e.slice(),s=i.shift();if("function"==typeof s)return[s,null,null];if("string"!=typeof s)throw new Error("[Formulario]: For array constraint first element must be rule name or Validator function");const[a,n]=V(s);if(o(t,a))return[F(t[a],a,i,r[a]||r.default),a,n];throw new Error("[Formulario] Can't create validator for constraint: "+JSON.stringify(e))}(e,t,r):"string"==typeof e?function(e,t,r){const i=e.split(":"),[s,a]=V(i.shift()||"");if(o(t,s))return[F(t[s],s,i.length?i.join(":").split(","):[],r[s]||r.default),s,a];throw new Error("[Formulario] Can't create validator for constraint: "+e)}(e,t,r):[()=>Promise.resolve(null),null,null]}function j(e){const t=[];if(e.length){let r=e.shift();t.push(r),e.forEach(e=>{e.bail||e.bail!==r.bail?(r=Object.assign({},e),t.push(r)):r.validators.push(...e.validators)})}return t}function R(e,t){return new Promise(r=>{const i=(e,o=[])=>{if(e.length){const s=e.shift();(function(e,t){return Promise.all(e.validators.map(e=>e(t))).then(e=>e.filter(e=>null!==e))})(s,t).then(t=>0!==t.length&&s.bail||!e.length?r(o.concat(t)):i(e,o.concat(t)))}else r([])};i(function(e){const t=([e,,t])=>({validators:[e],bail:"^"===t}),r=[],i=e.findIndex(([,e])=>e&&"bail"===e.toLowerCase());return i>=0?(r.push(...j(e.splice(0,i+1).slice(0,-1).map(t))),r.push(...e.map(([e])=>({validators:[e],bail:!0})))):r.push(...j(e.map(t))),r}(e))})}const w={DEMAND:"demand",LIVE:"live",SUBMIT:"submit"};let A=class extends r{constructor(){super(...arguments),this.proxy=this.getInitialValue(),this.localErrors=[],this.violations=[],this.validationRun=Promise.resolve()}get fullQualifiedName(){return""!==this.path?`${this.path}.${this.name}`:this.name}get model(){const e=this.hasModel?"value":"proxy";return void 0===this[e]?"":this[e]}set model(e){n(e,this.proxy)||(this.proxy=e),this.$emit("input",e),"function"==typeof this.formularioSetter&&this.formularioSetter(this.context.name,e)}get context(){return Object.defineProperty({name:this.fullQualifiedName,runValidation:this.runValidation.bind(this),violations:this.violations,errors:this.localErrors,allErrors:[...this.localErrors,...this.violations.map(e=>e.message)]},"model",{get:()=>this.model,set:e=>{this.model=e}})}get normalizedValidationRules(){const e={};return Object.keys(this.validationRules).forEach(t=>{e[l(t)]=this.validationRules[t]}),e}get normalizedValidationMessages(){const e={};return Object.keys(this.validationMessages).forEach(t=>{e[l(t)]=this.validationMessages[t]}),e}get hasModel(){return o(this.$options.propsData||{},"value")}onProxyChanged(e,t){this.hasModel||n(e,t)||(this.context.model=e),this.validationBehavior===w.LIVE?this.runValidation():this.violations=[]}onValueChanged(e,t){this.hasModel&&!n(e,t)&&(this.context.model=e)}created(){this.initProxy(),"function"==typeof this.formularioRegister&&this.formularioRegister(this.fullQualifiedName,this),"function"!=typeof this.addErrorObserver||this.errorsDisabled||this.addErrorObserver({callback:this.setErrors,type:"input",field:this.fullQualifiedName}),this.validationBehavior===w.LIVE&&this.runValidation()}beforeDestroy(){this.errorsDisabled||"function"!=typeof this.removeErrorObserver||this.removeErrorObserver(this.setErrors),"function"==typeof this.formularioDeregister&&this.formularioDeregister(this.fullQualifiedName)}getInitialValue(){return o(this.$options.propsData||{},"value")?this.value:""}initProxy(){n(this.context.model,this.proxy)||(this.context.model=this.proxy)}runValidation(){return this.validationRun=this.validate().then(e=>{const t=!n(e,this.violations);if(this.violations=e,t){const e={name:this.context.name,violations:this.violations};this.$emit("validation",e),"function"==typeof this.onFormularioFieldValidation&&this.onFormularioFieldValidation(e)}return this.violations}),this.validationRun}validate(){return R(function e(t,r,i){return"string"==typeof t?e(t.split("|").filter(e=>e.length),r,i):Array.isArray(t)?t.map(e=>O(e,r,i)):[]}(this.validation,this.$formulario.getRules(this.normalizedValidationRules),this.$formulario.getMessages(this,this.normalizedValidationMessages)),{value:this.context.model,name:this.context.name,formValues:this.getFormValues()})}hasValidationErrors(){return new Promise(e=>{this.$nextTick(()=>{this.validationRun.then(()=>e(this.violations.length>0))})})}setErrors(e){var t;this.localErrors=(t=e)?"string"==typeof t?[t]:Array.isArray(t)?t:"object"==typeof t?Object.values(t):[]:[]}resetValidation(){this.localErrors=[],this.violations=[]}};f([i.Inject({default:void 0})],A.prototype,"formularioSetter",void 0),f([i.Inject({default:()=>()=>{}})],A.prototype,"onFormularioFieldValidation",void 0),f([i.Inject({default:void 0})],A.prototype,"formularioRegister",void 0),f([i.Inject({default:void 0})],A.prototype,"formularioDeregister",void 0),f([i.Inject({default:()=>()=>({})})],A.prototype,"getFormValues",void 0),f([i.Inject({default:void 0})],A.prototype,"addErrorObserver",void 0),f([i.Inject({default:void 0})],A.prototype,"removeErrorObserver",void 0),f([i.Inject({default:""})],A.prototype,"path",void 0),f([i.Model("input",{default:""})],A.prototype,"value",void 0),f([i.Prop({required:!0,validator:e=>"string"==typeof e&&e.length>0})],A.prototype,"name",void 0),f([i.Prop({default:""})],A.prototype,"validation",void 0),f([i.Prop({default:()=>({})})],A.prototype,"validationRules",void 0),f([i.Prop({default:()=>({})})],A.prototype,"validationMessages",void 0),f([i.Prop({default:w.DEMAND,validator:e=>Object.values(w).includes(e)})],A.prototype,"validationBehavior",void 0),f([i.Prop({default:!1})],A.prototype,"errorsDisabled",void 0),f([i.Watch("proxy")],A.prototype,"onProxyChanged",null),f([i.Watch("value")],A.prototype,"onValueChanged",null),A=f([i.Component({name:"FormularioInput",inheritAttrs:!1})],A);const M=A;var _=function(){var e=this.$createElement;return(this._self._c||e)("div",{staticClass:"formulario-input"},[this._t("default",null,{context:this.context})],2)};_._withStripped=!0;const D=y({render:_,staticRenderFns:[]},void 0,M,void 0,!1,void 0,!1,void 0,void 0,void 0);return new class{constructor(){this.validationRules={},this.validationMessages={},this.validationRules=d,this.validationMessages=h}install(e,t){e.prototype.$formulario=this,e.component("FormularioForm",E),e.component("FormularioGrouping",N),e.component("FormularioInput",D),this.extend(t||{})}extend(e){if("object"==typeof e)return this.validationRules=s(this.validationRules,e.validationRules||{}),this.validationMessages=s(this.validationMessages,e.validationMessages||{}),this;throw new Error(`[Formulario]: Formulario.extend() should be passed an object (was ${typeof e})`)}getRules(e={}){return s(this.validationRules,e)}getMessages(e,t){const r=s(this.validationMessages||{},t),i={};for(const t in r)i[t]=(i,...o)=>"string"==typeof r[t]?r[t]:r[t](e,i,...o);return i}}})); + /** + * Shorthand for Object.prototype.hasOwnProperty.call (space saving) + */ + function has(ctx, prop) { + return Object.prototype.hasOwnProperty.call(ctx, prop); + } + + /** + * Create a new object by copying properties of base and mergeWith. + * Note: arrays don't overwrite - they push + * + * @param {Object} a + * @param {Object} b + * @param {boolean} concatArrays + */ + function merge(a, b, concatArrays = true) { + const merged = {}; + for (const key in a) { + if (has(b, key)) { + if (isPlainObject(b[key]) && isPlainObject(a[key])) { + merged[key] = merge(a[key], b[key], concatArrays); + } + else if (concatArrays && Array.isArray(a[key]) && Array.isArray(b[key])) { + merged[key] = a[key].concat(b[key]); + } + else { + merged[key] = b[key]; + } + } + else { + merged[key] = a[key]; + } + } + for (const prop in b) { + if (!has(merged, prop)) { + merged[prop] = b[prop]; + } + } + return merged; + } + + /** + * Converts to array. + * If given parameter is not string, object ot array, result will be an empty array. + * @param {*} item + */ + function arrayify(item) { + if (!item) { + return []; + } + if (typeof item === 'string') { + return [item]; + } + if (Array.isArray(item)) { + return item; + } + if (typeof item === 'object') { + return Object.values(item); + } + return []; + } + + function isScalar(data) { + switch (typeof data) { + case 'symbol': + case 'number': + case 'string': + case 'boolean': + case 'undefined': + return true; + default: + return data === null; + } + } + + /** + * A simple (somewhat non-comprehensive) clone function, valid for our use + * case of needing to unbind reactive watchers. + */ + function clone(value) { + if (typeof value !== 'object') { + return value; + } + const copy = Array.isArray(value) ? [] : {}; + for (const key in value) { + if (has(value, key)) { + if (isScalar(value[key])) { + copy[key] = value[key]; + } + else if (value instanceof Date) { + copy[key] = new Date(copy[key]); + } + else { + copy[key] = clone(value[key]); + } + } + } + return copy; + } + + /** + * Escape a string for use in regular expressions. + */ + function escapeRegExp(string) { + return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string + } + /** + * Given a string format (date) return a regex to match against. + */ + function regexForFormat(format) { + const escaped = `^${escapeRegExp(format)}$`; + const formats = { + MM: '(0[1-9]|1[012])', + M: '([1-9]|1[012])', + DD: '([012][1-9]|3[01])', + D: '([012]?[1-9]|3[01])', + YYYY: '\\d{4}', + YY: '\\d{2}' + }; + return new RegExp(Object.keys(formats).reduce((regex, format) => { + return regex.replace(format, formats[format]); + }, escaped)); + } + + function shallowEqualObjects(objA, objB) { + if (objA === objB) { + return true; + } + if (!objA || !objB) { + return false; + } + const aKeys = Object.keys(objA); + const bKeys = Object.keys(objB); + if (bKeys.length !== aKeys.length) { + return false; + } + if (objA instanceof Date && objB instanceof Date) { + return objA.getTime() === objB.getTime(); + } + if (aKeys.length === 0) { + return objA === objB; + } + for (let i = 0; i < aKeys.length; i++) { + const key = aKeys[i]; + if (objA[key] !== objB[key]) { + return false; + } + } + return true; + } + + /** + * Given a string, convert snake_case to camelCase + */ + function snakeToCamel(string) { + return string.replace(/([_][a-z0-9])/ig, ($1) => { + if (string.indexOf($1) !== 0 && string[string.indexOf($1) - 1] !== '_') { + return $1.toUpperCase().replace('_', ''); + } + return $1; + }); + } + + function getNested(obj, field) { + const fieldParts = field.split('.'); + let result = obj; + for (const key in fieldParts) { + const matches = fieldParts[key].match(/(.+)\[(\d+)\]$/); + if (result === undefined) { + return null; + } + if (matches) { + result = result[matches[1]]; + if (result === undefined) { + return null; + } + result = result[matches[2]]; + } + else { + result = result[fieldParts[key]]; + } + } + return result; + } + function setNested(obj, field, value) { + const fieldParts = field.split('.'); + let subProxy = obj; + for (let i = 0; i < fieldParts.length; i++) { + const fieldPart = fieldParts[i]; + const matches = fieldPart.match(/(.+)\[(\d+)\]$/); + if (matches) { + if (subProxy[matches[1]] === undefined) { + subProxy[matches[1]] = []; + } + subProxy = subProxy[matches[1]]; + if (i === fieldParts.length - 1) { + subProxy[matches[2]] = value; + break; + } + else { + subProxy = subProxy[matches[2]]; + } + } + else { + if (subProxy === undefined) { + break; + } + if (i === fieldParts.length - 1) { + subProxy[fieldPart] = value; + break; + } + else { + // eslint-disable-next-line max-depth + if (subProxy[fieldPart] === undefined) { + subProxy[fieldPart] = {}; + } + subProxy = subProxy[fieldPart]; + } + } + } + } + + const rules = { + /** + * Rule: the value must be "yes", "on", "1", or true + */ + accepted({ value }) { + return ['yes', 'on', '1', 1, true, 'true'].includes(value); + }, + /** + * Rule: checks if a value is after a given date. Defaults to current time + */ + after({ value }, compare = false) { + const compareTimestamp = compare !== false ? Date.parse(compare) : Date.now(); + const valueTimestamp = value instanceof Date ? value.getTime() : Date.parse(value); + return isNaN(valueTimestamp) ? false : (valueTimestamp > compareTimestamp); + }, + /** + * Rule: checks if the value is only alpha + */ + alpha({ value }, set = 'default') { + const sets = { + default: /^[a-zA-ZÀ-ÖØ-öø-ÿ]+$/, + latin: /^[a-zA-Z]+$/, + }; + return typeof value === 'string' && sets[has(sets, set) ? set : 'default'].test(value); + }, + /** + * Rule: checks if the value is alpha numeric + */ + alphanumeric({ value }, set = 'default') { + const sets = { + default: /^[a-zA-Z0-9À-ÖØ-öø-ÿ]+$/, + latin: /^[a-zA-Z0-9]+$/ + }; + return typeof value === 'string' && sets[has(sets, set) ? set : 'default'].test(value); + }, + /** + * Rule: checks if a value is after a given date. Defaults to current time + */ + before({ value }, compare = false) { + const compareTimestamp = compare !== false ? Date.parse(compare) : Date.now(); + const valueTimestamp = value instanceof Date ? value.getTime() : Date.parse(value); + return isNaN(valueTimestamp) ? false : (valueTimestamp < compareTimestamp); + }, + /** + * Rule: checks if the value is between two other values + */ + between({ value }, from = 0, to = 10, force) { + if (from === null || to === null || isNaN(from) || isNaN(to)) { + return false; + } + if ((!isNaN(Number(value)) && force !== 'length') || force === 'value') { + value = Number(value); + return (value > Number(from) && value < Number(to)); + } + if (typeof value === 'string' || force === 'length') { + value = (!isNaN(Number(value)) ? value.toString() : value); + return value.length > from && value.length < to; + } + return false; + }, + /** + * Confirm that the value of one field is the same as another, mostly used + * for password confirmations. + */ + confirm({ value, formValues, name }, field) { + let confirmationFieldName = field; + if (!confirmationFieldName) { + confirmationFieldName = /_confirm$/.test(name) ? name.substr(0, name.length - 8) : `${name}_confirm`; + } + return formValues[confirmationFieldName] === value; + }, + /** + * Rule: ensures the value is a date according to Date.parse(), or a format + * regex. + */ + date({ value }, format = false) { + return format ? regexForFormat(format).test(value) : !isNaN(Date.parse(value)); + }, + /** + * Rule: tests + */ + email({ value }) { + if (!value) { + return true; + } + // eslint-disable-next-line + const isEmail = /^(([^<>()\[\].,;:\s@"]+(\.[^<>()\[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})$/i; + return isEmail.test(value); + }, + /** + * Rule: Value ends with one of the given Strings + */ + endsWith({ value }, ...stack) { + if (!value) { + return true; + } + if (typeof value === 'string') { + return stack.length === 0 || stack.some(str => value.endsWith(str)); + } + return false; + }, + /** + * Rule: Value is in an array (stack). + */ + in({ value }, ...stack) { + return stack.some(item => typeof item === 'object' ? shallowEqualObjects(item, value) : item === value); + }, + /** + * Rule: Match the value against a (stack) of patterns or strings + */ + matches({ value }, ...stack) { + return !!stack.find(pattern => { + if (typeof pattern === 'string' && pattern.substr(0, 1) === '/' && pattern.substr(-1) === '/') { + pattern = new RegExp(pattern.substr(1, pattern.length - 2)); + } + if (pattern instanceof RegExp) { + return pattern.test(value); + } + return pattern === value; + }); + }, + /** + * Check the maximum value of a particular. + */ + max({ value }, maximum = 10, force) { + if (Array.isArray(value)) { + maximum = !isNaN(Number(maximum)) ? Number(maximum) : maximum; + return value.length <= maximum; + } + if ((!isNaN(value) && force !== 'length') || force === 'value') { + value = !isNaN(value) ? Number(value) : value; + return value <= maximum; + } + if (typeof value === 'string' || (force === 'length')) { + value = !isNaN(value) ? value.toString() : value; + return value.length <= maximum; + } + return false; + }, + /** + * Check the minimum value of a particular. + */ + min({ value }, minimum = 1, force) { + if (Array.isArray(value)) { + minimum = !isNaN(minimum) ? Number(minimum) : minimum; + return value.length >= minimum; + } + if ((!isNaN(value) && force !== 'length') || force === 'value') { + value = !isNaN(value) ? Number(value) : value; + return value >= minimum; + } + if (typeof value === 'string' || (force === 'length')) { + value = !isNaN(value) ? value.toString() : value; + return value.length >= minimum; + } + return false; + }, + /** + * Rule: Value is not in stack. + */ + not({ value }, ...stack) { + return !stack.some(item => typeof item === 'object' ? shallowEqualObjects(item, value) : item === value); + }, + /** + * Rule: checks if the value is only alpha numeric + */ + number({ value }) { + return String(value).length > 0 && !isNaN(Number(value)); + }, + /** + * Rule: must be a value + */ + required({ value }, isRequired = true) { + if (!isRequired || ['no', 'false'].includes(isRequired)) { + return true; + } + if (Array.isArray(value)) { + return !!value.length; + } + if (typeof value === 'string') { + return !!value; + } + if (typeof value === 'object') { + return (!value) ? false : !!Object.keys(value).length; + } + return true; + }, + /** + * Rule: Value starts with one of the given Strings + */ + startsWith({ value }, ...stack) { + if (!value) { + return true; + } + if (typeof value === 'string') { + return stack.length === 0 || stack.some(str => value.startsWith(str)); + } + return false; + }, + /** + * Rule: checks if a string is a valid url + */ + url({ value }) { + return isUrl(value); + }, + /** + * Rule: not a true rule — more like a compiler flag. + */ + bail() { + return true; + }, + }; + + /** + * Message builders, names match rules names, see @/validation/rules + */ + const messages = { + /** + * Fallback for rules without message builder + * @param vm + * @param context + */ + default(vm, context) { + return vm.$t('validation.default', context); + }, + accepted(vm, context) { + return vm.$t('validation.accepted', context); + }, + after(vm, context, compare = false) { + if (typeof compare === 'string' && compare.length) { + return vm.$t('validation.after.compare', context); + } + return vm.$t('validation.after.default', context); + }, + alpha(vm, context) { + return vm.$t('validation.alpha', context); + }, + alphanumeric(vm, context) { + return vm.$t('validation.alphanumeric', context); + }, + before(vm, context, compare = false) { + if (typeof compare === 'string' && compare.length) { + return vm.$t('validation.before.compare', context); + } + return vm.$t('validation.before.default', context); + }, + between(vm, context, from = 0, to = 10, force) { + const data = Object.assign(Object.assign({}, context), { from, to }); + if ((!isNaN(context.value) && force !== 'length') || force === 'value') { + return vm.$t('validation.between.force', data); + } + return vm.$t('validation.between.default', data); + }, + confirm(vm, context) { + return vm.$t('validation.confirm', context); + }, + date(vm, context, format = false) { + if (typeof format === 'string' && format.length) { + return vm.$t('validation.date.format', context); + } + return vm.$t('validation.date.default', context); + }, + email(vm, context) { + return vm.$t('validation.email.default', context); + }, + endsWith(vm, context) { + return vm.$t('validation.endsWith.default', context); + }, + in(vm, context) { + if (typeof context.value === 'string' && context.value) { + return vm.$t('validation.in.string', context); + } + return vm.$t('validation.in.default', context); + }, + matches(vm, context) { + return vm.$t('validation.matches.default', context); + }, + max(vm, context, maximum = 10, force) { + if (Array.isArray(context.value)) { + return vm.$tc('validation.max.array', maximum, context); + } + if ((!isNaN(context.value) && force !== 'length') || force === 'value') { + return vm.$tc('validation.max.force', maximum, context); + } + return vm.$tc('validation.max.default', maximum, context); + }, + min(vm, context, minimum = 1, force) { + if (Array.isArray(context.value)) { + return vm.$tc('validation.min.array', minimum, context); + } + if ((!isNaN(context.value) && force !== 'length') || force === 'value') { + return vm.$tc('validation.min.force', minimum, context); + } + return vm.$tc('validation.min.default', minimum, context); + }, + not(vm, context) { + return vm.$t('validation.not.default', context); + }, + number(vm, context) { + return vm.$t('validation.number.default', context); + }, + required(vm, context) { + return vm.$t('validation.required.default', context); + }, + startsWith(vm, context) { + return vm.$t('validation.startsWith.default', context); + }, + url(vm, context) { + return vm.$t('validation.url.default', context); + } + }; + + /** + * The base formulario library. + */ + class Formulario { + constructor(options) { + this.validationRules = {}; + this.validationMessages = {}; + this.validationRules = rules; + this.validationMessages = messages; + this.extend(options || {}); + } + /** + * Given a set of options, apply them to the pre-existing options. + */ + extend(extendWith) { + if (typeof extendWith === 'object') { + this.validationRules = merge(this.validationRules, extendWith.validationRules || {}); + this.validationMessages = merge(this.validationMessages, extendWith.validationMessages || {}); + return this; + } + throw new Error(`[Formulario]: Formulario.extend() should be passed an object (was ${typeof extendWith})`); + } + /** + * Get validation rules by merging any passed in with global rules. + */ + getRules(extendWith = {}) { + return merge(this.validationRules, extendWith); + } + /** + * Get validation messages by merging any passed in with global messages. + */ + getMessages(vm, extendWith) { + const raw = merge(this.validationMessages || {}, extendWith); + const messages = {}; + for (const name in raw) { + messages[name] = (context, ...args) => { + return typeof raw[name] === 'string' ? raw[name] : raw[name](vm, context, ...args); + }; + } + return messages; + } + } + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + + function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + } + + function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + } + + /** + * Component registry with inherent depth to handle complex nesting. This is + * important for features such as grouped fields. + */ + class Registry { + /** + * Create a new registry of components. + * @param {FormularioForm} ctx The host vm context of the registry. + */ + constructor(ctx) { + this.registry = new Map(); + this.ctx = ctx; + } + /** + * Fully register a component. + * @param {string} field name of the field. + * @param {FormularioForm} component the actual component instance. + */ + add(field, component) { + if (this.registry.has(field)) { + return; + } + this.registry.set(field, component); + // @ts-ignore + const value = getNested(this.ctx.initialValues, field); + const hasModel = has(component.$options.propsData || {}, 'value'); + // @ts-ignore + if (!hasModel && this.ctx.hasInitialValue && value !== undefined) { + // In the case that the form is carrying an initial value and the + // element is not, set it directly. + // @ts-ignore + component.context.model = value; + // @ts-ignore + } + else if (hasModel && !shallowEqualObjects(component.proxy, value)) { + // In this case, the field is v-modeled or has an initial value and the + // form has no value or a different value, so use the field value + // @ts-ignore + this.ctx.setFieldValueAndEmit(field, component.proxy); + } + } + /** + * Remove an item from the registry. + */ + remove(name) { + this.registry.delete(name); + // @ts-ignore + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const _a = this.ctx.proxy, _b = name, value = _a[_b], newProxy = __rest(_a, [typeof _b === "symbol" ? _b : _b + ""]); + // @ts-ignore + this.ctx.proxy = newProxy; + } + /** + * Check if the registry has the given key. + */ + has(key) { + return this.registry.has(key); + } + /** + * Check if the registry has elements, that equals or nested given key + */ + hasNested(key) { + for (const i of this.registry.keys()) { + if (i === key || i.includes(key + '.')) { + return true; + } + } + return false; + } + /** + * Get a particular registry value. + */ + get(key) { + return this.registry.get(key); + } + /** + * Get registry value for key or nested to given key + */ + getNested(key) { + const result = new Map(); + for (const i of this.registry.keys()) { + const objectKey = key + '.'; + const arrayKey = key + '['; + if (i === key || + i.substring(0, objectKey.length) === objectKey || + i.substring(0, arrayKey.length) === arrayKey) { + result.set(i, this.registry.get(i)); + } + } + return result; + } + /** + * Map over the registry (recursively). + */ + forEach(callback) { + this.registry.forEach((component, field) => { + callback(component, field); + }); + } + /** + * Return the keys of the registry. + */ + keys() { + return Array.from(this.registry.keys()); + } + /** + * Reduce the registry. + * @param {function} callback + * @param accumulator + */ + reduce(callback, accumulator) { + this.registry.forEach((component, field) => { + accumulator = callback(accumulator, component, field); + }); + return accumulator; + } + } + + class ErrorObserverRegistry { + constructor(observers = []) { + this.observers = []; + this.observers = observers; + } + add(observer) { + if (!this.observers.some(o => o.callback === observer.callback)) { + this.observers.push(observer); + } + } + remove(handler) { + this.observers = this.observers.filter(o => o.callback !== handler); + } + filter(predicate) { + return new ErrorObserverRegistry(this.observers.filter(predicate)); + } + some(predicate) { + return this.observers.some(predicate); + } + observe(errors) { + this.observers.forEach(observer => { + if (observer.type === 'form') { + observer.callback(errors); + } + else if (observer.field && + !Array.isArray(errors) && + has(errors, observer.field)) { + observer.callback(errors[observer.field]); + } + }); + } + } + + let FormularioForm = class FormularioForm extends Vue { + constructor() { + super(...arguments); + this.path = ''; + this.proxy = {}; + this.registry = new Registry(this); + this.errorObserverRegistry = new ErrorObserverRegistry(); + // Local error messages are temporal, they wiped each resetValidation call + this.localFormErrors = []; + this.localFieldErrors = {}; + } + get initialValues() { + if (this.hasModel && typeof this.formularioValue === 'object') { + // If there is a v-model on the form/group, use those values as first priority + return Object.assign({}, this.formularioValue); // @todo - use a deep clone to detach reference types + } + return {}; + } + get mergedFormErrors() { + return [...this.formErrors, ...this.localFormErrors]; + } + get mergedFieldErrors() { + return merge(this.errors || {}, this.localFieldErrors); + } + get hasModel() { + return has(this.$options.propsData || {}, 'formularioValue'); + } + get hasInitialValue() { + return this.formularioValue && typeof this.formularioValue === 'object'; + } + onFormularioValueChanged(values) { + if (this.hasModel && values && typeof values === 'object') { + this.setValues(values); + } + } + onMergedFormErrorsChanged(errors) { + this.errorObserverRegistry.filter(o => o.type === 'form').observe(errors); + } + onMergedFieldErrorsChanged(errors) { + this.errorObserverRegistry.filter(o => o.type === 'input').observe(errors); + } + created() { + this.initProxy(); + } + getFormValues() { + return this.proxy; + } + onFormSubmit() { + return this.hasValidationErrors() + .then(hasErrors => hasErrors ? undefined : clone(this.proxy)) + .then(data => { + if (typeof data !== 'undefined') { + this.$emit('submit', data); + } + else { + this.$emit('error'); + } + }); + } + onFormularioFieldValidation(payload) { + this.$emit('validation', payload); + } + addErrorObserver(observer) { + this.errorObserverRegistry.add(observer); + if (observer.type === 'form') { + observer.callback(this.mergedFormErrors); + } + else if (observer.field && has(this.mergedFieldErrors, observer.field)) { + observer.callback(this.mergedFieldErrors[observer.field]); + } + } + removeErrorObserver(observer) { + this.errorObserverRegistry.remove(observer); + } + register(field, component) { + this.registry.add(field, component); + } + deregister(field) { + this.registry.remove(field); + } + initProxy() { + if (this.hasInitialValue) { + this.proxy = this.initialValues; + } + } + setValues(values) { + const keys = Array.from(new Set([...Object.keys(values), ...Object.keys(this.proxy)])); + let proxyHasChanges = false; + keys.forEach(field => { + if (!this.registry.hasNested(field)) { + return; + } + this.registry.getNested(field).forEach((registryField, registryKey) => { + const $input = this.registry.get(registryKey); + const oldValue = getNested(this.proxy, registryKey); + const newValue = getNested(values, registryKey); + if (!shallowEqualObjects(newValue, oldValue)) { + this.setFieldValue(registryKey, newValue); + proxyHasChanges = true; + } + if (!shallowEqualObjects(newValue, $input.proxy)) { + $input.context.model = newValue; + } + }); + }); + this.initProxy(); + if (proxyHasChanges) { + this.$emit('input', Object.assign({}, this.proxy)); + } + } + setFieldValue(field, value) { + if (value === undefined) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const _a = this.proxy, _b = field, value = _a[_b], proxy = __rest(_a, [typeof _b === "symbol" ? _b : _b + ""]); + this.proxy = proxy; + } + else { + setNested(this.proxy, field, value); + } + } + setFieldValueAndEmit(field, value) { + this.setFieldValue(field, value); + this.$emit('input', Object.assign({}, this.proxy)); + } + setErrors({ formErrors, inputErrors }) { + this.localFormErrors = formErrors || []; + this.localFieldErrors = inputErrors || {}; + } + hasValidationErrors() { + return Promise.all(this.registry.reduce((resolvers, input) => { + resolvers.push(input.runValidation() && input.hasValidationErrors()); + return resolvers; + }, [])).then(results => results.some(hasErrors => hasErrors)); + } + resetValidation() { + this.localFormErrors = []; + this.localFieldErrors = {}; + this.registry.forEach((input) => { + input.resetValidation(); + }); + } + }; + __decorate([ + vuePropertyDecorator.Model('input', { default: () => ({}) }) + ], FormularioForm.prototype, "formularioValue", void 0); + __decorate([ + vuePropertyDecorator.Prop({ default: () => ({}) }) + ], FormularioForm.prototype, "errors", void 0); + __decorate([ + vuePropertyDecorator.Prop({ default: () => ([]) }) + ], FormularioForm.prototype, "formErrors", void 0); + __decorate([ + vuePropertyDecorator.Provide() + ], FormularioForm.prototype, "path", void 0); + __decorate([ + vuePropertyDecorator.Watch('formularioValue', { deep: true }) + ], FormularioForm.prototype, "onFormularioValueChanged", null); + __decorate([ + vuePropertyDecorator.Watch('mergedFormErrors') + ], FormularioForm.prototype, "onMergedFormErrorsChanged", null); + __decorate([ + vuePropertyDecorator.Watch('mergedFieldErrors', { deep: true, immediate: true }) + ], FormularioForm.prototype, "onMergedFieldErrorsChanged", null); + __decorate([ + vuePropertyDecorator.Provide() + ], FormularioForm.prototype, "getFormValues", null); + __decorate([ + vuePropertyDecorator.Provide() + ], FormularioForm.prototype, "onFormularioFieldValidation", null); + __decorate([ + vuePropertyDecorator.Provide() + ], FormularioForm.prototype, "addErrorObserver", null); + __decorate([ + vuePropertyDecorator.Provide() + ], FormularioForm.prototype, "removeErrorObserver", null); + __decorate([ + vuePropertyDecorator.Provide('formularioRegister') + ], FormularioForm.prototype, "register", null); + __decorate([ + vuePropertyDecorator.Provide('formularioDeregister') + ], FormularioForm.prototype, "deregister", null); + __decorate([ + vuePropertyDecorator.Provide('formularioSetter') + ], FormularioForm.prototype, "setFieldValueAndEmit", null); + FormularioForm = __decorate([ + vuePropertyDecorator.Component({ name: 'FormularioForm' }) + ], FormularioForm); + var script = FormularioForm; + + function normalizeComponent(template, style, script, scopeId, isFunctionalTemplate, moduleIdentifier /* server only */, shadowMode, createInjector, createInjectorSSR, createInjectorShadow) { + if (typeof shadowMode !== 'boolean') { + createInjectorSSR = createInjector; + createInjector = shadowMode; + shadowMode = false; + } + // Vue.extend constructor export interop. + const options = typeof script === 'function' ? script.options : script; + // render functions + if (template && template.render) { + options.render = template.render; + options.staticRenderFns = template.staticRenderFns; + options._compiled = true; + // functional template + if (isFunctionalTemplate) { + options.functional = true; + } + } + // scopedId + if (scopeId) { + options._scopeId = scopeId; + } + let hook; + if (moduleIdentifier) { + // server build + hook = function (context) { + // 2.3 injection + context = + context || // cached call + (this.$vnode && this.$vnode.ssrContext) || // stateful + (this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext); // functional + // 2.2 with runInNewContext: true + if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') { + context = __VUE_SSR_CONTEXT__; + } + // inject component styles + if (style) { + style.call(this, createInjectorSSR(context)); + } + // register component module identifier for async chunk inference + if (context && context._registeredComponents) { + context._registeredComponents.add(moduleIdentifier); + } + }; + // used by ssr in case component is cached and beforeCreate + // never gets called + options._ssrRegister = hook; + } + else if (style) { + hook = shadowMode + ? function (context) { + style.call(this, createInjectorShadow(context, this.$root.$options.shadowRoot)); + } + : function (context) { + style.call(this, createInjector(context)); + }; + } + if (hook) { + if (options.functional) { + // register for functional component in vue file + const originalRender = options.render; + options.render = function renderWithStyleInjection(h, context) { + hook.call(context); + return originalRender(h, context); + }; + } + else { + // inject component registration as beforeCreate hook + const existing = options.beforeCreate; + options.beforeCreate = existing ? [].concat(existing, hook) : [hook]; + } + } + return script; + } + + /* script */ + const __vue_script__ = script; + + /* template */ + var __vue_render__ = function() { + var _vm = this; + var _h = _vm.$createElement; + var _c = _vm._self._c || _h; + return _c( + "form", + { + on: { + submit: function($event) { + $event.preventDefault(); + return _vm.onFormSubmit($event) + } + } + }, + [_vm._t("default", null, { errors: _vm.mergedFormErrors })], + 2 + ) + }; + var __vue_staticRenderFns__ = []; + __vue_render__._withStripped = true; + + /* style */ + const __vue_inject_styles__ = undefined; + /* scoped */ + const __vue_scope_id__ = undefined; + /* module identifier */ + const __vue_module_identifier__ = undefined; + /* functional template */ + const __vue_is_functional_template__ = false; + /* style inject */ + + /* style inject SSR */ + + /* style inject shadow dom */ + + + + const __vue_component__ = /*#__PURE__*/normalizeComponent( + { render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ }, + __vue_inject_styles__, + __vue_script__, + __vue_scope_id__, + __vue_is_functional_template__, + __vue_module_identifier__, + false, + undefined, + undefined, + undefined + ); + + let FormularioGrouping = class FormularioGrouping extends Vue { + get groupPath() { + if (this.isArrayItem) { + return `${this.path}[${this.name}]`; + } + if (this.path === '') { + return this.name; + } + return `${this.path}.${this.name}`; + } + }; + __decorate([ + vuePropertyDecorator.Inject({ default: '' }) + ], FormularioGrouping.prototype, "path", void 0); + __decorate([ + vuePropertyDecorator.Prop({ required: true }) + ], FormularioGrouping.prototype, "name", void 0); + __decorate([ + vuePropertyDecorator.Prop({ default: false }) + ], FormularioGrouping.prototype, "isArrayItem", void 0); + __decorate([ + vuePropertyDecorator.Provide('path') + ], FormularioGrouping.prototype, "groupPath", null); + FormularioGrouping = __decorate([ + vuePropertyDecorator.Component({ name: 'FormularioGrouping' }) + ], FormularioGrouping); + var script$1 = FormularioGrouping; + + /* script */ + const __vue_script__$1 = script$1; + + /* template */ + var __vue_render__$1 = function() { + var _vm = this; + var _h = _vm.$createElement; + var _c = _vm._self._c || _h; + return _c("div", [_vm._t("default")], 2) + }; + var __vue_staticRenderFns__$1 = []; + __vue_render__$1._withStripped = true; + + /* style */ + const __vue_inject_styles__$1 = undefined; + /* scoped */ + const __vue_scope_id__$1 = undefined; + /* module identifier */ + const __vue_module_identifier__$1 = undefined; + /* functional template */ + const __vue_is_functional_template__$1 = false; + /* style inject */ + + /* style inject SSR */ + + /* style inject shadow dom */ + + + + const __vue_component__$1 = /*#__PURE__*/normalizeComponent( + { render: __vue_render__$1, staticRenderFns: __vue_staticRenderFns__$1 }, + __vue_inject_styles__$1, + __vue_script__$1, + __vue_scope_id__$1, + __vue_is_functional_template__$1, + __vue_module_identifier__$1, + false, + undefined, + undefined, + undefined + ); + + function createValidator(ruleFn, ruleName, ruleArgs, messageFn) { + return (context) => { + return Promise.resolve(ruleFn(context, ...ruleArgs)).then(valid => { + return !valid ? { + rule: ruleName, + args: ruleArgs, + context, + message: messageFn(context, ...ruleArgs), + } : null; + }); + }; + } + function parseModifier(ruleName) { + if (/^[\^]/.test(ruleName.charAt(0))) { + return [snakeToCamel(ruleName.substr(1)), ruleName.charAt(0)]; + } + return [snakeToCamel(ruleName), null]; + } + function processSingleArrayConstraint(constraint, rules, messages) { + const args = constraint.slice(); + const first = args.shift(); + if (typeof first === 'function') { + return [first, null, null]; + } + if (typeof first !== 'string') { + throw new Error('[Formulario]: For array constraint first element must be rule name or Validator function'); + } + const [name, modifier] = parseModifier(first); + if (has(rules, name)) { + return [ + createValidator(rules[name], name, args, messages[name] || messages.default), + name, + modifier, + ]; + } + throw new Error(`[Formulario] Can't create validator for constraint: ${JSON.stringify(constraint)}`); + } + function processSingleStringConstraint(constraint, rules, messages) { + const args = constraint.split(':'); + const [name, modifier] = parseModifier(args.shift() || ''); + if (has(rules, name)) { + return [ + createValidator(rules[name], name, args.length ? args.join(':').split(',') : [], messages[name] || messages.default), + name, + modifier, + ]; + } + throw new Error(`[Formulario] Can't create validator for constraint: ${constraint}`); + } + function processSingleConstraint(constraint, rules, messages) { + if (typeof constraint === 'function') { + return [constraint, null, null]; + } + if (Array.isArray(constraint) && constraint.length) { + return processSingleArrayConstraint(constraint, rules, messages); + } + if (typeof constraint === 'string') { + return processSingleStringConstraint(constraint, rules, messages); + } + return [() => Promise.resolve(null), null, null]; + } + function processConstraints(constraints, rules, messages) { + if (typeof constraints === 'string') { + return processConstraints(constraints.split('|').filter(f => f.length), rules, messages); + } + if (!Array.isArray(constraints)) { + return []; + } + return constraints.map(constraint => processSingleConstraint(constraint, rules, messages)); + } + function enlarge(groups) { + const enlarged = []; + if (groups.length) { + let current = groups.shift(); + enlarged.push(current); + groups.forEach((group) => { + if (!group.bail && group.bail === current.bail) { + current.validators.push(...group.validators); + } + else { + current = Object.assign({}, group); + enlarged.push(current); + } + }); + } + return enlarged; + } + /** + * Given an array of rules, group them by bail signals. For example for this: + * bail|required|min:10|max:20 + * we would expect: + * [[required], [min], [max]] + * because any sub-array failure would cause a shutdown. While + * ^required|min:10|max:10 + * would return: + * [[required], [min, max]] + * and no bailing would produce: + * [[required, min, max]] + * @param {array} rules + */ + function createValidatorGroups(rules) { + const mapper = ([validator, /** name */ , modifier]) => ({ + validators: [validator], + bail: modifier === '^', + }); + const groups = []; + const bailIndex = rules.findIndex(([, name]) => name && name.toLowerCase() === 'bail'); + if (bailIndex >= 0) { + groups.push(...enlarge(rules.splice(0, bailIndex + 1).slice(0, -1).map(mapper))); + groups.push(...rules.map(([validator]) => ({ + validators: [validator], + bail: true, + }))); + } + else { + groups.push(...enlarge(rules.map(mapper))); + } + return groups; + } + function validateByGroup(group, context) { + return Promise.all(group.validators.map(validate => validate(context))) + .then(violations => violations.filter(v => v !== null)); + } + function validate(validators, context) { + return new Promise(resolve => { + const resolveGroups = (groups, all = []) => { + if (groups.length) { + const current = groups.shift(); + validateByGroup(current, context).then(violations => { + // The rule passed or its a non-bailing group, and there are additional groups to check, continue + if ((violations.length === 0 || !current.bail) && groups.length) { + return resolveGroups(groups, all.concat(violations)); + } + return resolve(all.concat(violations)); + }); + } + else { + resolve([]); + } + }; + resolveGroups(createValidatorGroups(validators)); + }); + } + + const VALIDATION_BEHAVIOR = { + DEMAND: 'demand', + LIVE: 'live', + SUBMIT: 'submit', + }; + let FormularioInput = class FormularioInput extends Vue { + constructor() { + super(...arguments); + this.proxy = this.getInitialValue(); + this.localErrors = []; + this.violations = []; + this.validationRun = Promise.resolve(); + } + get fullQualifiedName() { + return this.path !== '' ? `${this.path}.${this.name}` : this.name; + } + get model() { + const model = this.hasModel ? 'value' : 'proxy'; + return this[model] !== undefined ? this[model] : ''; + } + set model(value) { + if (!shallowEqualObjects(value, this.proxy)) { + this.proxy = value; + } + this.$emit('input', value); + if (typeof this.formularioSetter === 'function') { + this.formularioSetter(this.context.name, value); + } + } + get context() { + return Object.defineProperty({ + name: this.fullQualifiedName, + runValidation: this.runValidation.bind(this), + violations: this.violations, + errors: this.localErrors, + allErrors: [...this.localErrors, ...this.violations.map(v => v.message)], + }, 'model', { + get: () => this.model, + set: (value) => { + this.model = value; + }, + }); + } + get normalizedValidationRules() { + const rules = {}; + Object.keys(this.validationRules).forEach(key => { + rules[snakeToCamel(key)] = this.validationRules[key]; + }); + return rules; + } + get normalizedValidationMessages() { + const messages = {}; + Object.keys(this.validationMessages).forEach(key => { + messages[snakeToCamel(key)] = this.validationMessages[key]; + }); + return messages; + } + /** + * Determines if this formulario element is v-modeled or not. + */ + get hasModel() { + return has(this.$options.propsData || {}, 'value'); + } + onProxyChanged(newValue, oldValue) { + if (!this.hasModel && !shallowEqualObjects(newValue, oldValue)) { + this.context.model = newValue; + } + if (this.validationBehavior === VALIDATION_BEHAVIOR.LIVE) { + this.runValidation(); + } + else { + this.violations = []; + } + } + onValueChanged(newValue, oldValue) { + if (this.hasModel && !shallowEqualObjects(newValue, oldValue)) { + this.context.model = newValue; + } + } + created() { + this.initProxy(); + if (typeof this.formularioRegister === 'function') { + this.formularioRegister(this.fullQualifiedName, this); + } + if (typeof this.addErrorObserver === 'function' && !this.errorsDisabled) { + this.addErrorObserver({ callback: this.setErrors, type: 'input', field: this.fullQualifiedName }); + } + if (this.validationBehavior === VALIDATION_BEHAVIOR.LIVE) { + this.runValidation(); + } + } + // noinspection JSUnusedGlobalSymbols + beforeDestroy() { + if (!this.errorsDisabled && typeof this.removeErrorObserver === 'function') { + this.removeErrorObserver(this.setErrors); + } + if (typeof this.formularioDeregister === 'function') { + this.formularioDeregister(this.fullQualifiedName); + } + } + getInitialValue() { + return has(this.$options.propsData || {}, 'value') ? this.value : ''; + } + initProxy() { + // This should only be run immediately on created and ensures that the + // proxy and the model are both the same before any additional registration. + if (!shallowEqualObjects(this.context.model, this.proxy)) { + this.context.model = this.proxy; + } + } + runValidation() { + this.validationRun = this.validate().then(violations => { + const validationChanged = !shallowEqualObjects(violations, this.violations); + this.violations = violations; + if (validationChanged) { + const payload = { + name: this.context.name, + violations: this.violations, + }; + this.$emit('validation', payload); + if (typeof this.onFormularioFieldValidation === 'function') { + this.onFormularioFieldValidation(payload); + } + } + return this.violations; + }); + return this.validationRun; + } + validate() { + return validate(processConstraints(this.validation, this.$formulario.getRules(this.normalizedValidationRules), this.$formulario.getMessages(this, this.normalizedValidationMessages)), { + value: this.context.model, + name: this.context.name, + formValues: this.getFormValues(), + }); + } + hasValidationErrors() { + return new Promise(resolve => { + this.$nextTick(() => { + this.validationRun.then(() => resolve(this.violations.length > 0)); + }); + }); + } + setErrors(errors) { + this.localErrors = arrayify(errors); + } + resetValidation() { + this.localErrors = []; + this.violations = []; + } + }; + __decorate([ + vuePropertyDecorator.Inject({ default: undefined }) + ], FormularioInput.prototype, "formularioSetter", void 0); + __decorate([ + vuePropertyDecorator.Inject({ default: () => () => { } }) + ], FormularioInput.prototype, "onFormularioFieldValidation", void 0); + __decorate([ + vuePropertyDecorator.Inject({ default: undefined }) + ], FormularioInput.prototype, "formularioRegister", void 0); + __decorate([ + vuePropertyDecorator.Inject({ default: undefined }) + ], FormularioInput.prototype, "formularioDeregister", void 0); + __decorate([ + vuePropertyDecorator.Inject({ default: () => () => ({}) }) + ], FormularioInput.prototype, "getFormValues", void 0); + __decorate([ + vuePropertyDecorator.Inject({ default: undefined }) + ], FormularioInput.prototype, "addErrorObserver", void 0); + __decorate([ + vuePropertyDecorator.Inject({ default: undefined }) + ], FormularioInput.prototype, "removeErrorObserver", void 0); + __decorate([ + vuePropertyDecorator.Inject({ default: '' }) + ], FormularioInput.prototype, "path", void 0); + __decorate([ + vuePropertyDecorator.Model('input', { default: '' }) + ], FormularioInput.prototype, "value", void 0); + __decorate([ + vuePropertyDecorator.Prop({ + required: true, + validator: (name) => typeof name === 'string' && name.length > 0, + }) + ], FormularioInput.prototype, "name", void 0); + __decorate([ + vuePropertyDecorator.Prop({ default: '' }) + ], FormularioInput.prototype, "validation", void 0); + __decorate([ + vuePropertyDecorator.Prop({ default: () => ({}) }) + ], FormularioInput.prototype, "validationRules", void 0); + __decorate([ + vuePropertyDecorator.Prop({ default: () => ({}) }) + ], FormularioInput.prototype, "validationMessages", void 0); + __decorate([ + vuePropertyDecorator.Prop({ + default: VALIDATION_BEHAVIOR.DEMAND, + validator: behavior => Object.values(VALIDATION_BEHAVIOR).includes(behavior) + }) + ], FormularioInput.prototype, "validationBehavior", void 0); + __decorate([ + vuePropertyDecorator.Prop({ default: false }) + ], FormularioInput.prototype, "errorsDisabled", void 0); + __decorate([ + vuePropertyDecorator.Watch('proxy') + ], FormularioInput.prototype, "onProxyChanged", null); + __decorate([ + vuePropertyDecorator.Watch('value') + ], FormularioInput.prototype, "onValueChanged", null); + FormularioInput = __decorate([ + vuePropertyDecorator.Component({ name: 'FormularioInput', inheritAttrs: false }) + ], FormularioInput); + var script$2 = FormularioInput; + + /* script */ + const __vue_script__$2 = script$2; + + /* template */ + var __vue_render__$2 = function() { + var _vm = this; + var _h = _vm.$createElement; + var _c = _vm._self._c || _h; + return _c( + "div", + { staticClass: "formulario-input" }, + [_vm._t("default", null, { context: _vm.context })], + 2 + ) + }; + var __vue_staticRenderFns__$2 = []; + __vue_render__$2._withStripped = true; + + /* style */ + const __vue_inject_styles__$2 = undefined; + /* scoped */ + const __vue_scope_id__$2 = undefined; + /* module identifier */ + const __vue_module_identifier__$2 = undefined; + /* functional template */ + const __vue_is_functional_template__$2 = false; + /* style inject */ + + /* style inject SSR */ + + /* style inject shadow dom */ + + + + const __vue_component__$2 = /*#__PURE__*/normalizeComponent( + { render: __vue_render__$2, staticRenderFns: __vue_staticRenderFns__$2 }, + __vue_inject_styles__$2, + __vue_script__$2, + __vue_scope_id__$2, + __vue_is_functional_template__$2, + __vue_module_identifier__$2, + false, + undefined, + undefined, + undefined + ); + + var index = { + install(Vue, options) { + Vue.component('FormularioForm', __vue_component__); + Vue.component('FormularioGrouping', __vue_component__$1); + Vue.component('FormularioInput', __vue_component__$2); + Vue.mixin({ + beforeCreate() { + const o = this.$options; + if (typeof o.formulario === 'function') { + this.$formulario = o.formulario(); + } + else if (o.parent && o.parent.$formulario) { + this.$formulario = o.parent.$formulario; + } + else { + this.$formulario = new Formulario(options); + } + } + }); + }, + }; + + return index; + +}))); diff --git a/package.json b/package.json index 1d40f06..35049b9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@retailcrm/vue-formulario", - "version": "0.3.2", + "version": "0.4.0", "author": "RetailDriverLLC ", "scripts": { "build": "npm run build:esm & npm run build:umd & npm run build:iife & wait && echo \"Build complete:\nesm: $(gzip -c dist/formulario.esm.js | wc -c)b gzip\numd: $(gzip -c dist/formulario.umd.js | wc -c)b gzip\nmin: $(gzip -c dist/formulario.min.js | wc -c)b gzip\"",