@stoker-platform/node-client 0.5.98 → 0.5.99

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 CHANGED
@@ -1,14 +1,10 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Xe=require("lodash/isEqual.js"),ta=require("lodash/merge.js"),na=require("lodash/set.js"),pe=require("lodash/cloneDeep.js"),vt=require("firebase-admin/app"),oe=require("firebase-admin/firestore"),Ei=require("node:url"),sa=require("cross-spawn"),vi=require("firebase-admin/database"),bt=require("firebase-admin/auth"),Qn=t=>!!t&&!Array.isArray(t),cn=(t,e)=>t.access?Qn(t.access)?!1:t.access.includes(e):!0,ra=(t,e)=>{if(Qn(t.access))return e.fieldAccessGroups?.[t.access.group]},qs=t=>{const e={};return Object.keys(t.fieldAccessGroups||{}).forEach(n=>{e[n]=[]}),t.fields.forEach(n=>{if(Qn(n.access)){const{group:s}=n.access;e[s]&&e[s].push(n)}}),e},Kn=(t,e,n,s)=>{if(!n)return!0;if(n.Role&&!t.applicableRoles.includes(n.Role))return!1;const r=n.collections?.[e],i=[];if(t.collectionAuth!==void 0&&i.push(!!r?.auth===t.collectionAuth),t.roles&&i.push(!!n.Role&&t.roles.includes(n.Role)),t.claims&&i.push(Object.entries(t.claims).every(([o,a])=>{let l=s?.[o];return l===void 0&&o==="role"&&(l=n.Role),Array.isArray(a)?a.some(c=>c===l):l===a})),t.restrictions){const{recordOwner:o,recordUser:a,recordProperty:l,restrictEntities:c}=t.restrictions;i.push((o===void 0||!!r?.recordOwner?.active===o)&&(a===void 0||!!r?.recordUser?.active===a)&&(l===void 0||!!r?.recordProperty?.active===l)&&(c===void 0||!!r?.restrictEntities===c))}return i.length===0?!1:t.match==="all"?i.every(Boolean):i.some(Boolean)},ia=(t,e,n,s)=>{const r=ra(t,e);return r?Kn(r,e.labels.collection,n,s):!1},Xn=t=>!!t.auth,xe=(t,e)=>{if(e?.operations)return e.operations.includes(t)},He=(t,e,n,s)=>e?e.Role?Qn(t.access)?!n||!s?!1:ia(t,n,e,s):t.access?.includes(e.Role):!1:!0,Oi=(t,e,n,s)=>t===!0?!1:Array.isArray(t)?t.includes(e.Role):typeof t=="object"&&t!==null?!n||!s?!1:Kn(t,n,e,s):!0,oa=(t,e,n,s)=>e?e.Role?Oi(t.restrictCreate,e,n,s):!1:!0,ki=(t,e,n,s)=>e?e.Role?Oi(t.restrictUpdate,e,n,s):!1:!0,Or=(t,e,n,s)=>{const{labels:r}=t;return n.collections&&xe("Update",n.collections[r.collection])&&(!e.access||He(e,n,t,s))&&ki(e,n,r.collection,s)&&!(t.auth&&!n.collections?.[r.collection].auth&&["Enabled","Role","Name","Email","Photo_URL"].includes(e.name))},L=(t,e)=>t.filter(n=>n.name===e)[0],X=t=>["OneToOne","OneToMany","ManyToOne","ManyToMany"].includes(t.type),bi=(t,e)=>{const n={Record_Owner:"recordOwner",Record_User:"recordUser",Record_Property:"recordProperty"},s=[],{labels:r,access:i}=t,{attributeRestrictions:o}=i,a=e.collections?.[r.collection];return o?.forEach(l=>{"roles"in l&&l.roles.forEach(c=>{const d=a?.[n[l.type]];c.role===e.Role&&(!c.assignable||d?.active)&&s.push(l)})}),s},Bs=(t,e)=>{const n=[],{labels:s,access:r}=t,{entityRestrictions:i}=r,o=e.collections?.[s.collection];return i?.restrictions?.forEach(a=>{"roles"in a&&a.roles.forEach(l=>{l.role===e.Role&&(!i.assignable?.includes(e.Role)||o?.restrictEntities)&&n.push(a)})}),n},Ri=(t,e,n)=>{const s=[],{access:r}=t,{entityRestrictions:i}=r;return i?.parentFilters?.forEach(o=>{if(!o.roles.some(f=>f.role===n.Role))return;const a=o.collectionField,l=L(t.fields,a);if(!X(l))throw new Error("PERMISSION_DENIED");const c=n.collections?.[l.collection],p=e.collections[l.collection].access.entityRestrictions;if(!p)throw new Error("PERMISSION_DENIED");const u=p.restrictions?.find(f=>f.type===o.type&&f.roles.some(g=>g.role===n.Role));if(!u)throw new Error("PERMISSION_DENIED");u.roles.forEach(f=>{f.role===n.Role&&(!p.assignable?.includes(n.Role)||c?.restrictEntities)&&s.push({parentFilter:o,parentRestriction:u})})}),s},Ti=(t,e,n,s)=>{const r=Object.values(e.collections),{labels:i}=t,o=[];for(const a of r){const{fields:l}=a;for(const c of l)if(!(c.access&&!He(c,n,a,s))&&n.Role&&X(c)&&c.collection===i.collection&&c.dependencyFields)for(const d of c.dependencyFields)!o.find(u=>u.field===d.field)&&d.roles.includes(n.Role)&&o.push(d)}return o},aa=(t,e,n,s,r,i,o)=>{const{fields:a}=e,l=r.collections?.[e.labels.collection];let c=!0;if(!l){c=!1;return}const d=bi(e,r),p=Bs(e,r),u=Ri(e,n,r);d?.filter(_=>_.type==="Record_Owner").forEach(_=>{"operations"in _&&_.operations&&!_.operations.includes(t)||i.Created_By!==s&&(c=!1)}),d?.filter(_=>_.type==="Record_User").forEach(_=>{if("operations"in _&&_.operations&&!_.operations.includes(t))return;const I=L(a,_.collectionField);i[`${I.name}_Array`]?.includes(r.Doc_ID)||(c=!1)}),d?.filter(_=>_.type==="Record_Property").forEach(_=>{if("operations"in _&&_.operations&&!_.operations.includes(t))return;const I=L(a,_.propertyField),j=_.roles.find(v=>v.role===r.Role);I.type==="Array"?j.values?.some(v=>i[I.name].includes(v))||(c=!1):j.values?.includes(i[I.name])||(c=!1)});let f=!0,g=!1;p?.filter(_=>_.type==="Individual").forEach(()=>{g=!0,l?.individualEntities?.includes(i.id)||(f=!1)});let k=!0,y=!1;if(p?.filter(_=>_.type==="Parent").forEach(_=>{y=!0;const I=L(a,_.collectionField);l?.parentEntities?.some(j=>i[`${I.name}_Array`].includes(j))||(k=!1)}),p?.filter(_=>_.type==="Parent_Property").forEach(_=>{y=!0;const I=L(a,_.collectionField),j=L(a,_.propertyField);Object.entries(l?.parentPropertyEntities||{}).some(v=>{const[U,h]=v;return U===i[j.name]&&i[`${I.name}_Array`].some(x=>h.includes(x))})||(k=!1)}),g&&y){if(!(f||k)){c=!1;return}}else if(!f||!k){c=!1;return}let E=!0,w=!1;u?.filter(_=>_.parentFilter.type==="Individual").forEach(_=>{w=!0;const{parentFilter:I}=_,j=L(a,I.collectionField),v=r.collections?.[j.collection];if(!v){c=!1;return}v.individualEntities?.some(U=>i[`${j.name}_Array`].includes(U))||(E=!1)});let A=!0,O=!1;if(u?.filter(_=>_.parentFilter.type==="Parent").forEach(_=>{O=!0;const{parentFilter:I}=_,j=L(a,I.collectionField),v=L(a,I.parentCollectionField),U=r.collections?.[j.collection];if(!U){c=!1;return}U.parentEntities?.some(h=>i[`${v.name}_Array`].includes(h))||(A=!1)}),u?.filter(_=>_.parentFilter.type==="Parent_Property").forEach(_=>{O=!0;const{parentFilter:I}=_,j=L(a,I.collectionField),v=L(a,I.parentPropertyField),U=L(a,I.parentCollectionField),h=r.collections?.[j.collection];if(!h){c=!1;return}Object.entries(h.parentPropertyEntities||{}).some(x=>{const[R,q]=x;return R===i[v.name]&&i[`${U.name}_Array`].some(Z=>q.includes(Z))})||(A=!1)}),w&&O){if(!(E||A)){c=!1;return}}else if(!E||!A){c=!1;return}return c},ft=(t,e,n,s,r,i)=>{const{labels:o}=e,a=r.collections?.[o.collection];let l=!0;if(!a||!r.Role)return l=!1,l;xe(t,a)||(l=!1);const d=Bs(e,r)?.filter(p=>p.type==="Individual").length>0;return t==="Create"&&d&&(l=!1),aa(t,e,n,s,r,i)||(l=!1),l},Si=(t,e,n)=>{const{labels:s}=t,r=[];for(const i of Object.values(e.collections));return r},la=(t,e)=>{let n=!0,s="";return Object.keys(e).forEach(r=>{if(!["Doc_ID","Role","Collection","Enabled","collections"].includes(r)){n=!1,s="Permissions object must contain Doc_ID, Role, Collection, Enabled, and collections";return}}),e.collections&&(Object.keys(e.collections).forEach(r=>{if(!Object.keys(t.collections).includes(r)){s=`Collection ${r} not found in schema`,n=!1;return}const i=t.collections[r],o=e.collections?.[r];if(o){if(!o.operations){s=`Collection ${r} does not have operations`,n=!1;return}if(!Object.keys(o).every(a=>["operations","auth","restrictEntities","individualEntities","parentEntities","parentPropertyEntities","recordProperty","recordUser","recordOwner"].includes(a))){s=`Collection ${r} has invalid properties`,n=!1;return}if(!o.operations.every(a=>["Read","Create","Update","Delete"].includes(a))){s=`Collection ${r} has invalid operations`,n=!1;return}if(o.auth&&(typeof o.auth!="boolean"||!i.auth)){s=`Collection ${r} has invalid auth value`,n=!1;return}if(o.restrictEntities&&!i.access.entityRestrictions?.restrictions){s=`Collection ${r} has invalid restrictEntities value`,n=!1;return}Object.entries(o).forEach(([a,l])=>{if(a!=="operations"&&a!=="auth"&&a!=="restrictEntities"){let c;a==="recordOwner"?c="Record_Owner":a==="recordUser"?c="Record_User":a==="recordProperty"?c="Record_Property":a==="individualEntities"?c="Individual":a==="parentEntities"?c="Parent":a==="parentPropertyEntities"&&(c="Parent_Property");const d=i.access.attributeRestrictions?.filter(u=>u.type===c&&u.roles.some(f=>f.role===e.Role)),p=i.access.entityRestrictions?.restrictions?.filter(u=>u.type===c&&u.roles.some(f=>f.role===e.Role));if(i.access.entityRestrictions?.assignable&&!(Array.isArray(i.access.entityRestrictions.assignable)&&i.access.entityRestrictions.assignable.every(u=>t.config.roles.includes(u)))){s=`Collection ${r} has invalid entity restrictions assignable value`,n=!1;return}if(d?.length||p?.length){if(a==="Record_Owner"||a==="Record_User"||a==="Record_Property"){const u=Object.keys(l);if(u.length!==1||u[0]!=="active"||typeof l.active!="boolean"){s=`Collection ${r} has invalid attribute restriction value`,n=!1;return}}if(a==="Individual"&&!Array.isArray(l)){s=`Collection ${r} has invalid individual entities value`,n=!1;return}if(a==="Parent"){const u=Object.keys(l);if(!(u.length===1&&Object.keys(t.collections).includes(u[0])&&Array.isArray(l[u[0]]))){s=`Collection ${r} has invalid parent entities value`,n=!1;return}}if(a==="Parent_Property"){const u=Object.keys(l);if(!(u.length===1&&Object.keys(t.collections).includes(u[0])&&typeof l[u[0]]=="object"&&l[u[0]]!==null)){s=`Collection ${r} has invalid parent property entities value`,n=!1;return}}}else{s=`Collection ${r} has invalid restriction type ${a}`,n=!1;return}}})}}),s&&console.error(`PERMISSION_DENIED: ${s}`)),n},ca=(t,e,n)=>{let s=!0,r="";Object.values(t.collections).filter(i=>i.auth).forEach(i=>{const o=e.collections?.[i.labels.collection],a=i.access.auth,l=e.Role;if(o?.auth&&!a?.roles.includes(l)){r="Record cannot have auth access to collection",s=!1;return}if(a?.roles.includes(l)&&!a.assignable?.includes(l)&&!o?.auth){r="Record is missing required auth access to collection",s=!1;return}});for(const i of Object.values(t.collections)){const{labels:o,access:a,fields:l}=i,{operations:c,attributeRestrictions:d,entityRestrictions:p}=a,u=c.assignable,f=e.collections?.[o.collection],g=["read","create","update","delete"];if(u!==!0&&!(typeof u=="object"&&u.includes(n))?g.forEach(y=>{const E=y.charAt(0).toUpperCase()+y.slice(1);if(y!=="assignable"){const w=!!a.operations[y]?.includes(n),A=!!f?.operations.includes(E);if(!w&&A){r=`Collection ${o.collection} has excess ${y} operation for role ${n}`,s=!1;return}if(w&&!A){r=`Collection ${o.collection} has missing ${y} operation for role ${n}`,s=!1;return}}}):g.forEach(y=>{const E=y.charAt(0).toUpperCase()+y.slice(1);if(y!=="assignable"){const w=!!a.operations[y]?.includes(n),A=!!f?.operations.includes(E);if(!w&&A){r=`Collection ${o.collection} has excess ${y} operation for role ${n}`,s=!1;return}}}),!d&&!p||(d?.forEach(y=>{for(const E of y.roles)if(E.role===n&&!E.assignable){if(y.type==="Record_Owner"&&!e.collections?.[o.collection]?.recordOwner?.active){r=`Collection ${o.collection} is missing Record_Owner restriction for role ${n}`,s=!1;return}if(y.type==="Record_User"&&!e.collections?.[o.collection]?.recordUser?.active){r=`Collection ${o.collection} is missing Record_User restriction for role ${n}`,s=!1;return}if(y.type==="Record_Property"&&!e.collections?.[o.collection]?.recordProperty?.active){r=`Collection ${o.collection} is missing Record_Property restriction for role ${n}`,s=!1;return}}}),p?.assignable?.includes(n)))continue;let k=!1;if(p?.restrictions?.forEach(y=>{for(const E of y.roles)if(E.role===n){if(k=!0,y.type==="Individual"&&!e.collections?.[o.collection]?.individualEntities){r=`Collection ${o.collection} is missing individual entities`,s=!1;return}if(y.type==="Parent"){const w=L(l,y.collectionField);if(!X(w)){s=!1;return}if(!e.collections?.[o.collection]?.parentEntities){r=`Collection ${o.collection} is missing parent entities`,s=!1;return}}if(y.type==="Parent_Property"){const w=L(l,y.collectionField);if(!X(w)){s=!1;return}if(!e.collections?.[o.collection]?.parentPropertyEntities?.[w.collection]){r=`Collection ${o.collection} is missing parent property entities`,s=!1;return}}}}),k&&!e.collections?.[o.collection]?.restrictEntities){r=`Collection ${o.collection} must have restrictEntities set to true`,s=!1;return}}return r&&console.error(`PERMISSION_DENIED: ${r}`),s},ua=(t,e,n,s,r,i,o,a,l)=>{const{access:c}=e,{permissionWriteRestrictions:d}=c;let p=!0,u="";const f=d?.filter(g=>s===g.userRole);return f?.length&&!f.some(g=>g.recordRole===r)?(u=`User ${s} does not have write access to record with role ${r}`,p=!1,p):t==="update"&&o.User_ID&&f?.length&&!f.some(g=>g.recordRole===a)?(u=`User ${s} does not have write access to record with role ${r}`,p=!1,p):(d?.forEach(g=>{s===g.userRole&&g.recordRole===r&&t!=="delete"&&i&&Object.keys(n.collections).forEach(k=>{const y=i.collections?.[k],E=l?.collections?.[k];if(!(t==="update"&&Xe(y,E))&&y){const w=g.collections.some(A=>A.collection===k);if(w){if(w){const A=g.collections.find(_=>_.collection===k);if(!(y.operations.every(_=>A.operations.includes(_))||t==="update"&&Xe(y.operations,E?.operations))){u=`User ${s} does not have write access to all included operations for collection ${k}`,p=!1;return}if(!A.auth&&y.auth&&!(t==="update"&&Xe(y.auth,E?.auth))){u=`User ${s} does not have write access to auth for collection ${k}`,p=!1;return}const O={recordOwner:"Record_Owner",recordUser:"Record_User",recordProperty:"Record_Property"};if(Object.keys(O).forEach(_=>{const I=O[_];if(A.attributeRestrictions?.includes(I)&&!(y[_]?.active||t==="update"&&Xe(y[_],E?.[_]))){u=`User ${s} does not have write access to attribute restriction ${_} for collection ${k}`,p=!1;return}}),A.restrictEntities&&!y.restrictEntities&&!(t==="update"&&Xe(y.restrictEntities,E?.restrictEntities))){u=`User ${s} does not have write access to restrictEntities for collection ${k}`,p=!1;return}}}else{u=`User ${s} does not have write access to collection ${k}`,p=!1;return}}})}),u&&console.error(`PERMISSION_DENIED: ${u}`),p)},da=(t,e,n,s)=>{let r=!0,i="";return Object.values(t.collections).forEach(o=>{const a=n.collections?.[o.labels.collection],l=s?.collections?.[o.labels.collection],c=e?.collections?.[o.labels.collection];if(a?.auth&&!l?.auth&&!Xn(c)){i=`User does not have auth access to collection ${o.labels.collection}`,r=!1;return}for(const d of a?.operations||[])if(!l?.operations.includes(d)&&(!xe("Read",c)||!xe(d,c))){i=`User does not have ${d.toLowerCase()} access to collection ${o.labels.collection}`,r=!1;return}if(!a?.recordOwner&&l?.recordOwner&&c?.recordOwner){i=`User does not have write access to recordOwner for collection ${o.labels.collection}`,r=!1;return}if(!a?.recordUser&&l?.recordUser&&c?.recordUser){i=`User does not have write access to recordUser for collection ${o.labels.collection}`,r=!1;return}if(!a?.recordProperty&&l?.recordProperty&&c?.recordProperty){i=`User does not have write access to recordProperty for collection ${o.labels.collection}`,r=!1;return}if(!a?.restrictEntities&&l?.restrictEntities&&c?.restrictEntities){i=`User does not have write access to restrictEntities for collection ${o.labels.collection}`,r=!1;return}}),i&&console.error(`PERMISSION_DENIED: ${i}`),r},Hs=(t,e,n,s,r,i,o,a,l,c,d)=>{const{labels:p}=s;let u=!0,f="";if(!e.Role)return f="Record does not have a role",u=!1,u;if(t==="update"&&!c)return f="Original record is required for update operations",u=!1,u;if(t==="update"&&i&&d==="update"&&a&&!l)return f="Original permissions are required for this operation",u=!1,u;if(i){if(!o?.Role)return f="Current user does not have a role",u=!1,u;if(!ua(t,s,r,o.Role,e.Role,a,c,c?.Role,l))return u=!1,u;if(t==="update"&&d!=="delete"&&c?.User_ID&&e.User_ID!==c.User_ID)return f="User ID does not match original user ID",u=!1,u;if(t==="update"&&c&&c.User_ID&&i===c.User_ID&&(a||e.Role!==c.Role||e.Enabled!==void 0&&e.Enabled!==c.Enabled))return f="User cannot update their own record",u=!1,u;if(t==="delete"&&i===e.User_ID)return f="User cannot delete their own record",u=!1,u}return t==="delete"||d==="delete"||!a?u:a.Role?(la(r,a)||(u=!1),a.Collection&&a.Collection!==p.collection?(f="Permissions collection does not match record collection",u=!1,u):a.Role!==e.Role?(f="Permissions role does not match record role",u=!1,u):a.Enabled!==void 0&&!!a.Enabled!=!!e.Enabled?(f="Permissions enabled state does not match record enabled state",u=!1,u):a.Doc_ID&&a.Doc_ID!==n?(f="Permissions doc ID does not match record doc ID",u=!1,u):!ca(r,a,a.Role)||i&&o&&l&&!da(r,o,a,l)?(u=!1,u):(f&&console.error(`PERMISSION_DENIED: ${f}`),u)):(f="Permissions do not have a role",u=!1,u)},kr=(t,e,n,s,r,i,o,a)=>{const{labels:l,fields:c}=n,d=i?.collections?.[l.collection];let p=!0;if(r&&!d)throw new Error("PERMISSION_DENIED");r&&!xe("Create",d)&&(p=!1),r&&!ft("Create",n,s,r,i,t)&&(p=!1),n.auth&&o&&(r&&!Xn(d)&&(p=!1),Hs("create",t,e,n,s,r,i,o)||(p=!1));for(const u of c){const f=t[u.name];u.access&&!He(u,i,n,a)&&f!==void 0&&(p=!1),f!==void 0&&!oa(u,i,l.collection,a)&&(p=!1)}if(!p)throw new Error("PERMISSION_DENIED")},be=t=>t&&(t._methodName==="deleteField"||t.constructor.name==="DeleteTransform"),et=t=>{for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(be(t[e])?delete t[e]:typeof t[e]=="object"&&t[e]!==null&&et(t[e]))},br=(t,e,n,s,r,i,o,a,l,c,d)=>{const{labels:p,fields:u}=s,f=o?.collections?.[p.collection],g={...e,...t};et(g);let k=!0,y="";if(i&&!f)throw new Error("PERMISSION_DENIED");i&&!xe("Update",f)&&(k=!1,y="Authenticated user does not have Update access to this collection"),i&&(!ft("Update",s,r,i,o,e)||!ft("Update",s,r,i,o,g))&&(k=!1,y="Authenticated user does not have Update access to this document"),i&&s.softDelete&&g[s.softDelete.archivedField]!==e[s.softDelete.archivedField]&&!xe("Delete",f)&&(k=!1,y="Authenticated user does not have Delete or Restore access to this document"),a&&(i&&!Xn(f)&&(k=!1,y="Authenticated user does not have Auth access for this collection"),Hs("update",g,n,s,r,i,o,l,c,e,a)||(y="Authenticated user does not have sufficient write access for this record",k=!1));for(const E of u){const w=t[E.name];E.access&&!He(E,o,s,d)&&w!==void 0&&(y=`Authenticated user does not have access to field ${E.name}`,k=!1),w!==void 0&&!ki(E,o,p.collection,d)&&(y=`Authenticated user does not have Update access to field ${E.name}`,k=!1)}if(!k)throw y&&console.error(`PERMISSION_DENIED: ${y}`),new Error("PERMISSION_DENIED")},fa=(t,e,n,s,r,i)=>{const{labels:o}=n,a=i.collections?.[o.collection];let l=!0;if(!a)throw new Error("PERMISSION_DENIED");if(xe("Delete",a)||(l=!1),ft("Delete",n,s,r,i,t)||(l=!1),n.auth&&t.User_ID&&(Xn(a)||(l=!1),Hs("delete",t,e,n,s,r,i)||(l=!1)),!l)throw new Error("PERMISSION_DENIED")},ha=async(t,e,n,s,r)=>{const{labels:i}=e,o=r.collections?.[i.collection];let a=!0;if(!o){a=!1;return}if(xe("Read",o)||(a=!1),ft("Read",e,n,s,r,t)||(a=!1),!a)throw new Error("PERMISSION_DENIED")},ma=async(t,e,n,s,r)=>{const{labels:i}=e,o=r.collections?.[i.collection];let a=!0;if(!o){a=!1;return}if(xe("Read",o)||(a=!1),t.forEach(l=>{ft("Read",e,n,s,r,l)||(a=!1)}),!a)throw new Error("PERMISSION_DENIED")},pa=(t,e,n)=>{const{access:s}=t;return s.operations[n]?.includes(e)},ya=(t,e,n)=>{const{access:s}=e,{entityRestrictions:r}=s;if(r?.restrictions){for(const i of r.restrictions)if(i.roles?.some(o=>o.role===t)&&!("singleQuery"in i&&i.singleQuery))return`${i.type} entity restriction`}if(r?.parentFilters)for(const i of r.parentFilters){if(!i.roles.some(c=>c.role===t))continue;const o=L(e.fields,i.collectionField);if(!X(o))throw new Error("PERMISSION_DENIED");const l=n.collections[o.collection].access.entityRestrictions?.restrictions?.find(c=>c.type===i.type&&c.roles.some(d=>d.role===t));if(!l)throw new Error("PERMISSION_DENIED");if(l.type!==i.type)throw new Error("PERMISSION_DENIED");if(!("singleQuery"in l&&l.singleQuery))return`${i.type} parent filter`}return!0},ga=(t,e,n,s,r)=>{const i={};for(const o of t){const l=e[o].default({sdk:n,utils:s,context:r});for(const c in l)c==="custom"||c==="admin"||c==="fields"||delete l[c];for(const c of l.fields)for(const d in c)d==="custom"||d==="admin"||d==="name"||d==="formula"||delete c[d];i[o]=l}return i},We=(t,e)=>e.fields.filter(n=>n.name===t.name)[0],os={global:{},collections:{}},Kt=(t,e)=>t&&typeof t=="function"?e?t(...e):t():t,ae=async(t,e)=>{let n=t;return t&&(typeof t=="function"||typeof t.then=="function")&&(e?n=await t(...e):n=await t()),n},wa=async(t,e,n,s)=>{for(const d of e)if(d==="__proto__"||d==="constructor"||d==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");let r=os,i=!0;for(const d of e){if(d===void 0||r[d]===void 0){i=!1;break}r=r[d]}if(r&&i&&!s)return r;let o,a=t,l=!0;e[0]==="collections"?o=e.slice(2):o=e.slice(1);for(const d of o){if(d===void 0||a[d]===void 0){l=!1;break}a=a[d]}let c;if(l&&(c=await ae(a,n)),c){let d=os;const p={};for(let u=0;u<e.length;u++){const f=e[u];if(f!==void 0){if(f==="__proto__"||f==="constructor"||f==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");u===e.length-1?na(p,e.join("."),c):(d[f]||={},d=d[f])}}ta(os,p)}return c},mt=(t,e,n)=>{const s=Object.values(n.collections),{labels:r}=e;let i=!1;for(const o of s){const{fields:a}=o;for(const l of a)if(X(l)&&l.collection===r.collection&&l.dependencyFields)for(const c of l.dependencyFields)c.field===t.name&&(i=!0)}return i},Ii=(t,e)=>{const n=Object.values(e.collections),{labels:s}=t,r={};return n.forEach(i=>{const{labels:o,fields:a}=i;a.forEach(l=>{X(l)&&l.collection===s.collection&&l.dependencyFields&&l.dependencyFields.forEach(c=>{r[c.field]||={},r[c.field][o.collection]||=[],r[c.field][o.collection]=r[c.field][o.collection].concat(c.roles),r[c.field][o.collection]=[...new Set(r[c.field][o.collection])]})})}),r},as=t=>JSON.stringify(t.map(e=>e.name)),ct=["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"],mn=()=>ct.map(t=>{let e="",n;switch(t){case"id":e="String";break;case"Collection_Path":e="Array";break;case"Created_At":e="Timestamp";break;case"Saved_At":e="Timestamp";break;case"Created_By":e="String";break;case"Last_Write_At":e="Timestamp";break;case"Last_Save_At":e="Timestamp";break;case"Last_Write_By":e="String";break;case"Last_Write_App":e="String";break;case"Last_Write_Connection_Status":e="String",n=["Online","Offline"];break;case"Last_Write_Version":e="Number";break}const s={name:t,type:e,required:!0};return n&&(s.values=n),s}),Gs=(t,e)=>{const n=[],{access:s,fields:r}=t,{attributeRestrictions:i,entityRestrictions:o}=s,a=mn();return i&&i.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Record_Owner":n.push(L(a,"Created_By"));break;case"Record_User":n.push(L(r,l.collectionField));break;case"Record_Property":n.push(L(r,l.propertyField));break}}),o&&(o.restrictions?.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Individual":n.push(L(a,"id"));break;case"Parent":n.push(L(r,l.collectionField));break;case"Parent_Property":n.push(L(r,l.collectionField)),n.push(L(r,l.propertyField));break}}),o.parentFilters&&o.parentFilters.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Individual":n.push(L(r,l.collectionField));break;case"Parent":n.push(L(r,l.parentCollectionField));break;case"Parent_Property":n.push(L(r,l.parentCollectionField)),n.push(L(r,l.parentPropertyField));break}})),[...new Set(n)]},_a=(t,e)=>{const n=[],{fields:s,roleSystemFields:r,preloadCache:i,queries:o}=t,a=mn();return n.push({name:"Collection_Path",type:"Array",required:!0}),s.forEach(c=>{cn(c,e)&&n.push(c)}),r?.filter(c=>(!c.roles||c.roles.includes(e))&&c.field!=="Collection_Path").forEach(c=>{n.push(L(a,c.field))}),i?.range&&i.range.fields.forEach(c=>{ct.includes(c)&&n.push(L(a,c))}),o?.forEach(c=>{const d=L(s.concat(a),c.field);(!c.roles||c.roles.includes(e))&&d&&cn(d,e)&&ct.includes(c.field)&&n.push(L(a,c.field))}),Gs(t,e).forEach(c=>{ct.includes(c.name)&&n.push(L(a,c.name))}),[...new Set(n)]},Ea=(t,e,n)=>{const s=[],{fields:r,preloadCache:i}=e,o=mn(),a=new Set,l=Ii(e,n);return Object.entries(l).map(([c,d])=>{t.name===c&&Object.values(d).forEach(p=>{p.forEach(u=>{a.add(u)})})}),a.forEach(c=>{s.push(...Gs(e,c))}),i?.range&&i.range.fields.forEach(c=>{ct.includes(c)?s.push(L(o,c)):Array.from(a).some(d=>cn(L(r,c),d))&&s.push(L(r,c))}),[...new Set(s)]},En=(t,e,n)=>{const s=[],{fields:r,softDelete:i}=e;s.push({name:"Collection_Path",type:"Array",required:!0}),s.push({name:"id",type:"String",required:!0});const o=[],a=Ii(e,n);if(Object.values(a).forEach(l=>{Object.keys(l).forEach(c=>{n.collections[c].fields.forEach(p=>{X(p)&&p.collection===e.labels.collection&&p.dependencyFields?.some(u=>u.field===t.name)&&p.constraints&&p.constraints.forEach(u=>{o.push(u[0])})})})}),o.forEach(l=>{s.push(L(r,l))}),i){const l=L(r,i.archivedField);l&&s.push(l)}return s.push(...Ea(t,e,n)),[...new Set(s)]},va=(t,e,n)=>{const s=e.fieldAccessGroups?.[t]?.applicableRoles||[];return n.roles.filter(r=>s.includes(r))},on=(t,e)=>`${t}-${e}`,vn=(t,e,n)=>{if(!e.fieldAccessGroups?.[t])return[];const s=va(t,e,n);if(s.length===0)return[];const r=[],{fields:i,softDelete:o,preloadCache:a,roleSystemFields:l,queries:c}=e,d=mn();r.push({name:"Collection_Path",type:"Array",required:!0}),r.push({name:"id",type:"String",required:!0});const p=qs(e)[t]||[];if(r.push(...p),o){const u=L(i,o.archivedField);u&&!p.includes(u)&&r.push(u)}a?.range&&a.range.fields.forEach(u=>{ct.includes(u)?r.push(L(d,u)):s.some(f=>cn(L(i,u),f))&&r.push(L(i,u))}),l?.filter(u=>u.field!=="Collection_Path"&&s.some(f=>!u.roles||u.roles.includes(f))).forEach(u=>{r.push(L(d,u.field))}),c?.forEach(u=>{const f=L(i.concat(d),u.field);f&&s.some(g=>(!u.roles||u.roles.includes(g))&&cn(f,g))&&r.push(f)});for(const u of s)r.push(...Gs(e,u));return[...new Set(r)]},xi=(t,e)=>{const{preloadCache:n}=t,s=new Set;for(const r of e.config.roles){if(!pa(t,r,"read"))continue;const i=_a(t,r);let o=!1;if(s.size===0)s.add({key:"1",roles:[r],fields:i}),o=!0;else for(const a of s)i.length===a.fields.length&&i.every(l=>a.fields.some(c=>c.name===l.name))&&!!n?.roles.includes(r)==!!a.roles.every(l=>n?.roles.includes(l))&&(a.roles.push(r),o=!0);o||s.add({key:(s.size+1).toString(),roles:[r],fields:i})}return s},Ai=(t,e,n)=>{const s=xi(e,n);for(const r of s.values())if(r.roles.includes(t))return r},Oa=(t,e)=>{const{fields:n}=e,s=mn(),r=[];return[...n,...s.filter(o=>o.name!=="id")].forEach(o=>{t?.fields.some(a=>a.name===o.name)||r.push(o)}),r},Ys=(t,e,n)=>{const s={};return Object.values(t.collections).forEach(r=>{const i=xi(r,t),o=Array.from(i);o.map(a=>(a.fields.forEach(l=>{}),a)),s[r.labels.collection]=new Set(o)}),s},$n=t=>({Last_Write_At:t.Last_Write_At,Last_Write_By:t.Last_Write_By,Last_Write_Connection_Status:t.Last_Write_Connection_Status,Last_Write_Version:t.Last_Write_Version,Last_Write_App:t.Last_Write_App,Last_Save_At:t.Last_Save_At}),ls=async(t,e,n)=>{if(e){const s=await ae(e,[n]);if(s===!1)throw new Error(`CANCELLED: Operation cancelled by ${t}`);return s}};async function ce(t,e,n,s){const r=await ls(t,n.custom?.[t],s);for(const i of n.fields)await ls(t,i.custom?.[t],s);if(t!=="setEmbedding"&&(await ls(t,e?.[t],s),t==="postWriteError"))return r}const Js=(t,e,n,s,r,i,o,a,l,c)=>(t==="create"&&(n.Collection_Path=e,n.Created_At=a,n.Saved_At=l,n.Created_By=o||"System"),n.Last_Write_App=r,n.Last_Write_At=a,n.Last_Save_At=l,n.Last_Write_By=o||"System",n.Last_Write_Connection_Status=i,n.Last_Write_Version=s.version,n),gt=(t,e)=>{const{access:n,queries:s}=t,{serverReadOnly:r}=n,i=new Set;if(s)for(const o of s){const a=L(e,o.field);e.find(l=>l.name===o.field)&&X(a)&&["OneToOne","OneToMany"].includes(a.type)&&i.add(a)}return e.forEach(o=>{X(o)&&["OneToOne","OneToMany"].includes(o.type)&&o.sorting&&(typeof o.sorting=="boolean"||!o.sorting.roles?.every(a=>r?.includes(a)))&&i.add(o)}),i},Rt=(t,e)=>{const{access:n,recordTitleField:s}=t,{serverReadOnly:r}=n,i=new Set;return e.forEach(o=>{(s===o.name||o.sorting&&(typeof o.sorting=="boolean"||!o.sorting.roles?.every(a=>r?.includes(a))))&&o.type==="String"&&i.add(o)}),i},ka=(t,e)=>{const n={Collection_Path:t.Collection_Path};if(t.deleted!==void 0&&(n.deleted=t.deleted),e)for(const s of e)t[s]!==void 0&&(n[s]=t[s]);return n},wt=(t,e,n)=>{const{fields:s}=t;s.forEach(i=>{if(X(i))if(e[i.name]){if(be(e[i.name]))e[`${i.name}_Array`]=e[i.name];else if(Object.keys(e[i.name]).forEach(o=>{const a=e[i.name][o];e[i.name][o]=ka(a,i.includeFields)}),e[`${i.name}_Array`]=Object.keys(e[i.name]),i.includeFields)for(const o of i.includeFields){const a=n.collections[i.collection],l=L(a.fields,o);Rt(a,[l]).size===1&&Object.keys(e[i.name]).forEach(d=>{e[i.name][d][o]?e[i.name][d][`${o}_Lowercase`]=e[i.name][d][o].toLowerCase():delete e[i.name][d][`${o}_Lowercase`]})}}else delete e[`${i.name}_Array`],delete e[`${i.name}_Single`]}),gt(t,s).forEach(i=>{if(e[i.name])if(be(e[i.name]))e[`${i.name}_Single`]=e[i.name];else{const o=e[`${i.name}_Array`]?.[0];if(o){const a=e[i.name][o]||{};e[`${i.name}_Single`]={id:o,...a}}}})},Mn=(t,e)=>{Rt(t,t.fields).forEach(s=>{e[s.name]?e[`${s.name}_Lowercase`]=e[s.name].toLowerCase():delete e[`${s.name}_Lowercase`]})},ba=async(t,e,n,s,r)=>{const{fields:i}=e;for(const o of n.fields){const a=L(i,o.name);o.custom?.initialValue!==void 0&&(!a.access||He(a,s,e,r||{}))&&(t[o.name]=await ae(o.custom.initialValue,[t]),Rt(e,[a]).size===1&&(t[`${o.name}_Lowercase`]=t[o.name].toLowerCase()))}for(const o of i)(!o.access||He(o,s,e,r||{}))&&("autoIncrement"in o&&o.autoIncrement&&!t[o.name]&&(t[o.name]="Pending"),!X(o)&&o.nullable&&t[o.name]===void 0&&(t[o.name]=null))};var se;(function(t){t.assertEqual=r=>{};function e(r){}t.assertIs=e;function n(r){throw new Error}t.assertNever=n,t.arrayToEnum=r=>{const i={};for(const o of r)i[o]=o;return i},t.getValidEnumValues=r=>{const i=t.objectKeys(r).filter(a=>typeof r[r[a]]!="number"),o={};for(const a of i)o[a]=r[a];return t.objectValues(o)},t.objectValues=r=>t.objectKeys(r).map(function(i){return r[i]}),t.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const i=[];for(const o in r)Object.prototype.hasOwnProperty.call(r,o)&&i.push(o);return i},t.find=(r,i)=>{for(const o of r)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function s(r,i=" | "){return r.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=s,t.jsonStringifyReplacer=(r,i)=>typeof i=="bigint"?i.toString():i})(se||(se={}));var Rr;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Rr||(Rr={}));const W=se.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ot=t=>{switch(typeof t){case"undefined":return W.undefined;case"string":return W.string;case"number":return Number.isNaN(t)?W.nan:W.number;case"boolean":return W.boolean;case"function":return W.function;case"bigint":return W.bigint;case"symbol":return W.symbol;case"object":return Array.isArray(t)?W.array:t===null?W.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?W.promise:typeof Map<"u"&&t instanceof Map?W.map:typeof Set<"u"&&t instanceof Set?W.set:typeof Date<"u"&&t instanceof Date?W.date:W.object;default:return W.unknown}},N=se.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"]);class nt extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){const n=e||function(i){return i.message},s={_errors:[]},r=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(r);else if(o.code==="invalid_return_type")r(o.returnTypeError);else if(o.code==="invalid_arguments")r(o.argumentsError);else if(o.path.length===0)s._errors.push(n(o));else{let a=s,l=0;for(;l<o.path.length;){const c=o.path[l];l===o.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(o))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return r(this),s}static assert(e){if(!(e instanceof nt))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,se.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},s=[];for(const r of this.issues)if(r.path.length>0){const i=r.path[0];n[i]=n[i]||[],n[i].push(e(r))}else s.push(e(r));return{formErrors:s,fieldErrors:n}}get formErrors(){return this.flatten()}}nt.create=t=>new nt(t);const Rs=(t,e)=>{let n;switch(t.code){case N.invalid_type:t.received===W.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case N.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,se.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:n=`Unrecognized key(s) in object: ${se.joinValues(t.keys,", ")}`;break;case N.invalid_union:n="Invalid input";break;case N.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${se.joinValues(t.options)}`;break;case N.invalid_enum_value:n=`Invalid enum value. Expected ${se.joinValues(t.options)}, received '${t.received}'`;break;case N.invalid_arguments:n="Invalid function arguments";break;case N.invalid_return_type:n="Invalid function return type";break;case N.invalid_date:n="Invalid date";break;case N.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:se.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case N.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case N.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case N.custom:n="Invalid input";break;case N.invalid_intersection_types:n="Intersection results could not be merged";break;case N.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case N.not_finite:n="Number must be finite";break;default:n=e.defaultError,se.assertNever(t)}return{message:n}};let Ra=Rs;function Ta(){return Ra}const Sa=t=>{const{data:e,path:n,errorMaps:s,issueData:r}=t,i=[...n,...r.path||[]],o={...r,path:i};if(r.message!==void 0)return{...r,path:i,message:r.message};let a="";const l=s.filter(c=>!!c).slice().reverse();for(const c of l)a=c(o,{data:e,defaultError:a}).message;return{...r,path:i,message:a}};function P(t,e){const n=Ta(),s=Sa({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Rs?void 0:Rs].filter(r=>!!r)});t.common.issues.push(s)}class Se{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const s=[];for(const r of n){if(r.status==="aborted")return J;r.status==="dirty"&&e.dirty(),s.push(r.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,n){const s=[];for(const r of n){const i=await r.key,o=await r.value;s.push({key:i,value:o})}return Se.mergeObjectSync(e,s)}static mergeObjectSync(e,n){const s={};for(const r of n){const{key:i,value:o}=r;if(i.status==="aborted"||o.status==="aborted")return J;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||r.alwaysSet)&&(s[i.value]=o.value)}return{status:e.value,value:s}}}const J=Object.freeze({status:"aborted"}),Xt=t=>({status:"dirty",value:t}),Pe=t=>({status:"valid",value:t}),Tr=t=>t.status==="aborted",Sr=t=>t.status==="dirty",Pt=t=>t.status==="valid",Pn=t=>typeof Promise<"u"&&t instanceof Promise;var z;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(z||(z={}));class Ge{constructor(e,n,s,r){this._cachedPath=[],this.parent=e,this.data=n,this._path=s,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}}const Ir=(t,e)=>{if(Pt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new nt(t.common.issues);return this._error=n,this._error}}};function K(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:s,description:r}=t;if(e&&(n||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(o,a)=>{const{message:l}=t;return o.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??s??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:r}}class te{get description(){return this._def.description}_getType(e){return ot(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:ot(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Se,ctx:{common:e.parent.common,data:e.data,parsedType:ot(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(Pn(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const s=this.safeParse(e,n);if(s.success)return s.data;throw s.error}safeParse(e,n){const s={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ot(e)},r=this._parseSync({data:e,path:s.path,parent:s});return Ir(s,r)}"~validate"(e){const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ot(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:n});return Pt(s)?{value:s.value}:{issues:n.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(s=>Pt(s)?{value:s.value}:{issues:n.common.issues})}async parseAsync(e,n){const s=await this.safeParseAsync(e,n);if(s.success)return s.data;throw s.error}async safeParseAsync(e,n){const s={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ot(e)},r=this._parse({data:e,path:s.path,parent:s}),i=await(Pn(r)?r:Promise.resolve(r));return Ir(s,i)}refine(e,n){const s=r=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(r):n;return this._refinement((r,i)=>{const o=e(r),a=()=>i.addIssue({code:N.custom,...s(r)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,n){return this._refinement((s,r)=>e(s)?!0:(r.addIssue(typeof n=="function"?n(s,r):n),!1))}_refinement(e){return new Ut({schema:this,typeName:Y.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:n=>this["~validate"](n)}}optional(){return ut.create(this,this._def)}nullable(){return Wt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ze.create(this)}promise(){return jn.create(this,this._def)}or(e){return Vn.create([this,e],this._def)}and(e){return Un.create(this,e,this._def)}transform(e){return new Ut({...K(this._def),schema:this,typeName:Y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new Ns({...K(this._def),innerType:this,defaultValue:n,typeName:Y.ZodDefault})}brand(){return new Ja({typeName:Y.ZodBranded,type:this,...K(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new Ds({...K(this._def),innerType:this,catchValue:n,typeName:Y.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Qs.create(this,e)}readonly(){return Cs.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Ia=/^c[^\s-]{8,}$/i,xa=/^[0-9a-z]+$/,Aa=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Na=/^[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,Da=/^[a-z0-9_-]{21}$/i,Ca=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Fa=/^[-+]?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)?)??$/,$a=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ma="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let cs;const Pa=/^(?:(?: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])$/,La=/^(?:(?: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])$/,Va=/^(([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]))$/,Ua=/^(([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])$/,Wa=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ja=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ni="((\\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])))",Za=new RegExp(`^${Ni}$`);function Di(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function za(t){return new RegExp(`^${Di(t)}$`)}function qa(t){let e=`${Ni}T${Di(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function Ba(t,e){return!!((e==="v4"||!e)&&Pa.test(t)||(e==="v6"||!e)&&Va.test(t))}function Ha(t,e){if(!Ca.test(t))return!1;try{const[n]=t.split(".");if(!n)return!1;const s=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),r=JSON.parse(atob(s));return!(typeof r!="object"||r===null||"typ"in r&&r?.typ!=="JWT"||!r.alg||e&&r.alg!==e)}catch{return!1}}function Ga(t,e){return!!((e==="v4"||!e)&&La.test(t)||(e==="v6"||!e)&&Ua.test(t))}class tt extends te{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==W.string){const i=this._getOrReturnCtx(e);return P(i,{code:N.invalid_type,expected:W.string,received:i.parsedType}),J}const s=new Se;let r;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(r=this._getOrReturnCtx(e,r),P(r,{code:N.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="max")e.data.length>i.value&&(r=this._getOrReturnCtx(e,r),P(r,{code:N.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="length"){const o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(r=this._getOrReturnCtx(e,r),o?P(r,{code:N.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&P(r,{code:N.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),s.dirty())}else if(i.kind==="email")$a.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"email",code:N.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")cs||(cs=new RegExp(Ma,"u")),cs.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"emoji",code:N.invalid_string,message:i.message}),s.dirty());else if(i.kind==="uuid")Na.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"uuid",code:N.invalid_string,message:i.message}),s.dirty());else if(i.kind==="nanoid")Da.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"nanoid",code:N.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid")Ia.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"cuid",code:N.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid2")xa.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"cuid2",code:N.invalid_string,message:i.message}),s.dirty());else if(i.kind==="ulid")Aa.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"ulid",code:N.invalid_string,message:i.message}),s.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),P(r,{validation:"url",code:N.invalid_string,message:i.message}),s.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"regex",code:N.invalid_string,message:i.message}),s.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(r=this._getOrReturnCtx(e,r),P(r,{code:N.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),s.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(r=this._getOrReturnCtx(e,r),P(r,{code:N.invalid_string,validation:{startsWith:i.value},message:i.message}),s.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(r=this._getOrReturnCtx(e,r),P(r,{code:N.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()):i.kind==="datetime"?qa(i).test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:N.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?Za.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:N.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?za(i).test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:N.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?Fa.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"duration",code:N.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?Ba(e.data,i.version)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"ip",code:N.invalid_string,message:i.message}),s.dirty()):i.kind==="jwt"?Ha(e.data,i.alg)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"jwt",code:N.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?Ga(e.data,i.version)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"cidr",code:N.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?Wa.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"base64",code:N.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?ja.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"base64url",code:N.invalid_string,message:i.message}),s.dirty()):se.assertNever(i);return{status:s.value,value:e.data}}_regex(e,n,s){return this.refinement(r=>e.test(r),{validation:n,code:N.invalid_string,...z.errToObj(s)})}_addCheck(e){return new tt({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...z.errToObj(e)})}url(e){return this._addCheck({kind:"url",...z.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...z.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...z.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...z.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...z.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...z.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...z.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...z.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...z.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...z.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...z.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...z.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:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...z.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:typeof e?.precision>"u"?null:e?.precision,...z.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...z.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...z.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...z.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...z.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...z.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...z.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...z.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...z.errToObj(n)})}nonempty(e){return this.min(1,z.errToObj(e))}trim(){return new tt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new tt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new tt({...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(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}tt.create=t=>new tt({checks:[],typeName:Y.ZodString,coerce:t?.coerce??!1,...K(t)});function Ya(t,e){const n=(t.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,r=n>s?n:s,i=Number.parseInt(t.toFixed(r).replace(".","")),o=Number.parseInt(e.toFixed(r).replace(".",""));return i%o/10**r}class Lt extends te{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)!==W.number){const i=this._getOrReturnCtx(e);return P(i,{code:N.invalid_type,expected:W.number,received:i.parsedType}),J}let s;const r=new Se;for(const i of this._def.checks)i.kind==="int"?se.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{code:N.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),P(s,{code:N.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),P(s,{code:N.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="multipleOf"?Ya(e.data,i.value)!==0&&(s=this._getOrReturnCtx(e,s),P(s,{code:N.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{code:N.not_finite,message:i.message}),r.dirty()):se.assertNever(i);return{status:r.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,z.toString(n))}gt(e,n){return this.setLimit("min",e,!1,z.toString(n))}lte(e,n){return this.setLimit("max",e,!0,z.toString(n))}lt(e,n){return this.setLimit("max",e,!1,z.toString(n))}setLimit(e,n,s,r){return new Lt({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:s,message:z.toString(r)}]})}_addCheck(e){return new Lt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:z.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:z.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:z.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:z.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:z.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&se.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(n===null||s.value>n)&&(n=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(n)&&Number.isFinite(e)}}Lt.create=t=>new Lt({checks:[],typeName:Y.ZodNumber,coerce:t?.coerce||!1,...K(t)});class un extends te{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)!==W.bigint)return this._getInvalidInput(e);let s;const r=new Se;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),P(s,{code:N.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),P(s,{code:N.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),P(s,{code:N.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):se.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return P(n,{code:N.invalid_type,expected:W.bigint,received:n.parsedType}),J}gte(e,n){return this.setLimit("min",e,!0,z.toString(n))}gt(e,n){return this.setLimit("min",e,!1,z.toString(n))}lte(e,n){return this.setLimit("max",e,!0,z.toString(n))}lt(e,n){return this.setLimit("max",e,!1,z.toString(n))}setLimit(e,n,s,r){return new un({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:s,message:z.toString(r)}]})}_addCheck(e){return new un({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:z.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}un.create=t=>new un({checks:[],typeName:Y.ZodBigInt,coerce:t?.coerce??!1,...K(t)});class Ts extends te{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==W.boolean){const s=this._getOrReturnCtx(e);return P(s,{code:N.invalid_type,expected:W.boolean,received:s.parsedType}),J}return Pe(e.data)}}Ts.create=t=>new Ts({typeName:Y.ZodBoolean,coerce:t?.coerce||!1,...K(t)});class Ln extends te{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==W.date){const i=this._getOrReturnCtx(e);return P(i,{code:N.invalid_type,expected:W.date,received:i.parsedType}),J}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return P(i,{code:N.invalid_date}),J}const s=new Se;let r;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(r=this._getOrReturnCtx(e,r),P(r,{code:N.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),s.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(r=this._getOrReturnCtx(e,r),P(r,{code:N.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),s.dirty()):se.assertNever(i);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Ln({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:z.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:z.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}}Ln.create=t=>new Ln({checks:[],coerce:t?.coerce||!1,typeName:Y.ZodDate,...K(t)});class xr extends te{_parse(e){if(this._getType(e)!==W.symbol){const s=this._getOrReturnCtx(e);return P(s,{code:N.invalid_type,expected:W.symbol,received:s.parsedType}),J}return Pe(e.data)}}xr.create=t=>new xr({typeName:Y.ZodSymbol,...K(t)});class Ss extends te{_parse(e){if(this._getType(e)!==W.undefined){const s=this._getOrReturnCtx(e);return P(s,{code:N.invalid_type,expected:W.undefined,received:s.parsedType}),J}return Pe(e.data)}}Ss.create=t=>new Ss({typeName:Y.ZodUndefined,...K(t)});class Ar extends te{_parse(e){if(this._getType(e)!==W.null){const s=this._getOrReturnCtx(e);return P(s,{code:N.invalid_type,expected:W.null,received:s.parsedType}),J}return Pe(e.data)}}Ar.create=t=>new Ar({typeName:Y.ZodNull,...K(t)});class Is extends te{constructor(){super(...arguments),this._any=!0}_parse(e){return Pe(e.data)}}Is.create=t=>new Is({typeName:Y.ZodAny,...K(t)});class Nr extends te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Pe(e.data)}}Nr.create=t=>new Nr({typeName:Y.ZodUnknown,...K(t)});class ht extends te{_parse(e){const n=this._getOrReturnCtx(e);return P(n,{code:N.invalid_type,expected:W.never,received:n.parsedType}),J}}ht.create=t=>new ht({typeName:Y.ZodNever,...K(t)});class Dr extends te{_parse(e){if(this._getType(e)!==W.undefined){const s=this._getOrReturnCtx(e);return P(s,{code:N.invalid_type,expected:W.void,received:s.parsedType}),J}return Pe(e.data)}}Dr.create=t=>new Dr({typeName:Y.ZodVoid,...K(t)});class ze extends te{_parse(e){const{ctx:n,status:s}=this._processInputParams(e),r=this._def;if(n.parsedType!==W.array)return P(n,{code:N.invalid_type,expected:W.array,received:n.parsedType}),J;if(r.exactLength!==null){const o=n.data.length>r.exactLength.value,a=n.data.length<r.exactLength.value;(o||a)&&(P(n,{code:o?N.too_big:N.too_small,minimum:a?r.exactLength.value:void 0,maximum:o?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),s.dirty())}if(r.minLength!==null&&n.data.length<r.minLength.value&&(P(n,{code:N.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()),r.maxLength!==null&&n.data.length>r.maxLength.value&&(P(n,{code:N.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()),n.common.async)return Promise.all([...n.data].map((o,a)=>r.type._parseAsync(new Ge(n,o,n.path,a)))).then(o=>Se.mergeArray(s,o));const i=[...n.data].map((o,a)=>r.type._parseSync(new Ge(n,o,n.path,a)));return Se.mergeArray(s,i)}get element(){return this._def.type}min(e,n){return new ze({...this._def,minLength:{value:e,message:z.toString(n)}})}max(e,n){return new ze({...this._def,maxLength:{value:e,message:z.toString(n)}})}length(e,n){return new ze({...this._def,exactLength:{value:e,message:z.toString(n)}})}nonempty(e){return this.min(1,e)}}ze.create=(t,e)=>new ze({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Y.ZodArray,...K(e)});function Dt(t){if(t instanceof he){const e={};for(const n in t.shape){const s=t.shape[n];e[n]=ut.create(Dt(s))}return new he({...t._def,shape:()=>e})}else return t instanceof ze?new ze({...t._def,type:Dt(t.element)}):t instanceof ut?ut.create(Dt(t.unwrap())):t instanceof Wt?Wt.create(Dt(t.unwrap())):t instanceof Ot?Ot.create(t.items.map(e=>Dt(e))):t}class he extends te{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=se.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==W.object){const c=this._getOrReturnCtx(e);return P(c,{code:N.invalid_type,expected:W.object,received:c.parsedType}),J}const{status:s,ctx:r}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof ht&&this._def.unknownKeys==="strip"))for(const c in r.data)o.includes(c)||a.push(c);const l=[];for(const c of o){const d=i[c],p=r.data[c];l.push({key:{status:"valid",value:c},value:d._parse(new Ge(r,p,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof ht){const c=this._def.unknownKeys;if(c==="passthrough")for(const d of a)l.push({key:{status:"valid",value:d},value:{status:"valid",value:r.data[d]}});else if(c==="strict")a.length>0&&(P(r,{code:N.unrecognized_keys,keys:a}),s.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const d of a){const p=r.data[d];l.push({key:{status:"valid",value:d},value:c._parse(new Ge(r,p,r.path,d)),alwaysSet:d in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const c=[];for(const d of l){const p=await d.key,u=await d.value;c.push({key:p,value:u,alwaysSet:d.alwaysSet})}return c}).then(c=>Se.mergeObjectSync(s,c)):Se.mergeObjectSync(s,l)}get shape(){return this._def.shape()}strict(e){return z.errToObj,new he({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,s)=>{const r=this._def.errorMap?.(n,s).message??s.defaultError;return n.code==="unrecognized_keys"?{message:z.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new he({...this._def,unknownKeys:"strip"})}passthrough(){return new he({...this._def,unknownKeys:"passthrough"})}extend(e){return new he({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new he({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Y.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new he({...this._def,catchall:e})}pick(e){const n={};for(const s of se.objectKeys(e))e[s]&&this.shape[s]&&(n[s]=this.shape[s]);return new he({...this._def,shape:()=>n})}omit(e){const n={};for(const s of se.objectKeys(this.shape))e[s]||(n[s]=this.shape[s]);return new he({...this._def,shape:()=>n})}deepPartial(){return Dt(this)}partial(e){const n={};for(const s of se.objectKeys(this.shape)){const r=this.shape[s];e&&!e[s]?n[s]=r:n[s]=r.optional()}return new he({...this._def,shape:()=>n})}required(e){const n={};for(const s of se.objectKeys(this.shape))if(e&&!e[s])n[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof ut;)i=i._def.innerType;n[s]=i}return new he({...this._def,shape:()=>n})}keyof(){return Ci(se.objectKeys(this.shape))}}he.create=(t,e)=>new he({shape:()=>t,unknownKeys:"strip",catchall:ht.create(),typeName:Y.ZodObject,...K(e)});he.strictCreate=(t,e)=>new he({shape:()=>t,unknownKeys:"strict",catchall:ht.create(),typeName:Y.ZodObject,...K(e)});he.lazycreate=(t,e)=>new he({shape:t,unknownKeys:"strip",catchall:ht.create(),typeName:Y.ZodObject,...K(e)});class Vn extends te{_parse(e){const{ctx:n}=this._processInputParams(e),s=this._def.options;function r(i){for(const a of i)if(a.result.status==="valid")return a.result;for(const a of i)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(a=>new nt(a.ctx.common.issues));return P(n,{code:N.invalid_union,unionErrors:o}),J}if(n.common.async)return Promise.all(s.map(async i=>{const o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(r);{let i;const o=[];for(const l of s){const c={...n,common:{...n.common,issues:[]},parent:null},d=l._parseSync({data:n.data,path:n.path,parent:c});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(l=>new nt(l));return P(n,{code:N.invalid_union,unionErrors:a}),J}}get options(){return this._def.options}}Vn.create=(t,e)=>new Vn({options:t,typeName:Y.ZodUnion,...K(e)});function xs(t,e){const n=ot(t),s=ot(e);if(t===e)return{valid:!0,data:t};if(n===W.object&&s===W.object){const r=se.objectKeys(e),i=se.objectKeys(t).filter(a=>r.indexOf(a)!==-1),o={...t,...e};for(const a of i){const l=xs(t[a],e[a]);if(!l.valid)return{valid:!1};o[a]=l.data}return{valid:!0,data:o}}else if(n===W.array&&s===W.array){if(t.length!==e.length)return{valid:!1};const r=[];for(let i=0;i<t.length;i++){const o=t[i],a=e[i],l=xs(o,a);if(!l.valid)return{valid:!1};r.push(l.data)}return{valid:!0,data:r}}else return n===W.date&&s===W.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class Un extends te{_parse(e){const{status:n,ctx:s}=this._processInputParams(e),r=(i,o)=>{if(Tr(i)||Tr(o))return J;const a=xs(i.value,o.value);return a.valid?((Sr(i)||Sr(o))&&n.dirty(),{status:n.value,value:a.data}):(P(s,{code:N.invalid_intersection_types}),J)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([i,o])=>r(i,o)):r(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}Un.create=(t,e,n)=>new Un({left:t,right:e,typeName:Y.ZodIntersection,...K(n)});class Ot extends te{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==W.array)return P(s,{code:N.invalid_type,expected:W.array,received:s.parsedType}),J;if(s.data.length<this._def.items.length)return P(s,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&s.data.length>this._def.items.length&&(P(s,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...s.data].map((o,a)=>{const l=this._def.items[a]||this._def.rest;return l?l._parse(new Ge(s,o,s.path,a)):null}).filter(o=>!!o);return s.common.async?Promise.all(i).then(o=>Se.mergeArray(n,o)):Se.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new Ot({...this._def,rest:e})}}Ot.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ot({items:t,typeName:Y.ZodTuple,rest:null,...K(e)})};class Wn extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==W.object)return P(s,{code:N.invalid_type,expected:W.object,received:s.parsedType}),J;const r=[],i=this._def.keyType,o=this._def.valueType;for(const a in s.data)r.push({key:i._parse(new Ge(s,a,s.path,a)),value:o._parse(new Ge(s,s.data[a],s.path,a)),alwaysSet:a in s.data});return s.common.async?Se.mergeObjectAsync(n,r):Se.mergeObjectSync(n,r)}get element(){return this._def.valueType}static create(e,n,s){return n instanceof te?new Wn({keyType:e,valueType:n,typeName:Y.ZodRecord,...K(s)}):new Wn({keyType:tt.create(),valueType:e,typeName:Y.ZodRecord,...K(n)})}}class Cr extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==W.map)return P(s,{code:N.invalid_type,expected:W.map,received:s.parsedType}),J;const r=this._def.keyType,i=this._def.valueType,o=[...s.data.entries()].map(([a,l],c)=>({key:r._parse(new Ge(s,a,s.path,[c,"key"])),value:i._parse(new Ge(s,l,s.path,[c,"value"]))}));if(s.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const l of o){const c=await l.key,d=await l.value;if(c.status==="aborted"||d.status==="aborted")return J;(c.status==="dirty"||d.status==="dirty")&&n.dirty(),a.set(c.value,d.value)}return{status:n.value,value:a}})}else{const a=new Map;for(const l of o){const c=l.key,d=l.value;if(c.status==="aborted"||d.status==="aborted")return J;(c.status==="dirty"||d.status==="dirty")&&n.dirty(),a.set(c.value,d.value)}return{status:n.value,value:a}}}}Cr.create=(t,e,n)=>new Cr({valueType:e,keyType:t,typeName:Y.ZodMap,...K(n)});class dn extends te{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==W.set)return P(s,{code:N.invalid_type,expected:W.set,received:s.parsedType}),J;const r=this._def;r.minSize!==null&&s.data.size<r.minSize.value&&(P(s,{code:N.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),n.dirty()),r.maxSize!==null&&s.data.size>r.maxSize.value&&(P(s,{code:N.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),n.dirty());const i=this._def.valueType;function o(l){const c=new Set;for(const d of l){if(d.status==="aborted")return J;d.status==="dirty"&&n.dirty(),c.add(d.value)}return{status:n.value,value:c}}const a=[...s.data.values()].map((l,c)=>i._parse(new Ge(s,l,s.path,c)));return s.common.async?Promise.all(a).then(l=>o(l)):o(a)}min(e,n){return new dn({...this._def,minSize:{value:e,message:z.toString(n)}})}max(e,n){return new dn({...this._def,maxSize:{value:e,message:z.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}dn.create=(t,e)=>new dn({valueType:t,minSize:null,maxSize:null,typeName:Y.ZodSet,...K(e)});class Fr extends te{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Fr.create=(t,e)=>new Fr({getter:t,typeName:Y.ZodLazy,...K(e)});class As extends te{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return P(n,{received:n.data,code:N.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}}As.create=(t,e)=>new As({value:t,typeName:Y.ZodLiteral,...K(e)});function Ci(t,e){return new Vt({values:t,typeName:Y.ZodEnum,...K(e)})}class Vt extends te{_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),s=this._def.values;return P(n,{expected:se.joinValues(s),received:n.parsedType,code:N.invalid_type}),J}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const n=this._getOrReturnCtx(e),s=this._def.values;return P(n,{received:n.data,code:N.invalid_enum_value,options:s}),J}return Pe(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return Vt.create(e,{...this._def,...n})}exclude(e,n=this._def){return Vt.create(this.options.filter(s=>!e.includes(s)),{...this._def,...n})}}Vt.create=Ci;class $r extends te{_parse(e){const n=se.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==W.string&&s.parsedType!==W.number){const r=se.objectValues(n);return P(s,{expected:se.joinValues(r),received:s.parsedType,code:N.invalid_type}),J}if(this._cache||(this._cache=new Set(se.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const r=se.objectValues(n);return P(s,{received:s.data,code:N.invalid_enum_value,options:r}),J}return Pe(e.data)}get enum(){return this._def.values}}$r.create=(t,e)=>new $r({values:t,typeName:Y.ZodNativeEnum,...K(e)});class jn extends te{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==W.promise&&n.common.async===!1)return P(n,{code:N.invalid_type,expected:W.promise,received:n.parsedType}),J;const s=n.parsedType===W.promise?n.data:Promise.resolve(n.data);return Pe(s.then(r=>this._def.type.parseAsync(r,{path:n.path,errorMap:n.common.contextualErrorMap})))}}jn.create=(t,e)=>new jn({type:t,typeName:Y.ZodPromise,...K(e)});class Ut extends te{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:s}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:o=>{P(s,o),o.fatal?n.abort():n.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){const o=r.transform(s.data,i);if(s.common.async)return Promise.resolve(o).then(async a=>{if(n.value==="aborted")return J;const l=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return l.status==="aborted"?J:l.status==="dirty"||n.value==="dirty"?Xt(l.value):l});{if(n.value==="aborted")return J;const a=this._def.schema._parseSync({data:o,path:s.path,parent:s});return a.status==="aborted"?J:a.status==="dirty"||n.value==="dirty"?Xt(a.value):a}}if(r.type==="refinement"){const o=a=>{const l=r.refinement(a,i);if(s.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(s.common.async===!1){const a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?J:(a.status==="dirty"&&n.dirty(),o(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>a.status==="aborted"?J:(a.status==="dirty"&&n.dirty(),o(a.value).then(()=>({status:n.value,value:a.value}))))}if(r.type==="transform")if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!Pt(o))return J;const a=r.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>Pt(o)?Promise.resolve(r.transform(o.value,i)).then(a=>({status:n.value,value:a})):J);se.assertNever(r)}}Ut.create=(t,e,n)=>new Ut({schema:t,typeName:Y.ZodEffects,effect:e,...K(n)});Ut.createWithPreprocess=(t,e,n)=>new Ut({schema:e,effect:{type:"preprocess",transform:t},typeName:Y.ZodEffects,...K(n)});class ut extends te{_parse(e){return this._getType(e)===W.undefined?Pe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ut.create=(t,e)=>new ut({innerType:t,typeName:Y.ZodOptional,...K(e)});class Wt extends te{_parse(e){return this._getType(e)===W.null?Pe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Wt.create=(t,e)=>new Wt({innerType:t,typeName:Y.ZodNullable,...K(e)});class Ns extends te{_parse(e){const{ctx:n}=this._processInputParams(e);let s=n.data;return n.parsedType===W.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Ns.create=(t,e)=>new Ns({innerType:t,typeName:Y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...K(e)});class Ds extends te{_parse(e){const{ctx:n}=this._processInputParams(e),s={...n,common:{...n.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return Pn(r)?r.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new nt(s.common.issues)},input:s.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new nt(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}Ds.create=(t,e)=>new Ds({innerType:t,typeName:Y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...K(e)});class Mr extends te{_parse(e){if(this._getType(e)!==W.nan){const s=this._getOrReturnCtx(e);return P(s,{code:N.invalid_type,expected:W.nan,received:s.parsedType}),J}return{status:"valid",value:e.data}}}Mr.create=t=>new Mr({typeName:Y.ZodNaN,...K(t)});class Ja extends te{_parse(e){const{ctx:n}=this._processInputParams(e),s=n.data;return this._def.type._parse({data:s,path:n.path,parent:n})}unwrap(){return this._def.type}}class Qs extends te{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?J:i.status==="dirty"?(n.dirty(),Xt(i.value)):this._def.out._parseAsync({data:i.value,path:s.path,parent:s})})();{const r=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return r.status==="aborted"?J:r.status==="dirty"?(n.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:s.path,parent:s})}}static create(e,n){return new Qs({in:e,out:n,typeName:Y.ZodPipeline})}}class Cs extends te{_parse(e){const n=this._def.innerType._parse(e),s=r=>(Pt(r)&&(r.value=Object.freeze(r.value)),r);return Pn(n)?n.then(r=>s(r)):s(n)}unwrap(){return this._def.innerType}}Cs.create=(t,e)=>new Cs({innerType:t,typeName:Y.ZodReadonly,...K(e)});var Y;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Y||(Y={}));const Ie=tt.create,_t=Lt.create,an=Ts.create,us=Ss.create,ve=Is.create;ht.create;const Tt=ze.create,qe=he.create,Oe=Vn.create;Un.create;Ot.create;const pn=Wn.create,Ee=As.create,Zn=Vt.create;jn.create;ut.create;Wt.create;const In=()=>ve().refine(t=>t&&(t.seconds!==void 0&&t.nanoseconds!==void 0||t._seconds!==void 0&&t._nanoseconds!==void 0),{message:"Value is not a valid timestamp"}),Pr=()=>ve().refine(t=>t&&(t._methodName==="serverTimestamp"||t.constructor.name==="ServerTimestampTransform"),{message:"Value is not a valid server timestamp"}),Fi=(t,e,n)=>{const s={};if(t.includeFields){const i=e.collections[t.collection];if(!i)return pn(ve());t.includeFields.forEach(o=>{const a=i.fields.find(c=>c.name===o);if(!a)throw new Error(`Field ${o} not found in collection ${t.collection}`);s[o]=zn(i,a),Rt(i,[a]).size===1&&(s[`${o}_Lowercase`]=zn(i,a,!0))})}const r={Collection_Path:Tt(Ie()),...s};return n&&(r.id=Ie().length(20)),qe(r)},Qa=(t,e)=>{let n=pn(Fi(t,e));return t.required||(n=n.optional()),n},Ka=t=>{let e=Tt(Oe([Ie().length(20),Ie().length(28)]));return["OneToOne","OneToMany"].includes(t.type)?e=e.max(1):(t.min&&(e=e.min(t.min)),t.max&&(e=e.max(t.max)),t.length&&(e=e.length(t.length))),t.required?e=e.nonempty():e=e.optional(),e},zn=(t,e,n)=>{const{softDelete:s}=t,r=s?.timestampField;let i;switch(e.type){case"String":if(i=Ie(),e.length&&(i=i.length(e.length)),e.minlength&&(i=i.min(e.minlength)),e.maxlength&&(i=i.max(e.maxlength)),e.email&&(i=i.email()),e.uuid&&(i=i.uuid()),e.url&&(i=i.url()),e.emoji&&(i=i.emoji()),e.ip&&(i=i.ip()),n&&(i=i.toLowerCase()),e.pattern&&(i=Oe([i.regex(new RegExp(e.pattern)),Ee("")])),e.values)if(n){const o=e.values.map(a=>a.toLowerCase());i=Zn(o)}else i=Zn(e.values);break;case"Boolean":i=an();break;case"Number":e.autoIncrement?i=Oe([Ee("Pending"),_t().int()]):(i=_t(),e.min&&(i=i.min(e.min)),e.max&&(i=i.max(e.max)),e.decimal?i=i.refine(o=>e.decimal?(o.toString().split(".")[1]?.length||0)<=e.decimal:!1,{message:`Value must have ${e.decimal} or fewer decimal places`}):i=i.int(),e.values&&(i=i.refine(o=>e.values?.includes(o),{message:"Value is not an allowed value"})));break;case"Timestamp":e.name===r?i=ve().refine(o=>o&&(o._methodName==="serverTimestamp"||o.constructor.name==="ServerTimestampTransform"||o.seconds!==void 0&&o.nanoseconds!==void 0||o._seconds!==void 0&&o._nanoseconds!==void 0),{message:"Value is not a valid timestamp"}):(i=In(),e.min&&(i=i.refine(o=>o.toMillis()>=e.min,{message:`Value is less than the minimum allowed value of ${e.min}`})),e.max&&(i=i.refine(o=>o.toMillis()<=e.max,{message:`Value is greater than the maximum allowed value of ${e.max}`})));break;case"Array":i=Tt(ve()),e.length&&(i=i.length(e.length)),e.minlength?i=i.min(e.minlength):e.required&&(i=i.nonempty()),e.maxlength&&(i=i.max(e.maxlength)),e.values&&(i=i.refine(o=>{let a=!0;return o.forEach(l=>{e.values&&!e.values.includes(l)&&(a=!1)}),a},{message:"Value is not an allowed value"}));break;case"Map":i=pn(ve()),e.required&&(i=i.refine(o=>o&&typeof o=="object"&&Object.keys(o).length>0,{message:"Value must have at least one object property"}));break;case"Embedding":i=ve();break}return!X(e)&&e.nullable&&(i=i.nullable()),e.required||(i=i.optional()),i},$i=(t,e,n)=>{const s={Collection_Path:Tt(Ie()),Last_Write_App:Ie(),Last_Write_At:In(),Last_Save_At:Pr(),Last_Write_By:Oe([Ie().length(28),Ee("System")]),Last_Write_Connection_Status:Zn(["Online","Offline"]),Last_Write_Version:_t().int(),id:Ie().regex(new RegExp("^[a-zA-Z0-9]+$")).length(20),Created_At:In(),Created_By:Oe([Ie().length(28),Ee("System")])};t==="create"&&(s.Saved_At=Pr()),t==="update"&&(s.Saved_At=In(),s.Collection_Path=s.Collection_Path.optional(),s.id=s.id.optional(),s.Created_At=s.Created_At.optional(),s.Saved_At=s.Saved_At.optional(),s.Created_By=s.Created_By.optional());const r=gt(e,e.fields),i=Array.from(r).map(l=>l.name);e.fields.forEach(l=>{X(l)?(s[l.name]=Qa(l,n),s[`${l.name}_Array`]=Ka(l),i.includes(l.name)&&(s[`${l.name}_Single`]=Fi(l,n,!0),l.required||(s[`${l.name}_Single`]=s[`${l.name}_Single`].optional())),l.length&&(s[l.name]=s[l.name].refine(c=>l.length&&c&&Object.keys(c).length===l.length,{message:`Value must contain ${l.length} item(s)`})),l.min&&(s[l.name]=s[l.name].refine(c=>l.min&&c&&Object.keys(c).length>=l.min,{message:`Value must contain at least ${l.min} item(s)`})),l.max&&(s[l.name]=s[l.name].refine(c=>l.max&&(!c||Object.keys(c).length<=l.max),{message:`Value must contain at most ${l.max} item(s)`}))):l.type!=="Computed"&&(s[l.name]=zn(e,l))}),Rt(e,e.fields).forEach(l=>{s[l.name]&&(s[`${l.name}_Lowercase`]=zn(e,l,!0))});const a=qe(s);return e.allowSchemalessFields?a.passthrough():a.strict()};class St extends Error{}class Xa extends St{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class el extends St{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class tl extends St{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class Ct extends St{}class Mi extends St{constructor(e){super(`Invalid unit ${e}`)}}class ke extends St{}class it extends St{constructor(){super("Zone is an abstract class")}}const $="numeric",je="short",Ae="long",qn={year:$,month:$,day:$},Pi={year:$,month:je,day:$},nl={year:$,month:je,day:$,weekday:je},Li={year:$,month:Ae,day:$},Vi={year:$,month:Ae,day:$,weekday:Ae},Ui={hour:$,minute:$},Wi={hour:$,minute:$,second:$},ji={hour:$,minute:$,second:$,timeZoneName:je},Zi={hour:$,minute:$,second:$,timeZoneName:Ae},zi={hour:$,minute:$,hourCycle:"h23"},qi={hour:$,minute:$,second:$,hourCycle:"h23"},Bi={hour:$,minute:$,second:$,hourCycle:"h23",timeZoneName:je},Hi={hour:$,minute:$,second:$,hourCycle:"h23",timeZoneName:Ae},Gi={year:$,month:$,day:$,hour:$,minute:$},Yi={year:$,month:$,day:$,hour:$,minute:$,second:$},Ji={year:$,month:je,day:$,hour:$,minute:$},Qi={year:$,month:je,day:$,hour:$,minute:$,second:$},sl={year:$,month:je,day:$,weekday:je,hour:$,minute:$},Ki={year:$,month:Ae,day:$,hour:$,minute:$,timeZoneName:je},Xi={year:$,month:Ae,day:$,hour:$,minute:$,second:$,timeZoneName:je},eo={year:$,month:Ae,day:$,weekday:Ae,hour:$,minute:$,timeZoneName:Ae},to={year:$,month:Ae,day:$,weekday:Ae,hour:$,minute:$,second:$,timeZoneName:Ae};class yn{get type(){throw new it}get name(){throw new it}get ianaName(){return this.name}get isUniversal(){throw new it}offsetName(e,n){throw new it}formatOffset(e,n){throw new it}offset(e){throw new it}equals(e){throw new it}get isValid(){throw new it}}let ds=null;class es extends yn{static get instance(){return ds===null&&(ds=new es),ds}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:n,locale:s}){return ho(e,n,s)}formatOffset(e,n){return ln(this.offset(e),n)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}const Fs=new Map;function rl(t){let e=Fs.get(t);return e===void 0&&(e=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"}),Fs.set(t,e)),e}const il={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function ol(t,e){const n=t.format(e).replace(/\u200E/g,""),s=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(n),[,r,i,o,a,l,c,d]=s;return[o,r,i,a,l,c,d]}function al(t,e){const n=t.formatToParts(e),s=[];for(let r=0;r<n.length;r++){const{type:i,value:o}=n[r],a=il[i];i==="era"?s[a]=o:G(a)||(s[a]=parseInt(o,10))}return s}const fs=new Map;class st extends yn{static create(e){let n=fs.get(e);return n===void 0&&fs.set(e,n=new st(e)),n}static resetCache(){fs.clear(),Fs.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(e){super(),this.zoneName=e,this.valid=st.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:n,locale:s}){return ho(e,n,s,this.name)}formatOffset(e,n){return ln(this.offset(e),n)}offset(e){if(!this.valid)return NaN;const n=new Date(e);if(isNaN(n))return NaN;const s=rl(this.name);let[r,i,o,a,l,c,d]=s.formatToParts?al(s,n):ol(s,n);a==="BC"&&(r=-Math.abs(r)+1);const u=ns({year:r,month:i,day:o,hour:l===24?0:l,minute:c,second:d,millisecond:0});let f=+n;const g=f%1e3;return f-=g>=0?g:1e3+g,(u-f)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}let Lr={};function ll(t,e={}){const n=JSON.stringify([t,e]);let s=Lr[n];return s||(s=new Intl.ListFormat(t,e),Lr[n]=s),s}const $s=new Map;function Ms(t,e={}){const n=JSON.stringify([t,e]);let s=$s.get(n);return s===void 0&&(s=new Intl.DateTimeFormat(t,e),$s.set(n,s)),s}const Ps=new Map;function cl(t,e={}){const n=JSON.stringify([t,e]);let s=Ps.get(n);return s===void 0&&(s=new Intl.NumberFormat(t,e),Ps.set(n,s)),s}const Ls=new Map;function ul(t,e={}){const{base:n,...s}=e,r=JSON.stringify([t,s]);let i=Ls.get(r);return i===void 0&&(i=new Intl.RelativeTimeFormat(t,e),Ls.set(r,i)),i}let en=null;function dl(){return en||(en=new Intl.DateTimeFormat().resolvedOptions().locale,en)}const Vs=new Map;function no(t){let e=Vs.get(t);return e===void 0&&(e=new Intl.DateTimeFormat(t).resolvedOptions(),Vs.set(t,e)),e}const Us=new Map;function fl(t){let e=Us.get(t);if(!e){const n=new Intl.Locale(t);e="getWeekInfo"in n?n.getWeekInfo():n.weekInfo,"minimalDays"in e||(e={...so,...e}),Us.set(t,e)}return e}function hl(t){const e=t.indexOf("-x-");e!==-1&&(t=t.substring(0,e));const n=t.indexOf("-u-");if(n===-1)return[t];{let s,r;try{s=Ms(t).resolvedOptions(),r=t}catch{const l=t.substring(0,n);s=Ms(l).resolvedOptions(),r=l}const{numberingSystem:i,calendar:o}=s;return[r,i,o]}}function ml(t,e,n){return(n||e)&&(t.includes("-u-")||(t+="-u"),n&&(t+=`-ca-${n}`),e&&(t+=`-nu-${e}`)),t}function pl(t){const e=[];for(let n=1;n<=12;n++){const s=V.utc(2009,n,1);e.push(t(s))}return e}function yl(t){const e=[];for(let n=1;n<=7;n++){const s=V.utc(2016,11,13+n);e.push(t(s))}return e}function On(t,e,n,s){const r=t.listingMode();return r==="error"?null:r==="en"?n(e):s(e)}function gl(t){return t.numberingSystem&&t.numberingSystem!=="latn"?!1:t.numberingSystem==="latn"||!t.locale||t.locale.startsWith("en")||no(t.locale).numberingSystem==="latn"}class wl{constructor(e,n,s){this.padTo=s.padTo||0,this.floor=s.floor||!1;const{padTo:r,floor:i,...o}=s;if(!n||Object.keys(o).length>0){const a={useGrouping:!1,...s};s.padTo>0&&(a.minimumIntegerDigits=s.padTo),this.inf=cl(e,a)}}format(e){if(this.inf){const n=this.floor?Math.floor(e):e;return this.inf.format(n)}else{const n=this.floor?Math.floor(e):nr(e,3);return me(n,this.padTo)}}}class _l{constructor(e,n,s){this.opts=s,this.originalZone=void 0;let r;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){const o=-1*(e.offset/60),a=o>=0?`Etc/GMT+${o}`:`Etc/GMT${o}`;e.offset!==0&&st.create(a).valid?(r=a,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);const i={...this.opts};i.timeZone=i.timeZone||r,this.dtf=Ms(n,i)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){const e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(n=>{if(n.type==="timeZoneName"){const s=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...n,value:s}}else return n}):e}resolvedOptions(){return this.dtf.resolvedOptions()}}class El{constructor(e,n,s){this.opts={style:"long",...s},!n&&uo()&&(this.rtf=ul(e,s))}format(e,n){return this.rtf?this.rtf.format(e,n):jl(n,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,n){return this.rtf?this.rtf.formatToParts(e,n):[]}}const so={firstDay:1,minimalDays:4,weekend:[6,7]};class ie{static fromOpts(e){return ie.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,n,s,r,i=!1){const o=e||de.defaultLocale,a=o||(i?"en-US":dl()),l=n||de.defaultNumberingSystem,c=s||de.defaultOutputCalendar,d=js(r)||de.defaultWeekSettings;return new ie(a,l,c,d,o)}static resetCache(){en=null,$s.clear(),Ps.clear(),Ls.clear(),Vs.clear(),Us.clear()}static fromObject({locale:e,numberingSystem:n,outputCalendar:s,weekSettings:r}={}){return ie.create(e,n,s,r)}constructor(e,n,s,r,i){const[o,a,l]=hl(e);this.locale=o,this.numberingSystem=n||a||null,this.outputCalendar=s||l||null,this.weekSettings=r,this.intl=ml(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==null&&(this.fastNumbersCached=gl(this)),this.fastNumbersCached}listingMode(){const e=this.isEnglish(),n=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&n?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:ie.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,js(e.weekSettings)||this.weekSettings,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,n=!1){return On(this,e,yo,()=>{const s=this.intl==="ja"||this.intl.startsWith("ja-");n&=!s;const r=n?{month:e,day:"numeric"}:{month:e},i=n?"format":"standalone";if(!this.monthsCache[i][e]){const o=s?a=>this.dtFormatter(a,r).format():a=>this.extract(a,r,"month");this.monthsCache[i][e]=pl(o)}return this.monthsCache[i][e]})}weekdays(e,n=!1){return On(this,e,_o,()=>{const s=n?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},r=n?"format":"standalone";return this.weekdaysCache[r][e]||(this.weekdaysCache[r][e]=yl(i=>this.extract(i,s,"weekday"))),this.weekdaysCache[r][e]})}meridiems(){return On(this,void 0,()=>Eo,()=>{if(!this.meridiemCache){const e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[V.utc(2016,11,13,9),V.utc(2016,11,13,19)].map(n=>this.extract(n,e,"dayperiod"))}return this.meridiemCache})}eras(e){return On(this,e,vo,()=>{const n={era:e};return this.eraCache[e]||(this.eraCache[e]=[V.utc(-40,1,1),V.utc(2017,1,1)].map(s=>this.extract(s,n,"era"))),this.eraCache[e]})}extract(e,n,s){const r=this.dtFormatter(e,n),i=r.formatToParts(),o=i.find(a=>a.type.toLowerCase()===s);return o?o.value:null}numberFormatter(e={}){return new wl(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,n={}){return new _l(e,this.intl,n)}relFormatter(e={}){return new El(this.intl,this.isEnglish(),e)}listFormatter(e={}){return ll(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||no(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:fo()?fl(this.locale):so}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})`}}let hs=null;class Te extends yn{static get utcInstance(){return hs===null&&(hs=new Te(0)),hs}static instance(e){return e===0?Te.utcInstance:new Te(e)}static parseSpecifier(e){if(e){const n=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(n)return new Te(ss(n[1],n[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${ln(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${ln(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,n){return ln(this.fixed,n)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}}class vl extends yn{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 lt(t,e){if(G(t)||t===null)return e;if(t instanceof yn)return t;if(Sl(t)){const n=t.toLowerCase();return n==="default"?e:n==="local"||n==="system"?es.instance:n==="utc"||n==="gmt"?Te.utcInstance:Te.parseSpecifier(n)||st.create(t)}else return dt(t)?Te.instance(t):typeof t=="object"&&"offset"in t&&typeof t.offset=="function"?t:new vl(t)}const Ks={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},Vr={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]},Ol=Ks.hanidec.replace(/[\[|\]]/g,"").split("");function kl(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let n=0;n<t.length;n++){const s=t.charCodeAt(n);if(t[n].search(Ks.hanidec)!==-1)e+=Ol.indexOf(t[n]);else for(const r in Vr){const[i,o]=Vr[r];s>=i&&s<=o&&(e+=s-i)}}return parseInt(e,10)}else return e}const Ws=new Map;function bl(){Ws.clear()}function Le({numberingSystem:t},e=""){const n=t||"latn";let s=Ws.get(n);s===void 0&&(s=new Map,Ws.set(n,s));let r=s.get(e);return r===void 0&&(r=new RegExp(`${Ks[n]}${e}`),s.set(e,r)),r}let Ur=()=>Date.now(),Wr="system",jr=null,Zr=null,zr=null,qr=60,Br,Hr=null;class de{static get now(){return Ur}static set now(e){Ur=e}static set defaultZone(e){Wr=e}static get defaultZone(){return lt(Wr,es.instance)}static get defaultLocale(){return jr}static set defaultLocale(e){jr=e}static get defaultNumberingSystem(){return Zr}static set defaultNumberingSystem(e){Zr=e}static get defaultOutputCalendar(){return zr}static set defaultOutputCalendar(e){zr=e}static get defaultWeekSettings(){return Hr}static set defaultWeekSettings(e){Hr=js(e)}static get twoDigitCutoffYear(){return qr}static set twoDigitCutoffYear(e){qr=e%100}static get throwOnInvalid(){return Br}static set throwOnInvalid(e){Br=e}static resetCaches(){ie.resetCache(),st.resetCache(),V.resetCache(),bl()}}class Ue{constructor(e,n){this.reason=e,this.explanation=n}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}const ro=[0,31,59,90,120,151,181,212,243,273,304,334],io=[0,31,60,91,121,152,182,213,244,274,305,335];function $e(t,e){return new Ue("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function Xs(t,e,n){const s=new Date(Date.UTC(t,e-1,n));t<100&&t>=0&&s.setUTCFullYear(s.getUTCFullYear()-1900);const r=s.getUTCDay();return r===0?7:r}function oo(t,e,n){return n+(gn(t)?io:ro)[e-1]}function ao(t,e){const n=gn(t)?io:ro,s=n.findIndex(i=>i<e),r=e-n[s];return{month:s+1,day:r}}function er(t,e){return(t-e+7)%7+1}function Bn(t,e=4,n=1){const{year:s,month:r,day:i}=t,o=oo(s,r,i),a=er(Xs(s,r,i),n);let l=Math.floor((o-a+14-e)/7),c;return l<1?(c=s-1,l=fn(c,e,n)):l>fn(s,e,n)?(c=s+1,l=1):c=s,{weekYear:c,weekNumber:l,weekday:a,...rs(t)}}function Gr(t,e=4,n=1){const{weekYear:s,weekNumber:r,weekday:i}=t,o=er(Xs(s,1,e),n),a=$t(s);let l=r*7+i-o-7+e,c;l<1?(c=s-1,l+=$t(c)):l>a?(c=s+1,l-=$t(s)):c=s;const{month:d,day:p}=ao(c,l);return{year:c,month:d,day:p,...rs(t)}}function ms(t){const{year:e,month:n,day:s}=t,r=oo(e,n,s);return{year:e,ordinal:r,...rs(t)}}function Yr(t){const{year:e,ordinal:n}=t,{month:s,day:r}=ao(e,n);return{year:e,month:s,day:r,...rs(t)}}function Jr(t,e){if(!G(t.localWeekday)||!G(t.localWeekNumber)||!G(t.localWeekYear)){if(!G(t.weekday)||!G(t.weekNumber)||!G(t.weekYear))throw new Ct("Cannot mix locale-based week fields with ISO-based week fields");return G(t.localWeekday)||(t.weekday=t.localWeekday),G(t.localWeekNumber)||(t.weekNumber=t.localWeekNumber),G(t.localWeekYear)||(t.weekYear=t.localWeekYear),delete t.localWeekday,delete t.localWeekNumber,delete t.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function Rl(t,e=4,n=1){const s=ts(t.weekYear),r=Me(t.weekNumber,1,fn(t.weekYear,e,n)),i=Me(t.weekday,1,7);return s?r?i?!1:$e("weekday",t.weekday):$e("week",t.weekNumber):$e("weekYear",t.weekYear)}function Tl(t){const e=ts(t.year),n=Me(t.ordinal,1,$t(t.year));return e?n?!1:$e("ordinal",t.ordinal):$e("year",t.year)}function lo(t){const e=ts(t.year),n=Me(t.month,1,12),s=Me(t.day,1,Hn(t.year,t.month));return e?n?s?!1:$e("day",t.day):$e("month",t.month):$e("year",t.year)}function co(t){const{hour:e,minute:n,second:s,millisecond:r}=t,i=Me(e,0,23)||e===24&&n===0&&s===0&&r===0,o=Me(n,0,59),a=Me(s,0,59),l=Me(r,0,999);return i?o?a?l?!1:$e("millisecond",r):$e("second",s):$e("minute",n):$e("hour",e)}function G(t){return typeof t>"u"}function dt(t){return typeof t=="number"}function ts(t){return typeof t=="number"&&t%1===0}function Sl(t){return typeof t=="string"}function Il(t){return Object.prototype.toString.call(t)==="[object Date]"}function uo(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function fo(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function xl(t){return Array.isArray(t)?t:[t]}function Qr(t,e,n){if(t.length!==0)return t.reduce((s,r)=>{const i=[e(r),r];return s&&n(s[0],i[0])===s[0]?s:i},null)[1]}function Al(t,e){return e.reduce((n,s)=>(n[s]=t[s],n),{})}function jt(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function js(t){if(t==null)return null;if(typeof t!="object")throw new ke("Week settings must be an object");if(!Me(t.firstDay,1,7)||!Me(t.minimalDays,1,7)||!Array.isArray(t.weekend)||t.weekend.some(e=>!Me(e,1,7)))throw new ke("Invalid week settings");return{firstDay:t.firstDay,minimalDays:t.minimalDays,weekend:Array.from(t.weekend)}}function Me(t,e,n){return ts(t)&&t>=e&&t<=n}function Nl(t,e){return t-e*Math.floor(t/e)}function me(t,e=2){const n=t<0;let s;return n?s="-"+(""+-t).padStart(e,"0"):s=(""+t).padStart(e,"0"),s}function at(t){if(!(G(t)||t===null||t===""))return parseInt(t,10)}function pt(t){if(!(G(t)||t===null||t===""))return parseFloat(t)}function tr(t){if(!(G(t)||t===null||t==="")){const e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function nr(t,e,n="round"){const s=10**e;switch(n){case"expand":return t>0?Math.ceil(t*s)/s:Math.floor(t*s)/s;case"trunc":return Math.trunc(t*s)/s;case"round":return Math.round(t*s)/s;case"floor":return Math.floor(t*s)/s;case"ceil":return Math.ceil(t*s)/s;default:throw new RangeError(`Value rounding ${n} is out of range`)}}function gn(t){return t%4===0&&(t%100!==0||t%400===0)}function $t(t){return gn(t)?366:365}function Hn(t,e){const n=Nl(e-1,12)+1,s=t+(e-n)/12;return n===2?gn(s)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][n-1]}function ns(t){let e=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second,t.millisecond);return t.year<100&&t.year>=0&&(e=new Date(e),e.setUTCFullYear(t.year,t.month-1,t.day)),+e}function Kr(t,e,n){return-er(Xs(t,1,e),n)+e-1}function fn(t,e=4,n=1){const s=Kr(t,e,n),r=Kr(t+1,e,n);return($t(t)-s+r)/7}function Zs(t){return t>99?t:t>de.twoDigitCutoffYear?1900+t:2e3+t}function ho(t,e,n,s=null){const r=new Date(t),i={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};s&&(i.timeZone=s);const o={timeZoneName:e,...i},a=new Intl.DateTimeFormat(n,o).formatToParts(r).find(l=>l.type.toLowerCase()==="timezonename");return a?a.value:null}function ss(t,e){let n=parseInt(t,10);Number.isNaN(n)&&(n=0);const s=parseInt(e,10)||0,r=n<0||Object.is(n,-0)?-s:s;return n*60+r}function mo(t){const e=Number(t);if(typeof t=="boolean"||t===""||!Number.isFinite(e))throw new ke(`Invalid unit value ${t}`);return e}function Gn(t,e){const n={};for(const s in t)if(jt(t,s)){const r=t[s];if(r==null)continue;n[e(s)]=mo(r)}return n}function ln(t,e){const n=Math.trunc(Math.abs(t/60)),s=Math.trunc(Math.abs(t%60)),r=t>=0?"+":"-";switch(e){case"short":return`${r}${me(n,2)}:${me(s,2)}`;case"narrow":return`${r}${n}${s>0?`:${s}`:""}`;case"techie":return`${r}${me(n,2)}${me(s,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function rs(t){return Al(t,["hour","minute","second","millisecond"])}const Dl=["January","February","March","April","May","June","July","August","September","October","November","December"],po=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Cl=["J","F","M","A","M","J","J","A","S","O","N","D"];function yo(t){switch(t){case"narrow":return[...Cl];case"short":return[...po];case"long":return[...Dl];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}}const go=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],wo=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],Fl=["M","T","W","T","F","S","S"];function _o(t){switch(t){case"narrow":return[...Fl];case"short":return[...wo];case"long":return[...go];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const Eo=["AM","PM"],$l=["Before Christ","Anno Domini"],Ml=["BC","AD"],Pl=["B","A"];function vo(t){switch(t){case"narrow":return[...Pl];case"short":return[...Ml];case"long":return[...$l];default:return null}}function Ll(t){return Eo[t.hour<12?0:1]}function Vl(t,e){return _o(e)[t.weekday-1]}function Ul(t,e){return yo(e)[t.month-1]}function Wl(t,e){return vo(e)[t.year<0?0:1]}function jl(t,e,n="always",s=!1){const r={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."]},i=["hours","minutes","seconds"].indexOf(t)===-1;if(n==="auto"&&i){const p=t==="days";switch(e){case 1:return p?"tomorrow":`next ${r[t][0]}`;case-1:return p?"yesterday":`last ${r[t][0]}`;case 0:return p?"today":`this ${r[t][0]}`}}const o=Object.is(e,-0)||e<0,a=Math.abs(e),l=a===1,c=r[t],d=s?l?c[1]:c[2]||c[1]:l?r[t][0]:t;return o?`${a} ${d} ago`:`in ${a} ${d}`}function Xr(t,e){let n="";for(const s of t)s.literal?n+=s.val:n+=e(s.val);return n}const Zl={D:qn,DD:Pi,DDD:Li,DDDD:Vi,t:Ui,tt:Wi,ttt:ji,tttt:Zi,T:zi,TT:qi,TTT:Bi,TTTT:Hi,f:Gi,ff:Ji,fff:Ki,ffff:eo,F:Yi,FF:Qi,FFF:Xi,FFFF:to};class Re{static create(e,n={}){return new Re(e,n)}static parseFormat(e){let n=null,s="",r=!1;const i=[];for(let o=0;o<e.length;o++){const a=e.charAt(o);a==="'"?((s.length>0||r)&&i.push({literal:r||/^\s+$/.test(s),val:s===""?"'":s}),n=null,s="",r=!r):r||a===n?s+=a:(s.length>0&&i.push({literal:/^\s+$/.test(s),val:s}),s=a,n=a)}return s.length>0&&i.push({literal:r||/^\s+$/.test(s),val:s}),i}static macroTokenToFormatOpts(e){return Zl[e]}constructor(e,n){this.opts=n,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,n){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...n}).format()}dtFormatter(e,n={}){return this.loc.dtFormatter(e,{...this.opts,...n})}formatDateTime(e,n){return this.dtFormatter(e,n).format()}formatDateTimeParts(e,n){return this.dtFormatter(e,n).formatToParts()}formatInterval(e,n){return this.dtFormatter(e.start,n).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,n){return this.dtFormatter(e,n).resolvedOptions()}num(e,n=0,s=void 0){if(this.opts.forceSimple)return me(e,n);const r={...this.opts};return n>0&&(r.padTo=n),s&&(r.signDisplay=s),this.loc.numberFormatter(r).format(e)}formatDateTimeFromString(e,n){const s=this.loc.listingMode()==="en",r=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",i=(f,g)=>this.loc.extract(e,f,g),o=f=>e.isOffsetFixed&&e.offset===0&&f.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,f.format):"",a=()=>s?Ll(e):i({hour:"numeric",hourCycle:"h12"},"dayperiod"),l=(f,g)=>s?Ul(e,f):i(g?{month:f}:{month:f,day:"numeric"},"month"),c=(f,g)=>s?Vl(e,f):i(g?{weekday:f}:{weekday:f,month:"long",day:"numeric"},"weekday"),d=f=>{const g=Re.macroTokenToFormatOpts(f);return g?this.formatWithSystemDefault(e,g):f},p=f=>s?Wl(e,f):i({era:f},"era"),u=f=>{switch(f){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.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 e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return a();case"d":return r?i({day:"numeric"},"day"):this.num(e.day);case"dd":return r?i({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return c("short",!0);case"cccc":return c("long",!0);case"ccccc":return c("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return c("short",!1);case"EEEE":return c("long",!1);case"EEEEE":return c("narrow",!1);case"L":return r?i({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return r?i({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return l("short",!0);case"LLLL":return l("long",!0);case"LLLLL":return l("narrow",!0);case"M":return r?i({month:"numeric"},"month"):this.num(e.month);case"MM":return r?i({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return l("short",!1);case"MMMM":return l("long",!1);case"MMMMM":return l("narrow",!1);case"y":return r?i({year:"numeric"},"year"):this.num(e.year);case"yy":return r?i({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return r?i({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return r?i({year:"numeric"},"year"):this.num(e.year,6);case"G":return p("short");case"GG":return p("long");case"GGGGG":return p("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return d(f)}};return Xr(Re.parseFormat(n),u)}formatDurationFromString(e,n){const s=this.opts.signMode==="negativeLargestOnly"?-1:1,r=d=>{switch(d[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}},i=(d,p)=>u=>{const f=r(u);if(f){const g=p.isNegativeDuration&&f!==p.largestUnit?s:1;let k;return this.opts.signMode==="negativeLargestOnly"&&f!==p.largestUnit?k="never":this.opts.signMode==="all"?k="always":k="auto",this.num(d.get(f)*g,u.length,k)}else return u},o=Re.parseFormat(n),a=o.reduce((d,{literal:p,val:u})=>p?d:d.concat(u),[]),l=e.shiftTo(...a.map(r).filter(d=>d)),c={isNegativeDuration:l<0,largestUnit:Object.keys(l.values)[0]};return Xr(o,i(l,c))}}const Oo=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Zt(...t){const e=t.reduce((n,s)=>n+s.source,"");return RegExp(`^${e}$`)}function zt(...t){return e=>t.reduce(([n,s,r],i)=>{const[o,a,l]=i(e,r);return[{...n,...o},a||s,l]},[{},null,1]).slice(0,2)}function qt(t,...e){if(t==null)return[null,null];for(const[n,s]of e){const r=n.exec(t);if(r)return s(r)}return[null,null]}function ko(...t){return(e,n)=>{const s={};let r;for(r=0;r<t.length;r++)s[t[r]]=at(e[n+r]);return[s,null,n+r]}}const bo=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,zl=`(?:${bo.source}?(?:\\[(${Oo.source})\\])?)?`,sr=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,Ro=RegExp(`${sr.source}${zl}`),rr=RegExp(`(?:[Tt]${Ro.source})?`),ql=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Bl=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Hl=/(\d{4})-?(\d{3})/,Gl=ko("weekYear","weekNumber","weekDay"),Yl=ko("year","ordinal"),Jl=/(\d{4})-(\d\d)-(\d\d)/,To=RegExp(`${sr.source} ?(?:${bo.source}|(${Oo.source}))?`),Ql=RegExp(`(?: ${To.source})?`);function Mt(t,e,n){const s=t[e];return G(s)?n:at(s)}function Kl(t,e){return[{year:Mt(t,e),month:Mt(t,e+1,1),day:Mt(t,e+2,1)},null,e+3]}function Bt(t,e){return[{hours:Mt(t,e,0),minutes:Mt(t,e+1,0),seconds:Mt(t,e+2,0),milliseconds:tr(t[e+3])},null,e+4]}function wn(t,e){const n=!t[e]&&!t[e+1],s=ss(t[e+1],t[e+2]),r=n?null:Te.instance(s);return[{},r,e+3]}function _n(t,e){const n=t[e]?st.create(t[e]):null;return[{},n,e+1]}const Xl=RegExp(`^T?${sr.source}$`),ec=/^-?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 tc(t){const[e,n,s,r,i,o,a,l,c]=t,d=e[0]==="-",p=l&&l[0]==="-",u=(f,g=!1)=>f!==void 0&&(g||f&&d)?-f:f;return[{years:u(pt(n)),months:u(pt(s)),weeks:u(pt(r)),days:u(pt(i)),hours:u(pt(o)),minutes:u(pt(a)),seconds:u(pt(l),l==="-0"),milliseconds:u(tr(c),p)}]}const nc={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function ir(t,e,n,s,r,i,o){const a={year:e.length===2?Zs(at(e)):at(e),month:po.indexOf(n)+1,day:at(s),hour:at(r),minute:at(i)};return o&&(a.second=at(o)),t&&(a.weekday=t.length>3?go.indexOf(t)+1:wo.indexOf(t)+1),a}const sc=/^(?:(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 rc(t){const[,e,n,s,r,i,o,a,l,c,d,p]=t,u=ir(e,r,s,n,i,o,a);let f;return l?f=nc[l]:c?f=0:f=ss(d,p),[u,new Te(f)]}function ic(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const oc=/^(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$/,ac=/^(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$/,lc=/^(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 ei(t){const[,e,n,s,r,i,o,a]=t;return[ir(e,r,s,n,i,o,a),Te.utcInstance]}function cc(t){const[,e,n,s,r,i,o,a]=t;return[ir(e,a,n,s,r,i,o),Te.utcInstance]}const uc=Zt(ql,rr),dc=Zt(Bl,rr),fc=Zt(Hl,rr),hc=Zt(Ro),So=zt(Kl,Bt,wn,_n),mc=zt(Gl,Bt,wn,_n),pc=zt(Yl,Bt,wn,_n),yc=zt(Bt,wn,_n);function gc(t){return qt(t,[uc,So],[dc,mc],[fc,pc],[hc,yc])}function wc(t){return qt(ic(t),[sc,rc])}function _c(t){return qt(t,[oc,ei],[ac,ei],[lc,cc])}function Ec(t){return qt(t,[ec,tc])}const vc=zt(Bt);function Oc(t){return qt(t,[Xl,vc])}const kc=Zt(Jl,Ql),bc=Zt(To),Rc=zt(Bt,wn,_n);function Tc(t){return qt(t,[kc,So],[bc,Rc])}const ti="Invalid Duration",Io={weeks:{days:7,hours:168,minutes:10080,seconds:10080*60,milliseconds:10080*60*1e3},days:{hours:24,minutes:1440,seconds:1440*60,milliseconds:1440*60*1e3},hours:{minutes:60,seconds:3600,milliseconds:3600*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},Sc={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:2184,minutes:2184*60,seconds:2184*60*60,milliseconds:2184*60*60*1e3},months:{weeks:4,days:30,hours:720,minutes:720*60,seconds:720*60*60,milliseconds:720*60*60*1e3},...Io},Fe=146097/400,xt=146097/4800,Ic={years:{quarters:4,months:12,weeks:Fe/7,days:Fe,hours:Fe*24,minutes:Fe*24*60,seconds:Fe*24*60*60,milliseconds:Fe*24*60*60*1e3},quarters:{months:3,weeks:Fe/28,days:Fe/4,hours:Fe*24/4,minutes:Fe*24*60/4,seconds:Fe*24*60*60/4,milliseconds:Fe*24*60*60*1e3/4},months:{weeks:xt/7,days:xt,hours:xt*24,minutes:xt*24*60,seconds:xt*24*60*60,milliseconds:xt*24*60*60*1e3},...Io},Et=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],xc=Et.slice(0).reverse();function Ke(t,e,n=!1){const s={values:n?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy,matrix:e.matrix||t.matrix};return new ne(s)}function xo(t,e){let n=e.milliseconds??0;for(const s of xc.slice(1))e[s]&&(n+=e[s]*t[s].milliseconds);return n}function ni(t,e){const n=xo(t,e)<0?-1:1;Et.reduceRight((s,r)=>{if(G(e[r]))return s;if(s){const i=e[s]*n,o=t[r][s],a=Math.floor(i/o);e[r]+=a*n,e[s]-=a*o*n}return r},null),Et.reduce((s,r)=>{if(G(e[r]))return s;if(s){const i=e[s]%1;e[s]-=i,e[r]+=i*t[s][r]}return r},null)}function si(t){const e={};for(const[n,s]of Object.entries(t))s!==0&&(e[n]=s);return e}class ne{constructor(e){const n=e.conversionAccuracy==="longterm"||!1;let s=n?Ic:Sc;e.matrix&&(s=e.matrix),this.values=e.values,this.loc=e.loc||ie.create(),this.conversionAccuracy=n?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=s,this.isLuxonDuration=!0}static fromMillis(e,n){return ne.fromObject({milliseconds:e},n)}static fromObject(e,n={}){if(e==null||typeof e!="object")throw new ke(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new ne({values:Gn(e,ne.normalizeUnit),loc:ie.fromObject(n),conversionAccuracy:n.conversionAccuracy,matrix:n.matrix})}static fromDurationLike(e){if(dt(e))return ne.fromMillis(e);if(ne.isDuration(e))return e;if(typeof e=="object")return ne.fromObject(e);throw new ke(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,n){const[s]=Ec(e);return s?ne.fromObject(s,n):ne.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,n){const[s]=Oc(e);return s?ne.fromObject(s,n):ne.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,n=null){if(!e)throw new ke("need to specify a reason the Duration is invalid");const s=e instanceof Ue?e:new Ue(e,n);if(de.throwOnInvalid)throw new tl(s);return new ne({invalid:s})}static normalizeUnit(e){const n={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(!n)throw new Mi(e);return n}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,n={}){const s={...n,floor:n.round!==!1&&n.floor!==!1};return this.isValid?Re.create(this.loc,s).formatDurationFromString(this,e):ti}toHuman(e={}){if(!this.isValid)return ti;const n=e.showZeros!==!1,s=Et.map(r=>{const i=this.values[r];return G(i)||i===0&&!n?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:r.slice(0,-1)}).format(i)}).filter(r=>r);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(s)}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+=nr(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;const n=this.toMillis();return n<0||n>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},V.fromMillis(n,{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?xo(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;const n=ne.fromDurationLike(e),s={};for(const r of Et)(jt(n.values,r)||jt(this.values,r))&&(s[r]=n.get(r)+this.get(r));return Ke(this,{values:s},!0)}minus(e){if(!this.isValid)return this;const n=ne.fromDurationLike(e);return this.plus(n.negate())}mapUnits(e){if(!this.isValid)return this;const n={};for(const s of Object.keys(this.values))n[s]=mo(e(this.values[s],s));return Ke(this,{values:n},!0)}get(e){return this[ne.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const n={...this.values,...Gn(e,ne.normalizeUnit)};return Ke(this,{values:n})}reconfigure({locale:e,numberingSystem:n,conversionAccuracy:s,matrix:r}={}){const o={loc:this.loc.clone({locale:e,numberingSystem:n}),matrix:r,conversionAccuracy:s};return Ke(this,o)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;const e=this.toObject();return ni(this.matrix,e),Ke(this,{values:e},!0)}rescale(){if(!this.isValid)return this;const e=si(this.normalize().shiftToAll().toObject());return Ke(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(o=>ne.normalizeUnit(o));const n={},s={},r=this.toObject();let i;for(const o of Et)if(e.indexOf(o)>=0){i=o;let a=0;for(const c in s)a+=this.matrix[c][o]*s[c],s[c]=0;dt(r[o])&&(a+=r[o]);const l=Math.trunc(a);n[o]=l,s[o]=(a*1e3-l*1e3)/1e3}else dt(r[o])&&(s[o]=r[o]);for(const o in s)s[o]!==0&&(n[i]+=o===i?s[o]:s[o]/this.matrix[i][o]);return ni(this.matrix,n),Ke(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;const e={};for(const n of Object.keys(this.values))e[n]=this.values[n]===0?0:-this.values[n];return Ke(this,{values:e},!0)}removeZeros(){if(!this.isValid)return this;const e=si(this.values);return Ke(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 n(s,r){return s===void 0||s===0?r===void 0||r===0:s===r}for(const s of Et)if(!n(this.values[s],e.values[s]))return!1;return!0}}const At="Invalid Interval";function Ac(t,e){return!t||!t.isValid?ue.invalid("missing or invalid start"):!e||!e.isValid?ue.invalid("missing or invalid end"):e<t?ue.invalid("end before start",`The end of an interval must be after its start, but you had start=${t.toISO()} and end=${e.toISO()}`):null}class ue{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,n=null){if(!e)throw new ke("need to specify a reason the Interval is invalid");const s=e instanceof Ue?e:new Ue(e,n);if(de.throwOnInvalid)throw new el(s);return new ue({invalid:s})}static fromDateTimes(e,n){const s=Qt(e),r=Qt(n),i=Ac(s,r);return i??new ue({start:s,end:r})}static after(e,n){const s=ne.fromDurationLike(n),r=Qt(e);return ue.fromDateTimes(r,r.plus(s))}static before(e,n){const s=ne.fromDurationLike(n),r=Qt(e);return ue.fromDateTimes(r.minus(s),r)}static fromISO(e,n){const[s,r]=(e||"").split("/",2);if(s&&r){let i,o;try{i=V.fromISO(s,n),o=i.isValid}catch{o=!1}let a,l;try{a=V.fromISO(r,n),l=a.isValid}catch{l=!1}if(o&&l)return ue.fromDateTimes(i,a);if(o){const c=ne.fromISO(r,n);if(c.isValid)return ue.after(i,c)}else if(l){const c=ne.fromISO(s,n);if(c.isValid)return ue.before(a,c)}}return ue.invalid("unparsable",`the input "${e}" 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",n){if(!this.isValid)return NaN;const s=this.start.startOf(e,n);let r;return n?.useLocaleWeeks?r=this.end.reconfigure({locale:s.locale}):r=this.end,r=r.startOf(e,n),Math.floor(r.diff(s,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:e,end:n}={}){return this.isValid?ue.fromDateTimes(e||this.s,n||this.e):this}splitAt(...e){if(!this.isValid)return[];const n=e.map(Qt).filter(o=>this.contains(o)).sort((o,a)=>o.toMillis()-a.toMillis()),s=[];let{s:r}=this,i=0;for(;r<this.e;){const o=n[i]||this.e,a=+o>+this.e?this.e:o;s.push(ue.fromDateTimes(r,a)),r=a,i+=1}return s}splitBy(e){const n=ne.fromDurationLike(e);if(!this.isValid||!n.isValid||n.as("milliseconds")===0)return[];let{s}=this,r=1,i;const o=[];for(;s<this.e;){const a=this.start.plus(n.mapUnits(l=>l*r));i=+a>+this.e?this.e:a,o.push(ue.fromDateTimes(s,i)),s=i,r+=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(e){if(!this.isValid)return this;const n=this.s>e.s?this.s:e.s,s=this.e<e.e?this.e:e.e;return n>=s?null:ue.fromDateTimes(n,s)}union(e){if(!this.isValid)return this;const n=this.s<e.s?this.s:e.s,s=this.e>e.e?this.e:e.e;return ue.fromDateTimes(n,s)}static merge(e){const[n,s]=e.sort((r,i)=>r.s-i.s).reduce(([r,i],o)=>i?i.overlaps(o)||i.abutsStart(o)?[r,i.union(o)]:[r.concat([i]),o]:[r,o],[[],null]);return s&&n.push(s),n}static xor(e){let n=null,s=0;const r=[],i=e.map(l=>[{time:l.s,type:"s"},{time:l.e,type:"e"}]),o=Array.prototype.concat(...i),a=o.sort((l,c)=>l.time-c.time);for(const l of a)s+=l.type==="s"?1:-1,s===1?n=l.time:(n&&+n!=+l.time&&r.push(ue.fromDateTimes(n,l.time)),n=null);return ue.merge(r)}difference(...e){return ue.xor([this].concat(e)).map(n=>this.intersection(n)).filter(n=>n&&!n.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:At}[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=qn,n={}){return this.isValid?Re.create(this.s.loc.clone(n),e).formatInterval(this):At}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:At}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:At}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:At}toFormat(e,{separator:n=" – "}={}){return this.isValid?`${this.s.toFormat(e)}${n}${this.e.toFormat(e)}`:At}toDuration(e,n){return this.isValid?this.e.diff(this.s,e,n):ne.invalid(this.invalidReason)}mapEndpoints(e){return ue.fromDateTimes(e(this.s),e(this.e))}}class kn{static hasDST(e=de.defaultZone){const n=V.now().setZone(e).set({month:12});return!e.isUniversal&&n.offset!==n.set({month:6}).offset}static isValidIANAZone(e){return st.isValidZone(e)}static normalizeZone(e){return lt(e,de.defaultZone)}static getStartOfWeek({locale:e=null,locObj:n=null}={}){return(n||ie.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:n=null}={}){return(n||ie.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:n=null}={}){return(n||ie.create(e)).getWeekendDays().slice()}static months(e="long",{locale:n=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||ie.create(n,s,i)).months(e)}static monthsFormat(e="long",{locale:n=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||ie.create(n,s,i)).months(e,!0)}static weekdays(e="long",{locale:n=null,numberingSystem:s=null,locObj:r=null}={}){return(r||ie.create(n,s,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:n=null,numberingSystem:s=null,locObj:r=null}={}){return(r||ie.create(n,s,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return ie.create(e).meridiems()}static eras(e="short",{locale:n=null}={}){return ie.create(n,null,"gregory").eras(e)}static features(){return{relative:uo(),localeWeek:fo()}}}function ri(t,e){const n=r=>r.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),s=n(e)-n(t);return Math.floor(ne.fromMillis(s).as("days"))}function Nc(t,e,n){const s=[["years",(l,c)=>c.year-l.year],["quarters",(l,c)=>c.quarter-l.quarter+(c.year-l.year)*4],["months",(l,c)=>c.month-l.month+(c.year-l.year)*12],["weeks",(l,c)=>{const d=ri(l,c);return(d-d%7)/7}],["days",ri]],r={},i=t;let o,a;for(const[l,c]of s)n.indexOf(l)>=0&&(o=l,r[l]=c(t,e),a=i.plus(r),a>e?(r[l]--,t=i.plus(r),t>e&&(a=t,r[l]--,t=i.plus(r))):t=a);return[t,r,a,o]}function Dc(t,e,n,s){let[r,i,o,a]=Nc(t,e,n);const l=e-r,c=n.filter(p=>["hours","minutes","seconds","milliseconds"].indexOf(p)>=0);c.length===0&&(o<e&&(o=r.plus({[a]:1})),o!==r&&(i[a]=(i[a]||0)+l/(o-r)));const d=ne.fromObject(i,s);return c.length>0?ne.fromMillis(l,s).shiftTo(...c).plus(d):d}const Cc="missing Intl.DateTimeFormat.formatToParts support";function re(t,e=n=>n){return{regex:t,deser:([n])=>e(kl(n))}}const Fc=" ",Ao=`[ ${Fc}]`,No=new RegExp(Ao,"g");function $c(t){return t.replace(/\./g,"\\.?").replace(No,Ao)}function ii(t){return t.replace(/\./g,"").replace(No," ").toLowerCase()}function Ve(t,e){return t===null?null:{regex:RegExp(t.map($c).join("|")),deser:([n])=>t.findIndex(s=>ii(n)===ii(s))+e}}function oi(t,e){return{regex:t,deser:([,n,s])=>ss(n,s),groups:e}}function bn(t){return{regex:t,deser:([e])=>e}}function Mc(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Pc(t,e){const n=Le(e),s=Le(e,"{2}"),r=Le(e,"{3}"),i=Le(e,"{4}"),o=Le(e,"{6}"),a=Le(e,"{1,2}"),l=Le(e,"{1,3}"),c=Le(e,"{1,6}"),d=Le(e,"{1,9}"),p=Le(e,"{2,4}"),u=Le(e,"{4,6}"),f=y=>({regex:RegExp(Mc(y.val)),deser:([E])=>E,literal:!0}),k=(y=>{if(t.literal)return f(y);switch(y.val){case"G":return Ve(e.eras("short"),0);case"GG":return Ve(e.eras("long"),0);case"y":return re(c);case"yy":return re(p,Zs);case"yyyy":return re(i);case"yyyyy":return re(u);case"yyyyyy":return re(o);case"M":return re(a);case"MM":return re(s);case"MMM":return Ve(e.months("short",!0),1);case"MMMM":return Ve(e.months("long",!0),1);case"L":return re(a);case"LL":return re(s);case"LLL":return Ve(e.months("short",!1),1);case"LLLL":return Ve(e.months("long",!1),1);case"d":return re(a);case"dd":return re(s);case"o":return re(l);case"ooo":return re(r);case"HH":return re(s);case"H":return re(a);case"hh":return re(s);case"h":return re(a);case"mm":return re(s);case"m":return re(a);case"q":return re(a);case"qq":return re(s);case"s":return re(a);case"ss":return re(s);case"S":return re(l);case"SSS":return re(r);case"u":return bn(d);case"uu":return bn(a);case"uuu":return re(n);case"a":return Ve(e.meridiems(),0);case"kkkk":return re(i);case"kk":return re(p,Zs);case"W":return re(a);case"WW":return re(s);case"E":case"c":return re(n);case"EEE":return Ve(e.weekdays("short",!1),1);case"EEEE":return Ve(e.weekdays("long",!1),1);case"ccc":return Ve(e.weekdays("short",!0),1);case"cccc":return Ve(e.weekdays("long",!0),1);case"Z":case"ZZ":return oi(new RegExp(`([+-]${a.source})(?::(${s.source}))?`),2);case"ZZZ":return oi(new RegExp(`([+-]${a.source})(${s.source})?`),2);case"z":return bn(/[a-z_+-/]{1,256}?/i);case" ":return bn(/[^\S\n\r]/);default:return f(y)}})(t)||{invalidReason:Cc};return k.token=t,k}const Lc={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 Vc(t,e,n){const{type:s,value:r}=t;if(s==="literal"){const l=/^\s+$/.test(r);return{literal:!l,val:l?" ":r}}const i=e[s];let o=s;s==="hour"&&(e.hour12!=null?o=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?o="hour12":o="hour24":o=n.hour12?"hour12":"hour24");let a=Lc[o];if(typeof a=="object"&&(a=a[i]),a)return{literal:!1,val:a}}function Uc(t){return[`^${t.map(n=>n.regex).reduce((n,s)=>`${n}(${s.source})`,"")}$`,t]}function Wc(t,e,n){const s=t.match(e);if(s){const r={};let i=1;for(const o in n)if(jt(n,o)){const a=n[o],l=a.groups?a.groups+1:1;!a.literal&&a.token&&(r[a.token.val[0]]=a.deser(s.slice(i,i+l))),i+=l}return[s,r]}else return[s,{}]}function jc(t){const e=i=>{switch(i){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}};let n=null,s;return G(t.z)||(n=st.create(t.z)),G(t.Z)||(n||(n=new Te(t.Z)),s=t.Z),G(t.q)||(t.M=(t.q-1)*3+1),G(t.h)||(t.h<12&&t.a===1?t.h+=12:t.h===12&&t.a===0&&(t.h=0)),t.G===0&&t.y&&(t.y=-t.y),G(t.u)||(t.S=tr(t.u)),[Object.keys(t).reduce((i,o)=>{const a=e(o);return a&&(i[a]=t[o]),i},{}),n,s]}let ps=null;function Zc(){return ps||(ps=V.fromMillis(1555555555555)),ps}function zc(t,e){if(t.literal)return t;const n=Re.macroTokenToFormatOpts(t.val),s=$o(n,e);return s==null||s.includes(void 0)?t:s}function Do(t,e){return Array.prototype.concat(...t.map(n=>zc(n,e)))}class Co{constructor(e,n){if(this.locale=e,this.format=n,this.tokens=Do(Re.parseFormat(n),e),this.units=this.tokens.map(s=>Pc(s,e)),this.disqualifyingUnit=this.units.find(s=>s.invalidReason),!this.disqualifyingUnit){const[s,r]=Uc(this.units);this.regex=RegExp(s,"i"),this.handlers=r}}explainFromTokens(e){if(this.isValid){const[n,s]=Wc(e,this.regex,this.handlers),[r,i,o]=s?jc(s):[null,null,void 0];if(jt(s,"a")&&jt(s,"H"))throw new Ct("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:this.tokens,regex:this.regex,rawMatches:n,matches:s,result:r,zone:i,specificOffset:o}}else return{input:e,tokens:this.tokens,invalidReason:this.invalidReason}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}}function Fo(t,e,n){return new Co(t,n).explainFromTokens(e)}function qc(t,e,n){const{result:s,zone:r,specificOffset:i,invalidReason:o}=Fo(t,e,n);return[s,r,i,o]}function $o(t,e){if(!t)return null;const s=Re.create(e,t).dtFormatter(Zc()),r=s.formatToParts(),i=s.resolvedOptions();return r.map(o=>Vc(o,t,i))}const ys="Invalid DateTime",ai=864e13;function tn(t){return new Ue("unsupported zone",`the zone "${t.name}" is not supported`)}function gs(t){return t.weekData===null&&(t.weekData=Bn(t.c)),t.weekData}function ws(t){return t.localWeekData===null&&(t.localWeekData=Bn(t.c,t.loc.getMinDaysInFirstWeek(),t.loc.getStartOfWeek())),t.localWeekData}function yt(t,e){const n={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new V({...n,...e,old:n})}function Mo(t,e,n){let s=t-e*60*1e3;const r=n.offset(s);if(e===r)return[s,e];s-=(r-e)*60*1e3;const i=n.offset(s);return r===i?[s,r]:[t-Math.min(r,i)*60*1e3,Math.max(r,i)]}function Rn(t,e){t+=e*60*1e3;const n=new Date(t);return{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate(),hour:n.getUTCHours(),minute:n.getUTCMinutes(),second:n.getUTCSeconds(),millisecond:n.getUTCMilliseconds()}}function xn(t,e,n){return Mo(ns(t),e,n)}function li(t,e){const n=t.o,s=t.c.year+Math.trunc(e.years),r=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,i={...t.c,year:s,month:r,day:Math.min(t.c.day,Hn(s,r))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},o=ne.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),a=ns(i);let[l,c]=Mo(a,n,t.zone);return o!==0&&(l+=o,c=t.zone.offset(l)),{ts:l,o:c}}function Nt(t,e,n,s,r,i){const{setZone:o,zone:a}=n;if(t&&Object.keys(t).length!==0||e){const l=e||a,c=V.fromObject(t,{...n,zone:l,specificOffset:i});return o?c:c.setZone(a)}else return V.invalid(new Ue("unparsable",`the input "${r}" can't be parsed as ${s}`))}function Tn(t,e,n=!0){return t.isValid?Re.create(ie.create("en-US"),{allowZ:n,forceSimple:!0}).formatDateTimeFromString(t,e):null}function _s(t,e,n){const s=t.c.year>9999||t.c.year<0;let r="";if(s&&t.c.year>=0&&(r+="+"),r+=me(t.c.year,s?6:4),n==="year")return r;if(e){if(r+="-",r+=me(t.c.month),n==="month")return r;r+="-"}else if(r+=me(t.c.month),n==="month")return r;return r+=me(t.c.day),r}function ci(t,e,n,s,r,i,o){let a=!n||t.c.millisecond!==0||t.c.second!==0,l="";switch(o){case"day":case"month":case"year":break;default:if(l+=me(t.c.hour),o==="hour")break;if(e){if(l+=":",l+=me(t.c.minute),o==="minute")break;a&&(l+=":",l+=me(t.c.second))}else{if(l+=me(t.c.minute),o==="minute")break;a&&(l+=me(t.c.second))}if(o==="second")break;a&&(!s||t.c.millisecond!==0)&&(l+=".",l+=me(t.c.millisecond,3))}return r&&(t.isOffsetFixed&&t.offset===0&&!i?l+="Z":t.o<0?(l+="-",l+=me(Math.trunc(-t.o/60)),l+=":",l+=me(Math.trunc(-t.o%60))):(l+="+",l+=me(Math.trunc(t.o/60)),l+=":",l+=me(Math.trunc(t.o%60)))),i&&(l+="["+t.zone.ianaName+"]"),l}const Po={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Bc={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Hc={ordinal:1,hour:0,minute:0,second:0,millisecond:0},An=["year","month","day","hour","minute","second","millisecond"],Gc=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Yc=["year","ordinal","hour","minute","second","millisecond"];function Nn(t){const e={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"}[t.toLowerCase()];if(!e)throw new Mi(t);return e}function ui(t){switch(t.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return Nn(t)}}function Jc(t){if(nn===void 0&&(nn=de.now()),t.type!=="iana")return t.offset(nn);const e=t.name;let n=zs.get(e);return n===void 0&&(n=t.offset(nn),zs.set(e,n)),n}function di(t,e){const n=lt(e.zone,de.defaultZone);if(!n.isValid)return V.invalid(tn(n));const s=ie.fromObject(e);let r,i;if(G(t.year))r=de.now();else{for(const l of An)G(t[l])&&(t[l]=Po[l]);const o=lo(t)||co(t);if(o)return V.invalid(o);const a=Jc(n);[r,i]=xn(t,a,n)}return new V({ts:r,zone:n,loc:s,o:i})}function fi(t,e,n){const s=G(n.round)?!0:n.round,r=G(n.rounding)?"trunc":n.rounding,i=(a,l)=>(a=nr(a,s||n.calendary?0:2,n.calendary?"round":r),e.loc.clone(n).relFormatter(n).format(a,l)),o=a=>n.calendary?e.hasSame(t,a)?0:e.startOf(a).diff(t.startOf(a),a).get(a):e.diff(t,a).get(a);if(n.unit)return i(o(n.unit),n.unit);for(const a of n.units){const l=o(a);if(Math.abs(l)>=1)return i(l,a)}return i(t>e?-0:0,n.units[n.units.length-1])}function hi(t){let e={},n;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],n=Array.from(t).slice(0,t.length-1)):n=Array.from(t),[e,n]}let nn;const zs=new Map;class V{constructor(e){const n=e.zone||de.defaultZone;let s=e.invalid||(Number.isNaN(e.ts)?new Ue("invalid input"):null)||(n.isValid?null:tn(n));this.ts=G(e.ts)?de.now():e.ts;let r=null,i=null;if(!s)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(n))[r,i]=[e.old.c,e.old.o];else{const a=dt(e.o)&&!e.old?e.o:n.offset(this.ts);r=Rn(this.ts,a),s=Number.isNaN(r.year)?new Ue("invalid input"):null,r=s?null:r,i=s?null:a}this._zone=n,this.loc=e.loc||ie.create(),this.invalid=s,this.weekData=null,this.localWeekData=null,this.c=r,this.o=i,this.isLuxonDateTime=!0}static now(){return new V({})}static local(){const[e,n]=hi(arguments),[s,r,i,o,a,l,c]=n;return di({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static utc(){const[e,n]=hi(arguments),[s,r,i,o,a,l,c]=n;return e.zone=Te.utcInstance,di({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static fromJSDate(e,n={}){const s=Il(e)?e.valueOf():NaN;if(Number.isNaN(s))return V.invalid("invalid input");const r=lt(n.zone,de.defaultZone);return r.isValid?new V({ts:s,zone:r,loc:ie.fromObject(n)}):V.invalid(tn(r))}static fromMillis(e,n={}){if(dt(e))return e<-ai||e>ai?V.invalid("Timestamp out of range"):new V({ts:e,zone:lt(n.zone,de.defaultZone),loc:ie.fromObject(n)});throw new ke(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,n={}){if(dt(e))return new V({ts:e*1e3,zone:lt(n.zone,de.defaultZone),loc:ie.fromObject(n)});throw new ke("fromSeconds requires a numerical input")}static fromObject(e,n={}){e=e||{};const s=lt(n.zone,de.defaultZone);if(!s.isValid)return V.invalid(tn(s));const r=ie.fromObject(n),i=Gn(e,ui),{minDaysInFirstWeek:o,startOfWeek:a}=Jr(i,r),l=de.now(),c=G(n.specificOffset)?s.offset(l):n.specificOffset,d=!G(i.ordinal),p=!G(i.year),u=!G(i.month)||!G(i.day),f=p||u,g=i.weekYear||i.weekNumber;if((f||d)&&g)throw new Ct("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(u&&d)throw new Ct("Can't mix ordinal dates with month/day");const k=g||i.weekday&&!f;let y,E,w=Rn(l,c);k?(y=Gc,E=Bc,w=Bn(w,o,a)):d?(y=Yc,E=Hc,w=ms(w)):(y=An,E=Po);let A=!1;for(const h of y){const x=i[h];G(x)?A?i[h]=E[h]:i[h]=w[h]:A=!0}const O=k?Rl(i,o,a):d?Tl(i):lo(i),_=O||co(i);if(_)return V.invalid(_);const I=k?Gr(i,o,a):d?Yr(i):i,[j,v]=xn(I,c,s),U=new V({ts:j,zone:s,o:v,loc:r});return i.weekday&&f&&e.weekday!==U.weekday?V.invalid("mismatched weekday",`you can't specify both a weekday of ${i.weekday} and a date of ${U.toISO()}`):U.isValid?U:V.invalid(U.invalid)}static fromISO(e,n={}){const[s,r]=gc(e);return Nt(s,r,n,"ISO 8601",e)}static fromRFC2822(e,n={}){const[s,r]=wc(e);return Nt(s,r,n,"RFC 2822",e)}static fromHTTP(e,n={}){const[s,r]=_c(e);return Nt(s,r,n,"HTTP",n)}static fromFormat(e,n,s={}){if(G(e)||G(n))throw new ke("fromFormat requires an input string and a format");const{locale:r=null,numberingSystem:i=null}=s,o=ie.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0}),[a,l,c,d]=qc(o,e,n);return d?V.invalid(d):Nt(a,l,s,`format ${n}`,e,c)}static fromString(e,n,s={}){return V.fromFormat(e,n,s)}static fromSQL(e,n={}){const[s,r]=Tc(e);return Nt(s,r,n,"SQL",e)}static invalid(e,n=null){if(!e)throw new ke("need to specify a reason the DateTime is invalid");const s=e instanceof Ue?e:new Ue(e,n);if(de.throwOnInvalid)throw new Xa(s);return new V({invalid:s})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,n={}){const s=$o(e,ie.fromObject(n));return s?s.map(r=>r?r.val:null).join(""):null}static expandFormat(e,n={}){return Do(Re.parseFormat(e),ie.fromObject(n)).map(r=>r.val).join("")}static resetCache(){nn=void 0,zs.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?gs(this).weekYear:NaN}get weekNumber(){return this.isValid?gs(this).weekNumber:NaN}get weekday(){return this.isValid?gs(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?ws(this).weekday:NaN}get localWeekNumber(){return this.isValid?ws(this).weekNumber:NaN}get localWeekYear(){return this.isValid?ws(this).weekYear:NaN}get ordinal(){return this.isValid?ms(this.c).ordinal:NaN}get monthShort(){return this.isValid?kn.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?kn.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?kn.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?kn.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];const e=864e5,n=6e4,s=ns(this.c),r=this.zone.offset(s-e),i=this.zone.offset(s+e),o=this.zone.offset(s-r*n),a=this.zone.offset(s-i*n);if(o===a)return[this];const l=s-o*n,c=s-a*n,d=Rn(l,o),p=Rn(c,a);return d.hour===p.hour&&d.minute===p.minute&&d.second===p.second&&d.millisecond===p.millisecond?[yt(this,{ts:l}),yt(this,{ts:c})]:[this]}get isInLeapYear(){return gn(this.year)}get daysInMonth(){return Hn(this.year,this.month)}get daysInYear(){return this.isValid?$t(this.year):NaN}get weeksInWeekYear(){return this.isValid?fn(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?fn(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){const{locale:n,numberingSystem:s,calendar:r}=Re.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:n,numberingSystem:s,outputCalendar:r}}toUTC(e=0,n={}){return this.setZone(Te.instance(e),n)}toLocal(){return this.setZone(de.defaultZone)}setZone(e,{keepLocalTime:n=!1,keepCalendarTime:s=!1}={}){if(e=lt(e,de.defaultZone),e.equals(this.zone))return this;if(e.isValid){let r=this.ts;if(n||s){const i=e.offset(this.ts),o=this.toObject();[r]=xn(o,i,e)}return yt(this,{ts:r,zone:e})}else return V.invalid(tn(e))}reconfigure({locale:e,numberingSystem:n,outputCalendar:s}={}){const r=this.loc.clone({locale:e,numberingSystem:n,outputCalendar:s});return yt(this,{loc:r})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const n=Gn(e,ui),{minDaysInFirstWeek:s,startOfWeek:r}=Jr(n,this.loc),i=!G(n.weekYear)||!G(n.weekNumber)||!G(n.weekday),o=!G(n.ordinal),a=!G(n.year),l=!G(n.month)||!G(n.day),c=a||l,d=n.weekYear||n.weekNumber;if((c||o)&&d)throw new Ct("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&o)throw new Ct("Can't mix ordinal dates with month/day");let p;i?p=Gr({...Bn(this.c,s,r),...n},s,r):G(n.ordinal)?(p={...this.toObject(),...n},G(n.day)&&(p.day=Math.min(Hn(p.year,p.month),p.day))):p=Yr({...ms(this.c),...n});const[u,f]=xn(p,this.o,this.zone);return yt(this,{ts:u,o:f})}plus(e){if(!this.isValid)return this;const n=ne.fromDurationLike(e);return yt(this,li(this,n))}minus(e){if(!this.isValid)return this;const n=ne.fromDurationLike(e).negate();return yt(this,li(this,n))}startOf(e,{useLocaleWeeks:n=!1}={}){if(!this.isValid)return this;const s={},r=ne.normalizeUnit(e);switch(r){case"years":s.month=1;case"quarters":case"months":s.day=1;case"weeks":case"days":s.hour=0;case"hours":s.minute=0;case"minutes":s.second=0;case"seconds":s.millisecond=0;break}if(r==="weeks")if(n){const i=this.loc.getStartOfWeek(),{weekday:o}=this;o<i&&(s.weekNumber=this.weekNumber-1),s.weekday=i}else s.weekday=1;if(r==="quarters"){const i=Math.ceil(this.month/3);s.month=(i-1)*3+1}return this.set(s)}endOf(e,n){return this.isValid?this.plus({[e]:1}).startOf(e,n).minus(1):this}toFormat(e,n={}){return this.isValid?Re.create(this.loc.redefaultToEN(n)).formatDateTimeFromString(this,e):ys}toLocaleString(e=qn,n={}){return this.isValid?Re.create(this.loc.clone(n),e).formatDateTime(this):ys}toLocaleParts(e={}){return this.isValid?Re.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:n=!1,suppressMilliseconds:s=!1,includeOffset:r=!0,extendedZone:i=!1,precision:o="milliseconds"}={}){if(!this.isValid)return null;o=Nn(o);const a=e==="extended";let l=_s(this,a,o);return An.indexOf(o)>=3&&(l+="T"),l+=ci(this,a,n,s,r,i,o),l}toISODate({format:e="extended",precision:n="day"}={}){return this.isValid?_s(this,e==="extended",Nn(n)):null}toISOWeekDate(){return Tn(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:n=!1,includeOffset:s=!0,includePrefix:r=!1,extendedZone:i=!1,format:o="extended",precision:a="milliseconds"}={}){return this.isValid?(a=Nn(a),(r&&An.indexOf(a)>=3?"T":"")+ci(this,o==="extended",n,e,s,i,a)):null}toRFC2822(){return Tn(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return Tn(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?_s(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:n=!1,includeOffsetSpace:s=!0}={}){let r="HH:mm:ss.SSS";return(n||e)&&(s&&(r+=" "),n?r+="z":e&&(r+="ZZ")),Tn(this,r,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():ys}[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{};const n={...this.c};return e.includeConfig&&(n.outputCalendar=this.outputCalendar,n.numberingSystem=this.loc.numberingSystem,n.locale=this.loc.locale),n}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,n="milliseconds",s={}){if(!this.isValid||!e.isValid)return ne.invalid("created by diffing an invalid DateTime");const r={locale:this.locale,numberingSystem:this.numberingSystem,...s},i=xl(n).map(ne.normalizeUnit),o=e.valueOf()>this.valueOf(),a=o?this:e,l=o?e:this,c=Dc(a,l,i,r);return o?c.negate():c}diffNow(e="milliseconds",n={}){return this.diff(V.now(),e,n)}until(e){return this.isValid?ue.fromDateTimes(this,e):this}hasSame(e,n,s){if(!this.isValid)return!1;const r=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(n,s)<=r&&r<=i.endOf(n,s)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;const n=e.base||V.fromObject({},{zone:this.zone}),s=e.padding?this<n?-e.padding:e.padding:0;let r=["years","months","days","hours","minutes","seconds"],i=e.unit;return Array.isArray(e.unit)&&(r=e.unit,i=void 0),fi(n,this.plus(s),{...e,numeric:"always",units:r,unit:i})}toRelativeCalendar(e={}){return this.isValid?fi(e.base||V.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(V.isDateTime))throw new ke("min requires all arguments be DateTimes");return Qr(e,n=>n.valueOf(),Math.min)}static max(...e){if(!e.every(V.isDateTime))throw new ke("max requires all arguments be DateTimes");return Qr(e,n=>n.valueOf(),Math.max)}static fromFormatExplain(e,n,s={}){const{locale:r=null,numberingSystem:i=null}=s,o=ie.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});return Fo(o,e,n)}static fromStringExplain(e,n,s={}){return V.fromFormatExplain(e,n,s)}static buildFormatParser(e,n={}){const{locale:s=null,numberingSystem:r=null}=n,i=ie.fromOpts({locale:s,numberingSystem:r,defaultToEN:!0});return new Co(i,e)}static fromFormatParser(e,n,s={}){if(G(e)||G(n))throw new ke("fromFormatParser requires an input string and a format parser");const{locale:r=null,numberingSystem:i=null}=s,o=ie.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});if(!o.equals(n.locale))throw new ke(`fromFormatParser called with a locale of ${o}, but the format parser was created for ${n.locale}`);const{result:a,zone:l,specificOffset:c,invalidReason:d}=n.explainFromTokens(e);return d?V.invalid(d):Nt(a,l,s,`format ${n.format}`,e,c)}static get DATE_SHORT(){return qn}static get DATE_MED(){return Pi}static get DATE_MED_WITH_WEEKDAY(){return nl}static get DATE_FULL(){return Li}static get DATE_HUGE(){return Vi}static get TIME_SIMPLE(){return Ui}static get TIME_WITH_SECONDS(){return Wi}static get TIME_WITH_SHORT_OFFSET(){return ji}static get TIME_WITH_LONG_OFFSET(){return Zi}static get TIME_24_SIMPLE(){return zi}static get TIME_24_WITH_SECONDS(){return qi}static get TIME_24_WITH_SHORT_OFFSET(){return Bi}static get TIME_24_WITH_LONG_OFFSET(){return Hi}static get DATETIME_SHORT(){return Gi}static get DATETIME_SHORT_WITH_SECONDS(){return Yi}static get DATETIME_MED(){return Ji}static get DATETIME_MED_WITH_SECONDS(){return Qi}static get DATETIME_MED_WITH_WEEKDAY(){return sl}static get DATETIME_FULL(){return Ki}static get DATETIME_FULL_WITH_SECONDS(){return Xi}static get DATETIME_HUGE(){return eo}static get DATETIME_HUGE_WITH_SECONDS(){return to}}function Qt(t){if(V.isDateTime(t))return t;if(t&&t.valueOf&&dt(t.valueOf()))return V.fromJSDate(t);if(t&&typeof t=="object")return V.fromObject(t);throw new ke(`Unknown datetime argument: ${t}, of type ${typeof t}`)}const Qc=(t,e)=>{const n={};if(t.includeFields){const s=e.collections[t.collection];if(!s)return pn(ve());t.includeFields.forEach(r=>{const i=s.fields.find(o=>o.name===r);i?n[r]=Lo(i)?.nullable():n[r]=ve()})}return qe({Collection_Path:Tt(Ie()),...n})},Kc=(t,e,n,s)=>{let r=qe({}).catchall(Qc(t,e)),i;if(!s&&n){const o=We(t,n);i=Kt(o.admin?.skipFormRequiredValidation)}return(!t.required||i)&&(r=r.optional()),r},Xc=()=>ve().refine(t=>t===null||t&&(t.seconds!==void 0&&t.nanoseconds!==void 0||t._seconds!==void 0&&t._nanoseconds!==void 0),{message:"Must be a valid date"}),Lo=(t,e,n)=>{let s;const r=`${Kt(t.description)}
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
- `||"";let i,o,a;if(!n&&e){const l=We(t,e);i=l.admin?.condition?.form!==void 0&&!Kt(l.admin.condition.form),o=Kt(l.admin?.skipFormRequiredValidation),a=Kt(l.admin?.image)}switch(t.type){case"String":s=Ie(),t.length&&(s=s.length(t.length,`Must be ${t.length} character(s) long`)),t.minlength&&(s=s.min(t.minlength,`Must contain at least ${t.minlength} character(s)`)),t.maxlength&&(s=s.max(t.maxlength,`Must contain at most ${t.maxlength} character(s)`)),t.email?s=s.email("Must be a valid email address"):t.uuid?s=Oe([s.uuid("Must be a valid UUID"),Ee("")]):t.url?s=Oe([s.url("Must be a valid URL"),Ee("")]):t.emoji?s=Oe([s.emoji("Must be a valid emoji"),Ee("")]):t.ip?s=Oe([s.ip("Must be a valid IP address"),Ee("")]):t.pattern&&(!n&&a?s=Oe([s.regex(new RegExp(t.pattern)),s.regex(/^blob:/),Ee("")],{message:"Must be a valid value"}):s=Oe([s.regex(new RegExp(t.pattern),"Must be a valid value"),Ee("")])),t.values&&(s=Oe([Zn(t.values,{message:`Must be one of the following values: ${t.values.join(", ")}`}),us()])),r&&(s=s.describe(r.trim()));break;case"Boolean":s=an(),r&&(s=s.describe(r.trim()));break;case"Number":t.autoIncrement?s=Oe([us(),_t().int()],{message:"Must be a valid number"}):(s=_t({message:"Must be a valid number"}),t.min&&(s=s.min(t.min,`Must be greater than or equal to ${t.min}`)),t.max&&(s=s.max(t.max,`Must be less than or equal to ${t.max}`)),t.decimal?n?s=s.describe(`${r}Must have ${t.decimal} decimal places`):s=s.refine(l=>t.decimal?(l.toString().split(".")[1]?.length||0)<=t.decimal:!1,{message:`Must have ${t.decimal} or fewer decimal places`}):s=s.int("Must not have decimal places"),t.values?(n||(s=Oe([s.refine(l=>t.values?.includes(l),{message:`Must be one of the following values: ${t.values.join(", ")}`}),us()])),s=s.describe(`${r}Must be one of the following values: ${t.values.join(", ")}`)):r&&(s=s.describe(r.trim())));break;case"Timestamp":n?(s=qe({seconds:_t(),nanoseconds:_t()}),t.min&&t.max?s=s.describe(`${r}Must be between ${V.fromMillis(t.min).toLocaleString(V.DATE_MED)} and ${V.fromMillis(t.max).toLocaleString(V.DATE_MED)}`):t.min?s=s.describe(`${r}Must be greater than or equal to ${V.fromMillis(t.min).toLocaleString(V.DATE_MED)}`):t.max?s=s.describe(`${r}Must be less than or equal to ${V.fromMillis(t.max).toLocaleString(V.DATE_MED)}`):r&&(s=s.describe(r.trim()))):(s=Xc(),t.min&&(s=s.refine(l=>l.toMillis()>=t.min,{message:`Must be greater than or equal to ${V.fromMillis(t.min).toLocaleString(V.DATE_MED)}`})),t.max&&(s=s.refine(l=>l.toMillis()<=t.max,{message:`Must be less than or equal to ${V.fromMillis(t.max).toLocaleString(V.DATE_MED)}`})));break;case"Array":s=Tt(ve()),t.length&&(s=s.length(t.length,`Must contain ${t.length} item(s)`)),t.minlength?s=s.min(t.minlength,`Must contain at least ${t.minlength} item(s)`):t.required&&!i&&(s=s.nonempty("Must contain at least one item")),t.maxlength&&(s=s.max(t.maxlength,`Must contain at most ${t.maxlength} item(s)`)),t.values?(n||(s=s.refine(l=>{let c=!0;return l.forEach(d=>{t.values&&!t.values.includes(d)&&(c=!1)}),c},{message:`Must only contain the following values: ${t.values.join(", ")}`})),s=s.describe(`${r}Must only contain the following values: ${t.values.join(", ")}`)):r&&(s=s.describe(r.trim())),t.nullable&&(s=s.nullable());break;case"Map":t.required&&!i?n?s=qe({}).catchall(ve()).describe(`${r}Must be an object. Must contain at least one object property.`):s=pn(ve()).refine(l=>l&&typeof l=="object"&&Object.keys(l).length>0,{message:"Must not be an empty value"}):s=qe({}).catchall(ve()).describe(`${r}Must be an object`);break;case"Computed":s=ve()}return(!t.required||i||o)&&(s=s.optional()),s},eu=(t,e,n,s,r)=>{const{auth:i,softDelete:o}=t,a={};t.fields.forEach(c=>{c.type==="Embedding"||s&&c.type==="Computed"||s&&(c.name===o?.archivedField||c.name===o?.timestampField)||(X(c)?(a[c.name]=Kc(c,e,n,s),s?(c.length&&(a[c.name]=a[c.name].describe(`Must contain ${c.length} item(s)`)),c.min&&(a[c.name]=a[c.name].describe(`Must contain at least ${c.min} item(s)`)),c.max&&(a[c.name]=a[c.name].describe(`Must contain at most ${c.max} item(s)`))):(c.length&&(a[c.name]=a[c.name].refine(d=>c.length&&d&&Object.keys(d).length===c.length,{message:`Must contain ${c.length} item(s)`})),c.min&&(a[c.name]=a[c.name].refine(d=>c.min&&d&&Object.keys(d).length>=c.min,{message:`Must contain at least ${c.min} item(s)`})),c.max&&(a[c.name]=a[c.name].refine(d=>c.max&&(!d||Object.keys(d).length<=c.max),{message:`Must contain at most ${c.max} item(s)`})))):a[c.name]=Lo(c,n,s),r&&(a[c.name]=a[c.name].optional()))}),!s&&i&&(a.operation=Oe([Ee("create"),Ee("update"),Ee("delete")]).optional(),a.password=Ie().optional(),a.passwordConfirm=Ie().optional(),Object.values(e.collections).forEach(c=>{a[`auth-${c.labels.collection}`]=an().optional(),a[`operations-${c.labels.collection}`]=Tt(Oe([Ee("Read"),Ee("Create"),Ee("Update"),Ee("Delete")])).optional(),a[`restrict-${c.labels.collection}`]=an().optional(),c.access.attributeRestrictions?.forEach(d=>{a[`attribute-${c.labels.collection}-${d.type}`]=an().optional()}),c.access.entityRestrictions?.restrictions?.forEach(d=>{if(d.type==="Individual"&&(a[`accessible-${c.labels.collection}-${c.labels.collection}`]=qe({}).catchall(ve()).optional()),d.type==="Parent"||d.type==="Parent_Property"){const p=L(c.fields,d.collectionField);a[`accessible-${c.labels.collection}-${p.collection}`]=qe({}).catchall(ve()).optional()}})}));const l=qe(a);return t.allowSchemalessFields?l.passthrough():l.strict()},mi=async(t,e)=>{if(t){const n=await ae(t,[e]);if(!n.valid)throw new Error(n.message)}},hn=async(t,e,n,s,r,i)=>{await mi(s.custom?.preValidate,r);for(const a of s.fields)await mi(a.custom?.preValidate,r);return $i(t,n,i).parse(e),e},or=(t,e,n,s,r,i,o,a,l,c,d,p,u,f,g,k,y,E,w,A,O)=>{const{fields:_}=o;_.filter(h=>"unique"in h&&h.unique).forEach(h=>{t!=="delete"&&(typeof r[h.name]=="string"||typeof r[h.name]=="number")&&(e.set(f(h,r[h.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||")),{id:s,Collection_Path:n}),O&&O.size++)}),_.forEach(h=>{if(mt(h,o,i)){const x=En(h,o,i),R={};r[h.name]!==void 0&&(R[h.name]=r[h.name],X(h)&&(R[`${h.name}_Array`]=r[`${h.name}_Array`])),x.forEach(q=>{r[q.name]!==void 0&&(X(q)?R[`${q.name}_Array`]=r[`${q.name}_Array`]:R[q.name]=r[q.name])}),Object.keys(R).length>0&&(t==="create"&&(R.Collection_Path=n,R.Collection_Path_String=n.join("/"),e.set(u(h),R)),t==="update"&&e.update(u(h),R),t==="delete"&&e.delete(u(h)),O&&O.size++)}});const I=l[o.labels.collection];Object.keys(o.fieldAccessGroups||{}).forEach(h=>{for(const x of I){const R=vn(h,o,x);if(R.length===0)continue;const q=on(h,x.key),Z={};R.forEach(m=>{[m.name,`${m.name}_Array`,`${m.name}_Single`,`${m.name}_Lowercase`].forEach(b=>{r[b]!==void 0&&(Z[b]=r[b])})}),t==="create"&&(Z.Collection_Path||=n,Z.Collection_Path_String=n.join("/"),e.set(g(q),Z),O&&O.size++),t==="update"&&Object.keys(Z).length>0&&(e.update(g(q),Z),O&&O.size++),t==="delete"&&(e.delete(g(q)),O&&O.size++)}});for(const h of I){const x=Oa(h,o),R={...r};x.forEach(q=>{delete R[q.name],delete R[`${q.name}_Array`],delete R[`${q.name}_Single`],delete R[`${q.name}_Lowercase`]}),Object.keys(R).length>0&&(t==="create"&&(R.Collection_Path||=n,R.Collection_Path_String=n.join("/"),e.set(g(h.key),R)),t==="update"&&e.update(g(h.key),R),t==="delete"&&e.delete(g(h.key)),O&&O.size++)}const j=(h,x)=>{let R=1;mt(x,h,i)&&R++,h.fields.forEach(Z=>{mt(Z,h,i)&&JSON.parse(as(En(Z,h,i))).includes(x.name)&&R++});const q=l[h.labels.collection];for(const Z of q)Z.fields.some(m=>m.name===x.name)&&X(x)&&R++;for(const Z of Object.keys(h.fieldAccessGroups||{}))for(const m of q)vn(Z,h,m).some(b=>b.name===x.name)&&X(x)&&R++;return R},v=(h,x,R,q,Z)=>{const m={};m[`${R.name}.${s}`]=p(),m[`${R.name}_Array`]=d(s),m[`${R.name}_Single`]=p(),e.update(k(Z,q),m),mt(R,x,i)&&e.update(y(h,R.name,q),{[`${R.name}.${s}`]:p(),[`${R.name}_Array`]:d(s)}),x.fields.forEach(b=>{mt(b,x,i)&&JSON.parse(as(En(b,x,i))).includes(R.name)&&e.update(y(h,b.name,q),{[`${R.name}_Array`]:d(s)})});const T=l[x.labels.collection];for(const b of T)b.fields.some(F=>F.name===R.name)&&X(R)&&e.update(E(h,b.key,q),m);for(const b of Object.keys(x.fieldAccessGroups||{}))for(const F of T){const D=vn(b,x,F),M=on(b,F.key);D.some(H=>H.name===R.name)&&X(R)&&e.update(E(h,M,q),m)}};if(t==="delete")return;const U=_.filter(h=>X(h)&&h.twoWay);if(!a?.noTwoWay){for(const h of U){if(!O)throw new Error("VALIDATION_ERROR: batchSize is required");const x=i.collections[h.collection],R=L(x.fields,h.twoWay),q=gt(x,x.fields),Z=Array.from(q).map(m=>m.name);if(!R)throw new Error(`SCHEMA_ERROR: Field ${h.twoWay} not found in collection ${h.collection}`);if(X(R)){if(r[`${h.name}_Array`])for(const[m,T]of Object.entries(r[h.name])){if(t==="update"&&w&&w[`${h.name}_Array`]?.includes(m))continue;const b={...w,...r};et(b);const F={};R.includeFields&&R.includeFields.forEach(C=>{if(b[C]!==void 0){F[C]=b[C];const B=L(o.fields,C);Rt(o,[B]).size===1&&(F[`${C}_Lowercase`]=b[`${C}_Lowercase`])}});const D={[`${h.twoWay}.${s}`]:{Collection_Path:n,...F},[`${h.twoWay}_Array`]:c(s)};Z.includes(R.name)&&(D[`${h.twoWay}_Single`]={Collection_Path:n,id:s,...F});const M=$n(r);e.update(k(T.Collection_Path,m),{...D,...M}),O.size++,mt(R,x,i)&&(e.update(y(h,R.name,m),{[`${R.name}.${s}`]:{Collection_Path:n,...F},[`${R.name}_Array`]:c(s)}),O.size++),x.fields.forEach(C=>{if(mt(C,x,i)){const B=JSON.parse(as(En(C,x,i))),S={};B.includes(R.name)&&(S[`${h.twoWay}_Array`]=c(s)),Object.keys(M).forEach(Q=>{B.includes(Q)&&(S[Q]=M[Q])}),Object.keys(S).length>0&&(e.update(y(h,C.name,m),S),O.size++)}});const H=l[x.labels.collection];for(const C of H)if(C.fields.some(B=>B.name===R.name)){const B={...D};Object.keys(M).forEach(S=>{C.fields.some(Q=>Q.name===S)&&(B[S]=M[S])}),Object.keys(B).length>0&&(e.update(E(h,C.key,m),B),O.size++)}for(const C of Object.keys(x.fieldAccessGroups||{}))for(const B of H){const S=vn(C,x,B),Q=on(C,B.key);if(S.some(ee=>ee.name===R.name)){const ee={...D};Object.keys(M).forEach(ye=>{S.some(le=>le.name===ye)&&(ee[ye]=M[ye])}),Object.keys(ee).length>0&&(e.update(E(h,Q,m),ee),O.size++)}}}}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${R.type}`)}O&&O.size>500&&console.error(new Error(`VALIDATION_ERROR: ${O.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(const h of U){if(!O)throw new Error("VALIDATION_ERROR: batchSize is required");const x=i.collections[h.collection],R=L(x.fields,h.twoWay);if(!R)throw new Error(`SCHEMA_ERROR: Field ${h.twoWay} not found in collection ${h.collection}`);if(X(R)){if(t==="update"&&w&&!(r[h.name]&&be(r[h.name]))&&r[`${h.name}_Array`]&&w[`${h.name}_Array`]?.length>0)for(const[q,Z]of Object.entries(w[h.name]))!r[`${h.name}_Array`].includes(q)&&!A?.get(h.name)?.includes(q)&&(O.size+=j(x,R),O.size<=500&&v(h,x,R,q,Z.Collection_Path))}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${R.type}`)}for(const h of U){if(!O)throw new Error("VALIDATION_ERROR: batchSize is required");const x=i.collections[h.collection],R=L(x.fields,h.twoWay);if(!R)throw new Error(`SCHEMA_ERROR: Field ${h.twoWay} not found in collection ${h.collection}`);if(X(R)){if(t==="update"&&w&&r[h.name]&&be(r[h.name])&&w[`${h.name}_Array`]?.length>0)for(const[q,Z]of Object.entries(w[h.name]))A?.get(h.name)?.includes(q)||(O.size+=j(x,R),O.size<=500&&v(h,x,R,q,Z.Collection_Path))}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${R.type}`)}}},Ze=t=>{for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(t[e]===void 0?delete t[e]:typeof t[e]=="object"&&t[e]!==null&&Ze(t[e]))},Vo=t=>{if(t=t.toString(),/[/]|^\.+$|^__.*__$/.test(t))return!1;try{const s=new TextEncoder().encode(t),r=new TextDecoder().decode(s);if(t!==r)return!1}catch{return!1}return!(new Blob([t]).size>1500)},pi=async(t,e,n,s=1e3,r=5)=>{for(;r>0;)try{await t(...e);break}catch(i){if(r--,r===0)throw i;await new Promise(o=>setTimeout(o,s)),s*=2}},Yn=t=>{if(!t||typeof t!="string")return"";let e=t.replace(/[\r\n]/g,"");if(e=e.replace(/\0/g,""),e=e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,""),e=e.trim(),e.length>254)throw new Error("Email address is too long");return e},Es=t=>t?Array.isArray(t)?t.map(s=>Yn(s)).filter(s=>s.length>0):Yn(t)||"":"",tu=t=>{if(!t||typeof t!="string")return"";let e=t.replace(/[\r\n]/g," ");if(e=e.replace(/\0/g,""),e=e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,""),e=e.trim(),e.length>998)throw new Error("Email subject is too long");return e},yi=t=>{if(!t||typeof t!="string")return"";let e=t.replace(/\0/g,"");if(e=e.replace(/\r\n\r\n/g,`
4
-
5
- `),e=e.replace(/\r\n/g,`
6
- `),e.length>5e6)throw new Error("Email body is too long");return e},nu=(t="enterprise",e)=>t==="enterprise"?e:"(default)",fe=()=>{const t=vt.getApp(),e=process.env.STOKER_FB_WEB_APP_CONFIG;if(!e)throw new Error("STOKER_FB_WEB_APP_CONFIG not set.");const n=JSON.parse(e),s=nu(process.env.FB_FIRESTORE_EDITION,n.projectId);return oe.getFirestore(t,s)},Uo=async(t,e)=>{const n={};for(const s of e){const r=`${t}/${s}.js`,i=Ei.pathToFileURL(r).href;n[s]=await import(i)}return n};let vs,Wo,Dn,jo,sn,Zo,Cn,Fn,Os=0,gi=!1;const Ft={getTenant(){if(!Dn)throw new Error("Tenant not provided");return Dn},setTenant(t){Dn=t},getMode(){return Wo},getTimezone(){return jo},getGlobalConfigModule(){return pe(sn)},getCustomizationFile(t,e){if(!Object.keys(e.collections).includes(t))throw new Error("PERMISSION_DENIED");const n=ga([t],Zo,"node",Ft);return pe(n?.[t])},getVersionInfo(){return Cn},getMaintenanceInfo(){return Fn},getStokerFirestore:fe},su=async(t,e,n,s,r)=>{const i=!!gi;if(gi=!0,e&&(Dn=e),Wo=t,vs&&!r)return Ft;if(!process.env.STOKER_FB_WEB_APP_CONFIG)throw new Error("STOKER_FB_WEB_APP_CONFIG not set.");const o=process.env.STOKER_FB_WEB_APP_CONFIG,a=JSON.parse(o),d=(await import(Ei.pathToFileURL(n).href)).default;sn=d({sdk:"node",utils:Ft}),!r&&t==="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{vs=vt.getApp()}catch{vs=vt.initializeApp({credential:vt.applicationDefault(),databaseURL:a.databaseURL,storageBucket:a.storageBucket,projectId:a.projectId})}const p=await Ye();return Zo=await Uo(s,Object.keys(p.collections)),jo=await ae(sn.timezone),i||fe().collection("system_deployment").doc("maintenance_mode").onSnapshot(u=>{u.exists?(Fn=u.data(),ae(sn.onMaintenanceUpdate,["node",Fn.active?"on":"off"])):console.error("Maintenance status not found")},u=>{console.error(u.message)}),i||fe().collection("system_deployment").doc("latest_deploy").onSnapshot(u=>{u.exists?(Cn=u.data(),Os++,Os>1&&ae(sn.onVersionUpdate,["node",Cn,Os])):console.error("Version info not found")},u=>{console.error(u.message)}),await new Promise(u=>{const f=()=>{Fn&&Cn?u(Ft):setTimeout(f,100)};f()}),Ft},{getTenant:Je,setTenant:ru,getMode:ar,getTimezone:lr,getGlobalConfigModule:It,getCustomizationFile:rt,getVersionInfo:iu,getMaintenanceInfo:ou}=Ft,au=async(t,e,n,s)=>new Promise((r,i)=>{const o=sa(t,e,{cwd:n||process.cwd(),env:{...process.env,...s}});let a="";const l=()=>{o.kill("SIGINT")},c=()=>{o.kill("SIGTERM")},d=()=>{process.removeListener("SIGINT",l),process.removeListener("SIGTERM",c)};o.stdout?.on("data",p=>{a+=p.toString(),console.log(p.toString())}),o.stderr?.on("data",p=>{console.log(p.toString())}),o.on("exit",p=>{d(),p===0?r(a):i()}),process.on("SIGINT",l),process.on("SIGTERM",c)}),lu=async()=>{const t=process.env.STOKER_FB_WEB_APP_CONFIG;if(!t)throw new Error("Firebase web app config not found");const e=JSON.parse(t);try{return vt.getApp()}catch{return vt.initializeApp({credential:vt.applicationDefault(),databaseURL:e.databaseURL,storageBucket:e.storageBucket,projectId:e.projectId})}},Ye=async(t=!1)=>{const s=await vi.getDatabase().ref("schema").orderByChild("published_time").limitToLast(1).get(),r=Object.values(s.val())[0];if(t){for(const i of Object.values(r.collections))for(const o of i.fields)if(o.type==="Computed"){const a=We(o,rt(i.labels.collection,r));a.formula&&(o.formula=a.formula)}}else for(const i of Object.values(r.collections))i.fields=i.fields.filter(o=>o.type!=="Computed");return r},cu=async()=>{const n=await vi.getDatabase().ref("schema").orderByChild("published_time").limitToLast(2).get();if(!(n.numChildren()<2))return Object.values(n.val())[0]},Ne=(t,e,n)=>{let s=t.collection("tenants").doc(n);for(let r=0;r<e.length;r++)r%2===0?s=s.collection(e[r]):s=s.doc(e[r]);return s},zo=(t,e,n,s,r,i)=>{const o=fe(),a=e.at(-1);if(!a)throw new Error("EMPTY_PATH");const l=n.collections[a],{labels:c,fields:d,preloadCache:p}=l,u=rt(a,n),f=Ne(o,e,t);if(r)if(s){const g=r.collections?.[c.collection];if(!r.Role)throw new Error("PERMISSION_DENIED");const k=g&&xe("Read",g),y=Ti(l,n,r,i??{}),E=bi(l,r),w=Bs(l,r),A=Ri(l,n,r),O=(m=[])=>{const T=[],b=Ai(r.Role,l,n);if(!b)throw new Error("PERMISSION_DENIED");if(k){let F=o.collection("tenants").doc(t).collection("system_fields").doc(c.collection).collection(`${c.collection}-${b.key}`).where("Collection_Path_String","==",e.join("/"));m.forEach(M=>{F=F.where(...M)}),T.push(F);const D=qs(l);Object.entries(l.fieldAccessGroups||{}).forEach(([M,H])=>{if(!D[M]?.length||!Kn(H,c.collection,r,i??{}))return;const C=on(M,b.key);let B=o.collection("tenants").doc(t).collection("system_fields").doc(c.collection).collection(`${c.collection}-${C}`).where("Collection_Path_String","==",e.join("/"));m.forEach(S=>{B=B.where(...S)}),T.push(B)})}else if(y)for(const F of y){let D=o.collection("tenants").doc(t).collection("system_fields").doc(c.collection).collection(`${c.collection}-${F.field}`).where("Collection_Path_String","==",e.join("/"));m.forEach(M=>{D=D.where(...M)}),T.push(D)}return T},_=E.filter(m=>"operations"in m&&m.operations?m.operations.includes("Read"):!0);if(_.length===0&&w.length===0&&A.length===0)return O();let I=0;const j=m=>{m&&(I===0?I=m:I*=m)};if(_.length>0){for(const m of _)if(m.operations&&m.type==="Record_Property"){const T=m.roles.find(b=>b.role===r.Role);if(!T)throw new Error("PERMISSION_DENIED");j(T.values?.length)}}p?.roles.includes(r.Role)&&p.range&&j(p.range.fields.length);const v=u.admin?.statusField;v&&!p?.roles.includes(r.Role)&&j(Math.max(v.active?.length||0,v.archived?.length||0));const U=I===0?30:Math.max(1,Math.floor(30/I)),h=[];_.filter(m=>m.type==="Record_Owner").forEach(()=>h.push(["Created_By","==",s])),_.filter(m=>m.type==="Record_User").forEach(m=>{if("collectionField"in m){const T=L(d,m.collectionField);h.push([`${T.name}_Array`,"array-contains",r.Doc_ID])}}),_.filter(m=>m.type==="Record_Property").forEach(m=>{if("propertyField"in m){const T=m.roles.find(F=>F.role===r.Role);if(!T)throw new Error("PERMISSION_DENIED");const b=L(d,m.propertyField);b.type==="Array"?h.push([`${b.name}_Array`,"array-contains-any",T.values]):h.push([b.name,"in",T.values])}});const x=[];w.filter(m=>m.type==="Individual").forEach(m=>{const T=g?.individualEntities,b=[];if(T){const F=m.singleQuery?m.singleQuery:U;for(let D=0;D<T.length;D+=F){const M=T.slice(D,D+F);b.push(M)}if(!m.singleQuery)b.forEach(D=>{x.push(...O(h.concat([["id","in",D]])))});else{if(T.length>F)throw new Error(`INPUT_ERROR: Individual entity restriction with singleQuery set to true must not have more than ${m.singleQuery} entities`);h.push(["id","in",T])}}}),A.filter(m=>m.parentFilter.type==="Individual").forEach(m=>{const{parentFilter:T,parentRestriction:b}=m;if("collectionField"in T){const F=L(d,T.collectionField);if("collection"in F){const D=r.collections?.[F.collection];if(!D)throw new Error("PERMISSION_DENIED");const M=D.individualEntities,H=[];if(M){const C=b.singleQuery?b.singleQuery:U;for(let B=0;B<M.length;B+=C){const S=M.slice(B,B+C);H.push(S)}if(!b.singleQuery)H.forEach(B=>{x.push(...O(h.concat([[`${F.name}_Array`,"array-contains-any",B]])))});else{if(M.length>C)throw new Error(`INPUT_ERROR: Individual entity parentFilter with singleQuery set to true must not have more than ${b.singleQuery} entities`);h.push([`${F.name}_Array`,"array-contains-any",M])}}}}});const R=[];w.filter(m=>m.type==="Parent").forEach(m=>{if("collectionField"in m){const T=L(d,m.collectionField);if("collection"in T){const b=g?.parentEntities,F=[];if(b){const D=m.singleQuery?m.singleQuery:U;for(let M=0;M<b.length;M+=D){const H=b.slice(M,M+D);F.push(H)}if(!m.singleQuery)F.forEach(M=>{R.push(...O(h.concat([[`${T.name}_Array`,"array-contains-any",M]])))});else{if(b&&b.length>D)throw new Error(`INPUT_ERROR: Parent entity restriction with singleQuery set to true must not have more than ${m.singleQuery} entities`);h.push([`${T.name}_Array`,"array-contains-any",b])}}}}}),A.filter(m=>m.parentFilter.type==="Parent").forEach(m=>{const{parentFilter:T,parentRestriction:b}=m;if("collectionField"in T&&"parentCollectionField"in T){const F=L(d,T.collectionField),D=L(d,T.parentCollectionField);if("collection"in F&&"collection"in D){const M=r.collections?.[F.collection];if(!M)throw new Error("PERMISSION_DENIED");const H=M.parentEntities,C=[];if(H){const B=b.singleQuery?b.singleQuery:U;for(let S=0;S<H.length;S+=B){const Q=H.slice(S,S+B);C.push(Q)}if(!b.singleQuery)C.forEach(S=>{R.push(...O(h.concat([[`${D.name}_Array`,"array-contains-any",S]])))});else{if(H&&H.length>B)throw new Error(`INPUT_ERROR: Profile_Parent entity parentFilter with singleQuery set to true must not have more than ${b.singleQuery} entities`);h.push([`${D.name}_Array`,"array-contains-any",H])}}}}});const q=[];R.length===0&&(w.filter(m=>m.type==="Parent_Property").forEach(m=>{if("collectionField"in m&&"propertyField"in m){const T=L(d,m.collectionField),b=L(d,m.propertyField);if("collection"in T){const F=g?.parentPropertyEntities||{};Object.entries(F).forEach(([D,M])=>{if(M.length>0){const H=[];for(let C=0;C<M.length;C+=U){const B=M.slice(C,C+U);H.push(B)}H.forEach(C=>{q.push(...O(h.concat([[`${T.name}_Array`,"array-contains-any",C],[b.name,"==",D]])))})}})}}}),A.filter(m=>m.parentFilter.type==="Parent_Property").forEach(m=>{const{parentFilter:T}=m;if("collectionField"in T&&"parentCollectionField"in T&&"parentPropertyField"in T){const b=L(d,T.collectionField),F=L(d,T.parentCollectionField),D=L(d,T.parentPropertyField);if("collection"in b&&"collection"in F){const M=r.collections?.[b.collection];if(!M)throw new Error("PERMISSION_DENIED");const H=M.parentPropertyEntities||{};Object.entries(H).forEach(([C,B])=>{if(B.length>0){const S=[];for(let Q=0;Q<B.length;Q+=U){const ee=B.slice(Q,Q+U);S.push(ee)}S.forEach(Q=>{q.push(...O(h.concat([[`${F.name}_Array`,"array-contains-any",Q],[D.name,"==",C]])))})}})}}}));const Z=[...x,...R,...q];return!w.length&&!A.length?O(h):Z}else throw new Error("PERMISSION_DENIED");else return[f]},cr=(t,e,n,s,r,i)=>{const o=fe(),a=e.at(-1);if(!a)throw new Error("EMPTY_PATH");const l=s.collections[a],{labels:c}=l,d=Ne(o,e,t);if(r){const p=r.collections?.[c.collection];if(!r.Role)throw new Error("PERMISSION_DENIED");const u=p&&xe("Read",p),f=Ti(l,s,r,i??{}),g=[],k=Ai(r.Role,l,s);if(!k)throw new Error("PERMISSION_DENIED");if(u){g.push(o.collection("tenants").doc(t).collection("system_fields").doc(c.collection).collection(`${c.collection}-${k.key}`).doc(n));const y=qs(l);Object.entries(l.fieldAccessGroups||{}).forEach(([E,w])=>{if(!y[E]?.length||!Kn(w,c.collection,r,i??{}))return;const A=on(E,k.key);g.push(o.collection("tenants").doc(t).collection("system_fields").doc(c.collection).collection(`${c.collection}-${A}`).doc(n))})}else if(f)for(const y of f)g.push(o.collection("tenants").doc(t).collection("system_fields").doc(c.collection).collection(`${c.collection}-${y.field}`).doc(n));return g}else return[d.doc(n)]},Ht=async t=>await bt.getAuth().getUser(t),qo=async(t,e,n,s,r,i,o,a,l,c)=>{const d=n.at(-2),p=Si(r.collections[d],r).map(g=>g.labels.collection);s.collections?s.collections.forEach(g=>{if(!p.includes(g))throw new Error(`SCHEMA_ERROR: Collection ${g} not found in subcollections of ${d}`)}):s.collections=p;const u=s.depth-1,f=s.collections.map(async g=>{const k=await dr([...n,g],{constraints:s.constraints,userId:a,pagination:s.limit,providedTransaction:l,noEmbeddingFields:c}).catch(y=>{throw y.code==="permission-denied"&&console.info(`PERMISSION_DENIED for subcollection ${g} for document at ${n.join("/")}`),y});e[g]=k.records,i&&await Promise.all(e[g].map(y=>ur(t,y,[...n,g,y.id],i,r,void 0,a,l,c))),u>0&&await Promise.all(e[g].map(y=>qo(t,y,[...n,g,y.id],{depth:u},r,i,o,a,l,c)))});await Promise.all(f)},ur=async(t,e,n,s,r,i,o,a,l)=>{const c=n.at(-2);s.fields||=r.collections[c].fields.filter(u=>X(u));const d=s.depth-1,p=[];for(const u of s.fields)if("collection"in u){const f=e[u.name];if(!f)continue;const g=Object.keys(f);for(const k of g){const y=f[k],E=Be(y.Collection_Path,k,{userId:o,providedTransaction:a,noEmbeddingFields:l}).then(w=>{if(f[k]=w,d>0)return ur(t,f[k],[...y.Collection_Path,k],{depth:d},r,i,o,a,l)}).catch(w=>{if(w.message.includes("NOT_FOUND")||w.code==="permission-denied")delete f[k];else throw w});p.push(E)}}await Promise.all(p)},dr=async(t,e)=>{if(e?.subcollections?.depth&&e.subcollections.depth>10)throw new Error("INPUT_ERROR: Subcollections depth cannot exceed 10");if(e?.relations?.depth&&e.relations.depth>10)throw new Error("INPUT_ERROR: Relations depth cannot exceed 10");if(e?.pagination?.number!==void 0){const c=e.pagination.number;if(typeof c!="number"||!Number.isFinite(c)||!Number.isInteger(c)||c<1)throw new Error("INPUT_ERROR: Pagination number must be a positive finite integer")}const n=e?.constraints,s=Je(),r=fe();let i,o,a;const l=async c=>{const[d,p,u,f]=await Promise.all([e?.userId?c.get(r.collection("tenants").doc(s).collection("system_user_permissions").doc(e.userId)):Promise.resolve({}),c.get(r.collection("system_deployment").doc("maintenance_mode")),Ye(!0),e?.userId?Ht(e.userId):Promise.resolve(void 0)]);if(!p.exists)throw new Error("MAINTENANCE_MODE");if(p.data().active)throw new Error("MAINTENANCE_MODE");const k=u;let y;const E=It(),w=t.at(-1);if(!w)throw new Error("EMPTY_PATH");const A=Object.keys(k.collections).includes(w),O=E.disabledCollections?.includes(w);if(!A||O)throw new Error("COLLECTION_NOT_FOUND");const _=k.collections[w],{labels:I}=_,j=rt(I.collection,k);if(e?.userId){if(!d?.exists)throw new Error("PERMISSION_DENIED");if(y=d.data(),!y.Role)throw new Error("USER_ERROR");if(!y.Enabled)throw new Error("PERMISSION_DENIED")}let v=zo(s,t,k,e?.userId,y,f?.customClaims??{});if(v.length===0)return{cursor:{},pages:0,records:[]};if(n&&(v=v.map(m=>(n.forEach(([T,b,F])=>{m=m.where(T,b,F)}),m))),o=e?.pagination?.startAfter||e?.pagination?.endBefore||{first:new Map,last:new Map},e?.pagination){if(e.pagination.startAfter&&e.pagination.endBefore)throw new Error("INPUT_ERROR: startAfter and endBefore cannot be provided together");const m=e.pagination.startAfter||e.pagination.endBefore;if(e?.userId){const T=ya(y.Role,_,k);if(m&&T!==!0)throw new Error("INPUT_ERROR: Pagination is not allowed when using "+T)}e.pagination.orderByField&&e.pagination.orderByDirection?!e.pagination.startAfter&&!e.pagination.endBefore?v=v.map(T=>T.orderBy(e.pagination.orderByField,e.pagination.orderByDirection).limit(e.pagination.number)):e.pagination.startAfter?v=v.map((T,b)=>T.orderBy(e.pagination.orderByField,e.pagination.orderByDirection).startAfter(o.last.get(b)).limit(e.pagination.number)):v=v.map((T,b)=>T.orderBy(e.pagination.orderByField,e.pagination.orderByDirection).endBefore(o.first.get(b)).limitToLast(e.pagination.number)):!e.pagination.startAfter&&!e.pagination.endBefore?v=v.map(T=>T.limit(e.pagination.number)):e.pagination.startAfter?v=v.map((T,b)=>T.startAfter(o.last.get(b)).limit(e.pagination.number)):v=v.map((T,b)=>T.endBefore(o.first.get(b)).limitToLast(e.pagination.number))}const U={};await ce("preOperation",E,j,{operation:"read",context:U}),await ce("preRead",E,j,{context:U,refs:v,multiple:!0,listener:!1}),a=new Map;const R=v.map(async m=>await c.get(m)),q=await Promise.all(R);for(const m of q){for(const T of m.docs){a.has(T.id)||a.set(T.id,{});const b=T.data(),F=a.get(T.id);F.id||=T.id;const D={...F,...b};delete D.Collection_Path_String,a.set(T.id,D)}o.first.set(q.indexOf(m),m.docs[0]),o.last.set(q.indexOf(m),m.docs.at(-1)||m.docs[0])}if(e?.pagination){let m=v[0];n&&(m=n.reduce((D,[M,H,C])=>D.where(M,H,C),m)),e.pagination.orderByField&&e.pagination.orderByDirection&&(m=m.orderBy(e.pagination.orderByField,e.pagination.orderByDirection));const b=(await m.count().get()).data().count,F=e.pagination.number;i=F>0?Math.ceil(b/F):0}let Z;e?.noComputedFields||(Z=await ae(j.admin?.retriever));for(const m of a.values()){const T=[],b=[...m.Collection_Path,m.id];e?.subcollections&&T.push(qo(s,a.get(m.id),b,pe(e.subcollections),k,pe(e?.relations),void 0,e.userId,e.transactional?c:void 0,e?.noEmbeddingFields)),e?.relations&&(e.relations.fields&&(e.relations.fields=e.relations.fields.map(H=>{if(typeof H=="string"){const C=_.fields.find(B=>B.name===H);if(C)return C;throw new Error(`SCHEMA_ERROR: Field ${H} not found in collection ${w}`)}return H})),T.push(ur(s,a.get(m.id),b,pe(e.relations),k,void 0,e.userId,e.transactional?c:void 0,e?.noEmbeddingFields))),await Promise.all(T);const F=[];for(const H of _.fields){if(H.type==="Computed"&&!e?.noComputedFields){const C=We(H,j);if(!C.formula)continue;F.push(ae(C.formula,[m,Z]).then(B=>{m[H.name]=B}))}e?.noEmbeddingFields&&H.type==="Embedding"&&delete m[H.name]}if(await Promise.all(F),e?.userId&&y?.Role){if(!f)throw new Error("USER_ERROR");if(!(j.custom?.serverAccess?.read!==void 0?await ae(j.custom.serverAccess.read,[y,f,m]):!0)){a.delete(m.id);continue}for(const C of _.fields){const B=!C.access||He(C,y,_,f?.customClaims??{}),S=We(C,j),Q=S?.custom?.serverAccess?.read!==void 0?await ae(S.custom.serverAccess.read,[y,f,m]):!0;(!B||!Q)&&(X(C)?(delete a.get(m.id)[C.name],delete a.get(m.id)[`${C.name}_Array`],delete a.get(m.id)[`${C.name}_Single`]):delete a.get(m.id)[C.name])}}const D={operation:"read",data:m,recordId:m.id,context:U};await ce("postOperation",E,j,D),await ce("postRead",E,j,{context:U,refs:v,record:m,listener:!1})}e?.userId&&await ma(Array.from(a.values()),_,k,e.userId,y)};return e?.providedTransaction?await l(e.providedTransaction):await r.runTransaction(async c=>{await l(c)},{readOnly:!0}),{cursor:o,pages:i,records:Array.from(a.values())}},Bo=async(t,e,n,s,r,i,o,a)=>{const l=s.at(-2),c=Si(i.collections[l],i).map(u=>u.labels.collection);r.collections?r.collections.forEach(u=>{if(!c.includes(u))throw new Error(`SCHEMA_ERROR: Collection ${u} not found in subcollections of ${l}`)}):r.collections=c;const d=r.depth-1,p=r.collections.map(async u=>{const f=await dr([...s,u],{constraints:r.constraints||[],userId:a,relations:o,pagination:r.limit,providedTransaction:e}).catch(g=>{throw g.code==="permission-denied"&&console.info(`PERMISSION_DENIED for subcollection ${u} for document at ${s.join("/")}`),g});n[u]=f.records,d>0&&await Promise.all(n[u].map(async g=>{await Bo(t,e,g,[...s,u,g.id],{depth:d},i,o,a)}))});await Promise.all(p)},Ho=async(t,e,n,s,r,i,o,a,l)=>{const c=s.at(-2);i.fields||=r.collections[c].fields.filter(u=>X(u));const d=i.depth-1,p=[];for(const u of i.fields)if("collection"in u){const f=n[u.name];if(!f)continue;for(const[g,k]of Object.entries(f)){const y=Be(k.Collection_Path,g,{userId:o,providedTransaction:e,noComputedFields:a,noEmbeddingFields:l}).then(E=>{if(f[g]=E,d>0)return Ho(t,e,f[g],[...k.Collection_Path,g],r,{depth:d},o,a,l)}).catch(E=>{if(E.message.includes("NOT_FOUND")||E.code==="permission-denied")delete f[g];else throw E});p.push(y)}}await Promise.all(p)},Be=async(t,e,n)=>{if(n?.subcollections?.depth&&n.subcollections.depth>10)throw new Error("INPUT_ERROR: Subcollections depth cannot exceed 10");if(n?.relations?.depth&&n.relations.depth>10)throw new Error("INPUT_ERROR: Relations depth cannot exceed 10");const s=Je(),r=fe();let i;const o=async a=>{const[l,c,d,p]=await Promise.all([n?.userId?a.get(r.collection("tenants").doc(s).collection("system_user_permissions").doc(n.userId)):Promise.resolve({}),a.get(r.collection("system_deployment").doc("maintenance_mode")),Ye(!0),n?.userId?Ht(n.userId):Promise.resolve(void 0)]);if(!c.exists)throw new Error("MAINTENANCE_MODE");if(c.data().active)throw new Error("MAINTENANCE_MODE");const f=d;let g;const k=It(),y=t.at(-1);if(!y)throw new Error("EMPTY_PATH");const E=Object.keys(f.collections).includes(y),w=k.disabledCollections?.includes(y);if(!E||w)throw new Error("COLLECTION_NOT_FOUND");const A=f.collections[y],{labels:O}=A,_=rt(O.collection,f);let I;if(n?.userId){if(!l?.exists)throw new Error("PERMISSION_DENIED");if(g=l.data(),!g.Role)throw new Error("USER_ERROR");if(!g.Enabled)throw new Error("PERMISSION_DENIED");if(I=g.collections?.[O.collection],!I)throw new Error("PERMISSION_DENIED")}if(n?.userId&&(!I||!xe("Read",I)))throw new Error("PERMISSION_DENIED");const j=cr(s,t,e,f,g,p?.customClaims??{});if(j.length===0)throw new Error("PERMISSION_DENIED");const v={};await ce("preOperation",k,_,{operation:"read",recordId:e,context:v}),await ce("preRead",k,_,{context:v,refs:j,multiple:!1,listener:!1}),i={};const x=j.map(b=>a.get(b)),R=await Promise.all(x);for(const b of R)if(b.exists){const F=b.data();i.id||=b.id,i={...i,...F},delete i.Collection_Path_String}else throw new Error(`NOT_FOUND: Document with ID ${e} does not exist at location ${t?.join("/")||O.collection}`);const q=[],Z=t?[...t,e]:[O.collection,e];if(n?.subcollections&&q.push(Bo(s,a,i,Z,n.subcollections,f,void 0,n.userId)),n?.relations&&(n.relations.fields&&(n.relations.fields=n.relations.fields.map(b=>{if(typeof b=="string"){const F=A.fields.find(D=>D.name===b);if(F)return F;throw new Error(`SCHEMA_ERROR: Field ${b} not found in collection ${y}`)}return b})),q.push(Ho(s,a,i,Z,f,n.relations,n.userId,n.noComputedFields,n.noEmbeddingFields))),await Promise.all(q),!n?.noComputedFields){for(const b of A.fields)if(b.type==="Computed"){const F=We(b,_);if(!F.formula)continue;i[b.name]=await F.formula(i)}}if(n?.noEmbeddingFields)for(const b of A.fields)b.type==="Embedding"&&delete i[b.name];if(n?.userId&&g?.Role){if(!p)throw new Error("USER_ERROR");if(!(_.custom?.serverAccess?.read!==void 0?await ae(_.custom?.serverAccess?.read,[g,p,i]):!0))throw new Error("PERMISSION_DENIED");for(const F of A.fields){const D=!F.access||He(F,g,A,p?.customClaims??{}),M=We(F,_),H=M?.custom?.serverAccess?.read!==void 0?await ae(M.custom.serverAccess.read,[g,p,i]):!0;(!D||!H)&&(X(F)?(delete i[F.name],delete i[`${F.name}_Array`],delete i[`${F.name}_Single`]):delete i[F.name])}}await ce("postOperation",k,_,{operation:"read",data:i,recordId:e,context:v}),await ce("postRead",k,_,{context:v,refs:j,record:i,listener:!1}),n?.userId&&await ha(i,A,f,n.userId,g)};return n?.providedTransaction?await o(n.providedTransaction):await r.runTransaction(async a=>{await o(a)},{readOnly:!0}),i},kt=async(t,e,n,s,r,i,o,a,l)=>{const{labels:c}=o,d=fe(),p=It(),u=await ae(p.firebase?.writeLogTTL),f={operation:t,collection:c.collection,docId:i,user:"System",status:e,Collection_Path:r,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(u){const E=new Date,w=new Date(new Date().setDate(E.getDate()+u));f.TTL=oe.Timestamp.fromDate(w)}const g=pe(n);et(g),t!=="delete"&&(f.data.data=pe(g)),t==="update"&&(f.data.originalRecord=pe(l)),t!=="delete"&&["started","written"].includes(e)&&(delete f.data.data.Saved_At,delete f.data.data.Last_Save_At),e==="failed"&&(f.data.error=JSON.stringify(a));const k=Ne(d,r,s),y=n.Last_Write_At;await k.doc(i).collection("system_write_log").doc(`${n.Last_Write_By}-${y.valueOf()}`).set(f)},Gt=async t=>{const e=Je(),n=bt.getAuth(),s=fe(),r=[];if(await Promise.all([(async()=>{try{await s.collection("tenants").doc(e).collection("system_user_permissions").doc(t.User_ID).delete()}catch(i){r.push(`Error deleting user permissions:
7
- ${i}`)}})(),(async()=>{try{await n.deleteUser(t.User_ID)}catch(i){if(i.code==="auth/user-not-found")return;r.push(`Error deleting user:
8
- ${i}`)}})()]),r.length>0)throw new Error(r.join(", "))},fr=async(t,e,n,s,r,i,o,a,l)=>{const c=fe(),d=ar(),p=process.env.ADMIN_EMAIL;if(d==="development"||process.env.FIRESTORE_EMULATOR_HOST)if(p)t=p;else throw new Error("Admin email not set");const u=Es(t),f=tu(e),g=n?yi(n):void 0,k=s?yi(s):void 0,y=r?Es(r):void 0,E=i?Es(i):void 0,w=o?Yn(o):void 0,A=l?Yn(l):void 0,O=Array.isArray(u)?u:[u];if(O.length===0||O.length===1&&!O[0])throw new Error("No valid email addresses provided");const _={to:u,message:{subject:f}};if(g&&(_.message.text=g),k&&(_.message.html=k),y){const I=Array.isArray(y)?y:[y];I.length>0&&I[0]&&(_.cc=y)}if(E){const I=Array.isArray(E)?E:[E];I.length>0&&I[0]&&(_.bcc=E)}w&&(_.replyTo=w),a&&(_.message.attachments=a),A&&(_.from=A),await c.collection("system_mail").add(_)},uu=["tenant","role","collection","doc"],Go=new Set(uu);function hr(t){return Go.has(t)}function du(t){if(!t)return{};const e={};for(const n of Object.keys(t))Go.has(n)||(e[n]=t[n]);return e}const mr=async(t,e,n,s,r,i,o)=>{const a=bt.getAuth(),l=fe(),{labels:c,fields:d}=s;if(be(r.Email)||!r.Email)throw new Error("VALIDATION_ERROR: Email field is required");if(be(r.Role)||!r.Role)throw new Error("VALIDATION_ERROR: Role field is required");if(r.Enabled===void 0||r.Enabled===null||be(r.Enabled))throw new Error("VALIDATION_ERROR: Enabled field is required");const p="USER_ERROR",u=async(y,E)=>{try{await Gt(y)}catch{throw new Error(`ROLLBACK_FAILED: ${E}`)}};let f;try{f=await a.createUser({email:r.Email,emailVerified:!1,password:o,displayName:r.Name,photoURL:r.Photo_URL,disabled:!r.Enabled})}catch{throw new Error(p)}const g={};for(const y of d)y.saveToAuthToken&&!hr(y.name)&&r[y.name]!==void 0&&y.type!=="Timestamp"&&y.type!=="Computed"&&y.type!=="Embedding"&&(be(r[y.name])?g[y.name]=null:g[y.name]=r[y.name]);try{await a.setCustomUserClaims(f.uid,{...g,tenant:t,role:r.Role,collection:c.collection,doc:e})}catch{throw await u(r,p),new Error(p)}try{await l.collection("tenants").doc(t).collection("system_user_permissions").doc(f.uid).set({...i,Role:r.Role,Enabled:r.Enabled??!1,Collection:c.collection,Doc_ID:e})}catch{throw await u(r,p),new Error(p)}const k=n.auth.enableMultiFactorAuth;if(k===!0||typeof k=="object"&&k.includes(r.Role)){let y;try{y=await a.generateEmailVerificationLink(r.Email)}catch{throw await u(r,p),new Error(p)}if(y.includes("apiKey=&")){const E=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);y=y.replace("apiKey=&",`apiKey=${E.apiKey}&`)}if(y){const E=`https://${a.app.options.projectId}.firebaseapp.com/__/auth/action${y}`,w=await ae(n.appName),A=n?.mail?.emailVerification&&n.mail.emailVerification(E,w);try{await fr(r.Email,A?.subject||"Please verify your email address",void 0,A?.html||`Please verify your email address by clicking the link:
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:
9
5
  </br>
10
6
  </br>
11
- <a href="${E}">${E}</a>`)}catch{throw await u(r,p),new Error(p)}}}return f.uid},pr=async(t,e)=>{const{labels:n,parentCollection:s}=e;if(s){const r=t.at(-2);if(!r)throw new Error("PERMISSION_DENIED");const i=[...t].slice(0,-2),o=await Be(i,r).catch(()=>{throw new Error("PERMISSION_DENIED")}),a=o.Collection_Path;if(a.push(o.id),a.push(n.collection),!Xe(t,a))throw new Error("PERMISSION_DENIED")}else if(t.length>1)throw new Error("PERMISSION_DENIED")},Jn=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),fu=t=>{const e=n=>{Object.entries(n).forEach(([s,r])=>{Jn(r)&&Object.keys(r).length===2&&typeof r.seconds=="number"&&typeof r.nanoseconds=="number"?n[s]=new oe.Timestamp(r.seconds,r.nanoseconds):Jn(r)&&e(r)})};e(t)},yr=t=>{const e=n=>{Object.entries(n).forEach(([s,r])=>{Jn(r)&&Object.keys(r).length===2&&typeof r._seconds=="number"&&typeof r._nanoseconds=="number"?n[s]=new oe.Timestamp(r._seconds,r._nanoseconds):Jn(r)&&e(r)})};e(t)},is=t=>{if(typeof t=="object")for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(t[e]==="_DELETE_FIELD"?t[e]=oe.FieldValue.delete():is(t[e]))},hu=(t,e,n)=>{if(X(n)&&n.includeFields){const s={};return n.includeFields.forEach(r=>{if(e[r]!==void 0){s[r]=e[r];const i=L(t.fields,r);Rt(t,[i]).size===1&&(s[`${r}_Lowercase`]=e[`${r}_Lowercase`])}}),s}return{}},wi=async(t,e,n,s,r,i,o)=>{if(!X(n)||!n.enforceHierarchy)return;const{fields:a}=e,l=fe(),c=Object.entries(s[n.name]);if(!c.length)throw new Error(`VALIDATION_ERROR: relation ${n.name} is required`);const[d,p]=c[0];if(!p)throw new Error(`VALIDATION_ERROR: Relation ${n.name} is required`);const u=Ne(l,p.Collection_Path,t);if(i.size++,!o&&i.size>500)throw new 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.");const f=await r.get(u.doc(d));if(!f.exists)throw new Error(`VALIDATION_ERROR: Record ${d} not found in collection ${n.collection}`);const g=f.data(),k=L(a,n.enforceHierarchy.field),y=n.enforceHierarchy;if(!g[y.recordLinkField]||!s[k.name]||!Object.keys(s[k.name]).every(E=>Object.keys(g[y.recordLinkField]).includes(E)))throw new Error("VALIDATION_ERROR: Invalid relation hierarchy")},Sn=async(t,e,n)=>{delete e[t.name][n],e[`${t.name}_Array`]=e[`${t.name}_Array`]?.filter(s=>s!==n),delete e[`${t.name}_Single`]},ks=async(t,e,n,s,r)=>{e[t.name]||={},e[t.name][s]=n,e[`${t.name}_Array`]||=[],e[`${t.name}_Array`].push(s),r&&(e[`${t.name}_Single`]={id:s,...n})},mu=(t,e,n,s,r,i)=>{const o=[],a=[];for(const l of s.fields)X(l)&&l.twoWay&&l.collection===n&&((t==="Create"||!i?.[l.name]?.[e])&&r[l.name]?.[e]&&o.push(l),t==="Update"&&i?.[l.name]?.[e]&&!r[l.name]?.[e]&&a.push(l));return{addedFields:o,removedFields:a}},gr=async(t,e,n,s,r,i,o,a,l,c,d,p,u)=>{const{fields:f}=i,g=fe(),k=new Map,y=new Map,E=new Map;for(const w of f)X(w)&&["OneToOne","OneToMany"].includes(w.type)&&w.enforceHierarchy&&s[w.name]&&(t==="Create"||t==="Update"&&!Xe(p?.[w.name],s[w.name]))&&await wi(e,i,w,s,a,l);for(const w of f)if(X(w)&&w.twoWay){const A=o.collections[w.collection],O=L(A.fields,w.twoWay),_=gt(A,[O]);if(s[w.name]){const I=Object.entries(s[w.name]);for(const j of I){const[v,U]=j;if(t==="Create"||!p?.[w.name]?.[v]){let h;const x=E.get(w.collection)?.[v];if(x)h=x;else{l.size++,l&&l.size>500&&console.error(new 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.`));const q=Ne(g,U.Collection_Path,e),Z=await a.get(q.doc(v));if(!Z.exists){Sn(w,r,v);continue}const m=Z.data();y.set(w.collection,{...y.get(w.collection)||{},[v]:m}),h=pe({...m,...$n(s)})}const R={...h[O.name],[n]:{Collection_Path:s.Collection_Path,...hu(i,s,O)}};h[O.name]=R,h[`${O.name}_Array`]||=[],h[`${O.name}_Array`].push(n),_.size===1&&(h[`${O.name}_Single`]={id:n,...R}),E.set(w.collection,{...E.get(w.collection)||{},[v]:h})}}}if(t==="Update"){const I=Object.entries(p?.[w.name]||{});for(const j of I){const[v,U]=j;if(!s[w.name]?.[v]){let h;const x=E.get(w.collection)?.[v];if(x)h=x;else{l.size++,l&&l.size>500&&console.error(new 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.`));const R=Ne(g,U.Collection_Path,e),q=await a.get(R.doc(v));if(!q.exists){k.set(w.name,[...k.get(w.name)||[],v]);continue}const Z=q.data();y.set(w.collection,{...y.get(w.collection)||{},[v]:Z}),h=pe({...Z,...$n(s)})}h[O.name][n]&&delete h[O.name][n],Array.isArray(h[`${O.name}_Array`])&&(h[`${O.name}_Array`]=h[`${O.name}_Array`].filter(R=>R!==n)),_.size===1&&delete h[`${O.name}_Single`],E.set(w.collection,{...E.get(w.collection)||{},[v]:h})}}}}for(const[w,A]of E.entries()){const O=o.collections[w],_=rt(w,o);for(const[I,j]of Object.entries(A)){const{addedFields:v,removedFields:U}=mu(t,I,w,i,s,p);if(c&&d){for(const h of v){const x=L(O.fields,h.twoWay);if(!Or(O,x,d,u??{})){Sn(h,r,I);continue}}for(const h of U){const x=L(O.fields,h.twoWay),R=gt(O,[x]);if(!Or(O,x,d,u??{})){ks(h,r,p?.[h.name]?.[I],I,R.size===1);continue}}if(!ft("Update",O,o,c,d,y.get(w)?.[I])){for(const h of v)Sn(h,r,I);for(const h of U){const x=L(O.fields,h.twoWay),R=gt(O,[x]);ks(h,r,p?.[h.name]?.[I],I,R.size===1)}}if(!ft("Update",O,o,c,d,j)){for(const h of v)Sn(h,r,I);for(const h of U){const x=L(O.fields,h.twoWay),R=gt(O,[x]);ks(h,r,p?.[h.name]?.[I],I,R.size===1)}}}try{await hn("update",j,O,_,{operation:"update",data:j,context:{},originalRecord:j},o)}catch(h){throw new Error(`VALIDATION_ERROR: Two way relation update would invalidate record ${I} in ${w}: ${h.message}`)}for(const h of v){const x=L(O.fields,h.twoWay);["OneToOne","OneToMany"].includes(x.type)&&X(x)&&x.enforceHierarchy&&await wi(e,O,x,j,a,l,!0)}}}return k},Yo=(t,e,n)=>{t==="create"&&ct.forEach(s=>{if(!Xe(e[s],n[s]))throw new Error(`Updating system fields in hooks is not allowed: ${s}`)}),t==="update"&&(["id","Collection_Path","Created_At","Saved_At","Created_By"].forEach(s=>{if(s in e)throw new Error(`Cannot update system field: ${s}`)}),ct.forEach(s=>{if(!["id","Collection_Path","Created_At","Saved_At","Created_By"].includes(s)&&!Xe(e[s],n[s]))throw new Error(`Updating system fields in hooks is not allowed: ${s}`)}))},wr=(t,e,n,s)=>{const{softDelete:r}=e;if(!r)return;const i=r?.archivedField,o=r?.timestampField;if(n[i]===!0)if(t==="create")n[o]=oe.FieldValue.serverTimestamp();else{if(!s)throw new Error("Original record is required for update");if(!s[i])n[o]=oe.FieldValue.serverTimestamp();else if(n[o]&&n[o]?.valueOf()!==s[o]?.valueOf())throw new Error("Soft delete timestamp cannot be changed")}},bs=async(t,e,n,s,r)=>{if(!xe("Read",r.collections?.[e.labels.collection]))return!1;try{await Be([e.labels.collection],n,{userId:s,providedTransaction:t})}catch{return!1}return!0},pu=10,yu=async(t,e)=>{if(t.length===0)return;const n=Math.min(e,t.length);let s=0;const r=async()=>{for(;s<t.length;){const i=s;s+=1,await t[i]()}};await Promise.all(Array.from({length:n},r))},Jo=async(t,e,n,s,r,i,o)=>{for(const[a,l]of Object.entries(e?.collections||{})){if(!r.collections[a])throw new Error("PERMISSION_DENIED");const c=r.collections[a].access,d=r.collections[a];if(s.collections?.[a]?.restrictEntities||s?.collections?.[a]?.recordOwner?.active||s?.collections?.[a]?.recordUser?.active||s?.collections?.[a]?.recordProperty?.active){const u=i?.collections?.[a],f=[];if(l.individualEntities){const g=l.individualEntities,k=u?.individualEntities||[],y=i?g.filter(E=>!k.includes(E)):g;for(const E of y){if(o&&o.size++,o&&o.size>500)throw new 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 bs(t,d,E,n,s))throw new Error("PERMISSION_DENIED")})}}if(l.parentEntities){const g=c.entityRestrictions?.restrictions?.find(O=>O.type==="Parent"&&O.roles.some(_=>_.role===e.Role));if(!g)throw new Error("PERMISSION_DENIED");const k=L(d.fields,g.collectionField),y=r.collections[k.collection],E=l.parentEntities,w=u?.parentEntities||[],A=i?E.filter(O=>!w.includes(O)):E;for(const O of A){if(o&&o.size++,o&&o.size>500)throw new 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 bs(t,y,O,n,s))throw new Error("PERMISSION_DENIED")})}}if(l.parentPropertyEntities){const g=c.entityRestrictions?.restrictions?.find(A=>A.type==="Parent_Property"&&A.roles.some(O=>O.role===e.Role));if(!g)throw new Error("PERMISSION_DENIED");const k=L(d.fields,g.collectionField),y=r.collections[k.collection],E=l.parentPropertyEntities,w=u?.parentPropertyEntities||{};for(const[A,O]of Object.entries(E)){const _=w[A]||[],I=i?O.filter(j=>!_.includes(j)):O;for(const j of I){if(o&&o.size++,o&&o.size>500)throw new 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 bs(t,y,j,n,s))throw new Error("PERMISSION_DENIED")})}}}await yu(f,pu)}}},gu=async(t,e,n)=>{const s=n?.userId,r=n?.user;let i=n?.context;const o=Je(),a=It();if(n?.providedTransaction&&s)throw new Error("PERMISSION_DENIED");if(n?.providedSchema&&s)throw new Error("PERMISSION_DENIED");let l=n?.providedSchema||await Ye();if(t.length===0)throw new Error("EMPTY_PATH");const c=t.at(-1),d=Object.keys(l.collections).includes(c),p=a.disabledCollections?.includes(c);if(!d||p)throw new Error("COLLECTION_NOT_FOUND");const u=l.collections[c],{labels:f,fields:g,enableWriteLog:k,softDelete:y}=u,E=rt(f.collection,l),w=await ae(a.appName),A=fe(),O=bt.getAuth(),_=s?await O.getUser(s):void 0;let I,j;s&&await pr(t,u);const v=Ne(A,t,o),U=n?.id||v.doc().id;i=i||{},i.collection=f.collection,e.id=U,yr(e),is(e);const h=Js("create",t,e,l,w,"Online",s||"System",oe.Timestamp.now(),oe.FieldValue.serverTimestamp());n?.createdAt&&(h.Created_At=n.createdAt),n?.createdBy&&(h.Created_By=n.createdBy);const x=pe(h);y&&(h[y.archivedField]=!1),Ze(e),wt(u,h,l),k&&!n?.providedTransaction&&await kt("create","started",h,o,t,U,u),await ce("preOperation",a,E,{operation:"create",data:h,recordId:U,context:i}),await ce("preWrite",a,E,{operation:"create",data:h,recordId:U,context:i}),wt(u,h,l),Mn(u,h);const m=(s?await A.collection("tenants").doc(o).collection("system_user_permissions").doc(s).get():void 0)?.data();await ba(h,u,E,m,_?.customClaims||{}),Ze(h);try{if(u.auth&&r){if(!r.password)throw new Error("Password is required");if(!h.Role)throw new Error("Role field is required");if(!h.Email)throw new Error("Email field is required");if(h.Enabled===void 0||h.Enabled===null)throw new Error("Enabled field is required")}n?.providedTransaction||await hn("create",h,u,E,{operation:"create",data:h,context:i},l)}catch(D){throw new Error(`VALIDATION_ERROR: ${D.message}`)}Ze(h),e.id=U,y&&(h[y.archivedField]=!1),wt(u,h,l),Mn(u,h);try{Yo("create",h,x),wr("create",u,h),await hn("create",h,u,E,{operation:"create",data:h,context:i},l)}catch(D){throw new Error(`VALIDATION_ERROR: ${D.message}`)}if(s){if(!_)throw new Error("USER_ERROR");if(!m?.Role)throw new Error("USER_ERROR");const D=m;if(!(E.custom?.serverAccess?.create!==void 0?await ae(E.custom.serverAccess.create,[D,_,h]):!0))throw new Error("PERMISSION_DENIED");for(const H of u.fields){if(!(H.name in h))continue;const C=We(H,E);if(C?.custom?.serverAccess?.create!==void 0&&!await ae(C.custom.serverAccess.create,[D,_,h]))throw new Error("PERMISSION_DENIED")}}r&&(r.permissions||={},r.permissions.Role||=h.Role,r.permissions.Enabled||=h.Enabled);const T=async(D,M)=>{const[H,C,B,S,Q]=await Promise.all([n?.providedTransaction?Promise.resolve({}):D.get(A.collection("system_deployment").doc("latest_deploy")),n?.providedTransaction?Promise.resolve({}):D.get(A.collection("system_deployment").doc("maintenance_mode")),s?D.get(A.collection("tenants").doc(o).collection("system_user_permissions").doc(s)):Promise.resolve({}),n?.providedSchema?Promise.resolve(n.providedSchema):Ye(),s?Ht(s):Promise.resolve(void 0)]);if(M&&(M.size+=3),!n?.providedTransaction){if(!H.exists)throw new Error("VERSION_ERROR");const ee=H.data();if(ee.force&&h.Last_Write_At.valueOf()<ee.time.valueOf())throw new Error("VERSION_ERROR");if(!C.exists)throw new Error("MAINTENANCE_MODE");if(C.data().active)throw new Error("MAINTENANCE_MODE")}if(l=S,s){if(!B?.exists)throw new Error("PERMISSION_DENIED");if(I=B.data(),!I.Role)throw new Error("USER_ERROR");if(!I.Enabled)throw new Error("PERMISSION_DENIED");j=Q?.customClaims??{}}if(!n?.providedTransaction){const ye=g.filter(le=>"unique"in le&&le.unique).map(async le=>{if(!s||!le.access||He(le,I,u,j)){if(!h[le.name])return;const Qe=We(le,E);if(!(s&&I&&Q&&Qe?.custom?.serverAccess?.read!==void 0?await ae(Qe.custom.serverAccess.read,[I,Q,h]):!0))throw new Error("PERMISSION_DENIED");const De=h[le.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Vo(De)){if(M&&M.size++,M&&M.size>500)throw new 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 D.get(A.collection("tenants").doc(o).collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${le.name}`).doc(De)))?.exists)throw new Error(`VALIDATION_ERROR: ${le.name} "${h[le.name]}" already exists`)}else throw new Error(`VALIDATION_ERROR: ${le.name} "${h[le.name]}" is invalid`)}});await Promise.all(ye)}kr(h,U,u,l,s,I,r?.permissions,j),r?.permissions&&s&&I&&await Jo(D,r.permissions,s,I,l),kr(h,U,u,l,s,I,r?.permissions,j)};if(u.auth&&r){await A.runTransaction(async M=>{await T(M)},{maxAttempts:10});const D=await mr(o,U,a,u,h,r.permissions,r.password);h.User_ID=D}const b=async D=>{try{const M={size:1};await T(D,M),n?.noTwoWay||await gr("Create",o,U,h,h,u,l,D,M,s,I,void 0,j);const H=Ys(l);or("create",D,t,U,h,l,u,n,H,oe.FieldValue.arrayUnion,oe.FieldValue.arrayRemove,oe.FieldValue.delete,C=>A.collection("tenants").doc(o).collection("system_fields").doc(f.collection).collection(`${f.collection}-${C.name}`).doc(U),(C,B)=>A.collection("tenants").doc(o).collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${C.name}`).doc(B),C=>A.collection("tenants").doc(o).collection("system_fields").doc(f.collection).collection(`${f.collection}-${C}`).doc(U),(C,B)=>Ne(A,C,o).doc(B),(C,B,S)=>A.collection("tenants").doc(o).collection("system_fields").doc(C.collection).collection(`${C.collection}-${B}`).doc(S),(C,B,S)=>A.collection("tenants").doc(o).collection("system_fields").doc(C.collection).collection(`${C.collection}-${B.replaceAll(" ","-")}`).doc(S),void 0,void 0,M),D.set(v.doc(U),h)}catch(M){if(n?.providedTransaction)throw M;{const C=await ce("postWriteError",a,E,{operation:"create",data:h,recordId:U,context:i,error:M});if(k&&(await new Promise(B=>{setTimeout(B,250)}),await kt("create",C?.resolved?"success":"failed",h,o,t,U,u,C?.resolved?void 0:M)),!C?.resolved)throw u.auth&&r&&await Gt(h),M}}};if(n?.providedTransaction?await b(n.providedTransaction):await A.runTransaction(async D=>{await b(D)},{maxAttempts:10}),!n?.providedTransaction){const D={operation:"create",data:h,recordId:U,context:i},M={...D};await ce("postWrite",a,E,D),await ce("postOperation",a,E,M)}return{id:U,...h}},rn=async(t,e,n,s)=>{const r=Je(),i=bt.getAuth(),o=fe(),a=e.customClaims||{};let l=!1;try{await i.updateUser(t,{email:e.email,disabled:e.disabled,displayName:e.displayName,photoURL:e.photoURL,emailVerified:!!e.emailVerified})}catch{l=!0}try{await i.setCustomUserClaims(t,{...a})}catch{l=!0}try{await o.collection("tenants").doc(r).collection("system_user_permissions").doc(t).update({...n,Collection:a.collection,Doc_ID:a.doc,Role:a.role,Enabled:!e.disabled})}catch{l=!0}if(l)throw new Error(`ROLLBACK_FAILED: ${s}`)},Qo=async(t,e,n,s,r,i,o,a,l,c,d)=>{const p=bt.getAuth(),u=fe(),f={};for(const y of r.fields)y.saveToAuthToken&&!hr(y.name)&&i[y.name]!==void 0&&y.type!=="Timestamp"&&y.type!=="Computed"&&y.type!=="Embedding"&&(be(i[y.name])?f[y.name]=null:f[y.name]=i[y.name]);const g="USER_ERROR";let k="";if(t==="create"){if(!d)throw new Error("VALIDATION_ERROR: Password is required");if(!l)throw new Error("VALIDATION_ERROR: Permissions are required");try{k=await mr(e,n,s,r,i,l,d)}catch(y){throw new Error(y.message)}}else if(t==="update"){if(!c||!a)throw new Error("USER_ERROR");const y={};if(o.Name!==i.Name&&(y.displayName=i.Name),o.Email!==i.Email&&(y.email=i.Email,y.emailVerified=!1),o.Photo_URL!==i.Photo_URL&&(y.photoURL=i.Photo_URL?i.Photo_URL:void 0),o.Enabled!==i.Enabled&&(y.disabled=!i.Enabled),d&&(y.password=d),Object.keys(y).length)try{await p.updateUser(o.User_ID,y),y.disabled===!0&&await p.revokeRefreshTokens(o.User_ID)}catch{throw await rn(o.User_ID,a,c,g),new Error(g)}if(i.Role&&i.Role!==o.Role||Object.keys(f).length)try{const E={...du(a.customClaims),...f};await p.setCustomUserClaims(o.User_ID,{...E,tenant:e,role:i.Role,collection:r.labels.collection,doc:n}),await p.revokeRefreshTokens(o.User_ID)}catch{throw await rn(o.User_ID,a,c,g),new Error(g)}try{await u.collection("tenants").doc(e).collection("system_user_permissions").doc(o.User_ID).set({...l||c,Collection:r.labels.collection,Doc_ID:n,Role:i.Role,Enabled:i.Enabled??o.Enabled??!1})}catch{throw await rn(o.User_ID,a,c,g),new Error(g)}if(o.Email!==i.Email){const E=s.auth.enableMultiFactorAuth;if(E===!0||typeof E=="object"&&E.includes(i.Role)){let w=await p.generateEmailVerificationLink(i.Email).catch(()=>{throw new Error("Error generating email verification link")});if(w.includes("apiKey=&")){const A=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);w=w.replace("apiKey=&",`apiKey=${A.apiKey}&`)}if(w){const A=`https://${p.app.options.projectId}.firebaseapp.com/__/auth/action${w}`,O=await ae(s.appName),_=s?.mail?.emailVerification&&s.mail.emailVerification(A,O);try{await fr(i.Email,_?.subject||"Please verify your email address",void 0,_?.html||`Please verify your email address by clicking the link:
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:
12
8
  </br>
13
9
  </br>
14
- <a href="${A}">${A}</a>`)}catch{throw await rn(o.User_ID,a,c,g),new Error(g)}}}}}else if(t==="delete")try{await Gt(o)}catch(y){throw new Error(y.message)}if(k)return k},wu=async(t,e,n)=>{const s=Je(),r=fe(),i=[e];n&&n.trim()!==""&&i.push(n),i.sort();const o=[];for(const a of i){const l=r.collection("tenants").doc(s).collection("system_locks").doc(a);if((await t.get(l)).exists)throw new Error("DOCUMENT_LOCKED");o.push(l)}for(const a of o)t.set(a,{locked:!0})},_i=async(t,e)=>{const n=Je(),s=fe(),r=[t];e&&e.trim()!==""&&r.push(e),r.sort();const i=s.batch();for(const o of r){const a=s.collection("tenants").doc(n).collection("system_locks").doc(o);i.delete(a)}await i.commit()},Ko=async(t,e,n,s)=>{const r=s?.userId;let i=s?.user,o=s?.context;const a=Je(),l=It();if(s?.providedTransaction&&r)throw new Error("PERMISSION_DENIED");if(s?.providedSchema&&r)throw new Error("PERMISSION_DENIED");if(s?.providedTransaction&&!s?.originalRecord)throw new Error("PERMISSION_DENIED");let c=s?.providedSchema||await Ye(!0);if(t.length===0)throw new Error("EMPTY_PATH");const d=t.at(-1),p=Object.keys(c.collections).includes(d),u=l.disabledCollections?.includes(d);if(!p||u)throw new Error("COLLECTION_NOT_FOUND");const f=c.collections[d],{labels:g,fields:k,enableWriteLog:y}=f,E=rt(g.collection,c),w=await ae(l.appName),A=bt.getAuth(),O=fe();let _,I;r&&await pr(t,f);const j=Ne(O,t,a);o=o||{},o.collection=g.collection;let v=s?.originalRecord||await Be(t,e,{userId:r,noComputedFields:!0,noEmbeddingFields:!0}),U=v;r&&(U=await Be(t,e,{noComputedFields:!0,noEmbeddingFields:!0}));for(const S of k)S.type==="Computed"&&(delete n[S.name],delete v[S.name]);if(c={...c,collections:Object.fromEntries(Object.entries(c.collections).map(([S,Q])=>[S,{...Q,fields:Q.fields.filter(ee=>ee.type!=="Computed")}]))},i&&!i.operation)throw new Error("VALIDATION_ERROR: User operation is required");if(i&&!f.auth)throw new Error("VALIDATION_ERROR: User operations are only permitted for auth collections");if(i?.operation==="delete"&&i.permissions)throw new Error("VALIDATION_ERROR: Permissions are not allowed for delete operations");const h=f.fields.filter(S=>S.saveToAuthToken&&!hr(S.name)),x=f.auth&&i?.operation==="create",R=f.auth&&i?.operation==="delete",q=f.auth&&!x&&!R&&(i?.operation==="update"||v.User_ID&&(n.Role||n.Enabled!==void 0||n.Name||n.Email||n.Photo_URL||h.some(S=>n[S.name]!==void 0))),Z=S=>S.User_ID&&(f.auth&&!x&&!R&&i?.operation==="update"||n.Role&&n.Role!==S.Role||n.Enabled!==void 0&&n.Enabled!==S.Enabled||n.Name&&n.Name!==S.Name||n.Email&&n.Email!==S.Email||n.Photo_URL&&n.Photo_URL!==S.Photo_URL||h.some(Q=>n[Q.name]!==void 0&&n[Q.name]!==S[Q.name]));delete n.id,yr(n),is(n);const m=Js("update",t,n,c,w,"Online",r||"System",oe.Timestamp.now(),oe.FieldValue.serverTimestamp()),T=pe(m);for(const S of k)!X(S)&&be(m[S.name])&&S.nullable&&(m[S.name]=null);Ze(m),Ze(v),wt(f,m,c),wt(f,v,c),y&&!s?.providedTransaction&&await kt("update","started",m,a,t,e,f,void 0,v);const b={operation:"update",data:m,recordId:e,context:o,originalRecord:pe(v)};await ce("preOperation",l,E,b);const F={operation:"update",data:m,recordId:e,context:o,originalRecord:pe(v)};await ce("preWrite",l,E,F),wt(f,m,c),Mn(f,m),Ze(m);try{if(x&&!i?.password)throw new Error("Password is required");if(!s?.providedTransaction){const S={...U,...m};et(S),await hn("update",S,f,E,{operation:"update",data:m,context:o,originalRecord:pe(v)},c)}}catch(S){throw new Error(`VALIDATION_ERROR: ${S.message}`)}Ze(m),delete n.id,wt(f,m,c),Mn(f,m);for(const S of k)!X(S)&&be(m[S.name])&&S.nullable&&(m[S.name]=null);try{const S={...U,...m};et(S),wr("update",f,m,v),Yo("update",m,T),await hn("update",S,f,E,{operation:"update",data:m,context:o,originalRecord:pe(v)},c)}catch(S){throw new Error(`VALIDATION_ERROR: ${S.message}`)}let D;i&&(i.permissions||={});const M=async(S,Q,ee)=>{const[ye,le,Qe,ge,De,Ce]=await Promise.all([s?.providedTransaction?Promise.resolve({}):S.get(O.collection("system_deployment").doc("latest_deploy")),s?.providedTransaction?Promise.resolve({}):S.get(O.collection("system_deployment").doc("maintenance_mode")),s?.providedTransaction?Promise.resolve(v):Be(t,e,{userId:r,providedTransaction:S,noComputedFields:!0}),r?S.get(O.collection("tenants").doc(a).collection("system_user_permissions").doc(r)):Promise.resolve({}),s?.providedSchema?Promise.resolve(s.providedSchema):Ye(),r?Ht(r):Promise.resolve(void 0)]);if(ee&&(ee.size+=3),!s?.providedTransaction){if(!ye.exists)throw new Error("VERSION_ERROR");const we=ye.data();if(we.force&&m.Last_Write_At.valueOf()<we.time.valueOf())throw new Error("VERSION_ERROR");if(!le.exists)throw new Error("MAINTENANCE_MODE");if(le.data().active)throw new Error("MAINTENANCE_MODE")}if(!Qe)throw new Error("NOT_FOUND");if(v=Qe,c=De,r){if(!ge?.exists)throw new Error("PERMISSION_DENIED");if(_=ge.data(),!_.Role)throw new Error("USER_ERROR");if(!_.Enabled)throw new Error("PERMISSION_DENIED");I=Ce?.customClaims??{}}if(ee&&(ee.size+=cr(a,t,e,c,_,I).length),x&&v.User_ID||R&&!v.User_ID)throw new Error("USER_ERROR");if(Z(v)){const we=await S.get(O.collection("tenants").doc(a).collection("system_user_permissions").doc(v.User_ID));if(ee&&ee.size++,!we?.exists)throw new Error("PERMISSION_DENIED");D=we.data();const Yt=i?.permissions&&Object.keys(i.permissions).length>0?i.permissions:void 0;if(m.Role&&m.Role!==v.Role&&!Yt&&(i||={operation:"update",permissions:{}},i.permissions=pe(D),i.permissions.Role=m.Role),i?.permissions){if(i.permissions.Role||=m.Role||v.Role,i.permissions.Enabled??=m.Enabled??v.Enabled,be(i.permissions.Role)||!i.permissions.Role)throw new Error("VALIDATION_ERROR: Role field is required");if(be(i.permissions.Enabled)||i.permissions.Enabled===void 0||i.permissions.Enabled===null)throw new Error("VALIDATION_ERROR: Enabled field is required")}}if(x){const we={...v,...m};if(et(we),!we.Role)throw new Error("VALIDATION_ERROR: Role field is required");if(we.Enabled===void 0||we.Enabled===null)throw new Error("VALIDATION_ERROR: Enabled field is required");if(!we.Email)throw new Error("VALIDATION_ERROR: Email field is required");i?.permissions&&(i.permissions.Role||=we.Role,i.permissions.Enabled??=we.Enabled)}if(!s?.providedTransaction){const Yt=k.filter(_e=>"unique"in _e&&_e.unique).map(async _e=>{if(!r||!_e.access||He(_e,_,f,I)){if(m[_e.name]===void 0||be(m[_e.name]))return;const Jt=We(_e,E),_r={...v,...m};if(!(r&&_&&Ce&&Jt?.custom?.serverAccess?.read!==void 0?await ae(Jt.custom.serverAccess.read,[_,Ce,_r]):!0))throw new Error("PERMISSION_DENIED");const Er=m[_e.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Vo(Er)){if(ee&&ee.size++,ee&&ee.size>500)throw new 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.");const vr=await S.get(O.collection("tenants").doc(a).collection("system_unique").doc(g.collection).collection(`Unique-${g.collection}-${_e.name}`).doc(Er));if(vr.exists&&vr.data().id!==e)throw new Error(`VALIDATION_ERROR: ${_e.name} "${m[_e.name]}" already exists`)}else throw new Error(`VALIDATION_ERROR: ${_e.name} "${m[_e.name]}" is invalid`)}});await Promise.all(Yt)}if(r&&_?.Role){if(!Ce)throw new Error("USER_ERROR");const we={...v,...m};if(!(E.custom?.serverAccess?.update!==void 0?await ae(E.custom.serverAccess.update,[_,Ce,we,v]):!0))throw new Error("PERMISSION_DENIED");for(const _e of f.fields){const Jt=We(_e,E);if(Object.prototype.hasOwnProperty.call(m,_e.name)&&Jt?.custom?.serverAccess?.update!==void 0&&!await ae(Jt.custom.serverAccess.update,[_,Ce,we,v]))throw new Error("PERMISSION_DENIED")}}br(m,v,e,f,c,r,_,i?.operation?i.operation:q?"update":void 0,i?.permissions,D,I),i?.permissions&&r&&_&&await Jo(S,i.permissions,r,_,c,D,ee),br(m,v,e,f,c,r,_,i?.operation?i.operation:q?"update":void 0,i?.permissions,D,I),Q&&(x||Z(v)||R)&&await wu(S,e,v.User_ID)};(x||q||R)&&await O.runTransaction(async S=>{await M(S,!0)},{maxAttempts:10});const H=async(S,Q)=>{if(!v)throw new Error("NOT_FOUND");try{const ee={size:1},ye={...v,...m};await M(S,!1,ee);let le;!s?.noTwoWay&&!s?.providedTransaction&&(le=await gr("Update",a,e,ye,m,f,c,S,ee,r,_,v,I));const Qe=Ys(c);or("update",S,t,e,m,c,f,s,Qe,oe.FieldValue.arrayUnion,oe.FieldValue.arrayRemove,oe.FieldValue.delete,ge=>O.collection("tenants").doc(a).collection("system_fields").doc(g.collection).collection(`${g.collection}-${ge.name}`).doc(e),(ge,De)=>O.collection("tenants").doc(a).collection("system_unique").doc(g.collection).collection(`Unique-${g.collection}-${ge.name}`).doc(De),ge=>O.collection("tenants").doc(a).collection("system_fields").doc(g.collection).collection(`${g.collection}-${ge}`).doc(e),(ge,De)=>Ne(O,ge,a).doc(De),(ge,De,Ce)=>O.collection("tenants").doc(a).collection("system_fields").doc(ge.collection).collection(`${ge.collection}-${De}`).doc(Ce),(ge,De,Ce)=>O.collection("tenants").doc(a).collection("system_fields").doc(ge.collection).collection(`${ge.collection}-${De.replaceAll(" ","-")}`).doc(Ce),v,le,ee),S.update(j.doc(e),m)}catch(ee){if(s?.providedTransaction)throw ee;{const ye={operation:"update",data:m,recordId:e,context:o,error:ee,originalRecord:pe(v)},le=await ce("postWriteError",l,E,ye);if(y&&(await new Promise(Qe=>{setTimeout(Qe,250)}),await kt("update",le?.resolved?"success":"failed",m,a,t,e,f,le?.resolved?void 0:ee,v)),!le?.resolved)throw x&&await Gt(v),Z(v)&&await rn(v.User_ID,Q,D,"USER_ERROR"),R&&await O.collection("tenants").doc(a).collection(g.collection).doc(e).update({User_ID:oe.FieldValue.delete()}),ee}}(x||Z(v)||R)&&await pi(_i,[e,v.User_ID]).catch(()=>{throw new Error("USER_ERROR")})};try{let S;if(x||Z(v)||R){if(Z(v)){S=await A.getUser(v.User_ID);const ye=S.customClaims;if(!(ye&&ye.role&&ye.collection&&ye.doc))throw new Error("USER_ERROR")}const Q={...v,...m};et(Q);const ee=await Qo(i?.operation||"update",a,e,l,f,Q,v,S,i?.permissions,D,i?.password);x&&(m.User_ID=ee),R&&(m.User_ID=oe.FieldValue.delete())}s?.providedTransaction?await H(s.providedTransaction,S):await O.runTransaction(async Q=>{await H(Q,S)},{maxAttempts:10})}catch(S){throw(x||Z(v)||R)&&await pi(_i,[e,v.User_ID]).catch(()=>{throw new Error("USER_ERROR")}),S}if(!s?.providedTransaction){const S={operation:"update",data:m,recordId:e,context:o,originalRecord:pe(v)},Q={...S};await ce("postWrite",l,E,S),await ce("postOperation",l,E,Q)}const C={...v,...m};return et(C),{id:e,...C}},_u=async(t,e,n)=>{const s=n?.userId;let r=n?.context;const i=Je(),o=It();let a=await Ye();if(t.length===0)throw new Error("EMPTY_PATH");const l=t.at(-1),c=Object.keys(a.collections).includes(l),d=o.disabledCollections?.includes(l);if(!c||d)throw new Error("COLLECTION_NOT_FOUND");const p=a.collections[l],{labels:u,auth:f,enableWriteLog:g,softDelete:k}=p,y=rt(u.collection,a),E=await ae(o.appName);if(k&&!f&&!n?.force)return await Ko(t,e,{[k.archivedField]:!0,[k.timestampField]:oe.FieldValue.serverTimestamp()},{userId:s});const w=fe();let A;s&&await pr(t,p);const O=Ne(w,t,i);r=r||{},r.collection=u.collection;const _=await Be(t,e,{userId:s});let I=Js("delete",t,_,a,E,"Online",s||"System",oe.Timestamp.now(),oe.FieldValue.serverTimestamp());const j=$n(I);Ze(I),g&&await kt("delete","started",I,i,t,e,p),await ce("preOperation",o,y,{operation:"delete",data:I,recordId:e,context:r}),await ce("preWrite",o,y,{operation:"delete",data:I,recordId:e,context:r}),Ze(I);const h=async Z=>{const[m,T,b,F,D]=await Promise.all([Z.get(w.collection("system_deployment").doc("maintenance_mode")),Be(t,e,{userId:s,providedTransaction:Z}),s?Z.get(w.collection("tenants").doc(i).collection("system_user_permissions").doc(s)):Promise.resolve({}),Ye(),s?Ht(s):Promise.resolve(void 0)]);if(!m.exists)throw new Error("MAINTENANCE_MODE");if(m.data().active)throw new Error("MAINTENANCE_MODE");if(!T)throw new Error("NOT_FOUND");if(I={...T,...j},a=F,s){if(!b?.exists)throw new Error("PERMISSION_DENIED");if(A=b.data(),!A.Role)throw new Error("USER_ERROR");if(!A.Enabled)throw new Error("PERMISSION_DENIED");fa(I,e,p,a,s,A)}if(s&&A?.Role){if(!D)throw new Error("USER_ERROR");if(!(y.custom?.serverAccess?.delete!==void 0?await ae(y.custom.serverAccess.delete,[A,D,I]):!0))throw new Error("PERMISSION_DENIED")}};p.auth&&(await w.runTransaction(async Z=>{await h(Z)},{maxAttempts:10}),I.User_ID&&await Gt(I));try{await w.runTransaction(async Z=>{await h(Z);const m=Ys(a);or("delete",Z,t,e,I,a,p,n,m,oe.FieldValue.arrayUnion,oe.FieldValue.arrayRemove,oe.FieldValue.delete,T=>w.collection("tenants").doc(i).collection("system_fields").doc(u.collection).collection(`${u.collection}-${T.name}`).doc(e),(T,b)=>w.collection("tenants").doc(i).collection("system_unique").doc(u.collection).collection(`Unique-${u.collection}-${T.name}`).doc(b),T=>w.collection("tenants").doc(i).collection("system_fields").doc(u.collection).collection(`${u.collection}-${T}`).doc(e),(T,b)=>Ne(w,T,i).doc(b),(T,b,F)=>w.collection("tenants").doc(i).collection("system_fields").doc(T.collection).collection(`${T.collection}-${b}`).doc(F),(T,b,F)=>w.collection("tenants").doc(i).collection("system_fields").doc(T.collection).collection(`${T.collection}-${b.replaceAll(" ","-")}`).doc(F)),Z.delete(O.doc(e))},{maxAttempts:10})}catch(Z){const T=await ce("postWriteError",o,y,{operation:"delete",data:I,recordId:e,context:r,error:Z});if(g&&(await new Promise(b=>{setTimeout(b,250)}),await kt("delete",T?.resolved?"success":"failed",I,i,t,e,p,T?.resolved?void 0:Z)),!T?.resolved)throw p.auth&&I.User_ID&&await w.collection("tenants").doc(i).collection(u.collection).doc(e).update({User_ID:oe.FieldValue.delete()}),Z}const x={operation:"delete",data:I,recordId:e,context:r},R={...x};return await ce("postWrite",o,y,x),await ce("postOperation",o,y,R),{id:e,...I}},Eu=async(t,e)=>{const n=fe(),s=ar(),r=process.env.ADMIN_SMS;if(s==="development")if(r)t=r;else throw new Error("Admin phone not set");const i={to:t,body:e};await n.collection("system_messages").add(i)},vu=t=>t!==null&&typeof t=="object",Ou=t=>{const e=n=>{Object.entries(n).forEach(([s,r])=>{r instanceof oe.Timestamp?n[s]={_seconds:r.seconds,_nanoseconds:r.nanoseconds}:vu(r)&&e(r)})};e(t)},ku=t=>{const e=lr();return V.fromJSDate(t).setZone(e)},Xo=t=>{const e=lr();return V.fromJSDate(t.toDate()).setZone(e)},bu=(t,e)=>{const s=V.fromJSDate(t,{zone:e}).offset,i=V.fromJSDate(t).offset,o=s-i;return V.fromJSDate(t).plus({minutes:o}).toJSDate()},Ru=(t,e)=>{const s=V.fromJSDate(t,{zone:e}).offset,i=V.fromJSDate(t).offset,o=s-i;return V.fromJSDate(t).minus({minutes:o}).toJSDate()},Tu=t=>"seconds"in t&&"nanoseconds"in t?Xo(new oe.Timestamp(t.seconds,t.nanoseconds)).toFormat("MMMM d, yyyy '@' h:mm a"):"";exports.addRecord=gu;exports.addUser=mr;exports.convertDateToTimezone=ku;exports.convertTimestampToTimezone=Xo;exports.deleteRecord=_u;exports.deleteUser=Gt;exports.deserializeDeleteSentinels=is;exports.deserializeTimestamps=yr;exports.deserializeTimestampsWithoutUnderscores=fu;exports.displayDate=Tu;exports.fetchCurrentSchema=Ye;exports.fetchLastSchema=cu;exports.getCachedConfigValue=wa;exports.getCollectionRefs=zo;exports.getCustomizationFile=rt;exports.getCustomizationFiles=Uo;exports.getDocumentRefs=cr;exports.getFirestorePathRef=Ne;exports.getGlobalConfigModule=It;exports.getInputSchema=eu;exports.getMaintenanceInfo=ou;exports.getMode=ar;exports.getOne=Be;exports.getSome=dr;exports.getStokerFirestore=fe;exports.getTenant=Je;exports.getTimezone=lr;exports.getUser=Ht;exports.getVersionInfo=iu;exports.getZodSchema=$i;exports.initializeFirebase=lu;exports.initializeStoker=su;exports.isDeleteSentinel=be;exports.keepTimezone=bu;exports.removeTimezone=Ru;exports.runChildProcess=au;exports.sendMail=fr;exports.sendMessage=Eu;exports.serializeTimestamps=Ou;exports.setTenant=ru;exports.tryPromise=ae;exports.updateRecord=Ko;exports.updateUser=Qo;exports.validateRelations=gr;exports.validateSoftDelete=wr;exports.writeLog=kt;
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;