@questwork/q-utilities 0.1.30 → 0.1.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/q-utilities.cjs +12 -0
- package/dist/q-utilities.d.ts +1035 -0
- package/dist/q-utilities.esm.js +2817 -4419
- package/dist/q-utilities.iife.js +12 -0
- package/dist/q-utilities.umd.js +12 -0
- package/package.json +22 -24
- package/.github/workflows/publish.yml +0 -60
- package/dist/index.min.cjs +0 -4744
- package/dist/q-utilities.min.js +0 -4775
- package/eslint.config.js +0 -3
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"use strict";var Nt=Object.defineProperty;var Dt=(n,e,t)=>e in n?Nt(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var $e=(n,e,t)=>Dt(n,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});function Me({allowCoordinator:n,allowOwner:e,query:t={},required:r,user:s}){if(!s)throw new Error("Require login.");s.permission;const i=s.permission.getScopes(r||{})||[];!i||i.length,i.includes("*")||(t.tenantCode=s.tenantCode),i.includes("TENANT")||(t.eventShortCode=s.eventShortCode),n&&t.registrationGroupCode&&s.myManagedRegistrationGroupCodes.includes(t.registrationGroupCode)?t.__ALLOW_COORDINATOR=!0:i.includes("EVENT")||(t.eventRegistrationCode=s.eventRegistrationCode),e&&(t.__ALLOW_OWNER=!0);const a=s.getExcludedFields(r);return a.length>0&&(t.__EXCLUDED_FIELDS=a),t.__LOGIN_SUBJECT_CODE=s.loginSubjectCode,t}function je(n,e){const t=new Date(n),r=e?new Date(e):new Date;if(isNaN(t.getTime())||isNaN(r.getTime())||t>r)return null;let s=r.getFullYear()-t.getFullYear();const i=r.getMonth()-t.getMonth();return(i<0||i===0&&r.getDate()<t.getDate())&&s--,s}function le(n,{source:e,target:t}){return n.meta?((!n.meta.creator||n.meta.creator===e.getId())&&(n.meta.creator=t.getId()),(!n.meta.owner||n.meta.owner===e.getId())&&(n.meta.owner=t.getId())):((!n.creator||n.creator===e.getId())&&(n.creator=t.getId()),(!n.owner||n.owner===e.getId())&&(n.owner=t.getId())),n}function Y(n){return n!=null&&typeof n!="boolean"&&String(n).trim()!==""&&!isNaN(Number(n))}function g(n,e){let t=n,r=e;if(typeof n=="string"&&(t=t.split(".")),!Array.isArray(n)&&typeof n=="object"){const{keys:i,obj:a}=n;t=i,r=a}if(t.length===0)return r;const s=t.shift();return r&&Object.prototype.hasOwnProperty.call(r,s)?g(t,r[s]):r&&s?t.length>0?g(t,r[s]):r[s]:r}function Mt(n){const e={};for(const[t,r]of Object.entries(n)){const s=t.match(/^(.*?)\|(boolean|date|html|number|string)$/);let i=t,a=null;s&&(i=s[1],a=s[2]);const o=i.split(".");let l=e;for(let c=0;c<o.length-1;c++){const f=o[c];(!l[f]||typeof l[f]!="object")&&(l[f]={}),l=l[f]}const u=o[o.length-1];if(a==="boolean")r===1||r==="1"||r===!0||r==="true"||r==="TRUE"?l[u]=!0:r===0||r==="0"||r===!1||r==="false"||r==="FALSE"?l[u]=!1:l[u]=!!r;else if(a==="number")l[u]=Number(r)||0;else if(a==="date")l[u]=new Date(r);else if(a==="html")if(r&&typeof r=="string"){let c=[];r.includes(`
|
|
2
|
+
|
|
3
|
+
`)||r.includes(`\r
|
|
4
|
+
\r
|
|
5
|
+
`)?c=r.split(/\r?\n\s*\r?\n/).filter(f=>f.trim()!==""):c=r.split(/\r?\n/).filter(f=>f.trim()!==""),c.length>0?l[u]=c.map(f=>`<div>${f.trim()}</div>`).join(""):l[u]=r?`<div>${r}</div>`:""}else l[u]=r?`<div>${r.toString()}</div>`:"";else if(r==null)l[u]="";else if(typeof r=="number")l[u]=r;else if(typeof r=="string"&&r.trim()!==""){const c=r.trim();/^-?\d+$/.test(c)?l[u]=Number.parseInt(c,10):/^-?\d+\.\d+$/.test(c)?l[u]=Number.parseFloat(c):l[u]=r}else l[u]=(r==null?void 0:r.toString())||""}return e}function jt(n,e){return e.split(".").reduce((r,s)=>{if(s.endsWith("[]")){const i=s.slice(0,-2);return Array.isArray(r[i])?r[i]:[]}if(s.includes("[")&&s.includes("]")){const i=s.match(/(\w+)\[(\d+)\]/);if(i){const a=i[1],o=i[2];return r&&r[a]&&r[a][o]}}else return r&&Array.isArray(r)?r.map(i=>i[s]):r&&r[s]},n)}function kt(n,e){return e.split(".").reduce((t,r)=>t&&t[r]!==void 0?t[r]:void 0,n)}function Ft(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof Date)&&!(n instanceof RegExp)&&Object.prototype.toString.call(n)==="[object Object]"}function ae(n,...e){if(!e.length)return n;const t=e.shift();if(ne(n)&&ne(t))for(const r in t)ne(t[r])?(n[r]||(n[r]={}),ae(n[r],t[r])):n[r]=t[r];return ae(n,...e)}function Pt(n,e,t){const r=e.split(".");let s=n;for(let o=0;o<r.length-1;o++){const l=r[o];let u,c;const f=l.match(/^(\w+)\[(\d+)\]$/);if(f){for(u=f[1],c=Number.parseInt(f[2],10),(!s[u]||!Array.isArray(s[u]))&&(s[u]=[]);s[u].length<=c;)s[u].push(void 0);s[u][c]==null&&(s[u][c]={}),s=s[u][c]}else s[l]||(s[l]={}),s=s[l]}const i=r[r.length-1],a=i.match(/^(\w+)\[(\d+)\]$/);if(a){const o=a[1],l=Number.parseInt(a[2],10);for((!s[o]||!Array.isArray(s[o]))&&(s[o]=[]);s[o].length<=l;)s[o].push(void 0);s[o][l]=t}else s[i]=t}function ne(n){return n&&typeof n=="object"&&!Array.isArray(n)}const b={expandDotNotation:Mt,get:jt,getNestedValue:kt,isPlainObject:Ft,merge:ae,set:Pt};class A{constructor(e={}){e=e||{},this.key=e.key||null,this.value=typeof e.value<"u"?e.value:""}static init(e={}){if(e instanceof this)return e;const t=new this(e);return t.isValid?t:null}static initFromArray(e=[]){return Array.isArray(e)?e.map(t=>this.init(t)):[]}static initOnlyValidFromArray(e=[]){return this.initFromArray(e).filter(t=>t)}static get _classname(){return"KeyValueObject"}static get _superclass(){return"KeyValueObject"}static addItem(e,t,r){e.push(this.init({key:t,value:r}))}static addRecord(e=[],t,r){return this.hasKeyValue(e,t,r)||e.push(this.init({key:t,value:r})),e}static appendRecord(e=[],t,r){return e.map(s=>(this.sameKey(s,t)&&(s.value=[...s.value,...r]),s))}static appendValueArray(e=[],t,r){return e.map(s=>(this.sameKey(s,t)&&(s.value=[...s.value,...r]),s))}static foundByKey(e=[],t){return e.find(s=>this.sameKey(s,t))||null}static foundValueByKey(e=[],t){const r=this.foundByKey(e,t);return r?r.value:null}static fromObject(e={}){return Object.keys(e).reduce((t,r)=>(t.push(this.init({key:r,value:e[r]})),t),[])}static getValueByKey(e=[],t){return this.foundValueByKey(e,t)}static getMetadataValueByKeyAsArray(e=[],t){const r=this.getValueByKey(e,t);return r?b.isPlainObject(r)?Object.keys(r).reduce((s,i)=>(s.push({key:i,value:r[i]}),s),[]):r:[]}static getValueByKeyFromArray(e=[],t){if(e.length===0)return null;const s=e.shift().find(i=>this.sameKey(i,t));return s&&s.value?s.value:this.getValueByKeyFromArray(e,t)}static getValuesByKey(e=[],t){return e.reduce((r,s)=>(this.sameKey(s,t)&&r.push(s.value),r),[])}static hasKeyValue(e=[],t,r){return typeof r>"u"?e.filter(s=>this.sameKey(s,t)).length>0:e.filter(s=>this.sameKey(s,t)&&ve(s.value,r)).length>0}static insertOrUpdateRecord(e=[],t,r){let s=[...e];return this.hasKeyValue(e,t)?s=this.updateRecord(e,t,r):s.push(this.init({key:t,value:r})),s}static keys(e=[]){return Array.isArray(e)?e.reduce((t,r)=>(t.push(r.key),t),[]):[]}static mapToKeyValue(e=[],t="key",r="value"){return Array.isArray(e)?e.reduce((s,i)=>{if(i&&typeof i=="object"){const a=b.get(i,t),o=b.get(i,r);a!=null&&s.push(this.init({key:a,value:o!==void 0?o:""}))}return s},[]):[]}static merge(e,t){return(t||[]).map(r=>{const s=e.find(i=>i.key===r.key);s?s.value=Lt(r.value,s.value):e.push(r)}),e}static removeByKey(e,t){return e.reduce((r,s)=>(this.sameKey(s,t)||r.push(s),r),[])}static removeByKeys(e,t){return e.reduce((r,s)=>(t.includes(s.key)||r.push(s),r),[])}static sameKey(e,t){return e?ve(e.key,t):!1}static toObject(e=[]){return Array.isArray(e)?e.reduce((t,r)=>(t[r.key]=r.value,t),{}):{}}static toString(e=[],t="; "){return Array.isArray(e)?e.reduce((r,s)=>(r.push(`${s.key}: ${s.value}`),r),[]).join(t):""}static updateRecord(e=[],t,r){return e.map(s=>this.sameKey(s,t)?{...s,value:r}:s)}static updateOrInsertRecord(e=[],t,r){return this.insertOrUpdateRecord(e,t,r)}static updateRecordsFromArray(e=[],t=[]){if(Array.isArray(e)&&Array.isArray(t)){const r=this.toObject(e),s=this.toObject(t);return this.fromObject({...r,...s})}return[]}static values(e=[]){return Array.isArray(e)?e.reduce((t,r)=>(t.push(r.value),t),[]):[]}get isValid(){return!!this.key}get toObject(){const e={};return this.isValid&&(e[this.key]=this.value),e}}function Lt(n,e){return n===void 0?e:Array.isArray(n)&&Array.isArray(e)?[...new Set([...n,...e])]:typeof n=="object"&&typeof e=="object"&&!Array.isArray(n)&&!Array.isArray(e)?{...n,...e}:e}function ve(n,e){return n===e}function E(n,e,t=Vt,r=A){if(!n)return!0;if(typeof t!="function"||r&&typeof r!="function")return!1;const{key:s="",value:i,placeholder:a,keyValuePath:o=""}=n,[l]=Object.keys(i);if(!s&&typeof a>"u")switch(l){case"$and":return i.$and.reduce((c,f)=>c&&E(f,e,t,r),!0);case"$or":return i.$or.reduce((c,f)=>c||E(f,e,t,r),!1);default:return!1}let u=typeof a>"u"?t(s,e):a;if(o){const c=r.toObject(u);u=t(o,c)}switch(l){case"$after":{if(Y(i==null?void 0:i.$after)){const c=Number(String(i==null?void 0:i.$after));return Date.now()>c}return!1}case"$before":{if(Y(i==null?void 0:i.$before)){const c=Number(String(i==null?void 0:i.$before));return Date.now()<c}return!1}case"$empty":return u==null===i.$empty;case"$eq":return u===i.$eq;case"$gt":return u>i.$gt;case"$gte":return u>=i.$gte;case"$hasOverlap":return Bt(u,i.$hasOverlap);case"$lt":return u<i.$lt;case"$lte":return u<=i.$lte;case"$in":return Array.isArray(u)?!!u.find(c=>i.$in.includes(c)):typeof u!="object"?!!i.$in.includes(u):!1;case"$includes":return Array.isArray(u)?u.includes(i.$includes):!1;case"$intervalTimeGt":{const c=new Date().getTime(),f=new Date(u).getTime();return c-f>i.$intervalTimeGt}case"$intervalTimeLt":{const c=new Date().getTime(),f=new Date(u).getTime();return c-f<i.$intervalTimeLt}case"$inValue":{const c=t(i.$inValue,e),f=Array.isArray(c)?c:[];return Array.isArray(u)?!!u.find(h=>f.includes(h)):typeof u=="string"?!!f.includes(u):!1}case"$isToday":{const c=new Date,f=c.setHours(0,0,0,0),h=c.setHours(23,59,59,59),d=new Date(u).getTime();return(f<=d&&h>=d)===i.$isToday}case"$ne":return u!==i.$ne;case"$notIn":return Array.isArray(u)?!u.find(c=>i.$notIn.includes(c)):typeof u!="object"?!i.$notIn.includes(u):!1;case"$notInValue":{const c=t(i.$notInValue,e),f=Array.isArray(c)?c:[];return Array.isArray(u)?!u.find(h=>f.includes(h)):typeof u!="object"?!f.includes(u):!1}case"$range":{const[c,f]=i.$range;return typeof c=="number"&&typeof f=="number"&&u>=c&&u<=f}default:return!1}}function Vt(n,e){return g(n.split("."),e)}function Bt(n,e){let t=n,r=e;typeof t=="string"&&(t=t.split(",")),typeof r=="string"&&(r=r.split(","));const s=new Set(t);return r.find(i=>s.has(i))}function ce(n,e){const t=n&&n instanceof Date?n:new Date(n),r=["日","一","二","三","四","五","六"],s=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],i=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],a=e||"YYYY/MM/DD hh:mm",o=t.getDay(),l=i[o],u=r[o],c=s[o],f=t.getFullYear(),h=t.getMonth()+1,d=t.getDate(),y=t.getHours(),C=t.getMinutes(),R=t.getSeconds();return a.replace("YYYY",f).replace("MM",S(h)).replace("MM",S(h)).replace("DD",S(d)).replace("hh",S(y)).replace("mm",S(C)).replace("ss",S(R)).replace("M",h).replace("D",d).replace("h",y).replace("m",C).replace("s",R).replace("EEEE",S(c)).replace("EEE",S(u)).replace("EE",S(l)).replace("E",S(o))}function S(n){return n<10?`0${n}`:n}const p={argumentEmptyException:"Argument is empty",argumentFormatException:"Incorrect number or format of argument",invalidFuntionException:"Function Name is invalid",invalidRegExpException:"Invalid regular expression",isNotAFunctionException:"Is not a function",notExistException:"Key does not exist",resultEmptyException:"Result is empty",resultMoreThanOneException:"More than one result"};class m extends Error{constructor(e){super(e),this.message=e}}const Ut="_EMPTY",Oe=["concatIf","divide","eq","exec","filterAll","filterOne","formatDate","get","gt","gte","isEmpty","isNotEmpty","join","lt","lte","map","neq","removeHtml","replaceChar","sum","toLowerCase","toUpperCase"],Re="_HIDE",Kt="_NOT_EMPTY",w="_SELF",Ht=["<%=","%>"],Wt=["{{","}}"];function ke(n,e){if(typeof n!="string")throw new m(`_concatIf: ${p.argumentFormatException}: the data must be string :${n.join(", ")}`);if(e.length!==3)throw new m(`_concatIf: ${p.argumentFormatException}: ${e.join(", ")}`);if(n===null||typeof n>"u")return null;const[t,r,s]=e;if([Ut,Kt].includes(t)||r.length!==2)throw new m(`concatIf: ${p.argumentEmptyException}: ${t}, ${r}`);return n===""&&s.includes(Re)?"":n!==""&&(n!==null||n!==void 0)&&s.includes(Re)?`${r[0]}${n}${r[r.length-1]}`:s}function Fe(n,e){try{return Number.isNaN(n)?n:n/e}catch(t){throw t}}function Pe(n,e){if(e.length!==3)throw new m(`eq: ${p.argumentFormatException}: ${e.join(", ")}`);if(n===null||typeof n>"u")return null;e.includes(w)&&(e=e.map(r=>r===w?n:r));const t=e[0];return n===t?e[1]:e[2]}function Yt(n,e){try{const[t,...r]=e;return n[t](...r)}catch(t){throw t}}function fe(n,e){try{if(!Array.isArray(e)||e.length===0)throw new m(p.argumentEmptyException);return!Array.isArray(n)||n.length===0?[]:typeof n[0]=="object"?Le(n,e):typeof n[0]=="string"||typeof n[0]=="number"?zt(n,e):[]}catch(t){throw t}}function zt(n,e){const t=e.flat();return n.filter(r=>t.some(s=>Ve(s,r)))}function Le(n,e){if(e.length===1){const i=e[0];return n.filter(a=>i.includes(".")?g(i.split("."),a):Object.prototype.hasOwnProperty.call(a,i))}if(e.length>2){let i=n;for(let a=0;a<e.length;a+=2){const o=[e[a],e[a+1]];i=Le(i,o)}return i}const[t,...r]=e,s=r.flat();return n.filter(i=>{const a=t.includes(".")?g(t.split("."),i):i[t];return s.some(o=>Ve(o,a))})}function Ve(n,e){if(n===void 0&&e===void 0||n===null&&e===null)return!0;if(typeof n=="boolean")return n===e;if(n===""||n==="*")return e==null?!1:typeof e=="string"?n===""?e==="":e!=="":Array.isArray(e)?n===""?e.length===0:e.length!==0:n!=="";if(qt(n))return n===e;if(n.startsWith("[")&&n.endsWith("]"))return n==="[]"?Array.isArray(e)&&e.length===0:n==="[*]"?Array.isArray(e)&&e.length!==0:!1;const{operator:t,value:r}=Gt(n);if(!t||r!==0&&!r)return!1;switch(t){case">":return e>r;case"<":return e<r;case"!=":return e!==r;case">=":return e>=r;case"<=":return e<=r;default:return!1}}function qt(n){return typeof n=="string"?!(n.startsWith("[")&&n.endsWith("]")||/!=|>=|<=|>|</.test(n)):!Number.isNaN(n)}function Gt(n){const t=["!=",">=","<=",">","<"].find(i=>n.startsWith(i));if(!t)return{operator:null,value:null};const r=n.slice(t.length);if(/^[a-z]*$/i.test(r)&&t!=="!=")return{operator:null,value:null};const s=!Number.isNaN(Number.parseFloat(r))&&!Number.isNaN(r)?Number(r):r;return{operator:t,value:s}}function Jt(n,e){try{const t=fe(n,e);if(t.length===1)return t[0];if(t.length===0)return null;throw new m(p.resultMoreThanOneException)}catch(t){throw t}}function Be(n,e){if(e.length===0)throw new m(`_formateDate: ${p.argumentFormatException}: format parts must be not empty array`);if(n==null)return null;const t=new Date(n),r={yyyy:String(t.getFullYear()),mm:String(t.getMonth()+1).padStart(2,"0"),dd:String(t.getDate()).padStart(2,"0")},s=["yyyy","mm","dd"];if(e.filter(a=>a.length>1&&!s.includes(a)).length>0)throw new m(`_formateDate: ${p.argumentFormatException}: the format type is not valid: ${e.join(", ")}`);return e.reduce((a,o)=>a+(r[o]||o),"")}function J(n,e,t=null){try{if(e===null||typeof e>"u"||e==="")throw new m(p.argumentEmptyException);if(n===null)return null;if(e.includes(".")){const r=e.split(".");if(r.length>1){const s=r.shift(),i=r.join(".");return typeof n[s]<"u"?J(n[s],i,t):xe(e,t)}}return typeof n[e]<"u"?n[e]:xe(e,t)}catch(r){throw r}}function xe(n,e){return e!==null?e:null}function Ue(n,e){if(e.length!==3)throw new m(`_gt: ${p.argumentFormatException}: ${e.join(", ")}`);if(n===null||typeof n>"u")return null;e.includes(w)&&(e=e.map(r=>r===w?n:r));const t=e[0];return n>t?e[1]:e[2]}function Ke(n,e){if(e.length!==3)throw new m(`_gte: ${p.argumentFormatException}: ${e.join(", ")}`);if(n===null||typeof n>"u")return null;e.includes(w)&&(e=e.map(r=>r===w?n:r));const t=e[0];return n>=t?e[1]:e[2]}function He(n,e){if(e.length!==2)throw new m(`_isEmpty: ${p.argumentFormatException}: ${e.join(", ")}`);return e.includes(w)&&(e=e.map(t=>t===w?n:t)),n!==null&&typeof n=="object"&&Object.keys(n).length===0||n===""||n===null||n===void 0||n.length===0?e[0]:e[1]}function We(n,e){if(e.length!==2)throw new m(`_isNotEmpty: ${p.argumentFormatException}: ${e.join(", ")}`);return e.includes(w)&&(e=e.map(t=>t===w?n:t)),n!==null&&typeof n=="object"&&Object.keys(n).length===0||Array.isArray(n)&&n.length===0||typeof n=="string"&&n===""||n==null?e[1]:e[0]}function Ye(n,e){try{return n.length===0?"":n.length===1?Te(n[0]):n.map(t=>Te(t)).join(e)}catch(t){throw t}}function Te(n){return JSON.stringify(n).replace(/"([^"]+)":/g,"$1: ").replace(/"([^"]+)"/g,"$1").replace(/,/g,", ")}function ze(n,e){if(e.length!==3)throw new m(`_lt: ${p.argumentFormatException}: ${e.join(", ")}`);if(n===null||typeof n>"u")return null;e.includes(w)&&(e=e.map(r=>r===w?n:r));const t=e[0];return n<t?e[1]:e[2]}function qe(n,e){if(e.length!==3)throw new m(`_lte: ${p.argumentFormatException}: ${e.join(", ")}`);if(n===null||typeof n>"u")return null;e.includes(w)&&(e=e.map(r=>r===w?n:r));const t=e[0];return n<=t?e[1]:e[2]}function Ge(n,e){try{if(e.length===0)throw new m(p.argumentEmptyException);return n===null||typeof n>"u"?null:n.reduce((r,s)=>{e.length===1&&Array.isArray(e[0])&&(e=e[0],r.hasFormat=!0);const i=e.map(a=>{if(a.includes(".")){const o=a.split("."),l=o[0];o.shift();const u=o.join(".");return J(s[l],u)}return typeof s[a]<"u"?s[a]:null});return r.hasFormat?r.content.push(i):r.content=r.content.concat(i),r},{content:[],hasFormat:!1}).content}catch(t){throw t}}function Je(n,e){if(e.length!==3)throw new m(`_neq: ${p.argumentFormatException}: ${e.join(", ")}`);if(n===null||typeof n>"u")return null;e.includes(w)&&(e=e.map(r=>r===w?n:r));const t=e[0];return n!==t?e[1]:e[2]}function Ze(n,e){if(n==null)return null;if(!Array.isArray(e))throw new m(`_removeHtml: ${p.argumentFormatException}: args parts must be array`);return Zt(n,e[0])}function Zt(n,e=`
|
|
6
|
+
`){typeof e!="string"&&(e=`
|
|
7
|
+
`);let r=n.replace(/ /g," ").replace(/\s+/g," ").replace(/<\/?(p|div|h[1-6]|ul|ol|li|pre|section|article|table|tr|td|th)(\s[^>]*)?>/gi,"~~~").replace(/<br\s*\/?>/gi,"~~~").replace(/<[^>]+>/g,"").replace(/~{3,}/g,e).trim();return e===""?r=r.replace(/\s+/g," "):(r=r.replace(new RegExp(`${re(e)}+`,"g"),e),r=r.replace(new RegExp(`^${re(e)}|${re(e)}$`,"g"),"")),r}function re(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Xe(n,e){if(n==null)return null;if(!Array.isArray(e))throw new m(`_replaceChar: ${p.argumentFormatException}: args parts must be array`);return Xt(n,e[0],e[1])}function Xt(n,e,t){return!n||!e?n:n.replace(new RegExp(e,"g"),t)}function Qe(n,e){return Number.isNaN(n)||n===null||typeof n>"u"||n===""?n:e.reduce((t,r)=>t+r,n)}function et(n,e){if(e!==void 0)throw new m(`_toLowerCase: ${p.argumentFormatException}: ${e.join(", ")}`);return n===null||typeof n>"u"||typeof n!="string"?null:String(n).toLowerCase()}function tt(n,e){if(typeof n!="string")throw new m(`_toUpperCase: ${p.argumentFormatException}: the data must be string: ${n}`);if(e!==void 0)throw new m(`_toUpperCase: ${p.argumentFormatException}: the argument must be empty: ${e.join(", ")}`);return n===null||typeof n>"u"||typeof n!="string"?null:String(n).toUpperCase()}class de{constructor(e){this.data=e}static init(e){return new this(e)}static initFromArray(e=[]){return Array.isArray(e)?e.map(t=>this.init(t)):[]}static initOnlyValidFromArray(e=[]){return this.initFromArray(e).filter(t=>t)}static concatIf(e,t){return ke(e,t)}static divide(e,t){return Fe(e,t)}static eq(e,t){return Pe(e,t)}static filterAll(e,t){return fe(e,t)}static formatDate(e,t){return Be(e,t)}static get(e,t,r=null){return J(e,t,r)}static gt(e,t){return Ue(e,t)}static gte(e,t){return Ke(e,t)}static isEmpty(e,t){return He(e,t)}static isNotEmpty(e,t){return We(e,t)}static join(e,t=""){return Ye(e,t)}static lt(e,t){return ze(e,t)}static lte(e,t){return qe(e,t)}static map(e,t=[]){return Ge(e,t)}static neq(e,t){return Je(e,t)}static removeHtml(e,t){return Ze(e,t)}static replaceChar(e,t){return Xe(e,t)}static sum(e,t){return Qe(e,t)}static toLowerCase(e,t){return et(e,t)}static toUpperCase(e,t){return tt(e,t)}static parseFunction(e){return Ie(e,Oe)}static parseParams(e){return nt(e)}pipe(e=""){this.delimiters=e.substring(0,2)==="{{"?Wt:Ht;const t=new RegExp(`${this.delimiters[0]}\\s(.*?)\\s${this.delimiters[1]}`),r=e.match(t);if(r!==null)try{return Ie(r[1],Oe).reduce((i,a)=>nn(i,a.name,a.args),this.data)}catch(s){throw new m(`TemplateCompiler engine error: ${s.message}`)}throw new m(`TemplateCompiler engine error: ${p.invalidRegExpException}`)}}function Ie(n,e){const t=/(\w+)\(((?:[^()]|\((?:[^()]|\([^()]*\))*\))*)\)/;let r;if(n.includes("|")){r=[];let s="",i=0,a=null;for(let o=0;o<n.length;o++){const l=n[o];if((l==='"'||l==="'")&&(o===0||n[o-1]!=="\\")){a===l?a=null:a===null&&(a=l),s+=l;continue}a===null&&(l==="("?i++:l===")"&&i--),l==="|"&&i===0&&a===null?(r.push(s),s=""):s+=l}s&&r.push(s)}else r=[n];return r.reduce((s,i)=>{const a=i.match(t);if(a!==null){const o=a[1],l=a[2],u=nt(l);if(e.includes(o))s.push({name:o,args:u});else throw new m(`${o} is not a valid function`)}return s},[])}function nt(n){const e=n.trim();return e?e.includes(",")?Qt(e).map(r=>oe(r.trim())):[oe(e)]:[]}function Qt(n){const e=[];let t="",r=0,s=0,i=null;for(let a=0;a<n.length;a++){const o=n[a];if((o==='"'||o==="'")&&(a===0||n[a-1]!=="\\")){i===o?i=null:i===null&&(i=o),t+=o;continue}if(i!==null){t+=o;continue}o==="["?r++:o==="]"?r--:o==="("?s++:o===")"&&s--,o===","&&i===null&&r===0&&s===0?(e.push(t),t=""):t+=o}return t&&e.push(t),e}function oe(n){if(typeof n!="string")return n;const e=n.trim();if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.substring(1,e.length-1);const t=tn(e);return typeof t!="string"?t:e.startsWith("[")&&e.endsWith("]")?en(e):n}function en(n){const e=n.substring(1,n.length-1).trim();if(!e)return[];const t=[];let r="",s=null;for(let i=0;i<e.length;i++){const a=e[i];if((a==='"'||a==="'")&&(i===0||e[i-1]!=="\\")){s===a?s=null:s===null&&(s=a),r+=a;continue}a===","&&s===null?(r.trim()&&t.push(r.trim()),r=""):r+=a}return r.trim()&&t.push(r.trim()),t.map(i=>oe(i))}function tn(n){if(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))return n.substring(1,n.length-1);if(n==="true")return!0;if(n==="false")return!1;if(n!=="undefined")return n==="null"?null:!Number.isNaN(n)&&!Number.isNaN(Number.parseFloat(n))?Number(n):n}function nn(n,e,t){try{let r;switch(e){case"concatIf":return ke(n,t);case"divide":return Fe(n,t);case"eq":return Pe(n,t);case"exec":return Yt(n,t);case"filterAll":return fe(n,t);case"filterOne":return Jt(n,t);case"formatDate":return Be(n,t);case"get":if(t.length>2)throw new m(p.argumentFormatException);return t.length===2&&(r=t[t.length-1]),J(n,t[0],r);case"gt":return Ue(n,t);case"gte":return Ke(n,t);case"isEmpty":return He(n,t);case"isNotEmpty":return We(n,t);case"join":return Ye(n,t[0]);case"lt":return ze(n,t);case"lte":return qe(n,t);case"map":return Ge(n,t);case"neq":return Je(n,t);case"removeHtml":return Ze(n,t);case"replaceChar":return Xe(n,t);case"sum":return Qe(n,t);case"toLowerCase":return et(n);case"toUpperCase":return tt(n);default:throw new Error(`${e} is not a valid function`)}}catch(r){throw r}}function z(n,e){return n.reduce((t,r)=>{const{type:s,value:i="",restriction:a,template:o,format:l,showMinutes:u}=r;switch(s){case"array":{if(E(a,e,g)){const c=g(i.split("."),e)||[];t+=c.reduce((f,h)=>f+=z(o,h),"")}break}case"date":{if(E(a,e,g)){const c=g(i.split("."),e)||"";t+=ce(c,l).toString()}break}case"ellipsis":{if(E(a,e,g)){const{maxLength:c}=r,f=g(i.split("."),e)||"";f.length<=c?t+=f.toString():t+=`${f.substr(0,c)}...`}break}case"group":{if(E(a,e,g))return z(i,e);break}case"label":{E(a,e,g)&&(t+=i.toString());break}case"templateCompiler":{if(E(a,e,g)){const c=new de({data:e});t+=c.pipe(i)}break}case"value":{if(E(a,e,g)){const c=g(i.split("."),e)||"";t+=c.toString()}break}}return t},"")}function rt(n,e=/\$\{(.+?)\}/g,t,r){if(!n)return"";const s=typeof r=="function"?r:g,i=new RegExp(e,"g");return n.replace(i,(a,o)=>{const l=s({keys:o.split("."),obj:t});return l==null?"":typeof l=="object"?JSON.stringify(l):l})}function rn(n,e=0){try{if(typeof n=="number")return n.toString().length===10&&(n=n*1e3),new Date(n);if(typeof n=="string"&&n.length===8){const t=Number.parseInt(n.slice(0,4),10),r=Number.parseInt(n.slice(4,6),10)-1,s=Number.parseInt(n.slice(6,8),10);return new Date(t,r,s)}return new Date(n)}catch{throw new Error("input does not meet the requirements")}}class U{constructor({date:e,isUTC:t,is24Hour:r,timezoneOffset:s=0}={}){this.date=e,this.isUTC=t,this.is24Hour=r,this.timezoneOffset=s}getDateComponent(e){if(this.timezoneOffset!==0){const t=this.timezoneOffset*60*1e3;return new Date(this.date.getTime()+t)[`getUTC${e}`]()}else return this.isUTC?this.date[`getUTC${e}`]():this.date[`get${e}`]()}process(e){return e}}function D(n,e="0"){if(typeof n!="number")throw new TypeError("Parameter must be of number");return n<10?`${e}${n}`:n}class sn extends U{process(e){const t=this.getDateComponent("Date");return e=e.replace("DD",D(t)),e}}const an=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];class on extends U{process(e){const t=this.getDateComponent("Month");return e=e.replace("MMM",an[t]),e=e.replace("MM",D(t+1)),e}}class un extends U{process(e){const t=this.getDateComponent("FullYear");return e=e.replace("yyyy",t),e=e.replace("YYYY",t),e=e.replace("yy",t.toString().slice(-2)),e=e.replace("YY",t.toString().slice(-2)),e}}class ln extends U{process(e){let t=this.getDateComponent("Hours");const r=!this.is24Hour;if(r&&t>12&&(t-=12),r&&t===0&&(t=12),e=e.replace("HH",D(this.getDateComponent("Hours"))),e=e.replace("hh",D(t)),this.is24Hour)e=e.replace(/\s*\bA\b\s*/g," "),e=e.replace(/\s*\ba\b\s*/g," "),e=e.replace(/\s+/g," ").trim();else{if(e.includes("A")){const s=this.getDateComponent("Hours")>=12?"PM":"AM";e=e.replace(/\bA\b/g,s)}if(e.includes("a")){const s=this.getDateComponent("Hours")>=12?"pm":"am";e=e.replace(/\ba\b/g,s)}}return e=e.replace("mm",D(this.getDateComponent("Minutes"))),e=e.replace("ss",D(this.getDateComponent("Seconds"))),e}}class cn extends U{process(e){if(e.includes("Z"))if(this.isUTC)e=e.replace("Z","+0000");else{const t=this.date.getTimezoneOffset(),r=t>0?"-":"+",s=Math.abs(t),i=Math.floor(s/60),a=s%60,o=`${r}${i.toString().padStart(2,"0")}${a.toString().padStart(2,"0")}`;e=e.replace("Z",o)}if(e.includes("ddd")){const t=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],r=this.getDateComponent("Day");e=e.replace("ddd",t[r])}if(e.includes("dd")){const t=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],r=this.getDateComponent("Day");e=e.replace("dd",t[r])}return e}}function fn({date:n,format:e,isUTC:t,is24Hour:r,timezoneOffset:s=0}){return[cn,sn,on,un,ln].reduce((i,a)=>new a({date:n,isUTC:t,is24Hour:r,timezoneOffset:s}).process(i),e)}function st(n,e){const t=e||"YYYY/MM/DD hh:mm",r=t.includes("HH");let s=null;if(t.includes("Z"))s=0;else if(t.includes("+")){const a=t.match(/[+-]\d{2}:?\d{2}/);if(a){const o=a[0],l=o[0]==="+"?1:-1,u=parseInt(o.slice(1,3),10),c=o.includes(":")?parseInt(o.slice(4,6),10):parseInt(o.slice(3,5),10);s=l*(u*60+c)}}const i=rn(n,s===null?0:s);return fn({date:i,format:t,isUTC:s!==null,is24Hour:r,timezoneOffset:s===null?0:s})}function it(n,e={}){const{preserveBasicWhitespace:t=!0,removeNewlines:r=!1}=e;if(typeof n!="string")return{hasControlChars:!1,matches:[],inputType:typeof n,message:"Input is not a string"};const s=[];let i;return t&&!r?i=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F\u200B-\u200D\uFEFF\u202A-\u202E]/g:i=/[\x00-\x1F\x7F-\x9F\u200B-\u200D\uFEFF\u202A-\u202E]/g,n.replace(i,(a,o)=>(s.push({character:a,code:a.charCodeAt(0),hex:"0x"+a.charCodeAt(0).toString(16).toUpperCase().padStart(4,"0"),position:o,context:dn(n,o,10)}),"")),{hasControlChars:s.length>0,matches:s,totalFound:s.length,inputPreview:n.length>50?n.substring(0,50)+"...":n,inputLength:n.length,optionsUsed:{preserveBasicWhitespace:t},regexPattern:i.toString()}}function dn(n,e,t=10){const r=Math.max(0,e-t),s=Math.min(n.length,e+t+1);let i=n.substring(r,s);return i=i.replace(/[\x00-\x1F\x7F-\x9F]/g,a=>"\\u"+a.charCodeAt(0).toString(16).toUpperCase().padStart(4,"0")),i}function at(n){console.log("=== Control Character Detection Report ==="),console.log(`Input: "${n.inputPreview}" (${n.inputLength} chars)`),console.log(`Options: preserveBasicWhitespace = ${n.optionsUsed.preserveBasicWhitespace}`),console.log(`Regex pattern: ${n.regexPattern}`),console.log(`Control characters found: ${n.totalFound}`),n.hasControlChars?(console.log(`
|
|
8
|
+
📋 Matches found:`),n.matches.forEach((e,t)=>{console.log(`
|
|
9
|
+
${t+1}. Character: ${JSON.stringify(e.character)}`),console.log(` Code: ${e.code} (${e.hex})`),console.log(` Position: ${e.position}`),console.log(` Context: "...${e.context}..."`)})):console.log("✅ No control characters detected in Phase 1 range"),console.log("=== End Report ===")}function ot(n,e){n=n||{},e=e||{};const{firstName:t,middleName:r,noFirstName:s,prefix:i,title:a,upperCaseLastName:o=!0}=e;e.hasAsianCharacters=!1;let l=[];if((i||a)&&n.prefix){const c=se(e);l=c(l,n.prefix),l=c(l,n.title)}if(t!==!1&&!s){const c=se(e);l=c(l,n.firstName),l=c(l,n.givenName)}r===!0&&n.middleName&&(e.hasAsianCharacters=e.hasAsianCharacters||ut(n.middleName.toString()),l.push(n.middleName.toString()));const u=se(e,o);return l=u(l,n.lastName),l=u(l,n.familyName),l=u(l,n.surname),e.hasAsianCharacters?l.reverse().join(""):l.join(" ")}function se(n={},e=!1){let t=!1;return(r,s)=>{if(!t&&s){t=!0,n.hasAsianCharacters=n.hasAsianCharacters||ut(s.toString());const i=e?s.toString().toUpperCase():s.toString();r.push(i)}return r}}function ut(n){return/[\u3400-\u9FBF]/.test(n)}function lt({dataUrl:n="",filename:e=""}={}){const t=document.createElement("a");t.download=e,t.href=n,document.body.appendChild(t),t.click(),document.body.removeChild(t)}function ct(n){return String(n).replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")}function hn({responseHelper:n,handler:e,ignoreError:t=!1}){return async(r,s,i)=>{const a=typeof s=="function"&&!i,o=a?r:null,l=a?r.request:r,u=a?r.response:s,c=a?s:i;try{return await e({req:l,res:u}),a?await c():c()}catch(f){if(t)return a?await c():c();if(!n){if(a)throw f;return c(f)}const h=f.status||400,d=f.message||"An error occurred",y=n.standardizeResponse({err:f,message:d});a?(o.status=h,o.body=y):u.status(h).json(y)}}}function mn({responseHelper:n,service:e}){return async(t,r,s)=>{try{const{query:i}=t,a=await e.findAll({query:i});r.locals.findAllResult=a,await s()}catch(i){r.status(400).json(n.standardizeResponse({err:i,message:i.message||i}))}}}function pn({responseHelper:n,service:e}){return async(t,r,s)=>{try{const{params:i,query:a}=t,{id:o}=i,l=await e.findOne({query:{...a,id:o}});r.locals.findOneResult=l,await s()}catch(i){r.status(400).json(n.standardizeResponse({err:i,message:i.message||i}))}}}function yn(n,{query:e={}}={}){!e.__EXCLUDED_FIELDS||Array.isArray(e.__EXCLUDED_FIELDS)&&e.__EXCLUDED_FIELDS.length===0||(n.push({$set:{__originalEmail:"$_eventRegistration.email",__originalPhone:"$_eventRegistration.phone",__queryArr:{$ifNull:[e.__EXCLUDED_FIELDS||[],[]]},__isMyself:{$eq:["$_eventRegistration.loginSubjectCode",e.__LOGIN_SUBJECT_CODE]},__isGroupCoordinator:!!e.__ALLOW_COORDINATOR,__hasEventRegistration:{$ne:["$_eventRegistration",null]}}}),n.push({$set:{__shouldShowEmail:{$and:["$__hasEventRegistration",{$or:["$__isMyself","$__isGroupCoordinator",{$not:{$in:["email","$__queryArr"]}}]}]},__shouldShowPhone:{$and:["$__hasEventRegistration",{$or:["$__isMyself","$__isGroupCoordinator",{$not:{$in:["phone","$__queryArr"]}}]}]}}}),n.push({$set:{"_eventRegistration.email":{$cond:["$__shouldShowEmail","$__originalEmail","$$REMOVE"]},"_eventRegistration.phone":{$cond:["$__shouldShowPhone","$__originalPhone","$$REMOVE"]}}}),n.push({$unset:["__originalEmail","__originalPhone","__isMyself","__isGroupCoordinator","__queryArr","__hasEventRegistration","__shouldShowEmail","__shouldShowPhone"]}))}function gn({responseHelper:n,service:e}){return async(t,r,s)=>{try{const{body:i}=t;let a;Array.isArray(i)?a=await e.saveAll({docs:i}):a=await e.saveOne({doc:i}),r.locals.postResult=a,await s()}catch(i){r.status(400).json(n.standardizeResponse({err:i,message:i.message||i}))}}}function _n({responseHelper:n,service:e}){return async(t,r,s)=>{try{const{body:i,params:a}=t,{id:o}=a;if(o!==i.id)throw new Error("id in params and body must be same");const{data:l}=await e.findOne({query:{id:o}}),u=l[0];u.update(i);const c=await e.saveOne({doc:u});r.locals.updateOneResult=c,await s()}catch(i){r.status(400).json(n.standardizeResponse({err:i,message:i.message||i}))}}}const ft={customHandler:hn,findAllResult:mn,findOneResult:pn,hideSensitiveFields:yn,postResult:gn,updateOneResult:_n};function dt(n){const e=/[\w.%+-]+@[a-z0-9.-]+\.[a-z]{2,}/gi,t=new Set;return n?(n.forEach(r=>{if(!(!r||typeof r!="string"||!r.trim()))try{const i=r.replace(/[\u200B-\u200D\uFEFF\u202A-\u202E]/g,"").replace(/[<>]/g," ").replace(/\s+/g," ").trim().match(e);i&&i.forEach(a=>t.add(a.toLowerCase()))}catch(s){console.warn("Failed to process entry:",r,s)}}),Array.from(t).sort((r,s)=>r.localeCompare(s))):[]}async function Z(n,e,t){return new Promise((r,s)=>{const i=n[Symbol.iterator]();let a=0;const o=async l=>{const u=i.next();if(u.done){r(l);return}try{const[c,f]=await Promise.all([l,u.value]);o(e(c,f,a++))}catch(c){s(c)}};o(t)})}class X{constructor(e){e=e||{},this.model=e.model,this._sharedOptions=e._sharedOptions,this._queryOptions=e._queryOptions,this._saveOptions=e._saveOptions,this._Class=e._constructor&&e._constructor._Class?e._constructor._Class:null}static init(e={}){return O(this,e)}static get _classname(){return"Repo"}static get _superclass(){return"Repo"}get _classname(){return"Repo"}get _superclass(){return"Repo"}get isValid(){return this.model&&typeof this.model.deleteOne=="function"&&typeof this.model.findAll=="function"&&typeof this.model.saveOne=="function"}get queryOptions(){return{...this._sharedOptions,...this._queryOptions}}get saveOptions(){return{...this._sharedOptions,...this._saveOptions}}init(e){return this._Class&&typeof this._Class.init=="function"?this._Class.init(e):e}async deleteOne({id:e}){try{return{...await this.model.deleteOne({_id:e}),isNew:!1,data:[]}}catch(t){throw t}}findAll({config:e={},query:t,systemLog:r}){const s=W({systemLog:r,label:"REPO_READ",message:`fn ${this._classname}.prototype.findAll`,input:[{query:{...t},systemLog:{...r}}]}),i={...this.queryOptions,...e};return new Promise((a,o)=>{this.model.findAll(t,i,(l,u,c)=>{if(l)s({level:"warn",output:l.toString()}),o(l);else{const f={isNew:!1,data:u,total:c||u.length};s({level:"info",output:{...f}}),a(f)}})})}findOne({config:e={},query:t,systemLog:r}){const s=W({systemLog:r,label:"REPO_READ",message:`fn ${this._classname}.prototype.findOne`,input:[{query:{...t},systemLog:{...r}}]}),i={...this.queryOptions,...e};return new Promise((a,o)=>{this.model.findAll(t,i,(l,u)=>{if(l)o(l);else if(u.length===1){const c={isNew:!1,data:u,total:1};s({level:"info",output:{...c}}),a(c)}else u.length===0?o(new Error("record not found")):o(new Error("more than one is found"))})}).catch(a=>{throw s({level:"warn",output:a.toString()}),a})}saveAll({config:e={},docs:t,systemLog:r}){let s;const i=W({systemLog:r,label:"REPO_WRITE",message:`fn ${this._classname}.prototype.saveAll`,input:[{config:e,docs:[...t],systemLog:{...r}}]});return(typeof this.model.saveAll=="function"?this.model.saveAll({config:e,docs:t}):wn({config:e,docs:t,service:this})).then(o=>{o.length!==1&&(s=null);const l={data:o,isNew:s,total:o.length};return i({level:"info",output:{...l}}),l}).catch(o=>{throw i({level:"warn",output:o.toString()}),o})}saveOne({config:e={},doc:t,systemLog:r}){const s=W({systemLog:r,label:"REPO_WRITE",message:`fn ${this._classname}.prototype.saveOne`,input:[{config:e,doc:{...t},systemLog:{...r}}]}),i={...this.saveOptions,...e};return new Promise((a,o)=>{this.model.saveOne(t,i,(l,u)=>{l?(s({level:"warn",output:l.toString()}),o(l)):(s({level:"info",output:{...u}}),a(u))})})}}function W({systemLog:n,label:e,message:t,input:r}={}){return({level:s,messgae:i,output:a}={})=>{n&&n.systemLogHelper&&n.systemLogHelper.log({batchId:n.batchId,label:e,level:s,message:i||t,data:{payload:{input:r,output:a}}})}}async function wn({config:n={},docs:e,service:t}){let r=null;return n.session||t.saveOptions.session?r=await _e(e,async s=>{if(s){const i=await t.saveOne({config:n,doc:s});return(i._data||i.data)[0]}return null},{concurrency:1}):r=await Promise.all(e.map(async s=>{if(s){const i=await t.saveOne({config:n,doc:s});return(i._data||i.data)[0]}return null})),r}class he{constructor(e={}){e=e||{},this._data=e.data||e._data||[],this.err=e.err,this.isNew=e.isNew||!1,this.message=e.message,this.total=e.total||0,this._instanceBuilder=e._instanceBuilder}static init(e={}){return e instanceof this?e:new this(e)}static get _classname(){return"ApiResponse"}static get _superclass(){return"ApiResponse"}get data(){return this._instanceBuilder&&typeof this._instanceBuilder=="function"?this._data.map(this._instanceBuilder):this._data}}function I({repo:n,result:e}){return he.init({...e,_instanceBuilder:t=>n.init(t)})}class me{constructor({repo:e}){this.repo=e}static get _classname(){return"Service"}static get _superclass(){return"Service"}async deleteOne({id:e}){const t=await this.repo.deleteOne({id:e});return I({repo:this.repo,result:t})}async findAll({config:e={},query:t={},systemLog:r}={}){const s=await this.repo.findAll({config:e,query:t,systemLog:r});return I({repo:this.repo,result:s})}async findOne({config:e={},query:t={},systemLog:r}={}){const s=await this.repo.findOne({config:e,query:t,systemLog:r});return I({repo:this.repo,result:s})}init(e){return this.repo.init(e)}initFromArray(e=[]){return Array.isArray(e)?e.map(t=>this.init(t)):[]}initOnlyValidFromArray(e=[]){return this.initFromArray(e).filter(t=>t)}async saveAll({config:e={},docs:t=[],systemLog:r}={}){const s=t.map(a=>e.skipInit?a:this.init(a)),i=await this.repo.saveAll({config:e,docs:s,systemLog:r});return I({repo:this.repo,result:i})}async saveOne({config:e={},doc:t={},systemLog:r}={}){const s=e.skipInit?t:this.init(t);if(s){const i=await this.repo.saveOne({config:e,doc:s,systemLog:r});return I({repo:this.repo,result:i})}return{isNew:null,data:[],err:new Error("doc is not a valid instance")}}}function pe({repo:n}){if(n===void 0)throw new Error("repo is required.");if(n._superclass!==X._superclass)throw new Error("repo is not an instance of Repo.");return new me({repo:n})}async function ht({body:n={},GeneralModel:e,UniqueKeyGenerator:t,resourceInfo:r}){const{resources:s,data:i,globalShared:a={},shared:o={},relationship:l={}}=n,u=r||n.resourceInfo;return An(i,a,o),await Z(s,async(f,h)=>{const d=bn(h,u,t,e);En(i,l[h],f);const y=i[h],C=await d.saveAll({docs:[].concat(y)});return f[h]=Array.isArray(y)?C._data:C._data[0],f},{})}function An(n,e={},t={}){Object.keys(t).forEach(r=>{const s=n[r];Array.isArray(s)?n[r]=s.map(i=>b.merge({},i,e,t[r]||{})):n[r]=b.merge({},s,e,t[r]||{})})}function En(n,e={},t){Object.keys(e).forEach(r=>{const s=e[r],i=b.get(t,s);b.set(n,r,i)})}function bn(n,e,t,r){const{collectionName:s,fields:i}=e[n],a=t.makeGenerator(i),o=new r({collectionName:s,uniqueKeyGenerator:a});return pe({repo:new X({model:o})})}function ye(n,e,t,r,s){const i=s||A;return!Array.isArray(n)||n.length===0?null:n.reduce((a,o)=>{const{key:l,type:u,value:c,restriction:f}=o;if(r&&typeof r=="function"?r({rule:f,data:e}):!0){let d=c;switch(u){case"array":{d=c.map(y=>t({keys:y.value.split("."),obj:e}));break}case"fromKeyValue":{const{dataPath:y,key:C}=c,R=t({keys:y.split("."),obj:e});d=i.getValuesByKey(R,C)[0];break}case"toKeyValue":{const y=t({keys:c.split("."),obj:e});d=i.fromObject(y);break}case"nested":{d=ye(c,e,t,r);break}case"path":{d=t({keys:c.split("."),obj:e});break}case"orgin":{d=c;break}case"origin":{d=c;break}default:{d=c;break}}return l?{...a,[l]:d}:typeof d=="string"?d:{...a,...d}}return a},{})}function mt(n,e){return!e||typeof e!="string"?{}:n.reduce((t,r)=>(t[r[e]]||(t[r[e]]=0),t[r[e]]++,t),{})}function O(n,e){if(e instanceof n)return e;try{const t=new n(e);return t.isValid!==!1?t:null}catch(t){return console.log(`init failed for class: ${n._classname||"no _classname"}`,t),null}}function K(n,e){return Array.isArray(e)?e.map(t=>O(n,t)):[]}function Q(n,e){return K(n,e).filter(t=>t)}function pt(n,e){const t=Array.isArray(n)?n:[],r=Array.isArray(e)?e:[],s=new Map,i=(a,o)=>a===void 0?o:Array.isArray(a)&&Array.isArray(o)?[...new Set([...a,...o])]:typeof a=="object"&&typeof o=="object"&&!Array.isArray(a)&&!Array.isArray(o)?{...a,...o}:o;return t.forEach(a=>{s.set(a.key,a.value)}),r.forEach(a=>{const o=s.get(a.key);s.set(a.key,i(o,a.value))}),Array.from(s.entries()).map(([a,o])=>({key:a,value:o}))}function ge(n,e=6){return n=n.toString(),n.length<e?ge(`0${n}`,e):n}async function _e(n,e,{concurrency:t=Number.POSITIVE_INFINITY,stopOnError:r=!0,signal:s}={}){return new Promise((i,a)=>{if(n[Symbol.iterator]===void 0&&n[Symbol.asyncIterator]===void 0)throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof n})`);if(typeof e!="function")throw new TypeError("Mapper function is required");if(!(Number.isSafeInteger(t)&&t>=1||t===Number.POSITIVE_INFINITY))throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${t}\` (${typeof t})`);const o=[],l=[],u=new Map;let c=!1,f=!1,h=!1,d=0,y=0;const C=n[Symbol.iterator]===void 0?n[Symbol.asyncIterator]():n[Symbol.iterator](),R=()=>{N(s.reason)},Ce=()=>{s==null||s.removeEventListener("abort",R)},Se=$=>{i($),Ce()},N=$=>{c=!0,f=!0,a($),Ce()};s&&(s.aborted&&N(s.reason),s.addEventListener("abort",R,{once:!0}));const te=async()=>{if(f)return;const $=await C.next(),F=y;if(y++,$.done){if(h=!0,d===0&&!f){if(!r&&l.length>0){N(new AggregateError(l));return}if(f=!0,u.size===0){Se(o);return}const x=[];for(const[T,It]of o.entries())u.get(T)!==M&&x.push(It);Se(x)}return}d++,(async()=>{try{const x=await $.value;if(f)return;const T=await e(x,F);T===M&&u.set(F,T),o[F]=T,d--,await te()}catch(x){if(r)N(x);else{l.push(x),d--;try{await te()}catch(T){N(T)}}}})()};(async()=>{for(let $=0;$<t;$++){try{await te()}catch(F){N(F);break}if(h||c)break}})()})}function yt(n,e,{concurrency:t=Number.POSITIVE_INFINITY,backpressure:r=t}={}){if(n[Symbol.iterator]===void 0&&n[Symbol.asyncIterator]===void 0)throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof n})`);if(typeof e!="function")throw new TypeError("Mapper function is required");if(!(Number.isSafeInteger(t)&&t>=1||t===Number.POSITIVE_INFINITY))throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${t}\` (${typeof t})`);if(!(Number.isSafeInteger(r)&&r>=t||r===Number.POSITIVE_INFINITY))throw new TypeError(`Expected \`backpressure\` to be an integer from \`concurrency\` (${t}) and up or \`Infinity\`, got \`${r}\` (${typeof r})`);return{async*[Symbol.asyncIterator](){const s=n[Symbol.asyncIterator]===void 0?n[Symbol.iterator]():n[Symbol.asyncIterator](),i=[];let a=0,o=!1,l=0;function u(){if(o||!(a<t&&i.length<r))return;a++;const c=(async()=>{const{done:f,value:h}=await s.next();if(f)return a--,{done:!0};u();try{const d=await e(await h,l++);if(a--,d===M){const y=i.indexOf(c);y>0&&i.splice(y,1)}return u(),{done:!1,value:d}}catch(d){return a--,o=!0,{error:d}}})();i.push(c)}for(u();i.length>0;){const{error:c,done:f,value:h}=await i[0];if(i.shift(),c)throw c;if(f)return;u(),h!==M&&(yield h)}}}}const M=Symbol("skip");function gt({engine:n,template:e,value:t}={}){if(!e)return"";const r=n.init(t),s=/\{\{\s(.*?)\s\}\}/g;return e.replace(s,i=>{const a=r.pipe(i);return a==null?"":typeof a=="object"?JSON.stringify(a):a})}function _t({content:n,mapping:e}){let t=!1;typeof n=="object"&&n!==null&&(n=JSON.stringify(n),t=!0);const r=/\[\[\s*([^[\]]+?)\s*\]\]/g,s=n.replace(r,(i,a)=>{const o=a.trim();if(/^[\w.\-]+$/.test(o)){const l=o.split(".");let u=e;for(const c of l)if(c&&(u=u==null?void 0:u[c],u===void 0))break;if(u!==void 0)return u}return`<%= ${o} %>`});return t?JSON.parse(s):s}function wt(n,e={}){const{normalizeWhitespace:t=!0,removeNewlines:r=!1,trim:s=!0,preserveBasicWhitespace:i=!0,debug:a=!1}=e;if(typeof n!="string")return n;let o=n;if(a&&(console.log("Original input:",JSON.stringify(n)),console.log("Options:",{normalizeWhitespace:t,removeNewlines:r,trim:s,preserveBasicWhitespace:i})),i&&!r)if(a){const l=[];o=o.replace(/[\x00-\x08\v\f\x0E-\x1F\x7F-\x9F\u200B-\u200D\uFEFF\u202A-\u202E]/g,u=>(l.push({char:u,code:u.charCodeAt(0),hex:`0x${u.charCodeAt(0).toString(16).toUpperCase().padStart(4,"0")}`}),"")),l.length>0?(console.log("Phase 1 (preserve mode) - Removed characters:"),l.forEach(u=>{console.log(` - Character: ${JSON.stringify(u.char)}, Code: ${u.code}, Hex: ${u.hex}`)}),console.log(`Removed ${l.length} control character(s)`)):console.log("Phase 1 (preserve mode) - No control characters found")}else o=o.replace(/[\x00-\x08\v\f\x0E-\x1F\x7F-\x9F\u200B-\u200D\uFEFF\u202A-\u202E]/g,"");else if(a){const l=[];o=o.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200D\uFEFF\u202A-\u202E]/g,u=>(l.push({char:u,code:u.charCodeAt(0),hex:`0x${u.charCodeAt(0).toString(16).toUpperCase().padStart(4,"0")}`}),"")),l.length>0?(console.log("Phase 1 (full removal mode) - Removed characters:"),l.forEach(u=>{console.log(` - Character: ${JSON.stringify(u.char)}, Code: ${u.code}, Hex: ${u.hex}`)}),console.log(`Removed ${l.length} control character(s)`)):console.log("Phase 1 (full removal mode) - No control characters found")}else o=o.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200D\uFEFF\u202A-\u202E]/g,"");return a&&console.log("After Phase 1:",JSON.stringify(o)),r&&(a?(o=o.replace(/[\r\n]+/g," "),console.log("Phase 2 - Converted newlines to spaces")):o=o.replace(/[\r\n]+/g," ")),t&&(a?(o=o.replace(/[ \t]+/g," "),console.log("Phase 2 - Normalized whitespace")):o=o.replace(/[ \t]+/g," ")),a&&console.log("After Phase 2:",JSON.stringify(o)),s&&(a?(o=o.trim(),console.log("Phase 3 - Trimmed leading/trailing whitespace")):o=o.trim()),a&&(console.log("Final result:",JSON.stringify(o)),console.log("--- Sanitization complete ---")),o}function we(n){return n&&typeof n.toString=="function"?n.toString():n}function At(n){const e=[...n];for(let t=e.length-1;t>=0;t--){const r=Math.floor(Math.random()*(t+1));[e[t],e[r]]=[e[r],e[t]]}return e}function P(n,e="_"){return n===null||typeof n>"u"||typeof n.toString>"u"?null:n.toString().trim().toUpperCase().replace("-",e).replace(" ",e)}function Cn(n,e=34){const t=$n(e);return Sn(n,t)}function Sn(n,e){const{byCode:t}=e;if(n===0)return t[0];let r="";const s=e.length;for(;n>0;)r=t[n%s]+r,n=Math.floor(n/s);return r}function $n(n){let e="9876543210ABCDEFGHJKLMNPQRSTUVWXYZ";return n===58&&(e="9876543210ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz"),On(e)}function vn(n){return Et(`${n}`).toLowerCase().split(" ").join("-")}function On(n){const e={},t={},{length:r}=n;let s;for(let i=0;i<r;i++)s=n[i],e[i]=s,t[s]=i;return{byCode:e,byChar:t,length:r}}function Rn(n,e){return typeof n!="string"||typeof e!="string"?!1:n.trim().toUpperCase()===e.trim().toUpperCase()}function Et(n){return n.replace(/\s+/g,"-").replace(/[.,\/#!$%\^&\*;:{}=\_`~()]/g,"")}function xn({len:n=16,pattern:e="a1"}={}){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZ",r="abcdefghijklmnopqrstuvwxyz",s="1234567890",i="~!@#$%^&*_+-=";let a="";e.includes("A")&&(a+=t),e.includes("a")&&(a+=r),e.includes("1")&&(a+=s),e.includes("#")&&(a+=i);const o=[...a];return[...new Array(n)].map(l=>o[Math.random()*o.length|0]).join``}function Tn(n){return(typeof n!="string"?n.toString():n).split("").reverse().join("")}function In(n){return typeof(n==null?void 0:n.toUpperCase)=="function"?n.toUpperCase():""}function Nn(n){let e=34,t=8;n===void 0||(typeof n=="number"?e=n:typeof n=="object"&&n!==null&&(e=n.base??e,t=n.len??t));const r=new Date().valueOf(),s=xn({len:t,pattern:"1"}),i=Tn(`${r}${s}`);return Cn(i,e)}function Dn(n){return n?n.trim().split(/\s+/).map((e,t)=>e?t===0?e.toLowerCase():e.charAt(0).toUpperCase()+e.slice(1).toLowerCase():"").join(""):""}function Mn(n){return n?n.trim().toLowerCase():""}function jn(n){return/[^\w\s]|_/g.test(n.replace(/_/g,""))?null:n.replace(/([a-z])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/[\s\-\.]+/g,"_").toUpperCase().replace(/^_+|_+$/g,"").replace(/_{2,}/g,"_")}const ee={getCssClass:vn,isSame:Rn,punctuationless:Et,safeToUpperCase:In,setCode:Nn,toCamelCase:Dn,toLowerCase:Mn,toScreamingSnakeCase:jn};function Ae(n,e){n.add({meta:{active:{type:Boolean,default:!0},created:{type:Number},creator:{type:String},deleted:{type:Boolean,default:!1},modified:{type:Number},owner:{type:String}}}),n.pre("save",function(t){this.meta.modified=Date.now(),t()}),n.index({"meta.active":1,"meta.deleted":1},{name:"tracking_status_index",background:!0,partialFilterExpression:{"meta.active":!0,"meta.deleted":!1}})}function bt(n,e){n.path("meta")||Ae(n),n.add({metadata:[{type:Object}],remarks:[{type:Object}],tenantCode:{type:String,required:!0}}),n.index({tenantCode:1},{name:"tenant_core_index",background:!0}),n.indexes().some(s=>s.name==="tenant_status_index")||n.index({tenantCode:1,_type:1},{name:"tenant_status_index",background:!0,partialFilterExpression:{_type:"Tenant","meta.active":!0,"meta.deleted":!1}})}const kn=Object.freeze(Object.defineProperty({__proto__:null,authorize:Me,calculateAge:je,changeCreatorOwner:le,concatStringByArray:z,convertString:rt,convertTimestampToString:st,detectControlCharacters:it,displayName:ot,downloadFileByUrl:lt,escapeRegex:ct,expressHelper:ft,extractEmails:dt,formatDate:ce,generalPost:ht,getObjectByArr:ye,getValidation:E,getValueByKeys:g,groupArrayByKey:mt,init:O,initFromArray:K,initOnlyValidFromArray:Q,isConvertibleToNumber:Y,mergeArraysByKey:pt,objectHelper:b,pMap:_e,pMapIterable:yt,pMapSkip:M,pReduce:Z,padZeros:ge,printControlCharReport:at,renderByTemplate:gt,replacePlaceholders:_t,sanitizeText:wt,setId:we,shuffleArray:At,stringFormatter:P,stringHelper:ee,tenantPlugin:bt,trackingPlugin:Ae},Symbol.toStringTag,{value:"Module"}));class Ct{constructor(e){e=e||{},this.expiration=e.expiration||null,this.s3Client=e.s3Client||null,this.getIdToken=e.getIdToken,this.region=e.region||"ap-east-1",this.roleArn=e.roleArn,this.roleSessionName=e.roleSessionName||"web-identity-session",this.durationSession=e.durationSession||3600,this.awsClientSts=e.awsClientSts,this.awsClientS3=e.awsClientS3}static dummyData(){return{getIdToken:()=>"mock-web-identity-token",roleArn:"arn:aws:iam::846252828949:role/oidcS3Jccpa",awsClientSts:{STSClient:class{},AssumeRoleWithWebIdentityCommand:class{}},awsClientS3:{S3Client:class{},PutObjectCommand:class{},GetObjectCommand:class{},DeleteObjectCommand:class{}}}}static init(e={}){if(e instanceof this)return e;try{const t=new this(e);return t.isValid?t:null}catch{return null}}get isExpired(){if(!this.expiration)return!0;const e=new Date,t=1*60*1e3;return e>=new Date(this.expiration.getTime()-t)}get isValid(){if(!this.getIdToken)throw new Error("Missing required configuration: getIdToken function");if(!this.roleArn)throw new Error("Missing required configuration: roleArn");if(!this.awsClientSts)throw new Error("Missing required AWS awsClientSts client configuration");if(!this.awsClientSts.STSClient)throw new Error("Missing STSClient in AWS awsClientSts client configuration");if(!this.awsClientSts.AssumeRoleWithWebIdentityCommand)throw new Error("Missing AssumeRoleWithWebIdentityCommand in AWS awsClientSts client configuration");if(!this.awsClientS3)throw new Error("Missing required AWS awsClientS3 client configuration");const e=["S3Client","PutObjectCommand","GetObjectCommand","DeleteObjectCommand"];for(const t of e)if(!this.awsClientS3[t])throw new Error(`Missing ${t} in AWS awsClientS3 client configuration`);return!0}async refreshCredentials(){try{if(!await this.getIdToken())throw new Error("getIdToken function returned empty or invalid token");const s=(await new this.awsClientSts.STSClient({region:this.region}).send(new this.awsClientSts.AssumeRoleWithWebIdentityCommand({RoleArn:this.roleArn,RoleSessionName:this.roleSessionName,WebIdentityToken:await this.getIdToken(),DurationSeconds:this.durationSession}))).Credentials;if(!s)throw new Error("No credentials returned from awsClientSts");return this.expiration=s.Expiration,this.s3Client=new this.awsClientS3.S3Client({region:this.region,credentials:{accessKeyId:s.AccessKeyId,secretAccessKey:s.SecretAccessKey,sessionToken:s.SessionToken}}),this}catch(e){throw new Error(`Failed to refresh credentials: ${e.message}`)}}async getS3Client(){return(this.isExpired||!this.s3Client)&&await this.refreshCredentials(),this.s3Client}async putObject(e){try{const t=await this.getS3Client(),r=new this.awsClientS3.PutObjectCommand(e);await t.send(r);const s=e.Key.split("/");return{url:`https://s3.${this.region}.amazonaws.com/${e.Bucket}/${e.Key}`,filename:s.pop(),folder:e.Bucket,subFolders:s}}catch(t){throw new Error(`Failed to put object: ${t.message}`)}}async getObject(e){try{const t=await this.getS3Client(),r=new this.awsClientS3.GetObjectCommand(e),s=await t.send(r);return{body:s.Body,contentType:s.ContentType,lastModified:s.LastModified,contentLength:s.ContentLength}}catch(t){throw new Error(`Failed to get object: ${t.message}`)}}async deleteObject(e){try{const t=await this.getS3Client(),r=new this.awsClientS3.DeleteObjectCommand(e);return await t.send(r),!0}catch(t){throw new Error(`Failed to delete object: ${t.message}`)}}}const ue="_";class v extends A{static init(e={}){if(e instanceof this)return e;const t=new this({...e,key:P(e.key,ue)});return t.isValid?t:null}static get _classname(){return"Metadata"}static mapToKeyValue(e=[],t="key",r="value"){return Array.isArray(e)?e.reduce((s,i)=>{if(i&&typeof i=="object"){const a=b.get(i,t),o=b.get(i,r);if(a!=null){const l=o!==void 0?ee.toScreamingSnakeCase(String(o)):"";s.push(this.init({key:a,value:l}))}}return s},[]):[]}static merge(e,t){return(t||[]).map(r=>{const s=e.find(i=>Ne(i.key,r.key));return s?s.value=Fn(r.value,s.value):e.push(r),r}),e}static sameKey(e,t){return Ne(e.key,t)}}function Ne(n,e){return P(n,ue)===P(e,ue)}function Fn(n,e){return n===void 0?e:Array.isArray(n)&&Array.isArray(e)?[...new Set([...n,...e])]:typeof n=="object"&&typeof e=="object"&&!Array.isArray(n)&&!Array.isArray(e)?{...n,...e}:e}class H{constructor(e={}){var s,i,a,o,l,u;e=e||{};const t=e._id||e.id;this.id=we(t),this._type=e._type||"TrackedEntity";const r=Date.now();this.meta={active:((s=e.meta)==null?void 0:s.active)??e.active??!0,created:((i=e.meta)==null?void 0:i.created)??(e.created?new Date(e.created).getTime():r),creator:((a=e.meta)==null?void 0:a.creator)??e.creator??"",deleted:((o=e.meta)==null?void 0:o.deleted)??e.deleted??!1,modified:((l=e.meta)==null?void 0:l.modified)??(e.modified?new Date(e.modified).getTime():r),owner:((u=e.meta)==null?void 0:u.owner)??e.owner??""}}static dummyData(){const e=Date.now();return{meta:{active:!0,deleted:!1,created:e,creator:"creator",modified:e,owner:"owner"}}}static get _classname(){return"TrackedEntity"}static get _superclass(){return"TrackedEntity"}static init(e={}){return O(this,e)}static initFromArray(e=[]){return K(this,e)}static initOnlyValidFromArray(e=[]){return Q(this,e)}get __valid(){return{}}get isValid(){return!!this}get active(){var e;return((e=this.meta)==null?void 0:e.active)??this.active}get created(){var e;return((e=this.meta)==null?void 0:e.created)??this.created}get creator(){var e;return((e=this.meta)==null?void 0:e.creator)??this.creator}get deleted(){var e;return((e=this.meta)==null?void 0:e.deleted)??this.deleted}get modified(){var e;return((e=this.meta)==null?void 0:e.modified)??this.modified}get owner(){var e;return((e=this.meta)==null?void 0:e.owner)??this.owner}changeCreatorOwner({source:e,target:t}){return le(this,{source:e,target:t}).setModified()}delete(){return this.setDeleted()}setActive(){return this.meta?this.meta.active=!0:this.active=!0,this}setDeleted(){return this.meta?this.meta.deleted=!0:this.deleted=!0,this}setModified(){const e=Date.now();return this.meta?this.meta.modified=e:this.modified=e,this}setOwner(e){return e?(this.meta?this.meta.owner=e:this.owner=e,this):this}unsetActive(){return this.meta?this.meta.active=!1:this.active=!1,this}unsetDeleted(){return this.meta?this.meta.deleted=!1:this.deleted=!1,this}update(e){const t=this.constructor.ALLOWED_META_PROPS,r={...this.meta};return e.meta&&t.forEach(s=>{e.meta.hasOwnProperty(s)&&(r[s]=e.meta[s])}),t.forEach(s=>{e.hasOwnProperty(s)&&(r[s]=e[s])}),JSON.stringify(this.meta)!==JSON.stringify(r)&&(this.meta=r),this.setModified()}}$e(H,"ALLOWED_META_PROPS",["active","deleted","owner"]);class St extends H{constructor(e){e=e||{},super(e),this.id=e.id,this.body=e.body,this.data=e.data,this.dirty=e.dirty,this.metadata=v.initOnlyValidFromArray(e.metadata),this.remarks=A.initOnlyValidFromArray(e.remarks),this.threadID=e.threadID,this.title=e.title}static get _classname(){return"PushEnvelope"}static get _superclass(){return"PushEnvelope"}static init(e={}){return O(this,e)}get _classname(){return"PushEnvelope"}get _superclass(){return"PushEnvelope"}get isValid(){return super.isValid&&this.data}}const _={trace:{weight:10,name:"TRACE"},debug:{weight:20,name:"DEBUG"},info:{weight:30,name:"INFO"},warn:{weight:40,name:"WARN"},error:{weight:50,name:"ERROR"},critical:{weight:60,name:"CRITICAL"},alert:{weight:70,name:"ALERT"},emergency:{weight:80,name:"EMERGENCY"}};class Ee{constructor(e={}){e=e||{},this.data=e.data,this.level=e.level,this.timestamp=e.timestamp,this.stackTrace=Pn(e),this.name=e.name??"",this.zone=e.zone}toString(){return`[${this.logName(this)}] ${this.serialize(this)}
|
|
10
|
+
${this.stackTrace||""}
|
|
11
|
+
${this.zone||""}`}logName(){let e=`${this.timestamp}`;return this.level.name&&(e+=`>${this.level.name}`),this.name&&(e+=`>${this.name}`),e}serialize(){var e;return this.data instanceof Error||typeof((e=this.data)==null?void 0:e.message)<"u"?this.data.message:this.data===null?"null":this.data===void 0?"undefined":typeof this.data=="object"?JSON.stringify(this.data):this.data.toString()}}function Pn(n){var e;return n.stackTrace?n.stackTrace:n.data instanceof Error||typeof((e=n.data)==null?void 0:e.stack)<"u"?n.data.stack:null}let ie;class j{constructor(e={}){const{level:t}=e;this._level=t??_.debug,this._handlers=new Map}static getInstance(e){return ie||(ie=new j(e)),ie}setLevel(e){return this._level=e,this}addHandler(e){return e instanceof j&&this._handlers.set(e.constructor,e),this}removeHandler(e){return this._handlers.delete(e),this}receive({record:e}){var t,r;((t=e.level)==null?void 0:t.weight)<((r=this._level)==null?void 0:r.weight)||(this._handlers.forEach(s=>{s.receive({record:e})}),this.logBody(e))}logBody(e){}trace(e,t){return this._log({level:_.trace,object:t,options:e})}debug(e,t){return this._log({level:_.debug,object:t,options:e})}info(e,t){return this._log({level:_.info,object:t,options:e})}warn(e,t){return this._log({level:_.warn,object:t,options:e})}error(e,t){return this._log({level:_.error,object:t,options:e})}critical(e,t){return this._log({level:_.critical,object:t,options:e})}_log({level:e,object:t,options:r}){typeof t>"u"&&(t=r,r="");const s=Date.now(),i=new Ee({data:t,level:e,timestamp:s,stackTrace:(t==null?void 0:t.stack)??(r==null?void 0:r.stack)??null,name:r??""});return this.receive({record:i})}}class $t extends j{constructor(e={}){const{format:t}=e;super(e),this.format=t}logBody(e){const t=e.logName(),r=this.format?this.format(e):e.serialize();switch(e.level){case _.error:case _.critical:case _.alert:case _.emergency:console.error(`[${t}] ${r}`,e.stackTrace||"");break;case _.warn:console.warn(`[${t}] ${r}`,e.stackTrace||"");break;case _.info:console.error(`[${t}] ${r}`,e.stackTrace||"");break;case _.debug:console.error(`[${t}] ${r}`,e.stackTrace||"");break;default:console.error(`[${t}] ${r}`,e.stackTrace||"")}}}const q={debug:{name:"DEBUG"},production:{name:"PRODUCTION"}};function vt(n){const e=n.toLowerCase();return q[e]?q[e]:null}const Ln=["attributes","ref"];class L{constructor(e={}){e=e||{},this.attributes=A.initOnlyValidFromArray(e.attributes),this.ref=e.ref||{}}static get _classname(){return"QMeta"}static get _superclass(){return"QMeta"}static init(e={}){return e instanceof L?e:new L(e)}addAttribute(e){const t=A.init(e);if(!t)throw new Error("invalid meta attribute");return this.attributes.push(t),this}update(e){return Object.keys(e).forEach(t=>{Ln.includes(t)&&(t==="attributes"?this[t]=A.initOnlyValidFromArray(e[t]):this[t]=e[t])}),this}}class G{constructor(e){e=e||{};const{_Actor:t}=e._constructor||{};this._Actor=t,this._actor=e._actor,this.actorCode=typeof e=="number"?null:e.actorCode||null,this.timestamp=typeof e=="number"?e:e.timestamp||null}static get _classname(){return"ActionRecord"}static get _superclass(){return"ActionRecord"}static dummyData(){return{timestamp:new Date().valueOf()}}static init(e={}){return O(this,e)}get _classname(){return"ActionRecord"}get _superclass(){return"ActionRecord"}get actor(){return this._Actor&&typeof this._Actor.init=="function"?this._Actor.init(this._actor):this._actor}get isValid(){return!!this.timestamp}update(e){return typeof e=="number"?(this.timestamp=e,this):(Object.keys(e).forEach(t=>{this[t]=e[t]}),this)}}const Vn=["_ActionRecord","created"];class be{constructor(e){e=e||{};const{_ActionRecord:t}=e._constructor||{};this._ActionRecord=t&&t._superclass===G._superclass?t:G,this.created=this._ActionRecord.init(e.created||{timestamp:new Date().valueOf()})}static get _classname(){return"Status"}static get _superclass(){return"Status"}static dummyData(){return{}}static init(e={}){return O(this,e)}static initFromArray(e=[]){return K(this,e)}static initOnlyValidFromArray(e=[]){return Q(this,e)}get _classname(){return"Status"}get _superclass(){return"Status"}get isCreated(){var e;return((e=this.created)==null?void 0:e.timestamp)!==null}get isValid(){return!!this}setValue(e,t,r){const s=e||Date.now();return this[r]=this[r]instanceof this._ActionRecord?this[r].update({actorCode:t,timestamp:s}):this._ActionRecord.init({actorCode:t,timestamp:s}),this}update(e){return Object.keys(e).forEach(t=>{Vn.includes(t)||(this[t]=this[t]instanceof this._ActionRecord?this[t].update(e[t]):this._ActionRecord.init(e[t]))}),this}}class Ot extends be{constructor(e){e=e||{},super(e),this.archived=this._ActionRecord.init(e.archived),this.completed=this._ActionRecord.init(e.completed),this.discarded=this._ActionRecord.init(e.discarded),this.drafted=this._ActionRecord.init(e.drafted)}static get _classname(){return"StatusDocument"}get _classname(){return"StatusDocument"}get isArchived(){var e;return((e=this.created)==null?void 0:e.timestamp)!==null}get isCompleted(){var e;return((e=this.completed)==null?void 0:e.timestamp)!==null}get isDiscarded(){var e;return((e=this.discarded)==null?void 0:e.timestamp)!==null}get isDrafted(){var e;return((e=this.drafted)==null?void 0:e.timestamp)!==null}get isValid(){return super.isValid}setArchived(e,t){return this.setValue(e,t,"archived")}setCompleted(e,t){return this.setValue(e,t,"completed")}setDiscarded(e,t){return this.setValue(e,t,"discarded")}setDrafted(e,t){return this.setValue(e,t,"drafted")}}class Rt extends H{constructor(e={}){e=e||{},super(e),this._type=e._type||"TenantAwareEntity",this._tenant=e._tenant,this.metadata=v.initOnlyValidFromArray(e.metadata),this.remarks=A.initOnlyValidFromArray(e.remarks),this.tenantCode=e.tenantCode}static dummyData(){return{...super.dummyData(),metadata:[],remarks:[],tenantCode:"tenantCode"}}static get _classname(){return"TenantAwareEntity"}static get _superclass(){return"TenantAwareEntity"}get __valid(){return{...super.__valid,tenantCode:this.tenantCode}}get isValid(){return super.isValid&&!!this.tenantCode}insertOrUpdateMetadata(e,t){return this.metadata=v.insertOrUpdateRecord(this.metadata,e,t),this}getMetadata(){return this.metadata}getMetadataByKey(e){return v.foundByKey(this.metadata,e)}getMetadataValueByKey(e){const t=this.getMetadataByKey(e);return t?t.value:null}getMetadataValueByKeys(e,t){if(!Array.isArray(e))return null;if(t=t||this.metadata,e.length===0)return t;const r=e.shift(),s=v.getMetadataValueByKeyAsArray(t,r);return this.getMetadataValueByKeys(e,s)}getMetadataValueByKeyAsArray(e){return v.getMetadataValueByKeyAsArray(this.metadata,e)}getRemarks(){return this.remarks}getRemarkByKey(e){return A.foundByKey(this.remarks,e)}getRemarksValueByKey(e){const t=this.getRemarkByKey(e);return t?t.value:null}getTenantCode(){return this.tenantCode}update(e){return e.metadata&&Array.isArray(e.metadata)&&(this.metadata=v.initOnlyValidFromArray(e.metadata)),e.remarks&&Array.isArray(e.remarks)&&(this.remarks=A.initOnlyValidFromArray(e.remarks)),super.update(e)}}class xt{static get _classname(){return"UniqueKeyGenerator"}static get _superclass(){return"UniqueKeyGenerator"}static makeFormatter({fieldName:e,format:t,options:r}){switch(t){case"set_code":return De(e);default:return De(e)}}static makeGenerator(e){const t=e.map(r=>this.makeFormatter(r));return async r=>await Z(t,async(i,a)=>{const o=await a(r);return Object.assign(i,o)},r)}}function De(n,e){return async(t={})=>t[n]?{}:{[n]:ee.setCode()}}class V{constructor(e={}){this.blockUI=e.blockUI??!1,this.callback=e.callback??null,this.data=e.data??null,this.event=e.event??null,this.reloadPage=e.reloadPage??!1,this.sessionId=e.sessionId??null,this.timeout=e.timeout??3e4}static get _classname(){return"WebAppRequest"}static get _superclass(){return"WebAppRequest"}static init(e){if(e instanceof V)return e;const t=new V(e);return t.isValid?t:null}static dummyData(){return{data:null,sessionId:"sessionId"}}get isValid(){return!!this.sessionId}getId(){try{return this.sessionId}catch{return null}}}const Tt={EXCUTE_EVENT_ERROR:"EXCUTE_EVENT_ERROR",NOT_FOUND:"NOT_FOUND",SERVER_ERROR:"SERVER_ERROR",TIMEOUT:"TIMEOUT",UNAUTHORIZED:"UNAUTHORIZED",VALIDATION_ERROR:"VALIDATION_ERROR"};class k{constructor(e={}){this.code=e.code??null,this.message=e.message??"",this.timestamp=e.timestamp??null}static init(e){if(e instanceof k)return e;const t=new k(e);return t.isValid?t:null}get isValid(){return!!this.code}}class B{constructor(e={}){this.data=e.data??null,this.errorDetail=k.init(e.errorDetail),this.sessionId=e.sessionId??null,this.success=e.success??!1}static get _classname(){return"WebAppResponse"}static get _superclass(){return"WebAppResponse"}static init(e){if(e instanceof B)return e;const t=new B(e);return t.isValid?t:null}static dummyData(){return{data:null,errorDetail:null,sessionId:"sessionId",success:!1}}get isValid(){return!!this.sessionId}getId(){try{return this.sessionId}catch{return null}}}const Bn=Object.freeze(Object.defineProperty({__proto__:null,ActionRecord:G,ApiResponse:he,AwsStsS3Client:Ct,ConsoleLog:$t,ERROR_CODES:Tt,ErrorDetail:k,KeyValueObject:A,LogRecord:Ee,Metadata:v,PushEnvelope:St,QLog:j,QLogEnv:q,QLogLevel:_,QMeta:L,Repo:X,Service:me,Status:be,StatusDocument:Ot,TemplateCompiler:de,TenantAwareEntity:Rt,TrackedEntity:H,UniqueKeyGenerator:xt,WebAppRequest:V,WebAppResponse:B,getQLogEnv:vt,makeApiResponse:I,makeService:pe},Symbol.toStringTag,{value:"Module"})),Un={...kn,...Bn};exports.ActionRecord=G;exports.ApiResponse=he;exports.AwsStsS3Client=Ct;exports.ConsoleLog=$t;exports.ERROR_CODES=Tt;exports.ErrorDetail=k;exports.KeyValueObject=A;exports.LogRecord=Ee;exports.Metadata=v;exports.PushEnvelope=St;exports.QLog=j;exports.QLogEnv=q;exports.QLogLevel=_;exports.QMeta=L;exports.Repo=X;exports.Service=me;exports.Status=be;exports.StatusDocument=Ot;exports.TemplateCompiler=de;exports.TenantAwareEntity=Rt;exports.TrackedEntity=H;exports.UniqueKeyGenerator=xt;exports.WebAppRequest=V;exports.WebAppResponse=B;exports.authorize=Me;exports.calculateAge=je;exports.changeCreatorOwner=le;exports.concatStringByArray=z;exports.convertString=rt;exports.convertTimestampToString=st;exports.default=Un;exports.detectControlCharacters=it;exports.displayName=ot;exports.downloadFileByUrl=lt;exports.escapeRegex=ct;exports.expressHelper=ft;exports.extractEmails=dt;exports.formatDate=ce;exports.generalPost=ht;exports.getObjectByArr=ye;exports.getQLogEnv=vt;exports.getValidation=E;exports.getValueByKeys=g;exports.groupArrayByKey=mt;exports.init=O;exports.initFromArray=K;exports.initOnlyValidFromArray=Q;exports.isConvertibleToNumber=Y;exports.makeApiResponse=I;exports.makeService=pe;exports.mergeArraysByKey=pt;exports.objectHelper=b;exports.pMap=_e;exports.pMapIterable=yt;exports.pMapSkip=M;exports.pReduce=Z;exports.padZeros=ge;exports.printControlCharReport=at;exports.renderByTemplate=gt;exports.replacePlaceholders=_t;exports.sanitizeText=wt;exports.setId=we;exports.shuffleArray=At;exports.stringFormatter=P;exports.stringHelper=ee;exports.tenantPlugin=bt;exports.trackingPlugin=Ae;
|
|
12
|
+
//# sourceMappingURL=q-utilities.cjs.map
|