@lpdjs/firestore-repo-service 3.0.11 → 3.0.13

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.
Files changed (60) hide show
  1. package/README.md +27 -14
  2. package/dist/{create-servers-KRf2J2fi.d.ts → create-servers-Db1xUY2N.d.ts} +4 -4
  3. package/dist/{create-servers-DQBvtkBM.d.cts → create-servers-LyRLAOh3.d.cts} +4 -4
  4. package/dist/history/index.cjs +1 -1
  5. package/dist/history/index.cjs.map +1 -1
  6. package/dist/history/index.js +1 -1
  7. package/dist/history/index.js.map +1 -1
  8. package/dist/index.cjs +69 -69
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +19 -15
  11. package/dist/index.d.ts +19 -15
  12. package/dist/index.js +69 -69
  13. package/dist/index.js.map +1 -1
  14. package/dist/llms-full.txt +36 -23
  15. package/dist/llms.txt +2 -2
  16. package/dist/{openapi-CzrvqcOE.d.ts → openapi-CNIA7QRw.d.ts} +1 -1
  17. package/dist/{openapi-DK7pS1zN.d.cts → openapi-QVpqnnes.d.cts} +1 -1
  18. package/dist/{queue-HoGBozpD.d.ts → queue-BEB-ujA3.d.ts} +1 -1
  19. package/dist/{queue-CdmBSUNN.d.cts → queue-CpHe6M5j.d.cts} +1 -1
  20. package/dist/{rules-Bu2WJoLI.d.cts → rules-Bu2NB7Eb.d.cts} +1 -1
  21. package/dist/{rules-gKR5VFhO.d.ts → rules-Cafrkb9v.d.ts} +1 -1
  22. package/dist/servers/admin/index.cjs +26 -26
  23. package/dist/servers/admin/index.cjs.map +1 -1
  24. package/dist/servers/admin/index.d.cts +3 -1
  25. package/dist/servers/admin/index.d.ts +3 -1
  26. package/dist/servers/admin/index.js +26 -26
  27. package/dist/servers/admin/index.js.map +1 -1
  28. package/dist/servers/crud/index.cjs +2 -2
  29. package/dist/servers/crud/index.cjs.map +1 -1
  30. package/dist/servers/crud/index.d.cts +6 -6
  31. package/dist/servers/crud/index.d.ts +6 -6
  32. package/dist/servers/crud/index.js +2 -2
  33. package/dist/servers/crud/index.js.map +1 -1
  34. package/dist/servers/hono/index.cjs +12 -12
  35. package/dist/servers/hono/index.cjs.map +1 -1
  36. package/dist/servers/hono/index.js +12 -12
  37. package/dist/servers/hono/index.js.map +1 -1
  38. package/dist/servers/index.cjs +88 -88
  39. package/dist/servers/index.cjs.map +1 -1
  40. package/dist/servers/index.d.cts +8 -8
  41. package/dist/servers/index.d.ts +8 -8
  42. package/dist/servers/index.js +88 -88
  43. package/dist/servers/index.js.map +1 -1
  44. package/dist/sync/bigquery.d.cts +1 -1
  45. package/dist/sync/bigquery.d.ts +1 -1
  46. package/dist/sync/index.cjs +41 -41
  47. package/dist/sync/index.cjs.map +1 -1
  48. package/dist/sync/index.d.cts +5 -5
  49. package/dist/sync/index.d.ts +5 -5
  50. package/dist/sync/index.js +41 -41
  51. package/dist/sync/index.js.map +1 -1
  52. package/dist/sync/meilisearch.d.cts +1 -1
  53. package/dist/sync/meilisearch.d.ts +1 -1
  54. package/dist/{types-DZoEAKT7.d.cts → types-B51LYvQZ.d.cts} +58 -7
  55. package/dist/{types-8Yoacm2k.d.cts → types-CNseHqF7.d.cts} +4 -2
  56. package/dist/{types-DiGFAWPA.d.ts → types-Ci0dGbuW.d.ts} +58 -7
  57. package/dist/{types-DzJ9WrcY.d.ts → types-DGQURFSq.d.ts} +1 -1
  58. package/dist/{types-DRKB8gTA.d.ts → types-DmXW_fVz.d.ts} +4 -2
  59. package/dist/{types-KEVZXCF4.d.cts → types-VVuLlmfc.d.cts} +1 -1
  60. package/package.json +3 -2
@@ -1,4 +1,4 @@
1
- import {jsx,jsxs,Fragment}from'hono/jsx/jsx-runtime';import {Timestamp}from'firebase-admin/firestore';import {randomUUID,randomBytes}from'crypto';import {z as z$1}from'zod';import {renderToString}from'hono/jsx/dom/server';import {extendZodWithOpenApi,OpenAPIRegistry,OpenApiGeneratorV31,getOpenApiMetadata}from'@asteasolutions/zod-to-openapi';import {Hono}from'hono';import {getRequestListener}from'@hono/node-server';import {AsyncLocalStorage}from'async_hooks';var Ft=Object.defineProperty;var es=Object.getOwnPropertyDescriptor;var ts=Object.getOwnPropertyNames;var ns=Object.prototype.hasOwnProperty;var On=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Le=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var En=(e,t)=>{for(var n in t)Ft(e,n,{get:t[n],enumerable:true});},rs=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ts(t))!ns.call(e,s)&&s!==n&&Ft(e,s,{get:()=>t[s],enumerable:!(r=es(t,s))||r.enumerable});return e};var ss=e=>rs(Ft({},"__esModule",{value:true}),e);function K(e){let t=e,n=t._zod?.def?.type;if(n)return Ts[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=t._def?.typeName;return r||""}function ne(e){let t=e;if(t._zod?.def?.innerType)return t._zod.def.innerType;if(t._def?.innerType)return t._def.innerType}function Qe(e){let t=e,n=t._zod?.def?.in;if(n)return n;if(t._def?.schema)return t._def.schema}function wt(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}function qn(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 re(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 Ge(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 Je(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 Ye(e){let t=e;return Array.isArray(t._zod?.def?.values)?t._zod.def.values[0]:t._def?.value}function Xe(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 Zn(e){let t=e,n=[],r=t._zod?.def?.checks;if(Array.isArray(r)){for(let o of r)o.format&&n.push(o.format);if(n.length>0)return n}let s=t._def?.checks;if(Array.isArray(s))for(let o of s)o.kind&&n.push(o.kind);return n}var Ts,je=Le(()=>{"use strict";Ts={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 or({val:e}){return jsx("span",{class:"text-sm text-base-content/80 font-mono tabular-nums whitespace-nowrap",children:e.toLocaleString()})}function Ws({message:e}){return jsx("span",{class:"tooltip tooltip-warning tooltip-right inline-flex align-middle ml-1 text-warning","data-tip":e,role:"img","aria-label":e,children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",class:"size-3.5",children:jsx("path",{d:"M12 2 1 22h22L12 2zm0 6 7.5 13h-15L12 8zm-1 4v4h2v-4h-2zm0 5v2h2v-2h-2z"})})})}function Fe({val:e,mismatch:t}){let n=tn(e);return t?jsxs("span",{class:"inline-flex items-start gap-0.5",children:[n,jsx(Ws,{message:t})]}):n}function tn(e){if(e==null)return jsx("span",{class:"opacity-30 italic text-xs",children:"\u2014"});if(typeof e=="boolean")return e?jsx("span",{class:"badge badge-success badge-sm",children:"true"}):jsx("span",{class:"badge badge-error badge-sm",children:"false"});if(e instanceof Date)return jsx(or,{val:e});if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")return jsx(or,{val:e.toDate()});if(typeof e=="number")return jsx("span",{class:"text-sm font-mono tabular-nums",children:String(e)});if(Array.isArray(e))return e.length===0?jsx("span",{class:"text-xs text-base-content/30",children:"[]"}):jsxs("ul",{class:"list-none p-0 m-0 space-y-0.5 text-xs",children:[e.slice(0,8).map((n,r)=>jsx("li",{class:"break-all",children:tn(n)},r)),e.length>8&&jsxs("li",{class:"text-base-content/40 italic",children:["+",e.length-8," more\u2026"]})]});if(typeof e=="object"&&e!==null){let n=Object.entries(e);return n.length===0?jsx("span",{class:"text-xs text-base-content/30",children:"{}"}):jsxs("dl",{class:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 text-xs m-0",children:[n.slice(0,8).map(([r,s])=>jsxs(Fragment,{children:[jsx("dt",{class:"text-base-content/50 font-semibold whitespace-nowrap",children:r}),jsx("dd",{class:"break-all",children:tn(s)})]})),n.length>8&&jsxs("dt",{class:"col-span-2 text-base-content/40 italic",children:["+",n.length-8," more\u2026"]})]})}let t=String(e);return jsx("span",{class:"text-sm break-all",children:t})}var At=Le(()=>{"use strict";});function st(e){if(!e)return "unknown";let t=nn(e);switch(K(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 nn(e){let t=K(e);if(t==="ZodOptional"||t==="ZodNullable"||t==="ZodDefault"){let n=ne(e);return n?nn(n):e}return e}function ot(e,t){if(!e)return;let n=t.split("."),r=e;for(let s of n){if(!r)return;let o=nn(r);if(K(o)!=="ZodObject")return;r=re(o)[s];}return r}function Js(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 at(e,t){if(e==="unknown")return null;let n=Js(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 rn=Le(()=>{"use strict";je();});var cr={};En(cr,{PanelMany:()=>Xs,PanelOne:()=>Ys,RightPanel:()=>sn});function Ys({doc:e,repoName:t,basePath:n,schema:r,columns:s}){if(!e)return jsx("div",{class:"text-center py-12 text-base-content/50",children:"Document not found."});let o=String(e.docId??e.id??""),a=`${n}/${t}/${encodeURIComponent(o)}/edit`,i=ir(r,s);return jsxs("div",{class:"space-y-4",children:[jsxs("div",{class:"flex items-center justify-between gap-2",children:[jsxs("div",{class:"text-xs text-base-content/60",children:[jsx("span",{class:"font-mono",children:t}),jsx("span",{class:"opacity-50",children:" \xB7 "}),jsx("span",{class:"font-mono break-all",children:o})]}),jsx("a",{href:a,class:"btn btn-sm btn-primary",children:"Edit \u2192"})]}),jsx("dl",{class:"grid grid-cols-[max-content_1fr] gap-x-4 gap-y-2 border border-base-300 rounded-box p-4 bg-base-100",children:s.map(l=>{let y=e[l],g=i[l],b=g?at(g,y):null;return jsxs(Fragment,{children:[jsx("dt",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide pt-0.5",children:l}),jsx("dd",{class:"min-w-0",children:jsx(Fe,{val:y,mismatch:b})})]})})})]})}function Xs({docs:e,repoName:t,basePath:n,fk:r,fv:s,columns:o,schema:a,pagination:i}){let l=`${n}/${t}?fv_${r}=${encodeURIComponent(s)}`,y=ir(a,o);return jsxs("div",{class:"space-y-4",children:[jsxs("div",{class:"flex items-center justify-between gap-2",children:[jsxs("div",{class:"text-xs text-base-content/60",children:[jsx("span",{class:"font-mono",children:t}),jsx("span",{class:"opacity-50",children:" where "}),jsx("span",{class:"font-mono",children:r}),jsx("span",{class:"opacity-50",children:" = "}),jsx("span",{class:"font-mono break-all",children:s}),jsx("span",{class:"opacity-50",children:" \xB7 "}),jsxs("span",{children:[e.length," doc",e.length!==1?"s":""]})]}),jsx("a",{href:l,class:"btn btn-sm btn-outline",children:"Full view \u2192"})]}),jsx("div",{class:"overflow-x-auto rounded-box border border-base-300 bg-base-100",children:jsxs("table",{class:"table table-xs w-full",children:[jsx("thead",{children:jsxs("tr",{class:"bg-base-200/50",children:[o.map((g,b)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:g},b)),jsx("th",{})]})}),jsx("tbody",{children:e.length===0?jsx("tr",{children:jsx("td",{colspan:o.length+1,class:"text-center py-10 text-base-content/40",children:"No related documents"})}):e.map((g,b)=>{let v=String(g.docId??g.id??""),C=`${n}/${t}/${encodeURIComponent(v)}/edit`;return jsxs("tr",{class:"hover",children:[o.map((R,T)=>{let P=g[R],N=y[R],S=N?at(N,P):null;return jsx("td",{class:"align-top py-1.5",children:jsx(Fe,{val:P,mismatch:S})},T)}),jsx("td",{class:"text-right py-1.5",children:jsx("a",{href:C,class:"btn btn-xs btn-ghost",children:"Edit"})})]},b)})})]})}),(i.hasPrev||i.hasNext)&&jsxs("div",{class:"flex justify-center items-center gap-2",children:[i.hasPrev?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"prev","data-cursor":i.prevCursor,children:"\u2190 Previous"}):jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"\u2190 Previous"}),i.hasNext?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"next","data-cursor":i.nextCursor,children:"Next \u2192"}):jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"Next \u2192"})]})]})}function ir(e,t){if(!e)return {};let n={};for(let r of t)n[r]=st(ot(e,r));return n}var sn,on=Le(()=>{"use strict";At();rn();sn=({basePath:e=""})=>jsxs("div",{class:"fixed inset-0 z-[100] hidden pointer-events-none","data-frs-panel-root":!0,"data-frs-base-path":e,"aria-hidden":"true",children:[jsx("div",{class:"absolute inset-0 bg-black/30 opacity-0 transition-opacity duration-200 pointer-events-auto","data-frs-panel-backdrop":!0}),jsxs("aside",{class:"absolute top-0 right-0 h-full w-full md:w-1/2 bg-base-100 shadow-2xl border-l border-base-300 translate-x-full transition-transform duration-200 pointer-events-auto flex flex-col","data-frs-panel":!0,role:"dialog","aria-label":"Relation preview",children:[jsxs("header",{class:"flex items-center justify-between px-5 py-3 border-b border-base-300 bg-base-200/40 shrink-0",children:[jsx("h2",{class:"font-semibold text-base truncate","data-frs-panel-title":!0,children:"Relation"}),jsx("button",{type:"button",class:"btn btn-sm btn-ghost btn-circle","data-frs-panel-close":!0,"aria-label":"Close panel",children:"\u2715"})]}),jsx("div",{class:"flex-1 overflow-auto p-5 text-sm","data-frs-panel-body":!0,children:jsx("div",{class:"flex items-center justify-center py-12 text-base-content/40",children:jsx("span",{class:"loading loading-spinner loading-md"})})})]})]});});var Rr={};En(Rr,{DEFAULT_HTML_CSP:()=>wn,securityHeaders:()=>$t});function $t(e={}){let t=e.csp===void 0?wn:e.csp,n=e.frameOptions===void 0?"DENY":e.frameOptions,r=e.referrerPolicy===void 0?"no-referrer":e.referrerPolicy,s=e.cacheControl===void 0?"private, no-store":e.cacheControl;return async(o,a,i)=>{typeof a?.setHeader=="function"&&(a.setHeader("X-Content-Type-Options","nosniff"),n&&a.setHeader("X-Frame-Options",n),r&&a.setHeader("Referrer-Policy",r),s&&a.setHeader("Cache-Control",s),t&&a.setHeader("Content-Security-Policy",t)),await i();}}var vr,Sr,wn,It=Le(()=>{"use strict";vr="https://cdn.jsdelivr.net",Sr="https://www.gstatic.com",wn=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${vr} ${Sr}`,`style-src 'self' 'unsafe-inline' ${vr}`,`connect-src 'self' ${Sr} 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 zt(e){if(e===null)return "null";if(e===void 0)return "undefined";if(e instanceof Timestamp)return "timestamp";if(e instanceof Date)return "date";if(Array.isArray(e))return "array";let t=typeof e;return t==="string"||t==="number"||t==="boolean"?t:"object"}function Ke(e,t,n=new WeakMap){if(e===t)return true;if(e===null||t===null||e===void 0||t===void 0)return e===t;if(e instanceof Timestamp&&t instanceof Timestamp)return e.isEqual(t);if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return false;if(n.get(e)===t)return true;n.set(e,t);for(let r=0;r<e.length;r++)if(!Ke(e[r],t[r],n))return false;return true}if(typeof e=="object"&&typeof t=="object"){if(e instanceof Date||t instanceof Date||e instanceof Timestamp||t instanceof Timestamp)return false;if(n.get(e)===t)return true;n.set(e,t);let r=Object.keys(e),s=Object.keys(t);if(r.length!==s.length)return false;for(let o of r)if(!Object.prototype.hasOwnProperty.call(t,o)||!Ke(e[o],t[o],n))return false;return true}return false}function Ht(e,t,n={}){let r=new Set([...n.exclude??[],...n.metaFields??[],...n.systemKeys??[]]),s=n.include?new Set(n.include):null,o=e??{},a=t??{},i=new Set([...Object.keys(o),...Object.keys(a)]),l={};for(let y of i){if(r.has(y)||s&&!s.has(y))continue;let g=o[y],b=a[y];Ke(g,b)||(l[y]={oldValue:g===void 0?null:g,newValue:b===void 0?null:b,type:{old:zt(g),new:zt(b)}});}return l}var as=7e5;function qt(e){let t=e.ttlOverride??e.config.ttl,r={schemaVersion:2,historyDocId:randomUUID(),historyToObjectId:e.entityId,historySetAt:Timestamp.now(),operation:e.operation,meta:e.meta,changes:e.changes};t&&(r.expiresAt=Timestamp.fromMillis(Date.now()+t.days*24*60*60*1e3));let s=o=>{try{return Buffer.byteLength(JSON.stringify(o,(a,i)=>i instanceof Timestamp?i.toMillis():i),"utf8")}catch{return 0}};if(s(r.changes)>as){let o={};for(let[a,i]of Object.entries(r.changes)){let l=s(i.oldValue),y=s(i.newValue);o[a]={oldValue:l>5e4?"[truncated]":i.oldValue,newValue:y>5e4?"[truncated]":i.newValue,type:i.type};}r.changes=o,r._truncated=true;}return r}async function Zt(e,t,n,r){let s=t;return n.onBeforeWrite&&(s=await n.onBeforeWrite(t,r)),s?(await e.doc(s.historyDocId).set(s),{written:true,entry:s}):{written:false,reason:"dropped-by-onBeforeWrite"}}function Lt(e,t){let n=e??{},r={},s=t.meta;if(!s)return r;let o=g=>{if(!g)return;let b=n[g];return b===void 0||b===null?null:String(b)},a=o(s.userId);a!==void 0&&(r.userId=a);let i=o(s.userEmail);i!==void 0&&(r.userEmail=i);let l=o(s.reason);l!==void 0&&(r.reason=l);let y=o(s.comment);if(y!==void 0&&(r.comment=y),s.extras&&s.extras.length>0){let g={},b=false;for(let v of s.extras)v in n&&(g[v]=n[v],b=true);b&&(r.extras=g);}return r}function Ut(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 is="history";function cs(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 ls(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 ds(e,t){return t?`${t}/{docId}`:(console.warn(`[HistoryTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function Pn(e,t){let{onDocumentWritten:n}=t.deps,r={},s=e?.rawMapping,o=s?Object.entries(s).map(([a,i])=>[a,cs(i)]):Object.entries(e).map(([a,i])=>[a,ls(i)]);for(let[a,i]of o){let l=i.historyConfig;if(!l?.enabled)continue;let y=l.subcollection??is,g=l.ttl??t.defaults?.ttl,b=t.repos?.[a],v;if(i.isGroup){if(!b?.triggerPath){console.warn(`[HistoryTriggers] Skipping collection-group repo "${a}". Provide a triggerPath in the history triggers repos override.`);continue}v=b.triggerPath;}else v=b?.triggerPath??ds(a,i.collectionPath);if(!v)continue;let C=i.systemKeys,R=C[0]??"docId",T=Ut(l),P={...t.triggerOptions,...l?.triggerOptions,...b?.triggerOptions},N=Object.keys(P).length>0,S=async d=>{try{let p=d.data?.before?.data(),u=d.data?.after?.data(),c;if(!p&&u)c="create";else if(p&&!u)c="delete";else if(p&&u)c="update";else return;let f=String(u?.[R]??p?.[R]??d.params?.docId??d.data?.after?.id??d.data?.before?.id??"");if(!f)return;let m=Ht(p??{},u??{},{include:l.include,exclude:l.exclude,metaFields:T,systemKeys:C});if(c==="update"&&Object.keys(m).length===0)return;let x=Lt(u??p??null,l),h=qt({entityId:f,operation:c,changes:m,meta:x,config:l,ttlOverride:g}),w=d.data?.after?.ref??d.data?.before?.ref;if(!w)return;let O=w.collection(y);await Zt(O,h,l,{repoName:a,docId:f,before:p??null,after:u??null});}catch(p){console.error(`[HistoryTriggers] Failed to record history for "${a}":`,p);}};r[`${a}_onHistory`]=n(N?{document:v,...P}:v,S);}return r}var Dn="preserve";function Wt(){return Dn}function us(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function _n(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof Timestamp)return e.toDate();if(us(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 Re(e){return e}function ys(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(s=>s.trim().replace(/\s*[:=].*$/,"").trim()).filter(Boolean);return r.length<=2?[]:r.slice(1,-1)}function ms(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?ys(e?.refCb):[],relationalKeys:e?.relationalKeys,_historyConfig:n,_historySubcollection:n?.enabled?n.subcollection??"history":void 0,_collectionPath:typeof e?.path=="string"?e.path:null}}function ht(e,t){let n=ms(e),r,s=()=>{let o=r??(r=t());if(!o){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 o};return new Proxy(n,{get(o,a){return typeof a=="string"&&a in n?n[a]:s()[a]},has(o,a){return typeof a=="string"&&a in n?true:a in s()}})}function hs(e){let t=[],n=e.replace(/[.*+?^${}()|[\]\\]/g,r=>r===":"?r:`\\${r}`).replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(r,s)=>(t.push(s),"([^/]+)"));return {pattern:new RegExp(`^${n}$`),paramNames:t}}function gs(e){let t=e.path??e.url??"/",n=t.indexOf("?");return n===-1?t:t.slice(0,n)}var ye=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:s,paramNames:o}=hs(n);return this.routes.push({method:t.toUpperCase(),pattern:s,paramNames:o,handler:r}),this}async handle(t,n){let r=(t.method??"GET").toUpperCase(),s=gs(t),o=null,a={};for(let y of this.routes){if(y.method!==r)continue;let g=s.match(y.pattern);if(g){o=y,a={},y.paramNames.forEach((b,v)=>{a[b]=decodeURIComponent(g[v+1]??"");});break}}let i=Object.assign(t,{params:a}),l=o?o.handler:this.notFoundHandler;try{await this.runMiddlewareChain(i,n,l);}catch(y){this.errorHandler(y,t,n);}}async runMiddlewareChain(t,n,r){let s=0,o=async()=>{if(s<this.middlewares.length){let a=this.middlewares[s++];await a(t,n,o);}else await r(t,n);};await o();}};function de(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",i=n??process.env.FUNCTION_REGION??"us-central1",l=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${a}/${i}/${l}${r}`}let s=process.env.K_SERVICE,o=e?.hostname??e?.headers?.host??"";return s&&typeof o=="string"&&o.includes("cloudfunctions.net")?`/${s.toLowerCase()}${r}`:r}function gt(e){if(typeof e=="string")return e;if(Array.isArray(e)){let t=e[0];return typeof t=="string"?t:void 0}}function We(e){return !!e&&typeof e=="object"&&e.__authExtension===true}function Vt(e,t,n=new WeakSet,r=0){if(e==null)return null;if(typeof e=="object"&&typeof e.toDate=="function")return e.toDate().toISOString();if(e instanceof Date)return e.toISOString();if(Buffer.isBuffer(e))return e.toString("base64");if(e instanceof Uint8Array)return Buffer.from(e).toString("base64");if(typeof e=="object"&&"latitude"in e&&"longitude"in e){let s=e;return t?.stringifyArrays===false?{lat:s.latitude,lng:s.longitude}:JSON.stringify({lat:s.latitude,lng:s.longitude})}if(Array.isArray(e)){let s=e.map(o=>Vt(o,t,n,r+1));return t?.stringifyArrays===false?s:JSON.stringify(s)}return typeof e=="object"&&e!==null&&t?.stringifyArrays===false?Qt(e,new Set,{},n,r+1):e}var Mn=32,xs=5e3;function Fn(e,t,n,r=new WeakSet,s=0){if(s>Mn){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[o,a]of Object.entries(e)){if(Object.keys(n).length>=xs)break;let i=t?`${t}__${o}`:o;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)?Fn(a,i,n,r,s+1):n[i]=Vt(a);}r.delete(e);}function Qt(e,t,n,r=new WeakSet,s=0){if(s>Mn)return {__truncated:true};if(r.has(e))return {__cycle:true};r.add(e);let o={};for(let[a,i]of Object.entries(e)){if(t.has(a))continue;let l=n[a]??a;i!=null&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)&&!Buffer.isBuffer(i)&&!(i instanceof Uint8Array)&&typeof i.toDate!="function"&&!("latitude"in i&&"longitude"in i)?o[l]=Qt(i,new Set,{},r,s+1):o[l]=Vt(i,{stringifyArrays:false},r,s+1);}return r.delete(e),o}function zn(e){let t={};for(let[n,r]of Object.entries(e)){let s=r;if(typeof s=="string"){let i=s.trim();if(i.startsWith("[")&&i.endsWith("]")||i.startsWith("{")&&i.endsWith("}"))try{s=JSON.parse(i);}catch{}}if(n.startsWith("__")||!n.includes("__")){t[n]=s;continue}let o=n.split("__").filter(Boolean),a=t;for(let i=0;i<o.length-1;i++){let l=o[i];(!a[l]||typeof a[l]!="object"||Array.isArray(a[l]))&&(a[l]={}),a=a[l];}a[o[o.length-1]]=s;}return t}function Ve(e,t){let n=t?.flat!==false,r;if(n){let s=new Set(t?.exclude),o=t?.columnMap??{},a={};Fn(e,"",a),r={};for(let[i,l]of Object.entries(a)){if(s.has(i))continue;let y=i.split("__")[0];if(y!==i&&s.has(y))continue;let g=o[i]??(i.includes("__")?o[i.split("__").pop()]:void 0)??i;r[g]=l;}}else {let s=new Set(t?.exclude),o=t?.columnMap??{};r=Qt(e,s,o);}return typeof t?.transformDoc=="function"&&(r=t.transformDoc(r)),r}function me(e,t,n){return `<!DOCTYPE html>
1
+ import {jsx,jsxs,Fragment}from'hono/jsx/jsx-runtime';import {randomUUID,randomBytes}from'crypto';import {Timestamp}from'firebase-admin/firestore';import {z as z$1}from'zod';import {renderToString}from'hono/jsx/dom/server';import {extendZodWithOpenApi,OpenAPIRegistry,OpenApiGeneratorV31,getOpenApiMetadata}from'@asteasolutions/zod-to-openapi';import {Hono}from'hono';import {getRequestListener}from'@hono/node-server';import {AsyncLocalStorage}from'async_hooks';var qt=Object.defineProperty;var so=Object.getOwnPropertyDescriptor;var ao=Object.getOwnPropertyNames;var io=Object.prototype.hasOwnProperty;var In=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var We=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Dn=(e,t)=>{for(var n in t)qt(e,n,{get:t[n],enumerable:true});},co=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ao(t))!io.call(e,o)&&o!==n&&qt(e,o,{get:()=>t[o],enumerable:!(r=so(t,o))||r.enumerable});return e};var lo=e=>co(qt({},"__esModule",{value:true}),e);function K(e){let t=e,n=t._zod?.def?.type;if(n)return Io[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=t._def?.typeName;return r||""}function ne(e){let t=e;if(t._zod?.def?.innerType)return t._zod.def.innerType;if(t._def?.innerType)return t._def.innerType}function Xe(e){let t=e,n=t._zod?.def?.in;if(n)return n;if(t._def?.schema)return t._def.schema}function Rt(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}function Wn(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 re(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 et(e){let t=e;return Array.isArray(t.options)?t.options:t._zod?.def?.entries?Object.values(t._zod.def.entries):Array.isArray(t._def?.values)?t._def.values:[]}function tt(e){let t=e;return t._zod?.def?.entries?t._zod.def.entries:t.enum&&typeof t.enum=="object"?t.enum:t._def?.values&&typeof t._def.values=="object"?t._def.values:{}}function nt(e){let t=e;return Array.isArray(t._zod?.def?.values)?t._zod.def.values[0]:t._def?.value}function rt(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 Gn(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 Io,Fe=We(()=>{"use strict";Io={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 dr({val:e}){return jsx("span",{class:"text-sm text-base-content/80 font-mono tabular-nums whitespace-nowrap",children:e.toLocaleString()})}function es({message:e}){return jsx("span",{class:"tooltip tooltip-warning tooltip-right inline-flex align-middle ml-1 text-warning","data-tip":e,role:"img","aria-label":e,children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",class:"size-3.5",children:jsx("path",{d:"M12 2 1 22h22L12 2zm0 6 7.5 13h-15L12 8zm-1 4v4h2v-4h-2zm0 5v2h2v-2h-2z"})})})}function Be({val:e,mismatch:t}){let n=an(e);return t?jsxs("span",{class:"inline-flex items-start gap-0.5",children:[n,jsx(es,{message:t})]}):n}function an(e){if(e==null)return jsx("span",{class:"opacity-30 italic text-xs",children:"\u2014"});if(typeof e=="boolean")return e?jsx("span",{class:"badge badge-success badge-sm",children:"true"}):jsx("span",{class:"badge badge-error badge-sm",children:"false"});if(e instanceof Date)return jsx(dr,{val:e});if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")return jsx(dr,{val:e.toDate()});if(typeof e=="number")return jsx("span",{class:"text-sm font-mono tabular-nums",children:String(e)});if(Array.isArray(e))return e.length===0?jsx("span",{class:"text-xs text-base-content/30",children:"[]"}):jsxs("ul",{class:"list-none p-0 m-0 space-y-0.5 text-xs",children:[e.slice(0,8).map((n,r)=>jsx("li",{class:"break-all",children:an(n)},r)),e.length>8&&jsxs("li",{class:"text-base-content/40 italic",children:["+",e.length-8," more\u2026"]})]});if(typeof e=="object"&&e!==null){let n=Object.entries(e);return n.length===0?jsx("span",{class:"text-xs text-base-content/30",children:"{}"}):jsxs("dl",{class:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 text-xs m-0",children:[n.slice(0,8).map(([r,o])=>jsxs(Fragment,{children:[jsx("dt",{class:"text-base-content/50 font-semibold whitespace-nowrap",children:r}),jsx("dd",{class:"break-all",children:an(o)})]})),n.length>8&&jsxs("dt",{class:"col-span-2 text-base-content/40 italic",children:["+",n.length-8," more\u2026"]})]})}let t=String(e);return jsx("span",{class:"text-sm break-all",children:t})}var Pt=We(()=>{"use strict";});function ct(e){if(!e)return "unknown";let t=cn(e);switch(K(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 cn(e){let t=K(e);if(t==="ZodOptional"||t==="ZodNullable"||t==="ZodDefault"){let n=ne(e);return n?cn(n):e}return e}function lt(e,t){if(!e)return;let n=t.split("."),r=e;for(let o of n){if(!r)return;let s=cn(r);if(K(s)!=="ZodObject")return;r=re(s)[o];}return r}function os(e){return e==null?"null":e instanceof Date?"date":Array.isArray(e)?"array":typeof e=="string"?"string":typeof e=="boolean"?"boolean":typeof e=="bigint"?"bigint":typeof e=="number"?"number":typeof e=="object"?typeof e.toDate=="function"?"date":"object":"unknown"}function dt(e,t){if(e==="unknown")return null;let n=os(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 ln=We(()=>{"use strict";Fe();});var fr={};Dn(fr,{PanelMany:()=>as,PanelOne:()=>ss,RightPanel:()=>dn});function ss({doc:e,repoName:t,basePath:n,schema:r,columns:o}){if(!e)return jsx("div",{class:"text-center py-12 text-base-content/50",children:"Document not found."});let s=String(e.docId??e.id??""),a=`${n}/${t}/${encodeURIComponent(s)}/edit`,i=pr(r,o);return jsxs("div",{class:"space-y-4",children:[jsxs("div",{class:"flex items-center justify-between gap-2",children:[jsxs("div",{class:"text-xs text-base-content/60",children:[jsx("span",{class:"font-mono",children:t}),jsx("span",{class:"opacity-50",children:" \xB7 "}),jsx("span",{class:"font-mono break-all",children:s})]}),jsx("a",{href:a,class:"btn btn-sm btn-primary",children:"Edit \u2192"})]}),jsx("dl",{class:"grid grid-cols-[max-content_1fr] gap-x-4 gap-y-2 border border-base-300 rounded-box p-4 bg-base-100",children:o.map(c=>{let y=e[c],h=i[c],m=h?dt(h,y):null;return jsxs(Fragment,{children:[jsx("dt",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide pt-0.5",children:c}),jsx("dd",{class:"min-w-0",children:jsx(Be,{val:y,mismatch:m})})]})})})]})}function as({docs:e,repoName:t,basePath:n,fk:r,fv:o,columns:s,schema:a,pagination:i}){let c=`${n}/${t}?fv_${r}=${encodeURIComponent(o)}`,y=pr(a,s);return jsxs("div",{class:"space-y-4",children:[jsxs("div",{class:"flex items-center justify-between gap-2",children:[jsxs("div",{class:"text-xs text-base-content/60",children:[jsx("span",{class:"font-mono",children:t}),jsx("span",{class:"opacity-50",children:" where "}),jsx("span",{class:"font-mono",children:r}),jsx("span",{class:"opacity-50",children:" = "}),jsx("span",{class:"font-mono break-all",children:o}),jsx("span",{class:"opacity-50",children:" \xB7 "}),jsxs("span",{children:[e.length," doc",e.length!==1?"s":""]})]}),jsx("a",{href:c,class:"btn btn-sm btn-outline",children:"Full view \u2192"})]}),jsx("div",{class:"overflow-x-auto rounded-box border border-base-300 bg-base-100",children:jsxs("table",{class:"table table-xs w-full",children:[jsx("thead",{children:jsxs("tr",{class:"bg-base-200/50",children:[s.map((h,m)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:h},m)),jsx("th",{})]})}),jsx("tbody",{children:e.length===0?jsx("tr",{children:jsx("td",{colspan:s.length+1,class:"text-center py-10 text-base-content/40",children:"No related documents"})}):e.map((h,m)=>{let x=String(h.docId??h.id??""),C=`${n}/${t}/${encodeURIComponent(x)}/edit`;return jsxs("tr",{class:"hover",children:[s.map((T,k)=>{let E=h[T],N=y[T],S=N?dt(N,E):null;return jsx("td",{class:"align-top py-1.5",children:jsx(Be,{val:E,mismatch:S})},k)}),jsx("td",{class:"text-right py-1.5",children:jsx("a",{href:C,class:"btn btn-xs btn-ghost",children:"Edit"})})]},m)})})]})}),(i.hasPrev||i.hasNext)&&jsxs("div",{class:"flex justify-center items-center gap-2",children:[i.hasPrev?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"prev","data-cursor":i.prevCursor,children:"\u2190 Previous"}):jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"\u2190 Previous"}),i.hasNext?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"next","data-cursor":i.nextCursor,children:"Next \u2192"}):jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"Next \u2192"})]})]})}function pr(e,t){if(!e)return {};let n={};for(let r of t)n[r]=ct(lt(e,r));return n}var dn,un=We(()=>{"use strict";Pt();ln();dn=({basePath:e=""})=>jsxs("div",{class:"fixed inset-0 z-[100] hidden pointer-events-none","data-frs-panel-root":!0,"data-frs-base-path":e,"aria-hidden":"true",children:[jsx("div",{class:"absolute inset-0 bg-black/30 opacity-0 transition-opacity duration-200 pointer-events-auto","data-frs-panel-backdrop":!0}),jsxs("aside",{class:"absolute top-0 right-0 h-full w-full md:w-1/2 bg-base-100 shadow-2xl border-l border-base-300 translate-x-full transition-transform duration-200 pointer-events-auto flex flex-col","data-frs-panel":!0,role:"dialog","aria-label":"Relation preview",children:[jsxs("header",{class:"flex items-center justify-between px-5 py-3 border-b border-base-300 bg-base-200/40 shrink-0",children:[jsx("h2",{class:"font-semibold text-base truncate","data-frs-panel-title":!0,children:"Relation"}),jsx("button",{type:"button",class:"btn btn-sm btn-ghost btn-circle","data-frs-panel-close":!0,"aria-label":"Close panel",children:"\u2715"})]}),jsx("div",{class:"flex-1 overflow-auto p-5 text-sm","data-frs-panel-body":!0,children:jsx("div",{class:"flex items-center justify-center py-12 text-base-content/40",children:jsx("span",{class:"loading loading-spinner loading-md"})})})]})]});});var Or={};Dn(Or,{DEFAULT_HTML_CSP:()=>Rn,securityHeaders:()=>jt});function jt(e={}){let t=e.csp===void 0?Rn: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,i)=>{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 i();}}var Ar,Cr,Rn,Nt=We(()=>{"use strict";Ar="https://cdn.jsdelivr.net",Cr="https://www.gstatic.com",Rn=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${Ar} ${Cr}`,`style-src 'self' 'unsafe-inline' ${Ar}`,`connect-src 'self' ${Cr} https://*.googleapis.com https://*.firebaseio.com https://identitytoolkit.googleapis.com`,"img-src 'self' data:","font-src 'self' data:","frame-ancestors 'none'","base-uri 'self'","form-action 'self'"].join("; ");});var Zt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Ne(){let e="";for(;e.length<20;){let t=randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let r=t[n];r>=Zt.length*4||(e+=Zt.charAt(r%Zt.length));}}return e}function _n(e){return e.match(/^\{([^}]+)\}$/)?.[1]?.trim()||null}function me(e,t="docId",n=false){if(typeof e!="string"||!e.trim())return {rawPath:e??"",collectionId:"",collectionPath:"",parentKeys:[],documentPathTemplate:null,hasTemplate:false};let r=e.split("/").map(m=>m.trim()).filter(Boolean);if(r.length===0)return {rawPath:e,collectionId:e,collectionPath:e,parentKeys:[],documentPathTemplate:null,hasTemplate:false};if(r.length===1){let m=r[0];return {rawPath:e,collectionId:m,collectionPath:m,parentKeys:[],documentPathTemplate:n?null:`${m}/{${t}}`,hasTemplate:e.includes("{")&&e.includes("}")}}let o=r.length%2===0,s=o?r.slice(0,-1):r,a=s[s.length-1],i=s.join("/"),y=s.slice(0,-1).map(_n).filter(m=>m!==null),h=o?r.join("/"):`${i}/{${t}}`;return {rawPath:e,collectionId:a,collectionPath:i,parentKeys:y,documentPathTemplate:h,hasTemplate:true}}function Ge(e,t={}){if(!e||typeof e!="object")return;let{pathKey:n,documentKey:r="docId",parentKeys:o,documentPathTemplate:s,isGroup:a}=t,i=n&&typeof e[n]=="string"&&e[n]?e[n]:void 0;if(i&&s){let c=i.split("/").filter(Boolean),y=s.split("/").filter(Boolean);if(c.length===y.length){let h=[];for(let m=0;m<y.length;m++)_n(y[m])!==null&&h.push(c[m]);if(h.length>0)return h}}if(o&&o.length>0){let c=o.length+1;if(i){let h=i.split("/").filter(Boolean),m=[];for(let x=1;x<h.length;x+=2)m.push(h[x]);if(m.length>=c)return m.slice(m.length-c)}let y=r?e[r]:void 0;if(typeof y=="string"&&y.trim()!==""){let h=[],m=true;for(let x of o){let C=e[x];if(typeof C=="string"&&C.trim()!=="")h.push(C);else {m=false;break}}if(m)return [...h,y]}}if(i){let c=i.split("/").filter(Boolean),y=[];for(let h=1;h<c.length;h+=2)y.push(c[h]);if(y.length>0)return !a&&(!o||o.length===0)?[y[y.length-1]]:y}}function Lt(e){if(e===null)return "null";if(e===void 0)return "undefined";if(e instanceof Timestamp)return "timestamp";if(e instanceof Date)return "date";if(Array.isArray(e))return "array";let t=typeof e;return t==="string"||t==="number"||t==="boolean"?t:"object"}function Qe(e,t,n=new WeakMap){if(e===t)return true;if(e===null||t===null||e===void 0||t===void 0)return e===t;if(e instanceof Timestamp&&t instanceof Timestamp)return e.isEqual(t);if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return false;if(n.get(e)===t)return true;n.set(e,t);for(let r=0;r<e.length;r++)if(!Qe(e[r],t[r],n))return false;return true}if(typeof e=="object"&&typeof t=="object"){if(e instanceof Date||t instanceof Date||e instanceof Timestamp||t instanceof Timestamp)return false;if(n.get(e)===t)return true;n.set(e,t);let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return false;for(let s of r)if(!Object.prototype.hasOwnProperty.call(t,s)||!Qe(e[s],t[s],n))return false;return true}return false}function Ut(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??{},i=new Set([...Object.keys(s),...Object.keys(a)]),c={};for(let y of i){if(r.has(y)||o&&!o.has(y))continue;let h=s[y],m=a[y];Qe(h,m)||(c[y]={oldValue:h===void 0?null:h,newValue:m===void 0?null:m,type:{old:Lt(h),new:Lt(m)}});}return c}var fo=7e5;function Wt(e){let t=e.ttlOverride??e.config.ttl,r={schemaVersion:2,historyDocId:randomUUID(),historyToObjectId:e.entityId,historySetAt:Timestamp.now(),operation:e.operation,meta:e.meta,changes:e.changes};t&&(r.expiresAt=Timestamp.fromMillis(Date.now()+t.days*24*60*60*1e3));let o=s=>{try{return Buffer.byteLength(JSON.stringify(s,(a,i)=>i instanceof Timestamp?i.toMillis():i),"utf8")}catch{return 0}};if(o(r.changes)>fo){let s={};for(let[a,i]of Object.entries(r.changes)){let c=o(i.oldValue),y=o(i.newValue);s[a]={oldValue:c>5e4?"[truncated]":i.oldValue,newValue:y>5e4?"[truncated]":i.newValue,type:i.type};}r.changes=s,r._truncated=true;}return r}async function Gt(e,t,n,r){let o=t;return n.onBeforeWrite&&(o=await n.onBeforeWrite(t,r)),o?(await e.doc(o.historyDocId).set(o),{written:true,entry:o}):{written:false,reason:"dropped-by-onBeforeWrite"}}function Vt(e,t){let n=e??{},r={},o=t.meta;if(!o)return r;let s=h=>{if(!h)return;let m=n[h];return m===void 0||m===null?null:String(m)},a=s(o.userId);a!==void 0&&(r.userId=a);let i=s(o.userEmail);i!==void 0&&(r.userEmail=i);let c=s(o.reason);c!==void 0&&(r.reason=c);let y=s(o.comment);if(y!==void 0&&(r.comment=y),o.extras&&o.extras.length>0){let h={},m=false;for(let x of o.extras)x in n&&(h[x]=n[x],m=true);m&&(r.extras=h);}return r}function Qt(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 yo="history";function mo(e){let t=e&&typeof e.history=="object"&&e.history!==null?e.history:void 0,n=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(s=>typeof s=="string"),r=typeof e?.path=="string"?e.path:null,o=r?me(r,e?.documentKey??"docId"):null;return {historyConfig:t,systemKeys:n,isGroup:!!e?.isGroup,collectionPath:o?o.collectionPath:null,documentPathTemplate:o&&(!e?.isGroup||o.collectionPath.includes("/"))?o.documentPathTemplate:null}}function ho(e){let t=e._historyConfig??(typeof e.history=="object"&&e.history!==null&&"enabled"in e.history?e.history:void 0),n=e._collectionPath??e.ref?.path??null,r=typeof e._documentPathTemplate=="string"?e._documentPathTemplate:null;return {historyConfig:t,systemKeys:e._systemKeys??[],isGroup:!!e._isGroup,collectionPath:n,documentPathTemplate:r&&(!e._isGroup||n&&n.includes("/"))?r:null}}function go(e,t){return t?`${t}/{docId}`:(console.warn(`[HistoryTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function jn(e,t){let{onDocumentWritten:n}=t.deps,r={},o=e?.rawMapping,s=o?Object.entries(o).map(([a,i])=>[a,mo(i)]):Object.entries(e).map(([a,i])=>[a,ho(i)]);for(let[a,i]of s){let c=i.historyConfig;if(!c?.enabled)continue;let y=c.subcollection??yo,h=c.ttl??t.defaults?.ttl,m=t.repos?.[a],x;if(i.isGroup){let l=m?.triggerPath??i.documentPathTemplate;if(!l){console.warn(`[HistoryTriggers] Skipping collection-group repo "${a}". Provide a triggerPath in the history triggers repos override or use a full path template.`);continue}x=l;}else x=m?.triggerPath??i.documentPathTemplate??go(a,i.collectionPath);if(!x)continue;let C=i.systemKeys,T=C[0]??"docId",k=Qt(c),E={...t.triggerOptions,...c?.triggerOptions,...m?.triggerOptions},N=Object.keys(E).length>0,S=async l=>{try{let p=l.data?.before?.data(),u=l.data?.after?.data(),d;if(!p&&u)d="create";else if(p&&!u)d="delete";else if(p&&u)d="update";else return;let f=String(u?.[T]??p?.[T]??l.params?.docId??l.data?.after?.id??l.data?.before?.id??"");if(!f)return;let g=Ut(p??{},u??{},{include:c.include,exclude:c.exclude,metaFields:k,systemKeys:C});if(d==="update"&&Object.keys(g).length===0)return;let v=Vt(u??p??null,c),b=Wt({entityId:f,operation:d,changes:g,meta:v,config:c,ttlOverride:h}),w=l.data?.after?.ref??l.data?.before?.ref;if(!w)return;let O=w.collection(y);await Gt(O,b,c,{repoName:a,docId:f,before:p??null,after:u??null});}catch(p){console.error(`[HistoryTriggers] Failed to record history for "${a}":`,p);}};r[`${a}_onHistory`]=n(N?{document:x,...E}:x,S);}return r}var Fn="preserve";function Yt(){return Fn}function bo(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function zn(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof Timestamp)return e.toDate();if(bo(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 ke(e){return e}function vo(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 So(e){let t=e?.documentKey??"docId",n=!!e?.isGroup,r=me(typeof e?.path=="string"?e.path:"",t,n),o=r.parentKeys.length>0?r.parentKeys:n?vo(e?.refCb):[],s=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(i=>typeof i=="string"),a=e?.history&&typeof e.history=="object"?e.history:void 0;return {schema:e?.schema,_systemKeys:s,_pathKey:e?.pathKey??null,_isGroup:n,_createdKey:e?.createdKey??null,_parentKeys:o,_documentPathTemplate:r.documentPathTemplate,_collectionId:typeof e?.path=="string"?r.collectionId:null,relationalKeys:e?.relationalKeys,_historyConfig:a,_historySubcollection:a?.enabled?a.subcollection??"history":void 0,_collectionPath:typeof e?.path=="string"?r.collectionPath:null}}function xt(e,t){let n=So(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 Ro(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 To(e){let t=e.path??e.url??"/",n=t.indexOf("?");return n===-1?t:t.slice(0,n)}var he=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}=Ro(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=To(t),s=null,a={};for(let y of this.routes){if(y.method!==r)continue;let h=o.match(y.pattern);if(h){s=y,a={},y.paramNames.forEach((m,x)=>{a[m]=decodeURIComponent(h[x+1]??"");});break}}let i=Object.assign(t,{params:a}),c=s?s.handler:this.notFoundHandler;try{await this.runMiddlewareChain(i,n,c);}catch(y){this.errorHandler(y,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 ue(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",i=n??process.env.FUNCTION_REGION??"us-central1",c=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${a}/${i}/${c}${r}`}let o=process.env.K_SERVICE,s=e?.hostname??e?.headers?.host??"";return o&&typeof s=="string"&&s.includes("cloudfunctions.net")?`/${o.toLowerCase()}${r}`:r}function vt(e){if(typeof e=="string")return e;if(Array.isArray(e)){let t=e[0];return typeof t=="string"?t:void 0}}function Je(e){return !!e&&typeof e=="object"&&e.__authExtension===true}function Xt(e,t,n=new WeakSet,r=0){if(e==null)return null;if(typeof e=="object"&&typeof e.toDate=="function")return e.toDate().toISOString();if(e instanceof Date)return e.toISOString();if(Buffer.isBuffer(e))return e.toString("base64");if(e instanceof Uint8Array)return Buffer.from(e).toString("base64");if(typeof e=="object"&&"latitude"in e&&"longitude"in e){let o=e;return t?.stringifyArrays===false?{lat:o.latitude,lng:o.longitude}:JSON.stringify({lat:o.latitude,lng:o.longitude})}if(Array.isArray(e)){let o=e.map(s=>Xt(s,t,n,r+1));return t?.stringifyArrays===false?o:JSON.stringify(o)}return typeof e=="object"&&e!==null&&t?.stringifyArrays===false?en(e,new Set,{},n,r+1):e}var qn=32,Co=5e3;function Zn(e,t,n,r=new WeakSet,o=0){if(o>qn){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>=Co)break;let i=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)?Zn(a,i,n,r,o+1):n[i]=Xt(a);}r.delete(e);}function en(e,t,n,r=new WeakSet,o=0){if(o>qn)return {__truncated:true};if(r.has(e))return {__cycle:true};r.add(e);let s={};for(let[a,i]of Object.entries(e)){if(t.has(a))continue;let c=n[a]??a;i!=null&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)&&!Buffer.isBuffer(i)&&!(i instanceof Uint8Array)&&typeof i.toDate!="function"&&!("latitude"in i&&"longitude"in i)?s[c]=en(i,new Set,{},r,o+1):s[c]=Xt(i,{stringifyArrays:false},r,o+1);}return r.delete(e),s}function Ln(e){let t={};for(let[n,r]of Object.entries(e)){let o=r;if(typeof o=="string"){let i=o.trim();if(i.startsWith("[")&&i.endsWith("]")||i.startsWith("{")&&i.endsWith("}"))try{o=JSON.parse(i);}catch{}}if(n.startsWith("__")||!n.includes("__")){t[n]=o;continue}let s=n.split("__").filter(Boolean),a=t;for(let i=0;i<s.length-1;i++){let c=s[i];(!a[c]||typeof a[c]!="object"||Array.isArray(a[c]))&&(a[c]={}),a=a[c];}a[s[s.length-1]]=o;}return t}function Ye(e,t){let n=t?.flat!==false,r;if(n){let o=new Set(t?.exclude),s=t?.columnMap??{},a={};Zn(e,"",a),r={};for(let[i,c]of Object.entries(a)){if(o.has(i))continue;let y=i.split("__")[0];if(y!==i&&o.has(y))continue;let h=s[i]??(i.includes("__")?s[i.split("__").pop()]:void 0)??i;r[h]=c;}}else {let o=new Set(t?.exclude),s=t?.columnMap??{};r=en(e,o,s);}return typeof t?.transformDoc=="function"&&(r=t.transformDoc(r)),r}function ge(e,t,n){return `<!DOCTYPE html>
2
2
  <html lang="en"><head>
3
3
  <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
4
4
  <title>${e} \u2014 Sync Admin</title>
@@ -28,75 +28,75 @@ import {jsx,jsxs,Fragment}from'hono/jsx/jsx-runtime';import {Timestamp}from'fire
28
28
  <nav><a href="${t}/">\u2190 Dashboard</a></nav>
29
29
  <h1>${e}</h1>
30
30
  ${n}
31
- </body></html>`}function he(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function _e(e,t,n=200){e.status(n).set("Content-Type","application/json").send(JSON.stringify(t,null,2));}function bt(e){return (e.headers?.accept??"").includes("application/json")}function Hn(e,t,n,r,s,o,a,i){let l=(s.basePath??"/").replace(/\/$/,"")||"",y=s.featuresFlag??{},g=gt(s.httpsOptions?.region),b=Array.isArray(t)?t:[t],v=e?.rawMapping,C=[],R=Object.keys(o??{}),T=R.length>0,P=Object.keys(v||e),N=T?R.filter(d=>P.includes(d)||d in e):P;for(let d of N){let p=o[d],u=v?ht(v[d],()=>e[d]):e[d],c=!!u._isGroup;if(!T&&c&&!p?.triggerPath)continue;let f=p?.adapters&&p.adapters.length>0?b.filter(m=>p.adapters.includes(m.name)):b;C.push({name:d,schema:u.schema??null,documentKey:u._systemKeys?.[0]??u.documentKey??"docId",tableName:p?.tableName??d,isGroup:c,repoCfg:p,repo:u,adapters:f});}let S=new ye;if(s.auth)if(We(s.auth)){let d=s.auth;for(let p of d.routes){let u=`${l}${p.path}`;p.method==="GET"?S.get(u,p.handler):S.post(u,p.handler);}S.use(d.middleware);}else if(typeof s.auth=="function")S.use(s.auth);else {let d=s.auth.realm??"Sync Admin",p="Basic "+Buffer.from(`${s.auth.username}:${s.auth.password}`).toString("base64");S.use((u,c,f)=>{if((u.headers?.authorization??"")!==p){c.status(401).set("WWW-Authenticate",`Basic realm="${d}"`).set("Content-Type","text/plain").send("Unauthorized");return}f();});}return S.get(`${l}/`,(d,p)=>{let u=de(d,l,g),c=C.map(x=>{let h=[];y.healthCheck&&h.push(`<a class="btn" href="${u}/${x.name}/health">Health</a>`),y.manualSync&&h.push(`<a class="btn btn-primary" href="${u}/${x.name}/force-sync">Force Sync</a>`);let w=x.adapters.map(O=>`<span class="badge badge-ok">${O.name}</span>`).join(" ");return `<tr>
32
- <td><strong>${x.name}</strong></td>
33
- <td>${x.tableName}</td>
31
+ </body></html>`}function be(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function Me(e,t,n=200){e.status(n).set("Content-Type","application/json").send(JSON.stringify(t,null,2));}function St(e){return (e.headers?.accept??"").includes("application/json")}function Un(e,t,n,r,o,s,a,i){let c=(o.basePath??"/").replace(/\/$/,"")||"",y=o.featuresFlag??{},h=vt(o.httpsOptions?.region),m=Array.isArray(t)?t:[t],x=e?.rawMapping,C=[],T=Object.keys(s??{}),k=T.length>0,E=Object.keys(x||e),N=k?T.filter(l=>E.includes(l)||l in e):E;for(let l of N){let p=s[l],u=x?xt(x[l],()=>e[l]):e[l],d=!!u._isGroup,f=u._collectionPath,g=typeof f=="string"&&f.includes("/");if(!k&&d&&!p?.triggerPath&&!g)continue;let v=p?.adapters&&p.adapters.length>0?m.filter(b=>p.adapters.includes(b.name)):m;C.push({name:l,schema:u.schema??null,documentKey:u._systemKeys?.[0]??u.documentKey??"docId",tableName:p?.tableName??l,isGroup:d,repoCfg:p,repo:u,adapters:v});}let S=new he;if(o.auth)if(Je(o.auth)){let l=o.auth;for(let p of l.routes){let u=`${c}${p.path}`;p.method==="GET"?S.get(u,p.handler):S.post(u,p.handler);}S.use(l.middleware);}else if(typeof o.auth=="function")S.use(o.auth);else {let l=o.auth.realm??"Sync Admin",p="Basic "+Buffer.from(`${o.auth.username}:${o.auth.password}`).toString("base64");S.use((u,d,f)=>{if((u.headers?.authorization??"")!==p){d.status(401).set("WWW-Authenticate",`Basic realm="${l}"`).set("Content-Type","text/plain").send("Unauthorized");return}f();});}return S.get(`${c}/`,(l,p)=>{let u=ue(l,c,h),d=C.map(v=>{let b=[];y.healthCheck&&b.push(`<a class="btn" href="${u}/${v.name}/health">Health</a>`),y.manualSync&&b.push(`<a class="btn btn-primary" href="${u}/${v.name}/force-sync">Force Sync</a>`);let w=v.adapters.map(O=>`<span class="badge badge-ok">${O.name}</span>`).join(" ");return `<tr>
32
+ <td><strong>${v.name}</strong></td>
33
+ <td>${v.tableName}</td>
34
34
  <td>${w||'<span class="badge badge-warn">none</span>'}</td>
35
- <td>${x.isGroup?'<span class="badge badge-warn">group</span>':'<span class="badge badge-ok">collection</span>'}</td>
36
- <td>${x.schema?"\u2713":"\u2717"}</td>
37
- <td>${h.join(" ")}</td>
35
+ <td>${v.isGroup?'<span class="badge badge-warn">group</span>':'<span class="badge badge-ok">collection</span>'}</td>
36
+ <td>${v.schema?"\u2713":"\u2717"}</td>
37
+ <td>${b.join(" ")}</td>
38
38
  </tr>`}).join(`
39
- `),f=y.configCheck?`<p style="margin-top:.5rem"><a class="btn" href="${u}/config-check">\u2699 Config Check</a></p>`:"",m=me("Sync Dashboard",u,`<div class="card">
39
+ `),f=y.configCheck?`<p style="margin-top:.5rem"><a class="btn" href="${u}/config-check">\u2699 Config Check</a></p>`:"",g=ge("Sync Dashboard",u,`<div class="card">
40
40
  <table>
41
41
  <thead><tr><th>Repository</th><th>Target Name</th><th>Adapters</th><th>Type</th><th>Schema</th><th>Actions</th></tr></thead>
42
- <tbody>${c}</tbody>
42
+ <tbody>${d}</tbody>
43
43
  </table>
44
44
  ${f}
45
- </div>`);he(p,m);}),S.get(`${l}`,(d,p)=>{let u=de(d,l,g);p.status(302).set("Location",`${u}/`).send("");}),y.healthCheck&&S.get(`${l}/:repoName/health`,async(d,p)=>{let u=de(d,l,g),c=C.find(w=>w.name===d.params.repoName);if(!c){he(p,me("Not Found",u,`<p>Unknown repo: ${d.params.repoName}</p>`),404);return}let f=[];for(let w of c.adapters)if(typeof w.healthCheck=="function"){let O=await w.healthCheck({targetName:c.tableName,primaryKey:c.documentKey,schema:c.schema??void 0,repoConfig:c.repoCfg});f.push({adapterName:w.name,health:O});}else try{let O=await w.targetExists(c.tableName);f.push({adapterName:w.name,health:{healthy:O,targetName:c.tableName,targetExists:O,error:O?null:`Target "${c.tableName}" does not exist`}});}catch(O){f.push({adapterName:w.name,health:{healthy:false,targetName:c.tableName,targetExists:false,error:O?.message??String(O)}});}let m=f.length>0&&f.every(w=>w.health.healthy);if(bt(d)){_e(p,{repo:c.name,targetName:c.tableName,healthy:m,adapters:f.map(w=>({name:w.adapterName,...w.health}))});return}let x=w=>{let{adapterName:O,health:$}=w,I=$.healthy?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Unhealthy</span>',_="",k=$.details;if(k?.expected&&Array.isArray(k.expected)){let D=k.expected,j=new Set(k.actual??[]),A=k.extra??[],E=D.map(Z=>{let U=j.has(Z.name)?'<span class="badge badge-ok">OK</span>':'<span class="badge badge-err">MISSING</span>';return `<tr><td>${Z.name}</td><td>${Z.type}</td><td>${Z.nullable?"Yes":"No"}</td><td>${Z.isPrimaryKey?"\u2713":""}</td><td>${U}</td></tr>`}).join(`
45
+ </div>`);be(p,g);}),S.get(`${c}`,(l,p)=>{let u=ue(l,c,h);p.status(302).set("Location",`${u}/`).send("");}),y.healthCheck&&S.get(`${c}/:repoName/health`,async(l,p)=>{let u=ue(l,c,h),d=C.find(w=>w.name===l.params.repoName);if(!d){be(p,ge("Not Found",u,`<p>Unknown repo: ${l.params.repoName}</p>`),404);return}let f=[];for(let w of d.adapters)if(typeof w.healthCheck=="function"){let O=await w.healthCheck({targetName:d.tableName,primaryKey:d.documentKey,schema:d.schema??void 0,repoConfig:d.repoCfg});f.push({adapterName:w.name,health:O});}else try{let O=await w.targetExists(d.tableName);f.push({adapterName:w.name,health:{healthy:O,targetName:d.tableName,targetExists:O,error:O?null:`Target "${d.tableName}" does not exist`}});}catch(O){f.push({adapterName:w.name,health:{healthy:false,targetName:d.tableName,targetExists:false,error:O?.message??String(O)}});}let g=f.length>0&&f.every(w=>w.health.healthy);if(St(l)){Me(p,{repo:d.name,targetName:d.tableName,healthy:g,adapters:f.map(w=>({name:w.adapterName,...w.health}))});return}let v=w=>{let{adapterName:O,health:I}=w,P=I.healthy?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Unhealthy</span>',_="",R=I.details;if(R?.expected&&Array.isArray(R.expected)){let D=R.expected,j=new Set(R.actual??[]),A=R.extra??[],$=D.map(Z=>{let U=j.has(Z.name)?'<span class="badge badge-ok">OK</span>':'<span class="badge badge-err">MISSING</span>';return `<tr><td>${Z.name}</td><td>${Z.type}</td><td>${Z.nullable?"Yes":"No"}</td><td>${Z.isPrimaryKey?"\u2713":""}</td><td>${U}</td></tr>`}).join(`
46
46
  `),M=A.map(Z=>`<tr><td>${Z}</td><td colspan="3" class="muted">not in schema</td><td><span class="badge badge-warn">EXTRA</span></td></tr>`).join(`
47
47
  `);_=`<h2>Columns</h2>
48
48
  <table>
49
49
  <thead><tr><th>Column</th><th>SQL Type</th><th>Nullable</th><th>PK</th><th>Status</th></tr></thead>
50
- <tbody>${E}${M}</tbody>
51
- </table>`;}else k?.numberOfDocuments!==void 0&&(_=`<h2>Index Stats</h2>
50
+ <tbody>${$}${M}</tbody>
51
+ </table>`;}else R?.numberOfDocuments!==void 0&&(_=`<h2>Index Stats</h2>
52
52
  <table>
53
- <tr><th>Documents Count</th><td>${k.numberOfDocuments}</td></tr>
54
- <tr><th>Indexing in Progress</th><td>${k.isIndexing?'<span class="badge badge-warn">Yes</span>':'<span class="badge badge-ok">No</span>'}</td></tr>
55
- <tr><th>Primary Key</th><td><code>${k.primaryKey??"default"}</code></td></tr>
53
+ <tr><th>Documents Count</th><td>${R.numberOfDocuments}</td></tr>
54
+ <tr><th>Indexing in Progress</th><td>${R.isIndexing?'<span class="badge badge-warn">Yes</span>':'<span class="badge badge-ok">No</span>'}</td></tr>
55
+ <tr><th>Primary Key</th><td><code>${R.primaryKey??"default"}</code></td></tr>
56
56
  </table>`);return `<div class="card" style="margin-top:1rem">
57
- <h2>Adapter: <code>${O}</code> ${I}</h2>
58
- <p>Target: <code>${$.targetName}</code> ${$.targetExists?"":'<span class="badge badge-err">NOT FOUND</span>'}</p>
59
- ${$.error?`<p class="badge badge-err" style="margin-top:.5rem">Error: ${$.error}</p>`:""}
57
+ <h2>Adapter: <code>${O}</code> ${P}</h2>
58
+ <p>Target: <code>${I.targetName}</code> ${I.targetExists?"":'<span class="badge badge-err">NOT FOUND</span>'}</p>
59
+ ${I.error?`<p class="badge badge-err" style="margin-top:.5rem">Error: ${I.error}</p>`:""}
60
60
  ${_}
61
- </div>`},h=me(`Health: ${c.name}`,u,`<div class="card">
62
- <p>Overall status for <strong>${c.name}</strong>: ${m?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Issues detected</span>'}</p>
61
+ </div>`},b=ge(`Health: ${d.name}`,u,`<div class="card">
62
+ <p>Overall status for <strong>${d.name}</strong>: ${g?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Issues detected</span>'}</p>
63
63
  </div>
64
- ${f.map(x).join(`
65
- `)}`);he(p,h);}),y.manualSync&&(S.get(`${l}/:repoName/force-sync`,(d,p)=>{let u=de(d,l,g),c=C.find(m=>m.name===d.params.repoName);if(!c){he(p,me("Not Found",u,`<p>Unknown repo: ${d.params.repoName}</p>`),404);return}let f=me(`Force Sync: ${c.name}`,u,`<div class="card">
66
- <p>This will read <strong>all</strong> documents from the <code>${c.name}</code> Firestore collection
67
- and upsert them into all active target storage adapters (${c.adapters.map(m=>m.name).join(", ")}).</p>
64
+ ${f.map(v).join(`
65
+ `)}`);be(p,b);}),y.manualSync&&(S.get(`${c}/:repoName/force-sync`,(l,p)=>{let u=ue(l,c,h),d=C.find(g=>g.name===l.params.repoName);if(!d){be(p,ge("Not Found",u,`<p>Unknown repo: ${l.params.repoName}</p>`),404);return}let f=ge(`Force Sync: ${d.name}`,u,`<div class="card">
66
+ <p>This will read <strong>all</strong> documents from the <code>${d.name}</code> Firestore collection
67
+ and upsert them into all active target storage adapters (${d.adapters.map(g=>g.name).join(", ")}).</p>
68
68
  <p class="muted" style="margin:.75rem 0">This may take a while for large collections.</p>
69
- <form method="POST" action="${u}/${c.name}/force-sync">
69
+ <form method="POST" action="${u}/${d.name}/force-sync">
70
70
  <button type="submit" class="btn btn-primary">Start Force Sync</button>
71
71
  </form>
72
- </div>`);he(p,f);}),S.post(`${l}/:repoName/force-sync`,async(d,p)=>{let u=de(d,l,g),c=C.find(k=>k.name===d.params.repoName);if(!c){_e(p,{error:`Unknown repo: ${d.params.repoName}`},404);return}let f=c.repo.ref;if(!f){_e(p,{error:`No collection reference for "${c.name}"`},400);return}let m=0,x=0,h=[],w=500,O=f.limit(w),$=null;try{for(;;){let D=await($?O.startAfter($):O).get();if(D.empty)break;for(let j of D.docs){let A=j.data(),E=String(A[c.documentKey]??j.id),M=Ve(A,{exclude:c.repoCfg?.exclude,columnMap:c.repoCfg?.columnMap,flat:c.repoCfg?.flat,transformDoc:c.repoCfg?.transformDoc});try{await r({operation:"UPSERT",repoName:c.name,docId:E,data:M,timestamp:new Date().toISOString()}),m++;}catch(Z){x++;let U=Z?.message??String(Z);console.error(`[ForceSync:${c.name}] doc=${E} failed:`,Z),h.length<5&&h.push(`${E}: ${U}`);}}if($=D.docs[D.docs.length-1],D.docs.length<w)break}for(let k of c.adapters){let D=`${c.name}:${k.name}`,j=n.get(D)??n.get(c.name);j&&await j.flush();}}catch(k){if(bt(d)){_e(p,{error:k?.message??String(k),synced:m,errors:x},500);return}he(p,me(`Force Sync: ${c.name}`,u,`<div class="card">
73
- <p class="badge badge-err">Error: ${k?.message??String(k)}</p>
74
- <p>Synced ${m} docs before failure (${x} errors).</p>
75
- </div>`),500);return}if(bt(d)){_e(p,{repo:c.name,table:c.tableName,synced:m,errors:x,...h.length>0&&{errorSamples:h}});return}let I=h.length>0?`<details style="margin-top:1rem"><summary>First ${h.length} error(s)</summary>
76
- <pre style="white-space:pre-wrap">${h.map(k=>k.replace(/[<>&]/g,D=>`&#${D.charCodeAt(0)};`)).join(`
72
+ </div>`);be(p,f);}),S.post(`${c}/:repoName/force-sync`,async(l,p)=>{let u=ue(l,c,h),d=C.find(R=>R.name===l.params.repoName);if(!d){Me(p,{error:`Unknown repo: ${l.params.repoName}`},404);return}let f=d.repo.ref;if(!f){Me(p,{error:`No collection reference for "${d.name}"`},400);return}let g=0,v=0,b=[],w=500,O=f.limit(w),I=null;try{for(;;){let D=await(I?O.startAfter(I):O).get();if(D.empty)break;for(let j of D.docs){let A=j.data(),$=String(A[d.documentKey]??j.id),M=Ye(A,{exclude:d.repoCfg?.exclude,columnMap:d.repoCfg?.columnMap,flat:d.repoCfg?.flat,transformDoc:d.repoCfg?.transformDoc});try{await r({operation:"UPSERT",repoName:d.name,docId:$,data:M,timestamp:new Date().toISOString()}),g++;}catch(Z){v++;let U=Z?.message??String(Z);console.error(`[ForceSync:${d.name}] doc=${$} failed:`,Z),b.length<5&&b.push(`${$}: ${U}`);}}if(I=D.docs[D.docs.length-1],D.docs.length<w)break}for(let R of d.adapters){let D=`${d.name}:${R.name}`,j=n.get(D)??n.get(d.name);j&&await j.flush();}}catch(R){if(St(l)){Me(p,{error:R?.message??String(R),synced:g,errors:v},500);return}be(p,ge(`Force Sync: ${d.name}`,u,`<div class="card">
73
+ <p class="badge badge-err">Error: ${R?.message??String(R)}</p>
74
+ <p>Synced ${g} docs before failure (${v} errors).</p>
75
+ </div>`),500);return}if(St(l)){Me(p,{repo:d.name,table:d.tableName,synced:g,errors:v,...b.length>0&&{errorSamples:b}});return}let P=b.length>0?`<details style="margin-top:1rem"><summary>First ${b.length} error(s)</summary>
76
+ <pre style="white-space:pre-wrap">${b.map(R=>R.replace(/[<>&]/g,D=>`&#${D.charCodeAt(0)};`)).join(`
77
77
 
78
- `)}</pre></details>`:"",_=me(`Force Sync: ${c.name}`,u,`<div class="card">
79
- <p class="badge ${x>0?"badge-warn":"badge-ok"}">${x>0?"Completed with errors":"Complete"}</p>
80
- <p>Synced <strong>${m}</strong> documents to targets (${c.adapters.map(k=>k.name).join(", ")}).</p>
81
- ${x>0?`<p class="badge badge-warn">${x} error(s)</p>`:""}
82
- ${I}
83
- </div>`);he(p,_);})),y.configCheck&&S.get(`${l}/config-check`,async(d,p)=>{let u=de(d,l,g),c=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCP_PROJECT??"unknown",f="https://console.cloud.google.com",m=i??"firestore-sync",x=[];for(let k of b)if(k.name==="bigquery")try{await k.targetExists("__nonexistent_health_check__"),x.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable"});}catch(D){let j=D?.message??String(D),A=j.toLowerCase(),E=A.includes("disabled")||A.includes("has not been used")||A.includes("accessnotconfigured"),M=A.includes("permission")||j.includes("403")||A.includes("access denied"),Z=A.includes("project")&&A.includes("not found"),U=A.includes("not found")||j.includes("404");E?x.push({name:"BigQuery API",category:"bigquery",status:"error",message:"BigQuery API is not enabled",fix:{gcloud:`gcloud services enable bigquery.googleapis.com --project=${c}`,console:`${f}/apis/library/bigquery.googleapis.com?project=${c}`}}):Z?x.push({name:"BigQuery Project",category:"bigquery",status:"error",message:j,fix:{hint:"The GCP project does not exist or the credentials don't have access to it.",console:`${f}/home/dashboard`}}):M?x.push({name:"BigQuery API",category:"bigquery",status:"error",message:`Permission denied: ${j}`,fix:{hint:"Grant the service account BigQuery Data Editor + BigQuery Job User roles",console:`${f}/iam-admin/iam?project=${c}`}}):U?x.push({name:"BigQuery Dataset",category:"bigquery",status:"error",message:`Dataset not found: ${j}`,fix:{hint:"Create the dataset first",gcloud:`bq mk --dataset ${c}:YOUR_DATASET_ID`,console:`${f}/bigquery?project=${c}`}}):x.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable (table lookup returned expected error)"});}else if(k.name==="meilisearch"||typeof k.checkConnection=="function")try{let D=typeof k.checkConnection=="function"?await k.checkConnection():{healthy:await k.targetExists("__nonexistent__")};x.push({name:"Meilisearch API",category:"meilisearch",status:D.healthy?"ok":"error",message:D.healthy?`Meilisearch is reachable${D.version?` (v${D.version})`:""}`:`Meilisearch connection error: ${D.error??"unknown"}`,...D.error&&{fix:{hint:"Ensure Meilisearch is running and host/apiKey options are valid."}}});}catch(D){x.push({name:"Meilisearch API",category:"meilisearch",status:"error",message:`Meilisearch error: ${D?.message??String(D)}`});}for(let k of C)for(let D of k.adapters){let j=D.name==="bigquery"?"bigquery":D.name==="meilisearch"?"meilisearch":"storage";try{let A=await D.targetExists(k.tableName);x.push({name:`[${D.name}] Target: ${k.tableName}`,category:j,status:A?"ok":"warn",message:A?`Target \`${k.tableName}\` exists`:`Target \`${k.tableName}\` does not exist yet`,...!A&&{fix:{hint:"Target will be auto-created on first sync if autoMigrate is enabled."}}});}catch(A){x.push({name:`[${D.name}] Target: ${k.tableName}`,category:j,status:"error",message:A?.message??String(A)});}}if(a)for(let k of C){let D=`${m}-${k.name}`;try{let j=a.topic(D);if(typeof j.exists=="function"){let[A]=await j.exists();x.push({name:`Topic: ${D}`,category:"pubsub",status:A?"ok":"error",message:A?`Topic \`${D}\` exists`:`Topic \`${D}\` does not exist`,...!A&&{fix:{gcloud:`gcloud pubsub topics create ${D} --project=${c}`,console:`${f}/cloudpubsub/topic/list?project=${c}`}}});}else x.push({name:`Topic: ${D}`,category:"pubsub",status:"warn",message:"Cannot verify topic existence (PubSub client doesn't expose .exists())",fix:{gcloud:`gcloud pubsub topics create ${D} --project=${c}`,console:`${f}/cloudpubsub/topic/list?project=${c}`}});}catch(j){let A=j?.message??String(j),E=A.includes("disabled")||A.includes("has not been used");if(x.push({name:E?"Pub/Sub API":`Topic: ${D}`,category:"pubsub",status:"error",message:E?"Pub/Sub API is not enabled":A,fix:E?{gcloud:`gcloud services enable pubsub.googleapis.com --project=${c}`,console:`${f}/apis/library/pubsub.googleapis.com?project=${c}`}:{gcloud:`gcloud pubsub topics create ${D} --project=${c}`,console:`${f}/cloudpubsub/topic/list?project=${c}`}}),E)break}}else x.push({name:"Pub/Sub Client",category:"pubsub",status:"warn",message:"PubSub client not available for config check"});if(bt(d)){let k=x.every(D=>D.status==="ok");_e(p,{project:c,healthy:k,checks:x});return}let h=k=>k==="ok"?'<span class="badge badge-ok">OK</span>':k==="warn"?'<span class="badge badge-warn">WARN</span>':'<span class="badge badge-err">ERROR</span>',w={bigquery:x.filter(k=>k.category==="bigquery"),meilisearch:x.filter(k=>k.category==="meilisearch"),pubsub:x.filter(k=>k.category==="pubsub"),firestore:x.filter(k=>k.category==="firestore"),storage:x.filter(k=>k.category==="storage")},O=(k,D)=>{if(D.length===0)return "";let j=D.map(A=>{let E="";if(A.fix){let M=[];A.fix.hint&&M.push(`<p class="muted">${A.fix.hint}</p>`),A.fix.gcloud&&M.push(`<pre>$ ${A.fix.gcloud}</pre>`),A.fix.console&&M.push(`<p><a href="${A.fix.console}" target="_blank">Open GCP Console \u2192</a></p>`),E=`<div style="margin-top:.5rem">${M.join("")}</div>`;}return `<tr>
84
- <td>${h(A.status)}</td>
85
- <td><strong>${A.name}</strong><br><span class="muted">${A.message}</span>${E}</td>
78
+ `)}</pre></details>`:"",_=ge(`Force Sync: ${d.name}`,u,`<div class="card">
79
+ <p class="badge ${v>0?"badge-warn":"badge-ok"}">${v>0?"Completed with errors":"Complete"}</p>
80
+ <p>Synced <strong>${g}</strong> documents to targets (${d.adapters.map(R=>R.name).join(", ")}).</p>
81
+ ${v>0?`<p class="badge badge-warn">${v} error(s)</p>`:""}
82
+ ${P}
83
+ </div>`);be(p,_);})),y.configCheck&&S.get(`${c}/config-check`,async(l,p)=>{let u=ue(l,c,h),d=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCP_PROJECT??"unknown",f="https://console.cloud.google.com",g=i??"firestore-sync",v=[];for(let R of m)if(R.name==="bigquery")try{await R.targetExists("__nonexistent_health_check__"),v.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable"});}catch(D){let j=D?.message??String(D),A=j.toLowerCase(),$=A.includes("disabled")||A.includes("has not been used")||A.includes("accessnotconfigured"),M=A.includes("permission")||j.includes("403")||A.includes("access denied"),Z=A.includes("project")&&A.includes("not found"),U=A.includes("not found")||j.includes("404");$?v.push({name:"BigQuery API",category:"bigquery",status:"error",message:"BigQuery API is not enabled",fix:{gcloud:`gcloud services enable bigquery.googleapis.com --project=${d}`,console:`${f}/apis/library/bigquery.googleapis.com?project=${d}`}}):Z?v.push({name:"BigQuery Project",category:"bigquery",status:"error",message:j,fix:{hint:"The GCP project does not exist or the credentials don't have access to it.",console:`${f}/home/dashboard`}}):M?v.push({name:"BigQuery API",category:"bigquery",status:"error",message:`Permission denied: ${j}`,fix:{hint:"Grant the service account BigQuery Data Editor + BigQuery Job User roles",console:`${f}/iam-admin/iam?project=${d}`}}):U?v.push({name:"BigQuery Dataset",category:"bigquery",status:"error",message:`Dataset not found: ${j}`,fix:{hint:"Create the dataset first",gcloud:`bq mk --dataset ${d}:YOUR_DATASET_ID`,console:`${f}/bigquery?project=${d}`}}):v.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable (table lookup returned expected error)"});}else if(R.name==="meilisearch"||typeof R.checkConnection=="function")try{let D=typeof R.checkConnection=="function"?await R.checkConnection():{healthy:await R.targetExists("__nonexistent__")};v.push({name:"Meilisearch API",category:"meilisearch",status:D.healthy?"ok":"error",message:D.healthy?`Meilisearch is reachable${D.version?` (v${D.version})`:""}`:`Meilisearch connection error: ${D.error??"unknown"}`,...D.error&&{fix:{hint:"Ensure Meilisearch is running and host/apiKey options are valid."}}});}catch(D){v.push({name:"Meilisearch API",category:"meilisearch",status:"error",message:`Meilisearch error: ${D?.message??String(D)}`});}for(let R of C)for(let D of R.adapters){let j=D.name==="bigquery"?"bigquery":D.name==="meilisearch"?"meilisearch":"storage";try{let A=await D.targetExists(R.tableName);v.push({name:`[${D.name}] Target: ${R.tableName}`,category:j,status:A?"ok":"warn",message:A?`Target \`${R.tableName}\` exists`:`Target \`${R.tableName}\` does not exist yet`,...!A&&{fix:{hint:"Target will be auto-created on first sync if autoMigrate is enabled."}}});}catch(A){v.push({name:`[${D.name}] Target: ${R.tableName}`,category:j,status:"error",message:A?.message??String(A)});}}if(a)for(let R of C){let D=`${g}-${R.name}`;try{let j=a.topic(D);if(typeof j.exists=="function"){let[A]=await j.exists();v.push({name:`Topic: ${D}`,category:"pubsub",status:A?"ok":"error",message:A?`Topic \`${D}\` exists`:`Topic \`${D}\` does not exist`,...!A&&{fix:{gcloud:`gcloud pubsub topics create ${D} --project=${d}`,console:`${f}/cloudpubsub/topic/list?project=${d}`}}});}else v.push({name:`Topic: ${D}`,category:"pubsub",status:"warn",message:"Cannot verify topic existence (PubSub client doesn't expose .exists())",fix:{gcloud:`gcloud pubsub topics create ${D} --project=${d}`,console:`${f}/cloudpubsub/topic/list?project=${d}`}});}catch(j){let A=j?.message??String(j),$=A.includes("disabled")||A.includes("has not been used");if(v.push({name:$?"Pub/Sub API":`Topic: ${D}`,category:"pubsub",status:"error",message:$?"Pub/Sub API is not enabled":A,fix:$?{gcloud:`gcloud services enable pubsub.googleapis.com --project=${d}`,console:`${f}/apis/library/pubsub.googleapis.com?project=${d}`}:{gcloud:`gcloud pubsub topics create ${D} --project=${d}`,console:`${f}/cloudpubsub/topic/list?project=${d}`}}),$)break}}else v.push({name:"Pub/Sub Client",category:"pubsub",status:"warn",message:"PubSub client not available for config check"});if(St(l)){let R=v.every(D=>D.status==="ok");Me(p,{project:d,healthy:R,checks:v});return}let b=R=>R==="ok"?'<span class="badge badge-ok">OK</span>':R==="warn"?'<span class="badge badge-warn">WARN</span>':'<span class="badge badge-err">ERROR</span>',w={bigquery:v.filter(R=>R.category==="bigquery"),meilisearch:v.filter(R=>R.category==="meilisearch"),pubsub:v.filter(R=>R.category==="pubsub"),firestore:v.filter(R=>R.category==="firestore"),storage:v.filter(R=>R.category==="storage")},O=(R,D)=>{if(D.length===0)return "";let j=D.map(A=>{let $="";if(A.fix){let M=[];A.fix.hint&&M.push(`<p class="muted">${A.fix.hint}</p>`),A.fix.gcloud&&M.push(`<pre>$ ${A.fix.gcloud}</pre>`),A.fix.console&&M.push(`<p><a href="${A.fix.console}" target="_blank">Open GCP Console \u2192</a></p>`),$=`<div style="margin-top:.5rem">${M.join("")}</div>`;}return `<tr>
84
+ <td>${b(A.status)}</td>
85
+ <td><strong>${A.name}</strong><br><span class="muted">${A.message}</span>${$}</td>
86
86
  </tr>`}).join(`
87
- `);return `<h2>${k}</h2>
87
+ `);return `<h2>${R}</h2>
88
88
  <table><thead><tr><th style="width:80px">Status</th><th>Check</th></tr></thead>
89
- <tbody>${j}</tbody></table>`},I=x.every(k=>k.status==="ok")?'<span class="badge badge-ok">All checks passed</span>':'<span class="badge badge-warn">Some issues found</span>',_=me("Config Check",u,`<div class="card">
90
- <p>Project: <code>${c}</code> ${I}</p>
89
+ <tbody>${j}</tbody></table>`},P=v.every(R=>R.status==="ok")?'<span class="badge badge-ok">All checks passed</span>':'<span class="badge badge-warn">Some issues found</span>',_=ge("Config Check",u,`<div class="card">
90
+ <p>Project: <code>${d}</code> ${P}</p>
91
91
  ${O("BigQuery",w.bigquery)}
92
92
  ${O("Meilisearch",w.meilisearch)}
93
93
  ${O("Pub/Sub",w.pubsub)}
94
94
  ${O("Other Targets",w.storage)}
95
95
  ${O("Firestore",w.firestore)}
96
- </div>`);he(p,_);}),async(d,p)=>{await S.handle(d,p);}}var vs="firestore-sync";function Ss(e,t){return t?`${t}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function Rs(e){let t=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(n=>typeof n=="string");return {isGroup:!!e?.isGroup,documentKey:t[0]??"docId",collectionPath:typeof e?.path=="string"?e.path:null}}function ks(e){return {isGroup:!!e?._isGroup,documentKey:e?._systemKeys?.[0]??"docId",collectionPath:e?.ref?.path??null}}function Bn(e,t){let{onDocumentWritten:n}=t.deps.firestoreTriggers,r=t.deps.pubsub,s=t?.topicPrefix??vs,o={},a=new Map;function i(R){let T=a.get(R);return T||(T=r.topic(R),a.set(R,T),T)}async function l(R,T){await i(R).publishMessage({json:T});}let y=e?.rawMapping,g=y?Object.entries(y).map(([R,T])=>[R,Rs(T)]):Object.entries(e).map(([R,T])=>[R,ks(T)]),b=t?.repos,C=Object.keys(b??{}).length>0;for(let[R,T]of g){if(C&&(!b||!(R in b)))continue;let P=b?.[R],N;if(T.isGroup){if(!P?.triggerPath){console.warn(`[SyncTriggers] Skipping collection-group repo "${R}". Provide a triggerPath in the sync repos config for group collections.`);continue}N=P.triggerPath;}else N=P?.triggerPath??Ss(R,T.collectionPath);if(!N)continue;let S=T.documentKey,d=`${s}-${R}`,p={...t?.triggerOptions,...P?.triggerOptions},u=Object.keys(p).length>0,c=async f=>{let m=f.data?.before,x=f.data?.after;if(!m&&!x)return;let h=!!m?.exists,w=!!x?.exists;if(!h&&w){let O=x.data();if(!O)return;let $=String(O[S]??x.id),I=Ve(O,{exclude:P?.exclude,columnMap:P?.columnMap,flat:P?.flat,transformDoc:P?.transformDoc}),_={operation:"INSERT",repoName:R,docId:$,data:I,timestamp:new Date().toISOString(),version:Date.now()};await l(d,_);}else if(h&&w){let O=x.data();if(!O)return;let $=String(O[S]??x.id),I=Ve(O,{exclude:P?.exclude,columnMap:P?.columnMap,flat:P?.flat,transformDoc:P?.transformDoc}),_={operation:"UPSERT",repoName:R,docId:$,data:I,timestamp:new Date().toISOString(),version:Date.now()};await l(d,_);}else if(h&&!w){let O=m.data(),$=String(O?.[S]??m.id),I={operation:"DELETE",repoName:R,docId:$,data:null,timestamp:new Date().toISOString(),version:Date.now()};await l(d,I);}};o[`${R}_onSync`]=n(u?{document:N,...p}:N,c);}return o}var ce="__sync_version";je();var As=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function Cs(e){let t=e,n=false;for(;;){let r=K(t);if(!As.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(n=true);let s=ne(t);if(!s)break;t=s;}return {inner:t,nullable:n}}var Os={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function Ln(e,t,n,r,s,o,a,i){for(let[l,y]of Object.entries(e)){let g=n?`${n}__${l}`:l;if(s.has(l)||s.has(g))continue;let{inner:b,nullable:v}=Cs(y),C=K(b),R=r||v;if(C==="ZodObject"){let S=re(b);Ln(S,t,g,R,s,o,a,i);continue}let T=Os[C]??"json",P=g===a||l===a,N=o[g]??o[l]??g;i.push({name:N,sqlType:t.mapType(T),nullable:P?false:R,isPrimaryKey:P});}}function et(e,t,n={}){let{primaryKey:r,exclude:s=[],columnMap:o={}}=n,a=new Set(s),i=re(e),l=[];return Ln(i,t,"",false,a,o,r,l),l.some(y=>y.name===ce)||l.push({name:ce,sqlType:t.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),l}var Rt=class{constructor(t){this.buffer=[];this.flushing=false;this.flushPromise=null;this.timer=null;this.adapter=t.adapter,this.tableName=t.tableName,this.primaryKey=t.primaryKey,this.batchSize=t.batchSize??100,this.onFlushError=t.onFlushError;let n=t.flushIntervalMs??5e3;n>0&&(this.timer=setInterval(()=>{this.flush();},n),typeof this.timer=="object"&&"unref"in this.timer&&this.timer.unref());}get size(){return this.buffer.length}enqueue(...t){this.buffer.push(...t),this.buffer.length>=this.batchSize&&this.flush();}async flush(){for(;this.flushPromise;)await this.flushPromise;this.buffer.length!==0&&(this.flushing=true,this.flushPromise=this._drain().finally(()=>{this.flushing=false,this.flushPromise=null;}),await this.flushPromise);}async _drain(){for(;this.buffer.length>0&&await this._doFlush(););}async _doFlush(){let t=this.buffer.splice(0,this.batchSize);try{let n=new Map,r=[];for(let o of t)if(o.operation==="DELETE")r.push(o.docId),n.delete(o.docId);else if(o.data){let a=n.get(o.docId);if(!a)n.set(o.docId,o.data);else {let i=Number(a[ce]??0);Number(o.data[ce]??0)>=i&&n.set(o.docId,o.data);}}let s=Array.from(n.values());s.length>0&&(typeof this.adapter.upsert=="function"?await this.adapter.upsert(this.tableName,s,this.primaryKey):typeof this.adapter.upsertRows=="function"&&await this.adapter.upsertRows(this.tableName,s,this.primaryKey)),r.length>0&&(typeof this.adapter.delete=="function"?await this.adapter.delete(this.tableName,this.primaryKey,r):typeof this.adapter.deleteRows=="function"&&await this.adapter.deleteRows(this.tableName,this.primaryKey,r));}catch(n){if(this.onFlushError)await this.onFlushError(t,n);else return this.buffer.unshift(...t),console.error(`[SyncQueue] Flush failed for ${this.tableName}:`,n),false}return true}async shutdown(){this.timer&&(clearInterval(this.timer),this.timer=null),await this.flush();}};var Vn=new Set;async function Ds(e,t,n,r,s,o,a){let i=`${e}:${t.name}`;if(!Vn.has(i)){if(typeof t.ensureTarget=="function")await t.ensureTarget({targetName:r,primaryKey:s,schema:n,exclude:o,columnMap:a});else if("dialect"in t&&typeof t.createTable=="function"){let l=t,y=et(n,l.dialect,{primaryKey:s,exclude:o,columnMap:a});if(!await l.tableExists(r))await l.createTable({tableName:r,columns:y});else {let b=new Set(await l.getTableColumns(r)),v=y.filter(C=>!b.has(C.name));v.length>0&&(await l.addColumns(r,v),await l.onSchemaChange?.(r));}}Vn.add(i);}}function Qn(e,t){let{deps:n,adapter:r,adapters:s,batchSize:o=100,flushIntervalMs:a=5e3,autoMigrate:i=false,topicPrefix:l="firestore-sync",maxDlqAttempts:y=5,workerOptions:g,repos:b={}}=t,C=(s||(Array.isArray(r)?r:r?[r]:[])).map(d=>typeof d=="function"?d():d);function R(d){let p=b[d];if(p?.adapters&&p.adapters.length>0){let u=new Set(p.adapters);return C.filter(c=>u.has(c.name))}return C}let T=new Map;function P(d,p,u){let c=`${d}:${p.name}`,f=T.get(c);if(f)return f;let x=b[d]?.tableName??d,h=`${l}-${d}-${p.name}-dlq`,w=n.pubsub.topic(h),O=false,$=async()=>{if(!O){try{await w.create(),console.info(`[SyncWorker:${p.name}] Created DLQ topic "${h}"`);}catch(_){if(_?.code!==6)throw _}O=true;}},I=async(_,k)=>{console.error(`[SyncWorker:${p.name}] Flush failed for "${d}" (${_.length} events):`,k),await $(),await Promise.all(_.map(D=>{let j=(D.attempts??0)+1;if(y>0&&j>y)return console.error(`[SyncWorker:${p.name}] Dropping event for "${d}" after ${j-1} DLQ attempts:`,{docId:D.docId,operation:D.operation}),Promise.resolve();let A={...D,attempts:j,firstFailedAt:D.firstFailedAt??Date.now()};return w.publishMessage({json:A})}));};return f=new Rt({adapter:p,tableName:x,primaryKey:u,batchSize:o,flushIntervalMs:a,onFlushError:I}),T.set(c,f),T.has(d)||T.set(d,f),f}async function N(d){let{repoName:p}=d,u=e[p];if(!u){console.warn(`[SyncWorker] Unknown repo "${p}", skipping event`);return}let c=u._systemKeys?.[0]??u.documentKey??"docId",f=b[p],m=f?.columnMap,x=m?.[c]??c;d.data&&(d.data[ce]=d.version??Date.now());let h=R(p);for(let w of h){if(i){let $=u.schema??void 0;if($){let I=f?.tableName??p;await Ds(p,w,$,I,x,f?.exclude,m);}}P(p,w,x).enqueue(d);}}function S(d){let p=async u=>{let c=u.data?.message?.json??u.data?.json;if(!c){console.warn("[SyncWorker] Received empty PubSub message");return}await N(c);let f=R(c.repoName);for(let m of f){let x=`${c.repoName}:${m.name}`,h=T.get(x);h&&await h.flush();}};return g?n.pubsubHandler.onMessagePublished({topic:d,...g},p):n.pubsubHandler.onMessagePublished(d,p)}return {handleMessage:N,createHandler:S,queues:T,async shutdown(){let d=[],p=new Set;for(let u of T.values())p.has(u)||(p.add(u),d.push(u.shutdown()));await Promise.all(d);}}}var _s="firestore-sync";function Gn(e){if(typeof e!="function")return e;let t=e,n;return new Proxy({},{get(r,s){return n||(n=t()),n[s]},has(r,s){return n||(n=t()),s in n}})}function Jn(e,t){let{deps:n,adapter:r,adapters:s,topicPrefix:o=_s,batchSize:a,flushIntervalMs:i,autoMigrate:l,admin:y,workerOptions:g,triggerOptions:b,repos:v}=t,C=Gn(n.pubsub),T=(s||(Array.isArray(r)?r:r?[r]:[])).map(w=>Gn(w)),P=Bn(e,{deps:{firestoreTriggers:n.firestoreTriggers,pubsub:C},topicPrefix:o,triggerOptions:b,repos:v}),N=Qn(e,{deps:{pubsubHandler:n.pubsubHandler,pubsub:C},adapters:T,batchSize:a,flushIntervalMs:i,autoMigrate:l,topicPrefix:o,workerOptions:g,repos:v}),S={},d=v,p=e?.rawMapping,u=Object.keys(d??{}),c=u.length>0,f=Object.keys(p||e),m=c?u.filter(w=>f.includes(w)||w in e):f;for(let w of m){let O=e?.rawMapping,$=O?!!O[w]?.isGroup:!!e[w]?._isGroup;!c&&$&&!d?.[w]?.triggerPath||(S[`sync_${w}`]=N.createHandler(`${o}-${w}`));}let x=null;y&&(x=Hn(e,T,N.queues,N.handleMessage,y,v??{},C,o),S.adminsync=y.onRequest?y.httpsOptions?y.onRequest(y.httpsOptions,x):y.onRequest(x):x);let h={functions:{...P,...S},adminHandler:x,handleMessage:N.handleMessage,queues:N.queues,shutdown:N.shutdown};for(let w of ["adminHandler","handleMessage","queues","shutdown"])Object.defineProperty(h,w,{enumerable:false});return h}function js(e){if(e.client)return e.client;if(!e.host)throw new Error("MeilisearchAdapter requires either a `client` instance or a `host` option.");try{let{MeiliSearch:t}=On("meilisearch");return new t({host:e.host,apiKey:e.apiKey})}catch(t){throw new Error(`Failed to load the "meilisearch" package. Please install it with:
96
+ </div>`);be(p,_);}),async(l,p)=>{await S.handle(l,p);}}var Oo="firestore-sync";function Eo(e,t){return t?`${t}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function Po(e){let t=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(o=>typeof o=="string"),n=typeof e?.path=="string"?e.path:null,r=n?me(n,e?.documentKey??"docId"):null;return {isGroup:!!e?.isGroup,documentKey:t[0]??"docId",collectionPath:r?r.collectionPath:null,documentPathTemplate:r&&(!e?.isGroup||r.collectionPath.includes("/"))?r.documentPathTemplate:null}}function $o(e){let t=e?._collectionPath??e?.ref?.path??null,n=typeof e?._documentPathTemplate=="string"?e._documentPathTemplate:null;return {isGroup:!!e?._isGroup,documentKey:e?._systemKeys?.[0]??"docId",collectionPath:t,documentPathTemplate:n&&(!e?._isGroup||t&&t.includes("/"))?n:null}}function Kn(e,t){let{onDocumentWritten:n}=t.deps.firestoreTriggers,r=t.deps.pubsub,o=t?.topicPrefix??Oo,s={},a=new Map;function i(T){let k=a.get(T);return k||(k=r.topic(T),a.set(T,k),k)}async function c(T,k){await i(T).publishMessage({json:k});}let y=e?.rawMapping,h=y?Object.entries(y).map(([T,k])=>[T,Po(k)]):Object.entries(e).map(([T,k])=>[T,$o(k)]),m=t?.repos,C=Object.keys(m??{}).length>0;for(let[T,k]of h){if(C&&(!m||!(T in m)))continue;let E=m?.[T],N;if(k.isGroup){let f=E?.triggerPath??k.documentPathTemplate;if(!f){console.warn(`[SyncTriggers] Skipping collection-group repo "${T}". Provide a triggerPath in the sync repos config for group collections or use a full path template.`);continue}N=f;}else N=E?.triggerPath??k.documentPathTemplate??Eo(T,k.collectionPath);if(!N)continue;let S=k.documentKey,l=`${o}-${T}`,p={...t?.triggerOptions,...E?.triggerOptions},u=Object.keys(p).length>0,d=async f=>{let g=f.data?.before,v=f.data?.after;if(!g&&!v)return;let b=!!g?.exists,w=!!v?.exists;if(!b&&w){let O=v.data();if(!O)return;let I=String(O[S]??v.id),P=Ye(O,{exclude:E?.exclude,columnMap:E?.columnMap,flat:E?.flat,transformDoc:E?.transformDoc}),_={operation:"INSERT",repoName:T,docId:I,data:P,timestamp:new Date().toISOString(),version:Date.now()};await c(l,_);}else if(b&&w){let O=v.data();if(!O)return;let I=String(O[S]??v.id),P=Ye(O,{exclude:E?.exclude,columnMap:E?.columnMap,flat:E?.flat,transformDoc:E?.transformDoc}),_={operation:"UPSERT",repoName:T,docId:I,data:P,timestamp:new Date().toISOString(),version:Date.now()};await c(l,_);}else if(b&&!w){let O=g.data(),I=String(O?.[S]??g.id),P={operation:"DELETE",repoName:T,docId:I,data:null,timestamp:new Date().toISOString(),version:Date.now()};await c(l,P);}};s[`${T}_onSync`]=n(u?{document:N,...p}:N,d);}return s}var le="__sync_version";Fe();var Do=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function _o(e){let t=e,n=false;for(;;){let r=K(t);if(!Do.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(n=true);let o=ne(t);if(!o)break;t=o;}return {inner:t,nullable:n}}var jo={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function Vn(e,t,n,r,o,s,a,i){for(let[c,y]of Object.entries(e)){let h=n?`${n}__${c}`:c;if(o.has(c)||o.has(h))continue;let{inner:m,nullable:x}=_o(y),C=K(m),T=r||x;if(C==="ZodObject"){let S=re(m);Vn(S,t,h,T,o,s,a,i);continue}let k=jo[C]??"json",E=h===a||c===a,N=s[h]??s[c]??h;i.push({name:N,sqlType:t.mapType(k),nullable:E?false:T,isPrimaryKey:E});}}function ot(e,t,n={}){let{primaryKey:r,exclude:o=[],columnMap:s={}}=n,a=new Set(o),i=re(e),c=[];return Vn(i,t,"",false,a,s,r,c),c.some(y=>y.name===le)||c.push({name:le,sqlType:t.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),c}var Ct=class{constructor(t){this.buffer=[];this.flushing=false;this.flushPromise=null;this.timer=null;this.adapter=t.adapter,this.tableName=t.tableName,this.primaryKey=t.primaryKey,this.batchSize=t.batchSize??100,this.onFlushError=t.onFlushError;let n=t.flushIntervalMs??5e3;n>0&&(this.timer=setInterval(()=>{this.flush();},n),typeof this.timer=="object"&&"unref"in this.timer&&this.timer.unref());}get size(){return this.buffer.length}enqueue(...t){this.buffer.push(...t),this.buffer.length>=this.batchSize&&this.flush();}async flush(){for(;this.flushPromise;)await this.flushPromise;this.buffer.length!==0&&(this.flushing=true,this.flushPromise=this._drain().finally(()=>{this.flushing=false,this.flushPromise=null;}),await this.flushPromise);}async _drain(){for(;this.buffer.length>0&&await this._doFlush(););}async _doFlush(){let t=this.buffer.splice(0,this.batchSize);try{let n=new Map,r=[];for(let s of t)if(s.operation==="DELETE")r.push(s.docId),n.delete(s.docId);else if(s.data){let a=n.get(s.docId);if(!a)n.set(s.docId,s.data);else {let i=Number(a[le]??0);Number(s.data[le]??0)>=i&&n.set(s.docId,s.data);}}let o=Array.from(n.values());o.length>0&&(typeof this.adapter.upsert=="function"?await this.adapter.upsert(this.tableName,o,this.primaryKey):typeof this.adapter.upsertRows=="function"&&await this.adapter.upsertRows(this.tableName,o,this.primaryKey)),r.length>0&&(typeof this.adapter.delete=="function"?await this.adapter.delete(this.tableName,this.primaryKey,r):typeof this.adapter.deleteRows=="function"&&await this.adapter.deleteRows(this.tableName,this.primaryKey,r));}catch(n){if(this.onFlushError)await this.onFlushError(t,n);else return this.buffer.unshift(...t),console.error(`[SyncQueue] Flush failed for ${this.tableName}:`,n),false}return true}async shutdown(){this.timer&&(clearInterval(this.timer),this.timer=null),await this.flush();}};var Xn=new Set;async function Ho(e,t,n,r,o,s,a){let i=`${e}:${t.name}`;if(!Xn.has(i)){if(typeof t.ensureTarget=="function")await t.ensureTarget({targetName:r,primaryKey:o,schema:n,exclude:s,columnMap:a});else if("dialect"in t&&typeof t.createTable=="function"){let c=t,y=ot(n,c.dialect,{primaryKey:o,exclude:s,columnMap:a});if(!await c.tableExists(r))await c.createTable({tableName:r,columns:y});else {let m=new Set(await c.getTableColumns(r)),x=y.filter(C=>!m.has(C.name));x.length>0&&(await c.addColumns(r,x),await c.onSchemaChange?.(r));}}Xn.add(i);}}function er(e,t){let{deps:n,adapter:r,adapters:o,batchSize:s=100,flushIntervalMs:a=5e3,autoMigrate:i=false,topicPrefix:c="firestore-sync",maxDlqAttempts:y=5,workerOptions:h,repos:m={}}=t,C=(o||(Array.isArray(r)?r:r?[r]:[])).map(l=>typeof l=="function"?l():l);function T(l){let p=m[l];if(p?.adapters&&p.adapters.length>0){let u=new Set(p.adapters);return C.filter(d=>u.has(d.name))}return C}let k=new Map;function E(l,p,u){let d=`${l}:${p.name}`,f=k.get(d);if(f)return f;let v=m[l]?.tableName??l,b=`${c}-${l}-${p.name}-dlq`,w=n.pubsub.topic(b),O=false,I=async()=>{if(!O){try{await w.create(),console.info(`[SyncWorker:${p.name}] Created DLQ topic "${b}"`);}catch(_){if(_?.code!==6)throw _}O=true;}},P=async(_,R)=>{console.error(`[SyncWorker:${p.name}] Flush failed for "${l}" (${_.length} events):`,R),await I(),await Promise.all(_.map(D=>{let j=(D.attempts??0)+1;if(y>0&&j>y)return console.error(`[SyncWorker:${p.name}] Dropping event for "${l}" after ${j-1} DLQ attempts:`,{docId:D.docId,operation:D.operation}),Promise.resolve();let A={...D,attempts:j,firstFailedAt:D.firstFailedAt??Date.now()};return w.publishMessage({json:A})}));};return f=new Ct({adapter:p,tableName:v,primaryKey:u,batchSize:s,flushIntervalMs:a,onFlushError:P}),k.set(d,f),k.has(l)||k.set(l,f),f}async function N(l){let{repoName:p}=l,u=e[p];if(!u){console.warn(`[SyncWorker] Unknown repo "${p}", skipping event`);return}let d=u._systemKeys?.[0]??u.documentKey??"docId",f=m[p],g=f?.columnMap,v=g?.[d]??d;l.data&&(l.data[le]=l.version??Date.now());let b=T(p);for(let w of b){if(i){let I=u.schema??void 0;if(I){let P=f?.tableName??p;await Ho(p,w,I,P,v,f?.exclude,g);}}E(p,w,v).enqueue(l);}}function S(l){let p=async u=>{let d=u.data?.message?.json??u.data?.json;if(!d){console.warn("[SyncWorker] Received empty PubSub message");return}await N(d);let f=T(d.repoName);for(let g of f){let v=`${d.repoName}:${g.name}`,b=k.get(v);b&&await b.flush();}};return h?n.pubsubHandler.onMessagePublished({topic:l,...h},p):n.pubsubHandler.onMessagePublished(l,p)}return {handleMessage:N,createHandler:S,queues:k,async shutdown(){let l=[],p=new Set;for(let u of k.values())p.has(u)||(p.add(u),l.push(u.shutdown()));await Promise.all(l);}}}var Bo="firestore-sync";function tr(e){if(typeof e!="function")return e;let t=e,n;return new Proxy({},{get(r,o){return n||(n=t()),n[o]},has(r,o){return n||(n=t()),o in n}})}function nr(e,t){let{deps:n,adapter:r,adapters:o,topicPrefix:s=Bo,batchSize:a,flushIntervalMs:i,autoMigrate:c,admin:y,workerOptions:h,triggerOptions:m,repos:x}=t,C=tr(n.pubsub),k=(o||(Array.isArray(r)?r:r?[r]:[])).map(w=>tr(w)),E=Kn(e,{deps:{firestoreTriggers:n.firestoreTriggers,pubsub:C},topicPrefix:s,triggerOptions:m,repos:x}),N=er(e,{deps:{pubsubHandler:n.pubsubHandler,pubsub:C},adapters:k,batchSize:a,flushIntervalMs:i,autoMigrate:c,topicPrefix:s,workerOptions:h,repos:x}),S={},l=x,p=e?.rawMapping,u=Object.keys(l??{}),d=u.length>0,f=Object.keys(p||e),g=d?u.filter(w=>f.includes(w)||w in e):f;for(let w of g){let O=e?.rawMapping,I=O?!!O[w]?.isGroup:!!e[w]?._isGroup,P=O?O[w]?.path:e[w]?._collectionPath,_=typeof P=="string"&&P.includes("/");!d&&I&&!l?.[w]?.triggerPath&&!_||(S[`sync_${w}`]=N.createHandler(`${s}-${w}`));}let v=null;y&&(v=Un(e,k,N.queues,N.handleMessage,y,x??{},C,s),S.adminsync=y.onRequest?y.httpsOptions?y.onRequest(y.httpsOptions,v):y.onRequest(v):v);let b={functions:{...E,...S},adminHandler:v,handleMessage:N.handleMessage,queues:N.queues,shutdown:N.shutdown};for(let w of ["adminHandler","handleMessage","queues","shutdown"])Object.defineProperty(b,w,{enumerable:false});return b}function qo(e){if(e.client)return e.client;if(!e.host)throw new Error("MeilisearchAdapter requires either a `client` instance or a `host` option.");try{let{MeiliSearch:t}=In("meilisearch");return new t({host:e.host,apiKey:e.apiKey})}catch(t){throw new Error(`Failed to load the "meilisearch" package. Please install it with:
97
97
  bun add meilisearch # or npm install meilisearch
98
- Original error: ${t?.message??String(t)}`)}}function Ns(e,t){if(!e||!t)return false;for(let[n,r]of Object.entries(t)){if(r===void 0)continue;let s=e[n];if(Array.isArray(r)){if(!Array.isArray(s)||r.length!==s.length)return false;for(let o=0;o<r.length;o++)if(r[o]!==s[o])return false}else if(typeof r=="object"&&r!==null){if(JSON.stringify(r)!==JSON.stringify(s))return false}else if(r!==s)return false}return true}var kt=class{constructor(t){this.name="meilisearch";this._client=null;this.options=t,t.client&&(this._client=t.client);}get indexesSettings(){return this.options.indexesSettings}get client(){return this._client||(this._client=js(this.options)),this._client}async targetExists(t){try{return await this.client.getIndex(t),!0}catch(n){if(n?.code==="index_not_found"||n?.cause?.code==="index_not_found"||n?.statusCode===404||n?.status===404||n?.response?.status===404||n?.cause?.status===404||n?.cause?.statusCode===404||n?.cause?.response?.status===404)return false;throw n}}async upsert(t,n,r){if(n.length===0)return;let s=this.options.unflatten!==false,o=n.map(i=>{let l=s?zn(i):i;return typeof this.options.transformDoc=="function"&&(l=this.options.transformDoc(l)),l});await this.client.index(t).addDocuments(o,{primaryKey:r});}async delete(t,n,r){if(r.length===0)return;await this.client.index(t).deleteDocuments(r);}async ensureTarget(t){let{targetName:n,primaryKey:r}=t;await this.targetExists(n)||await this.client.createIndex(n,{primaryKey:r});let o=this.options.indexesSettings?.[n];if(o){let{retrievableAttributes:a,attributesToRetrieve:i,...l}=o,y={...l,displayedAttributes:l.displayedAttributes??a??i};y.displayedAttributes===void 0&&delete y.displayedAttributes;let g=this.client.index(n);if(typeof g.getSettings=="function")try{let b=await g.getSettings();if(Ns(b,y))return}catch{}await g.updateSettings(y);}}async healthCheck(t){let{targetName:n}=t;try{if(!await this.targetExists(n))return {healthy:!1,targetName:n,targetExists:!1,error:`Meilisearch index "${n}" does not exist`};let s=this.client.index(n),o=await s.getStats(),a=typeof s.getRawInfo=="function"?await s.getRawInfo():{};return {healthy:!0,targetName:n,targetExists:!0,error:null,details:{numberOfDocuments:o?.numberOfDocuments??0,isIndexing:o?.isIndexing??!1,fieldDistribution:o?.fieldDistribution??{},primaryKey:a?.primaryKey??t.primaryKey}}}catch(r){return {healthy:false,targetName:n,targetExists:false,error:r?.message??String(r)}}}async checkConnection(){try{let t=!0;if(typeof this.client.isHealthy=="function"){let r=await this.client.isHealthy();t=r?.status==="available"||r===!0;}else if(typeof this.client.health=="function"){let r=await this.client.health();t=r?.status==="available"||r===!0;}let n;return typeof this.client.getVersion=="function"&&(n=(await this.client.getVersion())?.pkgVersion),{healthy:t,version:n}}catch(t){return {healthy:false,error:t?.message??String(t)}}}};je();je();function Ms(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/^\s/,"").replace(/^./,t=>t.toUpperCase())}function Yn(e){let t=e,n=true,r=false,s;for(;;){let o=K(t);if(o==="ZodOptional")n=false,t=ne(t);else if(o==="ZodNullable")n=false,r=true,t=ne(t);else if(o==="ZodDefault")n=false,s=qn(t),t=ne(t);else if(o==="ZodEffects"||o==="ZodPipe"||o==="ZodTransform"){let a=Qe(t);if(!a)break;t=a;}else break}return {inner:t,required:n,nullable:r,defaultValue:s}}function ie(e,t=""){if(K(e)==="ZodObject"){let r=re(e);return Object.entries(r).map(([s,o])=>Xn(t?`${t}.${s}`:s,s,o))}return [Xn(t||"value",t||"value",e)]}function Xn(e,t,n){let{inner:r,required:s,nullable:o,defaultValue:a}=Yn(n),i=K(r),l=Ms(t.split(".").pop()??t);switch(i){case "ZodString":{let y=Zn(r),g=y.includes("email"),b=y.includes("url");return {name:e,label:l,type:"text",required:s,nullable:o,defaultValue:a,hint:g?"email":b?"url":void 0}}case "ZodNumber":case "ZodBigInt":return {name:e,label:l,type:"number",required:s,nullable:o,defaultValue:a};case "ZodBoolean":return {name:e,label:l,type:"checkbox",required:s,nullable:o,defaultValue:a};case "ZodDate":case "ZodCoerce":return {name:e,label:l,type:"datetime-local",required:s,nullable:o,defaultValue:a};case "ZodEnum":{let y=Ge(r);return {name:e,label:l,type:"select",required:s,nullable:o,defaultValue:a,options:y}}case "ZodNativeEnum":{let y=Je(r),g=Object.values(y).filter(b=>typeof b=="string");return {name:e,label:l,type:"select",required:s,nullable:o,defaultValue:a,options:g}}case "ZodLiteral":{let y=String(Ye(r)??"");return {name:e,label:l,type:"select",required:s,nullable:o,defaultValue:a,options:[y]}}case "ZodUnion":{let y=Xe(r);if(y.length>0&&y.every(C=>K(C)==="ZodLiteral")){let C=y.map(R=>String(Ye(R)??""));return {name:e,label:l,type:"select",required:s,nullable:o,defaultValue:a,options:C}}if(y.some(C=>K(C)==="ZodDate"))return {name:e,label:l,type:"datetime-local",required:s,nullable:o,defaultValue:a};let v=y.find(C=>{if(K(C)==="ZodObject"){let R=re(C);return "_latitude"in R&&"_longitude"in R||"latitude"in R&&"longitude"in R}return false});return v?{name:e,label:l,type:"textarea",required:s,nullable:o,defaultValue:a,nested:ie(v,e),hint:"GeoPoint"}:{name:e,label:l,type:"textarea",required:s,nullable:o,defaultValue:a,hint:"JSON"}}case "ZodObject":{let y=ie(r,e);return {name:e,label:l,type:"textarea",required:s,nullable:o,defaultValue:a,nested:y,hint:"JSON object"}}case "ZodArray":{let y=wt(r);if(!y)return {name:e,label:l,type:"textarea",required:s,nullable:o,defaultValue:a,hint:"JSON array"};let{inner:g}=Yn(y),b=K(g),v,C,R;switch(b){case "ZodString":v="text";break;case "ZodNumber":case "ZodBigInt":v="number";break;case "ZodBoolean":v="checkbox";break;case "ZodDate":v="datetime-local";break;case "ZodEnum":v="select",C=Ge(g);break;case "ZodNativeEnum":v="select",C=Object.values(Je(g)).filter(T=>typeof T=="string");break;case "ZodObject":v="object",R=ie(g);break;default:return {name:e,label:l,type:"textarea",required:s,nullable:o,defaultValue:a,hint:"JSON array"}}return {name:e,label:l,type:"textarea",required:s,nullable:o,defaultValue:a,arrayElementType:v,arrayElementOptions:C,arrayElementFields:R}}default:return {name:e,label:l,type:"textarea",required:s,nullable:o,defaultValue:a,hint:"JSON"}}}function tt(e,t=0){let n=t>0?`ml-${t*4}`:"",r=`field_${e.name.replace(/\./g,"__")}`,s=e.name,o=e.required?" required":"",a=e.defaultValue==="__null__",i=!a&&e.defaultValue!=null?String(e.defaultValue):"",l=e.nullable&&e.type!=="checkbox"?`<span class="flex items-center gap-1 shrink-0">
99
- <input type="hidden" id="${r}__isnull" name="${s}__isnull" value="${a?"1":""}">
98
+ Original error: ${t?.message??String(t)}`)}}function Zo(e,t){if(!e||!t)return false;for(let[n,r]of Object.entries(t)){if(r===void 0)continue;let o=e[n];if(Array.isArray(r)){if(!Array.isArray(o)||r.length!==o.length)return false;for(let s=0;s<r.length;s++)if(r[s]!==o[s])return false}else if(typeof r=="object"&&r!==null){if(JSON.stringify(r)!==JSON.stringify(o))return false}else if(r!==o)return false}return true}var Ot=class{constructor(t){this.name="meilisearch";this._client=null;this.options=t,t.client&&(this._client=t.client);}get indexesSettings(){return this.options.indexesSettings}get client(){return this._client||(this._client=qo(this.options)),this._client}async targetExists(t){try{return await this.client.getIndex(t),!0}catch(n){if(n?.code==="index_not_found"||n?.cause?.code==="index_not_found"||n?.statusCode===404||n?.status===404||n?.response?.status===404||n?.cause?.status===404||n?.cause?.statusCode===404||n?.cause?.response?.status===404)return false;throw n}}async upsert(t,n,r){if(n.length===0)return;let o=this.options.unflatten!==false,s=n.map(i=>{let c=o?Ln(i):i;return typeof this.options.transformDoc=="function"&&(c=this.options.transformDoc(c)),c});await this.client.index(t).addDocuments(s,{primaryKey:r});}async delete(t,n,r){if(r.length===0)return;await this.client.index(t).deleteDocuments(r);}async ensureTarget(t){let{targetName:n,primaryKey:r}=t;await this.targetExists(n)||await this.client.createIndex(n,{primaryKey:r});let s=this.options.indexesSettings?.[n];if(s){let{retrievableAttributes:a,attributesToRetrieve:i,...c}=s,y={...c,displayedAttributes:c.displayedAttributes??a??i};y.displayedAttributes===void 0&&delete y.displayedAttributes;let h=this.client.index(n);if(typeof h.getSettings=="function")try{let m=await h.getSettings();if(Zo(m,y))return}catch{}await h.updateSettings(y);}}async healthCheck(t){let{targetName:n}=t;try{if(!await this.targetExists(n))return {healthy:!1,targetName:n,targetExists:!1,error:`Meilisearch index "${n}" does not exist`};let o=this.client.index(n),s=await o.getStats(),a=typeof o.getRawInfo=="function"?await o.getRawInfo():{};return {healthy:!0,targetName:n,targetExists:!0,error:null,details:{numberOfDocuments:s?.numberOfDocuments??0,isIndexing:s?.isIndexing??!1,fieldDistribution:s?.fieldDistribution??{},primaryKey:a?.primaryKey??t.primaryKey}}}catch(r){return {healthy:false,targetName:n,targetExists:false,error:r?.message??String(r)}}}async checkConnection(){try{let t=!0;if(typeof this.client.isHealthy=="function"){let r=await this.client.isHealthy();t=r?.status==="available"||r===!0;}else if(typeof this.client.health=="function"){let r=await this.client.health();t=r?.status==="available"||r===!0;}let n;return typeof this.client.getVersion=="function"&&(n=(await this.client.getVersion())?.pkgVersion),{healthy:t,version:n}}catch(t){return {healthy:false,error:t?.message??String(t)}}}};Fe();Fe();function Lo(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/^\s/,"").replace(/^./,t=>t.toUpperCase())}function rr(e){let t=e,n=true,r=false,o;for(;;){let s=K(t);if(s==="ZodOptional")n=false,t=ne(t);else if(s==="ZodNullable")n=false,r=true,t=ne(t);else if(s==="ZodDefault")n=false,o=Wn(t),t=ne(t);else if(s==="ZodEffects"||s==="ZodPipe"||s==="ZodTransform"){let a=Xe(t);if(!a)break;t=a;}else break}return {inner:t,required:n,nullable:r,defaultValue:o}}function ce(e,t=""){if(K(e)==="ZodObject"){let r=re(e);return Object.entries(r).map(([o,s])=>or(t?`${t}.${o}`:o,o,s))}return [or(t||"value",t||"value",e)]}function or(e,t,n){let{inner:r,required:o,nullable:s,defaultValue:a}=rr(n),i=K(r),c=Lo(t.split(".").pop()??t);switch(i){case "ZodString":{let y=Gn(r),h=y.includes("email"),m=y.includes("url");return {name:e,label:c,type:"text",required:o,nullable:s,defaultValue:a,hint:h?"email":m?"url":void 0}}case "ZodNumber":case "ZodBigInt":return {name:e,label:c,type:"number",required:o,nullable:s,defaultValue:a};case "ZodBoolean":return {name:e,label:c,type:"checkbox",required:o,nullable:s,defaultValue:a};case "ZodDate":case "ZodCoerce":return {name:e,label:c,type:"datetime-local",required:o,nullable:s,defaultValue:a};case "ZodEnum":{let y=et(r);return {name:e,label:c,type:"select",required:o,nullable:s,defaultValue:a,options:y}}case "ZodNativeEnum":{let y=tt(r),h=Object.values(y).filter(m=>typeof m=="string");return {name:e,label:c,type:"select",required:o,nullable:s,defaultValue:a,options:h}}case "ZodLiteral":{let y=String(nt(r)??"");return {name:e,label:c,type:"select",required:o,nullable:s,defaultValue:a,options:[y]}}case "ZodUnion":{let y=rt(r);if(y.length>0&&y.every(C=>K(C)==="ZodLiteral")){let C=y.map(T=>String(nt(T)??""));return {name:e,label:c,type:"select",required:o,nullable:s,defaultValue:a,options:C}}if(y.some(C=>K(C)==="ZodDate"))return {name:e,label:c,type:"datetime-local",required:o,nullable:s,defaultValue:a};let x=y.find(C=>{if(K(C)==="ZodObject"){let T=re(C);return "_latitude"in T&&"_longitude"in T||"latitude"in T&&"longitude"in T}return false});return x?{name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,nested:ce(x,e),hint:"GeoPoint"}:{name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON"}}case "ZodObject":{let y=ce(r,e);return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,nested:y,hint:"JSON object"}}case "ZodArray":{let y=Rt(r);if(!y)return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"};let{inner:h}=rr(y),m=K(h),x,C,T;switch(m){case "ZodString":x="text";break;case "ZodNumber":case "ZodBigInt":x="number";break;case "ZodBoolean":x="checkbox";break;case "ZodDate":x="datetime-local";break;case "ZodEnum":x="select",C=et(h);break;case "ZodNativeEnum":x="select",C=Object.values(tt(h)).filter(k=>typeof k=="string");break;case "ZodObject":x="object",T=ce(h);break;default:return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"}}return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,arrayElementType:x,arrayElementOptions:C,arrayElementFields:T}}default:return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON"}}}function st(e,t=0){let n=t>0?`ml-${t*4}`:"",r=`field_${e.name.replace(/\./g,"__")}`,o=e.name,s=e.required?" required":"",a=e.defaultValue==="__null__",i=!a&&e.defaultValue!=null?String(e.defaultValue):"",c=e.nullable&&e.type!=="checkbox"?`<span class="flex items-center gap-1 shrink-0">
99
+ <input type="hidden" id="${r}__isnull" name="${o}__isnull" value="${a?"1":""}">
100
100
  <label class="flex items-center gap-1 cursor-pointer select-none text-xs text-base-content/40 hover:text-base-content/70 border border-base-300 rounded px-2 py-1">
101
101
  <input type="checkbox" class="checkbox checkbox-xs" ${a?"checked":""}
102
102
  onchange="(function(cb){
@@ -107,7 +107,7 @@ Original error: ${t?.message??String(t)}`)}}function Ns(e,t){if(!e||!t)return f
107
107
  })(this)">
108
108
  <span>null</span>
109
109
  </label>
110
- </span>`:"",y;switch(e.type){case "checkbox":if(e.nullable){let g=a?"__null__":i==="true"?"true":i==="false"?"false":"__null__";return `
110
+ </span>`:"",y;switch(e.type){case "checkbox":if(e.nullable){let h=a?"__null__":i==="true"?"true":i==="false"?"false":"__null__";return `
111
111
  <div class="form-control mb-3 ${n}">
112
112
  <label for="${r}" class="label pb-1">
113
113
  <span class="label-text font-medium">
@@ -115,34 +115,34 @@ Original error: ${t?.message??String(t)}`)}}function Ns(e,t){if(!e||!t)return f
115
115
  <span class="text-base-content/40 text-xs ml-1">(nullable)</span>
116
116
  </span>
117
117
  </label>
118
- <select id="${r}" name="${s}" class="select select-bordered select-sm w-full">
119
- <option value="__null__"${g==="__null__"?" selected":""}>\u2014 null \u2014</option>
120
- <option value="true"${g==="true"?" selected":""}>\u2713 true</option>
121
- <option value="false"${g==="false"?" selected":""}>\u2717 false</option>
118
+ <select id="${r}" name="${o}" class="select select-bordered select-sm w-full">
119
+ <option value="__null__"${h==="__null__"?" selected":""}>\u2014 null \u2014</option>
120
+ <option value="true"${h==="true"?" selected":""}>\u2713 true</option>
121
+ <option value="false"${h==="false"?" selected":""}>\u2717 false</option>
122
122
  </select>
123
123
  </div>`}return `
124
124
  <div class="form-control ${n}">
125
125
  <label class="label cursor-pointer justify-start gap-3">
126
- <input type="checkbox" id="${r}" name="${s}" value="true"${i==="true"?" checked":""} class="checkbox checkbox-primary checkbox-sm">
126
+ <input type="checkbox" id="${r}" name="${o}" value="true"${i==="true"?" checked":""} class="checkbox checkbox-primary checkbox-sm">
127
127
  <span class="label-text font-medium">
128
128
  ${H(e.label)}${e.required?' <span class="text-error">*</span>':""}
129
129
  </span>
130
130
  </label>
131
- </div>`;case "select":y=`<select id="${r}" name="${s}"${o}${a?' disabled style="opacity:0.35"':""} class="select select-bordered select-sm w-full">
131
+ </div>`;case "select":y=`<select id="${r}" name="${o}"${s}${a?' disabled style="opacity:0.35"':""} class="select select-bordered select-sm w-full">
132
132
  ${e.required&&!e.nullable?"":'<option value="">\u2014 optional \u2014</option>'}
133
- ${(e.options??[]).map(g=>`<option value="${H(g)}"${i===g?" selected":""}>${H(g)}</option>`).join(`
133
+ ${(e.options??[]).map(h=>`<option value="${H(h)}"${i===h?" selected":""}>${H(h)}</option>`).join(`
134
134
  `)}
135
- </select>`;break;case "textarea":if(e.arrayElementType)return Fs(e,t);if(e.nested&&e.nested.length>0){let g=e.nested.map(b=>tt(b,t+1)).join(`
135
+ </select>`;break;case "textarea":if(e.arrayElementType)return Uo(e,t);if(e.nested&&e.nested.length>0){let h=e.nested.map(m=>st(m,t+1)).join(`
136
136
  `);return `
137
137
  <fieldset class="fieldset border border-base-300 rounded-box p-3 mb-3 ${n}">
138
138
  <legend class="fieldset-legend text-xs font-semibold text-base-content/60 px-1">
139
139
  ${H(e.label)}${e.required?' <span class="text-error">*</span>':""}
140
140
  </legend>
141
- ${g}
142
- </fieldset>`}y=`<textarea id="${r}" name="${s}"${o} rows="3"${a?' disabled style="opacity:0.35"':""}
141
+ ${h}
142
+ </fieldset>`}y=`<textarea id="${r}" name="${o}"${s} rows="3"${a?' disabled style="opacity:0.35"':""}
143
143
  data-json
144
144
  class="textarea textarea-bordered textarea-sm w-full font-mono text-xs"
145
- placeholder="${H(e.hint??"JSON")}">${H(i)}</textarea>`;break;default:y=`<input type="${e.type}" id="${r}" name="${s}"${o}${a?' disabled style="opacity:0.35"':""}
145
+ placeholder="${H(e.hint??"JSON")}">${H(i)}</textarea>`;break;default:y=`<input type="${e.type}" id="${r}" name="${o}"${s}${a?' disabled style="opacity:0.35"':""}
146
146
  value="${H(i)}"
147
147
  class="input input-bordered input-sm w-full"${e.hint==="email"?' autocomplete="email"':e.hint==="url"?' autocomplete="url"':""}>`;}return `
148
148
  <div class="form-control mb-3 ${n}">
@@ -154,14 +154,14 @@ Original error: ${t?.message??String(t)}`)}}function Ns(e,t){if(!e||!t)return f
154
154
  </label>
155
155
  <div class="flex items-center gap-2">
156
156
  <div class="flex-1 min-w-0">${y}</div>
157
- ${l}
157
+ ${c}
158
158
  </div>
159
- </div>`}function H(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Fs(e,t){let n=t>0?`ml-${t*4}`:"",r=`field_${e.name.replace(/\./g,"__")}`,s=e.defaultValue==="__null__",o=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 i=o?a.map(g=>tr(e,g??{})).join(`
160
- `):a.map(g=>er(e,g)).join(`
161
- `),l=o?tr(e,{}):er(e,""),y=e.nullable?`<span class="flex items-center gap-1 mt-2">
162
- <input type="hidden" id="${r}__isnull" name="${H(e.name)}__isnull" value="${s?"1":""}">
159
+ </div>`}function H(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Uo(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 i=s?a.map(h=>ar(e,h??{})).join(`
160
+ `):a.map(h=>sr(e,h)).join(`
161
+ `),c=s?ar(e,{}):sr(e,""),y=e.nullable?`<span class="flex items-center gap-1 mt-2">
162
+ <input type="hidden" id="${r}__isnull" name="${H(e.name)}__isnull" value="${o?"1":""}">
163
163
  <label class="flex items-center gap-1 cursor-pointer select-none text-xs text-base-content/40 hover:text-base-content/70 border border-base-300 rounded px-2 py-1">
164
- <input type="checkbox" class="checkbox checkbox-xs" ${s?"checked":""}
164
+ <input type="checkbox" class="checkbox checkbox-xs" ${o?"checked":""}
165
165
  onchange="(function(cb){
166
166
  var fs = cb.closest('[data-frs-array]');
167
167
  var h = document.getElementById('${r}__isnull');
@@ -177,60 +177,60 @@ Original error: ${t?.message??String(t)}`)}}function Ns(e,t){if(!e||!t)return f
177
177
  <legend class="fieldset-legend text-xs font-semibold text-base-content/60 px-1">
178
178
  ${H(e.label)}${e.required?' <span class="text-error">*</span>':""}
179
179
  </legend>
180
- <input type="hidden" id="${r}" name="${H(e.name)}" value="${H(JSON.stringify(a))}"${s?" disabled":""}>
181
- <div data-frs-array-items${s?' style="opacity:0.35"':""}>
180
+ <input type="hidden" id="${r}" name="${H(e.name)}" value="${H(JSON.stringify(a))}"${o?" disabled":""}>
181
+ <div data-frs-array-items${o?' style="opacity:0.35"':""}>
182
182
  ${i}
183
183
  </div>
184
- <template data-frs-array-tpl>${l}</template>
184
+ <template data-frs-array-tpl>${c}</template>
185
185
  <button type="button" class="btn btn-xs btn-outline mt-1" data-frs-array-add>+ Add</button>
186
186
  ${y}
187
- </fieldset>`}function er(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">
187
+ </fieldset>`}function sr(e,t){let n=t!=null?String(t):"",r;switch(e.arrayElementType){case "select":r=`<select data-frs-val class="select select-bordered select-sm flex-1">
188
188
  <option value="">\u2014</option>
189
- ${(e.arrayElementOptions??[]).map(s=>`<option value="${H(s)}"${n===s?" selected":""}>${H(s)}</option>`).join("")}
189
+ ${(e.arrayElementOptions??[]).map(o=>`<option value="${H(o)}"${n===o?" selected":""}>${H(o)}</option>`).join("")}
190
190
  </select>`;break;case "checkbox":r=`<label class="flex items-center gap-2 flex-1 cursor-pointer">
191
191
  <input type="checkbox" data-frs-val class="checkbox checkbox-sm checkbox-primary"${n==="true"?" checked":""}>
192
192
  <span class="text-sm">true</span>
193
193
  </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>
194
194
  ${r}
195
195
  <button type="button" class="btn btn-xs btn-ghost text-error" data-frs-array-rm>&times;</button>
196
- </div>`}function tr(e,t){return `<div class="border border-base-200 rounded p-3 mb-2" data-frs-array-item>
196
+ </div>`}function ar(e,t){return `<div class="border border-base-200 rounded p-3 mb-2" data-frs-array-item>
197
197
  <div class="flex justify-end mb-1">
198
198
  <button type="button" class="btn btn-xs btn-ghost text-error" data-frs-array-rm>&times;</button>
199
199
  </div>
200
- ${(e.arrayElementFields??[]).map(s=>{let o=t[s.name],a=o==null?"":typeof o=="object"?JSON.stringify(o):String(o);switch(s.type){case "checkbox":return `<div class="form-control mb-2">
200
+ ${(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">
201
201
  <label class="label cursor-pointer justify-start gap-3">
202
- <input type="checkbox" data-frs-key="${H(s.name)}" class="checkbox checkbox-sm checkbox-primary"${a==="true"?" checked":""}>
203
- <span class="label-text text-sm">${H(s.label)}</span>
202
+ <input type="checkbox" data-frs-key="${H(o.name)}" class="checkbox checkbox-sm checkbox-primary"${a==="true"?" checked":""}>
203
+ <span class="label-text text-sm">${H(o.label)}</span>
204
204
  </label>
205
205
  </div>`;case "select":return `<div class="form-control mb-2">
206
- <label class="label pb-1"><span class="label-text text-sm">${H(s.label)}</span></label>
207
- <select data-frs-key="${H(s.name)}" class="select select-bordered select-sm w-full">
208
- ${s.required?"":'<option value="">\u2014</option>'}
209
- ${(s.options??[]).map(i=>`<option value="${H(i)}"${a===i?" selected":""}>${H(i)}</option>`).join("")}
206
+ <label class="label pb-1"><span class="label-text text-sm">${H(o.label)}</span></label>
207
+ <select data-frs-key="${H(o.name)}" class="select select-bordered select-sm w-full">
208
+ ${o.required?"":'<option value="">\u2014</option>'}
209
+ ${(o.options??[]).map(i=>`<option value="${H(i)}"${a===i?" selected":""}>${H(i)}</option>`).join("")}
210
210
  </select>
211
211
  </div>`;case "number":return `<div class="form-control mb-2">
212
- <label class="label pb-1"><span class="label-text text-sm">${H(s.label)}</span></label>
213
- <input type="number" data-frs-key="${H(s.name)}" value="${H(a)}" class="input input-bordered input-sm w-full">
212
+ <label class="label pb-1"><span class="label-text text-sm">${H(o.label)}</span></label>
213
+ <input type="number" data-frs-key="${H(o.name)}" value="${H(a)}" class="input input-bordered input-sm w-full">
214
214
  </div>`;case "datetime-local":return `<div class="form-control mb-2">
215
- <label class="label pb-1"><span class="label-text text-sm">${H(s.label)}</span></label>
216
- <input type="datetime-local" data-frs-key="${H(s.name)}" value="${H(a)}" class="input input-bordered input-sm w-full">
215
+ <label class="label pb-1"><span class="label-text text-sm">${H(o.label)}</span></label>
216
+ <input type="datetime-local" data-frs-key="${H(o.name)}" value="${H(a)}" class="input input-bordered input-sm w-full">
217
217
  </div>`;case "textarea":return `<div class="form-control mb-2">
218
- <label class="label pb-1"><span class="label-text text-sm">${H(s.label)}</span></label>
219
- <textarea data-frs-key="${H(s.name)}" rows="2" class="textarea textarea-bordered textarea-sm w-full font-mono text-xs" placeholder="JSON">${H(a)}</textarea>
218
+ <label class="label pb-1"><span class="label-text text-sm">${H(o.label)}</span></label>
219
+ <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>
220
220
  </div>`;default:return `<div class="form-control mb-2">
221
- <label class="label pb-1"><span class="label-text text-sm">${H(s.label)}</span></label>
222
- <input type="text" data-frs-key="${H(s.name)}" value="${H(a)}" class="input input-bordered input-sm w-full">
221
+ <label class="label pb-1"><span class="label-text text-sm">${H(o.label)}</span></label>
222
+ <input type="text" data-frs-key="${H(o.name)}" value="${H(a)}" class="input input-bordered input-sm w-full">
223
223
  </div>`}}).join(`
224
224
  `)}
225
- </div>`}function ge(e,t,n,r="Save"){let s=e.map(o=>tt(o)).join(`
225
+ </div>`}function we(e,t,n,r="Save"){let o=e.map(s=>st(s)).join(`
226
226
  `);return `
227
227
  <form action="${H(t)}" method="${n}" novalidate data-frs-form>
228
- ${s}
228
+ ${o}
229
229
  <div class="flex gap-2 mt-4 pt-4 border-t border-base-200">
230
230
  <button type="submit" class="btn btn-primary btn-sm">${H(r)}</button>
231
231
  <button type="button" class="btn btn-ghost btn-sm" onclick="history.back()">Cancel</button>
232
232
  </div>
233
- </form>`}var zs=new Set(["<","<=",">",">=","!="]),Hs=new Set(["array-contains","array-contains-any"]);function Jt(e){return e==="desc"?"DESCENDING":"ASCENDING"}function Bs(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function qs(e,t,n,r,s){let o=[],a=new Set;for(let l of r)if(l.op==="=="||l.op==="in"||l.op==="not-in"){if(a.has(l.field))continue;a.add(l.field),o.push({fieldPath:l.field,order:"ASCENDING"});}for(let l of r)if(Hs.has(l.op)){if(a.has(l.field))continue;a.add(l.field),o.push({fieldPath:l.field,arrayConfig:"CONTAINS"});}for(let l of r)if(zs.has(l.op)){if(a.has(l.field))continue;a.add(l.field);let y=s?.field===l.field?Jt(s.dir):"ASCENDING";o.push({fieldPath:l.field,order:y});}if(s&&!a.has(s.field)&&o.push({fieldPath:s.field,order:Jt(s.dir)}),o.length===1&&n)return Us(e,t,o[0]);let i=s&&o.some(l=>l.fieldPath===s.field)?Jt(s.dir):"ASCENDING";return o.push({fieldPath:"__name__",order:i}),Zs(e,t,n,o)}function Zs(e,t,n,r,s="(default)"){let o=`projects/${e}/databases/${s}/collectionGroups/${t}/indexes/_`,a=[...en(1,o),...Tt(2,n?2:1)];for(let y of r)a.push(...nr(3,rr(y)));let i=s==="(default)"?"-default-":s,l=encodeURIComponent(sr(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${i}/indexes?create_composite=${l}`}function Ls(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 Xt(e,t){return e<<3|t}function en(e,t){let n=Array.from(new TextEncoder().encode(t));return [Xt(e,2),...Yt(n.length),...n]}function Tt(e,t){return [Xt(e,0),...Yt(t)]}function nr(e,t){return [Xt(e,2),...Yt(t.length),...t]}function rr(e){let t=[...en(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...Tt(3,1)):t.push(...Tt(2,e.order==="DESCENDING"?2:1)),t}function sr(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 Us(e,t,n,r="(default)"){let s=`projects/${e}/databases/${r}/collectionGroups/${t}/fields/${n.fieldPath}`,o=[...en(1,s),...Tt(2,2),...nr(3,rr(n))],a=r==="(default)"?"-default-":r,i=encodeURIComponent(sr(o));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${i}`}function Ks(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 s of n)if(typeof s=="string"&&s.length>0)return s;return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.FIREBASE_PROJECT_ID||void 0}function ke(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function nt(e,t){let n=e??{},r=ke(e),s;if(r&&(s=n.message?Ls(n.message):void 0,!s)){let o=Ks(t.ref);if(o){let a=Bs(t.path);s=qs(o,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:s}}At();var ar=`// \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
233
+ </form>`}var Ko=new Set(["<","<=",">",">=","!="]),Wo=new Set(["array-contains","array-contains-any"]);function nn(e){return e==="desc"?"DESCENDING":"ASCENDING"}function Go(e){return me(e).collectionId||e}function Vo(e,t,n,r,o){let s=[],a=new Set;for(let c of r)if(c.op==="=="||c.op==="in"||c.op==="not-in"){if(a.has(c.field))continue;a.add(c.field),s.push({fieldPath:c.field,order:"ASCENDING"});}for(let c of r)if(Wo.has(c.op)){if(a.has(c.field))continue;a.add(c.field),s.push({fieldPath:c.field,arrayConfig:"CONTAINS"});}for(let c of r)if(Ko.has(c.op)){if(a.has(c.field))continue;a.add(c.field);let y=o?.field===c.field?nn(o.dir):"ASCENDING";s.push({fieldPath:c.field,order:y});}if(o&&!a.has(o.field)&&s.push({fieldPath:o.field,order:nn(o.dir)}),s.length===1&&n)return Yo(e,t,s[0]);let i=o&&s.some(c=>c.fieldPath===o.field)?nn(o.dir):"ASCENDING";return s.push({fieldPath:"__name__",order:i}),Qo(e,t,n,s)}function Qo(e,t,n,r,o="(default)"){let s=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,a=[...sn(1,s),...Et(2,n?2:1)];for(let y of r)a.push(...ir(3,cr(y)));let i=o==="(default)"?"-default-":o,c=encodeURIComponent(lr(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${i}/indexes?create_composite=${c}`}function Jo(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function rn(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function on(e,t){return e<<3|t}function sn(e,t){let n=Array.from(new TextEncoder().encode(t));return [on(e,2),...rn(n.length),...n]}function Et(e,t){return [on(e,0),...rn(t)]}function ir(e,t){return [on(e,2),...rn(t.length),...t]}function cr(e){let t=[...sn(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...Et(3,1)):t.push(...Et(2,e.order==="DESCENDING"?2:1)),t}function lr(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 Yo(e,t,n,r="(default)"){let o=`projects/${e}/databases/${r}/collectionGroups/${t}/fields/${n.fieldPath}`,s=[...sn(1,o),...Et(2,2),...ir(3,cr(n))],a=r==="(default)"?"-default-":r,i=encodeURIComponent(lr(s));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${i}`}function Xo(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 Ae(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function at(e,t){let n=e??{},r=Ae(e),o;if(r&&(o=n.message?Jo(n.message):void 0,!o)){let s=Xo(t.ref);if(s){let a=Go(t.path);o=Vo(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}}Pt();var ur=`// \u2500\u2500 Shared helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
234
234
  function frsGetBasePath() {
235
235
  var root = document.querySelector("[data-frs-panel-root]");
236
236
  var bp = root && root.getAttribute("data-frs-base-path");
@@ -1152,7 +1152,7 @@ function initColumnReorder(table) {
1152
1152
  });
1153
1153
  });
1154
1154
  }
1155
- `;function rt(){return jsx("script",{dangerouslySetInnerHTML:{__html:ar}})}on();function be(e){return "<!DOCTYPE html>"+renderToString(e)}var no=["corporate","silk","dark"],ro=()=>jsxs("div",{class:"dropdown dropdown-end","data-frs-theme-switcher":true,children:[jsxs("button",{type:"button",tabIndex:0,class:"btn btn-sm btn-ghost text-neutral-content gap-1.5","aria-label":"Switch theme",children:[jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",class:"size-4",children:[jsx("circle",{cx:"12",cy:"12",r:"4"}),jsx("path",{d:"M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"})]}),jsx("span",{class:"text-xs hidden sm:inline","data-frs-theme-current":true,children:"Theme"})]}),jsx("ul",{tabIndex:0,class:"dropdown-content menu menu-sm bg-base-100 text-base-content rounded-box z-50 mt-2 w-40 p-1 shadow-lg border border-base-300",children:no.map(e=>jsx("li",{children:jsxs("button",{type:"button","data-frs-theme":e,class:"capitalize justify-between",children:[jsx("span",{children:e}),jsx("span",{class:"hidden text-primary","data-frs-theme-check":e,children:"\u2713"})]})},e))})]}),we=({opts:e,children:t})=>{let{title:n,breadcrumb:r,flash:s,basePath:o="/"}=e;return jsxs("html",{lang:"en","data-theme":"corporate",children:[jsxs("head",{children:[jsx("meta",{charset:"UTF-8"}),jsx("meta",{name:"viewport",content:"width=device-width, initial-scale=1"}),jsxs("title",{children:[n," \u2014 FRS Admin"]}),jsx("script",{dangerouslySetInnerHTML:{__html:"(function(){try{var t=localStorage.getItem('frs-admin-theme');if(t){document.documentElement.setAttribute('data-theme',t);}}catch(_){}})();"}}),jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/themes.css",rel:"stylesheet",type:"text/css"}),jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/daisyui.css",rel:"stylesheet",type:"text/css"}),jsx("script",{src:"https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"})]}),jsxs("body",{class:"bg-base-200/50 min-h-screen flex flex-col",children:[jsxs("div",{class:"navbar bg-neutral text-neutral-content shadow-sm sticky top-0 z-50 px-6",children:[jsx("div",{class:"flex-1",children:jsx("a",{href:o,class:"font-bold text-lg tracking-tight hover:opacity-80 transition-opacity",children:"FRS Admin"})}),jsx("div",{class:"flex-none",children:jsx(ro,{})})]}),jsxs("main",{class:"px-6 py-8 w-full flex-1",children:[r&&r.length>0&&jsx("div",{class:"text-sm breadcrumbs mb-4",children:jsx("ul",{children:r.map((a,i)=>a.href?jsx("li",{children:jsx("a",{href:a.href,children:a.label})},i):jsx("li",{class:"text-base-content/60",children:a.label},i))})}),jsx("h1",{class:"text-2xl font-bold mb-6",children:n}),s&&jsxs("div",{role:"alert",class:`alert ${s.type==="success"?"alert-success":s.type==="warning"?"alert-warning":"alert-error"} mb-6`,children:[jsx("span",{class:"flex-1",children:s.message}),s.action&&jsx("a",{href:s.action.href,...s.action.external?{target:"_blank",rel:"noopener noreferrer"}:{},class:"btn btn-sm btn-outline",children:s.action.label})]}),t]}),jsx(sn,{basePath:o}),jsx(rt,{})]})]})};function an(e,t){return be(jsx(we,{opts:t,children:jsx("div",{dangerouslySetInnerHTML:{__html:e}})}))}function cn(e,t){return be(jsx(we,{opts:{title:"Repositories",basePath:t},children:e.length===0?jsxs("div",{class:"text-center py-20 text-base-content/50",children:[jsx("p",{class:"text-lg font-medium mb-1",children:"No repositories configured"}),jsx("p",{class:"text-sm",children:"Add a repository to your FRS config to get started."})]}):jsx("div",{class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:e.map(n=>jsx("a",{href:`${t}/${n.name}`,class:"card bg-base-100 border border-base-300 hover:shadow-md no-underline transition-shadow",children:jsxs("div",{class:"card-body p-5",children:[jsx("h2",{class:"card-title text-sm font-semibold",children:n.name}),jsx("p",{class:"text-xs text-base-content/50 font-mono",children:n.path})]})},n.name))})}))}var dr=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],so=[{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"}],oo=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function ao(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return so;case "ZodBoolean":return dr;case "ZodArray":return oo;default:return dr}}var xe="__null__";function io(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="${xe}"]');if(!o){o=document.createElement('option');o.value='${xe}';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='${xe}';i.readOnly=true;}i.style.opacity='0.55';}else{i.style.opacity='';if(i.tagName==='SELECT'){var o2=i.querySelector('option[value="${xe}"][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!=='${xe}')?i.dataset._prev:'';}}})(this)`}function co(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 it({inputId:e,active:t}){return jsxs("label",{class:"flex items-center gap-1 cursor-pointer select-none text-xs text-base-content/60 hover:text-base-content border border-base-300 rounded-md px-1.5 py-1 shrink-0 leading-none h-8",title:"Filter where field IS NULL",children:[jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",checked:t,onchange:io(e)}),jsx("span",{children:"\u2205"})]})}function lo({col:e,active:t}){let n=t?.value??"",r=n===xe,s=`fv_input_${e.name.replace(/\./g,"__")}`,o=t?.op,a=o==="in"||o==="not-in";if(e.enumValues&&e.enumValues.length>0){if(a){let i=new Set(n.split(",").map(y=>y.trim()).filter(Boolean)),l=`eg_${e.name.replace(/\./g,"__")}`;return jsxs("div",{class:"flex flex-wrap items-center gap-1 w-full",children:[jsx("input",{type:"hidden",id:s,name:`fv_${e.name}`,value:n}),e.enumValues.map(y=>jsxs("label",{class:"flex items-center gap-1 text-xs border border-base-300 rounded px-2 cursor-pointer hover:bg-base-200",children:[jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",value:y,checked:i.has(y),"data-enum-group":l,onchange:co(s,l)}),jsx("span",{children:y})]},y))]})}return jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxs("select",{id:s,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),e.enumValues.map(i=>jsx("option",{value:i,selected:n===i,children:i},i)),e.nullable&&jsx("option",{value:xe,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx(it,{inputId:s,active:r})]})}if(e.zodType==="ZodBoolean")return jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxs("select",{id:s,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),jsx("option",{value:"true",selected:n==="true",children:"true"}),jsx("option",{value:"false",selected:n==="false",children:"false"}),e.nullable&&jsx("option",{value:xe,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx(it,{inputId:s,active:r})]});if(e.zodType==="ZodArray"){let i=t?.op==="array-contains-any";return jsx("input",{id:s,type:"text",name:`fv_${e.name}`,value:n,placeholder:i?"val1, val2, \u2026":"value",class:"input input-sm input-bordered w-full"})}return e.zodType==="ZodNumber"||e.zodType==="ZodBigInt"?jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsx("input",{id:s,type:r?"text":"number",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0,"data-_type":r?"number":void 0}),e.nullable&&jsx(it,{inputId:s,active:r})]}):e.zodType==="ZodDate"?jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsx("input",{id:s,type:r?"text":"datetime-local",name:`fv_${e.name}`,value:n,class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0,"data-_type":r?"datetime-local":void 0}),e.nullable&&jsx(it,{inputId:s,active:r})]}):jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsx("input",{id:s,type:"text",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0}),e.nullable&&jsx(it,{inputId:s,active:r})]})}function ln({action:e,columnMeta:t,activeFilters:n,isGroup:r}){let s=Object.fromEntries(n.map(l=>[l.field,l])),o=n.length>0,a=n.length>=2||r&&o,i=t.filter(l=>l.zodType!=="ZodObject"&&l.zodType!=="ZodRecord");return jsxs("details",{class:"collapse collapse-arrow bg-base-100 border border-base-300 rounded-box mb-6 shadow-sm",open:o?true:void 0,children:[jsxs("summary",{class:"collapse-title text-sm font-medium py-2 min-h-0",children:["Filters",o&&jsxs("span",{class:"badge badge-primary badge-sm ml-2",children:[n.length," active"]})]}),jsx("div",{class:"collapse-content pb-4 pt-2",children:jsxs("form",{method:"get",action:e,children:[jsx("div",{class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:i.map(l=>{let y=ao(l.zodType),g=s[l.name],b=g?.op??y[0].value;return jsxs("div",{class:"flex flex-col gap-1.5",children:[jsx("label",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:l.name}),jsxs("div",{class:"flex gap-1.5",children:[y.length>1?jsx("select",{name:`fo_${l.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:y.map(v=>jsx("option",{value:v.value,selected:v.value===b,children:v.label},v.value))}):jsx("input",{type:"hidden",name:`fo_${l.name}`,value:y[0].value}),jsx(lo,{col:l,active:g})]})]},l.name)})}),jsxs("div",{class:"flex flex-wrap gap-2 mt-4 pt-3 border-t border-base-200 items-center",children:[jsx("button",{type:"submit",class:"btn btn-sm btn-primary",children:"Apply"}),o&&jsx("a",{href:e,class:"btn btn-sm btn-ghost",children:"Clear"}),a&&jsxs("span",{class:"text-xs text-warning ml-auto flex items-center gap-1",children:[jsx("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-4 w-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),r?"Collection group queries require a composite index":"Multiple filters may require a composite index"]})]})]})})]})}function dn(e,t,n,r,s,o){let a=n==="create"?`Create ${e}`:`Edit ${e} / ${r??""}`,i=n==="create"?[{label:"Repositories",href:s},{label:e,href:`${s}/${e}`},{label:"New document"}]:[{label:"Repositories",href:s},{label:e,href:`${s}/${e}`},{label:`Edit ${r??""}`}];return be(jsx(we,{opts:{title:a,breadcrumb:i,basePath:s,flash:o},children:jsx("div",{class:"card bg-base-100 border border-base-300",children:jsx("div",{class:"card-body p-6",children:jsx("div",{dangerouslySetInnerHTML:{__html:t}})})})}))}At();rn();function un(e,t,n){let r=new URLSearchParams;for(let s of e)r.set(`fv_${s.field}`,s.value),r.set(`fo_${s.field}`,s.op);return t&&(r.set("ob",t.field),r.set("od",t.dir)),n&&r.set("ps",String(n)),r}function ur(e,t,n,r,s){let o=un(e,r,s);return o.set("cursor",t),o.set("dir",n),`?${o.toString()}`}function uo(e,t,n,r){let s=un(n,void 0,r);return t?.field===e?t.dir==="asc"&&(s.set("ob",e),s.set("od","desc")):(s.set("ob",e),s.set("od","asc")),`?${s.toString()}`}function po(e,t,n){return `?${un(t,n,e).toString()}`}function pn(e,t,n,r,s,o,a=[],i=[],l=false,y=[],g,b,v,C,R,T,P,N=false){let S=`${r}/${e}`,d=`${S}/create`,p={};if(P)for(let w of n)p[w]=st(ot(P,w));let u=(T??[]).filter(w=>true),c=u.length>0,f=l,m=f||c,x=u.map(w=>{let O=ot(P,w),$=st(O),I=a.find(_=>_.name===w);return {name:w,type:$,enumValues:I?.enumValues??null,nullable:I?.nullable??false}}),h=[];return P&&(h=ie(P).filter(O=>u.includes(O.name))),be(jsxs(we,{opts:{title:e,breadcrumb:[{label:"Repositories",href:r},{label:e}],basePath:r,flash:o},children:[a.length>0&&jsx(ln,{action:S,columnMeta:a,activeFilters:i,isGroup:C}),v&&jsxs("div",{role:"alert",class:`alert ${v.type==="index"?"alert-warning":"alert-error"} mb-6 shadow-sm`,children:[jsx("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6 shrink-0 stroke-current",fill:"none",viewBox:"0 0 24 24",children:v.type==="index"?jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"}):jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"})}),jsxs("div",{class:"flex-1",children:[jsx("h3",{class:"font-bold",children:v.type==="index"?"Composite index required":"Query failed"}),jsx("div",{class:"text-sm",children:v.message})]}),v.indexUrl&&jsx("a",{href:v.indexUrl,target:"_blank",rel:"noopener noreferrer",class:"btn btn-sm btn-outline",children:"Create Index \u2192"})]}),jsxs("div",{class:"flex flex-wrap justify-between items-center mb-4 gap-3","data-frs-toolbar":true,children:[jsxs("div",{class:"flex items-center gap-3",children:[jsxs("span",{class:"text-sm text-base-content/60",children:[t.length,typeof R=="number"&&jsxs(Fragment,{children:[" ","of"," ",jsx("span",{class:"font-semibold text-base-content/80",children:R})]})," ","document",(typeof R=="number"?R:t.length)!==1&&"s"]}),jsxs("div",{class:"flex items-center gap-1.5 text-sm text-base-content/60",children:[jsx("span",{children:"Rows"}),jsx("div",{class:"join",children:[10,25,50,100].map(w=>jsx("a",{href:po(w,i,g),class:`join-item btn btn-xs ${b===w?"btn-active btn-primary":"btn-outline"}`,children:w},w))})]})]}),jsxs("div",{class:"flex gap-2",children:[jsx("form",{method:"post",action:`${S}/_bulk/backfill`,onsubmit:"return confirm('Backfill entire repository? This will scan all documents and fill missing system keys.')",children:jsx("button",{type:"submit",class:"btn btn-outline btn-sm",children:"Backfill"})}),jsx("a",{href:d,class:"btn btn-primary btn-sm",children:"+ New"})]})]}),m&&jsxs("div",{class:"hidden mb-3 alert alert-info py-2 px-3","data-frs-bulk-bar":true,"data-frs-repo":e,"data-frs-total":typeof R=="number"?String(R):"","data-frs-page-size":String(b??t.length),"data-frs-allow-delete":f?"1":"0","data-frs-allow-update":c?"1":"0","data-frs-fields":JSON.stringify(x),"data-frs-filters":JSON.stringify(i),children:[jsxs("div",{class:"flex-1 text-sm",children:[jsx("span",{"data-frs-bulk-summary":true,children:"0 selected"}),typeof R=="number"&&R>t.length&&jsxs("button",{type:"button",class:"ml-3 link text-sm hidden","data-frs-bulk-select-all":true,children:["Select all ",R," matching documents"]}),jsxs("span",{class:"hidden ml-3 italic","data-frs-bulk-all-active":true,children:["All ",R??"?"," matching documents are selected."," ",jsx("button",{type:"button",class:"link","data-frs-bulk-clear":true,children:"Clear selection"})]})]}),jsxs("div",{class:"flex gap-2",children:[c&&jsx("button",{type:"button",class:"btn btn-sm btn-outline","data-frs-bulk-action":"update",children:"Update field\u2026"}),f&&jsx("button",{type:"button",class:"btn btn-sm btn-error btn-outline","data-frs-bulk-action":"delete",children:"Delete"})]})]}),jsx("div",{class:"overflow-x-auto rounded-box border border-base-300 bg-base-100","data-frs-table-wrap":true,children:jsxs("table",{class:"table table-sm w-full","data-frs-table":true,"data-frs-repo":e,"data-frs-colcount":n.length,children:[jsx("thead",{children:jsxs("tr",{class:"bg-base-200/50",children:[m&&jsx("th",{class:"w-8",children:jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-page":true,"aria-label":"Select all on this page"})}),[...n].map((w,O)=>{let $=g?.field===w,I=$?g.dir==="asc"?" \u25B2":" \u25BC":"";return jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:jsxs("a",{href:uo(w,g,i,b),class:`hover:text-base-content inline-flex items-center gap-0.5${$?" text-primary font-bold":""}`,children:[w,I]})},O)}),y.map((w,O)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:w.column},`rel-${O}`)),jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide text-right",children:"Actions"})]})}),jsx("tbody",{children:t.length===0?jsx("tr",{children:jsx("td",{colspan:n.length+y.length+1+(m?1:0),class:"text-center py-16 text-base-content/40",children:"No documents found"})}):t.map((w,O)=>{let $=String(w.docId??w.id??""),I=`${r}/${e}/${encodeURIComponent($)}/edit`,_=`${r}/${e}/${encodeURIComponent($)}/delete`;return jsxs("tr",{class:"hover","data-frs-row-id":$,children:[m&&jsx("td",{class:"align-middle py-2",children:jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-row":true,value:$,"aria-label":`Select ${$}`})}),n.map((k,D)=>{let j=w[k],A=p[k],E=A?at(A,j):null;return jsx("td",{class:"align-top py-2",children:jsx(Fe,{val:j,mismatch:E})},D)}),y.map((k,D)=>{let j=w[k.key];if(j==null||j==="")return jsx("td",{class:"py-2"},`rel-${D}`);let A=k.type==="one"?`${r}/${k.targetRepo}/${encodeURIComponent(String(j))}/edit`:`${r}/${k.targetRepo}?fv_${k.targetKey}=${encodeURIComponent(String(j))}`;return jsx("td",{class:"align-middle py-2",children:jsx("a",{href:A,class:"btn btn-xs btn-ghost btn-outline","data-frs-relation":true,"data-frs-rel-type":k.type,"data-frs-rel-repo":k.targetRepo,"data-frs-rel-fk":k.targetKey,"data-frs-rel-val":String(j),"data-frs-rel-label":k.column,children:k.column})},`rel-${D}`)}),jsx("td",{class:"align-middle text-right whitespace-nowrap py-2",children:jsxs("div",{class:"flex gap-1 justify-end",children:[jsx("a",{href:I,class:"btn btn-xs btn-outline",children:"Edit"}),N&&jsx("a",{href:`${r}/${e}/${encodeURIComponent($)}/history`,class:"btn btn-xs btn-outline",title:"View change history",children:"History"}),l&&jsx("form",{method:"post",action:_,onsubmit:"return confirm('Delete this document?')",children:jsx("button",{type:"submit",class:"btn btn-xs btn-error btn-outline",children:"Delete"})})]})})]},O)})})]})}),(s.hasPrev||s.hasNext)&&jsxs("div",{class:"flex flex-col items-center mt-6 gap-2",children:[jsxs("div",{class:"flex justify-center items-center gap-2",children:[s.hasPrev?jsx("a",{href:ur(i,s.prevCursor,"prev",g,b),class:"btn btn-sm btn-outline",children:"\u2190 Previous"}):jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"\u2190 Previous"}),s.hasNext?jsx("a",{href:ur(i,s.nextCursor,"next",g,b),class:"btn btn-sm btn-outline",children:"Next \u2192"}):jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"Next \u2192"})]}),typeof R=="number"&&jsxs("div",{class:"text-xs text-base-content/50",children:[R," total document",R!==1?"s":"",i.length>0?" matching filters":""]})]}),m&&c&&jsxs("dialog",{id:"frs-bulk-update-modal",class:"modal",children:[jsxs("div",{class:"modal-box",children:[jsx("h3",{class:"font-bold text-lg mb-3",children:"Bulk update field"}),jsx("p",{class:"text-sm text-base-content/60 mb-4","data-frs-bulk-update-summary":true,children:"Update one field on the selected documents."}),jsxs("form",{method:"dialog","data-frs-bulk-update-form":true,"data-frs-form":true,children:[jsxs("label",{class:"form-control w-full mb-3",children:[jsx("div",{class:"label",children:jsx("span",{class:"label-text text-xs uppercase tracking-wide",children:"Field"})}),jsxs("select",{class:"select select-bordered select-sm w-full",name:"field",required:true,"data-frs-bulk-field-select":true,children:[jsx("option",{value:"",children:"\u2014 Select a field \u2014"}),u.map(w=>jsx("option",{value:w,children:w},w))]})]}),jsx("div",{class:"mb-4","data-frs-bulk-value-container":true}),jsxs("div",{class:"modal-action",children:[jsx("button",{type:"button",class:"btn btn-sm btn-ghost","data-frs-bulk-update-cancel":true,children:"Cancel"}),jsx("button",{type:"submit",class:"btn btn-sm btn-primary","data-frs-bulk-update-submit":true,children:"Apply"})]})]})]}),jsx("form",{method:"dialog",class:"modal-backdrop",children:jsx("button",{children:"close"})})]}),jsx("div",{class:"hidden","data-frs-bulk-templates":true,children:h.map(w=>jsx("div",{"data-frs-bulk-template-for":w.name,dangerouslySetInnerHTML:{__html:tt(w)}},w.name))})]}))}var yo="";function ct(e,t){return an(e,t)}function fn(e,t){return cn(e,t)}function yn(e,t,n,r,s,o,a,i,l,y,g,b,v,C,R,T,P,N){return pn(e,t,n,r,s,o,a,i,l,y,g,b,v,C,R,T,P,N)}function ve(e,t,n,r,s,o){return dn(e,t,n,r,s,o)}var mn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function go(){let e="";for(;e.length<20;){let t=randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let r=t[n];r>=mn.length*4||(e+=mn.charAt(r%mn.length));}}return e}async function pr(e,t){if(t)try{let n=e.repo.ref,r=n?.firestore;if(t.startsWith("{"))try{let s=JSON.parse(t);if(s.docPath&&r&&typeof r.doc=="function"){let o=await r.doc(s.docPath).get();if(o.exists)return o}s.docId&&(t=s.docId);}catch{}if(t.includes("/")&&r&&typeof r.doc=="function"){let s=await r.doc(t).get();if(s.exists)return s}if(typeof n.doc=="function"){let s=await n.doc(t).get();if(s.exists)return s}}catch{}}function Ot(e,t){if(!t)return;let n=e[t];if(typeof n!="string"||!n)return;let r=n.split("/").filter(Boolean),s=[];for(let o=1;o<r.length;o+=2)s.push(r[o]);return s.length>0?s:void 0}async function ze(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 o=await e.repo.get[r](t);if(o)return o}catch{}return (await e.repo.query.by({where:[[n,"==",t]],limit:1}))[0]??null}function hn(e,t,n){let r=e.documentKey??"docId",s=nt(n,{ref:e.repo.ref,path:e.path,isGroup:!!e.isGroup,filters:[{field:r,op:"==",value:t}]});return s.type==="index"?{type:"warning",message:"Loading this document requires a composite index that does not exist yet.",...s.indexUrl?{action:{href:s.indexUrl,label:"Create Index \u2192",external:true}}:{}}:{type:"error",message:s.message}}function B(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[s,o]of Object.entries(n)){let a=bn(o),i=K(a),l=i==="ZodObject",y=a,g=false;if(i==="ZodUnion"){let C=Xe(a);C.some(T=>K(T)==="ZodDate")&&(g=true);let R=C.find(T=>{if(K(T)==="ZodObject"){let P=re(T);return "latitude"in P&&"longitude"in P}return false});R&&(l=true,y=R);}if(e[s+"__isnull"]==="1"){r[s]=null;continue}if(l){let C={},R=false;for(let[N,S]of Object.entries(e))N.startsWith(`${s}.`)&&(C[N.slice(s.length+1)]=S,R=true);if(R){r[s]=Pt(C,y);continue}let T=e[s],P=Array.isArray(T)?T[T.length-1]:T;if(P)try{r[s]=JSON.parse(P);}catch{r[s]=P;}continue}let b=e[s],v=Array.isArray(b)?b[b.length-1]:b;if(v===void 0||v===""){i==="ZodBoolean"&&(r[s]=false);continue}if(g){r[s]=new Date(v);continue}switch(i){case "ZodBoolean":v==="__null__"?r[s]=null:r[s]=v==="true"||v==="on"||v==="1";break;case "ZodNumber":case "ZodBigInt":r[s]=Number(v);break;case "ZodDate":r[s]=new Date(v);break;case "ZodArray":try{r[s]=JSON.parse(v);}catch{r[s]=v;}break;default:if(v.startsWith("{")||v.startsWith("["))try{r[s]=JSON.parse(v);break}catch{}r[s]=v;}}return r}function fr(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 mr(e){let t=e;for(;;){let n=K(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=ne(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=Qe(t);if(!r)return n;t=r;}else return n}}function bn(e){let t=e;for(;;){let n=K(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=ne(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=Qe(t);if(!r)return t;t=r;}else return t}}function hr(e){let t=e;for(;;){let n=K(t);if(n==="ZodOptional"||n==="ZodNullable")return true;if(n==="ZodDefault"){t=ne(t);continue}return false}}function gr(e){let t=bn(e),n=K(t);if(n==="ZodEnum"){let r=Ge(t);return r.length>0?r:void 0}if(n==="ZodNativeEnum"){let r=Je(t),s=Object.values(r).filter(o=>typeof o=="string");return s.length>0?s:void 0}if(n==="ZodLiteral"){let r=Ye(t);return typeof r=="string"?[r]:void 0}}function br(e,t,n=""){let r={};for(let s of Object.keys(t.shape)){let o=n?`${n}.${s}`:s,a=e[s];if(a===null){r[o]="__null__";continue}if(a===void 0)continue;let i=bn(t.shape[s]),l=K(i),y=l==="ZodObject",g=i,b=false;if(l==="ZodUnion"){let v=Xe(i);v.some(R=>K(R)==="ZodDate")&&(b=true);let C=v.find(R=>{if(K(R)==="ZodObject"){let T=re(R);return "latitude"in T&&"longitude"in T}return false});C&&(y=true,g=C);}if(y&&typeof a=="object"&&a!==null&&!Array.isArray(a)&&!("_seconds"in a)&&typeof a.toDate!="function"){let v=br(a,g,o);Object.assign(r,v);}else if(l==="ZodDate"||b){let v=fr(a);v!==null&&(r[o]=v);}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)&&("_seconds"in a||typeof a.toDate=="function")){let v=fr(a);r[o]=v??JSON.stringify(a,null,2);}else typeof a=="object"?r[o]=JSON.stringify(a,null,2):r[o]=String(a);}return r}function gn(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?gn(n.nested,t):void 0}))}function bo(e,t){let n=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),r=[];for(let[s,o]of Object.entries(e)){if(!s.startsWith("fv_"))continue;let a=s.slice(3);if(!t.has(a))continue;let i=(o??"").trim();if(!i)continue;let l=e[`fo_${a}`]??"==",y=n.has(l)?l:"==";r.push({field:a,op:y,value:i});}return r}function yr(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 s=r.value.split(",").map(o=>o.trim()).filter(o=>o!==""&&o!==t).map(o=>n(o));return [r.field,r.op,s]}return [r.field,r.op,n(r.value)]})}function wr(e,t,n=""){let r=[];for(let s of e){let o=n?`${n}.${s}`:s,a=t.shape[s];if(!a){r.push({name:o,zodType:"ZodString"});continue}let i=mr(a);if(i==="ZodObject"){let l=a;for(;;){let g=K(l);if(g==="ZodOptional"||g==="ZodNullable"||g==="ZodDefault")l=ne(l);else break}let y=re(l);r.push(...wr(Object.keys(y),l,o));}else r.push({name:o,zodType:i,nullable:hr(a),enumValues:gr(a)});}return r}function wo(e,t){let n=t.split("."),r=e;for(let s of n){for(;;){let a=K(r);if(a==="ZodOptional"||a==="ZodNullable"||a==="ZodDefault")r=ne(r);else break}let o=re(r);if(!(s in o))return null;r=o[s];}return r}function Ae(e,t){if(!t||t.length===0)return e;let n=[],r=new Map;for(let o of t){let a=o.indexOf(".");if(a===-1)n.push(o);else {let i=o.slice(0,a),l=o.slice(a+1);r.has(i)||r.set(i,[]),r.get(i).push(l);}}let s={};for(let o of n)o in e.shape&&(s[o]=e.shape[o]);for(let[o,a]of r){if(!(o in e.shape))continue;let i=e.shape[o];for(;;){let l=K(i);if(l==="ZodOptional"||l==="ZodNullable"||l==="ZodDefault")i=ne(i);else break}if(K(i)!=="ZodObject"){s[o]=e.shape[o];continue}s[o]=Ae(i,a);}return z$1.object(s)}function ue(e,t,n){return de(e,t,n)}function xr(e,t,n){let r=(d,p)=>{let u=ue(d,t,n),c=Object.values(e).map(f=>({name:f.name,path:f.path}));B(p,fn(c,u));},s=async(d,p)=>{let u=d.params.repoName;if(!u){B(p,"Bad request",400);return}let c=e[u];if(!c){B(p,"Repository not found",404);return}let f=c.pageSize??25,m=d.query??{},x=m.cursor,h=m.dir==="prev"?"prev":"next",w=m.ob??"",O=m.od==="desc"?"desc":"asc",$=w?{field:w,dir:O}:void 0,I=parseInt(m.ps??""),_=Number.isFinite(I)&&I>0?Math.min(I,200):f,k=c.listColumns??Object.keys(c.schema.shape),D=c.documentKey??"docId",j=[D,...k.filter(ae=>ae!==D)];$&&(new Set([D,...k]).has($.field)||($=void 0));let A=c.filterableFields?(()=>{let ae=[];for(let fe of c.filterableFields)(fe.includes(".")||k.includes(fe))&&ae.push(fe);return ae})():k,E=(()=>{let ae=[];for(let fe of A)if(fe.includes(".")){let De=wo(c.schema,fe);ae.push({name:fe,zodType:De?mr(De):"ZodString",nullable:De?hr(De):false,enumValues:De?gr(De):void 0});}else ae.push(...wr([fe],c.schema));return ae})(),M=new Set(E.map(ae=>ae.name)),Z=bo(m,M),U=yr(Z),Ie;x&&(Ie=await pr(c,x));let[J,G]=await Promise.all([c.repo.query.paginate({pageSize:_,cursor:Ie,direction:h,...U.length>0?{where:U}:{},...$?{orderBy:[{field:$.field,direction:$.dir}]}:{}}).catch(ae=>({queryError:nt(ae,{ref:c.repo.ref,path:c.path,isGroup:!!c.isGroup,filters:Z,sort:$})})),c.repo.aggregate.count(U.length>0?{where:U}:{}).catch(()=>{})]),te="queryError"in J,Qr=te?[]:J.data,Gr=te?"":J.nextCursor?.ref?.path??J.nextCursor?.id??"",Jr=te?"":J.prevCursor?.ref?.path??J.prevCursor?.id??"",Yr=te?J.queryError:void 0,Xr=ue(d,t,n),Ze,mt=m.flash;mt==="created"?Ze={type:"success",message:"Document created successfully."}:mt==="updated"?Ze={type:"success",message:"Document updated successfully."}:mt==="deleted"?Ze={type:"success",message:"Document deleted successfully."}:mt==="backfilled"&&(Ze={type:"success",message:"Repository backfilled successfully."}),B(p,yn(c.name,Qr,j,Xr,{hasPrev:te?false:J.hasPrevPage,hasNext:te?false:J.hasNextPage,prevCursor:Jr,nextCursor:Gr},Ze,E,Z,c.allowDelete??false,c.relationalMeta,$,_,Yr,c.isGroup,G,c.mutableFields,c.schema,c.historyEnabled));},o=(d,p)=>{let u=d.params.repoName;if(!u){B(p,"Bad request",400);return}let c=e[u];if(!c){B(p,"Repository not found",404);return}let f=ue(d,t,n),m=Ae(c.schema,c.createFields),x=ie(m),h=`${f}/${c.name}/create`,w=ge(x,h,"POST","Create document");B(p,ve(c.name,w,"create",null,f));},a=async(d,p)=>{let u=d.params.repoName;if(!u){B(p,"Bad request",400);return}let c=e[u];if(!c){B(p,"Repository not found",404);return}let f=ue(d,t,n),m=d.body??{},x=Pt(m,c.schema),h=Ae(c.schema,c.createFields),w=h.safeParse(x);if(!w.success){let O=ie(h),$=`${f}/${c.name}/create`,I=ge(O,$,"POST","Create document"),_=w.error.issues.map(k=>`${k.path.join(".")}: ${k.message}`).join(", ");B(p,ve(c.name,I,"create",null,f,{type:"error",message:`Validation error: ${_}`}),422);return}try{if(c.isGroup&&c.parentKeys&&c.parentKeys.length>0){let O={...w.data};c.createdKey&&(O[c.createdKey]=new Date);let $=c.parentKeys.filter(D=>!O[D]);if($.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${$.join(", ")}`);let I=c.parentKeys.map(D=>O[D]),_=c.documentKey??"docId",k=O[_]||go();await c.repo.set(...I,k,O);}else await c.repo.create(w.data);Et(p,`${f}/${c.name}?flash=created`);}catch(O){let $=Ae(c.schema,c.createFields),I=ie($),_=`${f}/${c.name}/create`,k=ge(I,_,"POST","Create document");B(p,ve(c.name,k,"create",null,f,{type:"error",message:`Save error: ${O.message}`}),500);}},i=async(d,p)=>{let u=d.params.repoName,c=d.params.id;if(!u||!c){B(p,"Bad request",400);return}let f=e[u];if(!f){B(p,"Repository not found",404);return}let m=ue(d,t,n),x=null;try{x=await ze(f,c);}catch(_){let k=hn(f,c,_),D=ke(_)?424:500;B(p,ct("",{title:`Edit ${f.name} / ${c}`,basePath:m,breadcrumb:[{label:"Repositories",href:m},{label:f.name,href:`${m}/${f.name}`},{label:`Edit ${c}`}],flash:k}),D);return}if(!x){B(p,"Document not found",404);return}let h=br(x,f.schema),w=Ae(f.schema,f.mutableFields),O=gn(ie(w),h),$=`${m}/${f.name}/${encodeURIComponent(c)}/edit`,I=ge(O,$,"POST","Save changes");B(p,ve(f.name,I,"edit",c,m));},l=async(d,p)=>{let u=d.params.repoName,c=d.params.id;if(!u||!c){B(p,"Bad request",400);return}let f=e[u];if(!f){B(p,"Repository not found",404);return}let m=ue(d,t,n),x=d.body??{},h=Pt(x,f.schema),w=Ae(f.schema,f.mutableFields),$=w.partial().safeParse(h);if(!$.success){let I=Object.fromEntries(Object.entries(x).map(([A,E])=>[A,Array.isArray(E)?E.join(","):E??""])),_=gn(ie(w),I),k=`${m}/${f.name}/${encodeURIComponent(c)}/edit`,D=ge(_,k,"POST","Save changes"),j=$.error.issues.map(A=>`${A.path.join(".")}: ${A.message}`).join(", ");B(p,ve(f.name,D,"edit",c,m,{type:"error",message:`Validation error: ${j}`}),422);return}try{let I=await ze(f,c),_=(I&&Ot(I,f.pathKey))??[c];await f.repo.update(..._,$.data),Et(p,`${m}/${f.name}?flash=updated`);}catch(I){let _=Ae(f.schema,f.mutableFields),k=ie(_),D=`${m}/${f.name}/${encodeURIComponent(c)}/edit`,j=ge(k,D,"POST","Save changes"),A=ke(I)?hn(f,c,I):{type:"error",message:`Save error: ${I.message}`},E=ke(I)?424:500;B(p,ve(f.name,j,"edit",c,m,A),E);}},y=async(d,p)=>{let u=d.params.repoName,c=d.params.id;if(!u||!c){B(p,"Bad request",400);return}let f=e[u];if(!f){B(p,"Repository not found",404);return}if(!f.allowDelete){B(p,"Delete is not allowed for this repository",403);return}let m=ue(d,t,n);try{let x=await ze(f,c),h=(x&&Ot(x,f.pathKey))??[c];await f.repo.delete(...h),Et(p,`${m}/${f.name}?flash=deleted`);}catch(x){let h=ke(x)?hn(f,c,x):{type:"error",message:`Delete error: ${x.message}`},w=ke(x)?424:500;B(p,ct("",{title:`Delete ${f.name} / ${c}`,basePath:m,breadcrumb:[{label:"Repositories",href:m},{label:f.name,href:`${m}/${f.name}`},{label:`Delete ${c}`}],flash:h}),w);}},g=async(d,p)=>{let u=d.params.repoName;if(!u){B(p,"Bad request",400);return}let c=e[u];if(!c){B(p,"Repository not found",404);return}let f=ue(d,t,n),m=d.query,x=m?.type==="many"?"many":"one",h=Math.max(1,Math.min(100,Number(m?.ps??25)||25)),w=c.listColumns??Object.keys(re(c.schema)),{PanelOne:O,PanelMany:$}=await Promise.resolve().then(()=>(on(),cr)),{renderToString:I}=await import('hono/jsx/dom/server');if(x==="one"){let E=String(m?.id??"");if(!E){B(p,"<div class='p-6 text-error'>Missing id parameter.</div>",400);return}try{let M=await ze(c,E),Z=I(O({doc:M,repoName:c.name,basePath:f,schema:c.schema,columns:w}));B(p,Z);}catch(M){B(p,`<div class='p-6 text-error text-sm'>Error: ${M.message}</div>`,500);}return}let _=String(m?.fk??""),k=String(m?.fv??"");if(!_||!k){B(p,"<div class='p-6 text-error'>Missing fk/fv parameters.</div>",400);return}let D=m?.cursor??"",j=m?.dir==="prev"?"prev":"next",A;D&&(A=await pr(c,D));try{let E=await c.repo.query.paginate({pageSize:h,cursor:A,direction:j,where:[[_,"==",xo(k)]]}),M=I($({docs:E.data,repoName:c.name,basePath:f,fk:_,fv:k,columns:w,schema:c.schema,pagination:{hasPrev:E.hasPrevPage,hasNext:E.hasNextPage,prevCursor:E.prevCursor?.ref?.path??E.prevCursor?.id??"",nextCursor:E.nextCursor?.ref?.path??E.nextCursor?.id??"",pageSize:h}}));B(p,M);}catch(E){B(p,`<div class='p-6 text-error text-sm'>Error: ${E.message}</div>`,500);}},b=async(d,p)=>{let u=d.params.repoName;if(!u){B(p,"Bad request",400);return}let c=e[u];if(!c){B(p,"Repository not found",404);return}let f=ue(d,t,n);try{await c.repo.system.backfillKeys(),Et(p,`${f}/${c.name}?flash=backfilled`);}catch(m){B(p,`<div class="p-6 text-error">Backfill failed: ${m.message}</div>`,500);}},v=async(d,p)=>{let u=[];for(let c of p){let f;if(d.isGroup||d.parentKeys?.length){let m=await ze(d,c);f=m?Ot(m,d.pathKey):void 0;}f||(f=[c]);try{let m=d.repo.documentRef(...f);m&&u.push(m);}catch{}}return u},C=async(d,p)=>{let u=yr(p),c=d.documentKey??"docId",f=[],m;for(;;){let x=await d.repo.query.paginate({pageSize:500,cursor:m,direction:"next",...u.length>0?{where:u}:{}});for(let h of x.data){let w=String(h[c]??h.id??"");w&&f.push(w);}if(!x.hasNextPage||!x.nextCursor)break;m=x.nextCursor;}return f},R=async(d,p)=>{let u=d.params.repoName;if(!u){oe(p,{error:"Bad request"},400);return}let c=e[u];if(!c){oe(p,{error:"Repository not found"},404);return}if(!c.allowDelete){oe(p,{error:"Delete is not allowed for this repository"},403);return}let f=d.body??{};try{let m=await P(c,f);if(m.length===0){oe(p,{deleted:0});return}let x=await v(c,m);for(let h=0;h<x.length;h+=500)await c.repo.bulk.delete(x.slice(h,h+500));oe(p,{deleted:x.length});}catch(m){oe(p,{error:m.message},500);}},T=async(d,p)=>{let u=d.params.repoName;if(!u){oe(p,{error:"Bad request"},400);return}let c=e[u];if(!c){oe(p,{error:"Repository not found"},404);return}let f=d.body??{},m=String(f.field??"");if(!m){oe(p,{error:"Missing 'field'"},400);return}if(!c.mutableFields||!c.mutableFields.includes(m)){oe(p,{error:`Field '${m}' is not bulk-updatable`},403);return}let x=c.schema.shape?.[m],h;if(x){let w=typeof c.schema=="object"&&c.schema&&"constructor"in c.schema&&c.schema.constructor.name.includes("Zod")?c.schema.pick({[m]:true}):void 0;if(!w){oe(p,{error:"Invalid schema structure"},500);return}h=Pt(f.formPayload??{},w)[m];let $=x.safeParse(h);if(!$.success){oe(p,{error:`Invalid value for '${m}': ${$.error.message}`},400);return}h=$.data;}try{let w=await P(c,f);if(w.length===0){oe(p,{updated:0});return}let $=(await v(c,w)).map(I=>({docRef:I,data:{[m]:h}}));for(let I=0;I<$.length;I+=500)await c.repo.bulk.update($.slice(I,I+500));oe(p,{updated:$.length});}catch(w){oe(p,{error:w.message},500);}};async function P(d,p){if(p.selectAll){let u=N(p.filters,d);return await C(d,u)}return Array.isArray(p.ids)?p.ids.filter(u=>typeof u=="string"&&!!u):[]}function N(d,p){if(!Array.isArray(d))return [];let u=new Set((p.filterableFields??Object.keys(re(p.schema))).map(m=>String(m))),c=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),f=[];for(let m of d)m&&typeof m=="object"&&typeof m.field=="string"&&u.has(m.field)&&typeof m.value=="string"&&c.has(String(m.op))&&f.push({field:m.field,op:m.op,value:m.value});return f}return {handleDashboard:r,handleList:s,handleCreateForm:o,handleCreateSubmit:a,handleEditForm:i,handleEditSubmit:l,handleDelete:y,handlePanel:g,handleBulkDelete:R,handleBulkUpdate:T,handleBulkBackfill:b,handleHistory:async(d,p)=>{let u=d.params.repoName,c=d.params.id;if(!u||!c){B(p,"Bad request",400);return}let f=e[u];if(!f){B(p,"Repository not found",404);return}if(!f.historyEnabled||!f.repo.history){B(p,"History not enabled for this repository",404);return}let m=ue(d,t,n),x=f.historySubcollection??"history",h=[c];try{let E=await ze(f,c),M=E?Ot(E,f.pathKey):void 0;M&&M.length>0&&(h=M);}catch{}let w=parseInt(String(d.query?.limit??"")),O=Number.isFinite(w)&&w>0?Math.min(w,500):100,$=[],I;try{$=await f.repo.history.list(...h,{limit:O});}catch(E){I=E.message;}let _=E=>String(E??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),k=E=>{if(E===void 0)return '<span class="opacity-40">undefined</span>';if(E===null)return '<span class="opacity-40">null</span>';if(typeof E=="object")try{return `<code class="text-xs">${_(JSON.stringify(E))}</code>`}catch{return _(String(E))}return _(String(E))},D=E=>E?typeof E.toDate=="function"?E.toDate().toISOString():E instanceof Date?E.toISOString():_(String(E)):"",j=E=>`<span class="badge badge-sm ${E==="create"?"badge-success":E==="delete"?"badge-error":"badge-info"}">${_(E)}</span>`,A="";if(A+='<div class="flex items-center justify-between mb-4">',A+=`<a href="${m}/${f.name}/${encodeURIComponent(c)}/edit" class="btn btn-sm btn-outline">\u2190 Back to edit</a>`,A+=`<a href="${m}/${f.name}" class="btn btn-sm btn-outline">\u2190 Back to list</a>`,A+="</div>",A+=`<p class="text-sm text-base-content/60 mb-4">Subcollection: <code>${_(x)}</code> \xB7 Showing up to ${O} entries.</p>`,I)A+=`<div class="alert alert-error mb-4">${_(I)}</div>`;else if($.length===0)A+='<div class="alert">No history entries found.</div>';else {A+='<div class="overflow-x-auto"><table class="table table-zebra table-sm">',A+="<thead><tr><th>When</th><th>Op</th><th>User</th><th>Reason / Comment</th><th>Changes</th></tr></thead><tbody>";for(let E of $){let M=E.meta??{},Z=[M.reason,M.comment].filter(J=>J!=null&&J!=="").map(J=>_(String(J))).join(" \u2014 "),U="",Ie=Object.keys(E.changes??{});Ie.length===0?U='<span class="opacity-40">\u2014</span>':U='<ul class="space-y-1">'+Ie.map(J=>{let G=E.changes[J];return `<li><strong>${_(J)}</strong>: ${k(G.oldValue)} \u2192 ${k(G.newValue)}</li>`}).join("")+"</ul>",A+="<tr>",A+=`<td class="whitespace-nowrap text-xs font-mono">${_(D(E.historySetAt))}</td>`,A+=`<td>${j(E.operation??"update")}</td>`,A+=`<td class="text-xs">${_(M.userEmail??M.userId??"")}</td>`,A+=`<td class="text-xs">${Z}</td>`,A+=`<td>${U}</td>`,A+="</tr>";}A+="</tbody></table></div>";}B(p,ct(A,{title:`History \u2014 ${f.name} / ${c}`,basePath:m,breadcrumb:[{label:"Repositories",href:m},{label:f.name,href:`${m}/${f.name}`},{label:`History ${c}`}]}));}}}function oe(e,t,n=200){e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(t));}function xo(e){return e==="true"?true:e==="false"?false:e!==""&&!isNaN(Number(e))?Number(e):e}It();async function vo(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function So(e){let t={};if(!e)return t;for(let n of e.split("&")){let r=n.indexOf("=");if(r===-1)continue;let s=decodeURIComponent(n.slice(0,r).replace(/\+/g," ")),o=decodeURIComponent(n.slice(r+1).replace(/\+/g," ")),a=t[s];a===void 0?t[s]=o:Array.isArray(a)?a.push(o):t[s]=[a,o];}return t}function kr(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:s,auth:o,middleware:a=[],httpsOptions:i}=e,l=t==="/"?"":t.replace(/\/$/,""),y={};for(let[C,R]of Object.entries(n)){if(!R.repo)throw new Error(`[createAdminServer] Repository "${C}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let T=R.schema??R.repo.schema??null;if(!T)throw new Error(`[createAdminServer] Repository "${C}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let P,N,S;if(R.fieldsConfig){let u=R.fieldsConfig;P=[],N=[],S=[];for(let[c,f]of Object.entries(u))for(let m of f)m==="filterable"?P.push(c):m==="mutable"?N.push(c):m==="create"&&S.push(c);P.length===0&&(P=void 0),N.length===0&&(N=void 0),S.length===0&&(S=void 0);}let d=(()=>{let u=R.repo._parentKeys;return u&&u.length>0?u:void 0})();if(d&&S)for(let u of d)S.includes(u)||S.push(u);let p={name:C,path:R.path,repo:R.repo,schema:T,documentKey:R.documentKey??"docId",pathKey:R.repo._pathKey??void 0,isGroup:!!R.repo._isGroup,parentKeys:d,createdKey:R.repo._createdKey??void 0,listColumns:R.listColumns,pageSize:R.pageSize,filterableFields:P,mutableFields:N,createFields:S,allowDelete:R.allowDelete??false,historyEnabled:!!R.repo._historyConfig?.enabled,historySubcollection:(R.repo._historyConfig?.enabled&&R.repo._historySubcollection)??void 0,relationalMeta:(()=>{if(!R.relationalFields||R.relationalFields.length===0)return;let u=R.repo.relationalKeys??{},c=[];for(let f of R.relationalFields){let m=u[f.key];m&&c.push({key:m.sourceKey?String(m.sourceKey):f.key,column:f.column,targetRepo:String(m.repo),targetKey:String(m.key),type:m.type});}return c.length>0?c:void 0})()};y[C]=p;}let g=xr(y,l,gt(i?.region)),b=new ye;if(s!==false&&b.use($t(s===void 0?{}:s)),r&&b.use(async(C,R,T)=>{let P=C,N=String(P.headers?.["content-type"]??"");if(N.includes("application/x-www-form-urlencoded")){let S=await vo(P);C.body=So(S);}else if(N.includes("application/json")&&typeof P.body=="string")try{C.body=JSON.parse(P.body);}catch{}await T();}),o)if(We(o)){for(let C of o.routes){let R=`${l}${C.path}`;C.method==="GET"?b.get(R,C.handler):b.post(R,C.handler);}b.use(o.middleware);}else if(typeof o=="function")b.use(o);else {let C=o.realm??"Admin",R="Basic "+Buffer.from(`${o.username}:${o.password}`).toString("base64");b.use((T,P,N)=>{if((T.headers?.authorization??"")!==R){P.status(401).set("WWW-Authenticate",`Basic realm="${C}"`).set("Content-Type","text/plain").send("Unauthorized");return}N();});}for(let C of a)b.use(C);b.get(`${l}/`,g.handleDashboard),b.get(`${l}`,g.handleDashboard),b.get(`${l}/:repoName/_panel`,g.handlePanel),b.post(`${l}/:repoName/_bulk/delete`,g.handleBulkDelete),b.post(`${l}/:repoName/_bulk/update`,g.handleBulkUpdate),b.post(`${l}/:repoName/_bulk/backfill`,g.handleBulkBackfill),b.get(`${l}/:repoName`,g.handleList),b.get(`${l}/:repoName/create`,g.handleCreateForm),b.post(`${l}/:repoName/create`,g.handleCreateSubmit),b.get(`${l}/:repoName/:id/edit`,g.handleEditForm),b.post(`${l}/:repoName/:id/edit`,g.handleEditSubmit),b.get(`${l}/:repoName/:id/history`,g.handleHistory),b.post(`${l}/:repoName/:id/delete`,g.handleDelete);let v=async(C,R)=>{await b.handle(C,R);};return i&&(v.httpsOptions=i),v}je();function lt(e,t){let n=e||{},r={},s={...n};for(let[o,a]of Object.entries(t||{})){let i=n[o];Ke(i,a)||(r[o]=a,s[o]=a);}return {before:n,after:s,changes:r}}function Tr(e){return e}async function xn(e,t,n){let r=e.changes||{};for(let s of Object.keys(r)){let o=t[s];if(o&&o.length>0){for(let a of o)if(await a.rule({diff:e,key:s,user:n,authenticatedUser:n})===false)return {allowed:false,reason:a.description}}}return {allowed:true}}function Ar(e){return async t=>xn(t.diff,e,t.user)}function kn(e,t,n=200){let r=Re(t);return e.json(r,n)}function Ce(e,t,n,r=200){return kn(e,{success:true,data:t,meta:n},r)}function z(e,t,n=400){return kn(e,{success:false,error:t},n)}async function vn(e,t,n,r,s,o){let a=nt(t,n),i=a.type==="index",l=i?424:500,g={success:false,error:i?a.message:s&&t instanceof Error?t.message:r};if(i&&(g.errorType="index",a.indexUrl&&(g.indexUrl=a.indexUrl,o)))try{let b=o({indexUrl:a.indexUrl,repoName:n.repoName??"",path:n.path,isGroup:n.isGroup,filters:n.filters,sort:n.sort,error:t,c:e});b instanceof Promise&&await b;}catch(b){s&&console.error("[crudServer] Error in indexesError callback:",b);}return kn(e,g,l)}var Sn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Cr(){let e="";for(;e.length<20;){let t=randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let r=t[n];r>=Sn.length*4||(e+=Sn.charAt(r%Sn.length));}}return e}function Oe(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return z$1.preprocess(r=>_n(r)??r,e);if(n==="ZodObject"||n==="object"){let r=e.shape,s={};for(let[o,a]of Object.entries(r))s[o]=Oe(a);return z$1.object(s)}if(n==="ZodArray"||n==="array"){let r=t.element??t.type;if(r)return z$1.array(Oe(r))}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(r)return Oe(r).optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(r)return Oe(r).nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType,s=t.defaultValue;if(r){let o=Oe(r);return typeof s=="function"?o.default(s()):o.default(s)}}return e}function ko(e,t,n=[]){let r=e.shape,s={},o=t&&t.length>0?t:Object.keys(r);for(let a of o){if(n.includes(a))continue;let i=a.split(".")[0];i&&r[i]&&(s[i]=r[i]);}return z$1.object(s)}function Rn(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 Pr(e,t){let n=t.split("."),r=Rn(e);for(let s=0;s<n.length;s++){let o=n[s];if(!o)continue;let a=r?.shape;if(!a||!a[o])return;let i=a[o];if(s===n.length-1)return i;r=Rn(i);}return r}function Ee(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type;if(n==="ZodObject"||n==="object"){let r=e.shape,s={};for(let[o,a]of Object.entries(r))s[o]=Ee(a);return z$1.object(s).partial()}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(!r)return e;let s=Ee(r);return s===r?e:s.optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(!r)return e;let s=Ee(r);return s===r?e:s.nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType;return r?Ee(r).optional():e}if(n==="ZodUnion"||n==="union"){let r=t.options;if(!r||r.length<2)return e;let s=r.map(a=>Ee(a));return s.some((a,i)=>a!==r[i])?z$1.union(s):e}return e}function Dt(e,t,n,r=false,s=[]){if(typeof t!="object"||t===null||Array.isArray(t))return {success:false,error:"Data payload must be an object"};try{let o=t,a={},i={};for(let[l,y]of Object.entries(o))if(l.includes(".")){let g=l.split(".")[0];if(s.includes(l)||s.includes(g))continue;if(n&&n.length>0&&!n.includes(l)&&!n.includes(g))return {success:!1,error:`Field '${l}' is not allowed for this operation`};let b=Pr(e,l);if(!b)return {success:!1,error:`Field '${l}' does not exist in schema`};let v=r?Ee(b):b,R=(Wt()==="normalize"?Oe(v):v).parse(y);a[l]=R;}else i[l]=y;if(Object.keys(i).length>0||Object.keys(a).length===0){let l=ko(e,n,s),y=r?Ee(l):l,b=(Wt()==="normalize"?Oe(y):y).parse(i);Object.assign(a,b);}return {success:!0,data:a}}catch(o){return o instanceof z$1.ZodError?{success:false,error:`Validation failed: ${o.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}var $r={eq:"==","==":"==",ne:"!=","!=":"!=",lt:"<","<":"<",lte:"<=","<=":"<=",gt:">",">":">",gte:">=",">=":">=",in:"in",nin:"not-in","not-in":"not-in",not_in:"not-in",contains:"array-contains","array-contains":"array-contains",array_contains:"array-contains",arrayContains:"array-contains",containsAny:"array-contains-any","array-contains-any":"array-contains-any",array_contains_any:"array-contains-any",arrayContainsAny:"array-contains-any"};function dt(e){return $r[e]??e}function To(e){return e in $r}function _t(e,t,n,r){let s=Pr(e,t);if(!s||typeof s.safeParse!="function")return {success:true,data:n};let o=r?dt(r):void 0,a=Rn(s),i=wt(a);if(o==="array-contains"){let g=i??s;if(typeof g.safeParse=="function"){let b=g.safeParse(n);return b.success?{success:true,data:b.data}:{success:false,error:b.error.issues.map(C=>C.message).join(", ")}}return {success:true,data:n}}if(o==="array-contains-any"){if(!Array.isArray(n))return {success:false,error:"Expected array value for array-contains-any"};let g=i??s,b=[];for(let v of n)if(typeof g.safeParse=="function"){let C=g.safeParse(v);if(C.success)b.push(C.data);else return {success:false,error:C.error.issues.map(T=>T.message).join(", ")}}else b.push(v);return {success:true,data:b}}let l=s.safeParse(n);if(l.success)return {success:true,data:l.data};if(Array.isArray(n)){let g=i??s,b=[];for(let v of n)if(typeof g.safeParse=="function"){let C=g.safeParse(v);if(C.success)b.push(C.data);else return {success:false,error:C.error.issues.map(T=>T.message).join(", ")}}else b.push(v);return {success:true,data:b}}return {success:false,error:l.error.issues.map(g=>g.message).join(", ")}}function Ao(e,t){let n=[],r=t?new Set(t):null;for(let[s,o]of Object.entries(e)){if(o===void 0||["cursor","direction","limit","pageSize","orderBy","orderDir","select","includes","withTotal"].includes(s))continue;let a=Array.isArray(o)?o[0]:o;if(a===void 0||a==="")continue;let i=s.lastIndexOf("__"),l,y="==";if(i!==-1){let b=s.slice(0,i),v=s.slice(i+2);To(v)?(l=b,y=dt(v)):(l=s,y="==");}else l=s;if(r&&!r.has(l))continue;let g=a;y==="in"||y==="not-in"||y==="array-contains-any"?g=a.split(",").map(b=>Or(b.trim())):g=Or(a),n.push({field:l,op:y,value:g});}return n}function Or(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 jt(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function Er(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,s=typeof n.docId=="string"?n.docId:void 0;try{let o=e.repo.ref,a=o?.firestore;if(r&&a&&typeof a.doc=="function"){let i=await a.doc(r).get();if(i.exists)return i}if(s&&s.includes("/")&&a&&typeof a.doc=="function"){let i=await a.doc(s).get();if(i.exists)return i}if(s&&typeof o.doc=="function"){let i=await o.doc(s).get();if(i.exists)return i}return}catch{return}}function Ir(e,t,n,r){async function s(S,d,p,u){if(!d.rules)return {allowed:true};let c=d.rules?.[p];if(!c)return {allowed:false,errorResponse:z(S,`Operation "${p}" is not allowed for this repository`,403)};try{let f=await c(u);return f===!1?{allowed:!1,errorResponse:z(S,"Forbidden",403)}:typeof f=="string"?{allowed:!1,errorResponse:z(S,f,403)}:typeof f=="object"&&f!==null&&!f.allowed?{allowed:!1,errorResponse:z(S,f.reason||"Forbidden",403)}:{allowed:!0}}catch(f){let m=n&&f instanceof Error?f.message:"Forbidden";return {allowed:false,errorResponse:z(S,m,403)}}}async function o(S,d,p,u){if(!S.rules)return u;let c=S.rules?.filter;if(!c)return u;let f=[];for(let m of u)try{await c({user:d,doc:m,params:p})&&f.push(m);}catch{}return f}function a(S){return S.get("user")??S.get("docsUser")??null}function i(S,d){if(!S){let p=d.req.path.split("/");for(let u of p)if(e[u]){S=u;break}}return !S||!e[S]?null:e[S]??null}function l(S,d){if(!d)return;let p=S[d];if(typeof p!="string"||!p)return;let u=p.split("/").filter(Boolean),c=[];for(let f=1;f<u.length;f+=2)c.push(u[f]);return c.length>0?c:void 0}async function y(S,d){let p=`by${S.documentKey.charAt(0).toUpperCase()}${S.documentKey.slice(1)}`,u=S.repo.get[p];if(typeof u=="function")try{let f=await u(d);if(f)return f}catch{}return (await S.repo.query.by({where:[[S.documentKey,"==",d]],limit:1}))[0]??null}async function g(S){let d=S.c,p=d.req.param(),u=i(p.repoName,d);if(!u)return z(d,"Repository not found",404);let c=a(d),f=await s(d,u,"list",{user:c,query:d.req.query(),params:p});if(!f.allowed)return f.errorResponse;let m=[],x;try{let h=d.req.query(),w=Math.min(Number(h.pageSize)||u.pageSize,100),O=h.cursor,$=h.direction?.toLowerCase()==="prev"?"prev":"next",I=h.orderBy,_=h.orderDir?.toLowerCase()==="desc"?"desc":"asc",k=h.select,D=k?k.split(",").map(G=>G.trim()):void 0,j=h.withTotal,A=j==="true"||j==="1"||j===!0,E;u.allowedIncludes&&h.includes&&(E=(typeof h.includes=="string"?h.includes.split(",").map(te=>te.trim()):Array.isArray(h.includes)?h.includes:[]).filter(te=>typeof te=="string"&&u.allowedIncludes.includes(te)),E?.length===0&&(E=void 0));let M=Ao(h,u.filterableFields);m=M.map(G=>({field:G.field,op:G.op,value:String(G.value??"")})),I&&(x={field:I,dir:_});let Z={pageSize:w,direction:$,...A?{withTotal:!0}:{}};if(O)try{let G=typeof O=="string"?JSON.parse(O):O;Z.cursor=await Er(u,G);}catch{}if(I){if(u.orderableFields&&!u.orderableFields.includes(I))return z(d,`Field not orderable: ${I}`,400);Z.orderBy=[{field:I,direction:_}];}if(M.length>0){Z.where=[];for(let G of M){let te=_t(u.schema,G.field,G.value,G.op);if(!te.success)return z(d,`Invalid filter value for '${G.field}': ${te.error}`,400);Z.where.push([G.field,G.op,te.data]);}}D&&(Z.select=D),E&&(Z.include=E);let U=await u.repo.query.paginate(Z),J={items:await o(u,a(d),p,U.data),hasNextPage:U.hasNextPage,hasPrevPage:U.hasPrevPage,nextCursor:jt(U.nextCursor),prevCursor:jt(U.prevCursor),...U.totalCount!==void 0?{totalCount:U.totalCount,totalCountIsExact:U.totalCountIsExact}:{}};return Ce(d,J,{pageSize:w,hasMore:U.hasNextPage,...U.totalCount!==void 0?{totalCount:U.totalCount,totalCountIsExact:U.totalCountIsExact}:{}})}catch(h){return await vn(d,h,{repoName:p.repoName||u.name,ref:u.repo.ref,path:u.path,isGroup:!!u.isGroup,filters:m,sort:x},"Failed to fetch documents",n,r)}}async function b(S){let d=S.c,p=d.req.param(),u=i(p.repoName,d);if(!u)return z(d,"Repository not found",404);let c=a(d),f=await s(d,u,"list",{user:c,query:S.input||{},params:p});if(!f.allowed)return f.errorResponse;let m=[],x;try{let h=S.input||{},w=Math.min(h.pageSize||u.pageSize,100),O=h.direction==="prev"?"prev":"next";h.where&&(m=h.where.map(j=>({field:String(j[0]),op:j[1],value:String(j[2]??"")}))),h.orderBy&&h.orderBy[0]&&(x={field:h.orderBy[0].field,dir:h.orderBy[0].direction==="desc"?"desc":"asc"});let $=h.withTotal===!0||String(h.withTotal)==="true",I={pageSize:w,direction:O,...$?{withTotal:!0}:{}};if(h.cursor)try{let j=typeof h.cursor=="string"?JSON.parse(h.cursor):h.cursor;I.cursor=await Er(u,j);}catch{}if(u.allowedIncludes&&h.includes&&h.includes.length>0){let j=h.includes.filter(A=>typeof A=="string"?u.allowedIncludes.includes(A):typeof A=="object"&&A!==null&&"relation"in A&&typeof A.relation=="string"?u.allowedIncludes.includes(A.relation):!1);j.length>0&&(I.include=j);}if(h.where&&h.where.length>0){if(u.filterableFields){let A=new Set(u.filterableFields),E=h.where.filter(M=>!A.has(M[0]));if(E.length>0){z(d,`Fields not filterable: ${E.map(M=>M[0]).join(", ")}`,400);return}}let j=[];for(let A of h.where){let E=dt(A[1]),M=_t(u.schema,A[0],A[2],E);if(!M.success){z(d,`Invalid filter value for '${A[0]}': ${M.error}`,400);return}j.push([A[0],E,M.data]);}I.where=j;}if(h.orWhere&&h.orWhere.length>0){if(u.filterableFields){let A=new Set(u.filterableFields),E=h.orWhere.filter(M=>!A.has(M[0]));if(E.length>0){z(d,`Fields not filterable: ${E.map(M=>M[0]).join(", ")}`,400);return}}let j=[];for(let A of h.orWhere){let E=dt(A[1]),M=_t(u.schema,A[0],A[2],E);if(!M.success){z(d,`Invalid filter value for '${A[0]}': ${M.error}`,400);return}j.push([A[0],E,M.data]);}I.orWhere=j;}if(h.orWhereGroups&&h.orWhereGroups.length>0){if(u.filterableFields){let A=new Set(u.filterableFields);for(let E of h.orWhereGroups){let M=E.filter(Z=>!A.has(Z[0]));if(M.length>0){z(d,`Fields not filterable: ${M.map(Z=>Z[0]).join(", ")}`,400);return}}}let j=[];for(let A of h.orWhereGroups){let E=[];for(let M of A){let Z=dt(M[1]),U=_t(u.schema,M[0],M[2],Z);if(!U.success){z(d,`Invalid filter value for '${M[0]}': ${U.error}`,400);return}E.push([M[0],Z,U.data]);}j.push(E);}I.orWhereGroups=j;}if(h.orderBy&&h.orderBy.length>0){if(u.orderableFields){let j=new Set(u.orderableFields),A=h.orderBy.filter(E=>!j.has(E.field));if(A.length>0){z(d,`Fields not orderable: ${A.map(E=>E.field).join(", ")}`,400);return}}I.orderBy=h.orderBy;}h.select&&h.select.length>0&&(I.select=h.select);let _=await u.repo.query.paginate(I),D={items:await o(u,a(d),p,_.data),hasNextPage:_.hasNextPage,hasPrevPage:_.hasPrevPage,nextCursor:jt(_.nextCursor),prevCursor:jt(_.prevCursor),..._.totalCount!==void 0?{totalCount:_.totalCount,totalCountIsExact:_.totalCountIsExact}:{}};return Ce(d,D,{pageSize:w,hasMore:_.hasNextPage,..._.totalCount!==void 0?{totalCount:_.totalCount,totalCountIsExact:_.totalCountIsExact}:{}})}catch(h){return await vn(d,h,{repoName:p.repoName||u.name,ref:u.repo.ref,path:u.path,isGroup:!!u.isGroup,filters:m,sort:x},"Failed to query documents",n,r)}}async function v(S){let d=S.c,p=d.req.param(),u=i(p.repoName,d);if(!u)return z(d,"Repository not found",404);let c=p.id;if(!c)return z(d,"Document ID required",400);try{let f=await y(u,c);if(!f)return z(d,"Document not found",404);let m=a(d),x=await s(d,u,"get",{user:m,doc:f,params:p});if(!x.allowed)return x.errorResponse;if(u.rules?.filter)try{if(!await u.rules.filter({user:m,doc:f,params:p}))return z(d,"Document not found",404)}catch{return z(d,"Document not found",404)}return Ce(d,f)}catch(f){return await vn(d,f,{repoName:p.repoName||u.name,ref:u.repo.ref,path:u.path,isGroup:!!u.isGroup,filters:[{field:u.documentKey,op:"==",value:c}]},"Failed to fetch document",n,r)}}async function C(S){let d=S.c,p=d.req.param(),u=i(p.repoName,d);if(!u)return z(d,"Repository not found",404);try{let c=S.input||{},f=a(d),m=await s(d,u,"create",{user:f,body:c,params:p});if(!m.allowed)return m.errorResponse;let x=Dt(u.schema,c,u.createFields,!1,u.systemKeys);if(!x.success)return z(d,x.error,400);if(u.validate){let w=await u.validate(x.data,"create");if(w)return z(d,w,400)}let h;if(u.isGroup&&u.parentKeys&&u.parentKeys.length>0){let w={...x.data};u.createdKey&&(w[u.createdKey]=new Date);let O=u.parentKeys.filter(_=>!w[_]);if(O.length>0){z(d,`Missing parent key(s) for subcollection create: ${O.join(", ")}`,400);return}let $=u.parentKeys.map(_=>w[_]),I=w[u.documentKey]||Cr();h=await u.repo.set(...$,I,w);}else h=await u.repo.create(x.data);return Ce(d,h,void 0,201)}catch(c){let f=n&&c instanceof Error?c.message:"Failed to create document";return z(d,f,500)}}async function R(S,d){let p=S.c,u=p.req.param(),c=i(u.repoName,p);if(!c)return z(p,"Repository not found",404);let f=u.id;if(!f)return z(p,"Document ID required",400);try{let m=S.input||{},x=await y(c,f);if(!x)return z(p,"Document not found",404);let h=Dt(c.schema,m,c.mutableFields,d,c.systemKeys);if(!h.success)return z(p,h.error,400);if(c.validate){let k=await c.validate(h.data,"update");if(k)return z(p,k,400)}let w=lt(x,h.data),O=a(p),$=await s(p,c,"update",{user:O,doc:x,body:h.data,diff:w,params:u});if(!$.allowed)return $.errorResponse;let I=l(x,c.pathKey)??[f],_=await c.repo.update(...I,h.data);return Ce(p,_)}catch(m){let x=n&&m instanceof Error?m.message:"Failed to update document";return z(p,x,500)}}async function T(S){let d=S.c,p=d.req.param(),u=i(p.repoName,d);if(!u)return z(d,"Repository not found",404);if(!u.allowDelete)return z(d,"Delete not allowed for this repository",403);let c=p.id;if(!c)return z(d,"Document ID required",400);try{let f=await y(u,c);if(!f)return z(d,"Document not found",404);let m=a(d),x=await s(d,u,"delete",{user:m,doc:f,params:p});if(!x.allowed)return x.errorResponse;let h=l(f,u.pathKey)??[c];return await u.repo.delete(...h),Ce(d,{deleted:!0})}catch(f){let m=n&&f instanceof Error?f.message:"Failed to delete document";return z(d,m,500)}}function P(S){return S.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 N(S){let d=S.c,p=d.req.param(),u=i(p.repoName,d);if(!u)return z(d,"Repository not found",404);try{let c=S.input||{};if(!Array.isArray(c.operations))return z(d,"operations array is required",400);let f=a(d),m=u.repo.batch.create(),x=[];for(let h of c.operations){if(!h.type||!["create","update","delete"].includes(h.type))return z(d,"Invalid operation type",400);if(h.type==="create"){let w=await s(d,u,"create",{user:f,body:h.data,params:p});if(!w.allowed)return w.errorResponse;let O=Dt(u.schema,h.data,u.createFields,!1,u.systemKeys);if(!O.success)return z(d,O.error,400);let $=h.data[u.documentKey]||Cr(),I={...O.data};if(u.createdKey&&(I[u.createdKey]=new Date),u.isGroup&&u.parentKeys){let _=u.parentKeys.map(k=>I[k]);m.set(..._,$,I);}else m.set($,I);x.push({op:"create",id:$});}else if(h.type==="update"){if(!h.id)return z(d,"id required for update",400);let w=await y(u,h.id);if(!w)return z(d,`Document ${h.id} not found`,404);let O=Dt(u.schema,h.data,u.mutableFields,!0,u.systemKeys);if(!O.success)return z(d,O.error,400);if(u.validate){let k=await u.validate(O.data,"update");if(k)return z(d,k,400)}let $=lt(w,O.data),I=await s(d,u,"update",{user:f,doc:w,body:O.data,diff:$,params:p});if(!I.allowed)return I.errorResponse;let _=l(w,u.pathKey)??[h.id];m.update(..._,O.data),x.push({op:"update",id:h.id});}else if(h.type==="delete"){if(!u.allowDelete)return z(d,"Delete not allowed",403);if(!h.id)return z(d,"id required for delete",400);let w=await y(u,h.id);if(!w)return z(d,`Document ${h.id} not found`,404);let O=await s(d,u,"delete",{user:f,doc:w,params:p});if(!O.allowed)return O.errorResponse;let $=l(w,u.pathKey)??[h.id];m.delete(...$),x.push({op:"delete",id:h.id});}}return await m.commit(),Ce(d,{results:x})}catch(c){let f=n&&c instanceof Error?c.message:"Batch operation failed";return z(d,f,500)}}return {handleList:g,handleQuery:b,handleGet:v,handleCreate:C,handleUpdate:R,handleDelete:T,handleBatch:N,handleOptions:P}}function Be(e){try{return z$1.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=getOpenApiMetadata(t.zodSchema);n&&(Object.assign(t.jsonSchema,n),(t.jsonSchema.anyOf||t.jsonSchema.oneOf)&&delete t.jsonSchema.type);let r=t.zodSchema?._zod?.def;r&&(r.type==="date"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):r.type==="bigint"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf&&(t.jsonSchema.type="string",t.jsonSchema.format="int64"));}})}catch(t){return typeof console<"u"&&console.warn&&console.warn("[generateOpenAPISpec] Failed to convert Zod schema to JSON Schema; falling back to {type:object}.",t),{type:"object"}}}function ee(e){return {$ref:`#/components/schemas/${e}`}}function Q(e){return {description:e,content:{"application/json":{schema:ee("ErrorResponse")}}}}function He(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function Co(e){return {description:"Paginated list of documents",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:{type:"object",properties:{items:{type:"array",items:e},nextCursor:{oneOf:[{type:"object"},{type:"null"}]},prevCursor:{oneOf:[{type:"object"},{type:"null"}]},hasNextPage:{type:"boolean"},hasPrevPage:{type:"boolean"},totalCount:{type:"integer",description:"Total count of matching documents (when requested with withTotal=true)"},totalCountIsExact:{type:"boolean",description:"Whether totalCount is exact (true) or estimated due to OR conditions (false)"}},required:["items","hasNextPage","hasPrevPage"]},meta:{type:"object",properties:{pageSize:{type:"integer"},hasMore:{type:"boolean"},totalCount:{type:"integer"},totalCountIsExact:{type:"boolean"},cursor:{oneOf:[{type:"string"},{type:"null"}]}}}},required:["success","data"]}}}}}function pt(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 Oo(e,t){let n=t.split("."),r=pt(e);for(let s=0;s<n.length;s++){let o=n[s];if(!o)continue;let a=r?.shape;if(!a||!a[o])return;let i=a[o];if(s===n.length-1)return i;r=pt(i);}return r}function $e(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type,r=s=>{let o=getOpenApiMetadata(e);return o&&typeof s.openapi=="function"?s.openapi(o):s};if(n==="ZodObject"||n==="object"){let s=e.shape,o={};for(let[a,i]of Object.entries(s))o[a]=$e(i);return r(z$1.object(o).partial())}if(n==="ZodOptional"||n==="optional"){let s=t.innerType;if(!s)return e;let o=$e(s);return o===s?e:r(o.optional())}if(n==="ZodNullable"||n==="nullable"){let s=t.innerType;if(!s)return e;let o=$e(s);return o===s?e:r(o.nullable())}if(n==="ZodDefault"||n==="default"){let s=t.innerType;return s?r($e(s).optional()):e}if(n==="ZodUnion"||n==="union"){let s=t.options;if(!s||s.length<2)return e;let o=s.map(i=>$e(i));return o.some((i,l)=>i!==s[l])?r(z$1.union(o)):e}return e}function Tn(e,t="",n=0){if(n>5)return [];let s=pt(e)?.shape;if(!s)return [];let o=[];for(let[a,i]of Object.entries(s)){let l=t?`${t}.${a}`:a,y=pt(i);y?.shape&&typeof y.shape=="object"?(o.push({path:l,zodSchema:i}),o.push(...Tn(y,l,n+1))):o.push({path:l,zodSchema:i});}return o}function Eo(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:Oo(e.schema,t)})):Tn(e.schema)}function Dr(e){if(!e)return {type:"string"};let t=Be(e);return delete t.$schema,delete t.title,t}function jr(){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)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function Po(e){let t=Eo(e),n=e.orderableFields??t.map(a=>a.path),r=t.map(a=>a.path);if(t.length===0)return jr();let s=[];for(let{path:a,zodSchema:i}of t){let l=Dr(i),y=pt(i),b=y?._zod?.def?.type==="array"||y?._def?.typeName==="ZodArray"||y?._def?.type==="array"?Dr(y?._zod?.def?.element??y?._def?.type??y?._def?.element):l;s.push({type:"array",description:`Condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["==","!=","<","<=",">",">=","eq","ne","lt","lte","gt","gte"]},l],minItems:3,maxItems:3}),s.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:l}],minItems:3,maxItems:3}),s.push({type:"array",description:`Array contains condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains","contains"]},b],minItems:3,maxItems:3}),s.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:b}],minItems:3,maxItems:3});}let o={oneOf:s};return {type:"object",properties:{where:{type:"array",items:o,description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:o,description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:o},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)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function $o(e,t,n,r,s,o=null,a="QueryRequestBody"){let i={},l=e.name,y=`${t}/${e.name}`,g=`${y}/{${e.documentKey}}`,b={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};i[y]={post:{operationId:`create${Se(e.name)}`,summary:`Create a ${pe(e.name)}`,tags:[l],requestBody:{required:true,content:{"application/json":{schema:ee(r??n)}}},responses:{201:He("Document created",ee(n)),400:Q("Validation error"),403:Q("Forbidden"),500:Q("Internal server error")}}},i[`${y}/query`]={post:{operationId:`query${Se(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[l],requestBody:{required:true,content:{"application/json":{schema:ee(a)}}},responses:{200:Co(ee(n)),400:Q("Invalid query"),403:Q("Forbidden"),424:Q("Missing composite index (includes indexUrl in response)"),500:Q("Internal server error")}}},i[`${y}/batch`]={post:{operationId:`batch${Se(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[l],requestBody:{required:true,content:{"application/json":{schema:ee(`${n}BatchRequest`)}}},responses:{200:He("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:Q("Validation error"),403:Q("Forbidden"),404:Q("Document not found"),500:Q("Internal server error")}}};let v={};return v.get={operationId:`get${Se(pe(e.name))}`,summary:`Get a single ${pe(e.name)}`,tags:[l],parameters:[b],responses:{200:He("Document found",ee(n)),400:Q("Document ID required"),403:Q("Forbidden"),404:Q("Document not found"),424:Q("Missing composite index (includes indexUrl in response)"),500:Q("Internal server error")}},v.put={operationId:`update${Se(pe(e.name))}`,summary:`Update a ${pe(e.name)} (full replace)`,tags:[l],parameters:[b],requestBody:{required:true,content:{"application/json":{schema:ee(s??n)}}},responses:{200:He("Document updated",ee(n)),400:Q("Validation error"),403:Q("Forbidden"),404:Q("Document not found"),500:Q("Internal server error")}},v.patch={operationId:`patch${Se(pe(e.name))}`,summary:`Partially update a ${pe(e.name)}`,tags:[l],parameters:[b],requestBody:{required:true,content:{"application/json":{schema:ee(o??s??n)}}},responses:{200:He("Document patched",ee(n)),400:Q("Validation error"),403:Q("Forbidden"),404:Q("Document not found"),500:Q("Internal server error")}},e.allowDelete&&(v.delete={operationId:`delete${Se(pe(e.name))}`,summary:`Delete a ${pe(e.name)}`,tags:[l],parameters:[b],responses:{200:He("Document deleted",{type:"object",properties:{id:{type:"string"}}}),400:Q("Document ID required"),403:Q("Forbidden"),404:Q("Document not found"),500:Q("Internal server error")}}),i[g]=v,i}function An(e,t,n={}){let{title:r="CRUD API",version:s="1.0.0",description:o,servers:a,auth:i=false}=n,l=t==="/"?"":t.replace(/\/$/,""),y={},g={},b=[];y.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string",description:"Human-readable error description"},errorType:{type:"string",enum:["index"],description:"Error category discriminator. Set to 'index' when a Firestore composite index is missing."},indexUrl:{type:"string",format:"uri",description:"Direct Firebase Console URL to create the required composite index (when errorType is 'index')."}},required:["success","error"]},y.QueryRequestBody=jr();for(let[T,P]of Object.entries(e)){let N=Se(pe(T)),S=`${N}Create`,d=`${N}Update`,p=`${N}Patch`,u=`${N}QueryRequestBody`;y[N]=Be(P.schema),y[u]=Po(P);let c=k=>{let D={},j=Tn(P.schema);for(let{path:A,zodSchema:E}of j){let M=A.split(".")[0];P.systemKeys.includes(M)||P.systemKeys.includes(A)||k&&k.length>0&&!k.includes(A)&&!k.includes(M)||(A.includes(".")?D[A]=E.optional():D[A]=E);}return D},f=null,m=c(P.createFields);Object.keys(m).length>0&&(y[S]=Be(z$1.object(m)),f=S);let x=null,h=null,w=c(P.mutableFields);if(Object.keys(w).length>0){let k=z$1.object(w);y[d]=Be(k),x=d,y[p]=Be($e(k)),h=p;}else y[p]=Be($e(P.schema)),h=p;let O=`${N}BatchCreateOperation`,$=`${N}BatchUpdateOperation`,I=`${N}BatchDeleteOperation`;y[O]={type:"object",title:`${N} Create Operation`,properties:{type:{type:"string",enum:["create"],const:"create"},data:ee(f??N)},required:["type","data"]},y[$]={type:"object",title:`${N} Update Operation`,properties:{type:{type:"string",enum:["update"],const:"update"},id:{type:"string"},data:ee(h??x??N)},required:["type","id","data"]},P.allowDelete&&(y[I]={type:"object",title:`${N} Delete Operation`,properties:{type:{type:"string",enum:["delete"],const:"delete"},id:{type:"string"}},required:["type","id"]}),y[`${N}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[ee(O),ee($),...P.allowDelete?[ee(I)]:[]],discriminator:{propertyName:"type"}}}},required:["operations"]};let _=$o(P,l,N,f,x,h,u);Object.assign(g,_),b.push({name:T,description:`Operations on ${T} (collection: ${P.path})`});}let v={},C;return i==="basic"?(v.basicAuth={type:"http",scheme:"basic"},C=[{basicAuth:[]}]):i==="bearer"&&(v.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},C=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:s,...o?{description:o}:{}},...a&&a.length>0?{servers:a}:{},paths:g,components:{schemas:y,...Object.keys(v).length>0?{securitySchemes:v}:{}},...C?{security:C}:{},tags:b}}function Se(e){return e.charAt(0).toUpperCase()+e.slice(1)}function pe(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 qe=class extends Error{constructor(n,r){super("Request validation failed");this.zodError=n;this.source=r;this.statusCode=400;this.name="ValidationError";}};var ft=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},yt=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function Nr(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function Mr(e,t){return t instanceof qe?e.json({success:false,error:"Validation failed",issues:Nr(t.zodError)},400):t instanceof ft?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof yt?e.json({success:false,error:"Output validation failed",issues:Nr(t.zodError)},500):null}extendZodWithOpenApi(z$1);var Fr="Successful response",zr="Error response";function No(e){return e==="get"?"query":"json"}function Mo(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function Fo(e){if(typeof e.safeParse=="function")return {description:zr,schema:e};let t=e;return {description:t.description??zr,schema:t.schema}}function Br(e,t,n,r){let s=new OpenAPIRegistry;if(n.securitySchemes)for(let[i,l]of Object.entries(n.securitySchemes))s.registerComponent("securitySchemes",i,l);for(let i of e){let l=i.method,y=i.source??No(l),g=Bo(t,i.path??"/"),b=i.status??200,v=zo(l,y,i.input),C=Hr(y,i.input,"query"),R=Hr(y,i.input,"param"),T=qo(l,g),P=Mo(i.output,r),N={[b]:P?{description:Fr,content:{"application/json":{schema:P}}}:{description:Fr}};if(r?.errors)for(let[S,d]of Object.entries(r.errors)){let{description:p,schema:u}=Fo(d);N[S]=u?{description:p,content:{"application/json":{schema:u}}}:{description:p};}s.registerPath({method:l,path:Ho(g),operationId:T,summary:i.summary,description:i.description,tags:i.tags,deprecated:i.deprecated,security:i.security,request:{...C?{query:C}:{},...R?{params:R}:{},...v?{body:v}:{}},responses:N});}return new OpenApiGeneratorV31(s.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security})}function zo(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 Hr(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function Ho(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function Bo(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,s=`${n}${r}`;return s===""?"/":s}function qo(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function qr(e,t){let n=e.replace(/"/g,"&quot;");return `<!doctype html>
1155
+ `;function it(){return jsx("script",{dangerouslySetInnerHTML:{__html:ur}})}un();function xe(e){return "<!DOCTYPE html>"+renderToString(e)}var ls=["corporate","silk","dark"],ds=()=>jsxs("div",{class:"dropdown dropdown-end","data-frs-theme-switcher":true,children:[jsxs("button",{type:"button",tabIndex:0,class:"btn btn-sm btn-ghost text-neutral-content gap-1.5","aria-label":"Switch theme",children:[jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",class:"size-4",children:[jsx("circle",{cx:"12",cy:"12",r:"4"}),jsx("path",{d:"M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"})]}),jsx("span",{class:"text-xs hidden sm:inline","data-frs-theme-current":true,children:"Theme"})]}),jsx("ul",{tabIndex:0,class:"dropdown-content menu menu-sm bg-base-100 text-base-content rounded-box z-50 mt-2 w-40 p-1 shadow-lg border border-base-300",children:ls.map(e=>jsx("li",{children:jsxs("button",{type:"button","data-frs-theme":e,class:"capitalize justify-between",children:[jsx("span",{children:e}),jsx("span",{class:"hidden text-primary","data-frs-theme-check":e,children:"\u2713"})]})},e))})]}),ve=({opts:e,children:t})=>{let{title:n,breadcrumb:r,flash:o,basePath:s="/"}=e;return jsxs("html",{lang:"en","data-theme":"corporate",children:[jsxs("head",{children:[jsx("meta",{charset:"UTF-8"}),jsx("meta",{name:"viewport",content:"width=device-width, initial-scale=1"}),jsxs("title",{children:[n," \u2014 FRS Admin"]}),jsx("script",{dangerouslySetInnerHTML:{__html:"(function(){try{var t=localStorage.getItem('frs-admin-theme');if(t){document.documentElement.setAttribute('data-theme',t);}}catch(_){}})();"}}),jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/themes.css",rel:"stylesheet",type:"text/css"}),jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/daisyui.css",rel:"stylesheet",type:"text/css"}),jsx("script",{src:"https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"})]}),jsxs("body",{class:"bg-base-200/50 min-h-screen flex flex-col",children:[jsxs("div",{class:"navbar bg-neutral text-neutral-content shadow-sm sticky top-0 z-50 px-6",children:[jsx("div",{class:"flex-1",children:jsx("a",{href:s,class:"font-bold text-lg tracking-tight hover:opacity-80 transition-opacity",children:"FRS Admin"})}),jsx("div",{class:"flex-none",children:jsx(ds,{})})]}),jsxs("main",{class:"px-6 py-8 w-full flex-1",children:[r&&r.length>0&&jsx("div",{class:"text-sm breadcrumbs mb-4",children:jsx("ul",{children:r.map((a,i)=>a.href?jsx("li",{children:jsx("a",{href:a.href,children:a.label})},i):jsx("li",{class:"text-base-content/60",children:a.label},i))})}),jsx("h1",{class:"text-2xl font-bold mb-6",children:n}),o&&jsxs("div",{role:"alert",class:`alert ${o.type==="success"?"alert-success":o.type==="warning"?"alert-warning":"alert-error"} mb-6`,children:[jsx("span",{class:"flex-1",children:o.message}),o.action&&jsx("a",{href:o.action.href,...o.action.external?{target:"_blank",rel:"noopener noreferrer"}:{},class:"btn btn-sm btn-outline",children:o.action.label})]}),t]}),jsx(dn,{basePath:s}),jsx(it,{})]})]})};function pn(e,t){return xe(jsx(ve,{opts:t,children:jsx("div",{dangerouslySetInnerHTML:{__html:e}})}))}function fn(e,t){return xe(jsx(ve,{opts:{title:"Repositories",basePath:t},children:e.length===0?jsxs("div",{class:"text-center py-20 text-base-content/50",children:[jsx("p",{class:"text-lg font-medium mb-1",children:"No repositories configured"}),jsx("p",{class:"text-sm",children:"Add a repository to your FRS config to get started."})]}):jsx("div",{class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:e.map(n=>jsx("a",{href:`${t}/${n.name}`,class:"card bg-base-100 border border-base-300 hover:shadow-md no-underline transition-shadow",children:jsxs("div",{class:"card-body p-5",children:[jsx("h2",{class:"card-title text-sm font-semibold",children:n.name}),jsx("p",{class:"text-xs text-base-content/50 font-mono",children:n.path})]})},n.name))})}))}var mr=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],us=[{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"}],ps=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function fs(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return us;case "ZodBoolean":return mr;case "ZodArray":return ps;default:return mr}}var Se="__null__";function ys(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="${Se}"]');if(!o){o=document.createElement('option');o.value='${Se}';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='${Se}';i.readOnly=true;}i.style.opacity='0.55';}else{i.style.opacity='';if(i.tagName==='SELECT'){var o2=i.querySelector('option[value="${Se}"][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!=='${Se}')?i.dataset._prev:'';}}})(this)`}function ms(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 ut({inputId:e,active:t}){return jsxs("label",{class:"flex items-center gap-1 cursor-pointer select-none text-xs text-base-content/60 hover:text-base-content border border-base-300 rounded-md px-1.5 py-1 shrink-0 leading-none h-8",title:"Filter where field IS NULL",children:[jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",checked:t,onchange:ys(e)}),jsx("span",{children:"\u2205"})]})}function hs({col:e,active:t}){let n=t?.value??"",r=n===Se,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 i=new Set(n.split(",").map(y=>y.trim()).filter(Boolean)),c=`eg_${e.name.replace(/\./g,"__")}`;return jsxs("div",{class:"flex flex-wrap items-center gap-1 w-full",children:[jsx("input",{type:"hidden",id:o,name:`fv_${e.name}`,value:n}),e.enumValues.map(y=>jsxs("label",{class:"flex items-center gap-1 text-xs border border-base-300 rounded px-2 cursor-pointer hover:bg-base-200",children:[jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",value:y,checked:i.has(y),"data-enum-group":c,onchange:ms(o,c)}),jsx("span",{children:y})]},y))]})}return jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),e.enumValues.map(i=>jsx("option",{value:i,selected:n===i,children:i},i)),e.nullable&&jsx("option",{value:Se,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx(ut,{inputId:o,active:r})]})}if(e.zodType==="ZodBoolean")return jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),jsx("option",{value:"true",selected:n==="true",children:"true"}),jsx("option",{value:"false",selected:n==="false",children:"false"}),e.nullable&&jsx("option",{value:Se,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx(ut,{inputId:o,active:r})]});if(e.zodType==="ZodArray"){let i=t?.op==="array-contains-any";return jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:i?"val1, val2, \u2026":"value",class:"input input-sm input-bordered w-full"})}return e.zodType==="ZodNumber"||e.zodType==="ZodBigInt"?jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsx("input",{id:o,type:r?"text":"number",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0,"data-_type":r?"number":void 0}),e.nullable&&jsx(ut,{inputId:o,active:r})]}):e.zodType==="ZodDate"?jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsx("input",{id:o,type:r?"text":"datetime-local",name:`fv_${e.name}`,value:n,class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0,"data-_type":r?"datetime-local":void 0}),e.nullable&&jsx(ut,{inputId:o,active:r})]}):jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0}),e.nullable&&jsx(ut,{inputId:o,active:r})]})}function yn({action:e,columnMeta:t,activeFilters:n,isGroup:r}){let o=Object.fromEntries(n.map(c=>[c.field,c])),s=n.length>0,a=n.length>=2||r&&s,i=t.filter(c=>c.zodType!=="ZodObject"&&c.zodType!=="ZodRecord");return jsxs("details",{class:"collapse collapse-arrow bg-base-100 border border-base-300 rounded-box mb-6 shadow-sm",open:s?true:void 0,children:[jsxs("summary",{class:"collapse-title text-sm font-medium py-2 min-h-0",children:["Filters",s&&jsxs("span",{class:"badge badge-primary badge-sm ml-2",children:[n.length," active"]})]}),jsx("div",{class:"collapse-content pb-4 pt-2",children:jsxs("form",{method:"get",action:e,children:[jsx("div",{class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:i.map(c=>{let y=fs(c.zodType),h=o[c.name],m=h?.op??y[0].value;return jsxs("div",{class:"flex flex-col gap-1.5",children:[jsx("label",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:c.name}),jsxs("div",{class:"flex gap-1.5",children:[y.length>1?jsx("select",{name:`fo_${c.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:y.map(x=>jsx("option",{value:x.value,selected:x.value===m,children:x.label},x.value))}):jsx("input",{type:"hidden",name:`fo_${c.name}`,value:y[0].value}),jsx(hs,{col:c,active:h})]})]},c.name)})}),jsxs("div",{class:"flex flex-wrap gap-2 mt-4 pt-3 border-t border-base-200 items-center",children:[jsx("button",{type:"submit",class:"btn btn-sm btn-primary",children:"Apply"}),s&&jsx("a",{href:e,class:"btn btn-sm btn-ghost",children:"Clear"}),a&&jsxs("span",{class:"text-xs text-warning ml-auto flex items-center gap-1",children:[jsx("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-4 w-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),r?"Collection group queries require a composite index":"Multiple filters may require a composite index"]})]})]})})]})}function mn(e,t,n,r,o,s){let a=n==="create"?`Create ${e}`:`Edit ${e} / ${r??""}`,i=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 xe(jsx(ve,{opts:{title:a,breadcrumb:i,basePath:o,flash:s},children:jsx("div",{class:"card bg-base-100 border border-base-300",children:jsx("div",{class:"card-body p-6",children:jsx("div",{dangerouslySetInnerHTML:{__html:t}})})})}))}Pt();ln();function hn(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 hr(e,t,n,r,o){let s=hn(e,r,o);return s.set("cursor",t),s.set("dir",n),`?${s.toString()}`}function gs(e,t,n,r){let o=hn(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 bs(e,t,n){return `?${hn(t,n,e).toString()}`}function gn(e,t,n,r,o,s,a=[],i=[],c=false,y=[],h,m,x,C,T,k,E,N=false){let S=`${r}/${e}`,l=`${S}/create`,p={};if(E)for(let w of n)p[w]=ct(lt(E,w));let u=(k??[]).filter(w=>true),d=u.length>0,f=c,g=f||d,v=u.map(w=>{let O=lt(E,w),I=ct(O),P=a.find(_=>_.name===w);return {name:w,type:I,enumValues:P?.enumValues??null,nullable:P?.nullable??false}}),b=[];return E&&(b=ce(E).filter(O=>u.includes(O.name))),xe(jsxs(ve,{opts:{title:e,breadcrumb:[{label:"Repositories",href:r},{label:e}],basePath:r,flash:s},children:[a.length>0&&jsx(yn,{action:S,columnMeta:a,activeFilters:i,isGroup:C}),x&&jsxs("div",{role:"alert",class:`alert ${x.type==="index"?"alert-warning":"alert-error"} mb-6 shadow-sm`,children:[jsx("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6 shrink-0 stroke-current",fill:"none",viewBox:"0 0 24 24",children:x.type==="index"?jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"}):jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"})}),jsxs("div",{class:"flex-1",children:[jsx("h3",{class:"font-bold",children:x.type==="index"?"Composite index required":"Query failed"}),jsx("div",{class:"text-sm",children:x.message})]}),x.indexUrl&&jsx("a",{href:x.indexUrl,target:"_blank",rel:"noopener noreferrer",class:"btn btn-sm btn-outline",children:"Create Index \u2192"})]}),jsxs("div",{class:"flex flex-wrap justify-between items-center mb-4 gap-3","data-frs-toolbar":true,children:[jsxs("div",{class:"flex items-center gap-3",children:[jsxs("span",{class:"text-sm text-base-content/60",children:[t.length,typeof T=="number"&&jsxs(Fragment,{children:[" ","of"," ",jsx("span",{class:"font-semibold text-base-content/80",children:T})]})," ","document",(typeof T=="number"?T:t.length)!==1&&"s"]}),jsxs("div",{class:"flex items-center gap-1.5 text-sm text-base-content/60",children:[jsx("span",{children:"Rows"}),jsx("div",{class:"join",children:[10,25,50,100].map(w=>jsx("a",{href:bs(w,i,h),class:`join-item btn btn-xs ${m===w?"btn-active btn-primary":"btn-outline"}`,children:w},w))})]})]}),jsxs("div",{class:"flex gap-2",children:[jsx("form",{method:"post",action:`${S}/_bulk/backfill`,onsubmit:"return confirm('Backfill entire repository? This will scan all documents and fill missing system keys.')",children:jsx("button",{type:"submit",class:"btn btn-outline btn-sm",children:"Backfill"})}),jsx("a",{href:l,class:"btn btn-primary btn-sm",children:"+ New"})]})]}),g&&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 T=="number"?String(T):"","data-frs-page-size":String(m??t.length),"data-frs-allow-delete":f?"1":"0","data-frs-allow-update":d?"1":"0","data-frs-fields":JSON.stringify(v),"data-frs-filters":JSON.stringify(i),children:[jsxs("div",{class:"flex-1 text-sm",children:[jsx("span",{"data-frs-bulk-summary":true,children:"0 selected"}),typeof T=="number"&&T>t.length&&jsxs("button",{type:"button",class:"ml-3 link text-sm hidden","data-frs-bulk-select-all":true,children:["Select all ",T," matching documents"]}),jsxs("span",{class:"hidden ml-3 italic","data-frs-bulk-all-active":true,children:["All ",T??"?"," matching documents are selected."," ",jsx("button",{type:"button",class:"link","data-frs-bulk-clear":true,children:"Clear selection"})]})]}),jsxs("div",{class:"flex gap-2",children:[d&&jsx("button",{type:"button",class:"btn btn-sm btn-outline","data-frs-bulk-action":"update",children:"Update field\u2026"}),f&&jsx("button",{type:"button",class:"btn btn-sm btn-error btn-outline","data-frs-bulk-action":"delete",children:"Delete"})]})]}),jsx("div",{class:"overflow-x-auto rounded-box border border-base-300 bg-base-100","data-frs-table-wrap":true,children:jsxs("table",{class:"table table-sm w-full","data-frs-table":true,"data-frs-repo":e,"data-frs-colcount":n.length,children:[jsx("thead",{children:jsxs("tr",{class:"bg-base-200/50",children:[g&&jsx("th",{class:"w-8",children:jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-page":true,"aria-label":"Select all on this page"})}),[...n].map((w,O)=>{let I=h?.field===w,P=I?h.dir==="asc"?" \u25B2":" \u25BC":"";return jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:jsxs("a",{href:gs(w,h,i,m),class:`hover:text-base-content inline-flex items-center gap-0.5${I?" text-primary font-bold":""}`,children:[w,P]})},O)}),y.map((w,O)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:w.column},`rel-${O}`)),jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide text-right",children:"Actions"})]})}),jsx("tbody",{children:t.length===0?jsx("tr",{children:jsx("td",{colspan:n.length+y.length+1+(g?1:0),class:"text-center py-16 text-base-content/40",children:"No documents found"})}):t.map((w,O)=>{let I=String(w.docId??w.id??""),P=`${r}/${e}/${encodeURIComponent(I)}/edit`,_=`${r}/${e}/${encodeURIComponent(I)}/delete`;return jsxs("tr",{class:"hover","data-frs-row-id":I,children:[g&&jsx("td",{class:"align-middle py-2",children:jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-row":true,value:I,"aria-label":`Select ${I}`})}),n.map((R,D)=>{let j=w[R],A=p[R],$=A?dt(A,j):null;return jsx("td",{class:"align-top py-2",children:jsx(Be,{val:j,mismatch:$})},D)}),y.map((R,D)=>{let j=w[R.key];if(j==null||j==="")return jsx("td",{class:"py-2"},`rel-${D}`);let A=R.type==="one"?`${r}/${R.targetRepo}/${encodeURIComponent(String(j))}/edit`:`${r}/${R.targetRepo}?fv_${R.targetKey}=${encodeURIComponent(String(j))}`;return jsx("td",{class:"align-middle py-2",children:jsx("a",{href:A,class:"btn btn-xs btn-ghost btn-outline","data-frs-relation":true,"data-frs-rel-type":R.type,"data-frs-rel-repo":R.targetRepo,"data-frs-rel-fk":R.targetKey,"data-frs-rel-val":String(j),"data-frs-rel-label":R.column,children:R.column})},`rel-${D}`)}),jsx("td",{class:"align-middle text-right whitespace-nowrap py-2",children:jsxs("div",{class:"flex gap-1 justify-end",children:[jsx("a",{href:P,class:"btn btn-xs btn-outline",children:"Edit"}),N&&jsx("a",{href:`${r}/${e}/${encodeURIComponent(I)}/history`,class:"btn btn-xs btn-outline",title:"View change history",children:"History"}),c&&jsx("form",{method:"post",action:_,onsubmit:"return confirm('Delete this document?')",children:jsx("button",{type:"submit",class:"btn btn-xs btn-error btn-outline",children:"Delete"})})]})})]},O)})})]})}),(o.hasPrev||o.hasNext)&&jsxs("div",{class:"flex flex-col items-center mt-6 gap-2",children:[jsxs("div",{class:"flex justify-center items-center gap-2",children:[o.hasPrev?jsx("a",{href:hr(i,o.prevCursor,"prev",h,m),class:"btn btn-sm btn-outline",children:"\u2190 Previous"}):jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"\u2190 Previous"}),o.hasNext?jsx("a",{href:hr(i,o.nextCursor,"next",h,m),class:"btn btn-sm btn-outline",children:"Next \u2192"}):jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"Next \u2192"})]}),typeof T=="number"&&jsxs("div",{class:"text-xs text-base-content/50",children:[T," total document",T!==1?"s":"",i.length>0?" matching filters":""]})]}),g&&d&&jsxs("dialog",{id:"frs-bulk-update-modal",class:"modal",children:[jsxs("div",{class:"modal-box",children:[jsx("h3",{class:"font-bold text-lg mb-3",children:"Bulk update field"}),jsx("p",{class:"text-sm text-base-content/60 mb-4","data-frs-bulk-update-summary":true,children:"Update one field on the selected documents."}),jsxs("form",{method:"dialog","data-frs-bulk-update-form":true,"data-frs-form":true,children:[jsxs("label",{class:"form-control w-full mb-3",children:[jsx("div",{class:"label",children:jsx("span",{class:"label-text text-xs uppercase tracking-wide",children:"Field"})}),jsxs("select",{class:"select select-bordered select-sm w-full",name:"field",required:true,"data-frs-bulk-field-select":true,children:[jsx("option",{value:"",children:"\u2014 Select a field \u2014"}),u.map(w=>jsx("option",{value:w,children:w},w))]})]}),jsx("div",{class:"mb-4","data-frs-bulk-value-container":true}),jsxs("div",{class:"modal-action",children:[jsx("button",{type:"button",class:"btn btn-sm btn-ghost","data-frs-bulk-update-cancel":true,children:"Cancel"}),jsx("button",{type:"submit",class:"btn btn-sm btn-primary","data-frs-bulk-update-submit":true,children:"Apply"})]})]})]}),jsx("form",{method:"dialog",class:"modal-backdrop",children:jsx("button",{children:"close"})})]}),jsx("div",{class:"hidden","data-frs-bulk-templates":true,children:b.map(w=>jsx("div",{"data-frs-bulk-template-for":w.name,dangerouslySetInnerHTML:{__html:st(w)}},w.name))})]}))}var xs="";function pt(e,t){return pn(e,t)}function bn(e,t){return fn(e,t)}function wn(e,t,n,r,o,s,a,i,c,y,h,m,x,C,T,k,E,N){return gn(e,t,n,r,o,s,a,i,c,y,h,m,x,C,T,k,E,N)}function Re(e,t,n,r,o,s){return mn(e,t,n,r,o,s)}async function gr(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 It(e,t){return Ge(e,{pathKey:t.pathKey,documentKey:t.documentKey??"docId",parentKeys:t.parentKeys,documentPathTemplate:t.documentPathTemplate,isGroup:t.isGroup})}async function qe(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 xn(e,t,n){let r=e.documentKey??"docId",o=at(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 B(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function Dt(e,t){e.status(302).set("Location",t).send("");}function _t(e,t){let n=t.shape,r={};for(let[o,s]of Object.entries(n)){let a=Sn(s),i=K(a),c=i==="ZodObject",y=a,h=false;if(i==="ZodUnion"){let C=rt(a);C.some(k=>K(k)==="ZodDate")&&(h=true);let T=C.find(k=>{if(K(k)==="ZodObject"){let E=re(k);return "latitude"in E&&"longitude"in E}return false});T&&(c=true,y=T);}if(e[o+"__isnull"]==="1"){r[o]=null;continue}if(c){let C={},T=false;for(let[N,S]of Object.entries(e))N.startsWith(`${o}.`)&&(C[N.slice(o.length+1)]=S,T=true);if(T){r[o]=_t(C,y);continue}let k=e[o],E=Array.isArray(k)?k[k.length-1]:k;if(E)try{r[o]=JSON.parse(E);}catch{r[o]=E;}continue}let m=e[o],x=Array.isArray(m)?m[m.length-1]:m;if(x===void 0||x===""){i==="ZodBoolean"&&(r[o]=false);continue}if(h){r[o]=new Date(x);continue}switch(i){case "ZodBoolean":x==="__null__"?r[o]=null:r[o]=x==="true"||x==="on"||x==="1";break;case "ZodNumber":case "ZodBigInt":r[o]=Number(x);break;case "ZodDate":r[o]=new Date(x);break;case "ZodArray":try{r[o]=JSON.parse(x);}catch{r[o]=x;}break;default:if(x.startsWith("{")||x.startsWith("["))try{r[o]=JSON.parse(x);break}catch{}r[o]=x;}}return r}function br(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 xr(e){let t=e;for(;;){let n=K(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=ne(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=Xe(t);if(!r)return n;t=r;}else return n}}function Sn(e){let t=e;for(;;){let n=K(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=ne(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=Xe(t);if(!r)return t;t=r;}else return t}}function vr(e){let t=e;for(;;){let n=K(t);if(n==="ZodOptional"||n==="ZodNullable")return true;if(n==="ZodDefault"){t=ne(t);continue}return false}}function Sr(e){let t=Sn(e),n=K(t);if(n==="ZodEnum"){let r=et(t);return r.length>0?r:void 0}if(n==="ZodNativeEnum"){let r=tt(t),o=Object.values(r).filter(s=>typeof s=="string");return o.length>0?o:void 0}if(n==="ZodLiteral"){let r=nt(t);return typeof r=="string"?[r]:void 0}}function Rr(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 i=Sn(t.shape[o]),c=K(i),y=c==="ZodObject",h=i,m=false;if(c==="ZodUnion"){let x=rt(i);x.some(T=>K(T)==="ZodDate")&&(m=true);let C=x.find(T=>{if(K(T)==="ZodObject"){let k=re(T);return "latitude"in k&&"longitude"in k}return false});C&&(y=true,h=C);}if(y&&typeof a=="object"&&a!==null&&!Array.isArray(a)&&!("_seconds"in a)&&typeof a.toDate!="function"){let x=Rr(a,h,s);Object.assign(r,x);}else if(c==="ZodDate"||m){let x=br(a);x!==null&&(r[s]=x);}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)&&("_seconds"in a||typeof a.toDate=="function")){let x=br(a);r[s]=x??JSON.stringify(a,null,2);}else typeof a=="object"?r[s]=JSON.stringify(a,null,2):r[s]=String(a);}return r}function vn(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?vn(n.nested,t):void 0}))}function Ss(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 i=(s??"").trim();if(!i)continue;let c=e[`fo_${a}`]??"==",y=n.has(c)?c:"==";r.push({field:a,op:y,value:i});}return r}function wr(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 Tr(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 i=xr(a);if(i==="ZodObject"){let c=a;for(;;){let h=K(c);if(h==="ZodOptional"||h==="ZodNullable"||h==="ZodDefault")c=ne(c);else break}let y=re(c);r.push(...Tr(Object.keys(y),c,s));}else r.push({name:s,zodType:i,nullable:vr(a),enumValues:Sr(a)});}return r}function Rs(e,t){let n=t.split("."),r=e;for(let o of n){for(;;){let a=K(r);if(a==="ZodOptional"||a==="ZodNullable"||a==="ZodDefault")r=ne(r);else break}let s=re(r);if(!(o in s))return null;r=s[o];}return r}function Oe(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 i=s.slice(0,a),c=s.slice(a+1);r.has(i)||r.set(i,[]),r.get(i).push(c);}}let o={};for(let s of n)s in e.shape&&(o[s]=e.shape[s]);for(let[s,a]of r){if(!(s in e.shape))continue;let i=e.shape[s];for(;;){let c=K(i);if(c==="ZodOptional"||c==="ZodNullable"||c==="ZodDefault")i=ne(i);else break}if(K(i)!=="ZodObject"){o[s]=e.shape[s];continue}o[s]=Oe(i,a);}return z$1.object(o)}function pe(e,t,n){return ue(e,t,n)}function kr(e,t,n){let r=(l,p)=>{let u=pe(l,t,n),d=Object.values(e).map(f=>({name:f.name,path:f.path}));B(p,bn(d,u));},o=async(l,p)=>{let u=l.params.repoName;if(!u){B(p,"Bad request",400);return}let d=e[u];if(!d){B(p,"Repository not found",404);return}let f=d.pageSize??25,g=l.query??{},v=g.cursor,b=g.dir==="prev"?"prev":"next",w=g.ob??"",O=g.od==="desc"?"desc":"asc",I=w?{field:w,dir:O}:void 0,P=parseInt(g.ps??""),_=Number.isFinite(P)&&P>0?Math.min(P,200):f,R=d.listColumns??Object.keys(d.schema.shape),D=d.documentKey??"docId",j=[D,...R.filter(ie=>ie!==D)];I&&(new Set([D,...R]).has(I.field)||(I=void 0));let A=d.filterableFields?(()=>{let ie=[];for(let ye of d.filterableFields)(ye.includes(".")||R.includes(ye))&&ie.push(ye);return ie})():R,$=(()=>{let ie=[];for(let ye of A)if(ye.includes(".")){let je=Rs(d.schema,ye);ie.push({name:ye,zodType:je?xr(je):"ZodString",nullable:je?vr(je):false,enumValues:je?Sr(je):void 0});}else ie.push(...Tr([ye],d.schema));return ie})(),M=new Set($.map(ie=>ie.name)),Z=Ss(g,M),U=wr(Z),_e;v&&(_e=await gr(d,v));let[J,Q]=await Promise.all([d.repo.query.paginate({pageSize:_,cursor:_e,direction:b,...U.length>0?{where:U}:{},...I?{orderBy:[{field:I.field,direction:I.dir}]}:{}}).catch(ie=>({queryError:at(ie,{ref:d.repo.ref,path:d.path,isGroup:!!d.isGroup,filters:Z,sort:I})})),d.repo.aggregate.count(U.length>0?{where:U}:{}).catch(()=>{})]),te="queryError"in J,eo=te?[]:J.data,to=te?"":J.nextCursor?.ref?.path??J.nextCursor?.id??"",no=te?"":J.prevCursor?.ref?.path??J.prevCursor?.id??"",ro=te?J.queryError:void 0,oo=pe(l,t,n),Ke,wt=g.flash;wt==="created"?Ke={type:"success",message:"Document created successfully."}:wt==="updated"?Ke={type:"success",message:"Document updated successfully."}:wt==="deleted"?Ke={type:"success",message:"Document deleted successfully."}:wt==="backfilled"&&(Ke={type:"success",message:"Repository backfilled successfully."}),B(p,wn(d.name,eo,j,oo,{hasPrev:te?false:J.hasPrevPage,hasNext:te?false:J.hasNextPage,prevCursor:no,nextCursor:to},Ke,$,Z,d.allowDelete??false,d.relationalMeta,I,_,ro,d.isGroup,Q,d.mutableFields,d.schema,d.historyEnabled));},s=(l,p)=>{let u=l.params.repoName;if(!u){B(p,"Bad request",400);return}let d=e[u];if(!d){B(p,"Repository not found",404);return}let f=pe(l,t,n),g=Oe(d.schema,d.createFields),v=ce(g),b=`${f}/${d.name}/create`,w=we(v,b,"POST","Create document");B(p,Re(d.name,w,"create",null,f));},a=async(l,p)=>{let u=l.params.repoName;if(!u){B(p,"Bad request",400);return}let d=e[u];if(!d){B(p,"Repository not found",404);return}let f=pe(l,t,n),g=l.body??{},v=_t(g,d.schema),b=Oe(d.schema,d.createFields),w=b.safeParse(v);if(!w.success){let O=ce(b),I=`${f}/${d.name}/create`,P=we(O,I,"POST","Create document"),_=w.error.issues.map(R=>`${R.path.join(".")}: ${R.message}`).join(", ");B(p,Re(d.name,P,"create",null,f,{type:"error",message:`Validation error: ${_}`}),422);return}try{if(d.isGroup&&d.parentKeys&&d.parentKeys.length>0){let O={...w.data},I=d.parentKeys.filter(P=>O[P]===void 0||O[P]===null||typeof O[P]=="string"&&O[P].trim()==="");if(I.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${I.join(", ")}`);if(typeof d.repo.create=="function")await d.repo.create(O);else {let P=d.parentKeys.map(D=>String(O[D])),_=d.documentKey??"docId",R=O[_]||Ne();await d.repo.set(...P,R,O);}}else await d.repo.create(w.data);Dt(p,`${f}/${d.name}?flash=created`);}catch(O){let I=Oe(d.schema,d.createFields),P=ce(I),_=`${f}/${d.name}/create`,R=we(P,_,"POST","Create document");B(p,Re(d.name,R,"create",null,f,{type:"error",message:`Save error: ${O.message}`}),500);}},i=async(l,p)=>{let u=l.params.repoName,d=l.params.id;if(!u||!d){B(p,"Bad request",400);return}let f=e[u];if(!f){B(p,"Repository not found",404);return}let g=pe(l,t,n),v=null;try{v=await qe(f,d);}catch(_){let R=xn(f,d,_),D=Ae(_)?424:500;B(p,pt("",{title:`Edit ${f.name} / ${d}`,basePath:g,breadcrumb:[{label:"Repositories",href:g},{label:f.name,href:`${g}/${f.name}`},{label:`Edit ${d}`}],flash:R}),D);return}if(!v){B(p,"Document not found",404);return}let b=Rr(v,f.schema),w=Oe(f.schema,f.mutableFields),O=vn(ce(w),b),I=`${g}/${f.name}/${encodeURIComponent(d)}/edit`,P=we(O,I,"POST","Save changes");B(p,Re(f.name,P,"edit",d,g));},c=async(l,p)=>{let u=l.params.repoName,d=l.params.id;if(!u||!d){B(p,"Bad request",400);return}let f=e[u];if(!f){B(p,"Repository not found",404);return}let g=pe(l,t,n),v=l.body??{},b=_t(v,f.schema),w=Oe(f.schema,f.mutableFields),I=w.partial().safeParse(b);if(!I.success){let P=Object.fromEntries(Object.entries(v).map(([A,$])=>[A,Array.isArray($)?$.join(","):$??""])),_=vn(ce(w),P),R=`${g}/${f.name}/${encodeURIComponent(d)}/edit`,D=we(_,R,"POST","Save changes"),j=I.error.issues.map(A=>`${A.path.join(".")}: ${A.message}`).join(", ");B(p,Re(f.name,D,"edit",d,g,{type:"error",message:`Validation error: ${j}`}),422);return}try{let P=await qe(f,d),_=(P&&It(P,f))??[d];await f.repo.update(..._,I.data),Dt(p,`${g}/${f.name}?flash=updated`);}catch(P){let _=Oe(f.schema,f.mutableFields),R=ce(_),D=`${g}/${f.name}/${encodeURIComponent(d)}/edit`,j=we(R,D,"POST","Save changes"),A=Ae(P)?xn(f,d,P):{type:"error",message:`Save error: ${P.message}`},$=Ae(P)?424:500;B(p,Re(f.name,j,"edit",d,g,A),$);}},y=async(l,p)=>{let u=l.params.repoName,d=l.params.id;if(!u||!d){B(p,"Bad request",400);return}let f=e[u];if(!f){B(p,"Repository not found",404);return}if(!f.allowDelete){B(p,"Delete is not allowed for this repository",403);return}let g=pe(l,t,n);try{let v=await qe(f,d),b=(v&&It(v,f))??[d];await f.repo.delete(...b),Dt(p,`${g}/${f.name}?flash=deleted`);}catch(v){let b=Ae(v)?xn(f,d,v):{type:"error",message:`Delete error: ${v.message}`},w=Ae(v)?424:500;B(p,pt("",{title:`Delete ${f.name} / ${d}`,basePath:g,breadcrumb:[{label:"Repositories",href:g},{label:f.name,href:`${g}/${f.name}`},{label:`Delete ${d}`}],flash:b}),w);}},h=async(l,p)=>{let u=l.params.repoName;if(!u){B(p,"Bad request",400);return}let d=e[u];if(!d){B(p,"Repository not found",404);return}let f=pe(l,t,n),g=l.query,v=g?.type==="many"?"many":"one",b=Math.max(1,Math.min(100,Number(g?.ps??25)||25)),w=d.listColumns??Object.keys(re(d.schema)),{PanelOne:O,PanelMany:I}=await Promise.resolve().then(()=>(un(),fr)),{renderToString:P}=await import('hono/jsx/dom/server');if(v==="one"){let $=String(g?.id??"");if(!$){B(p,"<div class='p-6 text-error'>Missing id parameter.</div>",400);return}try{let M=await qe(d,$),Z=P(O({doc:M,repoName:d.name,basePath:f,schema:d.schema,columns:w}));B(p,Z);}catch(M){B(p,`<div class='p-6 text-error text-sm'>Error: ${M.message}</div>`,500);}return}let _=String(g?.fk??""),R=String(g?.fv??"");if(!_||!R){B(p,"<div class='p-6 text-error'>Missing fk/fv parameters.</div>",400);return}let D=g?.cursor??"",j=g?.dir==="prev"?"prev":"next",A;D&&(A=await gr(d,D));try{let $=await d.repo.query.paginate({pageSize:b,cursor:A,direction:j,where:[[_,"==",Ts(R)]]}),M=P(I({docs:$.data,repoName:d.name,basePath:f,fk:_,fv:R,columns:w,schema:d.schema,pagination:{hasPrev:$.hasPrevPage,hasNext:$.hasNextPage,prevCursor:$.prevCursor?.ref?.path??$.prevCursor?.id??"",nextCursor:$.nextCursor?.ref?.path??$.nextCursor?.id??"",pageSize:b}}));B(p,M);}catch($){B(p,`<div class='p-6 text-error text-sm'>Error: ${$.message}</div>`,500);}},m=async(l,p)=>{let u=l.params.repoName;if(!u){B(p,"Bad request",400);return}let d=e[u];if(!d){B(p,"Repository not found",404);return}let f=pe(l,t,n);try{await d.repo.system.backfillKeys(),Dt(p,`${f}/${d.name}?flash=backfilled`);}catch(g){B(p,`<div class="p-6 text-error">Backfill failed: ${g.message}</div>`,500);}},x=async(l,p)=>{let u=[];for(let d of p){let f;if(l.isGroup||l.parentKeys?.length){let g=await qe(l,d);f=g?It(g,l):void 0;}f||(f=[d]);try{let g=l.repo.documentRef(...f);g&&u.push(g);}catch{}}return u},C=async(l,p)=>{let u=wr(p),d=l.documentKey??"docId",f=[],g;for(;;){let v=await l.repo.query.paginate({pageSize:500,cursor:g,direction:"next",...u.length>0?{where:u}:{}});for(let b of v.data){let w=String(b[d]??b.id??"");w&&f.push(w);}if(!v.hasNextPage||!v.nextCursor)break;g=v.nextCursor;}return f},T=async(l,p)=>{let u=l.params.repoName;if(!u){se(p,{error:"Bad request"},400);return}let d=e[u];if(!d){se(p,{error:"Repository not found"},404);return}if(!d.allowDelete){se(p,{error:"Delete is not allowed for this repository"},403);return}let f=l.body??{};try{let g=await E(d,f);if(g.length===0){se(p,{deleted:0});return}let v=await x(d,g);for(let b=0;b<v.length;b+=500)await d.repo.bulk.delete(v.slice(b,b+500));se(p,{deleted:v.length});}catch(g){se(p,{error:g.message},500);}},k=async(l,p)=>{let u=l.params.repoName;if(!u){se(p,{error:"Bad request"},400);return}let d=e[u];if(!d){se(p,{error:"Repository not found"},404);return}let f=l.body??{},g=String(f.field??"");if(!g){se(p,{error:"Missing 'field'"},400);return}if(!d.mutableFields||!d.mutableFields.includes(g)){se(p,{error:`Field '${g}' is not bulk-updatable`},403);return}let v=d.schema.shape?.[g],b;if(v){let w=typeof d.schema=="object"&&d.schema&&"constructor"in d.schema&&d.schema.constructor.name.includes("Zod")?d.schema.pick({[g]:true}):void 0;if(!w){se(p,{error:"Invalid schema structure"},500);return}b=_t(f.formPayload??{},w)[g];let I=v.safeParse(b);if(!I.success){se(p,{error:`Invalid value for '${g}': ${I.error.message}`},400);return}b=I.data;}try{let w=await E(d,f);if(w.length===0){se(p,{updated:0});return}let I=(await x(d,w)).map(P=>({docRef:P,data:{[g]:b}}));for(let P=0;P<I.length;P+=500)await d.repo.bulk.update(I.slice(P,P+500));se(p,{updated:I.length});}catch(w){se(p,{error:w.message},500);}};async function E(l,p){if(p.selectAll){let u=N(p.filters,l);return await C(l,u)}return Array.isArray(p.ids)?p.ids.filter(u=>typeof u=="string"&&!!u):[]}function N(l,p){if(!Array.isArray(l))return [];let u=new Set((p.filterableFields??Object.keys(re(p.schema))).map(g=>String(g))),d=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),f=[];for(let g of l)g&&typeof g=="object"&&typeof g.field=="string"&&u.has(g.field)&&typeof g.value=="string"&&d.has(String(g.op))&&f.push({field:g.field,op:g.op,value:g.value});return f}return {handleDashboard:r,handleList:o,handleCreateForm:s,handleCreateSubmit:a,handleEditForm:i,handleEditSubmit:c,handleDelete:y,handlePanel:h,handleBulkDelete:T,handleBulkUpdate:k,handleBulkBackfill:m,handleHistory:async(l,p)=>{let u=l.params.repoName,d=l.params.id;if(!u||!d){B(p,"Bad request",400);return}let f=e[u];if(!f){B(p,"Repository not found",404);return}if(!f.historyEnabled||!f.repo.history){B(p,"History not enabled for this repository",404);return}let g=pe(l,t,n),v=f.historySubcollection??"history",b=[d];try{let $=await qe(f,d),M=$?It($,f):void 0;M&&M.length>0&&(b=M);}catch{}let w=parseInt(String(l.query?.limit??"")),O=Number.isFinite(w)&&w>0?Math.min(w,500):100,I=[],P;try{I=await f.repo.history.list(...b,{limit:O});}catch($){P=$.message;}let _=$=>String($??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),R=$=>{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">${_(JSON.stringify($))}</code>`}catch{return _(String($))}return _(String($))},D=$=>$?typeof $.toDate=="function"?$.toDate().toISOString():$ instanceof Date?$.toISOString():_(String($)):"",j=$=>`<span class="badge badge-sm ${$==="create"?"badge-success":$==="delete"?"badge-error":"badge-info"}">${_($)}</span>`,A="";if(A+='<div class="flex items-center justify-between mb-4">',A+=`<a href="${g}/${f.name}/${encodeURIComponent(d)}/edit" class="btn btn-sm btn-outline">\u2190 Back to edit</a>`,A+=`<a href="${g}/${f.name}" class="btn btn-sm btn-outline">\u2190 Back to list</a>`,A+="</div>",A+=`<p class="text-sm text-base-content/60 mb-4">Subcollection: <code>${_(v)}</code> \xB7 Showing up to ${O} entries.</p>`,P)A+=`<div class="alert alert-error mb-4">${_(P)}</div>`;else if(I.length===0)A+='<div class="alert">No history entries found.</div>';else {A+='<div class="overflow-x-auto"><table class="table table-zebra table-sm">',A+="<thead><tr><th>When</th><th>Op</th><th>User</th><th>Reason / Comment</th><th>Changes</th></tr></thead><tbody>";for(let $ of I){let M=$.meta??{},Z=[M.reason,M.comment].filter(J=>J!=null&&J!=="").map(J=>_(String(J))).join(" \u2014 "),U="",_e=Object.keys($.changes??{});_e.length===0?U='<span class="opacity-40">\u2014</span>':U='<ul class="space-y-1">'+_e.map(J=>{let Q=$.changes[J];return `<li><strong>${_(J)}</strong>: ${R(Q.oldValue)} \u2192 ${R(Q.newValue)}</li>`}).join("")+"</ul>",A+="<tr>",A+=`<td class="whitespace-nowrap text-xs font-mono">${_(D($.historySetAt))}</td>`,A+=`<td>${j($.operation??"update")}</td>`,A+=`<td class="text-xs">${_(M.userEmail??M.userId??"")}</td>`,A+=`<td class="text-xs">${Z}</td>`,A+=`<td>${U}</td>`,A+="</tr>";}A+="</tbody></table></div>";}B(p,pt(A,{title:`History \u2014 ${f.name} / ${d}`,basePath:g,breadcrumb:[{label:"Repositories",href:g},{label:f.name,href:`${g}/${f.name}`},{label:`History ${d}`}]}));}}}function se(e,t,n=200){e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(t));}function Ts(e){return e==="true"?true:e==="false"?false:e!==""&&!isNaN(Number(e))?Number(e):e}Nt();async function ks(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function As(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 Er(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,auth:s,middleware:a=[],httpsOptions:i}=e,c=t==="/"?"":t.replace(/\/$/,""),y={};for(let[C,T]of Object.entries(n)){if(!T.repo)throw new Error(`[createAdminServer] Repository "${C}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let k=T.schema??T.repo.schema??null;if(!k)throw new Error(`[createAdminServer] Repository "${C}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let E,N,S;if(T.fieldsConfig){let u=T.fieldsConfig;E=[],N=[],S=[];for(let[d,f]of Object.entries(u))for(let g of f)g==="filterable"?E.push(d):g==="mutable"?N.push(d):g==="create"&&S.push(d);E.length===0&&(E=void 0),N.length===0&&(N=void 0),S.length===0&&(S=void 0);}let l=(()=>{let u=T.repo._parentKeys;return u&&u.length>0?u:void 0})();if(l&&S)for(let u of l)S.includes(u)||S.push(u);let p={name:C,path:T.path,repo:T.repo,schema:k,documentKey:T.documentKey??"docId",pathKey:T.repo._pathKey??void 0,isGroup:!!T.repo._isGroup,parentKeys:l,documentPathTemplate:T.repo._documentPathTemplate??void 0,createdKey:T.repo._createdKey??void 0,listColumns:T.listColumns,pageSize:T.pageSize,filterableFields:E,mutableFields:N,createFields:S,allowDelete:T.allowDelete??false,historyEnabled:!!T.repo._historyConfig?.enabled,historySubcollection:(T.repo._historyConfig?.enabled&&T.repo._historySubcollection)??void 0,relationalMeta:(()=>{if(!T.relationalFields||T.relationalFields.length===0)return;let u=T.repo.relationalKeys??{},d=[];for(let f of T.relationalFields){let g=u[f.key];g&&d.push({key:g.sourceKey?String(g.sourceKey):f.key,column:f.column,targetRepo:String(g.repo),targetKey:String(g.key),type:g.type});}return d.length>0?d:void 0})()};y[C]=p;}let h=kr(y,c,vt(i?.region)),m=new he;if(o!==false&&m.use(jt(o===void 0?{}:o)),r&&m.use(async(C,T,k)=>{let E=C,N=String(E.headers?.["content-type"]??"");if(N.includes("application/x-www-form-urlencoded")){let S=await ks(E);C.body=As(S);}else if(N.includes("application/json")&&typeof E.body=="string")try{C.body=JSON.parse(E.body);}catch{}await k();}),s)if(Je(s)){for(let C of s.routes){let T=`${c}${C.path}`;C.method==="GET"?m.get(T,C.handler):m.post(T,C.handler);}m.use(s.middleware);}else if(typeof s=="function")m.use(s);else {let C=s.realm??"Admin",T="Basic "+Buffer.from(`${s.username}:${s.password}`).toString("base64");m.use((k,E,N)=>{if((k.headers?.authorization??"")!==T){E.status(401).set("WWW-Authenticate",`Basic realm="${C}"`).set("Content-Type","text/plain").send("Unauthorized");return}N();});}for(let C of a)m.use(C);m.get(`${c}/`,h.handleDashboard),m.get(`${c}`,h.handleDashboard),m.get(`${c}/:repoName/_panel`,h.handlePanel),m.post(`${c}/:repoName/_bulk/delete`,h.handleBulkDelete),m.post(`${c}/:repoName/_bulk/update`,h.handleBulkUpdate),m.post(`${c}/:repoName/_bulk/backfill`,h.handleBulkBackfill),m.get(`${c}/:repoName`,h.handleList),m.get(`${c}/:repoName/create`,h.handleCreateForm),m.post(`${c}/:repoName/create`,h.handleCreateSubmit),m.get(`${c}/:repoName/:id/edit`,h.handleEditForm),m.post(`${c}/:repoName/:id/edit`,h.handleEditSubmit),m.get(`${c}/:repoName/:id/history`,h.handleHistory),m.post(`${c}/:repoName/:id/delete`,h.handleDelete);let x=async(C,T)=>{await m.handle(C,T);};return i&&(x.httpsOptions=i),x}Fe();function ft(e,t){let n=e||{},r={},o={...n};for(let[s,a]of Object.entries(t||{})){let i=n[s];Qe(i,a)||(r[s]=a,o[s]=a);}return {before:n,after:o,changes:r}}function Pr(e){return e}async function Tn(e,t,n){let r=e.changes||{};for(let o of Object.keys(r)){let s=t[o];if(s&&s.length>0){for(let a of s)if(await a.rule({diff:e,key:o,user:n,authenticatedUser:n})===false)return {allowed:false,reason:a.description}}}return {allowed:true}}function $r(e){return async t=>Tn(t.diff,e,t.user)}function Cn(e,t,n=200){let r=ke(t);return e.json(r,n)}function Ee(e,t,n,r=200){return Cn(e,{success:true,data:t,meta:n},r)}function z(e,t,n=400){return Cn(e,{success:false,error:t},n)}async function kn(e,t,n,r,o,s){let a=at(t,n),i=a.type==="index",c=i?424:500,h={success:false,error:i?a.message:o&&t instanceof Error?t.message:r};if(i&&(h.errorType="index",a.indexUrl&&(h.indexUrl=a.indexUrl,s)))try{let m=s({indexUrl:a.indexUrl,repoName:n.repoName??"",path:n.path,isGroup:n.isGroup,filters:n.filters,sort:n.sort,error:t,c:e});m instanceof Promise&&await m;}catch(m){o&&console.error("[crudServer] Error in indexesError callback:",m);}return Cn(e,h,c)}function Pe(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return z$1.preprocess(r=>zn(r)??r,e);if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[s,a]of Object.entries(r))o[s]=Pe(a);return z$1.object(o)}if(n==="ZodArray"||n==="array"){let r=t.element??t.type;if(r)return z$1.array(Pe(r))}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(r)return Pe(r).optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(r)return Pe(r).nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType,o=t.defaultValue;if(r){let s=Pe(r);return typeof o=="function"?s.default(o()):s.default(o)}}return e}function Cs(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 i=a.split(".")[0];i&&r[i]&&(o[i]=r[i]);}return z$1.object(o)}function An(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 _r(e,t){let n=t.split("."),r=An(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 i=a[s];if(o===n.length-1)return i;r=An(i);}return r}function $e(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type;if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[s,a]of Object.entries(r))o[s]=$e(a);return z$1.object(o).partial()}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(!r)return e;let o=$e(r);return o===r?e:o.optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(!r)return e;let o=$e(r);return o===r?e:o.nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType;return r?$e(r).optional():e}if(n==="ZodUnion"||n==="union"){let r=t.options;if(!r||r.length<2)return e;let o=r.map(a=>$e(a));return o.some((a,i)=>a!==r[i])?z$1.union(o):e}return e}function Mt(e,t,n,r=false,o=[]){if(typeof t!="object"||t===null||Array.isArray(t))return {success:false,error:"Data payload must be an object"};try{let s=t,a={},i={};for(let[c,y]of Object.entries(s))if(c.includes(".")){let h=c.split(".")[0];if(o.includes(c)||o.includes(h))continue;if(n&&n.length>0&&!n.includes(c)&&!n.includes(h))return {success:!1,error:`Field '${c}' is not allowed for this operation`};let m=_r(e,c);if(!m)return {success:!1,error:`Field '${c}' does not exist in schema`};let x=r?$e(m):m,T=(Yt()==="normalize"?Pe(x):x).parse(y);a[c]=T;}else i[c]=y;if(Object.keys(i).length>0||Object.keys(a).length===0){let c=Cs(e,n,o),y=r?$e(c):c,m=(Yt()==="normalize"?Pe(y):y).parse(i);Object.assign(a,m);}return {success:!0,data:a}}catch(s){return s instanceof z$1.ZodError?{success:false,error:`Validation failed: ${s.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}var jr={eq:"==","==":"==",ne:"!=","!=":"!=",lt:"<","<":"<",lte:"<=","<=":"<=",gt:">",">":">",gte:">=",">=":">=",in:"in",nin:"not-in","not-in":"not-in",not_in:"not-in",contains:"array-contains","array-contains":"array-contains",array_contains:"array-contains",arrayContains:"array-contains",containsAny:"array-contains-any","array-contains-any":"array-contains-any",array_contains_any:"array-contains-any",arrayContainsAny:"array-contains-any"};function yt(e){return jr[e]??e}function Os(e){return e in jr}function Ft(e,t,n,r){let o=_r(e,t);if(!o||typeof o.safeParse!="function")return {success:true,data:n};let s=r?yt(r):void 0,a=An(o),i=Rt(a);if(s==="array-contains"){let h=i??o;if(typeof h.safeParse=="function"){let m=h.safeParse(n);return m.success?{success:true,data:m.data}:{success:false,error:m.error.issues.map(C=>C.message).join(", ")}}return {success:true,data:n}}if(s==="array-contains-any"){if(!Array.isArray(n))return {success:false,error:"Expected array value for array-contains-any"};let h=i??o,m=[];for(let x of n)if(typeof h.safeParse=="function"){let C=h.safeParse(x);if(C.success)m.push(C.data);else return {success:false,error:C.error.issues.map(k=>k.message).join(", ")}}else m.push(x);return {success:true,data:m}}let c=o.safeParse(n);if(c.success)return {success:true,data:c.data};if(Array.isArray(n)){let h=i??o,m=[];for(let x of n)if(typeof h.safeParse=="function"){let C=h.safeParse(x);if(C.success)m.push(C.data);else return {success:false,error:C.error.issues.map(k=>k.message).join(", ")}}else m.push(x);return {success:true,data:m}}return {success:false,error:c.error.issues.map(h=>h.message).join(", ")}}function Es(e,t){let n=[],r=t?new Set(t):null;for(let[o,s]of Object.entries(e)){if(s===void 0||["cursor","direction","limit","pageSize","orderBy","orderDir","select","includes","withTotal"].includes(o))continue;let a=Array.isArray(s)?s[0]:s;if(a===void 0||a==="")continue;let i=o.lastIndexOf("__"),c,y="==";if(i!==-1){let m=o.slice(0,i),x=o.slice(i+2);Os(x)?(c=m,y=yt(x)):(c=o,y="==");}else c=o;if(r&&!r.has(c))continue;let h=a;y==="in"||y==="not-in"||y==="array-contains-any"?h=a.split(",").map(m=>Ir(m.trim())):h=Ir(a),n.push({field:c,op:y,value:h});}return n}function Ir(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 zt(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function Dr(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 i=await a.doc(r).get();if(i.exists)return i}if(o&&o.includes("/")&&a&&typeof a.doc=="function"){let i=await a.doc(o).get();if(i.exists)return i}if(o&&typeof s.doc=="function"){let i=await s.doc(o).get();if(i.exists)return i}return}catch{return}}function Nr(e,t,n,r){async function o(S,l,p,u){if(!l.rules)return {allowed:true};let d=l.rules?.[p];if(!d)return {allowed:false,errorResponse:z(S,`Operation "${p}" is not allowed for this repository`,403)};try{let f=await d(u);return f===!1?{allowed:!1,errorResponse:z(S,"Forbidden",403)}:typeof f=="string"?{allowed:!1,errorResponse:z(S,f,403)}:typeof f=="object"&&f!==null&&!f.allowed?{allowed:!1,errorResponse:z(S,f.reason||"Forbidden",403)}:{allowed:!0}}catch(f){let g=n&&f instanceof Error?f.message:"Forbidden";return {allowed:false,errorResponse:z(S,g,403)}}}async function s(S,l,p,u){if(!S.rules)return u;let d=S.rules?.filter;if(!d)return u;let f=[];for(let g of u)try{await d({user:l,doc:g,params:p})&&f.push(g);}catch{}return f}function a(S){return S.get("user")??S.get("docsUser")??null}function i(S,l){if(!S){let p=l.req.path.split("/");for(let u of p)if(e[u]){S=u;break}}return !S||!e[S]?null:e[S]??null}function c(S,l){return Ge(S,{pathKey:l.pathKey,documentKey:l.documentKey,parentKeys:l.parentKeys,documentPathTemplate:l.documentPathTemplate,isGroup:l.isGroup})}async function y(S,l){let p=`by${S.documentKey.charAt(0).toUpperCase()}${S.documentKey.slice(1)}`,u=S.repo.get[p];if(typeof u=="function")try{let f=await u(l);if(f)return f}catch{}return (await S.repo.query.by({where:[[S.documentKey,"==",l]],limit:1}))[0]??null}async function h(S){let l=S.c,p=l.req.param(),u=i(p.repoName,l);if(!u)return z(l,"Repository not found",404);let d=a(l),f=await o(l,u,"list",{user:d,query:l.req.query(),params:p});if(!f.allowed)return f.errorResponse;let g=[],v;try{let b=l.req.query(),w=Math.min(Number(b.pageSize)||u.pageSize,100),O=b.cursor,I=b.direction?.toLowerCase()==="prev"?"prev":"next",P=b.orderBy,_=b.orderDir?.toLowerCase()==="desc"?"desc":"asc",R=b.select,D=R?R.split(",").map(Q=>Q.trim()):void 0,j=b.withTotal,A=j==="true"||j==="1"||j===!0,$;u.allowedIncludes&&b.includes&&($=(typeof b.includes=="string"?b.includes.split(",").map(te=>te.trim()):Array.isArray(b.includes)?b.includes:[]).filter(te=>typeof te=="string"&&u.allowedIncludes.includes(te)),$?.length===0&&($=void 0));let M=Es(b,u.filterableFields);g=M.map(Q=>({field:Q.field,op:Q.op,value:String(Q.value??"")})),P&&(v={field:P,dir:_});let Z={pageSize:w,direction:I,...A?{withTotal:!0}:{}};if(O)try{let Q=typeof O=="string"?JSON.parse(O):O;Z.cursor=await Dr(u,Q);}catch{}if(P){if(u.orderableFields&&!u.orderableFields.includes(P))return z(l,`Field not orderable: ${P}`,400);Z.orderBy=[{field:P,direction:_}];}if(M.length>0){Z.where=[];for(let Q of M){let te=Ft(u.schema,Q.field,Q.value,Q.op);if(!te.success)return z(l,`Invalid filter value for '${Q.field}': ${te.error}`,400);Z.where.push([Q.field,Q.op,te.data]);}}D&&(Z.select=D),$&&(Z.include=$);let U=await u.repo.query.paginate(Z),J={items:await s(u,a(l),p,U.data),hasNextPage:U.hasNextPage,hasPrevPage:U.hasPrevPage,nextCursor:zt(U.nextCursor),prevCursor:zt(U.prevCursor),...U.totalCount!==void 0?{totalCount:U.totalCount,totalCountIsExact:U.totalCountIsExact}:{}};return Ee(l,J,{pageSize:w,hasMore:U.hasNextPage,...U.totalCount!==void 0?{totalCount:U.totalCount,totalCountIsExact:U.totalCountIsExact}:{}})}catch(b){return await kn(l,b,{repoName:p.repoName||u.name,ref:u.repo.ref,path:u.path,isGroup:!!u.isGroup,filters:g,sort:v},"Failed to fetch documents",n,r)}}async function m(S){let l=S.c,p=l.req.param(),u=i(p.repoName,l);if(!u)return z(l,"Repository not found",404);let d=a(l),f=await o(l,u,"list",{user:d,query:S.input||{},params:p});if(!f.allowed)return f.errorResponse;let g=[],v;try{let b=S.input||{},w=Math.min(b.pageSize||u.pageSize,100),O=b.direction==="prev"?"prev":"next";b.where&&(g=b.where.map(j=>({field:String(j[0]),op:j[1],value:String(j[2]??"")}))),b.orderBy&&b.orderBy[0]&&(v={field:b.orderBy[0].field,dir:b.orderBy[0].direction==="desc"?"desc":"asc"});let I=b.withTotal===!0||String(b.withTotal)==="true",P={pageSize:w,direction:O,...I?{withTotal:!0}:{}};if(b.cursor)try{let j=typeof b.cursor=="string"?JSON.parse(b.cursor):b.cursor;P.cursor=await Dr(u,j);}catch{}if(u.allowedIncludes&&b.includes&&b.includes.length>0){let j=b.includes.filter(A=>typeof A=="string"?u.allowedIncludes.includes(A):typeof A=="object"&&A!==null&&"relation"in A&&typeof A.relation=="string"?u.allowedIncludes.includes(A.relation):!1);j.length>0&&(P.include=j);}if(b.where&&b.where.length>0){if(u.filterableFields){let A=new Set(u.filterableFields),$=b.where.filter(M=>!A.has(M[0]));if($.length>0){z(l,`Fields not filterable: ${$.map(M=>M[0]).join(", ")}`,400);return}}let j=[];for(let A of b.where){let $=yt(A[1]),M=Ft(u.schema,A[0],A[2],$);if(!M.success){z(l,`Invalid filter value for '${A[0]}': ${M.error}`,400);return}j.push([A[0],$,M.data]);}P.where=j;}if(b.orWhere&&b.orWhere.length>0){if(u.filterableFields){let A=new Set(u.filterableFields),$=b.orWhere.filter(M=>!A.has(M[0]));if($.length>0){z(l,`Fields not filterable: ${$.map(M=>M[0]).join(", ")}`,400);return}}let j=[];for(let A of b.orWhere){let $=yt(A[1]),M=Ft(u.schema,A[0],A[2],$);if(!M.success){z(l,`Invalid filter value for '${A[0]}': ${M.error}`,400);return}j.push([A[0],$,M.data]);}P.orWhere=j;}if(b.orWhereGroups&&b.orWhereGroups.length>0){if(u.filterableFields){let A=new Set(u.filterableFields);for(let $ of b.orWhereGroups){let M=$.filter(Z=>!A.has(Z[0]));if(M.length>0){z(l,`Fields not filterable: ${M.map(Z=>Z[0]).join(", ")}`,400);return}}}let j=[];for(let A of b.orWhereGroups){let $=[];for(let M of A){let Z=yt(M[1]),U=Ft(u.schema,M[0],M[2],Z);if(!U.success){z(l,`Invalid filter value for '${M[0]}': ${U.error}`,400);return}$.push([M[0],Z,U.data]);}j.push($);}P.orWhereGroups=j;}if(b.orderBy&&b.orderBy.length>0){if(u.orderableFields){let j=new Set(u.orderableFields),A=b.orderBy.filter($=>!j.has($.field));if(A.length>0){z(l,`Fields not orderable: ${A.map($=>$.field).join(", ")}`,400);return}}P.orderBy=b.orderBy;}b.select&&b.select.length>0&&(P.select=b.select);let _=await u.repo.query.paginate(P),D={items:await s(u,a(l),p,_.data),hasNextPage:_.hasNextPage,hasPrevPage:_.hasPrevPage,nextCursor:zt(_.nextCursor),prevCursor:zt(_.prevCursor),..._.totalCount!==void 0?{totalCount:_.totalCount,totalCountIsExact:_.totalCountIsExact}:{}};return Ee(l,D,{pageSize:w,hasMore:_.hasNextPage,..._.totalCount!==void 0?{totalCount:_.totalCount,totalCountIsExact:_.totalCountIsExact}:{}})}catch(b){return await kn(l,b,{repoName:p.repoName||u.name,ref:u.repo.ref,path:u.path,isGroup:!!u.isGroup,filters:g,sort:v},"Failed to query documents",n,r)}}async function x(S){let l=S.c,p=l.req.param(),u=i(p.repoName,l);if(!u)return z(l,"Repository not found",404);let d=p.id;if(!d)return z(l,"Document ID required",400);try{let f=await y(u,d);if(!f)return z(l,"Document not found",404);let g=a(l),v=await o(l,u,"get",{user:g,doc:f,params:p});if(!v.allowed)return v.errorResponse;if(u.rules?.filter)try{if(!await u.rules.filter({user:g,doc:f,params:p}))return z(l,"Document not found",404)}catch{return z(l,"Document not found",404)}return Ee(l,f)}catch(f){return await kn(l,f,{repoName:p.repoName||u.name,ref:u.repo.ref,path:u.path,isGroup:!!u.isGroup,filters:[{field:u.documentKey,op:"==",value:d}]},"Failed to fetch document",n,r)}}async function C(S){let l=S.c,p=l.req.param(),u=i(p.repoName,l);if(!u)return z(l,"Repository not found",404);try{let d=S.input||{},f=a(l),g=await o(l,u,"create",{user:f,body:d,params:p});if(!g.allowed)return g.errorResponse;let v=Mt(u.schema,d,u.createFields,!1,u.systemKeys);if(!v.success)return z(l,v.error,400);if(u.validate){let w=await u.validate(v.data,"create");if(w)return z(l,w,400)}let b;if(u.isGroup&&u.parentKeys&&u.parentKeys.length>0){let w={...v.data},O=u.parentKeys.filter(I=>w[I]===void 0||w[I]===null||typeof w[I]=="string"&&w[I].trim()==="");if(O.length>0){z(l,`Missing parent key(s) for subcollection create: ${O.join(", ")}`,400);return}if(typeof u.repo.create=="function")b=await u.repo.create(w);else {let I=u.parentKeys.map(_=>String(w[_])),P=w[u.documentKey]||Ne();b=await u.repo.set(...I,P,w);}}else b=await u.repo.create(v.data);return Ee(l,b,void 0,201)}catch(d){let f=n&&d instanceof Error?d.message:"Failed to create document";return z(l,f,500)}}async function T(S,l){let p=S.c,u=p.req.param(),d=i(u.repoName,p);if(!d)return z(p,"Repository not found",404);let f=u.id;if(!f)return z(p,"Document ID required",400);try{let g=S.input||{},v=await y(d,f);if(!v)return z(p,"Document not found",404);let b=Mt(d.schema,g,d.mutableFields,l,d.systemKeys);if(!b.success)return z(p,b.error,400);if(d.validate){let R=await d.validate(b.data,"update");if(R)return z(p,R,400)}let w=ft(v,b.data),O=a(p),I=await o(p,d,"update",{user:O,doc:v,body:b.data,diff:w,params:u});if(!I.allowed)return I.errorResponse;let P=c(v,d)??[f],_=await d.repo.update(...P,b.data);return Ee(p,_)}catch(g){let v=n&&g instanceof Error?g.message:"Failed to update document";return z(p,v,500)}}async function k(S){let l=S.c,p=l.req.param(),u=i(p.repoName,l);if(!u)return z(l,"Repository not found",404);if(!u.allowDelete)return z(l,"Delete not allowed for this repository",403);let d=p.id;if(!d)return z(l,"Document ID required",400);try{let f=await y(u,d);if(!f)return z(l,"Document not found",404);let g=a(l),v=await o(l,u,"delete",{user:g,doc:f,params:p});if(!v.allowed)return v.errorResponse;let b=c(f,u)??[d];return await u.repo.delete(...b),Ee(l,{deleted:!0})}catch(f){let g=n&&f instanceof Error?f.message:"Failed to delete document";return z(l,g,500)}}function E(S){return S.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 N(S){let l=S.c,p=l.req.param(),u=i(p.repoName,l);if(!u)return z(l,"Repository not found",404);try{let d=S.input||{};if(!Array.isArray(d.operations))return z(l,"operations array is required",400);let f=a(l),g=u.repo.batch.create(),v=[];for(let b of d.operations){if(!b.type||!["create","update","delete"].includes(b.type))return z(l,"Invalid operation type",400);if(b.type==="create"){let w=await o(l,u,"create",{user:f,body:b.data,params:p});if(!w.allowed)return w.errorResponse;let O=Mt(u.schema,b.data,u.createFields,!1,u.systemKeys);if(!O.success)return z(l,O.error,400);let I=b.data[u.documentKey]||Ne(),P={...O.data};if(u.createdKey&&P[u.createdKey]===void 0&&(P[u.createdKey]=new Date),u.isGroup&&u.parentKeys){let _=u.parentKeys.map(R=>P[R]);g.set(..._,I,P);}else g.set(I,P);v.push({op:"create",id:I});}else if(b.type==="update"){if(!b.id)return z(l,"id required for update",400);let w=await y(u,b.id);if(!w)return z(l,`Document ${b.id} not found`,404);let O=Mt(u.schema,b.data,u.mutableFields,!0,u.systemKeys);if(!O.success)return z(l,O.error,400);if(u.validate){let R=await u.validate(O.data,"update");if(R)return z(l,R,400)}let I=ft(w,O.data),P=await o(l,u,"update",{user:f,doc:w,body:O.data,diff:I,params:p});if(!P.allowed)return P.errorResponse;let _=c(w,u)??[b.id];g.update(..._,O.data),v.push({op:"update",id:b.id});}else if(b.type==="delete"){if(!u.allowDelete)return z(l,"Delete not allowed",403);if(!b.id)return z(l,"id required for delete",400);let w=await y(u,b.id);if(!w)return z(l,`Document ${b.id} not found`,404);let O=await o(l,u,"delete",{user:f,doc:w,params:p});if(!O.allowed)return O.errorResponse;let I=c(w,u)??[b.id];g.delete(...I),v.push({op:"delete",id:b.id});}}return await g.commit(),Ee(l,{results:v})}catch(d){let f=n&&d instanceof Error?d.message:"Batch operation failed";return z(l,f,500)}}return {handleList:h,handleQuery:m,handleGet:x,handleCreate:C,handleUpdate:T,handleDelete:k,handleBatch:N,handleOptions:E}}function Le(e){try{return z$1.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=getOpenApiMetadata(t.zodSchema);n&&(Object.assign(t.jsonSchema,n),(t.jsonSchema.anyOf||t.jsonSchema.oneOf)&&delete t.jsonSchema.type);let r=t.zodSchema?._zod?.def;r&&(r.type==="date"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):r.type==="bigint"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf&&(t.jsonSchema.type="string",t.jsonSchema.format="int64"));}})}catch(t){return typeof console<"u"&&console.warn&&console.warn("[generateOpenAPISpec] Failed to convert Zod schema to JSON Schema; falling back to {type:object}.",t),{type:"object"}}}function ee(e){return {$ref:`#/components/schemas/${e}`}}function V(e){return {description:e,content:{"application/json":{schema:ee("ErrorResponse")}}}}function Ze(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function Ps(e){return {description:"Paginated list of documents",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:{type:"object",properties:{items:{type:"array",items:e},nextCursor:{oneOf:[{type:"object"},{type:"null"}]},prevCursor:{oneOf:[{type:"object"},{type:"null"}]},hasNextPage:{type:"boolean"},hasPrevPage:{type:"boolean"},totalCount:{type:"integer",description:"Total count of matching documents (when requested with withTotal=true)"},totalCountIsExact:{type:"boolean",description:"Whether totalCount is exact (true) or estimated due to OR conditions (false)"}},required:["items","hasNextPage","hasPrevPage"]},meta:{type:"object",properties:{pageSize:{type:"integer"},hasMore:{type:"boolean"},totalCount:{type:"integer"},totalCountIsExact:{type:"boolean"},cursor:{oneOf:[{type:"string"},{type:"null"}]}}}},required:["success","data"]}}}}}function ht(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 $s(e,t){let n=t.split("."),r=ht(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 i=a[s];if(o===n.length-1)return i;r=ht(i);}return r}function De(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type,r=o=>{let s=getOpenApiMetadata(e);return s&&typeof o.openapi=="function"?o.openapi(s):o};if(n==="ZodObject"||n==="object"){let o=e.shape,s={};for(let[a,i]of Object.entries(o))s[a]=De(i);return r(z$1.object(s).partial())}if(n==="ZodOptional"||n==="optional"){let o=t.innerType;if(!o)return e;let s=De(o);return s===o?e:r(s.optional())}if(n==="ZodNullable"||n==="nullable"){let o=t.innerType;if(!o)return e;let s=De(o);return s===o?e:r(s.nullable())}if(n==="ZodDefault"||n==="default"){let o=t.innerType;return o?r(De(o).optional()):e}if(n==="ZodUnion"||n==="union"){let o=t.options;if(!o||o.length<2)return e;let s=o.map(i=>De(i));return s.some((i,c)=>i!==o[c])?r(z$1.union(s)):e}return e}function On(e,t="",n=0){if(n>5)return [];let o=ht(e)?.shape;if(!o)return [];let s=[];for(let[a,i]of Object.entries(o)){let c=t?`${t}.${a}`:a,y=ht(i);y?.shape&&typeof y.shape=="object"?(s.push({path:c,zodSchema:i}),s.push(...On(y,c,n+1))):s.push({path:c,zodSchema:i});}return s}function Is(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:$s(e.schema,t)})):On(e.schema)}function Mr(e){if(!e)return {type:"string"};let t=Le(e);return delete t.$schema,delete t.title,t}function zr(){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)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function Ds(e){let t=Is(e),n=e.orderableFields??t.map(a=>a.path),r=t.map(a=>a.path);if(t.length===0)return zr();let o=[];for(let{path:a,zodSchema:i}of t){let c=Mr(i),y=ht(i),m=y?._zod?.def?.type==="array"||y?._def?.typeName==="ZodArray"||y?._def?.type==="array"?Mr(y?._zod?.def?.element??y?._def?.type??y?._def?.element):c;o.push({type:"array",description:`Condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["==","!=","<","<=",">",">=","eq","ne","lt","lte","gt","gte"]},c],minItems:3,maxItems:3}),o.push({type:"array",description:`List condition on '${a}' (in, not-in)`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["in","not-in","nin"]},{type:"array",items:c}],minItems:3,maxItems:3}),o.push({type:"array",description:`Array contains condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains","contains"]},m],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:m}],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)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function _s(e,t,n,r,o,s=null,a="QueryRequestBody"){let i={},c=e.name,y=`${t}/${e.name}`,h=`${y}/{${e.documentKey}}`,m={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};i[y]={post:{operationId:`create${Te(e.name)}`,summary:`Create a ${fe(e.name)}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:ee(r??n)}}},responses:{201:Ze("Document created",ee(n)),400:V("Validation error"),403:V("Forbidden"),500:V("Internal server error")}}},i[`${y}/query`]={post:{operationId:`query${Te(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:ee(a)}}},responses:{200:Ps(ee(n)),400:V("Invalid query"),403:V("Forbidden"),424:V("Missing composite index (includes indexUrl in response)"),500:V("Internal server error")}}},i[`${y}/batch`]={post:{operationId:`batch${Te(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:ee(`${n}BatchRequest`)}}},responses:{200:Ze("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:V("Validation error"),403:V("Forbidden"),404:V("Document not found"),500:V("Internal server error")}}};let x={};return x.get={operationId:`get${Te(fe(e.name))}`,summary:`Get a single ${fe(e.name)}`,tags:[c],parameters:[m],responses:{200:Ze("Document found",ee(n)),400:V("Document ID required"),403:V("Forbidden"),404:V("Document not found"),424:V("Missing composite index (includes indexUrl in response)"),500:V("Internal server error")}},x.put={operationId:`update${Te(fe(e.name))}`,summary:`Update a ${fe(e.name)} (full replace)`,tags:[c],parameters:[m],requestBody:{required:true,content:{"application/json":{schema:ee(o??n)}}},responses:{200:Ze("Document updated",ee(n)),400:V("Validation error"),403:V("Forbidden"),404:V("Document not found"),500:V("Internal server error")}},x.patch={operationId:`patch${Te(fe(e.name))}`,summary:`Partially update a ${fe(e.name)}`,tags:[c],parameters:[m],requestBody:{required:true,content:{"application/json":{schema:ee(s??o??n)}}},responses:{200:Ze("Document patched",ee(n)),400:V("Validation error"),403:V("Forbidden"),404:V("Document not found"),500:V("Internal server error")}},e.allowDelete&&(x.delete={operationId:`delete${Te(fe(e.name))}`,summary:`Delete a ${fe(e.name)}`,tags:[c],parameters:[m],responses:{200:Ze("Document deleted",{type:"object",properties:{id:{type:"string"}}}),400:V("Document ID required"),403:V("Forbidden"),404:V("Document not found"),500:V("Internal server error")}}),i[h]=x,i}function En(e,t,n={}){let{title:r="CRUD API",version:o="1.0.0",description:s,servers:a,auth:i=false}=n,c=t==="/"?"":t.replace(/\/$/,""),y={},h={},m=[];y.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string",description:"Human-readable error description"},errorType:{type:"string",enum:["index"],description:"Error category discriminator. Set to 'index' when a Firestore composite index is missing."},indexUrl:{type:"string",format:"uri",description:"Direct Firebase Console URL to create the required composite index (when errorType is 'index')."}},required:["success","error"]},y.QueryRequestBody=zr();for(let[k,E]of Object.entries(e)){let N=Te(fe(k)),S=`${N}Create`,l=`${N}Update`,p=`${N}Patch`,u=`${N}QueryRequestBody`;y[N]=Le(E.schema),y[u]=Ds(E);let d=R=>{let D={},j=On(E.schema);for(let{path:A,zodSchema:$}of j){let M=A.split(".")[0];E.systemKeys.includes(M)||E.systemKeys.includes(A)||R&&R.length>0&&!R.includes(A)&&!R.includes(M)||(A.includes(".")?D[A]=$.optional():D[A]=$);}return D},f=null,g=d(E.createFields);if(E.isGroup&&E.parentKeys&&E.parentKeys.length>0){let R=E.schema?.shape??{};for(let D of E.parentKeys)!g[D]&&R[D]&&(g[D]=R[D]);}if(Object.keys(g).length>0){let R=Le(z$1.object(g));if(E.isGroup&&E.parentKeys&&E.parentKeys.length>0){let D=new Set(Array.isArray(R.required)?R.required:[]);for(let j of E.parentKeys)R.properties?.[j]&&D.add(j);D.size>0&&(R.required=Array.from(D));}y[S]=R,f=S;}let v=null,b=null,w=d(E.mutableFields);if(Object.keys(w).length>0){let R=z$1.object(w);y[l]=Le(R),v=l,y[p]=Le(De(R)),b=p;}else y[p]=Le(De(E.schema)),b=p;let O=`${N}BatchCreateOperation`,I=`${N}BatchUpdateOperation`,P=`${N}BatchDeleteOperation`;y[O]={type:"object",title:`${N} Create Operation`,properties:{type:{type:"string",enum:["create"],const:"create"},data:ee(f??N)},required:["type","data"]},y[I]={type:"object",title:`${N} Update Operation`,properties:{type:{type:"string",enum:["update"],const:"update"},id:{type:"string"},data:ee(b??v??N)},required:["type","id","data"]},E.allowDelete&&(y[P]={type:"object",title:`${N} Delete Operation`,properties:{type:{type:"string",enum:["delete"],const:"delete"},id:{type:"string"}},required:["type","id"]}),y[`${N}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[ee(O),ee(I),...E.allowDelete?[ee(P)]:[]],discriminator:{propertyName:"type"}}}},required:["operations"]};let _=_s(E,c,N,f,v,b,u);Object.assign(h,_),m.push({name:k,description:`Operations on ${k} (collection: ${E.path})`});}let x={},C;return i==="basic"?(x.basicAuth={type:"http",scheme:"basic"},C=[{basicAuth:[]}]):i==="bearer"&&(x.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},C=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:o,...s?{description:s}:{}},...a&&a.length>0?{servers:a}:{},paths:h,components:{schemas:y,...Object.keys(x).length>0?{securitySchemes:x}:{}},...C?{security:C}:{},tags:m}}function Te(e){return e.charAt(0).toUpperCase()+e.slice(1)}function fe(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 Ue=class extends Error{constructor(n,r){super("Request validation failed");this.zodError=n;this.source=r;this.statusCode=400;this.name="ValidationError";}};var gt=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},bt=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function Hr(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function Br(e,t){return t instanceof Ue?e.json({success:false,error:"Validation failed",issues:Hr(t.zodError)},400):t instanceof gt?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof bt?e.json({success:false,error:"Output validation failed",issues:Hr(t.zodError)},500):null}extendZodWithOpenApi(z$1);var qr="Successful response",Zr="Error response";function ae(e,t=new Set){if(!e||typeof e!="object"||t.has(e))return;t.add(e);let n=e,r=n._zod?.def??n.def;if(!r)return;if(r.type==="custom"){let s=getOpenApiMetadata(n);s?.type||z$1.globalRegistry.add(n,{...s??{},type:"object"});return}if(r.innerType&&ae(r.innerType,t),r.element&&ae(r.element,t),r.valueType&&ae(r.valueType,t),r.keyType&&ae(r.keyType,t),r.left&&ae(r.left,t),r.right&&ae(r.right,t),r.in&&ae(r.in,t),r.out&&ae(r.out,t),typeof r.getter=="function")try{ae(r.getter(),t);}catch{}if(Array.isArray(r.options))for(let s of r.options)ae(s,t);if(Array.isArray(r.items))for(let s of r.items)ae(s,t);let o=typeof r.shape=="function"?r.shape():r.shape;if(o&&typeof o=="object")for(let s of Object.values(o))ae(s,t);}function Pn(e){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(let n of e)Pn(n);return}let t=e;(Array.isArray(t.anyOf)||Array.isArray(t.oneOf))&&"type"in t&&delete t.type;for(let n of Object.values(t))Pn(n);}function zs(e){return e==="get"?"query":"json"}function Hs(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function Bs(e){if(typeof e.safeParse=="function")return {description:Zr,schema:e};let t=e;return {description:t.description??Zr,schema:t.schema}}function Kr(e,t,n,r){let o=new OpenAPIRegistry;if(n.securitySchemes)for(let[i,c]of Object.entries(n.securitySchemes))o.registerComponent("securitySchemes",i,c);for(let i of e){let c=i.method,y=i.source??zs(c),h=Ls(t,i.path??"/"),m=i.status??200;i.input&&ae(i.input);let x=qs(c,y,i.input),C=Lr(y,i.input,"query"),T=Lr(y,i.input,"param"),k=Us(c,h),E=Hs(i.output,r);E&&ae(E);let N={[m]:E?{description:qr,content:{"application/json":{schema:E}}}:{description:qr}};if(r?.errors)for(let[S,l]of Object.entries(r.errors)){let{description:p,schema:u}=Bs(l);u&&ae(u),N[S]=u?{description:p,content:{"application/json":{schema:u}}}:{description:p};}o.registerPath({method:c,path:Zs(h),operationId:k,summary:i.summary,description:i.description,tags:i.tags,deprecated:i.deprecated,security:i.security,request:{...C?{query:C}:{},...T?{params:T}:{},...x?{body:x}:{}},responses:N});}let a=new OpenApiGeneratorV31(o.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security});return Pn(a),a}function qs(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 Lr(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function Zs(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function Ls(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function Us(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function Wr(e,t){let n=e.replace(/"/g,"&quot;");return `<!doctype html>
1156
1156
  <html lang="en">
1157
1157
  <head>
1158
1158
  <meta charset="utf-8" />
@@ -1163,5 +1163,5 @@ function initColumnReorder(table) {
1163
1163
  <script id="api-reference" data-url="${n}"></script>
1164
1164
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
1165
1165
  </body>
1166
- </html>`}function Zr(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var Cn=new AsyncLocalStorage;function Lr(){return async(e,t)=>{await Cn.run({c:e},async()=>{await t();});}}var Ko=Object.freeze({}),Mt=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new Hono,this.mountedRoutes=Qo(t.routes,t.api),t.services&&this.app.use("*",Lr());let n=[...t.middlewares??[],...t.globalMiddlewares??[]];for(let r of n)this.app.use("*",r);this.mountRoutes(),this.mountOpenApi(),t.notFound&&this.app.notFound(t.notFound),t.onError&&this.app.onError(t.onError);}get hono(){return this.app}get nodeHandler(){return getRequestListener(this.app.fetch,{overrideGlobalObjects:false})}toFunction(t,n){let r=this.nodeHandler;return n?t(n,r):t(r)}buildOpenApiSpec(){if(this.cachedSpec)return this.cachedSpec;if(!this.options.openapi)throw new Error("[HonoServer] openapi config not set");return this.cachedSpec=Br(this.mountedRoutes,this.options.basePath??"",this.options.openapi,Vo(this.options.interceptor)),this.cachedSpec}mountRoutes(){let t=this.options.basePath??"",n=this.options.validateOutput??false,r=this.options.verbose??false;for(let s of this.mountedRoutes){if(!s.path)throw new Error(`[HonoServer] route "${s.method.toUpperCase()} (no path)" \u2014 missing \`path\`. Run the codegen so the path is derived from the file location, or set it explicitly.`);let o=Nt(t,s.path),a=s.middlewares??[],i=s.source??(s.method==="get"?"query":"json"),l=Yo(s,i,n,Wo(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),y=s.method.toUpperCase();this.app.on(y,[o],...a,l),r&&console.log(`[HonoServer] ${s.method.toUpperCase().padEnd(6)} ${o}`);}}mountOpenApi(){let t=this.options.openapi;if(!t)return;let n=t.path??"/openapi.json",r=t.docsPath===void 0?"/docs":t.docsPath,s=Nt(this.options.basePath??"",n),o=r===false?null:Nt(this.options.basePath??"",r),a;if(Zr(t.docsAuth)){let i=t.docsAuth;a=[i.middleware];let l=Go(o??s);for(let y of i.routes)this.app.on(y.method,[Nt(l,y.name)],y.handler);}else a=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[s],...a,i=>i.json(this.buildOpenApiSpec())),o){let i=Jo(o,s);this.app.on("GET",[o],...a,l=>l.html(qr(i,t.info.title)));}}};function Ur(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function Wo(e){if(e)return Ur(e)?e.handler:e}function Vo(e){return Ur(e)?e:void 0}function Qo(e,t){return t?e.filter(n=>Array.isArray(n.api)?n.api.includes(t):n.api===t):e.slice()}function Nt(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,s=`${n}${r}`;return s===""?"/":s}function Go(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function Jo(e,t){let n=e.split("/").filter(Boolean),r=t.split("/").filter(Boolean);n.pop();let s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s++;let o=n.length-s;return [...Array(o).fill(".."),...r.slice(s)].join("/")||"./"}function Yo(e,t,n,r,s,o,a){let i=e.input,l=e.output,y=e.status??200,g=s??Ko;return async b=>{let v=async T=>{if(o){let P=await o.handle({error:T,c:b,route:e,services:g,logger:a});if(P)return P}return Mr(b,T)},C=async()=>{let T,P;try{P=await Xo(b,t,e.method);}catch(S){throw new ft(S instanceof Error?S.message:String(S))}if(i){let S=i.safeParse(P);if(!S.success)throw new qe(S.error,t);T=S.data;}else T=P;let N=await e.handler({input:T,c:b,services:g,errorHandler:o,logger:a});if(n&&l&&!(N instanceof Response)){let S=l.safeParse(N);if(!S.success)throw new yt(S.error);return S.data}return N},R;if(r)try{R=await r({next:C,route:e,c:b,services:g,errorHandler:o,logger:a});}catch(T){let P=await v(T);if(P)return P;throw T}else try{R=await C();}catch(T){let P=await v(T);if(P)return P;throw T}return R instanceof Response?R:b.json(R,y)}}async function Xo(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(s){throw new Error(`Invalid JSON body: ${s instanceof Error?s.message:String(s)}`)}}case "query":return e.req.query();case "form":return await e.req.parseBody();case "param":return e.req.param();default:return {}}}function Kr(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:s,verbose:o=false,httpsOptions:a}=e,i=t==="/"?"":t.replace(/\/$/,""),l={};for(let[S,d]of Object.entries(n)){if(!d.repo)throw new Error(`[createCrudServer] Repository "${S}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let p=d.schema??d.repo.schema??null;if(!p)throw new Error(`[createCrudServer] Repository "${S}" has no Zod schema.`);let u,c,f,m;if(d.fieldsConfig){let w=d.fieldsConfig;u=[],c=[],f=[],m=[];for(let[O,$]of Object.entries(w))for(let I of $)I==="filterable"?u.push(O):I==="orderable"?c.push(O):I==="mutable"?f.push(O):I==="create"&&m.push(O);c.length===0&&(c=u),u.length===0&&(u=void 0),c&&c.length===0&&(c=void 0),f.length===0&&(f=void 0),m.length===0&&(m=void 0);}let x=(()=>{let w=d.repo._parentKeys;return w&&w.length>0?w:void 0})();if(x&&m)for(let w of x)m.includes(w)||m.push(w);let h={name:S,path:d.path,repo:d.repo,schema:p,systemKeys:d.repo._systemKeys??[d.documentKey??"docId"],documentKey:d.documentKey??"docId",pathKey:d.repo._pathKey??void 0,isGroup:!!d.repo._isGroup,parentKeys:x,createdKey:d.repo._createdKey??void 0,pageSize:d.pageSize??25,filterableFields:u,orderableFields:c,mutableFields:f,createFields:m,allowDelete:d.allowDelete??false,allowedIncludes:d.allowedIncludes,validate:d.validate,rules:d.rules};l[S]=h;}let y=e.indexesError??e.onIndexError,g=Ir(l,i,o,y),b=e.openapi,v=b&&typeof b=="object"?b:{},C=null;function R(){return C||(C=An(l,i,{...v,auth:v.auth??false})),C}let T=[];for(let S of Object.keys(l))T.push({api:"crud",method:"post",path:`/${S}/query`,source:"json",handler:g.handleQuery}),T.push({api:"crud",method:"get",path:`/${S}/:id`,source:"query",handler:g.handleGet}),T.push({api:"crud",method:"post",path:`/${S}`,source:"json",handler:g.handleCreate}),T.push({api:"crud",method:"put",path:`/${S}/:id`,source:"json",handler:d=>g.handleUpdate(d,false)}),T.push({api:"crud",method:"patch",path:`/${S}/:id`,source:"json",handler:d=>g.handleUpdate(d,true)}),T.push({api:"crud",method:"delete",path:`/${S}/:id`,source:"query",handler:g.handleDelete}),T.push({api:"crud",method:"post",path:`/${S}/batch`,source:"json",handler:g.handleBatch});let P=new Mt({...e,openapi:b!==false?{path:v.path??"/openapi.json",docsPath:v.docsPath??"/docs",info:{title:v.title??"CRUD API",version:v.version??"1.0.0"},docsAuth:v.docsAuth}:void 0,basePath:t,api:"crud",routes:T,middlewares:[async(S,d)=>{if(S.req.method==="OPTIONS")return S.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"});S.header("Access-Control-Allow-Origin","*"),S.header("Access-Control-Allow-Credentials","true"),await d();},...e.middlewares||[]]});if(b!==false&&(P.buildOpenApiSpec=R),s!==false){let{securityHeaders:S}=(It(),ss(Rr)),d=s===void 0?{csp:false}:s;P.hono.use("*",async(p,u)=>{let c=S(d);await new Promise(f=>{let m=p.req.raw;c(m,{setHeader:(h,w)=>p.header(h,w),removeHeader:h=>p.res.headers.delete(h)},()=>f());}),await u();});}let N=P.nodeHandler;return N.spec=R,a&&(N.httpsOptions=a),N}function Wr(e,t){if(!t.onRequest)return e;let n=e.httpsOptions??t.httpsOptions,r=n?t.onRequest(n,e):t.onRequest(e),s=e.spec;return typeof s=="function"&&(r.spec=s),r}function Vr(e,t,n){let r={},s=e?.rawMapping;for(let[o,a]of Object.entries(t)){if(!a)continue;if(!(s?o in s:!!e[o]))throw new Error(`[createServers.${n}] Unknown repo "${o}" \u2014 not present in the registry passed to createServers().`);let l=s?ht(s[o],()=>e[o]):e[o];r[o]={...a,repo:l};}return r}function ea(e,t={}){return {admin(n){let r=Vr(e,n.repos,"admin"),s=kr({...n,repos:r,httpsOptions:n.httpsOptions??t.httpsOptions});return Wr(s,t)},crud(n){let r=Vr(e,n.repos,"crud"),s=Kr({...n,repos:r,httpsOptions:n.httpsOptions??t.httpsOptions});return Wr(s,t)},sync(n){let r=t.triggerOptions||n.triggerOptions?{...t.triggerOptions,...n.triggerOptions}:void 0,s={...n,...r?{triggerOptions:r}:{}};return t.onRequest&&s.admin&&!s.admin.onRequest&&(s.admin={...s.admin,onRequest:t.onRequest,httpsOptions:s.admin.httpsOptions??t.httpsOptions}),Jn(e,s)},meilisearchAdapter(n){return ()=>new kt(n)},history(n){let r=t.triggerOptions||n.triggerOptions?{...t.triggerOptions,...n.triggerOptions}:void 0,s={...n,...r?{triggerOptions:r}:{}};return Pn(e,s)}}}It();export{yo as CSS,rt as ClientScript,wn as DEFAULT_HTML_CSP,ye as MiniRouter,xn as applyRules,lt as computeDeepDiff,Ar as createBeforeRules,Tr as createRules,ea as createServers,fn as renderDashboard,tt as renderField,ge as renderForm,ve as renderFormPage,yn as renderList,ct as renderPage,$t as securityHeaders,ie as zodToFields};//# sourceMappingURL=index.js.map
1166
+ </html>`}function Gr(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var $n=new AsyncLocalStorage;function Vr(){return async(e,t)=>{await $n.run({c:e},async()=>{await t();});}}var Vs=Object.freeze({}),Bt=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new Hono,this.mountedRoutes=Ys(t.routes,t.api),t.services&&this.app.use("*",Vr());let n=[...t.middlewares??[],...t.globalMiddlewares??[]];for(let r of n)this.app.use("*",r);this.mountRoutes(),this.mountOpenApi(),t.notFound&&this.app.notFound(t.notFound),t.onError&&this.app.onError(t.onError);}get hono(){return this.app}get nodeHandler(){return getRequestListener(this.app.fetch,{overrideGlobalObjects:false})}toFunction(t,n){let r=this.nodeHandler;return n?t(n,r):t(r)}buildOpenApiSpec(){if(this.cachedSpec)return this.cachedSpec;if(!this.options.openapi)throw new Error("[HonoServer] openapi config not set");return this.cachedSpec=Kr(this.mountedRoutes,this.options.basePath??"",this.options.openapi,Js(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=Ht(t,o.path),a=o.middlewares??[],i=o.source??(o.method==="get"?"query":"json"),c=ta(o,i,n,Qs(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),y=o.method.toUpperCase();this.app.on(y,[s],...a,c),r&&console.log(`[HonoServer] ${o.method.toUpperCase().padEnd(6)} ${s}`);}}mountOpenApi(){let t=this.options.openapi;if(!t)return;let n=t.path??"/openapi.json",r=t.docsPath===void 0?"/docs":t.docsPath,o=Ht(this.options.basePath??"",n),s=r===false?null:Ht(this.options.basePath??"",r),a;if(Gr(t.docsAuth)){let i=t.docsAuth;a=[i.middleware];let c=Xs(s??o);for(let y of i.routes)this.app.on(y.method,[Ht(c,y.name)],y.handler);}else a=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[o],...a,i=>i.json(this.buildOpenApiSpec())),s){let i=ea(s,o);this.app.on("GET",[s],...a,c=>c.html(Wr(i,t.info.title)));}}};function Qr(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function Qs(e){if(e)return Qr(e)?e.handler:e}function Js(e){return Qr(e)?e:void 0}function Ys(e,t){return t?e.filter(n=>Array.isArray(n.api)?n.api.includes(t):n.api===t):e.slice()}function Ht(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function Xs(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function ea(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 ta(e,t,n,r,o,s,a){let i=e.input,c=e.output,y=e.status??200,h=o??Vs;return async m=>{let x=async k=>{if(s){let E=await s.handle({error:k,c:m,route:e,services:h,logger:a});if(E)return E}return Br(m,k)},C=async()=>{let k,E;try{E=await na(m,t,e.method);}catch(S){throw new gt(S instanceof Error?S.message:String(S))}if(i){let S=i.safeParse(E);if(!S.success)throw new Ue(S.error,t);k=S.data;}else k=E;let N=await e.handler({input:k,c:m,services:h,errorHandler:s,logger:a});if(n&&c&&!(N instanceof Response)){let S=c.safeParse(N);if(!S.success)throw new bt(S.error);return S.data}return N},T;if(r)try{T=await r({next:C,route:e,c:m,services:h,errorHandler:s,logger:a});}catch(k){let E=await x(k);if(E)return E;throw k}else try{T=await C();}catch(k){let E=await x(k);if(E)return E;throw k}return T instanceof Response?T:m.json(T,y)}}async function na(e,t,n){switch(t){case "json":{if(n==="get")return e.req.query();let r=await e.req.text();if(!r)return {};try{return JSON.parse(r)}catch(o){throw new Error(`Invalid JSON body: ${o instanceof Error?o.message:String(o)}`)}}case "query":return e.req.query();case "form":return await e.req.parseBody();case "param":return e.req.param();default:return {}}}function Jr(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,verbose:s=false,httpsOptions:a}=e,i=t==="/"?"":t.replace(/\/$/,""),c={};for(let[S,l]of Object.entries(n)){if(!l.repo)throw new Error(`[createCrudServer] Repository "${S}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let p=l.schema??l.repo.schema??null;if(!p)throw new Error(`[createCrudServer] Repository "${S}" has no Zod schema.`);let u,d,f,g;if(l.fieldsConfig){let w=l.fieldsConfig;u=[],d=[],f=[],g=[];for(let[O,I]of Object.entries(w))for(let P of I)P==="filterable"?u.push(O):P==="orderable"?d.push(O):P==="mutable"?f.push(O):P==="create"&&g.push(O);d.length===0&&(d=u),u.length===0&&(u=void 0),d&&d.length===0&&(d=void 0),f.length===0&&(f=void 0),g.length===0&&(g=void 0);}let v=(()=>{let w=l.repo._parentKeys;return w&&w.length>0?w:void 0})();if(v&&g)for(let w of v)g.includes(w)||g.push(w);let b={name:S,path:l.path,repo:l.repo,schema:p,systemKeys:l.repo._systemKeys??[l.documentKey??"docId"],documentKey:l.documentKey??"docId",pathKey:l.repo._pathKey??void 0,isGroup:!!l.repo._isGroup,parentKeys:v,documentPathTemplate:l.repo._documentPathTemplate??void 0,createdKey:l.repo._createdKey??void 0,pageSize:l.pageSize??25,filterableFields:u,orderableFields:d,mutableFields:f,createFields:g,allowDelete:l.allowDelete??false,allowedIncludes:l.allowedIncludes,validate:l.validate,rules:l.rules};c[S]=b;}let y=e.indexesError??e.onIndexError,h=Nr(c,i,s,y),m=e.openapi,x=m&&typeof m=="object"?m:{},C=null;function T(){return C||(C=En(c,i,{...x,auth:x.auth??false})),C}let k=[];for(let S of Object.keys(c))k.push({api:"crud",method:"post",path:`/${S}/query`,source:"json",handler:h.handleQuery}),k.push({api:"crud",method:"get",path:`/${S}/:id`,source:"query",handler:h.handleGet}),k.push({api:"crud",method:"post",path:`/${S}`,source:"json",handler:h.handleCreate}),k.push({api:"crud",method:"put",path:`/${S}/:id`,source:"json",handler:l=>h.handleUpdate(l,false)}),k.push({api:"crud",method:"patch",path:`/${S}/:id`,source:"json",handler:l=>h.handleUpdate(l,true)}),k.push({api:"crud",method:"delete",path:`/${S}/:id`,source:"query",handler:h.handleDelete}),k.push({api:"crud",method:"post",path:`/${S}/batch`,source:"json",handler:h.handleBatch});let E=new Bt({...e,openapi:m!==false?{path:x.path??"/openapi.json",docsPath:x.docsPath??"/docs",info:{title:x.title??"CRUD API",version:x.version??"1.0.0"},docsAuth:x.docsAuth}:void 0,basePath:t,api:"crud",routes:k,middlewares:[async(S,l)=>{if(S.req.method==="OPTIONS")return S.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"});S.header("Access-Control-Allow-Origin","*"),S.header("Access-Control-Allow-Credentials","true"),await l();},...e.middlewares||[]]});if(m!==false&&(E.buildOpenApiSpec=T),o!==false){let{securityHeaders:S}=(Nt(),lo(Or)),l=o===void 0?{csp:false}:o;E.hono.use("*",async(p,u)=>{let d=S(l);await new Promise(f=>{let g=p.req.raw;d(g,{setHeader:(b,w)=>p.header(b,w),removeHeader:b=>p.res.headers.delete(b)},()=>f());}),await u();});}let N=E.nodeHandler;return N.spec=T,a&&(N.httpsOptions=a),N}function Yr(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 Xr(e,t,n){let r={},o=e?.rawMapping;for(let[s,a]of Object.entries(t)){if(!a)continue;if(!(o?s in o:!!e[s]))throw new Error(`[createServers.${n}] Unknown repo "${s}" \u2014 not present in the registry passed to createServers().`);let c=o?xt(o[s],()=>e[s]):e[s];r[s]={...a,repo:c};}return r}function ra(e,t={}){return {admin(n){let r=Xr(e,n.repos,"admin"),o=Er({...n,repos:r,httpsOptions:n.httpsOptions??t.httpsOptions});return Yr(o,t)},crud(n){let r=Xr(e,n.repos,"crud"),o=Jr({...n,repos:r,httpsOptions:n.httpsOptions??t.httpsOptions});return Yr(o,t)},sync(n){let r=t.triggerOptions||n.triggerOptions?{...t.triggerOptions,...n.triggerOptions}:void 0,o={...n,...r?{triggerOptions:r}:{}};return t.onRequest&&o.admin&&!o.admin.onRequest&&(o.admin={...o.admin,onRequest:t.onRequest,httpsOptions:o.admin.httpsOptions??t.httpsOptions}),nr(e,o)},meilisearchAdapter(n){return ()=>new Ot(n)},history(n){let r=t.triggerOptions||n.triggerOptions?{...t.triggerOptions,...n.triggerOptions}:void 0,o={...n,...r?{triggerOptions:r}:{}};return jn(e,o)}}}Nt();export{xs as CSS,it as ClientScript,Rn as DEFAULT_HTML_CSP,he as MiniRouter,Tn as applyRules,ft as computeDeepDiff,$r as createBeforeRules,Pr as createRules,ra as createServers,bn as renderDashboard,st as renderField,we as renderForm,Re as renderFormPage,wn as renderList,pt as renderPage,jt as securityHeaders,ce as zodToFields};//# sourceMappingURL=index.js.map
1167
1167
  //# sourceMappingURL=index.js.map