@lpdjs/firestore-repo-service 2.6.46 → 2.6.48

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.
@@ -1138,7 +1138,7 @@ function initColumnReorder(table) {
1138
1138
  });
1139
1139
  });
1140
1140
  }
1141
- `;function Qe(){return jsxRuntime.jsx("script",{dangerouslySetInnerHTML:{__html:Un}})}Lt();function ge(e){return "<!DOCTYPE html>"+server.renderToString(e)}var Do=["corporate","silk","dark"],_o=()=>jsxRuntime.jsxs("div",{class:"dropdown dropdown-end","data-frs-theme-switcher":true,children:[jsxRuntime.jsxs("button",{type:"button",tabIndex:0,class:"btn btn-sm btn-ghost text-neutral-content gap-1.5","aria-label":"Switch theme",children:[jsxRuntime.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",class:"size-4",children:[jsxRuntime.jsx("circle",{cx:"12",cy:"12",r:"4"}),jsxRuntime.jsx("path",{d:"M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"})]}),jsxRuntime.jsx("span",{class:"text-xs hidden sm:inline","data-frs-theme-current":true,children:"Theme"})]}),jsxRuntime.jsx("ul",{tabIndex:0,class:"dropdown-content menu menu-sm bg-base-100 text-base-content rounded-box z-50 mt-2 w-40 p-1 shadow-lg border border-base-300",children:Do.map(e=>jsxRuntime.jsx("li",{children:jsxRuntime.jsxs("button",{type:"button","data-frs-theme":e,class:"capitalize justify-between",children:[jsxRuntime.jsx("span",{children:e}),jsxRuntime.jsx("span",{class:"hidden text-primary","data-frs-theme-check":e,children:"\u2713"})]})},e))})]}),be=({opts:e,children:t})=>{let{title:n,breadcrumb:r,flash:o,basePath:s="/"}=e;return jsxRuntime.jsxs("html",{lang:"en","data-theme":"corporate",children:[jsxRuntime.jsxs("head",{children:[jsxRuntime.jsx("meta",{charset:"UTF-8"}),jsxRuntime.jsx("meta",{name:"viewport",content:"width=device-width, initial-scale=1"}),jsxRuntime.jsxs("title",{children:[n," \u2014 FRS Admin"]}),jsxRuntime.jsx("script",{dangerouslySetInnerHTML:{__html:"(function(){try{var t=localStorage.getItem('frs-admin-theme');if(t){document.documentElement.setAttribute('data-theme',t);}}catch(_){}})();"}}),jsxRuntime.jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/themes.css",rel:"stylesheet",type:"text/css"}),jsxRuntime.jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/daisyui.css",rel:"stylesheet",type:"text/css"}),jsxRuntime.jsx("script",{src:"https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"})]}),jsxRuntime.jsxs("body",{class:"bg-base-200/50 min-h-screen flex flex-col",children:[jsxRuntime.jsxs("div",{class:"navbar bg-neutral text-neutral-content shadow-sm sticky top-0 z-50 px-6",children:[jsxRuntime.jsx("div",{class:"flex-1",children:jsxRuntime.jsx("a",{href:s,class:"font-bold text-lg tracking-tight hover:opacity-80 transition-opacity",children:"FRS Admin"})}),jsxRuntime.jsx("div",{class:"flex-none",children:jsxRuntime.jsx(_o,{})})]}),jsxRuntime.jsxs("main",{class:"px-6 py-8 w-full flex-1",children:[r&&r.length>0&&jsxRuntime.jsx("div",{class:"text-sm breadcrumbs mb-4",children:jsxRuntime.jsx("ul",{children:r.map((a,l)=>a.href?jsxRuntime.jsx("li",{children:jsxRuntime.jsx("a",{href:a.href,children:a.label})},l):jsxRuntime.jsx("li",{class:"text-base-content/60",children:a.label},l))})}),jsxRuntime.jsx("h1",{class:"text-2xl font-bold mb-6",children:n}),o&&jsxRuntime.jsxs("div",{role:"alert",class:`alert ${o.type==="success"?"alert-success":o.type==="warning"?"alert-warning":"alert-error"} mb-6`,children:[jsxRuntime.jsx("span",{class:"flex-1",children:o.message}),o.action&&jsxRuntime.jsx("a",{href:o.action.href,...o.action.external?{target:"_blank",rel:"noopener noreferrer"}:{},class:"btn btn-sm btn-outline",children:o.action.label})]}),t]}),jsxRuntime.jsx(Zt,{basePath:s}),jsxRuntime.jsx(Qe,{})]})]})};function Ut(e,t){return ge(jsxRuntime.jsx(be,{opts:t,children:jsxRuntime.jsx("div",{dangerouslySetInnerHTML:{__html:e}})}))}function Kt(e,t){return ge(jsxRuntime.jsx(be,{opts:{title:"Repositories",basePath:t},children:e.length===0?jsxRuntime.jsxs("div",{class:"text-center py-20 text-base-content/50",children:[jsxRuntime.jsx("p",{class:"text-lg font-medium mb-1",children:"No repositories configured"}),jsxRuntime.jsx("p",{class:"text-sm",children:"Add a repository to your FRS config to get started."})]}):jsxRuntime.jsx("div",{class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:e.map(n=>jsxRuntime.jsx("a",{href:`${t}/${n.name}`,class:"card bg-base-100 border border-base-300 hover:shadow-md no-underline transition-shadow",children:jsxRuntime.jsxs("div",{class:"card-body p-5",children:[jsxRuntime.jsx("h2",{class:"card-title text-sm font-semibold",children:n.name}),jsxRuntime.jsx("p",{class:"text-xs text-base-content/50 font-mono",children:n.path})]})},n.name))})}))}var Qn=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],jo=[{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"}],Fo=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function Mo(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return jo;case "ZodBoolean":return Qn;case "ZodArray":return Fo;default:return Qn}}var we="__null__";function No(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="${we}"]');if(!o){o=document.createElement('option');o.value='${we}';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='${we}';i.readOnly=true;}i.style.opacity='0.55';}else{i.style.opacity='';if(i.tagName==='SELECT'){var o2=i.querySelector('option[value="${we}"][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!=='${we}')?i.dataset._prev:'';}}})(this)`}function Ho(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 Ye({inputId:e,active:t}){return jsxRuntime.jsxs("label",{class:"flex items-center gap-1 cursor-pointer select-none text-xs text-base-content/60 hover:text-base-content border border-base-300 rounded-md px-1.5 py-1 shrink-0 leading-none h-8",title:"Filter where field IS NULL",children:[jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",checked:t,onchange:No(e)}),jsxRuntime.jsx("span",{children:"\u2205"})]})}function zo({col:e,active:t}){let n=t?.value??"",r=n===we,o=`fv_input_${e.name.replace(/\./g,"__")}`,s=t?.op,a=s==="in"||s==="not-in";if(e.enumValues&&e.enumValues.length>0){if(a){let l=new Set(n.split(",").map(y=>y.trim()).filter(Boolean)),c=`eg_${e.name.replace(/\./g,"__")}`;return jsxRuntime.jsxs("div",{class:"flex flex-wrap items-center gap-1 w-full",children:[jsxRuntime.jsx("input",{type:"hidden",id:o,name:`fv_${e.name}`,value:n}),e.enumValues.map(y=>jsxRuntime.jsxs("label",{class:"flex items-center gap-1 text-xs border border-base-300 rounded px-2 cursor-pointer hover:bg-base-200",children:[jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",value:y,checked:l.has(y),"data-enum-group":c,onchange:Ho(o,c)}),jsxRuntime.jsx("span",{children:y})]},y))]})}return jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsxRuntime.jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),e.enumValues.map(l=>jsxRuntime.jsx("option",{value:l,selected:n===l,children:l},l)),e.nullable&&jsxRuntime.jsx("option",{value:we,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsxRuntime.jsx(Ye,{inputId:o,active:r})]})}if(e.zodType==="ZodBoolean")return jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsxRuntime.jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),jsxRuntime.jsx("option",{value:"true",selected:n==="true",children:"true"}),jsxRuntime.jsx("option",{value:"false",selected:n==="false",children:"false"}),e.nullable&&jsxRuntime.jsx("option",{value:we,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsxRuntime.jsx(Ye,{inputId:o,active:r})]});if(e.zodType==="ZodArray"){let l=t?.op==="array-contains-any";return jsxRuntime.jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:l?"val1, val2, \u2026":"value",class:"input input-sm input-bordered w-full"})}return e.zodType==="ZodNumber"||e.zodType==="ZodBigInt"?jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsx("input",{id:o,type:r?"text":"number",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0,"data-_type":r?"number":void 0}),e.nullable&&jsxRuntime.jsx(Ye,{inputId:o,active:r})]}):e.zodType==="ZodDate"?jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsx("input",{id:o,type:r?"text":"datetime-local",name:`fv_${e.name}`,value:n,class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0,"data-_type":r?"datetime-local":void 0}),e.nullable&&jsxRuntime.jsx(Ye,{inputId:o,active:r})]}):jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0}),e.nullable&&jsxRuntime.jsx(Ye,{inputId:o,active:r})]})}function Vt({action:e,columnMeta:t,activeFilters:n,isGroup:r}){let o=Object.fromEntries(n.map(c=>[c.field,c])),s=n.length>0,a=n.length>=2||r&&s,l=t.filter(c=>c.zodType!=="ZodObject"&&c.zodType!=="ZodRecord");return jsxRuntime.jsxs("details",{class:"collapse collapse-arrow bg-base-100 border border-base-300 rounded-box mb-6 shadow-sm",open:s?true:void 0,children:[jsxRuntime.jsxs("summary",{class:"collapse-title text-sm font-medium py-2 min-h-0",children:["Filters",s&&jsxRuntime.jsxs("span",{class:"badge badge-primary badge-sm ml-2",children:[n.length," active"]})]}),jsxRuntime.jsx("div",{class:"collapse-content pb-4 pt-2",children:jsxRuntime.jsxs("form",{method:"get",action:e,children:[jsxRuntime.jsx("div",{class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:l.map(c=>{let y=Mo(c.zodType),v=o[c.name],x=v?.op??y[0].value;return jsxRuntime.jsxs("div",{class:"flex flex-col gap-1.5",children:[jsxRuntime.jsx("label",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:c.name}),jsxRuntime.jsxs("div",{class:"flex gap-1.5",children:[y.length>1?jsxRuntime.jsx("select",{name:`fo_${c.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:y.map(T=>jsxRuntime.jsx("option",{value:T.value,selected:T.value===x,children:T.label},T.value))}):jsxRuntime.jsx("input",{type:"hidden",name:`fo_${c.name}`,value:y[0].value}),jsxRuntime.jsx(zo,{col:c,active:v})]})]},c.name)})}),jsxRuntime.jsxs("div",{class:"flex flex-wrap gap-2 mt-4 pt-3 border-t border-base-200 items-center",children:[jsxRuntime.jsx("button",{type:"submit",class:"btn btn-sm btn-primary",children:"Apply"}),s&&jsxRuntime.jsx("a",{href:e,class:"btn btn-sm btn-ghost",children:"Clear"}),a&&jsxRuntime.jsxs("span",{class:"text-xs text-warning ml-auto flex items-center gap-1",children:[jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-4 w-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:jsxRuntime.jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),r?"Collection group queries require a composite index":"Multiple filters may require a composite index"]})]})]})})]})}function Wt(e,t,n,r,o,s){let a=n==="create"?`Create ${e}`:`Edit ${e} / ${r??""}`,l=n==="create"?[{label:"Repositories",href:o},{label:e,href:`${o}/${e}`},{label:"New document"}]:[{label:"Repositories",href:o},{label:e,href:`${o}/${e}`},{label:`Edit ${r??""}`}];return ge(jsxRuntime.jsx(be,{opts:{title:a,breadcrumb:l,basePath:o,flash:s},children:jsxRuntime.jsx("div",{class:"card bg-base-100 border border-base-300",children:jsxRuntime.jsx("div",{class:"card-body p-6",children:jsxRuntime.jsx("div",{dangerouslySetInnerHTML:{__html:t}})})})}))}pt();qt();function Qt(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 Gn(e,t,n,r,o){let s=Qt(e,r,o);return s.set("cursor",t),s.set("dir",n),`?${s.toString()}`}function Bo(e,t,n,r){let o=Qt(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 qo(e,t,n){return `?${Qt(t,n,e).toString()}`}function Gt(e,t,n,r,o,s,a=[],l=[],c=false,y=[],v,x,T,R,b,k,h,g=false){let u=`${r}/${e}`,f=`${u}/create`,i={};if(h)for(let S of n)i[S]=Ge(Je(h,S));let w=(k??[]).filter(S=>true),d=w.length>0,m=c,p=m||d,O=w.map(S=>{let P=Je(h,S),E=Ge(P),I=a.find(C=>C.name===S);return {name:S,type:E,enumValues:I?.enumValues??null,nullable:I?.nullable??false}}),A=[];return h&&(A=se(h).filter(P=>w.includes(P.name))),ge(jsxRuntime.jsxs(be,{opts:{title:e,breadcrumb:[{label:"Repositories",href:r},{label:e}],basePath:r,flash:s},children:[a.length>0&&jsxRuntime.jsx(Vt,{action:u,columnMeta:a,activeFilters:l,isGroup:R}),T&&jsxRuntime.jsxs("div",{role:"alert",class:`alert ${T.type==="index"?"alert-warning":"alert-error"} mb-6 shadow-sm`,children:[jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6 shrink-0 stroke-current",fill:"none",viewBox:"0 0 24 24",children:T.type==="index"?jsxRuntime.jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"}):jsxRuntime.jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"})}),jsxRuntime.jsxs("div",{class:"flex-1",children:[jsxRuntime.jsx("h3",{class:"font-bold",children:T.type==="index"?"Composite index required":"Query failed"}),jsxRuntime.jsx("div",{class:"text-sm",children:T.message})]}),T.indexUrl&&jsxRuntime.jsx("a",{href:T.indexUrl,target:"_blank",rel:"noopener noreferrer",class:"btn btn-sm btn-outline",children:"Create Index \u2192"})]}),jsxRuntime.jsxs("div",{class:"flex flex-wrap justify-between items-center mb-4 gap-3","data-frs-toolbar":true,children:[jsxRuntime.jsxs("div",{class:"flex items-center gap-3",children:[jsxRuntime.jsxs("span",{class:"text-sm text-base-content/60",children:[t.length,typeof b=="number"&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[" ","of"," ",jsxRuntime.jsx("span",{class:"font-semibold text-base-content/80",children:b})]})," ","document",(typeof b=="number"?b:t.length)!==1&&"s"]}),jsxRuntime.jsxs("div",{class:"flex items-center gap-1.5 text-sm text-base-content/60",children:[jsxRuntime.jsx("span",{children:"Rows"}),jsxRuntime.jsx("div",{class:"join",children:[10,25,50,100].map(S=>jsxRuntime.jsx("a",{href:qo(S,l,v),class:`join-item btn btn-xs ${x===S?"btn-active btn-primary":"btn-outline"}`,children:S},S))})]})]}),jsxRuntime.jsxs("div",{class:"flex gap-2",children:[jsxRuntime.jsx("form",{method:"post",action:`${u}/_bulk/backfill`,onsubmit:"return confirm('Backfill entire repository? This will scan all documents and fill missing system keys.')",children:jsxRuntime.jsx("button",{type:"submit",class:"btn btn-outline btn-sm",children:"Backfill"})}),jsxRuntime.jsx("a",{href:f,class:"btn btn-primary btn-sm",children:"+ New"})]})]}),p&&jsxRuntime.jsxs("div",{class:"hidden mb-3 alert alert-info py-2 px-3","data-frs-bulk-bar":true,"data-frs-repo":e,"data-frs-total":typeof b=="number"?String(b):"","data-frs-page-size":String(x??t.length),"data-frs-allow-delete":m?"1":"0","data-frs-allow-update":d?"1":"0","data-frs-fields":JSON.stringify(O),"data-frs-filters":JSON.stringify(l),children:[jsxRuntime.jsxs("div",{class:"flex-1 text-sm",children:[jsxRuntime.jsx("span",{"data-frs-bulk-summary":true,children:"0 selected"}),typeof b=="number"&&b>t.length&&jsxRuntime.jsxs("button",{type:"button",class:"ml-3 link text-sm hidden","data-frs-bulk-select-all":true,children:["Select all ",b," matching documents"]}),jsxRuntime.jsxs("span",{class:"hidden ml-3 italic","data-frs-bulk-all-active":true,children:["All ",b??"?"," matching documents are selected."," ",jsxRuntime.jsx("button",{type:"button",class:"link","data-frs-bulk-clear":true,children:"Clear selection"})]})]}),jsxRuntime.jsxs("div",{class:"flex gap-2",children:[d&&jsxRuntime.jsx("button",{type:"button",class:"btn btn-sm btn-outline","data-frs-bulk-action":"update",children:"Update field\u2026"}),m&&jsxRuntime.jsx("button",{type:"button",class:"btn btn-sm btn-error btn-outline","data-frs-bulk-action":"delete",children:"Delete"})]})]}),jsxRuntime.jsx("div",{class:"overflow-x-auto rounded-box border border-base-300 bg-base-100","data-frs-table-wrap":true,children:jsxRuntime.jsxs("table",{class:"table table-sm w-full","data-frs-table":true,"data-frs-repo":e,"data-frs-colcount":n.length,children:[jsxRuntime.jsx("thead",{children:jsxRuntime.jsxs("tr",{class:"bg-base-200/50",children:[p&&jsxRuntime.jsx("th",{class:"w-8",children:jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-page":true,"aria-label":"Select all on this page"})}),[...n].map((S,P)=>{let E=v?.field===S,I=E?v.dir==="asc"?" \u25B2":" \u25BC":"";return jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:jsxRuntime.jsxs("a",{href:Bo(S,v,l,x),class:`hover:text-base-content inline-flex items-center gap-0.5${E?" text-primary font-bold":""}`,children:[S,I]})},P)}),y.map((S,P)=>jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:S.column},`rel-${P}`)),jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide text-right",children:"Actions"})]})}),jsxRuntime.jsx("tbody",{children:t.length===0?jsxRuntime.jsx("tr",{children:jsxRuntime.jsx("td",{colspan:n.length+y.length+1+(p?1:0),class:"text-center py-16 text-base-content/40",children:"No documents found"})}):t.map((S,P)=>{let E=String(S.docId??S.id??""),I=`${r}/${e}/${encodeURIComponent(E)}/edit`,C=`${r}/${e}/${encodeURIComponent(E)}/delete`;return jsxRuntime.jsxs("tr",{class:"hover","data-frs-row-id":E,children:[p&&jsxRuntime.jsx("td",{class:"align-middle py-2",children:jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-row":true,value:E,"aria-label":`Select ${E}`})}),n.map(($,j)=>{let N=S[$],F=i[$],_=F?Xe(F,N):null;return jsxRuntime.jsx("td",{class:"align-top py-2",children:jsxRuntime.jsx(Pe,{val:N,mismatch:_})},j)}),y.map(($,j)=>{let N=S[$.key];if(N==null||N==="")return jsxRuntime.jsx("td",{class:"py-2"},`rel-${j}`);let F=$.type==="one"?`${r}/${$.targetRepo}/${encodeURIComponent(String(N))}/edit`:`${r}/${$.targetRepo}?fv_${$.targetKey}=${encodeURIComponent(String(N))}`;return jsxRuntime.jsx("td",{class:"align-middle py-2",children:jsxRuntime.jsx("a",{href:F,class:"btn btn-xs btn-ghost btn-outline","data-frs-relation":true,"data-frs-rel-type":$.type,"data-frs-rel-repo":$.targetRepo,"data-frs-rel-fk":$.targetKey,"data-frs-rel-val":String(N),"data-frs-rel-label":$.column,children:$.column})},`rel-${j}`)}),jsxRuntime.jsx("td",{class:"align-middle text-right whitespace-nowrap py-2",children:jsxRuntime.jsxs("div",{class:"flex gap-1 justify-end",children:[jsxRuntime.jsx("a",{href:I,class:"btn btn-xs btn-outline",children:"Edit"}),g&&jsxRuntime.jsx("a",{href:`${r}/${e}/${encodeURIComponent(E)}/history`,class:"btn btn-xs btn-outline",title:"View change history",children:"History"}),c&&jsxRuntime.jsx("form",{method:"post",action:C,onsubmit:"return confirm('Delete this document?')",children:jsxRuntime.jsx("button",{type:"submit",class:"btn btn-xs btn-error btn-outline",children:"Delete"})})]})})]},P)})})]})}),(o.hasPrev||o.hasNext)&&jsxRuntime.jsxs("div",{class:"flex flex-col items-center mt-6 gap-2",children:[jsxRuntime.jsxs("div",{class:"flex justify-center items-center gap-2",children:[o.hasPrev?jsxRuntime.jsx("a",{href:Gn(l,o.prevCursor,"prev",v,x),class:"btn btn-sm btn-outline",children:"\u2190 Previous"}):jsxRuntime.jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"\u2190 Previous"}),o.hasNext?jsxRuntime.jsx("a",{href:Gn(l,o.nextCursor,"next",v,x),class:"btn btn-sm btn-outline",children:"Next \u2192"}):jsxRuntime.jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"Next \u2192"})]}),typeof b=="number"&&jsxRuntime.jsxs("div",{class:"text-xs text-base-content/50",children:[b," total document",b!==1?"s":"",l.length>0?" matching filters":""]})]}),p&&d&&jsxRuntime.jsxs("dialog",{id:"frs-bulk-update-modal",class:"modal",children:[jsxRuntime.jsxs("div",{class:"modal-box",children:[jsxRuntime.jsx("h3",{class:"font-bold text-lg mb-3",children:"Bulk update field"}),jsxRuntime.jsx("p",{class:"text-sm text-base-content/60 mb-4","data-frs-bulk-update-summary":true,children:"Update one field on the selected documents."}),jsxRuntime.jsxs("form",{method:"dialog","data-frs-bulk-update-form":true,"data-frs-form":true,children:[jsxRuntime.jsxs("label",{class:"form-control w-full mb-3",children:[jsxRuntime.jsx("div",{class:"label",children:jsxRuntime.jsx("span",{class:"label-text text-xs uppercase tracking-wide",children:"Field"})}),jsxRuntime.jsxs("select",{class:"select select-bordered select-sm w-full",name:"field",required:true,"data-frs-bulk-field-select":true,children:[jsxRuntime.jsx("option",{value:"",children:"\u2014 Select a field \u2014"}),w.map(S=>jsxRuntime.jsx("option",{value:S,children:S},S))]})]}),jsxRuntime.jsx("div",{class:"mb-4","data-frs-bulk-value-container":true}),jsxRuntime.jsxs("div",{class:"modal-action",children:[jsxRuntime.jsx("button",{type:"button",class:"btn btn-sm btn-ghost","data-frs-bulk-update-cancel":true,children:"Cancel"}),jsxRuntime.jsx("button",{type:"submit",class:"btn btn-sm btn-primary","data-frs-bulk-update-submit":true,children:"Apply"})]})]})]}),jsxRuntime.jsx("form",{method:"dialog",class:"modal-backdrop",children:jsxRuntime.jsx("button",{children:"close"})})]}),jsxRuntime.jsx("div",{class:"hidden","data-frs-bulk-templates":true,children:A.map(S=>jsxRuntime.jsx("div",{"data-frs-bulk-template-for":S.name,dangerouslySetInnerHTML:{__html:Ve(S)}},S.name))})]}))}var Lo="";function et(e,t){return Ut(e,t)}function Jt(e,t){return Kt(e,t)}function Xt(e,t,n,r,o,s,a,l,c,y,v,x,T,R,b,k,h,g){return Gt(e,t,n,r,o,s,a,l,c,y,v,x,T,R,b,k,h,g)}function ve(e,t,n,r,o,s){return Wt(e,t,n,r,o,s)}var Yt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Vo(){let e="";for(;e.length<20;){let t=crypto.randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let r=t[n];r>=Yt.length*4||(e+=Yt.charAt(r%Yt.length));}}return e}async function Jn(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 yt(e,t){if(!t)return;let n=e[t];if(typeof n!="string"||!n)return;let r=n.split("/").filter(Boolean),o=[];for(let s=1;s<r.length;s+=2)o.push(r[s]);return o.length>0?o:void 0}async function $e(e,t){let n=e.documentKey??"docId",r=`by${n.charAt(0).toUpperCase()}${n.slice(1)}`;if(typeof e.repo.get[r]=="function")try{let s=await e.repo.get[r](t);if(s)return s}catch{}return (await e.repo.query.by({where:[[n,"==",t]],limit:1}))[0]??null}function en(e,t,n){let r=e.documentKey??"docId",o=We(n,{ref:e.repo.ref,path:e.path,isGroup:!!e.isGroup,filters:[{field:r,op:"==",value:t}]});return o.type==="index"?{type:"warning",message:"Loading this document requires a composite index that does not exist yet.",...o.indexUrl?{action:{href:o.indexUrl,label:"Create Index \u2192",external:true}}:{}}:{type:"error",message:o.message}}function z(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function mt(e,t){e.status(302).set("Location",t).send("");}function ht(e,t){let n=t.shape,r={};for(let[o,s]of Object.entries(n)){let a=nn(s),l=Z(a),c=l==="ZodObject",y=a,v=false;if(l==="ZodUnion"){let R=Le(a);R.some(k=>Z(k)==="ZodDate")&&(v=true);let b=R.find(k=>{if(Z(k)==="ZodObject"){let h=ee(k);return "latitude"in h&&"longitude"in h}return false});b&&(c=true,y=b);}if(e[o+"__isnull"]==="1"){r[o]=null;continue}if(c){let R={},b=false;for(let[g,u]of Object.entries(e))g.startsWith(`${o}.`)&&(R[g.slice(o.length+1)]=u,b=true);if(b){r[o]=ht(R,y);continue}let k=e[o],h=Array.isArray(k)?k[k.length-1]:k;if(h)try{r[o]=JSON.parse(h);}catch{r[o]=h;}continue}let x=e[o],T=Array.isArray(x)?x[x.length-1]:x;if(T===void 0||T===""){l==="ZodBoolean"&&(r[o]=false);continue}if(v){r[o]=new Date(T);continue}switch(l){case "ZodBoolean":T==="__null__"?r[o]=null:r[o]=T==="true"||T==="on"||T==="1";break;case "ZodNumber":case "ZodBigInt":r[o]=Number(T);break;case "ZodDate":r[o]=new Date(T);break;case "ZodArray":try{r[o]=JSON.parse(T);}catch{r[o]=T;}break;default:if(T.startsWith("{")||T.startsWith("["))try{r[o]=JSON.parse(T);break}catch{}r[o]=T;}}return r}function Xn(e){let t=null;if(e instanceof Date)t=e;else if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")t=e.toDate();else if(typeof e=="object"&&e!==null&&"_seconds"in e&&"_nanoseconds"in e)t=new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));else if(typeof e=="string"||typeof e=="number"){let r=new Date(e);isNaN(r.getTime())||(t=r);}if(!t||isNaN(t.getTime()))return null;let n=r=>String(r).padStart(2,"0");return `${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function er(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=Y(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=ze(t);if(!r)return n;t=r;}else return n}}function nn(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=Y(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=ze(t);if(!r)return t;t=r;}else return t}}function tr(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable")return true;if(n==="ZodDefault"){t=Y(t);continue}return false}}function nr(e){let t=nn(e),n=Z(t);if(n==="ZodEnum"){let r=Be(t);return r.length>0?r:void 0}if(n==="ZodNativeEnum"){let r=qe(t),o=Object.values(r).filter(s=>typeof s=="string");return o.length>0?o:void 0}if(n==="ZodLiteral"){let r=Ze(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 l=nn(t.shape[o]),c=Z(l),y=c==="ZodObject",v=l,x=false;if(c==="ZodUnion"){let T=Le(l);T.some(b=>Z(b)==="ZodDate")&&(x=true);let R=T.find(b=>{if(Z(b)==="ZodObject"){let k=ee(b);return "latitude"in k&&"longitude"in k}return false});R&&(y=true,v=R);}if(y&&typeof a=="object"&&a!==null&&!Array.isArray(a)&&!("_seconds"in a)&&typeof a.toDate!="function"){let T=rr(a,v,s);Object.assign(r,T);}else if(c==="ZodDate"||x){let T=Xn(a);T!==null&&(r[s]=T);}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)&&("_seconds"in a||typeof a.toDate=="function")){let T=Xn(a);r[s]=T??JSON.stringify(a,null,2);}else typeof a=="object"?r[s]=JSON.stringify(a,null,2):r[s]=String(a);}return r}function tn(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?tn(n.nested,t):void 0}))}function Wo(e,t){let n=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),r=[];for(let[o,s]of Object.entries(e)){if(!o.startsWith("fv_"))continue;let a=o.slice(3);if(!t.has(a))continue;let l=(s??"").trim();if(!l)continue;let c=e[`fo_${a}`]??"==",y=n.has(c)?c:"==";r.push({field:a,op:y,value:l});}return r}function Yn(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 or(e,t,n=""){let r=[];for(let o of e){let s=n?`${n}.${o}`:o,a=t.shape[o];if(!a){r.push({name:s,zodType:"ZodString"});continue}let l=er(a);if(l==="ZodObject"){let c=a;for(;;){let v=Z(c);if(v==="ZodOptional"||v==="ZodNullable"||v==="ZodDefault")c=Y(c);else break}let y=ee(c);r.push(...or(Object.keys(y),c,s));}else r.push({name:s,zodType:l,nullable:tr(a),enumValues:nr(a)});}return r}function Qo(e,t){let n=t.split("."),r=e;for(let o of n){for(;;){let a=Z(r);if(a==="ZodOptional"||a==="ZodNullable"||a==="ZodDefault")r=Y(r);else break}let s=ee(r);if(!(o in s))return null;r=s[o];}return r}function ke(e,t){if(!t||t.length===0)return e;let n=[],r=new Map;for(let s of t){let a=s.indexOf(".");if(a===-1)n.push(s);else {let l=s.slice(0,a),c=s.slice(a+1);r.has(l)||r.set(l,[]),r.get(l).push(c);}}let o={};for(let s of n)s in e.shape&&(o[s]=e.shape[s]);for(let[s,a]of r){if(!(s in e.shape))continue;let l=e.shape[s];for(;;){let c=Z(l);if(c==="ZodOptional"||c==="ZodNullable"||c==="ZodDefault")l=Y(l);else break}if(Z(l)!=="ZodObject"){o[s]=e.shape[s];continue}o[s]=ke(l,a);}return zod.z.object(o)}function ce(e,t,n){return ie(e,t,n)}function sr(e,t,n){let r=(f,i)=>{let w=ce(f,t,n),d=Object.values(e).map(m=>({name:m.name,path:m.path}));z(i,Jt(d,w));},o=async(f,i)=>{let w=f.params.repoName;if(!w){z(i,"Bad request",400);return}let d=e[w];if(!d){z(i,"Repository not found",404);return}let m=d.pageSize??25,p=f.query??{},O=p.cursor,A=p.dir==="prev"?"prev":"next",S=p.ob??"",P=p.od==="desc"?"desc":"asc",E=S?{field:S,dir:P}:void 0,I=parseInt(p.ps??""),C=Number.isFinite(I)&&I>0?Math.min(I,200):m,$=d.listColumns??Object.keys(d.schema.shape),j=d.documentKey??"docId",N=[j,...$.filter(re=>re!==j)];E&&(new Set([j,...$]).has(E.field)||(E=void 0));let F=d.filterableFields?(()=>{let re=[];for(let de of d.filterableFields)(de.includes(".")||$.includes(de))&&re.push(de);return re})():$,_=(()=>{let re=[];for(let de of F)if(de.includes(".")){let Ce=Qo(d.schema,de);re.push({name:de,zodType:Ce?er(Ce):"ZodString",nullable:Ce?tr(Ce):false,enumValues:Ce?nr(Ce):void 0});}else re.push(...or([de],d.schema));return re})(),V=new Set(_.map(re=>re.name)),K=Wo(p,V),G=Yn(K),je;O&&(je=await Jn(d,O));let[J,st]=await Promise.all([d.repo.query.paginate({pageSize:C,cursor:je,direction:A,...G.length>0?{where:G}:{},...E?{orderBy:[{field:E.field,direction:E.dir}]}:{}}).catch(re=>({queryError:We(re,{ref:d.repo.ref,path:d.path,isGroup:!!d.isGroup,filters:K,sort:E})})),d.repo.aggregate.count(G.length>0?{where:G}:{}).catch(()=>{})]),Ae="queryError"in J,Pr=Ae?[]:J.data,$r=Ae?"":J.nextCursor?.ref?.path??J.nextCursor?.id??"",Ir=Ae?"":J.prevCursor?.ref?.path??J.prevCursor?.id??"",Dr=Ae?J.queryError:void 0,_r=ce(f,t,n),Fe,at=p.flash;at==="created"?Fe={type:"success",message:"Document created successfully."}:at==="updated"?Fe={type:"success",message:"Document updated successfully."}:at==="deleted"?Fe={type:"success",message:"Document deleted successfully."}:at==="backfilled"&&(Fe={type:"success",message:"Repository backfilled successfully."}),z(i,Xt(d.name,Pr,N,_r,{hasPrev:Ae?false:J.hasPrevPage,hasNext:Ae?false:J.hasNextPage,prevCursor:Ir,nextCursor:$r},Fe,_,K,d.allowDelete??false,d.relationalMeta,E,C,Dr,d.isGroup,st,d.mutableFields,d.schema,d.historyEnabled));},s=(f,i)=>{let w=f.params.repoName;if(!w){z(i,"Bad request",400);return}let d=e[w];if(!d){z(i,"Repository not found",404);return}let m=ce(f,t,n),p=ke(d.schema,d.createFields),O=se(p),A=`${m}/${d.name}/create`,S=he(O,A,"POST","Create document");z(i,ve(d.name,S,"create",null,m));},a=async(f,i)=>{let w=f.params.repoName;if(!w){z(i,"Bad request",400);return}let d=e[w];if(!d){z(i,"Repository not found",404);return}let m=ce(f,t,n),p=f.body??{},O=ht(p,d.schema),A=ke(d.schema,d.createFields),S=A.safeParse(O);if(!S.success){let P=se(A),E=`${m}/${d.name}/create`,I=he(P,E,"POST","Create document"),C=S.error.issues.map($=>`${$.path.join(".")}: ${$.message}`).join(", ");z(i,ve(d.name,I,"create",null,m,{type:"error",message:`Validation error: ${C}`}),422);return}try{if(d.isGroup&&d.parentKeys&&d.parentKeys.length>0){let P={...S.data};d.createdKey&&(P[d.createdKey]=new Date);let E=d.parentKeys.filter(j=>!P[j]);if(E.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${E.join(", ")}`);let I=d.parentKeys.map(j=>P[j]),C=d.documentKey??"docId",$=P[C]||Vo();await d.repo.set(...I,$,P);}else await d.repo.create(S.data);mt(i,`${m}/${d.name}?flash=created`);}catch(P){let E=ke(d.schema,d.createFields),I=se(E),C=`${m}/${d.name}/create`,$=he(I,C,"POST","Create document");z(i,ve(d.name,$,"create",null,m,{type:"error",message:`Save error: ${P.message}`}),500);}},l=async(f,i)=>{let w=f.params.repoName,d=f.params.id;if(!w||!d){z(i,"Bad request",400);return}let m=e[w];if(!m){z(i,"Repository not found",404);return}let p=ce(f,t,n),O=null;try{O=await $e(m,d);}catch(C){let $=en(m,d,C),j=Se(C)?424:500;z(i,et("",{title:`Edit ${m.name} / ${d}`,basePath:p,breadcrumb:[{label:"Repositories",href:p},{label:m.name,href:`${p}/${m.name}`},{label:`Edit ${d}`}],flash:$}),j);return}if(!O){z(i,"Document not found",404);return}let A=rr(O,m.schema),S=ke(m.schema,m.mutableFields),P=tn(se(S),A),E=`${p}/${m.name}/${encodeURIComponent(d)}/edit`,I=he(P,E,"POST","Save changes");z(i,ve(m.name,I,"edit",d,p));},c=async(f,i)=>{let w=f.params.repoName,d=f.params.id;if(!w||!d){z(i,"Bad request",400);return}let m=e[w];if(!m){z(i,"Repository not found",404);return}let p=ce(f,t,n),O=f.body??{},A=ht(O,m.schema),S=ke(m.schema,m.mutableFields),E=S.partial().safeParse(A);if(!E.success){let I=Object.fromEntries(Object.entries(O).map(([F,_])=>[F,Array.isArray(_)?_.join(","):_??""])),C=tn(se(S),I),$=`${p}/${m.name}/${encodeURIComponent(d)}/edit`,j=he(C,$,"POST","Save changes"),N=E.error.issues.map(F=>`${F.path.join(".")}: ${F.message}`).join(", ");z(i,ve(m.name,j,"edit",d,p,{type:"error",message:`Validation error: ${N}`}),422);return}try{let I=await $e(m,d),C=(I&&yt(I,m.pathKey))??[d];await m.repo.update(...C,E.data),mt(i,`${p}/${m.name}?flash=updated`);}catch(I){let C=ke(m.schema,m.mutableFields),$=se(C),j=`${p}/${m.name}/${encodeURIComponent(d)}/edit`,N=he($,j,"POST","Save changes"),F=Se(I)?en(m,d,I):{type:"error",message:`Save error: ${I.message}`},_=Se(I)?424:500;z(i,ve(m.name,N,"edit",d,p,F),_);}},y=async(f,i)=>{let w=f.params.repoName,d=f.params.id;if(!w||!d){z(i,"Bad request",400);return}let m=e[w];if(!m){z(i,"Repository not found",404);return}if(!m.allowDelete){z(i,"Delete is not allowed for this repository",403);return}let p=ce(f,t,n);try{let O=await $e(m,d),A=(O&&yt(O,m.pathKey))??[d];await m.repo.delete(...A),mt(i,`${p}/${m.name}?flash=deleted`);}catch(O){let A=Se(O)?en(m,d,O):{type:"error",message:`Delete error: ${O.message}`},S=Se(O)?424:500;z(i,et("",{title:`Delete ${m.name} / ${d}`,basePath:p,breadcrumb:[{label:"Repositories",href:p},{label:m.name,href:`${p}/${m.name}`},{label:`Delete ${d}`}],flash:A}),S);}},v=async(f,i)=>{let w=f.params.repoName;if(!w){z(i,"Bad request",400);return}let d=e[w];if(!d){z(i,"Repository not found",404);return}let m=ce(f,t,n),p=f.query,O=p?.type==="many"?"many":"one",A=Math.max(1,Math.min(100,Number(p?.ps??25)||25)),S=d.listColumns??Object.keys(ee(d.schema)),{PanelOne:P,PanelMany:E}=await Promise.resolve().then(()=>(Lt(),Vn)),{renderToString:I}=await import('hono/jsx/dom/server');if(O==="one"){let _=String(p?.id??"");if(!_){z(i,"<div class='p-6 text-error'>Missing id parameter.</div>",400);return}try{let V=await $e(d,_),K=I(P({doc:V,repoName:d.name,basePath:m,schema:d.schema,columns:S}));z(i,K);}catch(V){z(i,`<div class='p-6 text-error text-sm'>Error: ${V.message}</div>`,500);}return}let C=String(p?.fk??""),$=String(p?.fv??"");if(!C||!$){z(i,"<div class='p-6 text-error'>Missing fk/fv parameters.</div>",400);return}let j=p?.cursor??"",N=p?.dir==="prev"?"prev":"next",F;j&&(F=await Jn(d,j));try{let _=await d.repo.query.paginate({pageSize:A,cursor:F,direction:N,where:[[C,"==",Go($)]]}),V=I(E({docs:_.data,repoName:d.name,basePath:m,fk:C,fv:$,columns:S,schema:d.schema,pagination:{hasPrev:_.hasPrevPage,hasNext:_.hasNextPage,prevCursor:_.prevCursor?.ref?.path??_.prevCursor?.id??"",nextCursor:_.nextCursor?.ref?.path??_.nextCursor?.id??"",pageSize:A}}));z(i,V);}catch(_){z(i,`<div class='p-6 text-error text-sm'>Error: ${_.message}</div>`,500);}},x=async(f,i)=>{let w=f.params.repoName;if(!w){z(i,"Bad request",400);return}let d=e[w];if(!d){z(i,"Repository not found",404);return}let m=ce(f,t,n);try{await d.repo.system.backfillKeys(),mt(i,`${m}/${d.name}?flash=backfilled`);}catch(p){z(i,`<div class="p-6 text-error">Backfill failed: ${p.message}</div>`,500);}},T=async(f,i)=>{let w=[];for(let d of i){let m;if(f.isGroup||f.parentKeys?.length){let p=await $e(f,d);m=p?yt(p,f.pathKey):void 0;}m||(m=[d]);try{let p=f.repo.documentRef(...m);p&&w.push(p);}catch{}}return w},R=async(f,i)=>{let w=Yn(i),d=f.documentKey??"docId",m=[],p;for(;;){let O=await f.repo.query.paginate({pageSize:500,cursor:p,direction:"next",...w.length>0?{where:w}:{}});for(let A of O.data){let S=String(A[d]??A.id??"");S&&m.push(S);}if(!O.hasNextPage||!O.nextCursor)break;p=O.nextCursor;}return m},b=async(f,i)=>{let w=f.params.repoName;if(!w){ne(i,{error:"Bad request"},400);return}let d=e[w];if(!d){ne(i,{error:"Repository not found"},404);return}if(!d.allowDelete){ne(i,{error:"Delete is not allowed for this repository"},403);return}let m=f.body??{};try{let p=await h(d,m);if(p.length===0){ne(i,{deleted:0});return}let O=await T(d,p);for(let A=0;A<O.length;A+=500)await d.repo.bulk.delete(O.slice(A,A+500));ne(i,{deleted:O.length});}catch(p){ne(i,{error:p.message},500);}},k=async(f,i)=>{let w=f.params.repoName;if(!w){ne(i,{error:"Bad request"},400);return}let d=e[w];if(!d){ne(i,{error:"Repository not found"},404);return}let m=f.body??{},p=String(m.field??"");if(!p){ne(i,{error:"Missing 'field'"},400);return}if(!d.mutableFields||!d.mutableFields.includes(p)){ne(i,{error:`Field '${p}' is not bulk-updatable`},403);return}let O=d.schema.shape?.[p],A;if(O){let S=typeof d.schema=="object"&&d.schema&&"constructor"in d.schema&&d.schema.constructor.name.includes("Zod")?d.schema.pick({[p]:true}):void 0;if(!S){ne(i,{error:"Invalid schema structure"},500);return}A=ht(m.formPayload??{},S)[p];let E=O.safeParse(A);if(!E.success){ne(i,{error:`Invalid value for '${p}': ${E.error.message}`},400);return}A=E.data;}try{let S=await h(d,m);if(S.length===0){ne(i,{updated:0});return}let E=(await T(d,S)).map(I=>({docRef:I,data:{[p]:A}}));for(let I=0;I<E.length;I+=500)await d.repo.bulk.update(E.slice(I,I+500));ne(i,{updated:E.length});}catch(S){ne(i,{error:S.message},500);}};async function h(f,i){if(i.selectAll){let w=g(i.filters,f);return await R(f,w)}return Array.isArray(i.ids)?i.ids.filter(w=>typeof w=="string"&&!!w):[]}function g(f,i){if(!Array.isArray(f))return [];let w=new Set((i.filterableFields??Object.keys(ee(i.schema))).map(p=>String(p))),d=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),m=[];for(let p of f)p&&typeof p=="object"&&typeof p.field=="string"&&w.has(p.field)&&typeof p.value=="string"&&d.has(String(p.op))&&m.push({field:p.field,op:p.op,value:p.value});return m}return {handleDashboard:r,handleList:o,handleCreateForm:s,handleCreateSubmit:a,handleEditForm:l,handleEditSubmit:c,handleDelete:y,handlePanel:v,handleBulkDelete:b,handleBulkUpdate:k,handleBulkBackfill:x,handleHistory:async(f,i)=>{let w=f.params.repoName,d=f.params.id;if(!w||!d){z(i,"Bad request",400);return}let m=e[w];if(!m){z(i,"Repository not found",404);return}if(!m.historyEnabled||!m.repo.history){z(i,"History not enabled for this repository",404);return}let p=ce(f,t,n),O=m.historySubcollection??"history",A=[d];try{let _=await $e(m,d),V=_?yt(_,m.pathKey):void 0;V&&V.length>0&&(A=V);}catch{}let S=parseInt(String(f.query?.limit??"")),P=Number.isFinite(S)&&S>0?Math.min(S,500):100,E=[],I;try{E=await m.repo.history.list(...A,{limit:P});}catch(_){I=_.message;}let C=_=>String(_??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),$=_=>{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">${C(JSON.stringify(_))}</code>`}catch{return C(String(_))}return C(String(_))},j=_=>_?typeof _.toDate=="function"?_.toDate().toISOString():_ instanceof Date?_.toISOString():C(String(_)):"",N=_=>`<span class="badge badge-sm ${_==="create"?"badge-success":_==="delete"?"badge-error":"badge-info"}">${C(_)}</span>`,F="";if(F+='<div class="flex items-center justify-between mb-4">',F+=`<a href="${p}/${m.name}/${encodeURIComponent(d)}/edit" class="btn btn-sm btn-outline">\u2190 Back to edit</a>`,F+=`<a href="${p}/${m.name}" class="btn btn-sm btn-outline">\u2190 Back to list</a>`,F+="</div>",F+=`<p class="text-sm text-base-content/60 mb-4">Subcollection: <code>${C(O)}</code> \xB7 Showing up to ${P} entries.</p>`,I)F+=`<div class="alert alert-error mb-4">${C(I)}</div>`;else if(E.length===0)F+='<div class="alert">No history entries found.</div>';else {F+='<div class="overflow-x-auto"><table class="table table-zebra table-sm">',F+="<thead><tr><th>When</th><th>Op</th><th>User</th><th>Reason / Comment</th><th>Changes</th></tr></thead><tbody>";for(let _ of E){let V=_.meta??{},K=[V.reason,V.comment].filter(J=>J!=null&&J!=="").map(J=>C(String(J))).join(" \u2014 "),G="",je=Object.keys(_.changes??{});je.length===0?G='<span class="opacity-40">\u2014</span>':G='<ul class="space-y-1">'+je.map(J=>{let st=_.changes[J];return `<li><strong>${C(J)}</strong>: ${$(st.oldValue)} \u2192 ${$(st.newValue)}</li>`}).join("")+"</ul>",F+="<tr>",F+=`<td class="whitespace-nowrap text-xs font-mono">${C(j(_.historySetAt))}</td>`,F+=`<td>${N(_.operation??"update")}</td>`,F+=`<td class="text-xs">${C(V.userEmail??V.userId??"")}</td>`,F+=`<td class="text-xs">${K}</td>`,F+=`<td>${G}</td>`,F+="</tr>";}F+="</tbody></table></div>";}z(i,et(F,{title:`History \u2014 ${m.name} / ${d}`,basePath:p,breadcrumb:[{label:"Repositories",href:p},{label:m.name,href:`${p}/${m.name}`},{label:`History ${d}`}]}));}}}function ne(e,t,n=200){e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(t));}function Go(e){return e==="true"?true:e==="false"?false:e!==""&&!isNaN(Number(e))?Number(e):e}bt();async function Jo(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function Xo(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 lr(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,auth:s,middleware:a=[],httpsOptions:l}=e,c=t==="/"?"":t.replace(/\/$/,""),y={};for(let[R,b]of Object.entries(n)){if(!b.repo)throw new Error(`[createAdminServer] Repository "${R}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let k=b.schema??b.repo.schema??null;if(!k)throw new Error(`[createAdminServer] Repository "${R}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let h,g,u;if(b.fieldsConfig){let w=b.fieldsConfig;h=[],g=[],u=[];for(let[d,m]of Object.entries(w))for(let p of m)p==="filterable"?h.push(d):p==="mutable"?g.push(d):p==="create"&&u.push(d);h.length===0&&(h=void 0),g.length===0&&(g=void 0),u.length===0&&(u=void 0);}let f=(()=>{let w=b.repo._parentKeys;return w&&w.length>0?w:void 0})();if(f&&u)for(let w of f)u.includes(w)||u.push(w);let i={name:R,path:b.path,repo:b.repo,schema:k,documentKey:b.documentKey??"docId",pathKey:b.repo._pathKey??void 0,isGroup:!!b.repo._isGroup,parentKeys:f,createdKey:b.repo._createdKey??void 0,listColumns:b.listColumns,pageSize:b.pageSize,filterableFields:h,mutableFields:g,createFields:u,allowDelete:b.allowDelete??false,historyEnabled:!!b.repo._historyConfig?.enabled,historySubcollection:(b.repo._historyConfig?.enabled&&b.repo._historySubcollection)??void 0,relationalMeta:(()=>{if(!b.relationalFields||b.relationalFields.length===0)return;let w=b.repo.relationalKeys??{},d=[];for(let m of b.relationalFields){let p=w[m.key];p&&d.push({key:p.sourceKey?String(p.sourceKey):m.key,column:m.column,targetRepo:String(p.repo),targetKey:String(p.key),type:p.type});}return d.length>0?d:void 0})()};y[R]=i;}let v=sr(y,c,xn(l?.region)),x=new ye;if(o!==false&&x.use(gt(o===void 0?{}:o)),r&&x.use(async(R,b,k)=>{let h=R,g=String(h.headers?.["content-type"]??"");if(g.includes("application/x-www-form-urlencoded")){let u=await Jo(h);R.body=Xo(u);}else if(g.includes("application/json")&&typeof h.body=="string")try{R.body=JSON.parse(h.body);}catch{}await k();}),s)if(He(s)){for(let R of s.routes){let b=`${c}${R.path}`;R.method==="GET"?x.get(b,R.handler):x.post(b,R.handler);}x.use(s.middleware);}else if(typeof s=="function")x.use(s);else {let R=s.realm??"Admin",b="Basic "+Buffer.from(`${s.username}:${s.password}`).toString("base64");x.use((k,h,g)=>{if((k.headers?.authorization??"")!==b){h.status(401).set("WWW-Authenticate",`Basic realm="${R}"`).set("Content-Type","text/plain").send("Unauthorized");return}g();});}for(let R of a)x.use(R);x.get(`${c}/`,v.handleDashboard),x.get(`${c}`,v.handleDashboard),x.get(`${c}/:repoName/_panel`,v.handlePanel),x.post(`${c}/:repoName/_bulk/delete`,v.handleBulkDelete),x.post(`${c}/:repoName/_bulk/update`,v.handleBulkUpdate),x.post(`${c}/:repoName/_bulk/backfill`,v.handleBulkBackfill),x.get(`${c}/:repoName`,v.handleList),x.get(`${c}/:repoName/create`,v.handleCreateForm),x.post(`${c}/:repoName/create`,v.handleCreateSubmit),x.get(`${c}/:repoName/:id/edit`,v.handleEditForm),x.post(`${c}/:repoName/:id/edit`,v.handleEditSubmit),x.get(`${c}/:repoName/:id/history`,v.handleHistory),x.post(`${c}/:repoName/:id/delete`,v.handleDelete);let T=async(R,b)=>{await x.handle(R,b);};return l&&(T.httpsOptions=l),T}function an(e,t,n=200){let r=xe(t);return e.json(r,n)}function Te(e,t,n,r=200){return an(e,{success:true,data:t,meta:n},r)}function M(e,t,n=400){return an(e,{success:false,error:t},n)}function on(e,t,n,r,o){let s=We(t,n),a=s.type==="index",l=a?424:500,y={success:false,error:a?s.message:o&&t instanceof Error?t.message:r};return a&&(y.errorType="index",s.indexUrl&&(y.indexUrl=s.indexUrl)),an(e,y,l)}var sn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function dr(){let e="";for(;e.length<20;){let t=crypto.randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let r=t[n];r>=sn.length*4||(e+=sn.charAt(r%sn.length));}}return e}function Ie(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return zod.z.preprocess(r=>wn(r)??r,e);if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[s,a]of Object.entries(r))o[s]=Ie(a);return zod.z.object(o)}if(n==="ZodArray"||n==="array"){let r=t.element??t.type;if(r)return zod.z.array(Ie(r))}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(r)return Ie(r).optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(r)return Ie(r).nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType,o=t.defaultValue;if(r){let s=Ie(r);return typeof o=="function"?s.default(o()):s.default(o)}}return e}function es(e,t,n=[]){let r=e.shape,o={},s=t&&t.length>0?t:Object.keys(r);for(let a of s){if(n.includes(a))continue;let l=a.split(".")[0];l&&r[l]&&(o[l]=r[l]);}return zod.z.object(o)}function wt(e,t,n,r=false,o=[]){try{let s=es(e,n,o),a=r?s.partial():s;return {success:!0,data:(bn()==="normalize"?Ie(a):a).parse(t)}}catch(s){return s instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${s.issues.map(l=>`${l.path.join(".")}: ${l.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function vt(e,t,n){let r=e?.shape?.[t];if(!r||typeof r.safeParse!="function")return {success:true,data:n};let o=r.safeParse(n);if(o.success)return {success:true,data:o.data};if(Array.isArray(n)){let a=[];for(let l of n){let c=r.safeParse(l);if(c.success)a.push(c.data);else return {success:false,error:c.error.issues.map(v=>v.message).join(", ")}}return {success:true,data:a}}return {success:false,error:o.error.issues.map(a=>a.message).join(", ")}}function ts(e,t){let n=[],r=t?new Set(t):null,o={eq:"==",ne:"!=",lt:"<",lte:"<=",gt:">",gte:">=",in:"in",nin:"not-in",contains:"array-contains",containsAny:"array-contains-any"};for(let[s,a]of Object.entries(e)){if(a===void 0||["cursor","limit","pageSize","orderBy","orderDir","select"].includes(s))continue;let l=Array.isArray(a)?a[0]:a;if(l===void 0||l==="")continue;let c=s.match(/^(\w+)__(\w+)$/),y,v="==";if(c&&c[1]&&c[2]){y=c[1];let T=c[2];if(o[T])v=o[T];else continue}else if(!c)y=s;else continue;if(r&&!r.has(y))continue;let x=l;v==="in"||v==="not-in"||v==="array-contains-any"?x=l.split(",").map(T=>ur(T.trim())):x=ur(l),n.push({field:y,op:v,value:x});}return n}function ur(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 xt(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function pr(e,t){if(!t)return;let n;if(typeof t=="string")try{n=JSON.parse(t);}catch{n=t.includes("/")?{docPath:t}:{docId:t};}else typeof t=="object"&&(n=t);if(!n)return;let r=typeof n.docPath=="string"?n.docPath:void 0,o=typeof n.docId=="string"?n.docId:void 0;try{let s=e.repo.ref,a=s?.firestore;if(r&&a&&typeof a.doc=="function"){let l=await a.doc(r).get();if(l.exists)return l}if(o&&o.includes("/")&&a&&typeof a.doc=="function"){let l=await a.doc(o).get();if(l.exists)return l}if(o&&typeof s.doc=="function"){let l=await s.doc(o).get();if(l.exists)return l}return}catch{return}}function fr(e,t,n){async function r(g,u,f,i){if(!u.rules)return true;let w=u.rules?.[f];if(!w)return M(g,`Operation "${f}" is not allowed for this repository`,403),false;try{return await w(i)?!0:M(g,"Forbidden",403)}catch(d){let m=n&&d instanceof Error?d.message:"Forbidden";return M(g,m,403)}}async function o(g,u,f,i){if(!g.rules)return i;let w=g.rules?.filter;if(!w)return i;let d=[];for(let m of i)try{await w({user:u,doc:m,params:f})&&d.push(m);}catch{}return d}function s(g){return g.get("user")??g.get("docsUser")??null}function a(g,u){if(!g){let f=u.req.path.split("/");for(let i of f)if(e[i]){g=i;break}}return !g||!e[g]?null:e[g]??null}function l(g,u){if(!u)return;let f=g[u];if(typeof f!="string"||!f)return;let i=f.split("/").filter(Boolean),w=[];for(let d=1;d<i.length;d+=2)w.push(i[d]);return w.length>0?w:void 0}async function c(g,u){let f=`by${g.documentKey.charAt(0).toUpperCase()}${g.documentKey.slice(1)}`,i=g.repo.get[f];if(typeof i=="function")try{let d=await i(u);if(d)return d}catch{}return (await g.repo.query.by({where:[[g.documentKey,"==",u]],limit:1}))[0]??null}async function y(g){let u=g.c,f=u.req.param(),i=a(f.repoName,u);if(!i)return M(u,"Repository not found",404);let w=s(u);if(!await r(u,i,"list",{user:w,query:u.req.query(),params:f}))return;let d=[],m;try{let p=u.req.query(),O=Math.min(Number(p.pageSize)||i.pageSize,100),A=p.cursor,S=p.direction?.toLowerCase()==="prev"?"prev":"next",P=p.orderBy,E=p.orderDir?.toLowerCase()==="desc"?"desc":"asc",I=p.select,C=I?I.split(",").map(K=>K.trim()):void 0,$;i.allowedIncludes&&p.includes&&($=(typeof p.includes=="string"?p.includes.split(",").map(G=>G.trim()):Array.isArray(p.includes)?p.includes:[]).filter(G=>typeof G=="string"&&i.allowedIncludes.includes(G)),$?.length===0&&($=void 0));let j=ts(p,i.filterableFields);d=j.map(K=>({field:K.field,op:K.op,value:String(K.value??"")})),P&&(m={field:P,dir:E});let N={pageSize:O,direction:S};if(A)try{let K=typeof A=="string"?JSON.parse(A):A;N.cursor=await pr(i,K);}catch{}if(P){if(i.orderableFields&&!i.orderableFields.includes(P))return M(u,`Field not orderable: ${P}`,400);N.orderBy=[{field:P,direction:E}];}if(j.length>0){N.where=[];for(let K of j){let G=vt(i.schema,K.field,K.value);if(!G.success)return M(u,`Invalid filter value for '${K.field}': ${G.error}`,400);N.where.push([K.field,K.op,G.data]);}}C&&(N.select=C),$&&(N.include=$);let F=await i.repo.query.paginate(N),V={items:await o(i,s(u),f,F.data),hasNextPage:F.hasNextPage,hasPrevPage:F.hasPrevPage,nextCursor:xt(F.nextCursor),prevCursor:xt(F.prevCursor)};return Te(u,V,{pageSize:O,hasMore:F.hasNextPage})}catch(p){on(u,p,{ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:d,sort:m},"Failed to fetch documents",n);}}async function v(g){let u=g.c,f=u.req.param(),i=a(f.repoName,u);if(!i)return M(u,"Repository not found",404);let w=s(u);if(!await r(u,i,"list",{user:w,query:g.input||{},params:f}))return;let d=[],m;try{let p=g.input||{},O=Math.min(p.pageSize||i.pageSize,100),A=p.direction==="prev"?"prev":"next";p.where&&(d=p.where.map(C=>({field:String(C[0]),op:C[1],value:String(C[2]??"")}))),p.orderBy&&p.orderBy[0]&&(m={field:p.orderBy[0].field,dir:p.orderBy[0].direction==="desc"?"desc":"asc"});let S={pageSize:O,direction:A};if(p.cursor)try{let C=typeof p.cursor=="string"?JSON.parse(p.cursor):p.cursor;S.cursor=await pr(i,C);}catch{}if(i.allowedIncludes&&p.includes&&p.includes.length>0){let C=p.includes.filter($=>typeof $=="string"?i.allowedIncludes.includes($):typeof $=="object"&&$!==null&&"relation"in $&&typeof $.relation=="string"?i.allowedIncludes.includes($.relation):!1);C.length>0&&(S.include=C);}if(p.where&&p.where.length>0){if(i.filterableFields){let $=new Set(i.filterableFields),j=p.where.filter(N=>!$.has(N[0]));if(j.length>0){M(u,`Fields not filterable: ${j.map(N=>N[0]).join(", ")}`,400);return}}let C=[];for(let $ of p.where){let j=vt(i.schema,$[0],$[2]);if(!j.success){M(u,`Invalid filter value for '${$[0]}': ${j.error}`,400);return}C.push([$[0],$[1],j.data]);}S.where=C;}if(p.orWhere&&p.orWhere.length>0){if(i.filterableFields){let $=new Set(i.filterableFields),j=p.orWhere.filter(N=>!$.has(N[0]));if(j.length>0){M(u,`Fields not filterable: ${j.map(N=>N[0]).join(", ")}`,400);return}}let C=[];for(let $ of p.orWhere){let j=vt(i.schema,$[0],$[2]);if(!j.success){M(u,`Invalid filter value for '${$[0]}': ${j.error}`,400);return}C.push([$[0],$[1],j.data]);}S.orWhere=C;}if(p.orWhereGroups&&p.orWhereGroups.length>0){if(i.filterableFields){let $=new Set(i.filterableFields);for(let j of p.orWhereGroups){let N=j.filter(F=>!$.has(F[0]));if(N.length>0){M(u,`Fields not filterable: ${N.map(F=>F[0]).join(", ")}`,400);return}}}let C=[];for(let $ of p.orWhereGroups){let j=[];for(let N of $){let F=vt(i.schema,N[0],N[2]);if(!F.success){M(u,`Invalid filter value for '${N[0]}': ${F.error}`,400);return}j.push([N[0],N[1],F.data]);}C.push(j);}S.orWhereGroups=C;}if(p.orderBy&&p.orderBy.length>0){if(i.orderableFields){let C=new Set(i.orderableFields),$=p.orderBy.filter(j=>!C.has(j.field));if($.length>0){M(u,`Fields not orderable: ${$.map(j=>j.field).join(", ")}`,400);return}}S.orderBy=p.orderBy;}p.select&&p.select.length>0&&(S.select=p.select);let P=await i.repo.query.paginate(S),I={items:await o(i,s(u),f,P.data),hasNextPage:P.hasNextPage,hasPrevPage:P.hasPrevPage,nextCursor:xt(P.nextCursor),prevCursor:xt(P.prevCursor)};return Te(u,I,{pageSize:O,hasMore:P.hasNextPage})}catch(p){on(u,p,{ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:d,sort:m},"Failed to query documents",n);}}async function x(g){let u=g.c,f=u.req.param(),i=a(f.repoName,u);if(!i)return M(u,"Repository not found",404);let w=f.id;if(!w)return M(u,"Document ID required",400);try{let d=await c(i,w);if(!d)return M(u,"Document not found",404);let m=s(u);if(!await r(u,i,"get",{user:m,doc:d,params:f}))return;if(i.rules?.filter)try{if(!await i.rules.filter({user:m,doc:d,params:f}))return M(u,"Document not found",404)}catch{return M(u,"Document not found",404)}return Te(u,d)}catch(d){on(u,d,{ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:[{field:i.documentKey,op:"==",value:w}]},"Failed to fetch document",n);}}async function T(g){let u=g.c,f=u.req.param(),i=a(f.repoName,u);if(!i)return M(u,"Repository not found",404);try{let w=g.input||{},d=s(u);if(!await r(u,i,"create",{user:d,body:w,params:f}))return;let m=wt(i.schema,w,i.createFields,!1,i.systemKeys);if(!m.success)return M(u,m.error,400);if(i.validate){let O=await i.validate(m.data,"create");if(O)return M(u,O,400)}let p;if(i.isGroup&&i.parentKeys&&i.parentKeys.length>0){let O={...m.data};i.createdKey&&(O[i.createdKey]=new Date);let A=i.parentKeys.filter(E=>!O[E]);if(A.length>0){M(u,`Missing parent key(s) for subcollection create: ${A.join(", ")}`,400);return}let S=i.parentKeys.map(E=>O[E]),P=O[i.documentKey]||dr();p=await i.repo.set(...S,P,O);}else p=await i.repo.create(m.data);return Te(u,p,void 0,201)}catch(w){let d=n&&w instanceof Error?w.message:"Failed to create document";return M(u,d,500)}}async function R(g,u){let f=g.c,i=f.req.param(),w=a(i.repoName,f);if(!w)return M(f,"Repository not found",404);let d=i.id;if(!d)return M(f,"Document ID required",400);try{let m=g.input||{},p=await c(w,d);if(!p)return M(f,"Document not found",404);let O=s(f);if(!await r(f,w,"update",{user:O,doc:p,body:m,params:i}))return;let A=wt(w.schema,m,w.mutableFields,u,w.systemKeys);if(!A.success)return M(f,A.error,400);if(w.validate){let E=await w.validate(A.data,"update");if(E)return M(f,E,400)}let S=l(p,w.pathKey)??[d],P=await w.repo.update(...S,A.data);return Te(f,P)}catch(m){let p=n&&m instanceof Error?m.message:"Failed to update document";return M(f,p,500)}}async function b(g){let u=g.c,f=u.req.param(),i=a(f.repoName,u);if(!i)return M(u,"Repository not found",404);if(!i.allowDelete)return M(u,"Delete not allowed for this repository",403);let w=f.id;if(!w)return M(u,"Document ID required",400);try{let d=await c(i,w);if(!d)return M(u,"Document not found",404);let m=s(u);if(!await r(u,i,"delete",{user:m,doc:d,params:f}))return;let p=l(d,i.pathKey)??[w];return await i.repo.delete(...p),Te(u,{deleted:!0})}catch(d){let m=n&&d instanceof Error?d.message:"Failed to delete document";return M(u,m,500)}}function k(g){return g.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 h(g){let u=g.c,f=u.req.param(),i=a(f.repoName,u);if(!i)return M(u,"Repository not found",404);try{let w=g.input||{};if(!Array.isArray(w.operations))return M(u,"operations array is required",400);let d=s(u),m=i.repo.batch.create(),p=[];for(let O of w.operations){if(!O.type||!["create","update","delete"].includes(O.type))return M(u,"Invalid operation type",400);if(O.type==="create"){if(!await r(u,i,"create",{user:d,body:O.data,params:f}))return;let A=wt(i.schema,O.data,i.createFields,!1,i.systemKeys);if(!A.success)return M(u,A.error,400);let S=O.data[i.documentKey]||dr(),P={...A.data};if(i.createdKey&&(P[i.createdKey]=new Date),i.isGroup&&i.parentKeys){let E=i.parentKeys.map(I=>P[I]);m.set(...E,S,P);}else m.set(S,P);p.push({op:"create",id:S});}else if(O.type==="update"){if(!O.id)return M(u,"id required for update",400);let A=await c(i,O.id);if(!A)return M(u,`Document ${O.id} not found`,404);if(!await r(u,i,"update",{user:d,doc:A,body:O.data,params:f}))return;let S=wt(i.schema,O.data,i.mutableFields,!0,i.systemKeys);if(!S.success)return M(u,S.error,400);let P=l(A,i.pathKey)??[O.id];m.update(...P,S.data),p.push({op:"update",id:O.id});}else if(O.type==="delete"){if(!i.allowDelete)return M(u,"Delete not allowed",403);if(!O.id)return M(u,"id required for delete",400);let A=await c(i,O.id);if(!A)return M(u,`Document ${O.id} not found`,404);if(!await r(u,i,"delete",{user:d,doc:A,params:f}))return;let S=l(A,i.pathKey)??[O.id];m.delete(...S),p.push({op:"delete",id:O.id});}}return await m.commit(),Te(u,{results:p})}catch(w){let d=n&&w instanceof Error?w.message:"Batch operation failed";return M(u,d,500)}}return {handleList:y,handleQuery:v,handleGet:x,handleCreate:T,handleUpdate:R,handleDelete:b,handleBatch:h,handleOptions:k}}function St(e){try{return zod.z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=zodToOpenapi.getOpenApiMetadata(t.zodSchema);n&&Object.assign(t.jsonSchema,n);let r=t.zodSchema?._zod?.def;r&&(r.type==="date"&&!t.jsonSchema.type?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):r.type==="bigint"&&!t.jsonSchema.type&&(t.jsonSchema.type="string",t.jsonSchema.format="int64"));}})}catch(t){return typeof console<"u"&&console.warn&&console.warn("[generateOpenAPISpec] Failed to convert Zod schema to JSON Schema; falling back to {type:object}.",t),{type:"object"}}}function oe(e){return {$ref:`#/components/schemas/${e}`}}function W(e){return {description:e,content:{"application/json":{schema:oe("ErrorResponse")}}}}function De(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function yr(e){return {description:"Paginated list of documents",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:{type:"object",properties:{items:{type:"array",items:e},nextCursor:{oneOf:[{type:"object"},{type:"null"}]},prevCursor:{oneOf:[{type:"object"},{type:"null"}]},hasNextPage:{type:"boolean"},hasPrevPage:{type:"boolean"}},required:["items","hasNextPage","hasPrevPage"]},meta:{type:"object",properties:{pageSize:{type:"integer"},hasMore:{type:"boolean"},cursor:{oneOf:[{type:"string"},{type:"null"}]}}}},required:["success","data"]}}}}}function nt(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function rs(e,t){let n=t.split("."),r=nt(e);for(let o=0;o<n.length;o++){let s=n[o];if(!s)continue;let a=r?.shape;if(!a||!a[s])return;r=nt(a[s]);}return r}function mr(e,t="",n=0){if(n>5)return [];let o=nt(e)?.shape;if(!o)return [];let s=[];for(let[a,l]of Object.entries(o)){let c=t?`${t}.${a}`:a,y=nt(l);y?.shape&&typeof y.shape=="object"?s.push(...mr(y,c,n+1)):s.push({path:c,zodSchema:l});}return s}function dn(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:rs(e.schema,t)})):mr(e.schema)}function ln(e){if(!e)return {type:"string"};let t=St(e);return delete t.$schema,delete t.title,t}function os(e){let t=dn(e),n=e.orderableFields??t.map(r=>r.path);return [{name:"pageSize",in:"query",schema:{type:"integer",default:e.pageSize,maximum:100},description:"Number of items per page"},{name:"cursor",in:"query",schema:{type:"string"},description:"Base64 pagination cursor"},{name:"orderBy",in:"query",schema:{type:"string",...n.length>0?{enum:n}:{}},description:"Field name to order by"},{name:"orderDir",in:"query",schema:{type:"string",enum:["asc","desc"]},description:"Order direction"},{name:"select",in:"query",schema:{type:"string"},description:`Comma-separated list of fields to return${t.length>0?` (${t.map(r=>r.path).join(", ")})`:""}`}]}function ss(e){let t=dn(e),n=["eq","ne","lt","lte","gt","gte","in","nin","contains","containsAny"],r={eq:"equals. Use 'null' or '__null__' to match null values",ne:"not equals. Use 'null' or '__null__' to match non-null values",lt:"less than",lte:"less than or equal",gt:"greater than",gte:"greater than or equal",in:"in list (comma-separated values). Supports 'null' and '__null__' (e.g. val1,val2,__null__)",nin:"not in list (comma-separated values). Supports 'null' and '__null__'",contains:"array-contains",containsAny:"array-contains-any (comma-separated values). Supports 'null' and '__null__'"},o=[];for(let{path:s,zodSchema:a}of t){let l=ln(a);o.push({name:s,in:"query",schema:l,description:`Filter by ${s} (equality). Use 'null' or '__null__' for null values`});for(let c of n){let y=r[c]?` (${r[c]})`:"",v=c==="in"||c==="nin"||c==="containsAny";o.push({name:`${s}__${c}`,in:"query",schema:v?{type:"string",description:"Comma-separated list of values"}:l,description:`Filter ${s} with operator ${c}${y}`});}}return o}function hr(){return {type:"object",properties:{where:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3},description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3},description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3}},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string"},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string"},description:"Fields to select (projection)"},pageSize:{type:"integer",maximum:100,description:"Number of items per page"},cursor:{oneOf:[{type:"string"},{type:"object"}],description:"Pagination cursor"},direction:{type:"string",enum:["next","prev"],description:"Pagination direction"},includes:{type:"array",items:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"}}}}function as(e){let t=dn(e),n=e.orderableFields??t.map(a=>a.path),r=t.map(a=>a.path);if(t.length===0)return hr();let o=[];for(let{path:a,zodSchema:l}of t){let c=ln(l),y=nt(l),x=y?._zod?.def?.type==="array"||y?._def?.typeName==="ZodArray"||y?._def?.type==="array"?ln(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"]},x],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:x}],minItems:3,maxItems:3});}let s={oneOf:o};return {type:"object",properties:{where:{type:"array",items:s,description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:s,description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:s},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string",enum:n},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string",enum:r},description:"Fields to select (projection)"},pageSize:{type:"integer",maximum:100,description:"Number of items per page"},cursor:{oneOf:[{type:"string"},{type:"object"}],description:"Pagination cursor"},direction:{type:"string",enum:["next","prev"],description:"Pagination direction"},includes:{type:"array",items:e.allowedIncludes&&e.allowedIncludes.length>0?{oneOf:[{type:"string",enum:e.allowedIncludes},{type:"object",properties:{relation:{type:"string",enum:e.allowedIncludes},select:{type:"array",items:{type:"string"}}},required:["relation"]}]}:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"}}}}function is(e,t,n,r,o,s="QueryRequestBody"){let a={},l=e.name,c=`${t}/${e.name}`,y=`${c}/{${e.documentKey}}`,v={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};a[c]={get:{operationId:`list${fe(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[l],parameters:[...os(e),...ss(e)],responses:{200:yr(oe(n)),500:W("Internal server error")}},post:{operationId:`create${fe(e.name)}`,summary:`Create a ${le(e.name)}`,tags:[l],requestBody:{required:true,content:{"application/json":{schema:oe(r??n)}}},responses:{201:De("Document created",oe(n)),400:W("Validation error"),500:W("Internal server error")}}},a[`${c}/query`]={post:{operationId:`query${fe(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[l],requestBody:{required:true,content:{"application/json":{schema:oe(s)}}},responses:{200:yr(oe(n)),400:W("Invalid query"),500:W("Internal server error")}}},a[`${c}/batch`]={post:{operationId:`batch${fe(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[l],requestBody:{required:true,content:{"application/json":{schema:oe(`${n}BatchRequest`)}}},responses:{200:De("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:W("Validation error"),403:W("Forbidden"),404:W("Document not found"),500:W("Internal server error")}}};let x={};return x.get={operationId:`get${fe(le(e.name))}`,summary:`Get a single ${le(e.name)}`,tags:[l],parameters:[v],responses:{200:De("Document found",oe(n)),404:W("Document not found"),500:W("Internal server error")}},x.put={operationId:`update${fe(le(e.name))}`,summary:`Update a ${le(e.name)} (full replace)`,tags:[l],parameters:[v],requestBody:{required:true,content:{"application/json":{schema:oe(o??n)}}},responses:{200:De("Document updated",oe(n)),400:W("Validation error"),404:W("Document not found"),500:W("Internal server error")}},x.patch={operationId:`patch${fe(le(e.name))}`,summary:`Partially update a ${le(e.name)}`,tags:[l],parameters:[v],requestBody:{required:true,content:{"application/json":{schema:{allOf:[oe(o??n)],description:"All fields are optional for partial updates"}}}},responses:{200:De("Document patched",oe(n)),400:W("Validation error"),404:W("Document not found"),500:W("Internal server error")}},e.allowDelete&&(x.delete={operationId:`delete${fe(le(e.name))}`,summary:`Delete a ${le(e.name)}`,tags:[l],parameters:[v],responses:{200:De("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:W("Document not found"),500:W("Internal server error")}}),a[y]=x,a}function un(e,t,n={}){let{title:r="CRUD API",version:o="1.0.0",description:s,servers:a,auth:l=false}=n,c=t==="/"?"":t.replace(/\/$/,""),y={},v={},x=[];y.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},y.QueryRequestBody=hr();for(let[k,h]of Object.entries(e)){let g=fe(le(k)),u=`${g}Create`,f=`${g}Update`,i=`${g}QueryRequestBody`;y[g]=St(h.schema),y[i]=as(h);let w=S=>{let P=S&&S.length>0?S:Object.keys(h.schema.shape),E={};for(let I of P){let C=I.split(".")[0];C&&h.schema.shape[C]&&!h.systemKeys.includes(C)&&(E[C]=h.schema.shape[C]);}return E},d=null,m=w(h.createFields);Object.keys(m).length>0&&(y[u]=St(zod.z.object(m)),d=u);let p=null,O=w(h.mutableFields);Object.keys(O).length>0&&(y[f]=St(zod.z.object(O)),p=f),y[`${g}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",enum:["create"]},data:oe(d??g)},required:["type","data"]},{type:"object",properties:{type:{type:"string",enum:["update"]},id:{type:"string"},data:{allOf:[oe(p??g)],description:"Partial updates allowed"}},required:["type","id","data"]},...h.allowDelete?[{type:"object",properties:{type:{type:"string",enum:["delete"]},id:{type:"string"}},required:["type","id"]}]:[]]}}},required:["operations"]};let A=is(h,c,g,d,p,i);Object.assign(v,A),x.push({name:k,description:`Operations on ${k} (collection: ${h.path})`});}let T={},R;return l==="basic"?(T.basicAuth={type:"http",scheme:"basic"},R=[{basicAuth:[]}]):l==="bearer"&&(T.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},R=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:o,...s?{description:s}:{}},...a&&a.length>0?{servers:a}:{},paths:v,components:{schemas:y,...Object.keys(T).length>0?{securitySchemes:T}:{}},...R?{security:R}:{},tags:x}}function fe(e){return e.charAt(0).toUpperCase()+e.slice(1)}function le(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 _e=class extends Error{constructor(n,r){super("Request validation failed");this.zodError=n;this.source=r;this.statusCode=400;this.name="ValidationError";}};var rt=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},ot=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function gr(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function br(e,t){return t instanceof _e?e.json({success:false,error:"Validation failed",issues:gr(t.zodError)},400):t instanceof rt?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof ot?e.json({success:false,error:"Output validation failed",issues:gr(t.zodError)},500):null}zodToOpenapi.extendZodWithOpenApi(zod.z);var wr="Successful response",vr="Error response";function ps(e){return e==="get"?"query":"json"}function fs(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function ys(e){if(typeof e.safeParse=="function")return {description:vr,schema:e};let t=e;return {description:t.description??vr,schema:t.schema}}function Sr(e,t,n,r){let o=new zodToOpenapi.OpenAPIRegistry;if(n.securitySchemes)for(let[l,c]of Object.entries(n.securitySchemes))o.registerComponent("securitySchemes",l,c);for(let l of e){let c=l.method,y=l.source??ps(c),v=gs(t,l.path??"/"),x=l.status??200,T=ms(c,y,l.input),R=xr(y,l.input,"query"),b=xr(y,l.input,"param"),k=bs(c,v),h=fs(l.output,r),g={[x]:h?{description:wr,content:{"application/json":{schema:h}}}:{description:wr}};if(r?.errors)for(let[u,f]of Object.entries(r.errors)){let{description:i,schema:w}=ys(f);g[u]=w?{description:i,content:{"application/json":{schema:w}}}:{description:i};}o.registerPath({method:c,path:hs(v),operationId:k,summary:l.summary,description:l.description,tags:l.tags,deprecated:l.deprecated,security:l.security,request:{...R?{query:R}:{},...b?{params:b}:{},...T?{body:T}:{}},responses:g});}return new zodToOpenapi.OpenApiGeneratorV31(o.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security})}function ms(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 xr(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function hs(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function gs(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function bs(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function Rr(e,t){let n=e.replace(/"/g,"&quot;");return `<!doctype html>
1141
+ `;function Qe(){return jsxRuntime.jsx("script",{dangerouslySetInnerHTML:{__html:Un}})}Lt();function ge(e){return "<!DOCTYPE html>"+server.renderToString(e)}var Do=["corporate","silk","dark"],_o=()=>jsxRuntime.jsxs("div",{class:"dropdown dropdown-end","data-frs-theme-switcher":true,children:[jsxRuntime.jsxs("button",{type:"button",tabIndex:0,class:"btn btn-sm btn-ghost text-neutral-content gap-1.5","aria-label":"Switch theme",children:[jsxRuntime.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",class:"size-4",children:[jsxRuntime.jsx("circle",{cx:"12",cy:"12",r:"4"}),jsxRuntime.jsx("path",{d:"M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"})]}),jsxRuntime.jsx("span",{class:"text-xs hidden sm:inline","data-frs-theme-current":true,children:"Theme"})]}),jsxRuntime.jsx("ul",{tabIndex:0,class:"dropdown-content menu menu-sm bg-base-100 text-base-content rounded-box z-50 mt-2 w-40 p-1 shadow-lg border border-base-300",children:Do.map(e=>jsxRuntime.jsx("li",{children:jsxRuntime.jsxs("button",{type:"button","data-frs-theme":e,class:"capitalize justify-between",children:[jsxRuntime.jsx("span",{children:e}),jsxRuntime.jsx("span",{class:"hidden text-primary","data-frs-theme-check":e,children:"\u2713"})]})},e))})]}),be=({opts:e,children:t})=>{let{title:n,breadcrumb:r,flash:o,basePath:s="/"}=e;return jsxRuntime.jsxs("html",{lang:"en","data-theme":"corporate",children:[jsxRuntime.jsxs("head",{children:[jsxRuntime.jsx("meta",{charset:"UTF-8"}),jsxRuntime.jsx("meta",{name:"viewport",content:"width=device-width, initial-scale=1"}),jsxRuntime.jsxs("title",{children:[n," \u2014 FRS Admin"]}),jsxRuntime.jsx("script",{dangerouslySetInnerHTML:{__html:"(function(){try{var t=localStorage.getItem('frs-admin-theme');if(t){document.documentElement.setAttribute('data-theme',t);}}catch(_){}})();"}}),jsxRuntime.jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/themes.css",rel:"stylesheet",type:"text/css"}),jsxRuntime.jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/daisyui.css",rel:"stylesheet",type:"text/css"}),jsxRuntime.jsx("script",{src:"https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"})]}),jsxRuntime.jsxs("body",{class:"bg-base-200/50 min-h-screen flex flex-col",children:[jsxRuntime.jsxs("div",{class:"navbar bg-neutral text-neutral-content shadow-sm sticky top-0 z-50 px-6",children:[jsxRuntime.jsx("div",{class:"flex-1",children:jsxRuntime.jsx("a",{href:s,class:"font-bold text-lg tracking-tight hover:opacity-80 transition-opacity",children:"FRS Admin"})}),jsxRuntime.jsx("div",{class:"flex-none",children:jsxRuntime.jsx(_o,{})})]}),jsxRuntime.jsxs("main",{class:"px-6 py-8 w-full flex-1",children:[r&&r.length>0&&jsxRuntime.jsx("div",{class:"text-sm breadcrumbs mb-4",children:jsxRuntime.jsx("ul",{children:r.map((a,l)=>a.href?jsxRuntime.jsx("li",{children:jsxRuntime.jsx("a",{href:a.href,children:a.label})},l):jsxRuntime.jsx("li",{class:"text-base-content/60",children:a.label},l))})}),jsxRuntime.jsx("h1",{class:"text-2xl font-bold mb-6",children:n}),o&&jsxRuntime.jsxs("div",{role:"alert",class:`alert ${o.type==="success"?"alert-success":o.type==="warning"?"alert-warning":"alert-error"} mb-6`,children:[jsxRuntime.jsx("span",{class:"flex-1",children:o.message}),o.action&&jsxRuntime.jsx("a",{href:o.action.href,...o.action.external?{target:"_blank",rel:"noopener noreferrer"}:{},class:"btn btn-sm btn-outline",children:o.action.label})]}),t]}),jsxRuntime.jsx(Zt,{basePath:s}),jsxRuntime.jsx(Qe,{})]})]})};function Ut(e,t){return ge(jsxRuntime.jsx(be,{opts:t,children:jsxRuntime.jsx("div",{dangerouslySetInnerHTML:{__html:e}})}))}function Kt(e,t){return ge(jsxRuntime.jsx(be,{opts:{title:"Repositories",basePath:t},children:e.length===0?jsxRuntime.jsxs("div",{class:"text-center py-20 text-base-content/50",children:[jsxRuntime.jsx("p",{class:"text-lg font-medium mb-1",children:"No repositories configured"}),jsxRuntime.jsx("p",{class:"text-sm",children:"Add a repository to your FRS config to get started."})]}):jsxRuntime.jsx("div",{class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:e.map(n=>jsxRuntime.jsx("a",{href:`${t}/${n.name}`,class:"card bg-base-100 border border-base-300 hover:shadow-md no-underline transition-shadow",children:jsxRuntime.jsxs("div",{class:"card-body p-5",children:[jsxRuntime.jsx("h2",{class:"card-title text-sm font-semibold",children:n.name}),jsxRuntime.jsx("p",{class:"text-xs text-base-content/50 font-mono",children:n.path})]})},n.name))})}))}var Qn=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],jo=[{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"}],Fo=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function Mo(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return jo;case "ZodBoolean":return Qn;case "ZodArray":return Fo;default:return Qn}}var we="__null__";function No(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="${we}"]');if(!o){o=document.createElement('option');o.value='${we}';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='${we}';i.readOnly=true;}i.style.opacity='0.55';}else{i.style.opacity='';if(i.tagName==='SELECT'){var o2=i.querySelector('option[value="${we}"][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!=='${we}')?i.dataset._prev:'';}}})(this)`}function Ho(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 Ye({inputId:e,active:t}){return jsxRuntime.jsxs("label",{class:"flex items-center gap-1 cursor-pointer select-none text-xs text-base-content/60 hover:text-base-content border border-base-300 rounded-md px-1.5 py-1 shrink-0 leading-none h-8",title:"Filter where field IS NULL",children:[jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",checked:t,onchange:No(e)}),jsxRuntime.jsx("span",{children:"\u2205"})]})}function zo({col:e,active:t}){let n=t?.value??"",r=n===we,o=`fv_input_${e.name.replace(/\./g,"__")}`,s=t?.op,a=s==="in"||s==="not-in";if(e.enumValues&&e.enumValues.length>0){if(a){let l=new Set(n.split(",").map(y=>y.trim()).filter(Boolean)),c=`eg_${e.name.replace(/\./g,"__")}`;return jsxRuntime.jsxs("div",{class:"flex flex-wrap items-center gap-1 w-full",children:[jsxRuntime.jsx("input",{type:"hidden",id:o,name:`fv_${e.name}`,value:n}),e.enumValues.map(y=>jsxRuntime.jsxs("label",{class:"flex items-center gap-1 text-xs border border-base-300 rounded px-2 cursor-pointer hover:bg-base-200",children:[jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",value:y,checked:l.has(y),"data-enum-group":c,onchange:Ho(o,c)}),jsxRuntime.jsx("span",{children:y})]},y))]})}return jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsxRuntime.jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),e.enumValues.map(l=>jsxRuntime.jsx("option",{value:l,selected:n===l,children:l},l)),e.nullable&&jsxRuntime.jsx("option",{value:we,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsxRuntime.jsx(Ye,{inputId:o,active:r})]})}if(e.zodType==="ZodBoolean")return jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsxRuntime.jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),jsxRuntime.jsx("option",{value:"true",selected:n==="true",children:"true"}),jsxRuntime.jsx("option",{value:"false",selected:n==="false",children:"false"}),e.nullable&&jsxRuntime.jsx("option",{value:we,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsxRuntime.jsx(Ye,{inputId:o,active:r})]});if(e.zodType==="ZodArray"){let l=t?.op==="array-contains-any";return jsxRuntime.jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:l?"val1, val2, \u2026":"value",class:"input input-sm input-bordered w-full"})}return e.zodType==="ZodNumber"||e.zodType==="ZodBigInt"?jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsx("input",{id:o,type:r?"text":"number",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0,"data-_type":r?"number":void 0}),e.nullable&&jsxRuntime.jsx(Ye,{inputId:o,active:r})]}):e.zodType==="ZodDate"?jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsx("input",{id:o,type:r?"text":"datetime-local",name:`fv_${e.name}`,value:n,class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0,"data-_type":r?"datetime-local":void 0}),e.nullable&&jsxRuntime.jsx(Ye,{inputId:o,active:r})]}):jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0}),e.nullable&&jsxRuntime.jsx(Ye,{inputId:o,active:r})]})}function Vt({action:e,columnMeta:t,activeFilters:n,isGroup:r}){let o=Object.fromEntries(n.map(c=>[c.field,c])),s=n.length>0,a=n.length>=2||r&&s,l=t.filter(c=>c.zodType!=="ZodObject"&&c.zodType!=="ZodRecord");return jsxRuntime.jsxs("details",{class:"collapse collapse-arrow bg-base-100 border border-base-300 rounded-box mb-6 shadow-sm",open:s?true:void 0,children:[jsxRuntime.jsxs("summary",{class:"collapse-title text-sm font-medium py-2 min-h-0",children:["Filters",s&&jsxRuntime.jsxs("span",{class:"badge badge-primary badge-sm ml-2",children:[n.length," active"]})]}),jsxRuntime.jsx("div",{class:"collapse-content pb-4 pt-2",children:jsxRuntime.jsxs("form",{method:"get",action:e,children:[jsxRuntime.jsx("div",{class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:l.map(c=>{let y=Mo(c.zodType),v=o[c.name],x=v?.op??y[0].value;return jsxRuntime.jsxs("div",{class:"flex flex-col gap-1.5",children:[jsxRuntime.jsx("label",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:c.name}),jsxRuntime.jsxs("div",{class:"flex gap-1.5",children:[y.length>1?jsxRuntime.jsx("select",{name:`fo_${c.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:y.map(T=>jsxRuntime.jsx("option",{value:T.value,selected:T.value===x,children:T.label},T.value))}):jsxRuntime.jsx("input",{type:"hidden",name:`fo_${c.name}`,value:y[0].value}),jsxRuntime.jsx(zo,{col:c,active:v})]})]},c.name)})}),jsxRuntime.jsxs("div",{class:"flex flex-wrap gap-2 mt-4 pt-3 border-t border-base-200 items-center",children:[jsxRuntime.jsx("button",{type:"submit",class:"btn btn-sm btn-primary",children:"Apply"}),s&&jsxRuntime.jsx("a",{href:e,class:"btn btn-sm btn-ghost",children:"Clear"}),a&&jsxRuntime.jsxs("span",{class:"text-xs text-warning ml-auto flex items-center gap-1",children:[jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-4 w-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:jsxRuntime.jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),r?"Collection group queries require a composite index":"Multiple filters may require a composite index"]})]})]})})]})}function Wt(e,t,n,r,o,s){let a=n==="create"?`Create ${e}`:`Edit ${e} / ${r??""}`,l=n==="create"?[{label:"Repositories",href:o},{label:e,href:`${o}/${e}`},{label:"New document"}]:[{label:"Repositories",href:o},{label:e,href:`${o}/${e}`},{label:`Edit ${r??""}`}];return ge(jsxRuntime.jsx(be,{opts:{title:a,breadcrumb:l,basePath:o,flash:s},children:jsxRuntime.jsx("div",{class:"card bg-base-100 border border-base-300",children:jsxRuntime.jsx("div",{class:"card-body p-6",children:jsxRuntime.jsx("div",{dangerouslySetInnerHTML:{__html:t}})})})}))}pt();qt();function Qt(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 Gn(e,t,n,r,o){let s=Qt(e,r,o);return s.set("cursor",t),s.set("dir",n),`?${s.toString()}`}function Bo(e,t,n,r){let o=Qt(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 qo(e,t,n){return `?${Qt(t,n,e).toString()}`}function Gt(e,t,n,r,o,s,a=[],l=[],c=false,y=[],v,x,T,R,b,k,h,g=false){let u=`${r}/${e}`,f=`${u}/create`,i={};if(h)for(let S of n)i[S]=Ge(Je(h,S));let w=(k??[]).filter(S=>true),d=w.length>0,m=c,p=m||d,O=w.map(S=>{let P=Je(h,S),E=Ge(P),I=a.find(C=>C.name===S);return {name:S,type:E,enumValues:I?.enumValues??null,nullable:I?.nullable??false}}),A=[];return h&&(A=se(h).filter(P=>w.includes(P.name))),ge(jsxRuntime.jsxs(be,{opts:{title:e,breadcrumb:[{label:"Repositories",href:r},{label:e}],basePath:r,flash:s},children:[a.length>0&&jsxRuntime.jsx(Vt,{action:u,columnMeta:a,activeFilters:l,isGroup:R}),T&&jsxRuntime.jsxs("div",{role:"alert",class:`alert ${T.type==="index"?"alert-warning":"alert-error"} mb-6 shadow-sm`,children:[jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6 shrink-0 stroke-current",fill:"none",viewBox:"0 0 24 24",children:T.type==="index"?jsxRuntime.jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"}):jsxRuntime.jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"})}),jsxRuntime.jsxs("div",{class:"flex-1",children:[jsxRuntime.jsx("h3",{class:"font-bold",children:T.type==="index"?"Composite index required":"Query failed"}),jsxRuntime.jsx("div",{class:"text-sm",children:T.message})]}),T.indexUrl&&jsxRuntime.jsx("a",{href:T.indexUrl,target:"_blank",rel:"noopener noreferrer",class:"btn btn-sm btn-outline",children:"Create Index \u2192"})]}),jsxRuntime.jsxs("div",{class:"flex flex-wrap justify-between items-center mb-4 gap-3","data-frs-toolbar":true,children:[jsxRuntime.jsxs("div",{class:"flex items-center gap-3",children:[jsxRuntime.jsxs("span",{class:"text-sm text-base-content/60",children:[t.length,typeof b=="number"&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[" ","of"," ",jsxRuntime.jsx("span",{class:"font-semibold text-base-content/80",children:b})]})," ","document",(typeof b=="number"?b:t.length)!==1&&"s"]}),jsxRuntime.jsxs("div",{class:"flex items-center gap-1.5 text-sm text-base-content/60",children:[jsxRuntime.jsx("span",{children:"Rows"}),jsxRuntime.jsx("div",{class:"join",children:[10,25,50,100].map(S=>jsxRuntime.jsx("a",{href:qo(S,l,v),class:`join-item btn btn-xs ${x===S?"btn-active btn-primary":"btn-outline"}`,children:S},S))})]})]}),jsxRuntime.jsxs("div",{class:"flex gap-2",children:[jsxRuntime.jsx("form",{method:"post",action:`${u}/_bulk/backfill`,onsubmit:"return confirm('Backfill entire repository? This will scan all documents and fill missing system keys.')",children:jsxRuntime.jsx("button",{type:"submit",class:"btn btn-outline btn-sm",children:"Backfill"})}),jsxRuntime.jsx("a",{href:f,class:"btn btn-primary btn-sm",children:"+ New"})]})]}),p&&jsxRuntime.jsxs("div",{class:"hidden mb-3 alert alert-info py-2 px-3","data-frs-bulk-bar":true,"data-frs-repo":e,"data-frs-total":typeof b=="number"?String(b):"","data-frs-page-size":String(x??t.length),"data-frs-allow-delete":m?"1":"0","data-frs-allow-update":d?"1":"0","data-frs-fields":JSON.stringify(O),"data-frs-filters":JSON.stringify(l),children:[jsxRuntime.jsxs("div",{class:"flex-1 text-sm",children:[jsxRuntime.jsx("span",{"data-frs-bulk-summary":true,children:"0 selected"}),typeof b=="number"&&b>t.length&&jsxRuntime.jsxs("button",{type:"button",class:"ml-3 link text-sm hidden","data-frs-bulk-select-all":true,children:["Select all ",b," matching documents"]}),jsxRuntime.jsxs("span",{class:"hidden ml-3 italic","data-frs-bulk-all-active":true,children:["All ",b??"?"," matching documents are selected."," ",jsxRuntime.jsx("button",{type:"button",class:"link","data-frs-bulk-clear":true,children:"Clear selection"})]})]}),jsxRuntime.jsxs("div",{class:"flex gap-2",children:[d&&jsxRuntime.jsx("button",{type:"button",class:"btn btn-sm btn-outline","data-frs-bulk-action":"update",children:"Update field\u2026"}),m&&jsxRuntime.jsx("button",{type:"button",class:"btn btn-sm btn-error btn-outline","data-frs-bulk-action":"delete",children:"Delete"})]})]}),jsxRuntime.jsx("div",{class:"overflow-x-auto rounded-box border border-base-300 bg-base-100","data-frs-table-wrap":true,children:jsxRuntime.jsxs("table",{class:"table table-sm w-full","data-frs-table":true,"data-frs-repo":e,"data-frs-colcount":n.length,children:[jsxRuntime.jsx("thead",{children:jsxRuntime.jsxs("tr",{class:"bg-base-200/50",children:[p&&jsxRuntime.jsx("th",{class:"w-8",children:jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-page":true,"aria-label":"Select all on this page"})}),[...n].map((S,P)=>{let E=v?.field===S,I=E?v.dir==="asc"?" \u25B2":" \u25BC":"";return jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:jsxRuntime.jsxs("a",{href:Bo(S,v,l,x),class:`hover:text-base-content inline-flex items-center gap-0.5${E?" text-primary font-bold":""}`,children:[S,I]})},P)}),y.map((S,P)=>jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:S.column},`rel-${P}`)),jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide text-right",children:"Actions"})]})}),jsxRuntime.jsx("tbody",{children:t.length===0?jsxRuntime.jsx("tr",{children:jsxRuntime.jsx("td",{colspan:n.length+y.length+1+(p?1:0),class:"text-center py-16 text-base-content/40",children:"No documents found"})}):t.map((S,P)=>{let E=String(S.docId??S.id??""),I=`${r}/${e}/${encodeURIComponent(E)}/edit`,C=`${r}/${e}/${encodeURIComponent(E)}/delete`;return jsxRuntime.jsxs("tr",{class:"hover","data-frs-row-id":E,children:[p&&jsxRuntime.jsx("td",{class:"align-middle py-2",children:jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-row":true,value:E,"aria-label":`Select ${E}`})}),n.map(($,j)=>{let N=S[$],F=i[$],_=F?Xe(F,N):null;return jsxRuntime.jsx("td",{class:"align-top py-2",children:jsxRuntime.jsx(Pe,{val:N,mismatch:_})},j)}),y.map(($,j)=>{let N=S[$.key];if(N==null||N==="")return jsxRuntime.jsx("td",{class:"py-2"},`rel-${j}`);let F=$.type==="one"?`${r}/${$.targetRepo}/${encodeURIComponent(String(N))}/edit`:`${r}/${$.targetRepo}?fv_${$.targetKey}=${encodeURIComponent(String(N))}`;return jsxRuntime.jsx("td",{class:"align-middle py-2",children:jsxRuntime.jsx("a",{href:F,class:"btn btn-xs btn-ghost btn-outline","data-frs-relation":true,"data-frs-rel-type":$.type,"data-frs-rel-repo":$.targetRepo,"data-frs-rel-fk":$.targetKey,"data-frs-rel-val":String(N),"data-frs-rel-label":$.column,children:$.column})},`rel-${j}`)}),jsxRuntime.jsx("td",{class:"align-middle text-right whitespace-nowrap py-2",children:jsxRuntime.jsxs("div",{class:"flex gap-1 justify-end",children:[jsxRuntime.jsx("a",{href:I,class:"btn btn-xs btn-outline",children:"Edit"}),g&&jsxRuntime.jsx("a",{href:`${r}/${e}/${encodeURIComponent(E)}/history`,class:"btn btn-xs btn-outline",title:"View change history",children:"History"}),c&&jsxRuntime.jsx("form",{method:"post",action:C,onsubmit:"return confirm('Delete this document?')",children:jsxRuntime.jsx("button",{type:"submit",class:"btn btn-xs btn-error btn-outline",children:"Delete"})})]})})]},P)})})]})}),(o.hasPrev||o.hasNext)&&jsxRuntime.jsxs("div",{class:"flex flex-col items-center mt-6 gap-2",children:[jsxRuntime.jsxs("div",{class:"flex justify-center items-center gap-2",children:[o.hasPrev?jsxRuntime.jsx("a",{href:Gn(l,o.prevCursor,"prev",v,x),class:"btn btn-sm btn-outline",children:"\u2190 Previous"}):jsxRuntime.jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"\u2190 Previous"}),o.hasNext?jsxRuntime.jsx("a",{href:Gn(l,o.nextCursor,"next",v,x),class:"btn btn-sm btn-outline",children:"Next \u2192"}):jsxRuntime.jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"Next \u2192"})]}),typeof b=="number"&&jsxRuntime.jsxs("div",{class:"text-xs text-base-content/50",children:[b," total document",b!==1?"s":"",l.length>0?" matching filters":""]})]}),p&&d&&jsxRuntime.jsxs("dialog",{id:"frs-bulk-update-modal",class:"modal",children:[jsxRuntime.jsxs("div",{class:"modal-box",children:[jsxRuntime.jsx("h3",{class:"font-bold text-lg mb-3",children:"Bulk update field"}),jsxRuntime.jsx("p",{class:"text-sm text-base-content/60 mb-4","data-frs-bulk-update-summary":true,children:"Update one field on the selected documents."}),jsxRuntime.jsxs("form",{method:"dialog","data-frs-bulk-update-form":true,"data-frs-form":true,children:[jsxRuntime.jsxs("label",{class:"form-control w-full mb-3",children:[jsxRuntime.jsx("div",{class:"label",children:jsxRuntime.jsx("span",{class:"label-text text-xs uppercase tracking-wide",children:"Field"})}),jsxRuntime.jsxs("select",{class:"select select-bordered select-sm w-full",name:"field",required:true,"data-frs-bulk-field-select":true,children:[jsxRuntime.jsx("option",{value:"",children:"\u2014 Select a field \u2014"}),w.map(S=>jsxRuntime.jsx("option",{value:S,children:S},S))]})]}),jsxRuntime.jsx("div",{class:"mb-4","data-frs-bulk-value-container":true}),jsxRuntime.jsxs("div",{class:"modal-action",children:[jsxRuntime.jsx("button",{type:"button",class:"btn btn-sm btn-ghost","data-frs-bulk-update-cancel":true,children:"Cancel"}),jsxRuntime.jsx("button",{type:"submit",class:"btn btn-sm btn-primary","data-frs-bulk-update-submit":true,children:"Apply"})]})]})]}),jsxRuntime.jsx("form",{method:"dialog",class:"modal-backdrop",children:jsxRuntime.jsx("button",{children:"close"})})]}),jsxRuntime.jsx("div",{class:"hidden","data-frs-bulk-templates":true,children:A.map(S=>jsxRuntime.jsx("div",{"data-frs-bulk-template-for":S.name,dangerouslySetInnerHTML:{__html:Ve(S)}},S.name))})]}))}var Lo="";function et(e,t){return Ut(e,t)}function Jt(e,t){return Kt(e,t)}function Xt(e,t,n,r,o,s,a,l,c,y,v,x,T,R,b,k,h,g){return Gt(e,t,n,r,o,s,a,l,c,y,v,x,T,R,b,k,h,g)}function ve(e,t,n,r,o,s){return Wt(e,t,n,r,o,s)}var Yt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Vo(){let e="";for(;e.length<20;){let t=crypto.randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let r=t[n];r>=Yt.length*4||(e+=Yt.charAt(r%Yt.length));}}return e}async function Jn(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 yt(e,t){if(!t)return;let n=e[t];if(typeof n!="string"||!n)return;let r=n.split("/").filter(Boolean),o=[];for(let s=1;s<r.length;s+=2)o.push(r[s]);return o.length>0?o:void 0}async function $e(e,t){let n=e.documentKey??"docId",r=`by${n.charAt(0).toUpperCase()}${n.slice(1)}`;if(typeof e.repo.get[r]=="function")try{let s=await e.repo.get[r](t);if(s)return s}catch{}return (await e.repo.query.by({where:[[n,"==",t]],limit:1}))[0]??null}function en(e,t,n){let r=e.documentKey??"docId",o=We(n,{ref:e.repo.ref,path:e.path,isGroup:!!e.isGroup,filters:[{field:r,op:"==",value:t}]});return o.type==="index"?{type:"warning",message:"Loading this document requires a composite index that does not exist yet.",...o.indexUrl?{action:{href:o.indexUrl,label:"Create Index \u2192",external:true}}:{}}:{type:"error",message:o.message}}function z(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function mt(e,t){e.status(302).set("Location",t).send("");}function ht(e,t){let n=t.shape,r={};for(let[o,s]of Object.entries(n)){let a=nn(s),l=Z(a),c=l==="ZodObject",y=a,v=false;if(l==="ZodUnion"){let R=Le(a);R.some(k=>Z(k)==="ZodDate")&&(v=true);let b=R.find(k=>{if(Z(k)==="ZodObject"){let h=ee(k);return "latitude"in h&&"longitude"in h}return false});b&&(c=true,y=b);}if(e[o+"__isnull"]==="1"){r[o]=null;continue}if(c){let R={},b=false;for(let[g,u]of Object.entries(e))g.startsWith(`${o}.`)&&(R[g.slice(o.length+1)]=u,b=true);if(b){r[o]=ht(R,y);continue}let k=e[o],h=Array.isArray(k)?k[k.length-1]:k;if(h)try{r[o]=JSON.parse(h);}catch{r[o]=h;}continue}let x=e[o],T=Array.isArray(x)?x[x.length-1]:x;if(T===void 0||T===""){l==="ZodBoolean"&&(r[o]=false);continue}if(v){r[o]=new Date(T);continue}switch(l){case "ZodBoolean":T==="__null__"?r[o]=null:r[o]=T==="true"||T==="on"||T==="1";break;case "ZodNumber":case "ZodBigInt":r[o]=Number(T);break;case "ZodDate":r[o]=new Date(T);break;case "ZodArray":try{r[o]=JSON.parse(T);}catch{r[o]=T;}break;default:if(T.startsWith("{")||T.startsWith("["))try{r[o]=JSON.parse(T);break}catch{}r[o]=T;}}return r}function Xn(e){let t=null;if(e instanceof Date)t=e;else if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")t=e.toDate();else if(typeof e=="object"&&e!==null&&"_seconds"in e&&"_nanoseconds"in e)t=new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));else if(typeof e=="string"||typeof e=="number"){let r=new Date(e);isNaN(r.getTime())||(t=r);}if(!t||isNaN(t.getTime()))return null;let n=r=>String(r).padStart(2,"0");return `${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function er(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=Y(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=ze(t);if(!r)return n;t=r;}else return n}}function nn(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=Y(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=ze(t);if(!r)return t;t=r;}else return t}}function tr(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable")return true;if(n==="ZodDefault"){t=Y(t);continue}return false}}function nr(e){let t=nn(e),n=Z(t);if(n==="ZodEnum"){let r=Be(t);return r.length>0?r:void 0}if(n==="ZodNativeEnum"){let r=qe(t),o=Object.values(r).filter(s=>typeof s=="string");return o.length>0?o:void 0}if(n==="ZodLiteral"){let r=Ze(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 l=nn(t.shape[o]),c=Z(l),y=c==="ZodObject",v=l,x=false;if(c==="ZodUnion"){let T=Le(l);T.some(b=>Z(b)==="ZodDate")&&(x=true);let R=T.find(b=>{if(Z(b)==="ZodObject"){let k=ee(b);return "latitude"in k&&"longitude"in k}return false});R&&(y=true,v=R);}if(y&&typeof a=="object"&&a!==null&&!Array.isArray(a)&&!("_seconds"in a)&&typeof a.toDate!="function"){let T=rr(a,v,s);Object.assign(r,T);}else if(c==="ZodDate"||x){let T=Xn(a);T!==null&&(r[s]=T);}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)&&("_seconds"in a||typeof a.toDate=="function")){let T=Xn(a);r[s]=T??JSON.stringify(a,null,2);}else typeof a=="object"?r[s]=JSON.stringify(a,null,2):r[s]=String(a);}return r}function tn(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?tn(n.nested,t):void 0}))}function Wo(e,t){let n=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),r=[];for(let[o,s]of Object.entries(e)){if(!o.startsWith("fv_"))continue;let a=o.slice(3);if(!t.has(a))continue;let l=(s??"").trim();if(!l)continue;let c=e[`fo_${a}`]??"==",y=n.has(c)?c:"==";r.push({field:a,op:y,value:l});}return r}function Yn(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 or(e,t,n=""){let r=[];for(let o of e){let s=n?`${n}.${o}`:o,a=t.shape[o];if(!a){r.push({name:s,zodType:"ZodString"});continue}let l=er(a);if(l==="ZodObject"){let c=a;for(;;){let v=Z(c);if(v==="ZodOptional"||v==="ZodNullable"||v==="ZodDefault")c=Y(c);else break}let y=ee(c);r.push(...or(Object.keys(y),c,s));}else r.push({name:s,zodType:l,nullable:tr(a),enumValues:nr(a)});}return r}function Qo(e,t){let n=t.split("."),r=e;for(let o of n){for(;;){let a=Z(r);if(a==="ZodOptional"||a==="ZodNullable"||a==="ZodDefault")r=Y(r);else break}let s=ee(r);if(!(o in s))return null;r=s[o];}return r}function ke(e,t){if(!t||t.length===0)return e;let n=[],r=new Map;for(let s of t){let a=s.indexOf(".");if(a===-1)n.push(s);else {let l=s.slice(0,a),c=s.slice(a+1);r.has(l)||r.set(l,[]),r.get(l).push(c);}}let o={};for(let s of n)s in e.shape&&(o[s]=e.shape[s]);for(let[s,a]of r){if(!(s in e.shape))continue;let l=e.shape[s];for(;;){let c=Z(l);if(c==="ZodOptional"||c==="ZodNullable"||c==="ZodDefault")l=Y(l);else break}if(Z(l)!=="ZodObject"){o[s]=e.shape[s];continue}o[s]=ke(l,a);}return zod.z.object(o)}function ce(e,t,n){return ie(e,t,n)}function sr(e,t,n){let r=(f,i)=>{let w=ce(f,t,n),d=Object.values(e).map(m=>({name:m.name,path:m.path}));z(i,Jt(d,w));},o=async(f,i)=>{let w=f.params.repoName;if(!w){z(i,"Bad request",400);return}let d=e[w];if(!d){z(i,"Repository not found",404);return}let m=d.pageSize??25,p=f.query??{},O=p.cursor,A=p.dir==="prev"?"prev":"next",S=p.ob??"",P=p.od==="desc"?"desc":"asc",E=S?{field:S,dir:P}:void 0,I=parseInt(p.ps??""),C=Number.isFinite(I)&&I>0?Math.min(I,200):m,$=d.listColumns??Object.keys(d.schema.shape),j=d.documentKey??"docId",N=[j,...$.filter(re=>re!==j)];E&&(new Set([j,...$]).has(E.field)||(E=void 0));let F=d.filterableFields?(()=>{let re=[];for(let de of d.filterableFields)(de.includes(".")||$.includes(de))&&re.push(de);return re})():$,_=(()=>{let re=[];for(let de of F)if(de.includes(".")){let Ce=Qo(d.schema,de);re.push({name:de,zodType:Ce?er(Ce):"ZodString",nullable:Ce?tr(Ce):false,enumValues:Ce?nr(Ce):void 0});}else re.push(...or([de],d.schema));return re})(),V=new Set(_.map(re=>re.name)),K=Wo(p,V),G=Yn(K),je;O&&(je=await Jn(d,O));let[J,st]=await Promise.all([d.repo.query.paginate({pageSize:C,cursor:je,direction:A,...G.length>0?{where:G}:{},...E?{orderBy:[{field:E.field,direction:E.dir}]}:{}}).catch(re=>({queryError:We(re,{ref:d.repo.ref,path:d.path,isGroup:!!d.isGroup,filters:K,sort:E})})),d.repo.aggregate.count(G.length>0?{where:G}:{}).catch(()=>{})]),Ae="queryError"in J,Pr=Ae?[]:J.data,$r=Ae?"":J.nextCursor?.ref?.path??J.nextCursor?.id??"",Ir=Ae?"":J.prevCursor?.ref?.path??J.prevCursor?.id??"",Dr=Ae?J.queryError:void 0,_r=ce(f,t,n),Fe,at=p.flash;at==="created"?Fe={type:"success",message:"Document created successfully."}:at==="updated"?Fe={type:"success",message:"Document updated successfully."}:at==="deleted"?Fe={type:"success",message:"Document deleted successfully."}:at==="backfilled"&&(Fe={type:"success",message:"Repository backfilled successfully."}),z(i,Xt(d.name,Pr,N,_r,{hasPrev:Ae?false:J.hasPrevPage,hasNext:Ae?false:J.hasNextPage,prevCursor:Ir,nextCursor:$r},Fe,_,K,d.allowDelete??false,d.relationalMeta,E,C,Dr,d.isGroup,st,d.mutableFields,d.schema,d.historyEnabled));},s=(f,i)=>{let w=f.params.repoName;if(!w){z(i,"Bad request",400);return}let d=e[w];if(!d){z(i,"Repository not found",404);return}let m=ce(f,t,n),p=ke(d.schema,d.createFields),O=se(p),A=`${m}/${d.name}/create`,S=he(O,A,"POST","Create document");z(i,ve(d.name,S,"create",null,m));},a=async(f,i)=>{let w=f.params.repoName;if(!w){z(i,"Bad request",400);return}let d=e[w];if(!d){z(i,"Repository not found",404);return}let m=ce(f,t,n),p=f.body??{},O=ht(p,d.schema),A=ke(d.schema,d.createFields),S=A.safeParse(O);if(!S.success){let P=se(A),E=`${m}/${d.name}/create`,I=he(P,E,"POST","Create document"),C=S.error.issues.map($=>`${$.path.join(".")}: ${$.message}`).join(", ");z(i,ve(d.name,I,"create",null,m,{type:"error",message:`Validation error: ${C}`}),422);return}try{if(d.isGroup&&d.parentKeys&&d.parentKeys.length>0){let P={...S.data};d.createdKey&&(P[d.createdKey]=new Date);let E=d.parentKeys.filter(j=>!P[j]);if(E.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${E.join(", ")}`);let I=d.parentKeys.map(j=>P[j]),C=d.documentKey??"docId",$=P[C]||Vo();await d.repo.set(...I,$,P);}else await d.repo.create(S.data);mt(i,`${m}/${d.name}?flash=created`);}catch(P){let E=ke(d.schema,d.createFields),I=se(E),C=`${m}/${d.name}/create`,$=he(I,C,"POST","Create document");z(i,ve(d.name,$,"create",null,m,{type:"error",message:`Save error: ${P.message}`}),500);}},l=async(f,i)=>{let w=f.params.repoName,d=f.params.id;if(!w||!d){z(i,"Bad request",400);return}let m=e[w];if(!m){z(i,"Repository not found",404);return}let p=ce(f,t,n),O=null;try{O=await $e(m,d);}catch(C){let $=en(m,d,C),j=Se(C)?424:500;z(i,et("",{title:`Edit ${m.name} / ${d}`,basePath:p,breadcrumb:[{label:"Repositories",href:p},{label:m.name,href:`${p}/${m.name}`},{label:`Edit ${d}`}],flash:$}),j);return}if(!O){z(i,"Document not found",404);return}let A=rr(O,m.schema),S=ke(m.schema,m.mutableFields),P=tn(se(S),A),E=`${p}/${m.name}/${encodeURIComponent(d)}/edit`,I=he(P,E,"POST","Save changes");z(i,ve(m.name,I,"edit",d,p));},c=async(f,i)=>{let w=f.params.repoName,d=f.params.id;if(!w||!d){z(i,"Bad request",400);return}let m=e[w];if(!m){z(i,"Repository not found",404);return}let p=ce(f,t,n),O=f.body??{},A=ht(O,m.schema),S=ke(m.schema,m.mutableFields),E=S.partial().safeParse(A);if(!E.success){let I=Object.fromEntries(Object.entries(O).map(([F,_])=>[F,Array.isArray(_)?_.join(","):_??""])),C=tn(se(S),I),$=`${p}/${m.name}/${encodeURIComponent(d)}/edit`,j=he(C,$,"POST","Save changes"),N=E.error.issues.map(F=>`${F.path.join(".")}: ${F.message}`).join(", ");z(i,ve(m.name,j,"edit",d,p,{type:"error",message:`Validation error: ${N}`}),422);return}try{let I=await $e(m,d),C=(I&&yt(I,m.pathKey))??[d];await m.repo.update(...C,E.data),mt(i,`${p}/${m.name}?flash=updated`);}catch(I){let C=ke(m.schema,m.mutableFields),$=se(C),j=`${p}/${m.name}/${encodeURIComponent(d)}/edit`,N=he($,j,"POST","Save changes"),F=Se(I)?en(m,d,I):{type:"error",message:`Save error: ${I.message}`},_=Se(I)?424:500;z(i,ve(m.name,N,"edit",d,p,F),_);}},y=async(f,i)=>{let w=f.params.repoName,d=f.params.id;if(!w||!d){z(i,"Bad request",400);return}let m=e[w];if(!m){z(i,"Repository not found",404);return}if(!m.allowDelete){z(i,"Delete is not allowed for this repository",403);return}let p=ce(f,t,n);try{let O=await $e(m,d),A=(O&&yt(O,m.pathKey))??[d];await m.repo.delete(...A),mt(i,`${p}/${m.name}?flash=deleted`);}catch(O){let A=Se(O)?en(m,d,O):{type:"error",message:`Delete error: ${O.message}`},S=Se(O)?424:500;z(i,et("",{title:`Delete ${m.name} / ${d}`,basePath:p,breadcrumb:[{label:"Repositories",href:p},{label:m.name,href:`${p}/${m.name}`},{label:`Delete ${d}`}],flash:A}),S);}},v=async(f,i)=>{let w=f.params.repoName;if(!w){z(i,"Bad request",400);return}let d=e[w];if(!d){z(i,"Repository not found",404);return}let m=ce(f,t,n),p=f.query,O=p?.type==="many"?"many":"one",A=Math.max(1,Math.min(100,Number(p?.ps??25)||25)),S=d.listColumns??Object.keys(ee(d.schema)),{PanelOne:P,PanelMany:E}=await Promise.resolve().then(()=>(Lt(),Vn)),{renderToString:I}=await import('hono/jsx/dom/server');if(O==="one"){let _=String(p?.id??"");if(!_){z(i,"<div class='p-6 text-error'>Missing id parameter.</div>",400);return}try{let V=await $e(d,_),K=I(P({doc:V,repoName:d.name,basePath:m,schema:d.schema,columns:S}));z(i,K);}catch(V){z(i,`<div class='p-6 text-error text-sm'>Error: ${V.message}</div>`,500);}return}let C=String(p?.fk??""),$=String(p?.fv??"");if(!C||!$){z(i,"<div class='p-6 text-error'>Missing fk/fv parameters.</div>",400);return}let j=p?.cursor??"",N=p?.dir==="prev"?"prev":"next",F;j&&(F=await Jn(d,j));try{let _=await d.repo.query.paginate({pageSize:A,cursor:F,direction:N,where:[[C,"==",Go($)]]}),V=I(E({docs:_.data,repoName:d.name,basePath:m,fk:C,fv:$,columns:S,schema:d.schema,pagination:{hasPrev:_.hasPrevPage,hasNext:_.hasNextPage,prevCursor:_.prevCursor?.ref?.path??_.prevCursor?.id??"",nextCursor:_.nextCursor?.ref?.path??_.nextCursor?.id??"",pageSize:A}}));z(i,V);}catch(_){z(i,`<div class='p-6 text-error text-sm'>Error: ${_.message}</div>`,500);}},x=async(f,i)=>{let w=f.params.repoName;if(!w){z(i,"Bad request",400);return}let d=e[w];if(!d){z(i,"Repository not found",404);return}let m=ce(f,t,n);try{await d.repo.system.backfillKeys(),mt(i,`${m}/${d.name}?flash=backfilled`);}catch(p){z(i,`<div class="p-6 text-error">Backfill failed: ${p.message}</div>`,500);}},T=async(f,i)=>{let w=[];for(let d of i){let m;if(f.isGroup||f.parentKeys?.length){let p=await $e(f,d);m=p?yt(p,f.pathKey):void 0;}m||(m=[d]);try{let p=f.repo.documentRef(...m);p&&w.push(p);}catch{}}return w},R=async(f,i)=>{let w=Yn(i),d=f.documentKey??"docId",m=[],p;for(;;){let O=await f.repo.query.paginate({pageSize:500,cursor:p,direction:"next",...w.length>0?{where:w}:{}});for(let A of O.data){let S=String(A[d]??A.id??"");S&&m.push(S);}if(!O.hasNextPage||!O.nextCursor)break;p=O.nextCursor;}return m},b=async(f,i)=>{let w=f.params.repoName;if(!w){ne(i,{error:"Bad request"},400);return}let d=e[w];if(!d){ne(i,{error:"Repository not found"},404);return}if(!d.allowDelete){ne(i,{error:"Delete is not allowed for this repository"},403);return}let m=f.body??{};try{let p=await h(d,m);if(p.length===0){ne(i,{deleted:0});return}let O=await T(d,p);for(let A=0;A<O.length;A+=500)await d.repo.bulk.delete(O.slice(A,A+500));ne(i,{deleted:O.length});}catch(p){ne(i,{error:p.message},500);}},k=async(f,i)=>{let w=f.params.repoName;if(!w){ne(i,{error:"Bad request"},400);return}let d=e[w];if(!d){ne(i,{error:"Repository not found"},404);return}let m=f.body??{},p=String(m.field??"");if(!p){ne(i,{error:"Missing 'field'"},400);return}if(!d.mutableFields||!d.mutableFields.includes(p)){ne(i,{error:`Field '${p}' is not bulk-updatable`},403);return}let O=d.schema.shape?.[p],A;if(O){let S=typeof d.schema=="object"&&d.schema&&"constructor"in d.schema&&d.schema.constructor.name.includes("Zod")?d.schema.pick({[p]:true}):void 0;if(!S){ne(i,{error:"Invalid schema structure"},500);return}A=ht(m.formPayload??{},S)[p];let E=O.safeParse(A);if(!E.success){ne(i,{error:`Invalid value for '${p}': ${E.error.message}`},400);return}A=E.data;}try{let S=await h(d,m);if(S.length===0){ne(i,{updated:0});return}let E=(await T(d,S)).map(I=>({docRef:I,data:{[p]:A}}));for(let I=0;I<E.length;I+=500)await d.repo.bulk.update(E.slice(I,I+500));ne(i,{updated:E.length});}catch(S){ne(i,{error:S.message},500);}};async function h(f,i){if(i.selectAll){let w=g(i.filters,f);return await R(f,w)}return Array.isArray(i.ids)?i.ids.filter(w=>typeof w=="string"&&!!w):[]}function g(f,i){if(!Array.isArray(f))return [];let w=new Set((i.filterableFields??Object.keys(ee(i.schema))).map(p=>String(p))),d=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),m=[];for(let p of f)p&&typeof p=="object"&&typeof p.field=="string"&&w.has(p.field)&&typeof p.value=="string"&&d.has(String(p.op))&&m.push({field:p.field,op:p.op,value:p.value});return m}return {handleDashboard:r,handleList:o,handleCreateForm:s,handleCreateSubmit:a,handleEditForm:l,handleEditSubmit:c,handleDelete:y,handlePanel:v,handleBulkDelete:b,handleBulkUpdate:k,handleBulkBackfill:x,handleHistory:async(f,i)=>{let w=f.params.repoName,d=f.params.id;if(!w||!d){z(i,"Bad request",400);return}let m=e[w];if(!m){z(i,"Repository not found",404);return}if(!m.historyEnabled||!m.repo.history){z(i,"History not enabled for this repository",404);return}let p=ce(f,t,n),O=m.historySubcollection??"history",A=[d];try{let _=await $e(m,d),V=_?yt(_,m.pathKey):void 0;V&&V.length>0&&(A=V);}catch{}let S=parseInt(String(f.query?.limit??"")),P=Number.isFinite(S)&&S>0?Math.min(S,500):100,E=[],I;try{E=await m.repo.history.list(...A,{limit:P});}catch(_){I=_.message;}let C=_=>String(_??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),$=_=>{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">${C(JSON.stringify(_))}</code>`}catch{return C(String(_))}return C(String(_))},j=_=>_?typeof _.toDate=="function"?_.toDate().toISOString():_ instanceof Date?_.toISOString():C(String(_)):"",N=_=>`<span class="badge badge-sm ${_==="create"?"badge-success":_==="delete"?"badge-error":"badge-info"}">${C(_)}</span>`,F="";if(F+='<div class="flex items-center justify-between mb-4">',F+=`<a href="${p}/${m.name}/${encodeURIComponent(d)}/edit" class="btn btn-sm btn-outline">\u2190 Back to edit</a>`,F+=`<a href="${p}/${m.name}" class="btn btn-sm btn-outline">\u2190 Back to list</a>`,F+="</div>",F+=`<p class="text-sm text-base-content/60 mb-4">Subcollection: <code>${C(O)}</code> \xB7 Showing up to ${P} entries.</p>`,I)F+=`<div class="alert alert-error mb-4">${C(I)}</div>`;else if(E.length===0)F+='<div class="alert">No history entries found.</div>';else {F+='<div class="overflow-x-auto"><table class="table table-zebra table-sm">',F+="<thead><tr><th>When</th><th>Op</th><th>User</th><th>Reason / Comment</th><th>Changes</th></tr></thead><tbody>";for(let _ of E){let V=_.meta??{},K=[V.reason,V.comment].filter(J=>J!=null&&J!=="").map(J=>C(String(J))).join(" \u2014 "),G="",je=Object.keys(_.changes??{});je.length===0?G='<span class="opacity-40">\u2014</span>':G='<ul class="space-y-1">'+je.map(J=>{let st=_.changes[J];return `<li><strong>${C(J)}</strong>: ${$(st.oldValue)} \u2192 ${$(st.newValue)}</li>`}).join("")+"</ul>",F+="<tr>",F+=`<td class="whitespace-nowrap text-xs font-mono">${C(j(_.historySetAt))}</td>`,F+=`<td>${N(_.operation??"update")}</td>`,F+=`<td class="text-xs">${C(V.userEmail??V.userId??"")}</td>`,F+=`<td class="text-xs">${K}</td>`,F+=`<td>${G}</td>`,F+="</tr>";}F+="</tbody></table></div>";}z(i,et(F,{title:`History \u2014 ${m.name} / ${d}`,basePath:p,breadcrumb:[{label:"Repositories",href:p},{label:m.name,href:`${p}/${m.name}`},{label:`History ${d}`}]}));}}}function ne(e,t,n=200){e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(t));}function Go(e){return e==="true"?true:e==="false"?false:e!==""&&!isNaN(Number(e))?Number(e):e}bt();async function Jo(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function Xo(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 lr(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,auth:s,middleware:a=[],httpsOptions:l}=e,c=t==="/"?"":t.replace(/\/$/,""),y={};for(let[R,b]of Object.entries(n)){if(!b.repo)throw new Error(`[createAdminServer] Repository "${R}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let k=b.schema??b.repo.schema??null;if(!k)throw new Error(`[createAdminServer] Repository "${R}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let h,g,u;if(b.fieldsConfig){let w=b.fieldsConfig;h=[],g=[],u=[];for(let[d,m]of Object.entries(w))for(let p of m)p==="filterable"?h.push(d):p==="mutable"?g.push(d):p==="create"&&u.push(d);h.length===0&&(h=void 0),g.length===0&&(g=void 0),u.length===0&&(u=void 0);}let f=(()=>{let w=b.repo._parentKeys;return w&&w.length>0?w:void 0})();if(f&&u)for(let w of f)u.includes(w)||u.push(w);let i={name:R,path:b.path,repo:b.repo,schema:k,documentKey:b.documentKey??"docId",pathKey:b.repo._pathKey??void 0,isGroup:!!b.repo._isGroup,parentKeys:f,createdKey:b.repo._createdKey??void 0,listColumns:b.listColumns,pageSize:b.pageSize,filterableFields:h,mutableFields:g,createFields:u,allowDelete:b.allowDelete??false,historyEnabled:!!b.repo._historyConfig?.enabled,historySubcollection:(b.repo._historyConfig?.enabled&&b.repo._historySubcollection)??void 0,relationalMeta:(()=>{if(!b.relationalFields||b.relationalFields.length===0)return;let w=b.repo.relationalKeys??{},d=[];for(let m of b.relationalFields){let p=w[m.key];p&&d.push({key:p.sourceKey?String(p.sourceKey):m.key,column:m.column,targetRepo:String(p.repo),targetKey:String(p.key),type:p.type});}return d.length>0?d:void 0})()};y[R]=i;}let v=sr(y,c,xn(l?.region)),x=new ye;if(o!==false&&x.use(gt(o===void 0?{}:o)),r&&x.use(async(R,b,k)=>{let h=R,g=String(h.headers?.["content-type"]??"");if(g.includes("application/x-www-form-urlencoded")){let u=await Jo(h);R.body=Xo(u);}else if(g.includes("application/json")&&typeof h.body=="string")try{R.body=JSON.parse(h.body);}catch{}await k();}),s)if(He(s)){for(let R of s.routes){let b=`${c}${R.path}`;R.method==="GET"?x.get(b,R.handler):x.post(b,R.handler);}x.use(s.middleware);}else if(typeof s=="function")x.use(s);else {let R=s.realm??"Admin",b="Basic "+Buffer.from(`${s.username}:${s.password}`).toString("base64");x.use((k,h,g)=>{if((k.headers?.authorization??"")!==b){h.status(401).set("WWW-Authenticate",`Basic realm="${R}"`).set("Content-Type","text/plain").send("Unauthorized");return}g();});}for(let R of a)x.use(R);x.get(`${c}/`,v.handleDashboard),x.get(`${c}`,v.handleDashboard),x.get(`${c}/:repoName/_panel`,v.handlePanel),x.post(`${c}/:repoName/_bulk/delete`,v.handleBulkDelete),x.post(`${c}/:repoName/_bulk/update`,v.handleBulkUpdate),x.post(`${c}/:repoName/_bulk/backfill`,v.handleBulkBackfill),x.get(`${c}/:repoName`,v.handleList),x.get(`${c}/:repoName/create`,v.handleCreateForm),x.post(`${c}/:repoName/create`,v.handleCreateSubmit),x.get(`${c}/:repoName/:id/edit`,v.handleEditForm),x.post(`${c}/:repoName/:id/edit`,v.handleEditSubmit),x.get(`${c}/:repoName/:id/history`,v.handleHistory),x.post(`${c}/:repoName/:id/delete`,v.handleDelete);let T=async(R,b)=>{await x.handle(R,b);};return l&&(T.httpsOptions=l),T}function an(e,t,n=200){let r=xe(t);return e.json(r,n)}function Te(e,t,n,r=200){return an(e,{success:true,data:t,meta:n},r)}function M(e,t,n=400){return an(e,{success:false,error:t},n)}function on(e,t,n,r,o){let s=We(t,n),a=s.type==="index",l=a?424:500,y={success:false,error:a?s.message:o&&t instanceof Error?t.message:r};return a&&(y.errorType="index",s.indexUrl&&(y.indexUrl=s.indexUrl)),an(e,y,l)}var sn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function dr(){let e="";for(;e.length<20;){let t=crypto.randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let r=t[n];r>=sn.length*4||(e+=sn.charAt(r%sn.length));}}return e}function Ie(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return zod.z.preprocess(r=>wn(r)??r,e);if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[s,a]of Object.entries(r))o[s]=Ie(a);return zod.z.object(o)}if(n==="ZodArray"||n==="array"){let r=t.element??t.type;if(r)return zod.z.array(Ie(r))}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(r)return Ie(r).optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(r)return Ie(r).nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType,o=t.defaultValue;if(r){let s=Ie(r);return typeof o=="function"?s.default(o()):s.default(o)}}return e}function es(e,t,n=[]){let r=e.shape,o={},s=t&&t.length>0?t:Object.keys(r);for(let a of s){if(n.includes(a))continue;let l=a.split(".")[0];l&&r[l]&&(o[l]=r[l]);}return zod.z.object(o)}function wt(e,t,n,r=false,o=[]){try{let s=es(e,n,o),a=r?s.partial():s;return {success:!0,data:(bn()==="normalize"?Ie(a):a).parse(t)}}catch(s){return s instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${s.issues.map(l=>`${l.path.join(".")}: ${l.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function vt(e,t,n){let r=e?.shape?.[t];if(!r||typeof r.safeParse!="function")return {success:true,data:n};let o=r.safeParse(n);if(o.success)return {success:true,data:o.data};if(Array.isArray(n)){let a=[];for(let l of n){let c=r.safeParse(l);if(c.success)a.push(c.data);else return {success:false,error:c.error.issues.map(v=>v.message).join(", ")}}return {success:true,data:a}}return {success:false,error:o.error.issues.map(a=>a.message).join(", ")}}function ts(e,t){let n=[],r=t?new Set(t):null,o={eq:"==",ne:"!=",lt:"<",lte:"<=",gt:">",gte:">=",in:"in",nin:"not-in",contains:"array-contains",containsAny:"array-contains-any"};for(let[s,a]of Object.entries(e)){if(a===void 0||["cursor","limit","pageSize","orderBy","orderDir","select"].includes(s))continue;let l=Array.isArray(a)?a[0]:a;if(l===void 0||l==="")continue;let c=s.match(/^(\w+)__(\w+)$/),y,v="==";if(c&&c[1]&&c[2]){y=c[1];let T=c[2];if(o[T])v=o[T];else continue}else if(!c)y=s;else continue;if(r&&!r.has(y))continue;let x=l;v==="in"||v==="not-in"||v==="array-contains-any"?x=l.split(",").map(T=>ur(T.trim())):x=ur(l),n.push({field:y,op:v,value:x});}return n}function ur(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 xt(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function pr(e,t){if(!t)return;let n;if(typeof t=="string")try{n=JSON.parse(t);}catch{n=t.includes("/")?{docPath:t}:{docId:t};}else typeof t=="object"&&(n=t);if(!n)return;let r=typeof n.docPath=="string"?n.docPath:void 0,o=typeof n.docId=="string"?n.docId:void 0;try{let s=e.repo.ref,a=s?.firestore;if(r&&a&&typeof a.doc=="function"){let l=await a.doc(r).get();if(l.exists)return l}if(o&&o.includes("/")&&a&&typeof a.doc=="function"){let l=await a.doc(o).get();if(l.exists)return l}if(o&&typeof s.doc=="function"){let l=await s.doc(o).get();if(l.exists)return l}return}catch{return}}function fr(e,t,n){async function r(g,u,f,i){if(!u.rules)return true;let w=u.rules?.[f];if(!w)return M(g,`Operation "${f}" is not allowed for this repository`,403),false;try{return await w(i)?!0:M(g,"Forbidden",403)}catch(d){let m=n&&d instanceof Error?d.message:"Forbidden";return M(g,m,403)}}async function o(g,u,f,i){if(!g.rules)return i;let w=g.rules?.filter;if(!w)return i;let d=[];for(let m of i)try{await w({user:u,doc:m,params:f})&&d.push(m);}catch{}return d}function s(g){return g.get("user")??g.get("docsUser")??null}function a(g,u){if(!g){let f=u.req.path.split("/");for(let i of f)if(e[i]){g=i;break}}return !g||!e[g]?null:e[g]??null}function l(g,u){if(!u)return;let f=g[u];if(typeof f!="string"||!f)return;let i=f.split("/").filter(Boolean),w=[];for(let d=1;d<i.length;d+=2)w.push(i[d]);return w.length>0?w:void 0}async function c(g,u){let f=`by${g.documentKey.charAt(0).toUpperCase()}${g.documentKey.slice(1)}`,i=g.repo.get[f];if(typeof i=="function")try{let d=await i(u);if(d)return d}catch{}return (await g.repo.query.by({where:[[g.documentKey,"==",u]],limit:1}))[0]??null}async function y(g){let u=g.c,f=u.req.param(),i=a(f.repoName,u);if(!i)return M(u,"Repository not found",404);let w=s(u);if(!await r(u,i,"list",{user:w,query:u.req.query(),params:f}))return;let d=[],m;try{let p=u.req.query(),O=Math.min(Number(p.pageSize)||i.pageSize,100),A=p.cursor,S=p.direction?.toLowerCase()==="prev"?"prev":"next",P=p.orderBy,E=p.orderDir?.toLowerCase()==="desc"?"desc":"asc",I=p.select,C=I?I.split(",").map(K=>K.trim()):void 0,$;i.allowedIncludes&&p.includes&&($=(typeof p.includes=="string"?p.includes.split(",").map(G=>G.trim()):Array.isArray(p.includes)?p.includes:[]).filter(G=>typeof G=="string"&&i.allowedIncludes.includes(G)),$?.length===0&&($=void 0));let j=ts(p,i.filterableFields);d=j.map(K=>({field:K.field,op:K.op,value:String(K.value??"")})),P&&(m={field:P,dir:E});let N={pageSize:O,direction:S};if(A)try{let K=typeof A=="string"?JSON.parse(A):A;N.cursor=await pr(i,K);}catch{}if(P){if(i.orderableFields&&!i.orderableFields.includes(P))return M(u,`Field not orderable: ${P}`,400);N.orderBy=[{field:P,direction:E}];}if(j.length>0){N.where=[];for(let K of j){let G=vt(i.schema,K.field,K.value);if(!G.success)return M(u,`Invalid filter value for '${K.field}': ${G.error}`,400);N.where.push([K.field,K.op,G.data]);}}C&&(N.select=C),$&&(N.include=$);let F=await i.repo.query.paginate(N),V={items:await o(i,s(u),f,F.data),hasNextPage:F.hasNextPage,hasPrevPage:F.hasPrevPage,nextCursor:xt(F.nextCursor),prevCursor:xt(F.prevCursor)};return Te(u,V,{pageSize:O,hasMore:F.hasNextPage})}catch(p){on(u,p,{ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:d,sort:m},"Failed to fetch documents",n);}}async function v(g){let u=g.c,f=u.req.param(),i=a(f.repoName,u);if(!i)return M(u,"Repository not found",404);let w=s(u);if(!await r(u,i,"list",{user:w,query:g.input||{},params:f}))return;let d=[],m;try{let p=g.input||{},O=Math.min(p.pageSize||i.pageSize,100),A=p.direction==="prev"?"prev":"next";p.where&&(d=p.where.map(C=>({field:String(C[0]),op:C[1],value:String(C[2]??"")}))),p.orderBy&&p.orderBy[0]&&(m={field:p.orderBy[0].field,dir:p.orderBy[0].direction==="desc"?"desc":"asc"});let S={pageSize:O,direction:A};if(p.cursor)try{let C=typeof p.cursor=="string"?JSON.parse(p.cursor):p.cursor;S.cursor=await pr(i,C);}catch{}if(i.allowedIncludes&&p.includes&&p.includes.length>0){let C=p.includes.filter($=>typeof $=="string"?i.allowedIncludes.includes($):typeof $=="object"&&$!==null&&"relation"in $&&typeof $.relation=="string"?i.allowedIncludes.includes($.relation):!1);C.length>0&&(S.include=C);}if(p.where&&p.where.length>0){if(i.filterableFields){let $=new Set(i.filterableFields),j=p.where.filter(N=>!$.has(N[0]));if(j.length>0){M(u,`Fields not filterable: ${j.map(N=>N[0]).join(", ")}`,400);return}}let C=[];for(let $ of p.where){let j=vt(i.schema,$[0],$[2]);if(!j.success){M(u,`Invalid filter value for '${$[0]}': ${j.error}`,400);return}C.push([$[0],$[1],j.data]);}S.where=C;}if(p.orWhere&&p.orWhere.length>0){if(i.filterableFields){let $=new Set(i.filterableFields),j=p.orWhere.filter(N=>!$.has(N[0]));if(j.length>0){M(u,`Fields not filterable: ${j.map(N=>N[0]).join(", ")}`,400);return}}let C=[];for(let $ of p.orWhere){let j=vt(i.schema,$[0],$[2]);if(!j.success){M(u,`Invalid filter value for '${$[0]}': ${j.error}`,400);return}C.push([$[0],$[1],j.data]);}S.orWhere=C;}if(p.orWhereGroups&&p.orWhereGroups.length>0){if(i.filterableFields){let $=new Set(i.filterableFields);for(let j of p.orWhereGroups){let N=j.filter(F=>!$.has(F[0]));if(N.length>0){M(u,`Fields not filterable: ${N.map(F=>F[0]).join(", ")}`,400);return}}}let C=[];for(let $ of p.orWhereGroups){let j=[];for(let N of $){let F=vt(i.schema,N[0],N[2]);if(!F.success){M(u,`Invalid filter value for '${N[0]}': ${F.error}`,400);return}j.push([N[0],N[1],F.data]);}C.push(j);}S.orWhereGroups=C;}if(p.orderBy&&p.orderBy.length>0){if(i.orderableFields){let C=new Set(i.orderableFields),$=p.orderBy.filter(j=>!C.has(j.field));if($.length>0){M(u,`Fields not orderable: ${$.map(j=>j.field).join(", ")}`,400);return}}S.orderBy=p.orderBy;}p.select&&p.select.length>0&&(S.select=p.select);let P=await i.repo.query.paginate(S),I={items:await o(i,s(u),f,P.data),hasNextPage:P.hasNextPage,hasPrevPage:P.hasPrevPage,nextCursor:xt(P.nextCursor),prevCursor:xt(P.prevCursor)};return Te(u,I,{pageSize:O,hasMore:P.hasNextPage})}catch(p){on(u,p,{ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:d,sort:m},"Failed to query documents",n);}}async function x(g){let u=g.c,f=u.req.param(),i=a(f.repoName,u);if(!i)return M(u,"Repository not found",404);let w=f.id;if(!w)return M(u,"Document ID required",400);try{let d=await c(i,w);if(!d)return M(u,"Document not found",404);let m=s(u);if(!await r(u,i,"get",{user:m,doc:d,params:f}))return;if(i.rules?.filter)try{if(!await i.rules.filter({user:m,doc:d,params:f}))return M(u,"Document not found",404)}catch{return M(u,"Document not found",404)}return Te(u,d)}catch(d){on(u,d,{ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:[{field:i.documentKey,op:"==",value:w}]},"Failed to fetch document",n);}}async function T(g){let u=g.c,f=u.req.param(),i=a(f.repoName,u);if(!i)return M(u,"Repository not found",404);try{let w=g.input||{},d=s(u);if(!await r(u,i,"create",{user:d,body:w,params:f}))return;let m=wt(i.schema,w,i.createFields,!1,i.systemKeys);if(!m.success)return M(u,m.error,400);if(i.validate){let O=await i.validate(m.data,"create");if(O)return M(u,O,400)}let p;if(i.isGroup&&i.parentKeys&&i.parentKeys.length>0){let O={...m.data};i.createdKey&&(O[i.createdKey]=new Date);let A=i.parentKeys.filter(E=>!O[E]);if(A.length>0){M(u,`Missing parent key(s) for subcollection create: ${A.join(", ")}`,400);return}let S=i.parentKeys.map(E=>O[E]),P=O[i.documentKey]||dr();p=await i.repo.set(...S,P,O);}else p=await i.repo.create(m.data);return Te(u,p,void 0,201)}catch(w){let d=n&&w instanceof Error?w.message:"Failed to create document";return M(u,d,500)}}async function R(g,u){let f=g.c,i=f.req.param(),w=a(i.repoName,f);if(!w)return M(f,"Repository not found",404);let d=i.id;if(!d)return M(f,"Document ID required",400);try{let m=g.input||{},p=await c(w,d);if(!p)return M(f,"Document not found",404);let O=s(f);if(!await r(f,w,"update",{user:O,doc:p,body:m,params:i}))return;let A=wt(w.schema,m,w.mutableFields,u,w.systemKeys);if(!A.success)return M(f,A.error,400);if(w.validate){let E=await w.validate(A.data,"update");if(E)return M(f,E,400)}let S=l(p,w.pathKey)??[d],P=await w.repo.update(...S,A.data);return Te(f,P)}catch(m){let p=n&&m instanceof Error?m.message:"Failed to update document";return M(f,p,500)}}async function b(g){let u=g.c,f=u.req.param(),i=a(f.repoName,u);if(!i)return M(u,"Repository not found",404);if(!i.allowDelete)return M(u,"Delete not allowed for this repository",403);let w=f.id;if(!w)return M(u,"Document ID required",400);try{let d=await c(i,w);if(!d)return M(u,"Document not found",404);let m=s(u);if(!await r(u,i,"delete",{user:m,doc:d,params:f}))return;let p=l(d,i.pathKey)??[w];return await i.repo.delete(...p),Te(u,{deleted:!0})}catch(d){let m=n&&d instanceof Error?d.message:"Failed to delete document";return M(u,m,500)}}function k(g){return g.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 h(g){let u=g.c,f=u.req.param(),i=a(f.repoName,u);if(!i)return M(u,"Repository not found",404);try{let w=g.input||{};if(!Array.isArray(w.operations))return M(u,"operations array is required",400);let d=s(u),m=i.repo.batch.create(),p=[];for(let O of w.operations){if(!O.type||!["create","update","delete"].includes(O.type))return M(u,"Invalid operation type",400);if(O.type==="create"){if(!await r(u,i,"create",{user:d,body:O.data,params:f}))return;let A=wt(i.schema,O.data,i.createFields,!1,i.systemKeys);if(!A.success)return M(u,A.error,400);let S=O.data[i.documentKey]||dr(),P={...A.data};if(i.createdKey&&(P[i.createdKey]=new Date),i.isGroup&&i.parentKeys){let E=i.parentKeys.map(I=>P[I]);m.set(...E,S,P);}else m.set(S,P);p.push({op:"create",id:S});}else if(O.type==="update"){if(!O.id)return M(u,"id required for update",400);let A=await c(i,O.id);if(!A)return M(u,`Document ${O.id} not found`,404);if(!await r(u,i,"update",{user:d,doc:A,body:O.data,params:f}))return;let S=wt(i.schema,O.data,i.mutableFields,!0,i.systemKeys);if(!S.success)return M(u,S.error,400);let P=l(A,i.pathKey)??[O.id];m.update(...P,S.data),p.push({op:"update",id:O.id});}else if(O.type==="delete"){if(!i.allowDelete)return M(u,"Delete not allowed",403);if(!O.id)return M(u,"id required for delete",400);let A=await c(i,O.id);if(!A)return M(u,`Document ${O.id} not found`,404);if(!await r(u,i,"delete",{user:d,doc:A,params:f}))return;let S=l(A,i.pathKey)??[O.id];m.delete(...S),p.push({op:"delete",id:O.id});}}return await m.commit(),Te(u,{results:p})}catch(w){let d=n&&w instanceof Error?w.message:"Batch operation failed";return M(u,d,500)}}return {handleList:y,handleQuery:v,handleGet:x,handleCreate:T,handleUpdate:R,handleDelete:b,handleBatch:h,handleOptions:k}}function St(e){try{return zod.z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=zodToOpenapi.getOpenApiMetadata(t.zodSchema);n&&(Object.assign(t.jsonSchema,n),(t.jsonSchema.anyOf||t.jsonSchema.oneOf)&&delete t.jsonSchema.type);let r=t.zodSchema?._zod?.def;r&&(r.type==="date"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):r.type==="bigint"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf&&(t.jsonSchema.type="string",t.jsonSchema.format="int64"));}})}catch(t){return typeof console<"u"&&console.warn&&console.warn("[generateOpenAPISpec] Failed to convert Zod schema to JSON Schema; falling back to {type:object}.",t),{type:"object"}}}function oe(e){return {$ref:`#/components/schemas/${e}`}}function W(e){return {description:e,content:{"application/json":{schema:oe("ErrorResponse")}}}}function De(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function yr(e){return {description:"Paginated list of documents",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:{type:"object",properties:{items:{type:"array",items:e},nextCursor:{oneOf:[{type:"object"},{type:"null"}]},prevCursor:{oneOf:[{type:"object"},{type:"null"}]},hasNextPage:{type:"boolean"},hasPrevPage:{type:"boolean"}},required:["items","hasNextPage","hasPrevPage"]},meta:{type:"object",properties:{pageSize:{type:"integer"},hasMore:{type:"boolean"},cursor:{oneOf:[{type:"string"},{type:"null"}]}}}},required:["success","data"]}}}}}function nt(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function rs(e,t){let n=t.split("."),r=nt(e);for(let o=0;o<n.length;o++){let s=n[o];if(!s)continue;let a=r?.shape;if(!a||!a[s])return;let l=a[s];if(o===n.length-1)return l;r=nt(l);}return r}function mr(e,t="",n=0){if(n>5)return [];let o=nt(e)?.shape;if(!o)return [];let s=[];for(let[a,l]of Object.entries(o)){let c=t?`${t}.${a}`:a,y=nt(l);y?.shape&&typeof y.shape=="object"?(s.push({path:c,zodSchema:l}),s.push(...mr(y,c,n+1))):s.push({path:c,zodSchema:l});}return s}function dn(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:rs(e.schema,t)})):mr(e.schema)}function ln(e){if(!e)return {type:"string"};let t=St(e);return delete t.$schema,delete t.title,t}function os(e){let t=dn(e),n=e.orderableFields??t.map(r=>r.path);return [{name:"pageSize",in:"query",schema:{type:"integer",default:e.pageSize,maximum:100},description:"Number of items per page"},{name:"cursor",in:"query",schema:{type:"string"},description:"Base64 pagination cursor"},{name:"orderBy",in:"query",schema:{type:"string",...n.length>0?{enum:n}:{}},description:"Field name to order by"},{name:"orderDir",in:"query",schema:{type:"string",enum:["asc","desc"]},description:"Order direction"},{name:"select",in:"query",schema:{type:"string"},description:`Comma-separated list of fields to return${t.length>0?` (${t.map(r=>r.path).join(", ")})`:""}`}]}function ss(e){let t=dn(e),n=["eq","ne","lt","lte","gt","gte","in","nin","contains","containsAny"],r={eq:"equals. Use 'null' or '__null__' to match null values",ne:"not equals. Use 'null' or '__null__' to match non-null values",lt:"less than",lte:"less than or equal",gt:"greater than",gte:"greater than or equal",in:"in list (comma-separated values). Supports 'null' and '__null__' (e.g. val1,val2,__null__)",nin:"not in list (comma-separated values). Supports 'null' and '__null__'",contains:"array-contains",containsAny:"array-contains-any (comma-separated values). Supports 'null' and '__null__'"},o=[];for(let{path:s,zodSchema:a}of t){let l=ln(a);o.push({name:s,in:"query",schema:l,description:`Filter by ${s} (equality). Use 'null' or '__null__' for null values`});for(let c of n){let y=r[c]?` (${r[c]})`:"",v=c==="in"||c==="nin"||c==="containsAny";o.push({name:`${s}__${c}`,in:"query",schema:v?{type:"string",description:"Comma-separated list of values"}:l,description:`Filter ${s} with operator ${c}${y}`});}}return o}function hr(){return {type:"object",properties:{where:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3},description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3},description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3}},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string"},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string"},description:"Fields to select (projection)"},pageSize:{type:"integer",maximum:100,description:"Number of items per page"},cursor:{oneOf:[{type:"string"},{type:"object"}],description:"Pagination cursor"},direction:{type:"string",enum:["next","prev"],description:"Pagination direction"},includes:{type:"array",items:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"}}}}function as(e){let t=dn(e),n=e.orderableFields??t.map(a=>a.path),r=t.map(a=>a.path);if(t.length===0)return hr();let o=[];for(let{path:a,zodSchema:l}of t){let c=ln(l),y=nt(l),x=y?._zod?.def?.type==="array"||y?._def?.typeName==="ZodArray"||y?._def?.type==="array"?ln(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"]},x],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:x}],minItems:3,maxItems:3});}let s={oneOf:o};return {type:"object",properties:{where:{type:"array",items:s,description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:s,description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:s},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string",enum:n},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string",enum:r},description:"Fields to select (projection)"},pageSize:{type:"integer",maximum:100,description:"Number of items per page"},cursor:{oneOf:[{type:"string"},{type:"object"}],description:"Pagination cursor"},direction:{type:"string",enum:["next","prev"],description:"Pagination direction"},includes:{type:"array",items:e.allowedIncludes&&e.allowedIncludes.length>0?{oneOf:[{type:"string",enum:e.allowedIncludes},{type:"object",properties:{relation:{type:"string",enum:e.allowedIncludes},select:{type:"array",items:{type:"string"}}},required:["relation"]}]}:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"}}}}function is(e,t,n,r,o,s="QueryRequestBody"){let a={},l=e.name,c=`${t}/${e.name}`,y=`${c}/{${e.documentKey}}`,v={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};a[c]={get:{operationId:`list${fe(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[l],parameters:[...os(e),...ss(e)],responses:{200:yr(oe(n)),500:W("Internal server error")}},post:{operationId:`create${fe(e.name)}`,summary:`Create a ${le(e.name)}`,tags:[l],requestBody:{required:true,content:{"application/json":{schema:oe(r??n)}}},responses:{201:De("Document created",oe(n)),400:W("Validation error"),500:W("Internal server error")}}},a[`${c}/query`]={post:{operationId:`query${fe(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[l],requestBody:{required:true,content:{"application/json":{schema:oe(s)}}},responses:{200:yr(oe(n)),400:W("Invalid query"),500:W("Internal server error")}}},a[`${c}/batch`]={post:{operationId:`batch${fe(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[l],requestBody:{required:true,content:{"application/json":{schema:oe(`${n}BatchRequest`)}}},responses:{200:De("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:W("Validation error"),403:W("Forbidden"),404:W("Document not found"),500:W("Internal server error")}}};let x={};return x.get={operationId:`get${fe(le(e.name))}`,summary:`Get a single ${le(e.name)}`,tags:[l],parameters:[v],responses:{200:De("Document found",oe(n)),404:W("Document not found"),500:W("Internal server error")}},x.put={operationId:`update${fe(le(e.name))}`,summary:`Update a ${le(e.name)} (full replace)`,tags:[l],parameters:[v],requestBody:{required:true,content:{"application/json":{schema:oe(o??n)}}},responses:{200:De("Document updated",oe(n)),400:W("Validation error"),404:W("Document not found"),500:W("Internal server error")}},x.patch={operationId:`patch${fe(le(e.name))}`,summary:`Partially update a ${le(e.name)}`,tags:[l],parameters:[v],requestBody:{required:true,content:{"application/json":{schema:{allOf:[oe(o??n)],description:"All fields are optional for partial updates"}}}},responses:{200:De("Document patched",oe(n)),400:W("Validation error"),404:W("Document not found"),500:W("Internal server error")}},e.allowDelete&&(x.delete={operationId:`delete${fe(le(e.name))}`,summary:`Delete a ${le(e.name)}`,tags:[l],parameters:[v],responses:{200:De("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:W("Document not found"),500:W("Internal server error")}}),a[y]=x,a}function un(e,t,n={}){let{title:r="CRUD API",version:o="1.0.0",description:s,servers:a,auth:l=false}=n,c=t==="/"?"":t.replace(/\/$/,""),y={},v={},x=[];y.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},y.QueryRequestBody=hr();for(let[k,h]of Object.entries(e)){let g=fe(le(k)),u=`${g}Create`,f=`${g}Update`,i=`${g}QueryRequestBody`;y[g]=St(h.schema),y[i]=as(h);let w=S=>{let P=S&&S.length>0?S:Object.keys(h.schema.shape),E={};for(let I of P){let C=I.split(".")[0];C&&h.schema.shape[C]&&!h.systemKeys.includes(C)&&(E[C]=h.schema.shape[C]);}return E},d=null,m=w(h.createFields);Object.keys(m).length>0&&(y[u]=St(zod.z.object(m)),d=u);let p=null,O=w(h.mutableFields);Object.keys(O).length>0&&(y[f]=St(zod.z.object(O)),p=f),y[`${g}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",enum:["create"]},data:oe(d??g)},required:["type","data"]},{type:"object",properties:{type:{type:"string",enum:["update"]},id:{type:"string"},data:{allOf:[oe(p??g)],description:"Partial updates allowed"}},required:["type","id","data"]},...h.allowDelete?[{type:"object",properties:{type:{type:"string",enum:["delete"]},id:{type:"string"}},required:["type","id"]}]:[]]}}},required:["operations"]};let A=is(h,c,g,d,p,i);Object.assign(v,A),x.push({name:k,description:`Operations on ${k} (collection: ${h.path})`});}let T={},R;return l==="basic"?(T.basicAuth={type:"http",scheme:"basic"},R=[{basicAuth:[]}]):l==="bearer"&&(T.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},R=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:o,...s?{description:s}:{}},...a&&a.length>0?{servers:a}:{},paths:v,components:{schemas:y,...Object.keys(T).length>0?{securitySchemes:T}:{}},...R?{security:R}:{},tags:x}}function fe(e){return e.charAt(0).toUpperCase()+e.slice(1)}function le(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 _e=class extends Error{constructor(n,r){super("Request validation failed");this.zodError=n;this.source=r;this.statusCode=400;this.name="ValidationError";}};var rt=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},ot=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function gr(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function br(e,t){return t instanceof _e?e.json({success:false,error:"Validation failed",issues:gr(t.zodError)},400):t instanceof rt?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof ot?e.json({success:false,error:"Output validation failed",issues:gr(t.zodError)},500):null}zodToOpenapi.extendZodWithOpenApi(zod.z);var wr="Successful response",vr="Error response";function ps(e){return e==="get"?"query":"json"}function fs(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function ys(e){if(typeof e.safeParse=="function")return {description:vr,schema:e};let t=e;return {description:t.description??vr,schema:t.schema}}function Sr(e,t,n,r){let o=new zodToOpenapi.OpenAPIRegistry;if(n.securitySchemes)for(let[l,c]of Object.entries(n.securitySchemes))o.registerComponent("securitySchemes",l,c);for(let l of e){let c=l.method,y=l.source??ps(c),v=gs(t,l.path??"/"),x=l.status??200,T=ms(c,y,l.input),R=xr(y,l.input,"query"),b=xr(y,l.input,"param"),k=bs(c,v),h=fs(l.output,r),g={[x]:h?{description:wr,content:{"application/json":{schema:h}}}:{description:wr}};if(r?.errors)for(let[u,f]of Object.entries(r.errors)){let{description:i,schema:w}=ys(f);g[u]=w?{description:i,content:{"application/json":{schema:w}}}:{description:i};}o.registerPath({method:c,path:hs(v),operationId:k,summary:l.summary,description:l.description,tags:l.tags,deprecated:l.deprecated,security:l.security,request:{...R?{query:R}:{},...b?{params:b}:{},...T?{body:T}:{}},responses:g});}return new zodToOpenapi.OpenApiGeneratorV31(o.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security})}function ms(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 xr(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function hs(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function gs(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function bs(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function Rr(e,t){let n=e.replace(/"/g,"&quot;");return `<!doctype html>
1142
1142
  <html lang="en">
1143
1143
  <head>
1144
1144
  <meta charset="utf-8" />