@lpdjs/firestore-repo-service 2.6.46 → 2.6.47
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +34 -34
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +34 -34
- package/dist/index.js.map +1 -1
- package/dist/llms-full.txt +1 -1
- package/dist/llms.txt +1 -1
- package/dist/servers/crud/index.cjs +2 -2
- package/dist/servers/crud/index.cjs.map +1 -1
- package/dist/servers/crud/index.js +2 -2
- package/dist/servers/crud/index.js.map +1 -1
- package/dist/servers/index.cjs +1 -1
- package/dist/servers/index.cjs.map +1 -1
- package/dist/servers/index.js +1 -1
- package/dist/servers/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var jsxRuntime=require('hono/jsx/jsx-runtime'),firestore=require('firebase-admin/firestore'),crypto=require('crypto'),zod=require('zod'),server=require('hono/jsx/dom/server'),zodToOpenapi=require('@asteasolutions/zod-to-openapi'),hono=require('hono'),nodeServer=require('@hono/node-server'),async_hooks=require('async_hooks');var zt=Object.defineProperty;var po=Object.getOwnPropertyDescriptor;var fo=Object.getOwnPropertyNames;var yo=Object.prototype.hasOwnProperty;var Ne=(e,t)=>()=>(e&&(t=e(e=0)),t);var Pn=(e,t)=>{for(var n in t)zt(e,n,{get:t[n],enumerable:true});},mo=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of fo(t))!yo.call(e,o)&&o!==n&&zt(e,o,{get:()=>t[o],enumerable:!(r=po(t,o))||r.enumerable});return e};var go=e=>mo(zt({},"__esModule",{value:true}),e);function Z(e){let t=e,n=t._zod?.def?.type;if(n)return Uo[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=t._def?.typeName;return r||""}function ee(e){let t=e;if(t._zod?.def?.innerType)return t._zod.def.innerType;if(t._def?.innerType)return t._def.innerType}function Le(e){let t=e,n=t._zod?.def?.in;if(n)return n;if(t._def?.schema)return t._def.schema}function Xn(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}function Yn(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 te(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 Ue(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 Qe(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 Ve(e){let t=e;return Array.isArray(t._zod?.def?.values)?t._zod.def.values[0]:t._def?.value}function We(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 er(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 Uo,Ge=Ne(()=>{Uo={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 xr({val:e}){return jsxRuntime.jsx("span",{class:"text-sm text-base-content/80 font-mono tabular-nums whitespace-nowrap",children:e.toLocaleString()})}function ys({message:e}){return jsxRuntime.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:jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",class:"size-3.5",children:jsxRuntime.jsx("path",{d:"M12 2 1 22h22L12 2zm0 6 7.5 13h-15L12 8zm-1 4v4h2v-4h-2zm0 5v2h2v-2h-2z"})})})}function De({val:e,mismatch:t}){let n=nn(e);return t?jsxRuntime.jsxs("span",{class:"inline-flex items-start gap-0.5",children:[n,jsxRuntime.jsx(ys,{message:t})]}):n}function nn(e){if(e==null)return jsxRuntime.jsx("span",{class:"opacity-30 italic text-xs",children:"\u2014"});if(typeof e=="boolean")return e?jsxRuntime.jsx("span",{class:"badge badge-success badge-sm",children:"true"}):jsxRuntime.jsx("span",{class:"badge badge-error badge-sm",children:"false"});if(e instanceof Date)return jsxRuntime.jsx(xr,{val:e});if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")return jsxRuntime.jsx(xr,{val:e.toDate()});if(typeof e=="number")return jsxRuntime.jsx("span",{class:"text-sm font-mono tabular-nums",children:String(e)});if(Array.isArray(e))return e.length===0?jsxRuntime.jsx("span",{class:"text-xs text-base-content/30",children:"[]"}):jsxRuntime.jsxs("ul",{class:"list-none p-0 m-0 space-y-0.5 text-xs",children:[e.slice(0,8).map((n,r)=>jsxRuntime.jsx("li",{class:"break-all",children:nn(n)},r)),e.length>8&&jsxRuntime.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?jsxRuntime.jsx("span",{class:"text-xs text-base-content/30",children:"{}"}):jsxRuntime.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])=>jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("dt",{class:"text-base-content/50 font-semibold whitespace-nowrap",children:r}),jsxRuntime.jsx("dd",{class:"break-all",children:nn(o)})]})),n.length>8&&jsxRuntime.jsxs("dt",{class:"col-span-2 text-base-content/40 italic",children:["+",n.length-8," more\u2026"]})]})}let t=String(e);return jsxRuntime.jsx("span",{class:"text-sm break-all",children:t})}var At=Ne(()=>{});function tt(e){if(!e)return "unknown";let t=rn(e);switch(Z(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 rn(e){let t=Z(e);if(t==="ZodOptional"||t==="ZodNullable"||t==="ZodDefault"){let n=ee(e);return n?rn(n):e}return e}function nt(e,t){if(!e)return;let n=t.split("."),r=e;for(let o of n){if(!r)return;let s=rn(r);if(Z(s)!=="ZodObject")return;r=te(s)[o];}return r}function bs(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 rt(e,t){if(e==="unknown")return null;let n=bs(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 on=Ne(()=>{Ge();});var Rr={};Pn(Rr,{PanelMany:()=>vs,PanelOne:()=>xs,RightPanel:()=>sn});function xs({doc:e,repoName:t,basePath:n,schema:r,columns:o}){if(!e)return jsxRuntime.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=wr(r,o);return jsxRuntime.jsxs("div",{class:"space-y-4",children:[jsxRuntime.jsxs("div",{class:"flex items-center justify-between gap-2",children:[jsxRuntime.jsxs("div",{class:"text-xs text-base-content/60",children:[jsxRuntime.jsx("span",{class:"font-mono",children:t}),jsxRuntime.jsx("span",{class:"opacity-50",children:" \xB7 "}),jsxRuntime.jsx("span",{class:"font-mono break-all",children:s})]}),jsxRuntime.jsx("a",{href:a,class:"btn btn-sm btn-primary",children:"Edit \u2192"})]}),jsxRuntime.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],d=f?rt(f,u):null;return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("dt",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide pt-0.5",children:i}),jsxRuntime.jsx("dd",{class:"min-w-0",children:jsxRuntime.jsx(De,{val:u,mismatch:d})})]})})})]})}function vs({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=wr(a,s);return jsxRuntime.jsxs("div",{class:"space-y-4",children:[jsxRuntime.jsxs("div",{class:"flex items-center justify-between gap-2",children:[jsxRuntime.jsxs("div",{class:"text-xs text-base-content/60",children:[jsxRuntime.jsx("span",{class:"font-mono",children:t}),jsxRuntime.jsx("span",{class:"opacity-50",children:" where "}),jsxRuntime.jsx("span",{class:"font-mono",children:r}),jsxRuntime.jsx("span",{class:"opacity-50",children:" = "}),jsxRuntime.jsx("span",{class:"font-mono break-all",children:o}),jsxRuntime.jsx("span",{class:"opacity-50",children:" \xB7 "}),jsxRuntime.jsxs("span",{children:[e.length," doc",e.length!==1?"s":""]})]}),jsxRuntime.jsx("a",{href:i,class:"btn btn-sm btn-outline",children:"Full view \u2192"})]}),jsxRuntime.jsx("div",{class:"overflow-x-auto rounded-box border border-base-300 bg-base-100",children:jsxRuntime.jsxs("table",{class:"table table-xs w-full",children:[jsxRuntime.jsx("thead",{children:jsxRuntime.jsxs("tr",{class:"bg-base-200/50",children:[s.map((f,d)=>jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:f},d)),jsxRuntime.jsx("th",{})]})}),jsxRuntime.jsx("tbody",{children:e.length===0?jsxRuntime.jsx("tr",{children:jsxRuntime.jsx("td",{colspan:s.length+1,class:"text-center py-10 text-base-content/40",children:"No related documents"})}):e.map((f,d)=>{let g=String(f.docId??f.id??""),x=`${n}/${t}/${encodeURIComponent(g)}/edit`;return jsxRuntime.jsxs("tr",{class:"hover",children:[s.map((m,S)=>{let b=f[m],w=u[m],p=w?rt(w,b):null;return jsxRuntime.jsx("td",{class:"align-top py-1.5",children:jsxRuntime.jsx(De,{val:b,mismatch:p})},S)}),jsxRuntime.jsx("td",{class:"text-right py-1.5",children:jsxRuntime.jsx("a",{href:x,class:"btn btn-xs btn-ghost",children:"Edit"})})]},d)})})]})}),(c.hasPrev||c.hasNext)&&jsxRuntime.jsxs("div",{class:"flex justify-center items-center gap-2",children:[c.hasPrev?jsxRuntime.jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"prev","data-cursor":c.prevCursor,children:"\u2190 Previous"}):jsxRuntime.jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"\u2190 Previous"}),c.hasNext?jsxRuntime.jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"next","data-cursor":c.nextCursor,children:"Next \u2192"}):jsxRuntime.jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"Next \u2192"})]})]})}function wr(e,t){if(!e)return {};let n={};for(let r of t)n[r]=tt(nt(e,r));return n}var sn,an=Ne(()=>{At();on();sn=({basePath:e=""})=>jsxRuntime.jsxs("div",{class:"fixed inset-0 z-[100] hidden pointer-events-none","data-frs-panel-root":true,"data-frs-base-path":e,"aria-hidden":"true",children:[jsxRuntime.jsx("div",{class:"absolute inset-0 bg-black/30 opacity-0 transition-opacity duration-200 pointer-events-auto","data-frs-panel-backdrop":true}),jsxRuntime.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":true,role:"dialog","aria-label":"Relation preview",children:[jsxRuntime.jsxs("header",{class:"flex items-center justify-between px-5 py-3 border-b border-base-300 bg-base-200/40 shrink-0",children:[jsxRuntime.jsx("h2",{class:"font-semibold text-base truncate","data-frs-panel-title":true,children:"Relation"}),jsxRuntime.jsx("button",{type:"button",class:"btn btn-sm btn-ghost btn-circle","data-frs-panel-close":true,"aria-label":"Close panel",children:"\u2715"})]}),jsxRuntime.jsx("div",{class:"flex-1 overflow-auto p-5 text-sm","data-frs-panel-body":true,children:jsxRuntime.jsx("div",{class:"flex items-center justify-center py-12 text-base-content/40",children:jsxRuntime.jsx("span",{class:"loading loading-spinner loading-md"})})})]})]});});var Mr={};Pn(Mr,{DEFAULT_HTML_CSP:()=>vn,securityHeaders:()=>$t});function $t(e={}){let t=e.csp===void 0?vn: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 Fr,jr,vn,It=Ne(()=>{Fr="https://cdn.jsdelivr.net",jr="https://www.gstatic.com",vn=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${Fr} ${jr}`,`style-src 'self' 'unsafe-inline' ${Fr}`,`connect-src 'self' ${jr} 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 ho(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Be(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 Nt(e){let[,t,n]=e;return (t==="in"||t==="array-contains-any")&&Array.isArray(n)&&n.length>30}function $n(e){let[t,n,r]=e;return Nt(e)?ho(r,30).map(s=>[t,n,s]):[e]}function pt(e,t){let n=e;for(let[r,o,s]of t)n=n.where(String(r),o,s);return n}async function In(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 ke(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 Be(e,t).get();if(!t.where.some(Nt)){let d=pt(e,t.where);return d=Be(d,t),d.get()}let i=t.where.map($n),f=Bt(i).map(d=>{let g=pt(e,d);return g=Be(g,t),g});return In(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(Nt)){let f=i.map($n),g=Bt(f).map(x=>{let m=pt(e,x);return m=Be(m,t),m});a.push(...g);}else {let f=pt(e,i);f=Be(f,t),a.push(f);}}return In(a)}function Bt(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=Bt(n),o=[];for(let s of t)for(let a of r)o.push([s,...a]);return o}var qt="preserve";function bo(e){qt=e;}function Zt(){return qt}function xo(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function Kt(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof firestore.Timestamp)return e.toDate();if(xo(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 vo(e){if(typeof e!="object"||e===null)return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ft(e){if(e instanceof firestore.Timestamp)return e.toDate();if(Array.isArray(e))return e.map(t=>ft(t));if(vo(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=ft(r);return t}return e}function V(e){return qt==="normalize"?ft(e):e}function _n(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function pe(e){return e.charAt(0).toUpperCase()+e.slice(1)}function he(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 yt(e,t){let n={...t,limit:t.pageSize+1};t.cursor&&(t.direction==="prev"?n.endBefore=t.cursor:n.startAfter=t.cursor);let o=(await ke(e,n)).docs,s=o.length>t.pageSize,a=s?o.slice(0,t.pageSize):o,c=a.map(u=>V({...u.data(),docId:u.id})),i=t.direction==="prev";return {data:c,nextCursor:i?a.length>0?a[a.length-1]:void 0:s?a[a.length-1]:void 0,prevCursor:i?s?a[0]:void 0:a[0],hasNextPage:i?!!t.cursor:s,hasPrevPage:i?s:!!t.cursor,pageSize:c.length}}async function*Lt(e,t){let n,r=true;for(;r;){let o=await yt(e,{...t,cursor:n,direction:"next"});yield o,r=o.hasNextPage,n=o.nextCursor;}}function Ze(e){if(e===null)return "null";if(e===void 0)return "undefined";if(e instanceof firestore.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 Ut(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 firestore.Timestamp&&t instanceof firestore.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(!Ut(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 firestore.Timestamp||t instanceof firestore.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)||!Ut(e[s],t[s],n))return false;return true}return false}function mt(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],d=a[u];Ut(f,d)||(i[u]={oldValue:f===void 0?null:f,newValue:d===void 0?null:d,type:{old:Ze(f),new:Ze(d)}});}return i}var wo=5;function Ro(e){return e.schemaVersion===2}function Fn(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 So(e){return {historyDocId:e.historyDocId,historyToObjectId:e.historyToObjectId,historySetAt:e.historySetAt,schemaVersion:2,operation:e.operation,meta:e.meta??{},changes:e.changes??{}}}function ko(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 To(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?Fn(r):Ze(t),new:o?Fn(o):Ze(n)}}}function Ao(e){let t=To(e),n=ko(e);return {historyDocId:e.historyDocId,historyToObjectId:e.historyToObjectId,historySetAt:e.historySetAt,schemaVersion:1,operation:"update",meta:n,changes:{[e.field]:t}}}function Co(e,t,n){return Math.abs(e.toMillis()-t.toMillis())<=n}function Oo(e,t){return (e.userId??null)===(t.userId??null)}function jn(e,t={}){let n=t.groupToleranceMs??wo,r=[];for(let o of e){if(Ro(o)){r.push(So(o));continue}let a=Ao(o),c=r[r.length-1];c&&c.schemaVersion===1&&Co(c.historySetAt,a.historySetAt,n)&&Oo(c.meta,a.meta)?Object.assign(c.changes,a.changes):r.push(a);}return r}var Po=7e5;function gt(e){let t=e.ttlOverride??e.config.ttl,r={schemaVersion:2,historyDocId:crypto.randomUUID(),historyToObjectId:e.entityId,historySetAt:firestore.Timestamp.now(),operation:e.operation,meta:e.meta,changes:e.changes};t&&(r.expiresAt=firestore.Timestamp.fromMillis(Date.now()+t.days*24*60*60*1e3));let o=s=>{try{return Buffer.byteLength(JSON.stringify(s,(a,c)=>c instanceof firestore.Timestamp?c.toMillis():c),"utf8")}catch{return 0}};if(o(r.changes)>Po){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 ht(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 bt(e,t){let n=e??{},r={},o=t.meta;if(!o)return r;let s=f=>{if(!f)return;let d=n[f];return d===void 0||d===null?null:String(d)},a=s(o.userId);a!==void 0&&(r.userId=a);let c=s(o.userEmail);c!==void 0&&(r.userEmail=c);let i=s(o.reason);i!==void 0&&(r.reason=i);let u=s(o.comment);if(u!==void 0&&(r.comment=u),o.extras&&o.extras.length>0){let f={},d=false;for(let g of o.extras)g in n&&(f[g]=n[g],d=true);d&&(r.extras=f);}return r}function xt(e){let t=e.meta;if(!t)return [];let n=[];return t.userId&&n.push(t.userId),t.userEmail&&n.push(t.userEmail),t.reason&&n.push(t.reason),t.comment&&n.push(t.comment),t.extras&&n.push(...t.extras),n}var $o="history",Io=50;function Mn(e,t,n){return e(...n).collection(t)}function Do(e){return String(e[e.length-1]??"")}function Hn(e,t,n,r){if(!r?.enabled)return null;let o=r.subcollection??$o;async function s(...f){let d={},g=f,x=f[f.length-1];x!==null&&typeof x=="object"&&!(x instanceof firestore.Timestamp)&&("limit"in x||"cursor"in x||"direction"in x)&&(d=x,g=f.slice(0,-1));let m=Mn(e,o,g),S=d.direction??"desc",b=m.orderBy("historySetAt",S);return d.cursor&&(b=b.startAfter(d.cursor)),d.limit&&d.limit>0&&(b=b.limit(d.limit)),(await b.get()).docs.map(p=>({id:p.id,data:p.data()}))}async function a(...f){let d={},g=f,x=f[f.length-1];x!==null&&typeof x=="object"&&!(x instanceof firestore.Timestamp)&&("limit"in x||"cursor"in x||"direction"in x||"fields"in x||"operations"in x)&&(d=x,g=f.slice(0,-1));let m=d.limit??Io,S=Math.max(m,Math.min(m*8,500)),b=await s(...g,{limit:S,cursor:d.cursor,direction:d.direction??"desc"}),w=jn(b.map(p=>p.data));if(d.fields&&d.fields.length>0){let p=new Set(d.fields);w=w.filter(h=>Object.keys(h.changes).some(l=>p.has(l)));}if(d.operations&&d.operations.length>0){let p=new Set(d.operations);w=w.filter(h=>p.has(h.operation));}return w.slice(0,m)}async function c(...f){let d=f[f.length-1],g={},x,m;return d!==null&&typeof d=="object"&&!(d instanceof firestore.Timestamp)?(g=d,x=f[f.length-2],m=f.slice(0,-2)):(x=d,m=f.slice(0,-1)),a(...m,{...g,fields:[x]})}async function i(...f){let d=f[f.length-1],g={},x,m;return d!==null&&typeof d=="object"&&!(d instanceof firestore.Timestamp)?(g=d,x=f[f.length-2],m=f.slice(0,-2)):(x=d,m=f.slice(0,-1)),a(...m,{...g,operations:[x]})}async function u(...f){let d=f[f.length-1],g=f.slice(0,-1),x=Do(g),m=mt(d.before??{},d.after??{},{include:r.include,exclude:r.exclude,metaFields:xt(r),systemKeys:t});if(d.operation==="update"&&Object.keys(m).length===0)return null;let b={...bt(d.after??d.before??null,r),...d.meta??{}},w=gt({entityId:x,operation:d.operation,changes:m,meta:b,config:r}),p=Mn(e,o,g),h=await ht(p,w,r,{repoName:n,docId:x,before:d.before??null,after:d.after??null});return !h.written||!h.entry?null:{historyDocId:h.entry.historyDocId,historyToObjectId:h.entry.historyToObjectId,historySetAt:h.entry.historySetAt,schemaVersion:2,operation:h.entry.operation,meta:h.entry.meta,changes:h.entry.changes}}return {list:a,raw:s,byField:c,byOperation:i,recordManual:u}}function zn(e){return {count:async(t={})=>{let n=e;return n=he(n,t),(await n.count().get()).data().count},sum:async(t,n={})=>{let r=e;r=he(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=he(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 Nn(e,t,n,r,o,s){let a=()=>new Date;return {create:()=>{let c=e.batch();return {batch:c,set:(...i)=>{let u=i[i.length-1],f=typeof u=="object"&&u!==null&&"merge"in u,d=f?i[i.length-2]:i[i.length-1],g=f?i.slice(0,-2):i.slice(0,-1),x=f?u:{merge:true},m=t(...g),S={...d},b=g[g.length-1];n&&b&&(S[n]=b),r&&(S[r]=m.path),o&&(S[o]=a()),s&&(S[s]=a()),c.set(m,S,x);},update:(...i)=>{let u=i.pop(),d=t(...i),g={...u};s&&(g[s]=a()),c.update(d,g);},delete:(...i)=>{let u=t(...i);c.delete(u);},commit:async()=>{await c.commit();}}}}}var _o=new Set([4,8,10,13,14]);function Vt(e,t){let n=[],r=t.maxAttempts??5;return e.onWriteError(o=>{let s=o?.code;if(o.failedAttempts<r&&s!==void 0&&_o.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 Wt(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 Bn(e,t,n){let r=()=>new Date;return {set:async(o,s={})=>{let a=e.bulkWriter(),c=Vt(a,s);for(let i of o){if(!i)continue;let{docRef:u,data:f,merge:d=true}=i,g={...f};t&&(g[t]=r()),n&&(g[n]=r()),a.set(u,g,{merge:d});}return await a.close(),Wt(c,s)},update:async(o,s={})=>{let a=e.bulkWriter(),c=Vt(a,s);for(let i of o){if(!i)continue;let{docRef:u,data:f}=i,d={...f};n&&(d[n]=r()),a.update(u,d);}return await a.close(),Wt(c,s)},delete:async(o,s={})=>{let a=e.bulkWriter(),c=Vt(a,s);for(let i of o)i&&a.delete(i);return await a.close(),Wt(c,s)}}}function qn(e,t,n,r,o,s){let a=()=>new Date;return {create:async d=>{if(!e)throw new Error("Cannot use create() on collection groups. Use set() with a specific document ID instead.");let g,x,m={...d};if(o&&(m[o]=a()),s&&(m[s]=a()),d[n]){x=d[n],g=e.doc(x);let b=r?{...m,[r]:g.path}:m;await g.set(b);}else {g=await e.add(m),x=g.id;let b={[n]:x};r&&(b[r]=g.path),await g.update(b);}let S=await g.get();return V(S.data())},set:async(...d)=>{let g=d[d.length-1],x=typeof g=="object"&&g!==null&&"merge"in g,m=x?d[d.length-2]:d[d.length-1],S=x?d.slice(0,-2):d.slice(0,-1),b=x?g:{merge:true},w={...m};s&&(w[s]=a());let p=t(...S),h=S[S.length-1];n&&h!=null&&(w[n]=h),r&&(w[r]=p.path),await p.set(w,b);let l=await p.get();return V(l.data())},update:async(...d)=>{let g=d.pop(),x=d,m={...g};s&&(m[s]=a());let S=t(...x);await S.update(m);let b=await S.get();return V(b.data())},delete:async(...d)=>{await t(...d).delete();}}}function Zn(e,t,n,r,o){let s={};return s.byList=async(a,c,i="in",u={})=>{if(c.length===0)return [];let f=[],d=_n(c,30);for(let g of d){let x=e;x=x.where(a,i,g),u.select&&u.select.length>0&&(x=x.select(...u.select.map(S=>String(S)))),(await x.get()).forEach(S=>{let b=V(S.data());f.push(u.returnDoc?{data:b,doc:S}:b);});}return f},t.forEach(a=>{let c=`by${pe(String(a))}`;s[c]=async(...i)=>{let u={},f=i[i.length-1];if(typeof f=="boolean"?(u={returnDoc:f},i=i.slice(0,-1)):typeof f=="object"&&f!==null&&!Array.isArray(f)&&(u=f,i=i.slice(0,-1)),String(a)===o&&(i.length>1||i.length===1&&n!==null)){let w=await r(...i).get();if(!w.exists)return null;let p=V(w.data());return u.returnDoc?{data:p,doc:w}:p}let d=i[0];if(d===void 0)return null;let g=e;g=g.where(String(a),"==",d).limit(1),u.select&&u.select.length>0&&(g=g.select(...u.select.map(b=>String(b))));let x=await g.get();if(x.empty)return null;let m=x.docs[0];if(!m)return null;let S=V(m.data());return u.returnDoc?{data:S,doc:m}:S};}),s}function Kn(e,t,n,r){let o={},s=async(a,c)=>{if(!n||!r||c.length===0)return a;let i=c.map(u=>typeof u=="string"?{key:u}:{key:u.relation,select:u.select});return Promise.all(a.map(async u=>{let f=await Promise.all(i.map(async({key:g,select:x})=>{let m=n[g];if(!m)return [g,void 0];let S=r[m.repo];if(!S)return [g,void 0];let b=u[g];if(b==null)return [g,m.type==="one"?null:[]];let w=x?{select:x}:void 0;try{if(m.type==="one"){let p=`by${pe(m.key)}`,h=typeof S.get?.[p]=="function"?await S.get[p](b,w):null;return [g,h]}else {let p=`by${pe(m.key)}`,h=typeof S.query?.[p]=="function"?await S.query[p](b,w):[];return [g,h]}}catch(p){return console.error(`[include] Error populating "${g}":`,p),[g,m.type==="one"?null:[]]}})),d={};for(let[g,x]of f)g!==void 0&&(d[g]=x);return {...u,populated:d}}))};return t.forEach(a=>{let c=`by${pe(a)}`;o[c]=async(i,u={})=>{let f={...u,where:[[a,"==",i],...u.where??[]]};return (await ke(e,f)).docs.map(g=>V(g.data()))};}),o.by=async a=>(await ke(e,a)).docs.map(i=>V(i.data())),o.getAll=async(a={})=>(await ke(e,a)).docs.map(i=>V(i.data())),o.onSnapshot=(a,c,i)=>he(e,a).onSnapshot(f=>{c(f.docs.map(d=>V(d.data())));},i),o.paginate=async a=>{let{include:c,...i}=a,u=await yt(e,i);if(c&&c.length>0){let f=await s(u.data,c);return {...u,data:f}}return u},o.paginateAll=async function*(a){let{include:c,...i}=a;for await(let u of Lt(e,i))if(c&&c.length>0){let f=await s(u.data,c);yield {...u,data:f};}else yield u;},o}function Ln(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 d=u.sourceKey||i,g=n[d];if(g==null)return [i,u.type==="one"?null:[]];let x=s[i],m=x?{select:x}:void 0;try{if(u.type==="one"){let S=`by${pe(u.key)}`,b=typeof f.get?.[S]=="function"?await f.get[S](g,m):null;return [i,b]}else {let S=`by${pe(u.key)}`,b=typeof f.query?.[S]=="function"?await f.query[S](g,m):[];return [i,b]}}catch(S){return console.error(`[populate] Error populating "${i}":`,S),[i,u.type==="one"?null:[]]}})),c={};for(let[i,u]of a)u!==void 0&&(c[i]=u);return {...n,populated:c}}}}var jo=new Set([4,8,10,13,14]);function Un(e,t,n,r,o,s){let a=()=>new Date;return {backfillKeys:async(i={})=>{let{overwriteCreated:u=false,touchUpdated:f=true,overwritePath:d=false,pageSize:g=300,dryRun:x=false,maxAttempts:m=5,onError:S,onSuccess:b}=i,w=[],p=0,h=0,l=0,k=x?null:e.bulkWriter();k&&(k.onWriteError(R=>{let v=R?.code;if(R.failedAttempts<m&&v!==void 0&&jo.has(v))return true;let C={path:R?.documentRef?.path??"(unknown)",error:R};return w.push(C),S?.(C),false}),b&&k.onWriteResult(R=>b(R.path)));let y;for(;;){let R=t.orderBy(firestore.FieldPath.documentId());y&&(R=R.startAfter(y)),R=R.limit(g);let v=await R.get();if(v.empty)break;for(let C of v.docs){p++;let A=C.data(),T={};if(n&&A[n]==null&&(T[n]=C.id),r&&(d||A[r]==null)&&A[r]!==C.ref.path&&(T[r]=C.ref.path),o&&(u||A[o]==null)&&(T[o]=a()),f&&s&&A[s]==null&&(T[s]=a()),Object.keys(T).length===0){l++;continue}h++,k&&k.set(C.ref,T,{merge:true});}if(v.size<g)break;y=v.docs[v.docs.length-1];}return k&&await k.close(),{scanned:p,written:h,skipped:l,failures:w}}}}function Qn(e,t,n,r,o,s){let a=()=>new Date;return {run:async c=>e.runTransaction(async i=>c({get:async(...f)=>{let d=t(...f),g=await i.get(d);return g.exists?V({...g.data(),docId:g.id}):null},set:(...f)=>{let d=f[f.length-1],g=typeof d=="object"&&d!==null&&"merge"in d,x=g?f[f.length-2]:f[f.length-1],m=g?f.slice(0,-2):f.slice(0,-1),S=g?d:{merge:true},b=t(...m),w={...x},p=m[m.length-1];n&&p&&(w[n]=p),r&&(w[r]=b.path),o&&(w[o]=a()),s&&(w[s]=a()),i.set(b,w,S);},update:(...f)=>{let d=f[f.length-1],g=f.slice(0,-1),x=t(...g),m={...d};s&&(m[s]=a()),i.update(x,m);},delete:(...f)=>{let d=t(...f);i.delete(d);},raw:i}))}}function Vn(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 Mo(e){let t=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(r=>typeof r=="string"),n=e?.history&&typeof e.history=="object"?e.history:void 0;return {schema:e?.schema,_systemKeys:t,_pathKey:e?.pathKey??null,_isGroup:!!e?.isGroup,_createdKey:e?.createdKey??null,_parentKeys:e?.isGroup?Vn(e?.refCb):[],relationalKeys:e?.relationalKeys,_historyConfig:n,_historySubcollection:n?.enabled?n.subcollection??"history":void 0,_collectionPath:typeof e?.path=="string"?e.path:null}}function wt(e,t){let n=Mo(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 Gt(e,t,n={}){let r=t.isGroup?e.collectionGroup(t.path):e.collection(t.path),o=t.isGroup?null:e.collection(t.path),s=(...w)=>t.refCb(e,...w),a=Zn(r,t.foreignKeys,o,s,t.documentKey),c=Kn(r,t.queryKeys,t.relationalKeys,n),i=zn(r),u=qn(o,s,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),f=Nn(e,s,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),d=Qn(e,s,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),g=Bn(e,t.createdKey,t.updatedKey),x=Un(e,r,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),m=Ln(t,n),S=t.history,b=S?.enabled?Hn(s,[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(w=>typeof w=="string"),t.path??"(unknown)",S):null;return {ref:r,documentRef:s,get:a,query:c,aggregate:i,...u,batch:f,transaction:d,bulk:g,system:x,...m,...b?{history:b}:{},_historySubcollection:b?S?.subcollection??"history":void 0,_historyConfig:S,schema:t.schema,relationalKeys:t.relationalKeys,_systemKeys:[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(w=>typeof w=="string"),_pathKey:t.pathKey??null,_isGroup:!!t.isGroup,_parentKeys:t.isGroup?Vn(t.refCb):[],_createdKey:t.createdKey??null}}var Ho="history";function zo(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(r=>typeof r=="string");return {historyConfig:t,systemKeys:n,isGroup:!!e?.isGroup,collectionPath:typeof e?.path=="string"?e.path:null}}function No(e){return {historyConfig:e._historyConfig??(typeof e.history=="object"&&e.history!==null&&"enabled"in e.history?e.history:void 0),systemKeys:e._systemKeys??[],isGroup:!!e._isGroup,collectionPath:e.ref?.path??null}}function Bo(e,t){return t?`${t}/{docId}`:(console.warn(`[HistoryTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function Wn(e,t){let{onDocumentWritten:n}=t.deps,r={},o=e?.rawMapping,s=o?Object.entries(o).map(([a,c])=>[a,zo(c)]):Object.entries(e).map(([a,c])=>[a,No(c)]);for(let[a,c]of s){let i=c.historyConfig;if(!i?.enabled)continue;let u=i.subcollection??Ho,f=i.ttl??t.defaults?.ttl,d=t.repos?.[a],g;if(c.isGroup){if(!d?.triggerPath){console.warn(`[HistoryTriggers] Skipping collection-group repo "${a}". Provide a triggerPath in the history triggers repos override.`);continue}g=d.triggerPath;}else g=d?.triggerPath??Bo(a,c.collectionPath);if(!g)continue;let x=c.systemKeys,m=x[0]??"docId",S=xt(i);r[`${a}_onHistory`]=n(g,async b=>{try{let w=b.data?.before?.data(),p=b.data?.after?.data(),h;if(!w&&p)h="create";else if(w&&!p)h="delete";else if(w&&p)h="update";else return;let l=String(p?.[m]??w?.[m]??b.params?.docId??b.data?.after?.id??b.data?.before?.id??"");if(!l)return;let k=mt(w??{},p??{},{include:i.include,exclude:i.exclude,metaFields:S,systemKeys:x});if(h==="update"&&Object.keys(k).length===0)return;let y=bt(p??w??null,i),R=gt({entityId:l,operation:h,changes:k,meta:y,config:i,ttlOverride:f}),v=b.data?.after?.ref??b.data?.before?.ref;if(!v)return;let C=v.collection(u);await ht(C,R,i,{repoName:a,docId:l,before:w??null,after:p??null});}catch(w){console.error(`[HistoryTriggers] Failed to record history for "${a}":`,w);}});}return r}function qo(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 Zo(e){let t=e.path??e.url??"/",n=t.indexOf("?");return n===-1?t:t.slice(0,n)}var fe=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}=qo(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=Zo(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((d,g)=>{a[d]=decodeURIComponent(f[g+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 ce(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 Gn(e){if(typeof e=="string")return e;if(Array.isArray(e)){let t=e[0];return typeof t=="string"?t:void 0}}function Ke(e){return !!e&&typeof e=="object"&&e.__authExtension===true}Ge();var be="__sync_version";var Qo=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function Vo(e){let t=e,n=false;for(;;){let r=Z(t);if(!Qo.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(n=true);let o=ee(t);if(!o)break;t=o;}return {inner:t,nullable:n}}var Wo={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function tr(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:d,nullable:g}=Vo(u),x=Z(d),m=r||g;if(x==="ZodObject"){let p=te(d);tr(p,t,f,m,o,s,a,c);continue}let S=Wo[x]??"json",b=f===a||i===a,w=s[f]??s[i]??f;c.push({name:w,sqlType:t.mapType(S),nullable:b?false:m,isPrimaryKey:b});}}function Rt(e,t,n={}){let{primaryKey:r,exclude:o=[],columnMap:s={}}=n,a=new Set(o),c=te(e),i=[];return tr(c,t,"",false,a,s,r,i),i.some(u=>u.name===be)||i.push({name:be,sqlType:t.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),i}function nr(e){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 t=e;return JSON.stringify({lat:t.latitude,lng:t.longitude})}return Array.isArray(e)?JSON.stringify(e.map(nr)):e}var Go=32,Jo=5e3;function rr(e,t,n,r=new WeakSet,o=0){if(o>Go){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>=Jo)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)?rr(a,c,n,r,o+1):n[c]=nr(a);}r.delete(e);}function Je(e,t){let n=new Set(t?.exclude),r=t?.columnMap??{},o={};rr(e,"",o);let s={};for(let[a,c]of Object.entries(o)){if(n.has(a))continue;let i=a.split("__")[0];if(i!==a&&n.has(i))continue;let u=r[a]??(a.includes("__")?r[a.split("__").pop()]:void 0)??a;s[u]=c;}return s}function ye(e,t,n){return `<!DOCTYPE html>
|
|
1
|
+
'use strict';var jsxRuntime=require('hono/jsx/jsx-runtime'),firestore=require('firebase-admin/firestore'),crypto=require('crypto'),zod=require('zod'),server=require('hono/jsx/dom/server'),zodToOpenapi=require('@asteasolutions/zod-to-openapi'),hono=require('hono'),nodeServer=require('@hono/node-server'),async_hooks=require('async_hooks');var Ht=Object.defineProperty;var po=Object.getOwnPropertyDescriptor;var fo=Object.getOwnPropertyNames;var yo=Object.prototype.hasOwnProperty;var Ne=(e,t)=>()=>(e&&(t=e(e=0)),t);var Pn=(e,t)=>{for(var n in t)Ht(e,n,{get:t[n],enumerable:true});},mo=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of fo(t))!yo.call(e,o)&&o!==n&&Ht(e,o,{get:()=>t[o],enumerable:!(r=po(t,o))||r.enumerable});return e};var go=e=>mo(Ht({},"__esModule",{value:true}),e);function Z(e){let t=e,n=t._zod?.def?.type;if(n)return Uo[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=t._def?.typeName;return r||""}function ee(e){let t=e;if(t._zod?.def?.innerType)return t._zod.def.innerType;if(t._def?.innerType)return t._def.innerType}function Le(e){let t=e,n=t._zod?.def?.in;if(n)return n;if(t._def?.schema)return t._def.schema}function Xn(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}function Yn(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 te(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 Ue(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 Qe(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 Ve(e){let t=e;return Array.isArray(t._zod?.def?.values)?t._zod.def.values[0]:t._def?.value}function We(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 er(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 Uo,Ge=Ne(()=>{Uo={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 xr({val:e}){return jsxRuntime.jsx("span",{class:"text-sm text-base-content/80 font-mono tabular-nums whitespace-nowrap",children:e.toLocaleString()})}function ys({message:e}){return jsxRuntime.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:jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",class:"size-3.5",children:jsxRuntime.jsx("path",{d:"M12 2 1 22h22L12 2zm0 6 7.5 13h-15L12 8zm-1 4v4h2v-4h-2zm0 5v2h2v-2h-2z"})})})}function De({val:e,mismatch:t}){let n=nn(e);return t?jsxRuntime.jsxs("span",{class:"inline-flex items-start gap-0.5",children:[n,jsxRuntime.jsx(ys,{message:t})]}):n}function nn(e){if(e==null)return jsxRuntime.jsx("span",{class:"opacity-30 italic text-xs",children:"\u2014"});if(typeof e=="boolean")return e?jsxRuntime.jsx("span",{class:"badge badge-success badge-sm",children:"true"}):jsxRuntime.jsx("span",{class:"badge badge-error badge-sm",children:"false"});if(e instanceof Date)return jsxRuntime.jsx(xr,{val:e});if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")return jsxRuntime.jsx(xr,{val:e.toDate()});if(typeof e=="number")return jsxRuntime.jsx("span",{class:"text-sm font-mono tabular-nums",children:String(e)});if(Array.isArray(e))return e.length===0?jsxRuntime.jsx("span",{class:"text-xs text-base-content/30",children:"[]"}):jsxRuntime.jsxs("ul",{class:"list-none p-0 m-0 space-y-0.5 text-xs",children:[e.slice(0,8).map((n,r)=>jsxRuntime.jsx("li",{class:"break-all",children:nn(n)},r)),e.length>8&&jsxRuntime.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?jsxRuntime.jsx("span",{class:"text-xs text-base-content/30",children:"{}"}):jsxRuntime.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])=>jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("dt",{class:"text-base-content/50 font-semibold whitespace-nowrap",children:r}),jsxRuntime.jsx("dd",{class:"break-all",children:nn(o)})]})),n.length>8&&jsxRuntime.jsxs("dt",{class:"col-span-2 text-base-content/40 italic",children:["+",n.length-8," more\u2026"]})]})}let t=String(e);return jsxRuntime.jsx("span",{class:"text-sm break-all",children:t})}var At=Ne(()=>{});function tt(e){if(!e)return "unknown";let t=rn(e);switch(Z(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 rn(e){let t=Z(e);if(t==="ZodOptional"||t==="ZodNullable"||t==="ZodDefault"){let n=ee(e);return n?rn(n):e}return e}function nt(e,t){if(!e)return;let n=t.split("."),r=e;for(let o of n){if(!r)return;let s=rn(r);if(Z(s)!=="ZodObject")return;r=te(s)[o];}return r}function bs(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 rt(e,t){if(e==="unknown")return null;let n=bs(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 on=Ne(()=>{Ge();});var Rr={};Pn(Rr,{PanelMany:()=>vs,PanelOne:()=>xs,RightPanel:()=>sn});function xs({doc:e,repoName:t,basePath:n,schema:r,columns:o}){if(!e)return jsxRuntime.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=wr(r,o);return jsxRuntime.jsxs("div",{class:"space-y-4",children:[jsxRuntime.jsxs("div",{class:"flex items-center justify-between gap-2",children:[jsxRuntime.jsxs("div",{class:"text-xs text-base-content/60",children:[jsxRuntime.jsx("span",{class:"font-mono",children:t}),jsxRuntime.jsx("span",{class:"opacity-50",children:" \xB7 "}),jsxRuntime.jsx("span",{class:"font-mono break-all",children:s})]}),jsxRuntime.jsx("a",{href:a,class:"btn btn-sm btn-primary",children:"Edit \u2192"})]}),jsxRuntime.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],d=f?rt(f,u):null;return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("dt",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide pt-0.5",children:i}),jsxRuntime.jsx("dd",{class:"min-w-0",children:jsxRuntime.jsx(De,{val:u,mismatch:d})})]})})})]})}function vs({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=wr(a,s);return jsxRuntime.jsxs("div",{class:"space-y-4",children:[jsxRuntime.jsxs("div",{class:"flex items-center justify-between gap-2",children:[jsxRuntime.jsxs("div",{class:"text-xs text-base-content/60",children:[jsxRuntime.jsx("span",{class:"font-mono",children:t}),jsxRuntime.jsx("span",{class:"opacity-50",children:" where "}),jsxRuntime.jsx("span",{class:"font-mono",children:r}),jsxRuntime.jsx("span",{class:"opacity-50",children:" = "}),jsxRuntime.jsx("span",{class:"font-mono break-all",children:o}),jsxRuntime.jsx("span",{class:"opacity-50",children:" \xB7 "}),jsxRuntime.jsxs("span",{children:[e.length," doc",e.length!==1?"s":""]})]}),jsxRuntime.jsx("a",{href:i,class:"btn btn-sm btn-outline",children:"Full view \u2192"})]}),jsxRuntime.jsx("div",{class:"overflow-x-auto rounded-box border border-base-300 bg-base-100",children:jsxRuntime.jsxs("table",{class:"table table-xs w-full",children:[jsxRuntime.jsx("thead",{children:jsxRuntime.jsxs("tr",{class:"bg-base-200/50",children:[s.map((f,d)=>jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:f},d)),jsxRuntime.jsx("th",{})]})}),jsxRuntime.jsx("tbody",{children:e.length===0?jsxRuntime.jsx("tr",{children:jsxRuntime.jsx("td",{colspan:s.length+1,class:"text-center py-10 text-base-content/40",children:"No related documents"})}):e.map((f,d)=>{let g=String(f.docId??f.id??""),x=`${n}/${t}/${encodeURIComponent(g)}/edit`;return jsxRuntime.jsxs("tr",{class:"hover",children:[s.map((m,S)=>{let b=f[m],w=u[m],p=w?rt(w,b):null;return jsxRuntime.jsx("td",{class:"align-top py-1.5",children:jsxRuntime.jsx(De,{val:b,mismatch:p})},S)}),jsxRuntime.jsx("td",{class:"text-right py-1.5",children:jsxRuntime.jsx("a",{href:x,class:"btn btn-xs btn-ghost",children:"Edit"})})]},d)})})]})}),(c.hasPrev||c.hasNext)&&jsxRuntime.jsxs("div",{class:"flex justify-center items-center gap-2",children:[c.hasPrev?jsxRuntime.jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"prev","data-cursor":c.prevCursor,children:"\u2190 Previous"}):jsxRuntime.jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"\u2190 Previous"}),c.hasNext?jsxRuntime.jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"next","data-cursor":c.nextCursor,children:"Next \u2192"}):jsxRuntime.jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"Next \u2192"})]})]})}function wr(e,t){if(!e)return {};let n={};for(let r of t)n[r]=tt(nt(e,r));return n}var sn,an=Ne(()=>{At();on();sn=({basePath:e=""})=>jsxRuntime.jsxs("div",{class:"fixed inset-0 z-[100] hidden pointer-events-none","data-frs-panel-root":true,"data-frs-base-path":e,"aria-hidden":"true",children:[jsxRuntime.jsx("div",{class:"absolute inset-0 bg-black/30 opacity-0 transition-opacity duration-200 pointer-events-auto","data-frs-panel-backdrop":true}),jsxRuntime.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":true,role:"dialog","aria-label":"Relation preview",children:[jsxRuntime.jsxs("header",{class:"flex items-center justify-between px-5 py-3 border-b border-base-300 bg-base-200/40 shrink-0",children:[jsxRuntime.jsx("h2",{class:"font-semibold text-base truncate","data-frs-panel-title":true,children:"Relation"}),jsxRuntime.jsx("button",{type:"button",class:"btn btn-sm btn-ghost btn-circle","data-frs-panel-close":true,"aria-label":"Close panel",children:"\u2715"})]}),jsxRuntime.jsx("div",{class:"flex-1 overflow-auto p-5 text-sm","data-frs-panel-body":true,children:jsxRuntime.jsx("div",{class:"flex items-center justify-center py-12 text-base-content/40",children:jsxRuntime.jsx("span",{class:"loading loading-spinner loading-md"})})})]})]});});var Mr={};Pn(Mr,{DEFAULT_HTML_CSP:()=>vn,securityHeaders:()=>$t});function $t(e={}){let t=e.csp===void 0?vn: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 Fr,jr,vn,It=Ne(()=>{Fr="https://cdn.jsdelivr.net",jr="https://www.gstatic.com",vn=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${Fr} ${jr}`,`style-src 'self' 'unsafe-inline' ${Fr}`,`connect-src 'self' ${jr} 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 ho(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Be(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 Nt(e){let[,t,n]=e;return (t==="in"||t==="array-contains-any")&&Array.isArray(n)&&n.length>30}function $n(e){let[t,n,r]=e;return Nt(e)?ho(r,30).map(s=>[t,n,s]):[e]}function pt(e,t){let n=e;for(let[r,o,s]of t)n=n.where(String(r),o,s);return n}async function In(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 ke(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 Be(e,t).get();if(!t.where.some(Nt)){let d=pt(e,t.where);return d=Be(d,t),d.get()}let i=t.where.map($n),f=Bt(i).map(d=>{let g=pt(e,d);return g=Be(g,t),g});return In(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(Nt)){let f=i.map($n),g=Bt(f).map(x=>{let m=pt(e,x);return m=Be(m,t),m});a.push(...g);}else {let f=pt(e,i);f=Be(f,t),a.push(f);}}return In(a)}function Bt(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=Bt(n),o=[];for(let s of t)for(let a of r)o.push([s,...a]);return o}var qt="preserve";function bo(e){qt=e;}function Zt(){return qt}function xo(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function Kt(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof firestore.Timestamp)return e.toDate();if(xo(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 vo(e){if(typeof e!="object"||e===null)return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ft(e){if(e instanceof firestore.Timestamp)return e.toDate();if(Array.isArray(e))return e.map(t=>ft(t));if(vo(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=ft(r);return t}return e}function V(e){return qt==="normalize"?ft(e):e}function _n(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function pe(e){return e.charAt(0).toUpperCase()+e.slice(1)}function he(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 yt(e,t){let n={...t,limit:t.pageSize+1};t.cursor&&(t.direction==="prev"?n.endBefore=t.cursor:n.startAfter=t.cursor);let o=(await ke(e,n)).docs,s=o.length>t.pageSize,a=s?o.slice(0,t.pageSize):o,c=a.map(u=>V({...u.data(),docId:u.id})),i=t.direction==="prev";return {data:c,nextCursor:i?a.length>0?a[a.length-1]:void 0:s?a[a.length-1]:void 0,prevCursor:i?s?a[0]:void 0:a[0],hasNextPage:i?!!t.cursor:s,hasPrevPage:i?s:!!t.cursor,pageSize:c.length}}async function*Lt(e,t){let n,r=true;for(;r;){let o=await yt(e,{...t,cursor:n,direction:"next"});yield o,r=o.hasNextPage,n=o.nextCursor;}}function Ze(e){if(e===null)return "null";if(e===void 0)return "undefined";if(e instanceof firestore.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 Ut(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 firestore.Timestamp&&t instanceof firestore.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(!Ut(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 firestore.Timestamp||t instanceof firestore.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)||!Ut(e[s],t[s],n))return false;return true}return false}function mt(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],d=a[u];Ut(f,d)||(i[u]={oldValue:f===void 0?null:f,newValue:d===void 0?null:d,type:{old:Ze(f),new:Ze(d)}});}return i}var wo=5;function Ro(e){return e.schemaVersion===2}function Fn(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 So(e){return {historyDocId:e.historyDocId,historyToObjectId:e.historyToObjectId,historySetAt:e.historySetAt,schemaVersion:2,operation:e.operation,meta:e.meta??{},changes:e.changes??{}}}function ko(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 To(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?Fn(r):Ze(t),new:o?Fn(o):Ze(n)}}}function Ao(e){let t=To(e),n=ko(e);return {historyDocId:e.historyDocId,historyToObjectId:e.historyToObjectId,historySetAt:e.historySetAt,schemaVersion:1,operation:"update",meta:n,changes:{[e.field]:t}}}function Co(e,t,n){return Math.abs(e.toMillis()-t.toMillis())<=n}function Oo(e,t){return (e.userId??null)===(t.userId??null)}function jn(e,t={}){let n=t.groupToleranceMs??wo,r=[];for(let o of e){if(Ro(o)){r.push(So(o));continue}let a=Ao(o),c=r[r.length-1];c&&c.schemaVersion===1&&Co(c.historySetAt,a.historySetAt,n)&&Oo(c.meta,a.meta)?Object.assign(c.changes,a.changes):r.push(a);}return r}var Po=7e5;function gt(e){let t=e.ttlOverride??e.config.ttl,r={schemaVersion:2,historyDocId:crypto.randomUUID(),historyToObjectId:e.entityId,historySetAt:firestore.Timestamp.now(),operation:e.operation,meta:e.meta,changes:e.changes};t&&(r.expiresAt=firestore.Timestamp.fromMillis(Date.now()+t.days*24*60*60*1e3));let o=s=>{try{return Buffer.byteLength(JSON.stringify(s,(a,c)=>c instanceof firestore.Timestamp?c.toMillis():c),"utf8")}catch{return 0}};if(o(r.changes)>Po){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 ht(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 bt(e,t){let n=e??{},r={},o=t.meta;if(!o)return r;let s=f=>{if(!f)return;let d=n[f];return d===void 0||d===null?null:String(d)},a=s(o.userId);a!==void 0&&(r.userId=a);let c=s(o.userEmail);c!==void 0&&(r.userEmail=c);let i=s(o.reason);i!==void 0&&(r.reason=i);let u=s(o.comment);if(u!==void 0&&(r.comment=u),o.extras&&o.extras.length>0){let f={},d=false;for(let g of o.extras)g in n&&(f[g]=n[g],d=true);d&&(r.extras=f);}return r}function xt(e){let t=e.meta;if(!t)return [];let n=[];return t.userId&&n.push(t.userId),t.userEmail&&n.push(t.userEmail),t.reason&&n.push(t.reason),t.comment&&n.push(t.comment),t.extras&&n.push(...t.extras),n}var $o="history",Io=50;function Mn(e,t,n){return e(...n).collection(t)}function Do(e){return String(e[e.length-1]??"")}function zn(e,t,n,r){if(!r?.enabled)return null;let o=r.subcollection??$o;async function s(...f){let d={},g=f,x=f[f.length-1];x!==null&&typeof x=="object"&&!(x instanceof firestore.Timestamp)&&("limit"in x||"cursor"in x||"direction"in x)&&(d=x,g=f.slice(0,-1));let m=Mn(e,o,g),S=d.direction??"desc",b=m.orderBy("historySetAt",S);return d.cursor&&(b=b.startAfter(d.cursor)),d.limit&&d.limit>0&&(b=b.limit(d.limit)),(await b.get()).docs.map(p=>({id:p.id,data:p.data()}))}async function a(...f){let d={},g=f,x=f[f.length-1];x!==null&&typeof x=="object"&&!(x instanceof firestore.Timestamp)&&("limit"in x||"cursor"in x||"direction"in x||"fields"in x||"operations"in x)&&(d=x,g=f.slice(0,-1));let m=d.limit??Io,S=Math.max(m,Math.min(m*8,500)),b=await s(...g,{limit:S,cursor:d.cursor,direction:d.direction??"desc"}),w=jn(b.map(p=>p.data));if(d.fields&&d.fields.length>0){let p=new Set(d.fields);w=w.filter(h=>Object.keys(h.changes).some(l=>p.has(l)));}if(d.operations&&d.operations.length>0){let p=new Set(d.operations);w=w.filter(h=>p.has(h.operation));}return w.slice(0,m)}async function c(...f){let d=f[f.length-1],g={},x,m;return d!==null&&typeof d=="object"&&!(d instanceof firestore.Timestamp)?(g=d,x=f[f.length-2],m=f.slice(0,-2)):(x=d,m=f.slice(0,-1)),a(...m,{...g,fields:[x]})}async function i(...f){let d=f[f.length-1],g={},x,m;return d!==null&&typeof d=="object"&&!(d instanceof firestore.Timestamp)?(g=d,x=f[f.length-2],m=f.slice(0,-2)):(x=d,m=f.slice(0,-1)),a(...m,{...g,operations:[x]})}async function u(...f){let d=f[f.length-1],g=f.slice(0,-1),x=Do(g),m=mt(d.before??{},d.after??{},{include:r.include,exclude:r.exclude,metaFields:xt(r),systemKeys:t});if(d.operation==="update"&&Object.keys(m).length===0)return null;let b={...bt(d.after??d.before??null,r),...d.meta??{}},w=gt({entityId:x,operation:d.operation,changes:m,meta:b,config:r}),p=Mn(e,o,g),h=await ht(p,w,r,{repoName:n,docId:x,before:d.before??null,after:d.after??null});return !h.written||!h.entry?null:{historyDocId:h.entry.historyDocId,historyToObjectId:h.entry.historyToObjectId,historySetAt:h.entry.historySetAt,schemaVersion:2,operation:h.entry.operation,meta:h.entry.meta,changes:h.entry.changes}}return {list:a,raw:s,byField:c,byOperation:i,recordManual:u}}function Hn(e){return {count:async(t={})=>{let n=e;return n=he(n,t),(await n.count().get()).data().count},sum:async(t,n={})=>{let r=e;r=he(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=he(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 Nn(e,t,n,r,o,s){let a=()=>new Date;return {create:()=>{let c=e.batch();return {batch:c,set:(...i)=>{let u=i[i.length-1],f=typeof u=="object"&&u!==null&&"merge"in u,d=f?i[i.length-2]:i[i.length-1],g=f?i.slice(0,-2):i.slice(0,-1),x=f?u:{merge:true},m=t(...g),S={...d},b=g[g.length-1];n&&b&&(S[n]=b),r&&(S[r]=m.path),o&&(S[o]=a()),s&&(S[s]=a()),c.set(m,S,x);},update:(...i)=>{let u=i.pop(),d=t(...i),g={...u};s&&(g[s]=a()),c.update(d,g);},delete:(...i)=>{let u=t(...i);c.delete(u);},commit:async()=>{await c.commit();}}}}}var _o=new Set([4,8,10,13,14]);function Vt(e,t){let n=[],r=t.maxAttempts??5;return e.onWriteError(o=>{let s=o?.code;if(o.failedAttempts<r&&s!==void 0&&_o.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 Wt(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 Bn(e,t,n){let r=()=>new Date;return {set:async(o,s={})=>{let a=e.bulkWriter(),c=Vt(a,s);for(let i of o){if(!i)continue;let{docRef:u,data:f,merge:d=true}=i,g={...f};t&&(g[t]=r()),n&&(g[n]=r()),a.set(u,g,{merge:d});}return await a.close(),Wt(c,s)},update:async(o,s={})=>{let a=e.bulkWriter(),c=Vt(a,s);for(let i of o){if(!i)continue;let{docRef:u,data:f}=i,d={...f};n&&(d[n]=r()),a.update(u,d);}return await a.close(),Wt(c,s)},delete:async(o,s={})=>{let a=e.bulkWriter(),c=Vt(a,s);for(let i of o)i&&a.delete(i);return await a.close(),Wt(c,s)}}}function qn(e,t,n,r,o,s){let a=()=>new Date;return {create:async d=>{if(!e)throw new Error("Cannot use create() on collection groups. Use set() with a specific document ID instead.");let g,x,m={...d};if(o&&(m[o]=a()),s&&(m[s]=a()),d[n]){x=d[n],g=e.doc(x);let b=r?{...m,[r]:g.path}:m;await g.set(b);}else {g=await e.add(m),x=g.id;let b={[n]:x};r&&(b[r]=g.path),await g.update(b);}let S=await g.get();return V(S.data())},set:async(...d)=>{let g=d[d.length-1],x=typeof g=="object"&&g!==null&&"merge"in g,m=x?d[d.length-2]:d[d.length-1],S=x?d.slice(0,-2):d.slice(0,-1),b=x?g:{merge:true},w={...m};s&&(w[s]=a());let p=t(...S),h=S[S.length-1];n&&h!=null&&(w[n]=h),r&&(w[r]=p.path),await p.set(w,b);let l=await p.get();return V(l.data())},update:async(...d)=>{let g=d.pop(),x=d,m={...g};s&&(m[s]=a());let S=t(...x);await S.update(m);let b=await S.get();return V(b.data())},delete:async(...d)=>{await t(...d).delete();}}}function Zn(e,t,n,r,o){let s={};return s.byList=async(a,c,i="in",u={})=>{if(c.length===0)return [];let f=[],d=_n(c,30);for(let g of d){let x=e;x=x.where(a,i,g),u.select&&u.select.length>0&&(x=x.select(...u.select.map(S=>String(S)))),(await x.get()).forEach(S=>{let b=V(S.data());f.push(u.returnDoc?{data:b,doc:S}:b);});}return f},t.forEach(a=>{let c=`by${pe(String(a))}`;s[c]=async(...i)=>{let u={},f=i[i.length-1];if(typeof f=="boolean"?(u={returnDoc:f},i=i.slice(0,-1)):typeof f=="object"&&f!==null&&!Array.isArray(f)&&(u=f,i=i.slice(0,-1)),String(a)===o&&(i.length>1||i.length===1&&n!==null)){let w=await r(...i).get();if(!w.exists)return null;let p=V(w.data());return u.returnDoc?{data:p,doc:w}:p}let d=i[0];if(d===void 0)return null;let g=e;g=g.where(String(a),"==",d).limit(1),u.select&&u.select.length>0&&(g=g.select(...u.select.map(b=>String(b))));let x=await g.get();if(x.empty)return null;let m=x.docs[0];if(!m)return null;let S=V(m.data());return u.returnDoc?{data:S,doc:m}:S};}),s}function Kn(e,t,n,r){let o={},s=async(a,c)=>{if(!n||!r||c.length===0)return a;let i=c.map(u=>typeof u=="string"?{key:u}:{key:u.relation,select:u.select});return Promise.all(a.map(async u=>{let f=await Promise.all(i.map(async({key:g,select:x})=>{let m=n[g];if(!m)return [g,void 0];let S=r[m.repo];if(!S)return [g,void 0];let b=u[g];if(b==null)return [g,m.type==="one"?null:[]];let w=x?{select:x}:void 0;try{if(m.type==="one"){let p=`by${pe(m.key)}`,h=typeof S.get?.[p]=="function"?await S.get[p](b,w):null;return [g,h]}else {let p=`by${pe(m.key)}`,h=typeof S.query?.[p]=="function"?await S.query[p](b,w):[];return [g,h]}}catch(p){return console.error(`[include] Error populating "${g}":`,p),[g,m.type==="one"?null:[]]}})),d={};for(let[g,x]of f)g!==void 0&&(d[g]=x);return {...u,populated:d}}))};return t.forEach(a=>{let c=`by${pe(a)}`;o[c]=async(i,u={})=>{let f={...u,where:[[a,"==",i],...u.where??[]]};return (await ke(e,f)).docs.map(g=>V(g.data()))};}),o.by=async a=>(await ke(e,a)).docs.map(i=>V(i.data())),o.getAll=async(a={})=>(await ke(e,a)).docs.map(i=>V(i.data())),o.onSnapshot=(a,c,i)=>he(e,a).onSnapshot(f=>{c(f.docs.map(d=>V(d.data())));},i),o.paginate=async a=>{let{include:c,...i}=a,u=await yt(e,i);if(c&&c.length>0){let f=await s(u.data,c);return {...u,data:f}}return u},o.paginateAll=async function*(a){let{include:c,...i}=a;for await(let u of Lt(e,i))if(c&&c.length>0){let f=await s(u.data,c);yield {...u,data:f};}else yield u;},o}function Ln(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 d=u.sourceKey||i,g=n[d];if(g==null)return [i,u.type==="one"?null:[]];let x=s[i],m=x?{select:x}:void 0;try{if(u.type==="one"){let S=`by${pe(u.key)}`,b=typeof f.get?.[S]=="function"?await f.get[S](g,m):null;return [i,b]}else {let S=`by${pe(u.key)}`,b=typeof f.query?.[S]=="function"?await f.query[S](g,m):[];return [i,b]}}catch(S){return console.error(`[populate] Error populating "${i}":`,S),[i,u.type==="one"?null:[]]}})),c={};for(let[i,u]of a)u!==void 0&&(c[i]=u);return {...n,populated:c}}}}var jo=new Set([4,8,10,13,14]);function Un(e,t,n,r,o,s){let a=()=>new Date;return {backfillKeys:async(i={})=>{let{overwriteCreated:u=false,touchUpdated:f=true,overwritePath:d=false,pageSize:g=300,dryRun:x=false,maxAttempts:m=5,onError:S,onSuccess:b}=i,w=[],p=0,h=0,l=0,k=x?null:e.bulkWriter();k&&(k.onWriteError(R=>{let v=R?.code;if(R.failedAttempts<m&&v!==void 0&&jo.has(v))return true;let C={path:R?.documentRef?.path??"(unknown)",error:R};return w.push(C),S?.(C),false}),b&&k.onWriteResult(R=>b(R.path)));let y;for(;;){let R=t.orderBy(firestore.FieldPath.documentId());y&&(R=R.startAfter(y)),R=R.limit(g);let v=await R.get();if(v.empty)break;for(let C of v.docs){p++;let A=C.data(),T={};if(n&&A[n]==null&&(T[n]=C.id),r&&(d||A[r]==null)&&A[r]!==C.ref.path&&(T[r]=C.ref.path),o&&(u||A[o]==null)&&(T[o]=a()),f&&s&&A[s]==null&&(T[s]=a()),Object.keys(T).length===0){l++;continue}h++,k&&k.set(C.ref,T,{merge:true});}if(v.size<g)break;y=v.docs[v.docs.length-1];}return k&&await k.close(),{scanned:p,written:h,skipped:l,failures:w}}}}function Qn(e,t,n,r,o,s){let a=()=>new Date;return {run:async c=>e.runTransaction(async i=>c({get:async(...f)=>{let d=t(...f),g=await i.get(d);return g.exists?V({...g.data(),docId:g.id}):null},set:(...f)=>{let d=f[f.length-1],g=typeof d=="object"&&d!==null&&"merge"in d,x=g?f[f.length-2]:f[f.length-1],m=g?f.slice(0,-2):f.slice(0,-1),S=g?d:{merge:true},b=t(...m),w={...x},p=m[m.length-1];n&&p&&(w[n]=p),r&&(w[r]=b.path),o&&(w[o]=a()),s&&(w[s]=a()),i.set(b,w,S);},update:(...f)=>{let d=f[f.length-1],g=f.slice(0,-1),x=t(...g),m={...d};s&&(m[s]=a()),i.update(x,m);},delete:(...f)=>{let d=t(...f);i.delete(d);},raw:i}))}}function Vn(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 Mo(e){let t=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(r=>typeof r=="string"),n=e?.history&&typeof e.history=="object"?e.history:void 0;return {schema:e?.schema,_systemKeys:t,_pathKey:e?.pathKey??null,_isGroup:!!e?.isGroup,_createdKey:e?.createdKey??null,_parentKeys:e?.isGroup?Vn(e?.refCb):[],relationalKeys:e?.relationalKeys,_historyConfig:n,_historySubcollection:n?.enabled?n.subcollection??"history":void 0,_collectionPath:typeof e?.path=="string"?e.path:null}}function wt(e,t){let n=Mo(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 Gt(e,t,n={}){let r=t.isGroup?e.collectionGroup(t.path):e.collection(t.path),o=t.isGroup?null:e.collection(t.path),s=(...w)=>t.refCb(e,...w),a=Zn(r,t.foreignKeys,o,s,t.documentKey),c=Kn(r,t.queryKeys,t.relationalKeys,n),i=Hn(r),u=qn(o,s,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),f=Nn(e,s,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),d=Qn(e,s,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),g=Bn(e,t.createdKey,t.updatedKey),x=Un(e,r,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),m=Ln(t,n),S=t.history,b=S?.enabled?zn(s,[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(w=>typeof w=="string"),t.path??"(unknown)",S):null;return {ref:r,documentRef:s,get:a,query:c,aggregate:i,...u,batch:f,transaction:d,bulk:g,system:x,...m,...b?{history:b}:{},_historySubcollection:b?S?.subcollection??"history":void 0,_historyConfig:S,schema:t.schema,relationalKeys:t.relationalKeys,_systemKeys:[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(w=>typeof w=="string"),_pathKey:t.pathKey??null,_isGroup:!!t.isGroup,_parentKeys:t.isGroup?Vn(t.refCb):[],_createdKey:t.createdKey??null}}var zo="history";function Ho(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(r=>typeof r=="string");return {historyConfig:t,systemKeys:n,isGroup:!!e?.isGroup,collectionPath:typeof e?.path=="string"?e.path:null}}function No(e){return {historyConfig:e._historyConfig??(typeof e.history=="object"&&e.history!==null&&"enabled"in e.history?e.history:void 0),systemKeys:e._systemKeys??[],isGroup:!!e._isGroup,collectionPath:e.ref?.path??null}}function Bo(e,t){return t?`${t}/{docId}`:(console.warn(`[HistoryTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function Wn(e,t){let{onDocumentWritten:n}=t.deps,r={},o=e?.rawMapping,s=o?Object.entries(o).map(([a,c])=>[a,Ho(c)]):Object.entries(e).map(([a,c])=>[a,No(c)]);for(let[a,c]of s){let i=c.historyConfig;if(!i?.enabled)continue;let u=i.subcollection??zo,f=i.ttl??t.defaults?.ttl,d=t.repos?.[a],g;if(c.isGroup){if(!d?.triggerPath){console.warn(`[HistoryTriggers] Skipping collection-group repo "${a}". Provide a triggerPath in the history triggers repos override.`);continue}g=d.triggerPath;}else g=d?.triggerPath??Bo(a,c.collectionPath);if(!g)continue;let x=c.systemKeys,m=x[0]??"docId",S=xt(i);r[`${a}_onHistory`]=n(g,async b=>{try{let w=b.data?.before?.data(),p=b.data?.after?.data(),h;if(!w&&p)h="create";else if(w&&!p)h="delete";else if(w&&p)h="update";else return;let l=String(p?.[m]??w?.[m]??b.params?.docId??b.data?.after?.id??b.data?.before?.id??"");if(!l)return;let k=mt(w??{},p??{},{include:i.include,exclude:i.exclude,metaFields:S,systemKeys:x});if(h==="update"&&Object.keys(k).length===0)return;let y=bt(p??w??null,i),R=gt({entityId:l,operation:h,changes:k,meta:y,config:i,ttlOverride:f}),v=b.data?.after?.ref??b.data?.before?.ref;if(!v)return;let C=v.collection(u);await ht(C,R,i,{repoName:a,docId:l,before:w??null,after:p??null});}catch(w){console.error(`[HistoryTriggers] Failed to record history for "${a}":`,w);}});}return r}function qo(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 Zo(e){let t=e.path??e.url??"/",n=t.indexOf("?");return n===-1?t:t.slice(0,n)}var fe=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}=qo(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=Zo(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((d,g)=>{a[d]=decodeURIComponent(f[g+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 ce(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 Gn(e){if(typeof e=="string")return e;if(Array.isArray(e)){let t=e[0];return typeof t=="string"?t:void 0}}function Ke(e){return !!e&&typeof e=="object"&&e.__authExtension===true}Ge();var be="__sync_version";var Qo=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function Vo(e){let t=e,n=false;for(;;){let r=Z(t);if(!Qo.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(n=true);let o=ee(t);if(!o)break;t=o;}return {inner:t,nullable:n}}var Wo={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function tr(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:d,nullable:g}=Vo(u),x=Z(d),m=r||g;if(x==="ZodObject"){let p=te(d);tr(p,t,f,m,o,s,a,c);continue}let S=Wo[x]??"json",b=f===a||i===a,w=s[f]??s[i]??f;c.push({name:w,sqlType:t.mapType(S),nullable:b?false:m,isPrimaryKey:b});}}function Rt(e,t,n={}){let{primaryKey:r,exclude:o=[],columnMap:s={}}=n,a=new Set(o),c=te(e),i=[];return tr(c,t,"",false,a,s,r,i),i.some(u=>u.name===be)||i.push({name:be,sqlType:t.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),i}function nr(e){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 t=e;return JSON.stringify({lat:t.latitude,lng:t.longitude})}return Array.isArray(e)?JSON.stringify(e.map(nr)):e}var Go=32,Jo=5e3;function rr(e,t,n,r=new WeakSet,o=0){if(o>Go){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>=Jo)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)?rr(a,c,n,r,o+1):n[c]=nr(a);}r.delete(e);}function Je(e,t){let n=new Set(t?.exclude),r=t?.columnMap??{},o={};rr(e,"",o);let s={};for(let[a,c]of Object.entries(o)){if(n.has(a))continue;let i=a.split("__")[0];if(i!==a&&n.has(i))continue;let u=r[a]??(a.includes("__")?r[a.split("__").pop()]:void 0)??a;s[u]=c;}return s}function ye(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>
|
|
@@ -58,7 +58,7 @@ ${n}
|
|
|
58
58
|
<form method="POST" action="${S}/${b.name}/force-sync">
|
|
59
59
|
<button type="submit" class="btn btn-primary">Start Force Sync</button>
|
|
60
60
|
</form>
|
|
61
|
-
</div>`);me(m,w);}),g.post(`${i}/:repoName/force-sync`,async(x,m)=>{let S=ce(x,i),b=d.find(A=>A.name===x.params.repoName);if(!b){$e(m,{error:`Unknown repo: ${x.params.repoName}`},404);return}let w=b.repo.ref;if(!w){$e(m,{error:`No collection reference for "${b.name}"`},400);return}let p=0,h=0,l=[],k=500,y=w.limit(k),R=null;try{for(;;){let P=await(R?y.startAfter(R):y).get();if(P.empty)break;for(let E of P.docs){let I=E.data(),O=String(I[b.documentKey]??E.id),$=Je(I,{exclude:b.repoCfg?.exclude,columnMap:b.repoCfg?.columnMap});try{await r({operation:"UPSERT",repoName:b.name,docId:O,data:$,timestamp:new Date().toISOString()}),p++;}catch(F){h++;let
|
|
61
|
+
</div>`);me(m,w);}),g.post(`${i}/:repoName/force-sync`,async(x,m)=>{let S=ce(x,i),b=d.find(A=>A.name===x.params.repoName);if(!b){$e(m,{error:`Unknown repo: ${x.params.repoName}`},404);return}let w=b.repo.ref;if(!w){$e(m,{error:`No collection reference for "${b.name}"`},400);return}let p=0,h=0,l=[],k=500,y=w.limit(k),R=null;try{for(;;){let P=await(R?y.startAfter(R):y).get();if(P.empty)break;for(let E of P.docs){let I=E.data(),O=String(I[b.documentKey]??E.id),$=Je(I,{exclude:b.repoCfg?.exclude,columnMap:b.repoCfg?.columnMap});try{await r({operation:"UPSERT",repoName:b.name,docId:O,data:$,timestamp:new Date().toISOString()}),p++;}catch(F){h++;let z=F?.message??String(F);console.error(`[ForceSync:${b.name}] doc=${O} failed:`,F),l.length<5&&l.push(`${O}: ${z}`);}}if(R=P.docs[P.docs.length-1],P.docs.length<k)break}let A=n.get(b.name);A&&await A.flush();}catch(A){if(St(x)){$e(m,{error:A?.message??String(A),synced:p,errors:h},500);return}me(m,ye(`Force Sync: ${b.name}`,S,`<div class="card">
|
|
62
62
|
<p class="badge badge-err">Error: ${A?.message??String(A)}</p>
|
|
63
63
|
<p>Synced ${p} docs before failure (${h} errors).</p>
|
|
64
64
|
</div>`),500);return}if(St(x)){$e(m,{repo:b.name,table:b.tableName,synced:p,errors:h,...l.length>0&&{errorSamples:l}});return}let v=l.length>0?`<details style="margin-top:1rem"><summary>First ${l.length} error(s)</summary>
|
|
@@ -97,7 +97,7 @@ ${n}
|
|
|
97
97
|
<div class="form-control mb-3 ${n}">
|
|
98
98
|
<label for="${r}" class="label pb-1">
|
|
99
99
|
<span class="label-text font-medium">
|
|
100
|
-
${
|
|
100
|
+
${H(e.label)}
|
|
101
101
|
<span class="text-base-content/40 text-xs ml-1">(nullable)</span>
|
|
102
102
|
</span>
|
|
103
103
|
</label>
|
|
@@ -111,41 +111,41 @@ ${n}
|
|
|
111
111
|
<label class="label cursor-pointer justify-start gap-3">
|
|
112
112
|
<input type="checkbox" id="${r}" name="${o}" value="true"${c==="true"?" checked":""} class="checkbox checkbox-primary checkbox-sm">
|
|
113
113
|
<span class="label-text font-medium">
|
|
114
|
-
${
|
|
114
|
+
${H(e.label)}${e.required?' <span class="text-error">*</span>':""}
|
|
115
115
|
</span>
|
|
116
116
|
</label>
|
|
117
117
|
</div>`;case "select":u=`<select id="${r}" name="${o}"${s}${a?' disabled style="opacity:0.35"':""} class="select select-bordered select-sm w-full">
|
|
118
118
|
${e.required&&!e.nullable?"":'<option value="">\u2014 optional \u2014</option>'}
|
|
119
|
-
${(e.options??[]).map(f=>`<option value="${
|
|
119
|
+
${(e.options??[]).map(f=>`<option value="${H(f)}"${c===f?" selected":""}>${H(f)}</option>`).join(`
|
|
120
120
|
`)}
|
|
121
121
|
</select>`;break;case "textarea":if(e.arrayElementType)return ss(e,t);if(e.nested&&e.nested.length>0){let f=e.nested.map(d=>Xe(d,t+1)).join(`
|
|
122
122
|
`);return `
|
|
123
123
|
<fieldset class="fieldset border border-base-300 rounded-box p-3 mb-3 ${n}">
|
|
124
124
|
<legend class="fieldset-legend text-xs font-semibold text-base-content/60 px-1">
|
|
125
|
-
${
|
|
125
|
+
${H(e.label)}${e.required?' <span class="text-error">*</span>':""}
|
|
126
126
|
</legend>
|
|
127
127
|
${f}
|
|
128
128
|
</fieldset>`}u=`<textarea id="${r}" name="${o}"${s} rows="3"${a?' disabled style="opacity:0.35"':""}
|
|
129
129
|
data-json
|
|
130
130
|
class="textarea textarea-bordered textarea-sm w-full font-mono text-xs"
|
|
131
|
-
placeholder="${
|
|
132
|
-
value="${
|
|
131
|
+
placeholder="${H(e.hint??"JSON")}">${H(c)}</textarea>`;break;default:u=`<input type="${e.type}" id="${r}" name="${o}"${s}${a?' disabled style="opacity:0.35"':""}
|
|
132
|
+
value="${H(c)}"
|
|
133
133
|
class="input input-bordered input-sm w-full"${e.hint==="email"?' autocomplete="email"':e.hint==="url"?' autocomplete="url"':""}>`;}return `
|
|
134
134
|
<div class="form-control mb-3 ${n}">
|
|
135
135
|
<label for="${r}" class="label pb-1">
|
|
136
136
|
<span class="label-text font-medium">
|
|
137
|
-
${
|
|
138
|
-
${e.hint?`<span class="text-base-content/40 text-xs ml-1">(${
|
|
137
|
+
${H(e.label)}${e.required?' <span class="text-error">*</span>':""}
|
|
138
|
+
${e.hint?`<span class="text-base-content/40 text-xs ml-1">(${H(e.hint)})</span>`:""}
|
|
139
139
|
</span>
|
|
140
140
|
</label>
|
|
141
141
|
<div class="flex items-center gap-2">
|
|
142
142
|
<div class="flex-1 min-w-0">${u}</div>
|
|
143
143
|
${i}
|
|
144
144
|
</div>
|
|
145
|
-
</div>`}function
|
|
145
|
+
</div>`}function H(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ss(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=>mr(e,f??{})).join(`
|
|
146
146
|
`):a.map(f=>yr(e,f)).join(`
|
|
147
147
|
`),i=s?mr(e,{}):yr(e,""),u=e.nullable?`<span class="flex items-center gap-1 mt-2">
|
|
148
|
-
<input type="hidden" id="${r}__isnull" name="${
|
|
148
|
+
<input type="hidden" id="${r}__isnull" name="${H(e.name)}__isnull" value="${o?"1":""}">
|
|
149
149
|
<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">
|
|
150
150
|
<input type="checkbox" class="checkbox checkbox-xs" ${o?"checked":""}
|
|
151
151
|
onchange="(function(cb){
|
|
@@ -159,11 +159,11 @@ ${n}
|
|
|
159
159
|
</label>
|
|
160
160
|
</span>`:"";return `
|
|
161
161
|
<fieldset class="fieldset border border-base-300 rounded-box p-3 mb-3 ${n}"
|
|
162
|
-
data-frs-array="${
|
|
162
|
+
data-frs-array="${H(e.name)}" data-frs-array-type="${H(e.arrayElementType??"text")}">
|
|
163
163
|
<legend class="fieldset-legend text-xs font-semibold text-base-content/60 px-1">
|
|
164
|
-
${
|
|
164
|
+
${H(e.label)}${e.required?' <span class="text-error">*</span>':""}
|
|
165
165
|
</legend>
|
|
166
|
-
<input type="hidden" id="${r}" name="${
|
|
166
|
+
<input type="hidden" id="${r}" name="${H(e.name)}" value="${H(JSON.stringify(a))}"${o?" disabled":""}>
|
|
167
167
|
<div data-frs-array-items${o?' style="opacity:0.35"':""}>
|
|
168
168
|
${c}
|
|
169
169
|
</div>
|
|
@@ -172,11 +172,11 @@ ${n}
|
|
|
172
172
|
${u}
|
|
173
173
|
</fieldset>`}function yr(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">
|
|
174
174
|
<option value="">\u2014</option>
|
|
175
|
-
${(e.arrayElementOptions??[]).map(o=>`<option value="${
|
|
175
|
+
${(e.arrayElementOptions??[]).map(o=>`<option value="${H(o)}"${n===o?" selected":""}>${H(o)}</option>`).join("")}
|
|
176
176
|
</select>`;break;case "checkbox":r=`<label class="flex items-center gap-2 flex-1 cursor-pointer">
|
|
177
177
|
<input type="checkbox" data-frs-val class="checkbox checkbox-sm checkbox-primary"${n==="true"?" checked":""}>
|
|
178
178
|
<span class="text-sm">true</span>
|
|
179
|
-
</label>`;break;case "number":r=`<input type="number" data-frs-val value="${
|
|
179
|
+
</label>`;break;case "number":r=`<input type="number" data-frs-val value="${H(n)}" class="input input-bordered input-sm flex-1">`;break;case "datetime-local":r=`<input type="datetime-local" data-frs-val value="${H(n)}" class="input input-bordered input-sm flex-1">`;break;default:r=`<input type="text" data-frs-val value="${H(n)}" class="input input-bordered input-sm flex-1">`;}return `<div class="flex items-center gap-2 mb-2" data-frs-array-item>
|
|
180
180
|
${r}
|
|
181
181
|
<button type="button" class="btn btn-xs btn-ghost text-error" data-frs-array-rm>×</button>
|
|
182
182
|
</div>`}function mr(e,t){return `<div class="border border-base-200 rounded p-3 mb-2" data-frs-array-item>
|
|
@@ -185,35 +185,35 @@ ${n}
|
|
|
185
185
|
</div>
|
|
186
186
|
${(e.arrayElementFields??[]).map(o=>{let s=t[o.name],a=s==null?"":typeof s=="object"?JSON.stringify(s):String(s);switch(o.type){case "checkbox":return `<div class="form-control mb-2">
|
|
187
187
|
<label class="label cursor-pointer justify-start gap-3">
|
|
188
|
-
<input type="checkbox" data-frs-key="${
|
|
189
|
-
<span class="label-text text-sm">${
|
|
188
|
+
<input type="checkbox" data-frs-key="${H(o.name)}" class="checkbox checkbox-sm checkbox-primary"${a==="true"?" checked":""}>
|
|
189
|
+
<span class="label-text text-sm">${H(o.label)}</span>
|
|
190
190
|
</label>
|
|
191
191
|
</div>`;case "select":return `<div class="form-control mb-2">
|
|
192
|
-
<label class="label pb-1"><span class="label-text text-sm">${
|
|
193
|
-
<select data-frs-key="${
|
|
192
|
+
<label class="label pb-1"><span class="label-text text-sm">${H(o.label)}</span></label>
|
|
193
|
+
<select data-frs-key="${H(o.name)}" class="select select-bordered select-sm w-full">
|
|
194
194
|
${o.required?"":'<option value="">\u2014</option>'}
|
|
195
|
-
${(o.options??[]).map(c=>`<option value="${
|
|
195
|
+
${(o.options??[]).map(c=>`<option value="${H(c)}"${a===c?" selected":""}>${H(c)}</option>`).join("")}
|
|
196
196
|
</select>
|
|
197
197
|
</div>`;case "number":return `<div class="form-control mb-2">
|
|
198
|
-
<label class="label pb-1"><span class="label-text text-sm">${
|
|
199
|
-
<input type="number" data-frs-key="${
|
|
198
|
+
<label class="label pb-1"><span class="label-text text-sm">${H(o.label)}</span></label>
|
|
199
|
+
<input type="number" data-frs-key="${H(o.name)}" value="${H(a)}" class="input input-bordered input-sm w-full">
|
|
200
200
|
</div>`;case "datetime-local":return `<div class="form-control mb-2">
|
|
201
|
-
<label class="label pb-1"><span class="label-text text-sm">${
|
|
202
|
-
<input type="datetime-local" data-frs-key="${
|
|
201
|
+
<label class="label pb-1"><span class="label-text text-sm">${H(o.label)}</span></label>
|
|
202
|
+
<input type="datetime-local" data-frs-key="${H(o.name)}" value="${H(a)}" class="input input-bordered input-sm w-full">
|
|
203
203
|
</div>`;case "textarea":return `<div class="form-control mb-2">
|
|
204
|
-
<label class="label pb-1"><span class="label-text text-sm">${
|
|
205
|
-
<textarea data-frs-key="${
|
|
204
|
+
<label class="label pb-1"><span class="label-text text-sm">${H(o.label)}</span></label>
|
|
205
|
+
<textarea data-frs-key="${H(o.name)}" rows="2" class="textarea textarea-bordered textarea-sm w-full font-mono text-xs" placeholder="JSON">${H(a)}</textarea>
|
|
206
206
|
</div>`;default:return `<div class="form-control mb-2">
|
|
207
|
-
<label class="label pb-1"><span class="label-text text-sm">${
|
|
208
|
-
<input type="text" data-frs-key="${
|
|
207
|
+
<label class="label pb-1"><span class="label-text text-sm">${H(o.label)}</span></label>
|
|
208
|
+
<input type="text" data-frs-key="${H(o.name)}" value="${H(a)}" class="input input-bordered input-sm w-full">
|
|
209
209
|
</div>`}}).join(`
|
|
210
210
|
`)}
|
|
211
211
|
</div>`}function xe(e,t,n,r="Save"){let o=e.map(s=>Xe(s)).join(`
|
|
212
212
|
`);return `
|
|
213
|
-
<form action="${
|
|
213
|
+
<form action="${H(t)}" method="${n}" novalidate data-frs-form>
|
|
214
214
|
${o}
|
|
215
215
|
<div class="flex gap-2 mt-4 pt-4 border-t border-base-200">
|
|
216
|
-
<button type="submit" class="btn btn-primary btn-sm">${
|
|
216
|
+
<button type="submit" class="btn btn-primary btn-sm">${H(r)}</button>
|
|
217
217
|
<button type="button" class="btn btn-ghost btn-sm" onclick="history.back()">Cancel</button>
|
|
218
218
|
</div>
|
|
219
219
|
</form>`}var as=new Set(["<","<=",">",">=","!="]),is=new Set(["array-contains","array-contains-any"]);function Xt(e){return e==="desc"?"DESCENDING":"ASCENDING"}function cs(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function ls(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(is.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(as.has(i.op)){if(a.has(i.field))continue;a.add(i.field);let u=o?.field===i.field?Xt(o.dir):"ASCENDING";s.push({fieldPath:i.field,order:u});}if(o&&!a.has(o.field)&&s.push({fieldPath:o.field,order:Xt(o.dir)}),s.length===1&&n)return ps(e,t,s[0]);let c=o&&s.some(i=>i.fieldPath===o.field)?Xt(o.dir):"ASCENDING";return s.push({fieldPath:"__name__",order:c}),ds(e,t,n,s)}function ds(e,t,n,r,o="(default)"){let s=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,a=[...tn(1,s),...Tt(2,n?2:1)];for(let u of r)a.push(...gr(3,hr(u)));let c=o==="(default)"?"-default-":o,i=encodeURIComponent(br(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${c}/indexes?create_composite=${i}`}function us(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function Yt(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function en(e,t){return e<<3|t}function tn(e,t){let n=Array.from(new TextEncoder().encode(t));return [en(e,2),...Yt(n.length),...n]}function Tt(e,t){return [en(e,0),...Yt(t)]}function gr(e,t){return [en(e,2),...Yt(t.length),...t]}function hr(e){let t=[...tn(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...Tt(3,1)):t.push(...Tt(2,e.order==="DESCENDING"?2:1)),t}function br(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 ps(e,t,n,r="(default)"){let o=`projects/${e}/databases/${r}/collectionGroups/${t}/fields/${n.fieldPath}`,s=[...tn(1,o),...Tt(2,2),...gr(3,hr(n))],a=r==="(default)"?"-default-":r,c=encodeURIComponent(br(s));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${c}`}function fs(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 Te(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Ye(e,t){let n=e??{},r=Te(e),o;if(r&&(o=n.message?us(n.message):void 0,!o)){let s=fs(t.ref);if(s){let a=cs(t.path);o=ls(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}}At();var vr=`// \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
|
|
@@ -1138,7 +1138,7 @@ function initColumnReorder(table) {
|
|
|
1138
1138
|
});
|
|
1139
1139
|
});
|
|
1140
1140
|
}
|
|
1141
|
-
`;function et(){return jsxRuntime.jsx("script",{dangerouslySetInnerHTML:{__html:vr}})}an();function ve(e){return "<!DOCTYPE html>"+server.renderToString(e)}var Ss=["corporate","silk","dark"],ks=()=>jsxRuntime.jsxs("div",{class:"dropdown dropdown-end","data-frs-theme-switcher":true,children:[jsxRuntime.jsxs("button",{type:"button",tabIndex:0,class:"btn btn-sm btn-ghost text-neutral-content gap-1.5","aria-label":"Switch theme",children:[jsxRuntime.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:[jsxRuntime.jsx("circle",{cx:"12",cy:"12",r:"4"}),jsxRuntime.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"})]}),jsxRuntime.jsx("span",{class:"text-xs hidden sm:inline","data-frs-theme-current":true,children:"Theme"})]}),jsxRuntime.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:Ss.map(e=>jsxRuntime.jsx("li",{children:jsxRuntime.jsxs("button",{type:"button","data-frs-theme":e,class:"capitalize justify-between",children:[jsxRuntime.jsx("span",{children:e}),jsxRuntime.jsx("span",{class:"hidden text-primary","data-frs-theme-check":e,children:"\u2713"})]})},e))})]}),we=({opts:e,children:t})=>{let{title:n,breadcrumb:r,flash:o,basePath:s="/"}=e;return jsxRuntime.jsxs("html",{lang:"en","data-theme":"corporate",children:[jsxRuntime.jsxs("head",{children:[jsxRuntime.jsx("meta",{charset:"UTF-8"}),jsxRuntime.jsx("meta",{name:"viewport",content:"width=device-width, initial-scale=1"}),jsxRuntime.jsxs("title",{children:[n," \u2014 FRS Admin"]}),jsxRuntime.jsx("script",{dangerouslySetInnerHTML:{__html:"(function(){try{var t=localStorage.getItem('frs-admin-theme');if(t){document.documentElement.setAttribute('data-theme',t);}}catch(_){}})();"}}),jsxRuntime.jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/themes.css",rel:"stylesheet",type:"text/css"}),jsxRuntime.jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/daisyui.css",rel:"stylesheet",type:"text/css"}),jsxRuntime.jsx("script",{src:"https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"})]}),jsxRuntime.jsxs("body",{class:"bg-base-200/50 min-h-screen flex flex-col",children:[jsxRuntime.jsxs("div",{class:"navbar bg-neutral text-neutral-content shadow-sm sticky top-0 z-50 px-6",children:[jsxRuntime.jsx("div",{class:"flex-1",children:jsxRuntime.jsx("a",{href:s,class:"font-bold text-lg tracking-tight hover:opacity-80 transition-opacity",children:"FRS Admin"})}),jsxRuntime.jsx("div",{class:"flex-none",children:jsxRuntime.jsx(ks,{})})]}),jsxRuntime.jsxs("main",{class:"px-6 py-8 w-full flex-1",children:[r&&r.length>0&&jsxRuntime.jsx("div",{class:"text-sm breadcrumbs mb-4",children:jsxRuntime.jsx("ul",{children:r.map((a,c)=>a.href?jsxRuntime.jsx("li",{children:jsxRuntime.jsx("a",{href:a.href,children:a.label})},c):jsxRuntime.jsx("li",{class:"text-base-content/60",children:a.label},c))})}),jsxRuntime.jsx("h1",{class:"text-2xl font-bold mb-6",children:n}),o&&jsxRuntime.jsxs("div",{role:"alert",class:`alert ${o.type==="success"?"alert-success":o.type==="warning"?"alert-warning":"alert-error"} mb-6`,children:[jsxRuntime.jsx("span",{class:"flex-1",children:o.message}),o.action&&jsxRuntime.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]}),jsxRuntime.jsx(sn,{basePath:s}),jsxRuntime.jsx(et,{})]})]})};function cn(e,t){return ve(jsxRuntime.jsx(we,{opts:t,children:jsxRuntime.jsx("div",{dangerouslySetInnerHTML:{__html:e}})}))}function ln(e,t){return ve(jsxRuntime.jsx(we,{opts:{title:"Repositories",basePath:t},children:e.length===0?jsxRuntime.jsxs("div",{class:"text-center py-20 text-base-content/50",children:[jsxRuntime.jsx("p",{class:"text-lg font-medium mb-1",children:"No repositories configured"}),jsxRuntime.jsx("p",{class:"text-sm",children:"Add a repository to your FRS config to get started."})]}):jsxRuntime.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=>jsxRuntime.jsx("a",{href:`${t}/${n.name}`,class:"card bg-base-100 border border-base-300 hover:shadow-md no-underline transition-shadow",children:jsxRuntime.jsxs("div",{class:"card-body p-5",children:[jsxRuntime.jsx("h2",{class:"card-title text-sm font-semibold",children:n.name}),jsxRuntime.jsx("p",{class:"text-xs text-base-content/50 font-mono",children:n.path})]})},n.name))})}))}var kr=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],Ts=[{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"}],As=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function Cs(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return Ts;case "ZodBoolean":return kr;case "ZodArray":return As;default:return kr}}var Re="__null__";function Os(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="${Re}"]');if(!o){o=document.createElement('option');o.value='${Re}';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='${Re}';i.readOnly=true;}i.style.opacity='0.55';}else{i.style.opacity='';if(i.tagName==='SELECT'){var o2=i.querySelector('option[value="${Re}"][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!=='${Re}')?i.dataset._prev:'';}}})(this)`}function Es(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 jsxRuntime.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:[jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",checked:t,onchange:Os(e)}),jsxRuntime.jsx("span",{children:"\u2205"})]})}function Ps({col:e,active:t}){let n=t?.value??"",r=n===Re,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 jsxRuntime.jsxs("div",{class:"flex flex-wrap items-center gap-1 w-full",children:[jsxRuntime.jsx("input",{type:"hidden",id:o,name:`fv_${e.name}`,value:n}),e.enumValues.map(u=>jsxRuntime.jsxs("label",{class:"flex items-center gap-1 text-xs border border-base-300 rounded px-2 cursor-pointer hover:bg-base-200",children:[jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",value:u,checked:c.has(u),"data-enum-group":i,onchange:Es(o,i)}),jsxRuntime.jsx("span",{children:u})]},u))]})}return jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsxRuntime.jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),e.enumValues.map(c=>jsxRuntime.jsx("option",{value:c,selected:n===c,children:c},c)),e.nullable&&jsxRuntime.jsx("option",{value:Re,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsxRuntime.jsx(ot,{inputId:o,active:r})]})}if(e.zodType==="ZodBoolean")return jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsxRuntime.jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),jsxRuntime.jsx("option",{value:"true",selected:n==="true",children:"true"}),jsxRuntime.jsx("option",{value:"false",selected:n==="false",children:"false"}),e.nullable&&jsxRuntime.jsx("option",{value:Re,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsxRuntime.jsx(ot,{inputId:o,active:r})]});if(e.zodType==="ZodArray"){let c=t?.op==="array-contains-any";return jsxRuntime.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"?jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.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&&jsxRuntime.jsx(ot,{inputId:o,active:r})]}):e.zodType==="ZodDate"?jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.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&&jsxRuntime.jsx(ot,{inputId:o,active:r})]}):jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.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&&jsxRuntime.jsx(ot,{inputId:o,active:r})]})}function dn({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 jsxRuntime.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:[jsxRuntime.jsxs("summary",{class:"collapse-title text-sm font-medium py-2 min-h-0",children:["Filters",s&&jsxRuntime.jsxs("span",{class:"badge badge-primary badge-sm ml-2",children:[n.length," active"]})]}),jsxRuntime.jsx("div",{class:"collapse-content pb-4 pt-2",children:jsxRuntime.jsxs("form",{method:"get",action:e,children:[jsxRuntime.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=Cs(i.zodType),f=o[i.name],d=f?.op??u[0].value;return jsxRuntime.jsxs("div",{class:"flex flex-col gap-1.5",children:[jsxRuntime.jsx("label",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:i.name}),jsxRuntime.jsxs("div",{class:"flex gap-1.5",children:[u.length>1?jsxRuntime.jsx("select",{name:`fo_${i.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:u.map(g=>jsxRuntime.jsx("option",{value:g.value,selected:g.value===d,children:g.label},g.value))}):jsxRuntime.jsx("input",{type:"hidden",name:`fo_${i.name}`,value:u[0].value}),jsxRuntime.jsx(Ps,{col:i,active:f})]})]},i.name)})}),jsxRuntime.jsxs("div",{class:"flex flex-wrap gap-2 mt-4 pt-3 border-t border-base-200 items-center",children:[jsxRuntime.jsx("button",{type:"submit",class:"btn btn-sm btn-primary",children:"Apply"}),s&&jsxRuntime.jsx("a",{href:e,class:"btn btn-sm btn-ghost",children:"Clear"}),a&&jsxRuntime.jsxs("span",{class:"text-xs text-warning ml-auto flex items-center gap-1",children:[jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-4 w-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:jsxRuntime.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 un(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 ve(jsxRuntime.jsx(we,{opts:{title:a,breadcrumb:c,basePath:o,flash:s},children:jsxRuntime.jsx("div",{class:"card bg-base-100 border border-base-300",children:jsxRuntime.jsx("div",{class:"card-body p-6",children:jsxRuntime.jsx("div",{dangerouslySetInnerHTML:{__html:t}})})})}))}At();on();function pn(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 Tr(e,t,n,r,o){let s=pn(e,r,o);return s.set("cursor",t),s.set("dir",n),`?${s.toString()}`}function $s(e,t,n,r){let o=pn(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 Is(e,t,n){return `?${pn(t,n,e).toString()}`}function fn(e,t,n,r,o,s,a=[],c=[],i=false,u=[],f,d,g,x,m,S,b,w=false){let p=`${r}/${e}`,h=`${p}/create`,l={};if(b)for(let T of n)l[T]=tt(nt(b,T));let k=(S??[]).filter(T=>true),y=k.length>0,R=i,v=R||y,C=k.map(T=>{let P=nt(b,T),E=tt(P),I=a.find(O=>O.name===T);return {name:T,type:E,enumValues:I?.enumValues??null,nullable:I?.nullable??false}}),A=[];return b&&(A=ae(b).filter(P=>k.includes(P.name))),ve(jsxRuntime.jsxs(we,{opts:{title:e,breadcrumb:[{label:"Repositories",href:r},{label:e}],basePath:r,flash:s},children:[a.length>0&&jsxRuntime.jsx(dn,{action:p,columnMeta:a,activeFilters:c,isGroup:x}),g&&jsxRuntime.jsxs("div",{role:"alert",class:`alert ${g.type==="index"?"alert-warning":"alert-error"} mb-6 shadow-sm`,children:[jsxRuntime.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:g.type==="index"?jsxRuntime.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"}):jsxRuntime.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"})}),jsxRuntime.jsxs("div",{class:"flex-1",children:[jsxRuntime.jsx("h3",{class:"font-bold",children:g.type==="index"?"Composite index required":"Query failed"}),jsxRuntime.jsx("div",{class:"text-sm",children:g.message})]}),g.indexUrl&&jsxRuntime.jsx("a",{href:g.indexUrl,target:"_blank",rel:"noopener noreferrer",class:"btn btn-sm btn-outline",children:"Create Index \u2192"})]}),jsxRuntime.jsxs("div",{class:"flex flex-wrap justify-between items-center mb-4 gap-3","data-frs-toolbar":true,children:[jsxRuntime.jsxs("div",{class:"flex items-center gap-3",children:[jsxRuntime.jsxs("span",{class:"text-sm text-base-content/60",children:[t.length,typeof m=="number"&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[" ","of"," ",jsxRuntime.jsx("span",{class:"font-semibold text-base-content/80",children:m})]})," ","document",(typeof m=="number"?m:t.length)!==1&&"s"]}),jsxRuntime.jsxs("div",{class:"flex items-center gap-1.5 text-sm text-base-content/60",children:[jsxRuntime.jsx("span",{children:"Rows"}),jsxRuntime.jsx("div",{class:"join",children:[10,25,50,100].map(T=>jsxRuntime.jsx("a",{href:Is(T,c,f),class:`join-item btn btn-xs ${d===T?"btn-active btn-primary":"btn-outline"}`,children:T},T))})]})]}),jsxRuntime.jsxs("div",{class:"flex gap-2",children:[jsxRuntime.jsx("form",{method:"post",action:`${p}/_bulk/backfill`,onsubmit:"return confirm('Backfill entire repository? This will scan all documents and fill missing system keys.')",children:jsxRuntime.jsx("button",{type:"submit",class:"btn btn-outline btn-sm",children:"Backfill"})}),jsxRuntime.jsx("a",{href:h,class:"btn btn-primary btn-sm",children:"+ New"})]})]}),v&&jsxRuntime.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 m=="number"?String(m):"","data-frs-page-size":String(d??t.length),"data-frs-allow-delete":R?"1":"0","data-frs-allow-update":y?"1":"0","data-frs-fields":JSON.stringify(C),"data-frs-filters":JSON.stringify(c),children:[jsxRuntime.jsxs("div",{class:"flex-1 text-sm",children:[jsxRuntime.jsx("span",{"data-frs-bulk-summary":true,children:"0 selected"}),typeof m=="number"&&m>t.length&&jsxRuntime.jsxs("button",{type:"button",class:"ml-3 link text-sm hidden","data-frs-bulk-select-all":true,children:["Select all ",m," matching documents"]}),jsxRuntime.jsxs("span",{class:"hidden ml-3 italic","data-frs-bulk-all-active":true,children:["All ",m??"?"," matching documents are selected."," ",jsxRuntime.jsx("button",{type:"button",class:"link","data-frs-bulk-clear":true,children:"Clear selection"})]})]}),jsxRuntime.jsxs("div",{class:"flex gap-2",children:[y&&jsxRuntime.jsx("button",{type:"button",class:"btn btn-sm btn-outline","data-frs-bulk-action":"update",children:"Update field\u2026"}),R&&jsxRuntime.jsx("button",{type:"button",class:"btn btn-sm btn-error btn-outline","data-frs-bulk-action":"delete",children:"Delete"})]})]}),jsxRuntime.jsx("div",{class:"overflow-x-auto rounded-box border border-base-300 bg-base-100","data-frs-table-wrap":true,children:jsxRuntime.jsxs("table",{class:"table table-sm w-full","data-frs-table":true,"data-frs-repo":e,"data-frs-colcount":n.length,children:[jsxRuntime.jsx("thead",{children:jsxRuntime.jsxs("tr",{class:"bg-base-200/50",children:[v&&jsxRuntime.jsx("th",{class:"w-8",children:jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-page":true,"aria-label":"Select all on this page"})}),[...n].map((T,P)=>{let E=f?.field===T,I=E?f.dir==="asc"?" \u25B2":" \u25BC":"";return jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:jsxRuntime.jsxs("a",{href:$s(T,f,c,d),class:`hover:text-base-content inline-flex items-center gap-0.5${E?" text-primary font-bold":""}`,children:[T,I]})},P)}),u.map((T,P)=>jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:T.column},`rel-${P}`)),jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide text-right",children:"Actions"})]})}),jsxRuntime.jsx("tbody",{children:t.length===0?jsxRuntime.jsx("tr",{children:jsxRuntime.jsx("td",{colspan:n.length+u.length+1+(v?1:0),class:"text-center py-16 text-base-content/40",children:"No documents found"})}):t.map((T,P)=>{let E=String(T.docId??T.id??""),I=`${r}/${e}/${encodeURIComponent(E)}/edit`,O=`${r}/${e}/${encodeURIComponent(E)}/delete`;return jsxRuntime.jsxs("tr",{class:"hover","data-frs-row-id":E,children:[v&&jsxRuntime.jsx("td",{class:"align-middle py-2",children:jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-row":true,value:E,"aria-label":`Select ${E}`})}),n.map(($,F)=>{let H=T[$],j=l[$],_=j?rt(j,H):null;return jsxRuntime.jsx("td",{class:"align-top py-2",children:jsxRuntime.jsx(De,{val:H,mismatch:_})},F)}),u.map(($,F)=>{let H=T[$.key];if(H==null||H==="")return jsxRuntime.jsx("td",{class:"py-2"},`rel-${F}`);let j=$.type==="one"?`${r}/${$.targetRepo}/${encodeURIComponent(String(H))}/edit`:`${r}/${$.targetRepo}?fv_${$.targetKey}=${encodeURIComponent(String(H))}`;return jsxRuntime.jsx("td",{class:"align-middle py-2",children:jsxRuntime.jsx("a",{href:j,class:"btn btn-xs btn-ghost btn-outline","data-frs-relation":true,"data-frs-rel-type":$.type,"data-frs-rel-repo":$.targetRepo,"data-frs-rel-fk":$.targetKey,"data-frs-rel-val":String(H),"data-frs-rel-label":$.column,children:$.column})},`rel-${F}`)}),jsxRuntime.jsx("td",{class:"align-middle text-right whitespace-nowrap py-2",children:jsxRuntime.jsxs("div",{class:"flex gap-1 justify-end",children:[jsxRuntime.jsx("a",{href:I,class:"btn btn-xs btn-outline",children:"Edit"}),w&&jsxRuntime.jsx("a",{href:`${r}/${e}/${encodeURIComponent(E)}/history`,class:"btn btn-xs btn-outline",title:"View change history",children:"History"}),i&&jsxRuntime.jsx("form",{method:"post",action:O,onsubmit:"return confirm('Delete this document?')",children:jsxRuntime.jsx("button",{type:"submit",class:"btn btn-xs btn-error btn-outline",children:"Delete"})})]})})]},P)})})]})}),(o.hasPrev||o.hasNext)&&jsxRuntime.jsxs("div",{class:"flex flex-col items-center mt-6 gap-2",children:[jsxRuntime.jsxs("div",{class:"flex justify-center items-center gap-2",children:[o.hasPrev?jsxRuntime.jsx("a",{href:Tr(c,o.prevCursor,"prev",f,d),class:"btn btn-sm btn-outline",children:"\u2190 Previous"}):jsxRuntime.jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"\u2190 Previous"}),o.hasNext?jsxRuntime.jsx("a",{href:Tr(c,o.nextCursor,"next",f,d),class:"btn btn-sm btn-outline",children:"Next \u2192"}):jsxRuntime.jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"Next \u2192"})]}),typeof m=="number"&&jsxRuntime.jsxs("div",{class:"text-xs text-base-content/50",children:[m," total document",m!==1?"s":"",c.length>0?" matching filters":""]})]}),v&&y&&jsxRuntime.jsxs("dialog",{id:"frs-bulk-update-modal",class:"modal",children:[jsxRuntime.jsxs("div",{class:"modal-box",children:[jsxRuntime.jsx("h3",{class:"font-bold text-lg mb-3",children:"Bulk update field"}),jsxRuntime.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."}),jsxRuntime.jsxs("form",{method:"dialog","data-frs-bulk-update-form":true,"data-frs-form":true,children:[jsxRuntime.jsxs("label",{class:"form-control w-full mb-3",children:[jsxRuntime.jsx("div",{class:"label",children:jsxRuntime.jsx("span",{class:"label-text text-xs uppercase tracking-wide",children:"Field"})}),jsxRuntime.jsxs("select",{class:"select select-bordered select-sm w-full",name:"field",required:true,"data-frs-bulk-field-select":true,children:[jsxRuntime.jsx("option",{value:"",children:"\u2014 Select a field \u2014"}),k.map(T=>jsxRuntime.jsx("option",{value:T,children:T},T))]})]}),jsxRuntime.jsx("div",{class:"mb-4","data-frs-bulk-value-container":true}),jsxRuntime.jsxs("div",{class:"modal-action",children:[jsxRuntime.jsx("button",{type:"button",class:"btn btn-sm btn-ghost","data-frs-bulk-update-cancel":true,children:"Cancel"}),jsxRuntime.jsx("button",{type:"submit",class:"btn btn-sm btn-primary","data-frs-bulk-update-submit":true,children:"Apply"})]})]})]}),jsxRuntime.jsx("form",{method:"dialog",class:"modal-backdrop",children:jsxRuntime.jsx("button",{children:"close"})})]}),jsxRuntime.jsx("div",{class:"hidden","data-frs-bulk-templates":true,children:A.map(T=>jsxRuntime.jsx("div",{"data-frs-bulk-template-for":T.name,dangerouslySetInnerHTML:{__html:Xe(T)}},T.name))})]}))}function st(e,t){return cn(e,t)}function yn(e,t){return ln(e,t)}function mn(e,t,n,r,o,s,a,c,i,u,f,d,g,x,m,S,b,w){return fn(e,t,n,r,o,s,a,c,i,u,f,d,g,x,m,S,b,w)}function Se(e,t,n,r,o,s){return un(e,t,n,r,o,s)}var gn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function js(){let e="";for(;e.length<20;){let t=crypto.randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let r=t[n];r>=gn.length*4||(e+=gn.charAt(r%gn.length));}}return e}async function Ar(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 Ot(e,t){if(!t)return;let n=e[t];if(typeof n!="string"||!n)return;let r=n.split("/").filter(Boolean),o=[];for(let s=1;s<r.length;s+=2)o.push(r[s]);return o.length>0?o:void 0}async function _e(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 hn(e,t,n){let r=e.documentKey??"docId",o=Ye(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 N(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function Et(e,t){e.status(302).set("Location",t).send("");}function Pt(e,t){let n=t.shape,r={};for(let[o,s]of Object.entries(n)){let a=xn(s),c=Z(a),i=c==="ZodObject",u=a,f=false;if(c==="ZodUnion"){let x=We(a);x.some(S=>Z(S)==="ZodDate")&&(f=true);let m=x.find(S=>{if(Z(S)==="ZodObject"){let b=te(S);return "latitude"in b&&"longitude"in b}return false});m&&(i=true,u=m);}if(e[o+"__isnull"]==="1"){r[o]=null;continue}if(i){let x={},m=false;for(let[w,p]of Object.entries(e))w.startsWith(`${o}.`)&&(x[w.slice(o.length+1)]=p,m=true);if(m){r[o]=Pt(x,u);continue}let S=e[o],b=Array.isArray(S)?S[S.length-1]:S;if(b)try{r[o]=JSON.parse(b);}catch{r[o]=b;}continue}let d=e[o],g=Array.isArray(d)?d[d.length-1]:d;if(g===void 0||g===""){c==="ZodBoolean"&&(r[o]=false);continue}if(f){r[o]=new Date(g);continue}switch(c){case "ZodBoolean":g==="__null__"?r[o]=null:r[o]=g==="true"||g==="on"||g==="1";break;case "ZodNumber":case "ZodBigInt":r[o]=Number(g);break;case "ZodDate":r[o]=new Date(g);break;case "ZodArray":try{r[o]=JSON.parse(g);}catch{r[o]=g;}break;default:if(g.startsWith("{")||g.startsWith("["))try{r[o]=JSON.parse(g);break}catch{}r[o]=g;}}return r}function Cr(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 Er(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=ee(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=Le(t);if(!r)return n;t=r;}else return n}}function xn(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=ee(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=Le(t);if(!r)return t;t=r;}else return t}}function Pr(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable")return true;if(n==="ZodDefault"){t=ee(t);continue}return false}}function $r(e){let t=xn(e),n=Z(t);if(n==="ZodEnum"){let r=Ue(t);return r.length>0?r:void 0}if(n==="ZodNativeEnum"){let r=Qe(t),o=Object.values(r).filter(s=>typeof s=="string");return o.length>0?o:void 0}if(n==="ZodLiteral"){let r=Ve(t);return typeof r=="string"?[r]:void 0}}function Ir(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=xn(t.shape[o]),i=Z(c),u=i==="ZodObject",f=c,d=false;if(i==="ZodUnion"){let g=We(c);g.some(m=>Z(m)==="ZodDate")&&(d=true);let x=g.find(m=>{if(Z(m)==="ZodObject"){let S=te(m);return "latitude"in S&&"longitude"in S}return false});x&&(u=true,f=x);}if(u&&typeof a=="object"&&a!==null&&!Array.isArray(a)&&!("_seconds"in a)&&typeof a.toDate!="function"){let g=Ir(a,f,s);Object.assign(r,g);}else if(i==="ZodDate"||d){let g=Cr(a);g!==null&&(r[s]=g);}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)&&("_seconds"in a||typeof a.toDate=="function")){let g=Cr(a);r[s]=g??JSON.stringify(a,null,2);}else typeof a=="object"?r[s]=JSON.stringify(a,null,2):r[s]=String(a);}return r}function bn(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?bn(n.nested,t):void 0}))}function Ms(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 Or(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 Dr(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=Er(a);if(c==="ZodObject"){let i=a;for(;;){let f=Z(i);if(f==="ZodOptional"||f==="ZodNullable"||f==="ZodDefault")i=ee(i);else break}let u=te(i);r.push(...Dr(Object.keys(u),i,s));}else r.push({name:s,zodType:c,nullable:Pr(a),enumValues:$r(a)});}return r}function Hs(e,t){let n=t.split("."),r=e;for(let o of n){for(;;){let a=Z(r);if(a==="ZodOptional"||a==="ZodNullable"||a==="ZodDefault")r=ee(r);else break}let s=te(r);if(!(o in s))return null;r=s[o];}return r}function Ce(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=Z(c);if(i==="ZodOptional"||i==="ZodNullable"||i==="ZodDefault")c=ee(c);else break}if(Z(c)!=="ZodObject"){o[s]=e.shape[s];continue}o[s]=Ce(c,a);}return zod.z.object(o)}function le(e,t,n){return ce(e,t,n)}function _r(e,t,n){let r=(h,l)=>{let k=le(h,t,n),y=Object.values(e).map(R=>({name:R.name,path:R.path}));N(l,yn(y,k));},o=async(h,l)=>{let k=h.params.repoName;if(!k){N(l,"Bad request",400);return}let y=e[k];if(!y){N(l,"Repository not found",404);return}let R=y.pageSize??25,v=h.query??{},C=v.cursor,A=v.dir==="prev"?"prev":"next",T=v.ob??"",P=v.od==="desc"?"desc":"asc",E=T?{field:T,dir:P}:void 0,I=parseInt(v.ps??""),O=Number.isFinite(I)&&I>0?Math.min(I,200):R,$=y.listColumns??Object.keys(y.schema.shape),F=y.documentKey??"docId",H=[F,...$.filter(oe=>oe!==F)];E&&(new Set([F,...$]).has(E.field)||(E=void 0));let j=y.filterableFields?(()=>{let oe=[];for(let ue of y.filterableFields)(ue.includes(".")||$.includes(ue))&&oe.push(ue);return oe})():$,_=(()=>{let oe=[];for(let ue of j)if(ue.includes(".")){let Pe=Hs(y.schema,ue);oe.push({name:ue,zodType:Pe?Er(Pe):"ZodString",nullable:Pe?Pr(Pe):false,enumValues:Pe?$r(Pe):void 0});}else oe.push(...Dr([ue],y.schema));return oe})(),Q=new Set(_.map(oe=>oe.name)),U=Ms(v,Q),J=Or(U),He;C&&(He=await Ar(y,C));let[X,dt]=await Promise.all([y.repo.query.paginate({pageSize:O,cursor:He,direction:A,...J.length>0?{where:J}:{},...E?{orderBy:[{field:E.field,direction:E.dir}]}:{}}).catch(oe=>({queryError:Ye(oe,{ref:y.repo.ref,path:y.path,isGroup:!!y.isGroup,filters:U,sort:E})})),y.repo.aggregate.count(J.length>0?{where:J}:{}).catch(()=>{})]),Ee="queryError"in X,ao=Ee?[]:X.data,io=Ee?"":X.nextCursor?.ref?.path??X.nextCursor?.id??"",co=Ee?"":X.prevCursor?.ref?.path??X.prevCursor?.id??"",lo=Ee?X.queryError:void 0,uo=le(h,t,n),ze,ut=v.flash;ut==="created"?ze={type:"success",message:"Document created successfully."}:ut==="updated"?ze={type:"success",message:"Document updated successfully."}:ut==="deleted"?ze={type:"success",message:"Document deleted successfully."}:ut==="backfilled"&&(ze={type:"success",message:"Repository backfilled successfully."}),N(l,mn(y.name,ao,H,uo,{hasPrev:Ee?false:X.hasPrevPage,hasNext:Ee?false:X.hasNextPage,prevCursor:co,nextCursor:io},ze,_,U,y.allowDelete??false,y.relationalMeta,E,O,lo,y.isGroup,dt,y.mutableFields,y.schema,y.historyEnabled));},s=(h,l)=>{let k=h.params.repoName;if(!k){N(l,"Bad request",400);return}let y=e[k];if(!y){N(l,"Repository not found",404);return}let R=le(h,t,n),v=Ce(y.schema,y.createFields),C=ae(v),A=`${R}/${y.name}/create`,T=xe(C,A,"POST","Create document");N(l,Se(y.name,T,"create",null,R));},a=async(h,l)=>{let k=h.params.repoName;if(!k){N(l,"Bad request",400);return}let y=e[k];if(!y){N(l,"Repository not found",404);return}let R=le(h,t,n),v=h.body??{},C=Pt(v,y.schema),A=Ce(y.schema,y.createFields),T=A.safeParse(C);if(!T.success){let P=ae(A),E=`${R}/${y.name}/create`,I=xe(P,E,"POST","Create document"),O=T.error.issues.map($=>`${$.path.join(".")}: ${$.message}`).join(", ");N(l,Se(y.name,I,"create",null,R,{type:"error",message:`Validation error: ${O}`}),422);return}try{if(y.isGroup&&y.parentKeys&&y.parentKeys.length>0){let P={...T.data};y.createdKey&&(P[y.createdKey]=new Date);let E=y.parentKeys.filter(F=>!P[F]);if(E.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${E.join(", ")}`);let I=y.parentKeys.map(F=>P[F]),O=y.documentKey??"docId",$=P[O]||js();await y.repo.set(...I,$,P);}else await y.repo.create(T.data);Et(l,`${R}/${y.name}?flash=created`);}catch(P){let E=Ce(y.schema,y.createFields),I=ae(E),O=`${R}/${y.name}/create`,$=xe(I,O,"POST","Create document");N(l,Se(y.name,$,"create",null,R,{type:"error",message:`Save error: ${P.message}`}),500);}},c=async(h,l)=>{let k=h.params.repoName,y=h.params.id;if(!k||!y){N(l,"Bad request",400);return}let R=e[k];if(!R){N(l,"Repository not found",404);return}let v=le(h,t,n),C=null;try{C=await _e(R,y);}catch(O){let $=hn(R,y,O),F=Te(O)?424:500;N(l,st("",{title:`Edit ${R.name} / ${y}`,basePath:v,breadcrumb:[{label:"Repositories",href:v},{label:R.name,href:`${v}/${R.name}`},{label:`Edit ${y}`}],flash:$}),F);return}if(!C){N(l,"Document not found",404);return}let A=Ir(C,R.schema),T=Ce(R.schema,R.mutableFields),P=bn(ae(T),A),E=`${v}/${R.name}/${encodeURIComponent(y)}/edit`,I=xe(P,E,"POST","Save changes");N(l,Se(R.name,I,"edit",y,v));},i=async(h,l)=>{let k=h.params.repoName,y=h.params.id;if(!k||!y){N(l,"Bad request",400);return}let R=e[k];if(!R){N(l,"Repository not found",404);return}let v=le(h,t,n),C=h.body??{},A=Pt(C,R.schema),T=Ce(R.schema,R.mutableFields),E=T.partial().safeParse(A);if(!E.success){let I=Object.fromEntries(Object.entries(C).map(([j,_])=>[j,Array.isArray(_)?_.join(","):_??""])),O=bn(ae(T),I),$=`${v}/${R.name}/${encodeURIComponent(y)}/edit`,F=xe(O,$,"POST","Save changes"),H=E.error.issues.map(j=>`${j.path.join(".")}: ${j.message}`).join(", ");N(l,Se(R.name,F,"edit",y,v,{type:"error",message:`Validation error: ${H}`}),422);return}try{let I=await _e(R,y),O=(I&&Ot(I,R.pathKey))??[y];await R.repo.update(...O,E.data),Et(l,`${v}/${R.name}?flash=updated`);}catch(I){let O=Ce(R.schema,R.mutableFields),$=ae(O),F=`${v}/${R.name}/${encodeURIComponent(y)}/edit`,H=xe($,F,"POST","Save changes"),j=Te(I)?hn(R,y,I):{type:"error",message:`Save error: ${I.message}`},_=Te(I)?424:500;N(l,Se(R.name,H,"edit",y,v,j),_);}},u=async(h,l)=>{let k=h.params.repoName,y=h.params.id;if(!k||!y){N(l,"Bad request",400);return}let R=e[k];if(!R){N(l,"Repository not found",404);return}if(!R.allowDelete){N(l,"Delete is not allowed for this repository",403);return}let v=le(h,t,n);try{let C=await _e(R,y),A=(C&&Ot(C,R.pathKey))??[y];await R.repo.delete(...A),Et(l,`${v}/${R.name}?flash=deleted`);}catch(C){let A=Te(C)?hn(R,y,C):{type:"error",message:`Delete error: ${C.message}`},T=Te(C)?424:500;N(l,st("",{title:`Delete ${R.name} / ${y}`,basePath:v,breadcrumb:[{label:"Repositories",href:v},{label:R.name,href:`${v}/${R.name}`},{label:`Delete ${y}`}],flash:A}),T);}},f=async(h,l)=>{let k=h.params.repoName;if(!k){N(l,"Bad request",400);return}let y=e[k];if(!y){N(l,"Repository not found",404);return}let R=le(h,t,n),v=h.query,C=v?.type==="many"?"many":"one",A=Math.max(1,Math.min(100,Number(v?.ps??25)||25)),T=y.listColumns??Object.keys(te(y.schema)),{PanelOne:P,PanelMany:E}=await Promise.resolve().then(()=>(an(),Rr)),{renderToString:I}=await import('hono/jsx/dom/server');if(C==="one"){let _=String(v?.id??"");if(!_){N(l,"<div class='p-6 text-error'>Missing id parameter.</div>",400);return}try{let Q=await _e(y,_),U=I(P({doc:Q,repoName:y.name,basePath:R,schema:y.schema,columns:T}));N(l,U);}catch(Q){N(l,`<div class='p-6 text-error text-sm'>Error: ${Q.message}</div>`,500);}return}let O=String(v?.fk??""),$=String(v?.fv??"");if(!O||!$){N(l,"<div class='p-6 text-error'>Missing fk/fv parameters.</div>",400);return}let F=v?.cursor??"",H=v?.dir==="prev"?"prev":"next",j;F&&(j=await Ar(y,F));try{let _=await y.repo.query.paginate({pageSize:A,cursor:j,direction:H,where:[[O,"==",zs($)]]}),Q=I(E({docs:_.data,repoName:y.name,basePath:R,fk:O,fv:$,columns:T,schema:y.schema,pagination:{hasPrev:_.hasPrevPage,hasNext:_.hasNextPage,prevCursor:_.prevCursor?.ref?.path??_.prevCursor?.id??"",nextCursor:_.nextCursor?.ref?.path??_.nextCursor?.id??"",pageSize:A}}));N(l,Q);}catch(_){N(l,`<div class='p-6 text-error text-sm'>Error: ${_.message}</div>`,500);}},d=async(h,l)=>{let k=h.params.repoName;if(!k){N(l,"Bad request",400);return}let y=e[k];if(!y){N(l,"Repository not found",404);return}let R=le(h,t,n);try{await y.repo.system.backfillKeys(),Et(l,`${R}/${y.name}?flash=backfilled`);}catch(v){N(l,`<div class="p-6 text-error">Backfill failed: ${v.message}</div>`,500);}},g=async(h,l)=>{let k=[];for(let y of l){let R;if(h.isGroup||h.parentKeys?.length){let v=await _e(h,y);R=v?Ot(v,h.pathKey):void 0;}R||(R=[y]);try{let v=h.repo.documentRef(...R);v&&k.push(v);}catch{}}return k},x=async(h,l)=>{let k=Or(l),y=h.documentKey??"docId",R=[],v;for(;;){let C=await h.repo.query.paginate({pageSize:500,cursor:v,direction:"next",...k.length>0?{where:k}:{}});for(let A of C.data){let T=String(A[y]??A.id??"");T&&R.push(T);}if(!C.hasNextPage||!C.nextCursor)break;v=C.nextCursor;}return R},m=async(h,l)=>{let k=h.params.repoName;if(!k){re(l,{error:"Bad request"},400);return}let y=e[k];if(!y){re(l,{error:"Repository not found"},404);return}if(!y.allowDelete){re(l,{error:"Delete is not allowed for this repository"},403);return}let R=h.body??{};try{let v=await b(y,R);if(v.length===0){re(l,{deleted:0});return}let C=await g(y,v);for(let A=0;A<C.length;A+=500)await y.repo.bulk.delete(C.slice(A,A+500));re(l,{deleted:C.length});}catch(v){re(l,{error:v.message},500);}},S=async(h,l)=>{let k=h.params.repoName;if(!k){re(l,{error:"Bad request"},400);return}let y=e[k];if(!y){re(l,{error:"Repository not found"},404);return}let R=h.body??{},v=String(R.field??"");if(!v){re(l,{error:"Missing 'field'"},400);return}if(!y.mutableFields||!y.mutableFields.includes(v)){re(l,{error:`Field '${v}' is not bulk-updatable`},403);return}let C=y.schema.shape?.[v],A;if(C){let T=typeof y.schema=="object"&&y.schema&&"constructor"in y.schema&&y.schema.constructor.name.includes("Zod")?y.schema.pick({[v]:true}):void 0;if(!T){re(l,{error:"Invalid schema structure"},500);return}A=Pt(R.formPayload??{},T)[v];let E=C.safeParse(A);if(!E.success){re(l,{error:`Invalid value for '${v}': ${E.error.message}`},400);return}A=E.data;}try{let T=await b(y,R);if(T.length===0){re(l,{updated:0});return}let E=(await g(y,T)).map(I=>({docRef:I,data:{[v]:A}}));for(let I=0;I<E.length;I+=500)await y.repo.bulk.update(E.slice(I,I+500));re(l,{updated:E.length});}catch(T){re(l,{error:T.message},500);}};async function b(h,l){if(l.selectAll){let k=w(l.filters,h);return await x(h,k)}return Array.isArray(l.ids)?l.ids.filter(k=>typeof k=="string"&&!!k):[]}function w(h,l){if(!Array.isArray(h))return [];let k=new Set((l.filterableFields??Object.keys(te(l.schema))).map(v=>String(v))),y=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),R=[];for(let v of h)v&&typeof v=="object"&&typeof v.field=="string"&&k.has(v.field)&&typeof v.value=="string"&&y.has(String(v.op))&&R.push({field:v.field,op:v.op,value:v.value});return R}return {handleDashboard:r,handleList:o,handleCreateForm:s,handleCreateSubmit:a,handleEditForm:c,handleEditSubmit:i,handleDelete:u,handlePanel:f,handleBulkDelete:m,handleBulkUpdate:S,handleBulkBackfill:d,handleHistory:async(h,l)=>{let k=h.params.repoName,y=h.params.id;if(!k||!y){N(l,"Bad request",400);return}let R=e[k];if(!R){N(l,"Repository not found",404);return}if(!R.historyEnabled||!R.repo.history){N(l,"History not enabled for this repository",404);return}let v=le(h,t,n),C=R.historySubcollection??"history",A=[y];try{let _=await _e(R,y),Q=_?Ot(_,R.pathKey):void 0;Q&&Q.length>0&&(A=Q);}catch{}let T=parseInt(String(h.query?.limit??"")),P=Number.isFinite(T)&&T>0?Math.min(T,500):100,E=[],I;try{E=await R.repo.history.list(...A,{limit:P});}catch(_){I=_.message;}let O=_=>String(_??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),$=_=>{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">${O(JSON.stringify(_))}</code>`}catch{return O(String(_))}return O(String(_))},F=_=>_?typeof _.toDate=="function"?_.toDate().toISOString():_ instanceof Date?_.toISOString():O(String(_)):"",H=_=>`<span class="badge badge-sm ${_==="create"?"badge-success":_==="delete"?"badge-error":"badge-info"}">${O(_)}</span>`,j="";if(j+='<div class="flex items-center justify-between mb-4">',j+=`<a href="${v}/${R.name}/${encodeURIComponent(y)}/edit" class="btn btn-sm btn-outline">\u2190 Back to edit</a>`,j+=`<a href="${v}/${R.name}" class="btn btn-sm btn-outline">\u2190 Back to list</a>`,j+="</div>",j+=`<p class="text-sm text-base-content/60 mb-4">Subcollection: <code>${O(C)}</code> \xB7 Showing up to ${P} entries.</p>`,I)j+=`<div class="alert alert-error mb-4">${O(I)}</div>`;else if(E.length===0)j+='<div class="alert">No history entries found.</div>';else {j+='<div class="overflow-x-auto"><table class="table table-zebra table-sm">',j+="<thead><tr><th>When</th><th>Op</th><th>User</th><th>Reason / Comment</th><th>Changes</th></tr></thead><tbody>";for(let _ of E){let Q=_.meta??{},U=[Q.reason,Q.comment].filter(X=>X!=null&&X!=="").map(X=>O(String(X))).join(" \u2014 "),J="",He=Object.keys(_.changes??{});He.length===0?J='<span class="opacity-40">\u2014</span>':J='<ul class="space-y-1">'+He.map(X=>{let dt=_.changes[X];return `<li><strong>${O(X)}</strong>: ${$(dt.oldValue)} \u2192 ${$(dt.newValue)}</li>`}).join("")+"</ul>",j+="<tr>",j+=`<td class="whitespace-nowrap text-xs font-mono">${O(F(_.historySetAt))}</td>`,j+=`<td>${H(_.operation??"update")}</td>`,j+=`<td class="text-xs">${O(Q.userEmail??Q.userId??"")}</td>`,j+=`<td class="text-xs">${U}</td>`,j+=`<td>${J}</td>`,j+="</tr>";}j+="</tbody></table></div>";}N(l,st(j,{title:`History \u2014 ${R.name} / ${y}`,basePath:v,breadcrumb:[{label:"Repositories",href:v},{label:R.name,href:`${v}/${R.name}`},{label:`History ${y}`}]}));}}}function re(e,t,n=200){e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(t));}function zs(e){return e==="true"?true:e==="false"?false:e!==""&&!isNaN(Number(e))?Number(e):e}It();async function Ns(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function Bs(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 Hr(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[x,m]of Object.entries(n)){if(!m.repo)throw new Error(`[createAdminServer] Repository "${x}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let S=m.schema??m.repo.schema??null;if(!S)throw new Error(`[createAdminServer] Repository "${x}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let b,w,p;if(m.fieldsConfig){let k=m.fieldsConfig;b=[],w=[],p=[];for(let[y,R]of Object.entries(k))for(let v of R)v==="filterable"?b.push(y):v==="mutable"?w.push(y):v==="create"&&p.push(y);b.length===0&&(b=void 0),w.length===0&&(w=void 0),p.length===0&&(p=void 0);}let h=(()=>{let k=m.repo._parentKeys;return k&&k.length>0?k:void 0})();if(h&&p)for(let k of h)p.includes(k)||p.push(k);let l={name:x,path:m.path,repo:m.repo,schema:S,documentKey:m.documentKey??"docId",pathKey:m.repo._pathKey??void 0,isGroup:!!m.repo._isGroup,parentKeys:h,createdKey:m.repo._createdKey??void 0,listColumns:m.listColumns,pageSize:m.pageSize,filterableFields:b,mutableFields:w,createFields:p,allowDelete:m.allowDelete??false,historyEnabled:!!m.repo._historyConfig?.enabled,historySubcollection:(m.repo._historyConfig?.enabled&&m.repo._historySubcollection)??void 0,relationalMeta:(()=>{if(!m.relationalFields||m.relationalFields.length===0)return;let k=m.repo.relationalKeys??{},y=[];for(let R of m.relationalFields){let v=k[R.key];v&&y.push({key:v.sourceKey?String(v.sourceKey):R.key,column:R.column,targetRepo:String(v.repo),targetKey:String(v.key),type:v.type});}return y.length>0?y:void 0})()};u[x]=l;}let f=_r(u,i,Gn(c?.region)),d=new fe;if(o!==false&&d.use($t(o===void 0?{}:o)),r&&d.use(async(x,m,S)=>{let b=x,w=String(b.headers?.["content-type"]??"");if(w.includes("application/x-www-form-urlencoded")){let p=await Ns(b);x.body=Bs(p);}else if(w.includes("application/json")&&typeof b.body=="string")try{x.body=JSON.parse(b.body);}catch{}await S();}),s)if(Ke(s)){for(let x of s.routes){let m=`${i}${x.path}`;x.method==="GET"?d.get(m,x.handler):d.post(m,x.handler);}d.use(s.middleware);}else if(typeof s=="function")d.use(s);else {let x=s.realm??"Admin",m="Basic "+Buffer.from(`${s.username}:${s.password}`).toString("base64");d.use((S,b,w)=>{if((S.headers?.authorization??"")!==m){b.status(401).set("WWW-Authenticate",`Basic realm="${x}"`).set("Content-Type","text/plain").send("Unauthorized");return}w();});}for(let x of a)d.use(x);d.get(`${i}/`,f.handleDashboard),d.get(`${i}`,f.handleDashboard),d.get(`${i}/:repoName/_panel`,f.handlePanel),d.post(`${i}/:repoName/_bulk/delete`,f.handleBulkDelete),d.post(`${i}/:repoName/_bulk/update`,f.handleBulkUpdate),d.post(`${i}/:repoName/_bulk/backfill`,f.handleBulkBackfill),d.get(`${i}/:repoName`,f.handleList),d.get(`${i}/:repoName/create`,f.handleCreateForm),d.post(`${i}/:repoName/create`,f.handleCreateSubmit),d.get(`${i}/:repoName/:id/edit`,f.handleEditForm),d.post(`${i}/:repoName/:id/edit`,f.handleEditSubmit),d.get(`${i}/:repoName/:id/history`,f.handleHistory),d.post(`${i}/:repoName/:id/delete`,f.handleDelete);let g=async(x,m)=>{await d.handle(x,m);};return c&&(g.httpsOptions=c),g}function Sn(e,t,n=200){let r=V(t);return e.json(r,n)}function Oe(e,t,n,r=200){return Sn(e,{success:true,data:t,meta:n},r)}function M(e,t,n=400){return Sn(e,{success:false,error:t},n)}function wn(e,t,n,r,o){let s=Ye(t,n),a=s.type==="index",c=a?424:500,u={success:false,error:a?s.message:o&&t instanceof Error?t.message:r};return a&&(u.errorType="index",s.indexUrl&&(u.indexUrl=s.indexUrl)),Sn(e,u,c)}var Rn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function zr(){let e="";for(;e.length<20;){let t=crypto.randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let r=t[n];r>=Rn.length*4||(e+=Rn.charAt(r%Rn.length));}}return e}function Fe(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return zod.z.preprocess(r=>Kt(r)??r,e);if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[s,a]of Object.entries(r))o[s]=Fe(a);return zod.z.object(o)}if(n==="ZodArray"||n==="array"){let r=t.element??t.type;if(r)return zod.z.array(Fe(r))}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(r)return Fe(r).optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(r)return Fe(r).nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType,o=t.defaultValue;if(r){let s=Fe(r);return typeof o=="function"?s.default(o()):s.default(o)}}return e}function Zs(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 zod.z.object(o)}function Dt(e,t,n,r=false,o=[]){try{let s=Zs(e,n,o),a=r?s.partial():s;return {success:!0,data:(Zt()==="normalize"?Fe(a):a).parse(t)}}catch(s){return s instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${s.issues.map(c=>`${c.path.join(".")}: ${c.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function _t(e,t,n){let r=e?.shape?.[t];if(!r||typeof r.safeParse!="function")return {success:true,data:n};let o=r.safeParse(n);if(o.success)return {success:true,data:o.data};if(Array.isArray(n)){let a=[];for(let c of n){let i=r.safeParse(c);if(i.success)a.push(i.data);else return {success:false,error:i.error.issues.map(f=>f.message).join(", ")}}return {success:true,data:a}}return {success:false,error:o.error.issues.map(a=>a.message).join(", ")}}function Ks(e,t){let n=[],r=t?new Set(t):null,o={eq:"==",ne:"!=",lt:"<",lte:"<=",gt:">",gte:">=",in:"in",nin:"not-in",contains:"array-contains",containsAny:"array-contains-any"};for(let[s,a]of Object.entries(e)){if(a===void 0||["cursor","limit","pageSize","orderBy","orderDir","select"].includes(s))continue;let c=Array.isArray(a)?a[0]:a;if(c===void 0||c==="")continue;let i=s.match(/^(\w+)__(\w+)$/),u,f="==";if(i&&i[1]&&i[2]){u=i[1];let g=i[2];if(o[g])f=o[g];else continue}else if(!i)u=s;else continue;if(r&&!r.has(u))continue;let d=c;f==="in"||f==="not-in"||f==="array-contains-any"?d=c.split(",").map(g=>Nr(g.trim())):d=Nr(c),n.push({field:u,op:f,value:d});}return n}function Nr(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 Ft(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function Br(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 qr(e,t,n){async function r(w,p,h,l){if(!p.rules)return true;let k=p.rules?.[h];if(!k)return M(w,`Operation "${h}" is not allowed for this repository`,403),false;try{return await k(l)?!0:M(w,"Forbidden",403)}catch(y){let R=n&&y instanceof Error?y.message:"Forbidden";return M(w,R,403)}}async function o(w,p,h,l){if(!w.rules)return l;let k=w.rules?.filter;if(!k)return l;let y=[];for(let R of l)try{await k({user:p,doc:R,params:h})&&y.push(R);}catch{}return y}function s(w){return w.get("user")??w.get("docsUser")??null}function a(w,p){if(!w){let h=p.req.path.split("/");for(let l of h)if(e[l]){w=l;break}}return !w||!e[w]?null:e[w]??null}function c(w,p){if(!p)return;let h=w[p];if(typeof h!="string"||!h)return;let l=h.split("/").filter(Boolean),k=[];for(let y=1;y<l.length;y+=2)k.push(l[y]);return k.length>0?k:void 0}async function i(w,p){let h=`by${w.documentKey.charAt(0).toUpperCase()}${w.documentKey.slice(1)}`,l=w.repo.get[h];if(typeof l=="function")try{let y=await l(p);if(y)return y}catch{}return (await w.repo.query.by({where:[[w.documentKey,"==",p]],limit:1}))[0]??null}async function u(w){let p=w.c,h=p.req.param(),l=a(h.repoName,p);if(!l)return M(p,"Repository not found",404);let k=s(p);if(!await r(p,l,"list",{user:k,query:p.req.query(),params:h}))return;let y=[],R;try{let v=p.req.query(),C=Math.min(Number(v.pageSize)||l.pageSize,100),A=v.cursor,T=v.direction?.toLowerCase()==="prev"?"prev":"next",P=v.orderBy,E=v.orderDir?.toLowerCase()==="desc"?"desc":"asc",I=v.select,O=I?I.split(",").map(U=>U.trim()):void 0,$;l.allowedIncludes&&v.includes&&($=(typeof v.includes=="string"?v.includes.split(",").map(J=>J.trim()):Array.isArray(v.includes)?v.includes:[]).filter(J=>typeof J=="string"&&l.allowedIncludes.includes(J)),$?.length===0&&($=void 0));let F=Ks(v,l.filterableFields);y=F.map(U=>({field:U.field,op:U.op,value:String(U.value??"")})),P&&(R={field:P,dir:E});let H={pageSize:C,direction:T};if(A)try{let U=typeof A=="string"?JSON.parse(A):A;H.cursor=await Br(l,U);}catch{}if(P){if(l.orderableFields&&!l.orderableFields.includes(P))return M(p,`Field not orderable: ${P}`,400);H.orderBy=[{field:P,direction:E}];}if(F.length>0){H.where=[];for(let U of F){let J=_t(l.schema,U.field,U.value);if(!J.success)return M(p,`Invalid filter value for '${U.field}': ${J.error}`,400);H.where.push([U.field,U.op,J.data]);}}O&&(H.select=O),$&&(H.include=$);let j=await l.repo.query.paginate(H),Q={items:await o(l,s(p),h,j.data),hasNextPage:j.hasNextPage,hasPrevPage:j.hasPrevPage,nextCursor:Ft(j.nextCursor),prevCursor:Ft(j.prevCursor)};return Oe(p,Q,{pageSize:C,hasMore:j.hasNextPage})}catch(v){wn(p,v,{ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:y,sort:R},"Failed to fetch documents",n);}}async function f(w){let p=w.c,h=p.req.param(),l=a(h.repoName,p);if(!l)return M(p,"Repository not found",404);let k=s(p);if(!await r(p,l,"list",{user:k,query:w.input||{},params:h}))return;let y=[],R;try{let v=w.input||{},C=Math.min(v.pageSize||l.pageSize,100),A=v.direction==="prev"?"prev":"next";v.where&&(y=v.where.map(O=>({field:String(O[0]),op:O[1],value:String(O[2]??"")}))),v.orderBy&&v.orderBy[0]&&(R={field:v.orderBy[0].field,dir:v.orderBy[0].direction==="desc"?"desc":"asc"});let T={pageSize:C,direction:A};if(v.cursor)try{let O=typeof v.cursor=="string"?JSON.parse(v.cursor):v.cursor;T.cursor=await Br(l,O);}catch{}if(l.allowedIncludes&&v.includes&&v.includes.length>0){let O=v.includes.filter($=>typeof $=="string"?l.allowedIncludes.includes($):typeof $=="object"&&$!==null&&"relation"in $&&typeof $.relation=="string"?l.allowedIncludes.includes($.relation):!1);O.length>0&&(T.include=O);}if(v.where&&v.where.length>0){if(l.filterableFields){let $=new Set(l.filterableFields),F=v.where.filter(H=>!$.has(H[0]));if(F.length>0){M(p,`Fields not filterable: ${F.map(H=>H[0]).join(", ")}`,400);return}}let O=[];for(let $ of v.where){let F=_t(l.schema,$[0],$[2]);if(!F.success){M(p,`Invalid filter value for '${$[0]}': ${F.error}`,400);return}O.push([$[0],$[1],F.data]);}T.where=O;}if(v.orWhere&&v.orWhere.length>0){if(l.filterableFields){let $=new Set(l.filterableFields),F=v.orWhere.filter(H=>!$.has(H[0]));if(F.length>0){M(p,`Fields not filterable: ${F.map(H=>H[0]).join(", ")}`,400);return}}let O=[];for(let $ of v.orWhere){let F=_t(l.schema,$[0],$[2]);if(!F.success){M(p,`Invalid filter value for '${$[0]}': ${F.error}`,400);return}O.push([$[0],$[1],F.data]);}T.orWhere=O;}if(v.orWhereGroups&&v.orWhereGroups.length>0){if(l.filterableFields){let $=new Set(l.filterableFields);for(let F of v.orWhereGroups){let H=F.filter(j=>!$.has(j[0]));if(H.length>0){M(p,`Fields not filterable: ${H.map(j=>j[0]).join(", ")}`,400);return}}}let O=[];for(let $ of v.orWhereGroups){let F=[];for(let H of $){let j=_t(l.schema,H[0],H[2]);if(!j.success){M(p,`Invalid filter value for '${H[0]}': ${j.error}`,400);return}F.push([H[0],H[1],j.data]);}O.push(F);}T.orWhereGroups=O;}if(v.orderBy&&v.orderBy.length>0){if(l.orderableFields){let O=new Set(l.orderableFields),$=v.orderBy.filter(F=>!O.has(F.field));if($.length>0){M(p,`Fields not orderable: ${$.map(F=>F.field).join(", ")}`,400);return}}T.orderBy=v.orderBy;}v.select&&v.select.length>0&&(T.select=v.select);let P=await l.repo.query.paginate(T),I={items:await o(l,s(p),h,P.data),hasNextPage:P.hasNextPage,hasPrevPage:P.hasPrevPage,nextCursor:Ft(P.nextCursor),prevCursor:Ft(P.prevCursor)};return Oe(p,I,{pageSize:C,hasMore:P.hasNextPage})}catch(v){wn(p,v,{ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:y,sort:R},"Failed to query documents",n);}}async function d(w){let p=w.c,h=p.req.param(),l=a(h.repoName,p);if(!l)return M(p,"Repository not found",404);let k=h.id;if(!k)return M(p,"Document ID required",400);try{let y=await i(l,k);if(!y)return M(p,"Document not found",404);let R=s(p);if(!await r(p,l,"get",{user:R,doc:y,params:h}))return;if(l.rules?.filter)try{if(!await l.rules.filter({user:R,doc:y,params:h}))return M(p,"Document not found",404)}catch{return M(p,"Document not found",404)}return Oe(p,y)}catch(y){wn(p,y,{ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:[{field:l.documentKey,op:"==",value:k}]},"Failed to fetch document",n);}}async function g(w){let p=w.c,h=p.req.param(),l=a(h.repoName,p);if(!l)return M(p,"Repository not found",404);try{let k=w.input||{},y=s(p);if(!await r(p,l,"create",{user:y,body:k,params:h}))return;let R=Dt(l.schema,k,l.createFields,!1,l.systemKeys);if(!R.success)return M(p,R.error,400);if(l.validate){let C=await l.validate(R.data,"create");if(C)return M(p,C,400)}let v;if(l.isGroup&&l.parentKeys&&l.parentKeys.length>0){let C={...R.data};l.createdKey&&(C[l.createdKey]=new Date);let A=l.parentKeys.filter(E=>!C[E]);if(A.length>0){M(p,`Missing parent key(s) for subcollection create: ${A.join(", ")}`,400);return}let T=l.parentKeys.map(E=>C[E]),P=C[l.documentKey]||zr();v=await l.repo.set(...T,P,C);}else v=await l.repo.create(R.data);return Oe(p,v,void 0,201)}catch(k){let y=n&&k instanceof Error?k.message:"Failed to create document";return M(p,y,500)}}async function x(w,p){let h=w.c,l=h.req.param(),k=a(l.repoName,h);if(!k)return M(h,"Repository not found",404);let y=l.id;if(!y)return M(h,"Document ID required",400);try{let R=w.input||{},v=await i(k,y);if(!v)return M(h,"Document not found",404);let C=s(h);if(!await r(h,k,"update",{user:C,doc:v,body:R,params:l}))return;let A=Dt(k.schema,R,k.mutableFields,p,k.systemKeys);if(!A.success)return M(h,A.error,400);if(k.validate){let E=await k.validate(A.data,"update");if(E)return M(h,E,400)}let T=c(v,k.pathKey)??[y],P=await k.repo.update(...T,A.data);return Oe(h,P)}catch(R){let v=n&&R instanceof Error?R.message:"Failed to update document";return M(h,v,500)}}async function m(w){let p=w.c,h=p.req.param(),l=a(h.repoName,p);if(!l)return M(p,"Repository not found",404);if(!l.allowDelete)return M(p,"Delete not allowed for this repository",403);let k=h.id;if(!k)return M(p,"Document ID required",400);try{let y=await i(l,k);if(!y)return M(p,"Document not found",404);let R=s(p);if(!await r(p,l,"delete",{user:R,doc:y,params:h}))return;let v=c(y,l.pathKey)??[k];return await l.repo.delete(...v),Oe(p,{deleted:!0})}catch(y){let R=n&&y instanceof Error?y.message:"Failed to delete document";return M(p,R,500)}}function S(w){return w.c.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","Access-Control-Max-Age":"86400"})}async function b(w){let p=w.c,h=p.req.param(),l=a(h.repoName,p);if(!l)return M(p,"Repository not found",404);try{let k=w.input||{};if(!Array.isArray(k.operations))return M(p,"operations array is required",400);let y=s(p),R=l.repo.batch.create(),v=[];for(let C of k.operations){if(!C.type||!["create","update","delete"].includes(C.type))return M(p,"Invalid operation type",400);if(C.type==="create"){if(!await r(p,l,"create",{user:y,body:C.data,params:h}))return;let A=Dt(l.schema,C.data,l.createFields,!1,l.systemKeys);if(!A.success)return M(p,A.error,400);let T=C.data[l.documentKey]||zr(),P={...A.data};if(l.createdKey&&(P[l.createdKey]=new Date),l.isGroup&&l.parentKeys){let E=l.parentKeys.map(I=>P[I]);R.set(...E,T,P);}else R.set(T,P);v.push({op:"create",id:T});}else if(C.type==="update"){if(!C.id)return M(p,"id required for update",400);let A=await i(l,C.id);if(!A)return M(p,`Document ${C.id} not found`,404);if(!await r(p,l,"update",{user:y,doc:A,body:C.data,params:h}))return;let T=Dt(l.schema,C.data,l.mutableFields,!0,l.systemKeys);if(!T.success)return M(p,T.error,400);let P=c(A,l.pathKey)??[C.id];R.update(...P,T.data),v.push({op:"update",id:C.id});}else if(C.type==="delete"){if(!l.allowDelete)return M(p,"Delete not allowed",403);if(!C.id)return M(p,"id required for delete",400);let A=await i(l,C.id);if(!A)return M(p,`Document ${C.id} not found`,404);if(!await r(p,l,"delete",{user:y,doc:A,params:h}))return;let T=c(A,l.pathKey)??[C.id];R.delete(...T),v.push({op:"delete",id:C.id});}}return await R.commit(),Oe(p,{results:v})}catch(k){let y=n&&k instanceof Error?k.message:"Batch operation failed";return M(p,y,500)}}return {handleList:u,handleQuery:f,handleGet:d,handleCreate:g,handleUpdate:x,handleDelete:m,handleBatch:b,handleOptions:S}}function jt(e){try{return zod.z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=zodToOpenapi.getOpenApiMetadata(t.zodSchema);n&&Object.assign(t.jsonSchema,n);let r=t.zodSchema?._zod?.def;r&&(r.type==="date"&&!t.jsonSchema.type?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):r.type==="bigint"&&!t.jsonSchema.type&&(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 se(e){return {$ref:`#/components/schemas/${e}`}}function W(e){return {description:e,content:{"application/json":{schema:se("ErrorResponse")}}}}function je(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function Zr(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"}},required:["items","hasNextPage","hasPrevPage"]},meta:{type:"object",properties:{pageSize:{type:"integer"},hasMore:{type:"boolean"},cursor:{oneOf:[{type:"string"},{type:"null"}]}}}},required:["success","data"]}}}}}function it(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 Us(e,t){let n=t.split("."),r=it(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;r=it(a[s]);}return r}function Kr(e,t="",n=0){if(n>5)return [];let o=it(e)?.shape;if(!o)return [];let s=[];for(let[a,c]of Object.entries(o)){let i=t?`${t}.${a}`:a,u=it(c);u?.shape&&typeof u.shape=="object"?s.push(...Kr(u,i,n+1)):s.push({path:i,zodSchema:c});}return s}function An(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:Us(e.schema,t)})):Kr(e.schema)}function Tn(e){if(!e)return {type:"string"};let t=jt(e);return delete t.$schema,delete t.title,t}function Qs(e){let t=An(e),n=e.orderableFields??t.map(r=>r.path);return [{name:"pageSize",in:"query",schema:{type:"integer",default:e.pageSize,maximum:100},description:"Number of items per page"},{name:"cursor",in:"query",schema:{type:"string"},description:"Base64 pagination cursor"},{name:"orderBy",in:"query",schema:{type:"string",...n.length>0?{enum:n}:{}},description:"Field name to order by"},{name:"orderDir",in:"query",schema:{type:"string",enum:["asc","desc"]},description:"Order direction"},{name:"select",in:"query",schema:{type:"string"},description:`Comma-separated list of fields to return${t.length>0?` (${t.map(r=>r.path).join(", ")})`:""}`}]}function Vs(e){let t=An(e),n=["eq","ne","lt","lte","gt","gte","in","nin","contains","containsAny"],r={eq:"equals. Use 'null' or '__null__' to match null values",ne:"not equals. Use 'null' or '__null__' to match non-null values",lt:"less than",lte:"less than or equal",gt:"greater than",gte:"greater than or equal",in:"in list (comma-separated values). Supports 'null' and '__null__' (e.g. val1,val2,__null__)",nin:"not in list (comma-separated values). Supports 'null' and '__null__'",contains:"array-contains",containsAny:"array-contains-any (comma-separated values). Supports 'null' and '__null__'"},o=[];for(let{path:s,zodSchema:a}of t){let c=Tn(a);o.push({name:s,in:"query",schema:c,description:`Filter by ${s} (equality). Use 'null' or '__null__' for null values`});for(let i of n){let u=r[i]?` (${r[i]})`:"",f=i==="in"||i==="nin"||i==="containsAny";o.push({name:`${s}__${i}`,in:"query",schema:f?{type:"string",description:"Comma-separated list of values"}:c,description:`Filter ${s} with operator ${i}${u}`});}}return o}function Lr(){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",maximum:100,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)"}}}}function Ws(e){let t=An(e),n=e.orderableFields??t.map(a=>a.path),r=t.map(a=>a.path);if(t.length===0)return Lr();let o=[];for(let{path:a,zodSchema:c}of t){let i=Tn(c),u=it(c),d=u?._zod?.def?.type==="array"||u?._def?.typeName==="ZodArray"||u?._def?.type==="array"?Tn(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"]},d],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:d}],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",maximum:100,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)"}}}}function Gs(e,t,n,r,o,s="QueryRequestBody"){let a={},c=e.name,i=`${t}/${e.name}`,u=`${i}/{${e.documentKey}}`,f={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};a[i]={get:{operationId:`list${ge(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[c],parameters:[...Qs(e),...Vs(e)],responses:{200:Zr(se(n)),500:W("Internal server error")}},post:{operationId:`create${ge(e.name)}`,summary:`Create a ${de(e.name)}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:se(r??n)}}},responses:{201:je("Document created",se(n)),400:W("Validation error"),500:W("Internal server error")}}},a[`${i}/query`]={post:{operationId:`query${ge(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:se(s)}}},responses:{200:Zr(se(n)),400:W("Invalid query"),500:W("Internal server error")}}},a[`${i}/batch`]={post:{operationId:`batch${ge(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:se(`${n}BatchRequest`)}}},responses:{200:je("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:W("Validation error"),403:W("Forbidden"),404:W("Document not found"),500:W("Internal server error")}}};let d={};return d.get={operationId:`get${ge(de(e.name))}`,summary:`Get a single ${de(e.name)}`,tags:[c],parameters:[f],responses:{200:je("Document found",se(n)),404:W("Document not found"),500:W("Internal server error")}},d.put={operationId:`update${ge(de(e.name))}`,summary:`Update a ${de(e.name)} (full replace)`,tags:[c],parameters:[f],requestBody:{required:true,content:{"application/json":{schema:se(o??n)}}},responses:{200:je("Document updated",se(n)),400:W("Validation error"),404:W("Document not found"),500:W("Internal server error")}},d.patch={operationId:`patch${ge(de(e.name))}`,summary:`Partially update a ${de(e.name)}`,tags:[c],parameters:[f],requestBody:{required:true,content:{"application/json":{schema:{allOf:[se(o??n)],description:"All fields are optional for partial updates"}}}},responses:{200:je("Document patched",se(n)),400:W("Validation error"),404:W("Document not found"),500:W("Internal server error")}},e.allowDelete&&(d.delete={operationId:`delete${ge(de(e.name))}`,summary:`Delete a ${de(e.name)}`,tags:[c],parameters:[f],responses:{200:je("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:W("Document not found"),500:W("Internal server error")}}),a[u]=d,a}function Cn(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={},d=[];u.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},u.QueryRequestBody=Lr();for(let[S,b]of Object.entries(e)){let w=ge(de(S)),p=`${w}Create`,h=`${w}Update`,l=`${w}QueryRequestBody`;u[w]=jt(b.schema),u[l]=Ws(b);let k=T=>{let P=T&&T.length>0?T:Object.keys(b.schema.shape),E={};for(let I of P){let O=I.split(".")[0];O&&b.schema.shape[O]&&!b.systemKeys.includes(O)&&(E[O]=b.schema.shape[O]);}return E},y=null,R=k(b.createFields);Object.keys(R).length>0&&(u[p]=jt(zod.z.object(R)),y=p);let v=null,C=k(b.mutableFields);Object.keys(C).length>0&&(u[h]=jt(zod.z.object(C)),v=h),u[`${w}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",enum:["create"]},data:se(y??w)},required:["type","data"]},{type:"object",properties:{type:{type:"string",enum:["update"]},id:{type:"string"},data:{allOf:[se(v??w)],description:"Partial updates allowed"}},required:["type","id","data"]},...b.allowDelete?[{type:"object",properties:{type:{type:"string",enum:["delete"]},id:{type:"string"}},required:["type","id"]}]:[]]}}},required:["operations"]};let A=Gs(b,i,w,y,v,l);Object.assign(f,A),d.push({name:S,description:`Operations on ${S} (collection: ${b.path})`});}let g={},x;return c==="basic"?(g.basicAuth={type:"http",scheme:"basic"},x=[{basicAuth:[]}]):c==="bearer"&&(g.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},x=[{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(g).length>0?{securitySchemes:g}:{}},...x?{security:x}:{},tags:d}}function ge(e){return e.charAt(0).toUpperCase()+e.slice(1)}function de(e){return e.endsWith("ies")?e.slice(0,-3)+"y":e.endsWith("ses")||e.endsWith("xes")||e.endsWith("zes")?e.slice(0,-2):e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e}var Me=class extends Error{constructor(n,r){super("Request validation failed");this.zodError=n;this.source=r;this.statusCode=400;this.name="ValidationError";}};var ct=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},lt=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function Ur(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function Qr(e,t){return t instanceof Me?e.json({success:false,error:"Validation failed",issues:Ur(t.zodError)},400):t instanceof ct?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof lt?e.json({success:false,error:"Output validation failed",issues:Ur(t.zodError)},500):null}zodToOpenapi.extendZodWithOpenApi(zod.z);var Vr="Successful response",Wr="Error response";function ta(e){return e==="get"?"query":"json"}function na(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function ra(e){if(typeof e.safeParse=="function")return {description:Wr,schema:e};let t=e;return {description:t.description??Wr,schema:t.schema}}function Jr(e,t,n,r){let o=new zodToOpenapi.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??ta(i),f=aa(t,c.path??"/"),d=c.status??200,g=oa(i,u,c.input),x=Gr(u,c.input,"query"),m=Gr(u,c.input,"param"),S=ia(i,f),b=na(c.output,r),w={[d]:b?{description:Vr,content:{"application/json":{schema:b}}}:{description:Vr}};if(r?.errors)for(let[p,h]of Object.entries(r.errors)){let{description:l,schema:k}=ra(h);w[p]=k?{description:l,content:{"application/json":{schema:k}}}:{description:l};}o.registerPath({method:i,path:sa(f),operationId:S,summary:c.summary,description:c.description,tags:c.tags,deprecated:c.deprecated,security:c.security,request:{...x?{query:x}:{},...m?{params:m}:{},...g?{body:g}:{}},responses:w});}return new zodToOpenapi.OpenApiGeneratorV31(o.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security})}function oa(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 Gr(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function sa(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function aa(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function ia(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function Xr(e,t){let n=e.replace(/"/g,""");return `<!doctype html>
|
|
1141
|
+
`;function et(){return jsxRuntime.jsx("script",{dangerouslySetInnerHTML:{__html:vr}})}an();function ve(e){return "<!DOCTYPE html>"+server.renderToString(e)}var Ss=["corporate","silk","dark"],ks=()=>jsxRuntime.jsxs("div",{class:"dropdown dropdown-end","data-frs-theme-switcher":true,children:[jsxRuntime.jsxs("button",{type:"button",tabIndex:0,class:"btn btn-sm btn-ghost text-neutral-content gap-1.5","aria-label":"Switch theme",children:[jsxRuntime.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:[jsxRuntime.jsx("circle",{cx:"12",cy:"12",r:"4"}),jsxRuntime.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"})]}),jsxRuntime.jsx("span",{class:"text-xs hidden sm:inline","data-frs-theme-current":true,children:"Theme"})]}),jsxRuntime.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:Ss.map(e=>jsxRuntime.jsx("li",{children:jsxRuntime.jsxs("button",{type:"button","data-frs-theme":e,class:"capitalize justify-between",children:[jsxRuntime.jsx("span",{children:e}),jsxRuntime.jsx("span",{class:"hidden text-primary","data-frs-theme-check":e,children:"\u2713"})]})},e))})]}),we=({opts:e,children:t})=>{let{title:n,breadcrumb:r,flash:o,basePath:s="/"}=e;return jsxRuntime.jsxs("html",{lang:"en","data-theme":"corporate",children:[jsxRuntime.jsxs("head",{children:[jsxRuntime.jsx("meta",{charset:"UTF-8"}),jsxRuntime.jsx("meta",{name:"viewport",content:"width=device-width, initial-scale=1"}),jsxRuntime.jsxs("title",{children:[n," \u2014 FRS Admin"]}),jsxRuntime.jsx("script",{dangerouslySetInnerHTML:{__html:"(function(){try{var t=localStorage.getItem('frs-admin-theme');if(t){document.documentElement.setAttribute('data-theme',t);}}catch(_){}})();"}}),jsxRuntime.jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/themes.css",rel:"stylesheet",type:"text/css"}),jsxRuntime.jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/daisyui.css",rel:"stylesheet",type:"text/css"}),jsxRuntime.jsx("script",{src:"https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"})]}),jsxRuntime.jsxs("body",{class:"bg-base-200/50 min-h-screen flex flex-col",children:[jsxRuntime.jsxs("div",{class:"navbar bg-neutral text-neutral-content shadow-sm sticky top-0 z-50 px-6",children:[jsxRuntime.jsx("div",{class:"flex-1",children:jsxRuntime.jsx("a",{href:s,class:"font-bold text-lg tracking-tight hover:opacity-80 transition-opacity",children:"FRS Admin"})}),jsxRuntime.jsx("div",{class:"flex-none",children:jsxRuntime.jsx(ks,{})})]}),jsxRuntime.jsxs("main",{class:"px-6 py-8 w-full flex-1",children:[r&&r.length>0&&jsxRuntime.jsx("div",{class:"text-sm breadcrumbs mb-4",children:jsxRuntime.jsx("ul",{children:r.map((a,c)=>a.href?jsxRuntime.jsx("li",{children:jsxRuntime.jsx("a",{href:a.href,children:a.label})},c):jsxRuntime.jsx("li",{class:"text-base-content/60",children:a.label},c))})}),jsxRuntime.jsx("h1",{class:"text-2xl font-bold mb-6",children:n}),o&&jsxRuntime.jsxs("div",{role:"alert",class:`alert ${o.type==="success"?"alert-success":o.type==="warning"?"alert-warning":"alert-error"} mb-6`,children:[jsxRuntime.jsx("span",{class:"flex-1",children:o.message}),o.action&&jsxRuntime.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]}),jsxRuntime.jsx(sn,{basePath:s}),jsxRuntime.jsx(et,{})]})]})};function cn(e,t){return ve(jsxRuntime.jsx(we,{opts:t,children:jsxRuntime.jsx("div",{dangerouslySetInnerHTML:{__html:e}})}))}function ln(e,t){return ve(jsxRuntime.jsx(we,{opts:{title:"Repositories",basePath:t},children:e.length===0?jsxRuntime.jsxs("div",{class:"text-center py-20 text-base-content/50",children:[jsxRuntime.jsx("p",{class:"text-lg font-medium mb-1",children:"No repositories configured"}),jsxRuntime.jsx("p",{class:"text-sm",children:"Add a repository to your FRS config to get started."})]}):jsxRuntime.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=>jsxRuntime.jsx("a",{href:`${t}/${n.name}`,class:"card bg-base-100 border border-base-300 hover:shadow-md no-underline transition-shadow",children:jsxRuntime.jsxs("div",{class:"card-body p-5",children:[jsxRuntime.jsx("h2",{class:"card-title text-sm font-semibold",children:n.name}),jsxRuntime.jsx("p",{class:"text-xs text-base-content/50 font-mono",children:n.path})]})},n.name))})}))}var kr=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],Ts=[{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"}],As=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function Cs(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return Ts;case "ZodBoolean":return kr;case "ZodArray":return As;default:return kr}}var Re="__null__";function Os(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="${Re}"]');if(!o){o=document.createElement('option');o.value='${Re}';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='${Re}';i.readOnly=true;}i.style.opacity='0.55';}else{i.style.opacity='';if(i.tagName==='SELECT'){var o2=i.querySelector('option[value="${Re}"][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!=='${Re}')?i.dataset._prev:'';}}})(this)`}function Es(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 jsxRuntime.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:[jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",checked:t,onchange:Os(e)}),jsxRuntime.jsx("span",{children:"\u2205"})]})}function Ps({col:e,active:t}){let n=t?.value??"",r=n===Re,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 jsxRuntime.jsxs("div",{class:"flex flex-wrap items-center gap-1 w-full",children:[jsxRuntime.jsx("input",{type:"hidden",id:o,name:`fv_${e.name}`,value:n}),e.enumValues.map(u=>jsxRuntime.jsxs("label",{class:"flex items-center gap-1 text-xs border border-base-300 rounded px-2 cursor-pointer hover:bg-base-200",children:[jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",value:u,checked:c.has(u),"data-enum-group":i,onchange:Es(o,i)}),jsxRuntime.jsx("span",{children:u})]},u))]})}return jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsxRuntime.jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),e.enumValues.map(c=>jsxRuntime.jsx("option",{value:c,selected:n===c,children:c},c)),e.nullable&&jsxRuntime.jsx("option",{value:Re,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsxRuntime.jsx(ot,{inputId:o,active:r})]})}if(e.zodType==="ZodBoolean")return jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsxRuntime.jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),jsxRuntime.jsx("option",{value:"true",selected:n==="true",children:"true"}),jsxRuntime.jsx("option",{value:"false",selected:n==="false",children:"false"}),e.nullable&&jsxRuntime.jsx("option",{value:Re,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsxRuntime.jsx(ot,{inputId:o,active:r})]});if(e.zodType==="ZodArray"){let c=t?.op==="array-contains-any";return jsxRuntime.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"?jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.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&&jsxRuntime.jsx(ot,{inputId:o,active:r})]}):e.zodType==="ZodDate"?jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.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&&jsxRuntime.jsx(ot,{inputId:o,active:r})]}):jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.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&&jsxRuntime.jsx(ot,{inputId:o,active:r})]})}function dn({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 jsxRuntime.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:[jsxRuntime.jsxs("summary",{class:"collapse-title text-sm font-medium py-2 min-h-0",children:["Filters",s&&jsxRuntime.jsxs("span",{class:"badge badge-primary badge-sm ml-2",children:[n.length," active"]})]}),jsxRuntime.jsx("div",{class:"collapse-content pb-4 pt-2",children:jsxRuntime.jsxs("form",{method:"get",action:e,children:[jsxRuntime.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=Cs(i.zodType),f=o[i.name],d=f?.op??u[0].value;return jsxRuntime.jsxs("div",{class:"flex flex-col gap-1.5",children:[jsxRuntime.jsx("label",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:i.name}),jsxRuntime.jsxs("div",{class:"flex gap-1.5",children:[u.length>1?jsxRuntime.jsx("select",{name:`fo_${i.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:u.map(g=>jsxRuntime.jsx("option",{value:g.value,selected:g.value===d,children:g.label},g.value))}):jsxRuntime.jsx("input",{type:"hidden",name:`fo_${i.name}`,value:u[0].value}),jsxRuntime.jsx(Ps,{col:i,active:f})]})]},i.name)})}),jsxRuntime.jsxs("div",{class:"flex flex-wrap gap-2 mt-4 pt-3 border-t border-base-200 items-center",children:[jsxRuntime.jsx("button",{type:"submit",class:"btn btn-sm btn-primary",children:"Apply"}),s&&jsxRuntime.jsx("a",{href:e,class:"btn btn-sm btn-ghost",children:"Clear"}),a&&jsxRuntime.jsxs("span",{class:"text-xs text-warning ml-auto flex items-center gap-1",children:[jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-4 w-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:jsxRuntime.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 un(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 ve(jsxRuntime.jsx(we,{opts:{title:a,breadcrumb:c,basePath:o,flash:s},children:jsxRuntime.jsx("div",{class:"card bg-base-100 border border-base-300",children:jsxRuntime.jsx("div",{class:"card-body p-6",children:jsxRuntime.jsx("div",{dangerouslySetInnerHTML:{__html:t}})})})}))}At();on();function pn(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 Tr(e,t,n,r,o){let s=pn(e,r,o);return s.set("cursor",t),s.set("dir",n),`?${s.toString()}`}function $s(e,t,n,r){let o=pn(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 Is(e,t,n){return `?${pn(t,n,e).toString()}`}function fn(e,t,n,r,o,s,a=[],c=[],i=false,u=[],f,d,g,x,m,S,b,w=false){let p=`${r}/${e}`,h=`${p}/create`,l={};if(b)for(let T of n)l[T]=tt(nt(b,T));let k=(S??[]).filter(T=>true),y=k.length>0,R=i,v=R||y,C=k.map(T=>{let P=nt(b,T),E=tt(P),I=a.find(O=>O.name===T);return {name:T,type:E,enumValues:I?.enumValues??null,nullable:I?.nullable??false}}),A=[];return b&&(A=ae(b).filter(P=>k.includes(P.name))),ve(jsxRuntime.jsxs(we,{opts:{title:e,breadcrumb:[{label:"Repositories",href:r},{label:e}],basePath:r,flash:s},children:[a.length>0&&jsxRuntime.jsx(dn,{action:p,columnMeta:a,activeFilters:c,isGroup:x}),g&&jsxRuntime.jsxs("div",{role:"alert",class:`alert ${g.type==="index"?"alert-warning":"alert-error"} mb-6 shadow-sm`,children:[jsxRuntime.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:g.type==="index"?jsxRuntime.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"}):jsxRuntime.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"})}),jsxRuntime.jsxs("div",{class:"flex-1",children:[jsxRuntime.jsx("h3",{class:"font-bold",children:g.type==="index"?"Composite index required":"Query failed"}),jsxRuntime.jsx("div",{class:"text-sm",children:g.message})]}),g.indexUrl&&jsxRuntime.jsx("a",{href:g.indexUrl,target:"_blank",rel:"noopener noreferrer",class:"btn btn-sm btn-outline",children:"Create Index \u2192"})]}),jsxRuntime.jsxs("div",{class:"flex flex-wrap justify-between items-center mb-4 gap-3","data-frs-toolbar":true,children:[jsxRuntime.jsxs("div",{class:"flex items-center gap-3",children:[jsxRuntime.jsxs("span",{class:"text-sm text-base-content/60",children:[t.length,typeof m=="number"&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[" ","of"," ",jsxRuntime.jsx("span",{class:"font-semibold text-base-content/80",children:m})]})," ","document",(typeof m=="number"?m:t.length)!==1&&"s"]}),jsxRuntime.jsxs("div",{class:"flex items-center gap-1.5 text-sm text-base-content/60",children:[jsxRuntime.jsx("span",{children:"Rows"}),jsxRuntime.jsx("div",{class:"join",children:[10,25,50,100].map(T=>jsxRuntime.jsx("a",{href:Is(T,c,f),class:`join-item btn btn-xs ${d===T?"btn-active btn-primary":"btn-outline"}`,children:T},T))})]})]}),jsxRuntime.jsxs("div",{class:"flex gap-2",children:[jsxRuntime.jsx("form",{method:"post",action:`${p}/_bulk/backfill`,onsubmit:"return confirm('Backfill entire repository? This will scan all documents and fill missing system keys.')",children:jsxRuntime.jsx("button",{type:"submit",class:"btn btn-outline btn-sm",children:"Backfill"})}),jsxRuntime.jsx("a",{href:h,class:"btn btn-primary btn-sm",children:"+ New"})]})]}),v&&jsxRuntime.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 m=="number"?String(m):"","data-frs-page-size":String(d??t.length),"data-frs-allow-delete":R?"1":"0","data-frs-allow-update":y?"1":"0","data-frs-fields":JSON.stringify(C),"data-frs-filters":JSON.stringify(c),children:[jsxRuntime.jsxs("div",{class:"flex-1 text-sm",children:[jsxRuntime.jsx("span",{"data-frs-bulk-summary":true,children:"0 selected"}),typeof m=="number"&&m>t.length&&jsxRuntime.jsxs("button",{type:"button",class:"ml-3 link text-sm hidden","data-frs-bulk-select-all":true,children:["Select all ",m," matching documents"]}),jsxRuntime.jsxs("span",{class:"hidden ml-3 italic","data-frs-bulk-all-active":true,children:["All ",m??"?"," matching documents are selected."," ",jsxRuntime.jsx("button",{type:"button",class:"link","data-frs-bulk-clear":true,children:"Clear selection"})]})]}),jsxRuntime.jsxs("div",{class:"flex gap-2",children:[y&&jsxRuntime.jsx("button",{type:"button",class:"btn btn-sm btn-outline","data-frs-bulk-action":"update",children:"Update field\u2026"}),R&&jsxRuntime.jsx("button",{type:"button",class:"btn btn-sm btn-error btn-outline","data-frs-bulk-action":"delete",children:"Delete"})]})]}),jsxRuntime.jsx("div",{class:"overflow-x-auto rounded-box border border-base-300 bg-base-100","data-frs-table-wrap":true,children:jsxRuntime.jsxs("table",{class:"table table-sm w-full","data-frs-table":true,"data-frs-repo":e,"data-frs-colcount":n.length,children:[jsxRuntime.jsx("thead",{children:jsxRuntime.jsxs("tr",{class:"bg-base-200/50",children:[v&&jsxRuntime.jsx("th",{class:"w-8",children:jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-page":true,"aria-label":"Select all on this page"})}),[...n].map((T,P)=>{let E=f?.field===T,I=E?f.dir==="asc"?" \u25B2":" \u25BC":"";return jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:jsxRuntime.jsxs("a",{href:$s(T,f,c,d),class:`hover:text-base-content inline-flex items-center gap-0.5${E?" text-primary font-bold":""}`,children:[T,I]})},P)}),u.map((T,P)=>jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:T.column},`rel-${P}`)),jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide text-right",children:"Actions"})]})}),jsxRuntime.jsx("tbody",{children:t.length===0?jsxRuntime.jsx("tr",{children:jsxRuntime.jsx("td",{colspan:n.length+u.length+1+(v?1:0),class:"text-center py-16 text-base-content/40",children:"No documents found"})}):t.map((T,P)=>{let E=String(T.docId??T.id??""),I=`${r}/${e}/${encodeURIComponent(E)}/edit`,O=`${r}/${e}/${encodeURIComponent(E)}/delete`;return jsxRuntime.jsxs("tr",{class:"hover","data-frs-row-id":E,children:[v&&jsxRuntime.jsx("td",{class:"align-middle py-2",children:jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-row":true,value:E,"aria-label":`Select ${E}`})}),n.map(($,F)=>{let z=T[$],j=l[$],_=j?rt(j,z):null;return jsxRuntime.jsx("td",{class:"align-top py-2",children:jsxRuntime.jsx(De,{val:z,mismatch:_})},F)}),u.map(($,F)=>{let z=T[$.key];if(z==null||z==="")return jsxRuntime.jsx("td",{class:"py-2"},`rel-${F}`);let j=$.type==="one"?`${r}/${$.targetRepo}/${encodeURIComponent(String(z))}/edit`:`${r}/${$.targetRepo}?fv_${$.targetKey}=${encodeURIComponent(String(z))}`;return jsxRuntime.jsx("td",{class:"align-middle py-2",children:jsxRuntime.jsx("a",{href:j,class:"btn btn-xs btn-ghost btn-outline","data-frs-relation":true,"data-frs-rel-type":$.type,"data-frs-rel-repo":$.targetRepo,"data-frs-rel-fk":$.targetKey,"data-frs-rel-val":String(z),"data-frs-rel-label":$.column,children:$.column})},`rel-${F}`)}),jsxRuntime.jsx("td",{class:"align-middle text-right whitespace-nowrap py-2",children:jsxRuntime.jsxs("div",{class:"flex gap-1 justify-end",children:[jsxRuntime.jsx("a",{href:I,class:"btn btn-xs btn-outline",children:"Edit"}),w&&jsxRuntime.jsx("a",{href:`${r}/${e}/${encodeURIComponent(E)}/history`,class:"btn btn-xs btn-outline",title:"View change history",children:"History"}),i&&jsxRuntime.jsx("form",{method:"post",action:O,onsubmit:"return confirm('Delete this document?')",children:jsxRuntime.jsx("button",{type:"submit",class:"btn btn-xs btn-error btn-outline",children:"Delete"})})]})})]},P)})})]})}),(o.hasPrev||o.hasNext)&&jsxRuntime.jsxs("div",{class:"flex flex-col items-center mt-6 gap-2",children:[jsxRuntime.jsxs("div",{class:"flex justify-center items-center gap-2",children:[o.hasPrev?jsxRuntime.jsx("a",{href:Tr(c,o.prevCursor,"prev",f,d),class:"btn btn-sm btn-outline",children:"\u2190 Previous"}):jsxRuntime.jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"\u2190 Previous"}),o.hasNext?jsxRuntime.jsx("a",{href:Tr(c,o.nextCursor,"next",f,d),class:"btn btn-sm btn-outline",children:"Next \u2192"}):jsxRuntime.jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"Next \u2192"})]}),typeof m=="number"&&jsxRuntime.jsxs("div",{class:"text-xs text-base-content/50",children:[m," total document",m!==1?"s":"",c.length>0?" matching filters":""]})]}),v&&y&&jsxRuntime.jsxs("dialog",{id:"frs-bulk-update-modal",class:"modal",children:[jsxRuntime.jsxs("div",{class:"modal-box",children:[jsxRuntime.jsx("h3",{class:"font-bold text-lg mb-3",children:"Bulk update field"}),jsxRuntime.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."}),jsxRuntime.jsxs("form",{method:"dialog","data-frs-bulk-update-form":true,"data-frs-form":true,children:[jsxRuntime.jsxs("label",{class:"form-control w-full mb-3",children:[jsxRuntime.jsx("div",{class:"label",children:jsxRuntime.jsx("span",{class:"label-text text-xs uppercase tracking-wide",children:"Field"})}),jsxRuntime.jsxs("select",{class:"select select-bordered select-sm w-full",name:"field",required:true,"data-frs-bulk-field-select":true,children:[jsxRuntime.jsx("option",{value:"",children:"\u2014 Select a field \u2014"}),k.map(T=>jsxRuntime.jsx("option",{value:T,children:T},T))]})]}),jsxRuntime.jsx("div",{class:"mb-4","data-frs-bulk-value-container":true}),jsxRuntime.jsxs("div",{class:"modal-action",children:[jsxRuntime.jsx("button",{type:"button",class:"btn btn-sm btn-ghost","data-frs-bulk-update-cancel":true,children:"Cancel"}),jsxRuntime.jsx("button",{type:"submit",class:"btn btn-sm btn-primary","data-frs-bulk-update-submit":true,children:"Apply"})]})]})]}),jsxRuntime.jsx("form",{method:"dialog",class:"modal-backdrop",children:jsxRuntime.jsx("button",{children:"close"})})]}),jsxRuntime.jsx("div",{class:"hidden","data-frs-bulk-templates":true,children:A.map(T=>jsxRuntime.jsx("div",{"data-frs-bulk-template-for":T.name,dangerouslySetInnerHTML:{__html:Xe(T)}},T.name))})]}))}function st(e,t){return cn(e,t)}function yn(e,t){return ln(e,t)}function mn(e,t,n,r,o,s,a,c,i,u,f,d,g,x,m,S,b,w){return fn(e,t,n,r,o,s,a,c,i,u,f,d,g,x,m,S,b,w)}function Se(e,t,n,r,o,s){return un(e,t,n,r,o,s)}var gn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function js(){let e="";for(;e.length<20;){let t=crypto.randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let r=t[n];r>=gn.length*4||(e+=gn.charAt(r%gn.length));}}return e}async function Ar(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 Ot(e,t){if(!t)return;let n=e[t];if(typeof n!="string"||!n)return;let r=n.split("/").filter(Boolean),o=[];for(let s=1;s<r.length;s+=2)o.push(r[s]);return o.length>0?o:void 0}async function _e(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 hn(e,t,n){let r=e.documentKey??"docId",o=Ye(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 N(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function Et(e,t){e.status(302).set("Location",t).send("");}function Pt(e,t){let n=t.shape,r={};for(let[o,s]of Object.entries(n)){let a=xn(s),c=Z(a),i=c==="ZodObject",u=a,f=false;if(c==="ZodUnion"){let x=We(a);x.some(S=>Z(S)==="ZodDate")&&(f=true);let m=x.find(S=>{if(Z(S)==="ZodObject"){let b=te(S);return "latitude"in b&&"longitude"in b}return false});m&&(i=true,u=m);}if(e[o+"__isnull"]==="1"){r[o]=null;continue}if(i){let x={},m=false;for(let[w,p]of Object.entries(e))w.startsWith(`${o}.`)&&(x[w.slice(o.length+1)]=p,m=true);if(m){r[o]=Pt(x,u);continue}let S=e[o],b=Array.isArray(S)?S[S.length-1]:S;if(b)try{r[o]=JSON.parse(b);}catch{r[o]=b;}continue}let d=e[o],g=Array.isArray(d)?d[d.length-1]:d;if(g===void 0||g===""){c==="ZodBoolean"&&(r[o]=false);continue}if(f){r[o]=new Date(g);continue}switch(c){case "ZodBoolean":g==="__null__"?r[o]=null:r[o]=g==="true"||g==="on"||g==="1";break;case "ZodNumber":case "ZodBigInt":r[o]=Number(g);break;case "ZodDate":r[o]=new Date(g);break;case "ZodArray":try{r[o]=JSON.parse(g);}catch{r[o]=g;}break;default:if(g.startsWith("{")||g.startsWith("["))try{r[o]=JSON.parse(g);break}catch{}r[o]=g;}}return r}function Cr(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 Er(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=ee(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=Le(t);if(!r)return n;t=r;}else return n}}function xn(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=ee(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=Le(t);if(!r)return t;t=r;}else return t}}function Pr(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable")return true;if(n==="ZodDefault"){t=ee(t);continue}return false}}function $r(e){let t=xn(e),n=Z(t);if(n==="ZodEnum"){let r=Ue(t);return r.length>0?r:void 0}if(n==="ZodNativeEnum"){let r=Qe(t),o=Object.values(r).filter(s=>typeof s=="string");return o.length>0?o:void 0}if(n==="ZodLiteral"){let r=Ve(t);return typeof r=="string"?[r]:void 0}}function Ir(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=xn(t.shape[o]),i=Z(c),u=i==="ZodObject",f=c,d=false;if(i==="ZodUnion"){let g=We(c);g.some(m=>Z(m)==="ZodDate")&&(d=true);let x=g.find(m=>{if(Z(m)==="ZodObject"){let S=te(m);return "latitude"in S&&"longitude"in S}return false});x&&(u=true,f=x);}if(u&&typeof a=="object"&&a!==null&&!Array.isArray(a)&&!("_seconds"in a)&&typeof a.toDate!="function"){let g=Ir(a,f,s);Object.assign(r,g);}else if(i==="ZodDate"||d){let g=Cr(a);g!==null&&(r[s]=g);}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)&&("_seconds"in a||typeof a.toDate=="function")){let g=Cr(a);r[s]=g??JSON.stringify(a,null,2);}else typeof a=="object"?r[s]=JSON.stringify(a,null,2):r[s]=String(a);}return r}function bn(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?bn(n.nested,t):void 0}))}function Ms(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 Or(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 Dr(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=Er(a);if(c==="ZodObject"){let i=a;for(;;){let f=Z(i);if(f==="ZodOptional"||f==="ZodNullable"||f==="ZodDefault")i=ee(i);else break}let u=te(i);r.push(...Dr(Object.keys(u),i,s));}else r.push({name:s,zodType:c,nullable:Pr(a),enumValues:$r(a)});}return r}function zs(e,t){let n=t.split("."),r=e;for(let o of n){for(;;){let a=Z(r);if(a==="ZodOptional"||a==="ZodNullable"||a==="ZodDefault")r=ee(r);else break}let s=te(r);if(!(o in s))return null;r=s[o];}return r}function Ce(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=Z(c);if(i==="ZodOptional"||i==="ZodNullable"||i==="ZodDefault")c=ee(c);else break}if(Z(c)!=="ZodObject"){o[s]=e.shape[s];continue}o[s]=Ce(c,a);}return zod.z.object(o)}function le(e,t,n){return ce(e,t,n)}function _r(e,t,n){let r=(h,l)=>{let k=le(h,t,n),y=Object.values(e).map(R=>({name:R.name,path:R.path}));N(l,yn(y,k));},o=async(h,l)=>{let k=h.params.repoName;if(!k){N(l,"Bad request",400);return}let y=e[k];if(!y){N(l,"Repository not found",404);return}let R=y.pageSize??25,v=h.query??{},C=v.cursor,A=v.dir==="prev"?"prev":"next",T=v.ob??"",P=v.od==="desc"?"desc":"asc",E=T?{field:T,dir:P}:void 0,I=parseInt(v.ps??""),O=Number.isFinite(I)&&I>0?Math.min(I,200):R,$=y.listColumns??Object.keys(y.schema.shape),F=y.documentKey??"docId",z=[F,...$.filter(oe=>oe!==F)];E&&(new Set([F,...$]).has(E.field)||(E=void 0));let j=y.filterableFields?(()=>{let oe=[];for(let ue of y.filterableFields)(ue.includes(".")||$.includes(ue))&&oe.push(ue);return oe})():$,_=(()=>{let oe=[];for(let ue of j)if(ue.includes(".")){let Pe=zs(y.schema,ue);oe.push({name:ue,zodType:Pe?Er(Pe):"ZodString",nullable:Pe?Pr(Pe):false,enumValues:Pe?$r(Pe):void 0});}else oe.push(...Dr([ue],y.schema));return oe})(),Q=new Set(_.map(oe=>oe.name)),U=Ms(v,Q),J=Or(U),ze;C&&(ze=await Ar(y,C));let[X,dt]=await Promise.all([y.repo.query.paginate({pageSize:O,cursor:ze,direction:A,...J.length>0?{where:J}:{},...E?{orderBy:[{field:E.field,direction:E.dir}]}:{}}).catch(oe=>({queryError:Ye(oe,{ref:y.repo.ref,path:y.path,isGroup:!!y.isGroup,filters:U,sort:E})})),y.repo.aggregate.count(J.length>0?{where:J}:{}).catch(()=>{})]),Ee="queryError"in X,ao=Ee?[]:X.data,io=Ee?"":X.nextCursor?.ref?.path??X.nextCursor?.id??"",co=Ee?"":X.prevCursor?.ref?.path??X.prevCursor?.id??"",lo=Ee?X.queryError:void 0,uo=le(h,t,n),He,ut=v.flash;ut==="created"?He={type:"success",message:"Document created successfully."}:ut==="updated"?He={type:"success",message:"Document updated successfully."}:ut==="deleted"?He={type:"success",message:"Document deleted successfully."}:ut==="backfilled"&&(He={type:"success",message:"Repository backfilled successfully."}),N(l,mn(y.name,ao,z,uo,{hasPrev:Ee?false:X.hasPrevPage,hasNext:Ee?false:X.hasNextPage,prevCursor:co,nextCursor:io},He,_,U,y.allowDelete??false,y.relationalMeta,E,O,lo,y.isGroup,dt,y.mutableFields,y.schema,y.historyEnabled));},s=(h,l)=>{let k=h.params.repoName;if(!k){N(l,"Bad request",400);return}let y=e[k];if(!y){N(l,"Repository not found",404);return}let R=le(h,t,n),v=Ce(y.schema,y.createFields),C=ae(v),A=`${R}/${y.name}/create`,T=xe(C,A,"POST","Create document");N(l,Se(y.name,T,"create",null,R));},a=async(h,l)=>{let k=h.params.repoName;if(!k){N(l,"Bad request",400);return}let y=e[k];if(!y){N(l,"Repository not found",404);return}let R=le(h,t,n),v=h.body??{},C=Pt(v,y.schema),A=Ce(y.schema,y.createFields),T=A.safeParse(C);if(!T.success){let P=ae(A),E=`${R}/${y.name}/create`,I=xe(P,E,"POST","Create document"),O=T.error.issues.map($=>`${$.path.join(".")}: ${$.message}`).join(", ");N(l,Se(y.name,I,"create",null,R,{type:"error",message:`Validation error: ${O}`}),422);return}try{if(y.isGroup&&y.parentKeys&&y.parentKeys.length>0){let P={...T.data};y.createdKey&&(P[y.createdKey]=new Date);let E=y.parentKeys.filter(F=>!P[F]);if(E.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${E.join(", ")}`);let I=y.parentKeys.map(F=>P[F]),O=y.documentKey??"docId",$=P[O]||js();await y.repo.set(...I,$,P);}else await y.repo.create(T.data);Et(l,`${R}/${y.name}?flash=created`);}catch(P){let E=Ce(y.schema,y.createFields),I=ae(E),O=`${R}/${y.name}/create`,$=xe(I,O,"POST","Create document");N(l,Se(y.name,$,"create",null,R,{type:"error",message:`Save error: ${P.message}`}),500);}},c=async(h,l)=>{let k=h.params.repoName,y=h.params.id;if(!k||!y){N(l,"Bad request",400);return}let R=e[k];if(!R){N(l,"Repository not found",404);return}let v=le(h,t,n),C=null;try{C=await _e(R,y);}catch(O){let $=hn(R,y,O),F=Te(O)?424:500;N(l,st("",{title:`Edit ${R.name} / ${y}`,basePath:v,breadcrumb:[{label:"Repositories",href:v},{label:R.name,href:`${v}/${R.name}`},{label:`Edit ${y}`}],flash:$}),F);return}if(!C){N(l,"Document not found",404);return}let A=Ir(C,R.schema),T=Ce(R.schema,R.mutableFields),P=bn(ae(T),A),E=`${v}/${R.name}/${encodeURIComponent(y)}/edit`,I=xe(P,E,"POST","Save changes");N(l,Se(R.name,I,"edit",y,v));},i=async(h,l)=>{let k=h.params.repoName,y=h.params.id;if(!k||!y){N(l,"Bad request",400);return}let R=e[k];if(!R){N(l,"Repository not found",404);return}let v=le(h,t,n),C=h.body??{},A=Pt(C,R.schema),T=Ce(R.schema,R.mutableFields),E=T.partial().safeParse(A);if(!E.success){let I=Object.fromEntries(Object.entries(C).map(([j,_])=>[j,Array.isArray(_)?_.join(","):_??""])),O=bn(ae(T),I),$=`${v}/${R.name}/${encodeURIComponent(y)}/edit`,F=xe(O,$,"POST","Save changes"),z=E.error.issues.map(j=>`${j.path.join(".")}: ${j.message}`).join(", ");N(l,Se(R.name,F,"edit",y,v,{type:"error",message:`Validation error: ${z}`}),422);return}try{let I=await _e(R,y),O=(I&&Ot(I,R.pathKey))??[y];await R.repo.update(...O,E.data),Et(l,`${v}/${R.name}?flash=updated`);}catch(I){let O=Ce(R.schema,R.mutableFields),$=ae(O),F=`${v}/${R.name}/${encodeURIComponent(y)}/edit`,z=xe($,F,"POST","Save changes"),j=Te(I)?hn(R,y,I):{type:"error",message:`Save error: ${I.message}`},_=Te(I)?424:500;N(l,Se(R.name,z,"edit",y,v,j),_);}},u=async(h,l)=>{let k=h.params.repoName,y=h.params.id;if(!k||!y){N(l,"Bad request",400);return}let R=e[k];if(!R){N(l,"Repository not found",404);return}if(!R.allowDelete){N(l,"Delete is not allowed for this repository",403);return}let v=le(h,t,n);try{let C=await _e(R,y),A=(C&&Ot(C,R.pathKey))??[y];await R.repo.delete(...A),Et(l,`${v}/${R.name}?flash=deleted`);}catch(C){let A=Te(C)?hn(R,y,C):{type:"error",message:`Delete error: ${C.message}`},T=Te(C)?424:500;N(l,st("",{title:`Delete ${R.name} / ${y}`,basePath:v,breadcrumb:[{label:"Repositories",href:v},{label:R.name,href:`${v}/${R.name}`},{label:`Delete ${y}`}],flash:A}),T);}},f=async(h,l)=>{let k=h.params.repoName;if(!k){N(l,"Bad request",400);return}let y=e[k];if(!y){N(l,"Repository not found",404);return}let R=le(h,t,n),v=h.query,C=v?.type==="many"?"many":"one",A=Math.max(1,Math.min(100,Number(v?.ps??25)||25)),T=y.listColumns??Object.keys(te(y.schema)),{PanelOne:P,PanelMany:E}=await Promise.resolve().then(()=>(an(),Rr)),{renderToString:I}=await import('hono/jsx/dom/server');if(C==="one"){let _=String(v?.id??"");if(!_){N(l,"<div class='p-6 text-error'>Missing id parameter.</div>",400);return}try{let Q=await _e(y,_),U=I(P({doc:Q,repoName:y.name,basePath:R,schema:y.schema,columns:T}));N(l,U);}catch(Q){N(l,`<div class='p-6 text-error text-sm'>Error: ${Q.message}</div>`,500);}return}let O=String(v?.fk??""),$=String(v?.fv??"");if(!O||!$){N(l,"<div class='p-6 text-error'>Missing fk/fv parameters.</div>",400);return}let F=v?.cursor??"",z=v?.dir==="prev"?"prev":"next",j;F&&(j=await Ar(y,F));try{let _=await y.repo.query.paginate({pageSize:A,cursor:j,direction:z,where:[[O,"==",Hs($)]]}),Q=I(E({docs:_.data,repoName:y.name,basePath:R,fk:O,fv:$,columns:T,schema:y.schema,pagination:{hasPrev:_.hasPrevPage,hasNext:_.hasNextPage,prevCursor:_.prevCursor?.ref?.path??_.prevCursor?.id??"",nextCursor:_.nextCursor?.ref?.path??_.nextCursor?.id??"",pageSize:A}}));N(l,Q);}catch(_){N(l,`<div class='p-6 text-error text-sm'>Error: ${_.message}</div>`,500);}},d=async(h,l)=>{let k=h.params.repoName;if(!k){N(l,"Bad request",400);return}let y=e[k];if(!y){N(l,"Repository not found",404);return}let R=le(h,t,n);try{await y.repo.system.backfillKeys(),Et(l,`${R}/${y.name}?flash=backfilled`);}catch(v){N(l,`<div class="p-6 text-error">Backfill failed: ${v.message}</div>`,500);}},g=async(h,l)=>{let k=[];for(let y of l){let R;if(h.isGroup||h.parentKeys?.length){let v=await _e(h,y);R=v?Ot(v,h.pathKey):void 0;}R||(R=[y]);try{let v=h.repo.documentRef(...R);v&&k.push(v);}catch{}}return k},x=async(h,l)=>{let k=Or(l),y=h.documentKey??"docId",R=[],v;for(;;){let C=await h.repo.query.paginate({pageSize:500,cursor:v,direction:"next",...k.length>0?{where:k}:{}});for(let A of C.data){let T=String(A[y]??A.id??"");T&&R.push(T);}if(!C.hasNextPage||!C.nextCursor)break;v=C.nextCursor;}return R},m=async(h,l)=>{let k=h.params.repoName;if(!k){re(l,{error:"Bad request"},400);return}let y=e[k];if(!y){re(l,{error:"Repository not found"},404);return}if(!y.allowDelete){re(l,{error:"Delete is not allowed for this repository"},403);return}let R=h.body??{};try{let v=await b(y,R);if(v.length===0){re(l,{deleted:0});return}let C=await g(y,v);for(let A=0;A<C.length;A+=500)await y.repo.bulk.delete(C.slice(A,A+500));re(l,{deleted:C.length});}catch(v){re(l,{error:v.message},500);}},S=async(h,l)=>{let k=h.params.repoName;if(!k){re(l,{error:"Bad request"},400);return}let y=e[k];if(!y){re(l,{error:"Repository not found"},404);return}let R=h.body??{},v=String(R.field??"");if(!v){re(l,{error:"Missing 'field'"},400);return}if(!y.mutableFields||!y.mutableFields.includes(v)){re(l,{error:`Field '${v}' is not bulk-updatable`},403);return}let C=y.schema.shape?.[v],A;if(C){let T=typeof y.schema=="object"&&y.schema&&"constructor"in y.schema&&y.schema.constructor.name.includes("Zod")?y.schema.pick({[v]:true}):void 0;if(!T){re(l,{error:"Invalid schema structure"},500);return}A=Pt(R.formPayload??{},T)[v];let E=C.safeParse(A);if(!E.success){re(l,{error:`Invalid value for '${v}': ${E.error.message}`},400);return}A=E.data;}try{let T=await b(y,R);if(T.length===0){re(l,{updated:0});return}let E=(await g(y,T)).map(I=>({docRef:I,data:{[v]:A}}));for(let I=0;I<E.length;I+=500)await y.repo.bulk.update(E.slice(I,I+500));re(l,{updated:E.length});}catch(T){re(l,{error:T.message},500);}};async function b(h,l){if(l.selectAll){let k=w(l.filters,h);return await x(h,k)}return Array.isArray(l.ids)?l.ids.filter(k=>typeof k=="string"&&!!k):[]}function w(h,l){if(!Array.isArray(h))return [];let k=new Set((l.filterableFields??Object.keys(te(l.schema))).map(v=>String(v))),y=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),R=[];for(let v of h)v&&typeof v=="object"&&typeof v.field=="string"&&k.has(v.field)&&typeof v.value=="string"&&y.has(String(v.op))&&R.push({field:v.field,op:v.op,value:v.value});return R}return {handleDashboard:r,handleList:o,handleCreateForm:s,handleCreateSubmit:a,handleEditForm:c,handleEditSubmit:i,handleDelete:u,handlePanel:f,handleBulkDelete:m,handleBulkUpdate:S,handleBulkBackfill:d,handleHistory:async(h,l)=>{let k=h.params.repoName,y=h.params.id;if(!k||!y){N(l,"Bad request",400);return}let R=e[k];if(!R){N(l,"Repository not found",404);return}if(!R.historyEnabled||!R.repo.history){N(l,"History not enabled for this repository",404);return}let v=le(h,t,n),C=R.historySubcollection??"history",A=[y];try{let _=await _e(R,y),Q=_?Ot(_,R.pathKey):void 0;Q&&Q.length>0&&(A=Q);}catch{}let T=parseInt(String(h.query?.limit??"")),P=Number.isFinite(T)&&T>0?Math.min(T,500):100,E=[],I;try{E=await R.repo.history.list(...A,{limit:P});}catch(_){I=_.message;}let O=_=>String(_??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),$=_=>{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">${O(JSON.stringify(_))}</code>`}catch{return O(String(_))}return O(String(_))},F=_=>_?typeof _.toDate=="function"?_.toDate().toISOString():_ instanceof Date?_.toISOString():O(String(_)):"",z=_=>`<span class="badge badge-sm ${_==="create"?"badge-success":_==="delete"?"badge-error":"badge-info"}">${O(_)}</span>`,j="";if(j+='<div class="flex items-center justify-between mb-4">',j+=`<a href="${v}/${R.name}/${encodeURIComponent(y)}/edit" class="btn btn-sm btn-outline">\u2190 Back to edit</a>`,j+=`<a href="${v}/${R.name}" class="btn btn-sm btn-outline">\u2190 Back to list</a>`,j+="</div>",j+=`<p class="text-sm text-base-content/60 mb-4">Subcollection: <code>${O(C)}</code> \xB7 Showing up to ${P} entries.</p>`,I)j+=`<div class="alert alert-error mb-4">${O(I)}</div>`;else if(E.length===0)j+='<div class="alert">No history entries found.</div>';else {j+='<div class="overflow-x-auto"><table class="table table-zebra table-sm">',j+="<thead><tr><th>When</th><th>Op</th><th>User</th><th>Reason / Comment</th><th>Changes</th></tr></thead><tbody>";for(let _ of E){let Q=_.meta??{},U=[Q.reason,Q.comment].filter(X=>X!=null&&X!=="").map(X=>O(String(X))).join(" \u2014 "),J="",ze=Object.keys(_.changes??{});ze.length===0?J='<span class="opacity-40">\u2014</span>':J='<ul class="space-y-1">'+ze.map(X=>{let dt=_.changes[X];return `<li><strong>${O(X)}</strong>: ${$(dt.oldValue)} \u2192 ${$(dt.newValue)}</li>`}).join("")+"</ul>",j+="<tr>",j+=`<td class="whitespace-nowrap text-xs font-mono">${O(F(_.historySetAt))}</td>`,j+=`<td>${z(_.operation??"update")}</td>`,j+=`<td class="text-xs">${O(Q.userEmail??Q.userId??"")}</td>`,j+=`<td class="text-xs">${U}</td>`,j+=`<td>${J}</td>`,j+="</tr>";}j+="</tbody></table></div>";}N(l,st(j,{title:`History \u2014 ${R.name} / ${y}`,basePath:v,breadcrumb:[{label:"Repositories",href:v},{label:R.name,href:`${v}/${R.name}`},{label:`History ${y}`}]}));}}}function re(e,t,n=200){e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(t));}function Hs(e){return e==="true"?true:e==="false"?false:e!==""&&!isNaN(Number(e))?Number(e):e}It();async function Ns(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function Bs(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 zr(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[x,m]of Object.entries(n)){if(!m.repo)throw new Error(`[createAdminServer] Repository "${x}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let S=m.schema??m.repo.schema??null;if(!S)throw new Error(`[createAdminServer] Repository "${x}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let b,w,p;if(m.fieldsConfig){let k=m.fieldsConfig;b=[],w=[],p=[];for(let[y,R]of Object.entries(k))for(let v of R)v==="filterable"?b.push(y):v==="mutable"?w.push(y):v==="create"&&p.push(y);b.length===0&&(b=void 0),w.length===0&&(w=void 0),p.length===0&&(p=void 0);}let h=(()=>{let k=m.repo._parentKeys;return k&&k.length>0?k:void 0})();if(h&&p)for(let k of h)p.includes(k)||p.push(k);let l={name:x,path:m.path,repo:m.repo,schema:S,documentKey:m.documentKey??"docId",pathKey:m.repo._pathKey??void 0,isGroup:!!m.repo._isGroup,parentKeys:h,createdKey:m.repo._createdKey??void 0,listColumns:m.listColumns,pageSize:m.pageSize,filterableFields:b,mutableFields:w,createFields:p,allowDelete:m.allowDelete??false,historyEnabled:!!m.repo._historyConfig?.enabled,historySubcollection:(m.repo._historyConfig?.enabled&&m.repo._historySubcollection)??void 0,relationalMeta:(()=>{if(!m.relationalFields||m.relationalFields.length===0)return;let k=m.repo.relationalKeys??{},y=[];for(let R of m.relationalFields){let v=k[R.key];v&&y.push({key:v.sourceKey?String(v.sourceKey):R.key,column:R.column,targetRepo:String(v.repo),targetKey:String(v.key),type:v.type});}return y.length>0?y:void 0})()};u[x]=l;}let f=_r(u,i,Gn(c?.region)),d=new fe;if(o!==false&&d.use($t(o===void 0?{}:o)),r&&d.use(async(x,m,S)=>{let b=x,w=String(b.headers?.["content-type"]??"");if(w.includes("application/x-www-form-urlencoded")){let p=await Ns(b);x.body=Bs(p);}else if(w.includes("application/json")&&typeof b.body=="string")try{x.body=JSON.parse(b.body);}catch{}await S();}),s)if(Ke(s)){for(let x of s.routes){let m=`${i}${x.path}`;x.method==="GET"?d.get(m,x.handler):d.post(m,x.handler);}d.use(s.middleware);}else if(typeof s=="function")d.use(s);else {let x=s.realm??"Admin",m="Basic "+Buffer.from(`${s.username}:${s.password}`).toString("base64");d.use((S,b,w)=>{if((S.headers?.authorization??"")!==m){b.status(401).set("WWW-Authenticate",`Basic realm="${x}"`).set("Content-Type","text/plain").send("Unauthorized");return}w();});}for(let x of a)d.use(x);d.get(`${i}/`,f.handleDashboard),d.get(`${i}`,f.handleDashboard),d.get(`${i}/:repoName/_panel`,f.handlePanel),d.post(`${i}/:repoName/_bulk/delete`,f.handleBulkDelete),d.post(`${i}/:repoName/_bulk/update`,f.handleBulkUpdate),d.post(`${i}/:repoName/_bulk/backfill`,f.handleBulkBackfill),d.get(`${i}/:repoName`,f.handleList),d.get(`${i}/:repoName/create`,f.handleCreateForm),d.post(`${i}/:repoName/create`,f.handleCreateSubmit),d.get(`${i}/:repoName/:id/edit`,f.handleEditForm),d.post(`${i}/:repoName/:id/edit`,f.handleEditSubmit),d.get(`${i}/:repoName/:id/history`,f.handleHistory),d.post(`${i}/:repoName/:id/delete`,f.handleDelete);let g=async(x,m)=>{await d.handle(x,m);};return c&&(g.httpsOptions=c),g}function Sn(e,t,n=200){let r=V(t);return e.json(r,n)}function Oe(e,t,n,r=200){return Sn(e,{success:true,data:t,meta:n},r)}function M(e,t,n=400){return Sn(e,{success:false,error:t},n)}function wn(e,t,n,r,o){let s=Ye(t,n),a=s.type==="index",c=a?424:500,u={success:false,error:a?s.message:o&&t instanceof Error?t.message:r};return a&&(u.errorType="index",s.indexUrl&&(u.indexUrl=s.indexUrl)),Sn(e,u,c)}var Rn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Hr(){let e="";for(;e.length<20;){let t=crypto.randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let r=t[n];r>=Rn.length*4||(e+=Rn.charAt(r%Rn.length));}}return e}function Fe(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return zod.z.preprocess(r=>Kt(r)??r,e);if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[s,a]of Object.entries(r))o[s]=Fe(a);return zod.z.object(o)}if(n==="ZodArray"||n==="array"){let r=t.element??t.type;if(r)return zod.z.array(Fe(r))}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(r)return Fe(r).optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(r)return Fe(r).nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType,o=t.defaultValue;if(r){let s=Fe(r);return typeof o=="function"?s.default(o()):s.default(o)}}return e}function Zs(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 zod.z.object(o)}function Dt(e,t,n,r=false,o=[]){try{let s=Zs(e,n,o),a=r?s.partial():s;return {success:!0,data:(Zt()==="normalize"?Fe(a):a).parse(t)}}catch(s){return s instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${s.issues.map(c=>`${c.path.join(".")}: ${c.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function _t(e,t,n){let r=e?.shape?.[t];if(!r||typeof r.safeParse!="function")return {success:true,data:n};let o=r.safeParse(n);if(o.success)return {success:true,data:o.data};if(Array.isArray(n)){let a=[];for(let c of n){let i=r.safeParse(c);if(i.success)a.push(i.data);else return {success:false,error:i.error.issues.map(f=>f.message).join(", ")}}return {success:true,data:a}}return {success:false,error:o.error.issues.map(a=>a.message).join(", ")}}function Ks(e,t){let n=[],r=t?new Set(t):null,o={eq:"==",ne:"!=",lt:"<",lte:"<=",gt:">",gte:">=",in:"in",nin:"not-in",contains:"array-contains",containsAny:"array-contains-any"};for(let[s,a]of Object.entries(e)){if(a===void 0||["cursor","limit","pageSize","orderBy","orderDir","select"].includes(s))continue;let c=Array.isArray(a)?a[0]:a;if(c===void 0||c==="")continue;let i=s.match(/^(\w+)__(\w+)$/),u,f="==";if(i&&i[1]&&i[2]){u=i[1];let g=i[2];if(o[g])f=o[g];else continue}else if(!i)u=s;else continue;if(r&&!r.has(u))continue;let d=c;f==="in"||f==="not-in"||f==="array-contains-any"?d=c.split(",").map(g=>Nr(g.trim())):d=Nr(c),n.push({field:u,op:f,value:d});}return n}function Nr(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 Ft(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function Br(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 qr(e,t,n){async function r(w,p,h,l){if(!p.rules)return true;let k=p.rules?.[h];if(!k)return M(w,`Operation "${h}" is not allowed for this repository`,403),false;try{return await k(l)?!0:M(w,"Forbidden",403)}catch(y){let R=n&&y instanceof Error?y.message:"Forbidden";return M(w,R,403)}}async function o(w,p,h,l){if(!w.rules)return l;let k=w.rules?.filter;if(!k)return l;let y=[];for(let R of l)try{await k({user:p,doc:R,params:h})&&y.push(R);}catch{}return y}function s(w){return w.get("user")??w.get("docsUser")??null}function a(w,p){if(!w){let h=p.req.path.split("/");for(let l of h)if(e[l]){w=l;break}}return !w||!e[w]?null:e[w]??null}function c(w,p){if(!p)return;let h=w[p];if(typeof h!="string"||!h)return;let l=h.split("/").filter(Boolean),k=[];for(let y=1;y<l.length;y+=2)k.push(l[y]);return k.length>0?k:void 0}async function i(w,p){let h=`by${w.documentKey.charAt(0).toUpperCase()}${w.documentKey.slice(1)}`,l=w.repo.get[h];if(typeof l=="function")try{let y=await l(p);if(y)return y}catch{}return (await w.repo.query.by({where:[[w.documentKey,"==",p]],limit:1}))[0]??null}async function u(w){let p=w.c,h=p.req.param(),l=a(h.repoName,p);if(!l)return M(p,"Repository not found",404);let k=s(p);if(!await r(p,l,"list",{user:k,query:p.req.query(),params:h}))return;let y=[],R;try{let v=p.req.query(),C=Math.min(Number(v.pageSize)||l.pageSize,100),A=v.cursor,T=v.direction?.toLowerCase()==="prev"?"prev":"next",P=v.orderBy,E=v.orderDir?.toLowerCase()==="desc"?"desc":"asc",I=v.select,O=I?I.split(",").map(U=>U.trim()):void 0,$;l.allowedIncludes&&v.includes&&($=(typeof v.includes=="string"?v.includes.split(",").map(J=>J.trim()):Array.isArray(v.includes)?v.includes:[]).filter(J=>typeof J=="string"&&l.allowedIncludes.includes(J)),$?.length===0&&($=void 0));let F=Ks(v,l.filterableFields);y=F.map(U=>({field:U.field,op:U.op,value:String(U.value??"")})),P&&(R={field:P,dir:E});let z={pageSize:C,direction:T};if(A)try{let U=typeof A=="string"?JSON.parse(A):A;z.cursor=await Br(l,U);}catch{}if(P){if(l.orderableFields&&!l.orderableFields.includes(P))return M(p,`Field not orderable: ${P}`,400);z.orderBy=[{field:P,direction:E}];}if(F.length>0){z.where=[];for(let U of F){let J=_t(l.schema,U.field,U.value);if(!J.success)return M(p,`Invalid filter value for '${U.field}': ${J.error}`,400);z.where.push([U.field,U.op,J.data]);}}O&&(z.select=O),$&&(z.include=$);let j=await l.repo.query.paginate(z),Q={items:await o(l,s(p),h,j.data),hasNextPage:j.hasNextPage,hasPrevPage:j.hasPrevPage,nextCursor:Ft(j.nextCursor),prevCursor:Ft(j.prevCursor)};return Oe(p,Q,{pageSize:C,hasMore:j.hasNextPage})}catch(v){wn(p,v,{ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:y,sort:R},"Failed to fetch documents",n);}}async function f(w){let p=w.c,h=p.req.param(),l=a(h.repoName,p);if(!l)return M(p,"Repository not found",404);let k=s(p);if(!await r(p,l,"list",{user:k,query:w.input||{},params:h}))return;let y=[],R;try{let v=w.input||{},C=Math.min(v.pageSize||l.pageSize,100),A=v.direction==="prev"?"prev":"next";v.where&&(y=v.where.map(O=>({field:String(O[0]),op:O[1],value:String(O[2]??"")}))),v.orderBy&&v.orderBy[0]&&(R={field:v.orderBy[0].field,dir:v.orderBy[0].direction==="desc"?"desc":"asc"});let T={pageSize:C,direction:A};if(v.cursor)try{let O=typeof v.cursor=="string"?JSON.parse(v.cursor):v.cursor;T.cursor=await Br(l,O);}catch{}if(l.allowedIncludes&&v.includes&&v.includes.length>0){let O=v.includes.filter($=>typeof $=="string"?l.allowedIncludes.includes($):typeof $=="object"&&$!==null&&"relation"in $&&typeof $.relation=="string"?l.allowedIncludes.includes($.relation):!1);O.length>0&&(T.include=O);}if(v.where&&v.where.length>0){if(l.filterableFields){let $=new Set(l.filterableFields),F=v.where.filter(z=>!$.has(z[0]));if(F.length>0){M(p,`Fields not filterable: ${F.map(z=>z[0]).join(", ")}`,400);return}}let O=[];for(let $ of v.where){let F=_t(l.schema,$[0],$[2]);if(!F.success){M(p,`Invalid filter value for '${$[0]}': ${F.error}`,400);return}O.push([$[0],$[1],F.data]);}T.where=O;}if(v.orWhere&&v.orWhere.length>0){if(l.filterableFields){let $=new Set(l.filterableFields),F=v.orWhere.filter(z=>!$.has(z[0]));if(F.length>0){M(p,`Fields not filterable: ${F.map(z=>z[0]).join(", ")}`,400);return}}let O=[];for(let $ of v.orWhere){let F=_t(l.schema,$[0],$[2]);if(!F.success){M(p,`Invalid filter value for '${$[0]}': ${F.error}`,400);return}O.push([$[0],$[1],F.data]);}T.orWhere=O;}if(v.orWhereGroups&&v.orWhereGroups.length>0){if(l.filterableFields){let $=new Set(l.filterableFields);for(let F of v.orWhereGroups){let z=F.filter(j=>!$.has(j[0]));if(z.length>0){M(p,`Fields not filterable: ${z.map(j=>j[0]).join(", ")}`,400);return}}}let O=[];for(let $ of v.orWhereGroups){let F=[];for(let z of $){let j=_t(l.schema,z[0],z[2]);if(!j.success){M(p,`Invalid filter value for '${z[0]}': ${j.error}`,400);return}F.push([z[0],z[1],j.data]);}O.push(F);}T.orWhereGroups=O;}if(v.orderBy&&v.orderBy.length>0){if(l.orderableFields){let O=new Set(l.orderableFields),$=v.orderBy.filter(F=>!O.has(F.field));if($.length>0){M(p,`Fields not orderable: ${$.map(F=>F.field).join(", ")}`,400);return}}T.orderBy=v.orderBy;}v.select&&v.select.length>0&&(T.select=v.select);let P=await l.repo.query.paginate(T),I={items:await o(l,s(p),h,P.data),hasNextPage:P.hasNextPage,hasPrevPage:P.hasPrevPage,nextCursor:Ft(P.nextCursor),prevCursor:Ft(P.prevCursor)};return Oe(p,I,{pageSize:C,hasMore:P.hasNextPage})}catch(v){wn(p,v,{ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:y,sort:R},"Failed to query documents",n);}}async function d(w){let p=w.c,h=p.req.param(),l=a(h.repoName,p);if(!l)return M(p,"Repository not found",404);let k=h.id;if(!k)return M(p,"Document ID required",400);try{let y=await i(l,k);if(!y)return M(p,"Document not found",404);let R=s(p);if(!await r(p,l,"get",{user:R,doc:y,params:h}))return;if(l.rules?.filter)try{if(!await l.rules.filter({user:R,doc:y,params:h}))return M(p,"Document not found",404)}catch{return M(p,"Document not found",404)}return Oe(p,y)}catch(y){wn(p,y,{ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:[{field:l.documentKey,op:"==",value:k}]},"Failed to fetch document",n);}}async function g(w){let p=w.c,h=p.req.param(),l=a(h.repoName,p);if(!l)return M(p,"Repository not found",404);try{let k=w.input||{},y=s(p);if(!await r(p,l,"create",{user:y,body:k,params:h}))return;let R=Dt(l.schema,k,l.createFields,!1,l.systemKeys);if(!R.success)return M(p,R.error,400);if(l.validate){let C=await l.validate(R.data,"create");if(C)return M(p,C,400)}let v;if(l.isGroup&&l.parentKeys&&l.parentKeys.length>0){let C={...R.data};l.createdKey&&(C[l.createdKey]=new Date);let A=l.parentKeys.filter(E=>!C[E]);if(A.length>0){M(p,`Missing parent key(s) for subcollection create: ${A.join(", ")}`,400);return}let T=l.parentKeys.map(E=>C[E]),P=C[l.documentKey]||Hr();v=await l.repo.set(...T,P,C);}else v=await l.repo.create(R.data);return Oe(p,v,void 0,201)}catch(k){let y=n&&k instanceof Error?k.message:"Failed to create document";return M(p,y,500)}}async function x(w,p){let h=w.c,l=h.req.param(),k=a(l.repoName,h);if(!k)return M(h,"Repository not found",404);let y=l.id;if(!y)return M(h,"Document ID required",400);try{let R=w.input||{},v=await i(k,y);if(!v)return M(h,"Document not found",404);let C=s(h);if(!await r(h,k,"update",{user:C,doc:v,body:R,params:l}))return;let A=Dt(k.schema,R,k.mutableFields,p,k.systemKeys);if(!A.success)return M(h,A.error,400);if(k.validate){let E=await k.validate(A.data,"update");if(E)return M(h,E,400)}let T=c(v,k.pathKey)??[y],P=await k.repo.update(...T,A.data);return Oe(h,P)}catch(R){let v=n&&R instanceof Error?R.message:"Failed to update document";return M(h,v,500)}}async function m(w){let p=w.c,h=p.req.param(),l=a(h.repoName,p);if(!l)return M(p,"Repository not found",404);if(!l.allowDelete)return M(p,"Delete not allowed for this repository",403);let k=h.id;if(!k)return M(p,"Document ID required",400);try{let y=await i(l,k);if(!y)return M(p,"Document not found",404);let R=s(p);if(!await r(p,l,"delete",{user:R,doc:y,params:h}))return;let v=c(y,l.pathKey)??[k];return await l.repo.delete(...v),Oe(p,{deleted:!0})}catch(y){let R=n&&y instanceof Error?y.message:"Failed to delete document";return M(p,R,500)}}function S(w){return w.c.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","Access-Control-Max-Age":"86400"})}async function b(w){let p=w.c,h=p.req.param(),l=a(h.repoName,p);if(!l)return M(p,"Repository not found",404);try{let k=w.input||{};if(!Array.isArray(k.operations))return M(p,"operations array is required",400);let y=s(p),R=l.repo.batch.create(),v=[];for(let C of k.operations){if(!C.type||!["create","update","delete"].includes(C.type))return M(p,"Invalid operation type",400);if(C.type==="create"){if(!await r(p,l,"create",{user:y,body:C.data,params:h}))return;let A=Dt(l.schema,C.data,l.createFields,!1,l.systemKeys);if(!A.success)return M(p,A.error,400);let T=C.data[l.documentKey]||Hr(),P={...A.data};if(l.createdKey&&(P[l.createdKey]=new Date),l.isGroup&&l.parentKeys){let E=l.parentKeys.map(I=>P[I]);R.set(...E,T,P);}else R.set(T,P);v.push({op:"create",id:T});}else if(C.type==="update"){if(!C.id)return M(p,"id required for update",400);let A=await i(l,C.id);if(!A)return M(p,`Document ${C.id} not found`,404);if(!await r(p,l,"update",{user:y,doc:A,body:C.data,params:h}))return;let T=Dt(l.schema,C.data,l.mutableFields,!0,l.systemKeys);if(!T.success)return M(p,T.error,400);let P=c(A,l.pathKey)??[C.id];R.update(...P,T.data),v.push({op:"update",id:C.id});}else if(C.type==="delete"){if(!l.allowDelete)return M(p,"Delete not allowed",403);if(!C.id)return M(p,"id required for delete",400);let A=await i(l,C.id);if(!A)return M(p,`Document ${C.id} not found`,404);if(!await r(p,l,"delete",{user:y,doc:A,params:h}))return;let T=c(A,l.pathKey)??[C.id];R.delete(...T),v.push({op:"delete",id:C.id});}}return await R.commit(),Oe(p,{results:v})}catch(k){let y=n&&k instanceof Error?k.message:"Batch operation failed";return M(p,y,500)}}return {handleList:u,handleQuery:f,handleGet:d,handleCreate:g,handleUpdate:x,handleDelete:m,handleBatch:b,handleOptions:S}}function jt(e){try{return zod.z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=zodToOpenapi.getOpenApiMetadata(t.zodSchema);n&&Object.assign(t.jsonSchema,n);let r=t.zodSchema?._zod?.def;r&&(r.type==="date"&&!t.jsonSchema.type?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):r.type==="bigint"&&!t.jsonSchema.type&&(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 se(e){return {$ref:`#/components/schemas/${e}`}}function W(e){return {description:e,content:{"application/json":{schema:se("ErrorResponse")}}}}function je(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function Zr(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"}},required:["items","hasNextPage","hasPrevPage"]},meta:{type:"object",properties:{pageSize:{type:"integer"},hasMore:{type:"boolean"},cursor:{oneOf:[{type:"string"},{type:"null"}]}}}},required:["success","data"]}}}}}function it(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 Us(e,t){let n=t.split("."),r=it(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=it(c);}return r}function Kr(e,t="",n=0){if(n>5)return [];let o=it(e)?.shape;if(!o)return [];let s=[];for(let[a,c]of Object.entries(o)){let i=t?`${t}.${a}`:a,u=it(c);u?.shape&&typeof u.shape=="object"?(s.push({path:i,zodSchema:c}),s.push(...Kr(u,i,n+1))):s.push({path:i,zodSchema:c});}return s}function An(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:Us(e.schema,t)})):Kr(e.schema)}function Tn(e){if(!e)return {type:"string"};let t=jt(e);return delete t.$schema,delete t.title,t}function Qs(e){let t=An(e),n=e.orderableFields??t.map(r=>r.path);return [{name:"pageSize",in:"query",schema:{type:"integer",default:e.pageSize,maximum:100},description:"Number of items per page"},{name:"cursor",in:"query",schema:{type:"string"},description:"Base64 pagination cursor"},{name:"orderBy",in:"query",schema:{type:"string",...n.length>0?{enum:n}:{}},description:"Field name to order by"},{name:"orderDir",in:"query",schema:{type:"string",enum:["asc","desc"]},description:"Order direction"},{name:"select",in:"query",schema:{type:"string"},description:`Comma-separated list of fields to return${t.length>0?` (${t.map(r=>r.path).join(", ")})`:""}`}]}function Vs(e){let t=An(e),n=["eq","ne","lt","lte","gt","gte","in","nin","contains","containsAny"],r={eq:"equals. Use 'null' or '__null__' to match null values",ne:"not equals. Use 'null' or '__null__' to match non-null values",lt:"less than",lte:"less than or equal",gt:"greater than",gte:"greater than or equal",in:"in list (comma-separated values). Supports 'null' and '__null__' (e.g. val1,val2,__null__)",nin:"not in list (comma-separated values). Supports 'null' and '__null__'",contains:"array-contains",containsAny:"array-contains-any (comma-separated values). Supports 'null' and '__null__'"},o=[];for(let{path:s,zodSchema:a}of t){let c=Tn(a);o.push({name:s,in:"query",schema:c,description:`Filter by ${s} (equality). Use 'null' or '__null__' for null values`});for(let i of n){let u=r[i]?` (${r[i]})`:"",f=i==="in"||i==="nin"||i==="containsAny";o.push({name:`${s}__${i}`,in:"query",schema:f?{type:"string",description:"Comma-separated list of values"}:c,description:`Filter ${s} with operator ${i}${u}`});}}return o}function Lr(){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",maximum:100,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)"}}}}function Ws(e){let t=An(e),n=e.orderableFields??t.map(a=>a.path),r=t.map(a=>a.path);if(t.length===0)return Lr();let o=[];for(let{path:a,zodSchema:c}of t){let i=Tn(c),u=it(c),d=u?._zod?.def?.type==="array"||u?._def?.typeName==="ZodArray"||u?._def?.type==="array"?Tn(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"]},d],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:d}],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",maximum:100,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)"}}}}function Gs(e,t,n,r,o,s="QueryRequestBody"){let a={},c=e.name,i=`${t}/${e.name}`,u=`${i}/{${e.documentKey}}`,f={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};a[i]={get:{operationId:`list${ge(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[c],parameters:[...Qs(e),...Vs(e)],responses:{200:Zr(se(n)),500:W("Internal server error")}},post:{operationId:`create${ge(e.name)}`,summary:`Create a ${de(e.name)}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:se(r??n)}}},responses:{201:je("Document created",se(n)),400:W("Validation error"),500:W("Internal server error")}}},a[`${i}/query`]={post:{operationId:`query${ge(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:se(s)}}},responses:{200:Zr(se(n)),400:W("Invalid query"),500:W("Internal server error")}}},a[`${i}/batch`]={post:{operationId:`batch${ge(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:se(`${n}BatchRequest`)}}},responses:{200:je("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:W("Validation error"),403:W("Forbidden"),404:W("Document not found"),500:W("Internal server error")}}};let d={};return d.get={operationId:`get${ge(de(e.name))}`,summary:`Get a single ${de(e.name)}`,tags:[c],parameters:[f],responses:{200:je("Document found",se(n)),404:W("Document not found"),500:W("Internal server error")}},d.put={operationId:`update${ge(de(e.name))}`,summary:`Update a ${de(e.name)} (full replace)`,tags:[c],parameters:[f],requestBody:{required:true,content:{"application/json":{schema:se(o??n)}}},responses:{200:je("Document updated",se(n)),400:W("Validation error"),404:W("Document not found"),500:W("Internal server error")}},d.patch={operationId:`patch${ge(de(e.name))}`,summary:`Partially update a ${de(e.name)}`,tags:[c],parameters:[f],requestBody:{required:true,content:{"application/json":{schema:{allOf:[se(o??n)],description:"All fields are optional for partial updates"}}}},responses:{200:je("Document patched",se(n)),400:W("Validation error"),404:W("Document not found"),500:W("Internal server error")}},e.allowDelete&&(d.delete={operationId:`delete${ge(de(e.name))}`,summary:`Delete a ${de(e.name)}`,tags:[c],parameters:[f],responses:{200:je("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:W("Document not found"),500:W("Internal server error")}}),a[u]=d,a}function Cn(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={},d=[];u.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},u.QueryRequestBody=Lr();for(let[S,b]of Object.entries(e)){let w=ge(de(S)),p=`${w}Create`,h=`${w}Update`,l=`${w}QueryRequestBody`;u[w]=jt(b.schema),u[l]=Ws(b);let k=T=>{let P=T&&T.length>0?T:Object.keys(b.schema.shape),E={};for(let I of P){let O=I.split(".")[0];O&&b.schema.shape[O]&&!b.systemKeys.includes(O)&&(E[O]=b.schema.shape[O]);}return E},y=null,R=k(b.createFields);Object.keys(R).length>0&&(u[p]=jt(zod.z.object(R)),y=p);let v=null,C=k(b.mutableFields);Object.keys(C).length>0&&(u[h]=jt(zod.z.object(C)),v=h),u[`${w}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",enum:["create"]},data:se(y??w)},required:["type","data"]},{type:"object",properties:{type:{type:"string",enum:["update"]},id:{type:"string"},data:{allOf:[se(v??w)],description:"Partial updates allowed"}},required:["type","id","data"]},...b.allowDelete?[{type:"object",properties:{type:{type:"string",enum:["delete"]},id:{type:"string"}},required:["type","id"]}]:[]]}}},required:["operations"]};let A=Gs(b,i,w,y,v,l);Object.assign(f,A),d.push({name:S,description:`Operations on ${S} (collection: ${b.path})`});}let g={},x;return c==="basic"?(g.basicAuth={type:"http",scheme:"basic"},x=[{basicAuth:[]}]):c==="bearer"&&(g.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},x=[{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(g).length>0?{securitySchemes:g}:{}},...x?{security:x}:{},tags:d}}function ge(e){return e.charAt(0).toUpperCase()+e.slice(1)}function de(e){return e.endsWith("ies")?e.slice(0,-3)+"y":e.endsWith("ses")||e.endsWith("xes")||e.endsWith("zes")?e.slice(0,-2):e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e}var Me=class extends Error{constructor(n,r){super("Request validation failed");this.zodError=n;this.source=r;this.statusCode=400;this.name="ValidationError";}};var ct=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},lt=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function Ur(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function Qr(e,t){return t instanceof Me?e.json({success:false,error:"Validation failed",issues:Ur(t.zodError)},400):t instanceof ct?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof lt?e.json({success:false,error:"Output validation failed",issues:Ur(t.zodError)},500):null}zodToOpenapi.extendZodWithOpenApi(zod.z);var Vr="Successful response",Wr="Error response";function ta(e){return e==="get"?"query":"json"}function na(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function ra(e){if(typeof e.safeParse=="function")return {description:Wr,schema:e};let t=e;return {description:t.description??Wr,schema:t.schema}}function Jr(e,t,n,r){let o=new zodToOpenapi.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??ta(i),f=aa(t,c.path??"/"),d=c.status??200,g=oa(i,u,c.input),x=Gr(u,c.input,"query"),m=Gr(u,c.input,"param"),S=ia(i,f),b=na(c.output,r),w={[d]:b?{description:Vr,content:{"application/json":{schema:b}}}:{description:Vr}};if(r?.errors)for(let[p,h]of Object.entries(r.errors)){let{description:l,schema:k}=ra(h);w[p]=k?{description:l,content:{"application/json":{schema:k}}}:{description:l};}o.registerPath({method:i,path:sa(f),operationId:S,summary:c.summary,description:c.description,tags:c.tags,deprecated:c.deprecated,security:c.security,request:{...x?{query:x}:{},...m?{params:m}:{},...g?{body:g}:{}},responses:w});}return new zodToOpenapi.OpenApiGeneratorV31(o.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security})}function oa(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 Gr(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function sa(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function aa(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function ia(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function Xr(e,t){let n=e.replace(/"/g,""");return `<!doctype html>
|
|
1142
1142
|
<html lang="en">
|
|
1143
1143
|
<head>
|
|
1144
1144
|
<meta charset="utf-8" />
|
|
@@ -1149,5 +1149,5 @@ function initColumnReorder(table) {
|
|
|
1149
1149
|
<script id="api-reference" data-url="${n}"></script>
|
|
1150
1150
|
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
|
|
1151
1151
|
</body>
|
|
1152
|
-
</html>`}function Yr(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var On=new async_hooks.AsyncLocalStorage;function eo(){return async(e,t)=>{await On.run({c:e},async()=>{await t();});}}var ua=Object.freeze({}),
|
|
1152
|
+
</html>`}function Yr(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var On=new async_hooks.AsyncLocalStorage;function eo(){return async(e,t)=>{await On.run({c:e},async()=>{await t();});}}var ua=Object.freeze({}),zt=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new hono.Hono,this.mountedRoutes=ya(t.routes,t.api),t.services&&this.app.use("*",eo());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 nodeServer.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=Jr(this.mountedRoutes,this.options.basePath??"",this.options.openapi,fa(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=Mt(t,o.path),a=o.middlewares??[],c=o.source??(o.method==="get"?"query":"json"),i=ha(o,c,n,pa(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=Mt(this.options.basePath??"",n),s=r===false?null:Mt(this.options.basePath??"",r),a;if(Yr(t.docsAuth)){let c=t.docsAuth;a=[c.middleware];let i=ma(s??o);for(let u of c.routes)this.app.on(u.method,[Mt(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=ga(s,o);this.app.on("GET",[s],...a,i=>i.html(Xr(c,t.info.title)));}}};function to(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function pa(e){if(e)return to(e)?e.handler:e}function fa(e){return to(e)?e:void 0}function ya(e,t){return t?e.filter(n=>Array.isArray(n.api)?n.api.includes(t):n.api===t):e.slice()}function Mt(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function ma(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function ga(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 ha(e,t,n,r,o,s,a){let c=e.input,i=e.output,u=e.status??200,f=o??ua;return async d=>{let g=async S=>{if(s){let b=await s.handle({error:S,c:d,route:e,services:f,logger:a});if(b)return b}return Qr(d,S)},x=async()=>{let S,b;try{b=await ba(d,t,e.method);}catch(p){throw new ct(p instanceof Error?p.message:String(p))}if(c){let p=c.safeParse(b);if(!p.success)throw new Me(p.error,t);S=p.data;}else S=b;let w=await e.handler({input:S,c:d,services:f,errorHandler:s,logger:a});if(n&&i&&!(w instanceof Response)){let p=i.safeParse(w);if(!p.success)throw new lt(p.error);return p.data}return w},m;if(r)try{m=await r({next:x,route:e,c:d,services:f,errorHandler:s,logger:a});}catch(S){let b=await g(S);if(b)return b;throw S}else try{m=await x();}catch(S){let b=await g(S);if(b)return b;throw S}return m instanceof Response?m:d.json(m,u)}}async function ba(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 no(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,verbose:s=false,httpsOptions:a}=e,c=t==="/"?"":t.replace(/\/$/,""),i={};for(let[w,p]of Object.entries(n)){if(!p.repo)throw new Error(`[createCrudServer] Repository "${w}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let h=p.schema??p.repo.schema??null;if(!h)throw new Error(`[createCrudServer] Repository "${w}" has no Zod schema.`);let l,k,y,R;if(p.fieldsConfig){let A=p.fieldsConfig;l=[],k=[],y=[],R=[];for(let[T,P]of Object.entries(A))for(let E of P)E==="filterable"?l.push(T):E==="orderable"?k.push(T):E==="mutable"?y.push(T):E==="create"&&R.push(T);k.length===0&&(k=l),l.length===0&&(l=void 0),k&&k.length===0&&(k=void 0),y.length===0&&(y=void 0),R.length===0&&(R=void 0);}let v=(()=>{let A=p.repo._parentKeys;return A&&A.length>0?A:void 0})();if(v&&R)for(let A of v)R.includes(A)||R.push(A);let C={name:w,path:p.path,repo:p.repo,schema:h,systemKeys:p.repo._systemKeys??[p.documentKey??"docId"],documentKey:p.documentKey??"docId",pathKey:p.repo._pathKey??void 0,isGroup:!!p.repo._isGroup,parentKeys:v,createdKey:p.repo._createdKey??void 0,pageSize:p.pageSize??25,filterableFields:l,orderableFields:k,mutableFields:y,createFields:R,allowDelete:p.allowDelete??false,allowedIncludes:p.allowedIncludes,validate:p.validate,rules:p.rules};i[w]=C;}let u=qr(i,c,s),f=e.openapi,d=f&&typeof f=="object"?f:{},g=null;function x(){return g||(g=Cn(i,c,{...d,auth:d.auth??false})),g}let m=[];for(let w of Object.keys(i))m.push({api:"crud",method:"get",path:`/${w}`,source:"query",handler:u.handleList}),m.push({api:"crud",method:"post",path:`/${w}/query`,source:"json",handler:u.handleQuery}),m.push({api:"crud",method:"get",path:`/${w}/:id`,source:"query",handler:u.handleGet}),m.push({api:"crud",method:"post",path:`/${w}`,source:"json",handler:u.handleCreate}),m.push({api:"crud",method:"put",path:`/${w}/:id`,source:"json",handler:p=>u.handleUpdate(p,false)}),m.push({api:"crud",method:"patch",path:`/${w}/:id`,source:"json",handler:p=>u.handleUpdate(p,true)}),m.push({api:"crud",method:"delete",path:`/${w}/:id`,source:"query",handler:u.handleDelete}),m.push({api:"crud",method:"post",path:`/${w}/batch`,source:"json",handler:u.handleBatch});let S=new zt({...e,openapi:f!==false?{path:d.path??"/openapi.json",docsPath:d.docsPath??"/docs",info:{title:d.title??"CRUD API",version:d.version??"1.0.0"},docsAuth:d.docsAuth}:void 0,basePath:t,api:"crud",routes:m,middlewares:[async(w,p)=>{if(w.req.method==="OPTIONS")return w.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","Access-Control-Max-Age":"86400","Access-Control-Allow-Origin":"*","Access-Control-Allow-Credentials":"true"});w.header("Access-Control-Allow-Origin","*"),w.header("Access-Control-Allow-Credentials","true"),await p();},...e.middlewares||[]]});if(f!==false&&(S.buildOpenApiSpec=x),o!==false){let{securityHeaders:w}=(It(),go(Mr)),p=o===void 0?{csp:false}:o;S.hono.use("*",async(h,l)=>{let k=w(p);await new Promise(y=>{let R=h.req.raw;k(R,{setHeader:(C,A)=>h.header(C,A),removeHeader:C=>h.res.headers.delete(C)},()=>y());}),await l();});}let b=S.nodeHandler;return b.spec=x,a&&(b.httpsOptions=a),b}function ro(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 oo(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 so(e,t={}){return {admin(n){let r=oo(e,n.repos,"admin"),o=zr({...n,repos:r,httpsOptions:n.httpsOptions??t.httpsOptions});return ro(o,t)},crud(n){let r=oo(e,n.repos,"crud"),o=no({...n,repos:r,httpsOptions:n.httpsOptions??t.httpsOptions});return ro(o,t)},sync(n){let r={...n};return t.onRequest&&r.admin&&!r.admin.onRequest&&(r.admin={...r.admin,onRequest:t.onRequest,httpsOptions:r.admin.httpsOptions??t.httpsOptions}),ur(e,r)},history(n){return Wn(e,n)}}}It();function id(e){return t=>({...t,schema:e,type:null,documentRef:null,update:null})}function cd(e,t){let n={...e};for(let r in t)t[r]&&(n[r]={...e[r],relationalKeys:t[r]});return n}var En=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]=Gt(t,this.mapping[n],{});for(let n of Object.keys(this.mapping))this.allRepositories[n]=Gt(t,this.mapping[n],this.allRepositories);}getRepository(t){return this.ensureInitialized(),this.allRepositories[t]}};function ld(e,t){let n=new En(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]},ownKeys(){return r},getOwnPropertyDescriptor(o,s){if(typeof s=="string"&&s in t)return {configurable:true,enumerable:true,writable:false}}})}exports.MiniRouter=fe;exports.RepositoryMapping=En;exports.applyPaginationQueryOptions=he;exports.buildAndExecuteQuery=ke;exports.buildRepositoryRelations=cd;exports.coerceToDate=Kt;exports.createPaginationIterator=Lt;exports.createRepositoryConfig=id;exports.createRepositoryMapping=ld;exports.createServers=so;exports.executePaginatedQuery=yt;exports.getDateHandling=Zt;exports.normalizeTimestamps=ft;exports.setDateHandling=bo;//# sourceMappingURL=index.cjs.map
|
|
1153
1153
|
//# sourceMappingURL=index.cjs.map
|