@upfrontjs/framework
Version:
Data handling framework complementary to backend model systems.
6 lines • 58 kB
JavaScript
/*! ================================
@upfrontjs/framework v0.19.0
(c) 2020-present Nandor Kraszlan
Released under MIT License
================================== */
import t from"lodash.uniq";import e from"lodash.orderby";import r from"lodash.isequal";import s from"lodash.merge";import i from"lodash.clonedeep";import n from"qs";import o from"lodash.snakecase";import{validate as a,v4 as h}from"uuid";import u from"pluralize";function l(t,e,r,s){return new(r||(r=Promise))(function(i,n){function o(t){try{h(s.next(t))}catch(t){n(t)}}function a(t){try{h(s.throw(t))}catch(t){n(t)}}function h(t){t.done?i(t.value):function(t){return t instanceof r?t:new r(function(e){e(t)})}(t.value).then(o,a)}h((s=s.apply(t,e||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class c extends Error{}class d extends c{get name(){return"LogicException"}}function g(t=void 0,e,r){if(!t)return r;"object"==typeof e&&"toArray"in e&&"function"==typeof e.toArray&&(e=e.toArray());const s=Array.isArray(e)?e:e.split(".");let i=t;for(let t=0;t<s.length;t++){if("*"===s[t]){if("object"==typeof i&&"toArray"in i&&"function"==typeof i.toArray&&(i=i.toArray()),!Array.isArray(i))return r;i=i.map(e=>g(e,s.slice(t+1),r));const e=s.slice(t).filter(t=>"*"===t).length;if(e>1&&(i=i.flat(e)),t+=e+1,i.every(t=>String(t)===String(r)))return r;continue}if(!(s[t]in i))return t=s.length,r;i=i[s[t]]}return i}function f(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}class y extends c{get name(){return"InvalidOffsetException"}}class m{constructor(t){if(this.length=0,!t)return this;let e=t;return Array.isArray(e)||(e=[e]),0===e.length||this._setArray(e),this}*[Symbol.iterator](){for(let t=0;t<this.length;t++)yield this[t]}_newInstance(t){return new this.constructor(t)}_setArray(t){for(const[e,r]of t.entries())this[e]=r;return this.length=t.length,this}first(t){if(!this.isEmpty())return t?this.toArray().filter((e,r)=>t(e,r))[0]:this[Number(this.keys()[0])]}last(t){if(!this.isEmpty())return t?this.toArray().reverse().filter((e,r)=>t(e,r))[0]:this[Number(this.keys().length-1)]}random(t=1){if(t=Math.abs(t),!this.length||0===t)return;if(t>=this.length)return this;if(t>1){const e=[];for(let r=0;r<t;r++)e.push(this[Math.floor(Math.random()*this.length)]);return this._newInstance(e)}return this[Math.floor(Math.random()*this.length)]}shuffle(){if(this.length<=1)return this._newInstance(this.toArray());const t=this.toArray();for(let e=t.length-1;e>0;e--){const r=Math.floor(Math.random()*(e+1));[t[e],t[r]]=[t[r],t[e]]}return this._newInstance(t)}is(t){return t instanceof this.constructor&&t.length===this.length&&this.every((e,s)=>r(e,t[s]))}isEmpty(){return!this.length}isNotEmpty(){return!this.isEmpty()}hasDuplicates(t){return!!this._newInstance(this.toArray()).duplicates(t).length}unique(e){if(!this._allAreObjects()){let r;if(e instanceof Function){const t=this.toArray();r=t.filter(r=>1===t.filter(t=>e(t)===e(r)).length)}else r=t(this.toArray());return this._newInstance(r)}const s=[];return this.forEach(t=>{(t=>e instanceof Function?!s.some(s=>r(e(s),e(t))):"string"==typeof e&&e in t?!s.some(s=>r(s[e],t[e])):!s.some(e=>r(e,t)))(t)&&s.push(t)}),this._newInstance(s)}duplicates(e){const s=this.toArray();if(!this._allAreObjects()){const e=s.filter(t=>s.filter(e=>r(e,t)).length>1);return this._newInstance(t(e))}const i=[];return this.forEach(t=>{let n;n=e instanceof Function?s.filter(s=>r(e(t),e(s))).length>1&&!i.some(s=>r(e(t),e(s))):e&&e in t?s.filter(s=>r(t[e],s[e])).length>1&&!i.some(s=>r(t[e],s[e])):s.filter(e=>r(t,e)).length>1&&!i.some(e=>r(t,e)),n&&i.push(t)}),this._newInstance(i)}delete(t){return this._newInstance(this.filter(e=>!r(e,t)).toArray())}nth(t){return this.filter((e,r)=>(r+1)%t===0)}withoutEmpty(){return this.filter(t=>null!=t)}pad(t,e){const r=this.length<Math.abs(t),s=this._newInstance(this.toArray());if(r){const r=Math.abs(t)-this.length,i=0<t;e instanceof Function&&(e=e()),e||(e=void 0);for(let t=0;t<r;t++)i?s.push(e):s.unshift(e)}return s}union(...t){const e=this._newInstance(this.toArray());return Array.from(t).forEach(t=>{t=Array.isArray(t)||m.isCollection(t)?t:[t],e.push(...t.filter(t=>!e.includes(t)))}),e}diff(t){const e=m.isCollection(t)?t:new m(Array.isArray(t)?t:[t]),r=this.toArray().filter(t=>!e.includes(t));return r.push(...e.toArray().filter(t=>!this.includes(t))),this._newInstance(r)}intersect(t){const e=m.isCollection(t)?t:new m(Array.isArray(t)?t:[t]);return this.filter(t=>e.includes(t))}chunk(t){const e=[];for(let r=0;r<this.length;r++){const s=r*t;s>=this.length||e.push(this.slice(s,s+t))}return new m(e)}chunkBy(t){if(!this._allAreObjects())throw new TypeError("Every item needs to be an object to be able to access its properties.");const e={};if("string"==typeof t||"number"==typeof t||"symbol"==typeof t){if(!this.every(e=>t in e))throw new y("'"+String(t)+"' is not present in every item of the collection.");this.pluck(String(t)).unique().forEach(r=>{e[r]=this.filter(e=>e[t]===r)})}else this.forEach(r=>{const s=t(r);s in e||(e[s]=new m),e[s].push(r)});return e}partition(t){const e=this._newInstance(),r=this._newInstance();return this.forEach(s=>t(s)?r.push(s):e.push(s)),[e,r]}when(t,e){return(t instanceof Function?!!t(this._newInstance(this.toArray())):!!t)?e(this._newInstance(this.toArray())):this}unless(t,e){return(t instanceof Function?!!t(this._newInstance(this.toArray())):!!t)?this:e(this._newInstance(this.toArray()))}whenEmpty(t){return this.isEmpty()&&t(this._newInstance(this.toArray())),this}whenNotEmpty(t){return this.isNotEmpty()&&t(this._newInstance(this.toArray())),this}take(t){return Math.abs(t)>this.length?this:t<0?this.reverse().filter((e,r)=>r+1<=Math.abs(t)).reverse():this.filter((e,r)=>r+1<=t)}takeUntil(t){const e=this.toArray(),r=[];for(;e[0]&&!t(e[0]);)r.push(e.splice(0,1)[0]);return this._newInstance(r)}takeWhile(t){const e=this.toArray(),r=[];for(;e[0]&&t(e[0]);)r.push(e.splice(0,1)[0]);return this._newInstance(r)}skip(t){return t>=this.length?this._newInstance(this.toArray()):t<0?this.reverse().filter((e,r)=>r>=Math.abs(t)).reverse():this.filter((e,r)=>r>=t)}skipUntil(t){const e=this.toArray();for(;e[0]&&!t(e[0]);)e.shift();return this._newInstance(e)}skipWhile(t){const e=this.toArray();for(;e.length&&t(e[0]);)e.shift();return this._newInstance(e)}pluck(t){if(!this._allAreObjects())throw new TypeError("Every item needs to be an object to be able to access its properties.");return Array.isArray(t)?this.map(e=>{const r={};return t.forEach(t=>r[t]=g(e,t)),r}):this.map(e=>g(e,t))}tap(t){return t(this._newInstance(this.toArray())),this}pipe(t){return t(this._newInstance(this.toArray()))}dump(t){return console.groupCollapsed((new Date).toLocaleTimeString()+(t?" ("+t+")":"")+":"),this.forEach((t,e)=>console.log(String(e)+":",t)),console.groupEnd(),this}keys(){return Object.keys(this).filter(t=>!isNaN(Number(t)))}orderBy(t,...r){if(!this._allAreObjects())throw new TypeError("Every item needs to be an object to be able to access its properties.");const s=Array.isArray(t)?t:[t];return s.push(...r),this._newInstance(e(this.toArray(),s.map(t=>t.property),s.map(t=>t.direction)))}getNumericValues(t){let e=this;if(t&&(e="string"==typeof t?e.pluck(t):e.map(t)),e=e.map(t=>Number(t)),e.some(t=>isNaN(t)))throw new d("Some values cannot be cast to numbers.");return e.toArray()}sum(t){return this.getNumericValues(t).reduce((t,e)=>t+e,0)}max(t){return this.getNumericValues(t).reduce((t,e)=>t>e?t:e)}min(t){return this.getNumericValues(t).reduce((t,e)=>t<e?t:e)}average(t){return this.sum(t)/this.length}toArray(){return Array.from(this)}toJSON(){return{elements:this.toArray()}}static isCollection(t){return t instanceof m}static times(t,e){const r=[];for(let s=1;s<t+1;s++)r.push(e instanceof Function?e(s):e);return new this(r)}includes(t){return this.some(e=>r(e,t))}forEach(t,e){return this.toArray().forEach(t,e),this}map(t,e){return new m(this.toArray().map(t,e))}reverse(){return this._newInstance(this.toArray().reverse())}concat(...t){return this._newInstance(this.toArray().concat(...t))}sort(t){return this._newInstance(this.toArray().sort(t))}splice(t,e,...r){const s=this.toArray(),i=s.splice(t,e,...r);return this._setArray(s),this._newInstance(i)}slice(t,e){return this._newInstance(this.toArray().slice(t,e))}filter(t,e){return this._newInstance(this.toArray().filter(t,e))}flat(t=1){const e=new m;return this.isEmpty()||(t>0?this.forEach(r=>{m.isCollection(r)?e.push(...r.flat(t-1)):e.push(r)}):e.push(...this.toArray())),e}flatMap(t,e){return new m(this.toArray().flatMap(t,e))}shift(){if(!this.length)return;const t=this.first();return this._setArray(this.filter((t,e)=>0!==e).toArray()),t}unshift(...t){return this._setArray([...t,...this]),this.length}pop(){const t=this.toArray(),e=t.pop();return this._setArray(t),e}push(...t){let e=this.length?Number(this.keys()[this.length-1])+1:0;for(const r of t)this[e]=r,e++;return this.length+=t.length,this.length}fill(t,e,r){return this._setArray(this.toArray().fill(t,e,r)),this}copyWithin(t,e,r){return this._newInstance(this.toArray().copyWithin(t,e,r))}every(t,e){return this.toArray().every(t,e)}some(t,e){return this.toArray().some(t,e)}find(t,e){return this.toArray().find(t,e)}findLast(t,e){return this.toArray().reverse().find(t,e)}findIndex(t,e){return this.toArray().findIndex(t,e)}findLastIndex(t,e){return this.toArray().findLastIndex(t,e)}indexOf(t,e=0){return this.toArray().indexOf(t,e)}join(t,e=t){return e="string"==typeof e?e:",",this._allAreObjects()?t?("string"==typeof t?this.pluck(t):this.map(t)).toArray().join(e):this.map(t=>String(t)).join(e):this.toArray().join(e)}toString(){return this.join()}lastIndexOf(t,e){return e?this.toArray().lastIndexOf(t,e):this.toArray().lastIndexOf(t)}reduce(t,e){return e?this.toArray().reduce(t,e):this.toArray().reduce(t)}reduceRight(t,e){return e?this.toArray().reduceRight(t,e):this.toArray().reduceRight(t)}with(t,e){return this._newInstance(this.toArray().with(t,e))}at(t){return this.toArray().at(t)}entries(){return this.toArray().entries()}values(){return this.toArray().values()}_allAreObjects(){return this.every(f)}}class p extends m{constructor(t){super(t),this._throwIfNotModels()}_throwIfNotModels(t){if(m.isCollection(t)&&(t=t.toArray()),t||(t=this.toArray()),(!Array.isArray(t)||t.length)&&!p._isModelArray(t))throw new TypeError("ModelCollection can only handle Model values.")}static _isModelArray(t){return!!Array.isArray(t)&&(!!t.length&&t.every(t=>this._isModel(t)))}static _isModel(t){return"object"==typeof t&&null!==t&&t.getKey instanceof Function&&t.getName instanceof Function}_getArgumentKeys(t){if(t instanceof p)return t.modelKeys().map(t=>String(t));t instanceof m&&(t=t.toArray());const e=Array.isArray(t)?t:[t];return new m(e.flat().filter(t=>"string"==typeof t||"number"==typeof t||p._isModel(t)).map(t=>String(p._isModel(t)?t.getKey():t)))}modelKeys(){return this._throwIfNotModels(),this.map(t=>t.getKey())}findByKey(t,e){this._throwIfNotModels();const r=new Set(this._getArgumentKeys(t)),s=[];return r.forEach(t=>{const e=this.toArray().find(e=>String(e.getKey())===t);e&&s.push(e)}),s.length?1===s.length?s[0]:this._newInstance(s):e}unique(t){this._throwIfNotModels();const e=[];return this.forEach(r=>{let s;s=t||t&&t in r?t instanceof Function?!e.some(e=>t(e)===t(r)):t in r&&r[t]instanceof Function?!e.some(e=>e[t]()===r[t]()):!e.some(e=>e[String(t)]===r[String(t)]):!e.some(t=>t.is(r)),s&&e.push(r)}),this._newInstance(e)}hasDuplicates(t){return!!this.duplicates(t).length}duplicates(t){this._throwIfNotModels();const e=this.toArray(),r=[];return this.forEach(s=>{let i;i=t instanceof Function?!r.some(e=>t(e)===t(s))&&e.filter(e=>t(e)===t(s)).length>1:t&&void 0!==s[t]?s[t]instanceof Function?!r.some(e=>e[t]()===s[t]())&&e.filter(e=>e[t]()===s[t]()).length>1:!r.some(e=>e[String(t)]===s[String(t)])&&e.filter(e=>e[String(t)]===s[String(t)]).length>1:!r.some(t=>t.is(s))&&e.filter(t=>t.is(s)).length>1,i&&r.push(s)}),this._newInstance(r)}diff(t){this._throwIfNotModels();const e=p.isModelCollection(t)?t:new p(Array.isArray(t)?t:[t]),r=this.toArray().filter(t=>!e.includes(t));return r.push(...e.toArray().filter(t=>!this.includes(t))),this._newInstance(r)}only(t){this._throwIfNotModels();const e=this._getArgumentKeys(t);return this._newInstance(this.toArray().filter(t=>e.includes(String(t.getKey()))))}except(t){this._throwIfNotModels();const e=this._getArgumentKeys(t);return this._newInstance(this.toArray().filter(t=>!e.includes(String(t.getKey()))))}static isModelCollection(t){return!!m.isCollection(t)&&(t instanceof p&&this._isModelArray(t.toArray()))}intersect(t){return t=p.isModelCollection(t)?t.toArray():Array.isArray(t)?t:[t],this._throwIfNotModels(),this._throwIfNotModels(t),super.intersect(t)}delete(t){return this._throwIfNotModels(),this._newInstance(this.toArray().filter(e=>!e.is(t)))}union(t){this._throwIfNotModels(t);const e=this._newInstance(this.toArray());return e.push(...t.filter(t=>!this.includes(t))),e}includes(t){this._throwIfNotModels();const[e]=this._getArgumentKeys(t);return!!this.toArray().filter(t=>String(t.getKey())===e).length}push(...t){return this._throwIfNotModels(Array.of(...t)),super.push(...t)}unshift(...t){return this._throwIfNotModels(Array.of(...t)),super.unshift(...t)}map(t,e){const r=super.map(t,e);return r.every(t=>p._isModel(t))?new this.constructor(r.toArray()):r}toJSON(){return{elements:this.toArray().map(t=>t.toJSON())}}}class w{constructor(t){t&&s(w.configuration,t)}get(t,e){if(!this.has(t))return e;const r=w.configuration[t];return w.usedAsReference.includes(t)||w.usedAsReference.includes("*")||"function"==typeof r?r:i(r)}has(t){return t in w.configuration}set(t,e){w.usedAsReference.includes(t)||w.usedAsReference.includes("*")?w.configuration[t]=e:w.configuration[t]="function"==typeof e?e:i(e)}unset(t){delete w.configuration[t]}reset(){w.configuration={}}}function A(t,e){return t.endsWith(e)?t:t+e}w.configuration={},w.usedAsReference=["headers"];class b extends c{get name(){return"InvalidArgumentException"}}class O{constructor(){this.getParamEncodingOptions={arrayFormat:"indices",strictNullHandling:!0,indices:!0,encodeValuesOnly:!0,charset:"utf-8"}}call(t,e,r,s,i){return l(this,void 0,void 0,function*(){const n=yield this.initConfig(t,e,r,s,i);return fetch(n.url,n.requestInit).then(t=>Object.assign(t,{request:n.requestInit}))})}initConfig(t,e,r,s,i){return l(this,void 0,void 0,function*(){var o;const a={method:e.toUpperCase()},h=new Headers((new w).get("headers"));if(i=null!=i?i:{},f(this.requestOptions)&&Object.assign(a,this.requestOptions),this.initRequest&&this.initRequest instanceof Function){const s=yield this.initRequest(t,e,r,i);f(s)&&Object.assign(a,s)}const u=new Headers(a.headers);return h.forEach((t,e)=>{u.append(e,t)}),a.method=null!==(o=a.method)&&void 0!==o?o:"GET","GET"!==a.method&&"HEAD"!==a.method||delete a.body,(f(r)&&Object.keys(r).length||r instanceof FormData)&&("GET"!==a.method&&"HEAD"!==a.method?r instanceof FormData?a.body=r:(u.has("Content-Type")||u.set("Content-Type",'application/json; charset="utf-8"'),a.body=JSON.stringify(r)):Object.assign(i,r)),Object.keys(i).length&&(t=A(t,"?")+n.stringify(i,this.getParamEncodingOptions)),f(s)&&Object.keys(s).forEach(t=>{let e=s[t];Array.isArray(e)||(e=[e]),e.forEach(e=>{if("string"!=typeof e)throw new b("For '"+t+"' expected type string, got: "+typeof e);u.append(t,e)})}),u.has("Accept")||u.set("Accept","application/json"),a.headers=u,{url:t,requestInit:a}})}}class N{handle(t){return l(this,void 0,void 0,function*(){return t.then(t=>l(this,void 0,void 0,function*(){return this.handleResponse(t)})).catch(t=>l(this,void 0,void 0,function*(){return this.handleError(t)})).finally(()=>this.handleFinally())})}handleResponse(t){return l(this,void 0,void 0,function*(){var e,r;if(t.status>=400)throw t;if(t.status<200||t.status>299||204===t.status)return;const s=null===(r=null===(e=t.request)||void 0===e?void 0:e.method)||void 0===r?void 0:r.toUpperCase();return s&&["OPTIONS","HEAD","TRACE","CONNECT"].includes(s)?t:"function"==typeof t.json?t.json():void 0})}handleError(t){return l(this,void 0,void 0,function*(){return Promise.reject(t)})}handleFinally(){}}function v(t){return t instanceof Function&&/^\s*class\s+/.test(String(t))}class E{constructor(){this.attributeCasts=this.casts}get casts(){return{}}mergeCasts(t){return this.attributeCasts=s(this.attributeCasts,t),this}setCasts(t){return this.attributeCasts=t,this}hasCast(t){const e=this.getCastType(t);return!!e&&["boolean","datetime","number","collection","object","string"].includes(e)}getCastType(t){const e=this.attributeCasts[t];if(e)return this.implementsCaster(e)?"object":e}castAttribute(t,e,r="get"){if(e=i(e),!this.hasCast(t))return e;switch(this.getCastType(t)){case"boolean":e=this.castToBoolean(t,e);break;case"string":e=this.castToString(t,e);break;case"number":e=this.castToNumber(t,e);break;case"object":e=this.castWithObject(t,e,this.getRawAttributes(),r);break;case"collection":"set"===r?m.isCollection(e)&&(e=e.toArray()):e=new m(e);break;case"datetime":"set"===r?this.castToDateTime(t,e):e=this.castToDateTime(t,e);break;default:throw new d("Impossible logic path reached. getCastType() returned unexpected value.")}return e}implementsCaster(t){return!!f(t)&&("set"in t&&t.set instanceof Function&&"get"in t&&t.get instanceof Function)}castToString(t,e){return String(e)}castToNumber(t,e){const r=Number(e);if(isNaN(r))throw new d("'"+t+"' is not castable to a number type in '"+this.getName()+"'.");return r}castToBoolean(t,e){const r=String(e).toLowerCase();let s;if(["1","true"].includes(r)&&(s=!0),["0","false"].includes(r)&&(s=!1),"boolean"!=typeof s)throw new d("'"+t+"' is not castable to a boolean type in '"+this.getName()+"'.");return s}castToDateTime(t,e){const r=(new w).get("datetime",Date);if("function"!=typeof r)throw new b("'datetime' is not of expected type set in the "+w.name+".");if(Object.is(Date,r)){if(null===e)return e;const r=new Date(e);if(isNaN(r.getTime()))throw new d("'"+t+"' is not castable to a date time in '"+this.getName()+"'.");return r}return v(r)?new r(e):r(e)}castWithObject(t,e,r,s){return this.attributeCasts[t][s](e,r)}}class P extends E{constructor(){super(...arguments),this.fillableAttributes=this.fillable,this.guardedAttributes=this.guarded}get fillable(){return[]}get guarded(){return["*"]}getGuarded(){return this.guardedAttributes}getFillable(){return this.fillableAttributes}mergeFillable(t){return this.fillableAttributes=[...this.getFillable(),...t],this}mergeGuarded(t){return this.guardedAttributes=[...this.getGuarded(),...t],this}setFillable(t){return this.fillableAttributes=t,this}setGuarded(t){return this.guardedAttributes=t,this}isFillable(t){return this.getFillable().includes(t)||this.getFillable().includes("*")}isGuarded(t){return(this.getGuarded().includes(t)||this.getGuarded().includes("*"))&&!this.isFillable(t)}getFillableFromObject(t){const e={};if(this.getFillable().includes("*"))return t;for(const[r,s]of Object.entries(t))this.isGuarded(r)||(e[r]=s);return e}}function C(t,e){return""===e?"":t.includes(e)?t.substring(t.indexOf(e)+e.length,t.length):""}function I(t,e){return""===e?"":t.includes(e)?t.substring(t.lastIndexOf(e)+e.length,t.length):""}function _(t,e){return""===e?"":t.includes(e)?t.substring(0,t.indexOf(e)):""}function S(t,e){return""===e?"":t.includes(e)?t.substring(0,t.lastIndexOf(e)):""}function M(t){return t.charAt(0).toUpperCase()+t.slice(1)}function R(t){return o(t)}function j(t){return M(R(t)).split("_").reduce((t,e)=>t+" "+M(e))}function x(t){const e=j(t).replace(/ /g,"");return e.charAt(0).toLowerCase()+e.slice(1)}function T(t,e){return e.every(e=>t.includes(e))}function D(t,e,r=!1){"string"==typeof e&&(e=new RegExp(e.replace(/\*/g,".*"),r?"i":""));const s=e.exec(t);return!!s&&!!s.length&&s[0]===t}function K(t){return"string"==typeof t&&a(t)}function k(t){return R(t).replace(/_/g,"-")}function F(t,e,r="..."){const s=t.substring(0,e);return t.length>s.length?s+r:s}function q(t){return M(x(t))}function Q(t){return u.plural(t)}function W(t){return u.singular(t)}function B(t,e){return t.startsWith(e)?t:e+t}function L(){return h()}function G(t,e,r="..."){const s=t.split(" ").slice(0,e).join(" ");return s.length===t.length?t:s+r}function U(t,e="camel"){const r={};return Object.keys(t).forEach(s=>{r["camel"===e?x(s):R(s)]=f(t[s])&&t[s].constructor===Object?U(t[s],e):Array.isArray(t[s])?t[s].map(t=>f(t)&&t.constructor===Object?U(t,e):t):t[s]}),r}class $ extends P{constructor(){super(...arguments),this.attributes=Object.create(null),this.original=Object.create(null)}get attributeCasing(){return"camel"}get serverAttributeCasing(){return"snake"}*[Symbol.iterator](){const t=Object.assign({},this.attributes,this.relations),e=Object.keys(t);for(let r=0;r<e.length;r++)yield[i(t[e[r]]),e[r]]}setStringCase(t){return"camel"===this.attributeCasing?x(t):R(t)}setServerStringCase(t){return"camel"===this.serverAttributeCasing?x(t):R(t)}getAttribute(t,e){var r;if(t in this.attributes)return this.hasGetAccessor(t)?this[`get${q(t)}Attribute`](i(this.attributes[t])):this.castAttribute(t,this.attributes[t]);if(this.relationLoaded(t))return this.getRelation(t);if(t in this){const s=null===(r=Reflect.getOwnPropertyDescriptor(this,t))||void 0===r?void 0:r.value;return void 0===s||s instanceof Function?e:s}return e}getAttributes(){const t={};return Object.keys(this.attributes).forEach(e=>{t[e]=this.getAttribute(e)}),t}getRawAttributes(){return i(this.attributes)}getAttributeKeys(){return Object.keys(this.attributes)}setAttribute(t,e){return this.hasSetMutator(t)?(this[`set${q(t)}Attribute`](i(e)),this.createDescriptor(t),this):this.hasCast(t)?(this.attributes[t]=this.castAttribute(t,e,"set"),this.createDescriptor(t),this):(f(e)&&!m.isCollection(e)||(Array.isArray(e)||m.isCollection(e))&&e.every(t=>f(t)))&&this.relationDefined(t)?(this.addRelation(t,e),this):(this.attributes[t]=i(e),this.createDescriptor(t),this)}setupMagicAccess(){var t;const e=[],r=[];null===(t=this.constructor.toString().match(/(?<!\$)(?:get|set)[a-zA-Z0-9_]*Attribute(?=\s*\()/g))||void 0===t||t.forEach(t=>{const s=t.startsWith("get")?"get":"set",i=this.setStringCase(t.slice(3,t.length-9));i in this.attributes||("get"===s?e.push(i):r.push(i))}),e.forEach(t=>{const e=r.findIndex(e=>e===t),s={get:()=>this[`get${q(t)}Attribute`](),enumerable:!0,configurable:!0};-1!==e&&(s.set=e=>this[`set${q(t)}Attribute`](e),r.splice(e,1)),Object.defineProperty(this,t,s)}),r.forEach(t=>{Object.defineProperty(this,t,{set:e=>this[`set${q(t)}Attribute`](e),enumerable:!0,configurable:!0})})}createDescriptor(t){return(t=Array.isArray(t)?t:[t]).forEach(t=>{Object.defineProperty(this,t,{get:()=>this.getAttribute(t),set:e=>this.setAttribute(t,e),enumerable:!0,configurable:!0})}),this}deleteAttribute(t){return delete this.attributes[t],this.relationDefined(t)?this.removeRelation(t):!Object.getOwnPropertyDescriptor(this,t)||this[t]instanceof Function||delete this[t],this}hasSetMutator(t){return`set${q(t)}Attribute`in this&&this[`set${q(t)}Attribute`]instanceof Function}hasGetAccessor(t){return`get${q(t)}Attribute`in this&&this[`get${q(t)}Attribute`]instanceof Function}fill(t){return this.forceFill(this.getFillableFromObject(t)),this}forceFill(t){t=U(t,this.attributeCasing);for(const[e,r]of Object.entries(t))this.setAttribute(e,r);return this}syncOriginal(t){return t?((t=Array.isArray(t)?t:[t]).flat().forEach(t=>{t in this.attributes?this.original[t]=i(this.attributes[t]):delete this.original[t]}),this):(this.original=i(this.attributes),this)}reset(){return this.attributes=i(this.original),this}getOriginal(t,e){const r=t=>this.hasGetAccessor(t)?this[`get${q(t)}Attribute`](i(this.original[t])):this.castAttribute(t,this.original[t]);if(t)return t in this.original?r(t):e;const s={};return Object.keys(this.original).forEach(t=>s[t]=r(t)),s}getRawOriginal(t,e){return t?t in this.original?i(this.original[t]):e:i(this.original)}getChanges(t){if(t)return r(this.getRawOriginal(t),this.attributes[t])?{}:{[t]:this.castAttribute(t,this.attributes[t])};const e={};return Object.keys(this.attributes).forEach(t=>{r(this.getRawOriginal(t),this.attributes[t])||(e[t]=this.castAttribute(t,this.attributes[t]))}),e}getDeletedAttributes(t){if(t)return t in this.original?t in this.attributes?{}:{[t]:this.castAttribute(t,this.original[t])}:{};const e=this.getRawAttributes(),r={};return Object.keys(this.getRawOriginal()).forEach(t=>{t in e||(r[t]=this.castAttribute(t,this.original[t]))}),r}getNewAttributes(t){if(t)return t in this.attributes?t in this.original?{}:{[t]:this.castAttribute(t,this.attributes[t])}:{};const e=this.getRawOriginal(),r={};return Object.keys(this.getRawAttributes()).forEach(t=>{t in e||(r[t]=this.castAttribute(t,this.attributes[t]))}),r}hasChanges(t){return!!Object.keys(this.getChanges(t)).length||!!Object.keys(this.getDeletedAttributes(t)).length||!!Object.keys(this.getNewAttributes(t)).length}isDirty(t){return this.hasChanges(t)}isClean(t){return!this.hasChanges(t)}only(t){t=Array.isArray(t)?t:[t];const e={};return t.forEach(t=>{t in this.attributes&&(e[t]=this.getAttribute(t))}),e}except(t){const e={};return t=Array.isArray(t)?t:[t],this.getAttributeKeys().filter(e=>!t.includes(e)).forEach(t=>{t in this.attributes&&(e[t]=this.getAttribute(t))}),e}toJSON(){const t=this.getRawAttributes(),e=this.getRelations();return Object.keys(e).forEach(r=>{e[r]instanceof $?t[r]=e[r].toJSON():t[r]=e[r].map(t=>t.toJSON()).toArray()}),t}toString(){return JSON.stringify(this.toJSON(),null,4)}}class H extends ${constructor(){super(...arguments),this.queryParameters={columns:[],distinct:[],limit:0,offset:0,orders:[],page:0,relationsExists:[],scopes:[],wheres:[],with:[],without:[]},this.withRelations=[]}static newQuery(){return new this}compileQueryParameters(){const t={};this.queryParameters.wheres.length&&(t.wheres=this.queryParameters.wheres),this.queryParameters.columns.length&&(t.columns=this.queryParameters.columns);const e=new Set([...this.queryParameters.with,...this.withRelations]);e.forEach(t=>{this.queryParameters.without.includes(t)&&e.delete(t)}),e.size&&(t.with=[...e]),this.queryParameters.scopes.length&&(t.scopes=this.queryParameters.scopes),this.queryParameters.relationsExists.length&&(t.relationsExists=this.queryParameters.relationsExists),this.queryParameters.orders.length&&(t.orders=this.queryParameters.orders),this.queryParameters.distinct.length&&(t.distinct=this.queryParameters.distinct),this.queryParameters.offset>0&&(t.offset=this.queryParameters.offset),this.queryParameters.limit>0&&(t.limit=this.queryParameters.limit),this.queryParameters.page>0&&(t.page=this.queryParameters.page);let r=t;return"formatQueryParameters"in this&&this.formatQueryParameters instanceof Function&&(r=this.formatQueryParameters(t)),r}resetQueryParameters(){return this.queryParameters={columns:[],distinct:[],limit:0,offset:0,orders:[],page:0,relationsExists:[],scopes:[],wheres:[],with:[],without:[]},this}addWhereConstraint(t,e,r,s){if(!["=","<",">","<=",">=","!=","like","in","notIn","between","notBetween"].includes(e))throw new b("'"+e+"' is not an expected type of operator.");if(s=s.toLowerCase(),!["and","or"].includes(s))throw new b("'"+s+"' is not an expected type of operator.");const i={column:t,operator:e,value:r,boolean:s};return this.queryParameters.wheres.some(i=>i.column===t&&i.operator===e&&i.boolean===s&&i.value==r)||this.queryParameters.wheres.push(i),this}where(t,e,r,s="and"){return this.addWhereConstraint(t,arguments.length>2?e:"=",arguments.length>2?r:e,s)}static where(t,e,r,s="and"){return this.newQuery().where(t,arguments.length>2?e:"=",arguments.length>2?r:e,s)}orWhere(t,e,r){return this.where(t,r?e:"=",r||e,"or")}whereKey(t,e="and"){const r=this.getKeyName();return Array.isArray(t)?this.whereIn(r,t,e):this.where(r,"=",t,e)}static whereKey(t,e="and"){return this.newQuery().whereKey(t,e)}orWhereKey(t){return this.whereKey(t,"or")}whereKeyNot(t,e="and"){const r=this.getKeyName();return Array.isArray(t)?this.whereNotIn(r,t,e):this.where(r,"!=",t,e)}static whereKeyNot(t,e="and"){return this.newQuery().whereKeyNot(t,e)}orWhereKeyNot(t){return this.whereKeyNot(t,"or")}whereNull(t,e="and"){return Array.isArray(t)||(t=[t]),t.forEach(t=>this.where(t,"=",String(null),e)),this}static whereNull(t){return this.newQuery().whereNull(t)}orWhereNull(t){return this.whereNull(t,"or")}whereNotNull(t,e="and"){return Array.isArray(t)||(t=[t]),t.forEach(t=>this.where(t,"!=",String(null),e)),this}static whereNotNull(t){return this.newQuery().whereNotNull(t)}orWhereNotNull(t){return this.whereNotNull(t,"or")}whereIn(t,e,r="and"){return this.where(t,"in",e,r)}static whereIn(t,e,r="and"){return this.newQuery().whereIn(t,e,r)}orWhereIn(t,e){return this.whereIn(t,e,"or")}whereNotIn(t,e,r="and"){return this.where(t,"notIn",e,r)}static whereNotIn(t,e,r="and"){return this.newQuery().whereNotIn(t,e,r)}orWhereNotIn(t,e){return this.whereNotIn(t,e,"or")}whereBetween(t,e,r="and"){if(!Array.isArray(e)||Array.isArray(e)&&2!==e.length)throw new b("Expected an array with 2 values for 'whereBetween' got: '"+JSON.stringify(e)+"'.");return this.where(t,"between",e,r)}static whereBetween(t,e,r="and"){return this.newQuery().whereBetween(t,e,r)}orWhereBetween(t,e){return this.where(t,"between",e,"or")}whereNotBetween(t,e,r="and"){if(!Array.isArray(e)||2!==e.length)throw new b("Expected an array with 2 values for 'whereNotBetween' got: '"+JSON.stringify(e)+"'.");return this.where(t,"notBetween",e,r)}static whereNotBetween(t,e,r="and"){return this.newQuery().whereNotBetween(t,e,r)}orWhereNotBetween(t,e){if(!Array.isArray(e)||2!==e.length)throw new b("Expected an array with 2 values for 'orWhereNotBetween' got: '"+JSON.stringify(e)+"'.");return this.where(t,"notBetween",e,"or")}limit(t){if("number"!=typeof t)throw new b("The limit method expects a number, got: "+typeof t);return this.queryParameters.limit=t,this}static limit(t){return this.newQuery().limit(t)}page(t){if("number"!=typeof t)throw new b("The page method expects a number, got: "+typeof t);return this.queryParameters.page=t,this}static page(t){return this.newQuery().page(t)}distinct(t){return this.queryParameters.distinct=Array.isArray(t)?t:[t],this}static distinct(t){return this.newQuery().distinct(t)}select(t){return this.queryParameters.columns.push(...Array.isArray(t)?t:[t]),this}static select(t){return this.newQuery().select(t)}has(t){return this.queryParameters.relationsExists.push(...Array.isArray(t)?t:[t]),this}static has(t){return this.newQuery().has(t)}with(t){return this.queryParameters.with.push(...Array.isArray(t)?t:[t]),this}static with(t){return this.newQuery().with(t)}without(t){return this.queryParameters.without.push(...Array.isArray(t)?t:[t]),this}static without(t){return this.newQuery().without(t)}scope(t){return this.queryParameters.scopes.push(...Array.isArray(t)?t:[t]),this}static scope(t){return this.newQuery().scope(t)}orderBy(t,e="asc"){return this.queryParameters.orders.push({column:t,direction:e}),this}static orderBy(t,e="asc"){return this.newQuery().orderBy(t,e)}orderByDesc(t){return this.orderBy(t,"desc")}static orderByDesc(t){return this.newQuery().orderByDesc(t)}latest(t){return t=null!=t?t:this.getCreatedAtName(),this.orderBy(this.setServerStringCase(t),"desc")}static latest(t){return this.newQuery().latest(t)}oldest(t){return t=null!=t?t:this.getCreatedAtName(),this.orderBy(this.setServerStringCase(t),"asc")}static oldest(t="created_at"){return this.newQuery().oldest(t)}offset(t){if("number"!=typeof t)throw new b("The offset method expects a number, got: "+typeof t);return this.queryParameters.offset=t,this}static offset(t){return this.newQuery().offset(t)}skip(t){return this.offset(t)}static skip(t){return this.newQuery().skip(t)}}class J extends H{get endpoint(){return""}get loading(){return this.requestCount>0}constructor(){super(),this.mutatedEndpoint="",this.requestCount=0,this.resetEndpoint()}call(t,e,r){return l(this,void 0,void 0,function*(){const s=this.getEndpoint();if(!s.length)throw new d("Endpoint is not defined when calling '"+t+"' method on '"+this.getName()+"'.");let i=U(this.compileQueryParameters(),this.serverAttributeCasing);const n=new w,o=(n.get("baseEndPoint")?A(n.get("baseEndPoint",""),"/"):"")+(s.startsWith("/")?s.slice(1):s),a=new(n.get("api",O)),h=new(n.get("apiResponseHandler",N));!e||!f(e)||e instanceof FormData||(e=U(e,this.serverAttributeCasing));const u=n.get("requestMiddleware");if(u){const s=yield u.handle(o,t,e,r,i);("data"in s&&void 0===s.data||f(s.data))&&(e=s.data),("customHeaders"in s&&void 0===s.customHeaders||f(s.customHeaders))&&(r=s.customHeaders),("queryParameters"in s&&void 0===s.queryParameters||f(s.queryParameters))&&(i=s.queryParameters)}return this.requestCount++,h.handle(a.call(o,t,e,r,i)).finally(()=>{this.requestCount--,this.resetEndpoint(),this.resetQueryParameters()})})}getDataFromResponse(t){return f(t)&&"data"in t?t.data:t}get(t){return l(this,void 0,void 0,function*(){return this.call("GET",t).then(t=>this.newInstanceFromResponseData(this.getDataFromResponse(t)))})}static get(t){return l(this,void 0,void 0,function*(){return(new this).get(t)})}post(t){return l(this,void 0,void 0,function*(){return this.call("POST",t).then(t=>this.getResponseModel(this.getDataFromResponse(t)))})}put(t){return l(this,void 0,void 0,function*(){return this.call("PUT",t).then(t=>this.getResponseModel(this.getDataFromResponse(t)))})}patch(t){return l(this,void 0,void 0,function*(){return this.call("PATCH",t).then(t=>this.getResponseModel(this.getDataFromResponse(t)))})}delete(t){return l(this,void 0,void 0,function*(){return this.call("DELETE",t).then(t=>this.getResponseModel(this.getDataFromResponse(t)))})}getResponseModel(t){return f(t)?this.newInstanceFromResponseData(t):this}newInstanceFromResponseData(t){if(null==t||"object"!=typeof t||Array.isArray(t)&&t.some(t=>!f(t)))throw new TypeError("Unexpected response type. Ensure that the endpoint returns model data only.");const e=t=>(new this.constructor).forceFill(t).syncOriginal().setLastSyncedAt();return Array.isArray(t)?new p(t.map(e)):e(t)}setLastSyncedAt(t=new Date){const e="_"+this.setStringCase("last_synced_at");return Object.defineProperty(this,e,{get:()=>this.castToDateTime(e,t),configurable:!0,enumerable:!0}),this}setEndpoint(t){return this.mutatedEndpoint=t,this}setModelEndpoint(){const t=this.getKey();if(!t)throw new d("Primary key missing when calling setModelEndpoint method");return this.setEndpoint(A(this.getEndpoint(),"/")+String(t))}getEndpoint(){return this.mutatedEndpoint}resetEndpoint(){return this.mutatedEndpoint="string"==typeof this.endpoint&&this.endpoint.length?this.endpoint:Q(k(this.getName()).toLowerCase()),this}appendToEndpoint(t){return this.mutatedEndpoint+=t,this}}class V extends J{constructor(){super(...arguments),this.relations={}}get relationMethodPrefix(){return"$"}load(t){return l(this,arguments,void 0,function*(t,e=!1){if(this.throwIfModelDoesntExistsWhenCalling("load"),Array.isArray(t)||(t=[t]),(t=t.filter(t=>e||!this.relationLoaded(t))).forEach(t=>{if(!this.relationDefined(t))throw new y("'"+t+"' relationship is not defined.")}),!t.length)return this;if(1===t.length){const e=yield this[B(t[0],this.relationMethodPrefix)]().get();return this.addRelation(t[0],e),this}const r=(yield this.with(t).setModelEndpoint().get()).getRelations();return Object.keys(r).forEach(t=>{this.addRelation(t,r[t])}),this})}relationLoaded(t){return this.loadedRelationKeys().includes(this.removeRelationPrefix(t))}loadedRelationKeys(){return Object.keys(this.getRelations())}getRelation(t){if(t=this.removeRelationPrefix(t),!this.relationDefined(t))throw new b("'"+t+"' relationship is not defined.");if(!this.relations[t])throw new d("Trying to access the '"+t+"' relationship before it is loaded.");return i(this.relations[t])}relationDefined(t){if(this[t=B(t,this.relationMethodPrefix)]instanceof Function){return this[t]()instanceof V&&!!this.getRelationType(t)}return!1}getRelationType(t){const e=this[t=B(t,this.relationMethodPrefix)]();if(!e._relationType)throw new d("'"+t+"' relation is not using any of the expected relation types.");return e._relationType}addRelation(t,e){if(t=this.removeRelationPrefix(t),!this.relationDefined(t))throw new d("Attempted to add an undefined relation: '"+t+"'.");const r=this.getRelationType(t),s=["belongsTo","hasOne","morphOne","morphTo"].includes(r),i=Array.isArray(e)&&e.every(t=>t instanceof V),n=t=>m.isCollection(t)&&t.every(t=>t instanceof V);if(e instanceof V||n(e)||i){if(s&&(n(e)||i))throw new b("'"+t+"' is a singular relation, received type: '"+e.constructor.name+"'.");return n(e)&&!p.isModelCollection(e)&&(e=new p(e.toArray())),i&&(e=new p(e)),e instanceof V&&(s?"belongsTo"===r&&this.setAttribute(e.guessForeignKeyName(),e.getKey()):e=new p([e])),this.relations[t]=e,this.createDescriptor(t),this}let o,a=this[B(t,this.relationMethodPrefix)]().constructor;if(Array.isArray(e)||m.isCollection(e)){if(s)throw new b("'"+t+"' is a singular relation, received type: '"+(Array.isArray(e)?Array.name:m.name)+"'.");const r=new p;e.forEach(t=>r.push(a.make(t))),o=r}else{const i=a.make(e);if("belongsTo"===r&&this.setAttribute(i.guessForeignKeyName(),i.getKey()),s)if("morphTo"===r){let r=this.morphToCb;if(!r){r=this[B(t,this.relationMethodPrefix)]().morphToCb}if("function"!=typeof r)throw new b("The morphTo relation was called with invalid argument type.");a=r(this,e),o=a.make(e),delete this.morphToCb}else o=i;else o=new p([i])}return this.relations[t]=o,this.createDescriptor(t),this}removeRelation(t){return t=this.removeRelationPrefix(t),delete this.relations[t],!Object.getOwnPropertyDescriptor(this,t)||this[t]instanceof Function||!this.relationDefined(t)||delete this[t],this}getRelations(){return i(this.relations)}guessForeignKeyName(){return this.setStringCase(R(this.getName()).toLowerCase()+"_"+this.getKeyName())}removeRelationPrefix(t){return t.startsWith(this.relationMethodPrefix)?t.slice(this.relationMethodPrefix.length):t}static configureRelationType(t,e){Object.defineProperty(t,"_relationType",{configurable:!1,enumerable:!1,writable:!1,value:e})}for(t){t=Array.isArray(t)?t:[t],this.resetEndpoint();let e="";return t.forEach(t=>{t instanceof V||(t=new t),e+=t.getEndpoint()+"/"+(t.getKey()?String(t.getKey())+"/":"")}),this.setEndpoint(e+this.getEndpoint()),this}belongsTo(t,e){const r=new t;e=null!=e?e:r.guessForeignKeyName();const s=this.getAttribute(e);if(!s)throw new d("'"+this.getName()+"' doesn't have '"+e+"' defined.");return V.configureRelationType(r,"belongsTo"),r.setEndpoint(A(r.getEndpoint(),"/")+String(s))}belongsToMany(t,e){const r=new t;return V.configureRelationType(r,"belongsToMany"),e=null!=e?e:Q(this.getName()).toLowerCase(),r.where(e+"."+this.getKeyName(),"=",this.getKey())}hasOne(t,e=this.guessForeignKeyName()){const r=new t;return V.configureRelationType(r,"hasOne"),r.setAttribute(e,this.getKey()),r.hasOneOrManyParentKeyName=e,r.where(e,"=",this.getKey())}hasMany(t,e=this.guessForeignKeyName()){const r=new t;return V.configureRelationType(r,"hasMany"),r.setAttribute(e,this.getKey()),r.hasOneOrManyParentKeyName=e,r.where(e,"=",this.getKey())}morphMany(t,e){const r=new t,s=r.getMorphs();return V.configureRelationType(r,"morphMany"),r.where(s.type,"=",null!=e?e:this.getName()).where(s.id,"=",this.getKey())}morphOne(t,e){const r=new t,s=r.getMorphs();return V.configureRelationType(r,"morphOne"),r.where(s.type,"=",null!=e?e:this.getName()).where(s.id,"=",this.getKey())}morphTo(t,e){e=null!=e?e:this.getMorphs().id.slice(0,-3);const r=(new this.constructor).with([e]);return r.setEndpoint(A(r.getEndpoint(),"/")+String(this.getKey())),V.configureRelationType(r,"morphTo"),Object.defineProperty(r,"morphToCb",{configurable:!0,enumerable:!1,writable:!1,value:t}),r}getMorphs(t){return{id:(t=null!=t?t:A(this.getName().toLowerCase(),"able"))+"_id",type:t+"_type"}}throwIfModelDoesntExistsWhenCalling(t){if(!this.exists)throw new d("Attempted to call "+t+" on '"+this.getName()+"' when it has not been persisted yet or it has been soft deleted.")}}class z extends V{constructor(){super(...arguments),this.timestamps=!0}getCreatedAtName(){return this.setStringCase(this.constructor.createdAt)}getUpdatedAtName(){return this.setStringCase(this.constructor.updatedAt)}usesTimestamps(){return this.timestamps}touch(){return l(this,void 0,void 0,function*(){if(!this.usesTimestamps())return this;this.throwIfModelDoesntExistsWhenCalling("touch");const t=this.getUpdatedAtName();return this.setModelEndpoint().patch({[t]:(new Date).toISOString()}).then(e=>{if(!(t in e))throw new b("'"+t+"' is not found in the response model.");return this.setAttribute(t,e.getAttribute(t)).syncOriginal(t)})})}freshTimestamps(){return l(this,void 0,void 0,function*(){if(!this.usesTimestamps())return this;this.throwIfModelDoesntExistsWhenCalling("freshTimestamps");const t=this.getCreatedAtName(),e=this.getUpdatedAtName();return this.select([t,e]).whereKey(this.getKey()).setModelEndpoint().get().then(r=>{if(!(t in r))throw new b("'"+t+"' is not found in the response model.");if(!(e in r))throw new b("'"+e+"' is not found in the response model.");return this.setAttribute(t,r.getAttribute(t)).setAttribute(e,r.getAttribute(e)).syncOriginal([t,e])})})}}z.createdAt="created_at",z.updatedAt="updated_at";class Y extends z{constructor(){super(...arguments),this.softDeletes=!0}trashed(){return!!this.getAttribute(this.getDeletedAtName())}getDeletedAtName(){return this.setStringCase(this.constructor.deletedAt)}usesSoftDeletes(){return this.softDeletes}delete(t){const e=Object.create(null,{delete:{get:()=>super.delete}});return l(this,void 0,void 0,function*(){if(!this.usesSoftDeletes())return e.delete.call(this,t);const r=this.getDeletedAtName();if(this.getAttribute(r))return this;if(this.throwIfModelDoesntExistsWhenCalling("delete"),this.setModelEndpoint(),t)if(t instanceof FormData){const e=this.setServerStringCase(r);t.has(e)||t.append(e,(new Date).toISOString())}else r in t||(t[r]=(new Date).toISOString());else t={[r]:(new Date).toISOString()};return e.delete.call(this,t).then(t=>this.setAttribute(r,t.getAttribute(r)).syncOriginal(r))})}restore(){return l(this,void 0,void 0,function*(){if(!this.usesSoftDeletes()||!this.getAttribute(this.getDeletedAtName()))return this;if(!this.getKey())throw new d("Attempted to call restore on '"+this.getName()+"' when it doesn't have a primary key.");return this.setModelEndpoint().patch({[this.getDeletedAtName()]:null}).then(t=>{const e=this.getDeletedAtName();return this.setAttribute(e,t.getAttribute(e,null)).syncOriginal(e)})})}}Y.deletedAt="deleted_at";class Z{constructor(){this.random=(new w).get("randomDataGenerator")}definition(t,e){return{}}getClassName(){return this.constructor.name}}class X{constructor(t){this.amount=1,this.states=[],this.relations={},this.extraAttributes={},this.model=new t}state(t){return this.states=Array.isArray(t)?[...new Set(t)]:[t],this}attributes(t){return this.extraAttributes=t,this}times(t){if(t<1)throw new b("'amount' expected to be higher than 0.");return this.amount=Math.round(t),this}raw(t){return this.addRelations(this.rawAttributes(t),"raw")}rawOne(t){return this.times(1).raw(t)}rawMany(t){const e=this.raw(t);return e instanceof m?e:new m(e)}make(t){const e=this.compileRaw(t),r=this.getFactory();return"afterMaking"in r&&r.afterMaking instanceof Function&&r.afterMaking(e),this.addRelations(e,"make")}makeOne(t){return this.times(1).make(t)}makeMany(t){const e=this.make(t);return e instanceof p?e:new p(e)}create(t){const e=this.compileRaw(t);p.isModelCollection(e)?e.forEach(t=>{this.addPersistenceAttributes(t)}):this.addPersistenceAttributes(e);const r=this.getFactory();return"afterCreating"in r&&r.afterCreating instanceof Function&&r.afterCreating(e),this.addRelations(e,"create")}createOne(t){return this.times(1).create(t)}createMany(t){const e=this.create(t);return e instanceof p?e:new p(e)}with(t,e){if(t instanceof X)e=null!=e?e:t.model.getName().toLowerCase();else{if(!v(t))throw new b("Argument for the 'with' method expected to be an instance of "+X.name+" or a Model constructor.");e=null!=e?e:(new t).getName().toLowerCase(),t=t.factory()}if(!this.model.relationDefined(e)&&(e=Q(e),!this.model.relationDefined(e)))throw new b("'"+this.model.getName()+"' doesn't have the '"+W(e)+"' or '"+e+"' relationship defined.");return this.relations[e]=t,this}addRelations(t,e){return Object.keys(this.relations).length&&(m.isCollection(t)?t=t.map(t=>this.addRelations(t,e)):Object.keys(this.relations).forEach(r=>{const s=this.relations[r][e]();"raw"===e?((new this.model.constructor).addRelation(r,s),t[r]=s):t.addRelation(r,s)})),t}addPersistenceAttributes(t){return t.getKey()||t.setAttribute(t.getKeyName(),this.getKey()),t.usesTimestamps()&&(t.getAttribute(t.getCreatedAtName())||t.setAttribute(t.getCreatedAtName(),(new Date).toISOString()),t.getAttribute(t.getUpdatedAtName())||t.setAttribute(t.getUpdatedAtName(),(new Date).toISOString())),t.setLastSyncedAt(),t.syncOriginal()}compileRaw(t){const e=this.rawAttributes(t);if(m.isCollection(e)){const t=[];return e.forEach(e=>{const r=new this.model.constructor;t.push(r.forceFill(e).syncOriginal())}),new p(t)}return(new this.model.constructor).forceFill(e).syncOriginal()}rawAttributes(t={}){var e,r,s,i;const n=this.getFactory(),o=[];let a=0;for(;a!==this.amount;){a++;let h=this.resolveAttributes(n.definition(this.model,a));null===(e=this.states)||void 0===e||e.forEach(t=>{if(!(t in n))throw new y("'"+t+"' is not defined on the '"+n.getClassName()+"' factory class.");if(!(n[t]instanceof Function))throw new y("'"+t+"' is not a method on the '"+n.getClassName()+"' factory class.");const e=n[t](this.model,a);if(!e||"object"!=typeof e)throw new TypeError("'"+t+"' is not returning an object on '"+n.getClassName()+"' factory class.");h=this.resolveAttributes(e,h)}),h=this.resolveAttributes(this.extraAttributes,h),this.model.usesTimestamps()&&(t[this.model.getCreatedAtName()]=null!==(r=t[this.model.getCreatedAtName()])&&void 0!==r?r:null,t[this.model.getUpdatedAtName()]=null!==(s=t[this.model.getUpdatedAtName()])&&void 0!==s?s:null),this.model.usesSoftDeletes()&&(t[this.model.getDeletedAtName()]=null!==(i=t[this.model.getDeletedAtName()])&&void 0!==i?i:null),o.push(this.resolveAttributes(t,h))}return o.length?1===o.length?o[0]:new m(o):{}}resolveAttributes(t,e={}){return Object.getOwnPropertyNames(t).forEach(r=>{e[r]=t[r]instanceof Function?t[r](e):t[r]}),e}getFactory(){if(this.factory)return this.factory;if(!("factory"in this.model&&this.model.factory instanceof Function))throw new y("The method factory() is either not defined or not and instance of Function on the '"+this.model.getName()+"' class.");const t=this.model.factory();if(!(t instanceof Z))throw new TypeError("Invalid return type defined on the factory() method on the '"+this.model.getName()+"' class. Expected '"+Z.name+"', got '"+typeof t+"'.");return this.factory=t}getKey(){const t=new w,e=t.get("_lastIds",{}),r=this.model.getName();return e[r]?(e[r]++,t.set("_lastIds",e)):(e[r]=1,t.set("_lastIds",e)),"string"===this.model.keyType?`unique-id-${e[r]}`:e[r]}}function tt(t,...e){return"function"==typeof t?t(...e):t}function et(t){return l(this,arguments,void 0,function*(t,e=3,r=0,s){return new Promise((i,n)=>{let o=0;const a=()=>{t().then(i).catch(t=>{s&&!s(t)&&n(t);const i=Array.isArray(e)?e[o]:r;o++<(Array.isArray(e)?e.length:e)?i?setTimeout(a,tt(i,o)):a():n(t)})};a()})})}function rt(t){return l(this,arguments,void 0,function*(t,e=0,r){let s=0;return new Promise((i,n)=>{const o=()=>l(this,void 0,void 0,function*(){try{s++;const n=yield t();if(r&&(r instanceof Date?new Date>=r:r(n,s)))return void i(n);setTimeout(()=>{o()},"function"==typeof e?e(n,s):e)}catch(t){n(t)}});o()})})}class st extends Y{get primaryKey(){return"id"}get keyType(){return"number"}get exists(){let t="string"===this.keyType?!!this.getKey():!isNaN(Number(this.getKey()));const e="_"+this.setStringCase("last_synced_at");return t&&this.usesTimestamps()&&(t=!!this.getAttribute(this.getCreatedAtName())),t&&this.usesSoftDeletes()&&(t=!this.getAttribute(this.getDeletedAtName())),t&&e in this&&!!this[e]}getKeyName(){return this.primaryKey}getKey(){return this.getAttribute(this.getKeyName())}new(t){return this.constructor.make(t)}static make(t){const e=new this;if(t instanceof st){const e=t.getRawAttributes();f(t.relations)&&Object.assign(e,t.getRelations()),t=e}return f(t)&&Object.keys(t).length&&e.fill(t).syncOriginal(),e.setupMagicAccess(),e}replicate(t){const e=new Set([this.getKeyName(),this.getCreatedAtName(),this.getUpdatedAtName(),this.getDeletedAtName()]);t&&(Array.isArray(t)?t.forEach(t=>e.add(t)):e.add(t));const r=Object.assign(Object.assign({},this.getRawAttributes()),this.getRelations());return e.forEach(t=>delete r[t]),this.new(r)}clone(){const t=this.new(this);return t.original=this.getRawOriginal(),t.fillableAttributes=i(this.fillableAttributes),t.guardedAttributes=i(this.guardedAttributes),t.attributeCasts=i(this.attributeCasts),t.hasOneOrManyParentKeyName=this.hasOneOrManyParentKeyName,t.mutatedEndpoint=this.mutatedEndpoint,t.setLastSyncedAt(this["_"+this.setStringCase("last_synced_at")]),t.queryParameters=i(this.queryParameters),t}is(t){return t instanceof st&&t.getKey()===this.getKey()&&t.getName()===this.getName()}isNot(t){return!this.is(t)}getName(){throw new Error("Your model has to define the getName method.")}when(t,e){return tt(t,this.clone())&&e(this),this}unless(t,e){return tt(t,this.clone())||e(this),this}tap(t){return t(this.clone()),this}static factory(t=1){return new X(this).times(t)}static all(){return l(this,void 0,void 0,function*(){let t=yield(new this).get();return t instanceof st&&(t=new p([t])),t})}save(t){return l(this,void 0,void 0,function*(){const e=Object.assign(this.exists?this.getChanges():this.getRawAttributes(),t);if(!Object.keys(e).length)return this;"_relationType"in this&&"string"==typeof this._relationType&&["hasOne","hasMany"].includes(this._relationType)&&(this.queryParameters.wheres=this.queryParameters.wheres.filter(t=>!("="===t.operator&&"and