@stoker-platform/node-client 0.5.101 → 0.5.102
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/bundle.cjs +2 -2
- package/dist/bundle.js +10 -10
- package/package.json +1 -1
package/dist/bundle.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));let c=require("lodash/isEqual.js");c=s(c,1);let l=require("lodash/merge.js");l=s(l,1);let u=require("lodash/set.js");u=s(u,1);let d=require("lodash/cloneDeep.js");d=s(d,1);let f=require("firebase-admin/app"),p=require("firebase-admin/firestore"),m=require("node:url"),h=require("cross-spawn");h=s(h,1);let g=require("firebase-admin/database"),_=require("firebase-admin/auth");var v=e=>!!e&&!Array.isArray(e),y=(e,t)=>!e.access||!v(e.access)&&e.access.includes(t),b=(e,t)=>{if(v(e.access))return t.fieldAccessGroups?.[e.access.group]},x=e=>{let t={};return Object.keys(e.fieldAccessGroups||{}).forEach(e=>{t[e]=[]}),e.fields.forEach(e=>{if(v(e.access)){let{group:n}=e.access;t[n]&&t[n].push(e)}}),t},S=(e,t,n,r)=>{if(!n)return!0;if(n.Role&&!e.applicableRoles.includes(n.Role))return!1;let i=n.collections?.[t],a=[];if(e.collectionAuth!==void 0&&a.push(!!i?.auth===e.collectionAuth),e.roles&&a.push(!!n.Role&&e.roles.includes(n.Role)),e.claims&&a.push(Object.entries(e.claims).every(([e,t])=>{let i=r?.[e];return i===void 0&&e===`role`&&(i=n.Role),Array.isArray(t)?t.some(e=>e===i):i===t})),e.restrictions){let{recordOwner:t,recordUser:n,recordProperty:r,restrictEntities:o}=e.restrictions;a.push((t===void 0||!!i?.recordOwner?.active===t)&&(n===void 0||!!i?.recordUser?.active===n)&&(r===void 0||!!i?.recordProperty?.active===r)&&(o===void 0||!!i?.restrictEntities===o))}return a.length===0?!1:e.match===`all`?a.every(Boolean):a.some(Boolean)},C=(e,t,n,r)=>{let i=b(e,t);return i?S(i,t.labels.collection,n,r):!1},w=e=>!!e.auth,T=(e,t)=>{if(t?.operations)return t.operations.includes(e)},E=(e,t,n,r)=>t?t.Role?v(e.access)?!n||!r?!1:C(e,n,t,r):e.access?.includes(t.Role):!1:!0,D=(e,t,n,r)=>e===!0?!1:Array.isArray(e)?e.includes(t.Role):typeof e==`object`&&e?!n||!r?!1:S(e,n,t,r):!0,O=(e,t,n,r)=>t?t.Role?D(e.restrictCreate,t,n,r):!1:!0,k=(e,t,n,r)=>t?t.Role?D(e.restrictUpdate,t,n,r):!1:!0,A=(e,t,n,r)=>{let{labels:i}=e;return n.collections&&T(`Update`,n.collections[i.collection])&&(!t.access||E(t,n,e,r))&&k(t,n,i.collection,r)&&!(e.auth&&!n.collections?.[i.collection].auth&&[`Enabled`,`Role`,`Name`,`Email`,`Photo_URL`].includes(t.name))},j=(e,t)=>e.filter(e=>e.name===t)[0],M=e=>[`OneToOne`,`OneToMany`,`ManyToOne`,`ManyToMany`].includes(e.type),ee=(e,t)=>{let n={Record_Owner:`recordOwner`,Record_User:`recordUser`,Record_Property:`recordProperty`},r=[],{labels:i,access:a}=e,{attributeRestrictions:o}=a,s=t.collections?.[i.collection];return o?.forEach(e=>{`roles`in e&&e.roles.forEach(i=>{let a=s?.[n[e.type]];i.role===t.Role&&(!i.assignable||a?.active)&&r.push(e)})}),r},te=(e,t)=>{let n=[],{labels:r,access:i}=e,{entityRestrictions:a}=i,o=t.collections?.[r.collection];return a?.restrictions?.forEach(e=>{`roles`in e&&e.roles.forEach(r=>{r.role===t.Role&&(!a.assignable?.includes(t.Role)||o?.restrictEntities)&&n.push(e)})}),n},ne=(e,t,n)=>{let r=[],{access:i}=e,{entityRestrictions:a}=i;return a?.parentFilters?.forEach(i=>{if(!i.roles.some(e=>e.role===n.Role))return;let a=i.collectionField,o=j(e.fields,a);if(!M(o))throw Error(`PERMISSION_DENIED`);let s=n.collections?.[o.collection],c=t.collections[o.collection].access.entityRestrictions;if(!c)throw Error(`PERMISSION_DENIED`);let l=c.restrictions?.find(e=>e.type===i.type&&e.roles.some(e=>e.role===n.Role));if(!l)throw Error(`PERMISSION_DENIED`);l.roles.forEach(e=>{e.role===n.Role&&(!c.assignable?.includes(n.Role)||s?.restrictEntities)&&r.push({parentFilter:i,parentRestriction:l})})}),r},N=(e,t,n,r)=>{let i=Object.values(t.collections),{labels:a}=e,o=[];for(let e of i){let{fields:t}=e;for(let i of t)if(!(i.access&&!E(i,n,e,r))&&n.Role&&M(i)&&i.collection===a.collection&&i.dependencyFields)for(let e of i.dependencyFields)!o.find(t=>t.field===e.field)&&e.roles.includes(n.Role)&&o.push(e)}return o},re=(e,t,n,r,i,a,o)=>{let{fields:s}=t,c=i.collections?.[t.labels.collection],l=!0;if(!c&&!o){l=!1;return}let u=ee(t,i),d=te(t,i),f=ne(t,n,i);u?.filter(e=>e.type===`Record_Owner`).forEach(t=>{`operations`in t&&t.operations&&!t.operations.includes(e)||a.Created_By!==r&&(l=!1)}),u?.filter(e=>e.type===`Record_User`).forEach(t=>{`operations`in t&&t.operations&&!t.operations.includes(e)||a[`${j(s,t.collectionField).name}_Array`]?.includes(i.Doc_ID)||(l=!1)}),u?.filter(e=>e.type===`Record_Property`).forEach(t=>{if(`operations`in t&&t.operations&&!t.operations.includes(e))return;let n=j(s,t.propertyField),r=t.roles.find(e=>e.role===i.Role);n.type===`Array`?r.values?.some(e=>a[n.name].includes(e))||(l=!1):r.values?.includes(a[n.name])||(l=!1)});let p=!0,m=!1;d?.filter(e=>e.type===`Individual`).forEach(()=>{m=!0,c?.individualEntities?.includes(a.id)||(p=!1)});let h=!0,g=!1;if(d?.filter(e=>e.type===`Parent`).forEach(e=>{g=!0;let t=j(s,e.collectionField);c?.parentEntities?.some(e=>a[`${t.name}_Array`].includes(e))||(h=!1)}),d?.filter(e=>e.type===`Parent_Property`).forEach(e=>{g=!0;let t=j(s,e.collectionField),n=j(s,e.propertyField);Object.entries(c?.parentPropertyEntities||{}).some(e=>{let[r,i]=e;return r===a[n.name]&&a[`${t.name}_Array`].some(e=>i.includes(e))})||(h=!1)}),m&&g){if(!(p||h)){l=!1;return}}else if(!p||!h){l=!1;return}let _=!0,v=!1;f?.filter(e=>e.parentFilter.type===`Individual`).forEach(e=>{v=!0;let{parentFilter:t}=e,n=j(s,t.collectionField),r=i.collections?.[n.collection];if(!r){l=!1;return}r.individualEntities?.some(e=>a[`${n.name}_Array`].includes(e))||(_=!1)});let y=!0,b=!1;if(f?.filter(e=>e.parentFilter.type===`Parent`).forEach(e=>{b=!0;let{parentFilter:t}=e,n=j(s,t.collectionField),r=j(s,t.parentCollectionField),o=i.collections?.[n.collection];if(!o){l=!1;return}o.parentEntities?.some(e=>a[`${r.name}_Array`].includes(e))||(y=!1)}),f?.filter(e=>e.parentFilter.type===`Parent_Property`).forEach(e=>{b=!0;let{parentFilter:t}=e,n=j(s,t.collectionField),r=j(s,t.parentPropertyField),o=j(s,t.parentCollectionField),c=i.collections?.[n.collection];if(!c){l=!1;return}Object.entries(c.parentPropertyEntities||{}).some(e=>{let[t,n]=e;return t===a[r.name]&&a[`${o.name}_Array`].some(e=>n.includes(e))})||(y=!1)}),v&&b){if(!(_||y)){l=!1;return}}else if(!_||!y){l=!1;return}return l},ie=(e,t,n,r,i,a)=>{let{labels:o}=t,s=i.collections?.[o.collection],c=!0;if(!s||!i.Role)return c=!1,c;T(e,s)||(c=!1);let l=te(t,i)?.filter(e=>e.type===`Individual`).length>0;return e===`Create`&&l&&(c=!1),re(e,t,n,r,i,a)||(c=!1),c},ae=(e,t,n)=>{let{labels:r}=e,i=[];for(let e of Object.values(t.collections)){let t=n?.collections?.[e.labels.collection];t&&e.parentCollection===r.collection&&(!n||T(`Read`,t))&&i.push(e)}return i},oe=(e,t)=>{let n=!0,r=``;return Object.keys(t).forEach(e=>{if(![`Doc_ID`,`Role`,`Collection`,`Enabled`,`collections`].includes(e)){n=!1,r=`Permissions object must contain Doc_ID, Role, Collection, Enabled, and collections`;return}}),t.collections?(Object.keys(t.collections).forEach(i=>{if(!Object.keys(e.collections).includes(i)){r=`Collection ${i} not found in schema`,n=!1;return}let a=e.collections[i],o=t.collections?.[i];if(o){if(!o.operations){r=`Collection ${i} does not have operations`,n=!1;return}if(!Object.keys(o).every(e=>[`operations`,`auth`,`restrictEntities`,`individualEntities`,`parentEntities`,`parentPropertyEntities`,`recordProperty`,`recordUser`,`recordOwner`].includes(e))){r=`Collection ${i} has invalid properties`,n=!1;return}if(!o.operations.every(e=>[`Read`,`Create`,`Update`,`Delete`].includes(e))){r=`Collection ${i} has invalid operations`,n=!1;return}if(o.auth&&(typeof o.auth!=`boolean`||!a.auth)){r=`Collection ${i} has invalid auth value`,n=!1;return}if(o.restrictEntities&&!a.access.entityRestrictions?.restrictions){r=`Collection ${i} has invalid restrictEntities value`,n=!1;return}Object.entries(o).forEach(([o,s])=>{if(o!==`operations`&&o!==`auth`&&o!==`restrictEntities`){let c;o===`recordOwner`?c=`Record_Owner`:o===`recordUser`?c=`Record_User`:o===`recordProperty`?c=`Record_Property`:o===`individualEntities`?c=`Individual`:o===`parentEntities`?c=`Parent`:o===`parentPropertyEntities`&&(c=`Parent_Property`);let l=a.access.attributeRestrictions?.filter(e=>e.type===c&&e.roles.some(e=>e.role===t.Role)),u=a.access.entityRestrictions?.restrictions?.filter(e=>e.type===c&&e.roles.some(e=>e.role===t.Role));if(a.access.entityRestrictions?.assignable&&!(Array.isArray(a.access.entityRestrictions.assignable)&&a.access.entityRestrictions.assignable.every(t=>e.config.roles.includes(t)))){r=`Collection ${i} has invalid entity restrictions assignable value`,n=!1;return}if(l?.length||u?.length){if(o===`Record_Owner`||o===`Record_User`||o===`Record_Property`){let e=Object.keys(s);if(e.length!==1||e[0]!==`active`||typeof s.active!=`boolean`){r=`Collection ${i} has invalid attribute restriction value`,n=!1;return}}if(o===`Individual`&&!Array.isArray(s)){r=`Collection ${i} has invalid individual entities value`,n=!1;return}if(o===`Parent`){let t=Object.keys(s);if(!(t.length===1&&Object.keys(e.collections).includes(t[0])&&Array.isArray(s[t[0]]))){r=`Collection ${i} has invalid parent entities value`,n=!1;return}}if(o===`Parent_Property`){let t=Object.keys(s);if(!(t.length===1&&Object.keys(e.collections).includes(t[0])&&typeof s[t[0]]==`object`&&s[t[0]]!==null)){r=`Collection ${i} has invalid parent property entities value`,n=!1;return}}}else{r=`Collection ${i} has invalid restriction type ${o}`,n=!1;return}}})}}),r&&console.error(`PERMISSION_DENIED: ${r}`),n):n},se=(e,t,n)=>{let r=!0,i=``;Object.values(e.collections).filter(e=>e.auth).forEach(e=>{let n=t.collections?.[e.labels.collection],a=e.access.auth,o=t.Role;if(n?.auth&&!a?.roles.includes(o)){i=`Record cannot have auth access to collection`,r=!1;return}if(a?.roles.includes(o)&&!a.assignable?.includes(o)&&!n?.auth){i=`Record is missing required auth access to collection`,r=!1;return}});for(let a of Object.values(e.collections)){let{labels:e,access:o,fields:s}=a,{operations:c,attributeRestrictions:l,entityRestrictions:u}=o,d=c.assignable,f=t.collections?.[e.collection],p=[`read`,`create`,`update`,`delete`];if(d!==!0&&!(typeof d==`object`&&d.includes(n))?p.forEach(t=>{let a=t.charAt(0).toUpperCase()+t.slice(1);if(t!==`assignable`){let s=!!o.operations[t]?.includes(n),c=!!f?.operations.includes(a);if(!s&&c){i=`Collection ${e.collection} has excess ${t} operation for role ${n}`,r=!1;return}if(s&&!c){i=`Collection ${e.collection} has missing ${t} operation for role ${n}`,r=!1;return}}}):p.forEach(t=>{let a=t.charAt(0).toUpperCase()+t.slice(1);if(t!==`assignable`){let s=!!o.operations[t]?.includes(n),c=!!f?.operations.includes(a);if(!s&&c){i=`Collection ${e.collection} has excess ${t} operation for role ${n}`,r=!1;return}}}),!l&&!u||(l?.forEach(a=>{for(let o of a.roles)if(o.role===n&&!o.assignable){if(a.type===`Record_Owner`&&!t.collections?.[e.collection]?.recordOwner?.active){i=`Collection ${e.collection} is missing Record_Owner restriction for role ${n}`,r=!1;return}if(a.type===`Record_User`&&!t.collections?.[e.collection]?.recordUser?.active){i=`Collection ${e.collection} is missing Record_User restriction for role ${n}`,r=!1;return}if(a.type===`Record_Property`&&!t.collections?.[e.collection]?.recordProperty?.active){i=`Collection ${e.collection} is missing Record_Property restriction for role ${n}`,r=!1;return}}}),u?.assignable?.includes(n)))continue;let m=!1;if(u?.restrictions?.forEach(a=>{for(let o of a.roles)if(o.role===n){if(m=!0,a.type===`Individual`&&!t.collections?.[e.collection]?.individualEntities){i=`Collection ${e.collection} is missing individual entities`,r=!1;return}if(a.type===`Parent`){if(!M(j(s,a.collectionField))){r=!1;return}if(!t.collections?.[e.collection]?.parentEntities){i=`Collection ${e.collection} is missing parent entities`,r=!1;return}}if(a.type===`Parent_Property`){let n=j(s,a.collectionField);if(!M(n)){r=!1;return}if(!t.collections?.[e.collection]?.parentPropertyEntities?.[n.collection]){i=`Collection ${e.collection} is missing parent property entities`,r=!1;return}}}}),m&&!t.collections?.[e.collection]?.restrictEntities){i=`Collection ${e.collection} must have restrictEntities set to true`,r=!1;return}}return i&&console.error(`PERMISSION_DENIED: ${i}`),r},ce=(e,t,n,r,i,a,o,s,l)=>{let{access:u}=t,{permissionWriteRestrictions:d}=u,f=!0,p=``,m=d?.filter(e=>r===e.userRole);return m?.length&&!m.some(e=>e.recordRole===i)||e===`update`&&o.User_ID&&m?.length&&!m.some(e=>e.recordRole===s)?(p=`User ${r} does not have write access to record with role ${i}`,f=!1,f):(d?.forEach(t=>{r===t.userRole&&t.recordRole===i&&e!==`delete`&&a&&Object.keys(n.collections).forEach(n=>{let i=a.collections?.[n],o=l?.collections?.[n];if(!(e===`update`&&(0,c.default)(i,o))&&i){let a=t.collections.some(e=>e.collection===n);if(!a){p=`User ${r} does not have write access to collection ${n}`,f=!1;return}if(a){let a=t.collections.find(e=>e.collection===n);if(!(i.operations.every(e=>a.operations.includes(e))||e===`update`&&(0,c.default)(i.operations,o?.operations))){p=`User ${r} does not have write access to all included operations for collection ${n}`,f=!1;return}if(!a.auth&&i.auth&&!(e===`update`&&(0,c.default)(i.auth,o?.auth))){p=`User ${r} does not have write access to auth for collection ${n}`,f=!1;return}let s={recordOwner:`Record_Owner`,recordUser:`Record_User`,recordProperty:`Record_Property`};if(Object.keys(s).forEach(t=>{let l=s[t];if(a.attributeRestrictions?.includes(l)&&!(i[t]?.active||e===`update`&&(0,c.default)(i[t],o?.[t]))){p=`User ${r} does not have write access to attribute restriction ${t} for collection ${n}`,f=!1;return}}),a.restrictEntities&&!i.restrictEntities&&!(e===`update`&&(0,c.default)(i.restrictEntities,o?.restrictEntities))){p=`User ${r} does not have write access to restrictEntities for collection ${n}`,f=!1;return}}}})}),p&&console.error(`PERMISSION_DENIED: ${p}`),f)},le=(e,t,n,r)=>{let i=!0,a=``;return Object.values(e.collections).forEach(e=>{let o=n.collections?.[e.labels.collection],s=r?.collections?.[e.labels.collection],c=t?.collections?.[e.labels.collection];if(o?.auth&&!s?.auth&&!w(c)){a=`User does not have auth access to collection ${e.labels.collection}`,i=!1;return}for(let t of o?.operations||[])if(!s?.operations.includes(t)&&(!T(`Read`,c)||!T(t,c))){a=`User does not have ${t.toLowerCase()} access to collection ${e.labels.collection}`,i=!1;return}if(!o?.recordOwner&&s?.recordOwner&&c?.recordOwner){a=`User does not have write access to recordOwner for collection ${e.labels.collection}`,i=!1;return}if(!o?.recordUser&&s?.recordUser&&c?.recordUser){a=`User does not have write access to recordUser for collection ${e.labels.collection}`,i=!1;return}if(!o?.recordProperty&&s?.recordProperty&&c?.recordProperty){a=`User does not have write access to recordProperty for collection ${e.labels.collection}`,i=!1;return}if(!o?.restrictEntities&&s?.restrictEntities&&c?.restrictEntities){a=`User does not have write access to restrictEntities for collection ${e.labels.collection}`,i=!1;return}}),a&&console.error(`PERMISSION_DENIED: ${a}`),i},ue=(e,t,n,r,i,a,o,s,c,l,u)=>{let{labels:d}=r,f=!0,p=``;if(!t.Role)return p=`Record does not have a role`,f=!1,f;if(e===`update`&&!l)return p=`Original record is required for update operations`,f=!1,f;if(e===`update`&&a&&u===`update`&&s&&!c)return p=`Original permissions are required for this operation`,f=!1,f;if(a){if(!o?.Role)return p=`Current user does not have a role`,f=!1,f;if(!ce(e,r,i,o.Role,t.Role,s,l,l?.Role,c))return f=!1,f;if(e===`update`&&u!==`delete`&&l?.User_ID&&t.User_ID!==l.User_ID)return p=`User ID does not match original user ID`,f=!1,f;if(e===`update`&&l&&l.User_ID&&a===l.User_ID&&(s||t.Role!==l.Role||t.Enabled!==void 0&&t.Enabled!==l.Enabled))return p=`User cannot update their own record`,f=!1,f;if(e===`delete`&&a===t.User_ID)return p=`User cannot delete their own record`,f=!1,f}return e===`delete`||u===`delete`||!s?f:s.Role?(oe(i,s)||(f=!1),s.Collection&&s.Collection!==d.collection?(p=`Permissions collection does not match record collection`,f=!1,f):s.Role===t.Role?s.Enabled!==void 0&&!!s.Enabled!=!!t.Enabled?(p=`Permissions enabled state does not match record enabled state`,f=!1,f):s.Doc_ID&&s.Doc_ID!==n?(p=`Permissions doc ID does not match record doc ID`,f=!1,f):!se(i,s,s.Role)||a&&o&&c&&!le(i,o,s,c)?(f=!1,f):(p&&console.error(`PERMISSION_DENIED: ${p}`),f):(p=`Permissions role does not match record role`,f=!1,f)):(p=`Permissions do not have a role`,f=!1,f)},de=(e,t,n,r,i,a,o,s)=>{let{labels:c,fields:l}=n,u=a?.collections?.[c.collection],d=!0;if(i&&!u)throw Error(`PERMISSION_DENIED`);i&&!T(`Create`,u)&&(d=!1),i&&!ie(`Create`,n,r,i,a,e)&&(d=!1),n.auth&&o&&(i&&!w(u)&&(d=!1),ue(`create`,e,t,n,r,i,a,o)||(d=!1));for(let t of l){let r=e[t.name];t.access&&!E(t,a,n,s)&&r!==void 0&&(d=!1),r!==void 0&&!O(t,a,c.collection,s)&&(d=!1)}if(!d)throw Error(`PERMISSION_DENIED`)},fe=e=>e&&(e._methodName===`deleteField`||e.constructor.name===`DeleteTransform`),pe=e=>{for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&(fe(e[t])?delete e[t]:typeof e[t]==`object`&&e[t]!==null&&pe(e[t]))},me=(e,t,n,r,i,a,o,s,c,l,u)=>{let{labels:d,fields:f}=r,p=o?.collections?.[d.collection],m={...t,...e};pe(m);let h=!0,g=``;if(a&&!p)throw Error(`PERMISSION_DENIED`);a&&!T(`Update`,p)&&(h=!1,g=`Authenticated user does not have Update access to this collection`),a&&(!ie(`Update`,r,i,a,o,t)||!ie(`Update`,r,i,a,o,m))&&(h=!1,g=`Authenticated user does not have Update access to this document`),a&&r.softDelete&&m[r.softDelete.archivedField]!==t[r.softDelete.archivedField]&&!T(`Delete`,p)&&(h=!1,g=`Authenticated user does not have Delete or Restore access to this document`),s&&(a&&!w(p)&&(h=!1,g=`Authenticated user does not have Auth access for this collection`),ue(`update`,m,n,r,i,a,o,c,l,t,s)||(g=`Authenticated user does not have sufficient write access for this record`,h=!1));for(let t of f){let n=e[t.name];t.access&&!E(t,o,r,u)&&n!==void 0&&(g=`Authenticated user does not have access to field ${t.name}`,h=!1),n!==void 0&&!k(t,o,d.collection,u)&&(g=`Authenticated user does not have Update access to field ${t.name}`,h=!1)}if(!h)throw g&&console.error(`PERMISSION_DENIED: ${g}`),Error(`PERMISSION_DENIED`)},he=(e,t,n,r,i,a)=>{let{labels:o}=n,s=a.collections?.[o.collection],c=!0;if(!s||(T(`Delete`,s)||(c=!1),ie(`Delete`,n,r,i,a,e)||(c=!1),n.auth&&e.User_ID&&(w(s)||(c=!1),ue(`delete`,e,t,n,r,i,a)||(c=!1)),!c))throw Error(`PERMISSION_DENIED`)},ge=async(e,t,n,r,i)=>{let{labels:a}=t,o=i.collections?.[a.collection],s=!0;if(!o){s=!1;return}if(T(`Read`,o)||(s=!1),ie(`Read`,t,n,r,i,e)||(s=!1),!s)throw Error(`PERMISSION_DENIED`)},_e=async(e,t,n,r,i)=>{let{labels:a}=t,o=i.collections?.[a.collection],s=!0;if(!o){s=!1;return}if(T(`Read`,o)||(s=!1),e.forEach(e=>{ie(`Read`,t,n,r,i,e)||(s=!1)}),!s)throw Error(`PERMISSION_DENIED`)},ve=(e,t,n)=>{let{access:r}=e;return r.operations[n]?.includes(t)},ye=(e,t,n)=>{let{access:r}=t,{entityRestrictions:i}=r;if(i?.restrictions){for(let t of i.restrictions)if(t.roles?.some(t=>t.role===e)&&!(`singleQuery`in t&&t.singleQuery))return`${t.type} entity restriction`}if(i?.parentFilters)for(let r of i.parentFilters){if(!r.roles.some(t=>t.role===e))continue;let i=j(t.fields,r.collectionField);if(!M(i))throw Error(`PERMISSION_DENIED`);let a=n.collections[i.collection].access.entityRestrictions?.restrictions?.find(t=>t.type===r.type&&t.roles.some(t=>t.role===e));if(!a||a.type!==r.type)throw Error(`PERMISSION_DENIED`);if(!(`singleQuery`in a&&a.singleQuery))return`${r.type} parent filter`}return!0},be=(e,t,n,r,i)=>{let a={};for(let o of e){let e=t[o].default({sdk:n,utils:r,context:i});for(let t in e)t!==`custom`&&t!==`admin`&&t!==`fields`&&delete e[t];for(let t of e.fields)for(let e in t)e!==`custom`&&e!==`admin`&&e!==`name`&&e!==`formula`&&delete t[e];a[o]=e}return a},xe=(e,t)=>t.fields.filter(t=>t.name===e.name)[0],Se={global:{},collections:{}},Ce=(e,t)=>e&&typeof e==`function`?t?e(...t):e():e,P=async(e,t)=>{let n=e;return e&&(typeof e==`function`||typeof e.then==`function`)&&(n=t?await e(...t):await e()),n},we=async(e,t,n,r)=>{for(let e of t)if(e===`__proto__`||e===`constructor`||e===`prototype`)throw Error(`Invalid config path: prototype pollution keys are not allowed`);let i=Se,a=!0;for(let e of t){if(e===void 0||i[e]===void 0){a=!1;break}i=i[e]}if(i&&a&&!r)return i;let o,s=e,c=!0;o=t[0]===`collections`?t.slice(2):t.slice(1);for(let e of o){if(e===void 0||s[e]===void 0){c=!1;break}s=s[e]}let d;if(c&&(d=await P(s,n)),d){let e=Se,n={};for(let r=0;r<t.length;r++){let i=t[r];if(i!==void 0){if(i===`__proto__`||i===`constructor`||i===`prototype`)throw Error(`Invalid config path: prototype pollution keys are not allowed`);r===t.length-1?(0,u.default)(n,t.join(`.`),d):(e[i]||={},e=e[i])}}(0,l.default)(Se,n)}return d},Te=(e,t,n)=>{let r=Object.values(n.collections),{labels:i}=t,a=!1;for(let t of r){let{fields:n}=t;for(let t of n)if(M(t)&&t.collection===i.collection&&t.dependencyFields)for(let n of t.dependencyFields)n.field===e.name&&(a=!0)}return a},Ee=(e,t)=>{let n=Object.values(t.collections),{labels:r}=e,i={};return n.forEach(e=>{let{labels:t,fields:n}=e;n.forEach(e=>{M(e)&&e.collection===r.collection&&e.dependencyFields&&e.dependencyFields.forEach(e=>{i[e.field]||={},i[e.field][t.collection]||=[],i[e.field][t.collection]=i[e.field][t.collection].concat(e.roles),i[e.field][t.collection]=[...new Set(i[e.field][t.collection])]})})}),i},De=e=>JSON.stringify(e.map(e=>e.name)),Oe=[`id`,`Collection_Path`,`Last_Write_At`,`Last_Save_At`,`Last_Write_By`,`Last_Write_App`,`Last_Write_Connection_Status`,`Last_Write_Version`,`Created_At`,`Saved_At`,`Created_By`],ke=()=>Oe.map(e=>{let t=``,n;switch(e){case`id`:t=`String`;break;case`Collection_Path`:t=`Array`;break;case`Created_At`:t=`Timestamp`;break;case`Saved_At`:t=`Timestamp`;break;case`Created_By`:t=`String`;break;case`Last_Write_At`:t=`Timestamp`;break;case`Last_Save_At`:t=`Timestamp`;break;case`Last_Write_By`:t=`String`;break;case`Last_Write_App`:t=`String`;break;case`Last_Write_Connection_Status`:t=`String`,n=[`Online`,`Offline`];break;case`Last_Write_Version`:t=`Number`}let r={name:e,type:t,required:!0};return n&&(r.values=n),r}),Ae=(e,t)=>{let n=[],{access:r,fields:i}=e,{attributeRestrictions:a,entityRestrictions:o}=r,s=ke();return a&&a.forEach(e=>{if(e.roles.some(e=>e.role===t))switch(e.type){case`Record_Owner`:n.push(j(s,`Created_By`));break;case`Record_User`:n.push(j(i,e.collectionField));break;case`Record_Property`:n.push(j(i,e.propertyField))}}),o&&(o.restrictions?.forEach(e=>{if(e.roles.some(e=>e.role===t))switch(e.type){case`Individual`:n.push(j(s,`id`));break;case`Parent`:n.push(j(i,e.collectionField));break;case`Parent_Property`:n.push(j(i,e.collectionField)),n.push(j(i,e.propertyField))}}),o.parentFilters&&o.parentFilters.forEach(e=>{if(e.roles.some(e=>e.role===t))switch(e.type){case`Individual`:n.push(j(i,e.collectionField));break;case`Parent`:n.push(j(i,e.parentCollectionField));break;case`Parent_Property`:n.push(j(i,e.parentCollectionField)),n.push(j(i,e.parentPropertyField))}})),[...new Set(n)]},je=(e,t)=>{let n=[],{fields:r,roleSystemFields:i,preloadCache:a,queries:o}=e,s=ke();return n.push({name:`Collection_Path`,type:`Array`,required:!0}),r.forEach(e=>{y(e,t)&&n.push(e)}),i?.filter(e=>(!e.roles||e.roles.includes(t))&&e.field!==`Collection_Path`).forEach(e=>{n.push(j(s,e.field))}),a?.range&&a.range.fields.forEach(e=>{Oe.includes(e)&&n.push(j(s,e))}),o?.forEach(e=>{let i=j(r.concat(s),e.field);(!e.roles||e.roles.includes(t))&&i&&y(i,t)&&Oe.includes(e.field)&&n.push(j(s,e.field))}),Ae(e,t).forEach(e=>{Oe.includes(e.name)&&n.push(j(s,e.name))}),[...new Set(n)]},Me=(e,t,n)=>{let r=[],{fields:i,preloadCache:a}=t,o=ke(),s=new Set,c=Ee(t,n);return Object.entries(c).map(([t,n])=>{e.name===t&&Object.values(n).forEach(e=>{e.forEach(e=>{s.add(e)})})}),s.forEach(e=>{r.push(...Ae(t,e))}),a?.range&&a.range.fields.forEach(e=>{Oe.includes(e)?r.push(j(o,e)):Array.from(s).some(t=>y(j(i,e),t))&&r.push(j(i,e))}),[...new Set(r)]},Ne=(e,t,n)=>{let r=[],{fields:i,softDelete:a}=t;r.push({name:`Collection_Path`,type:`Array`,required:!0}),r.push({name:`id`,type:`String`,required:!0});let o=[],s=Ee(t,n);if(Object.values(s).forEach(r=>{Object.keys(r).forEach(r=>{n.collections[r].fields.forEach(n=>{M(n)&&n.collection===t.labels.collection&&n.dependencyFields?.some(t=>t.field===e.name)&&n.constraints&&n.constraints.forEach(e=>{o.push(e[0])})})})}),o.forEach(e=>{r.push(j(i,e))}),a){let e=j(i,a.archivedField);e&&r.push(e)}return r.push(...Me(e,t,n)),[...new Set(r)]},Pe=(e,t,n)=>{let r=t.fieldAccessGroups?.[e]?.applicableRoles||[];return n.roles.filter(e=>r.includes(e))},Fe=(e,t)=>`${e}-${t}`,Ie=(e,t,n)=>{if(!t.fieldAccessGroups?.[e])return[];let r=Pe(e,t,n);if(r.length===0)return[];let i=[],{fields:a,softDelete:o,preloadCache:s,roleSystemFields:c,queries:l}=t,u=ke();i.push({name:`Collection_Path`,type:`Array`,required:!0}),i.push({name:`id`,type:`String`,required:!0});let d=x(t)[e]||[];if(i.push(...d),o){let e=j(a,o.archivedField);e&&!d.includes(e)&&i.push(e)}s?.range&&s.range.fields.forEach(e=>{Oe.includes(e)?i.push(j(u,e)):r.some(t=>y(j(a,e),t))&&i.push(j(a,e))}),c?.filter(e=>e.field!==`Collection_Path`&&r.some(t=>!e.roles||e.roles.includes(t))).forEach(e=>{i.push(j(u,e.field))}),l?.forEach(e=>{let t=j(a.concat(u),e.field);t&&r.some(n=>(!e.roles||e.roles.includes(n))&&y(t,n))&&i.push(t)});for(let e of r)i.push(...Ae(t,e));return[...new Set(i)]},Le=(e,t)=>{let{preloadCache:n}=e,r=new Set;for(let i of t.config.roles){if(!ve(e,i,`read`))continue;let t=je(e,i),a=!1;if(r.size===0)r.add({key:`1`,roles:[i],fields:t}),a=!0;else for(let e of r)t.length===e.fields.length&&t.every(t=>e.fields.some(e=>e.name===t.name))&&!!n?.roles.includes(i)==!!e.roles.every(e=>n?.roles.includes(e))&&(e.roles.push(i),a=!0);a||r.add({key:(r.size+1).toString(),roles:[i],fields:t})}return r},Re=(e,t,n)=>{let r=Le(t,n);for(let t of r.values())if(t.roles.includes(e))return t},ze=(e,t)=>{let{fields:n}=t,r=ke(),i=[];return[...n,...r.filter(e=>e.name!==`id`)].forEach(t=>{e?.fields.some(e=>e.name===t.name)||i.push(t)}),i},Be=(e,t,n)=>{let r={};return Object.values(e.collections).forEach(i=>{if(n&&!n.includes(i.labels.collection))return;let a=Le(i,e),o=Array.from(a);o.map(e=>(e.fields.forEach(n=>{t&&n.access&&!y(n,t.Role)&&(e.fields=e.fields.filter(e=>e.name!==n.name))}),e)),r[i.labels.collection]=new Set(o)}),r},Ve=e=>({Last_Write_At:e.Last_Write_At,Last_Write_By:e.Last_Write_By,Last_Write_Connection_Status:e.Last_Write_Connection_Status,Last_Write_Version:e.Last_Write_Version,Last_Write_App:e.Last_Write_App,Last_Save_At:e.Last_Save_At}),He=async(e,t,n)=>{if(t){let r=await P(t,[n]);if(r===!1)throw Error(`CANCELLED: Operation cancelled by ${e}`);return r}};async function F(e,t,n,r){let i=await He(e,n.custom?.[e],r);for(let t of n.fields)await He(e,t.custom?.[e],r);if(e!==`setEmbedding`&&(await He(e,t?.[e],r),e===`postWriteError`))return i}var Ue=(e,t,n,r,i,a,o,s,c,l)=>(e===`create`&&(n.Collection_Path=t,l||(n.Created_At=s),n.Saved_At=c,n.Created_By=o||`System`),n.Last_Write_App=i,l||(n.Last_Write_At=s),n.Last_Save_At=c,n.Last_Write_By=o||`System`,n.Last_Write_Connection_Status=a,n.Last_Write_Version=r.version,n),We=(e,t)=>{let{access:n,queries:r}=e,{serverReadOnly:i}=n,a=new Set;if(r)for(let e of r){let n=j(t,e.field);t.find(t=>t.name===e.field)&&M(n)&&[`OneToOne`,`OneToMany`].includes(n.type)&&a.add(n)}return t.forEach(e=>{M(e)&&[`OneToOne`,`OneToMany`].includes(e.type)&&e.sorting&&(typeof e.sorting==`boolean`||!e.sorting.roles?.every(e=>i?.includes(e)))&&a.add(e)}),a},Ge=(e,t)=>{let{access:n,recordTitleField:r}=e,{serverReadOnly:i}=n,a=new Set;return t.forEach(e=>{(r===e.name||e.sorting&&(typeof e.sorting==`boolean`||!e.sorting.roles?.every(e=>i?.includes(e))))&&e.type===`String`&&a.add(e)}),a},Ke=(e,t)=>{let n={Collection_Path:e.Collection_Path};if(e.deleted!==void 0&&(n.deleted=e.deleted),t)for(let r of t)e[r]!==void 0&&(n[r]=e[r]);return n},qe=(e,t,n)=>{let{fields:r}=e;r.forEach(e=>{if(M(e)){if(t[e.name]){if(fe(t[e.name]))t[`${e.name}_Array`]=t[e.name];else if(Object.keys(t[e.name]).forEach(n=>{let r=t[e.name][n];t[e.name][n]=Ke(r,e.includeFields)}),t[`${e.name}_Array`]=Object.keys(t[e.name]),e.includeFields)for(let r of e.includeFields){let i=n.collections[e.collection];Ge(i,[j(i.fields,r)]).size===1&&Object.keys(t[e.name]).forEach(n=>{t[e.name][n][r]?t[e.name][n][`${r}_Lowercase`]=t[e.name][n][r].toLowerCase():delete t[e.name][n][`${r}_Lowercase`]})}}else delete t[`${e.name}_Array`],delete t[`${e.name}_Single`]}}),We(e,r).forEach(e=>{if(t[e.name]){if(fe(t[e.name]))t[`${e.name}_Single`]=t[e.name];else{let n=t[`${e.name}_Array`]?.[0];if(n){let r=t[e.name][n]||{};t[`${e.name}_Single`]={id:n,...r}}}}})},Je=(e,t)=>{Ge(e,e.fields).forEach(e=>{t[e.name]?t[`${e.name}_Lowercase`]=t[e.name].toLowerCase():delete t[`${e.name}_Lowercase`]})},Ye=async(e,t,n,r,i)=>{let{fields:a}=t;for(let o of n.fields){let n=j(a,o.name);o.custom?.initialValue!==void 0&&(!n.access||E(n,r,t,i||{}))&&(e[o.name]=await P(o.custom.initialValue,[e]),Ge(t,[n]).size===1&&(e[`${o.name}_Lowercase`]=e[o.name].toLowerCase()))}for(let n of a)(!n.access||E(n,r,t,i||{}))&&(`autoIncrement`in n&&n.autoIncrement&&!e[n.name]&&(e[n.name]=`Pending`),!M(n)&&n.nullable&&e[n.name]===void 0&&(e[n.name]=null))},I;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(I||={});var Xe;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(Xe||={});var L=I.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),Ze=e=>{switch(typeof e){case`undefined`:return L.undefined;case`string`:return L.string;case`number`:return Number.isNaN(e)?L.nan:L.number;case`boolean`:return L.boolean;case`function`:return L.function;case`bigint`:return L.bigint;case`symbol`:return L.symbol;case`object`:return Array.isArray(e)?L.array:e===null?L.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?L.promise:typeof Map<`u`&&e instanceof Map?L.map:typeof Set<`u`&&e instanceof Set?L.set:typeof Date<`u`&&e instanceof Date?L.date:L.object;default:return L.unknown}},R=I.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]),Qe=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,I.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t={},n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};Qe.create=e=>new Qe(e);var $e=(e,t)=>{let n;switch(e.code){case R.invalid_type:n=e.received===L.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case R.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,I.jsonStringifyReplacer)}`;break;case R.unrecognized_keys:n=`Unrecognized key(s) in object: ${I.joinValues(e.keys,`, `)}`;break;case R.invalid_union:n=`Invalid input`;break;case R.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${I.joinValues(e.options)}`;break;case R.invalid_enum_value:n=`Invalid enum value. Expected ${I.joinValues(e.options)}, received '${e.received}'`;break;case R.invalid_arguments:n=`Invalid function arguments`;break;case R.invalid_return_type:n=`Invalid function return type`;break;case R.invalid_date:n=`Invalid date`;break;case R.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:I.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case R.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case R.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case R.custom:n=`Invalid input`;break;case R.invalid_intersection_types:n=`Intersection results could not be merged`;break;case R.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case R.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,I.assertNever(e)}return{message:n}},et=$e;function tt(){return et}var nt=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function z(e,t){let n=tt(),r=nt({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===$e?void 0:$e].filter(e=>!!e)});e.common.issues.push(r)}var rt=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return B;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return B;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}},B=Object.freeze({status:`aborted`}),it=e=>({status:`dirty`,value:e}),at=e=>({status:`valid`,value:e}),ot=e=>e.status===`aborted`,st=e=>e.status===`dirty`,ct=e=>e.status===`valid`,lt=e=>typeof Promise<`u`&&e instanceof Promise,V;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(V||={});var ut=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},dt=(e,t)=>{if(ct(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new Qe(e.common.issues);return this._error=t,this._error}}};function H(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var U=class{get description(){return this._def.description}_getType(e){return Ze(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Ze(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new rt,ctx:{common:e.parent.common,data:e.data,parsedType:Ze(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(lt(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ze(e)};return dt(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ze(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return ct(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>ct(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ze(e)},r=this._parse({data:e,path:n.path,parent:n});return dt(n,await(lt(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:R.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new hn({schema:this,typeName:W.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return gn.create(this,this._def)}nullable(){return _n.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yt.create(this)}promise(){return mn.create(this,this._def)}or(e){return Qt.create([this,e],this._def)}and(e){return nn.create(this,e,this._def)}transform(e){return new hn({...H(this._def),schema:this,typeName:W.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new vn({...H(this._def),innerType:this,defaultValue:t,typeName:W.ZodDefault})}brand(){return new xn({typeName:W.ZodBranded,type:this,...H(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new yn({...H(this._def),innerType:this,catchValue:t,typeName:W.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Sn.create(this,e)}readonly(){return Cn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},ft=/^c[^\s-]{8,}$/i,pt=/^[0-9a-z]+$/,mt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ht=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,gt=/^[a-z0-9_-]{21}$/i,_t=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,vt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,yt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,bt=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,xt,St=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ct=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,wt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Tt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Et=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Dt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ot=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,kt=RegExp(`^${Ot}$`);function At(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function jt(e){return RegExp(`^${At(e)}$`)}function Mt(e){let t=`${Ot}T${At(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Nt(e,t){return!!((t===`v4`||!t)&&St.test(e)||(t===`v6`||!t)&&wt.test(e))}function Pt(e,t){if(!_t.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function Ft(e,t){return!!((t===`v4`||!t)&&Ct.test(e)||(t===`v6`||!t)&&Tt.test(e))}var It=class e extends U{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==L.string){let t=this._getOrReturnCtx(e);return z(t,{code:R.invalid_type,expected:L.string,received:t.parsedType}),B}let t=new rt,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),z(n,{code:R.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),z(n,{code:R.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?z(n,{code:R.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&z(n,{code:R.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)yt.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:`email`,code:R.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)xt||=new RegExp(bt,`u`),xt.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:`emoji`,code:R.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)ht.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:`uuid`,code:R.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)gt.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:`nanoid`,code:R.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)ft.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:`cuid`,code:R.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)pt.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:`cuid2`,code:R.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)mt.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:`ulid`,code:R.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),z(n,{validation:`url`,code:R.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:`regex`,code:R.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),z(n,{code:R.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),z(n,{code:R.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),z(n,{code:R.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Mt(r).test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{code:R.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?kt.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{code:R.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?jt(r).test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{code:R.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?vt.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:`duration`,code:R.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Nt(e.data,r.version)||(n=this._getOrReturnCtx(e,n),z(n,{validation:`ip`,code:R.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Pt(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),z(n,{validation:`jwt`,code:R.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Ft(e.data,r.version)||(n=this._getOrReturnCtx(e,n),z(n,{validation:`cidr`,code:R.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Et.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:`base64`,code:R.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Dt.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:`base64url`,code:R.invalid_string,message:r.message}),t.dirty()):I.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:R.invalid_string,...V.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...V.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...V.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...V.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...V.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...V.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...V.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...V.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...V.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...V.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...V.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...V.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...V.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...V.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...V.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...V.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...V.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...V.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...V.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...V.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...V.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...V.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...V.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...V.errToObj(t)})}nonempty(e){return this.min(1,V.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};It.create=e=>new It({checks:[],typeName:W.ZodString,coerce:e?.coerce??!1,...H(e)});function Lt(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var Rt=class e extends U{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==L.number){let t=this._getOrReturnCtx(e);return z(t,{code:R.invalid_type,expected:L.number,received:t.parsedType}),B}let t,n=new rt;for(let r of this._def.checks)r.kind===`int`?I.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),z(t,{code:R.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),z(t,{code:R.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),z(t,{code:R.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Lt(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),z(t,{code:R.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),z(t,{code:R.not_finite,message:r.message}),n.dirty()):I.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,V.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,V.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,V.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,V.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:V.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:V.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:V.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:V.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:V.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:V.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:V.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:V.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:V.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:V.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&I.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};Rt.create=e=>new Rt({checks:[],typeName:W.ZodNumber,coerce:e?.coerce||!1,...H(e)});var zt=class e extends U{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==L.bigint)return this._getInvalidInput(e);let t,n=new rt;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),z(t,{code:R.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),z(t,{code:R.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),z(t,{code:R.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):I.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return z(t,{code:R.invalid_type,expected:L.bigint,received:t.parsedType}),B}gte(e,t){return this.setLimit(`min`,e,!0,V.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,V.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,V.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,V.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:V.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:V.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:V.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:V.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:V.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:V.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};zt.create=e=>new zt({checks:[],typeName:W.ZodBigInt,coerce:e?.coerce??!1,...H(e)});var Bt=class extends U{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==L.boolean){let t=this._getOrReturnCtx(e);return z(t,{code:R.invalid_type,expected:L.boolean,received:t.parsedType}),B}return at(e.data)}};Bt.create=e=>new Bt({typeName:W.ZodBoolean,coerce:e?.coerce||!1,...H(e)});var Vt=class e extends U{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==L.date){let t=this._getOrReturnCtx(e);return z(t,{code:R.invalid_type,expected:L.date,received:t.parsedType}),B}if(Number.isNaN(e.data.getTime()))return z(this._getOrReturnCtx(e),{code:R.invalid_date}),B;let t=new rt,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),z(n,{code:R.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),z(n,{code:R.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):I.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:V.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:V.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};Vt.create=e=>new Vt({checks:[],coerce:e?.coerce||!1,typeName:W.ZodDate,...H(e)});var Ht=class extends U{_parse(e){if(this._getType(e)!==L.symbol){let t=this._getOrReturnCtx(e);return z(t,{code:R.invalid_type,expected:L.symbol,received:t.parsedType}),B}return at(e.data)}};Ht.create=e=>new Ht({typeName:W.ZodSymbol,...H(e)});var Ut=class extends U{_parse(e){if(this._getType(e)!==L.undefined){let t=this._getOrReturnCtx(e);return z(t,{code:R.invalid_type,expected:L.undefined,received:t.parsedType}),B}return at(e.data)}};Ut.create=e=>new Ut({typeName:W.ZodUndefined,...H(e)});var Wt=class extends U{_parse(e){if(this._getType(e)!==L.null){let t=this._getOrReturnCtx(e);return z(t,{code:R.invalid_type,expected:L.null,received:t.parsedType}),B}return at(e.data)}};Wt.create=e=>new Wt({typeName:W.ZodNull,...H(e)});var Gt=class extends U{constructor(){super(...arguments),this._any=!0}_parse(e){return at(e.data)}};Gt.create=e=>new Gt({typeName:W.ZodAny,...H(e)});var Kt=class extends U{constructor(){super(...arguments),this._unknown=!0}_parse(e){return at(e.data)}};Kt.create=e=>new Kt({typeName:W.ZodUnknown,...H(e)});var qt=class extends U{_parse(e){let t=this._getOrReturnCtx(e);return z(t,{code:R.invalid_type,expected:L.never,received:t.parsedType}),B}};qt.create=e=>new qt({typeName:W.ZodNever,...H(e)});var Jt=class extends U{_parse(e){if(this._getType(e)!==L.undefined){let t=this._getOrReturnCtx(e);return z(t,{code:R.invalid_type,expected:L.void,received:t.parsedType}),B}return at(e.data)}};Jt.create=e=>new Jt({typeName:W.ZodVoid,...H(e)});var Yt=class e extends U{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==L.array)return z(t,{code:R.invalid_type,expected:L.array,received:t.parsedType}),B;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(z(t,{code:e?R.too_big:R.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(z(t,{code:R.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(z(t,{code:R.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new ut(t,e,t.path,n)))).then(e=>rt.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new ut(t,e,t.path,n)));return rt.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:V.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:V.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:V.toString(n)}})}nonempty(e){return this.min(1,e)}};Yt.create=(e,t)=>new Yt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:W.ZodArray,...H(t)});function Xt(e){if(e instanceof Zt){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=gn.create(Xt(r))}return new Zt({...e._def,shape:()=>t})}return e instanceof Yt?new Yt({...e._def,type:Xt(e.element)}):e instanceof gn?gn.create(Xt(e.unwrap())):e instanceof _n?_n.create(Xt(e.unwrap())):e instanceof rn?rn.create(e.items.map(e=>Xt(e))):e}var Zt=class e extends U{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=I.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==L.object){let t=this._getOrReturnCtx(e);return z(t,{code:R.invalid_type,expected:L.object,received:t.parsedType}),B}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof qt&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new ut(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof qt){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(z(n,{code:R.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new ut(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>rt.mergeObjectSync(t,e)):rt.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return V.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:V.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:W.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of I.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of I.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Xt(this)}partial(t){let n={};for(let e of I.objectKeys(this.shape)){let r=this.shape[e];n[e]=t&&!t[e]?r:r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of I.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof gn;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return dn(I.objectKeys(this.shape))}};Zt.create=(e,t)=>new Zt({shape:()=>e,unknownKeys:`strip`,catchall:qt.create(),typeName:W.ZodObject,...H(t)}),Zt.strictCreate=(e,t)=>new Zt({shape:()=>e,unknownKeys:`strict`,catchall:qt.create(),typeName:W.ZodObject,...H(t)}),Zt.lazycreate=(e,t)=>new Zt({shape:e,unknownKeys:`strip`,catchall:qt.create(),typeName:W.ZodObject,...H(t)});var Qt=class extends U{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new Qe(e.ctx.common.issues));return z(t,{code:R.invalid_union,unionErrors:n}),B}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new Qe(e));return z(t,{code:R.invalid_union,unionErrors:i}),B}}get options(){return this._def.options}};Qt.create=(e,t)=>new Qt({options:e,typeName:W.ZodUnion,...H(t)});var $t=e=>e instanceof ln?$t(e.schema):e instanceof hn?$t(e.innerType()):e instanceof un?[e.value]:e instanceof fn?e.options:e instanceof pn?I.objectValues(e.enum):e instanceof vn?$t(e._def.innerType):e instanceof Ut?[void 0]:e instanceof Wt?[null]:e instanceof gn?[void 0,...$t(e.unwrap())]:e instanceof _n?[null,...$t(e.unwrap())]:e instanceof xn||e instanceof Cn?$t(e.unwrap()):e instanceof yn?$t(e._def.innerType):[],en=class e extends U{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==L.object)return z(t,{code:R.invalid_type,expected:L.object,received:t.parsedType}),B;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(z(t,{code:R.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),B)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=$t(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:W.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...H(r)})}};function tn(e,t){let n=Ze(e),r=Ze(t);if(e===t)return{valid:!0,data:e};if(n===L.object&&r===L.object){let n=I.objectKeys(t),r=I.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=tn(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}if(n===L.array&&r===L.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=tn(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}return n===L.date&&r===L.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var nn=class extends U{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(ot(e)||ot(r))return B;let i=tn(e.value,r.value);return i.valid?((st(e)||st(r))&&t.dirty(),{status:t.value,value:i.data}):(z(n,{code:R.invalid_intersection_types}),B)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};nn.create=(e,t,n)=>new nn({left:e,right:t,typeName:W.ZodIntersection,...H(n)});var rn=class e extends U{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==L.array)return z(n,{code:R.invalid_type,expected:L.array,received:n.parsedType}),B;if(n.data.length<this._def.items.length)return z(n,{code:R.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),B;!this._def.rest&&n.data.length>this._def.items.length&&(z(n,{code:R.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new ut(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>rt.mergeArray(t,e)):rt.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};rn.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new rn({items:e,typeName:W.ZodTuple,rest:null,...H(t)})};var an=class e extends U{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==L.object)return z(n,{code:R.invalid_type,expected:L.object,received:n.parsedType}),B;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new ut(n,e,n.path,e)),value:a._parse(new ut(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?rt.mergeObjectAsync(t,r):rt.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof U?new e({keyType:t,valueType:n,typeName:W.ZodRecord,...H(r)}):new e({keyType:It.create(),valueType:t,typeName:W.ZodRecord,...H(n)})}},on=class extends U{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==L.map)return z(n,{code:R.invalid_type,expected:L.map,received:n.parsedType}),B;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new ut(n,e,n.path,[a,`key`])),value:i._parse(new ut(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return B;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return B;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};on.create=(e,t,n)=>new on({valueType:t,keyType:e,typeName:W.ZodMap,...H(n)});var sn=class e extends U{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==L.set)return z(n,{code:R.invalid_type,expected:L.set,received:n.parsedType}),B;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(z(n,{code:R.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(z(n,{code:R.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return B;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new ut(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:V.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:V.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};sn.create=(e,t)=>new sn({valueType:e,minSize:null,maxSize:null,typeName:W.ZodSet,...H(t)});var cn=class e extends U{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==L.function)return z(t,{code:R.invalid_type,expected:L.function,received:t.parsedType}),B;function n(e,n){return nt({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,tt(),$e].filter(e=>!!e),issueData:{code:R.invalid_arguments,argumentsError:n}})}function r(e,n){return nt({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,tt(),$e].filter(e=>!!e),issueData:{code:R.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof mn){let e=this;return at(async function(...t){let o=new Qe([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}{let e=this;return at(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new Qe([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new Qe([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:rn.create(t).rest(Kt.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||rn.create([]).rest(Kt.create()),returns:n||Kt.create(),typeName:W.ZodFunction,...H(r)})}},ln=class extends U{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};ln.create=(e,t)=>new ln({getter:e,typeName:W.ZodLazy,...H(t)});var un=class extends U{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return z(t,{received:t.data,code:R.invalid_literal,expected:this._def.value}),B}return{status:`valid`,value:e.data}}get value(){return this._def.value}};un.create=(e,t)=>new un({value:e,typeName:W.ZodLiteral,...H(t)});function dn(e,t){return new fn({values:e,typeName:W.ZodEnum,...H(t)})}var fn=class e extends U{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return z(t,{expected:I.joinValues(n),received:t.parsedType,code:R.invalid_type}),B}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return z(t,{received:t.data,code:R.invalid_enum_value,options:n}),B}return at(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};fn.create=dn;var pn=class extends U{_parse(e){let t=I.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==L.string&&n.parsedType!==L.number){let e=I.objectValues(t);return z(n,{expected:I.joinValues(e),received:n.parsedType,code:R.invalid_type}),B}if(this._cache||=new Set(I.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=I.objectValues(t);return z(n,{received:n.data,code:R.invalid_enum_value,options:e}),B}return at(e.data)}get enum(){return this._def.values}};pn.create=(e,t)=>new pn({values:e,typeName:W.ZodNativeEnum,...H(t)});var mn=class extends U{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==L.promise&&t.common.async===!1?(z(t,{code:R.invalid_type,expected:L.promise,received:t.parsedType}),B):at((t.parsedType===L.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};mn.create=(e,t)=>new mn({type:e,typeName:W.ZodPromise,...H(t)});var hn=class extends U{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===W.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{z(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return B;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?B:r.status===`dirty`||t.value===`dirty`?it(r.value):r});{if(t.value===`aborted`)return B;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?B:r.status===`dirty`||t.value===`dirty`?it(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?B:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?B:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`){if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ct(e))return B;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>ct(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):B)}I.assertNever(r)}};hn.create=(e,t,n)=>new hn({schema:e,typeName:W.ZodEffects,effect:t,...H(n)}),hn.createWithPreprocess=(e,t,n)=>new hn({schema:t,effect:{type:`preprocess`,transform:e},typeName:W.ZodEffects,...H(n)});var gn=class extends U{_parse(e){return this._getType(e)===L.undefined?at(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};gn.create=(e,t)=>new gn({innerType:e,typeName:W.ZodOptional,...H(t)});var _n=class extends U{_parse(e){return this._getType(e)===L.null?at(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};_n.create=(e,t)=>new _n({innerType:e,typeName:W.ZodNullable,...H(t)});var vn=class extends U{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===L.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};vn.create=(e,t)=>new vn({innerType:e,typeName:W.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...H(t)});var yn=class extends U{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return lt(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new Qe(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new Qe(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};yn.create=(e,t)=>new yn({innerType:e,typeName:W.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...H(t)});var bn=class extends U{_parse(e){if(this._getType(e)!==L.nan){let t=this._getOrReturnCtx(e);return z(t,{code:R.invalid_type,expected:L.nan,received:t.parsedType}),B}return{status:`valid`,value:e.data}}};bn.create=e=>new bn({typeName:W.ZodNaN,...H(e)});var xn=class extends U{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},Sn=class e extends U{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?B:e.status===`dirty`?(t.dirty(),it(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?B:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:W.ZodPipeline})}},Cn=class extends U{_parse(e){let t=this._def.innerType._parse(e),n=e=>(ct(e)&&(e.value=Object.freeze(e.value)),e);return lt(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};Cn.create=(e,t)=>new Cn({innerType:e,typeName:W.ZodReadonly,...H(t)}),Zt.lazycreate;var W;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(W||={});var wn=It.create,Tn=Rt.create;bn.create,zt.create;var En=Bt.create;Vt.create,Ht.create;var Dn=Ut.create;Wt.create;var G=Gt.create;Kt.create,qt.create,Jt.create;var On=Yt.create,kn=Zt.create;Zt.strictCreate;var An=Qt.create;en.create,nn.create,rn.create;var jn=an.create;on.create,sn.create,cn.create,ln.create;var Mn=un.create,Nn=fn.create;pn.create,mn.create,hn.create,gn.create,_n.create,hn.createWithPreprocess,Sn.create;var Pn=()=>G().refine(e=>e&&(e.seconds!==void 0&&e.nanoseconds!==void 0||e._seconds!==void 0&&e._nanoseconds!==void 0),{message:`Value is not a valid timestamp`}),Fn=()=>G().refine(e=>e&&(e._methodName===`serverTimestamp`||e.constructor.name===`ServerTimestampTransform`),{message:`Value is not a valid server timestamp`}),In=(e,t,n)=>{let r={};if(e.includeFields){let n=t.collections[e.collection];if(!n)return jn(G());e.includeFields.forEach(t=>{let i=n.fields.find(e=>e.name===t);if(!i)throw Error(`Field ${t} not found in collection ${e.collection}`);r[t]=zn(n,i),Ge(n,[i]).size===1&&(r[`${t}_Lowercase`]=zn(n,i,!0))})}let i={Collection_Path:On(wn()),...r};return n&&(i.id=wn().length(20)),kn(i)},Ln=(e,t)=>{let n=jn(In(e,t));return e.required||(n=n.optional()),n},Rn=e=>{let t=On(An([wn().length(20),wn().length(28)]));return[`OneToOne`,`OneToMany`].includes(e.type)?t=t.max(1):(e.min&&(t=t.min(e.min)),e.max&&(t=t.max(e.max)),e.length&&(t=t.length(e.length))),t=e.required?t.nonempty():t.optional(),t},zn=(e,t,n)=>{let{softDelete:r}=e,i=r?.timestampField,a;switch(t.type){case`String`:a=wn(),t.length&&(a=a.length(t.length)),t.minlength&&(a=a.min(t.minlength)),t.maxlength&&(a=a.max(t.maxlength)),t.email&&(a=a.email()),t.uuid&&(a=a.uuid()),t.url&&(a=a.url()),t.emoji&&(a=a.emoji()),t.ip&&(a=a.ip()),n&&(a=a.toLowerCase()),t.pattern&&(a=An([a.regex(new RegExp(t.pattern)),Mn(``)])),t.values&&(a=Nn(n?t.values.map(e=>e.toLowerCase()):t.values));break;case`Boolean`:a=En();break;case`Number`:t.autoIncrement?a=An([Mn(`Pending`),Tn().int()]):(a=Tn(),t.min&&(a=a.min(t.min)),t.max&&(a=a.max(t.max)),a=t.decimal?a.refine(e=>t.decimal?(e.toString().split(`.`)[1]?.length||0)<=t.decimal:!1,{message:`Value must have ${t.decimal} or fewer decimal places`}):a.int(),t.values&&(a=a.refine(e=>t.values?.includes(e),{message:`Value is not an allowed value`})));break;case`Timestamp`:t.name===i?a=G().refine(e=>e&&(e._methodName===`serverTimestamp`||e.constructor.name===`ServerTimestampTransform`||e.seconds!==void 0&&e.nanoseconds!==void 0||e._seconds!==void 0&&e._nanoseconds!==void 0),{message:`Value is not a valid timestamp`}):(a=Pn(),t.min&&(a=a.refine(e=>e.toMillis()>=t.min,{message:`Value is less than the minimum allowed value of ${t.min}`})),t.max&&(a=a.refine(e=>e.toMillis()<=t.max,{message:`Value is greater than the maximum allowed value of ${t.max}`})));break;case`Array`:a=On(G()),t.length&&(a=a.length(t.length)),t.minlength?a=a.min(t.minlength):t.required&&(a=a.nonempty()),t.maxlength&&(a=a.max(t.maxlength)),t.values&&(a=a.refine(e=>{let n=!0;return e.forEach(e=>{t.values&&!t.values.includes(e)&&(n=!1)}),n},{message:`Value is not an allowed value`}));break;case`Map`:a=jn(G()),t.required&&(a=a.refine(e=>e&&typeof e==`object`&&Object.keys(e).length>0,{message:`Value must have at least one object property`}));break;case`Embedding`:a=G()}return!M(t)&&t.nullable&&(a=a.nullable()),t.required||(a=a.optional()),a},Bn=(e,t,n)=>{let r={Collection_Path:On(wn()),Last_Write_App:wn(),Last_Write_At:Pn(),Last_Save_At:Fn(),Last_Write_By:An([wn().length(28),Mn(`System`)]),Last_Write_Connection_Status:Nn([`Online`,`Offline`]),Last_Write_Version:Tn().int(),id:wn().regex(RegExp(`^[a-zA-Z0-9]+$`)).length(20),Created_At:Pn(),Created_By:An([wn().length(28),Mn(`System`)])};e===`create`&&(r.Saved_At=Fn()),e===`update`&&(r.Saved_At=Pn(),r.Collection_Path=r.Collection_Path.optional(),r.id=r.id.optional(),r.Created_At=r.Created_At.optional(),r.Saved_At=r.Saved_At.optional(),r.Created_By=r.Created_By.optional());let i=We(t,t.fields),a=Array.from(i).map(e=>e.name);t.fields.forEach(e=>{M(e)?(r[e.name]=Ln(e,n),r[`${e.name}_Array`]=Rn(e),a.includes(e.name)&&(r[`${e.name}_Single`]=In(e,n,!0),e.required||(r[`${e.name}_Single`]=r[`${e.name}_Single`].optional())),e.length&&(r[e.name]=r[e.name].refine(t=>e.length&&t&&Object.keys(t).length===e.length,{message:`Value must contain ${e.length} item(s)`})),e.min&&(r[e.name]=r[e.name].refine(t=>e.min&&t&&Object.keys(t).length>=e.min,{message:`Value must contain at least ${e.min} item(s)`})),e.max&&(r[e.name]=r[e.name].refine(t=>e.max&&(!t||Object.keys(t).length<=e.max),{message:`Value must contain at most ${e.max} item(s)`}))):e.type!==`Computed`&&(r[e.name]=zn(t,e))}),Ge(t,t.fields).forEach(e=>{r[e.name]&&(r[`${e.name}_Lowercase`]=zn(t,e,!0))});let o=kn(r);return t.allowSchemalessFields?o.passthrough():o.strict()},Vn=class extends Error{},Hn=class extends Vn{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},Un=class extends Vn{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},Wn=class extends Vn{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},Gn=class extends Vn{},Kn=class extends Vn{constructor(e){super(`Invalid unit ${e}`)}},qn=class extends Vn{},Jn=class extends Vn{constructor(){super(`Zone is an abstract class`)}},K=`numeric`,Yn=`short`,Xn=`long`,Zn={year:K,month:K,day:K},Qn={year:K,month:Yn,day:K},$n={year:K,month:Yn,day:K,weekday:Yn},er={year:K,month:Xn,day:K},tr={year:K,month:Xn,day:K,weekday:Xn},nr={hour:K,minute:K},rr={hour:K,minute:K,second:K},ir={hour:K,minute:K,second:K,timeZoneName:Yn},ar={hour:K,minute:K,second:K,timeZoneName:Xn},or={hour:K,minute:K,hourCycle:`h23`},sr={hour:K,minute:K,second:K,hourCycle:`h23`},cr={hour:K,minute:K,second:K,hourCycle:`h23`,timeZoneName:Yn},lr={hour:K,minute:K,second:K,hourCycle:`h23`,timeZoneName:Xn},ur={year:K,month:K,day:K,hour:K,minute:K},dr={year:K,month:K,day:K,hour:K,minute:K,second:K},fr={year:K,month:Yn,day:K,hour:K,minute:K},pr={year:K,month:Yn,day:K,hour:K,minute:K,second:K},mr={year:K,month:Yn,day:K,weekday:Yn,hour:K,minute:K},hr={year:K,month:Xn,day:K,hour:K,minute:K,timeZoneName:Yn},gr={year:K,month:Xn,day:K,hour:K,minute:K,second:K,timeZoneName:Yn},_r={year:K,month:Xn,day:K,weekday:Xn,hour:K,minute:K,timeZoneName:Xn},vr={year:K,month:Xn,day:K,weekday:Xn,hour:K,minute:K,second:K,timeZoneName:Xn},yr=class{get type(){throw new Jn}get name(){throw new Jn}get ianaName(){return this.name}get isUniversal(){throw new Jn}offsetName(e,t){throw new Jn}formatOffset(e,t){throw new Jn}offset(e){throw new Jn}equals(e){throw new Jn}get isValid(){throw new Jn}},br=null,xr=class e extends yr{static get instance(){return br===null&&(br=new e),br}get type(){return`system`}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:t,locale:n}){return aa(e,t,n)}formatOffset(e,t){return la(this.offset(e),t)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type===`system`}get isValid(){return!0}},Sr=new Map;function Cr(e){let t=Sr.get(e);return t===void 0&&(t=new Intl.DateTimeFormat(`en-US`,{hour12:!1,timeZone:e,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,era:`short`}),Sr.set(e,t)),t}var wr={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function Tr(e,t){let n=e.format(t).replace(/\u200E/g,``),[,r,i,a,o,s,c,l]=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(n);return[a,r,i,o,s,c,l]}function Er(e,t){let n=e.formatToParts(t),r=[];for(let e=0;e<n.length;e++){let{type:t,value:i}=n[e],a=wr[t];t===`era`?r[a]=i:Y(a)||(r[a]=parseInt(i,10))}return r}var Dr=new Map,Or=class e extends yr{static create(t){let n=Dr.get(t);return n===void 0&&Dr.set(t,n=new e(t)),n}static resetCache(){Dr.clear(),Sr.clear()}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat(`en-US`,{timeZone:e}).format(),!0}catch{return!1}}constructor(t){super(),this.zoneName=t,this.valid=e.isValidZone(t)}get type(){return`iana`}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:t,locale:n}){return aa(e,t,n,this.name)}formatOffset(e,t){return la(this.offset(e),t)}offset(e){if(!this.valid)return NaN;let t=new Date(e);if(isNaN(t))return NaN;let n=Cr(this.name),[r,i,a,o,s,c,l]=n.formatToParts?Er(n,t):Tr(n,t);o===`BC`&&(r=-Math.abs(r)+1);let u=ta({year:r,month:i,day:a,hour:s===24?0:s,minute:c,second:l,millisecond:0}),d=+t,f=d%1e3;return d-=f>=0?f:1e3+f,(u-d)/6e4}equals(e){return e.type===`iana`&&e.name===this.name}get isValid(){return this.valid}},kr={};function Ar(e,t={}){let n=JSON.stringify([e,t]),r=kr[n];return r||(r=new Intl.ListFormat(e,t),kr[n]=r),r}var jr=new Map;function Mr(e,t={}){let n=JSON.stringify([e,t]),r=jr.get(n);return r===void 0&&(r=new Intl.DateTimeFormat(e,t),jr.set(n,r)),r}var Nr=new Map;function Pr(e,t={}){let n=JSON.stringify([e,t]),r=Nr.get(n);return r===void 0&&(r=new Intl.NumberFormat(e,t),Nr.set(n,r)),r}var Fr=new Map;function Ir(e,t={}){let{base:n,...r}=t,i=JSON.stringify([e,r]),a=Fr.get(i);return a===void 0&&(a=new Intl.RelativeTimeFormat(e,t),Fr.set(i,a)),a}var Lr=null;function Rr(){return Lr||(Lr=new Intl.DateTimeFormat().resolvedOptions().locale,Lr)}var zr=new Map;function Br(e){let t=zr.get(e);return t===void 0&&(t=new Intl.DateTimeFormat(e).resolvedOptions(),zr.set(e,t)),t}var Vr=new Map;function Hr(e){let t=Vr.get(e);if(!t){let n=new Intl.Locale(e);t=`getWeekInfo`in n?n.getWeekInfo():n.weekInfo,`minimalDays`in t||(t={...Qr,...t}),Vr.set(e,t)}return t}function Ur(e){let t=e.indexOf(`-x-`);t!==-1&&(e=e.substring(0,t));let n=e.indexOf(`-u-`);if(n===-1)return[e];{let t,r;try{t=Mr(e).resolvedOptions(),r=e}catch{let i=e.substring(0,n);t=Mr(i).resolvedOptions(),r=i}let{numberingSystem:i,calendar:a}=t;return[r,i,a]}}function Wr(e,t,n){return n||t?(e.includes(`-u-`)||(e+=`-u`),n&&(e+=`-ca-${n}`),t&&(e+=`-nu-${t}`),e):e}function Gr(e){let t=[];for(let n=1;n<=12;n++){let r=Q.utc(2009,n,1);t.push(e(r))}return t}function Kr(e){let t=[];for(let n=1;n<=7;n++){let r=Q.utc(2016,11,13+n);t.push(e(r))}return t}function qr(e,t,n,r){let i=e.listingMode();return i===`error`?null:i===`en`?n(t):r(t)}function Jr(e){return e.numberingSystem&&e.numberingSystem!==`latn`?!1:e.numberingSystem===`latn`||!e.locale||e.locale.startsWith(`en`)||Br(e.locale).numberingSystem===`latn`}var Yr=class{constructor(e,t,n){this.padTo=n.padTo||0,this.floor=n.floor||!1;let{padTo:r,floor:i,...a}=n;if(!t||Object.keys(a).length>0){let t={useGrouping:!1,...n};n.padTo>0&&(t.minimumIntegerDigits=n.padTo),this.inf=Pr(e,t)}}format(e){if(this.inf){let t=this.floor?Math.floor(e):e;return this.inf.format(t)}return X(this.floor?Math.floor(e):Zi(e,3),this.padTo)}},Xr=class{constructor(e,t,n){this.opts=n,this.originalZone=void 0;let r;if(this.opts.timeZone)this.dt=e;else if(e.zone.type===`fixed`){let t=-1*(e.offset/60),n=t>=0?`Etc/GMT+${t}`:`Etc/GMT${t}`;e.offset!==0&&Or.create(n).valid?(r=n,this.dt=e):(r=`UTC`,this.dt=e.offset===0?e:e.setZone(`UTC`).plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type===`system`?this.dt=e:e.zone.type===`iana`?(this.dt=e,r=e.zone.name):(r=`UTC`,this.dt=e.setZone(`UTC`).plus({minutes:e.offset}),this.originalZone=e.zone);let i={...this.opts};i.timeZone=i.timeZone||r,this.dtf=Mr(t,i)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(``):this.dtf.format(this.dt.toJSDate())}formatToParts(){let e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(e=>{if(e.type===`timeZoneName`){let t=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...e,value:t}}return e}):e}resolvedOptions(){return this.dtf.resolvedOptions()}},Zr=class{constructor(e,t,n){this.opts={style:`long`,...n},!t&&zi()&&(this.rtf=Ir(e,n))}format(e,t){return this.rtf?this.rtf.format(e,t):Oa(t,e,this.opts.numeric,this.opts.style!==`long`)}formatToParts(e,t){return this.rtf?this.rtf.formatToParts(e,t):[]}},Qr={firstDay:1,minimalDays:4,weekend:[6,7]},q=class e{static fromOpts(t){return e.create(t.locale,t.numberingSystem,t.outputCalendar,t.weekSettings,t.defaultToEN)}static create(t,n,r,i,a=!1){let o=t||J.defaultLocale,s=o||(a?`en-US`:Rr()),c=n||J.defaultNumberingSystem,l=r||J.defaultOutputCalendar,u=Gi(i)||J.defaultWeekSettings;return new e(s,c,l,u,o)}static resetCache(){Lr=null,jr.clear(),Nr.clear(),Fr.clear(),zr.clear(),Vr.clear()}static fromObject({locale:t,numberingSystem:n,outputCalendar:r,weekSettings:i}={}){return e.create(t,n,r,i)}constructor(e,t,n,r,i){let[a,o,s]=Ur(e);this.locale=a,this.numberingSystem=t||o||null,this.outputCalendar=n||s||null,this.weekSettings=r,this.intl=Wr(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=i,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached??=Jr(this),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),t=(this.numberingSystem===null||this.numberingSystem===`latn`)&&(this.outputCalendar===null||this.outputCalendar===`gregory`);return e&&t?`en`:`intl`}clone(t){return!t||Object.getOwnPropertyNames(t).length===0?this:e.create(t.locale||this.specifiedLocale,t.numberingSystem||this.numberingSystem,t.outputCalendar||this.outputCalendar,Gi(t.weekSettings)||this.weekSettings,t.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,t=!1){return qr(this,e,ma,()=>{let n=this.intl===`ja`||this.intl.startsWith(`ja-`);t&=!n;let r=t?{month:e,day:`numeric`}:{month:e},i=t?`format`:`standalone`;if(!this.monthsCache[i][e]){let t=n?e=>this.dtFormatter(e,r).format():e=>this.extract(e,r,`month`);this.monthsCache[i][e]=Gr(t)}return this.monthsCache[i][e]})}weekdays(e,t=!1){return qr(this,e,va,()=>{let n=t?{weekday:e,year:`numeric`,month:`long`,day:`numeric`}:{weekday:e},r=t?`format`:`standalone`;return this.weekdaysCache[r][e]||(this.weekdaysCache[r][e]=Kr(e=>this.extract(e,n,`weekday`))),this.weekdaysCache[r][e]})}meridiems(){return qr(this,void 0,()=>ya,()=>{if(!this.meridiemCache){let e={hour:`numeric`,hourCycle:`h12`};this.meridiemCache=[Q.utc(2016,11,13,9),Q.utc(2016,11,13,19)].map(t=>this.extract(t,e,`dayperiod`))}return this.meridiemCache})}eras(e){return qr(this,e,Ca,()=>{let t={era:e};return this.eraCache[e]||(this.eraCache[e]=[Q.utc(-40,1,1),Q.utc(2017,1,1)].map(e=>this.extract(e,t,`era`))),this.eraCache[e]})}extract(e,t,n){let r=this.dtFormatter(e,t).formatToParts().find(e=>e.type.toLowerCase()===n);return r?r.value:null}numberFormatter(e={}){return new Yr(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,t={}){return new Xr(e,this.intl,t)}relFormatter(e={}){return new Zr(this.intl,this.isEnglish(),e)}listFormatter(e={}){return Ar(this.intl,e)}isEnglish(){return this.locale===`en`||this.locale.toLowerCase()===`en-us`||Br(this.intl).locale.startsWith(`en-us`)}getWeekSettings(){return this.weekSettings?this.weekSettings:Bi()?Hr(this.locale):Qr}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}toString(){return`Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`}},$r=null,ei=class e extends yr{static get utcInstance(){return $r===null&&($r=new e(0)),$r}static instance(t){return t===0?e.utcInstance:new e(t)}static parseSpecifier(t){if(t){let n=t.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(n)return new e(oa(n[1],n[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return`fixed`}get name(){return this.fixed===0?`UTC`:`UTC${la(this.fixed,`narrow`)}`}get ianaName(){return this.fixed===0?`Etc/UTC`:`Etc/GMT${la(-this.fixed,`narrow`)}`}offsetName(){return this.name}formatOffset(e,t){return la(this.fixed,t)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type===`fixed`&&e.fixed===this.fixed}get isValid(){return!0}},ti=class extends yr{constructor(e){super(),this.zoneName=e}get type(){return`invalid`}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return``}offset(){return NaN}equals(){return!1}get isValid(){return!1}};function ni(e,t){if(Y(e)||e===null)return t;if(e instanceof yr)return e;if(Li(e)){let n=e.toLowerCase();return n==="default"?t:n===`local`||n===`system`?xr.instance:n===`utc`||n===`gmt`?ei.utcInstance:ei.parseSpecifier(n)||Or.create(e)}return Fi(e)?ei.instance(e):typeof e==`object`&&`offset`in e&&typeof e.offset==`function`?e:new ti(e)}var ri={arab:`[٠-٩]`,arabext:`[۰-۹]`,bali:`[᭐-᭙]`,beng:`[০-৯]`,deva:`[०-९]`,fullwide:`[0-9]`,gujr:`[૦-૯]`,hanidec:`[〇|一|二|三|四|五|六|七|八|九]`,khmr:`[០-៩]`,knda:`[೦-೯]`,laoo:`[໐-໙]`,limb:`[᥆-᥏]`,mlym:`[൦-൯]`,mong:`[᠐-᠙]`,mymr:`[၀-၉]`,orya:`[୦-୯]`,tamldec:`[௦-௯]`,telu:`[౦-౯]`,thai:`[๐-๙]`,tibt:`[༠-༩]`,latn:`\\d`},ii={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},ai=ri.hanidec.replace(/[\[|\]]/g,``).split(``);function oi(e){let t=parseInt(e,10);if(isNaN(t)){t=``;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(e[n].search(ri.hanidec)!==-1)t+=ai.indexOf(e[n]);else for(let e in ii){let[n,i]=ii[e];r>=n&&r<=i&&(t+=r-n)}}return parseInt(t,10)}return t}var si=new Map;function ci(){si.clear()}function li({numberingSystem:e},t=``){let n=e||`latn`,r=si.get(n);r===void 0&&(r=new Map,si.set(n,r));let i=r.get(t);return i===void 0&&(i=RegExp(`${ri[n]}${t}`),r.set(t,i)),i}var ui=()=>Date.now(),di=`system`,fi=null,pi=null,mi=null,hi=60,gi,_i=null,J=class{static get now(){return ui}static set now(e){ui=e}static set defaultZone(e){di=e}static get defaultZone(){return ni(di,xr.instance)}static get defaultLocale(){return fi}static set defaultLocale(e){fi=e}static get defaultNumberingSystem(){return pi}static set defaultNumberingSystem(e){pi=e}static get defaultOutputCalendar(){return mi}static set defaultOutputCalendar(e){mi=e}static get defaultWeekSettings(){return _i}static set defaultWeekSettings(e){_i=Gi(e)}static get twoDigitCutoffYear(){return hi}static set twoDigitCutoffYear(e){hi=e%100}static get throwOnInvalid(){return gi}static set throwOnInvalid(e){gi=e}static resetCaches(){q.resetCache(),Or.resetCache(),Q.resetCache(),ci()}},vi=class{constructor(e,t){this.reason=e,this.explanation=t}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}},yi=[0,31,59,90,120,151,181,212,243,273,304,334],bi=[0,31,60,91,121,152,182,213,244,274,305,335];function xi(e,t){return new vi(`unit out of range`,`you specified ${t} (of type ${typeof t}) as a ${e}, which is invalid`)}function Si(e,t,n){let r=new Date(Date.UTC(e,t-1,n));e<100&&e>=0&&r.setUTCFullYear(r.getUTCFullYear()-1900);let i=r.getUTCDay();return i===0?7:i}function Ci(e,t,n){return n+(Qi(e)?bi:yi)[t-1]}function wi(e,t){let n=Qi(e)?bi:yi,r=n.findIndex(e=>e<t),i=t-n[r];return{month:r+1,day:i}}function Ti(e,t){return(e-t+7)%7+1}function Ei(e,t=4,n=1){let{year:r,month:i,day:a}=e,o=Ci(r,i,a),s=Ti(Si(r,i,a),n),c=Math.floor((o-s+14-t)/7),l;return c<1?(l=r-1,c=ra(l,t,n)):c>ra(r,t,n)?(l=r+1,c=1):l=r,{weekYear:l,weekNumber:c,weekday:s,...ua(e)}}function Di(e,t=4,n=1){let{weekYear:r,weekNumber:i,weekday:a}=e,o=Ti(Si(r,1,t),n),s=$i(r),c=i*7+a-o-7+t,l;c<1?(l=r-1,c+=$i(l)):c>s?(l=r+1,c-=$i(r)):l=r;let{month:u,day:d}=wi(l,c);return{year:l,month:u,day:d,...ua(e)}}function Oi(e){let{year:t,month:n,day:r}=e;return{year:t,ordinal:Ci(t,n,r),...ua(e)}}function ki(e){let{year:t,ordinal:n}=e,{month:r,day:i}=wi(t,n);return{year:t,month:r,day:i,...ua(e)}}function Ai(e,t){if(!Y(e.localWeekday)||!Y(e.localWeekNumber)||!Y(e.localWeekYear)){if(!Y(e.weekday)||!Y(e.weekNumber)||!Y(e.weekYear))throw new Gn(`Cannot mix locale-based week fields with ISO-based week fields`);return Y(e.localWeekday)||(e.weekday=e.localWeekday),Y(e.localWeekNumber)||(e.weekNumber=e.localWeekNumber),Y(e.localWeekYear)||(e.weekYear=e.localWeekYear),delete e.localWeekday,delete e.localWeekNumber,delete e.localWeekYear,{minDaysInFirstWeek:t.getMinDaysInFirstWeek(),startOfWeek:t.getStartOfWeek()}}return{minDaysInFirstWeek:4,startOfWeek:1}}function ji(e,t=4,n=1){let r=Ii(e.weekYear),i=Ki(e.weekNumber,1,ra(e.weekYear,t,n)),a=Ki(e.weekday,1,7);return r?i?!a&&xi(`weekday`,e.weekday):xi(`week`,e.weekNumber):xi(`weekYear`,e.weekYear)}function Mi(e){let t=Ii(e.year),n=Ki(e.ordinal,1,$i(e.year));return t?!n&&xi(`ordinal`,e.ordinal):xi(`year`,e.year)}function Ni(e){let t=Ii(e.year),n=Ki(e.month,1,12),r=Ki(e.day,1,ea(e.year,e.month));return t?n?!r&&xi(`day`,e.day):xi(`month`,e.month):xi(`year`,e.year)}function Pi(e){let{hour:t,minute:n,second:r,millisecond:i}=e,a=Ki(t,0,23)||t===24&&n===0&&r===0&&i===0,o=Ki(n,0,59),s=Ki(r,0,59),c=Ki(i,0,999);return a?o?s?!c&&xi(`millisecond`,i):xi(`second`,r):xi(`minute`,n):xi(`hour`,t)}function Y(e){return e===void 0}function Fi(e){return typeof e==`number`}function Ii(e){return typeof e==`number`&&e%1==0}function Li(e){return typeof e==`string`}function Ri(e){return Object.prototype.toString.call(e)===`[object Date]`}function zi(){try{return typeof Intl<`u`&&!!Intl.RelativeTimeFormat}catch{return!1}}function Bi(){try{return typeof Intl<`u`&&!!Intl.Locale&&(`weekInfo`in Intl.Locale.prototype||`getWeekInfo`in Intl.Locale.prototype)}catch{return!1}}function Vi(e){return Array.isArray(e)?e:[e]}function Hi(e,t,n){if(e.length!==0)return e.reduce((e,r)=>{let i=[t(r),r];return e&&n(e[0],i[0])===e[0]?e:i},null)[1]}function Ui(e,t){return t.reduce((t,n)=>(t[n]=e[n],t),{})}function Wi(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Gi(e){if(e==null)return null;if(typeof e!=`object`)throw new qn(`Week settings must be an object`);if(!Ki(e.firstDay,1,7)||!Ki(e.minimalDays,1,7)||!Array.isArray(e.weekend)||e.weekend.some(e=>!Ki(e,1,7)))throw new qn(`Invalid week settings`);return{firstDay:e.firstDay,minimalDays:e.minimalDays,weekend:Array.from(e.weekend)}}function Ki(e,t,n){return Ii(e)&&e>=t&&e<=n}function qi(e,t){return e-t*Math.floor(e/t)}function X(e,t=2){let n=e<0,r;return r=n?`-`+(``+-e).padStart(t,`0`):(``+e).padStart(t,`0`),r}function Ji(e){if(!(Y(e)||e===null||e===``))return parseInt(e,10)}function Yi(e){if(!(Y(e)||e===null||e===``))return parseFloat(e)}function Xi(e){if(!(Y(e)||e===null||e===``)){let t=parseFloat(`0.`+e)*1e3;return Math.floor(t)}}function Zi(e,t,n=`round`){let r=10**t;switch(n){case`expand`:return e>0?Math.ceil(e*r)/r:Math.floor(e*r)/r;case`trunc`:return Math.trunc(e*r)/r;case`round`:return Math.round(e*r)/r;case`floor`:return Math.floor(e*r)/r;case`ceil`:return Math.ceil(e*r)/r;default:throw RangeError(`Value rounding ${n} is out of range`)}}function Qi(e){return e%4==0&&(e%100!=0||e%400==0)}function $i(e){return Qi(e)?366:365}function ea(e,t){let n=qi(t-1,12)+1,r=e+(t-n)/12;return n===2?Qi(r)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][n-1]}function ta(e){let t=Date.UTC(e.year,e.month-1,e.day,e.hour,e.minute,e.second,e.millisecond);return e.year<100&&e.year>=0&&(t=new Date(t),t.setUTCFullYear(e.year,e.month-1,e.day)),+t}function na(e,t,n){return-Ti(Si(e,1,t),n)+t-1}function ra(e,t=4,n=1){let r=na(e,t,n),i=na(e+1,t,n);return($i(e)-r+i)/7}function ia(e){return e>99?e:e>J.twoDigitCutoffYear?1900+e:2e3+e}function aa(e,t,n,r=null){let i=new Date(e),a={hourCycle:`h23`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`};r&&(a.timeZone=r);let o={timeZoneName:t,...a},s=new Intl.DateTimeFormat(n,o).formatToParts(i).find(e=>e.type.toLowerCase()===`timezonename`);return s?s.value:null}function oa(e,t){let n=parseInt(e,10);Number.isNaN(n)&&(n=0);let r=parseInt(t,10)||0,i=n<0||Object.is(n,-0)?-r:r;return n*60+i}function sa(e){let t=Number(e);if(typeof e==`boolean`||e===``||!Number.isFinite(t))throw new qn(`Invalid unit value ${e}`);return t}function ca(e,t){let n={};for(let r in e)if(Wi(e,r)){let i=e[r];if(i==null)continue;n[t(r)]=sa(i)}return n}function la(e,t){let n=Math.trunc(Math.abs(e/60)),r=Math.trunc(Math.abs(e%60)),i=e>=0?`+`:`-`;switch(t){case`short`:return`${i}${X(n,2)}:${X(r,2)}`;case`narrow`:return`${i}${n}${r>0?`:${r}`:``}`;case`techie`:return`${i}${X(n,2)}${X(r,2)}`;default:throw RangeError(`Value format ${t} is out of range for property format`)}}function ua(e){return Ui(e,[`hour`,`minute`,`second`,`millisecond`])}var da=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],fa=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],pa=[`J`,`F`,`M`,`A`,`M`,`J`,`J`,`A`,`S`,`O`,`N`,`D`];function ma(e){switch(e){case`narrow`:return[...pa];case`short`:return[...fa];case`long`:return[...da];case`numeric`:return[`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`10`,`11`,`12`];case`2-digit`:return[`01`,`02`,`03`,`04`,`05`,`06`,`07`,`08`,`09`,`10`,`11`,`12`];default:return null}}var ha=[`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`,`Sunday`],ga=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`],_a=[`M`,`T`,`W`,`T`,`F`,`S`,`S`];function va(e){switch(e){case`narrow`:return[..._a];case`short`:return[...ga];case`long`:return[...ha];case`numeric`:return[`1`,`2`,`3`,`4`,`5`,`6`,`7`];default:return null}}var ya=[`AM`,`PM`],ba=[`Before Christ`,`Anno Domini`],xa=[`BC`,`AD`],Sa=[`B`,`A`];function Ca(e){switch(e){case`narrow`:return[...Sa];case`short`:return[...xa];case`long`:return[...ba];default:return null}}function wa(e){return ya[e.hour<12?0:1]}function Ta(e,t){return va(t)[e.weekday-1]}function Ea(e,t){return ma(t)[e.month-1]}function Da(e,t){return Ca(t)[e.year<0?0:1]}function Oa(e,t,n=`always`,r=!1){let i={years:[`year`,`yr.`],quarters:[`quarter`,`qtr.`],months:[`month`,`mo.`],weeks:[`week`,`wk.`],days:[`day`,`day`,`days`],hours:[`hour`,`hr.`],minutes:[`minute`,`min.`],seconds:[`second`,`sec.`]},a=[`hours`,`minutes`,`seconds`].indexOf(e)===-1;if(n===`auto`&&a){let n=e===`days`;switch(t){case 1:return n?`tomorrow`:`next ${i[e][0]}`;case-1:return n?`yesterday`:`last ${i[e][0]}`;case 0:return n?`today`:`this ${i[e][0]}`}}let o=Object.is(t,-0)||t<0,s=Math.abs(t),c=s===1,l=i[e],u=r?c?l[1]:l[2]||l[1]:c?i[e][0]:e;return o?`${s} ${u} ago`:`in ${s} ${u}`}function ka(e,t){let n=``;for(let r of e)r.literal?n+=r.val:n+=t(r.val);return n}var Aa={D:Zn,DD:Qn,DDD:er,DDDD:tr,t:nr,tt:rr,ttt:ir,tttt:ar,T:or,TT:sr,TTT:cr,TTTT:lr,f:ur,ff:fr,fff:hr,ffff:_r,F:dr,FF:pr,FFF:gr,FFFF:vr},ja=class e{static create(t,n={}){return new e(t,n)}static parseFormat(e){let t=null,n=``,r=!1,i=[];for(let a=0;a<e.length;a++){let o=e.charAt(a);o===`'`?((n.length>0||r)&&i.push({literal:r||/^\s+$/.test(n),val:n===``?`'`:n}),t=null,n=``,r=!r):r||o===t?n+=o:(n.length>0&&i.push({literal:/^\s+$/.test(n),val:n}),n=o,t=o)}return n.length>0&&i.push({literal:r||/^\s+$/.test(n),val:n}),i}static macroTokenToFormatOpts(e){return Aa[e]}constructor(e,t){this.opts=t,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,t){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...t}).format()}dtFormatter(e,t={}){return this.loc.dtFormatter(e,{...this.opts,...t})}formatDateTime(e,t){return this.dtFormatter(e,t).format()}formatDateTimeParts(e,t){return this.dtFormatter(e,t).formatToParts()}formatInterval(e,t){return this.dtFormatter(e.start,t).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,t){return this.dtFormatter(e,t).resolvedOptions()}num(e,t=0,n=void 0){if(this.opts.forceSimple)return X(e,t);let r={...this.opts};return t>0&&(r.padTo=t),n&&(r.signDisplay=n),this.loc.numberFormatter(r).format(e)}formatDateTimeFromString(t,n){let r=this.loc.listingMode()===`en`,i=this.loc.outputCalendar&&this.loc.outputCalendar!==`gregory`,a=(e,n)=>this.loc.extract(t,e,n),o=e=>t.isOffsetFixed&&t.offset===0&&e.allowZ?`Z`:t.isValid?t.zone.formatOffset(t.ts,e.format):``,s=()=>r?wa(t):a({hour:`numeric`,hourCycle:`h12`},`dayperiod`),c=(e,n)=>r?Ea(t,e):a(n?{month:e}:{month:e,day:`numeric`},`month`),l=(e,n)=>r?Ta(t,e):a(n?{weekday:e}:{weekday:e,month:`long`,day:`numeric`},`weekday`),u=n=>{let r=e.macroTokenToFormatOpts(n);return r?this.formatWithSystemDefault(t,r):n},d=e=>r?Da(t,e):a({era:e},`era`);return ka(e.parseFormat(n),e=>{switch(e){case`S`:return this.num(t.millisecond);case`u`:case`SSS`:return this.num(t.millisecond,3);case`s`:return this.num(t.second);case`ss`:return this.num(t.second,2);case`uu`:return this.num(Math.floor(t.millisecond/10),2);case`uuu`:return this.num(Math.floor(t.millisecond/100));case`m`:return this.num(t.minute);case`mm`:return this.num(t.minute,2);case`h`:return this.num(t.hour%12==0?12:t.hour%12);case`hh`:return this.num(t.hour%12==0?12:t.hour%12,2);case`H`:return this.num(t.hour);case`HH`:return this.num(t.hour,2);case`Z`:return o({format:`narrow`,allowZ:this.opts.allowZ});case`ZZ`:return o({format:`short`,allowZ:this.opts.allowZ});case`ZZZ`:return o({format:`techie`,allowZ:this.opts.allowZ});case`ZZZZ`:return t.zone.offsetName(t.ts,{format:`short`,locale:this.loc.locale});case`ZZZZZ`:return t.zone.offsetName(t.ts,{format:`long`,locale:this.loc.locale});case`z`:return t.zoneName;case`a`:return s();case`d`:return i?a({day:`numeric`},`day`):this.num(t.day);case`dd`:return i?a({day:`2-digit`},`day`):this.num(t.day,2);case`c`:return this.num(t.weekday);case`ccc`:return l(`short`,!0);case`cccc`:return l(`long`,!0);case`ccccc`:return l(`narrow`,!0);case`E`:return this.num(t.weekday);case`EEE`:return l(`short`,!1);case`EEEE`:return l(`long`,!1);case`EEEEE`:return l(`narrow`,!1);case`L`:return i?a({month:`numeric`,day:`numeric`},`month`):this.num(t.month);case`LL`:return i?a({month:`2-digit`,day:`numeric`},`month`):this.num(t.month,2);case`LLL`:return c(`short`,!0);case`LLLL`:return c(`long`,!0);case`LLLLL`:return c(`narrow`,!0);case`M`:return i?a({month:`numeric`},`month`):this.num(t.month);case`MM`:return i?a({month:`2-digit`},`month`):this.num(t.month,2);case`MMM`:return c(`short`,!1);case`MMMM`:return c(`long`,!1);case`MMMMM`:return c(`narrow`,!1);case`y`:return i?a({year:`numeric`},`year`):this.num(t.year);case`yy`:return i?a({year:`2-digit`},`year`):this.num(t.year.toString().slice(-2),2);case`yyyy`:return i?a({year:`numeric`},`year`):this.num(t.year,4);case`yyyyyy`:return i?a({year:`numeric`},`year`):this.num(t.year,6);case`G`:return d(`short`);case`GG`:return d(`long`);case`GGGGG`:return d(`narrow`);case`kk`:return this.num(t.weekYear.toString().slice(-2),2);case`kkkk`:return this.num(t.weekYear,4);case`W`:return this.num(t.weekNumber);case`WW`:return this.num(t.weekNumber,2);case`n`:return this.num(t.localWeekNumber);case`nn`:return this.num(t.localWeekNumber,2);case`ii`:return this.num(t.localWeekYear.toString().slice(-2),2);case`iiii`:return this.num(t.localWeekYear,4);case`o`:return this.num(t.ordinal);case`ooo`:return this.num(t.ordinal,3);case`q`:return this.num(t.quarter);case`qq`:return this.num(t.quarter,2);case`X`:return this.num(Math.floor(t.ts/1e3));case`x`:return this.num(t.ts);default:return u(e)}})}formatDurationFromString(t,n){let r=this.opts.signMode===`negativeLargestOnly`?-1:1,i=e=>{switch(e[0]){case`S`:return`milliseconds`;case`s`:return`seconds`;case`m`:return`minutes`;case`h`:return`hours`;case`d`:return`days`;case`w`:return`weeks`;case`M`:return`months`;case`y`:return`years`;default:return null}},a=(e,t)=>n=>{let a=i(n);if(a){let i=t.isNegativeDuration&&a!==t.largestUnit?r:1,o;return o=this.opts.signMode===`negativeLargestOnly`&&a!==t.largestUnit?`never`:this.opts.signMode===`all`?`always`:`auto`,this.num(e.get(a)*i,n.length,o)}return n},o=e.parseFormat(n),s=o.reduce((e,{literal:t,val:n})=>t?e:e.concat(n),[]),c=t.shiftTo(...s.map(i).filter(e=>e));return ka(o,a(c,{isNegativeDuration:c<0,largestUnit:Object.keys(c.values)[0]}))}},Ma=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Na(...e){let t=e.reduce((e,t)=>e+t.source,``);return RegExp(`^${t}$`)}function Pa(...e){return t=>e.reduce(([e,n,r],i)=>{let[a,o,s]=i(t,r);return[{...e,...a},o||n,s]},[{},null,1]).slice(0,2)}function Fa(e,...t){if(e==null)return[null,null];for(let[n,r]of t){let t=n.exec(e);if(t)return r(t)}return[null,null]}function Ia(...e){return(t,n)=>{let r={},i;for(i=0;i<e.length;i++)r[e[i]]=Ji(t[n+i]);return[r,null,n+i]}}var La=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,Ra=`(?:${La.source}?(?:\\[(${Ma.source})\\])?)?`,za=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,Ba=RegExp(`${za.source}${Ra}`),Va=RegExp(`(?:[Tt]${Ba.source})?`),Ha=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Ua=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Wa=/(\d{4})-?(\d{3})/,Ga=Ia(`weekYear`,`weekNumber`,`weekDay`),Ka=Ia(`year`,`ordinal`),qa=/(\d{4})-(\d\d)-(\d\d)/,Ja=RegExp(`${za.source} ?(?:${La.source}|(${Ma.source}))?`),Ya=RegExp(`(?: ${Ja.source})?`);function Xa(e,t,n){let r=e[t];return Y(r)?n:Ji(r)}function Za(e,t){return[{year:Xa(e,t),month:Xa(e,t+1,1),day:Xa(e,t+2,1)},null,t+3]}function Qa(e,t){return[{hours:Xa(e,t,0),minutes:Xa(e,t+1,0),seconds:Xa(e,t+2,0),milliseconds:Xi(e[t+3])},null,t+4]}function $a(e,t){let n=!e[t]&&!e[t+1],r=oa(e[t+1],e[t+2]);return[{},n?null:ei.instance(r),t+3]}function eo(e,t){return[{},e[t]?Or.create(e[t]):null,t+1]}var to=RegExp(`^T?${za.source}$`),no=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function ro(e){let[t,n,r,i,a,o,s,c,l]=e,u=t[0]===`-`,d=c&&c[0]===`-`,f=(e,t=!1)=>e!==void 0&&(t||e&&u)?-e:e;return[{years:f(Yi(n)),months:f(Yi(r)),weeks:f(Yi(i)),days:f(Yi(a)),hours:f(Yi(o)),minutes:f(Yi(s)),seconds:f(Yi(c),c===`-0`),milliseconds:f(Xi(l),d)}]}var io={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function ao(e,t,n,r,i,a,o){let s={year:t.length===2?ia(Ji(t)):Ji(t),month:fa.indexOf(n)+1,day:Ji(r),hour:Ji(i),minute:Ji(a)};return o&&(s.second=Ji(o)),e&&(s.weekday=e.length>3?ha.indexOf(e)+1:ga.indexOf(e)+1),s}var oo=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function so(e){let[,t,n,r,i,a,o,s,c,l,u,d]=e,f=ao(t,i,r,n,a,o,s),p;return p=c?io[c]:l?0:oa(u,d),[f,new ei(p)]}function co(e){return e.replace(/\([^()]*\)|[\n\t]/g,` `).replace(/(\s\s+)/g,` `).trim()}var lo=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,uo=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,fo=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function po(e){let[,t,n,r,i,a,o,s]=e;return[ao(t,i,r,n,a,o,s),ei.utcInstance]}function mo(e){let[,t,n,r,i,a,o,s]=e;return[ao(t,s,n,r,i,a,o),ei.utcInstance]}var ho=Na(Ha,Va),go=Na(Ua,Va),_o=Na(Wa,Va),vo=Na(Ba),yo=Pa(Za,Qa,$a,eo),bo=Pa(Ga,Qa,$a,eo),xo=Pa(Ka,Qa,$a,eo),So=Pa(Qa,$a,eo);function Co(e){return Fa(e,[ho,yo],[go,bo],[_o,xo],[vo,So])}function wo(e){return Fa(co(e),[oo,so])}function To(e){return Fa(e,[lo,po],[uo,po],[fo,mo])}function Eo(e){return Fa(e,[no,ro])}var Do=Pa(Qa);function Oo(e){return Fa(e,[to,Do])}var ko=Na(qa,Ya),Ao=Na(Ja),jo=Pa(Qa,$a,eo);function Mo(e){return Fa(e,[ko,yo],[Ao,jo])}var No=`Invalid Duration`,Po={weeks:{days:7,hours:168,minutes:10080,seconds:604800,milliseconds:6048e5},days:{hours:24,minutes:1440,seconds:86400,milliseconds:864e5},hours:{minutes:60,seconds:3600,milliseconds:36e5},minutes:{seconds:60,milliseconds:6e4},seconds:{milliseconds:1e3}},Fo={years:{quarters:4,months:12,weeks:52,days:365,hours:8760,minutes:525600,seconds:31536e3,milliseconds:31536e6},quarters:{months:3,weeks:13,days:91,hours:2184,minutes:131040,seconds:7862400,milliseconds:78624e5},months:{weeks:4,days:30,hours:720,minutes:43200,seconds:2592e3,milliseconds:2592e6},...Po},Io=146097/400,Lo=146097/4800,Ro={years:{quarters:4,months:12,weeks:Io/7,days:Io,hours:Io*24,minutes:Io*24*60,seconds:Io*24*60*60,milliseconds:Io*24*60*60*1e3},quarters:{months:3,weeks:Io/28,days:Io/4,hours:Io*24/4,minutes:Io*24*60/4,seconds:Io*24*60*60/4,milliseconds:Io*24*60*60*1e3/4},months:{weeks:Lo/7,days:Lo,hours:Lo*24,minutes:Lo*24*60,seconds:Lo*24*60*60,milliseconds:Lo*24*60*60*1e3},...Po},zo=[`years`,`quarters`,`months`,`weeks`,`days`,`hours`,`minutes`,`seconds`,`milliseconds`],Bo=zo.slice(0).reverse();function Vo(e,t,n=!1){return new Go({values:n?t.values:{...e.values,...t.values||{}},loc:e.loc.clone(t.loc),conversionAccuracy:t.conversionAccuracy||e.conversionAccuracy,matrix:t.matrix||e.matrix})}function Ho(e,t){let n=t.milliseconds??0;for(let r of Bo.slice(1))t[r]&&(n+=t[r]*e[r].milliseconds);return n}function Uo(e,t){let n=Ho(e,t)<0?-1:1;zo.reduceRight((r,i)=>{if(Y(t[i]))return r;if(r){let a=t[r]*n,o=e[i][r],s=Math.floor(a/o);t[i]+=s*n,t[r]-=s*o*n}return i},null),zo.reduce((n,r)=>{if(Y(t[r]))return n;if(n){let i=t[n]%1;t[n]-=i,t[r]+=i*e[n][r]}return r},null)}function Wo(e){let t={};for(let[n,r]of Object.entries(e))r!==0&&(t[n]=r);return t}var Go=class e{constructor(e){let t=e.conversionAccuracy===`longterm`||!1,n=t?Ro:Fo;e.matrix&&(n=e.matrix),this.values=e.values,this.loc=e.loc||q.create(),this.conversionAccuracy=t?`longterm`:`casual`,this.invalid=e.invalid||null,this.matrix=n,this.isLuxonDuration=!0}static fromMillis(t,n){return e.fromObject({milliseconds:t},n)}static fromObject(t,n={}){if(typeof t!=`object`||!t)throw new qn(`Duration.fromObject: argument expected to be an object, got ${t===null?`null`:typeof t}`);return new e({values:ca(t,e.normalizeUnit),loc:q.fromObject(n),conversionAccuracy:n.conversionAccuracy,matrix:n.matrix})}static fromDurationLike(t){if(Fi(t))return e.fromMillis(t);if(e.isDuration(t))return t;if(typeof t==`object`)return e.fromObject(t);throw new qn(`Unknown duration argument ${t} of type ${typeof t}`)}static fromISO(t,n){let[r]=Eo(t);return r?e.fromObject(r,n):e.invalid(`unparsable`,`the input "${t}" can't be parsed as ISO 8601`)}static fromISOTime(t,n){let[r]=Oo(t);return r?e.fromObject(r,n):e.invalid(`unparsable`,`the input "${t}" can't be parsed as ISO 8601`)}static invalid(t,n=null){if(!t)throw new qn(`need to specify a reason the Duration is invalid`);let r=t instanceof vi?t:new vi(t,n);if(J.throwOnInvalid)throw new Wn(r);return new e({invalid:r})}static normalizeUnit(e){let t={year:`years`,years:`years`,quarter:`quarters`,quarters:`quarters`,month:`months`,months:`months`,week:`weeks`,weeks:`weeks`,day:`days`,days:`days`,hour:`hours`,hours:`hours`,minute:`minutes`,minutes:`minutes`,second:`seconds`,seconds:`seconds`,millisecond:`milliseconds`,milliseconds:`milliseconds`}[e&&e.toLowerCase()];if(!t)throw new Kn(e);return t}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,t={}){let n={...t,floor:t.round!==!1&&t.floor!==!1};return this.isValid?ja.create(this.loc,n).formatDurationFromString(this,e):No}toHuman(e={}){if(!this.isValid)return No;let t=e.showZeros!==!1,n=zo.map(n=>{let r=this.values[n];return Y(r)||r===0&&!t?null:this.loc.numberFormatter({style:`unit`,unitDisplay:`long`,...e,unit:n.slice(0,-1)}).format(r)}).filter(e=>e);return this.loc.listFormatter({type:`conjunction`,style:e.listStyle||`narrow`,...e}).format(n)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e=`P`;return this.years!==0&&(e+=this.years+`Y`),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+`M`),this.weeks!==0&&(e+=this.weeks+`W`),this.days!==0&&(e+=this.days+`D`),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+=`T`),this.hours!==0&&(e+=this.hours+`H`),this.minutes!==0&&(e+=this.minutes+`M`),(this.seconds!==0||this.milliseconds!==0)&&(e+=Zi(this.seconds+this.milliseconds/1e3,3)+`S`),e===`P`&&(e+=`T0S`),e}toISOTime(e={}){if(!this.isValid)return null;let t=this.toMillis();return t<0||t>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:`extended`,...e,includeOffset:!1},Q.fromMillis(t,{zone:`UTC`}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for(`nodejs.util.inspect.custom`)](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?Ho(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(t){if(!this.isValid)return this;let n=e.fromDurationLike(t),r={};for(let e of zo)(Wi(n.values,e)||Wi(this.values,e))&&(r[e]=n.get(e)+this.get(e));return Vo(this,{values:r},!0)}minus(t){if(!this.isValid)return this;let n=e.fromDurationLike(t);return this.plus(n.negate())}mapUnits(e){if(!this.isValid)return this;let t={};for(let n of Object.keys(this.values))t[n]=sa(e(this.values[n],n));return Vo(this,{values:t},!0)}get(t){return this[e.normalizeUnit(t)]}set(t){if(!this.isValid)return this;let n={...this.values,...ca(t,e.normalizeUnit)};return Vo(this,{values:n})}reconfigure({locale:e,numberingSystem:t,conversionAccuracy:n,matrix:r}={}){let i={loc:this.loc.clone({locale:e,numberingSystem:t}),matrix:r,conversionAccuracy:n};return Vo(this,i)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return Uo(this.matrix,e),Vo(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=Wo(this.normalize().shiftToAll().toObject());return Vo(this,{values:e},!0)}shiftTo(...t){if(!this.isValid||t.length===0)return this;t=t.map(t=>e.normalizeUnit(t));let n={},r={},i=this.toObject(),a;for(let e of zo)if(t.indexOf(e)>=0){a=e;let t=0;for(let n in r)t+=this.matrix[n][e]*r[n],r[n]=0;Fi(i[e])&&(t+=i[e]);let o=Math.trunc(t);n[e]=o,r[e]=(t*1e3-o*1e3)/1e3}else Fi(i[e])&&(r[e]=i[e]);for(let e in r)r[e]!==0&&(n[a]+=e===a?r[e]:r[e]/this.matrix[a][e]);return Uo(this.matrix,n),Vo(this,{values:n},!0)}shiftToAll(){return this.isValid?this.shiftTo(`years`,`months`,`weeks`,`days`,`hours`,`minutes`,`seconds`,`milliseconds`):this}negate(){if(!this.isValid)return this;let e={};for(let t of Object.keys(this.values))e[t]=this.values[t]===0?0:-this.values[t];return Vo(this,{values:e},!0)}removeZeros(){if(!this.isValid)return this;let e=Wo(this.values);return Vo(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function t(e,t){return e===void 0||e===0?t===void 0||t===0:e===t}for(let n of zo)if(!t(this.values[n],e.values[n]))return!1;return!0}},Ko=`Invalid Interval`;function qo(e,t){return!e||!e.isValid?Jo.invalid(`missing or invalid start`):!t||!t.isValid?Jo.invalid(`missing or invalid end`):t<e?Jo.invalid(`end before start`,`The end of an interval must be after its start, but you had start=${e.toISO()} and end=${t.toISO()}`):null}var Jo=class e{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(t,n=null){if(!t)throw new qn(`need to specify a reason the Interval is invalid`);let r=t instanceof vi?t:new vi(t,n);if(J.throwOnInvalid)throw new Un(r);return new e({invalid:r})}static fromDateTimes(t,n){let r=Xs(t),i=Xs(n);return qo(r,i)??new e({start:r,end:i})}static after(t,n){let r=Go.fromDurationLike(n),i=Xs(t);return e.fromDateTimes(i,i.plus(r))}static before(t,n){let r=Go.fromDurationLike(n),i=Xs(t);return e.fromDateTimes(i.minus(r),i)}static fromISO(t,n){let[r,i]=(t||``).split(`/`,2);if(r&&i){let t,a;try{t=Q.fromISO(r,n),a=t.isValid}catch{a=!1}let o,s;try{o=Q.fromISO(i,n),s=o.isValid}catch{s=!1}if(a&&s)return e.fromDateTimes(t,o);if(a){let r=Go.fromISO(i,n);if(r.isValid)return e.after(t,r)}else if(s){let t=Go.fromISO(r,n);if(t.isValid)return e.before(o,t)}}return e.invalid(`unparsable`,`the input "${t}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get lastDateTime(){return this.isValid&&this.e?this.e.minus(1):null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e=`milliseconds`){return this.isValid?this.toDuration(e).get(e):NaN}count(e=`milliseconds`,t){if(!this.isValid)return NaN;let n=this.start.startOf(e,t),r;return r=t?.useLocaleWeeks?this.end.reconfigure({locale:n.locale}):this.end,r=r.startOf(e,t),Math.floor(r.diff(n,e).get(e))+(r.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:t,end:n}={}){return this.isValid?e.fromDateTimes(t||this.s,n||this.e):this}splitAt(...t){if(!this.isValid)return[];let n=t.map(Xs).filter(e=>this.contains(e)).sort((e,t)=>e.toMillis()-t.toMillis()),r=[],{s:i}=this,a=0;for(;i<this.e;){let t=n[a]||this.e,o=+t>+this.e?this.e:t;r.push(e.fromDateTimes(i,o)),i=o,a+=1}return r}splitBy(t){let n=Go.fromDurationLike(t);if(!this.isValid||!n.isValid||n.as(`milliseconds`)===0)return[];let{s:r}=this,i=1,a,o=[];for(;r<this.e;){let t=this.start.plus(n.mapUnits(e=>e*i));a=+t>+this.e?this.e:t,o.push(e.fromDateTimes(r,a)),r=a,i+=1}return o}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(t){if(!this.isValid)return this;let n=this.s>t.s?this.s:t.s,r=this.e<t.e?this.e:t.e;return n>=r?null:e.fromDateTimes(n,r)}union(t){if(!this.isValid)return this;let n=this.s<t.s?this.s:t.s,r=this.e>t.e?this.e:t.e;return e.fromDateTimes(n,r)}static merge(e){let[t,n]=e.sort((e,t)=>e.s-t.s).reduce(([e,t],n)=>t?t.overlaps(n)||t.abutsStart(n)?[e,t.union(n)]:[e.concat([t]),n]:[e,n],[[],null]);return n&&t.push(n),t}static xor(t){let n=null,r=0,i=[],a=t.map(e=>[{time:e.s,type:`s`},{time:e.e,type:`e`}]),o=Array.prototype.concat(...a).sort((e,t)=>e.time-t.time);for(let t of o)r+=t.type===`s`?1:-1,r===1?n=t.time:(n&&+n!=+t.time&&i.push(e.fromDateTimes(n,t.time)),n=null);return e.merge(i)}difference(...t){return e.xor([this].concat(t)).map(e=>this.intersection(e)).filter(e=>e&&!e.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:Ko}[Symbol.for(`nodejs.util.inspect.custom`)](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(e=Zn,t={}){return this.isValid?ja.create(this.s.loc.clone(t),e).formatInterval(this):Ko}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:Ko}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Ko}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:Ko}toFormat(e,{separator:t=` – `}={}){return this.isValid?`${this.s.toFormat(e)}${t}${this.e.toFormat(e)}`:Ko}toDuration(e,t){return this.isValid?this.e.diff(this.s,e,t):Go.invalid(this.invalidReason)}mapEndpoints(t){return e.fromDateTimes(t(this.s),t(this.e))}},Yo=class{static hasDST(e=J.defaultZone){let t=Q.now().setZone(e).set({month:12});return!e.isUniversal&&t.offset!==t.set({month:6}).offset}static isValidIANAZone(e){return Or.isValidZone(e)}static normalizeZone(e){return ni(e,J.defaultZone)}static getStartOfWeek({locale:e=null,locObj:t=null}={}){return(t||q.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:t=null}={}){return(t||q.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:t=null}={}){return(t||q.create(e)).getWeekendDays().slice()}static months(e=`long`,{locale:t=null,numberingSystem:n=null,locObj:r=null,outputCalendar:i=`gregory`}={}){return(r||q.create(t,n,i)).months(e)}static monthsFormat(e=`long`,{locale:t=null,numberingSystem:n=null,locObj:r=null,outputCalendar:i=`gregory`}={}){return(r||q.create(t,n,i)).months(e,!0)}static weekdays(e=`long`,{locale:t=null,numberingSystem:n=null,locObj:r=null}={}){return(r||q.create(t,n,null)).weekdays(e)}static weekdaysFormat(e=`long`,{locale:t=null,numberingSystem:n=null,locObj:r=null}={}){return(r||q.create(t,n,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return q.create(e).meridiems()}static eras(e=`short`,{locale:t=null}={}){return q.create(t,null,`gregory`).eras(e)}static features(){return{relative:zi(),localeWeek:Bi()}}};function Xo(e,t){let n=e=>e.toUTC(0,{keepLocalTime:!0}).startOf(`day`).valueOf(),r=n(t)-n(e);return Math.floor(Go.fromMillis(r).as(`days`))}function Zo(e,t,n){let r=[[`years`,(e,t)=>t.year-e.year],[`quarters`,(e,t)=>t.quarter-e.quarter+(t.year-e.year)*4],[`months`,(e,t)=>t.month-e.month+(t.year-e.year)*12],[`weeks`,(e,t)=>{let n=Xo(e,t);return(n-n%7)/7}],[`days`,Xo]],i={},a=e,o,s;for(let[c,l]of r)n.indexOf(c)>=0&&(o=c,i[c]=l(e,t),s=a.plus(i),s>t?(i[c]--,e=a.plus(i),e>t&&(s=e,i[c]--,e=a.plus(i))):e=s);return[e,i,s,o]}function Qo(e,t,n,r){let[i,a,o,s]=Zo(e,t,n),c=t-i,l=n.filter(e=>[`hours`,`minutes`,`seconds`,`milliseconds`].indexOf(e)>=0);l.length===0&&(o<t&&(o=i.plus({[s]:1})),o!==i&&(a[s]=(a[s]||0)+c/(o-i)));let u=Go.fromObject(a,r);return l.length>0?Go.fromMillis(c,r).shiftTo(...l).plus(u):u}var $o=`missing Intl.DateTimeFormat.formatToParts support`;function Z(e,t=e=>e){return{regex:e,deser:([e])=>t(oi(e))}}var es=`[ \xA0]`,ts=new RegExp(es,`g`);function ns(e){return e.replace(/\./g,`\\.?`).replace(ts,es)}function rs(e){return e.replace(/\./g,``).replace(ts,` `).toLowerCase()}function is(e,t){return e===null?null:{regex:RegExp(e.map(ns).join(`|`)),deser:([n])=>e.findIndex(e=>rs(n)===rs(e))+t}}function as(e,t){return{regex:e,deser:([,e,t])=>oa(e,t),groups:t}}function os(e){return{regex:e,deser:([e])=>e}}function ss(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,`\\$&`)}function cs(e,t){let n=li(t),r=li(t,`{2}`),i=li(t,`{3}`),a=li(t,`{4}`),o=li(t,`{6}`),s=li(t,`{1,2}`),c=li(t,`{1,3}`),l=li(t,`{1,6}`),u=li(t,`{1,9}`),d=li(t,`{2,4}`),f=li(t,`{4,6}`),p=e=>({regex:RegExp(ss(e.val)),deser:([e])=>e,literal:!0}),m=(m=>{if(e.literal)return p(m);switch(m.val){case`G`:return is(t.eras(`short`),0);case`GG`:return is(t.eras(`long`),0);case`y`:return Z(l);case`yy`:return Z(d,ia);case`yyyy`:return Z(a);case`yyyyy`:return Z(f);case`yyyyyy`:return Z(o);case`M`:return Z(s);case`MM`:return Z(r);case`MMM`:return is(t.months(`short`,!0),1);case`MMMM`:return is(t.months(`long`,!0),1);case`L`:return Z(s);case`LL`:return Z(r);case`LLL`:return is(t.months(`short`,!1),1);case`LLLL`:return is(t.months(`long`,!1),1);case`d`:return Z(s);case`dd`:return Z(r);case`o`:return Z(c);case`ooo`:return Z(i);case`HH`:return Z(r);case`H`:return Z(s);case`hh`:return Z(r);case`h`:return Z(s);case`mm`:return Z(r);case`m`:return Z(s);case`q`:return Z(s);case`qq`:return Z(r);case`s`:return Z(s);case`ss`:return Z(r);case`S`:return Z(c);case`SSS`:return Z(i);case`u`:return os(u);case`uu`:return os(s);case`uuu`:return Z(n);case`a`:return is(t.meridiems(),0);case`kkkk`:return Z(a);case`kk`:return Z(d,ia);case`W`:return Z(s);case`WW`:return Z(r);case`E`:case`c`:return Z(n);case`EEE`:return is(t.weekdays(`short`,!1),1);case`EEEE`:return is(t.weekdays(`long`,!1),1);case`ccc`:return is(t.weekdays(`short`,!0),1);case`cccc`:return is(t.weekdays(`long`,!0),1);case`Z`:case`ZZ`:return as(RegExp(`([+-]${s.source})(?::(${r.source}))?`),2);case`ZZZ`:return as(RegExp(`([+-]${s.source})(${r.source})?`),2);case`z`:return os(/[a-z_+-/]{1,256}?/i);case` `:return os(/[^\S\n\r]/);default:return p(m)}})(e)||{invalidReason:$o};return m.token=e,m}var ls={year:{"2-digit":`yy`,numeric:`yyyyy`},month:{numeric:`M`,"2-digit":`MM`,short:`MMM`,long:`MMMM`},day:{numeric:`d`,"2-digit":`dd`},weekday:{short:`EEE`,long:`EEEE`},dayperiod:`a`,dayPeriod:`a`,hour12:{numeric:`h`,"2-digit":`hh`},hour24:{numeric:`H`,"2-digit":`HH`},minute:{numeric:`m`,"2-digit":`mm`},second:{numeric:`s`,"2-digit":`ss`},timeZoneName:{long:`ZZZZZ`,short:`ZZZ`}};function us(e,t,n){let{type:r,value:i}=e;if(r===`literal`){let e=/^\s+$/.test(i);return{literal:!e,val:e?` `:i}}let a=t[r],o=r;r===`hour`&&(o=t.hour12==null?t.hourCycle==null?n.hour12?`hour12`:`hour24`:t.hourCycle===`h11`||t.hourCycle===`h12`?`hour12`:`hour24`:t.hour12?`hour12`:`hour24`);let s=ls[o];if(typeof s==`object`&&(s=s[a]),s)return{literal:!1,val:s}}function ds(e){return[`^${e.map(e=>e.regex).reduce((e,t)=>`${e}(${t.source})`,``)}$`,e]}function fs(e,t,n){let r=e.match(t);if(r){let e={},t=1;for(let i in n)if(Wi(n,i)){let a=n[i],o=a.groups?a.groups+1:1;!a.literal&&a.token&&(e[a.token.val[0]]=a.deser(r.slice(t,t+o))),t+=o}return[r,e]}return[r,{}]}function ps(e){let t=e=>{switch(e){case`S`:return`millisecond`;case`s`:return`second`;case`m`:return`minute`;case`h`:case`H`:return`hour`;case`d`:return`day`;case`o`:return`ordinal`;case`L`:case`M`:return`month`;case`y`:return`year`;case`E`:case`c`:return`weekday`;case`W`:return`weekNumber`;case`k`:return`weekYear`;case`q`:return`quarter`;default:return null}},n=null,r;return Y(e.z)||(n=Or.create(e.z)),Y(e.Z)||(n||=new ei(e.Z),r=e.Z),Y(e.q)||(e.M=(e.q-1)*3+1),Y(e.h)||(e.h<12&&e.a===1?e.h+=12:e.h===12&&e.a===0&&(e.h=0)),e.G===0&&e.y&&(e.y=-e.y),Y(e.u)||(e.S=Xi(e.u)),[Object.keys(e).reduce((n,r)=>{let i=t(r);return i&&(n[i]=e[r]),n},{}),n,r]}var ms=null;function hs(){return ms||=Q.fromMillis(1555555555555),ms}function gs(e,t){if(e.literal)return e;let n=xs(ja.macroTokenToFormatOpts(e.val),t);return n==null||n.includes(void 0)?e:n}function _s(e,t){return Array.prototype.concat(...e.map(e=>gs(e,t)))}var vs=class{constructor(e,t){if(this.locale=e,this.format=t,this.tokens=_s(ja.parseFormat(t),e),this.units=this.tokens.map(t=>cs(t,e)),this.disqualifyingUnit=this.units.find(e=>e.invalidReason),!this.disqualifyingUnit){let[e,t]=ds(this.units);this.regex=RegExp(e,`i`),this.handlers=t}}explainFromTokens(e){if(this.isValid){let[t,n]=fs(e,this.regex,this.handlers),[r,i,a]=n?ps(n):[null,null,void 0];if(Wi(n,`a`)&&Wi(n,`H`))throw new Gn(`Can't include meridiem when specifying 24-hour format`);return{input:e,tokens:this.tokens,regex:this.regex,rawMatches:t,matches:n,result:r,zone:i,specificOffset:a}}return{input:e,tokens:this.tokens,invalidReason:this.invalidReason}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}};function ys(e,t,n){return new vs(e,n).explainFromTokens(t)}function bs(e,t,n){let{result:r,zone:i,specificOffset:a,invalidReason:o}=ys(e,t,n);return[r,i,a,o]}function xs(e,t){if(!e)return null;let n=ja.create(t,e).dtFormatter(hs()),r=n.formatToParts(),i=n.resolvedOptions();return r.map(t=>us(t,e,i))}var Ss=`Invalid DateTime`,Cs=864e13;function ws(e){return new vi(`unsupported zone`,`the zone "${e.name}" is not supported`)}function Ts(e){return e.weekData===null&&(e.weekData=Ei(e.c)),e.weekData}function Es(e){return e.localWeekData===null&&(e.localWeekData=Ei(e.c,e.loc.getMinDaysInFirstWeek(),e.loc.getStartOfWeek())),e.localWeekData}function Ds(e,t){let n={ts:e.ts,zone:e.zone,c:e.c,o:e.o,loc:e.loc,invalid:e.invalid};return new Q({...n,...t,old:n})}function Os(e,t,n){let r=e-t*60*1e3,i=n.offset(r);if(t===i)return[r,t];r-=(i-t)*60*1e3;let a=n.offset(r);return i===a?[r,i]:[e-Math.min(i,a)*60*1e3,Math.max(i,a)]}function ks(e,t){e+=t*60*1e3;let n=new Date(e);return{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate(),hour:n.getUTCHours(),minute:n.getUTCMinutes(),second:n.getUTCSeconds(),millisecond:n.getUTCMilliseconds()}}function As(e,t,n){return Os(ta(e),t,n)}function js(e,t){let n=e.o,r=e.c.year+Math.trunc(t.years),i=e.c.month+Math.trunc(t.months)+Math.trunc(t.quarters)*3,a={...e.c,year:r,month:i,day:Math.min(e.c.day,ea(r,i))+Math.trunc(t.days)+Math.trunc(t.weeks)*7},o=Go.fromObject({years:t.years-Math.trunc(t.years),quarters:t.quarters-Math.trunc(t.quarters),months:t.months-Math.trunc(t.months),weeks:t.weeks-Math.trunc(t.weeks),days:t.days-Math.trunc(t.days),hours:t.hours,minutes:t.minutes,seconds:t.seconds,milliseconds:t.milliseconds}).as(`milliseconds`),[s,c]=Os(ta(a),n,e.zone);return o!==0&&(s+=o,c=e.zone.offset(s)),{ts:s,o:c}}function Ms(e,t,n,r,i,a){let{setZone:o,zone:s}=n;if(e&&Object.keys(e).length!==0||t){let r=t||s,i=Q.fromObject(e,{...n,zone:r,specificOffset:a});return o?i:i.setZone(s)}return Q.invalid(new vi(`unparsable`,`the input "${i}" can't be parsed as ${r}`))}function Ns(e,t,n=!0){return e.isValid?ja.create(q.create(`en-US`),{allowZ:n,forceSimple:!0}).formatDateTimeFromString(e,t):null}function Ps(e,t,n){let r=e.c.year>9999||e.c.year<0,i=``;if(r&&e.c.year>=0&&(i+=`+`),i+=X(e.c.year,r?6:4),n===`year`)return i;if(t){if(i+=`-`,i+=X(e.c.month),n===`month`)return i;i+=`-`}else if(i+=X(e.c.month),n===`month`)return i;return i+=X(e.c.day),i}function Fs(e,t,n,r,i,a,o){let s=!n||e.c.millisecond!==0||e.c.second!==0,c=``;switch(o){case`day`:case`month`:case`year`:break;default:if(c+=X(e.c.hour),o===`hour`)break;if(t){if(c+=`:`,c+=X(e.c.minute),o===`minute`)break;s&&(c+=`:`,c+=X(e.c.second))}else{if(c+=X(e.c.minute),o===`minute`)break;s&&(c+=X(e.c.second))}if(o===`second`)break;s&&(!r||e.c.millisecond!==0)&&(c+=`.`,c+=X(e.c.millisecond,3))}return i&&(e.isOffsetFixed&&e.offset===0&&!a?c+=`Z`:e.o<0?(c+=`-`,c+=X(Math.trunc(-e.o/60)),c+=`:`,c+=X(Math.trunc(-e.o%60))):(c+=`+`,c+=X(Math.trunc(e.o/60)),c+=`:`,c+=X(Math.trunc(e.o%60)))),a&&(c+=`[`+e.zone.ianaName+`]`),c}var Is={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Ls={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Rs={ordinal:1,hour:0,minute:0,second:0,millisecond:0},zs=[`year`,`month`,`day`,`hour`,`minute`,`second`,`millisecond`],Bs=[`weekYear`,`weekNumber`,`weekday`,`hour`,`minute`,`second`,`millisecond`],Vs=[`year`,`ordinal`,`hour`,`minute`,`second`,`millisecond`];function Hs(e){let t={year:`year`,years:`year`,month:`month`,months:`month`,day:`day`,days:`day`,hour:`hour`,hours:`hour`,minute:`minute`,minutes:`minute`,quarter:`quarter`,quarters:`quarter`,second:`second`,seconds:`second`,millisecond:`millisecond`,milliseconds:`millisecond`,weekday:`weekday`,weekdays:`weekday`,weeknumber:`weekNumber`,weeksnumber:`weekNumber`,weeknumbers:`weekNumber`,weekyear:`weekYear`,weekyears:`weekYear`,ordinal:`ordinal`}[e.toLowerCase()];if(!t)throw new Kn(e);return t}function Us(e){switch(e.toLowerCase()){case`localweekday`:case`localweekdays`:return`localWeekday`;case`localweeknumber`:case`localweeknumbers`:return`localWeekNumber`;case`localweekyear`:case`localweekyears`:return`localWeekYear`;default:return Hs(e)}}function Ws(e){if(Js===void 0&&(Js=J.now()),e.type!==`iana`)return e.offset(Js);let t=e.name,n=Ys.get(t);return n===void 0&&(n=e.offset(Js),Ys.set(t,n)),n}function Gs(e,t){let n=ni(t.zone,J.defaultZone);if(!n.isValid)return Q.invalid(ws(n));let r=q.fromObject(t),i,a;if(Y(e.year))i=J.now();else{for(let t of zs)Y(e[t])&&(e[t]=Is[t]);let t=Ni(e)||Pi(e);if(t)return Q.invalid(t);let r=Ws(n);[i,a]=As(e,r,n)}return new Q({ts:i,zone:n,loc:r,o:a})}function Ks(e,t,n){let r=Y(n.round)?!0:n.round,i=Y(n.rounding)?`trunc`:n.rounding,a=(e,a)=>(e=Zi(e,r||n.calendary?0:2,n.calendary?`round`:i),t.loc.clone(n).relFormatter(n).format(e,a)),o=r=>n.calendary?t.hasSame(e,r)?0:t.startOf(r).diff(e.startOf(r),r).get(r):t.diff(e,r).get(r);if(n.unit)return a(o(n.unit),n.unit);for(let e of n.units){let t=o(e);if(Math.abs(t)>=1)return a(t,e)}return a(e>t?-0:0,n.units[n.units.length-1])}function qs(e){let t={},n;return e.length>0&&typeof e[e.length-1]==`object`?(t=e[e.length-1],n=Array.from(e).slice(0,e.length-1)):n=Array.from(e),[t,n]}var Js,Ys=new Map,Q=class e{constructor(e){let t=e.zone||J.defaultZone,n=e.invalid||(Number.isNaN(e.ts)?new vi(`invalid input`):null)||(t.isValid?null:ws(t));this.ts=Y(e.ts)?J.now():e.ts;let r=null,i=null;if(!n){if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(t))[r,i]=[e.old.c,e.old.o];else{let a=Fi(e.o)&&!e.old?e.o:t.offset(this.ts);r=ks(this.ts,a),n=Number.isNaN(r.year)?new vi(`invalid input`):null,r=n?null:r,i=n?null:a}}this._zone=t,this.loc=e.loc||q.create(),this.invalid=n,this.weekData=null,this.localWeekData=null,this.c=r,this.o=i,this.isLuxonDateTime=!0}static now(){return new e({})}static local(){let[e,t]=qs(arguments),[n,r,i,a,o,s,c]=t;return Gs({year:n,month:r,day:i,hour:a,minute:o,second:s,millisecond:c},e)}static utc(){let[e,t]=qs(arguments),[n,r,i,a,o,s,c]=t;return e.zone=ei.utcInstance,Gs({year:n,month:r,day:i,hour:a,minute:o,second:s,millisecond:c},e)}static fromJSDate(t,n={}){let r=Ri(t)?t.valueOf():NaN;if(Number.isNaN(r))return e.invalid(`invalid input`);let i=ni(n.zone,J.defaultZone);return i.isValid?new e({ts:r,zone:i,loc:q.fromObject(n)}):e.invalid(ws(i))}static fromMillis(t,n={}){if(!Fi(t))throw new qn(`fromMillis requires a numerical input, but received a ${typeof t} with value ${t}`);return t<-864e13||t>Cs?e.invalid(`Timestamp out of range`):new e({ts:t,zone:ni(n.zone,J.defaultZone),loc:q.fromObject(n)})}static fromSeconds(t,n={}){if(Fi(t))return new e({ts:t*1e3,zone:ni(n.zone,J.defaultZone),loc:q.fromObject(n)});throw new qn(`fromSeconds requires a numerical input`)}static fromObject(t,n={}){t||={};let r=ni(n.zone,J.defaultZone);if(!r.isValid)return e.invalid(ws(r));let i=q.fromObject(n),a=ca(t,Us),{minDaysInFirstWeek:o,startOfWeek:s}=Ai(a,i),c=J.now(),l=Y(n.specificOffset)?r.offset(c):n.specificOffset,u=!Y(a.ordinal),d=!Y(a.year),f=!Y(a.month)||!Y(a.day),p=d||f,m=a.weekYear||a.weekNumber;if((p||u)&&m)throw new Gn(`Can't mix weekYear/weekNumber units with year/month/day or ordinals`);if(f&&u)throw new Gn(`Can't mix ordinal dates with month/day`);let h=m||a.weekday&&!p,g,_,v=ks(c,l);h?(g=Bs,_=Ls,v=Ei(v,o,s)):u?(g=Vs,_=Rs,v=Oi(v)):(g=zs,_=Is);let y=!1;for(let e of g){let t=a[e];Y(t)?a[e]=y?_[e]:v[e]:y=!0}let b=(h?ji(a,o,s):u?Mi(a):Ni(a))||Pi(a);if(b)return e.invalid(b);let[x,S]=As(h?Di(a,o,s):u?ki(a):a,l,r),C=new e({ts:x,zone:r,o:S,loc:i});return a.weekday&&p&&t.weekday!==C.weekday?e.invalid(`mismatched weekday`,`you can't specify both a weekday of ${a.weekday} and a date of ${C.toISO()}`):C.isValid?C:e.invalid(C.invalid)}static fromISO(e,t={}){let[n,r]=Co(e);return Ms(n,r,t,`ISO 8601`,e)}static fromRFC2822(e,t={}){let[n,r]=wo(e);return Ms(n,r,t,`RFC 2822`,e)}static fromHTTP(e,t={}){let[n,r]=To(e);return Ms(n,r,t,`HTTP`,t)}static fromFormat(t,n,r={}){if(Y(t)||Y(n))throw new qn(`fromFormat requires an input string and a format`);let{locale:i=null,numberingSystem:a=null}=r,[o,s,c,l]=bs(q.fromOpts({locale:i,numberingSystem:a,defaultToEN:!0}),t,n);return l?e.invalid(l):Ms(o,s,r,`format ${n}`,t,c)}static fromString(t,n,r={}){return e.fromFormat(t,n,r)}static fromSQL(e,t={}){let[n,r]=Mo(e);return Ms(n,r,t,`SQL`,e)}static invalid(t,n=null){if(!t)throw new qn(`need to specify a reason the DateTime is invalid`);let r=t instanceof vi?t:new vi(t,n);if(J.throwOnInvalid)throw new Hn(r);return new e({invalid:r})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,t={}){let n=xs(e,q.fromObject(t));return n?n.map(e=>e?e.val:null).join(``):null}static expandFormat(e,t={}){return _s(ja.parseFormat(e),q.fromObject(t)).map(e=>e.val).join(``)}static resetCache(){Js=void 0,Ys.clear()}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?Ts(this).weekYear:NaN}get weekNumber(){return this.isValid?Ts(this).weekNumber:NaN}get weekday(){return this.isValid?Ts(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?Es(this).weekday:NaN}get localWeekNumber(){return this.isValid?Es(this).weekNumber:NaN}get localWeekYear(){return this.isValid?Es(this).weekYear:NaN}get ordinal(){return this.isValid?Oi(this.c).ordinal:NaN}get monthShort(){return this.isValid?Yo.months(`short`,{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Yo.months(`long`,{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Yo.weekdays(`short`,{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Yo.weekdays(`long`,{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:`short`,locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:`long`,locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];let e=864e5,t=6e4,n=ta(this.c),r=this.zone.offset(n-e),i=this.zone.offset(n+e),a=this.zone.offset(n-r*t),o=this.zone.offset(n-i*t);if(a===o)return[this];let s=n-a*t,c=n-o*t,l=ks(s,a),u=ks(c,o);return l.hour===u.hour&&l.minute===u.minute&&l.second===u.second&&l.millisecond===u.millisecond?[Ds(this,{ts:s}),Ds(this,{ts:c})]:[this]}get isInLeapYear(){return Qi(this.year)}get daysInMonth(){return ea(this.year,this.month)}get daysInYear(){return this.isValid?$i(this.year):NaN}get weeksInWeekYear(){return this.isValid?ra(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?ra(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){let{locale:t,numberingSystem:n,calendar:r}=ja.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:t,numberingSystem:n,outputCalendar:r}}toUTC(e=0,t={}){return this.setZone(ei.instance(e),t)}toLocal(){return this.setZone(J.defaultZone)}setZone(t,{keepLocalTime:n=!1,keepCalendarTime:r=!1}={}){if(t=ni(t,J.defaultZone),t.equals(this.zone))return this;if(t.isValid){let e=this.ts;if(n||r){let n=t.offset(this.ts),r=this.toObject();[e]=As(r,n,t)}return Ds(this,{ts:e,zone:t})}return e.invalid(ws(t))}reconfigure({locale:e,numberingSystem:t,outputCalendar:n}={}){let r=this.loc.clone({locale:e,numberingSystem:t,outputCalendar:n});return Ds(this,{loc:r})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let t=ca(e,Us),{minDaysInFirstWeek:n,startOfWeek:r}=Ai(t,this.loc),i=!Y(t.weekYear)||!Y(t.weekNumber)||!Y(t.weekday),a=!Y(t.ordinal),o=!Y(t.year),s=!Y(t.month)||!Y(t.day),c=o||s,l=t.weekYear||t.weekNumber;if((c||a)&&l)throw new Gn(`Can't mix weekYear/weekNumber units with year/month/day or ordinals`);if(s&&a)throw new Gn(`Can't mix ordinal dates with month/day`);let u;i?u=Di({...Ei(this.c,n,r),...t},n,r):Y(t.ordinal)?(u={...this.toObject(),...t},Y(t.day)&&(u.day=Math.min(ea(u.year,u.month),u.day))):u=ki({...Oi(this.c),...t});let[d,f]=As(u,this.o,this.zone);return Ds(this,{ts:d,o:f})}plus(e){if(!this.isValid)return this;let t=Go.fromDurationLike(e);return Ds(this,js(this,t))}minus(e){if(!this.isValid)return this;let t=Go.fromDurationLike(e).negate();return Ds(this,js(this,t))}startOf(e,{useLocaleWeeks:t=!1}={}){if(!this.isValid)return this;let n={},r=Go.normalizeUnit(e);switch(r){case`years`:n.month=1;case`quarters`:case`months`:n.day=1;case`weeks`:case`days`:n.hour=0;case`hours`:n.minute=0;case`minutes`:n.second=0;case`seconds`:n.millisecond=0}if(r===`weeks`){if(t){let e=this.loc.getStartOfWeek(),{weekday:t}=this;t<e&&(n.weekNumber=this.weekNumber-1),n.weekday=e}else n.weekday=1}return r===`quarters`&&(n.month=(Math.ceil(this.month/3)-1)*3+1),this.set(n)}endOf(e,t){return this.isValid?this.plus({[e]:1}).startOf(e,t).minus(1):this}toFormat(e,t={}){return this.isValid?ja.create(this.loc.redefaultToEN(t)).formatDateTimeFromString(this,e):Ss}toLocaleString(e=Zn,t={}){return this.isValid?ja.create(this.loc.clone(t),e).formatDateTime(this):Ss}toLocaleParts(e={}){return this.isValid?ja.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e=`extended`,suppressSeconds:t=!1,suppressMilliseconds:n=!1,includeOffset:r=!0,extendedZone:i=!1,precision:a=`milliseconds`}={}){if(!this.isValid)return null;a=Hs(a);let o=e===`extended`,s=Ps(this,o,a);return zs.indexOf(a)>=3&&(s+=`T`),s+=Fs(this,o,t,n,r,i,a),s}toISODate({format:e=`extended`,precision:t=`day`}={}){return this.isValid?Ps(this,e===`extended`,Hs(t)):null}toISOWeekDate(){return Ns(this,`kkkk-'W'WW-c`)}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:t=!1,includeOffset:n=!0,includePrefix:r=!1,extendedZone:i=!1,format:a=`extended`,precision:o=`milliseconds`}={}){return this.isValid?(o=Hs(o),(r&&zs.indexOf(o)>=3?`T`:``)+Fs(this,a===`extended`,t,e,n,i,o)):null}toRFC2822(){return Ns(this,`EEE, dd LLL yyyy HH:mm:ss ZZZ`,!1)}toHTTP(){return Ns(this.toUTC(),`EEE, dd LLL yyyy HH:mm:ss 'GMT'`)}toSQLDate(){return this.isValid?Ps(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:t=!1,includeOffsetSpace:n=!0}={}){let r=`HH:mm:ss.SSS`;return(t||e)&&(n&&(r+=` `),t?r+=`z`:e&&(r+=`ZZ`)),Ns(this,r,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():Ss}[Symbol.for(`nodejs.util.inspect.custom`)](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};let t={...this.c};return e.includeConfig&&(t.outputCalendar=this.outputCalendar,t.numberingSystem=this.loc.numberingSystem,t.locale=this.loc.locale),t}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,t=`milliseconds`,n={}){if(!this.isValid||!e.isValid)return Go.invalid(`created by diffing an invalid DateTime`);let r={locale:this.locale,numberingSystem:this.numberingSystem,...n},i=Vi(t).map(Go.normalizeUnit),a=e.valueOf()>this.valueOf(),o=Qo(a?this:e,a?e:this,i,r);return a?o.negate():o}diffNow(t=`milliseconds`,n={}){return this.diff(e.now(),t,n)}until(e){return this.isValid?Jo.fromDateTimes(this,e):this}hasSame(e,t,n){if(!this.isValid)return!1;let r=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(t,n)<=r&&r<=i.endOf(t,n)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(t={}){if(!this.isValid)return null;let n=t.base||e.fromObject({},{zone:this.zone}),r=t.padding?this<n?-t.padding:t.padding:0,i=[`years`,`months`,`days`,`hours`,`minutes`,`seconds`],a=t.unit;return Array.isArray(t.unit)&&(i=t.unit,a=void 0),Ks(n,this.plus(r),{...t,numeric:`always`,units:i,unit:a})}toRelativeCalendar(t={}){return this.isValid?Ks(t.base||e.fromObject({},{zone:this.zone}),this,{...t,numeric:`auto`,units:[`years`,`months`,`days`],calendary:!0}):null}static min(...t){if(!t.every(e.isDateTime))throw new qn(`min requires all arguments be DateTimes`);return Hi(t,e=>e.valueOf(),Math.min)}static max(...t){if(!t.every(e.isDateTime))throw new qn(`max requires all arguments be DateTimes`);return Hi(t,e=>e.valueOf(),Math.max)}static fromFormatExplain(e,t,n={}){let{locale:r=null,numberingSystem:i=null}=n;return ys(q.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0}),e,t)}static fromStringExplain(t,n,r={}){return e.fromFormatExplain(t,n,r)}static buildFormatParser(e,t={}){let{locale:n=null,numberingSystem:r=null}=t;return new vs(q.fromOpts({locale:n,numberingSystem:r,defaultToEN:!0}),e)}static fromFormatParser(t,n,r={}){if(Y(t)||Y(n))throw new qn(`fromFormatParser requires an input string and a format parser`);let{locale:i=null,numberingSystem:a=null}=r,o=q.fromOpts({locale:i,numberingSystem:a,defaultToEN:!0});if(!o.equals(n.locale))throw new qn(`fromFormatParser called with a locale of ${o}, but the format parser was created for ${n.locale}`);let{result:s,zone:c,specificOffset:l,invalidReason:u}=n.explainFromTokens(t);return u?e.invalid(u):Ms(s,c,r,`format ${n.format}`,t,l)}static get DATE_SHORT(){return Zn}static get DATE_MED(){return Qn}static get DATE_MED_WITH_WEEKDAY(){return $n}static get DATE_FULL(){return er}static get DATE_HUGE(){return tr}static get TIME_SIMPLE(){return nr}static get TIME_WITH_SECONDS(){return rr}static get TIME_WITH_SHORT_OFFSET(){return ir}static get TIME_WITH_LONG_OFFSET(){return ar}static get TIME_24_SIMPLE(){return or}static get TIME_24_WITH_SECONDS(){return sr}static get TIME_24_WITH_SHORT_OFFSET(){return cr}static get TIME_24_WITH_LONG_OFFSET(){return lr}static get DATETIME_SHORT(){return ur}static get DATETIME_SHORT_WITH_SECONDS(){return dr}static get DATETIME_MED(){return fr}static get DATETIME_MED_WITH_SECONDS(){return pr}static get DATETIME_MED_WITH_WEEKDAY(){return mr}static get DATETIME_FULL(){return hr}static get DATETIME_FULL_WITH_SECONDS(){return gr}static get DATETIME_HUGE(){return _r}static get DATETIME_HUGE_WITH_SECONDS(){return vr}};function Xs(e){if(Q.isDateTime(e))return e;if(e&&e.valueOf&&Fi(e.valueOf()))return Q.fromJSDate(e);if(e&&typeof e==`object`)return Q.fromObject(e);throw new qn(`Unknown datetime argument: ${e}, of type ${typeof e}`)}var Zs=(e,t)=>{let n={};if(e.includeFields){let r=t.collections[e.collection];if(!r)return jn(G());e.includeFields.forEach(e=>{let t=r.fields.find(t=>t.name===e);t?n[e]=ec(t)?.nullable():n[e]=G()})}return kn({Collection_Path:On(wn()),...n})},Qs=(e,t,n,r)=>{let i=kn({}).catchall(Zs(e,t)),a;return!r&&n&&(a=Ce(xe(e,n).admin?.skipFormRequiredValidation)),(!e.required||a)&&(i=i.optional()),i},$s=()=>G().refine(e=>e===null||e&&(e.seconds!==void 0&&e.nanoseconds!==void 0||e._seconds!==void 0&&e._nanoseconds!==void 0),{message:`Must be a valid date`}),ec=(e,t,n)=>{let r,i=`${Ce(e.description)}\n\n`||``,a,o,s;if(!n&&t){let n=xe(e,t);a=n.admin?.condition?.form!==void 0&&!Ce(n.admin.condition.form),o=Ce(n.admin?.skipFormRequiredValidation),s=Ce(n.admin?.image)}switch(e.type){case`String`:r=wn(),e.length&&(r=r.length(e.length,`Must be ${e.length} character(s) long`)),e.minlength&&(r=r.min(e.minlength,`Must contain at least ${e.minlength} character(s)`)),e.maxlength&&(r=r.max(e.maxlength,`Must contain at most ${e.maxlength} character(s)`)),e.email?r=r.email(`Must be a valid email address`):e.uuid?r=An([r.uuid(`Must be a valid UUID`),Mn(``)]):e.url?r=An([r.url(`Must be a valid URL`),Mn(``)]):e.emoji?r=An([r.emoji(`Must be a valid emoji`),Mn(``)]):e.ip?r=An([r.ip(`Must be a valid IP address`),Mn(``)]):e.pattern&&(r=!n&&s?An([r.regex(new RegExp(e.pattern)),r.regex(/^blob:/),Mn(``)],{message:`Must be a valid value`}):An([r.regex(new RegExp(e.pattern),`Must be a valid value`),Mn(``)])),e.values&&(r=An([Nn(e.values,{message:`Must be one of the following values: ${e.values.join(`, `)}`}),Dn()])),i&&(r=r.describe(i.trim()));break;case`Boolean`:r=En(),i&&(r=r.describe(i.trim()));break;case`Number`:e.autoIncrement?r=An([Dn(),Tn().int()],{message:`Must be a valid number`}):(r=Tn({message:`Must be a valid number`}),e.min&&(r=r.min(e.min,`Must be greater than or equal to ${e.min}`)),e.max&&(r=r.max(e.max,`Must be less than or equal to ${e.max}`)),r=e.decimal?n?r.describe(`${i}Must have ${e.decimal} decimal places`):r.refine(t=>e.decimal?(t.toString().split(`.`)[1]?.length||0)<=e.decimal:!1,{message:`Must have ${e.decimal} or fewer decimal places`}):r.int(`Must not have decimal places`),e.values?(n||(r=An([r.refine(t=>e.values?.includes(t),{message:`Must be one of the following values: ${e.values.join(`, `)}`}),Dn()])),r=r.describe(`${i}Must be one of the following values: ${e.values.join(`, `)}`)):i&&(r=r.describe(i.trim())));break;case`Timestamp`:n?(r=kn({seconds:Tn(),nanoseconds:Tn()}),e.min&&e.max?r=r.describe(`${i}Must be between ${Q.fromMillis(e.min).toLocaleString(Q.DATE_MED)} and ${Q.fromMillis(e.max).toLocaleString(Q.DATE_MED)}`):e.min?r=r.describe(`${i}Must be greater than or equal to ${Q.fromMillis(e.min).toLocaleString(Q.DATE_MED)}`):e.max?r=r.describe(`${i}Must be less than or equal to ${Q.fromMillis(e.max).toLocaleString(Q.DATE_MED)}`):i&&(r=r.describe(i.trim()))):(r=$s(),e.min&&(r=r.refine(t=>t.toMillis()>=e.min,{message:`Must be greater than or equal to ${Q.fromMillis(e.min).toLocaleString(Q.DATE_MED)}`})),e.max&&(r=r.refine(t=>t.toMillis()<=e.max,{message:`Must be less than or equal to ${Q.fromMillis(e.max).toLocaleString(Q.DATE_MED)}`})));break;case`Array`:r=On(G()),e.length&&(r=r.length(e.length,`Must contain ${e.length} item(s)`)),e.minlength?r=r.min(e.minlength,`Must contain at least ${e.minlength} item(s)`):e.required&&!a&&(r=r.nonempty(`Must contain at least one item`)),e.maxlength&&(r=r.max(e.maxlength,`Must contain at most ${e.maxlength} item(s)`)),e.values?(n||(r=r.refine(t=>{let n=!0;return t.forEach(t=>{e.values&&!e.values.includes(t)&&(n=!1)}),n},{message:`Must only contain the following values: ${e.values.join(`, `)}`})),r=r.describe(`${i}Must only contain the following values: ${e.values.join(`, `)}`)):i&&(r=r.describe(i.trim())),e.nullable&&(r=r.nullable());break;case`Map`:r=e.required&&!a?n?kn({}).catchall(G()).describe(`${i}Must be an object. Must contain at least one object property.`):jn(G()).refine(e=>e&&typeof e==`object`&&Object.keys(e).length>0,{message:`Must not be an empty value`}):kn({}).catchall(G()).describe(`${i}Must be an object`);break;case`Computed`:r=G()}return(!e.required||a||o)&&(r=r.optional()),r},tc=(e,t,n,r,i)=>{let{auth:a,softDelete:o}=e,s={};e.fields.forEach(e=>{e.type===`Embedding`||r&&e.type===`Computed`||r&&(e.name===o?.archivedField||e.name===o?.timestampField)||(M(e)?(s[e.name]=Qs(e,t,n,r),r?(e.length&&(s[e.name]=s[e.name].describe(`Must contain ${e.length} item(s)`)),e.min&&(s[e.name]=s[e.name].describe(`Must contain at least ${e.min} item(s)`)),e.max&&(s[e.name]=s[e.name].describe(`Must contain at most ${e.max} item(s)`))):(e.length&&(s[e.name]=s[e.name].refine(t=>e.length&&t&&Object.keys(t).length===e.length,{message:`Must contain ${e.length} item(s)`})),e.min&&(s[e.name]=s[e.name].refine(t=>e.min&&t&&Object.keys(t).length>=e.min,{message:`Must contain at least ${e.min} item(s)`})),e.max&&(s[e.name]=s[e.name].refine(t=>e.max&&(!t||Object.keys(t).length<=e.max),{message:`Must contain at most ${e.max} item(s)`})))):s[e.name]=ec(e,n,r),i&&(s[e.name]=s[e.name].optional()))}),!r&&a&&(s.operation=An([Mn(`create`),Mn(`update`),Mn(`delete`)]).optional(),s.password=wn().optional(),s.passwordConfirm=wn().optional(),Object.values(t.collections).forEach(e=>{s[`auth-${e.labels.collection}`]=En().optional(),s[`operations-${e.labels.collection}`]=On(An([Mn(`Read`),Mn(`Create`),Mn(`Update`),Mn(`Delete`)])).optional(),s[`restrict-${e.labels.collection}`]=En().optional(),e.access.attributeRestrictions?.forEach(t=>{s[`attribute-${e.labels.collection}-${t.type}`]=En().optional()}),e.access.entityRestrictions?.restrictions?.forEach(t=>{if(t.type===`Individual`&&(s[`accessible-${e.labels.collection}-${e.labels.collection}`]=kn({}).catchall(G()).optional()),t.type===`Parent`||t.type===`Parent_Property`){let n=j(e.fields,t.collectionField);s[`accessible-${e.labels.collection}-${n.collection}`]=kn({}).catchall(G()).optional()}})}));let c=kn(s);return e.allowSchemalessFields?c.passthrough():c.strict()},nc=async(e,t)=>{if(e){let n=await P(e,[t]);if(!n.valid)throw Error(n.message)}},rc=async(e,t,n,r,i,a)=>{await nc(r.custom?.preValidate,i);for(let e of r.fields)await nc(e.custom?.preValidate,i);return Bn(e,n,a).parse(t),t},ic=(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b)=>{let{fields:x}=o;x.filter(e=>`unique`in e&&e.unique).forEach(a=>{e!==`delete`&&(typeof i[a.name]==`string`||typeof i[a.name]==`number`)&&(t.set(p(a,i[a.name].toString().toLowerCase().replace(/\s/g,`---`).replaceAll(`/`,`|||`)),{id:r,Collection_Path:n}),b&&b.size++)}),x.forEach(r=>{if(Te(r,o,a)){let s=Ne(r,o,a),c={};i[r.name]!==void 0&&(c[r.name]=i[r.name],M(r)&&(c[`${r.name}_Array`]=i[`${r.name}_Array`])),s.forEach(e=>{i[e.name]!==void 0&&(M(e)?c[`${e.name}_Array`]=i[`${e.name}_Array`]:c[e.name]=i[e.name])}),Object.keys(c).length>0&&(e===`create`&&(c.Collection_Path=n,c.Collection_Path_String=n.join(`/`),t.set(f(r),c)),e===`update`&&t.update(f(r),c),e===`delete`&&t.delete(f(r)),b&&b.size++)}});let S=c[o.labels.collection];Object.keys(o.fieldAccessGroups||{}).forEach(r=>{for(let a of S){let s=Ie(r,o,a);if(s.length===0)continue;let c=Fe(r,a.key),l={};s.forEach(e=>{[e.name,`${e.name}_Array`,`${e.name}_Single`,`${e.name}_Lowercase`].forEach(e=>{i[e]!==void 0&&(l[e]=i[e])})}),e===`create`&&(l.Collection_Path||=n,l.Collection_Path_String=n.join(`/`),t.set(m(c),l),b&&b.size++),e===`update`&&Object.keys(l).length>0&&(t.update(m(c),l),b&&b.size++),e===`delete`&&(t.delete(m(c)),b&&b.size++)}});for(let r of S){let a=ze(r,o),s={...i};a.forEach(e=>{delete s[e.name],delete s[`${e.name}_Array`],delete s[`${e.name}_Single`],delete s[`${e.name}_Lowercase`]}),Object.keys(s).length>0&&(e===`create`&&(s.Collection_Path||=n,s.Collection_Path_String=n.join(`/`),t.set(m(r.key),s)),e===`update`&&t.update(m(r.key),s),e===`delete`&&t.delete(m(r.key)),b&&b.size++)}let C=(e,t)=>{let n=1;Te(t,e,a)&&n++,e.fields.forEach(r=>{Te(r,e,a)&&JSON.parse(De(Ne(r,e,a))).includes(t.name)&&n++});let r=c[e.labels.collection];for(let e of r)e.fields.some(e=>e.name===t.name)&&M(t)&&n++;for(let i of Object.keys(e.fieldAccessGroups||{}))for(let a of r)Ie(i,e,a).some(e=>e.name===t.name)&&M(t)&&n++;return n},w=(e,n,i,o,s)=>{let l={};l[`${i.name}.${r}`]=d(),l[`${i.name}_Array`]=u(r),l[`${i.name}_Single`]=d(),t.update(h(s,o),l),Te(i,n,a)&&t.update(g(e,i.name,o),{[`${i.name}.${r}`]:d(),[`${i.name}_Array`]:u(r)}),n.fields.forEach(s=>{Te(s,n,a)&&JSON.parse(De(Ne(s,n,a))).includes(i.name)&&t.update(g(e,s.name,o),{[`${i.name}_Array`]:u(r)})});let f=c[n.labels.collection];for(let n of f)n.fields.some(e=>e.name===i.name)&&M(i)&&t.update(_(e,n.key,o),l);for(let r of Object.keys(n.fieldAccessGroups||{}))for(let a of f){let s=Ie(r,n,a),c=Fe(r,a.key);s.some(e=>e.name===i.name)&&M(i)&&t.update(_(e,c,o),l)}};if(e===`delete`)return;let T=x.filter(e=>M(e)&&e.twoWay);if(!s?.noTwoWay){for(let s of T){if(!b)throw Error(`VALIDATION_ERROR: batchSize is required`);let u=a.collections[s.collection],d=j(u.fields,s.twoWay),f=We(u,u.fields),p=Array.from(f).map(e=>e.name);if(!d)throw Error(`SCHEMA_ERROR: Field ${s.twoWay} not found in collection ${s.collection}`);if(M(d)){if(i[`${s.name}_Array`])for(let[f,m]of Object.entries(i[s.name])){if(e===`update`&&v&&v[`${s.name}_Array`]?.includes(f))continue;let y={...v,...i};pe(y);let x={};d.includeFields&&d.includeFields.forEach(e=>{y[e]!==void 0&&(x[e]=y[e],Ge(o,[j(o.fields,e)]).size===1&&(x[`${e}_Lowercase`]=y[`${e}_Lowercase`]))});let S={[`${s.twoWay}.${r}`]:{Collection_Path:n,...x},[`${s.twoWay}_Array`]:l(r)};p.includes(d.name)&&(S[`${s.twoWay}_Single`]={Collection_Path:n,id:r,...x});let C=Ve(i);t.update(h(m.Collection_Path,f),{...S,...C}),b.size++,Te(d,u,a)&&(t.update(g(s,d.name,f),{[`${d.name}.${r}`]:{Collection_Path:n,...x},[`${d.name}_Array`]:l(r)}),b.size++),u.fields.forEach(e=>{if(Te(e,u,a)){let n=JSON.parse(De(Ne(e,u,a))),i={};n.includes(d.name)&&(i[`${s.twoWay}_Array`]=l(r)),Object.keys(C).forEach(e=>{n.includes(e)&&(i[e]=C[e])}),Object.keys(i).length>0&&(t.update(g(s,e.name,f),i),b.size++)}});let w=c[u.labels.collection];for(let e of w)if(e.fields.some(e=>e.name===d.name)){let n={...S};Object.keys(C).forEach(t=>{e.fields.some(e=>e.name===t)&&(n[t]=C[t])}),Object.keys(n).length>0&&(t.update(_(s,e.key,f),n),b.size++)}for(let e of Object.keys(u.fieldAccessGroups||{}))for(let n of w){let r=Ie(e,u,n),i=Fe(e,n.key);if(r.some(e=>e.name===d.name)){let e={...S};Object.keys(C).forEach(t=>{r.some(e=>e.name===t)&&(e[t]=C[t])}),Object.keys(e).length>0&&(t.update(_(s,i,f),e),b.size++)}}}}else throw Error(`SCHEMA_ERROR: Invalid field type: ${d.type}`)}b&&b.size>500&&console.error(Error(`VALIDATION_ERROR: ${b.size} operations in the Firestore transaction has exceeded the recommended limit of 500. This is likely due to a large number of two way updates, roles, dependencies on the collection, unique field checks, entity restrictions (in permissions when dealing with user collections) or relation hierarchy checks.`));for(let t of T){if(!b)throw Error(`VALIDATION_ERROR: batchSize is required`);let n=a.collections[t.collection],r=j(n.fields,t.twoWay);if(!r)throw Error(`SCHEMA_ERROR: Field ${t.twoWay} not found in collection ${t.collection}`);if(M(r)){if(e===`update`&&v&&!(i[t.name]&&fe(i[t.name]))&&i[`${t.name}_Array`]&&v[`${t.name}_Array`]?.length>0)for(let[e,a]of Object.entries(v[t.name]))!i[`${t.name}_Array`].includes(e)&&!y?.get(t.name)?.includes(e)&&(b.size+=C(n,r),b.size<=500&&w(t,n,r,e,a.Collection_Path))}else throw Error(`SCHEMA_ERROR: Invalid field type: ${r.type}`)}for(let t of T){if(!b)throw Error(`VALIDATION_ERROR: batchSize is required`);let n=a.collections[t.collection],r=j(n.fields,t.twoWay);if(!r)throw Error(`SCHEMA_ERROR: Field ${t.twoWay} not found in collection ${t.collection}`);if(M(r)){if(e===`update`&&v&&i[t.name]&&fe(i[t.name])&&v[`${t.name}_Array`]?.length>0)for(let[e,i]of Object.entries(v[t.name]))y?.get(t.name)?.includes(e)||(b.size+=C(n,r),b.size<=500&&w(t,n,r,e,i.Collection_Path))}else throw Error(`SCHEMA_ERROR: Invalid field type: ${r.type}`)}}},ac=e=>{for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&(e[t]===void 0?delete e[t]:typeof e[t]==`object`&&e[t]!==null&&ac(e[t]))},oc=e=>{if(e=e.toString(),/[/]|^\.+$|^__.*__$/.test(e))return!1;try{let t=new TextEncoder().encode(e),n=new TextDecoder().decode(t);if(e!==n)return!1}catch{return!1}return!(new Blob([e]).size>1500)},sc=async(e,t,n,r=1e3,i=5)=>{for(;i>0;)try{await e(...t);break}catch(e){if(i--,i===0)throw e;n&&n(e),await new Promise(e=>setTimeout(e,r)),r*=2}},cc=e=>{if(!e||typeof e!=`string`)return``;let t=e.replace(/[\r\n]/g,``);if(t=t.replace(/\0/g,``),t=t.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,``),t=t.trim(),t.length>254)throw Error(`Email address is too long`);return t},lc=e=>e?Array.isArray(e)?e.map(e=>cc(e)).filter(e=>e.length>0):cc(e)||``:``,uc=e=>{if(!e||typeof e!=`string`)return``;let t=e.replace(/[\r\n]/g,` `);if(t=t.replace(/\0/g,``),t=t.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,``),t=t.trim(),t.length>998)throw Error(`Email subject is too long`);return t},dc=e=>{if(!e||typeof e!=`string`)return``;let t=e.replace(/\0/g,``);if(t=t.replace(/\r\n\r\n/g,`
|
|
2
2
|
|
|
3
3
|
`),t=t.replace(/\r\n/g,`
|
|
4
|
-
`),t.length>5e6)throw Error(`Email body is too long`);return t},fc=(e=`enterprise`,t)=>e===`enterprise`?t:`(default)`,$=()=>{let e=(0,f.getApp)(),t=process.env.STOKER_FB_WEB_APP_CONFIG;if(!t)throw Error(`STOKER_FB_WEB_APP_CONFIG not set.`);let n=JSON.parse(t),r=fc(process.env.FB_FIRESTORE_EDITION,n.projectId);return(0,p.getFirestore)(e,r)},pc=async(e,t)=>{let n={};for(let r of t){let t=`${e}/${r}.js`;n[r]=await import((0,m.pathToFileURL)(t).href)}return n},mc,hc,gc,_c,vc,yc,bc,xc,Sc=0,Cc=!1,wc={getTenant(){if(!gc)throw Error(`Tenant not provided`);return gc},setTenant(e){gc=e},getMode(){return hc},getTimezone(){return _c},getGlobalConfigModule(){return(0,d.default)(vc)},getCustomizationFile(e,t){if(!Object.keys(t.collections).includes(e))throw Error(`PERMISSION_DENIED`);let n=be([e],yc,`node`,wc);return(0,d.default)(n?.[e])},getVersionInfo(){return bc},getMaintenanceInfo(){return xc},getStokerFirestore:$},Tc=async(e,t,n,r,i)=>{let a=!!Cc;if(Cc=!0,t&&(gc=t),hc=e,mc&&!i)return wc;if(!process.env.STOKER_FB_WEB_APP_CONFIG)throw Error(`STOKER_FB_WEB_APP_CONFIG not set.`);let o=process.env.STOKER_FB_WEB_APP_CONFIG,s=JSON.parse(o),c=(await import((0,m.pathToFileURL)(n).href)).default;vc=c({sdk:`node`,utils:wc}),!i&&e===`development`&&(process.env.FIREBASE_AUTH_EMULATOR_HOST=`127.0.0.1:9099`,process.env.FIREBASE_DATABASE_EMULATOR_HOST=`127.0.0.1:9000`,process.env.FIRESTORE_EMULATOR_HOST=`127.0.0.1:8080`,process.env.FIREBASE_STORAGE_EMULATOR_HOST=`127.0.0.1:9199`);try{mc=(0,f.getApp)()}catch{mc=(0,f.initializeApp)({credential:(0,f.applicationDefault)(),databaseURL:s.databaseURL,storageBucket:s.storageBucket,projectId:s.projectId})}let l=await Ic();return yc=await pc(r,Object.keys(l.collections)),_c=await P(vc.timezone),a||$().collection(`system_deployment`).doc(`maintenance_mode`).onSnapshot(e=>{e.exists?(xc=e.data(),P(vc.onMaintenanceUpdate,[`node`,xc.active?`on`:`off`])):console.error(`Maintenance status not found`)},e=>{console.error(e.message)}),a||$().collection(`system_deployment`).doc(`latest_deploy`).onSnapshot(e=>{e.exists?(bc=e.data(),Sc++,Sc>1&&P(vc.onVersionUpdate,[`node`,bc,Sc])):console.error(`Version info not found`)},e=>{console.error(e.message)}),await new Promise(e=>{let t=()=>{xc&&bc?e(wc):setTimeout(t,100)};t()}),wc},{getTenant:Ec,setTenant:Dc,getMode:Oc,getTimezone:kc,getGlobalConfigModule:Ac,getCustomizationFile:jc,getVersionInfo:Mc,getMaintenanceInfo:Nc}=wc,Pc=async(e,t,n,r)=>new Promise((i,a)=>{let o=(0,h.default)(e,t,{cwd:n||process.cwd(),env:{...process.env,...r}}),s=``,c=()=>{o.kill(`SIGINT`)},l=()=>{o.kill(`SIGTERM`)},u=()=>{process.removeListener(`SIGINT`,c),process.removeListener(`SIGTERM`,l)};o.stdout?.on(`data`,e=>{s+=e.toString(),console.log(e.toString())}),o.stderr?.on(`data`,e=>{console.log(e.toString())}),o.on(`exit`,e=>{u(),e===0?i(s):a()}),process.on(`SIGINT`,c),process.on(`SIGTERM`,l)}),Fc=async()=>{let e=process.env.STOKER_FB_WEB_APP_CONFIG;if(!e)throw Error(`Firebase web app config not found`);let t=JSON.parse(e);try{return(0,f.getApp)()}catch{return(0,f.initializeApp)({credential:(0,f.applicationDefault)(),databaseURL:t.databaseURL,storageBucket:t.storageBucket,projectId:t.projectId})}},Ic=async(e=!1)=>{let t=await(0,g.getDatabase)().ref(`schema`).orderByChild(`published_time`).limitToLast(1).get(),n=Object.values(t.val())[0];if(e){for(let e of Object.values(n.collections))for(let t of e.fields)if(t.type===`Computed`){let r=xe(t,jc(e.labels.collection,n));r.formula&&(t.formula=r.formula)}}else for(let e of Object.values(n.collections))e.fields=e.fields.filter(e=>e.type!==`Computed`);return n},Lc=async()=>{let e=await(0,g.getDatabase)().ref(`schema`).orderByChild(`published_time`).limitToLast(2).get();if(!(e.numChildren()<2))return Object.values(e.val())[0]},Rc=(e,t,n)=>{let r=e.collection(`tenants`).doc(n);for(let e=0;e<t.length;e++)r=e%2==0?r.collection(t[e]):r.doc(t[e]);return r},zc=(e,t,n,r,i,a)=>{let o=$(),s=t.at(-1);if(!s)throw Error(`EMPTY_PATH`);let c=n.collections[s],{labels:l,fields:u,preloadCache:d}=c,f=jc(s,n),p=Rc(o,t,e);if(!i)return[p];if(r){let s=i.collections?.[l.collection];if(!i.Role)throw Error(`PERMISSION_DENIED`);let p=s&&T(`Read`,s),m=N(c,n,i,a??{}),h=ee(c,i),g=te(c,i),_=ne(c,n,i),v=(r=[])=>{let s=[],u=Re(i.Role,c,n);if(!u)throw Error(`PERMISSION_DENIED`);if(p){let n=o.collection(`tenants`).doc(e).collection(`system_fields`).doc(l.collection).collection(`${l.collection}-${u.key}`).where(`Collection_Path_String`,`==`,t.join(`/`));r.forEach(e=>{n=n.where(...e)}),s.push(n);let d=x(c);Object.entries(c.fieldAccessGroups||{}).forEach(([n,c])=>{if(!d[n]?.length||!S(c,l.collection,i,a??{}))return;let f=Fe(n,u.key),p=o.collection(`tenants`).doc(e).collection(`system_fields`).doc(l.collection).collection(`${l.collection}-${f}`).where(`Collection_Path_String`,`==`,t.join(`/`));r.forEach(e=>{p=p.where(...e)}),s.push(p)})}else if(m)for(let n of m){let i=o.collection(`tenants`).doc(e).collection(`system_fields`).doc(l.collection).collection(`${l.collection}-${n.field}`).where(`Collection_Path_String`,`==`,t.join(`/`));r.forEach(e=>{i=i.where(...e)}),s.push(i)}return s},y=h.filter(e=>`operations`in e&&e.operations?e.operations.includes(`Read`):!0);if(y.length===0&&g.length===0&&_.length===0)return v();let b=0,C=e=>{e&&(b===0?b=e:b*=e)};if(y.length>0){for(let e of y)if(e.operations&&e.type===`Record_Property`){let t=e.roles.find(e=>e.role===i.Role);if(!t)throw Error(`PERMISSION_DENIED`);C(t.values?.length)}}d?.roles.includes(i.Role)&&d.range&&C(d.range.fields.length);let w=f.admin?.statusField;w&&!d?.roles.includes(i.Role)&&C(Math.max(w.active?.length||0,w.archived?.length||0));let E=b===0?30:Math.max(1,Math.floor(30/b)),D=[];y.filter(e=>e.type===`Record_Owner`).forEach(()=>D.push([`Created_By`,`==`,r])),y.filter(e=>e.type===`Record_User`).forEach(e=>{if(`collectionField`in e){let t=j(u,e.collectionField);D.push([`${t.name}_Array`,`array-contains`,i.Doc_ID])}}),y.filter(e=>e.type===`Record_Property`).forEach(e=>{if(`propertyField`in e){let t=e.roles.find(e=>e.role===i.Role);if(!t)throw Error(`PERMISSION_DENIED`);let n=j(u,e.propertyField);n.type===`Array`?D.push([`${n.name}_Array`,`array-contains-any`,t.values]):D.push([n.name,`in`,t.values])}});let O=[];g.filter(e=>e.type===`Individual`).forEach(e=>{let t=s?.individualEntities,n=[];if(t){let r=e.singleQuery?e.singleQuery:E;for(let e=0;e<t.length;e+=r){let i=t.slice(e,e+r);n.push(i)}if(!e.singleQuery)n.forEach(e=>{O.push(...v(D.concat([[`id`,`in`,e]])))});else{if(t.length>r)throw Error(`INPUT_ERROR: Individual entity restriction with singleQuery set to true must not have more than ${e.singleQuery} entities`);D.push([`id`,`in`,t])}}}),_.filter(e=>e.parentFilter.type===`Individual`).forEach(e=>{let{parentFilter:t,parentRestriction:n}=e;if(`collectionField`in t){let e=j(u,t.collectionField);if(`collection`in e){let t=i.collections?.[e.collection];if(!t)throw Error(`PERMISSION_DENIED`);let r=t.individualEntities,a=[];if(r){let t=n.singleQuery?n.singleQuery:E;for(let e=0;e<r.length;e+=t){let n=r.slice(e,e+t);a.push(n)}if(!n.singleQuery)a.forEach(t=>{O.push(...v(D.concat([[`${e.name}_Array`,`array-contains-any`,t]])))});else{if(r.length>t)throw Error(`INPUT_ERROR: Individual entity parentFilter with singleQuery set to true must not have more than ${n.singleQuery} entities`);D.push([`${e.name}_Array`,`array-contains-any`,r])}}}}});let k=[];g.filter(e=>e.type===`Parent`).forEach(e=>{if(`collectionField`in e){let t=j(u,e.collectionField);if(`collection`in t){let n=s?.parentEntities,r=[];if(n){let i=e.singleQuery?e.singleQuery:E;for(let e=0;e<n.length;e+=i){let t=n.slice(e,e+i);r.push(t)}if(!e.singleQuery)r.forEach(e=>{k.push(...v(D.concat([[`${t.name}_Array`,`array-contains-any`,e]])))});else{if(n&&n.length>i)throw Error(`INPUT_ERROR: Parent entity restriction with singleQuery set to true must not have more than ${e.singleQuery} entities`);D.push([`${t.name}_Array`,`array-contains-any`,n])}}}}}),_.filter(e=>e.parentFilter.type===`Parent`).forEach(e=>{let{parentFilter:t,parentRestriction:n}=e;if(`collectionField`in t&&`parentCollectionField`in t){let e=j(u,t.collectionField),r=j(u,t.parentCollectionField);if(`collection`in e&&`collection`in r){let t=i.collections?.[e.collection];if(!t)throw Error(`PERMISSION_DENIED`);let a=t.parentEntities,o=[];if(a){let e=n.singleQuery?n.singleQuery:E;for(let t=0;t<a.length;t+=e){let n=a.slice(t,t+e);o.push(n)}if(!n.singleQuery)o.forEach(e=>{k.push(...v(D.concat([[`${r.name}_Array`,`array-contains-any`,e]])))});else{if(a&&a.length>e)throw Error(`INPUT_ERROR: Profile_Parent entity parentFilter with singleQuery set to true must not have more than ${n.singleQuery} entities`);D.push([`${r.name}_Array`,`array-contains-any`,a])}}}}});let A=[];k.length===0&&(g.filter(e=>e.type===`Parent_Property`).forEach(e=>{if(`collectionField`in e&&`propertyField`in e){let t=j(u,e.collectionField),n=j(u,e.propertyField);if(`collection`in t){let e=s?.parentPropertyEntities||{};Object.entries(e).forEach(([e,r])=>{if(r.length>0){let i=[];for(let e=0;e<r.length;e+=E){let t=r.slice(e,e+E);i.push(t)}i.forEach(r=>{A.push(...v(D.concat([[`${t.name}_Array`,`array-contains-any`,r],[n.name,`==`,e]])))})}})}}}),_.filter(e=>e.parentFilter.type===`Parent_Property`).forEach(e=>{let{parentFilter:t}=e;if(`collectionField`in t&&`parentCollectionField`in t&&`parentPropertyField`in t){let e=j(u,t.collectionField),n=j(u,t.parentCollectionField),r=j(u,t.parentPropertyField);if(`collection`in e&&`collection`in n){let t=i.collections?.[e.collection];if(!t)throw Error(`PERMISSION_DENIED`);let a=t.parentPropertyEntities||{};Object.entries(a).forEach(([e,t])=>{if(t.length>0){let i=[];for(let e=0;e<t.length;e+=E){let n=t.slice(e,e+E);i.push(n)}i.forEach(t=>{A.push(...v(D.concat([[`${n.name}_Array`,`array-contains-any`,t],[r.name,`==`,e]])))})}})}}}));let M=[...O,...k,...A];return!g.length&&!_.length?v(D):M}throw Error(`PERMISSION_DENIED`)},Bc=(e,t,n,r,i,a)=>{let o=$(),s=t.at(-1);if(!s)throw Error(`EMPTY_PATH`);let c=r.collections[s],{labels:l}=c,u=Rc(o,t,e);if(i){let t=i.collections?.[l.collection];if(!i.Role)throw Error(`PERMISSION_DENIED`);let s=t&&T(`Read`,t),u=N(c,r,i,a??{}),d=[],f=Re(i.Role,c,r);if(!f)throw Error(`PERMISSION_DENIED`);if(s){d.push(o.collection(`tenants`).doc(e).collection(`system_fields`).doc(l.collection).collection(`${l.collection}-${f.key}`).doc(n));let t=x(c);Object.entries(c.fieldAccessGroups||{}).forEach(([r,s])=>{if(!t[r]?.length||!S(s,l.collection,i,a??{}))return;let c=Fe(r,f.key);d.push(o.collection(`tenants`).doc(e).collection(`system_fields`).doc(l.collection).collection(`${l.collection}-${c}`).doc(n))})}else if(u)for(let t of u)d.push(o.collection(`tenants`).doc(e).collection(`system_fields`).doc(l.collection).collection(`${l.collection}-${t.field}`).doc(n));return d}return[u.doc(n)]},Vc=async e=>await(0,_.getAuth)().getUser(e),Hc=async(e,t,n,r,i,a,o,s,c,l)=>{let u=n.at(-2),d=ae(i.collections[u],i).map(e=>e.labels.collection);r.collections?r.collections.forEach(e=>{if(!d.includes(e))throw Error(`SCHEMA_ERROR: Collection ${e} not found in subcollections of ${u}`)}):r.collections=d;let f=r.depth-1,p=r.collections.map(async u=>{t[u]=(await Wc([...n,u],{constraints:r.constraints,userId:s,pagination:r.limit,providedTransaction:c,noEmbeddingFields:l}).catch(e=>{throw e.code===`permission-denied`&&console.info(`PERMISSION_DENIED for subcollection ${u} for document at ${n.join(`/`)}`),e})).records,a&&await Promise.all(t[u].map(t=>Uc(e,t,[...n,u,t.id],a,i,void 0,s,c,l))),f>0&&await Promise.all(t[u].map(t=>Hc(e,t,[...n,u,t.id],{depth:f},i,a,o,s,c,l)))});await Promise.all(p)},Uc=async(e,t,n,r,i,a,o,s,c)=>{let l=n.at(-2);r.fields||=i.collections[l].fields.filter(e=>M(e));let u=r.depth-1,d=[];for(let n of r.fields)if(`collection`in n){let r=t[n.name];if(!r)continue;let l=Object.keys(r);for(let t of l){let n=r[t],l=qc(n.Collection_Path,t,{userId:o,providedTransaction:s,noEmbeddingFields:c}).then(l=>{if(r[t]=l,u>0)return Uc(e,r[t],[...n.Collection_Path,t],{depth:u},i,a,o,s,c)}).catch(e=>{if(e.message.includes(`NOT_FOUND`)||e.code===`permission-denied`)delete r[t];else throw e});d.push(l)}}await Promise.all(d)},Wc=async(e,t)=>{if(t?.subcollections?.depth&&t.subcollections.depth>10)throw Error(`INPUT_ERROR: Subcollections depth cannot exceed 10`);if(t?.relations?.depth&&t.relations.depth>10)throw Error(`INPUT_ERROR: Relations depth cannot exceed 10`);if(t?.pagination?.number!==void 0){let e=t.pagination.number;if(typeof e!=`number`||!Number.isFinite(e)||!Number.isInteger(e)||e<1)throw Error(`INPUT_ERROR: Pagination number must be a positive finite integer`)}let n=t?.constraints,r=Ec(),i=$(),a,o,s,c=async c=>{let[l,u,f,p]=await Promise.all([t?.userId?c.get(i.collection(`tenants`).doc(r).collection(`system_user_permissions`).doc(t.userId)):Promise.resolve({}),c.get(i.collection(`system_deployment`).doc(`maintenance_mode`)),Ic(!0),t?.userId?Vc(t.userId):Promise.resolve(void 0)]);if(!u.exists||u.data().active)throw Error(`MAINTENANCE_MODE`);let m=f,h,g=Ac(),_=e.at(-1);if(!_)throw Error(`EMPTY_PATH`);let v=Object.keys(m.collections).includes(_),y=g.disabledCollections?.includes(_);if(!v||y)throw Error(`COLLECTION_NOT_FOUND`);let b=m.collections[_],{labels:x}=b,S=jc(x.collection,m);if(t?.userId){if(!l?.exists)throw Error(`PERMISSION_DENIED`);if(h=l.data(),!h.Role)throw Error(`USER_ERROR`);if(!h.Enabled)throw Error(`PERMISSION_DENIED`)}let C=zc(r,e,m,t?.userId,h,p?.customClaims??{});if(C.length===0)return{cursor:{},pages:0,records:[]};if(n&&(C=C.map(e=>(n.forEach(([t,n,r])=>{e=e.where(t,n,r)}),e))),o=t?.pagination?.startAfter||t?.pagination?.endBefore||{first:new Map,last:new Map},t?.pagination){if(t.pagination.startAfter&&t.pagination.endBefore)throw Error(`INPUT_ERROR: startAfter and endBefore cannot be provided together`);let e=t.pagination.startAfter||t.pagination.endBefore;if(t?.userId){let t=ye(h.Role,b,m);if(e&&t!==!0)throw Error(`INPUT_ERROR: Pagination is not allowed when using `+t)}C=t.pagination.orderByField&&t.pagination.orderByDirection?!t.pagination.startAfter&&!t.pagination.endBefore?C.map(e=>e.orderBy(t.pagination.orderByField,t.pagination.orderByDirection).limit(t.pagination.number)):t.pagination.startAfter?C.map((e,n)=>e.orderBy(t.pagination.orderByField,t.pagination.orderByDirection).startAfter(o.last.get(n)).limit(t.pagination.number)):C.map((e,n)=>e.orderBy(t.pagination.orderByField,t.pagination.orderByDirection).endBefore(o.first.get(n)).limitToLast(t.pagination.number)):!t.pagination.startAfter&&!t.pagination.endBefore?C.map(e=>e.limit(t.pagination.number)):t.pagination.startAfter?C.map((e,n)=>e.startAfter(o.last.get(n)).limit(t.pagination.number)):C.map((e,n)=>e.endBefore(o.first.get(n)).limitToLast(t.pagination.number))}let w={};await F(`preOperation`,g,S,{operation:`read`,context:w}),await F(`preRead`,g,S,{context:w,refs:C,multiple:!0,listener:!1}),s=new Map;let T=C.map(async e=>await c.get(e)),D=await Promise.all(T);for(let e of D){for(let t of e.docs){s.has(t.id)||s.set(t.id,{});let e=t.data(),n=s.get(t.id);n.id||=t.id;let r={...n,...e};delete r.Collection_Path_String,s.set(t.id,r)}o.first.set(D.indexOf(e),e.docs[0]),o.last.set(D.indexOf(e),e.docs.at(-1)||e.docs[0])}if(t?.pagination){let e=C[0];n&&(e=n.reduce((e,[t,n,r])=>e.where(t,n,r),e)),t.pagination.orderByField&&t.pagination.orderByDirection&&(e=e.orderBy(t.pagination.orderByField,t.pagination.orderByDirection));let r=(await e.count().get()).data().count,i=t.pagination.number;a=i>0?Math.ceil(r/i):0}let O;t?.noComputedFields||(O=await P(S.admin?.retriever));for(let e of s.values()){let n=[],i=[...e.Collection_Path,e.id];t?.subcollections&&n.push(Hc(r,s.get(e.id),i,(0,d.default)(t.subcollections),m,(0,d.default)(t?.relations),void 0,t.userId,t.transactional?c:void 0,t?.noEmbeddingFields)),t?.relations&&(t.relations.fields&&(t.relations.fields=t.relations.fields.map(e=>{if(typeof e==`string`){let t=b.fields.find(t=>t.name===e);if(t)return t;throw Error(`SCHEMA_ERROR: Field ${e} not found in collection ${_}`)}return e})),n.push(Uc(r,s.get(e.id),i,(0,d.default)(t.relations),m,void 0,t.userId,t.transactional?c:void 0,t?.noEmbeddingFields))),await Promise.all(n);let a=[];for(let n of b.fields){if(n.type===`Computed`&&!t?.noComputedFields){let t=xe(n,S);if(!t.formula)continue;a.push(P(t.formula,[e,O]).then(t=>{e[n.name]=t}))}t?.noEmbeddingFields&&n.type===`Embedding`&&delete e[n.name]}if(await Promise.all(a),t?.userId&&h?.Role){if(!p)throw Error(`USER_ERROR`);if(!(S.custom?.serverAccess?.read===void 0||await P(S.custom.serverAccess.read,[h,p,e]))){s.delete(e.id);continue}for(let t of b.fields){let n=!t.access||E(t,h,b,p?.customClaims??{}),r=xe(t,S),i=r?.custom?.serverAccess?.read===void 0||await P(r.custom.serverAccess.read,[h,p,e]);(!n||!i)&&(M(t)?(delete s.get(e.id)[t.name],delete s.get(e.id)[`${t.name}_Array`],delete s.get(e.id)[`${t.name}_Single`]):delete s.get(e.id)[t.name])}}await F(`postOperation`,g,S,{operation:`read`,data:e,recordId:e.id,context:w}),await F(`postRead`,g,S,{context:w,refs:C,record:e,listener:!1})}t?.userId&&await _e(Array.from(s.values()),b,m,t.userId,h)};return t?.providedTransaction?await c(t.providedTransaction):await i.runTransaction(async e=>{await c(e)},{readOnly:!0}),{cursor:o,pages:a,records:Array.from(s.values())}},Gc=async(e,t,n,r,i,a,o,s)=>{let c=r.at(-2),l=ae(a.collections[c],a).map(e=>e.labels.collection);i.collections?i.collections.forEach(e=>{if(!l.includes(e))throw Error(`SCHEMA_ERROR: Collection ${e} not found in subcollections of ${c}`)}):i.collections=l;let u=i.depth-1,d=i.collections.map(async c=>{n[c]=(await Wc([...r,c],{constraints:i.constraints||[],userId:s,relations:o,pagination:i.limit,providedTransaction:t}).catch(e=>{throw e.code===`permission-denied`&&console.info(`PERMISSION_DENIED for subcollection ${c} for document at ${r.join(`/`)}`),e})).records,u>0&&await Promise.all(n[c].map(async n=>{await Gc(e,t,n,[...r,c,n.id],{depth:u},a,o,s)}))});await Promise.all(d)},Kc=async(e,t,n,r,i,a,o,s,c)=>{let l=r.at(-2);a.fields||=i.collections[l].fields.filter(e=>M(e));let u=a.depth-1,d=[];for(let r of a.fields)if(`collection`in r){let a=n[r.name];if(!a)continue;for(let[n,r]of Object.entries(a)){let l=qc(r.Collection_Path,n,{userId:o,providedTransaction:t,noComputedFields:s,noEmbeddingFields:c}).then(l=>{if(a[n]=l,u>0)return Kc(e,t,a[n],[...r.Collection_Path,n],i,{depth:u},o,s,c)}).catch(e=>{if(e.message.includes(`NOT_FOUND`)||e.code===`permission-denied`)delete a[n];else throw e});d.push(l)}}await Promise.all(d)},qc=async(e,t,n)=>{if(n?.subcollections?.depth&&n.subcollections.depth>10)throw Error(`INPUT_ERROR: Subcollections depth cannot exceed 10`);if(n?.relations?.depth&&n.relations.depth>10)throw Error(`INPUT_ERROR: Relations depth cannot exceed 10`);let r=Ec(),i=$(),a,o=async o=>{let[s,c,l,u]=await Promise.all([n?.userId?o.get(i.collection(`tenants`).doc(r).collection(`system_user_permissions`).doc(n.userId)):Promise.resolve({}),o.get(i.collection(`system_deployment`).doc(`maintenance_mode`)),Ic(!0),n?.userId?Vc(n.userId):Promise.resolve(void 0)]);if(!c.exists||c.data().active)throw Error(`MAINTENANCE_MODE`);let d=l,f,p=Ac(),m=e.at(-1);if(!m)throw Error(`EMPTY_PATH`);let h=Object.keys(d.collections).includes(m),g=p.disabledCollections?.includes(m);if(!h||g)throw Error(`COLLECTION_NOT_FOUND`);let _=d.collections[m],{labels:v}=_,y=jc(v.collection,d),b;if(n?.userId){if(!s?.exists)throw Error(`PERMISSION_DENIED`);if(f=s.data(),!f.Role)throw Error(`USER_ERROR`);if(!f.Enabled||(b=f.collections?.[v.collection],!b))throw Error(`PERMISSION_DENIED`)}if(n?.userId&&(!b||!T(`Read`,b)))throw Error(`PERMISSION_DENIED`);let x=Bc(r,e,t,d,f,u?.customClaims??{});if(x.length===0)throw Error(`PERMISSION_DENIED`);let S={};await F(`preOperation`,p,y,{operation:`read`,recordId:t,context:S}),await F(`preRead`,p,y,{context:S,refs:x,multiple:!1,listener:!1}),a={};let C=x.map(e=>o.get(e)),w=await Promise.all(C);for(let n of w)if(n.exists){let e=n.data();a.id||=n.id,a={...a,...e},delete a.Collection_Path_String}else throw Error(`NOT_FOUND: Document with ID ${t} does not exist at location ${e?.join(`/`)||v.collection}`);let D=[],O=e?[...e,t]:[v.collection,t];if(n?.subcollections&&D.push(Gc(r,o,a,O,n.subcollections,d,void 0,n.userId)),n?.relations&&(n.relations.fields&&(n.relations.fields=n.relations.fields.map(e=>{if(typeof e==`string`){let t=_.fields.find(t=>t.name===e);if(t)return t;throw Error(`SCHEMA_ERROR: Field ${e} not found in collection ${m}`)}return e})),D.push(Kc(r,o,a,O,d,n.relations,n.userId,n.noComputedFields,n.noEmbeddingFields))),await Promise.all(D),!n?.noComputedFields){for(let e of _.fields)if(e.type===`Computed`){let t=xe(e,y);if(!t.formula)continue;a[e.name]=await t.formula(a)}}if(n?.noEmbeddingFields)for(let e of _.fields)e.type===`Embedding`&&delete a[e.name];if(n?.userId&&f?.Role){if(!u)throw Error(`USER_ERROR`);if(!(y.custom?.serverAccess?.read===void 0||await P(y.custom?.serverAccess?.read,[f,u,a])))throw Error(`PERMISSION_DENIED`);for(let e of _.fields){let t=!e.access||E(e,f,_,u?.customClaims??{}),n=xe(e,y),r=n?.custom?.serverAccess?.read===void 0||await P(n.custom.serverAccess.read,[f,u,a]);(!t||!r)&&(M(e)?(delete a[e.name],delete a[`${e.name}_Array`],delete a[`${e.name}_Single`]):delete a[e.name])}}await F(`postOperation`,p,y,{operation:`read`,data:a,recordId:t,context:S}),await F(`postRead`,p,y,{context:S,refs:x,record:a,listener:!1}),n?.userId&&await ge(a,_,d,n.userId,f)};return n?.providedTransaction?await o(n.providedTransaction):await i.runTransaction(async e=>{await o(e)},{readOnly:!0}),a},Jc=async(e,t,n,r,i,a,o,s,c)=>{let{labels:l}=o,u=$(),f=await P(Ac().firebase?.writeLogTTL),m={operation:e,collection:l.collection,docId:a,user:`System`,status:t,Collection_Path:i,Last_Write_At:n.Last_Write_At,Last_Write_By:n.Last_Write_By,Last_Write_Connection_Status:n.Last_Write_Connection_Status,Last_Write_App:n.Last_Write_App,Last_Write_Version:n.Last_Write_Version,data:{}};if(f){let e=new Date,t=new Date(new Date().setDate(e.getDate()+f));m.TTL=p.Timestamp.fromDate(t)}let h=(0,d.default)(n);pe(h),e!==`delete`&&(m.data.data=(0,d.default)(h)),e===`update`&&(m.data.originalRecord=(0,d.default)(c)),e!==`delete`&&[`started`,`written`].includes(t)&&(delete m.data.data.Saved_At,delete m.data.data.Last_Save_At),t===`failed`&&(m.data.error=JSON.stringify(s));let g=Rc(u,i,r),_=n.Last_Write_At;await g.doc(a).collection(`system_write_log`).doc(`${n.Last_Write_By}-${_.valueOf()}`).set(m)},Yc=async e=>{let t=Ec(),n=(0,_.getAuth)(),r=$(),i=[];if(await Promise.all([(async()=>{try{await r.collection(`tenants`).doc(t).collection(`system_user_permissions`).doc(e.User_ID).delete()}catch(e){i.push(`Error deleting user permissions:\n${e}`)}})(),(async()=>{try{await n.deleteUser(e.User_ID)}catch(e){if(e.code===`auth/user-not-found`)return;i.push(`Error deleting user:\n${e}`)}})()]),i.length>0)throw Error(i.join(`, `))},Xc=async(e,t,n,r,i,a,o,s,c)=>{let l=$(),u=Oc(),d=process.env.ADMIN_EMAIL;if(u===`development`||process.env.FIRESTORE_EMULATOR_HOST){if(d)e=d;else throw Error(`Admin email not set`)}let f=lc(e),p=uc(t),m=n?dc(n):void 0,h=r?dc(r):void 0,g=i?lc(i):void 0,_=a?lc(a):void 0,v=o?cc(o):void 0,y=c?cc(c):void 0,b=Array.isArray(f)?f:[f];if(b.length===0||b.length===1&&!b[0])throw Error(`No valid email addresses provided`);let x={to:f,message:{subject:p}};if(m&&(x.message.text=m),h&&(x.message.html=h),g){let e=Array.isArray(g)?g:[g];e.length>0&&e[0]&&(x.cc=g)}if(_){let e=Array.isArray(_)?_:[_];e.length>0&&e[0]&&(x.bcc=_)}v&&(x.replyTo=v),s&&(x.message.attachments=s),y&&(x.from=y),await l.collection(`system_mail`).add(x)},Zc=new Set([`tenant`,`role`,`collection`,`doc`]);function Qc(e){return Zc.has(e)}function $c(e){if(!e)return{};let t={};for(let n of Object.keys(e))Zc.has(n)||(t[n]=e[n]);return t}var el=async(e,t,n,r,i,a,o)=>{let s=(0,_.getAuth)(),c=$(),{labels:l,fields:u}=r;if(fe(i.Email)||!i.Email)throw Error(`VALIDATION_ERROR: Email field is required`);if(fe(i.Role)||!i.Role)throw Error(`VALIDATION_ERROR: Role field is required`);if(i.Enabled===void 0||i.Enabled===null||fe(i.Enabled))throw Error(`VALIDATION_ERROR: Enabled field is required`);let d=`USER_ERROR`,f=async(e,t)=>{try{await Yc(e)}catch{throw Error(`ROLLBACK_FAILED: ${t}`)}},p;try{p=await s.createUser({email:i.Email,emailVerified:!1,password:o,displayName:i.Name,photoURL:i.Photo_URL,disabled:!i.Enabled})}catch{throw Error(d)}let m={};for(let e of u)e.saveToAuthToken&&!Qc(e.name)&&i[e.name]!==void 0&&e.type!==`Timestamp`&&e.type!==`Computed`&&e.type!==`Embedding`&&(fe(i[e.name])?m[e.name]=null:m[e.name]=i[e.name]);try{await s.setCustomUserClaims(p.uid,{...m,tenant:e,role:i.Role,collection:l.collection,doc:t})}catch{throw await f(i,d),Error(d)}try{await c.collection(`tenants`).doc(e).collection(`system_user_permissions`).doc(p.uid).set({...a,Role:i.Role,Enabled:i.Enabled??!1,Collection:l.collection,Doc_ID:t})}catch{throw await f(i,d),Error(d)}let h=n.auth.enableMultiFactorAuth;if(h===!0||typeof h==`object`&&h.includes(i.Role)){let e;try{e=await s.generateEmailVerificationLink(i.Email)}catch{throw await f(i,d),Error(d)}if(e.includes(`apiKey=&`)){let t=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);e=e.replace(`apiKey=&`,`apiKey=${t.apiKey}&`)}if(e){let t=`https://${s.app.options.projectId}.firebaseapp.com/__/auth/action${e}`,r=await P(n.appName),a=n?.mail?.emailVerification&&n.mail.emailVerification(t,r);try{await Xc(i.Email,a?.subject||`Please verify your email address`,void 0,a?.html||`Please verify your email address by clicking the link:
|
|
4
|
+
`),t.length>5e6)throw Error(`Email body is too long`);return t},fc=(e=`enterprise`,t)=>e===`enterprise`?t:`(default)`,$=()=>{let e=(0,f.getApp)(),t=process.env.STOKER_FB_WEB_APP_CONFIG;if(!t)throw Error(`STOKER_FB_WEB_APP_CONFIG not set.`);let n=JSON.parse(t),r=fc(process.env.FB_FIRESTORE_EDITION,n.projectId);return(0,p.getFirestore)(e,r)},pc=async(e,t)=>{let n={};for(let r of t){let t=`${e}/${r}.js`;n[r]=await import((0,m.pathToFileURL)(t).href)}return n},mc,hc,gc,_c,vc,yc,bc,xc,Sc=0,Cc=!1,wc={getTenant(){if(!gc)throw Error(`Tenant not provided`);return gc},setTenant(e){gc=e},getMode(){return hc},getTimezone(){return _c},getGlobalConfigModule(){return(0,d.default)(vc)},getCustomizationFile(e,t){if(!Object.keys(t.collections).includes(e))throw Error(`PERMISSION_DENIED`);let n=be([e],yc,`node`,wc);return(0,d.default)(n?.[e])},getVersionInfo(){return bc},getMaintenanceInfo(){return xc},getStokerFirestore:$},Tc=async(e,t,n,r,i)=>{let a=!!Cc;if(Cc=!0,t&&(gc=t),hc=e,mc&&!i)return wc;if(!process.env.STOKER_FB_WEB_APP_CONFIG)throw Error(`STOKER_FB_WEB_APP_CONFIG not set.`);let o=process.env.STOKER_FB_WEB_APP_CONFIG,s=JSON.parse(o),c=(await import((0,m.pathToFileURL)(n).href)).default;vc=c({sdk:`node`,utils:wc}),!i&&e===`development`&&(process.env.FIREBASE_AUTH_EMULATOR_HOST=`127.0.0.1:9099`,process.env.FIREBASE_DATABASE_EMULATOR_HOST=`127.0.0.1:9000`,process.env.FIRESTORE_EMULATOR_HOST=`127.0.0.1:8080`,process.env.FIREBASE_STORAGE_EMULATOR_HOST=`127.0.0.1:9199`);try{mc=(0,f.getApp)()}catch{mc=(0,f.initializeApp)({credential:(0,f.applicationDefault)(),databaseURL:s.databaseURL,storageBucket:s.storageBucket,projectId:s.projectId})}let l=await Ic();return yc=await pc(r,Object.keys(l.collections)),_c=await P(vc.timezone),a||$().collection(`system_deployment`).doc(`maintenance_mode`).onSnapshot(e=>{e.exists?(xc=e.data(),P(vc.onMaintenanceUpdate,[`node`,xc.active?`on`:`off`])):console.error(`Maintenance status not found`)},e=>{console.error(e.message)}),a||$().collection(`system_deployment`).doc(`latest_deploy`).onSnapshot(e=>{e.exists?(bc=e.data(),Sc++,Sc>1&&P(vc.onVersionUpdate,[`node`,bc,Sc])):console.error(`Version info not found`)},e=>{console.error(e.message)}),await new Promise(e=>{let t=()=>{xc&&bc?e(wc):setTimeout(t,100)};t()}),wc},{getTenant:Ec,setTenant:Dc,getMode:Oc,getTimezone:kc,getGlobalConfigModule:Ac,getCustomizationFile:jc,getVersionInfo:Mc,getMaintenanceInfo:Nc}=wc,Pc=async(e,t,n,r)=>new Promise((i,a)=>{let o=(0,h.default)(e,t,{cwd:n||process.cwd(),env:{...process.env,...r}}),s=``,c=()=>{o.kill(`SIGINT`)},l=()=>{o.kill(`SIGTERM`)},u=()=>{process.removeListener(`SIGINT`,c),process.removeListener(`SIGTERM`,l)};o.stdout?.on(`data`,e=>{s+=e.toString(),console.log(e.toString())}),o.stderr?.on(`data`,e=>{console.log(e.toString())}),o.on(`exit`,e=>{u(),e===0?i(s):a()}),process.on(`SIGINT`,c),process.on(`SIGTERM`,l)}),Fc=async()=>{let e=process.env.STOKER_FB_WEB_APP_CONFIG;if(!e)throw Error(`Firebase web app config not found`);let t=JSON.parse(e);try{return(0,f.getApp)()}catch{return(0,f.initializeApp)({credential:(0,f.applicationDefault)(),databaseURL:t.databaseURL,storageBucket:t.storageBucket,projectId:t.projectId})}},Ic=async(e=!1)=>{let t=await(0,g.getDatabase)().ref(`schema`).orderByChild(`published_time`).limitToLast(1).get(),n=Object.values(t.val())[0];if(e){for(let e of Object.values(n.collections))for(let t of e.fields)if(t.type===`Computed`){let r=xe(t,jc(e.labels.collection,n));r.formula&&(t.formula=r.formula)}}else for(let e of Object.values(n.collections))e.fields=e.fields.filter(e=>e.type!==`Computed`);return n},Lc=async()=>{let e=await(0,g.getDatabase)().ref(`schema`).orderByChild(`published_time`).limitToLast(2).get();if(!(e.numChildren()<2))return Object.values(e.val())[0]},Rc=(e,t,n)=>{let r=e.collection(`tenants`).doc(n);for(let e=0;e<t.length;e++)r=e%2==0?r.collection(t[e]):r.doc(t[e]);return r},zc=(e,t,n,r,i,a)=>{let o=$(),s=t.at(-1);if(!s)throw Error(`EMPTY_PATH`);let c=n.collections[s],{labels:l,fields:u,preloadCache:d}=c,f=jc(s,n),p=Rc(o,t,e);if(!i)return[p];if(r){let s=i.collections?.[l.collection];if(!i.Role)throw Error(`PERMISSION_DENIED`);let p=s&&T(`Read`,s),m=N(c,n,i,a??{}),h=ee(c,i),g=te(c,i),_=ne(c,n,i),v=(r=[])=>{let s=[],u=Re(i.Role,c,n);if(!u)throw Error(`PERMISSION_DENIED`);if(p){let n=o.collection(`tenants`).doc(e).collection(`system_fields`).doc(l.collection).collection(`${l.collection}-${u.key}`).where(`Collection_Path_String`,`==`,t.join(`/`));r.forEach(e=>{n=n.where(...e)}),s.push(n);let d=x(c);Object.entries(c.fieldAccessGroups||{}).forEach(([n,c])=>{if(!d[n]?.length||!S(c,l.collection,i,a??{}))return;let f=Fe(n,u.key),p=o.collection(`tenants`).doc(e).collection(`system_fields`).doc(l.collection).collection(`${l.collection}-${f}`).where(`Collection_Path_String`,`==`,t.join(`/`));r.forEach(e=>{p=p.where(...e)}),s.push(p)})}else if(m)for(let n of m){let i=o.collection(`tenants`).doc(e).collection(`system_fields`).doc(l.collection).collection(`${l.collection}-${n.field}`).where(`Collection_Path_String`,`==`,t.join(`/`));r.forEach(e=>{i=i.where(...e)}),s.push(i)}return s},y=h.filter(e=>`operations`in e&&e.operations?e.operations.includes(`Read`):!0);if(y.length===0&&g.length===0&&_.length===0)return v();let b=0,C=e=>{e&&(b===0?b=e:b*=e)};if(y.length>0){for(let e of y)if(e.operations&&e.type===`Record_Property`){let t=e.roles.find(e=>e.role===i.Role);if(!t)throw Error(`PERMISSION_DENIED`);C(t.values?.length)}}d?.roles.includes(i.Role)&&d.range&&C(d.range.fields.length);let w=f.admin?.statusField;w&&!d?.roles.includes(i.Role)&&C(Math.max(w.active?.length||0,w.archived?.length||0));let E=b===0?30:Math.max(1,Math.floor(30/b)),D=[];y.filter(e=>e.type===`Record_Owner`).forEach(()=>D.push([`Created_By`,`==`,r])),y.filter(e=>e.type===`Record_User`).forEach(e=>{if(`collectionField`in e){let t=j(u,e.collectionField);D.push([`${t.name}_Array`,`array-contains`,i.Doc_ID])}}),y.filter(e=>e.type===`Record_Property`).forEach(e=>{if(`propertyField`in e){let t=e.roles.find(e=>e.role===i.Role);if(!t)throw Error(`PERMISSION_DENIED`);let n=j(u,e.propertyField);n.type===`Array`?D.push([`${n.name}_Array`,`array-contains-any`,t.values]):D.push([n.name,`in`,t.values])}});let O=[];g.filter(e=>e.type===`Individual`).forEach(e=>{let t=s?.individualEntities,n=[];if(t){let r=e.singleQuery?e.singleQuery:E;for(let e=0;e<t.length;e+=r){let i=t.slice(e,e+r);n.push(i)}if(!e.singleQuery)n.forEach(e=>{O.push(...v(D.concat([[`id`,`in`,e]])))});else{if(t.length>r)throw Error(`INPUT_ERROR: Individual entity restriction with singleQuery set to true must not have more than ${e.singleQuery} entities`);D.push([`id`,`in`,t])}}}),_.filter(e=>e.parentFilter.type===`Individual`).forEach(e=>{let{parentFilter:t,parentRestriction:n}=e;if(`collectionField`in t){let e=j(u,t.collectionField);if(`collection`in e){let t=i.collections?.[e.collection];if(!t)throw Error(`PERMISSION_DENIED`);let r=t.individualEntities,a=[];if(r){let t=n.singleQuery?n.singleQuery:E;for(let e=0;e<r.length;e+=t){let n=r.slice(e,e+t);a.push(n)}if(!n.singleQuery)a.forEach(t=>{O.push(...v(D.concat([[`${e.name}_Array`,`array-contains-any`,t]])))});else{if(r.length>t)throw Error(`INPUT_ERROR: Individual entity parentFilter with singleQuery set to true must not have more than ${n.singleQuery} entities`);D.push([`${e.name}_Array`,`array-contains-any`,r])}}}}});let k=[];g.filter(e=>e.type===`Parent`).forEach(e=>{if(`collectionField`in e){let t=j(u,e.collectionField);if(`collection`in t){let n=s?.parentEntities,r=[];if(n){let i=e.singleQuery?e.singleQuery:E;for(let e=0;e<n.length;e+=i){let t=n.slice(e,e+i);r.push(t)}if(!e.singleQuery)r.forEach(e=>{k.push(...v(D.concat([[`${t.name}_Array`,`array-contains-any`,e]])))});else{if(n&&n.length>i)throw Error(`INPUT_ERROR: Parent entity restriction with singleQuery set to true must not have more than ${e.singleQuery} entities`);D.push([`${t.name}_Array`,`array-contains-any`,n])}}}}}),_.filter(e=>e.parentFilter.type===`Parent`).forEach(e=>{let{parentFilter:t,parentRestriction:n}=e;if(`collectionField`in t&&`parentCollectionField`in t){let e=j(u,t.collectionField),r=j(u,t.parentCollectionField);if(`collection`in e&&`collection`in r){let t=i.collections?.[e.collection];if(!t)throw Error(`PERMISSION_DENIED`);let a=t.parentEntities,o=[];if(a){let e=n.singleQuery?n.singleQuery:E;for(let t=0;t<a.length;t+=e){let n=a.slice(t,t+e);o.push(n)}if(!n.singleQuery)o.forEach(e=>{k.push(...v(D.concat([[`${r.name}_Array`,`array-contains-any`,e]])))});else{if(a&&a.length>e)throw Error(`INPUT_ERROR: Profile_Parent entity parentFilter with singleQuery set to true must not have more than ${n.singleQuery} entities`);D.push([`${r.name}_Array`,`array-contains-any`,a])}}}}});let A=[];k.length===0&&(g.filter(e=>e.type===`Parent_Property`).forEach(e=>{if(`collectionField`in e&&`propertyField`in e){let t=j(u,e.collectionField),n=j(u,e.propertyField);if(`collection`in t){let e=s?.parentPropertyEntities||{};Object.entries(e).forEach(([e,r])=>{if(r.length>0){let i=[];for(let e=0;e<r.length;e+=E){let t=r.slice(e,e+E);i.push(t)}i.forEach(r=>{A.push(...v(D.concat([[`${t.name}_Array`,`array-contains-any`,r],[n.name,`==`,e]])))})}})}}}),_.filter(e=>e.parentFilter.type===`Parent_Property`).forEach(e=>{let{parentFilter:t}=e;if(`collectionField`in t&&`parentCollectionField`in t&&`parentPropertyField`in t){let e=j(u,t.collectionField),n=j(u,t.parentCollectionField),r=j(u,t.parentPropertyField);if(`collection`in e&&`collection`in n){let t=i.collections?.[e.collection];if(!t)throw Error(`PERMISSION_DENIED`);let a=t.parentPropertyEntities||{};Object.entries(a).forEach(([e,t])=>{if(t.length>0){let i=[];for(let e=0;e<t.length;e+=E){let n=t.slice(e,e+E);i.push(n)}i.forEach(t=>{A.push(...v(D.concat([[`${n.name}_Array`,`array-contains-any`,t],[r.name,`==`,e]])))})}})}}}));let M=[...O,...k,...A];return!g.length&&!_.length?v(D):M}throw Error(`PERMISSION_DENIED`)},Bc=(e,t,n,r,i,a)=>{let o=$(),s=t.at(-1);if(!s)throw Error(`EMPTY_PATH`);let c=r.collections[s],{labels:l}=c,u=Rc(o,t,e);if(i){let t=i.collections?.[l.collection];if(!i.Role)throw Error(`PERMISSION_DENIED`);let s=t&&T(`Read`,t),u=N(c,r,i,a??{}),d=[],f=Re(i.Role,c,r);if(!f)throw Error(`PERMISSION_DENIED`);if(s){d.push(o.collection(`tenants`).doc(e).collection(`system_fields`).doc(l.collection).collection(`${l.collection}-${f.key}`).doc(n));let t=x(c);Object.entries(c.fieldAccessGroups||{}).forEach(([r,s])=>{if(!t[r]?.length||!S(s,l.collection,i,a??{}))return;let c=Fe(r,f.key);d.push(o.collection(`tenants`).doc(e).collection(`system_fields`).doc(l.collection).collection(`${l.collection}-${c}`).doc(n))})}else if(u)for(let t of u)d.push(o.collection(`tenants`).doc(e).collection(`system_fields`).doc(l.collection).collection(`${l.collection}-${t.field}`).doc(n));return d}return[u.doc(n)]},Vc=async e=>await(0,_.getAuth)().getUser(e),Hc=async(e,t,n,r,i,a,o,s,c,l)=>{let u=n.at(-2),d=ae(i.collections[u],i).map(e=>e.labels.collection);r.collections?r.collections.forEach(e=>{if(!d.includes(e))throw Error(`SCHEMA_ERROR: Collection ${e} not found in subcollections of ${u}`)}):r.collections=d;let f=r.depth-1,p=r.collections.map(async u=>{t[u]=(await Wc([...n,u],{constraints:r.constraints,userId:s,pagination:r.limit,providedTransaction:c,noEmbeddingFields:l}).catch(e=>{throw e.code===`permission-denied`&&console.info(`PERMISSION_DENIED for subcollection ${u} for document at ${n.join(`/`)}`),e})).records,a&&await Promise.all(t[u].map(t=>Uc(e,t,[...n,u,t.id],a,i,void 0,s,c,l))),f>0&&await Promise.all(t[u].map(t=>Hc(e,t,[...n,u,t.id],{depth:f},i,a,o,s,c,l)))});await Promise.all(p)},Uc=async(e,t,n,r,i,a,o,s,c)=>{let l=n.at(-2);r.fields||=i.collections[l].fields.filter(e=>M(e));let u=r.depth-1,d=[];for(let n of r.fields)if(`collection`in n){let r=t[n.name];if(!r)continue;let l=Object.keys(r);for(let t of l){let n=r[t],l=qc(n.Collection_Path,t,{userId:o,providedTransaction:s,noEmbeddingFields:c}).then(l=>{if(r[t]=l,u>0)return Uc(e,r[t],[...n.Collection_Path,t],{depth:u},i,a,o,s,c)}).catch(e=>{if(e.message.includes(`NOT_FOUND`)||e.code===`permission-denied`)delete r[t];else throw e});d.push(l)}}await Promise.all(d)},Wc=async(e,t)=>{if(t?.subcollections?.depth&&t.subcollections.depth>10)throw Error(`INPUT_ERROR: Subcollections depth cannot exceed 10`);if(t?.relations?.depth&&t.relations.depth>10)throw Error(`INPUT_ERROR: Relations depth cannot exceed 10`);if(t?.pagination?.number!==void 0){let e=t.pagination.number;if(typeof e!=`number`||!Number.isFinite(e)||!Number.isInteger(e)||e<1)throw Error(`INPUT_ERROR: Pagination number must be a positive finite integer`)}let n=t?.constraints,r=Ec(),i=$(),a,o,s,c=async c=>{let[l,u,f,p]=await Promise.all([t?.userId?c.get(i.collection(`tenants`).doc(r).collection(`system_user_permissions`).doc(t.userId)):Promise.resolve({}),c.get(i.collection(`system_deployment`).doc(`maintenance_mode`)),Ic(!0),t?.userId?Vc(t.userId):Promise.resolve(void 0)]);if(!u.exists||u.data().active)throw Error(`MAINTENANCE_MODE`);let m=f,h,g=Ac(),_=e.at(-1);if(!_)throw Error(`EMPTY_PATH`);let v=Object.keys(m.collections).includes(_),y=g.disabledCollections?.includes(_);if(!v||y)throw Error(`COLLECTION_NOT_FOUND`);let b=m.collections[_],{labels:x}=b,S=jc(x.collection,m);if(t?.userId){if(!l?.exists)throw Error(`PERMISSION_DENIED`);if(h=l.data(),!h.Role)throw Error(`USER_ERROR`);if(!h.Enabled)throw Error(`PERMISSION_DENIED`)}let C=zc(r,e,m,t?.userId,h,p?.customClaims??{});if(C.length===0)return{cursor:{},pages:0,records:[]};if(n&&(C=C.map(e=>(n.forEach(([t,n,r])=>{e=e.where(t,n,r)}),e))),o=t?.pagination?.startAfter||t?.pagination?.endBefore||{first:new Map,last:new Map},t?.pagination){if(t.pagination.startAfter&&t.pagination.endBefore)throw Error(`INPUT_ERROR: startAfter and endBefore cannot be provided together`);let e=t.pagination.startAfter||t.pagination.endBefore;if(t?.userId){let t=ye(h.Role,b,m);if(e&&t!==!0)throw Error(`INPUT_ERROR: Pagination is not allowed when using `+t)}C=t.pagination.orderByField&&t.pagination.orderByDirection?!t.pagination.startAfter&&!t.pagination.endBefore?C.map(e=>e.orderBy(t.pagination.orderByField,t.pagination.orderByDirection).limit(t.pagination.number)):t.pagination.startAfter?C.map((e,n)=>e.orderBy(t.pagination.orderByField,t.pagination.orderByDirection).startAfter(o.last.get(n)).limit(t.pagination.number)):C.map((e,n)=>e.orderBy(t.pagination.orderByField,t.pagination.orderByDirection).endBefore(o.first.get(n)).limitToLast(t.pagination.number)):!t.pagination.startAfter&&!t.pagination.endBefore?C.map(e=>e.limit(t.pagination.number)):t.pagination.startAfter?C.map((e,n)=>e.startAfter(o.last.get(n)).limit(t.pagination.number)):C.map((e,n)=>e.endBefore(o.first.get(n)).limitToLast(t.pagination.number))}let w={};await F(`preOperation`,g,S,{operation:`read`,context:w}),await F(`preRead`,g,S,{context:w,refs:C,multiple:!0,listener:!1}),s=new Map;let T=C.map(async e=>await c.get(e)),D=await Promise.all(T);for(let e of D){for(let t of e.docs){s.has(t.id)||s.set(t.id,{});let e=t.data(),n=s.get(t.id);n.id||=t.id;let r={...n,...e};delete r.Collection_Path_String,s.set(t.id,r)}o.first.set(D.indexOf(e),e.docs[0]),o.last.set(D.indexOf(e),e.docs.at(-1)||e.docs[0])}if(t?.pagination){let e=C[0];n&&(e=n.reduce((e,[t,n,r])=>e.where(t,n,r),e)),t.pagination.orderByField&&t.pagination.orderByDirection&&(e=e.orderBy(t.pagination.orderByField,t.pagination.orderByDirection));let r=(await e.count().get()).data().count,i=t.pagination.number;a=i>0?Math.ceil(r/i):0}let O;t?.noComputedFields||(O=await P(S.admin?.retriever));for(let e of s.values()){let n=[],i=[...e.Collection_Path,e.id];t?.subcollections&&n.push(Hc(r,s.get(e.id),i,(0,d.default)(t.subcollections),m,(0,d.default)(t?.relations),void 0,t.userId,t.transactional?c:void 0,t?.noEmbeddingFields)),t?.relations&&(t.relations.fields&&(t.relations.fields=t.relations.fields.map(e=>{if(typeof e==`string`){let t=b.fields.find(t=>t.name===e);if(t)return t;throw Error(`SCHEMA_ERROR: Field ${e} not found in collection ${_}`)}return e})),n.push(Uc(r,s.get(e.id),i,(0,d.default)(t.relations),m,void 0,t.userId,t.transactional?c:void 0,t?.noEmbeddingFields))),await Promise.all(n);let a=[];for(let n of b.fields){if(n.type===`Computed`&&!t?.noComputedFields){let t=xe(n,S);if(!t.formula)continue;a.push(P(t.formula,[e,O]).then(t=>{e[n.name]=t}))}t?.noEmbeddingFields&&n.type===`Embedding`&&delete e[n.name]}if(await Promise.all(a),t?.userId&&h?.Role){if(!p)throw Error(`USER_ERROR`);if(!(S.custom?.serverAccess?.read===void 0||await P(S.custom.serverAccess.read,[h,p,e]))){s.delete(e.id);continue}for(let t of b.fields){let n=!t.access||E(t,h,b,p?.customClaims??{}),r=xe(t,S),i=r?.custom?.serverAccess?.read===void 0||await P(r.custom.serverAccess.read,[h,p,e]);(!n||!i)&&(M(t)?(delete s.get(e.id)[t.name],delete s.get(e.id)[`${t.name}_Array`],delete s.get(e.id)[`${t.name}_Single`]):delete s.get(e.id)[t.name])}}await F(`postOperation`,g,S,{operation:`read`,data:e,recordId:e.id,context:w}),await F(`postRead`,g,S,{context:w,refs:C,record:e,listener:!1})}t?.userId&&await _e(Array.from(s.values()),b,m,t.userId,h)};return t?.providedTransaction?await c(t.providedTransaction):await i.runTransaction(async e=>{await c(e)},{readOnly:!0}),{cursor:o,pages:a,records:Array.from(s.values())}},Gc=async(e,t,n,r,i,a,o,s)=>{let c=r.at(-2),l=ae(a.collections[c],a).map(e=>e.labels.collection);i.collections?i.collections.forEach(e=>{if(!l.includes(e))throw Error(`SCHEMA_ERROR: Collection ${e} not found in subcollections of ${c}`)}):i.collections=l;let u=i.depth-1,d=i.collections.map(async c=>{n[c]=(await Wc([...r,c],{constraints:i.constraints||[],userId:s,relations:o,pagination:i.limit,providedTransaction:t}).catch(e=>{throw e.code===`permission-denied`&&console.info(`PERMISSION_DENIED for subcollection ${c} for document at ${r.join(`/`)}`),e})).records,u>0&&await Promise.all(n[c].map(async n=>{await Gc(e,t,n,[...r,c,n.id],{depth:u},a,o,s)}))});await Promise.all(d)},Kc=async(e,t,n,r,i,a,o,s,c)=>{let l=r.at(-2);a.fields||=i.collections[l].fields.filter(e=>M(e));let u=a.depth-1,d=[];for(let r of a.fields)if(`collection`in r){let a=n[r.name];if(!a)continue;for(let[n,r]of Object.entries(a)){let l=qc(r.Collection_Path,n,{userId:o,providedTransaction:t,noComputedFields:s,noEmbeddingFields:c}).then(l=>{if(a[n]=l,u>0)return Kc(e,t,a[n],[...r.Collection_Path,n],i,{depth:u},o,s,c)}).catch(e=>{if(e.message.includes(`NOT_FOUND`)||e.code===`permission-denied`)delete a[n];else throw e});d.push(l)}}await Promise.all(d)},qc=async(e,t,n)=>{if(n?.subcollections?.depth&&n.subcollections.depth>10)throw Error(`INPUT_ERROR: Subcollections depth cannot exceed 10`);if(n?.relations?.depth&&n.relations.depth>10)throw Error(`INPUT_ERROR: Relations depth cannot exceed 10`);let r=Ec(),i=$(),a,o=async o=>{let[s,c,l,u]=await Promise.all([n?.userId?o.get(i.collection(`tenants`).doc(r).collection(`system_user_permissions`).doc(n.userId)):Promise.resolve({}),o.get(i.collection(`system_deployment`).doc(`maintenance_mode`)),Ic(!0),n?.userId?Vc(n.userId):Promise.resolve(void 0)]);if(!c.exists||c.data().active)throw Error(`MAINTENANCE_MODE`);let d=l,f,p=Ac(),m=e.at(-1);if(!m)throw Error(`EMPTY_PATH`);let h=Object.keys(d.collections).includes(m),g=p.disabledCollections?.includes(m);if(!h||g)throw Error(`COLLECTION_NOT_FOUND`);let _=d.collections[m],{labels:v}=_,y=jc(v.collection,d),b;if(n?.userId){if(!s?.exists)throw Error(`PERMISSION_DENIED`);if(f=s.data(),!f.Role)throw Error(`USER_ERROR`);if(!f.Enabled||(b=f.collections?.[v.collection],!b))throw Error(`PERMISSION_DENIED`)}if(n?.userId&&(!b||!T(`Read`,b)))throw Error(`PERMISSION_DENIED`);let x=Bc(r,e,t,d,f,u?.customClaims??{});if(x.length===0)throw Error(`PERMISSION_DENIED`);let S={};await F(`preOperation`,p,y,{operation:`read`,recordId:t,context:S}),await F(`preRead`,p,y,{context:S,refs:x,multiple:!1,listener:!1}),a={};let C=x.map(e=>o.get(e)),w=await Promise.all(C);for(let n of w)if(n.exists){let e=n.data();a.id||=n.id,a={...a,...e},delete a.Collection_Path_String}else throw Error(`NOT_FOUND: Document with ID ${t} does not exist at location ${e?.join(`/`)||v.collection}`);let D=[],O=e?[...e,t]:[v.collection,t];if(n?.subcollections&&D.push(Gc(r,o,a,O,n.subcollections,d,void 0,n.userId)),n?.relations&&(n.relations.fields&&(n.relations.fields=n.relations.fields.map(e=>{if(typeof e==`string`){let t=_.fields.find(t=>t.name===e);if(t)return t;throw Error(`SCHEMA_ERROR: Field ${e} not found in collection ${m}`)}return e})),D.push(Kc(r,o,a,O,d,n.relations,n.userId,n.noComputedFields,n.noEmbeddingFields))),await Promise.all(D),!n?.noComputedFields){for(let e of _.fields)if(e.type===`Computed`){let t=xe(e,y);if(!t.formula)continue;a[e.name]=await t.formula(a)}}if(n?.noEmbeddingFields)for(let e of _.fields)e.type===`Embedding`&&delete a[e.name];if(n?.userId&&f?.Role){if(!u)throw Error(`USER_ERROR`);if(!(y.custom?.serverAccess?.read===void 0||await P(y.custom?.serverAccess?.read,[f,u,a])))throw Error(`PERMISSION_DENIED`);for(let e of _.fields){let t=!e.access||E(e,f,_,u?.customClaims??{}),n=xe(e,y),r=n?.custom?.serverAccess?.read===void 0||await P(n.custom.serverAccess.read,[f,u,a]);(!t||!r)&&(M(e)?(delete a[e.name],delete a[`${e.name}_Array`],delete a[`${e.name}_Single`]):delete a[e.name])}}await F(`postOperation`,p,y,{operation:`read`,data:a,recordId:t,context:S}),await F(`postRead`,p,y,{context:S,refs:x,record:a,listener:!1}),n?.userId&&await ge(a,_,d,n.userId,f)};return n?.providedTransaction?await o(n.providedTransaction):await i.runTransaction(async e=>{await o(e)},{readOnly:!0}),a},Jc=async(e,t,n,r,i,a,o,s,c)=>{let{labels:l}=o,u=$(),f=await P(Ac().firebase?.writeLogTTL),m={operation:e,collection:l.collection,docId:a,user:`System`,status:t,Collection_Path:i,Last_Write_At:n.Last_Write_At,Last_Write_By:n.Last_Write_By,Last_Write_Connection_Status:n.Last_Write_Connection_Status,Last_Write_App:n.Last_Write_App,Last_Write_Version:n.Last_Write_Version,data:{}};if(f){let e=new Date,t=new Date(new Date().setDate(e.getDate()+f));m.TTL=p.Timestamp.fromDate(t)}let h=(0,d.default)(n);pe(h),e!==`delete`&&(m.data.data=(0,d.default)(h)),e===`update`&&(m.data.originalRecord=(0,d.default)(c)),e!==`delete`&&[`started`,`written`].includes(t)&&(delete m.data.data.Saved_At,delete m.data.data.Last_Save_At),t===`failed`&&(m.data.error=JSON.stringify(s));let g=Rc(u,i,r),_=n.Last_Write_At;await g.doc(a).collection(`system_write_log`).doc(`${n.Last_Write_By}-${_.valueOf()}`).set(m)},Yc=async e=>{let t=Ec(),n=(0,_.getAuth)(),r=$(),i=[];if(await Promise.all([(async()=>{try{await r.collection(`tenants`).doc(t).collection(`system_user_permissions`).doc(e.User_ID).delete()}catch(e){i.push(`Error deleting user permissions:\n${e}`)}})(),(async()=>{try{await n.deleteUser(e.User_ID)}catch(e){if(e.code===`auth/user-not-found`)return;i.push(`Error deleting user:\n${e}`)}})()]),i.length>0)throw Error(i.join(`, `))},Xc=async(e,t,n,r,i,a,o,s,c)=>{let l=$(),u=Oc(),d=process.env.ADMIN_EMAIL;if(u===`development`||process.env.FIRESTORE_EMULATOR_HOST){if(d)e=d;else throw Error(`Admin email not set`)}let f=lc(e),p=uc(t),m=n?dc(n):void 0,h=r?dc(r):void 0,g=i?lc(i):void 0,_=a?lc(a):void 0,v=o?cc(o):void 0,y=c?cc(c):void 0,b=Array.isArray(f)?f:[f];if(b.length===0||b.length===1&&!b[0])throw Error(`No valid email addresses provided`);let x={to:f,message:{subject:p}};if(m&&(x.message.text=m),h&&(x.message.html=h),g){let e=Array.isArray(g)?g:[g];e.length>0&&e[0]&&(x.cc=g)}if(_){let e=Array.isArray(_)?_:[_];e.length>0&&e[0]&&(x.bcc=_)}v&&(x.replyTo=v),s&&(x.message.attachments=s),y&&(x.from=y),await l.collection(`system_mail`).add(x)},Zc=new Set([`tenant`,`role`,`collection`,`doc`]);function Qc(e){return Zc.has(e)}function $c(e){if(!e)return{};let t={};for(let n of Object.keys(e))Zc.has(n)||(t[n]=e[n]);return t}var el=async(e,t,n,r,i,a,o)=>{let s=(0,_.getAuth)(),c=$(),{labels:l,fields:u}=r;if(fe(i.Email)||!i.Email)throw Error(`VALIDATION_ERROR: Email field is required`);if(fe(i.Role)||!i.Role)throw Error(`VALIDATION_ERROR: Role field is required`);if(i.Enabled===void 0||i.Enabled===null||fe(i.Enabled))throw Error(`VALIDATION_ERROR: Enabled field is required`);let d=`USER_ERROR`,f=async(e,t)=>{try{await Yc(e)}catch{throw Error(`ROLLBACK_FAILED: ${t}`)}},p;try{p=await s.createUser({email:i.Email,emailVerified:!1,password:o,displayName:i.Name,photoURL:i.Photo_URL,disabled:!i.Enabled})}catch(e){throw console.error(e.message),Error(d)}let m={};for(let e of u)e.saveToAuthToken&&!Qc(e.name)&&i[e.name]!==void 0&&e.type!==`Timestamp`&&e.type!==`Computed`&&e.type!==`Embedding`&&(fe(i[e.name])?m[e.name]=null:m[e.name]=i[e.name]);try{await s.setCustomUserClaims(p.uid,{...m,tenant:e,role:i.Role,collection:l.collection,doc:t})}catch(e){throw console.error(e.message),await f(i,d),Error(d)}try{await c.collection(`tenants`).doc(e).collection(`system_user_permissions`).doc(p.uid).set({...a,Role:i.Role,Enabled:i.Enabled??!1,Collection:l.collection,Doc_ID:t})}catch(e){throw console.error(e.message),await f(i,d),Error(d)}let h=n.auth.enableMultiFactorAuth;if(h===!0||typeof h==`object`&&h.includes(i.Role)){let e;try{e=await s.generateEmailVerificationLink(i.Email)}catch(e){throw console.error(e.message),await f(i,d),Error(d)}if(e.includes(`apiKey=&`)){let t=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);e=e.replace(`apiKey=&`,`apiKey=${t.apiKey}&`)}if(e){let t=`https://${s.app.options.projectId}.firebaseapp.com/__/auth/action${e}`,r=await P(n.appName),a=n?.mail?.emailVerification&&n.mail.emailVerification(t,r);try{await Xc(i.Email,a?.subject||`Please verify your email address`,void 0,a?.html||`Please verify your email address by clicking the link:
|
|
5
5
|
</br>
|
|
6
6
|
</br>
|
|
7
|
-
<a href="${t}">${t}</a>`)}catch{throw await f(i,d),Error(d)}}}return p.uid},tl=async(e,t)=>{let{labels:n,parentCollection:r}=t;if(r){let t=e.at(-2);if(!t)throw Error(`PERMISSION_DENIED`);let r=await qc([...e].slice(0,-2),t).catch(()=>{throw Error(`PERMISSION_DENIED`)}),i=r.Collection_Path;if(i.push(r.id),i.push(n.collection),!(0,c.default)(e,i))throw Error(`PERMISSION_DENIED`)}else if(e.length>1)throw Error(`PERMISSION_DENIED`)},nl=e=>typeof e==`object`&&!!e&&!Array.isArray(e),rl=e=>{let t=e=>{Object.entries(e).forEach(([n,r])=>{nl(r)&&Object.keys(r).length===2&&typeof r.seconds==`number`&&typeof r.nanoseconds==`number`?e[n]=new p.Timestamp(r.seconds,r.nanoseconds):nl(r)&&t(r)})};t(e)},il=e=>{let t=e=>{Object.entries(e).forEach(([n,r])=>{nl(r)&&Object.keys(r).length===2&&typeof r._seconds==`number`&&typeof r._nanoseconds==`number`?e[n]=new p.Timestamp(r._seconds,r._nanoseconds):nl(r)&&t(r)})};t(e)},al=e=>{if(typeof e==`object`)for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&(e[t]===`_DELETE_FIELD`?e[t]=p.FieldValue.delete():al(e[t]))},ol=(e,t,n)=>{if(M(n)&&n.includeFields){let r={};return n.includeFields.forEach(n=>{t[n]!==void 0&&(r[n]=t[n],Ge(e,[j(e.fields,n)]).size===1&&(r[`${n}_Lowercase`]=t[`${n}_Lowercase`]))}),r}return{}},sl=async(e,t,n,r,i,a,o)=>{if(!M(n)||!n.enforceHierarchy)return;let{fields:s}=t,c=$(),l=Object.entries(r[n.name]);if(!l.length)throw Error(`VALIDATION_ERROR: relation ${n.name} is required`);let[u,d]=l[0];if(!d)throw Error(`VALIDATION_ERROR: Relation ${n.name} is required`);let f=Rc(c,d.Collection_Path,e);if(a.size++,!o&&a.size>500)throw Error(`VALIDATION ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks, entity restrictions (in permissions when dealing with user collections) or relation hierarchy checks.`);let p=await i.get(f.doc(u));if(!p.exists)throw Error(`VALIDATION_ERROR: Record ${u} not found in collection ${n.collection}`);let m=p.data(),h=j(s,n.enforceHierarchy.field),g=n.enforceHierarchy;if(!m[g.recordLinkField]||!r[h.name]||!Object.keys(r[h.name]).every(e=>Object.keys(m[g.recordLinkField]).includes(e)))throw Error(`VALIDATION_ERROR: Invalid relation hierarchy`)},cl=async(e,t,n)=>{delete t[e.name][n],t[`${e.name}_Array`]=t[`${e.name}_Array`]?.filter(e=>e!==n),delete t[`${e.name}_Single`]},ll=async(e,t,n,r,i)=>{t[e.name]||={},t[e.name][r]=n,t[`${e.name}_Array`]||=[],t[`${e.name}_Array`].push(r),i&&(t[`${e.name}_Single`]={id:r,...n})},ul=(e,t,n,r,i,a)=>{let o=[],s=[];for(let c of r.fields)M(c)&&c.twoWay&&c.collection===n&&((e===`Create`||!a?.[c.name]?.[t])&&i[c.name]?.[t]&&o.push(c),e===`Update`&&a?.[c.name]?.[t]&&!i[c.name]?.[t]&&s.push(c));return{addedFields:o,removedFields:s}},dl=async(e,t,n,r,i,a,o,s,l,u,f,p,m)=>{let{fields:h}=a,g=$(),_=new Map,v=new Map,y=new Map;for(let n of h)M(n)&&[`OneToOne`,`OneToMany`].includes(n.type)&&n.enforceHierarchy&&r[n.name]&&(e===`Create`||e===`Update`&&!(0,c.default)(p?.[n.name],r[n.name]))&&await sl(t,a,n,r,s,l);for(let c of h)if(M(c)&&c.twoWay){let u=o.collections[c.collection],f=j(u.fields,c.twoWay),m=We(u,[f]);if(r[c.name]){let o=Object.entries(r[c.name]);for(let u of o){let[o,h]=u;if(e===`Create`||!p?.[c.name]?.[o]){let e,u=y.get(c.collection)?.[o];if(u)e=u;else{l.size++,l&&l.size>500&&console.error(Error(`VALIDATION_ERROR: ${l.size} operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of two way updates, unique field checks, entity restrictions (in permissions when dealing with user collections) or relation hierarchy checks.`));let n=Rc(g,h.Collection_Path,t),a=await s.get(n.doc(o));if(!a.exists){cl(c,i,o);continue}let u=a.data();v.set(c.collection,{...v.get(c.collection)||{},[o]:u}),e=(0,d.default)({...u,...Ve(r)})}let p={...e[f.name],[n]:{Collection_Path:r.Collection_Path,...ol(a,r,f)}};e[f.name]=p,e[`${f.name}_Array`]||=[],e[`${f.name}_Array`].push(n),m.size===1&&(e[`${f.name}_Single`]={id:n,...p}),y.set(c.collection,{...y.get(c.collection)||{},[o]:e})}}}if(e===`Update`){let e=Object.entries(p?.[c.name]||{});for(let i of e){let[e,a]=i;if(!r[c.name]?.[e]){let i,o=y.get(c.collection)?.[e];if(o)i=o;else{l.size++,l&&l.size>500&&console.error(Error(`VALIDATION_ERROR: ${l.size} operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of two way updates, unique field checks, entity restrictions (in permissions when dealing with user collections) or relation hierarchy checks.`));let n=Rc(g,a.Collection_Path,t),o=await s.get(n.doc(e));if(!o.exists){_.set(c.name,[..._.get(c.name)||[],e]);continue}let u=o.data();v.set(c.collection,{...v.get(c.collection)||{},[e]:u}),i=(0,d.default)({...u,...Ve(r)})}i[f.name][n]&&delete i[f.name][n],Array.isArray(i[`${f.name}_Array`])&&(i[`${f.name}_Array`]=i[`${f.name}_Array`].filter(e=>e!==n)),m.size===1&&delete i[`${f.name}_Single`],y.set(c.collection,{...y.get(c.collection)||{},[e]:i})}}}}for(let[n,c]of y.entries()){let d=o.collections[n],h=jc(n,o);for(let[g,_]of Object.entries(c)){let{addedFields:c,removedFields:y}=ul(e,g,n,a,r,p);if(u&&f){for(let e of c)if(!A(d,j(d.fields,e.twoWay),f,m??{})){cl(e,i,g);continue}for(let e of y){let t=j(d.fields,e.twoWay),n=We(d,[t]);if(!A(d,t,f,m??{})){ll(e,i,p?.[e.name]?.[g],g,n.size===1);continue}}if(!ie(`Update`,d,o,u,f,v.get(n)?.[g])){for(let e of c)cl(e,i,g);for(let e of y){let t=We(d,[j(d.fields,e.twoWay)]);ll(e,i,p?.[e.name]?.[g],g,t.size===1)}}if(!ie(`Update`,d,o,u,f,_)){for(let e of c)cl(e,i,g);for(let e of y){let t=We(d,[j(d.fields,e.twoWay)]);ll(e,i,p?.[e.name]?.[g],g,t.size===1)}}}try{await rc(`update`,_,d,h,{operation:`update`,data:_,context:{},originalRecord:_},o)}catch(e){throw Error(`VALIDATION_ERROR: Two way relation update would invalidate record ${g} in ${n}: ${e.message}`)}for(let e of c){let n=j(d.fields,e.twoWay);[`OneToOne`,`OneToMany`].includes(n.type)&&M(n)&&n.enforceHierarchy&&await sl(t,d,n,_,s,l,!0)}}}return _},fl=(e,t,n)=>{e===`create`&&Oe.forEach(e=>{if(!(0,c.default)(t[e],n[e]))throw Error(`Updating system fields in hooks is not allowed: ${e}`)}),e===`update`&&([`id`,`Collection_Path`,`Created_At`,`Saved_At`,`Created_By`].forEach(e=>{if(e in t)throw Error(`Cannot update system field: ${e}`)}),Oe.forEach(e=>{if(![`id`,`Collection_Path`,`Created_At`,`Saved_At`,`Created_By`].includes(e)&&!(0,c.default)(t[e],n[e]))throw Error(`Updating system fields in hooks is not allowed: ${e}`)}))},pl=(e,t,n,r)=>{let{softDelete:i}=t;if(!i)return;let a=i?.archivedField,o=i?.timestampField;if(n[a]===!0){if(e===`create`)n[o]=p.FieldValue.serverTimestamp();else{if(!r)throw Error(`Original record is required for update`);if(!r[a])n[o]=p.FieldValue.serverTimestamp();else if(n[o]&&n[o]?.valueOf()!==r[o]?.valueOf())throw Error(`Soft delete timestamp cannot be changed`)}}},ml=async(e,t,n,r,i)=>{if(!T(`Read`,i.collections?.[t.labels.collection]))return!1;try{await qc([t.labels.collection],n,{userId:r,providedTransaction:e})}catch{return!1}return!0},hl=10,gl=async(e,t)=>{if(e.length===0)return;let n=Math.min(t,e.length),r=0;await Promise.all(Array.from({length:n},async()=>{for(;r<e.length;){let t=r;r+=1,await e[t]()}}))},_l=async(e,t,n,r,i,a,o)=>{for(let[s,c]of Object.entries(t?.collections||{})){if(!i.collections[s])throw Error(`PERMISSION_DENIED`);let l=i.collections[s].access,u=i.collections[s];if(r.collections?.[s]?.restrictEntities||r?.collections?.[s]?.recordOwner?.active||r?.collections?.[s]?.recordUser?.active||r?.collections?.[s]?.recordProperty?.active){let d=a?.collections?.[s],f=[];if(c.individualEntities){let t=c.individualEntities,i=d?.individualEntities||[],s=a?t.filter(e=>!i.includes(e)):t;for(let t of s){if(o&&o.size++,o&&o.size>500)throw Error(`VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks or entity restrictions (in permissions when dealing with user collections).`);f.push(async()=>{if(!await ml(e,u,t,n,r))throw Error(`PERMISSION_DENIED`)})}}if(c.parentEntities){let s=l.entityRestrictions?.restrictions?.find(e=>e.type===`Parent`&&e.roles.some(e=>e.role===t.Role));if(!s)throw Error(`PERMISSION_DENIED`);let p=j(u.fields,s.collectionField),m=i.collections[p.collection],h=c.parentEntities,g=d?.parentEntities||[],_=a?h.filter(e=>!g.includes(e)):h;for(let t of _){if(o&&o.size++,o&&o.size>500)throw Error(`VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks or entity restrictions (in permissions when dealing with user collections).`);f.push(async()=>{if(!await ml(e,m,t,n,r))throw Error(`PERMISSION_DENIED`)})}}if(c.parentPropertyEntities){let s=l.entityRestrictions?.restrictions?.find(e=>e.type===`Parent_Property`&&e.roles.some(e=>e.role===t.Role));if(!s)throw Error(`PERMISSION_DENIED`);let p=j(u.fields,s.collectionField),m=i.collections[p.collection],h=c.parentPropertyEntities,g=d?.parentPropertyEntities||{};for(let[t,i]of Object.entries(h)){let s=g[t]||[],c=a?i.filter(e=>!s.includes(e)):i;for(let t of c){if(o&&o.size++,o&&o.size>500)throw Error(`VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks or entity restrictions (in permissions when dealing with user collections).`);f.push(async()=>{if(!await ml(e,m,t,n,r))throw Error(`PERMISSION_DENIED`)})}}}await gl(f,hl)}}},vl=async(e,t,n)=>{let r=n?.userId,i=n?.user,a=n?.context,o=Ec(),s=Ac();if(n?.providedTransaction&&r||n?.providedSchema&&r)throw Error(`PERMISSION_DENIED`);let c=n?.providedSchema||await Ic();if(e.length===0)throw Error(`EMPTY_PATH`);let l=e.at(-1),u=Object.keys(c.collections).includes(l),f=s.disabledCollections?.includes(l);if(!u||f)throw Error(`COLLECTION_NOT_FOUND`);let m=c.collections[l],{labels:h,fields:g,enableWriteLog:v,softDelete:y}=m,b=jc(h.collection,c),x=await P(s.appName),S=$(),C=(0,_.getAuth)(),w=r?await C.getUser(r):void 0,T,D;r&&await tl(e,m);let O=Rc(S,e,o),k=n?.id||O.doc().id;a||={},a.collection=h.collection,t.id=k,il(t),al(t);let A=Ue(`create`,e,t,c,x,`Online`,r||`System`,p.Timestamp.now(),p.FieldValue.serverTimestamp());n?.createdAt&&(A.Created_At=n.createdAt),n?.createdBy&&(A.Created_By=n.createdBy);let j=(0,d.default)(A);y&&(A[y.archivedField]=!1),ac(t),qe(m,A,c),v&&!n?.providedTransaction&&await Jc(`create`,`started`,A,o,e,k,m),await F(`preOperation`,s,b,{operation:`create`,data:A,recordId:k,context:a}),await F(`preWrite`,s,b,{operation:`create`,data:A,recordId:k,context:a}),qe(m,A,c),Je(m,A);let M=(r?await S.collection(`tenants`).doc(o).collection(`system_user_permissions`).doc(r).get():void 0)?.data();await Ye(A,m,b,M,w?.customClaims||{}),ac(A);try{if(m.auth&&i){if(!i.password)throw Error(`Password is required`);if(!A.Role)throw Error(`Role field is required`);if(!A.Email)throw Error(`Email field is required`);if(A.Enabled===void 0||A.Enabled===null)throw Error(`Enabled field is required`)}n?.providedTransaction||await rc(`create`,A,m,b,{operation:`create`,data:A,context:a},c)}catch(e){throw Error(`VALIDATION_ERROR: ${e.message}`)}ac(A),t.id=k,y&&(A[y.archivedField]=!1),qe(m,A,c),Je(m,A);try{fl(`create`,A,j),pl(`create`,m,A),await rc(`create`,A,m,b,{operation:`create`,data:A,context:a},c)}catch(e){throw Error(`VALIDATION_ERROR: ${e.message}`)}if(r){if(!w||!M?.Role)throw Error(`USER_ERROR`);let e=M;if(!(b.custom?.serverAccess?.create===void 0||await P(b.custom.serverAccess.create,[e,w,A])))throw Error(`PERMISSION_DENIED`);for(let t of m.fields){if(!(t.name in A))continue;let n=xe(t,b);if(n?.custom?.serverAccess?.create!==void 0&&!await P(n.custom.serverAccess.create,[e,w,A]))throw Error(`PERMISSION_DENIED`)}}i&&(i.permissions||={},i.permissions.Role||=A.Role,i.permissions.Enabled||=A.Enabled);let ee=async(e,t)=>{let[a,s,l,u,d]=await Promise.all([n?.providedTransaction?Promise.resolve({}):e.get(S.collection(`system_deployment`).doc(`latest_deploy`)),n?.providedTransaction?Promise.resolve({}):e.get(S.collection(`system_deployment`).doc(`maintenance_mode`)),r?e.get(S.collection(`tenants`).doc(o).collection(`system_user_permissions`).doc(r)):Promise.resolve({}),n?.providedSchema?Promise.resolve(n.providedSchema):Ic(),r?Vc(r):Promise.resolve(void 0)]);if(t&&(t.size+=3),!n?.providedTransaction){if(!a.exists)throw Error(`VERSION_ERROR`);let e=a.data();if(e.force&&A.Last_Write_At.valueOf()<e.time.valueOf())throw Error(`VERSION_ERROR`);if(!s.exists||s.data().active)throw Error(`MAINTENANCE_MODE`)}if(c=u,r){if(!l?.exists)throw Error(`PERMISSION_DENIED`);if(T=l.data(),!T.Role)throw Error(`USER_ERROR`);if(!T.Enabled)throw Error(`PERMISSION_DENIED`);D=d?.customClaims??{}}if(!n?.providedTransaction){let n=g.filter(e=>`unique`in e&&e.unique).map(async n=>{if(!r||!n.access||E(n,T,m,D)){if(!A[n.name])return;let i=xe(n,b);if(!(!(r&&T&&d&&i?.custom?.serverAccess?.read!==void 0)||await P(i.custom.serverAccess.read,[T,d,A])))throw Error(`PERMISSION_DENIED`);let a=A[n.name].toString().toLowerCase().replace(/\s/g,`---`).replaceAll(`/`,`|||`);if(oc(a)){if(t&&t.size++,t&&t.size>500)throw Error(`VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks.`);if((await e.get(S.collection(`tenants`).doc(o).collection(`system_unique`).doc(h.collection).collection(`Unique-${h.collection}-${n.name}`).doc(a)))?.exists)throw Error(`VALIDATION_ERROR: ${n.name} "${A[n.name]}" already exists`)}else throw Error(`VALIDATION_ERROR: ${n.name} "${A[n.name]}" is invalid`)}});await Promise.all(n)}de(A,k,m,c,r,T,i?.permissions,D),i?.permissions&&r&&T&&await _l(e,i.permissions,r,T,c),de(A,k,m,c,r,T,i?.permissions,D)};m.auth&&i&&(await S.runTransaction(async e=>{await ee(e)},{maxAttempts:10}),A.User_ID=await el(o,k,s,m,A,i.permissions,i.password));let te=async t=>{try{let i={size:1};await ee(t,i),n?.noTwoWay||await dl(`Create`,o,k,A,A,m,c,t,i,r,T,void 0,D);let a=Be(c);ic(`create`,t,e,k,A,c,m,n,a,p.FieldValue.arrayUnion,p.FieldValue.arrayRemove,p.FieldValue.delete,e=>S.collection(`tenants`).doc(o).collection(`system_fields`).doc(h.collection).collection(`${h.collection}-${e.name}`).doc(k),(e,t)=>S.collection(`tenants`).doc(o).collection(`system_unique`).doc(h.collection).collection(`Unique-${h.collection}-${e.name}`).doc(t),e=>S.collection(`tenants`).doc(o).collection(`system_fields`).doc(h.collection).collection(`${h.collection}-${e}`).doc(k),(e,t)=>Rc(S,e,o).doc(t),(e,t,n)=>S.collection(`tenants`).doc(o).collection(`system_fields`).doc(e.collection).collection(`${e.collection}-${t}`).doc(n),(e,t,n)=>S.collection(`tenants`).doc(o).collection(`system_fields`).doc(e.collection).collection(`${e.collection}-${t.replaceAll(` `,`-`)}`).doc(n),void 0,void 0,i),t.set(O.doc(k),A)}catch(t){if(n?.providedTransaction)throw t;{let n=await F(`postWriteError`,s,b,{operation:`create`,data:A,recordId:k,context:a,error:t});if(v&&(await new Promise(e=>{setTimeout(e,250)}),await Jc(`create`,n?.resolved?`success`:`failed`,A,o,e,k,m,n?.resolved?void 0:t)),!n?.resolved)throw m.auth&&i&&await Yc(A),t}}};if(n?.providedTransaction?await te(n.providedTransaction):await S.runTransaction(async e=>{await te(e)},{maxAttempts:10}),!n?.providedTransaction){let e={operation:`create`,data:A,recordId:k,context:a},t={...e};await F(`postWrite`,s,b,e),await F(`postOperation`,s,b,t)}return{id:k,...A}},yl=async(e,t,n,r)=>{let i=Ec(),a=(0,_.getAuth)(),o=$(),s=t.customClaims||{},c=!1;try{await a.updateUser(e,{email:t.email,disabled:t.disabled,displayName:t.displayName,photoURL:t.photoURL,emailVerified:!!t.emailVerified})}catch{c=!0}try{await a.setCustomUserClaims(e,{...s})}catch{c=!0}try{await o.collection(`tenants`).doc(i).collection(`system_user_permissions`).doc(e).update({...n,Collection:s.collection,Doc_ID:s.doc,Role:s.role,Enabled:!t.disabled})}catch{c=!0}if(c)throw Error(`ROLLBACK_FAILED: ${r}`)},bl=async(e,t,n,r,i,a,o,s,c,l,u)=>{let d=(0,_.getAuth)(),f=$(),p={};for(let e of i.fields)e.saveToAuthToken&&!Qc(e.name)&&a[e.name]!==void 0&&e.type!==`Timestamp`&&e.type!==`Computed`&&e.type!==`Embedding`&&(fe(a[e.name])?p[e.name]=null:p[e.name]=a[e.name]);let m=`USER_ERROR`,h=``;if(e===`create`){if(!u)throw Error(`VALIDATION_ERROR: Password is required`);if(!c)throw Error(`VALIDATION_ERROR: Permissions are required`);try{h=await el(t,n,r,i,a,c,u)}catch(e){throw Error(e.message)}}else if(e===`update`){if(!l||!s)throw Error(`USER_ERROR`);let e={};if(o.Name!==a.Name&&(e.displayName=a.Name),o.Email!==a.Email&&(e.email=a.Email,e.emailVerified=!1),o.Photo_URL!==a.Photo_URL&&(e.photoURL=a.Photo_URL?a.Photo_URL:void 0),o.Enabled!==a.Enabled&&(e.disabled=!a.Enabled),u&&(e.password=u),Object.keys(e).length)try{await d.updateUser(o.User_ID,e),e.disabled===!0&&await d.revokeRefreshTokens(o.User_ID)}catch{throw await yl(o.User_ID,s,l,m),Error(m)}if(a.Role&&a.Role!==o.Role||Object.keys(p).length)try{let e={...$c(s.customClaims),...p};await d.setCustomUserClaims(o.User_ID,{...e,tenant:t,role:a.Role,collection:i.labels.collection,doc:n}),await d.revokeRefreshTokens(o.User_ID)}catch{throw await yl(o.User_ID,s,l,m),Error(m)}try{await f.collection(`tenants`).doc(t).collection(`system_user_permissions`).doc(o.User_ID).set({...c||l,Collection:i.labels.collection,Doc_ID:n,Role:a.Role,Enabled:a.Enabled??o.Enabled??!1})}catch{throw await yl(o.User_ID,s,l,m),Error(m)}if(o.Email!==a.Email){let e=r.auth.enableMultiFactorAuth;if(e===!0||typeof e==`object`&&e.includes(a.Role)){let e=await d.generateEmailVerificationLink(a.Email).catch(()=>{throw Error(`Error generating email verification link`)});if(e.includes(`apiKey=&`)){let t=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);e=e.replace(`apiKey=&`,`apiKey=${t.apiKey}&`)}if(e){let t=`https://${d.app.options.projectId}.firebaseapp.com/__/auth/action${e}`,n=await P(r.appName),i=r?.mail?.emailVerification&&r.mail.emailVerification(t,n);try{await Xc(a.Email,i?.subject||`Please verify your email address`,void 0,i?.html||`Please verify your email address by clicking the link:
|
|
7
|
+
<a href="${t}">${t}</a>`)}catch(e){throw console.error(e.message),await f(i,d),Error(d)}}}return p.uid},tl=async(e,t)=>{let{labels:n,parentCollection:r}=t;if(r){let t=e.at(-2);if(!t)throw Error(`PERMISSION_DENIED`);let r=await qc([...e].slice(0,-2),t).catch(()=>{throw Error(`PERMISSION_DENIED`)}),i=r.Collection_Path;if(i.push(r.id),i.push(n.collection),!(0,c.default)(e,i))throw Error(`PERMISSION_DENIED`)}else if(e.length>1)throw Error(`PERMISSION_DENIED`)},nl=e=>typeof e==`object`&&!!e&&!Array.isArray(e),rl=e=>{let t=e=>{Object.entries(e).forEach(([n,r])=>{nl(r)&&Object.keys(r).length===2&&typeof r.seconds==`number`&&typeof r.nanoseconds==`number`?e[n]=new p.Timestamp(r.seconds,r.nanoseconds):nl(r)&&t(r)})};t(e)},il=e=>{let t=e=>{Object.entries(e).forEach(([n,r])=>{nl(r)&&Object.keys(r).length===2&&typeof r._seconds==`number`&&typeof r._nanoseconds==`number`?e[n]=new p.Timestamp(r._seconds,r._nanoseconds):nl(r)&&t(r)})};t(e)},al=e=>{if(typeof e==`object`)for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&(e[t]===`_DELETE_FIELD`?e[t]=p.FieldValue.delete():al(e[t]))},ol=(e,t,n)=>{if(M(n)&&n.includeFields){let r={};return n.includeFields.forEach(n=>{t[n]!==void 0&&(r[n]=t[n],Ge(e,[j(e.fields,n)]).size===1&&(r[`${n}_Lowercase`]=t[`${n}_Lowercase`]))}),r}return{}},sl=async(e,t,n,r,i,a,o)=>{if(!M(n)||!n.enforceHierarchy)return;let{fields:s}=t,c=$(),l=Object.entries(r[n.name]);if(!l.length)throw Error(`VALIDATION_ERROR: relation ${n.name} is required`);let[u,d]=l[0];if(!d)throw Error(`VALIDATION_ERROR: Relation ${n.name} is required`);let f=Rc(c,d.Collection_Path,e);if(a.size++,!o&&a.size>500)throw Error(`VALIDATION ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks, entity restrictions (in permissions when dealing with user collections) or relation hierarchy checks.`);let p=await i.get(f.doc(u));if(!p.exists)throw Error(`VALIDATION_ERROR: Record ${u} not found in collection ${n.collection}`);let m=p.data(),h=j(s,n.enforceHierarchy.field),g=n.enforceHierarchy;if(!m[g.recordLinkField]||!r[h.name]||!Object.keys(r[h.name]).every(e=>Object.keys(m[g.recordLinkField]).includes(e)))throw Error(`VALIDATION_ERROR: Invalid relation hierarchy`)},cl=async(e,t,n)=>{delete t[e.name][n],t[`${e.name}_Array`]=t[`${e.name}_Array`]?.filter(e=>e!==n),delete t[`${e.name}_Single`]},ll=async(e,t,n,r,i)=>{t[e.name]||={},t[e.name][r]=n,t[`${e.name}_Array`]||=[],t[`${e.name}_Array`].push(r),i&&(t[`${e.name}_Single`]={id:r,...n})},ul=(e,t,n,r,i,a)=>{let o=[],s=[];for(let c of r.fields)M(c)&&c.twoWay&&c.collection===n&&((e===`Create`||!a?.[c.name]?.[t])&&i[c.name]?.[t]&&o.push(c),e===`Update`&&a?.[c.name]?.[t]&&!i[c.name]?.[t]&&s.push(c));return{addedFields:o,removedFields:s}},dl=async(e,t,n,r,i,a,o,s,l,u,f,p,m)=>{let{fields:h}=a,g=$(),_=new Map,v=new Map,y=new Map;for(let n of h)M(n)&&[`OneToOne`,`OneToMany`].includes(n.type)&&n.enforceHierarchy&&r[n.name]&&(e===`Create`||e===`Update`&&!(0,c.default)(p?.[n.name],r[n.name]))&&await sl(t,a,n,r,s,l);for(let c of h)if(M(c)&&c.twoWay){let u=o.collections[c.collection],f=j(u.fields,c.twoWay),m=We(u,[f]);if(r[c.name]){let o=Object.entries(r[c.name]);for(let u of o){let[o,h]=u;if(e===`Create`||!p?.[c.name]?.[o]){let e,u=y.get(c.collection)?.[o];if(u)e=u;else{l.size++,l&&l.size>500&&console.error(Error(`VALIDATION_ERROR: ${l.size} operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of two way updates, unique field checks, entity restrictions (in permissions when dealing with user collections) or relation hierarchy checks.`));let n=Rc(g,h.Collection_Path,t),a=await s.get(n.doc(o));if(!a.exists){cl(c,i,o);continue}let u=a.data();v.set(c.collection,{...v.get(c.collection)||{},[o]:u}),e=(0,d.default)({...u,...Ve(r)})}let p={...e[f.name],[n]:{Collection_Path:r.Collection_Path,...ol(a,r,f)}};e[f.name]=p,e[`${f.name}_Array`]||=[],e[`${f.name}_Array`].push(n),m.size===1&&(e[`${f.name}_Single`]={id:n,...p}),y.set(c.collection,{...y.get(c.collection)||{},[o]:e})}}}if(e===`Update`){let e=Object.entries(p?.[c.name]||{});for(let i of e){let[e,a]=i;if(!r[c.name]?.[e]){let i,o=y.get(c.collection)?.[e];if(o)i=o;else{l.size++,l&&l.size>500&&console.error(Error(`VALIDATION_ERROR: ${l.size} operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of two way updates, unique field checks, entity restrictions (in permissions when dealing with user collections) or relation hierarchy checks.`));let n=Rc(g,a.Collection_Path,t),o=await s.get(n.doc(e));if(!o.exists){_.set(c.name,[..._.get(c.name)||[],e]);continue}let u=o.data();v.set(c.collection,{...v.get(c.collection)||{},[e]:u}),i=(0,d.default)({...u,...Ve(r)})}i[f.name][n]&&delete i[f.name][n],Array.isArray(i[`${f.name}_Array`])&&(i[`${f.name}_Array`]=i[`${f.name}_Array`].filter(e=>e!==n)),m.size===1&&delete i[`${f.name}_Single`],y.set(c.collection,{...y.get(c.collection)||{},[e]:i})}}}}for(let[n,c]of y.entries()){let d=o.collections[n],h=jc(n,o);for(let[g,_]of Object.entries(c)){let{addedFields:c,removedFields:y}=ul(e,g,n,a,r,p);if(u&&f){for(let e of c)if(!A(d,j(d.fields,e.twoWay),f,m??{})){cl(e,i,g);continue}for(let e of y){let t=j(d.fields,e.twoWay),n=We(d,[t]);if(!A(d,t,f,m??{})){ll(e,i,p?.[e.name]?.[g],g,n.size===1);continue}}if(!ie(`Update`,d,o,u,f,v.get(n)?.[g])){for(let e of c)cl(e,i,g);for(let e of y){let t=We(d,[j(d.fields,e.twoWay)]);ll(e,i,p?.[e.name]?.[g],g,t.size===1)}}if(!ie(`Update`,d,o,u,f,_)){for(let e of c)cl(e,i,g);for(let e of y){let t=We(d,[j(d.fields,e.twoWay)]);ll(e,i,p?.[e.name]?.[g],g,t.size===1)}}}try{await rc(`update`,_,d,h,{operation:`update`,data:_,context:{},originalRecord:_},o)}catch(e){throw Error(`VALIDATION_ERROR: Two way relation update would invalidate record ${g} in ${n}: ${e.message}`)}for(let e of c){let n=j(d.fields,e.twoWay);[`OneToOne`,`OneToMany`].includes(n.type)&&M(n)&&n.enforceHierarchy&&await sl(t,d,n,_,s,l,!0)}}}return _},fl=(e,t,n)=>{e===`create`&&Oe.forEach(e=>{if(!(0,c.default)(t[e],n[e]))throw Error(`Updating system fields in hooks is not allowed: ${e}`)}),e===`update`&&([`id`,`Collection_Path`,`Created_At`,`Saved_At`,`Created_By`].forEach(e=>{if(e in t)throw Error(`Cannot update system field: ${e}`)}),Oe.forEach(e=>{if(![`id`,`Collection_Path`,`Created_At`,`Saved_At`,`Created_By`].includes(e)&&!(0,c.default)(t[e],n[e]))throw Error(`Updating system fields in hooks is not allowed: ${e}`)}))},pl=(e,t,n,r)=>{let{softDelete:i}=t;if(!i)return;let a=i?.archivedField,o=i?.timestampField;if(n[a]===!0){if(e===`create`)n[o]=p.FieldValue.serverTimestamp();else{if(!r)throw Error(`Original record is required for update`);if(!r[a])n[o]=p.FieldValue.serverTimestamp();else if(n[o]&&n[o]?.valueOf()!==r[o]?.valueOf())throw Error(`Soft delete timestamp cannot be changed`)}}},ml=async(e,t,n,r,i)=>{if(!T(`Read`,i.collections?.[t.labels.collection]))return!1;try{await qc([t.labels.collection],n,{userId:r,providedTransaction:e})}catch{return!1}return!0},hl=10,gl=async(e,t)=>{if(e.length===0)return;let n=Math.min(t,e.length),r=0;await Promise.all(Array.from({length:n},async()=>{for(;r<e.length;){let t=r;r+=1,await e[t]()}}))},_l=async(e,t,n,r,i,a,o)=>{for(let[s,c]of Object.entries(t?.collections||{})){if(!i.collections[s])throw Error(`PERMISSION_DENIED`);let l=i.collections[s].access,u=i.collections[s];if(r.collections?.[s]?.restrictEntities||r?.collections?.[s]?.recordOwner?.active||r?.collections?.[s]?.recordUser?.active||r?.collections?.[s]?.recordProperty?.active){let d=a?.collections?.[s],f=[];if(c.individualEntities){let t=c.individualEntities,i=d?.individualEntities||[],s=a?t.filter(e=>!i.includes(e)):t;for(let t of s){if(o&&o.size++,o&&o.size>500)throw Error(`VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks or entity restrictions (in permissions when dealing with user collections).`);f.push(async()=>{if(!await ml(e,u,t,n,r))throw Error(`PERMISSION_DENIED`)})}}if(c.parentEntities){let s=l.entityRestrictions?.restrictions?.find(e=>e.type===`Parent`&&e.roles.some(e=>e.role===t.Role));if(!s)throw Error(`PERMISSION_DENIED`);let p=j(u.fields,s.collectionField),m=i.collections[p.collection],h=c.parentEntities,g=d?.parentEntities||[],_=a?h.filter(e=>!g.includes(e)):h;for(let t of _){if(o&&o.size++,o&&o.size>500)throw Error(`VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks or entity restrictions (in permissions when dealing with user collections).`);f.push(async()=>{if(!await ml(e,m,t,n,r))throw Error(`PERMISSION_DENIED`)})}}if(c.parentPropertyEntities){let s=l.entityRestrictions?.restrictions?.find(e=>e.type===`Parent_Property`&&e.roles.some(e=>e.role===t.Role));if(!s)throw Error(`PERMISSION_DENIED`);let p=j(u.fields,s.collectionField),m=i.collections[p.collection],h=c.parentPropertyEntities,g=d?.parentPropertyEntities||{};for(let[t,i]of Object.entries(h)){let s=g[t]||[],c=a?i.filter(e=>!s.includes(e)):i;for(let t of c){if(o&&o.size++,o&&o.size>500)throw Error(`VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks or entity restrictions (in permissions when dealing with user collections).`);f.push(async()=>{if(!await ml(e,m,t,n,r))throw Error(`PERMISSION_DENIED`)})}}}await gl(f,hl)}}},vl=async(e,t,n)=>{let r=n?.userId,i=n?.user,a=n?.context,o=Ec(),s=Ac();if(n?.providedTransaction&&r||n?.providedSchema&&r)throw Error(`PERMISSION_DENIED`);let c=n?.providedSchema||await Ic();if(e.length===0)throw Error(`EMPTY_PATH`);let l=e.at(-1),u=Object.keys(c.collections).includes(l),f=s.disabledCollections?.includes(l);if(!u||f)throw Error(`COLLECTION_NOT_FOUND`);let m=c.collections[l],{labels:h,fields:g,enableWriteLog:v,softDelete:y}=m,b=jc(h.collection,c),x=await P(s.appName),S=$(),C=(0,_.getAuth)(),w=r?await C.getUser(r):void 0,T,D;r&&await tl(e,m);let O=Rc(S,e,o),k=n?.id||O.doc().id;a||={},a.collection=h.collection,t.id=k,il(t),al(t);let A=Ue(`create`,e,t,c,x,`Online`,r||`System`,p.Timestamp.now(),p.FieldValue.serverTimestamp());n?.createdAt&&(A.Created_At=n.createdAt),n?.createdBy&&(A.Created_By=n.createdBy);let j=(0,d.default)(A);y&&(A[y.archivedField]=!1),ac(t),qe(m,A,c),v&&!n?.providedTransaction&&await Jc(`create`,`started`,A,o,e,k,m),await F(`preOperation`,s,b,{operation:`create`,data:A,recordId:k,context:a}),await F(`preWrite`,s,b,{operation:`create`,data:A,recordId:k,context:a}),qe(m,A,c),Je(m,A);let M=(r?await S.collection(`tenants`).doc(o).collection(`system_user_permissions`).doc(r).get():void 0)?.data();await Ye(A,m,b,M,w?.customClaims||{}),ac(A);try{if(m.auth&&i){if(!i.password)throw Error(`Password is required`);if(!A.Role)throw Error(`Role field is required`);if(!A.Email)throw Error(`Email field is required`);if(A.Enabled===void 0||A.Enabled===null)throw Error(`Enabled field is required`)}n?.providedTransaction||await rc(`create`,A,m,b,{operation:`create`,data:A,context:a},c)}catch(e){throw Error(`VALIDATION_ERROR: ${e.message}`)}ac(A),t.id=k,y&&(A[y.archivedField]=!1),qe(m,A,c),Je(m,A);try{fl(`create`,A,j),pl(`create`,m,A),await rc(`create`,A,m,b,{operation:`create`,data:A,context:a},c)}catch(e){throw Error(`VALIDATION_ERROR: ${e.message}`)}if(r){if(!w||!M?.Role)throw Error(`USER_ERROR`);let e=M;if(!(b.custom?.serverAccess?.create===void 0||await P(b.custom.serverAccess.create,[e,w,A])))throw Error(`PERMISSION_DENIED`);for(let t of m.fields){if(!(t.name in A))continue;let n=xe(t,b);if(n?.custom?.serverAccess?.create!==void 0&&!await P(n.custom.serverAccess.create,[e,w,A]))throw Error(`PERMISSION_DENIED`)}}i&&(i.permissions||={},i.permissions.Role||=A.Role,i.permissions.Enabled||=A.Enabled);let ee=async(e,t)=>{let[a,s,l,u,d]=await Promise.all([n?.providedTransaction?Promise.resolve({}):e.get(S.collection(`system_deployment`).doc(`latest_deploy`)),n?.providedTransaction?Promise.resolve({}):e.get(S.collection(`system_deployment`).doc(`maintenance_mode`)),r?e.get(S.collection(`tenants`).doc(o).collection(`system_user_permissions`).doc(r)):Promise.resolve({}),n?.providedSchema?Promise.resolve(n.providedSchema):Ic(),r?Vc(r):Promise.resolve(void 0)]);if(t&&(t.size+=3),!n?.providedTransaction){if(!a.exists)throw Error(`VERSION_ERROR`);let e=a.data();if(e.force&&A.Last_Write_At.valueOf()<e.time.valueOf())throw Error(`VERSION_ERROR`);if(!s.exists||s.data().active)throw Error(`MAINTENANCE_MODE`)}if(c=u,r){if(!l?.exists)throw Error(`PERMISSION_DENIED`);if(T=l.data(),!T.Role)throw Error(`USER_ERROR`);if(!T.Enabled)throw Error(`PERMISSION_DENIED`);D=d?.customClaims??{}}if(!n?.providedTransaction){let n=g.filter(e=>`unique`in e&&e.unique).map(async n=>{if(!r||!n.access||E(n,T,m,D)){if(!A[n.name])return;let i=xe(n,b);if(!(!(r&&T&&d&&i?.custom?.serverAccess?.read!==void 0)||await P(i.custom.serverAccess.read,[T,d,A])))throw Error(`PERMISSION_DENIED`);let a=A[n.name].toString().toLowerCase().replace(/\s/g,`---`).replaceAll(`/`,`|||`);if(oc(a)){if(t&&t.size++,t&&t.size>500)throw Error(`VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks.`);if((await e.get(S.collection(`tenants`).doc(o).collection(`system_unique`).doc(h.collection).collection(`Unique-${h.collection}-${n.name}`).doc(a)))?.exists)throw Error(`VALIDATION_ERROR: ${n.name} "${A[n.name]}" already exists`)}else throw Error(`VALIDATION_ERROR: ${n.name} "${A[n.name]}" is invalid`)}});await Promise.all(n)}de(A,k,m,c,r,T,i?.permissions,D),i?.permissions&&r&&T&&await _l(e,i.permissions,r,T,c),de(A,k,m,c,r,T,i?.permissions,D)};m.auth&&i&&(await S.runTransaction(async e=>{await ee(e)},{maxAttempts:10}),A.User_ID=await el(o,k,s,m,A,i.permissions,i.password));let te=async t=>{try{let i={size:1};await ee(t,i),n?.noTwoWay||await dl(`Create`,o,k,A,A,m,c,t,i,r,T,void 0,D);let a=Be(c);ic(`create`,t,e,k,A,c,m,n,a,p.FieldValue.arrayUnion,p.FieldValue.arrayRemove,p.FieldValue.delete,e=>S.collection(`tenants`).doc(o).collection(`system_fields`).doc(h.collection).collection(`${h.collection}-${e.name}`).doc(k),(e,t)=>S.collection(`tenants`).doc(o).collection(`system_unique`).doc(h.collection).collection(`Unique-${h.collection}-${e.name}`).doc(t),e=>S.collection(`tenants`).doc(o).collection(`system_fields`).doc(h.collection).collection(`${h.collection}-${e}`).doc(k),(e,t)=>Rc(S,e,o).doc(t),(e,t,n)=>S.collection(`tenants`).doc(o).collection(`system_fields`).doc(e.collection).collection(`${e.collection}-${t}`).doc(n),(e,t,n)=>S.collection(`tenants`).doc(o).collection(`system_fields`).doc(e.collection).collection(`${e.collection}-${t.replaceAll(` `,`-`)}`).doc(n),void 0,void 0,i),t.set(O.doc(k),A)}catch(t){if(n?.providedTransaction)throw t;{let n=await F(`postWriteError`,s,b,{operation:`create`,data:A,recordId:k,context:a,error:t});if(v&&(await new Promise(e=>{setTimeout(e,250)}),await Jc(`create`,n?.resolved?`success`:`failed`,A,o,e,k,m,n?.resolved?void 0:t)),!n?.resolved)throw m.auth&&i&&await Yc(A),t}}};if(n?.providedTransaction?await te(n.providedTransaction):await S.runTransaction(async e=>{await te(e)},{maxAttempts:10}),!n?.providedTransaction){let e={operation:`create`,data:A,recordId:k,context:a},t={...e};await F(`postWrite`,s,b,e),await F(`postOperation`,s,b,t)}return{id:k,...A}},yl=async(e,t,n,r)=>{let i=Ec(),a=(0,_.getAuth)(),o=$(),s=t.customClaims||{},c=!1;try{await a.updateUser(e,{email:t.email,disabled:t.disabled,displayName:t.displayName,photoURL:t.photoURL,emailVerified:!!t.emailVerified})}catch{c=!0}try{await a.setCustomUserClaims(e,{...s})}catch{c=!0}try{await o.collection(`tenants`).doc(i).collection(`system_user_permissions`).doc(e).update({...n,Collection:s.collection,Doc_ID:s.doc,Role:s.role,Enabled:!t.disabled})}catch{c=!0}if(c)throw Error(`ROLLBACK_FAILED: ${r}`)},bl=async(e,t,n,r,i,a,o,s,c,l,u)=>{let d=(0,_.getAuth)(),f=$(),p={};for(let e of i.fields)e.saveToAuthToken&&!Qc(e.name)&&a[e.name]!==void 0&&e.type!==`Timestamp`&&e.type!==`Computed`&&e.type!==`Embedding`&&(fe(a[e.name])?p[e.name]=null:p[e.name]=a[e.name]);let m=`USER_ERROR`,h=``;if(e===`create`){if(!u)throw Error(`VALIDATION_ERROR: Password is required`);if(!c)throw Error(`VALIDATION_ERROR: Permissions are required`);try{h=await el(t,n,r,i,a,c,u)}catch(e){throw Error(e.message)}}else if(e===`update`){if(!l||!s)throw Error(`USER_ERROR`);let e={};if(o.Name!==a.Name&&(e.displayName=a.Name),o.Email!==a.Email&&(e.email=a.Email,e.emailVerified=!1),o.Photo_URL!==a.Photo_URL&&(e.photoURL=a.Photo_URL?a.Photo_URL:void 0),o.Enabled!==a.Enabled&&(e.disabled=!a.Enabled),u&&(e.password=u),Object.keys(e).length)try{await d.updateUser(o.User_ID,e),e.disabled===!0&&await d.revokeRefreshTokens(o.User_ID)}catch{throw await yl(o.User_ID,s,l,m),Error(m)}if(a.Role&&a.Role!==o.Role||Object.keys(p).length)try{let e={...$c(s.customClaims),...p};await d.setCustomUserClaims(o.User_ID,{...e,tenant:t,role:a.Role,collection:i.labels.collection,doc:n}),await d.revokeRefreshTokens(o.User_ID)}catch{throw await yl(o.User_ID,s,l,m),Error(m)}try{await f.collection(`tenants`).doc(t).collection(`system_user_permissions`).doc(o.User_ID).set({...c||l,Collection:i.labels.collection,Doc_ID:n,Role:a.Role,Enabled:a.Enabled??o.Enabled??!1})}catch{throw await yl(o.User_ID,s,l,m),Error(m)}if(o.Email!==a.Email){let e=r.auth.enableMultiFactorAuth;if(e===!0||typeof e==`object`&&e.includes(a.Role)){let e=await d.generateEmailVerificationLink(a.Email).catch(()=>{throw Error(`Error generating email verification link`)});if(e.includes(`apiKey=&`)){let t=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);e=e.replace(`apiKey=&`,`apiKey=${t.apiKey}&`)}if(e){let t=`https://${d.app.options.projectId}.firebaseapp.com/__/auth/action${e}`,n=await P(r.appName),i=r?.mail?.emailVerification&&r.mail.emailVerification(t,n);try{await Xc(a.Email,i?.subject||`Please verify your email address`,void 0,i?.html||`Please verify your email address by clicking the link:
|
|
8
8
|
</br>
|
|
9
9
|
</br>
|
|
10
10
|
<a href="${t}">${t}</a>`)}catch{throw await yl(o.User_ID,s,l,m),Error(m)}}}}}else if(e===`delete`)try{await Yc(o)}catch(e){throw Error(e.message)}if(h)return h},xl=async(e,t,n)=>{let r=Ec(),i=$(),a=[t];n&&n.trim()!==``&&a.push(n),a.sort();let o=[];for(let t of a){let n=i.collection(`tenants`).doc(r).collection(`system_locks`).doc(t);if((await e.get(n)).exists)throw Error(`DOCUMENT_LOCKED`);o.push(n)}for(let t of o)e.set(t,{locked:!0})},Sl=async(e,t)=>{let n=Ec(),r=$(),i=[e];t&&t.trim()!==``&&i.push(t),i.sort();let a=r.batch();for(let e of i){let t=r.collection(`tenants`).doc(n).collection(`system_locks`).doc(e);a.delete(t)}await a.commit()},Cl=async(e,t,n,r)=>{let i=r?.userId,a=r?.user,o=r?.context,s=Ec(),c=Ac();if(r?.providedTransaction&&i||r?.providedSchema&&i||r?.providedTransaction&&!r?.originalRecord)throw Error(`PERMISSION_DENIED`);let l=r?.providedSchema||await Ic(!0);if(e.length===0)throw Error(`EMPTY_PATH`);let u=e.at(-1),f=Object.keys(l.collections).includes(u),m=c.disabledCollections?.includes(u);if(!f||m)throw Error(`COLLECTION_NOT_FOUND`);let h=l.collections[u],{labels:g,fields:v,enableWriteLog:y}=h,b=jc(g.collection,l),x=await P(c.appName),S=(0,_.getAuth)(),C=$(),w,T;i&&await tl(e,h);let D=Rc(C,e,s);o||={},o.collection=g.collection;let O=r?.originalRecord||await qc(e,t,{userId:i,noComputedFields:!0,noEmbeddingFields:!0}),k=O;i&&(k=await qc(e,t,{noComputedFields:!0,noEmbeddingFields:!0}));for(let e of v)e.type===`Computed`&&(delete n[e.name],delete O[e.name]);if(l={...l,collections:Object.fromEntries(Object.entries(l.collections).map(([e,t])=>[e,{...t,fields:t.fields.filter(e=>e.type!==`Computed`)}]))},a&&!a.operation)throw Error(`VALIDATION_ERROR: User operation is required`);if(a&&!h.auth)throw Error(`VALIDATION_ERROR: User operations are only permitted for auth collections`);if(a?.operation===`delete`&&a.permissions)throw Error(`VALIDATION_ERROR: Permissions are not allowed for delete operations`);let A=h.fields.filter(e=>e.saveToAuthToken&&!Qc(e.name)),j=h.auth&&a?.operation===`create`,ee=h.auth&&a?.operation===`delete`,te=h.auth&&!j&&!ee&&(a?.operation===`update`||O.User_ID&&(n.Role||n.Enabled!==void 0||n.Name||n.Email||n.Photo_URL||A.some(e=>n[e.name]!==void 0))),ne=e=>e.User_ID&&(h.auth&&!j&&!ee&&a?.operation===`update`||n.Role&&n.Role!==e.Role||n.Enabled!==void 0&&n.Enabled!==e.Enabled||n.Name&&n.Name!==e.Name||n.Email&&n.Email!==e.Email||n.Photo_URL&&n.Photo_URL!==e.Photo_URL||A.some(t=>n[t.name]!==void 0&&n[t.name]!==e[t.name]));delete n.id,il(n),al(n);let N=Ue(`update`,e,n,l,x,`Online`,i||`System`,p.Timestamp.now(),p.FieldValue.serverTimestamp()),re=(0,d.default)(N);for(let e of v)!M(e)&&fe(N[e.name])&&e.nullable&&(N[e.name]=null);ac(N),ac(O),qe(h,N,l),qe(h,O,l),y&&!r?.providedTransaction&&await Jc(`update`,`started`,N,s,e,t,h,void 0,O),await F(`preOperation`,c,b,{operation:`update`,data:N,recordId:t,context:o,originalRecord:(0,d.default)(O)}),await F(`preWrite`,c,b,{operation:`update`,data:N,recordId:t,context:o,originalRecord:(0,d.default)(O)}),qe(h,N,l),Je(h,N),ac(N);try{if(j&&!a?.password)throw Error(`Password is required`);if(!r?.providedTransaction){let e={...k,...N};pe(e),await rc(`update`,e,h,b,{operation:`update`,data:N,context:o,originalRecord:(0,d.default)(O)},l)}}catch(e){throw Error(`VALIDATION_ERROR: ${e.message}`)}ac(N),delete n.id,qe(h,N,l),Je(h,N);for(let e of v)!M(e)&&fe(N[e.name])&&e.nullable&&(N[e.name]=null);try{let e={...k,...N};pe(e),pl(`update`,h,N,O),fl(`update`,N,re),await rc(`update`,e,h,b,{operation:`update`,data:N,context:o,originalRecord:(0,d.default)(O)},l)}catch(e){throw Error(`VALIDATION_ERROR: ${e.message}`)}let ie;a&&(a.permissions||={});let ae=async(n,o,c)=>{let[u,f,p,m,_,y]=await Promise.all([r?.providedTransaction?Promise.resolve({}):n.get(C.collection(`system_deployment`).doc(`latest_deploy`)),r?.providedTransaction?Promise.resolve({}):n.get(C.collection(`system_deployment`).doc(`maintenance_mode`)),r?.providedTransaction?Promise.resolve(O):qc(e,t,{userId:i,providedTransaction:n,noComputedFields:!0}),i?n.get(C.collection(`tenants`).doc(s).collection(`system_user_permissions`).doc(i)):Promise.resolve({}),r?.providedSchema?Promise.resolve(r.providedSchema):Ic(),i?Vc(i):Promise.resolve(void 0)]);if(c&&(c.size+=3),!r?.providedTransaction){if(!u.exists)throw Error(`VERSION_ERROR`);let e=u.data();if(e.force&&N.Last_Write_At.valueOf()<e.time.valueOf())throw Error(`VERSION_ERROR`);if(!f.exists||f.data().active)throw Error(`MAINTENANCE_MODE`)}if(!p)throw Error(`NOT_FOUND`);if(O=p,l=_,i){if(!m?.exists)throw Error(`PERMISSION_DENIED`);if(w=m.data(),!w.Role)throw Error(`USER_ERROR`);if(!w.Enabled)throw Error(`PERMISSION_DENIED`);T=y?.customClaims??{}}if(c&&(c.size+=Bc(s,e,t,l,w,T).length),j&&O.User_ID||ee&&!O.User_ID)throw Error(`USER_ERROR`);if(ne(O)){let e=await n.get(C.collection(`tenants`).doc(s).collection(`system_user_permissions`).doc(O.User_ID));if(c&&c.size++,!e?.exists)throw Error(`PERMISSION_DENIED`);ie=e.data();let t=a?.permissions&&Object.keys(a.permissions).length>0?a.permissions:void 0;if(N.Role&&N.Role!==O.Role&&!t&&(a||={operation:`update`,permissions:{}},a.permissions=(0,d.default)(ie),a.permissions.Role=N.Role),a?.permissions){if(a.permissions.Role||=N.Role||O.Role,a.permissions.Enabled??=N.Enabled??O.Enabled,fe(a.permissions.Role)||!a.permissions.Role)throw Error(`VALIDATION_ERROR: Role field is required`);if(fe(a.permissions.Enabled)||a.permissions.Enabled===void 0||a.permissions.Enabled===null)throw Error(`VALIDATION_ERROR: Enabled field is required`)}}if(j){let e={...O,...N};if(pe(e),!e.Role)throw Error(`VALIDATION_ERROR: Role field is required`);if(e.Enabled===void 0||e.Enabled===null)throw Error(`VALIDATION_ERROR: Enabled field is required`);if(!e.Email)throw Error(`VALIDATION_ERROR: Email field is required`);a?.permissions&&(a.permissions.Role||=e.Role,a.permissions.Enabled??=e.Enabled)}if(!r?.providedTransaction){let e=v.filter(e=>`unique`in e&&e.unique).map(async e=>{if(!i||!e.access||E(e,w,h,T)){if(N[e.name]===void 0||fe(N[e.name]))return;let r=xe(e,b),a={...O,...N};if(!(!(i&&w&&y&&r?.custom?.serverAccess?.read!==void 0)||await P(r.custom.serverAccess.read,[w,y,a])))throw Error(`PERMISSION_DENIED`);let o=N[e.name].toString().toLowerCase().replace(/\s/g,`---`).replaceAll(`/`,`|||`);if(oc(o)){if(c&&c.size++,c&&c.size>500)throw Error(`VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks.`);let r=await n.get(C.collection(`tenants`).doc(s).collection(`system_unique`).doc(g.collection).collection(`Unique-${g.collection}-${e.name}`).doc(o));if(r.exists&&r.data().id!==t)throw Error(`VALIDATION_ERROR: ${e.name} "${N[e.name]}" already exists`)}else throw Error(`VALIDATION_ERROR: ${e.name} "${N[e.name]}" is invalid`)}});await Promise.all(e)}if(i&&w?.Role){if(!y)throw Error(`USER_ERROR`);let e={...O,...N};if(!(b.custom?.serverAccess?.update===void 0||await P(b.custom.serverAccess.update,[w,y,e,O])))throw Error(`PERMISSION_DENIED`);for(let t of h.fields){let n=xe(t,b);if(Object.prototype.hasOwnProperty.call(N,t.name)&&n?.custom?.serverAccess?.update!==void 0&&!await P(n.custom.serverAccess.update,[w,y,e,O]))throw Error(`PERMISSION_DENIED`)}}me(N,O,t,h,l,i,w,a?.operation?a.operation:te?`update`:void 0,a?.permissions,ie,T),a?.permissions&&i&&w&&await _l(n,a.permissions,i,w,l,ie,c),me(N,O,t,h,l,i,w,a?.operation?a.operation:te?`update`:void 0,a?.permissions,ie,T),o&&(j||ne(O)||ee)&&await xl(n,t,O.User_ID)};(j||te||ee)&&await C.runTransaction(async e=>{await ae(e,!0)},{maxAttempts:10});let oe=async(n,a)=>{if(!O)throw Error(`NOT_FOUND`);try{let a={size:1},o={...O,...N};await ae(n,!1,a);let c;!r?.noTwoWay&&!r?.providedTransaction&&(c=await dl(`Update`,s,t,o,N,h,l,n,a,i,w,O,T));let u=Be(l);ic(`update`,n,e,t,N,l,h,r,u,p.FieldValue.arrayUnion,p.FieldValue.arrayRemove,p.FieldValue.delete,e=>C.collection(`tenants`).doc(s).collection(`system_fields`).doc(g.collection).collection(`${g.collection}-${e.name}`).doc(t),(e,t)=>C.collection(`tenants`).doc(s).collection(`system_unique`).doc(g.collection).collection(`Unique-${g.collection}-${e.name}`).doc(t),e=>C.collection(`tenants`).doc(s).collection(`system_fields`).doc(g.collection).collection(`${g.collection}-${e}`).doc(t),(e,t)=>Rc(C,e,s).doc(t),(e,t,n)=>C.collection(`tenants`).doc(s).collection(`system_fields`).doc(e.collection).collection(`${e.collection}-${t}`).doc(n),(e,t,n)=>C.collection(`tenants`).doc(s).collection(`system_fields`).doc(e.collection).collection(`${e.collection}-${t.replaceAll(` `,`-`)}`).doc(n),O,c,a),n.update(D.doc(t),N)}catch(n){if(r?.providedTransaction)throw n;{let r={operation:`update`,data:N,recordId:t,context:o,error:n,originalRecord:(0,d.default)(O)},i=await F(`postWriteError`,c,b,r);if(y&&(await new Promise(e=>{setTimeout(e,250)}),await Jc(`update`,i?.resolved?`success`:`failed`,N,s,e,t,h,i?.resolved?void 0:n,O)),!i?.resolved)throw j&&await Yc(O),ne(O)&&await yl(O.User_ID,a,ie,`USER_ERROR`),ee&&await C.collection(`tenants`).doc(s).collection(g.collection).doc(t).update({User_ID:p.FieldValue.delete()}),n}}(j||ne(O)||ee)&&await sc(Sl,[t,O.User_ID]).catch(()=>{throw Error(`USER_ERROR`)})};try{let e;if(j||ne(O)||ee){if(ne(O)){e=await S.getUser(O.User_ID);let t=e.customClaims;if(!(t&&t.role&&t.collection&&t.doc))throw Error(`USER_ERROR`)}let n={...O,...N};pe(n);let r=await bl(a?.operation||`update`,s,t,c,h,n,O,e,a?.permissions,ie,a?.password);j&&(N.User_ID=r),ee&&(N.User_ID=p.FieldValue.delete())}r?.providedTransaction?await oe(r.providedTransaction,e):await C.runTransaction(async t=>{await oe(t,e)},{maxAttempts:10})}catch(e){throw(j||ne(O)||ee)&&await sc(Sl,[t,O.User_ID]).catch(()=>{throw Error(`USER_ERROR`)}),e}if(!r?.providedTransaction){let e={operation:`update`,data:N,recordId:t,context:o,originalRecord:(0,d.default)(O)},n={...e};await F(`postWrite`,c,b,e),await F(`postOperation`,c,b,n)}let se={...O,...N};return pe(se),{id:t,...se}},wl=async(e,t,n)=>{let r=n?.userId,i=n?.context,a=Ec(),o=Ac(),s=await Ic();if(e.length===0)throw Error(`EMPTY_PATH`);let c=e.at(-1),l=Object.keys(s.collections).includes(c),u=o.disabledCollections?.includes(c);if(!l||u)throw Error(`COLLECTION_NOT_FOUND`);let d=s.collections[c],{labels:f,auth:m,enableWriteLog:h,softDelete:g}=d,_=jc(f.collection,s),v=await P(o.appName);if(g&&!m&&!n?.force)return await Cl(e,t,{[g.archivedField]:!0,[g.timestampField]:p.FieldValue.serverTimestamp()},{userId:r});let y=$(),b;r&&await tl(e,d);let x=Rc(y,e,a);i||={},i.collection=f.collection;let S=Ue(`delete`,e,await qc(e,t,{userId:r}),s,v,`Online`,r||`System`,p.Timestamp.now(),p.FieldValue.serverTimestamp()),C=Ve(S);ac(S),h&&await Jc(`delete`,`started`,S,a,e,t,d),await F(`preOperation`,o,_,{operation:`delete`,data:S,recordId:t,context:i}),await F(`preWrite`,o,_,{operation:`delete`,data:S,recordId:t,context:i}),ac(S);let w=async n=>{let[i,o,c,l,u]=await Promise.all([n.get(y.collection(`system_deployment`).doc(`maintenance_mode`)),qc(e,t,{userId:r,providedTransaction:n}),r?n.get(y.collection(`tenants`).doc(a).collection(`system_user_permissions`).doc(r)):Promise.resolve({}),Ic(),r?Vc(r):Promise.resolve(void 0)]);if(!i.exists||i.data().active)throw Error(`MAINTENANCE_MODE`);if(!o)throw Error(`NOT_FOUND`);if(S={...o,...C},s=l,r){if(!c?.exists)throw Error(`PERMISSION_DENIED`);if(b=c.data(),!b.Role)throw Error(`USER_ERROR`);if(!b.Enabled)throw Error(`PERMISSION_DENIED`);he(S,t,d,s,r,b)}if(r&&b?.Role){if(!u)throw Error(`USER_ERROR`);if(!(_.custom?.serverAccess?.delete===void 0||await P(_.custom.serverAccess.delete,[b,u,S])))throw Error(`PERMISSION_DENIED`)}};d.auth&&(await y.runTransaction(async e=>{await w(e)},{maxAttempts:10}),S.User_ID&&await Yc(S));try{await y.runTransaction(async r=>{await w(r);let i=Be(s);ic(`delete`,r,e,t,S,s,d,n,i,p.FieldValue.arrayUnion,p.FieldValue.arrayRemove,p.FieldValue.delete,e=>y.collection(`tenants`).doc(a).collection(`system_fields`).doc(f.collection).collection(`${f.collection}-${e.name}`).doc(t),(e,t)=>y.collection(`tenants`).doc(a).collection(`system_unique`).doc(f.collection).collection(`Unique-${f.collection}-${e.name}`).doc(t),e=>y.collection(`tenants`).doc(a).collection(`system_fields`).doc(f.collection).collection(`${f.collection}-${e}`).doc(t),(e,t)=>Rc(y,e,a).doc(t),(e,t,n)=>y.collection(`tenants`).doc(a).collection(`system_fields`).doc(e.collection).collection(`${e.collection}-${t}`).doc(n),(e,t,n)=>y.collection(`tenants`).doc(a).collection(`system_fields`).doc(e.collection).collection(`${e.collection}-${t.replaceAll(` `,`-`)}`).doc(n)),r.delete(x.doc(t))},{maxAttempts:10})}catch(n){let r=await F(`postWriteError`,o,_,{operation:`delete`,data:S,recordId:t,context:i,error:n});if(h&&(await new Promise(e=>{setTimeout(e,250)}),await Jc(`delete`,r?.resolved?`success`:`failed`,S,a,e,t,d,r?.resolved?void 0:n)),!r?.resolved)throw d.auth&&S.User_ID&&await y.collection(`tenants`).doc(a).collection(f.collection).doc(t).update({User_ID:p.FieldValue.delete()}),n}let T={operation:`delete`,data:S,recordId:t,context:i},E={...T};return await F(`postWrite`,o,_,T),await F(`postOperation`,o,_,E),{id:t,...S}},Tl=async(e,t)=>{let n=$(),r=Oc(),i=process.env.ADMIN_SMS;if(r===`development`){if(i)e=i;else throw Error(`Admin phone not set`)}let a={to:e,body:t};await n.collection(`system_messages`).add(a)},El=e=>typeof e==`object`&&!!e,Dl=e=>{let t=e=>{Object.entries(e).forEach(([n,r])=>{r instanceof p.Timestamp?e[n]={_seconds:r.seconds,_nanoseconds:r.nanoseconds}:El(r)&&t(r)})};t(e)},Ol=e=>{let t=kc();return Q.fromJSDate(e).setZone(t)},kl=e=>{let t=kc();return Q.fromJSDate(e.toDate()).setZone(t)},Al=(e,t)=>{let n=Q.fromJSDate(e,{zone:t}).offset-Q.fromJSDate(e).offset;return Q.fromJSDate(e).plus({minutes:n}).toJSDate()},jl=(e,t)=>{let n=Q.fromJSDate(e,{zone:t}).offset-Q.fromJSDate(e).offset;return Q.fromJSDate(e).minus({minutes:n}).toJSDate()},Ml=e=>`seconds`in e&&`nanoseconds`in e?kl(new p.Timestamp(e.seconds,e.nanoseconds)).toFormat(`MMMM d, yyyy '@' h:mm a`):``;exports.addRecord=vl,exports.addUser=el,exports.convertDateToTimezone=Ol,exports.convertTimestampToTimezone=kl,exports.deleteRecord=wl,exports.deleteUser=Yc,exports.deserializeDeleteSentinels=al,exports.deserializeTimestamps=il,exports.deserializeTimestampsWithoutUnderscores=rl,exports.displayDate=Ml,exports.fetchCurrentSchema=Ic,exports.fetchLastSchema=Lc,exports.getCachedConfigValue=we,exports.getCollectionRefs=zc,exports.getCustomizationFile=jc,exports.getCustomizationFiles=pc,exports.getDocumentRefs=Bc,exports.getFirestorePathRef=Rc,exports.getGlobalConfigModule=Ac,exports.getInputSchema=tc,exports.getMaintenanceInfo=Nc,exports.getMode=Oc,exports.getOne=qc,exports.getSome=Wc,exports.getStokerFirestore=$,exports.getTenant=Ec,exports.getTimezone=kc,exports.getUser=Vc,exports.getVersionInfo=Mc,exports.getZodSchema=Bn,exports.initializeFirebase=Fc,exports.initializeStoker=Tc,exports.isDeleteSentinel=fe,exports.keepTimezone=Al,exports.removeTimezone=jl,exports.runChildProcess=Pc,exports.sendMail=Xc,exports.sendMessage=Tl,exports.serializeTimestamps=Dl,exports.setTenant=Dc,exports.tryPromise=P,exports.updateRecord=Cl,exports.updateUser=bl,exports.validateRelations=dl,exports.validateSoftDelete=pl,exports.writeLog=Jc;
|
package/dist/bundle.js
CHANGED
|
@@ -8216,8 +8216,8 @@ var Xc = async (e, t, n, r, i, a, o) => {
|
|
|
8216
8216
|
photoURL: i.Photo_URL,
|
|
8217
8217
|
disabled: !i.Enabled
|
|
8218
8218
|
});
|
|
8219
|
-
} catch {
|
|
8220
|
-
throw Error(d);
|
|
8219
|
+
} catch (e) {
|
|
8220
|
+
throw console.error(e.message), Error(d);
|
|
8221
8221
|
}
|
|
8222
8222
|
let h = {};
|
|
8223
8223
|
for (let e of u) e.saveToAuthToken && !Jc(e.name) && i[e.name] !== void 0 && e.type !== "Timestamp" && e.type !== "Computed" && e.type !== "Embedding" && (ce(i[e.name]) ? h[e.name] = null : h[e.name] = i[e.name]);
|
|
@@ -8229,8 +8229,8 @@ var Xc = async (e, t, n, r, i, a, o) => {
|
|
|
8229
8229
|
collection: l.collection,
|
|
8230
8230
|
doc: t
|
|
8231
8231
|
});
|
|
8232
|
-
} catch {
|
|
8233
|
-
throw await f(i, d), Error(d);
|
|
8232
|
+
} catch (e) {
|
|
8233
|
+
throw console.error(e.message), await f(i, d), Error(d);
|
|
8234
8234
|
}
|
|
8235
8235
|
try {
|
|
8236
8236
|
await c.collection("tenants").doc(e).collection("system_user_permissions").doc(m.uid).set({
|
|
@@ -8240,16 +8240,16 @@ var Xc = async (e, t, n, r, i, a, o) => {
|
|
|
8240
8240
|
Collection: l.collection,
|
|
8241
8241
|
Doc_ID: t
|
|
8242
8242
|
});
|
|
8243
|
-
} catch {
|
|
8244
|
-
throw await f(i, d), Error(d);
|
|
8243
|
+
} catch (e) {
|
|
8244
|
+
throw console.error(e.message), await f(i, d), Error(d);
|
|
8245
8245
|
}
|
|
8246
8246
|
let g = n.auth.enableMultiFactorAuth;
|
|
8247
8247
|
if (g === !0 || typeof g == "object" && g.includes(i.Role)) {
|
|
8248
8248
|
let e;
|
|
8249
8249
|
try {
|
|
8250
8250
|
e = await s.generateEmailVerificationLink(i.Email);
|
|
8251
|
-
} catch {
|
|
8252
|
-
throw await f(i, d), Error(d);
|
|
8251
|
+
} catch (e) {
|
|
8252
|
+
throw console.error(e.message), await f(i, d), Error(d);
|
|
8253
8253
|
}
|
|
8254
8254
|
if (e.includes("apiKey=&")) {
|
|
8255
8255
|
let t = JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);
|
|
@@ -8262,8 +8262,8 @@ var Xc = async (e, t, n, r, i, a, o) => {
|
|
|
8262
8262
|
</br>
|
|
8263
8263
|
</br>
|
|
8264
8264
|
<a href="${t}">${t}</a>`);
|
|
8265
|
-
} catch {
|
|
8266
|
-
throw await f(i, d), Error(d);
|
|
8265
|
+
} catch (e) {
|
|
8266
|
+
throw console.error(e.message), await f(i, d), Error(d);
|
|
8267
8267
|
}
|
|
8268
8268
|
}
|
|
8269
8269
|
}
|