@lpdjs/firestore-repo-service 3.0.21 → 3.0.22

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/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import {jsx,jsxs,Fragment}from'hono/jsx/jsx-runtime';import {Timestamp,Filter,Query,FieldPath}from'firebase-admin/firestore';import {AsyncLocalStorage}from'async_hooks';import {randomUUID,randomBytes}from'crypto';import {z}from'zod';import {renderToString}from'hono/jsx/dom/server';import {extendZodWithOpenApi,OpenAPIRegistry,OpenApiGeneratorV31,getOpenApiMetadata}from'@asteasolutions/zod-to-openapi';import {Hono}from'hono';import {getRequestListener}from'@hono/node-server';var _n=Object.defineProperty;var Us=Object.getOwnPropertyDescriptor;var Ls=Object.getOwnPropertyNames;var Ks=Object.prototype.hasOwnProperty;var Kr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var St=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Zr=(e,t)=>{for(var n in t)_n(e,n,{get:t[n],enumerable:true});},Zs=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ls(t))!Ks.call(e,o)&&o!==n&&_n(e,o,{get:()=>t[o],enumerable:!(r=Us(t,o))||r.enumerable});return e};var Ws=e=>Zs(_n({},"__esModule",{value:true}),e);function J(e){let t=e,n=t._zod?.def?.type;if(n)return oi[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=t._def?.typeName;return r||""}function ye(e){let t=e;if(t._zod?.def?.innerType)return t._zod.def.innerType;if(t._def?.innerType)return t._def.innerType}function $t(e){let t=e,n=t._zod?.def?.in;if(n)return n;if(t._def?.schema)return t._def.schema}function pn(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}function Do(e){let t=e;if(t._zod?.def?.defaultValue!==void 0)return t._zod.def.defaultValue;let n=t._def?.defaultValue;return typeof n=="function"?n():n}function me(e){let t=e;return t.shape&&typeof t.shape=="object"?t.shape:t._zod?.def?.shape&&typeof t._zod.def.shape=="object"?t._zod.def.shape:t._def?.shape?typeof t._def.shape=="function"?t._def.shape():t._def.shape:{}}function Ht(e){let t=e;return Array.isArray(t.options)?t.options:t._zod?.def?.entries?Object.values(t._zod.def.entries):Array.isArray(t._def?.values)?t._def.values:[]}function _t(e){let t=e;return t._zod?.def?.entries?t._zod.def.entries:t.enum&&typeof t.enum=="object"?t.enum:t._def?.values&&typeof t._def.values=="object"?t._def.values:{}}function Mt(e){let t=e;return Array.isArray(t._zod?.def?.values)?t._zod.def.values[0]:t._def?.value}function Ft(e){let t=e;return Array.isArray(t.options)?t.options:Array.isArray(t._zod?.def?.options)?t._zod.def.options:Array.isArray(t._def?.options)?t._def.options:[]}function $o(e){let t=e,n=[],r=t._zod?.def?.checks;if(Array.isArray(r)){for(let s of r)s.format&&n.push(s.format);if(n.length>0)return n}let o=t._def?.checks;if(Array.isArray(o))for(let s of o)s.kind&&n.push(s.kind);return n}var oi,ft=St(()=>{"use strict";oi={string:"ZodString",number:"ZodNumber",bigint:"ZodBigInt",boolean:"ZodBoolean",date:"ZodDate",enum:"ZodEnum",nativeEnum:"ZodNativeEnum",literal:"ZodLiteral",object:"ZodObject",array:"ZodArray",optional:"ZodOptional",nullable:"ZodNullable",default:"ZodDefault",coerce:"ZodCoerce",union:"ZodUnion",undefined:"ZodUndefined",unknown:"ZodUnknown",any:"ZodAny",record:"ZodRecord"};});function Vo({val:e}){return jsx("span",{class:"text-sm text-base-content/80 font-mono tabular-nums whitespace-nowrap",children:e.toLocaleString()})}function Ci({message:e}){return jsx("span",{class:"tooltip tooltip-warning tooltip-right inline-flex align-middle ml-1 text-warning","data-tip":e,role:"img","aria-label":e,children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",class:"size-3.5",children:jsx("path",{d:"M12 2 1 22h22L12 2zm0 6 7.5 13h-15L12 8zm-1 4v4h2v-4h-2zm0 5v2h2v-2h-2z"})})})}function ht({val:e,mismatch:t}){let n=ur(e);return t?jsxs("span",{class:"inline-flex items-start gap-0.5",children:[n,jsx(Ci,{message:t})]}):n}function ur(e){if(e==null)return jsx("span",{class:"opacity-30 italic text-xs",children:"\u2014"});if(typeof e=="boolean")return e?jsx("span",{class:"badge badge-success badge-sm",children:"true"}):jsx("span",{class:"badge badge-error badge-sm",children:"false"});if(e instanceof Date)return jsx(Vo,{val:e});if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")return jsx(Vo,{val:e.toDate()});if(typeof e=="number")return jsx("span",{class:"text-sm font-mono tabular-nums",children:String(e)});if(Array.isArray(e))return e.length===0?jsx("span",{class:"text-xs text-base-content/30",children:"[]"}):jsxs("ul",{class:"list-none p-0 m-0 space-y-0.5 text-xs",children:[e.slice(0,8).map((n,r)=>jsx("li",{class:"break-all",children:ur(n)},r)),e.length>8&&jsxs("li",{class:"text-base-content/40 italic",children:["+",e.length-8," more\u2026"]})]});if(typeof e=="object"&&e!==null){let n=Object.entries(e);return n.length===0?jsx("span",{class:"text-xs text-base-content/30",children:"{}"}):jsxs("dl",{class:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 text-xs m-0",children:[n.slice(0,8).map(([r,o])=>jsxs(Fragment,{children:[jsx("dt",{class:"text-base-content/50 font-semibold whitespace-nowrap",children:r}),jsx("dd",{class:"break-all",children:ur(o)})]})),n.length>8&&jsxs("dt",{class:"col-span-2 text-base-content/40 italic",children:["+",n.length-8," more\u2026"]})]})}let t=String(e);return jsx("span",{class:"text-sm break-all",children:t})}var xn=St(()=>{"use strict";});function qt(e){if(!e)return "unknown";let t=pr(e);switch(J(t)){case "ZodString":return "string";case "ZodNumber":return "number";case "ZodBigInt":return "bigint";case "ZodBoolean":return "boolean";case "ZodDate":return "date";case "ZodArray":return "array";case "ZodObject":case "ZodRecord":return "object";case "ZodEnum":case "ZodNativeEnum":return "enum";case "ZodLiteral":return "literal";default:return "unknown"}}function pr(e){let t=J(e);if(t==="ZodOptional"||t==="ZodNullable"||t==="ZodDefault"){let n=ye(e);return n?pr(n):e}return e}function Ut(e,t){if(!e)return;let n=t.split("."),r=e;for(let o of n){if(!r)return;let s=pr(r);if(J(s)!=="ZodObject")return;r=me(s)[o];}return r}function Pi(e){return e==null?"null":e instanceof Date?"date":Array.isArray(e)?"array":typeof e=="string"?"string":typeof e=="boolean"?"boolean":typeof e=="bigint"?"bigint":typeof e=="number"?"number":typeof e=="object"?typeof e.toDate=="function"?"date":"object":"unknown"}function Lt(e,t){if(e==="unknown")return null;let n=Pi(t);return n==="null"?null:e==="enum"||e==="literal"?n==="string"||n==="number"?null:`Expected ${e} (string/number), got ${n}`:e===n||e==="number"&&n==="bigint"||e==="bigint"&&n==="number"?null:`Expected ${e}, got ${n}`}var fr=St(()=>{"use strict";ft();});var Yo={};Zr(Yo,{PanelMany:()=>Di,PanelOne:()=>Ii,RightPanel:()=>yr});function Ii({doc:e,repoName:t,basePath:n,schema:r,columns:o}){if(!e)return jsx("div",{class:"text-center py-12 text-base-content/50",children:"Document not found."});let s=String(e.docId??e.id??""),a=`${n}/${t}/${encodeURIComponent(s)}/edit`,l=Jo(r,o);return jsxs("div",{class:"space-y-4",children:[jsxs("div",{class:"flex items-center justify-between gap-2",children:[jsxs("div",{class:"text-xs text-base-content/60",children:[jsx("span",{class:"font-mono",children:t}),jsx("span",{class:"opacity-50",children:" \xB7 "}),jsx("span",{class:"font-mono break-all",children:s})]}),jsx("a",{href:a,class:"btn btn-sm btn-primary",children:"Edit \u2192"})]}),jsx("dl",{class:"grid grid-cols-[max-content_1fr] gap-x-4 gap-y-2 border border-base-300 rounded-box p-4 bg-base-100",children:o.map(c=>{let u=e[c],p=l[c],f=p?Lt(p,u):null;return jsxs(Fragment,{children:[jsx("dt",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide pt-0.5",children:c}),jsx("dd",{class:"min-w-0",children:jsx(ht,{val:u,mismatch:f})})]})})})]})}function Di({docs:e,repoName:t,basePath:n,fk:r,fv:o,columns:s,schema:a,pagination:l}){let c=`${n}/${t}?fv_${r}=${encodeURIComponent(o)}`,u=Jo(a,s);return jsxs("div",{class:"space-y-4",children:[jsxs("div",{class:"flex items-center justify-between gap-2",children:[jsxs("div",{class:"text-xs text-base-content/60",children:[jsx("span",{class:"font-mono",children:t}),jsx("span",{class:"opacity-50",children:" where "}),jsx("span",{class:"font-mono",children:r}),jsx("span",{class:"opacity-50",children:" = "}),jsx("span",{class:"font-mono break-all",children:o}),jsx("span",{class:"opacity-50",children:" \xB7 "}),jsxs("span",{children:[e.length," doc",e.length!==1?"s":""]})]}),jsx("a",{href:c,class:"btn btn-sm btn-outline",children:"Full view \u2192"})]}),jsx("div",{class:"overflow-x-auto rounded-box border border-base-300 bg-base-100",children:jsxs("table",{class:"table table-xs w-full",children:[jsx("thead",{children:jsxs("tr",{class:"bg-base-200/50",children:[s.map((p,f)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:p},f)),jsx("th",{})]})}),jsx("tbody",{children:e.length===0?jsx("tr",{children:jsx("td",{colspan:s.length+1,class:"text-center py-10 text-base-content/40",children:"No related documents"})}):e.map((p,f)=>{let b=String(p.docId??p.id??""),h=`${n}/${t}/${encodeURIComponent(b)}/edit`;return jsxs("tr",{class:"hover",children:[s.map((w,T)=>{let S=p[w],I=u[w],A=I?Lt(I,S):null;return jsx("td",{class:"align-top py-1.5",children:jsx(ht,{val:S,mismatch:A})},T)}),jsx("td",{class:"text-right py-1.5",children:jsx("a",{href:h,class:"btn btn-xs btn-ghost",children:"Edit"})})]},f)})})]})}),(l.hasPrev||l.hasNext)&&jsxs("div",{class:"flex justify-center items-center gap-2",children:[l.hasPrev?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"prev","data-cursor":l.prevCursor,children:"\u2190 Previous"}):jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"\u2190 Previous"}),l.hasNext?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"next","data-cursor":l.nextCursor,children:"Next \u2192"}):jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"Next \u2192"})]})]})}function Jo(e,t){if(!e)return {};let n={};for(let r of t)n[r]=qt(Ut(e,r));return n}var yr,mr=St(()=>{"use strict";xn();fr();yr=({basePath:e=""})=>jsxs("div",{class:"fixed inset-0 z-[100] hidden pointer-events-none","data-frs-panel-root":!0,"data-frs-base-path":e,"aria-hidden":"true",children:[jsx("div",{class:"absolute inset-0 bg-black/30 opacity-0 transition-opacity duration-200 pointer-events-auto","data-frs-panel-backdrop":!0}),jsxs("aside",{class:"absolute top-0 right-0 h-full w-full md:w-1/2 bg-base-100 shadow-2xl border-l border-base-300 translate-x-full transition-transform duration-200 pointer-events-auto flex flex-col","data-frs-panel":!0,role:"dialog","aria-label":"Relation preview",children:[jsxs("header",{class:"flex items-center justify-between px-5 py-3 border-b border-base-300 bg-base-200/40 shrink-0",children:[jsx("h2",{class:"font-semibold text-base truncate","data-frs-panel-title":!0,children:"Relation"}),jsx("button",{type:"button",class:"btn btn-sm btn-ghost btn-circle","data-frs-panel-close":!0,"aria-label":"Close panel",children:"\u2715"})]}),jsx("div",{class:"flex-1 overflow-auto p-5 text-sm","data-frs-panel-body":!0,children:jsx("div",{class:"flex items-center justify-center py-12 text-base-content/40",children:jsx("span",{class:"loading loading-spinner loading-md"})})})]})]});});var fs={};Zr(fs,{DEFAULT_HTML_CSP:()=>Er,securityHeaders:()=>Tn});function Tn(e={}){let t=e.csp===void 0?Er:e.csp,n=e.frameOptions===void 0?"DENY":e.frameOptions,r=e.referrerPolicy===void 0?"no-referrer":e.referrerPolicy,o=e.cacheControl===void 0?"private, no-store":e.cacheControl;return async(s,a,l)=>{typeof a?.setHeader=="function"&&(a.setHeader("X-Content-Type-Options","nosniff"),n&&a.setHeader("X-Frame-Options",n),r&&a.setHeader("Referrer-Policy",r),o&&a.setHeader("Cache-Control",o),t&&a.setHeader("Content-Security-Policy",t)),await l();}}var us,ps,Er,kn=St(()=>{"use strict";us="https://cdn.jsdelivr.net",ps="https://www.gstatic.com",Er=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${us} ${ps}`,`style-src 'self' 'unsafe-inline' ${us}`,`connect-src 'self' ${ps} https://*.googleapis.com https://*.firebaseio.com https://identitytoolkit.googleapis.com`,"img-src 'self' data:","font-src 'self' data:","frame-ancestors 'none'","base-uri 'self'","form-action 'self'"].join("; ");});var Qs=30,Vs=99,Xt="__name__",Gs=new Set(["<","<=",">",">=","!=","not-in"]);var Js=55296,Ys=57343;function Qr(e){return e>=Js&&e<=Ys}function lt(e,t){let n=Math.min(e.length,t.length);for(let r=0;r<n;r++){let o=e.charCodeAt(r),s=t.charCodeAt(r);if(o!==s){let a=Qr(o),l=Qr(s);return a===l?o<s?-1:1:a?1:-1}}return e.length<t.length?-1:e.length>t.length?1:0}function Vr(e){return e.length>6&&e.startsWith("__id")&&e.endsWith("__")&&/^-?\d+$/.test(e.slice(4,-2))}function Xs(e,t){let n=Vr(e),r=Vr(t);if(n&&!r)return -1;if(!n&&r)return 1;if(n&&r){let o=BigInt(e.slice(4,-2)),s=BigInt(t.slice(4,-2));return o<s?-1:o>s?1:0}return lt(e,t)}function to(e,t){let n=e.split("/"),r=t.split("/"),o=Math.min(n.length,r.length);for(let s=0;s<o;s++){let a=Xs(n[s],r[s]);if(a!==0)return a}return n.length<r.length?-1:n.length>r.length?1:0}function ea(e,t){let n=e.split("."),r=t.split("."),o=Math.min(n.length,r.length);for(let s=0;s<o;s++){let a=lt(n[s],r[s]);if(a!==0)return a}return n.length<r.length?-1:n.length>r.length?1:0}function vt(e,t){return e<t?-1:e>t?1:e===t?0:Number.isNaN(e)?Number.isNaN(t)?0:-1:1}function Mn(e){if(e instanceof Date){let t=e.getTime();if(Number.isNaN(t))return {seconds:Number.NaN,nanos:0};let n=Math.floor(t/1e3),r=(t%1e3+1e3)%1e3;return {seconds:n,nanos:r*1e6}}if(typeof e=="object"&&e!==null){let t=e;if(typeof t.seconds=="number"&&typeof t.nanoseconds=="number"&&typeof t.toDate=="function")return {seconds:t.seconds,nanos:t.nanoseconds};if(typeof t._seconds=="number"&&typeof t._nanoseconds=="number"&&Object.keys(t).length===2)return {seconds:t._seconds,nanos:t._nanoseconds}}return null}function ta(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.path=="string"&&typeof t.id=="string"&&typeof t.firestore=="object"&&t.firestore!==null}function na(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.latitude=="number"&&typeof t.longitude=="number"&&typeof t.isEqual=="function"}function Gr(e){if(e===void 0)return -1;if(e===null)return 0;let t=typeof e;return t==="boolean"?1:t==="number"||t==="bigint"?2:t==="string"?4:e instanceof Uint8Array?5:Mn(e)!==null?3:ta(e)?6:na(e)?7:Array.isArray(e)?8:9}function ra(e,t){let n=Math.min(e.length,t.length);for(let r=0;r<n;r++){let o=e[r],s=t[r];if(o!==s)return o<s?-1:1}return e.length<t.length?-1:e.length>t.length?1:0}function Fn(e,t){let n=Gr(e),r=Gr(t);if(n!==r)return n<r?-1:1;switch(n){case -1:case 0:return 0;case 1:return e===t?0:e?1:-1;case 2:return vt(Number(e),Number(t));case 3:{let o=Mn(e),s=Mn(t),a=vt(o.seconds,s.seconds);return a!==0?a:vt(o.nanos,s.nanos)}case 4:return lt(e,t);case 5:return ra(e,t);case 6:return to(e.path,t.path);case 7:{let o=e,s=t,a=vt(o.latitude,s.latitude);return a!==0?a:vt(o.longitude,s.longitude)}case 8:{let o=e,s=t,a=Math.min(o.length,s.length);for(let l=0;l<a;l++){let c=Fn(o[l],s[l]);if(c!==0)return c}return o.length<s.length?-1:o.length>s.length?1:0}case 9:{let o=e,s=t,a=Object.keys(o).sort(lt),l=Object.keys(s).sort(lt),c=Math.min(a.length,l.length);for(let u=0;u<c;u++){let p=a[u],f=l[u],b=lt(p,f);if(b!==0)return b;let h=Fn(o[p],s[f]);if(h!==0)return h}return a.length<l.length?-1:a.length>l.length?1:0}}}function Nn(e){return e.ref?.path??e.id}function Jr(e,t){if(typeof e.get=="function")return e.get(t);let n=e.data();if(!n)return;if(!t.includes("."))return n[t];let r=n;for(let o of t.split(".")){if(r==null||typeof r!="object")return;r=r[o];}return r}function oa(e,t){let n=[],r=new Set;if(e.orderBy)for(let a of e.orderBy){let l=String(a.field),c=a.direction==="desc"?"desc":"asc";r.has(l)||(n.push({field:l,direction:c}),r.add(l));}let o=n.length>0?n[n.length-1].direction:"asc",s=[];for(let[a,l]of t){let c=String(a);Gs.has(l)&&c!==Xt&&!r.has(c)&&(s.push(c),r.add(c));}s.sort(ea);for(let a of s)n.push({field:a,direction:o});return r.has(Xt)||n.push({field:Xt,direction:o}),n}function sa(e,t,n){for(let r of n){let o=r.field===Xt?to(Nn(e),Nn(t)):Fn(Jr(e,r.field),Jr(t,r.field));if(o!==0)return r.direction==="desc"?-o:o}return 0}function aa(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function ct(e,t){return t.orderBy&&t.orderBy.forEach(n=>{e=e.orderBy(String(n.field),n.direction??"asc");}),t.limit&&(e=e.limit(t.limit)),t.offset&&(e=e.offset(t.offset)),t.select&&t.select.length>0&&(e=e.select(...t.select.map(n=>String(n)))),t.startAt&&(e=Array.isArray(t.startAt)?e.startAt(...t.startAt):e.startAt(t.startAt)),t.startAfter&&(e=Array.isArray(t.startAfter)?e.startAfter(...t.startAfter):e.startAfter(t.startAfter)),t.endAt&&(e=Array.isArray(t.endAt)?e.endAt(...t.endAt):e.endAt(t.endAt)),t.endBefore&&(e=Array.isArray(t.endBefore)?e.endBefore(...t.endBefore):e.endBefore(t.endBefore)),e}function Yr(e){if(!e.offset||e.offset<=0)return e;let{offset:t,limit:n,...r}=e;return {...r,...n&&n>0?{limit:t+n}:{}}}function We(e){let[,t,n]=e;return (t==="in"||t==="array-contains-any")&&Array.isArray(n)&&n.length>30}function en(e){let[t,n,r]=e;return We(e)?aa(r,30).map(s=>[t,n,s]):[e]}function Ae(e,t){let n=e;for(let[r,o,s]of t)n=n.where(String(r),o,s);return n}async function Xr(e,t,n){let r=await Promise.all(e.map(f=>f.get())),o=new Map;r.forEach(f=>{f.docs.forEach(b=>{let h=Nn(b);o.has(h)||o.set(h,b);});});let s=r[0];if(!s)throw new Error("No snapshots returned");let a=oa(t,n),l=Array.from(o.values()).sort((f,b)=>sa(f,b,a)),c=t.offset&&t.offset>0?t.offset:0,u=t.limit&&t.limit>0?c+t.limit:void 0,p=c>0||u!==void 0?l.slice(c,u):l;return {...s,docs:p,size:p.length,empty:p.length===0,forEach:(f,b)=>{p.forEach(h=>f.call(b,h));}}}async function Qe(e,t){let n=t.orWhere&&t.orWhere.length>0,r=t.orWhereGroups&&t.orWhereGroups.length>0;if(!n&&!r){if(!t.where||t.where.length===0)return ct(e,t).get();if(!t.where.some(We)){let w=Ae(e,t.where);return w=ct(w,t),w.get()}let p=t.where.map(en),f=Tt(p);if(f.length===1){let w=Ae(e,f[0]);return w=ct(w,t),w.get()}let b=Yr(t),h=f.map(w=>{let T=Ae(e,w);return T=ct(T,b),T});return Xr(h,t,t.where)}let o=t.where??[],s=[...t.orWhere?.map(u=>[u])??[],...t.orWhereGroups??[]],a=[];for(let u of s){let p=[...o,...u];if(!p.some(We))a.push(p);else {let b=p.map(en),h=Tt(b);a.push(...h);}}if(a.length===1){let u=Ae(e,a[0]);return u=ct(u,t),u.get()}let l=Yr(t),c=a.map(u=>{let p=Ae(e,u);return p=ct(p,l),p});return Xr(c,t,o)}function Tt(e){if(e.length===0)return [[]];let t=e[0];if(e.length===1&&t)return t.map(s=>[s]);if(!t)return [[]];let n=e.slice(1),r=Tt(n),o=[];for(let s of t)for(let a of r)o.push([s,...a]);return o}function ia(e){return typeof Filter?.or=="function"&&typeof Filter?.and=="function"&&typeof Filter?.where=="function"&&typeof Query=="function"&&e instanceof Query}function ca(e,t){if(t.length<2)return false;let n=0,r=a=>{let[,l,c]=a;return !(We(a)||l==="not-in"||(l==="in"||l==="array-contains-any")&&(!Array.isArray(c)||c.length===0)||l==="!="&&(n++,n>1))};for(let a of e)if(!r(a))return false;let o=0,s=0;for(let a of t){for(let p of a)if(!r(p))return false;let l=[...e,...a],c=0,u=1;for(let[,p,f]of l)if((p==="array-contains"||p==="array-contains-any")&&(c++,c>1)||(p==="in"||p==="array-contains-any"?u*=f.length:p==="!="&&(u*=2),o+u>Qs))return false;if(o+=u,s+=u*l.length,s>Vs)return false}return true}function la(e,t,n){let r=n.map(s=>{let a=s.map(([l,c,u])=>Filter.where(String(l),c,u));return a.length===1?a[0]:Filter.and(...a)});return (t.length>0?Ae(e,t):e).where(Filter.or(...r))}function da(e){if(typeof e!="object"||e===null)return false;let t=e.code;if(t===3||t===9)return true;if(typeof t=="string"){let n=t.toLowerCase();return n==="invalid-argument"||n==="invalid_argument"||n==="failed-precondition"||n==="failed_precondition"}return false}async function eo(e,t){if(t.length===0)return {count:(await e.count().get()).data().count,isExact:true};if(!t.some(We))return {count:(await Ae(e,t).count().get()).data().count,isExact:true};let r=t.map(en),o=Tt(r),a=(await Promise.all(o.map(c=>Ae(e,c).count().get()))).reduce((c,u)=>c+u.data().count,0),l=t.some(c=>c[1]==="array-contains-any"&&We(c));return {count:a,isExact:!l}}async function jn(e,t){let n=t.where??[],r=[...t.orWhere?.map(l=>[l])??[],...t.orWhereGroups??[]].filter(l=>l.length>0);if(r.length===0)return eo(e,n);if(r.length===1)return eo(e,[...n,...r[0]]);if(ia(e)&&ca(n,r))try{return {count:(await la(e,n,r).count().get()).data().count,isExact:!0}}catch(l){if(!da(l))throw l}let o=[];for(let l of r){let c=[...n,...l];if(!c.some(We))o.push(Ae(e,c));else {let p=c.map(en),b=Tt(p).map(h=>Ae(e,h));o.push(...b);}}return {count:(await Promise.all(o.map(l=>l.count().get()))).reduce((l,c)=>l+c.data().count,0),isExact:false}}var Bn="preserve";function ua(e){Bn=e;}function nn(){return Bn}function pa(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function zn(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof Timestamp)return e.toDate();if(pa(e))return new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));if(typeof e=="string"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function fa(e){if(typeof e!="object"||e===null)return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function tn(e){if(e instanceof Timestamp)return e.toDate();if(Array.isArray(e))return e.map(t=>tn(t));if(fa(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=tn(r);return t}return e}function ce(e){return Bn==="normalize"?tn(e):e}function ro(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function He(e){return e.charAt(0).toUpperCase()+e.slice(1)}function je(e,t){return t.where&&t.where.forEach(([n,r,o])=>{e=e.where(String(n),r,o);}),t.orderBy&&t.orderBy.forEach(n=>{e=e.orderBy(String(n.field),n.direction??"asc");}),t.limit&&(e=e.limit(t.limit)),t.offset&&(e=e.offset(t.offset)),t.select&&t.select.length>0&&(e=e.select(...t.select.map(n=>String(n)))),t.startAt&&(e=Array.isArray(t.startAt)?e.startAt(...t.startAt):e.startAt(t.startAt)),t.startAfter&&(e=Array.isArray(t.startAfter)?e.startAfter(...t.startAfter):e.startAfter(t.startAfter)),t.endAt&&(e=Array.isArray(t.endAt)?e.endAt(...t.endAt):e.endAt(t.endAt)),t.endBefore&&(e=Array.isArray(t.endBefore)?e.endBefore(...t.endBefore):e.endBefore(t.endBefore)),e}async function rn(e,t){let n={...t,limit:t.pageSize+1};t.cursor&&(t.direction==="prev"?n.endBefore=t.cursor:n.startAfter=t.cursor);let[r,o]=await Promise.all([Qe(e,n),t.withTotal?jn(e,t):Promise.resolve(void 0)]),s=r.docs,a=s.length>t.pageSize,l=a?s.slice(0,t.pageSize):s,c=l.map(p=>ce({...p.data(),docId:p.id})),u=t.direction==="prev";return {data:c,nextCursor:u?l.length>0?l[l.length-1]:void 0:a?l[l.length-1]:void 0,prevCursor:u?a?l[0]:void 0:l[0],hasNextPage:u?!!t.cursor:a,hasPrevPage:u?a:!!t.cursor,pageSize:c.length,...o!==void 0?{totalCount:o.count,totalCountIsExact:o.isExact}:{}}}async function*qn(e,t){let n,r=true;for(;r;){let o=await rn(e,{...t,cursor:n,direction:"next"});yield o,r=o.hasNextPage,n=o.nextCursor;}}var Ve="X-History-Reason",Ge="X-History-Comment",ao=Symbol.for("@lpdjs/firestore-repo-service:actorResolverHeaders"),Un=Symbol.for("@lpdjs/firestore-repo-service:actorContext"),Ln=globalThis,on=Ln[Un]??(Ln[Un]=new AsyncLocalStorage);function ma(e,t){if(!t.includes("."))return e[t];let n=e;for(let r of t.split(".")){if(!n||typeof n!="object")return;n=n[r];}return n}function oo(e,t){for(let n of t){let r=ma(e,n);if(typeof r=="string"&&r.length>0)return r;if(typeof r=="number")return String(r)}return null}function so(e,t){if(t===false)return;let n=e?.req?.header;if(typeof n!="function")return;let r=n.call(e.req,t);return typeof r=="string"&&r.length>0?r:void 0}function Kn(e={}){let t=e.contextKeys??["user","docsUser"],n=e.userIdFields??["uid","id","sub"],r=e.userEmailFields??["email"],o=e.reasonHeader===void 0?"x-history-reason":e.reasonHeader,s=e.commentHeader===void 0?"x-history-comment":e.commentHeader,a=e.reasonHeader===void 0?Ve:e.reasonHeader,l=e.commentHeader===void 0?Ge:e.commentHeader,c=e.extras,u=p=>{let f=null,b=p?.get;if(typeof b=="function")for(let S of t){let I=b.call(p,S);if(I&&typeof I=="object"){f=I;break}}let h=so(p,o),w=so(p,s),T=c?c(p,f):void 0;return f?{userId:oo(f,n),userEmail:oo(f,r),...h!==void 0?{reason:h}:{},...w!==void 0?{comment:w}:{},...T?{extras:T}:{}}:h===void 0&&w===void 0&&!T?null:{...h!==void 0?{reason:h}:{},...w!==void 0?{comment:w}:{},...T?{extras:T}:{}}};return Object.defineProperty(u,ao,{value:{reasonHeader:a,commentHeader:l},enumerable:false,configurable:false}),u}function Zn(e){if(!e)return {reasonHeader:Ve,commentHeader:Ge};if(typeof e=="function"){let t=e[ao];return t?{...t}:{reasonHeader:Ve,commentHeader:Ge}}return {reasonHeader:e.reasonHeader===void 0?Ve:e.reasonHeader,commentHeader:e.commentHeader===void 0?Ge:e.commentHeader}}var io=Kn();function ha(e){if(e)return typeof e=="function"?e:Kn(e)}function Wn(e){let t=ha(e);return async(n,r)=>{await on.run({c:n,resolver:t},async()=>{await r();});}}function ut(){let e=on.getStore();if(!e)return null;let t=null;if(e.c)try{t=(e.resolver??io)(e.c);}catch{t=null;}if(!t&&!e.override)return null;let n={...t??{}};return e.override&&(e.override.userId!==void 0&&(n.userId=e.override.userId),e.override.userEmail!==void 0&&(n.userEmail=e.override.userEmail),e.override.reason!==void 0&&(n.reason=e.override.reason),e.override.comment!==void 0&&(n.comment=e.override.comment),e.override.extras!==void 0&&(n.extras={...t?.extras??{},...e.override.extras})),n}function ga(e,t){return on.run({override:{...e}},t)}function ba(e){let t=on.getStore();if(!t)return false;let n=t.override??{},r={...n,...e};return (n.extras||e.extras)&&(r.extras={...n.extras??{},...e.extras??{}}),t.override=r,true}var Qn="_historyMeta";function Ee(e){if(!e?.enabled||e.shadow===false||e.meta&&e.shadow===void 0)return null;let t=e.shadow,n=typeof t=="string"&&t.trim().length>0?t.trim():typeof t=="object"&&t!==null&&typeof t.key=="string"&&t.key.trim().length>0?t.key.trim():Qn,r=typeof t=="object"&&t!==null?t.fields:void 0;return {key:n,fields:{userId:r?.userId??"userId",userEmail:r?.userEmail??"userEmail",reason:r?.reason??"reason",comment:r?.comment??"comment",extras:r?.extras??"extras"}}}function ve(e){return Ee(e)?.key??null}function Vn(e){let t=Ee(e);return t?[t.key]:[]}function ue(e,t){if(!t||!e||typeof e!="object"||Array.isArray(e))return e;let n=e;if(!(t in n))return e;let{[t]:r,...o}=n;return o}function xe(e,t){if(!t?.enabled||t.autoInjectMeta===false)return;let n=Ee(t);if(!n)return;let r=ut(),o=t.fallbackActor??{},s=r?.userId!==void 0?r.userId:o.userId??null,a=r?.userEmail!==void 0?r.userEmail:o.userEmail??null,l=r?.reason??null,c=r?.comment??null,u=r?.extras&&Object.keys(r.extras).length>0?r.extras:null,p={},{fields:f}=n;f.userId!==false&&(p[f.userId]=s),f.userEmail!==false&&(p[f.userEmail]=a),f.reason!==false&&(p[f.reason]=l),f.comment!==false&&(p[f.comment]=c),f.extras!==false&&(p[f.extras]=u),e[n.key]=p;}function Ct(e){if(e===null)return "null";if(e===void 0)return "undefined";if(e instanceof Timestamp)return "timestamp";if(e instanceof Date)return "date";if(Array.isArray(e))return "array";let t=typeof e;return t==="string"||t==="number"||t==="boolean"?t:"object"}function At(e,t,n=new WeakMap){if(e===t)return true;if(e===null||t===null||e===void 0||t===void 0)return e===t;if(e instanceof Timestamp&&t instanceof Timestamp)return e.isEqual(t);if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return false;if(n.get(e)===t)return true;n.set(e,t);for(let r=0;r<e.length;r++)if(!At(e[r],t[r],n))return false;return true}if(typeof e=="object"&&typeof t=="object"){if(e instanceof Date||t instanceof Date||e instanceof Timestamp||t instanceof Timestamp)return false;if(n.get(e)===t)return true;n.set(e,t);let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return false;for(let s of r)if(!Object.prototype.hasOwnProperty.call(t,s)||!At(e[s],t[s],n))return false;return true}return false}function sn(e,t,n={}){let r=new Set([...n.exclude??[],...n.metaFields??[],...n.systemKeys??[]]),o=n.include?new Set(n.include):null,s=e??{},a=t??{},l=new Set([...Object.keys(s),...Object.keys(a)]),c={};for(let u of l){if(r.has(u)||o&&!o.has(u))continue;let p=s[u],f=a[u];At(p,f)||(c[u]={oldValue:p===void 0?null:p,newValue:f===void 0?null:f,type:{old:Ct(p),new:Ct(f)}});}return c}var wa=5;function xa(e){return e.schemaVersion===2}function co(e){if(typeof e!="string")return "object";switch(e){case "string":case "number":case "boolean":case "object":case "array":case "timestamp":case "date":case "null":case "undefined":return e;default:return "object"}}function Ra(e){return {historyDocId:e.historyDocId,historyToObjectId:e.historyToObjectId,historySetAt:e.historySetAt,schemaVersion:2,operation:e.operation,meta:e.meta??{},...e.custom?{custom:e.custom}:{},changes:e.changes??{}}}function Sa(e){let t={};e.historyUserId!==void 0&&(t.userId=e.historyUserId??null),e.historyUserEmail!==void 0&&(t.userEmail=e.historyUserEmail??null);let n=e.extraHistoryDetails??null;n&&(n.reason!==void 0&&(t.reason=n.reason??null),n.comment!==void 0&&(t.comment=n.comment??null));let r={},o=false;if(e.historyDetails&&typeof e.historyDetails=="object")for(let[s,a]of Object.entries(e.historyDetails))r[s]=a,o=true;if(e.extraContentKeys&&typeof e.extraContentKeys=="object")for(let[s,a]of Object.entries(e.extraContentKeys))r[`content.${s}`]=a,o=true;return o&&(t.extras=r),t}function va(e){let t=e.changes?.oldValue??null,n=e.changes?.newValue??null,r=e.types?.oldValue,o=e.types?.newValue;return {oldValue:t,newValue:n,type:{old:r?co(r):Ct(t),new:o?co(o):Ct(n)}}}function Ta(e){let t=va(e),n=Sa(e);return {historyDocId:e.historyDocId,historyToObjectId:e.historyToObjectId,historySetAt:e.historySetAt,schemaVersion:1,operation:"update",meta:n,changes:{[e.field]:t}}}function ka(e,t,n){return Math.abs(e.toMillis()-t.toMillis())<=n}function Ca(e,t){return (e.userId??null)===(t.userId??null)}function lo(e,t={}){let n=t.groupToleranceMs??wa,r=[];for(let o of e){if(xa(o)){r.push(Ra(o));continue}let a=Ta(o),l=r[r.length-1];l&&l.schemaVersion===1&&ka(l.historySetAt,a.historySetAt,n)&&Ca(l.meta,a.meta)?Object.assign(l.changes,a.changes):r.push(a);}return r}var Ea=7e5;function Et(e){let t=e.ttlOverride??e.config.ttl,r={schemaVersion:2,historyDocId:randomUUID(),historyToObjectId:e.entityId,historySetAt:Timestamp.now(),operation:e.operation,meta:e.meta,...e.custom?{custom:e.custom}:{},changes:e.changes};t&&(r.expiresAt=Timestamp.fromMillis(Date.now()+t.days*24*60*60*1e3));let o=s=>{try{return Buffer.byteLength(JSON.stringify(s,(a,l)=>l instanceof Timestamp?l.toMillis():l),"utf8")}catch{return 0}};if(o(r.changes)>Ea){let s={};for(let[a,l]of Object.entries(r.changes)){let c=o(l.oldValue),u=o(l.newValue);s[a]={oldValue:c>5e4?"[truncated]":l.oldValue,newValue:u>5e4?"[truncated]":l.newValue,type:l.type};}r.changes=s,r._truncated=true;}return r}async function Ot(e,t,n,r){let o=t;return n.onBeforeWrite&&(o=await n.onBeforeWrite(t,r)),o?(await e.doc(o.historyDocId).set(o),{written:true,entry:o}):{written:false,reason:"dropped-by-onBeforeWrite"}}function an(e,t){let n=e??{},r={},o=Ee(t);if(o){let f=n[o.key];if(f&&typeof f=="object"&&!Array.isArray(f)){let b=f,h=A=>{if(A===false||!(A in b))return;let O=b[A];return O==null?null:String(O)},w=h(o.fields.userId);w!==void 0&&(r.userId=w);let T=h(o.fields.userEmail);T!==void 0&&(r.userEmail=T);let S=h(o.fields.reason);S!==void 0&&(r.reason=S);let I=h(o.fields.comment);if(I!==void 0&&(r.comment=I),o.fields.extras!==false){let A=b[o.fields.extras];A&&typeof A=="object"&&!Array.isArray(A)&&Object.keys(A).length>0&&(r.extras=A);}}return r}let s=t.meta;if(!s)return r;let a=f=>{if(!f)return;let b=n[f];return b===void 0||b===null?null:String(b)},l=a(s.userId);l!==void 0&&(r.userId=l);let c=a(s.userEmail);c!==void 0&&(r.userEmail=c);let u=a(s.reason);u!==void 0&&(r.reason=u);let p=a(s.comment);if(p!==void 0&&(r.comment=p),s.extras&&s.extras.length>0){let f={},b=false;for(let h of s.extras)h in n&&(f[h]=n[h],b=true);b&&(r.extras=f);}return r}function cn(e){let t=[],n=Ee(e);n&&t.push(n.key);let r=e.meta;return r&&(r.userId&&t.push(r.userId),r.userEmail&&t.push(r.userEmail),r.reason&&t.push(r.reason),r.comment&&t.push(r.comment),r.extras&&t.push(...r.extras)),t}var Oa="history",Pa=50;function Jn(e,t,n){return e(...n).collection(t)}function uo(e){return String(e[e.length-1]??"")}function po(e,t,n,r){if(!r?.enabled)return null;let o=r.subcollection??Oa;async function s(...h){let w={},T=h,S=h[h.length-1];S!==null&&typeof S=="object"&&!(S instanceof Timestamp)&&("limit"in S||"cursor"in S||"direction"in S)&&(w=S,T=h.slice(0,-1));let I=Jn(e,o,T),A=w.direction??"desc",O=I.orderBy("historySetAt",A);return w.cursor&&(O=O.startAfter(w.cursor)),w.limit&&w.limit>0&&(O=O.limit(w.limit)),(await O.get()).docs.map(d=>({id:d.id,data:d.data()}))}async function a(...h){let w={},T=h,S=h[h.length-1];S!==null&&typeof S=="object"&&!(S instanceof Timestamp)&&("limit"in S||"cursor"in S||"direction"in S||"fields"in S||"operations"in S)&&(w=S,T=h.slice(0,-1));let I=w.limit??Pa,A=Math.max(I,Math.min(I*8,500)),O=await s(...T,{limit:A,cursor:w.cursor,direction:w.direction??"desc"}),x=lo(O.map(d=>d.data));if(w.fields&&w.fields.length>0){let d=new Set(w.fields);x=x.filter(y=>Object.keys(y.changes).some(i=>d.has(i)));}if(w.operations&&w.operations.length>0){let d=new Set(w.operations);x=x.filter(y=>d.has(y.operation));}return x.slice(0,I)}async function l(...h){let w=h[h.length-1],T={},S,I;return w!==null&&typeof w=="object"&&!(w instanceof Timestamp)?(T=w,S=h[h.length-2],I=h.slice(0,-2)):(S=w,I=h.slice(0,-1)),a(...I,{...T,fields:[S]})}async function c(...h){let w=h[h.length-1],T={},S,I;return w!==null&&typeof w=="object"&&!(w instanceof Timestamp)?(T=w,S=h[h.length-2],I=h.slice(0,-2)):(S=w,I=h.slice(0,-1)),a(...I,{...T,operations:[S]})}function u(h){let w={title:h.title,display:h.display??true};return h.description!==void 0&&(w.description=h.description),h.key!==void 0&&(w.key=h.key),h.data!==void 0&&(w.data=h.data),w}function p(){let h=ut(),w=r.fallbackActor??{},T=h?.userId!==void 0?h.userId:w.userId??null,S=h?.userEmail!==void 0?h.userEmail:w.userEmail??null;return {userId:T,userEmail:S,...h?.reason!==void 0?{reason:h.reason}:{},...h?.comment!==void 0?{comment:h.comment}:{},...h?.extras&&Object.keys(h.extras).length>0?{extras:h.extras}:{}}}async function f(...h){let w=h[h.length-1],T=h.slice(0,-1),S=uo(T),I=sn(w.before??{},w.after??{},{include:r.include,exclude:r.exclude,metaFields:cn(r),systemKeys:t});if(w.operation==="update"&&Object.keys(I).length===0)return null;let A=an(w.after??w.before??null,r),O=ut(),d={...O?{...O.userId!==void 0?{userId:O.userId}:{},...O.userEmail!==void 0?{userEmail:O.userEmail}:{},...O.reason!==void 0?{reason:O.reason}:{},...O.comment!==void 0?{comment:O.comment}:{},...O.extras&&Object.keys(O.extras).length>0?{extras:O.extras}:{}}:{},...A,...w.meta??{}},y=w.custom?u(w.custom):void 0,i=Et({entityId:S,operation:w.operation,changes:I,meta:d,custom:y,config:r}),g=Jn(e,o,T),m=await Ot(g,i,r,{repoName:n,docId:S,before:w.before??null,after:w.after??null});return !m.written||!m.entry?null:{historyDocId:m.entry.historyDocId,historyToObjectId:m.entry.historyToObjectId,historySetAt:m.entry.historySetAt,schemaVersion:2,operation:m.entry.operation,meta:m.entry.meta,...m.entry.custom?{custom:m.entry.custom}:{},changes:m.entry.changes}}async function b(...h){let w=h[h.length-1],T=h.slice(0,-1),S=uo(T),I=u(w),A={...p(),...w.meta??{}},O=Et({entityId:S,operation:"custom",changes:{},meta:A,custom:I,config:r}),x=Jn(e,o,T),d=await Ot(x,O,r,{repoName:n,docId:S,before:null,after:null});return !d.written||!d.entry?null:{historyDocId:d.entry.historyDocId,historyToObjectId:d.entry.historyToObjectId,historySetAt:d.entry.historySetAt,schemaVersion:2,operation:d.entry.operation,meta:d.entry.meta,...d.entry.custom?{custom:d.entry.custom}:{},changes:d.entry.changes}}return {list:a,raw:s,byField:l,byOperation:c,recordManual:f,recordCustom:b}}function fo(e){return {count:async(t={})=>{let n=e;return n=je(n,t),(await n.count().get()).data().count},sum:async(t,n={})=>{let r=e;r=je(r,n);let o=await r.get(),s=0;return o.forEach(a=>{let l=a.data()[t];typeof l=="number"&&(s+=l);}),s},average:async(t,n={})=>{let r=e;r=je(r,n);let o=await r.get();if(o.empty)return null;let s=0,a=0;return o.forEach(l=>{let c=l.data()[t];typeof c=="number"&&(s+=c,a++);}),a>0?s/a:null}}}function yo(e,t,n,r,o,s,a){let l=()=>new Date;return {create:()=>{let c=e.batch();return {batch:c,set:(...u)=>{let p=u[u.length-1],f=typeof p=="object"&&p!==null&&"merge"in p,b=f?u[u.length-2]:u[u.length-1],h=f?u.slice(0,-2):u.slice(0,-1),w=f?p:{merge:true},T=t(...h),S={...b},I=h[h.length-1];n&&I&&(S[n]=I),r&&(S[r]=T.path),o&&S[o]===void 0&&(S[o]=l()),s&&(S[s]=l()),xe(S,a),c.set(T,S,w);},update:(...u)=>{let p=u.pop(),b=t(...u),h={...p};s&&(h[s]=l()),xe(h,a),c.update(b,h);},delete:(...u)=>{let p=t(...u);c.delete(p);},commit:async()=>{await c.commit();}}}}}var Ia=new Set([4,8,10,13,14]);function Yn(e,t){let n=[],r=t.maxAttempts??5;return e.onWriteError(o=>{let s=o?.code;if(o.failedAttempts<r&&s!==void 0&&Ia.has(s))return true;let a={ref:o.documentRef,error:o};return n.push(a),t.onError?.(a),false}),t.onSuccess&&e.onWriteResult(o=>t.onSuccess(o)),n}function Xn(e,t){if(e.length>0&&!t.onError){let n=new Error(`bulk operation failed for ${e.length} document(s): `+e.slice(0,5).map(r=>`${r.ref.path} (${r.error.message})`).join("; "));throw n.failures=e,n}return {failures:e}}function mo(e,t,n,r){let o=()=>new Date;return {set:async(s,a={})=>{let l=e.bulkWriter(),c=Yn(l,a);try{for(let u of s){if(!u)continue;let{docRef:p,data:f,merge:b=!0}=u,h={...f};t&&h[t]===void 0&&(h[t]=o()),n&&(h[n]=o()),xe(h,r),Promise.resolve(l.set(p,h,{merge:b})).catch(()=>{});}}finally{await l.close();}return Xn(c,a)},update:async(s,a={})=>{let l=e.bulkWriter(),c=Yn(l,a);try{for(let u of s){if(!u)continue;let{docRef:p,data:f}=u,b={...f};n&&(b[n]=o()),xe(b,r),Promise.resolve(l.update(p,b)).catch(()=>{});}}finally{await l.close();}return Xn(c,a)},delete:async(s,a={})=>{let l=e.bulkWriter(),c=Yn(l,a);try{for(let u of s)u&&Promise.resolve(l.delete(u)).catch(()=>{});}finally{await l.close();}return Xn(c,a)}}}var er="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Be(){let e="";for(;e.length<20;){let t=randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let r=t[n];r>=er.length*4||(e+=er.charAt(r%er.length));}}return e}function tr(e){return e.match(/^\{([^}]+)\}$/)?.[1]?.trim()||null}function _e(e,t="docId",n=false){if(typeof e!="string"||!e.trim())return {rawPath:e??"",collectionId:"",collectionPath:"",parentKeys:[],documentPathTemplate:null,hasTemplate:false};let r=e.split("/").map(f=>f.trim()).filter(Boolean);if(r.length===0)return {rawPath:e,collectionId:e,collectionPath:e,parentKeys:[],documentPathTemplate:null,hasTemplate:false};if(r.length===1){let f=r[0];return {rawPath:e,collectionId:f,collectionPath:f,parentKeys:[],documentPathTemplate:n?null:`${f}/{${t}}`,hasTemplate:e.includes("{")&&e.includes("}")}}let o=r.length%2===0,s=o?r.slice(0,-1):r,a=s[s.length-1],l=s.join("/"),u=s.slice(0,-1).map(tr).filter(f=>f!==null),p=o?r.join("/"):`${l}/{${t}}`;return {rawPath:e,collectionId:a,collectionPath:l,parentKeys:u,documentPathTemplate:p,hasTemplate:true}}function ho(e,t,n){let r=t.split("/").map(c=>c.trim()).filter(Boolean),o=0,s=[];for(let c of r){let u=tr(c);if(u!==null){let p=n[o++];if(typeof p!="string"||p.trim()==="")throw new Error(`Missing or empty path parameter "${u}" when resolving document reference for "${t}".`);s.push(p);}else s.push(c);}let a=e;if(typeof a?.collection=="function"&&s.length>=2){let c=a,u=true;for(let p=0;p<s.length;p+=2){let f=s[p],b=s[p+1];if(typeof c?.collection!="function"){u=false;break}let h=c.collection(f);if(typeof h?.doc!="function"){u=false;break}c=h.doc(b);}if(u&&c&&c!==a)return c}let l=s.join("/");if(typeof a?.doc=="function")return a.doc(l);if(typeof a?.collection=="function"&&s.length>=2){let c=s.slice(0,-1).join("/"),u=s[s.length-1],p=a.collection(c);return typeof p?.doc=="function"?p.doc(u):p}throw new Error(`Cannot resolve DocumentReference for "${l}": Firestore instance does not expose .collection() or .doc().`)}function Je(e,t={}){if(!e||typeof e!="object")return;let{pathKey:n,documentKey:r="docId",parentKeys:o,documentPathTemplate:s,isGroup:a}=t,l=n&&typeof e[n]=="string"&&e[n]?e[n]:void 0;if(l&&s){let c=l.split("/").filter(Boolean),u=s.split("/").filter(Boolean);if(c.length===u.length){let p=[];for(let f=0;f<u.length;f++)tr(u[f])!==null&&p.push(c[f]);if(p.length>0)return p}}if(o&&o.length>0){let c=o.length+1;if(l){let p=l.split("/").filter(Boolean),f=[];for(let b=1;b<p.length;b+=2)f.push(p[b]);if(f.length>=c)return f.slice(f.length-c)}let u=r?e[r]:void 0;if(typeof u=="string"&&u.trim()!==""){let p=[],f=true;for(let b of o){let h=e[b];if(typeof h=="string"&&h.trim()!=="")p.push(h);else {f=false;break}}if(f)return [...p,u]}}if(l){let c=l.split("/").filter(Boolean),u=[];for(let p=1;p<c.length;p+=2)u.push(c[p]);if(u.length>0)return !a&&(!o||o.length===0)?[u[u.length-1]]:u}}function go(e,t,n,r,o,s,a=[],l,c){let u=()=>new Date,p=ve(c);return {create:async(...T)=>{let S=T[T.length-1],I=T.slice(0,-1);if(!S||typeof S!="object")throw new Error("Create data payload must be an object.");let A,O,x=typeof S[n]=="string"&&S[n].trim()!=="",d={...S};if(o&&d[o]===void 0&&(d[o]=u()),s&&(d[s]=u()),xe(d,c),e&&I.length===0)if(x){O=S[n],A=typeof e.doc=="function"?e.doc(O):t(O),d[n]=O;let y=r&&A?.path?{...d,[r]:A.path}:d;await A.set(y),r&&A?.path&&(d[r]=A.path);}else if(typeof e.add=="function"){A=await e.add(d),O=A.id,d[n]=O;let y={[n]:O};r&&A?.path&&(y[r]=A.path,d[r]=A.path),await A.update(y);}else O=Be(),A=typeof e.doc=="function"?e.doc(O):t(O),d[n]=A?.id??O,r&&A?.path&&(d[r]=A.path),await A.set(d);else {let y=[];if(I.length>0)for(let i=0;i<I.length;i++){let g=I[i];if(typeof g!="string"||g.trim()===""){let m=a[i]??`arg[${i}]`;throw new Error(`Missing or empty parent key "${m}" for subcollection create()`)}y.push(g);}else if(a.length>0){let i=[];for(let g of a){let m=S[g];typeof m=="string"&&m.trim()!==""?y.push(m):i.push(g);}if(i.length>0){let g=Je(S,{pathKey:r,documentKey:n,parentKeys:a,documentPathTemplate:l,isGroup:true});if(g&&g.length>=a.length)y=g.slice(0,a.length);else throw new Error(`Missing or empty required parent key(s) in data for subcollection create(): ${i.join(", ")}`)}}else if(r&&typeof S[r]=="string"&&S[r].trim()!==""){let i=Je(S,{pathKey:r,documentKey:n,parentKeys:a,documentPathTemplate:l,isGroup:true});i&&i.length>1&&(y=i.slice(0,-1));}if(y.length===0)throw new Error("Cannot use create() on collection groups without parent keys. Configure a path template (e.g. 'residences/{residenceId}/events') or provide parent keys in data.");O=x?S[n]:Be(),A=t(...y,O),d[n]=A?.id??O,r&&A?.path&&(d[r]=A.path),await A.set(d);}if(typeof A?.get=="function"){let y=await A.get(),i=typeof y?.data=="function"?y.data():d;return ue(ce(i??d),p)}return ue(ce(d),p)},set:async(...T)=>{let S=T[T.length-1],I=typeof S=="object"&&S!==null&&"merge"in S,A=I?T[T.length-2]:T[T.length-1],O=I?T.slice(0,-2):T.slice(0,-1),x=I?S:{merge:true},d={...A};o&&d[o]===void 0&&(d[o]=u()),s&&(d[s]=u()),xe(d,c);let y=t(...O),i=O[O.length-1];if(n&&i!=null&&(d[n]=i),r&&(d[r]=y.path),await y.set(d,x),typeof y?.get=="function"){let g=await y.get(),m=typeof g?.data=="function"?g.data():d;return ue(ce(m??d),p)}return ue(ce(d),p)},update:async(...T)=>{let S=T.pop(),I=T,A={...S};s&&(A[s]=u()),xe(A,c);let O=t(...I);await O.update(A);let x=await O.get();return ue(ce(x.data()),p)},delete:async(...T)=>{await t(...T).delete();}}}function bo(e,t,n,r,o,s=null){let a={};return a.byList=async(l,c,u="in",p={})=>{if(c.length===0)return [];let f=[],b=ro(c,30);for(let h of b){let w=e;w=w.where(l,u,h),p.select&&p.select.length>0&&(w=w.select(...p.select.map(S=>String(S)))),(await w.get()).forEach(S=>{let I=ue(ce(S.data()),s);f.push(p.returnDoc?{data:I,doc:S}:I);});}return f},t.forEach(l=>{let c=`by${He(String(l))}`;a[c]=async(...u)=>{let p={},f=u[u.length-1];if(typeof f=="boolean"?(p={returnDoc:f},u=u.slice(0,-1)):typeof f=="object"&&f!==null&&!Array.isArray(f)&&(p=f,u=u.slice(0,-1)),String(l)===o&&(u.length>1||u.length===1&&n!==null)){let A=await r(...u).get();if(!A.exists)return null;let O=ue(ce(A.data()),s);return p.returnDoc?{data:O,doc:A}:O}let b=u[0];if(b===void 0)return null;let h=e;h=h.where(String(l),"==",b).limit(1),p.select&&p.select.length>0&&(h=h.select(...p.select.map(I=>String(I))));let w=await h.get();if(w.empty)return null;let T=w.docs[0];if(!T)return null;let S=ue(ce(T.data()),s);return p.returnDoc?{data:S,doc:T}:S};}),a}function wo(e,t,n,r,o=null){let s={},a=c=>ue(ce(c),o),l=async(c,u)=>{if(!n||!r||u.length===0)return c;let p=u.map(f=>typeof f=="string"?{key:f}:{key:f.relation,select:f.select});return Promise.all(c.map(async f=>{let b=await Promise.all(p.map(async({key:w,select:T})=>{let S=n[w];if(!S)return [w,void 0];let I=r[S.repo];if(!I)return [w,void 0];let A=S.sourceKey||w,O=f[A];if(O==null)return [w,S.type==="one"?null:[]];let x=T?{select:T}:void 0;try{if(S.type==="one"){let d=`by${He(S.key)}`,y=typeof I.get?.[d]=="function"?await I.get[d](O,x):null;return [w,y]}else {let d=`by${He(S.key)}`,y=typeof I.query?.[d]=="function"?await I.query[d](O,x):[];return [w,y]}}catch(d){return console.error(`[include] Error populating "${w}":`,d),[w,S.type==="one"?null:[]]}})),h={};for(let[w,T]of b)w!==void 0&&(h[w]=T);return {...f,populated:h}}))};return t.forEach(c=>{let u=`by${He(c)}`;s[u]=async(p,f={})=>{let b={...f,where:[[c,"==",p],...f.where??[]]};return (await Qe(e,b)).docs.map(w=>a(w.data()))};}),s.by=async c=>(await Qe(e,c)).docs.map(p=>a(p.data())),s.getAll=async(c={})=>(await Qe(e,c)).docs.map(p=>a(p.data())),s.onSnapshot=(c,u,p)=>je(e,c).onSnapshot(b=>{u(b.docs.map(h=>a(h.data())));},p),s.paginate=async c=>{let{include:u,...p}=c,f=await rn(e,p),b=o?{...f,data:f.data.map(h=>ue(h,o))}:f;if(u&&u.length>0){let h=await l(b.data,u);return {...b,data:h}}return b},s.paginateAll=async function*(c){let{include:u,...p}=c;for await(let f of qn(e,p)){let b=o?{...f,data:f.data.map(h=>ue(h,o))}:f;if(u&&u.length>0){let h=await l(b.data,u);yield {...b,data:h};}else yield b;}},s}function xo(e,t){return {populate:async(n,r)=>{if(!e.relationalKeys)return {...n,populated:{}};let o,s={};if(typeof r=="object"&&!Array.isArray(r))if("relation"in r){let c=r;o=[c.relation],c.select&&(s[c.relation]=c.select);}else if("relations"in r){let c=r;o=Array.isArray(c.relations)?c.relations:[c.relations],s=c.select??{};}else o=[];else o=Array.isArray(r)?r:[r];let a=await Promise.all(o.map(async c=>{let u=e.relationalKeys?.[c];if(!u)return console.warn(`[populate] Relation "${c}" not found in config`),[c,void 0];let p=t[u.repo];if(!p)return console.warn(`[populate] Repository "${u.repo}" not found in mapping`),[c,void 0];let f=u.sourceKey||c,b=n[f];if(b==null)return [c,u.type==="one"?null:[]];let h=s[c],w=h?{select:h}:void 0;try{if(u.type==="one"){let T=`by${He(u.key)}`,S=typeof p.get?.[T]=="function"?await p.get[T](b,w):null;return [c,S]}else {let T=`by${He(u.key)}`,S=typeof p.query?.[T]=="function"?await p.query[T](b,w):[];return [c,S]}}catch(T){return console.error(`[populate] Error populating "${c}":`,T),[c,u.type==="one"?null:[]]}})),l={};for(let[c,u]of a)u!==void 0&&(l[c]=u);return {...n,populated:l}}}}var Ro=new Set([4,8,10,13,14]),Ha=5,_a=3,Ma=100,Fa=500;async function Na(e){let t=0;for(;;){t++;try{return await e.get()}catch(n){let r=n?.code;if(!(typeof r=="number"&&Ro.has(r))||t>=_a)throw n;let s=Ma*2**(t-1);await new Promise(a=>setTimeout(a,s));}}}function So(e,t,n,r,o,s){let a=()=>new Date;return {backfillKeys:async(c={})=>{let{overwriteCreated:u=false,touchUpdated:p=true,overwritePath:f=false,pageSize:b=300,dryRun:h=false,maxAttempts:w=5,flushThreshold:T=Fa,onError:S,onSuccess:I}=c,A=Math.max(1,T),O=Array.from(new Set([n,r,o,s].filter(C=>typeof C=="string"&&C.length>0))),x=[],d=0,y=0,i=0,g=0,m=h?null:e.bulkWriter();try{m&&(m.onWriteError(k=>{let R=k?.code;if(R===Ha)return i++,!1;if(k.failedAttempts<w&&R!==void 0&&Ro.has(R))return !0;let P={path:k?.documentRef?.path??"(unknown)",error:k};return x.push(P),S?.(P),!1}),m.onWriteResult(k=>{y++,I?.(k.path);}));let C;for(;;){let k=t.orderBy(FieldPath.documentId());O.length>0&&typeof k.select=="function"&&(k=k.select(...O)),C&&(k=k.startAfter(C)),k=k.limit(b);let R=await Na(k);if(R.empty)break;for(let P of R.docs){d++;let _=P.data(),$={};if(n&&(_[n]==null||_[n]==="")&&($[n]=P.id),r&&(f||_[r]==null||_[r]==="")&&_[r]!==P.ref.path&&($[r]=P.ref.path),o&&(u||_[o]==null)&&($[o]=P.createTime?.toDate?.()??a()),p&&s&&_[s]==null&&($[s]=P.updateTime?.toDate?.()??P.createTime?.toDate?.()??a()),Object.keys($).length===0){i++;continue}m?(Promise.resolve(m.update(P.ref,$)).catch(()=>{}),g++,g>=A&&typeof m.flush=="function"&&(await m.flush(),g=0)):y++;}if(R.size<b)break;C=R.docs[R.docs.length-1];}}finally{m&&await m.close();}return {scanned:d,written:y,skipped:i,failures:x}}}}function vo(e,t,n,r,o,s,a){let l=()=>new Date,c=ve(a);return {run:async u=>e.runTransaction(async p=>u({get:async(...b)=>{let h=t(...b),w=await p.get(h);return w.exists?ue(ce({...w.data(),docId:w.id}),c):null},set:(...b)=>{let h=b[b.length-1],w=typeof h=="object"&&h!==null&&"merge"in h,T=w?b[b.length-2]:b[b.length-1],S=w?b.slice(0,-2):b.slice(0,-1),I=w?h:{merge:true},A=t(...S),O={...T},x=S[S.length-1];n&&x&&(O[n]=x),r&&(O[r]=A.path),o&&O[o]===void 0&&(O[o]=l()),s&&(O[s]=l()),xe(O,a),p.set(A,O,I);},update:(...b)=>{let h=b[b.length-1],w=b.slice(0,-1),T=t(...w),S={...h};s&&(S[s]=l()),xe(S,a),p.update(T,S);},delete:(...b)=>{let h=t(...b);p.delete(h);},raw:p}))}}function To(e){if(typeof e!="function")return [];let n=e.toString().match(/^\s*(?:function\s*\w*\s*)?\(([^)]*)\)/);if(!n?.[1])return [];let r=n[1].split(",").map(o=>o.trim().replace(/\s*[:=].*$/,"").trim()).filter(Boolean);return r.length<=2?[]:r.slice(1,-1)}function ja(e){let t=e?.documentKey??"docId",n=!!e?.isGroup,r=_e(typeof e?.path=="string"?e.path:"",t,n),o=r.parentKeys.length>0?r.parentKeys:n?To(e?.refCb):[],s=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(l=>typeof l=="string"),a=e?.history&&typeof e.history=="object"?e.history:void 0;return {schema:e?.schema,_systemKeys:s,_pathKey:e?.pathKey??null,_isGroup:n,_createdKey:e?.createdKey??null,_parentKeys:o,_documentPathTemplate:r.documentPathTemplate,_collectionId:typeof e?.path=="string"?r.collectionId:null,relationalKeys:e?.relationalKeys,_historyConfig:a,_historyShadowKey:ve(a),_historyIdentityKeys:Vn(a),_historySubcollection:a?.enabled?a.subcollection??"history":void 0,_collectionPath:typeof e?.path=="string"?r.collectionPath:null}}function dn(e,t){let n=ja(e),r,o=()=>{let s=r??(r=t());if(!s){let a=n._collectionPath||"unknown";throw new Error(`[makeLazyRepo] Failed to resolve repository for path "${a}". The repository mapping resolved to undefined. This almost always indicates a circular import where the repository was exported as undefined.`)}return s};return new Proxy(n,{get(s,a){return typeof a=="string"&&a in n?n[a]:o()[a]},has(s,a){return typeof a=="string"&&a in n?true:a in o()}})}function nr(e,t,n={}){let r=t.documentKey,o=_e(t.path,r,!!t.isGroup),s=o.parentKeys.length>0?o.parentKeys:t.isGroup?To(t.refCb):[],a=t.isGroup?e.collectionGroup(o.collectionId):e.collection(o.collectionPath),l=t.isGroup?null:e.collection(o.collectionPath),c=typeof t.refCb=="function"?(...y)=>t.refCb(e,...y):(...y)=>ho(e,o.documentPathTemplate??`${o.collectionPath}/{${r}}`,y),u=t.history,p=ve(u),f=Vn(u),b=bo(a,t.foreignKeys,l,c,r,p),h=wo(a,t.queryKeys,t.relationalKeys,n,p),w=fo(a),T=go(l,c,r,t.pathKey,t.createdKey,t.updatedKey,s,o.documentPathTemplate,u),S=yo(e,c,t.documentKey,t.pathKey,t.createdKey,t.updatedKey,u),I=vo(e,c,t.documentKey,t.pathKey,t.createdKey,t.updatedKey,u),A=mo(e,t.createdKey,t.updatedKey,u),O=So(e,a,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),x=xo(t,n),d=u?.enabled?po(c,[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(y=>typeof y=="string"),t.path??"(unknown)",u):null;return {ref:a,documentRef:c,get:b,query:h,aggregate:w,...T,batch:S,transaction:I,bulk:A,system:O,...x,...d?{history:d}:{},_historySubcollection:d?u?.subcollection??"history":void 0,_historyConfig:u,_historyShadowKey:p,_historyIdentityKeys:f,schema:t.schema,relationalKeys:t.relationalKeys,_systemKeys:[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(y=>typeof y=="string"),_pathKey:t.pathKey??null,_isGroup:!!t.isGroup,_parentKeys:s,_documentPathTemplate:o.documentPathTemplate,_collectionId:o.collectionId,_collectionPath:o.collectionPath,_createdKey:t.createdKey??null}}var Ba="history";function za(e){let t=e&&typeof e.history=="object"&&e.history!==null?e.history:void 0,n=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(s=>typeof s=="string"),r=typeof e?.path=="string"?e.path:null,o=r?_e(r,e?.documentKey??"docId"):null;return {historyConfig:t,systemKeys:n,isGroup:!!e?.isGroup,collectionPath:o?o.collectionPath:null,documentPathTemplate:o&&(!e?.isGroup||o.collectionPath.includes("/"))?o.documentPathTemplate:null}}function qa(e){let t=e._historyConfig??(typeof e.history=="object"&&e.history!==null&&"enabled"in e.history?e.history:void 0),n=e._collectionPath??e.ref?.path??null,r=typeof e._documentPathTemplate=="string"?e._documentPathTemplate:null;return {historyConfig:t,systemKeys:e._systemKeys??[],isGroup:!!e._isGroup,collectionPath:n,documentPathTemplate:r&&(!e._isGroup||n&&n.includes("/"))?r:null}}function Ua(e,t){return t?`${t}/{docId}`:(console.warn(`[HistoryTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function ko(e,t){let{onDocumentWritten:n}=t.deps,r={},o=e?.rawMapping,s=o?Object.entries(o).map(([a,l])=>[a,za(l)]):Object.entries(e).map(([a,l])=>[a,qa(l)]);for(let[a,l]of s){let c=l.historyConfig;if(!c?.enabled)continue;let u=c.subcollection??Ba,p=c.ttl??t.defaults?.ttl,f=t.repos?.[a],b;if(l.isGroup){let O=f?.triggerPath??l.documentPathTemplate;if(!O){console.warn(`[HistoryTriggers] Skipping collection-group repo "${a}". Provide a triggerPath in the history triggers repos override or use a full path template.`);continue}b=O;}else b=f?.triggerPath??l.documentPathTemplate??Ua(a,l.collectionPath);if(!b)continue;let h=l.systemKeys,w=h[0]??"docId",T=cn(c),S={...t.triggerOptions,...c?.triggerOptions,...f?.triggerOptions},I=Object.keys(S).length>0,A=async O=>{try{let x=O.data?.before?.data(),d=O.data?.after?.data(),y;if(!x&&d)y="create";else if(x&&!d)y="delete";else if(x&&d)y="update";else return;let i=String(d?.[w]??x?.[w]??O.params?.docId??O.data?.after?.id??O.data?.before?.id??"");if(!i)return;let g=sn(x??{},d??{},{include:c.include,exclude:c.exclude,metaFields:T,systemKeys:h});if(y==="update"&&Object.keys(g).length===0)return;let m=an(d??x??null,c),C=Et({entityId:i,operation:y,changes:g,meta:m,config:c,ttlOverride:p}),k=O.data?.after?.ref??O.data?.before?.ref;if(!k)return;let R=k.collection(u);await Ot(R,C,c,{repoName:a,docId:i,before:x??null,after:d??null});}catch(x){console.error(`[HistoryTriggers] Failed to record history for "${a}":`,x);}};r[`${a}_onHistory`]=n(I?{document:b,...S}:b,A);}return r}function La(e){let t=[],n=e.replace(/[.*+?^${}()|[\]\\]/g,r=>r===":"?r:`\\${r}`).replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(r,o)=>(t.push(o),"([^/]+)"));return {pattern:new RegExp(`^${n}$`),paramNames:t}}function Ka(e){let t=e.path??e.url??"/",n=t.indexOf("?");return n===-1?t:t.slice(0,n)}var Me=class{constructor(){this.routes=[];this.middlewares=[];this.notFoundHandler=(t,n)=>{n.status(404).send("Not Found");};this.errorHandler=(t,n,r)=>{console.error("[MiniRouter]",t),r.status(500).send("Internal Server Error");};}use(t){return this.middlewares.push(t),this}get(t,n){return this.addRoute("GET",t,n)}post(t,n){return this.addRoute("POST",t,n)}put(t,n){return this.addRoute("PUT",t,n)}patch(t,n){return this.addRoute("PATCH",t,n)}delete(t,n){return this.addRoute("DELETE",t,n)}onNotFound(t){return this.notFoundHandler=t,this}onError(t){return this.errorHandler=t,this}addRoute(t,n,r){let{pattern:o,paramNames:s}=La(n);return this.routes.push({method:t.toUpperCase(),pattern:o,paramNames:s,handler:r}),this}async handle(t,n){let r=(t.method??"GET").toUpperCase(),o=Ka(t),s=null,a={};for(let u of this.routes){if(u.method!==r)continue;let p=o.match(u.pattern);if(p){s=u,a={},u.paramNames.forEach((f,b)=>{a[f]=decodeURIComponent(p[b+1]??"");});break}}let l=Object.assign(t,{params:a}),c=s?s.handler:this.notFoundHandler;try{await this.runMiddlewareChain(l,n,c);}catch(u){this.errorHandler(u,t,n);}}async runMiddlewareChain(t,n,r){let o=0,s=async()=>{if(o<this.middlewares.length){let a=this.middlewares[o++];await a(t,n,s);}else await r(t,n);};await s();}};function Oe(e,t,n){let r=t==="/"?"":t.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let a=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",l=n??process.env.FUNCTION_REGION??"us-central1",c=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${a}/${l}/${c}${r}`}let o=process.env.K_SERVICE,s=e?.hostname??e?.headers?.host??"";return o&&typeof s=="string"&&s.includes("cloudfunctions.net")?`/${o.toLowerCase()}${r}`:r}function un(e){if(typeof e=="string")return e;if(Array.isArray(e)){let t=e[0];return typeof t=="string"?t:void 0}}function Pt(e){return !!e&&typeof e=="object"&&e.__authExtension===true}function rr(e,t,n=new WeakSet,r=0){if(e==null)return null;if(typeof e=="object"&&typeof e.toDate=="function")return e.toDate().toISOString();if(e instanceof Date)return e.toISOString();if(Buffer.isBuffer(e))return e.toString("base64");if(e instanceof Uint8Array)return Buffer.from(e).toString("base64");if(typeof e=="object"&&"latitude"in e&&"longitude"in e){let o=e;return t?.stringifyArrays===false?{lat:o.latitude,lng:o.longitude}:JSON.stringify({lat:o.latitude,lng:o.longitude})}if(Array.isArray(e)){let o=e.map(s=>rr(s,t,n,r+1));return t?.stringifyArrays===false?o:JSON.stringify(o)}return typeof e=="object"&&e!==null&&t?.stringifyArrays===false?or(e,new Set,{},n,r+1):e}var Ao=32,Qa=5e3;function Eo(e,t,n,r=new WeakSet,o=0){if(o>Ao){n[t||"_truncated"]=JSON.stringify({__truncated:true});return}if(r.has(e)){n[t||"_cycle"]=JSON.stringify({__cycle:true});return}r.add(e);for(let[s,a]of Object.entries(e)){if(Object.keys(n).length>=Qa)break;let l=t?`${t}__${s}`:s;a!=null&&typeof a=="object"&&!Array.isArray(a)&&!(a instanceof Date)&&!Buffer.isBuffer(a)&&!(a instanceof Uint8Array)&&typeof a.toDate!="function"&&!("latitude"in a&&"longitude"in a)?Eo(a,l,n,r,o+1):n[l]=rr(a);}r.delete(e);}function or(e,t,n,r=new WeakSet,o=0){if(o>Ao)return {__truncated:true};if(r.has(e))return {__cycle:true};r.add(e);let s={};for(let[a,l]of Object.entries(e)){if(t.has(a))continue;let c=n[a]??a;l!=null&&typeof l=="object"&&!Array.isArray(l)&&!(l instanceof Date)&&!Buffer.isBuffer(l)&&!(l instanceof Uint8Array)&&typeof l.toDate!="function"&&!("latitude"in l&&"longitude"in l)?s[c]=or(l,new Set,{},r,o+1):s[c]=rr(l,{stringifyArrays:false},r,o+1);}return r.delete(e),s}function Oo(e){let t={};for(let[n,r]of Object.entries(e)){let o=r;if(typeof o=="string"){let l=o.trim();if(l.startsWith("[")&&l.endsWith("]")||l.startsWith("{")&&l.endsWith("}"))try{o=JSON.parse(l);}catch{}}if(n.startsWith("__")||!n.includes("__")){t[n]=o;continue}let s=n.split("__").filter(Boolean),a=t;for(let l=0;l<s.length-1;l++){let c=s[l];(!a[c]||typeof a[c]!="object"||Array.isArray(a[c]))&&(a[c]={}),a=a[c];}a[s[s.length-1]]=o;}return t}function It(e,t){let n=t?.flat!==false,r;if(n){let o=new Set(t?.exclude),s=t?.columnMap??{},a=e;if(o.size>0){let c=false,u={};for(let[p,f]of Object.entries(e)){if(o.has(p)){c=true;continue}u[p]=f;}c&&(a=u);}let l={};Eo(a,"",l),r={};for(let[c,u]of Object.entries(l)){if(o.has(c))continue;let p=c.split("__")[0];if(p!==c&&o.has(p))continue;let f=s[c]??(c.includes("__")?s[c.split("__").pop()]:void 0)??c;r[f]=u;}}else {let o=new Set(t?.exclude),s=t?.columnMap??{};r=or(e,o,s);}return typeof t?.transformDoc=="function"&&(r=t.transformDoc(r)),r}function G(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Fe(e,t,n){let r=G(e),o=G(t);return `<!DOCTYPE html>
1
+ import {jsx,jsxs,Fragment}from'hono/jsx/jsx-runtime';import {Timestamp,Filter,Query,FieldPath}from'firebase-admin/firestore';import {AsyncLocalStorage}from'async_hooks';import {randomUUID,randomBytes}from'crypto';import {z as z$1}from'zod';import {renderToString}from'hono/jsx/dom/server';import {extendZodWithOpenApi,OpenAPIRegistry,OpenApiGeneratorV31,getOpenApiMetadata}from'@asteasolutions/zod-to-openapi';import {Hono}from'hono';import {getRequestListener}from'@hono/node-server';var _n=Object.defineProperty;var Ks=Object.getOwnPropertyDescriptor;var Zs=Object.getOwnPropertyNames;var Ws=Object.prototype.hasOwnProperty;var Zr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var St=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Wr=(e,t)=>{for(var n in t)_n(e,n,{get:t[n],enumerable:true});},Qs=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Zs(t))!Ws.call(e,o)&&o!==n&&_n(e,o,{get:()=>t[o],enumerable:!(r=Ks(t,o))||r.enumerable});return e};var Vs=e=>Qs(_n({},"__esModule",{value:true}),e);function X(e){let t=e,n=t._zod?.def?.type;if(n)return ai[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=t._def?.typeName;return r||""}function me(e){let t=e;if(t._zod?.def?.innerType)return t._zod.def.innerType;if(t._def?.innerType)return t._def.innerType}function $t(e){let t=e,n=t._zod?.def?.in;if(n)return n;if(t._def?.schema)return t._def.schema}function pn(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}function Ho(e){let t=e;if(t._zod?.def?.defaultValue!==void 0)return t._zod.def.defaultValue;let n=t._def?.defaultValue;return typeof n=="function"?n():n}function he(e){let t=e;return t.shape&&typeof t.shape=="object"?t.shape:t._zod?.def?.shape&&typeof t._zod.def.shape=="object"?t._zod.def.shape:t._def?.shape?typeof t._def.shape=="function"?t._def.shape():t._def.shape:{}}function Ht(e){let t=e;return Array.isArray(t.options)?t.options:t._zod?.def?.entries?Object.values(t._zod.def.entries):Array.isArray(t._def?.values)?t._def.values:[]}function _t(e){let t=e;return t._zod?.def?.entries?t._zod.def.entries:t.enum&&typeof t.enum=="object"?t.enum:t._def?.values&&typeof t._def.values=="object"?t._def.values:{}}function Mt(e){let t=e;return Array.isArray(t._zod?.def?.values)?t._zod.def.values[0]:t._def?.value}function Nt(e){let t=e;return Array.isArray(t.options)?t.options:Array.isArray(t._zod?.def?.options)?t._zod.def.options:Array.isArray(t._def?.options)?t._def.options:[]}function _o(e){let t=e,n=[],r=t._zod?.def?.checks;if(Array.isArray(r)){for(let s of r)s.format&&n.push(s.format);if(n.length>0)return n}let o=t._def?.checks;if(Array.isArray(o))for(let s of o)s.kind&&n.push(s.kind);return n}var ai,ft=St(()=>{"use strict";ai={string:"ZodString",number:"ZodNumber",bigint:"ZodBigInt",boolean:"ZodBoolean",date:"ZodDate",enum:"ZodEnum",nativeEnum:"ZodNativeEnum",literal:"ZodLiteral",object:"ZodObject",array:"ZodArray",optional:"ZodOptional",nullable:"ZodNullable",default:"ZodDefault",coerce:"ZodCoerce",union:"ZodUnion",undefined:"ZodUndefined",unknown:"ZodUnknown",any:"ZodAny",record:"ZodRecord"};});function Jo({val:e}){return jsx("span",{class:"text-sm text-base-content/80 font-mono tabular-nums whitespace-nowrap",children:e.toLocaleString()})}function Ei({message:e}){return jsx("span",{class:"tooltip tooltip-warning tooltip-right inline-flex align-middle ml-1 text-warning","data-tip":e,role:"img","aria-label":e,children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",class:"size-3.5",children:jsx("path",{d:"M12 2 1 22h22L12 2zm0 6 7.5 13h-15L12 8zm-1 4v4h2v-4h-2zm0 5v2h2v-2h-2z"})})})}function ht({val:e,mismatch:t}){let n=ur(e);return t?jsxs("span",{class:"inline-flex items-start gap-0.5",children:[n,jsx(Ei,{message:t})]}):n}function ur(e){if(e==null)return jsx("span",{class:"opacity-30 italic text-xs",children:"\u2014"});if(typeof e=="boolean")return e?jsx("span",{class:"badge badge-success badge-sm",children:"true"}):jsx("span",{class:"badge badge-error badge-sm",children:"false"});if(e instanceof Date)return jsx(Jo,{val:e});if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")return jsx(Jo,{val:e.toDate()});if(typeof e=="number")return jsx("span",{class:"text-sm font-mono tabular-nums",children:String(e)});if(Array.isArray(e))return e.length===0?jsx("span",{class:"text-xs text-base-content/30",children:"[]"}):jsxs("ul",{class:"list-none p-0 m-0 space-y-0.5 text-xs",children:[e.slice(0,8).map((n,r)=>jsx("li",{class:"break-all",children:ur(n)},r)),e.length>8&&jsxs("li",{class:"text-base-content/40 italic",children:["+",e.length-8," more\u2026"]})]});if(typeof e=="object"&&e!==null){let n=Object.entries(e);return n.length===0?jsx("span",{class:"text-xs text-base-content/30",children:"{}"}):jsxs("dl",{class:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 text-xs m-0",children:[n.slice(0,8).map(([r,o])=>jsxs(Fragment,{children:[jsx("dt",{class:"text-base-content/50 font-semibold whitespace-nowrap",children:r}),jsx("dd",{class:"break-all",children:ur(o)})]})),n.length>8&&jsxs("dt",{class:"col-span-2 text-base-content/40 italic",children:["+",n.length-8," more\u2026"]})]})}let t=String(e);return jsx("span",{class:"text-sm break-all",children:t})}var xn=St(()=>{"use strict";});function qt(e){if(!e)return "unknown";let t=pr(e);switch(X(t)){case "ZodString":return "string";case "ZodNumber":return "number";case "ZodBigInt":return "bigint";case "ZodBoolean":return "boolean";case "ZodDate":return "date";case "ZodArray":return "array";case "ZodObject":case "ZodRecord":return "object";case "ZodEnum":case "ZodNativeEnum":return "enum";case "ZodLiteral":return "literal";default:return "unknown"}}function pr(e){let t=X(e);if(t==="ZodOptional"||t==="ZodNullable"||t==="ZodDefault"){let n=me(e);return n?pr(n):e}return e}function Ut(e,t){if(!e)return;let n=t.split("."),r=e;for(let o of n){if(!r)return;let s=pr(r);if(X(s)!=="ZodObject")return;r=he(s)[o];}return r}function Di(e){return e==null?"null":e instanceof Date?"date":Array.isArray(e)?"array":typeof e=="string"?"string":typeof e=="boolean"?"boolean":typeof e=="bigint"?"bigint":typeof e=="number"?"number":typeof e=="object"?typeof e.toDate=="function"?"date":"object":"unknown"}function Lt(e,t){if(e==="unknown")return null;let n=Di(t);return n==="null"?null:e==="enum"||e==="literal"?n==="string"||n==="number"?null:`Expected ${e} (string/number), got ${n}`:e===n||e==="number"&&n==="bigint"||e==="bigint"&&n==="number"?null:`Expected ${e}, got ${n}`}var fr=St(()=>{"use strict";ft();});var es={};Wr(es,{PanelMany:()=>Hi,PanelOne:()=>$i,RightPanel:()=>yr});function $i({doc:e,repoName:t,basePath:n,schema:r,columns:o}){if(!e)return jsx("div",{class:"text-center py-12 text-base-content/50",children:"Document not found."});let s=String(e.docId??e.id??""),a=`${n}/${t}/${encodeURIComponent(s)}/edit`,l=Xo(r,o);return jsxs("div",{class:"space-y-4",children:[jsxs("div",{class:"flex items-center justify-between gap-2",children:[jsxs("div",{class:"text-xs text-base-content/60",children:[jsx("span",{class:"font-mono",children:t}),jsx("span",{class:"opacity-50",children:" \xB7 "}),jsx("span",{class:"font-mono break-all",children:s})]}),jsx("a",{href:a,class:"btn btn-sm btn-primary",children:"Edit \u2192"})]}),jsx("dl",{class:"grid grid-cols-[max-content_1fr] gap-x-4 gap-y-2 border border-base-300 rounded-box p-4 bg-base-100",children:o.map(c=>{let u=e[c],p=l[c],f=p?Lt(p,u):null;return jsxs(Fragment,{children:[jsx("dt",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide pt-0.5",children:c}),jsx("dd",{class:"min-w-0",children:jsx(ht,{val:u,mismatch:f})})]})})})]})}function Hi({docs:e,repoName:t,basePath:n,fk:r,fv:o,columns:s,schema:a,pagination:l}){let c=`${n}/${t}?fv_${r}=${encodeURIComponent(o)}`,u=Xo(a,s);return jsxs("div",{class:"space-y-4",children:[jsxs("div",{class:"flex items-center justify-between gap-2",children:[jsxs("div",{class:"text-xs text-base-content/60",children:[jsx("span",{class:"font-mono",children:t}),jsx("span",{class:"opacity-50",children:" where "}),jsx("span",{class:"font-mono",children:r}),jsx("span",{class:"opacity-50",children:" = "}),jsx("span",{class:"font-mono break-all",children:o}),jsx("span",{class:"opacity-50",children:" \xB7 "}),jsxs("span",{children:[e.length," doc",e.length!==1?"s":""]})]}),jsx("a",{href:c,class:"btn btn-sm btn-outline",children:"Full view \u2192"})]}),jsx("div",{class:"overflow-x-auto rounded-box border border-base-300 bg-base-100",children:jsxs("table",{class:"table table-xs w-full",children:[jsx("thead",{children:jsxs("tr",{class:"bg-base-200/50",children:[s.map((p,f)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:p},f)),jsx("th",{})]})}),jsx("tbody",{children:e.length===0?jsx("tr",{children:jsx("td",{colspan:s.length+1,class:"text-center py-10 text-base-content/40",children:"No related documents"})}):e.map((p,f)=>{let b=String(p.docId??p.id??""),h=`${n}/${t}/${encodeURIComponent(b)}/edit`;return jsxs("tr",{class:"hover",children:[s.map((w,T)=>{let S=p[w],I=u[w],A=I?Lt(I,S):null;return jsx("td",{class:"align-top py-1.5",children:jsx(ht,{val:S,mismatch:A})},T)}),jsx("td",{class:"text-right py-1.5",children:jsx("a",{href:h,class:"btn btn-xs btn-ghost",children:"Edit"})})]},f)})})]})}),(l.hasPrev||l.hasNext)&&jsxs("div",{class:"flex justify-center items-center gap-2",children:[l.hasPrev?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"prev","data-cursor":l.prevCursor,children:"\u2190 Previous"}):jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"\u2190 Previous"}),l.hasNext?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"next","data-cursor":l.nextCursor,children:"Next \u2192"}):jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"Next \u2192"})]})]})}function Xo(e,t){if(!e)return {};let n={};for(let r of t)n[r]=qt(Ut(e,r));return n}var yr,mr=St(()=>{"use strict";xn();fr();yr=({basePath:e=""})=>jsxs("div",{class:"fixed inset-0 z-[100] hidden pointer-events-none","data-frs-panel-root":!0,"data-frs-base-path":e,"aria-hidden":"true",children:[jsx("div",{class:"absolute inset-0 bg-black/30 opacity-0 transition-opacity duration-200 pointer-events-auto","data-frs-panel-backdrop":!0}),jsxs("aside",{class:"absolute top-0 right-0 h-full w-full md:w-1/2 bg-base-100 shadow-2xl border-l border-base-300 translate-x-full transition-transform duration-200 pointer-events-auto flex flex-col","data-frs-panel":!0,role:"dialog","aria-label":"Relation preview",children:[jsxs("header",{class:"flex items-center justify-between px-5 py-3 border-b border-base-300 bg-base-200/40 shrink-0",children:[jsx("h2",{class:"font-semibold text-base truncate","data-frs-panel-title":!0,children:"Relation"}),jsx("button",{type:"button",class:"btn btn-sm btn-ghost btn-circle","data-frs-panel-close":!0,"aria-label":"Close panel",children:"\u2715"})]}),jsx("div",{class:"flex-1 overflow-auto p-5 text-sm","data-frs-panel-body":!0,children:jsx("div",{class:"flex items-center justify-center py-12 text-base-content/40",children:jsx("span",{class:"loading loading-spinner loading-md"})})})]})]});});var ms={};Wr(ms,{DEFAULT_HTML_CSP:()=>Er,securityHeaders:()=>Tn});function Tn(e={}){let t=e.csp===void 0?Er:e.csp,n=e.frameOptions===void 0?"DENY":e.frameOptions,r=e.referrerPolicy===void 0?"no-referrer":e.referrerPolicy,o=e.cacheControl===void 0?"private, no-store":e.cacheControl;return async(s,a,l)=>{typeof a?.setHeader=="function"&&(a.setHeader("X-Content-Type-Options","nosniff"),n&&a.setHeader("X-Frame-Options",n),r&&a.setHeader("Referrer-Policy",r),o&&a.setHeader("Cache-Control",o),t&&a.setHeader("Content-Security-Policy",t)),await l();}}var fs,ys,Er,kn=St(()=>{"use strict";fs="https://cdn.jsdelivr.net",ys="https://www.gstatic.com",Er=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${fs} ${ys}`,`style-src 'self' 'unsafe-inline' ${fs}`,`connect-src 'self' ${ys} https://*.googleapis.com https://*.firebaseio.com https://identitytoolkit.googleapis.com`,"img-src 'self' data:","font-src 'self' data:","frame-ancestors 'none'","base-uri 'self'","form-action 'self'"].join("; ");});var Gs=30,Js=99,Xt="__name__",Ys=new Set(["<","<=",">",">=","!=","not-in"]);var Xs=55296,ea=57343;function Vr(e){return e>=Xs&&e<=ea}function lt(e,t){let n=Math.min(e.length,t.length);for(let r=0;r<n;r++){let o=e.charCodeAt(r),s=t.charCodeAt(r);if(o!==s){let a=Vr(o),l=Vr(s);return a===l?o<s?-1:1:a?1:-1}}return e.length<t.length?-1:e.length>t.length?1:0}function Gr(e){return e.length>6&&e.startsWith("__id")&&e.endsWith("__")&&/^-?\d+$/.test(e.slice(4,-2))}function ta(e,t){let n=Gr(e),r=Gr(t);if(n&&!r)return -1;if(!n&&r)return 1;if(n&&r){let o=BigInt(e.slice(4,-2)),s=BigInt(t.slice(4,-2));return o<s?-1:o>s?1:0}return lt(e,t)}function no(e,t){let n=e.split("/"),r=t.split("/"),o=Math.min(n.length,r.length);for(let s=0;s<o;s++){let a=ta(n[s],r[s]);if(a!==0)return a}return n.length<r.length?-1:n.length>r.length?1:0}function na(e,t){let n=e.split("."),r=t.split("."),o=Math.min(n.length,r.length);for(let s=0;s<o;s++){let a=lt(n[s],r[s]);if(a!==0)return a}return n.length<r.length?-1:n.length>r.length?1:0}function vt(e,t){return e<t?-1:e>t?1:e===t?0:Number.isNaN(e)?Number.isNaN(t)?0:-1:1}function Mn(e){if(e instanceof Date){let t=e.getTime();if(Number.isNaN(t))return {seconds:Number.NaN,nanos:0};let n=Math.floor(t/1e3),r=(t%1e3+1e3)%1e3;return {seconds:n,nanos:r*1e6}}if(typeof e=="object"&&e!==null){let t=e;if(typeof t.seconds=="number"&&typeof t.nanoseconds=="number"&&typeof t.toDate=="function")return {seconds:t.seconds,nanos:t.nanoseconds};if(typeof t._seconds=="number"&&typeof t._nanoseconds=="number"&&Object.keys(t).length===2)return {seconds:t._seconds,nanos:t._nanoseconds}}return null}function ra(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.path=="string"&&typeof t.id=="string"&&typeof t.firestore=="object"&&t.firestore!==null}function oa(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.latitude=="number"&&typeof t.longitude=="number"&&typeof t.isEqual=="function"}function Jr(e){if(e===void 0)return -1;if(e===null)return 0;let t=typeof e;return t==="boolean"?1:t==="number"||t==="bigint"?2:t==="string"?4:e instanceof Uint8Array?5:Mn(e)!==null?3:ra(e)?6:oa(e)?7:Array.isArray(e)?8:9}function sa(e,t){let n=Math.min(e.length,t.length);for(let r=0;r<n;r++){let o=e[r],s=t[r];if(o!==s)return o<s?-1:1}return e.length<t.length?-1:e.length>t.length?1:0}function Nn(e,t){let n=Jr(e),r=Jr(t);if(n!==r)return n<r?-1:1;switch(n){case -1:case 0:return 0;case 1:return e===t?0:e?1:-1;case 2:return vt(Number(e),Number(t));case 3:{let o=Mn(e),s=Mn(t),a=vt(o.seconds,s.seconds);return a!==0?a:vt(o.nanos,s.nanos)}case 4:return lt(e,t);case 5:return sa(e,t);case 6:return no(e.path,t.path);case 7:{let o=e,s=t,a=vt(o.latitude,s.latitude);return a!==0?a:vt(o.longitude,s.longitude)}case 8:{let o=e,s=t,a=Math.min(o.length,s.length);for(let l=0;l<a;l++){let c=Nn(o[l],s[l]);if(c!==0)return c}return o.length<s.length?-1:o.length>s.length?1:0}case 9:{let o=e,s=t,a=Object.keys(o).sort(lt),l=Object.keys(s).sort(lt),c=Math.min(a.length,l.length);for(let u=0;u<c;u++){let p=a[u],f=l[u],b=lt(p,f);if(b!==0)return b;let h=Nn(o[p],s[f]);if(h!==0)return h}return a.length<l.length?-1:a.length>l.length?1:0}}}function Fn(e){return e.ref?.path??e.id}function Yr(e,t){if(typeof e.get=="function")return e.get(t);let n=e.data();if(!n)return;if(!t.includes("."))return n[t];let r=n;for(let o of t.split(".")){if(r==null||typeof r!="object")return;r=r[o];}return r}function aa(e,t){let n=[],r=new Set;if(e.orderBy)for(let a of e.orderBy){let l=String(a.field),c=a.direction==="desc"?"desc":"asc";r.has(l)||(n.push({field:l,direction:c}),r.add(l));}let o=n.length>0?n[n.length-1].direction:"asc",s=[];for(let[a,l]of t){let c=String(a);Ys.has(l)&&c!==Xt&&!r.has(c)&&(s.push(c),r.add(c));}s.sort(na);for(let a of s)n.push({field:a,direction:o});return r.has(Xt)||n.push({field:Xt,direction:o}),n}function ia(e,t,n){for(let r of n){let o=r.field===Xt?no(Fn(e),Fn(t)):Nn(Yr(e,r.field),Yr(t,r.field));if(o!==0)return r.direction==="desc"?-o:o}return 0}function ca(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function ct(e,t){return t.orderBy&&t.orderBy.forEach(n=>{e=e.orderBy(String(n.field),n.direction??"asc");}),t.limit&&(e=e.limit(t.limit)),t.offset&&(e=e.offset(t.offset)),t.select&&t.select.length>0&&(e=e.select(...t.select.map(n=>String(n)))),t.startAt&&(e=Array.isArray(t.startAt)?e.startAt(...t.startAt):e.startAt(t.startAt)),t.startAfter&&(e=Array.isArray(t.startAfter)?e.startAfter(...t.startAfter):e.startAfter(t.startAfter)),t.endAt&&(e=Array.isArray(t.endAt)?e.endAt(...t.endAt):e.endAt(t.endAt)),t.endBefore&&(e=Array.isArray(t.endBefore)?e.endBefore(...t.endBefore):e.endBefore(t.endBefore)),e}function Xr(e){if(!e.offset||e.offset<=0)return e;let{offset:t,limit:n,...r}=e;return {...r,...n&&n>0?{limit:t+n}:{}}}function We(e){let[,t,n]=e;return (t==="in"||t==="array-contains-any")&&Array.isArray(n)&&n.length>30}function en(e){let[t,n,r]=e;return We(e)?ca(r,30).map(s=>[t,n,s]):[e]}function Ee(e,t){let n=e;for(let[r,o,s]of t)n=n.where(String(r),o,s);return n}async function eo(e,t,n){let r=await Promise.all(e.map(f=>f.get())),o=new Map;r.forEach(f=>{f.docs.forEach(b=>{let h=Fn(b);o.has(h)||o.set(h,b);});});let s=r[0];if(!s)throw new Error("No snapshots returned");let a=aa(t,n),l=Array.from(o.values()).sort((f,b)=>ia(f,b,a)),c=t.offset&&t.offset>0?t.offset:0,u=t.limit&&t.limit>0?c+t.limit:void 0,p=c>0||u!==void 0?l.slice(c,u):l;return {...s,docs:p,size:p.length,empty:p.length===0,forEach:(f,b)=>{p.forEach(h=>f.call(b,h));}}}async function Qe(e,t){let n=t.orWhere&&t.orWhere.length>0,r=t.orWhereGroups&&t.orWhereGroups.length>0;if(!n&&!r){if(!t.where||t.where.length===0)return ct(e,t).get();if(!t.where.some(We)){let w=Ee(e,t.where);return w=ct(w,t),w.get()}let p=t.where.map(en),f=Tt(p);if(f.length===1){let w=Ee(e,f[0]);return w=ct(w,t),w.get()}let b=Xr(t),h=f.map(w=>{let T=Ee(e,w);return T=ct(T,b),T});return eo(h,t,t.where)}let o=t.where??[],s=[...t.orWhere?.map(u=>[u])??[],...t.orWhereGroups??[]],a=[];for(let u of s){let p=[...o,...u];if(!p.some(We))a.push(p);else {let b=p.map(en),h=Tt(b);a.push(...h);}}if(a.length===1){let u=Ee(e,a[0]);return u=ct(u,t),u.get()}let l=Xr(t),c=a.map(u=>{let p=Ee(e,u);return p=ct(p,l),p});return eo(c,t,o)}function Tt(e){if(e.length===0)return [[]];let t=e[0];if(e.length===1&&t)return t.map(s=>[s]);if(!t)return [[]];let n=e.slice(1),r=Tt(n),o=[];for(let s of t)for(let a of r)o.push([s,...a]);return o}function la(e){return typeof Filter?.or=="function"&&typeof Filter?.and=="function"&&typeof Filter?.where=="function"&&typeof Query=="function"&&e instanceof Query}function da(e,t){if(t.length<2)return false;let n=0,r=a=>{let[,l,c]=a;return !(We(a)||l==="not-in"||(l==="in"||l==="array-contains-any")&&(!Array.isArray(c)||c.length===0)||l==="!="&&(n++,n>1))};for(let a of e)if(!r(a))return false;let o=0,s=0;for(let a of t){for(let p of a)if(!r(p))return false;let l=[...e,...a],c=0,u=1;for(let[,p,f]of l)if((p==="array-contains"||p==="array-contains-any")&&(c++,c>1)||(p==="in"||p==="array-contains-any"?u*=f.length:p==="!="&&(u*=2),o+u>Gs))return false;if(o+=u,s+=u*l.length,s>Js)return false}return true}function ua(e,t,n){let r=n.map(s=>{let a=s.map(([l,c,u])=>Filter.where(String(l),c,u));return a.length===1?a[0]:Filter.and(...a)});return (t.length>0?Ee(e,t):e).where(Filter.or(...r))}function ro(e){if(typeof e!="object"||e===null)return false;let t=e;if(t.code===9)return true;if(typeof t.code=="string"){let n=t.code.toLowerCase();if(n==="failed-precondition"||n==="failed_precondition")return true}return typeof t.message=="string"&&t.message.includes("requires an index")}function pa(e){if(ro(e))return true;if(typeof e!="object"||e===null)return false;let t=e.code;if(t===3)return true;if(typeof t=="string"){let n=t.toLowerCase();return n==="invalid-argument"||n==="invalid_argument"}return false}async function to(e,t){if(t.length===0)return {count:(await e.count().get()).data().count,isExact:true};if(!t.some(We))return {count:(await Ee(e,t).count().get()).data().count,isExact:true};let r=t.map(en),o=Tt(r),a=(await Promise.all(o.map(c=>Ee(e,c).count().get()))).reduce((c,u)=>c+u.data().count,0),l=t.some(c=>c[1]==="array-contains-any"&&We(c));return {count:a,isExact:!l}}async function jn(e,t,n){let r=t.where??[],o=[...t.orWhere?.map(u=>[u])??[],...t.orWhereGroups??[]].filter(u=>u.length>0);if(o.length===0)return to(e,r);if(o.length===1)return to(e,[...r,...o[0]]);let s;if(la(e)&&da(r,o))try{return {count:(await ua(e,r,o).count().get()).data().count,isExact:!0}}catch(u){if(!pa(u))throw u;ro(u)&&(s=u);}let a=[];for(let u of o){let p=[...r,...u];if(!p.some(We))a.push(Ee(e,p));else {let b=p.map(en),w=Tt(b).map(T=>Ee(e,T));a.push(...w);}}let c=(await Promise.all(a.map(u=>u.count().get()))).reduce((u,p)=>u+p.data().count,0);return s!==void 0&&n?.(s),{count:c,isExact:false}}var Bn="preserve";function fa(e){Bn=e;}function nn(){return Bn}function ya(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function zn(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof Timestamp)return e.toDate();if(ya(e))return new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));if(typeof e=="string"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function ma(e){if(typeof e!="object"||e===null)return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function tn(e){if(e instanceof Timestamp)return e.toDate();if(Array.isArray(e))return e.map(t=>tn(t));if(ma(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=tn(r);return t}return e}function le(e){return Bn==="normalize"?tn(e):e}function so(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function He(e){return e.charAt(0).toUpperCase()+e.slice(1)}function je(e,t){return t.where&&t.where.forEach(([n,r,o])=>{e=e.where(String(n),r,o);}),t.orderBy&&t.orderBy.forEach(n=>{e=e.orderBy(String(n.field),n.direction??"asc");}),t.limit&&(e=e.limit(t.limit)),t.offset&&(e=e.offset(t.offset)),t.select&&t.select.length>0&&(e=e.select(...t.select.map(n=>String(n)))),t.startAt&&(e=Array.isArray(t.startAt)?e.startAt(...t.startAt):e.startAt(t.startAt)),t.startAfter&&(e=Array.isArray(t.startAfter)?e.startAfter(...t.startAfter):e.startAfter(t.startAfter)),t.endAt&&(e=Array.isArray(t.endAt)?e.endAt(...t.endAt):e.endAt(t.endAt)),t.endBefore&&(e=Array.isArray(t.endBefore)?e.endBefore(...t.endBefore):e.endBefore(t.endBefore)),e}async function rn(e,t){let{onCountIndexError:n,...r}=t,o={...r,limit:t.pageSize+1};t.cursor&&(t.direction==="prev"?o.endBefore=t.cursor:o.startAfter=t.cursor);let[s,a]=await Promise.all([Qe(e,o),t.withTotal?jn(e,r,n):Promise.resolve(void 0)]),l=s.docs,c=l.length>t.pageSize,u=c?l.slice(0,t.pageSize):l,p=u.map(b=>le({...b.data(),docId:b.id})),f=t.direction==="prev";return {data:p,nextCursor:f?u.length>0?u[u.length-1]:void 0:c?u[u.length-1]:void 0,prevCursor:f?c?u[0]:void 0:u[0],hasNextPage:f?!!t.cursor:c,hasPrevPage:f?c:!!t.cursor,pageSize:p.length,...a!==void 0?{totalCount:a.count,totalCountIsExact:a.isExact}:{}}}async function*qn(e,t){let n,r=true;for(;r;){let o=await rn(e,{...t,cursor:n,direction:"next"});yield o,r=o.hasNextPage,n=o.nextCursor;}}var Ve="X-History-Reason",Ge="X-History-Comment",co=Symbol.for("@lpdjs/firestore-repo-service:actorResolverHeaders"),Un=Symbol.for("@lpdjs/firestore-repo-service:actorContext"),Ln=globalThis,on=Ln[Un]??(Ln[Un]=new AsyncLocalStorage);function ga(e,t){if(!t.includes("."))return e[t];let n=e;for(let r of t.split(".")){if(!n||typeof n!="object")return;n=n[r];}return n}function ao(e,t){for(let n of t){let r=ga(e,n);if(typeof r=="string"&&r.length>0)return r;if(typeof r=="number")return String(r)}return null}function io(e,t){if(t===false)return;let n=e?.req?.header;if(typeof n!="function")return;let r=n.call(e.req,t);return typeof r=="string"&&r.length>0?r:void 0}function Kn(e={}){let t=e.contextKeys??["user","docsUser"],n=e.userIdFields??["uid","id","sub"],r=e.userEmailFields??["email"],o=e.reasonHeader===void 0?"x-history-reason":e.reasonHeader,s=e.commentHeader===void 0?"x-history-comment":e.commentHeader,a=e.reasonHeader===void 0?Ve:e.reasonHeader,l=e.commentHeader===void 0?Ge:e.commentHeader,c=e.extras,u=p=>{let f=null,b=p?.get;if(typeof b=="function")for(let S of t){let I=b.call(p,S);if(I&&typeof I=="object"){f=I;break}}let h=io(p,o),w=io(p,s),T=c?c(p,f):void 0;return f?{userId:ao(f,n),userEmail:ao(f,r),...h!==void 0?{reason:h}:{},...w!==void 0?{comment:w}:{},...T?{extras:T}:{}}:h===void 0&&w===void 0&&!T?null:{...h!==void 0?{reason:h}:{},...w!==void 0?{comment:w}:{},...T?{extras:T}:{}}};return Object.defineProperty(u,co,{value:{reasonHeader:a,commentHeader:l},enumerable:false,configurable:false}),u}function Zn(e){if(!e)return {reasonHeader:Ve,commentHeader:Ge};if(typeof e=="function"){let t=e[co];return t?{...t}:{reasonHeader:Ve,commentHeader:Ge}}return {reasonHeader:e.reasonHeader===void 0?Ve:e.reasonHeader,commentHeader:e.commentHeader===void 0?Ge:e.commentHeader}}var lo=Kn();function ba(e){if(e)return typeof e=="function"?e:Kn(e)}function Wn(e){let t=ba(e);return async(n,r)=>{await on.run({c:n,resolver:t},async()=>{await r();});}}function ut(){let e=on.getStore();if(!e)return null;let t=null;if(e.c)try{t=(e.resolver??lo)(e.c);}catch{t=null;}if(!t&&!e.override)return null;let n={...t??{}};return e.override&&(e.override.userId!==void 0&&(n.userId=e.override.userId),e.override.userEmail!==void 0&&(n.userEmail=e.override.userEmail),e.override.reason!==void 0&&(n.reason=e.override.reason),e.override.comment!==void 0&&(n.comment=e.override.comment),e.override.extras!==void 0&&(n.extras={...t?.extras??{},...e.override.extras})),n}function wa(e,t){return on.run({override:{...e}},t)}function xa(e){let t=on.getStore();if(!t)return false;let n=t.override??{},r={...n,...e};return (n.extras||e.extras)&&(r.extras={...n.extras??{},...e.extras??{}}),t.override=r,true}var Qn="_historyMeta";function Oe(e){if(!e?.enabled||e.shadow===false||e.meta&&e.shadow===void 0)return null;let t=e.shadow,n=typeof t=="string"&&t.trim().length>0?t.trim():typeof t=="object"&&t!==null&&typeof t.key=="string"&&t.key.trim().length>0?t.key.trim():Qn,r=typeof t=="object"&&t!==null?t.fields:void 0;return {key:n,fields:{userId:r?.userId??"userId",userEmail:r?.userEmail??"userEmail",reason:r?.reason??"reason",comment:r?.comment??"comment",extras:r?.extras??"extras"}}}function ve(e){return Oe(e)?.key??null}function Vn(e){let t=Oe(e);return t?[t.key]:[]}function pe(e,t){if(!t||!e||typeof e!="object"||Array.isArray(e))return e;let n=e;if(!(t in n))return e;let{[t]:r,...o}=n;return o}function Re(e,t){if(!t?.enabled||t.autoInjectMeta===false)return;let n=Oe(t);if(!n)return;let r=ut(),o=t.fallbackActor??{},s=r?.userId!==void 0?r.userId:o.userId??null,a=r?.userEmail!==void 0?r.userEmail:o.userEmail??null,l=r?.reason??null,c=r?.comment??null,u=r?.extras&&Object.keys(r.extras).length>0?r.extras:null,p={},{fields:f}=n;f.userId!==false&&(p[f.userId]=s),f.userEmail!==false&&(p[f.userEmail]=a),f.reason!==false&&(p[f.reason]=l),f.comment!==false&&(p[f.comment]=c),f.extras!==false&&(p[f.extras]=u),e[n.key]=p;}function Ct(e){if(e===null)return "null";if(e===void 0)return "undefined";if(e instanceof Timestamp)return "timestamp";if(e instanceof Date)return "date";if(Array.isArray(e))return "array";let t=typeof e;return t==="string"||t==="number"||t==="boolean"?t:"object"}function At(e,t,n=new WeakMap){if(e===t)return true;if(e===null||t===null||e===void 0||t===void 0)return e===t;if(e instanceof Timestamp&&t instanceof Timestamp)return e.isEqual(t);if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return false;if(n.get(e)===t)return true;n.set(e,t);for(let r=0;r<e.length;r++)if(!At(e[r],t[r],n))return false;return true}if(typeof e=="object"&&typeof t=="object"){if(e instanceof Date||t instanceof Date||e instanceof Timestamp||t instanceof Timestamp)return false;if(n.get(e)===t)return true;n.set(e,t);let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return false;for(let s of r)if(!Object.prototype.hasOwnProperty.call(t,s)||!At(e[s],t[s],n))return false;return true}return false}function sn(e,t,n={}){let r=new Set([...n.exclude??[],...n.metaFields??[],...n.systemKeys??[]]),o=n.include?new Set(n.include):null,s=e??{},a=t??{},l=new Set([...Object.keys(s),...Object.keys(a)]),c={};for(let u of l){if(r.has(u)||o&&!o.has(u))continue;let p=s[u],f=a[u];At(p,f)||(c[u]={oldValue:p===void 0?null:p,newValue:f===void 0?null:f,type:{old:Ct(p),new:Ct(f)}});}return c}var Ra=5;function Sa(e){return e.schemaVersion===2}function uo(e){if(typeof e!="string")return "object";switch(e){case "string":case "number":case "boolean":case "object":case "array":case "timestamp":case "date":case "null":case "undefined":return e;default:return "object"}}function va(e){return {historyDocId:e.historyDocId,historyToObjectId:e.historyToObjectId,historySetAt:e.historySetAt,schemaVersion:2,operation:e.operation,meta:e.meta??{},...e.custom?{custom:e.custom}:{},changes:e.changes??{}}}function Ta(e){let t={};e.historyUserId!==void 0&&(t.userId=e.historyUserId??null),e.historyUserEmail!==void 0&&(t.userEmail=e.historyUserEmail??null);let n=e.extraHistoryDetails??null;n&&(n.reason!==void 0&&(t.reason=n.reason??null),n.comment!==void 0&&(t.comment=n.comment??null));let r={},o=false;if(e.historyDetails&&typeof e.historyDetails=="object")for(let[s,a]of Object.entries(e.historyDetails))r[s]=a,o=true;if(e.extraContentKeys&&typeof e.extraContentKeys=="object")for(let[s,a]of Object.entries(e.extraContentKeys))r[`content.${s}`]=a,o=true;return o&&(t.extras=r),t}function ka(e){let t=e.changes?.oldValue??null,n=e.changes?.newValue??null,r=e.types?.oldValue,o=e.types?.newValue;return {oldValue:t,newValue:n,type:{old:r?uo(r):Ct(t),new:o?uo(o):Ct(n)}}}function Ca(e){let t=ka(e),n=Ta(e);return {historyDocId:e.historyDocId,historyToObjectId:e.historyToObjectId,historySetAt:e.historySetAt,schemaVersion:1,operation:"update",meta:n,changes:{[e.field]:t}}}function Aa(e,t,n){return Math.abs(e.toMillis()-t.toMillis())<=n}function Ea(e,t){return (e.userId??null)===(t.userId??null)}function po(e,t={}){let n=t.groupToleranceMs??Ra,r=[];for(let o of e){if(Sa(o)){r.push(va(o));continue}let a=Ca(o),l=r[r.length-1];l&&l.schemaVersion===1&&Aa(l.historySetAt,a.historySetAt,n)&&Ea(l.meta,a.meta)?Object.assign(l.changes,a.changes):r.push(a);}return r}var Pa=7e5;function Et(e){let t=e.ttlOverride??e.config.ttl,r={schemaVersion:2,historyDocId:randomUUID(),historyToObjectId:e.entityId,historySetAt:Timestamp.now(),operation:e.operation,meta:e.meta,...e.custom?{custom:e.custom}:{},changes:e.changes};t&&(r.expiresAt=Timestamp.fromMillis(Date.now()+t.days*24*60*60*1e3));let o=s=>{try{return Buffer.byteLength(JSON.stringify(s,(a,l)=>l instanceof Timestamp?l.toMillis():l),"utf8")}catch{return 0}};if(o(r.changes)>Pa){let s={};for(let[a,l]of Object.entries(r.changes)){let c=o(l.oldValue),u=o(l.newValue);s[a]={oldValue:c>5e4?"[truncated]":l.oldValue,newValue:u>5e4?"[truncated]":l.newValue,type:l.type};}r.changes=s,r._truncated=true;}return r}async function Ot(e,t,n,r){let o=t;return n.onBeforeWrite&&(o=await n.onBeforeWrite(t,r)),o?(await e.doc(o.historyDocId).set(o),{written:true,entry:o}):{written:false,reason:"dropped-by-onBeforeWrite"}}function an(e,t){let n=e??{},r={},o=Oe(t);if(o){let f=n[o.key];if(f&&typeof f=="object"&&!Array.isArray(f)){let b=f,h=A=>{if(A===false||!(A in b))return;let E=b[A];return E==null?null:String(E)},w=h(o.fields.userId);w!==void 0&&(r.userId=w);let T=h(o.fields.userEmail);T!==void 0&&(r.userEmail=T);let S=h(o.fields.reason);S!==void 0&&(r.reason=S);let I=h(o.fields.comment);if(I!==void 0&&(r.comment=I),o.fields.extras!==false){let A=b[o.fields.extras];A&&typeof A=="object"&&!Array.isArray(A)&&Object.keys(A).length>0&&(r.extras=A);}}return r}let s=t.meta;if(!s)return r;let a=f=>{if(!f)return;let b=n[f];return b===void 0||b===null?null:String(b)},l=a(s.userId);l!==void 0&&(r.userId=l);let c=a(s.userEmail);c!==void 0&&(r.userEmail=c);let u=a(s.reason);u!==void 0&&(r.reason=u);let p=a(s.comment);if(p!==void 0&&(r.comment=p),s.extras&&s.extras.length>0){let f={},b=false;for(let h of s.extras)h in n&&(f[h]=n[h],b=true);b&&(r.extras=f);}return r}function cn(e){let t=[],n=Oe(e);n&&t.push(n.key);let r=e.meta;return r&&(r.userId&&t.push(r.userId),r.userEmail&&t.push(r.userEmail),r.reason&&t.push(r.reason),r.comment&&t.push(r.comment),r.extras&&t.push(...r.extras)),t}var Ia="history",Da=50;function Jn(e,t,n){return e(...n).collection(t)}function fo(e){return String(e[e.length-1]??"")}function yo(e,t,n,r){if(!r?.enabled)return null;let o=r.subcollection??Ia;async function s(...h){let w={},T=h,S=h[h.length-1];S!==null&&typeof S=="object"&&!(S instanceof Timestamp)&&("limit"in S||"cursor"in S||"direction"in S)&&(w=S,T=h.slice(0,-1));let I=Jn(e,o,T),A=w.direction??"desc",E=I.orderBy("historySetAt",A);return w.cursor&&(E=E.startAfter(w.cursor)),w.limit&&w.limit>0&&(E=E.limit(w.limit)),(await E.get()).docs.map(d=>({id:d.id,data:d.data()}))}async function a(...h){let w={},T=h,S=h[h.length-1];S!==null&&typeof S=="object"&&!(S instanceof Timestamp)&&("limit"in S||"cursor"in S||"direction"in S||"fields"in S||"operations"in S)&&(w=S,T=h.slice(0,-1));let I=w.limit??Da,A=Math.max(I,Math.min(I*8,500)),E=await s(...T,{limit:A,cursor:w.cursor,direction:w.direction??"desc"}),x=po(E.map(d=>d.data));if(w.fields&&w.fields.length>0){let d=new Set(w.fields);x=x.filter(y=>Object.keys(y.changes).some(i=>d.has(i)));}if(w.operations&&w.operations.length>0){let d=new Set(w.operations);x=x.filter(y=>d.has(y.operation));}return x.slice(0,I)}async function l(...h){let w=h[h.length-1],T={},S,I;return w!==null&&typeof w=="object"&&!(w instanceof Timestamp)?(T=w,S=h[h.length-2],I=h.slice(0,-2)):(S=w,I=h.slice(0,-1)),a(...I,{...T,fields:[S]})}async function c(...h){let w=h[h.length-1],T={},S,I;return w!==null&&typeof w=="object"&&!(w instanceof Timestamp)?(T=w,S=h[h.length-2],I=h.slice(0,-2)):(S=w,I=h.slice(0,-1)),a(...I,{...T,operations:[S]})}function u(h){let w={title:h.title,display:h.display??true};return h.description!==void 0&&(w.description=h.description),h.key!==void 0&&(w.key=h.key),h.data!==void 0&&(w.data=h.data),w}function p(){let h=ut(),w=r.fallbackActor??{},T=h?.userId!==void 0?h.userId:w.userId??null,S=h?.userEmail!==void 0?h.userEmail:w.userEmail??null;return {userId:T,userEmail:S,...h?.reason!==void 0?{reason:h.reason}:{},...h?.comment!==void 0?{comment:h.comment}:{},...h?.extras&&Object.keys(h.extras).length>0?{extras:h.extras}:{}}}async function f(...h){let w=h[h.length-1],T=h.slice(0,-1),S=fo(T),I=sn(w.before??{},w.after??{},{include:r.include,exclude:r.exclude,metaFields:cn(r),systemKeys:t});if(w.operation==="update"&&Object.keys(I).length===0)return null;let A=an(w.after??w.before??null,r),E=ut(),d={...E?{...E.userId!==void 0?{userId:E.userId}:{},...E.userEmail!==void 0?{userEmail:E.userEmail}:{},...E.reason!==void 0?{reason:E.reason}:{},...E.comment!==void 0?{comment:E.comment}:{},...E.extras&&Object.keys(E.extras).length>0?{extras:E.extras}:{}}:{},...A,...w.meta??{}},y=w.custom?u(w.custom):void 0,i=Et({entityId:S,operation:w.operation,changes:I,meta:d,custom:y,config:r}),g=Jn(e,o,T),m=await Ot(g,i,r,{repoName:n,docId:S,before:w.before??null,after:w.after??null});return !m.written||!m.entry?null:{historyDocId:m.entry.historyDocId,historyToObjectId:m.entry.historyToObjectId,historySetAt:m.entry.historySetAt,schemaVersion:2,operation:m.entry.operation,meta:m.entry.meta,...m.entry.custom?{custom:m.entry.custom}:{},changes:m.entry.changes}}async function b(...h){let w=h[h.length-1],T=h.slice(0,-1),S=fo(T),I=u(w),A={...p(),...w.meta??{}},E=Et({entityId:S,operation:"custom",changes:{},meta:A,custom:I,config:r}),x=Jn(e,o,T),d=await Ot(x,E,r,{repoName:n,docId:S,before:null,after:null});return !d.written||!d.entry?null:{historyDocId:d.entry.historyDocId,historyToObjectId:d.entry.historyToObjectId,historySetAt:d.entry.historySetAt,schemaVersion:2,operation:d.entry.operation,meta:d.entry.meta,...d.entry.custom?{custom:d.entry.custom}:{},changes:d.entry.changes}}return {list:a,raw:s,byField:l,byOperation:c,recordManual:f,recordCustom:b}}function mo(e){return {count:async(t={})=>{let n=e;return n=je(n,t),(await n.count().get()).data().count},sum:async(t,n={})=>{let r=e;r=je(r,n);let o=await r.get(),s=0;return o.forEach(a=>{let l=a.data()[t];typeof l=="number"&&(s+=l);}),s},average:async(t,n={})=>{let r=e;r=je(r,n);let o=await r.get();if(o.empty)return null;let s=0,a=0;return o.forEach(l=>{let c=l.data()[t];typeof c=="number"&&(s+=c,a++);}),a>0?s/a:null}}}function ho(e,t,n,r,o,s,a){let l=()=>new Date;return {create:()=>{let c=e.batch();return {batch:c,set:(...u)=>{let p=u[u.length-1],f=typeof p=="object"&&p!==null&&"merge"in p,b=f?u[u.length-2]:u[u.length-1],h=f?u.slice(0,-2):u.slice(0,-1),w=f?p:{merge:true},T=t(...h),S={...b},I=h[h.length-1];n&&I&&(S[n]=I),r&&(S[r]=T.path),o&&S[o]===void 0&&(S[o]=l()),s&&(S[s]=l()),Re(S,a),c.set(T,S,w);},update:(...u)=>{let p=u.pop(),b=t(...u),h={...p};s&&(h[s]=l()),Re(h,a),c.update(b,h);},delete:(...u)=>{let p=t(...u);c.delete(p);},commit:async()=>{await c.commit();}}}}}var $a=new Set([4,8,10,13,14]);function Yn(e,t){let n=[],r=t.maxAttempts??5;return e.onWriteError(o=>{let s=o?.code;if(o.failedAttempts<r&&s!==void 0&&$a.has(s))return true;let a={ref:o.documentRef,error:o};return n.push(a),t.onError?.(a),false}),t.onSuccess&&e.onWriteResult(o=>t.onSuccess(o)),n}function Xn(e,t){if(e.length>0&&!t.onError){let n=new Error(`bulk operation failed for ${e.length} document(s): `+e.slice(0,5).map(r=>`${r.ref.path} (${r.error.message})`).join("; "));throw n.failures=e,n}return {failures:e}}function go(e,t,n,r){let o=()=>new Date;return {set:async(s,a={})=>{let l=e.bulkWriter(),c=Yn(l,a);try{for(let u of s){if(!u)continue;let{docRef:p,data:f,merge:b=!0}=u,h={...f};t&&h[t]===void 0&&(h[t]=o()),n&&(h[n]=o()),Re(h,r),Promise.resolve(l.set(p,h,{merge:b})).catch(()=>{});}}finally{await l.close();}return Xn(c,a)},update:async(s,a={})=>{let l=e.bulkWriter(),c=Yn(l,a);try{for(let u of s){if(!u)continue;let{docRef:p,data:f}=u,b={...f};n&&(b[n]=o()),Re(b,r),Promise.resolve(l.update(p,b)).catch(()=>{});}}finally{await l.close();}return Xn(c,a)},delete:async(s,a={})=>{let l=e.bulkWriter(),c=Yn(l,a);try{for(let u of s)u&&Promise.resolve(l.delete(u)).catch(()=>{});}finally{await l.close();}return Xn(c,a)}}}var er="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Be(){let e="";for(;e.length<20;){let t=randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let r=t[n];r>=er.length*4||(e+=er.charAt(r%er.length));}}return e}function tr(e){return e.match(/^\{([^}]+)\}$/)?.[1]?.trim()||null}function _e(e,t="docId",n=false){if(typeof e!="string"||!e.trim())return {rawPath:e??"",collectionId:"",collectionPath:"",parentKeys:[],documentPathTemplate:null,hasTemplate:false};let r=e.split("/").map(f=>f.trim()).filter(Boolean);if(r.length===0)return {rawPath:e,collectionId:e,collectionPath:e,parentKeys:[],documentPathTemplate:null,hasTemplate:false};if(r.length===1){let f=r[0];return {rawPath:e,collectionId:f,collectionPath:f,parentKeys:[],documentPathTemplate:n?null:`${f}/{${t}}`,hasTemplate:e.includes("{")&&e.includes("}")}}let o=r.length%2===0,s=o?r.slice(0,-1):r,a=s[s.length-1],l=s.join("/"),u=s.slice(0,-1).map(tr).filter(f=>f!==null),p=o?r.join("/"):`${l}/{${t}}`;return {rawPath:e,collectionId:a,collectionPath:l,parentKeys:u,documentPathTemplate:p,hasTemplate:true}}function bo(e,t,n){let r=t.split("/").map(c=>c.trim()).filter(Boolean),o=0,s=[];for(let c of r){let u=tr(c);if(u!==null){let p=n[o++];if(typeof p!="string"||p.trim()==="")throw new Error(`Missing or empty path parameter "${u}" when resolving document reference for "${t}".`);s.push(p);}else s.push(c);}let a=e;if(typeof a?.collection=="function"&&s.length>=2){let c=a,u=true;for(let p=0;p<s.length;p+=2){let f=s[p],b=s[p+1];if(typeof c?.collection!="function"){u=false;break}let h=c.collection(f);if(typeof h?.doc!="function"){u=false;break}c=h.doc(b);}if(u&&c&&c!==a)return c}let l=s.join("/");if(typeof a?.doc=="function")return a.doc(l);if(typeof a?.collection=="function"&&s.length>=2){let c=s.slice(0,-1).join("/"),u=s[s.length-1],p=a.collection(c);return typeof p?.doc=="function"?p.doc(u):p}throw new Error(`Cannot resolve DocumentReference for "${l}": Firestore instance does not expose .collection() or .doc().`)}function Je(e,t={}){if(!e||typeof e!="object")return;let{pathKey:n,documentKey:r="docId",parentKeys:o,documentPathTemplate:s,isGroup:a}=t,l=n&&typeof e[n]=="string"&&e[n]?e[n]:void 0;if(l&&s){let c=l.split("/").filter(Boolean),u=s.split("/").filter(Boolean);if(c.length===u.length){let p=[];for(let f=0;f<u.length;f++)tr(u[f])!==null&&p.push(c[f]);if(p.length>0)return p}}if(o&&o.length>0){let c=o.length+1;if(l){let p=l.split("/").filter(Boolean),f=[];for(let b=1;b<p.length;b+=2)f.push(p[b]);if(f.length>=c)return f.slice(f.length-c)}let u=r?e[r]:void 0;if(typeof u=="string"&&u.trim()!==""){let p=[],f=true;for(let b of o){let h=e[b];if(typeof h=="string"&&h.trim()!=="")p.push(h);else {f=false;break}}if(f)return [...p,u]}}if(l){let c=l.split("/").filter(Boolean),u=[];for(let p=1;p<c.length;p+=2)u.push(c[p]);if(u.length>0)return !a&&(!o||o.length===0)?[u[u.length-1]]:u}}function wo(e,t,n,r,o,s,a=[],l,c){let u=()=>new Date,p=ve(c);return {create:async(...T)=>{let S=T[T.length-1],I=T.slice(0,-1);if(!S||typeof S!="object")throw new Error("Create data payload must be an object.");let A,E,x=typeof S[n]=="string"&&S[n].trim()!=="",d={...S};if(o&&d[o]===void 0&&(d[o]=u()),s&&(d[s]=u()),Re(d,c),e&&I.length===0)if(x){E=S[n],A=typeof e.doc=="function"?e.doc(E):t(E),d[n]=E;let y=r&&A?.path?{...d,[r]:A.path}:d;await A.set(y),r&&A?.path&&(d[r]=A.path);}else if(typeof e.add=="function"){A=await e.add(d),E=A.id,d[n]=E;let y={[n]:E};r&&A?.path&&(y[r]=A.path,d[r]=A.path),await A.update(y);}else E=Be(),A=typeof e.doc=="function"?e.doc(E):t(E),d[n]=A?.id??E,r&&A?.path&&(d[r]=A.path),await A.set(d);else {let y=[];if(I.length>0)for(let i=0;i<I.length;i++){let g=I[i];if(typeof g!="string"||g.trim()===""){let m=a[i]??`arg[${i}]`;throw new Error(`Missing or empty parent key "${m}" for subcollection create()`)}y.push(g);}else if(a.length>0){let i=[];for(let g of a){let m=S[g];typeof m=="string"&&m.trim()!==""?y.push(m):i.push(g);}if(i.length>0){let g=Je(S,{pathKey:r,documentKey:n,parentKeys:a,documentPathTemplate:l,isGroup:true});if(g&&g.length>=a.length)y=g.slice(0,a.length);else throw new Error(`Missing or empty required parent key(s) in data for subcollection create(): ${i.join(", ")}`)}}else if(r&&typeof S[r]=="string"&&S[r].trim()!==""){let i=Je(S,{pathKey:r,documentKey:n,parentKeys:a,documentPathTemplate:l,isGroup:true});i&&i.length>1&&(y=i.slice(0,-1));}if(y.length===0)throw new Error("Cannot use create() on collection groups without parent keys. Configure a path template (e.g. 'residences/{residenceId}/events') or provide parent keys in data.");E=x?S[n]:Be(),A=t(...y,E),d[n]=A?.id??E,r&&A?.path&&(d[r]=A.path),await A.set(d);}if(typeof A?.get=="function"){let y=await A.get(),i=typeof y?.data=="function"?y.data():d;return pe(le(i??d),p)}return pe(le(d),p)},set:async(...T)=>{let S=T[T.length-1],I=typeof S=="object"&&S!==null&&"merge"in S,A=I?T[T.length-2]:T[T.length-1],E=I?T.slice(0,-2):T.slice(0,-1),x=I?S:{merge:true},d={...A};o&&d[o]===void 0&&(d[o]=u()),s&&(d[s]=u()),Re(d,c);let y=t(...E),i=E[E.length-1];if(n&&i!=null&&(d[n]=i),r&&(d[r]=y.path),await y.set(d,x),typeof y?.get=="function"){let g=await y.get(),m=typeof g?.data=="function"?g.data():d;return pe(le(m??d),p)}return pe(le(d),p)},update:async(...T)=>{let S=T.pop(),I=T,A={...S};s&&(A[s]=u()),Re(A,c);let E=t(...I);await E.update(A);let x=await E.get();return pe(le(x.data()),p)},delete:async(...T)=>{await t(...T).delete();}}}function xo(e,t,n,r,o,s=null){let a={};return a.byList=async(l,c,u="in",p={})=>{if(c.length===0)return [];let f=[],b=so(c,30);for(let h of b){let w=e;w=w.where(l,u,h),p.select&&p.select.length>0&&(w=w.select(...p.select.map(S=>String(S)))),(await w.get()).forEach(S=>{let I=pe(le(S.data()),s);f.push(p.returnDoc?{data:I,doc:S}:I);});}return f},t.forEach(l=>{let c=`by${He(String(l))}`;a[c]=async(...u)=>{let p={},f=u[u.length-1];if(typeof f=="boolean"?(p={returnDoc:f},u=u.slice(0,-1)):typeof f=="object"&&f!==null&&!Array.isArray(f)&&(p=f,u=u.slice(0,-1)),String(l)===o&&(u.length>1||u.length===1&&n!==null)){let A=await r(...u).get();if(!A.exists)return null;let E=pe(le(A.data()),s);return p.returnDoc?{data:E,doc:A}:E}let b=u[0];if(b===void 0)return null;let h=e;h=h.where(String(l),"==",b).limit(1),p.select&&p.select.length>0&&(h=h.select(...p.select.map(I=>String(I))));let w=await h.get();if(w.empty)return null;let T=w.docs[0];if(!T)return null;let S=pe(le(T.data()),s);return p.returnDoc?{data:S,doc:T}:S};}),a}function Ro(e,t,n,r,o=null){let s={},a=c=>pe(le(c),o),l=async(c,u)=>{if(!n||!r||u.length===0)return c;let p=u.map(f=>typeof f=="string"?{key:f}:{key:f.relation,select:f.select});return Promise.all(c.map(async f=>{let b=await Promise.all(p.map(async({key:w,select:T})=>{let S=n[w];if(!S)return [w,void 0];let I=r[S.repo];if(!I)return [w,void 0];let A=S.sourceKey||w,E=f[A];if(E==null)return [w,S.type==="one"?null:[]];let x=T?{select:T}:void 0;try{if(S.type==="one"){let d=`by${He(S.key)}`,y=typeof I.get?.[d]=="function"?await I.get[d](E,x):null;return [w,y]}else {let d=`by${He(S.key)}`,y=typeof I.query?.[d]=="function"?await I.query[d](E,x):[];return [w,y]}}catch(d){return console.error(`[include] Error populating "${w}":`,d),[w,S.type==="one"?null:[]]}})),h={};for(let[w,T]of b)w!==void 0&&(h[w]=T);return {...f,populated:h}}))};return t.forEach(c=>{let u=`by${He(c)}`;s[u]=async(p,f={})=>{let b={...f,where:[[c,"==",p],...f.where??[]]};return (await Qe(e,b)).docs.map(w=>a(w.data()))};}),s.by=async c=>(await Qe(e,c)).docs.map(p=>a(p.data())),s.getAll=async(c={})=>(await Qe(e,c)).docs.map(p=>a(p.data())),s.onSnapshot=(c,u,p)=>je(e,c).onSnapshot(b=>{u(b.docs.map(h=>a(h.data())));},p),s.paginate=async c=>{let{include:u,...p}=c,f=await rn(e,p),b=o?{...f,data:f.data.map(h=>pe(h,o))}:f;if(u&&u.length>0){let h=await l(b.data,u);return {...b,data:h}}return b},s.paginateAll=async function*(c){let{include:u,...p}=c;for await(let f of qn(e,p)){let b=o?{...f,data:f.data.map(h=>pe(h,o))}:f;if(u&&u.length>0){let h=await l(b.data,u);yield {...b,data:h};}else yield b;}},s}function So(e,t){return {populate:async(n,r)=>{if(!e.relationalKeys)return {...n,populated:{}};let o,s={};if(typeof r=="object"&&!Array.isArray(r))if("relation"in r){let c=r;o=[c.relation],c.select&&(s[c.relation]=c.select);}else if("relations"in r){let c=r;o=Array.isArray(c.relations)?c.relations:[c.relations],s=c.select??{};}else o=[];else o=Array.isArray(r)?r:[r];let a=await Promise.all(o.map(async c=>{let u=e.relationalKeys?.[c];if(!u)return console.warn(`[populate] Relation "${c}" not found in config`),[c,void 0];let p=t[u.repo];if(!p)return console.warn(`[populate] Repository "${u.repo}" not found in mapping`),[c,void 0];let f=u.sourceKey||c,b=n[f];if(b==null)return [c,u.type==="one"?null:[]];let h=s[c],w=h?{select:h}:void 0;try{if(u.type==="one"){let T=`by${He(u.key)}`,S=typeof p.get?.[T]=="function"?await p.get[T](b,w):null;return [c,S]}else {let T=`by${He(u.key)}`,S=typeof p.query?.[T]=="function"?await p.query[T](b,w):[];return [c,S]}}catch(T){return console.error(`[populate] Error populating "${c}":`,T),[c,u.type==="one"?null:[]]}})),l={};for(let[c,u]of a)u!==void 0&&(l[c]=u);return {...n,populated:l}}}}var vo=new Set([4,8,10,13,14]),Ma=5,Na=3,Fa=100,ja=500;async function Ba(e){let t=0;for(;;){t++;try{return await e.get()}catch(n){let r=n?.code;if(!(typeof r=="number"&&vo.has(r))||t>=Na)throw n;let s=Fa*2**(t-1);await new Promise(a=>setTimeout(a,s));}}}function To(e,t,n,r,o,s){let a=()=>new Date;return {backfillKeys:async(c={})=>{let{overwriteCreated:u=false,touchUpdated:p=true,overwritePath:f=false,pageSize:b=300,dryRun:h=false,maxAttempts:w=5,flushThreshold:T=ja,onError:S,onSuccess:I}=c,A=Math.max(1,T),E=Array.from(new Set([n,r,o,s].filter(C=>typeof C=="string"&&C.length>0))),x=[],d=0,y=0,i=0,g=0,m=h?null:e.bulkWriter();try{m&&(m.onWriteError(k=>{let R=k?.code;if(R===Ma)return i++,!1;if(k.failedAttempts<w&&R!==void 0&&vo.has(R))return !0;let P={path:k?.documentRef?.path??"(unknown)",error:k};return x.push(P),S?.(P),!1}),m.onWriteResult(k=>{y++,I?.(k.path);}));let C;for(;;){let k=t.orderBy(FieldPath.documentId());E.length>0&&typeof k.select=="function"&&(k=k.select(...E)),C&&(k=k.startAfter(C)),k=k.limit(b);let R=await Ba(k);if(R.empty)break;for(let P of R.docs){d++;let $=P.data(),D={};if(n&&($[n]==null||$[n]==="")&&(D[n]=P.id),r&&(f||$[r]==null||$[r]==="")&&$[r]!==P.ref.path&&(D[r]=P.ref.path),o&&(u||$[o]==null)&&(D[o]=P.createTime?.toDate?.()??a()),p&&s&&$[s]==null&&(D[s]=P.updateTime?.toDate?.()??P.createTime?.toDate?.()??a()),Object.keys(D).length===0){i++;continue}m?(Promise.resolve(m.update(P.ref,D)).catch(()=>{}),g++,g>=A&&typeof m.flush=="function"&&(await m.flush(),g=0)):y++;}if(R.size<b)break;C=R.docs[R.docs.length-1];}}finally{m&&await m.close();}return {scanned:d,written:y,skipped:i,failures:x}}}}function ko(e,t,n,r,o,s,a){let l=()=>new Date,c=ve(a);return {run:async u=>e.runTransaction(async p=>u({get:async(...b)=>{let h=t(...b),w=await p.get(h);return w.exists?pe(le({...w.data(),docId:w.id}),c):null},set:(...b)=>{let h=b[b.length-1],w=typeof h=="object"&&h!==null&&"merge"in h,T=w?b[b.length-2]:b[b.length-1],S=w?b.slice(0,-2):b.slice(0,-1),I=w?h:{merge:true},A=t(...S),E={...T},x=S[S.length-1];n&&x&&(E[n]=x),r&&(E[r]=A.path),o&&E[o]===void 0&&(E[o]=l()),s&&(E[s]=l()),Re(E,a),p.set(A,E,I);},update:(...b)=>{let h=b[b.length-1],w=b.slice(0,-1),T=t(...w),S={...h};s&&(S[s]=l()),Re(S,a),p.update(T,S);},delete:(...b)=>{let h=t(...b);p.delete(h);},raw:p}))}}function Co(e){if(typeof e!="function")return [];let n=e.toString().match(/^\s*(?:function\s*\w*\s*)?\(([^)]*)\)/);if(!n?.[1])return [];let r=n[1].split(",").map(o=>o.trim().replace(/\s*[:=].*$/,"").trim()).filter(Boolean);return r.length<=2?[]:r.slice(1,-1)}function za(e){let t=e?.documentKey??"docId",n=!!e?.isGroup,r=_e(typeof e?.path=="string"?e.path:"",t,n),o=r.parentKeys.length>0?r.parentKeys:n?Co(e?.refCb):[],s=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(l=>typeof l=="string"),a=e?.history&&typeof e.history=="object"?e.history:void 0;return {schema:e?.schema,_systemKeys:s,_pathKey:e?.pathKey??null,_isGroup:n,_createdKey:e?.createdKey??null,_parentKeys:o,_documentPathTemplate:r.documentPathTemplate,_collectionId:typeof e?.path=="string"?r.collectionId:null,relationalKeys:e?.relationalKeys,_historyConfig:a,_historyShadowKey:ve(a),_historyIdentityKeys:Vn(a),_historySubcollection:a?.enabled?a.subcollection??"history":void 0,_collectionPath:typeof e?.path=="string"?r.collectionPath:null}}function dn(e,t){let n=za(e),r,o=()=>{let s=r??(r=t());if(!s){let a=n._collectionPath||"unknown";throw new Error(`[makeLazyRepo] Failed to resolve repository for path "${a}". The repository mapping resolved to undefined. This almost always indicates a circular import where the repository was exported as undefined.`)}return s};return new Proxy(n,{get(s,a){return typeof a=="string"&&a in n?n[a]:o()[a]},has(s,a){return typeof a=="string"&&a in n?true:a in o()}})}function nr(e,t,n={}){let r=t.documentKey,o=_e(t.path,r,!!t.isGroup),s=o.parentKeys.length>0?o.parentKeys:t.isGroup?Co(t.refCb):[],a=t.isGroup?e.collectionGroup(o.collectionId):e.collection(o.collectionPath),l=t.isGroup?null:e.collection(o.collectionPath),c=typeof t.refCb=="function"?(...y)=>t.refCb(e,...y):(...y)=>bo(e,o.documentPathTemplate??`${o.collectionPath}/{${r}}`,y),u=t.history,p=ve(u),f=Vn(u),b=xo(a,t.foreignKeys,l,c,r,p),h=Ro(a,t.queryKeys,t.relationalKeys,n,p),w=mo(a),T=wo(l,c,r,t.pathKey,t.createdKey,t.updatedKey,s,o.documentPathTemplate,u),S=ho(e,c,t.documentKey,t.pathKey,t.createdKey,t.updatedKey,u),I=ko(e,c,t.documentKey,t.pathKey,t.createdKey,t.updatedKey,u),A=go(e,t.createdKey,t.updatedKey,u),E=To(e,a,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),x=So(t,n),d=u?.enabled?yo(c,[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(y=>typeof y=="string"),t.path??"(unknown)",u):null;return {ref:a,documentRef:c,get:b,query:h,aggregate:w,...T,batch:S,transaction:I,bulk:A,system:E,...x,...d?{history:d}:{},_historySubcollection:d?u?.subcollection??"history":void 0,_historyConfig:u,_historyShadowKey:p,_historyIdentityKeys:f,schema:t.schema,relationalKeys:t.relationalKeys,_systemKeys:[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(y=>typeof y=="string"),_pathKey:t.pathKey??null,_isGroup:!!t.isGroup,_parentKeys:s,_documentPathTemplate:o.documentPathTemplate,_collectionId:o.collectionId,_collectionPath:o.collectionPath,_createdKey:t.createdKey??null}}var qa="history";function Ua(e){let t=e&&typeof e.history=="object"&&e.history!==null?e.history:void 0,n=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(s=>typeof s=="string"),r=typeof e?.path=="string"?e.path:null,o=r?_e(r,e?.documentKey??"docId"):null;return {historyConfig:t,systemKeys:n,isGroup:!!e?.isGroup,collectionPath:o?o.collectionPath:null,documentPathTemplate:o&&(!e?.isGroup||o.collectionPath.includes("/"))?o.documentPathTemplate:null}}function La(e){let t=e._historyConfig??(typeof e.history=="object"&&e.history!==null&&"enabled"in e.history?e.history:void 0),n=e._collectionPath??e.ref?.path??null,r=typeof e._documentPathTemplate=="string"?e._documentPathTemplate:null;return {historyConfig:t,systemKeys:e._systemKeys??[],isGroup:!!e._isGroup,collectionPath:n,documentPathTemplate:r&&(!e._isGroup||n&&n.includes("/"))?r:null}}function Ka(e,t){return t?`${t}/{docId}`:(console.warn(`[HistoryTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function Ao(e,t){let{onDocumentWritten:n}=t.deps,r={},o=e?.rawMapping,s=o?Object.entries(o).map(([a,l])=>[a,Ua(l)]):Object.entries(e).map(([a,l])=>[a,La(l)]);for(let[a,l]of s){let c=l.historyConfig;if(!c?.enabled)continue;let u=c.subcollection??qa,p=c.ttl??t.defaults?.ttl,f=t.repos?.[a],b;if(l.isGroup){let E=f?.triggerPath??l.documentPathTemplate;if(!E){console.warn(`[HistoryTriggers] Skipping collection-group repo "${a}". Provide a triggerPath in the history triggers repos override or use a full path template.`);continue}b=E;}else b=f?.triggerPath??l.documentPathTemplate??Ka(a,l.collectionPath);if(!b)continue;let h=l.systemKeys,w=h[0]??"docId",T=cn(c),S={...t.triggerOptions,...c?.triggerOptions,...f?.triggerOptions},I=Object.keys(S).length>0,A=async E=>{try{let x=E.data?.before?.data(),d=E.data?.after?.data(),y;if(!x&&d)y="create";else if(x&&!d)y="delete";else if(x&&d)y="update";else return;let i=String(d?.[w]??x?.[w]??E.params?.docId??E.data?.after?.id??E.data?.before?.id??"");if(!i)return;let g=sn(x??{},d??{},{include:c.include,exclude:c.exclude,metaFields:T,systemKeys:h});if(y==="update"&&Object.keys(g).length===0)return;let m=an(d??x??null,c),C=Et({entityId:i,operation:y,changes:g,meta:m,config:c,ttlOverride:p}),k=E.data?.after?.ref??E.data?.before?.ref;if(!k)return;let R=k.collection(u);await Ot(R,C,c,{repoName:a,docId:i,before:x??null,after:d??null});}catch(x){console.error(`[HistoryTriggers] Failed to record history for "${a}":`,x);}};r[`${a}_onHistory`]=n(I?{document:b,...S}:b,A);}return r}function Za(e){let t=[],n=e.replace(/[.*+?^${}()|[\]\\]/g,r=>r===":"?r:`\\${r}`).replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(r,o)=>(t.push(o),"([^/]+)"));return {pattern:new RegExp(`^${n}$`),paramNames:t}}function Wa(e){let t=e.path??e.url??"/",n=t.indexOf("?");return n===-1?t:t.slice(0,n)}var Me=class{constructor(){this.routes=[];this.middlewares=[];this.notFoundHandler=(t,n)=>{n.status(404).send("Not Found");};this.errorHandler=(t,n,r)=>{console.error("[MiniRouter]",t),r.status(500).send("Internal Server Error");};}use(t){return this.middlewares.push(t),this}get(t,n){return this.addRoute("GET",t,n)}post(t,n){return this.addRoute("POST",t,n)}put(t,n){return this.addRoute("PUT",t,n)}patch(t,n){return this.addRoute("PATCH",t,n)}delete(t,n){return this.addRoute("DELETE",t,n)}onNotFound(t){return this.notFoundHandler=t,this}onError(t){return this.errorHandler=t,this}addRoute(t,n,r){let{pattern:o,paramNames:s}=Za(n);return this.routes.push({method:t.toUpperCase(),pattern:o,paramNames:s,handler:r}),this}async handle(t,n){let r=(t.method??"GET").toUpperCase(),o=Wa(t),s=null,a={};for(let u of this.routes){if(u.method!==r)continue;let p=o.match(u.pattern);if(p){s=u,a={},u.paramNames.forEach((f,b)=>{a[f]=decodeURIComponent(p[b+1]??"");});break}}let l=Object.assign(t,{params:a}),c=s?s.handler:this.notFoundHandler;try{await this.runMiddlewareChain(l,n,c);}catch(u){this.errorHandler(u,t,n);}}async runMiddlewareChain(t,n,r){let o=0,s=async()=>{if(o<this.middlewares.length){let a=this.middlewares[o++];await a(t,n,s);}else await r(t,n);};await s();}};function Pe(e,t,n){let r=t==="/"?"":t.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let a=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",l=n??process.env.FUNCTION_REGION??"us-central1",c=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${a}/${l}/${c}${r}`}let o=process.env.K_SERVICE,s=e?.hostname??e?.headers?.host??"";return o&&typeof s=="string"&&s.includes("cloudfunctions.net")?`/${o.toLowerCase()}${r}`:r}function un(e){if(typeof e=="string")return e;if(Array.isArray(e)){let t=e[0];return typeof t=="string"?t:void 0}}function Pt(e){return !!e&&typeof e=="object"&&e.__authExtension===true}function rr(e,t,n=new WeakSet,r=0){if(e==null)return null;if(typeof e=="object"&&typeof e.toDate=="function")return e.toDate().toISOString();if(e instanceof Date)return e.toISOString();if(Buffer.isBuffer(e))return e.toString("base64");if(e instanceof Uint8Array)return Buffer.from(e).toString("base64");if(typeof e=="object"&&"latitude"in e&&"longitude"in e){let o=e;return t?.stringifyArrays===false?{lat:o.latitude,lng:o.longitude}:JSON.stringify({lat:o.latitude,lng:o.longitude})}if(Array.isArray(e)){let o=e.map(s=>rr(s,t,n,r+1));return t?.stringifyArrays===false?o:JSON.stringify(o)}return typeof e=="object"&&e!==null&&t?.stringifyArrays===false?or(e,new Set,{},n,r+1):e}var Oo=32,Ga=5e3;function Po(e,t,n,r=new WeakSet,o=0){if(o>Oo){n[t||"_truncated"]=JSON.stringify({__truncated:true});return}if(r.has(e)){n[t||"_cycle"]=JSON.stringify({__cycle:true});return}r.add(e);for(let[s,a]of Object.entries(e)){if(Object.keys(n).length>=Ga)break;let l=t?`${t}__${s}`:s;a!=null&&typeof a=="object"&&!Array.isArray(a)&&!(a instanceof Date)&&!Buffer.isBuffer(a)&&!(a instanceof Uint8Array)&&typeof a.toDate!="function"&&!("latitude"in a&&"longitude"in a)?Po(a,l,n,r,o+1):n[l]=rr(a);}r.delete(e);}function or(e,t,n,r=new WeakSet,o=0){if(o>Oo)return {__truncated:true};if(r.has(e))return {__cycle:true};r.add(e);let s={};for(let[a,l]of Object.entries(e)){if(t.has(a))continue;let c=n[a]??a;l!=null&&typeof l=="object"&&!Array.isArray(l)&&!(l instanceof Date)&&!Buffer.isBuffer(l)&&!(l instanceof Uint8Array)&&typeof l.toDate!="function"&&!("latitude"in l&&"longitude"in l)?s[c]=or(l,new Set,{},r,o+1):s[c]=rr(l,{stringifyArrays:false},r,o+1);}return r.delete(e),s}function Io(e){let t={};for(let[n,r]of Object.entries(e)){let o=r;if(typeof o=="string"){let l=o.trim();if(l.startsWith("[")&&l.endsWith("]")||l.startsWith("{")&&l.endsWith("}"))try{o=JSON.parse(l);}catch{}}if(n.startsWith("__")||!n.includes("__")){t[n]=o;continue}let s=n.split("__").filter(Boolean),a=t;for(let l=0;l<s.length-1;l++){let c=s[l];(!a[c]||typeof a[c]!="object"||Array.isArray(a[c]))&&(a[c]={}),a=a[c];}a[s[s.length-1]]=o;}return t}function It(e,t){let n=t?.flat!==false,r;if(n){let o=new Set(t?.exclude),s=t?.columnMap??{},a=e;if(o.size>0){let c=false,u={};for(let[p,f]of Object.entries(e)){if(o.has(p)){c=true;continue}u[p]=f;}c&&(a=u);}let l={};Po(a,"",l),r={};for(let[c,u]of Object.entries(l)){if(o.has(c))continue;let p=c.split("__")[0];if(p!==c&&o.has(p))continue;let f=s[c]??(c.includes("__")?s[c.split("__").pop()]:void 0)??c;r[f]=u;}}else {let o=new Set(t?.exclude),s=t?.columnMap??{};r=or(e,o,s);}return typeof t?.transformDoc=="function"&&(r=t.transformDoc(r)),r}function Y(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Ne(e,t,n){let r=Y(e),o=Y(t);return `<!DOCTYPE html>
2
2
  <html lang="en"><head>
3
3
  <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
4
4
  <title>${r} \u2014 Sync Admin</title>
@@ -28,80 +28,80 @@ import {jsx,jsxs,Fragment}from'hono/jsx/jsx-runtime';import {Timestamp,Filter,Qu
28
28
  <nav><a href="${o}/">\u2190 Dashboard</a></nav>
29
29
  <h1>${r}</h1>
30
30
  ${n}
31
- </body></html>`}function Ne(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function Ye(e,t,n=200){e.status(n).set("Content-Type","application/json").send(JSON.stringify(t,null,2));}function Dt(e){return (e.headers?.accept??"").includes("application/json")}function pt(e){if(e===true||e===1)return true;if(Array.isArray(e))return e.some(pt);if(typeof e=="string"){let t=e.trim().toLowerCase();return t==="true"||t==="1"||t==="yes"||t==="on"}return false}function Ga(e){if(e.query&&pt(e.query.dryRun))return true;let t=e.url??e.originalUrl??"",n=t.indexOf("?");if(n!==-1){let o=new URLSearchParams(t.slice(n+1));if(pt(o.get("dryRun")))return true}let r=e.body;if(r&&typeof r=="object"){if(pt(r.dryRun))return true}else if(typeof r=="string"&&r.trim().length>0){let o=r.trim();if(o.startsWith("{"))try{let s=JSON.parse(o);if(s&&typeof s=="object"&&pt(s.dryRun))return !0}catch{}else {let s=new URLSearchParams(o);if(pt(s.get("dryRun")))return true}}return false}var Ja=new Set([4,8,10,13,14,"4","8","10","13","14","DEADLINE_EXCEEDED","RESOURCE_EXHAUSTED","ABORTED","INTERNAL","UNAVAILABLE"]);function Ya(e){if(!e||typeof e!="object")return false;let t=e.code;return (typeof t=="number"||typeof t=="string")&&Ja.has(t)}async function Xa(e,t=3,n=100){let r=0;for(;;){r++;try{return await e()}catch(o){if(r>=t||!Ya(o))throw o;let s=n*2**(r-1);await new Promise(a=>setTimeout(a,s));}}}function sr(e,t){let n=new Set,r=[];for(let o of e.adapters){let s=`${e.name}:${o.name}`,a=t.get(s);a&&!n.has(a)&&(n.add(a),r.push({adapterName:o.name??"default",queue:a}));}if(r.length===0){let o=t.get(e.name);o&&!n.has(o)&&(n.add(o),r.push({adapterName:e.adapters[0]?.name??"default",queue:o}));}return r}function Po(e,t,n,r,o,s,a,l){let c=(o.basePath??"/").replace(/\/$/,"")||"",u=o.featuresFlag??{},p=un(o.httpsOptions?.region),f=Array.isArray(t)?t:[t],b=e?.rawMapping,h=[],w=Object.keys(s??{}),T=w.length>0,S=Object.keys(b||e),I=T?w.filter(x=>S.includes(x)||x in e):S;for(let x of I){let d=s[x],y=b?dn(b[x],()=>e[x]):e[x],i=!!y._isGroup,g=y._collectionPath,m=typeof g=="string"&&g.includes("/");if(!T&&i&&!d?.triggerPath&&!m)continue;let C=d?.adapters&&d.adapters.length>0?f.filter(R=>d.adapters.includes(R.name)):f,k=typeof y._historyShadowKey=="string"?y._historyShadowKey:ve(y._historyConfig);h.push({name:x,schema:y.schema??null,documentKey:y._systemKeys?.[0]??y.documentKey??"docId",tableName:d?.tableName??x,isGroup:i,repoCfg:d,repo:y,adapters:C,historyShadowKey:k});}let A=new Me,O=new Set;if(o.auth)if(Pt(o.auth)){let x=o.auth;for(let d of x.routes){let y=`${c}${d.path}`;d.method==="GET"?A.get(y,d.handler):A.post(y,d.handler);}A.use(x.middleware);}else if(typeof o.auth=="function")A.use(o.auth);else {let x=o.auth.realm??"Sync Admin",d="Basic "+Buffer.from(`${o.auth.username}:${o.auth.password}`).toString("base64");A.use((y,i,g)=>{if((y.headers?.authorization??"")!==d){i.status(401).set("WWW-Authenticate",`Basic realm="${x}"`).set("Content-Type","text/plain").send("Unauthorized");return}g();});}return A.get(`${c}/`,(x,d)=>{let y=Oe(x,c,p),i=G(y),g=h.map(k=>{let R=G(k.name),P=encodeURIComponent(k.name),_=[];u.healthCheck&&_.push(`<a class="btn" href="${i}/${P}/health">Health</a>`),u.manualSync&&_.push(`<a class="btn btn-primary" href="${i}/${P}/force-sync">Force Sync</a>`);let $=k.adapters.map(M=>`<span class="badge badge-ok">${G(M.name)}</span>`).join(" ");return `<tr>
31
+ </body></html>`}function Fe(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function Ye(e,t,n=200){e.status(n).set("Content-Type","application/json").send(JSON.stringify(t,null,2));}function Dt(e){return (e.headers?.accept??"").includes("application/json")}function pt(e){if(e===true||e===1)return true;if(Array.isArray(e))return e.some(pt);if(typeof e=="string"){let t=e.trim().toLowerCase();return t==="true"||t==="1"||t==="yes"||t==="on"}return false}function Ya(e){if(e.query&&pt(e.query.dryRun))return true;let t=e.url??e.originalUrl??"",n=t.indexOf("?");if(n!==-1){let o=new URLSearchParams(t.slice(n+1));if(pt(o.get("dryRun")))return true}let r=e.body;if(r&&typeof r=="object"){if(pt(r.dryRun))return true}else if(typeof r=="string"&&r.trim().length>0){let o=r.trim();if(o.startsWith("{"))try{let s=JSON.parse(o);if(s&&typeof s=="object"&&pt(s.dryRun))return !0}catch{}else {let s=new URLSearchParams(o);if(pt(s.get("dryRun")))return true}}return false}var Xa=new Set([4,8,10,13,14,"4","8","10","13","14","DEADLINE_EXCEEDED","RESOURCE_EXHAUSTED","ABORTED","INTERNAL","UNAVAILABLE"]);function ei(e){if(!e||typeof e!="object")return false;let t=e.code;return (typeof t=="number"||typeof t=="string")&&Xa.has(t)}async function ti(e,t=3,n=100){let r=0;for(;;){r++;try{return await e()}catch(o){if(r>=t||!ei(o))throw o;let s=n*2**(r-1);await new Promise(a=>setTimeout(a,s));}}}function sr(e,t){let n=new Set,r=[];for(let o of e.adapters){let s=`${e.name}:${o.name}`,a=t.get(s);a&&!n.has(a)&&(n.add(a),r.push({adapterName:o.name??"default",queue:a}));}if(r.length===0){let o=t.get(e.name);o&&!n.has(o)&&(n.add(o),r.push({adapterName:e.adapters[0]?.name??"default",queue:o}));}return r}function Do(e,t,n,r,o,s,a,l){let c=(o.basePath??"/").replace(/\/$/,"")||"",u=o.featuresFlag??{},p=un(o.httpsOptions?.region),f=Array.isArray(t)?t:[t],b=e?.rawMapping,h=[],w=Object.keys(s??{}),T=w.length>0,S=Object.keys(b||e),I=T?w.filter(x=>S.includes(x)||x in e):S;for(let x of I){let d=s[x],y=b?dn(b[x],()=>e[x]):e[x],i=!!y._isGroup,g=y._collectionPath,m=typeof g=="string"&&g.includes("/");if(!T&&i&&!d?.triggerPath&&!m)continue;let C=d?.adapters&&d.adapters.length>0?f.filter(R=>d.adapters.includes(R.name)):f,k=typeof y._historyShadowKey=="string"?y._historyShadowKey:ve(y._historyConfig);h.push({name:x,schema:y.schema??null,documentKey:y._systemKeys?.[0]??y.documentKey??"docId",tableName:d?.tableName??x,isGroup:i,repoCfg:d,repo:y,adapters:C,historyShadowKey:k});}let A=new Me,E=new Set;if(o.auth)if(Pt(o.auth)){let x=o.auth;for(let d of x.routes){let y=`${c}${d.path}`;d.method==="GET"?A.get(y,d.handler):A.post(y,d.handler);}A.use(x.middleware);}else if(typeof o.auth=="function")A.use(o.auth);else {let x=o.auth.realm??"Sync Admin",d="Basic "+Buffer.from(`${o.auth.username}:${o.auth.password}`).toString("base64");A.use((y,i,g)=>{if((y.headers?.authorization??"")!==d){i.status(401).set("WWW-Authenticate",`Basic realm="${x}"`).set("Content-Type","text/plain").send("Unauthorized");return}g();});}return A.get(`${c}/`,(x,d)=>{let y=Pe(x,c,p),i=Y(y),g=h.map(k=>{let R=Y(k.name),P=encodeURIComponent(k.name),$=[];u.healthCheck&&$.push(`<a class="btn" href="${i}/${P}/health">Health</a>`),u.manualSync&&$.push(`<a class="btn btn-primary" href="${i}/${P}/force-sync">Force Sync</a>`);let D=k.adapters.map(N=>`<span class="badge badge-ok">${Y(N.name)}</span>`).join(" ");return `<tr>
32
32
  <td><strong>${R}</strong></td>
33
- <td>${G(k.tableName)}</td>
34
- <td>${$||'<span class="badge badge-warn">none</span>'}</td>
33
+ <td>${Y(k.tableName)}</td>
34
+ <td>${D||'<span class="badge badge-warn">none</span>'}</td>
35
35
  <td>${k.isGroup?'<span class="badge badge-warn">group</span>':'<span class="badge badge-ok">collection</span>'}</td>
36
36
  <td>${k.schema?"\u2713":"\u2717"}</td>
37
- <td>${_.join(" ")}</td>
37
+ <td>${$.join(" ")}</td>
38
38
  </tr>`}).join(`
39
- `),m=u.configCheck?`<p style="margin-top:.5rem"><a class="btn" href="${i}/config-check">\u2699 Config Check</a></p>`:"",C=Fe("Sync Dashboard",y,`<div class="card">
39
+ `),m=u.configCheck?`<p style="margin-top:.5rem"><a class="btn" href="${i}/config-check">\u2699 Config Check</a></p>`:"",C=Ne("Sync Dashboard",y,`<div class="card">
40
40
  <table>
41
41
  <thead><tr><th>Repository</th><th>Target Name</th><th>Adapters</th><th>Type</th><th>Schema</th><th>Actions</th></tr></thead>
42
42
  <tbody>${g}</tbody>
43
43
  </table>
44
44
  ${m}
45
- </div>`);Ne(d,C);}),A.get(`${c}`,(x,d)=>{let y=Oe(x,c,p);d.status(302).set("Location",`${y}/`).send("");}),u.healthCheck&&A.get(`${c}/:repoName/health`,async(x,d)=>{let y=Oe(x,c,p),i=h.find(R=>R.name===x.params.repoName);if(!i){Ne(d,Fe("Not Found",y,`<p>Unknown repo: ${G(x.params.repoName)}</p>`),404);return}let g=[];for(let R of i.adapters)if(typeof R.healthCheck=="function"){let P=await R.healthCheck({targetName:i.tableName,primaryKey:i.documentKey,schema:i.schema??void 0,repoConfig:i.repoCfg});g.push({adapterName:R.name,health:P});}else try{let P=await R.targetExists(i.tableName);g.push({adapterName:R.name,health:{healthy:P,targetName:i.tableName,targetExists:P,error:P?null:`Target "${i.tableName}" does not exist`}});}catch(P){g.push({adapterName:R.name,health:{healthy:false,targetName:i.tableName,targetExists:false,error:P?.message??String(P)}});}let m=g.length>0&&g.every(R=>R.health.healthy);if(Dt(x)){Ye(d,{repo:i.name,targetName:i.tableName,healthy:m,adapters:g.map(R=>({name:R.adapterName,...R.health}))});return}let C=R=>{let{adapterName:P,health:_}=R,$=_.healthy?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Unhealthy</span>',M="",v=_.details;if(v?.expected&&Array.isArray(v.expected)){let E=v.expected,F=new Set(v.actual??[]),H=v.extra??[],D=E.map(j=>{let z=F.has(j.name)?'<span class="badge badge-ok">OK</span>':'<span class="badge badge-err">MISSING</span>';return `<tr><td>${G(j.name)}</td><td>${G(j.type)}</td><td>${j.nullable?"Yes":"No"}</td><td>${j.isPrimaryKey?"\u2713":""}</td><td>${z}</td></tr>`}).join(`
46
- `),N=H.map(j=>`<tr><td>${G(j)}</td><td colspan="3" class="muted">not in schema</td><td><span class="badge badge-warn">EXTRA</span></td></tr>`).join(`
47
- `);M=`<h2>Columns</h2>
45
+ </div>`);Fe(d,C);}),A.get(`${c}`,(x,d)=>{let y=Pe(x,c,p);d.status(302).set("Location",`${y}/`).send("");}),u.healthCheck&&A.get(`${c}/:repoName/health`,async(x,d)=>{let y=Pe(x,c,p),i=h.find(R=>R.name===x.params.repoName);if(!i){Fe(d,Ne("Not Found",y,`<p>Unknown repo: ${Y(x.params.repoName)}</p>`),404);return}let g=[];for(let R of i.adapters)if(typeof R.healthCheck=="function"){let P=await R.healthCheck({targetName:i.tableName,primaryKey:i.documentKey,schema:i.schema??void 0,repoConfig:i.repoCfg});g.push({adapterName:R.name,health:P});}else try{let P=await R.targetExists(i.tableName);g.push({adapterName:R.name,health:{healthy:P,targetName:i.tableName,targetExists:P,error:P?null:`Target "${i.tableName}" does not exist`}});}catch(P){g.push({adapterName:R.name,health:{healthy:false,targetName:i.tableName,targetExists:false,error:P?.message??String(P)}});}let m=g.length>0&&g.every(R=>R.health.healthy);if(Dt(x)){Ye(d,{repo:i.name,targetName:i.tableName,healthy:m,adapters:g.map(R=>({name:R.adapterName,...R.health}))});return}let C=R=>{let{adapterName:P,health:$}=R,D=$.healthy?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Unhealthy</span>',N="",v=$.details;if(v?.expected&&Array.isArray(v.expected)){let O=v.expected,M=new Set(v.actual??[]),H=v.extra??[],_=O.map(F=>{let q=M.has(F.name)?'<span class="badge badge-ok">OK</span>':'<span class="badge badge-err">MISSING</span>';return `<tr><td>${Y(F.name)}</td><td>${Y(F.type)}</td><td>${F.nullable?"Yes":"No"}</td><td>${F.isPrimaryKey?"\u2713":""}</td><td>${q}</td></tr>`}).join(`
46
+ `),j=H.map(F=>`<tr><td>${Y(F)}</td><td colspan="3" class="muted">not in schema</td><td><span class="badge badge-warn">EXTRA</span></td></tr>`).join(`
47
+ `);N=`<h2>Columns</h2>
48
48
  <table>
49
49
  <thead><tr><th>Column</th><th>SQL Type</th><th>Nullable</th><th>PK</th><th>Status</th></tr></thead>
50
- <tbody>${D}${N}</tbody>
51
- </table>`;}else v?.numberOfDocuments!==void 0&&(M=`<h2>Index Stats</h2>
50
+ <tbody>${_}${j}</tbody>
51
+ </table>`;}else v?.numberOfDocuments!==void 0&&(N=`<h2>Index Stats</h2>
52
52
  <table>
53
- <tr><th>Documents Count</th><td>${G(v.numberOfDocuments)}</td></tr>
53
+ <tr><th>Documents Count</th><td>${Y(v.numberOfDocuments)}</td></tr>
54
54
  <tr><th>Indexing in Progress</th><td>${v.isIndexing?'<span class="badge badge-warn">Yes</span>':'<span class="badge badge-ok">No</span>'}</td></tr>
55
- <tr><th>Primary Key</th><td><code>${G(v.primaryKey??"default")}</code></td></tr>
55
+ <tr><th>Primary Key</th><td><code>${Y(v.primaryKey??"default")}</code></td></tr>
56
56
  </table>`);return `<div class="card" style="margin-top:1rem">
57
- <h2>Adapter: <code>${G(P)}</code> ${$}</h2>
58
- <p>Target: <code>${G(_.targetName)}</code> ${_.targetExists?"":'<span class="badge badge-err">NOT FOUND</span>'}</p>
59
- ${_.error?`<p class="badge badge-err" style="margin-top:.5rem">Error: ${G(_.error)}</p>`:""}
60
- ${M}
61
- </div>`},k=Fe(`Health: ${i.name}`,y,`<div class="card">
62
- <p>Overall status for <strong>${G(i.name)}</strong>: ${m?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Issues detected</span>'}</p>
57
+ <h2>Adapter: <code>${Y(P)}</code> ${D}</h2>
58
+ <p>Target: <code>${Y($.targetName)}</code> ${$.targetExists?"":'<span class="badge badge-err">NOT FOUND</span>'}</p>
59
+ ${$.error?`<p class="badge badge-err" style="margin-top:.5rem">Error: ${Y($.error)}</p>`:""}
60
+ ${N}
61
+ </div>`},k=Ne(`Health: ${i.name}`,y,`<div class="card">
62
+ <p>Overall status for <strong>${Y(i.name)}</strong>: ${m?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Issues detected</span>'}</p>
63
63
  </div>
64
64
  ${g.map(C).join(`
65
- `)}`);Ne(d,k);}),u.manualSync&&(A.get(`${c}/:repoName/force-sync`,(x,d)=>{let y=Oe(x,c,p),i=h.find(k=>k.name===x.params.repoName);if(!i){Ne(d,Fe("Not Found",y,`<p>Unknown repo: ${G(x.params.repoName)}</p>`),404);return}let g=G(i.name),m=i.adapters.map(k=>G(k.name)).join(", "),C=Fe(`Force Sync: ${i.name}`,y,`<div class="card">
65
+ `)}`);Fe(d,k);}),u.manualSync&&(A.get(`${c}/:repoName/force-sync`,(x,d)=>{let y=Pe(x,c,p),i=h.find(k=>k.name===x.params.repoName);if(!i){Fe(d,Ne("Not Found",y,`<p>Unknown repo: ${Y(x.params.repoName)}</p>`),404);return}let g=Y(i.name),m=i.adapters.map(k=>Y(k.name)).join(", "),C=Ne(`Force Sync: ${i.name}`,y,`<div class="card">
66
66
  <p>This will read <strong>all</strong> documents from the <code>${g}</code> Firestore collection
67
67
  and upsert them into all active target storage adapters (${m}).</p>
68
68
  <p class="muted" style="margin:.75rem 0">This may take a while for large collections.</p>
69
- <form method="POST" action="${G(y)}/${encodeURIComponent(i.name)}/force-sync">
69
+ <form method="POST" action="${Y(y)}/${encodeURIComponent(i.name)}/force-sync">
70
70
  <label style="display:block;margin-bottom:.75rem">
71
71
  <input type="checkbox" name="dryRun" value="true"> Dry run (scan &amp; validate serialization only, no writes)
72
72
  </label>
73
73
  <button type="submit" class="btn btn-primary">Start Force Sync</button>
74
74
  </form>
75
- </div>`);Ne(d,C);}),A.post(`${c}/:repoName/force-sync`,async(x,d)=>{let y=Oe(x,c,p),i=h.find(m=>m.name===x.params.repoName);if(!i){Ye(d,{error:`Unknown repo: ${x.params.repoName}`},404);return}let g=i.repo.ref;if(!g){Ye(d,{error:`No collection reference for "${i.name}"`},400);return}if(O.has(i.name)){if(Dt(x)){Ye(d,{error:`Force sync is already running for "${i.name}"`,repo:i.name},409);return}Ne(d,Fe(`Force Sync: ${i.name}`,y,`<div class="card">
75
+ </div>`);Fe(d,C);}),A.post(`${c}/:repoName/force-sync`,async(x,d)=>{let y=Pe(x,c,p),i=h.find(m=>m.name===x.params.repoName);if(!i){Ye(d,{error:`Unknown repo: ${x.params.repoName}`},404);return}let g=i.repo.ref;if(!g){Ye(d,{error:`No collection reference for "${i.name}"`},400);return}if(E.has(i.name)){if(Dt(x)){Ye(d,{error:`Force sync is already running for "${i.name}"`,repo:i.name},409);return}Fe(d,Ne(`Force Sync: ${i.name}`,y,`<div class="card">
76
76
  <p class="badge badge-warn">Already Running</p>
77
- <p>A force sync is already in progress for <strong>${G(i.name)}</strong>. Please wait for it to finish before starting another.</p>
78
- </div>`),409);return}O.add(i.name);try{let m=Ga(x),C=0,k=0,R=0,P=[],_=500,M=(typeof g.orderBy=="function"?g.orderBy(FieldPath.documentId()):g).limit(_),v=null,E=new Map,F=()=>{for(let[W,X]of E.entries()){if(typeof W.getStats!="function")continue;let oe=W.getStats();for(let se of oe.recentErrors)se.seq>X.lastErrorSeq&&P.length<5&&P.push(`[${X.adapterName}] flush failed (${se.count} event(s)): ${se.message}`);X.lastErrorSeq=oe.errorSeq;}},H=()=>{if(m)return {synced:0,errors:R};let W=Array.from(E.entries()).filter(([se])=>typeof se.getStats=="function");if(W.length===0)return {synced:k,errors:R};let X=k,oe=0;for(let[se,we]of W){let ne=se.getStats(),be=Math.max(0,ne.flushedEvents-we.flushedEvents),re=Math.max(0,ne.failedEvents-we.failedEvents);be<X&&(X=be),oe+=re;}return {synced:X,errors:R+oe}},D=i.historyShadowKey?Array.from(new Set([...i.repoCfg?.exclude??[],i.historyShadowKey])):i.repoCfg?.exclude;try{if(!m){let W=sr(i,n);for(let{adapterName:X,queue:oe}of W)if(await oe.flush(),typeof oe.getStats=="function"){let se=oe.getStats();E.set(oe,{adapterName:X,flushedEvents:se.flushedEvents,failedEvents:se.failedEvents,lastErrorSeq:se.errorSeq});}else E.set(oe,{adapterName:X,flushedEvents:0,failedEvents:0,lastErrorSeq:0});}for(;;){let W=v?M.startAfter(v):M,X=Date.now(),oe=await Xa(()=>(X=Date.now(),W.get()));if(oe.empty||oe.docs.length===0)break;for(let se of oe.docs){C++;let we=String(se.id??"unknown");try{let ne=se.data();we=String(ne?.[i.documentKey]??se.id);let be=It(ne,{exclude:D,columnMap:i.repoCfg?.columnMap,flat:i.repoCfg?.flat,transformDoc:i.repoCfg?.transformDoc});m||(await r({operation:"UPSERT",repoName:i.name,docId:we,data:be,timestamp:new Date(X).toISOString(),version:X}),k++);}catch(ne){R++;let be=ne?.message??String(ne);console.error(`[ForceSync:${i.name}] doc=${we} failed:`,ne),P.length<5&&P.push(`${we}: ${be}`);}}if(!m){let se=sr(i,n);for(let{adapterName:we,queue:ne}of se)E.has(ne)||E.set(ne,{adapterName:we,flushedEvents:0,failedEvents:0,lastErrorSeq:0}),await ne.flush();F();}if(v=oe.docs[oe.docs.length-1],oe.docs.length<_)break}}catch(W){if(!m){for(let{adapterName:we,queue:ne}of sr(i,n))E.has(ne)||E.set(ne,{adapterName:we,flushedEvents:0,failedEvents:0,lastErrorSeq:0});F();}let{synced:X,errors:oe}=H(),se=W?.message??String(W);if(Dt(x)){Ye(d,{error:se,...m&&{dryRun:!0},scanned:C,synced:X,errors:oe,...P.length>0&&{errorSamples:P}},500);return}Ne(d,Fe(`Force Sync: ${i.name}`,y,`<div class="card">
79
- <p class="badge badge-err">Error: ${G(se)}</p>
80
- <p>Scanned ${C} docs, synced ${X} docs before failure (${oe} errors).</p>
81
- </div>`),500);return}let{synced:N,errors:j}=H();if(Dt(x)){Ye(d,{...m&&{dryRun:!0},repo:i.name,table:i.tableName,scanned:C,synced:N,errors:j,...P.length>0&&{errorSamples:P}});return}let z=P.length>0?`<details style="margin-top:1rem"><summary>First ${P.length} error(s)</summary>
82
- <pre style="white-space:pre-wrap">${P.map(W=>G(W)).join(`
77
+ <p>A force sync is already in progress for <strong>${Y(i.name)}</strong>. Please wait for it to finish before starting another.</p>
78
+ </div>`),409);return}E.add(i.name);try{let m=Ya(x),C=0,k=0,R=0,P=[],$=500,N=(typeof g.orderBy=="function"?g.orderBy(FieldPath.documentId()):g).limit($),v=null,O=new Map,M=()=>{for(let[ie,Z]of O.entries()){if(typeof ie.getStats!="function")continue;let V=ie.getStats();for(let se of V.recentErrors)se.seq>Z.lastErrorSeq&&P.length<5&&P.push(`[${Z.adapterName}] flush failed (${se.count} event(s)): ${se.message}`);Z.lastErrorSeq=V.errorSeq;}},H=()=>{if(m)return {synced:0,errors:R};let ie=Array.from(O.entries()).filter(([se])=>typeof se.getStats=="function");if(ie.length===0)return {synced:k,errors:R};let Z=k,V=0;for(let[se,xe]of ie){let re=se.getStats(),we=Math.max(0,re.flushedEvents-xe.flushedEvents),oe=Math.max(0,re.failedEvents-xe.failedEvents);we<Z&&(Z=we),V+=oe;}return {synced:Z,errors:R+V}},_=i.historyShadowKey?Array.from(new Set([...i.repoCfg?.exclude??[],i.historyShadowKey])):i.repoCfg?.exclude;try{if(!m){let ie=sr(i,n);for(let{adapterName:Z,queue:V}of ie)if(await V.flush(),typeof V.getStats=="function"){let se=V.getStats();O.set(V,{adapterName:Z,flushedEvents:se.flushedEvents,failedEvents:se.failedEvents,lastErrorSeq:se.errorSeq});}else O.set(V,{adapterName:Z,flushedEvents:0,failedEvents:0,lastErrorSeq:0});}for(;;){let ie=v?N.startAfter(v):N,Z=Date.now(),V=await ti(()=>(Z=Date.now(),ie.get()));if(V.empty||V.docs.length===0)break;for(let se of V.docs){C++;let xe=String(se.id??"unknown");try{let re=se.data();xe=String(re?.[i.documentKey]??se.id);let we=It(re,{exclude:_,columnMap:i.repoCfg?.columnMap,flat:i.repoCfg?.flat,transformDoc:i.repoCfg?.transformDoc});m||(await r({operation:"UPSERT",repoName:i.name,docId:xe,data:we,timestamp:new Date(Z).toISOString(),version:Z}),k++);}catch(re){R++;let we=re?.message??String(re);console.error(`[ForceSync:${i.name}] doc=${xe} failed:`,re),P.length<5&&P.push(`${xe}: ${we}`);}}if(!m){let se=sr(i,n);for(let{adapterName:xe,queue:re}of se)O.has(re)||O.set(re,{adapterName:xe,flushedEvents:0,failedEvents:0,lastErrorSeq:0}),await re.flush();M();}if(v=V.docs[V.docs.length-1],V.docs.length<$)break}}catch(ie){if(!m){for(let{adapterName:xe,queue:re}of sr(i,n))O.has(re)||O.set(re,{adapterName:xe,flushedEvents:0,failedEvents:0,lastErrorSeq:0});M();}let{synced:Z,errors:V}=H(),se=ie?.message??String(ie);if(Dt(x)){Ye(d,{error:se,...m&&{dryRun:!0},scanned:C,synced:Z,errors:V,...P.length>0&&{errorSamples:P}},500);return}Fe(d,Ne(`Force Sync: ${i.name}`,y,`<div class="card">
79
+ <p class="badge badge-err">Error: ${Y(se)}</p>
80
+ <p>Scanned ${C} docs, synced ${Z} docs before failure (${V} errors).</p>
81
+ </div>`),500);return}let{synced:j,errors:F}=H();if(Dt(x)){Ye(d,{...m&&{dryRun:!0},repo:i.name,table:i.tableName,scanned:C,synced:j,errors:F,...P.length>0&&{errorSamples:P}});return}let q=P.length>0?`<details style="margin-top:1rem"><summary>First ${P.length} error(s)</summary>
82
+ <pre style="white-space:pre-wrap">${P.map(ie=>Y(ie)).join(`
83
83
 
84
- `)}</pre></details>`:"",te=i.adapters.map(W=>G(W.name)).join(", "),K=m?`<p class="badge ${j>0?"badge-warn":"badge-ok"}">${j>0?"Dry run completed with errors":"Dry run complete"}</p>`:`<p class="badge ${j>0?"badge-warn":"badge-ok"}">${j>0?"Completed with errors":"Complete"}</p>`,$e=m?`<p>Dry run scanned <strong>${C}</strong> documents (0 synced, no writes performed).</p>`:`<p>Scanned <strong>${C}</strong> documents, synced <strong>${N}</strong> documents to targets (${te}).</p>`,Se=Fe(`Force Sync: ${i.name}`,y,`<div class="card">
85
- ${K}
86
- ${$e}
87
- ${j>0?`<p class="badge badge-warn">${j} error(s)</p>`:""}
88
- ${z}
89
- </div>`);Ne(d,Se);}finally{O.delete(i.name);}})),u.configCheck&&A.get(`${c}/config-check`,async(x,d)=>{let y=Oe(x,c,p),i=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCP_PROJECT??"unknown",g="https://console.cloud.google.com",m=l??"firestore-sync",C=[];for(let v of f)if(v.name==="bigquery")try{await v.targetExists("__nonexistent_health_check__"),C.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable"});}catch(E){let F=E?.message??String(E),H=F.toLowerCase(),D=H.includes("disabled")||H.includes("has not been used")||H.includes("accessnotconfigured"),N=H.includes("permission")||F.includes("403")||H.includes("access denied"),j=H.includes("project")&&H.includes("not found"),z=H.includes("not found")||F.includes("404");D?C.push({name:"BigQuery API",category:"bigquery",status:"error",message:"BigQuery API is not enabled",fix:{gcloud:`gcloud services enable bigquery.googleapis.com --project=${i}`,console:`${g}/apis/library/bigquery.googleapis.com?project=${i}`}}):j?C.push({name:"BigQuery Project",category:"bigquery",status:"error",message:F,fix:{hint:"The GCP project does not exist or the credentials don't have access to it.",console:`${g}/home/dashboard`}}):N?C.push({name:"BigQuery API",category:"bigquery",status:"error",message:`Permission denied: ${F}`,fix:{hint:"Grant the service account BigQuery Data Editor + BigQuery Job User roles",console:`${g}/iam-admin/iam?project=${i}`}}):z?C.push({name:"BigQuery Dataset",category:"bigquery",status:"error",message:`Dataset not found: ${F}`,fix:{hint:"Create the dataset first",gcloud:`bq mk --dataset ${i}:YOUR_DATASET_ID`,console:`${g}/bigquery?project=${i}`}}):C.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable (table lookup returned expected error)"});}else if(v.name==="meilisearch"||typeof v.checkConnection=="function")try{let E=typeof v.checkConnection=="function"?await v.checkConnection():{healthy:await v.targetExists("__nonexistent__")};C.push({name:"Meilisearch API",category:"meilisearch",status:E.healthy?"ok":"error",message:E.healthy?`Meilisearch is reachable${E.version?` (v${E.version})`:""}`:`Meilisearch connection error: ${E.error??"unknown"}`,...E.error&&{fix:{hint:"Ensure Meilisearch is running and host/apiKey options are valid."}}});}catch(E){C.push({name:"Meilisearch API",category:"meilisearch",status:"error",message:`Meilisearch error: ${E?.message??String(E)}`});}for(let v of h)for(let E of v.adapters){let F=E.name==="bigquery"?"bigquery":E.name==="meilisearch"?"meilisearch":"storage";try{let H=await E.targetExists(v.tableName);C.push({name:`[${E.name}] Target: ${v.tableName}`,category:F,status:H?"ok":"warn",message:H?`Target \`${v.tableName}\` exists`:`Target \`${v.tableName}\` does not exist yet`,...!H&&{fix:{hint:"Target will be auto-created on first sync if autoMigrate is enabled."}}});}catch(H){C.push({name:`[${E.name}] Target: ${v.tableName}`,category:F,status:"error",message:H?.message??String(H)});}}if(a)for(let v of h){let E=`${m}-${v.name}`;try{let F=a.topic(E);if(typeof F.exists=="function"){let[H]=await F.exists();C.push({name:`Topic: ${E}`,category:"pubsub",status:H?"ok":"error",message:H?`Topic \`${E}\` exists`:`Topic \`${E}\` does not exist`,...!H&&{fix:{gcloud:`gcloud pubsub topics create ${E} --project=${i}`,console:`${g}/cloudpubsub/topic/list?project=${i}`}}});}else C.push({name:`Topic: ${E}`,category:"pubsub",status:"warn",message:"Cannot verify topic existence (PubSub client doesn't expose .exists())",fix:{gcloud:`gcloud pubsub topics create ${E} --project=${i}`,console:`${g}/cloudpubsub/topic/list?project=${i}`}});}catch(F){let H=F?.message??String(F),D=H.includes("disabled")||H.includes("has not been used");if(C.push({name:D?"Pub/Sub API":`Topic: ${E}`,category:"pubsub",status:"error",message:D?"Pub/Sub API is not enabled":H,fix:D?{gcloud:`gcloud services enable pubsub.googleapis.com --project=${i}`,console:`${g}/apis/library/pubsub.googleapis.com?project=${i}`}:{gcloud:`gcloud pubsub topics create ${E} --project=${i}`,console:`${g}/cloudpubsub/topic/list?project=${i}`}}),D)break}}else C.push({name:"Pub/Sub Client",category:"pubsub",status:"warn",message:"PubSub client not available for config check"});if(Dt(x)){let v=C.every(E=>E.status==="ok");Ye(d,{project:i,healthy:v,checks:C});return}let k=v=>v==="ok"?'<span class="badge badge-ok">OK</span>':v==="warn"?'<span class="badge badge-warn">WARN</span>':'<span class="badge badge-err">ERROR</span>',R={bigquery:C.filter(v=>v.category==="bigquery"),meilisearch:C.filter(v=>v.category==="meilisearch"),pubsub:C.filter(v=>v.category==="pubsub"),firestore:C.filter(v=>v.category==="firestore"),storage:C.filter(v=>v.category==="storage")},P=(v,E)=>{if(E.length===0)return "";let F=E.map(H=>{let D="";if(H.fix){let N=[];H.fix.hint&&N.push(`<p class="muted">${G(H.fix.hint)}</p>`),H.fix.gcloud&&N.push(`<pre>$ ${G(H.fix.gcloud)}</pre>`),H.fix.console&&N.push(`<p><a href="${G(H.fix.console)}" target="_blank">Open GCP Console \u2192</a></p>`),D=`<div style="margin-top:.5rem">${N.join("")}</div>`;}return `<tr>
84
+ `)}</pre></details>`:"",U=i.adapters.map(ie=>Y(ie.name)).join(", "),Q=m?`<p class="badge ${F>0?"badge-warn":"badge-ok"}">${F>0?"Dry run completed with errors":"Dry run complete"}</p>`:`<p class="badge ${F>0?"badge-warn":"badge-ok"}">${F>0?"Completed with errors":"Complete"}</p>`,ne=m?`<p>Dry run scanned <strong>${C}</strong> documents (0 synced, no writes performed).</p>`:`<p>Scanned <strong>${C}</strong> documents, synced <strong>${j}</strong> documents to targets (${U}).</p>`,ke=Ne(`Force Sync: ${i.name}`,y,`<div class="card">
85
+ ${Q}
86
+ ${ne}
87
+ ${F>0?`<p class="badge badge-warn">${F} error(s)</p>`:""}
88
+ ${q}
89
+ </div>`);Fe(d,ke);}finally{E.delete(i.name);}})),u.configCheck&&A.get(`${c}/config-check`,async(x,d)=>{let y=Pe(x,c,p),i=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCP_PROJECT??"unknown",g="https://console.cloud.google.com",m=l??"firestore-sync",C=[];for(let v of f)if(v.name==="bigquery")try{await v.targetExists("__nonexistent_health_check__"),C.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable"});}catch(O){let M=O?.message??String(O),H=M.toLowerCase(),_=H.includes("disabled")||H.includes("has not been used")||H.includes("accessnotconfigured"),j=H.includes("permission")||M.includes("403")||H.includes("access denied"),F=H.includes("project")&&H.includes("not found"),q=H.includes("not found")||M.includes("404");_?C.push({name:"BigQuery API",category:"bigquery",status:"error",message:"BigQuery API is not enabled",fix:{gcloud:`gcloud services enable bigquery.googleapis.com --project=${i}`,console:`${g}/apis/library/bigquery.googleapis.com?project=${i}`}}):F?C.push({name:"BigQuery Project",category:"bigquery",status:"error",message:M,fix:{hint:"The GCP project does not exist or the credentials don't have access to it.",console:`${g}/home/dashboard`}}):j?C.push({name:"BigQuery API",category:"bigquery",status:"error",message:`Permission denied: ${M}`,fix:{hint:"Grant the service account BigQuery Data Editor + BigQuery Job User roles",console:`${g}/iam-admin/iam?project=${i}`}}):q?C.push({name:"BigQuery Dataset",category:"bigquery",status:"error",message:`Dataset not found: ${M}`,fix:{hint:"Create the dataset first",gcloud:`bq mk --dataset ${i}:YOUR_DATASET_ID`,console:`${g}/bigquery?project=${i}`}}):C.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable (table lookup returned expected error)"});}else if(v.name==="meilisearch"||typeof v.checkConnection=="function")try{let O=typeof v.checkConnection=="function"?await v.checkConnection():{healthy:await v.targetExists("__nonexistent__")};C.push({name:"Meilisearch API",category:"meilisearch",status:O.healthy?"ok":"error",message:O.healthy?`Meilisearch is reachable${O.version?` (v${O.version})`:""}`:`Meilisearch connection error: ${O.error??"unknown"}`,...O.error&&{fix:{hint:"Ensure Meilisearch is running and host/apiKey options are valid."}}});}catch(O){C.push({name:"Meilisearch API",category:"meilisearch",status:"error",message:`Meilisearch error: ${O?.message??String(O)}`});}for(let v of h)for(let O of v.adapters){let M=O.name==="bigquery"?"bigquery":O.name==="meilisearch"?"meilisearch":"storage";try{let H=await O.targetExists(v.tableName);C.push({name:`[${O.name}] Target: ${v.tableName}`,category:M,status:H?"ok":"warn",message:H?`Target \`${v.tableName}\` exists`:`Target \`${v.tableName}\` does not exist yet`,...!H&&{fix:{hint:"Target will be auto-created on first sync if autoMigrate is enabled."}}});}catch(H){C.push({name:`[${O.name}] Target: ${v.tableName}`,category:M,status:"error",message:H?.message??String(H)});}}if(a)for(let v of h){let O=`${m}-${v.name}`;try{let M=a.topic(O);if(typeof M.exists=="function"){let[H]=await M.exists();C.push({name:`Topic: ${O}`,category:"pubsub",status:H?"ok":"error",message:H?`Topic \`${O}\` exists`:`Topic \`${O}\` does not exist`,...!H&&{fix:{gcloud:`gcloud pubsub topics create ${O} --project=${i}`,console:`${g}/cloudpubsub/topic/list?project=${i}`}}});}else C.push({name:`Topic: ${O}`,category:"pubsub",status:"warn",message:"Cannot verify topic existence (PubSub client doesn't expose .exists())",fix:{gcloud:`gcloud pubsub topics create ${O} --project=${i}`,console:`${g}/cloudpubsub/topic/list?project=${i}`}});}catch(M){let H=M?.message??String(M),_=H.includes("disabled")||H.includes("has not been used");if(C.push({name:_?"Pub/Sub API":`Topic: ${O}`,category:"pubsub",status:"error",message:_?"Pub/Sub API is not enabled":H,fix:_?{gcloud:`gcloud services enable pubsub.googleapis.com --project=${i}`,console:`${g}/apis/library/pubsub.googleapis.com?project=${i}`}:{gcloud:`gcloud pubsub topics create ${O} --project=${i}`,console:`${g}/cloudpubsub/topic/list?project=${i}`}}),_)break}}else C.push({name:"Pub/Sub Client",category:"pubsub",status:"warn",message:"PubSub client not available for config check"});if(Dt(x)){let v=C.every(O=>O.status==="ok");Ye(d,{project:i,healthy:v,checks:C});return}let k=v=>v==="ok"?'<span class="badge badge-ok">OK</span>':v==="warn"?'<span class="badge badge-warn">WARN</span>':'<span class="badge badge-err">ERROR</span>',R={bigquery:C.filter(v=>v.category==="bigquery"),meilisearch:C.filter(v=>v.category==="meilisearch"),pubsub:C.filter(v=>v.category==="pubsub"),firestore:C.filter(v=>v.category==="firestore"),storage:C.filter(v=>v.category==="storage")},P=(v,O)=>{if(O.length===0)return "";let M=O.map(H=>{let _="";if(H.fix){let j=[];H.fix.hint&&j.push(`<p class="muted">${Y(H.fix.hint)}</p>`),H.fix.gcloud&&j.push(`<pre>$ ${Y(H.fix.gcloud)}</pre>`),H.fix.console&&j.push(`<p><a href="${Y(H.fix.console)}" target="_blank">Open GCP Console \u2192</a></p>`),_=`<div style="margin-top:.5rem">${j.join("")}</div>`;}return `<tr>
90
90
  <td>${k(H.status)}</td>
91
- <td><strong>${G(H.name)}</strong><br><span class="muted">${G(H.message)}</span>${D}</td>
91
+ <td><strong>${Y(H.name)}</strong><br><span class="muted">${Y(H.message)}</span>${_}</td>
92
92
  </tr>`}).join(`
93
- `);return `<h2>${G(v)}</h2>
93
+ `);return `<h2>${Y(v)}</h2>
94
94
  <table><thead><tr><th style="width:80px">Status</th><th>Check</th></tr></thead>
95
- <tbody>${F}</tbody></table>`},$=C.every(v=>v.status==="ok")?'<span class="badge badge-ok">All checks passed</span>':'<span class="badge badge-warn">Some issues found</span>',M=Fe("Config Check",y,`<div class="card">
96
- <p>Project: <code>${G(i)}</code> ${$}</p>
95
+ <tbody>${M}</tbody></table>`},D=C.every(v=>v.status==="ok")?'<span class="badge badge-ok">All checks passed</span>':'<span class="badge badge-warn">Some issues found</span>',N=Ne("Config Check",y,`<div class="card">
96
+ <p>Project: <code>${Y(i)}</code> ${D}</p>
97
97
  ${P("BigQuery",R.bigquery)}
98
98
  ${P("Meilisearch",R.meilisearch)}
99
99
  ${P("Pub/Sub",R.pubsub)}
100
100
  ${P("Other Targets",R.storage)}
101
101
  ${P("Firestore",R.firestore)}
102
- </div>`);Ne(d,M);}),async(x,d)=>{await A.handle(x,d);}}var ei="firestore-sync";function ti(e,t){return t?`${t}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function ni(e){let t=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(o=>typeof o=="string"),n=typeof e?.path=="string"?e.path:null,r=n?_e(n,e?.documentKey??"docId"):null;return {isGroup:!!e?.isGroup,documentKey:t[0]??"docId",collectionPath:r?r.collectionPath:null,documentPathTemplate:r&&(!e?.isGroup||r.collectionPath.includes("/"))?r.documentPathTemplate:null,historyShadowKey:ve(e?.history)}}function ri(e){let t=e?._collectionPath??e?.ref?.path??null,n=typeof e?._documentPathTemplate=="string"?e._documentPathTemplate:null;return {isGroup:!!e?._isGroup,documentKey:e?._systemKeys?.[0]??"docId",collectionPath:t,documentPathTemplate:n&&(!e?._isGroup||t&&t.includes("/"))?n:null,historyShadowKey:typeof e?._historyShadowKey=="string"?e._historyShadowKey:ve(e?._historyConfig)}}function Io(e,t){let{onDocumentWritten:n}=t.deps.firestoreTriggers,r=t.deps.pubsub,o=t?.topicPrefix??ei,s={},a=new Map;function l(w){let T=a.get(w);return T||(T=r.topic(w),a.set(w,T),T)}async function c(w,T){await l(w).publishMessage({json:T});}let u=e?.rawMapping,p=u?Object.entries(u).map(([w,T])=>[w,ni(T)]):Object.entries(e).map(([w,T])=>[w,ri(T)]),f=t?.repos,h=Object.keys(f??{}).length>0;for(let[w,T]of p){if(h&&(!f||!(w in f)))continue;let S=f?.[w],I;if(T.isGroup){let g=S?.triggerPath??T.documentPathTemplate;if(!g){console.warn(`[SyncTriggers] Skipping collection-group repo "${w}". Provide a triggerPath in the sync repos config for group collections or use a full path template.`);continue}I=g;}else I=S?.triggerPath??T.documentPathTemplate??ti(w,T.collectionPath);if(!I)continue;let A=T.documentKey,O=T.historyShadowKey?Array.from(new Set([...S?.exclude??[],T.historyShadowKey])):S?.exclude,x=`${o}-${w}`,d={...t?.triggerOptions,...S?.triggerOptions},y=Object.keys(d).length>0,i=async g=>{let m=g.data?.before,C=g.data?.after;if(!m&&!C)return;let k=!!m?.exists,R=!!C?.exists;if(!k&&R){let P=C.data();if(!P)return;let _=String(P[A]??C.id),$=It(P,{exclude:O,columnMap:S?.columnMap,flat:S?.flat,transformDoc:S?.transformDoc}),M={operation:"INSERT",repoName:w,docId:_,data:$,timestamp:new Date().toISOString(),version:Date.now()};await c(x,M);}else if(k&&R){let P=C.data();if(!P)return;let _=String(P[A]??C.id),$=It(P,{exclude:O,columnMap:S?.columnMap,flat:S?.flat,transformDoc:S?.transformDoc}),M={operation:"UPSERT",repoName:w,docId:_,data:$,timestamp:new Date().toISOString(),version:Date.now()};await c(x,M);}else if(k&&!R){let P=m.data(),_=String(P?.[A]??m.id),$={operation:"DELETE",repoName:w,docId:_,data:null,timestamp:new Date().toISOString(),version:Date.now()};await c(x,$);}};s[`${w}_onSync`]=n(y?{document:I,...d}:I,i);}return s}var ke="__sync_version";ft();var si=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function ai(e){let t=e,n=false;for(;;){let r=J(t);if(!si.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(n=true);let o=ye(t);if(!o)break;t=o;}return {inner:t,nullable:n}}var ii={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function Ho(e,t,n,r,o,s,a,l){for(let[c,u]of Object.entries(e)){let p=n?`${n}__${c}`:c;if(o.has(c)||o.has(p))continue;let{inner:f,nullable:b}=ai(u),h=J(f),w=r||b;if(h==="ZodObject"){let A=me(f);Ho(A,t,p,w,o,s,a,l);continue}let T=ii[h]??"json",S=p===a||c===a,I=s[p]??s[c]??p;l.push({name:I,sqlType:t.mapType(T),nullable:S?false:w,isPrimaryKey:S});}}function Nt(e,t,n={}){let{primaryKey:r,exclude:o=[],columnMap:s={}}=n,a=new Set(o),l=me(e),c=[];return Ho(l,t,"",false,a,s,r,c),c.some(u=>u.name===ke)||c.push({name:ke,sqlType:t.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),c}var gn=class gn{constructor(t){this.buffer=[];this.flushing=false;this.lastFlushFailed=false;this.flushPromise=null;this.timer=null;this.flushedEvents=0;this.failedEvents=0;this.flushedBatches=0;this.failedBatches=0;this.errorSeq=0;this.recentErrors=[];this.adapter=t.adapter,this.tableName=t.tableName,this.primaryKey=t.primaryKey,this.batchSize=t.batchSize??100,this.onFlushError=t.onFlushError;let n=t.flushIntervalMs??5e3;n>0&&(this.timer=setInterval(()=>{this.flush().catch(r=>{console.error(`[SyncQueue] Scheduled flush failed for ${this.tableName}:`,r);});},n),typeof this.timer=="object"&&"unref"in this.timer&&this.timer.unref());}get size(){return this.buffer.length}getStats(){return {flushedEvents:this.flushedEvents,failedEvents:this.failedEvents,flushedBatches:this.flushedBatches,failedBatches:this.failedBatches,errorSeq:this.errorSeq,recentErrors:this.recentErrors.map(t=>({...t}))}}enqueue(...t){this.buffer.push(...t),this.buffer.length>=this.batchSize&&!this.flushing&&!this.lastFlushFailed&&this._autoFlush().catch(n=>{console.error(`[SyncQueue] Auto-flush failed for ${this.tableName}:`,n);});}async _autoFlush(){for(;this.flushPromise;)await this.flushPromise;this.buffer.length<this.batchSize||this.lastFlushFailed||(this.flushing=true,this.flushPromise=this._drain(true).finally(()=>{this.flushing=false,this.flushPromise=null;}),await this.flushPromise);}async flush(){for(;this.flushPromise;)await this.flushPromise;this.buffer.length!==0&&(this.flushing=true,this.flushPromise=this._drain(false).finally(()=>{this.flushing=false,this.flushPromise=null;}),await this.flushPromise);}async flushWithReport(){let t=this.getStats();await this.flush();let n=this.getStats();return {flushed:n.flushedEvents-t.flushedEvents,failed:n.failedEvents-t.failedEvents,errors:n.recentErrors.filter(r=>r.seq>t.errorSeq).map(r=>r.message)}}async _drain(t){try{for(;(t?this.buffer.length>=this.batchSize:this.buffer.length>0)&&await this._doFlush(););}finally{this.flushing=false;}}async _doFlush(){let t=this.buffer.splice(0,this.batchSize);if(t.length===0)return false;try{let n=new Map,r=[];for(let s of t)if(s.operation==="DELETE")r.push(s.docId),n.delete(s.docId);else if(s.data){let a=n.get(s.docId);if(!a)n.set(s.docId,s.data);else {let l=Number(a[ke]??0);Number(s.data[ke]??0)>=l&&n.set(s.docId,s.data);}}let o=Array.from(n.values());o.length>0&&(typeof this.adapter.upsert=="function"?await this.adapter.upsert(this.tableName,o,this.primaryKey):typeof this.adapter.upsertRows=="function"&&await this.adapter.upsertRows(this.tableName,o,this.primaryKey)),r.length>0&&(typeof this.adapter.delete=="function"?await this.adapter.delete(this.tableName,this.primaryKey,r):typeof this.adapter.deleteRows=="function"&&await this.adapter.deleteRows(this.tableName,this.primaryKey,r)),this.flushedEvents+=t.length,this.flushedBatches++,this.lastFlushFailed=!1;}catch(n){let r=n instanceof Error?n.message:String(n);if(this.failedEvents+=t.length,this.failedBatches++,this.errorSeq++,this.recentErrors.push({seq:this.errorSeq,message:r,count:t.length,timestamp:Date.now()}),this.recentErrors.length>gn.MAX_RECENT_ERRORS&&this.recentErrors.shift(),this.onFlushError)await this.onFlushError(t,n);else return this.buffer.unshift(...t),this.lastFlushFailed=true,console.error(`[SyncQueue] Flush failed for ${this.tableName}:`,n),false}return true}async shutdown(){this.timer&&(clearInterval(this.timer),this.timer=null),await this.flush();}};gn.MAX_RECENT_ERRORS=50;var hn=gn;var No=new Set;async function pi(e,t,n,r,o,s,a){let l=`${e}:${t.name}`;if(!No.has(l)){if(typeof t.ensureTarget=="function")await t.ensureTarget({targetName:r,primaryKey:o,schema:n,exclude:s,columnMap:a});else if("dialect"in t&&typeof t.createTable=="function"){let c=t,u=Nt(n,c.dialect,{primaryKey:o,exclude:s,columnMap:a});if(!await c.tableExists(r))await c.createTable({tableName:r,columns:u});else {let f=new Set(await c.getTableColumns(r)),b=u.filter(h=>!f.has(h.name));b.length>0&&(await c.addColumns(r,b),await c.onSchemaChange?.(r));}}No.add(l);}}function jo(e,t){let{deps:n,adapter:r,adapters:o,batchSize:s=100,flushIntervalMs:a=5e3,autoMigrate:l=false,topicPrefix:c="firestore-sync",maxDlqAttempts:u=5,workerOptions:p,repos:f={}}=t,h=(o||(Array.isArray(r)?r:r?[r]:[])).map(O=>typeof O=="function"?O():O);function w(O){let x=f[O];if(x?.adapters&&x.adapters.length>0){let d=new Set(x.adapters);return h.filter(y=>d.has(y.name))}return h}let T=new Map;function S(O,x,d){let y=`${O}:${x.name}`,i=T.get(y);if(i)return i;let m=f[O]?.tableName??O,C=`${c}-${O}-${x.name}-dlq`,k=n.pubsub.topic(C),R=false,P=async()=>{if(!R){try{await k.create(),console.info(`[SyncWorker:${x.name}] Created DLQ topic "${C}"`);}catch($){if($?.code!==6)throw $}R=true;}},_=async($,M)=>{console.error(`[SyncWorker:${x.name}] Flush failed for "${O}" (${$.length} events):`,M),await P(),await Promise.all($.map(v=>{let E=(v.attempts??0)+1;if(u>0&&E>u)return console.error(`[SyncWorker:${x.name}] Dropping event for "${O}" after ${E-1} DLQ attempts:`,{docId:v.docId,operation:v.operation}),Promise.resolve();let F={...v,attempts:E,firstFailedAt:v.firstFailedAt??Date.now()};return k.publishMessage({json:F})}));};return i=new hn({adapter:x,tableName:m,primaryKey:d,batchSize:s,flushIntervalMs:a,onFlushError:_}),T.set(y,i),T.has(O)||T.set(O,i),i}async function I(O){let{repoName:x}=O,d=e[x];if(!d){console.warn(`[SyncWorker] Unknown repo "${x}", skipping event`);return}let y=d._systemKeys?.[0]??d.documentKey??"docId",i=f[x],g=i?.columnMap,m=g?.[y]??y;O.data&&(O.data[ke]=O.version??Date.now());let C=w(x);for(let k of C){if(l){let P=d.schema??void 0;if(P){let _=i?.tableName??x;await pi(x,k,P,_,m,i?.exclude,g);}}S(x,k,m).enqueue(O);}}function A(O){let x=async d=>{let y=d.data?.message?.json??d.data?.json;if(!y){console.warn("[SyncWorker] Received empty PubSub message");return}await I(y);let i=w(y.repoName);for(let g of i){let m=`${y.repoName}:${g.name}`,C=T.get(m);C&&await C.flush();}};return p?n.pubsubHandler.onMessagePublished({topic:O,...p},x):n.pubsubHandler.onMessagePublished(O,x)}return {handleMessage:I,createHandler:A,queues:T,async shutdown(){let O=[],x=new Set;for(let d of T.values())x.has(d)||(x.add(d),O.push(d.shutdown()));await Promise.all(O);}}}var fi="firestore-sync";function Bo(e){if(typeof e!="function")return e;let t=e,n;return new Proxy({},{get(r,o){return n||(n=t()),n[o]},has(r,o){return n||(n=t()),o in n}})}function zo(e,t){let{deps:n,adapter:r,adapters:o,topicPrefix:s=fi,batchSize:a,flushIntervalMs:l,autoMigrate:c,admin:u,workerOptions:p,triggerOptions:f,repos:b}=t,h=Bo(n.pubsub),T=(o||(Array.isArray(r)?r:r?[r]:[])).map(k=>Bo(k)),S=Io(e,{deps:{firestoreTriggers:n.firestoreTriggers,pubsub:h},topicPrefix:s,triggerOptions:f,repos:b}),I=jo(e,{deps:{pubsubHandler:n.pubsubHandler,pubsub:h},adapters:T,batchSize:a,flushIntervalMs:l,autoMigrate:c,topicPrefix:s,workerOptions:p,repos:b}),A={},O=b,x=e?.rawMapping,d=Object.keys(O??{}),y=d.length>0,i=Object.keys(x||e),g=y?d.filter(k=>i.includes(k)||k in e):i;for(let k of g){let R=e?.rawMapping,P=R?!!R[k]?.isGroup:!!e[k]?._isGroup,_=R?R[k]?.path:e[k]?._collectionPath,$=typeof _=="string"&&_.includes("/");!y&&P&&!O?.[k]?.triggerPath&&!$||(A[`sync_${k}`]=I.createHandler(`${s}-${k}`));}let m=null;u&&(m=Po(e,T,I.queues,I.handleMessage,u,b??{},h,s),A.adminsync=u.onRequest?u.httpsOptions?u.onRequest(u.httpsOptions,m):u.onRequest(m):m);let C={functions:{...S,...A},adminHandler:m,handleMessage:I.handleMessage,queues:I.queues,shutdown:I.shutdown};for(let k of ["adminHandler","handleMessage","queues","shutdown"])Object.defineProperty(C,k,{enumerable:false});return C}function yi(e){if(e.client)return e.client;if(!e.host)throw new Error("MeilisearchAdapter requires either a `client` instance or a `host` option.");try{let{MeiliSearch:t}=Kr("meilisearch");return new t({host:e.host,apiKey:e.apiKey})}catch(t){throw new Error(`Failed to load the "meilisearch" package. Please install it with:
102
+ </div>`);Fe(d,N);}),async(x,d)=>{await A.handle(x,d);}}var ni="firestore-sync";function ri(e,t){return t?`${t}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function oi(e){let t=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(o=>typeof o=="string"),n=typeof e?.path=="string"?e.path:null,r=n?_e(n,e?.documentKey??"docId"):null;return {isGroup:!!e?.isGroup,documentKey:t[0]??"docId",collectionPath:r?r.collectionPath:null,documentPathTemplate:r&&(!e?.isGroup||r.collectionPath.includes("/"))?r.documentPathTemplate:null,historyShadowKey:ve(e?.history)}}function si(e){let t=e?._collectionPath??e?.ref?.path??null,n=typeof e?._documentPathTemplate=="string"?e._documentPathTemplate:null;return {isGroup:!!e?._isGroup,documentKey:e?._systemKeys?.[0]??"docId",collectionPath:t,documentPathTemplate:n&&(!e?._isGroup||t&&t.includes("/"))?n:null,historyShadowKey:typeof e?._historyShadowKey=="string"?e._historyShadowKey:ve(e?._historyConfig)}}function $o(e,t){let{onDocumentWritten:n}=t.deps.firestoreTriggers,r=t.deps.pubsub,o=t?.topicPrefix??ni,s={},a=new Map;function l(w){let T=a.get(w);return T||(T=r.topic(w),a.set(w,T),T)}async function c(w,T){await l(w).publishMessage({json:T});}let u=e?.rawMapping,p=u?Object.entries(u).map(([w,T])=>[w,oi(T)]):Object.entries(e).map(([w,T])=>[w,si(T)]),f=t?.repos,h=Object.keys(f??{}).length>0;for(let[w,T]of p){if(h&&(!f||!(w in f)))continue;let S=f?.[w],I;if(T.isGroup){let g=S?.triggerPath??T.documentPathTemplate;if(!g){console.warn(`[SyncTriggers] Skipping collection-group repo "${w}". Provide a triggerPath in the sync repos config for group collections or use a full path template.`);continue}I=g;}else I=S?.triggerPath??T.documentPathTemplate??ri(w,T.collectionPath);if(!I)continue;let A=T.documentKey,E=T.historyShadowKey?Array.from(new Set([...S?.exclude??[],T.historyShadowKey])):S?.exclude,x=`${o}-${w}`,d={...t?.triggerOptions,...S?.triggerOptions},y=Object.keys(d).length>0,i=async g=>{let m=g.data?.before,C=g.data?.after;if(!m&&!C)return;let k=!!m?.exists,R=!!C?.exists;if(!k&&R){let P=C.data();if(!P)return;let $=String(P[A]??C.id),D=It(P,{exclude:E,columnMap:S?.columnMap,flat:S?.flat,transformDoc:S?.transformDoc}),N={operation:"INSERT",repoName:w,docId:$,data:D,timestamp:new Date().toISOString(),version:Date.now()};await c(x,N);}else if(k&&R){let P=C.data();if(!P)return;let $=String(P[A]??C.id),D=It(P,{exclude:E,columnMap:S?.columnMap,flat:S?.flat,transformDoc:S?.transformDoc}),N={operation:"UPSERT",repoName:w,docId:$,data:D,timestamp:new Date().toISOString(),version:Date.now()};await c(x,N);}else if(k&&!R){let P=m.data(),$=String(P?.[A]??m.id),D={operation:"DELETE",repoName:w,docId:$,data:null,timestamp:new Date().toISOString(),version:Date.now()};await c(x,D);}};s[`${w}_onSync`]=n(y?{document:I,...d}:I,i);}return s}var Ce="__sync_version";ft();var ii=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function ci(e){let t=e,n=false;for(;;){let r=X(t);if(!ii.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(n=true);let o=me(t);if(!o)break;t=o;}return {inner:t,nullable:n}}var li={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function Mo(e,t,n,r,o,s,a,l){for(let[c,u]of Object.entries(e)){let p=n?`${n}__${c}`:c;if(o.has(c)||o.has(p))continue;let{inner:f,nullable:b}=ci(u),h=X(f),w=r||b;if(h==="ZodObject"){let A=he(f);Mo(A,t,p,w,o,s,a,l);continue}let T=li[h]??"json",S=p===a||c===a,I=s[p]??s[c]??p;l.push({name:I,sqlType:t.mapType(T),nullable:S?false:w,isPrimaryKey:S});}}function Ft(e,t,n={}){let{primaryKey:r,exclude:o=[],columnMap:s={}}=n,a=new Set(o),l=he(e),c=[];return Mo(l,t,"",false,a,s,r,c),c.some(u=>u.name===Ce)||c.push({name:Ce,sqlType:t.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),c}var gn=class gn{constructor(t){this.buffer=[];this.flushing=false;this.lastFlushFailed=false;this.flushPromise=null;this.timer=null;this.flushedEvents=0;this.failedEvents=0;this.flushedBatches=0;this.failedBatches=0;this.errorSeq=0;this.recentErrors=[];this.adapter=t.adapter,this.tableName=t.tableName,this.primaryKey=t.primaryKey,this.batchSize=t.batchSize??100,this.onFlushError=t.onFlushError;let n=t.flushIntervalMs??5e3;n>0&&(this.timer=setInterval(()=>{this.flush().catch(r=>{console.error(`[SyncQueue] Scheduled flush failed for ${this.tableName}:`,r);});},n),typeof this.timer=="object"&&"unref"in this.timer&&this.timer.unref());}get size(){return this.buffer.length}getStats(){return {flushedEvents:this.flushedEvents,failedEvents:this.failedEvents,flushedBatches:this.flushedBatches,failedBatches:this.failedBatches,errorSeq:this.errorSeq,recentErrors:this.recentErrors.map(t=>({...t}))}}enqueue(...t){this.buffer.push(...t),this.buffer.length>=this.batchSize&&!this.flushing&&!this.lastFlushFailed&&this._autoFlush().catch(n=>{console.error(`[SyncQueue] Auto-flush failed for ${this.tableName}:`,n);});}async _autoFlush(){for(;this.flushPromise;)await this.flushPromise;this.buffer.length<this.batchSize||this.lastFlushFailed||(this.flushing=true,this.flushPromise=this._drain(true).finally(()=>{this.flushing=false,this.flushPromise=null;}),await this.flushPromise);}async flush(){for(;this.flushPromise;)await this.flushPromise;this.buffer.length!==0&&(this.flushing=true,this.flushPromise=this._drain(false).finally(()=>{this.flushing=false,this.flushPromise=null;}),await this.flushPromise);}async flushWithReport(){let t=this.getStats();await this.flush();let n=this.getStats();return {flushed:n.flushedEvents-t.flushedEvents,failed:n.failedEvents-t.failedEvents,errors:n.recentErrors.filter(r=>r.seq>t.errorSeq).map(r=>r.message)}}async _drain(t){try{for(;(t?this.buffer.length>=this.batchSize:this.buffer.length>0)&&await this._doFlush(););}finally{this.flushing=false;}}async _doFlush(){let t=this.buffer.splice(0,this.batchSize);if(t.length===0)return false;try{let n=new Map,r=[];for(let s of t)if(s.operation==="DELETE")r.push(s.docId),n.delete(s.docId);else if(s.data){let a=n.get(s.docId);if(!a)n.set(s.docId,s.data);else {let l=Number(a[Ce]??0);Number(s.data[Ce]??0)>=l&&n.set(s.docId,s.data);}}let o=Array.from(n.values());o.length>0&&(typeof this.adapter.upsert=="function"?await this.adapter.upsert(this.tableName,o,this.primaryKey):typeof this.adapter.upsertRows=="function"&&await this.adapter.upsertRows(this.tableName,o,this.primaryKey)),r.length>0&&(typeof this.adapter.delete=="function"?await this.adapter.delete(this.tableName,this.primaryKey,r):typeof this.adapter.deleteRows=="function"&&await this.adapter.deleteRows(this.tableName,this.primaryKey,r)),this.flushedEvents+=t.length,this.flushedBatches++,this.lastFlushFailed=!1;}catch(n){let r=n instanceof Error?n.message:String(n);if(this.failedEvents+=t.length,this.failedBatches++,this.errorSeq++,this.recentErrors.push({seq:this.errorSeq,message:r,count:t.length,timestamp:Date.now()}),this.recentErrors.length>gn.MAX_RECENT_ERRORS&&this.recentErrors.shift(),this.onFlushError)await this.onFlushError(t,n);else return this.buffer.unshift(...t),this.lastFlushFailed=true,console.error(`[SyncQueue] Flush failed for ${this.tableName}:`,n),false}return true}async shutdown(){this.timer&&(clearInterval(this.timer),this.timer=null),await this.flush();}};gn.MAX_RECENT_ERRORS=50;var hn=gn;var Bo=new Set;async function yi(e,t,n,r,o,s,a){let l=`${e}:${t.name}`;if(!Bo.has(l)){if(typeof t.ensureTarget=="function")await t.ensureTarget({targetName:r,primaryKey:o,schema:n,exclude:s,columnMap:a});else if("dialect"in t&&typeof t.createTable=="function"){let c=t,u=Ft(n,c.dialect,{primaryKey:o,exclude:s,columnMap:a});if(!await c.tableExists(r))await c.createTable({tableName:r,columns:u});else {let f=new Set(await c.getTableColumns(r)),b=u.filter(h=>!f.has(h.name));b.length>0&&(await c.addColumns(r,b),await c.onSchemaChange?.(r));}}Bo.add(l);}}function zo(e,t){let{deps:n,adapter:r,adapters:o,batchSize:s=100,flushIntervalMs:a=5e3,autoMigrate:l=false,topicPrefix:c="firestore-sync",maxDlqAttempts:u=5,workerOptions:p,repos:f={}}=t,h=(o||(Array.isArray(r)?r:r?[r]:[])).map(E=>typeof E=="function"?E():E);function w(E){let x=f[E];if(x?.adapters&&x.adapters.length>0){let d=new Set(x.adapters);return h.filter(y=>d.has(y.name))}return h}let T=new Map;function S(E,x,d){let y=`${E}:${x.name}`,i=T.get(y);if(i)return i;let m=f[E]?.tableName??E,C=`${c}-${E}-${x.name}-dlq`,k=n.pubsub.topic(C),R=false,P=async()=>{if(!R){try{await k.create(),console.info(`[SyncWorker:${x.name}] Created DLQ topic "${C}"`);}catch(D){if(D?.code!==6)throw D}R=true;}},$=async(D,N)=>{console.error(`[SyncWorker:${x.name}] Flush failed for "${E}" (${D.length} events):`,N),await P(),await Promise.all(D.map(v=>{let O=(v.attempts??0)+1;if(u>0&&O>u)return console.error(`[SyncWorker:${x.name}] Dropping event for "${E}" after ${O-1} DLQ attempts:`,{docId:v.docId,operation:v.operation}),Promise.resolve();let M={...v,attempts:O,firstFailedAt:v.firstFailedAt??Date.now()};return k.publishMessage({json:M})}));};return i=new hn({adapter:x,tableName:m,primaryKey:d,batchSize:s,flushIntervalMs:a,onFlushError:$}),T.set(y,i),T.has(E)||T.set(E,i),i}async function I(E){let{repoName:x}=E,d=e[x];if(!d){console.warn(`[SyncWorker] Unknown repo "${x}", skipping event`);return}let y=d._systemKeys?.[0]??d.documentKey??"docId",i=f[x],g=i?.columnMap,m=g?.[y]??y;E.data&&(E.data[Ce]=E.version??Date.now());let C=w(x);for(let k of C){if(l){let P=d.schema??void 0;if(P){let $=i?.tableName??x;await yi(x,k,P,$,m,i?.exclude,g);}}S(x,k,m).enqueue(E);}}function A(E){let x=async d=>{let y=d.data?.message?.json??d.data?.json;if(!y){console.warn("[SyncWorker] Received empty PubSub message");return}await I(y);let i=w(y.repoName);for(let g of i){let m=`${y.repoName}:${g.name}`,C=T.get(m);C&&await C.flush();}};return p?n.pubsubHandler.onMessagePublished({topic:E,...p},x):n.pubsubHandler.onMessagePublished(E,x)}return {handleMessage:I,createHandler:A,queues:T,async shutdown(){let E=[],x=new Set;for(let d of T.values())x.has(d)||(x.add(d),E.push(d.shutdown()));await Promise.all(E);}}}var mi="firestore-sync";function qo(e){if(typeof e!="function")return e;let t=e,n;return new Proxy({},{get(r,o){return n||(n=t()),n[o]},has(r,o){return n||(n=t()),o in n}})}function Uo(e,t){let{deps:n,adapter:r,adapters:o,topicPrefix:s=mi,batchSize:a,flushIntervalMs:l,autoMigrate:c,admin:u,workerOptions:p,triggerOptions:f,repos:b}=t,h=qo(n.pubsub),T=(o||(Array.isArray(r)?r:r?[r]:[])).map(k=>qo(k)),S=$o(e,{deps:{firestoreTriggers:n.firestoreTriggers,pubsub:h},topicPrefix:s,triggerOptions:f,repos:b}),I=zo(e,{deps:{pubsubHandler:n.pubsubHandler,pubsub:h},adapters:T,batchSize:a,flushIntervalMs:l,autoMigrate:c,topicPrefix:s,workerOptions:p,repos:b}),A={},E=b,x=e?.rawMapping,d=Object.keys(E??{}),y=d.length>0,i=Object.keys(x||e),g=y?d.filter(k=>i.includes(k)||k in e):i;for(let k of g){let R=e?.rawMapping,P=R?!!R[k]?.isGroup:!!e[k]?._isGroup,$=R?R[k]?.path:e[k]?._collectionPath,D=typeof $=="string"&&$.includes("/");!y&&P&&!E?.[k]?.triggerPath&&!D||(A[`sync_${k}`]=I.createHandler(`${s}-${k}`));}let m=null;u&&(m=Do(e,T,I.queues,I.handleMessage,u,b??{},h,s),A.adminsync=u.onRequest?u.httpsOptions?u.onRequest(u.httpsOptions,m):u.onRequest(m):m);let C={functions:{...S,...A},adminHandler:m,handleMessage:I.handleMessage,queues:I.queues,shutdown:I.shutdown};for(let k of ["adminHandler","handleMessage","queues","shutdown"])Object.defineProperty(C,k,{enumerable:false});return C}function hi(e){if(e.client)return e.client;if(!e.host)throw new Error("MeilisearchAdapter requires either a `client` instance or a `host` option.");try{let{MeiliSearch:t}=Zr("meilisearch");return new t({host:e.host,apiKey:e.apiKey})}catch(t){throw new Error(`Failed to load the "meilisearch" package. Please install it with:
103
103
  bun add meilisearch # or npm install meilisearch
104
- Original error: ${t?.message??String(t)}`)}}function mi(e,t){if(!e||!t)return false;for(let[n,r]of Object.entries(t)){if(r===void 0)continue;let o=e[n];if(Array.isArray(r)){if(!Array.isArray(o)||r.length!==o.length)return false;for(let s=0;s<r.length;s++)if(r[s]!==o[s])return false}else if(typeof r=="object"&&r!==null){if(JSON.stringify(r)!==JSON.stringify(o))return false}else if(r!==o)return false}return true}var bn=class{constructor(t){this.name="meilisearch";this._client=null;this.options=t,t.client&&(this._client=t.client);}get indexesSettings(){return this.options.indexesSettings}get client(){return this._client||(this._client=yi(this.options)),this._client}async targetExists(t){try{return await this.client.getIndex(t),!0}catch(n){if(n?.code==="index_not_found"||n?.cause?.code==="index_not_found"||n?.statusCode===404||n?.status===404||n?.response?.status===404||n?.cause?.status===404||n?.cause?.statusCode===404||n?.cause?.response?.status===404)return false;throw n}}async upsert(t,n,r){if(n.length===0)return;let o=this.options.unflatten!==false,s=n.map(l=>{let c=o?Oo(l):l;return typeof this.options.transformDoc=="function"&&(c=this.options.transformDoc(c)),c});await this.client.index(t).addDocuments(s,{primaryKey:r});}async delete(t,n,r){if(r.length===0)return;await this.client.index(t).deleteDocuments(r);}async ensureTarget(t){let{targetName:n,primaryKey:r}=t;await this.targetExists(n)||await this.client.createIndex(n,{primaryKey:r});let s=this.options.indexesSettings?.[n];if(s){let{retrievableAttributes:a,attributesToRetrieve:l,...c}=s,u={...c,displayedAttributes:c.displayedAttributes??a??l};u.displayedAttributes===void 0&&delete u.displayedAttributes;let p=this.client.index(n);if(typeof p.getSettings=="function")try{let f=await p.getSettings();if(mi(f,u))return}catch{}await p.updateSettings(u);}}async healthCheck(t){let{targetName:n}=t;try{if(!await this.targetExists(n))return {healthy:!1,targetName:n,targetExists:!1,error:`Meilisearch index "${n}" does not exist`};let o=this.client.index(n),s=await o.getStats(),a=typeof o.getRawInfo=="function"?await o.getRawInfo():{};return {healthy:!0,targetName:n,targetExists:!0,error:null,details:{numberOfDocuments:s?.numberOfDocuments??0,isIndexing:s?.isIndexing??!1,fieldDistribution:s?.fieldDistribution??{},primaryKey:a?.primaryKey??t.primaryKey}}}catch(r){return {healthy:false,targetName:n,targetExists:false,error:r?.message??String(r)}}}async checkConnection(){try{let t=!0;if(typeof this.client.isHealthy=="function"){let r=await this.client.isHealthy();t=r?.status==="available"||r===!0;}else if(typeof this.client.health=="function"){let r=await this.client.health();t=r?.status==="available"||r===!0;}let n;return typeof this.client.getVersion=="function"&&(n=(await this.client.getVersion())?.pkgVersion),{healthy:t,version:n}}catch(t){return {healthy:false,error:t?.message??String(t)}}}};ft();ft();function hi(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/^\s/,"").replace(/^./,t=>t.toUpperCase())}function qo(e){let t=e,n=true,r=false,o;for(;;){let s=J(t);if(s==="ZodOptional")n=false,t=ye(t);else if(s==="ZodNullable")n=false,r=true,t=ye(t);else if(s==="ZodDefault")n=false,o=Do(t),t=ye(t);else if(s==="ZodEffects"||s==="ZodPipe"||s==="ZodTransform"){let a=$t(t);if(!a)break;t=a;}else break}return {inner:t,required:n,nullable:r,defaultValue:o}}function Re(e,t=""){if(J(e)==="ZodObject"){let r=me(e);return Object.entries(r).map(([o,s])=>Uo(t?`${t}.${o}`:o,o,s))}return [Uo(t||"value",t||"value",e)]}function Uo(e,t,n){let{inner:r,required:o,nullable:s,defaultValue:a}=qo(n),l=J(r),c=hi(t.split(".").pop()??t);switch(l){case "ZodString":{let u=$o(r),p=u.includes("email"),f=u.includes("url");return {name:e,label:c,type:"text",required:o,nullable:s,defaultValue:a,hint:p?"email":f?"url":void 0}}case "ZodNumber":case "ZodBigInt":return {name:e,label:c,type:"number",required:o,nullable:s,defaultValue:a};case "ZodBoolean":return {name:e,label:c,type:"checkbox",required:o,nullable:s,defaultValue:a};case "ZodDate":case "ZodCoerce":return {name:e,label:c,type:"datetime-local",required:o,nullable:s,defaultValue:a};case "ZodEnum":{let u=Ht(r);return {name:e,label:c,type:"select",required:o,nullable:s,defaultValue:a,options:u}}case "ZodNativeEnum":{let u=_t(r),p=Object.values(u).filter(f=>typeof f=="string");return {name:e,label:c,type:"select",required:o,nullable:s,defaultValue:a,options:p}}case "ZodLiteral":{let u=String(Mt(r)??"");return {name:e,label:c,type:"select",required:o,nullable:s,defaultValue:a,options:[u]}}case "ZodUnion":{let u=Ft(r);if(u.length>0&&u.every(h=>J(h)==="ZodLiteral")){let h=u.map(w=>String(Mt(w)??""));return {name:e,label:c,type:"select",required:o,nullable:s,defaultValue:a,options:h}}if(u.some(h=>J(h)==="ZodDate"))return {name:e,label:c,type:"datetime-local",required:o,nullable:s,defaultValue:a};let b=u.find(h=>{if(J(h)==="ZodObject"){let w=me(h);return "_latitude"in w&&"_longitude"in w||"latitude"in w&&"longitude"in w}return false});return b?{name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,nested:Re(b,e),hint:"GeoPoint"}:{name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON"}}case "ZodObject":{let u=Re(r,e);return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,nested:u,hint:"JSON object"}}case "ZodArray":{let u=pn(r);if(!u)return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"};let{inner:p}=qo(u),f=J(p),b,h,w;switch(f){case "ZodString":b="text";break;case "ZodNumber":case "ZodBigInt":b="number";break;case "ZodBoolean":b="checkbox";break;case "ZodDate":b="datetime-local";break;case "ZodEnum":b="select",h=Ht(p);break;case "ZodNativeEnum":b="select",h=Object.values(_t(p)).filter(T=>typeof T=="string");break;case "ZodObject":b="object",w=Re(p);break;default:return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"}}return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,arrayElementType:b,arrayElementOptions:h,arrayElementFields:w}}default:return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON"}}}function jt(e,t=0){let n=t>0?`ml-${t*4}`:"",r=`field_${e.name.replace(/\./g,"__")}`,o=e.name,s=e.required?" required":"",a=e.defaultValue==="__null__",l=!a&&e.defaultValue!=null?String(e.defaultValue):"",c=e.nullable&&e.type!=="checkbox"?`<span class="flex items-center gap-1 shrink-0">
104
+ Original error: ${t?.message??String(t)}`)}}function gi(e,t){if(!e||!t)return false;for(let[n,r]of Object.entries(t)){if(r===void 0)continue;let o=e[n];if(Array.isArray(r)){if(!Array.isArray(o)||r.length!==o.length)return false;for(let s=0;s<r.length;s++)if(r[s]!==o[s])return false}else if(typeof r=="object"&&r!==null){if(JSON.stringify(r)!==JSON.stringify(o))return false}else if(r!==o)return false}return true}var bn=class{constructor(t){this.name="meilisearch";this._client=null;this.options=t,t.client&&(this._client=t.client);}get indexesSettings(){return this.options.indexesSettings}get client(){return this._client||(this._client=hi(this.options)),this._client}async targetExists(t){try{return await this.client.getIndex(t),!0}catch(n){if(n?.code==="index_not_found"||n?.cause?.code==="index_not_found"||n?.statusCode===404||n?.status===404||n?.response?.status===404||n?.cause?.status===404||n?.cause?.statusCode===404||n?.cause?.response?.status===404)return false;throw n}}async upsert(t,n,r){if(n.length===0)return;let o=this.options.unflatten!==false,s=n.map(l=>{let c=o?Io(l):l;return typeof this.options.transformDoc=="function"&&(c=this.options.transformDoc(c)),c});await this.client.index(t).addDocuments(s,{primaryKey:r});}async delete(t,n,r){if(r.length===0)return;await this.client.index(t).deleteDocuments(r);}async ensureTarget(t){let{targetName:n,primaryKey:r}=t;await this.targetExists(n)||await this.client.createIndex(n,{primaryKey:r});let s=this.options.indexesSettings?.[n];if(s){let{retrievableAttributes:a,attributesToRetrieve:l,...c}=s,u={...c,displayedAttributes:c.displayedAttributes??a??l};u.displayedAttributes===void 0&&delete u.displayedAttributes;let p=this.client.index(n);if(typeof p.getSettings=="function")try{let f=await p.getSettings();if(gi(f,u))return}catch{}await p.updateSettings(u);}}async healthCheck(t){let{targetName:n}=t;try{if(!await this.targetExists(n))return {healthy:!1,targetName:n,targetExists:!1,error:`Meilisearch index "${n}" does not exist`};let o=this.client.index(n),s=await o.getStats(),a=typeof o.getRawInfo=="function"?await o.getRawInfo():{};return {healthy:!0,targetName:n,targetExists:!0,error:null,details:{numberOfDocuments:s?.numberOfDocuments??0,isIndexing:s?.isIndexing??!1,fieldDistribution:s?.fieldDistribution??{},primaryKey:a?.primaryKey??t.primaryKey}}}catch(r){return {healthy:false,targetName:n,targetExists:false,error:r?.message??String(r)}}}async checkConnection(){try{let t=!0;if(typeof this.client.isHealthy=="function"){let r=await this.client.isHealthy();t=r?.status==="available"||r===!0;}else if(typeof this.client.health=="function"){let r=await this.client.health();t=r?.status==="available"||r===!0;}let n;return typeof this.client.getVersion=="function"&&(n=(await this.client.getVersion())?.pkgVersion),{healthy:t,version:n}}catch(t){return {healthy:false,error:t?.message??String(t)}}}};ft();ft();function bi(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/^\s/,"").replace(/^./,t=>t.toUpperCase())}function Lo(e){let t=e,n=true,r=false,o;for(;;){let s=X(t);if(s==="ZodOptional")n=false,t=me(t);else if(s==="ZodNullable")n=false,r=true,t=me(t);else if(s==="ZodDefault")n=false,o=Ho(t),t=me(t);else if(s==="ZodEffects"||s==="ZodPipe"||s==="ZodTransform"){let a=$t(t);if(!a)break;t=a;}else break}return {inner:t,required:n,nullable:r,defaultValue:o}}function Se(e,t=""){if(X(e)==="ZodObject"){let r=he(e);return Object.entries(r).map(([o,s])=>Ko(t?`${t}.${o}`:o,o,s))}return [Ko(t||"value",t||"value",e)]}function Ko(e,t,n){let{inner:r,required:o,nullable:s,defaultValue:a}=Lo(n),l=X(r),c=bi(t.split(".").pop()??t);switch(l){case "ZodString":{let u=_o(r),p=u.includes("email"),f=u.includes("url");return {name:e,label:c,type:"text",required:o,nullable:s,defaultValue:a,hint:p?"email":f?"url":void 0}}case "ZodNumber":case "ZodBigInt":return {name:e,label:c,type:"number",required:o,nullable:s,defaultValue:a};case "ZodBoolean":return {name:e,label:c,type:"checkbox",required:o,nullable:s,defaultValue:a};case "ZodDate":case "ZodCoerce":return {name:e,label:c,type:"datetime-local",required:o,nullable:s,defaultValue:a};case "ZodEnum":{let u=Ht(r);return {name:e,label:c,type:"select",required:o,nullable:s,defaultValue:a,options:u}}case "ZodNativeEnum":{let u=_t(r),p=Object.values(u).filter(f=>typeof f=="string");return {name:e,label:c,type:"select",required:o,nullable:s,defaultValue:a,options:p}}case "ZodLiteral":{let u=String(Mt(r)??"");return {name:e,label:c,type:"select",required:o,nullable:s,defaultValue:a,options:[u]}}case "ZodUnion":{let u=Nt(r);if(u.length>0&&u.every(h=>X(h)==="ZodLiteral")){let h=u.map(w=>String(Mt(w)??""));return {name:e,label:c,type:"select",required:o,nullable:s,defaultValue:a,options:h}}if(u.some(h=>X(h)==="ZodDate"))return {name:e,label:c,type:"datetime-local",required:o,nullable:s,defaultValue:a};let b=u.find(h=>{if(X(h)==="ZodObject"){let w=he(h);return "_latitude"in w&&"_longitude"in w||"latitude"in w&&"longitude"in w}return false});return b?{name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,nested:Se(b,e),hint:"GeoPoint"}:{name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON"}}case "ZodObject":{let u=Se(r,e);return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,nested:u,hint:"JSON object"}}case "ZodArray":{let u=pn(r);if(!u)return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"};let{inner:p}=Lo(u),f=X(p),b,h,w;switch(f){case "ZodString":b="text";break;case "ZodNumber":case "ZodBigInt":b="number";break;case "ZodBoolean":b="checkbox";break;case "ZodDate":b="datetime-local";break;case "ZodEnum":b="select",h=Ht(p);break;case "ZodNativeEnum":b="select",h=Object.values(_t(p)).filter(T=>typeof T=="string");break;case "ZodObject":b="object",w=Se(p);break;default:return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"}}return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,arrayElementType:b,arrayElementOptions:h,arrayElementFields:w}}default:return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON"}}}function jt(e,t=0){let n=t>0?`ml-${t*4}`:"",r=`field_${e.name.replace(/\./g,"__")}`,o=e.name,s=e.required?" required":"",a=e.defaultValue==="__null__",l=!a&&e.defaultValue!=null?String(e.defaultValue):"",c=e.nullable&&e.type!=="checkbox"?`<span class="flex items-center gap-1 shrink-0">
105
105
  <input type="hidden" id="${r}__isnull" name="${o}__isnull" value="${a?"1":""}">
106
106
  <label class="flex items-center gap-1 cursor-pointer select-none text-xs text-base-content/40 hover:text-base-content/70 border border-base-300 rounded px-2 py-1">
107
107
  <input type="checkbox" class="checkbox checkbox-xs" ${a?"checked":""}
@@ -117,7 +117,7 @@ Original error: ${t?.message??String(t)}`)}}function mi(e,t){if(!e||!t)return f
117
117
  <div class="form-control mb-3 ${n}">
118
118
  <label for="${r}" class="label pb-1">
119
119
  <span class="label-text font-medium">
120
- ${U(e.label)}
120
+ ${L(e.label)}
121
121
  <span class="text-base-content/40 text-xs ml-1">(nullable)</span>
122
122
  </span>
123
123
  </label>
@@ -131,41 +131,41 @@ Original error: ${t?.message??String(t)}`)}}function mi(e,t){if(!e||!t)return f
131
131
  <label class="label cursor-pointer justify-start gap-3">
132
132
  <input type="checkbox" id="${r}" name="${o}" value="true"${l==="true"?" checked":""} class="checkbox checkbox-primary checkbox-sm">
133
133
  <span class="label-text font-medium">
134
- ${U(e.label)}${e.required?' <span class="text-error">*</span>':""}
134
+ ${L(e.label)}${e.required?' <span class="text-error">*</span>':""}
135
135
  </span>
136
136
  </label>
137
137
  </div>`;case "select":u=`<select id="${r}" name="${o}"${s}${a?' disabled style="opacity:0.35"':""} class="select select-bordered select-sm w-full">
138
138
  ${e.required&&!e.nullable?"":'<option value="">\u2014 optional \u2014</option>'}
139
- ${(e.options??[]).map(p=>`<option value="${U(p)}"${l===p?" selected":""}>${U(p)}</option>`).join(`
139
+ ${(e.options??[]).map(p=>`<option value="${L(p)}"${l===p?" selected":""}>${L(p)}</option>`).join(`
140
140
  `)}
141
- </select>`;break;case "textarea":if(e.arrayElementType)return gi(e,t);if(e.nested&&e.nested.length>0){let p=e.nested.map(f=>jt(f,t+1)).join(`
141
+ </select>`;break;case "textarea":if(e.arrayElementType)return wi(e,t);if(e.nested&&e.nested.length>0){let p=e.nested.map(f=>jt(f,t+1)).join(`
142
142
  `);return `
143
143
  <fieldset class="fieldset border border-base-300 rounded-box p-3 mb-3 ${n}">
144
144
  <legend class="fieldset-legend text-xs font-semibold text-base-content/60 px-1">
145
- ${U(e.label)}${e.required?' <span class="text-error">*</span>':""}
145
+ ${L(e.label)}${e.required?' <span class="text-error">*</span>':""}
146
146
  </legend>
147
147
  ${p}
148
148
  </fieldset>`}u=`<textarea id="${r}" name="${o}"${s} rows="3"${a?' disabled style="opacity:0.35"':""}
149
149
  data-json
150
150
  class="textarea textarea-bordered textarea-sm w-full font-mono text-xs"
151
- placeholder="${U(e.hint??"JSON")}">${U(l)}</textarea>`;break;default:u=`<input type="${e.type}" id="${r}" name="${o}"${s}${a?' disabled style="opacity:0.35"':""}
152
- value="${U(l)}"
151
+ placeholder="${L(e.hint??"JSON")}">${L(l)}</textarea>`;break;default:u=`<input type="${e.type}" id="${r}" name="${o}"${s}${a?' disabled style="opacity:0.35"':""}
152
+ value="${L(l)}"
153
153
  class="input input-bordered input-sm w-full"${e.hint==="email"?' autocomplete="email"':e.hint==="url"?' autocomplete="url"':""}>`;}return `
154
154
  <div class="form-control mb-3 ${n}">
155
155
  <label for="${r}" class="label pb-1">
156
156
  <span class="label-text font-medium">
157
- ${U(e.label)}${e.required?' <span class="text-error">*</span>':""}
158
- ${e.hint?`<span class="text-base-content/40 text-xs ml-1">(${U(e.hint)})</span>`:""}
157
+ ${L(e.label)}${e.required?' <span class="text-error">*</span>':""}
158
+ ${e.hint?`<span class="text-base-content/40 text-xs ml-1">(${L(e.hint)})</span>`:""}
159
159
  </span>
160
160
  </label>
161
161
  <div class="flex items-center gap-2">
162
162
  <div class="flex-1 min-w-0">${u}</div>
163
163
  ${c}
164
164
  </div>
165
- </div>`}function U(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function gi(e,t){let n=t>0?`ml-${t*4}`:"",r=`field_${e.name.replace(/\./g,"__")}`,o=e.defaultValue==="__null__",s=e.arrayElementType==="object",a=[];if(e.defaultValue!=null&&e.defaultValue!==""&&e.defaultValue!=="__null__")try{a=JSON.parse(String(e.defaultValue));}catch{}Array.isArray(a)||(a=[]);let l=s?a.map(p=>Ko(e,p??{})).join(`
166
- `):a.map(p=>Lo(e,p)).join(`
167
- `),c=s?Ko(e,{}):Lo(e,""),u=e.nullable?`<span class="flex items-center gap-1 mt-2">
168
- <input type="hidden" id="${r}__isnull" name="${U(e.name)}__isnull" value="${o?"1":""}">
165
+ </div>`}function L(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function wi(e,t){let n=t>0?`ml-${t*4}`:"",r=`field_${e.name.replace(/\./g,"__")}`,o=e.defaultValue==="__null__",s=e.arrayElementType==="object",a=[];if(e.defaultValue!=null&&e.defaultValue!==""&&e.defaultValue!=="__null__")try{a=JSON.parse(String(e.defaultValue));}catch{}Array.isArray(a)||(a=[]);let l=s?a.map(p=>Wo(e,p??{})).join(`
166
+ `):a.map(p=>Zo(e,p)).join(`
167
+ `),c=s?Wo(e,{}):Zo(e,""),u=e.nullable?`<span class="flex items-center gap-1 mt-2">
168
+ <input type="hidden" id="${r}__isnull" name="${L(e.name)}__isnull" value="${o?"1":""}">
169
169
  <label class="flex items-center gap-1 cursor-pointer select-none text-xs text-base-content/40 hover:text-base-content/70 border border-base-300 rounded px-2 py-1">
170
170
  <input type="checkbox" class="checkbox checkbox-xs" ${o?"checked":""}
171
171
  onchange="(function(cb){
@@ -179,64 +179,64 @@ Original error: ${t?.message??String(t)}`)}}function mi(e,t){if(!e||!t)return f
179
179
  </label>
180
180
  </span>`:"";return `
181
181
  <fieldset class="fieldset border border-base-300 rounded-box p-3 mb-3 ${n}"
182
- data-frs-array="${U(e.name)}" data-frs-array-type="${U(e.arrayElementType??"text")}">
182
+ data-frs-array="${L(e.name)}" data-frs-array-type="${L(e.arrayElementType??"text")}">
183
183
  <legend class="fieldset-legend text-xs font-semibold text-base-content/60 px-1">
184
- ${U(e.label)}${e.required?' <span class="text-error">*</span>':""}
184
+ ${L(e.label)}${e.required?' <span class="text-error">*</span>':""}
185
185
  </legend>
186
- <input type="hidden" id="${r}" name="${U(e.name)}" value="${U(JSON.stringify(a))}"${o?" disabled":""}>
186
+ <input type="hidden" id="${r}" name="${L(e.name)}" value="${L(JSON.stringify(a))}"${o?" disabled":""}>
187
187
  <div data-frs-array-items${o?' style="opacity:0.35"':""}>
188
188
  ${l}
189
189
  </div>
190
190
  <template data-frs-array-tpl>${c}</template>
191
191
  <button type="button" class="btn btn-xs btn-outline mt-1" data-frs-array-add>+ Add</button>
192
192
  ${u}
193
- </fieldset>`}function Lo(e,t){let n=t!=null?String(t):"",r;switch(e.arrayElementType){case "select":r=`<select data-frs-val class="select select-bordered select-sm flex-1">
193
+ </fieldset>`}function Zo(e,t){let n=t!=null?String(t):"",r;switch(e.arrayElementType){case "select":r=`<select data-frs-val class="select select-bordered select-sm flex-1">
194
194
  <option value="">\u2014</option>
195
- ${(e.arrayElementOptions??[]).map(o=>`<option value="${U(o)}"${n===o?" selected":""}>${U(o)}</option>`).join("")}
195
+ ${(e.arrayElementOptions??[]).map(o=>`<option value="${L(o)}"${n===o?" selected":""}>${L(o)}</option>`).join("")}
196
196
  </select>`;break;case "checkbox":r=`<label class="flex items-center gap-2 flex-1 cursor-pointer">
197
197
  <input type="checkbox" data-frs-val class="checkbox checkbox-sm checkbox-primary"${n==="true"?" checked":""}>
198
198
  <span class="text-sm">true</span>
199
- </label>`;break;case "number":r=`<input type="number" data-frs-val value="${U(n)}" class="input input-bordered input-sm flex-1">`;break;case "datetime-local":r=`<input type="datetime-local" data-frs-val value="${U(n)}" class="input input-bordered input-sm flex-1">`;break;default:r=`<input type="text" data-frs-val value="${U(n)}" class="input input-bordered input-sm flex-1">`;}return `<div class="flex items-center gap-2 mb-2" data-frs-array-item>
199
+ </label>`;break;case "number":r=`<input type="number" data-frs-val value="${L(n)}" class="input input-bordered input-sm flex-1">`;break;case "datetime-local":r=`<input type="datetime-local" data-frs-val value="${L(n)}" class="input input-bordered input-sm flex-1">`;break;default:r=`<input type="text" data-frs-val value="${L(n)}" class="input input-bordered input-sm flex-1">`;}return `<div class="flex items-center gap-2 mb-2" data-frs-array-item>
200
200
  ${r}
201
201
  <button type="button" class="btn btn-xs btn-ghost text-error" data-frs-array-rm>&times;</button>
202
- </div>`}function Ko(e,t){return `<div class="border border-base-200 rounded p-3 mb-2" data-frs-array-item>
202
+ </div>`}function Wo(e,t){return `<div class="border border-base-200 rounded p-3 mb-2" data-frs-array-item>
203
203
  <div class="flex justify-end mb-1">
204
204
  <button type="button" class="btn btn-xs btn-ghost text-error" data-frs-array-rm>&times;</button>
205
205
  </div>
206
206
  ${(e.arrayElementFields??[]).map(o=>{let s=t[o.name],a=s==null?"":typeof s=="object"?JSON.stringify(s):String(s);switch(o.type){case "checkbox":return `<div class="form-control mb-2">
207
207
  <label class="label cursor-pointer justify-start gap-3">
208
- <input type="checkbox" data-frs-key="${U(o.name)}" class="checkbox checkbox-sm checkbox-primary"${a==="true"?" checked":""}>
209
- <span class="label-text text-sm">${U(o.label)}</span>
208
+ <input type="checkbox" data-frs-key="${L(o.name)}" class="checkbox checkbox-sm checkbox-primary"${a==="true"?" checked":""}>
209
+ <span class="label-text text-sm">${L(o.label)}</span>
210
210
  </label>
211
211
  </div>`;case "select":return `<div class="form-control mb-2">
212
- <label class="label pb-1"><span class="label-text text-sm">${U(o.label)}</span></label>
213
- <select data-frs-key="${U(o.name)}" class="select select-bordered select-sm w-full">
212
+ <label class="label pb-1"><span class="label-text text-sm">${L(o.label)}</span></label>
213
+ <select data-frs-key="${L(o.name)}" class="select select-bordered select-sm w-full">
214
214
  ${o.required?"":'<option value="">\u2014</option>'}
215
- ${(o.options??[]).map(l=>`<option value="${U(l)}"${a===l?" selected":""}>${U(l)}</option>`).join("")}
215
+ ${(o.options??[]).map(l=>`<option value="${L(l)}"${a===l?" selected":""}>${L(l)}</option>`).join("")}
216
216
  </select>
217
217
  </div>`;case "number":return `<div class="form-control mb-2">
218
- <label class="label pb-1"><span class="label-text text-sm">${U(o.label)}</span></label>
219
- <input type="number" data-frs-key="${U(o.name)}" value="${U(a)}" class="input input-bordered input-sm w-full">
218
+ <label class="label pb-1"><span class="label-text text-sm">${L(o.label)}</span></label>
219
+ <input type="number" data-frs-key="${L(o.name)}" value="${L(a)}" class="input input-bordered input-sm w-full">
220
220
  </div>`;case "datetime-local":return `<div class="form-control mb-2">
221
- <label class="label pb-1"><span class="label-text text-sm">${U(o.label)}</span></label>
222
- <input type="datetime-local" data-frs-key="${U(o.name)}" value="${U(a)}" class="input input-bordered input-sm w-full">
221
+ <label class="label pb-1"><span class="label-text text-sm">${L(o.label)}</span></label>
222
+ <input type="datetime-local" data-frs-key="${L(o.name)}" value="${L(a)}" class="input input-bordered input-sm w-full">
223
223
  </div>`;case "textarea":return `<div class="form-control mb-2">
224
- <label class="label pb-1"><span class="label-text text-sm">${U(o.label)}</span></label>
225
- <textarea data-frs-key="${U(o.name)}" rows="2" class="textarea textarea-bordered textarea-sm w-full font-mono text-xs" placeholder="JSON">${U(a)}</textarea>
224
+ <label class="label pb-1"><span class="label-text text-sm">${L(o.label)}</span></label>
225
+ <textarea data-frs-key="${L(o.name)}" rows="2" class="textarea textarea-bordered textarea-sm w-full font-mono text-xs" placeholder="JSON">${L(a)}</textarea>
226
226
  </div>`;default:return `<div class="form-control mb-2">
227
- <label class="label pb-1"><span class="label-text text-sm">${U(o.label)}</span></label>
228
- <input type="text" data-frs-key="${U(o.name)}" value="${U(a)}" class="input input-bordered input-sm w-full">
227
+ <label class="label pb-1"><span class="label-text text-sm">${L(o.label)}</span></label>
228
+ <input type="text" data-frs-key="${L(o.name)}" value="${L(a)}" class="input input-bordered input-sm w-full">
229
229
  </div>`}}).join(`
230
230
  `)}
231
231
  </div>`}function ze(e,t,n,r="Save"){let o=e.map(s=>jt(s)).join(`
232
232
  `);return `
233
- <form action="${U(t)}" method="${n}" novalidate data-frs-form>
233
+ <form action="${L(t)}" method="${n}" novalidate data-frs-form>
234
234
  ${o}
235
235
  <div class="flex gap-2 mt-4 pt-4 border-t border-base-200">
236
- <button type="submit" class="btn btn-primary btn-sm">${U(r)}</button>
236
+ <button type="submit" class="btn btn-primary btn-sm">${L(r)}</button>
237
237
  <button type="button" class="btn btn-ghost btn-sm" onclick="history.back()">Cancel</button>
238
238
  </div>
239
- </form>`}var bi=new Set(["<","<=",">",">=","!="]),wi=new Set(["array-contains","array-contains-any"]);function ir(e){return e==="desc"?"DESCENDING":"ASCENDING"}function xi(e){return _e(e).collectionId||e}function Ri(e,t,n,r,o){let s=[],a=new Set;for(let c of r)if(c.op==="=="||c.op==="in"||c.op==="not-in"){if(a.has(c.field))continue;a.add(c.field),s.push({fieldPath:c.field,order:"ASCENDING"});}for(let c of r)if(wi.has(c.op)){if(a.has(c.field))continue;a.add(c.field),s.push({fieldPath:c.field,arrayConfig:"CONTAINS"});}for(let c of r)if(bi.has(c.op)){if(a.has(c.field))continue;a.add(c.field);let u=o?.field===c.field?ir(o.dir):"ASCENDING";s.push({fieldPath:c.field,order:u});}if(o&&!a.has(o.field)&&s.push({fieldPath:o.field,order:ir(o.dir)}),s.length===1&&n)return Ti(e,t,s[0]);let l=o&&s.some(c=>c.fieldPath===o.field)?ir(o.dir):"ASCENDING";return s.push({fieldPath:"__name__",order:l}),Si(e,t,n,s)}function Si(e,t,n,r,o="(default)"){let s=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,a=[...dr(1,s),...wn(2,n?2:1)];for(let u of r)a.push(...Zo(3,Wo(u)));let l=o==="(default)"?"-default-":o,c=encodeURIComponent(Qo(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${l}/indexes?create_composite=${c}`}function vi(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function cr(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function lr(e,t){return e<<3|t}function dr(e,t){let n=Array.from(new TextEncoder().encode(t));return [lr(e,2),...cr(n.length),...n]}function wn(e,t){return [lr(e,0),...cr(t)]}function Zo(e,t){return [lr(e,2),...cr(t.length),...t]}function Wo(e){let t=[...dr(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...wn(3,1)):t.push(...wn(2,e.order==="DESCENDING"?2:1)),t}function Qo(e){let t=String.fromCharCode(...e),n;if(typeof Buffer<"u")n=Buffer.from(e).toString("base64");else if(typeof btoa<"u")n=btoa(t);else throw new Error("No base64 encoder available");return n.replace(/=+$/,"")}function Ti(e,t,n,r="(default)"){let o=`projects/${e}/databases/${r}/collectionGroups/${t}/fields/${n.fieldPath}`,s=[...dr(1,o),...wn(2,2),...Zo(3,Wo(n))],a=r==="(default)"?"-default-":r,l=encodeURIComponent(Qo(s));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${l}`}function ki(e){let t=e,n=[t?.firestore?.projectId,t?.firestore?.app?.options?.projectId,t?.firestore?._settings?.projectId,t?.firestore?.databaseId?.projectId,t?._firestore?.projectId];for(let o of n)if(typeof o=="string"&&o.length>0)return o;return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.FIREBASE_PROJECT_ID||void 0}function Xe(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Bt(e,t){let n=e??{},r=Xe(e),o;if(r&&(o=n.message?vi(n.message):void 0,!o)){let s=ki(t.ref);if(s){let a=xi(t.path);o=Ri(s,a,t.isGroup,t.filters,t.sort);}}return {type:r?"index":"error",message:r?"This query requires a composite index that does not exist yet.":n.message??"Query failed",indexUrl:o}}xn();var Go=`// \u2500\u2500 Shared helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
239
+ </form>`}var xi=new Set(["<","<=",">",">=","!="]),Ri=new Set(["array-contains","array-contains-any"]);function ir(e){return e==="desc"?"DESCENDING":"ASCENDING"}function Si(e){return _e(e).collectionId||e}function vi(e,t,n,r,o){let s=[],a=new Set;for(let c of r)if(c.op==="=="||c.op==="in"||c.op==="not-in"){if(a.has(c.field))continue;a.add(c.field),s.push({fieldPath:c.field,order:"ASCENDING"});}for(let c of r)if(Ri.has(c.op)){if(a.has(c.field))continue;a.add(c.field),s.push({fieldPath:c.field,arrayConfig:"CONTAINS"});}for(let c of r)if(xi.has(c.op)){if(a.has(c.field))continue;a.add(c.field);let u=o?.field===c.field?ir(o.dir):"ASCENDING";s.push({fieldPath:c.field,order:u});}if(o&&!a.has(o.field)&&s.push({fieldPath:o.field,order:ir(o.dir)}),s.length===1&&n)return Ci(e,t,s[0]);let l=o&&s.some(c=>c.fieldPath===o.field)?ir(o.dir):"ASCENDING";return s.push({fieldPath:"__name__",order:l}),Ti(e,t,n,s)}function Ti(e,t,n,r,o="(default)"){let s=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,a=[...dr(1,s),...wn(2,n?2:1)];for(let u of r)a.push(...Qo(3,Vo(u)));let l=o==="(default)"?"-default-":o,c=encodeURIComponent(Go(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${l}/indexes?create_composite=${c}`}function ki(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function cr(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function lr(e,t){return e<<3|t}function dr(e,t){let n=Array.from(new TextEncoder().encode(t));return [lr(e,2),...cr(n.length),...n]}function wn(e,t){return [lr(e,0),...cr(t)]}function Qo(e,t){return [lr(e,2),...cr(t.length),...t]}function Vo(e){let t=[...dr(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...wn(3,1)):t.push(...wn(2,e.order==="DESCENDING"?2:1)),t}function Go(e){let t=String.fromCharCode(...e),n;if(typeof Buffer<"u")n=Buffer.from(e).toString("base64");else if(typeof btoa<"u")n=btoa(t);else throw new Error("No base64 encoder available");return n.replace(/=+$/,"")}function Ci(e,t,n,r="(default)"){let o=`projects/${e}/databases/${r}/collectionGroups/${t}/fields/${n.fieldPath}`,s=[...dr(1,o),...wn(2,2),...Qo(3,Vo(n))],a=r==="(default)"?"-default-":r,l=encodeURIComponent(Go(s));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${l}`}function Ai(e){let t=e,n=[t?.firestore?.projectId,t?.firestore?.app?.options?.projectId,t?.firestore?._settings?.projectId,t?.firestore?.databaseId?.projectId,t?._firestore?.projectId];for(let o of n)if(typeof o=="string"&&o.length>0)return o;return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.FIREBASE_PROJECT_ID||void 0}function Xe(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Bt(e,t){let n=e??{},r=Xe(e),o;if(r&&(o=n.message?ki(n.message):void 0,!o)){let s=Ai(t.ref);if(s){let a=Si(t.path);o=vi(s,a,t.isGroup,t.filters,t.sort);}}return {type:r?"index":"error",message:r?"This query requires a composite index that does not exist yet.":n.message??"Query failed",indexUrl:o}}xn();var Yo=`// \u2500\u2500 Shared helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
240
240
  function frsGetBasePath() {
241
241
  var root = document.querySelector("[data-frs-panel-root]");
242
242
  var bp = root && root.getAttribute("data-frs-base-path");
@@ -1158,7 +1158,7 @@ function initColumnReorder(table) {
1158
1158
  });
1159
1159
  });
1160
1160
  }
1161
- `;function zt(){return jsx("script",{dangerouslySetInnerHTML:{__html:Go}})}mr();function qe(e){return "<!DOCTYPE html>"+renderToString(e)}var _i=["corporate","silk","dark"],Mi=()=>jsxs("div",{class:"dropdown dropdown-end","data-frs-theme-switcher":true,children:[jsxs("button",{type:"button",tabIndex:0,class:"btn btn-sm btn-ghost text-neutral-content gap-1.5","aria-label":"Switch theme",children:[jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",class:"size-4",children:[jsx("circle",{cx:"12",cy:"12",r:"4"}),jsx("path",{d:"M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"})]}),jsx("span",{class:"text-xs hidden sm:inline","data-frs-theme-current":true,children:"Theme"})]}),jsx("ul",{tabIndex:0,class:"dropdown-content menu menu-sm bg-base-100 text-base-content rounded-box z-50 mt-2 w-40 p-1 shadow-lg border border-base-300",children:_i.map(e=>jsx("li",{children:jsxs("button",{type:"button","data-frs-theme":e,class:"capitalize justify-between",children:[jsx("span",{children:e}),jsx("span",{class:"hidden text-primary","data-frs-theme-check":e,children:"\u2713"})]})},e))})]}),Ue=({opts:e,children:t})=>{let{title:n,breadcrumb:r,flash:o,basePath:s="/"}=e;return jsxs("html",{lang:"en","data-theme":"corporate",children:[jsxs("head",{children:[jsx("meta",{charset:"UTF-8"}),jsx("meta",{name:"viewport",content:"width=device-width, initial-scale=1"}),jsxs("title",{children:[n," \u2014 FRS Admin"]}),jsx("script",{dangerouslySetInnerHTML:{__html:"(function(){try{var t=localStorage.getItem('frs-admin-theme');if(t){document.documentElement.setAttribute('data-theme',t);}}catch(_){}})();"}}),jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/themes.css",rel:"stylesheet",type:"text/css"}),jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/daisyui.css",rel:"stylesheet",type:"text/css"}),jsx("script",{src:"https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"})]}),jsxs("body",{class:"bg-base-200/50 min-h-screen flex flex-col",children:[jsxs("div",{class:"navbar bg-neutral text-neutral-content shadow-sm sticky top-0 z-50 px-6",children:[jsx("div",{class:"flex-1",children:jsx("a",{href:s,class:"font-bold text-lg tracking-tight hover:opacity-80 transition-opacity",children:"FRS Admin"})}),jsx("div",{class:"flex-none",children:jsx(Mi,{})})]}),jsxs("main",{class:"px-6 py-8 w-full flex-1",children:[r&&r.length>0&&jsx("div",{class:"text-sm breadcrumbs mb-4",children:jsx("ul",{children:r.map((a,l)=>a.href?jsx("li",{children:jsx("a",{href:a.href,children:a.label})},l):jsx("li",{class:"text-base-content/60",children:a.label},l))})}),jsx("h1",{class:"text-2xl font-bold mb-6",children:n}),o&&jsxs("div",{role:"alert",class:`alert ${o.type==="success"?"alert-success":o.type==="warning"?"alert-warning":"alert-error"} mb-6`,children:[jsx("span",{class:"flex-1",children:o.message}),o.action&&jsx("a",{href:o.action.href,...o.action.external?{target:"_blank",rel:"noopener noreferrer"}:{},class:"btn btn-sm btn-outline",children:o.action.label})]}),t]}),jsx(yr,{basePath:s}),jsx(zt,{})]})]})};function hr(e,t){return qe(jsx(Ue,{opts:t,children:jsx("div",{dangerouslySetInnerHTML:{__html:e}})}))}function gr(e,t){return qe(jsx(Ue,{opts:{title:"Repositories",basePath:t},children:e.length===0?jsxs("div",{class:"text-center py-20 text-base-content/50",children:[jsx("p",{class:"text-lg font-medium mb-1",children:"No repositories configured"}),jsx("p",{class:"text-sm",children:"Add a repository to your FRS config to get started."})]}):jsx("div",{class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:e.map(n=>jsx("a",{href:`${t}/${n.name}`,class:"card bg-base-100 border border-base-300 hover:shadow-md no-underline transition-shadow",children:jsxs("div",{class:"card-body p-5",children:[jsx("h2",{class:"card-title text-sm font-semibold",children:n.name}),jsx("p",{class:"text-xs text-base-content/50 font-mono",children:n.path})]})},n.name))})}))}var es=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],Fi=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"<",label:"<"},{value:"<=",label:"\u2264"},{value:">",label:">"},{value:">=",label:"\u2265"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],Ni=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function ji(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return Fi;case "ZodBoolean":return es;case "ZodArray":return Ni;default:return es}}var Le="__null__";function Bi(e){return `(function(cb){var i=document.getElementById('${e}');if(!i)return;if(cb.checked){i.dataset._prev=i.value;if(i.tagName==='SELECT'){var o=i.querySelector('option[value="${Le}"]');if(!o){o=document.createElement('option');o.value='${Le}';o.textContent='\u2205 null';o.dataset._auto='1';i.appendChild(o);}o.selected=true;}else{if(i.type==='number'||i.type==='datetime-local'){i.dataset._type=i.type;i.type='text';}i.value='${Le}';i.readOnly=true;}i.style.opacity='0.55';}else{i.style.opacity='';if(i.tagName==='SELECT'){var o2=i.querySelector('option[value="${Le}"][data-_auto="1"]');if(o2)o2.remove();var prev=i.dataset._prev||'';for(var k=0;k<i.options.length;k++)i.options[k].selected=(i.options[k].value===prev);}else{if(i.dataset._type){i.type=i.dataset._type;delete i.dataset._type;}i.readOnly=false;i.value=(i.dataset._prev&&i.dataset._prev!=='${Le}')?i.dataset._prev:'';}}})(this)`}function zi(e,t){return `(function(){var h=document.getElementById('${e}');var boxes=document.querySelectorAll('input[data-enum-group="${t}"]');h.value=Array.from(boxes).filter(function(b){return b.checked;}).map(function(b){return b.value;}).join(',');})()`}function Kt({inputId:e,active:t}){return jsxs("label",{class:"flex items-center gap-1 cursor-pointer select-none text-xs text-base-content/60 hover:text-base-content border border-base-300 rounded-md px-1.5 py-1 shrink-0 leading-none h-8",title:"Filter where field IS NULL",children:[jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",checked:t,onchange:Bi(e)}),jsx("span",{children:"\u2205"})]})}function qi({col:e,active:t}){let n=t?.value??"",r=n===Le,o=`fv_input_${e.name.replace(/\./g,"__")}`,s=t?.op,a=s==="in"||s==="not-in";if(e.enumValues&&e.enumValues.length>0){if(a){let l=new Set(n.split(",").map(u=>u.trim()).filter(Boolean)),c=`eg_${e.name.replace(/\./g,"__")}`;return jsxs("div",{class:"flex flex-wrap items-center gap-1 w-full",children:[jsx("input",{type:"hidden",id:o,name:`fv_${e.name}`,value:n}),e.enumValues.map(u=>jsxs("label",{class:"flex items-center gap-1 text-xs border border-base-300 rounded px-2 cursor-pointer hover:bg-base-200",children:[jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",value:u,checked:l.has(u),"data-enum-group":c,onchange:zi(o,c)}),jsx("span",{children:u})]},u))]})}return jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),e.enumValues.map(l=>jsx("option",{value:l,selected:n===l,children:l},l)),e.nullable&&jsx("option",{value:Le,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx(Kt,{inputId:o,active:r})]})}if(e.zodType==="ZodBoolean")return jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),jsx("option",{value:"true",selected:n==="true",children:"true"}),jsx("option",{value:"false",selected:n==="false",children:"false"}),e.nullable&&jsx("option",{value:Le,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx(Kt,{inputId:o,active:r})]});if(e.zodType==="ZodArray"){let l=t?.op==="array-contains-any";return jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:l?"val1, val2, \u2026":"value",class:"input input-sm input-bordered w-full"})}return e.zodType==="ZodNumber"||e.zodType==="ZodBigInt"?jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsx("input",{id:o,type:r?"text":"number",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0,"data-_type":r?"number":void 0}),e.nullable&&jsx(Kt,{inputId:o,active:r})]}):e.zodType==="ZodDate"?jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsx("input",{id:o,type:r?"text":"datetime-local",name:`fv_${e.name}`,value:n,class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0,"data-_type":r?"datetime-local":void 0}),e.nullable&&jsx(Kt,{inputId:o,active:r})]}):jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0}),e.nullable&&jsx(Kt,{inputId:o,active:r})]})}function br({action:e,columnMeta:t,activeFilters:n,isGroup:r}){let o=Object.fromEntries(n.map(c=>[c.field,c])),s=n.length>0,a=n.length>=2||r&&s,l=t.filter(c=>c.zodType!=="ZodObject"&&c.zodType!=="ZodRecord");return jsxs("details",{class:"collapse collapse-arrow bg-base-100 border border-base-300 rounded-box mb-6 shadow-sm",open:s?true:void 0,children:[jsxs("summary",{class:"collapse-title text-sm font-medium py-2 min-h-0",children:["Filters",s&&jsxs("span",{class:"badge badge-primary badge-sm ml-2",children:[n.length," active"]})]}),jsx("div",{class:"collapse-content pb-4 pt-2",children:jsxs("form",{method:"get",action:e,children:[jsx("div",{class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:l.map(c=>{let u=ji(c.zodType),p=o[c.name],f=p?.op??u[0].value;return jsxs("div",{class:"flex flex-col gap-1.5",children:[jsx("label",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:c.name}),jsxs("div",{class:"flex gap-1.5",children:[u.length>1?jsx("select",{name:`fo_${c.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:u.map(b=>jsx("option",{value:b.value,selected:b.value===f,children:b.label},b.value))}):jsx("input",{type:"hidden",name:`fo_${c.name}`,value:u[0].value}),jsx(qi,{col:c,active:p})]})]},c.name)})}),jsxs("div",{class:"flex flex-wrap gap-2 mt-4 pt-3 border-t border-base-200 items-center",children:[jsx("button",{type:"submit",class:"btn btn-sm btn-primary",children:"Apply"}),s&&jsx("a",{href:e,class:"btn btn-sm btn-ghost",children:"Clear"}),a&&jsxs("span",{class:"text-xs text-warning ml-auto flex items-center gap-1",children:[jsx("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-4 w-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),r?"Collection group queries require a composite index":"Multiple filters may require a composite index"]})]})]})})]})}function wr(e,t,n,r,o,s){let a=n==="create"?`Create ${e}`:`Edit ${e} / ${r??""}`,l=n==="create"?[{label:"Repositories",href:o},{label:e,href:`${o}/${e}`},{label:"New document"}]:[{label:"Repositories",href:o},{label:e,href:`${o}/${e}`},{label:`Edit ${r??""}`}];return qe(jsx(Ue,{opts:{title:a,breadcrumb:l,basePath:o,flash:s},children:jsx("div",{class:"card bg-base-100 border border-base-300",children:jsx("div",{class:"card-body p-6",children:jsx("div",{dangerouslySetInnerHTML:{__html:t}})})})}))}xn();fr();function xr(e,t,n){let r=new URLSearchParams;for(let o of e)r.set(`fv_${o.field}`,o.value),r.set(`fo_${o.field}`,o.op);return t&&(r.set("ob",t.field),r.set("od",t.dir)),n&&r.set("ps",String(n)),r}function ts(e,t,n,r,o){let s=xr(e,r,o);return s.set("cursor",t),s.set("dir",n),`?${s.toString()}`}function Ui(e,t,n,r){let o=xr(n,void 0,r);return t?.field===e?t.dir==="asc"&&(o.set("ob",e),o.set("od","desc")):(o.set("ob",e),o.set("od","asc")),`?${o.toString()}`}function Li(e,t,n){return `?${xr(t,n,e).toString()}`}function Rr(e,t,n,r,o,s,a=[],l=[],c=false,u=[],p,f,b,h,w,T,S,I=false,A=true){let O=`${r}/${e}`,x=`${O}/create`,d={};if(S)for(let R of n)d[R]=qt(Ut(S,R));let y=(T??[]).filter(R=>true),i=y.length>0,g=c,m=g||i,C=y.map(R=>{let P=Ut(S,R),_=qt(P),$=a.find(M=>M.name===R);return {name:R,type:_,enumValues:$?.enumValues??null,nullable:$?.nullable??false}}),k=[];return S&&(k=Re(S).filter(P=>y.includes(P.name))),qe(jsxs(Ue,{opts:{title:e,breadcrumb:[{label:"Repositories",href:r},{label:e}],basePath:r,flash:s},children:[a.length>0&&jsx(br,{action:O,columnMeta:a,activeFilters:l,isGroup:h}),b&&jsxs("div",{role:"alert",class:`alert ${b.type==="index"?"alert-warning":"alert-error"} mb-6 shadow-sm`,children:[jsx("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6 shrink-0 stroke-current",fill:"none",viewBox:"0 0 24 24",children:b.type==="index"?jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"}):jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"})}),jsxs("div",{class:"flex-1",children:[jsx("h3",{class:"font-bold",children:b.type==="index"?"Composite index required":"Query failed"}),jsx("div",{class:"text-sm",children:b.message})]}),b.indexUrl&&jsx("a",{href:b.indexUrl,target:"_blank",rel:"noopener noreferrer",class:"btn btn-sm btn-outline",children:"Create Index \u2192"})]}),jsxs("div",{class:"flex flex-wrap justify-between items-center mb-4 gap-3","data-frs-toolbar":true,children:[jsxs("div",{class:"flex items-center gap-3",children:[jsxs("span",{class:"text-sm text-base-content/60",children:[t.length,typeof w=="number"&&jsxs(Fragment,{children:[" ","of"," ",jsx("span",{class:"font-semibold text-base-content/80",children:w})]})," ","document",(typeof w=="number"?w:t.length)!==1&&"s"]}),jsxs("div",{class:"flex items-center gap-1.5 text-sm text-base-content/60",children:[jsx("span",{children:"Rows"}),jsx("div",{class:"join",children:[10,25,50,100].map(R=>jsx("a",{href:Li(R,l,p),class:`join-item btn btn-xs ${f===R?"btn-active btn-primary":"btn-outline"}`,children:R},R))})]})]}),jsxs("div",{class:"flex gap-2",children:[A&&jsxs("div",{class:"dropdown dropdown-end","data-frs-backfill-menu":true,children:[jsxs("button",{type:"button",tabIndex:0,class:"btn btn-outline btn-sm gap-1",children:["Backfill",jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",class:"size-4 opacity-70",children:jsx("path",{"fill-rule":"evenodd",d:"M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z","clip-rule":"evenodd"})})]}),jsxs("ul",{tabIndex:0,class:"dropdown-content menu menu-sm bg-base-100 text-base-content rounded-box z-50 mt-1 w-52 p-1 shadow-lg border border-base-300",children:[jsx("li",{children:jsxs("form",{method:"post",action:`${O}/_bulk/backfill?dryRun=true`,class:"p-0 block",children:[jsx("input",{type:"hidden",name:"dryRun",value:"1"}),jsx("button",{type:"submit",class:"w-full text-left px-3 py-1.5 rounded",children:"Dry-run backfill"})]})}),jsx("li",{children:jsx("form",{method:"post",action:`${O}/_bulk/backfill`,onsubmit:"return confirm('Backfill entire repository? This will scan all documents and fill missing system keys.')",class:"p-0 block",children:jsx("button",{type:"submit",class:"w-full text-left px-3 py-1.5 rounded text-warning",children:"Run backfill"})})})]})]}),jsx("a",{href:x,class:"btn btn-primary btn-sm",children:"+ New"})]})]}),m&&jsxs("div",{class:"hidden mb-3 alert alert-info py-2 px-3","data-frs-bulk-bar":true,"data-frs-repo":e,"data-frs-total":typeof w=="number"?String(w):"","data-frs-page-size":String(f??t.length),"data-frs-allow-delete":g?"1":"0","data-frs-allow-update":i?"1":"0","data-frs-fields":JSON.stringify(C),"data-frs-filters":JSON.stringify(l),children:[jsxs("div",{class:"flex-1 text-sm",children:[jsx("span",{"data-frs-bulk-summary":true,children:"0 selected"}),typeof w=="number"&&w>t.length&&jsxs("button",{type:"button",class:"ml-3 link text-sm hidden","data-frs-bulk-select-all":true,children:["Select all ",w," matching documents"]}),jsxs("span",{class:"hidden ml-3 italic","data-frs-bulk-all-active":true,children:["All ",w??"?"," matching documents are selected."," ",jsx("button",{type:"button",class:"link","data-frs-bulk-clear":true,children:"Clear selection"})]})]}),jsxs("div",{class:"flex gap-2",children:[i&&jsx("button",{type:"button",class:"btn btn-sm btn-outline","data-frs-bulk-action":"update",children:"Update field\u2026"}),g&&jsx("button",{type:"button",class:"btn btn-sm btn-error btn-outline","data-frs-bulk-action":"delete",children:"Delete"})]})]}),jsx("div",{class:"overflow-x-auto rounded-box border border-base-300 bg-base-100","data-frs-table-wrap":true,children:jsxs("table",{class:"table table-sm w-full","data-frs-table":true,"data-frs-repo":e,"data-frs-colcount":n.length,children:[jsx("thead",{children:jsxs("tr",{class:"bg-base-200/50",children:[m&&jsx("th",{class:"w-8",children:jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-page":true,"aria-label":"Select all on this page"})}),[...n].map((R,P)=>{let _=p?.field===R,$=_?p.dir==="asc"?" \u25B2":" \u25BC":"";return jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:jsxs("a",{href:Ui(R,p,l,f),class:`hover:text-base-content inline-flex items-center gap-0.5${_?" text-primary font-bold":""}`,children:[R,$]})},P)}),u.map((R,P)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:R.column},`rel-${P}`)),jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide text-right",children:"Actions"})]})}),jsx("tbody",{children:t.length===0?jsx("tr",{children:jsx("td",{colspan:n.length+u.length+1+(m?1:0),class:"text-center py-16 text-base-content/40",children:"No documents found"})}):t.map((R,P)=>{let _=String(R.docId??R.id??""),$=`${r}/${e}/${encodeURIComponent(_)}/edit`,M=`${r}/${e}/${encodeURIComponent(_)}/delete`;return jsxs("tr",{class:"hover","data-frs-row-id":_,children:[m&&jsx("td",{class:"align-middle py-2",children:jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-row":true,value:_,"aria-label":`Select ${_}`})}),n.map((v,E)=>{let F=R[v],H=d[v],D=H?Lt(H,F):null;return jsx("td",{class:"align-top py-2",children:jsx(ht,{val:F,mismatch:D})},E)}),u.map((v,E)=>{let F=R[v.key];if(F==null||F==="")return jsx("td",{class:"py-2"},`rel-${E}`);let H=v.type==="one"?`${r}/${v.targetRepo}/${encodeURIComponent(String(F))}/edit`:`${r}/${v.targetRepo}?fv_${v.targetKey}=${encodeURIComponent(String(F))}`;return jsx("td",{class:"align-middle py-2",children:jsx("a",{href:H,class:"btn btn-xs btn-ghost btn-outline","data-frs-relation":true,"data-frs-rel-type":v.type,"data-frs-rel-repo":v.targetRepo,"data-frs-rel-fk":v.targetKey,"data-frs-rel-val":String(F),"data-frs-rel-label":v.column,children:v.column})},`rel-${E}`)}),jsx("td",{class:"align-middle text-right whitespace-nowrap py-2",children:jsxs("div",{class:"flex gap-1 justify-end",children:[jsx("a",{href:$,class:"btn btn-xs btn-outline",children:"Edit"}),I&&jsx("a",{href:`${r}/${e}/${encodeURIComponent(_)}/history`,class:"btn btn-xs btn-outline",title:"View change history",children:"History"}),c&&jsx("form",{method:"post",action:M,onsubmit:"return confirm('Delete this document?')",children:jsx("button",{type:"submit",class:"btn btn-xs btn-error btn-outline",children:"Delete"})})]})})]},P)})})]})}),(o.hasPrev||o.hasNext)&&jsxs("div",{class:"flex flex-col items-center mt-6 gap-2",children:[jsxs("div",{class:"flex justify-center items-center gap-2",children:[o.hasPrev?jsx("a",{href:ts(l,o.prevCursor,"prev",p,f),class:"btn btn-sm btn-outline",children:"\u2190 Previous"}):jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"\u2190 Previous"}),o.hasNext?jsx("a",{href:ts(l,o.nextCursor,"next",p,f),class:"btn btn-sm btn-outline",children:"Next \u2192"}):jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"Next \u2192"})]}),typeof w=="number"&&jsxs("div",{class:"text-xs text-base-content/50",children:[w," total document",w!==1?"s":"",l.length>0?" matching filters":""]})]}),m&&i&&jsxs("dialog",{id:"frs-bulk-update-modal",class:"modal",children:[jsxs("div",{class:"modal-box",children:[jsx("h3",{class:"font-bold text-lg mb-3",children:"Bulk update field"}),jsx("p",{class:"text-sm text-base-content/60 mb-4","data-frs-bulk-update-summary":true,children:"Update one field on the selected documents."}),jsxs("form",{method:"dialog","data-frs-bulk-update-form":true,"data-frs-form":true,children:[jsxs("label",{class:"form-control w-full mb-3",children:[jsx("div",{class:"label",children:jsx("span",{class:"label-text text-xs uppercase tracking-wide",children:"Field"})}),jsxs("select",{class:"select select-bordered select-sm w-full",name:"field",required:true,"data-frs-bulk-field-select":true,children:[jsx("option",{value:"",children:"\u2014 Select a field \u2014"}),y.map(R=>jsx("option",{value:R,children:R},R))]})]}),jsx("div",{class:"mb-4","data-frs-bulk-value-container":true}),jsxs("div",{class:"modal-action",children:[jsx("button",{type:"button",class:"btn btn-sm btn-ghost","data-frs-bulk-update-cancel":true,children:"Cancel"}),jsx("button",{type:"submit",class:"btn btn-sm btn-primary","data-frs-bulk-update-submit":true,children:"Apply"})]})]})]}),jsx("form",{method:"dialog",class:"modal-backdrop",children:jsx("button",{children:"close"})})]}),jsx("div",{class:"hidden","data-frs-bulk-templates":true,children:k.map(R=>jsx("div",{"data-frs-bulk-template-for":R.name,dangerouslySetInnerHTML:{__html:jt(R)}},R.name))})]}))}function Zt(e,t){return hr(e,t)}function Sr(e,t){return gr(e,t)}function vr(e,t,n,r,o,s,a,l,c,u,p,f,b,h,w,T,S,I,A){return Rr(e,t,n,r,o,s,a,l,c,u,p,f,b,h,w,T,S,I,A)}function Ke(e,t,n,r,o,s){return wr(e,t,n,r,o,s)}async function ns(e,t){if(t)try{let n=e.repo.ref,r=n?.firestore;if(t.startsWith("{"))try{let o=JSON.parse(t);if(o.docPath&&r&&typeof r.doc=="function"){let s=await r.doc(o.docPath).get();if(s.exists)return s}o.docId&&(t=o.docId);}catch{}if(t.includes("/")&&r&&typeof r.doc=="function"){let o=await r.doc(t).get();if(o.exists)return o}if(typeof n.doc=="function"){let o=await n.doc(t).get();if(o.exists)return o}}catch{}}function Sn(e,t){return Je(e,{pathKey:t.pathKey,documentKey:t.documentKey??"docId",parentKeys:t.parentKeys,documentPathTemplate:t.documentPathTemplate,isGroup:t.isGroup})}async function gt(e,t){let n=e.documentKey??"docId",r=`by${n.charAt(0).toUpperCase()}${n.slice(1)}`;if(typeof e.repo.get[r]=="function")try{let s=await e.repo.get[r](t);if(s)return s}catch{}return (await e.repo.query.by({where:[[n,"==",t]],limit:1}))[0]??null}function Tr(e,t,n){let r=e.documentKey??"docId",o=Bt(n,{ref:e.repo.ref,path:e.path,isGroup:!!e.isGroup,filters:[{field:r,op:"==",value:t}]});return o.type==="index"?{type:"warning",message:"Loading this document requires a composite index that does not exist yet.",...o.indexUrl?{action:{href:o.indexUrl,label:"Create Index \u2192",external:true}}:{}}:{type:"error",message:o.message}}function L(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function tt(e,t){e.status(302).set("Location",t).send("");}function vn(e,t){let n=t.shape,r={};for(let[o,s]of Object.entries(n)){let a=Ar(s),l=J(a),c=l==="ZodObject",u=a,p=false;if(l==="ZodUnion"){let h=Ft(a);h.some(T=>J(T)==="ZodDate")&&(p=true);let w=h.find(T=>{if(J(T)==="ZodObject"){let S=me(T);return "latitude"in S&&"longitude"in S}return false});w&&(c=true,u=w);}if(e[o+"__isnull"]==="1"){r[o]=null;continue}if(c){let h={},w=false;for(let[I,A]of Object.entries(e))I.startsWith(`${o}.`)&&(h[I.slice(o.length+1)]=A,w=true);if(w){r[o]=vn(h,u);continue}let T=e[o],S=Array.isArray(T)?T[T.length-1]:T;if(S)try{r[o]=JSON.parse(S);}catch{r[o]=S;}continue}let f=e[o],b=Array.isArray(f)?f[f.length-1]:f;if(b===void 0||b===""){l==="ZodBoolean"&&(r[o]=false);continue}if(p){r[o]=new Date(b);continue}switch(l){case "ZodBoolean":b==="__null__"?r[o]=null:r[o]=b==="true"||b==="on"||b==="1";break;case "ZodNumber":case "ZodBigInt":r[o]=Number(b);break;case "ZodDate":r[o]=new Date(b);break;case "ZodArray":try{r[o]=JSON.parse(b);}catch{r[o]=b;}break;default:if(b.startsWith("{")||b.startsWith("["))try{r[o]=JSON.parse(b);break}catch{}r[o]=b;}}return r}function rs(e){let t=null;if(e instanceof Date)t=e;else if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")t=e.toDate();else if(typeof e=="object"&&e!==null&&"_seconds"in e&&"_nanoseconds"in e)t=new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));else if(typeof e=="string"||typeof e=="number"){let r=new Date(e);isNaN(r.getTime())||(t=r);}if(!t||isNaN(t.getTime()))return null;let n=r=>String(r).padStart(2,"0");return `${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function ss(e){let t=e;for(;;){let n=J(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=ye(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=$t(t);if(!r)return n;t=r;}else return n}}function Ar(e){let t=e;for(;;){let n=J(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=ye(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=$t(t);if(!r)return t;t=r;}else return t}}function as(e){let t=e;for(;;){let n=J(t);if(n==="ZodOptional"||n==="ZodNullable")return true;if(n==="ZodDefault"){t=ye(t);continue}return false}}function is(e){let t=Ar(e),n=J(t);if(n==="ZodEnum"){let r=Ht(t);return r.length>0?r:void 0}if(n==="ZodNativeEnum"){let r=_t(t),o=Object.values(r).filter(s=>typeof s=="string");return o.length>0?o:void 0}if(n==="ZodLiteral"){let r=Mt(t);return typeof r=="string"?[r]:void 0}}function cs(e,t,n=""){let r={};for(let o of Object.keys(t.shape)){let s=n?`${n}.${o}`:o,a=e[o];if(a===null){r[s]="__null__";continue}if(a===void 0)continue;let l=Ar(t.shape[o]),c=J(l),u=c==="ZodObject",p=l,f=false;if(c==="ZodUnion"){let b=Ft(l);b.some(w=>J(w)==="ZodDate")&&(f=true);let h=b.find(w=>{if(J(w)==="ZodObject"){let T=me(w);return "latitude"in T&&"longitude"in T}return false});h&&(u=true,p=h);}if(u&&typeof a=="object"&&a!==null&&!Array.isArray(a)&&!("_seconds"in a)&&typeof a.toDate!="function"){let b=cs(a,p,s);Object.assign(r,b);}else if(c==="ZodDate"||f){let b=rs(a);b!==null&&(r[s]=b);}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)&&("_seconds"in a||typeof a.toDate=="function")){let b=rs(a);r[s]=b??JSON.stringify(a,null,2);}else typeof a=="object"?r[s]=JSON.stringify(a,null,2):r[s]=String(a);}return r}function Cr(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?Cr(n.nested,t):void 0}))}function Wi(e,t){let n=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),r=[];for(let[o,s]of Object.entries(e)){if(!o.startsWith("fv_"))continue;let a=o.slice(3);if(!t.has(a))continue;let l=(s??"").trim();if(!l)continue;let c=e[`fo_${a}`]??"==",u=n.has(c)?c:"==";r.push({field:a,op:u,value:l});}return r}function os(e){let t="__null__",n=r=>r===t?null:r==="true"?true:r==="false"?false:r!==""&&!isNaN(Number(r))?Number(r):r;return e.map(r=>{if(r.op==="array-contains-any"||r.op==="in"||r.op==="not-in"){let o=r.value.split(",").map(s=>s.trim()).filter(s=>s!==""&&s!==t).map(s=>n(s));return [r.field,r.op,o]}return [r.field,r.op,n(r.value)]})}function ls(e,t,n=""){let r=[];for(let o of e){let s=n?`${n}.${o}`:o,a=t.shape[o];if(!a){r.push({name:s,zodType:"ZodString"});continue}let l=ss(a);if(l==="ZodObject"){let c=a;for(;;){let p=J(c);if(p==="ZodOptional"||p==="ZodNullable"||p==="ZodDefault")c=ye(c);else break}let u=me(c);r.push(...ls(Object.keys(u),c,s));}else r.push({name:s,zodType:l,nullable:as(a),enumValues:is(a)});}return r}function Qi(e,t){let n=t.split("."),r=e;for(let o of n){for(;;){let a=J(r);if(a==="ZodOptional"||a==="ZodNullable"||a==="ZodDefault")r=ye(r);else break}let s=me(r);if(!(o in s))return null;r=s[o];}return r}function nt(e,t){if(!t||t.length===0)return e;let n=[],r=new Map;for(let s of t){let a=s.indexOf(".");if(a===-1)n.push(s);else {let l=s.slice(0,a),c=s.slice(a+1);r.has(l)||r.set(l,[]),r.get(l).push(c);}}let o={};for(let s of n)s in e.shape&&(o[s]=e.shape[s]);for(let[s,a]of r){if(!(s in e.shape))continue;let l=e.shape[s];for(;;){let c=J(l);if(c==="ZodOptional"||c==="ZodNullable"||c==="ZodDefault")l=ye(l);else break}if(J(l)!=="ZodObject"){o[s]=e.shape[s];continue}o[s]=nt(l,a);}return z.object(o)}function Pe(e,t,n){return Oe(e,t,n)}function ds(e,t,n){let r=new Set,o=(x,d)=>{let y=Pe(x,t,n),i=Object.values(e).map(g=>({name:g.name,path:g.path}));L(d,Sr(i,y));},s=async(x,d)=>{let y=x.params.repoName;if(!y){L(d,"Bad request",400);return}let i=e[y];if(!i){L(d,"Repository not found",404);return}let g=i.pageSize??25,m=x.query??{},C=m.cursor,k=m.dir==="prev"?"prev":"next",R=m.ob??"",P=m.od==="desc"?"desc":"asc",_=R?{field:R,dir:P}:void 0,$=parseInt(m.ps??""),M=Number.isFinite($)&&$>0?Math.min($,200):g,v=i.listColumns??Object.keys(i.schema.shape),E=i.documentKey??"docId",F=[E,...v.filter(re=>re!==E)];_&&(new Set([E,...v]).has(_.field)||(_=void 0));let H=i.filterableFields?(()=>{let re=[];for(let ie of i.filterableFields)(ie.includes(".")||v.includes(ie))&&re.push(ie);return re})():v,D=(()=>{let re=[];for(let ie of H)if(ie.includes(".")){let fe=Qi(i.schema,ie);re.push({name:ie,zodType:fe?ss(fe):"ZodString",nullable:fe?as(fe):false,enumValues:fe?is(fe):void 0});}else re.push(...ls([ie],i.schema));return re})(),N=new Set(D.map(re=>re.name)),j=Wi(m,N),z=os(j),te;C&&(te=await ns(i,C));let[K,$e]=await Promise.all([i.repo.query.paginate({pageSize:M,cursor:te,direction:k,...z.length>0?{where:z}:{},..._?{orderBy:[{field:_.field,direction:_.dir}]}:{}}).catch(re=>({queryError:Bt(re,{ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:j,sort:_})})),i.repo.aggregate.count(z.length>0?{where:z}:{}).catch(()=>{})]),Se="queryError"in K,W=Se?[]:K.data,X=Se?"":K.nextCursor?.ref?.path??K.nextCursor?.id??"",oe=Se?"":K.prevCursor?.ref?.path??K.prevCursor?.id??"",se=Se?K.queryError:void 0,we=Pe(x,t,n),ne,be=m.flash;if(be==="created")ne={type:"success",message:"Document created successfully."};else if(be==="updated")ne={type:"success",message:"Document updated successfully."};else if(be==="deleted")ne={type:"success",message:"Document deleted successfully."};else if(be==="backfilled"){let re=Ie(m.scanned),ie=Ie(m.written),fe=Ie(m.skipped);ne={type:"success",message:re!==void 0&&ie!==void 0&&fe!==void 0?`Backfill complete: scanned ${re}, updated ${ie}, skipped ${fe}.`:"Repository backfilled successfully."};}else if(be==="backfill_dryrun"){let re=Ie(m.scanned),ie=Ie(m.written),fe=Ie(m.skipped);ne={type:"success",message:re!==void 0&&ie!==void 0&&fe!==void 0?`Dry run complete: scanned ${re}, would update ${ie}, skipped ${fe}.`:"Dry run complete."};}else if(be==="backfill_partial"){let re=Ie(m.scanned),ie=Ie(m.written),fe=Ie(m.skipped),Hn=Ie(m.failed),qs=re!==void 0&&ie!==void 0&&fe!==void 0&&Hn!==void 0;ne={type:ie!==void 0&&ie>0?"warning":"error",message:qs?`Backfill finished with ${Hn} failure${Hn===1?"":"s"} (scanned ${re}, updated ${ie}, skipped ${fe}). Check server logs for details.`:"Backfill finished with failures. Check server logs for details."};}else be==="backfill_busy"&&(ne={type:"warning",message:"A backfill is already running for this repository. Please wait for it to finish."});L(d,vr(i.name,W,F,we,{hasPrev:Se?false:K.hasPrevPage,hasNext:Se?false:K.hasNextPage,prevCursor:oe,nextCursor:X},ne,D,j,i.allowDelete??false,i.relationalMeta,_,M,se,i.isGroup,$e,i.mutableFields,i.schema,i.historyEnabled,i.allowBackfill!==false));},a=(x,d)=>{let y=x.params.repoName;if(!y){L(d,"Bad request",400);return}let i=e[y];if(!i){L(d,"Repository not found",404);return}let g=Pe(x,t,n),m=nt(i.schema,i.createFields),C=Re(m),k=`${g}/${i.name}/create`,R=ze(C,k,"POST","Create document");L(d,Ke(i.name,R,"create",null,g));},l=async(x,d)=>{let y=x.params.repoName;if(!y){L(d,"Bad request",400);return}let i=e[y];if(!i){L(d,"Repository not found",404);return}let g=Pe(x,t,n),m=x.body??{},C=vn(m,i.schema),k=nt(i.schema,i.createFields),R=k.safeParse(C);if(!R.success){let P=Re(k),_=`${g}/${i.name}/create`,$=ze(P,_,"POST","Create document"),M=R.error.issues.map(v=>`${v.path.join(".")}: ${v.message}`).join(", ");L(d,Ke(i.name,$,"create",null,g,{type:"error",message:`Validation error: ${M}`}),422);return}try{if(i.isGroup&&i.parentKeys&&i.parentKeys.length>0){let P={...R.data},_=i.parentKeys.filter($=>P[$]===void 0||P[$]===null||typeof P[$]=="string"&&P[$].trim()==="");if(_.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${_.join(", ")}`);if(typeof i.repo.create=="function")await i.repo.create(P);else {let $=i.parentKeys.map(E=>String(P[E])),M=i.documentKey??"docId",v=P[M]||Be();await i.repo.set(...$,v,P);}}else await i.repo.create(R.data);tt(d,`${g}/${i.name}?flash=created`);}catch(P){let _=nt(i.schema,i.createFields),$=Re(_),M=`${g}/${i.name}/create`,v=ze($,M,"POST","Create document");L(d,Ke(i.name,v,"create",null,g,{type:"error",message:`Save error: ${P.message}`}),500);}},c=async(x,d)=>{let y=x.params.repoName,i=x.params.id;if(!y||!i){L(d,"Bad request",400);return}let g=e[y];if(!g){L(d,"Repository not found",404);return}let m=Pe(x,t,n),C=null;try{C=await gt(g,i);}catch(M){let v=Tr(g,i,M),E=Xe(M)?424:500;L(d,Zt("",{title:`Edit ${g.name} / ${i}`,basePath:m,breadcrumb:[{label:"Repositories",href:m},{label:g.name,href:`${m}/${g.name}`},{label:`Edit ${i}`}],flash:v}),E);return}if(!C){L(d,"Document not found",404);return}let k=cs(C,g.schema),R=nt(g.schema,g.mutableFields),P=Cr(Re(R),k),_=`${m}/${g.name}/${encodeURIComponent(i)}/edit`,$=ze(P,_,"POST","Save changes");L(d,Ke(g.name,$,"edit",i,m));},u=async(x,d)=>{let y=x.params.repoName,i=x.params.id;if(!y||!i){L(d,"Bad request",400);return}let g=e[y];if(!g){L(d,"Repository not found",404);return}let m=Pe(x,t,n),C=x.body??{},k=vn(C,g.schema),R=nt(g.schema,g.mutableFields),_=R.partial().safeParse(k);if(!_.success){let $=Object.fromEntries(Object.entries(C).map(([H,D])=>[H,Array.isArray(D)?D.join(","):D??""])),M=Cr(Re(R),$),v=`${m}/${g.name}/${encodeURIComponent(i)}/edit`,E=ze(M,v,"POST","Save changes"),F=_.error.issues.map(H=>`${H.path.join(".")}: ${H.message}`).join(", ");L(d,Ke(g.name,E,"edit",i,m,{type:"error",message:`Validation error: ${F}`}),422);return}try{let $=await gt(g,i),M=($&&Sn($,g))??[i];await g.repo.update(...M,_.data),tt(d,`${m}/${g.name}?flash=updated`);}catch($){let M=nt(g.schema,g.mutableFields),v=Re(M),E=`${m}/${g.name}/${encodeURIComponent(i)}/edit`,F=ze(v,E,"POST","Save changes"),H=Xe($)?Tr(g,i,$):{type:"error",message:`Save error: ${$.message}`},D=Xe($)?424:500;L(d,Ke(g.name,F,"edit",i,m,H),D);}},p=async(x,d)=>{let y=x.params.repoName,i=x.params.id;if(!y||!i){L(d,"Bad request",400);return}let g=e[y];if(!g){L(d,"Repository not found",404);return}if(!g.allowDelete){L(d,"Delete is not allowed for this repository",403);return}let m=Pe(x,t,n);try{let C=await gt(g,i),k=(C&&Sn(C,g))??[i];await g.repo.delete(...k),tt(d,`${m}/${g.name}?flash=deleted`);}catch(C){let k=Xe(C)?Tr(g,i,C):{type:"error",message:`Delete error: ${C.message}`},R=Xe(C)?424:500;L(d,Zt("",{title:`Delete ${g.name} / ${i}`,basePath:m,breadcrumb:[{label:"Repositories",href:m},{label:g.name,href:`${m}/${g.name}`},{label:`Delete ${i}`}],flash:k}),R);}},f=async(x,d)=>{let y=x.params.repoName;if(!y){L(d,"Bad request",400);return}let i=e[y];if(!i){L(d,"Repository not found",404);return}let g=Pe(x,t,n),m=x.query,C=m?.type==="many"?"many":"one",k=Math.max(1,Math.min(100,Number(m?.ps??25)||25)),R=i.listColumns??Object.keys(me(i.schema)),{PanelOne:P,PanelMany:_}=await Promise.resolve().then(()=>(mr(),Yo)),{renderToString:$}=await import('hono/jsx/dom/server');if(C==="one"){let D=String(m?.id??"");if(!D){L(d,"<div class='p-6 text-error'>Missing id parameter.</div>",400);return}try{let N=await gt(i,D),j=$(P({doc:N,repoName:i.name,basePath:g,schema:i.schema,columns:R}));L(d,j);}catch(N){L(d,`<div class='p-6 text-error text-sm'>Error: ${N.message}</div>`,500);}return}let M=String(m?.fk??""),v=String(m?.fv??"");if(!M||!v){L(d,"<div class='p-6 text-error'>Missing fk/fv parameters.</div>",400);return}let E=m?.cursor??"",F=m?.dir==="prev"?"prev":"next",H;E&&(H=await ns(i,E));try{let D=await i.repo.query.paginate({pageSize:k,cursor:H,direction:F,where:[[M,"==",Yi(v)]]}),N=$(_({docs:D.data,repoName:i.name,basePath:g,fk:M,fv:v,columns:R,schema:i.schema,pagination:{hasPrev:D.hasPrevPage,hasNext:D.hasNextPage,prevCursor:D.prevCursor?.ref?.path??D.prevCursor?.id??"",nextCursor:D.nextCursor?.ref?.path??D.nextCursor?.id??"",pageSize:k}}));L(d,N);}catch(D){L(d,`<div class='p-6 text-error text-sm'>Error: ${D.message}</div>`,500);}},b=async(x,d)=>{let y=Gi(x),i=x.params.repoName;if(!i){y?ae(d,{error:"Bad request"},400):L(d,"Bad request",400);return}let g=e[i];if(!g){y?ae(d,{error:"Repository not found"},404):L(d,"Repository not found",404);return}if(g.allowBackfill===false){let k="Backfill is not allowed for this repository";y?ae(d,{error:k},403):L(d,k,403);return}let m=Pe(x,t,n);if(r.has(i)){y?ae(d,{error:`Backfill is already running for "${i}"`},409):tt(d,`${m}/${g.name}?flash=backfill_busy`);return}let C=Ji(x);r.add(i);try{let k=await g.repo.system.backfillKeys({dryRun:C}),R=k?.scanned??0,P=k?.written??0,_=k?.skipped??0,$=Array.isArray(k?.failures)?k.failures:[];if($.length>0&&console.error(`[admin] Backfill for "${i}" finished with ${$.length} failure(s) (scanned=${R}, written=${P}, skipped=${_}):`,$.map(v=>({path:v.path,error:kr(v.error)}))),y){let v=$.length===0?200:P>0?207:500;ae(d,{dryRun:C,scanned:R,written:P,skipped:_,failures:$.map(E=>({path:E.path,error:kr(E.error)}))},v);return}let M=new URLSearchParams({scanned:String(R),written:String(P),skipped:String(_)});$.length>0?(M.set("failed",String($.length)),tt(d,`${m}/${g.name}?flash=backfill_partial&${M.toString()}`)):C?tt(d,`${m}/${g.name}?flash=backfill_dryrun&${M.toString()}`):tt(d,`${m}/${g.name}?flash=backfilled&${M.toString()}`);}catch(k){let R=kr(k);console.error(`[admin] Backfill failed for "${i}":`,k),y?ae(d,{error:R},500):L(d,`<div class="p-6 text-error">Backfill failed: ${Vi(R)}</div>`,500);}finally{r.delete(i);}},h=async(x,d)=>{let y=[];for(let i of d){let g;if(x.isGroup||x.parentKeys?.length){let m=await gt(x,i);g=m?Sn(m,x):void 0;}g||(g=[i]);try{let m=x.repo.documentRef(...g);m&&y.push(m);}catch{}}return y},w=async(x,d)=>{let y=os(d),i=x.documentKey??"docId",g=[],m;for(;;){let C=await x.repo.query.paginate({pageSize:500,cursor:m,direction:"next",...y.length>0?{where:y}:{}});for(let k of C.data){let R=String(k[i]??k.id??"");R&&g.push(R);}if(!C.hasNextPage||!C.nextCursor)break;m=C.nextCursor;}return g},T=async(x,d)=>{let y=x.params.repoName;if(!y){ae(d,{error:"Bad request"},400);return}let i=e[y];if(!i){ae(d,{error:"Repository not found"},404);return}if(!i.allowDelete){ae(d,{error:"Delete is not allowed for this repository"},403);return}let g=x.body??{};try{let m=await I(i,g);if(m.length===0){ae(d,{deleted:0});return}let C=await h(i,m);for(let k=0;k<C.length;k+=500)await i.repo.bulk.delete(C.slice(k,k+500));ae(d,{deleted:C.length});}catch(m){ae(d,{error:m.message},500);}},S=async(x,d)=>{let y=x.params.repoName;if(!y){ae(d,{error:"Bad request"},400);return}let i=e[y];if(!i){ae(d,{error:"Repository not found"},404);return}let g=x.body??{},m=String(g.field??"");if(!m){ae(d,{error:"Missing 'field'"},400);return}if(!i.mutableFields||!i.mutableFields.includes(m)){ae(d,{error:`Field '${m}' is not bulk-updatable`},403);return}let C=i.schema.shape?.[m],k;if(C){let R=typeof i.schema=="object"&&i.schema&&"constructor"in i.schema&&i.schema.constructor.name.includes("Zod")?i.schema.pick({[m]:true}):void 0;if(!R){ae(d,{error:"Invalid schema structure"},500);return}k=vn(g.formPayload??{},R)[m];let _=C.safeParse(k);if(!_.success){ae(d,{error:`Invalid value for '${m}': ${_.error.message}`},400);return}k=_.data;}try{let R=await I(i,g);if(R.length===0){ae(d,{updated:0});return}let _=(await h(i,R)).map($=>({docRef:$,data:{[m]:k}}));for(let $=0;$<_.length;$+=500)await i.repo.bulk.update(_.slice($,$+500));ae(d,{updated:_.length});}catch(R){ae(d,{error:R.message},500);}};async function I(x,d){if(d.selectAll){let y=A(d.filters,x);return await w(x,y)}return Array.isArray(d.ids)?d.ids.filter(y=>typeof y=="string"&&!!y):[]}function A(x,d){if(!Array.isArray(x))return [];let y=new Set((d.filterableFields??Object.keys(me(d.schema))).map(m=>String(m))),i=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),g=[];for(let m of x)m&&typeof m=="object"&&typeof m.field=="string"&&y.has(m.field)&&typeof m.value=="string"&&i.has(String(m.op))&&g.push({field:m.field,op:m.op,value:m.value});return g}return {handleDashboard:o,handleList:s,handleCreateForm:a,handleCreateSubmit:l,handleEditForm:c,handleEditSubmit:u,handleDelete:p,handlePanel:f,handleBulkDelete:T,handleBulkUpdate:S,handleBulkBackfill:b,handleHistory:async(x,d)=>{let y=x.params.repoName,i=x.params.id;if(!y||!i){L(d,"Bad request",400);return}let g=e[y];if(!g){L(d,"Repository not found",404);return}if(!g.historyEnabled||!g.repo.history){L(d,"History not enabled for this repository",404);return}let m=Pe(x,t,n),C=g.historySubcollection??"history",k=[i];try{let D=await gt(g,i),N=D?Sn(D,g):void 0;N&&N.length>0&&(k=N);}catch{}let R=parseInt(String(x.query?.limit??"")),P=Number.isFinite(R)&&R>0?Math.min(R,500):100,_=[],$;try{_=await g.repo.history.list(...k,{limit:P});}catch(D){$=D.message;}let M=D=>String(D??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),v=D=>{if(D===void 0)return '<span class="opacity-40">undefined</span>';if(D===null)return '<span class="opacity-40">null</span>';if(typeof D=="object")try{return `<code class="text-xs">${M(JSON.stringify(D))}</code>`}catch{return M(String(D))}return M(String(D))},E=D=>D?typeof D.toDate=="function"?D.toDate().toISOString():D instanceof Date?D.toISOString():M(String(D)):"",F=D=>`<span class="badge badge-sm ${D==="create"?"badge-success":D==="delete"?"badge-error":D==="custom"?"badge-secondary":"badge-info"}">${M(D)}</span>`,H="";if(H+='<div class="flex items-center justify-between mb-4">',H+=`<a href="${m}/${g.name}/${encodeURIComponent(i)}/edit" class="btn btn-sm btn-outline">\u2190 Back to edit</a>`,H+=`<a href="${m}/${g.name}" class="btn btn-sm btn-outline">\u2190 Back to list</a>`,H+="</div>",H+=`<p class="text-sm text-base-content/60 mb-4">Subcollection: <code>${M(C)}</code> \xB7 Showing up to ${P} entries.</p>`,$)H+=`<div class="alert alert-error mb-4">${M($)}</div>`;else if(_.length===0)H+='<div class="alert">No history entries found.</div>';else {H+='<div class="overflow-x-auto"><table class="table table-zebra table-sm">',H+="<thead><tr><th>When</th><th>Op</th><th>User</th><th>Reason / Comment</th><th>Changes</th></tr></thead><tbody>";for(let D of _){let N=D.meta??{},j=[N.reason,N.comment].filter(K=>K!=null&&K!=="").map(K=>M(String(K))).join(" \u2014 "),z="",te=Object.keys(D.changes??{});if(D.custom){let K=`<strong>${M(D.custom.title)}</strong>`,$e=D.custom.key?` <code class="text-xs opacity-60">${M(D.custom.key)}</code>`:"",Se=D.custom.description?`<div class="text-xs opacity-80 mt-0.5">${M(D.custom.description)}</div>`:"";z=`<div>${K}${$e}${Se}</div>`;}else te.length===0?z='<span class="opacity-40">\u2014</span>':z='<ul class="space-y-1">'+te.map(K=>{let $e=D.changes[K];return `<li><strong>${M(K)}</strong>: ${v($e.oldValue)} \u2192 ${v($e.newValue)}</li>`}).join("")+"</ul>";H+="<tr>",H+=`<td class="whitespace-nowrap text-xs font-mono">${M(E(D.historySetAt))}</td>`,H+=`<td>${F(D.operation??"update")}</td>`,H+=`<td class="text-xs">${M(N.userEmail??N.userId??"")}</td>`,H+=`<td class="text-xs">${j}</td>`,H+=`<td>${z}</td>`,H+="</tr>";}H+="</tbody></table></div>";}L(d,Zt(H,{title:`History \u2014 ${g.name} / ${i}`,basePath:m,breadcrumb:[{label:"Repositories",href:m},{label:g.name,href:`${m}/${g.name}`},{label:`History ${i}`}]}));}}}function ae(e,t,n=200){e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(t));}function Vi(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function kr(e){return e instanceof Error||e&&typeof e=="object"&&typeof e.message=="string"?e.message:String(e)}function Gi(e){let t=e.headers??{},n="",r="";for(let[o,s]of Object.entries(t)){let a=o.toLowerCase(),l=Array.isArray(s)?s.join(","):String(s??"");a==="accept"?n=l.toLowerCase():a==="content-type"&&(r=l.toLowerCase());}return n.includes("application/json")||r.includes("application/json")}function bt(e){if(e===true||e===1)return true;if(typeof e=="string"){let t=e.trim().toLowerCase();return t==="true"||t==="1"}return Array.isArray(e)&&e.length>0?bt(e[e.length-1]):false}function Ji(e){let t=e.query??{};if(t.dryRun!==void 0)return bt(t.dryRun);if(typeof e.url=="string"){let r=e.url.indexOf("?");if(r!==-1){let s=new URLSearchParams(e.url.slice(r+1)).get("dryRun");if(s!==null)return bt(s)}}let n=e.body;if(n&&typeof n=="object"&&!Array.isArray(n)){let r=n.dryRun;if(r!==void 0)return bt(r)}else if(typeof n=="string"&&n.trim()!==""){let r=n.trim();if(r.startsWith("{"))try{let o=JSON.parse(r);if(o&&typeof o=="object"&&!Array.isArray(o)){let s=o.dryRun;if(s!==void 0)return bt(s)}}catch{}else {let s=new URLSearchParams(r).get("dryRun");if(s!==null)return bt(s)}}return false}function Ie(e){if(e===void 0||e==="")return;let t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function Yi(e){return e==="true"?true:e==="false"?false:e!==""&&!isNaN(Number(e))?Number(e):e}kn();async function ys(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function Xi(e){let t={};if(!e)return t;for(let n of e.split("&")){let r=n.indexOf("=");if(r===-1)continue;let o=decodeURIComponent(n.slice(0,r).replace(/\+/g," ")),s=decodeURIComponent(n.slice(r+1).replace(/\+/g," ")),a=t[o];a===void 0?t[o]=s:Array.isArray(a)?a.push(s):t[o]=[a,s];}return t}function ms(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,auth:s,middleware:a=[],httpsOptions:l}=e,c=t==="/"?"":t.replace(/\/$/,""),u={};for(let[h,w]of Object.entries(n)){if(!w.repo)throw new Error(`[createAdminServer] Repository "${h}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let T=w.schema??w.repo.schema??null;if(!T)throw new Error(`[createAdminServer] Repository "${h}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let S,I,A;if(w.fieldsConfig){let d=w.fieldsConfig;S=[],I=[],A=[];for(let[y,i]of Object.entries(d))for(let g of i)g==="filterable"?S.push(y):g==="mutable"?I.push(y):g==="create"&&A.push(y);S.length===0&&(S=void 0),I.length===0&&(I=void 0),A.length===0&&(A=void 0);}let O=(()=>{let d=w.repo._parentKeys;return d&&d.length>0?d:void 0})();if(O&&A)for(let d of O)A.includes(d)||A.push(d);let x={name:h,path:w.path,repo:w.repo,schema:T,documentKey:w.documentKey??"docId",pathKey:w.repo._pathKey??void 0,isGroup:!!w.repo._isGroup,parentKeys:O,documentPathTemplate:w.repo._documentPathTemplate??void 0,createdKey:w.repo._createdKey??void 0,listColumns:w.listColumns,pageSize:w.pageSize,filterableFields:S,mutableFields:I,createFields:A,allowDelete:w.allowDelete??false,allowBackfill:w.allowBackfill??true,historyEnabled:!!w.repo._historyConfig?.enabled,historySubcollection:(w.repo._historyConfig?.enabled&&w.repo._historySubcollection)??void 0,relationalMeta:(()=>{if(!w.relationalFields||w.relationalFields.length===0)return;let d=w.repo.relationalKeys??{},y=[];for(let i of w.relationalFields){let g=d[i.key];g&&y.push({key:g.sourceKey?String(g.sourceKey):i.key,column:i.column,targetRepo:String(g.repo),targetKey:String(g.key),type:g.type});}return y.length>0?y:void 0})()};u[h]=x;}let p=ds(u,c,un(l?.region)),f=new Me;if(o!==false&&f.use(Tn(o===void 0?{}:o)),r&&f.use(async(h,w,T)=>{let S=h,I="";if(S.headers){for(let[A,O]of Object.entries(S.headers))if(A.toLowerCase()==="content-type"){I=(Array.isArray(O)?O.join(","):String(O??"")).toLowerCase();break}}if(I.includes("application/x-www-form-urlencoded")){let A=await ys(S)||(typeof S.body=="string"?S.body:"");(A!==""||!S.body||typeof S.body!="object")&&(h.body=Xi(A));}else if(I.includes("application/json")){let A=typeof S.body=="string"?S.body:S.body===void 0?await ys(S):"";if(A)try{h.body=JSON.parse(A);}catch{}}await T();}),s)if(Pt(s)){for(let h of s.routes){let w=`${c}${h.path}`;h.method==="GET"?f.get(w,h.handler):f.post(w,h.handler);}f.use(s.middleware);}else if(typeof s=="function")f.use(s);else {let h=s.realm??"Admin",w="Basic "+Buffer.from(`${s.username}:${s.password}`).toString("base64");f.use((T,S,I)=>{if((T.headers?.authorization??"")!==w){S.status(401).set("WWW-Authenticate",`Basic realm="${h}"`).set("Content-Type","text/plain").send("Unauthorized");return}I();});}for(let h of a)f.use(h);f.get(`${c}/`,p.handleDashboard),f.get(`${c}`,p.handleDashboard),f.get(`${c}/:repoName/_panel`,p.handlePanel),f.post(`${c}/:repoName/_bulk/delete`,p.handleBulkDelete),f.post(`${c}/:repoName/_bulk/update`,p.handleBulkUpdate),f.post(`${c}/:repoName/_bulk/backfill`,p.handleBulkBackfill),f.get(`${c}/:repoName`,p.handleList),f.get(`${c}/:repoName/create`,p.handleCreateForm),f.post(`${c}/:repoName/create`,p.handleCreateSubmit),f.get(`${c}/:repoName/:id/edit`,p.handleEditForm),f.post(`${c}/:repoName/:id/edit`,p.handleEditSubmit),f.get(`${c}/:repoName/:id/history`,p.handleHistory),f.post(`${c}/:repoName/:id/delete`,p.handleDelete);let b=async(h,w)=>{await f.handle(h,w);};return l&&(b.httpsOptions=l),b}ft();function Te(e,t){let n=e||{},r={},o={...n};for(let[s,a]of Object.entries(t||{})){let l=n[s];At(l,a)||(r[s]=a,o[s]=a);}return {before:n,after:o,changes:r}}function Or(e){return e}async function Cn(e,t,n){let r=e.changes||{};for(let o of Object.keys(r)){let s=t[o];if(s&&s.length>0){for(let a of s)if(await a.rule({diff:e,key:o,user:n,authenticatedUser:n})===false)return {allowed:false,reason:a.description}}}return {allowed:true}}function Pr(e){return async t=>Cn(t.diff,e,t.user)}var Ir=1e3;function hs(e,t){if(e===void 0)return {success:true,value:Math.min(Math.max(1,t),Ir)};let n=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN;return !Number.isInteger(n)||n<=0||n>Ir?{success:false,error:`Invalid pageSize: must be an integer between 1 and ${Ir}`}:{success:true,value:n}}function Hr(e,t,n=200){let r=ce(t);return e.json(r,n)}function rt(e,t,n,r=200){return Hr(e,{success:true,data:t,meta:n},r)}function q(e,t,n=400){return Hr(e,{success:false,error:t},n)}async function Dr(e,t,n,r,o,s){let a=Bt(t,n),l=a.type==="index",c=l?424:500,p={success:false,error:l?a.message:o&&t instanceof Error?t.message:r};if(l&&(p.errorType="index",a.indexUrl&&(p.indexUrl=a.indexUrl,s)))try{let f=s({indexUrl:a.indexUrl,repoName:n.repoName??"",path:n.path,isGroup:n.isGroup,filters:n.filters,sort:n.sort,error:t,c:e});f instanceof Promise&&await f;}catch(f){o&&console.error("[crudServer] Error in indexesError callback:",f);}return Hr(e,p,c)}function ot(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return z.preprocess(r=>zn(r)??r,e);if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[s,a]of Object.entries(r))o[s]=ot(a);return z.object(o)}if(n==="ZodArray"||n==="array"){let r=t.element??t.type;if(r)return z.array(ot(r))}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(r)return ot(r).optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(r)return ot(r).nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType,o=t.defaultValue;if(r){let s=ot(r);return typeof o=="function"?s.default(o()):s.default(o)}}return e}function ec(e,t,n=[]){let r=e.shape,o={},s=t&&t.length>0?t:Object.keys(r);for(let a of s){if(n.includes(a))continue;let l=a.split(".")[0];l&&r[l]&&(o[l]=r[l]);}return z.object(o)}function $r(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function ws(e,t){let n=t.split("."),r=$r(e);for(let o=0;o<n.length;o++){let s=n[o];if(!s)continue;let a=r?.shape;if(!a||!a[s])return;let l=a[s];if(o===n.length-1)return l;r=$r(l);}return r}function st(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type;if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[s,a]of Object.entries(r))o[s]=st(a);return z.object(o).partial()}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(!r)return e;let o=st(r);return o===r?e:o.optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(!r)return e;let o=st(r);return o===r?e:o.nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType;return r?st(r).optional():e}if(n==="ZodUnion"||n==="union"){let r=t.options;if(!r||r.length<2)return e;let o=r.map(a=>st(a));return o.some((a,l)=>a!==r[l])?z.union(o):e}return e}function An(e,t,n,r=false,o=[]){if(typeof t!="object"||t===null||Array.isArray(t))return {success:false,error:"Data payload must be an object"};try{let s=t,a={},l={};for(let[c,u]of Object.entries(s))if(c.includes(".")){let p=c.split(".")[0];if(o.includes(c)||o.includes(p))continue;if(n&&n.length>0&&!n.includes(c)&&!n.includes(p))return {success:!1,error:`Field '${c}' is not allowed for this operation`};let f=ws(e,c);if(!f)return {success:!1,error:`Field '${c}' does not exist in schema`};let b=r?st(f):f,w=(nn()==="normalize"?ot(b):b).parse(u);a[c]=w;}else l[c]=u;if(Object.keys(l).length>0||Object.keys(a).length===0){let c=ec(e,n,o),u=r?st(c):c,f=(nn()==="normalize"?ot(u):u).parse(l);Object.assign(a,f);}return {success:!0,data:a}}catch(s){return s instanceof z.ZodError?{success:false,error:`Validation failed: ${s.issues.map(l=>`${l.path.join(".")}: ${l.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}var xs={eq:"==","==":"==",ne:"!=","!=":"!=",lt:"<","<":"<",lte:"<=","<=":"<=",gt:">",">":">",gte:">=",">=":">=",in:"in",nin:"not-in","not-in":"not-in",not_in:"not-in",contains:"array-contains","array-contains":"array-contains",array_contains:"array-contains",arrayContains:"array-contains",containsAny:"array-contains-any","array-contains-any":"array-contains-any",array_contains_any:"array-contains-any",arrayContainsAny:"array-contains-any"};function Wt(e){return xs[e]??e}function tc(e){return e in xs}function En(e,t,n,r){let o=ws(e,t);if(!o||typeof o.safeParse!="function")return {success:true,data:n};let s=r?Wt(r):void 0,a=$r(o),l=pn(a);if(s==="array-contains"){let p=l??o;if(typeof p.safeParse=="function"){let f=p.safeParse(n);return f.success?{success:true,data:f.data}:{success:false,error:f.error.issues.map(h=>h.message).join(", ")}}return {success:true,data:n}}if(s==="array-contains-any"){if(!Array.isArray(n))return {success:false,error:"Expected array value for array-contains-any"};let p=l??o,f=[];for(let b of n)if(typeof p.safeParse=="function"){let h=p.safeParse(b);if(h.success)f.push(h.data);else return {success:false,error:h.error.issues.map(T=>T.message).join(", ")}}else f.push(b);return {success:true,data:f}}let c=o.safeParse(n);if(c.success)return {success:true,data:c.data};if(Array.isArray(n)){let p=l??o,f=[];for(let b of n)if(typeof p.safeParse=="function"){let h=p.safeParse(b);if(h.success)f.push(h.data);else return {success:false,error:h.error.issues.map(T=>T.message).join(", ")}}else f.push(b);return {success:true,data:f}}return {success:false,error:c.error.issues.map(p=>p.message).join(", ")}}function nc(e,t){let n=[],r=t?new Set(t):null;for(let[o,s]of Object.entries(e)){if(s===void 0||["cursor","direction","limit","pageSize","orderBy","orderDir","select","includes","withTotal"].includes(o))continue;let a=Array.isArray(s)?s[0]:s;if(a===void 0||a==="")continue;let l=o.lastIndexOf("__"),c,u="==";if(l!==-1){let f=o.slice(0,l),b=o.slice(l+2);tc(b)?(c=f,u=Wt(b)):(c=o,u="==");}else c=o;if(r&&!r.has(c))continue;let p=a;u==="in"||u==="not-in"||u==="array-contains-any"?p=a.split(",").map(f=>gs(f.trim())):p=gs(a),n.push({field:c,op:u,value:p});}return n}function gs(e){if(e==="true")return true;if(e==="false")return false;if(e==="null"||e==="__null__")return null;let t=Number(e);return !isNaN(t)&&e!==""?t:e}function On(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function bs(e,t){if(!t)return;let n;if(typeof t=="string")try{n=JSON.parse(t);}catch{n=t.includes("/")?{docPath:t}:{docId:t};}else typeof t=="object"&&(n=t);if(!n)return;let r=typeof n.docPath=="string"?n.docPath:void 0,o=typeof n.docId=="string"?n.docId:void 0;try{let s=e.repo.ref,a=s?.firestore;if(r&&a&&typeof a.doc=="function"){let l=await a.doc(r).get();if(l.exists)return l}if(o&&o.includes("/")&&a&&typeof a.doc=="function"){let l=await a.doc(o).get();if(l.exists)return l}if(o&&typeof s.doc=="function"){let l=await s.doc(o).get();if(l.exists)return l}return}catch{return}}function Pn(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t={},n=0;for(let[r,o]of Object.entries(e))o!==void 0&&(t[r]=o,n++);return n>0?t:null}function Rs(e,t,n,r,o){async function s(x,d,y,i){let g=false;if(x.hooks?.onAfterError){g=true;try{let m=x.hooks.onAfterError(i,y.hook);m instanceof Promise&&await m;}catch(m){console.error("[crudServer] Error in hooks.onAfterError callback:",m);}}if(o){g=true;try{let m=o({...y,error:i});m instanceof Promise&&await m;}catch(m){console.error("[crudServer] Error in onHookError callback:",m);}}if(!g){if(d&&typeof d.error=="function"){d.error(i,{hook:y.hook,repoName:y.repoName,path:y.path,...y.id!==void 0?{id:y.id}:{},...y.pathArgs!==void 0?{pathArgs:y.pathArgs}:{}});return}console.error(`[crudServer] Hook "${y.hook}" failed on repo "${y.repoName}":`,{hook:y.hook,repoName:y.repoName,path:y.path,...y.id!==void 0?{id:y.id}:{},...y.pathArgs!==void 0?{pathArgs:y.pathArgs}:{},error:i});}}async function a(x,d,y,i){if(!d.rules)return {allowed:true};let g=d.rules?.[y];if(!g)return {allowed:false,errorResponse:q(x,`Operation "${y}" is not allowed for this repository`,403)};try{let m=await g(i);return m===!1?{allowed:!1,errorResponse:q(x,"Forbidden",403)}:typeof m=="string"?{allowed:!1,errorResponse:q(x,m,403)}:typeof m=="object"&&m!==null&&!m.allowed?{allowed:!1,errorResponse:q(x,m.reason||"Forbidden",403)}:{allowed:!0}}catch(m){let C=n&&m instanceof Error?m.message:"Forbidden";return {allowed:false,errorResponse:q(x,C,403)}}}async function l(x,d,y,i){if(!x.rules)return i;let g=x.rules?.filter;if(!g)return i;let m=[];for(let C of i)try{await g({user:d,doc:C,params:y})&&m.push(C);}catch{}return m}function c(x){return x.get("user")??x.get("docsUser")??null}function u(x,d){if(!x){let y=d.req.path.split("/");for(let i of y)if(e[i]){x=i;break}}return !x||!e[x]?null:e[x]??null}function p(x,d){return Je(x,{pathKey:d.pathKey,documentKey:d.documentKey,parentKeys:d.parentKeys,documentPathTemplate:d.documentPathTemplate,isGroup:d.isGroup})}async function f(x,d){let y=`by${x.documentKey.charAt(0).toUpperCase()}${x.documentKey.slice(1)}`,i=x.repo.get[y];if(typeof i=="function")try{let m=await i(d);if(m)return m}catch{}return (await x.repo.query.by({where:[[x.documentKey,"==",d]],limit:1}))[0]??null}async function b(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return q(d,"Repository not found",404);let g=c(d),m=await a(d,i,"list",{user:g,query:d.req.query(),params:y});if(!m.allowed)return m.errorResponse;let C=[],k;try{let R=d.req.query(),P=hs(R.pageSize,i.pageSize);if(!P.success)return q(d,P.error,400);let _=P.value,$=R.cursor,M=R.direction?.toLowerCase()==="prev"?"prev":"next",v=R.orderBy,E=R.orderDir?.toLowerCase()==="desc"?"desc":"asc",F=R.select,H=F?F.split(",").map(W=>W.trim()):void 0,D=R.withTotal,N=D==="true"||D==="1"||D===!0,j;i.allowedIncludes&&R.includes&&(j=(typeof R.includes=="string"?R.includes.split(",").map(X=>X.trim()):Array.isArray(R.includes)?R.includes:[]).filter(X=>typeof X=="string"&&i.allowedIncludes.includes(X)),j?.length===0&&(j=void 0));let z=nc(R,i.filterableFields);C=z.map(W=>({field:W.field,op:W.op,value:String(W.value??"")})),v&&(k={field:v,dir:E});let te={pageSize:_,direction:M,...N?{withTotal:!0}:{}};if($)try{let W=typeof $=="string"?JSON.parse($):$;te.cursor=await bs(i,W);}catch{}if(v){if(i.orderableFields&&!i.orderableFields.includes(v))return q(d,`Field not orderable: ${v}`,400);te.orderBy=[{field:v,direction:E}];}if(z.length>0){te.where=[];for(let W of z){let X=En(i.schema,W.field,W.value,W.op);if(!X.success)return q(d,`Invalid filter value for '${W.field}': ${X.error}`,400);te.where.push([W.field,W.op,X.data]);}}H&&(te.select=H),j&&(te.include=j);let K=await i.repo.query.paginate(te),Se={items:await l(i,c(d),y,K.data),hasNextPage:K.hasNextPage,hasPrevPage:K.hasPrevPage,nextCursor:On(K.nextCursor),prevCursor:On(K.prevCursor),...K.totalCount!==void 0?{totalCount:K.totalCount,totalCountIsExact:K.totalCountIsExact}:{}};return rt(d,Se,{pageSize:_,hasMore:K.hasNextPage,...K.totalCount!==void 0?{totalCount:K.totalCount,totalCountIsExact:K.totalCountIsExact}:{}})}catch(R){return await Dr(d,R,{repoName:y.repoName||i.name,ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:C,sort:k},"Failed to fetch documents",n,r)}}async function h(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return q(d,"Repository not found",404);let g=c(d),m=await a(d,i,"list",{user:g,query:x.input||{},params:y});if(!m.allowed)return m.errorResponse;let C=[],k;try{let R=x.input||{},P=hs(R.pageSize,i.pageSize);if(!P.success)return q(d,P.error,400);let _=P.value,$=R.direction==="prev"?"prev":"next";R.where&&(C=R.where.map(D=>({field:String(D[0]),op:D[1],value:String(D[2]??"")}))),R.orderBy&&R.orderBy[0]&&(k={field:R.orderBy[0].field,dir:R.orderBy[0].direction==="desc"?"desc":"asc"});let M=R.withTotal===!0||String(R.withTotal)==="true",v={pageSize:_,direction:$,...M?{withTotal:!0}:{}};if(R.cursor)try{let D=typeof R.cursor=="string"?JSON.parse(R.cursor):R.cursor;v.cursor=await bs(i,D);}catch{}if(i.allowedIncludes&&R.includes&&R.includes.length>0){let D=R.includes.filter(N=>typeof N=="string"?i.allowedIncludes.includes(N):typeof N=="object"&&N!==null&&"relation"in N&&typeof N.relation=="string"?i.allowedIncludes.includes(N.relation):!1);D.length>0&&(v.include=D);}if(R.where&&R.where.length>0){if(i.filterableFields){let N=new Set(i.filterableFields),j=R.where.filter(z=>!N.has(z[0]));if(j.length>0){q(d,`Fields not filterable: ${j.map(z=>z[0]).join(", ")}`,400);return}}let D=[];for(let N of R.where){let j=Wt(N[1]),z=En(i.schema,N[0],N[2],j);if(!z.success){q(d,`Invalid filter value for '${N[0]}': ${z.error}`,400);return}D.push([N[0],j,z.data]);}v.where=D;}if(R.orWhere&&R.orWhere.length>0){if(i.filterableFields){let N=new Set(i.filterableFields),j=R.orWhere.filter(z=>!N.has(z[0]));if(j.length>0){q(d,`Fields not filterable: ${j.map(z=>z[0]).join(", ")}`,400);return}}let D=[];for(let N of R.orWhere){let j=Wt(N[1]),z=En(i.schema,N[0],N[2],j);if(!z.success){q(d,`Invalid filter value for '${N[0]}': ${z.error}`,400);return}D.push([N[0],j,z.data]);}v.orWhere=D;}if(R.orWhereGroups&&R.orWhereGroups.length>0){if(i.filterableFields){let N=new Set(i.filterableFields);for(let j of R.orWhereGroups){let z=j.filter(te=>!N.has(te[0]));if(z.length>0){q(d,`Fields not filterable: ${z.map(te=>te[0]).join(", ")}`,400);return}}}let D=[];for(let N of R.orWhereGroups){let j=[];for(let z of N){let te=Wt(z[1]),K=En(i.schema,z[0],z[2],te);if(!K.success){q(d,`Invalid filter value for '${z[0]}': ${K.error}`,400);return}j.push([z[0],te,K.data]);}D.push(j);}v.orWhereGroups=D;}if(R.orderBy&&R.orderBy.length>0){if(i.orderableFields){let D=new Set(i.orderableFields),N=R.orderBy.filter(j=>!D.has(j.field));if(N.length>0){q(d,`Fields not orderable: ${N.map(j=>j.field).join(", ")}`,400);return}}v.orderBy=R.orderBy;}R.select&&R.select.length>0&&(v.select=R.select);let E=await i.repo.query.paginate(v),H={items:await l(i,c(d),y,E.data),hasNextPage:E.hasNextPage,hasPrevPage:E.hasPrevPage,nextCursor:On(E.nextCursor),prevCursor:On(E.prevCursor),...E.totalCount!==void 0?{totalCount:E.totalCount,totalCountIsExact:E.totalCountIsExact}:{}};return rt(d,H,{pageSize:_,hasMore:E.hasNextPage,...E.totalCount!==void 0?{totalCount:E.totalCount,totalCountIsExact:E.totalCountIsExact}:{}})}catch(R){return await Dr(d,R,{repoName:y.repoName||i.name,ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:C,sort:k},"Failed to query documents",n,r)}}async function w(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return q(d,"Repository not found",404);let g=y.id;if(!g)return q(d,"Document ID required",400);try{let m=await f(i,g);if(!m)return q(d,"Document not found",404);let C=c(d),k=await a(d,i,"get",{user:C,doc:m,params:y});if(!k.allowed)return k.errorResponse;if(i.rules?.filter)try{if(!await i.rules.filter({user:C,doc:m,params:y}))return q(d,"Document not found",404)}catch{return q(d,"Document not found",404)}return rt(d,m)}catch(m){return await Dr(d,m,{repoName:y.repoName||i.name,ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:[{field:i.documentKey,op:"==",value:g}]},"Failed to fetch document",n,r)}}async function T(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return q(d,"Repository not found",404);try{let g=x.input||{},m=c(d),C=await a(d,i,"create",{user:m,body:g,params:y});if(!C.allowed)return C.errorResponse;let k=An(i.schema,g,i.createFields,!1,i.systemKeys);if(!k.success)return q(d,k.error,400);if(i.validate){let $=await i.validate(k.data,"create");if($)return q(d,$,400)}i.hooks?.beforeCreate&&await i.hooks.beforeCreate({user:m,body:k.data,params:y,c:d});let R,P;if(i.isGroup&&i.parentKeys&&i.parentKeys.length>0){let $={...k.data},M=i.parentKeys.filter(v=>$[v]===void 0||$[v]===null||typeof $[v]=="string"&&$[v].trim()==="");if(M.length>0)return q(d,`Missing parent key(s) for subcollection create: ${M.join(", ")}`,400);if(typeof i.repo.create=="function")R=await i.repo.create($);else {let v=i.parentKeys.map(F=>String($[F])),E=$[i.documentKey]||Be();P=[...v,E],R=await i.repo.set(...v,E,$);}}else R=await i.repo.create(k.data);let _=R;if(i.hooks?.afterCreate){let $=R?.[i.documentKey]??P?.[P.length-1]??"",M=String($),v=P??p(R,i)??p({...k.data,...M?{[i.documentKey]:M}:{}},i)??(M?[M]:[]);try{let E=await i.hooks.afterCreate({user:m,doc:R,id:M,pathArgs:v,params:y,c:d}),F=Pn(E);F&&v.length>0&&(_=await i.repo.update(...v,F));}catch(E){await s(i,x.logger,{hook:"afterCreate",repoName:i.name,path:i.path,id:M,pathArgs:v,user:m,c:d},E);}}return rt(d,_,void 0,201)}catch(g){let m=n&&g instanceof Error?g.message:"Failed to create document";return q(d,m,500)}}async function S(x,d){let y=x.c,i=y.req.param(),g=u(i.repoName,y);if(!g)return q(y,"Repository not found",404);let m=i.id;if(!m)return q(y,"Document ID required",400);try{let C=x.input||{},k=await f(g,m);if(!k)return q(y,"Document not found",404);let R=An(g.schema,C,g.mutableFields,d,g.systemKeys);if(!R.success)return q(y,R.error,400);if(g.validate){let D=await g.validate(R.data,"update");if(D)return q(y,D,400)}let P=Te(k,R.data),_=c(y),$=await a(y,g,"update",{user:_,doc:k,body:R.data,diff:P,params:i});if(!$.allowed)return $.errorResponse;if(g.hooks?.beforeUpdate){let D=g.rules?.update?Te(k,R.data):P;await g.hooks.beforeUpdate({user:_,doc:k,body:R.data,diff:D,params:i,c:y});}let M={...R.data},v=g.hooks?.afterUpdate?Te(k,M):P,E=p(k,g)??[m],F=await g.repo.update(...E,R.data),H=F;if(g.hooks?.afterUpdate)try{let D=await g.hooks.afterUpdate({user:_,before:k,after:F,body:M,diff:v,id:m,pathArgs:E,params:i,c:y}),N=Pn(D);N&&(H=await g.repo.update(...E,N));}catch(D){await s(g,x.logger,{hook:"afterUpdate",repoName:g.name,path:g.path,id:m,pathArgs:E,user:_,c:y},D);}return rt(y,H)}catch(C){let k=n&&C instanceof Error?C.message:"Failed to update document";return q(y,k,500)}}async function I(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return q(d,"Repository not found",404);if(!i.allowDelete)return q(d,"Delete not allowed for this repository",403);let g=y.id;if(!g)return q(d,"Document ID required",400);try{let m=await f(i,g);if(!m)return q(d,"Document not found",404);let C=c(d),k=await a(d,i,"delete",{user:C,doc:m,params:y});if(!k.allowed)return k.errorResponse;let R=p(m,i)??[g];if(await i.repo.delete(...R),i.hooks?.afterDelete)try{await i.hooks.afterDelete({user:C,doc:m,id:g,pathArgs:R,params:y,c:d});}catch(P){await s(i,x.logger,{hook:"afterDelete",repoName:i.name,path:i.path,id:g,pathArgs:R,user:C,c:d},P);}return rt(d,{deleted:!0})}catch(m){let C=n&&m instanceof Error?m.message:"Failed to delete document";return q(d,C,500)}}function A(x){return x.c.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-History-Reason, X-History-Comment","Access-Control-Max-Age":"86400"})}async function O(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return q(d,"Repository not found",404);try{let g=x.input||{};if(!Array.isArray(g.operations))return q(d,"operations array is required",400);let m=c(d),C=i.repo.batch.create(),k=[],R=!!i.hooks,P=[],_=[],$=[];for(let v of g.operations){if(!v.type||!["create","update","delete"].includes(v.type))return q(d,"Invalid operation type",400);if(v.type==="create"){let E=await a(d,i,"create",{user:m,body:v.data,params:y});if(!E.allowed)return E.errorResponse;let F=An(i.schema,v.data,i.createFields,!1,i.systemKeys);if(!F.success)return q(d,F.error,400);i.hooks?.beforeCreate&&await i.hooks.beforeCreate({user:m,body:F.data,params:y,c:d});let H=v.data[i.documentKey]||F.data[i.documentKey]||Be(),D={...F.data};i.createdKey&&D[i.createdKey]===void 0&&(D[i.createdKey]=new Date);let N;if(i.isGroup&&i.parentKeys){let j=i.parentKeys.map(z=>String(D[z]));N=[...j,H],C.set(...j,H,D);}else N=[H],C.set(H,D);if(k.push({op:"create",id:H}),R){let j={...D,[i.documentKey]:H};if(i.pathKey&&typeof i.repo.documentRef=="function")try{let z=i.repo.documentRef(...N);z?.path&&(j[i.pathKey]=z.path);}catch{}P.push({id:H,pathArgs:N,doc:j});}}else if(v.type==="update"){if(!v.id)return q(d,"id required for update",400);let E=await f(i,v.id);if(!E)return q(d,`Document ${v.id} not found`,404);let F=An(i.schema,v.data,i.mutableFields,!0,i.systemKeys);if(!F.success)return q(d,F.error,400);if(i.validate){let te=await i.validate(F.data,"update");if(te)return q(d,te,400)}let H=Te(E,F.data),D=await a(d,i,"update",{user:m,doc:E,body:F.data,diff:H,params:y});if(!D.allowed)return D.errorResponse;if(i.hooks?.beforeUpdate){let te=i.rules?.update?Te(E,F.data):H;await i.hooks.beforeUpdate({user:m,doc:E,body:F.data,diff:te,params:y,c:d});}let N={...F.data},j=R?Te(E,N):H,z=p(E,i)??[v.id];C.update(...z,F.data),k.push({op:"update",id:v.id}),R&&_.push({id:v.id,pathArgs:z,before:E,after:j.after,body:N,diff:j});}else if(v.type==="delete"){if(!i.allowDelete)return q(d,"Delete not allowed",403);if(!v.id)return q(d,"id required for delete",400);let E=await f(i,v.id);if(!E)return q(d,`Document ${v.id} not found`,404);let F=await a(d,i,"delete",{user:m,doc:E,params:y});if(!F.allowed)return F.errorResponse;let H=p(E,i)??[v.id];C.delete(...H),k.push({op:"delete",id:v.id}),R&&$.push({id:v.id,pathArgs:H,doc:E});}}await C.commit();let M=P.length>0||_.length>0||$.length>0;if(i.hooks&&M)if(i.hooks.afterBatch)try{await i.hooks.afterBatch({user:m,created:P,updated:_,deleted:$,params:y,c:d});}catch(v){await s(i,x.logger,{hook:"afterBatch",repoName:i.name,path:i.path,user:m,c:d},v);}else {if(i.hooks.afterCreate)for(let v of P)try{let E=await i.hooks.afterCreate({user:m,doc:v.doc,id:v.id,pathArgs:v.pathArgs,params:y,c:d}),F=Pn(E);F&&v.pathArgs.length>0&&await i.repo.update(...v.pathArgs,F);}catch(E){await s(i,x.logger,{hook:"afterCreate",repoName:i.name,path:i.path,id:v.id,pathArgs:v.pathArgs,user:m,c:d},E);}if(i.hooks.afterUpdate)for(let v of _)try{let E=await i.hooks.afterUpdate({user:m,before:v.before,after:v.after,body:v.body,diff:v.diff,id:v.id,pathArgs:v.pathArgs,params:y,c:d}),F=Pn(E);F&&v.pathArgs.length>0&&await i.repo.update(...v.pathArgs,F);}catch(E){await s(i,x.logger,{hook:"afterUpdate",repoName:i.name,path:i.path,id:v.id,pathArgs:v.pathArgs,user:m,c:d},E);}if(i.hooks.afterDelete)for(let v of $)try{await i.hooks.afterDelete({user:m,doc:v.doc,id:v.id,pathArgs:v.pathArgs,params:y,c:d});}catch(E){await s(i,x.logger,{hook:"afterDelete",repoName:i.name,path:i.path,id:v.id,pathArgs:v.pathArgs,user:m,c:d},E);}}return rt(d,{results:k})}catch(g){let m=n&&g instanceof Error?g.message:"Batch operation failed";return q(d,m,500)}}return {handleList:b,handleQuery:h,handleGet:w,handleCreate:T,handleUpdate:S,handleDelete:I,handleBatch:O,handleOptions:A}}function xt(e){try{return z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=getOpenApiMetadata(t.zodSchema);n&&(Object.assign(t.jsonSchema,n),(t.jsonSchema.anyOf||t.jsonSchema.oneOf)&&delete t.jsonSchema.type);let r=t.zodSchema?._zod?.def;r&&(r.type==="date"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):r.type==="bigint"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf&&(t.jsonSchema.type="string",t.jsonSchema.format="int64"));}})}catch(t){return typeof console<"u"&&console.warn&&console.warn("[generateOpenAPISpec] Failed to convert Zod schema to JSON Schema; falling back to {type:object}.",t),{type:"object"}}}function pe(e){return {$ref:`#/components/schemas/${e}`}}function ee(e){return {description:e,content:{"application/json":{schema:pe("ErrorResponse")}}}}function wt(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function rc(e){return {description:"Paginated list of documents",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:{type:"object",properties:{items:{type:"array",items:e},nextCursor:{oneOf:[{type:"object"},{type:"null"}]},prevCursor:{oneOf:[{type:"object"},{type:"null"}]},hasNextPage:{type:"boolean"},hasPrevPage:{type:"boolean"},totalCount:{type:"integer",description:"Total count of matching documents (when requested with withTotal=true)"},totalCountIsExact:{type:"boolean",description:"Whether totalCount is exact (true) or estimated via parallel branch-sum fallback (false)"}},required:["items","hasNextPage","hasPrevPage"]},meta:{type:"object",properties:{pageSize:{type:"integer"},hasMore:{type:"boolean"},totalCount:{type:"integer"},totalCountIsExact:{type:"boolean"},cursor:{oneOf:[{type:"string"},{type:"null"}]}}}},required:["success","data"]}}}}}function Vt(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function oc(e,t){let n=t.split("."),r=Vt(e);for(let o=0;o<n.length;o++){let s=n[o];if(!s)continue;let a=r?.shape;if(!a||!a[s])return;let l=a[s];if(o===n.length-1)return l;r=Vt(l);}return r}function it(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type,r=o=>{let s=getOpenApiMetadata(e);return s&&typeof o.openapi=="function"?o.openapi(s):o};if(n==="ZodObject"||n==="object"){let o=e.shape,s={};for(let[a,l]of Object.entries(o))s[a]=it(l);return r(z.object(s).partial())}if(n==="ZodOptional"||n==="optional"){let o=t.innerType;if(!o)return e;let s=it(o);return s===o?e:r(s.optional())}if(n==="ZodNullable"||n==="nullable"){let o=t.innerType;if(!o)return e;let s=it(o);return s===o?e:r(s.nullable())}if(n==="ZodDefault"||n==="default"){let o=t.innerType;return o?r(it(o).optional()):e}if(n==="ZodUnion"||n==="union"){let o=t.options;if(!o||o.length<2)return e;let s=o.map(l=>it(l));return s.some((l,c)=>l!==o[c])?r(z.union(s)):e}return e}function _r(e,t="",n=0){if(n>5)return [];let o=Vt(e)?.shape;if(!o)return [];let s=[];for(let[a,l]of Object.entries(o)){let c=t?`${t}.${a}`:a,u=Vt(l);u?.shape&&typeof u.shape=="object"?(s.push({path:c,zodSchema:l}),s.push(..._r(u,c,n+1))):s.push({path:c,zodSchema:l});}return s}function sc(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:oc(e.schema,t)})):_r(e.schema)}function Ss(e){if(!e)return {type:"string"};let t=xt(e);return delete t.$schema,delete t.title,t}function Ts(){return {type:"object",properties:{where:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3},description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3},description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3}},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string"},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string"},description:"Fields to select (projection)"},pageSize:{type:"integer",minimum:1,maximum:1e3,description:"Number of items per page"},cursor:{oneOf:[{type:"string"},{type:"object"}],description:"Pagination cursor"},direction:{type:"string",enum:["next","prev"],description:"Pagination direction"},includes:{type:"array",items:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function ac(e){let t=sc(e),n=e.orderableFields??t.map(a=>a.path),r=t.map(a=>a.path);if(t.length===0)return Ts();let o=[];for(let{path:a,zodSchema:l}of t){let c=Ss(l),u=Vt(l),f=u?._zod?.def?.type==="array"||u?._def?.typeName==="ZodArray"||u?._def?.type==="array"?Ss(u?._zod?.def?.element??u?._def?.type??u?._def?.element):c;o.push({type:"array",description:`Condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["==","!=","<","<=",">",">=","eq","ne","lt","lte","gt","gte"]},c],minItems:3,maxItems:3}),o.push({type:"array",description:`List condition on '${a}' (in, not-in)`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["in","not-in","nin"]},{type:"array",items:c}],minItems:3,maxItems:3}),o.push({type:"array",description:`Array contains condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains","contains"]},f],minItems:3,maxItems:3}),o.push({type:"array",description:`Array contains-any condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains-any","containsAny"]},{type:"array",items:f}],minItems:3,maxItems:3});}let s={oneOf:o};return {type:"object",properties:{where:{type:"array",items:s,description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:s,description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:s},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string",enum:n},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string",enum:r},description:"Fields to select (projection)"},pageSize:{type:"integer",minimum:1,maximum:1e3,description:"Number of items per page"},cursor:{oneOf:[{type:"string"},{type:"object"}],description:"Pagination cursor"},direction:{type:"string",enum:["next","prev"],description:"Pagination direction"},includes:{type:"array",items:e.allowedIncludes&&e.allowedIncludes.length>0?{oneOf:[{type:"string",enum:e.allowedIncludes},{type:"object",properties:{relation:{type:"string",enum:e.allowedIncludes},select:{type:"array",items:{type:"string"}}},required:["relation"]}]}:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function ic(e){if(e.historyHeaders)return e.historyHeaders;let t=e.repo?._historyConfig;if(!t?.enabled||t.autoInjectMeta===false)return null;let n=Ee(t);return n?{reason:n.fields.reason!==false,comment:n.fields.comment!==false}:null}function cc(e,t){if(t===false)return [];let n=ic(e);if(!n)return [];let r=t?.reasonHeader===void 0?Ve:t.reasonHeader,o=t?.commentHeader===void 0?Ge:t.commentHeader,s=[],a=new Set;if(n.reason&&typeof r=="string"&&r.trim()){let l=r.trim();a.add(l.toLowerCase()),s.push({name:l,in:"header",required:false,schema:{type:"string"},description:"Optional reason recorded in the document's change history"});}if(n.comment&&typeof o=="string"&&o.trim()){let l=o.trim();a.has(l.toLowerCase())||(a.add(l.toLowerCase()),s.push({name:l,in:"header",required:false,schema:{type:"string"},description:"Optional comment recorded in the document's change history"}));}if(t?.extraHeaders?.length)for(let l of t.extraHeaders){let c=typeof l=="string"?{name:l}:l,u=c?.name?.trim();!u||a.has(u.toLowerCase())||(a.add(u.toLowerCase()),s.push({name:u,in:"header",required:c.required??false,schema:c.schema??{type:"string"},...c.description?{description:c.description}:{}}));}return s}function lc(e,t,n,r,o,s=null,a="QueryRequestBody",l=[]){let c={},u=e.name,p=`${t}/${e.name}`,f=`${p}/{${e.documentKey}}`,b={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};c[p]={post:{operationId:`create${Ze(e.name)}`,summary:`Create a ${De(e.name)}`,tags:[u],...l.length>0?{parameters:[...l]}:{},requestBody:{required:true,content:{"application/json":{schema:pe(r??n)}}},responses:{201:wt("Document created",pe(n)),400:ee("Validation error"),403:ee("Forbidden"),500:ee("Internal server error")}}},c[`${p}/query`]={post:{operationId:`query${Ze(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[u],requestBody:{required:true,content:{"application/json":{schema:pe(a)}}},responses:{200:rc(pe(n)),400:ee("Invalid query"),403:ee("Forbidden"),424:ee("Missing composite index (includes indexUrl in response)"),500:ee("Internal server error")}}},c[`${p}/batch`]={post:{operationId:`batch${Ze(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[u],...l.length>0?{parameters:[...l]}:{},requestBody:{required:true,content:{"application/json":{schema:pe(`${n}BatchRequest`)}}},responses:{200:wt("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:ee("Validation error"),403:ee("Forbidden"),404:ee("Document not found"),500:ee("Internal server error")}}};let h={};return h.get={operationId:`get${Ze(De(e.name))}`,summary:`Get a single ${De(e.name)}`,tags:[u],parameters:[b],responses:{200:wt("Document found",pe(n)),400:ee("Document ID required"),403:ee("Forbidden"),404:ee("Document not found"),424:ee("Missing composite index (includes indexUrl in response)"),500:ee("Internal server error")}},h.put={operationId:`update${Ze(De(e.name))}`,summary:`Update a ${De(e.name)} (full replace)`,tags:[u],parameters:[b,...l],requestBody:{required:true,content:{"application/json":{schema:pe(o??n)}}},responses:{200:wt("Document updated",pe(n)),400:ee("Validation error"),403:ee("Forbidden"),404:ee("Document not found"),500:ee("Internal server error")}},h.patch={operationId:`patch${Ze(De(e.name))}`,summary:`Partially update a ${De(e.name)}`,tags:[u],parameters:[b,...l],requestBody:{required:true,content:{"application/json":{schema:pe(s??o??n)}}},responses:{200:wt("Document patched",pe(n)),400:ee("Validation error"),403:ee("Forbidden"),404:ee("Document not found"),500:ee("Internal server error")}},e.allowDelete&&(h.delete={operationId:`delete${Ze(De(e.name))}`,summary:`Delete a ${De(e.name)}`,tags:[u],parameters:[b],responses:{200:wt("Document deleted",{type:"object",properties:{id:{type:"string"}}}),400:ee("Document ID required"),403:ee("Forbidden"),404:ee("Document not found"),500:ee("Internal server error")}}),c[f]=h,c}function Mr(e,t,n={}){let{title:r="CRUD API",version:o="1.0.0",description:s,servers:a,auth:l=false}=n,c=t==="/"?"":t.replace(/\/$/,""),u={},p={},f=[];u.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string",description:"Human-readable error description"},errorType:{type:"string",enum:["index"],description:"Error category discriminator. Set to 'index' when a Firestore composite index is missing."},indexUrl:{type:"string",format:"uri",description:"Direct Firebase Console URL to create the required composite index (when errorType is 'index')."}},required:["success","error"]},u.QueryRequestBody=Ts();for(let[T,S]of Object.entries(e)){let I=Ze(De(T)),A=`${I}Create`,O=`${I}Update`,x=`${I}Patch`,d=`${I}QueryRequestBody`;u[I]=xt(S.schema),u[d]=ac(S);let y=v=>{let E={},F=_r(S.schema);for(let{path:H,zodSchema:D}of F){let N=H.split(".")[0];S.systemKeys.includes(N)||S.systemKeys.includes(H)||v&&v.length>0&&!v.includes(H)&&!v.includes(N)||(H.includes(".")?E[H]=D.optional():E[H]=D);}return E},i=null,g=y(S.createFields);if(S.isGroup&&S.parentKeys&&S.parentKeys.length>0){let v=S.schema?.shape??{};for(let E of S.parentKeys)!g[E]&&v[E]&&(g[E]=v[E]);}if(Object.keys(g).length>0){let v=xt(z.object(g));if(S.isGroup&&S.parentKeys&&S.parentKeys.length>0){let E=new Set(Array.isArray(v.required)?v.required:[]);for(let F of S.parentKeys)v.properties?.[F]&&E.add(F);E.size>0&&(v.required=Array.from(E));}u[A]=v,i=A;}let m=null,C=null,k=y(S.mutableFields);if(Object.keys(k).length>0){let v=z.object(k);u[O]=xt(v),m=O,u[x]=xt(it(v)),C=x;}else u[x]=xt(it(S.schema)),C=x;let R=`${I}BatchCreateOperation`,P=`${I}BatchUpdateOperation`,_=`${I}BatchDeleteOperation`;u[R]={type:"object",title:`${I} Create Operation`,properties:{type:{type:"string",enum:["create"],const:"create"},data:pe(i??I)},required:["type","data"]},u[P]={type:"object",title:`${I} Update Operation`,properties:{type:{type:"string",enum:["update"],const:"update"},id:{type:"string"},data:pe(C??m??I)},required:["type","id","data"]},S.allowDelete&&(u[_]={type:"object",title:`${I} Delete Operation`,properties:{type:{type:"string",enum:["delete"],const:"delete"},id:{type:"string"}},required:["type","id"]}),u[`${I}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[pe(R),pe(P),...S.allowDelete?[pe(_)]:[]],discriminator:{propertyName:"type"}}}},required:["operations"]};let $=cc(S,n.historyHeaders),M=lc(S,c,I,i,m,C,d,$);Object.assign(p,M),f.push({name:T,description:`Operations on ${T} (collection: ${S.path})`});}let b={},h;return l==="basic"?(b.basicAuth={type:"http",scheme:"basic"},h=[{basicAuth:[]}]):l==="bearer"&&(b.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},h=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:o,...s?{description:s}:{}},...a&&a.length>0?{servers:a}:{},paths:p,components:{schemas:u,...Object.keys(b).length>0?{securitySchemes:b}:{}},...h?{security:h}:{},tags:f}}function Ze(e){return e.charAt(0).toUpperCase()+e.slice(1)}function De(e){return e.endsWith("ies")?e.slice(0,-3)+"y":e.endsWith("ses")||e.endsWith("xes")||e.endsWith("zes")?e.slice(0,-2):e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e}var Rt=class extends Error{constructor(n,r){super("Request validation failed");this.zodError=n;this.source=r;this.statusCode=400;this.name="ValidationError";}};var Gt=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},Jt=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function ks(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function Cs(e,t){return t instanceof Rt?e.json({success:false,error:"Validation failed",issues:ks(t.zodError)},400):t instanceof Gt?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof Jt?e.json({success:false,error:"Output validation failed",issues:ks(t.zodError)},500):null}extendZodWithOpenApi(z);var As="Successful response",Es="Error response";function ge(e,t=new Set){if(!e||typeof e!="object"||t.has(e))return;t.add(e);let n=e,r=n._zod?.def??n.def;if(!r)return;if(r.type==="custom"){let s=getOpenApiMetadata(n);s?.type||z.globalRegistry.add(n,{...s??{},type:"object"});return}if(r.innerType&&ge(r.innerType,t),r.element&&ge(r.element,t),r.valueType&&ge(r.valueType,t),r.keyType&&ge(r.keyType,t),r.left&&ge(r.left,t),r.right&&ge(r.right,t),r.in&&ge(r.in,t),r.out&&ge(r.out,t),typeof r.getter=="function")try{ge(r.getter(),t);}catch{}if(Array.isArray(r.options))for(let s of r.options)ge(s,t);if(Array.isArray(r.items))for(let s of r.items)ge(s,t);let o=typeof r.shape=="function"?r.shape():r.shape;if(o&&typeof o=="object")for(let s of Object.values(o))ge(s,t);}function Fr(e){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(let n of e)Fr(n);return}let t=e;(Array.isArray(t.anyOf)||Array.isArray(t.oneOf))&&"type"in t&&delete t.type;for(let n of Object.values(t))Fr(n);}function yc(e){return e==="get"?"query":"json"}function mc(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function hc(e){if(typeof e.safeParse=="function")return {description:Es,schema:e};let t=e;return {description:t.description??Es,schema:t.schema}}function Is(e,t,n,r){let o=new OpenAPIRegistry;if(n.securitySchemes)for(let[l,c]of Object.entries(n.securitySchemes))o.registerComponent("securitySchemes",l,c);for(let l of e){let c=l.method,u=l.source??yc(c),p=wc(t,l.path??"/"),f=l.status??200;l.input&&ge(l.input);let b=gc(c,u,l.input),h=Os(u,l.input,"query"),w=Os(u,l.input,"param"),T=xc(c,p),S=mc(l.output,r);S&&ge(S);let I={[f]:S?{description:As,content:{"application/json":{schema:S}}}:{description:As}};if(r?.errors)for(let[A,O]of Object.entries(r.errors)){let{description:x,schema:d}=hc(O);d&&ge(d),I[A]=d?{description:x,content:{"application/json":{schema:d}}}:{description:x};}o.registerPath({method:c,path:bc(p),operationId:T,summary:l.summary,description:l.description,tags:l.tags,deprecated:l.deprecated,security:l.security,request:{...h?{query:h}:{},...w?{params:w}:{},...b?{body:b}:{}},responses:I});}let a=new OpenApiGeneratorV31(o.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security});return Fr(a),a}function gc(e,t,n){return !n||e==="get"?null:t==="json"?{content:{"application/json":{schema:n}}}:t==="form"?{content:{"application/x-www-form-urlencoded":{schema:n}}}:null}function Os(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function bc(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function wc(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function xc(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function Ds(e,t){let n=e.replace(/"/g,"&quot;");return `<!doctype html>
1161
+ `;function zt(){return jsx("script",{dangerouslySetInnerHTML:{__html:Yo}})}mr();function qe(e){return "<!DOCTYPE html>"+renderToString(e)}var Ni=["corporate","silk","dark"],Fi=()=>jsxs("div",{class:"dropdown dropdown-end","data-frs-theme-switcher":true,children:[jsxs("button",{type:"button",tabIndex:0,class:"btn btn-sm btn-ghost text-neutral-content gap-1.5","aria-label":"Switch theme",children:[jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",class:"size-4",children:[jsx("circle",{cx:"12",cy:"12",r:"4"}),jsx("path",{d:"M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"})]}),jsx("span",{class:"text-xs hidden sm:inline","data-frs-theme-current":true,children:"Theme"})]}),jsx("ul",{tabIndex:0,class:"dropdown-content menu menu-sm bg-base-100 text-base-content rounded-box z-50 mt-2 w-40 p-1 shadow-lg border border-base-300",children:Ni.map(e=>jsx("li",{children:jsxs("button",{type:"button","data-frs-theme":e,class:"capitalize justify-between",children:[jsx("span",{children:e}),jsx("span",{class:"hidden text-primary","data-frs-theme-check":e,children:"\u2713"})]})},e))})]}),Ue=({opts:e,children:t})=>{let{title:n,breadcrumb:r,flash:o,basePath:s="/"}=e;return jsxs("html",{lang:"en","data-theme":"corporate",children:[jsxs("head",{children:[jsx("meta",{charset:"UTF-8"}),jsx("meta",{name:"viewport",content:"width=device-width, initial-scale=1"}),jsxs("title",{children:[n," \u2014 FRS Admin"]}),jsx("script",{dangerouslySetInnerHTML:{__html:"(function(){try{var t=localStorage.getItem('frs-admin-theme');if(t){document.documentElement.setAttribute('data-theme',t);}}catch(_){}})();"}}),jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/themes.css",rel:"stylesheet",type:"text/css"}),jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/daisyui.css",rel:"stylesheet",type:"text/css"}),jsx("script",{src:"https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"})]}),jsxs("body",{class:"bg-base-200/50 min-h-screen flex flex-col",children:[jsxs("div",{class:"navbar bg-neutral text-neutral-content shadow-sm sticky top-0 z-50 px-6",children:[jsx("div",{class:"flex-1",children:jsx("a",{href:s,class:"font-bold text-lg tracking-tight hover:opacity-80 transition-opacity",children:"FRS Admin"})}),jsx("div",{class:"flex-none",children:jsx(Fi,{})})]}),jsxs("main",{class:"px-6 py-8 w-full flex-1",children:[r&&r.length>0&&jsx("div",{class:"text-sm breadcrumbs mb-4",children:jsx("ul",{children:r.map((a,l)=>a.href?jsx("li",{children:jsx("a",{href:a.href,children:a.label})},l):jsx("li",{class:"text-base-content/60",children:a.label},l))})}),jsx("h1",{class:"text-2xl font-bold mb-6",children:n}),o&&jsxs("div",{role:"alert",class:`alert ${o.type==="success"?"alert-success":o.type==="warning"?"alert-warning":"alert-error"} mb-6`,children:[jsx("span",{class:"flex-1",children:o.message}),o.action&&jsx("a",{href:o.action.href,...o.action.external?{target:"_blank",rel:"noopener noreferrer"}:{},class:"btn btn-sm btn-outline",children:o.action.label})]}),t]}),jsx(yr,{basePath:s}),jsx(zt,{})]})]})};function hr(e,t){return qe(jsx(Ue,{opts:t,children:jsx("div",{dangerouslySetInnerHTML:{__html:e}})}))}function gr(e,t){return qe(jsx(Ue,{opts:{title:"Repositories",basePath:t},children:e.length===0?jsxs("div",{class:"text-center py-20 text-base-content/50",children:[jsx("p",{class:"text-lg font-medium mb-1",children:"No repositories configured"}),jsx("p",{class:"text-sm",children:"Add a repository to your FRS config to get started."})]}):jsx("div",{class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:e.map(n=>jsx("a",{href:`${t}/${n.name}`,class:"card bg-base-100 border border-base-300 hover:shadow-md no-underline transition-shadow",children:jsxs("div",{class:"card-body p-5",children:[jsx("h2",{class:"card-title text-sm font-semibold",children:n.name}),jsx("p",{class:"text-xs text-base-content/50 font-mono",children:n.path})]})},n.name))})}))}var ns=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],ji=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"<",label:"<"},{value:"<=",label:"\u2264"},{value:">",label:">"},{value:">=",label:"\u2265"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],Bi=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function zi(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return ji;case "ZodBoolean":return ns;case "ZodArray":return Bi;default:return ns}}var Le="__null__";function qi(e){return `(function(cb){var i=document.getElementById('${e}');if(!i)return;if(cb.checked){i.dataset._prev=i.value;if(i.tagName==='SELECT'){var o=i.querySelector('option[value="${Le}"]');if(!o){o=document.createElement('option');o.value='${Le}';o.textContent='\u2205 null';o.dataset._auto='1';i.appendChild(o);}o.selected=true;}else{if(i.type==='number'||i.type==='datetime-local'){i.dataset._type=i.type;i.type='text';}i.value='${Le}';i.readOnly=true;}i.style.opacity='0.55';}else{i.style.opacity='';if(i.tagName==='SELECT'){var o2=i.querySelector('option[value="${Le}"][data-_auto="1"]');if(o2)o2.remove();var prev=i.dataset._prev||'';for(var k=0;k<i.options.length;k++)i.options[k].selected=(i.options[k].value===prev);}else{if(i.dataset._type){i.type=i.dataset._type;delete i.dataset._type;}i.readOnly=false;i.value=(i.dataset._prev&&i.dataset._prev!=='${Le}')?i.dataset._prev:'';}}})(this)`}function Ui(e,t){return `(function(){var h=document.getElementById('${e}');var boxes=document.querySelectorAll('input[data-enum-group="${t}"]');h.value=Array.from(boxes).filter(function(b){return b.checked;}).map(function(b){return b.value;}).join(',');})()`}function Kt({inputId:e,active:t}){return jsxs("label",{class:"flex items-center gap-1 cursor-pointer select-none text-xs text-base-content/60 hover:text-base-content border border-base-300 rounded-md px-1.5 py-1 shrink-0 leading-none h-8",title:"Filter where field IS NULL",children:[jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",checked:t,onchange:qi(e)}),jsx("span",{children:"\u2205"})]})}function Li({col:e,active:t}){let n=t?.value??"",r=n===Le,o=`fv_input_${e.name.replace(/\./g,"__")}`,s=t?.op,a=s==="in"||s==="not-in";if(e.enumValues&&e.enumValues.length>0){if(a){let l=new Set(n.split(",").map(u=>u.trim()).filter(Boolean)),c=`eg_${e.name.replace(/\./g,"__")}`;return jsxs("div",{class:"flex flex-wrap items-center gap-1 w-full",children:[jsx("input",{type:"hidden",id:o,name:`fv_${e.name}`,value:n}),e.enumValues.map(u=>jsxs("label",{class:"flex items-center gap-1 text-xs border border-base-300 rounded px-2 cursor-pointer hover:bg-base-200",children:[jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",value:u,checked:l.has(u),"data-enum-group":c,onchange:Ui(o,c)}),jsx("span",{children:u})]},u))]})}return jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),e.enumValues.map(l=>jsx("option",{value:l,selected:n===l,children:l},l)),e.nullable&&jsx("option",{value:Le,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx(Kt,{inputId:o,active:r})]})}if(e.zodType==="ZodBoolean")return jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),jsx("option",{value:"true",selected:n==="true",children:"true"}),jsx("option",{value:"false",selected:n==="false",children:"false"}),e.nullable&&jsx("option",{value:Le,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx(Kt,{inputId:o,active:r})]});if(e.zodType==="ZodArray"){let l=t?.op==="array-contains-any";return jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:l?"val1, val2, \u2026":"value",class:"input input-sm input-bordered w-full"})}return e.zodType==="ZodNumber"||e.zodType==="ZodBigInt"?jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsx("input",{id:o,type:r?"text":"number",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0,"data-_type":r?"number":void 0}),e.nullable&&jsx(Kt,{inputId:o,active:r})]}):e.zodType==="ZodDate"?jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsx("input",{id:o,type:r?"text":"datetime-local",name:`fv_${e.name}`,value:n,class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0,"data-_type":r?"datetime-local":void 0}),e.nullable&&jsx(Kt,{inputId:o,active:r})]}):jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0}),e.nullable&&jsx(Kt,{inputId:o,active:r})]})}function br({action:e,columnMeta:t,activeFilters:n,isGroup:r}){let o=Object.fromEntries(n.map(c=>[c.field,c])),s=n.length>0,a=n.length>=2||r&&s,l=t.filter(c=>c.zodType!=="ZodObject"&&c.zodType!=="ZodRecord");return jsxs("details",{class:"collapse collapse-arrow bg-base-100 border border-base-300 rounded-box mb-6 shadow-sm",open:s?true:void 0,children:[jsxs("summary",{class:"collapse-title text-sm font-medium py-2 min-h-0",children:["Filters",s&&jsxs("span",{class:"badge badge-primary badge-sm ml-2",children:[n.length," active"]})]}),jsx("div",{class:"collapse-content pb-4 pt-2",children:jsxs("form",{method:"get",action:e,children:[jsx("div",{class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:l.map(c=>{let u=zi(c.zodType),p=o[c.name],f=p?.op??u[0].value;return jsxs("div",{class:"flex flex-col gap-1.5",children:[jsx("label",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:c.name}),jsxs("div",{class:"flex gap-1.5",children:[u.length>1?jsx("select",{name:`fo_${c.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:u.map(b=>jsx("option",{value:b.value,selected:b.value===f,children:b.label},b.value))}):jsx("input",{type:"hidden",name:`fo_${c.name}`,value:u[0].value}),jsx(Li,{col:c,active:p})]})]},c.name)})}),jsxs("div",{class:"flex flex-wrap gap-2 mt-4 pt-3 border-t border-base-200 items-center",children:[jsx("button",{type:"submit",class:"btn btn-sm btn-primary",children:"Apply"}),s&&jsx("a",{href:e,class:"btn btn-sm btn-ghost",children:"Clear"}),a&&jsxs("span",{class:"text-xs text-warning ml-auto flex items-center gap-1",children:[jsx("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-4 w-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),r?"Collection group queries require a composite index":"Multiple filters may require a composite index"]})]})]})})]})}function wr(e,t,n,r,o,s){let a=n==="create"?`Create ${e}`:`Edit ${e} / ${r??""}`,l=n==="create"?[{label:"Repositories",href:o},{label:e,href:`${o}/${e}`},{label:"New document"}]:[{label:"Repositories",href:o},{label:e,href:`${o}/${e}`},{label:`Edit ${r??""}`}];return qe(jsx(Ue,{opts:{title:a,breadcrumb:l,basePath:o,flash:s},children:jsx("div",{class:"card bg-base-100 border border-base-300",children:jsx("div",{class:"card-body p-6",children:jsx("div",{dangerouslySetInnerHTML:{__html:t}})})})}))}xn();fr();function xr(e,t,n){let r=new URLSearchParams;for(let o of e)r.set(`fv_${o.field}`,o.value),r.set(`fo_${o.field}`,o.op);return t&&(r.set("ob",t.field),r.set("od",t.dir)),n&&r.set("ps",String(n)),r}function rs(e,t,n,r,o){let s=xr(e,r,o);return s.set("cursor",t),s.set("dir",n),`?${s.toString()}`}function Ki(e,t,n,r){let o=xr(n,void 0,r);return t?.field===e?t.dir==="asc"&&(o.set("ob",e),o.set("od","desc")):(o.set("ob",e),o.set("od","asc")),`?${o.toString()}`}function Zi(e,t,n){return `?${xr(t,n,e).toString()}`}function Rr(e,t,n,r,o,s,a=[],l=[],c=false,u=[],p,f,b,h,w,T,S,I=false,A=true){let E=`${r}/${e}`,x=`${E}/create`,d={};if(S)for(let R of n)d[R]=qt(Ut(S,R));let y=(T??[]).filter(R=>true),i=y.length>0,g=c,m=g||i,C=y.map(R=>{let P=Ut(S,R),$=qt(P),D=a.find(N=>N.name===R);return {name:R,type:$,enumValues:D?.enumValues??null,nullable:D?.nullable??false}}),k=[];return S&&(k=Se(S).filter(P=>y.includes(P.name))),qe(jsxs(Ue,{opts:{title:e,breadcrumb:[{label:"Repositories",href:r},{label:e}],basePath:r,flash:s},children:[a.length>0&&jsx(br,{action:E,columnMeta:a,activeFilters:l,isGroup:h}),b&&jsxs("div",{role:"alert",class:`alert ${b.type==="index"?"alert-warning":"alert-error"} mb-6 shadow-sm`,children:[jsx("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6 shrink-0 stroke-current",fill:"none",viewBox:"0 0 24 24",children:b.type==="index"?jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"}):jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"})}),jsxs("div",{class:"flex-1",children:[jsx("h3",{class:"font-bold",children:b.type==="index"?"Composite index required":"Query failed"}),jsx("div",{class:"text-sm",children:b.message})]}),b.indexUrl&&jsx("a",{href:b.indexUrl,target:"_blank",rel:"noopener noreferrer",class:"btn btn-sm btn-outline",children:"Create Index \u2192"})]}),jsxs("div",{class:"flex flex-wrap justify-between items-center mb-4 gap-3","data-frs-toolbar":true,children:[jsxs("div",{class:"flex items-center gap-3",children:[jsxs("span",{class:"text-sm text-base-content/60",children:[t.length,typeof w=="number"&&jsxs(Fragment,{children:[" ","of"," ",jsx("span",{class:"font-semibold text-base-content/80",children:w})]})," ","document",(typeof w=="number"?w:t.length)!==1&&"s"]}),jsxs("div",{class:"flex items-center gap-1.5 text-sm text-base-content/60",children:[jsx("span",{children:"Rows"}),jsx("div",{class:"join",children:[10,25,50,100].map(R=>jsx("a",{href:Zi(R,l,p),class:`join-item btn btn-xs ${f===R?"btn-active btn-primary":"btn-outline"}`,children:R},R))})]})]}),jsxs("div",{class:"flex gap-2",children:[A&&jsxs("div",{class:"dropdown dropdown-end","data-frs-backfill-menu":true,children:[jsxs("button",{type:"button",tabIndex:0,class:"btn btn-outline btn-sm gap-1",children:["Backfill",jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",class:"size-4 opacity-70",children:jsx("path",{"fill-rule":"evenodd",d:"M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z","clip-rule":"evenodd"})})]}),jsxs("ul",{tabIndex:0,class:"dropdown-content menu menu-sm bg-base-100 text-base-content rounded-box z-50 mt-1 w-52 p-1 shadow-lg border border-base-300",children:[jsx("li",{children:jsxs("form",{method:"post",action:`${E}/_bulk/backfill?dryRun=true`,class:"p-0 block",children:[jsx("input",{type:"hidden",name:"dryRun",value:"1"}),jsx("button",{type:"submit",class:"w-full text-left px-3 py-1.5 rounded",children:"Dry-run backfill"})]})}),jsx("li",{children:jsx("form",{method:"post",action:`${E}/_bulk/backfill`,onsubmit:"return confirm('Backfill entire repository? This will scan all documents and fill missing system keys.')",class:"p-0 block",children:jsx("button",{type:"submit",class:"w-full text-left px-3 py-1.5 rounded text-warning",children:"Run backfill"})})})]})]}),jsx("a",{href:x,class:"btn btn-primary btn-sm",children:"+ New"})]})]}),m&&jsxs("div",{class:"hidden mb-3 alert alert-info py-2 px-3","data-frs-bulk-bar":true,"data-frs-repo":e,"data-frs-total":typeof w=="number"?String(w):"","data-frs-page-size":String(f??t.length),"data-frs-allow-delete":g?"1":"0","data-frs-allow-update":i?"1":"0","data-frs-fields":JSON.stringify(C),"data-frs-filters":JSON.stringify(l),children:[jsxs("div",{class:"flex-1 text-sm",children:[jsx("span",{"data-frs-bulk-summary":true,children:"0 selected"}),typeof w=="number"&&w>t.length&&jsxs("button",{type:"button",class:"ml-3 link text-sm hidden","data-frs-bulk-select-all":true,children:["Select all ",w," matching documents"]}),jsxs("span",{class:"hidden ml-3 italic","data-frs-bulk-all-active":true,children:["All ",w??"?"," matching documents are selected."," ",jsx("button",{type:"button",class:"link","data-frs-bulk-clear":true,children:"Clear selection"})]})]}),jsxs("div",{class:"flex gap-2",children:[i&&jsx("button",{type:"button",class:"btn btn-sm btn-outline","data-frs-bulk-action":"update",children:"Update field\u2026"}),g&&jsx("button",{type:"button",class:"btn btn-sm btn-error btn-outline","data-frs-bulk-action":"delete",children:"Delete"})]})]}),jsx("div",{class:"overflow-x-auto rounded-box border border-base-300 bg-base-100","data-frs-table-wrap":true,children:jsxs("table",{class:"table table-sm w-full","data-frs-table":true,"data-frs-repo":e,"data-frs-colcount":n.length,children:[jsx("thead",{children:jsxs("tr",{class:"bg-base-200/50",children:[m&&jsx("th",{class:"w-8",children:jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-page":true,"aria-label":"Select all on this page"})}),[...n].map((R,P)=>{let $=p?.field===R,D=$?p.dir==="asc"?" \u25B2":" \u25BC":"";return jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:jsxs("a",{href:Ki(R,p,l,f),class:`hover:text-base-content inline-flex items-center gap-0.5${$?" text-primary font-bold":""}`,children:[R,D]})},P)}),u.map((R,P)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:R.column},`rel-${P}`)),jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide text-right",children:"Actions"})]})}),jsx("tbody",{children:t.length===0?jsx("tr",{children:jsx("td",{colspan:n.length+u.length+1+(m?1:0),class:"text-center py-16 text-base-content/40",children:"No documents found"})}):t.map((R,P)=>{let $=String(R.docId??R.id??""),D=`${r}/${e}/${encodeURIComponent($)}/edit`,N=`${r}/${e}/${encodeURIComponent($)}/delete`;return jsxs("tr",{class:"hover","data-frs-row-id":$,children:[m&&jsx("td",{class:"align-middle py-2",children:jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-row":true,value:$,"aria-label":`Select ${$}`})}),n.map((v,O)=>{let M=R[v],H=d[v],_=H?Lt(H,M):null;return jsx("td",{class:"align-top py-2",children:jsx(ht,{val:M,mismatch:_})},O)}),u.map((v,O)=>{let M=R[v.key];if(M==null||M==="")return jsx("td",{class:"py-2"},`rel-${O}`);let H=v.type==="one"?`${r}/${v.targetRepo}/${encodeURIComponent(String(M))}/edit`:`${r}/${v.targetRepo}?fv_${v.targetKey}=${encodeURIComponent(String(M))}`;return jsx("td",{class:"align-middle py-2",children:jsx("a",{href:H,class:"btn btn-xs btn-ghost btn-outline","data-frs-relation":true,"data-frs-rel-type":v.type,"data-frs-rel-repo":v.targetRepo,"data-frs-rel-fk":v.targetKey,"data-frs-rel-val":String(M),"data-frs-rel-label":v.column,children:v.column})},`rel-${O}`)}),jsx("td",{class:"align-middle text-right whitespace-nowrap py-2",children:jsxs("div",{class:"flex gap-1 justify-end",children:[jsx("a",{href:D,class:"btn btn-xs btn-outline",children:"Edit"}),I&&jsx("a",{href:`${r}/${e}/${encodeURIComponent($)}/history`,class:"btn btn-xs btn-outline",title:"View change history",children:"History"}),c&&jsx("form",{method:"post",action:N,onsubmit:"return confirm('Delete this document?')",children:jsx("button",{type:"submit",class:"btn btn-xs btn-error btn-outline",children:"Delete"})})]})})]},P)})})]})}),(o.hasPrev||o.hasNext)&&jsxs("div",{class:"flex flex-col items-center mt-6 gap-2",children:[jsxs("div",{class:"flex justify-center items-center gap-2",children:[o.hasPrev?jsx("a",{href:rs(l,o.prevCursor,"prev",p,f),class:"btn btn-sm btn-outline",children:"\u2190 Previous"}):jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"\u2190 Previous"}),o.hasNext?jsx("a",{href:rs(l,o.nextCursor,"next",p,f),class:"btn btn-sm btn-outline",children:"Next \u2192"}):jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"Next \u2192"})]}),typeof w=="number"&&jsxs("div",{class:"text-xs text-base-content/50",children:[w," total document",w!==1?"s":"",l.length>0?" matching filters":""]})]}),m&&i&&jsxs("dialog",{id:"frs-bulk-update-modal",class:"modal",children:[jsxs("div",{class:"modal-box",children:[jsx("h3",{class:"font-bold text-lg mb-3",children:"Bulk update field"}),jsx("p",{class:"text-sm text-base-content/60 mb-4","data-frs-bulk-update-summary":true,children:"Update one field on the selected documents."}),jsxs("form",{method:"dialog","data-frs-bulk-update-form":true,"data-frs-form":true,children:[jsxs("label",{class:"form-control w-full mb-3",children:[jsx("div",{class:"label",children:jsx("span",{class:"label-text text-xs uppercase tracking-wide",children:"Field"})}),jsxs("select",{class:"select select-bordered select-sm w-full",name:"field",required:true,"data-frs-bulk-field-select":true,children:[jsx("option",{value:"",children:"\u2014 Select a field \u2014"}),y.map(R=>jsx("option",{value:R,children:R},R))]})]}),jsx("div",{class:"mb-4","data-frs-bulk-value-container":true}),jsxs("div",{class:"modal-action",children:[jsx("button",{type:"button",class:"btn btn-sm btn-ghost","data-frs-bulk-update-cancel":true,children:"Cancel"}),jsx("button",{type:"submit",class:"btn btn-sm btn-primary","data-frs-bulk-update-submit":true,children:"Apply"})]})]})]}),jsx("form",{method:"dialog",class:"modal-backdrop",children:jsx("button",{children:"close"})})]}),jsx("div",{class:"hidden","data-frs-bulk-templates":true,children:k.map(R=>jsx("div",{"data-frs-bulk-template-for":R.name,dangerouslySetInnerHTML:{__html:jt(R)}},R.name))})]}))}function Zt(e,t){return hr(e,t)}function Sr(e,t){return gr(e,t)}function vr(e,t,n,r,o,s,a,l,c,u,p,f,b,h,w,T,S,I,A){return Rr(e,t,n,r,o,s,a,l,c,u,p,f,b,h,w,T,S,I,A)}function Ke(e,t,n,r,o,s){return wr(e,t,n,r,o,s)}async function os(e,t){if(t)try{let n=e.repo.ref,r=n?.firestore;if(t.startsWith("{"))try{let o=JSON.parse(t);if(o.docPath&&r&&typeof r.doc=="function"){let s=await r.doc(o.docPath).get();if(s.exists)return s}o.docId&&(t=o.docId);}catch{}if(t.includes("/")&&r&&typeof r.doc=="function"){let o=await r.doc(t).get();if(o.exists)return o}if(typeof n.doc=="function"){let o=await n.doc(t).get();if(o.exists)return o}}catch{}}function Sn(e,t){return Je(e,{pathKey:t.pathKey,documentKey:t.documentKey??"docId",parentKeys:t.parentKeys,documentPathTemplate:t.documentPathTemplate,isGroup:t.isGroup})}async function gt(e,t){let n=e.documentKey??"docId",r=`by${n.charAt(0).toUpperCase()}${n.slice(1)}`;if(typeof e.repo.get[r]=="function")try{let s=await e.repo.get[r](t);if(s)return s}catch{}return (await e.repo.query.by({where:[[n,"==",t]],limit:1}))[0]??null}function Tr(e,t,n){let r=e.documentKey??"docId",o=Bt(n,{ref:e.repo.ref,path:e.path,isGroup:!!e.isGroup,filters:[{field:r,op:"==",value:t}]});return o.type==="index"?{type:"warning",message:"Loading this document requires a composite index that does not exist yet.",...o.indexUrl?{action:{href:o.indexUrl,label:"Create Index \u2192",external:true}}:{}}:{type:"error",message:o.message}}function K(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function tt(e,t){e.status(302).set("Location",t).send("");}function vn(e,t){let n=t.shape,r={};for(let[o,s]of Object.entries(n)){let a=Ar(s),l=X(a),c=l==="ZodObject",u=a,p=false;if(l==="ZodUnion"){let h=Nt(a);h.some(T=>X(T)==="ZodDate")&&(p=true);let w=h.find(T=>{if(X(T)==="ZodObject"){let S=he(T);return "latitude"in S&&"longitude"in S}return false});w&&(c=true,u=w);}if(e[o+"__isnull"]==="1"){r[o]=null;continue}if(c){let h={},w=false;for(let[I,A]of Object.entries(e))I.startsWith(`${o}.`)&&(h[I.slice(o.length+1)]=A,w=true);if(w){r[o]=vn(h,u);continue}let T=e[o],S=Array.isArray(T)?T[T.length-1]:T;if(S)try{r[o]=JSON.parse(S);}catch{r[o]=S;}continue}let f=e[o],b=Array.isArray(f)?f[f.length-1]:f;if(b===void 0||b===""){l==="ZodBoolean"&&(r[o]=false);continue}if(p){r[o]=new Date(b);continue}switch(l){case "ZodBoolean":b==="__null__"?r[o]=null:r[o]=b==="true"||b==="on"||b==="1";break;case "ZodNumber":case "ZodBigInt":r[o]=Number(b);break;case "ZodDate":r[o]=new Date(b);break;case "ZodArray":try{r[o]=JSON.parse(b);}catch{r[o]=b;}break;default:if(b.startsWith("{")||b.startsWith("["))try{r[o]=JSON.parse(b);break}catch{}r[o]=b;}}return r}function ss(e){let t=null;if(e instanceof Date)t=e;else if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")t=e.toDate();else if(typeof e=="object"&&e!==null&&"_seconds"in e&&"_nanoseconds"in e)t=new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));else if(typeof e=="string"||typeof e=="number"){let r=new Date(e);isNaN(r.getTime())||(t=r);}if(!t||isNaN(t.getTime()))return null;let n=r=>String(r).padStart(2,"0");return `${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function is(e){let t=e;for(;;){let n=X(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=me(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=$t(t);if(!r)return n;t=r;}else return n}}function Ar(e){let t=e;for(;;){let n=X(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=me(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=$t(t);if(!r)return t;t=r;}else return t}}function cs(e){let t=e;for(;;){let n=X(t);if(n==="ZodOptional"||n==="ZodNullable")return true;if(n==="ZodDefault"){t=me(t);continue}return false}}function ls(e){let t=Ar(e),n=X(t);if(n==="ZodEnum"){let r=Ht(t);return r.length>0?r:void 0}if(n==="ZodNativeEnum"){let r=_t(t),o=Object.values(r).filter(s=>typeof s=="string");return o.length>0?o:void 0}if(n==="ZodLiteral"){let r=Mt(t);return typeof r=="string"?[r]:void 0}}function ds(e,t,n=""){let r={};for(let o of Object.keys(t.shape)){let s=n?`${n}.${o}`:o,a=e[o];if(a===null){r[s]="__null__";continue}if(a===void 0)continue;let l=Ar(t.shape[o]),c=X(l),u=c==="ZodObject",p=l,f=false;if(c==="ZodUnion"){let b=Nt(l);b.some(w=>X(w)==="ZodDate")&&(f=true);let h=b.find(w=>{if(X(w)==="ZodObject"){let T=he(w);return "latitude"in T&&"longitude"in T}return false});h&&(u=true,p=h);}if(u&&typeof a=="object"&&a!==null&&!Array.isArray(a)&&!("_seconds"in a)&&typeof a.toDate!="function"){let b=ds(a,p,s);Object.assign(r,b);}else if(c==="ZodDate"||f){let b=ss(a);b!==null&&(r[s]=b);}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)&&("_seconds"in a||typeof a.toDate=="function")){let b=ss(a);r[s]=b??JSON.stringify(a,null,2);}else typeof a=="object"?r[s]=JSON.stringify(a,null,2):r[s]=String(a);}return r}function Cr(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?Cr(n.nested,t):void 0}))}function Vi(e,t){let n=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),r=[];for(let[o,s]of Object.entries(e)){if(!o.startsWith("fv_"))continue;let a=o.slice(3);if(!t.has(a))continue;let l=(s??"").trim();if(!l)continue;let c=e[`fo_${a}`]??"==",u=n.has(c)?c:"==";r.push({field:a,op:u,value:l});}return r}function as(e){let t="__null__",n=r=>r===t?null:r==="true"?true:r==="false"?false:r!==""&&!isNaN(Number(r))?Number(r):r;return e.map(r=>{if(r.op==="array-contains-any"||r.op==="in"||r.op==="not-in"){let o=r.value.split(",").map(s=>s.trim()).filter(s=>s!==""&&s!==t).map(s=>n(s));return [r.field,r.op,o]}return [r.field,r.op,n(r.value)]})}function us(e,t,n=""){let r=[];for(let o of e){let s=n?`${n}.${o}`:o,a=t.shape[o];if(!a){r.push({name:s,zodType:"ZodString"});continue}let l=is(a);if(l==="ZodObject"){let c=a;for(;;){let p=X(c);if(p==="ZodOptional"||p==="ZodNullable"||p==="ZodDefault")c=me(c);else break}let u=he(c);r.push(...us(Object.keys(u),c,s));}else r.push({name:s,zodType:l,nullable:cs(a),enumValues:ls(a)});}return r}function Gi(e,t){let n=t.split("."),r=e;for(let o of n){for(;;){let a=X(r);if(a==="ZodOptional"||a==="ZodNullable"||a==="ZodDefault")r=me(r);else break}let s=he(r);if(!(o in s))return null;r=s[o];}return r}function nt(e,t){if(!t||t.length===0)return e;let n=[],r=new Map;for(let s of t){let a=s.indexOf(".");if(a===-1)n.push(s);else {let l=s.slice(0,a),c=s.slice(a+1);r.has(l)||r.set(l,[]),r.get(l).push(c);}}let o={};for(let s of n)s in e.shape&&(o[s]=e.shape[s]);for(let[s,a]of r){if(!(s in e.shape))continue;let l=e.shape[s];for(;;){let c=X(l);if(c==="ZodOptional"||c==="ZodNullable"||c==="ZodDefault")l=me(l);else break}if(X(l)!=="ZodObject"){o[s]=e.shape[s];continue}o[s]=nt(l,a);}return z$1.object(o)}function Ie(e,t,n){return Pe(e,t,n)}function ps(e,t,n){let r=new Set,o=(x,d)=>{let y=Ie(x,t,n),i=Object.values(e).map(g=>({name:g.name,path:g.path}));K(d,Sr(i,y));},s=async(x,d)=>{let y=x.params.repoName;if(!y){K(d,"Bad request",400);return}let i=e[y];if(!i){K(d,"Repository not found",404);return}let g=i.pageSize??25,m=x.query??{},C=m.cursor,k=m.dir==="prev"?"prev":"next",R=m.ob??"",P=m.od==="desc"?"desc":"asc",$=R?{field:R,dir:P}:void 0,D=parseInt(m.ps??""),N=Number.isFinite(D)&&D>0?Math.min(D,200):g,v=i.listColumns??Object.keys(i.schema.shape),O=i.documentKey??"docId",M=[O,...v.filter(oe=>oe!==O)];$&&(new Set([O,...v]).has($.field)||($=void 0));let H=i.filterableFields?(()=>{let oe=[];for(let ce of i.filterableFields)(ce.includes(".")||v.includes(ce))&&oe.push(ce);return oe})():v,_=(()=>{let oe=[];for(let ce of H)if(ce.includes(".")){let ye=Gi(i.schema,ce);oe.push({name:ce,zodType:ye?is(ye):"ZodString",nullable:ye?cs(ye):false,enumValues:ye?ls(ye):void 0});}else oe.push(...us([ce],i.schema));return oe})(),j=new Set(_.map(oe=>oe.name)),F=Vi(m,j),q=as(F),U;C&&(U=await os(i,C));let[Q,ne]=await Promise.all([i.repo.query.paginate({pageSize:N,cursor:U,direction:k,...q.length>0?{where:q}:{},...$?{orderBy:[{field:$.field,direction:$.dir}]}:{}}).catch(oe=>({queryError:Bt(oe,{ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:F,sort:$})})),i.repo.aggregate.count(q.length>0?{where:q}:{}).catch(()=>{})]),ke="queryError"in Q,ie=ke?[]:Q.data,Z=ke?"":Q.nextCursor?.ref?.path??Q.nextCursor?.id??"",V=ke?"":Q.prevCursor?.ref?.path??Q.prevCursor?.id??"",se=ke?Q.queryError:void 0,xe=Ie(x,t,n),re,we=m.flash;if(we==="created")re={type:"success",message:"Document created successfully."};else if(we==="updated")re={type:"success",message:"Document updated successfully."};else if(we==="deleted")re={type:"success",message:"Document deleted successfully."};else if(we==="backfilled"){let oe=De(m.scanned),ce=De(m.written),ye=De(m.skipped);re={type:"success",message:oe!==void 0&&ce!==void 0&&ye!==void 0?`Backfill complete: scanned ${oe}, updated ${ce}, skipped ${ye}.`:"Repository backfilled successfully."};}else if(we==="backfill_dryrun"){let oe=De(m.scanned),ce=De(m.written),ye=De(m.skipped);re={type:"success",message:oe!==void 0&&ce!==void 0&&ye!==void 0?`Dry run complete: scanned ${oe}, would update ${ce}, skipped ${ye}.`:"Dry run complete."};}else if(we==="backfill_partial"){let oe=De(m.scanned),ce=De(m.written),ye=De(m.skipped),Hn=De(m.failed),Ls=oe!==void 0&&ce!==void 0&&ye!==void 0&&Hn!==void 0;re={type:ce!==void 0&&ce>0?"warning":"error",message:Ls?`Backfill finished with ${Hn} failure${Hn===1?"":"s"} (scanned ${oe}, updated ${ce}, skipped ${ye}). Check server logs for details.`:"Backfill finished with failures. Check server logs for details."};}else we==="backfill_busy"&&(re={type:"warning",message:"A backfill is already running for this repository. Please wait for it to finish."});K(d,vr(i.name,ie,M,xe,{hasPrev:ke?false:Q.hasPrevPage,hasNext:ke?false:Q.hasNextPage,prevCursor:V,nextCursor:Z},re,_,F,i.allowDelete??false,i.relationalMeta,$,N,se,i.isGroup,ne,i.mutableFields,i.schema,i.historyEnabled,i.allowBackfill!==false));},a=(x,d)=>{let y=x.params.repoName;if(!y){K(d,"Bad request",400);return}let i=e[y];if(!i){K(d,"Repository not found",404);return}let g=Ie(x,t,n),m=nt(i.schema,i.createFields),C=Se(m),k=`${g}/${i.name}/create`,R=ze(C,k,"POST","Create document");K(d,Ke(i.name,R,"create",null,g));},l=async(x,d)=>{let y=x.params.repoName;if(!y){K(d,"Bad request",400);return}let i=e[y];if(!i){K(d,"Repository not found",404);return}let g=Ie(x,t,n),m=x.body??{},C=vn(m,i.schema),k=nt(i.schema,i.createFields),R=k.safeParse(C);if(!R.success){let P=Se(k),$=`${g}/${i.name}/create`,D=ze(P,$,"POST","Create document"),N=R.error.issues.map(v=>`${v.path.join(".")}: ${v.message}`).join(", ");K(d,Ke(i.name,D,"create",null,g,{type:"error",message:`Validation error: ${N}`}),422);return}try{if(i.isGroup&&i.parentKeys&&i.parentKeys.length>0){let P={...R.data},$=i.parentKeys.filter(D=>P[D]===void 0||P[D]===null||typeof P[D]=="string"&&P[D].trim()==="");if($.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${$.join(", ")}`);if(typeof i.repo.create=="function")await i.repo.create(P);else {let D=i.parentKeys.map(O=>String(P[O])),N=i.documentKey??"docId",v=P[N]||Be();await i.repo.set(...D,v,P);}}else await i.repo.create(R.data);tt(d,`${g}/${i.name}?flash=created`);}catch(P){let $=nt(i.schema,i.createFields),D=Se($),N=`${g}/${i.name}/create`,v=ze(D,N,"POST","Create document");K(d,Ke(i.name,v,"create",null,g,{type:"error",message:`Save error: ${P.message}`}),500);}},c=async(x,d)=>{let y=x.params.repoName,i=x.params.id;if(!y||!i){K(d,"Bad request",400);return}let g=e[y];if(!g){K(d,"Repository not found",404);return}let m=Ie(x,t,n),C=null;try{C=await gt(g,i);}catch(N){let v=Tr(g,i,N),O=Xe(N)?424:500;K(d,Zt("",{title:`Edit ${g.name} / ${i}`,basePath:m,breadcrumb:[{label:"Repositories",href:m},{label:g.name,href:`${m}/${g.name}`},{label:`Edit ${i}`}],flash:v}),O);return}if(!C){K(d,"Document not found",404);return}let k=ds(C,g.schema),R=nt(g.schema,g.mutableFields),P=Cr(Se(R),k),$=`${m}/${g.name}/${encodeURIComponent(i)}/edit`,D=ze(P,$,"POST","Save changes");K(d,Ke(g.name,D,"edit",i,m));},u=async(x,d)=>{let y=x.params.repoName,i=x.params.id;if(!y||!i){K(d,"Bad request",400);return}let g=e[y];if(!g){K(d,"Repository not found",404);return}let m=Ie(x,t,n),C=x.body??{},k=vn(C,g.schema),R=nt(g.schema,g.mutableFields),$=R.partial().safeParse(k);if(!$.success){let D=Object.fromEntries(Object.entries(C).map(([H,_])=>[H,Array.isArray(_)?_.join(","):_??""])),N=Cr(Se(R),D),v=`${m}/${g.name}/${encodeURIComponent(i)}/edit`,O=ze(N,v,"POST","Save changes"),M=$.error.issues.map(H=>`${H.path.join(".")}: ${H.message}`).join(", ");K(d,Ke(g.name,O,"edit",i,m,{type:"error",message:`Validation error: ${M}`}),422);return}try{let D=await gt(g,i),N=(D&&Sn(D,g))??[i];await g.repo.update(...N,$.data),tt(d,`${m}/${g.name}?flash=updated`);}catch(D){let N=nt(g.schema,g.mutableFields),v=Se(N),O=`${m}/${g.name}/${encodeURIComponent(i)}/edit`,M=ze(v,O,"POST","Save changes"),H=Xe(D)?Tr(g,i,D):{type:"error",message:`Save error: ${D.message}`},_=Xe(D)?424:500;K(d,Ke(g.name,M,"edit",i,m,H),_);}},p=async(x,d)=>{let y=x.params.repoName,i=x.params.id;if(!y||!i){K(d,"Bad request",400);return}let g=e[y];if(!g){K(d,"Repository not found",404);return}if(!g.allowDelete){K(d,"Delete is not allowed for this repository",403);return}let m=Ie(x,t,n);try{let C=await gt(g,i),k=(C&&Sn(C,g))??[i];await g.repo.delete(...k),tt(d,`${m}/${g.name}?flash=deleted`);}catch(C){let k=Xe(C)?Tr(g,i,C):{type:"error",message:`Delete error: ${C.message}`},R=Xe(C)?424:500;K(d,Zt("",{title:`Delete ${g.name} / ${i}`,basePath:m,breadcrumb:[{label:"Repositories",href:m},{label:g.name,href:`${m}/${g.name}`},{label:`Delete ${i}`}],flash:k}),R);}},f=async(x,d)=>{let y=x.params.repoName;if(!y){K(d,"Bad request",400);return}let i=e[y];if(!i){K(d,"Repository not found",404);return}let g=Ie(x,t,n),m=x.query,C=m?.type==="many"?"many":"one",k=Math.max(1,Math.min(100,Number(m?.ps??25)||25)),R=i.listColumns??Object.keys(he(i.schema)),{PanelOne:P,PanelMany:$}=await Promise.resolve().then(()=>(mr(),es)),{renderToString:D}=await import('hono/jsx/dom/server');if(C==="one"){let _=String(m?.id??"");if(!_){K(d,"<div class='p-6 text-error'>Missing id parameter.</div>",400);return}try{let j=await gt(i,_),F=D(P({doc:j,repoName:i.name,basePath:g,schema:i.schema,columns:R}));K(d,F);}catch(j){K(d,`<div class='p-6 text-error text-sm'>Error: ${j.message}</div>`,500);}return}let N=String(m?.fk??""),v=String(m?.fv??"");if(!N||!v){K(d,"<div class='p-6 text-error'>Missing fk/fv parameters.</div>",400);return}let O=m?.cursor??"",M=m?.dir==="prev"?"prev":"next",H;O&&(H=await os(i,O));try{let _=await i.repo.query.paginate({pageSize:k,cursor:H,direction:M,where:[[N,"==",ec(v)]]}),j=D($({docs:_.data,repoName:i.name,basePath:g,fk:N,fv:v,columns:R,schema:i.schema,pagination:{hasPrev:_.hasPrevPage,hasNext:_.hasNextPage,prevCursor:_.prevCursor?.ref?.path??_.prevCursor?.id??"",nextCursor:_.nextCursor?.ref?.path??_.nextCursor?.id??"",pageSize:k}}));K(d,j);}catch(_){K(d,`<div class='p-6 text-error text-sm'>Error: ${_.message}</div>`,500);}},b=async(x,d)=>{let y=Yi(x),i=x.params.repoName;if(!i){y?ae(d,{error:"Bad request"},400):K(d,"Bad request",400);return}let g=e[i];if(!g){y?ae(d,{error:"Repository not found"},404):K(d,"Repository not found",404);return}if(g.allowBackfill===false){let k="Backfill is not allowed for this repository";y?ae(d,{error:k},403):K(d,k,403);return}let m=Ie(x,t,n);if(r.has(i)){y?ae(d,{error:`Backfill is already running for "${i}"`},409):tt(d,`${m}/${g.name}?flash=backfill_busy`);return}let C=Xi(x);r.add(i);try{let k=await g.repo.system.backfillKeys({dryRun:C}),R=k?.scanned??0,P=k?.written??0,$=k?.skipped??0,D=Array.isArray(k?.failures)?k.failures:[];if(D.length>0&&console.error(`[admin] Backfill for "${i}" finished with ${D.length} failure(s) (scanned=${R}, written=${P}, skipped=${$}):`,D.map(v=>({path:v.path,error:kr(v.error)}))),y){let v=D.length===0?200:P>0?207:500;ae(d,{dryRun:C,scanned:R,written:P,skipped:$,failures:D.map(O=>({path:O.path,error:kr(O.error)}))},v);return}let N=new URLSearchParams({scanned:String(R),written:String(P),skipped:String($)});D.length>0?(N.set("failed",String(D.length)),tt(d,`${m}/${g.name}?flash=backfill_partial&${N.toString()}`)):C?tt(d,`${m}/${g.name}?flash=backfill_dryrun&${N.toString()}`):tt(d,`${m}/${g.name}?flash=backfilled&${N.toString()}`);}catch(k){let R=kr(k);console.error(`[admin] Backfill failed for "${i}":`,k),y?ae(d,{error:R},500):K(d,`<div class="p-6 text-error">Backfill failed: ${Ji(R)}</div>`,500);}finally{r.delete(i);}},h=async(x,d)=>{let y=[];for(let i of d){let g;if(x.isGroup||x.parentKeys?.length){let m=await gt(x,i);g=m?Sn(m,x):void 0;}g||(g=[i]);try{let m=x.repo.documentRef(...g);m&&y.push(m);}catch{}}return y},w=async(x,d)=>{let y=as(d),i=x.documentKey??"docId",g=[],m;for(;;){let C=await x.repo.query.paginate({pageSize:500,cursor:m,direction:"next",...y.length>0?{where:y}:{}});for(let k of C.data){let R=String(k[i]??k.id??"");R&&g.push(R);}if(!C.hasNextPage||!C.nextCursor)break;m=C.nextCursor;}return g},T=async(x,d)=>{let y=x.params.repoName;if(!y){ae(d,{error:"Bad request"},400);return}let i=e[y];if(!i){ae(d,{error:"Repository not found"},404);return}if(!i.allowDelete){ae(d,{error:"Delete is not allowed for this repository"},403);return}let g=x.body??{};try{let m=await I(i,g);if(m.length===0){ae(d,{deleted:0});return}let C=await h(i,m);for(let k=0;k<C.length;k+=500)await i.repo.bulk.delete(C.slice(k,k+500));ae(d,{deleted:C.length});}catch(m){ae(d,{error:m.message},500);}},S=async(x,d)=>{let y=x.params.repoName;if(!y){ae(d,{error:"Bad request"},400);return}let i=e[y];if(!i){ae(d,{error:"Repository not found"},404);return}let g=x.body??{},m=String(g.field??"");if(!m){ae(d,{error:"Missing 'field'"},400);return}if(!i.mutableFields||!i.mutableFields.includes(m)){ae(d,{error:`Field '${m}' is not bulk-updatable`},403);return}let C=i.schema.shape?.[m],k;if(C){let R=typeof i.schema=="object"&&i.schema&&"constructor"in i.schema&&i.schema.constructor.name.includes("Zod")?i.schema.pick({[m]:true}):void 0;if(!R){ae(d,{error:"Invalid schema structure"},500);return}k=vn(g.formPayload??{},R)[m];let $=C.safeParse(k);if(!$.success){ae(d,{error:`Invalid value for '${m}': ${$.error.message}`},400);return}k=$.data;}try{let R=await I(i,g);if(R.length===0){ae(d,{updated:0});return}let $=(await h(i,R)).map(D=>({docRef:D,data:{[m]:k}}));for(let D=0;D<$.length;D+=500)await i.repo.bulk.update($.slice(D,D+500));ae(d,{updated:$.length});}catch(R){ae(d,{error:R.message},500);}};async function I(x,d){if(d.selectAll){let y=A(d.filters,x);return await w(x,y)}return Array.isArray(d.ids)?d.ids.filter(y=>typeof y=="string"&&!!y):[]}function A(x,d){if(!Array.isArray(x))return [];let y=new Set((d.filterableFields??Object.keys(he(d.schema))).map(m=>String(m))),i=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),g=[];for(let m of x)m&&typeof m=="object"&&typeof m.field=="string"&&y.has(m.field)&&typeof m.value=="string"&&i.has(String(m.op))&&g.push({field:m.field,op:m.op,value:m.value});return g}return {handleDashboard:o,handleList:s,handleCreateForm:a,handleCreateSubmit:l,handleEditForm:c,handleEditSubmit:u,handleDelete:p,handlePanel:f,handleBulkDelete:T,handleBulkUpdate:S,handleBulkBackfill:b,handleHistory:async(x,d)=>{let y=x.params.repoName,i=x.params.id;if(!y||!i){K(d,"Bad request",400);return}let g=e[y];if(!g){K(d,"Repository not found",404);return}if(!g.historyEnabled||!g.repo.history){K(d,"History not enabled for this repository",404);return}let m=Ie(x,t,n),C=g.historySubcollection??"history",k=[i];try{let _=await gt(g,i),j=_?Sn(_,g):void 0;j&&j.length>0&&(k=j);}catch{}let R=parseInt(String(x.query?.limit??"")),P=Number.isFinite(R)&&R>0?Math.min(R,500):100,$=[],D;try{$=await g.repo.history.list(...k,{limit:P});}catch(_){D=_.message;}let N=_=>String(_??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),v=_=>{if(_===void 0)return '<span class="opacity-40">undefined</span>';if(_===null)return '<span class="opacity-40">null</span>';if(typeof _=="object")try{return `<code class="text-xs">${N(JSON.stringify(_))}</code>`}catch{return N(String(_))}return N(String(_))},O=_=>_?typeof _.toDate=="function"?_.toDate().toISOString():_ instanceof Date?_.toISOString():N(String(_)):"",M=_=>`<span class="badge badge-sm ${_==="create"?"badge-success":_==="delete"?"badge-error":_==="custom"?"badge-secondary":"badge-info"}">${N(_)}</span>`,H="";if(H+='<div class="flex items-center justify-between mb-4">',H+=`<a href="${m}/${g.name}/${encodeURIComponent(i)}/edit" class="btn btn-sm btn-outline">\u2190 Back to edit</a>`,H+=`<a href="${m}/${g.name}" class="btn btn-sm btn-outline">\u2190 Back to list</a>`,H+="</div>",H+=`<p class="text-sm text-base-content/60 mb-4">Subcollection: <code>${N(C)}</code> \xB7 Showing up to ${P} entries.</p>`,D)H+=`<div class="alert alert-error mb-4">${N(D)}</div>`;else if($.length===0)H+='<div class="alert">No history entries found.</div>';else {H+='<div class="overflow-x-auto"><table class="table table-zebra table-sm">',H+="<thead><tr><th>When</th><th>Op</th><th>User</th><th>Reason / Comment</th><th>Changes</th></tr></thead><tbody>";for(let _ of $){let j=_.meta??{},F=[j.reason,j.comment].filter(Q=>Q!=null&&Q!=="").map(Q=>N(String(Q))).join(" \u2014 "),q="",U=Object.keys(_.changes??{});if(_.custom){let Q=`<strong>${N(_.custom.title)}</strong>`,ne=_.custom.key?` <code class="text-xs opacity-60">${N(_.custom.key)}</code>`:"",ke=_.custom.description?`<div class="text-xs opacity-80 mt-0.5">${N(_.custom.description)}</div>`:"";q=`<div>${Q}${ne}${ke}</div>`;}else U.length===0?q='<span class="opacity-40">\u2014</span>':q='<ul class="space-y-1">'+U.map(Q=>{let ne=_.changes[Q];return `<li><strong>${N(Q)}</strong>: ${v(ne.oldValue)} \u2192 ${v(ne.newValue)}</li>`}).join("")+"</ul>";H+="<tr>",H+=`<td class="whitespace-nowrap text-xs font-mono">${N(O(_.historySetAt))}</td>`,H+=`<td>${M(_.operation??"update")}</td>`,H+=`<td class="text-xs">${N(j.userEmail??j.userId??"")}</td>`,H+=`<td class="text-xs">${F}</td>`,H+=`<td>${q}</td>`,H+="</tr>";}H+="</tbody></table></div>";}K(d,Zt(H,{title:`History \u2014 ${g.name} / ${i}`,basePath:m,breadcrumb:[{label:"Repositories",href:m},{label:g.name,href:`${m}/${g.name}`},{label:`History ${i}`}]}));}}}function ae(e,t,n=200){e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(t));}function Ji(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function kr(e){return e instanceof Error||e&&typeof e=="object"&&typeof e.message=="string"?e.message:String(e)}function Yi(e){let t=e.headers??{},n="",r="";for(let[o,s]of Object.entries(t)){let a=o.toLowerCase(),l=Array.isArray(s)?s.join(","):String(s??"");a==="accept"?n=l.toLowerCase():a==="content-type"&&(r=l.toLowerCase());}return n.includes("application/json")||r.includes("application/json")}function bt(e){if(e===true||e===1)return true;if(typeof e=="string"){let t=e.trim().toLowerCase();return t==="true"||t==="1"}return Array.isArray(e)&&e.length>0?bt(e[e.length-1]):false}function Xi(e){let t=e.query??{};if(t.dryRun!==void 0)return bt(t.dryRun);if(typeof e.url=="string"){let r=e.url.indexOf("?");if(r!==-1){let s=new URLSearchParams(e.url.slice(r+1)).get("dryRun");if(s!==null)return bt(s)}}let n=e.body;if(n&&typeof n=="object"&&!Array.isArray(n)){let r=n.dryRun;if(r!==void 0)return bt(r)}else if(typeof n=="string"&&n.trim()!==""){let r=n.trim();if(r.startsWith("{"))try{let o=JSON.parse(r);if(o&&typeof o=="object"&&!Array.isArray(o)){let s=o.dryRun;if(s!==void 0)return bt(s)}}catch{}else {let s=new URLSearchParams(r).get("dryRun");if(s!==null)return bt(s)}}return false}function De(e){if(e===void 0||e==="")return;let t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function ec(e){return e==="true"?true:e==="false"?false:e!==""&&!isNaN(Number(e))?Number(e):e}kn();async function hs(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function tc(e){let t={};if(!e)return t;for(let n of e.split("&")){let r=n.indexOf("=");if(r===-1)continue;let o=decodeURIComponent(n.slice(0,r).replace(/\+/g," ")),s=decodeURIComponent(n.slice(r+1).replace(/\+/g," ")),a=t[o];a===void 0?t[o]=s:Array.isArray(a)?a.push(s):t[o]=[a,s];}return t}function gs(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,auth:s,middleware:a=[],httpsOptions:l}=e,c=t==="/"?"":t.replace(/\/$/,""),u={};for(let[h,w]of Object.entries(n)){if(!w.repo)throw new Error(`[createAdminServer] Repository "${h}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let T=w.schema??w.repo.schema??null;if(!T)throw new Error(`[createAdminServer] Repository "${h}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let S,I,A;if(w.fieldsConfig){let d=w.fieldsConfig;S=[],I=[],A=[];for(let[y,i]of Object.entries(d))for(let g of i)g==="filterable"?S.push(y):g==="mutable"?I.push(y):g==="create"&&A.push(y);S.length===0&&(S=void 0),I.length===0&&(I=void 0),A.length===0&&(A=void 0);}let E=(()=>{let d=w.repo._parentKeys;return d&&d.length>0?d:void 0})();if(E&&A)for(let d of E)A.includes(d)||A.push(d);let x={name:h,path:w.path,repo:w.repo,schema:T,documentKey:w.documentKey??"docId",pathKey:w.repo._pathKey??void 0,isGroup:!!w.repo._isGroup,parentKeys:E,documentPathTemplate:w.repo._documentPathTemplate??void 0,createdKey:w.repo._createdKey??void 0,listColumns:w.listColumns,pageSize:w.pageSize,filterableFields:S,mutableFields:I,createFields:A,allowDelete:w.allowDelete??false,allowBackfill:w.allowBackfill??true,historyEnabled:!!w.repo._historyConfig?.enabled,historySubcollection:(w.repo._historyConfig?.enabled&&w.repo._historySubcollection)??void 0,relationalMeta:(()=>{if(!w.relationalFields||w.relationalFields.length===0)return;let d=w.repo.relationalKeys??{},y=[];for(let i of w.relationalFields){let g=d[i.key];g&&y.push({key:g.sourceKey?String(g.sourceKey):i.key,column:i.column,targetRepo:String(g.repo),targetKey:String(g.key),type:g.type});}return y.length>0?y:void 0})()};u[h]=x;}let p=ps(u,c,un(l?.region)),f=new Me;if(o!==false&&f.use(Tn(o===void 0?{}:o)),r&&f.use(async(h,w,T)=>{let S=h,I="";if(S.headers){for(let[A,E]of Object.entries(S.headers))if(A.toLowerCase()==="content-type"){I=(Array.isArray(E)?E.join(","):String(E??"")).toLowerCase();break}}if(I.includes("application/x-www-form-urlencoded")){let A=await hs(S)||(typeof S.body=="string"?S.body:"");(A!==""||!S.body||typeof S.body!="object")&&(h.body=tc(A));}else if(I.includes("application/json")){let A=typeof S.body=="string"?S.body:S.body===void 0?await hs(S):"";if(A)try{h.body=JSON.parse(A);}catch{}}await T();}),s)if(Pt(s)){for(let h of s.routes){let w=`${c}${h.path}`;h.method==="GET"?f.get(w,h.handler):f.post(w,h.handler);}f.use(s.middleware);}else if(typeof s=="function")f.use(s);else {let h=s.realm??"Admin",w="Basic "+Buffer.from(`${s.username}:${s.password}`).toString("base64");f.use((T,S,I)=>{if((T.headers?.authorization??"")!==w){S.status(401).set("WWW-Authenticate",`Basic realm="${h}"`).set("Content-Type","text/plain").send("Unauthorized");return}I();});}for(let h of a)f.use(h);f.get(`${c}/`,p.handleDashboard),f.get(`${c}`,p.handleDashboard),f.get(`${c}/:repoName/_panel`,p.handlePanel),f.post(`${c}/:repoName/_bulk/delete`,p.handleBulkDelete),f.post(`${c}/:repoName/_bulk/update`,p.handleBulkUpdate),f.post(`${c}/:repoName/_bulk/backfill`,p.handleBulkBackfill),f.get(`${c}/:repoName`,p.handleList),f.get(`${c}/:repoName/create`,p.handleCreateForm),f.post(`${c}/:repoName/create`,p.handleCreateSubmit),f.get(`${c}/:repoName/:id/edit`,p.handleEditForm),f.post(`${c}/:repoName/:id/edit`,p.handleEditSubmit),f.get(`${c}/:repoName/:id/history`,p.handleHistory),f.post(`${c}/:repoName/:id/delete`,p.handleDelete);let b=async(h,w)=>{await f.handle(h,w);};return l&&(b.httpsOptions=l),b}ft();function Te(e,t){let n=e||{},r={},o={...n};for(let[s,a]of Object.entries(t||{})){let l=n[s];At(l,a)||(r[s]=a,o[s]=a);}return {before:n,after:o,changes:r}}function Or(e){return e}async function Cn(e,t,n){let r=e.changes||{};for(let o of Object.keys(r)){let s=t[o];if(s&&s.length>0){for(let a of s)if(await a.rule({diff:e,key:o,user:n,authenticatedUser:n})===false)return {allowed:false,reason:a.description}}}return {allowed:true}}function Pr(e){return async t=>Cn(t.diff,e,t.user)}var Ir=1e3;function bs(e,t){if(e===void 0)return {success:true,value:Math.min(Math.max(1,t),Ir)};let n=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN;return !Number.isInteger(n)||n<=0||n>Ir?{success:false,error:`Invalid pageSize: must be an integer between 1 and ${Ir}`}:{success:true,value:n}}function _r(e,t,n=200){let r=le(t);return e.json(r,n)}function rt(e,t,n,r=200){return _r(e,{success:true,data:t,meta:n},r)}function z(e,t,n=400){return _r(e,{success:false,error:t},n)}async function $r(e,t,n,r,o,s){let a=Bt(t,n);if(a.type==="index"&&a.indexUrl&&o)try{let l=o({indexUrl:a.indexUrl,repoName:n.repoName??"",path:n.path,isGroup:n.isGroup,filters:n.filters,sort:n.sort,error:t,c:e,...s?{nonFatal:!0}:{}});l instanceof Promise&&await l;}catch(l){r&&console.error("[crudServer] Error in indexesError callback:",l);}return a}async function Dr(e,t,n,r,o,s){let a=await $r(e,t,n,o,s),l=a.type==="index",c=l?424:500,p={success:false,error:l?a.message:o&&t instanceof Error?t.message:r};return l&&(p.errorType="index",a.indexUrl&&(p.indexUrl=a.indexUrl)),_r(e,p,c)}function ot(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return z$1.preprocess(r=>zn(r)??r,e);if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[s,a]of Object.entries(r))o[s]=ot(a);return z$1.object(o)}if(n==="ZodArray"||n==="array"){let r=t.element??t.type;if(r)return z$1.array(ot(r))}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(r)return ot(r).optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(r)return ot(r).nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType,o=t.defaultValue;if(r){let s=ot(r);return typeof o=="function"?s.default(o()):s.default(o)}}return e}function nc(e,t,n=[]){let r=e.shape,o={},s=t&&t.length>0?t:Object.keys(r);for(let a of s){if(n.includes(a))continue;let l=a.split(".")[0];l&&r[l]&&(o[l]=r[l]);}return z$1.object(o)}function Hr(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function Rs(e,t){let n=t.split("."),r=Hr(e);for(let o=0;o<n.length;o++){let s=n[o];if(!s)continue;let a=r?.shape;if(!a||!a[s])return;let l=a[s];if(o===n.length-1)return l;r=Hr(l);}return r}function st(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type;if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[s,a]of Object.entries(r))o[s]=st(a);return z$1.object(o).partial()}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(!r)return e;let o=st(r);return o===r?e:o.optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(!r)return e;let o=st(r);return o===r?e:o.nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType;return r?st(r).optional():e}if(n==="ZodUnion"||n==="union"){let r=t.options;if(!r||r.length<2)return e;let o=r.map(a=>st(a));return o.some((a,l)=>a!==r[l])?z$1.union(o):e}return e}function An(e,t,n,r=false,o=[]){if(typeof t!="object"||t===null||Array.isArray(t))return {success:false,error:"Data payload must be an object"};try{let s=t,a={},l={};for(let[c,u]of Object.entries(s))if(c.includes(".")){let p=c.split(".")[0];if(o.includes(c)||o.includes(p))continue;if(n&&n.length>0&&!n.includes(c)&&!n.includes(p))return {success:!1,error:`Field '${c}' is not allowed for this operation`};let f=Rs(e,c);if(!f)return {success:!1,error:`Field '${c}' does not exist in schema`};let b=r?st(f):f,w=(nn()==="normalize"?ot(b):b).parse(u);a[c]=w;}else l[c]=u;if(Object.keys(l).length>0||Object.keys(a).length===0){let c=nc(e,n,o),u=r?st(c):c,f=(nn()==="normalize"?ot(u):u).parse(l);Object.assign(a,f);}return {success:!0,data:a}}catch(s){return s instanceof z$1.ZodError?{success:false,error:`Validation failed: ${s.issues.map(l=>`${l.path.join(".")}: ${l.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}var Ss={eq:"==","==":"==",ne:"!=","!=":"!=",lt:"<","<":"<",lte:"<=","<=":"<=",gt:">",">":">",gte:">=",">=":">=",in:"in",nin:"not-in","not-in":"not-in",not_in:"not-in",contains:"array-contains","array-contains":"array-contains",array_contains:"array-contains",arrayContains:"array-contains",containsAny:"array-contains-any","array-contains-any":"array-contains-any",array_contains_any:"array-contains-any",arrayContainsAny:"array-contains-any"};function Wt(e){return Ss[e]??e}function rc(e){return e in Ss}function En(e,t,n,r){let o=Rs(e,t);if(!o||typeof o.safeParse!="function")return {success:true,data:n};let s=r?Wt(r):void 0,a=Hr(o),l=pn(a);if(s==="array-contains"){let p=l??o;if(typeof p.safeParse=="function"){let f=p.safeParse(n);return f.success?{success:true,data:f.data}:{success:false,error:f.error.issues.map(h=>h.message).join(", ")}}return {success:true,data:n}}if(s==="array-contains-any"){if(!Array.isArray(n))return {success:false,error:"Expected array value for array-contains-any"};let p=l??o,f=[];for(let b of n)if(typeof p.safeParse=="function"){let h=p.safeParse(b);if(h.success)f.push(h.data);else return {success:false,error:h.error.issues.map(T=>T.message).join(", ")}}else f.push(b);return {success:true,data:f}}let c=o.safeParse(n);if(c.success)return {success:true,data:c.data};if(Array.isArray(n)){let p=l??o,f=[];for(let b of n)if(typeof p.safeParse=="function"){let h=p.safeParse(b);if(h.success)f.push(h.data);else return {success:false,error:h.error.issues.map(T=>T.message).join(", ")}}else f.push(b);return {success:true,data:f}}return {success:false,error:c.error.issues.map(p=>p.message).join(", ")}}function oc(e,t){let n=[],r=t?new Set(t):null;for(let[o,s]of Object.entries(e)){if(s===void 0||["cursor","direction","limit","pageSize","orderBy","orderDir","select","includes","withTotal"].includes(o))continue;let a=Array.isArray(s)?s[0]:s;if(a===void 0||a==="")continue;let l=o.lastIndexOf("__"),c,u="==";if(l!==-1){let f=o.slice(0,l),b=o.slice(l+2);rc(b)?(c=f,u=Wt(b)):(c=o,u="==");}else c=o;if(r&&!r.has(c))continue;let p=a;u==="in"||u==="not-in"||u==="array-contains-any"?p=a.split(",").map(f=>ws(f.trim())):p=ws(a),n.push({field:c,op:u,value:p});}return n}function ws(e){if(e==="true")return true;if(e==="false")return false;if(e==="null"||e==="__null__")return null;let t=Number(e);return !isNaN(t)&&e!==""?t:e}function On(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function xs(e,t){if(!t)return;let n;if(typeof t=="string")try{n=JSON.parse(t);}catch{n=t.includes("/")?{docPath:t}:{docId:t};}else typeof t=="object"&&(n=t);if(!n)return;let r=typeof n.docPath=="string"?n.docPath:void 0,o=typeof n.docId=="string"?n.docId:void 0;try{let s=e.repo.ref,a=s?.firestore;if(r&&a&&typeof a.doc=="function"){let l=await a.doc(r).get();if(l.exists)return l}if(o&&o.includes("/")&&a&&typeof a.doc=="function"){let l=await a.doc(o).get();if(l.exists)return l}if(o&&typeof s.doc=="function"){let l=await s.doc(o).get();if(l.exists)return l}return}catch{return}}function Pn(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t={},n=0;for(let[r,o]of Object.entries(e))o!==void 0&&(t[r]=o,n++);return n>0?t:null}function vs(e,t,n,r,o){async function s(x,d,y,i){let g=false;if(x.hooks?.onAfterError){g=true;try{let m=x.hooks.onAfterError(i,y.hook);m instanceof Promise&&await m;}catch(m){console.error("[crudServer] Error in hooks.onAfterError callback:",m);}}if(o){g=true;try{let m=o({...y,error:i});m instanceof Promise&&await m;}catch(m){console.error("[crudServer] Error in onHookError callback:",m);}}if(!g){if(d&&typeof d.error=="function"){d.error(i,{hook:y.hook,repoName:y.repoName,path:y.path,...y.id!==void 0?{id:y.id}:{},...y.pathArgs!==void 0?{pathArgs:y.pathArgs}:{}});return}console.error(`[crudServer] Hook "${y.hook}" failed on repo "${y.repoName}":`,{hook:y.hook,repoName:y.repoName,path:y.path,...y.id!==void 0?{id:y.id}:{},...y.pathArgs!==void 0?{pathArgs:y.pathArgs}:{},error:i});}}async function a(x,d,y,i){if(!d.rules)return {allowed:true};let g=d.rules?.[y];if(!g)return {allowed:false,errorResponse:z(x,`Operation "${y}" is not allowed for this repository`,403)};try{let m=await g(i);return m===!1?{allowed:!1,errorResponse:z(x,"Forbidden",403)}:typeof m=="string"?{allowed:!1,errorResponse:z(x,m,403)}:typeof m=="object"&&m!==null&&!m.allowed?{allowed:!1,errorResponse:z(x,m.reason||"Forbidden",403)}:{allowed:!0}}catch(m){let C=n&&m instanceof Error?m.message:"Forbidden";return {allowed:false,errorResponse:z(x,C,403)}}}async function l(x,d,y,i){if(!x.rules)return i;let g=x.rules?.filter;if(!g)return i;let m=[];for(let C of i)try{await g({user:d,doc:C,params:y})&&m.push(C);}catch{}return m}function c(x){return x.get("user")??x.get("docsUser")??null}function u(x,d){if(!x){let y=d.req.path.split("/");for(let i of y)if(e[i]){x=i;break}}return !x||!e[x]?null:e[x]??null}function p(x,d){return Je(x,{pathKey:d.pathKey,documentKey:d.documentKey,parentKeys:d.parentKeys,documentPathTemplate:d.documentPathTemplate,isGroup:d.isGroup})}async function f(x,d){let y=`by${x.documentKey.charAt(0).toUpperCase()}${x.documentKey.slice(1)}`,i=x.repo.get[y];if(typeof i=="function")try{let m=await i(d);if(m)return m}catch{}return (await x.repo.query.by({where:[[x.documentKey,"==",d]],limit:1}))[0]??null}async function b(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return z(d,"Repository not found",404);let g=c(d),m=await a(d,i,"list",{user:g,query:d.req.query(),params:y});if(!m.allowed)return m.errorResponse;let C=[],k;try{let R=d.req.query(),P=bs(R.pageSize,i.pageSize);if(!P.success)return z(d,P.error,400);let $=P.value,D=R.cursor,N=R.direction?.toLowerCase()==="prev"?"prev":"next",v=R.orderBy,O=R.orderDir?.toLowerCase()==="desc"?"desc":"asc",M=R.select,H=M?M.split(",").map(Z=>Z.trim()):void 0,_=R.withTotal,j=_==="true"||_==="1"||_===!0,F;i.allowedIncludes&&R.includes&&(F=(typeof R.includes=="string"?R.includes.split(",").map(V=>V.trim()):Array.isArray(R.includes)?R.includes:[]).filter(V=>typeof V=="string"&&i.allowedIncludes.includes(V)),F?.length===0&&(F=void 0));let q=oc(R,i.filterableFields);C=q.map(Z=>({field:Z.field,op:Z.op,value:String(Z.value??"")})),v&&(k={field:v,dir:O});let U={pageSize:$,direction:N,...j?{withTotal:!0}:{}};if(D)try{let Z=typeof D=="string"?JSON.parse(D):D;U.cursor=await xs(i,Z);}catch{}if(v){if(i.orderableFields&&!i.orderableFields.includes(v))return z(d,`Field not orderable: ${v}`,400);U.orderBy=[{field:v,direction:O}];}if(q.length>0){U.where=[];for(let Z of q){let V=En(i.schema,Z.field,Z.value,Z.op);if(!V.success)return z(d,`Invalid filter value for '${Z.field}': ${V.error}`,400);U.where.push([Z.field,Z.op,V.data]);}}H&&(U.select=H),F&&(U.include=F);let Q;j&&r&&(U.onCountIndexError=Z=>{Q=Z;});let ne=await i.repo.query.paginate(U);Q!==void 0&&r&&await $r(d,Q,{repoName:y.repoName||i.name,ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:C},n,r,!0);let ie={items:await l(i,c(d),y,ne.data),hasNextPage:ne.hasNextPage,hasPrevPage:ne.hasPrevPage,nextCursor:On(ne.nextCursor),prevCursor:On(ne.prevCursor),...ne.totalCount!==void 0?{totalCount:ne.totalCount,totalCountIsExact:ne.totalCountIsExact}:{}};return rt(d,ie,{pageSize:$,hasMore:ne.hasNextPage,...ne.totalCount!==void 0?{totalCount:ne.totalCount,totalCountIsExact:ne.totalCountIsExact}:{}})}catch(R){return await Dr(d,R,{repoName:y.repoName||i.name,ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:C,sort:k},"Failed to fetch documents",n,r)}}async function h(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return z(d,"Repository not found",404);let g=c(d),m=await a(d,i,"list",{user:g,query:x.input||{},params:y});if(!m.allowed)return m.errorResponse;let C=[],k;try{let R=x.input||{},P=bs(R.pageSize,i.pageSize);if(!P.success)return z(d,P.error,400);let $=P.value,D=R.direction==="prev"?"prev":"next";R.where&&(C=R.where.map(j=>({field:String(j[0]),op:j[1],value:String(j[2]??"")}))),R.orderBy&&R.orderBy[0]&&(k={field:R.orderBy[0].field,dir:R.orderBy[0].direction==="desc"?"desc":"asc"});let N=R.withTotal===!0||String(R.withTotal)==="true",v={pageSize:$,direction:D,...N?{withTotal:!0}:{}};if(R.cursor)try{let j=typeof R.cursor=="string"?JSON.parse(R.cursor):R.cursor;v.cursor=await xs(i,j);}catch{}if(i.allowedIncludes&&R.includes&&R.includes.length>0){let j=R.includes.filter(F=>typeof F=="string"?i.allowedIncludes.includes(F):typeof F=="object"&&F!==null&&"relation"in F&&typeof F.relation=="string"?i.allowedIncludes.includes(F.relation):!1);j.length>0&&(v.include=j);}if(R.where&&R.where.length>0){if(i.filterableFields){let F=new Set(i.filterableFields),q=R.where.filter(U=>!F.has(U[0]));if(q.length>0){z(d,`Fields not filterable: ${q.map(U=>U[0]).join(", ")}`,400);return}}let j=[];for(let F of R.where){let q=Wt(F[1]),U=En(i.schema,F[0],F[2],q);if(!U.success){z(d,`Invalid filter value for '${F[0]}': ${U.error}`,400);return}j.push([F[0],q,U.data]);}v.where=j;}if(R.orWhere&&R.orWhere.length>0){if(i.filterableFields){let F=new Set(i.filterableFields),q=R.orWhere.filter(U=>!F.has(U[0]));if(q.length>0){z(d,`Fields not filterable: ${q.map(U=>U[0]).join(", ")}`,400);return}}let j=[];for(let F of R.orWhere){let q=Wt(F[1]),U=En(i.schema,F[0],F[2],q);if(!U.success){z(d,`Invalid filter value for '${F[0]}': ${U.error}`,400);return}j.push([F[0],q,U.data]);}v.orWhere=j;}if(R.orWhereGroups&&R.orWhereGroups.length>0){if(i.filterableFields){let F=new Set(i.filterableFields);for(let q of R.orWhereGroups){let U=q.filter(Q=>!F.has(Q[0]));if(U.length>0){z(d,`Fields not filterable: ${U.map(Q=>Q[0]).join(", ")}`,400);return}}}let j=[];for(let F of R.orWhereGroups){let q=[];for(let U of F){let Q=Wt(U[1]),ne=En(i.schema,U[0],U[2],Q);if(!ne.success){z(d,`Invalid filter value for '${U[0]}': ${ne.error}`,400);return}q.push([U[0],Q,ne.data]);}j.push(q);}v.orWhereGroups=j;}if(R.orderBy&&R.orderBy.length>0){if(i.orderableFields){let j=new Set(i.orderableFields),F=R.orderBy.filter(q=>!j.has(q.field));if(F.length>0){z(d,`Fields not orderable: ${F.map(q=>q.field).join(", ")}`,400);return}}v.orderBy=R.orderBy;}R.select&&R.select.length>0&&(v.select=R.select);let O;N&&r&&(v.onCountIndexError=j=>{O=j;});let M=await i.repo.query.paginate(v);O!==void 0&&r&&await $r(d,O,{repoName:y.repoName||i.name,ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:C},n,r,!0);let _={items:await l(i,c(d),y,M.data),hasNextPage:M.hasNextPage,hasPrevPage:M.hasPrevPage,nextCursor:On(M.nextCursor),prevCursor:On(M.prevCursor),...M.totalCount!==void 0?{totalCount:M.totalCount,totalCountIsExact:M.totalCountIsExact}:{}};return rt(d,_,{pageSize:$,hasMore:M.hasNextPage,...M.totalCount!==void 0?{totalCount:M.totalCount,totalCountIsExact:M.totalCountIsExact}:{}})}catch(R){return await Dr(d,R,{repoName:y.repoName||i.name,ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:C,sort:k},"Failed to query documents",n,r)}}async function w(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return z(d,"Repository not found",404);let g=y.id;if(!g)return z(d,"Document ID required",400);try{let m=await f(i,g);if(!m)return z(d,"Document not found",404);let C=c(d),k=await a(d,i,"get",{user:C,doc:m,params:y});if(!k.allowed)return k.errorResponse;if(i.rules?.filter)try{if(!await i.rules.filter({user:C,doc:m,params:y}))return z(d,"Document not found",404)}catch{return z(d,"Document not found",404)}return rt(d,m)}catch(m){return await Dr(d,m,{repoName:y.repoName||i.name,ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:[{field:i.documentKey,op:"==",value:g}]},"Failed to fetch document",n,r)}}async function T(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return z(d,"Repository not found",404);try{let g=x.input||{},m=c(d),C=await a(d,i,"create",{user:m,body:g,params:y});if(!C.allowed)return C.errorResponse;let k=An(i.schema,g,i.createFields,!1,i.systemKeys);if(!k.success)return z(d,k.error,400);if(i.validate){let D=await i.validate(k.data,"create");if(D)return z(d,D,400)}i.hooks?.beforeCreate&&await i.hooks.beforeCreate({user:m,body:k.data,params:y,c:d});let R,P;if(i.isGroup&&i.parentKeys&&i.parentKeys.length>0){let D={...k.data},N=i.parentKeys.filter(v=>D[v]===void 0||D[v]===null||typeof D[v]=="string"&&D[v].trim()==="");if(N.length>0)return z(d,`Missing parent key(s) for subcollection create: ${N.join(", ")}`,400);if(typeof i.repo.create=="function")R=await i.repo.create(D);else {let v=i.parentKeys.map(M=>String(D[M])),O=D[i.documentKey]||Be();P=[...v,O],R=await i.repo.set(...v,O,D);}}else R=await i.repo.create(k.data);let $=R;if(i.hooks?.afterCreate){let D=R?.[i.documentKey]??P?.[P.length-1]??"",N=String(D),v=P??p(R,i)??p({...k.data,...N?{[i.documentKey]:N}:{}},i)??(N?[N]:[]);try{let O=await i.hooks.afterCreate({user:m,doc:R,id:N,pathArgs:v,params:y,c:d}),M=Pn(O);M&&v.length>0&&($=await i.repo.update(...v,M));}catch(O){await s(i,x.logger,{hook:"afterCreate",repoName:i.name,path:i.path,id:N,pathArgs:v,user:m,c:d},O);}}return rt(d,$,void 0,201)}catch(g){let m=n&&g instanceof Error?g.message:"Failed to create document";return z(d,m,500)}}async function S(x,d){let y=x.c,i=y.req.param(),g=u(i.repoName,y);if(!g)return z(y,"Repository not found",404);let m=i.id;if(!m)return z(y,"Document ID required",400);try{let C=x.input||{},k=await f(g,m);if(!k)return z(y,"Document not found",404);let R=An(g.schema,C,g.mutableFields,d,g.systemKeys);if(!R.success)return z(y,R.error,400);if(g.validate){let _=await g.validate(R.data,"update");if(_)return z(y,_,400)}let P=Te(k,R.data),$=c(y),D=await a(y,g,"update",{user:$,doc:k,body:R.data,diff:P,params:i});if(!D.allowed)return D.errorResponse;if(g.hooks?.beforeUpdate){let _=g.rules?.update?Te(k,R.data):P;await g.hooks.beforeUpdate({user:$,doc:k,body:R.data,diff:_,params:i,c:y});}let N={...R.data},v=g.hooks?.afterUpdate?Te(k,N):P,O=p(k,g)??[m],M=await g.repo.update(...O,R.data),H=M;if(g.hooks?.afterUpdate)try{let _=await g.hooks.afterUpdate({user:$,before:k,after:M,body:N,diff:v,id:m,pathArgs:O,params:i,c:y}),j=Pn(_);j&&(H=await g.repo.update(...O,j));}catch(_){await s(g,x.logger,{hook:"afterUpdate",repoName:g.name,path:g.path,id:m,pathArgs:O,user:$,c:y},_);}return rt(y,H)}catch(C){let k=n&&C instanceof Error?C.message:"Failed to update document";return z(y,k,500)}}async function I(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return z(d,"Repository not found",404);if(!i.allowDelete)return z(d,"Delete not allowed for this repository",403);let g=y.id;if(!g)return z(d,"Document ID required",400);try{let m=await f(i,g);if(!m)return z(d,"Document not found",404);let C=c(d),k=await a(d,i,"delete",{user:C,doc:m,params:y});if(!k.allowed)return k.errorResponse;let R=p(m,i)??[g];if(await i.repo.delete(...R),i.hooks?.afterDelete)try{await i.hooks.afterDelete({user:C,doc:m,id:g,pathArgs:R,params:y,c:d});}catch(P){await s(i,x.logger,{hook:"afterDelete",repoName:i.name,path:i.path,id:g,pathArgs:R,user:C,c:d},P);}return rt(d,{deleted:!0})}catch(m){let C=n&&m instanceof Error?m.message:"Failed to delete document";return z(d,C,500)}}function A(x){return x.c.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-History-Reason, X-History-Comment","Access-Control-Max-Age":"86400"})}async function E(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return z(d,"Repository not found",404);try{let g=x.input||{};if(!Array.isArray(g.operations))return z(d,"operations array is required",400);let m=c(d),C=i.repo.batch.create(),k=[],R=!!i.hooks,P=[],$=[],D=[];for(let v of g.operations){if(!v.type||!["create","update","delete"].includes(v.type))return z(d,"Invalid operation type",400);if(v.type==="create"){let O=await a(d,i,"create",{user:m,body:v.data,params:y});if(!O.allowed)return O.errorResponse;let M=An(i.schema,v.data,i.createFields,!1,i.systemKeys);if(!M.success)return z(d,M.error,400);i.hooks?.beforeCreate&&await i.hooks.beforeCreate({user:m,body:M.data,params:y,c:d});let H=v.data[i.documentKey]||M.data[i.documentKey]||Be(),_={...M.data};i.createdKey&&_[i.createdKey]===void 0&&(_[i.createdKey]=new Date);let j;if(i.isGroup&&i.parentKeys){let F=i.parentKeys.map(q=>String(_[q]));j=[...F,H],C.set(...F,H,_);}else j=[H],C.set(H,_);if(k.push({op:"create",id:H}),R){let F={..._,[i.documentKey]:H};if(i.pathKey&&typeof i.repo.documentRef=="function")try{let q=i.repo.documentRef(...j);q?.path&&(F[i.pathKey]=q.path);}catch{}P.push({id:H,pathArgs:j,doc:F});}}else if(v.type==="update"){if(!v.id)return z(d,"id required for update",400);let O=await f(i,v.id);if(!O)return z(d,`Document ${v.id} not found`,404);let M=An(i.schema,v.data,i.mutableFields,!0,i.systemKeys);if(!M.success)return z(d,M.error,400);if(i.validate){let U=await i.validate(M.data,"update");if(U)return z(d,U,400)}let H=Te(O,M.data),_=await a(d,i,"update",{user:m,doc:O,body:M.data,diff:H,params:y});if(!_.allowed)return _.errorResponse;if(i.hooks?.beforeUpdate){let U=i.rules?.update?Te(O,M.data):H;await i.hooks.beforeUpdate({user:m,doc:O,body:M.data,diff:U,params:y,c:d});}let j={...M.data},F=R?Te(O,j):H,q=p(O,i)??[v.id];C.update(...q,M.data),k.push({op:"update",id:v.id}),R&&$.push({id:v.id,pathArgs:q,before:O,after:F.after,body:j,diff:F});}else if(v.type==="delete"){if(!i.allowDelete)return z(d,"Delete not allowed",403);if(!v.id)return z(d,"id required for delete",400);let O=await f(i,v.id);if(!O)return z(d,`Document ${v.id} not found`,404);let M=await a(d,i,"delete",{user:m,doc:O,params:y});if(!M.allowed)return M.errorResponse;let H=p(O,i)??[v.id];C.delete(...H),k.push({op:"delete",id:v.id}),R&&D.push({id:v.id,pathArgs:H,doc:O});}}await C.commit();let N=P.length>0||$.length>0||D.length>0;if(i.hooks&&N)if(i.hooks.afterBatch)try{await i.hooks.afterBatch({user:m,created:P,updated:$,deleted:D,params:y,c:d});}catch(v){await s(i,x.logger,{hook:"afterBatch",repoName:i.name,path:i.path,user:m,c:d},v);}else {if(i.hooks.afterCreate)for(let v of P)try{let O=await i.hooks.afterCreate({user:m,doc:v.doc,id:v.id,pathArgs:v.pathArgs,params:y,c:d}),M=Pn(O);M&&v.pathArgs.length>0&&await i.repo.update(...v.pathArgs,M);}catch(O){await s(i,x.logger,{hook:"afterCreate",repoName:i.name,path:i.path,id:v.id,pathArgs:v.pathArgs,user:m,c:d},O);}if(i.hooks.afterUpdate)for(let v of $)try{let O=await i.hooks.afterUpdate({user:m,before:v.before,after:v.after,body:v.body,diff:v.diff,id:v.id,pathArgs:v.pathArgs,params:y,c:d}),M=Pn(O);M&&v.pathArgs.length>0&&await i.repo.update(...v.pathArgs,M);}catch(O){await s(i,x.logger,{hook:"afterUpdate",repoName:i.name,path:i.path,id:v.id,pathArgs:v.pathArgs,user:m,c:d},O);}if(i.hooks.afterDelete)for(let v of D)try{await i.hooks.afterDelete({user:m,doc:v.doc,id:v.id,pathArgs:v.pathArgs,params:y,c:d});}catch(O){await s(i,x.logger,{hook:"afterDelete",repoName:i.name,path:i.path,id:v.id,pathArgs:v.pathArgs,user:m,c:d},O);}}return rt(d,{results:k})}catch(g){let m=n&&g instanceof Error?g.message:"Batch operation failed";return z(d,m,500)}}return {handleList:b,handleQuery:h,handleGet:w,handleCreate:T,handleUpdate:S,handleDelete:I,handleBatch:E,handleOptions:A}}function xt(e){try{return z$1.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=getOpenApiMetadata(t.zodSchema);n&&(Object.assign(t.jsonSchema,n),(t.jsonSchema.anyOf||t.jsonSchema.oneOf)&&delete t.jsonSchema.type);let r=t.zodSchema?._zod?.def;r&&(r.type==="date"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):r.type==="bigint"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf&&(t.jsonSchema.type="string",t.jsonSchema.format="int64"));}})}catch(t){return typeof console<"u"&&console.warn&&console.warn("[generateOpenAPISpec] Failed to convert Zod schema to JSON Schema; falling back to {type:object}.",t),{type:"object"}}}function fe(e){return {$ref:`#/components/schemas/${e}`}}function te(e){return {description:e,content:{"application/json":{schema:fe("ErrorResponse")}}}}function wt(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function sc(e){return {description:"Paginated list of documents",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:{type:"object",properties:{items:{type:"array",items:e},nextCursor:{oneOf:[{type:"object"},{type:"null"}]},prevCursor:{oneOf:[{type:"object"},{type:"null"}]},hasNextPage:{type:"boolean"},hasPrevPage:{type:"boolean"},totalCount:{type:"integer",description:"Total count of matching documents (when requested with withTotal=true)"},totalCountIsExact:{type:"boolean",description:"Whether totalCount is exact (true) or estimated via parallel branch-sum fallback (false)"}},required:["items","hasNextPage","hasPrevPage"]},meta:{type:"object",properties:{pageSize:{type:"integer"},hasMore:{type:"boolean"},totalCount:{type:"integer"},totalCountIsExact:{type:"boolean"},cursor:{oneOf:[{type:"string"},{type:"null"}]}}}},required:["success","data"]}}}}}function Vt(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function ac(e,t){let n=t.split("."),r=Vt(e);for(let o=0;o<n.length;o++){let s=n[o];if(!s)continue;let a=r?.shape;if(!a||!a[s])return;let l=a[s];if(o===n.length-1)return l;r=Vt(l);}return r}function it(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type,r=o=>{let s=getOpenApiMetadata(e);return s&&typeof o.openapi=="function"?o.openapi(s):o};if(n==="ZodObject"||n==="object"){let o=e.shape,s={};for(let[a,l]of Object.entries(o))s[a]=it(l);return r(z$1.object(s).partial())}if(n==="ZodOptional"||n==="optional"){let o=t.innerType;if(!o)return e;let s=it(o);return s===o?e:r(s.optional())}if(n==="ZodNullable"||n==="nullable"){let o=t.innerType;if(!o)return e;let s=it(o);return s===o?e:r(s.nullable())}if(n==="ZodDefault"||n==="default"){let o=t.innerType;return o?r(it(o).optional()):e}if(n==="ZodUnion"||n==="union"){let o=t.options;if(!o||o.length<2)return e;let s=o.map(l=>it(l));return s.some((l,c)=>l!==o[c])?r(z$1.union(s)):e}return e}function Mr(e,t="",n=0){if(n>5)return [];let o=Vt(e)?.shape;if(!o)return [];let s=[];for(let[a,l]of Object.entries(o)){let c=t?`${t}.${a}`:a,u=Vt(l);u?.shape&&typeof u.shape=="object"?(s.push({path:c,zodSchema:l}),s.push(...Mr(u,c,n+1))):s.push({path:c,zodSchema:l});}return s}function ic(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:ac(e.schema,t)})):Mr(e.schema)}function Ts(e){if(!e)return {type:"string"};let t=xt(e);return delete t.$schema,delete t.title,t}function Cs(){return {type:"object",properties:{where:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3},description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3},description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3}},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string"},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string"},description:"Fields to select (projection)"},pageSize:{type:"integer",minimum:1,maximum:1e3,description:"Number of items per page"},cursor:{oneOf:[{type:"string"},{type:"object"}],description:"Pagination cursor"},direction:{type:"string",enum:["next","prev"],description:"Pagination direction"},includes:{type:"array",items:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function cc(e){let t=ic(e),n=e.orderableFields??t.map(a=>a.path),r=t.map(a=>a.path);if(t.length===0)return Cs();let o=[];for(let{path:a,zodSchema:l}of t){let c=Ts(l),u=Vt(l),f=u?._zod?.def?.type==="array"||u?._def?.typeName==="ZodArray"||u?._def?.type==="array"?Ts(u?._zod?.def?.element??u?._def?.type??u?._def?.element):c;o.push({type:"array",description:`Condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["==","!=","<","<=",">",">=","eq","ne","lt","lte","gt","gte"]},c],minItems:3,maxItems:3}),o.push({type:"array",description:`List condition on '${a}' (in, not-in)`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["in","not-in","nin"]},{type:"array",items:c}],minItems:3,maxItems:3}),o.push({type:"array",description:`Array contains condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains","contains"]},f],minItems:3,maxItems:3}),o.push({type:"array",description:`Array contains-any condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains-any","containsAny"]},{type:"array",items:f}],minItems:3,maxItems:3});}let s={oneOf:o};return {type:"object",properties:{where:{type:"array",items:s,description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:s,description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:s},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string",enum:n},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string",enum:r},description:"Fields to select (projection)"},pageSize:{type:"integer",minimum:1,maximum:1e3,description:"Number of items per page"},cursor:{oneOf:[{type:"string"},{type:"object"}],description:"Pagination cursor"},direction:{type:"string",enum:["next","prev"],description:"Pagination direction"},includes:{type:"array",items:e.allowedIncludes&&e.allowedIncludes.length>0?{oneOf:[{type:"string",enum:e.allowedIncludes},{type:"object",properties:{relation:{type:"string",enum:e.allowedIncludes},select:{type:"array",items:{type:"string"}}},required:["relation"]}]}:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function lc(e){if(e.historyHeaders)return e.historyHeaders;let t=e.repo?._historyConfig;if(!t?.enabled||t.autoInjectMeta===false)return null;let n=Oe(t);return n?{reason:n.fields.reason!==false,comment:n.fields.comment!==false}:null}function dc(e,t){if(t===false)return [];let n=lc(e);if(!n)return [];let r=t?.reasonHeader===void 0?Ve:t.reasonHeader,o=t?.commentHeader===void 0?Ge:t.commentHeader,s=[],a=new Set;if(n.reason&&typeof r=="string"&&r.trim()){let l=r.trim();a.add(l.toLowerCase()),s.push({name:l,in:"header",required:false,schema:{type:"string"},description:"Optional reason recorded in the document's change history"});}if(n.comment&&typeof o=="string"&&o.trim()){let l=o.trim();a.has(l.toLowerCase())||(a.add(l.toLowerCase()),s.push({name:l,in:"header",required:false,schema:{type:"string"},description:"Optional comment recorded in the document's change history"}));}if(t?.extraHeaders?.length)for(let l of t.extraHeaders){let c=typeof l=="string"?{name:l}:l,u=c?.name?.trim();!u||a.has(u.toLowerCase())||(a.add(u.toLowerCase()),s.push({name:u,in:"header",required:c.required??false,schema:c.schema??{type:"string"},...c.description?{description:c.description}:{}}));}return s}function uc(e,t,n,r,o,s=null,a="QueryRequestBody",l=[]){let c={},u=e.name,p=`${t}/${e.name}`,f=`${p}/{${e.documentKey}}`,b={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};c[p]={post:{operationId:`create${Ze(e.name)}`,summary:`Create a ${$e(e.name)}`,tags:[u],...l.length>0?{parameters:[...l]}:{},requestBody:{required:true,content:{"application/json":{schema:fe(r??n)}}},responses:{201:wt("Document created",fe(n)),400:te("Validation error"),403:te("Forbidden"),500:te("Internal server error")}}},c[`${p}/query`]={post:{operationId:`query${Ze(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[u],requestBody:{required:true,content:{"application/json":{schema:fe(a)}}},responses:{200:sc(fe(n)),400:te("Invalid query"),403:te("Forbidden"),424:te("Missing composite index (includes indexUrl in response)"),500:te("Internal server error")}}},c[`${p}/batch`]={post:{operationId:`batch${Ze(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[u],...l.length>0?{parameters:[...l]}:{},requestBody:{required:true,content:{"application/json":{schema:fe(`${n}BatchRequest`)}}},responses:{200:wt("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:te("Validation error"),403:te("Forbidden"),404:te("Document not found"),500:te("Internal server error")}}};let h={};return h.get={operationId:`get${Ze($e(e.name))}`,summary:`Get a single ${$e(e.name)}`,tags:[u],parameters:[b],responses:{200:wt("Document found",fe(n)),400:te("Document ID required"),403:te("Forbidden"),404:te("Document not found"),424:te("Missing composite index (includes indexUrl in response)"),500:te("Internal server error")}},h.put={operationId:`update${Ze($e(e.name))}`,summary:`Update a ${$e(e.name)} (full replace)`,tags:[u],parameters:[b,...l],requestBody:{required:true,content:{"application/json":{schema:fe(o??n)}}},responses:{200:wt("Document updated",fe(n)),400:te("Validation error"),403:te("Forbidden"),404:te("Document not found"),500:te("Internal server error")}},h.patch={operationId:`patch${Ze($e(e.name))}`,summary:`Partially update a ${$e(e.name)}`,tags:[u],parameters:[b,...l],requestBody:{required:true,content:{"application/json":{schema:fe(s??o??n)}}},responses:{200:wt("Document patched",fe(n)),400:te("Validation error"),403:te("Forbidden"),404:te("Document not found"),500:te("Internal server error")}},e.allowDelete&&(h.delete={operationId:`delete${Ze($e(e.name))}`,summary:`Delete a ${$e(e.name)}`,tags:[u],parameters:[b],responses:{200:wt("Document deleted",{type:"object",properties:{id:{type:"string"}}}),400:te("Document ID required"),403:te("Forbidden"),404:te("Document not found"),500:te("Internal server error")}}),c[f]=h,c}function Nr(e,t,n={}){let{title:r="CRUD API",version:o="1.0.0",description:s,servers:a,auth:l=false}=n,c=t==="/"?"":t.replace(/\/$/,""),u={},p={},f=[];u.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string",description:"Human-readable error description"},errorType:{type:"string",enum:["index"],description:"Error category discriminator. Set to 'index' when a Firestore composite index is missing."},indexUrl:{type:"string",format:"uri",description:"Direct Firebase Console URL to create the required composite index (when errorType is 'index')."}},required:["success","error"]},u.QueryRequestBody=Cs();for(let[T,S]of Object.entries(e)){let I=Ze($e(T)),A=`${I}Create`,E=`${I}Update`,x=`${I}Patch`,d=`${I}QueryRequestBody`;u[I]=xt(S.schema),u[d]=cc(S);let y=v=>{let O={},M=Mr(S.schema);for(let{path:H,zodSchema:_}of M){let j=H.split(".")[0];S.systemKeys.includes(j)||S.systemKeys.includes(H)||v&&v.length>0&&!v.includes(H)&&!v.includes(j)||(H.includes(".")?O[H]=_.optional():O[H]=_);}return O},i=null,g=y(S.createFields);if(S.isGroup&&S.parentKeys&&S.parentKeys.length>0){let v=S.schema?.shape??{};for(let O of S.parentKeys)!g[O]&&v[O]&&(g[O]=v[O]);}if(Object.keys(g).length>0){let v=xt(z$1.object(g));if(S.isGroup&&S.parentKeys&&S.parentKeys.length>0){let O=new Set(Array.isArray(v.required)?v.required:[]);for(let M of S.parentKeys)v.properties?.[M]&&O.add(M);O.size>0&&(v.required=Array.from(O));}u[A]=v,i=A;}let m=null,C=null,k=y(S.mutableFields);if(Object.keys(k).length>0){let v=z$1.object(k);u[E]=xt(v),m=E,u[x]=xt(it(v)),C=x;}else u[x]=xt(it(S.schema)),C=x;let R=`${I}BatchCreateOperation`,P=`${I}BatchUpdateOperation`,$=`${I}BatchDeleteOperation`;u[R]={type:"object",title:`${I} Create Operation`,properties:{type:{type:"string",enum:["create"],const:"create"},data:fe(i??I)},required:["type","data"]},u[P]={type:"object",title:`${I} Update Operation`,properties:{type:{type:"string",enum:["update"],const:"update"},id:{type:"string"},data:fe(C??m??I)},required:["type","id","data"]},S.allowDelete&&(u[$]={type:"object",title:`${I} Delete Operation`,properties:{type:{type:"string",enum:["delete"],const:"delete"},id:{type:"string"}},required:["type","id"]}),u[`${I}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[fe(R),fe(P),...S.allowDelete?[fe($)]:[]],discriminator:{propertyName:"type"}}}},required:["operations"]};let D=dc(S,n.historyHeaders),N=uc(S,c,I,i,m,C,d,D);Object.assign(p,N),f.push({name:T,description:`Operations on ${T} (collection: ${S.path})`});}let b={},h;return l==="basic"?(b.basicAuth={type:"http",scheme:"basic"},h=[{basicAuth:[]}]):l==="bearer"&&(b.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},h=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:o,...s?{description:s}:{}},...a&&a.length>0?{servers:a}:{},paths:p,components:{schemas:u,...Object.keys(b).length>0?{securitySchemes:b}:{}},...h?{security:h}:{},tags:f}}function Ze(e){return e.charAt(0).toUpperCase()+e.slice(1)}function $e(e){return e.endsWith("ies")?e.slice(0,-3)+"y":e.endsWith("ses")||e.endsWith("xes")||e.endsWith("zes")?e.slice(0,-2):e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e}var Rt=class extends Error{constructor(n,r){super("Request validation failed");this.zodError=n;this.source=r;this.statusCode=400;this.name="ValidationError";}};var Gt=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},Jt=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function As(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function Es(e,t){return t instanceof Rt?e.json({success:false,error:"Validation failed",issues:As(t.zodError)},400):t instanceof Gt?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof Jt?e.json({success:false,error:"Output validation failed",issues:As(t.zodError)},500):null}extendZodWithOpenApi(z$1);var Os="Successful response",Ps="Error response";function be(e,t=new Set){if(!e||typeof e!="object"||t.has(e))return;t.add(e);let n=e,r=n._zod?.def??n.def;if(!r)return;if(r.type==="custom"){let s=getOpenApiMetadata(n);s?.type||z$1.globalRegistry.add(n,{...s??{},type:"object"});return}if(r.innerType&&be(r.innerType,t),r.element&&be(r.element,t),r.valueType&&be(r.valueType,t),r.keyType&&be(r.keyType,t),r.left&&be(r.left,t),r.right&&be(r.right,t),r.in&&be(r.in,t),r.out&&be(r.out,t),typeof r.getter=="function")try{be(r.getter(),t);}catch{}if(Array.isArray(r.options))for(let s of r.options)be(s,t);if(Array.isArray(r.items))for(let s of r.items)be(s,t);let o=typeof r.shape=="function"?r.shape():r.shape;if(o&&typeof o=="object")for(let s of Object.values(o))be(s,t);}function Fr(e){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(let n of e)Fr(n);return}let t=e;(Array.isArray(t.anyOf)||Array.isArray(t.oneOf))&&"type"in t&&delete t.type;for(let n of Object.values(t))Fr(n);}function hc(e){return e==="get"?"query":"json"}function gc(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function bc(e){if(typeof e.safeParse=="function")return {description:Ps,schema:e};let t=e;return {description:t.description??Ps,schema:t.schema}}function $s(e,t,n,r){let o=new OpenAPIRegistry;if(n.securitySchemes)for(let[l,c]of Object.entries(n.securitySchemes))o.registerComponent("securitySchemes",l,c);for(let l of e){let c=l.method,u=l.source??hc(c),p=Rc(t,l.path??"/"),f=l.status??200;l.input&&be(l.input);let b=wc(c,u,l.input),h=Is(u,l.input,"query"),w=Is(u,l.input,"param"),T=Sc(c,p),S=gc(l.output,r);S&&be(S);let I={[f]:S?{description:Os,content:{"application/json":{schema:S}}}:{description:Os}};if(r?.errors)for(let[A,E]of Object.entries(r.errors)){let{description:x,schema:d}=bc(E);d&&be(d),I[A]=d?{description:x,content:{"application/json":{schema:d}}}:{description:x};}o.registerPath({method:c,path:xc(p),operationId:T,summary:l.summary,description:l.description,tags:l.tags,deprecated:l.deprecated,security:l.security,request:{...h?{query:h}:{},...w?{params:w}:{},...b?{body:b}:{}},responses:I});}let a=new OpenApiGeneratorV31(o.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security});return Fr(a),a}function wc(e,t,n){return !n||e==="get"?null:t==="json"?{content:{"application/json":{schema:n}}}:t==="form"?{content:{"application/x-www-form-urlencoded":{schema:n}}}:null}function Is(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function xc(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function Rc(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function Sc(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function Hs(e,t){let n=e.replace(/"/g,"&quot;");return `<!doctype html>
1162
1162
  <html lang="en">
1163
1163
  <head>
1164
1164
  <meta charset="utf-8" />
@@ -1169,5 +1169,5 @@ function initColumnReorder(table) {
1169
1169
  <script id="api-reference" data-url="${n}"></script>
1170
1170
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
1171
1171
  </body>
1172
- </html>`}function $s(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var Nr=new AsyncLocalStorage;function Hs(){return async(e,t)=>{await Nr.run({c:e},async()=>{await t();});}}var Tc=Object.freeze({}),Dn=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new Hono,this.mountedRoutes=Ac(t.routes,t.api),this.app.use("*",Wn(t.actorResolver)),t.services&&this.app.use("*",Hs());let n=[...t.middlewares??[],...t.globalMiddlewares??[]];for(let r of n)this.app.use("*",r);this.mountRoutes(),this.mountOpenApi(),t.notFound&&this.app.notFound(t.notFound),t.onError&&this.app.onError(t.onError);}get hono(){return this.app}get nodeHandler(){return getRequestListener(this.app.fetch,{overrideGlobalObjects:false})}toFunction(t,n){let r=this.nodeHandler;return n?t(n,r):t(r)}buildOpenApiSpec(){if(this.cachedSpec)return this.cachedSpec;if(!this.options.openapi)throw new Error("[HonoServer] openapi config not set");return this.cachedSpec=Is(this.mountedRoutes,this.options.basePath??"",this.options.openapi,Cc(this.options.interceptor)),this.cachedSpec}mountRoutes(){let t=this.options.basePath??"",n=this.options.validateOutput??false,r=this.options.verbose??false;for(let o of this.mountedRoutes){if(!o.path)throw new Error(`[HonoServer] route "${o.method.toUpperCase()} (no path)" \u2014 missing \`path\`. Run the codegen so the path is derived from the file location, or set it explicitly.`);let s=In(t,o.path),a=o.middlewares??[],l=o.source??(o.method==="get"?"query":"json"),c=Pc(o,l,n,kc(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),u=o.method.toUpperCase();this.app.on(u,[s],...a,c),r&&console.log(`[HonoServer] ${o.method.toUpperCase().padEnd(6)} ${s}`);}}mountOpenApi(){let t=this.options.openapi;if(!t)return;let n=t.path??"/openapi.json",r=t.docsPath===void 0?"/docs":t.docsPath,o=In(this.options.basePath??"",n),s=r===false?null:In(this.options.basePath??"",r),a;if($s(t.docsAuth)){let l=t.docsAuth;a=[l.middleware];let c=Ec(s??o);for(let u of l.routes)this.app.on(u.method,[In(c,u.name)],u.handler);}else a=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[o],...a,l=>l.json(this.buildOpenApiSpec())),s){let l=Oc(s,o);this.app.on("GET",[s],...a,c=>c.html(Ds(l,t.info.title)));}}};function _s(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function kc(e){if(e)return _s(e)?e.handler:e}function Cc(e){return _s(e)?e:void 0}function Ac(e,t){return t?e.filter(n=>Array.isArray(n.api)?n.api.includes(t):n.api===t):e.slice()}function In(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function Ec(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function Oc(e,t){let n=e.split("/").filter(Boolean),r=t.split("/").filter(Boolean);n.pop();let o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o++;let s=n.length-o;return [...Array(s).fill(".."),...r.slice(o)].join("/")||"./"}function Pc(e,t,n,r,o,s,a){let l=e.input,c=e.output,u=e.status??200,p=o??Tc;return async f=>{let b=async T=>{if(s){let S=await s.handle({error:T,c:f,route:e,services:p,logger:a});if(S)return S}return Cs(f,T)},h=async()=>{let T,S;try{S=await Ic(f,t,e.method);}catch(A){throw new Gt(A instanceof Error?A.message:String(A))}if(l){let A=l.safeParse(S);if(!A.success)throw new Rt(A.error,t);T=A.data;}else T=S;let I=await e.handler({input:T,c:f,services:p,errorHandler:s,logger:a});if(n&&c&&!(I instanceof Response)){let A=c.safeParse(I);if(!A.success)throw new Jt(A.error);return A.data}return I},w;if(r)try{w=await r({next:h,route:e,c:f,services:p,errorHandler:s,logger:a});}catch(T){let S=await b(T);if(S)return S;throw T}else try{w=await h();}catch(T){let S=await b(T);if(S)return S;throw T}return w instanceof Response?w:f.json(w,u)}}async function Ic(e,t,n){switch(t){case "json":{if(n==="get")return e.req.query();let r=await e.req.text();if(!r)return {};try{return JSON.parse(r)}catch(o){throw new Error(`Invalid JSON body: ${o instanceof Error?o.message:String(o)}`)}}case "query":return e.req.query();case "form":return await e.req.parseBody();case "param":return e.req.param();default:return {}}}function jr(e){return e}async function Ms(e,t){if(e?.length){for(let n of e)if(typeof n=="function")await n(t);else if(n&&typeof n.mutation=="function"){if(n.operations&&!n.operations.includes(t.operation))continue;await n.mutation(t);}}}async function Yt(e,t,n,r,o,s=t?"update":"create"){for(let a of Object.keys(n.changes))await Ms(r[a],{body:e,doc:t,diff:n,key:a,operation:s,user:o});await Ms(r["*"],{body:e,doc:t,diff:n,key:"*",operation:s,user:o});}function Br(e){return async t=>{await Yt(t.body,t.doc,t.diff,e,t.user,"update");}}function zr(e){return async t=>{let n=Te({},t.body);await Yt(t.body,null,n,e,t.user,"create");}}function qr(e){return e}async function Fs(e,t,n,r,o,s,a,l){if(!e?.length)return s;let c=s;for(let u of e){let p=null,f=false;try{if(f=!!await u.rule({diff:n,key:t,user:a,operation:l}),f){let b=await u.handler(r);b&&(c={...c,...b});}}catch(b){p=b;}o.push({key:String(t),description:u.description,isCalled:f,error:p});}return c}async function $n(e,t,n,r,o="update"){let s=[],a={};for(let l of Object.keys(e.changes))a=await Fs(t[l],l,e,n,s,a,r,o);return a=await Fs(t["*"],"*",e,n,s,a,r,o),{results:s,changesNeeded:a,hasErrors:s.some(l=>l.error!==null)}}function Ur(e,t,n){return async r=>{let o=t(r),{results:s,changesNeeded:a}=await $n(r.diff,e,o,r.user,"update");if(n?.onRuleError)for(let l of s)l.error&&await n.onRuleError(l,r);return Object.keys(a).length>0?a:void 0}}function Ns(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,verbose:s=false,httpsOptions:a}=e,l=t==="/"?"":t.replace(/\/$/,""),c={};for(let[d,y]of Object.entries(n)){if(!y.repo)throw new Error(`[createCrudServer] Repository "${d}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let i=y.schema??y.repo.schema??null;if(!i)throw new Error(`[createCrudServer] Repository "${d}" has no Zod schema.`);let g,m,C,k;if(y.fieldsConfig){let H=y.fieldsConfig;g=[],m=[],C=[],k=[];for(let[D,N]of Object.entries(H))for(let j of N)j==="filterable"?g.push(D):j==="orderable"?m.push(D):j==="mutable"?C.push(D):j==="create"&&k.push(D);m.length===0&&(m=g),g.length===0&&(g=void 0),m&&m.length===0&&(m=void 0),C.length===0&&(C=void 0),k.length===0&&(k=void 0);}let R=(()=>{let H=y.repo._parentKeys;return H&&H.length>0?H:void 0})();if(R&&k)for(let H of R)k.includes(H)||k.push(H);let P=y.repo._systemKeys??[y.documentKey??"docId"],_=y.repo._historyIdentityKeys??[],$=Array.from(new Set([...P,..._])),M=y.repo._historyConfig,v=M?.enabled&&M.autoInjectMeta!==false?Ee(M):null,E=v?{reason:v.fields.reason!==false,comment:v.fields.comment!==false}:void 0,F={name:d,path:y.path,repo:y.repo,schema:i,systemKeys:$,documentKey:y.documentKey??"docId",pathKey:y.repo._pathKey??void 0,isGroup:!!y.repo._isGroup,parentKeys:R,documentPathTemplate:y.repo._documentPathTemplate??void 0,createdKey:y.repo._createdKey??void 0,pageSize:y.pageSize??25,filterableFields:g,orderableFields:m,mutableFields:C,createFields:k,allowDelete:y.allowDelete??false,allowedIncludes:y.allowedIncludes,validate:y.validate,rules:y.rules,hooks:y.hooks,...E?{historyHeaders:E}:{}};c[d]=F;}let u=e.indexesError??e.onIndexError,p=Rs(c,l,s,u,e.onHookError),f=e.openapi,b=f&&typeof f=="object"?f:{},h=Zn(e.actorResolver),w=b.historyHeaders===false?false:{reasonHeader:b.historyHeaders?.reasonHeader!==void 0?b.historyHeaders.reasonHeader:h.reasonHeader,commentHeader:b.historyHeaders?.commentHeader!==void 0?b.historyHeaders.commentHeader:h.commentHeader,...b.historyHeaders?.extraHeaders?{extraHeaders:b.historyHeaders.extraHeaders}:{}},T=(()=>{let d=["Content-Type","Authorization"],y=new Set(d.map(g=>g.toLowerCase())),i=g=>{if(typeof g!="string")return;let m=g.trim();!m||y.has(m.toLowerCase())||(y.add(m.toLowerCase()),d.push(m));};if(i(h.reasonHeader),i(h.commentHeader),b.historyHeaders&&typeof b.historyHeaders=="object"&&(i(b.historyHeaders.reasonHeader),i(b.historyHeaders.commentHeader),b.historyHeaders.extraHeaders))for(let g of b.historyHeaders.extraHeaders)i(typeof g=="string"?g:g?.name);return d.join(", ")})(),S=null;function I(){return S||(S=Mr(c,l,{...b,auth:b.auth??false,historyHeaders:w})),S}let A=[];for(let d of Object.keys(c))A.push({api:"crud",method:"post",path:`/${d}/query`,source:"json",handler:p.handleQuery}),A.push({api:"crud",method:"get",path:`/${d}/:id`,source:"query",handler:p.handleGet}),A.push({api:"crud",method:"post",path:`/${d}`,source:"json",handler:p.handleCreate}),A.push({api:"crud",method:"put",path:`/${d}/:id`,source:"json",handler:y=>p.handleUpdate(y,false)}),A.push({api:"crud",method:"patch",path:`/${d}/:id`,source:"json",handler:y=>p.handleUpdate(y,true)}),A.push({api:"crud",method:"delete",path:`/${d}/:id`,source:"query",handler:p.handleDelete}),A.push({api:"crud",method:"post",path:`/${d}/batch`,source:"json",handler:p.handleBatch});let O=new Dn({...e,openapi:f!==false?{path:b.path??"/openapi.json",docsPath:b.docsPath??"/docs",info:{title:b.title??"CRUD API",version:b.version??"1.0.0"},docsAuth:b.docsAuth}:void 0,basePath:t,api:"crud",routes:A,middlewares:[async(d,y)=>{if(d.req.method==="OPTIONS")return d.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":T,"Access-Control-Max-Age":"86400","Access-Control-Allow-Origin":"*","Access-Control-Allow-Credentials":"true"});d.header("Access-Control-Allow-Origin","*"),d.header("Access-Control-Allow-Credentials","true"),await y();},...e.middlewares||[]]});if(f!==false&&(O.buildOpenApiSpec=I),o!==false){let{securityHeaders:d}=(kn(),Ws(fs)),y=o===void 0?{csp:false}:o;O.hono.use("*",async(i,g)=>{let m=d(y);await new Promise(C=>{let k=i.req.raw;m(k,{setHeader:(P,_)=>i.header(P,_),removeHeader:P=>i.res.headers.delete(P)},()=>C());}),await g();});}let x=O.nodeHandler;return x.spec=I,a&&(x.httpsOptions=a),x}function js(e,t){if(!t.onRequest)return e;let n=e.httpsOptions??t.httpsOptions,r=n?t.onRequest(n,e):t.onRequest(e),o=e.spec;return typeof o=="function"&&(r.spec=o),r}function Bs(e,t,n){let r={},o=e?.rawMapping;for(let[s,a]of Object.entries(t)){if(!a)continue;if(!(o?s in o:!!e[s]))throw new Error(`[createServers.${n}] Unknown repo "${s}" \u2014 not present in the registry passed to createServers().`);let c=o?dn(o[s],()=>e[s]):e[s];r[s]={...a,repo:c};}return r}function zs(e,t={}){return {admin(n){let r=Bs(e,n.repos,"admin"),o=ms({...n,repos:r,httpsOptions:n.httpsOptions??t.httpsOptions});return js(o,t)},crud(n){let r=Bs(e,n.repos,"crud"),o=Ns({...n,repos:r,httpsOptions:n.httpsOptions??t.httpsOptions,actorResolver:n.actorResolver??t.actorResolver});return js(o,t)},sync(n){let r=t.triggerOptions||n.triggerOptions?{...t.triggerOptions,...n.triggerOptions}:void 0,o={...n,...r?{triggerOptions:r}:{}};return t.onRequest&&o.admin&&!o.admin.onRequest&&(o.admin={...o.admin,onRequest:t.onRequest,httpsOptions:o.admin.httpsOptions??t.httpsOptions}),zo(e,o)},meilisearchAdapter(n){return ()=>new bn(n)},history(n){let r=t.triggerOptions||n.triggerOptions?{...t.triggerOptions,...n.triggerOptions}:void 0,o={...n,...r?{triggerOptions:r}:{}};return ko(e,o)}}}kn();function mf(e){return t=>({...t,schema:e,type:null,documentRef:null,update:null})}function hf(e,t){let n={...e};for(let r in t)t[r]&&(n[r]={...e[r],relationalKeys:t[r]});return n}var Lr=class{constructor(t,n){this.allRepositories={};this.initialized=false;this.dbFactory=t,this.mapping=n;}get db(){return this._db??(this._db=this.dbFactory())}get rawMapping(){return this.mapping}ensureInitialized(){this.initialized||(this.initializeRepositories(),this.initialized=true);}initializeRepositories(){let t=this.db;for(let n of Object.keys(this.mapping))this.allRepositories[n]=nr(t,this.mapping[n],{});for(let n of Object.keys(this.mapping))this.allRepositories[n]=nr(t,this.mapping[n],this.allRepositories);}getRepository(t){return this.ensureInitialized(),this.allRepositories[t]}};function gf(e,t){let n=new Lr(e,t),r=Object.keys(t);return new Proxy(n,{get(o,s){return typeof s=="string"&&s in t?o.getRepository(s):o[s]},has(o,s){return typeof s=="string"&&s in t?true:s in o},ownKeys(){return r},getOwnPropertyDescriptor(o,s){if(typeof s=="string"&&s in t)return {configurable:true,enumerable:true,writable:false}}})}export{Ge as DEFAULT_HISTORY_COMMENT_HEADER,Ve as DEFAULT_HISTORY_REASON_HEADER,Qn as DEFAULT_HISTORY_SHADOW_KEY,Me as MiniRouter,Lr as RepositoryMapping,$n as applyEffects,Yt as applyMutations,je as applyPaginationQueryOptions,Cn as applyRules,jn as buildAndCountQuery,Qe as buildAndExecuteQuery,hf as buildRepositoryRelations,zn as coerceToDate,Te as computeDeepDiff,Wn as createActorContextMiddleware,Kn as createActorResolver,Ur as createAfterUpdateEffects,zr as createBeforeCreateMutations,Pr as createBeforeRules,Br as createBeforeUpdateMutations,qr as createEffects,jr as createMutations,qn as createPaginationIterator,mf as createRepositoryConfig,gf as createRepositoryMapping,Or as createRules,zs as createServers,io as defaultActorResolver,rn as executePaginatedQuery,Zn as getActorResolverHeaders,ut as getCurrentActor,nn as getDateHandling,tn as normalizeTimestamps,ua as setDateHandling,ba as setRequestActorMeta,ga as withActor};//# sourceMappingURL=index.js.map
1172
+ </html>`}function _s(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var jr=new AsyncLocalStorage;function Ms(){return async(e,t)=>{await jr.run({c:e},async()=>{await t();});}}var Cc=Object.freeze({}),Dn=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new Hono,this.mountedRoutes=Oc(t.routes,t.api),this.app.use("*",Wn(t.actorResolver)),t.services&&this.app.use("*",Ms());let n=[...t.middlewares??[],...t.globalMiddlewares??[]];for(let r of n)this.app.use("*",r);this.mountRoutes(),this.mountOpenApi(),t.notFound&&this.app.notFound(t.notFound),t.onError&&this.app.onError(t.onError);}get hono(){return this.app}get nodeHandler(){return getRequestListener(this.app.fetch,{overrideGlobalObjects:false})}toFunction(t,n){let r=this.nodeHandler;return n?t(n,r):t(r)}buildOpenApiSpec(){if(this.cachedSpec)return this.cachedSpec;if(!this.options.openapi)throw new Error("[HonoServer] openapi config not set");return this.cachedSpec=$s(this.mountedRoutes,this.options.basePath??"",this.options.openapi,Ec(this.options.interceptor)),this.cachedSpec}mountRoutes(){let t=this.options.basePath??"",n=this.options.validateOutput??false,r=this.options.verbose??false;for(let o of this.mountedRoutes){if(!o.path)throw new Error(`[HonoServer] route "${o.method.toUpperCase()} (no path)" \u2014 missing \`path\`. Run the codegen so the path is derived from the file location, or set it explicitly.`);let s=In(t,o.path),a=o.middlewares??[],l=o.source??(o.method==="get"?"query":"json"),c=Dc(o,l,n,Ac(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),u=o.method.toUpperCase();this.app.on(u,[s],...a,c),r&&console.log(`[HonoServer] ${o.method.toUpperCase().padEnd(6)} ${s}`);}}mountOpenApi(){let t=this.options.openapi;if(!t)return;let n=t.path??"/openapi.json",r=t.docsPath===void 0?"/docs":t.docsPath,o=In(this.options.basePath??"",n),s=r===false?null:In(this.options.basePath??"",r),a;if(_s(t.docsAuth)){let l=t.docsAuth;a=[l.middleware];let c=Pc(s??o);for(let u of l.routes)this.app.on(u.method,[In(c,u.name)],u.handler);}else a=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[o],...a,l=>l.json(this.buildOpenApiSpec())),s){let l=Ic(s,o);this.app.on("GET",[s],...a,c=>c.html(Hs(l,t.info.title)));}}};function Ns(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function Ac(e){if(e)return Ns(e)?e.handler:e}function Ec(e){return Ns(e)?e:void 0}function Oc(e,t){return t?e.filter(n=>Array.isArray(n.api)?n.api.includes(t):n.api===t):e.slice()}function In(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function Pc(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function Ic(e,t){let n=e.split("/").filter(Boolean),r=t.split("/").filter(Boolean);n.pop();let o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o++;let s=n.length-o;return [...Array(s).fill(".."),...r.slice(o)].join("/")||"./"}function Dc(e,t,n,r,o,s,a){let l=e.input,c=e.output,u=e.status??200,p=o??Cc;return async f=>{let b=async T=>{if(s){let S=await s.handle({error:T,c:f,route:e,services:p,logger:a});if(S)return S}return Es(f,T)},h=async()=>{let T,S;try{S=await $c(f,t,e.method);}catch(A){throw new Gt(A instanceof Error?A.message:String(A))}if(l){let A=l.safeParse(S);if(!A.success)throw new Rt(A.error,t);T=A.data;}else T=S;let I=await e.handler({input:T,c:f,services:p,errorHandler:s,logger:a});if(n&&c&&!(I instanceof Response)){let A=c.safeParse(I);if(!A.success)throw new Jt(A.error);return A.data}return I},w;if(r)try{w=await r({next:h,route:e,c:f,services:p,errorHandler:s,logger:a});}catch(T){let S=await b(T);if(S)return S;throw T}else try{w=await h();}catch(T){let S=await b(T);if(S)return S;throw T}return w instanceof Response?w:f.json(w,u)}}async function $c(e,t,n){switch(t){case "json":{if(n==="get")return e.req.query();let r=await e.req.text();if(!r)return {};try{return JSON.parse(r)}catch(o){throw new Error(`Invalid JSON body: ${o instanceof Error?o.message:String(o)}`)}}case "query":return e.req.query();case "form":return await e.req.parseBody();case "param":return e.req.param();default:return {}}}function Br(e){return e}async function Fs(e,t){if(e?.length){for(let n of e)if(typeof n=="function")await n(t);else if(n&&typeof n.mutation=="function"){if(n.operations&&!n.operations.includes(t.operation))continue;await n.mutation(t);}}}async function Yt(e,t,n,r,o,s=t?"update":"create"){for(let a of Object.keys(n.changes))await Fs(r[a],{body:e,doc:t,diff:n,key:a,operation:s,user:o});await Fs(r["*"],{body:e,doc:t,diff:n,key:"*",operation:s,user:o});}function zr(e){return async t=>{await Yt(t.body,t.doc,t.diff,e,t.user,"update");}}function qr(e){return async t=>{let n=Te({},t.body);await Yt(t.body,null,n,e,t.user,"create");}}function Ur(e){return e}async function js(e,t,n,r,o,s,a,l){if(!e?.length)return s;let c=s;for(let u of e){let p=null,f=false;try{if(f=!!await u.rule({diff:n,key:t,user:a,operation:l}),f){let b=await u.handler(r);b&&(c={...c,...b});}}catch(b){p=b;}o.push({key:String(t),description:u.description,isCalled:f,error:p});}return c}async function $n(e,t,n,r,o="update"){let s=[],a={};for(let l of Object.keys(e.changes))a=await js(t[l],l,e,n,s,a,r,o);return a=await js(t["*"],"*",e,n,s,a,r,o),{results:s,changesNeeded:a,hasErrors:s.some(l=>l.error!==null)}}function Lr(e,t,n){return async r=>{let o=t(r),{results:s,changesNeeded:a}=await $n(r.diff,e,o,r.user,"update");if(n?.onRuleError)for(let l of s)l.error&&await n.onRuleError(l,r);return Object.keys(a).length>0?a:void 0}}function Bs(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,verbose:s=false,httpsOptions:a}=e,l=t==="/"?"":t.replace(/\/$/,""),c={};for(let[d,y]of Object.entries(n)){if(!y.repo)throw new Error(`[createCrudServer] Repository "${d}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let i=y.schema??y.repo.schema??null;if(!i)throw new Error(`[createCrudServer] Repository "${d}" has no Zod schema.`);let g,m,C,k;if(y.fieldsConfig){let H=y.fieldsConfig;g=[],m=[],C=[],k=[];for(let[_,j]of Object.entries(H))for(let F of j)F==="filterable"?g.push(_):F==="orderable"?m.push(_):F==="mutable"?C.push(_):F==="create"&&k.push(_);m.length===0&&(m=g),g.length===0&&(g=void 0),m&&m.length===0&&(m=void 0),C.length===0&&(C=void 0),k.length===0&&(k=void 0);}let R=(()=>{let H=y.repo._parentKeys;return H&&H.length>0?H:void 0})();if(R&&k)for(let H of R)k.includes(H)||k.push(H);let P=y.repo._systemKeys??[y.documentKey??"docId"],$=y.repo._historyIdentityKeys??[],D=Array.from(new Set([...P,...$])),N=y.repo._historyConfig,v=N?.enabled&&N.autoInjectMeta!==false?Oe(N):null,O=v?{reason:v.fields.reason!==false,comment:v.fields.comment!==false}:void 0,M={name:d,path:y.path,repo:y.repo,schema:i,systemKeys:D,documentKey:y.documentKey??"docId",pathKey:y.repo._pathKey??void 0,isGroup:!!y.repo._isGroup,parentKeys:R,documentPathTemplate:y.repo._documentPathTemplate??void 0,createdKey:y.repo._createdKey??void 0,pageSize:y.pageSize??25,filterableFields:g,orderableFields:m,mutableFields:C,createFields:k,allowDelete:y.allowDelete??false,allowedIncludes:y.allowedIncludes,validate:y.validate,rules:y.rules,hooks:y.hooks,...O?{historyHeaders:O}:{}};c[d]=M;}let u=e.indexesError??e.onIndexError,p=vs(c,l,s,u,e.onHookError),f=e.openapi,b=f&&typeof f=="object"?f:{},h=Zn(e.actorResolver),w=b.historyHeaders===false?false:{reasonHeader:b.historyHeaders?.reasonHeader!==void 0?b.historyHeaders.reasonHeader:h.reasonHeader,commentHeader:b.historyHeaders?.commentHeader!==void 0?b.historyHeaders.commentHeader:h.commentHeader,...b.historyHeaders?.extraHeaders?{extraHeaders:b.historyHeaders.extraHeaders}:{}},T=(()=>{let d=["Content-Type","Authorization"],y=new Set(d.map(g=>g.toLowerCase())),i=g=>{if(typeof g!="string")return;let m=g.trim();!m||y.has(m.toLowerCase())||(y.add(m.toLowerCase()),d.push(m));};if(i(h.reasonHeader),i(h.commentHeader),b.historyHeaders&&typeof b.historyHeaders=="object"&&(i(b.historyHeaders.reasonHeader),i(b.historyHeaders.commentHeader),b.historyHeaders.extraHeaders))for(let g of b.historyHeaders.extraHeaders)i(typeof g=="string"?g:g?.name);return d.join(", ")})(),S=null;function I(){return S||(S=Nr(c,l,{...b,auth:b.auth??false,historyHeaders:w})),S}let A=[];for(let d of Object.keys(c))A.push({api:"crud",method:"post",path:`/${d}/query`,source:"json",handler:p.handleQuery}),A.push({api:"crud",method:"get",path:`/${d}/:id`,source:"query",handler:p.handleGet}),A.push({api:"crud",method:"post",path:`/${d}`,source:"json",handler:p.handleCreate}),A.push({api:"crud",method:"put",path:`/${d}/:id`,source:"json",handler:y=>p.handleUpdate(y,false)}),A.push({api:"crud",method:"patch",path:`/${d}/:id`,source:"json",handler:y=>p.handleUpdate(y,true)}),A.push({api:"crud",method:"delete",path:`/${d}/:id`,source:"query",handler:p.handleDelete}),A.push({api:"crud",method:"post",path:`/${d}/batch`,source:"json",handler:p.handleBatch});let E=new Dn({...e,openapi:f!==false?{path:b.path??"/openapi.json",docsPath:b.docsPath??"/docs",info:{title:b.title??"CRUD API",version:b.version??"1.0.0"},docsAuth:b.docsAuth}:void 0,basePath:t,api:"crud",routes:A,middlewares:[async(d,y)=>{if(d.req.method==="OPTIONS")return d.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":T,"Access-Control-Max-Age":"86400","Access-Control-Allow-Origin":"*","Access-Control-Allow-Credentials":"true"});d.header("Access-Control-Allow-Origin","*"),d.header("Access-Control-Allow-Credentials","true"),await y();},...e.middlewares||[]]});if(f!==false&&(E.buildOpenApiSpec=I),o!==false){let{securityHeaders:d}=(kn(),Vs(ms)),y=o===void 0?{csp:false}:o;E.hono.use("*",async(i,g)=>{let m=d(y);await new Promise(C=>{let k=i.req.raw;m(k,{setHeader:(P,$)=>i.header(P,$),removeHeader:P=>i.res.headers.delete(P)},()=>C());}),await g();});}let x=E.nodeHandler;return x.spec=I,a&&(x.httpsOptions=a),x}function zs(e,t){if(!t.onRequest)return e;let n=e.httpsOptions??t.httpsOptions,r=n?t.onRequest(n,e):t.onRequest(e),o=e.spec;return typeof o=="function"&&(r.spec=o),r}function qs(e,t,n){let r={},o=e?.rawMapping;for(let[s,a]of Object.entries(t)){if(!a)continue;if(!(o?s in o:!!e[s]))throw new Error(`[createServers.${n}] Unknown repo "${s}" \u2014 not present in the registry passed to createServers().`);let c=o?dn(o[s],()=>e[s]):e[s];r[s]={...a,repo:c};}return r}function Us(e,t={}){return {admin(n){let r=qs(e,n.repos,"admin"),o=gs({...n,repos:r,httpsOptions:n.httpsOptions??t.httpsOptions});return zs(o,t)},crud(n){let r=qs(e,n.repos,"crud"),o=Bs({...n,repos:r,httpsOptions:n.httpsOptions??t.httpsOptions,actorResolver:n.actorResolver??t.actorResolver});return zs(o,t)},sync(n){let r=t.triggerOptions||n.triggerOptions?{...t.triggerOptions,...n.triggerOptions}:void 0,o={...n,...r?{triggerOptions:r}:{}};return t.onRequest&&o.admin&&!o.admin.onRequest&&(o.admin={...o.admin,onRequest:t.onRequest,httpsOptions:o.admin.httpsOptions??t.httpsOptions}),Uo(e,o)},meilisearchAdapter(n){return ()=>new bn(n)},history(n){let r=t.triggerOptions||n.triggerOptions?{...t.triggerOptions,...n.triggerOptions}:void 0,o={...n,...r?{triggerOptions:r}:{}};return Ao(e,o)}}}kn();function gf(e){return t=>({...t,schema:e,type:null,documentRef:null,update:null})}function bf(e,t){let n={...e};for(let r in t)t[r]&&(n[r]={...e[r],relationalKeys:t[r]});return n}var Kr=class{constructor(t,n){this.allRepositories={};this.initialized=false;this.dbFactory=t,this.mapping=n;}get db(){return this._db??(this._db=this.dbFactory())}get rawMapping(){return this.mapping}ensureInitialized(){this.initialized||(this.initializeRepositories(),this.initialized=true);}initializeRepositories(){let t=this.db;for(let n of Object.keys(this.mapping))this.allRepositories[n]=nr(t,this.mapping[n],{});for(let n of Object.keys(this.mapping))this.allRepositories[n]=nr(t,this.mapping[n],this.allRepositories);}getRepository(t){return this.ensureInitialized(),this.allRepositories[t]}};function wf(e,t){let n=new Kr(e,t),r=Object.keys(t);return new Proxy(n,{get(o,s){return typeof s=="string"&&s in t?o.getRepository(s):o[s]},has(o,s){return typeof s=="string"&&s in t?true:s in o},ownKeys(){return r},getOwnPropertyDescriptor(o,s){if(typeof s=="string"&&s in t)return {configurable:true,enumerable:true,writable:false}}})}export{Ge as DEFAULT_HISTORY_COMMENT_HEADER,Ve as DEFAULT_HISTORY_REASON_HEADER,Qn as DEFAULT_HISTORY_SHADOW_KEY,Me as MiniRouter,Kr as RepositoryMapping,$n as applyEffects,Yt as applyMutations,je as applyPaginationQueryOptions,Cn as applyRules,jn as buildAndCountQuery,Qe as buildAndExecuteQuery,bf as buildRepositoryRelations,zn as coerceToDate,Te as computeDeepDiff,Wn as createActorContextMiddleware,Kn as createActorResolver,Lr as createAfterUpdateEffects,qr as createBeforeCreateMutations,Pr as createBeforeRules,zr as createBeforeUpdateMutations,Ur as createEffects,Br as createMutations,qn as createPaginationIterator,gf as createRepositoryConfig,wf as createRepositoryMapping,Or as createRules,Us as createServers,lo as defaultActorResolver,rn as executePaginatedQuery,Zn as getActorResolverHeaders,ut as getCurrentActor,nn as getDateHandling,tn as normalizeTimestamps,fa as setDateHandling,xa as setRequestActorMeta,wa as withActor};//# sourceMappingURL=index.js.map
1173
1173
  //# sourceMappingURL=index.js.map