@lpdjs/firestore-repo-service 3.0.17 → 3.0.19
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/{actor-context-DQZgWqj3.d.cts → actor-context-zNobm6nG.d.cts} +17 -2
- package/dist/{actor-context-DQZgWqj3.d.ts → actor-context-zNobm6nG.d.ts} +17 -2
- package/dist/{create-servers-DKg5Yg2d.d.cts → create-servers-DydjOOOS.d.cts} +3 -3
- package/dist/{create-servers-BQ7pxnG0.d.ts → create-servers-bMJVVjPj.d.ts} +3 -3
- package/dist/{effects-B8aIXMZ2.d.ts → effects-BYvL8JUK.d.ts} +1 -1
- package/dist/{effects-CqJSneNZ.d.cts → effects-DcM19dy4.d.cts} +1 -1
- package/dist/history/index.cjs +1 -1
- package/dist/history/index.cjs.map +1 -1
- package/dist/history/index.d.cts +1 -1
- package/dist/history/index.d.ts +1 -1
- package/dist/history/index.js +1 -1
- package/dist/history/index.js.map +1 -1
- package/dist/index.cjs +55 -55
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.js +55 -55
- package/dist/index.js.map +1 -1
- package/dist/llms-full.txt +30 -1
- package/dist/llms.txt +1 -1
- package/dist/servers/admin/index.d.cts +3 -3
- package/dist/servers/admin/index.d.ts +3 -3
- package/dist/servers/crud/index.cjs +2 -2
- package/dist/servers/crud/index.cjs.map +1 -1
- package/dist/servers/crud/index.d.cts +6 -6
- package/dist/servers/crud/index.d.ts +6 -6
- package/dist/servers/crud/index.js +2 -2
- package/dist/servers/crud/index.js.map +1 -1
- package/dist/servers/hono/index.cjs +12 -12
- package/dist/servers/hono/index.cjs.map +1 -1
- package/dist/servers/hono/index.d.cts +4 -4
- package/dist/servers/hono/index.d.ts +4 -4
- package/dist/servers/hono/index.js +12 -12
- package/dist/servers/hono/index.js.map +1 -1
- package/dist/servers/index.cjs +63 -63
- package/dist/servers/index.cjs.map +1 -1
- package/dist/servers/index.d.cts +6 -6
- package/dist/servers/index.d.ts +6 -6
- package/dist/servers/index.js +63 -63
- package/dist/servers/index.js.map +1 -1
- package/dist/sync/index.cjs +54 -54
- package/dist/sync/index.cjs.map +1 -1
- package/dist/sync/index.js +54 -54
- package/dist/sync/index.js.map +1 -1
- package/dist/{types-wMBgnYjH.d.ts → types-5Q7JDDba.d.ts} +52 -3
- package/dist/{types-w1rEqs0Z.d.ts → types-BJ6MAavL.d.ts} +1 -1
- package/dist/{types-DgzPoPvx.d.cts → types-BYPdlGSL.d.cts} +52 -3
- package/dist/{types-BDTx8VPg.d.cts → types-XvVG8_9J.d.cts} +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {jsx,jsxs,Fragment}from'hono/jsx/jsx-runtime';import {Timestamp,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 xn=Object.defineProperty;var ps=Object.getOwnPropertyDescriptor;var fs=Object.getOwnPropertyNames;var ys=Object.prototype.hasOwnProperty;var Sr=(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 at=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var kr=(e,t)=>{for(var n in t)xn(e,n,{get:t[n],enumerable:true});},ms=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of fs(t))!ys.call(e,o)&&o!==n&&xn(e,o,{get:()=>t[o],enumerable:!(r=ps(t,o))||r.enumerable});return e};var hs=e=>ms(xn({},"__esModule",{value:true}),e);function V(e){let t=e,n=t._zod?.def?.type;if(n)return na[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=t._def?.typeName;return r||""}function se(e){let t=e;if(t._zod?.def?.innerType)return t._zod.def.innerType;if(t._def?.innerType)return t._def.innerType}function gt(e){let t=e,n=t._zod?.def?.in;if(n)return n;if(t._def?.schema)return t._def.schema}function Qt(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}function eo(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 ae(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 bt(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 wt(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 xt(e){let t=e;return Array.isArray(t._zod?.def?.values)?t._zod.def.values[0]:t._def?.value}function vt(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 to(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 na,Je=at(()=>{"use strict";na={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 bo({val:e}){return jsx("span",{class:"text-sm text-base-content/80 font-mono tabular-nums whitespace-nowrap",children:e.toLocaleString()})}function Sa({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 et({val:e,mismatch:t}){let n=Un(e);return t?jsxs("span",{class:"inline-flex items-start gap-0.5",children:[n,jsx(Sa,{message:t})]}):n}function Un(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(bo,{val:e});if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")return jsx(bo,{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:Un(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:Un(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 rn=at(()=>{"use strict";});function Ct(e){if(!e)return "unknown";let t=Ln(e);switch(V(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 Ln(e){let t=V(e);if(t==="ZodOptional"||t==="ZodNullable"||t==="ZodDefault"){let n=se(e);return n?Ln(n):e}return e}function At(e,t){if(!e)return;let n=t.split("."),r=e;for(let o of n){if(!r)return;let s=Ln(r);if(V(s)!=="ZodObject")return;r=ae(s)[o];}return r}function Ea(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 Et(e,t){if(e==="unknown")return null;let n=Ea(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 Wn=at(()=>{"use strict";Je();});var vo={};kr(vo,{PanelMany:()=>Pa,PanelOne:()=>Oa,RightPanel:()=>Vn});function Oa({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`,c=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(i=>{let u=e[i],f=c[i],y=f?Et(f,u):null;return jsxs(Fragment,{children:[jsx("dt",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide pt-0.5",children:i}),jsx("dd",{class:"min-w-0",children:jsx(et,{val:u,mismatch:y})})]})})})]})}function Pa({docs:e,repoName:t,basePath:n,fk:r,fv:o,columns:s,schema:a,pagination:c}){let i=`${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:i,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((f,y)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:f},y)),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((f,y)=>{let w=String(f.docId??f.id??""),b=`${n}/${t}/${encodeURIComponent(w)}/edit`;return jsxs("tr",{class:"hover",children:[s.map((g,T)=>{let R=f[g],O=u[g],A=O?Et(O,R):null;return jsx("td",{class:"align-top py-1.5",children:jsx(et,{val:R,mismatch:A})},T)}),jsx("td",{class:"text-right py-1.5",children:jsx("a",{href:b,class:"btn btn-xs btn-ghost",children:"Edit"})})]},y)})})]})}),(c.hasPrev||c.hasNext)&&jsxs("div",{class:"flex justify-center items-center gap-2",children:[c.hasPrev?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"prev","data-cursor":c.prevCursor,children:"\u2190 Previous"}):jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"\u2190 Previous"}),c.hasNext?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"next","data-cursor":c.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]=Ct(At(e,r));return n}var Vn,Gn=at(()=>{"use strict";rn();Wn();Vn=({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 Ho={};kr(Ho,{DEFAULT_HTML_CSP:()=>ir,securityHeaders:()=>ln});function ln(e={}){let t=e.csp===void 0?ir: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,c)=>{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 c();}}var Mo,_o,ir,dn=at(()=>{"use strict";Mo="https://cdn.jsdelivr.net",_o="https://www.gstatic.com",ir=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${Mo} ${_o}`,`style-src 'self' 'unsafe-inline' ${Mo}`,`connect-src 'self' ${_o} 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("; ");});function gs(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function it(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 ct(e){let[,t,n]=e;return (t==="in"||t==="array-contains-any")&&Array.isArray(n)&&n.length>30}function jt(e){let[t,n,r]=e;return ct(e)?gs(r,30).map(s=>[t,n,s]):[e]}function Ce(e,t){let n=e;for(let[r,o,s]of t)n=n.where(String(r),o,s);return n}async function Cr(e){let t=await Promise.all(e.map(o=>o.get())),n=new Map;t.forEach(o=>{o.docs.forEach(s=>{n.has(s.id)||n.set(s.id,s);});});let r=t[0];if(!r)throw new Error("No snapshots returned");return {...r,docs:Array.from(n.values()),size:n.size,empty:n.size===0}}async function Fe(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 it(e,t).get();if(!t.where.some(ct)){let y=Ce(e,t.where);return y=it(y,t),y.get()}let i=t.where.map(jt),f=lt(i).map(y=>{let w=Ce(e,y);return w=it(w,t),w});return Cr(f)}let o=t.where??[],s=[...t.orWhere?.map(c=>[c])??[],...t.orWhereGroups??[]],a=[];for(let c of s){let i=[...o,...c];if(i.some(ct)){let f=i.map(jt),w=lt(f).map(b=>{let g=Ce(e,b);return g=it(g,t),g});a.push(...w);}else {let f=Ce(e,i);f=it(f,t),a.push(f);}}return Cr(a)}function lt(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=lt(n),o=[];for(let s of t)for(let a of r)o.push([s,...a]);return o}async function vn(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 {count:(await e.count().get()).data().count,isExact:true};if(!t.where.some(ct))return {count:(await Ce(e,t.where).count().get()).data().count,isExact:true};let f=t.where.map(jt),y=lt(f);return {count:(await Promise.all(y.map(g=>Ce(e,g).count().get()))).reduce((g,T)=>g+T.data().count,0),isExact:true}}let o=t.where??[],s=[...t.orWhere?.map(u=>[u])??[],...t.orWhereGroups??[]],a=[];for(let u of s){let f=[...o,...u];if(!f.some(ct))a.push(Ce(e,f));else {let w=f.map(jt),g=lt(w).map(T=>Ce(e,T));a.push(...g);}}return {count:(await Promise.all(a.map(u=>u.count().get()))).reduce((u,f)=>u+f.data().count,0),isExact:false}}var Rn="preserve";function bs(e){Rn=e;}function zt(){return Rn}function ws(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function Tn(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(ws(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 xs(e){if(typeof e!="object"||e===null)return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Nt(e){if(e instanceof Timestamp)return e.toDate();if(Array.isArray(e))return e.map(t=>Nt(t));if(xs(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Nt(r);return t}return e}function X(e){return Rn==="normalize"?Nt(e):e}function Er(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Te(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Ae(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 Bt(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([Fe(e,n),t.withTotal?vn(e,t):Promise.resolve(void 0)]),s=r.docs,a=s.length>t.pageSize,c=a?s.slice(0,t.pageSize):s,i=c.map(f=>X({...f.data(),docId:f.id})),u=t.direction==="prev";return {data:i,nextCursor:u?c.length>0?c[c.length-1]:void 0:a?c[c.length-1]:void 0,prevCursor:u?a?c[0]:void 0:c[0],hasNextPage:u?!!t.cursor:a,hasPrevPage:u?a:!!t.cursor,pageSize:i.length,...o!==void 0?{totalCount:o.count,totalCountIsExact:o.isExact}:{}}}async function*Sn(e,t){let n,r=true;for(;r;){let o=await Bt(e,{...t,cursor:n,direction:"next"});yield o,r=o.hasNextPage,n=o.nextCursor;}}var kn=Symbol.for("@lpdjs/firestore-repo-service:actorContext"),Cn=globalThis,qt=Cn[kn]??(Cn[kn]=new AsyncLocalStorage);function Rs(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 Or(e,t){for(let n of t){let r=Rs(e,n);if(typeof r=="string"&&r.length>0)return r;if(typeof r=="number")return String(r)}return null}function Pr(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 An(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.extras;return c=>{let i=null,u=c?.get;if(typeof u=="function")for(let b of t){let g=u.call(c,b);if(g&&typeof g=="object"){i=g;break}}let f=Pr(c,o),y=Pr(c,s),w=a?a(c,i):void 0;return i?{userId:Or(i,n),userEmail:Or(i,r),...f!==void 0?{reason:f}:{},...y!==void 0?{comment:y}:{},...w?{extras:w}:{}}:f===void 0&&y===void 0&&!w?null:{...f!==void 0?{reason:f}:{},...y!==void 0?{comment:y}:{},...w?{extras:w}:{}}}}var Ir=An();function Ts(e){if(e)return typeof e=="function"?e:An(e)}function En(e){let t=Ts(e);return async(n,r)=>{await qt.run({c:n,resolver:t},async()=>{await r();});}}function Ve(){let e=qt.getStore();if(!e)return null;let t=null;if(e.c)try{t=(e.resolver??Ir)(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 Ss(e,t){return qt.run({override:{...e}},t)}function ks(e){let t=qt.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 On="_historyMeta";function Ge(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():On,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 fe(e){return Ge(e)?.key??null}function Pn(e){let t=Ge(e);return t?[t.key]:[]}function re(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 ue(e,t){if(!t?.enabled||t.autoInjectMeta===false)return;let n=Ge(t);if(!n)return;let r=Ve(),o=t.fallbackActor??{},s=r?.userId!==void 0?r.userId:o.userId??null,a=r?.userEmail!==void 0?r.userEmail:o.userEmail??null,c=r?.reason??null,i=r?.comment??null,u=r?.extras&&Object.keys(r.extras).length>0?r.extras:null,f={},{fields:y}=n;y.userId!==false&&(f[y.userId]=s),y.userEmail!==false&&(f[y.userEmail]=a),y.reason!==false&&(f[y.reason]=c),y.comment!==false&&(f[y.comment]=i),y.extras!==false&&(f[y.extras]=u),e[n.key]=f;}function ut(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 pt(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(!pt(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)||!pt(e[s],t[s],n))return false;return true}return false}function Kt(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??{},c=new Set([...Object.keys(s),...Object.keys(a)]),i={};for(let u of c){if(r.has(u)||o&&!o.has(u))continue;let f=s[u],y=a[u];pt(f,y)||(i[u]={oldValue:f===void 0?null:f,newValue:y===void 0?null:y,type:{old:ut(f),new:ut(y)}});}return i}var Cs=5;function As(e){return e.schemaVersion===2}function Dr(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 Es(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 Os(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 Ps(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?Dr(r):ut(t),new:o?Dr(o):ut(n)}}}function Is(e){let t=Ps(e),n=Os(e);return {historyDocId:e.historyDocId,historyToObjectId:e.historyToObjectId,historySetAt:e.historySetAt,schemaVersion:1,operation:"update",meta:n,changes:{[e.field]:t}}}function Ds(e,t,n){return Math.abs(e.toMillis()-t.toMillis())<=n}function $s(e,t){return (e.userId??null)===(t.userId??null)}function $r(e,t={}){let n=t.groupToleranceMs??Cs,r=[];for(let o of e){if(As(o)){r.push(Es(o));continue}let a=Is(o),c=r[r.length-1];c&&c.schemaVersion===1&&Ds(c.historySetAt,a.historySetAt,n)&&$s(c.meta,a.meta)?Object.assign(c.changes,a.changes):r.push(a);}return r}var _s=7e5;function ft(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,c)=>c instanceof Timestamp?c.toMillis():c),"utf8")}catch{return 0}};if(o(r.changes)>_s){let s={};for(let[a,c]of Object.entries(r.changes)){let i=o(c.oldValue),u=o(c.newValue);s[a]={oldValue:i>5e4?"[truncated]":c.oldValue,newValue:u>5e4?"[truncated]":c.newValue,type:c.type};}r.changes=s,r._truncated=true;}return r}async function yt(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 Zt(e,t){let n=e??{},r={},o=Ge(t);if(o){let y=n[o.key];if(y&&typeof y=="object"&&!Array.isArray(y)){let w=y,b=A=>{if(A===false||!(A in w))return;let h=w[A];return h==null?null:String(h)},g=b(o.fields.userId);g!==void 0&&(r.userId=g);let T=b(o.fields.userEmail);T!==void 0&&(r.userEmail=T);let R=b(o.fields.reason);R!==void 0&&(r.reason=R);let O=b(o.fields.comment);if(O!==void 0&&(r.comment=O),o.fields.extras!==false){let A=w[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=y=>{if(!y)return;let w=n[y];return w===void 0||w===null?null:String(w)},c=a(s.userId);c!==void 0&&(r.userId=c);let i=a(s.userEmail);i!==void 0&&(r.userEmail=i);let u=a(s.reason);u!==void 0&&(r.reason=u);let f=a(s.comment);if(f!==void 0&&(r.comment=f),s.extras&&s.extras.length>0){let y={},w=false;for(let b of s.extras)b in n&&(y[b]=n[b],w=true);w&&(r.extras=y);}return r}function Ut(e){let t=[],n=Ge(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 Hs="history",Fs=50;function Dn(e,t,n){return e(...n).collection(t)}function Mr(e){return String(e[e.length-1]??"")}function _r(e,t,n,r){if(!r?.enabled)return null;let o=r.subcollection??Hs;async function s(...b){let g={},T=b,R=b[b.length-1];R!==null&&typeof R=="object"&&!(R instanceof Timestamp)&&("limit"in R||"cursor"in R||"direction"in R)&&(g=R,T=b.slice(0,-1));let O=Dn(e,o,T),A=g.direction??"desc",h=O.orderBy("historySetAt",A);return g.cursor&&(h=h.startAfter(g.cursor)),g.limit&&g.limit>0&&(h=h.limit(g.limit)),(await h.get()).docs.map(p=>({id:p.id,data:p.data()}))}async function a(...b){let g={},T=b,R=b[b.length-1];R!==null&&typeof R=="object"&&!(R instanceof Timestamp)&&("limit"in R||"cursor"in R||"direction"in R||"fields"in R||"operations"in R)&&(g=R,T=b.slice(0,-1));let O=g.limit??Fs,A=Math.max(O,Math.min(O*8,500)),h=await s(...T,{limit:A,cursor:g.cursor,direction:g.direction??"desc"}),m=$r(h.map(p=>p.data));if(g.fields&&g.fields.length>0){let p=new Set(g.fields);m=m.filter(d=>Object.keys(d.changes).some(l=>p.has(l)));}if(g.operations&&g.operations.length>0){let p=new Set(g.operations);m=m.filter(d=>p.has(d.operation));}return m.slice(0,O)}async function c(...b){let g=b[b.length-1],T={},R,O;return g!==null&&typeof g=="object"&&!(g instanceof Timestamp)?(T=g,R=b[b.length-2],O=b.slice(0,-2)):(R=g,O=b.slice(0,-1)),a(...O,{...T,fields:[R]})}async function i(...b){let g=b[b.length-1],T={},R,O;return g!==null&&typeof g=="object"&&!(g instanceof Timestamp)?(T=g,R=b[b.length-2],O=b.slice(0,-2)):(R=g,O=b.slice(0,-1)),a(...O,{...T,operations:[R]})}function u(b){let g={title:b.title,display:b.display??true};return b.description!==void 0&&(g.description=b.description),b.key!==void 0&&(g.key=b.key),b.data!==void 0&&(g.data=b.data),g}function f(){let b=Ve(),g=r.fallbackActor??{},T=b?.userId!==void 0?b.userId:g.userId??null,R=b?.userEmail!==void 0?b.userEmail:g.userEmail??null;return {userId:T,userEmail:R,...b?.reason!==void 0?{reason:b.reason}:{},...b?.comment!==void 0?{comment:b.comment}:{},...b?.extras&&Object.keys(b.extras).length>0?{extras:b.extras}:{}}}async function y(...b){let g=b[b.length-1],T=b.slice(0,-1),R=Mr(T),O=Kt(g.before??{},g.after??{},{include:r.include,exclude:r.exclude,metaFields:Ut(r),systemKeys:t});if(g.operation==="update"&&Object.keys(O).length===0)return null;let A=Zt(g.after??g.before??null,r),h=Ve(),p={...h?{...h.userId!==void 0?{userId:h.userId}:{},...h.userEmail!==void 0?{userEmail:h.userEmail}:{},...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}:{}}:{},...A,...g.meta??{}},d=g.custom?u(g.custom):void 0,l=ft({entityId:R,operation:g.operation,changes:O,meta:p,custom:d,config:r}),x=Dn(e,o,T),v=await yt(x,l,r,{repoName:n,docId:R,before:g.before??null,after:g.after??null});return !v.written||!v.entry?null:{historyDocId:v.entry.historyDocId,historyToObjectId:v.entry.historyToObjectId,historySetAt:v.entry.historySetAt,schemaVersion:2,operation:v.entry.operation,meta:v.entry.meta,...v.entry.custom?{custom:v.entry.custom}:{},changes:v.entry.changes}}async function w(...b){let g=b[b.length-1],T=b.slice(0,-1),R=Mr(T),O=u(g),A={...f(),...g.meta??{}},h=ft({entityId:R,operation:"custom",changes:{},meta:A,custom:O,config:r}),m=Dn(e,o,T),p=await yt(m,h,r,{repoName:n,docId:R,before:null,after:null});return !p.written||!p.entry?null:{historyDocId:p.entry.historyDocId,historyToObjectId:p.entry.historyToObjectId,historySetAt:p.entry.historySetAt,schemaVersion:2,operation:p.entry.operation,meta:p.entry.meta,...p.entry.custom?{custom:p.entry.custom}:{},changes:p.entry.changes}}return {list:a,raw:s,byField:c,byOperation:i,recordManual:y,recordCustom:w}}function Hr(e){return {count:async(t={})=>{let n=e;return n=Ae(n,t),(await n.count().get()).data().count},sum:async(t,n={})=>{let r=e;r=Ae(r,n);let o=await r.get(),s=0;return o.forEach(a=>{let c=a.data()[t];typeof c=="number"&&(s+=c);}),s},average:async(t,n={})=>{let r=e;r=Ae(r,n);let o=await r.get();if(o.empty)return null;let s=0,a=0;return o.forEach(c=>{let i=c.data()[t];typeof i=="number"&&(s+=i,a++);}),a>0?s/a:null}}}function Fr(e,t,n,r,o,s,a){let c=()=>new Date;return {create:()=>{let i=e.batch();return {batch:i,set:(...u)=>{let f=u[u.length-1],y=typeof f=="object"&&f!==null&&"merge"in f,w=y?u[u.length-2]:u[u.length-1],b=y?u.slice(0,-2):u.slice(0,-1),g=y?f:{merge:true},T=t(...b),R={...w},O=b[b.length-1];n&&O&&(R[n]=O),r&&(R[r]=T.path),o&&R[o]===void 0&&(R[o]=c()),s&&(R[s]=c()),ue(R,a),i.set(T,R,g);},update:(...u)=>{let f=u.pop(),w=t(...u),b={...f};s&&(b[s]=c()),ue(b,a),i.update(w,b);},delete:(...u)=>{let f=t(...u);i.delete(f);},commit:async()=>{await i.commit();}}}}}var js=new Set([4,8,10,13,14]);function $n(e,t){let n=[],r=t.maxAttempts??5;return e.onWriteError(o=>{let s=o?.code;if(o.failedAttempts<r&&s!==void 0&&js.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 Mn(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 jr(e,t,n,r){let o=()=>new Date;return {set:async(s,a={})=>{let c=e.bulkWriter(),i=$n(c,a);for(let u of s){if(!u)continue;let{docRef:f,data:y,merge:w=true}=u,b={...y};t&&b[t]===void 0&&(b[t]=o()),n&&(b[n]=o()),ue(b,r),c.set(f,b,{merge:w});}return await c.close(),Mn(i,a)},update:async(s,a={})=>{let c=e.bulkWriter(),i=$n(c,a);for(let u of s){if(!u)continue;let{docRef:f,data:y}=u,w={...y};n&&(w[n]=o()),ue(w,r),c.update(f,w);}return await c.close(),Mn(i,a)},delete:async(s,a={})=>{let c=e.bulkWriter(),i=$n(c,a);for(let u of s)u&&c.delete(u);return await c.close(),Mn(i,a)}}}var _n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Ee(){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>=_n.length*4||(e+=_n.charAt(r%_n.length));}}return e}function Hn(e){return e.match(/^\{([^}]+)\}$/)?.[1]?.trim()||null}function Se(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(y=>y.trim()).filter(Boolean);if(r.length===0)return {rawPath:e,collectionId:e,collectionPath:e,parentKeys:[],documentPathTemplate:null,hasTemplate:false};if(r.length===1){let y=r[0];return {rawPath:e,collectionId:y,collectionPath:y,parentKeys:[],documentPathTemplate:n?null:`${y}/{${t}}`,hasTemplate:e.includes("{")&&e.includes("}")}}let o=r.length%2===0,s=o?r.slice(0,-1):r,a=s[s.length-1],c=s.join("/"),u=s.slice(0,-1).map(Hn).filter(y=>y!==null),f=o?r.join("/"):`${c}/{${t}}`;return {rawPath:e,collectionId:a,collectionPath:c,parentKeys:u,documentPathTemplate:f,hasTemplate:true}}function Nr(e,t,n){let r=t.split("/").map(i=>i.trim()).filter(Boolean),o=0,s=[];for(let i of r){let u=Hn(i);if(u!==null){let f=n[o++];if(typeof f!="string"||f.trim()==="")throw new Error(`Missing or empty path parameter "${u}" when resolving document reference for "${t}".`);s.push(f);}else s.push(i);}let a=e;if(typeof a?.collection=="function"&&s.length>=2){let i=a,u=true;for(let f=0;f<s.length;f+=2){let y=s[f],w=s[f+1];if(typeof i?.collection!="function"){u=false;break}let b=i.collection(y);if(typeof b?.doc!="function"){u=false;break}i=b.doc(w);}if(u&&i&&i!==a)return i}let c=s.join("/");if(typeof a?.doc=="function")return a.doc(c);if(typeof a?.collection=="function"&&s.length>=2){let i=s.slice(0,-1).join("/"),u=s[s.length-1],f=a.collection(i);return typeof f?.doc=="function"?f.doc(u):f}throw new Error(`Cannot resolve DocumentReference for "${c}": 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,c=n&&typeof e[n]=="string"&&e[n]?e[n]:void 0;if(c&&s){let i=c.split("/").filter(Boolean),u=s.split("/").filter(Boolean);if(i.length===u.length){let f=[];for(let y=0;y<u.length;y++)Hn(u[y])!==null&&f.push(i[y]);if(f.length>0)return f}}if(o&&o.length>0){let i=o.length+1;if(c){let f=c.split("/").filter(Boolean),y=[];for(let w=1;w<f.length;w+=2)y.push(f[w]);if(y.length>=i)return y.slice(y.length-i)}let u=r?e[r]:void 0;if(typeof u=="string"&&u.trim()!==""){let f=[],y=true;for(let w of o){let b=e[w];if(typeof b=="string"&&b.trim()!=="")f.push(b);else {y=false;break}}if(y)return [...f,u]}}if(c){let i=c.split("/").filter(Boolean),u=[];for(let f=1;f<i.length;f+=2)u.push(i[f]);if(u.length>0)return !a&&(!o||o.length===0)?[u[u.length-1]]:u}}function zr(e,t,n,r,o,s,a=[],c,i){let u=()=>new Date,f=fe(i);return {create:async(...T)=>{let R=T[T.length-1],O=T.slice(0,-1);if(!R||typeof R!="object")throw new Error("Create data payload must be an object.");let A,h,m=typeof R[n]=="string"&&R[n].trim()!=="",p={...R};if(o&&p[o]===void 0&&(p[o]=u()),s&&(p[s]=u()),ue(p,i),e&&O.length===0)if(m){h=R[n],A=typeof e.doc=="function"?e.doc(h):t(h),p[n]=h;let d=r&&A?.path?{...p,[r]:A.path}:p;await A.set(d),r&&A?.path&&(p[r]=A.path);}else if(typeof e.add=="function"){A=await e.add(p),h=A.id,p[n]=h;let d={[n]:h};r&&A?.path&&(d[r]=A.path,p[r]=A.path),await A.update(d);}else h=Ee(),A=typeof e.doc=="function"?e.doc(h):t(h),p[n]=A?.id??h,r&&A?.path&&(p[r]=A.path),await A.set(p);else {let d=[];if(O.length>0)for(let l=0;l<O.length;l++){let x=O[l];if(typeof x!="string"||x.trim()===""){let v=a[l]??`arg[${l}]`;throw new Error(`Missing or empty parent key "${v}" for subcollection create()`)}d.push(x);}else if(a.length>0){let l=[];for(let x of a){let v=R[x];typeof v=="string"&&v.trim()!==""?d.push(v):l.push(x);}if(l.length>0){let x=je(R,{pathKey:r,documentKey:n,parentKeys:a,documentPathTemplate:c,isGroup:true});if(x&&x.length>=a.length)d=x.slice(0,a.length);else throw new Error(`Missing or empty required parent key(s) in data for subcollection create(): ${l.join(", ")}`)}}else if(r&&typeof R[r]=="string"&&R[r].trim()!==""){let l=je(R,{pathKey:r,documentKey:n,parentKeys:a,documentPathTemplate:c,isGroup:true});l&&l.length>1&&(d=l.slice(0,-1));}if(d.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.");h=m?R[n]:Ee(),A=t(...d,h),p[n]=A?.id??h,r&&A?.path&&(p[r]=A.path),await A.set(p);}if(typeof A?.get=="function"){let d=await A.get(),l=typeof d?.data=="function"?d.data():p;return re(X(l??p),f)}return re(X(p),f)},set:async(...T)=>{let R=T[T.length-1],O=typeof R=="object"&&R!==null&&"merge"in R,A=O?T[T.length-2]:T[T.length-1],h=O?T.slice(0,-2):T.slice(0,-1),m=O?R:{merge:true},p={...A};o&&p[o]===void 0&&(p[o]=u()),s&&(p[s]=u()),ue(p,i);let d=t(...h),l=h[h.length-1];if(n&&l!=null&&(p[n]=l),r&&(p[r]=d.path),await d.set(p,m),typeof d?.get=="function"){let x=await d.get(),v=typeof x?.data=="function"?x.data():p;return re(X(v??p),f)}return re(X(p),f)},update:async(...T)=>{let R=T.pop(),O=T,A={...R};s&&(A[s]=u()),ue(A,i);let h=t(...O);await h.update(A);let m=await h.get();return re(X(m.data()),f)},delete:async(...T)=>{await t(...T).delete();}}}function Br(e,t,n,r,o,s=null){let a={};return a.byList=async(c,i,u="in",f={})=>{if(i.length===0)return [];let y=[],w=Er(i,30);for(let b of w){let g=e;g=g.where(c,u,b),f.select&&f.select.length>0&&(g=g.select(...f.select.map(R=>String(R)))),(await g.get()).forEach(R=>{let O=re(X(R.data()),s);y.push(f.returnDoc?{data:O,doc:R}:O);});}return y},t.forEach(c=>{let i=`by${Te(String(c))}`;a[i]=async(...u)=>{let f={},y=u[u.length-1];if(typeof y=="boolean"?(f={returnDoc:y},u=u.slice(0,-1)):typeof y=="object"&&y!==null&&!Array.isArray(y)&&(f=y,u=u.slice(0,-1)),String(c)===o&&(u.length>1||u.length===1&&n!==null)){let A=await r(...u).get();if(!A.exists)return null;let h=re(X(A.data()),s);return f.returnDoc?{data:h,doc:A}:h}let w=u[0];if(w===void 0)return null;let b=e;b=b.where(String(c),"==",w).limit(1),f.select&&f.select.length>0&&(b=b.select(...f.select.map(O=>String(O))));let g=await b.get();if(g.empty)return null;let T=g.docs[0];if(!T)return null;let R=re(X(T.data()),s);return f.returnDoc?{data:R,doc:T}:R};}),a}function qr(e,t,n,r,o=null){let s={},a=i=>re(X(i),o),c=async(i,u)=>{if(!n||!r||u.length===0)return i;let f=u.map(y=>typeof y=="string"?{key:y}:{key:y.relation,select:y.select});return Promise.all(i.map(async y=>{let w=await Promise.all(f.map(async({key:g,select:T})=>{let R=n[g];if(!R)return [g,void 0];let O=r[R.repo];if(!O)return [g,void 0];let A=R.sourceKey||g,h=y[A];if(h==null)return [g,R.type==="one"?null:[]];let m=T?{select:T}:void 0;try{if(R.type==="one"){let p=`by${Te(R.key)}`,d=typeof O.get?.[p]=="function"?await O.get[p](h,m):null;return [g,d]}else {let p=`by${Te(R.key)}`,d=typeof O.query?.[p]=="function"?await O.query[p](h,m):[];return [g,d]}}catch(p){return console.error(`[include] Error populating "${g}":`,p),[g,R.type==="one"?null:[]]}})),b={};for(let[g,T]of w)g!==void 0&&(b[g]=T);return {...y,populated:b}}))};return t.forEach(i=>{let u=`by${Te(i)}`;s[u]=async(f,y={})=>{let w={...y,where:[[i,"==",f],...y.where??[]]};return (await Fe(e,w)).docs.map(g=>a(g.data()))};}),s.by=async i=>(await Fe(e,i)).docs.map(f=>a(f.data())),s.getAll=async(i={})=>(await Fe(e,i)).docs.map(f=>a(f.data())),s.onSnapshot=(i,u,f)=>Ae(e,i).onSnapshot(w=>{u(w.docs.map(b=>a(b.data())));},f),s.paginate=async i=>{let{include:u,...f}=i,y=await Bt(e,f),w=o?{...y,data:y.data.map(b=>re(b,o))}:y;if(u&&u.length>0){let b=await c(w.data,u);return {...w,data:b}}return w},s.paginateAll=async function*(i){let{include:u,...f}=i;for await(let y of Sn(e,f)){let w=o?{...y,data:y.data.map(b=>re(b,o))}:y;if(u&&u.length>0){let b=await c(w.data,u);yield {...w,data:b};}else yield w;}},s}function Kr(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 i=r;o=[i.relation],i.select&&(s[i.relation]=i.select);}else if("relations"in r){let i=r;o=Array.isArray(i.relations)?i.relations:[i.relations],s=i.select??{};}else o=[];else o=Array.isArray(r)?r:[r];let a=await Promise.all(o.map(async i=>{let u=e.relationalKeys?.[i];if(!u)return console.warn(`[populate] Relation "${i}" not found in config`),[i,void 0];let f=t[u.repo];if(!f)return console.warn(`[populate] Repository "${u.repo}" not found in mapping`),[i,void 0];let y=u.sourceKey||i,w=n[y];if(w==null)return [i,u.type==="one"?null:[]];let b=s[i],g=b?{select:b}:void 0;try{if(u.type==="one"){let T=`by${Te(u.key)}`,R=typeof f.get?.[T]=="function"?await f.get[T](w,g):null;return [i,R]}else {let T=`by${Te(u.key)}`,R=typeof f.query?.[T]=="function"?await f.query[T](w,g):[];return [i,R]}}catch(T){return console.error(`[populate] Error populating "${i}":`,T),[i,u.type==="one"?null:[]]}})),c={};for(let[i,u]of a)u!==void 0&&(c[i]=u);return {...n,populated:c}}}}var Bs=new Set([4,8,10,13,14]);function Zr(e,t,n,r,o,s){let a=()=>new Date;return {backfillKeys:async(i={})=>{let{overwriteCreated:u=false,touchUpdated:f=true,overwritePath:y=false,pageSize:w=300,dryRun:b=false,maxAttempts:g=5,onError:T,onSuccess:R}=i,O=[],A=0,h=0,m=0,p=b?null:e.bulkWriter();p&&(p.onWriteError(l=>{let x=l?.code;if(l.failedAttempts<g&&x!==void 0&&Bs.has(x))return true;let v={path:l?.documentRef?.path??"(unknown)",error:l};return O.push(v),T?.(v),false}),R&&p.onWriteResult(l=>R(l.path)));let d;for(;;){let l=t.orderBy(FieldPath.documentId());d&&(l=l.startAfter(d)),l=l.limit(w);let x=await l.get();if(x.empty)break;for(let v of x.docs){A++;let P=v.data(),S={};if(n&&P[n]==null&&(S[n]=v.id),r&&(y||P[r]==null)&&P[r]!==v.ref.path&&(S[r]=v.ref.path),o&&(u||P[o]==null)&&(S[o]=a()),f&&s&&P[s]==null&&(S[s]=a()),Object.keys(S).length===0){m++;continue}h++,p&&p.set(v.ref,S,{merge:true});}if(x.size<w)break;d=x.docs[x.docs.length-1];}return p&&await p.close(),{scanned:A,written:h,skipped:m,failures:O}}}}function Ur(e,t,n,r,o,s,a){let c=()=>new Date,i=fe(a);return {run:async u=>e.runTransaction(async f=>u({get:async(...w)=>{let b=t(...w),g=await f.get(b);return g.exists?re(X({...g.data(),docId:g.id}),i):null},set:(...w)=>{let b=w[w.length-1],g=typeof b=="object"&&b!==null&&"merge"in b,T=g?w[w.length-2]:w[w.length-1],R=g?w.slice(0,-2):w.slice(0,-1),O=g?b:{merge:true},A=t(...R),h={...T},m=R[R.length-1];n&&m&&(h[n]=m),r&&(h[r]=A.path),o&&h[o]===void 0&&(h[o]=c()),s&&(h[s]=c()),ue(h,a),f.set(A,h,O);},update:(...w)=>{let b=w[w.length-1],g=w.slice(0,-1),T=t(...g),R={...b};s&&(R[s]=c()),ue(R,a),f.update(T,R);},delete:(...w)=>{let b=t(...w);f.delete(b);},raw:f}))}}function Lr(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 qs(e){let t=e?.documentKey??"docId",n=!!e?.isGroup,r=Se(typeof e?.path=="string"?e.path:"",t,n),o=r.parentKeys.length>0?r.parentKeys:n?Lr(e?.refCb):[],s=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(c=>typeof c=="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:fe(a),_historyIdentityKeys:Pn(a),_historySubcollection:a?.enabled?a.subcollection??"history":void 0,_collectionPath:typeof e?.path=="string"?r.collectionPath:null}}function Wt(e,t){let n=qs(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 Fn(e,t,n={}){let r=t.documentKey,o=Se(t.path,r,!!t.isGroup),s=o.parentKeys.length>0?o.parentKeys:t.isGroup?Lr(t.refCb):[],a=t.isGroup?e.collectionGroup(o.collectionId):e.collection(o.collectionPath),c=t.isGroup?null:e.collection(o.collectionPath),i=typeof t.refCb=="function"?(...d)=>t.refCb(e,...d):(...d)=>Nr(e,o.documentPathTemplate??`${o.collectionPath}/{${r}}`,d),u=t.history,f=fe(u),y=Pn(u),w=Br(a,t.foreignKeys,c,i,r,f),b=qr(a,t.queryKeys,t.relationalKeys,n,f),g=Hr(a),T=zr(c,i,r,t.pathKey,t.createdKey,t.updatedKey,s,o.documentPathTemplate,u),R=Fr(e,i,t.documentKey,t.pathKey,t.createdKey,t.updatedKey,u),O=Ur(e,i,t.documentKey,t.pathKey,t.createdKey,t.updatedKey,u),A=jr(e,t.createdKey,t.updatedKey,u),h=Zr(e,a,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),m=Kr(t,n),p=u?.enabled?_r(i,[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(d=>typeof d=="string"),t.path??"(unknown)",u):null;return {ref:a,documentRef:i,get:w,query:b,aggregate:g,...T,batch:R,transaction:O,bulk:A,system:h,...m,...p?{history:p}:{},_historySubcollection:p?u?.subcollection??"history":void 0,_historyConfig:u,_historyShadowKey:f,_historyIdentityKeys:y,schema:t.schema,relationalKeys:t.relationalKeys,_systemKeys:[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(d=>typeof d=="string"),_pathKey:t.pathKey??null,_isGroup:!!t.isGroup,_parentKeys:s,_documentPathTemplate:o.documentPathTemplate,_collectionId:o.collectionId,_collectionPath:o.collectionPath,_createdKey:t.createdKey??null}}var Ks="history";function Zs(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?Se(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 Us(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 Ls(e,t){return t?`${t}/{docId}`:(console.warn(`[HistoryTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function Wr(e,t){let{onDocumentWritten:n}=t.deps,r={},o=e?.rawMapping,s=o?Object.entries(o).map(([a,c])=>[a,Zs(c)]):Object.entries(e).map(([a,c])=>[a,Us(c)]);for(let[a,c]of s){let i=c.historyConfig;if(!i?.enabled)continue;let u=i.subcollection??Ks,f=i.ttl??t.defaults?.ttl,y=t.repos?.[a],w;if(c.isGroup){let h=y?.triggerPath??c.documentPathTemplate;if(!h){console.warn(`[HistoryTriggers] Skipping collection-group repo "${a}". Provide a triggerPath in the history triggers repos override or use a full path template.`);continue}w=h;}else w=y?.triggerPath??c.documentPathTemplate??Ls(a,c.collectionPath);if(!w)continue;let b=c.systemKeys,g=b[0]??"docId",T=Ut(i),R={...t.triggerOptions,...i?.triggerOptions,...y?.triggerOptions},O=Object.keys(R).length>0,A=async h=>{try{let m=h.data?.before?.data(),p=h.data?.after?.data(),d;if(!m&&p)d="create";else if(m&&!p)d="delete";else if(m&&p)d="update";else return;let l=String(p?.[g]??m?.[g]??h.params?.docId??h.data?.after?.id??h.data?.before?.id??"");if(!l)return;let x=Kt(m??{},p??{},{include:i.include,exclude:i.exclude,metaFields:T,systemKeys:b});if(d==="update"&&Object.keys(x).length===0)return;let v=Zt(p??m??null,i),P=ft({entityId:l,operation:d,changes:x,meta:v,config:i,ttlOverride:f}),S=h.data?.after?.ref??h.data?.before?.ref;if(!S)return;let C=S.collection(u);await yt(C,P,i,{repoName:a,docId:l,before:m??null,after:p??null});}catch(m){console.error(`[HistoryTriggers] Failed to record history for "${a}":`,m);}};r[`${a}_onHistory`]=n(O?{document:w,...R}:w,A);}return r}function Ws(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 Vs(e){let t=e.path??e.url??"/",n=t.indexOf("?");return n===-1?t:t.slice(0,n)}var ke=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}=Ws(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=Vs(t),s=null,a={};for(let u of this.routes){if(u.method!==r)continue;let f=o.match(u.pattern);if(f){s=u,a={},u.paramNames.forEach((y,w)=>{a[y]=decodeURIComponent(f[w+1]??"");});break}}let c=Object.assign(t,{params:a}),i=s?s.handler:this.notFoundHandler;try{await this.runMiddlewareChain(c,n,i);}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 be(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",c=n??process.env.FUNCTION_REGION??"us-central1",i=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${a}/${c}/${i}${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 Vt(e){if(typeof e=="string")return e;if(Array.isArray(e)){let t=e[0];return typeof t=="string"?t:void 0}}function mt(e){return !!e&&typeof e=="object"&&e.__authExtension===true}function jn(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=>jn(s,t,n,r+1));return t?.stringifyArrays===false?o:JSON.stringify(o)}return typeof e=="object"&&e!==null&&t?.stringifyArrays===false?Nn(e,new Set,{},n,r+1):e}var Gr=32,Js=5e3;function Qr(e,t,n,r=new WeakSet,o=0){if(o>Gr){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>=Js)break;let c=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)?Qr(a,c,n,r,o+1):n[c]=jn(a);}r.delete(e);}function Nn(e,t,n,r=new WeakSet,o=0){if(o>Gr)return {__truncated:true};if(r.has(e))return {__cycle:true};r.add(e);let s={};for(let[a,c]of Object.entries(e)){if(t.has(a))continue;let i=n[a]??a;c!=null&&typeof c=="object"&&!Array.isArray(c)&&!(c instanceof Date)&&!Buffer.isBuffer(c)&&!(c instanceof Uint8Array)&&typeof c.toDate!="function"&&!("latitude"in c&&"longitude"in c)?s[i]=Nn(c,new Set,{},r,o+1):s[i]=jn(c,{stringifyArrays:false},r,o+1);}return r.delete(e),s}function Jr(e){let t={};for(let[n,r]of Object.entries(e)){let o=r;if(typeof o=="string"){let c=o.trim();if(c.startsWith("[")&&c.endsWith("]")||c.startsWith("{")&&c.endsWith("}"))try{o=JSON.parse(c);}catch{}}if(n.startsWith("__")||!n.includes("__")){t[n]=o;continue}let s=n.split("__").filter(Boolean),a=t;for(let c=0;c<s.length-1;c++){let i=s[c];(!a[i]||typeof a[i]!="object"||Array.isArray(a[i]))&&(a[i]={}),a=a[i];}a[s[s.length-1]]=o;}return t}function ht(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 i=false,u={};for(let[f,y]of Object.entries(e)){if(o.has(f)){i=true;continue}u[f]=y;}i&&(a=u);}let c={};Qr(a,"",c),r={};for(let[i,u]of Object.entries(c)){if(o.has(i))continue;let f=i.split("__")[0];if(f!==i&&o.has(f))continue;let y=s[i]??(i.includes("__")?s[i.split("__").pop()]:void 0)??i;r[y]=u;}}else {let o=new Set(t?.exclude),s=t?.columnMap??{};r=Nn(e,o,s);}return typeof t?.transformDoc=="function"&&(r=t.transformDoc(r)),r}function Oe(e,t,n){return `<!DOCTYPE html>
|
|
1
|
+
import {jsx,jsxs,Fragment}from'hono/jsx/jsx-runtime';import {Timestamp,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 kn=Object.defineProperty;var Es=Object.getOwnPropertyDescriptor;var Os=Object.getOwnPropertyNames;var Ps=Object.prototype.hasOwnProperty;var $r=(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 dt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Hr=(e,t)=>{for(var n in t)kn(e,n,{get:t[n],enumerable:true});},Is=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Os(t))!Ps.call(e,o)&&o!==n&&kn(e,o,{get:()=>t[o],enumerable:!(r=Es(t,o))||r.enumerable});return e};var Ds=e=>Is(kn({},"__esModule",{value:true}),e);function G(e){let t=e,n=t._zod?.def?.type;if(n)return Ea[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=t._def?.typeName;return r||""}function se(e){let t=e;if(t._zod?.def?.innerType)return t._zod.def.innerType;if(t._def?.innerType)return t._def.innerType}function Rt(e){let t=e,n=t._zod?.def?.in;if(n)return n;if(t._def?.schema)return t._def.schema}function tn(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}function go(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 ae(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 vt(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 Tt(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 St(e){let t=e;return Array.isArray(t._zod?.def?.values)?t._zod.def.values[0]:t._def?.value}function kt(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 bo(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 Ea,tt=dt(()=>{"use strict";Ea={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 Ho({val:e}){return jsx("span",{class:"text-sm text-base-content/80 font-mono tabular-nums whitespace-nowrap",children:e.toLocaleString()})}function Qa({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 ot({val:e,mismatch:t}){let n=er(e);return t?jsxs("span",{class:"inline-flex items-start gap-0.5",children:[n,jsx(Qa,{message:t})]}):n}function er(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(Ho,{val:e});if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")return jsx(Ho,{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:er(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:er(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 ln=dt(()=>{"use strict";});function Pt(e){if(!e)return "unknown";let t=tr(e);switch(G(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 tr(e){let t=G(e);if(t==="ZodOptional"||t==="ZodNullable"||t==="ZodDefault"){let n=se(e);return n?tr(n):e}return e}function It(e,t){if(!e)return;let n=t.split("."),r=e;for(let o of n){if(!r)return;let s=tr(r);if(G(s)!=="ZodObject")return;r=ae(s)[o];}return r}function ei(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 Dt(e,t){if(e==="unknown")return null;let n=ei(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 nr=dt(()=>{"use strict";tt();});var No={};Hr(No,{PanelMany:()=>ni,PanelOne:()=>ti,RightPanel:()=>rr});function ti({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`,c=_o(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(i=>{let u=e[i],f=c[i],y=f?Dt(f,u):null;return jsxs(Fragment,{children:[jsx("dt",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide pt-0.5",children:i}),jsx("dd",{class:"min-w-0",children:jsx(ot,{val:u,mismatch:y})})]})})})]})}function ni({docs:e,repoName:t,basePath:n,fk:r,fv:o,columns:s,schema:a,pagination:c}){let i=`${n}/${t}?fv_${r}=${encodeURIComponent(o)}`,u=_o(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:i,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((f,y)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:f},y)),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((f,y)=>{let b=String(f.docId??f.id??""),h=`${n}/${t}/${encodeURIComponent(b)}/edit`;return jsxs("tr",{class:"hover",children:[s.map((g,T)=>{let v=f[g],E=u[g],A=E?Dt(E,v):null;return jsx("td",{class:"align-top py-1.5",children:jsx(ot,{val:v,mismatch:A})},T)}),jsx("td",{class:"text-right py-1.5",children:jsx("a",{href:h,class:"btn btn-xs btn-ghost",children:"Edit"})})]},y)})})]})}),(c.hasPrev||c.hasNext)&&jsxs("div",{class:"flex justify-center items-center gap-2",children:[c.hasPrev?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"prev","data-cursor":c.prevCursor,children:"\u2190 Previous"}):jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"\u2190 Previous"}),c.hasNext?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"next","data-cursor":c.nextCursor,children:"Next \u2192"}):jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"Next \u2192"})]})]})}function _o(e,t){if(!e)return {};let n={};for(let r of t)n[r]=Pt(It(e,r));return n}var rr,or=dt(()=>{"use strict";ln();nr();rr=({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 Yo={};Hr(Yo,{DEFAULT_HTML_CSP:()=>hr,securityHeaders:()=>yn});function yn(e={}){let t=e.csp===void 0?hr: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,c)=>{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 c();}}var Qo,Jo,hr,mn=dt(()=>{"use strict";Qo="https://cdn.jsdelivr.net",Jo="https://www.gstatic.com",hr=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${Qo} ${Jo}`,`style-src 'self' 'unsafe-inline' ${Qo}`,`connect-src 'self' ${Jo} 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 qt="__name__",$s=new Set(["<","<=",">",">=","!=","not-in"]);var Hs=55296,Ms=57343;function Mr(e){return e>=Hs&&e<=Ms}function Ye(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=Mr(o),c=Mr(s);return a===c?o<s?-1:1:a?1:-1}}return e.length<t.length?-1:e.length>t.length?1:0}function _r(e){return e.length>6&&e.startsWith("__id")&&e.endsWith("__")&&/^-?\d+$/.test(e.slice(4,-2))}function _s(e,t){let n=_r(e),r=_r(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 Ye(e,t)}function Br(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=_s(n[s],r[s]);if(a!==0)return a}return n.length<r.length?-1:n.length>r.length?1:0}function Ns(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=Ye(n[s],r[s]);if(a!==0)return a}return n.length<r.length?-1:n.length>r.length?1:0}function ut(e,t){return e<t?-1:e>t?1:e===t?0:Number.isNaN(e)?Number.isNaN(t)?0:-1:1}function Cn(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 Fs(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 js(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 Nr(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:Cn(e)!==null?3:Fs(e)?6:js(e)?7:Array.isArray(e)?8:9}function zs(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 An(e,t){let n=Nr(e),r=Nr(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 ut(Number(e),Number(t));case 3:{let o=Cn(e),s=Cn(t),a=ut(o.seconds,s.seconds);return a!==0?a:ut(o.nanos,s.nanos)}case 4:return Ye(e,t);case 5:return zs(e,t);case 6:return Br(e.path,t.path);case 7:{let o=e,s=t,a=ut(o.latitude,s.latitude);return a!==0?a:ut(o.longitude,s.longitude)}case 8:{let o=e,s=t,a=Math.min(o.length,s.length);for(let c=0;c<a;c++){let i=An(o[c],s[c]);if(i!==0)return i}return o.length<s.length?-1:o.length>s.length?1:0}case 9:{let o=e,s=t,a=Object.keys(o).sort(Ye),c=Object.keys(s).sort(Ye),i=Math.min(a.length,c.length);for(let u=0;u<i;u++){let f=a[u],y=c[u],b=Ye(f,y);if(b!==0)return b;let h=An(o[f],s[y]);if(h!==0)return h}return a.length<c.length?-1:a.length>c.length?1:0}}}function En(e){return e.ref?.path??e.id}function Fr(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 Bs(e,t){let n=[],r=new Set;if(e.orderBy)for(let a of e.orderBy){let c=String(a.field),i=a.direction==="desc"?"desc":"asc";r.has(c)||(n.push({field:c,direction:i}),r.add(c));}let o=n.length>0?n[n.length-1].direction:"asc",s=[];for(let[a,c]of t){let i=String(a);$s.has(c)&&i!==qt&&!r.has(i)&&(s.push(i),r.add(i));}s.sort(Ns);for(let a of s)n.push({field:a,direction:o});return r.has(qt)||n.push({field:qt,direction:o}),n}function qs(e,t,n){for(let r of n){let o=r.field===qt?Br(En(e),En(t)):An(Fr(e,r.field),Fr(t,r.field));if(o!==0)return r.direction==="desc"?-o:o}return 0}function Ks(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Je(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 jr(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 pt(e){let[,t,n]=e;return (t==="in"||t==="array-contains-any")&&Array.isArray(n)&&n.length>30}function Kt(e){let[t,n,r]=e;return pt(e)?Ks(r,30).map(s=>[t,n,s]):[e]}function Se(e,t){let n=e;for(let[r,o,s]of t)n=n.where(String(r),o,s);return n}async function zr(e,t,n){let r=await Promise.all(e.map(y=>y.get())),o=new Map;r.forEach(y=>{y.docs.forEach(b=>{let h=En(b);o.has(h)||o.set(h,b);});});let s=r[0];if(!s)throw new Error("No snapshots returned");let a=Bs(t,n),c=Array.from(o.values()).sort((y,b)=>qs(y,b,a)),i=t.offset&&t.offset>0?t.offset:0,u=t.limit&&t.limit>0?i+t.limit:void 0,f=i>0||u!==void 0?c.slice(i,u):c;return {...s,docs:f,size:f.length,empty:f.length===0,forEach:(y,b)=>{f.forEach(h=>y.call(b,h));}}}async function Fe(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 Je(e,t).get();if(!t.where.some(pt)){let g=Se(e,t.where);return g=Je(g,t),g.get()}let f=t.where.map(Kt),y=ft(f);if(y.length===1){let g=Se(e,y[0]);return g=Je(g,t),g.get()}let b=jr(t),h=y.map(g=>{let T=Se(e,g);return T=Je(T,b),T});return zr(h,t,t.where)}let o=t.where??[],s=[...t.orWhere?.map(u=>[u])??[],...t.orWhereGroups??[]],a=[];for(let u of s){let f=[...o,...u];if(!f.some(pt))a.push(f);else {let b=f.map(Kt),h=ft(b);a.push(...h);}}if(a.length===1){let u=Se(e,a[0]);return u=Je(u,t),u.get()}let c=jr(t),i=a.map(u=>{let f=Se(e,u);return f=Je(f,c),f});return zr(i,t,o)}function ft(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=ft(n),o=[];for(let s of t)for(let a of r)o.push([s,...a]);return o}async function On(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 {count:(await e.count().get()).data().count,isExact:true};if(!t.where.some(pt))return {count:(await Se(e,t.where).count().get()).data().count,isExact:true};let f=t.where.map(Kt),y=ft(f);return {count:(await Promise.all(y.map(g=>Se(e,g).count().get()))).reduce((g,T)=>g+T.data().count,0),isExact:true}}let o=t.where??[],s=[...t.orWhere?.map(u=>[u])??[],...t.orWhereGroups??[]],a=[];for(let u of s){let f=[...o,...u];if(!f.some(pt))a.push(Se(e,f));else {let b=f.map(Kt),g=ft(b).map(T=>Se(e,T));a.push(...g);}}return {count:(await Promise.all(a.map(u=>u.count().get()))).reduce((u,f)=>u+f.data().count,0),isExact:false}}var Pn="preserve";function Us(e){Pn=e;}function Zt(){return Pn}function Zs(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function In(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(Zs(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 Ls(e){if(typeof e!="object"||e===null)return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ut(e){if(e instanceof Timestamp)return e.toDate();if(Array.isArray(e))return e.map(t=>Ut(t));if(Ls(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Ut(r);return t}return e}function X(e){return Pn==="normalize"?Ut(e):e}function Kr(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function ke(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Ee(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 Lt(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([Fe(e,n),t.withTotal?On(e,t):Promise.resolve(void 0)]),s=r.docs,a=s.length>t.pageSize,c=a?s.slice(0,t.pageSize):s,i=c.map(f=>X({...f.data(),docId:f.id})),u=t.direction==="prev";return {data:i,nextCursor:u?c.length>0?c[c.length-1]:void 0:a?c[c.length-1]:void 0,prevCursor:u?a?c[0]:void 0:c[0],hasNextPage:u?!!t.cursor:a,hasPrevPage:u?a:!!t.cursor,pageSize:i.length,...o!==void 0?{totalCount:o.count,totalCountIsExact:o.isExact}:{}}}async function*Dn(e,t){let n,r=true;for(;r;){let o=await Lt(e,{...t,cursor:n,direction:"next"});yield o,r=o.hasNextPage,n=o.nextCursor;}}var je="X-History-Reason",ze="X-History-Comment",Lr=Symbol.for("@lpdjs/firestore-repo-service:actorResolverHeaders"),$n=Symbol.for("@lpdjs/firestore-repo-service:actorContext"),Hn=globalThis,Wt=Hn[$n]??(Hn[$n]=new AsyncLocalStorage);function Gs(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 Ur(e,t){for(let n of t){let r=Gs(e,n);if(typeof r=="string"&&r.length>0)return r;if(typeof r=="number")return String(r)}return null}function Zr(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 Mn(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?je:e.reasonHeader,c=e.commentHeader===void 0?ze:e.commentHeader,i=e.extras,u=f=>{let y=null,b=f?.get;if(typeof b=="function")for(let v of t){let E=b.call(f,v);if(E&&typeof E=="object"){y=E;break}}let h=Zr(f,o),g=Zr(f,s),T=i?i(f,y):void 0;return y?{userId:Ur(y,n),userEmail:Ur(y,r),...h!==void 0?{reason:h}:{},...g!==void 0?{comment:g}:{},...T?{extras:T}:{}}:h===void 0&&g===void 0&&!T?null:{...h!==void 0?{reason:h}:{},...g!==void 0?{comment:g}:{},...T?{extras:T}:{}}};return Object.defineProperty(u,Lr,{value:{reasonHeader:a,commentHeader:c},enumerable:false,configurable:false}),u}function _n(e){if(!e)return {reasonHeader:je,commentHeader:ze};if(typeof e=="function"){let t=e[Lr];return t?{...t}:{reasonHeader:je,commentHeader:ze}}return {reasonHeader:e.reasonHeader===void 0?je:e.reasonHeader,commentHeader:e.commentHeader===void 0?ze:e.commentHeader}}var Wr=Mn();function Vs(e){if(e)return typeof e=="function"?e:Mn(e)}function Nn(e){let t=Vs(e);return async(n,r)=>{await Wt.run({c:n,resolver:t},async()=>{await r();});}}function Xe(){let e=Wt.getStore();if(!e)return null;let t=null;if(e.c)try{t=(e.resolver??Wr)(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 Qs(e,t){return Wt.run({override:{...e}},t)}function Js(e){let t=Wt.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 Fn="_historyMeta";function be(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():Fn,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 fe(e){return be(e)?.key??null}function jn(e){let t=be(e);return t?[t.key]:[]}function re(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 ue(e,t){if(!t?.enabled||t.autoInjectMeta===false)return;let n=be(t);if(!n)return;let r=Xe(),o=t.fallbackActor??{},s=r?.userId!==void 0?r.userId:o.userId??null,a=r?.userEmail!==void 0?r.userEmail:o.userEmail??null,c=r?.reason??null,i=r?.comment??null,u=r?.extras&&Object.keys(r.extras).length>0?r.extras:null,f={},{fields:y}=n;y.userId!==false&&(f[y.userId]=s),y.userEmail!==false&&(f[y.userEmail]=a),y.reason!==false&&(f[y.reason]=c),y.comment!==false&&(f[y.comment]=i),y.extras!==false&&(f[y.extras]=u),e[n.key]=f;}function mt(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 ht(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(!ht(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)||!ht(e[s],t[s],n))return false;return true}return false}function Gt(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??{},c=new Set([...Object.keys(s),...Object.keys(a)]),i={};for(let u of c){if(r.has(u)||o&&!o.has(u))continue;let f=s[u],y=a[u];ht(f,y)||(i[u]={oldValue:f===void 0?null:f,newValue:y===void 0?null:y,type:{old:mt(f),new:mt(y)}});}return i}var Ys=5;function Xs(e){return e.schemaVersion===2}function Gr(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 ea(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 na(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?Gr(r):mt(t),new:o?Gr(o):mt(n)}}}function ra(e){let t=na(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 oa(e,t,n){return Math.abs(e.toMillis()-t.toMillis())<=n}function sa(e,t){return (e.userId??null)===(t.userId??null)}function Vr(e,t={}){let n=t.groupToleranceMs??Ys,r=[];for(let o of e){if(Xs(o)){r.push(ea(o));continue}let a=ra(o),c=r[r.length-1];c&&c.schemaVersion===1&&oa(c.historySetAt,a.historySetAt,n)&&sa(c.meta,a.meta)?Object.assign(c.changes,a.changes):r.push(a);}return r}var ia=7e5;function gt(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,c)=>c instanceof Timestamp?c.toMillis():c),"utf8")}catch{return 0}};if(o(r.changes)>ia){let s={};for(let[a,c]of Object.entries(r.changes)){let i=o(c.oldValue),u=o(c.newValue);s[a]={oldValue:i>5e4?"[truncated]":c.oldValue,newValue:u>5e4?"[truncated]":c.newValue,type:c.type};}r.changes=s,r._truncated=true;}return r}async function bt(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 Vt(e,t){let n=e??{},r={},o=be(t);if(o){let y=n[o.key];if(y&&typeof y=="object"&&!Array.isArray(y)){let b=y,h=A=>{if(A===false||!(A in b))return;let x=b[A];return x==null?null:String(x)},g=h(o.fields.userId);g!==void 0&&(r.userId=g);let T=h(o.fields.userEmail);T!==void 0&&(r.userEmail=T);let v=h(o.fields.reason);v!==void 0&&(r.reason=v);let E=h(o.fields.comment);if(E!==void 0&&(r.comment=E),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=y=>{if(!y)return;let b=n[y];return b===void 0||b===null?null:String(b)},c=a(s.userId);c!==void 0&&(r.userId=c);let i=a(s.userEmail);i!==void 0&&(r.userEmail=i);let u=a(s.reason);u!==void 0&&(r.reason=u);let f=a(s.comment);if(f!==void 0&&(r.comment=f),s.extras&&s.extras.length>0){let y={},b=false;for(let h of s.extras)h in n&&(y[h]=n[h],b=true);b&&(r.extras=y);}return r}function Qt(e){let t=[],n=be(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 ca="history",la=50;function Bn(e,t,n){return e(...n).collection(t)}function Qr(e){return String(e[e.length-1]??"")}function Jr(e,t,n,r){if(!r?.enabled)return null;let o=r.subcollection??ca;async function s(...h){let g={},T=h,v=h[h.length-1];v!==null&&typeof v=="object"&&!(v instanceof Timestamp)&&("limit"in v||"cursor"in v||"direction"in v)&&(g=v,T=h.slice(0,-1));let E=Bn(e,o,T),A=g.direction??"desc",x=E.orderBy("historySetAt",A);return g.cursor&&(x=x.startAfter(g.cursor)),g.limit&&g.limit>0&&(x=x.limit(g.limit)),(await x.get()).docs.map(p=>({id:p.id,data:p.data()}))}async function a(...h){let g={},T=h,v=h[h.length-1];v!==null&&typeof v=="object"&&!(v instanceof Timestamp)&&("limit"in v||"cursor"in v||"direction"in v||"fields"in v||"operations"in v)&&(g=v,T=h.slice(0,-1));let E=g.limit??la,A=Math.max(E,Math.min(E*8,500)),x=await s(...T,{limit:A,cursor:g.cursor,direction:g.direction??"desc"}),m=Vr(x.map(p=>p.data));if(g.fields&&g.fields.length>0){let p=new Set(g.fields);m=m.filter(l=>Object.keys(l.changes).some(d=>p.has(d)));}if(g.operations&&g.operations.length>0){let p=new Set(g.operations);m=m.filter(l=>p.has(l.operation));}return m.slice(0,E)}async function c(...h){let g=h[h.length-1],T={},v,E;return g!==null&&typeof g=="object"&&!(g instanceof Timestamp)?(T=g,v=h[h.length-2],E=h.slice(0,-2)):(v=g,E=h.slice(0,-1)),a(...E,{...T,fields:[v]})}async function i(...h){let g=h[h.length-1],T={},v,E;return g!==null&&typeof g=="object"&&!(g instanceof Timestamp)?(T=g,v=h[h.length-2],E=h.slice(0,-2)):(v=g,E=h.slice(0,-1)),a(...E,{...T,operations:[v]})}function u(h){let g={title:h.title,display:h.display??true};return h.description!==void 0&&(g.description=h.description),h.key!==void 0&&(g.key=h.key),h.data!==void 0&&(g.data=h.data),g}function f(){let h=Xe(),g=r.fallbackActor??{},T=h?.userId!==void 0?h.userId:g.userId??null,v=h?.userEmail!==void 0?h.userEmail:g.userEmail??null;return {userId:T,userEmail:v,...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 y(...h){let g=h[h.length-1],T=h.slice(0,-1),v=Qr(T),E=Gt(g.before??{},g.after??{},{include:r.include,exclude:r.exclude,metaFields:Qt(r),systemKeys:t});if(g.operation==="update"&&Object.keys(E).length===0)return null;let A=Vt(g.after??g.before??null,r),x=Xe(),p={...x?{...x.userId!==void 0?{userId:x.userId}:{},...x.userEmail!==void 0?{userEmail:x.userEmail}:{},...x.reason!==void 0?{reason:x.reason}:{},...x.comment!==void 0?{comment:x.comment}:{},...x.extras&&Object.keys(x.extras).length>0?{extras:x.extras}:{}}:{},...A,...g.meta??{}},l=g.custom?u(g.custom):void 0,d=gt({entityId:v,operation:g.operation,changes:E,meta:p,custom:l,config:r}),w=Bn(e,o,T),R=await bt(w,d,r,{repoName:n,docId:v,before:g.before??null,after:g.after??null});return !R.written||!R.entry?null:{historyDocId:R.entry.historyDocId,historyToObjectId:R.entry.historyToObjectId,historySetAt:R.entry.historySetAt,schemaVersion:2,operation:R.entry.operation,meta:R.entry.meta,...R.entry.custom?{custom:R.entry.custom}:{},changes:R.entry.changes}}async function b(...h){let g=h[h.length-1],T=h.slice(0,-1),v=Qr(T),E=u(g),A={...f(),...g.meta??{}},x=gt({entityId:v,operation:"custom",changes:{},meta:A,custom:E,config:r}),m=Bn(e,o,T),p=await bt(m,x,r,{repoName:n,docId:v,before:null,after:null});return !p.written||!p.entry?null:{historyDocId:p.entry.historyDocId,historyToObjectId:p.entry.historyToObjectId,historySetAt:p.entry.historySetAt,schemaVersion:2,operation:p.entry.operation,meta:p.entry.meta,...p.entry.custom?{custom:p.entry.custom}:{},changes:p.entry.changes}}return {list:a,raw:s,byField:c,byOperation:i,recordManual:y,recordCustom:b}}function Yr(e){return {count:async(t={})=>{let n=e;return n=Ee(n,t),(await n.count().get()).data().count},sum:async(t,n={})=>{let r=e;r=Ee(r,n);let o=await r.get(),s=0;return o.forEach(a=>{let c=a.data()[t];typeof c=="number"&&(s+=c);}),s},average:async(t,n={})=>{let r=e;r=Ee(r,n);let o=await r.get();if(o.empty)return null;let s=0,a=0;return o.forEach(c=>{let i=c.data()[t];typeof i=="number"&&(s+=i,a++);}),a>0?s/a:null}}}function Xr(e,t,n,r,o,s,a){let c=()=>new Date;return {create:()=>{let i=e.batch();return {batch:i,set:(...u)=>{let f=u[u.length-1],y=typeof f=="object"&&f!==null&&"merge"in f,b=y?u[u.length-2]:u[u.length-1],h=y?u.slice(0,-2):u.slice(0,-1),g=y?f:{merge:true},T=t(...h),v={...b},E=h[h.length-1];n&&E&&(v[n]=E),r&&(v[r]=T.path),o&&v[o]===void 0&&(v[o]=c()),s&&(v[s]=c()),ue(v,a),i.set(T,v,g);},update:(...u)=>{let f=u.pop(),b=t(...u),h={...f};s&&(h[s]=c()),ue(h,a),i.update(b,h);},delete:(...u)=>{let f=t(...u);i.delete(f);},commit:async()=>{await i.commit();}}}}}var da=new Set([4,8,10,13,14]);function qn(e,t){let n=[],r=t.maxAttempts??5;return e.onWriteError(o=>{let s=o?.code;if(o.failedAttempts<r&&s!==void 0&&da.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 Kn(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 eo(e,t,n,r){let o=()=>new Date;return {set:async(s,a={})=>{let c=e.bulkWriter(),i=qn(c,a);for(let u of s){if(!u)continue;let{docRef:f,data:y,merge:b=true}=u,h={...y};t&&h[t]===void 0&&(h[t]=o()),n&&(h[n]=o()),ue(h,r),c.set(f,h,{merge:b});}return await c.close(),Kn(i,a)},update:async(s,a={})=>{let c=e.bulkWriter(),i=qn(c,a);for(let u of s){if(!u)continue;let{docRef:f,data:y}=u,b={...y};n&&(b[n]=o()),ue(b,r),c.update(f,b);}return await c.close(),Kn(i,a)},delete:async(s,a={})=>{let c=e.bulkWriter(),i=qn(c,a);for(let u of s)u&&c.delete(u);return await c.close(),Kn(i,a)}}}var Un="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Oe(){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>=Un.length*4||(e+=Un.charAt(r%Un.length));}}return e}function Zn(e){return e.match(/^\{([^}]+)\}$/)?.[1]?.trim()||null}function Ce(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(y=>y.trim()).filter(Boolean);if(r.length===0)return {rawPath:e,collectionId:e,collectionPath:e,parentKeys:[],documentPathTemplate:null,hasTemplate:false};if(r.length===1){let y=r[0];return {rawPath:e,collectionId:y,collectionPath:y,parentKeys:[],documentPathTemplate:n?null:`${y}/{${t}}`,hasTemplate:e.includes("{")&&e.includes("}")}}let o=r.length%2===0,s=o?r.slice(0,-1):r,a=s[s.length-1],c=s.join("/"),u=s.slice(0,-1).map(Zn).filter(y=>y!==null),f=o?r.join("/"):`${c}/{${t}}`;return {rawPath:e,collectionId:a,collectionPath:c,parentKeys:u,documentPathTemplate:f,hasTemplate:true}}function to(e,t,n){let r=t.split("/").map(i=>i.trim()).filter(Boolean),o=0,s=[];for(let i of r){let u=Zn(i);if(u!==null){let f=n[o++];if(typeof f!="string"||f.trim()==="")throw new Error(`Missing or empty path parameter "${u}" when resolving document reference for "${t}".`);s.push(f);}else s.push(i);}let a=e;if(typeof a?.collection=="function"&&s.length>=2){let i=a,u=true;for(let f=0;f<s.length;f+=2){let y=s[f],b=s[f+1];if(typeof i?.collection!="function"){u=false;break}let h=i.collection(y);if(typeof h?.doc!="function"){u=false;break}i=h.doc(b);}if(u&&i&&i!==a)return i}let c=s.join("/");if(typeof a?.doc=="function")return a.doc(c);if(typeof a?.collection=="function"&&s.length>=2){let i=s.slice(0,-1).join("/"),u=s[s.length-1],f=a.collection(i);return typeof f?.doc=="function"?f.doc(u):f}throw new Error(`Cannot resolve DocumentReference for "${c}": Firestore instance does not expose .collection() or .doc().`)}function Be(e,t={}){if(!e||typeof e!="object")return;let{pathKey:n,documentKey:r="docId",parentKeys:o,documentPathTemplate:s,isGroup:a}=t,c=n&&typeof e[n]=="string"&&e[n]?e[n]:void 0;if(c&&s){let i=c.split("/").filter(Boolean),u=s.split("/").filter(Boolean);if(i.length===u.length){let f=[];for(let y=0;y<u.length;y++)Zn(u[y])!==null&&f.push(i[y]);if(f.length>0)return f}}if(o&&o.length>0){let i=o.length+1;if(c){let f=c.split("/").filter(Boolean),y=[];for(let b=1;b<f.length;b+=2)y.push(f[b]);if(y.length>=i)return y.slice(y.length-i)}let u=r?e[r]:void 0;if(typeof u=="string"&&u.trim()!==""){let f=[],y=true;for(let b of o){let h=e[b];if(typeof h=="string"&&h.trim()!=="")f.push(h);else {y=false;break}}if(y)return [...f,u]}}if(c){let i=c.split("/").filter(Boolean),u=[];for(let f=1;f<i.length;f+=2)u.push(i[f]);if(u.length>0)return !a&&(!o||o.length===0)?[u[u.length-1]]:u}}function no(e,t,n,r,o,s,a=[],c,i){let u=()=>new Date,f=fe(i);return {create:async(...T)=>{let v=T[T.length-1],E=T.slice(0,-1);if(!v||typeof v!="object")throw new Error("Create data payload must be an object.");let A,x,m=typeof v[n]=="string"&&v[n].trim()!=="",p={...v};if(o&&p[o]===void 0&&(p[o]=u()),s&&(p[s]=u()),ue(p,i),e&&E.length===0)if(m){x=v[n],A=typeof e.doc=="function"?e.doc(x):t(x),p[n]=x;let l=r&&A?.path?{...p,[r]:A.path}:p;await A.set(l),r&&A?.path&&(p[r]=A.path);}else if(typeof e.add=="function"){A=await e.add(p),x=A.id,p[n]=x;let l={[n]:x};r&&A?.path&&(l[r]=A.path,p[r]=A.path),await A.update(l);}else x=Oe(),A=typeof e.doc=="function"?e.doc(x):t(x),p[n]=A?.id??x,r&&A?.path&&(p[r]=A.path),await A.set(p);else {let l=[];if(E.length>0)for(let d=0;d<E.length;d++){let w=E[d];if(typeof w!="string"||w.trim()===""){let R=a[d]??`arg[${d}]`;throw new Error(`Missing or empty parent key "${R}" for subcollection create()`)}l.push(w);}else if(a.length>0){let d=[];for(let w of a){let R=v[w];typeof R=="string"&&R.trim()!==""?l.push(R):d.push(w);}if(d.length>0){let w=Be(v,{pathKey:r,documentKey:n,parentKeys:a,documentPathTemplate:c,isGroup:true});if(w&&w.length>=a.length)l=w.slice(0,a.length);else throw new Error(`Missing or empty required parent key(s) in data for subcollection create(): ${d.join(", ")}`)}}else if(r&&typeof v[r]=="string"&&v[r].trim()!==""){let d=Be(v,{pathKey:r,documentKey:n,parentKeys:a,documentPathTemplate:c,isGroup:true});d&&d.length>1&&(l=d.slice(0,-1));}if(l.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.");x=m?v[n]:Oe(),A=t(...l,x),p[n]=A?.id??x,r&&A?.path&&(p[r]=A.path),await A.set(p);}if(typeof A?.get=="function"){let l=await A.get(),d=typeof l?.data=="function"?l.data():p;return re(X(d??p),f)}return re(X(p),f)},set:async(...T)=>{let v=T[T.length-1],E=typeof v=="object"&&v!==null&&"merge"in v,A=E?T[T.length-2]:T[T.length-1],x=E?T.slice(0,-2):T.slice(0,-1),m=E?v:{merge:true},p={...A};o&&p[o]===void 0&&(p[o]=u()),s&&(p[s]=u()),ue(p,i);let l=t(...x),d=x[x.length-1];if(n&&d!=null&&(p[n]=d),r&&(p[r]=l.path),await l.set(p,m),typeof l?.get=="function"){let w=await l.get(),R=typeof w?.data=="function"?w.data():p;return re(X(R??p),f)}return re(X(p),f)},update:async(...T)=>{let v=T.pop(),E=T,A={...v};s&&(A[s]=u()),ue(A,i);let x=t(...E);await x.update(A);let m=await x.get();return re(X(m.data()),f)},delete:async(...T)=>{await t(...T).delete();}}}function ro(e,t,n,r,o,s=null){let a={};return a.byList=async(c,i,u="in",f={})=>{if(i.length===0)return [];let y=[],b=Kr(i,30);for(let h of b){let g=e;g=g.where(c,u,h),f.select&&f.select.length>0&&(g=g.select(...f.select.map(v=>String(v)))),(await g.get()).forEach(v=>{let E=re(X(v.data()),s);y.push(f.returnDoc?{data:E,doc:v}:E);});}return y},t.forEach(c=>{let i=`by${ke(String(c))}`;a[i]=async(...u)=>{let f={},y=u[u.length-1];if(typeof y=="boolean"?(f={returnDoc:y},u=u.slice(0,-1)):typeof y=="object"&&y!==null&&!Array.isArray(y)&&(f=y,u=u.slice(0,-1)),String(c)===o&&(u.length>1||u.length===1&&n!==null)){let A=await r(...u).get();if(!A.exists)return null;let x=re(X(A.data()),s);return f.returnDoc?{data:x,doc:A}:x}let b=u[0];if(b===void 0)return null;let h=e;h=h.where(String(c),"==",b).limit(1),f.select&&f.select.length>0&&(h=h.select(...f.select.map(E=>String(E))));let g=await h.get();if(g.empty)return null;let T=g.docs[0];if(!T)return null;let v=re(X(T.data()),s);return f.returnDoc?{data:v,doc:T}:v};}),a}function oo(e,t,n,r,o=null){let s={},a=i=>re(X(i),o),c=async(i,u)=>{if(!n||!r||u.length===0)return i;let f=u.map(y=>typeof y=="string"?{key:y}:{key:y.relation,select:y.select});return Promise.all(i.map(async y=>{let b=await Promise.all(f.map(async({key:g,select:T})=>{let v=n[g];if(!v)return [g,void 0];let E=r[v.repo];if(!E)return [g,void 0];let A=v.sourceKey||g,x=y[A];if(x==null)return [g,v.type==="one"?null:[]];let m=T?{select:T}:void 0;try{if(v.type==="one"){let p=`by${ke(v.key)}`,l=typeof E.get?.[p]=="function"?await E.get[p](x,m):null;return [g,l]}else {let p=`by${ke(v.key)}`,l=typeof E.query?.[p]=="function"?await E.query[p](x,m):[];return [g,l]}}catch(p){return console.error(`[include] Error populating "${g}":`,p),[g,v.type==="one"?null:[]]}})),h={};for(let[g,T]of b)g!==void 0&&(h[g]=T);return {...y,populated:h}}))};return t.forEach(i=>{let u=`by${ke(i)}`;s[u]=async(f,y={})=>{let b={...y,where:[[i,"==",f],...y.where??[]]};return (await Fe(e,b)).docs.map(g=>a(g.data()))};}),s.by=async i=>(await Fe(e,i)).docs.map(f=>a(f.data())),s.getAll=async(i={})=>(await Fe(e,i)).docs.map(f=>a(f.data())),s.onSnapshot=(i,u,f)=>Ee(e,i).onSnapshot(b=>{u(b.docs.map(h=>a(h.data())));},f),s.paginate=async i=>{let{include:u,...f}=i,y=await Lt(e,f),b=o?{...y,data:y.data.map(h=>re(h,o))}:y;if(u&&u.length>0){let h=await c(b.data,u);return {...b,data:h}}return b},s.paginateAll=async function*(i){let{include:u,...f}=i;for await(let y of Dn(e,f)){let b=o?{...y,data:y.data.map(h=>re(h,o))}:y;if(u&&u.length>0){let h=await c(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 i=r;o=[i.relation],i.select&&(s[i.relation]=i.select);}else if("relations"in r){let i=r;o=Array.isArray(i.relations)?i.relations:[i.relations],s=i.select??{};}else o=[];else o=Array.isArray(r)?r:[r];let a=await Promise.all(o.map(async i=>{let u=e.relationalKeys?.[i];if(!u)return console.warn(`[populate] Relation "${i}" not found in config`),[i,void 0];let f=t[u.repo];if(!f)return console.warn(`[populate] Repository "${u.repo}" not found in mapping`),[i,void 0];let y=u.sourceKey||i,b=n[y];if(b==null)return [i,u.type==="one"?null:[]];let h=s[i],g=h?{select:h}:void 0;try{if(u.type==="one"){let T=`by${ke(u.key)}`,v=typeof f.get?.[T]=="function"?await f.get[T](b,g):null;return [i,v]}else {let T=`by${ke(u.key)}`,v=typeof f.query?.[T]=="function"?await f.query[T](b,g):[];return [i,v]}}catch(T){return console.error(`[populate] Error populating "${i}":`,T),[i,u.type==="one"?null:[]]}})),c={};for(let[i,u]of a)u!==void 0&&(c[i]=u);return {...n,populated:c}}}}var fa=new Set([4,8,10,13,14]);function ao(e,t,n,r,o,s){let a=()=>new Date;return {backfillKeys:async(i={})=>{let{overwriteCreated:u=false,touchUpdated:f=true,overwritePath:y=false,pageSize:b=300,dryRun:h=false,maxAttempts:g=5,onError:T,onSuccess:v}=i,E=[],A=0,x=0,m=0,p=h?null:e.bulkWriter();p&&(p.onWriteError(d=>{let w=d?.code;if(d.failedAttempts<g&&w!==void 0&&fa.has(w))return true;let R={path:d?.documentRef?.path??"(unknown)",error:d};return E.push(R),T?.(R),false}),v&&p.onWriteResult(d=>v(d.path)));let l;for(;;){let d=t.orderBy(FieldPath.documentId());l&&(d=d.startAfter(l)),d=d.limit(b);let w=await d.get();if(w.empty)break;for(let R of w.docs){A++;let P=R.data(),S={};if(n&&P[n]==null&&(S[n]=R.id),r&&(y||P[r]==null)&&P[r]!==R.ref.path&&(S[r]=R.ref.path),o&&(u||P[o]==null)&&(S[o]=a()),f&&s&&P[s]==null&&(S[s]=a()),Object.keys(S).length===0){m++;continue}x++,p&&p.set(R.ref,S,{merge:true});}if(w.size<b)break;l=w.docs[w.docs.length-1];}return p&&await p.close(),{scanned:A,written:x,skipped:m,failures:E}}}}function io(e,t,n,r,o,s,a){let c=()=>new Date,i=fe(a);return {run:async u=>e.runTransaction(async f=>u({get:async(...b)=>{let h=t(...b),g=await f.get(h);return g.exists?re(X({...g.data(),docId:g.id}),i):null},set:(...b)=>{let h=b[b.length-1],g=typeof h=="object"&&h!==null&&"merge"in h,T=g?b[b.length-2]:b[b.length-1],v=g?b.slice(0,-2):b.slice(0,-1),E=g?h:{merge:true},A=t(...v),x={...T},m=v[v.length-1];n&&m&&(x[n]=m),r&&(x[r]=A.path),o&&x[o]===void 0&&(x[o]=c()),s&&(x[s]=c()),ue(x,a),f.set(A,x,E);},update:(...b)=>{let h=b[b.length-1],g=b.slice(0,-1),T=t(...g),v={...h};s&&(v[s]=c()),ue(v,a),f.update(T,v);},delete:(...b)=>{let h=t(...b);f.delete(h);},raw:f}))}}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 ya(e){let t=e?.documentKey??"docId",n=!!e?.isGroup,r=Ce(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(c=>typeof c=="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:fe(a),_historyIdentityKeys:jn(a),_historySubcollection:a?.enabled?a.subcollection??"history":void 0,_collectionPath:typeof e?.path=="string"?r.collectionPath:null}}function Yt(e,t){let n=ya(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 Ln(e,t,n={}){let r=t.documentKey,o=Ce(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),c=t.isGroup?null:e.collection(o.collectionPath),i=typeof t.refCb=="function"?(...l)=>t.refCb(e,...l):(...l)=>to(e,o.documentPathTemplate??`${o.collectionPath}/{${r}}`,l),u=t.history,f=fe(u),y=jn(u),b=ro(a,t.foreignKeys,c,i,r,f),h=oo(a,t.queryKeys,t.relationalKeys,n,f),g=Yr(a),T=no(c,i,r,t.pathKey,t.createdKey,t.updatedKey,s,o.documentPathTemplate,u),v=Xr(e,i,t.documentKey,t.pathKey,t.createdKey,t.updatedKey,u),E=io(e,i,t.documentKey,t.pathKey,t.createdKey,t.updatedKey,u),A=eo(e,t.createdKey,t.updatedKey,u),x=ao(e,a,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),m=so(t,n),p=u?.enabled?Jr(i,[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(l=>typeof l=="string"),t.path??"(unknown)",u):null;return {ref:a,documentRef:i,get:b,query:h,aggregate:g,...T,batch:v,transaction:E,bulk:A,system:x,...m,...p?{history:p}:{},_historySubcollection:p?u?.subcollection??"history":void 0,_historyConfig:u,_historyShadowKey:f,_historyIdentityKeys:y,schema:t.schema,relationalKeys:t.relationalKeys,_systemKeys:[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(l=>typeof l=="string"),_pathKey:t.pathKey??null,_isGroup:!!t.isGroup,_parentKeys:s,_documentPathTemplate:o.documentPathTemplate,_collectionId:o.collectionId,_collectionPath:o.collectionPath,_createdKey:t.createdKey??null}}var ma="history";function ha(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?Ce(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 ga(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 ba(e,t){return t?`${t}/{docId}`:(console.warn(`[HistoryTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function lo(e,t){let{onDocumentWritten:n}=t.deps,r={},o=e?.rawMapping,s=o?Object.entries(o).map(([a,c])=>[a,ha(c)]):Object.entries(e).map(([a,c])=>[a,ga(c)]);for(let[a,c]of s){let i=c.historyConfig;if(!i?.enabled)continue;let u=i.subcollection??ma,f=i.ttl??t.defaults?.ttl,y=t.repos?.[a],b;if(c.isGroup){let x=y?.triggerPath??c.documentPathTemplate;if(!x){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=x;}else b=y?.triggerPath??c.documentPathTemplate??ba(a,c.collectionPath);if(!b)continue;let h=c.systemKeys,g=h[0]??"docId",T=Qt(i),v={...t.triggerOptions,...i?.triggerOptions,...y?.triggerOptions},E=Object.keys(v).length>0,A=async x=>{try{let m=x.data?.before?.data(),p=x.data?.after?.data(),l;if(!m&&p)l="create";else if(m&&!p)l="delete";else if(m&&p)l="update";else return;let d=String(p?.[g]??m?.[g]??x.params?.docId??x.data?.after?.id??x.data?.before?.id??"");if(!d)return;let w=Gt(m??{},p??{},{include:i.include,exclude:i.exclude,metaFields:T,systemKeys:h});if(l==="update"&&Object.keys(w).length===0)return;let R=Vt(p??m??null,i),P=gt({entityId:d,operation:l,changes:w,meta:R,config:i,ttlOverride:f}),S=x.data?.after?.ref??x.data?.before?.ref;if(!S)return;let C=S.collection(u);await bt(C,P,i,{repoName:a,docId:d,before:m??null,after:p??null});}catch(m){console.error(`[HistoryTriggers] Failed to record history for "${a}":`,m);}};r[`${a}_onHistory`]=n(E?{document:b,...v}:b,A);}return r}function wa(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 xa(e){let t=e.path??e.url??"/",n=t.indexOf("?");return n===-1?t:t.slice(0,n)}var Ae=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}=wa(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=xa(t),s=null,a={};for(let u of this.routes){if(u.method!==r)continue;let f=o.match(u.pattern);if(f){s=u,a={},u.paramNames.forEach((y,b)=>{a[y]=decodeURIComponent(f[b+1]??"");});break}}let c=Object.assign(t,{params:a}),i=s?s.handler:this.notFoundHandler;try{await this.runMiddlewareChain(c,n,i);}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 we(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",c=n??process.env.FUNCTION_REGION??"us-central1",i=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${a}/${c}/${i}${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 Xt(e){if(typeof e=="string")return e;if(Array.isArray(e)){let t=e[0];return typeof t=="string"?t:void 0}}function wt(e){return !!e&&typeof e=="object"&&e.__authExtension===true}function Wn(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=>Wn(s,t,n,r+1));return t?.stringifyArrays===false?o:JSON.stringify(o)}return typeof e=="object"&&e!==null&&t?.stringifyArrays===false?Gn(e,new Set,{},n,r+1):e}var po=32,Ta=5e3;function fo(e,t,n,r=new WeakSet,o=0){if(o>po){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>=Ta)break;let c=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)?fo(a,c,n,r,o+1):n[c]=Wn(a);}r.delete(e);}function Gn(e,t,n,r=new WeakSet,o=0){if(o>po)return {__truncated:true};if(r.has(e))return {__cycle:true};r.add(e);let s={};for(let[a,c]of Object.entries(e)){if(t.has(a))continue;let i=n[a]??a;c!=null&&typeof c=="object"&&!Array.isArray(c)&&!(c instanceof Date)&&!Buffer.isBuffer(c)&&!(c instanceof Uint8Array)&&typeof c.toDate!="function"&&!("latitude"in c&&"longitude"in c)?s[i]=Gn(c,new Set,{},r,o+1):s[i]=Wn(c,{stringifyArrays:false},r,o+1);}return r.delete(e),s}function yo(e){let t={};for(let[n,r]of Object.entries(e)){let o=r;if(typeof o=="string"){let c=o.trim();if(c.startsWith("[")&&c.endsWith("]")||c.startsWith("{")&&c.endsWith("}"))try{o=JSON.parse(c);}catch{}}if(n.startsWith("__")||!n.includes("__")){t[n]=o;continue}let s=n.split("__").filter(Boolean),a=t;for(let c=0;c<s.length-1;c++){let i=s[c];(!a[i]||typeof a[i]!="object"||Array.isArray(a[i]))&&(a[i]={}),a=a[i];}a[s[s.length-1]]=o;}return t}function xt(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 i=false,u={};for(let[f,y]of Object.entries(e)){if(o.has(f)){i=true;continue}u[f]=y;}i&&(a=u);}let c={};fo(a,"",c),r={};for(let[i,u]of Object.entries(c)){if(o.has(i))continue;let f=i.split("__")[0];if(f!==i&&o.has(f))continue;let y=s[i]??(i.includes("__")?s[i.split("__").pop()]:void 0)??i;r[y]=u;}}else {let o=new Set(t?.exclude),s=t?.columnMap??{};r=Gn(e,o,s);}return typeof t?.transformDoc=="function"&&(r=t.transformDoc(r)),r}function Pe(e,t,n){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>${e} \u2014 Sync Admin</title>
|
|
@@ -28,74 +28,74 @@ import {jsx,jsxs,Fragment}from'hono/jsx/jsx-runtime';import {Timestamp,FieldPath
|
|
|
28
28
|
<nav><a href="${t}/">\u2190 Dashboard</a></nav>
|
|
29
29
|
<h1>${e}</h1>
|
|
30
30
|
${n}
|
|
31
|
-
</body></html>`}function
|
|
32
|
-
<td><strong>${
|
|
33
|
-
<td>${
|
|
31
|
+
</body></html>`}function Ie(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function et(e,t,n=200){e.status(n).set("Content-Type","application/json").send(JSON.stringify(t,null,2));}function en(e){return (e.headers?.accept??"").includes("application/json")}function mo(e,t,n,r,o,s,a,c){let i=(o.basePath??"/").replace(/\/$/,"")||"",u=o.featuresFlag??{},f=Xt(o.httpsOptions?.region),y=Array.isArray(t)?t:[t],b=e?.rawMapping,h=[],g=Object.keys(s??{}),T=g.length>0,v=Object.keys(b||e),E=T?g.filter(x=>v.includes(x)||x in e):v;for(let x of E){let m=s[x],p=b?Yt(b[x],()=>e[x]):e[x],l=!!p._isGroup,d=p._collectionPath,w=typeof d=="string"&&d.includes("/");if(!T&&l&&!m?.triggerPath&&!w)continue;let R=m?.adapters&&m.adapters.length>0?y.filter(S=>m.adapters.includes(S.name)):y,P=typeof p._historyShadowKey=="string"?p._historyShadowKey:fe(p._historyConfig);h.push({name:x,schema:p.schema??null,documentKey:p._systemKeys?.[0]??p.documentKey??"docId",tableName:m?.tableName??x,isGroup:l,repoCfg:m,repo:p,adapters:R,historyShadowKey:P});}let A=new Ae;if(o.auth)if(wt(o.auth)){let x=o.auth;for(let m of x.routes){let p=`${i}${m.path}`;m.method==="GET"?A.get(p,m.handler):A.post(p,m.handler);}A.use(x.middleware);}else if(typeof o.auth=="function")A.use(o.auth);else {let x=o.auth.realm??"Sync Admin",m="Basic "+Buffer.from(`${o.auth.username}:${o.auth.password}`).toString("base64");A.use((p,l,d)=>{if((p.headers?.authorization??"")!==m){l.status(401).set("WWW-Authenticate",`Basic realm="${x}"`).set("Content-Type","text/plain").send("Unauthorized");return}d();});}return A.get(`${i}/`,(x,m)=>{let p=we(x,i,f),l=h.map(R=>{let P=[];u.healthCheck&&P.push(`<a class="btn" href="${p}/${R.name}/health">Health</a>`),u.manualSync&&P.push(`<a class="btn btn-primary" href="${p}/${R.name}/force-sync">Force Sync</a>`);let S=R.adapters.map(C=>`<span class="badge badge-ok">${C.name}</span>`).join(" ");return `<tr>
|
|
32
|
+
<td><strong>${R.name}</strong></td>
|
|
33
|
+
<td>${R.tableName}</td>
|
|
34
34
|
<td>${S||'<span class="badge badge-warn">none</span>'}</td>
|
|
35
|
-
<td>${
|
|
36
|
-
<td>${
|
|
35
|
+
<td>${R.isGroup?'<span class="badge badge-warn">group</span>':'<span class="badge badge-ok">collection</span>'}</td>
|
|
36
|
+
<td>${R.schema?"\u2713":"\u2717"}</td>
|
|
37
37
|
<td>${P.join(" ")}</td>
|
|
38
38
|
</tr>`}).join(`
|
|
39
|
-
`),
|
|
39
|
+
`),d=u.configCheck?`<p style="margin-top:.5rem"><a class="btn" href="${p}/config-check">\u2699 Config Check</a></p>`:"",w=Pe("Sync Dashboard",p,`<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
|
-
<tbody>${
|
|
42
|
+
<tbody>${l}</tbody>
|
|
43
43
|
</table>
|
|
44
|
-
${
|
|
45
|
-
</div>`);
|
|
46
|
-
`),
|
|
47
|
-
`);
|
|
44
|
+
${d}
|
|
45
|
+
</div>`);Ie(m,w);}),A.get(`${i}`,(x,m)=>{let p=we(x,i,f);m.status(302).set("Location",`${p}/`).send("");}),u.healthCheck&&A.get(`${i}/:repoName/health`,async(x,m)=>{let p=we(x,i,f),l=h.find(S=>S.name===x.params.repoName);if(!l){Ie(m,Pe("Not Found",p,`<p>Unknown repo: ${x.params.repoName}</p>`),404);return}let d=[];for(let S of l.adapters)if(typeof S.healthCheck=="function"){let C=await S.healthCheck({targetName:l.tableName,primaryKey:l.documentKey,schema:l.schema??void 0,repoConfig:l.repoCfg});d.push({adapterName:S.name,health:C});}else try{let C=await S.targetExists(l.tableName);d.push({adapterName:S.name,health:{healthy:C,targetName:l.tableName,targetExists:C,error:C?null:`Target "${l.tableName}" does not exist`}});}catch(C){d.push({adapterName:S.name,health:{healthy:false,targetName:l.tableName,targetExists:false,error:C?.message??String(C)}});}let w=d.length>0&&d.every(S=>S.health.healthy);if(en(x)){et(m,{repo:l.name,targetName:l.tableName,healthy:w,adapters:d.map(S=>({name:S.adapterName,...S.health}))});return}let R=S=>{let{adapterName:C,health:H}=S,_=H.healthy?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Unhealthy</span>',M="",O=H.details;if(O?.expected&&Array.isArray(O.expected)){let k=O.expected,D=new Set(O.actual??[]),I=O.extra??[],$=k.map(F=>{let j=D.has(F.name)?'<span class="badge badge-ok">OK</span>':'<span class="badge badge-err">MISSING</span>';return `<tr><td>${F.name}</td><td>${F.type}</td><td>${F.nullable?"Yes":"No"}</td><td>${F.isPrimaryKey?"\u2713":""}</td><td>${j}</td></tr>`}).join(`
|
|
46
|
+
`),N=I.map(F=>`<tr><td>${F}</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>
|
|
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>${
|
|
51
|
-
</table>`;}else
|
|
50
|
+
<tbody>${$}${N}</tbody>
|
|
51
|
+
</table>`;}else O?.numberOfDocuments!==void 0&&(M=`<h2>Index Stats</h2>
|
|
52
52
|
<table>
|
|
53
|
-
<tr><th>Documents Count</th><td>${
|
|
54
|
-
<tr><th>Indexing in Progress</th><td>${
|
|
55
|
-
<tr><th>Primary Key</th><td><code>${
|
|
53
|
+
<tr><th>Documents Count</th><td>${O.numberOfDocuments}</td></tr>
|
|
54
|
+
<tr><th>Indexing in Progress</th><td>${O.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>${O.primaryKey??"default"}</code></td></tr>
|
|
56
56
|
</table>`);return `<div class="card" style="margin-top:1rem">
|
|
57
|
-
<h2>Adapter: <code>${C}</code> ${
|
|
58
|
-
<p>Target: <code>${
|
|
59
|
-
${
|
|
60
|
-
${
|
|
61
|
-
</div>`},P=
|
|
62
|
-
<p>Overall status for <strong>${
|
|
57
|
+
<h2>Adapter: <code>${C}</code> ${_}</h2>
|
|
58
|
+
<p>Target: <code>${H.targetName}</code> ${H.targetExists?"":'<span class="badge badge-err">NOT FOUND</span>'}</p>
|
|
59
|
+
${H.error?`<p class="badge badge-err" style="margin-top:.5rem">Error: ${H.error}</p>`:""}
|
|
60
|
+
${M}
|
|
61
|
+
</div>`},P=Pe(`Health: ${l.name}`,p,`<div class="card">
|
|
62
|
+
<p>Overall status for <strong>${l.name}</strong>: ${w?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Issues detected</span>'}</p>
|
|
63
63
|
</div>
|
|
64
|
-
${
|
|
65
|
-
`)}`);
|
|
66
|
-
<p>This will read <strong>all</strong> documents from the <code>${
|
|
67
|
-
and upsert them into all active target storage adapters (${
|
|
64
|
+
${d.map(R).join(`
|
|
65
|
+
`)}`);Ie(m,P);}),u.manualSync&&(A.get(`${i}/:repoName/force-sync`,(x,m)=>{let p=we(x,i,f),l=h.find(w=>w.name===x.params.repoName);if(!l){Ie(m,Pe("Not Found",p,`<p>Unknown repo: ${x.params.repoName}</p>`),404);return}let d=Pe(`Force Sync: ${l.name}`,p,`<div class="card">
|
|
66
|
+
<p>This will read <strong>all</strong> documents from the <code>${l.name}</code> Firestore collection
|
|
67
|
+
and upsert them into all active target storage adapters (${l.adapters.map(w=>w.name).join(", ")}).</p>
|
|
68
68
|
<p class="muted" style="margin:.75rem 0">This may take a while for large collections.</p>
|
|
69
|
-
<form method="POST" action="${p}/${
|
|
69
|
+
<form method="POST" action="${p}/${l.name}/force-sync">
|
|
70
70
|
<button type="submit" class="btn btn-primary">Start Force Sync</button>
|
|
71
71
|
</form>
|
|
72
|
-
</div>`);
|
|
73
|
-
<p class="badge badge-err">Error: ${
|
|
74
|
-
<p>Synced ${
|
|
75
|
-
</div>`),500);return}if(
|
|
76
|
-
<pre style="white-space:pre-wrap">${P.map(
|
|
72
|
+
</div>`);Ie(m,d);}),A.post(`${i}/:repoName/force-sync`,async(x,m)=>{let p=we(x,i,f),l=h.find(O=>O.name===x.params.repoName);if(!l){et(m,{error:`Unknown repo: ${x.params.repoName}`},404);return}let d=l.repo.ref;if(!d){et(m,{error:`No collection reference for "${l.name}"`},400);return}let w=0,R=0,P=[],S=500,C=d.limit(S),H=null;try{for(;;){let k=await(H?C.startAfter(H):C).get();if(k.empty)break;let D=l.historyShadowKey?Array.from(new Set([...l.repoCfg?.exclude??[],l.historyShadowKey])):l.repoCfg?.exclude;for(let I of k.docs){let $=I.data(),N=String($[l.documentKey]??I.id),F=xt($,{exclude:D,columnMap:l.repoCfg?.columnMap,flat:l.repoCfg?.flat,transformDoc:l.repoCfg?.transformDoc});try{await r({operation:"UPSERT",repoName:l.name,docId:N,data:F,timestamp:new Date().toISOString()}),w++;}catch(j){R++;let q=j?.message??String(j);console.error(`[ForceSync:${l.name}] doc=${N} failed:`,j),P.length<5&&P.push(`${N}: ${q}`);}}if(H=k.docs[k.docs.length-1],k.docs.length<S)break}for(let O of l.adapters){let k=`${l.name}:${O.name}`,D=n.get(k)??n.get(l.name);D&&await D.flush();}}catch(O){if(en(x)){et(m,{error:O?.message??String(O),synced:w,errors:R},500);return}Ie(m,Pe(`Force Sync: ${l.name}`,p,`<div class="card">
|
|
73
|
+
<p class="badge badge-err">Error: ${O?.message??String(O)}</p>
|
|
74
|
+
<p>Synced ${w} docs before failure (${R} errors).</p>
|
|
75
|
+
</div>`),500);return}if(en(x)){et(m,{repo:l.name,table:l.tableName,synced:w,errors:R,...P.length>0&&{errorSamples:P}});return}let _=P.length>0?`<details style="margin-top:1rem"><summary>First ${P.length} error(s)</summary>
|
|
76
|
+
<pre style="white-space:pre-wrap">${P.map(O=>O.replace(/[<>&]/g,k=>`&#${k.charCodeAt(0)};`)).join(`
|
|
77
77
|
|
|
78
|
-
`)}</pre></details>`:"",
|
|
79
|
-
<p class="badge ${
|
|
80
|
-
<p>Synced <strong>${
|
|
81
|
-
${
|
|
82
|
-
${
|
|
83
|
-
</div>`);
|
|
78
|
+
`)}</pre></details>`:"",M=Pe(`Force Sync: ${l.name}`,p,`<div class="card">
|
|
79
|
+
<p class="badge ${R>0?"badge-warn":"badge-ok"}">${R>0?"Completed with errors":"Complete"}</p>
|
|
80
|
+
<p>Synced <strong>${w}</strong> documents to targets (${l.adapters.map(O=>O.name).join(", ")}).</p>
|
|
81
|
+
${R>0?`<p class="badge badge-warn">${R} error(s)</p>`:""}
|
|
82
|
+
${_}
|
|
83
|
+
</div>`);Ie(m,M);})),u.configCheck&&A.get(`${i}/config-check`,async(x,m)=>{let p=we(x,i,f),l=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCP_PROJECT??"unknown",d="https://console.cloud.google.com",w=c??"firestore-sync",R=[];for(let O of y)if(O.name==="bigquery")try{await O.targetExists("__nonexistent_health_check__"),R.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable"});}catch(k){let D=k?.message??String(k),I=D.toLowerCase(),$=I.includes("disabled")||I.includes("has not been used")||I.includes("accessnotconfigured"),N=I.includes("permission")||D.includes("403")||I.includes("access denied"),F=I.includes("project")&&I.includes("not found"),j=I.includes("not found")||D.includes("404");$?R.push({name:"BigQuery API",category:"bigquery",status:"error",message:"BigQuery API is not enabled",fix:{gcloud:`gcloud services enable bigquery.googleapis.com --project=${l}`,console:`${d}/apis/library/bigquery.googleapis.com?project=${l}`}}):F?R.push({name:"BigQuery Project",category:"bigquery",status:"error",message:D,fix:{hint:"The GCP project does not exist or the credentials don't have access to it.",console:`${d}/home/dashboard`}}):N?R.push({name:"BigQuery API",category:"bigquery",status:"error",message:`Permission denied: ${D}`,fix:{hint:"Grant the service account BigQuery Data Editor + BigQuery Job User roles",console:`${d}/iam-admin/iam?project=${l}`}}):j?R.push({name:"BigQuery Dataset",category:"bigquery",status:"error",message:`Dataset not found: ${D}`,fix:{hint:"Create the dataset first",gcloud:`bq mk --dataset ${l}:YOUR_DATASET_ID`,console:`${d}/bigquery?project=${l}`}}):R.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable (table lookup returned expected error)"});}else if(O.name==="meilisearch"||typeof O.checkConnection=="function")try{let k=typeof O.checkConnection=="function"?await O.checkConnection():{healthy:await O.targetExists("__nonexistent__")};R.push({name:"Meilisearch API",category:"meilisearch",status:k.healthy?"ok":"error",message:k.healthy?`Meilisearch is reachable${k.version?` (v${k.version})`:""}`:`Meilisearch connection error: ${k.error??"unknown"}`,...k.error&&{fix:{hint:"Ensure Meilisearch is running and host/apiKey options are valid."}}});}catch(k){R.push({name:"Meilisearch API",category:"meilisearch",status:"error",message:`Meilisearch error: ${k?.message??String(k)}`});}for(let O of h)for(let k of O.adapters){let D=k.name==="bigquery"?"bigquery":k.name==="meilisearch"?"meilisearch":"storage";try{let I=await k.targetExists(O.tableName);R.push({name:`[${k.name}] Target: ${O.tableName}`,category:D,status:I?"ok":"warn",message:I?`Target \`${O.tableName}\` exists`:`Target \`${O.tableName}\` does not exist yet`,...!I&&{fix:{hint:"Target will be auto-created on first sync if autoMigrate is enabled."}}});}catch(I){R.push({name:`[${k.name}] Target: ${O.tableName}`,category:D,status:"error",message:I?.message??String(I)});}}if(a)for(let O of h){let k=`${w}-${O.name}`;try{let D=a.topic(k);if(typeof D.exists=="function"){let[I]=await D.exists();R.push({name:`Topic: ${k}`,category:"pubsub",status:I?"ok":"error",message:I?`Topic \`${k}\` exists`:`Topic \`${k}\` does not exist`,...!I&&{fix:{gcloud:`gcloud pubsub topics create ${k} --project=${l}`,console:`${d}/cloudpubsub/topic/list?project=${l}`}}});}else R.push({name:`Topic: ${k}`,category:"pubsub",status:"warn",message:"Cannot verify topic existence (PubSub client doesn't expose .exists())",fix:{gcloud:`gcloud pubsub topics create ${k} --project=${l}`,console:`${d}/cloudpubsub/topic/list?project=${l}`}});}catch(D){let I=D?.message??String(D),$=I.includes("disabled")||I.includes("has not been used");if(R.push({name:$?"Pub/Sub API":`Topic: ${k}`,category:"pubsub",status:"error",message:$?"Pub/Sub API is not enabled":I,fix:$?{gcloud:`gcloud services enable pubsub.googleapis.com --project=${l}`,console:`${d}/apis/library/pubsub.googleapis.com?project=${l}`}:{gcloud:`gcloud pubsub topics create ${k} --project=${l}`,console:`${d}/cloudpubsub/topic/list?project=${l}`}}),$)break}}else R.push({name:"Pub/Sub Client",category:"pubsub",status:"warn",message:"PubSub client not available for config check"});if(en(x)){let O=R.every(k=>k.status==="ok");et(m,{project:l,healthy:O,checks:R});return}let P=O=>O==="ok"?'<span class="badge badge-ok">OK</span>':O==="warn"?'<span class="badge badge-warn">WARN</span>':'<span class="badge badge-err">ERROR</span>',S={bigquery:R.filter(O=>O.category==="bigquery"),meilisearch:R.filter(O=>O.category==="meilisearch"),pubsub:R.filter(O=>O.category==="pubsub"),firestore:R.filter(O=>O.category==="firestore"),storage:R.filter(O=>O.category==="storage")},C=(O,k)=>{if(k.length===0)return "";let D=k.map(I=>{let $="";if(I.fix){let N=[];I.fix.hint&&N.push(`<p class="muted">${I.fix.hint}</p>`),I.fix.gcloud&&N.push(`<pre>$ ${I.fix.gcloud}</pre>`),I.fix.console&&N.push(`<p><a href="${I.fix.console}" target="_blank">Open GCP Console \u2192</a></p>`),$=`<div style="margin-top:.5rem">${N.join("")}</div>`;}return `<tr>
|
|
84
84
|
<td>${P(I.status)}</td>
|
|
85
|
-
<td><strong>${I.name}</strong><br><span class="muted">${I.message}</span>${
|
|
85
|
+
<td><strong>${I.name}</strong><br><span class="muted">${I.message}</span>${$}</td>
|
|
86
86
|
</tr>`}).join(`
|
|
87
|
-
`);return `<h2>${
|
|
87
|
+
`);return `<h2>${O}</h2>
|
|
88
88
|
<table><thead><tr><th style="width:80px">Status</th><th>Check</th></tr></thead>
|
|
89
|
-
<tbody>${D}</tbody></table>`},
|
|
90
|
-
<p>Project: <code>${
|
|
89
|
+
<tbody>${D}</tbody></table>`},_=R.every(O=>O.status==="ok")?'<span class="badge badge-ok">All checks passed</span>':'<span class="badge badge-warn">Some issues found</span>',M=Pe("Config Check",p,`<div class="card">
|
|
90
|
+
<p>Project: <code>${l}</code> ${_}</p>
|
|
91
91
|
${C("BigQuery",S.bigquery)}
|
|
92
92
|
${C("Meilisearch",S.meilisearch)}
|
|
93
93
|
${C("Pub/Sub",S.pubsub)}
|
|
94
94
|
${C("Other Targets",S.storage)}
|
|
95
95
|
${C("Firestore",S.firestore)}
|
|
96
|
-
</div>`);Pe(m,_);}),async(h,m)=>{await A.handle(h,m);}}var Ys="firestore-sync";function Xs(e,t){return t?`${t}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function ea(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?Se(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:fe(e?.history)}}function ta(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:fe(e?._historyConfig)}}function Xr(e,t){let{onDocumentWritten:n}=t.deps.firestoreTriggers,r=t.deps.pubsub,o=t?.topicPrefix??Ys,s={},a=new Map;function c(g){let T=a.get(g);return T||(T=r.topic(g),a.set(g,T),T)}async function i(g,T){await c(g).publishMessage({json:T});}let u=e?.rawMapping,f=u?Object.entries(u).map(([g,T])=>[g,ea(T)]):Object.entries(e).map(([g,T])=>[g,ta(T)]),y=t?.repos,b=Object.keys(y??{}).length>0;for(let[g,T]of f){if(b&&(!y||!(g in y)))continue;let R=y?.[g],O;if(T.isGroup){let x=R?.triggerPath??T.documentPathTemplate;if(!x){console.warn(`[SyncTriggers] Skipping collection-group repo "${g}". Provide a triggerPath in the sync repos config for group collections or use a full path template.`);continue}O=x;}else O=R?.triggerPath??T.documentPathTemplate??Xs(g,T.collectionPath);if(!O)continue;let A=T.documentKey,h=T.historyShadowKey?Array.from(new Set([...R?.exclude??[],T.historyShadowKey])):R?.exclude,m=`${o}-${g}`,p={...t?.triggerOptions,...R?.triggerOptions},d=Object.keys(p).length>0,l=async x=>{let v=x.data?.before,P=x.data?.after;if(!v&&!P)return;let S=!!v?.exists,C=!!P?.exists;if(!S&&C){let $=P.data();if(!$)return;let H=String($[A]??P.id),_=ht($,{exclude:h,columnMap:R?.columnMap,flat:R?.flat,transformDoc:R?.transformDoc}),E={operation:"INSERT",repoName:g,docId:H,data:_,timestamp:new Date().toISOString(),version:Date.now()};await i(m,E);}else if(S&&C){let $=P.data();if(!$)return;let H=String($[A]??P.id),_=ht($,{exclude:h,columnMap:R?.columnMap,flat:R?.flat,transformDoc:R?.transformDoc}),E={operation:"UPSERT",repoName:g,docId:H,data:_,timestamp:new Date().toISOString(),version:Date.now()};await i(m,E);}else if(S&&!C){let $=v.data(),H=String($?.[A]??v.id),_={operation:"DELETE",repoName:g,docId:H,data:null,timestamp:new Date().toISOString(),version:Date.now()};await i(m,_);}};s[`${g}_onSync`]=n(d?{document:O,...p}:O,l);}return s}var me="__sync_version";Je();var ra=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function oa(e){let t=e,n=false;for(;;){let r=V(t);if(!ra.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(n=true);let o=se(t);if(!o)break;t=o;}return {inner:t,nullable:n}}var sa={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function no(e,t,n,r,o,s,a,c){for(let[i,u]of Object.entries(e)){let f=n?`${n}__${i}`:i;if(o.has(i)||o.has(f))continue;let{inner:y,nullable:w}=oa(u),b=V(y),g=r||w;if(b==="ZodObject"){let A=ae(y);no(A,t,f,g,o,s,a,c);continue}let T=sa[b]??"json",R=f===a||i===a,O=s[f]??s[i]??f;c.push({name:O,sqlType:t.mapType(T),nullable:R?false:g,isPrimaryKey:R});}}function Rt(e,t,n={}){let{primaryKey:r,exclude:o=[],columnMap:s={}}=n,a=new Set(o),c=ae(e),i=[];return no(c,t,"",false,a,s,r,i),i.some(u=>u.name===me)||i.push({name:me,sqlType:t.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),i}var en=class{constructor(t){this.buffer=[];this.flushing=false;this.flushPromise=null;this.timer=null;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();},n),typeof this.timer=="object"&&"unref"in this.timer&&this.timer.unref());}get size(){return this.buffer.length}enqueue(...t){this.buffer.push(...t),this.buffer.length>=this.batchSize&&this.flush();}async flush(){for(;this.flushPromise;)await this.flushPromise;this.buffer.length!==0&&(this.flushing=true,this.flushPromise=this._drain().finally(()=>{this.flushing=false,this.flushPromise=null;}),await this.flushPromise);}async _drain(){for(;this.buffer.length>0&&await this._doFlush(););}async _doFlush(){let t=this.buffer.splice(0,this.batchSize);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 c=Number(a[me]??0);Number(s.data[me]??0)>=c&&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));}catch(n){if(this.onFlushError)await this.onFlushError(t,n);else return this.buffer.unshift(...t),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();}};var ao=new Set;async function da(e,t,n,r,o,s,a){let c=`${e}:${t.name}`;if(!ao.has(c)){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 i=t,u=Rt(n,i.dialect,{primaryKey:o,exclude:s,columnMap:a});if(!await i.tableExists(r))await i.createTable({tableName:r,columns:u});else {let y=new Set(await i.getTableColumns(r)),w=u.filter(b=>!y.has(b.name));w.length>0&&(await i.addColumns(r,w),await i.onSchemaChange?.(r));}}ao.add(c);}}function io(e,t){let{deps:n,adapter:r,adapters:o,batchSize:s=100,flushIntervalMs:a=5e3,autoMigrate:c=false,topicPrefix:i="firestore-sync",maxDlqAttempts:u=5,workerOptions:f,repos:y={}}=t,b=(o||(Array.isArray(r)?r:r?[r]:[])).map(h=>typeof h=="function"?h():h);function g(h){let m=y[h];if(m?.adapters&&m.adapters.length>0){let p=new Set(m.adapters);return b.filter(d=>p.has(d.name))}return b}let T=new Map;function R(h,m,p){let d=`${h}:${m.name}`,l=T.get(d);if(l)return l;let v=y[h]?.tableName??h,P=`${i}-${h}-${m.name}-dlq`,S=n.pubsub.topic(P),C=false,$=async()=>{if(!C){try{await S.create(),console.info(`[SyncWorker:${m.name}] Created DLQ topic "${P}"`);}catch(_){if(_?.code!==6)throw _}C=true;}},H=async(_,E)=>{console.error(`[SyncWorker:${m.name}] Flush failed for "${h}" (${_.length} events):`,E),await $(),await Promise.all(_.map(k=>{let D=(k.attempts??0)+1;if(u>0&&D>u)return console.error(`[SyncWorker:${m.name}] Dropping event for "${h}" after ${D-1} DLQ attempts:`,{docId:k.docId,operation:k.operation}),Promise.resolve();let I={...k,attempts:D,firstFailedAt:k.firstFailedAt??Date.now()};return S.publishMessage({json:I})}));};return l=new en({adapter:m,tableName:v,primaryKey:p,batchSize:s,flushIntervalMs:a,onFlushError:H}),T.set(d,l),T.has(h)||T.set(h,l),l}async function O(h){let{repoName:m}=h,p=e[m];if(!p){console.warn(`[SyncWorker] Unknown repo "${m}", skipping event`);return}let d=p._systemKeys?.[0]??p.documentKey??"docId",l=y[m],x=l?.columnMap,v=x?.[d]??d;h.data&&(h.data[me]=h.version??Date.now());let P=g(m);for(let S of P){if(c){let $=p.schema??void 0;if($){let H=l?.tableName??m;await da(m,S,$,H,v,l?.exclude,x);}}R(m,S,v).enqueue(h);}}function A(h){let m=async p=>{let d=p.data?.message?.json??p.data?.json;if(!d){console.warn("[SyncWorker] Received empty PubSub message");return}await O(d);let l=g(d.repoName);for(let x of l){let v=`${d.repoName}:${x.name}`,P=T.get(v);P&&await P.flush();}};return f?n.pubsubHandler.onMessagePublished({topic:h,...f},m):n.pubsubHandler.onMessagePublished(h,m)}return {handleMessage:O,createHandler:A,queues:T,async shutdown(){let h=[],m=new Set;for(let p of T.values())m.has(p)||(m.add(p),h.push(p.shutdown()));await Promise.all(h);}}}var ua="firestore-sync";function co(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 lo(e,t){let{deps:n,adapter:r,adapters:o,topicPrefix:s=ua,batchSize:a,flushIntervalMs:c,autoMigrate:i,admin:u,workerOptions:f,triggerOptions:y,repos:w}=t,b=co(n.pubsub),T=(o||(Array.isArray(r)?r:r?[r]:[])).map(S=>co(S)),R=Xr(e,{deps:{firestoreTriggers:n.firestoreTriggers,pubsub:b},topicPrefix:s,triggerOptions:y,repos:w}),O=io(e,{deps:{pubsubHandler:n.pubsubHandler,pubsub:b},adapters:T,batchSize:a,flushIntervalMs:c,autoMigrate:i,topicPrefix:s,workerOptions:f,repos:w}),A={},h=w,m=e?.rawMapping,p=Object.keys(h??{}),d=p.length>0,l=Object.keys(m||e),x=d?p.filter(S=>l.includes(S)||S in e):l;for(let S of x){let C=e?.rawMapping,$=C?!!C[S]?.isGroup:!!e[S]?._isGroup,H=C?C[S]?.path:e[S]?._collectionPath,_=typeof H=="string"&&H.includes("/");!d&&$&&!h?.[S]?.triggerPath&&!_||(A[`sync_${S}`]=O.createHandler(`${s}-${S}`));}let v=null;u&&(v=Yr(e,T,O.queues,O.handleMessage,u,w??{},b,s),A.adminsync=u.onRequest?u.httpsOptions?u.onRequest(u.httpsOptions,v):u.onRequest(v):v);let P={functions:{...R,...A},adminHandler:v,handleMessage:O.handleMessage,queues:O.queues,shutdown:O.shutdown};for(let S of ["adminHandler","handleMessage","queues","shutdown"])Object.defineProperty(P,S,{enumerable:false});return P}function pa(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}=Sr("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:
|
|
96
|
+
</div>`);Ie(m,M);}),async(x,m)=>{await A.handle(x,m);}}var Sa="firestore-sync";function ka(e,t){return t?`${t}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function Ca(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?Ce(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:fe(e?.history)}}function Aa(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:fe(e?._historyConfig)}}function ho(e,t){let{onDocumentWritten:n}=t.deps.firestoreTriggers,r=t.deps.pubsub,o=t?.topicPrefix??Sa,s={},a=new Map;function c(g){let T=a.get(g);return T||(T=r.topic(g),a.set(g,T),T)}async function i(g,T){await c(g).publishMessage({json:T});}let u=e?.rawMapping,f=u?Object.entries(u).map(([g,T])=>[g,Ca(T)]):Object.entries(e).map(([g,T])=>[g,Aa(T)]),y=t?.repos,h=Object.keys(y??{}).length>0;for(let[g,T]of f){if(h&&(!y||!(g in y)))continue;let v=y?.[g],E;if(T.isGroup){let w=v?.triggerPath??T.documentPathTemplate;if(!w){console.warn(`[SyncTriggers] Skipping collection-group repo "${g}". Provide a triggerPath in the sync repos config for group collections or use a full path template.`);continue}E=w;}else E=v?.triggerPath??T.documentPathTemplate??ka(g,T.collectionPath);if(!E)continue;let A=T.documentKey,x=T.historyShadowKey?Array.from(new Set([...v?.exclude??[],T.historyShadowKey])):v?.exclude,m=`${o}-${g}`,p={...t?.triggerOptions,...v?.triggerOptions},l=Object.keys(p).length>0,d=async w=>{let R=w.data?.before,P=w.data?.after;if(!R&&!P)return;let S=!!R?.exists,C=!!P?.exists;if(!S&&C){let H=P.data();if(!H)return;let _=String(H[A]??P.id),M=xt(H,{exclude:x,columnMap:v?.columnMap,flat:v?.flat,transformDoc:v?.transformDoc}),O={operation:"INSERT",repoName:g,docId:_,data:M,timestamp:new Date().toISOString(),version:Date.now()};await i(m,O);}else if(S&&C){let H=P.data();if(!H)return;let _=String(H[A]??P.id),M=xt(H,{exclude:x,columnMap:v?.columnMap,flat:v?.flat,transformDoc:v?.transformDoc}),O={operation:"UPSERT",repoName:g,docId:_,data:M,timestamp:new Date().toISOString(),version:Date.now()};await i(m,O);}else if(S&&!C){let H=R.data(),_=String(H?.[A]??R.id),M={operation:"DELETE",repoName:g,docId:_,data:null,timestamp:new Date().toISOString(),version:Date.now()};await i(m,M);}};s[`${g}_onSync`]=n(l?{document:E,...p}:E,d);}return s}var me="__sync_version";tt();var Oa=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function Pa(e){let t=e,n=false;for(;;){let r=G(t);if(!Oa.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(n=true);let o=se(t);if(!o)break;t=o;}return {inner:t,nullable:n}}var Ia={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function wo(e,t,n,r,o,s,a,c){for(let[i,u]of Object.entries(e)){let f=n?`${n}__${i}`:i;if(o.has(i)||o.has(f))continue;let{inner:y,nullable:b}=Pa(u),h=G(y),g=r||b;if(h==="ZodObject"){let A=ae(y);wo(A,t,f,g,o,s,a,c);continue}let T=Ia[h]??"json",v=f===a||i===a,E=s[f]??s[i]??f;c.push({name:E,sqlType:t.mapType(T),nullable:v?false:g,isPrimaryKey:v});}}function Ct(e,t,n={}){let{primaryKey:r,exclude:o=[],columnMap:s={}}=n,a=new Set(o),c=ae(e),i=[];return wo(c,t,"",false,a,s,r,i),i.some(u=>u.name===me)||i.push({name:me,sqlType:t.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),i}var sn=class{constructor(t){this.buffer=[];this.flushing=false;this.flushPromise=null;this.timer=null;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();},n),typeof this.timer=="object"&&"unref"in this.timer&&this.timer.unref());}get size(){return this.buffer.length}enqueue(...t){this.buffer.push(...t),this.buffer.length>=this.batchSize&&this.flush();}async flush(){for(;this.flushPromise;)await this.flushPromise;this.buffer.length!==0&&(this.flushing=true,this.flushPromise=this._drain().finally(()=>{this.flushing=false,this.flushPromise=null;}),await this.flushPromise);}async _drain(){for(;this.buffer.length>0&&await this._doFlush(););}async _doFlush(){let t=this.buffer.splice(0,this.batchSize);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 c=Number(a[me]??0);Number(s.data[me]??0)>=c&&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));}catch(n){if(this.onFlushError)await this.onFlushError(t,n);else return this.buffer.unshift(...t),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();}};var To=new Set;async function _a(e,t,n,r,o,s,a){let c=`${e}:${t.name}`;if(!To.has(c)){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 i=t,u=Ct(n,i.dialect,{primaryKey:o,exclude:s,columnMap:a});if(!await i.tableExists(r))await i.createTable({tableName:r,columns:u});else {let y=new Set(await i.getTableColumns(r)),b=u.filter(h=>!y.has(h.name));b.length>0&&(await i.addColumns(r,b),await i.onSchemaChange?.(r));}}To.add(c);}}function So(e,t){let{deps:n,adapter:r,adapters:o,batchSize:s=100,flushIntervalMs:a=5e3,autoMigrate:c=false,topicPrefix:i="firestore-sync",maxDlqAttempts:u=5,workerOptions:f,repos:y={}}=t,h=(o||(Array.isArray(r)?r:r?[r]:[])).map(x=>typeof x=="function"?x():x);function g(x){let m=y[x];if(m?.adapters&&m.adapters.length>0){let p=new Set(m.adapters);return h.filter(l=>p.has(l.name))}return h}let T=new Map;function v(x,m,p){let l=`${x}:${m.name}`,d=T.get(l);if(d)return d;let R=y[x]?.tableName??x,P=`${i}-${x}-${m.name}-dlq`,S=n.pubsub.topic(P),C=false,H=async()=>{if(!C){try{await S.create(),console.info(`[SyncWorker:${m.name}] Created DLQ topic "${P}"`);}catch(M){if(M?.code!==6)throw M}C=true;}},_=async(M,O)=>{console.error(`[SyncWorker:${m.name}] Flush failed for "${x}" (${M.length} events):`,O),await H(),await Promise.all(M.map(k=>{let D=(k.attempts??0)+1;if(u>0&&D>u)return console.error(`[SyncWorker:${m.name}] Dropping event for "${x}" after ${D-1} DLQ attempts:`,{docId:k.docId,operation:k.operation}),Promise.resolve();let I={...k,attempts:D,firstFailedAt:k.firstFailedAt??Date.now()};return S.publishMessage({json:I})}));};return d=new sn({adapter:m,tableName:R,primaryKey:p,batchSize:s,flushIntervalMs:a,onFlushError:_}),T.set(l,d),T.has(x)||T.set(x,d),d}async function E(x){let{repoName:m}=x,p=e[m];if(!p){console.warn(`[SyncWorker] Unknown repo "${m}", skipping event`);return}let l=p._systemKeys?.[0]??p.documentKey??"docId",d=y[m],w=d?.columnMap,R=w?.[l]??l;x.data&&(x.data[me]=x.version??Date.now());let P=g(m);for(let S of P){if(c){let H=p.schema??void 0;if(H){let _=d?.tableName??m;await _a(m,S,H,_,R,d?.exclude,w);}}v(m,S,R).enqueue(x);}}function A(x){let m=async p=>{let l=p.data?.message?.json??p.data?.json;if(!l){console.warn("[SyncWorker] Received empty PubSub message");return}await E(l);let d=g(l.repoName);for(let w of d){let R=`${l.repoName}:${w.name}`,P=T.get(R);P&&await P.flush();}};return f?n.pubsubHandler.onMessagePublished({topic:x,...f},m):n.pubsubHandler.onMessagePublished(x,m)}return {handleMessage:E,createHandler:A,queues:T,async shutdown(){let x=[],m=new Set;for(let p of T.values())m.has(p)||(m.add(p),x.push(p.shutdown()));await Promise.all(x);}}}var Na="firestore-sync";function ko(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 Co(e,t){let{deps:n,adapter:r,adapters:o,topicPrefix:s=Na,batchSize:a,flushIntervalMs:c,autoMigrate:i,admin:u,workerOptions:f,triggerOptions:y,repos:b}=t,h=ko(n.pubsub),T=(o||(Array.isArray(r)?r:r?[r]:[])).map(S=>ko(S)),v=ho(e,{deps:{firestoreTriggers:n.firestoreTriggers,pubsub:h},topicPrefix:s,triggerOptions:y,repos:b}),E=So(e,{deps:{pubsubHandler:n.pubsubHandler,pubsub:h},adapters:T,batchSize:a,flushIntervalMs:c,autoMigrate:i,topicPrefix:s,workerOptions:f,repos:b}),A={},x=b,m=e?.rawMapping,p=Object.keys(x??{}),l=p.length>0,d=Object.keys(m||e),w=l?p.filter(S=>d.includes(S)||S in e):d;for(let S of w){let C=e?.rawMapping,H=C?!!C[S]?.isGroup:!!e[S]?._isGroup,_=C?C[S]?.path:e[S]?._collectionPath,M=typeof _=="string"&&_.includes("/");!l&&H&&!x?.[S]?.triggerPath&&!M||(A[`sync_${S}`]=E.createHandler(`${s}-${S}`));}let R=null;u&&(R=mo(e,T,E.queues,E.handleMessage,u,b??{},h,s),A.adminsync=u.onRequest?u.httpsOptions?u.onRequest(u.httpsOptions,R):u.onRequest(R):R);let P={functions:{...v,...A},adminHandler:R,handleMessage:E.handleMessage,queues:E.queues,shutdown:E.shutdown};for(let S of ["adminHandler","handleMessage","queues","shutdown"])Object.defineProperty(P,S,{enumerable:false});return P}function Fa(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}=$r("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:
|
|
97
97
|
bun add meilisearch # or npm install meilisearch
|
|
98
|
-
Original error: ${t?.message??String(t)}`)}}function
|
|
98
|
+
Original error: ${t?.message??String(t)}`)}}function ja(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 an=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=Fa(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(c=>{let i=o?yo(c):c;return typeof this.options.transformDoc=="function"&&(i=this.options.transformDoc(i)),i});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:c,...i}=s,u={...i,displayedAttributes:i.displayedAttributes??a??c};u.displayedAttributes===void 0&&delete u.displayedAttributes;let f=this.client.index(n);if(typeof f.getSettings=="function")try{let y=await f.getSettings();if(ja(y,u))return}catch{}await f.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)}}}};tt();tt();function za(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/^\s/,"").replace(/^./,t=>t.toUpperCase())}function Ao(e){let t=e,n=true,r=false,o;for(;;){let s=G(t);if(s==="ZodOptional")n=false,t=se(t);else if(s==="ZodNullable")n=false,r=true,t=se(t);else if(s==="ZodDefault")n=false,o=go(t),t=se(t);else if(s==="ZodEffects"||s==="ZodPipe"||s==="ZodTransform"){let a=Rt(t);if(!a)break;t=a;}else break}return {inner:t,required:n,nullable:r,defaultValue:o}}function pe(e,t=""){if(G(e)==="ZodObject"){let r=ae(e);return Object.entries(r).map(([o,s])=>Eo(t?`${t}.${o}`:o,o,s))}return [Eo(t||"value",t||"value",e)]}function Eo(e,t,n){let{inner:r,required:o,nullable:s,defaultValue:a}=Ao(n),c=G(r),i=za(t.split(".").pop()??t);switch(c){case "ZodString":{let u=bo(r),f=u.includes("email"),y=u.includes("url");return {name:e,label:i,type:"text",required:o,nullable:s,defaultValue:a,hint:f?"email":y?"url":void 0}}case "ZodNumber":case "ZodBigInt":return {name:e,label:i,type:"number",required:o,nullable:s,defaultValue:a};case "ZodBoolean":return {name:e,label:i,type:"checkbox",required:o,nullable:s,defaultValue:a};case "ZodDate":case "ZodCoerce":return {name:e,label:i,type:"datetime-local",required:o,nullable:s,defaultValue:a};case "ZodEnum":{let u=vt(r);return {name:e,label:i,type:"select",required:o,nullable:s,defaultValue:a,options:u}}case "ZodNativeEnum":{let u=Tt(r),f=Object.values(u).filter(y=>typeof y=="string");return {name:e,label:i,type:"select",required:o,nullable:s,defaultValue:a,options:f}}case "ZodLiteral":{let u=String(St(r)??"");return {name:e,label:i,type:"select",required:o,nullable:s,defaultValue:a,options:[u]}}case "ZodUnion":{let u=kt(r);if(u.length>0&&u.every(h=>G(h)==="ZodLiteral")){let h=u.map(g=>String(St(g)??""));return {name:e,label:i,type:"select",required:o,nullable:s,defaultValue:a,options:h}}if(u.some(h=>G(h)==="ZodDate"))return {name:e,label:i,type:"datetime-local",required:o,nullable:s,defaultValue:a};let b=u.find(h=>{if(G(h)==="ZodObject"){let g=ae(h);return "_latitude"in g&&"_longitude"in g||"latitude"in g&&"longitude"in g}return false});return b?{name:e,label:i,type:"textarea",required:o,nullable:s,defaultValue:a,nested:pe(b,e),hint:"GeoPoint"}:{name:e,label:i,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON"}}case "ZodObject":{let u=pe(r,e);return {name:e,label:i,type:"textarea",required:o,nullable:s,defaultValue:a,nested:u,hint:"JSON object"}}case "ZodArray":{let u=tn(r);if(!u)return {name:e,label:i,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"};let{inner:f}=Ao(u),y=G(f),b,h,g;switch(y){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=vt(f);break;case "ZodNativeEnum":b="select",h=Object.values(Tt(f)).filter(T=>typeof T=="string");break;case "ZodObject":b="object",g=pe(f);break;default:return {name:e,label:i,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"}}return {name:e,label:i,type:"textarea",required:o,nullable:s,defaultValue:a,arrayElementType:b,arrayElementOptions:h,arrayElementFields:g}}default:return {name:e,label:i,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON"}}}function At(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__",c=!a&&e.defaultValue!=null?String(e.defaultValue):"",i=e.nullable&&e.type!=="checkbox"?`<span class="flex items-center gap-1 shrink-0">
|
|
99
99
|
<input type="hidden" id="${r}__isnull" name="${o}__isnull" value="${a?"1":""}">
|
|
100
100
|
<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">
|
|
101
101
|
<input type="checkbox" class="checkbox checkbox-xs" ${a?"checked":""}
|
|
@@ -132,7 +132,7 @@ Original error: ${t?.message??String(t)}`)}}function fa(e,t){if(!e||!t)return f
|
|
|
132
132
|
${e.required&&!e.nullable?"":'<option value="">\u2014 optional \u2014</option>'}
|
|
133
133
|
${(e.options??[]).map(f=>`<option value="${K(f)}"${c===f?" selected":""}>${K(f)}</option>`).join(`
|
|
134
134
|
`)}
|
|
135
|
-
</select>`;break;case "textarea":if(e.arrayElementType)return
|
|
135
|
+
</select>`;break;case "textarea":if(e.arrayElementType)return Ba(e,t);if(e.nested&&e.nested.length>0){let f=e.nested.map(y=>At(y,t+1)).join(`
|
|
136
136
|
`);return `
|
|
137
137
|
<fieldset class="fieldset border border-base-300 rounded-box p-3 mb-3 ${n}">
|
|
138
138
|
<legend class="fieldset-legend text-xs font-semibold text-base-content/60 px-1">
|
|
@@ -156,9 +156,9 @@ Original error: ${t?.message??String(t)}`)}}function fa(e,t){if(!e||!t)return f
|
|
|
156
156
|
<div class="flex-1 min-w-0">${u}</div>
|
|
157
157
|
${i}
|
|
158
158
|
</div>
|
|
159
|
-
</div>`}function K(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function
|
|
160
|
-
`):a.map(f=>
|
|
161
|
-
`),i=s?
|
|
159
|
+
</div>`}function K(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Ba(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 c=s?a.map(f=>Po(e,f??{})).join(`
|
|
160
|
+
`):a.map(f=>Oo(e,f)).join(`
|
|
161
|
+
`),i=s?Po(e,{}):Oo(e,""),u=e.nullable?`<span class="flex items-center gap-1 mt-2">
|
|
162
162
|
<input type="hidden" id="${r}__isnull" name="${K(e.name)}__isnull" value="${o?"1":""}">
|
|
163
163
|
<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">
|
|
164
164
|
<input type="checkbox" class="checkbox checkbox-xs" ${o?"checked":""}
|
|
@@ -184,7 +184,7 @@ Original error: ${t?.message??String(t)}`)}}function fa(e,t){if(!e||!t)return f
|
|
|
184
184
|
<template data-frs-array-tpl>${i}</template>
|
|
185
185
|
<button type="button" class="btn btn-xs btn-outline mt-1" data-frs-array-add>+ Add</button>
|
|
186
186
|
${u}
|
|
187
|
-
</fieldset>`}function
|
|
187
|
+
</fieldset>`}function Oo(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">
|
|
188
188
|
<option value="">\u2014</option>
|
|
189
189
|
${(e.arrayElementOptions??[]).map(o=>`<option value="${K(o)}"${n===o?" selected":""}>${K(o)}</option>`).join("")}
|
|
190
190
|
</select>`;break;case "checkbox":r=`<label class="flex items-center gap-2 flex-1 cursor-pointer">
|
|
@@ -193,7 +193,7 @@ Original error: ${t?.message??String(t)}`)}}function fa(e,t){if(!e||!t)return f
|
|
|
193
193
|
</label>`;break;case "number":r=`<input type="number" data-frs-val value="${K(n)}" class="input input-bordered input-sm flex-1">`;break;case "datetime-local":r=`<input type="datetime-local" data-frs-val value="${K(n)}" class="input input-bordered input-sm flex-1">`;break;default:r=`<input type="text" data-frs-val value="${K(n)}" class="input input-bordered input-sm flex-1">`;}return `<div class="flex items-center gap-2 mb-2" data-frs-array-item>
|
|
194
194
|
${r}
|
|
195
195
|
<button type="button" class="btn btn-xs btn-ghost text-error" data-frs-array-rm>×</button>
|
|
196
|
-
</div>`}function
|
|
196
|
+
</div>`}function Po(e,t){return `<div class="border border-base-200 rounded p-3 mb-2" data-frs-array-item>
|
|
197
197
|
<div class="flex justify-end mb-1">
|
|
198
198
|
<button type="button" class="btn btn-xs btn-ghost text-error" data-frs-array-rm>×</button>
|
|
199
199
|
</div>
|
|
@@ -222,7 +222,7 @@ Original error: ${t?.message??String(t)}`)}}function fa(e,t){if(!e||!t)return f
|
|
|
222
222
|
<input type="text" data-frs-key="${K(o.name)}" value="${K(a)}" class="input input-bordered input-sm w-full">
|
|
223
223
|
</div>`}}).join(`
|
|
224
224
|
`)}
|
|
225
|
-
</div>`}function
|
|
225
|
+
</div>`}function De(e,t,n,r="Save"){let o=e.map(s=>At(s)).join(`
|
|
226
226
|
`);return `
|
|
227
227
|
<form action="${K(t)}" method="${n}" novalidate data-frs-form>
|
|
228
228
|
${o}
|
|
@@ -230,7 +230,7 @@ Original error: ${t?.message??String(t)}`)}}function fa(e,t){if(!e||!t)return f
|
|
|
230
230
|
<button type="submit" class="btn btn-primary btn-sm">${K(r)}</button>
|
|
231
231
|
<button type="button" class="btn btn-ghost btn-sm" onclick="history.back()">Cancel</button>
|
|
232
232
|
</div>
|
|
233
|
-
</form>`}var
|
|
233
|
+
</form>`}var qa=new Set(["<","<=",">",">=","!="]),Ka=new Set(["array-contains","array-contains-any"]);function Qn(e){return e==="desc"?"DESCENDING":"ASCENDING"}function Ua(e){return Ce(e).collectionId||e}function Za(e,t,n,r,o){let s=[],a=new Set;for(let i of r)if(i.op==="=="||i.op==="in"||i.op==="not-in"){if(a.has(i.field))continue;a.add(i.field),s.push({fieldPath:i.field,order:"ASCENDING"});}for(let i of r)if(Ka.has(i.op)){if(a.has(i.field))continue;a.add(i.field),s.push({fieldPath:i.field,arrayConfig:"CONTAINS"});}for(let i of r)if(qa.has(i.op)){if(a.has(i.field))continue;a.add(i.field);let u=o?.field===i.field?Qn(o.dir):"ASCENDING";s.push({fieldPath:i.field,order:u});}if(o&&!a.has(o.field)&&s.push({fieldPath:o.field,order:Qn(o.dir)}),s.length===1&&n)return Ga(e,t,s[0]);let c=o&&s.some(i=>i.fieldPath===o.field)?Qn(o.dir):"ASCENDING";return s.push({fieldPath:"__name__",order:c}),La(e,t,n,s)}function La(e,t,n,r,o="(default)"){let s=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,a=[...Xn(1,s),...cn(2,n?2:1)];for(let u of r)a.push(...Io(3,Do(u)));let c=o==="(default)"?"-default-":o,i=encodeURIComponent($o(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${c}/indexes?create_composite=${i}`}function Wa(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function Jn(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function Yn(e,t){return e<<3|t}function Xn(e,t){let n=Array.from(new TextEncoder().encode(t));return [Yn(e,2),...Jn(n.length),...n]}function cn(e,t){return [Yn(e,0),...Jn(t)]}function Io(e,t){return [Yn(e,2),...Jn(t.length),...t]}function Do(e){let t=[...Xn(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...cn(3,1)):t.push(...cn(2,e.order==="DESCENDING"?2:1)),t}function $o(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 Ga(e,t,n,r="(default)"){let o=`projects/${e}/databases/${r}/collectionGroups/${t}/fields/${n.fieldPath}`,s=[...Xn(1,o),...cn(2,2),...Io(3,Do(n))],a=r==="(default)"?"-default-":r,c=encodeURIComponent($o(s));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${c}`}function Va(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 qe(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Et(e,t){let n=e??{},r=qe(e),o;if(r&&(o=n.message?Wa(n.message):void 0,!o)){let s=Va(t.ref);if(s){let a=Ua(t.path);o=Za(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}}ln();var Mo=`// \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
|
|
234
234
|
function frsGetBasePath() {
|
|
235
235
|
var root = document.querySelector("[data-frs-panel-root]");
|
|
236
236
|
var bp = root && root.getAttribute("data-frs-base-path");
|
|
@@ -1152,7 +1152,7 @@ function initColumnReorder(table) {
|
|
|
1152
1152
|
});
|
|
1153
1153
|
});
|
|
1154
1154
|
}
|
|
1155
|
-
`;function kt(){return jsx("script",{dangerouslySetInnerHTML:{__html:wo}})}Gn();function De(e){return "<!DOCTYPE html>"+renderToString(e)}var $a=["corporate","silk","dark"],Ma=()=>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:$a.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))})]}),$e=({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(Ma,{})})]}),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,c)=>a.href?jsx("li",{children:jsx("a",{href:a.href,children:a.label})},c):jsx("li",{class:"text-base-content/60",children:a.label},c))})}),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(Vn,{basePath:s}),jsx(kt,{})]})]})};function Qn(e,t){return De(jsx($e,{opts:t,children:jsx("div",{dangerouslySetInnerHTML:{__html:e}})}))}function Jn(e,t){return De(jsx($e,{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 To=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],_a=[{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"}],Ha=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function Fa(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return _a;case "ZodBoolean":return To;case "ZodArray":return Ha;default:return To}}var Me="__null__";function ja(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="${Me}"]');if(!o){o=document.createElement('option');o.value='${Me}';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='${Me}';i.readOnly=true;}i.style.opacity='0.55';}else{i.style.opacity='';if(i.tagName==='SELECT'){var o2=i.querySelector('option[value="${Me}"][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!=='${Me}')?i.dataset._prev:'';}}})(this)`}function Na(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 Ot({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:ja(e)}),jsx("span",{children:"\u2205"})]})}function za({col:e,active:t}){let n=t?.value??"",r=n===Me,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 c=new Set(n.split(",").map(u=>u.trim()).filter(Boolean)),i=`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:c.has(u),"data-enum-group":i,onchange:Na(o,i)}),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(c=>jsx("option",{value:c,selected:n===c,children:c},c)),e.nullable&&jsx("option",{value:Me,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx(Ot,{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:Me,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx(Ot,{inputId:o,active:r})]});if(e.zodType==="ZodArray"){let c=t?.op==="array-contains-any";return jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:c?"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(Ot,{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(Ot,{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(Ot,{inputId:o,active:r})]})}function Yn({action:e,columnMeta:t,activeFilters:n,isGroup:r}){let o=Object.fromEntries(n.map(i=>[i.field,i])),s=n.length>0,a=n.length>=2||r&&s,c=t.filter(i=>i.zodType!=="ZodObject"&&i.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:c.map(i=>{let u=Fa(i.zodType),f=o[i.name],y=f?.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:i.name}),jsxs("div",{class:"flex gap-1.5",children:[u.length>1?jsx("select",{name:`fo_${i.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:u.map(w=>jsx("option",{value:w.value,selected:w.value===y,children:w.label},w.value))}):jsx("input",{type:"hidden",name:`fo_${i.name}`,value:u[0].value}),jsx(za,{col:i,active:f})]})]},i.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 Xn(e,t,n,r,o,s){let a=n==="create"?`Create ${e}`:`Edit ${e} / ${r??""}`,c=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 De(jsx($e,{opts:{title:a,breadcrumb:c,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}})})})}))}rn();Wn();function er(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 So(e,t,n,r,o){let s=er(e,r,o);return s.set("cursor",t),s.set("dir",n),`?${s.toString()}`}function Ba(e,t,n,r){let o=er(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 qa(e,t,n){return `?${er(t,n,e).toString()}`}function tr(e,t,n,r,o,s,a=[],c=[],i=false,u=[],f,y,w,b,g,T,R,O=false){let A=`${r}/${e}`,h=`${A}/create`,m={};if(R)for(let S of n)m[S]=Ct(At(R,S));let p=(T??[]).filter(S=>true),d=p.length>0,l=i,x=l||d,v=p.map(S=>{let C=At(R,S),$=Ct(C),H=a.find(_=>_.name===S);return {name:S,type:$,enumValues:H?.enumValues??null,nullable:H?.nullable??false}}),P=[];return R&&(P=pe(R).filter(C=>p.includes(C.name))),De(jsxs($e,{opts:{title:e,breadcrumb:[{label:"Repositories",href:r},{label:e}],basePath:r,flash:s},children:[a.length>0&&jsx(Yn,{action:A,columnMeta:a,activeFilters:c,isGroup:b}),w&&jsxs("div",{role:"alert",class:`alert ${w.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:w.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:w.type==="index"?"Composite index required":"Query failed"}),jsx("div",{class:"text-sm",children:w.message})]}),w.indexUrl&&jsx("a",{href:w.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 g=="number"&&jsxs(Fragment,{children:[" ","of"," ",jsx("span",{class:"font-semibold text-base-content/80",children:g})]})," ","document",(typeof g=="number"?g: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(S=>jsx("a",{href:qa(S,c,f),class:`join-item btn btn-xs ${y===S?"btn-active btn-primary":"btn-outline"}`,children:S},S))})]})]}),jsxs("div",{class:"flex gap-2",children:[jsx("form",{method:"post",action:`${A}/_bulk/backfill`,onsubmit:"return confirm('Backfill entire repository? This will scan all documents and fill missing system keys.')",children:jsx("button",{type:"submit",class:"btn btn-outline btn-sm",children:"Backfill"})}),jsx("a",{href:h,class:"btn btn-primary btn-sm",children:"+ New"})]})]}),x&&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 g=="number"?String(g):"","data-frs-page-size":String(y??t.length),"data-frs-allow-delete":l?"1":"0","data-frs-allow-update":d?"1":"0","data-frs-fields":JSON.stringify(v),"data-frs-filters":JSON.stringify(c),children:[jsxs("div",{class:"flex-1 text-sm",children:[jsx("span",{"data-frs-bulk-summary":true,children:"0 selected"}),typeof g=="number"&&g>t.length&&jsxs("button",{type:"button",class:"ml-3 link text-sm hidden","data-frs-bulk-select-all":true,children:["Select all ",g," matching documents"]}),jsxs("span",{class:"hidden ml-3 italic","data-frs-bulk-all-active":true,children:["All ",g??"?"," 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:[d&&jsx("button",{type:"button",class:"btn btn-sm btn-outline","data-frs-bulk-action":"update",children:"Update field\u2026"}),l&&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:[x&&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((S,C)=>{let $=f?.field===S,H=$?f.dir==="asc"?" \u25B2":" \u25BC":"";return jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:jsxs("a",{href:Ba(S,f,c,y),class:`hover:text-base-content inline-flex items-center gap-0.5${$?" text-primary font-bold":""}`,children:[S,H]})},C)}),u.map((S,C)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:S.column},`rel-${C}`)),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+(x?1:0),class:"text-center py-16 text-base-content/40",children:"No documents found"})}):t.map((S,C)=>{let $=String(S.docId??S.id??""),H=`${r}/${e}/${encodeURIComponent($)}/edit`,_=`${r}/${e}/${encodeURIComponent($)}/delete`;return jsxs("tr",{class:"hover","data-frs-row-id":$,children:[x&&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((E,k)=>{let D=S[E],I=m[E],M=I?Et(I,D):null;return jsx("td",{class:"align-top py-2",children:jsx(et,{val:D,mismatch:M})},k)}),u.map((E,k)=>{let D=S[E.key];if(D==null||D==="")return jsx("td",{class:"py-2"},`rel-${k}`);let I=E.type==="one"?`${r}/${E.targetRepo}/${encodeURIComponent(String(D))}/edit`:`${r}/${E.targetRepo}?fv_${E.targetKey}=${encodeURIComponent(String(D))}`;return jsx("td",{class:"align-middle py-2",children:jsx("a",{href:I,class:"btn btn-xs btn-ghost btn-outline","data-frs-relation":true,"data-frs-rel-type":E.type,"data-frs-rel-repo":E.targetRepo,"data-frs-rel-fk":E.targetKey,"data-frs-rel-val":String(D),"data-frs-rel-label":E.column,children:E.column})},`rel-${k}`)}),jsx("td",{class:"align-middle text-right whitespace-nowrap py-2",children:jsxs("div",{class:"flex gap-1 justify-end",children:[jsx("a",{href:H,class:"btn btn-xs btn-outline",children:"Edit"}),O&&jsx("a",{href:`${r}/${e}/${encodeURIComponent($)}/history`,class:"btn btn-xs btn-outline",title:"View change history",children:"History"}),i&&jsx("form",{method:"post",action:_,onsubmit:"return confirm('Delete this document?')",children:jsx("button",{type:"submit",class:"btn btn-xs btn-error btn-outline",children:"Delete"})})]})})]},C)})})]})}),(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:So(c,o.prevCursor,"prev",f,y),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:So(c,o.nextCursor,"next",f,y),class:"btn btn-sm btn-outline",children:"Next \u2192"}):jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"Next \u2192"})]}),typeof g=="number"&&jsxs("div",{class:"text-xs text-base-content/50",children:[g," total document",g!==1?"s":"",c.length>0?" matching filters":""]})]}),x&&d&&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"}),p.map(S=>jsx("option",{value:S,children:S},S))]})]}),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:P.map(S=>jsx("div",{"data-frs-bulk-template-for":S.name,dangerouslySetInnerHTML:{__html:Tt(S)}},S.name))})]}))}function Pt(e,t){return Qn(e,t)}function nr(e,t){return Jn(e,t)}function rr(e,t,n,r,o,s,a,c,i,u,f,y,w,b,g,T,R,O){return tr(e,t,n,r,o,s,a,c,i,u,f,y,w,b,g,T,R,O)}function _e(e,t,n,r,o,s){return Xn(e,t,n,r,o,s)}async function ko(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 tt(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 or(e,t,n){let r=e.documentKey??"docId",o=St(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 U(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function an(e,t){e.status(302).set("Location",t).send("");}function cn(e,t){let n=t.shape,r={};for(let[o,s]of Object.entries(n)){let a=ar(s),c=V(a),i=c==="ZodObject",u=a,f=false;if(c==="ZodUnion"){let b=vt(a);b.some(T=>V(T)==="ZodDate")&&(f=true);let g=b.find(T=>{if(V(T)==="ZodObject"){let R=ae(T);return "latitude"in R&&"longitude"in R}return false});g&&(i=true,u=g);}if(e[o+"__isnull"]==="1"){r[o]=null;continue}if(i){let b={},g=false;for(let[O,A]of Object.entries(e))O.startsWith(`${o}.`)&&(b[O.slice(o.length+1)]=A,g=true);if(g){r[o]=cn(b,u);continue}let T=e[o],R=Array.isArray(T)?T[T.length-1]:T;if(R)try{r[o]=JSON.parse(R);}catch{r[o]=R;}continue}let y=e[o],w=Array.isArray(y)?y[y.length-1]:y;if(w===void 0||w===""){c==="ZodBoolean"&&(r[o]=false);continue}if(f){r[o]=new Date(w);continue}switch(c){case "ZodBoolean":w==="__null__"?r[o]=null:r[o]=w==="true"||w==="on"||w==="1";break;case "ZodNumber":case "ZodBigInt":r[o]=Number(w);break;case "ZodDate":r[o]=new Date(w);break;case "ZodArray":try{r[o]=JSON.parse(w);}catch{r[o]=w;}break;default:if(w.startsWith("{")||w.startsWith("["))try{r[o]=JSON.parse(w);break}catch{}r[o]=w;}}return r}function Co(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 Eo(e){let t=e;for(;;){let n=V(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=se(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=gt(t);if(!r)return n;t=r;}else return n}}function ar(e){let t=e;for(;;){let n=V(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=se(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=gt(t);if(!r)return t;t=r;}else return t}}function Oo(e){let t=e;for(;;){let n=V(t);if(n==="ZodOptional"||n==="ZodNullable")return true;if(n==="ZodDefault"){t=se(t);continue}return false}}function Po(e){let t=ar(e),n=V(t);if(n==="ZodEnum"){let r=bt(t);return r.length>0?r:void 0}if(n==="ZodNativeEnum"){let r=wt(t),o=Object.values(r).filter(s=>typeof s=="string");return o.length>0?o:void 0}if(n==="ZodLiteral"){let r=xt(t);return typeof r=="string"?[r]:void 0}}function Io(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 c=ar(t.shape[o]),i=V(c),u=i==="ZodObject",f=c,y=false;if(i==="ZodUnion"){let w=vt(c);w.some(g=>V(g)==="ZodDate")&&(y=true);let b=w.find(g=>{if(V(g)==="ZodObject"){let T=ae(g);return "latitude"in T&&"longitude"in T}return false});b&&(u=true,f=b);}if(u&&typeof a=="object"&&a!==null&&!Array.isArray(a)&&!("_seconds"in a)&&typeof a.toDate!="function"){let w=Io(a,f,s);Object.assign(r,w);}else if(i==="ZodDate"||y){let w=Co(a);w!==null&&(r[s]=w);}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)&&("_seconds"in a||typeof a.toDate=="function")){let w=Co(a);r[s]=w??JSON.stringify(a,null,2);}else typeof a=="object"?r[s]=JSON.stringify(a,null,2):r[s]=String(a);}return r}function sr(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?sr(n.nested,t):void 0}))}function Ua(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 c=(s??"").trim();if(!c)continue;let i=e[`fo_${a}`]??"==",u=n.has(i)?i:"==";r.push({field:a,op:u,value:c});}return r}function Ao(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 Do(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 c=Eo(a);if(c==="ZodObject"){let i=a;for(;;){let f=V(i);if(f==="ZodOptional"||f==="ZodNullable"||f==="ZodDefault")i=se(i);else break}let u=ae(i);r.push(...Do(Object.keys(u),i,s));}else r.push({name:s,zodType:c,nullable:Oo(a),enumValues:Po(a)});}return r}function La(e,t){let n=t.split("."),r=e;for(let o of n){for(;;){let a=V(r);if(a==="ZodOptional"||a==="ZodNullable"||a==="ZodDefault")r=se(r);else break}let s=ae(r);if(!(o in s))return null;r=s[o];}return r}function Be(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 c=s.slice(0,a),i=s.slice(a+1);r.has(c)||r.set(c,[]),r.get(c).push(i);}}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 c=e.shape[s];for(;;){let i=V(c);if(i==="ZodOptional"||i==="ZodNullable"||i==="ZodDefault")c=se(c);else break}if(V(c)!=="ZodObject"){o[s]=e.shape[s];continue}o[s]=Be(c,a);}return z.object(o)}function we(e,t,n){return be(e,t,n)}function $o(e,t,n){let r=(h,m)=>{let p=we(h,t,n),d=Object.values(e).map(l=>({name:l.name,path:l.path}));U(m,nr(d,p));},o=async(h,m)=>{let p=h.params.repoName;if(!p){U(m,"Bad request",400);return}let d=e[p];if(!d){U(m,"Repository not found",404);return}let l=d.pageSize??25,x=h.query??{},v=x.cursor,P=x.dir==="prev"?"prev":"next",S=x.ob??"",C=x.od==="desc"?"desc":"asc",$=S?{field:S,dir:C}:void 0,H=parseInt(x.ps??""),_=Number.isFinite(H)&&H>0?Math.min(H,200):l,E=d.listColumns??Object.keys(d.schema.shape),k=d.documentKey??"docId",D=[k,...E.filter(de=>de!==k)];$&&(new Set([k,...E]).has($.field)||($=void 0));let I=d.filterableFields?(()=>{let de=[];for(let Re of d.filterableFields)(Re.includes(".")||E.includes(Re))&&de.push(Re);return de})():E,M=(()=>{let de=[];for(let Re of I)if(Re.includes(".")){let We=La(d.schema,Re);de.push({name:Re,zodType:We?Eo(We):"ZodString",nullable:We?Oo(We):false,enumValues:We?Po(We):void 0});}else de.push(...Do([Re],d.schema));return de})(),F=new Set(M.map(de=>de.name)),j=Ua(x,F),z=Ao(j),q;v&&(q=await ko(d,v));let[Z,Y]=await Promise.all([d.repo.query.paginate({pageSize:_,cursor:q,direction:P,...z.length>0?{where:z}:{},...$?{orderBy:[{field:$.field,direction:$.dir}]}:{}}).catch(de=>({queryError:St(de,{ref:d.repo.ref,path:d.path,isGroup:!!d.isGroup,filters:j,sort:$})})),d.repo.aggregate.count(z.length>0?{where:z}:{}).catch(()=>{})]),ve="queryError"in Z,wn=ve?[]:Z.data,te=ve?"":Z.nextCursor?.ref?.path??Z.nextCursor?.id??"",ge=ve?"":Z.prevCursor?.ref?.path??Z.prevCursor?.id??"",ds=ve?Z.queryError:void 0,us=we(h,t,n),st,Ft=x.flash;Ft==="created"?st={type:"success",message:"Document created successfully."}:Ft==="updated"?st={type:"success",message:"Document updated successfully."}:Ft==="deleted"?st={type:"success",message:"Document deleted successfully."}:Ft==="backfilled"&&(st={type:"success",message:"Repository backfilled successfully."}),U(m,rr(d.name,wn,D,us,{hasPrev:ve?false:Z.hasPrevPage,hasNext:ve?false:Z.hasNextPage,prevCursor:ge,nextCursor:te},st,M,j,d.allowDelete??false,d.relationalMeta,$,_,ds,d.isGroup,Y,d.mutableFields,d.schema,d.historyEnabled));},s=(h,m)=>{let p=h.params.repoName;if(!p){U(m,"Bad request",400);return}let d=e[p];if(!d){U(m,"Repository not found",404);return}let l=we(h,t,n),x=Be(d.schema,d.createFields),v=pe(x),P=`${l}/${d.name}/create`,S=Ie(v,P,"POST","Create document");U(m,_e(d.name,S,"create",null,l));},a=async(h,m)=>{let p=h.params.repoName;if(!p){U(m,"Bad request",400);return}let d=e[p];if(!d){U(m,"Repository not found",404);return}let l=we(h,t,n),x=h.body??{},v=cn(x,d.schema),P=Be(d.schema,d.createFields),S=P.safeParse(v);if(!S.success){let C=pe(P),$=`${l}/${d.name}/create`,H=Ie(C,$,"POST","Create document"),_=S.error.issues.map(E=>`${E.path.join(".")}: ${E.message}`).join(", ");U(m,_e(d.name,H,"create",null,l,{type:"error",message:`Validation error: ${_}`}),422);return}try{if(d.isGroup&&d.parentKeys&&d.parentKeys.length>0){let C={...S.data},$=d.parentKeys.filter(H=>C[H]===void 0||C[H]===null||typeof C[H]=="string"&&C[H].trim()==="");if($.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${$.join(", ")}`);if(typeof d.repo.create=="function")await d.repo.create(C);else {let H=d.parentKeys.map(k=>String(C[k])),_=d.documentKey??"docId",E=C[_]||Ee();await d.repo.set(...H,E,C);}}else await d.repo.create(S.data);an(m,`${l}/${d.name}?flash=created`);}catch(C){let $=Be(d.schema,d.createFields),H=pe($),_=`${l}/${d.name}/create`,E=Ie(H,_,"POST","Create document");U(m,_e(d.name,E,"create",null,l,{type:"error",message:`Save error: ${C.message}`}),500);}},c=async(h,m)=>{let p=h.params.repoName,d=h.params.id;if(!p||!d){U(m,"Bad request",400);return}let l=e[p];if(!l){U(m,"Repository not found",404);return}let x=we(h,t,n),v=null;try{v=await tt(l,d);}catch(_){let E=or(l,d,_),k=Ne(_)?424:500;U(m,Pt("",{title:`Edit ${l.name} / ${d}`,basePath:x,breadcrumb:[{label:"Repositories",href:x},{label:l.name,href:`${x}/${l.name}`},{label:`Edit ${d}`}],flash:E}),k);return}if(!v){U(m,"Document not found",404);return}let P=Io(v,l.schema),S=Be(l.schema,l.mutableFields),C=sr(pe(S),P),$=`${x}/${l.name}/${encodeURIComponent(d)}/edit`,H=Ie(C,$,"POST","Save changes");U(m,_e(l.name,H,"edit",d,x));},i=async(h,m)=>{let p=h.params.repoName,d=h.params.id;if(!p||!d){U(m,"Bad request",400);return}let l=e[p];if(!l){U(m,"Repository not found",404);return}let x=we(h,t,n),v=h.body??{},P=cn(v,l.schema),S=Be(l.schema,l.mutableFields),$=S.partial().safeParse(P);if(!$.success){let H=Object.fromEntries(Object.entries(v).map(([I,M])=>[I,Array.isArray(M)?M.join(","):M??""])),_=sr(pe(S),H),E=`${x}/${l.name}/${encodeURIComponent(d)}/edit`,k=Ie(_,E,"POST","Save changes"),D=$.error.issues.map(I=>`${I.path.join(".")}: ${I.message}`).join(", ");U(m,_e(l.name,k,"edit",d,x,{type:"error",message:`Validation error: ${D}`}),422);return}try{let H=await tt(l,d),_=(H&&sn(H,l))??[d];await l.repo.update(..._,$.data),an(m,`${x}/${l.name}?flash=updated`);}catch(H){let _=Be(l.schema,l.mutableFields),E=pe(_),k=`${x}/${l.name}/${encodeURIComponent(d)}/edit`,D=Ie(E,k,"POST","Save changes"),I=Ne(H)?or(l,d,H):{type:"error",message:`Save error: ${H.message}`},M=Ne(H)?424:500;U(m,_e(l.name,D,"edit",d,x,I),M);}},u=async(h,m)=>{let p=h.params.repoName,d=h.params.id;if(!p||!d){U(m,"Bad request",400);return}let l=e[p];if(!l){U(m,"Repository not found",404);return}if(!l.allowDelete){U(m,"Delete is not allowed for this repository",403);return}let x=we(h,t,n);try{let v=await tt(l,d),P=(v&&sn(v,l))??[d];await l.repo.delete(...P),an(m,`${x}/${l.name}?flash=deleted`);}catch(v){let P=Ne(v)?or(l,d,v):{type:"error",message:`Delete error: ${v.message}`},S=Ne(v)?424:500;U(m,Pt("",{title:`Delete ${l.name} / ${d}`,basePath:x,breadcrumb:[{label:"Repositories",href:x},{label:l.name,href:`${x}/${l.name}`},{label:`Delete ${d}`}],flash:P}),S);}},f=async(h,m)=>{let p=h.params.repoName;if(!p){U(m,"Bad request",400);return}let d=e[p];if(!d){U(m,"Repository not found",404);return}let l=we(h,t,n),x=h.query,v=x?.type==="many"?"many":"one",P=Math.max(1,Math.min(100,Number(x?.ps??25)||25)),S=d.listColumns??Object.keys(ae(d.schema)),{PanelOne:C,PanelMany:$}=await Promise.resolve().then(()=>(Gn(),vo)),{renderToString:H}=await import('hono/jsx/dom/server');if(v==="one"){let M=String(x?.id??"");if(!M){U(m,"<div class='p-6 text-error'>Missing id parameter.</div>",400);return}try{let F=await tt(d,M),j=H(C({doc:F,repoName:d.name,basePath:l,schema:d.schema,columns:S}));U(m,j);}catch(F){U(m,`<div class='p-6 text-error text-sm'>Error: ${F.message}</div>`,500);}return}let _=String(x?.fk??""),E=String(x?.fv??"");if(!_||!E){U(m,"<div class='p-6 text-error'>Missing fk/fv parameters.</div>",400);return}let k=x?.cursor??"",D=x?.dir==="prev"?"prev":"next",I;k&&(I=await ko(d,k));try{let M=await d.repo.query.paginate({pageSize:P,cursor:I,direction:D,where:[[_,"==",Wa(E)]]}),F=H($({docs:M.data,repoName:d.name,basePath:l,fk:_,fv:E,columns:S,schema:d.schema,pagination:{hasPrev:M.hasPrevPage,hasNext:M.hasNextPage,prevCursor:M.prevCursor?.ref?.path??M.prevCursor?.id??"",nextCursor:M.nextCursor?.ref?.path??M.nextCursor?.id??"",pageSize:P}}));U(m,F);}catch(M){U(m,`<div class='p-6 text-error text-sm'>Error: ${M.message}</div>`,500);}},y=async(h,m)=>{let p=h.params.repoName;if(!p){U(m,"Bad request",400);return}let d=e[p];if(!d){U(m,"Repository not found",404);return}let l=we(h,t,n);try{await d.repo.system.backfillKeys(),an(m,`${l}/${d.name}?flash=backfilled`);}catch(x){U(m,`<div class="p-6 text-error">Backfill failed: ${x.message}</div>`,500);}},w=async(h,m)=>{let p=[];for(let d of m){let l;if(h.isGroup||h.parentKeys?.length){let x=await tt(h,d);l=x?sn(x,h):void 0;}l||(l=[d]);try{let x=h.repo.documentRef(...l);x&&p.push(x);}catch{}}return p},b=async(h,m)=>{let p=Ao(m),d=h.documentKey??"docId",l=[],x;for(;;){let v=await h.repo.query.paginate({pageSize:500,cursor:x,direction:"next",...p.length>0?{where:p}:{}});for(let P of v.data){let S=String(P[d]??P.id??"");S&&l.push(S);}if(!v.hasNextPage||!v.nextCursor)break;x=v.nextCursor;}return l},g=async(h,m)=>{let p=h.params.repoName;if(!p){ce(m,{error:"Bad request"},400);return}let d=e[p];if(!d){ce(m,{error:"Repository not found"},404);return}if(!d.allowDelete){ce(m,{error:"Delete is not allowed for this repository"},403);return}let l=h.body??{};try{let x=await R(d,l);if(x.length===0){ce(m,{deleted:0});return}let v=await w(d,x);for(let P=0;P<v.length;P+=500)await d.repo.bulk.delete(v.slice(P,P+500));ce(m,{deleted:v.length});}catch(x){ce(m,{error:x.message},500);}},T=async(h,m)=>{let p=h.params.repoName;if(!p){ce(m,{error:"Bad request"},400);return}let d=e[p];if(!d){ce(m,{error:"Repository not found"},404);return}let l=h.body??{},x=String(l.field??"");if(!x){ce(m,{error:"Missing 'field'"},400);return}if(!d.mutableFields||!d.mutableFields.includes(x)){ce(m,{error:`Field '${x}' is not bulk-updatable`},403);return}let v=d.schema.shape?.[x],P;if(v){let S=typeof d.schema=="object"&&d.schema&&"constructor"in d.schema&&d.schema.constructor.name.includes("Zod")?d.schema.pick({[x]:true}):void 0;if(!S){ce(m,{error:"Invalid schema structure"},500);return}P=cn(l.formPayload??{},S)[x];let $=v.safeParse(P);if(!$.success){ce(m,{error:`Invalid value for '${x}': ${$.error.message}`},400);return}P=$.data;}try{let S=await R(d,l);if(S.length===0){ce(m,{updated:0});return}let $=(await w(d,S)).map(H=>({docRef:H,data:{[x]:P}}));for(let H=0;H<$.length;H+=500)await d.repo.bulk.update($.slice(H,H+500));ce(m,{updated:$.length});}catch(S){ce(m,{error:S.message},500);}};async function R(h,m){if(m.selectAll){let p=O(m.filters,h);return await b(h,p)}return Array.isArray(m.ids)?m.ids.filter(p=>typeof p=="string"&&!!p):[]}function O(h,m){if(!Array.isArray(h))return [];let p=new Set((m.filterableFields??Object.keys(ae(m.schema))).map(x=>String(x))),d=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),l=[];for(let x of h)x&&typeof x=="object"&&typeof x.field=="string"&&p.has(x.field)&&typeof x.value=="string"&&d.has(String(x.op))&&l.push({field:x.field,op:x.op,value:x.value});return l}return {handleDashboard:r,handleList:o,handleCreateForm:s,handleCreateSubmit:a,handleEditForm:c,handleEditSubmit:i,handleDelete:u,handlePanel:f,handleBulkDelete:g,handleBulkUpdate:T,handleBulkBackfill:y,handleHistory:async(h,m)=>{let p=h.params.repoName,d=h.params.id;if(!p||!d){U(m,"Bad request",400);return}let l=e[p];if(!l){U(m,"Repository not found",404);return}if(!l.historyEnabled||!l.repo.history){U(m,"History not enabled for this repository",404);return}let x=we(h,t,n),v=l.historySubcollection??"history",P=[d];try{let M=await tt(l,d),F=M?sn(M,l):void 0;F&&F.length>0&&(P=F);}catch{}let S=parseInt(String(h.query?.limit??"")),C=Number.isFinite(S)&&S>0?Math.min(S,500):100,$=[],H;try{$=await l.repo.history.list(...P,{limit:C});}catch(M){H=M.message;}let _=M=>String(M??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),E=M=>{if(M===void 0)return '<span class="opacity-40">undefined</span>';if(M===null)return '<span class="opacity-40">null</span>';if(typeof M=="object")try{return `<code class="text-xs">${_(JSON.stringify(M))}</code>`}catch{return _(String(M))}return _(String(M))},k=M=>M?typeof M.toDate=="function"?M.toDate().toISOString():M instanceof Date?M.toISOString():_(String(M)):"",D=M=>`<span class="badge badge-sm ${M==="create"?"badge-success":M==="delete"?"badge-error":M==="custom"?"badge-secondary":"badge-info"}">${_(M)}</span>`,I="";if(I+='<div class="flex items-center justify-between mb-4">',I+=`<a href="${x}/${l.name}/${encodeURIComponent(d)}/edit" class="btn btn-sm btn-outline">\u2190 Back to edit</a>`,I+=`<a href="${x}/${l.name}" class="btn btn-sm btn-outline">\u2190 Back to list</a>`,I+="</div>",I+=`<p class="text-sm text-base-content/60 mb-4">Subcollection: <code>${_(v)}</code> \xB7 Showing up to ${C} entries.</p>`,H)I+=`<div class="alert alert-error mb-4">${_(H)}</div>`;else if($.length===0)I+='<div class="alert">No history entries found.</div>';else {I+='<div class="overflow-x-auto"><table class="table table-zebra table-sm">',I+="<thead><tr><th>When</th><th>Op</th><th>User</th><th>Reason / Comment</th><th>Changes</th></tr></thead><tbody>";for(let M of $){let F=M.meta??{},j=[F.reason,F.comment].filter(Z=>Z!=null&&Z!=="").map(Z=>_(String(Z))).join(" \u2014 "),z="",q=Object.keys(M.changes??{});if(M.custom){let Z=`<strong>${_(M.custom.title)}</strong>`,Y=M.custom.key?` <code class="text-xs opacity-60">${_(M.custom.key)}</code>`:"",ve=M.custom.description?`<div class="text-xs opacity-80 mt-0.5">${_(M.custom.description)}</div>`:"";z=`<div>${Z}${Y}${ve}</div>`;}else q.length===0?z='<span class="opacity-40">\u2014</span>':z='<ul class="space-y-1">'+q.map(Z=>{let Y=M.changes[Z];return `<li><strong>${_(Z)}</strong>: ${E(Y.oldValue)} \u2192 ${E(Y.newValue)}</li>`}).join("")+"</ul>";I+="<tr>",I+=`<td class="whitespace-nowrap text-xs font-mono">${_(k(M.historySetAt))}</td>`,I+=`<td>${D(M.operation??"update")}</td>`,I+=`<td class="text-xs">${_(F.userEmail??F.userId??"")}</td>`,I+=`<td class="text-xs">${j}</td>`,I+=`<td>${z}</td>`,I+="</tr>";}I+="</tbody></table></div>";}U(m,Pt(I,{title:`History \u2014 ${l.name} / ${d}`,basePath:x,breadcrumb:[{label:"Repositories",href:x},{label:l.name,href:`${x}/${l.name}`},{label:`History ${d}`}]}));}}}function ce(e,t,n=200){e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(t));}function Wa(e){return e==="true"?true:e==="false"?false:e!==""&&!isNaN(Number(e))?Number(e):e}dn();async function Va(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function Ga(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 Fo(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,auth:s,middleware:a=[],httpsOptions:c}=e,i=t==="/"?"":t.replace(/\/$/,""),u={};for(let[b,g]of Object.entries(n)){if(!g.repo)throw new Error(`[createAdminServer] Repository "${b}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let T=g.schema??g.repo.schema??null;if(!T)throw new Error(`[createAdminServer] Repository "${b}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let R,O,A;if(g.fieldsConfig){let p=g.fieldsConfig;R=[],O=[],A=[];for(let[d,l]of Object.entries(p))for(let x of l)x==="filterable"?R.push(d):x==="mutable"?O.push(d):x==="create"&&A.push(d);R.length===0&&(R=void 0),O.length===0&&(O=void 0),A.length===0&&(A=void 0);}let h=(()=>{let p=g.repo._parentKeys;return p&&p.length>0?p:void 0})();if(h&&A)for(let p of h)A.includes(p)||A.push(p);let m={name:b,path:g.path,repo:g.repo,schema:T,documentKey:g.documentKey??"docId",pathKey:g.repo._pathKey??void 0,isGroup:!!g.repo._isGroup,parentKeys:h,documentPathTemplate:g.repo._documentPathTemplate??void 0,createdKey:g.repo._createdKey??void 0,listColumns:g.listColumns,pageSize:g.pageSize,filterableFields:R,mutableFields:O,createFields:A,allowDelete:g.allowDelete??false,historyEnabled:!!g.repo._historyConfig?.enabled,historySubcollection:(g.repo._historyConfig?.enabled&&g.repo._historySubcollection)??void 0,relationalMeta:(()=>{if(!g.relationalFields||g.relationalFields.length===0)return;let p=g.repo.relationalKeys??{},d=[];for(let l of g.relationalFields){let x=p[l.key];x&&d.push({key:x.sourceKey?String(x.sourceKey):l.key,column:l.column,targetRepo:String(x.repo),targetKey:String(x.key),type:x.type});}return d.length>0?d:void 0})()};u[b]=m;}let f=$o(u,i,Vt(c?.region)),y=new ke;if(o!==false&&y.use(ln(o===void 0?{}:o)),r&&y.use(async(b,g,T)=>{let R=b,O=String(R.headers?.["content-type"]??"");if(O.includes("application/x-www-form-urlencoded")){let A=await Va(R);b.body=Ga(A);}else if(O.includes("application/json")&&typeof R.body=="string")try{b.body=JSON.parse(R.body);}catch{}await T();}),s)if(mt(s)){for(let b of s.routes){let g=`${i}${b.path}`;b.method==="GET"?y.get(g,b.handler):y.post(g,b.handler);}y.use(s.middleware);}else if(typeof s=="function")y.use(s);else {let b=s.realm??"Admin",g="Basic "+Buffer.from(`${s.username}:${s.password}`).toString("base64");y.use((T,R,O)=>{if((T.headers?.authorization??"")!==g){R.status(401).set("WWW-Authenticate",`Basic realm="${b}"`).set("Content-Type","text/plain").send("Unauthorized");return}O();});}for(let b of a)y.use(b);y.get(`${i}/`,f.handleDashboard),y.get(`${i}`,f.handleDashboard),y.get(`${i}/:repoName/_panel`,f.handlePanel),y.post(`${i}/:repoName/_bulk/delete`,f.handleBulkDelete),y.post(`${i}/:repoName/_bulk/update`,f.handleBulkUpdate),y.post(`${i}/:repoName/_bulk/backfill`,f.handleBulkBackfill),y.get(`${i}/:repoName`,f.handleList),y.get(`${i}/:repoName/create`,f.handleCreateForm),y.post(`${i}/:repoName/create`,f.handleCreateSubmit),y.get(`${i}/:repoName/:id/edit`,f.handleEditForm),y.post(`${i}/:repoName/:id/edit`,f.handleEditSubmit),y.get(`${i}/:repoName/:id/history`,f.handleHistory),y.post(`${i}/:repoName/:id/delete`,f.handleDelete);let w=async(b,g)=>{await y.handle(b,g);};return c&&(w.httpsOptions=c),w}Je();function ye(e,t){let n=e||{},r={},o={...n};for(let[s,a]of Object.entries(t||{})){let c=n[s];pt(c,a)||(r[s]=a,o[s]=a);}return {before:n,after:o,changes:r}}function cr(e){return e}async function un(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 lr(e){return async t=>un(t.diff,e,t.user)}var dr=1e3;function jo(e,t){if(e===void 0)return {success:true,value:Math.min(Math.max(1,t),dr)};let n=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN;return !Number.isInteger(n)||n<=0||n>dr?{success:false,error:`Invalid pageSize: must be an integer between 1 and ${dr}`}:{success:true,value:n}}function fr(e,t,n=200){let r=X(t);return e.json(r,n)}function qe(e,t,n,r=200){return fr(e,{success:true,data:t,meta:n},r)}function B(e,t,n=400){return fr(e,{success:false,error:t},n)}async function ur(e,t,n,r,o,s){let a=St(t,n),c=a.type==="index",i=c?424:500,f={success:false,error:c?a.message:o&&t instanceof Error?t.message:r};if(c&&(f.errorType="index",a.indexUrl&&(f.indexUrl=a.indexUrl,s)))try{let y=s({indexUrl:a.indexUrl,repoName:n.repoName??"",path:n.path,isGroup:n.isGroup,filters:n.filters,sort:n.sort,error:t,c:e});y instanceof Promise&&await y;}catch(y){o&&console.error("[crudServer] Error in indexesError callback:",y);}return fr(e,f,i)}function Ke(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=>Tn(r)??r,e);if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[s,a]of Object.entries(r))o[s]=Ke(a);return z.object(o)}if(n==="ZodArray"||n==="array"){let r=t.element??t.type;if(r)return z.array(Ke(r))}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(r)return Ke(r).optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(r)return Ke(r).nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType,o=t.defaultValue;if(r){let s=Ke(r);return typeof o=="function"?s.default(o()):s.default(o)}}return e}function Qa(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 c=a.split(".")[0];c&&r[c]&&(o[c]=r[c]);}return z.object(o)}function pr(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 Bo(e,t){let n=t.split("."),r=pr(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 c=a[s];if(o===n.length-1)return c;r=pr(c);}return r}function Ze(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]=Ze(a);return z.object(o).partial()}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(!r)return e;let o=Ze(r);return o===r?e:o.optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(!r)return e;let o=Ze(r);return o===r?e:o.nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType;return r?Ze(r).optional():e}if(n==="ZodUnion"||n==="union"){let r=t.options;if(!r||r.length<2)return e;let o=r.map(a=>Ze(a));return o.some((a,c)=>a!==r[c])?z.union(o):e}return e}function pn(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={},c={};for(let[i,u]of Object.entries(s))if(i.includes(".")){let f=i.split(".")[0];if(o.includes(i)||o.includes(f))continue;if(n&&n.length>0&&!n.includes(i)&&!n.includes(f))return {success:!1,error:`Field '${i}' is not allowed for this operation`};let y=Bo(e,i);if(!y)return {success:!1,error:`Field '${i}' does not exist in schema`};let w=r?Ze(y):y,g=(zt()==="normalize"?Ke(w):w).parse(u);a[i]=g;}else c[i]=u;if(Object.keys(c).length>0||Object.keys(a).length===0){let i=Qa(e,n,o),u=r?Ze(i):i,y=(zt()==="normalize"?Ke(u):u).parse(c);Object.assign(a,y);}return {success:!0,data:a}}catch(s){return s instanceof z.ZodError?{success:false,error:`Validation failed: ${s.issues.map(c=>`${c.path.join(".")}: ${c.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}var qo={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 It(e){return qo[e]??e}function Ja(e){return e in qo}function fn(e,t,n,r){let o=Bo(e,t);if(!o||typeof o.safeParse!="function")return {success:true,data:n};let s=r?It(r):void 0,a=pr(o),c=Qt(a);if(s==="array-contains"){let f=c??o;if(typeof f.safeParse=="function"){let y=f.safeParse(n);return y.success?{success:true,data:y.data}:{success:false,error:y.error.issues.map(b=>b.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 f=c??o,y=[];for(let w of n)if(typeof f.safeParse=="function"){let b=f.safeParse(w);if(b.success)y.push(b.data);else return {success:false,error:b.error.issues.map(T=>T.message).join(", ")}}else y.push(w);return {success:true,data:y}}let i=o.safeParse(n);if(i.success)return {success:true,data:i.data};if(Array.isArray(n)){let f=c??o,y=[];for(let w of n)if(typeof f.safeParse=="function"){let b=f.safeParse(w);if(b.success)y.push(b.data);else return {success:false,error:b.error.issues.map(T=>T.message).join(", ")}}else y.push(w);return {success:true,data:y}}return {success:false,error:i.error.issues.map(f=>f.message).join(", ")}}function Ya(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 c=o.lastIndexOf("__"),i,u="==";if(c!==-1){let y=o.slice(0,c),w=o.slice(c+2);Ja(w)?(i=y,u=It(w)):(i=o,u="==");}else i=o;if(r&&!r.has(i))continue;let f=a;u==="in"||u==="not-in"||u==="array-contains-any"?f=a.split(",").map(y=>No(y.trim())):f=No(a),n.push({field:i,op:u,value:f});}return n}function No(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 yn(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function zo(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 c=await a.doc(r).get();if(c.exists)return c}if(o&&o.includes("/")&&a&&typeof a.doc=="function"){let c=await a.doc(o).get();if(c.exists)return c}if(o&&typeof s.doc=="function"){let c=await s.doc(o).get();if(c.exists)return c}return}catch{return}}function mn(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 Ko(e,t,n,r,o){async function s(m,p,d,l){let x=false;if(m.hooks?.onAfterError){x=true;try{let v=m.hooks.onAfterError(l,d.hook);v instanceof Promise&&await v;}catch(v){console.error("[crudServer] Error in hooks.onAfterError callback:",v);}}if(o){x=true;try{let v=o({...d,error:l});v instanceof Promise&&await v;}catch(v){console.error("[crudServer] Error in onHookError callback:",v);}}if(!x){if(p&&typeof p.error=="function"){p.error(l,{hook:d.hook,repoName:d.repoName,path:d.path,...d.id!==void 0?{id:d.id}:{},...d.pathArgs!==void 0?{pathArgs:d.pathArgs}:{}});return}console.error(`[crudServer] Hook "${d.hook}" failed on repo "${d.repoName}":`,{hook:d.hook,repoName:d.repoName,path:d.path,...d.id!==void 0?{id:d.id}:{},...d.pathArgs!==void 0?{pathArgs:d.pathArgs}:{},error:l});}}async function a(m,p,d,l){if(!p.rules)return {allowed:true};let x=p.rules?.[d];if(!x)return {allowed:false,errorResponse:B(m,`Operation "${d}" is not allowed for this repository`,403)};try{let v=await x(l);return v===!1?{allowed:!1,errorResponse:B(m,"Forbidden",403)}:typeof v=="string"?{allowed:!1,errorResponse:B(m,v,403)}:typeof v=="object"&&v!==null&&!v.allowed?{allowed:!1,errorResponse:B(m,v.reason||"Forbidden",403)}:{allowed:!0}}catch(v){let P=n&&v instanceof Error?v.message:"Forbidden";return {allowed:false,errorResponse:B(m,P,403)}}}async function c(m,p,d,l){if(!m.rules)return l;let x=m.rules?.filter;if(!x)return l;let v=[];for(let P of l)try{await x({user:p,doc:P,params:d})&&v.push(P);}catch{}return v}function i(m){return m.get("user")??m.get("docsUser")??null}function u(m,p){if(!m){let d=p.req.path.split("/");for(let l of d)if(e[l]){m=l;break}}return !m||!e[m]?null:e[m]??null}function f(m,p){return je(m,{pathKey:p.pathKey,documentKey:p.documentKey,parentKeys:p.parentKeys,documentPathTemplate:p.documentPathTemplate,isGroup:p.isGroup})}async function y(m,p){let d=`by${m.documentKey.charAt(0).toUpperCase()}${m.documentKey.slice(1)}`,l=m.repo.get[d];if(typeof l=="function")try{let v=await l(p);if(v)return v}catch{}return (await m.repo.query.by({where:[[m.documentKey,"==",p]],limit:1}))[0]??null}async function w(m){let p=m.c,d=p.req.param(),l=u(d.repoName,p);if(!l)return B(p,"Repository not found",404);let x=i(p),v=await a(p,l,"list",{user:x,query:p.req.query(),params:d});if(!v.allowed)return v.errorResponse;let P=[],S;try{let C=p.req.query(),$=jo(C.pageSize,l.pageSize);if(!$.success)return B(p,$.error,400);let H=$.value,_=C.cursor,E=C.direction?.toLowerCase()==="prev"?"prev":"next",k=C.orderBy,D=C.orderDir?.toLowerCase()==="desc"?"desc":"asc",I=C.select,M=I?I.split(",").map(te=>te.trim()):void 0,F=C.withTotal,j=F==="true"||F==="1"||F===!0,z;l.allowedIncludes&&C.includes&&(z=(typeof C.includes=="string"?C.includes.split(",").map(ge=>ge.trim()):Array.isArray(C.includes)?C.includes:[]).filter(ge=>typeof ge=="string"&&l.allowedIncludes.includes(ge)),z?.length===0&&(z=void 0));let q=Ya(C,l.filterableFields);P=q.map(te=>({field:te.field,op:te.op,value:String(te.value??"")})),k&&(S={field:k,dir:D});let Z={pageSize:H,direction:E,...j?{withTotal:!0}:{}};if(_)try{let te=typeof _=="string"?JSON.parse(_):_;Z.cursor=await zo(l,te);}catch{}if(k){if(l.orderableFields&&!l.orderableFields.includes(k))return B(p,`Field not orderable: ${k}`,400);Z.orderBy=[{field:k,direction:D}];}if(q.length>0){Z.where=[];for(let te of q){let ge=fn(l.schema,te.field,te.value,te.op);if(!ge.success)return B(p,`Invalid filter value for '${te.field}': ${ge.error}`,400);Z.where.push([te.field,te.op,ge.data]);}}M&&(Z.select=M),z&&(Z.include=z);let Y=await l.repo.query.paginate(Z),wn={items:await c(l,i(p),d,Y.data),hasNextPage:Y.hasNextPage,hasPrevPage:Y.hasPrevPage,nextCursor:yn(Y.nextCursor),prevCursor:yn(Y.prevCursor),...Y.totalCount!==void 0?{totalCount:Y.totalCount,totalCountIsExact:Y.totalCountIsExact}:{}};return qe(p,wn,{pageSize:H,hasMore:Y.hasNextPage,...Y.totalCount!==void 0?{totalCount:Y.totalCount,totalCountIsExact:Y.totalCountIsExact}:{}})}catch(C){return await ur(p,C,{repoName:d.repoName||l.name,ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:P,sort:S},"Failed to fetch documents",n,r)}}async function b(m){let p=m.c,d=p.req.param(),l=u(d.repoName,p);if(!l)return B(p,"Repository not found",404);let x=i(p),v=await a(p,l,"list",{user:x,query:m.input||{},params:d});if(!v.allowed)return v.errorResponse;let P=[],S;try{let C=m.input||{},$=jo(C.pageSize,l.pageSize);if(!$.success)return B(p,$.error,400);let H=$.value,_=C.direction==="prev"?"prev":"next";C.where&&(P=C.where.map(F=>({field:String(F[0]),op:F[1],value:String(F[2]??"")}))),C.orderBy&&C.orderBy[0]&&(S={field:C.orderBy[0].field,dir:C.orderBy[0].direction==="desc"?"desc":"asc"});let E=C.withTotal===!0||String(C.withTotal)==="true",k={pageSize:H,direction:_,...E?{withTotal:!0}:{}};if(C.cursor)try{let F=typeof C.cursor=="string"?JSON.parse(C.cursor):C.cursor;k.cursor=await zo(l,F);}catch{}if(l.allowedIncludes&&C.includes&&C.includes.length>0){let F=C.includes.filter(j=>typeof j=="string"?l.allowedIncludes.includes(j):typeof j=="object"&&j!==null&&"relation"in j&&typeof j.relation=="string"?l.allowedIncludes.includes(j.relation):!1);F.length>0&&(k.include=F);}if(C.where&&C.where.length>0){if(l.filterableFields){let j=new Set(l.filterableFields),z=C.where.filter(q=>!j.has(q[0]));if(z.length>0){B(p,`Fields not filterable: ${z.map(q=>q[0]).join(", ")}`,400);return}}let F=[];for(let j of C.where){let z=It(j[1]),q=fn(l.schema,j[0],j[2],z);if(!q.success){B(p,`Invalid filter value for '${j[0]}': ${q.error}`,400);return}F.push([j[0],z,q.data]);}k.where=F;}if(C.orWhere&&C.orWhere.length>0){if(l.filterableFields){let j=new Set(l.filterableFields),z=C.orWhere.filter(q=>!j.has(q[0]));if(z.length>0){B(p,`Fields not filterable: ${z.map(q=>q[0]).join(", ")}`,400);return}}let F=[];for(let j of C.orWhere){let z=It(j[1]),q=fn(l.schema,j[0],j[2],z);if(!q.success){B(p,`Invalid filter value for '${j[0]}': ${q.error}`,400);return}F.push([j[0],z,q.data]);}k.orWhere=F;}if(C.orWhereGroups&&C.orWhereGroups.length>0){if(l.filterableFields){let j=new Set(l.filterableFields);for(let z of C.orWhereGroups){let q=z.filter(Z=>!j.has(Z[0]));if(q.length>0){B(p,`Fields not filterable: ${q.map(Z=>Z[0]).join(", ")}`,400);return}}}let F=[];for(let j of C.orWhereGroups){let z=[];for(let q of j){let Z=It(q[1]),Y=fn(l.schema,q[0],q[2],Z);if(!Y.success){B(p,`Invalid filter value for '${q[0]}': ${Y.error}`,400);return}z.push([q[0],Z,Y.data]);}F.push(z);}k.orWhereGroups=F;}if(C.orderBy&&C.orderBy.length>0){if(l.orderableFields){let F=new Set(l.orderableFields),j=C.orderBy.filter(z=>!F.has(z.field));if(j.length>0){B(p,`Fields not orderable: ${j.map(z=>z.field).join(", ")}`,400);return}}k.orderBy=C.orderBy;}C.select&&C.select.length>0&&(k.select=C.select);let D=await l.repo.query.paginate(k),M={items:await c(l,i(p),d,D.data),hasNextPage:D.hasNextPage,hasPrevPage:D.hasPrevPage,nextCursor:yn(D.nextCursor),prevCursor:yn(D.prevCursor),...D.totalCount!==void 0?{totalCount:D.totalCount,totalCountIsExact:D.totalCountIsExact}:{}};return qe(p,M,{pageSize:H,hasMore:D.hasNextPage,...D.totalCount!==void 0?{totalCount:D.totalCount,totalCountIsExact:D.totalCountIsExact}:{}})}catch(C){return await ur(p,C,{repoName:d.repoName||l.name,ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:P,sort:S},"Failed to query documents",n,r)}}async function g(m){let p=m.c,d=p.req.param(),l=u(d.repoName,p);if(!l)return B(p,"Repository not found",404);let x=d.id;if(!x)return B(p,"Document ID required",400);try{let v=await y(l,x);if(!v)return B(p,"Document not found",404);let P=i(p),S=await a(p,l,"get",{user:P,doc:v,params:d});if(!S.allowed)return S.errorResponse;if(l.rules?.filter)try{if(!await l.rules.filter({user:P,doc:v,params:d}))return B(p,"Document not found",404)}catch{return B(p,"Document not found",404)}return qe(p,v)}catch(v){return await ur(p,v,{repoName:d.repoName||l.name,ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:[{field:l.documentKey,op:"==",value:x}]},"Failed to fetch document",n,r)}}async function T(m){let p=m.c,d=p.req.param(),l=u(d.repoName,p);if(!l)return B(p,"Repository not found",404);try{let x=m.input||{},v=i(p),P=await a(p,l,"create",{user:v,body:x,params:d});if(!P.allowed)return P.errorResponse;let S=pn(l.schema,x,l.createFields,!1,l.systemKeys);if(!S.success)return B(p,S.error,400);if(l.validate){let _=await l.validate(S.data,"create");if(_)return B(p,_,400)}l.hooks?.beforeCreate&&await l.hooks.beforeCreate({user:v,body:S.data,params:d,c:p});let C,$;if(l.isGroup&&l.parentKeys&&l.parentKeys.length>0){let _={...S.data},E=l.parentKeys.filter(k=>_[k]===void 0||_[k]===null||typeof _[k]=="string"&&_[k].trim()==="");if(E.length>0)return B(p,`Missing parent key(s) for subcollection create: ${E.join(", ")}`,400);if(typeof l.repo.create=="function")C=await l.repo.create(_);else {let k=l.parentKeys.map(I=>String(_[I])),D=_[l.documentKey]||Ee();$=[...k,D],C=await l.repo.set(...k,D,_);}}else C=await l.repo.create(S.data);let H=C;if(l.hooks?.afterCreate){let _=C?.[l.documentKey]??$?.[$.length-1]??"",E=String(_),k=$??f(C,l)??f({...S.data,...E?{[l.documentKey]:E}:{}},l)??(E?[E]:[]);try{let D=await l.hooks.afterCreate({user:v,doc:C,id:E,pathArgs:k,params:d,c:p}),I=mn(D);I&&k.length>0&&(H=await l.repo.update(...k,I));}catch(D){await s(l,m.logger,{hook:"afterCreate",repoName:l.name,path:l.path,id:E,pathArgs:k,user:v,c:p},D);}}return qe(p,H,void 0,201)}catch(x){let v=n&&x instanceof Error?x.message:"Failed to create document";return B(p,v,500)}}async function R(m,p){let d=m.c,l=d.req.param(),x=u(l.repoName,d);if(!x)return B(d,"Repository not found",404);let v=l.id;if(!v)return B(d,"Document ID required",400);try{let P=m.input||{},S=await y(x,v);if(!S)return B(d,"Document not found",404);let C=pn(x.schema,P,x.mutableFields,p,x.systemKeys);if(!C.success)return B(d,C.error,400);if(x.validate){let F=await x.validate(C.data,"update");if(F)return B(d,F,400)}let $=ye(S,C.data),H=i(d),_=await a(d,x,"update",{user:H,doc:S,body:C.data,diff:$,params:l});if(!_.allowed)return _.errorResponse;if(x.hooks?.beforeUpdate){let F=x.rules?.update?ye(S,C.data):$;await x.hooks.beforeUpdate({user:H,doc:S,body:C.data,diff:F,params:l,c:d});}let E={...C.data},k=x.hooks?.afterUpdate?ye(S,E):$,D=f(S,x)??[v],I=await x.repo.update(...D,C.data),M=I;if(x.hooks?.afterUpdate)try{let F=await x.hooks.afterUpdate({user:H,before:S,after:I,body:E,diff:k,id:v,pathArgs:D,params:l,c:d}),j=mn(F);j&&(M=await x.repo.update(...D,j));}catch(F){await s(x,m.logger,{hook:"afterUpdate",repoName:x.name,path:x.path,id:v,pathArgs:D,user:H,c:d},F);}return qe(d,M)}catch(P){let S=n&&P instanceof Error?P.message:"Failed to update document";return B(d,S,500)}}async function O(m){let p=m.c,d=p.req.param(),l=u(d.repoName,p);if(!l)return B(p,"Repository not found",404);if(!l.allowDelete)return B(p,"Delete not allowed for this repository",403);let x=d.id;if(!x)return B(p,"Document ID required",400);try{let v=await y(l,x);if(!v)return B(p,"Document not found",404);let P=i(p),S=await a(p,l,"delete",{user:P,doc:v,params:d});if(!S.allowed)return S.errorResponse;let C=f(v,l)??[x];if(await l.repo.delete(...C),l.hooks?.afterDelete)try{await l.hooks.afterDelete({user:P,doc:v,id:x,pathArgs:C,params:d,c:p});}catch($){await s(l,m.logger,{hook:"afterDelete",repoName:l.name,path:l.path,id:x,pathArgs:C,user:P,c:p},$);}return qe(p,{deleted:!0})}catch(v){let P=n&&v instanceof Error?v.message:"Failed to delete document";return B(p,P,500)}}function A(m){return m.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 h(m){let p=m.c,d=p.req.param(),l=u(d.repoName,p);if(!l)return B(p,"Repository not found",404);try{let x=m.input||{};if(!Array.isArray(x.operations))return B(p,"operations array is required",400);let v=i(p),P=l.repo.batch.create(),S=[],C=!!l.hooks,$=[],H=[],_=[];for(let k of x.operations){if(!k.type||!["create","update","delete"].includes(k.type))return B(p,"Invalid operation type",400);if(k.type==="create"){let D=await a(p,l,"create",{user:v,body:k.data,params:d});if(!D.allowed)return D.errorResponse;let I=pn(l.schema,k.data,l.createFields,!1,l.systemKeys);if(!I.success)return B(p,I.error,400);l.hooks?.beforeCreate&&await l.hooks.beforeCreate({user:v,body:I.data,params:d,c:p});let M=k.data[l.documentKey]||I.data[l.documentKey]||Ee(),F={...I.data};l.createdKey&&F[l.createdKey]===void 0&&(F[l.createdKey]=new Date);let j;if(l.isGroup&&l.parentKeys){let z=l.parentKeys.map(q=>String(F[q]));j=[...z,M],P.set(...z,M,F);}else j=[M],P.set(M,F);if(S.push({op:"create",id:M}),C){let z={...F,[l.documentKey]:M};if(l.pathKey&&typeof l.repo.documentRef=="function")try{let q=l.repo.documentRef(...j);q?.path&&(z[l.pathKey]=q.path);}catch{}$.push({id:M,pathArgs:j,doc:z});}}else if(k.type==="update"){if(!k.id)return B(p,"id required for update",400);let D=await y(l,k.id);if(!D)return B(p,`Document ${k.id} not found`,404);let I=pn(l.schema,k.data,l.mutableFields,!0,l.systemKeys);if(!I.success)return B(p,I.error,400);if(l.validate){let Z=await l.validate(I.data,"update");if(Z)return B(p,Z,400)}let M=ye(D,I.data),F=await a(p,l,"update",{user:v,doc:D,body:I.data,diff:M,params:d});if(!F.allowed)return F.errorResponse;if(l.hooks?.beforeUpdate){let Z=l.rules?.update?ye(D,I.data):M;await l.hooks.beforeUpdate({user:v,doc:D,body:I.data,diff:Z,params:d,c:p});}let j={...I.data},z=C?ye(D,j):M,q=f(D,l)??[k.id];P.update(...q,I.data),S.push({op:"update",id:k.id}),C&&H.push({id:k.id,pathArgs:q,before:D,after:z.after,body:j,diff:z});}else if(k.type==="delete"){if(!l.allowDelete)return B(p,"Delete not allowed",403);if(!k.id)return B(p,"id required for delete",400);let D=await y(l,k.id);if(!D)return B(p,`Document ${k.id} not found`,404);let I=await a(p,l,"delete",{user:v,doc:D,params:d});if(!I.allowed)return I.errorResponse;let M=f(D,l)??[k.id];P.delete(...M),S.push({op:"delete",id:k.id}),C&&_.push({id:k.id,pathArgs:M,doc:D});}}await P.commit();let E=$.length>0||H.length>0||_.length>0;if(l.hooks&&E)if(l.hooks.afterBatch)try{await l.hooks.afterBatch({user:v,created:$,updated:H,deleted:_,params:d,c:p});}catch(k){await s(l,m.logger,{hook:"afterBatch",repoName:l.name,path:l.path,user:v,c:p},k);}else {if(l.hooks.afterCreate)for(let k of $)try{let D=await l.hooks.afterCreate({user:v,doc:k.doc,id:k.id,pathArgs:k.pathArgs,params:d,c:p}),I=mn(D);I&&k.pathArgs.length>0&&await l.repo.update(...k.pathArgs,I);}catch(D){await s(l,m.logger,{hook:"afterCreate",repoName:l.name,path:l.path,id:k.id,pathArgs:k.pathArgs,user:v,c:p},D);}if(l.hooks.afterUpdate)for(let k of H)try{let D=await l.hooks.afterUpdate({user:v,before:k.before,after:k.after,body:k.body,diff:k.diff,id:k.id,pathArgs:k.pathArgs,params:d,c:p}),I=mn(D);I&&k.pathArgs.length>0&&await l.repo.update(...k.pathArgs,I);}catch(D){await s(l,m.logger,{hook:"afterUpdate",repoName:l.name,path:l.path,id:k.id,pathArgs:k.pathArgs,user:v,c:p},D);}if(l.hooks.afterDelete)for(let k of _)try{await l.hooks.afterDelete({user:v,doc:k.doc,id:k.id,pathArgs:k.pathArgs,params:d,c:p});}catch(D){await s(l,m.logger,{hook:"afterDelete",repoName:l.name,path:l.path,id:k.id,pathArgs:k.pathArgs,user:v,c:p},D);}}return qe(p,{results:S})}catch(x){let v=n&&x instanceof Error?x.message:"Batch operation failed";return B(p,v,500)}}return {handleList:w,handleQuery:b,handleGet:g,handleCreate:T,handleUpdate:R,handleDelete:O,handleBatch:h,handleOptions:A}}function rt(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 oe(e){return {$ref:`#/components/schemas/${e}`}}function J(e){return {description:e,content:{"application/json":{schema:oe("ErrorResponse")}}}}function nt(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function Xa(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 due to OR conditions (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 $t(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 ei(e,t){let n=t.split("."),r=$t(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 c=a[s];if(o===n.length-1)return c;r=$t(c);}return r}function Le(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,c]of Object.entries(o))s[a]=Le(c);return r(z.object(s).partial())}if(n==="ZodOptional"||n==="optional"){let o=t.innerType;if(!o)return e;let s=Le(o);return s===o?e:r(s.optional())}if(n==="ZodNullable"||n==="nullable"){let o=t.innerType;if(!o)return e;let s=Le(o);return s===o?e:r(s.nullable())}if(n==="ZodDefault"||n==="default"){let o=t.innerType;return o?r(Le(o).optional()):e}if(n==="ZodUnion"||n==="union"){let o=t.options;if(!o||o.length<2)return e;let s=o.map(c=>Le(c));return s.some((c,i)=>c!==o[i])?r(z.union(s)):e}return e}function yr(e,t="",n=0){if(n>5)return [];let o=$t(e)?.shape;if(!o)return [];let s=[];for(let[a,c]of Object.entries(o)){let i=t?`${t}.${a}`:a,u=$t(c);u?.shape&&typeof u.shape=="object"?(s.push({path:i,zodSchema:c}),s.push(...yr(u,i,n+1))):s.push({path:i,zodSchema:c});}return s}function ti(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:ei(e.schema,t)})):yr(e.schema)}function Zo(e){if(!e)return {type:"string"};let t=rt(e);return delete t.$schema,delete t.title,t}function Lo(){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 ni(e){let t=ti(e),n=e.orderableFields??t.map(a=>a.path),r=t.map(a=>a.path);if(t.length===0)return Lo();let o=[];for(let{path:a,zodSchema:c}of t){let i=Zo(c),u=$t(c),y=u?._zod?.def?.type==="array"||u?._def?.typeName==="ZodArray"||u?._def?.type==="array"?Zo(u?._zod?.def?.element??u?._def?.type??u?._def?.element):i;o.push({type:"array",description:`Condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["==","!=","<","<=",">",">=","eq","ne","lt","lte","gt","gte"]},i],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:i}],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"]},y],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:y}],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 ri(e,t,n,r,o,s=null,a="QueryRequestBody"){let c={},i=e.name,u=`${t}/${e.name}`,f=`${u}/{${e.documentKey}}`,y={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};c[u]={post:{operationId:`create${He(e.name)}`,summary:`Create a ${xe(e.name)}`,tags:[i],requestBody:{required:true,content:{"application/json":{schema:oe(r??n)}}},responses:{201:nt("Document created",oe(n)),400:J("Validation error"),403:J("Forbidden"),500:J("Internal server error")}}},c[`${u}/query`]={post:{operationId:`query${He(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[i],requestBody:{required:true,content:{"application/json":{schema:oe(a)}}},responses:{200:Xa(oe(n)),400:J("Invalid query"),403:J("Forbidden"),424:J("Missing composite index (includes indexUrl in response)"),500:J("Internal server error")}}},c[`${u}/batch`]={post:{operationId:`batch${He(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[i],requestBody:{required:true,content:{"application/json":{schema:oe(`${n}BatchRequest`)}}},responses:{200:nt("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:J("Validation error"),403:J("Forbidden"),404:J("Document not found"),500:J("Internal server error")}}};let w={};return w.get={operationId:`get${He(xe(e.name))}`,summary:`Get a single ${xe(e.name)}`,tags:[i],parameters:[y],responses:{200:nt("Document found",oe(n)),400:J("Document ID required"),403:J("Forbidden"),404:J("Document not found"),424:J("Missing composite index (includes indexUrl in response)"),500:J("Internal server error")}},w.put={operationId:`update${He(xe(e.name))}`,summary:`Update a ${xe(e.name)} (full replace)`,tags:[i],parameters:[y],requestBody:{required:true,content:{"application/json":{schema:oe(o??n)}}},responses:{200:nt("Document updated",oe(n)),400:J("Validation error"),403:J("Forbidden"),404:J("Document not found"),500:J("Internal server error")}},w.patch={operationId:`patch${He(xe(e.name))}`,summary:`Partially update a ${xe(e.name)}`,tags:[i],parameters:[y],requestBody:{required:true,content:{"application/json":{schema:oe(s??o??n)}}},responses:{200:nt("Document patched",oe(n)),400:J("Validation error"),403:J("Forbidden"),404:J("Document not found"),500:J("Internal server error")}},e.allowDelete&&(w.delete={operationId:`delete${He(xe(e.name))}`,summary:`Delete a ${xe(e.name)}`,tags:[i],parameters:[y],responses:{200:nt("Document deleted",{type:"object",properties:{id:{type:"string"}}}),400:J("Document ID required"),403:J("Forbidden"),404:J("Document not found"),500:J("Internal server error")}}),c[f]=w,c}function mr(e,t,n={}){let{title:r="CRUD API",version:o="1.0.0",description:s,servers:a,auth:c=false}=n,i=t==="/"?"":t.replace(/\/$/,""),u={},f={},y=[];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=Lo();for(let[T,R]of Object.entries(e)){let O=He(xe(T)),A=`${O}Create`,h=`${O}Update`,m=`${O}Patch`,p=`${O}QueryRequestBody`;u[O]=rt(R.schema),u[p]=ni(R);let d=E=>{let k={},D=yr(R.schema);for(let{path:I,zodSchema:M}of D){let F=I.split(".")[0];R.systemKeys.includes(F)||R.systemKeys.includes(I)||E&&E.length>0&&!E.includes(I)&&!E.includes(F)||(I.includes(".")?k[I]=M.optional():k[I]=M);}return k},l=null,x=d(R.createFields);if(R.isGroup&&R.parentKeys&&R.parentKeys.length>0){let E=R.schema?.shape??{};for(let k of R.parentKeys)!x[k]&&E[k]&&(x[k]=E[k]);}if(Object.keys(x).length>0){let E=rt(z.object(x));if(R.isGroup&&R.parentKeys&&R.parentKeys.length>0){let k=new Set(Array.isArray(E.required)?E.required:[]);for(let D of R.parentKeys)E.properties?.[D]&&k.add(D);k.size>0&&(E.required=Array.from(k));}u[A]=E,l=A;}let v=null,P=null,S=d(R.mutableFields);if(Object.keys(S).length>0){let E=z.object(S);u[h]=rt(E),v=h,u[m]=rt(Le(E)),P=m;}else u[m]=rt(Le(R.schema)),P=m;let C=`${O}BatchCreateOperation`,$=`${O}BatchUpdateOperation`,H=`${O}BatchDeleteOperation`;u[C]={type:"object",title:`${O} Create Operation`,properties:{type:{type:"string",enum:["create"],const:"create"},data:oe(l??O)},required:["type","data"]},u[$]={type:"object",title:`${O} Update Operation`,properties:{type:{type:"string",enum:["update"],const:"update"},id:{type:"string"},data:oe(P??v??O)},required:["type","id","data"]},R.allowDelete&&(u[H]={type:"object",title:`${O} Delete Operation`,properties:{type:{type:"string",enum:["delete"],const:"delete"},id:{type:"string"}},required:["type","id"]}),u[`${O}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[oe(C),oe($),...R.allowDelete?[oe(H)]:[]],discriminator:{propertyName:"type"}}}},required:["operations"]};let _=ri(R,i,O,l,v,P,p);Object.assign(f,_),y.push({name:T,description:`Operations on ${T} (collection: ${R.path})`});}let w={},b;return c==="basic"?(w.basicAuth={type:"http",scheme:"basic"},b=[{basicAuth:[]}]):c==="bearer"&&(w.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},b=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:o,...s?{description:s}:{}},...a&&a.length>0?{servers:a}:{},paths:f,components:{schemas:u,...Object.keys(w).length>0?{securitySchemes:w}:{}},...b?{security:b}:{},tags:y}}function He(e){return e.charAt(0).toUpperCase()+e.slice(1)}function xe(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 ot=class extends Error{constructor(n,r){super("Request validation failed");this.zodError=n;this.source=r;this.statusCode=400;this.name="ValidationError";}};var Mt=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},_t=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function Wo(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function Vo(e,t){return t instanceof ot?e.json({success:false,error:"Validation failed",issues:Wo(t.zodError)},400):t instanceof Mt?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof _t?e.json({success:false,error:"Output validation failed",issues:Wo(t.zodError)},500):null}extendZodWithOpenApi(z);var Go="Successful response",Qo="Error response";function le(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&&le(r.innerType,t),r.element&&le(r.element,t),r.valueType&&le(r.valueType,t),r.keyType&&le(r.keyType,t),r.left&&le(r.left,t),r.right&&le(r.right,t),r.in&&le(r.in,t),r.out&&le(r.out,t),typeof r.getter=="function")try{le(r.getter(),t);}catch{}if(Array.isArray(r.options))for(let s of r.options)le(s,t);if(Array.isArray(r.items))for(let s of r.items)le(s,t);let o=typeof r.shape=="function"?r.shape():r.shape;if(o&&typeof o=="object")for(let s of Object.values(o))le(s,t);}function hr(e){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(let n of e)hr(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))hr(n);}function ci(e){return e==="get"?"query":"json"}function li(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function di(e){if(typeof e.safeParse=="function")return {description:Qo,schema:e};let t=e;return {description:t.description??Qo,schema:t.schema}}function Xo(e,t,n,r){let o=new OpenAPIRegistry;if(n.securitySchemes)for(let[c,i]of Object.entries(n.securitySchemes))o.registerComponent("securitySchemes",c,i);for(let c of e){let i=c.method,u=c.source??ci(i),f=fi(t,c.path??"/"),y=c.status??200;c.input&&le(c.input);let w=ui(i,u,c.input),b=Jo(u,c.input,"query"),g=Jo(u,c.input,"param"),T=yi(i,f),R=li(c.output,r);R&&le(R);let O={[y]:R?{description:Go,content:{"application/json":{schema:R}}}:{description:Go}};if(r?.errors)for(let[A,h]of Object.entries(r.errors)){let{description:m,schema:p}=di(h);p&&le(p),O[A]=p?{description:m,content:{"application/json":{schema:p}}}:{description:m};}o.registerPath({method:i,path:pi(f),operationId:T,summary:c.summary,description:c.description,tags:c.tags,deprecated:c.deprecated,security:c.security,request:{...b?{query:b}:{},...g?{params:g}:{},...w?{body:w}:{}},responses:O});}let a=new OpenApiGeneratorV31(o.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security});return hr(a),a}function ui(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 Jo(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function pi(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function fi(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function yi(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function es(e,t){let n=e.replace(/"/g,""");return `<!doctype html>
|
|
1155
|
+
`;function Ot(){return jsx("script",{dangerouslySetInnerHTML:{__html:Mo}})}or();function $e(e){return "<!DOCTYPE html>"+renderToString(e)}var si=["corporate","silk","dark"],ai=()=>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:si.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))})]}),He=({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(ai,{})})]}),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,c)=>a.href?jsx("li",{children:jsx("a",{href:a.href,children:a.label})},c):jsx("li",{class:"text-base-content/60",children:a.label},c))})}),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(rr,{basePath:s}),jsx(Ot,{})]})]})};function sr(e,t){return $e(jsx(He,{opts:t,children:jsx("div",{dangerouslySetInnerHTML:{__html:e}})}))}function ar(e,t){return $e(jsx(He,{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 jo=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],ii=[{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"}],ci=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function li(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return ii;case "ZodBoolean":return jo;case "ZodArray":return ci;default:return jo}}var Me="__null__";function di(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="${Me}"]');if(!o){o=document.createElement('option');o.value='${Me}';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='${Me}';i.readOnly=true;}i.style.opacity='0.55';}else{i.style.opacity='';if(i.tagName==='SELECT'){var o2=i.querySelector('option[value="${Me}"][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!=='${Me}')?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 $t({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:di(e)}),jsx("span",{children:"\u2205"})]})}function pi({col:e,active:t}){let n=t?.value??"",r=n===Me,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 c=new Set(n.split(",").map(u=>u.trim()).filter(Boolean)),i=`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:c.has(u),"data-enum-group":i,onchange:ui(o,i)}),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(c=>jsx("option",{value:c,selected:n===c,children:c},c)),e.nullable&&jsx("option",{value:Me,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx($t,{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:Me,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx($t,{inputId:o,active:r})]});if(e.zodType==="ZodArray"){let c=t?.op==="array-contains-any";return jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:c?"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($t,{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($t,{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($t,{inputId:o,active:r})]})}function ir({action:e,columnMeta:t,activeFilters:n,isGroup:r}){let o=Object.fromEntries(n.map(i=>[i.field,i])),s=n.length>0,a=n.length>=2||r&&s,c=t.filter(i=>i.zodType!=="ZodObject"&&i.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:c.map(i=>{let u=li(i.zodType),f=o[i.name],y=f?.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:i.name}),jsxs("div",{class:"flex gap-1.5",children:[u.length>1?jsx("select",{name:`fo_${i.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:u.map(b=>jsx("option",{value:b.value,selected:b.value===y,children:b.label},b.value))}):jsx("input",{type:"hidden",name:`fo_${i.name}`,value:u[0].value}),jsx(pi,{col:i,active:f})]})]},i.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 cr(e,t,n,r,o,s){let a=n==="create"?`Create ${e}`:`Edit ${e} / ${r??""}`,c=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 $e(jsx(He,{opts:{title:a,breadcrumb:c,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}})})})}))}ln();nr();function lr(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 zo(e,t,n,r,o){let s=lr(e,r,o);return s.set("cursor",t),s.set("dir",n),`?${s.toString()}`}function fi(e,t,n,r){let o=lr(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 yi(e,t,n){return `?${lr(t,n,e).toString()}`}function dr(e,t,n,r,o,s,a=[],c=[],i=false,u=[],f,y,b,h,g,T,v,E=false){let A=`${r}/${e}`,x=`${A}/create`,m={};if(v)for(let S of n)m[S]=Pt(It(v,S));let p=(T??[]).filter(S=>true),l=p.length>0,d=i,w=d||l,R=p.map(S=>{let C=It(v,S),H=Pt(C),_=a.find(M=>M.name===S);return {name:S,type:H,enumValues:_?.enumValues??null,nullable:_?.nullable??false}}),P=[];return v&&(P=pe(v).filter(C=>p.includes(C.name))),$e(jsxs(He,{opts:{title:e,breadcrumb:[{label:"Repositories",href:r},{label:e}],basePath:r,flash:s},children:[a.length>0&&jsx(ir,{action:A,columnMeta:a,activeFilters:c,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 g=="number"&&jsxs(Fragment,{children:[" ","of"," ",jsx("span",{class:"font-semibold text-base-content/80",children:g})]})," ","document",(typeof g=="number"?g: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(S=>jsx("a",{href:yi(S,c,f),class:`join-item btn btn-xs ${y===S?"btn-active btn-primary":"btn-outline"}`,children:S},S))})]})]}),jsxs("div",{class:"flex gap-2",children:[jsx("form",{method:"post",action:`${A}/_bulk/backfill`,onsubmit:"return confirm('Backfill entire repository? This will scan all documents and fill missing system keys.')",children:jsx("button",{type:"submit",class:"btn btn-outline btn-sm",children:"Backfill"})}),jsx("a",{href:x,class:"btn btn-primary btn-sm",children:"+ New"})]})]}),w&&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 g=="number"?String(g):"","data-frs-page-size":String(y??t.length),"data-frs-allow-delete":d?"1":"0","data-frs-allow-update":l?"1":"0","data-frs-fields":JSON.stringify(R),"data-frs-filters":JSON.stringify(c),children:[jsxs("div",{class:"flex-1 text-sm",children:[jsx("span",{"data-frs-bulk-summary":true,children:"0 selected"}),typeof g=="number"&&g>t.length&&jsxs("button",{type:"button",class:"ml-3 link text-sm hidden","data-frs-bulk-select-all":true,children:["Select all ",g," matching documents"]}),jsxs("span",{class:"hidden ml-3 italic","data-frs-bulk-all-active":true,children:["All ",g??"?"," 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:[l&&jsx("button",{type:"button",class:"btn btn-sm btn-outline","data-frs-bulk-action":"update",children:"Update field\u2026"}),d&&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:[w&&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((S,C)=>{let H=f?.field===S,_=H?f.dir==="asc"?" \u25B2":" \u25BC":"";return jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:jsxs("a",{href:fi(S,f,c,y),class:`hover:text-base-content inline-flex items-center gap-0.5${H?" text-primary font-bold":""}`,children:[S,_]})},C)}),u.map((S,C)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:S.column},`rel-${C}`)),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+(w?1:0),class:"text-center py-16 text-base-content/40",children:"No documents found"})}):t.map((S,C)=>{let H=String(S.docId??S.id??""),_=`${r}/${e}/${encodeURIComponent(H)}/edit`,M=`${r}/${e}/${encodeURIComponent(H)}/delete`;return jsxs("tr",{class:"hover","data-frs-row-id":H,children:[w&&jsx("td",{class:"align-middle py-2",children:jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-row":true,value:H,"aria-label":`Select ${H}`})}),n.map((O,k)=>{let D=S[O],I=m[O],$=I?Dt(I,D):null;return jsx("td",{class:"align-top py-2",children:jsx(ot,{val:D,mismatch:$})},k)}),u.map((O,k)=>{let D=S[O.key];if(D==null||D==="")return jsx("td",{class:"py-2"},`rel-${k}`);let I=O.type==="one"?`${r}/${O.targetRepo}/${encodeURIComponent(String(D))}/edit`:`${r}/${O.targetRepo}?fv_${O.targetKey}=${encodeURIComponent(String(D))}`;return jsx("td",{class:"align-middle py-2",children:jsx("a",{href:I,class:"btn btn-xs btn-ghost btn-outline","data-frs-relation":true,"data-frs-rel-type":O.type,"data-frs-rel-repo":O.targetRepo,"data-frs-rel-fk":O.targetKey,"data-frs-rel-val":String(D),"data-frs-rel-label":O.column,children:O.column})},`rel-${k}`)}),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"}),E&&jsx("a",{href:`${r}/${e}/${encodeURIComponent(H)}/history`,class:"btn btn-xs btn-outline",title:"View change history",children:"History"}),i&&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"})})]})})]},C)})})]})}),(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:zo(c,o.prevCursor,"prev",f,y),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:zo(c,o.nextCursor,"next",f,y),class:"btn btn-sm btn-outline",children:"Next \u2192"}):jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"Next \u2192"})]}),typeof g=="number"&&jsxs("div",{class:"text-xs text-base-content/50",children:[g," total document",g!==1?"s":"",c.length>0?" matching filters":""]})]}),w&&l&&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"}),p.map(S=>jsx("option",{value:S,children:S},S))]})]}),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:P.map(S=>jsx("div",{"data-frs-bulk-template-for":S.name,dangerouslySetInnerHTML:{__html:At(S)}},S.name))})]}))}function Ht(e,t){return sr(e,t)}function ur(e,t){return ar(e,t)}function pr(e,t,n,r,o,s,a,c,i,u,f,y,b,h,g,T,v,E){return dr(e,t,n,r,o,s,a,c,i,u,f,y,b,h,g,T,v,E)}function _e(e,t,n,r,o,s){return cr(e,t,n,r,o,s)}async function Bo(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 un(e,t){return Be(e,{pathKey:t.pathKey,documentKey:t.documentKey??"docId",parentKeys:t.parentKeys,documentPathTemplate:t.documentPathTemplate,isGroup:t.isGroup})}async function st(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 fr(e,t,n){let r=e.documentKey??"docId",o=Et(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 Z(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function pn(e,t){e.status(302).set("Location",t).send("");}function fn(e,t){let n=t.shape,r={};for(let[o,s]of Object.entries(n)){let a=mr(s),c=G(a),i=c==="ZodObject",u=a,f=false;if(c==="ZodUnion"){let h=kt(a);h.some(T=>G(T)==="ZodDate")&&(f=true);let g=h.find(T=>{if(G(T)==="ZodObject"){let v=ae(T);return "latitude"in v&&"longitude"in v}return false});g&&(i=true,u=g);}if(e[o+"__isnull"]==="1"){r[o]=null;continue}if(i){let h={},g=false;for(let[E,A]of Object.entries(e))E.startsWith(`${o}.`)&&(h[E.slice(o.length+1)]=A,g=true);if(g){r[o]=fn(h,u);continue}let T=e[o],v=Array.isArray(T)?T[T.length-1]:T;if(v)try{r[o]=JSON.parse(v);}catch{r[o]=v;}continue}let y=e[o],b=Array.isArray(y)?y[y.length-1]:y;if(b===void 0||b===""){c==="ZodBoolean"&&(r[o]=false);continue}if(f){r[o]=new Date(b);continue}switch(c){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 qo(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 Uo(e){let t=e;for(;;){let n=G(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=se(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=Rt(t);if(!r)return n;t=r;}else return n}}function mr(e){let t=e;for(;;){let n=G(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=se(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=Rt(t);if(!r)return t;t=r;}else return t}}function Zo(e){let t=e;for(;;){let n=G(t);if(n==="ZodOptional"||n==="ZodNullable")return true;if(n==="ZodDefault"){t=se(t);continue}return false}}function Lo(e){let t=mr(e),n=G(t);if(n==="ZodEnum"){let r=vt(t);return r.length>0?r:void 0}if(n==="ZodNativeEnum"){let r=Tt(t),o=Object.values(r).filter(s=>typeof s=="string");return o.length>0?o:void 0}if(n==="ZodLiteral"){let r=St(t);return typeof r=="string"?[r]:void 0}}function Wo(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 c=mr(t.shape[o]),i=G(c),u=i==="ZodObject",f=c,y=false;if(i==="ZodUnion"){let b=kt(c);b.some(g=>G(g)==="ZodDate")&&(y=true);let h=b.find(g=>{if(G(g)==="ZodObject"){let T=ae(g);return "latitude"in T&&"longitude"in T}return false});h&&(u=true,f=h);}if(u&&typeof a=="object"&&a!==null&&!Array.isArray(a)&&!("_seconds"in a)&&typeof a.toDate!="function"){let b=Wo(a,f,s);Object.assign(r,b);}else if(i==="ZodDate"||y){let b=qo(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=qo(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 yr(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?yr(n.nested,t):void 0}))}function gi(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 c=(s??"").trim();if(!c)continue;let i=e[`fo_${a}`]??"==",u=n.has(i)?i:"==";r.push({field:a,op:u,value:c});}return r}function Ko(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 Go(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 c=Uo(a);if(c==="ZodObject"){let i=a;for(;;){let f=G(i);if(f==="ZodOptional"||f==="ZodNullable"||f==="ZodDefault")i=se(i);else break}let u=ae(i);r.push(...Go(Object.keys(u),i,s));}else r.push({name:s,zodType:c,nullable:Zo(a),enumValues:Lo(a)});}return r}function bi(e,t){let n=t.split("."),r=e;for(let o of n){for(;;){let a=G(r);if(a==="ZodOptional"||a==="ZodNullable"||a==="ZodDefault")r=se(r);else break}let s=ae(r);if(!(o in s))return null;r=s[o];}return r}function Ue(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 c=s.slice(0,a),i=s.slice(a+1);r.has(c)||r.set(c,[]),r.get(c).push(i);}}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 c=e.shape[s];for(;;){let i=G(c);if(i==="ZodOptional"||i==="ZodNullable"||i==="ZodDefault")c=se(c);else break}if(G(c)!=="ZodObject"){o[s]=e.shape[s];continue}o[s]=Ue(c,a);}return z.object(o)}function xe(e,t,n){return we(e,t,n)}function Vo(e,t,n){let r=(x,m)=>{let p=xe(x,t,n),l=Object.values(e).map(d=>({name:d.name,path:d.path}));Z(m,ur(l,p));},o=async(x,m)=>{let p=x.params.repoName;if(!p){Z(m,"Bad request",400);return}let l=e[p];if(!l){Z(m,"Repository not found",404);return}let d=l.pageSize??25,w=x.query??{},R=w.cursor,P=w.dir==="prev"?"prev":"next",S=w.ob??"",C=w.od==="desc"?"desc":"asc",H=S?{field:S,dir:C}:void 0,_=parseInt(w.ps??""),M=Number.isFinite(_)&&_>0?Math.min(_,200):d,O=l.listColumns??Object.keys(l.schema.shape),k=l.documentKey??"docId",D=[k,...O.filter(de=>de!==k)];H&&(new Set([k,...O]).has(H.field)||(H=void 0));let I=l.filterableFields?(()=>{let de=[];for(let Te of l.filterableFields)(Te.includes(".")||O.includes(Te))&&de.push(Te);return de})():O,$=(()=>{let de=[];for(let Te of I)if(Te.includes(".")){let Qe=bi(l.schema,Te);de.push({name:Te,zodType:Qe?Uo(Qe):"ZodString",nullable:Qe?Zo(Qe):false,enumValues:Qe?Lo(Qe):void 0});}else de.push(...Go([Te],l.schema));return de})(),N=new Set($.map(de=>de.name)),F=gi(w,N),j=Ko(F),q;R&&(q=await Bo(l,R));let[U,Y]=await Promise.all([l.repo.query.paginate({pageSize:M,cursor:q,direction:P,...j.length>0?{where:j}:{},...H?{orderBy:[{field:H.field,direction:H.dir}]}:{}}).catch(de=>({queryError:Et(de,{ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:F,sort:H})})),l.repo.aggregate.count(j.length>0?{where:j}:{}).catch(()=>{})]),ve="queryError"in U,Sn=ve?[]:U.data,te=ve?"":U.nextCursor?.ref?.path??U.nextCursor?.id??"",ge=ve?"":U.prevCursor?.ref?.path??U.prevCursor?.id??"",Cs=ve?U.queryError:void 0,As=xe(x,t,n),lt,Bt=w.flash;Bt==="created"?lt={type:"success",message:"Document created successfully."}:Bt==="updated"?lt={type:"success",message:"Document updated successfully."}:Bt==="deleted"?lt={type:"success",message:"Document deleted successfully."}:Bt==="backfilled"&&(lt={type:"success",message:"Repository backfilled successfully."}),Z(m,pr(l.name,Sn,D,As,{hasPrev:ve?false:U.hasPrevPage,hasNext:ve?false:U.hasNextPage,prevCursor:ge,nextCursor:te},lt,$,F,l.allowDelete??false,l.relationalMeta,H,M,Cs,l.isGroup,Y,l.mutableFields,l.schema,l.historyEnabled));},s=(x,m)=>{let p=x.params.repoName;if(!p){Z(m,"Bad request",400);return}let l=e[p];if(!l){Z(m,"Repository not found",404);return}let d=xe(x,t,n),w=Ue(l.schema,l.createFields),R=pe(w),P=`${d}/${l.name}/create`,S=De(R,P,"POST","Create document");Z(m,_e(l.name,S,"create",null,d));},a=async(x,m)=>{let p=x.params.repoName;if(!p){Z(m,"Bad request",400);return}let l=e[p];if(!l){Z(m,"Repository not found",404);return}let d=xe(x,t,n),w=x.body??{},R=fn(w,l.schema),P=Ue(l.schema,l.createFields),S=P.safeParse(R);if(!S.success){let C=pe(P),H=`${d}/${l.name}/create`,_=De(C,H,"POST","Create document"),M=S.error.issues.map(O=>`${O.path.join(".")}: ${O.message}`).join(", ");Z(m,_e(l.name,_,"create",null,d,{type:"error",message:`Validation error: ${M}`}),422);return}try{if(l.isGroup&&l.parentKeys&&l.parentKeys.length>0){let C={...S.data},H=l.parentKeys.filter(_=>C[_]===void 0||C[_]===null||typeof C[_]=="string"&&C[_].trim()==="");if(H.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${H.join(", ")}`);if(typeof l.repo.create=="function")await l.repo.create(C);else {let _=l.parentKeys.map(k=>String(C[k])),M=l.documentKey??"docId",O=C[M]||Oe();await l.repo.set(..._,O,C);}}else await l.repo.create(S.data);pn(m,`${d}/${l.name}?flash=created`);}catch(C){let H=Ue(l.schema,l.createFields),_=pe(H),M=`${d}/${l.name}/create`,O=De(_,M,"POST","Create document");Z(m,_e(l.name,O,"create",null,d,{type:"error",message:`Save error: ${C.message}`}),500);}},c=async(x,m)=>{let p=x.params.repoName,l=x.params.id;if(!p||!l){Z(m,"Bad request",400);return}let d=e[p];if(!d){Z(m,"Repository not found",404);return}let w=xe(x,t,n),R=null;try{R=await st(d,l);}catch(M){let O=fr(d,l,M),k=qe(M)?424:500;Z(m,Ht("",{title:`Edit ${d.name} / ${l}`,basePath:w,breadcrumb:[{label:"Repositories",href:w},{label:d.name,href:`${w}/${d.name}`},{label:`Edit ${l}`}],flash:O}),k);return}if(!R){Z(m,"Document not found",404);return}let P=Wo(R,d.schema),S=Ue(d.schema,d.mutableFields),C=yr(pe(S),P),H=`${w}/${d.name}/${encodeURIComponent(l)}/edit`,_=De(C,H,"POST","Save changes");Z(m,_e(d.name,_,"edit",l,w));},i=async(x,m)=>{let p=x.params.repoName,l=x.params.id;if(!p||!l){Z(m,"Bad request",400);return}let d=e[p];if(!d){Z(m,"Repository not found",404);return}let w=xe(x,t,n),R=x.body??{},P=fn(R,d.schema),S=Ue(d.schema,d.mutableFields),H=S.partial().safeParse(P);if(!H.success){let _=Object.fromEntries(Object.entries(R).map(([I,$])=>[I,Array.isArray($)?$.join(","):$??""])),M=yr(pe(S),_),O=`${w}/${d.name}/${encodeURIComponent(l)}/edit`,k=De(M,O,"POST","Save changes"),D=H.error.issues.map(I=>`${I.path.join(".")}: ${I.message}`).join(", ");Z(m,_e(d.name,k,"edit",l,w,{type:"error",message:`Validation error: ${D}`}),422);return}try{let _=await st(d,l),M=(_&&un(_,d))??[l];await d.repo.update(...M,H.data),pn(m,`${w}/${d.name}?flash=updated`);}catch(_){let M=Ue(d.schema,d.mutableFields),O=pe(M),k=`${w}/${d.name}/${encodeURIComponent(l)}/edit`,D=De(O,k,"POST","Save changes"),I=qe(_)?fr(d,l,_):{type:"error",message:`Save error: ${_.message}`},$=qe(_)?424:500;Z(m,_e(d.name,D,"edit",l,w,I),$);}},u=async(x,m)=>{let p=x.params.repoName,l=x.params.id;if(!p||!l){Z(m,"Bad request",400);return}let d=e[p];if(!d){Z(m,"Repository not found",404);return}if(!d.allowDelete){Z(m,"Delete is not allowed for this repository",403);return}let w=xe(x,t,n);try{let R=await st(d,l),P=(R&&un(R,d))??[l];await d.repo.delete(...P),pn(m,`${w}/${d.name}?flash=deleted`);}catch(R){let P=qe(R)?fr(d,l,R):{type:"error",message:`Delete error: ${R.message}`},S=qe(R)?424:500;Z(m,Ht("",{title:`Delete ${d.name} / ${l}`,basePath:w,breadcrumb:[{label:"Repositories",href:w},{label:d.name,href:`${w}/${d.name}`},{label:`Delete ${l}`}],flash:P}),S);}},f=async(x,m)=>{let p=x.params.repoName;if(!p){Z(m,"Bad request",400);return}let l=e[p];if(!l){Z(m,"Repository not found",404);return}let d=xe(x,t,n),w=x.query,R=w?.type==="many"?"many":"one",P=Math.max(1,Math.min(100,Number(w?.ps??25)||25)),S=l.listColumns??Object.keys(ae(l.schema)),{PanelOne:C,PanelMany:H}=await Promise.resolve().then(()=>(or(),No)),{renderToString:_}=await import('hono/jsx/dom/server');if(R==="one"){let $=String(w?.id??"");if(!$){Z(m,"<div class='p-6 text-error'>Missing id parameter.</div>",400);return}try{let N=await st(l,$),F=_(C({doc:N,repoName:l.name,basePath:d,schema:l.schema,columns:S}));Z(m,F);}catch(N){Z(m,`<div class='p-6 text-error text-sm'>Error: ${N.message}</div>`,500);}return}let M=String(w?.fk??""),O=String(w?.fv??"");if(!M||!O){Z(m,"<div class='p-6 text-error'>Missing fk/fv parameters.</div>",400);return}let k=w?.cursor??"",D=w?.dir==="prev"?"prev":"next",I;k&&(I=await Bo(l,k));try{let $=await l.repo.query.paginate({pageSize:P,cursor:I,direction:D,where:[[M,"==",wi(O)]]}),N=_(H({docs:$.data,repoName:l.name,basePath:d,fk:M,fv:O,columns:S,schema:l.schema,pagination:{hasPrev:$.hasPrevPage,hasNext:$.hasNextPage,prevCursor:$.prevCursor?.ref?.path??$.prevCursor?.id??"",nextCursor:$.nextCursor?.ref?.path??$.nextCursor?.id??"",pageSize:P}}));Z(m,N);}catch($){Z(m,`<div class='p-6 text-error text-sm'>Error: ${$.message}</div>`,500);}},y=async(x,m)=>{let p=x.params.repoName;if(!p){Z(m,"Bad request",400);return}let l=e[p];if(!l){Z(m,"Repository not found",404);return}let d=xe(x,t,n);try{await l.repo.system.backfillKeys(),pn(m,`${d}/${l.name}?flash=backfilled`);}catch(w){Z(m,`<div class="p-6 text-error">Backfill failed: ${w.message}</div>`,500);}},b=async(x,m)=>{let p=[];for(let l of m){let d;if(x.isGroup||x.parentKeys?.length){let w=await st(x,l);d=w?un(w,x):void 0;}d||(d=[l]);try{let w=x.repo.documentRef(...d);w&&p.push(w);}catch{}}return p},h=async(x,m)=>{let p=Ko(m),l=x.documentKey??"docId",d=[],w;for(;;){let R=await x.repo.query.paginate({pageSize:500,cursor:w,direction:"next",...p.length>0?{where:p}:{}});for(let P of R.data){let S=String(P[l]??P.id??"");S&&d.push(S);}if(!R.hasNextPage||!R.nextCursor)break;w=R.nextCursor;}return d},g=async(x,m)=>{let p=x.params.repoName;if(!p){ce(m,{error:"Bad request"},400);return}let l=e[p];if(!l){ce(m,{error:"Repository not found"},404);return}if(!l.allowDelete){ce(m,{error:"Delete is not allowed for this repository"},403);return}let d=x.body??{};try{let w=await v(l,d);if(w.length===0){ce(m,{deleted:0});return}let R=await b(l,w);for(let P=0;P<R.length;P+=500)await l.repo.bulk.delete(R.slice(P,P+500));ce(m,{deleted:R.length});}catch(w){ce(m,{error:w.message},500);}},T=async(x,m)=>{let p=x.params.repoName;if(!p){ce(m,{error:"Bad request"},400);return}let l=e[p];if(!l){ce(m,{error:"Repository not found"},404);return}let d=x.body??{},w=String(d.field??"");if(!w){ce(m,{error:"Missing 'field'"},400);return}if(!l.mutableFields||!l.mutableFields.includes(w)){ce(m,{error:`Field '${w}' is not bulk-updatable`},403);return}let R=l.schema.shape?.[w],P;if(R){let S=typeof l.schema=="object"&&l.schema&&"constructor"in l.schema&&l.schema.constructor.name.includes("Zod")?l.schema.pick({[w]:true}):void 0;if(!S){ce(m,{error:"Invalid schema structure"},500);return}P=fn(d.formPayload??{},S)[w];let H=R.safeParse(P);if(!H.success){ce(m,{error:`Invalid value for '${w}': ${H.error.message}`},400);return}P=H.data;}try{let S=await v(l,d);if(S.length===0){ce(m,{updated:0});return}let H=(await b(l,S)).map(_=>({docRef:_,data:{[w]:P}}));for(let _=0;_<H.length;_+=500)await l.repo.bulk.update(H.slice(_,_+500));ce(m,{updated:H.length});}catch(S){ce(m,{error:S.message},500);}};async function v(x,m){if(m.selectAll){let p=E(m.filters,x);return await h(x,p)}return Array.isArray(m.ids)?m.ids.filter(p=>typeof p=="string"&&!!p):[]}function E(x,m){if(!Array.isArray(x))return [];let p=new Set((m.filterableFields??Object.keys(ae(m.schema))).map(w=>String(w))),l=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),d=[];for(let w of x)w&&typeof w=="object"&&typeof w.field=="string"&&p.has(w.field)&&typeof w.value=="string"&&l.has(String(w.op))&&d.push({field:w.field,op:w.op,value:w.value});return d}return {handleDashboard:r,handleList:o,handleCreateForm:s,handleCreateSubmit:a,handleEditForm:c,handleEditSubmit:i,handleDelete:u,handlePanel:f,handleBulkDelete:g,handleBulkUpdate:T,handleBulkBackfill:y,handleHistory:async(x,m)=>{let p=x.params.repoName,l=x.params.id;if(!p||!l){Z(m,"Bad request",400);return}let d=e[p];if(!d){Z(m,"Repository not found",404);return}if(!d.historyEnabled||!d.repo.history){Z(m,"History not enabled for this repository",404);return}let w=xe(x,t,n),R=d.historySubcollection??"history",P=[l];try{let $=await st(d,l),N=$?un($,d):void 0;N&&N.length>0&&(P=N);}catch{}let S=parseInt(String(x.query?.limit??"")),C=Number.isFinite(S)&&S>0?Math.min(S,500):100,H=[],_;try{H=await d.repo.history.list(...P,{limit:C});}catch($){_=$.message;}let M=$=>String($??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),O=$=>{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">${M(JSON.stringify($))}</code>`}catch{return M(String($))}return M(String($))},k=$=>$?typeof $.toDate=="function"?$.toDate().toISOString():$ instanceof Date?$.toISOString():M(String($)):"",D=$=>`<span class="badge badge-sm ${$==="create"?"badge-success":$==="delete"?"badge-error":$==="custom"?"badge-secondary":"badge-info"}">${M($)}</span>`,I="";if(I+='<div class="flex items-center justify-between mb-4">',I+=`<a href="${w}/${d.name}/${encodeURIComponent(l)}/edit" class="btn btn-sm btn-outline">\u2190 Back to edit</a>`,I+=`<a href="${w}/${d.name}" class="btn btn-sm btn-outline">\u2190 Back to list</a>`,I+="</div>",I+=`<p class="text-sm text-base-content/60 mb-4">Subcollection: <code>${M(R)}</code> \xB7 Showing up to ${C} entries.</p>`,_)I+=`<div class="alert alert-error mb-4">${M(_)}</div>`;else if(H.length===0)I+='<div class="alert">No history entries found.</div>';else {I+='<div class="overflow-x-auto"><table class="table table-zebra table-sm">',I+="<thead><tr><th>When</th><th>Op</th><th>User</th><th>Reason / Comment</th><th>Changes</th></tr></thead><tbody>";for(let $ of H){let N=$.meta??{},F=[N.reason,N.comment].filter(U=>U!=null&&U!=="").map(U=>M(String(U))).join(" \u2014 "),j="",q=Object.keys($.changes??{});if($.custom){let U=`<strong>${M($.custom.title)}</strong>`,Y=$.custom.key?` <code class="text-xs opacity-60">${M($.custom.key)}</code>`:"",ve=$.custom.description?`<div class="text-xs opacity-80 mt-0.5">${M($.custom.description)}</div>`:"";j=`<div>${U}${Y}${ve}</div>`;}else q.length===0?j='<span class="opacity-40">\u2014</span>':j='<ul class="space-y-1">'+q.map(U=>{let Y=$.changes[U];return `<li><strong>${M(U)}</strong>: ${O(Y.oldValue)} \u2192 ${O(Y.newValue)}</li>`}).join("")+"</ul>";I+="<tr>",I+=`<td class="whitespace-nowrap text-xs font-mono">${M(k($.historySetAt))}</td>`,I+=`<td>${D($.operation??"update")}</td>`,I+=`<td class="text-xs">${M(N.userEmail??N.userId??"")}</td>`,I+=`<td class="text-xs">${F}</td>`,I+=`<td>${j}</td>`,I+="</tr>";}I+="</tbody></table></div>";}Z(m,Ht(I,{title:`History \u2014 ${d.name} / ${l}`,basePath:w,breadcrumb:[{label:"Repositories",href:w},{label:d.name,href:`${w}/${d.name}`},{label:`History ${l}`}]}));}}}function ce(e,t,n=200){e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(t));}function wi(e){return e==="true"?true:e==="false"?false:e!==""&&!isNaN(Number(e))?Number(e):e}mn();async function xi(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function Ri(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 Xo(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,auth:s,middleware:a=[],httpsOptions:c}=e,i=t==="/"?"":t.replace(/\/$/,""),u={};for(let[h,g]of Object.entries(n)){if(!g.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=g.schema??g.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 v,E,A;if(g.fieldsConfig){let p=g.fieldsConfig;v=[],E=[],A=[];for(let[l,d]of Object.entries(p))for(let w of d)w==="filterable"?v.push(l):w==="mutable"?E.push(l):w==="create"&&A.push(l);v.length===0&&(v=void 0),E.length===0&&(E=void 0),A.length===0&&(A=void 0);}let x=(()=>{let p=g.repo._parentKeys;return p&&p.length>0?p:void 0})();if(x&&A)for(let p of x)A.includes(p)||A.push(p);let m={name:h,path:g.path,repo:g.repo,schema:T,documentKey:g.documentKey??"docId",pathKey:g.repo._pathKey??void 0,isGroup:!!g.repo._isGroup,parentKeys:x,documentPathTemplate:g.repo._documentPathTemplate??void 0,createdKey:g.repo._createdKey??void 0,listColumns:g.listColumns,pageSize:g.pageSize,filterableFields:v,mutableFields:E,createFields:A,allowDelete:g.allowDelete??false,historyEnabled:!!g.repo._historyConfig?.enabled,historySubcollection:(g.repo._historyConfig?.enabled&&g.repo._historySubcollection)??void 0,relationalMeta:(()=>{if(!g.relationalFields||g.relationalFields.length===0)return;let p=g.repo.relationalKeys??{},l=[];for(let d of g.relationalFields){let w=p[d.key];w&&l.push({key:w.sourceKey?String(w.sourceKey):d.key,column:d.column,targetRepo:String(w.repo),targetKey:String(w.key),type:w.type});}return l.length>0?l:void 0})()};u[h]=m;}let f=Vo(u,i,Xt(c?.region)),y=new Ae;if(o!==false&&y.use(yn(o===void 0?{}:o)),r&&y.use(async(h,g,T)=>{let v=h,E=String(v.headers?.["content-type"]??"");if(E.includes("application/x-www-form-urlencoded")){let A=await xi(v);h.body=Ri(A);}else if(E.includes("application/json")&&typeof v.body=="string")try{h.body=JSON.parse(v.body);}catch{}await T();}),s)if(wt(s)){for(let h of s.routes){let g=`${i}${h.path}`;h.method==="GET"?y.get(g,h.handler):y.post(g,h.handler);}y.use(s.middleware);}else if(typeof s=="function")y.use(s);else {let h=s.realm??"Admin",g="Basic "+Buffer.from(`${s.username}:${s.password}`).toString("base64");y.use((T,v,E)=>{if((T.headers?.authorization??"")!==g){v.status(401).set("WWW-Authenticate",`Basic realm="${h}"`).set("Content-Type","text/plain").send("Unauthorized");return}E();});}for(let h of a)y.use(h);y.get(`${i}/`,f.handleDashboard),y.get(`${i}`,f.handleDashboard),y.get(`${i}/:repoName/_panel`,f.handlePanel),y.post(`${i}/:repoName/_bulk/delete`,f.handleBulkDelete),y.post(`${i}/:repoName/_bulk/update`,f.handleBulkUpdate),y.post(`${i}/:repoName/_bulk/backfill`,f.handleBulkBackfill),y.get(`${i}/:repoName`,f.handleList),y.get(`${i}/:repoName/create`,f.handleCreateForm),y.post(`${i}/:repoName/create`,f.handleCreateSubmit),y.get(`${i}/:repoName/:id/edit`,f.handleEditForm),y.post(`${i}/:repoName/:id/edit`,f.handleEditSubmit),y.get(`${i}/:repoName/:id/history`,f.handleHistory),y.post(`${i}/:repoName/:id/delete`,f.handleDelete);let b=async(h,g)=>{await y.handle(h,g);};return c&&(b.httpsOptions=c),b}tt();function ye(e,t){let n=e||{},r={},o={...n};for(let[s,a]of Object.entries(t||{})){let c=n[s];ht(c,a)||(r[s]=a,o[s]=a);}return {before:n,after:o,changes:r}}function gr(e){return e}async function hn(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 br(e){return async t=>hn(t.diff,e,t.user)}var wr=1e3;function es(e,t){if(e===void 0)return {success:true,value:Math.min(Math.max(1,t),wr)};let n=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN;return !Number.isInteger(n)||n<=0||n>wr?{success:false,error:`Invalid pageSize: must be an integer between 1 and ${wr}`}:{success:true,value:n}}function vr(e,t,n=200){let r=X(t);return e.json(r,n)}function Ze(e,t,n,r=200){return vr(e,{success:true,data:t,meta:n},r)}function B(e,t,n=400){return vr(e,{success:false,error:t},n)}async function xr(e,t,n,r,o,s){let a=Et(t,n),c=a.type==="index",i=c?424:500,f={success:false,error:c?a.message:o&&t instanceof Error?t.message:r};if(c&&(f.errorType="index",a.indexUrl&&(f.indexUrl=a.indexUrl,s)))try{let y=s({indexUrl:a.indexUrl,repoName:n.repoName??"",path:n.path,isGroup:n.isGroup,filters:n.filters,sort:n.sort,error:t,c:e});y instanceof Promise&&await y;}catch(y){o&&console.error("[crudServer] Error in indexesError callback:",y);}return vr(e,f,i)}function Le(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=>In(r)??r,e);if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[s,a]of Object.entries(r))o[s]=Le(a);return z.object(o)}if(n==="ZodArray"||n==="array"){let r=t.element??t.type;if(r)return z.array(Le(r))}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(r)return Le(r).optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(r)return Le(r).nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType,o=t.defaultValue;if(r){let s=Le(r);return typeof o=="function"?s.default(o()):s.default(o)}}return e}function vi(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 c=a.split(".")[0];c&&r[c]&&(o[c]=r[c]);}return z.object(o)}function Rr(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=Rr(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 c=a[s];if(o===n.length-1)return c;r=Rr(c);}return r}function We(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]=We(a);return z.object(o).partial()}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(!r)return e;let o=We(r);return o===r?e:o.optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(!r)return e;let o=We(r);return o===r?e:o.nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType;return r?We(r).optional():e}if(n==="ZodUnion"||n==="union"){let r=t.options;if(!r||r.length<2)return e;let o=r.map(a=>We(a));return o.some((a,c)=>a!==r[c])?z.union(o):e}return e}function gn(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={},c={};for(let[i,u]of Object.entries(s))if(i.includes(".")){let f=i.split(".")[0];if(o.includes(i)||o.includes(f))continue;if(n&&n.length>0&&!n.includes(i)&&!n.includes(f))return {success:!1,error:`Field '${i}' is not allowed for this operation`};let y=rs(e,i);if(!y)return {success:!1,error:`Field '${i}' does not exist in schema`};let b=r?We(y):y,g=(Zt()==="normalize"?Le(b):b).parse(u);a[i]=g;}else c[i]=u;if(Object.keys(c).length>0||Object.keys(a).length===0){let i=vi(e,n,o),u=r?We(i):i,y=(Zt()==="normalize"?Le(u):u).parse(c);Object.assign(a,y);}return {success:!0,data:a}}catch(s){return s instanceof z.ZodError?{success:false,error:`Validation failed: ${s.issues.map(c=>`${c.path.join(".")}: ${c.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}var os={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 Mt(e){return os[e]??e}function Ti(e){return e in os}function bn(e,t,n,r){let o=rs(e,t);if(!o||typeof o.safeParse!="function")return {success:true,data:n};let s=r?Mt(r):void 0,a=Rr(o),c=tn(a);if(s==="array-contains"){let f=c??o;if(typeof f.safeParse=="function"){let y=f.safeParse(n);return y.success?{success:true,data:y.data}:{success:false,error:y.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 f=c??o,y=[];for(let b of n)if(typeof f.safeParse=="function"){let h=f.safeParse(b);if(h.success)y.push(h.data);else return {success:false,error:h.error.issues.map(T=>T.message).join(", ")}}else y.push(b);return {success:true,data:y}}let i=o.safeParse(n);if(i.success)return {success:true,data:i.data};if(Array.isArray(n)){let f=c??o,y=[];for(let b of n)if(typeof f.safeParse=="function"){let h=f.safeParse(b);if(h.success)y.push(h.data);else return {success:false,error:h.error.issues.map(T=>T.message).join(", ")}}else y.push(b);return {success:true,data:y}}return {success:false,error:i.error.issues.map(f=>f.message).join(", ")}}function Si(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 c=o.lastIndexOf("__"),i,u="==";if(c!==-1){let y=o.slice(0,c),b=o.slice(c+2);Ti(b)?(i=y,u=Mt(b)):(i=o,u="==");}else i=o;if(r&&!r.has(i))continue;let f=a;u==="in"||u==="not-in"||u==="array-contains-any"?f=a.split(",").map(y=>ts(y.trim())):f=ts(a),n.push({field:i,op:u,value:f});}return n}function ts(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 wn(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function ns(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 c=await a.doc(r).get();if(c.exists)return c}if(o&&o.includes("/")&&a&&typeof a.doc=="function"){let c=await a.doc(o).get();if(c.exists)return c}if(o&&typeof s.doc=="function"){let c=await s.doc(o).get();if(c.exists)return c}return}catch{return}}function xn(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 ss(e,t,n,r,o){async function s(m,p,l,d){let w=false;if(m.hooks?.onAfterError){w=true;try{let R=m.hooks.onAfterError(d,l.hook);R instanceof Promise&&await R;}catch(R){console.error("[crudServer] Error in hooks.onAfterError callback:",R);}}if(o){w=true;try{let R=o({...l,error:d});R instanceof Promise&&await R;}catch(R){console.error("[crudServer] Error in onHookError callback:",R);}}if(!w){if(p&&typeof p.error=="function"){p.error(d,{hook:l.hook,repoName:l.repoName,path:l.path,...l.id!==void 0?{id:l.id}:{},...l.pathArgs!==void 0?{pathArgs:l.pathArgs}:{}});return}console.error(`[crudServer] Hook "${l.hook}" failed on repo "${l.repoName}":`,{hook:l.hook,repoName:l.repoName,path:l.path,...l.id!==void 0?{id:l.id}:{},...l.pathArgs!==void 0?{pathArgs:l.pathArgs}:{},error:d});}}async function a(m,p,l,d){if(!p.rules)return {allowed:true};let w=p.rules?.[l];if(!w)return {allowed:false,errorResponse:B(m,`Operation "${l}" is not allowed for this repository`,403)};try{let R=await w(d);return R===!1?{allowed:!1,errorResponse:B(m,"Forbidden",403)}:typeof R=="string"?{allowed:!1,errorResponse:B(m,R,403)}:typeof R=="object"&&R!==null&&!R.allowed?{allowed:!1,errorResponse:B(m,R.reason||"Forbidden",403)}:{allowed:!0}}catch(R){let P=n&&R instanceof Error?R.message:"Forbidden";return {allowed:false,errorResponse:B(m,P,403)}}}async function c(m,p,l,d){if(!m.rules)return d;let w=m.rules?.filter;if(!w)return d;let R=[];for(let P of d)try{await w({user:p,doc:P,params:l})&&R.push(P);}catch{}return R}function i(m){return m.get("user")??m.get("docsUser")??null}function u(m,p){if(!m){let l=p.req.path.split("/");for(let d of l)if(e[d]){m=d;break}}return !m||!e[m]?null:e[m]??null}function f(m,p){return Be(m,{pathKey:p.pathKey,documentKey:p.documentKey,parentKeys:p.parentKeys,documentPathTemplate:p.documentPathTemplate,isGroup:p.isGroup})}async function y(m,p){let l=`by${m.documentKey.charAt(0).toUpperCase()}${m.documentKey.slice(1)}`,d=m.repo.get[l];if(typeof d=="function")try{let R=await d(p);if(R)return R}catch{}return (await m.repo.query.by({where:[[m.documentKey,"==",p]],limit:1}))[0]??null}async function b(m){let p=m.c,l=p.req.param(),d=u(l.repoName,p);if(!d)return B(p,"Repository not found",404);let w=i(p),R=await a(p,d,"list",{user:w,query:p.req.query(),params:l});if(!R.allowed)return R.errorResponse;let P=[],S;try{let C=p.req.query(),H=es(C.pageSize,d.pageSize);if(!H.success)return B(p,H.error,400);let _=H.value,M=C.cursor,O=C.direction?.toLowerCase()==="prev"?"prev":"next",k=C.orderBy,D=C.orderDir?.toLowerCase()==="desc"?"desc":"asc",I=C.select,$=I?I.split(",").map(te=>te.trim()):void 0,N=C.withTotal,F=N==="true"||N==="1"||N===!0,j;d.allowedIncludes&&C.includes&&(j=(typeof C.includes=="string"?C.includes.split(",").map(ge=>ge.trim()):Array.isArray(C.includes)?C.includes:[]).filter(ge=>typeof ge=="string"&&d.allowedIncludes.includes(ge)),j?.length===0&&(j=void 0));let q=Si(C,d.filterableFields);P=q.map(te=>({field:te.field,op:te.op,value:String(te.value??"")})),k&&(S={field:k,dir:D});let U={pageSize:_,direction:O,...F?{withTotal:!0}:{}};if(M)try{let te=typeof M=="string"?JSON.parse(M):M;U.cursor=await ns(d,te);}catch{}if(k){if(d.orderableFields&&!d.orderableFields.includes(k))return B(p,`Field not orderable: ${k}`,400);U.orderBy=[{field:k,direction:D}];}if(q.length>0){U.where=[];for(let te of q){let ge=bn(d.schema,te.field,te.value,te.op);if(!ge.success)return B(p,`Invalid filter value for '${te.field}': ${ge.error}`,400);U.where.push([te.field,te.op,ge.data]);}}$&&(U.select=$),j&&(U.include=j);let Y=await d.repo.query.paginate(U),Sn={items:await c(d,i(p),l,Y.data),hasNextPage:Y.hasNextPage,hasPrevPage:Y.hasPrevPage,nextCursor:wn(Y.nextCursor),prevCursor:wn(Y.prevCursor),...Y.totalCount!==void 0?{totalCount:Y.totalCount,totalCountIsExact:Y.totalCountIsExact}:{}};return Ze(p,Sn,{pageSize:_,hasMore:Y.hasNextPage,...Y.totalCount!==void 0?{totalCount:Y.totalCount,totalCountIsExact:Y.totalCountIsExact}:{}})}catch(C){return await xr(p,C,{repoName:l.repoName||d.name,ref:d.repo.ref,path:d.path,isGroup:!!d.isGroup,filters:P,sort:S},"Failed to fetch documents",n,r)}}async function h(m){let p=m.c,l=p.req.param(),d=u(l.repoName,p);if(!d)return B(p,"Repository not found",404);let w=i(p),R=await a(p,d,"list",{user:w,query:m.input||{},params:l});if(!R.allowed)return R.errorResponse;let P=[],S;try{let C=m.input||{},H=es(C.pageSize,d.pageSize);if(!H.success)return B(p,H.error,400);let _=H.value,M=C.direction==="prev"?"prev":"next";C.where&&(P=C.where.map(N=>({field:String(N[0]),op:N[1],value:String(N[2]??"")}))),C.orderBy&&C.orderBy[0]&&(S={field:C.orderBy[0].field,dir:C.orderBy[0].direction==="desc"?"desc":"asc"});let O=C.withTotal===!0||String(C.withTotal)==="true",k={pageSize:_,direction:M,...O?{withTotal:!0}:{}};if(C.cursor)try{let N=typeof C.cursor=="string"?JSON.parse(C.cursor):C.cursor;k.cursor=await ns(d,N);}catch{}if(d.allowedIncludes&&C.includes&&C.includes.length>0){let N=C.includes.filter(F=>typeof F=="string"?d.allowedIncludes.includes(F):typeof F=="object"&&F!==null&&"relation"in F&&typeof F.relation=="string"?d.allowedIncludes.includes(F.relation):!1);N.length>0&&(k.include=N);}if(C.where&&C.where.length>0){if(d.filterableFields){let F=new Set(d.filterableFields),j=C.where.filter(q=>!F.has(q[0]));if(j.length>0){B(p,`Fields not filterable: ${j.map(q=>q[0]).join(", ")}`,400);return}}let N=[];for(let F of C.where){let j=Mt(F[1]),q=bn(d.schema,F[0],F[2],j);if(!q.success){B(p,`Invalid filter value for '${F[0]}': ${q.error}`,400);return}N.push([F[0],j,q.data]);}k.where=N;}if(C.orWhere&&C.orWhere.length>0){if(d.filterableFields){let F=new Set(d.filterableFields),j=C.orWhere.filter(q=>!F.has(q[0]));if(j.length>0){B(p,`Fields not filterable: ${j.map(q=>q[0]).join(", ")}`,400);return}}let N=[];for(let F of C.orWhere){let j=Mt(F[1]),q=bn(d.schema,F[0],F[2],j);if(!q.success){B(p,`Invalid filter value for '${F[0]}': ${q.error}`,400);return}N.push([F[0],j,q.data]);}k.orWhere=N;}if(C.orWhereGroups&&C.orWhereGroups.length>0){if(d.filterableFields){let F=new Set(d.filterableFields);for(let j of C.orWhereGroups){let q=j.filter(U=>!F.has(U[0]));if(q.length>0){B(p,`Fields not filterable: ${q.map(U=>U[0]).join(", ")}`,400);return}}}let N=[];for(let F of C.orWhereGroups){let j=[];for(let q of F){let U=Mt(q[1]),Y=bn(d.schema,q[0],q[2],U);if(!Y.success){B(p,`Invalid filter value for '${q[0]}': ${Y.error}`,400);return}j.push([q[0],U,Y.data]);}N.push(j);}k.orWhereGroups=N;}if(C.orderBy&&C.orderBy.length>0){if(d.orderableFields){let N=new Set(d.orderableFields),F=C.orderBy.filter(j=>!N.has(j.field));if(F.length>0){B(p,`Fields not orderable: ${F.map(j=>j.field).join(", ")}`,400);return}}k.orderBy=C.orderBy;}C.select&&C.select.length>0&&(k.select=C.select);let D=await d.repo.query.paginate(k),$={items:await c(d,i(p),l,D.data),hasNextPage:D.hasNextPage,hasPrevPage:D.hasPrevPage,nextCursor:wn(D.nextCursor),prevCursor:wn(D.prevCursor),...D.totalCount!==void 0?{totalCount:D.totalCount,totalCountIsExact:D.totalCountIsExact}:{}};return Ze(p,$,{pageSize:_,hasMore:D.hasNextPage,...D.totalCount!==void 0?{totalCount:D.totalCount,totalCountIsExact:D.totalCountIsExact}:{}})}catch(C){return await xr(p,C,{repoName:l.repoName||d.name,ref:d.repo.ref,path:d.path,isGroup:!!d.isGroup,filters:P,sort:S},"Failed to query documents",n,r)}}async function g(m){let p=m.c,l=p.req.param(),d=u(l.repoName,p);if(!d)return B(p,"Repository not found",404);let w=l.id;if(!w)return B(p,"Document ID required",400);try{let R=await y(d,w);if(!R)return B(p,"Document not found",404);let P=i(p),S=await a(p,d,"get",{user:P,doc:R,params:l});if(!S.allowed)return S.errorResponse;if(d.rules?.filter)try{if(!await d.rules.filter({user:P,doc:R,params:l}))return B(p,"Document not found",404)}catch{return B(p,"Document not found",404)}return Ze(p,R)}catch(R){return await xr(p,R,{repoName:l.repoName||d.name,ref:d.repo.ref,path:d.path,isGroup:!!d.isGroup,filters:[{field:d.documentKey,op:"==",value:w}]},"Failed to fetch document",n,r)}}async function T(m){let p=m.c,l=p.req.param(),d=u(l.repoName,p);if(!d)return B(p,"Repository not found",404);try{let w=m.input||{},R=i(p),P=await a(p,d,"create",{user:R,body:w,params:l});if(!P.allowed)return P.errorResponse;let S=gn(d.schema,w,d.createFields,!1,d.systemKeys);if(!S.success)return B(p,S.error,400);if(d.validate){let M=await d.validate(S.data,"create");if(M)return B(p,M,400)}d.hooks?.beforeCreate&&await d.hooks.beforeCreate({user:R,body:S.data,params:l,c:p});let C,H;if(d.isGroup&&d.parentKeys&&d.parentKeys.length>0){let M={...S.data},O=d.parentKeys.filter(k=>M[k]===void 0||M[k]===null||typeof M[k]=="string"&&M[k].trim()==="");if(O.length>0)return B(p,`Missing parent key(s) for subcollection create: ${O.join(", ")}`,400);if(typeof d.repo.create=="function")C=await d.repo.create(M);else {let k=d.parentKeys.map(I=>String(M[I])),D=M[d.documentKey]||Oe();H=[...k,D],C=await d.repo.set(...k,D,M);}}else C=await d.repo.create(S.data);let _=C;if(d.hooks?.afterCreate){let M=C?.[d.documentKey]??H?.[H.length-1]??"",O=String(M),k=H??f(C,d)??f({...S.data,...O?{[d.documentKey]:O}:{}},d)??(O?[O]:[]);try{let D=await d.hooks.afterCreate({user:R,doc:C,id:O,pathArgs:k,params:l,c:p}),I=xn(D);I&&k.length>0&&(_=await d.repo.update(...k,I));}catch(D){await s(d,m.logger,{hook:"afterCreate",repoName:d.name,path:d.path,id:O,pathArgs:k,user:R,c:p},D);}}return Ze(p,_,void 0,201)}catch(w){let R=n&&w instanceof Error?w.message:"Failed to create document";return B(p,R,500)}}async function v(m,p){let l=m.c,d=l.req.param(),w=u(d.repoName,l);if(!w)return B(l,"Repository not found",404);let R=d.id;if(!R)return B(l,"Document ID required",400);try{let P=m.input||{},S=await y(w,R);if(!S)return B(l,"Document not found",404);let C=gn(w.schema,P,w.mutableFields,p,w.systemKeys);if(!C.success)return B(l,C.error,400);if(w.validate){let N=await w.validate(C.data,"update");if(N)return B(l,N,400)}let H=ye(S,C.data),_=i(l),M=await a(l,w,"update",{user:_,doc:S,body:C.data,diff:H,params:d});if(!M.allowed)return M.errorResponse;if(w.hooks?.beforeUpdate){let N=w.rules?.update?ye(S,C.data):H;await w.hooks.beforeUpdate({user:_,doc:S,body:C.data,diff:N,params:d,c:l});}let O={...C.data},k=w.hooks?.afterUpdate?ye(S,O):H,D=f(S,w)??[R],I=await w.repo.update(...D,C.data),$=I;if(w.hooks?.afterUpdate)try{let N=await w.hooks.afterUpdate({user:_,before:S,after:I,body:O,diff:k,id:R,pathArgs:D,params:d,c:l}),F=xn(N);F&&($=await w.repo.update(...D,F));}catch(N){await s(w,m.logger,{hook:"afterUpdate",repoName:w.name,path:w.path,id:R,pathArgs:D,user:_,c:l},N);}return Ze(l,$)}catch(P){let S=n&&P instanceof Error?P.message:"Failed to update document";return B(l,S,500)}}async function E(m){let p=m.c,l=p.req.param(),d=u(l.repoName,p);if(!d)return B(p,"Repository not found",404);if(!d.allowDelete)return B(p,"Delete not allowed for this repository",403);let w=l.id;if(!w)return B(p,"Document ID required",400);try{let R=await y(d,w);if(!R)return B(p,"Document not found",404);let P=i(p),S=await a(p,d,"delete",{user:P,doc:R,params:l});if(!S.allowed)return S.errorResponse;let C=f(R,d)??[w];if(await d.repo.delete(...C),d.hooks?.afterDelete)try{await d.hooks.afterDelete({user:P,doc:R,id:w,pathArgs:C,params:l,c:p});}catch(H){await s(d,m.logger,{hook:"afterDelete",repoName:d.name,path:d.path,id:w,pathArgs:C,user:P,c:p},H);}return Ze(p,{deleted:!0})}catch(R){let P=n&&R instanceof Error?R.message:"Failed to delete document";return B(p,P,500)}}function A(m){return m.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 x(m){let p=m.c,l=p.req.param(),d=u(l.repoName,p);if(!d)return B(p,"Repository not found",404);try{let w=m.input||{};if(!Array.isArray(w.operations))return B(p,"operations array is required",400);let R=i(p),P=d.repo.batch.create(),S=[],C=!!d.hooks,H=[],_=[],M=[];for(let k of w.operations){if(!k.type||!["create","update","delete"].includes(k.type))return B(p,"Invalid operation type",400);if(k.type==="create"){let D=await a(p,d,"create",{user:R,body:k.data,params:l});if(!D.allowed)return D.errorResponse;let I=gn(d.schema,k.data,d.createFields,!1,d.systemKeys);if(!I.success)return B(p,I.error,400);d.hooks?.beforeCreate&&await d.hooks.beforeCreate({user:R,body:I.data,params:l,c:p});let $=k.data[d.documentKey]||I.data[d.documentKey]||Oe(),N={...I.data};d.createdKey&&N[d.createdKey]===void 0&&(N[d.createdKey]=new Date);let F;if(d.isGroup&&d.parentKeys){let j=d.parentKeys.map(q=>String(N[q]));F=[...j,$],P.set(...j,$,N);}else F=[$],P.set($,N);if(S.push({op:"create",id:$}),C){let j={...N,[d.documentKey]:$};if(d.pathKey&&typeof d.repo.documentRef=="function")try{let q=d.repo.documentRef(...F);q?.path&&(j[d.pathKey]=q.path);}catch{}H.push({id:$,pathArgs:F,doc:j});}}else if(k.type==="update"){if(!k.id)return B(p,"id required for update",400);let D=await y(d,k.id);if(!D)return B(p,`Document ${k.id} not found`,404);let I=gn(d.schema,k.data,d.mutableFields,!0,d.systemKeys);if(!I.success)return B(p,I.error,400);if(d.validate){let U=await d.validate(I.data,"update");if(U)return B(p,U,400)}let $=ye(D,I.data),N=await a(p,d,"update",{user:R,doc:D,body:I.data,diff:$,params:l});if(!N.allowed)return N.errorResponse;if(d.hooks?.beforeUpdate){let U=d.rules?.update?ye(D,I.data):$;await d.hooks.beforeUpdate({user:R,doc:D,body:I.data,diff:U,params:l,c:p});}let F={...I.data},j=C?ye(D,F):$,q=f(D,d)??[k.id];P.update(...q,I.data),S.push({op:"update",id:k.id}),C&&_.push({id:k.id,pathArgs:q,before:D,after:j.after,body:F,diff:j});}else if(k.type==="delete"){if(!d.allowDelete)return B(p,"Delete not allowed",403);if(!k.id)return B(p,"id required for delete",400);let D=await y(d,k.id);if(!D)return B(p,`Document ${k.id} not found`,404);let I=await a(p,d,"delete",{user:R,doc:D,params:l});if(!I.allowed)return I.errorResponse;let $=f(D,d)??[k.id];P.delete(...$),S.push({op:"delete",id:k.id}),C&&M.push({id:k.id,pathArgs:$,doc:D});}}await P.commit();let O=H.length>0||_.length>0||M.length>0;if(d.hooks&&O)if(d.hooks.afterBatch)try{await d.hooks.afterBatch({user:R,created:H,updated:_,deleted:M,params:l,c:p});}catch(k){await s(d,m.logger,{hook:"afterBatch",repoName:d.name,path:d.path,user:R,c:p},k);}else {if(d.hooks.afterCreate)for(let k of H)try{let D=await d.hooks.afterCreate({user:R,doc:k.doc,id:k.id,pathArgs:k.pathArgs,params:l,c:p}),I=xn(D);I&&k.pathArgs.length>0&&await d.repo.update(...k.pathArgs,I);}catch(D){await s(d,m.logger,{hook:"afterCreate",repoName:d.name,path:d.path,id:k.id,pathArgs:k.pathArgs,user:R,c:p},D);}if(d.hooks.afterUpdate)for(let k of _)try{let D=await d.hooks.afterUpdate({user:R,before:k.before,after:k.after,body:k.body,diff:k.diff,id:k.id,pathArgs:k.pathArgs,params:l,c:p}),I=xn(D);I&&k.pathArgs.length>0&&await d.repo.update(...k.pathArgs,I);}catch(D){await s(d,m.logger,{hook:"afterUpdate",repoName:d.name,path:d.path,id:k.id,pathArgs:k.pathArgs,user:R,c:p},D);}if(d.hooks.afterDelete)for(let k of M)try{await d.hooks.afterDelete({user:R,doc:k.doc,id:k.id,pathArgs:k.pathArgs,params:l,c:p});}catch(D){await s(d,m.logger,{hook:"afterDelete",repoName:d.name,path:d.path,id:k.id,pathArgs:k.pathArgs,user:R,c:p},D);}}return Ze(p,{results:S})}catch(w){let R=n&&w instanceof Error?w.message:"Batch operation failed";return B(p,R,500)}}return {handleList:b,handleQuery:h,handleGet:g,handleCreate:T,handleUpdate:v,handleDelete:E,handleBatch:x,handleOptions:A}}function it(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 oe(e){return {$ref:`#/components/schemas/${e}`}}function J(e){return {description:e,content:{"application/json":{schema:oe("ErrorResponse")}}}}function at(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function ki(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 due to OR conditions (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 Nt(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 Ci(e,t){let n=t.split("."),r=Nt(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 c=a[s];if(o===n.length-1)return c;r=Nt(c);}return r}function Ve(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,c]of Object.entries(o))s[a]=Ve(c);return r(z.object(s).partial())}if(n==="ZodOptional"||n==="optional"){let o=t.innerType;if(!o)return e;let s=Ve(o);return s===o?e:r(s.optional())}if(n==="ZodNullable"||n==="nullable"){let o=t.innerType;if(!o)return e;let s=Ve(o);return s===o?e:r(s.nullable())}if(n==="ZodDefault"||n==="default"){let o=t.innerType;return o?r(Ve(o).optional()):e}if(n==="ZodUnion"||n==="union"){let o=t.options;if(!o||o.length<2)return e;let s=o.map(c=>Ve(c));return s.some((c,i)=>c!==o[i])?r(z.union(s)):e}return e}function Tr(e,t="",n=0){if(n>5)return [];let o=Nt(e)?.shape;if(!o)return [];let s=[];for(let[a,c]of Object.entries(o)){let i=t?`${t}.${a}`:a,u=Nt(c);u?.shape&&typeof u.shape=="object"?(s.push({path:i,zodSchema:c}),s.push(...Tr(u,i,n+1))):s.push({path:i,zodSchema:c});}return s}function Ai(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:Ci(e.schema,t)})):Tr(e.schema)}function as(e){if(!e)return {type:"string"};let t=it(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 Ei(e){let t=Ai(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:c}of t){let i=as(c),u=Nt(c),y=u?._zod?.def?.type==="array"||u?._def?.typeName==="ZodArray"||u?._def?.type==="array"?as(u?._zod?.def?.element??u?._def?.type??u?._def?.element):i;o.push({type:"array",description:`Condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["==","!=","<","<=",">",">=","eq","ne","lt","lte","gt","gte"]},i],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:i}],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"]},y],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:y}],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 Oi(e){if(e.historyHeaders)return e.historyHeaders;let t=e.repo?._historyConfig;if(!t?.enabled||t.autoInjectMeta===false)return null;let n=be(t);return n?{reason:n.fields.reason!==false,comment:n.fields.comment!==false}:null}function Pi(e,t){if(t===false)return [];let n=Oi(e);if(!n)return [];let r=t?.reasonHeader===void 0?je:t.reasonHeader,o=t?.commentHeader===void 0?ze:t.commentHeader,s=[],a=new Set;if(n.reason&&typeof r=="string"&&r.trim()){let c=r.trim();a.add(c.toLowerCase()),s.push({name:c,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 c=o.trim();a.has(c.toLowerCase())||(a.add(c.toLowerCase()),s.push({name:c,in:"header",required:false,schema:{type:"string"},description:"Optional comment recorded in the document's change history"}));}if(t?.extraHeaders?.length)for(let c of t.extraHeaders){let i=typeof c=="string"?{name:c}:c,u=i?.name?.trim();!u||a.has(u.toLowerCase())||(a.add(u.toLowerCase()),s.push({name:u,in:"header",required:i.required??false,schema:i.schema??{type:"string"},...i.description?{description:i.description}:{}}));}return s}function Ii(e,t,n,r,o,s=null,a="QueryRequestBody",c=[]){let i={},u=e.name,f=`${t}/${e.name}`,y=`${f}/{${e.documentKey}}`,b={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};i[f]={post:{operationId:`create${Ne(e.name)}`,summary:`Create a ${Re(e.name)}`,tags:[u],...c.length>0?{parameters:[...c]}:{},requestBody:{required:true,content:{"application/json":{schema:oe(r??n)}}},responses:{201:at("Document created",oe(n)),400:J("Validation error"),403:J("Forbidden"),500:J("Internal server error")}}},i[`${f}/query`]={post:{operationId:`query${Ne(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[u],requestBody:{required:true,content:{"application/json":{schema:oe(a)}}},responses:{200:ki(oe(n)),400:J("Invalid query"),403:J("Forbidden"),424:J("Missing composite index (includes indexUrl in response)"),500:J("Internal server error")}}},i[`${f}/batch`]={post:{operationId:`batch${Ne(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[u],...c.length>0?{parameters:[...c]}:{},requestBody:{required:true,content:{"application/json":{schema:oe(`${n}BatchRequest`)}}},responses:{200:at("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:J("Validation error"),403:J("Forbidden"),404:J("Document not found"),500:J("Internal server error")}}};let h={};return h.get={operationId:`get${Ne(Re(e.name))}`,summary:`Get a single ${Re(e.name)}`,tags:[u],parameters:[b],responses:{200:at("Document found",oe(n)),400:J("Document ID required"),403:J("Forbidden"),404:J("Document not found"),424:J("Missing composite index (includes indexUrl in response)"),500:J("Internal server error")}},h.put={operationId:`update${Ne(Re(e.name))}`,summary:`Update a ${Re(e.name)} (full replace)`,tags:[u],parameters:[b,...c],requestBody:{required:true,content:{"application/json":{schema:oe(o??n)}}},responses:{200:at("Document updated",oe(n)),400:J("Validation error"),403:J("Forbidden"),404:J("Document not found"),500:J("Internal server error")}},h.patch={operationId:`patch${Ne(Re(e.name))}`,summary:`Partially update a ${Re(e.name)}`,tags:[u],parameters:[b,...c],requestBody:{required:true,content:{"application/json":{schema:oe(s??o??n)}}},responses:{200:at("Document patched",oe(n)),400:J("Validation error"),403:J("Forbidden"),404:J("Document not found"),500:J("Internal server error")}},e.allowDelete&&(h.delete={operationId:`delete${Ne(Re(e.name))}`,summary:`Delete a ${Re(e.name)}`,tags:[u],parameters:[b],responses:{200:at("Document deleted",{type:"object",properties:{id:{type:"string"}}}),400:J("Document ID required"),403:J("Forbidden"),404:J("Document not found"),500:J("Internal server error")}}),i[y]=h,i}function Sr(e,t,n={}){let{title:r="CRUD API",version:o="1.0.0",description:s,servers:a,auth:c=false}=n,i=t==="/"?"":t.replace(/\/$/,""),u={},f={},y=[];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,v]of Object.entries(e)){let E=Ne(Re(T)),A=`${E}Create`,x=`${E}Update`,m=`${E}Patch`,p=`${E}QueryRequestBody`;u[E]=it(v.schema),u[p]=Ei(v);let l=k=>{let D={},I=Tr(v.schema);for(let{path:$,zodSchema:N}of I){let F=$.split(".")[0];v.systemKeys.includes(F)||v.systemKeys.includes($)||k&&k.length>0&&!k.includes($)&&!k.includes(F)||($.includes(".")?D[$]=N.optional():D[$]=N);}return D},d=null,w=l(v.createFields);if(v.isGroup&&v.parentKeys&&v.parentKeys.length>0){let k=v.schema?.shape??{};for(let D of v.parentKeys)!w[D]&&k[D]&&(w[D]=k[D]);}if(Object.keys(w).length>0){let k=it(z.object(w));if(v.isGroup&&v.parentKeys&&v.parentKeys.length>0){let D=new Set(Array.isArray(k.required)?k.required:[]);for(let I of v.parentKeys)k.properties?.[I]&&D.add(I);D.size>0&&(k.required=Array.from(D));}u[A]=k,d=A;}let R=null,P=null,S=l(v.mutableFields);if(Object.keys(S).length>0){let k=z.object(S);u[x]=it(k),R=x,u[m]=it(Ve(k)),P=m;}else u[m]=it(Ve(v.schema)),P=m;let C=`${E}BatchCreateOperation`,H=`${E}BatchUpdateOperation`,_=`${E}BatchDeleteOperation`;u[C]={type:"object",title:`${E} Create Operation`,properties:{type:{type:"string",enum:["create"],const:"create"},data:oe(d??E)},required:["type","data"]},u[H]={type:"object",title:`${E} Update Operation`,properties:{type:{type:"string",enum:["update"],const:"update"},id:{type:"string"},data:oe(P??R??E)},required:["type","id","data"]},v.allowDelete&&(u[_]={type:"object",title:`${E} Delete Operation`,properties:{type:{type:"string",enum:["delete"],const:"delete"},id:{type:"string"}},required:["type","id"]}),u[`${E}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[oe(C),oe(H),...v.allowDelete?[oe(_)]:[]],discriminator:{propertyName:"type"}}}},required:["operations"]};let M=Pi(v,n.historyHeaders),O=Ii(v,i,E,d,R,P,p,M);Object.assign(f,O),y.push({name:T,description:`Operations on ${T} (collection: ${v.path})`});}let b={},h;return c==="basic"?(b.basicAuth={type:"http",scheme:"basic"},h=[{basicAuth:[]}]):c==="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:f,components:{schemas:u,...Object.keys(b).length>0?{securitySchemes:b}:{}},...h?{security:h}:{},tags:y}}function Ne(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Re(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 ct=class extends Error{constructor(n,r){super("Request validation failed");this.zodError=n;this.source=r;this.statusCode=400;this.name="ValidationError";}};var Ft=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 ls(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function ds(e,t){return t instanceof ct?e.json({success:false,error:"Validation failed",issues:ls(t.zodError)},400):t instanceof Ft?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof jt?e.json({success:false,error:"Output validation failed",issues:ls(t.zodError)},500):null}extendZodWithOpenApi(z);var us="Successful response",ps="Error response";function le(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&&le(r.innerType,t),r.element&&le(r.element,t),r.valueType&&le(r.valueType,t),r.keyType&&le(r.keyType,t),r.left&&le(r.left,t),r.right&&le(r.right,t),r.in&&le(r.in,t),r.out&&le(r.out,t),typeof r.getter=="function")try{le(r.getter(),t);}catch{}if(Array.isArray(r.options))for(let s of r.options)le(s,t);if(Array.isArray(r.items))for(let s of r.items)le(s,t);let o=typeof r.shape=="function"?r.shape():r.shape;if(o&&typeof o=="object")for(let s of Object.values(o))le(s,t);}function kr(e){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(let n of e)kr(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))kr(n);}function _i(e){return e==="get"?"query":"json"}function Ni(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function Fi(e){if(typeof e.safeParse=="function")return {description:ps,schema:e};let t=e;return {description:t.description??ps,schema:t.schema}}function ms(e,t,n,r){let o=new OpenAPIRegistry;if(n.securitySchemes)for(let[c,i]of Object.entries(n.securitySchemes))o.registerComponent("securitySchemes",c,i);for(let c of e){let i=c.method,u=c.source??_i(i),f=Bi(t,c.path??"/"),y=c.status??200;c.input&&le(c.input);let b=ji(i,u,c.input),h=fs(u,c.input,"query"),g=fs(u,c.input,"param"),T=qi(i,f),v=Ni(c.output,r);v&&le(v);let E={[y]:v?{description:us,content:{"application/json":{schema:v}}}:{description:us}};if(r?.errors)for(let[A,x]of Object.entries(r.errors)){let{description:m,schema:p}=Fi(x);p&&le(p),E[A]=p?{description:m,content:{"application/json":{schema:p}}}:{description:m};}o.registerPath({method:i,path:zi(f),operationId:T,summary:c.summary,description:c.description,tags:c.tags,deprecated:c.deprecated,security:c.security,request:{...h?{query:h}:{},...g?{params:g}:{},...b?{body:b}:{}},responses:E});}let a=new OpenApiGeneratorV31(o.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security});return kr(a),a}function ji(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 fs(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function zi(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function Bi(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function qi(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,""");return `<!doctype html>
|
|
1156
1156
|
<html lang="en">
|
|
1157
1157
|
<head>
|
|
1158
1158
|
<meta charset="utf-8" />
|
|
@@ -1163,5 +1163,5 @@ function initColumnReorder(table) {
|
|
|
1163
1163
|
<script id="api-reference" data-url="${n}"></script>
|
|
1164
1164
|
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
|
|
1165
1165
|
</body>
|
|
1166
|
-
</html>`}function ts(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var gr=new AsyncLocalStorage;function ns(){return async(e,t)=>{await gr.run({c:e},async()=>{await t();});}}var bi=Object.freeze({}),gn=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new Hono,this.mountedRoutes=vi(t.routes,t.api),this.app.use("*",En(t.actorResolver)),t.services&&this.app.use("*",ns());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=Xo(this.mountedRoutes,this.options.basePath??"",this.options.openapi,xi(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=hn(t,o.path),a=o.middlewares??[],c=o.source??(o.method==="get"?"query":"json"),i=Si(o,c,n,wi(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),u=o.method.toUpperCase();this.app.on(u,[s],...a,i),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=hn(this.options.basePath??"",n),s=r===false?null:hn(this.options.basePath??"",r),a;if(ts(t.docsAuth)){let c=t.docsAuth;a=[c.middleware];let i=Ri(s??o);for(let u of c.routes)this.app.on(u.method,[hn(i,u.name)],u.handler);}else a=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[o],...a,c=>c.json(this.buildOpenApiSpec())),s){let c=Ti(s,o);this.app.on("GET",[s],...a,i=>i.html(es(c,t.info.title)));}}};function rs(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function wi(e){if(e)return rs(e)?e.handler:e}function xi(e){return rs(e)?e:void 0}function vi(e,t){return t?e.filter(n=>Array.isArray(n.api)?n.api.includes(t):n.api===t):e.slice()}function hn(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function Ri(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function Ti(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 Si(e,t,n,r,o,s,a){let c=e.input,i=e.output,u=e.status??200,f=o??bi;return async y=>{let w=async T=>{if(s){let R=await s.handle({error:T,c:y,route:e,services:f,logger:a});if(R)return R}return Vo(y,T)},b=async()=>{let T,R;try{R=await ki(y,t,e.method);}catch(A){throw new Mt(A instanceof Error?A.message:String(A))}if(c){let A=c.safeParse(R);if(!A.success)throw new ot(A.error,t);T=A.data;}else T=R;let O=await e.handler({input:T,c:y,services:f,errorHandler:s,logger:a});if(n&&i&&!(O instanceof Response)){let A=i.safeParse(O);if(!A.success)throw new _t(A.error);return A.data}return O},g;if(r)try{g=await r({next:b,route:e,c:y,services:f,errorHandler:s,logger:a});}catch(T){let R=await w(T);if(R)return R;throw T}else try{g=await b();}catch(T){let R=await w(T);if(R)return R;throw T}return g instanceof Response?g:y.json(g,u)}}async function ki(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 os(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 Ht(e,t,n,r,o,s=t?"update":"create"){for(let a of Object.keys(n.changes))await os(r[a],{body:e,doc:t,diff:n,key:a,operation:s,user:o});await os(r["*"],{body:e,doc:t,diff:n,key:"*",operation:s,user:o});}function wr(e){return async t=>{await Ht(t.body,t.doc,t.diff,e,t.user,"update");}}function xr(e){return async t=>{let n=ye({},t.body);await Ht(t.body,null,n,e,t.user,"create");}}function vr(e){return e}async function ss(e,t,n,r,o,s,a,c){if(!e?.length)return s;let i=s;for(let u of e){let f=null,y=false;try{if(y=!!await u.rule({diff:n,key:t,user:a,operation:c}),y){let w=await u.handler(r);w&&(i={...i,...w});}}catch(w){f=w;}o.push({key:String(t),description:u.description,isCalled:y,error:f});}return i}async function bn(e,t,n,r,o="update"){let s=[],a={};for(let c of Object.keys(e.changes))a=await ss(t[c],c,e,n,s,a,r,o);return a=await ss(t["*"],"*",e,n,s,a,r,o),{results:s,changesNeeded:a,hasErrors:s.some(c=>c.error!==null)}}function Rr(e,t,n){return async r=>{let o=t(r),{results:s,changesNeeded:a}=await bn(r.diff,e,o,r.user,"update");if(n?.onRuleError)for(let c of s)c.error&&await n.onRuleError(c,r);return Object.keys(a).length>0?a:void 0}}function as(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,verbose:s=false,httpsOptions:a}=e,c=t==="/"?"":t.replace(/\/$/,""),i={};for(let[A,h]of Object.entries(n)){if(!h.repo)throw new Error(`[createCrudServer] Repository "${A}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let m=h.schema??h.repo.schema??null;if(!m)throw new Error(`[createCrudServer] Repository "${A}" has no Zod schema.`);let p,d,l,x;if(h.fieldsConfig){let H=h.fieldsConfig;p=[],d=[],l=[],x=[];for(let[_,E]of Object.entries(H))for(let k of E)k==="filterable"?p.push(_):k==="orderable"?d.push(_):k==="mutable"?l.push(_):k==="create"&&x.push(_);d.length===0&&(d=p),p.length===0&&(p=void 0),d&&d.length===0&&(d=void 0),l.length===0&&(l=void 0),x.length===0&&(x=void 0);}let v=(()=>{let H=h.repo._parentKeys;return H&&H.length>0?H:void 0})();if(v&&x)for(let H of v)x.includes(H)||x.push(H);let P=h.repo._systemKeys??[h.documentKey??"docId"],S=h.repo._historyIdentityKeys??[],C=Array.from(new Set([...P,...S])),$={name:A,path:h.path,repo:h.repo,schema:m,systemKeys:C,documentKey:h.documentKey??"docId",pathKey:h.repo._pathKey??void 0,isGroup:!!h.repo._isGroup,parentKeys:v,documentPathTemplate:h.repo._documentPathTemplate??void 0,createdKey:h.repo._createdKey??void 0,pageSize:h.pageSize??25,filterableFields:p,orderableFields:d,mutableFields:l,createFields:x,allowDelete:h.allowDelete??false,allowedIncludes:h.allowedIncludes,validate:h.validate,rules:h.rules,hooks:h.hooks};i[A]=$;}let u=e.indexesError??e.onIndexError,f=Ko(i,c,s,u,e.onHookError),y=e.openapi,w=y&&typeof y=="object"?y:{},b=null;function g(){return b||(b=mr(i,c,{...w,auth:w.auth??false})),b}let T=[];for(let A of Object.keys(i))T.push({api:"crud",method:"post",path:`/${A}/query`,source:"json",handler:f.handleQuery}),T.push({api:"crud",method:"get",path:`/${A}/:id`,source:"query",handler:f.handleGet}),T.push({api:"crud",method:"post",path:`/${A}`,source:"json",handler:f.handleCreate}),T.push({api:"crud",method:"put",path:`/${A}/:id`,source:"json",handler:h=>f.handleUpdate(h,false)}),T.push({api:"crud",method:"patch",path:`/${A}/:id`,source:"json",handler:h=>f.handleUpdate(h,true)}),T.push({api:"crud",method:"delete",path:`/${A}/:id`,source:"query",handler:f.handleDelete}),T.push({api:"crud",method:"post",path:`/${A}/batch`,source:"json",handler:f.handleBatch});let R=new gn({...e,openapi:y!==false?{path:w.path??"/openapi.json",docsPath:w.docsPath??"/docs",info:{title:w.title??"CRUD API",version:w.version??"1.0.0"},docsAuth:w.docsAuth}:void 0,basePath:t,api:"crud",routes:T,middlewares:[async(A,h)=>{if(A.req.method==="OPTIONS")return A.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","Access-Control-Allow-Origin":"*","Access-Control-Allow-Credentials":"true"});A.header("Access-Control-Allow-Origin","*"),A.header("Access-Control-Allow-Credentials","true"),await h();},...e.middlewares||[]]});if(y!==false&&(R.buildOpenApiSpec=g),o!==false){let{securityHeaders:A}=(dn(),hs(Ho)),h=o===void 0?{csp:false}:o;R.hono.use("*",async(m,p)=>{let d=A(h);await new Promise(l=>{let x=m.req.raw;d(x,{setHeader:(P,S)=>m.header(P,S),removeHeader:P=>m.res.headers.delete(P)},()=>l());}),await p();});}let O=R.nodeHandler;return O.spec=g,a&&(O.httpsOptions=a),O}function is(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 cs(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 i=o?Wt(o[s],()=>e[s]):e[s];r[s]={...a,repo:i};}return r}function ls(e,t={}){return {admin(n){let r=cs(e,n.repos,"admin"),o=Fo({...n,repos:r,httpsOptions:n.httpsOptions??t.httpsOptions});return is(o,t)},crud(n){let r=cs(e,n.repos,"crud"),o=as({...n,repos:r,httpsOptions:n.httpsOptions??t.httpsOptions,actorResolver:n.actorResolver??t.actorResolver});return is(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}),lo(e,o)},meilisearchAdapter(n){return ()=>new tn(n)},history(n){let r=t.triggerOptions||n.triggerOptions?{...t.triggerOptions,...n.triggerOptions}:void 0,o={...n,...r?{triggerOptions:r}:{}};return Wr(e,o)}}}dn();function np(e){return t=>({...t,schema:e,type:null,documentRef:null,update:null})}function rp(e,t){let n={...e};for(let r in t)t[r]&&(n[r]={...e[r],relationalKeys:t[r]});return n}var Tr=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]=Fn(t,this.mapping[n],{});for(let n of Object.keys(this.mapping))this.allRepositories[n]=Fn(t,this.mapping[n],this.allRepositories);}getRepository(t){return this.ensureInitialized(),this.allRepositories[t]}};function op(e,t){let n=new Tr(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{On as DEFAULT_HISTORY_SHADOW_KEY,ke as MiniRouter,Tr as RepositoryMapping,bn as applyEffects,Ht as applyMutations,Ae as applyPaginationQueryOptions,un as applyRules,vn as buildAndCountQuery,Fe as buildAndExecuteQuery,rp as buildRepositoryRelations,Tn as coerceToDate,ye as computeDeepDiff,En as createActorContextMiddleware,An as createActorResolver,Rr as createAfterUpdateEffects,xr as createBeforeCreateMutations,lr as createBeforeRules,wr as createBeforeUpdateMutations,vr as createEffects,br as createMutations,Sn as createPaginationIterator,np as createRepositoryConfig,op as createRepositoryMapping,cr as createRules,ls as createServers,Ir as defaultActorResolver,Bt as executePaginatedQuery,Ve as getCurrentActor,zt as getDateHandling,Nt as normalizeTimestamps,bs as setDateHandling,ks as setRequestActorMeta,Ss as withActor};//# sourceMappingURL=index.js.map
|
|
1166
|
+
</html>`}function gs(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var Cr=new AsyncLocalStorage;function bs(){return async(e,t)=>{await Cr.run({c:e},async()=>{await t();});}}var Li=Object.freeze({}),vn=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new Hono,this.mountedRoutes=Vi(t.routes,t.api),this.app.use("*",Nn(t.actorResolver)),t.services&&this.app.use("*",bs());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=ms(this.mountedRoutes,this.options.basePath??"",this.options.openapi,Gi(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=Rn(t,o.path),a=o.middlewares??[],c=o.source??(o.method==="get"?"query":"json"),i=Yi(o,c,n,Wi(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),u=o.method.toUpperCase();this.app.on(u,[s],...a,i),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=Rn(this.options.basePath??"",n),s=r===false?null:Rn(this.options.basePath??"",r),a;if(gs(t.docsAuth)){let c=t.docsAuth;a=[c.middleware];let i=Qi(s??o);for(let u of c.routes)this.app.on(u.method,[Rn(i,u.name)],u.handler);}else a=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[o],...a,c=>c.json(this.buildOpenApiSpec())),s){let c=Ji(s,o);this.app.on("GET",[s],...a,i=>i.html(hs(c,t.info.title)));}}};function ws(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function Wi(e){if(e)return ws(e)?e.handler:e}function Gi(e){return ws(e)?e:void 0}function Vi(e,t){return t?e.filter(n=>Array.isArray(n.api)?n.api.includes(t):n.api===t):e.slice()}function Rn(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function Qi(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function Ji(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 Yi(e,t,n,r,o,s,a){let c=e.input,i=e.output,u=e.status??200,f=o??Li;return async y=>{let b=async T=>{if(s){let v=await s.handle({error:T,c:y,route:e,services:f,logger:a});if(v)return v}return ds(y,T)},h=async()=>{let T,v;try{v=await Xi(y,t,e.method);}catch(A){throw new Ft(A instanceof Error?A.message:String(A))}if(c){let A=c.safeParse(v);if(!A.success)throw new ct(A.error,t);T=A.data;}else T=v;let E=await e.handler({input:T,c:y,services:f,errorHandler:s,logger:a});if(n&&i&&!(E instanceof Response)){let A=i.safeParse(E);if(!A.success)throw new jt(A.error);return A.data}return E},g;if(r)try{g=await r({next:h,route:e,c:y,services:f,errorHandler:s,logger:a});}catch(T){let v=await b(T);if(v)return v;throw T}else try{g=await h();}catch(T){let v=await b(T);if(v)return v;throw T}return g instanceof Response?g:y.json(g,u)}}async function Xi(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 Ar(e){return e}async function xs(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 zt(e,t,n,r,o,s=t?"update":"create"){for(let a of Object.keys(n.changes))await xs(r[a],{body:e,doc:t,diff:n,key:a,operation:s,user:o});await xs(r["*"],{body:e,doc:t,diff:n,key:"*",operation:s,user:o});}function Er(e){return async t=>{await zt(t.body,t.doc,t.diff,e,t.user,"update");}}function Or(e){return async t=>{let n=ye({},t.body);await zt(t.body,null,n,e,t.user,"create");}}function Pr(e){return e}async function Rs(e,t,n,r,o,s,a,c){if(!e?.length)return s;let i=s;for(let u of e){let f=null,y=false;try{if(y=!!await u.rule({diff:n,key:t,user:a,operation:c}),y){let b=await u.handler(r);b&&(i={...i,...b});}}catch(b){f=b;}o.push({key:String(t),description:u.description,isCalled:y,error:f});}return i}async function Tn(e,t,n,r,o="update"){let s=[],a={};for(let c of Object.keys(e.changes))a=await Rs(t[c],c,e,n,s,a,r,o);return a=await Rs(t["*"],"*",e,n,s,a,r,o),{results:s,changesNeeded:a,hasErrors:s.some(c=>c.error!==null)}}function Ir(e,t,n){return async r=>{let o=t(r),{results:s,changesNeeded:a}=await Tn(r.diff,e,o,r.user,"update");if(n?.onRuleError)for(let c of s)c.error&&await n.onRuleError(c,r);return Object.keys(a).length>0?a:void 0}}function vs(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,verbose:s=false,httpsOptions:a}=e,c=t==="/"?"":t.replace(/\/$/,""),i={};for(let[p,l]of Object.entries(n)){if(!l.repo)throw new Error(`[createCrudServer] Repository "${p}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let d=l.schema??l.repo.schema??null;if(!d)throw new Error(`[createCrudServer] Repository "${p}" has no Zod schema.`);let w,R,P,S;if(l.fieldsConfig){let $=l.fieldsConfig;w=[],R=[],P=[],S=[];for(let[N,F]of Object.entries($))for(let j of F)j==="filterable"?w.push(N):j==="orderable"?R.push(N):j==="mutable"?P.push(N):j==="create"&&S.push(N);R.length===0&&(R=w),w.length===0&&(w=void 0),R&&R.length===0&&(R=void 0),P.length===0&&(P=void 0),S.length===0&&(S=void 0);}let C=(()=>{let $=l.repo._parentKeys;return $&&$.length>0?$:void 0})();if(C&&S)for(let $ of C)S.includes($)||S.push($);let H=l.repo._systemKeys??[l.documentKey??"docId"],_=l.repo._historyIdentityKeys??[],M=Array.from(new Set([...H,..._])),O=l.repo._historyConfig,k=O?.enabled&&O.autoInjectMeta!==false?be(O):null,D=k?{reason:k.fields.reason!==false,comment:k.fields.comment!==false}:void 0,I={name:p,path:l.path,repo:l.repo,schema:d,systemKeys:M,documentKey:l.documentKey??"docId",pathKey:l.repo._pathKey??void 0,isGroup:!!l.repo._isGroup,parentKeys:C,documentPathTemplate:l.repo._documentPathTemplate??void 0,createdKey:l.repo._createdKey??void 0,pageSize:l.pageSize??25,filterableFields:w,orderableFields:R,mutableFields:P,createFields:S,allowDelete:l.allowDelete??false,allowedIncludes:l.allowedIncludes,validate:l.validate,rules:l.rules,hooks:l.hooks,...D?{historyHeaders:D}:{}};i[p]=I;}let u=e.indexesError??e.onIndexError,f=ss(i,c,s,u,e.onHookError),y=e.openapi,b=y&&typeof y=="object"?y:{},h=_n(e.actorResolver),g=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 p=["Content-Type","Authorization"],l=new Set(p.map(w=>w.toLowerCase())),d=w=>{if(typeof w!="string")return;let R=w.trim();!R||l.has(R.toLowerCase())||(l.add(R.toLowerCase()),p.push(R));};if(d(h.reasonHeader),d(h.commentHeader),b.historyHeaders&&typeof b.historyHeaders=="object"&&(d(b.historyHeaders.reasonHeader),d(b.historyHeaders.commentHeader),b.historyHeaders.extraHeaders))for(let w of b.historyHeaders.extraHeaders)d(typeof w=="string"?w:w?.name);return p.join(", ")})(),v=null;function E(){return v||(v=Sr(i,c,{...b,auth:b.auth??false,historyHeaders:g})),v}let A=[];for(let p of Object.keys(i))A.push({api:"crud",method:"post",path:`/${p}/query`,source:"json",handler:f.handleQuery}),A.push({api:"crud",method:"get",path:`/${p}/:id`,source:"query",handler:f.handleGet}),A.push({api:"crud",method:"post",path:`/${p}`,source:"json",handler:f.handleCreate}),A.push({api:"crud",method:"put",path:`/${p}/:id`,source:"json",handler:l=>f.handleUpdate(l,false)}),A.push({api:"crud",method:"patch",path:`/${p}/:id`,source:"json",handler:l=>f.handleUpdate(l,true)}),A.push({api:"crud",method:"delete",path:`/${p}/:id`,source:"query",handler:f.handleDelete}),A.push({api:"crud",method:"post",path:`/${p}/batch`,source:"json",handler:f.handleBatch});let x=new vn({...e,openapi:y!==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(p,l)=>{if(p.req.method==="OPTIONS")return p.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"});p.header("Access-Control-Allow-Origin","*"),p.header("Access-Control-Allow-Credentials","true"),await l();},...e.middlewares||[]]});if(y!==false&&(x.buildOpenApiSpec=E),o!==false){let{securityHeaders:p}=(mn(),Ds(Yo)),l=o===void 0?{csp:false}:o;x.hono.use("*",async(d,w)=>{let R=p(l);await new Promise(P=>{let S=d.req.raw;R(S,{setHeader:(H,_)=>d.header(H,_),removeHeader:H=>d.res.headers.delete(H)},()=>P());}),await w();});}let m=x.nodeHandler;return m.spec=E,a&&(m.httpsOptions=a),m}function Ts(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 Ss(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 i=o?Yt(o[s],()=>e[s]):e[s];r[s]={...a,repo:i};}return r}function ks(e,t={}){return {admin(n){let r=Ss(e,n.repos,"admin"),o=Xo({...n,repos:r,httpsOptions:n.httpsOptions??t.httpsOptions});return Ts(o,t)},crud(n){let r=Ss(e,n.repos,"crud"),o=vs({...n,repos:r,httpsOptions:n.httpsOptions??t.httpsOptions,actorResolver:n.actorResolver??t.actorResolver});return Ts(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}),Co(e,o)},meilisearchAdapter(n){return ()=>new an(n)},history(n){let r=t.triggerOptions||n.triggerOptions?{...t.triggerOptions,...n.triggerOptions}:void 0,o={...n,...r?{triggerOptions:r}:{}};return lo(e,o)}}}mn();function Hp(e){return t=>({...t,schema:e,type:null,documentRef:null,update:null})}function Mp(e,t){let n={...e};for(let r in t)t[r]&&(n[r]={...e[r],relationalKeys:t[r]});return n}var Dr=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]=Ln(t,this.mapping[n],{});for(let n of Object.keys(this.mapping))this.allRepositories[n]=Ln(t,this.mapping[n],this.allRepositories);}getRepository(t){return this.ensureInitialized(),this.allRepositories[t]}};function _p(e,t){let n=new Dr(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{ze as DEFAULT_HISTORY_COMMENT_HEADER,je as DEFAULT_HISTORY_REASON_HEADER,Fn as DEFAULT_HISTORY_SHADOW_KEY,Ae as MiniRouter,Dr as RepositoryMapping,Tn as applyEffects,zt as applyMutations,Ee as applyPaginationQueryOptions,hn as applyRules,On as buildAndCountQuery,Fe as buildAndExecuteQuery,Mp as buildRepositoryRelations,In as coerceToDate,ye as computeDeepDiff,Nn as createActorContextMiddleware,Mn as createActorResolver,Ir as createAfterUpdateEffects,Or as createBeforeCreateMutations,br as createBeforeRules,Er as createBeforeUpdateMutations,Pr as createEffects,Ar as createMutations,Dn as createPaginationIterator,Hp as createRepositoryConfig,_p as createRepositoryMapping,gr as createRules,ks as createServers,Wr as defaultActorResolver,Lt as executePaginatedQuery,_n as getActorResolverHeaders,Xe as getCurrentActor,Zt as getDateHandling,Ut as normalizeTimestamps,Us as setDateHandling,Js as setRequestActorMeta,Qs as withActor};//# sourceMappingURL=index.js.map
|
|
1167
1167
|
//# sourceMappingURL=index.js.map
|