/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/@thisisagile/easy@17.31.1/dist/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
"use strict";var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(t,e)=>{for(var s in e)__defProp(t,s,{get:e[s],enumerable:!0})},__copyProps=(t,e,s,i)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let r of __getOwnPropNames(e))__hasOwnProp.call(t,r)||r===s||__defProp(t,r,{get:()=>e[r],enumerable:!(i=__getOwnPropDesc(e,r))||i.enumerable});return t},__toESM=(t,e,s)=>(s=null!=t?__create(__getProtoOf(t)):{},__copyProps(!e&&t&&t.__esModule?s:__defProp(s,"default",{value:t,enumerable:!0}),t)),__toCommonJS=t=>__copyProps(__defProp({},"__esModule",{value:!0}),t),__decorateClass=(t,e,s,i)=>{for(var r,n=i>1?void 0:i?__getOwnPropDesc(e,s):e,o=t.length-1;o>=0;o--)(r=t[o])&&(n=(i?r(e,s,n):r(n))||n);return i&&n&&__defProp(e,s,n),n},src_exports={};__export(src_exports,{Agent:()=>Agent,Api:()=>Api,ApiGateway:()=>ApiGateway,App:()=>App,Audit:()=>Audit,AxiosProvider:()=>AxiosProvider,BaseContext:()=>BaseContext,BaseRequestContext:()=>BaseRequestContext,CacheControl:()=>CacheControl,Child:()=>Child,Clause:()=>Clause,Column:()=>Column,Condition:()=>Condition,ContentType:()=>ContentType,Context:()=>Context,Convert:()=>Convert,Database:()=>Database,DateTime:()=>DateTime,DefaultProvider:()=>DefaultProvider,Delete:()=>Delete,DotEnvContext:()=>DotEnvContext,EasyUri:()=>EasyUri,Entity:()=>Entity,Enum:()=>Enum,Environment:()=>Environment,Exception:()=>Exception,Field:()=>Field,Gateway:()=>Gateway,HttpHeader:()=>HttpHeader,HttpStatus:()=>HttpStatus,HttpVerb:()=>HttpVerb,InMemoryGateway:()=>InMemoryGateway,Insert:()=>Insert,Join:()=>Join,Jwt:()=>Jwt,List:()=>List,LogicalCondition:()=>LogicalCondition,Manage:()=>Manage,MappedRouteGateway:()=>MappedRouteGateway,Mapper:()=>Mapper,OrderColumn:()=>OrderColumn,PageList:()=>PageList,ParathesizedClause:()=>ParathesizedClause,Parser:()=>Parser,PatternColumn:()=>PatternColumn,Property:()=>Property,Repo:()=>Repo,Repository:()=>Repository,Req:()=>Req,RequestOptions:()=>RequestOptions,Results:()=>Results,RouteGateway:()=>RouteGateway,Scope:()=>Scope,Search:()=>Search,Select:()=>Select,Sentence:()=>Sentence,SortCondition:()=>SortCondition,SqlQuery:()=>SqlQuery,State:()=>State,Struct:()=>Struct,Table:()=>Table,TableGateway:()=>TableGateway,Template:()=>Template,ToText:()=>ToText,Try:()=>Try,Typo:()=>Typo,Update:()=>Update,UseCase:()=>UseCase,Value:()=>Value,View:()=>View,ViewRouteGateway:()=>ViewRouteGateway,Wait:()=>Wait,When:()=>When,accumulate:()=>accumulate,any:()=>any,api:()=>api,array:()=>array,asJson:()=>asJson,asList:()=>asList,asNumber:()=>asNumber,asPageList:()=>asPageList,asResults:()=>asResults,asString:()=>asString,asc:()=>asc,base64:()=>base64,build:()=>build,cache:()=>cache,cacheAge:()=>cacheAge,capitalize:()=>capitalize,choose:()=>choose,clipUri:()=>clipUri,constraint:()=>constraint,convert:()=>convert,ctx:()=>ctx,days:()=>days,defined:()=>defined,desc:()=>desc,dir:()=>dir,dt:()=>dt,entries:()=>entries,extractKeys:()=>extractKeys,future:()=>future,gt:()=>gt,gte:()=>gte,ifA:()=>ifA,ifDefined:()=>ifDefined,ifEither:()=>ifEither,ifFalse:()=>ifFalse,ifGet:()=>ifGet,ifNotEmpty:()=>ifNotEmpty,ifTrue:()=>ifTrue,inFuture:()=>inFuture,inList:()=>inList,inOptionalList:()=>inOptionalList,inPast:()=>inPast,includes:()=>includes,includesUuid:()=>includesUuid,isA:()=>isA,isAn:()=>isAn,isArray:()=>isArray,isBoolean:()=>isBoolean,isCacheAge:()=>isCacheAge,isClause:()=>isClause,isConstructor:()=>isConstructor,isCurrency:()=>isCurrency,isDate:()=>isDate,isDateTime:()=>isDateTime,isDefined:()=>isDefined,isDoesNotExist:()=>isDoesNotExist,isEmpty:()=>isEmpty,isEmptyObject:()=>isEmptyObject,isEnum:()=>isEnum,isEnumConstructor:()=>isEnumConstructor,isEqual:()=>isEqual,isError:()=>isError,isException:()=>isException,isFalsy:()=>isFalsy,isField:()=>isField,isFunc:()=>isFunc,isFunction:()=>isFunction,isHttpStatus:()=>isHttpStatus,isIdentity:()=>isIdentity,isIn:()=>isIn,isIndexed:()=>isIndexed,isInstance:()=>isInstance,isIntersecting:()=>isIntersecting,isIsoDateString:()=>isIsoDateString,isJson:()=>isJson,isList:()=>isList,isLoading:()=>isLoading,isMapping:()=>isMapping,isNotEmpty:()=>isNotEmpty,isNotPresent:()=>isNotPresent,isNullish:()=>isNullish,isNumber:()=>isNumber,isObject:()=>isObject,isPageList:()=>isPageList,isPresent:()=>isPresent,isPrimitive:()=>isPrimitive,isRequestOptions:()=>isRequestOptions,isResponse:()=>isResponse,isRestResult:()=>isRestResult,isResult:()=>isResult,isResults:()=>isResults,isSimpleView:()=>isSimpleView,isSortCondition:()=>isSortCondition,isString:()=>isString,isStruct:()=>isStruct,isText:()=>isText,isTrue:()=>isTrue,isTruthy:()=>isTruthy,isUndefined:()=>isUndefined,isUuid:()=>isUuid,isValid:()=>isValid,isValidatable:()=>isValidatable,isValue:()=>isValue,json:()=>json,kebab:()=>kebab,keys:()=>keys,log:()=>log,lt:()=>lt,lte:()=>lte,mappings:()=>mappings,maxLength:()=>maxLength,maxValue:()=>maxValue,meta:()=>meta,minLength:()=>minLength,minValue:()=>minValue,notEmpty:()=>notEmpty,ofConstruct:()=>ofConstruct,ofGet:()=>ofGet,ofMessage:()=>ofMessage,ofProperty:()=>ofProperty,on:()=>on,optional:()=>optional,past:()=>past,quote:()=>quote,reject:()=>reject,replaceAll:()=>replaceAll,required:()=>required,resolve:()=>resolve,rest:()=>rest,rule:()=>rule,searchable:()=>searchable,seconds:()=>seconds,settled:()=>settled,singleton:()=>singleton,tag:()=>tag,takeFirst:()=>takeFirst,takeFirstKey:()=>takeFirstKey,template:()=>template,text:()=>text,textValue:()=>textValue,toArray:()=>toArray,toCacheOptions:()=>toCacheOptions,toClause:()=>toClause,toCondition:()=>toCondition,toFilter:()=>toFilter,toHttpStatus:()=>toHttpStatus,toId:()=>toId,toJson:()=>toJson,toList:()=>toList,toName:()=>toName,toObject:()=>toObject,toPageList:()=>toPageList,toPageOptions:()=>toPageOptions,toReq:()=>toReq,toResponse:()=>toResponse,toResult:()=>toResult,toResults:()=>toResults,toSegment:()=>toSegment,toShortFilter:()=>toShortFilter,toUuid:()=>toUuid,toViewer:()=>toViewer,toWords:()=>toWords,traverse:()=>traverse,traverseSet:()=>traverseSet,tryTo:()=>tryTo,tuple:()=>tuple,tuple2:()=>tuple2,tuple3:()=>tuple3,tuple4:()=>tuple4,tuple5:()=>tuple5,tupleO:()=>tupleO,uri:()=>uri,use:()=>use,valid:()=>valid,validate:()=>validate,validateReject:()=>validateReject,values:()=>values,view:()=>view,views:()=>views,wait:()=>wait,we:()=>we,when:()=>when}),module.exports=__toCommonJS(src_exports);var isDefined=t=>null!=t,isUndefined=t=>null==t,isEmpty=t=>""===t||null==t||isArray(t)&&0===t.length,isNotEmpty=t=>""!==t&&null!=t&&(!isArray(t)||t.length>0),isString=t=>t instanceof String||"string"==typeof t,isIsoDateString=t=>isString(t)&&/^\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)$/.test(t),isBoolean=t=>isDefined(t)&&"boolean"==typeof t,isTrue=t=>isFunction(t)?isTrue(t()):isBoolean(t)?t:!!t,isNumber=t=>isDefined(t)&&"number"==typeof t&&!Number.isNaN(t),isObject=t=>null!=t&&"object"==typeof t&&!isArray(t),isEmptyObject=t=>isObject(t)&&0===Object.getOwnPropertyNames(t).length,isFunction=t=>isDefined(t)&&"function"==typeof t,isArray=t=>isDefined(t)&&t instanceof Array,isIn=(t,e)=>isArray(e)&&e.some((e=>e===t)),isIntersecting=(t,e)=>isArray(t)&&isArray(e)&&t.some((t=>isIn(t,e))),isError=t=>isDefined(t)&&t instanceof Error,isNotPresent=(...t)=>t.some((t=>null==t||""===t||t instanceof Array&&0===t.length||"object"==typeof t&&0===Object.getOwnPropertyNames(t).length)),isPresent=(...t)=>!isNotPresent(...t),isPrimitive=t=>null==t||isIn(typeof t,["string","number","bigint","boolean","symbol"]),isFunc=t=>!!t&&"function"==typeof t,isConstructor=t=>(isDefined(t)&&isFunc(t)&&t.prototype&&t.prototype.constructor)===t,isInstance=(t,e)=>isFunction(t)&&e instanceof t,ofConstruct=(t,...e)=>isConstructor(t)?new t(...e):isFunc(t)?t(...e):t,toName=(t,e="")=>t?.constructor?.name?.replace(e,"").toLowerCase()??"",isPromise=t=>t instanceof Promise,on=(t,e)=>{const s=e(t);return isPromise(s)?s.then((()=>t)):t},use=(t,e)=>e(t),ifA=(t,e,s)=>!isPrimitive(e)&&e instanceof t?e:s?ifA(t,s):void 0,isA=(t,...e)=>!isPrimitive(t)&&e.every((e=>e.toString()in t)),isAn=isA,isIdentity=t=>use(t,(t=>isObject(t)&&isDefined(t.id))),ofGet=(t,...e)=>isFunc(t)?t(...e):t,ifGet=(t,e,s)=>ofGet(t)?ofGet(e):ofGet(s),ofProperty=(t,e)=>isFunc(e)?e(t):t[e],toArray=(...t)=>t.length>1?t:isArray(t[0])?t[0]:isDefined(t[0])?[t[0]]:[],toObject=(t,...e)=>toArray(...e).reduce(((e,s)=>(e[s[t]]=s,e)),{}),array={merge:(t=[],e=[],s="id",i="id")=>t.map((t=>({...t,...e.find((e=>isDefined(e[i])&&isDefined(t[s])&&e[i]===t[s]))}))),switch:(t=[],e)=>use([...t],(t=>(on(t.indexOf(e),(s=>-1!==s?t.splice(s,1):t.push(e))),t))),splitIn:(t=[],e=2)=>{const s=Array.from({length:e},(()=>[]));return t.forEach(((t,i)=>s[i%e].push(t))),s},chunk:(t=[],e=2)=>{const s=Math.ceil(t.length/e),i=Array.from({length:s},(()=>[]));return t.forEach(((t,e)=>i[Math.floor(e/s)].push(t))),i}},isText=t=>isDefined(t)&&isFunc(t.toString),asString=(t,e="")=>(isText(t)?t:ofGet(e)).toString(),replaceAll=(t,e,s="")=>asString(t).split(asString(e)).join(asString(s)),toWords=t=>asString(t).replace(/(\p{Lower})(\p{Upper})/gu,"$1 $2").replace(/(\p{Upper})(\p{Upper}\p{Lower})/gu,"$1 $2").split(/[_\W]+/g).filter(Boolean),kebab=(t="")=>toWords(t).join("-").toLowerCase(),capitalize=(t="")=>t.charAt(0).toUpperCase()+t.slice(1),traverse=(t,e="")=>{t??={};const s=e.split("."),i=s.shift();return 0===s.length?t[i]:traverse(t[i],s.join("."))},traverseSet=(t,e,s)=>{const i=e.split("."),r=i.shift();return{...t,[r]:0===i.length?s:traverseSet(t[r],i.join("."),s)}},accumulate=(t,...e)=>t.map(((t,s,i)=>{const r=e.reduce(((e,r)=>traverseSet(e,r,0===s?traverse(t,r):traverse(i[s-1],r)+traverse(t,r))),t);return i[s]=r,r})),List=class extends Array{get ids(){return this.mapDefined((t=>t.id))}get indexed(){return this.map(((t,e)=>({...t,index:e})))}isSubSetOf(...t){return 0===this.diff(t).length}isSuperSetOf(...t){return this.length>t.length&&toList(...t).isSubSetOf(...this)}isIntersectingWith(...t){return this.intersect(t).length>0}isDisjointWith(...t){return!this.isIntersectingWith(...t)}areEqual(...t){return this.isSubSetOf(...t)&&toList(...t).isSubSetOf(...this)}asc(t){return this.sort(((e,s)=>ofProperty(e,t)>ofProperty(s,t)?1:-1))}desc(t){return this.sort(((e,s)=>ofProperty(e,t)<ofProperty(s,t)?1:-1))}first(t,e){return t?this.find(t,e):this[0]}firstValue(t,e){return ifDefined(this.first((e=>!!t(e))),t,(t=>ofGet(e,t)))}isFirst(t){return t===this.first()}next(t,e){return t?this[this.findIndex(t,e)+1]:this[0]}prev(t,e){return t?this[this.findIndex(t,e)-1]:this[0]}last(t,e){return t?this.filter(t,e).last():this[this.length-1]}isLast(t){return t===this.last()}overlaps(...t){return toList(...t).some((t=>this.some((e=>t===e))))}diff(t){return this.filter((e=>!t.includes(e)))}diffByKey(t,e){return this.filter((s=>!t.some((t=>t[e]===s[e]))))}symmetricDiff(t){return this.diff(t).concat(toList(...t).diff(this))}symmetricDiffByKey(t,e){return this.diffByKey(t,e).concat(toList(...t).diffByKey(this,e))}intersect(t){return this.filter((e=>t.includes(e)))}intersectByKey(t,e){return this.filter((s=>t.some((t=>t[e]===s[e]))))}intersectBy(t,e){return this.filter((s=>t.some((t=>e(s,t)))))}accumulate(...t){return this.map(((e,s,i)=>{const r=t.reduce(((t,r)=>(t[r]=0===s?e[r]:i[s-1][r]+e[r],t)),e);return i[s]=r,r}))}toJSON(){return this.reduce(((t,e)=>(t.push(JSON.parse(JSON.stringify(e??{}))),t)),new Array)}map(t,e){return toList(super.map(t,e))}flatMap(t,e){return toList(super.flatMap(t,e))}mapDefined(t,e){return this.map(t,e).defined()}mapAsync(t){return Promise.all(super.map((e=>t(e)))).then((t=>toList(t)))}mapSerial(t){return super.reduce(((e,s)=>e.then((e=>on(e,(async e=>e.push(await t(s))))))),Promise.resolve(toList()))}distinct(){return this.filter(((t,e)=>this.indexOf(t)===e))}distinctByKey(t){const e=new Set;return this.filter((s=>!e.has(s[t])&&e.add(s[t])))}distinctByValue(){const t=new Set;return this.filter((e=>!t.has(JSON.stringify(e))&&t.add(JSON.stringify(e))))}filter(t,e){return toList(super.filter(t,e))}sum(t){return this.reduce(((e,s)=>e+t(s)),0)}max(t){return"function"==typeof t?this.sort(((e,s)=>t(e)<t(s)?1:-1)).first():this.desc(t).first()}min(t){return"function"==typeof t?this.sort(((e,s)=>t(e)>t(s)?1:-1)).first():this.asc(t).first()}byId(t){return this.first((e=>asString(e.id)===asString(t)))}byKey(t,e){return this.first((s=>s[t]==e))}add(...t){return super.push(...toArray(...t)),this}concat(...t){return toList(super.concat(...t))}reverse(){return toList(super.reverse())}splice(t,e,...s){return toList(super.splice(t,e,...s))}remove(t){const e=this.indexOf(t);return e>-1&&this.splice(e,1),this}replace(t,e){const s=this.findIndex((s=>s[t]===e?.[t]));return ifTrue(-1!=s,(()=>this.splice(s,1,e))),this}switch(t){return this.includes(t)?this.remove(t):this.add(t)}switchOn(t,e){return use("function"==typeof e?this.find(e):use(traverse(t,e),(t=>this.find((s=>traverse(s,e)===t)))),(e=>e?this.remove(e):this.add(t)))}defined(){return this.reduce(((t,e)=>isDefined(e)?t.add(e):t),toList())}toObject(t,e={}){return this.reduce(((s,i)=>(s[i[t]]=i,e.deleteKey&&delete s[i[t]][t],s)),{})}toObjectList(t){return this.reduce(((e,s)=>{const i=s[t];return e[i]=e[i]??toList(),e[i].push(s),e}),{})}orElse(...t){return isEmpty(this)?isEmpty(...t)?void 0:toList(...t):this}weave(t,e){for(let s=e,i=0;s<=this.length&&i<t.length;s+=e+1)this.splice(s,0,t[i++]);return this}slice(t,e){return toList(super.slice(t,e))}none(t){return!this.some(t)}chunk(t){return this.reduce(((e,s,i)=>i%t==0?on(e,(e=>e.push(this.slice(i,i+t)))):e),toList())}update(t,e){return this.map(((s,i,r)=>t(s,i,r)?ofGet(e,s,i,r):s))}updateFirst(t,e){const s=this.findIndex(t);return this.update(((e,i)=>t(e,i,this)&&i==s),e)}updateFirstById(t,e){return this.updateFirst((e=>asString(e?.id)===asString(t)),e)}updateById(t,e){return this.update((e=>asString(e?.id)===asString(t)),e)}},toList=(...t)=>(new List).add(...t),isList=t=>isDefined(t)&&isArray(t)&&isA(t,"first","last","asc","desc"),asList=(t,e=[])=>toList(toArray(e).map((e=>new t(e)))),maxValue=(t,e)=>t.desc(e).first()?.[e],minValue=(t,e)=>t.asc(e).first()?.[e];function ifTrue(t,e,s){return isTrue(t)?ofConstruct(e,t):ofConstruct(s,t)}function ifFalse(t,e,s){return isTrue(t)?ofConstruct(s,t):ofConstruct(e,t)}function ifDefined(t,e,s){return isDefined(t)?ofConstruct(e,t):ofConstruct(s)}function ifNotEmpty(t,e=t=>t,s){return isNotEmpty(t)?ofConstruct(e,t):ofConstruct(s,t)}function ifEither(t,e=t=>t,s){return use(toList(t).first((t=>isPresent(t))),(t=>isDefined(t)?ofConstruct(e,t):ofConstruct(s,t)))}function entries(t){return ifDefined(t,(()=>toList([...Object.entries(t),...Object.entries(Object.getPrototypeOf(t)??{})])),(()=>toList()))}function values(t){return toList([...Object.values(t),...Object.values(Object.getPrototypeOf(t)??{})])}function keys(t){return toList([...Object.keys(t),...Object.keys(Object.getPrototypeOf(t)??{})])}function extractKeys(t,e){return e.filter((e=>e in t)).reduce(((e,s)=>(e.keys[s]=t[s],delete e[s],e)),{keys:{},...t})}var isJson=t=>isA(t,"toJSON"),json={parse:t=>JSON.parse(JSON.stringify(t??{})),merge:(...t)=>json.parse(t.map((t=>asJson(t,(t=>json.parse(t))))).reduce(((t,e)=>({...t,...e})),{})),delete:(t,e)=>(ifDefined(t,(()=>delete t[e])),t),set:(t,e="",s)=>isEmpty(e)?t:void 0!==s?{...t,[e]:s}:json.delete(t,e),omit:(t,...e)=>e.reduce(((t,e)=>json.delete(t,e)),json.parse(t)),pick:(t,...e)=>e.reduce(((e,s)=>json.set(e,s,t[s])),{}),defaults:(t={},e={})=>json.merge(e,t),isSubset:(t,e)=>!entries(e).some((([e,s])=>t[e]!==s)),split:(t,e,s="extracted")=>{const i={},r={...t};return e.forEach((e=>{e in t&&(ifDefined(t[e],(t=>i[e]=t)),delete r[e])})),{[s]:i,...r}}},toJson=json.merge,asJson=(t,e={})=>isJson(t)?t.toJSON():isObject(t)?t:ofGet(e,t),Any=class{constructor(t){this.value=t}merge=(...t)=>any(json.merge(this.value,...t));delete=t=>any(json.delete(this.value,t));omit=(...t)=>any(json.omit(this.value,...t));set=(t,e)=>any(json.set(this.value,t,e));toJSON(){return this.value}},takeFirstKey=(t,e="")=>entries(asJson(t)).first((([,t])=>isDefined(t)))?.[0]??e,takeFirst=t=>entries(t).first((([,t])=>isDefined(t))),any=t=>new Any(t),Convert=class{constructor(t,e){this.from=t,this.to=e}},convert={default:new Convert((t=>t),(t=>t)),ignore:new Convert((()=>{}),(()=>{})),toBool:{fromNumber:new Convert((t=>t?1:0),(t=>0!==t)),fromString:new Convert((t=>t?"true":"false"),(t=>"true"===t))},toDate:{fromString:new Convert((t=>new Date(t).toISOString()),(t=>t))},toNumber:{fromString:new Convert((t=>asString(t)),(t=>parseInt(t)))}},Condition=class{constructor(t,e,s){this.key=t,this.operator=e,this.value=s}and=(...t)=>new LogicalCondition("and",[this,...t]);or=(...t)=>new LogicalCondition("or",[this,...t]);toJSON(){return{[this.key]:{[`$${this.operator}`]:json.parse(this.value)}}}},LogicalCondition=class{constructor(t,e){this.operator=t,this.conditions=e}toJSON(){return{[`$${this.operator}`]:this.conditions.map((t=>t.toJSON()))}}},SortCondition=class extends Condition{constructor(t,e){super(t,"",e),this.key=t,this.value=e}toJSON(){return{[this.key]:this.value}}},toCondition=(t,e,s,i=convert.default)=>new Condition(t,e,i.from(s)),isSortCondition=t=>isDefined(t)&&t instanceof SortCondition,import_reflect_metadata=require("reflect-metadata"),ClassMeta=class{constructor(t,e=(t.prototype??t).constructor){this.subject=t,this.data=e}get=t=>Reflect.getMetadata(t,this.data);set=(t,e)=>(Reflect.defineMetadata(t,e,this.data),e);entries=()=>entries(this.subject);parse=(t,e={})=>{const{initial:s={},skipUndefined:i=!1}=e;return this.entries().reduce(((e,[s,r])=>use(t(r),(t=>isDefined(t)||!i?on(e,(e=>e[s]=t)):e))),s)};properties=t=>toList([...Object.getOwnPropertyNames(this.subject),...Object.getOwnPropertyNames(Object.getPrototypeOf(this.subject))]).map((t=>this.property(t))).filter((e=>t?e.get(t):e));keys=t=>this.properties().map((e=>e.get(t))).reduce(((t,e)=>e?t.add(e):t),toList());values=()=>values(this.subject);property=t=>new PropertyMeta(this.subject,t)},PropertyMeta=class{constructor(t,e,s=Reflect.getMetadata(e,t)){this.subject=t,this.property=e,this.data=s}get value(){return this.subject[this.property]}get=t=>isDefined(this.data)&&isDefined(this.data[t])?this.data[t]:void 0;set=(t,e)=>(Reflect.defineMetadata(this.property,{...this.data,[t]:e},this.subject),e)},meta=t=>new ClassMeta(t??{}),isEnumConstructor=t=>isFunction(t)&&t.isEnum,Enum=class{constructor(t,e=t.toLowerCase(),s=e.toString()){this.name=t,this.id=e,this.code=s}static isEnum=!0;get isValid(){return isDefined(this.id)}static all(){return meta(this.allTuple()).values()}static filter(t,e){return this.all().filter(t,e)}static first(t,e){return this.all().first(t,e)}static byIds(t=[]){return toList(t).mapDefined((t=>this.byId(t))).distinct()}static byId(t,e){return this.allTuple()[t]??ofGet(e)}static allTuple(){return meta(this).get(`all-${this.name}`)??meta(this).set(`all-${this.name}`,meta(this).values().filter(isEnum).toObject("id"))}equals(t){return this.id===(isEnum(t)?t.id:t)}isIn(...t){return t.some((t=>this.equals(t)))}toJSON(){return this.id}toString(){return this.id.toString()}},isEnum=t=>isDefined(t)&&t instanceof Enum&&isAn(t,"name","id","code"),resolve=t=>Promise.resolve(t),reject=t=>Promise.reject(t),tuple={2:(t,e)=>Promise.all([t,e]),3:(t,e,s)=>Promise.all([t,e,s]),4:(t,e,s,i)=>Promise.all([t,e,s,i]),5:(t,e,s,i,r)=>Promise.all([t,e,s,i,r]),all:(t,e)=>Promise.all([t,Promise.all(e)]),spread:(t,...e)=>Promise.all([t,Promise.all(toArray(e))]),list:t=>Promise.all([...t]).then(toList),settled:t=>Promise.allSettled([...t]).then((t=>({fulfilled:toList(...t.filter((t=>"fulfilled"===t.status)).map((t=>t.value))),rejected:toList(...t.filter((t=>"rejected"===t.status)).map((t=>asString(t.reason))))}))),object:t=>use(keys(t),(e=>tuple.list(values(t)).then((t=>t.reduce(((t,s,i)=>on(t,(t=>t[e[i]]=s))),{})))))},tuple2=tuple[2],tuple3=tuple[3],tuple4=tuple[4],tuple5=tuple[5],tupleO=tuple.object,settled=tuple.settled,When=class t{constructor(t,e=!0,s){this.subject=t,this.valid=e,this.results=s}get not(){return this.clone(!this.valid)}get and(){return this.clone(this.valid)}get isDefined(){return this.clone(this.valid===isDefined(this.subject))}get isEmpty(){return this.clone(this.valid===isEmpty(this.subject))}get isTrue(){return this.clone(this.valid===!!this.subject)}get isValid(){return this.results=validate(this.subject),this.clone(this.valid===this.results.isValid)}isInstance=t=>this.clone(this.valid===this.subject instanceof t);with=t=>this.clone(this.valid===ofGet(t,this.subject));contains=t=>this.clone(this.valid===isDefined(ofGet(t,this.subject)));in=(...t)=>this.clone(this.valid===isIn(this.subject,toArray(...t)));is=t=>this.clone(this.valid===(this.subject===t));reject=t=>this.valid?reject(ofGet(t,this.subject)??this.results??Exception.Unknown):resolve(this.subject);recover=t=>resolve(this.valid?t(this.subject):this.subject);clone=(e=!0)=>new t(this.subject,e,this.results)},when=t=>new When(t),DotEnvContext=class{domain=process.env.DOMAIN??"easy";name=process.env.ENVIRONMENT_NAME??"";host=process.env.HOST??"";port=Number.parseInt(process.env.PORT??"8080");app=process.env.APP??"";get=(t,e)=>{const s=text(t).map((t=>t.replace(/([a-z])([A-Z])/g,"$1 $2"))).snake.toString();return process.env[s]??e}},BaseRequestContext=class{state={};get token(){return this.get("token")}set token(t){this.set("token",t)}get identity(){return this.token}get jwt(){return this.get("jwt")}set jwt(t){this.set("jwt",t)}get correlationId(){return this.get("correlationId")}set correlationId(t){this.set("correlationId",t)}get lastError(){return this.get("lastError")}set lastError(t){this.set("lastError",t)}get(t){return this.state[t]}set(t,e){return this.state[t]=e}create=t=>t();wrap=t=>t()},BaseContext=class extends BaseRequestContext{},Context=class{constructor(t={}){this.state=t,this.state={env:new DotEnvContext,request:new BaseRequestContext,other:{},...this.state}}get env(){return this.state.env}set env(t){this.state.env=t}get request(){return this.state.request}set request(t){this.state.request=t}get other(){return this.state.other}},ctx=new Context,toResult=(t,e,s=ctx.env.domain)=>({message:t.toString(),location:e?.toString(),domain:s?.toString()}),isResult=t=>isA(t,"message"),parse=(...t)=>toArray(...t).map((t=>isResult(t)?t:toResult(t))),Results=class{results;constructor(...t){this.results=parse(...t)}get length(){return this.results.length}get isValid(){return 0===this.results.length}add=(...t)=>toResults(...this.results,...parse(...t))},toResults=(...t)=>new Results(...t),isResults=t=>isDefined(t)&&t instanceof Results,CaseBuilder=class{constructor(t){this.v=t}is={defined:(t,e)=>new Case(this.v).case(isDefined(t(this.v)),e),empty:(t,e)=>new Case(this.v).case(isEmpty(t(this.v)),e),valid:(t,e)=>new Case(this.v).case(validate(t(this.v)).isValid,e),in:(t,e)=>new Case(this.v).case(ofGet(t,this.v).includes(this.v),e),not:{defined:(t,e)=>new Case(this.v).case(!isDefined(t(this.v)),e),empty:(t,e)=>new Case(this.v).case(!isEmpty(t(this.v)),e),valid:(t,e)=>new Case(this.v).case(!validate(t(this.v)).isValid,e),in:(t,e)=>new Case(this.v).case(!ofGet(t,this.v).includes(this.v),e)}};if=this.is;case(t,e){return new Case(this.v).case(t,e)}type(t,e){return new Case(this.v).type(t,e)}equals(t,e){return new Case(this.v).equals(t,e)}},Case=class t{constructor(t,e){this.value=t,this.outcome=e}is={defined:(e,s)=>new t(this.value).case(isDefined(e(this.value)),s),empty:(e,s)=>new t(this.value).case(isEmpty(e(this.value)),s),valid:(e,s)=>new t(this.value).case(validate(e(this.value)).isValid,s),in:(e,s)=>new t(this.value).case(ofGet(e,this.value).includes(this.value),s),not:{defined:(e,s)=>new t(this.value).case(!isDefined(e(this.value)),s),empty:(e,s)=>new t(this.value).case(!isEmpty(e(this.value)),s),valid:(e,s)=>new t(this.value).case(!validate(e(this.value)).isValid,s),in:(e,s)=>new t(this.value).case(!ofGet(e,this.value).includes(this.value),s)}};if=this.is;case(t,e){return tryTo(t,this.value).is.true().map((()=>ofGet(e,this.value))).map((t=>new Found(this.value,t))).or(this)}type(t,e){return tryTo(t,this.value).is.true().map((()=>e(this.value))).map((t=>new Found(this.value,t))).or(this)}equals(t,e){return this.case(this.value===t,e)}else(t){return ofGet(t,this.value)}},Found=class extends Case{constructor(t,e){super(t,e),this.value=t,this.outcome=e}is={defined:(t,e)=>this,empty:(t,e)=>this,valid:(t,e)=>this,in:(t,e)=>this,not:{defined:(t,e)=>this,empty:(t,e)=>this,valid:(t,e)=>this,in:(t,e)=>this}};if=this.is;case(t,e){return this}type(t,e){return this}equals(t,e){return this}else(t){return this.outcome}},choose=t=>new CaseBuilder(t),Value=class{constructor(t){this.value=t,this.value=t}get isValid(){return isDefined(this.value)}toJSON(){return this.value}toString(){return asString(this.value)}},isValue=t=>t instanceof Value,isValidatable=t=>isA(t,"isValid"),asResults=(t,e,s={})=>toResults(toResult(text(e).parse(t,s),toName(t))),validators=t=>meta(t).keys("constraint").reduce(((t,e)=>t.add(e)),toList()),runValidator=(t,e)=>{try{const s=isFunction(e[t.property])?e[t.property]():e[t.property],i=t.constraint(s);return isResults(i)?i:i?toResults():asResults(e,t.text,{...t,actual:s})}catch(t){return asResults(e,asString(t))}},constraints=t=>validators(t).map((e=>runValidator(e,t))).reduce(((t,e)=>t.add(...e.results)),toResults()),validate=t=>choose(t).is.not.defined((t=>t),(()=>toResults("Subject is not defined."))).type(isEnum,(t=>t.isValid?toResults():asResults(t,"This is not a valid {type}."))).type(isValue,(t=>t.isValid?toResults():asResults(t,"This is not a valid {type}."))).type(isArray,(t=>t.map((t=>validate(t))).reduce(((t,e)=>t.add(...e.results)),toResults()))).type(isValidatable,(t=>constraints(t))).else(toResults()),validateReject=t=>when(t).not.isValid.reject(),isValid=t=>validate(t).isValid,Try=class t{is={defined:t=>this.filter((e=>isDefined(t?t(e):e))),empty:t=>this.filter((e=>isEmpty(t?t(e):e))),valid:t=>this.filter((e=>validate(t?t(e):e).isValid)),true:t=>this.filter((e=>isTrue(t?t(e):e))),false:t=>this.filter((e=>!isTrue(t?t(e):e))),not:{defined:t=>this.filter((e=>!isDefined(t?t(e):e))),empty:t=>this.filter((e=>!isEmpty(t?t(e):e))),valid:t=>this.filter((e=>!validate(t?t(e):e).isValid))}};if=this.is;static of=(e,...s)=>{try{const i=ofGet(e,...s);return new Success(i instanceof t?i.value:i)}catch(t){return new Failure(t)}}},Success=class extends Try{constructor(t){super(),this.value=t}get error(){throw new Error("No error found")}get isValid(){return!0}map(t){return tryTo(t,this.value)}recover(t){return this}recoverFrom(t,e){return this}accept(t){return tryTo((()=>(t(this.value),this)))}filter(t){return tryTo((()=>{if(t(this.value))return this;throw new Error(`Applying filter(${t.toString()}) failed.`)}))}or(t){return this.value}orElse(t){return this.value}orThrow(t){return this.value}},Failure=class t extends Try{constructor(t){super(),this.error=t}get value(){throw this.error}get isValid(){return!1}map(e){return new t(this.error)}recover(t){return tryTo(t,this.error)}recoverFrom(t,e){return tryTo((()=>this.error instanceof t?this.recover(e):this))}accept(t){return this}filter(t){return this}or(t){return ofGet(t)}orElse(t){return ofGet(t)}orThrow(t){throw ofConstruct(t)}},tryTo=(t,...e)=>Try.of(t,...e),Template=class{constructor(t,e={},s={}){this.template=t,this.subject=e,this.options=s}knownPrefixes=new Set(["type","property","actual","subject"]);toString=()=>entries(this.options).reduce(((t,[e])=>this.option(t,e)),this.object()).replace("  "," ");props=(t,e,s=toList())=>{const i=t.indexOf(`{${e}`);if(i<0)return s;const r=t.indexOf("}",i);return this.props(t.slice(r+1),e,s.add(t.substring(i+1,r)))};object=()=>tryTo((()=>this.template.replace(/\{this\./g,"{"))).map((t=>t.replace(/\{([^}]+)}/g,((t,e)=>this.knownPrefixes.has(e.split(".")[0])?t:textValue(this.subject,e))))).or("");option=(t,e)=>this.props(t,e).reduce(((t,e)=>t.replace(`{${e}}`,textValue(this.options,e))),t)};function template(t,e,s={}){return new Template(asString(t),e,{type:toName(e),subject:text(JSON.stringify(e)),...s})}var ToText=class{constructor(t){this.subject=t}get cap(){return this.map((t=>capitalize(t?.toLowerCase())))}get capFirst(){return this.map((t=>capitalize(t)))}get title(){return this.map((t=>t.split(" ").map((t=>text(t).cap)).join(" ")))}get pascal(){return this.title.replace(" ","")}get lower(){return this.map((t=>t.toLowerCase()))}get upper(){return this.map((t=>t.toUpperCase()))}get camel(){return this.title.trim.map((t=>`${t.charAt(0).toLowerCase()}${t.slice(1)}`))}get kebab(){return this.lower.replace(" ","-")}get strictKebab(){return this.map((t=>t.replace(/[^a-z\d]+/gi," ").trim())).kebab}get slug(){return this.map((t=>t.replace(/ß/g,"ss").normalize("NFKD").replace(/[\u0300-\u036F]/g,"").toLowerCase().replace(/[^a-z\d]+/g,"-").replace(/(^-)|(-$)/g,"")))}get snake(){return this.upper.replace(" ","_")}get plural(){return this.ifLike("")??this.add("s")}get space(){return this.map((t=>t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]/g," ")))}get sentence(){return this.isEmpty?this:this.map((t=>`${t.charAt(0).toUpperCase()}${t.slice(1)}.`))}get initials(){return this.map((t=>t.split(" ").map((t=>t[0])).join("")))}get trim(){return this.map((t=>t.replace(/[- ,_#]/g,"")))}get trimSentence(){return this.map((t=>t.replace(/[\u200B-\u200D\uFEFF]/g,"").replace(/[\s\u00A0]+/g," ").replace(/\s+([.,;:!?])/g,"$1").trim()))}get isEmpty(){return isEmpty(this.toString())}parse=(t,e={})=>text(template(this.subject,t,{type:toName(t),...e}));is=(...t)=>t.some((t=>this.toString()===text(t).toString()));equals=this.is;like=(...t)=>t.some((t=>this.trim.lower.toString().includes(text(t).trim.lower.toString())));isLike=(...t)=>t.some((t=>this.trim.lower.is(text(t).trim.lower)));ifLike=(...t)=>this.isLike(...t)?this:void 0;endsWith=t=>this.subject.endsWith(asString(t));startsWith=t=>this.subject.startsWith(asString(t));first=t=>this.map((e=>e.substring(0,t)));last=t=>this.map((e=>e.substring(e.length-t)));map=t=>text(ofGet(t,this.subject));replace=(t,e)=>this.map((s=>replaceAll(s,t,e)));add=(t,e="")=>this.map((s=>isNotEmpty(t)?`${s}${e}${text(t)}`:s));with=(t,...e)=>this.map((s=>toList(s).add(...e.map((t=>text(t).toString()))).filter((t=>isNotEmpty(t))).join(t)));split=(t=" ")=>toList(this.subject.split(t));toString(){return this.subject}toJSON(){return this.subject}};function text(t,e=""){const s=t?asString(t):e;return new ToText("[object Object]"!==s?s:"")}function textValue(t,e){const s=e.split("."),i=t?.[s[0]],r="object"==typeof i&&null!==i?i:text(i);return s.splice(1).reduce(((t,e)=>("object"==typeof t&&null!==t?t:text(t))?.[e]),r)?.toString()??""}var Exception=class t extends Enum{constructor(t,e,s){super(t,e??text(t).pascal.toString()),this.message=t,this.reason=s}static AlreadyExists=new t("Subject already exists");static DoesNotExist=new t("Does not exist");static IsMissingId=new t("Subject is missing an id");static IsNotImplemented=new t("Is not implemented");static IsNotValid=new t("Is not valid");static Unknown=new t("Unknown error");static CouldNotExecute=e=>new t(`Could not execute ${e}.`,"CouldNotExecute");static CouldNotValidate=e=>new t(`Could not validate ${e}.`,"CouldNotValidate");static EnvironmentVariableNotFound=e=>new t(`Environment variable ${text(e).upper} could not be found.`,"EnvironmentVariableNotFound");because=e=>new t(this.message,this.id,e)},isException=(t,e)=>t instanceof Exception&&(!isDefined(e)||t.equals(asString(e))),isDoesNotExist=t=>t instanceof Exception&&Exception.DoesNotExist.equals(t),Gateway=class{all(t){return reject(Exception.IsNotImplemented)}byId(t,e){return reject(Exception.IsNotImplemented)}by(t,e,s){return reject(Exception.IsNotImplemented)}byIds(...t){return reject(Exception.IsNotImplemented)}search(t,e){return reject(Exception.IsNotImplemented)}filter(t){return reject(Exception.IsNotImplemented)}exists(t,e){return reject(Exception.IsNotImplemented)}add(t,e){return reject(Exception.IsNotImplemented)}update(t,e){return reject(Exception.IsNotImplemented)}remove(t,e){return reject(Exception.IsNotImplemented)}},toFilter=(t,e)=>toShortFilter(t,t,e),toShortFilter=(t,e,s)=>({field:t,shortField:e,values:[{value:s}]}),PageList=class extends List{_options;get options(){return this._options}get take(){return this._options?.take??250}get skip(){return this._options?.skip??0}get total(){return this._options?.total}get sorts(){return this._options?.sorts}get filters(){return this._options?.filters}get meta(){return{take:this.take,skip:this.skip,total:this.total,sorts:this.sorts,filters:this.filters}}get ids(){return this.mapDefined((t=>t.id))}asc(t){return toPageList(super.asc(t),this)}desc(t){return toPageList(super.desc(t),this)}diff(t){return toPageList(super.diff(t),this)}diffByKey(t,e){return toPageList(super.diffByKey(t,e),this)}symmetricDiff(t){return toPageList(super.symmetricDiff(t),this)}symmetricDiffByKey(t,e){return toPageList(super.symmetricDiffByKey(t,e),this)}intersect(t){return toPageList(super.intersect(t),this)}intersectByKey(t,e){return toPageList(super.intersectByKey(t,e),this)}map(t,e){const s=super.map(t,e);return toPageList(s,this)}flatMap(t,e){return toPageList(super.flatMap(t,e),this)}mapDefined(t,e){return toPageList(super.mapDefined(t,e),this)}mapAsync(t){return super.mapAsync(t).then((t=>toPageList(t,this)))}areEqual(...t){return this.isSubSetOf(...t)&&toList(...t).isSubSetOf(...this)}distinct(){return toPageList(super.distinct(),this)}distinctByKey(t){return toPageList(super.distinctByKey(t),this)}distinctByValue(){return toPageList(super.distinctByValue(),this)}filter(t,e){return toPageList(super.filter(t,e),this)}accumulate(...t){return toPageList(super.accumulate(...t),this)}concat(...t){return toPageList(super.concat(...t),this)}reverse(){return toPageList(super.reverse(),this)}splice(t,e,...s){return toPageList(super.splice(t,e,...s),this)}remove(t){return toPageList(super.remove(t),this)}replace(t,e){return toPageList(super.replace(t,e),this)}switch(t){return toPageList(super.switch(t),this)}defined(){return toPageList(super.defined(),this)}orElse(...t){return toPageList(super.orElse(...t),this)}slice(t,e){return toPageList(super.slice(t,e),this)}update(t,e){return toPageList(super.update(t,e),this)}updateFirst(t,e){return toPageList(super.updateFirst(t,e),this)}updateFirstById(t,e){return toPageList(super.updateFirstById(t,e),this)}updateById(t,e){return toPageList(super.updateById(t,e),this)}setPageOptions(t){return this._options=t,this}},isPageList=t=>isList(t)&&isA(t,"total"),toPageList=(t=[],e)=>choose(t).case((t=>1===t.length&&isNumber(t[0])),(t=>(new PageList).add(...t))).else((t=>new PageList(...t))).setPageOptions(isPageList(e)?e.options:e),asPageList=(t,e=toPageList())=>e.map((e=>ofConstruct(t,e))),InMemoryGateway=class extends Gateway{constructor(t){super(),this.data=t}all(t){return this.data.then((t=>toPageList(t,t)))}byId(t){return this.data.then((e=>e.byId(t))).then((t=>t?{...t}:void 0))}by=(t,e)=>this.data.then((s=>s.filter((s=>s[t]===e))));exists(t){return this.byId(t).then((t=>isDefined(t)))}add(t){return when(t).not.contains((t=>t.id)).reject(Exception.IsMissingId).then((t=>this.exists(t.id))).then((t=>when(t).isTrue.reject(Exception.AlreadyExists))).then((()=>this.data.then((e=>e.add(t))))).then((()=>({...t})))}remove(t){return this.data.then((e=>when(e.findIndex((e=>e.id===t))).with((t=>t<0)).reject(Exception.DoesNotExist).then((t=>e.splice(t,1))))).then((()=>!0))}update(t){return when(t).not.contains((t=>t.id)).reject(Exception.IsMissingId).then((t=>this.remove(t.id).then((()=>this.add(t)))))}},DefaultProvider=class{},Database=class t extends Enum{constructor(t,e,s){super(t),this.provider=e,this.options=s}static Default=new t("Default",DefaultProvider);provide=()=>ofConstruct(this.provider,this)},Property=class{constructor(t,e){this.property=t,this.options=e,this.options={...e,convert:e?.convert??convert.default}}in=(t={})=>this.options?.convert?.to(t[this.property]??ofGet(this.options?.dflt));out=(t={},e="")=>this.options?.convert?.from(t[e]);toString(){return this.property}},Field=class extends Property{is=t=>this.condition("eq",t);isNot=t=>this.condition("ne",t);isIn=(...t)=>this.condition("in",toArray(t));notIn=(...t)=>this.condition("nin",toArray(t));exists=t=>this.condition("exists",t);greater=t=>this.condition("gt",t);greaterEqual=t=>this.condition("gte",t);less=t=>this.condition("lt",t);lessEqual=t=>this.condition("lte",t);asc=()=>new SortCondition(this.property,1);desc=()=>new SortCondition(this.property,-1);condition=(t,e)=>toCondition(this.property,t,e,this.options?.convert)},isField=t=>isDefined(t)&&t instanceof Field,Struct=class{constructor(t={}){this.state=t}get isValid(){return validate(this).isValid}toJSON(){return json.delete(json.parse({...this}),"state")}toString(){return this.constructor.name}update(t){return this}merge(t){return json.merge(this,t)}};function isStruct(t){return isDefined(t)&&t instanceof Struct}var import_luxon=require("luxon"),isDate=t=>t instanceof Date&&!isNaN(t.getTime()),days={add:(t,e)=>(t.setDate(t.getDate()+e),t),today:()=>new Date,yesterday:()=>days.add(days.today(),-1),tomorrow:()=>days.add(days.today(),1)},inPast=t=>isDate(t)&&t<=days.today(),inFuture=t=>isDate(t)&&t>days.today(),seconds={toDuration:t=>{const e=t%60,s=Math.floor(t/60)%60,i=Math.floor(t/3600)%24;return{days:Math.floor(t/86400),hours:i,minutes:s,seconds:e}},toText:t=>{const{days:e,hours:s,minutes:i,seconds:r}=seconds.toDuration(t);return toList(ifTrue(e,`${e}d`),ifTrue(s,`${s}h`),ifTrue(i,`${i}m`),ifTrue(e+s+i===0,`${r}s`)).mapDefined((t=>t)).join(" ")}};import_luxon.Settings.defaultZone="utc";var DateTime=class t extends Value{luxon;constructor(t,e){const s=choose(t).type(isString,(t=>e?import_luxon.DateTime.fromFormat(t,e,{setZone:!0}):import_luxon.DateTime.fromISO(t,{setZone:!0}))).type(isNumber,(t=>import_luxon.DateTime.fromMillis(t))).type(isDate,(t=>import_luxon.DateTime.fromJSDate(t))).type(isDateTime,(t=>t.luxon)).else(t instanceof import_luxon.DateTime?t:import_luxon.DateTime.fromISO(void 0));super(s.toISO()??void 0),this.luxon=s}static get now(){return new t(import_luxon.DateTime.utc())}get isValid(){return isDefined(this.value)&&this.utc.isValid}get fromNow(){return this.from()}get inAmsterdam(){return this.withZone("Europe/Amsterdam")}get inNewYork(){return this.withZone("America/New_York")}get inLondon(){return this.withZone("Europe/London")}get inWarsaw(){return this.withZone("Europe/Warsaw")}get utc(){return this.luxon.setZone("utc")}from(t,e){return use((isString(t)?t:e)??"en",(e=>ifDefined(isA(t)?t:void 0,(t=>this.utc.setLocale(e).toRelative({base:t.utc})),(()=>this.utc.setLocale(e).toRelative()))))??""}isAfter(t){return this.utc>t.utc}isBefore(t){return this.utc<t.utc}equals(t){return this.utc.hasSame(t.utc,"millisecond")}add(e,s="day"){return new t(this.luxon.plus(isNumber(e)?{[s]:e}:e))}subtract(e,s="day"){return new t(this.luxon.minus(isNumber(e)?{[s]:e}:e))}diff(t,e="day",s){return Math[s?.rounding??"floor"](this.utc.diff(t.utc).as(e))}startOf(e="day"){return new t(this.luxon.startOf(e))}endOf(e="day"){return new t(this.luxon.endOf(e))}isWeekend(){return this.luxon.isWeekend}withZone(e){return new t(this.luxon.setZone(e))}toString(){return this.value??""}toJSON(){return this.utc.toISO()}toFormat(t){return this.luxon.toFormat(t)}toLocale(t="nl-NL",e="D"){return this.luxon.setLocale(t).toFormat(e)}toFull(t){return this.toLocale(t,"DDD")}toDate(){return this.isValid?this.utc.toJSDate():void 0}toEpoch(){return this.luxon.toMillis()}ago(e=t.now){return seconds.toText(e.diff(this,"second"))}withClock(e){return tryTo((()=>[this.toDate(),e.toDate()])).map((([t,e])=>new Date(t.getFullYear(),t.getMonth(),t.getDate(),e.getHours(),e.getMinutes(),e.getSeconds()))).map((e=>new t(e))).value}},isDateTime=t=>isDefined(t)&&t instanceof DateTime,dt=t=>new DateTime(t),constraint=(t,e)=>(s,i)=>{const r=meta(s).property(i).get("constraint")??toList();meta(s).property(i).set("constraint",r.add({property:i,constraint:t,text:e}))},defined=t=>constraint((t=>isDefined(t)),t??"Property {property} must be defined."),required=t=>constraint((t=>isNotEmpty(t)),t??"Property {property} is required, and may not be empty."),notEmpty=t=>constraint((t=>isNotEmpty(t)),t??"Property {property} may not be empty."),valid=()=>constraint((t=>validate(t)),""),optional=()=>constraint((t=>!isDefined(t)||validate(t)),""),includes=(t,e)=>constraint((e=>isDefined(e)&&isString(e)&&e.includes(t)),e??`Value {actual} must include '${t}'.`),inList=(t,e)=>constraint((e=>isDefined(e)&&isIn(e,t)),e??"Value {actual} must appear in list."),inOptionalList=(t,e)=>constraint((e=>!isDefined(e)||isIn(e,t)),e??"Value {actual} must appear in list."),gt=(t,e)=>constraint((e=>e>t),e??`Value {actual} must be larger than '${t}'.`),gte=(t,e)=>constraint((e=>e>=t),e??`Value {actual} must be larger than or equal to ${t}.`),lt=(t,e)=>constraint((e=>e<t),e??`Value {actual} must be smaller than ${t}.`),lte=(t,e)=>constraint((e=>e<=t),e??`Value {actual} must be smaller than or equal to ${t}.`),past=t=>constraint((t=>inPast(t)),t??"Value {actual} must lay in the past."),future=t=>constraint((t=>inFuture(t)),t??"Value {actual} must lay in the future."),minLength=(t,e)=>constraint((e=>tryTo((()=>e)).is.defined().map((e=>text(e).toString().length>=t)).orElse(!0)),e??`Value {actual} must be at least '${t}' characters long.`),maxLength=(t,e)=>constraint((e=>tryTo((()=>e)).is.defined().map((e=>text(e).toString().length<=t)).orElse(!0)),e??`Value {actual} cannot be longer than '${t}' characters.`),rule=t=>constraint((t=>isFunction(t)?t():!!isBoolean(t)&&t),t??"Value {actual} must be true"),Audit=class extends Struct{by={id:this.state.by?.id,user:this.state.by?.user};when=new DateTime(this.state.when);constructor(t){super(choose(t).is.defined((t=>t),(t=>t)).else({by:isIdentity(ctx.request?.identity)?ctx.request?.identity:{id:0,user:"easy"},when:DateTime.now.toJSON()}))}};__decorateClass([required()],Audit.prototype,"by",2),__decorateClass([valid()],Audit.prototype,"when",2);var import_uuid=require("uuid"),toUuid=()=>(0,import_uuid.v4)(),isValidUuid=new RegExp(/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i),isUuid=t=>isString(t)&&isValidUuid.test(t),includeUuid=new RegExp(/\b[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\b/i),includesUuid=t=>includeUuid.test(asString(t)),toId=()=>toUuid(),Child=class extends Struct{id=this.state.id??toId();merge(t){return json.merge(this,t,{id:this.id})}};__decorateClass([required()],Child.prototype,"id",2);var Entity=class extends Struct{id=this.state.id??toId();created=new Audit(this.state.created);lastModified=new Audit(this.state.lastModified);merge(t){return json.merge(this,t,{id:this.id,created:this.created,lastModified:new Audit})}};__decorateClass([required()],Entity.prototype,"id",2),__decorateClass([required()],Entity.prototype,"created",2),__decorateClass([required()],Entity.prototype,"lastModified",2);var Repository=class{all(t){return reject(Exception.IsNotImplemented)}byId(t){return reject(Exception.IsNotImplemented)}byIds(...t){return reject(Exception.IsNotImplemented)}byKey(t,e){return reject(Exception.IsNotImplemented)}by(t,e,s){return reject(Exception.IsNotImplemented)}search(t,e){return reject(Exception.IsNotImplemented)}filter(t){return reject(Exception.IsNotImplemented)}exists(t){return reject(Exception.IsNotImplemented)}add(t){return reject(Exception.IsNotImplemented)}update(t,e){return reject(Exception.IsNotImplemented)}remove(t){return reject(Exception.IsNotImplemented)}upsert(t,e){return reject(Exception.IsNotImplemented)}},Repo=class extends Repository{constructor(t,e){super(),this.ctor=t,this.gateway=e}create=t=>isValidatable(t)?t:new this.ctor(t);all(t){return this.gateway.all(t).then((t=>t.map((t=>new this.ctor(t)))))}byId(t){return this.gateway.byId(t).then((t=>when(t).not.isDefined.reject(Exception.DoesNotExist))).then((t=>new this.ctor(t)))}byIds(...t){return this.gateway.byIds(...t).then((t=>asList(this.ctor,t)))}byKey(t,e){return this.gateway.by("key",t,e).then((t=>t.map((t=>new this.ctor(t)))))}by(t,e,s){return this.gateway.by(t.toString(),e,s).then((t=>t.map((t=>new this.ctor(t)))))}search(t,e){return this.gateway.search(t,e).then((t=>t.map((t=>new this.ctor(t)))))}filter(t){return this.gateway.filter(t).then((t=>t.map((t=>new this.ctor(t)))))}exists(t){return this.gateway.exists(t)}add(t){return this.extend(this.create(t),"add").then((t=>when(t).not.isValid.reject())).then((t=>this.validate(t,"add"))).then((t=>this.gateway.add(toJson(t)))).then((t=>new this.ctor(t)))}update(t,e){return this.gateway.byId(t).then((t=>when(t).not.isDefined.reject(Exception.DoesNotExist))).then((t=>new this.ctor(t).update(e))).then((t=>this.extend(t,"update"))).then((t=>when(t).not.isValid.reject())).then((t=>this.validate(t,"update"))).then((t=>this.gateway.update(toJson(t)))).then((t=>new this.ctor(t)))}remove(t){return this.gateway.remove(t)}extend(t,e){return resolve(t)}validate(t,e){return resolve(t)}upsert(t,e){return this.update(t,e).catch((t=>Exception.DoesNotExist.equals(t)?this.add(e):reject(t)))}},Typo=class extends Repository{constructor(t,e){super(),this.view=t,this.gateway=e}create=t=>this.view.from(t);all(t){return this.gateway.all(t).then((t=>t.map(this.create)))}byId(t){return this.gateway.byId(t).then((t=>when(t).not.isDefined.reject(Exception.DoesNotExist))).then((t=>this.create(t)))}byIds(...t){return this.gateway.byIds(...t).then((t=>t.map(this.create)))}byKey(t,e){return this.gateway.by("key",t,e).then((t=>t.map(this.create)))}by(t,e,s){return this.gateway.by(t.toString(),e,s).then((t=>t.map(this.create)))}search(t,e){return this.gateway.search(t,e).then((t=>t.map(this.create)))}filter(t){return this.gateway.filter(t).then((t=>t.map((t=>this.create(t)))))}exists(t){return this.gateway.exists(t)}},Agent=class extends Repository{constructor(t){super(),this.gateway=t}all(t){return this.gateway.all(t)}byId(t){return this.gateway.byId(t)}byIds(...t){return this.gateway.byIds(...t)}byKey(t,e){return this.gateway.by("key",t,e)}by(t,e,s){return this.gateway.by(t.toString(),e,s)}search(t,e){return this.gateway.search(t,e)}filter(t){return this.gateway.filter(t)}exists(t){return this.gateway.exists(t)}add(t){return this.gateway.add(toJson(t))}update(t,e){return this.gateway.update({...toJson(e),id:t})}upsert(t,e){return this.gateway.upsert({...toJson(e),id:t})}remove(t){return this.gateway.remove(t)}},asNumber=(t,e)=>tryTo((()=>asString(t))).map((t=>parseInt(t))).filter((t=>isNumber(t))).or(ofGet(e)??NaN),ageNumber=t=>asNumber(t.replace(/[a-z]/g,"")),cacheAge={toMilliseconds:t=>choose(asString(t)).case((t=>t.endsWith("ms")),(t=>ageNumber(t))).case((t=>t.endsWith("s")),(t=>1e3*ageNumber(t))).case((t=>t.endsWith("m")),(t=>60*ageNumber(t)*1e3)).case((t=>t.endsWith("h")),(t=>3600*ageNumber(t)*1e3)).case((t=>t.endsWith("d")),(t=>24*ageNumber(t)*3600*1e3)).else(t),toSeconds:t=>choose(asString(t)).case((t=>t.endsWith("ms")),(t=>ageNumber(t)/1e3)).case((t=>t.endsWith("s")),(t=>ageNumber(t))).case((t=>t.endsWith("m")),(t=>60*ageNumber(t))).case((t=>t.endsWith("h")),(t=>3600*ageNumber(t))).case((t=>t.endsWith("d")),(t=>24*ageNumber(t)*3600)).else(t)},isCacheAge=t=>isString(t)||isNumber(t),CacheControl=class t{constructor(t=!0,e={}){this.enabled=t,this.directives=e}name="Cache-Control";static disabled=()=>new t(!1);static OneSecond=()=>(new t).maxAge(1).staleWhileRevalidate(1);static fiveSeconds=()=>(new t).maxAge(5).staleWhileRevalidate(5);static tenSeconds=()=>(new t).maxAge(10).staleWhileRevalidate(10);static thirtySeconds=()=>(new t).maxAge(30).staleWhileRevalidate(30);static sixtySeconds=()=>(new t).maxAge(60).staleWhileRevalidate(60);static custom=(e,s)=>(new t).maxAge(e).staleWhileRevalidate(s);maxAge=t=>on(this,(e=>e.directives["max-age"]=t));sharedMaxAge=t=>on(this,(e=>e.directives["s-maxage"]=t));noCache=t=>on(this,(e=>e.directives["no-cache"]=t));mustRevalidate=t=>on(this,(e=>e.directives["must-revalidate"]=t));private=t=>on(this,(e=>e.directives.private=t));public=t=>on(this,(e=>e.directives.public=t));immutable=t=>on(this,(e=>e.directives.immutable=t));staleWhileRevalidate=t=>on(this,(e=>e.directives["stale-while-revalidate"]=t));value=()=>this.toString();toString(){return entries(this.directives).mapDefined((([t,e])=>ifDefined(e,isCacheAge(e)?`${t}=${cacheAge.toSeconds(e)}`:t))).join(",")}},import_form_urlencoded=__toESM(require("form-urlencoded")),ContentType=class t extends Enum{constructor(t,e,s=t=>asString(t)){super(t,e),this.type=e,this.encoder=s}static Form=new t("form","application/x-www-form-urlencoded",(t=>(0,import_form_urlencoded.default)(t)));static Json=new t("json","application/json",(t=>t));static RawJson=new t("rawJson","application/json",(t=>t));static Stream=new t("stream","application/octet-stream");static Text=new t("text","text/plain");static Xml=new t("xml","application/xml");encode=t=>ofGet(this.encoder,t)},HttpHeader={ContentType:"Content-Type",Correlation:"X-Correlation-Id"},HttpStatus=class t extends Enum{static Continue=new t("Continue",100);static SwitchingProtocols=new t("Switching protocols",101);static Processing=new t("Processing",102);static EarlyHints=new t("Early hints",103);static Ok=new t("Ok",200);static Created=new t("Created",201);static Accepted=new t("Accepted",202);static NonAuthoritativeInformation=new t("Non-authoritative information",203);static NoContent=new t("No content",204);static ResetContent=new t("Reset content",205);static PartialContent=new t("Partial content",206);static MultiStatus=new t("Multi-status",207);static AlreadyReported=new t("Already reported",208);static ImUsed=new t("IM used",226);static MultipleChoices=new t("Multiple Choices",300);static MovedPermanently=new t("Moved Permanently",301);static Found=new t("Found",302);static SeeOther=new t("See other",303);static NotModified=new t("Not modified",304);static UseProxy=new t("Use proxy",305);static SwitchProxy=new t("Switch proxy",306);static TemporaryRedirect=new t("Temporary redirect",307);static PermanentRedirect=new t("Permanent redirect",308);static BadRequest=new t("Bad request",400);static NotAuthorized=new t("Not authorized",401);static PaymentRequired=new t("Payment required",402);static Forbidden=new t("Forbidden",403);static NotFound=new t("Not found",404);static MethodNotAllowed=new t("Method not allowed",405);static NotAcceptable=new t("Not acceptable",406);static ProxyAuthenticationRequired=new t("Proxy authentication required",407);static RequestTimeout=new t("Request timeout",408);static Conflict=new t("Conflict",409);static Gone=new t("Gone",410);static LengthRequired=new t("Length required",411);static PreconditionFailed=new t("Precondition failed",412);static PayloadTooLarge=new t("Payload too large",413);static UriTooLong=new t("URI too long",414);static UnsupportedMediaType=new t("Unsupported media type",415);static RangeNotSatisfiable=new t("Range not satisfiable",416);static ExpectationFailed=new t("Expectation failed",417);static ImATeapot=new t("I'm a teapot",418);static MisdirectedRequest=new t("Misdirected request",421);static UnprocessableEntity=new t("Unprocessable entity",422);static Locked=new t("Locked",423);static FailedDependency=new t("Failed dependency",424);static TooEarly=new t("Too early",425);static UpgradeRequired=new t("Upgrade required",426);static PreconditionRequired=new t("Precondition required",428);static TooManyRequests=new t("Too many requests",429);static RequestHeaderFieldsTooLarge=new t("Request header fields too large",431);static UnavailableForLegalReasons=new t("Unavailable for legal reasons",451);static InternalServerError=new t("Internal server error",500);static NotImplemented=new t("Not implemented",501);static BadGateway=new t("Bad gateway",502);static ServiceUnavailable=new t("Service unavailable",503);static GatewayTimeout=new t("Gateway timeout",504);static HTTPVersionNotSupported=new t("Http version not supported",505);static VariantAlsoNegotiates=new t("Variant also negotiates",506);static InsufficientStorage=new t("Insufficient storage",507);static LoopDetected=new t("Loop detected",508);static NotExtended=new t("Not extended",510);static NetworkAuthenticationRequired=new t("Network authentication required",511);get isError(){return this.isClientError||this.isServerError}get isClientError(){return this.id>=400&&this.id<500}get isServerError(){return this.id>=500&&this.id<600}get status(){return this.id}},isHttpStatus=t=>isAn(t,"id","status"),toHttpStatus=t=>isHttpStatus(t)?t:HttpStatus.byId(t),HttpVerb=class t extends Enum{static Get=new t("Get");static Put=new t("Put");static Patch=new t("Patch");static Post=new t("Post");static Delete=new t("Delete");constructor(t){super(t,t.toLowerCase(),t.toUpperCase())}},toPageOptions=t=>t instanceof RequestOptions?t.pageOptions:t,RequestOptions=class t extends Enum{constructor(t=ContentType.Json,e={},s){super(t.name),this.type=t,this.headers=e,this.pageOptions=s,this.headers["Content-Type"]=t.id,this.headers[HttpHeader.Correlation]=ctx.request.correlationId??toUuid()}requestOptions={};static get Form(){return new t(ContentType.Form)}static get Json(){return new t(ContentType.Json)}static get Stream(){return new t(ContentType.Stream)}static get Text(){return new t(ContentType.Text)}static get Xml(){return new t(ContentType.Xml)}page=t=>(this.pageOptions=t,this);authorization=t=>this.setHeader("Authorization",t);apiKey=t=>this.setHeader("apiKey",t);setHeader=(t,e)=>on(this,(s=>s.headers[asString(t)]=e));setHeaderUnlessPresent=(t,e)=>e?this.setHeader(t,this.headers[t]??e):this;accept=t=>this.setHeader("Accept",t.id);bearer=t=>isNotEmpty(t)?this.authorization(`Bearer ${t}`):this;basic=(t,e)=>{const s=Buffer.from(`${t}:${e}`,"utf8").toString("base64");return this.authorization(`Basic ${s}`)};maxRedirects=t=>(this.requestOptions.maxRedirects=t,this);validateStatus=t=>(this.requestOptions.validateStatus=t,this);timeout=t=>(this.requestOptions.timeout=t,this)},isRequestOptions=t=>isDefined(t)&&t instanceof RequestOptions,isResponse=t=>isA(t,"status","body"),hasErrors=t=>isDefined(t?.error?.errors),hasItems=t=>isDefined(t?.data.items),rest={toData:(t,e=[],s,i)=>({data:{code:t.status,items:toList(e),itemCount:e.length,totalItems:s,meta:i}}),toError:(t,e=[toResult(t.name)])=>({error:{code:t.status,message:t.name??e[0].message??"Unknown",errors:toList(e),errorCount:e.length}}),to:(t,e)=>choose(t).is.not.defined((t=>t),void 0).type(isHttpStatus,(t=>rest.toError(t??e??HttpStatus.InternalServerError,[toResult(t.name)]))).type(isResult,(t=>rest.toError(e??HttpStatus.BadRequest,[t]))).type(isError,(t=>rest.toError(e??HttpStatus.BadRequest,[t]))).type(isResults,(t=>rest.toError(e??HttpStatus.BadRequest,t.results))).type(isResponse,(t=>rest.toError(e??HttpStatus.byId(t.body.error?.code),t.body.error?.errors))).type(hasErrors,(t=>rest.toError(e??HttpStatus.byId(t.error.code,HttpStatus.BadRequest),t.error.errors))).type(hasItems,(t=>rest.toData(e??HttpStatus.byId(t.data.code,HttpStatus.Ok),t.data.items,t.data.totalItems,t.data.meta))).else((t=>rest.toData(e??HttpStatus.Ok,toList(t))))},isRestResult=t=>isDefined(t)&&(isDefined(t.data)||isDefined(t.error));function toResponse(t,e,s){return{status:toHttpStatus(t),headers:s,body:rest.to(e)}}var Scope=class t extends Enum{constructor(t,e=text(t).kebab,s=toList()){super(t,e.toString()),this.name=t,this.subs=s}for(e){return new t(`${this.name} ${isString(e)?text(e).title:e.name}`,kebab(`${this.id} ${isString(e)?e:e.id}`))}combines(...t){return this.subs.add(t),this}expand(){return this.subs.flatMap((t=>t.expand())).add(this).distinct()}},App=class t extends Scope{constructor(t){super(t)}static Main=new t("Main")},Search=class{constructor(t){this.repo=t}all(t){return this.repo.all(t)}byId(t){return this.repo.byId(t)}byIds(...t){return this.repo.byIds(...t)}byKey(t,e){return this.repo.byKey(t,e)}query({query:t,skip:e,take:s}){return this.search(t,{skip:e,take:s})}search(t,e){return choose(t).is.not.empty((t=>t),(t=>this.repo.search(t,e))).else((()=>resolve(toPageList())))}filter(t){return this.repo.filter(t)}exists(t){return this.repo.exists(t)}},Manage=class extends Search{add(t){return this.repo.add(t)}update(t,e){return this.repo.update(t,e)}upsert(t,e){return this.repo.upsert(t,e)}remove(t){return this.repo.remove(t)}},UseCase=class t extends Enum{constructor(t,e,s=text(e).kebab,i=toList()){super(e,s.toString()),this.app=t,this.scopes=i}static byScopes(...t){return this.filter((e=>e.scopes.some((e=>isIn(e,t)))))}with(...t){return this.scopes.add(...toList(t).flatMap((t=>t.expand())).distinct()),this}for(e){return new t(this.app,`${this.name} ${isString(e)?e:e?.name}`,kebab(`${this.id} ${isString(e)?e:e.id}`)).with(...this.scopes.map((t=>t?.for(e))))}},Req=class{constructor(t={},e={},s,i){this.path=t,this.query=e,this.body=s,this.headers=i,this.skip=ifDefined(e.skip,(t=>asNumber(t))),this.take=ifDefined(e.take,(t=>asNumber(t)))}skip;take;get id(){return this.get("id")}get q(){return this.get("q")}get=t=>this.path[t.toString()]??this.query[t.toString()]};function toReq(t){return new Req(t.params,t.query,t.body,t.headers)}var import_jwt_decode=require("jwt-decode"),Jwt=class t extends Value{static of=e=>new t(e.jwt);decode=()=>(0,import_jwt_decode.jwtDecode)(this.value);toJSON(){return{jwt:this.value}}},import_axios=__toESM(require("axios")),isResponse2=t=>isDefined(t?.response),isRequest=t=>isDefined(t?.request),asResponse=(t,e,s)=>choose(s).type(isResponse2,(e=>toResponse(e.response.status,isRestResult(e.response.data)?e.response.data:toResult(e.response.statusText,t.path,t),e.response.headers))).type(isRequest,(e=>toResponse(e.request.status,toResult(e.request.message,t.path,t)))).else((e=>toResponse(HttpStatus.InternalServerError,toResult(e.message,t.path,t)))),AxiosProvider=class{constructor(t=import_axios.default){this.ai=t}execute=({uri:t,verb:e,body:s,transform:i=t=>t,transformError:r=t=>t,options:n=RequestOptions.Json})=>this.ai.request({url:t.toString(),method:e.toString(),headers:t.isInternal&&isEmpty(n.headers.Authorization)?n.bearer(ctx.request.jwt).headers:n.headers,data:n.type.encode(s),maxRedirects:n.requestOptions.maxRedirects,...n.requestOptions.timeout&&{timeout:cacheAge.toMilliseconds(n?.requestOptions.timeout)},...n.requestOptions.validateStatus&&{validateStatus:n.requestOptions.validateStatus}}).then((t=>toResponse(t.status,i(t.data),t.headers))).catch((s=>Promise.reject(asResponse(t,e,r(s)))))},Api=class{constructor(t=new AxiosProvider,e){this.provider=t,this.store=e}get(t,e,s,i=t=>t){return this.execute({uri:t.skip(toPageOptions(e)?.skip).take(toPageOptions(e)?.take),verb:HttpVerb.Get,transform:s,transformError:i,options:this.options(HttpVerb.Get,e)})}post(t,e,s=RequestOptions.Json,i,r=t=>t){return this.execute({uri:t,verb:HttpVerb.Post,body:e,transform:i,transformError:r,options:this.options(HttpVerb.Post,s)})}put(t,e,s=RequestOptions.Json,i,r=t=>t){return this.execute({uri:t,verb:HttpVerb.Put,body:e,transform:i,transformError:r,options:this.options(HttpVerb.Put,s)})}patch(t,e,s=RequestOptions.Json,i,r=t=>t){return this.execute({uri:t,verb:HttpVerb.Patch,body:e,transform:i,transformError:r,options:this.options(HttpVerb.Patch,s)})}delete(t,e=RequestOptions.Json,s,i=t=>t){return this.execute({uri:t,verb:HttpVerb.Delete,transform:s,transformError:i,options:this.options(HttpVerb.Delete,e)})}options(t,e){return e instanceof RequestOptions?e:RequestOptions.Json}execute(t){return this.store?this.store.execute(t,(()=>this.provider.execute(t))):this.provider.execute(t)}},api=new Api,ApiGateway=class extends Gateway{constructor(t=new Api){super(),this.api=t}get(t,e){return this.api.get(t,e).then((t=>use(t.body.data,(t=>toPageList(t?.items,{total:t?.totalItems,...t?.meta})))))}getOne(t,e){return this.get(t,e).then((t=>t.first()))}post(t,e,s){return this.api.post(t,e,s).then((t=>t.body.data?.items.first()??{}))}postSearch(t,e){return this.api.post(t,e).then((t=>use(t.body.data,(t=>toPageList(t?.items,{total:t?.totalItems,...t?.meta})))))}patch(t,e,s){return this.api.patch(t,e,s).then((t=>t.body.data?.items.first()??{}))}put(t,e,s){return this.api.put(t,e,s).then((t=>t.body.data?.items.first()??{}))}delete(t,e){return this.api.delete(t,e).then((()=>!0))}},RouteGateway=class extends ApiGateway{constructor(t,e,s=new Api){super(s),this.route=t,this.routeId=e,this.api=s}all(t){return this.get(this.route().expand(t??{}),t)}byId(t){return this.getOne(this.routeId().id(t))}byIds(...t){return this.get(this.route().ids(toArray(...t)))}search(t,e){return this.get(this.route().expand({...e,q:t}))}exists(t){return this.byId(t).then((t=>isDefined(t))).catch((t=>!HttpStatus.NotFound.equals(t.status)&&Promise.reject(t)))}add(t){return this.post(this.route(),t)}filter(t){return this.postSearch(this.route().expand(t??{}))}update(t){return this.patch(this.routeId().id(t.id),t)}upsert(t){return this.put(this.routeId().id(t.id),t)}remove(t){return this.delete(this.routeId().id(t))}},State=class{constructor(t={}){this.state=t}get=(t,e)=>this.state[t]??(this.state[t]=ofConstruct(e));set=(t,e)=>this.get(t,e)},isMapping=t=>isA(t,"in","out"),Mapper=class extends State{constructor(t={startFrom:"scratch"},e=""){super(),this.options=t,this.property=e}map=mappings;get properties(){return this.get("props",(()=>meta(this).entries().filter((([,t])=>isMapping(t)))))}get keys(){return this.get("keys",(()=>this.properties.map((([t])=>t))))}get columns(){return this.get("columns",(()=>this.properties.mapDefined((([,t])=>ifNotEmpty(t.property,t.property))))).distinct()}get droppedIn(){return this.get("droppedIn",(()=>this.columns.filter((t=>!this.keys.some((e=>e===t))))))}get droppedOut(){return this.get("droppedOut",(()=>this.properties.filter((([,t])=>!this.keys.some((e=>e===t.property)))).map((([t])=>t))))}in(t={}){return json.omit(this.properties.reduce(((e,[s,i])=>json.merge(e,{[s]:i.in({...e,...t})})),"source"===this.options.startFrom?t:{}),...this.droppedIn)}out(t={}){return json.omit(this.properties.reduce(((e,[s,i])=>json.merge(e,isEmpty(i.property)?i.out(t,s):{[i.property??""]:i.out({...e,...t},s)})),"source"===this.options.startFrom?t:{}),...this.droppedOut)}toString(){return this.constructor.name}},mappings={item:(t,e)=>new Property(t,e),ignore:(t="")=>({property:t,in:()=>{},out:()=>{}}),skipIn:t=>({property:t,in:()=>{},out:(e={})=>e[t]}),skipOut:t=>({property:t,in:(e={})=>e[t],out:()=>{}}),func:(t,e,s)=>({property:t,in:(t={})=>ofGet(e,t),out:(t={})=>ofGet(s,t)}),add:t=>({property:"",in:(e={})=>ofGet(t,e),out:()=>{}}),map:(t,e="")=>({property:e,in:(s={})=>ofConstruct(t).in(isEmpty(e)?s:s[e]),out:(e={},s="")=>ofConstruct(t).out(isEmpty(s)?e:e[s])}),propsToList:(...t)=>({property:"",in:(e={})=>toList(t.map((t=>ofConstruct(t).in(e)))).toJSON(),out:(e={},s="")=>t.reduce(((t,i,r)=>{const n=toList(e[s])[r],o=i.out(n);return{...t,[i.property]:o??{}}}),{})}),list:(t,e)=>({property:e,in:(s={})=>toList(s[e]).map((e=>t.in(e))).toJSON(),out:(e={},s="")=>toList(isEmpty(s)?e:e[s]).map((e=>t.out(e))).toJSON()})},MappedRouteGateway=class extends RouteGateway{constructor(t,e,s=new Mapper,i=new Api){super(t,e,i),this.route=t,this.routeId=e,this.map=s,this.api=i}get(t,e){return super.get(t,e).then((t=>t.map((t=>this.map.in(t)))))}getOne(t,e){return super.get(t,e).then((t=>t.first())).then((t=>this.map.in(t)))}add(t){return super.add(this.map.out(t))}update(t){return super.update(this.map.out(t))}},isEqualArray=(t,e)=>choose([t,e]).case((([t,e])=>!isArray(t)||!isArray(e)),!1).case((([t,e])=>t?.length!==e?.length),!1).else((([t,e])=>!t.some(((t,s)=>!isEqual(t,e[s]))))),isEqualObject=(t,e)=>choose([Object.keys(t),Object.keys(e)]).case((([t,e])=>t.length!==e.length),!1).case((([t,e])=>t.some((t=>!e.includes(t)))),!1).case((([s])=>s.some((s=>!isEqual(t[s],e[s])))),!1).else(!0),isEqual=(t,e)=>choose([t,e]).case((([t,e])=>t===e),!0).case((([t,e])=>isArray(t)||isArray(e)),(([t,e])=>isEqualArray(t,e))).case((([t,e])=>null==t||null==e||!isObject(t)&&!isObject(e)),(([t,e])=>t!=t&&e!=e)).else((([t,e])=>isEqualObject(t,e))),ignore=Symbol("view.ignore"),keep=Symbol("view.keep"),json2=Symbol("view.json"),spread="view.spread",toViewer=(t,e)=>choose(e).is.not.defined((t=>t),{key:t,f:()=>{}}).type(isBoolean,(e=>({key:t,f:()=>e}))).equals(ignore,{key:t,f:()=>{}}).equals(keep,{key:t,f:e=>traverse(e,t)}).equals(json2,{key:t,f:e=>asJson(traverse(e,t))}).type(isString,(e=>({key:t,f:t=>traverse(t,e)}))).type(isEnumConstructor,(e=>({key:t,f:(t,s)=>use(traverse(t,s),(t=>isArray(t)?e.byIds(t):e.byId(t)))}))).type(isConstructor,(e=>({key:t,f:(t,s)=>use(traverse(t,s),(t=>isArray(t)?t.map((t=>optional2(e,t))):optional2(e,t)))}))).type(isSimpleView,(e=>({key:t,f:s=>ifDefined(traverse(s,t),(t=>e.from(t)))}))).type(isFunction,(e=>({key:t,f:e}))).else((e=>({key:t,f:()=>e}))),optional2=(t,e)=>ifDefined(e,(e=>new t(e)),(()=>e)),toViewers=t=>meta(t).entries().map((([t,e])=>toViewer(t,e))),View=class t{constructor(t={},e="scratch",s=toViewers(t),i=[]){this.views=t,this.startsFrom=e,this.viewers=s,this.spreads=i}get fromSource(){return new t(this.views,"source",this.viewers,this.spreads)}spread(e){return new t(this.views,this.startsFrom,this.viewers,[...this.spreads,e])}from(t){return isPageList(t)?toPageList(t.map((t=>this.reduce(t))),t.options):isArray(t)?t.map((t=>this.reduce(t))):this.reduce(t)}same=(t,e)=>isEqual(this.from(t),this.from(e));reduce=t=>use(asJson(t),(t=>{const e=this.viewers.reduce(((e,s)=>s.key===spread?{...e,...asJson(s.f(t,s.key))}:json.set(e,s.key,s.f(t,s.key))),"scratch"===this.startsFrom?{}:t);return this.spreads.reduce(((e,s)=>({...e,...asJson(ofGet(s,t))})),e)}))},isSimpleView=t=>t instanceof View,view=t=>new View(t),views={ignore:ignore,keep:keep,json:json2,spread:spread,skip:ignore,equals:(t,e)=>s=>isEqual(traverse(s,t),e),value:t=>()=>t,coalesce:(...t)=>e=>t.reduce(((t,s)=>t??traverse(e,s)),void 0),or:{key:t=>(e,s)=>traverse(e,s)??traverse(e,t),value:t=>(e,s)=>traverse(e,s)??t,func:t=>(e,s)=>traverse(e,s)??t(e,s)}},ViewRouteGateway=class extends RouteGateway{constructor(t,e,s={in:view({}).fromSource,out:view({}).fromSource},i=new Api){super(t,e,i),this.route=t,this.routeId=e,this.views=s,this.api=i}get(t,e){return super.get(t,e).then((t=>t.map((t=>this.views.in.from(t)))))}getOne(t,e){return super.get(t,e).then((t=>t.first())).then((t=>this.views.in.from(t)))}add(t){return super.add(this.views.out.from(t))}update(t){return super.update(this.views.out.from(t))}},quote=t=>isNumber(t)||isBoolean(t)||isClause(t)?t.toString():`'${t}'`,Clause=class{constructor(t,e,s){this.first=t,this.operator=e,this.second=s}and=t=>new ParathesizedClause(this,"AND",t);or=t=>new ParathesizedClause(this,"OR",t);toString(){return`${this.first} ${this.operator} ${quote(this.second)}`}},ParathesizedClause=class extends Clause{toString(){return`(${this.first} ${this.operator} ${quote(this.second)})`}},toClause=(t,e,s,i=convert.default)=>new Clause(t,e,i.from(s)),isClause=t=>isA(t,"and","or"),Column=class extends Property{constructor(t,e,s){super(e,s),this.owner=t}get count(){return this.function("COUNT")}get max(){return this.function("MAX")}get min(){return this.function("MIN")}get sum(){return this.function("SUM")}get average(){return this.function("AVG")}get length(){return this.function("LEN")}get asc(){return this.format("$col ASC")}get desc(){return this.format("$col DESC")}in=(t={})=>tryTo(t).map((t=>t[this.property]??ofGet(this.options?.dflt))).map((t=>this.options?.convert?.to(t))).orElse();out=(t={},e="")=>tryTo(t).map((t=>this.options?.convert?.from(t[e]))).orElse();function=t=>this.format(`${t}($name)`);format=t=>new PatternColumn(this,t);is=t=>this.clause("=",t);not=t=>this.clause("<>",t);like=t=>this.clause("LIKE",`%${t}%`);startsLike=t=>this.clause("LIKE",`${t}%`);endsLike=t=>this.clause("LIKE",`%${t}`);unlike=t=>this.clause("NOT LIKE",`%${t}%`);less=t=>this.clause("<",t);lessEqual=t=>this.clause("<=",t);greater=t=>this.clause(">",t);greaterEqual=t=>this.clause(">=",t);as=t=>this.format(`$col AS ${t}`);toString(){return`${this.owner}.${this.property}`}clause=(t,e)=>toClause(this,t,e,this?.options?.convert)},PatternColumn=class extends Column{constructor(t,e){super(t.owner,t.property),this.col=t,this.pattern=e}toString(){return this.pattern.replace("$col",this.col.toString()).replace("$table",this.col.owner.toString).replace("$name",this.col.property)}},OrderColumn=class extends PatternColumn{},SqlQuery=class{constructor(t,e=toList()){this.table=t,this.clauses=e}where=(...t)=>(this.clauses.add(t),this)},Delete=class extends SqlQuery{toString(){return`DELETE FROM ${this.table}`+ifGet(this.clauses.length,` WHERE ${this.clauses.join(" AND ")};`,";")}},Insert=class extends SqlQuery{constructor(t,e){super(t),this.table=t,this.fields=e}toString(){return`INSERT INTO ${this.table} (${Object.keys(this.fields).join(", ")}) OUTPUT INSERTED.* VALUES (${Object.values(this.fields).map((t=>quote(t))).join(", ")});`}},Join=class{constructor(t,e,s,i){this.first=t,this.second=e,this.c=s,this.c2=i,this.db=this.first.db}db;on(t,e){return this.c=t,this.c2=e,this}toString(){return`${this.first} JOIN ${this.second} ON ${this.c} = ${this.c2}`}},Select=class extends SqlQuery{constructor(t,e=toList()){super(t),this.columns=e}ordered=toList();grouped=toList();_top=0;_limit=0;_offset=0;from(t){return this.table=t??this.table,this}orderBy=(...t)=>(this.ordered.add(t),this);groupBy(...t){return this.grouped.add(t),this}top(t){return this._top=t,this}limit(t){return this._limit=t,this}offset(t){return this._offset=t,this}toString(){return"SELECT "+ifGet(this._top,`TOP ${this._top} `,"")+ifGet(this.columns.length,this.columns.join(", "),"*")+` FROM ${this.table}`+ifGet(this.clauses.length,` WHERE ${this.clauses.join(" AND ")}`,"")+ifGet(this.grouped.length,` GROUP BY ${this.grouped.join(", ")}`,"")+ifGet(this.ordered.length,` ORDERED BY ${this.ordered.join(", ")}`,"")+ifGet(this._limit,` LIMIT ${this._limit}`,"")+ifGet(this._offset,` OFFSET ${this._offset};`,";")}},Update=class extends SqlQuery{constructor(t,e){super(t),this.table=t,this.fields=e}toString(){return`UPDATE ${this.table} SET ${Object.entries(this.fields).map((([t,e])=>toClause(t,"=",e))).join(", ")} OUTPUT INSERTED.*`+ifGet(this.clauses.length,` WHERE ${this.clauses.join(" AND ")};`,";")}},Count=class extends Select{toString(){return"SELECT COUNT(*)"+ifGet(this._top,` TOP ${this._top}`,"")+` FROM ${this.table}`+ifGet(this.clauses.length,` WHERE ${this.clauses.join(" AND ")}`,"")+ifGet(this.grouped.length,` GROUP BY ${this.grouped.join(", ")}`,"")+";"}},Table=class extends Mapper{map={...mappings,column:(t,e)=>new Column(this,t,e)};id=this.map.column("",{dflt:toUuid});constructor(t={startFrom:"source"}){super(t)}get db(){return Database.Default}get count(){return new Count(this)}prop=(t,e)=>this.map.column(t,e);select=(...t)=>new Select(this,toList(t));insert=t=>new Insert(this,this.out(t));update=t=>new Update(this,this.out(t));delete=()=>new Delete(this,toList());join=t=>new Join(this,t)},TableGateway=class extends Gateway{constructor(t,e=t.db.provide()){super(),this.table=t,this.provider=e}provide=({provider:t}={})=>t??this.provider;all(t){return this.provide(t).query(this.table.select()).then((e=>toPageList(e.map((t=>this.table.in(t))),t)))}byId(t,e){return this.provide(e).query(this.table.select().where(this.table.id.is(t))).then((t=>t.first())).then((t=>ifDefined(t,this.table.in(t))))}exists(t,e){return this.byId(t).then((t=>isDefined(t)))}add(t,e){return this.provide(e).query(this.table.insert(t)).then((e=>when(e.first()).not.isDefined.reject(`Could not add items with id ${t.id}`))).then((t=>this.table.in(t)))}remove(t,e){return this.provide(e).command(this.table.delete().where(this.table.id.is(t))).then((()=>!0))}update(t,e){return this.provide(e).query(this.table.update(t).where(this.table.id.is(t.id))).then((e=>when(e.first()).not.isDefined.reject(`Could not update item with id ${t.id}`))).then((t=>this.table.in(t)))}},builder=class t{static state={};static singleton=(e,...s)=>t.state[asString(e)]??(t.state[asString(e)]=new e(...s));static reset=()=>{t.state={}}},build={singleton:(t,...e)=>builder.singleton(t,...e),reset:()=>builder.reset()},singleton=(t,...e)=>build.singleton(t,...e),toCacheOptions=t=>({expiresIn:t.expiresIn??"5m",store:t.store}),cache=t=>e=>{meta(e).set("cache",toCacheOptions(t))},isCurrency=t=>isA(t,"id","name","digits","code"),Environment=class t extends Enum{static Dev=new t("Development","dev");static Tst=new t("Test","tst");static Acc=new t("Acceptance","acc");static Prd=new t("Production","prd")},isFalsy=t=>!t,isTruthy=t=>!isFalsy(t),isIndexed=t=>isA(t,"index"),ofMessage=(t,...e)=>isFunc(t)?t(...e):t,isNullish=t=>null==t,Parser=class{constructor(t,e=!0){this.value=t,this.valid=e}if={equals:t=>this.evaluate(isTrue,t),empty:t=>this.evaluate(isEmpty,t),defined:t=>this.evaluate(isDefined,t),valid:t=>this.evaluate(isValid,t),in:(...t)=>this.evaluate((()=>isIn(this.value,toArray(...t)))),is:{object:t=>this.evaluate(isObject,t),string:t=>this.evaluate(isString,t),instance:(t,e)=>this.evaluate((()=>this.value instanceof t),e)},not:{empty:t=>this.evaluateNot(isEmpty,t),defined:t=>this.evaluateNot(isDefined,t),valid:t=>this.evaluateNot(isValid,t),isObject:t=>this.evaluateNot(isObject,t),in:(...t)=>this.evaluate((()=>!isIn(this.value,toArray(...t)))),is:{object:t=>this.evaluateNot(isObject,t),string:t=>this.evaluateNot(isString,t),instance:(t,e)=>this.evaluate((()=>!(this.value instanceof t)),e)}}};evaluate(t,e){return on(this,(s=>s.valid=ofGet(t,e?ofGet(e,this.value):this.value)))}evaluateNot(t,e){return on(this,(s=>s.valid=!ofGet(t,e?ofGet(e,this.value):this.value)))}},asc=1,desc=-1,tag=t=>(e,s)=>{meta(e).property(s).set(t,s)},searchable=()=>tag(searchable.name),toSegment=(t,{segment:e,query:s}={})=>({key:t,segment:e,query:s,toString:()=>asString(t)}),uri={host:t=>toSegment(t,{segment:t??ctx.env.host??"$host"}),resource:t=>toSegment(toName(t,"Uri"),{segment:toName(t,"Uri")}),segment:t=>toSegment(t,{segment:t}),path:t=>toSegment(t,{segment:`:${t}`}),query:t=>toSegment(t,{query:e=>tryTo(e).is.defined().map((t=>encodeURIComponent(asString(t)))).map((e=>`${t}=${e}`)).orElse("")??""}),boolean:t=>toSegment(t,{query:e=>isTrue(e)?`${t}`:""})},toRoute=(...t)=>toList(t).mapDefined((t=>t.segment)).join("/"),EasyUri=class t{constructor(t=[]){this.segments=t}static id=uri.path("id");static ids=uri.query("ids");static query=uri.query("q");static sort=uri.query("s");static skip=uri.query("skip");static take=uri.query("take");host=uri.host();resource=uri.resource(this);state={};get path(){return toRoute(uri.segment(""),this.resource,...this.segments)}get complete(){return toRoute(this.host,this.resource,...this.segments)}get isInternal(){return toRoute(this.host)===(ctx.env.host??"$host")}get props(){return meta(this.state).values()}route=(t=this.resource.key)=>toRoute(uri.segment(""),uri.segment(t?.toLowerCase()),...this.segments);set=(t,e)=>(tryTo(e).is.defined().accept((e=>this.state[t.key??""]={segment:t,value:e})),this);toString(){return tryTo((()=>this.props)).map((t=>t.filter((t=>t.segment?.segment)))).map((t=>t.reduce(((t,e)=>t.replace(asString(e.segment.segment),asString(e.value))),this.complete))).map((t=>({route:t,query:this.props.mapDefined((t=>t.segment?.query?t.segment?.query(t.value):void 0))?.join("&")}))).map((({route:t,query:e})=>isNotEmpty(e)?`${t}?${e}`:t)).value}id=e=>this.set(t.id,e);ids=e=>this.set(t.ids,toArray(e).join(","));query=e=>this.set(t.query,e);sort=e=>this.set(t.sort,asString(e));skip=e=>this.set(t.skip,e);take=e=>this.set(t.take,e);expand(t){return entries(t).filter((([t,e])=>isNotEmpty(e))).reduce(((t,[e,s])=>isBoolean(s)?t.set(uri.boolean(e),s):t.set(uri.query(e),toArray(s).join(","))),this)}},clipUri=t=>tryTo((()=>asString(t))).map((t=>t.replace(/^(https?:\/\/)?(www\.)?/,""))).map((t=>t.replace(/\/$/,""))).value,base64={decode:t=>Buffer.from(t,"base64").toString("utf-8"),encode:t=>Buffer.from(t,"utf-8").toString("base64"),toJson:t=>JSON.parse(base64.decode(t))},isLoading=(...t)=>isNotPresent(...t);function log(t,e){return e?(console.log(t,e),e):(console.log(t),t)}function dir(t){return console.dir(t,{depth:200}),t}var Sentence=class{constructor(t,e,s=(e?.sentence??[]).concat(t)){this.sentence=s}toString(){return text(this.sentence.join(" ")).sentence.toString()}},Topic=class extends Sentence{it=new Sentence("it",this);anything=new Sentence("anything",this);id=t=>new Sentence(`id '${t}'`,this);your=t=>new Sentence(`your ${t??"item"}`,this);a=t=>new Sentence(t?`a ${t}`:"an item",this);an=t=>new Sentence(`an ${t??"item"}`,this);any=t=>new Sentence(`any ${t??"items"}`,this)},Verb=class extends Sentence{add=new Topic("add",this);check=new Topic("check",this);fetch=new Topic("fetch",this);find=new Topic("find",this);like=new Topic("like",this);process=new Topic("process",this);remove=new Topic("remove",this);translate=new Topic("translate",this);update=new Topic("update",this);validate=new Topic("validate",this)},Not=class extends Verb{},SupportVerb=class extends Verb{not=new Not("not",this)},We=class extends Sentence{could=new SupportVerb("could",this);did=new SupportVerb("did",this);added=new Topic("added",this);checked=new Topic("checked",this);fetched=new Topic("fetched",this);found=new Topic("found",this);liked=new Topic("liked",this);processed=new Topic("processed",this);removed=new Topic("removed",this);translated=new Topic("translated",this);updated=new Topic("updated",this);validated=new Topic("validated",this)},we=new We("we"),Wait=class{static wait(t=0){return new Promise((e=>setTimeout(e,t)))}static seconds(t=0){return this.wait(1e3*t)}},wait=t=>Wait.wait(t);
//# sourceMappingURL=/sm/e4c1e7e8682ccf67aa92e9bb04ef45289ce857e93d2045340c1c788a13ca6caa.map