@lpdjs/firestore-repo-service 2.1.2 → 2.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -13
- package/dist/index.cjs +44 -44
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +44 -44
- package/dist/index.js.map +1 -1
- package/dist/servers/admin/index.cjs +4 -4
- package/dist/servers/admin/index.cjs.map +1 -1
- package/dist/servers/admin/index.js +4 -4
- package/dist/servers/admin/index.js.map +1 -1
- package/dist/servers/crud/index.cjs +2 -2
- package/dist/servers/crud/index.cjs.map +1 -1
- package/dist/servers/crud/index.js +2 -2
- package/dist/servers/crud/index.js.map +1 -1
- package/dist/servers/index.cjs +2 -2
- package/dist/servers/index.cjs.map +1 -1
- package/dist/servers/index.js +2 -2
- package/dist/servers/index.js.map +1 -1
- package/dist/sync/bigquery.d.cts +1 -1
- package/dist/sync/bigquery.d.ts +1 -1
- package/dist/sync/index.cjs +33 -33
- package/dist/sync/index.cjs.map +1 -1
- package/dist/sync/index.d.cts +170 -170
- package/dist/sync/index.d.ts +170 -170
- package/dist/sync/index.js +33 -33
- package/dist/sync/index.js.map +1 -1
- package/dist/{types-PzZ0APQ_.d.cts → types-BG1kGsLO.d.cts} +25 -12
- package/dist/{types-PzZ0APQ_.d.ts → types-BG1kGsLO.d.ts} +25 -12
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var zod=require('zod'),jsxRuntime=require('hono/jsx/jsx-runtime'),server=require('hono/jsx/dom/server');function Et(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function le(e,t){return t.orderBy&&t.orderBy.forEach(n=>{e=e.orderBy(String(n.field),n.direction??"asc");}),t.limit&&(e=e.limit(t.limit)),t.offset&&(e=e.offset(t.offset)),t.select&&t.select.length>0&&(e=e.select(...t.select.map(n=>String(n)))),t.startAt&&(e=Array.isArray(t.startAt)?e.startAt(...t.startAt):e.startAt(t.startAt)),t.startAfter&&(e=Array.isArray(t.startAfter)?e.startAfter(...t.startAfter):e.startAfter(t.startAfter)),t.endAt&&(e=Array.isArray(t.endAt)?e.endAt(...t.endAt):e.endAt(t.endAt)),t.endBefore&&(e=Array.isArray(t.endBefore)?e.endBefore(...t.endBefore):e.endBefore(t.endBefore)),e}function be(e){let[,t,n]=e;return (t==="in"||t==="array-contains-any")&&Array.isArray(n)&&n.length>30}function qe(e){let[t,n,r]=e;return be(e)?Et(r,30).map(a=>[t,n,a]):[e]}function ye(e,t){let n=e;for(let[r,s,a]of t)n=n.where(String(r),s,a);return n}async function Qe(e){let t=await Promise.all(e.map(s=>s.get())),n=new Map;t.forEach(s=>{s.docs.forEach(a=>{n.has(a.id)||n.set(a.id,a);});});let r=t[0];if(!r)throw new Error("No snapshots returned");return {...r,docs:Array.from(n.values()),size:n.size,empty:n.size===0}}async function ee(e,t){let n=t.orWhere&&t.orWhere.length>0,r=t.orWhereGroups&&t.orWhereGroups.length>0;if(!n&&!r){if(!t.where||t.where.length===0)return le(e,t).get();if(!t.where.some(be)){let g=ye(e,t.where);return g=le(g,t),g.get()}let l=t.where.map(qe),c=Re(l).map(g=>{let u=ye(e,g);return u=le(u,t),u});return Qe(c)}let s=t.where??[],a=[...t.orWhere?.map(d=>[d])??[],...t.orWhereGroups??[]],o=[];for(let d of a){let l=[...s,...d];if(l.some(be)){let c=l.map(qe),u=Re(c).map(p=>{let f=ye(e,p);return f=le(f,t),f});o.push(...u);}else {let c=ye(e,l);c=le(c,t),o.push(c);}}return Qe(o)}function Re(e){if(e.length===0)return [[]];let t=e[0];if(e.length===1&&t)return t.map(a=>[a]);if(!t)return [[]];let n=e.slice(1),r=Re(n),s=[];for(let a of t)for(let o of r)s.push([a,...o]);return s}function We(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function L(e){return e.charAt(0).toUpperCase()+e.slice(1)}function G(e,t){return t.where&&t.where.forEach(([n,r,s])=>{e=e.where(String(n),r,s);}),t.orderBy&&t.orderBy.forEach(n=>{e=e.orderBy(String(n.field),n.direction??"asc");}),t.limit&&(e=e.limit(t.limit)),t.offset&&(e=e.offset(t.offset)),t.select&&t.select.length>0&&(e=e.select(...t.select.map(n=>String(n)))),t.startAt&&(e=Array.isArray(t.startAt)?e.startAt(...t.startAt):e.startAt(t.startAt)),t.startAfter&&(e=Array.isArray(t.startAfter)?e.startAfter(...t.startAfter):e.startAfter(t.startAfter)),t.endAt&&(e=Array.isArray(t.endAt)?e.endAt(...t.endAt):e.endAt(t.endAt)),t.endBefore&&(e=Array.isArray(t.endBefore)?e.endBefore(...t.endBefore):e.endBefore(t.endBefore)),e}async function me(e,t){let n={...t,limit:t.pageSize+1};t.cursor&&(t.direction==="prev"?n.endBefore=t.cursor:n.startAfter=t.cursor);let s=(await ee(e,n)).docs,a=s.length>t.pageSize,o=a?s.slice(0,t.pageSize):s,d=o.map(i=>({...i.data(),docId:i.id})),l=t.direction==="prev";return {data:d,nextCursor:l?o.length>0?o[o.length-1]:void 0:a?o[o.length-1]:void 0,prevCursor:l?a?o[0]:void 0:o[0],hasNextPage:l?!!t.cursor:a,hasPrevPage:l?a:!!t.cursor,pageSize:d.length}}async function*ve(e,t){let n,r=true;for(;r;){let s=await me(e,{...t,cursor:n,direction:"next"});yield s,r=s.hasNextPage,n=s.nextCursor;}}function Ue(e){return {count:async(t={})=>{let n=e;return n=G(n,t),(await n.count().get()).data().count},sum:async(t,n={})=>{let r=e;r=G(r,n);let s=await r.get(),a=0;return s.forEach(o=>{let d=o.data()[t];typeof d=="number"&&(a+=d);}),a},average:async(t,n={})=>{let r=e;r=G(r,n);let s=await r.get();if(s.empty)return null;let a=0,o=0;return s.forEach(d=>{let l=d.data()[t];typeof l=="number"&&(a+=l,o++);}),o>0?a/o:null}}}function Le(e,t,n,r,s,a){let o=()=>new Date;return {create:()=>{let d=e.batch();return {batch:d,set:(...l)=>{let i=l[l.length-1],c=typeof i=="object"&&i!==null&&"merge"in i,g=c?l[l.length-2]:l[l.length-1],u=c?l.slice(0,-2):l.slice(0,-1),p=c?i:{merge:true},f=t(...u),b={...g},m=u[u.length-1];n&&m&&(b[n]=m),r&&(b[r]=f.path),s&&(b[s]=o()),a&&(b[a]=o()),d.set(f,b,p);},update:(...l)=>{let i=l.pop(),g=t(...l),u={...i};a&&(u[a]=o()),d.update(g,u);},delete:(...l)=>{let i=t(...l);d.delete(i);},commit:async()=>{await d.commit();}}}}}function He(e,t,n){let r=()=>new Date;return {set:async s=>{let a=e.bulkWriter(),o=0;for(let d of s){if(!d)continue;let{docRef:l,data:i,merge:c=true}=d,g={...i};t&&(g[t]=r()),n&&(g[n]=r()),a.set(l,g,{merge:c}),o++,o>=500&&(await a.flush(),o=0);}await a.close();},update:async s=>{let a=e.bulkWriter(),o=0;for(let d of s){if(!d)continue;let{docRef:l,data:i}=d,c={...i};n&&(c[n]=r()),a.update(l,c),o++,o>=500&&(await a.flush(),o=0);}await a.close();},delete:async s=>{let a=e.bulkWriter(),o=0;for(let d of s)d&&(a.delete(d),o++,o>=500&&(await a.flush(),o=0));await a.close();}}}function Ge(e,t,n,r,s,a){let o=()=>new Date;return {create:async g=>{if(!e)throw new Error("Cannot use create() on collection groups. Use set() with a specific document ID instead.");let u,p,f={...g};if(s&&(f[s]=o()),a&&(f[a]=o()),g[n]){p=g[n],u=e.doc(p);let m=r?{...f,[r]:u.path}:f;await u.set(m);}else {u=await e.add(f),p=u.id;let m={[n]:p};r&&(m[r]=u.path),await u.update(m);}return (await u.get()).data()},set:async(...g)=>{let u=g[g.length-1],p=typeof u=="object"&&u!==null&&"merge"in u,f=p?g[g.length-2]:g[g.length-1],b=p?g.slice(0,-2):g.slice(0,-1),m=p?u:{merge:true},y={...f};a&&(y[a]=o());let h=t(...b),v=b[b.length-1];return n&&v!=null&&(y[n]=v),r&&(y[r]=h.path),await h.set(y,m),(await h.get()).data()},update:async(...g)=>{let u=g.pop(),p=g,f={...u};a&&(f[a]=o());let b=t(...p);return await b.update(f),(await b.get()).data()},delete:async(...g)=>{await t(...g).delete();}}}function Ve(e,t,n,r,s){let a={};return a.byList=async(o,d,l="in",i={})=>{if(d.length===0)return [];let c=[],g=We(d,30);for(let u of g){let p=e;p=p.where(o,l,u),i.select&&i.select.length>0&&(p=p.select(...i.select.map(b=>String(b)))),(await p.get()).forEach(b=>{let m=b.data();c.push(i.returnDoc?{data:m,doc:b}:m);});}return c},t.forEach(o=>{let d=`by${L(String(o))}`;a[d]=async(l,i={})=>{let c=typeof i=="boolean"?{returnDoc:i}:i;if(String(o)===s){let m=await r(l).get();if(!m.exists)return null;let y=m.data();return c.returnDoc?{data:y,doc:m}:y}let g=e;g=g.where(String(o),"==",l).limit(1),c.select&&c.select.length>0&&(g=g.select(...c.select.map(b=>String(b))));let u=await g.get();if(u.empty)return null;let p=u.docs[0];if(!p)return null;let f=p.data();return c.returnDoc?{data:f,doc:p}:f};}),a}function Je(e,t,n,r){let s={},a=async(o,d)=>{if(!n||!r||d.length===0)return o;let l=d.map(i=>typeof i=="string"?{key:i}:{key:i.relation,select:i.select});return Promise.all(o.map(async i=>{let c=await Promise.all(l.map(async({key:u,select:p})=>{let f=n[u];if(!f)return [u,void 0];let b=r[f.repo];if(!b)return [u,void 0];let m=i[u];if(m==null)return [u,f.type==="one"?null:[]];let y=p?{select:p}:void 0;try{if(f.type==="one"){let h=`by${L(f.key)}`,v=typeof b.get?.[h]=="function"?await b.get[h](m,y):null;return [u,v]}else {let h=`by${L(f.key)}`,v=typeof b.query?.[h]=="function"?await b.query[h](m,y):[];return [u,v]}}catch(h){return console.error(`[include] Error populating "${u}":`,h),[u,f.type==="one"?null:[]]}})),g={};for(let[u,p]of c)u!==void 0&&(g[u]=p);return {...i,populated:g}}))};return t.forEach(o=>{let d=`by${L(o)}`;s[d]=async(l,i={})=>{let c={...i,where:[[o,"==",l],...i.where??[]]};return (await ee(e,c)).docs.map(u=>u.data())};}),s.by=async o=>(await ee(e,o)).docs.map(l=>l.data()),s.getAll=async(o={})=>(await ee(e,o)).docs.map(l=>l.data()),s.onSnapshot=(o,d,l)=>G(e,o).onSnapshot(c=>{d(c.docs.map(g=>g.data()));},l),s.paginate=async o=>{let{include:d,...l}=o,i=await me(e,l);if(d&&d.length>0){let c=await a(i.data,d);return {...i,data:c}}return i},s.paginateAll=async function*(o){let{include:d,...l}=o;for await(let i of ve(e,l))if(d&&d.length>0){let c=await a(i.data,d);yield {...i,data:c};}else yield i;},s}function Xe(e,t){return {populate:async(n,r)=>{if(!e.relationalKeys)return {...n,populated:{}};let s,a={};if(typeof r=="object"&&!Array.isArray(r))if("relation"in r){let l=r;s=[l.relation],l.select&&(a[l.relation]=l.select);}else if("relations"in r){let l=r;s=Array.isArray(l.relations)?l.relations:[l.relations],a=l.select??{};}else s=[];else s=Array.isArray(r)?r:[r];let o=await Promise.all(s.map(async l=>{let i=e.relationalKeys?.[l];if(!i)return console.warn(`[populate] Relation "${l}" not found in config`),[l,void 0];let c=t[i.repo];if(!c)return console.warn(`[populate] Repository "${i.repo}" not found in mapping`),[l,void 0];let g=n[l];if(g==null)return [l,i.type==="one"?null:[]];let u=a[l],p=u?{select:u}:void 0;try{if(i.type==="one"){let f=`by${L(i.key)}`,b=typeof c.get?.[f]=="function"?await c.get[f](g,p):null;return [l,b]}else {let f=`by${L(i.key)}`,b=typeof c.query?.[f]=="function"?await c.query[f](g,p):[];return [l,b]}}catch(f){return console.error(`[populate] Error populating "${l}":`,f),[l,i.type==="one"?null:[]]}})),d={};for(let[l,i]of o)i!==void 0&&(d[l]=i);return {...n,populated:d}}}}function Ye(e,t){return {run:async n=>e.runTransaction(async r=>n({get:async(...a)=>{let o=t(...a),d=await r.get(o);return d.exists?{...d.data(),docId:d.id}:null},set:(...a)=>{let o=a[a.length-1],d=typeof o=="object"&&o!==null&&"merge"in o,l=d?a[a.length-2]:a[a.length-1],i=d?a.slice(0,-2):a.slice(0,-1),c=d?o:{merge:true},g=t(...i);r.set(g,l,c);},update:(...a)=>{let o=a[a.length-1],d=a.slice(0,-1),l=t(...d);r.update(l,o);},delete:(...a)=>{let o=t(...a);r.delete(o);},raw:r}))}}function Ft(e){if(typeof e!="function")return [];let n=e.toString().match(/^\s*(?:function\s*\w*\s*)?\(([^)]*)\)/);if(!n?.[1])return [];let r=n[1].split(",").map(s=>s.trim().replace(/\s*[:=].*$/,"").trim()).filter(Boolean);return r.length<=2?[]:r.slice(1,-1)}function xe(e,t,n={}){let r=t.isGroup?e.collectionGroup(t.path):e.collection(t.path),s=t.isGroup?null:e.collection(t.path),a=(...f)=>t.refCb(e,...f),o=Ve(r,t.foreignKeys,s,a,t.documentKey),d=Je(r,t.queryKeys,t.relationalKeys,n),l=Ue(r),i=Ge(s,a,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),c=Le(e,a,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),g=Ye(e,a),u=He(e,t.createdKey,t.updatedKey),p=Xe(t,n);return {ref:r,documentRef:a,get:o,query:d,aggregate:l,...i,batch:c,transaction:g,bulk:u,...p,schema:t.schema,relationalKeys:t.relationalKeys,_systemKeys:[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(f=>typeof f=="string"),_pathKey:t.pathKey??null,_isGroup:!!t.isGroup,_parentKeys:t.isGroup?Ft(t.refCb):[],_createdKey:t.createdKey??null}}var It={string:"ZodString",number:"ZodNumber",bigint:"ZodBigInt",boolean:"ZodBoolean",date:"ZodDate",enum:"ZodEnum",nativeEnum:"ZodNativeEnum",literal:"ZodLiteral",object:"ZodObject",array:"ZodArray",optional:"ZodOptional",nullable:"ZodNullable",default:"ZodDefault",coerce:"ZodCoerce",union:"ZodUnion",undefined:"ZodUndefined",unknown:"ZodUnknown",any:"ZodAny",record:"ZodRecord"};function z(e){let t=e,n=t._zod?.def?.type;if(n)return It[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=t._def?.typeName;return r||""}function M(e){let t=e;if(t._zod?.def?.innerType)return t._zod.def.innerType;if(t._def?.innerType)return t._def.innerType}function et(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}function tt(e){let t=e;if(t._zod?.def?.defaultValue!==void 0)return t._zod.def.defaultValue;let n=t._def?.defaultValue;return typeof n=="function"?n():n}function ce(e){let t=e;return t.shape&&typeof t.shape=="object"?t.shape:t._zod?.def?.shape&&typeof t._zod.def.shape=="object"?t._zod.def.shape:t._def?.shape?typeof t._def.shape=="function"?t._def.shape():t._def.shape:{}}function we(e){let t=e;return Array.isArray(t.options)?t.options:t._zod?.def?.entries?Object.values(t._zod.def.entries):Array.isArray(t._def?.values)?t._def.values:[]}function Te(e){let t=e;return t._zod?.def?.entries?t._zod.def.entries:t.enum&&typeof t.enum=="object"?t.enum:t._def?.values&&typeof t._def.values=="object"?t._def.values:{}}function nt(e){let t=e;return Array.isArray(t._zod?.def?.values)?t._zod.def.values[0]:t._def?.value}function rt(e){let t=e,n=[],r=t._zod?.def?.checks;if(Array.isArray(r)){for(let a of r)a.format&&n.push(a.format);if(n.length>0)return n}let s=t._def?.checks;if(Array.isArray(s))for(let a of s)a.kind&&n.push(a.kind);return n}function _t(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/^\s/,"").replace(/^./,t=>t.toUpperCase())}function st(e){let t=e,n=true,r=false,s;for(;;){let a=z(t);if(a==="ZodOptional")n=false,t=M(t);else if(a==="ZodNullable")n=false,r=true,t=M(t);else if(a==="ZodDefault")n=false,s=tt(t),t=M(t);else break}return {inner:t,required:n,nullable:r,defaultValue:s}}function Q(e,t=""){if(z(e)==="ZodObject"){let r=ce(e);return Object.entries(r).map(([s,a])=>at(t?`${t}.${s}`:s,s,a))}return [at(t||"value",t||"value",e)]}function at(e,t,n){let{inner:r,required:s,nullable:a,defaultValue:o}=st(n),d=z(r),l=_t(t.split(".").pop()??t);switch(d){case "ZodString":{let i=rt(r),c=i.includes("email"),g=i.includes("url");return {name:e,label:l,type:"text",required:s,nullable:a,defaultValue:o,hint:c?"email":g?"url":void 0}}case "ZodNumber":case "ZodBigInt":return {name:e,label:l,type:"number",required:s,nullable:a,defaultValue:o};case "ZodBoolean":return {name:e,label:l,type:"checkbox",required:s,nullable:a,defaultValue:o};case "ZodDate":case "ZodCoerce":return {name:e,label:l,type:"datetime-local",required:s,nullable:a,defaultValue:o};case "ZodEnum":{let i=we(r);return {name:e,label:l,type:"select",required:s,nullable:a,defaultValue:o,options:i}}case "ZodNativeEnum":{let i=Te(r),c=Object.values(i).filter(g=>typeof g=="string");return {name:e,label:l,type:"select",required:s,nullable:a,defaultValue:o,options:c}}case "ZodLiteral":{let i=String(nt(r)??"");return {name:e,label:l,type:"select",required:s,nullable:a,defaultValue:o,options:[i]}}case "ZodObject":{let i=Q(r,e);return {name:e,label:l,type:"textarea",required:s,nullable:a,defaultValue:o,nested:i,hint:"JSON object"}}case "ZodArray":{let i=et(r);if(!i)return {name:e,label:l,type:"textarea",required:s,nullable:a,defaultValue:o,hint:"JSON array"};let{inner:c}=st(i),g=z(c),u,p,f;switch(g){case "ZodString":u="text";break;case "ZodNumber":case "ZodBigInt":u="number";break;case "ZodBoolean":u="checkbox";break;case "ZodDate":u="datetime-local";break;case "ZodEnum":u="select",p=we(c);break;case "ZodNativeEnum":u="select",p=Object.values(Te(c)).filter(b=>typeof b=="string");break;case "ZodObject":u="object",f=Q(c);break;default:return {name:e,label:l,type:"textarea",required:s,nullable:a,defaultValue:o,hint:"JSON array"}}return {name:e,label:l,type:"textarea",required:s,nullable:a,defaultValue:o,arrayElementType:u,arrayElementOptions:p,arrayElementFields:f}}default:return {name:e,label:l,type:"textarea",required:s,nullable:a,defaultValue:o,hint:"JSON"}}}function Se(e,t=0){let n=t>0?`ml-${t*4}`:"",r=`field_${e.name.replace(/\./g,"__")}`,s=e.name,a=e.required?" required":"",o=e.defaultValue==="__null__",d=!o&&e.defaultValue!=null?String(e.defaultValue):"",l=e.nullable&&e.type!=="checkbox"?`<span class="flex items-center gap-1 shrink-0">
|
|
1
|
+
'use strict';var zod=require('zod'),jsxRuntime=require('hono/jsx/jsx-runtime'),server=require('hono/jsx/dom/server');function Et(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function le(e,t){return t.orderBy&&t.orderBy.forEach(n=>{e=e.orderBy(String(n.field),n.direction??"asc");}),t.limit&&(e=e.limit(t.limit)),t.offset&&(e=e.offset(t.offset)),t.select&&t.select.length>0&&(e=e.select(...t.select.map(n=>String(n)))),t.startAt&&(e=Array.isArray(t.startAt)?e.startAt(...t.startAt):e.startAt(t.startAt)),t.startAfter&&(e=Array.isArray(t.startAfter)?e.startAfter(...t.startAfter):e.startAfter(t.startAfter)),t.endAt&&(e=Array.isArray(t.endAt)?e.endAt(...t.endAt):e.endAt(t.endAt)),t.endBefore&&(e=Array.isArray(t.endBefore)?e.endBefore(...t.endBefore):e.endBefore(t.endBefore)),e}function be(e){let[,t,n]=e;return (t==="in"||t==="array-contains-any")&&Array.isArray(n)&&n.length>30}function qe(e){let[t,n,r]=e;return be(e)?Et(r,30).map(a=>[t,n,a]):[e]}function ye(e,t){let n=e;for(let[r,s,a]of t)n=n.where(String(r),s,a);return n}async function Qe(e){let t=await Promise.all(e.map(s=>s.get())),n=new Map;t.forEach(s=>{s.docs.forEach(a=>{n.has(a.id)||n.set(a.id,a);});});let r=t[0];if(!r)throw new Error("No snapshots returned");return {...r,docs:Array.from(n.values()),size:n.size,empty:n.size===0}}async function ee(e,t){let n=t.orWhere&&t.orWhere.length>0,r=t.orWhereGroups&&t.orWhereGroups.length>0;if(!n&&!r){if(!t.where||t.where.length===0)return le(e,t).get();if(!t.where.some(be)){let g=ye(e,t.where);return g=le(g,t),g.get()}let l=t.where.map(qe),d=Re(l).map(g=>{let u=ye(e,g);return u=le(u,t),u});return Qe(d)}let s=t.where??[],a=[...t.orWhere?.map(c=>[c])??[],...t.orWhereGroups??[]],o=[];for(let c of a){let l=[...s,...c];if(l.some(be)){let d=l.map(qe),u=Re(d).map(p=>{let f=ye(e,p);return f=le(f,t),f});o.push(...u);}else {let d=ye(e,l);d=le(d,t),o.push(d);}}return Qe(o)}function Re(e){if(e.length===0)return [[]];let t=e[0];if(e.length===1&&t)return t.map(a=>[a]);if(!t)return [[]];let n=e.slice(1),r=Re(n),s=[];for(let a of t)for(let o of r)s.push([a,...o]);return s}function We(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function L(e){return e.charAt(0).toUpperCase()+e.slice(1)}function G(e,t){return t.where&&t.where.forEach(([n,r,s])=>{e=e.where(String(n),r,s);}),t.orderBy&&t.orderBy.forEach(n=>{e=e.orderBy(String(n.field),n.direction??"asc");}),t.limit&&(e=e.limit(t.limit)),t.offset&&(e=e.offset(t.offset)),t.select&&t.select.length>0&&(e=e.select(...t.select.map(n=>String(n)))),t.startAt&&(e=Array.isArray(t.startAt)?e.startAt(...t.startAt):e.startAt(t.startAt)),t.startAfter&&(e=Array.isArray(t.startAfter)?e.startAfter(...t.startAfter):e.startAfter(t.startAfter)),t.endAt&&(e=Array.isArray(t.endAt)?e.endAt(...t.endAt):e.endAt(t.endAt)),t.endBefore&&(e=Array.isArray(t.endBefore)?e.endBefore(...t.endBefore):e.endBefore(t.endBefore)),e}async function me(e,t){let n={...t,limit:t.pageSize+1};t.cursor&&(t.direction==="prev"?n.endBefore=t.cursor:n.startAfter=t.cursor);let s=(await ee(e,n)).docs,a=s.length>t.pageSize,o=a?s.slice(0,t.pageSize):s,c=o.map(i=>({...i.data(),docId:i.id})),l=t.direction==="prev";return {data:c,nextCursor:l?o.length>0?o[o.length-1]:void 0:a?o[o.length-1]:void 0,prevCursor:l?a?o[0]:void 0:o[0],hasNextPage:l?!!t.cursor:a,hasPrevPage:l?a:!!t.cursor,pageSize:c.length}}async function*ve(e,t){let n,r=true;for(;r;){let s=await me(e,{...t,cursor:n,direction:"next"});yield s,r=s.hasNextPage,n=s.nextCursor;}}function Ue(e){return {count:async(t={})=>{let n=e;return n=G(n,t),(await n.count().get()).data().count},sum:async(t,n={})=>{let r=e;r=G(r,n);let s=await r.get(),a=0;return s.forEach(o=>{let c=o.data()[t];typeof c=="number"&&(a+=c);}),a},average:async(t,n={})=>{let r=e;r=G(r,n);let s=await r.get();if(s.empty)return null;let a=0,o=0;return s.forEach(c=>{let l=c.data()[t];typeof l=="number"&&(a+=l,o++);}),o>0?a/o:null}}}function Le(e,t,n,r,s,a){let o=()=>new Date;return {create:()=>{let c=e.batch();return {batch:c,set:(...l)=>{let i=l[l.length-1],d=typeof i=="object"&&i!==null&&"merge"in i,g=d?l[l.length-2]:l[l.length-1],u=d?l.slice(0,-2):l.slice(0,-1),p=d?i:{merge:true},f=t(...u),b={...g},m=u[u.length-1];n&&m&&(b[n]=m),r&&(b[r]=f.path),s&&(b[s]=o()),a&&(b[a]=o()),c.set(f,b,p);},update:(...l)=>{let i=l.pop(),g=t(...l),u={...i};a&&(u[a]=o()),c.update(g,u);},delete:(...l)=>{let i=t(...l);c.delete(i);},commit:async()=>{await c.commit();}}}}}function He(e,t,n){let r=()=>new Date;return {set:async s=>{let a=e.bulkWriter(),o=0;for(let c of s){if(!c)continue;let{docRef:l,data:i,merge:d=true}=c,g={...i};t&&(g[t]=r()),n&&(g[n]=r()),a.set(l,g,{merge:d}),o++,o>=500&&(await a.flush(),o=0);}await a.close();},update:async s=>{let a=e.bulkWriter(),o=0;for(let c of s){if(!c)continue;let{docRef:l,data:i}=c,d={...i};n&&(d[n]=r()),a.update(l,d),o++,o>=500&&(await a.flush(),o=0);}await a.close();},delete:async s=>{let a=e.bulkWriter(),o=0;for(let c of s)c&&(a.delete(c),o++,o>=500&&(await a.flush(),o=0));await a.close();}}}function Ge(e,t,n,r,s,a){let o=()=>new Date;return {create:async g=>{if(!e)throw new Error("Cannot use create() on collection groups. Use set() with a specific document ID instead.");let u,p,f={...g};if(s&&(f[s]=o()),a&&(f[a]=o()),g[n]){p=g[n],u=e.doc(p);let m=r?{...f,[r]:u.path}:f;await u.set(m);}else {u=await e.add(f),p=u.id;let m={[n]:p};r&&(m[r]=u.path),await u.update(m);}return (await u.get()).data()},set:async(...g)=>{let u=g[g.length-1],p=typeof u=="object"&&u!==null&&"merge"in u,f=p?g[g.length-2]:g[g.length-1],b=p?g.slice(0,-2):g.slice(0,-1),m=p?u:{merge:true},y={...f};a&&(y[a]=o());let h=t(...b),v=b[b.length-1];return n&&v!=null&&(y[n]=v),r&&(y[r]=h.path),await h.set(y,m),(await h.get()).data()},update:async(...g)=>{let u=g.pop(),p=g,f={...u};a&&(f[a]=o());let b=t(...p);return await b.update(f),(await b.get()).data()},delete:async(...g)=>{await t(...g).delete();}}}function Ve(e,t,n,r,s){let a={};return a.byList=async(o,c,l="in",i={})=>{if(c.length===0)return [];let d=[],g=We(c,30);for(let u of g){let p=e;p=p.where(o,l,u),i.select&&i.select.length>0&&(p=p.select(...i.select.map(b=>String(b)))),(await p.get()).forEach(b=>{let m=b.data();d.push(i.returnDoc?{data:m,doc:b}:m);});}return d},t.forEach(o=>{let c=`by${L(String(o))}`;a[c]=async(l,i={})=>{let d=typeof i=="boolean"?{returnDoc:i}:i;if(String(o)===s){let m=await r(l).get();if(!m.exists)return null;let y=m.data();return d.returnDoc?{data:y,doc:m}:y}let g=e;g=g.where(String(o),"==",l).limit(1),d.select&&d.select.length>0&&(g=g.select(...d.select.map(b=>String(b))));let u=await g.get();if(u.empty)return null;let p=u.docs[0];if(!p)return null;let f=p.data();return d.returnDoc?{data:f,doc:p}:f};}),a}function Je(e,t,n,r){let s={},a=async(o,c)=>{if(!n||!r||c.length===0)return o;let l=c.map(i=>typeof i=="string"?{key:i}:{key:i.relation,select:i.select});return Promise.all(o.map(async i=>{let d=await Promise.all(l.map(async({key:u,select:p})=>{let f=n[u];if(!f)return [u,void 0];let b=r[f.repo];if(!b)return [u,void 0];let m=i[u];if(m==null)return [u,f.type==="one"?null:[]];let y=p?{select:p}:void 0;try{if(f.type==="one"){let h=`by${L(f.key)}`,v=typeof b.get?.[h]=="function"?await b.get[h](m,y):null;return [u,v]}else {let h=`by${L(f.key)}`,v=typeof b.query?.[h]=="function"?await b.query[h](m,y):[];return [u,v]}}catch(h){return console.error(`[include] Error populating "${u}":`,h),[u,f.type==="one"?null:[]]}})),g={};for(let[u,p]of d)u!==void 0&&(g[u]=p);return {...i,populated:g}}))};return t.forEach(o=>{let c=`by${L(o)}`;s[c]=async(l,i={})=>{let d={...i,where:[[o,"==",l],...i.where??[]]};return (await ee(e,d)).docs.map(u=>u.data())};}),s.by=async o=>(await ee(e,o)).docs.map(l=>l.data()),s.getAll=async(o={})=>(await ee(e,o)).docs.map(l=>l.data()),s.onSnapshot=(o,c,l)=>G(e,o).onSnapshot(d=>{c(d.docs.map(g=>g.data()));},l),s.paginate=async o=>{let{include:c,...l}=o,i=await me(e,l);if(c&&c.length>0){let d=await a(i.data,c);return {...i,data:d}}return i},s.paginateAll=async function*(o){let{include:c,...l}=o;for await(let i of ve(e,l))if(c&&c.length>0){let d=await a(i.data,c);yield {...i,data:d};}else yield i;},s}function Xe(e,t){return {populate:async(n,r)=>{if(!e.relationalKeys)return {...n,populated:{}};let s,a={};if(typeof r=="object"&&!Array.isArray(r))if("relation"in r){let l=r;s=[l.relation],l.select&&(a[l.relation]=l.select);}else if("relations"in r){let l=r;s=Array.isArray(l.relations)?l.relations:[l.relations],a=l.select??{};}else s=[];else s=Array.isArray(r)?r:[r];let o=await Promise.all(s.map(async l=>{let i=e.relationalKeys?.[l];if(!i)return console.warn(`[populate] Relation "${l}" not found in config`),[l,void 0];let d=t[i.repo];if(!d)return console.warn(`[populate] Repository "${i.repo}" not found in mapping`),[l,void 0];let g=n[l];if(g==null)return [l,i.type==="one"?null:[]];let u=a[l],p=u?{select:u}:void 0;try{if(i.type==="one"){let f=`by${L(i.key)}`,b=typeof d.get?.[f]=="function"?await d.get[f](g,p):null;return [l,b]}else {let f=`by${L(i.key)}`,b=typeof d.query?.[f]=="function"?await d.query[f](g,p):[];return [l,b]}}catch(f){return console.error(`[populate] Error populating "${l}":`,f),[l,i.type==="one"?null:[]]}})),c={};for(let[l,i]of o)i!==void 0&&(c[l]=i);return {...n,populated:c}}}}function Ye(e,t){return {run:async n=>e.runTransaction(async r=>n({get:async(...a)=>{let o=t(...a),c=await r.get(o);return c.exists?{...c.data(),docId:c.id}:null},set:(...a)=>{let o=a[a.length-1],c=typeof o=="object"&&o!==null&&"merge"in o,l=c?a[a.length-2]:a[a.length-1],i=c?a.slice(0,-2):a.slice(0,-1),d=c?o:{merge:true},g=t(...i);r.set(g,l,d);},update:(...a)=>{let o=a[a.length-1],c=a.slice(0,-1),l=t(...c);r.update(l,o);},delete:(...a)=>{let o=t(...a);r.delete(o);},raw:r}))}}function Ft(e){if(typeof e!="function")return [];let n=e.toString().match(/^\s*(?:function\s*\w*\s*)?\(([^)]*)\)/);if(!n?.[1])return [];let r=n[1].split(",").map(s=>s.trim().replace(/\s*[:=].*$/,"").trim()).filter(Boolean);return r.length<=2?[]:r.slice(1,-1)}function xe(e,t,n={}){let r=t.isGroup?e.collectionGroup(t.path):e.collection(t.path),s=t.isGroup?null:e.collection(t.path),a=(...f)=>t.refCb(e,...f),o=Ve(r,t.foreignKeys,s,a,t.documentKey),c=Je(r,t.queryKeys,t.relationalKeys,n),l=Ue(r),i=Ge(s,a,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),d=Le(e,a,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),g=Ye(e,a),u=He(e,t.createdKey,t.updatedKey),p=Xe(t,n);return {ref:r,documentRef:a,get:o,query:c,aggregate:l,...i,batch:d,transaction:g,bulk:u,...p,schema:t.schema,relationalKeys:t.relationalKeys,_systemKeys:[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(f=>typeof f=="string"),_pathKey:t.pathKey??null,_isGroup:!!t.isGroup,_parentKeys:t.isGroup?Ft(t.refCb):[],_createdKey:t.createdKey??null}}var It={string:"ZodString",number:"ZodNumber",bigint:"ZodBigInt",boolean:"ZodBoolean",date:"ZodDate",enum:"ZodEnum",nativeEnum:"ZodNativeEnum",literal:"ZodLiteral",object:"ZodObject",array:"ZodArray",optional:"ZodOptional",nullable:"ZodNullable",default:"ZodDefault",coerce:"ZodCoerce",union:"ZodUnion",undefined:"ZodUndefined",unknown:"ZodUnknown",any:"ZodAny",record:"ZodRecord"};function z(e){let t=e,n=t._zod?.def?.type;if(n)return It[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=t._def?.typeName;return r||""}function M(e){let t=e;if(t._zod?.def?.innerType)return t._zod.def.innerType;if(t._def?.innerType)return t._def.innerType}function et(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}function tt(e){let t=e;if(t._zod?.def?.defaultValue!==void 0)return t._zod.def.defaultValue;let n=t._def?.defaultValue;return typeof n=="function"?n():n}function ce(e){let t=e;return t.shape&&typeof t.shape=="object"?t.shape:t._zod?.def?.shape&&typeof t._zod.def.shape=="object"?t._zod.def.shape:t._def?.shape?typeof t._def.shape=="function"?t._def.shape():t._def.shape:{}}function we(e){let t=e;return Array.isArray(t.options)?t.options:t._zod?.def?.entries?Object.values(t._zod.def.entries):Array.isArray(t._def?.values)?t._def.values:[]}function Te(e){let t=e;return t._zod?.def?.entries?t._zod.def.entries:t.enum&&typeof t.enum=="object"?t.enum:t._def?.values&&typeof t._def.values=="object"?t._def.values:{}}function nt(e){let t=e;return Array.isArray(t._zod?.def?.values)?t._zod.def.values[0]:t._def?.value}function rt(e){let t=e,n=[],r=t._zod?.def?.checks;if(Array.isArray(r)){for(let a of r)a.format&&n.push(a.format);if(n.length>0)return n}let s=t._def?.checks;if(Array.isArray(s))for(let a of s)a.kind&&n.push(a.kind);return n}function _t(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/^\s/,"").replace(/^./,t=>t.toUpperCase())}function st(e){let t=e,n=true,r=false,s;for(;;){let a=z(t);if(a==="ZodOptional")n=false,t=M(t);else if(a==="ZodNullable")n=false,r=true,t=M(t);else if(a==="ZodDefault")n=false,s=tt(t),t=M(t);else break}return {inner:t,required:n,nullable:r,defaultValue:s}}function Q(e,t=""){if(z(e)==="ZodObject"){let r=ce(e);return Object.entries(r).map(([s,a])=>at(t?`${t}.${s}`:s,s,a))}return [at(t||"value",t||"value",e)]}function at(e,t,n){let{inner:r,required:s,nullable:a,defaultValue:o}=st(n),c=z(r),l=_t(t.split(".").pop()??t);switch(c){case "ZodString":{let i=rt(r),d=i.includes("email"),g=i.includes("url");return {name:e,label:l,type:"text",required:s,nullable:a,defaultValue:o,hint:d?"email":g?"url":void 0}}case "ZodNumber":case "ZodBigInt":return {name:e,label:l,type:"number",required:s,nullable:a,defaultValue:o};case "ZodBoolean":return {name:e,label:l,type:"checkbox",required:s,nullable:a,defaultValue:o};case "ZodDate":case "ZodCoerce":return {name:e,label:l,type:"datetime-local",required:s,nullable:a,defaultValue:o};case "ZodEnum":{let i=we(r);return {name:e,label:l,type:"select",required:s,nullable:a,defaultValue:o,options:i}}case "ZodNativeEnum":{let i=Te(r),d=Object.values(i).filter(g=>typeof g=="string");return {name:e,label:l,type:"select",required:s,nullable:a,defaultValue:o,options:d}}case "ZodLiteral":{let i=String(nt(r)??"");return {name:e,label:l,type:"select",required:s,nullable:a,defaultValue:o,options:[i]}}case "ZodObject":{let i=Q(r,e);return {name:e,label:l,type:"textarea",required:s,nullable:a,defaultValue:o,nested:i,hint:"JSON object"}}case "ZodArray":{let i=et(r);if(!i)return {name:e,label:l,type:"textarea",required:s,nullable:a,defaultValue:o,hint:"JSON array"};let{inner:d}=st(i),g=z(d),u,p,f;switch(g){case "ZodString":u="text";break;case "ZodNumber":case "ZodBigInt":u="number";break;case "ZodBoolean":u="checkbox";break;case "ZodDate":u="datetime-local";break;case "ZodEnum":u="select",p=we(d);break;case "ZodNativeEnum":u="select",p=Object.values(Te(d)).filter(b=>typeof b=="string");break;case "ZodObject":u="object",f=Q(d);break;default:return {name:e,label:l,type:"textarea",required:s,nullable:a,defaultValue:o,hint:"JSON array"}}return {name:e,label:l,type:"textarea",required:s,nullable:a,defaultValue:o,arrayElementType:u,arrayElementOptions:p,arrayElementFields:f}}default:return {name:e,label:l,type:"textarea",required:s,nullable:a,defaultValue:o,hint:"JSON"}}}function Ce(e,t=0){let n=t>0?`ml-${t*4}`:"",r=`field_${e.name.replace(/\./g,"__")}`,s=e.name,a=e.required?" required":"",o=e.defaultValue==="__null__",c=!o&&e.defaultValue!=null?String(e.defaultValue):"",l=e.nullable&&e.type!=="checkbox"?`<span class="flex items-center gap-1 shrink-0">
|
|
2
2
|
<input type="hidden" id="${r}__isnull" name="${s}__isnull" value="${o?"1":""}">
|
|
3
3
|
<label class="flex items-center gap-1 cursor-pointer select-none text-xs text-base-content/40 hover:text-base-content/70 border border-base-300 rounded px-2 py-1">
|
|
4
4
|
<input type="checkbox" class="checkbox checkbox-xs" ${o?"checked":""}
|
|
@@ -10,59 +10,59 @@
|
|
|
10
10
|
})(this)">
|
|
11
11
|
<span>null</span>
|
|
12
12
|
</label>
|
|
13
|
-
</span>`:"",i;switch(e.type){case "checkbox":if(e.nullable){let
|
|
13
|
+
</span>`:"",i;switch(e.type){case "checkbox":if(e.nullable){let d=o?"__null__":c==="true"?"true":c==="false"?"false":"__null__";return `
|
|
14
14
|
<div class="form-control mb-3 ${n}">
|
|
15
15
|
<label for="${r}" class="label pb-1">
|
|
16
16
|
<span class="label-text font-medium">
|
|
17
|
-
${
|
|
17
|
+
${C(e.label)}
|
|
18
18
|
<span class="text-base-content/40 text-xs ml-1">(nullable)</span>
|
|
19
19
|
</span>
|
|
20
20
|
</label>
|
|
21
21
|
<select id="${r}" name="${s}" class="select select-bordered select-sm w-full">
|
|
22
|
-
<option value="__null__"${
|
|
23
|
-
<option value="true"${
|
|
24
|
-
<option value="false"${
|
|
22
|
+
<option value="__null__"${d==="__null__"?" selected":""}>\u2014 null \u2014</option>
|
|
23
|
+
<option value="true"${d==="true"?" selected":""}>\u2713 true</option>
|
|
24
|
+
<option value="false"${d==="false"?" selected":""}>\u2717 false</option>
|
|
25
25
|
</select>
|
|
26
26
|
</div>`}return `
|
|
27
27
|
<div class="form-control ${n}">
|
|
28
28
|
<label class="label cursor-pointer justify-start gap-3">
|
|
29
|
-
<input type="checkbox" id="${r}" name="${s}" value="true"${
|
|
29
|
+
<input type="checkbox" id="${r}" name="${s}" value="true"${c==="true"?" checked":""} class="checkbox checkbox-primary checkbox-sm">
|
|
30
30
|
<span class="label-text font-medium">
|
|
31
|
-
${
|
|
31
|
+
${C(e.label)}${e.required?' <span class="text-error">*</span>':""}
|
|
32
32
|
</span>
|
|
33
33
|
</label>
|
|
34
34
|
</div>`;case "select":i=`<select id="${r}" name="${s}"${a}${o?' disabled style="opacity:0.35"':""} class="select select-bordered select-sm w-full">
|
|
35
35
|
${e.required&&!e.nullable?"":'<option value="">\u2014 optional \u2014</option>'}
|
|
36
|
-
${(e.options??[]).map(
|
|
36
|
+
${(e.options??[]).map(d=>`<option value="${C(d)}"${c===d?" selected":""}>${C(d)}</option>`).join(`
|
|
37
37
|
`)}
|
|
38
|
-
</select>`;break;case "textarea":if(e.arrayElementType)return Zt(e,t);if(e.nested&&e.nested.length>0){let
|
|
38
|
+
</select>`;break;case "textarea":if(e.arrayElementType)return Zt(e,t);if(e.nested&&e.nested.length>0){let d=e.nested.map(g=>Ce(g,t+1)).join(`
|
|
39
39
|
`);return `
|
|
40
40
|
<fieldset class="fieldset border border-base-300 rounded-box p-3 mb-3 ${n}">
|
|
41
41
|
<legend class="fieldset-legend text-xs font-semibold text-base-content/60 px-1">
|
|
42
|
-
${
|
|
42
|
+
${C(e.label)}${e.required?' <span class="text-error">*</span>':""}
|
|
43
43
|
</legend>
|
|
44
|
-
${
|
|
44
|
+
${d}
|
|
45
45
|
</fieldset>`}i=`<textarea id="${r}" name="${s}"${a} rows="3"${o?' disabled style="opacity:0.35"':""}
|
|
46
46
|
data-json
|
|
47
47
|
class="textarea textarea-bordered textarea-sm w-full font-mono text-xs"
|
|
48
|
-
placeholder="${
|
|
49
|
-
value="${
|
|
48
|
+
placeholder="${C(e.hint??"JSON")}">${C(c)}</textarea>`;break;default:i=`<input type="${e.type}" id="${r}" name="${s}"${a}${o?' disabled style="opacity:0.35"':""}
|
|
49
|
+
value="${C(c)}"
|
|
50
50
|
class="input input-bordered input-sm w-full"${e.hint==="email"?' autocomplete="email"':e.hint==="url"?' autocomplete="url"':""}>`;}return `
|
|
51
51
|
<div class="form-control mb-3 ${n}">
|
|
52
52
|
<label for="${r}" class="label pb-1">
|
|
53
53
|
<span class="label-text font-medium">
|
|
54
|
-
${
|
|
55
|
-
${e.hint?`<span class="text-base-content/40 text-xs ml-1">(${
|
|
54
|
+
${C(e.label)}${e.required?' <span class="text-error">*</span>':""}
|
|
55
|
+
${e.hint?`<span class="text-base-content/40 text-xs ml-1">(${C(e.hint)})</span>`:""}
|
|
56
56
|
</span>
|
|
57
57
|
</label>
|
|
58
58
|
<div class="flex items-center gap-2">
|
|
59
59
|
<div class="flex-1 min-w-0">${i}</div>
|
|
60
60
|
${l}
|
|
61
61
|
</div>
|
|
62
|
-
</div>`}function
|
|
63
|
-
`):o.map(
|
|
62
|
+
</div>`}function C(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Zt(e,t){let n=t>0?`ml-${t*4}`:"",r=`field_${e.name.replace(/\./g,"__")}`,s=e.defaultValue==="__null__",a=e.arrayElementType==="object",o=[];if(e.defaultValue!=null&&e.defaultValue!==""&&e.defaultValue!=="__null__")try{o=JSON.parse(String(e.defaultValue));}catch{}Array.isArray(o)||(o=[]);let c=a?o.map(d=>it(e,d??{})).join(`
|
|
63
|
+
`):o.map(d=>ot(e,d)).join(`
|
|
64
64
|
`),l=a?it(e,{}):ot(e,""),i=e.nullable?`<span class="flex items-center gap-1 mt-2">
|
|
65
|
-
<input type="hidden" id="${r}__isnull" name="${
|
|
65
|
+
<input type="hidden" id="${r}__isnull" name="${C(e.name)}__isnull" value="${s?"1":""}">
|
|
66
66
|
<label class="flex items-center gap-1 cursor-pointer select-none text-xs text-base-content/40 hover:text-base-content/70 border border-base-300 rounded px-2 py-1">
|
|
67
67
|
<input type="checkbox" class="checkbox checkbox-xs" ${s?"checked":""}
|
|
68
68
|
onchange="(function(cb){
|
|
@@ -76,24 +76,24 @@
|
|
|
76
76
|
</label>
|
|
77
77
|
</span>`:"";return `
|
|
78
78
|
<fieldset class="fieldset border border-base-300 rounded-box p-3 mb-3 ${n}"
|
|
79
|
-
data-frs-array="${
|
|
79
|
+
data-frs-array="${C(e.name)}" data-frs-array-type="${C(e.arrayElementType??"text")}">
|
|
80
80
|
<legend class="fieldset-legend text-xs font-semibold text-base-content/60 px-1">
|
|
81
|
-
${
|
|
81
|
+
${C(e.label)}${e.required?' <span class="text-error">*</span>':""}
|
|
82
82
|
</legend>
|
|
83
|
-
<input type="hidden" id="${r}" name="${
|
|
83
|
+
<input type="hidden" id="${r}" name="${C(e.name)}" value="${C(JSON.stringify(o))}"${s?" disabled":""}>
|
|
84
84
|
<div data-frs-array-items${s?' style="opacity:0.35"':""}>
|
|
85
|
-
${
|
|
85
|
+
${c}
|
|
86
86
|
</div>
|
|
87
87
|
<template data-frs-array-tpl>${l}</template>
|
|
88
88
|
<button type="button" class="btn btn-xs btn-outline mt-1" data-frs-array-add>+ Add</button>
|
|
89
89
|
${i}
|
|
90
90
|
</fieldset>`}function ot(e,t){let n=t!=null?String(t):"",r;switch(e.arrayElementType){case "select":r=`<select data-frs-val class="select select-bordered select-sm flex-1">
|
|
91
91
|
<option value="">\u2014</option>
|
|
92
|
-
${(e.arrayElementOptions??[]).map(s=>`<option value="${
|
|
92
|
+
${(e.arrayElementOptions??[]).map(s=>`<option value="${C(s)}"${n===s?" selected":""}>${C(s)}</option>`).join("")}
|
|
93
93
|
</select>`;break;case "checkbox":r=`<label class="flex items-center gap-2 flex-1 cursor-pointer">
|
|
94
94
|
<input type="checkbox" data-frs-val class="checkbox checkbox-sm checkbox-primary"${n==="true"?" checked":""}>
|
|
95
95
|
<span class="text-sm">true</span>
|
|
96
|
-
</label>`;break;case "number":r=`<input type="number" data-frs-val value="${
|
|
96
|
+
</label>`;break;case "number":r=`<input type="number" data-frs-val value="${C(n)}" class="input input-bordered input-sm flex-1">`;break;case "datetime-local":r=`<input type="datetime-local" data-frs-val value="${C(n)}" class="input input-bordered input-sm flex-1">`;break;default:r=`<input type="text" data-frs-val value="${C(n)}" class="input input-bordered input-sm flex-1">`;}return `<div class="flex items-center gap-2 mb-2" data-frs-array-item>
|
|
97
97
|
${r}
|
|
98
98
|
<button type="button" class="btn btn-xs btn-ghost text-error" data-frs-array-rm>×</button>
|
|
99
99
|
</div>`}function it(e,t){return `<div class="border border-base-200 rounded p-3 mb-2" data-frs-array-item>
|
|
@@ -102,38 +102,38 @@
|
|
|
102
102
|
</div>
|
|
103
103
|
${(e.arrayElementFields??[]).map(s=>{let a=t[s.name],o=a==null?"":typeof a=="object"?JSON.stringify(a):String(a);switch(s.type){case "checkbox":return `<div class="form-control mb-2">
|
|
104
104
|
<label class="label cursor-pointer justify-start gap-3">
|
|
105
|
-
<input type="checkbox" data-frs-key="${
|
|
106
|
-
<span class="label-text text-sm">${
|
|
105
|
+
<input type="checkbox" data-frs-key="${C(s.name)}" class="checkbox checkbox-sm checkbox-primary"${o==="true"?" checked":""}>
|
|
106
|
+
<span class="label-text text-sm">${C(s.label)}</span>
|
|
107
107
|
</label>
|
|
108
108
|
</div>`;case "select":return `<div class="form-control mb-2">
|
|
109
|
-
<label class="label pb-1"><span class="label-text text-sm">${
|
|
110
|
-
<select data-frs-key="${
|
|
109
|
+
<label class="label pb-1"><span class="label-text text-sm">${C(s.label)}</span></label>
|
|
110
|
+
<select data-frs-key="${C(s.name)}" class="select select-bordered select-sm w-full">
|
|
111
111
|
${s.required?"":'<option value="">\u2014</option>'}
|
|
112
|
-
${(s.options??[]).map(
|
|
112
|
+
${(s.options??[]).map(c=>`<option value="${C(c)}"${o===c?" selected":""}>${C(c)}</option>`).join("")}
|
|
113
113
|
</select>
|
|
114
114
|
</div>`;case "number":return `<div class="form-control mb-2">
|
|
115
|
-
<label class="label pb-1"><span class="label-text text-sm">${
|
|
116
|
-
<input type="number" data-frs-key="${
|
|
115
|
+
<label class="label pb-1"><span class="label-text text-sm">${C(s.label)}</span></label>
|
|
116
|
+
<input type="number" data-frs-key="${C(s.name)}" value="${C(o)}" class="input input-bordered input-sm w-full">
|
|
117
117
|
</div>`;case "datetime-local":return `<div class="form-control mb-2">
|
|
118
|
-
<label class="label pb-1"><span class="label-text text-sm">${
|
|
119
|
-
<input type="datetime-local" data-frs-key="${
|
|
118
|
+
<label class="label pb-1"><span class="label-text text-sm">${C(s.label)}</span></label>
|
|
119
|
+
<input type="datetime-local" data-frs-key="${C(s.name)}" value="${C(o)}" class="input input-bordered input-sm w-full">
|
|
120
120
|
</div>`;case "textarea":return `<div class="form-control mb-2">
|
|
121
|
-
<label class="label pb-1"><span class="label-text text-sm">${
|
|
122
|
-
<textarea data-frs-key="${
|
|
121
|
+
<label class="label pb-1"><span class="label-text text-sm">${C(s.label)}</span></label>
|
|
122
|
+
<textarea data-frs-key="${C(s.name)}" rows="2" class="textarea textarea-bordered textarea-sm w-full font-mono text-xs" placeholder="JSON">${C(o)}</textarea>
|
|
123
123
|
</div>`;default:return `<div class="form-control mb-2">
|
|
124
|
-
<label class="label pb-1"><span class="label-text text-sm">${
|
|
125
|
-
<input type="text" data-frs-key="${
|
|
124
|
+
<label class="label pb-1"><span class="label-text text-sm">${C(s.label)}</span></label>
|
|
125
|
+
<input type="text" data-frs-key="${C(s.name)}" value="${C(o)}" class="input input-bordered input-sm w-full">
|
|
126
126
|
</div>`}}).join(`
|
|
127
127
|
`)}
|
|
128
|
-
</div>`}function V(e,t,n,r="Save"){let s=e.map(a=>
|
|
128
|
+
</div>`}function V(e,t,n,r="Save"){let s=e.map(a=>Ce(a)).join(`
|
|
129
129
|
`);return `
|
|
130
|
-
<form action="${
|
|
130
|
+
<form action="${C(t)}" method="${n}" novalidate data-frs-form>
|
|
131
131
|
${s}
|
|
132
132
|
<div class="flex gap-2 mt-4 pt-4 border-t border-base-200">
|
|
133
|
-
<button type="submit" class="btn btn-primary btn-sm">${
|
|
133
|
+
<button type="submit" class="btn btn-primary btn-sm">${C(r)}</button>
|
|
134
134
|
<button type="button" class="btn btn-ghost btn-sm" onclick="history.back()">Cancel</button>
|
|
135
135
|
</div>
|
|
136
|
-
</form>`}function lt({val:e}){return jsxRuntime.jsx("span",{class:"text-sm text-base-content/80 font-mono tabular-nums whitespace-nowrap",children:e.toLocaleString()})}function
|
|
136
|
+
</form>`}function lt({val:e}){return jsxRuntime.jsx("span",{class:"text-sm text-base-content/80 font-mono tabular-nums whitespace-nowrap",children:e.toLocaleString()})}function Se({val:e}){if(e==null)return jsxRuntime.jsx("span",{class:"opacity-30 italic text-xs",children:"\u2014"});if(typeof e=="boolean")return e?jsxRuntime.jsx("span",{class:"badge badge-success badge-sm",children:"true"}):jsxRuntime.jsx("span",{class:"badge badge-error badge-sm",children:"false"});if(e instanceof Date)return jsxRuntime.jsx(lt,{val:e});if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")return jsxRuntime.jsx(lt,{val:e.toDate()});if(typeof e=="number")return jsxRuntime.jsx("span",{class:"text-sm font-mono tabular-nums",children:String(e)});if(Array.isArray(e))return e.length===0?jsxRuntime.jsx("span",{class:"text-xs text-base-content/30",children:"[]"}):jsxRuntime.jsxs("ul",{class:"list-none p-0 m-0 space-y-0.5 text-xs",children:[e.slice(0,8).map((n,r)=>jsxRuntime.jsx("li",{class:"break-all",children:typeof n=="object"?JSON.stringify(n):String(n)},r)),e.length>8&&jsxRuntime.jsxs("li",{class:"text-base-content/40 italic",children:["+",e.length-8," more\u2026"]})]});if(typeof e=="object"&&e!==null){let n=Object.entries(e);return n.length===0?jsxRuntime.jsx("span",{class:"text-xs text-base-content/30",children:"{}"}):jsxRuntime.jsxs("dl",{class:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 text-xs m-0",children:[n.slice(0,8).map(([r,s])=>jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("dt",{class:"text-base-content/50 font-semibold whitespace-nowrap",children:r}),jsxRuntime.jsx("dd",{class:"break-all",children:String(s??"")})]})),n.length>8&&jsxRuntime.jsxs("dt",{class:"col-span-2 text-base-content/40 italic",children:["+",n.length-8," more\u2026"]})]})}let t=String(e);return jsxRuntime.jsx("span",{class:"text-sm break-all",children:t})}var ct=`// \u2500\u2500 Form validation + array serialization \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
137
137
|
document.addEventListener("submit", function (e) {
|
|
138
138
|
var form = e.target;
|
|
139
139
|
if (!form.hasAttribute("data-frs-form")) return;
|
|
@@ -552,7 +552,7 @@ function initColumnReorder(table) {
|
|
|
552
552
|
});
|
|
553
553
|
});
|
|
554
554
|
}
|
|
555
|
-
`;function ue(){return jsxRuntime.jsx("script",{dangerouslySetInnerHTML:{__html:ct}})}function te(e){return "<!DOCTYPE html>"+server.renderToString(e)}var ne=({opts:e,children:t})=>{let{title:n,breadcrumb:r,flash:s,basePath:a="/"}=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("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.jsx("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:a,class:"font-bold text-lg tracking-tight hover:opacity-80 transition-opacity",children:"FRS Admin"})})}),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((o,d)=>o.href?jsxRuntime.jsx("li",{children:jsxRuntime.jsx("a",{href:o.href,children:o.label})},d):jsxRuntime.jsx("li",{class:"text-base-content/60",children:o.label},d))})}),jsxRuntime.jsx("h1",{class:"text-2xl font-bold mb-6",children:n}),s&&jsxRuntime.jsx("div",{role:"alert",class:`alert ${s.type==="success"?"alert-success":"alert-error"} mb-6`,children:jsxRuntime.jsx("span",{children:s.message})}),t]}),jsxRuntime.jsx(ue,{})]})]})};function Ae(e,t){return te(jsxRuntime.jsx(ne,{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 ut=[{value:"==",label:"="},{value:"!=",label:"\u2260"}],Kt=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"<",label:"<"},{value:"<=",label:"\u2264"},{value:">",label:">"},{value:">=",label:"\u2265"}],Bt=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function qt(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return Kt;case "ZodBoolean":return ut;case "ZodArray":return Bt;default:return ut}}function Qt({col:e,active:t}){let n=t?.value??"";if(e.zodType==="ZodBoolean")return jsxRuntime.jsxs("select",{name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",children:[jsxRuntime.jsx("option",{value:"",selected:n==="",children:"\u2014"}),jsxRuntime.jsx("option",{value:"true",selected:n==="true",children:"true"}),jsxRuntime.jsx("option",{value:"false",selected:n==="false",children:"false"})]});if(e.zodType==="ZodArray"){let r=t?.op==="array-contains-any";return jsxRuntime.jsx("input",{type:"text",name:`fv_${e.name}`,value:n,placeholder:r?"val1, val2, \u2026":"value",class:"input input-sm input-bordered w-full"})}return e.zodType==="ZodNumber"||e.zodType==="ZodBigInt"?jsxRuntime.jsx("input",{type:"number",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full"}):e.zodType==="ZodDate"?jsxRuntime.jsx("input",{type:"datetime-local",name:`fv_${e.name}`,value:n,class:"input input-sm input-bordered w-full"}):jsxRuntime.jsx("input",{type:"text",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full"})}function Oe({action:e,columnMeta:t,activeFilters:n}){let r=Object.fromEntries(n.map(o=>[o.field,o])),s=n.length>0,a=t.filter(o=>o.zodType!=="ZodObject"&&o.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:a.map(o=>{let d=qt(o.zodType),l=r[o.name],i=l?.op??d[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:o.name}),jsxRuntime.jsxs("div",{class:"flex gap-1.5",children:[d.length>1?jsxRuntime.jsx("select",{name:`fo_${o.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:d.map(c=>jsxRuntime.jsx("option",{value:c.value,selected:c.value===i,children:c.label},c.value))}):jsxRuntime.jsx("input",{type:"hidden",name:`fo_${o.name}`,value:d[0].value}),jsxRuntime.jsx(Qt,{col:o,active:l})]})]},o.name)})}),jsxRuntime.jsxs("div",{class:"flex gap-2 mt-4 pt-3 border-t border-base-200",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"})]})]})})]})}function $e(e,t,n,r,s,a){let o=n==="create"?`Create ${e}`:`Edit ${e} / ${r??""}`,d=n==="create"?[{label:"Repositories",href:s},{label:e,href:`${s}/${e}`},{label:"New document"}]:[{label:"Repositories",href:s},{label:e,href:`${s}/${e}`},{label:`Edit ${r??""}`}];return te(jsxRuntime.jsx(ne,{opts:{title:o,breadcrumb:d,basePath:s,flash:a},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}})})})}))}function ke(e,t,n){let r=new URLSearchParams;for(let s of e)r.set(`fv_${s.field}`,s.value),r.set(`fo_${s.field}`,s.op);return t&&(r.set("ob",t.field),r.set("od",t.dir)),n&&r.set("ps",String(n)),r}function pt(e,t,n,r,s){let a=ke(e,r,s);return a.set("cursor",t),a.set("dir",n),`?${a.toString()}`}function Wt(e,t,n,r){let s=ke(n,void 0,r);return t?.field===e?t.dir==="asc"&&(s.set("ob",e),s.set("od","desc")):(s.set("ob",e),s.set("od","asc")),`?${s.toString()}`}function Ut(e,t,n){return `?${ke(t,n,e).toString()}`}function Pe(e,t,n,r,s,a,o=[],d=[],l=false,i=[],c,g){let u=`${r}/${e}`,p=`${u}/create`;return te(jsxRuntime.jsxs(ne,{opts:{title:e,breadcrumb:[{label:"Repositories",href:r},{label:e}],basePath:r,flash:a},children:[o.length>0&&jsxRuntime.jsx(Oe,{action:u,columnMeta:o,activeFilters:d}),jsxRuntime.jsxs("div",{class:"flex flex-wrap justify-between items-center mb-4 gap-3",children:[jsxRuntime.jsxs("div",{class:"flex items-center gap-3",children:[jsxRuntime.jsxs("span",{class:"text-sm text-base-content/60",children:[t.length," document",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(f=>jsxRuntime.jsx("a",{href:Ut(f,d,c),class:`join-item btn btn-xs ${g===f?"btn-active btn-primary":"btn-outline"}`,children:f},f))})]})]}),jsxRuntime.jsx("a",{href:p,class:"btn btn-primary btn-sm",children:"+ New"})]}),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:[[...n].map((f,b)=>{let m=c?.field===f,y=m?c.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:Wt(f,c,d,g),class:`hover:text-base-content inline-flex items-center gap-0.5${m?" text-primary font-bold":""}`,children:[f,y]})},b)}),i.map((f,b)=>jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:f.column},`rel-${b}`)),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+i.length+1,class:"text-center py-16 text-base-content/40",children:"No documents found"})}):t.map((f,b)=>{let m=String(f.docId??f.id??""),y=`${r}/${e}/${encodeURIComponent(m)}/edit`,h=`${r}/${e}/${encodeURIComponent(m)}/delete`;return jsxRuntime.jsxs("tr",{class:"hover",children:[n.map((v,R)=>jsxRuntime.jsx("td",{class:"align-top py-2",children:jsxRuntime.jsx(Ce,{val:f[v]})},R)),i.map((v,R)=>{let x=f[v.key];if(x==null||x==="")return jsxRuntime.jsx("td",{class:"py-2"},`rel-${R}`);let w=`${r}/${v.targetRepo}?fv_${v.targetKey}=${encodeURIComponent(String(x))}`;return jsxRuntime.jsx("td",{class:"align-middle py-2",children:jsxRuntime.jsx("a",{href:w,class:"btn btn-xs btn-ghost btn-outline",children:v.column})},`rel-${R}`)}),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:y,class:"btn btn-xs btn-outline",children:"Edit"}),l&&jsxRuntime.jsx("form",{method:"post",action:h,onsubmit:"return confirm('Delete this document?')",children:jsxRuntime.jsx("button",{type:"submit",class:"btn btn-xs btn-error btn-outline",children:"Delete"})})]})})]},b)})})]})}),(s.hasPrev||s.hasNext)&&jsxRuntime.jsxs("div",{class:"flex justify-center items-center mt-6 gap-2",children:[s.hasPrev?jsxRuntime.jsx("a",{href:pt(d,s.prevCursor,"prev",c,g),class:"btn btn-sm btn-outline",children:"\u2190 Previous"}):jsxRuntime.jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"\u2190 Previous"}),s.hasNext?jsxRuntime.jsx("a",{href:pt(d,s.nextCursor,"next",c,g),class:"btn btn-sm btn-outline",children:"Next \u2192"}):jsxRuntime.jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"Next \u2192"})]})]}))}function De(e,t){return Ae(e,t)}function Ee(e,t,n,r,s,a,o,d,l,i,c,g){return Pe(e,t,n,r,s,a,o,d,l,i,c,g)}function X(e,t,n,r,s,a){return $e(e,t,n,r,s,a)}var ft="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Gt(){let e="";for(let t=0;t<20;t++)e+=ft.charAt(Math.floor(Math.random()*ft.length));return e}function yt(e,t){if(!t)return;let n=e[t];if(typeof n!="string"||!n)return;let r=n.split("/").filter(Boolean),s=[];for(let a=1;a<r.length;a+=2)s.push(r[a]);return s.length>0?s:void 0}async function Fe(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 a=await e.repo.get[r](t);if(a)return a}catch{}return (await e.repo.query.by({where:[[n,"==",t]],limit:1}))[0]??null}function $(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function Ie(e,t){e.status(302).set("Location",t).send("");}function _e(e,t){let n=t.shape,r={};for(let[s,a]of Object.entries(n)){let o=ze(a);if(o==="ZodObject"){if(e[s+"__isnull"]==="1"){r[s]=null;continue}let i={},c=false;for(let[p,f]of Object.entries(e))p.startsWith(`${s}.`)&&(i[p.slice(s.length+1)]=f,c=true);if(c){let p=a;for(;;){let f=z(p);if(f==="ZodOptional"||f==="ZodNullable"||f==="ZodDefault")p=M(p);else break}r[s]=_e(i,p);continue}let g=e[s],u=Array.isArray(g)?g[g.length-1]:g;if(u)try{r[s]=JSON.parse(u);}catch{r[s]=u;}continue}let d=e[s],l=Array.isArray(d)?d[d.length-1]:d;if(e[s+"__isnull"]==="1"){r[s]=null;continue}if(l===void 0||l===""){o==="ZodBoolean"&&(r[s]=false);continue}switch(o){case "ZodBoolean":l==="__null__"?r[s]=null:r[s]=l==="true"||l==="on"||l==="1";break;case "ZodNumber":case "ZodBigInt":r[s]=Number(l);break;case "ZodDate":r[s]=new Date(l);break;case "ZodArray":try{r[s]=JSON.parse(l);}catch{r[s]=l;}break;default:if(l.startsWith("{")||l.startsWith("["))try{r[s]=JSON.parse(l);break}catch{}r[s]=l;}}return r}function mt(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 ze(e){let t=e;for(;;){let n=z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=M(t);else return n}}function gt(e,t,n=""){let r={};for(let s of Object.keys(t.shape)){let a=n?`${n}.${s}`:s,o=e[s];if(o===null){r[a]="__null__";continue}if(o===void 0)continue;let d=t.shape[s];for(;;){let i=z(d);if(i==="ZodOptional"||i==="ZodNullable"||i==="ZodDefault")d=M(d);else break}let l=z(d);if(l==="ZodObject"&&typeof o=="object"&&o!==null&&!Array.isArray(o)){let i=gt(o,d,a);Object.assign(r,i);}else if(l==="ZodDate"){let i=mt(o);i!==null&&(r[a]=i);}else if(typeof o=="object"&&o!==null&&!Array.isArray(o)&&("_seconds"in o||typeof o.toDate=="function")){let i=mt(o);r[a]=i??JSON.stringify(o,null,2);}else typeof o=="object"?r[a]=JSON.stringify(o,null,2):r[a]=String(o);}return r}function Ze(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?Ze(n.nested,t):void 0}))}function Vt(e,t){let n=new Set(["==","!=","<","<=",">",">=","array-contains","array-contains-any"]),r=[];for(let[s,a]of Object.entries(e)){if(!s.startsWith("fv_"))continue;let o=s.slice(3);if(!t.has(o))continue;let d=(a??"").trim();if(!d)continue;let l=e[`fo_${o}`]??"==",i=n.has(l)?l:"==";r.push({field:o,op:i,value:d});}return r}function Jt(e){let t=n=>n==="true"?true:n==="false"?false:n!==""&&!isNaN(Number(n))?Number(n):n;return e.map(n=>{if(n.op==="array-contains-any"){let r=n.value.split(",").map(s=>t(s.trim())).filter(s=>s!=="");return [n.field,n.op,r]}return [n.field,n.op,t(n.value)]})}function ht(e,t,n=""){let r=[];for(let s of e){let a=n?`${n}.${s}`:s,o=t.shape[s];if(!o){r.push({name:a,zodType:"ZodString"});continue}let d=ze(o);if(d==="ZodObject"){let l=o;for(;;){let c=z(l);if(c==="ZodOptional"||c==="ZodNullable"||c==="ZodDefault")l=M(l);else break}let i=ce(l);r.push(...ht(Object.keys(i),l,a));}else r.push({name:a,zodType:d});}return r}function Xt(e,t){let n=t.split("."),r=e;for(let s of n){for(;;){let o=z(r);if(o==="ZodOptional"||o==="ZodNullable"||o==="ZodDefault")r=M(r);else break}let a=ce(r);if(!(s in a))return null;r=a[s];}return r}function ae(e,t){if(!t||t.length===0)return e;let n=[],r=new Map;for(let a of t){let o=a.indexOf(".");if(o===-1)n.push(a);else {let d=a.slice(0,o),l=a.slice(o+1);r.has(d)||r.set(d,[]),r.get(d).push(l);}}let s={};for(let a of n)a in e.shape&&(s[a]=e.shape[a]);for(let[a,o]of r){if(!(a in e.shape))continue;let d=e.shape[a];for(;;){let l=z(d);if(l==="ZodOptional"||l==="ZodNullable"||l==="ZodDefault")d=M(d);else break}if(z(d)!=="ZodObject"){s[a]=e.shape[a];continue}s[a]=ae(d,o);}return zod.z.object(s)}function se(e,t){let n=t==="/"?"":t.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let a=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",o=process.env.FUNCTION_REGION??"us-central1",d=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${a}/${o}/${d}${n}`}let r=process.env.K_SERVICE,s=e.hostname??e.headers?.host??"";return r&&s.includes("cloudfunctions.net")?`/${r}${n}`:n}function bt(e,t){return {handleDashboard:(i,c)=>{let g=se(i,t),u=Object.values(e).map(p=>({name:p.name,path:p.path}));$(c,De(u,g));},handleList:async(i,c)=>{let g=i.params.repoName;if(!g){$(c,"Bad request",400);return}let u=e[g];if(!u){$(c,"Repository not found",404);return}let p=u.pageSize??25,f=i.query??{},b=f.cursor,m=f.dir==="prev"?"prev":"next",y=f.ob??"",h=f.od==="desc"?"desc":"asc",v=y?{field:y,dir:h}:void 0,R=parseInt(f.ps??""),x=Number.isFinite(R)&&R>0?Math.min(R,200):p,w=u.listColumns??Object.keys(u.schema.shape),T=u.documentKey??"docId",C=[T,...w.filter(Z=>Z!==T)],A=u.filterableFields?(()=>{let Z=[];for(let U of u.filterableFields)(U.includes(".")||w.includes(U))&&Z.push(U);return Z})():w,k=(()=>{let Z=[];for(let U of A)if(U.includes(".")){let Be=Xt(u.schema,U);Z.push({name:U,zodType:Be?ze(Be):"ZodString"});}else Z.push(...ht([U],u.schema));return Z})(),N=new Set(k.map(Z=>Z.name)),F=Vt(f,N),oe=Jt(F),D;if(b)try{let Z=u.repo.ref;typeof Z.doc=="function"&&(D=await Z.doc(b).get());}catch{}let q=await u.repo.query.paginate({pageSize:x,cursor:D,direction:m,...oe.length>0?{where:oe}:{},...v?{orderBy:[{field:v.field,direction:v.dir}]}:{}}),kt=q.nextCursor?.id??"",Pt=q.prevCursor?.id??"",Dt=se(i,t);$(c,Ee(u.name,q.data,C,Dt,{hasPrev:q.hasPrevPage,hasNext:q.hasNextPage,prevCursor:Pt,nextCursor:kt},void 0,k,F,u.allowDelete??false,u.relationalMeta,v,x));},handleCreateForm:(i,c)=>{let g=i.params.repoName;if(!g){$(c,"Bad request",400);return}let u=e[g];if(!u){$(c,"Repository not found",404);return}let p=se(i,t),f=ae(u.schema,u.createFields),b=Q(f),m=`${p}/${u.name}/create`,y=V(b,m,"POST","Create document");$(c,X(u.name,y,"create",null,p));},handleCreateSubmit:async(i,c)=>{let g=i.params.repoName;if(!g){$(c,"Bad request",400);return}let u=e[g];if(!u){$(c,"Repository not found",404);return}let p=se(i,t),f=i.body??{},b=_e(f,u.schema),m=ae(u.schema,u.createFields),y=m.safeParse(b);if(!y.success){let h=Q(m),v=`${p}/${u.name}/create`,R=V(h,v,"POST","Create document"),x=y.error.issues.map(w=>`${w.path.join(".")}: ${w.message}`).join(", ");$(c,X(u.name,R,"create",null,p,{type:"error",message:`Validation error: ${x}`}),422);return}try{if(u.isGroup&&u.parentKeys&&u.parentKeys.length>0){let h={...y.data};u.createdKey&&(h[u.createdKey]=new Date);let v=u.parentKeys.filter(T=>!h[T]);if(v.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${v.join(", ")}`);let R=u.parentKeys.map(T=>h[T]),x=u.documentKey??"docId",w=h[x]||Gt();await u.repo.set(...R,w,h);}else await u.repo.create(y.data);Ie(c,`${p}/${u.name}?flash=created`);}catch(h){let v=ae(u.schema,u.createFields),R=Q(v),x=`${p}/${u.name}/create`,w=V(R,x,"POST","Create document");$(c,X(u.name,w,"create",null,p,{type:"error",message:`Save error: ${h.message}`}),500);}},handleEditForm:async(i,c)=>{let g=i.params.repoName,u=i.params.id;if(!g||!u){$(c,"Bad request",400);return}let p=e[g];if(!p){$(c,"Repository not found",404);return}let f=null;try{f=await Fe(p,u);}catch(x){$(c,`Error fetching document: ${x.message}`,500);return}if(!f){$(c,"Document not found",404);return}let b=gt(f,p.schema),m=ae(p.schema,p.mutableFields),y=Ze(Q(m),b),h=se(i,t),v=`${h}/${p.name}/${encodeURIComponent(u)}/edit`,R=V(y,v,"POST","Save changes");$(c,X(p.name,R,"edit",u,h));},handleEditSubmit:async(i,c)=>{let g=i.params.repoName,u=i.params.id;if(!g||!u){$(c,"Bad request",400);return}let p=e[g];if(!p){$(c,"Repository not found",404);return}let f=se(i,t),b=i.body??{},m=_e(b,p.schema),y=ae(p.schema,p.mutableFields),v=y.partial().safeParse(m);if(!v.success){let R=Object.fromEntries(Object.entries(b).map(([A,k])=>[A,Array.isArray(k)?k.join(","):k??""])),x=Ze(Q(y),R),w=`${f}/${p.name}/${encodeURIComponent(u)}/edit`,T=V(x,w,"POST","Save changes"),C=v.error.issues.map(A=>`${A.path.join(".")}: ${A.message}`).join(", ");$(c,X(p.name,T,"edit",u,f,{type:"error",message:`Validation error: ${C}`}),422);return}try{let R=await Fe(p,u),x=(R&&yt(R,p.pathKey))??[u];await p.repo.update(...x,v.data),Ie(c,`${f}/${p.name}?flash=updated`);}catch(R){let x=ae(p.schema,p.mutableFields),w=Q(x),T=`${f}/${p.name}/${encodeURIComponent(u)}/edit`,C=V(w,T,"POST","Save changes");$(c,X(p.name,C,"edit",u,f,{type:"error",message:`Save error: ${R.message}`}),500);}},handleDelete:async(i,c)=>{let g=i.params.repoName,u=i.params.id;if(!g||!u){$(c,"Bad request",400);return}let p=e[g];if(!p){$(c,"Repository not found",404);return}if(!p.allowDelete){$(c,"Delete is not allowed for this repository",403);return}let f=se(i,t);try{let b=await Fe(p,u),m=(b&&yt(b,p.pathKey))??[u];await p.repo.delete(...m),Ie(c,`${f}/${p.name}?flash=deleted`);}catch(b){$(c,`Delete error: ${b.message}`,500);}}}}function Yt(e){let t=[],n=e.replace(/[.*+?^${}()|[\]\\]/g,r=>r===":"?r:`\\${r}`).replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(r,s)=>(t.push(s),"([^/]+)"));return {pattern:new RegExp(`^${n}$`),paramNames:t}}function en(e){let t=e.path??e.url??"/",n=t.indexOf("?");return n===-1?t:t.slice(0,n)}var H=class{constructor(){this.routes=[];this.middlewares=[];this.notFoundHandler=(t,n)=>{n.status(404).send("Not Found");};this.errorHandler=(t,n,r)=>{console.error("[MiniRouter]",t),r.status(500).send("Internal Server Error");};}use(t){return this.middlewares.push(t),this}get(t,n){return this.addRoute("GET",t,n)}post(t,n){return this.addRoute("POST",t,n)}put(t,n){return this.addRoute("PUT",t,n)}patch(t,n){return this.addRoute("PATCH",t,n)}delete(t,n){return this.addRoute("DELETE",t,n)}onNotFound(t){return this.notFoundHandler=t,this}onError(t){return this.errorHandler=t,this}addRoute(t,n,r){let{pattern:s,paramNames:a}=Yt(n);return this.routes.push({method:t.toUpperCase(),pattern:s,paramNames:a,handler:r}),this}async handle(t,n){let r=(t.method??"GET").toUpperCase(),s=en(t),a=null,o={};for(let i of this.routes){if(i.method!==r)continue;let c=s.match(i.pattern);if(c){a=i,o={},i.paramNames.forEach((g,u)=>{o[g]=decodeURIComponent(c[u+1]??"");});break}}let d=Object.assign(t,{params:o}),l=a?a.handler:this.notFoundHandler;try{await this.runMiddlewareChain(d,n,l);}catch(i){this.errorHandler(i,t,n);}}async runMiddlewareChain(t,n,r){let s=0,a=async()=>{if(s<this.middlewares.length){let o=this.middlewares[s++];await o(t,n,a);}else await r(t,n);};await a();}};async function tn(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function nn(e){let t={};if(!e)return t;for(let n of e.split("&")){let r=n.indexOf("=");if(r===-1)continue;let s=decodeURIComponent(n.slice(0,r).replace(/\+/g," ")),a=decodeURIComponent(n.slice(r+1).replace(/\+/g," ")),o=t[s];o===void 0?t[s]=a:Array.isArray(o)?o.push(a):t[s]=[o,a];}return t}function Rt(e){let{basePath:t="/",repos:n,parseBody:r=true,auth:s,middleware:a=[],httpsOptions:o}=e,d=t==="/"?"":t.replace(/\/$/,""),l={};for(let[u,p]of Object.entries(n)){let f=p.schema??p.repo.schema??null;if(!f)throw new Error(`[createAdminServer] Repository "${u}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let b,m,y;if(p.fieldsConfig){let R=p.fieldsConfig;b=[],m=[],y=[];for(let[x,w]of Object.entries(R))for(let T of w)T==="filterable"?b.push(x):T==="mutable"?m.push(x):T==="create"&&y.push(x);b.length===0&&(b=void 0),m.length===0&&(m=void 0),y.length===0&&(y=void 0);}let h=(()=>{let R=p.repo._parentKeys;return R&&R.length>0?R:void 0})();if(h&&y)for(let R of h)y.includes(R)||y.push(R);let v={name:u,path:p.path,repo:p.repo,schema:f,documentKey:p.documentKey??"docId",pathKey:p.repo._pathKey??void 0,isGroup:!!p.repo._isGroup,parentKeys:h,createdKey:p.repo._createdKey??void 0,listColumns:p.listColumns,pageSize:p.pageSize,filterableFields:b,mutableFields:m,createFields:y,allowDelete:p.allowDelete??false,relationalMeta:(()=>{if(!p.relationalFields||p.relationalFields.length===0)return;let R=p.repo.relationalKeys??{},x=[];for(let w of p.relationalFields){let T=R[w.key];T&&x.push({key:w.key,column:w.column,targetRepo:String(T.repo),targetKey:String(T.key),type:T.type});}return x.length>0?x:void 0})()};l[u]=v;}let i=bt(l,d),c=new H;if(r&&c.use(async(u,p,f)=>{let b=u,m=String(b.headers?.["content-type"]??"");if(m.includes("application/x-www-form-urlencoded")){let y=await tn(b);u.body=nn(y);}else if(m.includes("application/json")&&typeof b.body=="string")try{u.body=JSON.parse(b.body);}catch{}await f();}),s)if(typeof s=="function")c.use(s);else {let u=s.realm??"Admin",p="Basic "+Buffer.from(`${s.username}:${s.password}`).toString("base64");c.use((f,b,m)=>{if((f.headers?.authorization??"")!==p){b.status(401).set("WWW-Authenticate",`Basic realm="${u}"`).set("Content-Type","text/plain").send("Unauthorized");return}m();});}for(let u of a)c.use(u);c.get(`${d}/`,i.handleDashboard),c.get(`${d}`,i.handleDashboard),c.get(`${d}/:repoName`,i.handleList),c.get(`${d}/:repoName/create`,i.handleCreateForm),c.post(`${d}/:repoName/create`,i.handleCreateSubmit),c.get(`${d}/:repoName/:id/edit`,i.handleEditForm),c.post(`${d}/:repoName/:id/edit`,i.handleEditSubmit),c.post(`${d}/:repoName/:id/delete`,i.handleDelete);let g=async(u,p)=>{await c.handle(u,p);};return o&&(g.httpsOptions=o),g}function Ct(e,t,n=200){e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(t));}function ie(e,t,n,r=200){Ct(e,{success:true,data:t,meta:n},r);}function P(e,t,n=400){Ct(e,{success:false,error:t},n);}var vt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function rn(){let e="";for(let t=0;t<20;t++)e+=vt.charAt(Math.floor(Math.random()*vt.length));return e}function sn(e,t,n=[]){let r=e.shape,s={},a=t&&t.length>0?t:Object.keys(r);for(let o of a){if(n.includes(o))continue;let d=o.split(".")[0];d&&r[d]&&(s[d]=r[d]);}return zod.z.object(s)}function xt(e,t,n,r=false,s=[]){try{let a=sn(e,n,s);return {success:!0,data:(r?a.partial():a).parse(t)}}catch(a){return a instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${a.issues.map(d=>`${d.path.join(".")}: ${d.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function an(e,t){let n=[],r=t?new Set(t):null,s={eq:"==",ne:"!=",lt:"<",lte:"<=",gt:">",gte:">=",in:"in",nin:"not-in",contains:"array-contains",containsAny:"array-contains-any"};for(let[a,o]of Object.entries(e)){if(o===void 0||["cursor","limit","pageSize","orderBy","orderDir","select"].includes(a))continue;let d=Array.isArray(o)?o[0]:o;if(d===void 0||d==="")continue;let l=a.match(/^(\w+)__(\w+)$/),i,c="==";if(l&&l[1]&&l[2]){i=l[1];let u=l[2];if(s[u])c=s[u];else continue}else if(!l)i=a;else continue;if(r&&!r.has(i))continue;let g=d;c==="in"||c==="not-in"||c==="array-contains-any"?g=d.split(",").map(u=>wt(u.trim())):g=wt(d),n.push({field:i,op:c,value:g});}return n}function wt(e){if(e==="true")return true;if(e==="false")return false;if(e==="null")return null;let t=Number(e);return !isNaN(t)&&e!==""?t:e}function he(e){return e?{docId:e.id}:null}async function Tt(e,t){if(!t||typeof t!="object")return;let n=t.docId;if(typeof n=="string")try{let r=e.repo.ref;if(typeof r.doc!="function")return;let s=await r.doc(n).get();return s.exists?s:void 0}catch{return}}function At(e,t,n){function r(p,f){return !p||!e[p]?(P(f,`Repository "${p}" not found`,404),null):e[p]}function s(p,f){if(!f)return;let b=p[f];if(typeof b!="string"||!b)return;let m=b.split("/").filter(Boolean),y=[];for(let h=1;h<m.length;h+=2)y.push(m[h]);return y.length>0?y:void 0}async function a(p,f){let b=`by${p.documentKey.charAt(0).toUpperCase()}${p.documentKey.slice(1)}`,m=p.repo.get[b];if(typeof m=="function")try{let h=await m(f);if(h)return h}catch{}return (await p.repo.query.by({where:[[p.documentKey,"==",f]],limit:1}))[0]??null}async function o(p,f){let b=p.params||{},m=r(b.repoName,f);if(m)try{let y=p.query??{},h=Math.min(Number(y.pageSize)||m.pageSize,100),v=y.cursor,R=y.direction?.toLowerCase()==="prev"?"prev":"next",x=y.orderBy,w=y.orderDir?.toLowerCase()==="desc"?"desc":"asc",T=y.select,C=T?T.split(",").map(D=>D.trim()):void 0,A;m.allowedIncludes&&y.includes&&(A=(typeof y.includes=="string"?y.includes.split(",").map(q=>q.trim()):Array.isArray(y.includes)?y.includes:[]).filter(q=>typeof q=="string"&&m.allowedIncludes.includes(q)),A?.length===0&&(A=void 0));let k=an(y,m.filterableFields),N={pageSize:h,direction:R};if(v)try{let D=typeof v=="string"?JSON.parse(v):v;N.cursor=await Tt(m,D);}catch{}x&&(N.orderBy=[{field:x,direction:w}]),k.length>0&&(N.where=k.map(D=>[D.field,D.op,D.value])),C&&(N.select=C),A&&(N.include=A);let F=await m.repo.query.paginate(N),oe={items:F.data,hasNextPage:F.hasNextPage,hasPrevPage:F.hasPrevPage,nextCursor:he(F.nextCursor),prevCursor:he(F.prevCursor)};ie(f,oe,{pageSize:h,hasMore:F.hasNextPage});}catch(y){let h=n&&y instanceof Error?y.message:"Failed to fetch documents";P(f,h,500);}}async function d(p,f){let b=p.params||{},m=r(b.repoName,f);if(m)try{let y=p.body??{},h=Math.min(y.pageSize||m.pageSize,100),v=y.direction==="prev"?"prev":"next",R={pageSize:h,direction:v};if(y.cursor)try{let T=typeof y.cursor=="string"?JSON.parse(y.cursor):y.cursor;R.cursor=await Tt(m,T);}catch{}if(m.allowedIncludes&&y.includes&&y.includes.length>0){let T=y.includes.filter(C=>typeof C=="string"?m.allowedIncludes.includes(C):typeof C=="object"&&C!==null&&"relation"in C&&typeof C.relation=="string"?m.allowedIncludes.includes(C.relation):!1);T.length>0&&(R.include=T);}if(y.where&&y.where.length>0){if(m.filterableFields){let T=new Set(m.filterableFields),C=y.where.filter(A=>!T.has(A[0]));if(C.length>0){P(f,`Fields not filterable: ${C.map(A=>A[0]).join(", ")}`,400);return}}R.where=y.where;}if(y.orWhere&&y.orWhere.length>0){if(m.filterableFields){let T=new Set(m.filterableFields),C=y.orWhere.filter(A=>!T.has(A[0]));if(C.length>0){P(f,`Fields not filterable: ${C.map(A=>A[0]).join(", ")}`,400);return}}R.orWhere=y.orWhere;}if(y.orWhereGroups&&y.orWhereGroups.length>0){if(m.filterableFields){let T=new Set(m.filterableFields);for(let C of y.orWhereGroups){let A=C.filter(k=>!T.has(k[0]));if(A.length>0){P(f,`Fields not filterable: ${A.map(k=>k[0]).join(", ")}`,400);return}}}R.orWhereGroups=y.orWhereGroups;}y.orderBy&&y.orderBy.length>0&&(R.orderBy=y.orderBy),y.select&&y.select.length>0&&(R.select=y.select);let x=await m.repo.query.paginate(R),w={items:x.data,hasNextPage:x.hasNextPage,hasPrevPage:x.hasPrevPage,nextCursor:he(x.nextCursor),prevCursor:he(x.prevCursor)};ie(f,w,{pageSize:h,hasMore:x.hasNextPage});}catch(y){let h=n&&y instanceof Error?y.message:"Failed to query documents";P(f,h,500);}}async function l(p,f){let b=p.params||{},m=r(b.repoName,f);if(!m)return;let y=b.id;if(!y){P(f,"Document ID required",400);return}try{let h=await a(m,y);if(!h){P(f,"Document not found",404);return}ie(f,h);}catch(h){let v=n&&h instanceof Error?h.message:"Failed to fetch document";P(f,v,500);}}async function i(p,f){let b=p.params||{},m=r(b.repoName,f);if(m)try{let y=p.body??{},h=xt(m.schema,y,m.createFields,!1,m.systemKeys);if(!h.success){P(f,h.error,400);return}if(m.validate){let R=await m.validate(h.data,"create");if(R){P(f,R,400);return}}let v;if(m.isGroup&&m.parentKeys&&m.parentKeys.length>0){let R={...h.data};m.createdKey&&(R[m.createdKey]=new Date);let x=m.parentKeys.filter(C=>!R[C]);if(x.length>0){P(f,`Missing parent key(s) for subcollection create: ${x.join(", ")}`,400);return}let w=m.parentKeys.map(C=>R[C]),T=R[m.documentKey]||rn();v=await m.repo.set(...w,T,R);}else v=await m.repo.create(h.data);ie(f,v,void 0,201);}catch(y){let h=n&&y instanceof Error?y.message:"Failed to create document";P(f,h,500);}}async function c(p,f,b){let m=p.params||{},y=r(m.repoName,f);if(!y)return;let h=m.id;if(!h){P(f,"Document ID required",400);return}try{let v=p.body??{},R=xt(y.schema,v,y.mutableFields,b,y.systemKeys);if(!R.success){P(f,R.error,400);return}if(y.validate){let C=await y.validate(R.data,"update");if(C){P(f,C,400);return}}let x=await a(y,h),w=(x&&s(x,y.pathKey))??[h],T=await y.repo.update(...w,R.data);ie(f,T);}catch(v){let R=n&&v instanceof Error?v.message:"Failed to update document";P(f,R,500);}}async function g(p,f){let b=p.params||{},m=r(b.repoName,f);if(!m)return;if(!m.allowDelete){P(f,"Delete not allowed for this repository",403);return}let y=b.id;if(!y){P(f,"Document ID required",400);return}try{let h=await a(m,y),v=(h&&s(h,m.pathKey))??[y];await m.repo.delete(...v),ie(f,{deleted:!0});}catch(h){let v=n&&h instanceof Error?h.message:"Failed to delete document";P(f,v,500);}}function u(p,f){f.status(204).set("Access-Control-Allow-Methods","GET, POST, PUT, PATCH, DELETE, OPTIONS").set("Access-Control-Allow-Headers","Content-Type, Authorization").set("Access-Control-Max-Age","86400").send("");}return {handleList:o,handleQuery:d,handleGet:l,handleCreate:i,handleUpdate:c,handleDelete:g,handleOptions:u}}function je(e){try{return zod.z.toJSONSchema(e,{target:"openapi-3.1"})}catch{return {type:"object"}}}function B(e){return {$ref:`#/components/schemas/${e}`}}function _(e){return {description:e,content:{"application/json":{schema:B("ErrorResponse")}}}}function fe(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function Ot(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 on(e){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"},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"}]}function ln(e){let t=e.filterableFields??Object.keys(e.schema.shape),n=["eq","ne","lt","lte","gt","gte","in","nin","contains"],r=[];for(let s of t){r.push({name:s,in:"query",schema:{type:"string"},description:`Filter by ${s} (equality)`});for(let a of n)r.push({name:`${s}__${a}`,in:"query",schema:{type:"string"},description:`Filter ${s} with operator ${a}`});}return r}function cn(){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 dn(e,t,n,r,s){let a={},o=e.name,d=`${t}/${e.name}`,l=`${d}/{${e.documentKey}}`,i={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};a[d]={get:{operationId:`list${Y(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[o],parameters:[...on(e),...ln(e)],responses:{200:Ot(B(n)),500:_("Internal server error")}},post:{operationId:`create${Y(e.name)}`,summary:`Create a ${W(e.name)}`,tags:[o],requestBody:{required:true,content:{"application/json":{schema:B(r??n)}}},responses:{201:fe("Document created",B(n)),400:_("Validation error"),500:_("Internal server error")}}},a[`${d}/query`]={post:{operationId:`query${Y(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[o],requestBody:{required:true,content:{"application/json":{schema:B("QueryRequestBody")}}},responses:{200:Ot(B(n)),400:_("Invalid query"),500:_("Internal server error")}}};let c={};return c.get={operationId:`get${Y(W(e.name))}`,summary:`Get a single ${W(e.name)}`,tags:[o],parameters:[i],responses:{200:fe("Document found",B(n)),404:_("Document not found"),500:_("Internal server error")}},c.put={operationId:`update${Y(W(e.name))}`,summary:`Update a ${W(e.name)} (full replace)`,tags:[o],parameters:[i],requestBody:{required:true,content:{"application/json":{schema:B(s??n)}}},responses:{200:fe("Document updated",B(n)),400:_("Validation error"),404:_("Document not found"),500:_("Internal server error")}},c.patch={operationId:`patch${Y(W(e.name))}`,summary:`Partially update a ${W(e.name)}`,tags:[o],parameters:[i],requestBody:{required:true,content:{"application/json":{schema:{allOf:[B(s??n)],description:"All fields are optional for partial updates"}}}},responses:{200:fe("Document patched",B(n)),400:_("Validation error"),404:_("Document not found"),500:_("Internal server error")}},e.allowDelete&&(c.delete={operationId:`delete${Y(W(e.name))}`,summary:`Delete a ${W(e.name)}`,tags:[o],parameters:[i],responses:{200:fe("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:_("Document not found"),500:_("Internal server error")}}),a[l]=c,a}function Me(e,t,n={}){let{title:r="CRUD API",version:s="1.0.0",description:a,servers:o,auth:d=false}=n,l=t==="/"?"":t.replace(/\/$/,""),i={},c={},g=[];i.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},i.QueryRequestBody=cn();for(let[b,m]of Object.entries(e)){let y=Y(W(b)),h=`${y}Create`,v=`${y}Update`;i[y]=je(m.schema);let R=k=>{let N=k&&k.length>0?k:Object.keys(m.schema.shape),F={};for(let oe of N){let D=oe.split(".")[0];D&&m.schema.shape[D]&&!m.systemKeys.includes(D)&&(F[D]=m.schema.shape[D]);}return F},x=null,w=R(m.createFields);Object.keys(w).length>0&&(i[h]=je(zod.z.object(w)),x=h);let T=null,C=R(m.mutableFields);Object.keys(C).length>0&&(i[v]=je(zod.z.object(C)),T=v);let A=dn(m,l,y,x,T);Object.assign(c,A),g.push({name:b,description:`Operations on ${b} (collection: ${m.path})`});}let u={},p;return d==="basic"?(u.basicAuth={type:"http",scheme:"basic"},p=[{basicAuth:[]}]):d==="bearer"&&(u.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},p=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:s,...a?{description:a}:{}},...o&&o.length>0?{servers:o}:{},paths:c,components:{schemas:i,...Object.keys(u).length>0?{securitySchemes:u}:{}},...p?{security:p}:{},tags:g}}function Y(e){return e.charAt(0).toUpperCase()+e.slice(1)}function W(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}function un(e,t){return `<!DOCTYPE html>
|
|
555
|
+
`;function ue(){return jsxRuntime.jsx("script",{dangerouslySetInnerHTML:{__html:ct}})}function te(e){return "<!DOCTYPE html>"+server.renderToString(e)}var ne=({opts:e,children:t})=>{let{title:n,breadcrumb:r,flash:s,basePath:a="/"}=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("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.jsx("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:a,class:"font-bold text-lg tracking-tight hover:opacity-80 transition-opacity",children:"FRS Admin"})})}),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((o,c)=>o.href?jsxRuntime.jsx("li",{children:jsxRuntime.jsx("a",{href:o.href,children:o.label})},c):jsxRuntime.jsx("li",{class:"text-base-content/60",children:o.label},c))})}),jsxRuntime.jsx("h1",{class:"text-2xl font-bold mb-6",children:n}),s&&jsxRuntime.jsx("div",{role:"alert",class:`alert ${s.type==="success"?"alert-success":"alert-error"} mb-6`,children:jsxRuntime.jsx("span",{children:s.message})}),t]}),jsxRuntime.jsx(ue,{})]})]})};function Ae(e,t){return te(jsxRuntime.jsx(ne,{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 ut=[{value:"==",label:"="},{value:"!=",label:"\u2260"}],Kt=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"<",label:"<"},{value:"<=",label:"\u2264"},{value:">",label:">"},{value:">=",label:"\u2265"}],Bt=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function qt(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return Kt;case "ZodBoolean":return ut;case "ZodArray":return Bt;default:return ut}}function Qt({col:e,active:t}){let n=t?.value??"";if(e.zodType==="ZodBoolean")return jsxRuntime.jsxs("select",{name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",children:[jsxRuntime.jsx("option",{value:"",selected:n==="",children:"\u2014"}),jsxRuntime.jsx("option",{value:"true",selected:n==="true",children:"true"}),jsxRuntime.jsx("option",{value:"false",selected:n==="false",children:"false"})]});if(e.zodType==="ZodArray"){let r=t?.op==="array-contains-any";return jsxRuntime.jsx("input",{type:"text",name:`fv_${e.name}`,value:n,placeholder:r?"val1, val2, \u2026":"value",class:"input input-sm input-bordered w-full"})}return e.zodType==="ZodNumber"||e.zodType==="ZodBigInt"?jsxRuntime.jsx("input",{type:"number",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full"}):e.zodType==="ZodDate"?jsxRuntime.jsx("input",{type:"datetime-local",name:`fv_${e.name}`,value:n,class:"input input-sm input-bordered w-full"}):jsxRuntime.jsx("input",{type:"text",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full"})}function Oe({action:e,columnMeta:t,activeFilters:n}){let r=Object.fromEntries(n.map(o=>[o.field,o])),s=n.length>0,a=t.filter(o=>o.zodType!=="ZodObject"&&o.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:a.map(o=>{let c=qt(o.zodType),l=r[o.name],i=l?.op??c[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:o.name}),jsxRuntime.jsxs("div",{class:"flex gap-1.5",children:[c.length>1?jsxRuntime.jsx("select",{name:`fo_${o.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:c.map(d=>jsxRuntime.jsx("option",{value:d.value,selected:d.value===i,children:d.label},d.value))}):jsxRuntime.jsx("input",{type:"hidden",name:`fo_${o.name}`,value:c[0].value}),jsxRuntime.jsx(Qt,{col:o,active:l})]})]},o.name)})}),jsxRuntime.jsxs("div",{class:"flex gap-2 mt-4 pt-3 border-t border-base-200",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"})]})]})})]})}function $e(e,t,n,r,s,a){let o=n==="create"?`Create ${e}`:`Edit ${e} / ${r??""}`,c=n==="create"?[{label:"Repositories",href:s},{label:e,href:`${s}/${e}`},{label:"New document"}]:[{label:"Repositories",href:s},{label:e,href:`${s}/${e}`},{label:`Edit ${r??""}`}];return te(jsxRuntime.jsx(ne,{opts:{title:o,breadcrumb:c,basePath:s,flash:a},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}})})})}))}function ke(e,t,n){let r=new URLSearchParams;for(let s of e)r.set(`fv_${s.field}`,s.value),r.set(`fo_${s.field}`,s.op);return t&&(r.set("ob",t.field),r.set("od",t.dir)),n&&r.set("ps",String(n)),r}function pt(e,t,n,r,s){let a=ke(e,r,s);return a.set("cursor",t),a.set("dir",n),`?${a.toString()}`}function Wt(e,t,n,r){let s=ke(n,void 0,r);return t?.field===e?t.dir==="asc"&&(s.set("ob",e),s.set("od","desc")):(s.set("ob",e),s.set("od","asc")),`?${s.toString()}`}function Ut(e,t,n){return `?${ke(t,n,e).toString()}`}function Pe(e,t,n,r,s,a,o=[],c=[],l=false,i=[],d,g){let u=`${r}/${e}`,p=`${u}/create`;return te(jsxRuntime.jsxs(ne,{opts:{title:e,breadcrumb:[{label:"Repositories",href:r},{label:e}],basePath:r,flash:a},children:[o.length>0&&jsxRuntime.jsx(Oe,{action:u,columnMeta:o,activeFilters:c}),jsxRuntime.jsxs("div",{class:"flex flex-wrap justify-between items-center mb-4 gap-3",children:[jsxRuntime.jsxs("div",{class:"flex items-center gap-3",children:[jsxRuntime.jsxs("span",{class:"text-sm text-base-content/60",children:[t.length," document",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(f=>jsxRuntime.jsx("a",{href:Ut(f,c,d),class:`join-item btn btn-xs ${g===f?"btn-active btn-primary":"btn-outline"}`,children:f},f))})]})]}),jsxRuntime.jsx("a",{href:p,class:"btn btn-primary btn-sm",children:"+ New"})]}),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:[[...n].map((f,b)=>{let m=d?.field===f,y=m?d.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:Wt(f,d,c,g),class:`hover:text-base-content inline-flex items-center gap-0.5${m?" text-primary font-bold":""}`,children:[f,y]})},b)}),i.map((f,b)=>jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:f.column},`rel-${b}`)),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+i.length+1,class:"text-center py-16 text-base-content/40",children:"No documents found"})}):t.map((f,b)=>{let m=String(f.docId??f.id??""),y=`${r}/${e}/${encodeURIComponent(m)}/edit`,h=`${r}/${e}/${encodeURIComponent(m)}/delete`;return jsxRuntime.jsxs("tr",{class:"hover",children:[n.map((v,R)=>jsxRuntime.jsx("td",{class:"align-top py-2",children:jsxRuntime.jsx(Se,{val:f[v]})},R)),i.map((v,R)=>{let x=f[v.key];if(x==null||x==="")return jsxRuntime.jsx("td",{class:"py-2"},`rel-${R}`);let w=`${r}/${v.targetRepo}?fv_${v.targetKey}=${encodeURIComponent(String(x))}`;return jsxRuntime.jsx("td",{class:"align-middle py-2",children:jsxRuntime.jsx("a",{href:w,class:"btn btn-xs btn-ghost btn-outline",children:v.column})},`rel-${R}`)}),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:y,class:"btn btn-xs btn-outline",children:"Edit"}),l&&jsxRuntime.jsx("form",{method:"post",action:h,onsubmit:"return confirm('Delete this document?')",children:jsxRuntime.jsx("button",{type:"submit",class:"btn btn-xs btn-error btn-outline",children:"Delete"})})]})})]},b)})})]})}),(s.hasPrev||s.hasNext)&&jsxRuntime.jsxs("div",{class:"flex justify-center items-center mt-6 gap-2",children:[s.hasPrev?jsxRuntime.jsx("a",{href:pt(c,s.prevCursor,"prev",d,g),class:"btn btn-sm btn-outline",children:"\u2190 Previous"}):jsxRuntime.jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"\u2190 Previous"}),s.hasNext?jsxRuntime.jsx("a",{href:pt(c,s.nextCursor,"next",d,g),class:"btn btn-sm btn-outline",children:"Next \u2192"}):jsxRuntime.jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"Next \u2192"})]})]}))}function De(e,t){return Ae(e,t)}function Ee(e,t,n,r,s,a,o,c,l,i,d,g){return Pe(e,t,n,r,s,a,o,c,l,i,d,g)}function X(e,t,n,r,s,a){return $e(e,t,n,r,s,a)}var ft="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Gt(){let e="";for(let t=0;t<20;t++)e+=ft.charAt(Math.floor(Math.random()*ft.length));return e}function yt(e,t){if(!t)return;let n=e[t];if(typeof n!="string"||!n)return;let r=n.split("/").filter(Boolean),s=[];for(let a=1;a<r.length;a+=2)s.push(r[a]);return s.length>0?s:void 0}async function Fe(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 a=await e.repo.get[r](t);if(a)return a}catch{}return (await e.repo.query.by({where:[[n,"==",t]],limit:1}))[0]??null}function $(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function Ie(e,t){e.status(302).set("Location",t).send("");}function _e(e,t){let n=t.shape,r={};for(let[s,a]of Object.entries(n)){let o=ze(a);if(o==="ZodObject"){if(e[s+"__isnull"]==="1"){r[s]=null;continue}let i={},d=false;for(let[p,f]of Object.entries(e))p.startsWith(`${s}.`)&&(i[p.slice(s.length+1)]=f,d=true);if(d){let p=a;for(;;){let f=z(p);if(f==="ZodOptional"||f==="ZodNullable"||f==="ZodDefault")p=M(p);else break}r[s]=_e(i,p);continue}let g=e[s],u=Array.isArray(g)?g[g.length-1]:g;if(u)try{r[s]=JSON.parse(u);}catch{r[s]=u;}continue}let c=e[s],l=Array.isArray(c)?c[c.length-1]:c;if(e[s+"__isnull"]==="1"){r[s]=null;continue}if(l===void 0||l===""){o==="ZodBoolean"&&(r[s]=false);continue}switch(o){case "ZodBoolean":l==="__null__"?r[s]=null:r[s]=l==="true"||l==="on"||l==="1";break;case "ZodNumber":case "ZodBigInt":r[s]=Number(l);break;case "ZodDate":r[s]=new Date(l);break;case "ZodArray":try{r[s]=JSON.parse(l);}catch{r[s]=l;}break;default:if(l.startsWith("{")||l.startsWith("["))try{r[s]=JSON.parse(l);break}catch{}r[s]=l;}}return r}function mt(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 ze(e){let t=e;for(;;){let n=z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=M(t);else return n}}function gt(e,t,n=""){let r={};for(let s of Object.keys(t.shape)){let a=n?`${n}.${s}`:s,o=e[s];if(o===null){r[a]="__null__";continue}if(o===void 0)continue;let c=t.shape[s];for(;;){let i=z(c);if(i==="ZodOptional"||i==="ZodNullable"||i==="ZodDefault")c=M(c);else break}let l=z(c);if(l==="ZodObject"&&typeof o=="object"&&o!==null&&!Array.isArray(o)){let i=gt(o,c,a);Object.assign(r,i);}else if(l==="ZodDate"){let i=mt(o);i!==null&&(r[a]=i);}else if(typeof o=="object"&&o!==null&&!Array.isArray(o)&&("_seconds"in o||typeof o.toDate=="function")){let i=mt(o);r[a]=i??JSON.stringify(o,null,2);}else typeof o=="object"?r[a]=JSON.stringify(o,null,2):r[a]=String(o);}return r}function Ze(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?Ze(n.nested,t):void 0}))}function Vt(e,t){let n=new Set(["==","!=","<","<=",">",">=","array-contains","array-contains-any"]),r=[];for(let[s,a]of Object.entries(e)){if(!s.startsWith("fv_"))continue;let o=s.slice(3);if(!t.has(o))continue;let c=(a??"").trim();if(!c)continue;let l=e[`fo_${o}`]??"==",i=n.has(l)?l:"==";r.push({field:o,op:i,value:c});}return r}function Jt(e){let t=n=>n==="true"?true:n==="false"?false:n!==""&&!isNaN(Number(n))?Number(n):n;return e.map(n=>{if(n.op==="array-contains-any"){let r=n.value.split(",").map(s=>t(s.trim())).filter(s=>s!=="");return [n.field,n.op,r]}return [n.field,n.op,t(n.value)]})}function ht(e,t,n=""){let r=[];for(let s of e){let a=n?`${n}.${s}`:s,o=t.shape[s];if(!o){r.push({name:a,zodType:"ZodString"});continue}let c=ze(o);if(c==="ZodObject"){let l=o;for(;;){let d=z(l);if(d==="ZodOptional"||d==="ZodNullable"||d==="ZodDefault")l=M(l);else break}let i=ce(l);r.push(...ht(Object.keys(i),l,a));}else r.push({name:a,zodType:c});}return r}function Xt(e,t){let n=t.split("."),r=e;for(let s of n){for(;;){let o=z(r);if(o==="ZodOptional"||o==="ZodNullable"||o==="ZodDefault")r=M(r);else break}let a=ce(r);if(!(s in a))return null;r=a[s];}return r}function ae(e,t){if(!t||t.length===0)return e;let n=[],r=new Map;for(let a of t){let o=a.indexOf(".");if(o===-1)n.push(a);else {let c=a.slice(0,o),l=a.slice(o+1);r.has(c)||r.set(c,[]),r.get(c).push(l);}}let s={};for(let a of n)a in e.shape&&(s[a]=e.shape[a]);for(let[a,o]of r){if(!(a in e.shape))continue;let c=e.shape[a];for(;;){let l=z(c);if(l==="ZodOptional"||l==="ZodNullable"||l==="ZodDefault")c=M(c);else break}if(z(c)!=="ZodObject"){s[a]=e.shape[a];continue}s[a]=ae(c,o);}return zod.z.object(s)}function se(e,t){let n=t==="/"?"":t.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let a=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",o=process.env.FUNCTION_REGION??"us-central1",c=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${a}/${o}/${c}${n}`}let r=process.env.K_SERVICE,s=e.hostname??e.headers?.host??"";return r&&s.includes("cloudfunctions.net")?`/${r.toLowerCase()}${n}`:n}function bt(e,t){return {handleDashboard:(i,d)=>{let g=se(i,t),u=Object.values(e).map(p=>({name:p.name,path:p.path}));$(d,De(u,g));},handleList:async(i,d)=>{let g=i.params.repoName;if(!g){$(d,"Bad request",400);return}let u=e[g];if(!u){$(d,"Repository not found",404);return}let p=u.pageSize??25,f=i.query??{},b=f.cursor,m=f.dir==="prev"?"prev":"next",y=f.ob??"",h=f.od==="desc"?"desc":"asc",v=y?{field:y,dir:h}:void 0,R=parseInt(f.ps??""),x=Number.isFinite(R)&&R>0?Math.min(R,200):p,w=u.listColumns??Object.keys(u.schema.shape),T=u.documentKey??"docId",S=[T,...w.filter(Z=>Z!==T)],A=u.filterableFields?(()=>{let Z=[];for(let U of u.filterableFields)(U.includes(".")||w.includes(U))&&Z.push(U);return Z})():w,k=(()=>{let Z=[];for(let U of A)if(U.includes(".")){let Be=Xt(u.schema,U);Z.push({name:U,zodType:Be?ze(Be):"ZodString"});}else Z.push(...ht([U],u.schema));return Z})(),N=new Set(k.map(Z=>Z.name)),F=Vt(f,N),oe=Jt(F),D;if(b)try{let Z=u.repo.ref;typeof Z.doc=="function"&&(D=await Z.doc(b).get());}catch{}let q=await u.repo.query.paginate({pageSize:x,cursor:D,direction:m,...oe.length>0?{where:oe}:{},...v?{orderBy:[{field:v.field,direction:v.dir}]}:{}}),kt=q.nextCursor?.id??"",Pt=q.prevCursor?.id??"",Dt=se(i,t);$(d,Ee(u.name,q.data,S,Dt,{hasPrev:q.hasPrevPage,hasNext:q.hasNextPage,prevCursor:Pt,nextCursor:kt},void 0,k,F,u.allowDelete??false,u.relationalMeta,v,x));},handleCreateForm:(i,d)=>{let g=i.params.repoName;if(!g){$(d,"Bad request",400);return}let u=e[g];if(!u){$(d,"Repository not found",404);return}let p=se(i,t),f=ae(u.schema,u.createFields),b=Q(f),m=`${p}/${u.name}/create`,y=V(b,m,"POST","Create document");$(d,X(u.name,y,"create",null,p));},handleCreateSubmit:async(i,d)=>{let g=i.params.repoName;if(!g){$(d,"Bad request",400);return}let u=e[g];if(!u){$(d,"Repository not found",404);return}let p=se(i,t),f=i.body??{},b=_e(f,u.schema),m=ae(u.schema,u.createFields),y=m.safeParse(b);if(!y.success){let h=Q(m),v=`${p}/${u.name}/create`,R=V(h,v,"POST","Create document"),x=y.error.issues.map(w=>`${w.path.join(".")}: ${w.message}`).join(", ");$(d,X(u.name,R,"create",null,p,{type:"error",message:`Validation error: ${x}`}),422);return}try{if(u.isGroup&&u.parentKeys&&u.parentKeys.length>0){let h={...y.data};u.createdKey&&(h[u.createdKey]=new Date);let v=u.parentKeys.filter(T=>!h[T]);if(v.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${v.join(", ")}`);let R=u.parentKeys.map(T=>h[T]),x=u.documentKey??"docId",w=h[x]||Gt();await u.repo.set(...R,w,h);}else await u.repo.create(y.data);Ie(d,`${p}/${u.name}?flash=created`);}catch(h){let v=ae(u.schema,u.createFields),R=Q(v),x=`${p}/${u.name}/create`,w=V(R,x,"POST","Create document");$(d,X(u.name,w,"create",null,p,{type:"error",message:`Save error: ${h.message}`}),500);}},handleEditForm:async(i,d)=>{let g=i.params.repoName,u=i.params.id;if(!g||!u){$(d,"Bad request",400);return}let p=e[g];if(!p){$(d,"Repository not found",404);return}let f=null;try{f=await Fe(p,u);}catch(x){$(d,`Error fetching document: ${x.message}`,500);return}if(!f){$(d,"Document not found",404);return}let b=gt(f,p.schema),m=ae(p.schema,p.mutableFields),y=Ze(Q(m),b),h=se(i,t),v=`${h}/${p.name}/${encodeURIComponent(u)}/edit`,R=V(y,v,"POST","Save changes");$(d,X(p.name,R,"edit",u,h));},handleEditSubmit:async(i,d)=>{let g=i.params.repoName,u=i.params.id;if(!g||!u){$(d,"Bad request",400);return}let p=e[g];if(!p){$(d,"Repository not found",404);return}let f=se(i,t),b=i.body??{},m=_e(b,p.schema),y=ae(p.schema,p.mutableFields),v=y.partial().safeParse(m);if(!v.success){let R=Object.fromEntries(Object.entries(b).map(([A,k])=>[A,Array.isArray(k)?k.join(","):k??""])),x=Ze(Q(y),R),w=`${f}/${p.name}/${encodeURIComponent(u)}/edit`,T=V(x,w,"POST","Save changes"),S=v.error.issues.map(A=>`${A.path.join(".")}: ${A.message}`).join(", ");$(d,X(p.name,T,"edit",u,f,{type:"error",message:`Validation error: ${S}`}),422);return}try{let R=await Fe(p,u),x=(R&&yt(R,p.pathKey))??[u];await p.repo.update(...x,v.data),Ie(d,`${f}/${p.name}?flash=updated`);}catch(R){let x=ae(p.schema,p.mutableFields),w=Q(x),T=`${f}/${p.name}/${encodeURIComponent(u)}/edit`,S=V(w,T,"POST","Save changes");$(d,X(p.name,S,"edit",u,f,{type:"error",message:`Save error: ${R.message}`}),500);}},handleDelete:async(i,d)=>{let g=i.params.repoName,u=i.params.id;if(!g||!u){$(d,"Bad request",400);return}let p=e[g];if(!p){$(d,"Repository not found",404);return}if(!p.allowDelete){$(d,"Delete is not allowed for this repository",403);return}let f=se(i,t);try{let b=await Fe(p,u),m=(b&&yt(b,p.pathKey))??[u];await p.repo.delete(...m),Ie(d,`${f}/${p.name}?flash=deleted`);}catch(b){$(d,`Delete error: ${b.message}`,500);}}}}function Yt(e){let t=[],n=e.replace(/[.*+?^${}()|[\]\\]/g,r=>r===":"?r:`\\${r}`).replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(r,s)=>(t.push(s),"([^/]+)"));return {pattern:new RegExp(`^${n}$`),paramNames:t}}function en(e){let t=e.path??e.url??"/",n=t.indexOf("?");return n===-1?t:t.slice(0,n)}var H=class{constructor(){this.routes=[];this.middlewares=[];this.notFoundHandler=(t,n)=>{n.status(404).send("Not Found");};this.errorHandler=(t,n,r)=>{console.error("[MiniRouter]",t),r.status(500).send("Internal Server Error");};}use(t){return this.middlewares.push(t),this}get(t,n){return this.addRoute("GET",t,n)}post(t,n){return this.addRoute("POST",t,n)}put(t,n){return this.addRoute("PUT",t,n)}patch(t,n){return this.addRoute("PATCH",t,n)}delete(t,n){return this.addRoute("DELETE",t,n)}onNotFound(t){return this.notFoundHandler=t,this}onError(t){return this.errorHandler=t,this}addRoute(t,n,r){let{pattern:s,paramNames:a}=Yt(n);return this.routes.push({method:t.toUpperCase(),pattern:s,paramNames:a,handler:r}),this}async handle(t,n){let r=(t.method??"GET").toUpperCase(),s=en(t),a=null,o={};for(let i of this.routes){if(i.method!==r)continue;let d=s.match(i.pattern);if(d){a=i,o={},i.paramNames.forEach((g,u)=>{o[g]=decodeURIComponent(d[u+1]??"");});break}}let c=Object.assign(t,{params:o}),l=a?a.handler:this.notFoundHandler;try{await this.runMiddlewareChain(c,n,l);}catch(i){this.errorHandler(i,t,n);}}async runMiddlewareChain(t,n,r){let s=0,a=async()=>{if(s<this.middlewares.length){let o=this.middlewares[s++];await o(t,n,a);}else await r(t,n);};await a();}};async function tn(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function nn(e){let t={};if(!e)return t;for(let n of e.split("&")){let r=n.indexOf("=");if(r===-1)continue;let s=decodeURIComponent(n.slice(0,r).replace(/\+/g," ")),a=decodeURIComponent(n.slice(r+1).replace(/\+/g," ")),o=t[s];o===void 0?t[s]=a:Array.isArray(o)?o.push(a):t[s]=[o,a];}return t}function Rt(e){let{basePath:t="/",repos:n,parseBody:r=true,auth:s,middleware:a=[],httpsOptions:o}=e,c=t==="/"?"":t.replace(/\/$/,""),l={};for(let[u,p]of Object.entries(n)){let f=p.schema??p.repo.schema??null;if(!f)throw new Error(`[createAdminServer] Repository "${u}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let b,m,y;if(p.fieldsConfig){let R=p.fieldsConfig;b=[],m=[],y=[];for(let[x,w]of Object.entries(R))for(let T of w)T==="filterable"?b.push(x):T==="mutable"?m.push(x):T==="create"&&y.push(x);b.length===0&&(b=void 0),m.length===0&&(m=void 0),y.length===0&&(y=void 0);}let h=(()=>{let R=p.repo._parentKeys;return R&&R.length>0?R:void 0})();if(h&&y)for(let R of h)y.includes(R)||y.push(R);let v={name:u,path:p.path,repo:p.repo,schema:f,documentKey:p.documentKey??"docId",pathKey:p.repo._pathKey??void 0,isGroup:!!p.repo._isGroup,parentKeys:h,createdKey:p.repo._createdKey??void 0,listColumns:p.listColumns,pageSize:p.pageSize,filterableFields:b,mutableFields:m,createFields:y,allowDelete:p.allowDelete??false,relationalMeta:(()=>{if(!p.relationalFields||p.relationalFields.length===0)return;let R=p.repo.relationalKeys??{},x=[];for(let w of p.relationalFields){let T=R[w.key];T&&x.push({key:w.key,column:w.column,targetRepo:String(T.repo),targetKey:String(T.key),type:T.type});}return x.length>0?x:void 0})()};l[u]=v;}let i=bt(l,c),d=new H;if(r&&d.use(async(u,p,f)=>{let b=u,m=String(b.headers?.["content-type"]??"");if(m.includes("application/x-www-form-urlencoded")){let y=await tn(b);u.body=nn(y);}else if(m.includes("application/json")&&typeof b.body=="string")try{u.body=JSON.parse(b.body);}catch{}await f();}),s)if(typeof s=="function")d.use(s);else {let u=s.realm??"Admin",p="Basic "+Buffer.from(`${s.username}:${s.password}`).toString("base64");d.use((f,b,m)=>{if((f.headers?.authorization??"")!==p){b.status(401).set("WWW-Authenticate",`Basic realm="${u}"`).set("Content-Type","text/plain").send("Unauthorized");return}m();});}for(let u of a)d.use(u);d.get(`${c}/`,i.handleDashboard),d.get(`${c}`,i.handleDashboard),d.get(`${c}/:repoName`,i.handleList),d.get(`${c}/:repoName/create`,i.handleCreateForm),d.post(`${c}/:repoName/create`,i.handleCreateSubmit),d.get(`${c}/:repoName/:id/edit`,i.handleEditForm),d.post(`${c}/:repoName/:id/edit`,i.handleEditSubmit),d.post(`${c}/:repoName/:id/delete`,i.handleDelete);let g=async(u,p)=>{await d.handle(u,p);};return o&&(g.httpsOptions=o),g}function St(e,t,n=200){e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(t));}function ie(e,t,n,r=200){St(e,{success:true,data:t,meta:n},r);}function P(e,t,n=400){St(e,{success:false,error:t},n);}var vt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function rn(){let e="";for(let t=0;t<20;t++)e+=vt.charAt(Math.floor(Math.random()*vt.length));return e}function sn(e,t,n=[]){let r=e.shape,s={},a=t&&t.length>0?t:Object.keys(r);for(let o of a){if(n.includes(o))continue;let c=o.split(".")[0];c&&r[c]&&(s[c]=r[c]);}return zod.z.object(s)}function xt(e,t,n,r=false,s=[]){try{let a=sn(e,n,s);return {success:!0,data:(r?a.partial():a).parse(t)}}catch(a){return a instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${a.issues.map(c=>`${c.path.join(".")}: ${c.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function an(e,t){let n=[],r=t?new Set(t):null,s={eq:"==",ne:"!=",lt:"<",lte:"<=",gt:">",gte:">=",in:"in",nin:"not-in",contains:"array-contains",containsAny:"array-contains-any"};for(let[a,o]of Object.entries(e)){if(o===void 0||["cursor","limit","pageSize","orderBy","orderDir","select"].includes(a))continue;let c=Array.isArray(o)?o[0]:o;if(c===void 0||c==="")continue;let l=a.match(/^(\w+)__(\w+)$/),i,d="==";if(l&&l[1]&&l[2]){i=l[1];let u=l[2];if(s[u])d=s[u];else continue}else if(!l)i=a;else continue;if(r&&!r.has(i))continue;let g=c;d==="in"||d==="not-in"||d==="array-contains-any"?g=c.split(",").map(u=>wt(u.trim())):g=wt(c),n.push({field:i,op:d,value:g});}return n}function wt(e){if(e==="true")return true;if(e==="false")return false;if(e==="null")return null;let t=Number(e);return !isNaN(t)&&e!==""?t:e}function he(e){return e?{docId:e.id}:null}async function Tt(e,t){if(!t||typeof t!="object")return;let n=t.docId;if(typeof n=="string")try{let r=e.repo.ref;if(typeof r.doc!="function")return;let s=await r.doc(n).get();return s.exists?s:void 0}catch{return}}function At(e,t,n){function r(p,f){return !p||!e[p]?(P(f,`Repository "${p}" not found`,404),null):e[p]}function s(p,f){if(!f)return;let b=p[f];if(typeof b!="string"||!b)return;let m=b.split("/").filter(Boolean),y=[];for(let h=1;h<m.length;h+=2)y.push(m[h]);return y.length>0?y:void 0}async function a(p,f){let b=`by${p.documentKey.charAt(0).toUpperCase()}${p.documentKey.slice(1)}`,m=p.repo.get[b];if(typeof m=="function")try{let h=await m(f);if(h)return h}catch{}return (await p.repo.query.by({where:[[p.documentKey,"==",f]],limit:1}))[0]??null}async function o(p,f){let b=p.params||{},m=r(b.repoName,f);if(m)try{let y=p.query??{},h=Math.min(Number(y.pageSize)||m.pageSize,100),v=y.cursor,R=y.direction?.toLowerCase()==="prev"?"prev":"next",x=y.orderBy,w=y.orderDir?.toLowerCase()==="desc"?"desc":"asc",T=y.select,S=T?T.split(",").map(D=>D.trim()):void 0,A;m.allowedIncludes&&y.includes&&(A=(typeof y.includes=="string"?y.includes.split(",").map(q=>q.trim()):Array.isArray(y.includes)?y.includes:[]).filter(q=>typeof q=="string"&&m.allowedIncludes.includes(q)),A?.length===0&&(A=void 0));let k=an(y,m.filterableFields),N={pageSize:h,direction:R};if(v)try{let D=typeof v=="string"?JSON.parse(v):v;N.cursor=await Tt(m,D);}catch{}x&&(N.orderBy=[{field:x,direction:w}]),k.length>0&&(N.where=k.map(D=>[D.field,D.op,D.value])),S&&(N.select=S),A&&(N.include=A);let F=await m.repo.query.paginate(N),oe={items:F.data,hasNextPage:F.hasNextPage,hasPrevPage:F.hasPrevPage,nextCursor:he(F.nextCursor),prevCursor:he(F.prevCursor)};ie(f,oe,{pageSize:h,hasMore:F.hasNextPage});}catch(y){let h=n&&y instanceof Error?y.message:"Failed to fetch documents";P(f,h,500);}}async function c(p,f){let b=p.params||{},m=r(b.repoName,f);if(m)try{let y=p.body??{},h=Math.min(y.pageSize||m.pageSize,100),v=y.direction==="prev"?"prev":"next",R={pageSize:h,direction:v};if(y.cursor)try{let T=typeof y.cursor=="string"?JSON.parse(y.cursor):y.cursor;R.cursor=await Tt(m,T);}catch{}if(m.allowedIncludes&&y.includes&&y.includes.length>0){let T=y.includes.filter(S=>typeof S=="string"?m.allowedIncludes.includes(S):typeof S=="object"&&S!==null&&"relation"in S&&typeof S.relation=="string"?m.allowedIncludes.includes(S.relation):!1);T.length>0&&(R.include=T);}if(y.where&&y.where.length>0){if(m.filterableFields){let T=new Set(m.filterableFields),S=y.where.filter(A=>!T.has(A[0]));if(S.length>0){P(f,`Fields not filterable: ${S.map(A=>A[0]).join(", ")}`,400);return}}R.where=y.where;}if(y.orWhere&&y.orWhere.length>0){if(m.filterableFields){let T=new Set(m.filterableFields),S=y.orWhere.filter(A=>!T.has(A[0]));if(S.length>0){P(f,`Fields not filterable: ${S.map(A=>A[0]).join(", ")}`,400);return}}R.orWhere=y.orWhere;}if(y.orWhereGroups&&y.orWhereGroups.length>0){if(m.filterableFields){let T=new Set(m.filterableFields);for(let S of y.orWhereGroups){let A=S.filter(k=>!T.has(k[0]));if(A.length>0){P(f,`Fields not filterable: ${A.map(k=>k[0]).join(", ")}`,400);return}}}R.orWhereGroups=y.orWhereGroups;}y.orderBy&&y.orderBy.length>0&&(R.orderBy=y.orderBy),y.select&&y.select.length>0&&(R.select=y.select);let x=await m.repo.query.paginate(R),w={items:x.data,hasNextPage:x.hasNextPage,hasPrevPage:x.hasPrevPage,nextCursor:he(x.nextCursor),prevCursor:he(x.prevCursor)};ie(f,w,{pageSize:h,hasMore:x.hasNextPage});}catch(y){let h=n&&y instanceof Error?y.message:"Failed to query documents";P(f,h,500);}}async function l(p,f){let b=p.params||{},m=r(b.repoName,f);if(!m)return;let y=b.id;if(!y){P(f,"Document ID required",400);return}try{let h=await a(m,y);if(!h){P(f,"Document not found",404);return}ie(f,h);}catch(h){let v=n&&h instanceof Error?h.message:"Failed to fetch document";P(f,v,500);}}async function i(p,f){let b=p.params||{},m=r(b.repoName,f);if(m)try{let y=p.body??{},h=xt(m.schema,y,m.createFields,!1,m.systemKeys);if(!h.success){P(f,h.error,400);return}if(m.validate){let R=await m.validate(h.data,"create");if(R){P(f,R,400);return}}let v;if(m.isGroup&&m.parentKeys&&m.parentKeys.length>0){let R={...h.data};m.createdKey&&(R[m.createdKey]=new Date);let x=m.parentKeys.filter(S=>!R[S]);if(x.length>0){P(f,`Missing parent key(s) for subcollection create: ${x.join(", ")}`,400);return}let w=m.parentKeys.map(S=>R[S]),T=R[m.documentKey]||rn();v=await m.repo.set(...w,T,R);}else v=await m.repo.create(h.data);ie(f,v,void 0,201);}catch(y){let h=n&&y instanceof Error?y.message:"Failed to create document";P(f,h,500);}}async function d(p,f,b){let m=p.params||{},y=r(m.repoName,f);if(!y)return;let h=m.id;if(!h){P(f,"Document ID required",400);return}try{let v=p.body??{},R=xt(y.schema,v,y.mutableFields,b,y.systemKeys);if(!R.success){P(f,R.error,400);return}if(y.validate){let S=await y.validate(R.data,"update");if(S){P(f,S,400);return}}let x=await a(y,h),w=(x&&s(x,y.pathKey))??[h],T=await y.repo.update(...w,R.data);ie(f,T);}catch(v){let R=n&&v instanceof Error?v.message:"Failed to update document";P(f,R,500);}}async function g(p,f){let b=p.params||{},m=r(b.repoName,f);if(!m)return;if(!m.allowDelete){P(f,"Delete not allowed for this repository",403);return}let y=b.id;if(!y){P(f,"Document ID required",400);return}try{let h=await a(m,y),v=(h&&s(h,m.pathKey))??[y];await m.repo.delete(...v),ie(f,{deleted:!0});}catch(h){let v=n&&h instanceof Error?h.message:"Failed to delete document";P(f,v,500);}}function u(p,f){f.status(204).set("Access-Control-Allow-Methods","GET, POST, PUT, PATCH, DELETE, OPTIONS").set("Access-Control-Allow-Headers","Content-Type, Authorization").set("Access-Control-Max-Age","86400").send("");}return {handleList:o,handleQuery:c,handleGet:l,handleCreate:i,handleUpdate:d,handleDelete:g,handleOptions:u}}function je(e){try{return zod.z.toJSONSchema(e,{target:"openapi-3.1"})}catch{return {type:"object"}}}function B(e){return {$ref:`#/components/schemas/${e}`}}function _(e){return {description:e,content:{"application/json":{schema:B("ErrorResponse")}}}}function fe(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function Ot(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 on(e){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"},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"}]}function ln(e){let t=e.filterableFields??Object.keys(e.schema.shape),n=["eq","ne","lt","lte","gt","gte","in","nin","contains"],r=[];for(let s of t){r.push({name:s,in:"query",schema:{type:"string"},description:`Filter by ${s} (equality)`});for(let a of n)r.push({name:`${s}__${a}`,in:"query",schema:{type:"string"},description:`Filter ${s} with operator ${a}`});}return r}function cn(){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 dn(e,t,n,r,s){let a={},o=e.name,c=`${t}/${e.name}`,l=`${c}/{${e.documentKey}}`,i={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};a[c]={get:{operationId:`list${Y(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[o],parameters:[...on(e),...ln(e)],responses:{200:Ot(B(n)),500:_("Internal server error")}},post:{operationId:`create${Y(e.name)}`,summary:`Create a ${W(e.name)}`,tags:[o],requestBody:{required:true,content:{"application/json":{schema:B(r??n)}}},responses:{201:fe("Document created",B(n)),400:_("Validation error"),500:_("Internal server error")}}},a[`${c}/query`]={post:{operationId:`query${Y(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[o],requestBody:{required:true,content:{"application/json":{schema:B("QueryRequestBody")}}},responses:{200:Ot(B(n)),400:_("Invalid query"),500:_("Internal server error")}}};let d={};return d.get={operationId:`get${Y(W(e.name))}`,summary:`Get a single ${W(e.name)}`,tags:[o],parameters:[i],responses:{200:fe("Document found",B(n)),404:_("Document not found"),500:_("Internal server error")}},d.put={operationId:`update${Y(W(e.name))}`,summary:`Update a ${W(e.name)} (full replace)`,tags:[o],parameters:[i],requestBody:{required:true,content:{"application/json":{schema:B(s??n)}}},responses:{200:fe("Document updated",B(n)),400:_("Validation error"),404:_("Document not found"),500:_("Internal server error")}},d.patch={operationId:`patch${Y(W(e.name))}`,summary:`Partially update a ${W(e.name)}`,tags:[o],parameters:[i],requestBody:{required:true,content:{"application/json":{schema:{allOf:[B(s??n)],description:"All fields are optional for partial updates"}}}},responses:{200:fe("Document patched",B(n)),400:_("Validation error"),404:_("Document not found"),500:_("Internal server error")}},e.allowDelete&&(d.delete={operationId:`delete${Y(W(e.name))}`,summary:`Delete a ${W(e.name)}`,tags:[o],parameters:[i],responses:{200:fe("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:_("Document not found"),500:_("Internal server error")}}),a[l]=d,a}function Me(e,t,n={}){let{title:r="CRUD API",version:s="1.0.0",description:a,servers:o,auth:c=false}=n,l=t==="/"?"":t.replace(/\/$/,""),i={},d={},g=[];i.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},i.QueryRequestBody=cn();for(let[b,m]of Object.entries(e)){let y=Y(W(b)),h=`${y}Create`,v=`${y}Update`;i[y]=je(m.schema);let R=k=>{let N=k&&k.length>0?k:Object.keys(m.schema.shape),F={};for(let oe of N){let D=oe.split(".")[0];D&&m.schema.shape[D]&&!m.systemKeys.includes(D)&&(F[D]=m.schema.shape[D]);}return F},x=null,w=R(m.createFields);Object.keys(w).length>0&&(i[h]=je(zod.z.object(w)),x=h);let T=null,S=R(m.mutableFields);Object.keys(S).length>0&&(i[v]=je(zod.z.object(S)),T=v);let A=dn(m,l,y,x,T);Object.assign(d,A),g.push({name:b,description:`Operations on ${b} (collection: ${m.path})`});}let u={},p;return c==="basic"?(u.basicAuth={type:"http",scheme:"basic"},p=[{basicAuth:[]}]):c==="bearer"&&(u.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},p=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:s,...a?{description:a}:{}},...o&&o.length>0?{servers:o}:{},paths:d,components:{schemas:i,...Object.keys(u).length>0?{securitySchemes:u}:{}},...p?{security:p}:{},tags:g}}function Y(e){return e.charAt(0).toUpperCase()+e.slice(1)}function W(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}function un(e,t){return `<!DOCTYPE html>
|
|
556
556
|
<html lang="en">
|
|
557
557
|
<head>
|
|
558
558
|
<meta charset="utf-8" />
|
|
@@ -563,5 +563,5 @@ function initColumnReorder(table) {
|
|
|
563
563
|
<script id="api-reference" data-url="${t}"></script>
|
|
564
564
|
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
|
|
565
565
|
</body>
|
|
566
|
-
</html>`}function pn(e){let t
|
|
566
|
+
</html>`}function pn(e,t){let n=t==="/"?"":t.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let a=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",o=process.env.FUNCTION_REGION??"us-central1",c=process.env.FUNCTION_TARGET??"";return `/${a}/${o}/${c}${n}`}let r=process.env.K_SERVICE,s=e?.hostname??e?.headers?.host??"";return r&&s.includes("cloudfunctions.net")?`/${r.toLowerCase()}${n}`:n}async function fn(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function $t(e){let{basePath:t="/",repos:n,parseBody:r=true,auth:s,middleware:a=[],verbose:o=false,httpsOptions:c}=e,l=t==="/"?"":t.replace(/\/$/,""),i={};for(let[y,h]of Object.entries(n)){let v=h.schema??h.repo.schema??null;if(!v)throw new Error(`[createCrudServer] Repository "${y}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let R,x,w;if(h.fieldsConfig){let A=h.fieldsConfig;R=[],x=[],w=[];for(let[k,N]of Object.entries(A))for(let F of N)F==="filterable"?R.push(k):F==="mutable"?x.push(k):F==="create"&&w.push(k);R.length===0&&(R=void 0),x.length===0&&(x=void 0),w.length===0&&(w=void 0);}let T=(()=>{let A=h.repo._parentKeys;return A&&A.length>0?A:void 0})();if(T&&w)for(let A of T)w.includes(A)||w.push(A);let S={name:y,path:h.path,repo:h.repo,schema:v,systemKeys:h.repo._systemKeys??[h.documentKey??"docId"],documentKey:h.documentKey??"docId",pathKey:h.repo._pathKey??void 0,isGroup:!!h.repo._isGroup,parentKeys:T,createdKey:h.repo._createdKey??void 0,pageSize:h.pageSize??25,filterableFields:R,mutableFields:x,createFields:w,allowDelete:h.allowDelete??false,allowedIncludes:h.allowedIncludes,validate:h.validate};i[y]=S;}let d=At(i,l,o),g=e.openapi,u=g&&typeof g=="object"?g:{},p=null;function f(){if(!p){let y=s&&typeof s!="function"?"basic":s?"bearer":false;p=Me(i,l,{...u,auth:u.auth??y});}return p}let b=new H;if(b.use((y,h,v)=>{h.set("Access-Control-Allow-Origin","*"),h.set("Access-Control-Allow-Credentials","true"),v();}),r&&b.use(async(y,h,v)=>{let R=y;if(String(R.headers?.["content-type"]??"").includes("application/json")){if(typeof R.body=="string")try{y.body=JSON.parse(R.body);}catch{}else if(Buffer.isBuffer(y.rawBody))try{let w=await fn(R);y.body=JSON.parse(w);}catch{}}await v();}),s)if(typeof s=="function")b.use(s);else {let y=s.realm??"API",h="Basic "+Buffer.from(`${s.username}:${s.password}`).toString("base64");b.use((v,R,x)=>{if((v.headers?.authorization??"")!==h){R.status(401).set("WWW-Authenticate",`Basic realm="${y}"`).set("Content-Type","application/json").send(JSON.stringify({success:false,error:"Unauthorized"}));return}x();});}for(let y of a)b.use(y);if(g!==false){let y=`${l}/__spec.json`,h=`${l}/__docs`;b.get(y,(v,R)=>{let x=f();R.status(200).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(x,null,2));}),b.get(h,(v,R)=>{let x=pn(v,l)+"/__spec.json",w=un(u.title??"CRUD API",x);R.status(200).set("Content-Type","text/html; charset=utf-8").send(w);});}b.use((y,h,v)=>{if(y.method==="OPTIONS"){d.handleOptions(y,h);return}v();}),b.get(`${l}/:repoName`,d.handleList),b.post(`${l}/:repoName/query`,d.handleQuery),b.get(`${l}/:repoName/:id`,d.handleGet),b.post(`${l}/:repoName`,d.handleCreate),b.put(`${l}/:repoName/:id`,(y,h)=>d.handleUpdate(y,h,false)),b.patch(`${l}/:repoName/:id`,(y,h)=>d.handleUpdate(y,h,true)),b.delete(`${l}/:repoName/:id`,d.handleDelete);let m=async(y,h)=>{await b.handle(y,h);};return m.spec=f,c&&(m.httpsOptions=c),m}function Xr(e){return t=>({...t,schema:e,type:null,documentRef:null,update:null})}function Yr(e,t){let n={...e};for(let r in t)t[r]&&(n[r]={...e[r],relationalKeys:t[r]});return n}var Ke=class{constructor(t,n){this.repositoryCache=new Map;this.allRepositories={};this.db=t,this.mapping=n,this.initializeRepositories();}initializeRepositories(){for(let t of Object.keys(this.mapping))this.allRepositories[t]=xe(this.db,this.mapping[t],{});for(let t of Object.keys(this.mapping))this.allRepositories[t]=xe(this.db,this.mapping[t],this.allRepositories);}getRepository(t){return this.allRepositories[t]}};function es(e,t){let n=new Ke(e,t),r=Object.keys(t);return new Proxy(n,{get(s,a){return typeof a=="string"&&a in t?s.getRepository(a):s[a]},ownKeys(){return r},getOwnPropertyDescriptor(s,a){if(typeof a=="string"&&a in t)return {configurable:true,enumerable:true,writable:false}}})}exports.MiniRouter=H;exports.RepositoryMapping=Ke;exports.applyPaginationQueryOptions=G;exports.buildAndExecuteQuery=ee;exports.buildRepositoryRelations=Yr;exports.createAdminServer=Rt;exports.createCrudServer=$t;exports.createPaginationIterator=ve;exports.createRepositoryConfig=Xr;exports.createRepositoryMapping=es;exports.executePaginatedQuery=me;//# sourceMappingURL=index.cjs.map
|
|
567
567
|
//# sourceMappingURL=index.cjs.map
|